branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep># p1 # Project 1 + By: *<NAME>* + Production URL: <http://p1.tributeforgrade.me> ## Outside resources *your list of outside resources go here* * [Star Trek Quotes](https://www.needsomefun.net/best-star-trek-quotes-ever/) ## Notes for instructor I submitted [http://tributeforgrade.me/p1/](http://tributeforgrade.me/p1/) on the website. However my application is also accessible via [http://p1.tributeforgrade.me/](http://p1.tributeforgrade.me/) <file_sep><!DOCTYPE html> <html lang="en"> <head> <title>Introducing: <NAME></title> <link rel="stylesheet" href="./css/main.css"> </head> <body> <h1><NAME></h1><img src="./img/VietNguyen.jpg" alt="Viet" class="profilePic"> <h2>About me</h2> <p>Born and raised in Canada. I currently live in Boston. I have experience programming in different languages and I look forward to having a structured way of learning web development. </p> <h2>Random Quote</h2> <?php include("./includes/quotes.php"); ?> </html><file_sep><?php $quoteArray = [ 0 => 'Insufficient facts always invite danger. — Spock', 1 => 'I canna’ change the laws of physics. — Montgomery “Scotty” Scott', 'KHAAANNN! — Captain <NAME>', 2 => 'There is a way out of every box, a solution to every puzzle; it’s just a matter of finding it. — Captain <NAME>', 3 => 'There’s still much to do; still so much to learn. Mr. La Forge – engage! ― <NAME>', 4 => 'Seize the time... Live now! Make now always the most precious time. Now will never come again. ― <NAME>']; ?> <?php echo '<blockquote>' . $quoteArray[rand(0, 4)] . '</blockquote>'; ?>
1f71fb882761f8b57c73ea97a75d8d13ae1c9e87
[ "Markdown", "PHP" ]
3
Markdown
viettnguyen/p1
93afcc253ef5299e15c6a82053a2d841c83b99cb
1e726f3293eb19f7b2881e990832947da1a47096
refs/heads/master
<file_sep>__version__ = '0.0.1' __author__ = '<NAME>' __email__ = '<EMAIL>' <file_sep>from datetime import datetime async def get_emails(db, address): emails = await db.emails.find( {'to': address} ).to_list(50) return emails async def get_email(db, uuid): email = await db.emails.find_one({'uuid': uuid}) return email async def create_mailbox(db, address, token): document = { 'address': address, 'token': token, 'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'emails': [], } mailbox = await db.mailboxes.insert_one(document) return mailbox async def get_mailbox_by_address(db, address): mailbox = await db.mailboxes.find_one({'address': address}) return mailbox async def get_mailbox_by_token(db, token): mailbox = await db.mailboxes.find_one({'token': token}) return mailbox async def delete_mailbox_by_token(db, token): await db.mailboxes.delete_many({'token': token}) <file_sep>from os import path from setuptools import setup from yades_api import __version__, __author__, __email__ root_dir = path.abspath(path.dirname(__file__)) with open(path.join(root_dir, 'README.md'), encoding='utf-8') as f: long_description = f.read() with open('requirements.txt') as f: requirements = f.read().splitlines() setup( name='yades_api', version=__version__, author=__author__, author_email=__email__, packages=['yades_api'], include_package_data=True, url='https://github.com/yades/yades-api/', license='MIT', description='', long_description=long_description, long_description_content_type='text/markdown', classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Topic :: Internet', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords='aiohttp asyncio', install_requires=requirements, entry_points={ 'console_scripts': [ 'yades_api=yades_api.__main__:main', ], }, ) <file_sep>from yades_api import views def setup(app): app.router.add_route('GET', r'/inbox', views.inbox_detail) app.router.add_route('POST', r'/inbox', views.inbox_create) app.router.add_route( 'GET', r'/emails/{uuid:[\d\w\-]{36}}', views.inbox_email_detail ) <file_sep>aiohttp==3.6.2 # https://github.com/aio-libs/aiohttp motor==2.1.0 # https://github.com/mongodb/motor dnspython==1.16.0 # https://github.com/rthalley/dnspython environs==7.4.0 # https://github.com/sloria/environs <file_sep>from aiohttp.web_app import Application from yades_api import routes from yades_api.middlewares import token_middleware def create_app(loop, config, db): app = Application(loop=loop, middlewares=[token_middleware]) app['config'] = config app['db'] = db routes.setup(app) return app <file_sep>import json import uuid from aiohttp import web from yades_api import helpers async def inbox_detail(request): mailbox = await request.app['db'].mailboxes.find_one( {'token': request.token} ) if not mailbox: raise web.HTTPNotFound() context = { 'address': mailbox['address'], 'emails': mailbox['emails'], } return web.json_response(context) async def inbox_create(request): db = request.app['db'] config = request.app['config'] token = request.token if token: await helpers.delete_mailbox_by_token(db, request.token) else: token = str(uuid.uuid4()) data = await request.json() local = data.get('local') domain = data.get('domain') if not (local and domain): raise web.HTTPBadRequest( content_type='application/json', text=json.dumps({ 'code': 'no-required-fields' }) ) if domain not in config['allowed_domains']: raise web.HTTPBadRequest( content_type='application/json', text=json.dumps({ 'code': 'domain-not-allowed' }) ) address = f'{local}@{domain}' mailbox = await helpers.get_mailbox_by_address(db, address) if mailbox: raise web.HTTPBadRequest( content_type='application/json', text=json.dumps({ 'code': 'already-occupied' }) ) await helpers.create_mailbox(db, address, token) raise web.HTTPOk( content_type='application/json', text=json.dumps({ 'token': token, 'address': address, }) ) async def inbox_email_detail(request): email_uuid = request.match_info['uuid'] current_mailbox = await helpers.get_mailbox_by_token( request.app['db'], request.token ) email = await helpers.get_email( request.app['db'], email_uuid ) if not email or email['to'] != current_mailbox['address']: raise web.HTTPNotFound() response = { 'from_name': email['from_name'], 'from_address': email['from_address'], 'subject': email['subject'], 'timestamp': email['timestamp'], } plain = email['payload'].get('text/plain') if plain: response.update({'plain': plain}) html = email['payload'].get('text/html') if html: response.update({'html': html}) return web.json_response(response) <file_sep># yades-api <file_sep>from aiohttp.web import middleware @middleware async def token_middleware(request, handler): token = None auth = request.headers.get('Authorization', '').split() if auth and auth[0] == 'Token': token = auth[1] request.token = token response = await handler(request) return response <file_sep>import asyncio import argparse import logging from aiohttp.web import run_app from environs import Env from motor.motor_asyncio import AsyncIOMotorClient from yades_api.app import create_app async def close_db(app): app['db'].client.close() def main(): env = Env() env.read_env() with env.prefixed('YADES_'): parser = argparse.ArgumentParser(description="") parser.add_argument( '--host', type=str, default=env('API_HOST', 'localhost'), help='Host to listen on' ) parser.add_argument( '--port', type=int, default=env.int('API_PORT', 8080), help='Port to listen on' ) parser.add_argument( '--db-uri', type=str, default=env.str('MONGODB_URI', 'mongodb://localhost:27017'), help='Uri of mongodb server' ) parser.add_argument( '--db-name', type=str, default=env.str('MONGODB_NAME', 'yades'), help='Name of mongodb database' ) parser.add_argument( '--allowed-domains', nargs='+', default=env.list('ALLOWED_DOMAINS', []), help='Domains that can be used for receiving emails' ) args = parser.parse_args() config = { 'mongodb_uri': args.db_uri, 'mongodb_name': args.db_name, 'api_host': args.host, 'api_port': args.port, 'allowed_domains': args.allowed_domains, } logging.basicConfig(level=logging.DEBUG) if not config['allowed_domains']: raise Exception('No allowed domains specified') loop = asyncio.get_event_loop() db = AsyncIOMotorClient( config['mongodb_uri'], io_loop=loop )[config['mongodb_name']] app = create_app(loop, config, db) app.on_cleanup.append(close_db) run_app(app, host=config['api_host'], port=config['api_port']) if __name__ == '__main__': main()
1b09b1217e63ed8c68e0884e69d675cdbbebfc87
[ "Markdown", "Python", "Text" ]
10
Python
ikhomutov/yades-api
f6adc867cd233465446140e9b8eda49eeb599b28
560e99af7d599c352bbe9d1825b7060ebc9efaf2
refs/heads/master
<repo_name>dek-haji/Kennel-5<file_sep>/src/component/location/LocationList.js import React, { Component } from 'react'; import local from "./local.png" import { Link } from 'react-router-dom' import "./Location.css" class LocationList extends Component { render() { return ( <> <div className="locationButton"> <button type="button" className="btn btn-info" onClick={() => { this.props.history.push("/new")} }> Register New Locations </button> </div> <section className="locations"> <h1>Locations</h1> { this.props.locations.map(location => <div key={location.id}> <p>{location.name}</p> <img src={local} alt = "" className="icon--location" /> <p>{location.address}</p> <button onClick={() => { this.props.deleteLocation(location.id) }}>Delete</button> <Link className="nav-link" to={`/locations/${location.id}`}>Details</Link> </div> ) } </section> </> ); } } export default LocationList; <file_sep>/src/component/employee/EmployeeManager.js const remoteURL = "http://localhost:5002" export default Object.create(null, { get: { value: function (id) { /* Since the purpose of this module is to be used by all of the more specialized one, then the string of `animals` should not be hard coded here. */ return fetch(`${remoteURL}/employees/${id}`).then(e => e.json()) } }, all: { value: function () { return fetch(`${remoteURL}/employees`).then(e => e.json()) } }, deleteEmployees: { value: function (id) { return fetch(`${remoteURL}/employees/${id}`, { method: "DELETE", headers: { 'Content-Type': 'application/json', }, }).then(e => e.json()) } }, post: { value: function (newEmployee) { return fetch(`${remoteURL}/employees`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(newEmployee) }).then(data => data.json()) } }, put: { value: function (editEmployee) { return fetch(`${remoteURL}/employees/${editEmployee.id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(editEmployee) }).then(data => data.json()); } } })<file_sep>/src/component/employee/EmployeeDetails.js import React, { Component } from 'react'; import picpic from "./picpic.svg" class EmployeeDetails extends Component { state = { saveDisabled: false //initail state of the button before it clicks } render() { return ( <section className="employee"> <div key={this.props.employee.id} className="card" > <div className="card-body"> <h4 className="card-title"> <img src={ picpic } alt = "" className="icon--employee" /> { this.props.employee.name } </h4> <button onClick={ () => { this.setState( { saveDisabled: true }, //clicking the button updates the button state from false to true, () => this.props.deleteEmployees(this.props.employee.id) ) } } disabled={ this.state.saveDisabled } className="card-link">Delete</button> </div> </div> </section> ); } } export default EmployeeDetails; <file_sep>/src/component/ApplicationViews.js import { Route, Redirect } from 'react-router-dom' import React, { Component } from "react" import { withRouter } from 'react-router' import AnimalList from "./animal/AnimalList" import LocationList from './location/LocationList' import EmployeeList from './employee/EmployeeList' import StudentList from './student/StudentList'; import AnimalManager from "./animal/AnimalManager" import EmployeeManager from './employee/EmployeeManager'; import LocationManager from "./location/LocationManager" import StudentManager from './student/StudentManager'; import StudentForm from "./student/StudentForm" import AnimalDetail from "./animal/AnimalDetails" import AnimalForm from "./animal/AnimalForm" import EmployeeForm from './employee/EmployeeForm'; import EmployeeDetails from "./employee/EmployeeDetails" import LocationForm from './location/LocationForm'; import AnimalEditForm from "./animal/AnimalEditForm" import Login from './authentication/Login' import LocationDetails from "./location/LocationDetails" import EmployeeEditForm from './employee/EmployeeEditForm'; class ApplicationViews extends Component { // Check if credentials are in local storage isAuthenticated = () => sessionStorage.getItem("credentials") !== null state = { locations: [], animals: [], employees: [], students: [] } deleteAnimal = (id) => { const newState = {}; AnimalManager.deleteAnimal(id) .then(AnimalManager.all) .then(animals => { console.log("animals", animals); newState.animals = animals }) .then(() => this.setState(newState)) } deleteEmployees = (id) => { const newState = {}; EmployeeManager.deleteEmployees(id) .then(EmployeeManager.all) .then(employees => { console.log(employees) newState.employees = employees }) .then(() => this.setState(newState)) } deleteLocation = (id) => { const newState = {}; LocationManager.deleteLocation(id) .then(LocationManager.getAll) .then(locations => { console.log(locations) newState.locations = locations }) .then(() => this.setState(newState)) } deleteStudent = (id) => { const newState = {}; StudentManager.deleteStudent(id) .then(StudentManager.getAll) .then(students => { console.log(students) newState.students = students }) .then(() => this.setState(newState)) } addAnimal = animal => AnimalManager.post(animal) .then(() => AnimalManager.all()) .then(animals => this.setState({ animals: animals }) ); addEmployee = employee => EmployeeManager.post(employee) .then(() => EmployeeManager.all()) .then(employees => this.setState({ employees: employees }) ); updateEmployee= (editedEmployeeObj) => { return EmployeeManager.put(editedEmployeeObj) .then(() => EmployeeManager.all()) .then(employees => { this.props.history.push("/employees") this.setState({ employees: employees }) }); }; addLocation = location => LocationManager.post(location) .then(() => LocationManager.getAll()) .then(locations => this.setState({ locations: locations }) ); // update animals fetch call method updateAnimal = (editedAnimalObject) => { return AnimalManager.put(editedAnimalObject) .then(() => AnimalManager.all()) .then(animals => { this.props.history.push("/animals") this.setState({ animals: animals }) }); }; addStudent = student => StudentManager.post(student) .then(() => StudentManager.all()) .then(students => this.setState({ students: students }) ); componentDidMount() { const newState = {} fetch("http://localhost:5002/animals") .then(r => r.json()) .then(console.log("component did mount fired up")) .then(animals => newState.animals = animals) .then(() => fetch("http://localhost:5002/employees") .then(r => r.json())) .then(employees => newState.employees = employees) .then(() => fetch("http://localhost:5002/locations") .then(r => r.json())) .then(locations => newState.locations = locations) .then(() => fetch("http://localhost:5002/students") .then(r => r.json())) .then(students => newState.students = students) .then(() => this.setState(newState)) } render() { return ( <React.Fragment> <Route path="/login" component={Login} /> {/* location list card route path */} <Route exact path="/" render={(props) => { return <LocationList {...props} //?? locations={this.state.locations} deleteLocation={this.deleteLocation}/> }} /> {/* location form route */} <Route path="/new" render={(props) => { return <LocationForm {...props} addLocation={this.addLocation} /> }} /> {/* location details */} <Route path="/locations/:locationId(\d+)" render={(props) => { // Find the animal with the id of the route parameter let location = this.state.locations.find(location => location.id === parseInt(props.match.params.locationId) ) // If the location wasn't found, create a default one if (!location) { location = { id: 404, name: "404",} } return <LocationDetails location={location} deleteLocation={this.deleteLocation} /> }} /> <Route exact path="/animals" render={(props) => { return <AnimalList {...props} animals={this.state.animals} deleteAnimal={this.deleteAnimal}/> }} /> <Route path="/animals/new" render={(props) => { return <AnimalForm {...props} addAnimal={this.addAnimal} employees={this.state.employees} /> }} /> <Route path="/animals/:animalId(\d+)" render={(props) => { // Find the animal with the id of the route parameter let animal = this.state.animals.find(animal => animal.id === parseInt(props.match.params.animalId) ) // If the animal wasn't found, create a default one if (!animal) { animal = { id: 404, name: "404", breed: "Animal not found" } } return <AnimalDetail animal={animal} deleteAnimal={this.deleteAnimal} /> }} /> <Route exact path="/animals/:animalId(\d+)" render={props => { return ( <AnimalDetail {...props} deleteAnimal={this.deleteAnimal} animals={this.state.animals} /> ); }}/> <Route path="/animals/:animalId(\d+)/edit" render={props => { return <AnimalEditForm {...props} employees={this.state.employees} updateAnimal={this.updateAnimal}/> }} /> {/* and checks if the user loged in and takes u to employee list card route path */} <Route exact path="/employees" render={props => { if (this.isAuthenticated()) { return <EmployeeList {...props} deleteEmployee={this.deleteEmployee} employees={this.state.employees} /> } else { return <Redirect to="/login" /> } }} /> <Route path="/employees/new" render={(props) => { return <EmployeeForm {...props} addEmployee={this.addEmployee} /> }} /> <Route path="/employees/:employeeId(\d+)" render={(props) => { // Find the employee with the id of the route parameter let employee = this.state.employees.find(employee => employee.id === parseInt(props.match.params.employeeId) ) // If the employee wasn't found, create a default one if (!employee) { employee = { id: 404, name: "404", breed: "employee not found" } } return <EmployeeDetails employee={employee} deleteEmployees={this.deleteEmployees} /> }} /> <Route path="/employees/:employeeId(\d+)/edit" render={props => { return <EmployeeEditForm {...props} updateEmployee={this.updateEmployee}/> }} /> <Route path="/students" render={(props) => { return <StudentList {...props} students={this.state.students} deleteStudent={this.deleteStudent}/> }} /> <Route path="/students/new" render={(props) => { return <StudentForm {...props} addStudent={this.addStudent} /> }} /> </React.Fragment> ) } } export default withRouter(ApplicationViews)<file_sep>/src/component/nav/NavBar.js import React, { Component } from "react" import { Link } from "react-router-dom" import "bootstrap/dist/css/bootstrap.min.css" class NavBar extends Component { render() { return ( <nav className="navbar navbar-expand-lg navbar-dark bg-dark"> <ul className="navbar-nav mr-auto"> <li className="nav-item"> <Link className="nav-link" to="/">Locations</Link> </li> <li className="nav-item"> <Link className="nav-link" to="/animals">Animals</Link> </li> <li className="nav-item"> <Link className="nav-link" to="/employees">Employees</Link> </li> <li className="nav-item"> <Link className="nav-link" to="/students">classmates</Link> </li> <li className="nav-item"> <Link className="nav-link" to="/login">login</Link> </li> </ul> </nav> ) } } export default NavBar<file_sep>/src/component/employee/EmployeeList.js import React, { Component } from 'react'; import { Link } from "react-router-dom"; import picpic from "./picpic.svg" import "./Employee.css" class EmployeeList extends Component { handler = (event) => { console.log(event) this.props.deleteEmployees(this.props.employees.id) } render() { return ( <> <div className="employeeButton"> <button type="button" className="btn btn-info" onClick={() => { this.props.history.push("/employees/new")} }> Register New Employee </button> </div> <section className="employees"> <h1>Employees</h1> { this.props.employees.map(employee => <div key={employee.id}> <img src={picpic} alt = "" className="icon--employees" /> <p>{employee.name}</p> <button onClick={() => { this.props.deleteEmployees(employee.id) }}>Dismis</button> <Link className="nav-link" to={`/employees/${employee.id}`}>Details</Link> <button type="button" className="btn btn-info" onClick={() => { this.props.history.push(`/employees/${employee.id}/edit`); }}> Edit </button> </div> ) } </section> </> ); } } export default EmployeeList; <file_sep>/src/component/student/StudentList.js import React, { Component } from 'react'; import pic from "./pic.png" class StudentList extends Component { render() { return ( <> <div className="studentButton"> <button type="button" className="btn btn-info" onClick={() => { this.props.history.push("/students/new")} }> Register New Student </button> </div> <section className="locations"> <h1>Student List</h1> { this.props.students.map(student => <div key={student.id}> <img src={pic} alt = "" className="icon--student" /> <p>{student.name}</p> {/* <button onClick={()=> {this.props.deleteStudent(student.id)}}>Delete</button> */} </div> ) } </section> </> ); } } export default StudentList; <file_sep>/src/component/student/StudentForm.js import React, { Component } from 'react'; class StudentForm extends Component { // Set initial state state = { studentName: "" }; // Update state whenever an input field is edited handleFieldChange = evt => { const stateToChange = {}; stateToChange[evt.target.id] = evt.target.value; this.setState(stateToChange); }; /* Local method for validation, creating animal object, and invoking the function reference passed from parent component */ constructorNewStudent = evt => { evt.preventDefault(); const student = { name: this.state.studentName }; // Create the employee and redirect user to employee list this.props.addStudent(student) .then(() => this.props.history.push("/students")); } render() { return ( <React.Fragment> <form className="studentName"> <div className="form-group"> <label htmlFor="studentName">student name</label> <input type="text" required className="form-control" onChange={this.handleFieldChange} id="studentName" placeholder="Student name" /> <button type="button" onClick={this.constructorNewStudent} className="btn btn-primary"> Submit </button> </div> </form> </React.Fragment> ); } } export default StudentForm;
2ab0a02035f23328c6fcf0cb9a2d3d4e1d17712c
[ "JavaScript" ]
8
JavaScript
dek-haji/Kennel-5
1213ce308d688b776c85468cf1acb2b40d8597f9
fee51c180b5b9c11f6fd479a0e3d04328cff2204
refs/heads/master
<file_sep># Santa Cruz Wordpress Theme --- ![Santa cruz screenshot](screenshot.png) This is a wordpress theme for the TAD BOD Podcast via [tadbodpod.com](https://tadbodpod.com) <file_sep><?php /* Santa Cruz Theme ----------- index.php Main template file */ ?> <?php get_header(); ?> <main role="main"> <?php $classes = array(); if (!is_singular()) { array_push($classes, 'articles-listing'); } else { array_push($classes, 'article-single'); } ?> <div class="<?php echo implode(' ', $classes); ?>"> <?php if (have_posts()) : ?> <?php if (is_archive()) get_template_part('content/archive-heading'); ?> <?php /* Start the Loop */ ?> <?php while (have_posts()) : the_post(); ?> <?php get_template_part('content/content', get_post_type()); ?> <?php endwhile; ?> <?php if (!is_singular()) : ?> <div class="directional-links pagination"> <?php if (get_next_posts_link() != '') :?> <div class="nav-previous"><?php next_posts_link('<i class="fa fa-angle-left"></i> <span class="text">Older posts</span>'); ?></div> <?php endif; ?> <?php if (get_previous_posts_link() != '') :?> <div class="nav-next"><?php previous_posts_link('<span class="text">Newer posts</span> <i class="fa fa-angle-right"></i>'); ?></div> <?php endif; ?> </div> <?php endif; ?> <?php else : ?> <article id="post-0" class="post no-results not-found"> <h2>Nothing Found</h2> <p>I'm sorry, but no results were found. Perhaps searching will help find a related post.</p> <?php get_search_form(); ?> </article> <?php endif; ?> </div> </main> <?php get_footer(); ?><file_sep> </div> <footer class="footer-site"> <?php get_sidebar('footer'); ?> <div class="liner text-center"> <nav id="footer-nav" role="navigation"> <h2 class="assistive-text">Footer links</h2> <?php $menu_args = array( 'theme_location' => 'footer', 'container' => false, 'menu_class' => 'menu-inline', ); ?> <?php wp_nav_menu($menu_args); ?> </nav> <p>&copy; <?php echo date('Y'); ?> <?php bloginfo('name'); ?> All rights reserved.</p> </div> </footer> <?php wp_footer(); ?> </body> </html><file_sep><?php /* Santa Cruz Theme ----------- header.php Header template file */ ?><!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="<?php bloginfo('charset'); ?>" /> <?php /*<title><?php (wp_title('', false) != '') ? wp_title('&#8226;', true, 'right') : ''; ?><?php bloginfo('name'); ?></title>*/ // WP Managed ?> <!-- Meta --> <meta name="description" content="<?php bloginfo('description'); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="theme-color" content="#73dbbe"> <!-- Links --> <link rel="profile" href="http://gmpg.org/xfn/11" /> <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" /> <!-- Stylesheets --> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <?php // Stylesheets wp_enqueue_style('phosphate', get_template_directory_uri() . '/assets/fonts/phosphate/stylesheet.css'); wp_enqueue_style('wyatt', get_stylesheet_uri(), 'phosphate'); // Javascript // pull in the jQuery wp_enqueue_script('jquery'); // if (is_singular()) { // // pull in Nivo-gallery // wp_enqueue_script('nivo-lightbox', get_template_directory_uri() . '/lib/Nivo-Lightbox-1.1/nivo-lightbox.min.js', 'jquery', 1.0); // } // pull in the site js wp_enqueue_script('santacruz_js', get_template_directory_uri() . '/js/script.min.js', 'jquery', false); // comment script if (is_singular() && get_option('thread_comments')) : wp_enqueue_script('comment-reply'); endif; ?> <?php // Wordpress header content wp_head(); ?> </head> <body<?php echo (is_admin_bar_showing()) ? ' class="admin-bar"' : ''; ?>> <div class="page"> <header class="header-site"> <div class="liner"> <div class="row align-items-center justify-content-between"> <div class="col-12 col-md"> <div class="row flex-column text-center"> <div class="col"> <a href="<?php echo site_url(); ?>" class="branding-link"><?php santacruz_bullet_stylized(get_bloginfo('name')); ?></a> </div> <?php if (get_bloginfo('description') !== ''): ?> <div class="col order-first"> <span class="tagline"><?php bloginfo('description'); ?></span> </div> <?php endif; ?> </div> </div> <div class="col-auto order-md-first"> <div class="menu-system"> <a role="button" class="bubble-link menu-trigger"> <span><?php santacruz_icon('menu'); ?></span> <span><?php _e('Menu'); ?></span> </a> <div class="menu-container closed"> <h2 class="assistive-text">Main menu</h2> <?php $menu_args = array( 'theme_location' => 'primary', 'container' => false, 'menu_class' => 'menu', ); ?> <?php wp_nav_menu($menu_args); ?> </div> </div> </div> <div class="col-auto order-md-last"> <?php if (santacruz_show_getit_link()) : ?> <a href="<?php santacruz_getit_url(); ?>" class="bubble-link bubble-link--orange"> <span><?php santacruz_icon('rss'); ?></span> <span>Get it</span> </a> <?php endif; ?> </div> </div> </div> </header><file_sep><?php /* Santa Cruz Theme ---------------- functions.php Functions file */ ini_set('display_errors', 1); // for development /* * Enable post thumbnails */ add_theme_support('post-thumbnails'); /* * Setup post formats */ add_theme_support('post-formats', array('link', 'quote', 'video', 'audio')); /* * Let WordPress manage the document title. * By adding theme support, we declare that this theme does not use a * hard-coded <title> tag in the document head, and expect WordPress to * provide it for us. */ add_theme_support( 'title-tag' ); /* * Switch default core markup for search form, comment form, and comments * to output valid HTML5. */ add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption', 'script', 'style', ) ); // Add some image sizes for post thumbnails add_image_size('page-header', 1600, 700, true); // Add menus if (function_exists('register_nav_menu')) { register_nav_menu('primary', 'Main Menu'); register_nav_menu('footer', 'Footer Menu'); } /** * Custom Settings */ class santacruz_customize { public static function register($wp_customize) { // add the sections $wp_customize->add_section('santacruz_options', array( 'title' => __('Theme Options', 'santacruz'), 'priority' => 55, 'capability' => 'edit_theme_options', 'description' => __('Enable certain features of the theme.', 'santacruz') ) ); // Show home page title setting $wp_customize->add_setting('santacruz_get_it_link', array( 'default' => 0, 'type' => 'option', 'capability'=> 'edit_theme_options', 'transport' => 'refresh', ) ); // Show home page title control $page_options = array(0 => 'Do not use; hide link'); $all_pages = get_pages(); foreach ($all_pages as $page) { $page_options[$page->ID] = $page->post_title; } $wp_customize->add_control('santacruz_get_it_link', array( 'label' => '"Get it" Link Page', 'description' => __('What page should the orange "Get It" link point to?'), 'section' => 'santacruz_options', 'type' => 'select', 'choices' => $page_options, ) ); } } add_action('customize_register', array('santacruz_customize', 'register')); // Add widget areas function santacruz_widget_init() { // Register footer widgets register_sidebar( array( 'name' => __('Footer'), 'desc' => __('Place widgets in the site footer. These look best in multiples of two (2, 4, etc).'), 'id' => 'footer-widgets', 'before_widget' => '<div id="%1$s" class="widget col-md">', 'after_widget' => '</div>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>' ) ); } add_action('widgets_init', 'santacruz_widget_init'); // function to return the feature image function santacruz_featured_image() { $image = array(); if (get_the_post_thumbnail() != '') { // get the URL of the featured image $header_image = wp_get_attachment_image_src(get_post_thumbnail_id(), 'page-header'); $image['url'] = $header_image[0]; $image['width'] = $header_image[1]; $image['height'] = $header_image[2]; } return (!empty($image)) ? $image : false; } // GET IT link function santacruz_show_getit_link() { return (get_option('santacruz_get_it_link') !== 0); } function santacruz_getit_url() { $getit_link_post_id = get_option('santacruz_get_it_link'); if ($getit_link_post_id !== 0) { echo get_permalink($getit_link_post_id); } } // Content width if (!isset($content_width)) { $content_width = 568; } // Add automatic feed links add_theme_support('automatic-feed-links'); // adding fuction to get the author posts link (the only built-in function echos it). if (!function_exists('get_author_posts_link')) { // must be called from within the loop function get_author_posts_link() { $the_author = get_the_author(); $author_url = get_author_posts_url(get_the_author_meta('ID')); return '<a href="' . $author_url . '">' . $the_author . '</a>'; } } // Custom comment output function santacruz_comment($comment, $args, $depth) { $GLOBALS['comment'] = $comment; extract($args, EXTR_SKIP); $args['avatar_size'] = 48; $args['reply_text'] = '<span class="text">'.__('Reply').'</span>'; ?> <li id="comment-<?php comment_ID() ?>" <?php comment_class(empty($args['has_children']) ? '' : 'parent') ?>> <article class="comment<?php echo ($comment->comment_approved == '0') ? ' comment-pending' : ''; ?>"> <?php if ($comment->comment_approved == '0') : ?> <p class="comment-awaiting-moderation box box-warning text-center"><?php _e('Your comment is awaiting moderation.') ?></p> <?php endif; ?> <?php comment_text() ?> <div class="row align-items-center"> <!-- Comment details --> <div class="comment-details col-sm"> <span class="comment-date"><a href="<?php echo htmlspecialchars(get_comment_link($comment->comment_ID)); ?>"><?php printf(__('%1$s %2$s'), get_comment_date(), get_comment_time()); ?></a></span> <span class="comment-author"> <span><?php _e('Posted by'); ?></span> <span class="comment-avatar"><?php if ($args['avatar_size'] != 0) echo get_avatar( $comment, $args['avatar_size'] ); ?></span> <span class="vcard"><?php comment_author_link() ?></span> </span> </div> <!-- Comment links --> <div class="comment-links col-sm-auto"> <?php comment_reply_link(array_merge($args, array( 'add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth'], 'reply_text' => get_santacruz_icon('arrow-down-left') . __('Retort') ))) ?> <a href="<?php echo htmlspecialchars(get_comment_link($comment->comment_ID)); ?>" class="btn btn-secondary" title="Permalink"><?php santacruz_icon('link'); ?> <span class="sr-only">Link to comment</span></a> <?php edit_comment_link(get_santacruz_icon('edit-3') . '<span class="text">' . __('Edit') . '</span>','',''); ?> </div> </div> </article> </li> <?php } /** * The default Wordpress comment form * leaves a lot to be desired. Here is * a version that has more markup and is * easier to style. */ function santacruz_comment_form() { // define fields $fields = array( 'open_dir' => '<div class="row">', 'author' => '<p class="form-item col-12 col-md label-inline comment-form-author">' . '<label for="author">' . __( 'Name' ) . '</label> ' . ( $req ? '<span class="required">*</span>' : '' ) . '<span class="input-holder"><input id="author" name="author" type="text" class="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' /></span></p>', 'email' => '<p class="form-item col-12 col-md label-inline comment-form-email"><label for="email">' . __( 'Email' ) . '</label> ' . ( $req ? '<span class="required">*</span>' : '' ) . '<span class="input-holder"><input id="email" name="email" type="text" class="text" value="' . esc_attr( $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . ' /></span></p>', 'url' => '<p class="form-item col-12 col-md label-inline comment-form-url"><label for="url">' . __( 'Website' ) . '</label>' . '<span class="input-holder"><input id="url" name="url" type="text" class="text" value="' . esc_attr( $commenter['comment_author_url'] ) . '" size="30" /></span></p>', 'close_div' => '</div>' ); // build our new defaults array (based off of default defaults. customized values noted. $defaults = array( 'fields' => apply_filters('comment_form_default_fields', $fields ), /* customized */ 'comment_field' => '<p class="form-item label-inline comment-form-comment"><label for="comment">' . _x( 'Comment', 'noun' ) . '</label><span class="input-holder"><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true" class=""></textarea></span></p>', /* customized */ 'must_log_in' => '<p class="must-log-in help">' . sprintf( __( 'You must be <a href="%s">logged in</a> to post a comment.' ), wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>', 'logged_in_as' => '<p class="logged-in-as help">' . sprintf( __( 'Logged in as <a href="%1$s">%2$s</a>. <a href="%3$s" title="Log out of this account">Log out?</a>' ), admin_url( 'profile.php' ), $user_identity, wp_logout_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>', 'comment_notes_before' => '<p class="comment-notes help">' . __( 'Your email address will not be published.' ) . ( $req ? $required_text : '' ) . '</p>', 'comment_notes_after' => '<p class="some-html-allowed help small hide">' . sprintf(__('Some <abbr title="Hyper Text Markup Language">HTML</abbr> allowed: <code>%s</code>'), allowed_tags()) . '</p>', /* customized */ 'id_form' => 'commentform', 'id_submit' => 'submit', 'title_reply' => __( 'Leave a Comment' ), 'title_reply_to' => __( 'Leave a Reply to %s' ), 'cancel_reply_link' => __( 'Cancel Comment' ), 'label_submit' => __( 'Post Comment' ) ); // send them back out! Bam! return $defaults; } add_filter('comment_form_defaults', 'santacruz_comment_form'); /** * Functions available in templates */ // Function(s) to generate a list of links for sharing function get_share_links($url, $title, $class = 'sharing-list', $icon_prefix = 'fa fa-') { if (isset($url) && isset($title)) { $url = urlencode($url); $title = urlencode($title); $services['facebook'] = array( 'label' => 'Facebook', 'url' => 'http://www.facebook.com/sharer.php?s=100&amp;p[title]={{title}}&amp;p[url]={{url}}', 'icon' => 'facebook', ); $services['twitter'] = array( 'label' => 'Twitter', 'url' => 'https://twitter.com/intent/tweet?url={{url}}&amp;text={{title}}', 'icon' => 'twitter', ); $services['pinterest'] = array( 'label' => 'Pinterest', 'url' => 'http://www.pinterest.com/pin/create/bookmarklet/?url={{url}}&description={{title}}', 'icon' => 'pinterest', ); // $services['tumblr'] = array( // 'label' => 'Tumblr', // 'url' => 'http://www.tumblr.com/share/?url={{url}}&description={{title}}', // 'icon' => 'tumblr', // ); $services['email'] = array( 'label' => 'Email', 'url' => 'mailto:?&amp;Subject=Sharing:+{{title}}&amp;Body={{url}}', 'icon' => 'envelope', 'extra' => 'target="_blank"', ); // build the output $output = '<ul class="' . $class . '">' . "\n"; foreach ($services as $key => $service) { $extra = (isset($service['extra'])) ? ' '.$service['extra'] : ''; $output .= "\t" . '<li><a href="'.$service['url'].'" class="'.$key.'"'.$extra.'><i class="{{icon_prefix}}'.$service['icon'].'"></i> <span class="text">'.$service['label'].'</span></a></li>' . "\n"; } $output .= '</ul>'; $output = preg_replace('/{{url}}/', $url, $output); $output = preg_replace('/{{title}}/', $title, $output); $output = preg_replace('/{{icon_prefix}}/', $icon_prefix, $output); return $output; } else { // not enought data. return empty string. return ''; } } function share_links($url, $title, $class = 'sharing-list', $icon_prefix = 'fa fa-') { echo get_share_links($url, $title, $class, $icon_prefix); } function get_santacruz_icon($name = 'smile', $class = '') { $iconpath = get_template_directory_uri() . '/assets/img/feather-sprite.svg#' . $name; return "<svg class=\"icon {$class}\"><use xlink:href=\"{$iconpath}\"/></svg>"; } function santacruz_icon($name = 'smile', $class = '') { echo get_santacruz_icon($name, $class); } function santacruz_bullet_stylized($ref) { echo str_replace(' ', '&bull;', $ref); }<file_sep><?php /* Santa Cruz Theme ---------------- sidebar-footer.php Sidebar footer template file */?> <?php if (is_active_sidebar('footer-widgets')) : ?> <div id="footer-widgets" class="liner"> <div class="row"> <?php dynamic_sidebar('footer-widgets'); ?> </div> </div> <?php endif; ?> <file_sep><?php /* Santa Cruz Theme ---------------- article.php Article default template file * Called from within the loop. Will not work otherwise. * */ $classes = array('article'); if (!is_singular()) { array_push($classes, 'article-listed'); } else { array_push($classes, 'article-single'); } ?> <article id="post-<?php the_ID(); ?>" <?php post_class($classes); ?>> <?php if (is_singular()) : $featured_image = santacruz_featured_image(); if ($featured_image) : ?> <!-- Featured image --> <div class="featured-image"> <img src="<?php echo $featured_image['url']; ?>" width="<?php echo $featured_image['width']; ?>" height="<?php echo $featured_image['height']; ?>" /> </div> <?php endif; // end if featured image set ?> <?php endif; // end if singular ?> <div class="liner liner-narrow"> <div class="row"> <?php if (is_singular()) : ?> <div class="col-12"> <h1 class="page-title"><?php the_title(); ?></h1> </div> <?php endif; ?> <?php if (has_post_format('audio')) : ?> <div class="col-2 text-right"> <span class="icon-play"></span> </div> <?php endif; ?> <div class="article-body col"> <?php if (!is_singular()) :?> <h2><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h2> <?php endif;?> <?php $read_time = do_shortcode('[est_time]'); if ($read_time !== '[est_time]' && $read_time !== ''): ?> <p class="read-time"><?php echo __('Estimated reading time: ') . $read_time ?></p> <?php endif; ?> <?php if(!is_page()) : ?> <p><span class="article-post-date"><?php the_time(get_option('date_format')); ?></span></p> <?php endif; ?> <!-- Post Content --> <?php if (!is_singular()) : ?> <?php the_excerpt(); ?> <?php else : ?> <?php the_content(); ?> <?php wp_link_pages(array('before' => '<div class="page-links">' . __('Pages') . ':', 'after' => '</div>')); ?> <?php endif; ?> <div class="article-meta row align-items-center"> <div class="article-taxonomy col-sm-auto order-sm-last"> <!-- Post taxonomy --> <?php $categories_list = get_the_category_list(', '); ?> <?php $tags_list = get_the_tag_list('', ', '); ?> <?php if ($categories_list) : ?> <div class="details">Posted in <?php echo $categories_list; ?></div> <?php endif; ?> </div> <div class="article-links col-sm"> <!-- Post links --> <?php if (!is_singular()) : ?> <a href="<?php the_permalink(); ?>" title="<?php _e('Read more...'); ?>" class="btn btn-success"> <?php if (has_post_format('audio')) : ?> <?php santacruz_icon('headphones') ?> <span class="text"><?php _e('Listen now'); ?></span> <?php else: ?> <?php santacruz_icon('file-text') ?> <span class="text"><?php _e('Read more'); ?></span> <?php endif; ?> </a> <?php endif; ?> <?php if (comments_open()) : ?> <?php $comment_icon = get_santacruz_icon('message-circle'); ?> <?php comments_popup_link($comment_icon . '<span class="text">Comment</span>', $comment_icon . ' <span class="text">1 Comment</span>', $comment_icon . '<span class="text">% Comments</span>', 'btn btn-success'); ?> <?php endif; ?> <?php edit_post_link(get_santacruz_icon('edit-3') . '<span class="text">Edit</span>', '', '', null, 'btn btn-primary'); ?> </div> </div> </div> </div> <?php if (is_singular() && !is_page()) : ?> <div class="sharing"> <div class="row margin-collapse align-items-center justify-content-center"> <div class="col-md-auto"> <h2 class="h3 sharing-heading">Do that social:</h2> </div> <div class="col-md-auto"> <?php share_links(get_permalink(), get_the_title()); ?> </div> </div> </div> <?php endif; ?> <?php /** * Output comments wrapper if it's a post, or if comments are open, * or if there's a comment number – and check for password. * */ if (( is_single() || is_page() ) && ( comments_open() || get_comments_number() ) && ! post_password_required()): ?> <?php comments_template(); ?> <?php endif; ?> </div> </article> <?php if (is_single()) : ?> <div class="directional-links"> <div class="row margin-collapse no-gutters"> <div class="nav-next col-sm order-sm-last text-right"><?php next_post_link('%link', 'Next article: <span class="text">&#8220;%title&#8221;</span> '. get_santacruz_icon('arrow-right')); ?></div> <div class="nav-previous col-sm"><?php previous_post_link('%link', get_santacruz_icon('arrow-left') . ' Previous article: <span class="text">&#8220;%title&#8221;</span>'); ?></div> </div> </div> <?php endif; ?>
c25b7d4630b561d22a28f23af06ff0615e79c106
[ "Markdown", "PHP" ]
7
Markdown
rewdy/santacruz
d83f31fd3b6f2f0873bfd55c3072bd5a3070f75f
680ccbdb751a3d0135e1fe5da9876590e601bc6c
refs/heads/master
<repo_name>MarcosPedraza/NutriLife<file_sep>/app/src/main/java/com/kike/nutri/nutrilife/ResPersFragment.java package com.kike.nutri.nutrilife; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.kike.nutri.nutrilife.Adapters.RecetasAdapter; import com.kike.nutri.nutrilife.Models.DiaReceta; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class ResPersFragment extends Fragment { private static final String TAG = "ResPersFragment"; //widget RecyclerView rv_dias; //variables ArrayList<DiaReceta> list_days; public ResPersFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_res_pers, container, false); loadData(); rv_dias = view.findViewById(R.id.rv_res_personales); RecetasAdapter adapter = new RecetasAdapter(list_days, getContext()); rv_dias.setAdapter(adapter); rv_dias.setLayoutManager(new LinearLayoutManager(getContext())); return view; } public void loadData() { list_days = new ArrayList<>(); list_days.add(new DiaReceta("lun","Lunes",R.drawable.icon_lettuce)); list_days.add(new DiaReceta("mar","Martes",R.drawable.icon_paella)); list_days.add(new DiaReceta("mier","Miercoles",R.drawable.icon_wrap)); list_days.add(new DiaReceta("jue","Jueves",R.drawable.icons_vegan_f)); list_days.add(new DiaReceta("vie","Viernes",R.drawable.icon_porridge)); list_days.add(new DiaReceta("sab","Sabado",R.drawable.icons_tapas)); list_days.add(new DiaReceta("dom","Domingo",R.drawable.icon_eggs)); } } <file_sep>/app/src/main/java/com/kike/nutri/nutrilife/ConsejosFragment.java package com.kike.nutri.nutrilife; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.kike.nutri.nutrilife.Adapters.AdapterConsejos; import com.kike.nutri.nutrilife.Adapters.RecetasAdapter; import com.kike.nutri.nutrilife.Models.Consejo; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class ConsejosFragment extends Fragment { //widgets RecyclerView rv_consejos; //var ArrayList<Consejo> consejos; public ConsejosFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_consejos, container, false); rv_consejos = view.findViewById(R.id.rv_consejos); // rv_consejos.setHasFixedSize(true); loadData(); AdapterConsejos adapter = new AdapterConsejos(consejos,getContext()); rv_consejos.setAdapter(adapter); rv_consejos.setLayoutManager(new LinearLayoutManager(getContext())); return view; } private void loadData() { consejos = new ArrayList<>(); consejos.add(new Consejo("Compartí la información confiable y la opinión de los especialistas más prestigiosos con este link: 10 consejos para una alimentación saludable ","https://www.buenoyvegano.com/wp-content/uploads/2017/11/medium_PufK7Rj5Mi.jpg")); consejos.add(new Consejo("Compartí la información confiable y la opinión de los especialistas más prestigiosos con este link: 10 consejos para una alimentación saludable ","https://www.buenoyvegano.com/wp-content/uploads/2017/11/medium_PufK7Rj5Mi.jpg")); consejos.add(new Consejo("Compartí la información confiable y la opinión de los especialistas más prestigiosos con este link: 10 consejos para una alimentación saludable ","https://www.buenoyvegano.com/wp-content/uploads/2017/11/medium_PufK7Rj5Mi.jpg")); consejos.add(new Consejo("Compartí la información confiable y la opinión de los especialistas más prestigiosos con este link: 10 consejos para una alimentación saludable ","https://www.buenoyvegano.com/wp-content/uploads/2017/11/medium_PufK7Rj5Mi.jpg")); consejos.add(new Consejo("Compartí la información confiable y la opinión de los especialistas más prestigiosos con este link: 10 consejos para una alimentación saludable ","https://www.buenoyvegano.com/wp-content/uploads/2017/11/medium_PufK7Rj5Mi.jpg")); consejos.add(new Consejo("Compartí la información confiable y la opinión de los especialistas más prestigiosos con este link: 10 consejos para una alimentación saludable ","https://www.buenoyvegano.com/wp-content/uploads/2017/11/medium_PufK7Rj5Mi.jpg")); consejos.add(new Consejo("Compartí la información confiable y la opinión de los especialistas más prestigiosos con este link: 10 consejos para una alimentación saludable ","https://www.buenoyvegano.com/wp-content/uploads/2017/11/medium_PufK7Rj5Mi.jpg")); } } <file_sep>/app/src/main/java/com/kike/nutri/nutrilife/Adapters/AdapterEjercicios.java package com.kike.nutri.nutrilife.Adapters; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.kike.nutri.nutrilife.Models.Ejercicio; import com.kike.nutri.nutrilife.R; import java.util.ArrayList; public class AdapterEjercicios extends RecyclerView.Adapter<AdapterEjercicios.ViewHolder>{ ArrayList<Ejercicio> list_ejercicio; Context context; public AdapterEjercicios(ArrayList<Ejercicio> list_ejercicio, Context context) { this.list_ejercicio = list_ejercicio; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_ejercicio,parent,false); AdapterEjercicios.ViewHolder holder = new AdapterEjercicios.ViewHolder(view); return holder; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { holder.nombre_ejer.setText(list_ejercicio.get(position).getNombre_ejercicio()); Glide.with(context) .load(list_ejercicio.get(position).getUrl_img()) .into(holder.imag_video); } @Override public int getItemCount() { return list_ejercicio.size(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView nombre_ejer; ImageView imag_video; public ViewHolder(View itemView) { super(itemView); nombre_ejer = itemView.findViewById(R.id.tv_nom_ejercicio); imag_video = itemView.findViewById(R.id.img_ejercicio); } } } <file_sep>/app/src/main/java/com/kike/nutri/nutrilife/Configs/PlayerConfig.java package com.kike.nutri.nutrilife.Configs; public class PlayerConfig { PlayerConfig() { } public static final String API_KEY = "<KEY>"; }
362eb90d5f382b025a0bc891d581c9f3c037117b
[ "Java" ]
4
Java
MarcosPedraza/NutriLife
cffce4edb35cf87da9bbe13cf705e69a8bdc174b
fa3e9a264c295fa69c8d2ff2010ea0a0a50146bc
refs/heads/master
<repo_name>Skonchy/SecurityProject<file_sep>/scripts/connection.php <?php $servername="localhost"; $username="root"; $password=""; $conn=new mysqli($servername,$username,$password); if($conn->connect_error){ die("Database connection failed: " . $conn->connect_error); } echo("Database connection established."); ?><file_sep>/scripts/createDB.php <?php $servername = "localhost"; $username = "root"; $password = ""; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Create database $sql = "CREATE DATABASE 410Project"; if ($conn->query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: " . $conn->error; } //Create Table Users $sql_table1 = "CREATE TABLE Users ( id INT(6) UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY, username VARCHAR(40) NOT NULL, pass VARCHAR(50) NOT NULL, trust DECIMAL NOT NULL, reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, )"; if ($conn->query($sql_table1) === TRUE) { echo "Table Users created successfully"; } else { echo "Error creating table: " . $conn->error; } //Create Table Transactions $sql_table2 = "CREATE TABLE Transactions ( trans_num INT(6) UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY, trans_id BINARY(256) NOT NULL, cust_id INT(6) UNSIGNED NOT NULL, amount DECIMAL NOT NULL, trans_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, )"; if ($conn->query($sql_table2) === TRUE) { echo "Table Transactions created successfully"; } else { echo "Error creating table: " . $conn->error; } $conn->close(); ?><file_sep>/README.md # SecurityProject Group Project for CS 410 <file_sep>/scripts/transaction.php <?php $servername = "localhost"; $username = "root"; $pass=""; $db="410Project"; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } mysql_select_db($db); if(isset($_POST['transaction'])){ $logedinUser=$_SESSION['user']['Username']; $query=("SELECT id FROM Users WHERE username='$logedinUser'"); $result=mysql_query($query); $trans_id="hash"; $cust_id=$result; $amount=$_POST['amount']; $trans_date=CURRENT_TIMESTAMP; $query=("INSERT INTO Transactions (trans_id, cust_id, amount, trans_date) VALUES ('$trans_id','$cust_id','$amount','$trans_date')"); if(mysql_query($query)){ echo "Insert into Transactions successful"; } else { echo "Insert into Transactions failed"; } } ?><file_sep>/scripts/register.php <?php $servername = "localhost"; $username = "root"; $pass=""; $db="410Project"; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } mysql_select_db($db); if(isset($_POST['register'])){ $username=$_POST(['Username']); $pass=$_POST(['Password']); $trust='0.5'; $reg_date=CURRENT_TIMESTAMP; $query=("INSERT INTO Users (username, pass, trust, reg_date) VALUES ('$username','$pass','$trust','$reg_date')"); if(mysql_query($query)){ echo "Insert into Users successful"; } else { echo "Insert into Users failed"; } } ?>
58eb03a877c0d945ae9583aaf5e2e0839e1e7c5e
[ "Markdown", "PHP" ]
5
PHP
Skonchy/SecurityProject
641c7efec1c7516adbd0889ce3f9cd15d518c2dc
b2c8683d7f729c64a9c05983601456cf39362a54
refs/heads/master
<repo_name>well12-saber/FigureSquareTask<file_sep>/README.md # Task Тестовое задание 1 задание Напишите на C# библиотеку для поставки внешним клиентам, которая умеет вычислять площадь круга по радиусу и треугольника по трем сторонам. 2 задание В базе данных MS SQL Server есть продукты и категории. Одному продукту может соответствовать много категорий, в одной категории может быть много продуктов. Напишите SQL запрос для выбора всех пар «Имя продукта – Имя категории». Если у продукта нет категорий, то его имя все равно должно выводиться. <file_sep>/Figure/Triangle.cs using System; using static System.Math; namespace Figure { public class Triangle : AbstractFigure { private UDouble a; private UDouble b; private UDouble c; public Triangle (double x, double y, double z) { if ((x+y<z) || (x + z < y) || (y + z < x)) throw new Exception("Triangle doesn't exist."); a = x; b = y; c = z; } public override double getSquare() { double p = (a + b + c)/2; return Sqrt(p * (p - a) * (p - b) * (p - c)); } public bool checkReck() { if ((Pow(a,2)==(Pow(b, 2)+ Pow(c, 2))) || (Pow(b, 2) == (Pow(a, 2) + Pow(c, 2))) || (Pow(c, 2) == (Pow(a, 2) + Pow(b, 2)))) return true; else return false; } } } <file_sep>/Figure/Circle.cs using System; using System.Collections.Generic; using System.Text; using static System.Math; namespace Figure { public class Circle : AbstractFigure { private UDouble r; public Circle(double x) { r = x; } public override double getSquare() { return Math.PI * Math.Pow(r,2); } } } <file_sep>/sql_task/query.sql select product.name,category.name from product join productCategory on product.id=productCategory.productId join category on category.Id=productCategory.categoryId UNION select product.name,null from product where product.id not IN (select productId from productCategory) <file_sep>/Figure/AbstractFigure.cs using System; using System.Collections.Generic; using System.Text; namespace Figure { public abstract class AbstractFigure { public abstract double getSquare(); } } <file_sep>/Test/UnitTest.cs using Microsoft.VisualStudio.TestTools.UnitTesting; using Figure; using static System.Math; using System; namespace Test { [TestClass] public class UnitTest { [TestMethod] public void TestMethod1() { Circle c = new Circle(5); Assert.AreEqual(Math.PI * Pow(5, 2), c.getSquare()); } [TestMethod] public void TestMethod2() { Triangle t = new Triangle(3,4,5); Assert.AreEqual(6, t.getSquare()); } [TestMethod] [ExpectedException(typeof(Exception), "Value must be positive.")] public void TestMethod3() { Triangle t = new Triangle(-2,-3,-4); } [TestMethod] [ExpectedException(typeof(Exception), "Value must be positive.")] public void TestMethod4() { Circle c = new Circle(-2); } [TestMethod] [ExpectedException(typeof(Exception), "Triangle doesn't exist.")] public void TestMethod5() { Triangle t = new Triangle(2, 3, 10); } [TestMethod] public void TestMethod6() { Triangle t = new Triangle(3, 4, 5); Assert.AreEqual(true, t.checkReck()); } } } <file_sep>/Figure/UDouble.cs using System; using System.Collections.Generic; using System.Text; namespace Figure { public struct UDouble //Positive Double { private double value; public UDouble (double v) { if(v<=0) throw new Exception("Value must be positive."); value = v; } public static implicit operator double(UDouble d) { return d.value; } public static implicit operator UDouble(double v) { if (v <= 0) throw new Exception("Value must be positive"); return new UDouble(v); } } } <file_sep>/sql_task/db.sql create table product ( id int, name varchar(255) ); create table productCategory ( productId int , categoryId int ); create table category ( id int , name varchar(255) ); insert into product (id,name) values (1,'meat'), (2,'tea'), (3,'water'), (4,'chocolate'), (5,'bag'); insert into category (id,name) values (1,'A'), (2,'B'), (3,'C'); insert into productCategory (productId,categoryId) values (1,1), (2,3), (3,3), (4,2);
adbc443b891231220290a450063b0e301293e5df
[ "Markdown", "C#", "SQL" ]
8
Markdown
well12-saber/FigureSquareTask
375636b8afd64c9c12e77764a9eea6dc9fbd1060
ca1b427885aeac761ce97989f2ba04fba1fa0870
refs/heads/master
<repo_name>josephleblanc/libft_independent<file_sep>/libft_tests/test_ft_strlen.c #include <unistd.h> #include <stdio.h> #include <string.h> size_t ft_strlen(const char *s); int main(void) { printf("Testing strlen against ft_strlen\n\n"); printf("strlen(\"\"): %zu\nft_strlen(\"\"): %zu\n\n", strlen(""), ft_strlen("")); printf("strlen(\"1\"): %zu\nft_strlen(\"1\"): %zu\n\n", strlen("1"), ft_strlen("1")); printf("strlen(\"12\"): %zu\nft_strlen(\"12\"): %zu\n\n", strlen("12"), ft_strlen("12")); printf("strlen(\"123\"): %zu\nft_strlen(\"123\"): %zu\n\n", strlen("123"), ft_strlen("123")); printf("strlen(\"abc\"): %zu\nft_strlen(\"abc\"): %zu\n\n", strlen("abc"), ft_strlen("abc")); printf("strlen(\"NULL\"): %zu\nft_strlen(\"NULL\"): %zu\n\n", strlen("NULL"), ft_strlen("NULL")); printf("strlen(\"qwertyuiopasdfghjklzxcvbnm\"): %zu\nft_strlen(\"qwertyuiopasdfghjklzxcvbnm\"): %zu\n\n", strlen("qwertyuiopasdfghjklzxcvbnm"), ft_strlen("qwertyuiopasdfghjklzxcvbnm")); printf("Tests Complete\n"); return (0); }
52cfba34c93605ab758722d97bdee6e9bb25e505
[ "C" ]
1
C
josephleblanc/libft_independent
734ea91dab09c797bca0409a1aec21f6c8e2a557
16e8fe95c566d2c8b9458844076a4008f826a8b0
refs/heads/master
<repo_name>hanseljulio/VideoEditor<file_sep>/main.py import moviepy.editor from pytube import * from datetime import * from moviepy.editor import * import moviepy.video.fx.all as vfx def audioSplit(dirVideo, dirAudio): video = moviepy.editor.VideoFileClip(dirVideo) audio = video.audio audio.write_audiofile("{}.mp3".format(dirAudio)) def videoTrim(dirVideo): trimStart = int(input("Trim start (sec) > ")) trimEnd = int(input("Trim end (sec) > ")) newClip = dirVideo.subclip(trimStart, trimEnd) fps = int(input("FPS > ")) print(''' Video quality: [1] Normal (libx264, compressed) [2] High (mpeg4, higher quality) [3] Raw video (uncompressed, raw) [4] Perfect quality, smaller than raw video in size [5] Ogv file - open source [6] Webm file ''') vidChoice = int(input("Input choice > ")) result = str(input("Output file name > ")) if (choice == 3 or choice == 4): newClip.write_videofile("{}.avi".format(result), codec=videoQuality(vidChoice), fps=fps) elif (choice == 5): newClip.write_videofile("{}.ogv".format(result), codec=videoQuality(vidChoice), fps=fps) elif (choice == 6): newClip.write_videofile("{}.webm".format(result), codec=videoQuality(vidChoice), fps=fps) else: newClip.write_videofile("{}.mp4".format(result), codec=videoQuality(vidChoice), fps=fps) newClip.close() def videoQuality(vidChoice): switcher = { 1: "libx264", 2: "mpeg4", 3: "rawvideo", 4: "png", 5: "libvorbis", 6: "libvpx" } return switcher.get(vidChoice) def gifCreate(dirVideo): trimStart = int(input("Trim start (sec) > ")) trimEnd = int(input("Trim end (sec) > ")) newClip = dirVideo.subclip(trimStart, trimEnd) result = input("Output name > ") newClip.write_gif("{}.gif".format(result), fps=15) def ytInfo(yt): print("Title: ", yt.title) print("Number of views (as of {}):".format(date.today()), yt.views, "views") print("Length of video: ", yt.length, "seconds") print("Ratings: ", yt.rating) def ytDownloader(yt): ys = yt.streams.get_highest_resolution() print("Downloading...") ys.download() print("Download complete") def ytVidInfo(yt): print(yt.streams.filter(progressive=True)) def boomerang(dirVideo): trimStart = int(input("Trim start (sec) > ")) trimEnd = int(input("Trim end (sec) > ")) sub = dirVideo.subclip(trimStart, trimEnd) clip2 = sub.speedx(final_duration=2) clip3 = clip2.fx(vfx.time_mirror) final = concatenate_videoclips([clip2, clip3]) result = input("Output name > ") final.to_gif("{}.gif".format(result), fps=15) print(''' [1] Split audio from video [2] Trim video [3] Create a gif [4] Youtube video information [5] Download YouTube video [6] Youtube download resolution info [7] Boomerang GIF ''') choice = int(input("Input number > ")) if (choice == 1): print("Insert video directory, USE '\\\\' FOR BACKSLASH") dirVideo = str(input("Video location > ")) print() dirAudio = str(input("Output name > ")) audioSplit(dirVideo, dirAudio) elif (choice == 2): print("Insert video directory, USE '\\\\' FOR BACKSLASH") dirVideo = VideoFileClip(str(input("Video location > "))) videoTrim(dirVideo) elif (choice == 3): print("Insert video directory, USE '\\\\' FOR BACKSLASH") dirVideo = VideoFileClip(str(input("Video location > "))) gifCreate(dirVideo) elif (choice == 4): link = str(input("Link > ")) yt = YouTube(link) ytInfo(yt) elif (choice == 5): link = str(input("Link > ")) yt = YouTube(link) ytDownloader(yt) elif (choice == 6): link = str(input("Link > ")) yt = YouTube(link) ytVidInfo(yt) elif (choice == 7): print("Insert video directory, USE '\\\\' FOR BACKSLASH") dirVideo = VideoFileClip(str(input("Video location > "))) boomerang(dirVideo)
aefb0e87e60832dfe0c29440b9525e104c4c4478
[ "Python" ]
1
Python
hanseljulio/VideoEditor
b914e89c0c2f1a8a0ef82a9783d814be14dd45f9
3a8491bb6cdf384305b396277081e542443976d7
refs/heads/master
<file_sep>define([ window.pfinaljs.base_url + '/pfinaljs/plug/wangEditor/wangEditor.min.js', 'css!' + window.pfinaljs.base_url + '/pfinaljs/plug/wangEditor/wangEditor.min.css' ], function (E) { return function (el, callback) { let editor = new E(el) editor.create() if ($.isFunction(callback)) { callback(editor); } } });
a0caeaf8bef2ecf0b331ab3fdc91514776d6b758
[ "JavaScript" ]
1
JavaScript
pfinalclub/pfinal-js
03d93499d6481d23d0de8a36a4de4cc7ab610374
1365460c1be35ed4450d6b4b431d053fc262d8dc
refs/heads/master
<file_sep><?php namespace Ixudra\DateTime; class DateTimeServiceTest extends \PHPUnit_Framework_TestCase { protected static $dateTimeService; public static function setUpBeforeClass() { self::$dateTimeService = new DateTimeService(); } public static function tearDownAfterClass() { self::$dateTimeService = NULL; } /** * @covers DateTimeService::getWeekOFDate() */ public function testGetWeekOfDate() { $index = self::$dateTimeService->getWeekOfDate('2013-01-31'); $this->assertEquals( 5, $index ); } /** * @covers DateTimeService::getWeekOfDate() */ public function testGetWeekOfDate_returnsFirstWeekIfDateFallsInFirstWeek() { $index = self::$dateTimeService->getWeekOfDate('2013-01-05'); $this->assertEquals( 1, $index ); } /** * @covers DateTimeService::getDaysOfWeek() */ public function testGetDaysOfWeek() { $days = self::$dateTimeService->getDaysOfWeek(4, 2013); $this->assertCount( 7, $days ); $this->assertEquals( '2013-01-21', $days['monday'] ); $this->assertEquals( '2013-01-22', $days['tuesday'] ); $this->assertEquals( '2013-01-23', $days['wednesday'] ); $this->assertEquals( '2013-01-24', $days['thursday'] ); $this->assertEquals( '2013-01-25', $days['friday'] ); $this->assertEquals( '2013-01-26', $days['saturday'] ); $this->assertEquals( '2013-01-27', $days['sunday'] ); } /** * @covers DateTimeService::getDaysOfWeek() */ public function testGetDaysOfWeek_showsLastWeekOfAugust() { $days = self::$dateTimeService->getDaysOfWeek(35, 2013); $this->assertCount( 7, $days ); $this->assertEquals( '2013-08-26', $days['monday'] ); $this->assertEquals( '2013-08-27', $days['tuesday'] ); $this->assertEquals( '2013-08-28', $days['wednesday'] ); $this->assertEquals( '2013-08-29', $days['thursday'] ); $this->assertEquals( '2013-08-30', $days['friday'] ); $this->assertEquals( '2013-08-31', $days['saturday'] ); $this->assertEquals( '2013-09-01', $days['sunday'] ); } /** * @covers DateTimeService::getDaysOfWeek() */ public function testGetDaysOfWeek_showsLastWeekOfYearCorrectly() { $days = self::$dateTimeService->getDaysOfWeek(52, 2013); $this->assertCount( 7, $days ); $this->assertEquals( '2013-12-23', $days['monday'] ); $this->assertEquals( '2013-12-24', $days['tuesday'] ); $this->assertEquals( '2013-12-25', $days['wednesday'] ); $this->assertEquals( '2013-12-26', $days['thursday'] ); $this->assertEquals( '2013-12-27', $days['friday'] ); $this->assertEquals( '2013-12-28', $days['saturday'] ); $this->assertEquals( '2013-12-29', $days['sunday'] ); } /** * @covers DateTimeService::getDaysOfWeek() */ public function testGetDaysOfWeek_movesOnToNextYearIfWeekIsLargerThanFiftyTwo() { $days = self::$dateTimeService->getDaysOfWeek(55, 2013); $this->assertCount( 7, $days ); $this->assertEquals( '2014-01-13', $days['monday'] ); $this->assertEquals( '2014-01-14', $days['tuesday'] ); $this->assertEquals( '2014-01-15', $days['wednesday'] ); $this->assertEquals( '2014-01-16', $days['thursday'] ); $this->assertEquals( '2014-01-17', $days['friday'] ); $this->assertEquals( '2014-01-18', $days['saturday'] ); $this->assertEquals( '2014-01-19', $days['sunday'] ); } /** * @covers DateTimeService::getDaysOfWeek() */ public function testGetDaysOfWeek_returnsNullIfIndexIsSmallerThanOne() { $days = self::$dateTimeService->getDaysOfWeek(-4, 2013); $this->assertNull( $days ); } /** * @covers DateTimeService::getDaysOfWeek() */ public function testGetDaysOfWeek_returnsNullIfYearIsSmallerThanOne() { $days = self::$dateTimeService->getDaysOfWeek(4, -2013); $this->assertNull( $days ); } /** * @covers DateTimeService::getLastMondayBeforeDate() */ public function testGetLastMondayBeforeDate() { $date = self::$dateTimeService->getLastMondayBeforeDate('2013-05-25'); $this->assertEquals( '2013-05-20', $date ); } /** * @covers DateTimeService::getLastMondayBeforeDate() */ public function testGetLastMondayBeforeDate_returnsSameDateIfGivenDateIsMonday() { $date = self::$dateTimeService->getLastMondayBeforeDate('2013-05-20'); $this->assertEquals( '2013-05-20', $date ); } /** * @covers DateTimeService::getWeekDayOfDate() */ public function testGetWeekdayOfMessage() { $this->assertEquals( 'monday', self::$dateTimeService->getWeekDayOfDate('2013-08-12')); $this->assertEquals( 'tuesday', self::$dateTimeService->getWeekDayOfDate('2013-08-13')); $this->assertEquals( 'wednesday', self::$dateTimeService->getWeekDayOfDate('2013-08-14')); $this->assertEquals( 'thursday', self::$dateTimeService->getWeekDayOfDate('2013-08-15')); $this->assertEquals( 'friday', self::$dateTimeService->getWeekDayOfDate('2013-08-16')); $this->assertEquals( 'saturday', self::$dateTimeService->getWeekDayOfDate('2013-08-17')); $this->assertEquals( 'sunday', self::$dateTimeService->getWeekDayOfDate('2013-08-18')); } /** * @covers DateTimeService::convertTimeToThirtyMinuteTimestamp() */ public function testConvertTimeToThirtyMinuteTimestamp() { $this->assertEquals( '00:30', self::$dateTimeService->convertTimeToThirtyMinuteTimestamp('00:46')); $this->assertEquals( '15:30', self::$dateTimeService->convertTimeToThirtyMinuteTimestamp('15:30')); $this->assertEquals( '18:00', self::$dateTimeService->convertTimeToThirtyMinuteTimestamp('18:21')); $this->assertEquals( '00:00', self::$dateTimeService->convertTimeToThirtyMinuteTimestamp('00:00')); $this->assertEquals( '23:30', self::$dateTimeService->convertTimeToThirtyMinuteTimestamp('23:59')); $this->assertEquals( '21:30', self::$dateTimeService->convertTimeToThirtyMinuteTimestamp('21:31')); $this->assertEquals( '16:00', self::$dateTimeService->convertTimeToThirtyMinuteTimestamp('16:15')); } }<file_sep><?php namespace Ixudra\DateTime; use Illuminate\Support\ServiceProvider; class DateTimeServiceProvider extends ServiceProvider { /** * @var bool */ protected $defer = false; /** * @return void */ public function boot() { $this->package('ixudra/date-time'); } /** * @return void */ public function register() { $this->app['DateTime'] = $this->app->share( function($app) { return new DateTimeService(); } ); } /** * @return array */ public function provides() { return array('DateTime'); } } <file_sep><?php namespace Ixudra\DateTime; class DateTimeService { public function getWeekOfDate($date) { $firstDayOfYear = date('Y', strtotime($date)) .'-01-01'; $monday = $this->getLastMondayBeforeDate( $firstDayOfYear ); $index = 0; while( $date > $monday ) { ++$index; $monday = date('Y-m-d', strtotime('+7 days', strtotime($monday))); } return $index; } public function getDaysOfWeek($index, $year) { if( $index < 0 ) { return null; } if( $year < 0 ) { return null; } $firstDayOfYear = $year .'-01-01'; $monday = $this->getLastMondayBeforeDate( $firstDayOfYear ); for( $i = 1; $i < $index; ++$i ) { $monday = date('Y-m-d', strtotime('+7 days', strtotime($monday))); } return array( 'monday' => $monday, 'tuesday' => date('Y-m-d', strtotime('+1 days', strtotime($monday))), 'wednesday' => date('Y-m-d', strtotime('+2 days', strtotime($monday))), 'thursday' => date('Y-m-d', strtotime('+3 days', strtotime($monday))), 'friday' => date('Y-m-d', strtotime('+4 days', strtotime($monday))), 'saturday' => date('Y-m-d', strtotime('+5 days', strtotime($monday))), 'sunday' => date('Y-m-d', strtotime('+6 days', strtotime($monday))) ); } public function getWeekDayOfDate($date) { $days = array( 'Mon' => 'monday', 'Tue' => 'tuesday', 'Wed' => 'wednesday', 'Thu' => 'thursday', 'Fri' => 'friday', 'Sat' => 'saturday', 'Sun' => 'sunday' ); return $days[ date('D', strtotime($date) ) ]; } public function getLastMondayBeforeDate($date) { $monday = date('Y-m-d', strtotime('last monday', strtotime($date))); if( date('D', strtotime($date)) == 'Mon' ) { $monday = date('Y-m-d', strtotime('+7 days', strtotime($monday))); } return $monday; } public function convertTimeToThirtyMinuteTimestamp($time) { if( $time > '23:30' ) { return '23:30'; } $timestamp = '00:30'; while( $timestamp <= $time ) { $timestamp = date('H:i', strtotime('+30 minutes', strtotime($timestamp))); } return date('H:i', strtotime('-30 minutes', strtotime($timestamp))); } }<file_sep>Date-Time ============ Custom PHP date/time library for the Laravel 4 framework - developed by Ixudra. This package can be used by anyone at any given time, but keep in mind that it is optimized for my personal custom workflow. It may not suit your project perfectly and modifications may be in order.
a6b9f66e1f357781ab820e3f13528d9201a785b8
[ "Markdown", "PHP" ]
4
PHP
ixudra/date-time
50ef5a801224bda86b17d696767b08abf489dbc0
aa3309d85f73728625a1a90263e91d67566ead99
refs/heads/master
<file_sep>var tap = require('tap'); var pure = require('../index.js'); // api tap.ok(pure.getFile); tap.ok(pure.getFilePath); // assertions tap.match(pure.getFile('pure-min.css'), /pure\-button/, 'should load the file'); tap.match(pure.getFilePath('pure-min.css'), /pure\-min\.css/, 'should return file path'); tap.throws(pure.getFile, new Error('undefined does not exist'));
547a6fd7729f77966658b55584909ecdd0236c3a
[ "JavaScript" ]
1
JavaScript
chi50800/pure
3879b759de86329c52c32391f05bc97ae4fb40ab
d6c1f8379a18ecf893526b6ae1c8c5084f5bd3f1
refs/heads/master
<repo_name>r21ling/test<file_sep>/client/reducers/todos.js import { handleActions } from 'redux-actions' const initialState = [{ num: 0, name: 'default' }] export default handleActions({ 'add'(state, action) { return [{ num: state.reduce((maxId, todo) => Math.max(todo.num, maxId), -1) + 1 // name: action.payload.name }, ...state] }, 'subtract'(state, action) { state.shift() return [...state] }, 'test'(state, action) { return [{ num: state.reduce((maxId, todo) => Math.max(todo.num, maxId), -1) + 1, name: action.payload.name }, ...state] } }, initialState) <file_sep>/client/containers/app/app.js import React from 'react' import { IndexLink, Link } from 'react-router' const App = props => { let {children} = props return ( <div> <header> <Link to="/add">to add page</Link> {' '} <Link to="/subtract">to subtract page</Link> {' '} <IndexLink to="/"> Home </IndexLink> </header> {children} </div> ) } export default App<file_sep>/client/components/subtract.js import React from 'react'; import * as TodoActions from '../actions' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' const Subtract = props => { let {actions} = props return ( <div> <button onClick={()=>actions.subtract()}>subtracttttt</button> </div> ) } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(TodoActions, dispatch) } } export default connect(null,mapDispatchToProps)(Subtract); <file_sep>/readme.md ### 个人测试 ## just for testing <<<<<<< HEAD hello 666!!!aaa ======= hello 666!!!<file_sep>/client/components/add.js import React from 'react'; import * as TodoActions from '../actions' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import axios from 'axios' const Add = props => { let {actions} = props return ( <div> <button onClick={() => actions.test( timeout().then(json => { return { name: json.data[0].id } }) ) }>adddd</button> </div> ) } function timeout() { return new Promise((resolve, reject) => { axios.get('http://localhost:8000/api/comments') .then(resolve) }) } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(TodoActions, dispatch) } } export default connect(null, mapDispatchToProps)(Add);<file_sep>/client/index.js import { IndexRoute , Router, Route, browserHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import { Provider } from 'react-redux' import React from 'react' import ReactDOM from 'react-dom' import Home from "./containers/app/home" import App from "./containers/app/app" import Add from './components/add' import Subtract from './components/subtract' import configure from './store' const store = configure() const history = syncHistoryWithStore(browserHistory,store) ReactDOM.render( <Provider store={store}> <Router history={history}> <Route path="/" component={App}> <IndexRoute component={Home}/> <Route path="add" component={Add}/> <Route path="subtract" component={Subtract}/> </Route> </Router> </Provider>, document.getElementById('root') )<file_sep>/client/containers/app/home.js import React from 'react'; import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import * as TodoActions from '../../actions' import Add from "../../components/add" import Subtract from "../../components/subtract" const Home = props => { const { todos, actions } = props return ( <div> <h1>666</h1> {todos.map(todo => <p key={todo.num}>{todo.num}</p> )} <Add /> <Subtract /> </div> ) }; function mapStateToProps(state) { return { todos: state.todos } } // function mapDispatchToProps(dispatch) { // return { // actions: bindActionCreators(TodoActions, dispatch) // } // } export default connect( mapStateToProps )(Home)
a655085e684c0662176818c3a076728ea5ce28b3
[ "JavaScript", "Markdown" ]
7
JavaScript
r21ling/test
1fef7e6eab5dcf0003e69c898b7e29de982da62a
a7cf6f59709259b1904c32ec44b9020a67ae149a
refs/heads/master
<file_sep>package sync; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @author : renjiahui * @date : 2020/9/3 0:29 * @desc : 展示Lock的方法 */ public class LockExample { public static void main(String[] args) { Lock lock = new ReentrantLock(); //获取锁 lock.lock(); try { } catch (Exception e) { e.printStackTrace(); } finally { //释放锁 lock.unlock(); } //尝试获取锁 lock.tryLock(); try { //指定时间内拿不到锁就放弃 lock.tryLock(10, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } } <file_sep>package executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author : renjiahui * @date : 2020/11/8 22:02 * @desc : 带有缓存的线程池 * 这种线程池的弊端在于corePoolSize为Integer.MAX_VALUE,会造成OOM异常 */ public class CacheThreadPoolTest { public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < 1000; i++) { executorService.execute(new Task()); } } } <file_sep>package sync; /** * @author : renjiahui * @date : 2020/9/1 19:57 * @desc : 消失的请求,两个线程同时进行i++,最后结果会比预计的少 * * 结果比预计少的原因是: * count++,看上去只有一个操作,实际上包含了三个动作: * 1、读取count * 2、将count加1 * 3、将count的值写入到内存中 * * 这三个操作如果不按原子性执行的话,那么就会产生并发问题 */ public class DisappearRequest1 implements Runnable { static DisappearRequest1 instance = new DisappearRequest1(); static int i = 0; /** * 不使用并发手段的后果 * * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(instance); Thread t2 = new Thread(instance); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(i); } // public void run() { // for (int j = 0; j < 1000; j++) { // i++; // } // } /** * synchronized修饰方法 */ // public synchronized void run() { // for (int j = 0; j < 1000; j++) { // i++; // } // } public void run() { //同步代码块形式 synchronized (this) { for (int j = 0; j < 1000; j++) { i++; } } } } <file_sep>package executor; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * @author : renjiahui * @date : 2020/11/8 22:08 * @desc : 带有定时或周期的线程池 */ public class ScheduledThreadPoolTest { public static void main(String[] args) { ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10); //每隔5秒运行一次线程 scheduledExecutorService.schedule(new Task(), 5, TimeUnit.SECONDS); //刚开始1秒运行,之后每隔3秒运行一次 scheduledExecutorService.scheduleAtFixedRate(new Task(), 1, 3, TimeUnit.SECONDS); } } <file_sep>package sync; /** * @author : renjiahui * @date : 2020/9/2 22:07 * @desc : 同时访问同一个静态的synchronized和一个非静态的synchroinzed方法 --七种情况种的第6个 * 这是因为他们锁指定的锁对象不是同一个锁 */ public class SynchronizedStaticOrNormal8 implements Runnable { static SynchronizedStaticOrNormal8 instance = new SynchronizedStaticOrNormal8(); public void run() { String thread0 = "Thread-0"; if (Thread.currentThread().getName().equals(thread0)) { method1(); } else { method2(); } } public static synchronized void method1() { System.out.println("我是静态的加锁的方法1,我叫:" + Thread.currentThread().getName()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "运行结束"); } public synchronized void method2() { System.out.println("我是非静态的加锁的方法2,我叫:" + Thread.currentThread().getName()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "运行结束"); } public static void main(String[] args) { Thread t1 = new Thread(instance); Thread t2 = new Thread(instance); t1.start(); t2.start(); while (t1.isAlive() || t2.isAlive()) { } System.out.println("finished"); } } <file_sep>package sync; /** * @author : renjiahui * @date : 2020/9/1 20:09 * @desc : Synchronized对象锁,代码块形式 */ public class SynchronizedObjectCodeBlock2 implements Runnable{ static SynchronizedObjectCodeBlock2 instance = new SynchronizedObjectCodeBlock2(); /** * 定义两把锁对象,当使用两把不同的锁对象时,所得到的结果也是非常不相同的。 */ Object lock = new Object(); Object lock1 = new Object(); public void run() { //代码块形式的锁 synchronized (this) { System.out.println("我是对象锁的代码块形式。我叫" + Thread.currentThread().getName()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " 运行结束"); } /** * 使用的锁不同,返回的结果也不同 */ synchronized (lock) { System.out.println("我是lock。我叫" + Thread.currentThread().getName()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " lock部分运行结束"); } synchronized (lock1) { System.out.println("我是lock1。我叫" + Thread.currentThread().getName()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " lock1运行结束"); } } public static void main(String[] args) { Thread t1 = new Thread(instance); Thread t2 = new Thread(instance); t1.start(); t2.start(); while (t1.isAlive() || t2.isAlive()) { } System.out.println("finished"); } }
70e9258edaf37048cbada0864f2584992f72a85b
[ "Java" ]
6
Java
RenYuaaa/Concurrent_Demo
8c2aa78fcb85d255a694a3c8ab9e7e5ffe0d8b35
910b8e92945aec61c171ac7afd2f4c4b0c2f0382
refs/heads/master
<repo_name>Coinsence/coinsence-wallet<file_sep>/src/app/app.component.ts import { Component } from '@angular/core'; import { Platform, Events, ToastController } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { BackgroundMode } from '@ionic-native/background-mode'; import { EtherProvider } from '../providers/ether/ether'; import { TokenProvider } from '../providers/token/token'; import { NotificationProvider } from '../providers/notification/notification'; import { NetworkProvider } from '../providers/network/network'; //default tokens list import { defaultTokens } from '../utils/default-tokens'; @Component({ templateUrl: 'app.html' }) export class MyApp { rootPage: any; constructor( platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, backgroundMode: BackgroundMode, events: Events, etherProvider : EtherProvider, tokenProvider: TokenProvider, notificationProvider: NotificationProvider, networkProvider: NetworkProvider, public toastCtrl: ToastController ) { platform.ready().then(() => { if(platform.is('mobileweb') == false) { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. statusBar.styleDefault(); statusBar.styleLightContent(); splashScreen.hide(); backgroundMode.enable(); //check if app have permission to show notifications notificationProvider.checkPermission(); } // Check connectivity networkProvider.initializeNetworkEvents(); // Offline event events.subscribe('network:offline', () => { this.disconnectToast(); }); // Online event events.subscribe('network:online', () => { this.connectToast(); }); //if an imported, scanned or created wallet exist if(localStorage.getItem('isWallet') == 'true') { let provider = etherProvider.get(); let wallet = JSON.parse(localStorage.getItem('wallet')); let tokens = JSON.parse(localStorage.getItem('defaultTokens')); tokens.forEach(token => { tokenProvider.setTokenListener(wallet.signingKey.address, token, provider) }); this.rootPage = 'TabsPage'; } else { localStorage.setItem('defaultTokens', JSON.stringify(defaultTokens)); this.rootPage = 'LoginPage'; } }); } connectToast() { let toast = this.toastCtrl.create({ message: "You are online", duration: 2000, position: 'buttom', cssClass: 'success', }); toast.present(); } disconnectToast() { let toast = this.toastCtrl.create({ message: "You are offline", duration: 2000, position: 'buttom', cssClass: 'danger', }); toast.present(); } } <file_sep>/src/pages/import-wallet/import-wallet.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { ImportWalletPage } from './import-wallet'; @NgModule({ declarations: [ ImportWalletPage, ], imports: [ IonicPageModule.forChild(ImportWalletPage), ], }) export class ImportWalletPageModule {} <file_sep>/src/pages/home/home.ts import { Component } from '@angular/core'; import { IonicPage, NavController, ModalController, AlertController, ToastController } from 'ionic-angular'; import { EtherProvider } from '../../providers/ether/ether'; import { TokenProvider } from '../../providers/token/token'; import * as ColorHash from 'color-hash/dist/color-hash.js' @IonicPage() @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { // ether.js provider private provider: any; // wallet object public wallet: any; // list of tokens public tokens: Array<{ contractAddress: string, name: string, symbol: string, decimals: number }>; // list of tokens balances public tokensBalances: Array<number> = []; private colorHash; constructor( public navCtrl: NavController, public modalController: ModalController, private alertCtrl: AlertController, public toastCtrl: ToastController, private etherProvider: EtherProvider, private tokenProvider: TokenProvider ) { this.loadWallet(); } ionViewCanEnter(): boolean{ // can only enter this view if there is an existant wallet in localstorage if(localStorage.getItem("isWallet") == "true"){ return true; } else { return false; } } ionViewWillEnter() { console.log('ionViewWillEnter HomePage'); this.getProvider(); this.loadTokens(); this.colorHash = new ColorHash(); } /** * get ether.js provider */ private getProvider() { this.provider = this.etherProvider.get(); } /** * load wallet from localstorage */ private loadWallet() { this.wallet = JSON.parse(localStorage.getItem('wallet')); } /** * get list of tokens and load balances */ private async loadTokens() { this.tokens = JSON.parse(localStorage.getItem("defaultTokens")); await this.loadTokensBalances(); } private async loadTokensBalances() { for(let i=0; i<this.tokens.length; i++) { let tokenBalance = await this.tokenProvider.getBalance(this.wallet.signingKey.address, this.tokens[i].contractAddress, this.provider); this.tokensBalances[i] = parseInt(tokenBalance) / 10**this.tokens[i].decimals; } } doRefresh(refresher) { console.log('Begin async operation', refresher); setTimeout(async() => { await this.loadTokens(); console.log('Async operation has ended'); refresher.complete(); }, 2000); } /** * qr-scanner modal * @param fab any */ public scanOnclick(fab: any) { fab.close(); let scanQrModal = this.modalController.create('ScanQrPage'); scanQrModal.onDidDismiss(async(ethAddress) => { if(ethAddress != undefined) { //get contract address const tokenAddress = ethAddress.split(":").pop(); this.tokenProvider.getInfo(tokenAddress, this.provider).then(async(tokenInfo) => { console.log(tokenInfo); //update default tokens item let token = { contractAddress: tokenAddress, decimals: tokenInfo.decimals, name: tokenInfo.name, symbol: tokenInfo.symbol }; // add token to tokens list this.tokens.push(token); // save tokens list into localstorage localStorage.setItem("defaultTokens", JSON.stringify(this.tokens)); // load tokens await this.loadTokens(); //Create event listener for added token this.tokenProvider.setTokenListener(this.wallet.signingKey.address, token, this.provider); }, (err) => { this.permissionDeniedToast("Error"); }); } else { this.permissionDeniedToast("No address detected!"); } }) scanQrModal.present(); } /** * show permission denied toast * @param message toast message */ permissionDeniedToast(message: string) { let toast = this.toastCtrl.create({ message: message, duration: 3000, position: 'buttom', cssClass: 'danger', }); toast.present(); } /** * add token * @param fab any */ addTokenModal(fab: any) { fab.close(); // open add token modal let createWalletModal = this.modalController.create('AddTokenPage', { defaultTokens: this.tokens }, { showBackdrop: false, enableBackdropDismiss: false}); createWalletModal.onDidDismiss(async(addedToken) => { await this.loadTokens(); if(addedToken != undefined) { //Create event listener for added token this.tokenProvider.setTokenListener(this.wallet.signingKey.address, addedToken, this.provider); } }); createWalletModal.present(); } /** * show remove alert * @param e event * @param tokenIndex token index in tokens list */ public showRemoveAlert(e, tokenIndex: number) { e.preventDefault(); e.stopPropagation(); console.log("remove action triggered"); let alert = this.alertCtrl.create({ title: 'Confirm remove', message: 'Do you want to remove this token?', buttons: [ { text: 'Cancel', role: 'cancel', handler: () => { console.log('Cancel clicked'); } }, { text: 'Remove', handler: () => { this.removeToken(tokenIndex); } } ] }); alert.present(); } /** * remove token * @param tokenIndex token index in tokens list */ public async removeToken(tokenIndex: number) { this.tokens.splice(tokenIndex, 1); this.tokensBalances.splice(tokenIndex, 1); localStorage.setItem("defaultTokens", JSON.stringify(this.tokens)); await this.loadTokens(); } symbolBgColor(str: string) { let color = this.colorHash.hex(str); return color; } /** * @notice redirect to token details page * @param token token Object * @param balance token balance */ public showDetails(token: any, balance: number) { this.navCtrl.push('TokenDetailsPage', {token: token, tokenBalance: balance}); } /** * @notice redirect to token send page * @param token token object * @param balance token balance */ public sendTokenModal(e, token: any, balance: number) { e.preventDefault(); e.stopPropagation(); if(this.wallet.signingKey.privateKey != null) { this.navCtrl.push('TokenSendPage', { wallet: this.wallet, token: token, tokenBalance: balance }); } } } <file_sep>/src/providers/ethplorer/ethplorer.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { environment } from "../../environments/environment"; @Injectable() export class EthplorerProvider { constructor( public http: HttpClient ) { console.log('Hello EthplorerProvider Provider'); } public async getTokenInfo(tokenAddress: string) { let getUrl = `${environment.apiEthplorerMainnet.url}/getTokenInfo/${tokenAddress}?apiKey=${environment.apiEthplorerMainnet.apiKey}`; return this.http.get(getUrl).toPromise(); } public async getAddressInfo(address: string) { let getUrl = `${environment.apiEthplorerMainnet.url}/getAddressInfo/${address}?apiKey=${environment.apiEthplorerMainnet.apiKey}`; return this.http.get(getUrl).toPromise(); } public async getTransactionInfo(txHash: string) { let getUrl = `${environment.apiEthplorerMainnet.url}/getTxInfo/${txHash}?apiKey=${environment.apiEthplorerMainnet.apiKey}`; return this.http.get(getUrl).toPromise(); } public async getAddressTransactions(address: string) { let getUrl = `${environment.apiEthplorerMainnet.url}/getAddressTransactions/${address}?apiKey=${environment.apiEthplorerMainnet.apiKey}`; return this.http.get(getUrl).toPromise(); } } <file_sep>/src/providers/token/token.ts import { Injectable } from '@angular/core'; import { ethers } from 'ethers'; import { erc20Abi } from '../../utils/erc20-abi'; import { NotificationProvider } from '../notification/notification'; import { WalletProvider } from '../wallet/wallet'; @Injectable() export class TokenProvider { constructor( public notificationProvider: NotificationProvider, public walletProvider: WalletProvider ) { console.log('Hello TokenProvider Provider'); console.log(erc20Abi); } public estimateTokentransfer(contractAddress: string, decimals: number, provider: any, pk: string, to: string, value: number): Promise<any> { let _wallet = this.walletProvider.importWalletFromKey(pk); let _signer = this.walletProvider.getSigner(_wallet, provider); let tokenContract = new ethers.Contract(contractAddress, erc20Abi, provider); let contractWithSigner = tokenContract.connect(_signer); return new Promise((resolve, reject) => { let amount = ethers.utils.parseUnits(value.toString(), decimals); console.log(amount); contractWithSigner.estimate.transfer(to, amount).then((res) => { resolve(res); }, (err) => { console.log(err); reject(err); }); }); } public sendToken(contractAddress: string, decimals: number, provider: any, pk: string, to: string, value: number) : Promise<any> { let _wallet = this.walletProvider.importWalletFromKey(pk); let _signer = this.walletProvider.getSigner(_wallet, provider); let tokenContract = new ethers.Contract(contractAddress, erc20Abi, provider); let contractWithSigner = tokenContract.connect(_signer); return new Promise((resolve, reject) => { let amount = ethers.utils.parseUnits(value.toString(), decimals); console.log(amount); contractWithSigner.transfer(to, amount).then((res) => { resolve(res); }, (err) => { console.log(err); reject(err); }); }); } public getInfo(contractAddress: string, provider: any) : Promise<any> { let tokenContract = new ethers.Contract(contractAddress, erc20Abi, provider); return new Promise(async (resolve, reject) => { let result = { name: "", symbol: "", decimals: 18 }; try { result.name = await tokenContract.name(); result.symbol = await tokenContract.symbol(); result.decimals = await tokenContract.decimals(); resolve(result); } catch(e) { console.log(e); reject(e); } }); } public getBalance(walletAddress: string, contractAddress: string, provider: any) : Promise<any> { let tokenContract = new ethers.Contract(contractAddress, erc20Abi, provider); return new Promise((resolve, reject) => { tokenContract.balanceOf(walletAddress).then((res) => { resolve(res); }, (err) => { console.log(err); reject(err); }); }); } /** * Function to set listener on default tokens contracts * @param address wallet address * @param tokens Array of token object * @param provider ether provider */ public setTokenListener( address: string, token: any, provider: any ) { let contract = new ethers.Contract(token.contractAddress, erc20Abi, provider); //filter for Transfer event only let filter = contract.filters.Transfer(null, null); //check that there is no already a listener on that contract event contract.on(filter, (from, to, value) => { if(from == address) { let text = `Sent ${this.divideBalance(value, token.decimals).toString()} \n${token.name} to \n${to}`; let data = ''; this.notificationProvider.scheduleNotification(text, data); } if(to == address) { let text = `Received ${this.divideBalance(value, token.decimals).toString()} \n${token.name} from \n${from}`; let data = ''; this.notificationProvider.scheduleNotification(text, data); } }); } public divideBalance(balance: string, decimals: string): number { return parseInt(balance) / 10**parseInt(decimals); } } <file_sep>/src/pages/history/history.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ModalController } from 'ionic-angular'; import { EtherscanProvider } from '../../providers/etherscan/etherscan'; import { WalletProvider } from '../../providers/wallet/wallet'; import * as ColorHash from 'color-hash/dist/color-hash.js' @IonicPage() @Component({ selector: 'page-history', templateUrl: 'history.html', }) export class HistoryPage { public walletAddress: string; public txs: any; public page: number = 1; public limit: number = 10; private colorHash; constructor( public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, private etherscanProvider: EtherscanProvider, public walletProvider: WalletProvider ) { } ionViewWillEnter() { console.log('ionViewWillEnter HistoryPage'); this.init(); this.colorHash = new ColorHash(); } init() { const wallet = JSON.parse(localStorage.getItem("wallet")); this.walletAddress = wallet.signingKey.address; this.loadTransactionsHistory(); } async loadTransactionsHistory() { let tokenTxsLog = await this.etherscanProvider.getAllTokenTransfer(this.walletAddress, this.page, this.limit); this.txs = tokenTxsLog.result; } showDetail(tx: any) { let txDetailModal = this.modalCtrl.create('TransactionDetailPage', { tx: tx }); txDetailModal.onDidDismiss(() => { this.limit = 10; this.loadTransactionsHistory(); }); txDetailModal.present(); } doInfinite(infiniteScroll) { console.log("scroll down worked!"); setTimeout(() => { this.limit += 10; this.loadTransactionsHistory(); infiniteScroll.complete(); }, 500); } doRefresh(refresher) { console.log('Begin async operation', refresher); setTimeout(async() => { this.limit = 10; this.loadTransactionsHistory(); console.log('Async operation has ended'); refresher.complete(); }, 2000); } symbolBgColor(str: string) { let color = this.colorHash.hex(str); return color; } public divideBalance(balance: string, decimals: string): number { return parseInt(balance) / 10**parseInt(decimals); } } <file_sep>/src/pages/token-details/token-details.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { TokenDetailsPage } from './token-details'; @NgModule({ declarations: [ TokenDetailsPage, ], imports: [ IonicPageModule.forChild(TokenDetailsPage), ], }) export class TokenDetailsPageModule {} <file_sep>/src/providers/etherscan/etherscan.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { environment } from "../../environments/environment"; @Injectable() export class EtherscanProvider { constructor( public http: HttpClient ) { console.log('Hello EtherscanProvider Provider'); } //Don't know if this return also failed transactions public async getAllTokenTransfer(walletAddress: string, page: number, offset: number): Promise<{status: string, message: string, result: Array<Object>}> { let getUrl = `${environment.apiEtherscanRinkeby.url}?module=account&action=tokentx&address=${walletAddress}&sort=desc&page=${page}&offset=${offset}&apikey=${environment.apiEtherscanRinkeby.apiKey}`; return this.http.get(getUrl).toPromise() as Promise<{status: string, message: string, result: Array<Object>}>; } //Don't know if this return also failed transactions public async getContractTokenTransfer(walletAddress: string, contractAddress: string, page: number, offset: number): Promise<{status: string, message: string, result: Array<Object>}> { let getUrl = `${environment.apiEtherscanRinkeby.url}?module=account&action=tokentx&contractaddress=${contractAddress}&address=${walletAddress}&sort=desc&page=${page}&offset=${offset}&apikey=${environment.apiEtherscanRinkeby.apiKey}`; return this.http.get(getUrl).toPromise() as Promise<{status: string, message: string, result: Array<Object>}>; } public async getEtherBalance(walletAddress: string): Promise<{status: string, message: string, result: Array<Object>}> { let getUrl = `${environment.apiEtherscanRinkeby.url}?module=account&action=balance&address=${walletAddress}&tag=latest&apikey=${environment.apiEtherscanRinkeby.apiKey}`; return this.http.get(getUrl).toPromise() as Promise<{status: string, message: string, result: Array<Object>}>; } //Don't know if this return also failed transactions public async getTransactions(walletAddress: string, page: number, offset: number): Promise<{status: string, message: string, result: Array<Object>}> { let getUrl = `${environment.apiEtherscanRinkeby.url}?module=account&action=txlist&address=${walletAddress}&sort=desc&page=${page}&offset=${offset}&apikey=${environment.apiEtherscanRinkeby.apiKey}`; return this.http.get(getUrl).toPromise() as Promise<{status: string, message: string, result: Array<Object>}>; } } <file_sep>/src/providers/wallet/wallet.ts import { Injectable } from '@angular/core'; import { ethers } from 'ethers'; @Injectable() export class WalletProvider { constructor() { console.log('Hello WalletProvider Provider'); } public createWallet() { return ethers.Wallet.createRandom(); } public importWalletFromKey(privateKey: string) { return new ethers.Wallet(privateKey); } // not sure about this public watchWallet(address: string) { try { const walletAddress = ethers.utils.getAddress(address); return ({ address: walletAddress }); } catch (e) { return ({}); } } public getSigner(wallet: any, ethProvider: any) { const signer = wallet.connect(ethProvider); return signer; } public checkAddress(address: string) : boolean { try { ethers.utils.getAddress(address); return true; } catch (e) { return false; } } public checkSumAddress(address: string): string { return ethers.utils.getAddress(address); } } <file_sep>/src/pages/import-wallet/import-wallet.ts import { Component } from '@angular/core'; import { IonicPage, App, NavController, NavParams, ViewController } from 'ionic-angular'; import { EtherProvider } from '../../providers/ether/ether'; import { WalletProvider } from '../../providers/wallet/wallet'; @IonicPage() @Component({ selector: 'page-import-wallet', templateUrl: 'import-wallet.html', }) export class ImportWalletPage { public privateKey: string = ""; constructor( public appCtrl: App, public navCtrl: NavController, public navParams: NavParams, public viewController: ViewController, private etherProvider: EtherProvider, private walletProvider: WalletProvider ) { } ionViewDidLoad() { console.log('ionViewDidLoad ImportWalletPage'); } public importWallet() { let wallet = this.walletProvider.importWalletFromKey(this.privateKey); let provider = this.etherProvider.get(); let signer = this.walletProvider.getSigner(wallet, provider); localStorage.setItem("isWallet", "true"); localStorage.setItem("wallet", JSON.stringify(signer)); this.viewController.dismiss(); this.appCtrl.getRootNav().push('TabsPage'); } } <file_sep>/src/pages/token-send/token-send.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { TokenSendPage } from './token-send'; @NgModule({ declarations: [ TokenSendPage, ], imports: [ IonicPageModule.forChild(TokenSendPage), ], }) export class TokenSendPageModule {} <file_sep>/src/pages/token-details/token-details.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ModalController } from 'ionic-angular'; import { EtherProvider } from '../../providers/ether/ether'; import { TokenProvider } from '../../providers/token/token'; import { EtherscanProvider } from '../../providers/etherscan/etherscan'; import { WalletProvider } from "../../providers/wallet/wallet"; import * as ColorHash from 'color-hash/dist/color-hash.js' @IonicPage() @Component({ selector: 'page-token-details', templateUrl: 'token-details.html', }) export class TokenDetailsPage { public walletAddress: string; public token: { contractAddress: string, name: string, symbol: string, decimals: number }; public tokenBalance: number; public wallet: any; public txs: any; public page: number = 1; public limit: number = 10; private colorHash; constructor( public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public etherProvider: EtherProvider, public tokenProvider: TokenProvider, public etherscanProvider: EtherscanProvider, public walletProvider: WalletProvider ) { this.token = this.navParams.get('token'); this.wallet = JSON.parse(localStorage.getItem("wallet")); this.init(); this.colorHash = new ColorHash(); } ionViewWillEnter() { console.log('ionViewWillEnter TokenDetailsPage'); } init() { this.walletAddress = this.wallet.signingKey.address; this.loadBalance(); this.getTokenTransactions(); } private async loadBalance() { let tokenBalance = await this.tokenProvider.getBalance(this.wallet.signingKey.address, this.token.contractAddress, this.etherProvider.get()); this.tokenBalance = parseInt(tokenBalance) / 10**this.token.decimals; } private async getTokenTransactions() { let tokenTxsLog = await this.etherscanProvider.getContractTokenTransfer(this.wallet.signingKey.address, this.token.contractAddress, this.page, this.limit); this.txs = tokenTxsLog.result; console.log(this.txs); } doInfinite(infiniteScroll) { console.log("scroll down worked!"); setTimeout(() => { this.limit += 10; this.getTokenTransactions(); infiniteScroll.complete(); }, 500); } showDetail(tx: any) { let txDetailModal = this.modalCtrl.create('TransactionDetailPage', { tx: tx }); txDetailModal.onDidDismiss(() => { this.limit = 10; this.getTokenTransactions(); }); txDetailModal.present(); } symbolBgColor(str: string) { return this.colorHash.hex(str); } public divideBalance(balance: string, decimals: string): number { return parseInt(balance) / 10**parseInt(decimals); } doRefresh(refresher) { console.log('Begin async operation', refresher); setTimeout(async() => { await this.init(); console.log('Async operation has ended'); refresher.complete(); }, 2000); } } <file_sep>/src/pages/history/transaction-detail/transaction-detail.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular'; @IonicPage() @Component({ selector: 'page-transaction-detail', templateUrl: 'transaction-detail.html', }) export class TransactionDetailPage { public tx: any; constructor( public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController ) { this.tx = this.navParams.get('tx'); } ionViewDidLoad() { console.log('ionViewDidLoad TransactionDetailPage'); } public divideBalance(balance: string, decimals: string): number { return parseInt(balance) / 10**parseInt(decimals); } public closeModal() { this.viewCtrl.dismiss(); } } <file_sep>/README.md ![](docs/screenshots/logo.png) # Coinsence ERC20 mobile wallet ## Configuration Clone the repo and open the directory: ```sh git clone https://github.com/Coinsence/coinsence-wallet.git cd coinsence-wallet ``` Setup API's keys inside `src/environments/environment.ts` ```sh export const environment = { apiEtherscanRinkeby: { url: 'https://api-rinkeby.etherscan.io/api', apiKey: '' }, apiEthplorerMainnet: { url: 'https://api.ethplorer.io', apiKey: '' } } ``` ## Testing in a Browser > **Note:** This method should only be used for development purposes. When running Coinsence wallet in a normal browser environment, browser extensions and other malicious code might have access to internal data and private keys. For production use, see the latest official [releases](https://github.com/Coinsence/coinsence-wallet/releases). Ensure you have [Node](https://nodejs.org/) installed, then install and start Coinsence wallet: ```sh npm install npm run start ``` Visit [`localhost:8100`](http://localhost:8100/) to view the app. ## Testing on Real Devices It's recommended that all final testing be done on a real device – both to assess performance and to enable features that are unavailable to the emulator (e.g. a device camera). ### Android Follow the [Cordova Android Platform Guide](https://cordova.apache.org/docs/en/latest/guide/platforms/android/) to set up your development environment. When your developement enviroment is ready, run the `start:android` package script. ```sh npm run prepare:coinsence npm run start:android ``` ### iOS Follow the [Cordova iOS Platform Guide](https://cordova.apache.org/docs/en/latest/guide/platforms/ios/) to set up your development environment. When your developement enviroment is ready, run the `start:ios` package script. ```sh npm run prepare:coinsence npm run start:ios ``` ## Build Coinsence App APK The `final` commands build the production version of the app ### Android ```sh npm install npm run prepare:coinsence npm run final:android ``` ### iOS ```sh npm install npm run prepare:coinsence npm run final:ios ``` ## Build Coinsence App Bundle ### Android ```sh npm install npm run prepare:coinsence npm run build:android-bundle npm run sign:android-bundle ``` ## About Coinsence Wallet ### General ## License Coinsence Wallet is released under the MIT License. Please refer to the [LICENSE](https://github.com/Coinsence/coinsence-wallet/blob/master/LICENSE) file that accompanies this project for more information including complete terms and conditions. <file_sep>/src/providers/providers.module.ts import { NgModule } from "@angular/core"; import { EtherProvider } from './ether/ether'; import { WalletProvider } from './wallet/wallet'; import { EtherscanProvider } from './etherscan/etherscan'; import { TokenProvider } from './token/token'; import { EthplorerProvider } from './ethplorer/ethplorer'; import { NotificationProvider } from './notification/notification'; import { NetworkProvider } from './network/network'; @NgModule({ providers: [ EtherProvider, WalletProvider, EtherscanProvider, TokenProvider, EthplorerProvider, NotificationProvider, NetworkProvider ] }) export class ProvidersModule { } <file_sep>/src/pages/add-token/add-token.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { AddTokenPage } from './add-token'; @NgModule({ declarations: [ AddTokenPage, ], imports: [ IonicPageModule.forChild(AddTokenPage), ], }) export class AddTokenPageModule {} <file_sep>/src/pages/settings/settings.ts import { Component } from '@angular/core'; import { IonicPage, App, ModalController, AlertController } from 'ionic-angular'; import { EtherProvider } from '../../providers/ether/ether'; //default tokens list import { defaultTokens } from '../../utils/default-tokens'; @IonicPage() @Component({ selector: 'page-settings', templateUrl: 'settings.html', }) export class SettingsPage { // wallet object public wallet: any; // ether.js provider private provider: any; public etherBalance: number; constructor( public appCtrl: App, public modalController: ModalController, public alertCtrl: AlertController, private etherProvider: EtherProvider ) { this.loadWallet(); } ionViewDidLoad() { console.log('ionViewDidLoad SettingsPage'); } ionViewWillEnter() { console.log('ionViewWillEnter HomePage'); this.getProvider(); this.getEtherBalance(); } /** * load wallet from localstorage */ private loadWallet() { this.wallet = JSON.parse(localStorage.getItem('wallet')); } public aboutModal() { let aboutUsModal = this.modalController.create('AboutUsPage'); aboutUsModal.present(); } public privacyPolicyModal() { let privacyPolicyModal = this.modalController.create('PrivacyPolicyPage'); privacyPolicyModal.present(); } public logout() { //reset data localStorage.setItem("isWallet", "false"); localStorage.setItem("wallet", ""); localStorage.setItem("defaultTokens", JSON.stringify(defaultTokens)); this.appCtrl.getRootNav().setRoot('LoginPage'); } /** * get ether.js provider */ private getProvider() { this.provider = this.etherProvider.get(); } /** * get ETH balance */ private async getEtherBalance() { let weiBalance = await this.provider.getBalance(this.wallet.signingKey.address); this.etherBalance = parseFloat(this.etherProvider.weiToEther(weiBalance)); console.log(this.etherBalance); } presentEthBalance() { let alert = this.alertCtrl.create({ title: 'Balance', subTitle: `${this.etherBalance}`, buttons: ['Dismiss'] }); alert.present(); } } <file_sep>/src/providers/ether/ether.ts import { Injectable } from '@angular/core'; import { ethers } from 'ethers'; @Injectable() export class EtherProvider { public etherProvider: any; constructor() { this.etherProvider = ethers.getDefaultProvider('rinkeby'); } public get() { return this.etherProvider; } public weiToEther(wei) : string { return ethers.utils.formatEther(wei); } } <file_sep>/src/providers/notification/notification.ts import { Injectable } from '@angular/core'; import { LocalNotifications } from '@ionic-native/local-notifications'; import { Badge } from '@ionic-native/badge'; @Injectable() export class NotificationProvider { constructor( private localNotifications: LocalNotifications, private badge: Badge ) { console.log('Hello NotificationProvider Provider'); this.badge.set(0); } public checkPermission() { this.localNotifications.hasPermission().then((hasPermission) => { if(!hasPermission) { this.localNotifications.requestPermission(); } }); } public scheduleNotification( text: string, data: string ) { this.localNotifications.schedule({ id: 1, text: text, data: data, led: true, launch: true, foreground: true }); this.badge.increase(1); this.localNotifications.on('click').subscribe(notification => { console.log("notification clicked!"); this.badge.decrease(1); }); this.localNotifications.on('clear').subscribe(notification => { console.log("notification cleared!"); this.badge.decrease(1); }); } } <file_sep>/src/pages/add-token/add-token.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ViewController, LoadingController } from 'ionic-angular'; import { EtherProvider } from '../../providers/ether/ether'; import { TokenProvider } from '../../providers/token/token'; @IonicPage() @Component({ selector: 'page-add-token', templateUrl: 'add-token.html', }) export class AddTokenPage { public tokens: Array<any>; public token = { contractAddress: "", decimals: "", name: "", symbol: "", exist: false }; public isValidTokenContract: boolean = false; constructor( public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, public loadingCtrl: LoadingController, public etherProvider: EtherProvider, public tokenProvider: TokenProvider ) { this.tokens = this.navParams.get('defaultTokens'); } ionViewDidLoad() { console.log('ionViewDidLoad AddTokenPage'); } onContractInput($event) { let loading = this.loadingCtrl.create({ content: 'Loading token info...' }); loading.present(); setTimeout(async() => { //get token info this.tokenProvider.getInfo($event.target.value, this.etherProvider.get()).then((tokenInfo) => { console.log(tokenInfo); this.isValidTokenContract = true; //update default tokens item this.token.contractAddress = $event.target.value, this.token.decimals = tokenInfo.decimals, this.token.name = tokenInfo.name, this.token.symbol = tokenInfo.symbol, this.token.exist = true }, (err) => { console.log(err); alert("Error"); }); loading.dismiss(); }, 1000); } public addToken() { this.tokens.push(this.token); localStorage.setItem("defaultTokens", JSON.stringify(this.tokens)); this.viewCtrl.dismiss(this.token); } public cancel() { this.viewCtrl.dismiss(); } } <file_sep>/src/pages/token-send/token-send.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ModalController, ToastController } from 'ionic-angular'; import { EtherProvider } from '../../providers/ether/ether'; import { WalletProvider } from '../../providers/wallet/wallet'; import { TokenProvider } from '../../providers/token/token'; @IonicPage() @Component({ selector: 'page-token-send', templateUrl: 'token-send.html', }) export class TokenSendPage { public token: { contractAddress: string, name: string, symbol: string, decimals: number }; public tokenBalance: number; public wallet: any; public to: string; public value: number; constructor( public navCtrl: NavController, public navParams: NavParams, public toastCtrl: ToastController, private modalController: ModalController, public etherProvider: EtherProvider, public walletProvider: WalletProvider, public tokenProvider: TokenProvider ) { this.token = this.navParams.get('token'); this.tokenBalance = this.navParams.get('tokenBalance'); this.wallet = this.navParams.get('wallet'); this.value = 0; } ionViewDidLoad() { console.log('ionViewDidLoad TokenSendPage'); } ionViewCanEnter(): boolean{ // can only enter this view if there is an existant wallet in localstorage if(this.wallet.signingKey.privateKey != null){ return true; } else { return false; } } /** * open qr-scanner modal */ scanOnclick(e) { e.preventDefault(); let scanQrModal = this.modalController.create('ScanQrPage'); scanQrModal.onDidDismiss(ethAddress => { if(ethAddress != undefined) { //get ethereum address const address = ethAddress.split(":").pop(); // check if address is valid if(this.walletProvider.checkAddress(address)) { this.to = address; } else { this.errorToast('Invalid address!'); } } else { this.errorToast('No address detected!'); } }) scanQrModal.present(); } /** * show denied permission toast * @param message toast message to show */ errorToast(message: string) { let toast = this.toastCtrl.create({ message: message, duration: 3000, position: 'buttom', cssClass: 'danger', }); toast.present(); } public async send() { /* let estimation = await this.tokenProvider.estimateTokentransfer(this.token.contractAddress, this.token.decimals, this.etherProvider.get(), this.wallet.signingKey.privateKey, this.to, this.value); console.log(estimation.toNumber()); */ if(this.value > this.tokenBalance) { this.errorToast(`Insufficient ${this.token.symbol} balance`); } else { this.tokenProvider.sendToken(this.token.contractAddress, this.token.decimals, this.etherProvider.get(), this.wallet.signingKey.privateKey, this.to, this.value).then((tx) => { console.log(tx); this.cancel(); }); } } public cancel() { this.navCtrl.pop(); } } <file_sep>/src/pages/scan-qr/scan-qr.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular'; import { QRScanner, QRScannerStatus } from "@ionic-native/qr-scanner"; @IonicPage() @Component({ selector: 'page-scan-qr', templateUrl: 'scan-qr.html', }) export class ScanQrPage { private isBackMode: boolean = true; private isFlashLightOn: boolean = false; private scanSub: any; constructor( public navCtrl: NavController, public navParams: NavParams, public viewController: ViewController, public qrScanner: QRScanner ) { } ionViewWillEnter(){ // request the permission this.qrScanner.prepare() .then((status: QRScannerStatus) => { if (status.authorized) { // camera permission was granted console.log('Camera Permission Given'); //show camera this.showCamera(); // start scanning this.scanSub = this.qrScanner.scan().subscribe((text: string) => { console.log(text); this.scanSub.unsubscribe(); // stop scanning this.viewController.dismiss(text); }); // show camera preview this.qrScanner.show(); // wait for user to scan something, then the observable callback will be called } // no idea if this work // as denied permission return an exception not status.denied else if (status.denied) { // camera permission was permanently denied // you must use QRScanner.openSettings() method to guide the user to the settings page // then they can grant the permission from there console.log('Camera permission denied'); this.closeModal(); } else { // permission was denied, but not permanently. You can ask for permission again at a later time. console.log('Permission denied for this runtime.'); this.closeModal(); } }) .catch((e: any) => { this.closeModal(); console.log('Error is', e); }); } closeModal() { this.viewController.dismiss(); } toggleFlashLight(){ /** Default isFlashLightOn is false , * enable it if false **/ this.isFlashLightOn = !this.isFlashLightOn; if(this.isFlashLightOn){ this.qrScanner.enableLight(); } else{ this.qrScanner.disableLight(); } } toggleCamera(){ /** Toggle Camera , Default is isBackMode is true , toggle * to false to enable front camera and vice versa. * * @type {boolean} */ this.isBackMode = !this.isBackMode; if(this.isBackMode){ this.qrScanner.useFrontCamera(); } else{ this.qrScanner.useBackCamera(); } } ionViewWillLeave(){ this.qrScanner.hide(); // hide camera preview this.hideCamera(); } showCamera() { (window.document.querySelector('ion-app') as HTMLElement).classList.add('cameraView'); } hideCamera() { (window.document.querySelector('ion-app') as HTMLElement).classList.remove('cameraView'); } } <file_sep>/src/pages/login/login.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ModalController, ToastController } from 'ionic-angular'; import { WalletProvider } from '../../providers/wallet/wallet'; @IonicPage() @Component({ selector: 'page-login', templateUrl: 'login.html', }) export class LoginPage { constructor( public navCtrl: NavController, public navParams: NavParams, public toastCtrl: ToastController, private modalController: ModalController, private walletProvider: WalletProvider ) { } ionViewDidLoad() { console.log('ionViewDidLoad LoginPage'); } /** * open qr-scanner modal */ scanOnclick() { let scanQrModal = this.modalController.create('ScanQrPage'); scanQrModal.onDidDismiss(ethAddress => { if(ethAddress != undefined) { //get ethereum address const address = ethAddress.split(":").pop(); // check if address is valid if(this.walletProvider.checkAddress(address)) { const wallet = { signingKey: { address: address, privateKey: null } }; //save wallet localStorage.setItem("wallet", JSON.stringify(wallet)); localStorage.setItem("isWallet", "true"); this.navCtrl.push('TabsPage'); } else { this.permissionDeniedToast('Invalid address!'); } } else { this.permissionDeniedToast('No address detected!'); } }) scanQrModal.present(); } /** * show denied permission toast * @param message toast message to show */ permissionDeniedToast(message: string) { let toast = this.toastCtrl.create({ message: message, duration: 3000, position: 'buttom', cssClass: 'danger', }); toast.present(); } /** * open create wallet modal */ createWalletModal() { let wallet = this.walletProvider.createWallet(); let createWalletModal = this.modalController.create('CreateWalletPage', { wallet: wallet }, { showBackdrop: true, enableBackdropDismiss: false}); createWalletModal.present(); } importWalletModal() { let importWalletModal = this.modalController.create('ImportWalletPage', {}, { showBackdrop: true, enableBackdropDismiss: false }); importWalletModal.present(); } } <file_sep>/src/pages/create-wallet/create-wallet.ts import { Component } from '@angular/core'; import { IonicPage, App, NavParams, ViewController } from 'ionic-angular'; import { EtherProvider } from '../../providers/ether/ether'; import { WalletProvider } from '../../providers/wallet/wallet'; @IonicPage() @Component({ selector: 'page-create-wallet', templateUrl: 'create-wallet.html', }) export class CreateWalletPage { public wallet: any; constructor( public appCtrl: App, public navParams: NavParams, public viewController: ViewController, private etherProvider: EtherProvider, private walletProvider: WalletProvider ) { this.wallet = this.navParams.get('wallet'); } ionViewDidLoad() { console.log('ionViewDidLoad CreateWalletPage'); } public confirm() { const provider = this.etherProvider.get(); const signer = this.walletProvider.getSigner(this.wallet, provider); localStorage.setItem("isWallet", "true"); localStorage.setItem("wallet", JSON.stringify(signer)); this.viewController.dismiss(); this.appCtrl.getRootNav().push('TabsPage'); } }
943fe150558d70ceb798e733dd03daf32bbf8a63
[ "Markdown", "TypeScript" ]
24
TypeScript
Coinsence/coinsence-wallet
19768fd16b32f9102f75fbec9c9c58fc66a3cc3d
5bd66bcf852664b704aa9e1f1ea2bd59f0c6a52f
refs/heads/master
<file_sep><?php /** * Adds address fields to an object that can be geocoded and plotted on an interactive Google Map. * UI of Google Map can be defined in the CMS (width, height, map type, controls, etc.). * * Features: * - $GoogleMapAddressMap: Renders a dynamic Google Map with a single marker for the given address * - $GoogleRoutingLink: Renders a link with routing information, with the given address as target * * --- * * This Extension can be added to SiteTree (e.g. SiteTree, Page or any custom Page) * adding the follwoing lines to mysite/_config.php: * * Object::add_extension('Object', 'GoogleMapsAddressable'); * Object::add_extension('Object', 'Geocodable'); * * --- * * You can use the following variables in your templates: * * $GoogleMapsAddressMap * -> Renders a dynamic JavaScript Google Map, with controls as set up in the CMS * (using template GoogleMapsAddressMap.ss) * * $GoogleRoutingLink * -> Returns a link to Google Maps Routing service, with the given address set as target * * $AddressIsSet * -> Returns true if any of the address fields is set (Address, Suburb, State or Postcode) * You can use in an <% if %> clause * * --- * * This extensions also integrates with the {@link Geocoding} extension to * save co-ordinates on object write. * * @package silverstripe-addressable */ class GoogleMapsAddressable extends Addressable { public function extraStatics() { $db = parent::extraStatics(); $db = array('db' => array_merge( $db['db'], array( 'ShowGoogleMap' => 'Boolean', 'ShowRoutingLink' => 'Boolean', 'MapWidth' => 'Int', 'MapHeight' => 'Int', 'MapZoom' => 'Int', 'MapPanControl' => 'Boolean', 'MapZoomControl' => 'Boolean', 'MapZoomStyle' => "Enum('SMALL, LARGE, DEFAULT', 'DEFAULT')", 'MapTypeControl' => 'Boolean', 'MapTypeStyle' => "Enum('HORIZONTAL_BAR, DROPDOWN_MENU, DEFAULT', 'DEFAULT')", 'MapTypeId' => "Enum('HYBRID, ROADMAP, SATELLITE, TERRAIN', 'HYBRID')", 'MapScaleControl' => 'Boolean', 'MapStreetViewControl' => 'Boolean', 'MapOverviewMapControl' => 'Boolean' ) )); return $db; } public function populateDefaults() { $this->owner->ShowGoogleMap = 1; $this->owner->ShowRoutingLink = 1; $this->owner->MapWidth = 480; $this->owner->MapHeight = 320; $this->owner->MapZoom = 13; $this->owner->MapPanControl = 0; $this->owner->MapZoomControl = 1; $this->owner->MapZoomStyle = 'DEFAULT'; $this->owner->MapTypeControl = 1; $this->owner->MapTypeStyle = 'DEFAULT'; $this->owner->MapTypeId = 'HYBRID'; $this->owner->MapScaleControl = 0; $this->owner->MapStreetViewControl = 0; $this->owner->MapOverviewMapControl = 0; } /** * @return array */ protected function getAddressFields() { $fields = parent::getAddressFields(); // Add Map Setup $fields[] = new HeaderField('MapSetupHeader', _t('GoogleMapsAddressable.MAPSETUPHEADER', 'Map Setup')); $fields[] = new CheckboxField('ShowGoogleMap', _t('GoogleMapsAddressable.SHOWGOOGLEMAP', 'Show Google Map')); $fields[] = new CheckboxField('ShowRoutingLink', _t('GoogleMapsAddressable.SHOWROUTINGLINK', 'Show Routing Link')); $fields[] = new NumericField('MapWidth', _t('GoogleMapsAddressable.MAPWIDTH', 'Map width')); $fields[] = new NumericField('MapHeight', _t('GoogleMapsAddressable.MAPHEIGHT', 'Map height')); $fields[] = new NumericField('MapZoom', _t('GoogleMapsAddressable.MAPZOOM', 'Zoom Factor of Map (1 = worldview - 21 = street view)')); // Add Dynamic Map Setup $fields[] = new HeaderField('DynamicMapSetupHeader', _t('GoogleMapsAddressable.DYNAMICMAPSETUPHEADER', 'Dynamic Map Setup (Javascript Google Map)')); $fields[] = new CheckboxField('MapPanControl', _t('GoogleMapsAddressable.MAPPANCONTROL', 'Show Pan Control')); $fields[] = new CheckboxField('MapZoomControl', _t('GoogleMapsAddressable.MAPZOOMCONTROL', 'Show Zoom Control')); $zoomTypes = singleton($this->owner->ClassName)->dbObject('MapZoomStyle')->enumValues(); $fields[] = new DropdownField('MapZoomStyle', _t('GoogleMapsAddressable.MAPZOOMSTYLE', 'Zoom Control Styling'), $zoomTypes); $fields[] = new CheckboxField('MapTypeControl', _t('GoogleMapsAddressable.MAPTYPECONTROL', 'Show Map Type Control')); $typeTypes = singleton($this->owner->ClassName)->dbObject('MapTypeStyle')->enumValues(); $fields[] = new DropdownField('MapTypeStyle', _t('GoogleMapsAddressable.MAPTYPESTYLE', 'Map Type Control Styling'), $typeTypes); $typeIds = singleton($this->owner->ClassName)->dbObject('MapTypeId')->enumValues(); $fields[] = new DropdownField('MapTypeId', _t('GoogleMapsAddressable.MAPTYPEID', 'Map Type'), $typeIds); $fields[] = new CheckboxField('MapScaleControl', _t('GoogleMapsAddressable.MAPSCALECONTROL', 'Show Scale Control')); $fields[] = new CheckboxField('MapStreetViewControl', _t('GoogleMapsAddressable.MAPSTREETVIEWCONTROL', 'Show StreetView Control')); $fields[] = new CheckboxField('MapOverviewMapControl', _t('GoogleMapsAddressable.MAPOVERVIEWMAPCONTROL', 'Show Overview Map Control')); return $fields; } /** * @return bool */ public function AddressIsSet() { return ( $this->owner->Address || $this->owner->Suburb || $this->owner->State || $this->owner->Postcode ); } /** * Returns a dynamic google map with a marker for the given address * Controls and map setup is set using the CMS * * The Map is rendered using the GoogleMapsAddressMap.ss template * You can create a custom template in your themes folder: themes/MYTHEME/templates/GoogleMapsAddressMap.ss * * @return string */ public function GoogleMapsAddressMap() { $data = $this->owner->customise(array( 'AddressEncoded' => rawurlencode($this->getFullAddress()) )); return $data->renderWith('GoogleMapsAddressMap'); } /** * Returns a link to googles Routing Service, with the address as target address * * @return String */ public function GoogleRoutingLink() { return "http://maps.google.com/maps?daddr=".rawurlencode($this->owner->getFullAddress()); } }<file_sep><?php /** * English (US) language pack * @subpackage i18n */ global $lang; /** * Class Addressable */ $lang['en_US']['Addressable']['TABTITLE'] = 'Address Map'; $lang['en_US']['Addressable']['COMPANYHEADER'] = 'Company Name'; $lang['en_US']['Addressable']['COMPANYNAME'] = 'Company Name'; $lang['en_US']['Addressable']['ADDRESSHEADER'] = 'Address'; $lang['en_US']['Addressable']['ADDRESS'] = 'Street address'; $lang['en_US']['Addressable']['SUBURB'] = 'Suburb'; $lang['en_US']['Addressable']['STATE'] = 'State'; $lang['en_US']['Addressable']['POSTCODE'] = 'Postcode'; $lang['en_US']['Addressable']['COUNTRY'] = 'Country'; /** * Class GoogleMapsAddressable */ $lang['en_US']['GoogleMapsAddressable']['SHOWROUTINGLINK'] = 'Show Routing Link'; $lang['en_US']['GoogleMapsAddressable']['MAPSETUPHEADER'] = 'Map Setup'; $lang['en_US']['GoogleMapsAddressable']['SHOWGOOGLEMAP'] = 'Show Google Map'; $lang['en_US']['GoogleMapsAddressable']['MAPWIDTH'] = 'Map Width'; $lang['en_US']['GoogleMapsAddressable']['MAPHEIGHT'] = 'Map height'; $lang['en_US']['GoogleMapsAddressable']['DYNAMICMAPSETUPHEADER'] = 'Dynamic Map Setup (Javascript Google Map)'; $lang['en_US']['GoogleMapsAddressable']['MAPZOOM'] = 'Zoom Factor of Map (1 = worldview - 21 = street view)'; $lang['en_US']['GoogleMapsAddressable']['MAPPANCONTROL'] = 'Show Pan Control'; $lang['en_US']['GoogleMapsAddressable']['MAPZOOMCONTROL'] = 'Show Zoom Control'; $lang['en_US']['GoogleMapsAddressable']['MAPZOOMSTYLE'] = 'Zoom Control Styling'; $lang['en_US']['GoogleMapsAddressable']['MAPTYPECONTROL'] = 'Show Map Type Control'; $lang['en_US']['GoogleMapsAddressable']['MAPTYPESTYLE'] = 'Map Type Control Styling'; $lang['en_US']['GoogleMapsAddressable']['MAPTYPEID'] = 'Map Type'; $lang['en_US']['GoogleMapsAddressable']['MAPSCALECONTROL'] = 'Show Scale Control'; $lang['en_US']['GoogleMapsAddressable']['MAPSTREETVIEWCONTROL'] = 'Show StreetView Control'; $lang['en_US']['GoogleMapsAddressable']['MAPOVERVIEWMAPCONTROL'] = 'Show Overview Map Control'; $lang['en_US']['GoogleMapsAddressMap.ss']['CALCULATEROUTE'] = 'Get routing information'; <file_sep><?php /** * German (Germany) language pack * @subpackage i18n */ global $lang; /** * Class Addressable */ $lang['de_DE']['Addressable']['TABTITLE'] = 'Google Map'; $lang['de_DE']['Addressable']['COMPANYHEADER'] = 'Firmenname'; $lang['de_DE']['Addressable']['COMPANYNAME'] = 'Firma'; $lang['de_DE']['Addressable']['ADDRESSHEADER'] = 'Adresse'; $lang['de_DE']['Addressable']['ADDRESS'] = 'Straße und Hausnummer'; $lang['de_DE']['Addressable']['SUBURB'] = 'Ort'; $lang['de_DE']['Addressable']['STATE'] = 'Bundeland'; $lang['de_DE']['Addressable']['POSTCODE'] = 'Postleitzahl'; $lang['de_DE']['Addressable']['COUNTRY'] = 'Land'; /** * Class GoogleMapsAddressable */ $lang['de_DE']['GoogleMapsAddressable']['SHOWROUTINGLINK'] = 'Link mit Anfahrtsbeschreibung anzeigen'; $lang['de_DE']['GoogleMapsAddressable']['MAPSETUPHEADER'] = 'Google Map Setup'; $lang['de_DE']['GoogleMapsAddressable']['SHOWGOOGLEMAP'] = 'Google Map in Website anzeigen'; $lang['de_DE']['GoogleMapsAddressable']['MAPWIDTH'] = 'Breite'; $lang['de_DE']['GoogleMapsAddressable']['MAPHEIGHT'] = 'Höhe'; $lang['de_DE']['GoogleMapsAddressable']['DYNAMICMAPSETUPHEADER'] = 'Setup dynamische Google Map (Javascript Google Map)'; $lang['de_DE']['GoogleMapsAddressable']['MAPZOOM'] = 'Vergrößerung (1 = Weltansicht - 21 = Straßenansicht)'; $lang['de_DE']['GoogleMapsAddressable']['MAPPANCONTROL'] = 'Regler zum Verschieben der Karte anzeigen'; $lang['de_DE']['GoogleMapsAddressable']['MAPZOOMCONTROL'] = 'Zoom Regler anzeigen'; $lang['de_DE']['GoogleMapsAddressable']['MAPZOOMSTYLE'] = 'Stil des Zoom Reglers'; $lang['de_DE']['GoogleMapsAddressable']['MAPTYPECONTROL'] = 'Kartenauswahl anzeigen'; $lang['de_DE']['GoogleMapsAddressable']['MAPTYPESTYLE'] = 'Stil der Kartenauswahl'; $lang['de_DE']['GoogleMapsAddressable']['MAPTYPEID'] = 'Standard Karte'; $lang['de_DE']['GoogleMapsAddressable']['MAPSCALECONTROL'] = 'Maßstab anzeigen'; $lang['de_DE']['GoogleMapsAddressable']['MAPSTREETVIEWCONTROL'] = 'Regler für StreetView anzeigen'; $lang['de_DE']['GoogleMapsAddressable']['MAPOVERVIEWMAPCONTROL'] = 'Übersichtskarte anzeigen'; $lang['de_DE']['GoogleMapsAddressMap.ss']['CALCULATEROUTE'] = 'Anfahrtsbeschreibung berechnen lassen'; <file_sep>SilverStripe Addressable Module =============================== The Addressable module adds address fields to an object, and also has support for automatic geocoding. Maintainer Contact ------------------ * <NAME> (<<EMAIL>>) Requirements ------------ * SilverStripe 2.4+ Installation ------------ Extract the contents of the zip-file, rename the folder to `addressable` and copy it to your website root. Add the object extensions to your `mysite/_config.php` as needed (see Quick Usage Overview below). Then run a `mysite.com/dev/build?flush=1` to rebuild the database. Documentation ------------- Quick Usage Overview: Adressable Extension ----------------------------------------- In order to add simple address fields (address, suburb, city, postcode and country) to an object, simply apply to `Addressable` extension: Object::add_extension('Object', 'Addressable'); In order to then render the full address into a template, you can use either `$FullAddress` to return a simple string, or `$FullAddressHTML` to render the address into a HTML `<address>` tag. You can define a global set of allowed states or countries using `Addressable::set_allowed_states()` and `::set_allowed_countries()` respectively. These can also be set per-instance using `setAllowedStates()` and `setAllowedCountries()`. If a single string is provided as a value, then this will be set as the field for all new objects and the user will not be presented with an input field. If the value is an array, the user will be presented with a dropdown field. To add automatic geocoding to an `Addressable` object when the address is changed, simple apply the `Geocodable` extension: Object::add_extension('Object', 'Geocodable'); This will then use the Google Maps API to translate the address into a latitude and longitude on save, and save it into the `Lat` and `Lng` fields. Quick Usage Overview: GoogleMapsAdressable Extension --------------------------------------------------- GoogleMapsAddressable adds the ability to render a dynamic Google Maps map with a single marker for the given address on an object. You can setup the UI of the Google map in the CMS (width, height, map type, controls, etc.) It extends the `Addressable` extension, so you can as well use all the functionality described above. Simply apply the `GoogleMapsAddressable` and `Geocodable` extension to your Object, by adding the following line to your `mysite/_config.php`: Object::add_extension('Object', 'GoogleMapsAddressable'); Object::add_extension('Object', 'Geocodable'); Then run a `mysite.com/dev/build?flush=1` to rebuild the database. Now you can add the Google map by adding `$GoogleMapsAddressMap` to your template. `GoogleMapsAddressable` uses the `GoogleMapsAddressMap.ss` template. This template is a starting point with all variables and functions available. You can customize the code, by creating your own template in your themes folder: `themes/MYTHEME/templates/GoogleMapsAddressMap.ss`
7e11bcffca753bc17efe19fcb507c1416aaa6e90
[ "Markdown", "PHP" ]
4
PHP
sebastiand/silverstripe-addressable
42948f5c4ce5098d4d5ba13f841c90b88801b68a
9e823901a1058320c5fe85fe8f0e38c8addc417b
refs/heads/master
<file_sep>var user_model=require("../model/user_model.js") var md5=require('md5') /*练习页面 var async=require('async') exports.login=function(req,res,next){ //console.log(123) res.render('reg');//渲染登录页面 } exports.do_login=function(req,res,next){ var name=req.body.username;//只适用于post传输 var password=req.body.password; console.log(name); console.log(password); //解决地狱回调问题,将回调函数嵌套转换为两个串联函数 async.waterfall([ function(callback){ user_model.check(name,function(err,data){ callback(null,data) }) }, function(data,callback){ if(data.length>0){ res.send("用户名重名") }else{ user_model.reg(name,password,function(err,data){ if(data.affectedRows>0){ res.redirect('/login'); } }) } } ]) user_model.check(name,function(err,data){ if(data.length>0){ res.send("用户名重名") }else{ user_model.reg(name,password,function(err,data){ if(data.affectedRows>0){ res.redirect('/login'); } }) } }) } exports.donging_login=function(req,res,next){ res.render('login') } exports.parse=function(req,res,next){ console.log(req.query.yy) } exports.check=function(req,res,next){ var val=req.body.value; if(val=="aa"){ res.json({ errmsg:'正常', errno:101 }) }else{ res.json({ errmsg:'错误', errno:1 }) } } */ //首页,渲染登录页面 exports.reg=function(req,res,next){ res.render('reg') } //登录页面,进行登录操作,同时将注册内容加载到数据库 exports.do_reg=function(req,res,next){ var email=req.body.email; var name=req.body.name; var pwd=req.body.pwd; //var mpwd=md5(pwd) user_model.check(email,function(err,data){ if(data.length>0){ res.redirect('reg') }else{ user_model.insert(email,name,pwd,function(err,data){ if(data.affectedRows==1){ res.redirect('/login') } }) } }) } //检查是否重名 exports.checkname=function(req,res,next){ var email=req.body.email; user_model.check(email,function(err,data){ if(data.length>0){ res.json({ 'errno':101 }) }else{ res.json({ 'errno':1 }) } }) } //登录页面 exports.login=function(req,res,next){ res.render('login') } exports.do_login=function(req,res,next){ var email=req.body.email; var pass=<PASSWORD>; //var mpass=md5(pass) user_model.getname(email,pass,function(err,data){ if(data.length>0){ //console.log(data); //设置cookiesession---第三方包可以解决跨域问题 req.session.id=data[0].USER_ID; req.session.name=data[0].NAME; //接下来利用user_id和name来读取数据的blog主页信息t_blogs中的内容 res.redirect('/index') } }) } exports.unlogin=function(req,res,next){ req.session=null;//清除session res.redirect("/uindex") } //awesome node.js对于npm的功能做了分类<file_sep>var db=require('./db.js') //添加数据到数据库 exports.insert=function(email,name,password,callback){ var sql='insert into t_users(ACCOUNT,PASSWORD,NAME) values(?,?,?)' db.query(sql,[email,name,password],callback); } //检查是否数据库中有与传入email值相等的email exports.check=function(email,callback){ var sql='select * from t_users where ACCOUNT=?'; db.query(sql,[email],callback); } //查询登录邮箱和密码都对应的数据 exports.getname=function(email,pass,callback){ var sql='select * from t_users where ACCOUNT=? and PASSWORD=? ' db.query(sql,[email,pass],callback) } <file_sep>var express = require('express'); var router = express.Router(); var User=require('../controllers/users.js') var Blog=require('../controllers/blog.js') /* GET home page. */ //利用get 获取路由,执行回调函数 /*router.get('/', function(req, res, next) { res.render('uindex', { title: 'Express','name':'mm' }); });*/ //res.render()属于express内的方法 res.render(view [, locals] [, callback]) /*router.get('/parse',function(req,res,next){ res.render('dns',{ 'name':'dd', 'age':1 }); })*/ /*router.get('/reg',User.login) router.post('/reg',User.do_login) router.get('/login',User.donging_login) router.get('/parse',User.parse)//为什么在有两个get 请求,且第一个有返回值时获取不到传递的参数 /*router.post('/check',User.check)*/ //注册功能 router.get('/',User.reg)//当进入网站时,自动调用出方法reg(即渲染注册页面) router.get('/reg',User.reg)//进入注册页路由时,调用方法reg(即渲染出注册页面) router.post('/reg',User.do_reg)//在enter后发出请求,获取注册页面路由下获取输入框中的内容 //并接收获取内容的返回值,执行方法do_reg //检查注册邮件名字是否重名 router.post('/checkname',User.checkname)//为什么访问的时候拿到的同样是reg路径下的数据 //登录功能 router.get('/login',User.login)//注册成功后,进入/login路由控制,自动调用出方法login(即渲染登录页面) router.post('/login',User.do_login)//在enter后发出请求,获取登录页面路由下获取输入框中的内容 //并接收获取内容的返回值,执行方法do_login router.get('/unlogin',User.unlogin)//清除session值,并且作为中间值转换到uindex路由 //通过超链接跳转到uindex页面 //同时调用uindex方法(即渲染游客身份登录index页面) //主页功能 router.get('/index',Blog.index)//登录成功后,进入/index路由下,自动调用出方法login(即渲染某游客登录index_logined主页) router.get('/uindex',Blog.uindex)//通过超链接跳转到uindex页面,同时调用uindex方法(即渲染游客身份登录index页面) //发表博客功能及增删检查 router.get('/add_blogs',Blog.add_blogs) router.post('/add_blogs',Blog.do_add_blogs) router.get('/updata_blog/:bid',Blog.updata_blog) router.post('/updata_blog',Blog.do_updata_blog) router.get('/delete/:bid',Blog.delete_blog) //搜索栏 router.post('/search',Blog.search_blog) //博客分类管理 router.get('/blogcatalogs',Blog.catalog_blog) //阅读全文 router.get('/viewPost_logined/:bid',Blog.viewPost_logined) module.exports = router; <file_sep>var db=require('./db.js') var moment=require('moment') exports.sel_all_blogs=function(callback){ var sql="select * from t_blogs"; db.query(sql,[],callback) } exports.sel_one_blogs=function(uid,callback){ //var sql="select * from t_blogs,t_users where t_blogs.WRITER=t_users.USER_ID and t_blogs.WRITER=?"; var sql='select * from t_blogs,t_users,t_blog_catalogs where t_blogs.WRITER=t_users.USER_ID and t_blogs.CATALOG_ID=t_blog_catalogs.CATALOG_ID and t_blogs.WRITER=?' db.query(sql,[uid],callback) } //通过user_id找出发表博客的人将博客分的类别 exports.sel_cata_blog=function(uid,callback){ var sql='select * from t_blog_catalogs where USER_ID=?'; db.query(sql,[uid],callback) } exports.insert_blog=function(title,content,catalog,uid,callback){ var time=moment().format("YY-MM-DD hh-mm-ss") console.log(time) var sql="insert into t_blogs(TITLE,CONTENT,WRITER,CATALOG_ID,ADD_TIME) values(?,?,?,?,?) " db.query(sql,[title,content,uid,catalog,time],callback) } exports.sel_blogs_by_bid=function(blogid,callback){ var sql="select * from t_blogs where BLOG_ID=?" db.query(sql,[blogid],callback) } exports.updata_blog=function(title,content,cataid,blogid,callback){ var sql="update t_blogs set TITLE=?,CONTENT=?,CATALOG_ID=? where BLOG_ID=?"; db.query(sql,[title,content,cataid,blogid],callback) } exports.update_blog=function(blogid,title,content,cataid,callback){ var sql="update t_blogs set TITLE=?,CONTENT=?,CATALOG_ID=? where BLOG_ID=?"; db.query(sql,[title,content,cataid,blogid],callback); } exports.del_blog_by_bid=function(bid,callback){ var sql="delete from t_blogs where BLOG_ID=?"; db.query(sql,[bid],callback); } exports.search_blog=function(title,uid,callback){ var sql="select * from t_blogs where TITLE like '%"+ title +"%' and WRITER="+ uid; db.query(sql,[],callback); } exports.viewAllCom=function(bid,callback){ var sql='select * from t_blogs where BLOG_ID=?' db.query(sql,[bid],callback); } exports.updata_hits=function(bid,callback){ var sql='update t_blogs set CLICK_RATE=CLICK_RATE+1 where BLOG_ID=?'; // SELECT * from t_blogs where BLOG_ID<5 ORDER BY BLOG_ID asc LIMIT 1//查询小于五的第一个 // SELECT * from t_blogs where BLOG_ID<5 ORDER BY BLOG_ID desc LIMIT 1//查询小于五的最后一个(最大值) db.query(sql,[bid],callback) }//由于在sql中null+1=null所以在设计表时需要把默认值设置为零;javascriptsnull+1=1; exports.next_blog=function(bid,callback){ var sql='select * from t_blogs where BLOG_ID<5 ORDER BY BLOG_ID desc LIMIT 1' db.query(sql,[bid],callback) } exports.previous_blog=function(bid,callback){ var sql='select * from t_blogs where BLOG_ID>5 ORDER BY BLOG_ID asc LIMIT 1' db.query(sql,[bid],callback) }
4689aee222c3715b97d0eb5f7abe2eac4c94965d
[ "JavaScript" ]
4
JavaScript
Miraitowa007/Blog
768d7467ec28284ce244890c905c285e8bb5ffbd
fd56b4af4ae911eceafd4566e8c222f5f80d823c
refs/heads/master
<file_sep>package main import ( "fmt" "testing" "github.com/fatih/color" gcolor "github.com/gookit/color" ) // https://github.com/fatih/color func Benchmark_fatih_color(t *testing.B) { color.Cyan("Prints text in cyan.") } // https://github.com/gookit/color func Benchmark_gookit_color(t *testing.B) { gcolor.Cyan.Println("Prints text in cyan.") } // https://groups.google.com/g/golang-nuts/c/nluStAtr8NA?pli=1 func Benchmark_normalFmt_color(t *testing.B) { fmt.Printf("\x1b[36m%s\x1b[0m", "Prints text in cyan.") } <file_sep># Homebrew でコマンドラインツールを配布する手順 ## 手順 1. 作ったツールのバイナリファイルを github の `release` に登録 2. Formulaファイル `.rb` をおく、リポジトリを作成。 3. `homebrew-tap` にFormulaファイルを作成。 ### 1. 作ったツールのバイナリファイルを github の `release` に登録 `go build` などでバイナリーファイルを作成して、github の `release` タグに登録 ### 2. Formulaファイル `.rb` をおく、リポジトリを作成。 Formulaファイル `.rb` を置くための、リポジトリ(`homebrew-tap`と命名する人が多い)を作成。 ### 3. `homebrew-tap` にFormulaファイルを作成。 Formulaファイルを作成する。 ``` brew create <install URL> ``` `<install URL>`は配布したいツールのバイナリファイルのURL。 ↓ は一例([ctest](https://github.com/hmarf/homebrew-tap/blob/master/ctest.rb))だが、こんな感じにする。作成されたファイルのコメント消して、ちょっと変更するだけ。 ``` class Ctest < Formula desc "" homepage "" url "https://github.com/hmarf/cTest/releases/download/v1.0.1/ctest" sha256 "5478c31029a2b0fa6ed3cbfccbe0b23ae641169f258171436d578aee7fd9b6f8" license "" def install bin.install "<package name>" end test do system "true" end end ``` こいつをgithubにあげたらいける! ### install方法 ``` $ brew tap <user name>/tap $ brew install <package name> ```<file_sep># 外部コマンドをGoプログラム内で実行 ## 実行したいコマンドを `exec.Command` で準備 定義 & 注意: 再利用は不可能 ``` // Cmd represents an external command being prepared or run. // // A Cmd cannot be reused after calling its Run, Output or CombinedOutput methods. ``` ### `$ ls` のとき ``` package main import "os/exec" func main() { cmd := exec.Command("ls") ... } ``` ### `$ ls -a -G` のとき ``` package main import "os/exec" var lsOption := []string{"-a", "-G"} func main() { cmd := exec.Command("ls", lsOption...) ... } ``` ## 準備されたコマンドを実行 exec.Cmdにはいろいろ用意されている - Run() - Start() - String() - Wait() - CombinedOutput() - Output() - StderrPipe() - StdinPipe() - StdoutPipe() ### String() 人が読める形でコマンドを返す。実行とかは特にしない。 ``` string := cmd.String() ``` ### Run() 実行したコマンドの終了を待つ。コマンドが出力した結果などは受け取ることはできない。コマンドが正常に動作するかをチェックできる。 ``` err := cmd.Run() ``` ### Output() コマンドの標準出力を受け取ることができる。ただし、コマンドの終了を待つ。コマンドの終了を待ち、その結果(標準出力)を使って処理をかける。 ``` []byte, error := cmd.Output() // コマンドの結果をstringに result := string([]byte) ``` ### CombinedOutput() コマンドの標準出力&標準エラー出力を受け取ることができる。ただし、コマンドの終了を待つ。コマンドの終了を待ち、その結果(標準出力&標準エラー出力)を使って処理をかける。 ``` []byte, error := cmd.CombinedOutput() // コマンドの結果をstringに result := string([]byte) ``` ### Start(), StderrPipe(), StdinPipe(), StdoutPipe() コマンドの終了を待たない。単体で使うよりも `Cmd.Wait()` と組み合わせて使うことが多いと思う。`Cmd.Wait()`でコマンドの終了を待ってくれるのでリアルタイムで標準出力などを検知することができる。(使い勝手がいい子) コマンドの出力をリアタイで出力するプログラムを載せとく。 ``` package main import ( "bufio" "fmt" "os/exec" ) func main() { cmd := exec.Command("./a.sh") // standard output stdout, err := cmd.StdoutPipe() if err != nil { fmt.Println(err) return } // standard error output stderr, err := cmd.StderrPipe() if err != nil { fmt.Println(err) return } // start running command if err := cmd.Start(); err != nil { fmt.Println(err) return } // output scan := bufio.NewScanner(stdout) scanErr := bufio.NewScanner(stderr) go print(scan) go print(scanErr) // Wait for the command to finish if err = cmd.Wait(); err != nil { fmt.Println(err) } } func print(r *bufio.Scanner) { for r.Scan() { fmt.Println(r.Text()) } } ```<file_sep># TDD TDDはテスト手法ではない。TDDは分析技法であり、設計術法であり、実際には解析の全てのアクティビティを構造化する技法である。 **TDDの目的: 「動作するきれいなコード** 当たり前だが、"動作しない、きれいなコード" より "汚い、動作するコード" の方が価値がある。 TDDでは動くコードを作成した後、きれいなコードを目指していく。 ## TDDのサイクル & メリット ### TDDのサイクル 以下のサイクルを短い時間(10分程度)で回す。 > 1. テストを書き > 2. そのテストを実行して失敗させ(`Red`) > 3. 目的のコードを書き > 4. 1で書いたテストを成功させ(`Green`) > 5. テストが通った状態を維持しながらリファクタリングする(`Refactor`) > 6. 1 ~ 5 を繰り返す *[t-wada](https://twitter.com/t_wada)さんの[スライド](https://www.slideshare.net/t_wada/the-spirit-of-tdd)から引用* 最初に必要な機能のTODOリストを作成し、これから何を実装するのかを検討。 一部のテストコードを書き、失敗させる。 テストコードが通る最速の実際コードを書き、成功させる。 コードをきれいな形にリファクタリングし、次のTODOリストを行う。 ### メリット > TDDで大切なことは、細かいステップを踏むことではなく、踏み続け蹴られることだ。 *[テスト駆動開発](https://www.amazon.co.jp/dp/B077D2L69C/ref=dp-kindle-redirect?_encoding=UTF8&btkr=1) から引用* サイクルを細かく回すメリットは「いつ、どこで失敗したのかわかること」だと思う。自分の実装手順でどこに問題があるのかを早い段階で知ることができる。 テストを書くことでコードのきれいさに惑わされず、コードがもつの責務に集中することができる。このコードはこっちの方が実装きれいだなー。という感情に惑わされ、コードの責務を無視する機会が減る。 コードを使う側の気持ちになることもできる。 ## テスト評価手法 [テスト駆動開発](https://www.amazon.co.jp/dp/B077D2L69C/ref=dp-kindle-redirect?_encoding=UTF8&btkr=1) で紹介されていた手法に補足する形書く。 - ステートメントカバレッジ: プログラム内のコード(命令文)のうち、テストを実行した割合を示す。テスト駆動開発で開発を行うとカバレッジは100%になる。(ただし、[100%を追求しても品質は高くならないのでは?という議論もある](https://qiita.com/bremen/items/d02eb38e790b93f44728)) [松岡さんのYoutube(TDDオンライン勉強会 #1)](https://www.youtube.com/watch?v=UhHdnLTxOjE&t=7153s) で出てきた、"カバレッジは「足りないこと」はわかるが「十分であること」の根拠には使えない"は名言すぎる。 - 欠陥挿入(defect insertion): プロダクトコードの任意の行の意味合いを変えたらテストは失敗しなければならない。 ## 他に伝えたいこと - テスト間の依存関係は悪である。 - 1つのテストコードが失敗したら後続のテストが失敗すること。 - テストA → テストBの順番ならテストが成功するが、テストB → テストAの順番だと失敗する。 - 途中で開発をやめるうまいタイミングは、「テストを失敗した状態にすること」 - テストが失敗しているので、どこでやめたかわかりやすい。自分が何を考えていたかを思い出しやすい。<file_sep>module github.com/hmarf/benchColorStdout go 1.16 require ( github.com/fatih/color v1.10.0 github.com/gookit/color v1.4.2 ) <file_sep># tumblr Qiitaとかきちんと書くのがしんどいので、好き勝手書くブログ初めました。。。 https://hmarf.tumblr.com/ <file_sep># Go言語で標準出力にカラーをつけるライブラリーのベンチマーク比較 - `fmt` - `github.com/fatih/color` - `github.com/gookit/color` 比較したコード: ``` import ( "fmt" "testing" "github.com/fatih/color" gcolor "github.com/gookit/color" ) // https://github.com/fatih/color func Benchmark_fatih_color(t *testing.B) { color.Cyan("Prints text in cyan.") } // https://github.com/gookit/color func Benchmark_gookit_color(t *testing.B) { gcolor.Cyan.Println("Prints text in cyan.") } // https://groups.google.com/g/golang-nuts/c/nluStAtr8NA?pli=1 func Benchmark_fmt_color(t *testing.B) { fmt.Printf("\x1b[36m%s\x1b[0m", "Prints text in cyan.") } ``` 結果: ``` cpu: Intel(R) Core(TM) i7-5775R CPU @ 3.30GHz github.com/fatih/color: 1000000000 0.0000173 ns/op 0 B/op 0 allocs/op github.com/gookit/color: 1000000000 0.0000118 ns/op 0 B/op 0 allocs/op fmt: 1000000000 0.0000114 ns/op 0 B/op 0 allocs/op ``` *結果の関数名は見やすように変更* `fmt.Printf()`が最も高速だが、他も早い。 ただ直感的に描けるし、早いのでカラーつけるときは `"github.com/gookit/color"` 使おうかな。
7b16264ceb4c0dc88f3eb05cfdc7b1774c669849
[ "Markdown", "Go Module", "Go" ]
7
Go
hmarf/tumblr
c0df28da634ea6c1830b32b27c3f1c20b8b67dd2
5a5c4b928cd2632ac85c67a763a4f317f69b3e00
refs/heads/master
<repo_name>sorrycc/umi-example-monaco-editor<file_sep>/.umirc.ts const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin'); export default { nodeModulesTransform: { type: 'none', }, fastRefresh: {}, webpack5: {}, chainWebpack(memo) { memo.plugin('m').use(MonacoWebpackPlugin) } }
8f0d1208b1c470a35cf3f89ff2bc0d8e811936b0
[ "TypeScript" ]
1
TypeScript
sorrycc/umi-example-monaco-editor
88d9a98c5713fab67e70e78105029e029c26ac48
d7523ba7ad2f8790340398f37064bdb308fa8e9a
refs/heads/master
<file_sep>import re from xml.sax.saxutils import escape, unescape from html5lib.constants import tokenTypes from html5lib.sanitizer import HTMLSanitizerMixin from html5lib.tokenizer import HTMLTokenizer import urllib2 # SUPERMASSIVE # SUPERMASSIVE feed isn't in acceptable_protocols. I think html5lib got updated. #PROTOS = HTMLSanitizerMixin.acceptable_protocols #PROTOS.remove('feed') # SUPERMASSIVE ALLOWED_IFRAME_HOSTS = [ 'www.youtube.com', 'youtube.com', 'player.vimeo.com', ] """ We want to allow iframes for embedding videos from youtube/vimeo and other sites but definitely do not want iframes for any other reason. This is not straighforward because bleach has no support for optionally allowing tags based on attributes, in this case netloc host matching. Bleach provides it's own sanitizer on top of html5lib and we want what it provides but need to add custom logic to support iframe testing. Hence SMBleachSanitizerMixin. In order to get it into the inheritance chain of the top level bleach functions, monkey patching the bleach library was nessasary. All other solutions also required modifying key bleach inheritance chains anyway, so this is the most straightforward solution. """ class SMBleachSanitizerMixin(HTMLSanitizerMixin): """Mixin to replace sanitize_token() and sanitize_css(). ========================================================= SUPERMASSIVE This class has been modified to support Supermassives use case of embedding videos in descriptions / text fields using iframe tags if they have specific netloc hostnames. """ allowed_svg_properties = [] # TODO: When the next html5lib version comes out, nuke this. attr_val_is_uri = HTMLSanitizerMixin.attr_val_is_uri + ['poster'] def sanitize_token(self, token): """Sanitize a token either by HTML-encoding or dropping. Unlike HTMLSanitizerMixin.sanitize_token, allowed_attributes can be a dict of {'tag': ['attribute', 'pairs'], 'tag': callable}. Here callable is a function with two arguments of attribute name and value. It should return true of false. Also gives the option to strip tags instead of encoding. =========================================================== SUPERMASSIVE This function has been modified to support iframes from specific sites to allow embedding of videos using auto-generated embed links. """ if (getattr(self, 'wildcard_attributes', None) is None and isinstance(self.allowed_attributes, dict)): self.wildcard_attributes = self.allowed_attributes.get('*', []) if token['type'] in (tokenTypes['StartTag'], tokenTypes['EndTag'], tokenTypes['EmptyTag']): #=== SUPERMASSIVE Patch START if token['name'] == 'iframe': # only allow iframe that have a netloc host that in ALLOWED_IFRAME_HOSTS if 'data' in token and not token['selfClosing']: attrs = dict([(name, val) for name, val in token['data']]) if 'src' in attrs: # check that this is an allowed host if urllib2.urlparse.urlparse(attrs['src']).hostname in ALLOWED_IFRAME_HOSTS: return token elif token['type'] == tokenTypes['EndTag']: token['data'] = '</%s>' % token['name'] return token #=== SUPERMASSIVE Patch END elif token['name'] in self.allowed_elements: # if statement changed to elif - SUPERMASSIVE if 'data' in token: if isinstance(self.allowed_attributes, dict): allowed_attributes = self.allowed_attributes.get( token['name'], []) if not callable(allowed_attributes): allowed_attributes += self.wildcard_attributes else: allowed_attributes = self.allowed_attributes attrs = dict([(name, val) for name, val in token['data'][::-1] if (allowed_attributes(name, val) if callable(allowed_attributes) else name in allowed_attributes)]) for attr in self.attr_val_is_uri: if not attr in attrs: continue val_unescaped = re.sub("[`\000-\040\177-\240\s]+", '', unescape(attrs[attr])).lower() # Remove replacement characters from unescaped # characters. val_unescaped = val_unescaped.replace(u"\ufffd", "") if (re.match(r'^[a-z0-9][-+.a-z0-9]*:', val_unescaped) and (val_unescaped.split(':')[0] not in self.allowed_protocols)): del attrs[attr] for attr in self.svg_attr_val_allows_ref: if attr in attrs: attrs[attr] = re.sub(r'url\s*\(\s*[^#\s][^)]+?\)', ' ', unescape(attrs[attr])) if (token['name'] in self.svg_allow_local_href and 'xlink:href' in attrs and re.search(r'^\s*[^#\s].*', attrs['xlink:href'])): del attrs['xlink:href'] if 'style' in attrs: attrs['style'] = self.sanitize_css(attrs['style']) token['data'] = [(name, val) for name, val in attrs.items()] return token elif self.strip_disallowed_elements: pass else: if token['type'] == tokenTypes['EndTag']: token['data'] = '</%s>' % token['name'] elif token['data']: attrs = ''.join([' %s="%s"' % (k, escape(v)) for k, v in token['data']]) token['data'] = '<%s%s>' % (token['name'], attrs) else: token['data'] = '<%s>' % token['name'] if token['selfClosing']: token['data'] = token['data'][:-1] + '/>' token['type'] = tokenTypes['Characters'] del token["name"] return token elif token['type'] == tokenTypes['Comment']: if not self.strip_html_comments: return token else: return token def sanitize_css(self, style): """HTMLSanitizerMixin.sanitize_css replacement. HTMLSanitizerMixin.sanitize_css always whitelists background-*, border-*, margin-*, and padding-*. We only whitelist what's in the whitelist. """ # disallow urls style = re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ', style) # gauntlet # TODO: Make sure this does what it's meant to - I *think* it wants to # validate style attribute contents. parts = style.split(';') gauntlet = re.compile("""^([-/:,#%.'"\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'\s*""" """|"[\s\w]+"|\([\d,%\.\s]+\))*$""") for part in parts: if not gauntlet.match(part): return '' if not re.match("^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$", style): return '' clean = [] for prop, value in re.findall('([-\w]+)\s*:\s*([^:;]*)', style): if not value: continue if prop.lower() in self.allowed_css_properties: clean.append(prop + ': ' + value + ';') elif prop.lower() in self.allowed_svg_properties: clean.append(prop + ': ' + value + ';') return ' '.join(clean) class SMBleachSanitizer(HTMLTokenizer, SMBleachSanitizerMixin): def __init__(self, stream, encoding=None, parseMeta=True, useChardet=True, lowercaseElementName=True, lowercaseAttrName=True, **kwargs): HTMLTokenizer.__init__(self, stream, encoding, parseMeta, useChardet, lowercaseElementName, lowercaseAttrName, **kwargs) def __iter__(self): for token in HTMLTokenizer.__iter__(self): token = self.sanitize_token(token) if token: yield token
cf1767b6688210a2bbfe50e5622a08e9f58966c8
[ "Python" ]
1
Python
quadrivium33/bleach
0a2643c39338a25c86e401e9cd1ca218b4b4be23
2e58cfc2336327dabc1c3d855160af88807abfd8
refs/heads/master
<file_sep>[package] name = "pistoncore-event" version = "0.1.1" authors = [ "bvssvni <<EMAIL>>", "Coeuvre <<EMAIL>>" ] keywords = ["event", "piston"] description = "A library for flexible generic event threading" license = "MIT" readme = "README.md" repository = "https://github.com/pistondevelopers/event.git" homepage = "https://github.com/pistondevelopers/event" [lib] name = "event" path = "src/lib.rs" [dependencies.pistoncore-input] git = "https://github.com/PistonDevelopers/input" #version = "0.0.9" [dependencies.pistoncore-event_loop] git = "https://github.com/PistonDevelopers/event_loop" #version = "0.1.0" [dependencies.pistoncore-window] git = "https://github.com/PistonDevelopers/window" #version = "0.1.0" <file_sep>use std::any::Any; use { GenericEvent, MOUSE_SCROLL, MOUSE_RELATIVE, MOUSE_CURSOR }; /// The position of the mouse cursor pub trait MouseCursorEvent { /// Creates a mouse cursor event. fn from_xy(x: f64, y: f64) -> Option<Self>; /// Calls closure if this is a mouse cursor event. fn mouse_cursor<U, F>(&self, f: F) -> Option<U> where F: FnMut(f64, f64) -> U; /// Returns mouse cursor arguments. fn mouse_cursor_args(&self) -> Option<[f64; 2]> { self.mouse_cursor(|x, y| [x, y]) } } impl<T: GenericEvent> MouseCursorEvent for T { fn from_xy(x: f64, y: f64) -> Option<Self> { GenericEvent::from_args(MOUSE_CURSOR, &(x, y) as &Any) } fn mouse_cursor<U, F>(&self, mut f: F) -> Option<U> where F: FnMut(f64, f64) -> U { if self.event_id() != MOUSE_CURSOR { return None; } self.with_args(|any| { if let Some(&(x, y)) = any.downcast_ref::<(f64, f64)>() { Some(f(x, y)) } else { panic!("Expected (f64, f64)") } }) } } /// The relative movement of mouse cursor pub trait MouseRelativeEvent { /// Creates a mouse relative event. fn from_xy(x: f64, y: f64) -> Option<Self>; /// Calls closure if this is a mouse relative event. fn mouse_relative<U, F>(&self, f: F) -> Option<U> where F: FnMut(f64, f64) -> U; /// Returns mouse relative arguments. fn mouse_relative_args(&self) -> Option<[f64; 2]> { self.mouse_relative(|x, y| [x, y]) } } impl<T: GenericEvent> MouseRelativeEvent for T { fn from_xy(x: f64, y: f64) -> Option<Self> { GenericEvent::from_args(MOUSE_RELATIVE, &(x, y) as &Any) } fn mouse_relative<U, F>(&self, mut f: F) -> Option<U> where F: FnMut(f64, f64) -> U { if self.event_id() != MOUSE_RELATIVE { return None; } self.with_args(|any| { if let Some(&(x, y)) = any.downcast_ref::<(f64, f64)>() { Some(f(x, y)) } else { panic!("Expected (f64, f64)") } }) } } /// The scroll of the mouse wheel pub trait MouseScrollEvent { /// Creates a mouse scroll event. fn from_xy(x: f64, y: f64) -> Option<Self>; /// Calls a closure if this is a mouse scroll event. fn mouse_scroll<U, F>(&self, f: F) -> Option<U> where F: FnMut(f64, f64) -> U; /// Returns mouse scroll arguments. fn mouse_scroll_args(&self) -> Option<[f64; 2]> { self.mouse_scroll(|x, y| [x, y]) } } impl<T: GenericEvent> MouseScrollEvent for T { fn from_xy(x: f64, y: f64) -> Option<Self> { GenericEvent::from_args( MOUSE_SCROLL, &(x, y) as &Any ) } fn mouse_scroll<U, F>(&self, mut f: F) -> Option<U> where F: FnMut(f64, f64) -> U { if self.event_id() != MOUSE_SCROLL { return None; } self.with_args(|any| { if let Some(&(x, y)) = any.downcast_ref::<(f64, f64)>() { Some(f(x, y)) } else { panic!("Expected (f64, f64)") } }) } } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[test] fn test_input_mouse_cursor() { use input::Input; let x: Option<Input> = MouseCursorEvent::from_xy(1.0, 0.0); let y: Option<Input> = x.clone().unwrap().mouse_cursor(|x, y| MouseCursorEvent::from_xy(x, y)).unwrap(); assert_eq!(x, y); } #[bench] fn bench_input_mouse_cursor(bencher: &mut Bencher) { use input::Input; bencher.iter(|| { let _: Option<Input> = MouseCursorEvent::from_xy(1.0, 0.0); }); } #[test] fn test_event_mouse_cursor() { use Event; let x: Option<Event> = MouseCursorEvent::from_xy(1.0, 0.0); let y: Option<Event> = x.clone().unwrap().mouse_cursor(|x, y| MouseCursorEvent::from_xy(x, y)).unwrap(); assert_eq!(x, y); } #[bench] fn bench_event_mouse_cursor(bencher: &mut Bencher) { use Event; bencher.iter(|| { let _: Option<Event> = MouseCursorEvent::from_xy(1.0, 0.0); }); } #[test] fn test_input_mouse_relative() { use input::Input; let x: Option<Input> = MouseRelativeEvent::from_xy(1.0, 0.0); let y: Option<Input> = x.clone().unwrap().mouse_relative(|x, y| MouseRelativeEvent::from_xy(x, y)).unwrap(); assert_eq!(x, y); } #[bench] fn bench_input_mouse_relative(bencher: &mut Bencher) { use input::Input; bencher.iter(|| { let _: Option<Input> = MouseRelativeEvent::from_xy(1.0, 0.0); }); } #[test] fn test_event_mouse_relative() { use Event; let x: Option<Event> = MouseRelativeEvent::from_xy(1.0, 0.0); let y: Option<Event> = x.clone().unwrap().mouse_relative(|x, y| MouseRelativeEvent::from_xy(x, y)).unwrap(); assert_eq!(x, y); } #[bench] fn bench_event_mouse_relative(bencher: &mut Bencher) { use Event; bencher.iter(|| { let _: Option<Event> = MouseRelativeEvent::from_xy(1.0, 0.0); }); } #[test] fn test_input_mouse_scroll() { use input::Input; let x: Option<Input> = MouseScrollEvent::from_xy(1.0, 0.0); let y: Option<Input> = x.clone().unwrap().mouse_scroll(|x, y| MouseScrollEvent::from_xy(x, y)).unwrap(); assert_eq!(x, y); } #[bench] fn bench_input_mouse_scroll(bencher: &mut Bencher) { use input::Input; bencher.iter(|| { let _: Option<Input> = MouseScrollEvent::from_xy(1.0, 0.0); }); } #[test] fn test_event_mouse_scroll() { use Event; let x: Option<Event> = MouseScrollEvent::from_xy(1.0, 0.0); let y: Option<Event> = x.clone().unwrap().mouse_scroll(|x, y| MouseScrollEvent::from_xy(x, y)).unwrap(); assert_eq!(x, y); } #[bench] fn bench_event_mouse_scroll(bencher: &mut Bencher) { use Event; bencher.iter(|| { let _: Option<Event> = MouseScrollEvent::from_xy(1.0, 0.0); }); } }
02042c7639b82fdd6b12f6dab497844e7a798255
[ "TOML", "Rust" ]
2
TOML
Potpourri/event
65b9b5754e3da9062f522bb680a8cfc387cd6b84
9e238df1f24f24dc1305ffa1e6d4bd349a636274
refs/heads/master
<repo_name>dcuerdogarcia/Ejercicio1ARQ<file_sep>/src/arquivos/Arquivos.java /* * 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 arquivos; import java.io.File; import java.io.IOException; /** * * @author oracle */ public class Arquivos { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { File directorio = new File("/home/oracle/NetBeansProjects/arquivos/arquivosdir"); directorio.mkdirs(); File arquivo = new File("/home/oracle/NetBeansProjects/arquivos/arquivosdir/Products1.txt"); if (arquivo.createNewFile()) { System.out.println("Está creada"); } File directorio2 = new File("/home/oracle/NetBeansProjects/arquivos/arquivosdir/subdir"); directorio2.mkdirs(); File arquivo2 = new File("/home/oracle/NetBeansProjects/arquivos/arquivosdir/subdir/Products2.txt"); if (arquivo2.createNewFile()) { System.out.println("Está creada"); } File[] ficheros = directorio.listFiles(); for (int i = 0; i < ficheros.length; i++) { System.out.println(ficheros[i].getName()); } File miDir = new File("."); try { System.out.println("O directorio actual é: " + miDir.getCanonicalPath()); } catch (Exception e) { e.printStackTrace(); } System.out.println(directorio.getName() + "\n" + directorio.getAbsolutePath() + "\n" + directorio.canRead() + "\n" + directorio.canWrite() + "\n" + directorio.length()); directorio.setReadOnly(); directorio.setWritable(true); directorio.delete(); } }
80785dfefb3b23ef0e9ad7b578a985aa5dabd437
[ "Java" ]
1
Java
dcuerdogarcia/Ejercicio1ARQ
33cab9b3659ae3dfed4148aff00e6d5731c05fdc
8366692e168b65f12ebf97791ad58a9c6e347008
refs/heads/master
<file_sep>/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package controllers import ( "context" "fmt" "github.com/go-logr/logr" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" tenancyv1alpha1 "github.com/kubernetes-sigs/multi-tenancy/tenant/api/v1alpha1" ) // TenantReconciler reconciles a Tenant object type TenantReconciler struct { client.Client Log logr.Logger Scheme *runtime.Scheme } // +kubebuilder:rbac:groups=tenancy.x-k8s.io,resources=tenants,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=tenancy.x-k8s.io,resources=tenants/status,verbs=get;update;patch // +kubebuilder:rbac:groups=core,resources=namespaces,verbs=get;list;watch;create // +kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=clusterroles,verbs=get;list;create;update;patch // +kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=clusterrolebindings,verbs=get;list;create;update;patch // +kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=roles,verbs=get;list;create;update;patch // +kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=rolebindings,verbs=get;list;create;update;patch func (r *TenantReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) { ctx := context.Background() _ = r.Log.WithValues("tenant", req.NamespacedName) // Fetch the Tenant instance instance := &tenancyv1alpha1.Tenant{} // Tenant is a cluster scoped CR, we should clear the namespace field in request req.NamespacedName.Namespace = "" err := r.Get(ctx, req.NamespacedName, instance) if err != nil { if errors.IsNotFound(err) { // Object not found, return. Created objects are automatically garbage collected. // For additional cleanup logic use finalizers. return ctrl.Result{}, nil } // Error reading the object - requeue the request. return ctrl.Result{}, err } expectedOwnerRef := metav1.OwnerReference{ APIVersion: tenancyv1alpha1.GroupVersion.String(), Kind: "Tenant", Name: instance.Name, UID: instance.UID, } // Create tenantAdminNamespace if instance.Spec.TenantAdminNamespaceName != "" { nsList := &corev1.NamespaceList{} err := r.List(context.TODO(), nsList) if err != nil { return ctrl.Result{}, err } foundNs := false for _, each := range nsList.Items { if each.Name == instance.Spec.TenantAdminNamespaceName { foundNs = true // Check OwnerReference isOwner := false for _, ownerRef := range each.OwnerReferences { if ownerRef == expectedOwnerRef { isOwner = true break } } if !isOwner { err = fmt.Errorf("TenantAdminNamespace %v is owned by %v", each.Name, each.OwnerReferences) return ctrl.Result{}, err } break } } if !foundNs { tenantAdminNs := &corev1.Namespace{ TypeMeta: metav1.TypeMeta{ APIVersion: corev1.SchemeGroupVersion.String(), Kind: "Namespace", }, ObjectMeta: metav1.ObjectMeta{ Name: instance.Spec.TenantAdminNamespaceName, OwnerReferences: []metav1.OwnerReference{expectedOwnerRef}, }, } if err := r.Client.Create(context.TODO(), tenantAdminNs); err != nil { return ctrl.Result{}, err } } } // Create RBACs for tenantAdmins. if instance.Spec.TenantAdmins != nil { // First, create cluster roles to allow them to access tenant CR and tenantAdminNamespace. crName := fmt.Sprintf("%s-tenant-admin-role", instance.Name) cr := &rbacv1.ClusterRole{ TypeMeta: metav1.TypeMeta{ APIVersion: rbacv1.SchemeGroupVersion.String(), Kind: "ClusterRole", }, ObjectMeta: metav1.ObjectMeta{ Name: crName, OwnerReferences: []metav1.OwnerReference{expectedOwnerRef}, }, Rules: []rbacv1.PolicyRule{ { Verbs: []string{"get", "list", "watch", "update", "patch", "delete"}, APIGroups: []string{tenancyv1alpha1.GroupVersion.Group}, Resources: []string{"tenants"}, ResourceNames: []string{instance.Name}, }, { Verbs: []string{"get", "list", "watch"}, APIGroups: []string{""}, Resources: []string{"namespaces"}, ResourceNames: []string{instance.Spec.TenantAdminNamespaceName}, }, }, } if err := r.clientApply(ctx, cr); err != nil { return ctrl.Result{}, err } crbindingName := fmt.Sprintf("%s-tenant-admins-rolebinding", instance.Name) crbinding := &rbacv1.ClusterRoleBinding{ TypeMeta: metav1.TypeMeta{ APIVersion: rbacv1.SchemeGroupVersion.String(), Kind: "ClusterRoleBinding", }, ObjectMeta: metav1.ObjectMeta{ Name: crbindingName, OwnerReferences: []metav1.OwnerReference{expectedOwnerRef}, }, Subjects: instance.Spec.TenantAdmins, RoleRef: rbacv1.RoleRef{ APIGroup: rbacv1.GroupName, Kind: "ClusterRole", Name: crName, }, } if err = r.clientApply(ctx, crbinding); err != nil { return ctrl.Result{}, err } // Second, create namespace role to allow them to create tenantnamespace CR in tenantAdminNamespace. role := &rbacv1.Role{ TypeMeta: metav1.TypeMeta{ APIVersion: rbacv1.SchemeGroupVersion.String(), Kind: "Role", }, ObjectMeta: metav1.ObjectMeta{ Name: "tenant-admin-role", Namespace: instance.Spec.TenantAdminNamespaceName, OwnerReferences: []metav1.OwnerReference{expectedOwnerRef}, }, Rules: []rbacv1.PolicyRule{ { Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, APIGroups: []string{tenancyv1alpha1.GroupVersion.Group}, Resources: []string{"tenantnamespaces"}, }, }, } if err := r.clientApply(ctx, role); err != nil { return ctrl.Result{}, err } rbinding := &rbacv1.RoleBinding{ TypeMeta: metav1.TypeMeta{ APIVersion: rbacv1.SchemeGroupVersion.String(), Kind: "RoleBinding", }, ObjectMeta: metav1.ObjectMeta{ Name: "tenant-admins-rolebinding", Namespace: instance.Spec.TenantAdminNamespaceName, OwnerReferences: []metav1.OwnerReference{expectedOwnerRef}, }, Subjects: instance.Spec.TenantAdmins, RoleRef: rbacv1.RoleRef{ APIGroup: rbacv1.GroupName, Kind: "Role", Name: "tenant-admin-role", }, } if err = r.clientApply(ctx, rbinding); err != nil { return ctrl.Result{}, err } } return ctrl.Result{}, nil } func (r *TenantReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&tenancyv1alpha1.Tenant{}). Owns(&corev1.Namespace{}). Complete(r) } // Create if not existing, update otherwise func (r *TenantReconciler) clientApply(ctx context.Context, obj runtime.Object) error { var err error if err = r.Client.Create(ctx, obj); err != nil { if errors.IsAlreadyExists(err) { // Update instead of create err = r.Client.Update(ctx, obj) } } return err } <file_sep>module github.com/kubernetes-sigs/multi-tenancy/tenant go 1.13 require ( github.com/go-logr/logr v0.1.0 github.com/onsi/ginkgo v1.12.0 github.com/onsi/gomega v1.8.1 golang.org/x/net v0.0.0-20191004110552-13f9640d40b9 golang.org/x/sys v0.0.0-20200331124033-c3d80250170d // indirect k8s.io/api v0.17.2 k8s.io/apimachinery v0.17.2 k8s.io/client-go v0.17.2 sigs.k8s.io/controller-runtime v0.5.2 ) <file_sep>/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1alpha1 import ( "fmt" apivalidation "k8s.io/apimachinery/pkg/api/validation" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/webhook" ) // log is for logging in this package. var tenantlog = logf.Log.WithName("tenant-resource") func (r *Tenant) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). Complete() } // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // +kubebuilder:webhook:verbs=create;update,path=/validate-tenancy-x-k8s-io-v1alpha1-tenant,mutating=false,failurePolicy=fail,groups=tenancy.x-k8s.io,resources=tenants,versions=v1alpha1,name=vtenant.kb.io var _ webhook.Validator = &Tenant{} // ValidateCreate implements webhook.Validator so a webhook will be registered for the type func (r *Tenant) ValidateCreate() error { tenantlog.Info("validate create", "name", r.Name) allErrs := field.ErrorList{} for _, msg := range apivalidation.ValidateNamespaceName(r.Spec.TenantAdminNamespaceName, false) { allErrs = append(allErrs, field.Invalid(field.NewPath("spec").Child("tenantAdminNamespaceName"), r.Spec.TenantAdminNamespaceName, msg)) } return allErrs.ToAggregate() } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type func (r *Tenant) ValidateUpdate(old runtime.Object) error { oldObj := old.(*Tenant) tenantlog.Info("validate update", "name", r.Name) allErrs := field.ErrorList{} if r.Spec.TenantAdminNamespaceName != oldObj.Spec.TenantAdminNamespaceName { allErrs = append(allErrs, field.Forbidden(field.NewPath("spec").Child("tenantAdminNamespaceName"), fmt.Sprintf("cannot modify the tenantAdminNamespaceName field in spec after initial creation (attempting to change from %s to %s)", oldObj.Spec.TenantAdminNamespaceName, r.Spec.TenantAdminNamespaceName))) } if r.Spec.RequireNamespacePrefix != oldObj.Spec.RequireNamespacePrefix { allErrs = append(allErrs, field.Forbidden(field.NewPath("spec").Child("requireNamespacePrefix"), fmt.Sprintf("cannot modify the requireNamespacePrefix field in spec after initial creation (attempting to change from %v to %v)", oldObj.Spec.RequireNamespacePrefix, r.Spec.RequireNamespacePrefix))) } return allErrs.ToAggregate() } // ValidateDelete implements webhook.Validator so a webhook will be registered for the type func (r *Tenant) ValidateDelete() error { tenantnamespacelog.Info("validate delete", "name", r.Name) // TODO(user): fill in your validation logic upon object deletion. return nil } <file_sep>/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package controllers import ( "context" "fmt" tenantutil "github.com/kubernetes-sigs/multi-tenancy/tenant/controllers/util" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/util/retry" "github.com/go-logr/logr" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" tenancyv1alpha1 "github.com/kubernetes-sigs/multi-tenancy/tenant/api/v1alpha1" ) const ( // TenantAdminNamespaceAnnotation is the key for tenantAdminNamespace annotation TenantAdminNamespaceAnnotation = "x-k8s.io/tenantAdminNamespace" TenantNamespaceFinalizer = "tenantnamespace.finalizer.x-k8s.io" ) // TenantNamespaceReconciler reconciles a TenantNamespace object type TenantNamespaceReconciler struct { client.Client Log logr.Logger Scheme *runtime.Scheme } // +kubebuilder:rbac:groups=tenancy.x-k8s.io,resources=tenantnamespaces,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=tenancy.x-k8s.io,resources=tenantnamespaces/status,verbs=get;update;patch // +kubebuilder:rbac:groups=core,resources=namespaces,verbs=get;list;watch;create func (r *TenantNamespaceReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) { ctx := context.Background() log := r.Log.WithValues("tenantnamespace", req.NamespacedName) // Fetch the TenantNamespace instance instance := &tenancyv1alpha1.TenantNamespace{} err := r.Get(ctx, req.NamespacedName, instance) if err != nil { if errors.IsNotFound(err) { // Object not found, return. Created objects are automatically garbage collected. // For additional cleanup logic use finalizers. return ctrl.Result{}, nil } // Error reading the object - requeue the request. return ctrl.Result{}, err } // Fetch namespace list nsList := &corev1.NamespaceList{} err = r.List(ctx, nsList) if err != nil { return ctrl.Result{}, err } // Fetch tenant list tenantList := &tenancyv1alpha1.TenantList{} err = r.List(ctx, tenantList) if err != nil { return ctrl.Result{}, err } // Find the tenant of this instance requireNamespacePrefix := false var tenantName string for _, each := range tenantList.Items { if each.Spec.TenantAdminNamespaceName == instance.Namespace { requireNamespacePrefix = each.Spec.RequireNamespacePrefix tenantName = each.Name break } } if tenantName == "" { err = fmt.Errorf("TenantNamespace CR %v does not belong to any tenant", instance) return ctrl.Result{}, err } // Handle tenantNamespace CR deletion if instance.DeletionTimestamp != nil { // Remove namespace from tenant clusterrole if err = r.updateTenantClusterRole(ctx, log, tenantName, instance.Status.OwnedNamespace, false); err != nil { return ctrl.Result{}, err } else { instanceClone := instance.DeepCopy() if containsString(instanceClone.Finalizers, TenantNamespaceFinalizer) { instanceClone.Finalizers = removeString(instanceClone.Finalizers, TenantNamespaceFinalizer) } err = r.Update(ctx, instanceClone) return ctrl.Result{}, err } } // In case namespace already exists tenantNsName := tenantutil.GetTenantNamespaceName(requireNamespacePrefix, instance) expectedOwnerRef := metav1.OwnerReference{ APIVersion: tenancyv1alpha1.GroupVersion.String(), Kind: "TenantNamespace", Name: instance.Name, UID: instance.UID, } found := false for _, each := range nsList.Items { if each.Name == tenantNsName { found = true // Check OwnerReference isOwner := false for _, ownerRef := range each.OwnerReferences { if ownerRef == expectedOwnerRef { isOwner = true break } else if ownerRef.APIVersion == expectedOwnerRef.APIVersion && ownerRef.Kind == expectedOwnerRef.Kind { // The namespace is owned by another TenantNamespace CR, fail the reconcile err = fmt.Errorf("Namespace %v is owned by another %v TenantNamespace CR", each.Name, ownerRef) return ctrl.Result{}, err } } if !isOwner { log.Info("Namespace has been created without TenantNamespace owner", "namespace", each.Name) // Obtain namespace ownership by setting ownerReference, and add annotation if err = r.updateNamespace(log, &each, &instance.Namespace, &expectedOwnerRef); err != nil { return ctrl.Result{}, err } } break } } // In case a new namespace needs to be created if !found { tenantNs := &corev1.Namespace{ TypeMeta: metav1.TypeMeta{ APIVersion: corev1.SchemeGroupVersion.String(), Kind: "Namespace", }, ObjectMeta: metav1.ObjectMeta{ Name: tenantNsName, Annotations: map[string]string{ TenantAdminNamespaceAnnotation: instance.Namespace, }, OwnerReferences: []metav1.OwnerReference{expectedOwnerRef}, }, } if err = r.Client.Create(ctx, tenantNs); err != nil { return ctrl.Result{}, err } } // Update status instanceClone := instance.DeepCopy() err = retry.RetryOnConflict(retry.DefaultBackoff, func() error { if !containsString(instanceClone.Finalizers, TenantNamespaceFinalizer) { instanceClone.Finalizers = append(instanceClone.Finalizers, TenantNamespaceFinalizer) } instanceClone.Status.OwnedNamespace = tenantNsName updateErr := r.Update(ctx, instanceClone) if updateErr == nil { return nil } if err := r.Get(ctx, types.NamespacedName{Name: instance.Name, Namespace: instance.Namespace}, instanceClone); err != nil { log.Info("Fail to fetch tenantNamespace CR on update", "tenantNamespace", instance.Name) } return updateErr }) if err != nil { return ctrl.Result{}, err } // Add namespace to tenant clusterrule to allow tenant admins to access it. err = r.updateTenantClusterRole(ctx, log, tenantName, tenantNsName, true) return ctrl.Result{}, nil } func (r *TenantNamespaceReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&tenancyv1alpha1.TenantNamespace{}). Owns(&corev1.Namespace{}). Complete(r) } // This method updates tenant clusterrule to add or remove the tenant namespace. func (r *TenantNamespaceReconciler) updateTenantClusterRole(ctx context.Context, log logr.Logger, tenantName, tenantNsName string, add bool) error { var err error cr := &rbacv1.ClusterRole{} if err = r.Get(ctx, types.NamespacedName{Name: fmt.Sprintf("%s-tenant-admin-role", tenantName)}, cr); err != nil { return err } cr = cr.DeepCopy() foundNsRule := false needUpdate := add for i, each := range cr.Rules { for _, resource := range each.Resources { if resource == "namespaces" { foundNsRule = true break } } if foundNsRule { idx := 0 for ; idx < len(each.ResourceNames); idx++ { if each.ResourceNames[idx] == tenantNsName { needUpdate = !add break } } if needUpdate { if add { cr.Rules[i].ResourceNames = append(cr.Rules[i].ResourceNames, tenantNsName) } else { cr.Rules[i].ResourceNames = append(cr.Rules[i].ResourceNames[:idx], cr.Rules[i].ResourceNames[idx+1:]...) } } break } } if !foundNsRule { return fmt.Errorf("Cluster Role %s-tenant-admin-role does not have rules for namespaces.", tenantName) } if needUpdate { crClone := cr.DeepCopy() err = retry.RetryOnConflict(retry.DefaultBackoff, func() error { crClone.Rules = cr.Rules updateErr := r.Update(ctx, crClone) if updateErr == nil { return nil } if err := r.Get(ctx, types.NamespacedName{Name: crClone.Name}, crClone); err != nil { log.Info("Fail to fetch clusterrole on update", "clusterrole", crClone.Name) } return updateErr }) } return err } // Helper functions to check and remove string from a slice of strings. func containsString(slice []string, s string) bool { for _, item := range slice { if item == s { return true } } return false } func removeString(slice []string, s string) (result []string) { for _, item := range slice { if item == s { continue } result = append(result, item) } return } // Add a ownerReference and tenant admin namespace annotation to input namespace func (r *TenantNamespaceReconciler) updateNamespace(log logr.Logger, ns *corev1.Namespace, tenantAdminNamespaceName *string, ownerRef *metav1.OwnerReference) error { nsClone := ns.DeepCopy() err := retry.RetryOnConflict(retry.DefaultBackoff, func() error { nsClone.OwnerReferences = append(nsClone.OwnerReferences, *ownerRef) if nsClone.Annotations == nil { nsClone.Annotations = make(map[string]string) } nsClone.Annotations[TenantAdminNamespaceAnnotation] = *tenantAdminNamespaceName updateErr := r.Update(context.TODO(), nsClone) if updateErr == nil { return nil } key := types.NamespacedName{ Name: nsClone.Name, } if err := r.Get(context.TODO(), key, nsClone); err != nil { log.Info("Fail to fetch namespace on update failure", "namespace", nsClone.Name) } return updateErr }) return err }
a1695e3bd3d47765e44a7e3af8f932277900906c
[ "Go Module", "Go" ]
4
Go
minsheng-fintech-corp-ltd/multi-tenancy
19e4e70993f859162f5c79fb811948e2ffc2e1a1
0cd11d60ee4b3e0c267d0d7d4985fd3fc28761f1
refs/heads/master
<file_sep>const {remote} = require('electron'); const path = require('path'); const currentWindow = remote.getCurrentWindow(); function setThumbnailToolbar() { currentWindow.setThumbarButtons([{ tooltip: 'rewind', icon: path.join(__dirname, 'rewind.png') }, { tooltip: this.state === 'play' ? 'pause' : 'play', icon: path.join(__dirname, 'play.png') }, { tooltip: 'forward', icon: path.join(__dirname, 'forward.png') }]); alert('Please check task bar'); } function clearThumbnailToolbar() { currentWindow.setThumbarButtons([]); } function goFullScreen() { currentWindow.setFullScreen(true); } function exitFullScreen() { currentWindow.setFullScreen(false); } function hideAndShow() { currentWindow.hide(); setTimeout(() => currentWindow.show(), 2000); } function skipTaskbar() { currentWindow.setSkipTaskbar(true); } function showInTaskbar() { currentWindow.setSkipTaskbar(false); } function autoTest(type) { switch(type) { case 'fullscreen': setThumbnailToolbar(); goFullScreen(); setTimeout(exitFullScreen, 1000); setTimeout(setThumbnailToolbar, 2000); break; case 'visible': setThumbnailToolbar(); hideAndShow(); setTimeout(setThumbnailToolbar, 3000); break; case 'taskbar': setThumbnailToolbar(); skipTaskbar(); setTimeout(showInTaskbar, 1000); setTimeout(setThumbnailToolbar, 2000); } }
6f7f55c73b2fd31f5e66ab84d72fe54b4db16d95
[ "JavaScript" ]
1
JavaScript
codehz/electron-test
d54e68c2a2ebed9cb4aa49317b44c86da1a7cf10
d9a7be9df5d7184ffdfaefc422a48e34043e1d87
refs/heads/master
<file_sep>#!/bin/bash RED=$(tput setaf 1) GREEN=$(tput setaf 2) CYAN=$(tput setaf 6) BRIGHT=$(tput bold) NORMAL=$(tput sgr0) printf "\n%s" "Download your ${BRIGHT}jwt${NORMAL} user code by clicking here:" printf "\nhttps://project-assistant.udacity.com/auth_tokens/new \n" printf "\n%s" "You may need to ${BRIGHT}navigate to the link a second time${NORMAL} after logging in for the file to automatically download." printf "\n%s" "Once you've downloaded your ${BRIGHT}jwt${NORMAL}, copy the contents into: ${CYAN}${BRIGHT}/home/workspace/JWT/jwt${NORMAL}." printf "\n%s" "You can then submit your project by entering ${BRIGHT}submit${NORMAL} into the commandline." printf "\n" <file_sep># Robotics-ND Robotics Software Engineer Nanodegree
c7f96d7dc731e01c0e66dcc2dbb6a7af7cd23b50
[ "Markdown", "Shell" ]
2
Shell
jjdiep/Robotics-ND
fd7acd6ddb1696c26d53977c2cff87a88b9a40ad
5c07109278d1f239444a2cd404853209b314a54e
refs/heads/master
<repo_name>alfreedom/stm8-WaterPump<file_sep>/main.c /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * main.c * * Autor: <NAME> * Fecha: Mayo 1 del 2017 * Versión: 1.0 * * Descripción: * * Temporizador de encendido para Bomba de Agua. * * Este programa controla el tiempo de encendido de * una bomba de agua usada para bombear el liquido al * tinaco de un edificio. * * El circuito utiliza un relevador de estado sólido para * el control del la bomba de agua, 2 displays de 7 * segmentos para visualizar el tiempo de trabajo y 3 * botones para cambiar el tiempo de trabajo y para * iniciar o detener el temporizador. * * Para más detalles de la conexión, ver el esquemático. * * Copyright© <NAME> <<EMAIL>> * *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ #include "stm8happy.h" // Hay que habilitar los módulos a usar en el archivo stm8happy_cfg.h #include "tim2.h" // Bilbioteca para el manej del Timer 2. #include "gpio.h" // Bilbioteca para el manejo de los GPIO. #include "itc.h" // Biblioteca para el manejo de interrupciones. #define MAX_TIME_RUNNING 55 // Tiempo máximo que puede funcionar el sistema. #define ANIMATION_DURATION_SHORT 8 // Duración corta para animación. #define ANIMATION_DURATION_NORMAL 16 // Duración media para animación. #define ANIMATION_DURATION_LONG 26 // Duración larga para animación. #define LED_BOARD_GPIO GPIOB // Puerto GPIO para el led de la tarjeta. #define LED_BOARD GPIO_PIN_5 // Pin del led de la tarjeta. #define BOMBA_GPIO GPIOA // Puerto GPIO para el relay de la bomba #define BOMBA_PIN GPIO_PIN_3 // Pin del relay de la bomba. #define BOTONES_GPIO GPIOD // Puerto GPIO para los botones #define BOTON_MENOS GPIO_PIN_4 // Pin del botón - #define BOTON_MAS GPIO_PIN_5 // Pin del botón + #define BOTON_START GPIO_PIN_6 // Pin del boton de INICIO // Máscara de bits de los pines de los botones. #define BOTONES_MASK ( BOTON_MAS | BOTON_MENOS | BOTON_START ) #define DISPLAY_1_GPIO GPIOD // Primer puerto GPIO para los displays #define DISPLAY_2_GPIO GPIOC // Segundo puerto GPIO para los displays #define DISPLAY_A GPIO_PIN_3 // Pin del segmento A del display. #define DISPLAY_B GPIO_PIN_2 // Pin del segmento B del display. #define DISPLAY_C GPIO_PIN_1 // Pin del segmento C del display. #define DISPLAY_D GPIO_PIN_7 // Pin del segmento D del display. #define DISPLAY_E GPIO_PIN_6 // Pin del segmento E del display. #define DISPLAY_F GPIO_PIN_5 // Pin del segmento F del display. #define DISPLAY_G GPIO_PIN_4 // Pin del segmento G del display. // Máscara de bits 1 de los pines del display #define DISPLAY_1_MASK ( DISPLAY_A | DISPLAY_B | DISPLAY_C ) // Máscara de bits 2 de los pines del display #define DISPLAY_2_MASK ( DISPLAY_D | DISPLAY_E | DISPLAY_F | DISPLAY_G ) #define DISPLAY_1_EN_GPIO GPIOC // Puerto GPIO para la habilitación del display 1 #define DISPLAY_1_EN GPIO_PIN_3 // Pin de habilitación del display 1 #define DISPLAY_2_EN_GPIO GPIOB // Puerto GPIO para la habilitación del display 2 #define DISPLAY_2_EN GPIO_PIN_4 // Pin de habilitación del display 2 /** * @brief Funcion de retardo * * @param[in] count Intervalo a demorar. */ void delay(uint32_t count); /** * @brief Inicializa el sistema * * Hace las llamadas a las funciones de configuración * de los módulos del sistema a utilizar. */ void System_Init(); /** * @brief Inicializa el Timer 2 (TIM2) * * Configura el TIM2 para que genere una interrupción * cada 1 segundo, se utiliza para contar tiempo. */ void TIM2_Init(); /** * @brief Inicializa el LED de la tarjeta */ void LED_Init(); /** * @brief Inicializa el pin para el relevador. * * Configura el pin conectado al relevador para la * bomba como salida. */ void BombaRelay_Init(); /** * @brief Inicializa los displays de 7 segmentos * configurando sus pines. */ void Displays_Init(); /** * @brief Inicializa los botones. * * Inicializa los botones para el control del sistema. * Habilita la interrupción para atender cada pulsación * de los botones. */ void Botones_Init(); /** * @brief Envía un dato al display. * * Envía el dato separando sus bits para * cada pin del display. * * @param[in] data Dato codificado a mostrar en el display. */ void WriteDisplayData(uint8_t data); /** * @brief Muestra un número en los displays. * * Muestra un número en formato decimal en los displays, * separando las unidades y las decenas, para posteriormente * ser enviados a cada display por separado, haciendo el * efecto de que ambos displays están encendidos al mismo * tiempo (POV) * * @param[in] numero Número a mostrar en los displays */ void MuestraNumeroDisplays(unsigned char numero); /** * @brief Enciende la bomba de agua. * * Activa el relevador de la bomba de agua. */ void Enciende_Bomba(); /** * @brief Apaga la bomba de agua. * * Desactiva el relevador de la bomba de agua. */ void Apaga_Bomba(); /** * @brief Inicia el sistema de temporización. * * Esta función ejecuta las acciones para inciar la * temporización del sistem: enciende la bomba * y activa el timer para contar el tiempo transcurrido. */ void System_Start(); /** * @brief Detiene el sistema de temporización. * * Esta función detiene la temporización. Reinicia los * contadores de tiempo, apaga la bomba y detiene el * timer de conteo. */ void System_Stop(); /** * @brief Muestra una animación en los displays. * * Muestra una animación de parpadeo en los displays. * La animacíón se muestra en ambos displays, y la * duración es el numero de parpadeos que hace la animación. * * @param[in] show Dato a enviar por los displays. * @param[in] duration Número de repeticiones de la animación. */ void System_EndAnimation(uint8_t show, uint8_t duration); volatile uint8_t seconds; // Guarda los segundos transcurridos de la temporización volatile uint8_t minutes; // Guarda los minutos transcurridos de la temporización volatile uint8_t is_running; // Guarda el estado del sistema, si esta corriendo o no. volatile uint8_t time_left; // Guarda el tiempo restante de trabajo del sistema. uint8_t user_minutes; // Guarda los minutos de trabajo ingresados por el usuario uint8_t display_codes[10] = { // Arreglo con los digitos codificados para el display. 0x3F, // 0 0x06, // 1 0x5B, // 2 0x4F, // 3 0x66, // 4 0x6D, // 5 0x7D, // 6 0x07, // 7 0x7F, // 8 0x6F, // 9 }; /** * @brief Funcion de servicio de interrupción para manejar * el desbordamiento del TIMER2 cada segundo. */ void TIM2_OVF_IRQ() { seconds++; if(seconds == 60){ seconds=0; minutes++; if(minutes >= MAX_TIME_RUNNING) System_Stop(); time_left = user_minutes - minutes; } // Si terminó el tiempo, apaga el sistema if(time_left == 0) { System_Stop(); System_EndAnimation(0x40, ANIMATION_DURATION_NORMAL); } ClearBit(TIM2_SR1, TIM2_SR1_UIF); } /** * @brief Función para manejar la interrupción externa en el pin 3 * del puerto GPIOD configurado como interrupción en flanco * de bajada. */ void EXTI_PORTD_IRQ() { uint8_t butons_state; // Guarda el estado de los botones. butons_state = GPIORead(BOTONES_GPIO); // Desactiva interrupción externa en los botones GPIODisableExtInt(BOTONES_GPIO, BOTONES_MASK); // Si se presiona el boton de inicio... MuestraNumeroDisplays(user_minutes); if((butons_state & BOTON_START) == LOW) { // Espera a que se suelte el botón while((GPIORead(BOTONES_GPIO) & BOTON_START) == LOW) MuestraNumeroDisplays(user_minutes); // Si la temporización está iniciada, la detiene y muestra animación. if(is_running == TRUE) { System_Stop(); System_EndAnimation(0x40, ANIMATION_DURATION_NORMAL); } else // Si la temporización está detenida, la inicia. { System_Start(); delay(0xffff); } } else // Si se presionó el boton - ... if((butons_state & BOTON_MENOS) == LOW) { // Espera a que se suelte el botón while((GPIORead(BOTONES_GPIO) & BOTON_MENOS)== LOW) MuestraNumeroDisplays(user_minutes); // Si no está corriendo la temporización, decrementa el tiempo de temporización. if(is_running == FALSE) { user_minutes--; if(user_minutes==0) user_minutes = MAX_TIME_RUNNING; } else { // Si el sistema está corriendo, muestra animación de advertencia System_EndAnimation(0x79, ANIMATION_DURATION_SHORT); } } else // Si se presionó el boton + ... if((butons_state & BOTON_MAS) == LOW) { // Espera a que se suelte el botón while((GPIORead(BOTONES_GPIO) & BOTON_MAS) == LOW) MuestraNumeroDisplays(user_minutes); // Si no está corriendo la temporizacipon, incrementa el tiempo de temporización. if(is_running == FALSE) { user_minutes++; if(user_minutes> MAX_TIME_RUNNING) user_minutes = 1; } else {// Si el sistema está corriendo, muestra animación de advertencia System_EndAnimation(0x79, ANIMATION_DURATION_SHORT); } } // Activa de nuevo las interrupción externas en los botones GPIOEnableExtInt(BOTONES_GPIO, BOTONES_MASK); } /** * Función main. */ void main() { // Inicializa el sistema System_Init(); // Ciclo infinito y más allá. while(TRUE){ // Si la temporización esta corriendo .. if(is_running){ if( !(seconds%2)) { // Muestra el tiempo de temporización restante MuestraNumeroDisplays(time_left); } else{ // Apaga los displays GPIOWriteBit(DISPLAY_1_EN_GPIO, DISPLAY_1_EN, LOW); GPIOWriteBit(DISPLAY_2_EN_GPIO, DISPLAY_2_EN, LOW); } } else { // Si la temporización no está corriendo, muestra el tiempo // de temporización ingresado por el usuario. MuestraNumeroDisplays(user_minutes); } } } void System_Init() { /* Deshabilita todas las interrupciones. */ DisableInterrupts(); CLK_CKDIVR = 0; // Frecuencia del CPU a 16 MHz BombaRelay_Init(); Displays_Init(); Botones_Init(); LED_Init(); TIM2_Init(); System_Stop(); user_minutes = 1; /* Habilita todas las interrupciones. */ EnableInterrupts(); } void System_Start() { time_left = user_minutes; // Enciende el LED GPIOWriteBit(LED_BOARD_GPIO, LED_BOARD, LOW); // Enciende la bomba Enciende_Bomba(); // Inicia el timer. // Reinicia contadores TIM2_CNTRH = 0; TIM2_CNTRL = 0; seconds = 0; minutes = 0; TIM2Start(); is_running = TRUE; } void System_Stop() { // Apaga la bomba Apaga_Bomba(); // Detiene el timer TIM2Stop(); // Apaga el led GPIOWriteBit(LED_BOARD_GPIO, LED_BOARD, HIGH); is_running = FALSE; } void System_EndAnimation(uint8_t show, uint8_t duration) { unsigned char i; // Envía el dato a los displays. WriteDisplayData(show); for (i = 0; i < duration; ++i) { if(!(i%2)){ // Apaga ls displays GPIOWriteBit(DISPLAY_1_EN_GPIO, DISPLAY_1_EN, HIGH); GPIOWriteBit(DISPLAY_2_EN_GPIO, DISPLAY_2_EN, HIGH); } else{ // Enciende ls displays GPIOWriteBit(DISPLAY_1_EN_GPIO, DISPLAY_1_EN, LOW); GPIOWriteBit(DISPLAY_2_EN_GPIO, DISPLAY_2_EN, LOW); } // Retardo de la animación delay(0xFFFF); } } void Enciende_Bomba() { // Habilita el relevador de la bomba GPIOWriteBit(BOMBA_GPIO, BOMBA_PIN, HIGH); } void Apaga_Bomba() { // Deshabilita el relevador de la bomba GPIOWriteBit(BOMBA_GPIO, BOMBA_PIN, LOW); } void WriteDisplayData(uint8_t data) { uint8_t display_data; // obtiene los bits para el primer puerto del display display_data = ((data & 1) << 3) | ((data & 2) << 1) | ((data & 4) >>1); // Envía los bits al primer puerto del display GPIOWrite(DISPLAY_1_GPIO, display_data); // Obtiene los bits para el segundo puerto del display display_data = ((data & 8) << 4) | ((data & 16) << 2) | (data & 32) | ((data & 64) >>2); // Envía los bits al segundo puerto del display GPIOWrite(DISPLAY_2_GPIO, display_data); } void MuestraNumeroDisplays(unsigned char numero) { uint8_t dec, uni; // Calcula decenas dec = numero / 10; // Calcula unidades uni = numero % 10; // Obtiene la decodificación de las decenas para el display dec = display_codes[dec]; // Obtiene la decodificación de las unidaes para el display uni = display_codes[uni]; // Envía las decenas al primer display WriteDisplayData(dec); // Enciende el primer display GPIOWriteBit(DISPLAY_1_EN_GPIO, DISPLAY_1_EN, HIGH); // Espera un tiempo para visualizar el display delay(0xfff); // Apaga el primer display GPIOWriteBit(DISPLAY_1_EN_GPIO, DISPLAY_1_EN, LOW); // Envía las unidades al segundo display WriteDisplayData(uni); // Enciende el segundo display GPIOWriteBit(DISPLAY_2_EN_GPIO, DISPLAY_2_EN, HIGH); // Espera un tiempo para visualizar el display delay(0xfff); // Apaga el segundo display GPIOWriteBit(DISPLAY_2_EN_GPIO, DISPLAY_2_EN, LOW); } void delay(uint32_t count){ uint32_t i; for (i = 0; i < count; ++i) NOP(); } void LED_Init() { // Pin del led configurado como salida Open Drain (activo en bajo) GPIOInit(LED_BOARD_GPIO, LED_BOARD, GPIO_MODE_OUT_OD); GPIOWriteBit(LED_BOARD_GPIO, LED_BOARD, HIGH); } void TIM2_Init(){ // Habilita el reloj de periferico TIM2 SetBit(CLK_PCKENR1, CLK_PCKENR1_TIM2); // TIM2 a 3906.25 HZ, contando de 0 a 4096 TIM2_CR1 = 0; TIM2_PSCR = TIM2_PRESCALER_4096; TIM2_ARRH = 0x0F; TIM2_ARRL = 0x2F; SetBit(TIM2_IER, TIM2_IER_UIE); } void BombaRelay_Init() { // Configura el pin del relevador de la bomba como // salida Push Pull GPIOWriteBit(BOMBA_GPIO, BOMBA_PIN, LOW); GPIOInit(BOMBA_GPIO, BOMBA_PIN, GPIO_MODE_OUT_PP); } void Displays_Init() { // Pines de datos del display como salida GPIOInit(DISPLAY_1_GPIO, DISPLAY_1_MASK, GPIO_MODE_OUT_PP); GPIOInit(DISPLAY_2_GPIO, DISPLAY_2_MASK, GPIO_MODE_OUT_PP); // Pines de habilitación de los displays como salida GPIOInit(DISPLAY_1_EN_GPIO, DISPLAY_1_EN, GPIO_MODE_OUT_PP); GPIOInit(DISPLAY_2_EN_GPIO, DISPLAY_2_EN, GPIO_MODE_OUT_PP); // Limpia los displays GPIOWriteBit(DISPLAY_1_GPIO, DISPLAY_1_MASK, LOW); GPIOWriteBit(DISPLAY_2_GPIO, DISPLAY_2_MASK, LOW); // Apaga los displays GPIOWriteBit(DISPLAY_1_EN_GPIO, DISPLAY_1_EN, LOW); GPIOWriteBit(DISPLAY_2_EN_GPIO, DISPLAY_2_EN, LOW); } void Botones_Init() { // Configura puerto de los botones como salida GPIOInit(BOTONES_GPIO, BOTONES_MASK, GPIO_MODE_IN_PU); // Habilita la interrupción externa en los botones GPIOEnableExtInt(BOTONES_GPIO, BOTONES_MASK); // Configura interrupción en flanco de bajada. ITCSenseGPIOD(ITC_SENSE_FALLING); } <file_sep>/Makefile # Project Name PROJECT_NAME = BombaAgua # Project versión VERSION = 1_0 # Microcontroller Model CPU = stm8s103f3 # CPU speed in Hz CPU_FREQ = 16000000 # Source files to compile SOURCE_FILES = main.c #SOURCE_FILES += other source.c # stm8happy framework installation PATH STM8HAPPY_PATH = ../../stm8happy/stm8happy # Path for extra include files EXTRA_INCLUDE_PATH = ./ # stm8happy internals. include $(STM8HAPPY_PATH)/tools/Makefile.common <file_sep>/stm8happy_cfg.h #ifndef STM8HAPPY_CONFIG #define STM8HAPPY_CONFIG /** * Enable the GPIO hal driver. */ #define USE_GPIO 1 /** * Enable the ADC1 hal driver. */ #define USE_ADC1 0 /** * Enable the BEEPER hal driver. */ #define USE_BEEPER 1 /** * Enable the I2C hal driver. */ #define USE_I2C 0 /** * Enable the TIM1 hal driver. */ #define USE_TIM1 0 /** * Enable the TIM2 hal driver. */ #define USE_TIM2 1 /** * Enable the CAN hal driver. */ #define USE_CAN 0 /** * Enable the ITC hal driver. */ #define USE_ITC 1 /** * Enable the SPI hal driver. */ #define USE_SPI 0 /** * Enable the UART1 hal driver. */ #define USE_UART1 0 #endif // STM8HAPPY_CONFIG<file_sep>/README.md # stm8-WaterPump Temporizador para encendido de una bomba de agua. El programa esta echo para el microcontrolador stm8s103f3p6 con el framework stm8happy.
6ce054e9492d96edc7a2f34d40aff119fea55c68
[ "Markdown", "C", "Makefile" ]
4
C
alfreedom/stm8-WaterPump
f2d353772de4fc040de3fad3e6357fa0a6005a15
0c3ef6bcdf7eaa88b2a88d203afd25ec1f19c660
refs/heads/master
<repo_name>aquiles7/MODASDIEGO2020<file_sep>/php/enviar.php <?php // Llamando a los campos $name = $_POST['nombre']; $email = $_POST['direccion']; $phone = $_POST['telefono']; $subject = $_POST['asunto']; $message = $_POST['mensaje']; // Datos para el correo $addressee = "<EMAIL>"; $who = "<NAME>"; $letter = "A: $who \n"; $letter .= " $message \n"; $letter .= "Para mayor información, puede contacterse con mi persona al email $email o al teléfono $phone. \n"; $letter .= "De: $name"; // Enviando mensaje mail($addressee, $subject, $letter); header('Location: ../contact.html') ?> <file_sep>/us.html <!DOCTYPE html> <html> <head> <title>Modas Diego | Nosotros</title> <meta charset="utf-8"> <meta name="viewport" content="width=devise-width, user-scalable=no, initial-scale=1, maximun-scale=1, minimun-scale=1"> <link rel="stylesheet" href="css/estilos.css"> <link href="img/logo_icon2.png" rel="shortcut icon" type="image/x-icon" /> <script src="js/jquery-3.2.1.js"></script> <script src="js/all.js"></script> <script src="js/scrollTop.js"></script> </head> <body> <header> <div class="info"> <img src="img/Logo.png" alt=""> <div class="link"> <a>962-297-852 <span class="icon fab fa-whatsapp"></span></a> </div> </div> <div class="nav"> <ul class="menu" id="menu"> <div class="more left" id="left"> <i class="fas fa-chevron-left"></i> </div> <li><a href="index.html">Inicio</a></li> <li class="active"><a href="#">Nosotros</a></li> <li><a href="prod.html">Productos</a></li> <li class="des"><a href="contact.html">Contactenos</a></li> <div class="more right" id="right"> <i class="fas fa-chevron-right"></i> </div> </ul> </div> </header> <script> $(document).ready(function(){ var scroll = 0; $('#left').click(function(){ scroll -= 80; $('#menu').scrollLeft(scroll); }); $('#right').click(function(){ scroll += 80; $('#menu').scrollLeft(scroll); }); }) </script> <div class="next ab_us"> <div class="banner"><img src="img/nosotros.jpg" alt=""></div> <div class="info"> <div class="titulo">NOSOTROS</div> <div class="descrip"> <p>Modas Diego es creada en el año 2010 , en esa época La tienda contaba con productos que hacian falta hacia la clientela pero al cabo del tiepo se fue reforsando llegando hacia a varios hogares , a diferentes tipos de eventos con relación a los deportes de acción entre otros , donde lo principal de tienda es enfocarse en la moda urbana y asi llegar a mas lugares hoy en dia la tienda de esncuentra ubicada en Nuevo Horizonte, Distrito Polvora, Region San Martin</p> <p>En esta tienda la marca Gzuck es una de las mas represesntativas de la tienda ya que se tiene un convenio y por ello este marca que representa a una comunidad que tiene la creencia de seguir el instinto y vivir apasionadamente por aquello que más les gusta, reflejado en el estilo urbano. La rebeldía y la anarquía son los rasgos más importantes de la marca, sim embrago a pesar de esta maraca cuenta con mas marcas de prendas para la clientela.</p> <p>La meta de este negocio es vender productos de alta calidad para aquellos que comparten su pasión por la moda urbana La convicción de este negocio es “vender innovadoras ” determinando su disposición a entender los constantes cambios y diversidad que hay en el mundo y su capacidad de integrarlas en toda su expresión comunicacional y comercial.</p> <p>Sus productos que incluyen zapatillas, ropa urbana,accesorios, para hombre y Mujer logran un estilo único que combina calidad, durabilidad y comodidad. Entre las principales colecciones originales de cada marca en especial Gzuck.</p> <p> <NAME> <i class="fas fa-angle-double-left"></i> Join the crew <i class="fas fa-angle-double-right"></i></p> </div> </div> </div> <button id="btn_top"><i class="icon fas fa-arrow-alt-circle-up"></i></button> <footer> <p class="notice">Estimado cliente, si tiene alguna duda o desea realizar compras al por mayor, por favor comuniquese al número 01(4595152) anexo 256 en horario de 9:00 a.m a 6:00 p.m o al e-mail servicio al <EMAIL></p> <p class="right">© <NAME> - 2019. Todos los derechos reservados.</p> </footer> </body> </html>
36e70e014e018fdb068429cb8627872d35043eb1
[ "HTML", "PHP" ]
2
PHP
aquiles7/MODASDIEGO2020
d2d86b20b5cf501862d4ad72307fbde6ee76455a
b7fa9af5ddeccd0c064f2179acb0de2e639663ff
refs/heads/master
<file_sep>using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace app.WebApi.Model { public class Natural_person { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Key, Required] public int Id { get; set; } [Required] public int Id_Customer { get; set; } public Customers Customers { get; set; } [Column(TypeName = "char(14)")] public string Cpf { get; set; } } }<file_sep>using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace app.WebApi.Model { public class Products { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Key, Required] public int Id { get; set; } public string Name { get; set; } public int Amount { get; set; } [Column(TypeName = "decimal(37, 2)")] public int Price { get; set; } [Required] public int Id_categories { get; set; } public Categories Categories { get; set; } } }<file_sep>using Microsoft.EntityFrameworkCore; using app.WebApi.Model; namespace app.WebApi.Data { public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options) : base(options) { } public DbSet<Categories> Category { get; set; } public DbSet<Customers> Customer { get; set; } public DbSet<Natural_person> Natural_person { get; set; } public DbSet<Products> Products { get; set; } } }<file_sep>using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace app.WebApi.Model { public class Customers { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Key, Required] public int Id { get; set; } [Column(TypeName = "varchar(255)")] public string Name { get; set; } [Column(TypeName = "varchar(255)")] public string Street { get; set; } [Column(TypeName = "varchar(255)")] public string City { get; set; } [Column(TypeName = "char(2)")] public string State { get; set; } [Column(TypeName = "decimal(37, 2)")] public decimal Credit_Limit { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using app.WebApi.Model; using Microsoft.AspNetCore.Mvc; namespace app.WebApi.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<Customers>> Get() { return new Customers[] { new Customers() { Id = 1, Name = "<NAME>", Street = "Acesso Um", City = "Porto Alegre", State = "RS", Credit_Limit = 475 }, new Customers() { Id = 2, Name = "<NAME>", Street = "Rua Sizuka Usuy", City = "Cianorte", State = "PR", Credit_Limit = 3170 } }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult<Customers> Get(int id) => new Customers[] { new Customers() { Id = 1, Name = "<NAME>", Street = "Acesso Um", City = "Porto Alegre", State = "RS", Credit_Limit = 475 }, new Customers() { Id = 2, Name = "<NAME>", Street = "Rua Sizuka Usuy", City = "Cianorte", State = "PR", Credit_Limit = 3170 } }.FirstOrDefault(x => x.Id == id); // POST api/values [HttpPost] public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } } <file_sep>using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace app.WebApi.Migrations { public partial class efInicial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Category", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Category", x => x.Id); }); migrationBuilder.CreateTable( name: "Customer", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(type: "varchar(255)", nullable: true), Street = table.Column<string>(type: "varchar(255)", nullable: true), City = table.Column<string>(type: "varchar(255)", nullable: true), State = table.Column<string>(type: "char(2)", nullable: true), Credit_Limit = table.Column<decimal>(type: "decimal(37, 2)", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Customer", x => x.Id); }); migrationBuilder.CreateTable( name: "Products", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), Amount = table.Column<int>(nullable: false), Price = table.Column<decimal>(type: "decimal(37, 2)", nullable: false), Id_categories = table.Column<int>(nullable: false), CategoriesId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Products", x => x.Id); table.ForeignKey( name: "FK_Products_Category_CategoriesId", column: x => x.CategoriesId, principalTable: "Category", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Natural_person", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Id_Customer = table.Column<int>(nullable: false), CustomersId = table.Column<int>(nullable: true), Cpf = table.Column<string>(type: "char(14)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Natural_person", x => x.Id); table.ForeignKey( name: "FK_Natural_person_Customer_CustomersId", column: x => x.CustomersId, principalTable: "Customer", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Natural_person_CustomersId", table: "Natural_person", column: "CustomersId"); migrationBuilder.CreateIndex( name: "IX_Products_CategoriesId", table: "Products", column: "CategoriesId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Natural_person"); migrationBuilder.DropTable( name: "Products"); migrationBuilder.DropTable( name: "Customer"); migrationBuilder.DropTable( name: "Category"); } } }
958ae8f8841acaebf3ba75372545cd1930cc337b
[ "C#" ]
6
C#
jvsilvafilho-sjc/lifedental
a7f68b86d3827e91c21229fd856c21f2622dd4e1
11906d34224533bcd130e61edc9fac977a770ef4
refs/heads/master
<file_sep>/** Account API Wrapper */ module.exports = class Account { /** * Create an Account Client * @param {Object} binanceApiClient - Binance API Client */ constructor(binanceApiClient) { this.binanceApiClient = binanceApiClient } /** * Get balances with a positive free amount from Binance Account * @return {Array.<Object>} Binance Account Balances */ async getBalances() { const accountInfos = await this.binanceApiClient.fetchApi('/api/v3/account') const { balances } = accountInfos return balances.filter(balance => Number(balance['free'])) } } <file_sep># Binance Savings Rebalancer / CHANGELOG ### v1.1.0 (2020-12-04) * Add JSDoc documentation comments * Rename `Fixed Savings` to `Locked Savings` similar to Binance ### v1.0.0 (2020-12-03) * Initial release <file_sep>/** * Required module */ const helpers = require('./helpers') /** Locked Savings API Wrapper */ module.exports = class Locked { /** * Create a Locked Savings Client * @param {Object} binanceApiClient - Binance API Client * @param {Array.<Object>} accountBalances - Account Balances */ constructor(binanceApiClient, accountBalances) { this.binanceApiClient = binanceApiClient this.accountBalances = helpers.stripLendingPrefix(accountBalances) } /** * Get available Locked Savings projects * @return {Array.<Object>} Available projects */ async getAvailableProjects() { const projects = await this.binanceApiClient.fetchApi( '/sapi/v1/lending/project/list', { type: 'CUSTOMIZED_FIXED', status: 'SUBSCRIBABLE', size: 100 } ) return helpers.filterEqualAssetsByLots( this.accountBalances, helpers.reduceAssetsByInterestRate(projects) ) } /** * Purchase Locked Savings projects * @param {Array.<Object>} projects - Locked Savings projects to purchase */ async purchaseProjects(projects) { await Promise.all( projects.map(async project => { const { projectId, free, lotSize, maxLotsPerUser } = project const lot = Math.min((free / lotSize), maxLotsPerUser) await this.binanceApiClient.fetchApi( '/sapi/v1/lending/customizedFixed/purchase', { projectId, lot }, { method: 'POST' } ) helpers.log('Purchase a Locked Savings project', [project]) }) ) } } <file_sep>/** * Required modules */ const helpers = require('./libs/helpers') const binanceApi = require('./libs/binance-api') const binanceApiClient = new binanceApi(process.env['API_KEY'], process.env['API_SECRET']) const Locked = require('./libs/locked') const Account = require('./libs/account') const Activities = require('./libs/activities') const Flexible = require('./libs/flexible') ;(async () => { const account = new Account(binanceApiClient) const accountBalances = await account.getBalances() const flexibleBalances = accountBalances.filter(x => x['asset'].startsWith('LD')) /** * Activities */ const activities = new Activities(binanceApiClient, accountBalances) activities.getAvailableProjects().then(async projects => { const redeemProjects = helpers.filterEqualAssets(flexibleBalances, projects) redeemProjects && await flexible.redeemProducts(redeemProjects) await activities.purchaseProjects(projects) }) /** * Locked Savings */ const locked = new Locked(binanceApiClient, accountBalances) locked.getAvailableProjects().then(async projects => { const redeemProjects = helpers.filterEqualAssets(flexibleBalances, projects) redeemProjects && await flexible.redeemProducts(redeemProjects) await locked.purchaseProjects(projects) }) /** * Flexible Savings */ const flexible = new Flexible(binanceApiClient, accountBalances, flexibleBalances) flexible.getAvailableProducts().then(async products => { await flexible.purchaseProducts(products) }) })() <file_sep><p align="center"> <b>Binance Savings Rebalancer</b> <br> A 🤖 for transfers between Binance Savings for higher interest rates </p> Binance offers 3 types of savings accounts: *Flexible Savings* (deposit and redeem anytime), *Locked Savings* (flexible deposits, higher profits) and *Activities* (limited supply, higher demand). Savings accounts are unpredictable: different projects for different coins for different durations for different interest rates. 🤖 checks the Binance API for new financial products and moves coins from account balances into available Savings projects. If necessary, the 🤖 redeems coins from *Flexible Savings* to invest the assets in possible *Locked Savings* or *Activities* with higher interest rates. The priority of investments: Higher profit first! *Account Balances* → *Activities* → *Locked Savings* → *Flexible Savings* #### Benefits * Hand drafted library * Quick to install * No dependencies * Open Source #### Requirements * Binance API Key (Can Read / Enable Spot Trading) * Binance API Secret * Node.js instance (14.x) * Cron job for periodic checks #### Install * Provide `API_KEY` & `API_SECRET` as `process.env` variables * Try `yarn start` #### Warning Use the 🤖 at your own risk. #### Todos * Notification on project purchase #### Icon Made by [Skyclick](https://www.flaticon.com/authors/skyclick) from [Flaticon](https://www.flaticon.com)
d6d973aff1d46b45789b585a88214369c5f1b631
[ "JavaScript", "Markdown" ]
5
JavaScript
sergejmueller/binance-savings-rebalancer
64420e3f411cb25c4f64315fa0d425101ac9afa5
9d58ab73b9564c8f931515d46c3d16939ca574c5
refs/heads/master
<repo_name>gocd/build_map<file_sep>/build_go_cd_commit_to_package.rb #!/usr/bin/env ruby require 'rubygems' require 'rake' %w(rake rake/file_utils).each do |f| begin require f rescue LoadError => e puts "Unable to require #{f}, continuing" end end $stdout.sync = true $stderr.sync = true include FileUtils unless(ENV['UPDATE_GOCD_BUILD_MAP']) puts "Not updating build_map repo as Environment variable UPDATE_GOCD_BUILD_MAP is not set, exiting.." exit(true) end rm_rf 'build_map' sh("git clone https://github.com/gocd/build_map") at_exit do rm_rf 'build_map' end cd 'build_map' do entry = "#{ENV['GO_TO_REVISION_GOCD']}:#{ENV['GO_PIPELINE_COUNTER']}/#{ENV['GO_STAGE_COUNTER']}" File.open('commit_build_map', 'a') do |f| f.puts entry end sh 'git add .' sh "git commit -m 'Update map file - #{entry}' --author 'GoCD CI User <<EMAIL>>'" sh %Q{git push "https://#{ENV['BUILD_MAP_USER']}:#{ENV['BUILD_MAP_PASSWORD']}@github.com/gocd/build_map" master} puts "Map file updated" end
f15a3f3230705b3a124cd0d9c80b965370c02ebb
[ "Ruby" ]
1
Ruby
gocd/build_map
cdc46666772e1eb307a3958da66908e8e6d94861
a6d998de8bf90c2415f585889f59f552d75b2e94
refs/heads/master
<repo_name>p182/lastapp<file_sep>/src/lastfm/LastFM.hpp /* * LastFM.hpp * * Created on: Jun 29, 2017 * Author: misha */ #ifndef LASTFM_HPP_ #define LASTFM_HPP_ #include <QObject> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include "TrackController.hpp" #include "UserController.hpp" #include "ArtistController.hpp" #include "ChartController.hpp" #include "TagController.hpp" #include "AlbumController.hpp" #include <QUrl> #include "../Logger.hpp" using namespace bb::lastfm::controllers; namespace bb { namespace lastfm { class LastFM: public QObject { Q_OBJECT Q_PROPERTY(TrackController* track READ getTrackController) Q_PROPERTY(UserController* user READ getUserController) Q_PROPERTY(ArtistController* artist READ getArtistController) Q_PROPERTY(ChartController* chart READ getChartController) Q_PROPERTY(TagController* tag READ getTagController) Q_PROPERTY(AlbumController* album READ getAlbumController) public: LastFM(QObject* parent = 0); virtual ~LastFM(); static QUrl defaultUrl(const QString& method); static QUrl defaultBody(const QString& method); Q_INVOKABLE void authenticate(const QString& username, const QString& password); Q_INVOKABLE TrackController* getTrackController() const; Q_INVOKABLE UserController* getUserController() const; Q_INVOKABLE ArtistController* getArtistController() const; Q_INVOKABLE ChartController* getChartController() const; Q_INVOKABLE TagController* getTagController() const; Q_INVOKABLE AlbumController* getAlbumController() const; void setAccessToken(const QString& accessToken); Q_SIGNALS: void accessTokenObtained(const QString& name, const QString& accessToken); void authFinished(const QString& message, const bool& success); private slots: void onAuthenticate(); void onError(QNetworkReply::NetworkError e); private: static Logger logger; QNetworkAccessManager* m_pNetwork; TrackController* m_pTrack; UserController* m_pUser; ArtistController* m_pArtist; ChartController* m_pChart; TagController* m_pTag; AlbumController* m_pAlbum; }; } } #endif /* LASTFM_HPP_ */ <file_sep>/src/applicationui.hpp /* * Copyright (c) 2011-2015 BlackBerry Limited. * * 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. */ #ifndef ApplicationUI_HPP_ #define ApplicationUI_HPP_ #include <QObject> #include <QNetworkConfigurationManager> #include <bb/system/SystemToast> #include "lastfm/LastFM.hpp" #include "services/ImageService.hpp" #include "Logger.hpp" #include <bb/system/InvokeManager> #include <bb/system/InvokeRequest> #include <bb/system/InvokeTargetReply> #include <QSettings> #include <QFileSystemWatcher> namespace bb { namespace cascades { class LocaleHandler; } } class QTranslator; using namespace bb::cascades; using namespace bb::system; using namespace bb::lastfm; /*! * @brief Application UI object * * Use this object to create and init app UI, to create context objects, to register the new meta types etc. */ class ApplicationUI : public QObject { Q_OBJECT Q_PROPERTY(bool online READ isOnline NOTIFY onlineChanged) Q_PROPERTY(bool scrobblerEnabled READ isScrobblerEnabled WRITE setScrobblerEnabled NOTIFY scrobblerEnabledChanged) Q_PROPERTY(bool notificationsEnabled READ isNotificationsEnabled WRITE setNotificationsEnabled NOTIFY notificationsEnabledChanged) public: ApplicationUI(); virtual ~ApplicationUI(); Q_INVOKABLE void toast(const QString& message); Q_INVOKABLE void stopHeadless(); Q_INVOKABLE void startHeadless(); Q_INVOKABLE QVariant prop(const QString& key, const QVariant& defaultValue = ""); Q_INVOKABLE void setProp(const QString& key, const QVariant& val); bool isOnline() const; bool isScrobblerEnabled() const; void setScrobblerEnabled(const bool& scrobblingEnabled); bool isNotificationsEnabled() const; void setNotificationsEnabled(const bool& notificationsEnabled); Q_SIGNALS: void onlineChanged(const bool& online); void scrobblerEnabledChanged(const bool& scrobblerEnabled); void notificationsEnabledChanged(const bool& notificationsEnabledChanged); void propChanged(const QString& key, const QVariant& val); private slots: void onSystemLanguageChanged(); void storeAccessToken(const QString& name, const QString& accessToken); void onOnlineChanged(bool online); void headlessInvoked(); void onFileChanged(const QString& path); private: QTranslator* m_pTranslator; LocaleHandler* m_pLocaleHandler; QNetworkConfigurationManager* m_pNetworkConf; SystemToast* m_pToast; QFileSystemWatcher* m_pWatcher; LastFM* m_pLastFM; ImageService* m_pImageService; bool m_online; bool m_scrobblerEnabled; bool m_notificationsEnabled; InvokeManager* m_invokeManager; QSettings m_settings; static Logger logger; void renderLogin(); void renderMain(); }; #endif /* ApplicationUI_HPP_ */ <file_sep>/src/lastfm/LastFM.cpp /* * LastFM.cpp * * Created on: Jun 29, 2017 * Author: misha */ #include "LastFM.hpp" #include <QCryptographicHash> #include <QDebug> #include <bb/data/JsonDataAccess> #include <QVariantMap> #include "LastFMCommon.hpp" #include <bb/cascades/QmlDocument> using namespace bb::cascades; using namespace bb::data; namespace bb { namespace lastfm { Logger LastFM::logger = Logger::getLogger("LastFM"); LastFM::LastFM(QObject* parent) : QObject(parent) { m_pNetwork = QmlDocument::defaultDeclarativeEngine()->networkAccessManager(); m_pTrack = new TrackController(this); m_pUser = new UserController(this); m_pArtist = new ArtistController(this); m_pChart = new ChartController(this); m_pTag = new TagController(this); m_pAlbum = new AlbumController(this); } LastFM::~LastFM() { m_pNetwork->deleteLater(); m_pTrack->deleteLater(); m_pUser->deleteLater(); m_pArtist->deleteLater(); m_pChart->deleteLater(); m_pTag->deleteLater(); m_pAlbum->deleteLater(); } QUrl LastFM::defaultUrl(const QString& method) { QUrl url(API_ROOT); url.addQueryItem("method", method); url.addQueryItem("api_key", API_KEY); url.addQueryItem("format", "json"); return url; } QUrl LastFM::defaultBody(const QString& method) { QUrl body; body.addQueryItem("method", method); body.addQueryItem("api_key", API_KEY); body.addQueryItem("format", "json"); return body; } void LastFM::authenticate(const QString& username, const QString& password) { QNetworkRequest req; QUrl url(AUTH_ROOT); QByteArray body; url.addQueryItem("method", AUTH_METHOD); url.addQueryItem("username", username.toUtf8()); url.addQueryItem("password", <PASSWORD>.toUtf8()); url.addQueryItem("api_key", API_KEY); url.addQueryItem("format", "json"); QString sig = QString("api_key").append(API_KEY).append("method").append(AUTH_METHOD).append("password").append(password).append("username").append(username).append(SECRET); QString hash = QCryptographicHash::hash(sig.toAscii(), QCryptographicHash::Md5).toHex(); url.addQueryItem("api_sig", hash); req.setUrl(url); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); QNetworkReply* reply = m_pNetwork->post(req, body); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onAuthenticate())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void LastFM::onAuthenticate() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantMap session = jda.loadFromBuffer(reply->readAll()).toMap().value("session").toMap(); QString name = session.value("name").toString(); QString key = session.value("key").toString(); emit accessTokenObtained(name, key); emit authFinished(name, true); } reply->deleteLater(); } void LastFM::onError(QNetworkReply::NetworkError e) { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); logger.error(e); logger.error(reply->errorString()); reply->deleteLater(); emit authFinished(reply->errorString(), false); } TrackController* LastFM::getTrackController() const { return m_pTrack; } UserController* LastFM::getUserController() const { return m_pUser; } ArtistController* LastFM::getArtistController() const { return m_pArtist; } ChartController* LastFM::getChartController() const { return m_pChart; } TagController* LastFM::getTagController() const { return m_pTag; } AlbumController* LastFM::getAlbumController() const { return m_pAlbum; } void LastFM::setAccessToken(const QString& accessToken) { m_pTrack->setAccessToken(accessToken); m_pUser->setAccessToken(accessToken); m_pArtist->setAccessToken(accessToken); m_pTag->setAccessToken(accessToken); m_pAlbum->setAccessToken(accessToken); } } } <file_sep>/src/services/ImageService.cpp /* * ImageService.cpp * * Created on: Aug 27, 2017 * Author: misha */ #include "ImageService.hpp" #include <QUrl> #include <QNetworkRequest> #include <QStringList> #include <QVariantMap> #include <QDir> #include <QFile> #include "../Common.hpp" #include <bb/cascades/QmlDocument> using namespace bb::cascades; ImageService::ImageService(QObject* parent) : QObject(parent) { m_pNetwork = QmlDocument::defaultDeclarativeEngine()->networkAccessManager(); } ImageService::~ImageService() { m_pNetwork->deleteLater(); } Logger ImageService::logger = Logger::getLogger("ImageService"); void ImageService::loadImage(const QString& remotePath) { if (remotePath.compare("") == 0) { emit imageLoaded(remotePath, remotePath); } else { QString remotePathCopy = remotePath; QString filename = remotePathCopy.split("/").last(); QString localPath = QDir::currentPath().append(IMAGES_LOCATION).append("/").append(filename); QFile img(localPath); if (img.exists()) { emit imageLoaded(remotePath, QString("file://").append(localPath)); } else { QUrl url(remotePath); QNetworkRequest req; req.setUrl(url); // logger.info(url); QNetworkReply* reply = m_pNetwork->get(req); reply->setProperty("remote_path", remotePath); reply->setProperty("local_path", localPath); reply->setProperty("filename", filename); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onImageLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } } } void ImageService::onImageLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { QString remotePath = reply->property("remote_path").toString(); QString localPath = reply->property("local_path").toString(); QString filename = reply->property("filename").toString(); // logger.info("Create file: " + localPath); QFile file(localPath); if (file.open(QIODevice::WriteOnly)) { file.write(reply->readAll()); file.close(); emit imageLoaded(remotePath, QString("file://").append(localPath)); } else { logger.error(file.errorString()); emit imageLoaded(remotePath, ""); } } reply->deleteLater(); } QString ImageService::getImage(const QVariantList& images, const QString& size) { foreach(QVariant imgVar, images) { QVariantMap imgMap = imgVar.toMap(); if (imgMap.value("size").toString() == size) { return imgMap.value("#text", "").toString(); } } return ""; } void ImageService::onError(QNetworkReply::NetworkError e) { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); logger.error(e); logger.error(reply->errorString()); reply->deleteLater(); } <file_sep>/src/lastfm/ArtistController.hpp /* * ArtistController.hpp * * Created on: Aug 29, 2017 * Author: misha */ #ifndef ARTISTCONTROLLER_HPP_ #define ARTISTCONTROLLER_HPP_ #include <QObject> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QVariantMap> #include "../Logger.hpp" namespace bb { namespace lastfm { namespace controllers { class ArtistController: public QObject { Q_OBJECT public: ArtistController(QObject* parent = 0); virtual ~ArtistController(); Q_INVOKABLE void getInfo(const QString& artist, const QString& mbid = "", const QString& lang = "en", const int& autocorrect = 1, const QString username = ""); Q_INVOKABLE void getTopTracks(const QString& artist, const QString& mbid = "", const int& autocorrect = 1, const int& page = 1, const int& limit = 50); Q_INVOKABLE void search(const QString& artist, const int& page = 1, const int& limit = 50); void setAccessToken(const QString& accessToken); Q_SIGNALS: void infoLoaded(const QVariantMap& info); void topTracksLoaded(const QVariantList& topTracks); void searchLoaded(const QVariantList& searchResult); void error(); private slots: void onInfoLoaded(); void onTopTracksLoaded(); void onSearchLoaded(); void onError(QNetworkReply::NetworkError e); private: QNetworkAccessManager* m_pNetwork; QString m_accessToken; static Logger logger; }; } /* namespace controllers */ } /* namespace lastfm */ } /* namespace bb */ #endif /* ARTISTCONTROLLER_HPP_ */ <file_sep>/src/lastfm/AlbumController.hpp /* * AlbumController.hpp * * Created on: Sep 13, 2017 * Author: misha */ #ifndef ALBUMCONTROLLER_HPP_ #define ALBUMCONTROLLER_HPP_ #include <QObject> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QVariantMap> #include "../Logger.hpp" namespace bb { namespace lastfm { namespace controllers { class AlbumController: public QObject { Q_OBJECT public: AlbumController(QObject* parent = 0); virtual ~AlbumController(); Q_INVOKABLE void getInfo(const QString& artist, const QString& album, const QString& mbid = "", const int& autocorrect = 1, const QString& username = "", const QString& lang = "en"); Q_INVOKABLE void search(const QString& album, const int& page = 1, const int& limit = 50); void setAccessToken(const QString& accessToken); Q_SIGNALS: void infoLoaded(const QVariantMap& info); void searchLoaded(const QVariantList& searchResult); void error(); private slots: void onInfoLoaded(); void onSearchLoaded(); void onError(QNetworkReply::NetworkError e); private: static Logger logger; QNetworkAccessManager* m_pNetwork; QString m_accessToken; }; } /* namespace controllers */ } /* namespace lastfm */ } /* namespace bb */ #endif /* ALBUMCONTROLLER_HPP_ */ <file_sep>/src/lastfm/ChartController.hpp /* * ChartController.hpp * * Created on: Sep 10, 2017 * Author: misha */ #ifndef CHARTCONTROLLER_HPP_ #define CHARTCONTROLLER_HPP_ #include <QObject> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QVariantList> #include "../Logger.hpp" namespace bb { namespace lastfm { namespace controllers { class ChartController: public QObject { Q_OBJECT public: ChartController(QObject* parent = 0); virtual ~ChartController(); Q_INVOKABLE void getTopArtists(const int& page = 1, const int& limit = 50); Q_INVOKABLE void getTopTracks(const int& page = 1, const int& limit = 50); Q_INVOKABLE void getTopTags(const int& page = 1, const int& limit = 50); void setAccessToken(const QString& accessToken); Q_SIGNALS: void chartLoaded(const QVariantList& chartData); void error(); private slots: void onLoad(); void onError(QNetworkReply::NetworkError e); private: static Logger logger; QNetworkAccessManager* m_pNetwork; QString m_accessToken; void invoke(const QString& method, const int& page = 1, const int& limit = 50); void prepareChartData(const QVariantList& source, QVariantList& chartData, const QString& type); }; } /* namespace controllers */ } /* namespace lastfm */ } /* namespace bb */ #endif /* CHARTCONTROLLER_HPP_ */ <file_sep>/README.md # lastapp Qt/C++ LastFM client app for BlackBerry 10 <file_sep>/src/services/ImageService.hpp /* * ImageService.hpp * * Created on: Aug 27, 2017 * Author: misha */ #ifndef IMAGESERVICE_HPP_ #define IMAGESERVICE_HPP_ #include <QObject> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QVariantList> #include "../Logger.hpp" class ImageService: public QObject { Q_OBJECT public: ImageService(QObject* parent = 0); virtual ~ImageService(); Q_INVOKABLE void loadImage(const QString& remotePath); Q_INVOKABLE QString getImage(const QVariantList& images, const QString& size); Q_SIGNALS: void imageLoaded(const QString& remotePath, const QString& localPath); private slots: void onImageLoaded(); void onError(QNetworkReply::NetworkError e); private: QNetworkAccessManager* m_pNetwork; static Logger logger; }; #endif /* IMAGESERVICE_HPP_ */ <file_sep>/src/lastfm/ChartController.cpp /* * ChartController.cpp * * Created on: Sep 10, 2017 * Author: misha */ #include "ChartController.hpp" #include "../lastfm/LastFMCommon.hpp" #include <bb/cascades/QmlDocument> #include <QNetworkRequest> #include <QUrl> #include <bb/data/JsonDataAccess> #include <QVariantMap> #include "LastFM.hpp" using namespace bb::cascades; using namespace bb::data; namespace bb { namespace lastfm { namespace controllers { Logger ChartController::logger = Logger::getLogger("ChartController"); ChartController::ChartController(QObject* parent) : QObject(parent) { m_pNetwork = QmlDocument::defaultDeclarativeEngine()->networkAccessManager(); } ChartController::~ChartController() {} void ChartController::getTopArtists(const int& page, const int& limit) { invoke(CHART_GET_TOP_ARTISTS, page, limit); } void ChartController::getTopTracks(const int& page, const int& limit) { invoke(CHART_GET_TOP_TRACKS, page, limit); } void ChartController::getTopTags(const int& page, const int& limit) { invoke(CHART_GET_TOP_TAGS, page, limit); } void ChartController::invoke(const QString& method, const int& page, const int& limit) { QUrl url = LastFM::defaultUrl(method); url.addQueryItem("page", QString::number(page)); url.addQueryItem("limit", QString::number(limit)); logger.info(url); QNetworkRequest req; req.setUrl(url); QNetworkReply* reply = m_pNetwork->get(req); reply->setProperty("method", method); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onLoad())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void ChartController::onLoad() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { QString method = reply->property("method").toString(); JsonDataAccess jda; QVariantMap response = jda.loadFromBuffer(reply->readAll()).toMap(); QVariantList chartData; if (method.compare(QString(CHART_GET_TOP_ARTISTS)) == 0) { QVariantList artists = response.value("artists").toMap().value("artist").toList(); prepareChartData(artists, chartData, "artist"); } else if (method.compare(QString(CHART_GET_TOP_TAGS)) == 0) { QVariantList tags = response.value("tags").toMap().value("tag").toList(); prepareChartData(tags, chartData, "tag"); } else { QVariantList tracks = response.value("tracks").toMap().value("track").toList(); prepareChartData(tracks, chartData, "track"); } emit chartLoaded(chartData); } reply->deleteLater(); } void ChartController::onError(QNetworkReply::NetworkError e) { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); logger.error(e); logger.error(reply->errorString()); reply->deleteLater(); emit error(); } void ChartController::prepareChartData(const QVariantList& source, QVariantList& chartData, const QString& type) { foreach(QVariant var, source) { QVariantMap map = var.toMap(); map["type"] = type; chartData.append(map); } } void ChartController::setAccessToken(const QString& accessToken) { m_accessToken = accessToken; } } /* namespace controllers */ } /* namespace lastfm */ } /* namespace bb */ <file_sep>/src/applicationui.cpp /* * Copyright (c) 2011-2015 BlackBerry Limited. * * 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. */ #include "applicationui.hpp" #include <bb/cascades/Application> #include <bb/cascades/QmlDocument> #include <bb/cascades/AbstractPane> #include <bb/cascades/LocaleHandler> #include <bb/cascades/DevelopmentSupport> #include <bb/cascades/ThemeSupport> #include "lastfm/LastFMCommon.hpp" #include "Common.hpp" #include <QDir> #define SETTINGS_SCROBBLER_KEY "scrobbler.enabled" #define SETTINGS_NOW_PLAYING_KEY "notify_now_playing" #define LASTAPP_SERVICE "chachkouski.LastappService.start" #define START_APP_ACTION "chachkouski.LastappService.START" using namespace bb::cascades; Logger ApplicationUI::logger = Logger::getLogger("ApplicationUI"); ApplicationUI::ApplicationUI(): QObject() { m_pTranslator = new QTranslator(this); m_pLocaleHandler = new LocaleHandler(this); m_pLastFM = new LastFM(this); m_pImageService = new ImageService(this); m_pNetworkConf = new QNetworkConfigurationManager(this); m_pToast = new SystemToast(this); m_invokeManager = new InvokeManager(this); m_pWatcher = new QFileSystemWatcher(this); m_scrobblerEnabled = true; m_notificationsEnabled = true; QCoreApplication::setOrganizationName("mikhail.chachkouski"); QCoreApplication::setApplicationName("Lastapp"); QString theme = m_settings.value("theme", "DARK").toString(); if (theme.compare("") != 0) { if (theme.compare("DARK") == 0) { Application::instance()->themeSupport()->setVisualStyle(VisualStyle::Dark); } else { Application::instance()->themeSupport()->setVisualStyle(VisualStyle::Bright); } } m_pLastFM->setAccessToken(prop(LAST_FM_KEY).toString()); setScrobblerEnabled(prop(SETTINGS_SCROBBLER_KEY, true).toBool()); setNotificationsEnabled(prop(SETTINGS_NOW_PLAYING_KEY, true).toBool()); QString imagesPath = QDir::currentPath().append(IMAGES_LOCATION); QDir images(imagesPath); if (!images.exists()) { logger.info("Create path: " + imagesPath); images.mkpath(imagesPath); } bool res = QObject::connect(m_pLastFM, SIGNAL(accessTokenObtained(const QString&, const QString&)), this, SLOT(storeAccessToken(const QString&, const QString&))); Q_ASSERT(res); res = QObject::connect(m_pLocaleHandler, SIGNAL(systemLanguageChanged()), this, SLOT(onSystemLanguageChanged())); Q_ASSERT(res); res = QObject::connect(m_pNetworkConf, SIGNAL(onlineStateChanged(bool)), this, SLOT(onOnlineChanged(bool))); Q_ASSERT(res); res = QObject::connect(m_pWatcher, SIGNAL(fileChanged(const QString&)), this, SLOT(onFileChanged(const QString&))); Q_ASSERT(res); Q_UNUSED(res); m_pWatcher->addPath(m_settings.fileName()); onSystemLanguageChanged(); DevelopmentSupport::install(); QLocale systemLocale; QString lang = "en"; if (systemLocale.language() == QLocale::Russian) { lang = "ru"; } QDeclarativeEngine* engine = QmlDocument::defaultDeclarativeEngine(); QDeclarativeContext* rootContext = engine->rootContext(); rootContext->setContextProperty("_app", this); rootContext->setContextProperty("_lastFM", m_pLastFM); rootContext->setContextProperty("_user", m_pLastFM->getUserController()); rootContext->setContextProperty("_artist", m_pLastFM->getArtistController()); rootContext->setContextProperty("_chart", m_pLastFM->getChartController()); rootContext->setContextProperty("_tag", m_pLastFM->getTagController()); rootContext->setContextProperty("_album", m_pLastFM->getAlbumController()); rootContext->setContextProperty("_track", m_pLastFM->getTrackController()); rootContext->setContextProperty("_imageService", m_pImageService); rootContext->setContextProperty("_lang", lang); startHeadless(); if (prop(LAST_FM_KEY).toString().compare("") == 0) { renderLogin(); } else { renderMain(); } } ApplicationUI::~ApplicationUI() { m_pTranslator->deleteLater(); m_pLocaleHandler->deleteLater(); m_pNetworkConf->deleteLater(); m_pToast->deleteLater(); m_pLastFM->deleteLater(); m_invokeManager->deleteLater(); m_pWatcher->deleteLater(); } void ApplicationUI::headlessInvoked() { InvokeTargetReply* reply = qobject_cast<InvokeTargetReply*>(QObject::sender()); logger.info(QString("Invoked headless success: ").append(reply->isFinished() ? QString::number(1) : QString::number(0))); reply->deleteLater(); } void ApplicationUI::onSystemLanguageChanged() { QCoreApplication::instance()->removeTranslator(m_pTranslator); QString locale_string = QLocale().name(); QString file_name = QString("Lastapp_%1").arg(locale_string); if (m_pTranslator->load(file_name, "app/native/qm")) { QCoreApplication::instance()->installTranslator(m_pTranslator); } } void ApplicationUI::storeAccessToken(const QString& name, const QString& accessToken) { m_pLastFM->setAccessToken(accessToken); setProp(LAST_FM_KEY, accessToken); setProp(LAST_FM_NAME, name); Application::instance()->scene()->deleteLater(); toast(tr("Logged in as: ") + name); renderMain(); } void ApplicationUI::renderLogin() { QmlDocument *qml = QmlDocument::create("asset:///pages/Login.qml").parent(this); AbstractPane *root = qml->createRootObject<AbstractPane>(); Application::instance()->setScene(root); } void ApplicationUI::renderMain() { QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this); AbstractPane *root = qml->createRootObject<AbstractPane>(); Application::instance()->setScene(root); } void ApplicationUI::toast(const QString& message) { m_pToast->setBody(message); m_pToast->show(); } void ApplicationUI::stopHeadless() { logger.info("Stop Headless"); InvokeRequest request; request.setTarget(LASTAPP_SERVICE); request.setAction("bb.action.STOP"); InvokeTargetReply* reply = m_invokeManager->invoke(request); QObject::connect(reply, SIGNAL(finished()), this, SLOT(headlessInvoked())); } void ApplicationUI::startHeadless() { logger.info("Start Headless"); InvokeRequest request; request.setTarget(LASTAPP_SERVICE); request.setAction(START_APP_ACTION); InvokeTargetReply* reply = m_invokeManager->invoke(request); QObject::connect(reply, SIGNAL(finished()), this, SLOT(headlessInvoked())); } QVariant ApplicationUI::prop(const QString& key, const QVariant& defaultValue) { return m_settings.value(key, defaultValue); } void ApplicationUI::setProp(const QString& key, const QVariant& val) { logger.debug("Settings changed: " + key + " = " + val.toString()); if (key.compare(SETTINGS_SCROBBLER_KEY) == 0) { setScrobblerEnabled(val.toBool()); } else if (key.compare(SETTINGS_NOW_PLAYING_KEY) == 0) { setNotificationsEnabled(val.toBool()); } m_settings.setValue(key, val); m_settings.sync(); emit propChanged(key, val); } bool ApplicationUI::isOnline() const { return m_online; } void ApplicationUI::onOnlineChanged(bool online) { if (m_online != online) { m_online = online; emit onlineChanged(m_online); } } bool ApplicationUI::isScrobblerEnabled() const { return m_scrobblerEnabled; } void ApplicationUI::setScrobblerEnabled(const bool& scrobblingEnabled) { if (m_scrobblerEnabled != scrobblingEnabled) { m_scrobblerEnabled = scrobblingEnabled; emit scrobblerEnabledChanged(m_scrobblerEnabled); } } bool ApplicationUI::isNotificationsEnabled() const { return m_notificationsEnabled; } void ApplicationUI::setNotificationsEnabled(const bool& notificationsEnabled) { if (m_notificationsEnabled != notificationsEnabled) { m_notificationsEnabled = notificationsEnabled; emit notificationsEnabledChanged(m_notificationsEnabled); } } void ApplicationUI::onFileChanged(const QString& path) { if (path.contains(".conf")) { m_settings.sync(); setScrobblerEnabled(prop(SETTINGS_SCROBBLER_KEY).toBool()); } } <file_sep>/src/lastfm/TrackController.cpp /* * TrackController.cpp * * Created on: Jun 30, 2017 * Author: misha */ #define API_NAMESPACE "track" #include "TrackController.hpp" #include "LastFMCommon.hpp" #include <QUrl> #include <QCryptographicHash> #include <QDebug> #include <bb/cascades/QmlDocument> #include "LastFM.hpp" #include <bb/data/JsonDataAccess> using namespace bb::cascades; using namespace bb::data; namespace bb { namespace lastfm { namespace controllers { Logger TrackController::logger = Logger::getLogger("TrackController"); TrackController::TrackController(QObject* parent) : QObject(parent) { m_pNetwork = QmlDocument::defaultDeclarativeEngine()->networkAccessManager(); } TrackController::~TrackController() { m_pNetwork->deleteLater(); } void TrackController::updateNowPlaying(const QString& artist, const QString& track) { QNetworkRequest req; QUrl url(API_ROOT); req.setUrl(url); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); QString sk = m_accessToken; QString sig = QString("api_key").append(API_KEY) .append("artist").append(artist.toUtf8()) .append("method").append(TRACK_UPDATE_NOW_PLAYING) .append("sk").append(sk) .append("track").append(track.toUtf8()) .append(SECRET); QString hash = QCryptographicHash::hash(sig.toAscii(), QCryptographicHash::Md5).toHex(); QUrl body = LastFM::defaultBody(TRACK_UPDATE_NOW_PLAYING); body.addQueryItem("artist", artist.toUtf8()); body.addQueryItem("track", track.toUtf8()); body.addQueryItem("sk", sk); body.addQueryItem("api_sig", hash); logger.info(url); logger.info(body); QNetworkReply* reply = m_pNetwork->post(req, body.encodedQuery()); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onNowPlayingUpdated())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void TrackController::onNowPlayingUpdated() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { qDebug() << reply->readAll() << endl; } reply->deleteLater(); } void TrackController::scrobble(const QString& artist, const QString& track, const int& timestamp) { QNetworkRequest req; QUrl url(API_ROOT); req.setUrl(url); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); QString sk = m_accessToken; QString sig = QString("api_key").append(API_KEY) .append("artist").append(artist.toUtf8()) .append("method").append(TRACK_SCROBBLE) .append("sk").append(sk) .append("timestamp").append(QString::number(timestamp)) .append("track").append(track.toUtf8()) .append(SECRET); QString hash = QCryptographicHash::hash(sig.toAscii(), QCryptographicHash::Md5).toHex(); QUrl body = LastFM::defaultBody(TRACK_SCROBBLE); body.addQueryItem("artist", artist.toUtf8()); body.addQueryItem("track", track.toUtf8()); body.addQueryItem("timestamp", QString::number(timestamp)); body.addQueryItem("sk", sk); body.addQueryItem("api_sig", hash); logger.info(url); logger.info(body); QNetworkReply* reply = m_pNetwork->post(req, body.encodedQuery()); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onScrobbled())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void TrackController::love(const QString& artist, const QString& track) { QNetworkRequest req; QUrl url(API_ROOT); req.setUrl(url); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); QString sk = m_accessToken; QString sig = QString("api_key").append(API_KEY) .append("artist").append(artist.toUtf8()) .append("method").append(TRACK_LOVE) .append("sk").append(sk) .append("track").append(track.toUtf8()) .append(SECRET); QString hash = QCryptographicHash::hash(sig.toAscii(), QCryptographicHash::Md5).toHex(); QUrl body = LastFM::defaultBody(TRACK_LOVE); body.addQueryItem("artist", artist.toUtf8()); body.addQueryItem("track", track.toUtf8()); body.addQueryItem("sk", sk); body.addQueryItem("api_sig", hash); logger.info(url); logger.info(body); QNetworkReply* reply = m_pNetwork->post(req, body.encodedQuery()); reply->setProperty("artist", artist); reply->setProperty("track", track); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onLoved())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void TrackController::unlove(const QString& artist, const QString& track) { QString sk = m_accessToken; QString sig = QString("api_key").append(API_KEY) .append("artist").append(artist.toUtf8()) .append("method").append(TRACK_UNLOVE) .append("sk").append(sk) .append("track").append(track.toUtf8()) .append(SECRET); QString hash = QCryptographicHash::hash(sig.toAscii(), QCryptographicHash::Md5).toHex(); QUrl body = LastFM::defaultBody(TRACK_UNLOVE); body.addQueryItem("artist", artist.toUtf8()); body.addQueryItem("track", track.toUtf8()); body.addQueryItem("sk", sk); body.addQueryItem("api_sig", hash); QUrl url(API_ROOT); QNetworkRequest req; req.setUrl(url); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); logger.info(url); logger.info(body); QNetworkReply* reply = m_pNetwork->post(req, body.encodedQuery()); reply->setProperty("artist", artist); reply->setProperty("track", track); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onUnloved())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void TrackController::getInfo(const QString& track, const QString& artist, const QString& mbid, const QString& username, const int& autocorrect) { QUrl url = LastFM::defaultUrl(TRACK_GET_INFO); if (mbid.isEmpty()) { url.addQueryItem("track", track); } else { url.addQueryItem("mbid", mbid); } url.addQueryItem("artist", artist); url.addQueryItem("autocorrect", QString::number(autocorrect)); if (!username.isEmpty()) { url.addQueryItem("username", username); } QNetworkRequest req; req.setUrl(url); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); logger.info(url); QNetworkReply* reply = m_pNetwork->get(req); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onInfoLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void TrackController::onInfoLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantMap track = jda.loadFromBuffer(reply->readAll()).toMap().value("track").toMap(); emit infoLoaded(track); } reply->deleteLater(); } void TrackController::search(const QString& track, const QString& artist, const int& page, const int& limit) { QUrl url = LastFM::defaultUrl(TRACK_SEARCH); url.addQueryItem("page", QString::number(page)); url.addQueryItem("limit", QString::number(limit)); url.addQueryItem("track", track); if (!artist.isEmpty()) { url.addQueryItem("artist", artist); } logger.info(url); QNetworkRequest req; req.setUrl(url); QNetworkReply* reply = m_pNetwork->get(req); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onSearchLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void TrackController::onSearchLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantList tracks = jda.loadFromBuffer(reply->readAll()).toMap().value("results").toMap().value("trackmatches").toMap().value("track").toList(); emit searchLoaded(tracks); } reply->deleteLater(); } void TrackController::onScrobbled() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { qDebug() << reply->readAll() << endl; } reply->deleteLater(); emit scrobbled(); } void TrackController::onLoved() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { logger.info(reply->readAll()); m_toast.setBody(tr("Track loved!")); m_toast.show(); emit loved(reply->property("artist").toString(), reply->property("track").toString()); } reply->deleteLater(); } void TrackController::onUnloved() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { logger.info(reply->readAll()); m_toast.setBody(tr("Track unloved")); m_toast.show(); emit unloved(reply->property("artist").toString(), reply->property("track").toString()); } reply->deleteLater(); } void TrackController::onError(QNetworkReply::NetworkError e) { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); logger.error(e); logger.error(reply->errorString()); reply->deleteLater(); emit error(); } void TrackController::setAccessToken(const QString& accessToken) { m_accessToken = accessToken; } } } } <file_sep>/src/main.cpp /* * Copyright (c) 2011-2015 BlackBerry Limited. * * 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. */ #include "applicationui.hpp" #include <bb/cascades/Application> #include <QLocale> #include <QTranslator> #include <Qt/qdeclarativedebug.h> #include <QtCore/QTimer> #include "lastfm/TrackController.hpp" #include "lastfm/UserController.hpp" #include "lastfm/ArtistController.hpp" #include "lastfm/TagController.hpp" #include "lastfm/AlbumController.hpp" #include "services/ImageService.hpp" #include "vendor/Console.hpp" using namespace bb::cascades; using namespace bb::lastfm::controllers; void myMessageOutput(QtMsgType type, const char* msg) { // <-- ADD THIS Q_UNUSED(type); fprintf(stdout, "%s\n", msg); fflush(stdout); QSettings settings; if (settings.value("sendToConsoleDebug", true).toBool()) { Console* console = new Console(); console->sendMessage("ConsoleThis$$" + QString(msg)); console->deleteLater(); } } Q_DECL_EXPORT int main(int argc, char **argv) { qmlRegisterType<QTimer>("chachkouski.util", 1, 0, "Timer"); qRegisterMetaType<TrackController*>("TrackController*"); qRegisterMetaType<UserController*>("UserController*"); qRegisterMetaType<ArtistController*>("ArtistController*"); qRegisterMetaType<TagController*>("TagController*"); qRegisterMetaType<AlbumController*>("AlbumController*"); qRegisterMetaType<ImageService*>("ImageService*"); qmlRegisterUncreatableType<TrackController>("lastFM.controllers", 1, 0, "TrackController", "test"); qmlRegisterUncreatableType<UserController>("lastFM.controllers", 1, 0, "UserController", "test"); qmlRegisterUncreatableType<ArtistController>("lastFM.controllers", 1, 0, "ArtistController", "test"); qmlRegisterUncreatableType<ArtistController>("lastFM.controllers", 1, 0, "TagController", "test"); qmlRegisterUncreatableType<AlbumController>("lastFM.controllers", 1, 0, "AlbumController", "test"); qInstallMsgHandler(myMessageOutput); Application app(argc, argv); ApplicationUI appui; return Application::exec(); } <file_sep>/src/lastfm/UserController.hpp /* * UserController.hpp * * Created on: Aug 13, 2017 * Author: misha */ #ifndef USERCONTROLLER_HPP_ #define USERCONTROLLER_HPP_ #include <QObject> #include <QDateTime> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QVariantList> #include "../Logger.hpp" namespace bb { namespace lastfm { namespace controllers { class UserController: public QObject { Q_OBJECT public: UserController(QObject* parent = 0); virtual ~UserController(); Q_INVOKABLE void getRecentTracks(const QString& user, const int& page = 1, const int& limit = 50); Q_INVOKABLE void getTopArtists(const QString& user, const int& page = 1, const int& limit = 50, const QString& period = "overall"); Q_INVOKABLE void getTopAlbums(const QString& user, const int& page = 1, const int& limit = 50, const QString& period = "overall"); Q_INVOKABLE void getTopTracks(const QString& user, const int& page = 1, const int& limit = 50, const QString& period = "overall"); Q_INVOKABLE void getFriends(const QString& user, const int& page = 1, const int& limit = 50); Q_INVOKABLE void getInfo(const QString& user); Q_INVOKABLE void getLovedTracks(const QString& user, const int& page = 1, const int& limit = 50); void setAccessToken(const QString& accessToken); Q_SIGNALS: void recentTracksLoaded(const QVariantList& recentTracks); void topArtistsLoaded(const QVariantList& topArtists, const QString& period, const QString& user, const int& total); void topAlbumsLoaded(const QVariantList& topAlbums, const QString& period); void topTracksLoaded(const QVariantList& topTracks, const QString& period, const QString& user); void friendsLoaded(const QVariantList& friends); void infoLoaded(const QVariantMap& info); void lovedTracksLoaded(const QVariantList& tracks, const QString& user, const int& total); void error(); private slots: void onRecentTracksLoaded(); void onTopArtistsLoaded(); void onTopAlbumsLoaded(); void onTopTracksLoaded(); void onFriendsLoaded(); void onInfoLoaded(); void onLovedTracksLoaded(); void onError(QNetworkReply::NetworkError error); private: QNetworkAccessManager* m_pNetwork; QString m_accessToken; static Logger logger; }; } /* namespace controllers */ } /* namespace lastfm */ } /* namespace bb */ #endif /* USERCONTROLLER_HPP_ */ <file_sep>/src/lastfm/LastFMCommon.hpp /* * LastFMCommon.hpp * * Created on: Aug 9, 2017 * Author: misha */ #ifndef LASTFMCOMMON_HPP_ #define LASTFMCOMMON_HPP_ #define LAST_FM_KEY "lastfm_key" #define LAST_FM_NAME "lastfm_name" #define API_ROOT "http://ws.audioscrobbler.com/2.0/" #define AUTH_ROOT "https://ws.audioscrobbler.com/2.0/" #define API_KEY "<KEY>" #define SECRET "<KEY>" #define AUTH_METHOD "auth.getMobileSession" #define TRACK_UPDATE_NOW_PLAYING "track.updateNowPlaying" #define TRACK_SCROBBLE "track.scrobble" #define TRACK_LOVE "track.love" #define TRACK_UNLOVE "track.unlove" #define TRACK_GET_INFO "track.getInfo" #define TRACK_SEARCH "track.search" #define USER_GET_RECENT_TRACKS "user.getRecentTracks" #define USER_GET_TOP_ARTISTS "user.getTopArtists" #define USER_GET_TOP_ALBUMS "user.getTopAlbums" #define USER_GET_TOP_TRACKS "user.getTopTracks" #define USER_GET_FRIENDS "user.getFriends" #define USER_GET_INFO "user.getInfo" #define USER_GET_LOVED_TRACKS "user.getLovedTracks" #define ARTIST_GET_INFO "artist.getInfo" #define ARTIST_GET_TOP_TRACKS "artist.getTopTracks" #define ARTIST_SEARCH "artist.search" #define CHART_GET_TOP_ARTISTS "chart.getTopArtists" #define CHART_GET_TOP_TAGS "chart.getTopTags" #define CHART_GET_TOP_TRACKS "chart.getTopTracks" #define TAG_GET_TOP_ARTISTS "tag.getTopArtists" #define TAG_GET_TOP_ALBUMS "tag.getTopAlbums" #define TAG_GET_TOP_TRACKS "tag.getTopTracks" #define ALBUM_GET_INFO "album.getInfo" #define ALBUM_SEARCH "album.search" #endif /* LASTFMCOMMON_HPP_ */ <file_sep>/src/lastfm/UserController.cpp /* * UserController.cpp * * Created on: Aug 13, 2017 * Author: misha */ #include "UserController.hpp" #include "LastFMCommon.hpp" #include <QUrl> #include <QDebug> #include <QVariantMap> #include <bb/data/JsonDataAccess> #include <bb/cascades/QmlDocument> #include "LastFM.hpp" #include <QSettings> using namespace bb::cascades; using namespace bb::data; namespace bb { namespace lastfm { namespace controllers { Logger UserController::logger = Logger::getLogger("UserController"); UserController::UserController(QObject* parent) : QObject(parent) { m_pNetwork = QmlDocument::defaultDeclarativeEngine()->networkAccessManager(); } UserController::~UserController() { m_pNetwork->deleteLater(); } void UserController::getRecentTracks(const QString& user, const int& page, const int& limit) { QNetworkRequest req; QUrl url = LastFM::defaultUrl(USER_GET_RECENT_TRACKS); url.addQueryItem("user", user); url.addQueryItem("page", QString::number(page)); url.addQueryItem("limit", QString::number(limit)); req.setUrl(url); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); logger.info(url); QNetworkReply* reply = m_pNetwork->get(req); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onRecentTracksLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void UserController::onRecentTracksLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantMap response = jda.loadFromBuffer(reply->readAll()).toMap().value("recenttracks").toMap(); QVariantList tracks = response.value("track").toList(); emit recentTracksLoaded(tracks); } reply->deleteLater(); } void UserController::getTopArtists(const QString& user, const int& page, const int& limit, const QString& period) { QNetworkRequest req; QUrl url = LastFM::defaultUrl(USER_GET_TOP_ARTISTS); url.addQueryItem("user", user); url.addQueryItem("page", QString::number(page)); url.addQueryItem("limit", QString::number(limit)); url.addQueryItem("period", period); req.setUrl(url); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); logger.info(url); QNetworkReply* reply = m_pNetwork->get(req); reply->setProperty("period", period); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onTopArtistsLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void UserController::onTopArtistsLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantMap response = jda.loadFromBuffer(reply->readAll()).toMap().value("topartists").toMap(); QVariantList artists = response.value("artist").toList(); QVariantMap attr = response.value("@attr").toMap(); emit topArtistsLoaded(artists, reply->property("period").toString(), attr.value("user").toString(), attr.value("total").toInt()); } reply->deleteLater(); } void UserController::getTopAlbums(const QString& user, const int& page, const int& limit, const QString& period) { QNetworkRequest req; QUrl url = LastFM::defaultUrl(USER_GET_TOP_ALBUMS); url.addQueryItem("user", user); url.addQueryItem("page", QString::number(page)); url.addQueryItem("limit", QString::number(limit)); url.addQueryItem("period", period); req.setUrl(url); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); logger.info(url); QNetworkReply* reply = m_pNetwork->get(req); reply->setProperty("period", period); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onTopAlbumsLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void UserController::onTopAlbumsLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantMap response = jda.loadFromBuffer(reply->readAll()).toMap().value("topalbums").toMap(); QVariantList artists = response.value("album").toList(); emit topAlbumsLoaded(artists, reply->property("period").toString()); } reply->deleteLater(); } void UserController::getTopTracks(const QString& user, const int& page, const int& limit, const QString& period) { QNetworkRequest req; QUrl url = LastFM::defaultUrl(USER_GET_TOP_TRACKS); url.addQueryItem("user", user); url.addQueryItem("page", QString::number(page)); url.addQueryItem("limit", QString::number(limit)); url.addQueryItem("period", period); req.setUrl(url); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); logger.info(url); QNetworkReply* reply = m_pNetwork->get(req); reply->setProperty("period", period); reply->setProperty("user", user); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onTopTracksLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void UserController::onTopTracksLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantMap response = jda.loadFromBuffer(reply->readAll()).toMap().value("toptracks").toMap(); QVariantList artists = response.value("track").toList(); emit topTracksLoaded(artists, reply->property("period").toString(), reply->property("user").toString()); } reply->deleteLater(); } void UserController::getFriends(const QString& user, const int& page, const int& limit) { QNetworkRequest req; QUrl url = LastFM::defaultUrl(USER_GET_FRIENDS); url.addQueryItem("user", user); url.addQueryItem("page", QString::number(page)); url.addQueryItem("limit", QString::number(limit)); req.setUrl(url); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); logger.info(url); QNetworkReply* reply = m_pNetwork->get(req); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onFriendsLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void UserController::onFriendsLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantMap response = jda.loadFromBuffer(reply->readAll()).toMap().value("friends").toMap(); QVariantList friends = response.value("user").toList(); emit friendsLoaded(friends); } reply->deleteLater(); } void UserController::getInfo(const QString& user) { QUrl url = LastFM::defaultUrl(USER_GET_INFO); url.addQueryItem("user", user); logger.info(url); QNetworkRequest req; req.setUrl(url); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); QNetworkReply* reply = m_pNetwork->get(req); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onInfoLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void UserController::onInfoLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantMap user = jda.loadFromBuffer(reply->readAll()).toMap().value("user").toMap(); emit infoLoaded(user); } reply->deleteLater(); } void UserController::getLovedTracks(const QString& user, const int& page, const int& limit) { QUrl url = LastFM::defaultUrl(USER_GET_LOVED_TRACKS); url.addQueryItem("user", user); url.addQueryItem("page", QString::number(page)); url.addQueryItem("limit", QString::number(limit)); QNetworkRequest req; req.setUrl(url); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); QNetworkReply* reply = m_pNetwork->get(req); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onLovedTracksLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void UserController::onLovedTracksLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantMap response = jda.loadFromBuffer(reply->readAll()).toMap().value("lovedtracks").toMap(); QVariantList tracks = response.value("track").toList(); QVariantMap attr = response.value("@attr").toMap(); emit lovedTracksLoaded(tracks, attr.value("user").toString(), attr.value("total").toInt()); } reply->deleteLater(); } void UserController::onError(QNetworkReply::NetworkError e) { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); logger.error(e); logger.error(reply->errorString()); reply->deleteLater(); emit error(); } void UserController::setAccessToken(const QString& accessToken) { m_accessToken = accessToken; } } /* namespace controllers */ } /* namespace lastfm */ } /* namespace bb */ <file_sep>/src/lastfm/TrackController.hpp /* * TrackController.hpp * * Created on: Jun 30, 2017 * Author: misha */ #ifndef TRACKCONTROLLER_HPP_ #define TRACKCONTROLLER_HPP_ #include <QObject> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include "../Logger.hpp" #include <bb/system/SystemToast> using namespace bb::system; namespace bb { namespace lastfm { namespace controllers { class TrackController: public QObject { Q_OBJECT public: TrackController(QObject* parent = 0); virtual ~TrackController(); Q_INVOKABLE void updateNowPlaying(const QString& artist, const QString& track); Q_INVOKABLE void scrobble(const QString& artist, const QString& track, const int& timestamp); Q_INVOKABLE void love(const QString& artist, const QString& track); Q_INVOKABLE void unlove(const QString& artist, const QString& track); Q_INVOKABLE void getInfo(const QString& track, const QString& artist, const QString& mbid = "", const QString& username = "", const int& autocorrect = 1); Q_INVOKABLE void search(const QString& track, const QString& artist = "", const int& page = 1, const int& limit = 50); void setAccessToken(const QString& accessToken); Q_SIGNALS: void nowPlayingUpdated(); void scrobbled(); void loved(const QString& artist, const QString& track); void unloved(const QString& artist, const QString& track); void infoLoaded(const QVariantMap& track); void searchLoaded(const QVariantList& searchResult); void error(); private slots: void onNowPlayingUpdated(); void onScrobbled(); void onLoved(); void onUnloved(); void onInfoLoaded(); void onSearchLoaded(); void onError(QNetworkReply::NetworkError e); private: static Logger logger; QNetworkAccessManager* m_pNetwork; SystemToast m_toast; QString m_accessToken; }; } } } #endif /* TRACKCONTROLLER_HPP_ */ <file_sep>/src/lastfm/ArtistController.cpp /* * ArtistController.cpp * * Created on: Aug 29, 2017 * Author: misha */ #include "ArtistController.hpp" #include <QUrl> #include <QNetworkRequest> #include <bb/data/JsonDataAccess> #include "LastFMCommon.hpp" #include <bb/cascades/QmlDocument> #include "LastFM.hpp" using namespace bb::cascades; using namespace bb::data; namespace bb { namespace lastfm { namespace controllers { Logger ArtistController::logger = Logger::getLogger("ArtistController"); ArtistController::ArtistController(QObject* parent) : QObject(parent) { m_pNetwork = QmlDocument::defaultDeclarativeEngine()->networkAccessManager(); } ArtistController::~ArtistController() { m_pNetwork->deleteLater(); } void ArtistController::getInfo(const QString& artist, const QString& mbid, const QString& lang, const int& autocorrect, const QString username) { QUrl url = LastFM::defaultUrl(ARTIST_GET_INFO); url.addQueryItem("lang", lang); url.addQueryItem("autocorrect", QString::number(autocorrect)); if (!mbid.isEmpty()) { url.addQueryItem("mbid", mbid); } else { url.addQueryItem("artist", artist); } if (!username.isEmpty()) { url.addQueryItem("username", username); } logger.info(url); QNetworkRequest req; req.setUrl(url); QNetworkReply* reply = m_pNetwork->get(req); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onInfoLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void ArtistController::onInfoLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantMap artist = jda.loadFromBuffer(reply->readAll()).toMap().value("artist").toMap(); emit infoLoaded(artist); } reply->deleteLater(); } void ArtistController::getTopTracks(const QString& artist, const QString& mbid, const int& autocorrect, const int& page, const int& limit) { QUrl url = LastFM::defaultUrl(ARTIST_GET_TOP_TRACKS); url.addQueryItem("page", QString::number(page)); url.addQueryItem("limit", QString::number(limit)); url.addQueryItem("autocorrect", QString::number(autocorrect)); if (!mbid.isEmpty()) { url.addQueryItem("mbid", mbid); } else { url.addQueryItem("artist", artist); } logger.info(url); QNetworkRequest req; req.setUrl(url); QNetworkReply* reply = m_pNetwork->get(req); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onTopTracksLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void ArtistController::onTopTracksLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantList topTracks = jda.loadFromBuffer(reply->readAll()).toMap().value("toptracks").toMap().value("track").toList(); emit topTracksLoaded(topTracks); } reply->deleteLater(); } void ArtistController::search(const QString& artist, const int& page, const int& limit) { QUrl url = LastFM::defaultUrl(ARTIST_SEARCH); url.addQueryItem("page", QString::number(page)); url.addQueryItem("limit", QString::number(limit)); url.addQueryItem("artist", artist); logger.info(url); QNetworkRequest req; req.setUrl(url); QNetworkReply* reply = m_pNetwork->get(req); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onSearchLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void ArtistController::onSearchLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantList artists = jda.loadFromBuffer(reply->readAll()).toMap().value("results").toMap().value("artistmatches").toMap().value("artist").toList(); emit searchLoaded(artists); } reply->deleteLater(); } void ArtistController::onError(QNetworkReply::NetworkError e) { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); logger.error(e); logger.error(reply->errorString()); reply->deleteLater(); emit error(); } void ArtistController::setAccessToken(const QString& accessToken) { m_accessToken = accessToken; } } /* namespace controllers */ } /* namespace lastfm */ } /* namespace bb */ <file_sep>/src/lastfm/AlbumController.cpp /* * AlbumController.cpp * * Created on: Sep 13, 2017 * Author: misha */ #include "AlbumController.hpp" #include <bb/cascades/QmlDocument> #include "LastFMCommon.hpp" #include <QUrl> #include <QNetworkRequest> #include <bb/data/JsonDataAccess> #include "LastFM.hpp" using namespace bb::cascades; using namespace bb::data; namespace bb { namespace lastfm { namespace controllers { Logger AlbumController::logger = Logger::getLogger("AlbumController"); AlbumController::AlbumController(QObject* parent) : QObject(parent) { m_pNetwork = QmlDocument::defaultDeclarativeEngine()->networkAccessManager(); } AlbumController::~AlbumController() {} void AlbumController::getInfo(const QString& artist, const QString& album, const QString& mbid, const int& autocorrect, const QString& username, const QString& lang) { QUrl url = LastFM::defaultUrl(ALBUM_GET_INFO); if (mbid.isEmpty()) { url.addQueryItem("artist", artist); url.addQueryItem("album", album); } else { url.addQueryItem("mbid", mbid); } url.addQueryItem("autocorrect", QString::number(autocorrect)); if (!username.isEmpty()) { url.addQueryItem("username", username); } url.addQueryItem("lang", lang); logger.info(url); QNetworkRequest req; req.setUrl(url); QNetworkReply* reply = m_pNetwork->get(req); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onInfoLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void AlbumController::onInfoLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantMap album = jda.loadFromBuffer(reply->readAll()).toMap().value("album").toMap(); emit infoLoaded(album); } reply->deleteLater(); } void AlbumController::search(const QString& album, const int& page, const int& limit) { QUrl url = LastFM::defaultUrl(ALBUM_SEARCH); url.addQueryItem("page", QString::number(page)); url.addQueryItem("limit", QString::number(limit)); url.addQueryItem("album", album); logger.info(url); QNetworkRequest req; req.setUrl(url); QNetworkReply* reply = m_pNetwork->get(req); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onSearchLoaded())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void AlbumController::onSearchLoaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { JsonDataAccess jda; QVariantList albums = jda.loadFromBuffer(reply->readAll()).toMap().value("results").toMap().value("albummatches").toMap().value("album").toList(); emit searchLoaded(albums); } reply->deleteLater(); } void AlbumController::onError(QNetworkReply::NetworkError e) { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); logger.error(e); logger.error(reply->errorString()); reply->deleteLater(); emit error(); } void AlbumController::setAccessToken(const QString& accessToken) { m_accessToken = accessToken; } } /* namespace controllers */ } /* namespace lastfm */ } /* namespace bb */ <file_sep>/src/lastfm/TagController.hpp /* * TagController.hpp * * Created on: Sep 12, 2017 * Author: misha */ #ifndef TAGCONTROLLER_HPP_ #define TAGCONTROLLER_HPP_ #include <QObject> #include <QNetworkAccessmanager> #include <QNetworkReply> #include <bb/cascades/QmlDocument> #include "../Logger.hpp" using namespace bb::cascades; namespace bb { namespace lastfm { namespace controllers { class TagController: public QObject { Q_OBJECT public: TagController(QObject* parent = 0); virtual ~TagController(); Q_INVOKABLE void getTopArtists(const QString& tag, const int& page = 1, const int& limit = 50); Q_INVOKABLE void getTopAlbums(const QString& tag, const int& page = 1, const int& limit = 50); Q_INVOKABLE void getTopTracks(const QString& tag, const int& page = 1, const int& limit = 50); void setAccessToken(const QString& accessToken); Q_SIGNALS: void chartLoaded(const QVariantList& chartData); void error(); private slots: void onLoad(); void onError(QNetworkReply::NetworkError e); private: QNetworkAccessManager* m_pNetwork; static Logger logger; QString m_accessToken; void invoke(const QString& method, const QString& tag, const int& page, const int& limit); void prepareChartData(const QVariantList& source, QVariantList& chartData, const QString& type); }; } /* namespace controllers */ } /* namespace lastfm */ } /* namespace bb */ #endif /* TAGCONTROLLER_HPP_ */ <file_sep>/src/Common.hpp /* * Common.hpp * * Created on: Aug 27, 2017 * Author: misha */ #ifndef COMMON_HPP_ #define COMMON_HPP_ #define IMAGES_LOCATION "/data/images" #endif /* COMMON_HPP_ */ <file_sep>/src/lastfm/TagController.cpp /* * TagController.cpp * * Created on: Sep 12, 2017 * Author: misha */ #include "TagController.hpp" #include <QUrl> #include <QNetworkRequest> #include "LastFMCommon.hpp" #include <bb/data/JsonDataAccess> #include "LastFM.hpp" using namespace bb::data; namespace bb { namespace lastfm { namespace controllers { Logger TagController::logger = Logger::getLogger("TagController"); TagController::TagController(QObject* parent) : QObject(parent) { m_pNetwork = QmlDocument::defaultDeclarativeEngine()->networkAccessManager(); } TagController::~TagController() {} void TagController::getTopArtists(const QString& tag, const int& page, const int& limit) { invoke(TAG_GET_TOP_ARTISTS, tag, page, limit); } void TagController::getTopAlbums(const QString& tag, const int& page, const int& limit) { invoke(TAG_GET_TOP_ALBUMS, tag, page, limit); } void TagController::getTopTracks(const QString& tag, const int& page, const int& limit) { invoke(TAG_GET_TOP_TRACKS, tag, page, limit); } void TagController::invoke(const QString& method, const QString& tag, const int& page, const int& limit) { QUrl url = LastFM::defaultUrl(method); url.addQueryItem("tag", tag); url.addQueryItem("page", QString::number(page)); url.addQueryItem("limit", QString::number(limit)); logger.info(url); QNetworkRequest req; req.setUrl(url); QNetworkReply* reply = m_pNetwork->get(req); reply->setProperty("method", method); bool res = QObject::connect(reply, SIGNAL(finished()), this, SLOT(onLoad())); Q_ASSERT(res); res = QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError))); Q_ASSERT(res); Q_UNUSED(res); } void TagController::onLoad() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() == QNetworkReply::NoError) { QString method = reply->property("method").toString(); JsonDataAccess jda; QVariantMap response = jda.loadFromBuffer(reply->readAll()).toMap(); QVariantList chartData; if (method.compare(QString(TAG_GET_TOP_ARTISTS)) == 0) { QVariantList artists = response.value("topartists").toMap().value("artist").toList(); prepareChartData(artists, chartData, "artist"); } else if (method.compare(QString(TAG_GET_TOP_ALBUMS)) == 0) { QVariantList albums = response.value("albums").toMap().value("album").toList(); prepareChartData(albums, chartData, "album"); } else { QVariantList tracks = response.value("tracks").toMap().value("track").toList(); prepareChartData(tracks, chartData, "track"); } emit chartLoaded(chartData); } reply->deleteLater(); } void TagController::onError(QNetworkReply::NetworkError e) { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); logger.error(e); logger.error(reply->errorString()); reply->deleteLater(); emit error(); } void TagController::prepareChartData(const QVariantList& source, QVariantList& chartData, const QString& type) { foreach(QVariant var, source) { QVariantMap map = var.toMap(); map["type"] = type; chartData.append(map); } } void TagController::setAccessToken(const QString& accessToken) { m_accessToken = accessToken; } } /* namespace controllers */ } /* namespace lastfm */ } /* namespace bb */
4025f8bcd6cf7e9ecf7363f935177ed5d6eb6632
[ "Markdown", "C++" ]
22
C++
p182/lastapp
97c8c3f8eaea77b1f63ab9a2b82176813fa8003e
81d4ed33c694384c9f2da6a1ebce6da53ce7d705
refs/heads/master
<repo_name>del82/rws<file_sep>/sentence.py import logging import random import re from itertools import takewhile import nltk.data import wikipedia from google.appengine.ext import ndb logger = logging.getLogger(__name__) tokenizer = nltk.data.load('./english.pickle') class Article(ndb.Model): """ an article """ title = ndb.StringProperty(required = True, indexed=False) #content = ndb.JsonProperty(compressed=True, indexed=False) sentence_list = ndb.JsonProperty(compressed=True, indexed=False) revision_id = ndb.IntegerProperty(indexed = False) access_count = ndb.IntegerProperty(indexed = True, default = 1) loaded = ndb.DateTimeProperty(indexed = True, auto_now_add=True) def _smart_tokenize(text): blacklist = '|'.join(['References', # if we see any of these sections, the article's over. 'External links', 'Bibliography', 'See also', 'Further reading', 'Notes', ]) stopper = re.compile('== *(%s) *==' % blacklist) sentences = tokenizer.tokenize(text) pred = lambda x: not bool(stopper.match(x)) return [s for s in list(takewhile(pred, sentences)) if not '==' in s] def _get_random_article(): """ try to get a random article from wikipedia; return None on failure """ try: title = wikipedia.random(1) logger.debug('Trying %s' % title) article = wikipedia.page(title) sentence_list = _smart_tokenize(article.content) local = Article(title = unicode(article.title), revision_id = article.revision_id, sentence_list = sentence_list) if len(sentence_list) > 5: # save only long articles #random.shuffle(sentence_list) # pop off the front? local_key = local.put() return local except wikipedia.exceptions.DisambiguationError: logger.info('Caught DisambiguationError') return None except wikipedia.exceptions.HTTPTimeoutError: logger.info('Caught HTTPTimeoutError') return None def _get_random_cached_article(): queries = Article.query().order(Article.access_count).fetch(50) item = random.choice(queries) item.access_count += 1 item.put() return item def random_article(): article = _get_random_article() if article == None: # wikipedia article collection failed logger.warning("failed to get article from wikipedia") article = _get_random_cached_article() return article def random_sentence(): """ return a random sentence from a random article """ article = random_article() random_sentence = random.choice(article.sentence_list) return {'sentence' : unicode(random_sentence), 'title' : unicode(article.title), 'revision_id' : article.revision_id } <file_sep>/regenerate_error_pages.py import jinja2, wikipedia from itertools import takewhile import nltk.data tokenizer = nltk.data.load('./english.pickle') def _smart_tokenize(text): sentences = tokenizer.tokenize(text) pred = lambda x: x != '== References ==' return [s for s in list(takewhile(pred, sentences)) if not '==' in s] url_500 = "List_of_HTTP_status_codes#5xx_Server_Error" internal_server_error = """500 Internal Server Error: A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.""" service_unavailable = """503 Service Unavailable: The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state.""" if __name__=='__main__': error_404 = {'title' : "HTTP_404"} wiki_404 = wikipedia.page(error_404['title']) error_404['sentence'] = _smart_tokenize(wiki_404.content)[0] template = jinja2.Template(open('index.html').read()) page_404 = template.render(error_404) open('static/404.html','w').write(page_404) error_500 = {'title' : url_500, 'sentence': internal_server_error} error_503 = {'title' : url_500, 'sentence': service_unavailable} open('static/500.html', 'w').write(template.render(error_500)) open('static/503.html', 'w').write(template.render(error_503)) <file_sep>/README.md # rws A little toy that runs on Google App Engine and displays a random sentence from the English Wikipedia with every page load. Currently lives at http://random.wikipedia-sentence.com <file_sep>/main.py #!/usr/bin/env python import os, json, codecs import random import webapp2 import wikipedia import nltk.data import jinja2 import logging import sentence # directly access the default handler and set its format directly #logging.getLogger().handlers[0].setFormatter(fr) logger = logging.getLogger(__name__) from google.appengine.ext import ndb JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape'], autoescape=True) class MainHandler(webapp2.RequestHandler): def get(self): random_sentence = sentence.random_sentence() template = JINJA_ENVIRONMENT.get_template('index.html') self.response.write(template.render(random_sentence)) class JSONHandler(webapp2.RequestHandler): def get(self): random_sentence = sentence.random_sentence() random_sentence['source'] = 'https://en.wikipedia.org/wiki/%s' % random_sentence['title'] self.response.content_type = 'text/json' self.response.write(json.dumps(random_sentence)) class AdminHandler(webapp2.RequestHandler): def get(self): self.response.content_type = 'text/plain' stats = {'total in datastore' : sentence.Article.query().count(), 'total >1 access' : sentence.Article.query(sentence.Article.access_count > 1).count(), } self.response.write(json.dumps(stats, ensure_ascii = False, indent = 2)) class FHHandler(webapp2.RequestHandler): def get(self, error): if not error: error = 500 webapp2.abort(error, detail="as requested.") app = webapp2.WSGIApplication([ ('/', MainHandler), ('/api', JSONHandler), ('/del82_admin', AdminHandler), ('/del82_admin/error/(\d+)?', FHHandler) ], debug=False) def error_404(request, response, exception): logger.exception(exception) response.set_status(404) response.write(open('static/404.html').read()) app.error_handlers[404] = error_404 def error_500(request, response, exception): logger.exception(exception) response.set_status(500) response.write(open('static/500.html').read()) app.error_handlers[500] = error_500 def error_503(request, response, exception): logger.exception(exception) response.set_status(503) response.write(open('static/503.html').read()) app.error_handlers[503] = error_503
c8c86a6e4c139e64a9372653cd34ebb76aa21205
[ "Markdown", "Python" ]
4
Python
del82/rws
038bc7f9fc4894eb19d0242fb2b8c8df073c1965
0e32c8c91e79e8ecdcc338ebbf37ddb0bb577930
refs/heads/main
<file_sep># ToNotion Firefox Extension The purpose of this Firefox Extension is to be able to extract data from websites into Notion in different ways. ## Current State - Can export Kindle books (title, author, image) from https://read.amazon.com into a CSV file. <file_sep>document.getElementById('content').innerHTML = "#Books" const buttonCsv = document.getElementById('extractCSVButton'); function handleResponse(data) { document.getElementById('content').innerHTML = `Data: ${data.data.length}` } buttonCsv.addEventListener("click", async (ev) => { document.getElementById('content').innerHTML = "Waiting" const currentTabs = await browser.tabs.query({ currentWindow: true, active: true }); var sending = browser.tabs.sendMessage(currentTabs[0].id, { command: "fetch" }); sending.then(handleResponse); });<file_sep>function extractKindleBooks() { const coverEl = document.getElementById('cover'); const resArr = []; for (let i = 0; i < coverEl.children.length; i++) { const pTags = coverEl.children[i].getElementsByTagName("p"); const imgTags = coverEl.children[i].getElementsByTagName("img"); if (pTags.length == 2) { resArr.push({ name: pTags[0].innerHTML.replaceAll(",", " "), author: pTags[1].innerHTML.replaceAll(",", " "), imageLink: imgTags[0].src }) } } return resArr; } // Receive data from the extension browser.runtime.onMessage.addListener(data => { console.log('Received Data'); if (data.command === 'fetch') { const books = extractKindleBooks(); let resStr = "title,author,imageLink\r\n"; for (let i = 0; i < books.length; i++) { resStr += `${books[i].name},${books[i].author},${books[i].imageLink}\r\n`; }; var downloadLink = document.createElement("a"); downloadLink.href = encodeURI("data:text/csv;charset=utf-8," + resStr); downloadLink.download = "books.csv"; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); return Promise.resolve({ data: books }); } })
60654e037ccfd562d10e42a385312508872f5d25
[ "Markdown", "JavaScript" ]
3
Markdown
christopherhex/to-notion-firefox-extension
cf77f2f2c7032e202df197d1b84077061b0d63aa
86370ff880f6588b349bc0ed09432190a8f743a9
refs/heads/master
<file_sep>import com.itextpdf.text.DocumentException; import java.io.File; import java.io.IOException; public class Runner { public static void main(String[] args) { // new Menu().showMenu(); Menu menu = new Menu(); menu.showMenu(); /*File file = new File(DEST); file.getParentFile().mkdirs(); new SimpleTable().createPdf(DEST);*/ } } <file_sep>public class Products { private int barcode; private String name; private String category; private double price; // private String rawInfo; //reserved for future use public int getBarcode() { return barcode; } public void setBarcode(int barcode) { this.barcode = barcode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } // public String getRawInfo() { // return rawInfo; // } // public void setRawInfo(String rawInfo) { // this.rawInfo = rawInfo; // } public Products(int barcode, String name, String category, double price/*, String rawInfo*/) { this.barcode = barcode; this.name = name; this.category = category; this.price = price; // this.rawInfo = rawInfo; //reserved for future use } } <file_sep># my_simple_java_se first and simple java project when I was starter :) <file_sep>import com.bethecoder.ascii_table.ASCIITable; import com.bethecoder.ascii_table.impl.CollectionASCIITableAware; import com.bethecoder.ascii_table.spec.IASCIITableAware; import com.itextpdf.text.DocumentException; import java.io.File; import java.io.IOException; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.Scanner; public class FactorPrint { // Buy b = new Buy(); FileWriting fileWriting = new FileWriting(); Scanner sc = new Scanner(System.in); public void factorPrint(ArrayList<Buy> factorList) { if (factorList.size() == 0) { System.out.println("factorPrint is empty"); new Menu().showMenu(); } String customerName; System.out.println("Enter customer name:"); customerName = sc.next(); // calculate total price long tPrice = 0; for (Buy fp : factorList) { tPrice = tPrice + (long) fp.getTotalprice(); } IASCIITableAware iasciiTableAware = new CollectionASCIITableAware<Buy>(factorList, "barcode", "Category", "Name", "Count", "price", "totalprice"); // printShow ASCIITable.getInstance().printTable(iasciiTableAware); // fileShow String tableStr = ASCIITable.getInstance().getTable(iasciiTableAware); tablemaker(tPrice); String absolutePath = fileWriting.createFile(customerName); fileWriting.fileWriter(absolutePath, customerName, tableStr, tPrice); new Menu().showMenu(); } public void tablemaker(double tPrice) { String fstr = String.valueOf(tPrice); int len = fstr.length(); System.out.print("+-------------------------------------------+------------+"); System.out.print("\n| Total Price:"); for (int i = 0; i < (39 - len); i++) { if (i == 30) System.out.print("|"); System.out.print(" "); } System.out.print(tPrice + " $ |\n"); System.out.println("+-------------------------------------------+------------+"); } public static final String DEST = "C:\\java\\prj\\Hyper2\\Customer Factor.pdf"; public void pdfmaker() { File file = new File(DEST); //file.getParentFile().mkdirs(); try { new SimpleTable().createPdf(DEST); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } } } <file_sep>import java.util.ArrayList; import com.bethecoder.ascii_table.ASCIITable; import com.bethecoder.ascii_table.impl.CollectionASCIITableAware; import com.bethecoder.ascii_table.spec.IASCIITableAware; public class Buy { private int barcode; private String category; private String name; private int count; private double price; private double totalprice; // private String rawInfo; public int getBarcode() { return barcode; } public void setBarcode(int barcode) { this.barcode = barcode; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public double getTotalprice() { return totalprice; } public void setTotalprice(double totalprice) { this.totalprice = totalprice; } public Buy() { } public Buy(int barcode, String category, String name, int count, /*double totalPrice,*/ double price) { this.barcode = barcode; this.category = category; this.name = name; this.count = count; this.price = price; this.totalprice = price * count; } FileReading fr = new FileReading(); public static ArrayList<Buy> buyArrayList = new ArrayList<>(); // Buy b; public void buy(int inputBarcode, int inputCount, int i) { // int i = searchInProducts(inputBarcode); //index of food setBarcode(fr.storeArrayList.get(i).getBarcode()); setCategory(fr.storeArrayList.get(i).getCategory()); setName(fr.storeArrayList.get(i).getName()); setCount(inputCount); // setResult(); setPrice(fr.storeArrayList.get(i).getPrice()); buyArrayList.add(new Buy(this.barcode, this.category, this.name, this.count, this.price)); /*b = new Buy(); b.setBarcode(fr.storeArrayList.get(i).getBarcode()); b.setCategory(fr.storeArrayList.get(i).getCategory()); b.setName(fr.storeArrayList.get(i).getName()); b.setPrice(fr.storeArrayList.get(i).getPrice()); result = (int) (inputCount * fr.storeArrayList.get(i).getPrice()); b.setCount(inputCount); b.setTotalPrice(200); buyArrayList.add(b);*/ // new FactorPrint().factorPrint(Buy.buyArrayList); new Menu().showMenu(); // splittingRawInfo(i, inputCount); //this method get (index ,count) --> additionalArrList<> add(expDte,type,totalPrice) } // search index of barcode in storeArrayList<> public int searchInProducts(int inputBarcode) { int ret = -1; int i = 0; while (i != fr.storeArrayList.size()) { int tmpBarcode = fr.storeArrayList.get(i).getBarcode(); if (tmpBarcode == inputBarcode) { return i; } i++; } return ret; } }
d52ba136a2cce2cbf1d3d6ca02c494221f66b935
[ "Markdown", "Java" ]
5
Java
hamidzare71/my_simple_java_se
6ee771939fd7efbcb46a6d937f278ae532370540
5eff9aa0228c05186ca0c3475a7f9b126c5dada1
refs/heads/master
<file_sep>--- layout: post title: "First Post" description: "Testing things out" category: tags: [] --- {% include JB/setup %} Testing out Jekyll for blogging and site design. <file_sep>#!/usr/bin/env bash FILE_NAME="packages.md" PKG_PATH="OpenBSD/5.4/packages/zaurus/" rake page name="$FILE_NAME" sed -E -e 's/^description:.*/tagline: "for Zaurus"\ description: "OpenBSD packages for Zaurus"/' -i "" $FILE_NAME printf "\n## OpenBSD 5.4\n" >> $FILE_NAME printf "\n<ul>\n" >> $FILE_NAME for i in `ls -1 $PKG_PATH`; do printf "<li><a href=\"/$PKG_PATH$i\">$i</a></li>\n" >> $FILE_NAME ;done printf "</ul>\n" >> $FILE_NAME <file_sep>--- layout: post title: "Built irssi" description: "Compiled irssi for Zaurus" category: zaurus tags: ["zaurus", "openbsd", "packages"] --- {% include JB/setup %} Built irssi for OpenBSD/Zaurus and uploaded with new dependencies. Also still hacking away at cmake. :( <file_sep>--- layout: page title: Hello World! tagline: Supporting tagline --- {% include JB/setup %} Welcome! ## Site Articles This blog contains sample posts which help stage pages and blog data. Here's a sample "posts list". <ul class="posts"> {% for post in site.posts %} <li><span>{{ post.date | date_to_string }}</span> &raquo; <a href="{{ BASE_PATH }}{{ post.url }}">{{ post.title }}</a></li> {% endfor %} </ul> ## To-Do <ol> <li>Create an actual front page.</li> <li>Do something with this site.</li> </ol> <file_sep>--- layout: post title: "Built glib2" description: "" category: tags: [] --- {% include JB/setup %} Was able to patch and build glib2 on the Zaurus. Rebuilt irssi, and rxvt with it. Still can't build cmake. :(
edeee196c5be2641c09a7c0ea7fff7f899dfc92a
[ "Markdown", "Shell" ]
5
Markdown
trondd555/trondd555.github.io
4624dbedc96d87812d01e2949608607dd4aa20a7
6b7c03ed572fef3f8cba7a4ec1278e247e7bc252
refs/heads/LineageOS-14.1
<repo_name>hyperion70/TWRP_device_MTS_SMART_Surf_4G<file_sep>/cm.mk # Release name PRODUCT_RELEASE_NAME := SMART Surf LTE $(call inherit-product, device/MTS/SMART_Surf_4G/device_SMART_Surf_4G.mk) TARGET_SCREEN_HEIGHT := 1280 TARGET_SCREEN_WIDTH := 720 # Device identifier. This must come after all inclusions PRODUCT_DEVICE := SMART_Surf_4G PRODUCT_NAME := lineage_SMART_Surf_4G PRODUCT_BRAND := MTS PRODUCT_MODEL := SMART_Surf_4G PRODUCT_MANUFACTURER := MTS <file_sep>/BoardConfig.mk # # Copyright (C) 2012 The Android Open-Source Project # # 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. # # WARNING: Everything listed here will be built on ALL platforms, # including x86, the emulator, and the SDK. Modules must be uniquely # named (liblights.tuna), and must build everywhere, or limit themselves # to only building on ARM if they include assembly. Individual makefiles # are responsible for having their own logic, for fine-grained control. # Architecture TARGET_ARCH := arm TARGET_NO_BOOTLOADER := true TARGET_BOARD_PLATFORM := mt6735m TARGET_CPU_ABI := armeabi-v7a TARGET_CPU_ABI2 := armeabi TARGET_ARCH_VARIANT := armv7-a-neon TARGET_CPU_VARIANT := cortex-a7 TARGET_CPU_SMP := true ARCH_ARM_HAVE_TLS_REGISTER := true TARGET_BOOTLOADER_BOARD_NAME := MT6735M #extracted from stock recovery BOARD_KERNEL_CMDLINE := bootopt=64S3,32N2,32N2 BOARD_MKBOOTIMG_ARGS := --base 0x40000000 --pagesize 2048 --kernel_offset 0x00008000 --ramdisk_offset 0x04000000 --tags_offset 0x0e000000 --board 1471342055 # Partitions BOARD_RECOVERYIMAGE_PARTITION_SIZE := 16777216 BOARD_FLASH_BLOCK_SIZE := 131072 # SELinux BOARD_SEPOLICY_DIRS := \ device/MTS/SMART_Surf_4G/sepolicy # recovery__________TWRP 3.1.0 TARGET_RECOVERY_FSTAB := device/MTS/SMART_Surf_4G/recovery.fstab BOARD_HAS_NO_SELECT_BUTTON := true BOARD_USE_CUSTOM_RECOVERY_FONT := \"roboto_23x41.h\" TW_THEME := portrait_hdpi TW_USE_MODEL_HARDWARE_ID_FOR_DEVICE_ID := true TW_DEFAULT_LANGUAGE := ru TW_DEVICE_VERSION := M-2 by hyperion70 RECOVERY_SDCARD_ON_DATA := true TW_DEFAULT_EXTERNAL_STORAGE := true TW_BRIGHTNESS_PATH := /sys/devices/platform/leds-mt65xx/leds/lcd-backlight/brightness/ TW_MAX_BRIGHTNESS := 255 TARGET_USE_CUSTOM_LUN_FILE_PATH := /sys/class/android_usb/android0/f_mass_storage/lun/file TW_CUSTOM_CPU_TEMP_PATH := /sys/devices/virtual/thermal/thermal_zone1/temp <file_sep>/vendorsetup.sh #used to add device to CM's lunch add_lunch_combo cm_SMART_Surf_4G-$var <file_sep>/README.md TWRP device tree for SMART_Surf_4G (c) hyperion70 - 2017 Basic | Spec Sheet -------:|:------------------------- CPU | 1.0GHz Quad-Core MT6735P GPU | Mali-T720 Memory | 1GB RAM Shipped Android Version | 5.1 Storage | 8GB Battery | 1900 mAh Display | 5.0" 1280 x 720 px Camera | 5MPx + 2MPx, LED Flash ================================= To recovery build in the Lineage OS 14.1 sources $ cd $(SOURCE)/bootable $ rm -rf recovery $ git clone https://github.com/omnirom/android_bootable_recovery recovery $ cd recovery $ git apply -v ../../device/MTS/SMART_Surf_4G/01-twrp_recovery_mtk.patch $ cd ../.. $ . build/envsetup.sh $ breakfast SMART_Surf_4G $ make clean $ make recoveryimage ## Thanks to: * @blastagator * @DeckerSU * @olegsvs * @ariafan * @DeepFlex * @Zormax
7063581b20685d9df302587a11ebe50c3940ef77
[ "Markdown", "Makefile", "Shell" ]
4
Makefile
hyperion70/TWRP_device_MTS_SMART_Surf_4G
50cf1b14571917b79cf888a3cff6c75600ab1828
5643d39748aaff45ac820217814cb34cbe8b5641
refs/heads/master
<repo_name>imbipulkumar/CodeChef<file_sep>/README.md # CodeChef My CodeChef challenges' solutions and explanations.✅ <file_sep>/Rishu/SIMPLE IO-OP.cpp #include<iostream> using namespace std; int main() { int a; char b[100]; cout<<"Enter an integer\n"; cout<<"Enter an arrey value :\n"; cin>>n; for(i=0;i<=n;i++) { cin>>b[i]; } cout<<"your entered Arrey is:"<<"\n"; for(i=0;i<=n;i++) { cout<<b[i]<<" "; } cin>>a; cout<<"Integer that you have entered is:"<<a<<"\n"; return 0; } <file_sep>/Noob Farmer/README.md ## Noob Farmer Problem Code: NFAR Problen link [Noob Farmer | CodeChef](https://codechef_shared.s3.amazonaws.com/download/HYC/External_contest_images/DRI22019/NFAR/1.png) [![NFAR](https://codechef_shared.s3.amazonaws.com/download/HYC/External_contest_images/DRI22019/NFAR/1.png)](https://www.codechef.com/problems/NFAR) [![Solution](https://i.stack.imgur.com/lgOH0.jpg)](https://math.stackexchange.com/questions/3246324/find-area-of-triangle-which-is-divided-into-6-parts-and-areas-of-3-regions-is-gix#new-answer)<file_sep>/Noob Farmer/nfar.cpp //<NAME> //Problem Code: NFAR #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin>>t; while(t--) { long double a,b,c,p,t_area; cin>>a>>b>>c>>p; t_area=(a+b+c)+(a*a*c+a*b*c+a*c*c)/(a*b+b*b-a*c); cout<<fixed<<setprecision(2)<<t_area*p<<endl; } return 0; } /* Sample Input: 2 5 4 4 2 1 2 1 5 Sample Output: 58.50 24.00 */
1a16d910a01df58ee8fd5388cc435c3e4763b675
[ "Markdown", "C++" ]
4
Markdown
imbipulkumar/CodeChef
ddd4f4acece467d39e9e3a5587304af03a1f379f
9ac89d7ec21c8e4ebe7ee67aaadee201314fc92c
refs/heads/master
<file_sep>import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'index', component: (resolve) => { require(['../components/views/todoList/index'], resolve) } }, // { // path: '/', // name: 'leaderAdd', // component: (resolve) => { // require(['../components/views/leader/leaderAdd'], resolve) // } // }, { path: '/tag', name: 'tag', component: (resolve) => { require(['../components/views/list/tag'], resolve) } }, { path: '/leaderIndex', name: 'leaderIndex', component: (resolve) => { require(['../components/views/leader/leaderIndex'], resolve) } }, { path: '/case', name: 'case', component: (resolve) => { require(['../components/views/case/caseManage'], resolve) } }, { path: '/myStudents', name: 'myStudents', component: (resolve) => { require(['../components/views/myStudents'], resolve) } }, { path: '/connectList', name: 'connectList', component: (resolve) => { require(['../components/views/connectList'], resolve) } }, { path: '/connectCheck', name: 'connectCheck', component: (resolve) => { require(['../components/views/connectCheck'], resolve) } }, { path: '/connectCheckDetail', name: 'connectCheckDetail', component: (resolve) => { require(['../components/views/connectCheck/connectCheckDetail'], resolve) } }, { path: '/head', name: 'head', component: (resolve) => { require(['../components/views/HEAD/index'], resolve) } }, { path: '/index1', name: 'index1', component: (resolve) => { require(['../components/views/HEAD/index1'], resolve) } }, { path: '/index2', name: 'index2', component: (resolve) => { require(['../components/views/HEAD/index2'], resolve) } }, { path: '/index3', name: 'index3', component: (resolve) => { require(['../components/views/HEAD/index3'], resolve) } }, ] })
6a8fb19515f74f10c83a9bd16f8944315bf0b148
[ "JavaScript" ]
1
JavaScript
gaoshixing/rili
6cc351d93c83038f2c3859201a7fe693ad405bbf
56d89827d67266a8bbfcdfef8c12df9891e7eb54
refs/heads/master
<file_sep>### README ### Bunch of exercises from Eckels book organized by chapter title. <file_sep>package holding; /* * From Eckel book * * Chapter "holding", Exercise 2 * * Create a generator class that produces character names (as String objects) from your favorite movie * each time you call next(), and loops around to the beginning of the character list when it runs * out of names. Use this generator and fill an array, an ArrayList, a LinkedList, a HashSet, a LinkedHashSet, * and a TreeSet, then print each container. * * Created by <NAME> on 21.10.14. */ import java.util.*; class Ex4helper { private String[] favNames = {"Anna", "Bob", "Tom", "Han", "Chuwbaka", "Lea", "Luk", "Luk"}; private ArrayList<String> arrListNames = new ArrayList<String>(); private List<String> linkedListNames = new LinkedList<String>(); private Set<String> hashSetNames = new HashSet<String>(); private Set<String> linkedSetNames = new LinkedHashSet<String>(); private Set<String> treeSetNames = new TreeSet<String>(); Ex4helper() { generateCollections(); } private void generateCollections() { for (String name : favNames) { arrListNames.add(name); linkedListNames.add(name); hashSetNames.add(name); linkedSetNames.add(name); treeSetNames.add(name); } } public void printAllCollections() { System.out.println(arrListNames); System.out.println(linkedListNames); System.out.println(hashSetNames); System.out.println(linkedSetNames); System.out.println(treeSetNames); } } public class Exercise4 { public static void main(String[] args) { Ex4helper helper = new Ex4helper(); helper.printAllCollections(); } } /* Output: [Anna, Bob, Tom, Han, Chuwbaka, Lea, Luk, Luk] [Anna, Bob, Tom, Han, Chuwbaka, Lea, Luk, Luk] [Tom, Luk, Bob, Han, Chuwbaka, Lea, Anna] [Anna, Bob, Tom, Han, Chuwbaka, Lea, Luk] [Anna, Bob, Chuwbaka, Han, Lea, Luk, Tom] */ <file_sep>package innerclasses; /* * innerclasses/exercise3 * from Eckel * * Modify Exercise 1 so that Outer has a private String field (initialized by constructor), * and Inner has a toString() method that displays this field. Create an object of type Inner * and display it. * * Created by <NAME> on 19.10.14. */ class Outer2 { //to prevent name collision with ex1 private String message; Outer2 () { message = "This is Outer2"; } class Inner { public void sayHello() { System.out.println("Hello, I am Inner"); } public String toString() { return message; } } public Inner getInner() { return new Inner(); } } public class Exercise3 { public static void main(String[] args) { Outer2 outerObj = new Outer2(); outerObj.getInner().sayHello(); Outer2.Inner innerObj = outerObj.getInner(); System.out.println(innerObj.toString()); } } /* output: Hello, I am Inner */ <file_sep>package holding; /* * From Eckel book * * Chapter "holding", Exercise 2 * * Modify SimpleCollection.java to use a Set for c * * Created by <NAME> on 20.10.14. */ import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Set; public class Exercise2 { public static void main(String[] args) { Set<Integer> c = new HashSet<Integer>() { }; for (int i = 0; i < 10; i++) { c.add(i); c.add(i+2); //demonstrate how the Set works. Only unique added. } for (Integer i : c) { System.out.print(i + ", "); } } } /* Out: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, */ /* Original version public class Exercise2 { public static void main(String[] args) { Collection<Integer> c = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { c.add(i); } for (Integer i : c) { System.out.print(i + ", "); } } } */ <file_sep>package innerclasses; /* * innerclasses/exercise1 * from Eckel * * Write a class named Outer that contains an inner class named Inner. Add a method * too Outer that returns an object of type Inner. In main(), create and initialize * a reference to an Inner. * * Created by <NAME> on 19.10.14. */ class Outer { class Inner { public void sayHello() { System.out.println("Hello, I am Inner"); } } public Inner getInner() { return new Inner(); } } public class Exercise1 { public static void main(String[] args) { Outer outerObj = new Outer(); outerObj.getInner().sayHello(); } } /* output: Hello, I am Inner */ <file_sep>package innerclasses; /* * innerclasses/exrecise5 * from Eckel * * Created by <NAME> on 19.10.14. * * Create a class with an inner class. In a separate class make an instance of the inner class. * * */ class AnotherOuter { class Inner { Inner () { System.out.println("Hello, I am Inner class."); } } } public class Exercise5 { public static void main(String[] args) { AnotherOuter outerObj = new AnotherOuter(); AnotherOuter.Inner innerObj = outerObj.new Inner(); } } /* output: Hello, I am Inner class. */ <file_sep>/* * /interfaces/exercise 13 * from Eckel. * * Create a framework using Factory Methods that performs both coin tossing and dice tossing. * * 19.10.14 * * By <NAME> */ import java.util.Random; interface Tosser { String getTossResult(); } interface TosserFactory { Tosser getTosser(); } class Coin implements Tosser { @Override public String getTossResult() { return (Math.random() <= 0.5d) ? "Heads" : "Tails"; } } class Dice implements Tosser { @Override public String getTossResult() { Random rand = new Random(); return "Dice showed " + (rand.nextInt(6) + 1); //note: nextInt(n) -- n exclusive. } } class CoinFactory implements TosserFactory { @Override public Tosser getTosser() { return new Coin(); } } class DiceFactory implements TosserFactory { @Override public Tosser getTosser() { return new Dice(); } } public class FactoryMethodExercise { public static void main(String[] args) { Random rand = new Random(); TosserFactory[] tosserFactoriesArray = {new CoinFactory(), new DiceFactory()}; for (int i=1; i<20; i++) { TosserFactory randTosserFactory = tosserFactoriesArray[rand.nextInt(2)]; Tosser randTosser = randTosserFactory.getTosser(); System.out.println(randTosser.getTossResult()); } } } /* Output example: Heads Dice showed 1 Tails Dice showed 4 Dice showed 6 */<file_sep>package innerclasses; /* * innerclasses/exercise12 * * Created by <NAME> on 20.10.2014 * * Repeat Exercise 7 using an anonymous inner class. * * (Exercise 7: Create a class with a private field and a private method. * Create an inner class with a method that modifies the outer-class field and calls the outer-class method. * In a second outer-class method, create an object of the inner class and call its method, then show the * effect on the outer-class object.) * */ class Ex12Support { private String message = "Hello"; private void sayHello() { System.out.println(message); } class Inner { public void modify(String newMessage) { message = newMessage; sayHello(); } } public void callInnerMethod() { Inner innerObj = new Inner(); innerObj.modify("Ok, private var is modified."); } } public class Exercise12 { public static void main(String[] args) { Ex12Support outerObj = new Ex12Support(); outerObj.callInnerMethod(); } } /* output: Ok, private var is modified. */
0c934acb310872b8a3a74b06d33a4ef5e7510cce
[ "Markdown", "Java" ]
8
Markdown
AndrewBaliushin/Learning-Java
a818ee455b0d6798ab867e8de17c282511f7c931
5b82ee5119b00073ed7eb07c76342f9e20902367
refs/heads/master
<repo_name>sbuoy/mean421<file_sep>/final/meanPCParts/ERPHomePage Scott 2 2 2/js/delete.js function deletePO() { var id = +document.getElementById("deleteField").value; $.ajax({ method: "DELETE", url: "https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=Inventory421", data: JSON.stringify({ TableName: "PurchReq421", Key:{ "prOrderId": document.getElementById("prOrderId").value } }), success: reloadPage, contentType: "application/json", error: function ajaxError(jqXHR, textStatus, errorThrown) { console.error("Error creating order: ‘, textStatus, ‘, Details: , errorThrown"); console.error("Response: ’, jqXHR.responseText"); alert("An error occured when requesting your unicorn:\n’ + jqXHR.responseText"); } }); alert(id + 'has been deleted'); } <file_sep>/final/meanPCParts/ERPHomePage Scott 2 2 2/js/CRUD/salesorder.js //Get method// $(document).ready(function () { $(document).ready(function () { $("#viewInventory").click(function () { $.get("https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=Sales_Order", function (data, status) { var $table = $('#Items'); $('#Items').bootstrapTable({ data: data.Items }); }); }); }); $("#submit").click(function () { // POSTInventory method var jsonDoc = { "TableName": "Sales_Order", "Item": { "Sales_Order_Number": document.getElementById("Sales_Order_Number").value, "Date": document.getElementById("Date").value, "Payment_Method": document.getElementById("Payment_Method").value, //"Product_Design": document.getElementById("Product_Design").value, "Product_Serial_Number": document.getElementById("Product_Serial_Number").value, //"Quantity": document.getElementById("Quantity").value, "Shipping_Information": document.getElementById("Shipping_Information").value, // "Shipping_Address": document.getElementById("Shipping_Address").value, //"Shipping_City": document.getElementById("Shipping_City").value, // "Shipping_Country": document.getElementById("Shipping_Country").value, // "Shipping_Email": document.getElementById("Shipping_Email").value, // "Shipping_Name": document.getElementById("Shipping_Name").value, // "Shipping_Phone_Number": document.getElementById("Shipping_Phone_Number").value, // "Shipping_State": document.getElementById("Shipping_State").value, // "Shipping_Zip_Code": document.getElementById("Shipping_Zip_Code").value, "Total": document.getElementById("Total").value, "Customer_ID": document.getElementById("Customer_ID").value, } }; $.ajax({ url: "https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=Sales_Order", type: "POST", data: /* $("#form").serialize() */ JSON.stringify(jsonDoc), dataType: "json", sucess: function (jsonDoc) { console.info(jsonDoc); } }); alert("Successfully Submited!") }); // Update method $("#updateInventory").click(function () { var jsonDoc = { "TableName": "Sales_Order", "Key": { "Sales_Order_Number": document.getElementById("Sales_Order_Number").value }, "UpdateExpression": "set Product_Serial_Number= :a, Payment_Method =:e, Date =:b, Total =:h, Product_Design =:f, Shipping_Information =:g, Customer_ID =:i, ", //* Quantity =:c, Shipping_Address =:d, Shipping_City =:o, Shipping_Country =:j, Shipping_Email =:v, Shipping_Name =:x, Shipping_Phone_Number =:u, Shipping_State =:z, Shipping_Zip_Code =:s,*// "ExpressionAttributeValues": { ":b": document.getElementById("Date").value, ":e": document.getElementById("Payment_Method").value, ":f": document.getElementById("Product_Design").value, ":g": document.getElementById("Shipping_Information").value, ":h": document.getElementById("Total").value, ":i": document.getElementById("Customer_ID").value, ":a": document.getElementById("Product_Serial_Number").value, // ":c": document.getElementById("Quantity").value, // ":d": document.getElementById("Shipping_Address").value, // ":o": document.getElementById("Shipping_City").value, // ":j": document.getElementById("Shipping_Country").value, // ":v": document.getElementById("Shipping_Email").value, // ":x": document.getElementById("Shipping_Name").value, // ":u": document.getElementById("Shipping_Phone_Number").value, // ":z": document.getElementById("Shipping_State").value, // ":s": document.getElementById("Shipping_Zip_Code").value, }, "ReturnValues": "UPDATED_NEW" }; $.ajax({ url: "https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=Sales_Order", type: "PUT", data: JSON.stringify(jsonDoc), dataType: "json", sucess: function (jsonDoc) { console.info(jsonDoc); } }); if (alert("Updated Sales Order Info!")) {} else window.location.reload(); }); $("#deleteInventory").click(function () { // deleteInventory method var jsonDoc = { "TableName": "Sales_Order", "Key": { "Sales_Order_Number": document.getElementById("Sales_Order_Number").value } }; $.ajax({ url: "https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=Sales_Order", type: "delete", data: JSON.stringify(jsonDoc), dataType: "json", sucess: function (jsonDoc) { console.info(jsonDoc); } }); alert("Deleting record!") }); }); <file_sep>/final/meanPCParts/ERPHomePage Scott 2 2 2/js/CRUD/purchaseorder.js //Get method// $(document).ready(function() { $(document).ready(function() { $("#viewInventory").click(function() { $.get("https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=PurchReq421", function(data, status) { var $table = $('#Items'); $('#Items').bootstrapTable({ data: data.Items }); }); }); }); $("#submit").click(function() { // POSTInventory method var jsonDoc = { "TableName": "PurchReq421", "Item": { "prOrderId": document.getElementById("prOrderId").value, "color": document.getElementById("color").value, "itemID": document.getElementById("itemID").value, "orderDate": document.getElementById("orderDate").value, "orderStatus": document.getElementById("orderStatus").value, "price": document.getElementById("price").value, "quantity": document.getElementById("quantity").value, "vendorCity": document.getElementById("vendorCity").value, "vendorCountry": document.getElementById("vendorCountry").value, "vendorEmail": document.getElementById("vendorEmail").value, "vendorName": document.getElementById("vendorName").value, "vendorPhone": document.getElementById("vendorPhone").value, "vendorState": document.getElementById("vendorState").value, "vendorStreet": document.getElementById("vendorStreet").value } }; $.ajax({ url: "https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=PurchReq421", type: "POST", data: /* $("#form").serialize() */ JSON.stringify(jsonDoc), dataType: "json", sucess: function(jsonDoc) { console.info(jsonDoc); } }); alert("Successfully Submited!") }); $("#updateInventory").click(function() { // Update method var jsonDoc = { "TableName": "PurchReq421", "Key": { "prOrderId": document.getElementById("prOrderId").value }, "UpdateExpression": "set color = :a, itemID =:b, orderDate =:c, orderStatus =:e, price =:f, quantity =:g, vendorCity =:h, vendorCountry =:i, vendorEmail =:j, vendorName =:k, vendorPhone =:m, vendorState =:n, vendorStreet =:l", "ExpressionAttributeValues": { ":a": document.getElementById("color").value, ":b": document.getElementById("itemID").value, ":c": document.getElementById("orderDate").value, ":e": document.getElementById("orderStatus").value, ":f": document.getElementById("price").value, ":g": document.getElementById("quantity").value, ":h": document.getElementById("vendorCity").value, ":i": document.getElementById("vendorCountry").value, ":j": document.getElementById("vendorEmail").value, ":k": document.getElementById("vendorName").value, ":m": document.getElementById("vendorPhone").value, ":n": document.getElementById("vendorState").value, ":l": document.getElementById("vendorStreet").value }, "ReturnValues": "UPDATED_NEW" }; $.ajax({ url: "https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=PurchReq421", type: "PUT", data: JSON.stringify(jsonDoc), dataType: "json", sucess: function(jsonDoc) { console.info(jsonDoc); } }); alert("Updated PO Info!") }); $("#deleteInventory").click(function() { // deleteInventory method var jsonDoc = { "TableName": "PurchReq421", "Key": { "prOrderId": document.getElementById("prOrderId").value } }; $.ajax({ url: "https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=PurchReq", type: "delete", data: JSON.stringify(jsonDoc), dataType: "json", sucess: function(jsonDoc) { console.info(jsonDoc); } }); alert("Deleting record!") }); }); <file_sep>/final/meanPCParts/ERPHomePage Scott 2 2 2/js/CRUD/getcurrentuser.js function lAttribute(){ var data = { UserPoolId: _config.cognito.userPoolId, ClientId: _config.cognito.userPoolClientId, }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data); var cognitoUser = userPool.getCurrentUser(); try { if (cognitoUser != null) { cognitoUser.getSession(function(err, session) { if (err) { console.log(err); return; } /* console.log('session validity: ' + session.isValid()); console.log('session token: ' + session.getIdToken().getJwtToken()); */ }); var userinfo = cognitoUser.getUserAttributes(function(err,result){ if (err) { //alert(err); return; } // save username localStorage.setItem("username", result[0].getValue()); var accountInfo = ''; /* for (i = 0; i < result.length; i++) { console.log('attribute ' + result[i].getName() + ' has value ' + result[i].getValue()); } */ /* Update navigation */ document.getElementById("dropdownMenu1").innerHTML = result[5].getValue() + ' ' + result[6].getValue(); document.getElementById("signout").innerHTML += '<a href="account.html">Account Details</a><br><br>'; document.getElementById("signout").innerHTML += '<button class="btn btn-primary" onclick="signOutCurrent();">Sign Out</button>'; document.getElementById("signinForm").style.visibility="hidden"; var fulladdress = (result[1].getValue()).split('\n'); var fphonenumber =(result[4].getValue()).split('+1'); if(window.location.href.split("/").slice(-1) == "account.html") { /* Update account information page */ accountInfo = ` <div class="form-group row"> <label for="account" class="col-4 col-form-label">First Name</label> <div class="col-8"> <input id="first-name" class="form-control here"type="text" value="${result[5].getValue()}"> </div> </div> <div class="form-group row"> <label for="account" class="col-4 col-form-label">Last Name</label> <div class="col-8"> <input id="last-name" class="form-control here"type="text" value="${result[6].getValue()}"> </div> </div> <div class="form-group row"> <label for="account" class="col-4 col-form-label">Street Address</label> <div class="col-8"> <input id="street-address" class="form-control here"type="text" value="${fulladdress[0]}"> </div> </div> <div class="form-group row"> <label for="account" class="col-4 col-form-label">City</label> <div class="col-8"> <input id="city" class="form-control here"type="text" value="${fulladdress[1]}"> </div> </div> <div class="form-group row"> <label for="account" class="col-4 col-form-label">State</label> <div class="col-8"> <input id="state"class="form-control here" type="text" value="${fulladdress[2]}"> </div> </div> <div class="form-group row"> <label for="account" class="col-4 col-form-label">Zipcode</label> <div class="col-8"> <input id="zip-code" class="form-control here" type="text" value="${fulladdress[3]}"> </div> </div> <div class="form-group row"> <label for="account" class="col-4 col-form-label">Country</label> <div class="col-8"> <input id="country" class="form-control here" type="text" value="${fulladdress[4]}"> </div> </div> <div class="form-group row"> <label for="account" class="col-4 col-form-label">Phone Number</label> <div class="col-8"> <input id="phone-number" class="form-control here" type="text" value="${fphonenumber[1]}"> </div> </div> <div class="form-group row"> <label for="account" class="col-4 col-form-label">Email</label> <div class="col-8"> <input id="email" class="form-control here" type="text" value="${result[7].getValue()}"> </div> </div> <div class="form-group row"> <div class="offset-4 col-8"> <input id="submit" type="button" name="submit" class="btn btn-info" value="Submit" onclick="addAttribute():"> </div> </div> <div class="col-xs-6"> <h4>Change Password</h4> <hr> <div class="form-group row"> <label for="account" class="col-4 col-form-label">Old Password</label> <div class="col-8"> <input type="password" class="form-control" id="oldPassword" placeholder="<PASSWORD>" required> </div> </div> <div class="form-group row"> <label for="account" class="col-4 col-form-label">New Password</label> <div class="col-8"> <input type="password" class="form-control" id="newPassword" placeholder="<PASSWORD> " required> </div> </div> <div class="offset-4 col-8"> <input id="changePass" type="button" class="btn btn-lg btn-success" value="Change Password" onclick="cPassword();"> <input id="deleteUser" type="button" class="btn btn-lg" value="Delete Account" onclick="deleteUser();"> </br> `; } document.getElementById("account-info").innerHTML = accountInfo; }); } else { if(window.location.href.split("/").slice(-1) == "account.html") { /* Update account information page */ document.getElementById("account-info").innerHTML = ''; document.getElementById("account-info").innerHTML += '<p>You are not logged in.</p>'; return; } } } catch (e) { console.log(e); return; } } function deleteUser(){ var data = { UserPoolId: _config.cognito.userPoolId, ClientId: _config.cognito.userPoolClientId, }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data); var cognitoUser = userPool.getCurrentUser(); try { if (cognitoUser != null) { cognitoUser.getSession(function(err, session) { if (err) { console.log(err); return; } console.log('session validity: ' + session.isValid()); console.log('session token: ' + session.getIdToken().getJwtToken()); }); cognitoUser.deleteUser(function(err, result) { if (err) { alert(err); return; } console.log('call result: ' + result); }); } else { console.log(err); return; } } catch (e) { console.log(e); return; } alert('Your account has been deleted.') } function cPassword(){ var oldPassword =document.getElementById("oldPassword").value; var newPassword =document.getElementById("newPassword").value; var data = { UserPoolId: _config.cognito.userPoolId, ClientId: _config.cognito.userPoolClientId, }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data); var cognitoUser = userPool.getCurrentUser(); try { if (cognitoUser != null) { cognitoUser.getSession(function(err, session) { if (err) { console.log(err); return; } console.log('session validity: ' + session.isValid()); }); cognitoUser.changePassword(oldPassword, newPassword, function(err, result) { if (err) { alert(err); return; } console.log('call result: ' + result); }); } else { console.log(err); return; } } catch (e) { console.log(e); return; } } function forgotpasswordbutton() { var poolData = { UserPoolId: _config.cognito.userPoolId, ClientId: _config.cognito.userPoolClientId }; var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData); var userData = { Username : document.getElementById("emailReset").value, Pool : userPool, }; var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData); cognitoUser.forgotPassword({ onSuccess: function (result) { console.log('call result: ' + result); window.location.assign("./index.html"); //alert("Y") }, onFailure: function(err) { alert(err); console.log(err); }, inputVerificationCode() { window.location.href = "forgot-pass-verify.html"; } }); } function forgotPasswordUpdate() { var poolData = { UserPoolId: _config.cognito.userPoolId, ClientId: _config.cognito.userPoolClientId }; var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData); var userData = { Username : document.getElementById("forgotUser").value, Pool : userPool, }; var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData); var verificationCode = $('#forgotPassCode').val(); var user = $('#forgotUser').val(); var newPassword = $('#<PASSWORD>').val(); var newPassword2 = $('#forgot<PASSWORD>').val(); console.log(document.getElementById("forgotUser").value); if(newPassword == newPassword2) { console.log("here"); cognitoUser.confirmPassword(verificationCode, newPassword, this); alert("Sucessfully changed password.") } else { alert("Passwords do not match.") } } function signOutCurrent(){ VinylCutting.signOut(); window.location.assign("./index.html"); } function getCustomerOrders() { var data = { UserPoolId: _config.cognito.userPoolId, ClientId: _config.cognito.userPoolClientId, }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data); var cognitoUser = userPool.getCurrentUser(); try { if (cognitoUser != null) { cognitoUser.getSession(function (err, session) { if (err) { console.log(err); return; } }); var userinfo = cognitoUser.getUserAttributes(function (err, result) { if (err) { //alert(err); return; } // Get list of sales orders var API ="https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test2/CRUD?TableName=Sales_Order"; var JSONObject ={} try { $.getJSON(API,JSONObject) .done(function (json) { var counter = 1; for(var i = 0; i < json.Items.length; i++) { if(json.Items[i].Customer_ID == result[0].getValue()) { var orderNum = json.Items[i].Sales_Order_Number; var fullName = (json.Items[i].Shipping_Information.Shipping_Name).split(" "); var firstName = fullName[0]; var lastName = fullName[1]; var shippingAddress = json.Items[i].Shipping_Information.Shipping_Address + " " + json.Items[i].Shipping_Information.Shipping_City + ", " + json.Items[i].Shipping_Information.Shipping_State + " " + json.Items[i].Shipping_Information.Shipping_Zip_Code; var date = json.Items[i].Date; var price = "$" + json.Items[i].Total; var status = "Processing"; var order = ` <tr> <td>${counter}</td> <td>${orderNum}</td> <td>${shippingAddress}</td> <td>${date}</td> <td>${price}</td> <td>${status}</td> </tr> `; $('#customer_orders').append(order); counter += 1; } } }); } catch(err){ console.log(err); } }); } } catch (e) { console.log(e); return; } } window.onload = lAttribute(); if (window.location.href.split("/").slice(-1) == "myorder.html") { window.onload = getCustomerOrders(); } <file_sep>/final/meanPCParts/ERPHomePage Scott 2 2 2/js/crudusers.js var API = "https://9c28xk5i38.execute-api.us-east-1.amazonaws.com/ListUser/user"; var JSONObject = {} function setup() { payload = JSON.parse(sessionStorage.getItem("payload")); var counter = 1; for (var i = 0; i < payload.Users.length; i++) { var customerId = payload.Users[i].Username; var customerFirstName = payload.Users[i].Attributes[5].Value; var customerLastName = payload.Users[i].Attributes[6].Value; var address = (payload.Users[i].Attributes[1].Value).split('\n'); var streetAddress = address[0]; var city = address[1]; var state = address[2]; var zip = address[3]; var country = address[4]; var email = payload.Users[i].Attributes[7].Value; var phone = payload.Users[i].Attributes[4].Value; var status = payload.Users[i].UserStatus; var tableRow = ` <tr> <td>${counter}</td> <td>${customerId}</td> <td>${customerFirstName}</td> <td>${customerLastName}</td> <td>${streetAddress}</td> <td>${city}</td> <td>${state}</td> <td>${zip}</td> <td>${country}</td> <td>${email}</td> <td>${phone}</td> <td><span class="label label-info">${status}</span></td> </tr> `; // append to table $('#customerTable').append(tableRow); counter += 1; } } function search() { var counter = 1; var id = document.getElementById("search-customer-id").value; var firstName = document.getElementById("search-first-name").value; var lastName = document.getElementById("search-last-name").value; var streetAddress = document.getElementById("search-street-address").value; var city = document.getElementById("search-city").value; var state = document.getElementById("search-state").value; var zip = document.getElementById("search-zip-code").value; var country = document.getElementById("search-country").value; var email = document.getElementById("search-email").value; var phone = document.getElementById("search-phone-number").value; var status = document.getElementById("search-status").value; payload = JSON.parse(sessionStorage.getItem("payload")); payloadRefined = { "Users": [] }; // Cycle through all cases and check var add = true; for (var i = 0; i < payload.Users.length; i++) { var address = (payload.Users[i].Attributes[1].Value).split('\n'); add = true; if (id != "" && !String(payload.Users[i].Username).includes(id)) { add = false; } if (firstName != "" && !String(payload.Users[i].Attributes[5].Value).includes(firstName)) { add = false; } if (lastName != "" && !String(payload.Users[i].Attributes[6].Value).includes(lastName)) { add = false; } if (streetAddress != "" && !String(address[0]).includes(streetAddress)) { add = false; } if (city != "" && !String(address[1]).includes(city)) { add = false; } if (state != "" && !String(address[2]).includes(state)) { add = false; } if (zip != "" && !String(address[3]).includes(zip)) { add = false; } if (country != "" && !String(address[4]).includes(country)) { add = false; } if (email != "" && !String(payload.Users[i].Attributes[7].Value).includes(email)) { add = false; } if (phone != "" && !String(payload.Users[i].Attributes[4].Value).includes(phone)) { add = false; } if (status != "" && !String(payload.Users[i].UserStatus).includes(status)) { add = false; } if (add) { payloadRefined.Users.push(payload.Users[i]); } } // Remove all elements of the current table var myNode = document.getElementById("searchCustomerTable"); while (myNode.firstChild) { myNode.removeChild(myNode.firstChild); } // Print payload after refining search for (var i = 0; i < payloadRefined.Users.length; i++) { var customerId = payloadRefined.Users[i].Username; var customerFirstName = payloadRefined.Users[i].Attributes[5].Value; var customerLastName = payloadRefined.Users[i].Attributes[6].Value; var address = (payloadRefined.Users[i].Attributes[1].Value).split('\n'); var streetAddress = address[0]; var city = address[1]; var state = address[2]; var zip = address[3]; var country = address[4]; var email = payloadRefined.Users[i].Attributes[7].Value; var phone = payloadRefined.Users[i].Attributes[4].Value; var status = payloadRefined.Users[i].UserStatus; var tableRow = ` <tr> <td>${counter}</td> <td>${customerId}</td> <td>${customerFirstName}</td> <td>${customerLastName}</td> <td>${streetAddress}</td> <td>${city}</td> <td>${state}</td> <td>${zip}</td> <td>${country}</td> <td>${email}</td> <td>${phone}</td> <td><span class="label label-info">${status}</span></td> </tr> `; // append to table $('#searchCustomerTable').append(tableRow); counter += 1; } } function deleteCustomer() { var payload = { "username": document.getElementById("delete-customer-id").value } console.log(payload); // DELETE method $.ajax({ url: API, type: "DELETE", data: JSON.stringify(payload), dataType: "json", success: function() { alert("Successfully deleted customer."); location.reload(); }, error: function() { alert("An error occured."); } }); } //get the payload function grab() { try { $.getJSON(API, JSONObject) .done(function (json) { sessionStorage.setItem("payload", JSON.stringify(json)); setup(); }); } catch (err) { console.log(err); } } window.onload = grab(); <file_sep>/final/meanPCParts/ERPHomePage Scott 2 2 2/js/crudsalesorders.js var API = "https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=Sales_Order421"; var JSONObject = {} function setup() { payload = JSON.parse(sessionStorage.getItem("payload")); var counter = 1; for (var i = 0; i < payload.Items.length; i++) { var orderNum = payload.Items[i].Sales_Order_Number; var fullName = (payload.Items[i].Shipping_Information.Shipping_Name).split(" "); var firstName = fullName[0]; var lastName = fullName[1]; var shippingAddress = payload.Items[i].Shipping_Information.Shipping_Address + " " + payload.Items[i].Shipping_Information.Shipping_City + ", " + payload.Items[i].Shipping_Information.Shipping_State + " " + payload.Items[i].Shipping_Information.Shipping_Zip_Code; var date = payload.Items[i].Date; var price = "$" + payload.Items[i].Total; var status = "Processing"; var tableRow = ` <tr> <td>${counter}</td> <td>${orderNum}</td> <td>${firstName}</td> <td>${lastName}</td> <td>${shippingAddress}</td> <td>${date}</td> <td>${price}</td> <td><span class="label label-info">${status}</span></td> </tr> `; // Append to table $('#salesTable').append(tableRow); counter += 1; } // get product payload var API2 ="https://mhq011eieb.execute-api.us-east-1.amazonaws.com/product"; var JSONObject2 ={ "TableName": "Product421", "Type" : "Full", "id" : "YEL477" } $.getJSON(API2,JSONObject2) .done(function (json) { sessionStorage.setItem("payload-product", JSON.stringify(json)); }); } function createSalesOrder() { var salesOrder = { "TableName": "Sales_Order421", "Item": "" } var date = new Date(); date.setHours(date.getHours()-5); date.toISOString(); var payload = { "Sales_Order_Number": parseInt(date.getTime()), "Customer_ID": "", "Shipping_Information": "", "Product_Design": [], "Date": "", "Payment_Method": "", "Total": "" }; var shippingInformation = { "Shipping_Name": "", "Shipping_Address": "", "Shipping_City": "", "Shipping_State": "", "Shipping_Zip_Code": "", "Shipping_Country": "", "Shipping_Phone_Number": "", "Shipping_Email": "" }; payload.Customer_ID = 'Admin'; // Add shipping information shippingInformation.Shipping_Name = document.getElementById("create-first-name").value + " " + document.getElementById("create-last-name").value; shippingInformation.Shipping_Address = document.getElementById("create-street-address").value; shippingInformation.Shipping_City = document.getElementById("create-city").value; shippingInformation.Shipping_State = document.getElementById("create-state").value; shippingInformation.Shipping_Zip_Code = document.getElementById("create-zip-code").value; shippingInformation.Shipping_Country = document.getElementById("create-country").value; shippingInformation.Shipping_Phone_Number = document.getElementById("create-phone-number").value; shippingInformation.Shipping_Email = document.getElementById("create-user-email").value; payload.Shipping_Information = shippingInformation; var cart = document.getElementById("create-cart").value + ","; // Append extra comma to extra last item var items = cart.split(","); var total = 0; productPayload = JSON.parse(sessionStorage.getItem("payload-product")); for(var i = 0; i < items.length - 1; i++) { var productDesign = { "Product_Serial_Number": "", "Quantity": "" } productDesign.Product_Serial_Number = items[i]; productDesign.Quantity = 1; payload.Product_Design.push(productDesign); console.log(payload.Product_Design); for (var j = productPayload - 1; j >= 0; j--) { if(items[i] == productPayload[j].Product_Serial_Number) { var price = productPayload[j].Product_Price; price = Number(price.substring(1)); total += price; } } } payload.Total = total.toFixed(2);; // Add date payload.Date = date; // Add payment method payload.Payment_Method = "Credit"; // Add to sales order payload salesOrder.Item = payload; console.log(salesOrder); // POST method $.ajax({ url: "https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=Sales_Order421", type: "POST", data: JSON.stringify(salesOrder), dataType: "json", success: function() { alert("Sucessfully created order!") location.reload(); }, error: function(jqXHR, textStatus, errorThrown) { alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!'); $('#result').html('<p>status code: '+jqXHR.status+'</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>'); console.log('jqXHR:'); console.log(jqXHR); console.log('textStatus:'); console.log(textStatus); console.log('errorThrown:'); console.log(errorThrown); } }); } function search() { var counter = 1; var orderNum = document.getElementById("search-order-number").value; var firstName = document.getElementById("search-first-name").value; var lastName = document.getElementById("search-last-name").value; var shippingAddress = document.getElementById("search-shipping-address").value; var date = document.getElementById("search-date").value; var price = document.getElementById("search-price").value; var status = document.getElementById("search-status").value; payload = JSON.parse(sessionStorage.getItem("payload")); payloadRefined = { "Items": [] }; var add = true; for(var i = 0; i < payload.Items.length; i++) { add = true; var fullName = (payload.Items[i].Shipping_Information.Shipping_Name).split(" "); var payloadShippingAddress = payload.Items[i].Shipping_Information.Shipping_Address + " " + payload.Items[i].Shipping_Information.Shipping_City + ", " + payload.Items[i].Shipping_Information.Shipping_State + " " + payload.Items[i].Shipping_Information.Shipping_Zip_Code; if(orderNum != "" && !String(payload.Items[i].Sales_Order_Number).includes(orderNum)) { add = false; } if(firstName != "" && !String(fullName[0]).includes(firstName)) { add = false; } if(lastName != "" && !String(fullName[1]).includes(lastName)) { add = false; } if(shippingAddress != "" && !String(payloadShippingAddress).includes(shippingAddress)) { add = false; } if(date != "" && !String(payload.Items[i].Date).includes(date)) { add = false; } if(price != "" && !String(payload.Items[i].Total).includes(price)) { add = false; } if(add) { payloadRefined.Items.push((payload.Items[i])); } } console.log(payloadRefined); // Remove all elements of the current table var myNode = document.getElementById("searchSalesTable"); while (myNode.firstChild) { myNode.removeChild(myNode.firstChild); } for (var i = 0; i < payloadRefined.Items.length; i++) { var orderNum = payloadRefined.Items[i].Sales_Order_Number; var fullName = (payloadRefined.Items[i].Shipping_Information.Shipping_Name).split(" "); var firstName = fullName[0]; var lastName = fullName[1]; var shippingAddress = payloadRefined.Items[i].Shipping_Information.Shipping_Address + " " + payloadRefined.Items[i].Shipping_Information.Shipping_City + ", " + payloadRefined.Items[i].Shipping_Information.Shipping_State + " " + payloadRefined.Items[i].Shipping_Information.Shipping_Zip_Code; var date = payloadRefined.Items[i].Date; var price = "$" + payloadRefined.Items[i].Total; var status = "Processing"; var tableRow = ` <tr> <td>${counter}</td> <td>${orderNum}</td> <td>${firstName}</td> <td>${lastName}</td> <td>${shippingAddress}</td> <td>${date}</td> <td>${price}</td> <td><span class="label label-info">${status}</span></td> </tr> `; // Append to table $('#searchSalesTable').append(tableRow); counter += 1; } } function setUpdateValues() { var payload = JSON.parse(sessionStorage.getItem("payload")); for(var i = 0; i < payload.Items.length; i++) { if(payload.Items[i].Sales_Order_Number == document.getElementById("update-sales-id").value) { console.log(payload.Items[i]); var fullName = payload.Items[i].Shipping_Information.Shipping_Name.split(" "); var firstName = fullName[0]; var lastName = fullName[1]; // Fill in text boxes document.getElementById("update-first-name").value = firstName; document.getElementById("update-last-name").value = lastName; document.getElementById("update-street-address").value = payload.Items[i].Shipping_Information.Shipping_Address; document.getElementById("update-country").value = payload.Items[i].Shipping_Information.Shipping_Country; document.getElementById("update-city").value = payload.Items[i].Shipping_Information.Shipping_City; document.getElementById("update-zip-code").value = payload.Items[i].Shipping_Information.Shipping_Zip_Code; document.getElementById("update-state").value = payload.Items[i].Shipping_Information.Shipping_State; document.getElementById("update-phone-number").value = payload.Items[i].Shipping_Information.Shipping_Phone_Number; document.getElementById("update-user-email").value = payload.Items[i].Shipping_Information.Shipping_Email; var products = ""; for(var j = 0; j < payload.Items[i].Product_Design.length; j++) { products += payload.Items[i].Product_Design[j].Product_Serial_Number; if(j != payload.Items[i].Product_Design.length -1) { products += ","; } } document.getElementById("update-cart").value = products; } } } function updateSalesOrder() { var fullName = document.getElementById("update-first-name").value + " " + document.getElementById("update-last-name").value; var shippingInfo = { "Shipping_Address": document.getElementById("update-street-address").value, "Shipping_City": document.getElementById("update-city").value, "Shipping_Country": document.getElementById("update-country").value, "Shipping_Email": document.getElementById("update-user-email").value, "Shipping_Name": fullName, "Shipping_Phone_Number": document.getElementById("update-phone-number").value, "Shipping_State": document.getElementById("update-state").value, "Shipping_Zip_Code": document.getElementById("update-zip-code").value } var cart = [] var products = (document.getElementById("update-cart").value).split(","); for(var i = 0; i < products.length; i++) { var product = { "Product_Serial_Number": products[i], "Quantity": 1 } cart.push(product); } var payload = { "TableName": "Sales_Order421", "Key": { "Sales_Order_Number": parseInt(document.getElementById("update-sales-id").value) }, "UpdateExpression": "set Product_Design = :a, Shipping_Information = :b", "ExpressionAttributeValues": { ":a": cart, ":b": shippingInfo } } // PUT method $.ajax({ url: "https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=Sales_Order421", type: "PUT", data: JSON.stringify(payload), dataType: "json", success: function() { alert("Your Order Successfully updated"); location.reload(); }, error: function() { alert("An error occured."); } }); } function deleteOrder() { var payload = { "TableName": "Sales_Order", "Key": { "Sales_Order_Number": parseInt(document.getElementById("delete-order").value) } } console.log(payload); // DELETE method $.ajax({ url: "https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=Sales_Order421", type: "DELETE", data: JSON.stringify(payload), dataType: "json", success: function() { alert("Your Order Successfully Deleted."); location.reload(); }, error: function() { alert("An error occured."); } }); } //get the payload function grab() { try { $.getJSON(API, JSONObject) .done(function (json) { sessionStorage.setItem("payload", JSON.stringify(json)); setup(); }); } catch (err) { console.log(err); } } window.onload = grab(); <file_sep>/final/meanPCParts/ERPHomePage Scott 2 2 2/js/crud.js //GetInventory method// $(document).ready(function() { $(document).ready(function() { $("#viewInventory").click(function() { $.get("https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=Inventory", function(data, status) { // alert("Data: " + data + "\nStatus: " + status); //$("#InventoryV1").text(JSON.stringify(data)); var $table = $('#Items'); $('#Items').bootstrapTable({ data: data.Items }); }); }); }); $("#submit").click(function () { // POSTInventory method var jsonDoc = { "TableName": "Inventory", "Item": { "color": document.getElementById("color").value, "description": document.getElementById("description").value, "itemname": document.getElementById("itemname").value, "itemId": document.getElementById("itemId").value, "locationId": document.getElementById("locationId").value, "price": document.getElementById("price").value, "quantity": document.getElementById("quantity").value, "safetyStock": document.getElementById("safetyStock").value, "size": document.getElementById("size").value, "height": document.getElementById("height").value, "length": document.getElementById("lengthId").value, "width": document.getElementById("width").value, "stockOnHand": document.getElementById("stockOnHand").value } }; $.ajax({ url: "https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=Inventory", type: "POST", data: /* $("#form").serialize() */JSON.stringify(jsonDoc), dataType: "json", sucess: function (jsonDoc) { console.info(jsonDoc); } }); alert("Successfully Submited!") }); $("#updateInventory").click(function () { // updateInventory method var jsonDoc = { "TableName": "Inventory", "Key": { "itemId": document.getElementById("itemId").value }, "UpdateExpression": "set color = :a, description =:b, itemname =:c, locationId =:e, price =:f, quantity =:g, safetyStock =:h, size =:i, height =:j, lengthId =:k, width =:m, stockOnHand =:n", "ExpressionAttributeValues": { ":a": document.getElementById("color").value, ":b": document.getElementById("description").value, ":c": document.getElementById("itemname").value, ":e": document.getElementById("locationId").value, ":f": document.getElementById("price").value, ":g": document.getElementById("quantity").value, ":h": document.getElementById("safetyStock").value, ":i": document.getElementById("size").value, ":j": document.getElementById("height").value, ":k": document.getElementById("lengthId").value, ":m": document.getElementById("width").value, ":n": document.getElementById("stockOnHand").value }, "ReturnValues": "UPDATED_NEW" }; $.ajax({ url: "https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=Inventory", type: "PUT", data: JSON.stringify(jsonDoc), dataType: "json", sucess: function (jsonDoc) { console.info(jsonDoc); } }); alert("Updated PO Info!") }); $("#deleteInventory").click(function () { // deleteInventory method var jsonDoc = { "TableName": "Inventory", "Key": { "itemId": document.getElementById("itemId").value } }; $.ajax({ url: "https://qrb010ff1b.execute-api.us-east-1.amazonaws.com/test/CRUD?TableName=Inventory", type: "delete", data: JSON.stringify(jsonDoc), dataType: "json", sucess: function (jsonDoc) { console.info(jsonDoc); } }); alert("Deleting record!") }); });
9be00db6138aa4d27a02731d8eae5eab0f5fe3d2
[ "JavaScript" ]
7
JavaScript
sbuoy/mean421
8b019e5d5b7c84715fcdf7c972137c2f3a4913ec
d49c3c00dc2f666af9b884f3807633d19ba0fc02
refs/heads/master
<repo_name>akulgupta94/analytics<file_sep>/file3.R x1 = 3 x2 <- 3 #diff ways of assigning value x1 x2 ls() #variables in the env women ?AirPassengers data() #pre available data sets for use AirPassengers library() #packages loaded ?mean #help x <- c(0:10, 50) x ?c length(x) xm <- mean(x) c(xm, mean(x, trim = 0.10)) ??mean #search mean from other sources where people could have created mean with different functionalities 1:10000000 getwd() #working directory plot(1:10) #basic command to plot <file_sep>/file4-ds.R #vectors ----- 4-dashes create a bookmark which can be seen on the right side of this screen x=1:10 #create sequence of nos 1 to 10 x (x1 <- 1:20) #assigns and prints in the same command (x1=1:30) (x2=c(1,2,13,4,5)) x3=c('a','ABC') x3 class (x3) (X3=letters[1:10]) class(x3) LETTERS[1:26] (x3b=c('a',"Henry",4)) class(x3b) (x4=c(T,FALSE,TRUE,T,F)) class(x4) class(c(3,5)) #SAVES AS float class(c(3L,5L)) #saves as integer x5a=c(3,5) class(x5a) (x5b=c(1,'a',T,4L)) class(x5b) #access elements (x6=seq(0,100,by=2)) seq(0,100,3) #takes value as 0=start 100=end 3=by seq(100,0,3) #error as values in incorrect sequence seq(to=100,from=0,3) #correct way if incorrect sequence seq() seq(1) methods(class='numeric') ?seq ls() x6 length(x6) x6[20] #access 20th eement x6[3] #access 3rd value x6[c(2,4)] #access 2nd and 3rd value x6[10:20] #access all values from 10th to 20th x6[-1] #access all but 1st element x6[-c(1:10, 15:20)] #ALL these are temporary removals not removed fromactual variable x6[c(2.4,3.54)] #real nos are truncated to integers x6[x6>30 & x6<40] x6[-(length(x6)-1)] #remove the 2nd last symbol #modify x6 (x6=sample(1:50))#pick randomly arranged from 1-50 sort(x6) sort(x6[-c(1,2)]) sum(x6[x6>30 & x6<40]) x6[2] <- 99; x6[2:10] <- 99; x6 x6[x6>30 & x6<40] = 999 x6 x6[2:10] <- 99; x6 (x=seq(1,5,length.out=15)) #tells values of points when 15 equal divisions are done x=NULL x (x=rnorm(1000000)) #central tendency theorm, more the no the values more perfect the normal curve ?rnorm plot(density(x)) abline(v=c(-3,0,3)) mean(x) (x1=rnorm(1000000,mean=50,sd=5)) plot(density(x1)) abline(v=mean(x1),h=0.04) hist(x1) hist(x1,freq=2) hist(x1,freq=5) plot(density(x1)) hist(x1,freq=F) lines(density(x1),col=2) #freq done to F to map lines on hist #matrix ----- 100:111 length(100:111) (m1=matrix(100:111, nrow=4)) #automatically makes 3 colums as 12 elements (m2=matrix(100:111, ncol=3, byrow=T)) #row wise m1[1,];m1[,1] m1[1,2:3] #1st row 2-3 columns shown m1[c(1,3),1] m1[,-c(1,3)] m1[m1>105 & m1<108] #name of cols and rows m1 paste("C","D",sep="-") paste("c",1:100,sep="-") (colnames(m1)= paste('C',1:3,sep="-")) (rownames(m1)= paste('R',1:3,sep="-")) #missing part ask someone m2 cbind(m2,m2) #combining matrices COLUMN BIND when rown number same rbind(m2,m2) colSums(m1); rowSums(m1) colMeans(m1); rowMeans(m1) t(m1) #transpose m1 sweep(m1,MARGIN=1,STATS=c(2,3,4,5), FUN="+") #rowwise sweep(m1,MARGIN=2,STATS=c(2,3,4), FUN="*") ?addmargins addmargins(m1,1,mean) #colwise function addmargins(m1,margin=1,sum) #col addmargins(m1,2,sum) #row addmargins(m1,c(1,2),mean) #dataframe ---- #create vectors to be combined into DF (rollno=1:30) (sname=paste('student',1:30,sep='')) #setseed(1234) see this command too (gender=sample(c('M','F'),size=30,replace=T,prob=c(.7,.3))) #table(gender) #prop.table(table(gender)) (marks1=floor(rnorm(30,mean=50,sd=10))) #floor ceiling round truncate (marks2=ceiling(rnorm(30,40,5))) (course=sample(c('BBA','MBA'),size=30, replace=T,prob=c(.5,.5))) rollno;sname;gender marks1;marks2;course #create DF df1=data.frame(rollno,sname,gender,marks1,marks2,course, stringsAsFactors=F) #factors become categories in R but we dont want name to be a catagory, gender is fine. so we put F str(df1) #structure of DF head(df1) #top 6 rows tail(df1) #bot 6 rows class(df1) #DF summary(df1) #summary df1 df1$gender=factor(df1$gender) df1$course=factor(df1$course) str(df1) summary(df1) df1 #full data df1$gender #one column head(df1[,c(2,4)]) #multiple columns df1[1:10,] #select rows, all columns df1[1:5,1:4] #as per condition df1[marks1>50 & gender=="F", c('rollno','sname')] df1[marks1>50 & gender=="F",] df1[marks1>50 & gender=="F",c(1,2)] aggregate(df1$marks1, by=list(df1$gender), FUN=max) aggregate(df1$marks1, by=list(df1$gender, df1$course), FUN=sum) aggregate (marks1 ~ gender,data=df1,FUN=max) aggregate(cbind(marks1,marks2)) - gender,data=df1, FUN=max) (df2=aggregate()) #factors ----
50db73db362147ac9e4576782702b9cba0b8182f
[ "R" ]
2
R
akulgupta94/analytics
7faee4f3a7096683d284b1268188fda6fd177728
c629369eafdf9613029be7ff80d90a7e49358d4f
refs/heads/master
<repo_name>1787102205/git-test1<file_sep>/src/main/java/GitTest.java public class GitTest { public static void main(String[] args) { System.out.println("好耶!"); System.out.println("好耶!好耶!"); System.out.println("好耶!在hot-fix分支里的第一次提交"); System.out.println("push test"); System.out.println("pull test"); } }
2d4402c0c70d1a4a921f9b83c6cd776ec41d614d
[ "Java" ]
1
Java
1787102205/git-test1
def26133e21a6f45ede52de363cb9dcccd8a9b4a
9d53380deec02b8ef779146c23bd2791f02f0c13
refs/heads/master
<file_sep>package com.hva.madlevel5task2.database import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import androidx.sqlite.db.SupportSQLiteDatabase import com.hva.madlevel5task2.dao.GameDao import com.hva.madlevel5task2.helper.Converters import com.hva.madlevel5task2.model.Game import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.util.* @Database(entities = [Game:: class], version = 4, exportSchema = false) @TypeConverters(Converters::class) abstract class GameRoomDatabase : RoomDatabase() { abstract fun gameDao(): GameDao companion object { private const val DATABASE_NAME = "GAME_DATABASE" @Volatile private var gameRoomDatabaseInstance: GameRoomDatabase? = null fun getDatabase(context: Context): GameRoomDatabase? { if (gameRoomDatabaseInstance == null) { synchronized(GameRoomDatabase::class.java) { if (gameRoomDatabaseInstance == null) { gameRoomDatabaseInstance = Room.databaseBuilder( context.applicationContext, GameRoomDatabase::class.java, DATABASE_NAME) .fallbackToDestructiveMigration() .addCallback(object : RoomDatabase.Callback() { override fun onCreate(db: SupportSQLiteDatabase) { super.onCreate(db) gameRoomDatabaseInstance?.let { database -> CoroutineScope(Dispatchers.IO).launch { database.gameDao().insertGame(Game("Title","", Date())) } } } }) .build() } } } return gameRoomDatabaseInstance } } }<file_sep>package com.hva.madlevel5task2.model import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.TypeConverters import java.util.* @Entity(tableName = "gameTable") data class Game ( val title: String? = null, val platform: String? = null, @TypeConverters var releaseDate: Date? = null, @PrimaryKey(autoGenerate = true) val id: Long? = null ) { }<file_sep>package com.hva.madlevel5task2.ui import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.hva.madlevel5task2.R import com.hva.madlevel5task2.model.Game import kotlinx.android.synthetic.main.item_game.view.* import java.text.SimpleDateFormat class GameListAdapter(private var games: List<Game>) : RecyclerView.Adapter<GameListAdapter.ViewHolder>(){ inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun databind(game: Game) { itemView.tvTitleGame.text = game.title.toString() val format = SimpleDateFormat("dd-MM-yyyy") val dateString = format.format(game.releaseDate!!) itemView.tvConsoleReleaseDate.text = game.platform.toString() + " Release: " + dateString } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(parent.context).inflate( R.layout.item_game, parent, false )) } override fun getItemCount(): Int { return games.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.databind(games[position]) } }<file_sep>package com.hva.madlevel5task2.ui import android.graphics.Color import android.graphics.drawable.Icon import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentPagerAdapter import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.floatingactionbutton.FloatingActionButton import com.hva.madlevel5task2.R import com.hva.madlevel5task2.model.Game import com.hva.madlevel5task2.model.GameViewModel import kotlinx.android.synthetic.main.fragment_backlog_game.* /** * A simple [Fragment] subclass as the default destination in the navigation. */ class GameBacklogFragment : Fragment() { private var games: ArrayList<Game> = arrayListOf() private lateinit var gameAdapter: GameListAdapter private lateinit var viewManager: RecyclerView.LayoutManager private val viewModel: GameViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { activity?.title = getString(R.string.game_backlog_title) setHasOptionsMenu(true) // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_backlog_game, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) (activity as MainActivity).changeNavBar((activity as MainActivity).supportActionBar!!, false) val fabBtnGameBacklog = view.findViewById(R.id.fabGameBacklog) as FloatingActionButton fabBtnGameBacklog.setColorFilter(Color.WHITE) fabGameBacklog.setOnClickListener{ findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment) } initRv() observeAddGameResults() } // override on options of main activity and when trash can is clicked will delete the list override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId) { R.id.deleteAll ->{ viewModel.deleteAllGames() } } return super.onOptionsItemSelected(item) } private fun initRv() { gameAdapter = GameListAdapter(games) viewManager = LinearLayoutManager(activity) createItemTouchHelper().attachToRecyclerView(rvGameList) rvGameList.apply { setHasFixedSize(true) layoutManager = viewManager adapter = gameAdapter } } private fun observeAddGameResults() { viewModel.games.observe(viewLifecycleOwner, Observer { gameList -> this@GameBacklogFragment.games.clear() this@GameBacklogFragment.games.addAll(gameList as Collection<Game>) games.sortWith(compareBy<Game> {it.releaseDate}) gameAdapter.notifyDataSetChanged() }) } private fun createItemTouchHelper(): ItemTouchHelper { // Callback which is used to create the ItemTouch helper. Only enables left swipe. // Use ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) to also enable right swipe. val callback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) { // Enables or Disables the ability to move items up and down. override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } // Callback triggered when a user swiped an item. override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val position = viewHolder.adapterPosition val gameToDelete = games[position] viewModel.deleteGame(gameToDelete) } } return ItemTouchHelper(callback) } }<file_sep>package com.hva.madlevel5task2.ui import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.ActionBar import androidx.appcompat.app.AppCompatActivity import androidx.navigation.NavController import androidx.navigation.findNavController import com.hva.madlevel5task2.R class MainActivity : AppCompatActivity() { private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(findViewById(R.id.toolbar)) if(supportActionBar != null) { supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) } navController = findNavController(R.id.nav_host_fragment) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent // activity in AndroidManifest.xml. return when (item.itemId) { android.R.id.home ->{ navController.navigate(R.id.action_SecondFragment_to_FirstFragment) true } else -> super.onOptionsItemSelected(item) } } fun changeNavBar(toolbar: ActionBar, value: Boolean) { toolbar.setDisplayShowHomeEnabled(value) toolbar.setDisplayHomeAsUpEnabled(value) } }<file_sep>package com.hva.madlevel5task2.ui import android.annotation.SuppressLint import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.google.android.material.floatingactionbutton.FloatingActionButton import com.hva.madlevel5task2.R import com.hva.madlevel5task2.model.Game import com.hva.madlevel5task2.model.GameViewModel import kotlinx.android.synthetic.main.fragment_game_add.* import java.lang.Exception import java.text.ParseException import java.text.SimpleDateFormat import java.util.* /** * A simple [Fragment] subclass as the second destination in the navigation. */ class AddGameFragment : Fragment() { private val viewModel: GameViewModel by viewModels() private val simpleFormat = SimpleDateFormat("dd-MM-yyyy") @SuppressLint("ResourceType") override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { activity?.title = getString(R.string.add_game_title) setHasOptionsMenu(true) // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_game_add, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val fabBtnGameAdd = view.findViewById(R.id.fabGameAdd) as FloatingActionButton fabBtnGameAdd.setColorFilter(Color.WHITE) fabGameAdd.setOnClickListener{ onAddGame() } (activity as MainActivity).changeNavBar((activity as MainActivity).supportActionBar!!, true) } override fun onPrepareOptionsMenu(menu: Menu) { val item = menu.findItem(R.id.deleteAll) if (item != null) { item.isVisible = false } } private fun onAddGame() { var errorMessage = false val gameTitle = etTitleGame.text.toString() val gamePlatform = etPlatform.text.toString() val gameReleaseDate = etReleaseDate.text.toString() val date = parseStringToDate(gameReleaseDate) // if the field is not empty insert the data if(gameTitle.isNotBlank() && gamePlatform.isNotBlank() && gameReleaseDate.isNotBlank()) { viewModel.insertGame(Game(gameTitle, gamePlatform, date)) findNavController().popBackStack() } // some error handling if(gameTitle.isEmpty()) { errorMessage = true Toast.makeText(activity, R.string.empty_title, Toast.LENGTH_SHORT).show() } if(gamePlatform.isEmpty()) { errorMessage = true Toast.makeText(activity, R.string.empty_platform, Toast.LENGTH_SHORT).show() } if (gameReleaseDate.isEmpty()) { errorMessage = true Toast.makeText(activity, R.string.empty_release_date, Toast.LENGTH_SHORT).show() } if(errorMessage) { Toast.makeText(activity, R.string.not_valid_input, Toast.LENGTH_SHORT).show() } } private fun parseStringToDate(date: String?): Date { var result: Date? = null try { simpleFormat.isLenient = false result = simpleFormat.parse(date) } catch (e: ParseException) { e.printStackTrace() } return result!! } }
81a82bc1e95b94cc62c38b80082de88b4fcc8acb
[ "Kotlin" ]
6
Kotlin
jkschermer/MadLevel5Task2
f9e374f3911a76d2c1727fc52b9e7f8db7471e33
3758101db73fc33ea1769ef308b8def906c27761
refs/heads/master
<repo_name>stas-prokopiev/code_searcher<file_sep>/src/code_searcher/__init__.py # -*- coding: utf-8 -*- """ code_searcher ======================== code_searcher is a simple Python module with main purpose to help support changes in any function signature inside any project or library. """ import logging from code_searcher.code_searcher_class import CodeSearcher __all__ = ["CodeSearcher",] ##### # Prepare basic logger in case user is not setting it itself. ##### #STR_LOG_STDOUT_FORMAT = '[%(levelname)s]: %(message)s' # DEBUG=10 INFO=20 WARNING=30 ERROR=40 CRITICAL=50 #logging.basicConfig(format=STR_LOG_STDOUT_FORMAT, level=20) LOGGER = logging.getLogger("code_searcher") LOGGER.addHandler(logging.NullHandler()) <file_sep>/AUTHORS.rst ============ Contributors ============ * <NAME> <<EMAIL>> Contacts ======== * email: <EMAIL> * `vk.com <https://vk.com/stas.prokopyev>`_ * `Facebook <https://www.facebook.com/profile.php?id=100009380530321>`_ <file_sep>/docs/index.rst .. code_searcher documentation master file, created by sphinx-quickstart on Tue May 5 03:39:45 2020. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to code_searcher's documentation! ========================================= .. toctree:: :maxdepth: 1 README <README> Contents ======== .. toctree:: :maxdepth: 3 License <license> Authors <authors> Changelog <changelog> Module Reference <api/modules> Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`<file_sep>/src/code_searcher/additional_functions.py # -*- coding: utf-8 -*- """Additional functions""" # Standard library imports import logging # Third party imports # Local imports LOGGER = logging.getLogger("code_searcher") def func_simple_search_of_code(str_code_to_search, str_where_to_search): """Getting names of all modules imported in the python code Parameters ---------- str_py_code : str code where to search for imported modules Returns ------- bool If string is inside another string """ return str_code_to_search in str_where_to_search # if str_code_to_search not in str_where_to_search: # return False # ##### # # If code found check that it's not in quotes # str_in_quotes_1 = "'{}'".format(str_code_to_search) # str_in_quotes_2 = '"{}"'.format(str_code_to_search) # bool_is_code_in_quotes = ( # (str_in_quotes_1 in str_where_to_search) or # (str_in_quotes_2 in str_where_to_search) # ) # if bool_is_code_in_quotes: # return False # return True <file_sep>/tox.ini [tox] envlist = py38 py37 py27 skipsdist = true [testenv] deps = pytest pytest-cov -r{toxinidir}/requirements.txt commands = pip install -e . python -m pytest <file_sep>/src/code_searcher/code_searcher_class.py # -*- coding: utf-8 -*- """ This module is consists of main class for code searching through your code library. """ # Standard library imports import time import os import re from collections import defaultdict from collections import OrderedDict import logging # Third party imports # Local imports from code_searcher import working_with_files from code_searcher import additional_functions LOGGER = logging.getLogger("code_searcher") class CodeSearcher(object): """ A class used to do search operations on whole code of project ... Attributes ---------- self.list_str_dirs_where_to_look : list list most parent folders where to look for code files self.list_str_file_extensions : list list strings file extensions which files to explore self.dict_time_file_changed_by_path : dict {"path_to_file_1": float_time_when_last_modified, ...} self.dict_list_file_paths_by_ext_by_dir : dict dict with pathes of all initialized files {"folder_path_1": {"file_extension_1": [file_path_1, ...], ...}, ...} self.dict_str_file_content_by_file_path : dict {"file_path_1": file_1_content, "file_path_2": file_2_content, ...} self.dict_parent_dir_by_file_path : dict {"path_to_file_1": "path_to_parent_dir_given_by_user", ...} self.time_when_last_time_downloaded_files : float time.time() when last time downloaded files (need for not redownloading too often at least after 1 seconds) Methods ------- get_file_stats_of_the_code_library(...) Getting string with statistics about files in the library get_dict_list_file_paths_by_ext_by_dir(...) Getting dict with pathes to asked files by ext by dir download_all_files(...) For all files defined in self.dict_list_file_paths_by_ext_by_dir download up to date versions of files (Efficient realization) update_files(...) Re-search for all files in the folders and download them search(...) Searching some code inside whole library and print all occurrences in nice formatted way search_with_re(...) Searching some code inside library using regular expressions """ def __init__( self, list_str_dirs_where_to_look, list_str_file_extensions=[".py", "ipynb"], ): """Init object Parameters ---------- list_str_dirs_where_to_look : list list most parent folders where to look for code files list_str_file_extensions : list, optional list strings file extensions which files to explore (default is [".py", "ipynb"]) """ # 0) Check that as least some arguments are given assert list_str_dirs_where_to_look, ( "ERROR: for initializing code_searcher obj should be given \n" "list of folders where to search files with code \n" "var list_str_dirs_where_to_look: SHOULD NOT BE EMPTY" ) # 1) Initialize class variables # Take absolute path of list folders where to look for code files self.list_str_dirs_where_to_look = [ os.path.abspath(str_dir).lower() for str_dir in list_str_dirs_where_to_look ] # list strings file extensions which files to explore self.list_str_file_extensions = list_str_file_extensions # {"path_to_file_1": float_time_when_last_modified, ...} self.dict_time_file_changed_by_path = defaultdict(float) self.dict_str_file_content_by_file_path = {} self.dict_parent_dir_by_file_path = {} print("Downloading all files (it can be a long process, please wait.)") float_time_start = time.time() # {"folder_path_1": {"file_extension_1": [file_path_1, ...], ...}, ...} self.dict_list_file_paths_by_ext_by_dir = ( self.get_dict_list_file_paths_by_ext_by_dir() ) self.time_when_last_time_downloaded_files = 0.0 int_files_downloaded = self.download_all_files() print( "{} Files were downloaded in {} seconds".format( int_files_downloaded, round(time.time() - float_time_start, 2) ) ) def __repr__(self): """Representation of obj Returns ------- str representation of the obj """ self.download_all_files() str_obj_repr = "" str_obj_repr += "Folders to search in: \n" for str_dir in self.list_str_dirs_where_to_look: str_obj_repr += "--> " + str_dir + "\n" str_obj_repr += "\nExtensions to check: \n" for str_ext in self.list_str_file_extensions: str_obj_repr += "--> " + str_ext + "\n" str_obj_repr += self.get_file_stats_of_the_code_library() return str_obj_repr def get_file_stats_of_the_code_library(self): """Getting string with statistics about files in the library Parameters ---------- Returns ------- str File statistic of current obj """ self.download_all_files() str_stats = "\n" str_stats += "=" * 79 + "\n" str_stats += "Files Statistic of current code library:\n" str_stats += "=" * 79 + "\n" # Print file statistic for every folder for str_dir in self.dict_list_file_paths_by_ext_by_dir: str_stats_dir = "" str_stats_dir += "--> For folder: " + str(str_dir) + "\n" int_files_in_folder = 0 int_lines_in_folder = 0 str_stats_dir += "--> Files_found = {int_files_in_dir} " str_stats_dir += "Code_lines = {int_lines_in_dir}\n" dict_list_file_paths_by_ext = \ self.dict_list_file_paths_by_ext_by_dir[str_dir] # Count number of files with every extension for str_ext in dict_list_file_paths_by_ext: list_file_paths = dict_list_file_paths_by_ext[str_ext] int_code_lines = 0 for str_file_path in list_file_paths: str_full_file = \ self.dict_str_file_content_by_file_path[str_file_path] int_code_lines += str_full_file.count("\n") int_files = len(list_file_paths) ##### int_files_in_folder += int_files int_lines_in_folder += int_code_lines ##### # Add number of files with every extension to stats str_stats_dir += ( "----> {extension}: " "Files_found = {int_files}; " "Code_lines = {int_lines}; " "\n" ).format( extension=str_ext, int_files=int_files, int_lines=int_code_lines, ) str_stats += str_stats_dir.format( int_files_in_dir=int_files_in_folder, int_lines_in_dir=int_lines_in_folder, ) ##### str_stats += "=" * 79 + "\n" return str_stats def get_dict_list_file_paths_by_ext_by_dir(self): """Getting dict with pathes to asked files by ext by dir Returns ------- dict {"folder_path_1": {"file_extension_1": [file_path_1, ..], ..}, ..} """ dict_list_file_paths_by_ext_by_dir = OrderedDict() for str_dir_path in self.list_str_dirs_where_to_look: dict_list_file_paths_by_ext_by_dir[str_dir_path] = \ working_with_files.get_dict_list_file_paths_by_ext( str_dir_path, list_str_extensions=self.list_str_file_extensions, ) return dict_list_file_paths_by_ext_by_dir def download_one_file(self, str_file_path, str_parent_dir): """Download all content of 1 file Args: str_file_path (str): Path to file which to download str_parent_dir (str): From which parent dir this file is Returns: bool: Flag if file was updated """ # Check if file was deleted if not os.path.exists(str_file_path): self.dict_str_file_content_by_file_path[str_file_path] = "" return False ##### # Check if file was modified and if so redownload it float_time_file_changed = \ os.path.getmtime(str_file_path) + os.path.getsize(str_file_path) float_time_file_mod_before = \ self.dict_time_file_changed_by_path[str_file_path] if float_time_file_mod_before != float_time_file_changed: self.dict_str_file_content_by_file_path[str_file_path] = \ working_with_files.get_file_as_string(str_file_path) self.dict_parent_dir_by_file_path[str_file_path] = str_parent_dir self.dict_time_file_changed_by_path[str_file_path] = \ float_time_file_changed return True return False def download_all_files(self): """ For all files defined in self.dict_list_file_paths_by_ext_by_dir download up to date versions of files (Efficient realization) Returns ------- int Number of files for which were loaded new versions of files """ # Check if enough time gone (1 seconds) after last download of files if time.time() - self.time_when_last_time_downloaded_files < 1.0: LOGGER.debug( "Less than 1 second gone since last download so continue" ) return 0 self.time_when_last_time_downloaded_files = time.time() int_files_loaded = 0 ##### # For every folder where to look download code files # Only if they were updated LOGGER.debug("START: download_all_files") for str_dir_path in self.dict_list_file_paths_by_ext_by_dir: LOGGER.debug( "---> Try to download files from: %s", str_dir_path ) dict_list_file_paths_by_ext = \ self.dict_list_file_paths_by_ext_by_dir[str_dir_path] ##### for str_ext in dict_list_file_paths_by_ext: LOGGER.debug( "------> Try to download files for ext: %s", str_ext ) list_str_file_paths = dict_list_file_paths_by_ext[str_ext] LOGGER.debug( "---------> Files found: %d", len(list_str_file_paths) ) for str_file_path in list_str_file_paths: int_files_loaded += \ self.download_one_file(str_file_path, str_dir_path) ##### LOGGER.debug("Files were really downloaded: %d", int_files_loaded) return int_files_loaded def update_files(self): """Re-search for all files in the folders and download them Parameters ---------- Returns ------- """ print("Updating all files (it can be a long process, please wait.)") self.dict_list_file_paths_by_ext_by_dir = ( self.get_dict_list_file_paths_by_ext_by_dir() ) self.download_all_files() def search( self, str_code_to_search, bool_is_to_search_case_sensitive=True, ): """Searching some code inside whole library and print all occurrences in nice formatted way Parameters ---------- str_code_to_search : str Code to search in the library bool_is_to_search_case_sensitive : bool, optional A flag if to search cas sensitive (default is True) Returns ------- int times occurrences of code found in whole library """ self.download_all_files() return self.search_processes_common( additional_functions.func_simple_search_of_code, str_code_to_search, bool_is_to_search_case_sensitive=bool_is_to_search_case_sensitive, ) def search_with_re(self, str_re_template,): """Searching some code inside library using regular expressions Parameters ---------- str_code_to_search : str Code to search in the library Returns ------- int times occurrences of code found in whole library """ self.download_all_files() def func_search_of_code_with_re(str_re_pattern, str_where_to_search): return bool(re.findall(str_re_pattern, str_where_to_search)) return self.search_processes_common( func_search_of_code_with_re, str_re_template, bool_is_to_search_case_sensitive=True, ) def search_processes_common_for_one_file( self, str_file_path, func_check_if_string_is_in_the_line, str_code_to_search, bool_is_to_search_case_sensitive, ): """Searching some code inside one file Searching some code inside one file and print all occurrences in nice formatted way Parameters ---------- str_file_path : str Path to file where to search func_check_if_string_is_in_the_line : function Function which should check if string is inside another string str_code_to_search : str Code to search in the library bool_is_to_search_case_sensitive : bool, optional A flag if to search cas sensitive (default is True) Returns ------- int times occurrences of code found in whole library """ int_occurrences_found = 0 str_full_file = self.dict_str_file_content_by_file_path[str_file_path] if not bool_is_to_search_case_sensitive: str_full_file = str_full_file.lower() str_code_to_search = str_code_to_search.lower() ##### # Line by line searching for asked code bool_is_entry_found_for_cur_file = False for int_line_num, str_line in enumerate(str_full_file.splitlines()): if func_check_if_string_is_in_the_line( str_code_to_search, str_line, ): if not bool_is_entry_found_for_cur_file: bool_is_entry_found_for_cur_file = True str_par_dir = \ self.dict_parent_dir_by_file_path[str_file_path] str_rel_path = os.path.relpath(str_file_path, str_par_dir) print("----> Found in: ", str_rel_path) print( "------> {})".format(int_occurrences_found), "line:", int_line_num, " Code_line:", str_line.strip() ) int_occurrences_found += 1 return int_occurrences_found def search_processes_common( self, func_check_if_string_is_in_the_line, str_code_to_search, bool_is_to_search_case_sensitive=True, ): """Searching some code inside whole library Searching some code inside whole library and print all occurrences in nice formatted way Parameters ---------- func_check_if_string_is_in_the_line : function Function which should check if string is inside another string str_code_to_search : str Code to search in the library bool_is_to_search_case_sensitive : bool, optional A flag if to search cas sensitive (default is True) Returns ------- int times occurrences of code found in whole library """ # 1) If not necessary to search case sensitive, then lower everything int_occurrences_found = 0 # For every folder searching through all files inside folder for str_dir in self.dict_list_file_paths_by_ext_by_dir: dict_list_file_paths_by_ext = \ self.dict_list_file_paths_by_ext_by_dir[str_dir] print("=" * 79) print("For folder: {folder}".format(folder=str_dir)) for int_ext_num, str_ext in enumerate(dict_list_file_paths_by_ext): print("--> For extension: {}".format(str_ext)) int_found_for_ext = 0 # For every file search occurrences of asked code for str_file_path in dict_list_file_paths_by_ext[str_ext]: int_found_for_ext += \ self.search_processes_common_for_one_file( str_file_path, func_check_if_string_is_in_the_line, str_code_to_search, bool_is_to_search_case_sensitive, ) ##### if not int_found_for_ext: print("----> NOTHING FOUND.") # If extension is not last then add a new line to print if int_ext_num != len(dict_list_file_paths_by_ext) - 1: print("") int_occurrences_found += int_found_for_ext print("=" * 79) print("\nOverall occurrences found: ", int_occurrences_found) return int_occurrences_found <file_sep>/CONTRIBUTING.rst Contributing ============ - Fork it (<https://github.com/stas-prokopiev/code_searcher/fork>) - Create your feature branch (`git checkout -b feature/fooBar`) - Commit your changes (`git commit -am 'Add some fooBar'`) - Push to the branch (`git push origin feature/fooBar`) - Create a new Pull Request <file_sep>/CHANGELOG.rst ========= Changelog ========= Version 0.2.0 ================================= - No big changes, just thought that it's time to say that this library is v. 0.2 Version 0.1.18 (Bug fixes) ================================= - Fixed bugs from previous update. - Updated readme.rst - Added logging - more test Version 0.1.17 (Huge changes) ================================= - Deleted all methods not directly necessary for searching inside files - All these methods soon will be available in my another python package. Version 0.1.7-16 (Some changes) ================================= - Added searching with re patterns. - Added method to print places where line length exceeds certain limit. - Made functions to search 1) unused functions and 2) outer imported modules stable. - Small changes in format of functions output. Version 0.1.6 (Huge changes) ================================= - New way of dealing with files, now instead of dowloading all files again and again only changes from the initial download will be download (git style) - New much more pretty format of output for function: search_all_occurrences_of_the_code_in_the_library Version 0.1.1 - 0.1.5 (Bug fixes) =================================== - FIX: Updated docs - FIX: minor bags were fixed. Version 0.1.0 (Initial release.) ================================= - The first proper release - The main class for searching was added. - Checked on compatibility with both py2 and py3. - The basic docs were added. <file_sep>/src/code_searcher/working_with_files.py # -*- coding: utf-8 -*- """File with all methods connected to working with files""" # Standard library imports import os import codecs import json from collections import defaultdict import logging # Third party imports # Local imports LOGGER = logging.getLogger("code_searcher") def read_whole_file(str_path_to_file): """read the whole file with encoding Parameters ---------- str_path_to_file : str path to file which to read str_encoding : str encoding type to use Returns ------- str whole file as one string """ with codecs.open(str_path_to_file, "r", "utf-8", errors="ignore") as file: str_whole_file = file.read() return str_whole_file # .encode("utf-8") def read_ipynb_file(str_path_to_file): """read the ipynb file as string Parameters ---------- str_path_to_file : str path to file which to read Returns ------- str whole ipynb file as one string """ str_whole_file = read_whole_file(str_path_to_file) dict_ipynb_file = json.loads(str_whole_file) if "cells" not in dict_ipynb_file: return "" str_full_ipynb_file = "" for int_cell_num, dict_cell in enumerate(dict_ipynb_file["cells"]): str_cell_num = "In [{}] ".format(int_cell_num) str_cell_full_code = "" for str_one_line_of_code in dict_cell["source"]: if not str_one_line_of_code.strip(): continue str_cell_full_code += str_cell_num + str_one_line_of_code str_full_ipynb_file += str_cell_full_code + "\n" # print(str_full_ipynb_file) return str_full_ipynb_file def get_dict_list_file_paths_by_ext( str_folder_where_to_look, list_str_extensions=[".py"], ): """Getting pathes to all files with asked extension in the folder Parameters ---------- str_folder_where_to_look : str path to most parent folder where to look for files list_str_extensions : list Extensions for which to look for Returns ------- list pathes to all files with given extension inside the given folder """ LOGGER.debug("start get_dict_list_file_paths_by_ext:") dict_list_file_paths_by_ext = defaultdict(list) # Using os.walk getting all files with asked extension for str_parent_dir, _, list_filenames in os.walk(str_folder_where_to_look): LOGGER.debug( "---> Checking %d files in dir: %s", len(list_filenames), str_parent_dir ) if os.path.basename(str_parent_dir) == "__pycache__": LOGGER.debug("------> Cache folder found so continue") continue for str_ext in list_str_extensions: list_files_of_ext = [] # Add point before extension name in needed if not str_ext.startswith("."): str_ext = "." + str_ext ##### # If file is ipynb, then do no take files from folder checkpoints if str_ext == ".ipynb": str_par_folder_name = os.path.basename(str_parent_dir) if str_par_folder_name == ".ipynb_checkpoints": continue ##### for str_filename in list_filenames: if str_filename.endswith(str_ext): list_files_of_ext.append( os.path.join(str_parent_dir, str_filename) ) dict_list_file_paths_by_ext[str_ext] += list_files_of_ext LOGGER.debug( "------> Found files with ext %s: %d", str_ext, len(list_files_of_ext) ) return dict_list_file_paths_by_ext def get_file_as_string(str_file_path): """Get content of file as string for any type of file Parameters ---------- str_file_path : str path to file which to return as string Returns ------- str string content inside file """ str_file_ext = str(os.path.splitext(str_file_path)[1]) if str_file_ext == ".ipynb": return read_ipynb_file(str_file_path) return read_whole_file(str_file_path) <file_sep>/tests/test_code_searcher_class.py # -*- coding: utf-8 -*- # Standard library imports import os import logging # Third party imports # Local imports import code_searcher from code_searcher.code_searcher_class import CodeSearcher logging.basicConfig(level=logging.DEBUG) def test_CodeSearcher(): """""" str_code_searcher_file = os.path.abspath(code_searcher.__file__) str_folder_with_files = os.path.dirname(str_code_searcher_file) code_searcher_obj = CodeSearcher( [str_folder_with_files], list_str_file_extensions=[".py", ".ipynb"], ) ##### # Test main search functions search int_occurrences = \ code_searcher_obj.search("class CodeSearcher") assert int_occurrences == 1, "ERROR: 'search' is not working" int_occurrences = code_searcher_obj.search( "CLASS CodeSearcher", bool_is_to_search_case_sensitive=True, ) assert int_occurrences == 0, \ "ERROR: 'bool_is_to_search_case_sensitive' is not working" code_searcher_obj.search_with_re("^def ") ##### print(code_searcher_obj) code_searcher_obj.download_all_files() code_searcher_obj.update_files() code_searcher_obj.get_dict_list_file_paths_by_ext_by_dir() code_searcher_obj.get_file_stats_of_the_code_library() ##### return 0 <file_sep>/README.rst ============= CODE_SEARCHER ============= .. image:: https://img.shields.io/github/last-commit/stas-prokopiev/code_searcher :target: https://img.shields.io/github/last-commit/stas-prokopiev/code_searcher :alt: GitHub last commit .. image:: https://img.shields.io/github/license/stas-prokopiev/code_searcher :target: https://github.com/stas-prokopiev/code_searcher/blob/master/LICENSE.txt :alt: GitHub license<space><space> .. image:: https://readthedocs.org/projects/local-simple-database/badge/?version=latest :target: https://local-simple-database.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status .. image:: https://travis-ci.org/stas-prokopiev/code_searcher.svg?branch=master :target: https://travis-ci.org/stas-prokopiev/code_searcher .. image:: https://img.shields.io/pypi/v/code_searcher :target: https://img.shields.io/pypi/v/code_searcher :alt: PyPI .. image:: https://img.shields.io/pypi/pyversions/code_searcher :target: https://img.shields.io/pypi/pyversions/code_searcher :alt: PyPI - Python Version .. contents:: **Table of Contents** Short Overview. ========================= code_searcher is a simple Python package(**py>=2.7 or py>=3.4**) with the main purpose to make searching through your project codebase fast and simple. Currently, fully supported file types are **.py** and **.ipynb** nonetheless, search functional can be applied to any file extensions which can be read as plain text in utf-8 encoding. In additional it allows you to get some useful info about your project codebase. For more info check section: **Typical examples of Usage** More info. ========================= The main reason of building this package was to create universal tool to help support changes in methods signatures in both .py and .ipynb files. It's becoming quite useful when your project outgrows 1k lines of code and manual replacement becomes too annoying (Too easy to overlook replacement somewhere). For more info check section: **Typical examples of Usage** Installation ============ * Install via pip: .. code-block:: bash pip install code_searcher Typical examples of Usage ========================= | In any case, the first thing you need to do is to import the necessary module and initialize class obj. | To do so you need to give pathes to folders in which all your files located (searcher will look deeper to full extent). If you have a code of all your projects structured that there is the main folder for all .py files and there is the main folder for all .ipynb files then use them. .. code-block:: python from code_searcher import CodeSearcher LIST_STR_FOLDERS_WHERE_TO_LOOK = ["path_to_dir_1", "path_to_dir_1", ...] code_searcher_obj = CodeSearcher( LIST_STR_FOLDERS_WHERE_TO_LOOK, list_str_file_extensions=[".py", "ipynb"], ) Please note that first initialization can be a long process if the folders where you search for files are deep and wide. But after finding all files they won't be downloaded again unless they were changed. So excellent performance is expected. 1) To find all occurrences of some code. -------------------------------------------------------------------------------------------------- *E.G. You've changed a function signature and want to do necessary changes in the library.* *To find all the places where this function was used use the code below* .. code-block:: python code_searcher_obj.search("line_to_look_for") *Output:* .. code-block:: console =============================================================================== For folder: c:\users\stanislav\desktop\my_python_projects\code_search_engine\project\code_searcher\src\code_searcher --> For extension: .py ----> Found in: CodeSearcher.py ------> 0) line: 93 Code_line: line_to_look_for( ------> 1) line: 444 Code_line: def line_to_look_for( --> For extension: ipynb ----> NOTHING FOUND. =============================================================================== Overall occurrences found: 2 2) To find all occurrences of some regular expression pattern -------------------------------------------------------------------------------------------------- .. code-block:: python code_searcher_obj.search_with_re("^from __future__ import[\s]+") *Output:* .. code-block:: console =============================================================================== For folder: c:\users\stanislav\desktop\my_python_projects\code_search_engine\project\code_searcher\src\code_searcher --> For extension: .py ----> Found in: additional_functions.py ------> 0) line: 12 Code_line: from __future__ import print_function ----> Found in: CodeSearcher.py ------> 1) line: 11 Code_line: from __future__ import print_function ----> Found in: decorators.py ------> 2) line: 12 Code_line: from __future__ import print_function ----> Found in: working_with_files.py ------> 3) line: 12 Code_line: from __future__ import print_function --> For extension: ipynb ----> NOTHING FOUND. =============================================================================== Overall occurrences found: 4 3) To see some statistics about your library. ------------------------------------------------------ .. code-block:: python print(code_searcher_obj) *Output:* .. code-block:: console Folders to search in: --> c:\users\stanislav\desktop\my_python_projects\code_searcher\src\code_searcher --> c:\users\stanislav\desktop\my_python_projects\code_searcher\jupyter_notebooks Extensions to check: --> .py --> .ipynb =============================================================================== Files Statistic of current code library: =============================================================================== --> For folder: c:\users\stanislav\desktop\my_python_projects\code_searcher\src\code_searcher --> Files_found = 4 Code_lines = 664 ----> .py: Files_found = 4; Code_lines = 664; ----> .ipynb: Files_found = 0; Code_lines = 0; =============================================================================== --> For folder: c:\users\stanislav\desktop\my_python_projects\code_searcher\jupyter_notebooks --> Files_found = 1 Code_lines = 22 ----> .py: Files_found = 0; Code_lines = 0; ----> .ipynb: Files_found = 1; Code_lines = 22; =============================================================================== 4) To add new files to examine. -------------------------------------------------------------------------------------------------- *If you've created a new file inside folder given to code_searcher then you should update files for code_searcher* .. code-block:: python code_searcher_obj.update_files() 5) To get dictionary with content of all satisfy files. -------------------------------------------------------------------------------------------------- *For now on this dictionary structure is* *{"dir_path_1": {"file_extension_1": {"absolute_file_path_1": str_file_content, ..}, ..}, ..}* .. code-block:: python code_searcher_obj.dict_str_file_by_path_by_ext_by_dir Links ===== * `Pypi <https://pypi.org/project/code-searcher/>`_ * `readthedocs <https://code-searcher.readthedocs.io/en/latest/>`_ * `GitHub <https://github.com/stas-prokopiev/code_searcher>`_ * `CHANGELOG <https://github.com/stas-prokopiev/code_searcher/blob/master/CHANGELOG.rst>`_. * `CONTRIBUTING <https://github.com/stas-prokopiev/code_searcher/blob/master/CONTRIBUTING.rst>`_. Contacts ======== * Email: <EMAIL> * `vk.com <https://vk.com/stas.prokopyev>`_ * `Facebook <https://www.facebook.com/profile.php?id=100009380530321>`_ License ======= This project is licensed under the MIT License.
9704e9123080368876cbddb3c19a69463ca8ca57
[ "Python", "reStructuredText", "INI" ]
11
Python
stas-prokopiev/code_searcher
8b80f9c625a93c69166c6d5dacb42bdf32ddf2dd
36dc912b8a5ddcaa20e1d30c5f5be1b2d7252ec5
refs/heads/master
<repo_name>gregorypeter/OpenLoopSunTracker<file_sep>/feedforward_initial/feedforward_initial.ino /* CPV Feed-forward tracking * * <NAME> * AOPL * Summer 2016 * * Feed-forward tracking for CPV test setup. Reads data from GPS unit, calculates position of the sun, and converts solar position to mm * displacement along X and Y of the Zaber linear stages. */ #include <zaberx.h> #include <TinyGPS++.h> #include <DebugMacros.h> #include <LSM303CTypes.h> #include <SparkFunIMU.h> #include <SparkFunLSM303C.h> #include <Sun_position_algorithms.h> #include <translate.h> #include <SoftwareSerial.h> // GPS uses software serial by default, with RX = pin 2 and TX = pin 3. Mega 2560 does not support software serial RX on pin 2, so add a jumper wire from pin 2 on GPS shield to RX pin used int RXPin = 2; int TXPin = 3; int rsRX = 4; int rsTX = 5; // Variables involved in finding the panel pitch from 3-axis accelerometer readings const byte interrupt1 = 2; // Uno can support external interrupts on pins 2 and 3 volatile boolean setPitch = false; // boolean for setting panel tilt by reading accelerometer data; off by default int averaging = 100; // Acceleration components from 3-axis accelerometer double accelX; double accelY; double accelZ; sunpos SunPos; polar coord; // zenith and azimuth in a struct polar coordP; vector cart; vector cartP; // Enter array tilt and heading double heading = 180 * (PI/180); double tilt = 0 * (PI/180); double radius; double zaberOld[2] = {0, 0}; // [x,y] for the stages (in mm) double zaber[2] = {0, 0}; const unsigned long offsetX = 3880000; //tracking the starting and current absolute positions of the stages const unsigned long offsetY = 1200000; unsigned long posX = 0; unsigned long posY = 0; // Define common command numbers int axisX = 1; int axisY = 2; String Home = "home"; String MoveAbs = "move abs"; String MoveRel = "move rel"; String Stop = "stop"; String SetMaxspeed = "set maxspeed"; String GetPos = "get pos"; String moveAbsX = "/1 move abs "; String moveAbsY = "/2 move abs "; String moveRelX = "/1 move rel "; String moveRelY = "/2 move rel "; String comm; //Period of feedback iterations const int interval = 5000; unsigned long previousMillis = 0; unsigned long currentMillis = 0; int GPSBaud = 4800; // Create a TinyGPS++ object called "gps" TinyGPSPlus gps; //Create an object for the 6DOF IMU LSM303C imu; // Create a software serial port called "gpsSerial" SoftwareSerial gpsSerial(RXPin, TXPin); // Create a software serial port to communicate with the Zaber stages SoftwareSerial rs232(rsRX, rsTX); void setup() { // Start the Arduino hardware serial port at 9600 baud Serial.begin(9600); // Enable external interrupt on pin specified by interrupt1 in order to find panel pitch pinMode(interrupt1, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(interrupt1), findPitch, FALLING); // Start the software serial port at the GPS's default baud gpsSerial.begin(GPSBaud); //Start software serial connection with Zaber stages rs232.begin(115200); delay(2000); rs232.println("/renumber"); delay(1000); rs232.println("/home"); delay(10000); zMove(axisX, offsetX); zMove(axisY, offsetY); } void loop() { currentMillis = millis(); if(currentMillis - previousMillis >= interval) { if(gpsSerial.available() > 0) { if(gps.encode(gpsSerial.read())) { SunPos.UT = gps.time.hour() + double(gps.time.minute())/60.0 + double(gps.time.second())/3600.0 + double(gps.time.centisecond())/360000; // UT in hours [decimal] SunPos.Day = gps.date.day(); // day [integer] SunPos.Month = gps.date.month(); // month [integer] SunPos.Year = gps.date.year(); // year [integer] SunPos.Dt = 96.4 + 0.567*double(gps.date.year()-2061); // Terrestial time - UT SunPos.Longitude = gps.location.lng() * (2*PI/360.0); // State College Longitude and Latitude [radians] SunPos.Latitude = gps.location.lat() * (2*PI/360.0); SunPos.Pressure = 1.0; // Pressure [atm] //SunPos.Temperature = imu.readTempC(); // Temperature [C], pulled from LSM303C 6DOF sensor SunPos.Temperature = 20.0; SunPos.Algorithm5(); coord.ze = SunPos.Zenith; coord.az = SunPos.Azimuth + PI; // Finding solar coordinates w.r.t. panel normal cart = sph2rect(coord); cartP.x = (cos(heading) * cart.x) - (sin(heading) * cos(tilt) * cart.y) - (sin(heading) * sin(tilt) * cart.z); cartP.y = (1)*(sin(heading) * cart.x) + (cos(heading) * cos(tilt) * cart.y) + (cos(heading) * sin(tilt) * cart.z); cartP.z = (cos(tilt) * cart.z) - (sin(tilt) * cart.y); coordP = rect2sph(cartP); if(coordP.az < 0) { coordP.az += (2*PI); } else if(coordP.az > (2*PI)) { coordP.az -= (2*PI); } // Determining zaber stage coordinates zaberOld[0] = zaber[0]; zaberOld[1] = zaber[1]; if((coordP.ze < 90) && (coordP.ze > 0)) { radius = interp1(sin(coordP.ze)); zaber[0] = (-1) * radius * sin(coordP.az); zaber[1] = (-1) * radius * cos(coordP.az); } zMove(axisX, mm(zaber[0])); zMove(axisY, mm(zaber[1])); } } } if(setPitch == true) { accelX = 0; accelY = 0; accelZ = 0; for(int i = 0; i < averaging; i++) { accelX += imu.readAccelX(); accelY += imu.readAccelY(); accelZ += imu.readAccelZ(); delay(10); } accelX /= averaging; accelY /= averaging; accelZ /= averaging; tilt = atan2(accelX, sqrt((accelY * accelY) + (accelZ * accelZ))); setPitch = false; } } void findPitch() { setPitch = true; } void zMove(int axis, long pos) { String command; if(axis == 1) { posX = offsetX + pos; command = moveAbsX + posX; } else if(axis == 2) { posY = pos; command = moveAbsY + posY; } rs232.println(command); } void zMoveRel(int axis, long dist) { String command; if(axis == 1) { posX += dist; command = moveRelX + posX; } else if(axis == 2) { posY += dist; command = moveRelY + posY; } rs232.println(command); } <file_sep>/README.txt * Open loop tracking for CPV test setup * * <NAME> * * Summer 2016 * Repository contains the sketches for open-loop tracking. Pulls date, time, latitude and longitude from the GPS unit and calculates the position of the sun. Solar coordinates then get transformed into coordinates in the plane of the microcell, in terms of mm of displacement from the test jig "origin". Copy folders from "libraries" into your "Arduino/libraries" folder and restart the IDE before using. * * Sketch Descriptions * * feedforward_binary: Open-loop tracking; Zaber Binary Protocol; f20 lens data feedforward_binary_2: Open-loop tracking; Zaber Binary Protocol; f80 lens data feedforward_binary_test: Indoor positioning test with optics; Zaber Binary Protocol; f20 lens data feedforward_binary_test_2: Indoor positioning test with optics; Zaber Binary Protocol; f80 lens data feedforward_initial: Open-loop tracking; Zaber ASCII Protocol; f20 lens data feedforward_test: Indoor positioning test with optics; Zaber ASCII Protocol; f20 lens data gps_reader_lcd: Outputs date, time, lat. and long. from gps to LCD screen pitch_heading_test: Uses 6DOF IMU to find panel tilt and heading pitch_heading_test_lcd; Uses 6DOF IMU to find panel tilt and heading; outputs to LCD screen solar2planar: Demonstrates coordinate transform from solar coords to planar coords; f20 lens data solar2planar2: Demonstrates coordinate transform from solar coords to planar coords; f80 lens data<file_sep>/feedforward_binary_test_2/feedforward_binary_test_2.ino /* CPV Feed-forward tracking * Test Sketch for indoor optics lab testing * Using f80 lens data * * <NAME> * AOPL * Summer 2016 * * Allows user to input solar azimuth and zenith in degrees and calculates the displacement in mm along X and Y from the origin of the lens system. * These mm displacement values get converted to number of microsteps and are sent as absolute move commands to the Zaber X-LRM200A linear stages. */ #include <zaberx.h> #include <translate.h> #include <DebugMacros.h> #include <LSM303CTypes.h> #include <SparkFunIMU.h> #include <SparkFunLSM303C.h> #include <SoftwareSerial.h> #ifndef PI #define PI 3.14159265358979 #endif int rsRX = 2; int rsTX = 3; double azimuth; double zenith; polar coord; // zenith and azimuth in a struct polar coordP; vector cart; vector cartP; //Enter array tilt and heading double heading = 0 * (PI/180); double tilt = 0 * (PI/180); // Variables involved in finding the panel pitch from 3-axis accelerometer readings const byte interrupt1 = 2; // Uno can support external interrupts on pins 2 and 3 volatile boolean setPitch = false; // boolean for setting panel tilt by reading accelerometer data; off by default int averaging = 100; // Acceleration components from 3-axis accelerometer double accelX; double accelY; double accelZ; // Variables for Zaber binary communication byte command[6]; byte reply[6]; float outData; long replyData; double radius; double zaber[2] = {0, 0}; const unsigned long offsetX = 2148185; //tracking the starting and current absolute positions of the stages const unsigned long offsetY = 2104209; unsigned long posX = 0; unsigned long posY = 0; int axisX = 1; int axisY = 2; // Define common command numbers int homer = 1; // home the stage int renumber = 2; // renumber all devices in the chain int moveAbs = 20; // move absolute int moveRel = 21; // move relative int stopMove = 23; // Stop int speedSet = 42; // Speed to target = 0.00219727(V) degrees/sec (assuming 64 microstep resolution) int getPos = 60; // Query the device for its position int storePos = 16; // Position can be stored in registers 0 to 15 int returnPos = 17; // returns the value (in microsteps) of the position stored in the indicated register int move2Pos = 18; // move to the position stored in the indicated register int reset = 0; // akin to toggling device power String comm; //Period of feedback iterations const int interval = 5000; unsigned long previousMillis = 0; unsigned long currentMillis = 0; //Create an object for the 6DOF IMU LSM303C imu; // Create a software serial port to communicate with the Zaber stages SoftwareSerial rs232(rsRX, rsTX); void setup() { // Start the Arduino hardware serial port at 9600 baud Serial.begin(9600); delay(100); Serial.println("CPV Feed-forward test sketch"); /* // Enable external interrupt on pin specified by interrupt1 in order to find panel pitch pinMode(interrupt1, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(interrupt1), findPitch, FALLING); */ // Sets the stages to use binary protocol rs232.begin(115200); delay(1000); rs232.println("/tools setcomm 9600 1"); delay(500); Serial.println(rs232.readStringUntil('\n')); delay(100); rs232.end(); delay(200); //Start software serial connection with Zaber stages rs232.begin(9600); delay(2000); Serial.println("Positioning stages..."); /* // Positioning stages to origin coinciding with lens axis of symmetry posX = sendCommand(axisX, moveAbs, offsetX); posY = sendCommand(axisY, moveAbs, offsetY); delay(4000); while((sendCommand(axisX, getPos, 0) != offsetX) && (sendCommand(axisY, getPos, 0) != offsetY)) { delay(1000); } */ Serial.println("Ready."); Serial.println("Enter azimuth and zenith angles, separated by a space:"); } void loop() { if(Serial.available() > 0) { // Read azimuth and zenith from serial terminal comm = Serial.readStringUntil(' '); azimuth = comm.toFloat(); comm = Serial.readStringUntil('\n'); zenith = comm.toFloat(); coord.az = azimuth * (PI/180); coord.ze = zenith * (PI/180); // Finding solar coordinates w.r.t. panel normal cart = sph2rect(coord); cartP.x = (cos(heading) * cart.x) - (sin(heading) * cos(tilt) * cart.y) - (sin(heading) * sin(tilt) * cart.z); cartP.y = (1)*(sin(heading) * cart.x) + (cos(heading) * cos(tilt) * cart.y) + (cos(heading) * sin(tilt) * cart.z); cartP.z = (cos(tilt) * cart.z) - (sin(tilt) * cart.y); coordP = rect2sph(cartP); if(coordP.az < 0) { coordP.az += (2*PI); } else if(coordP.az > (2*PI)) { coordP.az -= (2*PI); } // Determining zaber stage coordinates radius = interp2(sin(coordP.ze)); zaber[0] = (-1) * radius * sin(coordP.az); zaber[1] = (-1) * radius * cos(coordP.az); Serial.print("Azimuth: "); Serial.print(azimuth); Serial.print("\tZenith: "); Serial.print(zenith); Serial.print("\tAzimuth*: "); Serial.print(coordP.az * (180/PI)); Serial.print("\tZenith*: "); Serial.print(coordP.ze * (180/PI)); Serial.print("\tX: "); Serial.print(zaber[0]); Serial.print("\tY: "); Serial.println(zaber[1]); posX = sendCommand(axisX, moveAbs, mm(zaber[0]) + offsetX); posY = sendCommand(axisY, moveAbs, mm(zaber[1]) + offsetY); } if(setPitch == true) { accelX = 0; accelY = 0; accelZ = 0; for(int i = 0; i < averaging; i++) { accelX += imu.readAccelX(); accelY += imu.readAccelY(); accelZ += imu.readAccelZ(); delay(10); } accelX /= averaging; accelY /= averaging; accelZ /= averaging; tilt = atan2(accelX, sqrt((accelY * accelY) + (accelZ * accelZ))); setPitch = false; } } void findPitch() { setPitch = true; } long sendCommand(int device, int com, long data) { unsigned long data2; unsigned long temp; unsigned long repData; long replyNeg; float replyFloat; byte dumper[1]; // Building the six command bytes command[0] = byte(device); command[1] = byte(com); if(data < 0) { data2 = data + quad; } else { data2 = data; } temp = data2 / cubed; command[5] = byte(temp); data2 -= (cubed * temp); temp = data2 / squared; command[4] = byte(temp); data2 -= (squared * temp); temp = data2 / 256; command[3] = byte(temp); data2 -= (256 * data2); command[2] = byte(data2); // Clearing serial buffer while(rs232.available() > 0) { rs232.readBytes(dumper, 1); } // Sending command to stage(s) rs232.write(command, 6); delay(20); // Reading device reply if(rs232.available() > 0) { rs232.readBytes(reply, 6); } replyFloat = (cubed * float(reply[5])) + (squared * float(reply[4])) + (256 * float(reply[3])) + float(reply[2]); repData = long(replyFloat); if(reply[5] > 127) { replyNeg = repData - quad; } // Printing full reply bytes as well as reply data in decimal Serial.print(reply[0]); Serial.print(' '); Serial.print(reply[1]); Serial.print(' '); Serial.print(reply[2]); Serial.print(' '); Serial.print(reply[3]); Serial.print(' '); Serial.print(reply[4]); Serial.print(' '); Serial.println(reply[5]); Serial.print("\tData:"); if(reply[5] > 127) { Serial.println(replyNeg); return replyNeg; } else { Serial.println(repData); return repData; } } <file_sep>/gps_reader_lcd/gps_reader_lcd.ino /* GPS data reader for an EM 506 gps module * Output to Hitachi HD44780 LCD * * <NAME> * AOPL * Summer 2016 * * Reads date, time, lat and long from gps and outputs to LCD screen. */ #include <SoftwareSerial.h> #include <TinyGPS++.h> #include <Wire.h> #include "RTClib.h" #include <Adafruit_RGBLCDShield.h> #include <utility/Adafruit_MCP23017.h> int GPSBaud = 4800; int RXPin = 2; int TXPin = 3; // Create a TinyGPS++ object called "gps" TinyGPSPlus gps; // Create a software serial port called "gpsSerial" SoftwareSerial gpsSerial(RXPin, TXPin); Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield(); void setup() { // begin communication with LCD lcd.begin(16, 2); // (columns, rows) lcd.setBacklight(0x5); // Start the software serial port at the GPS's default baud gpsSerial.begin(GPSBaud); } void loop() { if (gpsSerial.available() > 0) { if (gps.encode(gpsSerial.read())) { lcd.clear(); lcd.setCursor(0, 0); lcd.print(gps.date.month()); lcd.print('/'); lcd.print(gps.date.day()); lcd.print('/'); lcd.print(gps.date.year()); lcd.print(' '); lcd.print(gps.time.hour()); lcd.print(':'); lcd.print(gps.time.minute()); lcd.setCursor(0, 1); lcd.print(gps.location.lat()); lcd.setCursor(8, 1); lcd.print(gps.location.lng()); } } delay(500); } <file_sep>/feedforward_test_alt/feedforward_test_alt.ino /* CPV Feed-forward tracking - Outdoor test sketch * Using Zaber Binary protocol * Using new lens data * * <NAME> * AOPL * Summer 2016 * * Feed-forward tracking for CPV test setup. Reads data from GPS unit, calculates position of the sun, and converts solar position to mm * displacement along X and Y of the Zaber linear stages. */ #include <zaberx.h> #include "RTClib.h" #include <Sun_position_algorithms.h> #include <translate.h> #include <SoftwareSerial.h> #include <Wire.h> //#include <Adafruit_RGBLCDShield.h> //#include <utility/Adafruit_MCP23017.h> ///////////////////////// OPEN-LOOP TRACKING VARIABLES ///////////////////////////////////////// // Enter array tilt and heading // double heading = 180 * (PI/180); double tilt = 0 * (PI/180); // NREL solar position calculation variables sunpos SunPos; polar coord; // zenith and azimuth in a struct polar coordP; vector cart; vector cartP; int offsetUTC = 4; // number of hours local time is behind UTC char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; // Period of feedback iterations const int interval = 5000; unsigned long previousMillis = 0; unsigned long currentMillis = 0; /* // Variables involved in finding the panel pitch from 3-axis accelerometer readings const byte interrupt1 = 2; // Uno can support external interrupts on pins 2 and 3 volatile boolean setPitch = false; // boolean for setting panel tilt by reading accelerometer data; off by default int averaging = 100; // Acceleration components from 3-axis accelerometer double accelX; double accelY; double accelZ; */ //////////////////////// ZABER STAGE VARIABLES /////////////////////////////////////////////////////////// byte command[6]; byte reply[6]; long replyData; double radius; double zaber[2] = {0, 0}; // [x,y] for the stages (in mm) const unsigned long offsetX = 2119000; //tracking the starting and current absolute positions of the stages const unsigned long offsetY = 2095000; unsigned long posX = 0; unsigned long posY = 0; long delX; long delY; float posXum = 0; float posYum = 0; int axisX = 1; int axisY = 2; // Define common command numbers int homer = 1; // home the stage int renumber = 2; // renumber all devices in the chain int moveAbs = 20; // move absolute int moveRel = 21; // move relative int stopMove = 23; // Stop int speedSet = 42; // Speed to target = 0.00219727(V) degrees/sec (assuming 64 microstep resolution) int getPos = 60; // Query the device for its position int storePos = 16; // Position can be stored in registers 0 to 15 int returnPos = 17; // returns the value (in microsteps) of the position stored in the indicated register int move2Pos = 18; // move to the position stored in the indicated register int reset = 0; // akin to toggling device power String serialComm; ///////////////////////////// PIN DECLARATIONS /////////////////////////////////////////////////////// // GPS uses software serial by default, with RX = pin 2 and TX = pin 3. Mega 2560 does not support // software serial RX on pin 2, so add a jumper wire from pin 2 on GPS shield to RX pin used const int RXPin = 2; // GPS pins const int TXPin = 3; const int rsRX = 4; // RS-232 shield pins const int rsTX = 5; //////////////////////////// OBJECT DECLARATIONS ///////////////////////////////////////////////// RTC_DS1307 rtc; // Adafruit RGB LCD Shield //Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield(); //Create an object for the 6DOF IMU //LSM303C imu; // Create a software serial port to communicate with the Zaber stages SoftwareSerial rs232(rsRX, rsTX); ////////////////////////////// CODE /////////////////////////////////////////////////////////////// void setup() { // Start the Arduino hardware serial port at 9600 baud Serial.begin(57600); if (! rtc.begin()) { Serial.println("Couldn't find RTC"); while (1); } // Enable external interrupt on pin specified by interrupt1 in order to find panel pitch //pinMode(interrupt1, INPUT_PULLUP); //attachInterrupt(digitalPinToInterrupt(interrupt1), findPitch, FALLING); // Begin communication with LCD //lcd.begin(16, 2); // (columns, rows) //lcd.setBacklight(0x5); // Sets the stages to use binary protocol rs232.begin(115200); delay(1000); rs232.println("/tools setcomm 9600 1"); delay(500); Serial.println(rs232.readStringUntil('\n')); delay(100); rs232.end(); delay(200); // Start software serial connection with Zaber stages rs232.begin(9600); delay(2000); //replyData = sendCommand(0, 42, 34402); // Set speed to 1 mm/s } void loop() { DateTime now = rtc.now(); // Grab data from GPS for algorithm variables SunPos.UT = offsetUTC + now.hour() + double(now.minute())/60.0 + double(now.second())/3600.0; // UT in hours [decimal] SunPos.Day = now.day(); // day [integer] SunPos.Month = now.month(); // month [integer] SunPos.Year = now.year(); // year [integer] SunPos.Dt = 96.4 + 0.567*double(now.year()-2061); // Terrestial time - UT SunPos.Longitude = -77.8647 * (2*PI/360.0); // State College Longitude and Latitude [radians] SunPos.Latitude = 40.7946 * (2*PI/360.0); SunPos.Pressure = 1.0; // Pressure [atm] //SunPos.Temperature = imu.readTempC(); // Temperature [C], pulled from LSM303C 6DOF sensor SunPos.Temperature = 20.0; SunPos.Algorithm5(); coord.ze = SunPos.Zenith; coord.az = SunPos.Azimuth + PI; // Finding solar coordinates w.r.t. panel normal cart = sph2rect(coord); cartP.x = (cos(heading) * cart.x) + (sin(heading) * cos(tilt) * cart.y) + (sin(heading) * sin(tilt) * cart.z); cartP.y = (-1)*(sin(heading) * cart.x) + (cos(heading) * cos(tilt) * cart.y) + (cos(heading) * sin(tilt) * cart.z); cartP.z = (cos(tilt) * cart.z) - (sin(tilt) * cart.y); coordP = rect2sph(cartP); if(coordP.az < 0) { coordP.az += (2*PI); } else if(coordP.az > (2*PI)) { coordP.az -= (2*PI); } // Determining zaber stage coordinates if((coordP.ze < 90) && (coordP.ze > 0)) { radius = interp(sin(coordP.ze)); zaber[0] = (-1) * radius * sin(coordP.az); zaber[1] = (-1) * radius * cos(coordP.az); } /* lcd.clear(); lcd.setCursor(0, 0); lcd.print(gps.date.month()); lcd.print('/'); lcd.print(gps.date.day()); lcd.print('/'); lcd.print(gps.date.year()); lcd.print(' '); lcd.print(gps.time.hour()); lcd.print(':'); lcd.print(gps.time.minute()); lcd.setCursor(0, 1); lcd.print(gps.location.lat()); lcd.setCursor(8, 1); lcd.print(gps.location.lng()); */ // Serial commands if(Serial.available() > 0) { serialComm = Serial.readStringUntil('\n'); if(serialComm == "getpos") { posX = sendCommand(axisX, getPos, 0); delX = posX - offsetX; posXum = delX * umResolution; posY = sendCommand(axisY, getPos, 0); delY = posY - offsetY; posYum = delY * umResolution; Serial.print(posX); Serial.print('\t'); Serial.println(posY); Serial.print("X: "); Serial.print(delX); Serial.print(" uSteps, "); Serial.print (posXum); Serial.print(" um \tY: "); Serial.print(delY); Serial.print(" uSteps, "); Serial.print(posYum); Serial.println(" um"); } else if(serialComm == "gettime") { Serial.print(now.month()); Serial.print('/'); Serial.print(now.day()); Serial.print('/'); Serial.print(now.year()); Serial.print('\t'); Serial.print(now.hour()); Serial.print(':'); Serial.print(now.minute()); Serial.print(':'); Serial.println(now.second()); } else if(serialComm == "getcoords") { Serial.print("Az: "); Serial.print(coord.az * 180/PI); Serial.print("\tZe: "); Serial.print(coord.ze * 180/PI); Serial.print("\tAz*: "); Serial.print(coordP.az * 180/PI); Serial.print("\tZe*: "); Serial.print(coordP.ze * 180/PI); Serial.print("\tX: "); Serial.print(mm(zaber[0])); Serial.print(" uSteps, "); Serial.print(zaber[0] * 1000); Serial.print(" um \tY: "); Serial.print(mm(zaber[1])); Serial.print(" uSteps, "); Serial.print(zaber[1] * 1000); Serial.println(" um"); } else if(serialComm == "goto") { replyData = sendCommand(axisX, moveAbs, mm(zaber[0]) + offsetX); replyData = sendCommand(axisY, moveAbs, mm(zaber[1]) + offsetY); } else if(serialComm = "origin") { replyData = sendCommand(axisX, moveAbs, offsetX); replyData = sendCommand(axisY, moveAbs, offsetY); } } } long sendCommand(int device, int com, long data) { unsigned long data2; unsigned long temp; unsigned long repData; long replyNeg; float replyFloat; byte dumper[1]; // Building the six command bytes command[0] = byte(device); command[1] = byte(com); if(data < 0) { data2 = data + quad; } else { data2 = data; } temp = data2 / cubed; command[5] = byte(temp); data2 -= (cubed * temp); temp = data2 / squared; command[4] = byte(temp); data2 -= (squared * temp); temp = data2 / 256; command[3] = byte(temp); data2 -= (256 * data2); command[2] = byte(data2); // Clearing serial buffer while(rs232.available() > 0) { rs232.readBytes(dumper, 1); } // Sending command to stage(s) rs232.write(command, 6); delay(20); // Reading device reply if(rs232.available() > 0) { rs232.readBytes(reply, 6); } replyFloat = (cubed * float(reply[5])) + (squared * float(reply[4])) + (256 * float(reply[3])) + float(reply[2]); repData = long(replyFloat); if(reply[5] > 127) { replyNeg = repData - quad; } // Printing full reply bytes as well as reply data in decimal Serial.print(reply[0]); Serial.print(' '); Serial.print(reply[1]); Serial.print(' '); Serial.print(reply[2]); Serial.print(' '); Serial.print(reply[3]); Serial.print(' '); Serial.print(reply[4]); Serial.print(' '); Serial.println(reply[5]); Serial.print("\tData:"); if(reply[5] > 127) { Serial.println(replyNeg); return replyNeg; } else { Serial.println(repData); return repData; } } <file_sep>/pitch_heading_test_lcd/pitch_heading_test_lcd.ino /* LSM303C 6DOF IMU (6 Degree-of-freedom inertial measurement unit) Test Sketch * Using Hitachi HD44780 chipset LCD screen * * <NAME> * AOPL * Summer 2016 * * Reads X, Y, and Z components of acceleration and magnetic field and, assuming the board is stationary and is subject to only the earth's magnetic * field, determines the pitch and heading of the board. Outputs data to LCD screen instead of serial monitor. */ #include <LiquidCrystal.h> #include <DebugMacros.h> #include <LSM303CTypes.h> #include <SparkFunIMU.h> #include <SparkFunLSM303C.h> const int iter8 = 50; double accelX; //accelerometer components double accelY; double accelZ; double magX = 0; //magnetic field strength in x direction double magY = 0; //magnetic field strength in y direction double magZ = 0; //magnetic field strength in z direction double xHor = 0; //x component of projection of magnetic field vector onto XY plane double yHor = 0; //y component of projection of magnetic field vector onto XY plane double pitch = 0; //calculated values of pitch, roll, and yaw double roll = 0; double heading = 0; // Create an object to control LCD LiquidCrystal lcd(8, 9, 10, 11, 12, 13); // (RS, enable, D4, D5, D6, D7); R/W tied to ground for write only // Create an object to control LSM303C 6DOF IMU LSM303C imu; // Uno: A4 is SDA, A5 is SCL void setup() { lcd.begin(16, 2); // (characters per line, # of lines); if (imu.begin() != IMU_SUCCESS) { lcd.clear(); lcd.setCursor(0, 0); lcd.print("Failed setup."); while(1); } delay(1000); } void loop() { //Determining tilt from accelerometer readings /* accelX = imu.readAccelX(); accelY = imu.readAccelY(); accelZ = imu.readAccelZ(); */ accelX = 0; accelY = 0; accelZ = 0; magX = 0; magY = 0; magZ = 0; for(int i = 0; i < iter8; i++) { accelX += imu.readAccelX(); accelY += imu.readAccelY(); accelZ += imu.readAccelZ(); magX += imu.readMagX(); magY += imu.readMagY(); magZ += imu.readMagZ(); delay(9); } accelX /= iter8; accelY /= iter8; accelZ /= iter8; magX /= iter8; magY /= iter8; magZ /= iter8; pitch = atan2(accelX , sqrt((accelY * accelY) + (accelZ * accelZ))); roll = atan2(accelY , sqrt((accelX * accelX) + (accelZ * accelZ))); yHor = magY*cos(roll) + magZ*sin(roll); xHor = magX*cos(pitch) + magZ*sin(pitch)*sin(roll) + magZ*sin(pitch)*cos(roll); heading = (-atan2(yHor , xHor) * (180/PI)) + 180; lcd.clear(); lcd.setCursor(0, 0); lcd.print("P:"); lcd.print(pitch * (180/PI)); lcd.setCursor(8, 0); lcd.print("R:"); lcd.print(roll * (180/PI)); lcd.setCursor(0, 1); lcd.print(" H: "); lcd.print(heading); delay(100); } <file_sep>/pitch_heading_test/pitch_heading_test.ino /* LSM303C 6DOF IMU (6 Degree-of-freedom inertial measurement unit) Test Sketch * * <NAME> * AOPL * Summer 2016 * * Reads X, Y, and Z components of acceleration and magnetic field and, assuming the board is stationary and is subject to only the earth's magnetic * field, determines the pitch and heading of the board. */ #include <Wire.h> #include <translate.h> #include <DebugMacros.h> #include <LSM303CTypes.h> #include <SparkFunIMU.h> #include <SparkFunLSM303C.h> const int iter8 = 50; double accelX = 0; //accelerometer components double accelY = 0; double accelZ = 0; double accelM = 0; //magnitude of acceleration vector double magX = 0; //magnetic field strength in x direction double magY = 0; //magnetic field strength in y direction double magZ = 0; //magnetic field strength in z direction double magM = 0; //magnitude of magnetic vector double xHor = 0; //x component of projection of magnetic field vector onto XY plane double yHor = 0; //y component of projection of magnetic field vector onto XY plane double pitch = 0; //calculated values of pitch, roll, and yaw double roll = 0; double heading = 0; double emY = -0.38444; //Y and Z components of unit vector in direction of earth's magnetic field double emZ = -0.92315; double emYi = 1/emY; double trans[3][3]; polar coord; polar coordP; vector v_i; vector v_f; //Create an object to control LSM303C 6DOF IMU LSM303C imu; // Uno: A4 is SDA, A5 is SCL void setup() { Serial.begin(9600); /* Wire.begin(); delay(100); Wire.beginTransmission(0x1D); Wire.write(byte(0x20)); Wire.write(byte(0x57)); Wire.endTransmission(); delay(100); */ if (imu.begin() != IMU_SUCCESS) { Serial.println("Failed setup."); while(1); } delay(1000); } void loop() { //Determining tilt from accelerometer readings accelX = 0; accelY = 0; accelZ = 0; magX = 0; magY = 0; magZ = 0; for(int i = 0; i < iter8; i++) { accelX += imu.readAccelX(); accelY += imu.readAccelY(); accelZ += imu.readAccelZ(); magX += imu.readMagX(); magY += imu.readMagY(); magZ += imu.readMagZ(); delay(9); } accelX /= iter8; accelY /= iter8; accelZ /= iter8; magX /= iter8; magY /= iter8; magZ /= iter8; /* accelM = sqrt(accelX*accelX + accelY*accelY + accelZ*accelZ); magM = sqrt(magX*magX + magY*magY + magZ*magZ); trans[0][2] = (-1) * (accelX/accelM); trans[1][2] = (-1) * (accelY/accelM); trans[2][2] = (-1) * (accelZ/accelM); trans[0][1] = ((magX/magM) + (emZ * trans[0][2])) * emYi; trans[1][1] = ((magY/magM) + (emZ * trans[1][2])) * emYi; trans[2][1] = ((magX/magM) + (emZ * trans[2][2])) * emYi; trans[0][0] = (trans[1][1] * trans[2][2]) - (trans[2][1] * trans[1][2]); trans[1][0] = (trans[2][1] * trans[0][2]) - (trans[0][1] * trans[2][2]); trans[2][0] = (trans[0][1] * trans[1][2]) - (trans[1][1] * trans[0][2]); v_i.x = 0; v_i.y = 1; v_i.z = 0; v_f.x = (trans[0][0] * v_i.x) + (trans[0][1] * v_i.y) + (trans[0][2] * v_i.z); v_f.y = (trans[1][0] * v_i.x) + (trans[1][1] * v_i.y) + (trans[1][2] * v_i.z); v_f.z = (trans[2][0] * v_i.x) + (trans[2][1] * v_i.y) + (trans[2][2] * v_i.z); coordP = rect2sph(v_f); heading = (-1)*coordP.az * (180/PI); if(heading < 0) heading += 360; */ pitch = atan2(accelX , sqrt((accelY * accelY) + (accelZ * accelZ))); roll = atan2(accelY , sqrt((accelX * accelX) + (accelZ * accelZ))); yHor = magY*cos(roll) + magZ*sin(roll); xHor = magX*cos(pitch) + magZ*sin(pitch)*sin(roll) + magZ*sin(pitch)*cos(roll); heading = (-atan2(yHor , xHor) * (180/PI)) + 180; /* Serial.print("X: "); Serial.print(magX); Serial.print("\tY: "); Serial.print(magY); Serial.print("\tZ: "); Serial.println(magZ); */ /* Serial.print("AccelX: "); Serial.print(accelX); Serial.print("\tAccelY: "); Serial.print(accelY); Serial.print("\tAccelZ: "); Serial.print(accelZ); */ /* Serial.print("AccelX: "); Serial.print(averageX); Serial.print("\tAccelY: "); Serial.print(averageY); Serial.print("\tAccelZ: "); Serial.print(averageZ); */ Serial.print("\tPitch:"); Serial.print(pitch * (180/PI)); Serial.print("\tRoll:"); Serial.print(roll * (180/PI)); Serial.print("\tHeading:"); Serial.println(heading); } <file_sep>/feedforward_binary_2/feedforward_binary_2.ino /* CPV Feed-forward tracking * Using Zaber Binary protocol * Using f80 lens data * * <NAME> * AOPL * Summer 2016 * * Feed-forward tracking for CPV test setup. Reads data from GPS unit, calculates position of the sun, and converts solar position to mm * displacement along X and Y of the Zaber linear stages. */ #include <zaberx.h> #include <TinyGPS++.h> #include <DebugMacros.h> #include <LSM303CTypes.h> #include <SparkFunIMU.h> #include <SparkFunLSM303C.h> #include <Sun_position_algorithms.h> #include <translate.h> #include <SoftwareSerial.h> // GPS uses software serial by default, with RX = pin 2 and TX = pin 3. Mega 2560 does not support software serial RX on pin 2, so add a jumper wire from pin 2 on GPS shield to RX pin used const int RXPin = 2; const int TXPin = 3; const int rsRX = 4; const int rsTX = 5; // Variables involved in finding the panel pitch from 3-axis accelerometer readings const byte interrupt1 = 2; // Uno can support external interrupts on pins 2 and 3 volatile boolean setPitch = false; // boolean for setting panel tilt by reading accelerometer data; off by default int averaging = 100; // Acceleration components from 3-axis accelerometer double accelX; double accelY; double accelZ; // Variables for solar position calculations sunpos SunPos; polar coord; // zenith and azimuth in a struct polar coordP; vector cart; vector cartP; // Enter array tilt and heading double heading = 180 * (PI/180); double tilt = 0 * (PI/180); // Variables for Zaber binary communication byte command[6]; byte reply[6]; float outData; long replyData; double radius; double zaber[2] = {0, 0}; // [x,y] for the stages (in mm) const unsigned long offsetX = 2148185; //tracking the starting and current absolute positions of the stages const unsigned long offsetY = 2104209; unsigned long posX = 0; unsigned long posY = 0; int axisX = 1; int axisY = 2; // Define common command numbers int homer = 1; // home the stage int renumber = 2; // renumber all devices in the chain int moveAbs = 20; // move absolute int moveRel = 21; // move relative int stopMove = 23; // Stop int speedSet = 42; // Speed to target = 0.00219727(V) degrees/sec (assuming 64 microstep resolution) int getPos = 60; // Query the device for its position int storePos = 16; // Position can be stored in registers 0 to 15 int returnPos = 17; // returns the value (in microsteps) of the position stored in the indicated register int move2Pos = 18; // move to the position stored in the indicated register int reset = 0; // akin to toggling device power // Period of feedback iterations const int interval = 5000; unsigned long previousMillis = 0; unsigned long currentMillis = 0; int GPSBaud = 4800; // Create a TinyGPS++ object called "gps" TinyGPSPlus gps; //Create an object for the 6DOF IMU LSM303C imu; // Create a software serial port called "gpsSerial" SoftwareSerial gpsSerial(RXPin, TXPin); // Create a software serial port to communicate with the Zaber stages SoftwareSerial rs232(rsRX, rsTX); void setup() { // Start the Arduino hardware serial port at 9600 baud Serial.begin(9600); // Enable external interrupt on pin specified by interrupt1 in order to find panel pitch pinMode(interrupt1, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(interrupt1), findPitch, FALLING); // Start the software serial port at the GPS's default baud gpsSerial.begin(GPSBaud); // Sets the stages to use binary protocol rs232.begin(115200); delay(1000); rs232.println("/tools setcomm 9600 1"); delay(500); Serial.println(rs232.readStringUntil('\n')); delay(100); rs232.end(); delay(200); //Start software serial connection with Zaber stages rs232.begin(9600); delay(2000); /* // Positioning stages to origin coinciding with lens axis of symmetry posX = sendCommand(axisX, moveAbs, offsetX); posY = sendCommand(axisY, moveAbs, offsetY); delay(4000); while((sendCommand(axisX, getPos, 0) != offsetX) && (sendCommand(axisY, getPos, 0) != offsetY)) { delay(1000); } */ } void loop() { currentMillis = millis(); if(currentMillis - previousMillis >= interval) { if(gpsSerial.available() > 0) { if(gps.encode(gpsSerial.read())) { SunPos.UT = gps.time.hour() + double(gps.time.minute())/60.0 + double(gps.time.second())/3600.0 + double(gps.time.centisecond())/360000; // UT in hours [decimal] SunPos.Day = gps.date.day(); // day [integer] SunPos.Month = gps.date.month(); // month [integer] SunPos.Year = gps.date.year(); // year [integer] SunPos.Dt = 96.4 + 0.567*double(gps.date.year()-2061); // Terrestial time - UT SunPos.Longitude = gps.location.lng() * (2*PI/360.0); // State College Longitude and Latitude [radians] SunPos.Latitude = gps.location.lat() * (2*PI/360.0); SunPos.Pressure = 1.0; // Pressure [atm] //SunPos.Temperature = imu.readTempC(); // Temperature [C], pulled from LSM303C 6DOF sensor SunPos.Temperature = 20.0; SunPos.Algorithm5(); coord.ze = SunPos.Zenith; coord.az = SunPos.Azimuth + PI; // Finding solar coordinates w.r.t. panel normal cart = sph2rect(coord); cartP.x = (cos(heading) * cart.x) - (sin(heading) * cos(tilt) * cart.y) - (sin(heading) * sin(tilt) * cart.z); cartP.y = (1)*(sin(heading) * cart.x) + (cos(heading) * cos(tilt) * cart.y) + (cos(heading) * sin(tilt) * cart.z); cartP.z = (cos(tilt) * cart.z) - (sin(tilt) * cart.y); coordP = rect2sph(cartP); if(coordP.az < 0) { coordP.az += (2*PI); } else if(coordP.az > (2*PI)) { coordP.az -= (2*PI); } // Determining zaber stage coordinates if((coordP.ze < 90) && (coordP.ze > 0)) { radius = interp2(sin(coordP.ze)); zaber[0] = (-1) * radius * sin(coordP.az); zaber[1] = (-1) * radius * cos(coordP.az); } posX = sendCommand(axisX, moveAbs, mm(zaber[0]) + offsetX); posY = sendCommand(axisY, moveAbs, mm(zaber[1]) + offsetY); } } } if(setPitch == true) { accelX = 0; accelY = 0; accelZ = 0; for(int i = 0; i < averaging; i++) { accelX += imu.readAccelX(); accelY += imu.readAccelY(); accelZ += imu.readAccelZ(); delay(10); } accelX /= averaging; accelY /= averaging; accelZ /= averaging; tilt = atan2(accelX, sqrt((accelY * accelY) + (accelZ * accelZ))); setPitch = false; } } void findPitch() { setPitch = true; } long sendCommand(int device, int com, long data) { unsigned long data2; unsigned long temp; unsigned long repData; long replyNeg; float replyFloat; byte dumper[1]; // Building the six command bytes command[0] = byte(device); command[1] = byte(com); if(data < 0) { data2 = data + quad; } else { data2 = data; } temp = data2 / cubed; command[5] = byte(temp); data2 -= (cubed * temp); temp = data2 / squared; command[4] = byte(temp); data2 -= (squared * temp); temp = data2 / 256; command[3] = byte(temp); data2 -= (256 * data2); command[2] = byte(data2); // Clearing serial buffer while(rs232.available() > 0) { rs232.readBytes(dumper, 1); } // Sending command to stage(s) rs232.write(command, 6); delay(20); // Reading device reply if(rs232.available() > 0) { rs232.readBytes(reply, 6); } replyFloat = (cubed * float(reply[5])) + (squared * float(reply[4])) + (256 * float(reply[3])) + float(reply[2]); repData = long(replyFloat); if(reply[5] > 127) { replyNeg = repData - quad; } // Printing full reply bytes as well as reply data in decimal Serial.print(reply[0]); Serial.print(' '); Serial.print(reply[1]); Serial.print(' '); Serial.print(reply[2]); Serial.print(' '); Serial.print(reply[3]); Serial.print(' '); Serial.print(reply[4]); Serial.print(' '); Serial.println(reply[5]); Serial.print("\tData:"); if(reply[5] > 127) { Serial.println(replyNeg); return replyNeg; } else { Serial.println(repData); return repData; } } <file_sep>/solar2planar/solar2planar.ino /* Sample code for testing the conversion from solar coordinates to planar coordinates in the array of the concentrator cell * Using f20 lens data * * <NAME> * AOPL * Summer 2016 * * Gets data from GPS, calculates solar position, then transforms local horizontal solar coordinates into XY coordinates * in the plane of the concentrator. */ #include <TinyGPS++.h> #include <Sun_position_algorithms.h> #include <translate.h> #include <SoftwareSerial.h> //GPS uses software serial by default, with RX = pin 2 and TX = pin 3. Mega 2560 does not support software serial RX on pin 2, so add a jumper wire from pin 2 on GPS shield to RX pin used int RXPin = 2; int TXPin = 3; sunpos SunPos; polar coord; // zenith and azimuth in a struct polar coordP; vector cart; vector cartP; double radius; double zaberOld[2] = {0, 0}; // [x,y] for the stages (in mm) double zaber[2] = {0, 0}; //Enter array tilt and heading double heading = 180 * (PI/180); double tilt = 0 * (PI/180); int GPSBaud = 4800; double p[] = {0, 0.0235, 0.0470, 0.0705, 0.0940, 0.117, 0.141, 0.164, 0.188, 0.211, 0.235, 0.258, 0.282, 0.305, 0.329, 0.352, 0.376, 0.399, 0.423, 0.446, 0.470, 0.493, 0.517, 0.540, 0.564, 0.587, 0.611, 0.634, 0.658, 0.681, 0.705, 0.728, 0.752, 0.775, 0.799, 0.822, 0.846, 0.869, 0.893, 0.916, 0.940}; double q[] = {0, 0.132, 0.264, 0.397, 0.529, 0.662, 0.795, 0.928, 1.06, 1.20, 1.33, 1.46, 1.60, 1.74, 1.87, 2.01, 2.15, 2.29, 2.42, 2.57, 2.71, 2.85, 2.99, 3.14, 3.28, 3.43, 3.58, 3.73, 3.89, 4.05, 4.21, 4.37, 4.53, 4.69, 4.86, 5.04, 5.21, 5.39, 5.57, 5.76, 5.96}; // Create a TinyGPS++ object called "gps" TinyGPSPlus gps; // Create a software serial port called "gpsSerial" SoftwareSerial gpsSerial(RXPin, TXPin); void setup() { // Start the Arduino hardware serial port at 9600 baud Serial.begin(9600); // Start the software serial port at the GPS's default baud gpsSerial.begin(GPSBaud); delay(2000); Serial.println("Solar position routine begin"); } void loop() { while (gpsSerial.available() > 0) { if(gps.encode(gpsSerial.read())) { SunPos.UT = gps.time.hour() + double(gps.time.minute())/60.0 + double(gps.time.second())/3600.0 + double(gps.time.centisecond())/360000; // UT in hours [decimal] SunPos.Day = gps.date.day(); // day [integer] SunPos.Month = gps.date.month(); // month [integer] SunPos.Year = gps.date.year(); // year [integer] SunPos.Dt = 96.4 + 0.567*double(gps.date.year()-2061); // Terrestial time - UT SunPos.Longitude = gps.location.lng() * (2*PI/360.0); // State College Longitude and Latitude [radians] SunPos.Latitude = gps.location.lat() * (2*PI/360.0); SunPos.Pressure = 1.0; // Pressure [atm] //SunPos.Temperature = imu.readTempC(); // Temperature [C], pulled from LSM303C 6DOF sensor SunPos.Temperature = 20.0; SunPos.Algorithm5(); coord.ze = SunPos.Zenith; coord.az = SunPos.Azimuth + PI; // Finding solar coordinates w.r.t. panel normal cart = sph2rect(coord); cartP.x = (cos(heading) * cart.x) - (sin(heading) * cos(tilt) * cart.y) - (sin(heading) * sin(tilt) * cart.z); cartP.y = (1)*(sin(heading) * cart.x) + (cos(heading) * cos(tilt) * cart.y) + (cos(heading) * sin(tilt) * cart.z); cartP.z = (cos(tilt) * cart.z) - (sin(tilt) * cart.y); coordP = rect2sph(cartP); if(coordP.az < 0) { coordP.az += (2*PI); } else if(coordP.az > (2*PI)) { coordP.az -= (2*PI); } /* if((coord.az > PI) && (coordP.az < 0)) { coordP.az += (2* PI); } else if((coord.az < PI) && (coordP.az < 0)) { coordP.az += PI; } else if((coord.az > PI) && (coordP.az > 0)) { coordP.az += PI; } */ // Determining zaber stage coordinates zaberOld[0] = zaber[0]; zaberOld[1] = zaber[1]; if((coordP.ze < 90) && (coordP.ze > 0)) { radius = interp1(sin(coordP.ze)); zaber[0] = (-1) * radius * sin(coordP.az); zaber[1] = (-1) * radius * cos(coordP.az); } // prints out timestamp and zenith and azimuth angles in degrees Serial.print(gps.date.month()); Serial.print(F("/")); Serial.print(gps.date.day()); Serial.print(F("/")); Serial.print(gps.date.year()); Serial.print(F(" ")); if (gps.time.isValid()) { if (gps.time.hour() < 10) Serial.print(F("0")); Serial.print(gps.time.hour()); Serial.print(F(":")); if (gps.time.minute() < 10) Serial.print(F("0")); Serial.print(gps.time.minute()); Serial.print(F(":")); if (gps.time.second() < 10) Serial.print(F("0")); Serial.print(gps.time.second()); Serial.print(F(".")); if (gps.time.centisecond() < 10) Serial.print(F("0")); Serial.print(gps.time.centisecond()); } else { Serial.print(F("INVALID")); } Serial.print("\t"); Serial.print(gps.location.lat(), 6); Serial.print(F(",")); Serial.print(gps.location.lng(), 6); Serial.print("\tZenith: "); Serial.print(coord.ze * (180/PI)); Serial.print(" Azimuth: "); Serial.print(coord.az * (180/PI)); Serial.print("\tZenith*:"); Serial.print(coordP.ze * 180/PI); Serial.print("\tAzimuth*:"); Serial.print(coordP.az * 180/PI); Serial.print("\tX:"); Serial.print(zaber[0]); Serial.print("\tY:"); Serial.println(zaber[1]); delay(500); } } } double interp1(double input) { double out; int i = 0; while(input >= p[i]) { i++; } out = q[i-1] + ((input - p[i-1])/(p[i] - p[i-1])) * (q[i] - q[i-1]); return out; }
049eb242c957ee0d872fe83563af6391bb80616b
[ "Text", "C++" ]
9
C++
gregorypeter/OpenLoopSunTracker
8537b73fd82d941a18248ccb4f3cf7e3211f16d6
1d8f56417804f98d475e9f1b213abcc0292d33c9
refs/heads/master
<repo_name>asmina94/Monster<file_sep>/app/src/main/java/com/oreilly/demo/android/pa/uidemo/TouchMe.java package com.oreilly.demo.android.pa.uidemo; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.widget.EditText; import android.os.AsyncTask; import com.oreilly.demo.android.pa.uidemo.model.Dot; import com.oreilly.demo.android.pa.uidemo.model.DotWorld; import com.oreilly.demo.android.pa.uidemo.model.Dots; import com.oreilly.demo.android.pa.uidemo.model.LiveMonster; import com.oreilly.demo.android.pa.uidemo.view.DotView; /** Android UI demo program */ public class TouchMe extends Activity { /** Dot diameter */ public static final int DOT_DIAMETER = 80; /** Listen for taps. */ private static final class TrackingTouchListener implements View.OnTouchListener { private final Dots mDots; // private final Dot mDot; private List<Integer> tracks = new ArrayList<>(); TrackingTouchListener(final Dots dots) { mDots = dots; } // TrackingTouchListener(final Dots dots) { mDot = dots; } @Override public boolean onTouch(final View v, final MotionEvent evt) { final int action = evt.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: final int idx1 = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; tracks.add(evt.getPointerId(idx1)); break; case MotionEvent.ACTION_POINTER_UP: final int idx2 = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; tracks.remove(evt.getPointerId(idx2)); break; case MotionEvent.ACTION_MOVE: final int n = evt.getHistorySize(); for (Integer i: tracks) { final int idx = evt.findPointerIndex(i); for (int j = 0; j < n; j++) { // addDot( // mDots, // evt.getHistoricalX(idx, j), // evt.getHistoricalY(idx, j), // evt.getHistoricalPressure(idx, j), // evt.getHistoricalSize(idx, j)); } } break; default: return false; } for (final Integer i: tracks) { final int idx = evt.findPointerIndex(i); // addDot( // mDots, // evt.getX(idx), // evt.getY(idx), // evt.getPressure(idx), // evt.getSize(idx)); } return true; } private void addDot( final Dots dots, final int x, final int y, final int p, final int s) { dots.addDot(x, y); } } private final Random rand = new Random(); /** The application model */ private final Dots dotModel = new Dots(); private final Dots dotModel1 = new Dots(); /** The application view */ private DotView dotView; /** The dot generator */ private Timer dotGenerator; int dotcount =0 ; /** Called when the activity is first created. */ @Override public void onCreate(final Bundle state) { super.onCreate(state); // install the view setContentView(R.layout.main); // find the dots view dotView = (DotView) findViewById(R.id.dots); dotView.setDots(dotModel); dotView.setDots(dotModel1); dotView.setOnCreateContextMenuListener(this); dotView.setOnTouchListener(new TrackingTouchListener(dotModel)); dotView.setOnTouchListener(new TrackingTouchListener(dotModel1)); dotView.setOnKeyListener((final View v, final int keyCode, final KeyEvent event) -> { if (KeyEvent.ACTION_DOWN != event.getAction()) { return false; } int color; switch (keyCode) { case KeyEvent.KEYCODE_SPACE: color = Color.MAGENTA; break; case KeyEvent.KEYCODE_ENTER: color = Color.BLUE; break; default: return false; } // makeDot(dotModel, dotView, color); return true; }); // wire up the controller // findViewById(R.id.button1).setOnClickListener((final View v) -> // makeDot(dotModel, dotView, Color.RED) // ); // findViewById(R.id.button2).setOnClickListener((final View v) -> // makeDot(dotModel, dotView, Color.GREEN) // ); /* final EditText tb1 = (EditText) findViewById(R.id.text1); final EditText tb2 = (EditText) findViewById(R.id.text2); dotModel.setDotsChangeListener((final Dots dots) -> { final Dot d = dots.getLastDot(); tb1.setText((null == d) ? "" : String.valueOf(d.getX())); tb2.setText((null == d) ? "" : String.valueOf(d.getY())); */ dotView.invalidate(); // }); } @Override public void onResume() { super.onResume(); //initial the monsters Dot dotArr[][] = new Dot[7][5]; int x, y; for(int i=0; i< dotArr.length;i++) { x = i; for (int j = 0; j < dotArr[0].length; j++) { y = j; dotArr[i][j] = new Dot(x, y); dotModel.addDot(x, y); } } for(int i=0; i< dotArr.length;i++) { for (int j = 0; j < dotArr[0].length; j++) { System.out.println("dotArr[" + i + "][" + j+"]" + dotArr[i][j].getX() +dotArr[i][j].getY() ); } } //set neighbours of one monter DotWorld world= new DotWorld(dotArr); new MoveTask().execute(dotArr); } @Override public void onPause() { super.onPause(); if (dotGenerator != null) { dotGenerator.cancel(); dotGenerator = null; } } /** Install an options menu. */ @Override public boolean onCreateOptionsMenu(final Menu menu) { getMenuInflater().inflate(R.menu.simple_menu, menu); return true; } /** Respond to an options menu selection. */ @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.menu_clear: // dotModel.clearDots(); return true; default: return super.onOptionsItemSelected(item); } } /** Install a context menu. */ @Override public void onCreateContextMenu( final ContextMenu menu, final View v, final ContextMenuInfo menuInfo) { menu.add(Menu.NONE, 1, Menu.NONE, "Clear").setAlphabeticShortcut('x'); } /** Respond to a context menu selection. */ @Override public boolean onContextItemSelected(final MenuItem item) { switch (item.getItemId()) { case 1: // dotModel.clearDots(); return true; default: return false; } } class MoveTask extends AsyncTask<Dot[][], Dots, Dot> { /** * @param dots the monsters we're drawing * */ @Override protected void onProgressUpdate(Dots... dots) { dotView.invalidate(); } protected void onPostExecute(String result) { } /** * This method makes the monsters to move around among adjacent squares at random * @param dotarr * @return Dot */ @Override protected Dot doInBackground(Dot[][]... dotarr) { List<LiveMonster> monsterlist= new LinkedList<LiveMonster>(); //initial k monsters for(int i=0; i< 5;i++) { for (int j = 0; j < 4; j++) { LiveMonster m = new LiveMonster(dotarr[0][i][j]); monsterlist.add(m); }} while (!this.isCancelled()) { for(LiveMonster lm:monsterlist){ try { lm.getDot().randomNeighbor().enter(lm); } catch (InterruptedException e) { e.printStackTrace(); } dotModel1.addDot(lm.getDot().getX(), lm.getDot().getY()); try { Thread.sleep(5); } catch (InterruptedException ex) { ex.printStackTrace(); } } publishProgress(dotModel1); } return null; } } }<file_sep>/app/src/main/java/com/oreilly/demo/android/pa/uidemo/model/LiveMonster.java package com.oreilly.demo.android.pa.uidemo.model; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * This abstract class represents a monster with autonomous behavior. * Concrete subclasses should implement the <code>run()</code> method. */ public class LiveMonster implements Monster, Runnable { boolean DEBUG = false; ////////////////////////////////////////////////////////////// /** * The cell this monster is currently occupying. */ private Dot currentDot; /** * The live thread of this monster. This thread runs the <code>run()</code> * method implemented by concrete subclasses of this class. */ private ExecutorService liveThread; /** * The work thread of this monster. This thread handles requests, usually * coming from the live thread, to do some work, such as moving to another cell. * It is necessary to use a separate thread for this because an attempt to * enter another cell might block. For example, without using a separate * work thread, this can cause deadlock * if two monsters are trying to move into each other's cell of capacity one. * A separate work thread also allows an monster to change their mind * if another task of higher priority should take precedence over * a task on which the work thread is currently working. */ private ExecutorService workThread; /** * The destination of the most recent attempt to move. */ private Future task = null; public LiveMonster(Dot dot){ currentDot = dot; } /** * This method indicates whether this monster is still alive. */ protected synchronized boolean isAlive() { return liveThread != null; } /** * This method brings this monster to life by starting its internal threads. */ public synchronized void start() { System.out.println("Start"); if (! isAlive()) { liveThread = Executors.newFixedThreadPool(1); workThread = Executors.newFixedThreadPool(1); } liveThread.execute(this); } /** * This method kills this monster by stopping its internal threads. */ public synchronized void kill() { if (isAlive()) { liveThread.shutdown(); workThread.shutdown(); liveThread = null; workThread = null; } } public synchronized void setDot(Dot dot) { currentDot = dot; } public synchronized Dot getDot() { return currentDot; } /** * This method is used to schedule the runnable for execution by this * monster. If the monster is still waiting for a previously scheduled * runnable to execute, then this invocation preempts the previous one. */ protected synchronized void execute(Runnable runnable) { if (DEBUG) System.out.println(this + " wants to execute " + runnable); if (task != null && ! task.isDone()) { task.cancel(true); } task = workThread.submit(runnable); } /** * This method removes this dead monster from the cell it occupied. */ protected synchronized void die() { Dot dot = getDot(); setDot(null); dot.leave(this); } /////////////////////////////////////////////////////////////// private static Random random = new Random(); public void run() { while (! Thread.interrupted()) { try { Thread.sleep(random.nextInt(1000)); // schedule a move for execution execute(move); } catch (InterruptedException exc) { if (DEBUG) System.out.println(this + " live thread interrupted"); Thread.currentThread().interrupt(); } } System.out.println(this + ": squeak!"); } /** * A runnable representing a move. */ private Runnable move = new Runnable() { public void run() { try { getDot().randomNeighbor().enter(LiveMonster.this); } catch (InterruptedException e) { // if interrupted before entering the cell, then set interrupted flag // so that the worker thread can detect this Thread.currentThread().interrupt(); } } }; public void enterDot(DotEvent event) { if (event.getMonster() != this) { //System.out.println(this + ": hello " + event.getMonster()); } } public void leaveDot(DotEvent event) { if (event.getMonster() != this) { // System.out.println(this + ": goodbye " + event.getMonster()); } } }
b61bc538ffe812a4e1bcb455f80f925b0a0c0ec0
[ "Java" ]
2
Java
asmina94/Monster
0230a8247ef1b155ef36b8e49206c7bac3270621
02de622e803037b7c93a0f2a4ee94e76553e6b72
refs/heads/main
<file_sep>var garden,rabbit,apple,leaf1,leaf2,leaf3; var gardenImg,rabbitImg,appleImg,leaf1Img,leaf2Img,leaf3Img; var x; var y; var c; var d; var e; var f; var g; var h; var score = 0; function preload(){ gardenImg = loadImage("garden.png"); rabbitImg = loadImage("rabbit.png"); appleImg = loadImage("apple.png"); leaf1Img = loadImage("leaf.png"); leaf2Img = loadImage("orangeLeaf.png"); leaf3Img = loadImage("redImage.png"); } function setup(){ createCanvas(400,400); garden=createSprite(200,200); garden.addImage(gardenImg); rabbit = createSprite(180,340,30,30); rabbit.scale =0.09; rabbit.addImage(rabbitImg); x = Math.round(random(30,370)); y = Math.round(random(30,370)); c = Math.round(random(30,370)); d = Math.round(random(30,370)); edges = createEdgeSprites(); } function draw() { background("white"); rabbit.collide(edges); if(keyDown("UP_ARROW")){ rabbit.y = rabbit.y - 7.5; } if(keyDown("DOWN_ARROW")){ rabbit.y = rabbit.y + 7.5; } if(keyDown("LEFT_ARROW")){ rabbit.x = rabbit.x - 7.5; } if(keyDown("RIGHT_ARROW")){ rabbit.x = rabbit.x + 7.5; } //text("Score: " + score,200,200); fill("yellow"); if (frameCount % Math.round(100,300) === 0){ apple = createSprite(x,y,1,1); apple.addImage(appleImg); apple.scale = 0.05; apple.velocityY = 5; apple.lifetime = 100; x = Math.round(random(30,370)); y = Math.round(random(30,370)); } if (frameCount % Math.round(100,300) === 0){ leaf1 = createSprite(c,d,1,1); leaf1.addImage(leaf1Img); leaf1.scale = 0.05; c = Math.round(random(30,370)); d = Math.round(random(30,370)); leaf1.velocityY = 3; leaf1.lifetime = 150; } if (frameCount % Math.round(100,300) === 0){ leaf2 = createSprite(e,f,1,1); leaf2.addImage(leaf2Img); leaf2.scale = 0.05; e = Math.round(random(30,370)); f = Math.round(random(30,370)); leaf2.velocityY = 6; leaf2.lifetime = 150; } if (frameCount % Math.round(100,300) === 0){ leaf3 = createSprite(g,h,1,1); leaf3.addImage(leaf3Img); leaf3.scale = 0.05; g = Math.round(random(30,370)); h = Math.round(random(30,370)); leaf3.velocityY = 2; leaf3.lifetime = 150; } drawSprites(); }
3534da2868182e7239b46aa5a2e6300bbcd386ae
[ "JavaScript" ]
1
JavaScript
Nathzlamborghini/rabbit
ffe11649eb3bd4b977d5597ad0fb0de5ee71d3de
1f301f76cf8921250df825aad661e9222b27b747
refs/heads/master
<repo_name>ares333/php-yaf-library-demo<file_sep>/library/View.php <?php use Ares333\Yaf\Tool\SmartyView; use Ares333\Yaf\Tool\Singleton; class View extends SmartyView { use Singleton; }<file_sep>/app/controllers/Index.php <?php use Yaf\Controller_Abstract; use Yaf\Application; use Ares333\Yaf\Helper\Http; class IndexController extends Controller_Abstract { function indexAction() { echo 'Hello world!'; return false; } function apiAction() { $index = Application::app()->getAppDirectory() . '/../app-api/public/index.php'; require $index; $this->getResponse()->clearHeaders(); return false; } function jsConfigAction() { $request = $this->getRequest(); $config = array(); $config['urlOrigin'] = Http::getOriginUrl(); $config = json_encode($config, JSON_UNESCAPED_SLASHES); $name = $this->getRequest()->getQuery('name', '_config'); echo 'var ' . $name . '=' . $config; $this->getResponse()->setHeader('Content-Type', 'application/javascirpt'); return false; } }<file_sep>/library/Captcha/Image.php <?php namespace Captcha; use Zend\Captcha\Image as Base; use Yaf\Application; use Ares333\Yaf\Tool\Singleton; use Zend\Session\Container; class Image extends Base { use Singleton; function __construct($options = null) { if (! isset($options)) { $options = []; } $appPath = Application::app()->getAppDirectory(); if (! isset($options['font'])) { $options['font'] = $appPath . '/../data/fonts/consola.ttf'; } if (! isset($options['session'])) { $options['session'] = new Container(__CLASS__); $options['session']->setExpirationSeconds(600); } if (! isset($options['imgDir'])) { $options['imgDir'] = dirname($appPath) . '/public/_captcha'; } if (! isset($options['imgUrl'])) { $options['imgUrl'] = '/_captcha'; } if (! isset($options['imgAlt'])) { $options['imgAlt'] = '验证码'; } if (! isset($options['wordLen'])) { $options['wordLen'] = 4; } parent::__construct($options); } }<file_sep>/app/conf/admin/table/house/save.ini [product] cols.cityId.type=select cols.cityId.require.0.table=country cols.cityId.require.0.colValue=cityId@ provinceId@ countryId cols.decorationId.type=select cols.desc.type=editor ;标准多对多关系 child.0.type=image child.0.table=houseImage child.0.colSort=sort<file_sep>/app/conf/admin/table/houseImage/save.ini [product] cols.imageId.type=image<file_sep>/app/controllers/Admin/Table.php <?php use Yaf\Controller_Abstract; use Db\TableGateway; use Zend\Paginator\Paginator; use Ares333\Yaf\Zend\Paginator\Adapter\DbTableGatewaySelect; use Zend\Db\Sql\Predicate\Expression; use Db\TableGateway\Feature\MetadataFeature; use Zend\Db\Metadata\Object\ColumnObject; use Db\Adapter; use Zend\Db\Sql\Select; use Db\TableGateway\Feature\Mysql\SelectParentFeature; use Zend\Db\Metadata\Object\ViewObject; class Admin_TableController extends Controller_Abstract { protected $adapter; protected $tableGateway; protected $metadata; protected $columnSep; protected $parentSep; protected $modulePathName; protected $isView; function init() { $out = array(); if (! isset($this->adapter)) { $this->adapter = Adapter::getInstance(); } $this->modulePathName = lcfirst(explode('_', get_class($this))[0]); $this->tableGateway = TableGateway::getInstance( $this->getRequest()->getParam($this->modulePathName . '_tableName'), $this->adapter); $out['_metadata'] = $this->metadata = $this->tableGateway->getMetadata(); $this->isView = $this->tableGateway->getMetadata()->getTable( $this->tableGateway->getTable()) instanceof ViewObject; $parentFeature = $this->tableGateway->addSelectParentFeature(); $this->columnSep = $parentFeature->getColumnSep(); $this->parentSep = $parentFeature->getParentSep(); $userClass = '\\' . ucfirst($this->modulePathName) . '\User'; $rowUser = TableGateway::getInstance($this->modulePathName . 'User')->select( [ 'id' => $userClass::getInstance()->getId() ]) ->current(); unset($rowUser['password']); $out['_user'] = $rowUser; $out['_updateDeleteColumn'] = MetadataFeature::$updateDeleteColumn; $out['_controllerNameName'] = '_controllerNameTable'; $out['_columnSep'] = $this->columnSep; $this->getView()->assign($out); } protected function getInputId() { static $id = 1; return $id ++; } function indexAction() { $out = array(); $out['meta'] = $this->getIndexMeta(); $out['tableGateway'] = $this->tableGateway; $params = $this->getRequest()->getQuery(); if (! isset($params['where'])) { $params['where'] = array(); } if (! isset($params['join'])) { $params['join'] = array(); } $tableGateway = $this->tableGateway; $select = $tableGateway->getSql()->select(); // where foreach ($params['where'] as $k => $v) { if ('' !== $v) { $select->where( new Expression(urldecode($k), explode($this->columnSep, $v))); } } // group if (isset($params['group']) && $params['group'] === 'yes') { $select->group(null); } // join foreach ($params['join'] as $v) { $select->join($v['table'], $v['cond'], [], $select::$v['type']); } // order if (isset($params['sort'])) { $out['sort'] = null; if (! empty($params['sort'])) { $out['sort'] = $params['sort']; } } else if (isset($out['meta']['order'], $out['meta']['order']['default'])) { $out['sort'] = $out['meta']['order']['default']; } if (isset($out['sort'])) { $select->order($out['sort']); } // page $paginator = new Paginator( new DbTableGatewaySelect($tableGateway, $select)); $page = $this->getRequest()->getQuery('page', 1); $paginator->setCurrentPageNumber($page); $out['list'] = $paginator->getItemsByPage($page); $paginator->setItemCountPerPage(10); $out['pages'] = $paginator->getPages(); // process opt child if (false && $out['meta']['opt']['refd']['enable']) { $refd = $tableGateway->getReferencedColumn(); foreach ($refd as $v) { if ($v[0]['TABLE_NAME'] != $out['meta']['opt']['refd']['table']) { continue; } if (isset($out['meta']['opt']['refd']['column'])) { foreach ($v as $v1) { if (! in_array($v1['COLUMN_NAME'], $out['meta']['opt']['refd']['column'])) { continue; } } } $vQuery = array(); foreach ($v as $v1) { $optRefdPlaceholder = '{$' . $v1['REFERENCED_COLUMN_NAME'] . '}'; $vQuery[] = 'data[' . $v1['COLUMN_NAME'] . ']=' . $optRefdPlaceholder . '&where[' . $v1['TABLE_NAME'] . '.' . $v1['COLUMN_NAME'] . '%3D%3F]=' . $optRefdPlaceholder; } $vQuery = implode('&', $vQuery); $out['meta']['opt']['refd']['url'] = '/admin_table_' . strtolower($v[0]['TABLE_NAME']) . '?' . $vQuery; if (! isset($out['meta']['opt']['refd']['column'])) { $out['meta']['opt']['refd']['column'] = $v[0]['TABLE_NAME']; } break; } } $this->getView()->assign($out); return true; } protected function getConfig($name) { $file = $this->modulePathName . '/table/' . $this->tableGateway->getTable() . '/' . $name . '.ini'; return Config::get($file); } /** * get column name for label */ protected function getLabelColumnName($table) { $config = Config::get($this->modulePathName . '/table.ini'); if (null != $config->get($table)) { if (isset($config->get($table)->colLabel)) { return $config->get($table)->colLabel; } } foreach ($this->metadata->getColumns($table) as $v) { if (in_array($v->getDataType(), [ 'varchar', 'char' ])) { return $v->getName(); } } } protected function getIndexMeta() { $meta = []; $config = $this->getConfig('index'); $configTable = Config::get($this->modulePathName . '/table.ini'); $configTableCurrent = $configTable->get($this->tableGateway->getTable()); $meta['cols'] = $meta['where'] = []; if (isset($config, $config['cols'])) { $meta['cols'] = $config['cols']->toArray(); } else { $validDataType = [ 'int', 'varchar', 'char' ]; foreach ($this->metadata->getColumns( $this->tableGateway->getTable()) as $v) { if (in_array($v->getDataType(), $validDataType)) { if (isset(MetadataFeature::$updateDeleteColumn) && MetadataFeature::$updateDeleteColumn == $v->getName()) { continue; } $meta['cols'][] = [ 'column' => $v->getName() ]; } } } if (isset($config, $config['where'])) { $meta['where'] = $config['where']->toArray(); } foreach ($meta['cols'] as $k => $v) { if (false !== strpos($v['column'], ' ')) { $v['column'] = preg_split('/\s+/', $v['column']); $vReferencedTable = $this->tableGateway->getTable(); foreach ($v['column'] as $v1) { if ('@' === substr($v1, - 1)) { $v1column = explode($this->columnSep, substr($v1, 0, - 1)); $v1constraints = $this->metadata->getTable( $vReferencedTable)->getConstraints(); foreach ($v1constraints as $v2) { if ($v2->getColumns() == $v1column) { // used in order $v['name'] = $v2->getTableName() . '.' . $v2->getColumns()[0]; $vReferencedTable = $v2->getReferencedTableName(); } } } } if (isset($configTable, $configTable->$vReferencedTable->label)) { $v['label'] = $configTable->$vReferencedTable->label; if (isset( $configTable->$vReferencedTable->cols[end($v['column'])]->label)) { $v['label'] .= $configTable->$vReferencedTable->cols[end( $v['column'])]->label; } else { $v['label'] .= end($v['column']); } } else { $v['label'] = substr($v['column'][0], 0, - 1); } } else { if (isset($configTableCurrent, $configTableCurrent->cols[$v['column']]['label'])) { $v['label'] = $configTableCurrent->cols[$v['column']]['label']; } // used in order $v['name'] = $this->tableGateway->getTable() . '.' . $v['column']; } $meta['cols'][$k] = $v; } foreach ($meta['where'] as $k => $v) { if (! isset($v['type'])) { if (isset($v['table'])) { $v['type'] = 'select'; $v['colName'] = $this->getLabelColumnName($v['table']); } else { $v['type'] = 'text'; } } $meta['where'][$k] = $v; } $meta['opt'] = array(); if (isset($config, $config['opt'])) { $meta['opt'] = $config->opt->toArray(); } if ($this->isView) { $meta['opt']['add']['enable'] = false; $meta['opt']['edit']['enable'] = false; $meta['opt']['delete']['enable'] = false; $meta['opt']['detail']['enable'] = false; } else { if (! isset($meta['opt']['add']['enable'])) { $meta['opt']['add']['enable'] = true; } if (! isset($meta['opt']['edit']['enable'])) { $meta['opt']['edit']['enable'] = true; } if (! isset($meta['opt']['delete']['enable'])) { $meta['opt']['delete']['enable'] = true; } if (! isset($meta['opt']['detail']['enable'])) { $meta['opt']['detail']['enable'] = true; } } // opt child if (isset($meta['opt']['child'])) { foreach ($meta['opt']['child'] as $k => $v) { if (isset($configTable[$v['table']]['label'])) { $v['label'] = $configTable[$v['table']]['label']; } else { $v['label'] = $k; } $vConstraint = $this->metadata->getConstraintsFk($v['table']); $vPrimary = $this->metadata->getConstraintPrimaryKey( $this->tableGateway->getTable()); foreach ($vConstraint as $v1) { if ($v1->getReferencedTableName() == $this->tableGateway->getTable() && $v1->getReferencedColumns() == $vPrimary->getColumns()) { $v['whereKey'] = []; foreach ($vPrimary->getColumns() as $k2 => $v2) { $v['whereKey'][$v2] = $v1->getTableName() . '.' . $v1->getColumns()[$k2]; } break; } } $meta['opt']['child'][$k] = $v; } } $meta['order'] = []; if (isset($config, $config['order'])) { $meta['order'] = $config['order']->toArray(); } $meta['group'] = array( 'meta' => array(), 'node' => array() ); $meta['join'] = array( 'meta' => array(), 'node' => array() ); return $meta; } protected function getSaveMeta($type) { $out = array(); $meta = []; $tableGateway = $this->tableGateway; $cols = $this->metadata->getColumns($tableGateway->getTable()); $colsAutoInc = []; foreach ($this->metadata->getColumnsAutoIncrement( $tableGateway->getTable()) as $v) { $colsAutoInc[] = $v->getName(); } if ($type == 'add' || $type == 'edit') { $configType = 'save'; } else { $configType = $type; } $config = $this->getConfig($configType); $configTable = Config::get($this->modulePathName . '/table.ini'); $configTableCurrent = $configTable->get($tableGateway->getTable()); if (isset($configTableCurrent)) { $configTableCurrentCols = $configTableCurrent->get('cols'); } if (isset($config)) { $configCols = $config->get('cols'); } else { $configCols = null; } $colsMeta = []; foreach ($cols as $v) { $v = clone $v; if (in_array($v->getName(), $colsAutoInc)) { $v->isAutoIncrement = true; } else { $v->isAutoIncrement = false; } if (isset($configTableCurrentCols, $configTableCurrentCols->{$v->getName()})) { $vConfigTableCols = $configTableCurrentCols->{$v->getName()}; } else { $vConfigTableCols = null; } if (isset($configCols)) { $vConfig = $configCols->get($v->getName()); } else { $vConfig = null; } if (isset($vConfig->type)) { $v->type = $vConfig->type; } else { switch ($v->getDataType()) { case 'timestamp': $v->type = 'datetime'; break; case 'text': $v->type = 'textarea'; break; default: $v->type = 'text'; } } if ($v->type == 'editor') { $out['hasEditor'] = true; } if (isset($vConfig->readonly)) { $v->readonly = $vConfig->readonly; } if (isset($vConfig->disabled)) { $v->disabled = $vConfig->disabled; } if (isset($vConfig->plaintext)) { $v->isPlaintext = $vConfig->plaintext; } if ($v->isVirtual) { $v->isPlaintext = true; } if (isset($vConfigTableCols->label)) { $v->label = $vConfigTableCols->label; } if (isset($vConfig->rows)) { $v->rows = $vConfig->rows; } if (isset($vConfig->helper)) { $v->helper = $vConfig->helper; } if (isset($vConfig->placeholder)) { $v->placeholder = $vConfig->placeholder; } if ($v->type == 'select') { if (isset($vConfig->require)) { foreach ($vConfig->require as $v1) { $v1col = new ColumnObject(explode(' ', $v1['colValue']), $v1->table, $v1->schema ?? $this->metadata->getDefaultSchema()); $v1configTable = $configTable->get($v1['table']); $v1col->label = $v1['table']; if (isset($v1configTable) && isset($v1configTable['label'])) { $v1col->label = $v1configTable['label']; } if (isset($v1->where)) { $v1col->where = $v1->where; } $v1col->selectTable = $v1->table; $v1col->selectColName = $this->getLabelColumnName( $v1['table']); $v1col->type = 'select'; $v1col->setIsNullable(false); $v1col->id = $this->getInputId(); $v1col->required = true; $v1col->isVirtual = false; $v1col->isAutoIncrement = false; $colsMeta[] = $v1col; } } foreach ($this->metadata->getConstraintsFk($v->getTableName(), $v->getSchemaName()) as $v1) { if ($v1->getColumns() == [ $v->getName() ]) { $v->selectTable = $v1->getReferencedTableName(); $v->selectColName = $this->getLabelColumnName( $v->selectTable); } } } $v->id = $this->getInputId(); $colsMeta[] = $v; } $childMeta = []; if (isset($config, $config->child)) { foreach ($config->child as $v) { $vConstraintChild = null; $vConstraint = null; $vTable = []; if (isset($configTable)) { foreach ($configTable as $k1 => $v1) { if ($v1['type'] == 'image' || $v1['type'] == 'file') { $vTable[] = $k1; } } } foreach ($this->metadata->getConstraintsFk($v->table) as $v1) { if ($v1->getReferencedTableName() == $tableGateway->getTable()) { $vConstraintChild = $v1; } if (in_array($v1->getReferencedTableName(), $vTable)) { $vConstraint = $v1; } } if (! isset($vConstraintChild, $vConstraint)) { continue; } $vLabel = $v->table; if (isset($configTable, $configTable[$v->table]->label)) { $vLabel = $configTable[$v->table]->label; } $vNode = [ 'type' => $v->type, 'table' => $v->table, 'label' => $vLabel, 'constraintChild' => $vConstraintChild, 'constraint' => $vConstraint ]; if (! empty($v->colSort)) { $vNode['colSort'] = $v->colSort; } $childMeta[] = $vNode; } } if (! empty($childMeta)) { $childFeature = $this->tableGateway->addSelectChildFeature(); $parentFeature = $this->tableGateway->getFeatureSet()->getFeatureByClassName( SelectParentFeature::class); foreach ($childMeta as $k => $v) { $childFeature->add(null, $v['table'], null, null, $this->tableGateway->getTable()); if (isset($v['colSort'])) { $childFeature->addSelectFilter( function (Select $select) use ($v) { $select->order($v['table'] . '.' . $v['colSort']); return $select; }); } $v['columnNameChild'] = $childFeature->getChildColumnName( $v['constraintChild']); $v['columnName'] = implode($this->columnSep, $v['constraint']->getColumns()) . $this->parentSep; $v['columnParent'] = $v; $childMeta[$k] = $v; } } $meta['cols'] = $colsMeta; $meta['child'] = $childMeta; $this->getView()->assign($out); return $meta; } function addAction() { $out = array(); $indexMeta = $this->getIndexMeta(); if (! $indexMeta['opt']['add']['enable']) { $this->forward('Error', 'error403'); return false; } $out['meta'] = $this->getSaveMeta('add'); $this->getView()->assign($out); } function editAction() { $out = array(); $indexMeta = $this->getIndexMeta(); if (! $indexMeta['opt']['edit']['enable']) { $this->forward('Error', 'error403'); return false; } $out['meta'] = $this->getSaveMeta('edit'); $data = $this->getRequest()->getQuery('data', []); $row = $this->tableGateway->select($this->getPrimaryData($data)) ->current(); if (! isset($row)) { $this->forward('Error', 'error404'); return false; } $out['row'] = $row; $this->getView()->assign($out); } protected function getDetailMeta() { return $this->getSaveMeta('detail'); } protected function getPrimaryData($data) { $primary = $this->metadata->getConstraintPrimaryKey( $this->tableGateway->getTable()) ->getColumns(); array_walk($primary, function (&$v) { $v = $this->tableGateway->getTable() . $this->tableGateway->getAdapter() ->getPlatform() ->getIdentifierSeparator() . $v; }); if (count($primary) === count($data)) { return array_combine($primary, $data); } } function detailAction() { $out = array(); $out['meta'] = $this->getDetailMeta(); $data = $this->getRequest()->getQuery('data', []); $row = $this->tableGateway->select($this->getPrimaryData($data)) ->current(); if (! isset($row)) { $this->forward('Error', 'error404'); return false; } $out['row'] = $row; $this->getView()->assign($out); } }<file_sep>/app-api/src/middleware.php <?php use Slim\Http\Request; use Slim\Http\Response; // CORS app_api()->add( function (Request $request, Response $response, $next) { $response = $next($request, $response); $origin = $request->getServerParam('HTTP_ORIGIN'); $map = [ $origin ]; if (in_array($origin, $map)) { $response = $response->withHeader('Access-Control-Allow-Origin', $origin); } else { return $response; } $response = $response->withHeader('Access-Control-Allow-Headers', 'Content-Type') ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS') ->withHeader('Access-Control-Allow-Credentials', 'true') ->withHeader('Access-Control-Max-Age', 86400 * 30); return $response; }); // default response app_api()->add( function (Request $request, Response $response, $next) { $response = $response->withStatus(500); $response = $next($request, $response); return $response; });<file_sep>/app-api/src/settings.php <?php use Yaf\Application; $config = [ 'settings' => [ 'displayErrorDetails' => ini_get('display_errors'), // Monolog settings 'logger' => [ 'name' => 'api', 'path' => isset($_ENV['docker']) ? 'php://stdout' : Application::app()->getAppDirectory() . '/../logs/api-' . date('Y-m-d') . '.log', 'level' => \Monolog\Logger::DEBUG ] ] ]; if (Config::isDev()) { $config['settings']['addContentLengthHeader'] = false; $config['settings']['logger']['level'] = Monolog\Logger::WARNING; } return $config;<file_sep>/library/Api.php <?php use Slim\Http\Request; use Slim\Http\Response; use Ares333\Yaf\Tool\Singleton; class Api { use Singleton; protected $container; function __invoke(Request $request, Response $response, $args) { $this->container = app_api()->getContainer(); if (! method_exists($this, strtolower($request->getMethod()))) { return $response->withStatus(501); } return $this->{strtolower($request->getMethod())}($request, $response, $args); } }<file_sep>/app-api/src/routes.php <?php use Slim\Http\Request; use Slim\Http\Response; use Yaf\Application; spl_autoload_register( function ($name) { if (0 === strpos($name, 'Api\\')) { $path = explode('\\', $name); array_shift($path); $version = app_api()->getContainer()->has('version') ? app_api()->getContainer()->get( 'version') . '/' : ''; $path = implode('/', $path) . '.php'; $file = __DIR__ . '/api/' . $version . $path; if (is_file($file)) { require_once $file; } } }); app_api()->group('/api', function () { $call = function (Request $request, Response $response, $args) { $class = explode('/', $args['_class']); unset($args['_class']); array_unshift($class, 'Api'); array_walk($class, function (&$v) { $v = ucfirst($v); }); $class = implode('\\', $class); if (! class_exists($class)) { return $response->withStatus(404); } return call_user_func($class::getInstance(), $request, $response, $args); }; app_api()->options('/{path:.*}', function (Request $request, $response, $args) use ($call) { return $response->withStatus(200); }); $methods = [ 'POST', 'DELETE', 'PUT', 'PATCH', 'GET' ]; app_api()->map($methods, '/{_class:(?:admin)\/table}/{tableName}[{primaryData:\/.+}]', function (Request $request, $response, $args) use ($call) { if (isset($args['primaryData'])) { $args['primaryData'] = explode('/', ltrim($args['primaryData'], '/')); } $dir = Application::app()->getAppDirectory() . '/../app-api/src/api'; foreach (explode('/', $args['_class']) as $v) { $dir .= '/' . ucfirst($v); } if (is_file($dir . '/' . ucfirst($args['tableName']) . '.php')) { $args['_class'] .= '/' . $args['tableName']; } return $call($request, $response, $args); }); app_api()->map($methods, '/{_class:.*}', function (Request $request, $response, $args) use ($call) { preg_match('/(^|\/)v\d+\.\d+\.\d+\//', $args['_class'], $match); if (count($match) == 2) { app_api()->getContainer()['version'] = trim($match[0], '/'); $args['_class'] = str_replace($match[0], '', $args['_class']); } return $call($request, $response, $args); }); });<file_sep>/app/conf/admin/table/adminUserIdType/index.ini [product] cols.0.column=id cols.2.column=name <file_sep>/public/_assets/common/js/api.js var _api = { urlOrigin:'', completeDefault:undefined, settings:{ headers : { }, contentType: "application/json", xhrFields:{ withCredentials: true } }, request:function (method,url,data,cb,requestSettings){ var $this=this if('function'==typeof(data)){ requestSettings=cb cb=data data=undefined } if(null==url.match(/^https?:\/\//)){ url = $this.urlOrigin.replace(/\/$/,'') +'/'+ url.replace(/^\//,'') } var settings = { url : url, method : method, complete : function( jqXHR, textStatus ){ var data=jqXHR.responseText var type=jqXHR.getResponseHeader('Content-Type') if(null!=type && type.match(/application\/json/i)){ try { data=JSON.parse(data); } catch(e) { console.log(e) } } if(false!==cb(jqXHR.status,data,jqXHR) && undefined!==$this.completeDefault){ $this.completeDefault(jqXHR.status,data,jqXHR) } } } var settingsDefault=JSON.parse(JSON.stringify(this.settings)) settings=$.extend(settingsDefault,settings) if(undefined!=requestSettings){ settings=$.extend(settings,requestSettings) } if(settings.contentType=='application/json'){ if('GET'==method && data!=undefined){ data={ q:JSON.stringify(data) } }else{ data=JSON.stringify(data) } } settings.data=data $.ajax(settings) }, get:function(url,data,cb,settings){ this.request('GET',url,data,cb,settings) }, post:function(url,data,cb,settings){ this.request('POST',url,data,cb,settings) }, patch:function(url,data,cb,settings){ this.request('PATCH',url,data,cb,settings) }, delete:function(url,data,cb,settings){ this.request('DELETE',url,data,cb,settings) }, put:function(url,data,cb,settings){ this.request('PUT',url,data,cb,settings) } }<file_sep>/library/Session/SaveHandler/DbTableGateway.php <?php namespace Session\SaveHandler; use Zend\Session\SaveHandler\DbTableGateway as Base; class DbTableGateway extends Base { public $onAfterWrite; /** * * {@inheritdoc} * * @see \Zend\Session\SaveHandler\DbTableGateway::write() */ function write($id, $data) { $res = parent::write($id, $data); if (isset($this->onAfterWrite)) { call_user_func($this->onAfterWrite, $id, $data); } return $res; } /** * * @return \Zend\Db\TableGateway\TableGateway */ function getTableGateway() { return $this->tableGateway; } }<file_sep>/library/Db/TableGateway.php <?php namespace Db; use Ares333\Yaf\Zend\Db\TableGateway\TableGateway as Base; use Ares333\Yaf\Tool\Singleton; use Db\Metadata\Source\MysqlMetadata; use Db\TableGateway\Feature\MetadataFeature; use Db\TableGateway\Feature\Mysql\SelectParentFeature; use Db\TableGateway\Feature\Mysql\SelectChildFeature; use Db\TableGateway\Feature\Mysql\DeleteFeature; use Db\TableGateway\Feature\Mysql\SaveFeature; use Ares333\Yaf\Zend\Db\TableGateway\Feature\Mysql\SaveChildFeature; class TableGateway extends Base { use Singleton; protected $metadata; function __construct($table, $adapter = null, $features = null) { if (! isset($adapter)) { $adapter = Adapter::getInstance(); } parent::__construct($table, $adapter, $features); $this->metadata = MysqlMetadata::getInstance($adapter); $this->getFeatureSet()->addFeature(new MetadataFeature($this->metadata)); $this->getFeatureSet()->addFeature(new SaveFeature($this->metadata)); } function getMetadata() { return $this->metadata; } function addSelectParentFeature() { $feature = $this->getFeatureSet()->getFeatureByClassName( SelectParentFeature::class); if (false === $feature) { if (false !== $this->getFeatureSet()->getFeatureByClassName( SelectChildFeature::class)) { user_error( 'select parent can not be added because select child feature has already exist', E_USER_ERROR); } $feature = new SelectParentFeature($this->metadata); $this->getFeatureSet()->addFeature($feature); } return $feature; } function addSelectChildFeature() { $feature = $this->getFeatureSet()->getFeatureByClassName( SelectChildFeature::class); if (false === $feature) { $feature = new SelectChildFeature($this->metadata); $this->getFeatureSet()->addFeature($feature); } return $feature; } function addDeleteFeature() { $feature = $this->getFeatureSet()->getFeatureByClassName( DeleteFeature::class); if (false === $feature) { $feature = new DeleteFeature($this->metadata); $this->getFeatureSet()->addFeature($feature); } return $feature; } function addSaveChildFeature() { $feature = $this->getFeatureSet()->getFeatureByClassName( SaveChildFeature::class); if (false === $feature) { $feature = new SaveChildFeature($this->metadata); $this->getFeatureSet()->addFeature($feature); } return $feature; } }<file_sep>/app-api/src/api/Admin/Table/Files.php <?php namespace Api\Admin\Table; use Slim\Http\Response; use Slim\Http\Request; use Api\Admin; use Uploader\File as Uploader; class Files extends Admin { function post(Request $request, Response $response, $args) { $uploader = Uploader::getInstance(); $res = $uploader->uploadPost(key($request->getUploadedFiles())); return $response->withStatus(200)->withJson($res); } }<file_sep>/app-api/src/api/Admin/User/Signin/Captcha.php <?php namespace Api\Admin\User\Signin; use Slim\Http\Response; use Slim\Http\Request; use Captcha\Image; use Api\Admin; class Captcha extends Admin { function get(Request $request, Response $response) { $captcha = Image::getInstance(); $captcha->getSession()->setExpirationHops(1); $res = array(); $res['id'] = $captcha->generate(); $res['url'] = $captcha->getImgUrl() . $res['id'] . $captcha->getSuffix(); return $response->withStatus(200)->withJson($res); } }<file_sep>/app-api/src/dependencies.php <?php // DIC configuration $container = app_api()->getContainer(); // monolog $container['logger'] = function ($c) { $settings = $c->get('settings')['logger']; $logger = new Monolog\Logger($settings['name']); $logger->pushProcessor(new Monolog\Processor\UidProcessor()); $logger->pushHandler( new Monolog\Handler\StreamHandler($settings['path'], $settings['level'])); return $logger; };<file_sep>/library/Db/TableGateway/Feature/MetadataFeature.php <?php namespace Db\TableGateway\Feature; use Ares333\Yaf\Zend\Db\TableGateway\Feature\MetadataFeature as Base; use Ares333\Yaf\Tool\Singleton; class MetadataFeature extends Base { public static $updateDeleteColumn = 'isDelete'; use Singleton; }<file_sep>/app/controllers/Admin.php <?php use Yaf\Controller_Abstract; class AdminController extends Controller_Abstract { protected $modulePathName; function init() { $this->modulePathName = lcfirst( $this->getRequest()->getControllerName()); } function indexAction() { $this->redirect('/' . $this->modulePathName . '_index'); return false; } function signinAction() { $userClass = '\\' . ucfirst($this->modulePathName) . '\User'; $user = $userClass::getInstance(); if ($user->isLogin()) { $this->redirect('/' . $this->modulePathName . '_index'); return false; } } function signoutAction() { $userClass = '\\' . ucfirst($this->modulePathName) . '\User'; $user = $userClass::getInstance(); $user->logout(); $this->redirect('/'); return false; } }<file_sep>/app-api/src/api/Admin/Table.php <?php namespace Api\Admin; use Slim\Http\Response; use Slim\Http\Request; use Api\Admin; use Db\TableGateway; use Db\Metadata\Source\MysqlMetadata; use Db\Adapter; class Table extends Admin { protected $adapter; protected $metadata; function __invoke(Request $request, Response $response, $args) { if (! isset($this->adapter)) { $this->adapter = Adapter::getInstance(); } $this->metadata = MysqlMetadata::getInstance($this->adapter); return parent::__invoke($request, $response, $args); } function get(Request $request, Response $response, $args) { $limitMax = 32; $params = $request->getParam('q', '[]'); $params = json_decode($params, true); if (isset($params['offset'])) { settype($params['offset'], 'int'); } else { $params['offset'] = 0; } if (isset($params['limit'])) { settype($params['limit'], 'int'); } else { $params['limit'] = 8; } if ($params['limit'] > $limitMax) { $params['limit'] = $limitMax; } if (! isset($params['where'])) { $params['where'] = []; } $tableGateway = TableGateway::getInstance($args['tableName'], $this->adapter); $selectParentFeature = $tableGateway->addSelectParentFeature(); $select = $tableGateway->getSql() ->select() ->offset($params['offset']) ->limit($params['limit']); foreach ($params['where'] as $k => $v) { if (isset($v)) { $select->where->expression($k, explode($selectParentFeature->getColumnSep(), $v)); } else { $select->where->literal($k); } } $list = $tableGateway->selectWith($select)->toArray(); $total = $tableGateway->countWith($select); return $response->withStatus(200)->withJson( [ 'list' => $list, 'total' => $total ]); } function post(Request $request, Response $response, $args) { $data = $request->getParam('data', []); $tableGateway = TableGateway::getInstance($args['tableName'], $this->adapter); $configIndex = \Config::get( self::$modulePathName . '/table/' . $tableGateway->getTable() . '/index.ini'); if (isset($configIndex->opt->add->enable) && ! $configIndex->opt->add->enable) { return $response->withStatus(403); } // check empty $colsNameAutoInc = []; foreach ($this->metadata->getColumnsAutoIncrement( $tableGateway->getTable()) as $v) { $colsNameAutoInc[] = $v->getName(); } $colsRequire = []; foreach ($this->metadata->getColumns($tableGateway->getTable()) as $v) { // virtual if ($v->isVirtual) { unset($data[$v->getName()]); continue; } // required if ($v->isNullable() || in_array($v->getName(), $colsNameAutoInc)) { continue; } if (null !== $v->getColumnDefault()) { continue; } $colsRequire[] = $v->getName(); } $error = []; foreach (array_keys(array_diff_key(array_flip($colsRequire), $data)) as $v) { $error[] = $v; } if (! empty($error)) { return $response->withStatus(260, 'Incomplete')->withJson($error); } // check unique $unique = $this->metadata->getConstraintsUnique($args['tableName']); if (empty($colsNameAutoInc)) { $unique[] = $this->metadata->getConstraintPrimaryKey( $args['tableName']); } if (! empty($unique)) { foreach ($unique as $v) { $where = []; foreach ($v->getColumns() as $v1) { $where[$v1] = $data[$v1]; } $select = $tableGateway->getSql() ->select() ->where($where); if ($tableGateway->countWith($select) > 0) { return $response->withStatus(261, 'Duplicate')->withJson( array_keys($where)); } } } // password $file = self::$modulePathName . '/table/' . $tableGateway->getTable() . '/save.ini'; if (is_file($file)) { $config = \Config::get($file); $configCols = $config->get('cols'); foreach ($data as $k => $v) { $vConfig = $configCols->get($k); if (isset($vConfig->type)) { switch ($vConfig->type) { case 'password': $v = password_hash($v, PASSWORD_DEFAULT); break; } } $data[$k] = $v; } } $tableGateway->insert($data); return $response->withStatus(204); } function patch(Request $request, Response $response, $args) { $data = $request->getParam('data', []); $tableGateway = TableGateway::getInstance($args['tableName'], $this->adapter); $saveChildFeature = $tableGateway->addSaveChildFeature(); $configIndex = \Config::get( self::$modulePathName . '/table/' . $tableGateway->getTable() . '/index.ini'); if (isset($configIndex->opt->edit->enable) && ! $configIndex->opt->edit->enable) { return $response->withStatus(403); } $config = \Config::get( self::$modulePathName . '/table/' . $tableGateway->getTable() . '/save.ini'); // clean if (isset($config) && isset($config->cols)) { foreach ($config->cols as $k => $v) { if ($v->readonly || $v->plaintext) { unset($data[$k]); } } } foreach ($this->metadata->getColumns($tableGateway->getTable()) as $v) { if ($v->isVirtual) { unset($data[$v->getName()]); continue; } } $primary = $this->metadata->getConstraintPrimaryKey( $tableGateway->getTable()); $primaryData = $args['primaryData'] ?? []; if (count($primary->getColumns()) !== count($primaryData)) { return $response->withStatus(422); } $dataPrimary = array_combine($primary->getColumns(), $primaryData); // check unique $unique = $this->metadata->getConstraintsUnique($args['tableName']); $dataPrimaryNew = array_intersect_key($data, array_flip($primary->getColumns())); if ($dataPrimaryNew != [] && $dataPrimary != $dataPrimaryNew) { $unique[] = $primary; } foreach ($unique as $v) { $select = $tableGateway->getSql()->select(); $vWhere = $select->where; foreach ($v->getColumns() as $v1) { $vWhere->equalTo($v1, $data[$v1]); } foreach ($dataPrimary as $k1 => $v1) { $vWhere->notEqualTo($k1, $v1); } $select = $tableGateway->getSql() ->select() ->where($vWhere); if ($tableGateway->countWith($select) > 0) { return $response->withStatus(261, 'Duplicate')->withJson( $v->getColumns()); } } // check row $row = $tableGateway->select($dataPrimary)->current(); if (! isset($row)) { return $response->withStatus(260, 'Not found'); } // password if (isset($config)) { $configCols = $config->get('cols'); foreach ($data as $k => $v) { $vConfig = $configCols->get($k); if (isset($vConfig->type)) { switch ($vConfig->type) { case 'password': if ($v !== $row[$k]) { $v = password_hash($v, PASSWORD_DEFAULT); } break; } } $data[$k] = $v; } } // child image if (isset($config, $config->child)) { foreach ($config->child as $v) { if ($v->type == 'image') { $vConstraintChild = null; foreach ($this->metadata->getConstraintsFk($v->table) as $v1) { if ($v1->getReferencedTableName() == $tableGateway->getTable()) { $vConstraintChild = $v1; } } if (isset($vConstraintChild)) { $vColumnName = $saveChildFeature->getChildColumnName( $vConstraintChild); if (isset($data[$vColumnName])) { foreach ($data[$vColumnName] as $k1 => $v1) { if (! empty($v->colSort)) { $v1[$v->colSort] = $k1; } $data[$vColumnName][$k1] = $v1; } } } } } } $tableGateway->update($data, $dataPrimary); return $response->withStatus(204); } function delete(Request $request, Response $response, $args) { $primaryData = $args['primaryData'] ?? []; $tableGateway = TableGateway::getInstance($args['tableName'], $this->adapter); $tableGateway->addDeleteFeature(); $configIndex = \Config::get( self::$modulePathName . '/table/' . $tableGateway->getTable() . '/index.ini'); if (isset($configIndex->opt->delete->enable) && ! $configIndex->opt->delete->enable) { return $response->withStatus(403); } $primary = $this->metadata->getConstraintPrimaryKey( $tableGateway->getTable()) ->getColumns(); if (count($primary) !== count($primaryData)) { return $response->withStatus(422); } $dataPrimary = array_combine($primary, $primaryData); $tableGateway->delete($dataPrimary); return $response->withStatus(204); } }<file_sep>/README.md ## 安装 ``` composer create-project ares333/yaf-skeleton myProject ``` <file_sep>/app-api/public/index.php <?php /** * * @return \Slim\App */ function app_api() { static $instance; if (! isset($instance)) { $settings = require __DIR__ . '/../src/settings.php'; if (PHP_SAPI == 'cli') { global $argv; $env = []; if (isset($argv[2])) { $env['REQUEST_METHOD'] = $argv[2]; } $env['REQUEST_URI'] = $argv[1]; $settings['environment'] = \Slim\Http\Environment::mock($env); } $instance = new \Slim\App($settings); } return $instance; } // Set up dependencies require __DIR__ . '/../src/dependencies.php'; // Register middleware require __DIR__ . '/../src/middleware.php'; // Register routes require __DIR__ . '/../src/routes.php'; // Run app app_api()->run();<file_sep>/doc/api/readme.txt HTTP状态码详细信息见:https://zh.wikipedia.org/wiki/HTTP状态码 服务端默认状态码500,每个API需要显式指定。 2xx 200-208,226 HTTP预定义状态码 <260 全局状态码 260-299 接口自定义状态码 接口使用的全局状态码: 200 请求成功 201 资源已创建 204 请求成功并且无返回内容 401 未登陆 403 未授权或禁止访问 404 资源未找到 422 参数错误(https://tools.ietf.org/html/rfc4918#section-11.2)<file_sep>/library/Db/Metadata/Source/MysqlMetadata.php <?php namespace Db\Metadata\Source; use Ares333\Yaf\Tool\Singleton; use Cache\Storage\Adapter\Memcached; use Ares333\Yaf\Zend\Cache\Service\MysqlMetadata as Base; use Db\Adapter; class MysqlMetadata extends Base { use Singleton; function __construct($adapter = null) { if (! isset($adapter)) { $adapter = Adapter::getInstance(); } $storage = Memcached::getInstance( [ 'namespace' => 'metadata', 'ttl' => 86400 ]); parent::__construct($adapter, $storage); } }<file_sep>/library/HTMLPurifier.php <?php use HTMLPurifier as Base; use Ares333\Yaf\Tool\Singleton; class HTMLPurifier extends Base { use Singleton; }<file_sep>/public/_assets/common/js/default.js $(function () { $('[data-toggle="tooltip"]').tooltip() }) var _round = function (val, precision) { return Math.round(Math.round(val * Math.pow(10, (precision || 0) + 1)) / 10) / Math.pow(10, (precision || 0)); } function _base64encode(str, encoding = 'utf-8') { var bytes = new (TextEncoder || TextEncoderLite)(encoding).encode(str); return base64js.fromByteArray(bytes); } function _base64decode(str, encoding = 'utf-8') { var bytes = base64js.toByteArray(str); return new (TextDecoder || TextDecoderLite)(encoding).decode(bytes); }<file_sep>/app/conf/admin/table/user/detail.ini [product] cols.avatar.type=image<file_sep>/app/plugins/XHProf.php <?php use Yaf\Request_Abstract; use Yaf\Response_Abstract; use Yaf\Plugin_Abstract; class XHProfPlugin extends Plugin_Abstract { function dispatchLoopShutdown(Request_Abstract $request, Response_Abstract $response) { XHProf::getInstance()->replace($response); } }<file_sep>/library/Uploader/File.php <?php namespace Uploader; use Yaf\Application; use Ares333\Yaf\Tool\Uploader\File as Base; use Db\Adapter; use Ares333\Yaf\Tool\Singleton; use Ares333\Yaf\Helper\File as Helper; class File extends Base { use Singleton; function __construct() { $config = Application::app()->getConfig()->uploader->toArray(); if (! Helper::isAbsolute($config['dir'])) { $config['dir'] = Application::app()->getAppDirectory() . '/' . $config['dir']; } parent::__construct( function () { return Adapter::getInstance()->getDriver() ->getConnection() ->getResource(); }, $config['dir'], $config['url']); } }<file_sep>/app/conf/admin/table/house/index.ini [product] where.1.type=date where.1.column="house.createTime>=?" where.1.label=创建日期开始 where.12.type=date where.12.column="house.createTime<=?" where.12.label=创建日期结束 where.14.table=country where.14.required=yes where.20.table=city cols.0.column=id cols.5.column=decorationId@ name cols.11.column=title cols.12.column=buildYear cols.14.column=createTime order.default=house.createTime desc order.columns.0=house.createTime<file_sep>/app-api/src/api/Admin/User/Signin.php <?php namespace Api\Admin\User; use Slim\Http\Response; use Slim\Http\Request; use Db\TableGateway; use Api\Admin; use Captcha\Image; class Signin extends Admin { function post(Request $request, Response $response) { $params = $request->getParams(); foreach ([ 'username', 'password', 'captchaId', 'captchaInput', 'remember' ] as $v) { if (! isset($params[$v])) { $params[$v] = ''; } } $isNeed = Signin\Captcha\IsNeed::getInstance(); $captcha = Image::getInstance(); if ($isNeed->check($params['username'])) { $captcha = Image::getInstance(); if (! $captcha->isValid( [ 'id' => $params['captchaId'], 'input' => $params['captchaInput'] ])) { return $response->withStatus(260, 'Captcha error'); } } $tableUserId = TableGateway::getInstance(self::$modulePathName . 'UserId'); $typeOrder = [ 1, 2, 3 ]; if (false !== strpos($params['username'], '@')) { array_unshift($typeOrder, 1); } if (preg_match('/^1\d{10}$/', $params['username'])) { array_unshift($typeOrder, 2); } $typeOrder = array_unique($typeOrder, SORT_REGULAR); $select = $tableUserId->getSql()->select(); foreach ($typeOrder as $v) { $select->where->nest() ->equalTo('typeId', $v) ->equalTo('value', $params['username']) ->unnest()->or; } $rowUserId = $tableUserId->selectWith($select)->current(); if (! isset($rowUserId)) { return $response->withStatus(261, 'User not found'); } $passwordType = [ 1, 2, 3 ]; if (in_array((int) $rowUserId->typeId, $passwordType)) { $tableUser = TableGateway::getInstance(self::$modulePathName . 'User'); $rowUser = $tableUser->select( [ 'id' => $rowUserId->userId ])->current(); if (! password_verify($params['password'], $rowUser->password)) { $isNeed->fail($params['username']); if ($isNeed->check($params['username'])) { return $response->withStatus(263, 'Password error'); } else { return $response->withStatus(264, 'Password error'); } } } else { // oauth return; } $userClass = '\\' . ucfirst(self::$modulePathName) . '\User'; $user = $userClass::getInstance(); $remember = isset($params['remember']) && $params['remember'] === 'yes'; if ($user->login($rowUser->id, $remember)) { $isNeed->success($params['username']); return $response->withStatus(204); } } }<file_sep>/app-api/src/api/Admin/User/Signin/Captcha/IsNeed.php <?php namespace Api\Admin\User\Signin\Captcha; use Slim\Http\Response; use Slim\Http\Request; use Db\TableGateway; use Zend\Db\Sql\Expression; use Api\Admin; class IsNeed extends Admin { function get(Request $request, Response $response) { $params = json_decode($request->getQueryParam('q'), true); if (! isset($params['name'])) { return $response->withStatus(422); } if ($this->check($params['name'])) { return $response->withStatus(204); } else { return $response->withStatus(260, 'No need'); } } protected function getTable() { $table = TableGateway::getInstance(self::$modulePathName . 'LoginTry'); return $table; } function fail($name) { $table = $this->getTable(); $table->insertDuplicate( [ 'name' => $name, 'failNum' => 1 ], [ 'failNum' => new Expression('failNum+1') ]); } function success($name) { $this->getTable()->delete([ 'name' => $name ]); } function check($name) { $table = $this->getTable(); $row = $table->select([ 'name' => $name ])->current(); if (isset($row) && $row->failNum >= 3) { return true; } return false; } }<file_sep>/library/Uploader/Image.php <?php namespace Uploader; use Yaf\Application; use Ares333\Yaf\Tool\Uploader\Image as Base; use Db\Adapter; use Ares333\Yaf\Helper\File; use Ares333\Yaf\Tool\Singleton; class Image extends Base { use Singleton; function __construct() { $config = Application::app()->getConfig()->uploader->image->toArray(); if (! File::isAbsolute($config['dir'])) { $config['dir'] = Application::app()->getAppDirectory() . '/' . $config['dir']; } parent::__construct( function () { return Adapter::getInstance()->getDriver() ->getConnection() ->getResource(); }, $config['dir'], $config['url']); $this->setExtensions( array( 'jpg', 'jpeg', 'png', 'gif', 'svg' )); $this->setResize(1920 * 2, 1080 * 2); } }<file_sep>/library/XHProf.php <?php use Ares333\Yaf\Tool\XHProf as Base; use Ares333\Yaf\Tool\Singleton; use Yaf\Application; use Ares333\Yaf\Helper\File; use Yaf\Dispatcher; class XHProf extends Base { use Singleton; function __construct($path = null, $domain = null, $auto = null) { $xhprof = Application::app()->getConfig() ->get('xhprof') ->toArray(); if (! isset($path)) { if (! empty($xhprof['path'])) { if (! File::isAbsolute($xhprof['path'])) { $xhprof['path'] = Application::app()->getAppDirectory() . '/' . $xhprof['path']; } parent::__construct($xhprof['path'], $xhprof['domain'], $auto); } } } function replace($response) { if ($this->isEnabled()) { $body = $response->getBody(); $url = $this->run(); $body = str_replace('{$XHProfLink}', $url, $body); $response->setBody($body); } } function isEnabled() { if (Config::isDev() && is_dir($this->path)) { $request = Dispatcher::getInstance()->getRequest(); return null !== $request->getQuery('_xhprof'); } } }<file_sep>/library/Db/TableGateway/Feature/Mysql/DeleteFeature.php <?php namespace Db\TableGateway\Feature\Mysql; use Ares333\Yaf\Zend\Db\TableGateway\Feature\Mysql\DeleteFeature as Base; use Db\Metadata\Source\MysqlMetadata; use Db\TableGateway\Feature\MetadataFeature; class DeleteFeature extends Base { function __construct($metadata = null) { if (! isset($metadata)) { $metadata = MysqlMetadata::getInstance(); } parent::__construct($metadata); $this->updateDeleteColumn = MetadataFeature::$updateDeleteColumn; } }<file_sep>/app-api/src/api/Admin/Table/Images.php <?php namespace Api\Admin\Table; use Slim\Http\Response; use Slim\Http\Request; use Api\Admin; use Uploader\Image as Uploader; class Images extends Admin { function post(Request $request, Response $response, $args) { $uploader = Uploader::getInstance(); $res = $uploader->uploadPost(key($request->getUploadedFiles())); if ($request->getQueryParam('source') == 'ckeditor') { return $this->ckEditor($request, $response, $args, $res); } return $response->withStatus(200)->withJson($res); } protected function ckEditor(Request $request, Response $response, $args, $res) { // Check the $_FILES array and save the file. Assign the correct path to a variable ($url). if ($res['code'] == Uploader::ERR_OK) { $url = $res['value']->url . '?img' . $res['value']->id; $message = ''; } else { $url = ''; // Usually you will only assign something here if the file could not be uploaded. $message = $res['message']; } if ('json' == $request->getQueryParam('responseType')) { $body = []; if ($res['code'] == Uploader::ERR_OK) { $body['uploaded'] = 1; $body['fileName'] = $res['value']->name; $body['url'] = $url; } else { $body['uploaded'] = 0; $body['error'] = [ 'message' => $message ]; } $response = $response->withJson($body); } else { $query = $request->getQueryParams(); // Required: anonymous function reference number as explained above. $funcNum = $query['CKEditorFuncNum']; // Optional: instance name (might be used to load a specific configuration file or anything else). $CKEditor = $query['CKEditor']; // Optional: might be used to provide localized messages. $langCode = $query['langCode']; // Optional: compare it with the value of `ckCsrfToken` sent in a cookie to protect your server side uploader against CSRF. // Available since CKEditor 4.5.6. // $token = $_POST['ckCsrfToken']; $response->getBody()->write( "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$message');</script>"); } return $response->withStatus(200); } }<file_sep>/app/conf/admin/table/adminUserId/index.ini [product] cols.0.column=id cols.1.column=typeId cols.2.column=value cols.3.column=userId cols.5.column=createTime<file_sep>/library/Db/Adapter.php <?php namespace Db; use Zend\Db\Adapter\Adapter as Base; use Ares333\Yaf\Zend\Db\Adapter\Platform\Mysql; use Ares333\Yaf\Tool\Singleton; use Yaf\Application; class Adapter extends Base { use Singleton; function __construct($name = null) { if (! isset($name)) { $name = 'default'; } $driver = Application::app()->getConfig()->get('db'); $driver = $driver->get($name); if (! isset($driver)) { user_error('database not found', E_USER_ERROR); } $driver = $driver->toArray(); $driver['driver_options'] = [ \PDO::ATTR_EMULATE_PREPARES => false, \PDO::MYSQL_ATTR_LOCAL_INFILE => true, \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET time_zone = "' . date('P') . '"' ]; parent::__construct($driver); } protected function createPlatform(array $parameters) { return new Mysql($this->driver); } }<file_sep>/app/plugins/View.php <?php use Yaf\Request_Abstract; use Yaf\Response_Abstract; use Yaf\Plugin_Abstract; use Yaf\Dispatcher; use Ares333\Yaf\Helper\Http; use Yaf\Application; class ViewPlugin extends Plugin_Abstract { function dispatchLoopStartup(Request_Abstract $request, Response_Abstract $response) { $controllerName = $request->getControllerName(); $actionName = $request->getActionName(); $dispatcher = Dispatcher::getInstance(); $dispatcher->enableView(); $view = View::getInstance(); $out = array(); $out['_appName'] = Application::app()->getConfig() ->get('app') ->get('name'); $out['_isMobile'] = Http::isMobile(); $out['_controllerName'] = $controllerName; $out['_actionName'] = $actionName; $out['_assetsUrl'] = Application::app()->getConfig() ->get('assets') ->get('url'); $view->assign($out); Dispatcher::getInstance()->setView($view); } }<file_sep>/app/controllers/Admin/Index.php <?php use Yaf\Controller_Abstract; use Yaf\Application; class Admin_IndexController extends Controller_Abstract { function indexAction() {} /** * * @return boolean */ function svnupAction() { $out = []; $out['msg'] = ''; $encoding = 'export LC_ALL=en_US.UTF-8;export LANG=en_US.UTF-8;export LANGUAGE=en_US.UTF-8;'; $appPath = Application::app()->getAppDirectory(); $path = $appPath . '/../data/svn/admin'; $dir = $this->getRequest()->getQuery('dir', ''); $type = $this->getRequest()->getQuery('type'); $cmd = '/usr/bin/svn up --config-dir=' . dirname($appPath) . '/data/svn/admin ' . dirname($appPath) . '/' . $dir . ' 2>&1'; if ($type == 'dry') { $out['msg'] = 'sudo -u apache ' . $cmd; } elseif ($type == 'exec') { $out['msg'] = shell_exec($encoding . $cmd); } $this->getView()->assign($out); } }<file_sep>/library/Sms.php <?php use Ares333\Yaf\Tool\Sms as Base; use Db\TableGateway; class Sms extends Base { private $sender; function __construct() { $tableSms = TableGateway::getInstance('sms'); $getPdo = function () use ($tableSms) { return $tableSms->getAdapter() ->getDriver() ->getConnection() ->getResource(); }; parent::__construct($getPdo, $tableSms->getTable(), 'aws'); } /** * * @param string $mobile * @param string $message * @return array */ protected function doSend($mobile, $message) { $res = $this->sender->publish( [ 'Message' => $message, 'PhoneNumber' => $mobile ]); $return = array(); if ($res['@metadata']['statusCode'] === 200) { $return['status'] = true; } $return['message'] = json_encode($res->toArray()); return $return; } /** * * {@inheritdoc} * * @see \Ares333\YafLib\Tool\Sms::send() */ function send($mobile, $message, $ip = null, $type = null) { $message = '【I-HOUSE】' . $message; return parent::send($mobile, $message, $ip, $type); } }<file_sep>/library/Db/TableGateway/Feature/Mysql/SaveFeature.php <?php namespace Db\TableGateway\Feature\Mysql; use Db\Metadata\Source\MysqlMetadata; use Zend\Db\Sql\Update; use Db\TableGateway\Feature\MetadataFeature; use Zend\Db\Sql\Expression; use Ares333\Yaf\Zend\Db\TableGateway\Feature\Mysql\AbstractFeature; use Zend\Db\Sql\Insert; class SaveFeature extends AbstractFeature { function __construct($metadata = null) { if (! isset($metadata)) { $metadata = MysqlMetadata::getInstance(); } parent::__construct($metadata); $this->updateDeleteColumn = MetadataFeature::$updateDeleteColumn; } function dataFilter($data, $table) { $columns = $this->metadata->getColumns($table); foreach ($columns as $v) { // 如果mysql字段类型是int,php类型是bool,PDOStatement::execute()总是返回false并且不会触发相应Exception if ('int' == $v->getDataType() && array_key_exists($v->getName(), $data) && is_bool($data[$v->getName()])) { settype($data[$v->getName()], 'int'); } // XSS if (isset($data[$v->getName()]) && in_array($v->getDataType(), [ 'varchar', 'char', 'text' ])) { $data[$v->getName()] = \HTMLPurifier::getInstance()->purify( $data[$v->getName()]); } if (in_array($v->getDataType(), [ 'geometry', 'point' ]) && isset($data[$v->getName()])) { $data[$v->getName()] = new Expression( 'ST_GeomFromGeoJSON(\'' . $data[$v->getName()] . '\')'); } } return $data; } function preInsert(Insert $insert) { $state = $insert->getRawState(); $set = $this->dataFilter( array_combine($state['columns'], $state['values']), $state['table']); $insert->values($set); } function preUpdate(Update $update) { $state = $update->getRawState(); $set = $this->dataFilter($state['set'], $state['table']); $update->set($set); } }<file_sep>/library/Mail.php <?php use Ares333\Yaf\Tool\Singleton; class Mail extends PHPMailer { use Singleton; function __construct() { $this->isSMTP(); // Set mailer to use SMTP $this->Host = 'xxx'; // Specify main and backup SMTP servers $this->SMTPAuth = true; // Enable SMTP authentication $this->Username = 'xxx'; // SMTP username $this->Password = 'xxx'; // SMTP password $this->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted $this->Port = 465; // TCP port to connect to $this->CharSet = "utf-8"; $this->setFrom('xxx', 'xxx'); $this->isHTML(true); // Set email format to HTML } }<file_sep>/library/Cache/Storage/Adapter/Memcached.php <?php namespace Cache\Storage\Adapter; use Ares333\Yaf\Tool\Singleton; use Zend\Cache\StorageFactory; use Zend\Cache\Storage\Adapter\Memcached as Base; class Memcached extends Base { use Singleton; function __construct($options) { if (! isset($options['serversByName'])) { $options['serversByName'] = 'default'; } $options['lib_options'] = [ \Memcached::OPT_SERIALIZER => \Memcached::SERIALIZER_IGBINARY, \Memcached::OPT_DISTRIBUTION => \Memcached::DISTRIBUTION_CONSISTENT ]; parent::__construct($options); $this->addPlugin( StorageFactory::pluginFactory('exception_handler', [ 'throw_exceptions' => ini_get('display_errors') ])); } public function setOptions($options) { if (! $options instanceof MemcachedOptions) { $options = new MemcachedOptions($options); } return parent::setOptions($options); } }<file_sep>/app/conf/admin/table/houseImage/index.ini [product] where.1.column="houseImage.houseId=?" where.1.label=房屋ID order.default=houseImage.houseId asc order.columns.0=houseId<file_sep>/library/Cache/Storage/Adapter/MemcachedOptions.php <?php namespace Cache\Storage\Adapter; use Ares333\Yaf\Tool\Singleton; use Zend\Cache\Storage\Adapter\MemcachedOptions as Base; use Yaf\Application; class MemcachedOptions extends Base { use Singleton; function setServersByName($name) { $servers = Application::app()->getConfig() ->get('memcached') ->get($name); if (! isset($servers)) { user_error('memcached server not found', E_USER_ERROR); } $servers = explode(',', $servers); array_walk($servers, function (&$v) { $v = explode(':', $v); }); $this->setServers($servers); } }<file_sep>/library/Helper/Http.php <?php namespace Helper; use Ares333\Yaf\Helper\Http as Base; class Http extends Base { static function removeUrlQuery($url, $names) { $parse = parse_url($url); if (isset($parse['query'])) { if (is_string($names)) { $names = [ $names ]; } parse_str($parse['query'], $parse['query']); foreach ($names as $v) { unset($parse['query'][$v]); } $parse['query'] = http_build_query($parse['query']); } return self::buildUrl($parse); } }<file_sep>/app/conf/app.ini ;============================== ;PRODUCT ;============================== [product] yaf.directory=. yaf.dispatcher.throwException=yes yaf.dispatcher.catchException=yes yaf.system.use_spl_autoload=yes app.name=YAF-SKELETON db.default.driver=Pdo_Mysql db.default.hostname= db.default.username= db.default.password= db.default.database=yaf_skeleton db.default.charset=utf8mb4 assets.url=/_assets memcached.default=127.0.0.1:11211 php.display_errors=no php.log_errors=yes php.error_reporting=E_ALL php.error_log=../logs/php_error.log php.date.timezone=Asia/Shanghai xhprof.path= xhprof.domain= uploader.image.dir=../public/_upload/image uploader.image.url=/_upload/image ;============================== ;DEVELOPMENT ARES ;============================== [developmentAres:product] db.default.hostname=127.0.0.1 db.default.username=root db.default.password= php.display_errors=yes ;============================== ;DEVELOPMENT ARES COMPANY ;============================== [developmentAresCompany:product] db.default.hostname=192.168.87.109 db.default.username=root db.default.password=<PASSWORD> php.display_errors=yes<file_sep>/library/Admin/User.php <?php namespace Admin; use Ares333\Yaf\Tool\Singleton; use Zend\Session\Container; use Db\TableGateway; use Yaf\Dispatcher; use Db\Adapter; use Zend\Session\Exception\RuntimeException; /** * CREATE TABLE `adminUser` ( * `id` int(11) NOT NULL AUTO_INCREMENT, * `name` varchar(255) NOT NULL, * `password` varchar(255) DEFAULT NULL, * `createTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, * PRIMARY KEY (`id`) * ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; * * CREATE TABLE `adminUserId` ( * `id` int(11) NOT NULL AUTO_INCREMENT, * `typeId` int(11) NOT NULL, * `value` varchar(64) NOT NULL, * `userId` int(11) NOT NULL, * `createTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, * PRIMARY KEY (`id`), * UNIQUE KEY `typeId` (`typeId`,`value`) USING BTREE, * KEY `userId` (`userId`) USING BTREE, * CONSTRAINT `adminUserId_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `adminUser` (`id`) ON DELETE CASCADE, * CONSTRAINT `adminUserId_ibfk_2` FOREIGN KEY (`typeId`) REFERENCES `adminUserIdType` (`id`) ON DELETE CASCADE * ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; * * CREATE TABLE `adminUserIdType` ( * `id` int(11) NOT NULL AUTO_INCREMENT, * `name` varchar(16) NOT NULL, * PRIMARY KEY (`id`), * UNIQUE KEY `name` (`name`) * ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; * * CREATE TABLE `adminLoginTry` ( * `id` int(11) NOT NULL AUTO_INCREMENT, * `name` varchar(64) NOT NULL, * `failNum` int(11) NOT NULL, * `updateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, * PRIMARY KEY (`id`), * UNIQUE KEY `name` (`name`) * ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; */ class User { use Singleton; protected $session; protected $sessionLimit = 8; protected $ttl = 90 * 86400; function login($userId, bool $remember) { if (empty($userId)) { return false; } $session = $this->getSession(); if (! isset($session)) { return false; } $manager = $session->getManager(); if ($remember) { $manager->getConfig()->setOption('gc_maxlifetime', $this->ttl / 3); $manager->rememberMe($this->ttl); $name = $manager->getConfig()->getName(); $saveHandler = $manager->getSaveHandler(); $saveHandler->onAfterWrite = function ($id, $data) use ($userId, $name, $saveHandler) { $tableGateway = $saveHandler->getTableGateway(); $tableName = $tableGateway->getTable(); $limitTableGateway = $this->getLimitTableGateway(); $limitTableGateway->insert( [ 'id' => $id, 'name' => $name, 'userAgent' => Dispatcher::getInstance()->getRequest() ->getServer('HTTP_USER_AGENT'), 'userId' => $userId ]); $select = $limitTableGateway->getSql() ->select() ->columns( [ 'id', 'name' ]) ->join($tableName, $tableName . '.id=' . $limitTableGateway->getTable() . '.id and ' . $tableName . '.name=' . $limitTableGateway->getTable() . '.name', []) ->where( [ $limitTableGateway->getTable() . '.userId' => $userId ]) ->order($tableName . '.modified desc') ->offset($this->sessionLimit); $list = $limitTableGateway->selectWith($select)->toArray(); if (! empty($list)) { $where = $tableGateway->getSql()->delete()->where; foreach ($list as $v) { $where = $where->nest(); foreach ($v as $k1 => $v1) { $where = $where->equalTo($k1, $v1); } $where = $where->unnest(); $where = $where->or; } $tableGateway->delete($where); } }; } $session->userId = $userId; return true; } function getId() { $session = $this->getSession(); if (isset($session)) { return $session->userId; } } function isLogin() { $session = $this->getSession(); return isset($session->userId); } function logout() { $session = $this->getSession(); if (isset($session)) { $session->getManager()->destroy(); } } function getLimitTableGateway() { $adapter = Adapter::getInstance(); $sessionLimitTable = 'session' . explode('\\', get_class($this))[0]; $table = TableGateway::getInstance($sessionLimitTable, $adapter); return $table; } protected function getSession() { if (! isset($this->session)) { try { $this->session = new Container(__CLASS__); } catch (RuntimeException $e) { // may be session validation failed $this->logout(); } } return $this->session; } }<file_sep>/app/Bootstrap.php <?php use Yaf\Bootstrap_Abstract; use Yaf\Dispatcher; use Yaf\Loader; use Ares333\Yaf\Helper\Error; use Ares333\Yaf\Helper\Functions; use Ares333\Yaf\Plugin\PHPConfig; use Ares333\Yaf\Plugin\Cli; use Yaf\Route\Rewrite; class Bootstrap extends Bootstrap_Abstract { function _initAutoload(Dispatcher $dispatcher) { $dir = $dispatcher->getApplication()->getAppDirectory(); $libraryPath = $dir . '/../library'; Loader::getInstance($libraryPath, $libraryPath); Loader::import($dir . '/../vendor/autoload.php'); } function _initDebug(Dispatcher $dispatcher) { XHProf::getInstance(); new Functions(); Error::error2exception(); } function _initOutput(Dispatcher $dispatcher) { $dispatcher->returnResponse(false); } function _initPlugin(Dispatcher $dispatcher) { $dispatcher->registerPlugin(new PHPConfig()); $dispatcher->registerPlugin(new Cli()); $dispatcher->registerPlugin(new SessionPlugin()); $dispatcher->registerPlugin(new AdminPlugin()); $dispatcher->registerPlugin(new ViewPlugin()); $dispatcher->registerPlugin(new XHProfPlugin()); } function _initRoute(Dispatcher $dispatcher) { $router = $dispatcher->getRouter(); $jsConfigPath = array( '/_assets/common/js/config.js' ); foreach ($jsConfigPath as $k => $v) { $vRewrite = new Rewrite($v, array( 'controller' => 'Index', 'action' => 'jsConfig' )); $router->addRoute('jsConfig' . $k, $vRewrite); } $api = new Rewrite('/api', array( 'controller' => 'Index', 'action' => 'api' )); $router->addRoute('api', $api); } }<file_sep>/app/conf/admin/table/user/index.ini [product] cols.5.column=id cols.6.column=nickname cols.10.column=avatar@ id@ cols.10.type=imageIcon<file_sep>/app/conf/admin/nav.ini [product] sidebar.5.0.table=house sidebar.5.1.table=houseImage sidebar.5.5.table=user sidebar.10.0.table=adminUser sidebar.10.1.table=adminUserId sidebar.10.2.table=adminUserIdType sidebar.30.5.label=CRON sidebar.30.5.sub.0.label=TEST sidebar.30.5.sub.0.url= sidebar.30.10.label=SVN sidebar.30.10.url="/admin_index/svnup"<file_sep>/app/conf/admin/table/adminUser/index.ini [product] where.0.type=text where.0.column="adminUser.column like ?" where.0.label=名称(通配符:%) where.1.type=date where.1.column="adminUser.createTime>=?" where.1.label=创建日期开始 where.2.type=date where.2.column="adminUser.createTime<=?" where.2.label=创建日期结束 cols.0.column=id cols.1.column=name cols.2.column=createTime<file_sep>/library/Config.php <?php use Yaf\Application; use Yaf\Config\Ini; use Ares333\Yaf\Helper\File; class Config { protected static $ini = array(); static function get($file) { $app = Application::app(); if (! File::isAbsolute($file)) { $file = $app->getAppDirectory() . '/conf/' . $file; } $file = realpath($file); if (! is_file($file)) { return; } if (! isset(self::$ini[$file])) { $ini = new Ini($file); $env = $app->environ(); if ($ini->offsetExists($env)) { $ini = $ini->get($env); } else { $ini = $ini->current(); } self::$ini[$file] = $ini; } return self::$ini[$file]; } static function isDev() { return 0 === strpos(Application::app()->environ(), 'development'); } }<file_sep>/app-api/src/api/Admin.php <?php namespace Api; use Slim\Http\Request; use Slim\Http\Response; class Admin extends \Api { protected static $modulePathName; function __invoke(Request $request, Response $response, $args) { if (! isset(self::$modulePathName)) { self::$modulePathName = explode('\\', get_class($this)); self::$modulePathName = lcfirst(self::$modulePathName[1]); } $userClass = '\\' . ucfirst(self::$modulePathName) . '\User'; $user = $userClass::getInstance(); $whiteList = array( '/api/' . self::$modulePathName . '/user/signin', '/api/' . self::$modulePathName . '/user/signin/captcha', '/api/' . self::$modulePathName . '/user/signin/captcha/isneed' ); $uri = $request->getUri()->getPath(); if (! in_array(strtolower($uri), $whiteList) && ! $user->isLogin()) { return $response->withStatus(401); } return parent::__invoke($request, $response, $args); } protected function withStatusBase64($response, $code, $msg) { return $response->withStatus($code, '\b' . base64_encode($msg)); } }<file_sep>/library/Captcha/Account.php <?php namespace Captcha; use Ares333\Yaf\Tool\Singleton; use Zend\Captcha\Figlet; use Zend\Session\Container; class Account extends Figlet { use Singleton; protected $account; function __construct($options) { $this->account = md5($options['account']); if (! isset($options['session'])) { $options['session'] = new Container(__CLASS__); $options['session']->setExpirationSeconds(600); } parent::__construct($options); } protected function generateRandomId() { return $this->account; } function isValid($value) { $res = parent::isValid( [ 'input' => $value, 'id' => $this->account ]); if ($res) { $this->getSession()->setExpirationHops(0); } return $res; } }<file_sep>/library/Db/TableGateway/Feature/Mysql/SelectParentFeature.php <?php namespace Db\TableGateway\Feature\Mysql; use Ares333\Yaf\Zend\Db\TableGateway\Feature\Mysql\SelectParentFeature as Base; use Db\Metadata\Source\MysqlMetadata; use Db\TableGateway\Feature\MetadataFeature; use Uploader\Image; use Yaf\Dispatcher; use Zend\Db\Metadata\Object\AbstractTableObject; class SelectParentFeature extends Base { function __construct($metadata = null) { if (! isset($metadata)) { $metadata = MysqlMetadata::getInstance(); } parent::__construct($metadata); $this->updateDeleteColumn = MetadataFeature::$updateDeleteColumn; $this->setSelectColumnFilter( function ($tableName) { $metadata = $this->metadata->getTable($tableName); $map = []; foreach ($metadata->getColumns() as $v) { if (in_array($v->getDataType(), [ 'geometry', 'point' ])) { $map[$v->getName()] = new \Zend\Db\Sql\Expression( 'ST_AsGeoJSON(' . $tableName . $this->tableGateway->getAdapter() ->getPlatform() ->getIdentifierSeparator() . $v->getName() . ')'); } } return $map; }); $this->setResultFilter( function ($row, AbstractTableObject $meta) { $configTable = \Config::get('admin/table.ini'); if (isset($configTable, $configTable->{$meta->getName()}->type) && $configTable->{$meta->getName()}->type == 'file') { $uploader = Image::getInstance(); $row = $uploader->format($row); } if ($meta->getName() == 'user') { if (! Dispatcher::getInstance()->getRequest()->isAdmin) { unset($row['password']); } } return $row; }); } }<file_sep>/app/controllers/Error.php <?php use Ares333\Yaf\Tool\ErrorController as Base; class ErrorController extends Base { }<file_sep>/app/plugins/Session.php <?php use Yaf\Request_Abstract; use Yaf\Response_Abstract; use Yaf\Plugin_Abstract; use Zend\Session\Container; use Zend\Session\SessionManager; use Db\TableGateway; use Session\SaveHandler\DbTableGateway; use Zend\Session\SaveHandler\DbTableGatewayOptions; use Zend\Session\Config\SessionConfig; use Db\Adapter; use Zend\Session\Validator\HttpUserAgent; /** * CREATE TABLE `session` ( * `id` char(32) COLLATE utf8mb4_bin NOT NULL, * `name` char(32) COLLATE utf8mb4_bin NOT NULL, * `modified` int(11) DEFAULT NULL, * `lifetime` int(11) DEFAULT NULL, * `data` text COLLATE utf8mb4_bin, * PRIMARY KEY (`id`,`name`) * ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; * * CREATE TABLE `sessionAdmin` ( * `id` char(32) COLLATE utf8mb4_bin NOT NULL, * `name` char(32) COLLATE utf8mb4_bin NOT NULL, * `userId` int(11) NOT NULL, * `userAgent` varchar(255) COLLATE utf8mb4_bin NOT NULL, * `createTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, * PRIMARY KEY (`id`,`name`), * KEY `userId` (`userId`) USING BTREE, * CONSTRAINT `sessionAdmin_ibfk_1` FOREIGN KEY (`id`, `name`) REFERENCES `session` (`id`, `name`) ON DELETE CASCADE, * CONSTRAINT `sessionAdmin_ibfk_2` FOREIGN KEY (`userId`) REFERENCES `adminUser` (`id`) ON DELETE CASCADE * ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; */ class SessionPlugin extends Plugin_Abstract { function dispatchLoopStartup(Request_Abstract $request, Response_Abstract $response) { if ($request->isCli()) { return; } $tableGateway = new TableGateway('session', Adapter::getInstance()); $saveHandler = new DbTableGateway($tableGateway, new DbTableGatewayOptions()); $sessionConfig = new SessionConfig(); $sessionConfig->setOptions( [ 'name' => 'sess' ]); if ($request->isAdmin) { $sessionConfig->setName('sessa'); } $validators = []; if (! Config::isDev()) { $validators[] = HttpUserAgent::class; } $manager = new SessionManager($sessionConfig, null, $saveHandler, $validators); Container::setDefaultManager($manager); } }<file_sep>/app/plugins/Admin.php <?php use Yaf\Request_Abstract; use Yaf\Response_Abstract; use Yaf\Plugin_Abstract; use Yaf\Application; use Ares333\Yaf\Helper\Yaf; use Ares333\Yaf\Helper\Http; use Yaf\Dispatcher; class AdminPlugin extends Plugin_Abstract { function preDispatch(Request_Abstract $request, Response_Abstract $response) { $controllerName = $request->getControllerName(); $modulePathName = lcfirst(substr(get_class($this), 0, - 6)); $modulePathNameSelf = strtolower(substr(__CLASS__, 0, - 6)); if (preg_match('/^' . ucfirst($modulePathName) . '/', $controllerName)) { $out = []; $out['_modulePathName'] = $modulePathName; $out['_modulePathNameAssets'] = $modulePathNameSelf; $userClass = '\\' . ucfirst($modulePathName) . '\User'; $user = $userClass::getInstance(); $uri = $request->getRequestUri(); $whiteList = [ '/' . $modulePathName . '/signin', '/' . $modulePathName . '/signout' ]; if (! in_array(strtolower($uri), $whiteList) && ! $user->isLogin()) { $request->setControllerName('Error')->setActionName('dummy'); $response->setRedirect('/' . $modulePathName . '/signin'); return; } $out['_nav'] = Config::get($modulePathName . '/nav.ini')->toArray(); ksort($out['_nav']['sidebar']); $out['_tableConfig'] = $tableIni = Config::get( $modulePathName . '/table.ini'); $out['_currentUrl'] = Http::getCurrentUrl(); // table $controllerTablePrefixDefault = $modulePathName . '_table_'; $out['_controllerTablePrefix'] = $controllerTablePrefixDefault; $controllerTablePrefix = [ $controllerTablePrefixDefault, $modulePathName . '_app_table_' ]; foreach ($controllerTablePrefix as $v) { if (0 === strpos(strtolower($uri), '/' . $v)) { $vTableName = explode('_', explode('/', $uri)[1]); $vTableName = end($vTableName); $out['_tableName'] = $vTableName; $out['_controllerTablePrefix'] = $v; $out['_controllerNameTable'] = $v . $vTableName; $request->setParam($modulePathName . '_tableName', $vTableName); $controllerFile = Application::app()->getAppDirectory() . '/controllers'; foreach (explode('_', $out['_controllerNameTable']) as $v1) { $controllerFile .= '/' . ucfirst(strtolower($v1)); } $controllerFile .= '.' . Yaf::getConfig('ext'); if (! is_file($controllerFile)) { $vNewControllerName = explode('_', substr($v, 0, - 1)); array_walk($vNewControllerName, function (&$v) { $v = ucfirst($v); }); $request->setControllerName( implode('_', $vNewControllerName)); } } } View::getInstance()->assign($out); } } function routerShutdown(Request_Abstract $request, Response_Abstract $response) { $uri = Dispatcher::getInstance()->getRequest()->getRequestUri(); $request->isAdmin = (bool) preg_match('/^\/(admin|api\/admin)/i', $uri); } }<file_sep>/app/conf/admin/table/adminUser/save.ini [product] cols.password.type=password cols.password.placeholder=任意字符,区分大小写<file_sep>/public/_assets/admin/js/ckeditor-config.js /** * @license Copyright (c) 2003-2017, CKSource - <NAME>. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/terms-of-use/#open-source-licences */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.plugins = 'basicstyles,' + 'clipboard,' + 'colorbutton,' + 'colordialog,' + 'copyformatting,' + 'contextmenu,' + 'dialogadvtab,' + 'div,' + 'elementspath,'+ 'enterkey,' + 'entities,' + 'filebrowser,' + 'font,' + 'format,' + 'htmlwriter,' + 'image2,' + 'link,' + 'list,' + 'magicline,' + 'maximize,' + 'pastefromword,' + 'pastetext,' + 'copyformatting,' + 'removeformat,' + 'showblocks,' + 'showborders,' + 'sourcearea,' + 'table,' + 'tableselection,' + 'tabletools,' + 'toolbar,' + 'resize,' + 'undo,' + 'wysiwygarea'; config.extraPlugins = 'autogrow,tableresize,uploadimage'; config.autoGrow_onStartup = true; config.autoGrow_minHeight = 300; config.autoGrow_maxHeight = 600; config.autoGrow_bottomSpace = 30; config.language='zh-cn'; config.width='100%'; config.filebrowserImageUploadUrl=_config.urlOrigin+'/api/admin/table/image?source=ckeditor'; config.toolbar=[[ 'Format','FontSize' , 'TextColor', 'BGColor', 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript','CopyFormatting','RemoveFormat' , 'NumberedList', 'BulletedList', 'Link', 'Unlink', 'Anchor' ,'Image','Table' , 'PasteFromWord','Source','Maximize' ]]; };
2805b54b7a92f6c44ac2bda21e9ed273f282b14a
[ "JavaScript", "Markdown", "INI", "Text", "PHP" ]
62
PHP
ares333/php-yaf-library-demo
9f292a67acf3f9873d4757fe268657185781c96d
576e46b18280f71e6fbf760bc858674088cf5f7f
refs/heads/master
<repo_name>snail987/reports<file_sep>/src/main/java/com/dwl/rep/service/RepService.java package com.dwl.rep.service; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.alibaba.fastjson.JSONArray; import com.dwl.rep.common.Strings; import com.dwl.rep.dao.DataInfoMapper; import com.dwl.rep.dao.HeaderInfoMapper; import com.dwl.rep.dao.ReportDetailMapper; import com.dwl.rep.dao.ReportInfoMapper; import com.dwl.rep.pojo.ReportDetail; import com.dwl.rep.pojo.ReportInfo; @Service("repService") public class RepService { @Resource private ReportInfoMapper repMapper; @Resource private ReportDetailMapper reportDetailMapper; @Resource private HeaderInfoMapper headerInfoMapper; @Resource private DataInfoMapper dataInfoMapper; public List<ReportInfo> getRepList(){ return repMapper.getInfoList(); } public ReportInfo getInfoById(String repId){ return repMapper.selectByPrimaryKey(repId); } public ReportInfo getInfoWithDataById(String repId){ ReportInfo reportInfo = repMapper.selectByPrimaryKey(repId); String[] dataId = Strings.splitIgnoreBlank(reportInfo.getDataId()); List<Object> list = new ArrayList<>(); for(String id :dataId){ List<Object> map = JSONArray.parseArray(dataInfoMapper.selectByPrimaryKey(id).getResult()); list.addAll(map); } reportInfo.setData(list); return reportInfo; } public ReportInfo getInfoWithDeal(String repId){ ReportInfo reportInfo = repMapper.selectWithDetailById(repId); reportInfo.setHasSecHead1("0"); reportInfo.setHasSecHead2("0"); reportInfo.getDetails().forEach(info->{ info.setHeaderInfo(headerInfoMapper.selectWithDetailByPrimaryKey(info.getHeaderId())); if(!Strings.isEmpty(info.getSecHeaderId())){ info.setSecHeaderInfo(headerInfoMapper.selectWithDetailByPrimaryKey(info.getSecHeaderId())); if("0".equals(info.getType())) reportInfo.setHasSecHead1("1");//拥有2级横表头 else reportInfo.setHasSecHead2("1");//拥有2级竖表头 } }); return reportInfo; } public ReportInfo getInfoWithDetail(String repId){ ReportInfo reportInfo = repMapper.selectWithDetailById(repId); reportInfo.getDetails().forEach(info->{ info.setHeaderInfo(headerInfoMapper.selectWithDetailByPrimaryKey(info.getHeaderId())); if(!Strings.isEmpty(info.getSecHeaderId())){ info.setSecHeaderInfo(headerInfoMapper.selectWithDetailByPrimaryKey(info.getSecHeaderId())); } }); reportInfo.init(); return reportInfo; } @Transactional public int updateRepInfo(ReportInfo reportInfo){ reportDetailMapper.deleteByRepId(reportInfo.getRepId()); List<ReportDetail> list = reportInfo.getDetails(); for(int i=0;i<list.size();i++){ if(!Strings.isEmpty(list.get(i).getHeaderId())){ list.get(i).setId(UUID.randomUUID().toString()); list.get(i).setRepId(reportInfo.getRepId()); list.get(i).setOrders(i); reportDetailMapper.insert(list.get(i)); } } reportInfo.setUpdateTime(new Date()); return repMapper.updateByPrimaryKey(reportInfo); } public int updateRepInfoOnly(ReportInfo reportInfo){ reportInfo.setUpdateTime(new Date()); return repMapper.updateByPrimaryKeySelective(reportInfo); } @Transactional public int insertRepInfo(ReportInfo reportInfo){ List<ReportDetail> list = reportInfo.getDetails(); for(int i=0;i<list.size();i++){ if(!Strings.isEmpty(list.get(i).getHeaderId())){ list.get(i).setId(UUID.randomUUID().toString()); list.get(i).setRepId(reportInfo.getRepId()); list.get(i).setOrders(i); reportDetailMapper.insert(list.get(i)); } } return repMapper.insert(reportInfo); } @Transactional public int deleteRepInfo(String repId){ reportDetailMapper.deleteByRepId(repId); return repMapper.deleteByPrimaryKey(repId); } public List<ReportInfo> getCacheRepInfo(){ return repMapper.selectCacheRepInfo(); } }
61924a77370b4b66720b8d6254b464a0404222a7
[ "Java" ]
1
Java
snail987/reports
47122f9a3e52e0cf9cc55cc064f40fdd0e71d27d
479a934db0b46e120d09088164ebc40de686dec0
refs/heads/master
<file_sep># seyed__repository i don't know what should i write. <file_sep>import string def name_maker(s): new_s = "" for i in s: if i not in string.punctuation and i != "\n" and i != " ": new_s += i if i == " ": i = "_" new_s += i if new_s[-1] == "_": new_s = new_s[0:-1] return new_s source = open("audio.txt", "r") code = open("audio_code.txt", "w") while True: new_line = "" line = source.readline() if len(line) != 0 and line[-1] == " ": line[-1] = "" if len(line) == 0: break new_line = name_maker(line) code.write("public var {0}: AudioClip;\n".format(new_line)) source.close() code.close() <file_sep> console = open("console.txt", "r") console_code = open("console_code.txt", "w") while True: line1 = console.readline() line = line1[0:-1] if len(line) == 0: break if line[0:4] == "-r- ": console_code.write('<ListBoxItem Foreground="Red" Content="{0}"/>\n'.format(line[4:])) if line[0:4] == "-g- ": console_code.write('<ListBoxItem Foreground="Green" Content="{0}"/>\n'.format(line[4:])) if line[0:4] == "-b- ": console_code.write('<ListBoxItem Foreground="Black" Content="{0}"/>\n'.format(line[4:])) if line[0:4] == "-f- ": console_code.write("Test\n") if line[0:4] == "----": console_code.write('<System:String xml:space="preserve"> ------------------------------------- </System:String>\n') if line[0:4] == "-s- ": console_code.write("\n") console.close() console_code.close()
d781dc533a5faf68143e560b55365bcfa9cb17ca
[ "Markdown", "Python" ]
3
Markdown
mhras1317/seyed__repository
43f2e466002b7c4e7de1982ee7589d94181eb2c5
4d5a69912ccb4933990e78acdea9f804607fd446
refs/heads/master
<repo_name>VDoring/My-Baekjoon-online-judge<file_sep>/단계별/입출력과 사칙연산/2588.c #include <stdio.h> void calc(int num1, char num2[]); int main() { int num1 = 0; char cnum2[4] = { 0, }; scanf("%d", &num1); scanf("%s", cnum2); calc(num1, cnum2); return 0; } void calc(int num1, char num2[]) { //먼저 472 * 5를 해서 출력 //아후 472 * 6를 해서 출력 //이후 472 * 3를 해서 출력 //이후 2360 + 3776*10 + 1416*100 을 계산하고 출력 int multiply_1 = 0, multiply_2 = 0, multiply_3 = 0; int result = 0; int i; i = 2; multiply_1 = num1 * (num2[i] - 48); printf("%d\n", multiply_1); i = 1; multiply_2 = num1 * (num2[i] - 48); printf("%d\n", multiply_2); i = 0; multiply_3 = num1 * (num2[i] - 48); printf("%d\n", multiply_3); result = multiply_1 + (multiply_2 * 10) + (multiply_3 * 100); printf("%d", result); return; }<file_sep>/백준에서 가장 많이 출린 문제 TOP 100/11718.c #include <stdio.h> int main() { char input; while (scanf("%c", &input) != EOF) { //하나의 문자로 입력 및 EOF 체크(EOF일시 while 종료) printf("%c", input); //stdin에서 글자(스페이스 포함)하나씩 꺼내와 EOF가 될때까지 출력 } }<file_sep>/단계별/for문/10950.c /* 먼저 몇개적을껀지 갯수를 입력받는다. 그 갯수에 따라 for문 반복 및 입력 #include <stdio.h> #include <stdlib.h> int main() { int i, arr_len; char *num[] = { 0, }; scanf("%d", &arr_len); for (i = 0; i < arr_len; i+2) { scanf("%d %d", num[i], num[i+1]); } for (i = 0; i < arr_len; i+2) { printf("%d\n", num[i] + *num[i+1]); } } */ #include <stdio.h> int main() { int total_num; int first, second; int i; scanf("%d", &total_num); for (i = 0; i < total_num; i++) { scanf("%d %d", &first, &second); printf("%d\n", first + second); } return 0; }<file_sep>/10951.cpp #include <iostream> #include <cstdio> using namespace std; int main() { int num1, num2; while (scanf("%d%d", &num1, &num2) != EOF) { printf("%d\n", num1 + num2); } return 0; }<file_sep>/백준에서 가장 많이 출린 문제 TOP 100/11720.c #include <stdio.h> int main() { int count, sum = 0; //넣을 숫자의 갯수, 계산된 합계 char arr[100] = { 0, }; //더할 숫자를 저저장하는 배열 scanf("%d", &count); scanf("%s", arr); for (int i = 0; i < count; i++) { sum += arr[i] - '0'; //ASCII와의 구분을 위해 '0'을 넣으므로써 정수로써 계산되게 하였음 } printf("%d", sum); }<file_sep>/단계별/if문/2884.c #include <stdio.h> int main() { int hour, minute; scanf("%d %d", &hour, &minute); minute = minute - 45; if (minute < 0) { hour--; minute = minute + 60; if (hour < 0) hour = hour + 24; } printf("%d %d", hour, minute); return 0; }<file_sep>/백준에서 가장 많이 출린 문제 TOP 100/11721.c //<NAME> #include <stdio.h> #include <string.h> int main() { char text[100] = { 0, }; scanf("%s", text); printf("%c", text[0]); for (int i = 1; i < strlen(text); i++) { if (i % 10 == 0) printf("\n"); printf("%c", text[i]); } return 0; } /* 무한 반복 버전 #include <stdio.h> #include <string.h> int main() { char text[100] = { 0, }; while (1) { scanf("%s", text); printf("%c", text[0]); for (int i = 1; i < strlen(text); i++) { if (i % 10 == 0) printf("\n"); printf("%c", text[i]); } printf("\n"); } return 0; }*/ /* 내가 한 방법 #include <stdio.h> #include <string.h> int main() { char text[101] = { 0, }; //문자를 저장할 배열 int input_startcount = 1, input_maxcout = 11; //입력용 반복문 카운트 int output_startcount = 1, output_maxcount = 11; //출력용 반복문 카운트 int i, j; //반복문 안 변수 while (1) { for (i = input_startcount; i < input_maxcout; i++) { //문자 입력 scanf("%c", &text[i]); } if (text[i - 1] == '\n' || text[i - 1] == 0) break; else if (text[i - 1] != 0) { //문자가 더 저장되있을경우 input_startcount += 10; input_maxcout += 10; continue; //다음 배열칸으로 옮긴뒤 다시 입력 } } while (1) { for (j = output_startcount; j < output_maxcount; j++) { //문자 출력 if (text[j] == '\n') break; printf("%c", text[j]); } if (text[j] == '\n' || text[j]== 0) break; else if (text[j] != 0) { //문자가 더 저장되있을경우 printf("\n"); output_startcount += 10; output_maxcount += 10; continue; //다음 배열칸으로 옮긴뒤 다시 출력 } } return 0; }*/<file_sep>/10953.cpp #include <iostream> #include <cstdio> using namespace std; int main() { int totalnum; int num1, num2; scanf("%d", &totalnum); while (totalnum--) { scanf("%d,%d", &num1, &num2); printf("%d\n", num1+num2); } return 0; }<file_sep>/백준에서 가장 많이 출린 문제 TOP 100/2839.c /* 작동 안됨 */ #include <stdio.h> int main() { int Kg; //옮겨야 할 양 int bag_3 = 3, bag_5 = 5; //비닐봉지 3Kg, 5Kg int bag_3_count = 0, bag_5_count = 0, bag_count_sum = 0; //3kg, 5kg 비닐봉지 옮긴 휫수, 총 옮긴 휫수 scanf("%d", &Kg); while (1) { if (Kg % 5 >= 3) { //5Kg 비닐봉지로 나누고도 3kg비닐봉지를 사용할 수 있을때 while (1) { if (Kg % 5 == 0) break; if (Kg % 3 == 0 && Kg % 5 < 3) break; if (Kg % 5 != 0 && Kg % 3 != 0) break; while (Kg > 5) { //5Kg 비닐봉지로 최대한 담음 Kg = Kg - bag_5; bag_5_count++; } if (Kg % 3 == 0 || Kg >= 3) { //나머지는 3kg 비닐봉지로 담음(단 남아있는 짐 양이 3kg이하일경우 작동안됨) while (Kg != 0) { Kg = Kg - bag_3; bag_3_count++; } break; } } } if (Kg % 5 == 0) { //5Kg 비닐봉지로 한번에 처리할 수 있을때 while (Kg != 0) { Kg = Kg - bag_5; bag_5_count++; } } if (Kg % 3 == 0) { //3Kg 비닐봉지로 한번에 처리할 수 있을때 while (Kg != 0) { Kg = Kg - bag_3; bag_3_count++; } } if (Kg >= 5) { //5Kg 비닐봉지를 사용할 수 있을때 Kg = Kg - bag_5; bag_5_count++; } else if (Kg >= 3) { //3Kg 비닐봉지를 사용할 수 있을때 Kg = Kg - bag_3; bag_3_count++; } else if (Kg < 3 && Kg != 0) { //안 나누어 떨어질때 printf("-1"); return 0; } else break; } bag_count_sum = bag_5_count + bag_3_count; //비닐봉지 총 옮긴휫수 printf("%d", bag_count_sum); return 0; }<file_sep>/백준에서 가장 많이 출린 문제 TOP 100/1008.c #include <stdio.h> int main() { double in1, in2; scanf("%lf %lf", &in1, &in2); printf("%.9lf", in1 / in2); return 0; }<file_sep>/백준에서 가장 많이 출린 문제 TOP 100/10871.c #include <stdio.h> int main() { short numarr[10000] = { 0, }; //10000보다 작은 수만 들어오므로 메모리 절약을 위한 short형 배열 선언 //입력한 값들을 저장하는 역할 int N, X; //N: 입력할 숫자 갯수 //X: 비교할 숫자 scanf("%d %d", &N, &X); // 입력할 숫자 갯수, 비교할 숫자 입력 for (int i = 0; i < N; i++) { scanf("%d", &numarr[i]); //입력한 숫자 갯수만큼 배열에 값을 저장 } for (int i = 0; i < N; i++) { if (X > numarr[i]) { //입력한 값들이 비교할 숫자보다 작다면 printf("%d ", numarr[i]); //그 입력한 값을 출력 } } }<file_sep>/백준에서 가장 많이 출린 문제 TOP 100/1000.c // https://www.acmicpc.net/problem/1000 #include <stdio.h> int main() { int num1, num2; scanf("%d %d", &num1, &num2); printf("%d", num1 + num2); return 0; }<file_sep>/백준에서 가장 많이 출린 문제 TOP 100/10869.c #include <stdio.h> int main() { int input1, input2; scanf("%d %d", &input1, &input2); printf("%d\n", input1 + input2); printf("%d\n", input1 - input2); printf("%d\n", input1 * input2); printf("%d\n", input1 / input2); printf("%d", input1 % input2); return 0; }<file_sep>/10952.cpp #include <iostream> #include <cstdio> int main() { int n1, n2; while (1) { scanf("%d%d", &n1, &n2); if (n1 == 0 && n2 == 0) return 0; printf("%d\n", n1 + n2); } }<file_sep>/백준에서 가장 많이 출린 문제 TOP 100/11718.cpp #include <iostream> #include <string> using namespace std; int main() { string text; for (;;) { getline(cin, text); if (text == "") break; cout << text << endl; } }<file_sep>/백준에서 가장 많이 출린 문제 TOP 100/9498.c #include <stdio.h> int main() { int input; scanf("%d", &input); if (input >= 90) printf("A"); else if (input >= 80) printf("B"); else if (input >= 70) printf("C"); else if (input >= 60) printf("D"); else printf("F"); return 0; }<file_sep>/10818.c #include <stdio.h> #include <stdlib.h> int main() { int n; //숫자 개수 int in_num; //숫자요소들 int min_num = 1000001, max_num = -1000001; //최소값, 최대값 int *ar; scanf("%d", &n); ar = malloc(sizeof(int) * n); for (int i = 0; i < n; i++) { scanf("%d", &ar[i]); } for (int i = 0; i < n; i++) { if (max_num < ar[i]) max_num = ar[i]; if (min_num > ar[i]) min_num = ar[i]; } printf("%d %d", min_num, max_num); free(ar); return 0; }<file_sep>/백준에서 가장 많이 출린 문제 TOP 100/2742.c #include <stdio.h> int main() { int input; scanf("%d", &input); for (input; input > 0; input--) { printf("%d\n", input); } }<file_sep>/단계별/while문/10952.c #include <stdio.h> int main() { int first = -1, second = -1; while (1) { scanf("%d %d", &first, &second); if (first != 0 && second != 0) { printf("%d\n", first + second); continue; } else break; } return 0; }<file_sep>/1100.cpp //µ¿ÀÛ¾ÈÇÔ #include <iostream> int main() { char plate[8][8]; int count = 0; for (int i = 0; i < 8; i++) scanf("%s ", &plate[i]); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (i % 2 == 1) { j++; if (plate[i][j] == 'F') { count++; continue; } } if (plate[i][j] == 'F') count++; } } return 0; }<file_sep>/백준에서 가장 많이 출린 문제 TOP 100/2558.c #include <stdio.h> int main() { int input1, input2; int result = 0; scanf("%d", &input1); scanf("%d", &input2); result = input1 + input2; printf("%d", result); return 0; }<file_sep>/백준에서 가장 많이 출린 문제 TOP 100/1924.c #include <stdio.h> int main() { int user_month, user_days; //유저가 입력한 달과 일수를 받는 변수 int total_days = 0; //총 일수(월+일 합쳐서) char Monthlist[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 }; //달마다 몇일이 마지막인지 나열 scanf("%d %d", &user_month, &user_days); //유저의 월, 일 입력 for (int i = 1; i < user_month; i++) { //유저가 입력한 월의 수만큼 반복. //Q. 왜 i가 1로 시작되나요? //A. i를 0으로 하면 1월 1일인 경우에도 1월의 날짜를 모두 더하거든요. 본래는 2월 이상으로 가야 1월의 날자를 모두 더하는게 맞기때문에 i를 0으로 하면 안되요. total_days += Monthlist[i-1]; //해당 달의 일수를 total_days에 저장. //Q. 왜 Monthlist[i]가 아닌 Monthlist[i-1]인가요? //A. 위의 주석을 보면 알겠지만 i를 1로 초기화하였죠? 배열은 0부터 시작하기때문에 그냥 i(1)을 넣게된다면 2월달부터 더해지기 때문에 마이너스 1을 넣어주는거랍니다. } total_days += user_days; //유저가 입력한 일수를 total_days에 저장. switch (total_days % 7) { //총 일수를 7로 나눈 나머지. 나온 값에 다라 요일이 결정됨. case 0: printf("SUN"); break; case 1: printf("MON"); break; case 2: printf("TUE"); break; case 3: printf("WED"); break; case 4: printf("THU"); break; case 5: printf("FRI"); break; case 6: printf("SAT"); break; } }<file_sep>/단계별/for문/15552.c #include <stdio.h> int main() { int total_num; int first, second; int i; scanf("%d", &total_num); for (i = 0; i < total_num; i++) { scanf("%d %d", &first, &second); printf("%d\n", first + second); } return 0; }<file_sep>/구현/10039.c #include <stdio.h> int main() { int score[5]; int score_sum = 0; int score_average; for (int i = 0; i < 5; i++) { scanf("%d", &score[i]); if (score[i] < 40) score[i] = 40; score_sum += score[i]; } score_average = score_sum / 5; printf("%d", score_average); return 0; }<file_sep>/단계별/if문/14681.c #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main() { int x, y; scanf("%d", &x); scanf("%d", &y); //x,y 모두 양수 = Quadrant 1 if (x > 0 && y > 0) printf("1"); //x는 음수, y는 양수 = Quadrant 2 else if (x < 0 && y > 0) printf("2"); //x,y 모두 음수 = Quadrant 3 else if (x < 0 && y < 0) printf("3"); //x는 양수, y는 음수 = Quadrant 4 else if (x > 0 && y < 0) printf("4"); return 0; }<file_sep>/1546.c #include <stdio.h> #include <stdlib.h> int main() { int cnt; int *score; float *avr_score; int max_score = 0; float sum_avr_score = 0; scanf("%d", &cnt); score = malloc(sizeof(int)*cnt); avr_score = malloc(sizeof(float)*cnt); for (int i = 0; i < cnt; i++) { scanf("%d", &score[i]); } for (int i = 0; i < cnt; i++) { if (score[i] > max_score) max_score = score[i]; } for (int i = 0; i < cnt; i++) { avr_score[i] = (float)score[i] / max_score * 100; } for (int i = 0; i < cnt; i++) { sum_avr_score += avr_score[i]; } sum_avr_score /= cnt; printf("%.5f", sum_avr_score); free(score); free(avr_score); return 0; } //구하는 방법 /* 40점, 80점, 60점일때 40점 계산: 40 / 80 * 100 = 50점 80점 계산: 80 / 80 * 100 = 100점 60점 계산: 60 / 80 * 100 = 75점 (50+100+75) / 2 = 75점 */<file_sep>/단계별/while문/10951.c #include <stdio.h> int main() { int first, second; while (scanf("%d %d", &first, &second) != EOF) { printf("%d\n", first + second); } return 0; }<file_sep>/README.md # My-Baekjoon-online-judge 백준에서 해결한 문제들 저장소. https://www.acmicpc.net/
59eab4c48e255bb445c68ebd2d0f94f5dc19d474
[ "Markdown", "C", "C++" ]
28
C
VDoring/My-Baekjoon-online-judge
db8373416fe2f0f7294cc0f740e48757a033bee5
29c85a946f781ed1dd78c2dc1c21188cc8688703
refs/heads/main
<file_sep>import pyodbc server = 'epqtimeclock.database.windows.net' database = 'EPQTimeClockdb' username = 'Dap_1223' password = '<PASSWORD>' driver = '{ODBC Driver 17 for SQL Server}' def get_connected(): return pyodbc.connect('DRIVER=' + driver + ';SERVER=' + server + ';PORT=1433;DATABASE=' + database + ';UID=' + username + ';PWD=' + password)
77c8dfa95fa8f06b683a38e08f9c89c812230eb8
[ "Python" ]
1
Python
luisquiles28/test
b910f3253a0aedf7ff7c3ad4f8e1adcdb67a604f
5366d409bcde2d64c7e7886abf7596f8670071e2
refs/heads/master
<repo_name>colinrlly/nature_inspired_genetic_algo<file_sep>/genetic/InheritanceExample/Test.java package genetic.InheritanceExample; public class Test implements GeneticInterface { public void hello() { System.out.println("hello from test"); } } <file_sep>/genetic/UniformRecombinator.java package genetic; import java.util.ArrayList; import java.util.Collection; /** * Recombination method that utilizes Uniform Crossover */ public class UniformRecombinator implements Recombiner { @Override public Collection<Chromosome> recombine(Collection<Chromosome> mating_pool) { // Collection that holds all of the offspring generated from the mating_pool Collection<Chromosome> offspring = new ArrayList<>(); Collection<Chromosome> crossoffspring; // nested for loop, every chromosome is recombined with every other one, except itself // leading to n^2 offspring int num_of_iters = 0; for (Chromosome chr1 : mating_pool){ for (Chromosome chr2 : mating_pool){ num_of_iters++; if(chr1.toString().equals(chr2.toString())){ continue; } crossoffspring = uniformCrossover(chr1, chr2); Chromosome first = crossoffspring.iterator().next(); crossoffspring.remove(first); offspring.add(first); first = crossoffspring.iterator().next(); offspring.add(first); } if(num_of_iters == mating_pool.size()){ break; } } return offspring; } /** * Function that implements uniform crossover recombinations, accepts two Chromosomes as input, * iterates through every single row from both Chromosomes, and uses a random number generator * to determine from which parent do the offspring receive a gene * @param parent1 first input Chromosome * @param parent2 second input Chromosome * @return a collection of Offspring Chromosomes generated */ public Collection<Chromosome> uniformCrossover(Chromosome parent1, Chromosome parent2){ // initialization of the probability used to determine from what parent does the offspring // recieve genes from double prob; int row = parent1.getProblem().getNumMachines(); int col = parent1.getProblem().getNumJobs(); Collection<Chromosome> offspring = new ArrayList<>(); Chromosome offspring1 = new Chromosome(parent1.getProblem()); Chromosome offspring2 = new Chromosome(parent2.getProblem()); // nested for loop that iterates through the rows of the parents for (int i = 0; i < row; i++){ // generates a random real number from 0 to 1 prob = Math.random(); // if the number generated is larger than 0.5, the first offspring receives gene from the // first parent, and second offspring recieves gene from second parent if(prob > 0.5){ for (int j = 0; j < col; j++){ offspring1.setElement(i, j, parent1.getElement(i, j)); offspring2.setElement(i, j, parent2.getElement(i, j)); } }else{ for (int j = 0; j < col; j++){ offspring1.setElement(i, j, parent2.getElement(i, j)); offspring2.setElement(i, j, parent1.getElement(i, j)); } } } offspring1.setInitialized(); offspring.add(offspring1); offspring2.setInitialized(); offspring.add(offspring2); return offspring; } } <file_sep>/genetic/Mutator.java package genetic; import java.util.Collection; public interface Mutator { public Collection<Chromosome> mutate(Collection<Chromosome> mating_pool); } <file_sep>/genetic/SelectorPickBest.java package genetic; import java.util.ArrayList; import java.util.Collection; /** * Simple implementation of the selector interface. Returns the pool_size Chromosomes with the highest fitness. */ public class SelectorPickBest implements Selector { /** * Loop through population and return the pool_size most fit Chromosomes. */ public Collection<Chromosome> select(Problem problem, Collection<Chromosome> population, int pool_size) { ArrayList<Chromosome> pop_copy = new ArrayList<>(population); Collection<Chromosome> mating_pool = new ArrayList<>(); int pool_size_copy = pool_size; int highest_fitness; int current_fitness; Chromosome current_chromosome; Chromosome most_fit = new Chromosome(problem); int most_fit_index; // loop pool_size times while (pool_size_copy > 0) { most_fit_index = 0; highest_fitness = -1; // Loop through the population for (int i = 0; i < pop_copy.size(); i++) { current_chromosome = pop_copy.get(i); current_fitness = current_chromosome.getFitness(); // If we found a new highest fitness chromosome if (current_fitness > highest_fitness) { most_fit_index = i; highest_fitness = current_fitness; most_fit = current_chromosome; } } mating_pool.add(most_fit); // Add the most fit Chromosome to the mating pool // Remove the most fit Chromosome so we // don't keep selecting it over and over agian. pop_copy.remove(most_fit_index); pool_size_copy--; } return mating_pool; } } <file_sep>/genetic/InheritanceExample/OtherTest.java package genetic.InheritanceExample; public class OtherTest implements GeneticInterface { public void hello() { System.out.println("hello from other test"); } } <file_sep>/README.md # nature_inspired_genetic_algo Homework for nature inspired algorithms course. Assignment is to solve the minimum make-span problem using a genetic algorithm. # How to Build and Run To compile the code, when in the nature_inspired_genetic_algo directory run ``` javac genetic/*.java ``` # Parts of a genetic algorithm 1) Initializer 2) selecter 3) recombiner 4) mutater 5) replacer # Structure of Project There are 5 interfaces, each representing a step in the genetic algorithm. There are also 3 classes. The chromosome class, the Problem class, and the GeneticAlgorithm class. The chromosome class explains itself. The Problem class is used to hold the problem parameters like num machines and num jobs. The GeneticAlgorithm class is constructed with implementations of the 5 interfaces, and is used to actually run the genetic algorithm. # Structure of the Data Data files are structured as following.. benchark3_50_101.csv 50 Machines 101 Jobs Each line in the file is 1 jobs time to completion. # Colin Didn't Know How To Do Inheritance in Java... ...So he made a folder called InheritanceExample which successfully implements inheritance. Feel free to use it to remind yourself how inheritance works if you're into that sort of thing. <file_sep>/genetic/Problem.java package genetic; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Problem { private int numMachines; private int numJobs; private int[] data; public Problem(int numMachines, int numJobs, String path) { this.numMachines = numMachines; this.numJobs = numJobs; this.parseCSV(path); } /*** * Returns an array representing the data held in a csv file. * * @param path - Path of the csv file to load data from. * @return 2D arrayList representing the data held in the csv file. */ private void parseCSV(String path) { List<Integer> records = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(path))) { String line; while ((line = br.readLine()) != null) { records.add(Integer.parseInt(line)); } } catch (IOException e) { throw new java.lang.RuntimeException("Could not parse " + path); } // Convert array list of Integer objects to array of int. this.data = new int[records.size()]; for (int i=0; i < this.data.length; i++) { this.data[i] = records.get(i).intValue(); } } /** * Accessors */ /** * Get the number of machines for this problem. * * @return Number of machines. */ public int getNumMachines() { return this.numMachines; } /** * Get the number of jobs for this problem. * * @return Number of jobs. */ public int getNumJobs() { return this.numJobs; } /** * Access the data for this problem. * * @param index Index in the data to access. * @return Time to complete the job at the specified index. */ public int getData(int index) { return this.data[index]; } /** * Overrides the builtin toString method. * * @return Problem represented as a string. */ public String toString() { return "Problem(" + this.numMachines + ", " + this.numJobs + ", " + Arrays.toString(this.data) + ")"; } }
642bde6f18ba83e9dd6bf757f4856077ad65ac57
[ "Markdown", "Java" ]
7
Java
colinrlly/nature_inspired_genetic_algo
6bcb4f2bb827b6b5bac18411b8eb74af0e725e5d
bfa53e951d72f6a8804c30718e4ae4ca50818474
refs/heads/main
<repo_name>hayoiii/MY-POTION-app<file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/data/repository/intake/IntakeDatabase.java package com.palebluedot.mypotion.data.repository.intake; import android.content.Context; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import com.palebluedot.mypotion.data.model.Intake; @Database(entities = {Intake.class}, version = 1) public abstract class IntakeDatabase extends RoomDatabase { private static IntakeDatabase instance = null; public abstract IntakeDao intakeDao(); public static IntakeDatabase getInstance(final Context context) { if(instance == null) { synchronized (IntakeDatabase.class) { instance = Room.databaseBuilder(context.getApplicationContext(), IntakeDatabase.class, "intake_calendar") .fallbackToDestructiveMigration() // 데이터베이스 갱신 시 기존의 테이블 버리고 새로 사용 .build(); } } return instance; } } <file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/data/model/Like.java package com.palebluedot.mypotion.data.model; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; import java.util.ArrayList; import java.util.List; @Entity(tableName = "like") public class Like { @PrimaryKey(autoGenerate = true) @ColumnInfo(name="rowid") public int id; @ColumnInfo(name="name") public String name; @ColumnInfo(name="factory") public String factory; @ColumnInfo(name="serial_no") public String serialNo; @ColumnInfo(name="effect_tag") public List<String> effectTags; public Like(String name, String factory, String serialNo, List<String> effectTags) { this.name = name; this.factory = factory; this.serialNo = serialNo; this.effectTags = effectTags; } } <file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/util/MyCode.java package com.palebluedot.mypotion.util; public class MyCode { public static final int PRODUCE_CANCEL = 4000; public static int PRODUCE_COMPLETE = 1000; } <file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/feature/produce/CustomNameStep.java package com.palebluedot.mypotion.feature.produce; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import androidx.annotation.NonNull; import com.google.android.material.textfield.TextInputEditText; import com.palebluedot.mypotion.R; import com.palebluedot.mypotion.data.repository.RepositoryCallback; import com.palebluedot.mypotion.data.repository.mypotion.MyPotionRepository; import ernestoyaquello.com.verticalstepperform.Step; public class CustomNameStep extends Step<String> { private static final int MIN_CHARACTERS_ALARM_NAME = 2; private MyPotionRepository repository; private TextInputEditText nameEditText; private String minCharacterErrorString; private String duplicationErrorString; private String old = null; private boolean EDIT_MODE = false; boolean isDuplicated = false; public CustomNameStep(String title) { super(title); } public void setOld(String old) { this.old = old; EDIT_MODE = true; } @NonNull @Override protected View createStepContentLayout() { repository = new MyPotionRepository(getContext()); // We create this step view programmatically nameEditText = new TextInputEditText(getContext()); // Typeface typeFace = Typeface.createFromAsset(getContext().getAssets(), "font/r_nanumbarunpen.ttf"); // nameEditText.setTypeface(typeFace); if(EDIT_MODE) nameEditText.setText(old); nameEditText.setHint(R.string.form_hint_name); nameEditText.setSingleLine(true); nameEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) { markAsCompletedOrUncompleted(true); } @Override public void afterTextChanged(Editable s) {} }); nameEditText.setOnEditorActionListener((v, actionId, event) -> { getFormView().goToNextStep(true); return false; }); minCharacterErrorString = getContext().getResources().getString(R.string.form_error_min_characters); duplicationErrorString = getContext().getResources().getString(R.string.form_error_potion_duplication); return nameEditText; } @Override protected void onStepOpened(boolean animated) { // No need to do anything here } @Override protected void onStepClosed(boolean animated) { // No need to do anything here } @Override protected void onStepMarkedAsCompleted(boolean animated) { // No need to do anything here } @Override protected void onStepMarkedAsUncompleted(boolean animated) { // No need to do anything here } @Override public String getStepData() { Editable text = nameEditText.getText(); if (text != null) { return text.toString(); } return ""; } @Override public String getStepDataAsHumanReadableString() { String name = getStepData(); return name.equals("") ? getContext().getString(R.string.form_empty_field) : name; } @Override public void restoreStepData(String data) { if (nameEditText != null) { nameEditText.setText(data); } } @Override protected IsDataValid isStepDataValid(String stepData) { if (stepData.length() < MIN_CHARACTERS_ALARM_NAME) { String titleError = String.format(minCharacterErrorString, MIN_CHARACTERS_ALARM_NAME); return new IsDataValid(false, titleError); } else { if(EDIT_MODE && old.equals(stepData)) return new IsDataValid(true); if(repository.isDuplicatedAlias(getStepData())) return new IsDataValid(false, duplicationErrorString); } return new IsDataValid(true); } RepositoryCallback<Boolean> callback = new RepositoryCallback<Boolean>() { @Override public void onComplete(Boolean result) { isDuplicated = result; isStepDataValid(getStepData()); } }; } <file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/data/model/Intake.java package com.palebluedot.mypotion.data.model; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.Ignore; import androidx.room.PrimaryKey; @Entity(tableName = "intake_calendar") public class Intake { @PrimaryKey(autoGenerate = true) @ColumnInfo(name="rowid") public int id; @ColumnInfo(name="intake_date") public String date; @ColumnInfo(name = "intake_time") public String time; @ColumnInfo(name = "total_times") public int totalTimes; @ColumnInfo(name = "when_flag") public int whenFlag; @ColumnInfo(name = "potion_id") public int potionId; public Intake(String date, String time, int totalTimes, int whenFlag, int potionId) { this.date = date; this.time = time; this.totalTimes = totalTimes; this.whenFlag = whenFlag; this.potionId = potionId; } @Ignore public Intake(int id, String date, String time, int totalTimes, int whenFlag, int potionId) { this.id = id; this.date = date; this.time = time; this.totalTimes = totalTimes; this.whenFlag = whenFlag; this.potionId = potionId; } } <file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/util/WhenManager.java package com.palebluedot.mypotion.util; import android.content.SharedPreferences; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; public class WhenManager { public static final String SP_NAME = "when"; public static final int WHEN_1_BREAKFAST = 0x01; public static final int WHEN_2_AM = 0x02; public static final int WHEN_3_LUNCH = 0x04; public static final int WHEN_4_PM = 0x08; public static final int WHEN_5_DINNER = 0x10; public static final int WHEN_6_NIGHT = 0x20; public static final String BREAKFAST_BEGIN = "breakfast_begin"; public static final String BREAKFAST_END = "breakfast_end"; public static final String AM_END = "am_end"; public static final String LUNCH_END = "lunch_end"; public static final String PM_END = "pm_end"; public static final String DINNER_END = "dinner_end"; public static final int[] WHEN_FLAGS = { WHEN_1_BREAKFAST, WHEN_2_AM, WHEN_3_LUNCH, WHEN_4_PM, WHEN_5_DINNER, WHEN_6_NIGHT }; public static final String[] WHEN_SP_KEYS = { BREAKFAST_END, AM_END, LUNCH_END, PM_END, DINNER_END }; public static final Map<String, Integer> WHEN_SP_DEFAULT = new HashMap<String, Integer>() { { put(BREAKFAST_BEGIN, 6); put(BREAKFAST_END, 8); put(AM_END, 11); put(LUNCH_END, 14); put(PM_END, 17); put(DINNER_END, 20); } }; public static final String SharedPrefFile = "com.palebluedot.SharedPreferences"; public static String getWhenText(int flag) { String value = ""; switch (flag) { case WHEN_1_BREAKFAST: value = "아침"; break; case WHEN_2_AM: value = "오전"; break; case WHEN_3_LUNCH: value = "점심"; break; case WHEN_4_PM: value = "오후"; break; case WHEN_5_DINNER: value = "저녁"; break; case WHEN_6_NIGHT: value = "밤"; break; default: value = "?"; } return value; } public static int getWhenValue(SharedPreferences preferences, int hour_24) { int m = preferences.getInt(BREAKFAST_END, 8); int a = preferences.getInt(AM_END, 11); int l = preferences.getInt(LUNCH_END, 14); int p = preferences.getInt(PM_END, 17); int d = preferences.getInt(DINNER_END, 20); if (hour_24 >= 6 && hour_24 < m) { return WHEN_FLAGS[0]; } else if (hour_24 >= m && hour_24 < a) { return WHEN_FLAGS[1]; } else if (hour_24 >= a && hour_24 < l) { return WHEN_FLAGS[2]; } else if (hour_24 >= l && hour_24 < p) { return WHEN_FLAGS[3]; } else if (hour_24 >= p && hour_24 < d) { return WHEN_FLAGS[4]; } else if (hour_24 >= d && hour_24 <= 24) { return WHEN_FLAGS[5]; } else return 0; } public static int now(SharedPreferences preferences) { Calendar now = new GregorianCalendar(); int hour = now.get(Calendar.HOUR_OF_DAY); int m = preferences.getInt("morningEnd", 8); int a = preferences.getInt("amEnd", 11); int l = preferences.getInt("lunchEnd", 14); int p = preferences.getInt("pmEnd", 17); int d = preferences.getInt("dinnerEnd", 20); if(hour>=6 && hour<m){ return WHEN_FLAGS[0]; } else if(hour>=m && hour < a){ return WHEN_FLAGS[1]; } else if(hour>=a && hour < l){ return WHEN_FLAGS[2]; } else if(hour>=l && hour < p){ return WHEN_FLAGS[3]; } else if(hour>=p && hour < d){ return WHEN_FLAGS[4]; } else if(hour>=d && hour <= 24){ return WHEN_FLAGS[5]; } else return 0; } } <file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/data/model/MyPotionId.java package com.palebluedot.mypotion.data.model; import androidx.room.ColumnInfo; import androidx.room.Entity; public class MyPotionId { @ColumnInfo(name = "rowid") public int id; } <file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/data/repository/mypotion/MyPotionRepository.java package com.palebluedot.mypotion.data.repository.mypotion; import android.content.Context; import android.os.AsyncTask; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.palebluedot.mypotion.data.model.MyPotion; import com.palebluedot.mypotion.data.model.MyPotionId; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.Executors; public class MyPotionRepository { private MyPotionDatabase database; MyPotionDao dao; MutableLiveData<List<MyPotion>> listData; public MyPotionRepository(Context context) { this.database = MyPotionDatabase.getInstance(context); this.dao = database.myPotionDao(); listData = new MutableLiveData<>(); } public void insert(MyPotion potion) { Runnable runnable = new Runnable() { @Override public void run() { dao.insert(potion); } }; Executor diskIO = Executors.newSingleThreadExecutor(); diskIO.execute(runnable); } public void update(MyPotion potion) { Runnable runnable = new Runnable() { @Override public void run() { dao.update(potion); } }; Executor diskIO = Executors.newSingleThreadExecutor(); diskIO.execute(runnable); } public void delete(MyPotion potion) { Runnable runnable = new Runnable() { @Override public void run() { dao.delete(potion); } }; Executor diskIO = Executors.newSingleThreadExecutor(); diskIO.execute(runnable); } public LiveData<List<MyPotion>> getHomeList(){ HomeListService service = new HomeListService(); try { service.execute().get(); return listData; } catch (ExecutionException e) { e.printStackTrace(); return null; } catch (InterruptedException e) { e.printStackTrace(); return null; } } private class HomeListService extends AsyncTask<Void, Void, LiveData<List<MyPotion>>> { @Override protected LiveData<List<MyPotion>> doInBackground(Void... voids) { List<MyPotion> result = dao.getAllExceptFinsihed(); listData.postValue(result); return listData; } } public boolean isDuplicatedAlias(String alias) { DuplicatedAliasService service = new DuplicatedAliasService(alias); try { return service.execute().get(); } catch (ExecutionException e) { e.printStackTrace(); return false; } catch (InterruptedException e) { e.printStackTrace(); return false; } } private class DuplicatedAliasService extends AsyncTask<Void, Void, Boolean> { private String alias; public DuplicatedAliasService(String alias) { this.alias = alias; } @Override protected Boolean doInBackground(Void... voids) { MyPotionId[] result = dao.findDuplicatedAliasId(alias); return result.length != 0; } } } <file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/data/repository/detail/DetailApi.java package com.palebluedot.mypotion.data.repository.detail; import com.palebluedot.mypotion.data.repository.detail.model.DetailVo; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; public interface DetailApi { String BASE_URL = "https://openapi.foodsafetykorea.go.kr/api/"; //PRDLST_REPORT_NO=200400200021640 @GET("915bdf37e06e4760ac88/C003/json/1/1/PRDLST_REPORT_NO={serialNo}") Call<DetailVo> getDetail(@Path("serialNo") String SerialNo); } <file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/data/model/PotionItem.java package com.palebluedot.mypotion.data.model; import androidx.annotation.NonNull; public class PotionItem { private String product; private String factory; private String serialNo; public PotionItem(String product, String factory, String serialNo) { this.product = product; this.factory = factory; this.serialNo = serialNo; } public String getProduct() { return product; } public void setProduct(String product) { this.product = product; } public String getFactory() { return factory; } public void setFactory(String factory) { this.factory = factory; } public String getSerialNo() { return serialNo; } public void setSerialNo(String serialNo) { this.serialNo = serialNo; } @NonNull @Override public String toString() { return "Potion{" + "product='" + product + '\'' + ", factory='" + factory + '\'' + ", serialNo='" + serialNo + '\'' + '}'; } } <file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/feature/produce/ProduceActivity.java package com.palebluedot.mypotion.feature.produce; import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import com.palebluedot.mypotion.R; import com.palebluedot.mypotion.data.model.MyPotion; import com.palebluedot.mypotion.data.repository.mypotion.MyPotionRepository; import com.palebluedot.mypotion.util.Constant; import com.palebluedot.mypotion.util.MyCode; import java.util.GregorianCalendar; import java.util.List; import ernestoyaquello.com.verticalstepperform.VerticalStepperFormView; import ernestoyaquello.com.verticalstepperform.listener.StepperFormListener; public class ProduceActivity extends AppCompatActivity implements StepperFormListener { private MyPotionRepository repository; private VerticalStepperFormView verticalStepperForm; private final String[] steps = {"포션 이름", "메모", "효과 태그", "시작 날짜", "복용 주기"}; private final String[] mySteps = {"제품명", "제조사", "포션 이름","메모", "효과 태그", "시작 날짜", "복용 주기"}; //for customizing private CustomNameStep customNameStep; private OptionalStep factoryStep; private PeriodStep periodStep; private BeginDateStep beginDateStep; private OptionalStep aliasStep; private OptionalStep memoStep; private TagsStep tagsStep; private int id; private String name; private String factory; private String effect; private String serialNo; private boolean EDIT_MODE = false; private boolean CUSTOM_MODE = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); repository = new MyPotionRepository(this); setContentView(R.layout.activity_produce); // Toolbar toolbar = findViewById(R.id.main_toolbar); // setSupportActionBar(toolbar); verticalStepperForm = findViewById(R.id.stepper_form); Intent intent = getIntent(); EDIT_MODE = intent.getBooleanExtra("EDIT_MODE", false); CUSTOM_MODE = intent.getBooleanExtra("CUSTOM_MODE", false); /* null when CUSTOM_MODE */ name = intent.getStringExtra("name"); factory = intent.getStringExtra("factory"); effect = intent.getStringExtra("effect"); serialNo = intent.getStringExtra("serialNo"); aliasStep = new OptionalStep(steps[0], OptionalStep.FORM_TYPE_ALIAS); aliasStep.setData(name); memoStep = new OptionalStep(steps[1], OptionalStep.FORM_TYPE_MEMO); tagsStep = new TagsStep(steps[2]); if(!CUSTOM_MODE) tagsStep.initTags(effect); beginDateStep = new BeginDateStep(steps[3]); periodStep = new PeriodStep(steps[4]); if(EDIT_MODE){ aliasStep.setOld(intent.getStringExtra("alias")); memoStep.setOld(intent.getStringExtra("memo")); tagsStep.initTags(intent.getStringExtra("effect")); beginDateStep.setOld(intent.getStringExtra("beginDate")); periodStep.setOld(intent.getIntExtra("days", 1), intent.getIntExtra("times", 1), intent.getIntExtra("whenFlag", 0)); } if(CUSTOM_MODE) { //aliasStep 대신 customNameStep 사용 //factoryStep 추가 customNameStep = new CustomNameStep(mySteps[0]); factoryStep = new OptionalStep(mySteps[1], OptionalStep.FORM_TYPE_FACTORY); if(EDIT_MODE) { customNameStep.setOld(name); factoryStep.setOld(factory); } verticalStepperForm .setup(this, customNameStep, factoryStep, aliasStep, memoStep, tagsStep, beginDateStep, periodStep) .init(); } else { verticalStepperForm .setup(this, aliasStep, memoStep, tagsStep, beginDateStep, periodStep) .init(); } } @Override public void onCompletedForm() { String alias = aliasStep.getStepData(); if(CUSTOM_MODE) { name = customNameStep.getStepData(); factory = factoryStep.getStepData(); } //alias is non null if (alias.equals("")) alias = name; String memo = memoStep.getStepData(); List<String> tags = tagsStep.getStepData(); int mDate[] = beginDateStep.getStepData(); GregorianCalendar calendar = new GregorianCalendar(mDate[0], mDate[1], mDate[2]); String dateStr = Constant.DATE_FORMAT.format(calendar.getTime()); PeriodStep.PeriodHolder periodHolder = periodStep.getStepData(); int days = periodHolder.days; int times = periodHolder.times; int whenFlag = periodHolder.whenFlag; MyPotion potion = new MyPotion(serialNo, alias, name, factory, dateStr, null, tags, memo, days, times, whenFlag); repository.insert(potion); finishActivity(MyCode.PRODUCE_COMPLETE); finish(); } // TODO : sweet alert @Override public void onCancelledForm() { // SweetAlertDialog cancleSAD = AlertUtil.createCancleSAD(this, null); // cancleSAD.show(); // AlertUtil.setSAD(this, cancleSAD, R.color.warning_stroke_color); finishActivity(MyCode.PRODUCE_CANCEL); finish(); } @Override public void onBackPressed() { super.onBackPressed(); onCancelledForm(); } } <file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/data/repository/detail/DetailRepository.java package com.palebluedot.mypotion.data.repository.detail; import android.util.Log; import androidx.annotation.NonNull; import com.palebluedot.mypotion.data.model.PotionDetail; import com.palebluedot.mypotion.data.repository.RepositoryCallback; import com.palebluedot.mypotion.data.repository.RetrofitUtil; import com.palebluedot.mypotion.data.repository.detail.model.DetailVo; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class DetailRepository { private static DetailRepository instance = null; private RetrofitUtil mRetrofitUtil; private DetailApi api; private DetailRepository() { this.mRetrofitUtil = RetrofitUtil.getInstance(); this.api = mRetrofitUtil.getDetailApi(); } public static DetailRepository getInstance() { if(instance == null) { synchronized (DetailRepository.class) { if(instance == null) { instance = new DetailRepository(); } } } return instance; } public void fetchDetail(@NonNull String serialNo, @NonNull RepositoryCallback<PotionDetail> callback) { //TODO: error handling Call<DetailVo> res = api.getDetail(serialNo); res.enqueue(new Callback<DetailVo>() { @Override public void onResponse(Call<DetailVo> call, Response<DetailVo> response) { if (response.body() != null) { DetailVo detailVo = (DetailVo) response.body(); String code = detailVo.getC003().getRESULT().getCODE(); if (code.equals("INFO-000")) { String name = detailVo.getC003().getRow().get(0).getPRDLST_NM(); String factory = detailVo.getC003().getRow().get(0).getBSSH_NM(); String shape = detailVo.getC003().getRow().get(0).getDISPOS(); String takeWay = detailVo.getC003().getRow().get(0).getNTK_MTHD(); String effect = detailVo.getC003().getRow().get(0).getPRIMARY_FNCLTY(); String caution = detailVo.getC003().getRow().get(0).getIFTKN_ATNT_MATR_CN(); String storeWay = detailVo.getC003().getRow().get(0).getCSTDY_MTHD(); String rawMaterials = detailVo.getC003().getRow().get(0).getRAWMTRL_NM(); String expiration = detailVo.getC003().getRow().get(0).getPOG_DAYCNT(); PotionDetail data = new PotionDetail(takeWay, name, rawMaterials, expiration, effect, factory, caution, storeWay, shape); callback.onComplete(data); } else if(code.equals("INFO-200")) { //해당하는 데이터가 없을 때 callback.onComplete(null); } else { //TODO: 오류 코드 시 처리 } } } @Override public void onFailure(Call<DetailVo> call, Throwable t) { Log.e("Err", t.getMessage()); } }); } } <file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/data/repository/results/SearchResultsRepository.java package com.palebluedot.mypotion.data.repository.results; import android.app.Application; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import androidx.annotation.NonNull; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.palebluedot.mypotion.data.model.PotionItem; import com.palebluedot.mypotion.data.model.SearchResults; import com.palebluedot.mypotion.util.NetworkUtil; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.ExecutionException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; public class SearchResultsRepository { private static SearchResultsRepository instance; @NonNull MutableLiveData<SearchResults> data; @NonNull public MutableLiveData<SearchResults> getData() { return data; } public void setData(@NonNull MutableLiveData<SearchResults> data) { this.data = data; } public static SearchResultsRepository getInstance() { if(instance == null) { synchronized (SearchResultsRepository.class) { if(instance == null) { instance = new SearchResultsRepository(); } } } return instance; } private SearchResultsRepository(){ data = new MutableLiveData<>(); } public LiveData<SearchResults> getSearchResults(Context context, String keyword, int pageNo) { if(NetworkUtil.check(context)) { HtfsInfoServiceAPI task = new HtfsInfoServiceAPI(keyword, pageNo); try { data.setValue(task.execute().get()); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } else { data.setValue(new SearchResults(null, 1, 0, 0)); // TODO: 네트워크 연결 안되어있을 때 // AlertUtil.failureCookieBar(this, "네트워크 연결").setEnableAutoDismiss(false).show(); // SearchListAdapter adapter = new SearchListAdapter(new ArrayList<>()); // mPageContainer.setVisibility(View.INVISIBLE); // mListView.setAdapter(adapter); } return data; } /*건강기능식품 서비스 api*/ private class HtfsInfoServiceAPI extends AsyncTask<Void, Void, SearchResults> { private final String BASE_URI = "http://apis.data.go.kr/1470000/HtfsInfoService/getHtfsList?ServiceKey=<KEY>%2<KEY>%3D%3D"; private String url; HtfsInfoServiceAPI(String keyword, int pageNo) { this.url = keyword == null || keyword.equals("") ? this.BASE_URI + "&pageNo=" + pageNo : this.BASE_URI + "&Prduct=" + keyword + "&pageNo=" + pageNo; } /*백그라운드 스레드가 실행되기 전, 메인 스레드에 의해 호출되는 메서드 * 주로 UI 초기화 */ @Override protected void onPreExecute() { super.onPreExecute(); // loading progress bar // dialog = new SweetAlertDialog(mContext, SweetAlertDialog.PROGRESS_TYPE); // dialog.getProgressHelper().setBarColor(ContextCompat.getColor(mContext, R.color.secondary)); // dialog.setTitle("Loading"); // dialog.setCancelable(true); // dialog.setOnCancelListener(dialog -> { // me.cancel(true); // Toast.makeText(mContext, "취소되었습니다.", Toast.LENGTH_SHORT).show(); // }); // dialog.show(); } /*실질적인 비동기 작업이 실행 * UI를 직접 제어하면 X*/ @Override protected SearchResults doInBackground(Void... voids) { List<PotionItem> results = new ArrayList<>(); int pageNo; int maxPageNo; int total; DocumentBuilderFactory dbFactoty = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = null; try { dBuilder = dbFactoty.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } Document doc = null; try { doc = dBuilder.parse(this.url); } catch (IOException | SAXException e) { Log.d("Exception", "on Document"); // TODO: error handling e.printStackTrace(); } if(doc.getDocumentElement() == null){ return null; } // root tag Objects.requireNonNull(doc.getDocumentElement()).normalize(); //page 정보 NodeList nHeaderList = doc.getElementsByTagName("header"); Node nHeader = nHeaderList.item(0); org.w3c.dom.Element eHeader = (org.w3c.dom.Element) nHeader; String sCode = getTagValue("resultCode", eHeader); if (!sCode.equals("00")) { Log.e("API error", "error code-" + sCode); // TODO: error handling return null; } // 페이지 정보 추출 NodeList nBodyList = doc.getElementsByTagName("body"); Node nBody = nBodyList.item(0); org.w3c.dom.Element eBody = (org.w3c.dom.Element) nBody; String sPageNo = getTagValue("pageNo", eBody); String sTotal = getTagValue("totalCount", eBody); //건강기능식품 리스트 받아오기 NodeList nList = doc.getElementsByTagName("item"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { org.w3c.dom.Element eElement = (org.w3c.dom.Element) nNode; String product = getTagValue("PRDUCT", eElement); String factory = getTagValue("ENTRPS", eElement); String serialNo = getTagValue("STTEMNT_NO", eElement); PotionItem item = new PotionItem(product, factory, serialNo); results.add(item); } // for end } // if end pageNo = Integer.parseInt(sPageNo); maxPageNo = (int) Math.ceil(Integer.parseInt(sTotal) / 10.0); total = Integer.parseInt(sTotal); SearchResults searchResults = new SearchResults(results, pageNo, maxPageNo, total); return searchResults; } /*doInBackground의 결과값을 받음*/ @Override protected void onPostExecute(SearchResults searchResults) { // dialog.dismiss(); // if (potions != null) { // SearchListAdapter adapter = new SearchListAdapter(potions); // mListView.setAdapter(adapter); // if (potions.size() == 0) { // CookieBar.build(activity) // .setTitle("검색결과가 없습니다.").setBackgroundColor(R.color.secondary_light) // .setTitleColor(R.color.primary_text) // .setDuration(5000) // .setEnableAutoDismiss(true) // .setSwipeToDismiss(true) // .setCookiePosition(Gravity.BOTTOM); // mPageContainer.setVisibility(View.INVISIBLE); // } // mCurrpageNo.setText(Integer.toString(pageNo)); // mMaxpageNo.setText(Integer.toString(maxPageNo)); // // mListView.setOnItemClickListener((parent, view, position, id) -> { // //Intent intent = new Intent(getApplicationContext(), DetailActivity.class); // Potion potion = (Potion) parent.getItemAtPosition(position); // // detailFragmentFromSearch = DetailFragmentFromSearch.newInstance(potion.getSerialNo()); // detailFragmentFromSearch.init(isLiked(potion.getSerialNo())); // // getSupportFragmentManager().beginTransaction() // .add(R.id.search_layout, detailFragmentFromSearch) // .addToBackStack(null) // .commit(); // }); // mPageContainer.setVisibility(View.VISIBLE); // return; // } // //검색 실패 시 // AlertUtil.createFailureSAD(mContext, "요청").show(); // mPageContainer.setVisibility(View.INVISIBLE); } private String getTagValue(String tag, org.w3c.dom.Element eElement) { NodeList nlList = eElement.getElementsByTagName(tag).item(0).getChildNodes(); Node nValue = (Node) nlList.item(0); if (nValue == null) return null; return nValue.getNodeValue(); } } } <file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/feature/produce/TagsStep.java package com.palebluedot.mypotion.feature.produce; import android.view.LayoutInflater; import android.view.View; import androidx.annotation.NonNull; import com.google.android.material.chip.Chip; import com.google.android.material.chip.ChipGroup; import com.google.android.material.textfield.MaterialAutoCompleteTextView; import com.palebluedot.mypotion.R; import com.palebluedot.mypotion.util.Constant; import com.palebluedot.mypotion.util.TagManager; import java.util.Arrays; import java.util.LinkedList; import ernestoyaquello.com.verticalstepperform.Step; public class TagsStep extends Step<LinkedList<String>> { //TODO: 다이얼로그로 빼기, 갯수 제한 넣기 private LinkedList<String> tags; private View tagsStepContent; private MaterialAutoCompleteTextView autoCompleteText; ChipGroup checkedChips; private ChipGroup allChips; private boolean EDIT_MODE = false; public TagsStep(String title) { super(title); tags = new LinkedList<>(); } public void initTags(String effect){ if(tags!=null) tags = new LinkedList<String>(TagManager.getInstance().extract(effect)); } @NonNull @Override protected View createStepContentLayout() { // We create this step view by inflating an XML layout LayoutInflater inflater = LayoutInflater.from(getContext()); tagsStepContent = inflater.inflate(R.layout.form_effect_tags, null, false); autoCompleteText = tagsStepContent.findViewById(R.id.add_tag_auto_text_view); checkedChips = tagsStepContent.findViewById(R.id.add_selected_chips); allChips = tagsStepContent.findViewById(R.id.add_chips_list); /*자동완성 검색창 초기화*/ AutoCompleteAdapter adapter = new AutoCompleteAdapter(); autoCompleteText.setAdapter(adapter); autoCompleteText.setThreshold(1); autoCompleteText.setOnItemClickListener((adapterView, view1, i, l) -> { String selectedTag = (String) adapterView.getItemAtPosition(i); if(selectedTag.charAt(0) == '#'){ addCustomizedTag(selectedTag, false); } else addToCheckedChips(selectedTag); autoCompleteText.setText(""); }); /* 전체 태그 리스트 초기화 */ int count = tags.size(); for(int i = 0; i< Constant.TAGS.length; i++){ Chip chip = new Chip(getContext()); chip.setText(Constant.TAGS[i]); chip.setCloseIconVisible(false); chip.setTag(Constant.TAGS[i]); chip.setCheckable(true); chip.setChecked(false); //allChips에서 아이템 클릭 시 chip.setOnClickListener(v -> { addToCheckedChips(v.getTag().toString()); }); allChips.addView(chip); if(tags.contains(Constant.TAGS[i])) { addToCheckedChips(Constant.TAGS[i]); count--; } } //customized tag가 있을 때 if(EDIT_MODE && count>0){ int size = tags.size(); for(int i =0; i<size; i++) { addCustomizedTag(tags.get(i), true); } } return tagsStepContent; } private void addCustomizedTag(String rawTag, boolean init) { String customizedTag = rawTag; if(!init) customizedTag = rawTag.substring(rawTag.indexOf("'")+1, rawTag.lastIndexOf("'")); Chip existingChip = ((Chip) allChips.findViewWithTag(customizedTag)); if(existingChip != null) return; Chip newChip = new Chip(getContext()); newChip.setCloseIconVisible(true); newChip.setText(customizedTag); newChip.setChipBackgroundColorResource(R.color.secondary_light); newChip.setTag(customizedTag); newChip.setCheckable(false); newChip.setOnCloseIconClickListener(v -> { Object chipTag = newChip.getTag(); if(checkedChips.findViewWithTag(chipTag) !=null) { checkedChips.removeView(newChip); tags.remove((String)chipTag); } }); checkedChips.addView(newChip, 0); if(!init) tags.add(customizedTag); } private void addToCheckedChips(String tag){ Chip existingChip = ((Chip) checkedChips.findViewWithTag(tag)); if(existingChip != null) { //이미 체크되어있는 칩이면 체크 취소 removeFromCheckedChips(tag); return; } Chip newChip = new Chip(getContext()); newChip.setCloseIconVisible(true); newChip.setText(tag); newChip.setTag(tag); newChip.setChipBackgroundColorResource(R.color.secondary_light); newChip.setCheckable(false); newChip.setOnCloseIconClickListener(v -> removeFromCheckedChips(newChip.getTag().toString())); checkedChips.addView(newChip, 0); //allChips에서 해당 chip을 checked 상태로 만들기 //TODO: checked ui 변경 ((Chip) allChips.findViewWithTag(tag)).setChecked(true); if(!tags.contains(tag)) tags.add(tag); } void removeFromCheckedChips(String tag){ Chip target = checkedChips.findViewWithTag(tag); checkedChips.removeView(target); //allChips에서 해당 chip을 unchecked 상태로 만들기 ((Chip) allChips.findViewWithTag(tag)).setChecked(false); tags.remove(tag); } @Override protected void onStepOpened(boolean animated) { // No need to do anything here } @Override protected void onStepClosed(boolean animated) { // No need to do anything here } @Override protected void onStepMarkedAsCompleted(boolean animated) { // No need to do anything here } @Override protected void onStepMarkedAsUncompleted(boolean animated) { // No need to do anything here } @Override public LinkedList<String> getStepData() { return tags; } @Override public String getStepDataAsHumanReadableString() { int num = tags.size(); if(num == 0) return getContext().getString(R.string.form_empty_field); String checkedTags= TagManager.getInstance().listToString(tags); return checkedTags; } @Override public void restoreStepData(LinkedList<String> data) { tags = new LinkedList<>(); for(int i = 0; i< Constant.TAGS.length; i++) { if (data.contains(Constant.TAGS[i])) { addToCheckedChips(Constant.TAGS[i]); data.remove(Constant.TAGS[i]); } } int num = data.size(); for(int i=0; i< num; i++){ addCustomizedTag(data.pop(), false); } } @Override protected IsDataValid isStepDataValid(LinkedList<String> stepData) { return new IsDataValid(true); } }<file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/data/repository/like/LikeDatabase.java package com.palebluedot.mypotion.data.repository.like; import android.content.Context; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.room.TypeConverters; import com.palebluedot.mypotion.data.model.Like; @Database(entities = {Like.class}, version = 1) @TypeConverters({com.palebluedot.mypotion.data.TypeConverters.class}) public abstract class LikeDatabase extends RoomDatabase { private static LikeDatabase instance = null; public abstract LikeDao likeDao(); // Singleton public static LikeDatabase getInstance(final Context context) { if(instance == null) { synchronized (LikeDatabase.class) { instance = Room.databaseBuilder(context.getApplicationContext(), LikeDatabase.class, "like") .fallbackToDestructiveMigration() // 데이터베이스 갱신 시 기존의 테이블 버리고 새로 사용 .build(); } } return instance; } } <file_sep>/LICENSE.md Copyright (C) 2021 Hayeong <file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/data/repository/detail/model/Row.java package com.palebluedot.mypotion.data.repository.detail.model; public class Row { private String NTK_MTHD; //섭취방법 private String PRDLST_NM; //품목명 private String RAWMTRL_NM; //원재료 (컴마로 구분) private String PRMS_DT; private String CRET_DTM; private String POG_DAYCNT; //유통기한 private String PRDLST_REPORT_NO; private String PRIMARY_FNCLTY; //주된 기능 private String CSTDY_MTHD; private String BSSH_NM; //제조사 private String LAST_UPDT_DTM; private String LCNS_NO; private String IFTKN_ATNT_MATR_CN; //섭취 시 주의사항 private String STDR_STND; private String DISPOS; //성상성 (생김새) private String SHAP; @Override public String toString() { return "Row{" + "NTK_MTHD='" + NTK_MTHD + '\'' + ", PRDLST_NM='" + PRDLST_NM + '\'' + ", RAWMTRL_NM='" + RAWMTRL_NM + '\'' + ", PRMS_DT='" + PRMS_DT + '\'' + ", CRET_DTM='" + CRET_DTM + '\'' + ", POG_DAYCNT='" + POG_DAYCNT + '\'' + ", PRDLST_REPORT_NO='" + PRDLST_REPORT_NO + '\'' + ", PRIMARY_FNCLTY='" + PRIMARY_FNCLTY + '\'' + ", CSTDY_MTHD='" + CSTDY_MTHD + '\'' + ", BSSH_NM='" + BSSH_NM + '\'' + ", LAST_UPDT_DTM='" + LAST_UPDT_DTM + '\'' + ", LCNS_NO='" + LCNS_NO + '\'' + ", IFTKN_ATNT_MATR_CN='" + IFTKN_ATNT_MATR_CN + '\'' + ", STDR_STND='" + STDR_STND + '\'' + ", DISPOS='" + DISPOS + '\'' + ", SHAP='" + SHAP + '\'' + '}'; } public String getNTK_MTHD() { return NTK_MTHD; } public void setNTK_MTHD(String NTK_MTHD) { this.NTK_MTHD = NTK_MTHD; } public String getPRDLST_NM() { return PRDLST_NM; } public void setPRDLST_NM(String PRDLST_NM) { this.PRDLST_NM = PRDLST_NM; } public String getRAWMTRL_NM() { return RAWMTRL_NM; } public void setRAWMTRL_NM(String RAWMTRL_NM) { this.RAWMTRL_NM = RAWMTRL_NM; } public String getPRMS_DT() { return PRMS_DT; } public void setPRMS_DT(String PRMS_DT) { this.PRMS_DT = PRMS_DT; } public String getCRET_DTM() { return CRET_DTM; } public void setCRET_DTM(String CRET_DTM) { this.CRET_DTM = CRET_DTM; } public String getPOG_DAYCNT() { return POG_DAYCNT; } public void setPOG_DAYCNT(String POG_DAYCNT) { this.POG_DAYCNT = POG_DAYCNT; } public String getPRDLST_REPORT_NO() { return PRDLST_REPORT_NO; } public void setPRDLST_REPORT_NO(String PRDLST_REPORT_NO) { this.PRDLST_REPORT_NO = PRDLST_REPORT_NO; } public String getPRIMARY_FNCLTY() { return PRIMARY_FNCLTY; } public void setPRIMARY_FNCLTY(String PRIMARY_FNCLTY) { this.PRIMARY_FNCLTY = PRIMARY_FNCLTY; } public String getCSTDY_MTHD() { return CSTDY_MTHD; } public void setCSTDY_MTHD(String CSTDY_MTHD) { this.CSTDY_MTHD = CSTDY_MTHD; } public String getBSSH_NM() { return BSSH_NM; } public void setBSSH_NM(String BSSH_NM) { this.BSSH_NM = BSSH_NM; } public String getLAST_UPDT_DTM() { return LAST_UPDT_DTM; } public void setLAST_UPDT_DTM(String LAST_UPDT_DTM) { this.LAST_UPDT_DTM = LAST_UPDT_DTM; } public String getLCNS_NO() { return LCNS_NO; } public void setLCNS_NO(String LCNS_NO) { this.LCNS_NO = LCNS_NO; } public String getIFTKN_ATNT_MATR_CN() { return IFTKN_ATNT_MATR_CN; } public void setIFTKN_ATNT_MATR_CN(String IFTKN_ATNT_MATR_CN) { this.IFTKN_ATNT_MATR_CN = IFTKN_ATNT_MATR_CN; } public String getSTDR_STND() { return STDR_STND; } public void setSTDR_STND(String STDR_STND) { this.STDR_STND = STDR_STND; } public String getDISPOS() { return DISPOS; } public void setDISPOS(String DISPOS) { this.DISPOS = DISPOS; } public String getSHAP() { return SHAP; } public void setSHAP(String SHAP) { this.SHAP = SHAP; } public Row(String NTK_MTHD, String PRDLST_NM, String RAWMTRL_NM, String PRMS_DT, String CRET_DTM, String POG_DAYCNT, String PRDLST_REPORT_NO, String PRIMARY_FNCLTY, String CSTDY_MTHD, String BSSH_NM, String LAST_UPDT_DTM, String LCNS_NO, String IFTKN_ATNT_MATR_CN, String STDR_STND, String DISPOS, String SHAP) { this.NTK_MTHD = NTK_MTHD; this.PRDLST_NM = PRDLST_NM; this.RAWMTRL_NM = RAWMTRL_NM; this.PRMS_DT = PRMS_DT; this.CRET_DTM = CRET_DTM; this.POG_DAYCNT = POG_DAYCNT; this.PRDLST_REPORT_NO = PRDLST_REPORT_NO; this.PRIMARY_FNCLTY = PRIMARY_FNCLTY; this.CSTDY_MTHD = CSTDY_MTHD; this.BSSH_NM = BSSH_NM; this.LAST_UPDT_DTM = LAST_UPDT_DTM; this.LCNS_NO = LCNS_NO; this.IFTKN_ATNT_MATR_CN = IFTKN_ATNT_MATR_CN; this.STDR_STND = STDR_STND; this.DISPOS = DISPOS; this.SHAP = SHAP; } }<file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/MainActivity.java package com.palebluedot.mypotion; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import com.getbase.floatingactionbutton.FloatingActionButton; import com.google.android.material.navigation.NavigationView; import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.fragment.NavHostFragment; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import androidx.drawerlayout.widget.DrawerLayout; import androidx.appcompat.app.AppCompatActivity; import com.palebluedot.mypotion.databinding.ActivityMainBinding; import com.palebluedot.mypotion.feature.produce.ProduceActivity; import com.palebluedot.mypotion.feature.search.SearchActivity; import com.palebluedot.mypotion.ui.home.HomeFragment; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private AppBarConfiguration mAppBarConfiguration; private ActivityMainBinding binding; private HomeFragment homeFragement; private NavController navController; private NavHostFragment navHostFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); Toolbar toolbar = binding.appBarMain.toolbar; setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); // actionBar.setDisplayShowCustomEnabled(true); // actionBar.setDisplayShowTitleEnabled(false); //기본 제목을 없애기 // actionBar.setDisplayHomeAsUpEnabled(false); //자동 뒤로가기 버튼 DrawerLayout drawer = binding.drawerLayout; NavigationView navigationView = binding.navView; // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. mAppBarConfiguration = new AppBarConfiguration.Builder( R.id.nav_home, R.id.nav_storage, R.id.nav_calendar) .setOpenableLayout(drawer) .build(); navHostFragment = (NavHostFragment) getSupportFragmentManager() .findFragmentById(R.id.nav_host_fragment_content_main); navController = navHostFragment.getNavController(); // NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main); NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration); NavigationUI.setupWithNavController(navigationView, navController); //floating action button FloatingActionButton searchBtn = findViewById(R.id.menu_btn_search); FloatingActionButton addBtn = findViewById(R.id.menu_btn_customize); searchBtn.setOnClickListener(this); addBtn.setOnClickListener(this); homeFragement = new HomeFragment(); navController.navigate(R.id.nav_home); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main_activity, menu); return true; } @Override public boolean onSupportNavigateUp() { NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main); return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp(); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.menu_btn_search: Intent intent = new Intent(this, SearchActivity.class); startActivity(intent); break; case R.id.menu_btn_customize: Intent intent1 = new Intent(this, ProduceActivity.class); intent1.putExtra("CUSTOM_MODE", true); startActivity(intent1); break; } } @Override public void onBackPressed() { super.onBackPressed(); //TODO: 앱을 종료할 것인지 확인 } }<file_sep>/MyPotion/app/src/main/java/com/palebluedot/mypotion/data/repository/RetrofitUtil.java package com.palebluedot.mypotion.data.repository; import com.palebluedot.mypotion.data.repository.detail.DetailApi; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class RetrofitUtil { private static RetrofitUtil mRetrofitUtil = new RetrofitUtil(); private DetailApi detailApi; //singleton public static RetrofitUtil getInstance() { return mRetrofitUtil; } private RetrofitUtil(){ Retrofit mRetrofit = new Retrofit.Builder().baseUrl(DetailApi.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); detailApi = mRetrofit.create(DetailApi.class); } public DetailApi getDetailApi(){ return detailApi; } }
9c8e73260938553ecad58344c48bb7b503f48565
[ "Markdown", "Java" ]
19
Java
hayoiii/MY-POTION-app
fb8858d3a31b07f84aea5920d2e1c69b07b025dd
d20e5f772ad2bbf2fa7cbaa50f6c0c449f0dc6d7
refs/heads/main
<repo_name>VDominik/portaloveRiesenia<file_sep>/updated.php <?php include_once("classes/DB.php"); use classes\DB; $db = new DB("localhost", "root", "", "hotel", 3306); $id = $_POST['id2']; $nazov = $_POST['nazov2']; $cena = $_POST['cena2']; $popis = $_POST['popis2']; $imagep = $_POST['imagep2']; // Check connection if (!$db) { die("Connection failed: " . mysqli_connect_error()); } if ($db->update($nazov,$cena,$popis,$imagep,$id)) { $db = null; header('Location: /five-hotel/admin.php'); exit; } else { header('Location: /five-hotel/admin.php'); } <file_sep>/login.php <!DOCTYPE html> <html> <head> </head> <body> <?php $conn = mysqli_connect('localhost', 'root', ''); $db = mysqli_select_db($conn,'hotel'); $username=$_POST['username']; $password=$_POST['password']; $result = mysqli_query($conn,"select * from users where meno='$username' AND heslo='$password'") or die("Failed to connect ".mysqli_error()); $row = mysqli_fetch_array($result); if($row['meno']==$username && $row['heslo']==$password){ header('Location: /five-hotel/admin.php'); }else{ header('Location: /five-hotel'); } ?> </body> </html> <file_sep>/classes/DB.php <?php namespace classes; class DB { /** * @var string */ private $host = "localhost"; /** * @var string */ private $username = "root"; /** * @var string */ private $password = ""; /** * @var string */ private $dbName = ""; /** * @var int */ private $port; /** * @var \PDO */ private $connection; /** * DB constructor. * @param $host * @param $username * @param $password * @param $dbName * @param int $port */ public function __construct($host, $username, $password, $dbName, $port = 3306) { $this->host = $host; $this->username = $username; $this->password = $<PASSWORD>; $this->dbName = $dbName; $this->port = $port; try { $connection = new \PDO("mysql:host=".$this->host.";dbname=".$this->dbName.";port=".$this->port, $this->username, $this->password); $connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $this->connection = $connection; } catch (\PDOException $exception) { echo "Error while database connect " . $exception->getMessage(); } } /** * @return \PDO */ public function getConnection() { return $this->connection; } /** * @param $connectio */ public function setConnection($connectio) { if($connectio instanceof \PDO) { $this->connection = $connectio; } } /** * @return array */ public function getRooms() { $sql = "SELECT * FROM rooms ORDER BY id"; $stmt = $this->connection->prepare($sql); $stmt->execute(); return $stmt->fetchAll(\PDO::FETCH_ASSOC); } public function delete($id) { $sql = "DELETE FROM rooms WHERE id = '$id'"; $stmt = $this->connection->prepare($sql); $stmt->execute(); } public function update($nazov, $cena, $popis, $imagep, $id) { $sql = "UPDATE rooms SET Nazov='$nazov',Cena='$cena',Popis='$popis',image_path='$imagep' WHERE id = '$id'"; $stmt = $this->connection->prepare($sql); $stmt->execute(); } public function add($nazov, $cena, $popis, $imagep) { $sql = "INSERT INTO rooms (id,Nazov,Cena,Popis,image_path) VALUES ('NULL','$nazov','$cena','$popis','$imagep')"; $stmt = $this->connection->prepare($sql); $stmt->execute(); } }<file_sep>/admin_rooms.php <?php include_once("classes/DB.php"); use classes\DB; $db = new DB("localhost", "root", "", "hotel", 3306); $Room = $db->getRooms(); ?> <?php foreach ($Room as $key => $Room) { if ($Room['id'] === 'External') { ?> <div class="about lobster-font-family"> <div class="container"> <div class="row" style="padding: 20px"> <div class="col-lg-4 col-12"> <div class="img"> <img src="<?php echo $Room['image_path']; ?>"> </div> </div> <div class="col-lg-8 col-12"> <div class="block"> <div> <strong> <?php echo $Room['Cena']; ?></strong> <h5><?php echo $Room['Nazov']; ?></h5> <p style="height: 100px; overflow: hidden"><?php echo $Room['Popis']; ?></p> <form action="readMore.php" method="post" style="float: right"> <input type="hidden" name="id" value="<?php echo $Room['id']; ?>"> <input type="hidden" name="Nazov" value="<?php echo $Room['Nazov']; ?>"> <input type="hidden" name="Cena" value="<?php echo $Room['Cena']; ?>"> <input type="hidden" name="Popis" value="<?php echo $Room['Popis']; ?>"> <input type="hidden" name="image_path" value="<?php echo $Room['image_path']; ?>"> <button type="submit" value="submit" >Read more</button> </form> <form action="delete.php" method="post" style="float: left"> <input type="hidden" name="id" value="<?php echo $Room['id']; ?>"> <button type="submit" style="background-color: red" value="submit" onclick="return confirm('Are you sure you want to delete <?php echo $Room['id']; ?> ?');">Delete room</button> </form> <form action="update.php" method="post"> <input type="hidden" name="id" value="<?php echo $Room['id']; ?>"> <input type="hidden" name="Nazov" value="<?php echo $Room['Nazov']; ?>"> <input type="hidden" name="Cena" value="<?php echo $Room['Cena']; ?>"> <input type="hidden" name="Popis" value="<?php echo $Room['Popis']; ?>"> <input type="hidden" name="image_path" value="<?php echo $Room['image_path']; ?>"> <button type="submit" value="submit">Edit room</button> </form> </div> </div> </div> </div> </div> </div> <?php } else { ?> <div class="about lobster-font-family"> <div class="container"> <div class="row" style="padding: 20px"> <div class="col-lg-4 col-12"> <div class="img"> <img style="height: 450px; width: 580px; overflow: hidden" src="<?php echo $Room['image_path']; ?>"> </div> </div> <div class="col-lg-8 col-12"> <div class="block"> <div> <strong> <?php echo $Room['Cena']; ?> €</strong> <h5><?php echo $Room['Nazov']; ?></h5> <p style="height: 100px; overflow: hidden"><?php echo $Room['Popis']; ?></p> <form action="readMore.php" method="post" style="float: right"> <input type="hidden" name="id" value="<?php echo $Room['id']; ?>"> <input type="hidden" name="Nazov" value="<?php echo $Room['Nazov']; ?>"> <input type="hidden" name="Cena" value="<?php echo $Room['Cena']; ?>"> <input type="hidden" name="Popis" value="<?php echo $Room['Popis']; ?>"> <input type="hidden" name="image_path" value="<?php echo $Room['image_path']; ?>"> <button type="submit" value="submit" >Read more</button> </form> <form action="delete.php" method="post" style="float: left"> <input type="hidden" name="id" value="<?php echo $Room['id']; ?>"> <button type="submit" style="background-color: red" value="submit" onclick="return confirm('Are you sure you want to delete <?php echo $Room['Nazov']."#"; echo $Room['id']; ?> ?');">Delete room</button> </form> <form action="update.php" method="post"> <input type="hidden" name="id" value="<?php echo $Room['id']; ?>"> <input type="hidden" name="nazov" value="<?php echo $Room['Nazov']; ?>"> <input type="hidden" name="cena" value="<?php echo $Room['Cena']; ?>"> <input type="hidden" name="popis" value="<?php echo $Room['Popis']; ?>"> <input type="hidden" name="image_path" value="<?php echo $Room['image_path']; ?>"> <button type="submit" value="submit">Edit room</button> </form> </div> </div> </div> </div> </div> </div> <?php } } ?> <file_sep>/admin.php <!DOCTYPE html> <html> <head> <?php include_once ("header.php"); ?> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light text-capitalize main-font-family"> <div class="container"> <a class="navbar-brand" href="index.php"><img src="imgs/logo.png" alt="#" /></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#show-menu" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="admin.php"><h1>Admin center</h1></a> </div> </nav> <div class="about lobster-font-family"> <div style="text-align: center;"> <h1 style=" margin-top: 10%" class="text-capitalize" id="room">rooms & suits</h1> </div> <div style="text-align: center"> <a href="add.php"><button type="submit" value="submit">Add room</button></a> </div> <?php include_once ("admin_rooms.php"); ?> </div> <?php include_once ("footer.php"); ?> </body> </html><file_sep>/rooms.php <?php include_once("classes/DB.php"); use classes\DB; $db = new DB("localhost", "root", "", "hotel", 3306); $Room = $db->getRooms(); ?> <h2 class="text-capitalize" id="room">rooms & suits</h2> <?php foreach ($Room as $key => $Room) { if ($Room['Nazov'] === 'External') { ?> <div class="about lobster-font-family"> <div class="container"> <div class="row" style="padding: 20px"> <div class="col-lg-4 col-12"> <div class="img"> <img src="<?php echo $Room['image_path']; ?>"> </div> </div> <div class="col-lg-8 col-12"> <div class="block"> <div> <strong> <?php echo $Room['Cena']; ?></strong> <h5><?php echo $Room['Nazov']; ?></h5> <p style="height: 100px; overflow: hidden"><?php echo $Room['Popis']; ?></p> <button><a href="readMore.php" class="text-capitalize">Read more</a></button> </div> </div> </div> </div> </div> </div> <?php } else { ?> <div class="about lobster-font-family"> <div class="container"> <div class="row" style="padding: 20px"> <div class="col-lg-4 col-12"> <div class="img"> <img style="height: 450px; width: 580px; overflow: hidden" src="<?php echo $Room['image_path']; ?>"> </div> </div> <div class="col-lg-8 col-12"> <div class="block"> <div> <strong> <?php echo $Room['Cena']; ?> €</strong> <h5><?php echo $Room['Nazov']; ?></h5> <p style="height: 100px; overflow: hidden"><?php echo $Room['Popis']; ?></p> <form action="readMore.php" method="post" style="float: right"> <input type="hidden" name="id" value="<?php echo $Room['id']; ?>"> <input type="hidden" name="Nazov" value="<?php echo $Room['Nazov']; ?>"> <input type="hidden" name="Cena" value="<?php echo $Room['Cena']; ?>"> <input type="hidden" name="Popis" value="<?php echo $Room['Popis']; ?>"> <input type="hidden" name="image_path" value="<?php echo $Room['image_path']; ?>"> <button type="submit" value="submit" >Read more</button> </form> </div> </div> </div> </div> </div> </div> <?php } } ?> </div> </div> </div> <file_sep>/footer.php <script src="js/jquery-3.3.1.min.js"></script> <script src="js/bootstrap.min.js"></script> <script> $(function () { 'use strict'; var winH = $(window).height(); $('header').height(winH); $('.navbar ul.navbar-nav li a').on('click', function (e) { var getAttr = $(this).attr('href'); e.preventDefault(); $('html').animate({scrollTop: $(getAttr).offset().top}, 1000); }); }); </script><file_sep>/update.php <?php include_once("classes/DB.php"); use classes\DB; $db = new DB("localhost", "root", "", "hotel", 3306); $id = $_POST['id']; $nazov = $_POST['nazov']; $cena = $_POST['cena']; $popis = $_POST['popis']; $imagep = $_POST['image_path']; if (!$db) { die("Connection failed: " . mysqli_connect_error()); } ?> <!DOCTYPE html> <html> <head> <?php include_once ("header.php"); ?> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light text-capitalize main-font-family"> <div class="container"> <a class="navbar-brand" href="index.php"><img src="imgs/logo.png" alt="#" /></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#show-menu" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="admin.php"><h1>Admin center</h1></a> </div> </nav> <div style="margin-top: 10%" class="about lobster-font-family"> <<h1 style="text-align: center">EDIT ROOM</h1> <form style="text-align: center;" action="updated.php" method="post"> <label>ID</label> <input type="text" name="id2" value="<?php echo $id ?>"><br /><br /> <label>Nazov</label> <input type="text" name="nazov2" value="<?php echo $nazov ?>"><br /><br /> <label>Cena</label> <input type="text" name="cena2" value="<?php echo $cena ?>"><br /><br /> <label>Popis</label> <input type="text" name="popis2" value="<?php echo $popis ?>"><br /><br /> <label>Image_path</label> <input type="text" name="imagep2" value="<?php echo $imagep ?>"><br /><br /> <button type="submit" value="submit">Edit room</button> </form> </div> </body> </html> <file_sep>/index.php <!DOCTYPE html> <html> <head> <?php include_once ("header.php"); ?> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light text-capitalize main-font-family"> <div class="container"> <a class="navbar-brand" href="index.php"><img src="imgs/logo.png" alt="#" /></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#show-menu" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="show-menu"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#home">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#room">rooms</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Features </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">link</a> <a class="dropdown-item" href="#">Another link</a> <a class="dropdown-item" href="#">Another link</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link" href="#blog">blog</a> </li> <li class="nav-item"> <a class="nav-link" href="#contact">contacts</a> </li> <li class="nav-item book d-flex align-items-center"> <a class="nav-link" href="#">book now</a> </li> <li class="nav-item"> <a class="nav-link" href="#login"">admin login</a> </li> </ul> </div> </div> </nav> <header id="home"> <div class="small-container"> <form class="main-font-family text-center"> <input type="search"> <i class="fas fa-search"></i> <input type="submit" value="Search"> </form> <div class="row"> <div class="col-lg-4 col-12 lobster-font-family d-flex align-items-center"> <h2>It is a long established fact that a reader will be distracted by the readablen</h2> <button><a href="#">About hotel</a></button> </div> </div> <div class="h-slider roboto-font-family welcome d-flex align-items-center justify-content-center"> <h1 class="text-capitalize">Welcome to <br><span>five hotel</span></h1> <div id="headerslider" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item carousel-three active"></div> <div class="carousel-item carousel-two"></div> <div class="carousel-item carousel-one"></div> </div> <a class="carousel-control-prev" href="#headerslider" role="button" data-slide="prev"> <i class="fas fa-angle-double-left"></i> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#headerslider" role="button" data-slide="next"> <i class="fas fa-angle-double-right"></i> <span class="sr-only">Next</span> </a> </div> </div> </div> <div class="st-rec"></div> <div class="rd-rec"></div> </header> <div class="about lobster-font-family"> <div class="container"> <h2 class="text-center text-capitalize">About our hotel</h2> <img src="imgs/shape.png"> <div class="row"> <div class="col-lg-6 col-12"> <h4>A best place to enjoy your life</h4> <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. <NAME>, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered </p> <button><a href="#">Read more</a></button> </div> <div class="col-lg-6 col-12"> <div class="img"></div> </div> </div> <div class="about lobster-font-family"> <?php include_once ("rooms.php"); ?> </div> <!-- <div class="about lobster-font-family"> <div class="container"> <h2 class="text-capitalize" id="room">rooms & suits</h2> <div class="row"> <div class="col-lg-4 col-12"> <div class="img"></div> </div> <div class="col-lg-8 col-12"> <div class="block"> <div> <img src="imgs/shape.png"> <strong>$400</strong> <h5>luxury rooms</h5> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters,</p> <button><a href="#" class="text-capitalize">Read more</a></button> </div> </div> </div> </div> </div> </div> --> <div class="gallery lobster-font-family" id="blog"> <div class="container"> <h2 class="text-calitalize text-center">Our gallery</h2> <div class="row"> <div class="col-lg-4 col-md-6 col-12"> <div class="pic-one"><h4>Relaxed swimming</h4></div> <div class="pic-two"><h4>Spacious Accommodtion</h4></div> </div> <div class="col-lg-4 col-md-6 col-12"> <div class="pic-three active"><h4>Yoga Wellness</h4></div> </div> <div class="col-lg-4 col-md-6 col-12"> <div class="pic-four"><h4>Romantic dinner</h4></div> <div class="pic-five"><h4>Apa & Wellness</h4></div> </div> </div> </div> </div> <div class="slider main-font-family"> <h2 class="text-center text-capitalize main-font-family">what our clients say</h2> <div id="slideToNext" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#slideToNext" data-slide-to="0" class="active"></li> <li data-target="#slideToNext" data-slide-to="1"></li> <li data-target="#slideToNext" data-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <div class="carousel-caption d-block"> <img src="imgs/pic7.jpg"> <h5>jone due</h5> <p>It is a long established fact that a reader wil l be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters,</p> </div> </div> <div class="carousel-item"> <div class="carousel-caption d-block"> <img src="imgs/pic7.jpg"> <h5>jone due</h5> <p>It is a long established fact that a reader wil l be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters,</p> </div> </div> <div class="carousel-item"> <div class="carousel-caption d-block"> <img src="imgs/pic7.jpg"> <h5>jone due</h5> <p>It is a long established fact that a reader wil l be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters,</p> </div> </div> </div> </div> </div> <div class="contact main-font-family text-center"> <div class="container"> <h2 id="contact">Get in touch</h2> <div class="row"> <div class="col-6"> <div class="contact-form"> <form> <input type="text" placeholder="Name"> <input type="email" placeholder="Email"> <input type="text" placeholder="Phone"> <textarea placeholder="Message"></textarea> <input type="submit" value="submit"> </form> </div> </div> <div class="col-6"> <h2 class="text-right">Book Your Holiday Best for relaxed retreats and cultural encounters</h2> <img src="imgs/shape.png"> </div> </div> </div> <div></div> </div> <footer class="noto-font-family"> <div class="overlay"> <div class="container"> <div class="row"> <div class="col-lg-4 col-md-6 col-12"> <h3>Useful links</h3> <ul class="text-capitalize"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Rooms</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Contacts</a></li> </ul> </div> <div class="col-lg-4 col-md-6 col-12"> <h3>Find us</h3> <p>Healing Center, 176 W Street name,<br> New York, NY 10014, US<br> (+71) 987 654 3210<br> (+71) 987 654 3210<br> <EMAIL> </p> </div> <div class="col-lg-4 col-md-6 col-12 form"> <h3>News letter</h3> <form> <input type="email" placeholder="Email"> <input type="submit"> </form> <ul> <li><a href="#"><i class="fab fa-facebook-f"></i></a></li> <li><a href="#"><i class="fab fa-twitter"></i></a></li> <li><a href="#"><i class="fab fa-instagram"></i></a></li> </ul> </div> </div> </div> </div> </footer> <div class="copyright noto-font-family"> <p>© 2019 All Rights Reserved. Design by <a href="https://html.design/">Free Html Templates</a></p> </div> <div style="align-content: center; background-color: lightgray" id="login"> <form action="login.php" method = "post" style="text-align: center"> <h3><strong>Admin login</strong></h3> <label for="username">Username</label> <input type="username" id="username" name="username"><br /><br /> <label for="password">Password:</label> <input type="<PASSWORD>" id="password" name="password"><br /><br /> <button type = "submit" style="text-align: center">Login</button> </div> <?php include_once ("footer.php"); ?> </body> </html><file_sep>/readMore.php <?php include_once("classes/DB.php"); use classes\DB; $db = new DB("localhost", "root", "", "hotel", 3306); $id = $_POST['id']; $nazov = $_POST['Nazov']; $cena = $_POST['Cena']; $popis = $_POST['Popis']; $imagep = $_POST['image_path']; if (!$db) { die("Connection failed: " . mysqli_connect_error()); } ?> <!DOCTYPE html> <html> <head> <?php include_once ("header.php"); ?> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light text-capitalize main-font-family"> <div class="container"> <a class="navbar-brand" href="index.php"><img src="imgs/logo.png" alt="#" /></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#show-menu" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="admin.php"><h1>Admin center</h1></a> </div> </nav> <div class="about lobster-font-family"> <div class="container"> <div class="row" style="padding: 20px"> <div class="col-lg-4 col-12"> <div class="img"> <img style="height: 450px; width: 580px; overflow: hidden" src="<?php echo $imagep; ?>"> </div> </div> <div class="col-lg-8 col-12"> <div class="block"> <div> <strong> <?php echo $cena; ?> €</strong> <h5><?php echo $nazov; ?></h5> <p style="overflow: scroll; height: 200px"><?php echo $popis; ?></p> </div> </div> </div> <a style="margin-left: 90%; font-size: 30px" href="index.php"><button>Back</button></a> </div> </div> </div> </body> </html>
7d8a5ea58542d9176bc2df58cd01c3ac0bdcc5ab
[ "PHP" ]
10
PHP
VDominik/portaloveRiesenia
39866d3e58437a82d982bd3824423a3d9c3f3023
9604ce3a0ac58fe0bb1299c12759849ee17dc1cc
refs/heads/master
<repo_name>bozzmob/Network-Stats<file_sep>/README.md Shortcut script(Quick access) to network stats. Using vnstats internally. This is a wrapper over vnstats to get Historical and Realtime monitoring of network. <file_sep>/stats.sh echo "---NETWORK STATS---" echo "-------------------" echo "----wlan0 Daily Stats----" vnstat -d -i wlan0 echo "-------------------" echo "Complete Network Stats" vnstat echo "-------------------" echo "Live Network Stats" vnstat -l
867266f8f7be38282bca1854b805dc7b20dafd16
[ "Markdown", "Shell" ]
2
Markdown
bozzmob/Network-Stats
b67ca9505d39debade792b10457fbcee8fd236b9
9b2b999ce9cfb79c4a7b31ff487673776e4a64fc
refs/heads/master
<file_sep>// For more information on how to configure Gulp.js build system, please visit: // https://github.com/gulpjs/gulp/blob/master/docs/API.md 'use strict'; var gulp = require('gulp'); var clean = require('gulp-clean'); var less = require('gulp-less'); var gutil = require('gulp-util'); var livereload = require('gulp-livereload'); var lr = require('tiny-lr'); var lr_server = lr(); var es = require('event-stream'); // Clean up gulp.task('clean', function () { return gulp.src(['./build/**', '!build'], {read: false}).pipe(clean()); }); // Copy public/static files gulp.task('public', ['clean'], function () { return gulp.src('./public/**') .pipe(gulp.dest('./build')); }); // Copy vendor specific files gulp.task('vendor', ['clean'], function () { // TODO: Copy vendor specific files }); // LESS stylesheets gulp.task('styles', function () { gulp.src(['./build/app.css'], {read: false}).pipe(clean()) return gulp.src('./src/app.less') .pipe(less()) .pipe(gulp.dest('./build')) .pipe(livereload(lr_server)); }); // HTML files gulp.task('html', ['clean'], function () { return gulp.src('./src/**/*.html') .pipe(require("gulp-embedlr")()) .pipe(gulp.dest('./build')); }); // JavaScript code gulp.task('scripts', function () { var source = require('vinyl-source-stream'); //gulp.src(['./build/app.js'], {read: false}).pipe(clean()) return require('browserify')({entries: ['./src/app.js'], debug: !gutil.env.production}) .bundle() .pipe(source('app.js')) .pipe(gulp.dest('./build')) .pipe(livereload(lr_server)); }); // Build the app gulp.task('build', ['public', 'vendor', 'styles', 'scripts', 'html']); // Rerun tasks when a file changes gulp.task('watch', function () { lr_server.listen(35729, function (err) { if (err) return console.log(err); gulp.watch('src/**/*.less', ['styles']); gulp.watch('src/**/*.js', ['scripts']); }); }); // Launch a basic HTTP Server gulp.task('server', ['build'], function (next) { var fileServer = require('ecstatic')({root: './build', cache: 'no-cache', showDir: true}), port = 8000; require('http').createServer() .on('request', function (req, res) { // For non-existent files output the contents of /index.html page in order to make HTML5 routing work // if (req.url.length > 3 && // ['css', 'html', 'ico', 'js', 'png', 'txt', 'xml'].indexOf(req.url.split('.').pop()) == -1 && // ['fonts', 'images', 'vendor', 'views'].indexOf(req.url.split('/')[1]) == -1) { // req.url = '/index.html'; // } fileServer(req, res); }) .listen(port, function () { gutil.log('Server is listening on ' + gutil.colors.magenta('http://localhost:' + port + '/')); next(); }); }); // The default task gulp.task('default', ['server', 'watch']);<file_sep>SPA Front-end Starter Kit ========================= This project is an application skeleton for a typical single-page application (SPA). You can use it to quickly bootstrap your web application projects and dev environment for these projects. ### Components Below is a list of 3rd party runtime and development time components used in the project. | Runtime components | Development tools | |--------------------|----------------------| | HTML5 Boilerplate | Browserify | | jQuery | Gulp | | | Karma | | | Protractor | ### Directory Layout ``` . ├── build # A compiled version of the app ├── docs # Documentation files ├── node_modules # Node.js dev tools and utilities ├── public # Public / static files: favicon.ico etc. ├── src # The source code of the application │ ├── images │ ├── styles │ └── ... ├── test # Unit, integration and load tests │ ├── e2e # End-to-end tests │ └── unit # Unit tests └── ... ``` ### Getting Started To get started you can simply clone the repo and install the dependencies: ``` > git clone https://github.com/KriaSoft/SPA-Seed.Front-end.git MyApp > cd MyApp # Navigate to the newly created project's directory > npm install -g gulp # Install Gulp globally > npm install # Install node.js components listed in ./package.json ``` To compile and run the application do: ``` > gulp ``` Now browse to the app at `http://localhost:8000/` ### SPA-Seed Repositories * [SPA-Seed.Frontend](https://github.com/KriaSoft/SPA-Seed.Front-end) - Base SPA Front-end template * [SPA-Seed.Frontend.AngularJS](https://github.com/KriaSoft/SPA-Seed.Front-end.AngularJS) - AngularJS SPA template * [SPA-Seed.Frontend.React](https://github.com/KriaSoft/SPA-Seed.Front-end.React) - Facebook React SPA template * [SPA-Seed.Server](https://github.com/KriaSoft/SPA-Seed.Server-side) - SPA backend/server-side template (coming soon) ### Authors * [<NAME>](https://angel.co/koistya) ([@koistya](https://twitter.com/koistya)), KriaSoft LLC ### Copyright * Source code is licensed under the MIT License. See [LICENSE](./LICENSE) file in the project root. * Documentation to the project is licensed under the [CC BY 4.0](http://creativecommons.org/licenses/by/4.0/) license.
207b6901befb1e398a26a46fed4718d011820c26
[ "JavaScript", "Markdown" ]
2
JavaScript
Areks/SPA-Seed.Frontend
1192f155909113c2861e4387671d7e5ea57cd478
4b8331661f58166608dea9fab06b268f6e8618e1
refs/heads/master
<file_sep>package me.daansander.gunpvp.listener; import me.daansander.gunpvp.core.KitManager; import me.daansander.gunpvp.event.KitSelectEvent; import me.daansander.gunpvp.kits.Kit; import org.bukkit.Bukkit; import org.bukkit.entity.Entity; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerInteractAtEntityEvent; /** * Created by Daan on 2-1-2016. */ public class EntityInteract implements Listener { @EventHandler public void entityInteract(PlayerInteractAtEntityEvent event) { Entity entity = event.getRightClicked(); if (entity == null) return; if (!KitManager.entities.keySet().contains(entity.getCustomName())) return; Kit kit = KitManager.entities.get(entity.getCustomName()); kit.equip(event.getPlayer()); Bukkit.getServer().getPluginManager().callEvent(new KitSelectEvent(event.getPlayer(), kit)); } } <file_sep>package me.daansander.gunpvp.core; import me.daansander.gunpvp.kits.EquipmentSlot; import net.minecraft.server.v1_8_R2.NBTTagCompound; import org.bukkit.craftbukkit.v1_8_R2.entity.CraftEntity; import org.bukkit.craftbukkit.v1_8_R2.entity.CraftLivingEntity; import org.bukkit.craftbukkit.v1_8_R2.inventory.CraftItemStack; import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; /** * Created by Daan on 1-1-2016. */ public class EntityManager { public static void freeze(Entity entity) { net.minecraft.server.v1_8_R2.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbtTagCompound = new NBTTagCompound(); nmsEntity.c(nbtTagCompound); nbtTagCompound.setByte("NoAI", (byte) 1); nmsEntity.f(nbtTagCompound); } public static void unFreeze(Entity entity) { net.minecraft.server.v1_8_R2.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbtTagCompound = new NBTTagCompound(); nmsEntity.c(nbtTagCompound); nbtTagCompound.setByte("NoAI", (byte) 0); nmsEntity.f(nbtTagCompound); } public static void addItem(ItemStack itemStack, Entity entity, EquipmentSlot equipmentSlot) { ((CraftLivingEntity) entity).getHandle().setEquipment(equipmentSlot.SLOT, CraftItemStack.asNMSCopy(itemStack)); } }
9a321ef397c29909a8a02079e49758976915f254
[ "Java" ]
2
Java
HMCNetwork/GunPvP
2b5bc0a3224e9c7d132a00a9a456bd1dcd408594
5963366990b0f0f5ddbc2ecb63f99290544990d7
refs/heads/master
<repo_name>pjambet/redis-in-ruby<file_sep>/code/chapter-9/resp_types.rb module BYORedis RESPError = Struct.new(:message) do def serialize "-#{ message }\r\n" end end RESPInteger = Struct.new(:underlying_integer) do def serialize ":#{ underlying_integer }\r\n" end def to_i underlying_integer.to_i end end RESPSimpleString = Struct.new(:underlying_string) do def serialize "+#{ underlying_string }\r\n" end end OKSimpleStringInstance = Object.new.tap do |obj| OK_SIMPLE_STRING = "+OK\r\n".freeze def obj.serialize OK_SIMPLE_STRING end end RESPBulkString = Struct.new(:underlying_string) do def serialize "$#{ underlying_string.bytesize }\r\n#{ underlying_string }\r\n" end end NullBulkStringInstance = Object.new.tap do |obj| NULL_BULK_STRING = "$-1\r\n".freeze def obj.serialize NULL_BULK_STRING end end RESPArray = Struct.new(:underlying_array) do def serialize serialized_items = underlying_array.map do |item| case item when RESPSimpleString, RESPBulkString item.serialize when String RESPBulkString.new(item).serialize when Integer RESPInteger.new(item).serialize when Array RESPArray.new(item).serialize when nil NULL_BULK_STRING end end "*#{ underlying_array.length }\r\n#{ serialized_items.join }" end end EmptyArrayInstance = Object.new.tap do |obj| EMPTY_ARRAY = "*0\r\n".freeze def obj.serialize EMPTY_ARRAY end end NullArrayInstance = Object.new.tap do |obj| NULL_ARRAY = "*-1\r\n".freeze def obj.serialize NULL_ARRAY end end class RESPSerializer def self.serialize(object) case object when Array then RESPArray.new(object) when RedisSet then RESPArray.new(object.members) when List then ListSerializer.new(object) when Integer then RESPInteger.new(object) when String then RESPBulkString.new(object) when Dict pairs = [] object.each { |k, v| pairs.push(k, v) } RESPArray.new(pairs) when nil then NullBulkStringInstance else raise "Unknown object for RESP serialization #{ object }" end end end end <file_sep>/code/chapter-9/test/int_set_unit_test.rb require 'minitest/autorun' require_relative './test_helper' require_relative '../int_set' describe BYORedis::IntSet do describe 'add' do it 'returns true if the element is added' do set = new_set assert_equal(true, set.add(10)) assert_equal(true, set.add(256)) assert_equal(true, set.add(5)) assert_equal(true, set.add(20)) assert_equal(true, set.add(15)) assert_equal(5, set.card) end it 'returns false when the element already exists' do set = new_set assert_equal(true, set.add(10)) assert_equal(true, set.add(-10)) assert_equal(false, set.add(10)) assert_equal(true, set.add(32_768)) assert_equal(false, set.add(32_768)) assert_equal(false, set.add(10)) end it 'handles encoding updates' do set = new_set assert_equal(true, set.add(100)) assert_equal(true, set.add(32_768)) assert_equal(true, set.add(-2_147_483_649)) assert(set.include?(-2_147_483_649)) assert(set.include?(32_768)) assert(set.include?(100)) end end def new_set BYORedis::IntSet.new end end <file_sep>/code/chapter-6/test.rb # coding: utf-8 require_relative './test_helper' describe 'BYORedis::Server' do describe 'when initialized' do it 'listens on port 2000' do with_server do # lsof stands for "list open files", see for more info https://stackoverflow.com/a/4421674 lsof_result = `lsof -nP -i4TCP:2000 | grep LISTEN` assert_match 'ruby', lsof_result end end end describe 'closing closed connections' do it 'explicitly closes the connection' do with_server do Timeout.timeout(1) do nc_result = `echo "GET 1" | nc -c localhost 2000` assert_match "$-1\r\n", nc_result end end end end describe 'case sensitivity' do it 'ignores it' do assert_command_results [ [ 'gEt 1', BYORedis::NULL_BULK_STRING ], [ 'set 1 2', '+OK' ], [ 'get 1', '2' ], ] end end describe 'GET' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'GET', '-ERR wrong number of arguments for \'GET\' command' ], ] end it 'returns (nil) for unknown keys' do assert_command_results [ [ 'GET 1', BYORedis::NULL_BULK_STRING ], ] end it 'returns the value previously set by SET' do assert_command_results [ [ 'SET 1 2', '+OK' ], [ 'GET 1', '2' ], [ 'SET 1 😂', '+OK' ], [ 'GET 1', '😂' ], ] end end describe 'TTL' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'TTL', '-ERR wrong number of arguments for \'TTL\' command' ], ] end it 'returns the TTL for a key with a TTL' do assert_command_results [ [ 'SET key value EX 2', '+OK' ], [ 'TTL key', ':2' ], [ 'sleep 0.5' ], [ 'TTL key', ':1' ], ] end it 'returns -1 for a key without a TTL' do assert_command_results [ [ 'SET key value', '+OK' ], [ 'TTL key', ':-1' ], ] end it 'returns -2 if the key does not exist' do assert_command_results [ [ 'TTL key', ':-2' ], ] end end describe 'PTTL' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'PTTL', '-ERR wrong number of arguments for \'PTTL\' command' ], ] end it 'returns the TTL in ms for a key with a TTL' do assert_command_results [ [ 'SET key value EX 2', '+OK' ], [ 'PTTL key', '2000+/-20' ], # Initial 2000ms +/- 20ms [ 'sleep 0.5' ], [ 'PTTL key', '1500+/-20' ], # Initial 2000ms, minus ~500ms of sleep, +/- 20ms ] end it 'returns -1 for a key without a TTL' do assert_command_results [ [ 'SET key value', '+OK' ], [ 'PTTL key', ':-1' ], ] end it 'returns -2 if the key does not exist' do assert_command_results [ [ 'PTTL key', ':-2' ], ] end end describe 'SET' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SET', '-ERR wrong number of arguments for \'SET\' command' ], ] end it 'returns OK' do assert_command_results [ [ 'SET 1 3', '+OK' ], ] end it 'works with empty string' do assert_multipart_command_results [ [ to_query('SET', '', ''), '+OK'], [ to_query('GET', ''), '' ], ] end it 'handles the EX option with a valid argument' do assert_command_results [ [ 'SET 1 3 EX 1', '+OK' ], [ 'GET 1', '3' ], [ 'sleep 1' ], [ 'GET 1', BYORedis::NULL_BULK_STRING ], ] end it 'rejects the EX option with an invalid argument' do assert_command_results [ [ 'SET 1 3 EX foo', '-ERR value is not an integer or out of range' ] ] end it 'handles the PX option with a valid argument' do assert_command_results [ [ 'SET 1 3 PX 100', '+OK' ], [ 'GET 1', '3' ], [ 'sleep 0.1' ], [ 'GET 1', BYORedis::NULL_BULK_STRING ], ] end it 'rejects the PX option with an invalid argument' do assert_command_results [ [ 'SET 1 3 px foo', '-ERR value is not an integer or out of range' ] ] end it 'handles the NX option' do assert_command_results [ [ 'SET 1 2 nX', '+OK' ], [ 'SET 1 2 nx', BYORedis::NULL_BULK_STRING ], [ 'SET 1 2 NX', BYORedis::NULL_BULK_STRING ], [ 'SET 1 2 Nx', BYORedis::NULL_BULK_STRING ], ] end it 'handles the XX option' do assert_command_results [ [ 'SET 1 2 XX', BYORedis::NULL_BULK_STRING ], [ 'SET 1 2', '+OK' ], [ 'SET 1 2 XX', '+OK' ], [ 'SET 1 2 xx', '+OK' ], [ 'SET 1 2 xX', '+OK' ], ] end it 'removes ttl without KEEPTTL' do assert_command_results [ [ 'SET 1 3 PX 100', '+OK' ], [ 'SET 1 2', '+OK' ], [ 'sleep 0.1' ], [ 'GET 1', '2' ], ] end it 'handles the KEEPTTL option' do assert_command_results [ [ 'SET 1 3 PX 100', '+OK' ], [ 'SET 1 2 KEEPTTL', '+OK' ], [ 'sleep 0.1' ], [ 'GET 1', BYORedis::NULL_BULK_STRING ], ] end it 'accepts multiple options' do assert_command_results [ [ 'SET 1 3 NX EX 1', '+OK' ], [ 'GET 1', '3' ], [ 'SET 1 3 XX keepttl', '+OK' ], ] end it 'rejects with more than one expire related option' do assert_command_results [ [ 'SET 1 3 PX 1 EX 2', '-ERR syntax error' ], [ 'SET 1 3 PX 1 KEEPTTL', '-ERR syntax error' ], [ 'SET 1 3 KEEPTTL EX 2', '-ERR syntax error' ], ] end it 'rejects with both XX & NX' do assert_command_results [ [ 'SET 1 3 NX XX', '-ERR syntax error' ], ] end end describe 'COMMAND' do it 'describes all the supported commands' do assert_command_results [ # Results from: echo "COMMAND INFO COMMAND DEL GET SET TTL PTTL" | nc -c -v localhost 6379 [ 'COMMAND', "*6\r\n*7\r\n$7\r\ncommand\r\n:-1\r\n*3\r\n+random\r\n+loading\r\n+stale\r\n:0\r\n:0\r\n:0\r\n*2\r\n+@slow\r\n+@connection\r\n*7\r\n$3\r\ndel\r\n:-2\r\n*1\r\n+write\r\n:1\r\n:-1\r\n:1\r\n*3\r\n+@keyspace\r\n+@write\r\n+@slow\r\n*7\r\n$3\r\nget\r\n:2\r\n*2\r\n+readonly\r\n+fast\r\n:1\r\n:1\r\n:1\r\n*3\r\n+@read\r\n+@string\r\n+@fast\r\n*7\r\n$3\r\nset\r\n:-3\r\n*2\r\n+write\r\n+denyoom\r\n:1\r\n:1\r\n:1\r\n*3\r\n+@write\r\n+@string\r\n+@slow\r\n*7\r\n$3\r\nttl\r\n:2\r\n*3\r\n+readonly\r\n+random\r\n+fast\r\n:1\r\n:1\r\n:1\r\n*3\r\n+@keyspace\r\n+@read\r\n+@fast\r\n*7\r\n$4\r\npttl\r\n:2\r\n*3\r\n+readonly\r\n+random\r\n+fast\r\n:1\r\n:1\r\n:1\r\n*3\r\n+@keyspace\r\n+@read\r\n+@fast\r\n" ], ] end end describe 'DEL' do it 'deletes existing keys' do assert_command_results [ [ 'SET key value', '+OK' ], [ 'GET key', 'value' ], [ 'DEL key', ':1' ], [ 'GET key', BYORedis::NULL_BULK_STRING ], [ 'SET key-1 value', '+OK' ], [ 'SET key-2 value', '+OK' ], [ 'DEL key-1 key-2 not-a-key', ':2' ], ] end it 'returns 0 for a non existing key' do assert_command_results [ [ 'DEL not-a-key', ':0' ], ] end end describe 'Unknown commands' do it 'returns an error message' do assert_command_results [ [ 'NOT A COMMAND', '-ERR unknown command `NOT`, with args beginning with: `A`, `COMMAND`,' ], ] end end describe 'partial commands' do it 'accepts commands received through multiple reads' do assert_multipart_command_results [ [ to_query('SET', 'first-key', 'first-value'), '+OK' ], [ to_query('SET', 'second-key', 'second-value'), '+OK' ], [ to_query('SET', 'third-key', 'third-value'), '+OK' ], [ [ "*2\r\n$3\r\nGET\r\n", "$9\r\nfirst-key\r\n" ], 'first-value' ], [ [ "*2\r\n$3\r\nGET\r\n", "$10\r\nsecond-key\r\n*2" ], 'second-value' ], [ [ "\r\n$3\r\nGET\r\n$9\r\nthird-key\r\n" ], 'third-value' ], ] end it 'does not nothing if the command is incomplete' do assert_command_results [ [ "*2\r\n$3\r\nGET\r\n$10\r\nincomple", nil ], ] end end describe 'protocol errors' do it 'returns a protocol error when expecting a bulk string and not reading the leading $' do assert_command_results [ [ "*2\r\n$3\r\nGET\r\na-key\r\n", "-ERR Protocol error: expected '$', got 'a'" ], ] end it 'returns a protocol error when the length is invalid' do assert_command_results [ [ "*1\r\n$foo\r\n", '-ERR Protocol error: invalid bulk length' ], ] assert_command_results [ [ "*foo\r\n", '-ERR Protocol error: invalid multibulk length' ], ] end end describe 'pipelining' do it 'works with both inline & regular commands when starting with an inline command' do assert_multipart_command_results [ [ [ "GET a\r\n*2\r\n$3\r\nGET\r\n$1\r\nb\r\n" ], "$-1\r\n$-1\r\n" ], ] end it 'works with both inline & regular commands when starting with a regular command' do assert_multipart_command_results [ [ [ "*2\r\n$3\r\nGET\r\n$1\r\nb\r\nGET a\r\n" ], "$-1\r\n$-1\r\n" ], ] end end describe 'inline commands' do it 'accepts inline commands' do assert_command_results [ [ "SET a-key a-value\r\n", '+OK' ], [ "GET a-key\r\n", "$7\r\na-value\r\n" ], [ "GET a-key\r", "$7\r\na-value\r\n" ], [ "GET a-key\n", "$7\r\na-value\r\n" ], ] assert_multipart_command_results [ [ [ "SET a-key a-value\r\nSET ", 'another-key' ], '+OK' ], [ [ ' another-value', "\r\n" ], '+OK' ], [ [ "GET a-key\r\n" ], 'a-value' ], [ [ "GET another-key\r\n" ], 'another-value' ], ] end it 'rejects everything that is not a command and does not start with a *' do assert_command_results [ [ "-a\r\n", '-ERR unknown command `-a`, with args beginning with: ' ], ] end end describe 'resizing' do it 'stores items after reaching the initial size' do assert_command_results [ [ 'SET 1 2', '+OK' ], [ 'GET 1', '2' ], [ 'SET 3 4', '+OK' ], [ 'GET 3', '4' ], [ 'SET 5 6', '+OK' ], [ 'GET 5', '6' ], [ 'SET 7 8', '+OK' ], [ 'GET 7', '8' ], [ 'SET 9 10', '+OK' ], [ 'GET 9', '10' ], [ 'GET 1', '2' ], [ 'GET 3', '4' ], [ 'GET 5', '6' ], [ 'GET 7', '8' ], [ 'GET 9', '10' ], [ 'SET 11 12', '+OK' ], [ 'SET 13 14', '+OK' ], [ 'SET 14 16', '+OK' ], [ 'SET 17 18', '+OK' ], [ 'SET 19 20', '+OK' ], ] end end end <file_sep>/code/chapter-9/dict.rb require_relative './siphash' require_relative './dict_entry' require_relative './hash_table' module BYORedis class Dict INITIAL_SIZE = 4 MAX_SIZE = 2**63 attr_reader :hash_tables def initialize @hash_tables = [ HashTable.new(0), HashTable.new(0) ] @rehashidx = -1 end def used main_table.used + rehashing_table.used end def empty? used == 0 end def rehash_milliseconds(millis) start = Time.now.to_f * 1000 rehashes = 0 while rehash(100) == 1 rehashes += 100 time_ellapsed = Time.now.to_f * 1000 - start break if time_ellapsed > millis end rehashes end def resize return if rehashing? minimal = main_table.used minimal = INITIAL_SIZE if minimal < INITIAL_SIZE expand(minimal) end def include?(key) !get_entry(key).nil? end alias member? include? # Dangerous method that can create duplicate if used incorrectly, should only be called if # get_entry was previously called and returned nil # Explain that calling add while rehashing can create a race condition def add(key, value) index = key_index(key) # Only happens if we didn't check the presence before calling this method return nil if index == -1 rehash_step if rehashing? hash_table = rehashing? ? rehashing_table : main_table entry = hash_table.table[index] entry = entry.next while entry && entry.key != key if entry.nil? entry = DictEntry.new(key, value) entry.next = hash_table.table[index] hash_table.table[index] = entry hash_table.used += 1 else raise "Unexpectedly found an entry with same key when trying to add #{ key } / #{ value }" end end def set(key, value) entry = get_entry(key) if entry entry.value = value false else add(key, value) true end end alias []= set def get_entry(key) return if main_table.used == 0 && rehashing_table.used == 0 rehash_step if rehashing? hash = SipHash.digest(RANDOM_BYTES, key) iterate_through_hash_tables_unless_rehashing do |hash_table| index = hash & hash_table.sizemask entry = hash_table.table[index] while entry return entry if entry.key == key entry = entry.next end end nil end def get(key) get_entry(key)&.value end alias [] get def delete_entry(key) return if main_table.used == 0 && rehashing_table.used == 0 rehash_step if rehashing? hash_key = SipHash.digest(RANDOM_BYTES, key) iterate_through_hash_tables_unless_rehashing do |hash_table| index = hash_key & hash_table.sizemask entry = hash_table.table[index] previous_entry = nil while entry if entry.key == key if previous_entry previous_entry.next = entry.next else hash_table.table[index] = entry.next end hash_table.used -= 1 return entry end previous_entry = entry entry = entry.next end end nil end def delete(key) delete_entry(key)&.value end def each return if main_table.used == 0 && rehashing_table.used == 0 start_index = rehashing? ? @rehashidx : 0 main_table.table[start_index..-1].each do |bucket| next if bucket.nil? until bucket.nil? yield bucket.key, bucket.value bucket = bucket.next end end return unless rehashing? rehashing_table.each do |bucket| next if bucket.nil? until bucket.nil? yield bucket.key, bucket.value bucket = bucket.next end end end def keys keys = [] each do |key, _| keys << key end keys end def values values = [] each do |_, value| values << value end values end def needs_resize?(min_fill: 10) size = slots size > INITIAL_SIZE && ((used * 100) / size < min_fill) end GETFAIR_NUM_ENTRIES = 15 def fair_random_entry keys = get_some_entries(GETFAIR_NUM_ENTRIES) if keys.empty? random_entry else keys[rand(0...keys.size)] end end private def slots hash_tables[0].size + hash_tables[1].size end def main_table @hash_tables[0] end def rehashing_table @hash_tables[1] end def expand(size) return if rehashing? || main_table.used > size real_size = next_power(size) return if real_size == main_table.size new_hash_table = HashTable.new(real_size) # Is this the first initialization? If so it's not really a rehashing # we just set the first hash table so that it can accept keys. if main_table.table.nil? @hash_tables[0] = new_hash_table else @hash_tables[1] = new_hash_table @rehashidx = 0 end end # In the Redis codebase, they extensively use the following pattern: # for (table = 0; table <= 1; table++) { # ... # if (!dictIsRehashing(d)) break; # } # This is common for many operations, such as finding or deleting an item in the dict, # we first need to look at the main table, the first table, but we haven't found in the # first one, we should look in the rehashing table, the second one, but only if we're in # the process of rehashing. # Taking advantage of Ruby blocks, we can write this helper method instead def iterate_through_hash_tables_unless_rehashing @hash_tables.each do |hash_table| yield hash_table break unless rehashing? end end def key_index(key) expand_if_needed hash = SipHash.digest(RANDOM_BYTES, key) index = nil iterate_through_hash_tables_unless_rehashing do |hash_table| index = hash & hash_table.sizemask entry = hash_table.table[index] while entry # The key is already present in the hash so there's no valid index where to add it if entry.key == key return -1 else entry = entry.next end end end index end def rehash(n) empty_visits = n * 10 return 0 unless rehashing? while n > 0 && main_table.used != 0 n -= 1 entry = nil while main_table.table[@rehashidx].nil? @rehashidx += 1 empty_visits -= 1 return 1 if empty_visits == 0 end entry = main_table.table[@rehashidx] while entry next_entry = entry.next idx = SipHash.digest(RANDOM_BYTES, entry.key) & rehashing_table.sizemask entry.next = rehashing_table.table[idx] rehashing_table.table[idx] = entry main_table.used -= 1 rehashing_table.used += 1 entry = next_entry end main_table.table[@rehashidx] = nil @rehashidx += 1 end # Check if we already rehashed the whole table if main_table.used == 0 @hash_tables[0] = rehashing_table @hash_tables[1] = HashTable.new(0) @rehashidx = -1 0 else # There's more to rehash 1 end end def rehashing? @rehashidx != -1 end def expand_if_needed return if rehashing? if main_table.empty? expand(INITIAL_SIZE) elsif main_table.used >= main_table.size expand(main_table.size * 2) end end def next_power(size) # Ruby has practically no limit to how big an integer can be, because under the hood the # Integer class allocates the necessary resources to go beyond what could fit in a 64 bit # integer. # That being said, let's still copy what Redis does, since it makes sense to have an # explicit limit about how big our Dicts can get i = INITIAL_SIZE return MAX_SIZE if size >= MAX_SIZE loop do return i if i >= size i *= 2 end end def rehash_step rehash(1) end def get_some_entries(count) entries = [] stored = 0 count = used if count > used maxsteps = count * 10 count.times { rehash_step } if rehashing? tables = rehashing? ? 2 : 1 maxsizemask = main_table.sizemask if tables > 1 && rehashing_table.sizemask > maxsizemask maxsizemask = rehashing_table.sizemask end i = rand(0..maxsizemask) empty_len = 0 while stored < count && maxsteps iterate_through_hash_tables_unless_rehashing do |hash_table| # If we're in the process of rehashing, up to the indexes already visited in the main # table during the rehashing, there are no populated buckets so we can skip in the # main table, all the indexes between 0 and @rehashidx - 1 if rehashing? && hash_table == main_table && i < @rehashidx if i >= rehashing_table.size i = @rehashidx else next end end next if i >= hash_table.size # Out of range for this table hash_entry = hash_table.table[i] # Count contiguous empty bucket and jump to other locations if they reach 'count' # with a minimum of 5 if hash_entry.nil? empty_len += 1 if empty_len >= 5 && empty_len > count i = rand(0..maxsizemask) empty_len = 0 end else empty_len = 0 while hash_entry entries << hash_entry hash_entry = hash_entry.next stored += 1 return entries if stored == count end end end i = (i + 1) & maxsizemask # increment and wraparound if needed maxsteps -= 1 end entries end def random_entry return if used == 0 rehash_step if rehashing? hash_entry = nil if rehashing? # There are no elements indexes from 0 to rehashidx-1 so we know the only places we can # find an element are in main_table[rehashidx..-1] and anywhere in the rehashing table # We generate the random_index between the total number of slots (the two sizes), minus # the rehashing index. An example, we're growing from 8 to 16 buckets, that's 24 total # slots, now let's imagine that @rehashidx is 4, we generate an index between 0 and 20 # (excluded), and we add 4 to it, that means that we _never_ have a value under 4. # If the random index is 8 or more, we need to look in the rehashing table, but we need # adjust it by removing 8, the size of the main table to it, so say it was initially 19, # plus four, that' 23, minus 8, that's 15, the last bucket in the rehashing table. # If the random index is between 4 and 7, then we look directly in the main table while hash_entry.nil? max = slots - @rehashidx random_index = @rehashidx + rand(max) hash_entry = if random_index >= main_table.size rehashing_table.table[random_index - main_table.size] else main_table.table[random_index] end end else while hash_entry.nil? random_index = rand(main_table.size) hash_entry = main_table.table[random_index] end end # Now that we found a non empty bucket, we need to pick a random element from it, but if # there's only one item, we can save some time and return right away return hash_entry if hash_entry.next.nil? list_length = 0 original_hash_entry = hash_entry while hash_entry list_length += 1 hash_entry = hash_entry.next end random_list_index = rand(list_length) hash_entry = original_hash_entry random_list_index.times do hash_entry = hash_entry.next end hash_entry end end end <file_sep>/code/chapter-8/blocked_client_handler.rb module BYORedis class BlockedClientHandler def initialize(server, db) @server = server @db = db @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL end def handle(key) clients = @db.blocking_keys[key] unblocked_clients = [] list = @db.data_store[key] if !list || !list.is_a?(List) @logger.warn "Something weird happened, not a list: #{ key } / #{ list }" raise "Unexpectedly found nothing or not a list: #{ key } / #{ list }" end raise "Unexpected empty list for #{ key }" if list.empty? cursor = clients.left_pop while cursor client = cursor.value if handle_client(client, key, list) unblocked_clients << client end if list.empty? break else cursor = clients.left_pop end end @db.blocking_keys.delete(key) if clients.empty? unblocked_clients end def handle_client(client, key, list) blocked_state = client.blocked_state # The client is expected to be blocked on a set of keys, we unblock it based on the key # arg, which itself comes from @db.ready_keys, which is populated when a key that is # blocked on receives a push # So we pop (left or right) from the list at key, and send the response to the client if client.blocked_state response = pop_operation(key, list, blocked_state.operation, blocked_state.target) serialized_response = response.serialize @logger.debug "Writing '#{ serialized_response.inspect } to #{ client }" unless Utils.safe_write(client.socket, serialized_response) # If we failed to write the value back, we put the element back in the list rollback_operation(key, response, blocked_state.operation, blocked_state.target) @server.disconnect_client(client) return end else @logger.warn "Client was not blocked, weird!: #{ client }" return end true end private def pop_operation(key, list, operation, target) case operation when :lpop RESPArray.new([ key, @db.left_pop_from(key, list) ]) when :rpop RESPArray.new([ key, @db.right_pop_from(key, list) ]) when :rpoplpush raise "Expected a target value for a brpoplpush handling: #{ key }" if target.nil? ListUtils.common_rpoplpush(@db, key, target, list) else raise "Unknown pop operation #{ operation }" end end def rollback_operation(key, response, operation, target_key) list = @db.lookup_list_for_write(key) case operation when :lpop element = response.underlying_array[1] list.left_push(element) when :rpop element = response.underlying_array[1] list.right_push(element) when :rpoplpush target_list = @db.lookup_list(target_key) element = target_list.left_pop @db.data_store.delete(target_key) if target_list.empty? list.right_push(element.value) else raise "Unknown pop operation #{ operation }" end end end end <file_sep>/content/post/chapter-8-adding-hash-commands.md --- title: "Chapter 8 Adding Hash Commands" date: 2020-11-03T14:36:32-05:00 lastmod: 2020-11-03T14:36:38-05:00 draft: false comment: false keywords: [] summary: "In this chapter we add support for a new data type, Lists. We implement all the commands related to hashes, such as HSET, HGET & HGETALL" --- ## What we'll cover Now that our server supports Lists, the next data type we will add support for is Hashes. We've covered the concept of a Hash, also called Map or Dictionary in [Chapter 6][chapter-6] where we built our own `Dict` class, implemented as a hash table, to store all the database data in memory. It turns out that within this `Dict`, the `@data_store` instance variables in the `DB` class, values can also be hashes. This allows clients to store multiple key/value pairs for a top-level key. Say that for instance you wanted to store product data in Redis, where a product has an id, and a set of attributes, such as a name, a price, and an image URL. You could do this with good old `GET`/`SET`, but that would require you to use as many keys in the top level dictionary as you need attributes. It is simpler to use a hash in this case: ``` bash 127.0.0.1:6379> HSET product:1 name "Product One" price 25 image_url https://... (integer) 3 127.0.0.1:6379> HSET product:123 name "Product 123" price 100 image_url https://... (integer) 3 127.0.0.1:6379> HGETALL product:1 1) "name" 2) "Product One" 3) "price" 4) "25" 5) "image_url" 6) "https://..." 127.0.0.1:6379> HGETALL product:123 1) "name" 2) "Product 123" 3) "price" 4) "100" 5) "image_url" 6) "https://..." 127.0.0.1:6379> HGET product:1 name "Product One" 127.0.0.1:6379> HGET product:123 price "100" ``` With the `HSET` command we can set as many key/value pairs as we want for the given key, `product:1` and `product:123` in the example above. Note that since RESP does not support a dictionary type, the returned value of `HGETALL`, which returns all the pairs, is a flat array of field names and values, it is up to the client to read this array and wrap it in a more appropriate data type, such as `Hash` in Ruby, `Object` or `Map` in JavaScript, or `dict` in Python. There are [15 commands][redis-doc-hash-commands] for the Hash data type: - **HDEL**: Delete one or more fields from a hash - **HEXISTS**: Check for the existence of a field in a hash - **HGET**: Return the value for the given field - **HGETALL**: Return all the key/value pairs - **HINCRBY**: Increment the value for the given field, by the given integer, positive or negative - **HINCRBYFLOAT**: Increment the value for the given field, by the given float, positive or negative - **HKEYS**: Return all the keys - **HLEN**: Return the number of pairs - **HMGET**: Return all the values for the given keys - **HMSET**: This command is deprecated, it was necessary before HSET gained the capability to set multiple key/value pairs at once - **HSCAN**: Return a subset of key/value pairs as well as a scan cursor. This is similar to the [SCAN command][redis-doc-scan-command] - **HSET**: Set one or more key/value pairs, creating the hash if it does not already exist - **HSETNX**: Set the value for the given field in the hash, only if the field does not already exist - **HSTRLEN**: Return the length of the string stored for the given field - **HVALS**: Return all the values We will only implement thirteen of these fifteen commands, we will not implement `HMSET`, because as noted above, it was made obsolete when `HSET` was updated in 4.0.0 to become variadic. That's just a fancy word to say that it accepts one or more key/value pairs. Prior to that it would only accept a single pair. We will also ignore `HSCAN`, it behaves very similarly to `SCAN`, which operates on the top-level dictionary, `SSCAN`, which works on sets and `ZSCAN` which works on sorted sets. The idea behind each of these commands is that retrieving all the values is an O(n) operation, where n is the number of elements in the database for `SCAN`, the number of fields for `HSCAN` and the number of members for `SSCAN` & `ZSCAN`. In practical terms, it means that calling `HSCAN` on large hashes, which have no limit on the number of pairs, the memory available is the only limit, will be very slow if that number is really high. The `*SCAN` commands "solve" this problem by breaking the iteration in multiple steps, calling `HSCAN` only returns a subset of the key/value pairs, and includes a cursor that can be used to keep iterating until the cursor is 0, indicating that the iteration is over. `SCAN` is the alternative to `KEYS`, `HSCAN` is the alternative to `HKEYS`, `SSCAN` is the alternative to `SMEMBERS` and `ZSCAN` is the alternative to `ZRANGE zset 0 -1 WITHSCORES`. All four `*SCAN` commands work very similarly and are fairly complex, the C implementation spans over a few hundred lines and code, and for reference the documentation of `dictScan`, one of the main functions, is [over 80 lines long][redis-src-dict-scan-doc]. A big part of the complexity comes from the fact that the `*SCAN` commands are stateless, the server does not store any data with the status of the iteration, and it also needs to be smart to know how to iterate over the underlying dict if it is being rehashed. _The `*SCAN` commands might be implemented in a later chapter but this is not currently planned_ It is important to note that despite the existence of the `HINCRBY` & `HINCRBYFLOAT` commands, all keys and values in a Hash are strings. We will see in details how these two commands are implemented and how the data is converted from a string to an integer or a float later in this chapter. ## How does Redis do it We already know, to some extent, how Redis handles dictionaries, we explored how it implemented a hash table in the `dict.c` file in [Chapter 6][chapter-6], but what we built so far is missing a few elements, which we'll look into later. Additionally, Redis uses a really interesting approach where it uses a different underlying structure to store the hash data depending on the size of the hash and the length of the keys and values. These values can be configured through the configuration file, the default values are [512][redis-conf-max-items] for the maximum number of items stored as a ziplist & [64][redis-conf-max-value] for the maximum length of a key or value stored as a ziplist. As long as the number of keys is lower or equal to `512` and that the strings stored in the hash are shorter than `64` characters, Redis will use a ziplist to store the Hash. Once any of these two conditions break, it will convert the ziplist to a dict. We will implement a similar approach because it illustrates a crucial point with regard to time complexity and O-notation. Most of the operations important to a hash, such as `HGET`, have an O(n) time complexity when using a list. This is because in the case where the element we're looking for is the last element in the list or is not present, we'd have to browse the whole list to find it. On the other hand, as we've seen in [Chapter 6][chapter-6], a hash table, such as the one we implemented in the `Dict` class, can perform this operation with a O(1) complexity. That being said, O(n) does not mean "slow", and O(1) does not mean "fast". What they mean is that a dict lookup using a hash table will always require the same number of steps and therefore take roughly the same amount of time, that's what O(1) means, the time it takes is constant. On the other hand a hash lookup using a list will require one more step, in the worst case scenario, for each new items in the list, this is a linear growth. Now, back to our hash table, what we want, or what the users of our database want, is for it to be as fast as possible. If a hash only contains a single key/value pair, it seems very likely that a list implementation will actually be faster than a hash table. There's no hashing, no internal table allocation, a single check of the element at the head of the list and that's it. If a list is more efficient than a hash table for one element, it seems reasonable to assume it will also be faster for two, three, four and all "small" hashes. But how do we define "small" in concrete terms. Well, this is when you have to measure things. The process here would be to run benchmarks, to measure the performance of different operations, against each implementation and see at what point the list implementation starts to slow down to a point where a hash table would be faster. The developers of Redis did this work, and we the default value is 512 entries, as we can see in the [`redis.conf` file][redis-conf-file-hash-max-ziplist-entries]. This value means that Redis will use a ziplist for the first 512 pairs added to the hash, and adding a 513th one will start using a hash table. Let's look at it in practice: ``` bash 127.0.0.1:6379> HSET h 1 1 (integer) 1 127.0.0.1:6379> DEBUG OBJECT h Value at:0x7ffe00804650 refcount:1 encoding:ziplist serializedlength:16 lru:10150943 lru_seconds_idle:5 ``` The `DEBUG OBJECT` command returns information about the given key, including its encoding, and we can see that the hash at key `h` is encoded as a ziplist. Let's add 511 items to it and see what happens, we could do this with redis-cli, but it would take a while, so let's use `irb`, with the `redis` gem: ``` ruby irb(main):001:0> require 'redis' => true irb(main):002:0> redis = Redis.new irb(main):003:0> 511.times { |i| redis.hset('h', i, i) } => 511 ``` Back in `redis-cli`: ``` bash 127.0.0.1:6379> debug object h Value at:0x7ffdfec194a0 refcount:1 encoding:ziplist serializedlength:2836 lru:10150882 lru_seconds_idle:5 ``` The hash is still a ziplist, and contains 512 pairs, let's add another one: ``` bash 127.0.0.1:6379> HSET h f 1 (integer) 1 127.0.0.1:6379> debug object h Value at:0x7ffdfec194a0 refcount:1 encoding:hashtable serializedlength:2825 lru:10150894 lru_seconds_idle:2 ``` And voila! Redis updated the encoding of the hash from a ziplist to a hashtable, the changes are in practice invisible to the user, the commands are the same, but internally Redis uses what it believes is the most efficient implementation. The hash length is not the only factor Redis uses to decide which underlying implementation to use, it also uses the length of the values, with a default value of 64 in the [`redis.conf` file][redis-conf-file-hash-max-ziplist-value]. If either a key or a value in the hash has a length longer than 64, Redis will start using a hash table instead of a ziplist. This is a consequence of the ziplist data structure, which we explored in [Appendix A][chapter-7-appendix-a] in the previous chapter. Ziplists are represented as a chunk of contiguous memory, making them more and more expensive to manipulate at they grow, as the whole list needs to be reallocated when a new element is inserted for instance. When using small key and value strings, the whole chunk of memory allocated will stay relatively small, but if we were to store any strings until the size of the hash reaches 512 entries, we might still end up with a very big and slow ziplist if a client started using long strings as keys or values. ## Adding Hash Commands It's interesting to consider the fact that in essence the hash type in Redis does not require any new concrete data structures, it is a layer of abstraction on top of ziplists and dicts. We have not reimplemented ziplists so we will instead use our `List` class for small hashes, and use the `Dict` class for large hashes. We first need to add the ability to create hashes, that's what `HSET` & `HSETNX` do. ### Creating a Hash with HSET & HSETNX `HSET`'s behavior is fairly similar to `LPUSH` & `RPUSH` from the previous chapter. If no objects exist for the given key, a new hash is created, and all the given key/value pairs are added to it. If an object already exists and is not a hash, an error is returned, and if a hash already exists, the new pairs are added to it. The command returns the number of fields added to the hash. Updating elements does not count as adding new elements since we're not adding a new pair to the hash. Let's look at some examples: ``` bash 127.0.0.1:6379> HSET h field-1 value-1 one 1 2 two (integer) 3 127.0.0.1:6379> HGETALL h 1) "field-1" 2) "value-1" 3) "one" 4) "1" 5) "2" 6) "two" 127.0.0.1:6379> HSET h field-1 new-value one something-else a-new-key a-new-pair (integer) 1 127.0.0.1:6379> HGETALL h 1) "field-1" 2) "new-value" 3) "one" 4) "something-else" 5) "2" 6) "two" 7) "a-new-key" 8) "a-new-pair" ``` The second `HSET` command returned one because only one of the three given keys did not already exists, the other two, `field-1` and `one` were updated. As mentioned above, note that in a hash, everything is a string. **Config values** We want our hash implementation to behave similarly to Redis and choose the best underlying structure, between `List` and `Dict`, depending on the size of the hash. To achieve this we are creating a `Config` module, which will keep the value of all the supported configuration options. For now we only need two configs, `hash_max_ziplist_entries` & `hash_max_ziplist_value`: ``` ruby module BYORedis module Config UnsupportedConfigParameter = Class.new(StandardError) UnknownConfigType = Class.new(StandardError) DEFAULT = { hash_max_ziplist_entries: 512, hash_max_ziplist_value: 64, } @config = DEFAULT.clone def self.set_config(key, value) key = key.to_sym existing_config = @config[key] raise UnsupportedConfigParameter, key unless existing_config case existing_config when Integer @config[key] = Utils.string_to_integer(value) else raise UnknownConfigType, "#{ key }/#{ value }" end end def self.get_config(key) @config[key.to_sym] end end end ``` _listing 8.1 The `Config` class_ Similarly to what we did in the previous chapter, we're going to create a new file, `hash_commands.rb`, where we'll add all the command classes related to the Hash data type, let's start with `HSetCommand`: ``` ruby module BYORedis class HSetCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) key = @args.shift raise InvalidArgsLength unless @args.length.even? hash = @db.lookup_hash_for_write(key) count = 0 @args.each_slice(2).each do |pair| key = pair[0] value = pair[1] count += 1 if hash.set(key, value) end RESPInteger.new(count) end def self.describe Describe.new('hset', -4, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@hash', '@fast' ]) end end end ``` _listing 8.2 The `HSetCommand` class_ In order for the `Server` class to respond to the `HSET` command we need to add a `require` statement in `server.rb` for the new `hash_commands.rb` file, as well as adding an entry in the `COMMANDS` dictionary. This is a repetitive process, so we will stop showing it from now on, but remember that for each class that we add, we actually need to "enable" it in the `Server` class. We have to use a new type of validation for the number of arguments with the `HSET` command, all arguments after the hash's key come in pairs, so we need to validate that we have an even number of arguments after the key. We now need a class to represent the hash, in the Redis source code, the file that implements the hash logic is called `t_hash.c`. The main data types are all implemented in files starting with `t_`, which I assume stands for **T**ype. String commands are implemented in `t_string.c`, List commands in `t_list.c`, Set commands in `t_set.c`, Sorted Sets commands in `t_zset.c`, Hash commands in `t_hash.c` and Stream commands in `t_stream.c`. We could follow this pattern and name our class `THash`, but this is not a very explicit name, so instead we'll go with `RedisHash`, to be more explicit. We are not calling it `Hash` because Ruby already ships a `Hash` class, and even though nothing technically prevents up from "reopening" the class and adding our own methods, overriding existing ones, this would likely become problematic. For instance, we might accidentally use methods defined in the Ruby `Hash` class, it is easier to start fresh, with our own class. ``` ruby module BYORedis class RedisHash ListEntry = Struct.new(:key, :value) def initialize @underlying = List.new end def set(key, value) max_string_length = Config.get_config(:hash_max_ziplist_value) convert_list_to_dict if @underlying.is_a?(List) && (key.length > max_string_length || value.length > max_string_length) case @underlying when List then added = set_list(key, value) if @underlying.size + length > Config.get_config(:hash_max_ziplist_entries) convert_list_to_dict end added when Dict then @underlying.set(key, value) else raise "Unknown structure type: #{ @underlying }" end end alias []= set private def set_list(key, value) iterator = List.left_to_right_iterator(@underlying) while iterator.cursor && iterator.cursor.value.key != key iterator.next end if iterator.cursor.nil? @underlying.right_push(ListEntry.new(key, value)) true else iterator.cursor.value.value = value false end end def convert_list_to_dict dict = Dict.new iterator = List.left_to_right_iterator(@underlying) while iterator.cursor dict[iterator.cursor.value.key] = iterator.cursor.value.value iterator.next end @underlying = dict end end end ``` _listing 8.3 The `RedisHash` class_ The `RedisHash` class starts with a `List` as the data structure backing the hash, it will be converted to a `Dict` as needed, when the hash grows. Our implementation differs slightly from Redis with regards to how data is stored in the list. Redis stores the keys and values, as flat elements, one after the other. This means that adding one pair to the hash results in two elements being added to the list. Our approach is bit different, we create a struct, `ListEntry`, to store the pairs in the list. This allows us to use our `List` class in a slightly more idiomatic way. One pair represents conceptually one element. This allows us to directly use the `size` attribute of the list, instead of having to divide it by two to obtain the number of elements in the hash. The `set` method, which we alias to `[]=`, to provide a similar API to the `Dict` & `Hash` classes, is the method used by the `HSET` command. We first lookup the current value of the `hash_max_ziplist_value` config, and convert the list to a dict if either the key or the value we're adding are longer than the config. Once this check is performed, we use a pattern we'll see a lot in this chapter, a `case/when` statement to check the type of `@underlying`. There are three branches, it is either a `List`, a `Dict`, or anything else, in which case we want to crash the server as this is never supposed to happen. The code for the `List` branch requires a few more lines of code, so we extract it to the `set_list` private method, below in the class. In the `Dict` case, it only requires three lines of code. We start by checking how many items are present in the `Dict`, we then use the `Dict#set` method, which we slightly modify to return a boolean: ``` ruby module BYORedis class Dict # ... def set(key, value) entry = get_entry(key) if entry entry.value = value false else add(key, value) true end end alias []= set # ... end end end ``` _listing 8.4 Updates to the `set` method in the `Dict` class_ The `Dict#set` method we introduced in [Chapter 6][chapter-6] used to return the new value, which was not really helpful since the caller knows what the value is, it is the second argument to the method. We're now returning a boolean instead, indicating whether the pair was added or not. The method either updates the value if the key is already in the hash, or add it altogether. We're not using the `Dict#[]=` alias here because doing so will not return anything, and we do care about the boolean value returned, to increment the count in the `HSetCommand` class. The `set_list` method creates a list iterator and starts iterating from the head, as long as the node's key is different from the given key, we keep iterating. If we encounter a node with the same key, the iteration stops, and we update the value for that node. Otherwise, we add a new node at the end of the list. As noted above, we are using a new class to store node values, `ListEntry`. We could have used a "tuple approach", by storing a two-element array, such as `[ 'key', 'value' ]`, but the `ListEntry` struct makes things a little bit more explicit, the items stored in the list can be read with clear methods, `key` & `value`, instead of using `[0]` & `[1]` respectively with the tuple approach. Now that we have enough of `RedisHash` implemented, we need to add the new `lookup_hash_for_write` method to the `DB` class: ``` ruby module BYORedis class DB # ... def lookup_hash(key) hash = @data_store[key] raise WrongTypeError if hash && !hash.is_a?(RedisHash) hash end def lookup_hash_for_write(key) hash = lookup_hash(key) if hash.nil? hash = RedisHash.new @data_store[key] = hash end hash end end end ``` _listing 8.5 The `lookup_hash_for_write` method in the `DB` class_ This method is very similar to the one we create for lists in the [previous chapter][chapter-7], except that it expects a `Hash` instance and creates one if necessary. And with all this, the server can now response to `HSET` commands, let's now add the `HSetNXCommand`: ``` ruby module BYORedis # ... class HSetNXCommand < BaseCommand def call Utils.assert_args_length(3, @args) key = @args[0] field = @args[1] value = @args[2] hash = @db.lookup_hash_for_write(key) if hash[field] RESPInteger.new(0) else hash[field] = value RESPInteger.new(1) end end def self.describe Describe.new('hsetnx', 4, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@hash', '@fast' ]) end end end ``` _listing 8.6 The `HSetNX` class_ This new command uses existing methods, if the given field already exists in the hash, we directly return `0` and leave the hash untouched. On the other hand, if the field is not already present, we add it, using the `RedisHash#[]=` this time, since we know it will add the element, and return `1`. Now that we can create hashes, we need to update the `TypeCommand` class to respond with `hash` for hash keys: ``` ruby module BYORedis class TypeCommand < BaseCommand def call Utils.assert_args_length(1, @args) key = @args[0] ExpireHelper.check_if_expired(@db, key) value = @db.data_store[key] case value when nil then RESPSimpleString.new('none') when String then RESPSimpleString.new('string') when List then RESPSimpleString.new('list') when RedisHash then RESPSimpleString.new('hash') else raise "Unknown type for #{ value }" end end # ... end end ``` _listing 8.7 Updates to the `TypeCommand` class to handle `RedisHash` instances_ ### Reading Hash values with HGET, HMGET & HGETALL Now that we can create Hash instances in our database, we need to add the ability to read data from these hashes for them to be _actually_ useful. Redis hash three commands to do so, `HGET`, to retrieve a single value, `HMGET`, to retrieve multiple values at once, and `HGETALL` to retrieve all the key/value pairs. Let's start with adding the `HGetCommand`: ``` ruby module BYORedis # ... class HGetCommand < BaseCommand def call Utils.assert_args_length(2, @args) hash = @db.lookup_hash(@args[0]) if hash.nil? NullBulkStringInstance else key = @args[1] value = hash[key] if value.nil? NullBulkStringInstance else RESPBulkString.new(value) end end end def self.describe Describe.new('hget', 3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@hash', '@fast' ]) end end end ``` _listing 8.8 The `HGetCommand` class_ If the hash does not exist, or if the hash exists but does not contain the field, we return a null string, otherwise, we return the string stored for that field. We need to add the ability to find a key/value pair to the `RedisHash` class: ``` ruby module BYORedis class RedisHash # ... def get(field) case @underlying when List then get_list(field) when Dict then @underlying[field] else raise "Unknown structure type: #{ @underlying }" end end alias [] get private # ... def get_list(field) iterator = List.left_to_right_iterator(@underlying) while iterator.cursor return iterator.cursor.value.value if iterator.cursor.value.key == field iterator.next end end end end ``` _listing 8.9 The `RedisHash#get` method_ Once again, the `Dict` branch is simpler, so we perform it inline, we call the `Dict#[]` method, and return its result, a string or nil. In the `List` case, we go to the `get_list` private method. The approach here is very similar to the `set_list` method we wrote earlier, we iterate through the list, starting at the head, and stop if we find a `ListEntry` for which the `key` attribute matches the `field` parameter. If no entry matches, the method returns `nil`. Note that this is a perfect example of the worst case scenario time complexity we previously discussed. If the `field` is not present in the hash, we still have to iterate through the entire list to check every `ListEntry` instances. Let's continue with the `HMGetCommand`: ``` ruby module BYORedis # ... class HMGetCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) key = @args.shift hash = @db.lookup_hash(key) if hash.nil? responses = Array.new(@args.length) else responses = @args.map do |field| hash[field] end end RESPArray.new(responses) end def self.describe Describe.new('hmget', -3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@hash', '@fast' ]) end end end ``` _listing 8.10 The `HMGetCommand` class_ The `HMGET` command is very similar to `HGET`, the only difference is that it accepts multiple fields as its input, and returns an array. The implementation uses the same method from `RedisHash`, `get`, which we use through its alias, `[]`, and call it in the block passed to `Array#map`. Using `map` here allows us to maintain the order of the results, we create an array where the n-th item will be the value for the n-th field passed as command argument after the hash key itself. If the hash does not exist, we use the `Array.new` method to create an array of `nil` values with the same length as the number of fields passed to the command. The last read command we need to add is `HGetAllCommand`. Because RESP2 does not have support for a map type, the result is an even-numbered array, containing an alternating sequence of keys and values. ``` ruby module BYORedis # ... class HGetAllCommand < BaseCommand def call Utils.assert_args_length(1, @args) hash = @db.lookup_hash(@args[0]) if hash.nil? pairs = [] else pairs = hash.get_all end RESPArray.new(pairs) end def self.describe Describe.new('hgetall', 2, [ 'readonly', 'random' ], 1, 1, 1, [ '@read', '@hash', '@slow' ]) end end end ``` _listing 8.11 The `HGetAllCommand` class_ This time we need a new method in `RedisHash`, `get_all`: ``` ruby module BYORedis class RedisHash # ... def get_all case @underlying when List then get_all_list when Dict then get_all_dict else raise "Unknown structure type: #{ @underlying }" end end private # ... def get_all_list iterator = List.left_to_right_iterator(@underlying) pairs = [] while iterator.cursor pairs.push(iterator.cursor.value.key, iterator.cursor.value.value) iterator.next end pairs end def get_all_dict pairs = [] @underlying.each do |key, value| pairs.push(key, value) end pairs end end end ``` The implementation for both data structures requires a few lines of code, so we move it to two private methods. In `get_all_list`, we follow the tried and true pattern we've used so far. We start iterating from the head, and accumulate the keys and values in an array. In the `get_all_dict` method, we rely on the `Dict#each` method, which iterates through all the pairs in the dictionary, and for each pair we push both the key and the value to an array, and return it. We now have a solid foundation for the Hash commands, we can add elements to the hash and read them back. Next on the list is the ability to increment values, if and only if the strings represent numeric values. ### Incrementing numeric values with HINCRBY & HINCRBYFLOAT Redis supports two commands to increment or decrement numeric values, `HINCRBY` & `HINCRBYFLOAT`. Decrement operations are performed using these commands with a negative argument. To decrement a value in a hash by 1, you would call `HINCRBY h key -1`. These commands are very similar to [`INCRBY`][redis-doc-incrby] and [`INCRBYFLOAT`][redis-doc-incrbyfloat] which operates on Strings at the top-level. The `*INCRBY` commands only accept integer increments, and will reject floats, the `*INCRBYFLOAT` commands accept both integers and floats. Even though you could use integer values with `HINCRBYFLOAT`, `HINCRBY` is still useful for two reasons, well really, only the first one _actually_ matters: **Exactness**: because the float based commands use floating point arithmetic, you're not guaranteed to get the result you'd expect, unexpected results can (and will) happen. Let's look at an example, imagine that you're building a bidding platforms where you store prices. It would be a fair requirement to increment the price of a product after a bid: ``` bash 127.0.0.1:6379> HSET product price 166.92 (integer) 1 127.0.0.1:6379> HINCRBYFLOAT product price 402.22 "569.14000000000000001" ``` Yikes, yeah, that's close, but that's not really what we'd expect, which is `569.14`. Floating point errors happen very often, for instance, many languages fail to return `3.3` for `1.1 + 2.2`, you can try it with Ruby, Python, Elixir, Scala, Haskell and Javascript, they all pretty much return the same thing: `3.3000000000000003`. The website [0.30000000000000004.com][floating-point-errors] shows even more examples across most programming languages and explains in more details the cause of this unexpected result. The bottom line is that floating point arithmetic suffers from precision issues, whereas integer operations do not. The only caveat to be aware of regarding integer arithmetic is around overflows, which we'll cover later when we implement the `HINCRBY` command. **A little bit less memory used**: Redis uses `long double` variables for the floating point numbers, which use 16 bytes of memory, whereas it uses `long long` for integers, which use 8 bytes of memory. That being said, note these types are only used while the command is processed, the data in the hash, whether it is a list or a dict is a string, which uses one byte per digit. The string `'1'` representing the integer `1` uses 1 byte, the string `'1.1'` representing the float `1.1` uses 3 bytes, and so on. **Important note about prices** If you're working on any systems that handle prices, avoid at all cost using floating point numbers. A common approach is to always manipulate prices in cents, or whatever is the smallest currency unit, and use integers. In the example above, we would have done the following: ``` bash 127.0.0.1:6379> HSET product price 16692 (integer) 1 127.0.0.1:6379> HINCRBY product price 40222 (integer) 56914 ``` With this approach, you only transform the price from cents to the "regular" unit, dollar, yuan, pound, euro by doing the appropriate division only when displaying it to the user in the expected unit. By doing so, you guarantee that addition and subtraction operations will never result in loss of precision, as long as they don't overflow. **HINCRBY** Let's start with `HINCRBY`, and before writing any code, let's play with it quickly in the repl: ``` bash 127.0.0.1:6379> HINCRBY h an-int 1 (integer) 1 127.0.0.1:6379> HINCRBY h an-int a (error) ERR value is not an integer or out of range 127.0.0.1:6379> HSET h not-an-int a (integer) 1 127.0.0.1:6379> HINCRBY h not-an-int 1 (error) ERR hash value is not an integer 127.0.0.1:6379> HINCRBY h an-int 9223372036854775806 (integer) 9223372036854775807 127.0.0.1:6379> HINCRBY h an-int 1 (error) ERR increment or decrement would overflow 127.0.0.1:6379> HINCRBY h an-int -9223372036854775807 (integer) 0 127.0.0.1:6379> HINCRBY h an-int -9223372036854775807 (integer) -9223372036854775807 127.0.0.1:6379> HINCRBY h an-int -1 (integer) -9223372036854775808 127.0.0.1:6379> HINCRBY h an-int -1 (error) ERR increment or decrement would overflow ``` As we can see in the previous example, calling `HINCRBY` on a non existing hash creates one, initializes the field's value to 0 and apply the increment afterwards. An error is return is the increment value is not an integer, and a different error is return if the value we're trying to increment cannot be represented an integer. The other examples show the behavior around integer overflows. Redis attempts to convert the stored string values as `long long`, which are represented as signed 64 bit integers. The maximum value of a `long long` is `2^63 - 1`, `9,223,372,036,854,775,807` and the minimum value is `-(2^63)`, `-9,223,372,036,854,775,808`. One might expect that the minimum should equal the inverse of the maximum, that is `min = -max`, but as we just saw that's not the case, we have `min = -(max + 1)`. This is a result of the representation of signed integers as [two's complement][wikipedia-twos-complement]. With this representation the first bit is used to represent the sign, 1 means negative, 0 means positive. The other 63 bits are used to encode the actual integer value, which is why the max and min values are around `2^63`. The biggest value that can be encoded is a zero, for the positive sign, followed by sixty-three `1`s, which is `2^63 - 1`. Let's look at an example with less bits, for the sake of simplicity. Imagine a three bit integer, the max value would be `2^2 - 1`, `3` and the min value would be `-(2^2)`, `-4`. As previously mentioned the max value is a zero followed by ones, `011`. To obtain `3` from this, we start from the right, with the first digit, a `1`, and use the index, starting at zero, as the power value, we get `2^0`, which is `1`, we then continue, another `1`, at index 1, which gives us `2^1`, `2`. `2 + 1 = 3` so far so good. Another way to get to this number is with `2^2 - 1`, also `3`. In plain English, "Two to the power of the number of bits minus 1, minus 1". The same exact approach can be applied to 63 bits instead of 2, `2^0 + 2^1 + 2^2 + ... + 2^62 = 2^63 - 1`. In order to confirm the min value, we need to look at how negative numbers are represented in two's complement representation. Two's complement is defined as: > The two's complement of an N-bit number is defined as its complement with respect to 2^N; the sum of a number and its two's complement is 2^N Let's take 2 as an example, represented in binary as `010`, using three bits. So, with N set to three, `2^N` is `8`, so to get to 8 from 2, we need 6, since `8 - 2 = 6`, `6` is `110` as a three bit integer, `2^2 + 2^1`. This tells us that the complement of `2`, is `6`, so `-2` is represented the same way we'd represent `6`, as `110`. Another, and probably easier, way to obtain the two's complement of a number is by inverting the digits and adding one. Using this definition, let's see how we would represent `-1`. `1` is `001`, because `2^0 = 1`, so to represent `-1`, we first flip all the bits, `110`, and add one, `111`. Let's do the same thing for `-2`, `2` is `010`, because `2^1 = 2`, so flipping the bits gives `101`, and adding one is `110`, using the same process, we get to `101` for `-3`. We have the representation of 7 numbers so far, `-3` (`101`), `-2` (`110`), `-1` (`111`), `0` (`000`), `1` (`001`), `2` (`010`) & `3` (`011`), but there are eight possible values with three bits, indeed, none of these numbers use `100`. For the previous numbers, we started from their decimal representation, but to show that `100` represents `-4`, we can use the opposite approach, convert a number from its two's representation, to its decimal version. So let's start with `100` and show that we end up with `-4`. To do so, we can start from the left, and the leftmost digit is treated differently from others, if `1`, it is negative, if zero, well, it's zero, there's nothing to do, we then proceed to add all the following power of twos, so for `100`, which is the third digit from the right, so index 2 in a 0-based system, `2^2 = 4`, but since it's a `1`, we start start at `-4`, we then add `0^1`, we use `1` as the power here because the second digit, has an index of 1, and we finally add `0^0`, for the rightmost digit, 0, at index 0, `-4 + 0 + 0 = -4`! We can illustrate this approach with the numbers we previously arrived at, let's look at `-3`/`101` for instance `-(2^2) + 0^1 + 1^1`, which can be expanded to `-4 + 0 + 1`, `-3`! It's important to note that with two's complement, it is impossible to represent negative zero, which does not exist in ordinary arithmetic, zero does not have a sign. It's time to create the `HIncrByCommand` class: ``` ruby module BYORedis # ... class HIncrByCommand < BaseCommand def call Utils.assert_args_length(3, @args) incr = Utils.validate_integer(@args[2]) key = @args[0] field = @args[1] hash = @db.lookup_hash_for_write(key) value = hash[field] if value.nil? value = 0 else value = Utils.string_to_integer(value) end if (incr < 0 && value < 0 && incr < (LLONG_MIN - value)) || (incr > 0 && value > 0 && incr > (LLONG_MAX - value)) raise IntegerOverflow else new_value = value + incr end hash[field] = Utils.integer_to_string(new_value) RESPInteger.new(new_value) rescue InvalidIntegerString RESPError.new('ERR hash value is not an integer') rescue IntegerOverflow RESPError.new('ERR increment or decrement would overflow') end def self.describe Describe.new('hincrby', 4, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@hash', '@fast' ]) end end end ``` _listing 8.12 The `HIncrByCommand` class_ Once the validations are done, we look at the value for the given field and initialize it to `0` if the field does not exist. If the field does exist, we want to convert the string to an integer, returning an error if it cannot be converted. We use a new method in the `Utils` module to do so, `string_to_integer`. The next step in an integer overflow check. This check is artificial in a language like Ruby that supports overflowing numbers, but, in order to both keep compatibility with Redis as well as understand how integer arithmetic works, we're imposing these arbitrary constraints on ourselves here. We want to check that the operation will not result in an overflow. An overflow would happen if the sum of the old value and the new value were to be greater than the max value that can be represented by a signed 64-bit integer, `2^63-1` or lower than the minimum value, `-2^63`. We created two constants to hold these values, `LLONG_MIN` & `LLONG_MAX`, which happen to be defined in the `climits.h` header file in C. We _could_ have written these lines in a way that might be considered easier to read, with: ``` ruby new_value = value + incr if new_value > LLONG_MAX || new_value < LLONG_MIN ``` While this would work, this is a little bit of a chicken and egg problem, we'd be relying on the fact that the operation did overflow to raise an exception, but we wouldn't be able to know that the operation overflowed in a system where such situations can happen, like in C, because it would have overflowed. In other words, the condition could never have been true because no signed integer can be greater than `LLONG_MAX` and no signed integer can be lower than `LLONG_MIN`. So far we were relying on the `Kernel#Integer` method to parse strings to integers. While this worked well until now, doing this is a little bit like "cheating". As a matter of fact, Redis uses its own function to transform a string to a `long long`: [`string2ll`][redis-src-string2ll]. Let's now add the `string_to_integer` method to the `Utils` module: ``` ruby module BYORedis ULLONG_MAX = 2**64 - 1 # 18,446,744,073,709,551,615 ULLONG_MIN = 0 LLONG_MAX = 2**63 - 1 # 9,223,372,036,854,775,807 LLONG_MIN = 2**63 * - 1 # -9,223,372,036,854,775,808 IntegerOverflow = Class.new(StandardError) InvalidIntegerString = Class.new(StandardError) module Utils # ... def self.string_to_integer(string) raise InvalidIntegerString, 'Empty string' if string.empty? bytes = string.bytes zero_ord = '0'.ord # 48, 'a'.ord == 97, so return 0 if bytes.length == 1 && bytes[0] == zero_ord if bytes[0] == '-'.ord negative = true bytes.shift raise InvalidIntegerString, 'Nothing after -' if bytes.empty? else negative = false end unless bytes[0] >= '1'.ord && bytes[0] <= '9'.ord raise InvalidIntegerString end num = bytes[0] - zero_ord 1.upto(bytes.length - 1) do |i| unless bytes[i] >= zero_ord && bytes[i] <= '9'.ord raise InvalidIntegerString, "Not a number: '#{ bytes[i] }' / '#{ [ bytes[i] ].pack('C') }'" end raise IntegerOverflow, 'Overflow before *' if num > ULLONG_MAX / 10 num *= 10 raise IntegerOverflow, 'Overflow before +' if num > ULLONG_MAX - (bytes[i] - zero_ord) num += bytes[i] - zero_ord end if negative && num > -LLONG_MIN # In Redis, the condition is: # # if (v > ( (unsigned long long) (-(LLONG_MIN+1)) +1) ) # # But used to be (-(unsigned long long)LLONG_MIN) until this commit: # https://github.com/redis/redis/commit/5d08193126df54405dae3073c62b7c19ae03d1a4 # # Both seem to be similar but the current version might be safer on different machines. # Essentially it adds one to LLONG_MIN, so that multiplying it by -1 with the - operator # falls within the boundaries of a long long, given that min can be -9...808 while max # is always 9...807, we then cast the positive value to an unsigned long long, so that # we can add 1 to it, turning it into 9...808 # The C standard does not seem to be very specific around the exact value of LLONG_MIN # it seems to either be -9..807 or, as it is on my machine, a mac, -9...808, which is # because it uses Two's Complement. raise IntegerOverflow, 'Too small for a long long' elsif negative -num elsif num > LLONG_MAX raise IntegerOverflow, 'Too big for a long long' else num end end end end ``` _listing 8.13 The `string_to_integer` method_ There's a lot going on in this method, so let's take it one step at a time. The overall approach is to look at all the characters in the string, starting from the left, and converting them to a number, and accumulate it to the final result. The accumulated number is an unsigned number, and the last step is to make sure that the parsed number can fit within a signed number. Let's dive right in: If the string is empty, there's no need to continue, we raise an `InvalidIntegerString`, which is rescued in the command class to return the `value is not an integer or out of range` error. The next step is to get all the bytes in the string, which is what we'll be iterating over. Note that an array of bytes is how strings are represented in C, with the type `char buf[]`, a `char` is an 8-bit type, a byte. While it could have been tempting to use the `String#[]` method, as we've shown in [Chapter 5][chapter-5], the Ruby String class performs a few tricks under the hood to deal with characters spanning over more than one byte. The following is an example using the wave emoji: ``` ruby irb(main):102:0> s = '👋' irb(main):103:0> s[0] => "👋" irb(main):104:0> s.bytes => [240, 159, 145, 139] ``` As we can see the `String#[]` method makes it look like there's only one character, when there are actually four bytes in that string. The bytes are returned as numbers, between 0 and 255, the range of an 8-bit integer: ``` ruby irb(main):110:0> 'abc'.bytes => [97, 98, 99] irb(main):111:0> '123'.bytes => [49, 50, 51] ``` The next step is a small helper variable we'll need throughout the method. In Redis, they use `'0'` which can be used for integer arithmetic, and is replaced by its ASCII representation, 48. Because we will need this value a lot, we store it in a variable to avoid having to use `'0'.ord` throughout the method. The [`String#ord`][ruby-doc-string-ord] method returns the 'ordinal' value, that is its value in the ASCII encoding, `'a'` is `97`, `'b'` is `98`, `'1'` is `49`, `'2'` is `50` and so on. We can see that these values correspond to what the `String#bytes` method returns. If the string only contains one byte and that byte is equal to `48`, the value of the zero character, then we return `0` right away, the work is done. In the case where the first character is equal to `45`, which is the value returned by `'-'.ord`, then we set the boolean variable `negative` to true, so that we know to return a negative number at the end of the method. We also call `bytes.shift` to remove the negative sign from the byte array. If the array is empty after that, that is, we only received a string containing a negative sign, we raise an `InvalidIntegerString` error, the input is invalid. The first digit of a number cannot be `0`, it can only be between `1` and `9`, so we raise an error if the first byte is not in that range, between `49` (`'1'.ord`) and `57` (`'9'.ord`). We then initialize the `num` variable, which we'll be our accumulator throughout the method, to `num = bytes[0] - zero_ord`. The operation `bytes[0] - zero_ord` returns the integer value of a character representing a digit between `0` and `9`. This is because the value of the character `'0'` in ASCII is `48`, and only goes up from there, so the character `'5'`, which is `53` in ASCII, will return `5` when doing `'5'.ord - zero_ord`. Now that the first digit was converted, we need to convert the rest of the string, where this time `0` is now an acceptable value, since numbers cannot start with a zero but can contain a zero afterwards. In the loop, we start by checking that the current byte is within `48` & `57` and raise an error if it is isn't. We then need to perform a few overflow checks. For the sake of simplicity, let's imagine that we were dealing with 8-bit numbers, where the maximum value would be `255` for an unsigned number, `2^8 - 1`. Let's manually go through the steps for the number `254`, in this case, by the time we enter the loop, `num` would have been set to `'2'.ord - zero_ord`, `2`. In the loop, we'd start with `i` set to `1`, giving us `bytes[1] == '5'`. The range check would pass, `'5'.ord` is `53`, it is between `48` and `57`. The next check is `num > ULLONG_MAX / 10`, `ULLONG_MAX` is actually `2^64 - 1`, but in our simplified 8-bit example, it is `2^8 - 1`, `255`. `255 / 10` would return `25`, because this is an integer division, and `num`, `2`, is not greater than that, so the check would pass, we then multiply `num` by `10`, now that we know that multiplying it by `10` will not overflow. We then check that `num > ULLONG_MAX - (bytes[i] - zero_ord)`, which is essentially a way to check that adding the next digit from the string to `num` will not overflow. `bytes[i]` is `'5'`, subtracting `zero_ord` returns `5`, so we check that `20 > 255 - 5`, `20` is not greater than `250`, so we can perform the addition, `num` is now `25`. Repeating these steps in the next iteration, we look at the next character, `'4'`, `25` is not greater than `25`, so we multiply `num` by `10`, giving us `250`, and `250` is not greater than `255 - 4`, so we add `4` to `num` and get the final result, `254`. Let's quickly look at two examples that would have raised overflow errors. If we had attempted to parse `256`, we would have entered the loop with `num` set to `2`, similarly as above, left the iteration at `25`, multiplied by `10`, and then failed the check `250 > 255 - 6`. `255` is greater than `249`, so we cannot add `6` to `255`, it does not fit. The other failure happens with numbers greater than `299`, let's try with `300`. We would enter the loop with `num` set to `3`, exited the first iteration with `num` set to `30`, and in the second iteration, we would fail the check `30 > 25`. This tells us that we cannot multiply `30` by `10` and stay within the bounds of the integers we can represent. The next steps take care of handling the sign of the number. If `negative` is `true`, then we need to multiple `num` by `-1`, but before doing so, we need to check it is within the limits of a signed integer. So far we've parsed the numbers as an unsigned integer, which can go up to `2^64-1`, but the minimum value of a signed integer is `-2^63`, so if num is greater than `-LLONG_MIN`, `9,223,372,036,854,775,808`, then we raise an overflow error, otherwise, we can safely multiple `num` by `-1`. In other words, if `num` is `9,223,372,036,854,775,808` or lower, we can multiply it by `-1`, if it is `9,223,372,036,854,775,809` or more, then it would not fit. We perform a similar check if `negative` is `false` and the final number should be positive, in that case, we check that `num` is not greater than `LLONG_MAX`, `2^63 - 1`, `9,223,372,036,854,775,807`, and if it is, we raise an overflow error. Finally, if all the checks passed, we return `num`! We can now rewrite `validate_integer` to use our own `string_to_integer` method: Up until now we were using the `OptionUtils.validate_integer` method, which used the ruby `Integer` class to transform a `String` instance to an `Integer` instance, we can now use `string_to_integer` instead. So, let's delete the `option_utils` file altogether and only use the `Utils` module: ``` ruby module BYORedis module Utils # ... def self.validate_integer(str) string_to_integer(str) rescue IntegerOverflow, InvalidIntegerString raise ValidationError, 'ERR value is not an integer or out of range' end end end ``` _listing 8.14 The `validate_integer` method_ We catch both exceptions here `IntegerOverflow` and `InvalidIntegerString`, and raise a `ValidationError` instead. This allows us to keep using the code in `BaseCommand` we introduced in the previous chapter. The last method we need to add to the `Utils` module is `integer_to_string`, which we need to convert the new value back to a string before updating the value in the hash. ``` ruby module BYORedis module Utils # ... def self.integer_to_string(integer) return '0' if integer == 0 v = integer >= 0 ? integer : -integer zero_ord = '0'.ord bytes = [] until v == 0 bytes.prepend(zero_ord + v % 10) v /= 10 end bytes.prepend('-'.ord) if integer < 0 bytes.pack('C*') end end end ``` _listing 8.15 The `validate_integer` method_ We start this method by converting the input to a positive integer in case it was negative, this allows us to process it regardless of its sign, and we prepend the `'-'` character at the end if the input was indeed negative. We create an empty array, which we'll use to accumulate all the bytes representing all the characters of the string. We then loop until `v` reaches `0`. In each iteration of the loop we get the character value by getting the modulo 10 of the input. Getting the modulo 10 essentially returns the right most digit. `255 % 10 = 5`, `36 % 10 = 6`. Once we have the decimal value of the rightmost digit, we add it to `zero_ord`, `48`, to get the ASCII value of that number. The last step of the loop is to divide `v` by 10, to shift the whole number to the right, with the previous two examples, `255` would become `25`, and `36` would become `3`. Once the loop exits, we have an array of number, representing the byte values of the string. We can now use the `pack` method to transform it a Ruby String. The `C` format tells Ruby to treat each number in the array as an 8-bit value representing a character, so it knows that `48` will be `'0'`, `49`, `'1'` and so on. And with that, we have a working implementation of the `HINCRBY` command. **HINCRBYFLOAT** Ruby has a `Float` class, which, quoting the [official documentation][ruby-doc-float]: > represent inexact real numbers using the native architecture's double-precision floating point representation. While we could use the `Float` class to implement the `HINCRBYFLOAT` command, its precision is inferior to the implementation in Redis. Redis always use 17 digits precision, and with Ruby's `Float` class, we'd be stuck with at most a double-precision floating point number, which is a `double` in C. Redis uses [`long double`][wikipedia-long-double], which offer greater precision. Ruby does not provide an easy way to use `long double` numbers, but it provides another class to handle number with decimal digits, [`BigDecimal`][ruby-doc-bigdecimal]: > provides arbitrary-precision floating point decimal arithmetic The `BigDecimal` class provides so many features that it could be considered "cheating" according to the rules I set for this book, but dealing with floating point is a really complicated topic, and, to some extent, is not _that_ central to how Redis works. That being said, even the Redis codebase does not perform all the float operations "from scratch". The conversion from a string to a `long double` is performed with the [`strtold`][c-std-strtold] function provided by the C standard library. This function takes care of a lot of the heavy lifting, such as parsing numbers using the [E notation][wikipedia-e-notation], like `1.1234e5` being parsed to `112,340.0`. The conversion back from a `long double` to a string is then performed with `snprintf("%.17Lf")`, which is another function provided by the C standard library. Let's look at how `BigDecimal` works: ``` ruby irb(main):001:0> require 'bigdecimal' => true irb(main):002:0> 0.1 + 0.2 => 0.30000000000000004 irb(main):003:0> BigDecimal(0.1, 1) + BigDecimal(0.2, 1) => 0.3e0 ``` The `BigDecimal` constructor, which weirdly enough is the [method `BigDecimal` on the `Kernel` class][ruby-doc-big-decimal-method], requires two arguments if the first argument is a float, to determine how many significant digits should be considered. In this example, one is enough, but let's look at an example with other numbers to see its impact: ``` ruby irb(main):008:0> BigDecimal(0.123, 2) => 0.12e0 ``` We passed the float `0.123`, but because we told `BigDecimal` to only consider two significant digits, the result is a `BigDecimal` object representing the number `0.12`. Let's just check what Redis returns for the same operation: ``` bash 127.0.0.1:6379> HINCRBYFLOAT h 1 0.1 "0.1" 127.0.0.1:6379> HINCRBYFLOAT h 1 0.2 "0.3" ``` The example above illustrates that _some_ rounding errors we observe in Ruby, and other languages, with double-precision floating numbers are avoided with the `long double` type. So now that we settled on the `BigDecimal` class, it's time to create the command class: ``` ruby module BYORedis # ... class HIncrByFloatCommand < BaseCommand def call Utils.assert_args_length(3, @args) incr = Utils.validate_float(@args[2], 'ERR value is not a valid float') key = @args[0] field = @args[1] hash = @db.lookup_hash_for_write(key) value = hash[field] if value.nil? value = BigDecimal(0) else value = Utils.validate_float(value, 'ERR hash value is not a float') end new_value = value + incr if new_value.nan? || new_value.infinite? RESPError.new('ERR increment would produce NaN or Infinity') else new_value_as_string = Utils.float_to_string(new_value) hash[field] = new_value_as_string RESPBulkString.new(new_value_as_string) end rescue InvalidFloatString RESPError.new('ERR hash value is not a float') end def self.describe Describe.new('hincrbyfloat', 4, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@hash', '@fast' ]) end end end ``` _listing 8.16 The `HIncrByFloatCommand` class_ In the previous chapter we introduced the `OptionUtils.validate_float` method, but as we just did with `validate_integer`, we are going to use a new method in the `Utils` package, and use `BigDecimal` instead of the `Float` class as we used to: ``` ruby module BYORedis module Utils # ... def self.validate_float(str, error_message) case str.downcase when '+inf', 'inf', 'infinity', '+infinity' then BigDecimal::INFINITY when '-inf', '-infinity' then -BigDecimal::INFINITY else parsed = BigDecimal(str) if parsed.nan? raise ArgumentError else parsed end end rescue ArgumentError, TypeError raise ValidationError, error_message end end end ``` _listing 8.17 The `validate_float` method_ The method mainly relies on `Kernel#BigDecimal` to do the heavy lifting, but we have to add a few custom pieces of logic. The first one is to translate the Redis representation of infinity to the `BigDecimal` one. Redis recognizes the strings `'inf'`, `'+inf'`, `'infinity'`, `'+infinity'`, `'-inf'` & `'-infinity'` as special values representing the positive and negative infinity values, which are valid floats. We use `case str.downcase` to ignore the case of the string, like Redis does. The string `'+InFiNiTy'` is valid. The constraint of the `HINCRBYFLOAT` regarding infinity are interesting given that `HSET` can be used to set the value of a field to either `infinity` or `-infinity` but the result of `HINCRBYFLOAT` cannot be either of these values: ``` bash 127.0.0.1:6379> HSET h valid-inf inf (integer) 1 127.0.0.1:6379> HSET h invalid-inf infi (integer) 1 127.0.0.1:6379> HINCRBYFLOAT h valid-inf inf (error) ERR increment would produce NaN or Infinity 127.0.0.1:6379> HINCRBYFLOAT h invalid-inf inf (error) ERR hash value is not a float ``` This example shows that setting the value to `inf` means that Redis considers it to be a valid float, but rejects the operation because the result of `inf + inf` would result in infinity, and it refuses to do so. On the other hand, we can see that if the value in the hash was set to `infi`, which is _just_ a regular string, then it fails with a different error, telling us that it can't perform the operation because the value in the hash is not a valid float. The first error message also mentions `NaN`, which stands for **N**ot **A** **N**umber. `NaN` can happen for operations that cannot result in a valid result, such as the following: ``` ruby irb(main):122:0> BigDecimal::INFINITY - BigDecimal::INFINITY => NaN ``` In order to replicate this logic, we use the `BigDecimal#infinite?` and `BigDecimal#nan?` methods to raise an exception if the result of the operation is not valid for Redis. The last step is similar to the one in `HINCRBY`, we convert the value back to a string, store it in the hash and return it. Let's look at `float_to_string`: ``` ruby module BYORedis module Utils # ... def self.float_to_string(big_decimal) if big_decimal == BigDecimal::INFINITY 'inf' elsif big_decimal == -BigDecimal::INFINITY '-inf' elsif (truncated = big_decimal.truncate) == big_decimal # Remove the .0 part of the number integer_to_string(truncated) else big_decimal.to_s('F') end end end end ``` _listing 8.18 The `float_to_string` method_ If the value is either `INFINITY` or `-INFINITY`, we transform it to the valid Redis representation, `inf` & `-inf`. This is not necessary for now, but will become useful with other commands. In the case where the value could be represented as an integer, that is, there are only zeroes on the right side, we want to only return the left side. That is, if the value is `2.0`, we want to return `2`. Checking if the truncated number is the same as the number is a way to test whether or not the number is an integer, in which case we use the `integer_to_string` method. We have to do this because the `to_s` method would otherwise return the number `2.0`. Finally, we use the `to_s` method on `BigDecimal` with the `F` argument, which returns the number using "conventional floating point notation", it would otherwise use the E notation: ``` ruby irb(main):124:0> BigDecimal('1.2345').to_s('F') => "1.2345" irb(main):125:0> BigDecimal('1.2345').to_s => "0.12345e1" ``` We can now use the `validate_float` method to create the `validate_timeout` method, which we can use for the blocking methods we created in the previous chapter: ``` ruby module BYORedis module Utils # ... def self.validate_timeout(str) timeout = validate_float(str, 'ERR timeout is not a float or out of range') raise ValidationError, 'ERR timeout is negative' if timeout < 0 || timeout.infinite? timeout end end end ``` _listing 8.19 The `validate_timeout` method_ And we can now update the blocking list commands: ``` ruby module BYORedis # ... module ListUtils # ... def self.common_bpop(db, args, operation) Utils.assert_args_length_greater_than(1, args) timeout = Utils.validate_timeout(args.pop) list_names = args # ... end # ... end # ... class BRPopLPushCommand < BaseCommand def call Utils.assert_args_length(3, @args) source_key = @args[0] source = @db.lookup_list(source_key) timeout = Utils.validate_timeout(@args[2]) destination_key = @args[1] # ... end # ... end end ``` _listing 8.20 Updates to the blocking list commands_ ### Utility commands We have six more commands to add, which happen to be simpler than the ones we added earlier. Let's start with a really useful one, `HDEL`. **HDEL** `HDEL` allows clients to delete one or more fields in a hash: ``` ruby module BYORedis # ... class HDelCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) key = @args.shift hash = @db.lookup_hash(key) delete_count = 0 if hash delete_count += @db.delete_from_hash(key, hash, @args) end RESPInteger.new(delete_count) end def self.describe Describe.new('hdel', -3, [ 'write', 'fast' ], 1, 1, 1, [ '@write', '@hash', '@fast' ]) end end end ``` _listing 8.21 The `HDelCommend` class_ We call the `DB#delete_from_hash` method, so let's create this method now: ``` ruby module BYORedis class DB # ... def delete_from_hash(key, hash, fields) delete_count = 0 fields.each do |field| delete_count += (hash.delete(field) == true ? 1 : 0) end @data_store.delete(key) if hash.empty? delete_count end end end ``` _listing 8.22 The `delete_from_hash` method_ The method iterates over all the given fields and calls `RedisHash#delete`, incrementing a counter for all successful deletions, returning this count at the end of the process. The method also takes care of deleting the hash from the database if the hash is empty after deleting all fields. Let's look at the `delete` method: ``` ruby module BYORedis class RedisHash # ... def delete(field) case @underlying when List then was_deleted = delete_from_list(field) when Dict then was_deleted = !@underlying.delete(field).nil? if was_deleted && length - 1 == Config.get_config(:hash_max_ziplist_entries) convert_dict_to_list elsif @underlying.needs_resize? @underlying.resize end else raise "Unknown structure type: #{ @underlying }" end was_deleted end private # ... def convert_dict_to_list list = List.new @underlying.each do |key, value| list.right_push(ListEntry.new(key, value)) end @underlying = list end def delete_from_list(field) was_deleted = false iterator = List.left_to_right_iterator(@underlying) while iterator.cursor if iterator.cursor.value.key == field @underlying.remove_node(iterator.cursor) return true end iterator.next end was_deleted end end end ``` _listing 8.23 The `RedisHash#delete` method_ The deletion process for a list is delegated to the private method `delete_from_list`, while it is inlined for a `Dict`. For the latter, we call the `Dict#delete` method, which returns `nil` if nothing was deleted, or the value for the key it is was found and deleted. We perform two additional checks, first, if the size of the hash is now below the threshold, we convert the dict back to a list, through the private method `convert_dict_to_list`. Finally, we check whether or not the `Dict` instance needs resizing, `Dict` instances automatically grow but do not automatically shrink, so this check will make sure that a `Hash` can reduce its memory footprint and avoid waste. The `delete_from_list` method should look pretty familiar at this point, we iterate starting from the head, and keep going until we find the element we're trying to delete. When we do find the list entry we need to remove, we call a new method on the `List` class: `List#remove_node`: ``` ruby module BYORedis class List ListNode = Struct.new(:value, :prev_node, :next_node) do def remove if prev_node prev_node.next_node = next_node end if next_node next_node.prev_node = prev_node end self.next_node = nil self.prev_node = nil end end # ... def remove_node(node) if @head == node @head = node.next_node end if @tail == node @tail = node.prev_node end node.remove @size -= 1 end # ... end end ``` _listing 8.24 The `List#remove_node` & `ListNode#remove` methods_ The `remove_node` method removes the given node from the list, while updating the `@head` and `@tail` variables if needed. It uses the `ListNode#remove` method, which delegates all the `next_node`/`prev_node` handling to the struct itself. The whole process is very mechanical and reminiscent of the previous chapter, all the node pointers have to be updated, while being careful to check for nil values at each step of the way. **HEXISTS** The `HEXISTS` commands is used to check for the existence of a key inside a hash. Note that because RESP does have a boolean type, it returns a boolean, `1` if the key exists, `0` otherwise. ``` ruby module BYORedis # ... class HExistsCommand < BaseCommand def call Utils.assert_args_length(2, @args) hash = @db.lookup_hash(@args[0]) if hash.nil? RESPInteger.new(0) else value = hash[@args[1]] if value.nil? RESPInteger.new(0) else RESPInteger.new(1) end end end def self.describe Describe.new('hexists', 3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@hash', '@fast' ]) end end end ``` _listing 8.25 The `HDelCommend` class_ The command uses the `RedisHash#get`, through its `[]` alias, to check for the existence of the field, and return the appropriate number, acting as a boolean. **HKEYS** The `HKEYS` command is used to list all the keys inside a hash: ``` ruby module BYORedis # ... class HKeysCommand < BaseCommand def call Utils.assert_args_length(1, @args) hash = @db.lookup_hash(@args[0]) if hash.nil? EmptyArrayInstance else RESPArray.new(hash.keys) end end def self.describe Describe.new('hkeys', 2, [ 'readonly', 'sort_for_script' ], 1, 1, 1, [ '@read', '@hash', '@slow' ]) end end end ``` _listing 8.26 The `HKeysCommand` class_ The command uses the new `RedisHash#keys` method: ``` ruby module BYORedis class RedisHash # ... def keys case @underlying when List then keys_list when Dict then @underlying.keys else raise "Unknown structure type: #{ @underlying }" end end # ... def keys_list iterator = List.left_to_right_iterator(@underlying) keys = [] while iterator.cursor keys << iterator.cursor.value.key iterator.next end keys end # ... end end ``` _listing 8.27 The `RedisHash#keys` method_ When `@underlying` is a `Dict`, we can delegate directly to the `Dict#keys` method, on the other hand, if it is a `List`, we need to manually iterate through all the pairs in the list and accumulate the keys in an array. **HVALS** `HVALS` is very similar to `HKEYS`, except that it returns all the values: ``` ruby module BYORedis # ... class HValsCommand < BaseCommand def call Utils.assert_args_length(1, @args) hash = @db.lookup_hash(@args[0]) if hash.nil? EmptyArrayInstance else RESPArray.new(hash.values) end end def self.describe Describe.new('hvals', 2, [ 'readonly', 'sort_for_script' ], 1, 1, 1, [ '@read', '@hash', '@fast' ]) end end end ``` _listing 8.28 The `HValsCommand` class_ This implementation is also very similar to `HKeysCommand`, except that we call `RedisHash#values`: ``` ruby module BYORedis class RedisHash # ... def values case @underlying when List then values_list when Dict then @underlying.values else raise "Unknown structure type: #{ @underlying }" end end private # ... def values_list iterator = List.left_to_right_iterator(@underlying) values = [] while iterator.cursor values << iterator.cursor.value.value iterator.next end values end end end ``` _listing 8.29 The `RedisHash#values` method_ Similarly to `RedisHash#keys`, in the `Dict` case we call `Dict#values`, and in the `List` case we iterate through the list and accumulate all the values in an array. **HLEN** `HLEN` returns the number of key/value pairs in the hash: ``` ruby module BYORedis # ... class HLenCommand < BaseCommand def call Utils.assert_args_length(1, @args) hash = @db.lookup_hash(@args[0]) hash_length = 0 unless hash.nil? hash_length = hash.length end RESPInteger.new(hash_length) end def self.describe Describe.new('hlen', 2, [ 'readonly', 'sort_for_script' ], 1, 1, 1, [ '@read', '@hash', '@slow' ]) end end end ``` _listing 8.30 The `HLenCommand` class_ We use the `RedisHash#length` method to return the length of the hash: ``` ruby module BYORedis class RedisHash # ... def length case @underlying when List then @underlying.size when Dict then @underlying.used else raise "Unknown structure type: #{ @underlying }" end end # ... end end ``` _listing 8.31 The `RedisHash#length` method_ The `length` method is pretty succinct, it either calls `List#size` or `Dict#used`, which both return the number of elements they contain. **HSTRLEN** Finally, `HSTRLEN` returns the length of the value for the given key inside a hash: ``` ruby module BYORedis # ... class HStrLenCommand < BaseCommand def call Utils.assert_args_length(2, @args) key = @args[0] field = @args[1] hash = @db.lookup_hash(key) value_length = 0 unless hash.nil? value = hash[field] value_length = value.length unless value.nil? end RESPInteger.new(value_length) end def self.describe Describe.new('hstrlen', 3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@hash', '@fast' ]) end end end ``` _listing 8.32 The `HStrLenCommand` class_ This command does not need any new methods from the `RedisHash` class, it obtains the string stored at `field` with the `RedisHash#get` method and uses the Ruby `String#length` method to return its length. ## Refactoring the test utilities We introduced the `Config` class in this chapter, but there's no way to change the default values. We are going to add the `CONFIG GET` & `CONFIG SET` commands, in order to update config values at runtime and test the `RedisHash` class behavior with both a `List` and a `Dict` as the underlying data structure. Let's first add the `ConfigCommand` class. The `CONFIG` command is different from all the other commands we've implemented so far in that it supports sub-commands. We are only adding support for the `GET` & `SET` sub-commands here, but the real Redis also supports `CONFIG RESETSTAT` & `CONFIG REWRITE`. ``` ruby module BYORedis class ConfigCommand < BaseCommand def call if @args[0] != 'SET' && @args[0] != 'GET' message = "ERR Unknown subcommand or wrong number of arguments for '#{ @args[0] }'. Try CONFIG HELP." RESPError.new(message) elsif @args[0] == 'GET' Utils.assert_args_length(2, @args) value = Config.get_config(@args[1].to_sym) return RESPBulkString.new(Utils.integer_to_string(value)) elsif @args[0] == 'SET' Utils.assert_args_length_greater_than(2, @args) @args.shift # SET @args.each_slice(2) do |key, _| raise RESPSyntaxError if key.nil? || value.nil? Config.set_config(key, value) end end OKSimpleStringInstance end def self.describe Describe.new('config', -2, [ 'admin', 'noscript', 'loading', 'stale' ], 0, 0, 0, [ '@admin', '@slow', '@dangerous' ]) end end end ``` _listing 8.33 The `ConfigCommand` class_ The version of `CONFIG GET` we implemented is a simplified version of the one in Redis which supports glob-style patterns, with `*`. With these two new commands, we can now update the config values in our test, which will allow us to lower the value of `hash_max_ziplist_entries` so that we don't have to add 513 items to hash for it to be converted to a `Dict`. Ideally we'll want to run all our tests under different combinations of configuration values. The problem with the current approach to testing is that we spin up a new server for each test, which adds quite some time to each test as forking a new process and start a Ruby process within it takes some time. We will instead start a single process, and reuse it across our tests. In order to do so, we need to do a little bit of work to make sure that the state of the server is clean for each tests. For instance, if a tests sends the `BRPOPLPUSH a b 1` command, we want to make sure that if a next test runs within a second, that the first client correctly disconnected. We also need to make sure that the database is in a clean state, and for that we will implement the `FLUSHDB` command: ``` ruby module BYORedis class FlushDBCommand < BaseCommand def initialize(db, args) @db = db @args = args end def call Utils.assert_args_length(0, @args) @db.flush OKSimpleStringInstance end def self.describe Describe.new('flushdb', 1, [ 'write' ], 1, -1, 1, [ '@keyspace', '@write', '@slow' ]) end end end ``` _listing 8.34 The `FlushDBCommend` class_ Let's add the `DB#flush` method: ``` ruby module BYORedis class DB # ... def initialize @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL flush end def flush @data_store = Dict.new @expires = Dict.new @ready_keys = Dict.new @blocking_keys = Dict.new @client_timeouts = SortedArray.new(:timeout) @unblocked_clients = List.new end # ... end end ``` _listing 8.35 The `DB#flush` method_ Ruby makes our lives really easy here, to flush the database, we can simply instantiate a few fresh `Dict`, `List` and `SortedArray` and call it a day, the garbage collector will take care of freeing the memory of the previous ones now that they're not referenced anymore. We now need to make some changes to the `test_helper.rb` file. ``` ruby # test_helper.rb require 'timeout' require 'stringio' require 'logger' ENV['LOG_LEVEL'] = 'FATAL' unless ENV['LOG_LEVEL'] require_relative '../server' $child_process_pid = nil $socket_to_server = nil def restart_server kill_child $child_process_pid = nil start_server $socket_to_server = nil end def start_server if $child_process_pid.nil? if !!ENV['DEBUG'] options = {} else options = { [ :out, :err ] => '/dev/null' } end start_server_script = <<~RUBY begin BYORedis::Server.new rescue Interrupt end RUBY $child_process_pid = Process.spawn('ruby', '-r', './server', '-e', start_server_script, options) end end start_server # Make sure that we stop the server if tests are interrupted with Ctrl-C Signal.trap('INT') do kill_child exit(0) end require 'minitest/autorun' def do_teardown with_server do |socket| socket.write(to_query('FLUSHDB')) read_response(socket) args = BYORedis::Config::DEFAULT.flat_map do |key, value| [ key.to_s, value.to_s ] end socket.write(to_query('CONFIG', 'SET', *args)) read_response(socket) end end class MiniTest::Test def teardown with_server do do_teardown end rescue Errno::EPIPE, IOError => e $socket_to_server&.close $socket_to_server = nil connect_to_server do_teardown p "Exception during teardown: #{ e.class }/ #{ e }" end end def kill_child if $child_process_pid Process.kill('INT', $child_process_pid) begin Timeout.timeout(1) do Process.wait($child_process_pid) end rescue Timeout::Error Process.kill('KILL', $child_process_pid) end end rescue Errno::ESRCH # There was no process ensure if $socket_to_server $socket_to_server.close $socket_to_server = nil end end MiniTest.after_run do kill_child end def connect_to_server return $socket_to_server if !$socket_to_server.nil? && !$socket_to_server.closed? # The server might not be ready to listen to accepting connections by the time we try to # connect from the main thread, in the parent process. Using timeout here guarantees that we # won't wait more than 1s, which should more than enough time for the server to start, and the # retry loop inside, will retry to connect every 10ms until it succeeds connect_with_timeout rescue Timeout::Error # If we failed to connect, there's a chance that it's because the previous test crashed the # server, so retry once p "Restarting server because of timeout when connecting" restart_server connect_with_timeout end def connect_with_timeout Timeout.timeout(1) do loop do begin $socket_to_server = TCPSocket.new 'localhost', 2000 break rescue StandardError => e $socket_to_server = nil sleep 0.2 end end end $socket_to_server end def with_server server_socket = connect_to_server yield server_socket server_socket.close end ``` _listing 8.36 Updates to the `test_helper.rb` file_ Bare with me for a minute, I know that global variables are frowned upon, but we're only using them to make our lives easier. I would not describe global variables as something to never use, but instead, as something to be extremely careful with. They can indeed become really problematic if they're used a lot throughout a codebase, especially if the value they hold changes a lot. Doing so could require a lot of headache . By using a global variable, we make it easier to maintain a single instance of the child process, without having to create a class, instantiate it, and burying the logic, what we want is actually not that much: - At the beginning of the test, spawn a new process in which we start the server, keep the pid of this process - For each test, create a socket and connect it to the server. At the end of the test, disconnect the socket - If the server crashes, we want to restart it so that subsequent tests work - At the end of each test, we want to run the `FLUSHDB` command so that next tests start with a clean database This big refactor of the test context now allows us to use the following helper. Using this approach, which creates many more tests, would have been really slow with the "start a new process for each test approach", but now, each of these tests only generates a few round trips to the server, which is really fast, in the sub millisecond range. ``` ruby # test_helper.rb def test_with_config_values(combinations) # This line goes from a hash like: # { config_1: [ 'config_1_value_1', 'config_2_value_2' ], # config_2: [ 'config_2_value_1', 'config_2_value_2' ] } # to: # [ [ [:config_1, "config_1_value_1"], [:config_1, "config_2_value_2"] ], # [ [:config_2, "config_2_value_1"], [:config_2, "config_2_value_2"] ] ] config_pairs = combinations.map { |key, values| values.map { |value| [ key, value ] } } # This line combines all the config values into an array of all combinations: # [ [ [ :config_1, "config_1_value_1"], [:config_2, "config_2_value_1" ] ], # [ [ :config_1, "config_1_value_1"], [:config_2, "config_2_value_2" ] ], # [ [ :config_1, "config_2_value_2"], [:config_2, "config_2_value_1" ] ], # [ [ :config_1, "config_2_value_2"], [:config_2, "config_2_value_2" ] ] ] all_combinations = config_pairs[0].product(*config_pairs[1..-1]) # And finally, using the Hash.[] method, we create an array of hashes and obtain: # [ { :config_1=>"config_1_value_1", :config_2=>"config_2_value_1" }, # { :config_1=>"config_1_value_1", :config_2=>"config_2_value_2" }, # { :config_1=>"config_2_value_2", :config_2=>"config_2_value_1" }, # { :config_1=>"config_2_value_2", :config_2=>"config_2_value_2" } ] all_combination_hashes = all_combinations.map { |pairs| Hash[pairs] } all_combination_hashes.each do |config_hash| with_server do |socket| socket.write(to_query('FLUSHDB')) resp = read_response(socket) assert_equal("+OK\r\n", resp) config_parts = config_hash.flat_map { |key, value| [ key.to_s, value.to_s ] } socket.write(to_query('CONFIG', 'SET', *config_parts)) resp = read_response(socket) assert_equal("+OK\r\n", resp) end yield end end ``` _listing 8.37 the `test_with_config_values` helper in `test_helper.rb`_ You can find all the tests on GitHub, but here is an example of the tests we can now write with the `test_with_config_values` helper: ``` ruby describe 'HVALS' do it 'returns an array of all the values in the hash' do test_with_config_values(hash_max_ziplist_entries: [ '512', '1' ]) do assert_command_results [ [ 'HSET h f1 v1 f2 v2', ':2' ], [ 'HVALS h', unordered([ 'v1', 'v2' ]) ], ] end end end ``` _listing 8.38 Example of a test using `test_with_config_values` for the `HVALS` command_ The implementation of the `HVALS` command is different depending on whether the `RedisHash` instance is using a `List` or `Dict` to store the key/value pairs, so ideally we'd want to test both cases. Given that the test themselves are identical, at the end of the day, we do want to test the same output, but with two different implementation, it would be really repetitive to write the tests twice. This approach allows us to wrap the tests we want to run with the different config values, and the helper will use `FLUSHDB` and `CONFIG SET` to prepare the context before running the tests. ## Conclusion As usual, you can find the [code on GitHub][code-github-link]. In the next chapter we will implement Sets, see you there! [redis-doc-hashes]:https://redis.io/commands#hash [redis-conf-file-hash-max-ziplist-entries]:https://github.com/redis/redis/blob/6.0.0/redis.conf#L1481 [redis-conf-file-hash-max-ziplist-value]:https://github.com/redis/redis/blob/6.0.0/redis.conf#L1482 [chapter-7-appendix-a]:/post/chapter-7-adding-list-commands/#appendix-a-ziplist-deep-dive [chapter-7]:/post/chapter-7-adding-list-commands/ [chapter-6]:/post/chapter-6-building-a-hash-table/ [chapter-5]:/post/chapter-5-redis-protocol-compatibility/ [redis-doc-scan]:http://redis.io/commands/scan [redis-src-dict-scan-doc]:https://github.com/antirez/redis/blob/6.0.0/src/dict.c#L778-L861 [redis-src-string2ll]:https://github.com/redis/redis/blob/6.0.0/src/util.c#L360-L424 [code-github-link]:https://github.com/pjambet/redis-in-ruby/tree/master/code/chapter-8 [ruby-doc-big-decimal-method]:https://ruby-doc.org/stdlib-2.7.1/libdoc/bigdecimal/rdoc/Kernel.html#BigDecimal-method [c-std-strtold]:http://www.cplusplus.com/reference/cstdlib/strtold/ [floating-point-errors]:https://0.30000000000000004.com/ [wikipedia-twos-complement]:https://en.wikipedia.org/wiki/Two%27s_complement [redis-doc-hash-commands]:https://redis.io/commands#hash [redis-doc-scan-command]:http://redis.io/commands/scan [redis-doc-incrby]:http://redis.io/commands/incrby [redis-doc-incrbyfloat]:http://redis.io/commands/incrbyfloat [redis-conf-max-items]:https://github.com/redis/redis/blob/6.0.0/redis.conf#L1481 [redis-conf-max-value]:https://github.com/redis/redis/blob/6.0.0/redis.conf#L1482 [ruby-doc-string-ord]:https://ruby-doc.org/core-2.7.1/String.html#ord-method [wikipedia-long-double]:https://en.wikipedia.org/wiki/Long_double [ruby-doc-float]:https://ruby-doc.org/core-2.7.1/Float.html [ruby-doc-bigdecimal]:https://ruby-doc.org/stdlib-2.7.1/libdoc/bigdecimal/rdoc/BigDecimal.html [wikipedia-e-notation]:https://en.wikipedia.org/wiki/Scientific_notation#E_notation <file_sep>/code/chapter-9/test/set_test.rb # coding: utf-8 require_relative './test_helper' describe 'Set Commands' do describe 'SADD' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SADD', '-ERR wrong number of arguments for \'SADD\' command' ], [ 'SADD s', '-ERR wrong number of arguments for \'SADD\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SADD not-a-set 1 2', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'creates a set if necessary' do assert_command_results [ [ 'SADD s 1', ':1' ], [ 'TYPE s', '+set' ], ] end it 'adds the given int member(s) to an existing set' do assert_command_results [ [ 'SADD s 10', ':1' ], [ 'SADD s 5 1 100', ':3' ], [ 'SADD s 1024 256 5 1 65536', ':3' ], ] end it 'adds the given string member(s) to an existing set' do assert_command_results [ [ 'SADD s m1 m2', ':2' ], [ 'SADD s m5 m3 m2 m1000 m100', ':4' ], [ 'SADD s m1000 m101', ':1' ], ] end it 'handles a mix of strings and int members' do assert_command_results [ [ 'SADD s 20 10 30', ':3' ], [ 'SADD s m1 10 m2', ':2' ], [ 'SADD s m5 m3 m2 m1000 m100', ':4' ], [ 'SADD s m1000 15 m101', ':2' ], ] end end describe 'SCARD' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SCARD', '-ERR wrong number of arguments for \'SCARD\' command' ], [ 'SCARD s a', '-ERR wrong number of arguments for \'SCARD\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SCARD not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns 0 for a non existing set' do assert_command_results [ [ 'SCARD s', ':0' ], ] end it 'returns the cardinality of the set' do assert_command_results [ [ 'SADD s 1 2 3', ':3' ], [ 'SCARD s', ':3' ], [ 'SADD s 20 10 30 a b c', ':6' ], [ 'SCARD s', ':9' ], [ 'SADD s a b 10 20', ':0' ], [ 'SCARD s', ':9' ], ] end end describe 'SDIFF' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SDIFF', '-ERR wrong number of arguments for \'SDIFF\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SDIFF not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], [ 'SADD a-set 1 2', ':2' ], [ 'SDIFF a-set not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an empty array with non existing sets' do assert_command_results [ [ 'SDIFF s', [] ], [ 'SDIFF s1 s2 s3', [] ], ] end it 'returns the entire set with no other arguments' do assert_command_results [ [ 'SADD s 20 10 30', ':3' ], [ 'SDIFF s', [ '10', '20', '30' ] ], ] end it 'returns all the elements from the first set that are not in the other ones (bis)' do assert_command_results [ [ 'SADD s1 2 4 6', ':3' ], [ 'SADD s2 1 2 3 4 5 7 8 9 10 11', ':10' ], [ 'SDIFF s1 s2', unordered([ '6' ]) ], ] end it 'returns all the elements from the first set that are not in the other ones' do assert_command_results [ [ 'SADD s1 a b c d', ':4' ], [ 'SADD s2 c', ':1' ], [ 'SADD s3 a c e', ':3' ], [ 'SDIFF s1 s2 s3', unordered([ 'b', 'd' ]) ], # Algo 1 [ 'SADD s1 e f g h i j k l', ':8' ], [ 'SDIFF s1 s2 s3', unordered([ 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'b', 'd' ]) ], # Algo 2 ] end end describe 'SDIFFSTORE' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SDIFFSTORE', '-ERR wrong number of arguments for \'SDIFFSTORE\' command' ], [ 'SDIFFSTORE dest', '-ERR wrong number of arguments for \'SDIFFSTORE\' command' ], ] end it 'returns an error if one of the inputs is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SADD a-set 1 2 3', ':3' ], [ 'SDIFFSTORE dest not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], [ 'SDIFFSTORE dest non-existing not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], [ 'SDIFFSTORE dest a-set not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'does nothing and return 0 with a non existing set' do assert_command_results [ [ 'SDIFFSTORE dest s', ':0' ], [ 'TYPE dest', '+none' ], ] end it 'returns 0 and delete dest if the result is empty' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SADD s 1 2 3', ':3' ], [ 'SDIFFSTORE not-a-set s s', ':0' ], [ 'TYPE not-a-set', '+none' ], ] end it 'stores the same set in dest with a single set argument' do assert_command_results [ [ 'SADD s1 20 10 30', ':3' ], [ 'SDIFFSTORE dest s1', ':3' ], [ 'SCARD dest', ':3' ], [ 'SMEMBERS dest', [ '10', '20', '30' ] ], [ 'SADD s2 20 b c a 10', ':5' ], [ 'SDIFFSTORE dest s2', ':5' ], [ 'SCARD dest', ':5' ], [ 'SMEMBERS dest', unordered([ '20', '10', 'b', 'c', 'a' ]) ], ] end it 'stores the diff in dest' do assert_command_results [ [ 'SADD s1 20 10 30', ':3' ], [ 'SADD s2 40 30 50', ':3' ], [ 'SDIFFSTORE dest s1 s2', ':2' ], [ 'SMEMBERS dest', [ '10', '20' ] ], [ 'SADD s1 b c a', ':3' ], [ 'SADD s3 b a d', ':3' ], [ 'SDIFFSTORE dest s1 s2 s3', ':3' ], [ 'SMEMBERS dest', unordered([ '10', '20', 'c' ]) ], ] end it 'can use one of the input sets as the dest, and overwrites it' do assert_command_results [ [ 'SADD s1 20 10 30', ':3' ], [ 'SADD s2 10 30 40', ':3' ], [ 'SDIFFSTORE s1 s1 s2', ':1' ], [ 'SMEMBERS s1', [ '20' ] ], ] end it 'overwrites destination if it already exists' do assert_command_results [ [ 'SET dest a', '+OK' ], [ 'SADD s1 20 10 30', ':3' ], [ 'SDIFFSTORE dest s1', ':3' ], [ 'SMEMBERS dest', unordered([ '10', '20', '30' ]) ], ] end end describe 'SINTER' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SINTER', '-ERR wrong number of arguments for \'SINTER\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SINTER not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an empty array if one the keys does not exist' do assert_command_results [ [ 'SINTER s', BYORedis::EMPTY_ARRAY ], ] end it 'returns the set itself if not other sets are given' do assert_command_results [ [ 'SADD s 1 2 3', ':3' ], [ 'SINTER s', [ '1', '2', '3' ] ], [ 'SADD s b a', ':2' ], [ 'SINTER s', unordered([ 'a', 'b', '1', '2', '3' ]) ], ] end it 'returns the intersection of all the sets' do assert_command_results [ [ 'SADD s1 1 2 3 4', ':4' ], [ 'SADD s2 3', ':1' ], [ 'SADD s3 1 3 5', ':3' ], [ 'SINTER s1 s2 s3', unordered([ '3' ]) ], [ 'DEL s1 s2 s3', ':3' ], [ 'SADD s1 a b c d', ':4' ], [ 'SADD s2 c', ':1' ], [ 'SADD s3 a c e', ':3' ], [ 'SINTER s1 s2 s3', unordered([ 'c' ]) ], ] end end describe 'SINTERSTORE' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SINTERSTORE', '-ERR wrong number of arguments for \'SINTERSTORE\' command' ], [ 'SINTERSTORE dest', '-ERR wrong number of arguments for \'SINTERSTORE\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SINTERSTORE dest not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns 0 and delete dest if one the keys does not exist' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SINTERSTORE not-a-set s', ':0' ], [ 'TYPE not-a-set', '+none' ], ] end it 'store the the set itself in dest if no other sets are given' do assert_command_results [ [ 'SADD s 1 2 3', ':3' ], [ 'SINTERSTORE dest s', ':3' ], [ 'SMEMBERS dest', unordered([ '1', '2', '3' ]) ], [ 'SADD s b a', ':2' ], [ 'SINTERSTORE dest s', ':5' ], [ 'SMEMBERS dest', unordered([ '1', '2', '3', 'a', 'b' ]) ], ] end it 'can use one of the input sets as the dest, and overwrites it' do assert_command_results [ [ 'SADD s1 20 10 30', ':3' ], [ 'SADD s2 10 30 40', ':3' ], [ 'SINTERSTORE s1 s1 s2', ':2' ], [ 'SMEMBERS s1', unordered([ '10', '30' ]) ], ] end it 'stores the intersection of all the sets in dest' do assert_command_results [ [ 'SADD s1 1 2 3 4', ':4' ], [ 'SADD s2 3', ':1' ], [ 'SADD s3 1 3 5', ':3' ], [ 'SINTERSTORE dest s1 s2 s3', ':1' ], [ 'SMEMBERS dest', [ '3' ] ], [ 'DEL s1 s2 s3', ':3' ], [ 'SADD s1 a b c d', ':4' ], [ 'SADD s2 c', ':1' ], [ 'SADD s3 a c e', ':3' ], [ 'SINTERSTORE dest s1 s2 s3', ':1' ], [ 'SMEMBERS dest', [ 'c' ] ], ] end end describe 'SISMEMBER' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SISMEMBER', '-ERR wrong number of arguments for \'SISMEMBER\' command' ], [ 'SISMEMBER s', '-ERR wrong number of arguments for \'SISMEMBER\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SISMEMBER not-a-set f', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns 0 if the element is not a member of the set, 1 otherwise' do assert_command_results [ [ 'SADD s 20 10 30', ':3' ], [ 'SISMEMBER s a', ':0' ], [ 'SISMEMBER s 20', ':1' ], [ 'SISMEMBER s 21', ':0' ], [ 'SADD s a d c', ':3' ], [ 'SISMEMBER s a', ':1' ], [ 'SISMEMBER s e', ':0' ], ] end it 'returns 0 if the set does not exist' do assert_command_results [ [ 'SISMEMBER s a', ':0' ], [ 'SISMEMBER s 1', ':0' ], ] end end describe 'SMISMEMBER' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SMISMEMBER', '-ERR wrong number of arguments for \'SMISMEMBER\' command' ], [ 'SMISMEMBER s', '-ERR wrong number of arguments for \'SMISMEMBER\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SMISMEMBER not-a-set f', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an array of 0s and 1s depending on whether the members are in the set or not' do assert_command_results [ [ 'SADD s 20 10 30', ':3' ], [ 'SMISMEMBER s a', [ 0 ] ], [ 'SMISMEMBER s 20 a 21', [ 1, 0, 0 ] ], [ 'SADD s a d c', ':3' ], [ 'SMISMEMBER s a', [ 1 ] ], [ 'SMISMEMBER s d e f', [ 1, 0, 0 ] ], ] end it 'returns an array of 0s if the set does not exist' do assert_command_results [ [ 'SMISMEMBER s a b c', [ 0, 0, 0 ] ], [ 'SMISMEMBER s 1 2 3', [ 0, 0, 0 ] ], ] end end describe 'SMEMBERS' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SMEMBERS', '-ERR wrong number of arguments for \'SMEMBERS\' command' ], [ 'SMEMBERS a b', '-ERR wrong number of arguments for \'SMEMBERS\' command' ], ] end it 'returns an error if one of the inputs is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SMEMBERS not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns all the elements in the set' do assert_command_results [ [ 'SADD s 20 10 30', ':3' ], [ 'SMEMBERS s', [ '10', '20', '30' ] ], [ 'SADD s b c d a', ':4' ], [ 'SMEMBERS s', unordered([ '10', '20', '30', 'a', 'b', 'c', 'd' ]) ], ] end end describe 'SMOVE' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SMOVE', '-ERR wrong number of arguments for \'SMOVE\' command' ], [ 'SMOVE src', '-ERR wrong number of arguments for \'SMOVE\' command' ], [ 'SMOVE src dest', '-ERR wrong number of arguments for \'SMOVE\' command' ], [ 'SMOVE src dest member a', '-ERR wrong number of arguments for \'SMOVE\' command' ], ] end it 'returns an error if the source is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SMOVE not-a-set dest a', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an error if the destination is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SMOVE src not-a-set a', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns 0 if src is empty' do assert_command_results [ [ 'SMOVE src dest a', ':0' ], ] end it 'deletes the first set if it is empty after the move' do assert_command_results [ [ 'SADD s1 1', ':1' ], [ 'SMOVE s1 s2 1', ':1' ], [ 'TYPE s1', '+none' ], ] end it 'returns 1 if the member was moved' do assert_command_results [ [ 'SADD s 1 2 3', ':3' ], [ 'SMOVE s dest 4', ':0' ], [ 'SMOVE s dest 2', ':1' ], [ 'SMEMBERS s', unordered([ '1', '3' ]) ], [ 'SMEMBERS dest', unordered([ '2' ]) ], [ 'SADD s 2', ':1' ], [ 'SMOVE s dest 2', ':1' ], # Still returns 1 even if it already exists in dest [ 'SMEMBERS s', unordered([ '1', '3' ]) ], [ 'SMEMBERS dest', unordered([ '2' ]) ], [ 'DEL s dest', ':2' ], [ 'SADD s a b c', ':3' ], [ 'SMOVE s dest e', ':0' ], [ 'SMOVE s dest b', ':1' ], [ 'SMEMBERS s', unordered([ 'a', 'c' ]) ], [ 'SMEMBERS dest', unordered([ 'b' ]) ], [ 'SADD s b', ':1' ], [ 'SMOVE s dest b', ':1' ], # Still returns 1 even if it already exists in dest [ 'SMEMBERS s', unordered([ 'a', 'c' ]) ], [ 'SMEMBERS dest', unordered([ 'b' ]) ], ] end end describe 'SPOP' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SPOP', '-ERR wrong number of arguments for \'SPOP\' command' ], [ 'SPOP a 1 a', '-ERR syntax error' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SPOP not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an error if count is not an integer' do assert_command_results [ [ 'SPOP s a', '-ERR value is not an integer or out of range' ], ] end it 'returns an error if count is negative' do assert_command_results [ [ 'SPOP s -1', '-ERR index out of range' ], ] end it 'removes an element from the set and returns it' do assert_command_results [ [ 'SADD s 20 10 30', ':3' ], [ 'SPOP s', one_of([ '10', '20', '30' ]) ], [ 'SADD s b a c', ':3' ], [ 'SPOP s', one_of([ '10', '20', '30', 'a', 'b', 'c' ]) ], [ 'SCARD s', ':4' ], ] end def tests_for_spop(socket, set_members, count) socket.write(to_query(*[ 'SADD', 's' ] + set_members)) response = read_response(socket) assert_equal(":#{ set_members.size }\r\n", response) socket.write(to_query('SPOP', 's', count.to_s)) response = read_response(socket) response_parts = response.split("\r\n") length = response_parts.shift assert_equal("*#{ count }", length) response_parts = response_parts.each_slice(2).to_a.sort assert_equal(response_parts.uniq, response_parts) # No duplicates response_parts.each do |part| # part[0] is the length of the RESP string such as $1, part[1] is the string assert(set_members.include?(part[1])) end end it 'returns up to count elements with the count argument' do with_server do |socket| tests_for_spop(socket, [ '1', '2', '3', '4' ], 2) # Case 2 for an intset socket.write(to_query('DEL', 's')) read_response(socket) tests_for_spop(socket, [ 'a', 'b', 'c', 'd' ], 2) # Case 2 for a hash table socket.write(to_query('DEL', 's')) read_response(socket) tests_for_spop(socket, [ '1', '2', '3', '4', '5', '6' ], 5) # Case 3 for an intset socket.write(to_query('DEL', 's')) read_response(socket) tests_for_spop(socket, [ 'a', 'b', 'c', 'd', 'e', 'f' ], 5) # Case 3 for a hash table end end it 'returns the whole set if count is equal to or greater than the cardinality' do assert_command_results [ [ 'SADD s 1 2 3 4', ':4' ], [ 'SPOP s 5', unordered([ '1', '2', '3', '4' ]) ], [ 'TYPE s', '+none' ], [ 'SADD s a b c d', ':4' ], [ 'SPOP s 5', unordered([ 'a', 'b', 'c', 'd' ]) ], [ 'TYPE s', '+none' ], ] end it 'returns a nil string for a non existing set' do assert_command_results [ [ 'SPOP s', BYORedis::NULL_BULK_STRING ], ] end it 'returns an empty array for a non existing set with a count argument' do assert_command_results [ [ 'SPOP s 1', BYORedis::EMPTY_ARRAY ], ] end it 'returns an empty array for an existing set with a 0 count' do assert_command_results [ [ 'SADD s a', ':1' ], [ 'SPOP s 0', BYORedis::EMPTY_ARRAY ], ] end it 'deletes the set if it popped the last member' do assert_command_results [ [ 'SADD s 1', ':1' ], [ 'SPOP s', '1' ], [ 'TYPE s', '+none' ], ] end end describe 'SRANDMEMBER' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SRANDMEMBER', '-ERR wrong number of arguments for \'SRANDMEMBER\' command' ], [ 'SRANDMEMBER a 1 a', '-ERR syntax error' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SRANDMEMBER not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an error if count is not an integer' do assert_command_results [ [ 'SRANDMEMBER s a', '-ERR value is not an integer or out of range' ], ] end it 'returns an empty array with a negative count for a non existing set' do assert_command_results [ [ 'SRANDMEMBER s -10', BYORedis::EMPTY_ARRAY ], ] end it 'returns up to count elements, allowing duplicates if count is negative' do with_server do |socket| socket.write(to_query('SADD', 's', '1', '2', '3')) response = read_response(socket) assert_equal(":3\r\n", response) # With less than the total of elements, and only ints socket.write(to_query('SRANDMEMBER', 's', '-2')) response = read_response(socket) parts = response.split("\r\n") length = parts.shift assert_equal('*2', length) assert_equal(4, parts.length) parts.each_slice(2) do |part| assert_includes([ [ '$1', '1' ], [ '$1', '2' ], [ '$1', '3' ] ], part) end # With more than the total of elements, and only ints socket.write(to_query('SRANDMEMBER', 's', '-10')) response = read_response(socket) parts = response.split("\r\n") length = parts.shift assert_equal('*10', length) assert_equal(20, parts.length) parts.each_slice(2) do |part| assert_includes([ [ '$1', '1' ], [ '$1', '2' ], [ '$1', '3' ] ], part) end socket.write(to_query('SADD', 's', 'b', 'c', 'a')) response = read_response(socket) assert_equal(":3\r\n", response) # With less than the total of elements and a mix of ints and strings socket.write(to_query('SRANDMEMBER', 's', '-2')) response = read_response(socket) parts = response.split("\r\n") length = parts.shift assert_equal('*2', length) assert_equal(4, parts.length) parts.each_slice(2) do |part| assert_includes([ [ '$1', '1' ], [ '$1', '2' ], [ '$1', '3' ], [ '$1', 'a' ], [ '$1', 'b' ], [ '$1', 'c' ] ], part) end # With more than the total of elements and a mix of ints and strings socket.write(to_query('SRANDMEMBER', 's', '-20')) response = read_response(socket) parts = response.split("\r\n") length = parts.shift assert_equal('*20', length) assert_equal(40, parts.length) parts.each_slice(2) do |part| assert_includes([ [ '$1', '1' ], [ '$1', '2' ], [ '$1', '3' ], [ '$1', 'a' ], [ '$1', 'b' ], [ '$1', 'c' ] ], part) end end end it 'returns an element from the set but does not remove it' do assert_command_results [ [ 'SADD s 20 10 30', ':3' ], [ 'SRANDMEMBER s', one_of([ '10', '20', '30' ]) ], [ 'SMEMBERS s', unordered([ '10', '20', '30']) ], [ 'SADD s b a c', ':3' ], [ 'SRANDMEMBER s', one_of([ '10', '20', '30', 'a', 'b', 'c' ]) ], [ 'SMEMBERS s', unordered([ '10', '20', '30', 'a', 'b', 'c' ]) ], [ 'SCARD s', ':6' ], ] end it 'returns the whole set if count is positive and greater than the set\'s cardinality' do assert_command_results [ [ 'SADD s 20 10 30', ':3' ], [ 'SRANDMEMBER s 3', unordered([ '10', '20', '30' ]) ], [ 'SRANDMEMBER s 4', unordered([ '10', '20', '30' ]) ], [ 'SADD s b c a', ':3' ], [ 'SRANDMEMBER s 6', unordered([ '10', '20', '30', 'a', 'b', 'c' ]) ], [ 'SRANDMEMBER s 7', unordered([ '10', '20', '30', 'a', 'b', 'c' ]) ], ] end it 'returns up to count elements with the count argument' do with_server do |socket| socket.write(to_query('SADD', 's', '1', '2', '3', '4', '5', '6', '7', '8', '9')) response = read_response(socket) assert_equal(":9\r\n", response) socket.write(to_query('SRANDMEMBER', 's', '1')) response = read_response(socket) parts = response.split("\r\n") length = parts.shift assert_equal('*1', length) assert_equal(2, parts.length) parts.each_slice(2) do |part| assert_includes([ [ '$1', '1' ], [ '$1', '2' ], [ '$1', '3' ], [ '$1', '4' ], [ '$1', '5' ], [ '$1', '6' ], [ '$1', '7' ], [ '$1', '8' ], [ '$1', '9' ] ], part) end socket.write(to_query('SRANDMEMBER', 's', '2')) response = read_response(socket) parts = response.split("\r\n") length = parts.shift assert_equal('*2', length) assert_equal(4, parts.length) parts.each_slice(2) do |part| assert_includes([ [ '$1', '1' ], [ '$1', '2' ], [ '$1', '3' ], [ '$1', '4' ], [ '$1', '5' ], [ '$1', '6' ], [ '$1', '7' ], [ '$1', '8' ], [ '$1', '9' ] ], part) end socket.write(to_query('SADD', 's', 'b', 'c', 'a')) response = read_response(socket) assert_equal(":3\r\n", response) socket.write(to_query('SRANDMEMBER', 's', '2')) response = read_response(socket) parts = response.split("\r\n") length = parts.shift assert_equal('*2', length) assert_equal(4, parts.length) parts.each_slice(2) do |part| assert_includes([ [ '$1', '1' ], [ '$1', '2' ], [ '$1', '3' ], [ '$1', '4' ], [ '$1', '5' ], [ '$1', '6' ], [ '$1', '7' ], [ '$1', '8' ], [ '$1', '9' ], [ '$1', 'a' ], [ '$1', 'b' ], [ '$1', 'c' ] ], part) end socket.write( to_query(*(300.times.map { |i| (i + 100).to_s }.prepend('SADD', 's'))) ) response = read_response(socket) assert_equal(":300\r\n", response) socket.write(to_query('SRANDMEMBER', 's', '311')) response = read_response(socket) assert(!response.nil?, 'Expected to have received a response before timeout for SRANDMEMBER') parts = response.split("\r\n") length = parts.shift assert_equal('*311', length) assert_equal(622, parts.length) end end it 'returns a nil string for a non existing set' do assert_command_results [ [ 'SRANDMEMBER s', BYORedis::NULL_BULK_STRING ], ] end it 'returns an empty array for a non existing set with a count argument' do assert_command_results [ [ 'SRANDMEMBER s 1', BYORedis::EMPTY_ARRAY ], ] end it 'returns an empty array for an existing set with a 0 count' do assert_command_results [ [ 'SADD s a', ':1' ], [ 'SRANDMEMBER s 0', BYORedis::EMPTY_ARRAY ], ] end end describe 'SREM' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SREM', '-ERR wrong number of arguments for \'SREM\' command' ], [ 'SREM s', '-ERR wrong number of arguments for \'SREM\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SREM not-a-set s1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns the number of removed elements' do assert_command_results [ [ 'SADD s 1 2 3', ':3' ], [ 'SREM s 3 2 4 5', ':2' ], [ 'SREM s a', ':0' ], [ 'SMEMBERS s', unordered([ '1' ]) ], [ 'SADD s b c a', ':3' ], [ 'SREM s d a b', ':2' ], [ 'SMEMBERS s', unordered([ '1', 'c' ]) ], ] end it 'returns 0 if the set does not exist' do assert_command_results [ [ 'SREM s a', ':0' ], ] end it 'deletes the set if SREM removes the last member' do assert_command_results [ [ 'SADD s 1 2 3', ':3' ], [ 'SREM s 1', ':1' ], [ 'SREM s 2', ':1' ], [ 'SREM s 3', ':1' ], [ 'TYPE s', '+none' ], ] end end describe 'SUNION' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SUNION', '-ERR wrong number of arguments for \'SUNION\' command' ], ] end it 'returns an error if one of the inputs is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SADD a-set 1 2 3', ':3' ], [ 'SUNION not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], [ 'SUNION non-existing not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], [ 'SUNION a-set not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an empty array for a non existing set' do assert_command_results [ [ 'SUNION s', [] ], ] end it 'returns the union of all the given sets' do assert_command_results [ [ 'SADD s1 1 2 3', ':3' ], [ 'SADD s2 3 4 5', ':3' ], [ 'SUNION s1 s2', unordered([ '1', '2', '3', '4', '5' ]) ], [ 'SADD s1 a b c', ':3' ], [ 'SADD s2 c d e', ':3' ], [ 'SUNION s1 s2', unordered([ '1', '2', '3', '4', '5', 'a', 'b', 'c', 'd', 'e' ]) ], ] end end describe 'SUNIONSTORE' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SUNIONSTORE', '-ERR wrong number of arguments for \'SUNIONSTORE\' command' ], [ 'SUNIONSTORE dest', '-ERR wrong number of arguments for \'SUNIONSTORE\' command' ], ] end it 'returns an error if one of the inputs is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'SADD a-set 1 2 3', ':3' ], [ 'SUNIONSTORE dest not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], [ 'SUNIONSTORE dest non-existing not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], [ 'SUNIONSTORE dest a-set not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns 0 for a non existing set' do assert_command_results [ [ 'SUNIONSTORE dest s', ':0' ], [ 'TYPE dest', '+none' ], ] end it 'returns the size of the new set and store the union of all the given sets' do assert_command_results [ [ 'SADD s1 1 2 3', ':3' ], [ 'SADD s2 3 4 5', ':3' ], [ 'SUNIONSTORE dest s1 s2', ':5' ], [ 'SMEMBERS dest', unordered([ '1', '2', '3', '4', '5' ]) ], [ 'SADD s1 a b c', ':3' ], [ 'SADD s2 c d e', ':3' ], [ 'SUNIONSTORE dest s1 s2', ':10' ], [ 'SMEMBERS dest', unordered([ '1', '2', '3', '4', '5', 'a', 'b', 'c', 'd', 'e' ]) ], ] end it 'stores the same set in dest with a single set argument' do assert_command_results [ [ 'SADD s1 20 10 30', ':3' ], [ 'SUNIONSTORE dest s1', ':3' ], [ 'SCARD dest', ':3' ], [ 'SMEMBERS dest', [ '10', '20', '30' ] ], [ 'SADD s2 20 b c a 10', ':5' ], [ 'SUNIONSTORE dest s2', ':5' ], [ 'SCARD dest', ':5' ], [ 'SMEMBERS dest', unordered([ '20', '10', 'b', 'c', 'a' ]) ], ] end it 'can use one of the input sets as the dest, and overwrites it' do assert_command_results [ [ 'SADD s1 20 10 30', ':3' ], [ 'SADD s2 10 30 40', ':3' ], [ 'SUNIONSTORE s1 s1 s2', ':4' ], [ 'SMEMBERS s1', unordered([ '10', '20', '30', '40' ]) ], ] end it 'overwrites destination if it already exists' do assert_command_results [ [ 'SET dest a', '+OK' ], [ 'SADD s1 20 10 30', ':3' ], [ 'SUNIONSTORE dest s1', ':3' ], [ 'SMEMBERS dest', unordered([ '10', '20', '30' ]) ], ] end end end <file_sep>/code/chapter-7/utils.rb module BYORedis InvalidArgsLength = Class.new(StandardError) do def resp_error(command_name) RESPError.new("ERR wrong number of arguments for '#{ command_name }' command") end end WrongTypeError = Class.new(StandardError) do def resp_error RESPError.new('WRONGTYPE Operation against a key holding the wrong kind of value') end end RESPSyntaxError = Class.new(StandardError) do def resp_error RESPError.new('ERR syntax error') end end module Utils def self.assert_args_length(args_length, args) if args.length != args_length raise InvalidArgsLength, "Expected #{ args_length }, got #{ args.length }: #{ args }" end end def self.assert_args_length_greater_than(args_length, args) if args.length <= args_length raise InvalidArgsLength, "Expected more than #{ args_length } args, got #{ args.length }: #{ args }" end end def self.safe_write(socket, message) socket.write(message) rescue Errno::ECONNRESET, Errno::EPIPE, IOError false end end end <file_sep>/content/post/chapter-5-redis-protocol-compatibility.md --- title: "Chapter 5 - Redis Protocol Compatibility" date: 2020-08-14T10:53:06-04:00 lastmod: 2020-08-17T13:28:40-04:00 draft: false comment: false keywords: [] summary: "In this chapter we will focus on making RedisServer speak the Redis Protocol, RESP. Doing so will allow us to use Redis' built-in client, redis-cli to communicate with our own server." --- ## What we'll cover By the end of this chapter `RedisServer` will speak [the Redis Protocol, `RESP v2`][resp-spec]. Doing this will allow any clients that was written to communicate with the real Redis to also communicate with our own server, granted that the commands it uses are within the small subset of the ones we implemented. One such client is the `redis-cli` utility that ships with Redis, it'll look like this: ![redis-cli-gif](/img/redis.gif) [RESP v2][resp-spec] has been the protocol used by Redis since version 2.0, to quote the documentation: > 1.2 already supported it, but Redis 2.0 was the first version to talk only this protocol) As of version 6.0, RESP v2 is still the default protocol and is what we'll implement in this chapter. ## RESP3 RESP v2 is the default version, but not the latest one. RESP3 has been released in 2018, it improves many different aspects of RESP v2, such as adding new types for maps — often called dictionary — and a lot more. The spec is [on GitHub][resp3-spec] and explains in details [the background behind it][resp3-spec-background]. RESP3 is supported as of Redis 6.0, as indicated in [the release notes][release-notes-6-0]: > Redis now supports a new protocol called RESP3, which returns more semantical replies: new clients using this protocol can understand just from the reply what type to return to the calling program. The [`HELLO`][redis-doc-hello] command can be used to switch the connection to a different protocol version. As we can see below, only two versions are currently supported, 2 & 3. We can also see the new map type in action, `hello 2` returned an array with 14 items, representing 7 key/value pairs, whereas `hello 3` leveraged the new map type to return a map with 7 key/value pairs. ``` bash 127.0.0.1:6379> hello 2 1) "server" 2) "redis" 3) "version" 4) "6.0.6" 5) "proto" 6) (integer) 2 7) "id" 8) (integer) 6 9) "mode" 10) "standalone" 11) "role" 12) "master" 13) "modules" 14) (empty array) ``` ``` bash 127.0.0.1:6379> hello 3 1# "server" => "redis" 2# "version" => "6.0.6" 3# "proto" => (integer) 3 4# "id" => (integer) 6 5# "mode" => "standalone" 6# "role" => "master" 7# "modules" => (empty array) ``` ``` bash 127.0.0.1:6379> hello 1 (error) NOPROTO unsupported protocol version ``` ``` bash 127.0.0.1:6379> hello 4 (error) NOPROTO unsupported protocol version ``` Support for the `HELLO` command and RESP3 might be added in a later chapter but it's not currently on the roadmap of this online book. ## Back to RESP v2 The [official specification][resp-spec] goes into details about the protocol and is still reasonably short and approachable, so feel free to read it, but here are the main elements that will drive the changes to our server. ### The 5 data types RESP v2 defines five data types: - Simple Strings - Errors - Integers - Bulk Strings - Arrays The type of a serialized RESP data is determined by the first byte: - Simple Strings start with `+` - Errors start with `-` - Integers start with `:` - Bulk Strings start with `$` - Arrays start with `*` The data that follows the type byte depends on each type, let's look at each of them one by one. **Simple Strings** A Simple String cannot contain a new line. One of its main use cases is to return `OK` back to the client. The full format of a Simple String is "A `+` character, followed directly by the content of the string, followed by a carriage return (often written as `CR` or `\r`) and a line feed (often written as `LF` or `\n`). This is why Simple Strings cannot contain multiples lines, a newline would create confusion given that it is also use a delimiter. The `"OK"` string, here shown in its JSON form, returned by the `SET` command upon success is therefore serialized as `+OK\r\n`. `redis-cli` does the work of detecting the type of the response and only shows us the actual string, `OK`, as we can see in the example below: ``` bash 127.0.0.1:6379> SET 1 2 OK ``` Using `nc`, we can see what the full response sent back from Redis is: ``` bash > nc -v localhost 6379 SET 1 2 +OK ``` `nc` does not explicitly display invisible characters such as `CR` & `LF`, so it is hard to know for sure that they were returned, beside the newline printed after `+OK`. The `hexdump` command is useful here, it allows us to see all the bytes: ``` bash echo "SET 1 2" | nc localhost 6379 | hexdump -C # ... 00000000 2b 4f 4b 0d 0a |+OK..| 00000005 ``` The interesting part is the middle one, `2b 4f 4b 0d 0a`, these are the 5 bytes returned by Redis. The part to the right, between pipe characters (`|`) is their ASCII representation. We can see five characters there, `+` is the ASCII representation of `2b`, `O` is for `4f`, `K` is for `4d`, and the last two bytes do not have a visual representation so they're displayed as `.`. `2b` is the hex notation of 43 (`'2b'.to_i(16)` in `irb`), and 43 maps to `+` in the [ASCII table][ascii-table]. `4f` is the equivalent of 79, and the capital letter `O`, `4b`, the number 75 and the capital letter `K`. `0d` is the equivalent of the number 13, and the carriage return character (CR), and finally, `0a` is 10, the line feed character (LF). Redis follows the Redis Protocol, that's a good start! **Errors** Errors are very similar to Simple Strings, they also cannot contain new line characters. The main difference is that clients should treat them as errors instead of successful results. In languages with exceptions, a client library might decide to throw an exception when receiving an error from Redis. This is what [the official ruby library][redis-ruby-client] does. Similarly to Simple Strings, errors end with a carriage return and a line feed, let's see it in action: ``` bash > echo "GET 1 2" | nc localhost 6379 | hexdump -C 00000000 2d 45 52 52 20 77 72 6f 6e 67 20 6e 75 6d 62 65 |-ERR wrong numbe| 00000010 72 20 6f 66 20 61 72 67 75 6d 65 6e 74 73 20 66 |r of arguments f| 00000020 6f 72 20 27 67 65 74 27 20 63 6f 6d 6d 61 6e 64 |or 'get' command| 00000030 0d 0a |..| 00000032 ``` There are more bytes here, they represent the string: `"Err wrong number of arguments for 'get' command"`, but we can see that the response starts with the `2d` byte. Looking at the [ASCII table][ascii-table], we can see that 45, the numeric equivalent of `2d`, maps to `-`, so far so good. And finally, the response ends with `0d0a`, respectively `CR` & `LF`. **Integers** Integers have a similar representation to Simple Strings and errors. The actual integer comes after the `:` character and is followed by the `CR` & `LF` characters. An example of integer reply is with the `TTL` and `PTTL` commands The key `key-with-ttl` was set with the command: `SET key-with-ttl value EX 1000`. ``` bash > echo "TTL key-with-ttl" | nc localhost 6379 | hexdump -C # ... 00000000 3a 39 38 38 0d 0a |:988..| 00000006 ``` The key `not-a-key` does not exist. ``` bash > echo "TTL not-a-key" | nc localhost 6379 | hexdump -C # ... 00000000 3a 2d 32 0d 0a |:-2..| 00000005 ``` The key `key-without-ttl` was set with the command: `SET key-without-ttl value`. ``` bash > echo "TTL key-without-ttl" | nc localhost 6379 | hexdump -C # ... 00000000 3a 2d 31 0d 0a |:-1..| 00000005 ``` All of these responses start with the `3a` byte, which is equivalent to 58, aka `:`. In the two cases where the response is a negative value, `-2` for a non existent key and `-1` for an existing key without a ttl, the next byte is `2d`, equivalent to 45, aka `-`. The rest of the data, before the `0d` & `0a` bytes, is the actual integer data, in ASCII format, `31` is the hex equivalent to 49, which is the character `1`, 32 is the hex equivalent to 50, which is the character `2`. `39` & `38` are respectively the hex equivalent to 57 & 56, the characters `9` & `8`. A ruby client parsing this data would extract the string between `:` and `\r\n` and call `to_i` on it: `'988'.to_i == 988`. **Bulk Strings** In order to work for any strings, Bulk Strings need to first declare their length, and only then the actual data. This lets the receiver know how many bytes to expect, instead of reading anything until it finds `CRLF`, the way it does for a Simple String. The length of the string is sent directly after the dollar sign, and is delimited by `CRLF`, the following is the actual string data, and another `CRLF` to end the string. The RESP Bulk String representation of the JSON string `"GET"` is: `$3\r\nGET\r\n`. Interestingly, it seems like Redis does not care that much about the final `CRLF`, as long as it finds two characters there, it assumes it's the end of the Bulk String and tries to process what comes after. In the following example, we first send the command `GET a` to Redis over port 6379, as a an array of Bulk Strings, followed by the non existent command `NOT A COMMAND`. The response first contains the `-1` integer, followed by the error. ```ruby irb(main):001:0> require 'socket' => true irb(main):002:0> socket = TCPSocket.new 'localhost', 6379 irb(main):004:0> socket.write("*2\r\n$3\r\nGET\r\n$1\r\na\r\n*1\r\n$13\r\nNOT A COMMAND\r\n") => 35 irb(main):005:0> socket.read_nonblock(1024, exception: false) => "$-1\r\n-ERR unknown command `NOT`, with args beginning with: `A`, `COMMAND`, \r\n" ``` The following is handled identically by Redis, despite the fact the `a` Bulk String is not terminated by `CRLF`. We can see that Redis ignored the `b` and `c` characters and proceeded with the following command, the non existent `NOT A COMMAND`. I am assuming that the code in charge of reading client input first reads the length, then grabs that many bytes and jumps by two characters, regardless of what these characters are. ```ruby irb(main):027:0> socket.write("*2\r\n$3\r\nGET\r\n$1\r\nabc*1\r\n$13\r\nNOT A COMMAND\r\n") => 35 irb(main):030:0> socket.read_nonblock(1024, exception: false) => "$-1\r\n-ERR unknown command `NOT`, with args beginning with: `A`, `COMMAND`, \r\n" ``` There's a special value for Bulk Strings, the null Bulk String. It is commonly returned when a Bulk String would otherwise be expected, but there was no value to return. This happens in many cases, such as when there are no values for the key passed to the `GET` command. RESP represents it as a string with a length of -1: `$-1\r\n`. **Arrays** Arrays can contain values of any types, including other nested arrays. Similarly to Bulk Strings, arrays must first declare their lengths, followed by `CRLF`, and all items come afterwards, in their regular serialized form. The following is a JSON representation of an arbitrary array: ``` json [ 1, "a-string", [ "another-string-in-a-nested-array" ], "a-string-with\r\n-newlines" ] ``` The following is the RESP representation of the same array: ``` *4\r\n:1\r\n$8\r\na-string\r\n*1\r\n$32\r\nanother-string-in-a-nested-array\r\n$24\r\na-string-with\r\n-newlines\r\n ``` We can include newlines and indentation for the sake of readability ``` *4\r\n :1\r\n $8\r\na-string\r\n *1\r\n $32\r\nanother-string-in-a-nested-array\r\n $24\r\na-string-with\r\n-newlines\r\n ``` RESP has a special notation for the NULL array: `*-1\r\n`. The existence of two different NULL values, one for Bulk Strings and one for Bulk Arrays is confusing and is one of the many changes in RESP3. RESP3 has a single null value. ### Requests & Responses As we saw in a previous example, requests are sent as arrays of Bulk Strings. The command `GET a-key` should be sent as `*2\r\n$3\r\nGET\r\n$5\r\na-key\r\n`, or in plain English: "An array of length 2, where the first string is of length 3 and is GET and the second string is of length 5 and is a-key". We can illustrate this by sending this string with the `TCPSocket` class in ruby: ```ruby irb(main):001:0> require 'socket' => true irb(main):002:0> socket = TCPSocket.new 'localhost', 6379 irb(main):003:0> socket.write "*2\r\n$3\r\nGET\r\n$5\r\na-key\r\n" => 24 irb(main):004:0> socket.read_nonblock 1024 => "$-1\r\n" ``` ### Inline Protocol RESP's main mode of operation is following a request/response model described above. It also supports a simpler alternative, called "Inline Commands", which is useful for manual tests or interactions with a server. This is similar to how we've used `nc` in this book so far. Anything that does not start with a `*` character — which is the first character of an array, the format Redis expects for a command — is treated as an inline command. Redis will read everything until a newline is detected and attempts to parse that as a command. This is essentially what we've been doing so far when implementing the `RedisServer` class. Let's try this quickly with `nc`: ``` bash > nc localhost 6379 # ... SET 1 2 +OK GET 1 $1 2 ``` The reason RESP's main mode of operations is more complicated is because inline commands are severely limited. It is impossible to store a key or a value that contains the carriage return and line feed characters since they're use as delimiters even though Redis does support any strings as keys and values as seen in the following example: ``` bash > redis-cli 127.0.0.1:6379> SET a-key "foo\nbar" OK 127.0.0.1:6379> GET a-key "foo\nbar" ``` Let's double check with `nc` to see what Redis stored: ``` bash > nc localhost 6379 # ... GET a-key $7 foo bar ``` We could also use `hexdump` to triple check: ``` bash > echo "GET a-key" | nc localhost 6379 | hexdump -C # ... 00000000 24 37 0d 0a 66 6f 6f 0a 62 61 72 0d 0a |$7..foo.bar..| 0000000d ``` We can see the `0a` byte between `o`/`6f` & `b`/`62`. Without inline commands sending test commands would be excruciating: ``` bash > nc -c localhost 6379 *2 $3 GET $1 a $1 1 ``` Note that we're using the `-c` flags, which tells `nc` to send `CRLF` characters when we type the return key, instead of the default of `LF`. As we've seen above, for RESP arrays, RESP expects `CRLF` delimiters. ### Pub/Sub Redis supports a [Publish/Subscribe messaging paradigm][pub-sub-wikipedia], with the `SUBSCRIBE`, `UNSUBSCRIBE` & `PUBLISH` commands, documented on [Pub/Sub page][redis-doc-pub-sub] of the official documentation. These commands have a significant impact of how data flows between clients and servers, and given that we have not yet added support for pub/sub, we will ignore its impact on our implementation of the Redis Protocol for now. Future chapters will add support for pub/sub and will follow the RESP specification. ### Pipelining RESP clients can send multiple requests at once and the RESP server will write multiple responses back, this is called [pipelining][redis-pipelining]. The only constraint is that commands must be processed in the same ordered they were received, so that clients can associate the responses back to each request. The following is an example of sending two commands at once and then reading the two responses, in Ruby: ``` ruby irb(main):001:0> require 'socket' => true irb(main):002:0> socket = TCPSocket.new 'localhost', 6379 irb(main):003:0> socket.write "SET 1 2\r\nGET 1\r\n" => 16 irb(main):004:0> socket.read_nonblock 1024 => "+OK\r\n$1\r\n2\r\n" ``` We first wrote the string `"SET 1 2\r\nGET 1\r\n"`, which represents the command `SET 1 2` and the command `GET ` in the inline format. The response we get from the server is a string containing the two responses, fist the Simple String `+OK\r\n`, followed by the Bulk String `$1\r\n2\r\n`. ## Making our Server speak RESP As far as I know there is no official test suite that we could run our server against to validate that it correctly follows RESP. What we can do instead is rely on `redis-cli` as a way to test the RESP implementation of our server. Let's see what happens when we try it with the current server. First let's start the server from Chapter 4: ``` DEBUG=t ruby -r"./server" -e "RedisServer.new" ``` and in another shell, let's open `redis-cli` on port 2000: ``` > redis-cli -p 2000 ``` You should see the following the server logs: ``` D, [2020-08-12T16:11:42.461645 #91271] DEBUG -- : Received command: *1 D, [2020-08-12T16:11:42.461688 #91271] DEBUG -- : Response: (error) ERR unknown command `*1`, with args beginning with: D, [2020-08-12T16:11:42.461925 #91271] DEBUG -- : Received command: $7 D, [2020-08-12T16:11:42.461960 #91271] DEBUG -- : Response: (error) ERR unknown command `$7`, with args beginning with: D, [2020-08-12T16:11:42.462005 #91271] DEBUG -- : Received command: COMMAND D, [2020-08-12T16:11:42.462036 #91271] DEBUG -- : Response: (error) ERR unknown command `COMMAND`, with args beginning with: ``` The server received the string `"*1\r\n$7\r\nCOMMAND\r\n"`, which is the RESP representation of the string `"COMMAND"` in a single item array, `[ "COMMAND" ]` in JSON. The [`COMMAND` command][redis-doc-command] is useful when running Redis [in a cluster][redis-doc-cluster]. Given that we have not yet implementer cluster capabilities, going into details about the `COMMAND` command is a little bit out of scope. In short the `COMMAND` command is useful to provide meta information about each command, such as information about the positions of the keys. This is useful because in cluster mode, clients have to route requests to the different nodes in the cluster. It is common for a command to have the key as the second element, the one coming directly after the command itself. This happens to be the case for all the commands we've implemented so far. But some commands have different semantics. For instance [`MSET`][redis-doc-mset] can contain multiple keys, so clients need to know where the keys are in the command. While rare, some commands have the first key at a different index, this is the case for the [`OBJECT` command][redis-doc-object]. Back to `redis-cli` running against our Redis server, if you then try to send a command, `GET 1` for instance, `redis-cli` will crash after printing the following error: ``` Error: Protocol error, got "(" as reply type byte ``` This is because our server writes the string `(nil)` when it does find an try for the given key. `(nil)` is what `redis-cli` displays when it receives a null Bulk String, as we can see with the following example, we first send the `GET 1` command with `redis-cli` and then with `nc` and observe the response in each case: ``` bash > nc -c localhost 6379 GET 1 $-1 # ... > redis-cli 127.0.0.1:6379> GET 1 (nil) ``` Our server must send the null Bulk String, `$-1\r\n`, to follow RESP. This is what `redis-cli` tells us before stopping, it expected a "type byte", one of `+`, `-`, `:`, `$` or `*`, but instead got `(`. In order to use `redis-cli` against our own server, we should implement the `COMMAND` command, since it sends it directly after starting. We also need to change how we process client input, to parse RESP arrays of Bulk Strings. We also need to support inline commands. Finally, we also need to update the responses we write back, and serialize responses following RESP. Let's get to it! ### Parsing Client Input **Modules & Namespaces** Most of the changes will take place in `server.rb`. As the codebase started to grow, I thought it would be easier to start using ruby modules, so I nested the `Server` class under the `Redis` namespace. This will allow us to create other classes & modules under the `Redis` namespace as well. All the other classes have been updated to be under the `Redis` namespace as well, e.g. `ExpireHelper` is now `BYORedis::ExpireHelper`. `BYO` stands for **B**uild **Y**our **O**wn. I'm purposefully not using `Redis` as it is already used by the popular [`redis`][redis-gem] gem. We're not using both at the same time in the same project for now, so it wouldn't really have been a problem. But say that you would like to use the `redis` gem to communicate with the server we're building, we will prevent any kind of unexpected errors by using different names. ``` ruby # expire_helper.rb module BYORedis module ExpireHelper def self.check_if_expired(data_store, expires, key) # ... end end end ``` _listing 5.1: Nesting ExpireHelper under the Redis module_ **Storing partial client buffer** As of the previous chapter we never stored the client input. We would read from the socket when `IO.select` would tell us there is something to read, read until the end of the line, and process the result as a command. It turns out that this approach is a bit too aggressive. Clients should be able to send a single command in two parts, there's no reason to treat that as an error. In order to do this, we are going to create a `Client` struct to hold the client socket as well a string containing all the pending input we have not process yet: ``` ruby # server.rb Client = Struct.new(:socket, :buffer) do def initialize(socket) self.socket = socket self.buffer = '' end end ``` _listing 5.2: The new Client class_ We need to adapt `process_poll_events` to use this new class instead of the raw socket coming as a result of `TCPServer#accept`: ``` ruby # server.rb def process_poll_events(sockets) sockets.each do |socket| begin if socket.is_a?(TCPServer) @clients << Client.new(@server.accept) elsif socket.is_a?(TCPSocket) client = @clients.find { |client| client.socket == socket } client_command_with_args = socket.read_nonblock(1024, exception: false) if client_command_with_args.nil? @clients.delete(client) socket.close elsif client_command_with_args == :wait_readable # ... else # We now need to parse the input as a RESP array # ... end else # ... end rescue Errno::ECONNRESET @clients.delete_if { |client| client.socket == socket } end end end ``` _listing 5.3: Updated handling of socket in server.rb_ **Parsing commands as RESP Arrays** More things need to change in `process_poll_events`. We first append the result from `read_nonblock` to `client.buffer`, which will allow us to continue appending until we accumulate enough to read a whole command. We then delegate the processing of `client.buffer` to a different method, `split_commands`: ``` ruby # server.rb def process_poll_events(sockets) sockets.each do |socket| begin # ... elsif socket.is_a?(TCPSocket) # ... else client.buffer += client_command_with_args split_commands(client.buffer) do |command_parts| response = handle_client_command(command_parts) @logger.debug "Response: #{ response.class } / #{ response.inspect }" @logger.debug "Writing: '#{ response.serialize.inspect }'" socket.write response.serialize end end else # ... end # ... end end end def split_commands(client_buffer) @logger.debug "Full result from read: '#{ client_buffer.inspect }'" scanner = StringScanner.new(client_buffer.dup) until scanner.eos? if scanner.peek(1) == '*' yield parse_as_resp_array(scanner) else yield parse_as_inline_command(scanner) end client_buffer.slice!(0, scanner.charpos) end end #... ``` _listing 5.4 Updated handling of client input in server.rb_ `split_commands` is in charge of splitting the client input into multiple commands, which is necessary to support pipelining. As a reminder, since we're adding support pipelining, we have to assume that the content of `client.buffer` might contain more than one command, and if so, we want to process them all in the order we received them, and write the responses back, in the same order. It also handles the two different versions of commands, inline, or "regular", as RESP Arrays. We use the `StringScanner` class, which is really convenient to process data from a string, from left to right. We call `String#dup` on the argument to `StringScanner` to make sure that the `StringScanner` gets its own instance. As we iterate through `client.buffer`, every time we find a whole command, we want to remove it from the client input. We do this with `client_buffer.slice!(0, scanner.charpos)`. If `client_buffer` contains two commands, i.e. `GET a\r\nGET b\r\n`, once we processed `GET a`, we want to remove the first 7 characters from the string: `GET a\r\n`, so that we never attempt to process them again. Note that we only do this after yielding, meaning that we only ever treat a command as done after we successfully wrote to the socket. We first peek at the first character, if it is `*`, the following should be a RESP array, and we process it as such. Otherwise, we assume that we're dealing with an inline command. Each branch delegates to a method handling the parsing of the string. The `yield` approach allows us to process each parsed command one by one, once parsed, we `yield` it, and it is handled by the `handle_client_command` method, which has barely changed from the previous chapter. Let's look at the `parse_as_resp_array` & `parse_as_inline_command` methods: ``` ruby def parse_as_inline_command(client_buffer, scanner) command = scanner.scan_until(/(\r\n|\r|\n)+/) raise IncompleteCommand if command.nil? command.split.map(&:strip) end def parse_as_resp_array(scanner) unless scanner.getch == '*' raise 'Unexpectedly attempted to parse a non array as an array' end expected_length = scanner.scan_until(/\r\n/) raise IncompleteCommand if expected_length.nil? expected_length = parse_integer(expected_length, 'invalid multibulk length') command_parts = [] expected_length.times do raise IncompleteCommand if scanner.eos? parsed_value = parse_as_resp_bulk_string(scanner) raise IncompleteCommand if parsed_value.nil? command_parts << parsed_value end command_parts end def parse_integer(integer_str, error_message) begin value = Integer(integer_str) if value < 0 raise ProtocolError, "ERR Protocol error: #{ error_message }" else value end rescue ArgumentError raise ProtocolError, "ERR Protocol error: #{ error_message }" end end ``` _listing 5.5 Parsing RESP Arrays in server.rb_ `parse_as_inline_command` starts by calling `StringScanner#scan_until`, with `/\r\n/`. `scan_until` keeps iterating through the string, until it encounters something that matches its argument. In our case it will keep going through `client_buffer` until it finds `CRLF`, if it doesn't find a match, it returns `nil`. We're not even trying to process the string in this case, it is incomplete, so we'll leave it in there and eventually reattempt later on, the next time we read from this client. If the string returned is not `nil`, it contains the string, and in this case, we do what we used to, we split it on spaces, and return it as an array of string parts, e.g. `GET 1\r\n` would be returned as `[ 'GET', '1' ]` `parse_as_resp_array` is more complicated. As a sanity check, we test again that the first character is indeed `*`, `getch` also moves the internal cursor of `StringScanner`, moving it to the first character of the expected length. Using `scan_until` we extract all the characters until the first `CRLF` characters in the client input. If `nil` is returned, this means that we reached the end of the string without encountering `CR` & `LF`, and instead of treating this as a client error, we raise an `IncompleteCommand` error, to give the client a change to write the missing parts of the command later on. `expected_length` will contain a string composed of the characters before `CRLF` & the `CRLF` characters. For instance, if the scanner was created with the string `$3\r\nabc\r\n` — The Bulk String representation of the string `"3"` — `expected_length` would be equal to `"3\r\n"`. The Ruby `String#to_i` is not strict enough here. It returns `0` in a lot of cases where we'd want an error instead, such as `"abc".to_i == 0`. We instead use the `Kernel.Integer` method, which raises an `ArgumentError` exception with invalid strings. We catch `ArgumentError` and raise a `ProtocolError` instead. In the next step we iterate as many times as the value of `expected_length` with `expected_length.times`. We start each iteration by checking if we reached the end of the string with `eos?`. If we did, then instead of returning a protocol error, we raise an `IncompleteCommand` exception. This gives a chance to the client to send the remaining elements of the array later on. As mentioned above, a request to Redis is always an array of Bulk Strings, so we attempt to parse all the elements as strings, by calling `parse_as_bulk_string` with the same `scanner` instance. Before looking at the method, let's see how the two new exceptions `IncompleteCommand` & `ProtocolError` are defined and handled: `IncompleteCommand` & `ProtocolError` are custom exceptions defined at the top of the file: ``` ruby # server.rb IncompleteCommand = Class.new(StandardError) ProtocolError = Class.new(StandardError) do def serialize RESPError.new(message).serialize end end ``` _listing 5.6 The new exceptions in server.rb_ `RESPError` is defined in `resp_types.rb`: ``` ruby # resp_types.rb module BYORedis RESPError = Struct.new(:message) do def serialize "-#{ message }\r\n" end end # ... end ``` _listing 5.7 The new RESPError class_ They are handled in the `begin/rescue` block in `process_poll_events`: ``` ruby # server.rb begin # ... rescue Errno::ECONNRESET @clients.delete_if { |client| client.socket == socket } rescue IncompleteCommand # Not clearing the buffer or anything next rescue ProtocolError => e socket.write e.serialize socket.close @clients.delete(client) end ``` _listing 5.8 Handling the new exceptions in server.rb_ We don't write anything back when encountering an `IncompleteCommand` exception, we assume that the client has not finished sending the command. On the other hand, for `ProtocolError`, we write an error back to the client, following the format of a RESP error and we disconnect the client. This is what Redis does too. Back to `parse_as_resp_bulk_string`: ``` ruby # server.rb def parse_as_resp_bulk_string(scanner) type_char = scanner.getch unless type_char == '$' raise ProtocolError, "ERR Protocol error: expected '$', got '#{ type_char }'" end expected_length = scanner.scan_until(/\r\n/) raise IncompleteCommand if expected_length.nil? expected_length = parse_integer(expected_length, 'invalid bulk length') bulk_string = scanner.rest.slice(0, expected_length) raise IncompleteCommand if bulk_string.nil? || bulk_string.length != expected_length scanner.pos += bulk_string.bytesize + 2 bulk_string end ``` _listing 5.9 Parsing Bulk Strings_ The first step is calling `StringScanner#getch`, it moves the internal cursor of the scanner by one character and returns it. If the first character is `$`, we received a Bulk String as expected. Anything else is an error. Redis accepts empty strings, and while it may be unusual, it is possible for a Redis key to be an empty string, and a value can also be an empty string. If the expected length is negative, then we stop and return a `ProtocolError` The next step is extracting the actual string. `StringScanner` maintains an internal cursor of the progress through the string. At this point this cursor is right after `CRLF`, where the string content starts. `StringScanner#rest` returns the string from this cursor until the end, and using `slice`, we extract only the number of characters indicated by `expected_length`. If the result of this operation is `nil` or shorter than the expected length, we don't want to treat it as an error yet, since it is possible for the clients to write the missing elements of the command, so we raise an `IncompleteCommand`, in the hope that the client will send the missing parts later on. The final step is to advance the cursor position in the `StringScanner` instance. We do this with the `StringScanner#pos=` method. Notice how we use the `bytesize` methods and two to it. We use `bytesize` instead of `length` to handle characters that span over multiple bytes, such as [CJK characters][wikipedia-cjk], accentuated characters, emojis and many others. Let's look at the difference in `irb`: ``` ruby irb(main):045:1* def print_length_and_bytesize(str) irb(main):046:1* puts str.length irb(main):047:1* puts str.bytesize irb(main):048:0> end => :print_length_and_bytesize irb(main):049:0> print_length_and_bytesize('a') 1 1 => nil irb(main):050:0> print_length_and_bytesize('é') 1 2 => nil irb(main):051:0> print_length_and_bytesize('你') 1 3 => nil irb(main):058:0> print_length_and_bytesize('😬') 1 4 => nil ``` As we can see, all of these strings return `1` for `length`, but different values, respectively 2, 3 & 4 for `bytesize`. Going into details about UTF-8 encoding is out of scope, but the main takeaway from this is that what we consider to be a single character, might span over multiple bytes. If a client had sent `你` as a Bulk String, we'd expect it to pass the length as 3, and therefore we need to advance the cursor by 3 in the `StringScanner` instance. We also add two to account for the trailing `CRLF` characters. Note that, like Redis, we do not actually check that these two characters are indeed `CR` & `LF`, we just skip over them. ### Updating the command responses The commands we've implemented so far, `GET`, `SET`, `TTL` & `PTTL` do not return data that follows the format defined in RESP. `GET` needs to return Bulk Strings, `SET` returns the Simple String `OK` or the null Bulk String if it didn't set the value and the last two, `TTL` & `PTTL`, return integers. We will first create new classes to wrap the process of serializing strings and integers to their matching RESP format: ``` ruby # resp_types.rb module BYORedis # ... RESPInteger = Struct.new(:underlying_integer) do def serialize ":#{ underlying_integer }\r\n" end def to_i underlying_integer.to_i end end RESPSimpleString = Struct.new(:underlying_string) do def serialize "+#{ underlying_string }\r\n" end end OKSimpleStringInstance = Object.new.tap do |obj| OK_SIMPLE_STRING = "+OK\r\n".freeze def obj.serialize OK_SIMPLE_STRING end end RESPBulkString = Struct.new(:underlying_string) do def serialize "$#{ underlying_string.bytesize }\r\n#{ underlying_string }\r\n" end end NullBulkStringInstance = Object.new.tap do |obj| NULL_BULK_STRING = "$-1\r\n".freeze def obj.serialize NULL_BULK_STRING end end RESPArray = Struct.new(:underlying_array) do def serialize serialized_items = underlying_array.map do |item| case item when RESPSimpleString, RESPBulkString item.serialize when String RESPBulkString.new(item).serialize when Integer RESPInteger.new(item).serialize when Array RESPArray.new(item).serialize end end "*#{ underlying_array.length }\r\n#{ serialized_items.join }" end end NullArrayInstance = Object.new.tap do |obj| NULL_ARRAY = "*-1\r\n".freeze def obj.serialize NULL_ARRAY end end end ``` _listing 5.10 The new RESP types_ `RESPArray` is not strictly required at the moment since none of the commands we've implemented so far return array responses, but the `COMMAND` command, which we'll implement below returns an array, so it'll be useful there. We could have chosen a few different options to represent the null array and the null list, such as adding the logic in `serialize` methods of `RESPArray` & `RESPBulkString`. I instead decided to create two globally available instances that implement the same interface, the `serialize` method. This allows the code in `server.rb` to always call `serialize` on the result it gets from calling the `call` method. On the other hand, in the `*Command` classes, it forces us to explicitly handle these null cases, which I find preferable to passing `nil` values around. We use the `String#freeze` method to prevent accidental modifications of the values at runtime. Ruby will throw an exception if you attempt to do so: ``` ruby irb(main):001:0> require_relative './server' => true irb(main):002:0> BYORedis::NULL_BULK_STRING => "$-1\r\n" irb(main):003:0> BYORedis::NULL_BULK_STRING << "a" Traceback (most recent call last): 4: from /Users/pierre/.rbenv/versions/2.7.1/bin/irb:23:in `<main>' 3: from /Users/pierre/.rbenv/versions/2.7.1/bin/irb:23:in `load' 2: from /Users/pierre/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/irb-1.2.3/exe/irb:11:in `<top (required)>' 1: from (irb):3 FrozenError (can't modify frozen String: "$-1\r\n") ``` That said, do note that "constants" in Ruby aren't really "constants", it is possible to reassign the value at runtime: ``` ruby irb(main):004:0> BYORedis::NULL_BULK_STRING = "something else" (irb):4: warning: already initialized constant BYORedis::NULL_BULK_STRING /Users/pierre/dev/redis-in-ruby/code/chapter-5/resp_types.rb:32: warning: previous definition of NULL_BULK_STRING was here irb(main):005:0> BYORedis::NULL_BULK_STRING => "something else" ``` While it doesn't prevent all kinds of weird runtime issues, I do like the use of `String#freeze` to at least be explicit about the nature of the value, signifying that it is not supposed to be modified. The `OK` Simple String is so common that I created a constant for it, `OKSimpleStringInstance`, so that it can be reused instead of having to allocate a new instance every time we need it. Only the `SetCommand` class uses it for now, but more commands use it, such as `LSET`, `MSET` and many others. Let's start with `GET`: ``` ruby # get_command.rb module BYORedis class GetCommand # ... def call if @args.length != 1 RESPError.new("ERR wrong number of arguments for 'GET' command") else key = @args[0] ExpireHelper.check_if_expired(@data_store, @expires, key) value = @data_store[key] if value.nil? NullBulkStringInstance else RESPBulkString.new(value) end end end end end ``` _listing 5.11 Updated response in GetCommand_ Now that `BYORedis::GetCommand` has been updated, let's tackle `SetCommand`: ``` ruby # set_command.rb def call key, value = @args.shift(2) if key.nil? || value.nil? return RESPError.new("ERR wrong number of arguments for 'SET' command") end parse_result = parse_options existing_key = @data_store[key] if @options['presence'] # ... NullBulkStringInstance elsif @options['presence'] # ... NullBulkStringInstance else # ... OKSimpleStringInstance end rescue ValidationError => e RESPError.new(e.message) rescue SyntaxError => e RESPError.new(e.message) end ``` _listing 5.12 Updated response in SetCommand_ The `SET` command has two possible outputs, either the nil string if the outcome was that nothing was set, as a result of the `NX` or `XX` options, or the Simple String `OK` if the outcome was a successful set. This is where the special case instances `NullBulkStringInstance` & `OKSimpleStringInstance` come in handy. By returning them here, the code in `server.rb` can leverage duck typing and call the `serialize` method, but under the hood, the same strings will be used, `BYORedis::OK_SIMPLE_STRING` & `BYORedis::NULL_BULK_STRING`. This is a very small optimization, but given how common it is to call the `SET` command, it is interesting to think about things like that to prevent unnecessary work on the server. And finally we need to update `TtlCommand` and `PttlCommand` ``` ruby # pttl_command.rb def call if @args.length != 1 RESPError.new("ERR wrong number of arguments for 'PTTL' command") else key = @args[0] ExpireHelper.check_if_expired(@data_store, @expires, key) key_exists = @data_store.include? key value = if key_exists ttl = @expires[key] if ttl (ttl - (Time.now.to_f * 1000)).round else -1 end else -2 end RESPInteger.new(value) end end # ttl_command.rb def call if @args.length != 1 RESPError.new("ERR wrong number of arguments for 'TTL' command") else pttl_command = PttlCommand.new(@data_store, @expires, @args) result = pttl_command.call.to_i if result > 0 RESPInteger.new((result / 1000.0).round) else RESPInteger.new(result) end end end ``` _listing 5.13 Updated response in PttlCommand & TtlCommand_ ### Case insensitivity It is not explicitly mentioned in the RESP v2 documentation, but Redis treats commands and options as case insensitive. The following examples are all valid: `get 1`, `GeT 1`, `set key value EX 1 nx`. In order to apply the same handling logic, we changed the keys in the `COMMANDS` constant to be lower case, and we always lower case the client input when attempting to find a handler for the command: ``` ruby # server.rb COMMANDS = { 'command' => CommandCommand, 'get' => GetCommand, 'set' => SetCommand, 'ttl' => TtlCommand, 'pttl' => PttlCommand, } # ... def handle_client_command(command_parts) @logger.debug "Received command: #{ command_parts }" command_str = command_parts[0] args = command_parts[1..-1] command_class = COMMANDS[command_str.downcase] # ... end ``` _listing 5.14 Updates for case insensitivity in BYORedis::Server_ We also need to update the `BYORedis::SetCommand` class to handle options regardless of the case chosen by clients: ``` ruby # set_command.rb # ... OPTIONS = { 'ex' => CommandOptionWithValue.new( 'expire', ->(value) { validate_integer(value) * 1000 }, ), 'px' => CommandOptionWithValue.new( 'expire', ->(value) { validate_integer(value) }, ), 'keepttl' => CommandOption.new('expire'), 'nx' => CommandOption.new('presence'), 'xx' => CommandOption.new('presence'), } #... def parse_options while @args.any? option = @args.shift option_detail = OPTIONS[option.downcase] # ... end end #... ``` _listing 5.15 Updates for case insensitivity in SetCommand_ ### The `COMMAND` command In order to implement `COMMAND`, we added a describe method to each of the `*Command` classes, so that the `CommandCommand` class can iterate over all these classes and call `.describe` on them, and then serialize the result to a RESP array: ``` ruby # command_command.rb module BYORedis class CommandCommand def initialize(_data_store, _expires, _args) end def call RESPArray.new(Server::COMMANDS.map { |_, command_class| command_class.describe } ) end def self.describe [ 'command', -1, # arity # command flags [ 'random', 'loading', 'stale' ].map { |s| RESPSimpleString.new(s) }, 0, # position of first key in argument list 0, # position of last key in argument list 0, # step count for locating repeating keys # acl categories: https://github.com/antirez/redis/blob/6.0/src/server.c#L161-L166 [ '@slow', '@connection' ].map { |s| RESPSimpleString.new(s) }, ] end end end ``` _listing 5.16 The new CommandCommand class_ ``` ruby # get_command.rb def self.describe [ 'get', 2, # arity # command flags [ 'readonly', 'fast' ].map { |s| RESPSimpleString.new(s) }, 1, # position of first key in argument list 1, # position of last key in argument list 1, # step count for locating repeating keys # acl categories: https://github.com/antirez/redis/blob/6.0/src/server.c#L161-L166 [ '@read', '@string', '@fast' ].map { |s| RESPSimpleString.new(s) }, ] end # pttl_command.rb def self.describe [ 'pttl', 2, # arity # command flags [ 'readonly', 'random', 'fast' ].map { |s| RESPSimpleString.new(s) }, 1, # position of first key in argument list 1, # position of last key in argument list 1, # step count for locating repeating keys # acl categories: https://github.com/antirez/redis/blob/6.0/src/server.c#L161-L166 [ '@keyspace', '@read', '@fast' ].map { |s| RESPSimpleString.new(s) }, ] end # set_command.rb def self.describe [ 'set', -3, # arity # command flags [ 'write', 'denyoom' ].map { |s| RESPSimpleString.new(s) }, 1, # position of first key in argument list 1, # position of last key in argument list 1, # step count for locating repeating keys # acl categories: https://github.com/antirez/redis/blob/6.0/src/server.c#L161-L166 [ '@write', '@string', '@slow' ].map { |s| RESPSimpleString.new(s) }, ] end # ttl_command.rb def self.describe [ 'ttl', 2, # arity # command flags [ 'readonly', 'random', 'fast' ].map { |s| RESPSimpleString.new(s) }, 1, # position of first key in argument list 1, # position of last key in argument list 1, # step count for locating repeating keys # acl categories: https://github.com/antirez/redis/blob/6.0/src/server.c#L161-L166 [ '@keyspace', '@read', '@fast' ].map { |s| RESPSimpleString.new(s) }, ] end ``` _listing 5.17 Updates for the COMMAND command in SetCommand, GetCommand, TtlCommand & PttlCommand_ ### test.rb & test_helper.rb Testing the `BYORedis::Server` class is becoming more and more complicated, in order to keep things clean, I moved a lot of the helper method to the `test_helper.rb` file, so that `test.rb` only contains the actual tests. The `assert_command_results` helper has been updated to handle the RESP format. For the sake of simplicity, it assumes that the data is not serialized and does that for you. This allows us to write simpler assertions such as: ``` ruby assert_command_results [ [ 'SET 1 3 NX EX 1', '+OK' ], [ 'GET 1', '3' ], [ 'SET 1 3 XX keepttl', '+OK' ], ] ``` and the `assert_command_results` will serialize the commands as RESP Arrays for us. I also added a new assertion helper, `assert_multipart_command_results`. It allows a little bit more flexibility around expectations for commands sent through multiple `write` calls. Instead of being a single command like in `assert_command_results`, the first element of the pair is itself an array of strings, each of them representing a sequence of characters that will be sent to the server. This is handy to test pipelining as well as edge cases with regard to RESP. ``` ruby # test_helper.rb # The arguments in an array of array of the form # [ # [ [ "COMMAND-PART-I", "COMMAND-PART-II", ... ], "EXPECTED_RESULT" ], # ... # ] def assert_multipart_command_results(multipart_command_result_pairs) with_server do |server_socket| multipart_command_result_pairs.each do |command, expected_result| command.each do |command_part| server_socket.write command_part # Sleep for one milliseconds to give a chance to the server to read # the first partial command sleep 0.001 end response = read_response(server_socket) if response.length < expected_result.length # If the response we got is shorter, maybe we need to give the server a bit more time # to finish processing everything we wrote, so give it another shot sleep 0.1 response += read_response(server_socket) end assert_response(expected_result, response) end end end def assert_command_results(command_result_pairs) with_server do |server_socket| command_result_pairs.each do |command, expected_result| if command.is_a?(String) && command.start_with?('sleep') sleep command.split[1].to_f next end command_string = if command.start_with?('*') command else BYORedis::RESPArray.new(command.split).serialize end server_socket.write command_string response = read_response(server_socket) assert_response(expected_result, response) end end end def assert_response(expected_result, response) assertion_match = expected_result&.match(/(\d+)\+\/-(\d+)/) if assertion_match response_match = response.match(/\A:(\d+)\r\n\z/) assert response_match[0] assert_in_delta assertion_match[1].to_i, response_match[1].to_i, assertion_match[2].to_i else if expected_result && !%w(+ - : $ *).include?(expected_result[0]) # Convert to a Bulk String unless it is a Simple String (starts with a +) # or an error (starts with -) expected_result = BYORedis::RESPBulkString.new(expected_result).serialize end if expected_result && !expected_result.end_with?("\r\n") expected_result += "\r\n" end if expected_result.nil? assert_nil response else assert_equal expected_result, response end end end def read_response(server_socket) response = '' loop do select_res = IO.select([ server_socket ], [], [], 0.1) last_response = server_socket.read_nonblock(1024, exception: false) if last_response == :wait_readable || last_response.nil? || select_res.nil? response = nil break else response += last_response break if response.length < 1024 end end response&.force_encoding('utf-8') rescue Errno::ECONNRESET response&.force_encoding('utf-8') end def to_query(*command_parts) [ BYORedis::RESPArray.new(command_parts).serialize ] end ``` _listing 5.18 The new test helpers in test_helper.rb_ ## Conclusion We can now use redis-cli, with `redis-cli -p 2000` to interact with our redis server: ``` bash > redis-cli -p 2000 127.0.0.1:2000> COMMAND 1) 1) "command" 2) (integer) -1 3) 1) random 2) loading 3) stale 4) (integer) 0 5) (integer) 0 6) (integer) 0 7) 1) @slow 2) @connection 2) 1) "get" 2) (integer) 2 3) 1) readonly 2) fast 4) (integer) 1 5) (integer) 1 6) (integer) 1 7) 1) @read 2) @string 3) @fast 3) 1) "set" 2) (integer) -3 3) 1) write 2) denyoom 4) (integer) 1 5) (integer) 1 6) (integer) 1 7) 1) @write 2) @string 3) @slow 4) 1) "ttl" 2) (integer) 2 3) 1) readonly 2) random 3) fast 4) (integer) 1 5) (integer) 1 6) (integer) 1 7) 1) @keyspace 2) @read 3) @fast 5) 1) "pttl" 2) (integer) 2 3) 1) readonly 2) random 3) fast 4) (integer) 1 5) (integer) 1 6) (integer) 1 7) 1) @keyspace 2) @read 3) @fast 127.0.0.1:2000> GET a-key (nil) 127.0.0.1:2000> SET name pierre OK 127.0.0.1:2000> GET name "pierre" 127.0.0.1:2000> SET last-name J EX 10 OK 127.0.0.1:2000> TTL last-name (integer) 6 127.0.0.1:2000> PTTL last-name (integer) 5016 127.0.0.1:2000> PTTL last-name (integer) 2432 127.0.0.1:2000> DEL name (error) ERR unknown command `DEL`, with args beginning with: `name`, ``` All the commands we already implemented work as expected and non implemented commands such as `DEL` return an unknown command error. So far so good! In the next chapter we'll write our own Hashing algorithm and ban the use of the `Hash` class in our code. ### Code As usual, the code [is available on GitHub](https://github.com/pjambet/redis-in-ruby/tree/master/code/chapter-5). [github-code]:https://github.com/pjambet/redis-in-ruby/tree/master/code/chapter-5 [resp-spec]:https://redis.io/topics/protocol [resp3-spec]:https://github.com/antirez/RESP3/blob/master/spec.md [resp3-spec-background]:https://github.com/antirez/RESP3/blob/master/spec.md#background [release-notes-6-0]:https://github.com/redis/redis/blob/6.0/00-RELEASENOTES [redis-doc-hello]:http://redis.io/commands/hello [ascii-table]:http://www.asciitable.com/ [redis-ruby-client]:https://github.com/redis/redis-rb [redis-pipelining]:https://redis.io/topics/pipelining [redis-doc-object]:http://redis.io/commands/object [redis-doc-mset]:http://redis.io/commands/mset [redis-doc-command]:http://redis.io/commands/command [pub-sub-wikipedia]:http://en.wikipedia.org/wiki/Publish/subscribe [redis-doc-pub-sub]:https://redis.io/topics/pubsub [ruby-doc-string-scanner]:http://ruby-doc.org/stdlib-2.7.1/libdoc/strscan/rdoc/StringScanner.html [wikipedia-cjk]:https://en.wikipedia.org/wiki/CJK_characters [redis-doc-lrange]:https://redis.io/commands/lrange [chapter-7]:/post/chapter-7 [redis-doc-cluster]:https://redis.io/topics/cluster-tutorial [redis-gem]:https://github.com/redis/redis-rb <file_sep>/code/chapter-10/test/list_unit_test.rb # coding: utf-8 require_relative './test_helper' require_relative '../list' describe BYORedis::List do describe 'left_pop' do it 'returns nil with an empty list' do list = new_list assert_nil(list.left_pop) end it 'removes the element at the head of list' do list = new_list (1..3).each { |i| list.right_push(i) } head = list.left_pop assert_equal(1, head.value) assert_equal(2, list.head.value) assert_nil(list.head.prev_node) head = list.left_pop assert_equal(2, head.value) assert_equal(3, list.head.value) assert_nil(list.head.prev_node) head = list.left_pop assert_equal(3, head.value) assert_nil(list.head) assert_nil(list.tail) end end describe 'left_push' do it 'adds a new element that becomes the head of the list' do list = new_list (1..3).each { |i| list.left_push(i) } assert_has_elements(list, 3, 2, 1) head = list.head assert_nil(head.prev_node) assert_equal(2, head.next_node.value) second_node = list.head.next_node assert_equal(3, second_node.prev_node.value) assert_equal(1, second_node.next_node.value) assert_equal(list.tail, second_node.next_node) tail = list.head.next_node.next_node assert_nil(tail.next_node) assert_equal(2, tail.prev_node.value) end end describe 'right_pop' do it 'returns nil with an empty list' do list = new_list assert_nil(list.right_pop) end it 'removes the element as the tail of the list' do list = new_list (1..3).each { |i| list.right_push(i) } tail = list.right_pop assert_equal(3, tail.value) assert_equal(2, list.tail.value) assert_nil(list.tail.next_node) tail = list.right_pop assert_equal(2, tail.value) assert_equal(1, list.tail.value) assert_nil(list.tail.next_node) tail = list.right_pop assert_equal(1, tail.value) assert_nil(list.head) assert_nil(list.tail) end end describe 'right_push' do it 'adds a new element that becomes the new tail of the list' do list = new_list (1..3).each { |i| list.right_push(i) } assert_has_elements(list, 1, 2, 3) assert_equal(list.head.value, 1) assert_equal(list.tail.value, 3) head = list.head assert_nil(head.prev_node) assert_equal(2, head.next_node.value) second_node = list.head.next_node assert_equal(1, second_node.prev_node.value) assert_equal(3, second_node.next_node.value) assert_equal(list.tail, second_node.next_node) tail = list.head.next_node.next_node assert_nil(tail.next_node) assert_equal(2, tail.prev_node.value) end end describe 'set' do it 'updates the value at the given index' do list = new_list (1..3).each { |i| list.right_push(i) } list.set(1, 'foo') assert_has_elements(list, 1, 'foo', 3) end it 'updates the value starting from the right at the given negative' do list = new_list (1..3).each { |i| list.right_push(i) } list.set(-2, 'foo') assert_has_elements(list, 1, 'foo', 3) end end describe 'remove' do it 'removes n nodes matching element' do list = new_list (1..5).each { |i| list.right_push(i) } list.right_push(1) list.right_push(2) list.right_push(1) list.right_push(2) # List is 1,2,3,4,5,1,2,1,2 assert_equal(0, list.remove(1, 10)) assert_equal(1, list.remove(1, 2)) assert_has_elements(list, 1, 3, 4, 5, 1, 2, 1, 2) assert_equal(2, list.remove(2, 2)) assert_has_elements(list, 1, 3, 4, 5, 1, 1) assert_equal(3, list.remove(10, 1)) assert_has_elements(list, 3, 4, 5) assert_equal(3, list.head.value) assert_nil(list.head.prev_node) assert_equal(5, list.tail.value) assert_nil(list.tail.next_node) end it 'removes n nodes starting from the right with a negative count' do list = new_list (1..5).each { |i| list.right_push(i) } list.right_push(1) list.right_push(2) list.right_push(1) list.right_push(2) # list is 1,2,3,4,5,1,2,1,2 assert_equal(0, list.remove(-1, 10)) assert_equal(1, list.remove(-1, 2)) assert_has_elements(list, 1, 2, 3, 4, 5, 1, 2, 1) assert_equal(2, list.remove(-2, 2)) assert_has_elements(list, 1, 3, 4, 5, 1, 1) assert_equal(2, list.remove(-2, 1)) assert_has_elements(list, 1, 3, 4, 5) assert_equal(1, list.head.value) assert_nil(list.head.prev_node) assert_equal(5, list.tail.value) assert_nil(list.tail.next_node) end it 'removes all nodes matching element with count set to 0' do list = new_list (1..5).each { |i| list.right_push(i) } list.right_push(1) list.right_push(2) list.right_push(1) list.right_push(2) # list is 1,2,3,4,5,1,2,1,2 assert_equal(3, list.remove(0, 2)) assert_has_elements(list, 1, 3, 4, 5, 1, 1) assert_equal(3, list.remove(0, 1)) assert_has_elements(list, 3, 4, 5) end end describe 'position' do describe 'without any options' do it 'returns nil if no nodes match element' do list = new_list (1..5).each { |i| list.right_push(i) } assert_nil(list.position(10, nil, nil, nil)) end it 'returns the index of the first node matching element' do list = new_list (1..5).each { |i| list.right_push(i) } assert_equal(0, list.position(1, nil, nil, nil)) assert_equal(1, list.position(2, nil, nil, nil)) assert_equal(2, list.position(3, nil, nil, nil)) assert_equal(3, list.position(4, nil, nil, nil)) assert_equal(4, list.position(5, nil, nil, nil)) end end describe 'with a count' do it 'returns an empty array if no nodes match element' do list = new_list (1..5).each { |i| list.right_push(i) } assert_equal([], list.position(10, 1, nil, nil)) end it 'returns an array of up to n indexes for all matches' do list = new_list (1..5).each { |i| list.right_push(i) } 3.times { list.right_push(1) } # list is now 1,2,3,4,5,1,1,1 assert_equal([ 0 ], list.position(1, 1, nil, nil)) assert_equal([ 0, 5 ], list.position(1, 2, nil, nil)) assert_equal([ 0, 5, 6 ], list.position(1, 3, nil, nil)) assert_equal([ 0, 5, 6, 7 ], list.position(1, 4, nil, nil)) assert_equal([ 0, 5, 6, 7 ], list.position(1, 5, nil, nil)) end it 'returns nil with a negative count' do list = new_list assert_nil(list.position(1, -1, nil, nil)) end end describe 'with rank' do it 'skips n elements from the left with a positive rank' do list = new_list (1..5).each { |i| list.right_push(i) } 3.times { list.right_push(1) } # list is now 1,2,3,4,5,1,1,1 assert_equal(0, list.position(1, nil, nil, 1)) assert_equal(5, list.position(1, nil, nil, 2)) assert_equal(6, list.position(1, nil, nil, 3)) assert_equal(7, list.position(1, nil, nil, 4)) assert_nil(list.position(1, nil, nil, 5)) assert_equal([ 0 ], list.position(1, 1, nil, 1)) assert_equal([ 5 ], list.position(1, 1, nil, 2)) assert_equal([ 6 ], list.position(1, 1, nil, 3)) assert_equal([ 7 ], list.position(1, 1, nil, 4)) assert_equal([], list.position(1, 1, nil, 5)) assert_equal([ 6, 7 ], list.position(1, 3, nil, 3)) end it 'skips n elements from the right with a negative rank' do list = new_list (1..5).each { |i| list.right_push(i) } 3.times { list.right_push(1) } # list is now 1,2,3,4,5,1,1,1 assert_equal([ 7 ], list.position(1, 1, nil, -1)) assert_equal([ 7, 6 ], list.position(1, 2, nil, -1)) assert_equal([ 7, 6, 5 ], list.position(1, 3, nil, -1)) assert_equal([ 7, 6, 5, 0 ], list.position(1, 4, nil, -1)) assert_equal([ 7, 6, 5, 0 ], list.position(1, 5, nil, -1)) end end describe 'with maxlen' do it 'returns nil with a negative maxlen'do list = new_list assert_nil(list.position(10, 0, -1, 0)) end it 'only inspects maxlen nodes from the left' do list = new_list (1..5).each { |i| list.right_push(i) } 3.times { list.right_push(1) } # list is now 1,2,3,4,5,1,1,1 assert_equal(0, list.position(1, nil, 1, nil)) assert_equal([ 0 ], list.position(1, 3, 1, nil)) assert_equal([ 0, 5 ], list.position(1, 3, 6, nil)) end it 'only inspects maxlen nodes from the right with a negative rank' do list = new_list (1..5).each { |i| list.right_push(i) } 3.times { list.right_push(1) } # list is now 1,2,3,4,5,1,1,1 assert_equal(7, list.position(1, nil, 1, -1)) assert_equal([ 7 ], list.position(1, 3, 1, -1)) assert_equal([ 7, 6, 5 ], list.position(1, 3, 6, -1)) end it 'inspects the whole list with maxlen set to 0' do list = new_list (1..5).each { |i| list.right_push(i) } 3.times { list.right_push(1) } # list is now 1,2,3,4,5,1,1,1 assert_equal([ 0, 5, 6, 7 ], list.position(1, 0, 0, nil)) end end end describe 'insert_before' do it 'does nothing if no nodes match pivot' do list = new_list assert_equal(-1, list.insert_before(1, 1)) end it 'insert a new node before the first node matching pivot' do list = new_list (1..3).each { |i| list.right_push(i) } assert_equal(4, list.insert_before(3, 'new-node')) assert_has_elements(list, 1, 2, 'new-node', 3) assert_equal(5, list.insert_before(1, 'new-head')) assert_has_elements(list, 'new-head', 1, 2, 'new-node', 3) assert_nil(list.head.prev_node) end end describe 'insert_after' do it 'does nothing if no nodes match pivot' do list = new_list assert_equal(-1, list.insert_after(1, 1)) end it 'insert a new node after the first node matching pivot' do list = new_list (1..3).each { |i| list.right_push(i) } assert_equal(4, list.insert_after(2, 'new-node')) assert_has_elements(list, 1, 2, 'new-node', 3) assert_equal(5, list.insert_after(3, 'new-tail')) assert_has_elements(list, 1, 2, 'new-node', 3, 'new-tail') assert_nil(list.tail.next_node) end end describe 'at_index' do it 'returns nil if index is out of bound' do list = new_list assert_nil(list.at_index(0)) assert_nil(list.at_index(1)) end it 'returns the value of the element at the given index' do list = new_list (1..3).each { |i| list.right_push(i) } assert_equal(1, list.at_index(0)) assert_equal(2, list.at_index(1)) assert_equal(3, list.at_index(2)) end it 'returns the value of the element starting from the right at the given negative index' do list = new_list (1..3).each { |i| list.right_push(i) } assert_equal(3, list.at_index(-1)) assert_equal(2, list.at_index(-2)) assert_equal(1, list.at_index(-3)) assert_nil(list.at_index(-4)) end end describe 'trim' do it 'is a no-op with 0 -1' do list = new_list (1..3).each { |i| list.right_push(i) } list.trim(0, -1) assert_has_elements(list, 1, 2, 3) assert_equal(list.head.value, 1) assert_equal(list.tail.value, 3) end it 'removes elements at the beginning of the list' do list = new_list (1..5).each { |i| list.right_push(i) } list.trim(2, -1) assert_has_elements(list, 3, 4, 5) assert_equal(list.head.value, 3) assert_equal(list.tail.value, 5) end it 'removes elements at the end of the list' do list = new_list (1..5).each { |i| list.right_push(i) } list.trim(0, 2) assert_has_elements(list, 1, 2, 3) assert_equal(list.head.value, 1) assert_equal(list.tail.value, 3) end it 'empties the list if start is greater than the list size' do list = new_list (1..3).each { |i| list.right_push(i) } list.trim(10, 10) assert_equal(0, list.size) assert_nil(list.head) assert_nil(list.tail) end it 'empties the list if start > stop' do list = new_list (1..3).each { |i| list.right_push(i) } list.trim(2, 0) assert_equal(0, list.size) assert_nil(list.head) assert_nil(list.tail) end it 'handles an out of bound start index' do list = new_list (1..10).each { |i| list.right_push(i) } list.trim(-10, 2) assert_has_elements(list, 1, 2, 3) assert_equal(list.head.value, 1) assert_equal(list.tail.value, 3) end it 'handles an out of bound stop index' do list = new_list (1..10).each { |i| list.right_push(i) } list.trim(8, 100) assert_has_elements(list, 9, 10) assert_equal(list.head.value, 9) assert_equal(list.tail.value, 10) end it 'handles a negative index for start within the boundaries of the list' do list = new_list (1..10).each { |i| list.right_push(i) } list.trim(-2, 9) assert_has_elements(list, 9, 10) assert_equal(list.head.value, 9) assert_equal(list.tail.value, 10) end it 'handles a negative index for start outside the boundaries of the list' do list = new_list (1..3).each { |i| list.right_push(i) } list.trim(-20, 1) assert_has_elements(list, 1, 2) assert_equal(list.head.value, 1) assert_equal(list.tail.value, 2) end it 'handles a negative index for stop within the boundaries of the list' do list = new_list (1..10).each { |i| list.right_push(i) } list.trim(0, -8) assert_has_elements(list, 1, 2, 3) assert_equal(list.head.value, 1) assert_equal(list.tail.value, 3) end it 'handles a negative index for stop outside the boundaries of the list' do list = new_list (1..3).each { |i| list.right_push(i) } list.trim(1, 100) assert_has_elements(list, 2, 3) assert_equal(list.head.value, 2) assert_equal(list.tail.value, 3) end it 'handles a 0 99,999 trim for a 100,001 element list with a single operation' do list = new_list (1..100_001).each { |i| list.right_push(i) } t0 = Time.now list.trim(0, 99_999) t1 = Time.now duration = t1 - t0 # Assert that it was faster that 0.05 ms # A non-optimized version that has to iterate through the whole list would take a few ms # between 5ms and 7ms on my 2013 mbp assert_operator 0.000050, :>=, duration assert_equal(100_000, list.size) end it 'handles a 99,998 99,999 trim for a 100,001 element list with a single operation' do list = new_list (1..100_001).each { |i| list.right_push(i) } t0 = Time.now list.trim(99_998, 99_999) t1 = Time.now duration = t1 - t0 # Assert that it was faster that 0.05 ms # A non-optimized version that has to iterate through the whole list would take a few ms # between 5ms and 7ms on my 2013 mbp assert_operator 0.000070, :>=, duration assert_equal(2, list.size) end it 'something' do list = new_list list.right_push('b') list.right_push('c') list.right_push('d') # (1..100_001).each { |i| list.right_push(i) } # t0 = Time.now list.trim(2, 22) # t1 = Time.now # duration = t1 - t0 # Assert that it was faster that 0.05 ms # A non-optimized version that has to iterate through the whole list would take a few ms # between 5ms and 7ms on my 2013 mbp # assert_operator 0.000050, :>=, duration assert_equal(1, list.size) assert_equal(list.head.value, 'd') assert_equal(list.tail.value, 'd') end end def new_list BYORedis::List.new end def assert_has_elements(list, *elements) cursor = list.head assert_equal(elements.size, list.size) while cursor element = elements.shift assert_equal(element, cursor.value) cursor = cursor.next_node end end end <file_sep>/code/chapter-5/set_command.rb module BYORedis class SetCommand ValidationError = Class.new(StandardError) SyntaxError = Class.new(StandardError) CommandOption = Struct.new(:kind) CommandOptionWithValue = Struct.new(:kind, :validator) OPTIONS = { 'ex' => CommandOptionWithValue.new( 'expire', ->(value) { validate_integer(value) * 1000 }, ), 'px' => CommandOptionWithValue.new( 'expire', ->(value) { validate_integer(value) }, ), 'keepttl' => CommandOption.new('expire'), 'nx' => CommandOption.new('presence'), 'xx' => CommandOption.new('presence'), } def self.validate_integer(str) Integer(str) rescue ArgumentError, TypeError raise ValidationError, 'ERR value is not an integer or out of range' end def initialize(data_store, expires, args) @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @data_store = data_store @expires = expires @args = args @options = {} end def call key, value = @args.shift(2) if key.nil? || value.nil? return RESPError.new("ERR wrong number of arguments for 'SET' command") end parse_result = parse_options existing_key = @data_store[key] if @options['presence'] == 'nx' && !existing_key.nil? NullBulkStringInstance elsif @options['presence'] == 'xx' && existing_key.nil? NullBulkStringInstance else @data_store[key] = value expire_option = @options['expire'] # The implied third branch is if expire_option == 'KEEPTTL', in which case we don't have # to do anything if expire_option.is_a? Integer @expires[key] = (Time.now.to_f * 1000).to_i + expire_option elsif expire_option.nil? @expires.delete(key) end OKSimpleStringInstance end rescue ValidationError => e RESPError.new(e.message) rescue SyntaxError => e RESPError.new(e.message) end def self.describe [ 'set', -3, # arity # command flags [ 'write', 'denyoom' ].map { |s| RESPSimpleString.new(s) }, 1, # position of first key in argument list 1, # position of last key in argument list 1, # step count for locating repeating keys # acl categories: https://github.com/antirez/redis/blob/6.0/src/server.c#L161-L166 [ '@write', '@string', '@slow' ].map { |s| RESPSimpleString.new(s) }, ] end private def parse_options while @args.any? option = @args.shift option_detail = OPTIONS[option.downcase] if option_detail option_values = parse_option_arguments(option, option_detail) existing_option = @options[option_detail.kind] if existing_option raise SyntaxError, 'ERR syntax error' else @options[option_detail.kind] = option_values end else raise SyntaxError, 'ERR syntax error' end end end def parse_option_arguments(option, option_detail) case option_detail when CommandOptionWithValue option_value = @args.shift option_detail.validator.call(option_value) when CommandOption option.downcase else raise "Unknown command option type: #{ option_detail }" end end end end <file_sep>/code/chapter-10/flush_db_command.rb module BYORedis class FlushDBCommand < BaseCommand def initialize(db, args) @db = db @args = args end def call Utils.assert_args_length(0, @args) @db.flush OKSimpleStringInstance end def self.describe Describe.new('flushdb', 1, [ 'write' ], 1, -1, 1, [ '@keyspace', '@write', '@slow' ]) end end end <file_sep>/content/post/chapter-15-lru-cache.md --- title: "Chapter 15 Lru Cache" date: 2020-10-17T18:18:27-04:00 lastmod: 2020-10-17T18:18:27-04:00 draft: true comment: false keywords: [] summary: "" --- <!--more--> https://redis.io/topics/lru-cache <file_sep>/content/chapters.md --- title: "Chapters" date: 2020-05-17T23:45:33-04:00 lastmod: 2020-05-17T23:45:33-04:00 draft: false comment: false keywords: [] description: "List of all chapters" --- - [Chapter 1 - A Basic Server](/post/chapter-1-basic-server/) - [Chapter 2 - Respond to Get & Set](/post/chapter-2-respond-to-get-and-set/) - [Chapter 3 - Multiple clients](/post/chapter-3-multiple-clients/) - [Chapter 4 - Adding the missing options to SET](/post/chapter-4-adding-missing-options-to-set/) - [Chapter 5 - Deeper dive in the Redis Protocol](/post/chapter-5-redis-protocol-compatibility/) - [Chapter 6 - Building a Hash Table](/post/chapter-6-building-a-hash-table/) - [Chapter 7 - Adding List Commands](/post/chapter-7-adding-list-commands/) - [Chapter 8 - Hashes](/post/chapter-8-adding-hash-commands/) - [Chapter 9 - Sets](/post/chapter-9-adding-set-commands/) - [Chapter 10 - Sorted Sets](/post/chapter-10-adding-sorted-set-commands/) Coming Soon - [Chapter 11 - Bitmaps](/post/chapter-11-bitmaps/) - [Chapter 12 - HyperLogLogs](/post/chapter-12-hyperloglogs/) - [Chapter 13 - GEO* commands](/post/chapter-13-geo-commands/) - [Chapter 14 - Pub/Sub](/post/chapter-14-pub-sub-commands/) - [Chapter 15 - Redis as an LRU cache](/post/chapter-15-lru-cache/) - [Chapter 16 - Transactions](/post/chapter-16-transactions/) <file_sep>/code/chapter-8/command_command.rb module BYORedis class CommandCommand < BaseCommand def initialize(_db, _args); end SORTED_COMMANDS = [ CommandCommand, DelCommand, GetCommand, SetCommand, TtlCommand, PttlCommand, TypeCommand, # Lists LRangeCommand, LPushCommand, LPushXCommand, RPushCommand, RPushXCommand, LLenCommand, LPopCommand, BLPopCommand, RPopCommand, BRPopCommand, RPopLPushCommand, BRPopLPushCommand, LTrimCommand, LSetCommand, LRemCommand, LPosCommand, LInsertCommand, LIndexCommand, # Hashes HSetCommand, HGetAllCommand, HDelCommand, HExistsCommand, HGetCommand, HIncrByCommand, HIncrByFloatCommand, HKeysCommand, HLenCommand, HMGetCommand, HSetNXCommand, HStrLenCommand, HValsCommand, ] def call RESPArray.new(SORTED_COMMANDS.map { |command_class| command_class.describe.serialize }) end def self.describe Describe.new('command', -1, [ 'random', 'loading', 'stale' ], 0, 0, 0, [ '@slow', '@connection' ]) end end end <file_sep>/code/chapter-3/server_select_everything.rb require 'socket' require 'timeout' class BasicServer COMMANDS = [ "GET", "SET", ] def initialize @clients = [] @data_store = {} server = TCPServer.new 2000 puts "Server started at: #{ Time.now }" loop do # Selecting blocks, so if there's no client, we don't have to call it, which would # block, we can just keep looping result = IO.select(@clients + [server]) result[0].each do |socket| begin if socket.is_a?(TCPServer) @clients << server.accept elsif socket.is_a?(TCPSocket) client_command_with_args = socket.read_nonblock(1024, exception: false) if client_command_with_args.nil? @clients.delete(socket) elsif client_command_with_args == :wait_readable # There's nothing to read from the client, we don't have to do anything next elsif client_command_with_args.strip.empty? puts "Empty request received from #{ socket }" else response = handle_client_command(client_command_with_args.strip) socket.puts response end else raise "Unknown socket type: #{ socket }" end rescue Errno::ECONNRESET @clients.delete(socket) end end end end private def handle_client_command(client_command_with_args) command_parts = client_command_with_args.split command = command_parts[0] args = command_parts[1..-1] if COMMANDS.include?(command) if command == "GET" if args.length != 1 "(error) ERR wrong number of arguments for '#{ command }' command" else @data_store.fetch(args[0], "(nil)") end elsif command == "SET" if args.length != 2 "(error) ERR wrong number of arguments for '#{ command }' command" else @data_store[args[0]] = args[1] 'OK' end end else formatted_args = args.map { |arg| "`#{ arg }`," }.join(" ") "(error) ERR unknown command `#{ command }`, with args beginning with: #{ formatted_args }" end end end <file_sep>/code/chapter-8/test/test_helper.rb require 'timeout' require 'stringio' require 'logger' ENV['LOG_LEVEL'] = 'FATAL' unless ENV['LOG_LEVEL'] require_relative '../server' $child_process_pid = nil $socket_to_server = nil def restart_server kill_child $child_process_pid = nil start_server $socket_to_server = nil end def start_server if $child_process_pid.nil? if !!ENV['DEBUG'] options = {} else options = { [ :out, :err ] => '/dev/null' } end start_server_script = <<~RUBY begin BYORedis::Server.new rescue Interrupt end RUBY $child_process_pid = Process.spawn('ruby', '-r', './server', '-e', start_server_script, options) end end start_server # Make sure that we stop the server if tests are interrupted with Ctrl-C Signal.trap('INT') do kill_child exit(0) end require 'minitest/autorun' def do_teardown with_server do |socket| socket.write(to_query('FLUSHDB')) read_response(socket) args = BYORedis::Config::DEFAULT.flat_map do |key, value| [ key.to_s, value.to_s ] end socket.write(to_query('CONFIG', 'SET', *args)) read_response(socket) end end class MiniTest::Test def teardown with_server do do_teardown end rescue Errno::EPIPE, IOError => e $socket_to_server&.close $socket_to_server = nil connect_to_server do_teardown p "Exception during teardown: #{ e.class }/ #{ e }" end end def kill_child if $child_process_pid Process.kill('INT', $child_process_pid) begin Timeout.timeout(1) do Process.wait($child_process_pid) end rescue Timeout::Error Process.kill('KILL', $child_process_pid) end end rescue Errno::ESRCH # There was no process ensure if $socket_to_server $socket_to_server.close $socket_to_server = nil end end MiniTest.after_run do kill_child end def connect_to_server return $socket_to_server if !$socket_to_server.nil? && !$socket_to_server.closed? # The server might not be ready to listen to accepting connections by the time we try to # connect from the main thread, in the parent process. Using timeout here guarantees that we # won't wait more than 1s, which should more than enough time for the server to start, and the # retry loop inside, will retry to connect every 10ms until it succeeds connect_with_timeout rescue Timeout::Error # If we failed to connect, there's a chance that it's because the previous test crashed the # server, so retry once p "Restarting server because of timeout when connecting" restart_server connect_with_timeout end def connect_with_timeout Timeout.timeout(1) do loop do begin $socket_to_server = TCPSocket.new 'localhost', 2000 break rescue StandardError => e $socket_to_server = nil sleep 0.2 end end end $socket_to_server end def with_server server_socket = connect_to_server yield server_socket server_socket.close end # The arguments in an array of array of the form # [ # [ [ "COMMAND-PART-I", "COMMAND-PART-II", ... ], "EXPECTED_RESULT" ], # ... # ] def assert_multipart_command_results(multipart_command_result_pairs) with_server do |server_socket| multipart_command_result_pairs.each do |command, expected_result| command.each do |command_part| server_socket.write command_part # Sleep for one milliseconds to give a chance to the server to read # the first partial command sleep 0.001 end response = read_response(server_socket) if response.length < expected_result.length # If the response we got is shorter, maybe we need to give the server a bit more time # to finish processing everything we wrote, so give it another shot sleep 0.1 response += read_response(server_socket) end assert_response(expected_result, response) end end end def assert_command_results(command_result_pairs) with_server do |server_socket| command_result_pairs.each do |command, expected_result| if command.is_a?(String) && command.start_with?('sleep') sleep command.split[1].to_f next end command_string = if command.start_with?('*') command else BYORedis::RESPArray.new(command.split).serialize end server_socket.write command_string response = read_response(server_socket) assert_response(expected_result, response) end end end def assert_response(expected_result, response) assertion_match = expected_result&.match(/(\d+)\+\/-(\d+)/) if expected_result.is_a?(String) if assertion_match response_match = response.match(/\A:(\d+)\r\n\z/) assert response_match[0] assert_in_delta assertion_match[1].to_i, response_match[1].to_i, assertion_match[2].to_i else if expected_result&.is_a?(Array) expected_result = BYORedis::RESPArray.new(expected_result).serialize elsif expected_result&.is_a?(UnorderedArray) expected_result = BYORedis::RESPArray.new(expected_result.array.sort).serialize response = response.then do |r| parts = r.split response_size = parts.shift sorted_parts = parts.each_slice(2).sort_by { |p| p[1] } sorted_parts.flatten.prepend(response_size).map { |p| p << "\r\n" }.join end elsif expected_result&.is_a?(OneOf) expected = expected_result.array.map do |r| if r.start_with?(':') r + "\r\n" else BYORedis::RESPBulkString.new(r).serialize end end assert_includes(expected, response) return elsif expected_result && !%w(+ - : $ *).include?(expected_result[0]) # Convert to a Bulk String unless it is a simple string (starts with a +) # or an error (starts with -) expected_result = BYORedis::RESPBulkString.new(expected_result).serialize end if expected_result && !expected_result.end_with?("\r\n") expected_result += "\r\n" end if expected_result.nil? assert_nil response else assert_equal expected_result, response end end end def read_response(server_socket, read_timeout: 0.2) response = nil loop do select_res = IO.select([ server_socket ], [], [], read_timeout) last_response = server_socket.read_nonblock(1024, exception: false) if last_response == :wait_readable || last_response.nil? || select_res.nil? break else if response.nil? response = last_response else response += last_response end break if response.length < 1024 end end response&.force_encoding('utf-8') rescue Errno::ECONNRESET response&.force_encoding('utf-8') end def to_query(*command_parts) BYORedis::RESPArray.new(command_parts).serialize end UnorderedArray = Struct.new(:array) def unordered(array) UnorderedArray.new(array) end OneOf = Struct.new(:array) def one_of(array) OneOf.new(array) end def test_with_config_values(combinations) # This line goes from a hash like: # { config_1: [ 'config_1_value_1', 'config_2_value_2' ], # config_2: [ 'config_2_value_1', 'config_2_value_2' ] } # to: # [ [ [:config_1, "config_1_value_1"], [:config_1, "config_2_value_2"] ], # [ [:config_2, "config_2_value_1"], [:config_2, "config_2_value_2"] ] ] config_pairs = combinations.map { |key, values| values.map { |value| [ key, value ] } } # This line combines all the config values into an array of all combinations: # [ [ [ :config_1, "config_1_value_1"], [:config_2, "config_2_value_1" ] ], # [ [ :config_1, "config_1_value_1"], [:config_2, "config_2_value_2" ] ], # [ [ :config_1, "config_2_value_2"], [:config_2, "config_2_value_1" ] ], # [ [ :config_1, "config_2_value_2"], [:config_2, "config_2_value_2" ] ] ] all_combinations = config_pairs[0].product(*config_pairs[1..-1]) # And finally, using the Hash.[] method, we create an array of hashes and obtain: # [ { :config_1=>"config_1_value_1", :config_2=>"config_2_value_1" }, # { :config_1=>"config_1_value_1", :config_2=>"config_2_value_2" }, # { :config_1=>"config_2_value_2", :config_2=>"config_2_value_1" }, # { :config_1=>"config_2_value_2", :config_2=>"config_2_value_2" } ] all_combination_hashes = all_combinations.map { |pairs| Hash[pairs] } all_combination_hashes.each do |config_hash| with_server do |socket| socket.write(to_query('FLUSHDB')) resp = read_response(socket) assert_equal("+OK\r\n", resp) config_parts = config_hash.flat_map { |key, value| [ key.to_s, value.to_s ] } socket.write(to_query('CONFIG', 'SET', *config_parts)) resp = read_response(socket) assert_equal("+OK\r\n", resp) end yield end end <file_sep>/content/post/chapter-14-pub-sub-commands.md --- title: "Chapter 14 Adding Pub Sub Commands" date: 2020-10-17T18:18:09-04:00 lastmod: 2020-10-17T18:18:09-04:00 draft: true comment: false keywords: [] summary: "" --- <!--more--> PSUBSCRIBE PUBLISH PUBSUB PUNSUBSCRIBE SUBSCRIBE UNSUBSCRIBE <file_sep>/code/chapter-9/int_set.rb module BYORedis class IntSet INT16_MIN = -2**15 # -32,768 INT16_MAX = 2**15 - 1 # 32,767 INT32_MIN = -2**31 # -2,147,483,648 INT32_MAX = 2**31 - 1 # 2,147,483,647 INT64_MIN = -2**63 # -9,223,372,036,854,775,808 INT64_MAX = 2**63 - 1 # 9,223,372,036,854,775,807 # Each of the constant value represents the number of bytes used to store an integer ENCODING_16_BITS = 2 ENCODING_32_BITS = 4 ENCODING_64_BITS = 8 def initialize @underlying_array = [] @encoding = ENCODING_16_BITS end def empty? @underlying_array.empty? end def each(&block) members.each(&block) end def members size.times.map do |index| get(index) end end def size @underlying_array.size / @encoding end alias cardinality size alias card cardinality def add(member) raise "Member is not an int: #{ member }" unless member.is_a?(Integer) # Ruby's Integer can go over 64 bits, but this class can only store signed 64 bit integers # so we use this to reject out of range integers raise "Out of range integer: #{ member }" if member < INT64_MIN || member > INT64_MAX encoding = encoding_for_member(member) return upgrade_and_add(member) if encoding > @encoding # search always returns a value, either the position of the item or the position where it # should be inserted position = search(member) return false if get(position) == member move_tail(position, position + 1) if position < size set(position, member) true end def include?(member) return false if member.nil? index = search(member) get(index) == member end alias member? include? def pop rand_index = rand(size) value = get(rand_index) @underlying_array.slice!(rand_index * @encoding, @encoding) value end def random_member rand_index = rand(size) get(rand_index) end def remove(member) index = search(member) if get(index) == member @underlying_array.slice!(index * @encoding, @encoding) true else false end end private def set(position, member) @encoding.times do |i| index = (position * @encoding) + i @underlying_array[index] = ((member >> (i * 8)) & 0xff).chr end end def move_tail(from, to) @underlying_array[(to * @encoding)..-1] = @underlying_array[(from * @encoding)..-1] end def search(member) min = 0 max = size - 1 mid = -1 current = -1 # the index is always 0 for an empty array return 0 if empty? if member > get(max) return size elsif member < get(min) return 0 end while max >= min mid = (min + max) >> 1 current = get(mid) if member > current min = mid + 1 elsif member < current max = mid - 1 else break end end if member == current mid else min end end def get(position) get_with_encoding(position, @encoding) end def get_with_encoding(position, encoding) return nil if position >= size bytes = @underlying_array[position * encoding, encoding] # bytes is an array of bytes, in little endian, so with the small bytes first # We could iterate over the array and "assemble" the bytes into in a single integer, # by performing the opposite we did in set, that is with the following # # bytes.lazy.with_index.reduce(0) do |sum, (byte, index)| # sum | (byte << (index * 8)) # end # # But doing do would only work if the final result was positive, if the first bit of the # last byte was a 1, then the number we're re-assembling needs to be a negative number, we # could do so with the following: # # negative = (bytes[-1] >> 7) & 1 == 1 # # And at the end of the method, we could apply the following logic to obtain the value, # get the 1 complement, with `~` and add 1. We also need to apply a mask to make sure that # the 1 complement result stays within the bounds of the current encoding # For instance, with encoding set to 2, the mask would be 0xffff, which is 65,535 # # if negative # mask = (2**(encoding * 8) - 1) # v = -1 * ((~v & mask) + 1) # end # # Anyway, we can use the pack/unpack methods to let Ruby do that for us, calling # bytes.pack('C*') will return a string of bytes, for instance, the number -128 is stored # in the intset as [ 128, 255 ], calling, `.pack('C*')` returns "\x80\xFF". Next up, we # pick the right format, 's' for 16-bit integers, 'l' for 32 and 'q' for 64 and we let # Ruby put together the bytes into the final number. # The result of unpack is an array, but we use unpack1 here, which is a shortcut to # calling unpack() followed by [0] # # What this whole thing tells us is that we could have used `.pack('s').chars` in the # set method, but using >> 8 is more interesting to understand actually what happens! format = case encoding when ENCODING_16_BITS then 's' when ENCODING_32_BITS then 'l' when ENCODING_64_BITS then 'q' end bytes.join.unpack1(format) end def encoding_for_member(member) if member < INT32_MIN || member > INT32_MAX ENCODING_64_BITS elsif member < INT16_MIN || member > INT16_MAX ENCODING_32_BITS else ENCODING_16_BITS end end def upgrade_and_add(member) current_encoding = @encoding current_size = size new_size = current_size + 1 @encoding = encoding_for_member(member) prepend = member < 0 ? 1 : 0 @underlying_array[(new_size * @encoding) - 1] = nil # Allocate a bunch of nils # Upgrade back to front while (current_size -= 1) >= 0 value = get_with_encoding(current_size, current_encoding) # Note the use of the prepend variable to shift all elements one cell to the right in # the case where we need to add the new member as the first element in the array set(current_size + prepend, value) end if prepend == 1 set(0, member) else set(size - 1, member) end true end end end <file_sep>/code/chapter-8/base_command.rb module BYORedis class BaseCommand Describe = Struct.new(:name, :arity, :flags, :first_key_position, :last_key_position, :step_count, :acl_categories) do def serialize [ name, arity, flags.map { |flag| RESPSimpleString.new(flag) }, first_key_position, last_key_position, step_count, acl_categories.map { |category| RESPSimpleString.new(category) }, ] end end def initialize(db, args) @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @db = db @args = args end def execute_command call rescue InvalidArgsLength => e @logger.debug e.message command_name = self.class.describe.name.upcase e.resp_error(command_name) rescue WrongTypeError, RESPSyntaxError, ValidationError => e e.resp_error end def call raise NotImplementedError end end end <file_sep>/code/chapter-6/del_command.rb module BYORedis class DelCommand def initialize(data_store, expires, args) @data_store = data_store @expires = expires @args = args end def call if @args.empty? RESPError.new("ERR wrong number of arguments for 'GET' command") else keys = @args deleted_count = 0 keys.each do |key| entry = @data_store.delete(key) if entry != nil @expires.delete(key) deleted_count += 1 end end RESPInteger.new(deleted_count) end end def self.describe [ 'del', -2, # arity # command flags [ RESPSimpleString.new('write') ], 1, # position of first key in argument list -1, # position of last key in argument list 1, # step count for locating repeating keys # acl categories: https://github.com/antirez/redis/blob/6.0/src/server.c#L161-L166 [ '@keyspace', '@write', '@slow' ].map { |s| RESPSimpleString.new(s) }, ] end end end <file_sep>/code/chapter-8/server.rb require 'socket' require 'logger' require 'strscan' require 'securerandom' LOG_LEVEL = if ENV['DEBUG'] Logger::DEBUG elsif ENV['LOG_LEVEL'] # Will crash for unknown log levels, on purpose Logger.const_get(ENV['LOG_LEVEL'].upcase) else Logger::INFO end RANDOM_BYTES = SecureRandom.bytes(16) require_relative './config' require_relative './db' require_relative './dict' require_relative './utils' require_relative './sorted_array' require_relative './base_command' require_relative './blocked_client_handler' require_relative './resp_types' require_relative './expire_helper' require_relative './config_command' require_relative './flush_db_command' require_relative './del_command' require_relative './get_command' require_relative './set_command' require_relative './ttl_command' require_relative './pttl_command' require_relative './list_commands' require_relative './hash_commands' require_relative './type_command' require_relative './command_command' module BYORedis class Server COMMANDS = Dict.new COMMANDS.set('command', CommandCommand) COMMANDS.set('config', ConfigCommand) COMMANDS.set('del', DelCommand) COMMANDS.set('flushdb', FlushDBCommand) COMMANDS.set('get', GetCommand) COMMANDS.set('set', SetCommand) COMMANDS.set('ttl', TtlCommand) COMMANDS.set('pttl', PttlCommand) COMMANDS.set('lrange', LRangeCommand) COMMANDS.set('lpush', LPushCommand) COMMANDS.set('lpushx', LPushXCommand) COMMANDS.set('rpush', RPushCommand) COMMANDS.set('rpushx', RPushXCommand) COMMANDS.set('llen', LLenCommand) COMMANDS.set('lpop', LPopCommand) COMMANDS.set('blpop', BLPopCommand) COMMANDS.set('rpop', RPopCommand) COMMANDS.set('brpop', BRPopCommand) COMMANDS.set('rpoplpush', RPopLPushCommand) COMMANDS.set('brpoplpush', BRPopLPushCommand) COMMANDS.set('ltrim', LTrimCommand) COMMANDS.set('lset', LSetCommand) COMMANDS.set('lrem', LRemCommand) COMMANDS.set('lpos', LPosCommand) COMMANDS.set('linsert', LInsertCommand) COMMANDS.set('lindex', LIndexCommand) COMMANDS.set('type', TypeCommand) COMMANDS.set('hset', HSetCommand) COMMANDS.set('hgetall', HGetAllCommand) COMMANDS.set('hget', HGetCommand) COMMANDS.set('hdel', HDelCommand) COMMANDS.set('hexists', HExistsCommand) COMMANDS.set('hincrby', HIncrByCommand) COMMANDS.set('hincrbyfloat', HIncrByFloatCommand) COMMANDS.set('hkeys', HKeysCommand) COMMANDS.set('hlen', HLenCommand) COMMANDS.set('hmget', HMGetCommand) COMMANDS.set('hsetnx', HSetNXCommand) COMMANDS.set('hstrlen', HStrLenCommand) COMMANDS.set('hvals', HValsCommand) # ... COMMANDS.resize MAX_EXPIRE_LOOKUPS_PER_CYCLE = 20 DEFAULT_FREQUENCY = 10 # How many times server_cron runs per second HASHTABLE_MIN_FILL = 10 IncompleteCommand = Class.new(StandardError) ProtocolError = Class.new(StandardError) do def serialize RESPError.new(message).serialize end end TimeEvent = Struct.new(:process_at, :block) Client = Struct.new(:socket, :buffer, :blocked_state) do attr_reader :id def initialize(socket) @id = socket.fileno.to_s self.socket = socket self.buffer = '' end end BlockedState = Struct.new(:timeout, :keys, :operation, :target, :client) def initialize @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @clients = Dict.new @db = DB.new @blocked_client_handler = BlockedClientHandler.new(self, @db) @server = TCPServer.new 2000 @time_events = [] @logger.debug "Server started at: #{ Time.now }" add_time_event(Time.now.to_f.truncate + 1) do server_cron end start_event_loop end def disconnect_client(client) @clients.delete(client.id) if client.blocked_state @db.client_timeouts.delete(client.blocked_state) client.blocked_state.keys.each do |key| list = @db.blocking_keys[key] if list list.remove(1, client) @db.blocking_keys.delete(key) if list.empty? end end end client.socket.close end private def add_time_event(process_at, &block) @time_events << TimeEvent.new(process_at, block) end def nearest_time_event nearest = nil @time_events.each do |time_event| if nearest.nil? nearest = time_event elsif time_event.process_at < nearest.process_at nearest = time_event else next end end nearest end def select_timeout if @time_events.any? nearest = nearest_time_event now = (Time.now.to_f * 1000).truncate if nearest.process_at < now 0 else (nearest.process_at - now) / 1000.0 end else 0 end end def client_sockets sockets = [] @clients.each { |_, client| sockets << client.socket } sockets end def start_event_loop loop do handle_blocked_clients_timeout process_unblocked_clients timeout = select_timeout @logger.debug "select with a timeout of #{ timeout }" result = IO.select(client_sockets + [ @server ], [], [], timeout) sockets = result ? result[0] : [] process_poll_events(sockets) process_time_events end end def safe_accept_client @server.accept rescue Errno::ECONNRESET, Errno::EPIPE => e @logger.warn "Error when accepting client: #{ e }" nil end def safe_read(client) client.socket.read_nonblock(1024, exception: false) rescue Errno::ECONNRESET, Errno::EPIPE disconnect_client(client) end def process_poll_events(sockets) sockets.each do |socket| if socket.is_a?(TCPServer) socket = safe_accept_client next unless socket @clients[socket.fileno.to_s] = Client.new(socket) elsif socket.is_a?(TCPSocket) client = @clients[socket.fileno.to_s] client_command_with_args = safe_read(client) if client_command_with_args.nil? disconnect_client(client) elsif client_command_with_args == :wait_readable # There's nothing to read from the client, we don't have to do anything next elsif client_command_with_args.empty? @logger.debug "Empty request received from #{ socket }" else client.buffer += client_command_with_args process_client_buffer(client) end else raise "Unknown socket type: #{ socket }" end end end def process_client_buffer(client) split_commands(client.buffer) do |command_parts| return if client.blocked_state response = handle_client_command(command_parts) if response.is_a?(BlockedState) block_client(client, response) else @logger.debug "Response: #{ response.class } / #{ response.inspect }" serialized_response = response.serialize @logger.debug "Writing: '#{ serialized_response.inspect }'" unless Utils.safe_write(client.socket, serialized_response) disconnect_client(client) end handle_clients_blocked_on_keys end end rescue IncompleteCommand # Not clearing the buffer or anything rescue ProtocolError => e client.socket.write e.serialize disconnect_client(client) end def split_commands(client_buffer) @logger.debug "Client buffer content: '#{ client_buffer.inspect }'" scanner = StringScanner.new(client_buffer.dup) until scanner.eos? if scanner.peek(1) == '*' yield parse_as_resp_array(scanner) else yield parse_as_inline_command(scanner) end client_buffer.slice!(0, scanner.charpos) end end def parse_as_resp_array(scanner) unless scanner.getch == '*' raise 'Unexpectedly attempted to parse a non array as an array' end expected_length = scanner.scan_until(/\r\n/) raise IncompleteCommand if expected_length.nil? expected_length = parse_integer(expected_length, 'invalid multibulk length') command_parts = [] expected_length.times do raise IncompleteCommand if scanner.eos? parsed_value = parse_as_resp_bulk_string(scanner) raise IncompleteCommand if parsed_value.nil? command_parts << parsed_value end command_parts end def parse_as_resp_bulk_string(scanner) type_char = scanner.getch unless type_char == '$' raise ProtocolError, "ERR Protocol error: expected '$', got '#{ type_char }'" end expected_length = scanner.scan_until(/\r\n/) raise IncompleteCommand if expected_length.nil? expected_length = parse_integer(expected_length, 'invalid bulk length') bulk_string = scanner.rest.slice(0, expected_length) raise IncompleteCommand if bulk_string.nil? || bulk_string.length != expected_length scanner.pos += bulk_string.bytesize + 2 bulk_string end def parse_as_inline_command(scanner) command = scanner.scan_until(/(\r\n|\r|\n)+/) raise IncompleteCommand if command.nil? command.split.map(&:strip) end def process_time_events @time_events.delete_if do |time_event| next if time_event.process_at > Time.now.to_f * 1000 return_value = time_event.block.call if return_value.nil? true else time_event.process_at = (Time.now.to_f * 1000).truncate + return_value @logger.debug "Rescheduling time event #{ Time.at(time_event.process_at / 1000.0).to_f }" false end end end def handle_client_command(command_parts) @logger.debug "Received command: #{ command_parts }" command_str = command_parts[0] args = command_parts[1..-1] command_class = COMMANDS[command_str.downcase] if command_class command = command_class.new(@db, args) command.execute_command else formatted_args = args.map { |arg| "`#{ arg }`," }.join(' ') message = "ERR unknown command `#{ command_str }`, with args beginning with: #{ formatted_args }" RESPError.new(message) end end def server_cron start_timestamp = Time.now keys_fetched = 0 @db.expires.each do |key, _| if @db.expires[key] < Time.now.to_f * 1000 @logger.debug "Evicting #{ key }" @db.expires.delete(key) @db.data_store.delete(key) end keys_fetched += 1 if keys_fetched >= MAX_EXPIRE_LOOKUPS_PER_CYCLE break end end end_timestamp = Time.now @logger.debug do format( 'Processed %<number_of_keys>i keys in %<duration>.3f ms', number_of_keys: keys_fetched, duration: (end_timestamp - start_timestamp) * 1000, ) end databases_cron 1000 / DEFAULT_FREQUENCY end def databases_cron @db.data_store.resize if @db.data_store.needs_resize?(min_fill: HASHTABLE_MIN_FILL) @db.expires.resize if @db.expires.needs_resize?(min_fill: HASHTABLE_MIN_FILL) @db.data_store.rehash_milliseconds(1) @db.expires.rehash_milliseconds(1) end def parse_integer(integer_str, error_message) begin value = Integer(integer_str) if value < 0 raise ProtocolError, "ERR Protocol error: #{ error_message }" else value end rescue ArgumentError raise ProtocolError, "ERR Protocol error: #{ error_message }" end end def unblock_client(client) @db.unblocked_clients.right_push client return if client.blocked_state.nil? # Remove this client from the blocking_keys lists client.blocked_state.keys.each do |key2| list = @db.blocking_keys[key2] if list list.remove(1, client) @db.blocking_keys.delete(key2) if list.empty? end end @db.client_timeouts.delete(client.blocked_state) client.blocked_state = nil end def handle_blocked_clients_timeout @db.client_timeouts.delete_if do |blocked_state| client = blocked_state.client if client.blocked_state.nil? @logger.warn "Unexpectedly found a non blocked client in timeouts: #{ client }" true elsif client.blocked_state.timeout < Time.now @logger.debug "Expired timeout: #{ client }" unblock_client(client) unless Utils.safe_write(client.socket, NullArrayInstance.serialize) @logger.warn "Error writing back to #{ client }: #{ e.message }" disconnect_client(client) end true else # Impossible to find more later on since client_timeouts is sorted break end end end def process_unblocked_clients return if @db.unblocked_clients.empty? cursor = @db.unblocked_clients.left_pop while cursor client = cursor.value if @clients.include?(client.id) process_client_buffer(client) else @logger.warn "Unblocked client #{ client } must have disconnected" end cursor = @db.unblocked_clients.left_pop end end def block_client(client, blocked_state) if client.blocked_state @logger.warn "Client was already blocked: #{ blocked_state }" return end blocked_state.client = client # Add the state to the client client.blocked_state = blocked_state if blocked_state.timeout @db.client_timeouts << blocked_state end # Add this client to the list of clients waiting on this key blocked_state.keys.each do |key| client_list = @db.blocking_keys[key] if client_list.nil? client_list = List.new @db.blocking_keys[key] = client_list end client_list.right_push(client) end end def handle_clients_blocked_on_keys return if @db.ready_keys.used == 0 @db.ready_keys.each do |key, _| unblocked_clients = @blocked_client_handler.handle(key) unblocked_clients.each do |client| unblock_client(client) end end @db.ready_keys = Dict.new end end end <file_sep>/code/chapter-9/test/dict_unit_test.rb require_relative './test_helper' require_relative '../dict' describe 'Dict' do describe 'set' do it 'adds a new pair if the key is not already present' do dict = new_dict assert_equal('1', dict['a'] = '1') assert_equal('1', dict['a']) assert_equal(1, dict.used) end it 'overrides the existing value if the key is already present' do dict = new_dict([ 'a', '1' ]) assert_equal('2', dict['a'] = '2') assert_equal('2', dict['a']) assert_equal(1, dict.used) end it 'prevents duplicates even while rehashing' do dict = new_dict([ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ], [ 'd', '4' ], [ 'e', '5' ], [ 'f', '6' ], [ 'g', '7' ], [ 'h', '8' ]) dict['i'] = '9' # Trigger rehashing with a 9th element # Find an element that has not been rehashed not_yet_rehashed_entry = dict.hash_tables[0].table.reject(&:nil?)[-1] # Override that entry, and make sure it does not incorrectly add it to the rehashing table # instead dict[not_yet_rehashed_entry.key] = 'something else' pairs = [] dict.each do |key, value| pairs << [ key, value ] end # We only know at runtime which key we changed, so compute the expected result then expected_pairs = [ [ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ], [ 'd', '4' ], [ 'e', '5' ], [ 'f', '6' ], [ 'g', '7' ], [ 'h', '8' ], [ 'i', '9' ] ] updated_entry = expected_pairs.find { |p| p[0] == not_yet_rehashed_entry.key } updated_entry[1] = 'something else' assert_equal(expected_pairs, pairs.sort) end end describe 'get' do it 'returns nil if the key is not present' do dict = new_dict assert_nil(dict['a']) end it 'returns the value if the key is present' do dict = new_dict([ 'a', '1' ]) dict['b'] = '2' assert_equal('2', dict['b']) end end describe 'delete' do it 'returns nil if the key is not present' do dict = new_dict([ 'a', '1' ]) assert_nil(dict.delete('b')) end it 'removes the key/value pair is the key is present' do dict = new_dict([ 'a', '1' ]) assert_equal('1', dict.delete('a')) assert_nil(dict['a']) assert_equal(0, dict.used) end end describe 'each' do it 'iterates over all elements in the dict' do dict = new_dict([ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ]) pairs = [] dict.each do |key, value| pairs << [ key, value ] end assert_equal([ [ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ] ], pairs.sort) end it 'iterates over all elements in the dict while rehashing' do dict = new_dict([ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ], [ 'd', '4' ]) dict['e'] = '5' pairs = [] dict.each do |key, value| pairs << [ key, value ] end assert_equal([ [ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ], [ 'd', '4' ], [ 'e', '5' ] ], pairs.sort) end end describe 'random_entry' do it 'returns a random entry' do dict = new_dict([ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ]) random_entry = dict.send(:random_entry) assert([ 'a', 'b', 'c' ].include?(random_entry.key)) end it 'returns a random entry even while rehashing' do dict = new_dict([ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ], [ 'd', '4' ], [ 'e', '5' ], [ 'f', '6' ], [ 'g', '7' ], [ 'h', '8' ]) dict['i'] = '9' # Trigger rehashing with a 9th element dict.rehash_milliseconds(100) distribution = Hash.new { |h, k| h[k] = 0 } 10_000.times do random_entry = dict.send(:random_entry) distribution[random_entry.key] += 1 end distribution.each do |key, count| assert([ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' ].include?(key)) # 10,000 / 9 = 1,111.11 # The delta is huge, because the default algorithm doesn't take into account that # different buckets have different sizes and the distribution is all over the place # Still, it test that all keys are returned at least some non zero times assert_in_delta(count, 1111, 1000) end end end describe 'get_some_entries' do it 'returns up to count random keys' do dict = new_dict([ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ], [ 'd', '4' ], [ 'e', '5' ], [ 'f', '6' ], [ 'g', '7' ], [ 'h', '8' ]) entries = dict.send(:get_some_entries, 2) assert_equal(2, entries.size) entries = dict.send(:get_some_entries, 20) assert_equal(8, entries.size) end end describe 'fair_random_entry' do it 'returns a random entry' do dict = new_dict([ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ]) random_entry = dict.fair_random_entry assert([ 'a', 'b', 'c' ].include?(random_entry.key)) end it 'returns a random entry even while rehashing' do dict = new_dict([ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ], [ 'd', '4' ], [ 'e', '5' ], [ 'f', '6' ], [ 'g', '7' ], [ 'h', '8' ]) dict['i'] = '9' # Trigger rehashing with a 9th element dict.rehash_milliseconds(100) distribution = Hash.new { |h, k| h[k] = 0 } 10_000.times do random_entry = dict.fair_random_entry distribution[random_entry.key] += 1 end distribution.each do |key, count| assert([ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' ].include?(key)) # 10,000 / 9 = 1,111.11 # 100 is an arbitrary that seems to cover 90+% of the outcomes based on a non scientific # experiment I ran locally, just rant this "many" times (about 42 times) assert_in_delta(count, 1111, 100) end end end def new_dict(*pairs) dict = BYORedis::Dict.new pairs.each do |pair| dict[pair[0]] = pair[1] end dict end end <file_sep>/code/chapter-2/test.rb require 'minitest/autorun' require 'timeout' require 'stringio' require './server' describe 'BasicServer' do def connect_to_server socket = nil # The server might not be ready to listen to accepting connections by the time we try to connect from the main # thread, in the parent process. Using timeout here guarantees that we won't wait more than 1s, which should # more than enough time for the server to start, and the retry loop inside, will retry to connect every 10ms # until it succeeds Timeout::timeout(1) do loop do begin socket = TCPSocket.new 'localhost', 2000 break rescue sleep 0.01 end end end socket end def with_server child = Process.fork do # We're effectively silencing the server with these two lines # stderr would have logged something when it receives SIGINT, with a complete stacktrace $stderr = StringIO.new # stdout would haev logged the "Server started ..." & "New client connected ..." lines $stdout = StringIO.new BasicServer.new end yield ensure if child Process.kill('INT', child) Process.wait(child) end end def assert_command_results(command_result_pairs) with_server do command_result_pairs.each do |command, expected_result| begin socket = connect_to_server socket.puts command response = socket.gets assert_equal response, expected_result + "\n" ensure socket.close if socket end end end end describe 'when initialized' do it 'listens on port 2000' do with_server do # lsof stands for "list open files", see for more info https://stackoverflow.com/a/4421674 lsof_result = `lsof -nP -i4TCP:2000 | grep LISTEN` assert_match "ruby", lsof_result end end end describe 'GET' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'GET', '(error) ERR wrong number of arguments for \'GET\' command' ], ] end it 'returns (nil) for unknown keys' do assert_command_results [ [ 'GET 1', '(nil)' ], ] end it 'returns the value previously set by SET' do assert_command_results [ [ 'SET 1 2', 'OK' ], [ 'GET 1', '2'] ] end end describe 'SET' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SET', '(error) ERR wrong number of arguments for \'SET\' command' ], ] end it 'returns OK' do assert_command_results [ [ 'SET 1 3', 'OK' ], ] end end describe 'Unknown commands' do it 'returns an error message' do assert_command_results [ [ 'NOT A COMMAND', '(error) ERR unknown command `NOT`, with args beginning with: `A`, `COMMAND`,' ], ] end end end <file_sep>/code/chapter-10/hash_table.rb module BYORedis class HashTable attr_reader :table, :size, :sizemask attr_accessor :used def initialize(size) @table = size == 0 ? nil : Array.new(size) @size = size @sizemask = size == 0 ? 0 : size - 1 @used = 0 end def empty? @size == 0 end def each(&block) return unless @table @table.each(&block) end end end <file_sep>/code/chapter-10/type_command.rb module BYORedis class TypeCommand < BaseCommand def call Utils.assert_args_length(1, @args) key = @args[0] ExpireHelper.check_if_expired(@db, key) value = @db.data_store[key] type = case value when nil then 'none' when String then 'string' when List then 'list' when RedisHash then 'hash' when RedisSet then 'set' when RedisSortedSet then 'zset' else raise "Unknown type for #{ value }" end RESPSimpleString.new(type) end def self.describe Describe.new('type', 2, [ 'readonly', 'fast' ], 1, 1, 1, [ '@keyspace', '@read', '@fast' ]) end end end <file_sep>/code/chapter-4/test.rb require 'minitest/autorun' require 'timeout' require 'stringio' require './server' describe 'RedisServer' do def connect_to_server socket = nil # The server might not be ready to listen to accepting connections by the time we try to connect from the main # thread, in the parent process. Using timeout here guarantees that we won't wait more than 1s, which should # more than enough time for the server to start, and the retry loop inside, will retry to connect every 10ms # until it succeeds Timeout::timeout(1) do loop do begin socket = TCPSocket.new 'localhost', 2000 break rescue sleep 0.01 end end end socket end def with_server child = Process.fork do unless !!ENV['DEBUG'] # We're effectively silencing the server with these two lines # stderr would have logged something when it receives SIGINT, with a complete stacktrace $stderr = StringIO.new # stdout would have logged the "Server started ..." & "New client connected ..." lines $stdout = StringIO.new end begin RedisServer.new rescue Interrupt => e # Expected code path given we call kill with 'INT' below end end yield ensure if child Process.kill('INT', child) Process.wait(child) end end def assert_command_results(command_result_pairs) with_server do command_result_pairs.each do |command, expected_result| if command.start_with?('sleep') sleep command.split[1].to_f next end begin socket = connect_to_server socket.puts command response = socket.gets # Matches "2000+\-10", aka 2000 plus or minus 10 regexp_match = expected_result.match /(\d+)\+\/-(\d+)/ if regexp_match # The result is a range assert_in_delta regexp_match[1].to_i, response.to_i, regexp_match[2].to_i else assert_equal expected_result + "\n", response end ensure socket.close if socket end end end end describe 'when initialized' do it 'listens on port 2000' do with_server do # lsof stands for "list open files", see for more info https://stackoverflow.com/a/4421674 lsof_result = `lsof -nP -i4TCP:2000 | grep LISTEN` assert_match "ruby", lsof_result end end end describe 'GET' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'GET', '(error) ERR wrong number of arguments for \'GET\' command' ], ] end it 'returns (nil) for unknown keys' do assert_command_results [ [ 'GET 1', '(nil)' ], ] end it 'returns the value previously set by SET' do assert_command_results [ [ 'SET 1 2', 'OK' ], [ 'GET 1', '2'] ] end end describe 'TTL' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'TTL', '(error) ERR wrong number of arguments for \'TTL\' command' ], ] end it 'returns the TTL for a key with a TTL' do assert_command_results [ [ 'SET key value EX 2', 'OK'], [ 'TTL key', '2' ], [ 'sleep 0.5' ], [ 'TTL key', '1' ], ] end it 'returns -1 for a key without a TTL' do assert_command_results [ [ 'SET key value', 'OK' ], [ 'TTL key', '-1' ], ] end it 'returns -2 if the key does not exist' do assert_command_results [ [ 'TTL key', '-2' ], ] end end describe 'PTTL' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'PTTL', '(error) ERR wrong number of arguments for \'PTTL\' command' ], ] end it 'returns the TTL in ms for a key with a TTL' do assert_command_results [ [ 'SET key value EX 2', 'OK'], [ 'PTTL key', '2000+/-20' ], # Initial 2000ms +/- 20ms [ 'sleep 0.5' ], [ 'PTTL key', '1500+/-20' ], # Initial 2000ms, minus ~500ms of sleep, +/- 20ms ] end it 'returns -1 for a key without a TTL' do assert_command_results [ [ 'SET key value', 'OK' ], [ 'PTTL key', '-1' ], ] end it 'returns -2 if the key does not exist' do assert_command_results [ [ 'PTTL key', '-2' ], ] end end describe 'SET' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SET', '(error) ERR wrong number of arguments for \'SET\' command' ], ] end it 'returns OK' do assert_command_results [ [ 'SET 1 3', 'OK' ], ] end it 'handles the EX option with a valid argument' do assert_command_results [ [ 'SET 1 3 EX 1', 'OK' ], [ 'GET 1', '3' ], [ 'sleep 1' ], [ 'GET 1', '(nil)' ], ] end it 'rejects the EX option with an invalid argument' do assert_command_results [ [ 'SET 1 3 EX foo', '(error) ERR value is not an integer or out of range'] ] end it 'handles the PX option with a valid argument' do assert_command_results [ [ 'SET 1 3 PX 100', 'OK' ], [ 'GET 1', '3' ], [ 'sleep 0.1' ], [ 'GET 1', '(nil)' ], ] end it 'rejects the PX option with an invalid argument' do assert_command_results [ [ 'SET 1 3 PX foo', '(error) ERR value is not an integer or out of range'] ] end it 'handles the NX option' do assert_command_results [ [ 'SET 1 2 NX', 'OK' ], [ 'SET 1 2 NX', '(nil)' ], ] end it 'handles the XX option' do assert_command_results [ [ 'SET 1 2 XX', '(nil)'], [ 'SET 1 2', 'OK'], [ 'SET 1 2 XX', 'OK'], ] end it 'removes ttl without KEEPTTL' do assert_command_results [ [ 'SET 1 3 PX 100', 'OK' ], [ 'SET 1 2', 'OK' ], [ 'sleep 0.1' ], [ 'GET 1', '2' ], ] end it 'handles the KEEPTTL option' do assert_command_results [ [ 'SET 1 3 PX 100', 'OK' ], [ 'SET 1 2 KEEPTTL', 'OK' ], [ 'sleep 0.1' ], [ 'GET 1', '(nil)' ], ] end it 'accepts multiple options' do assert_command_results [ [ 'SET 1 3 NX EX 1', 'OK' ], [ 'GET 1', '3' ], [ 'SET 1 3 XX KEEPTTL', 'OK' ], ] end it 'rejects with more than one expire related option' do assert_command_results [ [ 'SET 1 3 PX 1 EX 2', '(error) ERR syntax error'], [ 'SET 1 3 PX 1 KEEPTTL', '(error) ERR syntax error'], [ 'SET 1 3 KEEPTTL EX 2', '(error) ERR syntax error'], ] end it 'rejects with both XX & NX' do assert_command_results [ [ 'SET 1 3 NX XX', '(error) ERR syntax error'], ] end end describe 'Unknown commands' do it 'returns an error message' do assert_command_results [ [ 'NOT A COMMAND', '(error) ERR unknown command `NOT`, with args beginning with: `A`, `COMMAND`,' ], ] end end end <file_sep>/code/chapter-6/siphash.rb # Credit to https://github.com/emboss/siphash-ruby/blob/master/lib/siphash.rb class SipHash # Ruby's Integer class allows numbers by going passed the max value of a 64 bit integer, # by encoding the value across multiple 64-bit integers under the hood. In order to make # sure that the values we deal with stay within the 64-bit range, we use the following # constant as the right operand of an AND bitwise operation MASK_64 = 0xffffffffffffffff def self.digest(key, msg, compress_rounds: 1, finalize_rounds: 2) new(key, msg, compress_rounds, finalize_rounds).digest end def initialize(key, msg, compress_rounds, finalize_rounds) @msg = msg @compress_rounds = compress_rounds @finalize_rounds = finalize_rounds # These are the four 64-bit integers of internal state. The initial values are based on the # arbitrary string: "somepseudorandomlygeneratedbytes" # "somepseu".split('').map(&:ord).map { |b| b.to_s(16) }.join # => "736f6d6570736575" # The 64-bit value is 8317987319222330741, its binary represenation is: # 0111 0011 0110 1111 0110 1101 0110 0101 0111 0000 0111 0011 0110 0101 0111 0101 # Which we can obtain with # "736f6d6570736575".scan(/../).map { |h| h.hex } # => [115, 111, 109, 101, 112, 115, 101, 117] # [115, 111, 109, 101, 112, 115, 101, 117].pack('c8') # => "somepseu" # "somepseu".unpack('Q>') # => 8317987319222330741 # '%064b' % 8317987319222330741 # => # 0111 0011 0110 1111 0110 1101 0110 0101 0111 0000 0111 0011 0110 0101 0111 0101 # # Note that we used 'Q>' which tells unpack to assume big-endianness. Using the default of # Q< would have returned the same 8 bytes but in the opposite order, from right to left: # "somepseu".unpack('Q<') # => 8459294401660546931 # '%064b' % 8459294401660546931 # => # 0111 0101 0110 0101 0111 0011 0111 0000 0110 0101 0110 1101 0110 1111 0111 0011 # These are the same bytes but in different order, the character s is the following 8 bits: # ('%08b' % 's'.ord).scan(/..../).join(' ') # => "0111 0011" # And the character o is: # ('%08b' % 'o'.ord).scan(/..../).join(' ') # => "0110 1111" # # We can see that in the big endian version, these two bytes are on the left side, and # they're on the right side with the little endian version # # "dorandom".split('').map(&:ord).map { |b| b.to_s(16) }.join # => "646f72616e646f6d" # "lygenera".split('').map(&:ord).map { |b| b.to_s(16) }.join # => "6c7967656e657261" # "tedbytes".split('').map(&:ord).map { |b| b.to_s(16) }.join # => "7465646279746573" @v0 = 0x736f6d6570736575 @v1 = 0x646f72616e646f6d @v2 = 0x6c7967656e657261 @v3 = 0x7465646279746573 # The key argument is a 16 byte string, which we want to unpack to two 64-bit integers. # A byte contains 8 bits, so one 64-bit integer is composed of 8 bytes, and one 16 byte # string can be unpacked to two 64-bit integers. # The first line grabs the first 8 bytes with the slice method, and calls unpack with the # Q< argument. Q means that Ruby will attempt to unpack as a long, and < is the explicit # way of telling it to unpack it as little endian, which is the default on many modern CPUs k0 = key.slice(0, 8).unpack('Q<')[0] # This line does the same thing with the last 8 bytes of the key k1 = key.slice(8, 8).unpack('Q<')[0] # The ^ Ruby operator is the XOR bitwise operation, a ^= b is equivalent to a = a ^ b # These four lines initialize the four 64-bit integers of internal state with the two # parts of the secret, k0 and k1 @v0 ^= k0 @v1 ^= k1 @v2 ^= k0 @v3 ^= k1 end def digest iter = @msg.size / 8 # Compression step iter.times do |i| m = @msg.slice(i * 8, 8).unpack('Q<')[0] compress(m) end # Compression of the last characters m = last_block(iter) compress(m) # Finalization step finalize # Digest result @v0 ^ @v1 ^ @v2 ^ @v3 end private # This function might look a little bit complicated at first, it implements this section of # the compression part of paper, 2.2: # where m w-1 includes the last 0 through 7 bytes of m followed by null bytes and endingwith a # byte encoding the positive integer b mod 256 def last_block(iter) # We initialize last as a 64-bit integer where the leftmost byte, the 8 bits to the left are # set to the length of the input. 8 bits can only encode a value up to 255, so if the length # is more than 255, the extra bites are discarded, for a length of 11, last would look like # 0000 1011 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 000 00000 # 11 is encoded as 1011 as binary, calling << 56 on it pushes it 56 bits to the left last = (@msg.size << 56) & MASK_64 left = @msg.size % 8 off = iter * 8 # At this point, we've applied the compress step to all the 8 byte chunks in the input # string, but if the length was not a multiple of 8, there might be between 1 & 7 more bytes # we have not compressed yet. # For instance, if the string was 'hello world', the length is 11. The digest method would # have computed an iter value of 1, because 11 / 8 => 1, and called compress once, with the # first 8 bytes, obtained with the slice method, 'hello world'.slice(0, 8) => 'hello wo' # We still need to compress the last 3 bytes, 'rld' # In this example, left will be 3, and off 8 # Note that this case/when statement is written to optimize for readability, there are ways # to express the same instructions with less code case left when 7 last |= @msg[off + 6].ord << 48 last |= @msg[off + 5].ord << 40 last |= @msg[off + 4].ord << 32 last |= @msg[off + 3].ord << 24 last |= @msg[off + 2].ord << 16 last |= @msg[off + 1].ord << 8 last |= @msg[off].ord when 6 last |= @msg[off + 5].ord << 40 last |= @msg[off + 4].ord << 32 last |= @msg[off + 3].ord << 24 last |= @msg[off + 2].ord << 16 last |= @msg[off + 1].ord << 8 last |= @msg[off].ord when 5 last |= @msg[off + 4].ord << 32 last |= @msg[off + 3].ord << 24 last |= @msg[off + 2].ord << 16 last |= @msg[off + 1].ord << 8 last |= @msg[off].ord when 4 last |= @msg[off + 3].ord << 24 last |= @msg[off + 2].ord << 16 last |= @msg[off + 1].ord << 8 last |= @msg[off].ord when 3 # In the example documented above, this is the branch of the case/when we would end up in. # last is initially set to: # 0000 1011 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 000 00000 # @msg[off + 2] is the character d, calling ord returns its integer value, 100. We shift # it 16 bits to the left, effectively inserting as the 6th byte starting from the left, or # third from the right: # 0000 1011 0000 0000 0000 0000 0000 0000 0000 0000 0110 0100 0000 0000 0000 0000 last |= @msg[off + 2].ord << 16 # @msg[off + 1]is the character l, ord returns 108, and we insert it as the 7th byte from # the left, or second from the right: # 0000 1011 0000 0000 0000 0000 0000 0000 0000 0000 0110 0100 0110 1100 0000 0000 last |= @msg[off + 1].ord << 8 # Finally, @msg[off] is the character r, with the ord value 100, and we insert it as the # byte from the left, or first from the right: # 0000 1011 0000 0000 0000 0000 0000 0000 0000 0000 0110 0100 0110 1100 0111 0010 last |= @msg[off].ord when 2 last |= @msg[off + 1].ord << 8 last |= @msg[off].ord when 1 last |= @msg[off].ord when 0 last else raise "Something unexpected happened with the r value: #{ r }, should be between 0 & 7" end # Last is now a 64 bit integer containing the length of the input and the last bytes, if any: last end # rotl64 is the left rotation, also called circular shift: # https://en.wikipedia.org/wiki/Circular_shift def rotl64(num, shift) ((num << shift) & MASK_64) | (num >> (64 - shift)) end # This is the main step of the siphash algorithm. A big difference with the C implementation # in the Redis codebase is the use of & MASK_64. As explained above, it is used to apply an # upper bounds to the results as Ruby would allow them to go past the max value of 64-bit # integer: 2^64 - 1 def sip_round @v0 = (@v0 + @v1) & MASK_64 @v2 = (@v2 + @v3) & MASK_64 @v1 = rotl64(@v1, 13) @v3 = rotl64(@v3, 16) @v1 ^= @v0 @v3 ^= @v2 @v0 = rotl64(@v0, 32) @v2 = (@v2 + @v1) & MASK_64 @v0 = (@v0 + @v3) & MASK_64 @v1 = rotl64(@v1, 17) @v3 = rotl64(@v3, 21) @v1 ^= @v2 @v3 ^= @v0 @v2 = rotl64(@v2, 32) end def compress(m) @v3 ^= m @compress_rounds.times { sip_round } @v0 ^= m end def finalize @v2 ^= 0xff @finalize_rounds.times { sip_round } end end <file_sep>/code/chapter-6/dumb_map.rb def add(map, key, value) map.each do |pair| pair_key = pair[0] # Override the value if the key is already present if key == pair_key pair[1] = value return pair end end pair = [key, value] map << pair pair end def lookup(map, key) map.each do |pair_key, pair_value| return pair_value if key == pair_key end return end map = [] add(map, "key-1", "value-1") # => ["key-1", "value-1"] add(map, "key-2", "value-2") # => ["key-2", "value-2"] p add(map, "key-2", "value-3") # => ["key-2", "value-3"] p map lookup(map, "key-1") # => "value-1" lookup(map, "key-2") # => "value-2" lookup(map, "key-3") # => nil <file_sep>/code/chapter-10/sorted_set_commands.rb require_relative './redis_sorted_set' module BYORedis module SortedSetUtils def self.generic_zpop(db, args) Utils.assert_args_length_greater_than(0, args) key = args.shift count = args.shift raise RESPSyntaxError unless args.empty? count = if count.nil? 1 else Utils.validate_integer(count) end sorted_set = db.lookup_sorted_set(key) popped = [] if sorted_set popped = db.generic_pop(key, sorted_set) do yield sorted_set, count end end RESPArray.new(popped) end def self.generic_bzpop(db, args, operation) Utils.assert_args_length_greater_than(1, args) timeout = Utils.validate_timeout(args.pop) args.each do |set_name| sorted_set = db.lookup_sorted_set(set_name) next if sorted_set.nil? popped = db.generic_pop(set_name, sorted_set) do yield sorted_set end return RESPArray.new([ set_name ] + popped) end Server::BlockedState.new( BlockedClientHandler.timeout_timestamp_or_nil(timeout), args, operation) end def self.intersection(db, args) set_operation(db, args) do |sets_with_weight, aggregate| RedisSortedSet.intersection(sets_with_weight, aggregate: aggregate) end end def self.union(db, args) set_operation(db, args) do |sets_with_weight, aggregate| RedisSortedSet.union(sets_with_weight, aggregate: aggregate) end end def self.set_operation(db, args) options = { aggregate: :sum, withscores: false } sets = SortedSetUtils.validate_number_of_sets(db, args) options.merge!(SortedSetUtils.parse_union_or_inter_options(args, sets.size)) sets_with_weight = sets.zip(options[:weights]) new_set = yield sets_with_weight, options[:aggregate] return new_set, options[:withscores] end def self.set_operation_command(args) Utils.assert_args_length_greater_than(1, args) set_result, withscores = yield SortedSetRankSerializer.new( set_result, RedisSortedSet::GenericRangeSpec.rank_range_spec(0, -1, set_result.cardinality), withscores: withscores, ) end def self.set_operation_store_command(db, args) Utils.assert_args_length_greater_than(2, args) destination_key = args.shift result_set, _ = yield if result_set.empty? db.data_store.delete(destination_key) else db.data_store[destination_key] = result_set end RESPInteger.new(result_set.cardinality) end def self.parse_union_or_inter_options(args, number_of_sets) options = { weights: Array.new(number_of_sets, 1) } while arg = args.shift case arg.downcase when 'weights' options[:weights] = validate_weights(number_of_sets, args) when 'aggregate' aggregate_mode = args.shift case aggregate_mode&.downcase when 'min' then options[:aggregate] = :min when 'max' then options[:aggregate] = :max when 'sum' then options[:aggregate] = :sum else raise RESPSyntaxError end when 'withscores' then options[:withscores] = true else raise RESPSyntaxError end end options end def self.validate_number_of_sets(db, args) number_of_sets = Utils.validate_integer(args.shift) if number_of_sets <= 0 raise ValidationError, 'ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE' else number_of_sets.times.map do set_key = args.shift raise RESPSyntaxError if set_key.nil? db.lookup_sorted_set_or_set(set_key) end end end def self.validate_weights(number_of_sets, args) number_of_sets.times.map do weight = args.shift raise RESPSyntaxError if weight.nil? Utils.validate_float(weight, 'ERR weight value is not a float') end end def self.parse_limit_option(args, options) offset = args.shift count = args.shift raise RESPSyntaxError if offset.nil? || count.nil? offset = Utils.validate_integer(offset) count = Utils.validate_integer(count) options[:offset] = offset options[:count] = count end def self.generic_range_by_score(db, args, reverse: false) # A negative count means "all of them" options = { offset: 0, count: -1, withscores: false } Utils.assert_args_length_greater_than(2, args) key = args.shift if reverse max = args.shift min = args.shift else min = args.shift max = args.shift end range_spec = Utils.validate_score_range_spec(min, max) parse_range_by_score_options(args, options) unless args.empty? sorted_set = db.lookup_sorted_set(key) if options[:offset] < 0 EmptyArrayInstance elsif sorted_set options[:reverse] = reverse SortedSetSerializerBy.new(sorted_set, range_spec, **options, &:score) else EmptyArrayInstance end end def self.parse_range_by_score_options(args, options) while arg = args.shift case arg.downcase when 'withscores' then options[:withscores] = true when 'limit' then SortedSetUtils.parse_limit_option(args, options) else raise RESPSyntaxError end end end def self.generic_range_by_lex(db, args, reverse: false) # A negative count means "all of them" options = { offset: 0, count: -1 } Utils.assert_args_length_greater_than(2, args) key = args.shift if reverse max = args.shift min = args.shift else min = args.shift max = args.shift end range_spec = Utils.validate_lex_range_spec(min, max) parse_range_by_lex_options(args, options) unless args.empty? sorted_set = db.lookup_sorted_set(key) if options[:offset] < 0 EmptyArrayInstance elsif sorted_set options[:withscores] = false options[:reverse] = reverse SortedSetSerializerBy.new(sorted_set, range_spec, **options, &:member) else EmptyArrayInstance end end def self.parse_range_by_lex_options(args, options) raise RESPSyntaxError unless args.length == 3 if args.shift.downcase == 'limit' SortedSetUtils.parse_limit_option(args, options) else raise RESPSyntaxError end end def self.reverse_range_index(index, max) if index >= 0 max - index elsif index < 0 max - (index + max + 1) end end def self.generic_range(db, args, reverse: false) Utils.assert_args_length_greater_than(2, args) start = Utils.validate_integer(args[1]) stop = Utils.validate_integer(args[2]) raise RESPSyntaxError if args.length > 4 if args[3] if args[3].downcase == 'withscores' withscores = true else raise RESPSyntaxError end end sorted_set = db.lookup_sorted_set(args[0]) if reverse tmp = reverse_range_index(start, sorted_set.cardinality - 1) start = reverse_range_index(stop, sorted_set.cardinality - 1) stop = tmp end if sorted_set range_spec = RedisSortedSet::GenericRangeSpec.rank_range_spec(start, stop, sorted_set.cardinality) SortedSetRankSerializer.new( sorted_set, range_spec, withscores: withscores, reverse: reverse, ) else EmptyArrayInstance end end def self.generic_count(db, args) Utils.assert_args_length(3, args) key = args[0] min = args[1] max = args[2] sorted_set = db.lookup_sorted_set(key) count = yield(sorted_set, min, max) || 0 RESPInteger.new(count) end end class ZAddCommand < BaseCommand def call @options = { presence: nil, ch: false, incr: false, } Utils.assert_args_length_greater_than(1, @args) key = @args.shift parse_options raise RESPSyntaxError unless @args.length.even? if @options[:incr] && @args.length > 2 raise ValidationError, 'ERR INCR option supports a single increment-element pair' end pairs = @args.each_slice(2).map do |pair| score = Utils.validate_float(pair[0], 'ERR value is not a valid float') member = pair[1] [ score, member ] end sorted_set = @db.lookup_sorted_set_for_write(key) return_count = 0 pairs.each do |pair| sorted_set_add_result = sorted_set.add(pair[0], pair[1], options: @options) if @options[:incr] if sorted_set_add_result return_count = Utils.float_to_string(sorted_set_add_result) else return_count = nil end elsif sorted_set_add_result return_count += 1 end end RESPSerializer.serialize(return_count) rescue FloatNaN RESPError.new('ERR resulting score is not a number (NaN)') end def self.describe Describe.new('zadd', -4, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@sortedset', '@fast' ]) end private def parse_options @options = {} loop do # We peek at the first arg to see if it is an option arg = @args[0] case arg.downcase when 'nx', 'xx' then set_presence_option(arg.downcase.to_sym) when 'ch' then @options[:ch] = true when 'incr' then @options[:incr] = true else # We found none of the known options, so let's stop here break end # Since we didn't break, we consume the head of @args @args.shift end end def set_presence_option(option_value) if @options[:presence] && @options[:presence] != option_value raise ValidationError, 'ERR XX and NX options at the same time are not compatible' else @options[:presence] = option_value end end end class ZCardCommand < BaseCommand def call Utils.assert_args_length(1, @args) sorted_set = @db.lookup_sorted_set(@args[0]) cardinality = sorted_set&.cardinality || 0 RESPInteger.new(cardinality) end def self.describe Describe.new('zcard', 2, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@sortedset', '@fast' ]) end end class ZRangeCommand < BaseCommand def call SortedSetUtils.generic_range(@db, @args) end def self.describe Describe.new('zrange', -4, [ 'readonly' ], 1, 1, 1, [ '@read', '@sortedset', '@slow' ]) end end class ZRangeByLexCommand < BaseCommand def call SortedSetUtils.generic_range_by_lex(@db, @args, reverse: false) end def self.describe Describe.new('zrangebylex', -4, [ 'readonly' ], 1, 1, 1, [ '@read', '@sortedset', '@slow' ]) end end class ZRangeByScoreCommand < BaseCommand def call SortedSetUtils.generic_range_by_score(@db, @args, reverse: false) end def self.describe Describe.new('zrangebyscore', -4, [ 'readonly' ], 1, 1, 1, [ '@read', '@sortedset', '@slow' ]) end end class ZInterCommand < BaseCommand def call SortedSetUtils.set_operation_command(@args) do SortedSetUtils.intersection(@db, @args) end end def self.describe Describe.new('zinter', -3, [ 'readonly', 'movablekeys' ], 0, 0, 0, [ '@read', '@sortedset', '@slow' ]) end end class ZInterStoreCommand < BaseCommand def call SortedSetUtils.set_operation_store_command(@db, @args) do SortedSetUtils.intersection(@db, @args) end end def self.describe Describe.new('zinterstore', -4, [ 'write', 'denyoom', 'movablekeys' ], 0, 0, 0, [ '@write', '@sortedset', '@slow' ]) end end class ZUnionCommand < BaseCommand def call SortedSetUtils.set_operation_command(@args) do SortedSetUtils.union(@db, @args) end end def self.describe Describe.new('zunion', -3, [ 'readonly', 'movablekeys' ], 0, 0, 0, [ '@read', '@sortedset', '@slow' ]) end end class ZUnionStoreCommand < BaseCommand def call SortedSetUtils.set_operation_store_command(@db, @args) do SortedSetUtils.union(@db, @args) end end def self.describe Describe.new('zunionstore', -4, [ 'write', 'denyoom', 'movablekeys' ], 0, 0, 0, [ '@write', '@sortedset', '@slow' ]) end end class ZRankCommand < BaseCommand def call Utils.assert_args_length(2, @args) sorted_set = @db.lookup_sorted_set(@args[0]) if sorted_set RESPSerializer.serialize(sorted_set.rank(@args[1])) else NullBulkStringInstance end end def self.describe Describe.new('zrank', 3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@sortedset', '@fast' ]) end end class ZScoreCommand < BaseCommand def call Utils.assert_args_length(2, @args) sorted_set = @db.lookup_sorted_set(@args[0]) if sorted_set RESPSerializer.serialize(sorted_set.score(@args[1])) else NullBulkStringInstance end end def self.describe Describe.new('zscore', 3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@sortedset', '@fast' ]) end end class ZMScoreCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) sorted_set = @db.lookup_sorted_set(@args[0]) scores = @args[1..-1].map do |member| sorted_set.score(member) if sorted_set end RESPArray.new(scores) end def self.describe Describe.new('zmscore', -3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@sortedset', '@fast' ]) end end class ZRemCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) sorted_set = @db.lookup_sorted_set(@args.shift) removed_count = 0 if sorted_set @args.each do |member| removed_count += 1 if sorted_set.remove(member) end end RESPInteger.new(removed_count) end def self.describe Describe.new('zrem', -3, [ 'write', 'fast' ], 1, 1, 1, [ '@write', '@sortedset', '@fast' ]) end end class ZRemRangeByLexCommand < BaseCommand def call Utils.assert_args_length(3, @args) range_spec = Utils.validate_lex_range_spec(@args[1], @args[2]) sorted_set = @db.lookup_sorted_set(@args[0]) removed_count = 0 if sorted_set removed_count = sorted_set.remove_lex_range(range_spec) end RESPInteger.new(removed_count) end def self.describe Describe.new('zremrangebylex', 4, [ 'write' ], 1, 1, 1, [ '@write', '@sortedset', '@slow' ]) end end class ZRemRangeByRankCommand < BaseCommand def call Utils.assert_args_length(3, @args) start = Utils.validate_integer(@args[1]) stop = Utils.validate_integer(@args[2]) sorted_set = @db.lookup_sorted_set(@args[0]) removed_count = 0 if sorted_set range_spec = RedisSortedSet::GenericRangeSpec.rank_range_spec(start, stop, sorted_set.cardinality) removed_count = sorted_set.remove_rank_range(range_spec) end RESPInteger.new(removed_count) end def self.describe Describe.new('zremrangebyrank', 4, [ 'write' ], 1, 1, 1, [ '@write', '@sortedset', '@slow' ]) end end class ZRemRangeByScoreCommand < BaseCommand def call Utils.assert_args_length(3, @args) range_spec = Utils.validate_score_range_spec(@args[1], @args[2]) sorted_set = @db.lookup_sorted_set(@args[0]) removed_count = 0 removed_count = sorted_set.remove_score_range(range_spec) if sorted_set RESPInteger.new(removed_count) end def self.describe Describe.new('zremrangebyscore', 4, [ 'write' ], 1, 1, 1, [ '@write', '@sortedset', '@slow' ]) end end class ZRevRangeCommand < BaseCommand def call SortedSetUtils.generic_range(@db, @args, reverse: true) end def self.describe Describe.new('zrevrange', -4, [ 'readonly' ], 1, 1, 1, [ '@read', '@sortedset', '@slow' ]) end end class ZRevRangeByLexCommand < BaseCommand def call SortedSetUtils.generic_range_by_lex(@db, @args, reverse: true) end def self.describe Describe.new('zrevrangebylex', -4, [ 'readonly' ], 1, 1, 1, [ '@read', '@sortedset', '@slow' ]) end end class ZRevRangeByScoreCommand < BaseCommand def call SortedSetUtils.generic_range_by_score(@db, @args, reverse: true) end def self.describe Describe.new('zrevrangebyscore', -4, [ 'readonly' ], 1, 1, 1, [ '@read', '@sortedset', '@slow' ]) end end class ZRevRankCommand < BaseCommand def call Utils.assert_args_length(2, @args) sorted_set = @db.lookup_sorted_set(@args[0]) if sorted_set RESPSerializer.serialize(sorted_set.rev_rank(@args[1])) else NullBulkStringInstance end end def self.describe Describe.new('zrevrank', 3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@sortedset', '@fast' ]) end end class ZPopMaxCommand < BaseCommand def call SortedSetUtils.generic_zpop(@db, @args) do |sorted_set, count| sorted_set.pop_max(count) end end def self.describe Describe.new('zpopmax', -2, [ 'write', 'fast' ], 1, 1, 1, [ '@write', '@sortedset', '@fast' ]) end end class ZPopMinCommand < BaseCommand def call SortedSetUtils.generic_zpop(@db, @args) do |sorted_set, count| sorted_set.pop_min(count) end end def self.describe Describe.new('zpopmin', -2, [ 'write', 'fast' ], 1, 1, 1, [ '@write', '@sortedset', '@fast' ]) end end class BZPopMaxCommand < BaseCommand def call SortedSetUtils.generic_bzpop(@db, @args, :zpopmax) do |sorted_set| sorted_set.pop_max(1) end end def self.describe Describe.new('bzpopmax', -3, [ 'write', 'noscript', 'fast' ], 1, -2, 1, [ '@write', '@sortedset', '@fast', '@blocking' ]) end end class BZPopMinCommand < BaseCommand def call SortedSetUtils.generic_bzpop(@db, @args, :zpopmin) do |sorted_set| sorted_set.pop_min(1) end end def self.describe Describe.new('bzpopmin', -3, [ 'write', 'noscript', 'fast' ], 1, -2, 1, [ '@write', '@sortedset', '@fast', '@blocking' ]) end end class ZCountCommand < BaseCommand def call SortedSetUtils.generic_count(@db, @args) do |sorted_set, min, max| range_spec = Utils.validate_score_range_spec(min, max) sorted_set&.count_in_score_range(range_spec) end end def self.describe Describe.new('zcount', 4, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@sortedset', '@fast' ]) end end class ZLexCountCommand < BaseCommand def call SortedSetUtils.generic_count(@db, @args) do |sorted_set, min, max| range_spec = Utils.validate_lex_range_spec(min, max) sorted_set&.count_in_lex_range(range_spec) end end def self.describe Describe.new('zlexcount', 4, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@sortedset', '@fast' ]) end end class ZIncrByCommand < BaseCommand def call Utils.assert_args_length(3, @args) incr = Utils.validate_float(@args[1], 'ERR value is not a valid float') key = @args[0] member = @args[2] sorted_set = @db.lookup_sorted_set_for_write(key) new_score = sorted_set.increment_score_by(member, incr) RESPBulkString.new(Utils.float_to_string(new_score)) rescue InvalidFloatString RESPError.new('ERR hash value is not a float') rescue FloatNaN RESPError.new('ERR resulting score is not a number (NaN)') end def self.describe Describe.new('zincrby', 4, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@sortedset', '@fast' ]) end end end <file_sep>/content/discussion.md --- title: Discussion description: Discussion --- ## Discussion Have a comment? question? feedback? You can find me on Twitter [@pierre_jambet](https://twitter.com/pierre_jambet) or add it below: <file_sep>/code/chapter-10/skiplist.rb module BYORedis class SkipList MAX_LEVEL = 32 # 32 is what Redis uses P = 0.25 Node = Struct.new(:member, :score, :backward, :levels, keyword_init: true) Level = Struct.new(:forward, :span, keyword_init: true) attr_reader :length def initialize @header = Node.new(member: nil, score: 0, backward: nil, levels: Array.new(MAX_LEVEL) { |_| Level.new(forward: nil, span: 0) }) @tail = nil @length = 0 @level = 1 end def search(val) end def insert(score, member) x = @header update = Array.new(MAX_LEVEL) rank = Array.new(MAX_LEVEL) (@level - 1).downto(0) do |level| rank[level] = (level == @level - 1) ? 0 : rank[level + 1] # p "levels: #{ x.levels.inspect }, level: #{ level }" # p "levels: #{ x.levels[level] }" while x.levels[level].forward && (x.levels[level].forward.score < score || (x.levels[level].forward.score == score && x.levels[level].forward.member < member)) rank[level] = x.levels[level].span x = x.levels[level].forward end update[level] = x end # p "Done with the update: #{ update.inspect }" level = random_level if level > @level @level.upto(level - 1).each do |i| rank[i] = 0 update[i] = @header update[i].levels[i].span = @length end @level = level end # p "We're at level: #{ level }/ #{ @level }" x = Node.new(member: member, score: score, backward: nil, levels: Array.new(level) { |_| Level.new(span: 0, forward: nil) }) # p "Here's x:" # p x 0.upto(level - 1).each do |i| x.levels[i].forward = update[i].levels[i].forward update[i].levels[i].forward = x # Update span covered by update[i] as x is inserted here x.levels[i].span = update[i].levels[i].span - (rank[0] - rank[i]) update[i].levels[i].span = (rank[0] - rank[i]) + 1 end # Increment span for untouched levels level.upto(@level - 1) do |i| update[i].levels[i].span += 1 end # p "Done updating the levels, last step is backward and tail, #{ update[0] == @header }" x.backward = (update[0] == @header) ? nil : update[0] if x.levels[0].forward x.levels[0].forward.backward = x else @tail = x end @length += 1 # p update x end def show p '---' @header.levels.each.with_index do |l,i| els = if l.forward.nil? ["N/A"] else nodes = [] while l.forward nodes << "#{l.forward.member}/#{l.forward.score}" l = l.forward.levels[i] end nodes end p "Level: #{i + 1}, #{ els.join(',') }" end p "@tail:" p @tail end def delete(score, member) end private def update_score(current_score, element, new_score) end def delete_node(node, update) end def random_level level = 1 while rand(0xffff) < (P * 0xffff) level += 1 end # p "Ended up at level: #{ level }" level < MAX_LEVEL ? level : MAX_LEVEL end end end <file_sep>/code/chapter-6/command_command.rb module BYORedis class CommandCommand def initialize(_data_store, _expires, _args) end SORTED_COMMANDS = [ CommandCommand, DelCommand, GetCommand, SetCommand, TtlCommand, PttlCommand, ] def call RESPArray.new(SORTED_COMMANDS.map { |command_class| command_class.describe }) end def self.describe [ 'command', -1, # arity # command flags [ 'random', 'loading', 'stale' ].map { |s| RESPSimpleString.new(s) }, 0, # position of first key in argument list 0, # position of last key in argument list 0, # step count for locating repeating keys # acl categories: https://github.com/antirez/redis/blob/6.0/src/server.c#L161-L166 [ '@slow', '@connection' ].map { |s| RESPSimpleString.new(s) }, ] end end end <file_sep>/code/chapter-8/utils.rb require 'bigdecimal' module BYORedis ULLONG_MAX = 2**64 - 1 # 18,446,744,073,709,551,615 ULLONG_MIN = 0 LLONG_MAX = 2**63 - 1 # 9,223,372,036,854,775,807 LLONG_MIN = 2**63 * - 1 # -9,223,372,036,854,775,808 InvalidArgsLength = Class.new(StandardError) do def resp_error(command_name) RESPError.new("ERR wrong number of arguments for '#{ command_name }' command") end end WrongTypeError = Class.new(StandardError) do def resp_error RESPError.new('WRONGTYPE Operation against a key holding the wrong kind of value') end end RESPSyntaxError = Class.new(StandardError) do def resp_error RESPError.new('ERR syntax error') end end ValidationError = Class.new(StandardError) do def resp_error RESPError.new(message) end end IntegerOverflow = Class.new(StandardError) InvalidIntegerString = Class.new(StandardError) InvalidFloatString = Class.new(StandardError) module Utils def self.assert_args_length(args_length, args) if args.length != args_length raise InvalidArgsLength, "Expected #{ args_length }, got #{ args.length }: #{ args }" end end def self.assert_args_length_greater_than(args_length, args) if args.length <= args_length raise InvalidArgsLength, "Expected more than #{ args_length } args, got #{ args.length }: #{ args }" end end def self.safe_write(socket, message) socket.write(message) rescue Errno::ECONNRESET, Errno::EPIPE, IOError false end def self.string_to_integer(string) raise InvalidIntegerString, 'Empty string' if string.empty? bytes = string.bytes zero_ord = '0'.ord # 48, 'a'.ord == 97, so return 0 if bytes.length == 1 && bytes[0] == zero_ord if bytes[0] == '-'.ord negative = true bytes.shift raise InvalidIntegerString, 'Nothing after -' if bytes.empty? else negative = false end unless bytes[0] >= '1'.ord && bytes[0] <= '9'.ord raise InvalidIntegerString end num = bytes[0] - zero_ord 1.upto(bytes.length - 1) do |i| unless bytes[i] >= zero_ord && bytes[i] <= '9'.ord raise InvalidIntegerString, "Not a number: '#{ bytes[i] }' / '#{ [ bytes[i] ].pack('C') }'" end raise IntegerOverflow, 'Overflow before *' if num > ULLONG_MAX / 10 num *= 10 raise IntegerOverflow, 'Overflow before +' if num > ULLONG_MAX - (bytes[i] - zero_ord) num += bytes[i] - zero_ord end if negative && num > -LLONG_MIN # In Redis, the condition is: # # if (v > ( (unsigned long long) (-(LLONG_MIN+1)) +1) ) # # But used to be (-(unsigned long long)LLONG_MIN) until this commit: # https://github.com/redis/redis/commit/5d08193126df54405dae3073c62b7c19ae03d1a4 # # Both seem to be similar but the current version might be safer on different machines. # Essentially it adds one to LLONG_MIN, so that multiplying it by -1 with the - operator # falls within the boundaries of a long long, given that min can be -9...808 while max # is always 9...807, we then cast the positive value to an unsigned long long, so that # we can add 1 to it, turning it into 9...808 # The C standard does not seem to be very specific around the exact value of LLONG_MIN # it seems to either be -9..807 or, as it is on my machine, a mac, -9...808, which is # because it uses Two's Complement. raise IntegerOverflow, 'Too small for a long long' elsif negative -num elsif num > LLONG_MAX raise IntegerOverflow, 'Too big for a long long' else num end end def self.float_to_string(big_decimal) if big_decimal == BigDecimal::INFINITY 'inf' elsif big_decimal == -BigDecimal::INFINITY '-inf' elsif (truncated = big_decimal.truncate) == big_decimal # Remove the .0 part of the number integer_to_string(truncated) else big_decimal.to_s('F') end end def self.integer_to_string(integer) return '0' if integer == 0 v = integer >= 0 ? integer : -integer zero_ord = '0'.ord bytes = [] until v == 0 bytes.prepend(zero_ord + v % 10) v /= 10 end bytes.prepend('-'.ord) if integer < 0 bytes.pack('C*') end def self.validate_integer(str) string_to_integer(str) rescue IntegerOverflow, InvalidIntegerString raise ValidationError, 'ERR value is not an integer or out of range' end def self.validate_float(str, error_message) case str.downcase when '+inf', 'inf', 'infinity', '+infinity' then BigDecimal::INFINITY when '-inf', '-infinity' then -BigDecimal::INFINITY else parsed = BigDecimal(str) if parsed.nan? raise ArgumentError else parsed end end rescue ArgumentError, TypeError raise ValidationError, error_message end def self.validate_timeout(str) timeout = validate_float(str, 'ERR timeout is not a float or out of range') raise ValidationError, 'ERR timeout is negative' if timeout < 0 || timeout.infinite? timeout end end end <file_sep>/code/chapter-10/redis_sorted_set.rb require 'bigdecimal' require_relative './dict' require_relative './list' require_relative './zset' module BYORedis class RedisSortedSet Pair = Struct.new(:score, :member) class GenericRangeSpec attr_reader :min, :max, :min_exclusive, :max_exclusive alias min_exclusive? min_exclusive alias max_exclusive? max_exclusive def self.lex_range_spec(min, max, min_exclusive, max_exclusive) GenericRangeSpec.new(min, max, min_exclusive, max_exclusive) do |a, b| RedisSortedSet.lex_compare(a, b) end end def self.score_range_spec(min, max, min_exclusive, max_exclusive) GenericRangeSpec.new(min, max, min_exclusive, max_exclusive) do |a, b| a <=> b end end def self.rank_range_spec(min, max, cardinality) max = cardinality + max if max < 0 min = cardinality + min if min < 0 max = cardinality - 1 if max >= cardinality min = 0 if min < 0 GenericRangeSpec.new(min, max, false, false) do |a, b| a <=> b end end def initialize(min, max, min_exclusive, max_exclusive, &block) @min = min @min_exclusive = min_exclusive @max = max @max_exclusive = max_exclusive @block = block end def empty? comparison = compare_with_max(min) comparison > 0 || (comparison == 0 && (min_exclusive? || max_exclusive?)) end def compare_with_max(element) @block.call(element, @max) end def compare_with_min(element) @block.call(element, @min) end def in_range?(element) return false if empty? comparison_min = compare_with_min(element) comparison_max = compare_with_max(element) comparison_min_ok = min_exclusive? ? comparison_min == 1 : comparison_min >= 0 comparison_max_ok = max_exclusive? ? comparison_max == -1 : comparison_max <= 0 comparison_min_ok && comparison_max_ok end end attr_reader :underlying def initialize @underlying = List.new end def self.lex_compare(s1, s2) return 0 if s1 == s2 return -1 if s1 == '-' || s2 == '+' return 1 if s1 == '+' || s2 == '-' s1 <=> s2 end def self.intersection(sets_with_weight, aggregate: :sum) # Sort the sets smallest to largest sets_with_weight.sort_by! { |set, _| set.nil? ? 0 : set.cardinality } smallest_set = sets_with_weight[0][0] smallest_set_weight = sets_with_weight[0][1] return RedisSortedSet.new if smallest_set.nil? intersection_set = RedisSortedSet.new # Iterate over the first set, if we find a set that does not contain the member, discard smallest_set.each do |set_member| present_in_all_other_sets = true if set_member.is_a?(Pair) pair = set_member else pair = Pair.new(BigDecimal(1), set_member) end weighted_pair_score = Utils.multiply_or_zero_if_nan(smallest_set_weight, pair.score) # For each member of the smallest set, we loop through all the other sets and try to # find the member, if we don't find it, we break the loop and move on, if we do find # a member, then we need to apply the weight/aggregate logic to it sets_with_weight[1..-1].each do |set_with_weight| set = set_with_weight[0] weight = set_with_weight[1] if set == smallest_set other_pair = pair elsif set.is_a?(RedisSet) other_pair = set.member?(pair.member) ? Pair.new(BigDecimal(1), pair.member) : nil elsif set.is_a?(RedisSortedSet) other_pair = set.find_pair(pair.member) else raise "Unknown set type: #{ set }" end if other_pair weighted_other_pair_score = Utils.multiply_or_zero_if_nan(other_pair.score, weight) weighted_pair_score = aggregate_scores(aggregate, weighted_other_pair_score, weighted_pair_score) else present_in_all_other_sets = false break end end # Otherwise, keep if present_in_all_other_sets intersection_set.add(weighted_pair_score, pair.member, options: {}) end end intersection_set end def self.union(sets_with_weight, aggregate: :sum) return RediSortedSet.new({}) if sets_with_weight.empty? accumulator = Dict.new sets_with_weight[0..-1].each do |set_with_weight| set = set_with_weight[0] weight = set_with_weight[1] next if set.nil? set.each do |set_member| if set.is_a?(RedisSet) pair = Pair.new(BigDecimal(1), set_member) elsif set.is_a?(RedisSortedSet) pair = set_member else raise "Unknown set type: #{ set }" end weighted_score = Utils.multiply_or_zero_if_nan(pair.score, weight) existing_entry = accumulator.get_entry(pair.member) if existing_entry new_score = aggregate_scores(aggregate, existing_entry.value, weighted_score) existing_entry.value = new_score else accumulator[pair.member] = weighted_score end end end union_set = RedisSortedSet.new accumulator.each do |key, value| union_set.add(value, key) end union_set end def self.aggregate_scores(aggregate, a, b) case aggregate when :sum then Utils.add_or_zero_if_nan(a, b) when :max then a < b ? b : a when :min then a < b ? a : b else raise "Unknown aggregate method: #{ aggregate }" end end private_class_method :aggregate_scores def cardinality case @underlying when List then @underlying.size when ZSet then @underlying.cardinality else raise "Unknown type for #{ @underlying }" end end def add(score, member, options: {}) convert_to_zset if @underlying.is_a?(List) && member.length > Config.get_config(:zset_max_ziplist_value) case @underlying when List added = add_list(score, member, options: options) convert_to_zset if added && cardinality >= Config.get_config(:zset_max_ziplist_entries) added when ZSet then @underlying.add(score, member, options) else raise "Unknown type for #{ @underlying }" end end def find_pair(member) case @underlying when List then list_find_pair(member) when ZSet dict_entry = @underlying.dict.get_entry(member) Pair.new(dict_entry.value, dict_entry.key) if dict_entry else raise "Unknown type for #{ @underlying }" end end def remove(member) case @underlying when List then remove_list(member) when ZSet then @underlying.remove_member(member) else raise "Unknown type for #{ @underlying }" end end def remove_lex_range(range_spec) return 0 if range_spec.empty? || no_overlap_with_range?(range_spec) { |pair, _| pair.member } case @underlying when List then remove_lex_range_list(range_spec) when ZSet then @underlying.remove_lex_range(range_spec) else raise "Unknown type for #{ @underlying }" end end def remove_rank_range(range_spec) return 0 if range_spec.empty? || no_overlap_with_range?(range_spec) { |_, rank| rank } case @underlying when List then remove_rank_range_list(range_spec) when ZSet then @underlying.remove_rank_range(range_spec.min, range_spec.max) else raise "Unknown type for #{ @underlying }" end end def remove_score_range(range_spec) return 0 if range_spec.empty? || no_overlap_with_range?(range_spec) { |pair, _| pair.score } case @underlying when List then remove_score_range_list(range_spec) when ZSet then @underlying.remove_score_range(range_spec) else raise "Unknown type for #{ @underlying }" end end def rev_rank(member) member_rank = rank(member) cardinality - 1 - member_rank if member_rank end def rank(member) case @underlying when List then find_member_in_list(member) { |_, rank| rank } when ZSet entry = @underlying.dict.get_entry(member) return nil unless entry @underlying.array.index(Pair.new(entry.value, member)) else raise "Unknown type for #{ @underlying }" end end def score(member) case @underlying when List then find_member_in_list(member) { |pair, _| pair.score } when ZSet then @underlying.dict[member] else raise "Unknown type for #{ @underlying }" end end def empty? cardinality == 0 end def each(&block) case @underlying when List then @underlying.each(&block) when ZSet then @underlying.array.each(&block) else raise "Unknown type for #{ @underlying }" end end def pop_max(count) case @underlying when List then generic_pop(count) { @underlying.right_pop&.value } when ZSet generic_pop(count) do max = @underlying.array.pop @underlying.dict.delete(max.member) if max max end else raise "Unknown type for #{ @underlying }" end end def pop_min(count) case @underlying when List then generic_pop(count) { @underlying.left_pop&.value } when ZSet generic_pop(count) do min = @underlying.array.shift @underlying.dict.delete(min.member) if min min end else raise "Unknown type for #{ @underlying }" end end def count_in_lex_range(range_spec) return 0 if range_spec.empty? || no_overlap_with_range?(range_spec) { |pair, _| pair.member } case @underlying when List then count_in_lex_range_list(range_spec) when ZSet then @underlying.count_in_lex_range(range_spec) else raise "Unknown type for #{ @underlying }" end end def count_in_score_range(range_spec) return 0 if range_spec.empty? || no_overlap_with_range?(range_spec) { |pair, _| pair.score } case @underlying when List then count_in_score_range_list(range_spec) when ZSet then @underlying.count_in_score_range(range_spec) else raise "Unknown type for #{ @underlying }" end end def increment_score_by(member, increment) current_score = score(member) || BigDecimal(0) new_score = Utils.add_or_raise_if_nan(current_score, increment) add(new_score, member) new_score end def no_overlap_with_range?(range_spec, &block) # Note that in that each condition the "value" is abstract and determined by the return # value of calling the block variable, in practice it's either score, member, or rank # There is no overlap under the four following conditions: # 1. the range spec min is greater than the max value: # set : |---| # range: |---| (min can be inclusive or exclusive, doesn't matter) # 2. the range spec min is exclusive and is equal to the max value # set : |---| # range: (---| (min is exclusive) # 3. the min value is greater than range spec max # set : |---| # range: |---| (max can be inclusive or exclusive, doesn't matter) # 4. the min value is equal to the range spec max which is exclusive # set : |---| # range: |---( (max is exclusive) max_pair, max_pair_rank = max_pair_with_rank min_pair, min_pair_rank = min_pair_with_rank set_max_range_spec_min_comparison = range_spec.compare_with_min(block.call(max_pair, max_pair_rank)) set_min_range_spec_max_comparison = range_spec.compare_with_max(block.call(min_pair, min_pair_rank)) set_max_range_spec_min_comparison == -1 || # case 1 (range_spec.min_exclusive? && set_max_range_spec_min_comparison == 0) || # case 2 set_min_range_spec_max_comparison == 1 || # case 3 (range_spec.max_exclusive? && set_min_range_spec_max_comparison == 0) # case 4 end private # @return [Array] Two values, the first is a Pair, and the second is the rank def max_pair_with_rank case @underlying when List return @underlying.tail.value, @underlying.size when ZSet return @underlying.array[-1], @underlying.array.size - 1 else raise "Unknown type for #{ @underlying }" end end # @return [Array] Two values, the first is a Pair, and the second is the rank def min_pair_with_rank case @underlying when List return @underlying.head.value, 0 when ZSet return @underlying.array[0], 0 else raise "Unknown type for #{ @underlying }" end end def generic_count_list(range_spec) count = 0 entered_range = false @underlying.each do |pair| in_range = range_spec.in_range?(yield(pair)) if in_range entered_range ||= true count += 1 elsif entered_range break end end count end def count_in_lex_range_list(range_spec) generic_count_list(range_spec, &:member) end def count_in_score_range_list(range_spec) generic_count_list(range_spec, &:score) end def find_member_in_list(member) index = 0 @underlying.each do |pair| return yield pair, index if pair.member == member index += 1 end nil end def remove_list(member) iterator = List.left_to_right_iterator(@underlying) while iterator.cursor if iterator.cursor.value.member == member @underlying.remove_node(iterator.cursor) return true end iterator.next end false end def generic_remove_range_list(range_spec) removed_count = 0 iterator = List.left_to_right_iterator(@underlying) entered_range = false rank = 0 while iterator.cursor pair = iterator.cursor.value in_range = range_spec.in_range?(yield(pair, rank)) if in_range entered_range ||= true removed_count += 1 next_node = iterator.cursor.next_node @underlying.remove_node(iterator.cursor) iterator.cursor = next_node elsif entered_range break else iterator.next end rank += 1 end removed_count end def remove_lex_range_list(range_spec) generic_remove_range_list(range_spec) { |pair, _| pair.member } end def remove_rank_range_list(range_spec) generic_remove_range_list(range_spec) { |_, rank| rank } end def remove_score_range_list(range_spec) generic_remove_range_list(range_spec) { |pair, _| pair.score } end def generic_pop(count) popped = [] return popped if count < 0 while count > 0 min = yield if min popped.push(min.member, min.score) count -= 1 else break end end popped end def convert_to_zset raise "#{ @underlying } is not a List" unless @underlying.is_a?(List) zset = ZSet.new @underlying.each do |pair| zset.dict[pair.member] = pair.score zset.array << pair end @underlying = zset end def add_list(score, member, options: {}) raise "#{ @underlying } is not a List" unless @underlying.is_a?(List) unless [ nil, :nx, :xx ].include?(options[:presence]) raise "Unknown presence value: #{ options[:presence] }" end iterator = List.left_to_right_iterator(@underlying) while iterator.cursor cursor = iterator.cursor pair = iterator.cursor.value if pair.member == member # We found a pair in the list with a matching member if pair.score == score && !options[:incr] # We found an exact match, without the INCR option, so we do nothing return false elsif options[:presence] == :nx # We found an element, but because of the NX option, we do nothing return false else # The score changed, so we might to reinsert the element at the correct location to # maintain the list sorted new_score = options[:incr] ? Utils.add_or_raise_if_nan(pair.score, score) : score prev_node = cursor.prev_node next_node = cursor.next_node if (next_node.nil? || next_node.value.score > new_score || (next_node.value.score == score && next_node.value.member > member)) && (prev_node.nil? || prev_node.value.score < new_score || (prev_node.value.score == score && prev_node.value.member < member)) cursor.value.score = new_score else @underlying.remove_node(cursor) # We add the node back, which takes care of finding the correct index unless add_list(new_score, member, options: { member_does_not_exist: true }) raise 'Unexpectedly failed to re-insert node after update' end end if options[:incr] return new_score else # If options[:ch] == true, then we want to count this update and return true return options[:ch] end end elsif pair.score > score || (pair.score == score && pair.member > member) # As soon as we find a node where its score is greater than the score of the # element we're attempting to insert, we store its reference in `location` so that # we can use insert_before_node below. # In case of a score equality, the right side of the || above, we use the # lexicographic order of the member value to sort them # We cannot stop here however because there might be an exact member match later in # the list, in which case the `if pair.member == member` check above will trigger # and return location ||= cursor if options[:member_does_not_exist] break else iterator.next end elsif pair.score < score || (pair.score == score && pair.member < member) # In this case we haven't found a node where the score is greater than the one we're # trying to insert, or the scores are equal but the lexicographic order tells us that # member is greater than the current node, so we keep searching for an insert location # to the right iterator.next else # We've covered all cases, this is never expected to happen raise "Unexpected else branch reached for #{ score }/#{ member }" end end return false if options[:presence] == :xx new_pair = Pair.new(score, member) if location @underlying.insert_before_node(location, new_pair) else @underlying.right_push(new_pair) end if options[:incr] score else true end end def list_find_pair(member) @underlying.each do |pair| return pair if pair.member == member end nil end end class SortedSetRankSerializer def initialize(sorted_set, range_spec, withscores: false, reverse: false) @sorted_set = sorted_set @range_spec = range_spec @withscores = withscores @reverse = reverse end def serialize return RESPArray.new([]).serialize if @range_spec.empty? case @sorted_set.underlying when List then serialize_list when ZSet then serialize_zset else raise "Unknown type for #{ @underlying }" end end private def serialize_zset members = [] (@range_spec.min..@range_spec.max).each do |rank| pair = @sorted_set.underlying.array[rank] if @reverse members.prepend(Utils.float_to_string(pair.score)) if @withscores members.prepend(pair.member) else members.push(pair.member) members.push(Utils.float_to_string(pair.score)) if @withscores end end RESPArray.new(members).serialize end def serialize_list ltr_acc = lambda do |value, response| response << RESPBulkString.new(value.member).serialize if @withscores response << RESPBulkString.new(Utils.float_to_string(value.score)).serialize end @withscores ? 2 : 1 end rtl_acc = lambda do |value, response| if @withscores response.prepend(RESPBulkString.new(Utils.float_to_string(value.score)).serialize) end response.prepend(RESPBulkString.new(value.member).serialize) @withscores ? 2 : 1 end if @reverse tmp = ltr_acc ltr_acc = rtl_acc rtl_acc = tmp end ListSerializer.new(@sorted_set.underlying, @range_spec.min, @range_spec.max) .serialize_with_accumulators(ltr_acc, rtl_acc) end end class SortedSetSerializerBy def initialize(sorted_set, range_spec, offset: 0, count: -1, withscores: false, reverse: false, &block) @sorted_set = sorted_set @range_spec = range_spec @offset = offset @count = count @withscores = withscores @reverse = reverse if block.arity != 2 @block = proc { |element, _| block.call(element) } else @block = block end end def serialize if @offset < 0 || @range_spec.empty? || @sorted_set.no_overlap_with_range?(@range_spec, &@block) return RESPArray.new([]).serialize end case @sorted_set.underlying when List then serialize_list when ZSet then serialize_zset else raise "Unknown type for #{ @underlying }" end end private def serialize_zset members = [] if @reverse start_index = @sorted_set.underlying.array.last_index_in_range(@range_spec, &@block) if start_index.nil? raise "Unexpectedly failed to find last index in range for #{ self }" end indices = start_index.downto(0) else start_index = @sorted_set.underlying.array.first_index_in_range(@range_spec, &@block) if start_index.nil? raise "Unexpectedly failed to find first index in range for #{ self }" end indices = start_index.upto(@sorted_set.cardinality - 1) end indices.each do |i| item = @sorted_set.underlying.array[i] if @range_spec.in_range?(@block.call(item)) if @offset == 0 members << item.member members << Utils.float_to_string(item.score) if @withscores @count -= 1 break if @count == 0 else @offset -= 1 end else break end end RESPArray.new(members).serialize end def serialize_list if @reverse iterator = List.right_to_left_iterator(@sorted_set.underlying) else iterator = List.left_to_right_iterator(@sorted_set.underlying) end members = [] entered_range = false while iterator.cursor && @count != 0 member = iterator.cursor.value if @range_spec.in_range?(@block.call(member)) entered_range ||= true if @offset == 0 members << member.member members << Utils.float_to_string(member.score) if @withscores @count -= 1 else @offset -= 1 end elsif entered_range == true break end iterator.next end RESPArray.new(members).serialize end end end <file_sep>/code/chapter-4/get_command.rb class GetCommand def initialize(data_store, expires, args) @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @data_store = data_store @expires = expires @args = args end def call if @args.length != 1 "(error) ERR wrong number of arguments for 'GET' command" else key = @args[0] ExpireHelper.check_if_expired(@data_store, @expires, key) @data_store.fetch(key, '(nil)') end end end <file_sep>/code/chapter-5/server.rb require 'socket' require 'logger' require 'strscan' LOG_LEVEL = ENV['DEBUG'] ? Logger::DEBUG : Logger::INFO require_relative './expire_helper' require_relative './command_command' require_relative './resp_types' require_relative './get_command' require_relative './set_command' require_relative './ttl_command' require_relative './pttl_command' module BYORedis class Server COMMANDS = { 'command' => CommandCommand, 'get' => GetCommand, 'set' => SetCommand, 'ttl' => TtlCommand, 'pttl' => PttlCommand, } MAX_EXPIRE_LOOKUPS_PER_CYCLE = 20 DEFAULT_FREQUENCY = 10 # How many times server_cron runs per second IncompleteCommand = Class.new(StandardError) ProtocolError = Class.new(StandardError) do def serialize RESPError.new(message).serialize end end TimeEvent = Struct.new(:process_at, :block) Client = Struct.new(:socket, :buffer) do def initialize(socket) self.socket = socket self.buffer = '' end end def initialize @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @clients = [] @data_store = {} @expires = {} @server = TCPServer.new 2000 @time_events = [] @logger.debug "Server started at: #{ Time.now }" add_time_event(Time.now.to_f.truncate + 1) do server_cron end start_event_loop end private def add_time_event(process_at, &block) @time_events << TimeEvent.new(process_at, block) end def nearest_time_event now = (Time.now.to_f * 1000).truncate nearest = nil @time_events.each do |time_event| if nearest.nil? nearest = time_event elsif time_event.process_at < nearest.process_at nearest = time_event else next end end nearest end def select_timeout if @time_events.any? nearest = nearest_time_event now = (Time.now.to_f * 1000).truncate if nearest.process_at < now 0 else (nearest.process_at - now) / 1000.0 end else 0 end end def client_sockets @clients.map(&:socket) end def start_event_loop loop do timeout = select_timeout @logger.debug "select with a timeout of #{ timeout }" result = IO.select(client_sockets + [@server], [], [], timeout) sockets = result ? result[0] : [] process_poll_events(sockets) process_time_events end end def process_poll_events(sockets) sockets.each do |socket| begin if socket.is_a?(TCPServer) @clients << Client.new(@server.accept) elsif socket.is_a?(TCPSocket) client = @clients.find { |client| client.socket == socket } client_command_with_args = socket.read_nonblock(1024, exception: false) if client_command_with_args.nil? @clients.delete(client) socket.close elsif client_command_with_args == :wait_readable # There's nothing to read from the client, we don't have to do anything next elsif client_command_with_args.empty? @logger.debug "Empty request received from #{ socket }" else client.buffer += client_command_with_args split_commands(client.buffer) do |command_parts| response = handle_client_command(command_parts) @logger.debug "Response: #{ response.class } / #{ response.inspect }" @logger.debug "Writing: '#{ response.serialize.inspect }'" socket.write response.serialize end end else raise "Unknown socket type: #{ socket }" end rescue Errno::ECONNRESET @clients.delete_if { |client| client.socket == socket } rescue IncompleteCommand # Not clearing the buffer or anything next rescue ProtocolError => e socket.write e.serialize socket.close @clients.delete(client) end end end def split_commands(client_buffer) @logger.debug "Full result from read: '#{ client_buffer.inspect }'" scanner = StringScanner.new(client_buffer.dup) until scanner.eos? if scanner.peek(1) == '*' yield parse_as_resp_array(scanner) else yield parse_as_inline_command(scanner) end client_buffer.slice!(0, scanner.charpos) end end def parse_as_resp_array(scanner) unless scanner.getch == '*' raise 'Unexpectedly attempted to parse a non array as an array' end expected_length = scanner.scan_until(/\r\n/) raise IncompleteCommand if expected_length.nil? expected_length = parse_integer(expected_length, 'invalid multibulk length') command_parts = [] expected_length.times do raise IncompleteCommand if scanner.eos? parsed_value = parse_as_resp_bulk_string(scanner) raise IncompleteCommand if parsed_value.nil? command_parts << parsed_value end command_parts end def parse_as_resp_bulk_string(scanner) type_char = scanner.getch unless type_char == '$' raise ProtocolError, "ERR Protocol error: expected '$', got '#{ type_char }'" end expected_length = scanner.scan_until(/\r\n/) raise IncompleteCommand if expected_length.nil? expected_length = parse_integer(expected_length, 'invalid bulk length') bulk_string = scanner.rest.slice(0, expected_length) raise IncompleteCommand if bulk_string.nil? || bulk_string.length != expected_length scanner.pos += bulk_string.bytesize + 2 bulk_string end def parse_as_inline_command(scanner) command = scanner.scan_until(/(\r\n|\r|\n)+/) raise IncompleteCommand if command.nil? command.split.map(&:strip) end def process_time_events @time_events.delete_if do |time_event| next if time_event.process_at > Time.now.to_f * 1000 return_value = time_event.block.call if return_value.nil? true else time_event.process_at = (Time.now.to_f * 1000).truncate + return_value @logger.debug "Rescheduling time event #{ Time.at(time_event.process_at / 1000.0).to_f }" false end end end def handle_client_command(command_parts) @logger.debug "Received command: #{ command_parts }" command_str = command_parts[0] args = command_parts[1..-1] command_class = COMMANDS[command_str.downcase] if command_class command = command_class.new(@data_store, @expires, args) command.call else formatted_args = args.map { |arg| "`#{ arg }`," }.join(' ') message = "ERR unknown command `#{ command_str }`, with args beginning with: #{ formatted_args }" RESPError.new(message) end end def server_cron start_timestamp = Time.now keys_fetched = 0 @expires.each do |key, _| if @expires[key] < Time.now.to_f * 1000 @logger.debug "Evicting #{ key }" @expires.delete(key) @data_store.delete(key) end keys_fetched += 1 if keys_fetched >= MAX_EXPIRE_LOOKUPS_PER_CYCLE break end end end_timestamp = Time.now @logger.debug do format( 'Processed %<number_of_keys>i keys in %<duration>.3f ms', number_of_keys: keys_fetched, duration: (end_timestamp - start_timestamp) * 1000, ) end 1000 / DEFAULT_FREQUENCY end def parse_integer(integer_str, error_message) begin value = Integer(integer_str) if value < 0 raise ProtocolError, "ERR Protocol error: #{ error_message }" else value end rescue ArgumentError raise ProtocolError, "ERR Protocol error: #{ error_message }" end end end end <file_sep>/content/about.md --- title: About me comment: false description: About me --- # About me Hey! My name is Pierre, I'm a French software engineer based in NYC. I write about tech stuff [on my blog](https://blog.pjam.me) and I also write about the thing when I don't write code, or write about writing code, running on [this other site](https://pacing.pjam.me). The chapters are also published on [Medium](https://medium.com/@pierre_jambet) and on [dev.to](https://dev.to/pjam). If you like this online book, do not hesitate to share your feedback: [@pierre_jambet](https://twitter.com/pierre_jambet) and maybe share a few bucks so I could spend more time writing content like this? <div style="text-align: center;"> <style>.bmc-button img{height: 34px !important;width: 35px !important;margin-bottom: 1px !important;box-shadow: none !important;border: none !important;vertical-align: middle !important;}.bmc-button{padding: 7px 15px 7px 10px !important;line-height: 35px !important;height:51px !important;text-decoration: none !important;display:inline-flex !important;color:#FFFFFF !important;background-color:#FF813F !important;border-radius: 5px !important;border: 1px solid transparent !important;padding: 7px 15px 7px 10px !important;font-size: 22px !important;letter-spacing: 0.6px !important;box-shadow: 0px 1px 2px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 1px 2px 2px rgba(190, 190, 190, 0.5) !important;margin: 0 auto !important;font-family:'Cookie', cursive !important;-webkit-box-sizing: border-box !important;box-sizing: border-box !important;}.bmc-button:hover, .bmc-button:active, .bmc-button:focus {-webkit-box-shadow: 0px 1px 2px 2px rgba(190, 190, 190, 0.5) !important;text-decoration: none !important;box-shadow: 0px 1px 2px 2px rgba(190, 190, 190, 0.5) !important;opacity: 0.85 !important;color:#FFFFFF !important;}</style> <link href="https://fonts.googleapis.com/css?family=Cookie" rel="stylesheet"> <a class="bmc-button" target="_blank" href="https://www.buymeacoffee.com/pjam"> <img src="https://cdn.buymeacoffee.com/buttons/bmc-new-btn-logo.svg" alt="Buy me a coffee"> <span style="margin-left:5px;margin-top: 0px;font-size:28px !important;">Buy me a coffee</span> </a> </div> <file_sep>/code/chapter-8/sorted_array.rb module BYORedis class SortedArray def initialize(field) @underlying = [] @field = field.to_sym end def push(new_element) if @underlying.empty? index = 0 else index = @underlying.bsearch_index do |element| element.send(@field) >= new_element.send(@field) end end index = @underlying.size if index.nil? @underlying.insert(index, new_element) end alias << push def [](index) @underlying[index] end def size @underlying.size end def shift @underlying.shift end def delete_if(&block) @underlying.delete_if(&block) end def delete(element) index = @underlying.bsearch_index { |x| x.send(@field) >= element.send(@field) } return if index.nil? element_at_index = @underlying[index] first_index_to_delete = nil number_of_items_to_delete = 0 while element_at_index if element_at_index == element first_index_to_delete ||= index number_of_items_to_delete += 1 end index += 1 next_element = @underlying[index] if next_element && next_element.send(@field) == element.send(@field) element_at_index = next_element else break end end @underlying.slice!(first_index_to_delete, number_of_items_to_delete) end end end <file_sep>/content/post/chapter-12-hyperloglogs.md --- title: "Chapter 12 Adding Hyperloglogs Commands" date: 2020-10-17T18:17:49-04:00 lastmod: 2020-10-17T18:17:49-04:00 draft: true comment: false keywords: [] summary: "" --- <!--more--> PFADD PFCOUNT PFMERGE Example with 1,000,000 values, 1 to 1,000,000: ``` bash 127.0.0.1:6379> pfcount hll (integer) 1009972 127.0.0.1:6379> scard s (integer) 1000000 127.0.0.1:6379> debug object hll Value at:0x7f88e9585080 refcount:1 encoding:raw serializedlength:10587 lru:11279204 lru_seconds_idle:18 127.0.0.1:6379> debug object s Value at:0x7f88e5f249f0 refcount:1 encoding:hashtable serializedlength:4934341 lru:11279207 lru_seconds_idle:16 ``` Off by 0.9972% ``` bash 127.0.0.1:6379> debug object s2 Value at:0x7f88ebb70330 refcount:1 encoding:hashtable serializedlength:2874 lru:11279316 lru_seconds_idle:9 127.0.0.1:6379> debug object hll2 Value at:0x7f88ebc5ad90 refcount:1 encoding:raw serializedlength:1838 lru:11279321 lru_seconds_idle:6 127.0.0.1:6379> scard s2 (integer) 1000 127.0.0.1:6379> pfcount hll2 (integer) 1001 ``` Off by 0.1% <file_sep>/code/chapter-10/list_commands.rb require_relative './list' module BYORedis ZeroRankError = Class.new(StandardError) do def message 'ERR RANK can\'t be zero: use 1 to start from the first match, 2 from the second, ...' end end NegativeOptionError = Class.new(StandardError) do def initialize(field_name) @field_name = field_name end def message "ERR #{ @field_name } can\'t be negative" end end module ListUtils def self.common_lpush(list, elements) elements.each { |element| list.left_push(element) } RESPInteger.new(list.size) end def self.common_rpush(list, elements) elements.each { |element| list.right_push(element) } RESPInteger.new(list.size) end def self.common_find(args) Utils.assert_args_length_greater_than(1, args) yield args[0] end def self.find_or_create_list(db, args) common_find(args) do |key| db.lookup_list_for_write(key) end end def self.find_list(db, args) common_find(args) do |key| db.lookup_list(key) end end def self.common_xpush(list) if list.nil? RESPInteger.new(0) else yield end end def self.common_pop(db, args) Utils.assert_args_length(1, args) key = args[0] list = db.lookup_list(key) if list.nil? NullBulkStringInstance else value = yield key, list RESPBulkString.new(value) end end def self.common_bpop(db, args, operation) Utils.assert_args_length_greater_than(1, args) timeout = Utils.validate_timeout(args.pop) list_names = args list_names.each do |list_name| list = db.lookup_list(list_name) next if list.nil? popped = yield list_name, list return RESPArray.new([ list_name, popped ]) end Server::BlockedState.new(BlockedClientHandler.timeout_timestamp_or_nil(timeout), list_names, operation) end def self.common_rpoplpush(db, source_key, destination_key, source) if source_key == destination_key && source.size == 1 source_tail = source.head.value else destination = db.lookup_list_for_write(destination_key) source_tail = db.right_pop_from(source_key, source) destination.left_push(source_tail) end RESPBulkString.new(source_tail) end end class LRangeCommand < BaseCommand def call Utils.assert_args_length(3, @args) key = @args[0] start = Utils.validate_integer(@args[1]) stop = Utils.validate_integer(@args[2]) list = @db.lookup_list(key) if list.nil? EmptyArrayInstance else ListSerializer.new(list, start, stop) end end def self.describe Describe.new('lrange', 4, [ 'readonly' ], 1, 1, 1, [ '@read', '@list', '@slow' ]) end end class LLenCommand < BaseCommand def call Utils.assert_args_length(1, @args) key = @args[0] list = @db.lookup_list(key) if list.nil? RESPInteger.new(0) else RESPInteger.new(list.size) end end def self.describe Describe.new('llen', 2, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@list', '@fast' ]) end end class LPopCommand < BaseCommand def call ListUtils.common_pop(@db, @args) do |key, list| @db.left_pop_from(key, list) end end def self.describe Describe.new('lpop', 2, [ 'write', 'fast' ], 1, 1, 1, [ '@write', '@list', '@fast' ]) end end class LPushCommand < BaseCommand def call list = ListUtils.find_or_create_list(@db, @args) values = @args[1..-1] ListUtils.common_lpush(list, values) end def self.describe Describe.new('lpush', -3, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@list', '@fast' ]) end end class LPushXCommand < BaseCommand def call list = ListUtils.find_list(@db, @args) values = @args[1..-1] ListUtils.common_xpush(list) do ListUtils.common_lpush(list, values) end end def self.describe Describe.new('lpushx', -3, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@list', '@fast' ]) end end class RPushCommand < BaseCommand def call list = ListUtils.find_or_create_list(@db, @args) values = @args[1..-1] ListUtils.common_rpush(list, values) end def self.describe Describe.new('rpush', -3, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@list', '@fast' ]) end end class RPushXCommand < BaseCommand def call list = ListUtils.find_list(@db, @args) values = @args[1..-1] ListUtils.common_xpush(list) do ListUtils.common_rpush(list, values) end end def self.describe Describe.new('rpushx', -3, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@list', '@fast' ]) end end class RPopCommand < BaseCommand def call ListUtils.common_pop(@db, @args) do |key, list| @db.right_pop_from(key, list) end end def self.describe Describe.new('rpop', 2, [ 'write', 'fast' ], 1, 1, 1, [ '@write', '@list', '@fast' ]) end end class RPopLPushCommand < BaseCommand def call Utils.assert_args_length(2, @args) source_key = @args[0] source = @db.lookup_list(source_key) if source.nil? NullBulkStringInstance else destination_key = @args[1] ListUtils.common_rpoplpush(@db, source_key, destination_key, source) end end def self.describe Describe.new('rpoplpush', 3, [ 'write', 'denyoom' ], 1, 2, 1, [ '@write', '@list', '@slow' ]) end end class LTrimCommand < BaseCommand def call Utils.assert_args_length(3, @args) key = @args[0] start = Utils.validate_integer(@args[1]) stop = Utils.validate_integer(@args[2]) list = @db.lookup_list(key) if list @db.trim(key, list, start, stop) end OKSimpleStringInstance end def self.describe Describe.new('ltrim', 4, [ 'write' ], 1, 1, 1, [ '@write', '@list', '@slow' ]) end end class LSetCommand < BaseCommand def call Utils.assert_args_length(3, @args) key = @args[0] index = Utils.validate_integer(@args[1]) new_value = @args[2] list = @db.lookup_list(key) if list.nil? RESPError.new('ERR no such key') elsif list.set(index, new_value) OKSimpleStringInstance else RESPError.new('ERR index out of range') end end def self.describe Describe.new('lset', 4, [ 'write', 'denyoom' ], 1, 1, 1, [ '@write', '@list', '@slow' ]) end end class LRemCommand < BaseCommand def call Utils.assert_args_length(3, @args) key = @args[0] count = Utils.validate_integer(@args[1]) element = @args[2] list = @db.lookup_list(key) if list.nil? RESPInteger.new(0) else RESPInteger.new(list.remove(count, element)) end end def self.describe Describe.new('lrem', 4, [ 'write' ], 1, 1, 1, [ '@write', '@list', '@slow' ]) end end class LPosCommand < BaseCommand def initialize(db, args) super @count = nil @maxlen = nil @rank = nil end def call Utils.assert_args_length_greater_than(1, @args) key = @args.shift element = @args.shift list = @db.lookup_list(key) parse_arguments unless @args.empty? if list.nil? NullBulkStringInstance else position = list.position(element, @count, @maxlen, @rank) if position.nil? NullBulkStringInstance elsif position.is_a?(Array) RESPArray.new(position) else RESPInteger.new(position) end end rescue ZeroRankError, NegativeOptionError => e RESPError.new(e.message) end def self.describe Describe.new('lpos', -3, [ 'readonly' ], 1, 1, 1, [ '@read', '@list', '@slow' ]) end private def parse_arguments until @args.empty? option_name = @args.shift option_value = @args.shift raise RESPSyntaxError if option_value.nil? case option_name.downcase when 'rank' rank = Utils.validate_integer(option_value) raise ZeroRankError if rank == 0 @rank = rank when 'count' count = Utils.validate_integer(option_value) raise NegativeOptionError, 'COUNT' if count < 0 @count = count when 'maxlen' maxlen = Utils.validate_integer(option_value) raise NegativeOptionError, 'MAXLEN' if maxlen < 0 @maxlen = maxlen else raise RESPSyntaxError end end end end class LInsertCommand < BaseCommand def call Utils.assert_args_length(4, @args) if ![ 'before', 'after' ].include?(@args[1].downcase) raise RESPSyntaxError else position = @args[1].downcase == 'before' ? :before : :after end pivot = @args[2] element = @args[3] list = @db.lookup_list(@args[0]) return RESPInteger.new(0) if list.nil? new_size = if position == :before list.insert_before(pivot, element) else list.insert_after(pivot, element) end RESPInteger.new(new_size) end def self.describe Describe.new('linsert', 5, [ 'write', 'denyoom' ], 1, 1, 1, [ '@write', '@list', '@slow' ]) end end class LIndexCommand < BaseCommand def call Utils.assert_args_length(2, @args) key = @args[0] index = Utils.validate_integer(@args[1]) list = @db.lookup_list(key) if list.nil? NullBulkStringInstance else value_at_index = list.at_index(index) if value_at_index RESPBulkString.new(value_at_index) else NullBulkStringInstance end end end def self.describe Describe.new('lindex', 3, [ 'readonly' ], 1, 1, 1, [ '@read', '@list', '@slow' ]) end end ### # Blocking ### class BLPopCommand < BaseCommand def call ListUtils.common_bpop(@db, @args, :lpop) do |list_name, list| @db.left_pop_from(list_name, list) end end def self.describe Describe.new('blpop', -3, [ 'write', 'noscript' ], 1, -2, 1, [ '@write', '@list', '@slow', '@blocking' ]) end end class BRPopCommand < BaseCommand def call ListUtils.common_bpop(@db, @args, :rpop) do |list_name, list| @db.right_pop_from(list_name, list) end end def self.describe Describe.new('brpop', -3, [ 'write', 'noscript' ], 1, -2, 1, [ '@write', '@list', '@slow', '@blocking' ]) end end class BRPopLPushCommand < BaseCommand def call Utils.assert_args_length(3, @args) source_key = @args[0] source = @db.lookup_list(source_key) timeout = Utils.validate_timeout(@args[2]) destination_key = @args[1] if source.nil? Server::BlockedState.new(BlockedClientHandler.timeout_timestamp_or_nil(timeout), [ source_key ], :rpoplpush, destination_key) else ListUtils.common_rpoplpush(@db, source_key, destination_key, source) end end def self.describe Describe.new('brpoplpush', 4, [ 'write', 'denyoom', 'noscript' ], 1, 2, 1, [ '@write', '@list', '@slow', '@blocking' ]) end end end <file_sep>/content/post/chapter-10-adding-sorted-set-commands.md --- title: "Chapter 10 Adding Sorted Sets Commands" date: 2020-11-16T19:33:26-05:00 lastmod: 2020-11-16T19:33:33-05:00 draft: false comment: false keywords: [] summary: "In this chapter we add support for the Sorted Set data type. We implement most of the sorted commands, such as ZADD, ZRANGE & BZPOPMAX" --- ## What we'll cover With support for Sets added in the previous chapter, our server is now only two data types short of the real Redis. In this chapter we will focus exclusively on Sorted Sets. Sorted sets are very similar to sets, with one major difference, instead of members being only strings, members are pairs of strings and floats, where the float value is used to sort members and is called the score. As mentioned in the previous chapters, Sets do not guarantee ordering and while the `IntSet` structure happened to provide a sorted data structure, the `Dict` class doesn't guarantee any ordering and calling `SMEMBERS` would not always return elements in the same order. Every command that returns all the elements in a set would show this behavior, which is the case for `SUNION`, `SDIFF` and `SINTER`. On the other hand, sorted sets guarantee ordering, but because the score value is not unique, members are sorted by the lexicographic of the member if scores are equal. Let's look at a few examples: ``` bash 127.0.0.1:6379> ZADD z 1.1 a 2.2 b 3.3 c 4 d 5.0 e 6e2 f 0 zero (integer) 7 127.0.0.1:6379> ZRANGE z 0 -1 1) "zero" 2) "a" 3) "b" 4) "c" 5) "d" 6) "e" 7) "f" 127.0.0.1:6379> ZRANGE z 0 -1 WITHSCORES 1) "zero" 2) "0" 3) "a" 4) "1.1000000000000001" 5) "b" 6) "2.2000000000000002" 7) "c" 8) "3.2999999999999998" 9) "d" 10) "4" 11) "e" 12) "5" 13) "f" 14) "600" ``` The first thing to note is that all sorted set commands are prefixed with a `Z`, and a sorted set if often referred to as a "zset" throughout the Redis codebase. As a matter of fact, all the sorted set commands are implemented in the [`t_zset.c`][redis-src-tzset] file. Members are added with `ZADD`, which accepts an even list of arguments after the key of the zset itself, `z` in the example, the first element of each member pair must be a valid float, as defined in the [Chapter 7][chapter-7] when we added the `HINCRBYFLOAT` command or in [Chapter 6][chapter-6] when we added validation for the timeout values for the blocking commands on lists. This means that besides "regular" values such as `5` or `26.2`, scores can also be expressed with the [E notation][wikipedia-e-notation], `7.03e1` for `70.3`, and the strings `inf` and `infinity`, with or without the `+` and `-` signs are accepted, in a case insensitive way. `ZRANGE 0 -1` returns all the members, without scores, similarly to the `LRANGE` command for lists. We can add the `WITHSCORES` option to include the scores. In both examples we can see that the order of elements in the RESP array returned by `ZRANGE` ordered the elements by their score values. You might have noticed that we've already observed issues with the accuracy of the float values. `a`, `b` & `c` all show rounding errors with the `WITHSCORES` option, which we can also illustrate with the `ZSCORE` command that returns the score of the given member: ``` bash 127.0.0.1:6379> ZSCORE z a "1.1000000000000001" 127.0.0.1:6379> ZSCORE z b "2.2000000000000002" 127.0.0.1:6379> ZSCORE z c "3.2999999999999998" ``` These issues are the exact same we discussed in [Chapter 7][chapter-7] when implementing the `HINCRBYFLOAT` command. That being said, we can see that the precision of the score value in a zset seems to be worse than what `HINCRBYFLOAT` provided: ``` bash 127.0.0.1:6379> HINCRBYFLOAT h a 1.1 "1.1" 127.0.0.1:6379> HGETALL h 1) "a" 2) "1.1" ``` This difference in precision is because Redis uses a `double` for the `score` field in a zset, whereas it uses a `long double` when performing the operation in `HINCRBYFLOAT`. One reason that might justify this choice is that values are stored as strings in a hash, so the extra bytes required to allocate a `long double` are only temporary, while performing the operation. On the other hand, the score is always stored as a number, alongside the member value as a string, in a zset, so the extra bytes required for a `long double` would affect the memory usage of the server significantly for large zsets. Let's approximate this difference. A `double` uses eight bytes, and a `long double` uses sixteen. Setting aside some of the overhead required by the data structure actually storing the sorted sets, we can infer that the size of a sorted set elements would be at least `'number of bytes in member' + 8` with a `double` and `'number of bytes in member' + 16` with a `long double`. While the difference might seem small, it means that a sorted set with 1,000,000,000 members would use an extra 8,000,000,000 bytes with a `long double`, 16,000,000,000 bytes compared to 8,000,000,000 bytes to store the scores, that's about 8 gigabytes (GB), or about 7.45 gibibytes (GiB) of memory! The two units are similar but different by a small factor, a kilobyte (KB) is 1,000 bytes, and a kibibyte (KiB) is 1,024 bytes, 2^10, a megabyte (MB) is 1,000,000 bytes, and a mebibyte (MiB) is 1,048,576 bytes, 2^20, or 1,204 * 1,024, and so on, you multiply by 1,000 in one case, and by 1,024 in the other. ISO-80000, or IEC 80000 is the standard the introduced these [Binary Prefix][wikipedia-binary-prefix] units. And we'll see in the next section that Redis actually stores the score twice, so this difference would actually be at least two bytes per member. It's also important to consider the trade-offs and the actual impact of these precision issues. It seems fair to expect a high level of precision for the increment commands, `INCRBYFLOAT` and `HINCRBYFLOAT`, as users are given the ability to perform operations on the values and use the results in their application. On the other hand, the score value is _only_ used for ordering, meaning that these precision issues aren't _that_ impactful, as long as they're consistent. In the previous example, despite the precision issues, we still observe the expected behavior, `1.1000000000000001` is lower than `2.2000000000000002` and the order of members is the same as if the scores had been precisely `1.1` and `2.2`. The consistency aspect is also important, because members are sorted by lexicographic order if members are equal, let's look at an example by adding another member with an identical score: ``` bash 127.0.0.1:6379> ZADD z 1.1 a (integer) 0 127.0.0.1:6379> ZADD z 1.1 aa (integer) 1 127.0.0.1:6379> ZADD z 1.1 ab (integer) 1 ``` The first `ZADD` call returned `0`, because the sorted set already contains the member `a`. The next two calls both returned `1` because `aa` and `ab` were both successfully added, with the same score as `a`, so let's look at the order of members now: ``` bash 127.0.0.1:6379> ZRANGE z 0 -1 1) "zero" 2) "a" 3) "aa" 4) "ab" 5) "b" 6) "c" 7) "d" 8) "e" 9) "f" 127.0.0.1:6379> ZRANGE z 0 -1 WITHSCORES 1) "zero" 2) "0" 3) "a" 4) "1.1000000000000001" 5) "aa" 6) "1.1000000000000001" 7) "ab" 8) "1.1000000000000001" 9) "b" 10) "2.2000000000000002" 11) "c" 12) "3.2999999999999998" 13) "d" 14) "4" 15) "e" 16) "5" 17) "f" 18) "600" ``` We can see that `aa` and `ab` were both added after `a` and before `b`. The three elements with identical scores are ordered by lexicographical order: `a < aa < ab`. While we could mimic the Redis behavior and use the Ruby `Float` class for the `score` value in a zset, and keep using `BigDecimal` for the increment operations, we will keep using `BigDecimal` to keep things simpler. As mentioned previously, the Server we're building does not try to optimize every single aspects, which we would be a losing battle by using such a high level language as Ruby. Redis supports [twenty eight (!!) commands][redis-sorted-set-commands] for Sorted Sets, and we'll implement all of them except `ZSCAN` for the same reasons outlined in [Chapter 8][chapter-8]. Because all the `*SCAN` commands are complicated and deserve their own chapter. - **ZADD**: Add one or more members (with their scores) to a sorted set, creating it if necessary - **ZCARD**: Return the _cardinality_ of the set, the number of members - **ZRANGE**: Return all the members with an index within the given range - **ZRANGEBYLEX**: Return all the members with a member value within the given lexicographic range - **ZRANGEBYSCORE**: Return all the members with a score value within the given score range - **ZSCORE**: Return the score of a member - **ZMSCORE**: Return the scores for all the given members - **ZRANK**: Return the rank, its 0-based index in the set, of a member - **ZREM**: Remove a member from the set - **ZREMRANGEBYLEX**: Remove all the members within the lexicographic range - **ZREMRANGEBYRANK**: Remove all the members within the rank range - **ZREMRANGEBYSCORE**: Remove all the members within the score range - **ZREVRANGE**: Return all the members with an index within the given range, sorted by descending score - **ZREVRANGEBYLEX**: Return all the members with an index within the given lexicographic range, sorted by descending lexicographic order - **ZREVRANGEBYSCORE**: Return all the members with an index within the given score range, sorted by descending score - **ZREVRANK**: Return the rank of a member, as if it was sorted by descending score - **ZINTER**: Return the intersection of multiple sets - **ZINTERSTORE**: Store the intersection of multiple sets in another key - **ZUNION**: Return the union of multiple sets - **ZUNIONSTORE**: Store the union of multiple sets in another key - **ZPOPMAX**: Remove the member with the highest score - **ZPOPMIN**: Remove the member with the smallest score - **BZPOPMAX**: Blocking variant of `ZPOPMAX` - **BZPOPMIN**: Blocking variant of `ZPOPMIN` - **ZCOUNT**: Count the number of members with a score in the given range - **ZLEXCOUNT**: Count the number of members within the given lexicographic range - **ZINCRBY**: Increment the score of a member Twenty-seven commands await us, it's gonna be a long chapter, and we have a lot of code to go through, buckle up! ## How Redis does it As we've seen in the last two chapters, Redis uses two underlying structures, depending on the size of the sorted sets to implement the sorted set API. The two criteria are similar to the ones used for the hash structure, the number of entries, configured through [`zset-max-ziplist-entries`][redis-conf-zset-max-entries], with a default value of `128` and the length of the members themselves, configured with [`zset-max-ziplist-value`][redis-conf-zset-max-value], with a default value of `64`. As long as the size of the sorted set is below `zset-max-ziplist-entries` and as long as each member's length is below `zset-max-ziplist-value`, the sorted set elements will be stored in a ziplist. The choice of a ziplist as a data structure for small sorted sets is driven by the same reasons Redis uses a ziplist for small hashes. Let's quickly confirm this with `redis-cli`, `DEBUG OBJECT`, `irb` and the `redis` gem: ``` 127.0.0.1:6379> ZADD z 0 1 (integer) 1 127.0.0.1:6379> DEBUG OBJECT z Value at:0x7fef01405b70 refcount:1 encoding:ziplist serializedlength:16 lru:11787108 lru_seconds_idle:3 ``` Now let's add 127 members to the sorted set: ``` ruby irb(main):001:0> require 'redis' => true irb(main):002:0> red = Redis.new; 127.times { |i| red.zadd('z', i, i) } => 127 ``` And let's inspect things back in `redis-cli`: ``` 127.0.0.1:6379> ZCARD z (integer) 128 127.0.0.1:6379> DEBUG OBJECT z Value at:0x7fa078f05810 refcount:1 encoding:ziplist serializedlength:533 lru:11787457 lru_seconds_idle:2 127.0.0.1:6379> ZADD z 0 b (integer) 1 127.0.0.1:6379> DEBUG OBJECT z Value at:0x7fa078f05810 refcount:1 encoding:skiplist serializedlength:1292 lru:11787463 lru_seconds_idle:2 127.0.0.1:6379> ZCARD z (integer) 129 ``` With 128 items the set is still using a ziplist, and as long as we get past that, it becomes a skiplist. If any of the two constraints is not met, Redis switches to a combination of a `dict` and a `skiplist`. The `dict` stores members as keys, which is similar to what we did in the previous chapter for sets, and the value is the score. While this is enough to guarantee uniqueness, as well as store the score values, it is problematic if we were to call the `ZRANGE` command to return the first element, with `ZRANGE z 0 0`. In order to know which member is the first one, we'd need to iterate through the whole `dict`, to find the member with the smallest score. In order to make these operations faster, Redis also stores the member and score values in a `skiplist`. A `skiplist` is a data structure that maintains its element sorted and provides some of the benefits of a linked list, such as efficient adding and removal operations, while also providing an efficient way to search for elements, with an O(logn) time complexity. Using a "regular" linked list would have an O(n) time complexity for search. Redis stores both the string and the score in the skiplist, allowing it to efficiently retrieve sorted set members based on their position according to the ordering by score. This position is called "rank". Implementing a skiplist is fairly complicated, and Redis uses a modified version which stores extra information, so given how much work we already have ahead of us, we will not implement it in this chapter. We will instead use a similar approach by modifying our `SortedArray` class. It's important to note that by using a sorted array, our sorted set implementation will suffer from the same problems we described about the ziplist becoming expensive to manipulate as they grow. This drawback is a conscious decision made in order to focus on other parts of the sorted set implementations, while keeping _some_ of the original ideas, that is the two data structures approach. The following is an illustration of what a skiplist looks like, the arrows can be seen as "express lanes". The [skiplist paper][skiplist-paper] goes into more details if you're interested in learning more about this structure: ![skiplist illustration](/img/skiplist.png) The tl;dr; is that the arrows seen above, the "express lanes", can be used to ignore big chunks of the list when searching for an element. The search process always starts from the top left, and follows arrows as needed. Say that we'd be searching for the number `7`, we'd follow the first arrow, see that nothing is on the other end, so move to the second arrow, it would point us to `4`, which given that we know that the list is sorted, gives us a chance to find `7` if we were to keep looping, following the arrow would take us to `6`, following it again would take us to the end of the list, so we would move to the one below and find `9`, which means that `7` cannot be found if we were to continue over there, so we keep going down, and land on `7`. The image below highlights all the steps that we would take to find `7`, where the red arrows show the paths we chose not to follow and the green ones the ones we did. ![skiplist illustration 2](/img/skiplist_highlight_1.png) The next example shows the path we would take if we were to search for `11`: ![skiplist illustration 2](/img/skiplist_highlight_2.png) Note that Redis optimizes a few things such as storing a reference to the tail of the list, which would have sped up the process to find `11`. --- ### Updating our SortedArray class As we mentioned earlier we will not implement a skiplist in this chapter, we will instead reuse our `SortedArray` class to store member/score pairs, ordered by their score, and by member if scores are equal. The initial version of `SortedArray` used to accept a `field` argument for its constructor, and it would use this field to order elements within the array. We used this with `SortedArray.new(:timeout)` to order `BlockedState` instances, which have a `timeout` field. The `field` was used to compare elements in blocks passed to `Array#bsearch_index` calls. The main change we want is for `SortedArray` instances to consider multiple fields, from left to right. The use case is that we want our `SortedArray` to store objects with a `score` field, and a `member` field, if the scores are different, we want elements to be ordered by score, otherwise, by `member`. In other words, the primary ordering is through scores and the member acts as a tiebreaker. It's worth noting that this approach, similarly to the skiplist in Redis, _does not_ enforce member uniqueness, this is the responsibility of the caller to check for member uniqueness and is what we will use a `Dict` for. There are different ways to solve the problem we're facing now, we could even create a new class, `ScoreAndMemberSortedArray`, and rename the current one to `TimeoutSortedArray`. Instead we will refactor the class to work with any number of fields. In order to do so, we will replace the argument from `field`, to `&block`, and let callers pass the block that will be fed to `bsearch_index`: ``` ruby require 'forwardable' module BYORedis class SortedArray extend Forwardable def_delegators :@underlying, :[], :delete_if, :size, :each, :delete_at, :shift, :bsearch_index, :map, :each_with_index, :pop, :empty? def initialize(&block) @underlying = [] @block = block end def push(new_element) if @underlying.empty? index = 0 else index = @underlying.bsearch_index do |element| @block.call(element, new_element) <= 0 end end index = @underlying.size if index.nil? @underlying.insert(index, new_element) end alias << push end end ``` _listing 10.1 The updated `push` method in the `SortedArray` class_ Note that we added the `Forwardable` module to delegate a bunch of methods directly to the underlying array. The only difference between the new `push` method and the old one is the `else` branch, it used to be: ``` ruby index = @underlying.bsearch_index do |element| element.send(@field) >= new_element.send(@field) end ``` The new version expects the block to return a "comparison value", which is what we explored in the previous chapter with the "spaceship operator". A negative value indicates that the left element is lower than the right one, `0` means that both elements are equal and a positive value means that left element is greater. While technically any negative or positive values are valid, the spaceship operator always returns `-1`, `0` or `1`. In the previous implementation, the block passed to `bsearch_index` was using the `find-minimum` mode, and was returning a boolean. The boolean would only be `true` if the field of the new element, `timeout` in practice, was lower than or equal to the one we're comparing it with in the array. As long as the `@block` given to the constructor is correctly created, it will return the same value, the following is the block that should be given for the behavior to stay the same: ``` ruby SortedArray.new do |array_element, new_element| new_element.timeout <=> array_element.timeout end ``` The block will return `-1` if: ``` ruby new_element.timeout < array_element.timeout ``` it will return `0` if: ``` ruby new_element.timeout == array_element.timeout ``` and will return `1` if ``` ruby new_element.timeout > array_element.timeout ``` The value returned by the block will be `<= 0` if and only if `new_element.timeout <= array_element.timeout`, so the behavior is the same! With this change, we can now create a `SortedArray` that compares multiple fields! ``` ruby SortedArray.new do |array_element, new_element| score_comparison = new_element.score <=> array_element.score if score_comparison == 0 new_element.member <=> array_element.member else score_comparison end end ``` If `score_comparison` is not `0`, then the scores are different, and by returning `score_comparison`, our `push` methods will end up ordering elements by `score` values. The difference is if the `score` values are equal, if `score_comparison == 0`, in this case we use the `member` values as tiebreaker, and return the result of the spaceship operators between the members values. Let's now update the `delete` method: ``` ruby module BYORedis class SortedArray # ... def delete(element) index = index(element) return if index.nil? element_at_index = @underlying[index] first_index_to_delete = nil number_of_items_to_delete = 0 while element_at_index if element_at_index == element first_index_to_delete ||= index number_of_items_to_delete += 1 end index += 1 next_element = @underlying[index] if next_element && @block.call(next_element, element_at_index) == 0 element_at_index = next_element else break end end @underlying.slice!(first_index_to_delete, number_of_items_to_delete) end def index(element) if @underlying.empty? nil else @underlying.bsearch_index do |existing_element| @block.call(existing_element, element) end end end end end ``` _listing 10.2 The updated `delete` method in the `SortedArray` class_ There are two differences between the new `delete` method and the previous one. First, we extracted an `index` method to return the `index` of a member, or `nil` if the element is not present. The `index` method uses the `@block` variable with `bsearch_index`, but this time it passes the result of the block directly, which uses the `find-any` mode, in which it will return the index of the element, if it exists, and `nil` otherwise. Note that if there are duplicates, the left-most element is returned in this mode. The rest of the `delete` method is almost identical, we grab the element at index `index`, and as long as they are equal according to `@block`, which we check with `@block.call(next_element, element_at_index) == 0`, we keep going right. This last step was necessary for the `timeout` based use case. In the timeout array we might end up with multiple values sharing the same timeout, in which case, we want to find `element` within these. #### Final touches Creating a new instance of `SortedArray` is now a bit tedious, you need to know how to craft the `block` argument for it to work as expected, here is what it would look like to replace the `timeout` based sorted array: ``` ruby SortedArray.new do |array_el, new_el| new_el.timeout <=> array_el.timeout end ``` It is even more complicated with our new use case, where we want to order items in the array by `score`, and fallback to `member` if the scores are equal: ``` ruby SortedArray.new do |array_el, new_el| score_comparison = new_el.score <=> array_el.score if score_comparison == 0 new_el.member <=> array_el.member else score_comparison end end ``` Let's improve this by providing a class method on `SortedArray` that creates the correct block based on the given fields: ``` ruby module BYORedis class SortedArray # ... def self.by_fields(*fields) SortedArray.new do |array_element, new_element| comparison = nil fields.each do |field| comparison = new_element.send(field) <=> array_element.send(field) # As long as the members are equal for field, we keep comparing if comparison == 0 next else break end end comparison end end end end ``` _listing 10.3 The `by_fields` class method for `SortedArray`_ We can now easily create a sorted array for `BlockedState` with: ``` ruby SortedArray.by_fields(:timeout) ``` And one for sorted set members with `score` and `member` attributes: ``` ruby SortedArray.by_fields(:score, :member) ``` Perfect! ## Creating and Updating Sorted Sets With regular sets there is no concept of "update", an element is a member of a set, or it isn't, we can either add it or remove it. Things are different with sorted sets, now that members have a score value associated with them, we can update the score of an existing member in a sorted set. All these operations are performed with the `ZADD` command. We only saw some of the ways in which it can be used in the introduction to this chapter. It's now time to add it to our server. ### The ZADD command In its simplest form, the `ZADD` command uses the format: `zset-key score, member ...` where `score` needs to be a valid float and _must_ be followed by a string value as the member. We've already looked at some examples earlier in the chapter, so let's now look at all the possible options: - `NX|XX`: With `NX`, members can only be added and are never updated and `XX` never adds new members, it only updates existing ones. The two options are mutually exclusive. - `LT|GT`: These two options have been added in 6.2.0 and have not yet been implemented in this book. Only updates the members if the new score is respectively lower than or greater than the existing score - `CH`: Return the number of changed, where "changed" means members added, or members updated. By default only the number of added member is returned - `INCR`: Limit the number of score/member pair to one, and increment the score for the given member by the new score, defaulting to `0` if the member was not present in the set. The `INCR` option changes the return value to the new score and ignores the `CH` option. The format is described as the following by the [Redis Documentation][redis-doc-zadd]: ``` ZADD key [NX|XX] [GT|LT] [CH] [INCR] score member [score member ...] ``` Let's look at some examples now: ``` bash 127.0.0.1:6379> ZADD z NX CH INCR 10.1 a "10.1" 127.0.0.1:6379> ZADD z NX CH 5 a 2.2 b (integer) 1 127.0.0.1:6379> ZRANGE z 0 -1 WITHSCORES 1) "b" 2) "2.2000000000000002" 3) "a" 4) "10.1" 127.0.0.1:6379> ZADD z CH 5 a 2.2 b (integer) 1 127.0.0.1:6379> ZRANGE z 0 -1 WITHSCORES 1) "b" 2) "2.2000000000000002" 3) "a" 4) "5" 127.0.0.1:6379> ZADD z CH 5 a (integer) 0 127.0.0.1:6379> ZADD z CH 6 a (integer) 1 127.0.0.1:6379> ZRANGE z 0 -1 WITHSCORES 1) "b" 2) "2.2000000000000002" 3) "a" 4) "6" ``` The first command, with the `INCR` option shows how it uses a default score value of `0` and added `10.1` to it. The `CH` option was overridden by the `INCR` option and the `NX` option did not do anything since the member was not already present. In the second example, `NX` blocked `a` from being updated and only `b` was added, which counts as an update and is counted with the `CH` option. The same command without the `NX` option updates both `a` and `b`, but because `b` has the same score, it is not updated and the count only includes the updated score of `a`. The next command shows a changed count of `0` because the score is the same. Finally, changing the score to a different value, `6`, returns a changed count of `1`. Let's start by creating the `sorted_set_commands.rb` file with the `ZAddCommand` class. ``` ruby require_relative './redis_sorted_set' module BYORedis class ZAddCommand < BaseCommand def call @options = { presence: nil, ch: false, incr: false, } Utils.assert_args_length_greater_than(1, @args) key = @args.shift parse_options raise RESPSyntaxError unless @args.length.even? if @options[:incr] && @args.length > 2 raise ValidationError, 'ERR INCR option supports a single increment-element pair' end pairs = @args.each_slice(2).map do |pair| score = Utils.validate_float(pair[0], 'ERR value is not a valid float') member = pair[1] [ score, member ] end sorted_set = @db.lookup_sorted_set_for_write(key) return_count = 0 pairs.each do |pair| sorted_set_add_result = sorted_set.add(pair[0], pair[1], options: @options) if @options[:incr] if sorted_set_add_result return_count = Utils.float_to_string(sorted_set_add_result) else return_count = nil end elsif sorted_set_add_result return_count += 1 end end RESPSerializer.serialize(return_count) rescue FloatNaN RESPError.new('ERR resulting score is not a number (NaN)') end def self.describe Describe.new('zadd', -4, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@sortedset', '@fast' ]) end private def parse_options @options = {} loop do # We peek at the first arg to see if it is an option arg = @args[0] case arg.downcase when 'nx', 'xx' then set_presence_option(arg.downcase.to_sym) when 'ch' then @options[:ch] = true when 'incr' then @options[:incr] = true else # We found none of the known options, so let's stop here break end # Since we didn't break, we consume the head of @args @args.shift end end def set_presence_option(option_value) if @options[:presence] && @options[:presence] != option_value raise ValidationError, 'ERR XX and NX options at the same time are not compatible' else @options[:presence] = option_value end end end end ``` _listing 10.4 The `ZAddCommand` class in `sorted_set_commands.rb`_ Handling all the various options makes the method longer than most other commands, let's slowly step through it. We initially create a hash of default values for the three options, `presence`, which has three possible values, `nil`, the default, `nx`, or `px`. `ch` defaults to `false` and will be set to `true` only we find the `ch` option among the arguments. Finally, `incr` defaults to `false` and will be switched to `true` if we find `incr` among the arguments. The validation of the length of the `@args` array is not as simple as it usually is, so we start by checking that we have _at least_ one argument, and we'll perform more validations later on. The first argument is the key of the sorted set, so we extract it with `Array#shift` and delegate the options handling to the private method `parse_options` The tricky thing about `parse_options` is that it operates on an array of arguments, but it doesn't know if it contains any options, since they're all optional, so if `@args` was set to `[ '1', 'a', '2', 'b' ]`, it shouldn't do anything, but if the first elements of the array are valid options, it needs to extract and process them. We use a "peek" approach, we look at the head of `@args`, with `@args[0]`, and compare it with all the valid option values. We use `String#downcase` to make sure that we handle any case variants of the options, such as `InCr` or `nx`. If we find either `nx` or `xx`, we call `set_presence_options`. This method takes care of returning an error if the arguments contained both `nx` and `xx`, which is invalid, as well as setting the value in `@options[:presence]`. Back to `parse_options`, the other two cases are `ch` and `incr`, in either situation we set the corresponding value to `true` in the `@options` hash. If the head of `@args` does not match any of these cases, we abort the loop and exit the method, we're done parsing options and we need to treat all the remaining elements as score/member pairs. If we did not exit the loop early with `break`, we reach the last line `@args.shift`, which effectively "consumes" the head of `@args` so that the next iteration sees the next element when it peeks at the head again. Back to `call`, all valid options have been shifted from `@args`, and an exception was raise if any of the options were invalid, so if we're back in `call` we know we have to handle all the elements in `@args` as member/score pairs. We start by checking that we have an even number of elements in the arguments array, to make sure that we're indeed dealing with pairs. Redis fails early in this case. It could technically process the elements one by one and abort when it fails to find a pair of element, but it instead validates the arguments eagerly. Next up, we need to confirm that we only received a single score/member pair if `@options[:incr]` was set to `true` through the `INCR` option. If all these checks pass, we iterate over all the elements, two at a time with `each_slice(2)` and validates that first element of each pair is a valid float string. The array returned by `Array#map` will be an array of pairs, where the first element of the pair is the score, as a `BigDecimal` and the second element is the member, as a `String`. Now that all the validations are behind us, we load the sorted set with `DB#lookup_sorted_set_for_write`, which we need to write: ``` ruby module BYORedis class DB # ... def lookup_sorted_set(key) sorted_set = @data_store[key] raise WrongTypeError if sorted_set && !sorted_set.is_a?(RedisSortedSet) sorted_set end def lookup_sorted_set_for_write(key) sorted_set = lookup_sorted_set(key) if sorted_set.nil? sorted_set = RedisSortedSet.new @data_store[key] = sorted_set if @blocking_keys[key] @ready_keys[key] = nil end end sorted_set end end end ``` _listing 10.5 The `DB#lookup_sorted_set_for_write` method_ The `@ready_keys[key] = nil` line, under the `if @blocking_keys[key]` condition is similar to what we had to write in `lookup_list_for_write` when adding the `BLPOP` and `BRPOP` commands. We're dealing with a similar situation here, blocking commands such as `BZPOPMIN` and `BZPOPMAX`, which will be implemented later in this chapter, can cause clients to be blocked until a sorted set can be popped from. The same way that Redis never stores empty list, it also never stores empty sorted sets, and the same applies to hashes and sets, which means that whenever we create a new sorted set, we might be able to unblock a client blocked for that key, adding it to `ready_keys` will allow us to check for that. We'll explore this in more details when adding the two blocking commands for sorted sets. Once the `sorted_set` variable is created, we initialize the `return_count` variable, its content will depend on the value of `@options[:ch]` or `@options[:incr]`. We then iterate over the `pairs` array, and for each pair we call `RedisSortedSet#add` with the score, the member and the `@options` hash. If `@options[:incr]` was set to `true` we store the value returned by `RedisSortedSet#add`, as a `BigDecimal` in `return_count` and return it with `RESPSerializer`, which will either return the new cardinality as RESP integer or the new score, as string, since RESP2 does not have a dedicated float type. We now need to dive into the `RedisSortedSet#add` method, which is the one that _actually_ adds items to the sorted set: ``` ruby require 'bigdecimal' require_relative './dict' require_relative './list' require_relative './zset' module BYORedis class RedisSortedSet Pair = Struct.new(:score, :member) attr_reader :underlying def initialize @underlying = List.new end def add(score, member, options) convert_to_zset if @underlying.is_a?(List) && member.length > Config.get_config(:zset_max_ziplist_value) case @underlying when List added = add_list(score, member, options) convert_to_zset if added && @cardinality >= Config.get_config(:zset_max_ziplist_entries) added when ZSet then @underlying.add(score, member, options) else raise "Unknown type for #{ @underlying }" end end private def convert_to_zset raise "#{ @underlying } is not a List" unless @underlying.is_a?(List) zset = ZSet.new @underlying.each do |pair| zset.dict[pair.member] = pair.score zset.array << pair end @underlying = zset end end end ``` _listing 10.6 The `RedisSortedSet#add` method_ We declare a new `Struct` at the beginning of the class, `Pair`, which will hold the score/member pairs inside the `List` or within the `ZSet`. The `ZSet` class is the class that will coordinate the `Dict` and `SortedArray` instances, as described earlier in the chapter: ``` ruby module BYORedis class ZSet attr_reader :dict, :array def initialize @dict = Dict.new @array = SortedArray.by_fields(:score, :member) end end end ``` _listing 10.7 The `ZSet` class_ Back to `RedisSortedSet#add`, we use the tried and true pattern of a `case/when` against `@underlying` to determine which data structure we're currently dealing with. In the `List` case we delegate the logic to the `add_list` private method, and in the `ZSet` case we use the `ZSet#add` method. Before looking at the process of adding or updating the score and member values in the `List` or the `ZSet`, let's take a look at the `convert_to_zset` method. We need to iterate through all the elements in the list to add them to the newly created `ZSet`, so instead of using the `List.left_to_right_iterator`, which is pretty verbose, let's add the `List#each` method: ``` ruby module BYORedis class List # ... def each(&block) raise 'No block given' unless block iterator = List.left_to_right_iterator(self) while iterator.cursor block.call(iterator.cursor.value) iterator.next end end # ... end end ``` _listing 10.8 The `List#each` method_ We won't always be able to use the `each` method, there are cases where we'll need to have a hold of the `ListNode` instance, to check the value of its `prev_node` for instance, and in these cases we'll still need to use `List.left_to_right_iterator`. We're about to see an example in the `add_list` method below. Once all the members from the `List` instances have been added to the `ZSet` one, we update `@underlying` to point at the latter and let the Garbage Collector do its job to get rid of the list. Let's now dive in `RedisSortedSet#add_list`: ``` ruby module BYORedis class RedisSortedSet # ... private def add_list(score, member, options: {}) raise "#{ @underlying } is not a List" unless @underlying.is_a?(List) unless [ nil, :nx, :xx ].include?(options[:presence]) raise "Unknown presence value: #{ options[:presence] }" end iterator = List.left_to_right_iterator(@underlying) while iterator.cursor cursor = iterator.cursor pair = iterator.cursor.value if pair.member == member # We found a pair in the list with a matching member if pair.score == score && !options[:incr] # We found an exact match, without the INCR option, so we do nothing return false elsif options[:presence] == :nx # We found an element, but because of the NX option, we do nothing return false else # The score changed, so we might need to reinsert the element at the correct # location to maintain the list sorted new_score = options[:incr] ? Utils.add_or_raise_if_nan(pair.score, score) : score prev_node = cursor.prev_node next_node = cursor.next_node if (next_node.nil? || next_node.value.score > new_score || (next_node.value.score == score && next_node.value.member > member)) && (prev_node.nil? || prev_node.value.score < new_score || (prev_node.value.score == score && prev_node.value.member < member)) cursor.value.score = new_score else @underlying.remove_node(cursor) # We add the node back, which takes care of finding the correct index unless add_list(new_score, member) raise 'Unexpectedly failed to re-insert node after update' end end if options[:incr] return new_score else # If options[:ch] == true, then we want to count this update and return true return options[:ch] end end elsif pair.score > score || (pair.score == score && pair.member > member) # As soon as we find a node where its score is greater than the score of the # element we're attempting to insert, we store its reference in `location` so that # we can use insert_before_node below. # In case of a score equality, the right side of the || above, we use the # lexicographic order of the member value to sort them # We cannot stop here however because there might be an exact member match later in # the list, in which case the `if pair.member == member` check above will trigger # and return location ||= cursor if options[:member_does_not_exist] break else iterator.next end elsif pair.score < score || (pair.score == score && pair.member < member) # In this case we haven't found a node where the score is greater than the one we're # trying to insert, or the scores are equal but the lexicographic order tells us that # member is greater than the current node, so we keep searching for an insert location # to the right iterator.next else # We've covered all cases, this is never expected to happen raise "Unexpected else branch reached for #{ score }/#{ member }" end end return false if options[:presence] == :xx new_pair = Pair.new(score, member) if location @underlying.insert_before_node(location, new_pair) else @underlying.right_push(new_pair) end if options[:incr] score else true end end end end ``` _listing 10.9 The `RedisSortedSet#add_list` method_ There is _a lot_ going on in there, let's go through all of it very slowly. The first few lines take care of performing some sanity checks, if `@underlying` is not a `List`, we raise an exception, if `options[:presence]` is not one of the valid values, we also raise an exception. These cases fall in the category of "bugs", they're not expected, and there's not much we could do beside reporting the error to the administrator of the server. Being so aggressive with the error handling, raising an error and letting it crash will ideally help catching these errors during the development phase. --- As a quick aside, there are different philosophies with regard to how errors like this one should be handled. Redis uses the [`serverPanic` macro][redis-src-server-panic] in a few places such as when the encoding of what it expects to be a sorted set is neither a skiplist or ziplist. This macro ends up calling `exit(3)`, with the argument `1`, the C function that exits the current process, and `1` signifies an error, `0` is the exit code for success. In this case, we could eventually rescue the exception and return an error to the user saying something like: "Something went wrong", similar to a web server returning a 500 HTTP response. This would let the server running and potentially serve other requests. That being said, some errors might be severe enough that we should worry about the state of the server and crashing might be safer than letting it run, potentially returning invalid values. There are also approaches where the behavior would be different in development or debug mode versus release or production mode, where the errors would be aggressively uncaught during the development phase to increase the likelihood of a developer catching them. This is a topic that would probably deserve its own book and as a conclusion note that the approach we're taking here is _one_ approach, among many others. --- Next, we create a `List` iterator with `List.left_to_right_iterator`, and we start iterating in a `while` loop over each element in the `List`. We will need to inspect the neighbors of the current node below, and as we explained earlier, this is why we cannot use the new `List#each` method here. Each element of the list is a `Pair` instance, with `score` & `member` methods. If `pair.member == member`, it's a match! We found a member in the sorted set that matches the one we're trying to insert. In this case we will handle the update in the `if` branch and return from there, but the code in there is the most complicated part of the method, so let's skip over it for now and we'll get back to it later. The next branches of the `if` are: ``` ruby pair.score > score || (pair.score == score && pair.member > member) ``` and: ``` ruby pair.score < score || (pair.score == score && pair.member < member) ``` The first one can be translated in plain English as "if the score of item under the cursor is greater than the score we're trying to add OR if the score of the item under the cursor is the same as the score we're trying to add but the member value, a string, of the item under the cursor is greater than the one we're trying to add". This is the case where we found the direct successor of the new element, and we should insert the new pair before it. There's a trick though! Even though it looks like we found the right place to insert the new pair in the list, this might not be true yet, we cannot know for sure at this point. If we made it to this branch, it means we have not yet found a pair with a matching member. So there are two possibilities here. Either the member is not in the set, and this is where it should be inserted, or, the member is in the set, with a greater score, further in the list. So we need to keep iterating through the list, just in case one of the elements we have not looked at yet is a match on `member`. The following is an example of this situation: ``` 127.0.0.1:6379> ZADD z 10.0 a 3.0 b (integer) 2 127.0.0.1:6379> ZRANGE z 0 -1 WITHSCORES 1) "b" 2) "3" 3) "a" 4) "10" 127.0.0.1:6379> ZADD z INCR 1 a "11" ``` If we had stopped right after `location ||= cursor`, then we would have inserted `<1, 'a'>` before `<3, 'b'>`, and ended up with a duplicated `'a'` in the set! We use the "or equals" operator, which will only assign a value if the left operand is truthy. We might find other members in the list that have greater scores or greater members, but we still want to keep the location of the first of those to determine which node should be the successor of the one we're trying to add. The second `elsif`, `pair.score < score || (pair.score == score && pair.member < member)` might as well had been written as an `else`, but writing as such allows us to catch bugs, because this is the only condition we'd expect to happen: "if the score of the item under the cursor is lower than the score we're trying to add, OR if the score of the item under the cursor is the same as the score we're trying to add but the member value, a string, of the item under the cursor is lower than the one we're trying to add". In other words, the new member should be added the further in the list, so we need to keep looking for the correct value for `location`. If we exited the loop without finding a match, and `options[:presence]` was set to `xx`, then we return `false`, because `xx` forbids the addition of new elements, and we are about to add a new element now. If `options[:presence]` is anything else, `nil` or `nx`, we are allowed to add new set members and we proceed to instantiating a new `Pair` with `score` and `member`. Now we need to decide where to insert `new_pair` in the `List`, with the constraint that we should maintain the elements sorted by `score`, and `member` if their `score` values are equal. It turns out that we skipped this step, while iterating through the list, we'll store a reference to the element that should succeed `new_pair`, in the `location` variable, and we call `List#insert_before_node` to add the set member. If we failed to set a `location`, it means that we did not find an element that should succeed `new_pair`, in which case we insert it last with `List#right_push`. The last step of the method is to decide what to return, if `options[:incr]` was set, we want to return the score of the new pair, otherwise we return `true`, to indicate that an element was added, which counts as a change no matter what, meaning that we count it regardless of the value of `options[:ch]`. The `List#insert_before_node` is a new one, let's look at it: ``` ruby module BYORedis class List # ... def insert_before_node(pivot_node, element) new_node = ListNode.new(element, pivot_node.prev_node, pivot_node) if @head == pivot_node @head = new_node else pivot_node.prev_node.next_node = new_node end pivot_node.prev_node = new_node @size += 1 end def insert_before(pivot, element) generic_insert(pivot) do |node| insert_before_node(node, element) end end def insert_after(pivot, element) generic_insert(pivot) do |node| new_node = ListNode.new(element, node, node.next_node) if @tail == node @tail = new_node else node.next_node.prev_node = new_node end node.next_node = new_node @size += 1 end end # ... private def generic_insert(pivot) cursor = @head while cursor break if cursor.value == pivot cursor = cursor.next_node end if cursor.nil? -1 else yield cursor @size end end end end ``` _listing 10.10 The `insert_before_node` refactor in the `List` class_ We use to be able to only have `insert_before` and `insert_after`, which both operate based on a `pivot` value, which they look for in the list. Both were initially created for the `LINSERT` command. But while we could still use `insert_before` here, it would be wasteful to start iterating from the start of the list if we already had a reference to the node we wanted to use as the insertion point. So this is what this refactor is about, `insert_before` and `insert_after` still have the same behavior, but `insert_before` is now written in terms of `insert_before_node`, a new method containing code that used to be in `insert_before`. We used to increment the `@size` instance variable in `generic_insert`, but because `insert_before_node` does not call it, we need to move it to make sure that calling either of three insert methods correctly increment the instance variable. Let's go back to `RedisSortedSet#add`, inside the `while` loop, inside the `if pair.member == member` condition. We first check if `pair.score == score`, in which case we found an exact match, there is a member in the set with the same `score` and the same `member`, which means that we usually have nothing to do, except if `option[:incr]` is set. In which case it doesn't matter what the current score is, we want to add the value in the `score` argument to the `score` that was already in the set. Next, if `options[:presence] == :nx`, then updates are forbidden, we're only allowed to add new elements, and since we found a match on `member`, we can return early, since we're about to update the existing pair. One more `else` branch, hang in there with me. We now need to perform an update, we found the node in the list that contains the member, but there are a few different possibilities depending on the values in `options`. First, we compute the new score, if `options[:incr]` is `true`, then we need to add the existing score to the new one, but we need to watch out for "invalid float values". What is an "invalid float value" you ask? Let's look at an example: ``` ruby irb(main):001:0> require 'bigdecimal' => true irb(main):002:0> inf = BigDecimal::INFINITY irb(main):003:0> inf + inf => Infinity irb(main):004:0> inf - inf => NaN ``` We can't subtract `inf` from `inf`, it's **N**ot a **N**umber, let's confirm this in redis: ``` ruby 127.0.0.1:6379> ZADD z INCR inf a "inf" 127.0.0.1:6379> ZADD z INCR -inf a (error) ERR resulting score is not a number (NaN) ``` We handle this with the `Utils.add_or_raise_if_nan` method: ``` ruby module BYORedis # ... IntegerOverflow = Class.new(StandardError) FloatNaN = Class.new(StandardError) InvalidIntegerString = Class.new(StandardError) InvalidFloatString = Class.new(StandardError) module Utils # ... def self.add_or_raise_if_nan(a, b) BigDecimal.save_exception_mode do BigDecimal.mode(BigDecimal::EXCEPTION_NaN, true) a + b end rescue FloatDomainError raise FloatNaN end end end ``` _listing 10.11 The `Utils.add_or_raise_if_nan` method_ We use the `save_exception_mode` so that we don't modify the behavior of `BigDecimal` operations once we're done here, and if it does raise an exception, `FloatDomainError`, we convert it to our own exception, `FloatNaN`, which we added at the top of the `utils.rb` file. If we're not in increment mode, then the new score is the `score` argument, we override what was there before. So now, we have the new score, we need to update it, we _could_ change the value in the list node with `cursor.value.score = new_score`, but how do we know if the node will still be where it should be in the list once the score is updated? Well, we can check for it. This is what this weird looking condition does: > If there is no next node, the current node is the last one, or if there is a next node, and that next node score is greater than the updated score of the current node, or if the scores are equal but the next node's member string is greater than the string of the current member > > AND > > If there is no previous node, the current node is the first one, or if there is a previous node, and that previous node score is lower than the updated score of the current node, or if the scores are equal but the previous node's member string is lower than the string of the current member > > THEN > > The list will still be in order after the score update If this condition fails, the current node will not be in the right place after the score update. Instead of trying to find the correct location, we remove the node and call `RedisSortedSet#add` again, with the new score, and we know it won't find the member so we pass the `member_does_not_exist` option to `break` right after `location ||= cursor`, to prevent a full iteration of the list: ``` ruby # ... elsif pair.score > score || (pair.score == score && pair.member > member) # ... location ||= cursor if options[:member_does_not_exist] break else iterator.next end elsif pair.score < score # ... # ... ``` _listing 10.12 The `member_does_not_exist` option handling in the `RedisSortedSet#add_list` method_ Done! That's it, we can add members to a sorted set ... as long as it uses a `List` under the hood, we need to handle the other case, when the strings are either too big, or the sorted set contains too many entries. #### Adding Members to a ZSet Luckily the process is not as complicated in a `ZSet`, thanks the easier lookup in a `Dict`. Let's create the `ZSet#add` method: ``` ruby module BYORedis class ZSet # ... def add(score, member, options) unless [ nil, :nx, :xx ].include?(options[:presence]) raise "Unknown presence value: #{ options[:presence] }" end entry = @dict.get_entry(member) if entry return false if options[:presence] == :nx if entry.value != score || options[:incr] existing_pair = new_pair(entry.value, member) index = @array.index(existing_pair) if index.nil? raise "Failed to find #{ member }/#{ entry.value } in #{ @array.inspect }" end array_element = @array[index] while array_element.member != member && index < @array.size index += 1 array_element = @array[index] end if index == @array.size raise "Failed to find #{ member }/#{ entry.value } in #{ @array.inspect }" end new_score = options[:incr] ? Utils.add_or_raise_if_nan(entry.value, score) : score next_member = @array[index + 1] prev_member = @array[index - 1] if (next_member.nil? || next_member.score > new_score || (next_member.score == new_score && next_member.member > member)) && (prev_member.nil? || prev_member.score < new_score || (prev_member.score == new_score && prev_member.member < member)) array_element.score = new_score else @array.delete_at(index) @array << new_pair(new_score, member) end entry.value = new_score end if options[:incr] new_score else options[:ch] # false by default end else return false if options[:presence] == :xx @array << new_pair(score, member) @dict[member] = score if options[:incr] score else true end end end private def new_pair(score, member) RedisSortedSet::Pair.new(score, member) end end end ``` _listing 10.13 The `ZSet#add` method_ First we use the `Dict#get_entry` method to check for the existence of `member` in the sorted set. Things are already simpler here, we don't have to iterate over anything to determine the presence of the member we're trying to add or update. If we found a match but `options[:presence]` is set to `:nx` then updates are forbidden and we can stop right away by returning `false`. If the `score` value of the existing member is the same as the one we're trying to add, there's nothing to do, the update would be a no-op, except if `options[:incr]` is set to `true`, in which case we want to sum the existing `score` and the new one. This is what we check with `if entry.value != score || options[:incr]`, if this condition is true, we do want to update the score of the existing member. `entry` is the result of calling `Dict#get_entry` and is a `DictEntry` instance where `key` is the score and `value` is the member. We create an instance of `Pair` to facilitate the interaction with the `SortedArray`, such as calling `SortedArray#index` to find the position of the pair in the sorted set. We always expect to find the pair in the sorted array, because we do the bookkeeping work necessary to maintain the consistency between the `Dict` and the `SortedArray`, but it is technically possible that `SortedArray#index` returns `nil`, and in this case we throw an exception. This is another instance of a case that falls in the category of "bugs", unexpected situations where there's nothing we can really do, and we might as well notify the administrator of the server with a crash and hope that these bugs would be caught in the development phase. The next check is pure paranoia and could be considered useless, but we double check that the value at index `index` is indeed equal to `existing_pair`. Since returning the index for the given value is the contract of the `SortedArray#index` method you might wonder why we'd want to perform it. The main reason here is that such check is "cheap" in the sense of it not requiring a lot of extra instructions, and it would catch obvious bugs in the `SortedArray#index` method, so why not! Back to the `add` method, we're using `Utils.add_or_raise_if_nan` similarly to how we did in the `List` case, to handle cases such as `inf - inf`. Next we perform the same check to see if the existing member's position in the sorted array will still be correct after the update. We compare it with the next and previous elements in the array, if they exist. If the order would not be broken, then we update the `Pair` instance, otherwise we delete it with `SortedArray#delete_at`, which is delegated to `Array#delete_at` and we insert it again, letting the `SortedArray` class find the new position. Finally, we update the value in `Dict` with `entry.value = new_score`. The return value after an update depends on the values of `options[:incr]` and `options[:ch]`. As we've seen earlier, the `INCR` option takes precedence, in which case we return the new score, otherwise we return `false` by default, if it was an update, or `true`, if the `CH` option was used and updates should be counted. The `else` branch handles the case where the member does not exist in the set, in which case we return `false` early if the `XX` option was used, forbidding adding members and only allowing updates. Otherwise, we add the `Pair` instance to the sorted array and add the score and member to the `Dict`. We use a logic similar to what we just did to determine the return value, except that regardless of the presence or not of the `CH` option, we always return `true` as additions always count as changes. And here we are! The `ZADD` command works! #### Counting members in a Sorted Set Now that we added the ability to create sorted sets and to add new members to them, let's add the `ZCARD` command to count the number of members in a sorted set: ``` ruby module BYORedis # ... class ZCardCommand < BaseCommand def call Utils.assert_args_length(1, @args) sorted_set = @db.lookup_sorted_set(@args[0]) cardinality = sorted_set&.cardinality || 0 RESPInteger.new(cardinality) end def self.describe Describe.new('zcard', 2, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@sortedset', '@fast' ]) end end end ``` _listing 10.14 The `ZCardCommand` class_ We call the `cardinality` method on the `RedisSortedSet` instance, with the "safe navigation" operator, `&.`, which returns `nil` if `sorted_set` itself is `nil`, which would then take us to the right side of the `||` operator and effectively default `cardinality` to `0`. Let's add the `RedisSortedSet#cardinality` method: ``` ruby module BYORedis class RedisSortedSet # ... def cardinality case @underlying when List then @underlying.size when ZSet then @underlying.cardinality else raise "Unknown type for #{ @underlying }" end end # ... end end ``` _listing 10.15 The `RedisSortedSet#cardinality` method_ In the `List` case we return the result of calling `List.size`, and for a `ZSet`, we need to add the `cardinality` method to the class: ``` ruby module BYORedis class ZSet # ... def cardinality @array.size end end end ``` _listing 10.16 The `ZSet#cardinality` method_ We could have included `Forwardable` and used it to delegate `#size` to `@array`, but there's only one method we need to directly delegate, so the "cost" of manually doing the delegation is really small compared to the "complexity" of including a module, and calling `def_delegators`, which doesn't save us much for only one method. This wraps up the first two commands for sorted sets, `ZADD` & `ZCARD`, next we'll look at the different range commands. ## Reading from Sorted Sets With `ZADD` implemented, we will now add commands to retrieve elements from sorted sets. We've already seen the `ZRANGE` command, but Redis provides two more similar commands, `ZRANGEBYSCORE` & `ZRANGEBYLEX`. Re-using the sorted set `z` from earlier in the chapter, we can use `ZRANGEBYSCORE` to only select a range of members within the given score, whereas `ZRANGE` returns member depending on their index in the sorted set, their rank. If `ZRANGE` had a more explicit name it'd be called `ZRANGEBYRANK`. ``` bash 127.0.0.1:6379> ZRANGEBYSCORE z 0 1 1) "zero" 127.0.0.1:6379> ZRANGEBYSCORE z 0 3 1) "zero" 2) "a" 3) "aa" 4) "aaa" 5) "ab" 6) "b" 127.0.0.1:6379> ZRANGEBYSCORE z 0 3 WITHSCORES 1) "zero" 2) "0" 3) "a" 4) "1.1000000000000001" 5) "aa" 6) "1.1000000000000001" 7) "aaa" 8) "1.1000000000000001" 9) "ab" 10) "1.1000000000000001" 11) "b" 12) "2.2000000000000002" ``` The equivalent of `ZRANGE z 0 -1`, that is, "return all the members" is `ZRANGE z -inf +inf`. This works because all possible values, including `-inf`, are greater than or equal to `-inf`, and all possible values, including `+inf` are lower than or equal to `+inf`. ``` bash 127.0.0.1:6379> ZRANGEBYSCORE z -inf +inf 1) "zero" 2) "a" 3) "aa" 4) "aaa" 5) "ab" 6) "b" 7) "c" 8) "d" 9) "e" 10) "f" ``` `ZRANGEBYLEX` is the first command of the `*BYLEX` category of sorted set commands. The other ones are `ZREMRANGEBYLEX` and `ZREVRANGEBYLEX`. These three commands are meant to be used for a sorted set containing elements with identical scores. A common pattern is to set a score value of `0`, but any score would work, as long as it is the same across all members. "LEX" is short for "lexicographic", which is a fancy term for "alphabetically", or what you would expects words to be sorted by in a dictionnary, the real kind, with word definitions, not the data structure. Both words are not absolutely equivalent, but they're equivalent enough for the sake of this explanation. The reason why these three commands require an identical score is because they only operate with the lexicographic order of the member values, but if scores where different, we'd have no guarantees that all members would be sorted in lexicographical order. Let's look at an example where all scores are the same first: ``` bash 127.0.0.1:6379> ZADD lex-zset 0 a 0 b 0 c 0 xylophone 0 zebra 0 something-else (integer) 6 127.0.0.1:6379> ZRANGE lex-zset 0 -1 1) "a" 2) "b" 3) "c" 4) "something-else" 5) "xylophone" 6) "zebra" ``` All the scores are identical, so the lexicographic order is used as a "tiebreaker" to sort the members in the sorted set. Now let's look at the same set of members, but with different scores: ``` bash 127.0.0.1:6379> ZADD lex-zset-with-scores 1 a 0 b 18 c 3.14 xylophone 1.414 zebra 0.01 something-else (integer) 6 127.0.0.1:6379> ZRANGE lex-zset-with-scores 0 -1 1) "b" 2) "something-else" 3) "a" 4) "zebra" 5) "xylophone" 6) "c" 127.0.0.1:6379> ZRANGE lex-zset-with-scores 0 -1 WITHSCORES 1) "b" 2) "0" 3) "something-else" 4) "0.01" 5) "a" 6) "1" 7) "zebra" 8) "1.4139999999999999" 9) "xylophone" 10) "3.1400000000000001" 11) "c" 12) "18" ``` The ordering by score takes precedence, and the set is not sorted alphabetically anymore. Redis does not check that the members in the sorted set all have the same score when using a `*BYLEX` command, it will instead incorrect results, so it is up to the caller to make sure that the data is correctly inserted before using these commands. We can use `ZRANGEBYLEX` to select members within the given lexicographic range, where `[` means inclusive and `(` exclusive: ``` bash 127.0.0.1:6379> ZRANGEBYLEX lex-zset [s [zebra 1) "something-else" 2) "xylophone" 3) "zebra" 127.0.0.1:6379> ZRANGEBYLEX lex-zset [s (zebra 1) "something-else" 2) "xylophone" ``` The special values `-` and `+` can be used to express values that are respectively lower than any other values and greater than any other values: ``` bash 127.0.0.1:6379> ZRANGEBYLEX lex-zset [s + 1) "something-else" 2) "xylophone" 3) "zebra" 127.0.0.1:6379> ZRANGEBYLEX lex-zset - [s 1) "a" 2) "b" 3) "c" ``` Let's look at the same commands, but with our other sorted set, `lex-zset-with-scores`: ``` bash 127.0.0.1:6379> ZRANGEBYLEX lex-zset-with-scores - [s 1) "b" 127.0.0.1:6379> ZRANGEBYLEX lex-zset-with-scores [s + (empty array) 127.0.0.1:6379> ZRANGEBYLEX lex-zset-with-scores [s [zebra (empty array) 127.0.0.1:6379> ZRANGEBYLEX lex-zset-with-scores [s (zebra (empty array) ``` The behavior is undefined, Redis makes the assumption that all elements are ordered alphabetically, since they're not, the result is nonsensical. A final word on lexicographic order, while it may look intuitive at first, the letter `a` comes before the letter `b`, it can be surprising when applied to numbers represented as strings, let's look at example in Ruby first: ``` ruby irb(main):010:0> '10' < '2' => true ``` The string `'2'` is considered to be greater than the string `'10'`, that's because with lexicographic order, we compare strings one character at a time, and `'1' < '2'` is `true`, so the `'0'` character in `'10'` is never even considered here. An example that might help is to use letters instead: ``` ruby irb(main):011:0> 'ba' < 'c' => true ``` `a`, `b` and `c` are the ASCII representation of the bytes `97`, `98` and `99`. This example is very similar to the previous one, given that the byte `'1'` has the value `49`, `'0'`, `48` and `'2'`, `50`. We're comparing two bytes on the left, with one on the right, on the left with have `49` and `48` and on the right we have `50`. `50` is greater than `49`, so we know which string is greater. ### By Rank We are going to start with the `ZRANGE` command. We already know that we're going to implement a very similar command later on, `ZREVRANGE`, so let's already create a method implementing the shared logic in `SortedSetUtils`. The `ZRANGE` command has the following format according to the [Redis documentation][redis-doc-zrange]: ``` ZRANGE key start stop [WITHSCORES] ``` ``` ruby module BYORedis module SortedSetUtils # ... def self.generic_range(db, args, reverse: false) Utils.assert_args_length_greater_than(2, args) start = Utils.validate_integer(args[1]) stop = Utils.validate_integer(args[2]) raise RESPSyntaxError if args.length > 4 if args[3] if args[3].downcase == 'withscores' withscores = true else raise RESPSyntaxError end end sorted_set = db.lookup_sorted_set(args[0]) if reverse tmp = reverse_range_index(start, sorted_set.cardinality - 1) start = reverse_range_index(stop, sorted_set.cardinality - 1) stop = tmp end if sorted_set range_spec = RedisSortedSet::GenericRangeSpec.rank_range_spec(start, stop, sorted_set.cardinality) SortedSetRankSerializer.new( sorted_set, range_spec, withscores: withscores, reverse: reverse, ) else EmptyArrayInstance end end end # ... class ZRangeCommand < BaseCommand def call SortedSetUtils.generic_range(@db, @args) end def self.describe Describe.new('zrange', -4, [ 'readonly' ], 1, 1, 1, [ '@read', '@sortedset', '@slow' ]) end end end ``` _listing 10.17 The `ZRangeCommand` class_ The `SortedSetUtils.generic_range` method implements the range logic, including validating the arguments and uses the `SortedSetRankSerializer` class to serialize the result Let's now look at the serializer class, as well as the "range spec" class, `GenericRankRangeSpec`. We'll make use of other type of range specs throughout this chapter, for score order and lexicographic order, when implementing other range related commands. This range spec class encapsulates all the data required to define a rank spec, that is, a minimum value and a maximum value, both `Integer` instances. We also pass the set cardinality to the class to let it transform negative indices into _actual_ indices. For example, `-1`, becomes `cardinality - 1`, the index of the last item in the set, `-2` becomes `cardinality - 2`, the second to last index, and so on. The `rank_range_spec` also makes sure that the final values of `min` and `max` are not outside the range of valid indices, that is `min` cannot be lower than `0` and `max` cannot be greater than or equal to `cardinality`, because there are no elements with such ranks. The range spec also defines a useful method, `empty?`, when the range cannot possibly include any elements, for instance the range `1..0` in Ruby is empty, as we can see with the result of calling `.to_a` on it, an empty array: ```ruby irb(main):034:0> (1..0).to_a => [] ``` The comparison logic relies on "comparison values" that we've explored we discussing the uses of the `bsearch_index` method, `-1` means that the first of the two items being compared is lower than the second one, `0` means they're equal and `1` means that the second one is greater. Using this approach will allow us to customize the actual comparison logic while still reusing the core methods of this class. The actual comparison function used by the `GenericRangeSpec` is the block argument given to its constructor, in this case use `a <=> b`, the expected order of integers. ``` ruby module BYORedis class RedisSortedSet # ... class GenericRangeSpec attr_reader :min, :max, :min_exclusive, :max_exclusive alias min_exclusive? min_exclusive alias max_exclusive? max_exclusive def self.rank_range_spec(min, max, cardinality) max = cardinality + max if max < 0 min = cardinality + min if min < 0 max = cardinality - 1 if max >= cardinality min = 0 if min < 0 GenericRangeSpec.new(min, max, false, false) do |a, b| a <=> b end end def initialize(min, max, min_exclusive, max_exclusive, &block) @min = min @min_exclusive = min_exclusive @max = max @max_exclusive = max_exclusive @block = block end def empty? comparison = compare_with_max(min) comparison > 0 || (comparison == 0 && (min_exclusive? || max_exclusive?)) end def compare_with_max(element) @block.call(element, @max) end end # ... end class SortedSetRankSerializer def initialize(sorted_set, range_spec, withscores: false, reverse: false) @sorted_set = sorted_set @range_spec = range_spec @withscores = withscores @reverse = reverse end def serialize return RESPArray.new([]).serialize if @range_spec.empty? case @sorted_set.underlying when List then serialize_list when ZSet then serialize_zset else raise "Unknown type for #{ @underlying }" end end private def serialize_zset members = [] (@range_spec.min..@range_spec.max).each do |rank| pair = @sorted_set.underlying.array[rank] if @reverse members.prepend(Utils.float_to_string(pair.score)) if @withscores members.prepend(pair.member) else members.push(pair.member) members.push(Utils.float_to_string(pair.score)) if @withscores end end RESPArray.new(members).serialize end def serialize_list ltr_acc = lambda do |value, response| response << RESPBulkString.new(value.member).serialize if @withscores response << RESPBulkString.new(Utils.float_to_string(value.score)).serialize end @withscores ? 2 : 1 end rtl_acc = lambda do |value, response| if @withscores response.prepend(RESPBulkString.new(Utils.float_to_string(value.score)).serialize) end response.prepend(RESPBulkString.new(value.member).serialize) @withscores ? 2 : 1 end if @reverse tmp = ltr_acc ltr_acc = rtl_acc rtl_acc = tmp end ListSerializer.new(@sorted_set.underlying, @range_spec.min, @range_spec.max) .serialize_with_accumulators(ltr_acc, rtl_acc) end end end ``` _listing 10.18 The `SortedSetRankSerializer` class_ The `serialize` method calls `serialize_list` or `serialize_zset` depending on the type of `@underlying`. Let's first look look at the `ZSet` case, we can leverage the array structure inside the `ZSet` to extract the range of elements we need, based on on `min` and `max` attribute of the range spec. The score values should only be included if the `WITHSCORES` option was set. Additionally, the order of the final array depends on the requested order. We're jumping ahead a little bit here, but we can already assume that the `ZREVRANGE` method will be very similar to the `ZRANGE` method. So for now `reverse` is always set to `false`, meaning that for each pair in the set we always append the `member` value, and conditionally add the `score` value afterward. Once the `members` array is created, we serialize it as a `RESPArray`. In the `List` case, we use a new method from the `ListSerializer` class, `serialize_with_accumulators`: ``` ruby module BYORedis # ... class ListSerializer def initialize(list, start, stop) @list = list @start = start @stop = stop end def serialize_with_accumulators(left_to_right_accumulator, right_to_left_accumulator) @stop = @list.size + @stop if @stop < 0 @start = @list.size + @start if @start < 0 @stop = @list.size - 1 if @stop >= @list.size @start = 0 if @start < 0 return EmptyArrayInstance.serialize if @start > @stop response = '' size = 0 distance_to_head = @start distance_to_tail = @list.size - @stop if distance_to_head <= distance_to_tail iterator = List.left_to_right_iterator(@list) within_bounds = ->(index) { index >= @start } stop_condition = ->(index) { index > @stop } accumulator = left_to_right_accumulator else iterator = List.right_to_left_iterator(@list) within_bounds = ->(index) { index <= @stop } stop_condition = ->(index) { index < @start } accumulator = right_to_left_accumulator end until stop_condition.call(iterator.index) if within_bounds.call(iterator.index) size += accumulator.call(iterator.cursor.value, response) end iterator.next end response.prepend("*#{ size }\r\n") end def serialize serialize_with_accumulators( lambda do |value, response| response << RESPBulkString.new(value).serialize 1 end, lambda do |value, response| response.prepend(RESPBulkString.new(value).serialize) 1 end, ) end end end ``` _listing 10.19 Updates to the `ListSerializer` class_ We extracted most of the `serialize` method to the new `serialize_with_accumulators` method, which allows us to use the same overall logic, while being able to serialize individual list nodes differently. This is what we do in the `SortedSetRankSerializer#serialize_list` method. Back to the `serialize_list` method in `SortedSetRankSerializer`, we create two different accumulators that are aware of the `@withscores` value and can decide whether or not to include it in the final serialized string when iterating over the list for serialization. As a reminder, we give both a "left to right" and a "right to left" accumulator to `ListSerializer` so that it can use the most efficient way to serialize the list. Depending on the range it needs to serialize, it might decide to iterate from the right, if it'll be faster to find the range in the list. Each of the accumulators now return an integer representing the number of elements added to the final response. This is necessary because the `WITHSCORES` option will force us to add two items in the final response for each item in the list, the `member` attribute, followed by the `score` attribute. When iterating from the left, we'll encounter items in the order we want them to be in the final array, so we can first append the `member` value to `response`, and then, conditionally, append the `score` value. On the other hand, if we're iterating from right to left, we'll encounter items in the opposite order we want them to be in the final array, so we first, conditionally, prepend the `score` value, and then, always, prepend the `member` value. Let's look at an example with a small array to illustrate this. If we have the array `[ [ 10, 'a' ] , [ 20, 'b' ], [ 30, 'c' ], [ 40, 'd' ], [ 50, 'e' ] ]`, and we're requesting the range `1, 2`, we should return the array ` [ 'b', 20, 'c', 30 ] `. If we were requesting the range `2, 3`, we should return the array `[ 'c', 30, 'd', 40 ]`. If we're iterating from left to right, as would be case with the range `1, 2`, since it's faster to reach it from the left side, we would first encounter `[ 20, 'b' ]`, and then `[ 30, 'c' ]`, so we can append elements as we go, in the same order as the desired final order, `member` first, `score`, second. On the other hand, if we're iterating from right to left, as would be the case with the range `2, 3`, because it's faster to reach from the right side, we would first encounter `[ 'd', 40 ]` and then `[ 'c', 30 ]`. So when reaching the first element, we would first prepend the `score` and then the member, giving us the array `[ 'd', 40 ]`, and we would do the same with the second pair, prepending `30`, and then prepending `'c'`, giving us the desired result `[ 'c', 30, 'd', 40 ]`. As we did earlier, we can ignore the `@reverse` branch, that'll only be needed for the `ZREVRANGE` method. ### By Score Let's now add the `ZRANGEBYSCORE` command, which has the following format according to the [Redis doc][redis-doc-zrangebyscore]: ``` ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count] ``` `min` and `max` are a new type of range, a "score range", which we'll also represent with the `GenericRangeSpec` class. Both values must be valid floats, that includes the values `-inf` and `+inf`, which happen to be the equivalent of `0` and `-1` in the `ZRANGE` command, that is, a way to ask for all the elements in the sorted set: ``` 127.0.0.1:6379> ZADD z 0.1 a 2 b 3.2 c -10 d (integer) 4 127.0.0.1:6379> ZRANGEBYSCORE z -inf +inf 1) "d" 2) "a" 3) "b" 4) "c" ``` By default the values are considered inclusive, but this can be controlled with the prefix `(` to mark it as exclusive, let's look at an example with the previous sorted set, `z`: ``` 127.0.0.1:6379> ZRANGEBYSCORE z -inf 2 1) "d" 2) "a" 3) "b" 127.0.0.1:6379> ZRANGEBYSCORE z -inf (2 1) "d" 2) "a" ``` `LIMIT` and `OFFSET` are used to respectively limit the number of elements in the result and skip an arbitrary number of elements. A negative count value is the same as not passing a value and means "return all matches", negative offsets are accepted but will always result in an empty array. Let's go ahead and add all that in `sorted_set_commands.rb`: ``` ruby module BYORedis module SortedSetUtils def self.generic_range_by_score(db, args, reverse: false) # A negative count means "all of them" options = { offset: 0, count: -1, withscores: false } Utils.assert_args_length_greater_than(2, args) key = args.shift if reverse max = args.shift min = args.shift else min = args.shift max = args.shift end range_spec = Utils.validate_score_range_spec(min, max) parse_range_by_score_options(args, options) unless args.empty? sorted_set = db.lookup_sorted_set(key) if options[:offset] < 0 EmptyArrayInstance elsif sorted_set options[:reverse] = reverse SortedSetSerializerBy.new(sorted_set, range_spec, **options, &:score) else EmptyArrayInstance end end def self.parse_limit_option(args, options) offset = args.shift count = args.shift raise RESPSyntaxError if offset.nil? || count.nil? offset = Utils.validate_integer(offset) count = Utils.validate_integer(count) options[:offset] = offset options[:count] = count end def self.parse_range_by_score_options(args, options) while arg = args.shift case arg.downcase when 'withscores' then options[:withscores] = true when 'limit' then SortedSetUtils.parse_limit_option(args, options) else raise RESPSyntaxError end end end # ... end # ... class ZRangeByScoreCommand < BaseCommand def call SortedSetUtils.generic_range_by_score(@db, @args, reverse: false) end def self.describe Describe.new('zrangebyscore', -4, [ 'readonly' ], 1, 1, 1, [ '@read', '@sortedset', '@slow' ]) end end end ``` _listing 10.20 The `ZRangeByScoreCommand` class_ We're again anticipating the upcoming reverse command, `ZREVRANGEBYSCORE` in this case, and create `generic_range_by_score` to share the common logic, for now `reverse` is always `false`, so we can ignore the branches where it handles the `true` case. We need to add the `validate_score_range_spec` method to the `Utils` module: ``` ruby module BYORedis module Utils # ... def self.validate_score_range_spec(min, max) min, min_exclusive = parse_score_range_item(min) max, max_exclusive = parse_score_range_item(max) RedisSortedSet::GenericRangeSpec.score_range_spec( min, max, min_exclusive, max_exclusive) end def self.parse_score_range_item(str) if str[0] == '(' str = str[1..-1] exclusive = true else exclusive = false end return validate_float(str, 'ERR min or max is not a float'), exclusive end private_class_method :parse_score_range_item end end ``` _listing 10.21 The `Utils.validate_score_range_spec` method_ The new method in the `Utils` module, `validate_score_range_spec`, takes care of creating an instance of `GenericRangeSpec`, with the correct exclusive flags set depending on the presence of `(`. Let's add a method to create a range spec with the appropriate comparison function, passed as a block. We're also adding a new method, `no_overlap_with_range?` which will be used to determine when we can avoid to do any work if we can determine that no items match the requested range. ``` ruby module BYORedis class RedisSortedSet # ... class GenericRangeSpec attr_reader :min, :max, :min_exclusive, :max_exclusive alias min_exclusive? min_exclusive alias max_exclusive? max_exclusive def self.score_range_spec(min, max, min_exclusive, max_exclusive) GenericRangeSpec.new(min, max, min_exclusive, max_exclusive) do |a, b| a <=> b end end # ... end # ... def no_overlap_with_range?(range_spec, &block) # Note that in that each condition the "value" is abstract and determined by the return # value of calling the block variable, in practice it's either score, member, or rank # There is no overlap under the four following conditions: # 1. the range spec min is greater than the max value: # set : |---| # range: |---| (min can be inclusive or exclusive, doesn't matter) # 2. the range spec min is exclusive and is equal to the max value # set : |---| # range: (---| (min is exclusive) # 3. the min value is greater than range spec max # set : |---| # range: |---| (max can be inclusive or exclusive, doesn't matter) # 4. the min value is equal to the range spec max which is exclusive # set : |---| # range: |---( (max is exclusive) max_pair, max_pair_rank = max_pair_with_rank min_pair, min_pair_rank = min_pair_with_rank set_max_range_spec_min_comparison = range_spec.compare_with_min(block.call(max_pair, max_pair_rank)) set_min_range_spec_max_comparison = range_spec.compare_with_max(block.call(min_pair, min_pair_rank)) set_max_range_spec_min_comparison == -1 || # case 1 (range_spec.min_exclusive? && set_max_range_spec_min_comparison == 0) || # case 2 set_min_range_spec_max_comparison == 1 || # case 3 (range_spec.max_exclusive? && set_min_range_spec_max_comparison == 0) # case 4 end private # @return [Array] Two values, the first is a Pair, and the second is the rank def max_pair_with_rank case @underlying when List return @underlying.tail.value, @underlying.size when ZSet return @underlying.array[-1], @underlying.array.size - 1 else raise "Unknown type for #{ @underlying }" end end # @return [Array] Two values, the first is a Pair, and the second is the rank def min_pair_with_rank case @underlying when List return @underlying.head.value, 0 when ZSet return @underlying.array[0], 0 else raise "Unknown type for #{ @underlying }" end end # ... end # ... end ``` _listing 10.22 The `score_range_spec` and `no_overlap_with_range?` methods_ The new class method on `GenericRangeSpec` allows us to create a range specific to score ranges, which handles the exclusive boundaries. The `score_range_spec` class method is almost identical to the `rank_range_spec` one from earlier, with the difference that it doesn't have to handle negative values, it just takes the score boundaries as in, as well as the exclusivity flags, which is something that we did not have to consider in the rank case, but the comparison of elements is the same, we're comparing numbers, `Integer` instances for ranks, `BigDecimal` instances for scores, and both can be compared with `<=>`, which is defined on both: [`Integer#<=>`][ruby-doc-integer-spaceship] and [`BigDecimal#<=>`][ruby-doc-bigdecimal-spaceship]. If either of the boundaries is flagged as exclusive, then the range will be empty if they're equal. Looking at a Ruby example illustrates this pretty clearly: ``` ruby irb(main):006:0> (0..0).to_a => [0] irb(main):007:0> (0...0).to_a => [] ``` The triple period notation is the exclusive range notation in Ruby, and as we can see the range "0 to 0, exclusive" is empty. If neither of the boundaries is flagged as exclusive, then the only condition making the range empty is if `min` is greater than `max`, that is if the value of `comparison` is `1`. If either of the boundaries is marked as exclusive then a comparison result of `0`, meaning equality, is enough to flag the range as empty. This is the logic that is implemented in the `empty?` method. Let's also add the `in_range?` method so we can check for the inclusivity of an element in the range with awareness of the exclusivity of the `min` and `max` boundaries: ``` ruby module BYORedis class RedisSortedSet # ... class GenericRangeSpec # ... def empty? comparison = compare_with_max(min) comparison > 0 || (comparison == 0 && (min_exclusive? || max_exclusive?)) end def compare_with_min(element) @block.call(element, @min) end def in_range?(element) return false if empty? comparison_min = compare_with_min(element) comparison_max = compare_with_max(element) comparison_min_ok = min_exclusive? ? comparison_min == 1 : comparison_min >= 0 comparison_max_ok = max_exclusive? ? comparison_max == -1 : comparison_max <= 0 comparison_min_ok && comparison_max_ok end end # ... end end ``` _listing 10.23 The `empty?`, `compare_with_min` & `in_range?` methods for the `GenericRangeSpec` class_ We can now use the same class for our different use cases, rank ranges and score ranges, let's quickly play with it in `irb`: ``` ruby irb(main):001:0> require_relative './redis_sorted_set' => true irb(main):002:0> range_spec_class = BYORedis::RedisSortedSet::GenericRangeSpec irb(main):003:0> rank_range_spec = range_spec_class.rank_range_spec(2, 3, 10) irb(main):004:0> rank_range_spec.in_range?(1) => false irb(main):005:0> rank_range_spec.in_range?(4) => false irb(main):006:0> rank_range_spec.in_range?(3) => true irb(main):007:0> rank_range_spec = range_spec_class.rank_range_spec(2, -1, 10) irb(main):008:0> rank_range_spec.in_range?(9) => true irb(main):009:0> rank_range_spec.in_range?(10) => false irb(main):010:0> score_range_spec = range_spec_class.score_range_spec(2, 10, true, false) irb(main):011:0> score_range_spec.in_range?(2) => false irb(main):012:0> score_range_spec.in_range?(2.1) => true irb(main):013:0> score_range_spec.in_range?(10) => true ``` `1` & `4` are out of range for the rank range spec `2, 3` within a set of size `10`, that makes sense, only `2` and `3` are in range. We can see the transformation of negative indices when using the range `2, -1` in a set of size `10`, the last rank is `9`, the 0-based index of the last element, so `9` is in range, and `10` is not. Switching to a score range, the last two boolean values determine the exclusivity of respectively the `min` and `max` boundaries, so the range we create is `(2 10`. We can see that `2` is out of range and `2.1` is in range, `10` is as well. We created the `range_spec_class` variable only for convenience within the `irb` session. Equipped with our new range spec constructor wrapper to create score range specs, the final class we need to add for this command is `SortedSetSerializerBy`: ``` ruby module BYORedis # ... class SortedSetSerializerBy def initialize(sorted_set, range_spec, offset: 0, count: -1, withscores: false, reverse: false, &block) @sorted_set = sorted_set @range_spec = range_spec @offset = offset @count = count @withscores = withscores @reverse = reverse if block.arity != 2 @block = proc { |element, _| block.call(element) } else @block = block end end def serialize if @offset < 0 || @range_spec.empty? || @sorted_set.no_overlap_with_range?(@range_spec, &@block) return RESPArray.new([]).serialize end case @sorted_set.underlying when List then serialize_list when ZSet then serialize_zset else raise "Unknown type for #{ @underlying }" end end private def serialize_zset members = [] if @reverse start_index = @sorted_set.underlying.array.last_index_in_range(@range_spec, &@block) if start_index.nil? raise "Unexpectedly failed to find last index in range for #{ self }" end indices = start_index.downto(0) else start_index = @sorted_set.underlying.array.first_index_in_range(@range_spec, &@block) if start_index.nil? raise "Unexpectedly failed to find first index in range for #{ self }" end indices = start_index.upto(@sorted_set.cardinality - 1) end indices.each do |i| item = @sorted_set.underlying.array[i] if @range_spec.in_range?(@block.call(item)) if @offset == 0 members << item.member members << Utils.float_to_string(item.score) if @withscores @count -= 1 break if @count == 0 else @offset -= 1 end else break end end RESPArray.new(members).serialize end def serialize_list if @reverse iterator = List.right_to_left_iterator(@sorted_set.underlying) else iterator = List.left_to_right_iterator(@sorted_set.underlying) end members = [] entered_range = false while iterator.cursor && @count != 0 member = iterator.cursor.value if @range_spec.in_range?(@block.call(member)) entered_range ||= true if @offset == 0 members << member.member members << Utils.float_to_string(member.score) if @withscores @count -= 1 else @offset -= 1 end elsif entered_range == true break end iterator.next end RESPArray.new(members).serialize end end end ``` _listing 10.24 The `serialize_zset` & `serialize_list` methods for the `SortedSetSerializerBy` class_ We start the `serialize` methods with three checks to return early if we can. In the first one, we test if the `offset` value is negative, if it is, we can return an empty array. We can also return early if the range is empty, or if the range and the set don't overlap. Let's take a closer look at the `no_overlap_with_range?` method. The following illustration shows the cases in which we don't even need to go further, we can already know that there won't be any results. There is no overlap under the four following conditions: - the range spec min is greater than the max value: ``` set : |---| range: |---| (min can be inclusive or exclusive, doesn't matter) ``` - the range spec min is exclusive and is equal to the max value: ``` set : |---| range: (---| (min is exclusive) ``` - the min value is greater than range spec max: ``` set : |---| range: |---| (max can be inclusive or exclusive, doesn't matter) ``` - the min value is equal to the range spec max which is exclusive: ``` set : |---| range: |---( (max is exclusive) ``` In other words, if the range is to the right, or to the left of the set, with special cases around exclusivity, we don't need to do any work, the result is empty. One final word about `no_overlap_with_range?`, it calls the block with two arguments, the `Pair` instance itself, the first one in the set or the last one in the set, with their rank, which will allow us to use this method when dealing with range ranks, such as `ZREMRANGEBYRANK` for instance. In practice the `block.call` expression will either return the `score` attribute, the `member` attribute or the rank value, for the pair. We could have written three methods, but the block based approach allows us to reuse the core logic for all three use cases. Calling the block with two arguments might be an issue given that the block that was passed to the `SortedSetSerializerBy` constructor is `&:score`, what does passing multiple arguments to this block will do, let's take a look at that now. #### A note about blocks, arity and Ruby being weird The need for the `if block.arity != 2` line in the `SortedSetSerializerBy` constructor deserves its own section, because it's kinda weird, Ruby does that sometimes. It's easier to start with what would happen, without this block, we would always set `@block` to `block`, which is `&:score` at this moment, a block that is _almost_ the equivalent of `{ |x| x.score }`, with a big difference, how it handles its arguments. Both versions create a `Proc`, and not a `Lambda`, there are two differences, lambdas `return` or `break` calls only affect the lambda itself, whereas returning from a `Proc` returns from the outer method. You can see that by running `lambda { return 1 }.call` in `irb`, and see that it returns `1`. This is because we create a lambda, call it, and get back the return value of the lambda, `1`. Now, run the proc version, `proc { return 1 }.call`, and you'll get a `LocalJumpError (unexpected return)` exception back. This is because you can't return in `irb`. You can see that by typing `return` on a new line and you'll get the same error. This shows that calling `return` within the proc actually tried to return from the caller, the main `irb` session. Blocks create procs and not lambdas, and this allows patterns such as returning early from the block, which is a pattern we use a lot in this chapter. Let's look at an example using a block, a proc and a lambda: ``` ruby def a_method(proc_or_lambda) if block_given? yield else proc_or_lambda.call end 'reached the end of a_method' end def call_with_block a_method(nil) { return 'nope' } end def call_with_lambda a_method(lambda { return 'nope' }) end def call_with_proc a_method(proc { return 'nope' }) end print "block: #{ call_with_block }\n" print "lambda: #{ call_with_lambda }\n" print "proc: #{ call_with_proc }\n" ``` Putting this in a file, say, `proc_vs_block_vs_lambda.rb` and running it with `ruby proc_vs_block_vs_lambda.rb`, we get the following result: ``` bash > ruby proc_vs_block_vs_lambda.rb block: nope lambda: reached the end of a_method proc: nope ``` We only reached the end of `a_method` when using a lambda, because the `return` call only affected the lambda itself. This behavior is what allows us to do something like the following: ``` ruby def first_item_or_nil(an_array) an_array&.each { |element| return element } end ``` This method might not seem really useful, we could have used `[0]` to return the first item, but it will return `nil` for a `nil` array whereas calling `[0]` on a `nil` value will raise a `NoMethodError` exception. Beside the small safety gain with this method, the point being that we can return from within the block, and that will affect the method where the block was created, in this case, `head_or_nil`. We'll see a lot of actually useful cases later, such as in `first_item_or_nil`. So blocks are procs, cool, now, the difference we care about here is how they handle different arguments being received: ``` ruby irb(main):001:0> p = proc { |x| p x } irb(main):002:0> p.call(1) 1 => 1 irb(main):003:0> p.call(1, 2) 1 => 1 irb(main):004:0> p = proc { |x, y| p x, y } irb(main):005:0> p.call(1) 1 nil => [1, nil] irb(main):006:0> p.call(1, 2) 1 2 => [1, 2] irb(main):007:0> l = lambda { |x| p x } irb(main):008:0> l.call(1) 1 => 1 irb(main):009:0> l.call(1, 2) Traceback (most recent call last): 5: from /Users/pierre/.rbenv/versions/2.7.1/bin/irb:23:in `<main>' 4: from /Users/pierre/.rbenv/versions/2.7.1/bin/irb:23:in `load' 3: from /Users/pierre/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/irb-1.2.3/exe/irb:11:in `<top (required)>' 2: from (irb):10 1: from (irb):8:in `block in irb_binding' ArgumentError (wrong number of arguments (given 2, expected 1)) irb(main):010:0> l = lambda { |x, y| p x, y } irb(main):011:0> l.call(1) Traceback (most recent call last): 5: from /Users/pierre/.rbenv/versions/2.7.1/bin/irb:23:in `<main>' 4: from /Users/pierre/.rbenv/versions/2.7.1/bin/irb:23:in `load' 3: from /Users/pierre/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/irb-1.2.3/exe/irb:11:in `<top (required)>' 2: from (irb):12 1: from (irb):11:in `block in irb_binding' ArgumentError (wrong number of arguments (given 1, expected 2)) irb(main):012:0> l.call(1, 2) 1 2 => [1, 2] ``` A `Proc` doesn't really care, if it needs more arguments that you give it, it defaults to `nil`, if it receives too many arguments, it just ignores them. A lambda on the other hand is like a method, it requires the exact number of arguments. Things are a bit difference when arguments have default values and become optional, but let's set that aside, it's not really what our problem is. Note that it's sometimes not explicit whether you're dealing with a lambda or a proc, but you can always use the `lambda?` method when in doubt. Now back to `&:member`, what it does is actually a bit unclear to me, because the block that is created is defined in some internal Ruby code, in C, but what we can do is inspect the block with some of the methods available on `Proc`, namely [`#parameters`][ruby-doc-proc-parameters] & [`#arity`][ruby-doc-proc-arity], let's add this small snippet in a file called `blocks.rb`: ``` ruby def inspect_ruby_block(&block) puts "parameters: #{ block.parameters }" puts "arity: #{ block.arity }" puts "lambda?: #{ block.lambda? }" end inspect_ruby_block { |x| x.score } p '---' inspect_ruby_block(&:score) ``` Let's run this with `ruby blocks.rb`: ``` ruby parameters: [[:opt, :x]] arity: 1 lambda?: false "---" parameters: [[:rest]] arity: -1 lambda?: false ``` So neither are lambdas, cool, they should be handling arguments in a flexible way, but there's a difference, their arity is not the same. Arity is just a fancy word for "how many arguments do they expect". In the first example, the explicit block, the value is `1`, which makes sense, we defined it as `|x|`, only one argument. But in the second example, it's `-1`, which happens to be _kinda_ similar to how Redis communicates arity for its commands. `-1` means that it is variadic, it accepts a variable number of arguments, but what makes this even weirder is the result of the `parameters` call. The one argument does not have a name. We can mimic a similar block with the following: ``` ruby irb(main):002:0> inspect_ruby_block { |*| } parameters: [[:rest]] arity: -1 lambda?: false => nil irb(main):003:0> inspect_ruby_block { |*a| } parameters: [[:rest, :a]] arity: -1 lambda?: false => nil ``` How Ruby goes from a block like that, that _seems_ to accept a variable number of arguments without naming them and is able to return the `score` attribute, or whatever we passed after the semicolon in `&:` is unclear to me, but it leads us to the problem we're trying to solve, this block, which is a proc, but of a slightly different kind, doesn't behave the way we want if we pass too many arguments. Let's first create a method that returns the block it receives so that we can play with it. This is useful because the only way to create a block through the ampersand column approach is by passing it as an argument, so by returning it, we'll get a hold of the block in a variable: ``` ruby def capture_block(&b) b end ``` And now let's look at the differences in behavior: ``` ruby irb(main):018:0> block = capture_block { |*| } irb(main):019:0> block.call(1) => nil irb(main):020:0> block.call(1, 2) => nil ``` So far, this is what we would expect, the block does nothing, and it silently accepts any number of arguments, but now let's take a look at the `&:score` approach: ``` ruby irb(main):025:0> block = capture_block(&:score) irb(main):026:0> block.call(Struct.new(:score).new(12)) => 12 ``` If we want to call `block`, we need an object that has a `score` method, so in one line we create a `Struct`, and instantiate it, and it works, so far so good. Now let's see what happens if we pass a second argument, which is what we want to do, call a block with a `Pair` and a number representing its rank: ``` ruby irb(main):027:0> block.call(Struct.new(:score).new(12), 10) Traceback (most recent call last): 5: from /Users/pierre/.rbenv/versions/2.7.1/bin/irb:23:in `<main>' 4: from /Users/pierre/.rbenv/versions/2.7.1/bin/irb:23:in `load' 3: from /Users/pierre/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/irb-1.2.3/exe/irb:11:in `<top (required)>' 2: from (irb):27 1: from (irb):27:in `score' ArgumentError (wrong number of arguments (given 1, expected 0)) ``` Yup, it blows up, and honestly, I can't really tell you why. My guess? By being defined in C, it is able to use the low level APIs of the language, and can say "give me the first argument, and call the method named after the argument I was created with on it". It's also interesting to look specifically at the error we get. It gives us a hint, `wrong number of arguments (given 1, expected 0)`, for `score`, so it seems like it tried to pass `10`, the second argument to `score`, which is a getter and only takes a single argument, so the `&:` approach can apparently be used for methods that require arguments, let's confirm this by creating this class in `irb`: ``` ruby class A def a_variadic_method(*args) p args end end ``` The method `a_variadic_method` is variadic, it accepts any number of arguments, and it prints them, let's now use this with a block created with the `&:` approach: ``` ruby irb(main):012:0> b = capture_block(&:a_variadic_method) irb(main):013:0> b.call(A.new) [] => [] irb(main):014:0> b.call(A.new, 1, 2, 3) [1, 2, 3] => [1, 2, 3] ``` We capture a block that will call `a_variadic_method` on its argument and first call it with an instance of `A`, and get back an empty array, it's because no arguments were given to `a_variadic_method`, so `args` was set to `[]`. Now let's add arguments to the `block.call` line, and we see that we get them back as an array, because they were passed as arguments! So what did we learn here, that a block created with `&:` is variadic and requires at least one argument, to call the method it was created with on, and if it receives any other arguments, it will pass them as arguments to the method. So anyway, what can we do? Well, we can create a block that accepts the number of arguments we need it to receive if we know it otherwise wouldn't be able to handle them. Reusing the same `block` variable from the previous example defined as `block = capture_block(&:score)`: ``` ruby irb(main):031:0> wrapper_block = proc { |pair, rank| block.call(pair) } irb(main):032:0> wrapper_block.call(Struct.new(:score).new(12), 10) => 12 irb(main):033:0> wrapper_block.call(Struct.new(:score).new(12)) => 12 ``` The second argument of the block is ignored, and we can pass a single argument! Just what we wanted! It's worth noting that we could have also changed the behavior when creating a `SortedSetSerializerBy`, with: ``` ruby SortedSetSerializerBy.new(sorted_set, range_spec, **options) { |x, _| x.score } ``` But I do believe that it is convenient to be able to only pass a single argument, since that's really what this block is saying: "This block, which is used to extract a variable from a `Pair` returns its score". It would be a little bit annoying to have to worry about a second argument, and ignoring it. #### Serializing a `ZSet` The two methods dedicated to serializing the `ZSet` or the `List` are pretty long, because they're written in a generic way that will allow them to be reused for the `*REV*` commands and the `*LEX*` commands. Let's start with `serialize_zset`, once again ignoring the `@reverse` flag for now, and assuming it to always be `false`. We start by creating the `members` array, which will hold all the values we need to serialize for the final result. We then find the index of the first item that fits in the range with the `SortedArray#first_index_in_range` method, and use it to create the `indices` enumeration, which contain all the indices we want to inspect. This step is a way to skip all the elements to left of the the first element that fits in the range by directly "jumping" to the first item in the range. This approach is a big win for a large set, where for instance, jumping to an element in the middle of the array would require way less steps that iterating one by one from the beginning of the array. We then iterate through the indices and inspect each `Pair` we find. Using the `in_range?` method, we can determine whether or not the current element is in the range. Note that we use the `block` variable, which was set to `&:score`. As discussed earlier, this notation is a shortcut for `{ |x| x.score }`. This approach makes the `SortedSetSerializerBy` agnostic of which fields we're serializing by, the caller gets to decide by passing the right block. The `in_range?` method will always return `true` for the first element, because `first_index_in_range` pointed us as the first element in range, but as we keep iterating to the right in the array, we might end up encountering an element that is outside the range, in which case we want to stop iterating. We also need to handle the `COUNT` and `OFFSET` options. Because of the `OFFSET` option, we might need to ignore the first items we find, so if the current item is in the range, we decrement `@offset` until it reaches `0`. If its value is `0` or less, then we start accumulating elements in `members`, with or without their score, depending on the `WITHSCORES` option. For each element we accumulate, we decrement `@count`, and break once it reaches `0`, telling us we've accumulated enough elements. This logic relies on the fact that we use a default value of `-1` for `@count`, meaning that by default we'll keep decrementing, and it will have no effect since its value will never reach `0`. --- As a quick note, the last sentence is true in Ruby, an integer that is initialized at `-1` cannot possibily reach `0` if we keep decrementing, but it is false in a language where integers can overflow, like C! We've already spent a lot of time talking about integers in the previous chapter, so we'll only say that once a signed integer reaches the minimul value its encoding allows, subtracting `1` will become the maximum of the range, and we keep subtracting, we'll reach `0` again. The following program outputs: `reached 0 (proof: 0) in 65535 steps`: ``` c #include <stdio.h> int main(void) { short i = -1; int steps = 0; while (i != 0) { i--; steps++; } printf("reached 0 (proof: %i) in %i steps", i, steps); return 0; } ``` _listing 10.25 A C example of integer overflow and the wrapping behavior_ --- Let's add the `first_index_in_range` method to `SortedArray`: ``` ruby module BYORedis class SortedArray # ... def first_index_in_range(range_spec) return nil if empty? @underlying.bsearch_index do |existing_element| compare = range_spec.compare_with_min(yield(existing_element)) if range_spec.min_exclusive? compare > 0 # existing_element.score > min else compare >= 0 # existing_element.score >= min end end end end end ``` _listing 10.26 The `SortedArray#first_index_in_range` method_ This method is a generic approach to using the following block: ``` ruby array.bsearch_index do |pair| pair.score >= range_spec.min # or pair.score > range_spec.min if exclusive end ``` Using the `block` approach will allow us to use the same method, but with the `member` value instead, in the lex command below, and using the `compare_with_min` method handles the specifities of the comparison logic. Things are not too complicated for now, we're comparing two float values with `a <=> b`, but will become a bit trickier in the lex case with the `+` & `-` special values, just a heads-up! Note that the block we're dealing with here is, in this case, the one passed to the constructor of `SortedSetSerializerBy`, but after being wrapped in a proc ignoring its second argument, so calling `yield` with a single argument will not cause any issues. The use of the comparison instead of directly using the `>` or `<` operator adds an extra level of indirection that can make things a little bit confusing, that being said, it does allow for a greater level of reusability, so its readability cost comes with _some_ benefit. Let's look at an example to see what the `first_index_in_range` really does: ``` ruby irb(main):001:0> require_relative './sorted_array' => true irb(main):002:0> require_relative './redis_sorted_set' => true irb(main):003:0> array = BYORedis::SortedArray.by_fields(:score, :member) irb(main):004:0> array << BYORedis::RedisSortedSet::Pair.new(1, 'a') => [#<struct BYORedis::RedisSortedSet::Pair score=1, member="a">] irb(main):005:0> array << BYORedis::RedisSortedSet::Pair.new(2, 'b') => [#<struct BYORedis::RedisSortedSet::Pair score=1, member="a">, ...] irb(main):006:0> array << BYORedis::RedisSortedSet::Pair.new(3, 'c') => [#<struct BYORedis::RedisSortedSet::Pair score=1, member="a">, ...] irb(main):007:0> array << BYORedis::RedisSortedSet::Pair.new(4, 'd') => [#<struct BYORedis::RedisSortedSet::Pair score=1, member="a">, ...] irb(main):008:0> array << BYORedis::RedisSortedSet::Pair.new(26, 'z') => [#<struct BYORedis::RedisSortedSet::Pair score=1, member="a">, ...] irb(main):009:0> range_spec = BYORedis::RedisSortedSet::GenericRangeSpec.score_range_spec(2, 4, false, false) irb(main):010:0> array.first_index_in_range(range_spec) { |x| x.score } => 1 ``` This example shows that, at least in this one example, it worked, `1` is indeed the first element of the array that is in the range `2 4`. The other indices of members in the range are `2` and `3`. The trick relies once again on `bsearch_index`, which can be a really powerful once you get the hang of it. In this example we rely on its `find-minimum` mode. In this mode we need to give it a block that returns the following values according to the documentation: > In find-minimum mode (this is a good choice for typical use cases), the block must always return true or false, and there must be an index i (0 <= i <= ary.size) so that: > - the block returns false for any element whose index is less than i, and > - the block returns true for any element whose index is greater than or equal to i. In other words, the method will return the smallest index, which can also be seen as the leftmost index, for which the block is `true`. Or, alternatively phrased, the index after the greatest index for which the block is `false`. Equipped with this definition, we can use it to find the first element that fits in the range, with the block `{ |x| x > min }`, the block will be false if it finds an element in the array equal to the `min` value of the range, and it will therefore return the index of the element after that, which is the first element of the range if the exclusive flag is set for the min value. Looking at it from the other angle, the block will be `true` for all values greater than min, and `false` for all values lower than `min`, including `min` itself. The block `{ |x| x >= min }` will return true as long the element being inspected by `bsearch_index` is greater or equal than the minimum value, so it if finds an element in the array equal to the `min`, it will return that index, otherwise, it will return the index of the smallest value that is still greater than the min. That's the index of the first element in the range if `min` is not exclusive Now let's look at the convoluted way in which `first_index_in_range` ends up achieving exactly what we described. As mentioned earlier, in order to keep the method abstract, we refuse to call `existing_element.score` directly, and instead delegate to the caller to decide what attribute to use, which is what `yield(existing_element)` does. In this example, the block given is `@block`, in the line `@sorted_set.underlying.array.first_index_in_range(@range_spec, &@block)`, with the ampersand to tell Ruby it's not just a _regular_ argument, it's a block. `@block` is the value of the block given to the constructor, which was done in the `SortedSetUtils.generic_range_by_score` method and is `&:score`, the equivalent of `{ |x| x.score }`. We use the value returned by `yield`, and feed it to `compare_with_min`, which calls `score <=> min`. The value returned by `compare_with_min` will be `1` if `existing_element.score > range_spec.min`, `0` if they're equal and `-1` if `existing_element.score < range_spec.min`. So now we can look at what we return from the block in `first_index_in_range`, in the `min_exclusive?` case we return `compare > 0`, which is the same as returning `existing_element.score > range_spec.min`, and in the non exclusive case, `compare >= 0` is the equivalent of `existing_element.score >= range_spec.min`, these are the values that will lead `bsearch_index` to return the index of the first element in the range, min being exclusive or not. Why are we jumping through all these hoops? Well, it'll make writing the next similar commands a breeze! #### Serializing a `List` We've looked at the `serialize_zset` private method in `SortedSetSerializerBy`, let's now look at `serialize_list`. Once again, let's set the `@reverse` branches aside and assume it always holds its default value for now, `false`. We start by creating a left to right iterator, since we have no way to know where the first element in the range is in the list, we'll start from the left and iterate from there. Similarly to the `ZSet` case, we create an array, `members`, which we'll use to aggregate the values as we find them, we also create a boolean that will help us exiting the loop early and prevent to unnecessarily iterate through the whole list if we can avoid it. We start iterating with the iterator, as well as with the `while` condition `@count != 0`. This is the same optimization as earlier, if a `count` was specified, then we'll stop iterating once we've accumulated enough elements, but if no count value is given, then the value will start at `-1` and decrement from there, and this condition will never trigger. For each element in the look, we ask the range if it is in the range, with `@range_spec.in_range?(@block.call(member))`. If this returns `true`, we first flag `entered_range` to `true`, which we only do once, there's no need to set the value again once we've done it. Next, we take the `@offset` value into account, the same way we did in the `ZSet` case, and if we've skipped enough values as indicated by `@offset`, then we start accumulating values, with or without scores, depending on the `@withscores` option. We always decrement the count value, to make sure that the `while` condition we just mentioned stops the loop once we've accumulated enough elements. If the element is not in the range, then we also check if we have previously entered the range, and if we did, then it means that we just found the first element that is outside the range. This tells us that we've found the last element that could be in the range, there's no point in continuing from now on and we exit the loop. If we have not exited the loop early, then we keep going through the list. Once the whole iteration is done, we return the serialized `members` array. ### By Lexicographic Order Let's add the last `ZRANGE*` command, `ZRANGEBYLEX`, but before looking at the `ZRangeByLexCommand` class, we need to spend some time looking at what a "lex range" is. First things first, the same way numbers can be sorted, strings can be sorted. Well, technically, as we've seen before, string are really array of bytes under the hood, and bytes are numbers, kinda. At least bytes have a numeric value, that's the accurate way of describing it. `'a'` is `97`, `'b'` is `98`, etc ... but that's an implementation detail! We can look at a dictionary to see a real life example. `A` come before `B`, and so on, and if there is a tie, we compare the next letter, and the next, and if there's still a tie, the shorter string is always the shortest one, that makes `'aa' < 'aaa'` a `true` comparison. Lower case letters are considered greater than their upper case equivalent, the following is `true`, `'A' < 'a'`. And for reference, `'A'.ord == 65`, `65` is indeed lower than `97`. At its core, that's what a lex range is, instead of using numbers like we've done before, such as `0 2`, or `0 -1`, a lex range is expressed as `a z`, or `aa aaa`. And the same way that `2 0` was nonsensical when used to return the range in a list, something like `d a` is nonsensical as well, these are empty ranges, there cannot be any elements that fits in them. There are two more things we need to cover about lex ranges, exclusivity with `[` & `(` and special values with `-` & `+`. Let's start with the bracket and parenthesis first. Range boundaries need to be explicitly marked as inclusive or exclusive, `[` means inclusive, and `(` means exclusive. Note that these characters are mandatory. Let's look at few examples: ``` 127.0.0.1:6379> ZADD z 0 a 0 b 0 c 0 d (integer) 4 127.0.0.1:6379> ZRANGEBYLEX z (a (d 1) "b" 2) "c" 127.0.0.1:6379> ZRANGEBYLEX z [a (d 1) "a" 2) "b" 3) "c" 127.0.0.1:6379> ZRANGEBYLEX z [d [a (empty array) 127.0.0.1:6379> ZRANGEBYLEX z [aa (d 1) "b" 2) "c" 127.0.0.1:6379> ZRANGEBYLEX z [d [z 1) "d" 127.0.0.1:6379> ZRANGEBYLEX z (d [z (empty array) ``` The set `z` contains the four members `a`, `b`, `c` & `d`. The first `ZRANGEBYLEX` calls is requesting all the elements between `a` and `d`, excluding both of them, and it returns `b` & `c`. The second example marks `a` as inclusive and the results includes it. The following example shows an instance of an empty range, `d` is greater than `a`, so that range does not make any sense. The next example shows how the string `'aa'` is considered greater than `'a'` which explains why `'a'` is not returned. In the second to last example `d` is marked as inclusive and is the only element returned, in the last example `d` is marked as exclusive and is not returned. Finally, `-` and `+` play a role similar to `-inf` and `+inf` in the `ZRANGEBYSCORE` method, they can be used to specify respectively a value this lower than any other values, and a value that is greater than any other values. A different with the infinity values is what while a score can have the value `-inf` or `inf`, no strings can actually have this special value. You could set a member with the value `-` or `+`, but that's not the same, these are the characters `+` and `-`. You could request them with: `ZRANGEBYLEX z [+ [-` but that's different from requesting `ZRANGEBYLEX z - +`. As a quick aside, `-` is greater than `+`, they have the values `43` & `45`. The character `'*'` has the value `42`, so we could use it: ``` 127.0.0.1:6379> ZADD z 0 + (integer) 1 127.0.0.1:6379> ZADD z 0 - (integer) 1 127.0.0.1:6379> ZRANGEBYLEX z - + 1) "+" 2) "-" 127.0.0.1:6379> zrangebylex z [+ [- 1) "+" 2) "-" 127.0.0.1:6379> zrangebylex z [* [- 1) "+" 2) "-" ``` I'm not sure if you'd ever want to use these values in a range, because that is pretty cryptic, but it is important to understand how these ranges work. The `ZRANGEBYLEX` command has the following format according to the [Redis documentation][redis-doc-zrangebylex]: ``` ZRANGEBYLEX key min max [LIMIT offset count] ``` ``` ruby module BYORedis module SortedSetUtils # ... def self.generic_range_by_lex(db, args, reverse: false) # A negative count means "all of them" options = { offset: 0, count: -1 } Utils.assert_args_length_greater_than(2, args) key = args.shift if reverse max = args.shift min = args.shift else min = args.shift max = args.shift end range_spec = Utils.validate_lex_range_spec(min, max) parse_range_by_lex_options(args, options) unless args.empty? sorted_set = db.lookup_sorted_set(key) if options[:offset] < 0 EmptyArrayInstance elsif sorted_set options[:withscores] = false options[:reverse] = reverse SortedSetSerializerBy.new(sorted_set, range_spec, **options, &:member) else EmptyArrayInstance end end def self.parse_range_by_lex_options(args, options) raise RESPSyntaxError unless args.length == 3 if args.shift.downcase == 'limit' SortedSetUtils.parse_limit_option(args, options) else raise RESPSyntaxError end end end # ... class ZRangeByLexCommand < BaseCommand def call SortedSetUtils.generic_range_by_lex(@db, @args, reverse: false) end def self.describe Describe.new('zrangebylex', -4, [ 'readonly' ], 1, 1, 1, [ '@read', '@sortedset', '@slow' ]) end end end ``` _listing 10.27 The `ZRangeByLexCommand` class_ The `generic_range_by_lex` method will be useful when we add the reverse variant, `ZREVRANGEBYLEX`, which is why it has a `reverse` flag, which defaults to `false`. We need to validate that `min` and `max` are valid lex range items, and if they are, we create an instance of the range spec class specific to lexicographic order, with `GenericRangeSpec.lex_range_spec`: ``` ruby module BYORedis module Utils # ... def self.validate_lex_range_spec(min, max) min_string, min_exclusive = parse_range_item(min) max_string, max_exclusive = parse_range_item(max) RedisSortedSet::GenericRangeSpec.lex_range_spec( min_string, max_string, min_exclusive, max_exclusive) end def self.parse_range_item(item) if item == '+' [ '+', true ] elsif item == '-' [ '-', true ] elsif item[0] == '[' [ item[1..-1], false ] elsif item[0] == '(' [ item[1..-1], true ] else raise ValidationError, 'ERR min or max not valid string range item' end end private_class_method :parse_range_item end ``` _listing 10.28 The `Utils.validate_lex_range_spec` class_ `validate_lex_range_spec` checks the format of both range items with `parse_range_item`. In this method we check all the edge cases. `+` and `-` are considered exclusive since no values can actually be equal to them. Let's now create a new class method on `GenericRangeSpec` to create a range spec that uses lex comparison as its ordering mechanism: ``` ruby module BYORedis class RedisSortedSet # ... class GenericRangeSpec # ... def self.lex_range_spec(min, max, min_exclusive, max_exclusive) GenericRangeSpec.new(min, max, min_exclusive, max_exclusive) do |a, b| RedisSortedSet.lex_compare(a, b) end end # ... end # ... def self.lex_compare(s1, s2) return 0 if s1 == s2 return -1 if s1 == '-' || s2 == '+' return 1 if s1 == '+' || s2 == '-' s1 <=> s2 end # ... end # ... end ``` _listing 10.29 The `GenericRangeSpec.lex_range_spec` class method_ The comparison of lex items is a bit trickier than previous comparisons we've had to deal with previously and is why we previously created the `compare_with_min` and `compare_with_max` methods. It is implemented in the `lex_compare` and essentially follows these rules: - If both strings are equal, return `0` - Otherwise, if the first string is `-`, or if the second string is `+`, then the first string is smaller than the second one - Otherwise, if the first string is `+` or the second string is `-`, then the first string is greater than the second string. - Otherwise, compare the strings the "regular" way, with `<=>`, that is `b` is greater than `aa`, which is greater than `a`, etc ... This is the [`String#<=>`][ruby-doc-string-spaceship] method. By using this new comparison system, but still returning `-1`, `0`, and `1` depending on the order, we can reuse all the code from `GenericRangeSpec`, neat!. And now that we've looked at this new way of using `GenericRangeSpec`, let's look at all the pieces falling into place. Back in `SortedSetUtils.generic_range_by_lex`, we now call `SortedSetSerializerBy` with the sorted set, the range spec, the parsed options, namely `LIMIT` and `OFFSET`, and the block `&:member`, the equivalent of `{ |x| x.member }`. We've spent a good amount of time talking about why we wrote `SortedSetSerializerBy` in a way that never explicitly called `.score` or `.member`, or even knew how to compare elements, and this is about to pay off. The `serialize` method in `SortedSetSerializerBy` can now return early if the range spec is empty, and the range spec is now a `GenericRangeSpec` created with `RedisSortedSet.lex_compare(a, b)` as the comparison block, so it will know how to compare the `min` and `max` elements and determine if the lex range is empty. It will also call `no_overlap_with_range?` with the block we gave it, which extracts the `member` attribute from a pair, and will again return early, if it determines that there is no overlap between ranges. Both specific methods, `serialize_zset` and `serialize_list`, function the exact same way as we explored in `ZRANGEBYSCORE`, the range spec says whether or not an item is in range, and if so they're accumulated, with or without their scores, in an array and returned to the user. And we'll be able to reuse a lot of this code soon with the `*REV*` commands too! ## Set Operations, Union & Intersection Sorted sets support set operation commands similar to the ones we added in the previous chapter, the `SINTER` and `SUNION` methods in the previous chapters, as well as their `*STORE` variants. As of Redis 6.0 there is no `ZDIFF` and `ZDIFFSTORE` commands, but it might be added soon as there is an active Pull Request as of November 2020: https://github.com/redis/redis/pull/7961. It _should_ be added in 6.2.0. The topic of the ZDIFF command has been discussed for a while, an earlier PR dates from April 2012: https://github.com/redis/redis/pull/448 The initial resistance to adding a `ZDIFF` commands has been discussed in the mailing list and can be summarized by this [2010 comment][google-group-zdiff-comment] from Redis developer <NAME>: > ZDIFFSTORE makes no sense, as discussed before on the ML (please search before posting). The intrinsic value of the scores gets lost when you simply start subtracting them As we're about to see, both `ZINTER` and `ZUNION` offer mechanisms to let users decide what happens to the score values from multiple sets and how to combine them. On the other hand, things would be different with `ZDIFF` as values could be completely discarded. ### Set Intersection Let's look at `ZINTER` first. Note that `ZINTER` was only added in Redis 6.2.0, in earlier versions only `ZINTERSTORE` was available. ``` bash 127.0.0.1:6379> ZADD z1 0 a 1 b 2 c (integer) 3 127.0.0.1:6379> ZADD z2 10 z 5 x 3 c (integer) 3 127.0.0.1:6379> ZINTER 2 z1 z2 1) "c" 127.0.0.1:6379> ZINTER 2 z1 z2 WITHSCORES 1) "c" 2) "5" ``` `ZINTER` requires the first argument to be the number of sets that will be given next. Without this explicit count argument, the command `ZINTER z1 z2 WITHSCORES` would be ambiguous, what if there is a set at the key `WITHSCORES`, did you mean the intersection of the three sets `z1`, `z2` & `WITHSCORES`, or the intersection of `z1` and `z2` with the option `WITHSCORES`? The `numkeys` argument prevents this and makes the number of set explicit. We can see in the previous example that the score of the only element in the result set is `5`, which is the sum of the score for member `c` in `z1` and the score for member `c` in `z2`. The aggregation of scores default to `SUM` and can be controller with the `AGGREGATE` option. The other two possible values are `MIN` and `MAX`: ``` bash 127.0.0.1:6379> ZINTER 2 z1 z2 WITHSCORES AGGREGATE MAX 1) "c" 2) "3" 127.0.0.1:6379> ZINTER 2 z1 z2 WITHSCORES AGGREGATE MIN 1) "c" 2) "2" ``` The last option to `ZINTER` is `WEIGHTS`, it _must_ be followed by a list of valid float values, of length equal to `numkeys`. In other words, if you explicit pass the `WEIGHTS` option, you need to give a weight for each set we're computing the intersection of. The implicit default value of the weights is `1`. When combining values in the final set, each score will be multiplied by the weight given to its set: ``` bash 127.0.0.1:6379> ZINTER 2 z1 z2 WITHSCORES WEIGHTS 1 1 1) "c" 2) "5" 127.0.0.1:6379> ZINTER 2 z1 z2 WITHSCORES WEIGHTS 1 2 1) "c" 2) "8" 127.0.0.1:6379> ZINTER 2 z1 z2 WITHSCORES WEIGHTS 1 3 1) "c" 2) "11" 127.0.0.1:6379> ZINTER 2 z1 z2 WITHSCORES WEIGHTS 10 3.2 1) "c" 2) "29.600000000000001" 127.0.0.1:6379> ZINTER 2 z1 z2 WITHSCORES WEIGHTS 10 inf 1) "c" 2) "inf" ``` As we can see, `WEIGHTS 1 1` returns the same as if we had omitted the weights, `5`. With `WEIGHTS 1 2`, all the members from the second set, `z2` will have their weight multiplied by `2` before being aggregated, so `2 * 1 + 3 * 2 == 8`, and in the next example we end up at `11` with `2 * 1 + 3 * 3`. The next example show that weights can be float, so `2 * 10 + 3 * 3.2 ~= 29.6`. In the last example, we end up with `inf` because any values multiplied by infinity equals infinity. The weight values are applied before the aggregation: ``` bash 127.0.0.1:6379> ZINTER 2 z1 z2 WITHSCORES WEIGHTS 100 10 AGGREGATE MAX 1) "c" 2) "200" 127.0.0.1:6379> ZINTER 2 z1 z2 WITHSCORES WEIGHTS 100 10 AGGREGATE MIN 1) "c" 2) "30" 127.0.0.1:6379> ZINTER 2 z1 z2 WITHSCORES WEIGHTS 100 10 AGGREGATE SUM 1) "c" 2) "230" ``` `200` is the result of `MAX((2 * 100), (3 * 10))`, `30` is the result of `MIN((2 * 100), (3 * 10))` and `230` is the result of `SUM((2 * 100), (3 * 10))`. Finally, `ZINTER` accepts regular sets, and assumes a score of `1` for each score-less set members. ``` bash 127.0.0.1:6379> ZINTER 3 z1 z2 s WITHSCORES 1) "c" 2) "6" 127.0.0.1:6379> ZINTER 3 z1 z2 s WITHSCORES WEIGHTS 0 0 1 1) "c" 2) "1" ``` Let's now create the `ZInterCommand` class, but first, since we already know we have three more very similar commands coming up soon, `ZINTERSTORE`, `ZUNION` & `ZUNIONSTORE`, let's go ahead and add methods in `SortedSetUtils` in order to reuse code across these commands. The [Redis documentation][redis-doc-zinter] describes the format of the command as: ``` ZINTER numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX] [WITHSCORES] ``` ``` ruby module BYORedis module SortedSetUtils # ... def self.intersection(db, args) set_operation(db, args) do |sets_with_weight, aggregate| RedisSortedSet.intersection(sets_with_weight, aggregate: aggregate) end end def self.set_operation(db, args) options = { aggregate: :sum, withscores: false } sets = SortedSetUtils.validate_number_of_sets(db, args) options.merge!(SortedSetUtils.parse_union_or_inter_options(args, sets.size)) sets_with_weight = sets.zip(options[:weights]) new_set = yield sets_with_weight, options[:aggregate] return new_set, options[:withscores] end def self.set_operation_command(args) Utils.assert_args_length_greater_than(1, args) set_result, withscores = yield SortedSetRankSerializer.new( set_result, RedisSortedSet::GenericRangeSpec.rank_range_spec(0, -1, set_result.cardinality), withscores: withscores, ) end def self.parse_union_or_inter_options(args, number_of_sets) options = { weights: Array.new(number_of_sets, 1) } while arg = args.shift case arg.downcase when 'weights' options[:weights] = validate_weights(number_of_sets, args) when 'aggregate' aggregate_mode = args.shift case aggregate_mode&.downcase when 'min' then options[:aggregate] = :min when 'max' then options[:aggregate] = :max when 'sum' then options[:aggregate] = :sum else raise RESPSyntaxError end when 'withscores' then options[:withscores] = true else raise RESPSyntaxError end end options end def self.validate_number_of_sets(db, args) number_of_sets = Utils.validate_integer(args.shift) if number_of_sets <= 0 raise ValidationError, 'ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE' else number_of_sets.times.map do set_key = args.shift raise RESPSyntaxError if set_key.nil? db.lookup_sorted_set_or_set(set_key) end end end def self.validate_weights(number_of_sets, args) number_of_sets.times.map do weight = args.shift raise RESPSyntaxError if weight.nil? Utils.validate_float(weight, 'ERR weight value is not a float') end end end # ... class ZInterCommand < BaseCommand def call SortedSetUtils.set_operation_command(@args) do SortedSetUtils.intersection(@db, @args) end end def self.describe Describe.new('zinter', -3, [ 'readonly', 'movablekeys' ], 0, 0, 0, [ '@read', '@sortedset', '@slow' ]) end end end ``` _listing 10.30 The `ZInterCommand` class_ The `ZInterCommand` is surprisingly short, it essentially amounts to the two statements: "Perform a regular set operation, no store, and use the intersection operation". Using this level of abstraction will allow us to write the following commands in a very concise way as well, but let's look at what `SortedSetUtils.set_operation_command` and `SortedSetUtils.intersection` do. `set_operation_command` is the method that performs the first validation, we need at least two arguments, the number of sets, `numkeys` and at least one set key. It then uses `yield` to give back the values of the actual result, as well as the options to the caller, the `call` method. The results from `yield`, which we'll look at shortly, are then fed to the `SortedSetRankSerializer` class, the same class we used to implement the `ZRANGE` command. With the range from `0` to `-1` this serializer will serialize the whole set, in rank order, which is what we need to return. The value of `withscores`, as well as `set_result`, come from calling `yield`, which returns `SortedSetUtils.intersection(@db, @args)` as we can see in the `ZInterCommand` class. This `intersection` method is a wrapper around `RedisSortedSet.intersection`, with a few additional steps, such as parsing all the remaining options, `WEIGHT`, `AGGREGATE` and `WITHSCORES`. These steps are performed in the `SortedSetUtils.set_operation`, which first calls the methods `validate_number_of_sets`, to check that we have the correct number of keys after the `numkeys` argument, and loads all the set with `DB#lookup_sorted_set_or_set`. We need this new method because this commands and the other set union commands for sorted sets accept regular sets as arguments as well: ``` ruby module BYORedis class DB # ... def lookup_sorted_set_or_set(key) set = @data_store[key] raise WrongTypeError if set && !set.is_a?(RedisSortedSet) && !set.is_a?(RedisSet) set end end end ``` _listing 10.31 The `DB#lookup_sorted_set_or_set` method_ Going back to `set_operation`, the next step is calling `parse_union_or_inter_options`. At this time we've parsed the value of `numkeys` so we know how many sets to expect, which means that if the `WEIGHTS` option is present, we have to validate that the number of weights matches the `numkeys` value. This validation is performed in the `validate_weights` method. We generate the default weight values with the line `Array.new(number_of_sets, 1)`. It initializes an array for which the size is `number_of_sets`, and all the elements are `1`. The other options we need to check for are `aggregate`, in which case the next argument _must_ be one of `min`, `max`, or `sum`, and `withscores`, if it is present, we set the corresponding flag to true. The `parse_union_or_inter_options` is a little bit simpler than the `parse_options` method in the `ZAddCommand` class because the options come at the end of the argument list here. This allows us to skip the whole "peek and only consume if the head is an option" approach we used there. Here we can `shift` as long as we find valid options. ##### The `Array#zip` method Once the weight values have been parsed into `BigDecimal` instances, we combine them with the set objects with the [`Array#zip`][ruby-doc-array-zip] method. This is a method we haven't used so far so let's take a quick look at what it does, sure, it "zips" things, but what does it mean? ```ruby irb(main):001:0> a1 = [1,2,3,4] irb(main):002:0> a2 = ['a','b','c','d'] irb(main):003:0> a1.zip(a2) => [[1, "a"], [2, "b"], [3, "c"], [4, "d"]] ``` `zip` is called on an array and the arguments are one or more arrays, the result is ... also an array, where each element is ... another array, which is the combination of elements from all the arrays at matching indices! Yup, that's a lot of arrays. Let's look at what happens with three arrays: ``` ruby irb(main):004:0> a3 = [true, false, true, false] irb(main):005:0> a1.zip(a2, a3) => [[1, "a", true], [2, "b", false], [3, "c", true], [4, "d", false]] ``` We can even reuse zip an array with itself: ``` ruby irb(main):006:0> a1.zip(a2, a3, a1) => [[1, "a", true, 1], [2, "b", false, 2], [3, "c", true, 3], [4, "d", false, 4]] ``` Lastly, let's look at the behavior when the lengths don't exactly match: ``` ruby irb(main):007:0> a1.zip([ true ]) => [[1, true], [2, nil], [3, nil], [4, nil]] irb(main):008:0> [true].zip(a1) => [[true, 1]] ``` The final result is always the same length as the `Array` we called `zip` on, and `nil` values are thrown in there if the other arrays are too small. ##### Finalizing the set intersection operation Back to the our use of the `zip` method in `set_operation`, we have an `Array` of `RedisSortedSet` or `RedisSet` and an `Array` of `BigDecimal`, and we zip them together in an array of pairs. This will allow us to iterate over the pairs and each element will contain a set, either sorted or not, and its weight. The next line in `set_operation` is `new_set = yield sets_with_weight, options[:aggregate]`, where we delegate the work of actually performing the operation, union, or intersection to the caller, in our case, the block `SortedSetUtils.intersection` method, which calls `RedisSortedSet.intersection`, with the sets, weights and options that `set_operation` took care of parsing for us. Once the set operation is performed, the whole stack unravels and the `set_operation_command` ends up back in control, it finally has a value for `set_result`, and feeds it to `SortedSetRankSerializer`, which is returned by `ZInterCommand#call`. That was a lot of blocks, yields, method calls, so let's summarize it: * `ZInterCommand#call` calls `SortedSetUtils.set_operation_command` with a block * `SortedSetUtils.set_operation_command` validates the length of the argument list and yields back to `ZInterCommand#call` * `ZInterCommand#call` calls `SortedSetUtils.intersection` from the block now that the argument list is confirmed to have the required number of elements * `SortedSetUtils.intersection` calls `SortedSetUtils.set_operation` with a block * `SortedSetUtils.set_operation` does a lot of the heavy lifting, loading the sets from memory, failing if they're of the wrong type, parsing all the arguments, and yields all that back to `SortedSetUtils.intersection` with the `sets_with_weights` and `aggregate` variable. * `SortedSetUtils.intersection` calls `RedisSortedSet.intersection` from the block with the `sets_with_weight` and `aggregate` variables * The result of `RedisSortedSet.intersection` is handled by `SortedSetUtils.set_operation` with the line `new_set = yield sets_with_weight, options[:aggregate]`, and it then returns it, alongside the `withscores` option. * The result of `SortedSetUtils.set_operation` is handled by `SortedSetUtils.set_operation_command` with the `set_result, withscores = yield` line, which it uses to create an instance of `SortedSetRankSerializer`. * The result of `SortedSetUtils.set_operation_command` is the last line of `ZInterCommand#call` and is what is returned to the `Server` class. The following is a summary of the main methods called: ``` call { Utils.intersection } set_operation_command validations Utils.intersection (through yield) set_operation { RedisSortedSet.intersection } validations RedisSortedSet.intersection (through yield) SortedSetRankSerializer.new ``` And with that, the `ZINTER` commands is done. Well, almost, we haven't looked at the _actual_ intersection implementation, in `RedisSortedSet`, let's do that now: ``` ruby module BYORedis class RedisSortedSet # ... def self.intersection(sets_with_weight, aggregate: :sum) # Sort the sets smallest to largest sets_with_weight.sort_by! { |set, _| set.nil? ? 0 : set.cardinality } smallest_set = sets_with_weight[0][0] smallest_set_weight = sets_with_weight[0][1] return RedisSortedSet.new if smallest_set.nil? intersection_set = RedisSortedSet.new # Iterate over the first set, if we find a set that does not contain the member, discard smallest_set.each do |set_member| present_in_all_other_sets = true if set_member.is_a?(Pair) pair = set_member else pair = Pair.new(BigDecimal(1), set_member) end weighted_pair_score = Utils.multiply_or_zero_if_nan(smallest_set_weight, pair.score) # For each member of the smallest set, we loop through all the other sets and try to # find the member, if we don't find it, we break the loop and move on, if we do find # a member, then we need to apply the weight/aggregate logic to it sets_with_weight[1..-1].each do |set_with_weight| set = set_with_weight[0] weight = set_with_weight[1] if set == smallest_set other_pair = pair elsif set.is_a?(RedisSet) other_pair = set.member?(pair.member) ? Pair.new(BigDecimal(1), pair.member) : nil elsif set.is_a?(RedisSortedSet) other_pair = set.find_pair(pair.member) else raise "Unknown set type: #{ set }" end if other_pair weighted_other_pair_score = Utils.multiply_or_zero_if_nan(other_pair.score, weight) weighted_pair_score = case aggregate when :sum then weighted_pair_score + weighted_other_pair_score when :max then [ weighted_other_pair_score, weighted_pair_score ].max when :min then [ weighted_other_pair_score, weighted_pair_score ].min else raise "Unknown aggregate method: #{ aggregate }" end else present_in_all_other_sets = false break end end # Otherwise, keep if present_in_all_other_sets intersection_set.add(weighted_pair_score, pair.member, {}) end end intersection_set end def self.aggregate_scores(aggregate, a, b) case aggregate when :sum then Utils.add_or_zero_if_nan(a, b) when :max then a < b ? b : a when :min then a < b ? a : b else raise "Unknown aggregate method: #{ aggregate }" end end private_class_method :aggregate_scores # ... def find_pair(member) case @underlying when List then list_find_pair(member) when ZSet dict_entry = @underlying.dict.get_entry(member) Pair.new(dict_entry.value, dict_entry.key) if dict_entry else raise "Unknown type for #{ @underlying }" end end def empty? cardinality == 0 end def each(&block) case @underlying when List then @underlying.each(&block) when ZSet then @underlying.array.each(&block) else raise "Unknown type for #{ @underlying }" end end # ... private # ... def list_find_pair(member) @underlying.each do |pair| return pair if pair.member == member end nil end end end ``` _listing 10.32 The `RedisSortedSet.intersection` method_ The logic is overall similar to the one we wrote in `RedisSet.intersection`, with the main difference being that we need to handle weights, and how to aggregate them. We start in a similar way, we sort sets from smallest to largest, because that way we will only iterate through the smallest set. If that set is nil, then we don't even have to go further, an empty set in an intersection guarantees that the result is an empty set. Like `0` in a multiplication, it doesn't matter what the other parts of the operation are. Once sets are sorted, the smallest set is the value at `sets_with_weight[0][0]`, the first element in the first pair of the main array, and its weight is at `sets_with_weight[0][1]`, the second element in the first pair of the main array. Remember that `sets_with_weights` looks like the following where `'s1'`, `'s2'` & `'s3'` are set instances: ``` ruby [ [ 's1', 1 ], [ 's2', 10 ], [ 's3', 0.5 ], ] ``` We now need to iterate through the smallest set, knowing that it might either be a `RedisSet` or a `RedisSortedSet`. `RedisSet` already has an `each` method, which we created in the previous chapter, but we're adding one on `RedisSortedSet` here. Both are pretty similar, they need to know how to iterate over the underlying data structure, in this case either a `List` or a `ZSet`. In the `List` case we use the new addition to the `List` class, `each`. For the `ZSet`, we use its `array` attribute, which is a `SortedArray`, and call `each` on it, which is the "real" `Array#each` method, forwarding the `block` attribute to it, with the ampersand, because Ruby needs that for blocks. The array is sorted, so callers will receive the elements in the correct order. Once we're in the iteration itself, in the block, if we're dealing with a `RedisSet`, then we won't get a `Pair` instance at each iteration, and we'll instead get a `String`, since `RedisSet` instances only store `String` instances as members. In this case we create a `Pair`, with a default score of `BigDecimal(1)`. Next we need to apply the `weight` value for that set to the score of the current member. While we might think that a multiplication with `*` would be enough, it's actually not! We need to handle `NaN` values, such as `0 * inf`. We do this with the accurately named `Utils.multiply_or_zero_if_nan` method. If applying a weight to a score results in `NaN`, we default to `0`. The next step of the intersection process is to iterate over all the other sets, and as soon as we find one that does not contain the current member of the smallest set, we stop and move on to the next element in the smallest set. We start the iteration with `sets_with_weight[1..-1]`, and we then extract the `set` and `weight` variable from the `set_with_weight` pair. It is possible that the same set is reused multiple times in a `ZINTER` command, such as `ZINTER 3 z1 z1 z1`, and in this case we do not need to look the pair up in the other set. The variable `pair`, from the smallest set, is the same, so we set `other_pair` to `pair`, as a shortcut, to avoid a lookup in `set`. Otherwise, we need to lookup `pair` in `set`, but `set` might a regular set or a sorted set. We test for the presence in a `RedisSet` instance with `set.member?(pair.member)`, and if we find a match, we create a new `Pair` instance with a default score of `1`, as we did earlier with the element from the smallest set. If `set` is a `RedisSortedSet`, then we call the `RedisSortedSet#find_pair` method. The `find_pair` method behaves differently depending on the type of `@underlying`. If it is a `ZSet`, we use the `get_entry` method with its `dict` attribute, which performs an O(1) operation to retrieve the element from the sorted set, or `nil`. If there is a result we instantiate a new `Pair` instance with the score and member values from `dict`. As we've already seen many times the `List` case is a bit more cumbersome and we delegate it to a private method. That method, `list_find_pair`, uses the `List#each` method to iterate through the list until it either reaches the end of the list or it finds a `Pair` instance in it for which its `member` attributes matches the `member` argument, which is an O(n) operation. Earlier we talked about why it was great that procs allowed us to return from the outer method, and this is a great example, it allows us to short-ciruit the iteration in the `each` method. Back to the `intersection` class method, by now we either found `other_pair` in `set`, or not. If we failed to find it, we break from the loop and move to the next element in the smallest set while setting `present_in_all_sets` to `false`. This variable is necessary because when we exit the loop over all the other sets, we need to know whether the current element in the smallest set, `pair` should be added to the result set, and it should only be added if we did find it in all the other sets. On the other hand, if `other_pair` is not nil, then we need to aggregate the scores, but first we need to apply the `weight` of the other set to `other_pair`, which we again use `multiply_or_zero_if_nan` for. The aggregation is delegated to the private class method `aggregate_scores`. This method takes an aggregate symbol, either `:min`, `:max` or `:sum` and two numeric values. It uses a `case/when` to apply the correct function, using `Utils.add_or_zero_if_nan` as a safety measure because some additions might return `NaN`, such as `inf - inf`. Let's add this method as well as `multiply_or_zero_if_nan`: ``` ruby module BYORedis module Utils # ... def self.multiply_or_zero_if_nan(a, b) BigDecimal.save_exception_mode do BigDecimal.mode(BigDecimal::EXCEPTION_NaN, true) a * b end rescue FloatDomainError BigDecimal(0) end def self.add_or_zero_if_nan(a, b) add_or_raise_if_nan(a, b) rescue FloatNaN BigDecimal(0) end end end ``` _listing 10.33 The `add_or_zero_if_nan` & `multiply_or_zero_if_nan` methods_ If the `aggregate` value is neither of the expected ones we follow the "this is not supposed to happen so throw a generic exception so that bugs are caught in the development cycle" approach. As previously mentioned, once we exit the loop over all the other sets, we need to check _why_ we exited it. Did we check all the sets and found `pair` in all of them? If so we need to add it, with the aggregated score, to the result set, `intersection_set`, otherwise, we can move on to the next member of the smallest set. And with that, we're now done, for real, with the `ZINTER` command. #### Sorted Set Intersection, but store the result this time `ZINTERSTORE` behaves almost exactly as `ZINTER`, with the only difference being that the first argument is the key where the result set will be stored and the return value is the cardinality of the new set. The format is described as the following by the [Redis documentation][redis-doc-zinterstore]: ``` ZINTERSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX] ``` Let's create the `ZInterStoreCommand` class: ``` ruby module BYORedis module SortedSetUtils # ... def self.set_operation_store_command(db, args) Utils.assert_args_length_greater_than(2, args) destination_key = args.shift result_set, _ = yield if result_set.empty? db.data_store.delete(destination_key) else db.data_store[destination_key] = result_set end RESPInteger.new(result_set.cardinality) end # ... end # ... class ZInterStoreCommand < BaseCommand def call SortedSetUtils.set_operation_store_command(@db, @args) do SortedSetUtils.intersection(@db, @args) end end def self.describe Describe.new('zinterstore', -4, [ 'write', 'denyoom', 'movablekeys' ], 0, 0, 0, [ '@write', '@sortedset', '@slow' ]) end end # ... end ``` _listing 10.34 The `ZInterStoreCommand` class_ Earlier we created the `SortedSetUtils.set_operation_command` method so we could share some of the logic between `ZINTER` and `ZUNION`, because they accept the same arguments, the only difference is that one performs an intersection and one a union. We're doing the same here with `SortedSetUtils.set_operation_store_command`, so that we share some logic between `ZINTERSTORE` and `ZUNIONSTORE`, which are both similar to the non-store commands, but different because they accept an extra key, `destination`. The `set_operation_store_command` checks that we have more than two arguments, the smallest list of arguments we can accept is `destination`, `numkeys` set to `1` and one `key`. We then call `Array#shift`, to extract the `destination` argument, and we end up with an argument list identical to what `ZINTER` accepts, so we use the exact same method in the `SortedSetUtils` module we did earlier, `intersection`. The other difference is in how we handle the result of the intersection operation, instead of returning it to the client, we store it at `destination_key`, and we return its cardinality. This is what `set_operation_store_command` does once it received the result from `yield`. Note that we discard the `withscores` value because we're not serializing the set. This command, like other `*STORE` commands deletes whatever was stored at `destination` if the result of the operation is empty. Redis never stores empty collection, but it clears the destination, to make the following sequence of operation sensible: ``` 127.0.0.1:6379> SET a-string whatever OK 127.0.0.1:6379> TYPE z none 127.0.0.1:6379> ZINTERSTORE a-string 2 z z (integer) 0 127.0.0.1:6379> ZCARD a-string (integer) 0 ``` The result of `ZINTERSTORE` is `0`, telling us that the result set is empty, and it seems reasonable that calling `ZCARD` on it would also return `0`, to keep things consistent. If Redis did not delete whatever might have already existed, the `a-string` key would still have been a string, and this is what we would have observed, which would have been _very_ surprising for users: ``` 127.0.0.1:6379> SET a-string whatever OK 127.0.0.1:6379> TYPE z none 127.0.0.1:6379> ZINTERSTORE a-string 2 z z (integer) 0 127.0.0.1:6379> ZCARD a-string (error) WRONGTYPE Operation against a key holding the wrong kind of value ``` ### Set Union Like `ZINTER`, `ZUNION` is a recent addition to Redis and was added in 6.2.0. `ZUNION` accepts the exact same options than `ZINTER`, the only difference being that it returns the set union instead of the set intersection. ``` ruby module BYORedis module SortedSetUtils # ... def self.union(db, args) set_operation(db, args) do |sets_with_weight, aggregate| RedisSortedSet.union(sets_with_weight, aggregate: aggregate) end end # ... end # ... class ZUnionCommand < BaseCommand def call SortedSetUtils.set_operation_command(@args) do SortedSetUtils.union(@db, @args) end end def self.describe Describe.new('zunion', -3, [ 'readonly', 'movablekeys' ], 0, 0, 0, [ '@read', '@sortedset', '@slow' ]) end end end ``` _listing 10.35 The `ZUnionCommand` class_ We can already see some of the decisions we made earlier when implementing `ZINTER` paying off. The content of `ZUnionCommand#call` is really concise and very similar to `ZInterCommand#call`, the only difference is the content of the block passed to `SortedSetUtils.set_operation_command`, which is `SortedSetUtils.union` this time. This method, `SortedSetUtils.union` is very similar to `SortedSetUtils.intersection`, it also calls `SortedSetUtils.set_operation`, which does the heavy lifting with regards to all the possible options, and calls `RedisSortedSet.union` instead: ``` ruby module BYORedis class RedisSortedSet # ... def self.union(sets_with_weight, aggregate: :sum) return RedisSortedSet.new({}) if sets_with_weight.empty? accumulator = Dict.new sets_with_weight[0..-1].each do |set_with_weight| set = set_with_weight[0] weight = set_with_weight[1] next if set.nil? set.each do |set_member| if set.is_a?(RedisSet) pair = Pair.new(BigDecimal(1), set_member) elsif set.is_a?(RedisSortedSet) pair = set_member else raise "Unknown set type: #{ set }" end weighted_score = Utils.multiply_or_zero_if_nan(pair.score, weight) existing_entry = accumulator.get_entry(pair.member) if existing_entry new_score = aggregate_scores(aggregate, existing_entry.value, weighted_score) existing_entry.value = new_score else accumulator[pair.member] = weighted_score end end end union_set = RedisSortedSet.new accumulator.each do |key, value| union_set.add(value, key) end union_set end # ... end end ``` _listing 10.36 The `RedisSortedSet.union` method_ Set intersection was the complicated one, and we've kept the simpler version of the two for last. `RedisSet.union` was also the simplest of the set operations in the previous chapter, and it is the same here. We need to iterate through all the sets no matter what, there's no shortcut here. For each set member, we need to check what type of set it is, and give it the default score of `1` if it's a "regular" set. We then weigh the scores, aggregate them, and throw the result in `accumulator`, a `Dict`. The use of a `Dict` here might be a bit surprising, because we need to return a `RedisSortedSet` after all. This is a small optimization because inserting in a `Dict` is cheaper on average than inserting in a `RedisSortedSet`. There might be a lot of insertions and updates required as we go through all the set members. It's entirely possible that members change positions through the iteration, but we don't care about maintaining the set sorted while we iterate, we only care about it at the end. So we use a `Dict`, which is an efficient way to keep track of all the members, updating their scores is "cheap" as we can find the dict entry, update its score and move on, no re-ordering or anything. Once the whole iteration is over, for all the sets, we convert the `Dict` to a `RedisSortedSet`, and we're done! #### Sorted Set Union stored instead of returned Finally, `ZUNIONSTORE` is the union variant, which behaves similarly to `ZINTERSTORE`, let's create the `ZUnionStoreCommand` class: ``` ruby module BYORedis # ... class ZUnionStoreCommand < BaseCommand def call SortedSetUtils.set_operation_store_command(@db, @args) do SortedSetUtils.union(@db, @args) end end def self.describe Describe.new('zunionstore', -4, [ 'write', 'denyoom', 'movablekeys' ], 0, 0, 0, [ '@write', '@sortedset', '@slow' ]) end end end ``` _listing 10.37 The `ZUnionStoreCommand` class_ By now we're already implemented all these methods! We've seen `SortedSetUtils.set_operation_store_command` when adding `ZINTERSTORE` and we've just seen `SortedSetUtils.union` when adding `ZUNION`. We can reuse the existing, and like Lego bricks, assemble them in a slightly different way and get what we need, sweet! Done with set operations, next we're going to move to a few utility commands returning information about sorted set members. ## Member data retrieval commands Redis supports some commands to retrieve information for one or more members in a sorted set. `ZRANK` returns the "rank", that is the position as a zero-based index of the member in the sorted set, or a `nil` string if it is not present. `ZSCORE` & `ZMSCORE` are similar, with the difference that `ZMSCORE` accepts multiple members and returns an array, similar so `SMISMEMBER` in the previous chapter. As their name implies, they return the score of the given member(s). Note that `ZMSCORE` is a recent addition in Redis 6.2.0. Let's start with the `ZRankCommand` class: ``` ruby module BYORedis # ... class ZRankCommand < BaseCommand def call Utils.assert_args_length(2, @args) sorted_set = @db.lookup_sorted_set(@args[0]) if sorted_set RESPSerializer.serialize(sorted_set.rank(@args[1])) else NullBulkStringInstance end end def self.describe Describe.new('zrank', 3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@sortedset', '@fast' ]) end end end ``` _listing 10.38 The `ZRankCommand` class_ The `ZRANK` command accepts two arguments, `key` and `member`, and nothing else, if we find a `RedisSortedSet` for `key`, we call the new `RedisSortedSet#rank` method: ```ruby module BYORedis class RedisSortedSet # ... def rank(member) case @underlying when List then find_member_in_list(member) { |_, rank| rank } when ZSet entry = @underlying.dict.get_entry(member) return nil unless entry @underlying.array.index(Pair.new(entry.value, member)) else raise "Unknown type for #{ @underlying }" end end private # ... def find_member_in_list(member) index = 0 @underlying.each do |pair| return yield pair, index if pair.member == member index += 1 end nil end end end ``` _listing 10.39 The `RedisSortedSet#rank` method_ To retrieve the rank of a member in `List`, we start iterating from the left with `each`, and count, until we find it. The rank of an element is its 0-based index after all. In a `ZSet` things are bit different. We could iterate through the sorted array, until we find the element we're looking for, but the combination of the `Dict` and the `SortedArray` allow us to be more efficient! We first call `Dict#get_entry`, to retrieve the `Pair` instance. This is already a big win, because if there is no entry, we can return `nil` right away, we know that there is no rank value to return. On the other hand, if we did find a member, the `Dict` itself cannot tell us its rank, because the `Pair` instances it stores are not ordered. We use the `SortedArray` for that, and because we have both the `score` and `member` values, we can leverage the sorted property to find the element faster than by having to iterate through the whole array, in O(logn) time. By knowing the score it's looking for, the `SortedArray#index` method will use binary search, with the `bsearch_index` method, to get to the element in less steps. The index returned by `SortedArray#index` happens to be the rank value, we found what we were looking for. Next is the `ZScoreCommand` class: ``` ruby module BYORedis # ... class ZScoreCommand < BaseCommand def call Utils.assert_args_length(2, @args) sorted_set = @db.lookup_sorted_set(@args[0]) if sorted_set RESPSerializer.serialize(sorted_set.score(@args[1])) else NullBulkStringInstance end end def self.describe Describe.new('zscore', 3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@sortedset', '@fast' ]) end end end ``` _listing 10.40 The `ZScoreCommand` class_ The `ZSCORE` command has a similar structure to `ZRANK`, it takes two arguments, `key` and `member`. We need to add the `RedisSortedSet#score` method: ``` ruby module BYORedis class RedisSortedSet # ... def score(member) case @underlying when List then find_member_in_list(member) { |pair, _| pair.score } when ZSet then @underlying.dict[member] else raise "Unknown type for #{ @underlying }" end end # ... end end ``` _listing 10.41 The `RedisSortedSet#score` method_ In the `List` case we use the same method we used earlier, `find_member_in_list`, and we return the `score` value of the element, if we find it. Things are easier in the `Dict` case, compared to `ZRANK`, the result of `Dict#[]` will return the value we store in each `DictEntry`, which happens to be the score, remember the keys are the member values, because these are the ones we need to maintain uniqueness on. So we have the score, we can return it. And finally, let's add the `ZMScoreCommand` class: ``` ruby module BYORedis # ... class ZMScoreCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) sorted_set = @db.lookup_sorted_set(@args[0]) scores = @args[1..-1].map do |member| sorted_set.score(member) if sorted_set end RESPArray.new(scores) end def self.describe Describe.new('zmscore', -3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@sortedset', '@fast' ]) end end end ``` _listing 10.42 The `ZMScoreCommand` class_ `ZMSCORE` can use mostly the same approach we used in `ZSCORE`, with the difference being that we iterate over each member we received in the argument list, and call `RedisSortedSet#score` for each of them, within a block given to `Array#map` so that the return value is a map of scores, potentially containing `nil` values. ## Remove commands Redis provides different ways to remove members from a sorted set. In this section we'll implement the `ZREM`, `ZREMRANGEBYLEX`, `ZREMRANGEBYRANK` & `ZREMRANGEBYSCORE` commands. Four other commands also remove members from sorted sets, `ZPOPMIN` & `ZPOPMAX` as well as their blocking variants, we'll explore these later in the chapter. We'll add `ZREM` first: ``` ruby module BYORedis # ... class ZRemCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) sorted_set = @db.lookup_sorted_set(@args.shift) removed_count = 0 if sorted_set @args.each do |member| removed_count += 1 if sorted_set.remove(member) end end RESPInteger.new(removed_count) end def self.describe Describe.new('zrem', -3, [ 'write', 'fast' ], 1, 1, 1, [ '@write', '@sortedset', '@fast' ]) end end end ``` _listing 10.43 The `ZRemCommand` class_ `ZREM` accepts one or more members, so we iterate over all of them, after shifting the `key` argument from the argument array. For each member, we call `RedisSortedSet#remove` and increment a counter if it returned `true`. Let's add this method: ``` ruby module BYORedis class RedisSortedSet # ... def remove(member) case @underlying when List then remove_list(member) when ZSet then @underlying.remove_member(member) else raise "Unknown type for #{ @underlying }" end end # ... private # ... def remove_list(member) iterator = List.left_to_right_iterator(@underlying) while iterator.cursor if iterator.cursor.value.member == member @underlying.remove_node(iterator.cursor) return true end iterator.next end false end end end ``` _listing 10.44 The `RedisSortedSet#remove` method_ In the `List` case, as has been the case a few times already, we delegate the work to a private method `remove_list`. In this method we iterate from left to right, until we find the member we're looking for. If we don't find it, we return `false`, to notify the caller that nothing was deleted. If we do find the member, we call `List#remove_node` with the node we get from the `iterator` variable to remove the member from the list. This is a rare case where we don't use the `List#each` method because we need a direct reference to the node value to pass to `List#remove_node`, and the `each` method skips over it to return the value the node contains, so we need a little bit more control here and use the lower level approach. In the `Dict` case, we call the `Dict#remove_member` method. This method needs to make sure that both internal collections, the `Dict` and the `SortedArray` are updated and no longer contain the member, if it was present. ``` ruby module BYORedis class ZSet # ... def remove_member(member) entry = @dict.delete_entry(member) return false unless entry index = @array.index(new_pair(entry.value, member)) @array.delete_at(index) true end # ... end end ``` _listing 10.45 The `ZSet#remove_member` method_ We start by calling `Dict#delete_entry`, which will return `false` if it fails to find the key we're looking for, or the `entry` that was removed if it contained it. With the `value` attribute of the `entry` variable, which is the score of the member, we can call `SortedArray#index` method, and it will efficiently find the index, that is, without a full scan of the array. Now that we have the `index` value, we can call `delete_at` to remove this `Pair` from the array. And with that the `ZSet` is now updated and the member is completely removed. ### Rank Ranges We are now going to add the `ZREMRANGEBYRANK` command, which has the following format according to the [Redis documentation][redis-doc-zremrangebyrank]: ``` ZREMRANGEBYRANK key start stop ``` `start` and `stop` _must_ be valid integers and negative values count as starting from the last member, the one with the highest score. The semantics are equivalent the the ones used in the `ZRANGE` command. The return value is the number of deleted members. ``` ruby module BYORedis # ... class ZRemRangeByRankCommand < BaseCommand def call Utils.assert_args_length(3, @args) start = Utils.validate_integer(@args[1]) stop = Utils.validate_integer(@args[2]) sorted_set = @db.lookup_sorted_set(@args[0]) removed_count = 0 if sorted_set range_spec = RedisSortedSet::GenericRangeSpec.rank_range_spec(start, stop, sorted_set.cardinality) removed_count = sorted_set.remove_rank_range(range_spec) end RESPInteger.new(removed_count) end def self.describe Describe.new('zremrangebyrank', 4, [ 'write' ], 1, 1, 1, [ '@write', '@sortedset', '@slow' ]) end end end ``` _listing 10.46 The `ZRemRangeByRankCommand` class_ Validating the number of arguments, checking that `start` and `stop` are both valid integers and looking up the set, once all these steps are successfully completed, we call `remove_rank_range` on the sorted set, which is a new method: ``` ruby module BYORedis class RedisSortedSet # ... def remove_rank_range(range_spec) return 0 if range_spec.empty? || no_overlap_with_range?(range_spec) { |_, rank| rank } case @underlying when List then remove_rank_range_list(range_spec) when ZSet then @underlying.remove_rank_range(range_spec.min, range_spec.max) else raise "Unknown type for #{ @underlying }" end end # ... private # ... def remove_rank_range_list(range_spec) generic_remove_range_list(range_spec) { |_, rank| rank } end def generic_remove_range_list(range_spec) removed_count = 0 iterator = List.left_to_right_iterator(@underlying) entered_range = false rank = 0 while iterator.cursor pair = iterator.cursor.value in_range = range_spec.in_range?(yield(pair, rank)) if in_range entered_range ||= true removed_count += 1 next_node = iterator.cursor.next_node @underlying.remove_node(iterator.cursor) iterator.cursor = next_node elsif entered_range break else iterator.next end rank += 1 end removed_count end end end ``` _listing 10.47 The `RedisSortedSet#remove_rank_range` method_ We already used `no_overlap_with_range?` earlier, when serializing sub ranges of sorted sets in `SortedSetSerializerBy`, which is used for both `ZRANGEBYSCORE` and `ZRANGEBYLEX`. We can also use it here, since there won't be anything to remove for a rank range that is completely outside the set. For instance, the range `5 10` would not have any overlap with the sorted set `{ < 1, 'a' >, < 2, 'b' > }`. This sorted set only contains two elements, with ranks `0` and `1`. This is why we made `no_overlap_with_range?` calls its `block` argument with two arguments, the `Pair`, and the `rank`, this lets the block we pass from `remove_rank_range` tell the range to use the rank values to compare elements: `return 0 if range_spec.empty? || no_overlap_with_range?(range_spec) { |_, rank| rank }`. The `List` branch delegates to the `remove_rank_range_list` private method, and the `ZSet`one to a method in that class, let's stay in `RedisSortedSet` for now and look at the list case. The process to delete a range, whether it's a rank range, a score range or a lex range is very similar, so we create the `generic_remove_range_list` method to encapsulate the logic. The only thing the method needs, beside a range spec, is a block that tells it what to consider when sorting elements, the score, the member, or the rank. In this case, we pass a block that tells it to use the rank: `{ |_, rank| rank }`. The `range_spec` we pass is the one we received from the `ZRemRangeByRankCommand#call`. In `generic_remove_range_list` we iterate from left to right, with a few additional variables to keep track of where we are in the set. `removed_count` is necessary since this is what we need to return, `entered_range` is a helper like we've seen earlier that we'll use to abort before the end of the set if we can, and `rank` is necessary to `yield` it to the given block. For each element we encounter, we ask the `range_spec` variable if it is in the range, using the result from `yield(pair, rank)`, which in this case always returns the `rank` value. Note how we once again use a method that does not specifically know what to call, `.score`, `.member` or something else, and instead relies on a block to parameterize its behavior. If the member is in range, we flag that we've entered the range with `entered_range ||= true`, increment `removed_count`, delete the node from the list, and tell the iterator to move to the next node. If the member is not in the range, but we've entered the range, it means we just exited it, and we can exit the loop, otherwise, we haven't entered the range yet so we need to keep iterating. Finally, we increment the rank before jumping to the next loop iteration. Once we exit the `while` loop, we return `removed_count`. This is another instance where we need a direct reference to the `ListNode` object and therefore need to use an iterator instead of `List#each`. Let's now take a look at hew `ZSet#remove_rank_range` method. It accepts two arguments, the `start` and `stop` values, which happen to map directly to the index of the elements in the `SortedArray`. This lets us use the `Array#slice!` method to delete the whole range, which returns the deleted elements. We then iterate over the deleted elements to also remove the entries in the `Dict`. ``` ruby module BYORedis class ZSet # ... def remove_rank_range(start, stop) removed = @array.slice!(start..stop) return 0 if removed.nil? removed.each do |pair| @dict.delete(pair.member) end removed.size end # ... end end ``` _listing 10.48 The `ZSet#remove_rank_range` method_ ### Lex Ranges Next is `ZREMRANGEBYLEX`, which has the following format according to the [Redis documentation][redis-doc-zremrangebylex]: ``` ZREMRANGEBYLEX key min max [LIMIT offset count] ``` We'll need to handle a lex range in the same way we did with `ZRANGEBYLEX` earlier, let's create the `ZRemRangeByLexCommand` class: ``` ruby module BYORedis # ... class ZRemRangeByLexCommand < BaseCommand def call Utils.assert_args_length(3, @args) range_spec = Utils.validate_lex_range_spec(@args[1], @args[2]) sorted_set = @db.lookup_sorted_set(@args[0]) removed_count = 0 if sorted_set removed_count = sorted_set.remove_lex_range(range_spec) end RESPInteger.new(removed_count) end def self.describe Describe.new('zremrangebylex', 4, [ 'write' ], 1, 1, 1, [ '@write', '@sortedset', '@slow' ]) end end end ``` _listing 10.49 The `ZRemRangeByLexCommand` class_ The `min` and `max` values use the same format used in `ZRANGEBYLEX`, so we reuse the `validate_lex_range_spec` method from the `Utils` module. We pass the range spec it returns, which is a range spec aware of the specificities of lex comparisons, created with `GenericRangeSpec.lex_range_spec`. Let's add the `remove_lex_range` to `RedisSortedSet`: ``` ruby module BYORedis class RedisSortedSet # ... def remove_lex_range(range_spec) return 0 if range_spec.empty? || no_overlap_with_range?(range_spec) { |pair, _| pair.member } case @underlying when List then remove_lex_range_list(range_spec) when ZSet then @underlying.remove_lex_range(range_spec) else raise "Unknown type for #{ @underlying }" end end # ... private # ... def remove_lex_range_list(range_spec) generic_remove_range_list(range_spec) { |pair, _| pair.member } end end end ``` _listing 10.50 The `RedisSortedSet#remove_lex_range` method_ The method starts almost identically to `remove_rank_range`, with the exception that this time we tell `no_overlap_with_range?` to use the `member` attribute from the `pair` variable, instead of the `rank` variable. The `List` case delegates to the `remove_lex_range_list` private method, which also uses the `generic_remove_range_list` private method, like `remove_rank_range_list` did, but tells it to use the `pair.member` value, instead of the rank, to decide what to remove from the list. This is another example of the benefits of `generic_remove_range_list` being so abstract, we can now express `remove_lex_range_list` very succinctly, and let `generic_remove_range_list` do the heavy lifting, removing elements from the list, counting the number of elements deleted, and so on. For the `ZSet` case, things are not as simple because this time we do not have the index values of the elements we need to delete like we had for `ZREMRANGEBYRANK`, let's create the `remove_lex_range` method: ``` ruby module BYORedis class ZSet # ... def remove_lex_range(range_spec) generic_remove(range_spec, &:member) end private # ... def generic_remove(range_spec, &block) first_in_range_index = @array.first_index_in_range(range_spec, &block) last_in_range_index = first_in_range_index (first_in_range_index.upto(@array.size - 1)).each do |rank| pair = @array[rank] in_range = range_spec.in_range?(yield(pair)) if in_range last_in_range_index = rank else break end end remove_rank_range(first_in_range_index, last_in_range_index) end end end ``` _listing 10.51 The `ZSet#remove_lex_range` method_ `remove_lex_range` uses the `generic_remove` method, which we'll be able to use when removing score ranges. We use `first_index_in_range`, from `SortedArray`, which we've added earlier when serializing ranges in `ZRANGEBYLEX` and `ZRANGEBYSCORE`. By giving the block that returns the `member` attribute of a `Pair` instance, `first_index_in_range` will be able to find the first element in the array that is in the range. Once we found this element, we iterate from there, and as long as elements are in the range, we mark the current index as the last index of elements in range with `last_in_range_index`. As soon as we find an element that is not in range, we exit the loop. At this point, we have the boundaries of the range we need to delete, in terms of indices, the index of the first element, which `first_index_in_range` gave us, and the last index, `last_in_range_index`, which we found by iterating through the array. These values are also ranks, since the rank is the index of the element in the set, meaning that we can use the `remove_rank_range` we added earlier when adding the `ZREMRANGEBYRANK` method. This method items from `@array` and `@dict`, and return the number of elements deleted, so we can return what it returns. ### Score Ranges And finally we are adding `ZRemRangeByScoreCommand`, for the `ZREMRANGEBYSCORE` command, which has the following format according to the [Redis Documentation][redis-doc-zremrangebyscore]: ``` ZREMRANGEBYSCORE key min max ``` `min` and `max` must be valid scores, with the same semantics as in `ZRANGEBYSCORE` where a score can be marked as exclusive with the `(` prefix. ``` ruby module BYORedis # ... class ZRemRangeByScoreCommand < BaseCommand def call Utils.assert_args_length(3, @args) range_spec = Utils.validate_score_range_spec(@args[1], @args[2]) sorted_set = @db.lookup_sorted_set(@args[0]) removed_count = 0 removed_count = sorted_set.remove_score_range(range_spec) if sorted_set RESPInteger.new(removed_count) end def self.describe Describe.new('zremrangebyscore', 4, [ 'write' ], 1, 1, 1, [ '@write', '@sortedset', '@slow' ]) end end end ``` _listing 10.52 The `ZRemRangeByScoreCommand` class_ We reuse the `validate_score_range_spec` method from the `Utils` module, to create the right type of range, a `GenericRangeSpec` created with `score_range_spec`, we then pass this range spec to `RedisSortedSet#remove_score_range`: ``` ruby module BYORedis class RedisSortedSet # ... def remove_score_range(range_spec) return 0 if range_spec.empty? || no_overlap_with_range?(range_spec) { |pair, _| pair.score } case @underlying when List then remove_score_range_list(range_spec) when ZSet then @underlying.remove_score_range(range_spec) else raise "Unknown type for #{ @underlying }" end end # ... private # ... def remove_score_range_list(range_spec) generic_remove_range_list(range_spec) { |pair, _| pair.score } end end end ``` _listing 10.53 The `RedisSortedSet#remove_score_range` method_ The structure of the method might look pretty familiar by now, this is almost identical to `remove_lex_range`, with the exception of the block given to `no_overlap_with_range?` which returns the `score` attribute this time. In the `List` case we call `remove_score_range_list`, which itself uses the `generic_remove_range_list`, with a block telling it to extract the `score` attribute from the `Pair` instances it handles. For `ZSet` instances, we call `remove_score_range`, which can be expressed in terms of the method we just wrote earlier for `ZREMRANGEBYLEX`, `generic_remove`: ``` ruby module BYORedis class ZSet # ... def remove_score_range(range_spec) generic_remove(range_spec, &:score) end # ... end end ``` _listing 10.54 The `ZSet#remove_score_range` method_ With `ZREMRANGEBYSCORE` we have now implemented all the `*REM*` methods, next up, the `*REV*` variants. Did you notice how we did not have to write any _real_ logic this time, we just called a few existing methods with the right block telling them what values to extract! ## Reverse commands All the commands we've implemented so far used an implicit sorting order by ascending score. Redis provides four commands that let users reverse the order and use the scores in descending order: `ZREVRANGE`, `ZREVRANGEBYLEX`, `ZREVRANGEBYSCORE`, & `ZREVRANK`. These commands behave almost identically to `ZRANGE`, `ZRANGEBYLEX`, `ZRANGEBYSCORE` & `ZRANK`, all of which were implemented earlier in the chapter, but use the reverse score ordering instead. We've spent some time earlier explaining why we were building things in a way that may have look convoluted, well, now we're about to see why. These commands will all be really short to write, because most of the logic already exists, we _just_ have to reverse things in a few places, here and there. Let's start with the `ZREVRANGE` command, which has the following format according to the [Redis Documentation][redis-doc-zrevrange]: ``` ZREVRANGE key start stop [WITHSCORES] ``` Let's create the `ZRevRangeCommand` class: ``` ruby module BYORedis # ... class ZRevRangeCommand < BaseCommand def call SortedSetUtils.generic_range(@db, @args, reverse: true) end def self.describe Describe.new('zrevrange', -4, [ 'readonly' ], 1, 1, 1, [ '@read', '@sortedset', '@slow' ]) end end end ``` _listing 10.55 The `ZRevRangeCommand` class_ We call the `generic_range` method we created earlier, but this time we set the `reverse` flag to `true`. The flag is used to decide in which order to handle the `start` and `stop` argument. We use a trick to convert `start` and `stop` in a way that will make it easy to reuse, before looking at the code, which is convoluted, let's first look at an example with the following sorted set: ``` 127.0.0.1:6379> ZADD z 10 a 15 c 20 f 50 m 100 z (integer) 5 127.0.0.1:6379> ZRANGE z 0 -1 1) "a" 2) "c" 3) "f" 4) "m" 5) "z" 127.0.0.1:6379> ZRANGE z 2 3 1) "f" 2) "m" 127.0.0.1:6379> ZREVRANGE z 0 -1 1) "z" 2) "m" 3) "f" 4) "c" 5) "a" 127.0.0.1:6379> ZREVRANGE z 2 3 1) "f" 2) "c" ``` With `ZRANGE`, the members `a`, `c`, `f`, `m`, & `z` have the ranks `0`, `1`, `2`, `3` & `4`, with `ZREVRANGE`, `a` has now the rank `4`, `c` `3`, `f`, `2`, `m` `1` and `z` `0`. It turns out that we can always convert a "regular index" to a reversed index with the following logic: - if index is greater than or equal to 0, convert it to the maximum index minus the index value - if index is negative, convert it to the maximum index value, minus the sum of the index, the maximum index value, and 1 Yup, that works, let's look at the values we used in the example above and start with `0`, its "reverse equivalent" is `4`, that is when we pass `0` to `ZREVRANGE`, we can get the desired value by fetching the element at rank `4` in the sorted set, which is where `z` is, at index `4` in the set, and `ZREVRANGE z 0 0` does return `z`. We apply the first rule, where max index is `4`, the max rank in the set, so `4 - 0 = 0`, `4` is indeed the index in the set where we would find `z`. Let's keep going, with a negative value this time, `-1`, in the set, this is the last index, the member `z`, when passed to `ZREVRANGE`, `-1` maps to `a`, which is the member at index `0` in the sorted set, so `-1` should give us `0` back. Let's check, it applies to the second rule, `4 - (-1 + 4 + 1) = 0`, it worked again! Let's check `2` and `3` now, in the set, they return the members `f` and `m`, but in `ZREVRANGE`, they respectively map to `f` and `c`, which are the members at index `2` and `1` in the set, so `2` should stay `2` and `3` should become `1`. They both trigger the first rule: `4 - 2 = 2` and `4 - 3 = 1`. These examples show us that we can apply these transformations to know where to look in the sorted set. For instance when we receive the command `ZREVRANGE z 2 3`, we'll transform `start` from `2` to `2` and `stop` from `3` to `1`, we can then swap start and stop, so that we maintain the condition `start <= stop` and we're almost done. The last thing is that we now need to tell the serializer to serialize the items from right to left. In `ZREVRANGE 0 -1`, both boundaries will be converted to `4` and `0`, and then swapped so that `start` is `0` and `stop` is `4`. Let's make these changes: ``` ruby module BYORedis module SortedSetUtils # ... def self.generic_range(db, args, reverse: false) Utils.assert_args_length_greater_than(2, args) start = Utils.validate_integer(args[1]) stop = Utils.validate_integer(args[2]) raise RESPSyntaxError if args.length > 4 if args[3] if args[3].downcase == 'withscores' withscores = true else raise RESPSyntaxError end end sorted_set = db.lookup_sorted_set(args[0]) if reverse tmp = reverse_range_index(start, sorted_set.cardinality - 1) start = reverse_range_index(stop, sorted_set.cardinality - 1) stop = tmp end if sorted_set range_spec = RedisSortedSet::GenericRangeSpec.rank_range_spec(start, stop, sorted_set.cardinality) SortedSetRankSerializer.new( sorted_set, range_spec, withscores: withscores, reverse: reverse, ) else EmptyArrayInstance end end def self.reverse_range_index(index, max) if index >= 0 max - index elsif index < 0 max - (index + max + 1) end end # ... end # ... end ``` _listing 10.56 The `generic_range` class method for the `SortedSetUtils` module_ If the `reverse` flag is true we convert the indices as described earlier and we swap the values to maintain the order of `start` and `stop`. We propagate the `reverse` flag to `SortedSetRankSerializer`: ``` ruby module BYORedis # ... class SortedSetRankSerializer # ... private def serialize_zset sub_array = @sorted_set.underlying.array[@range_spec.min..@range_spec.max] members = [] sub_array.each do |pair| if @reverse members.prepend(Utils.float_to_string(pair.score)) if @withscores members.prepend(pair.member) else members.push(pair.member) members.push(Utils.float_to_string(pair.score)) if @withscores end end RESPArray.new(members).serialize end def serialize_list ltr_acc = lambda do |value, response| response << RESPBulkString.new(value.member).serialize if @withscores response << RESPBulkString.new(Utils.float_to_string(value.score)).serialize end @withscores ? 2 : 1 end rtl_acc = lambda do |value, response| if @withscores response.prepend(RESPBulkString.new(Utils.float_to_string(value.score)).serialize) end response.prepend(RESPBulkString.new(value.member).serialize) @withscores ? 2 : 1 end if @reverse tmp = ltr_acc ltr_acc = rtl_acc rtl_acc = tmp end ListSerializer.new(@sorted_set.underlying, @range_spec.min, @range_spec.max) .serialize_with_accumulators(ltr_acc, rtl_acc) end # ... end end end ``` _listing 10.57 The `serialize_zset` & `serialize_list` methods for the `SortedSetRankSerializer` class_ In the `serialize_list` method we look at the `@reverse` flag and if it set to true we swap the values or `ltr_acc` and `rtl_acc`. Swapping these values has the effect of reverting the order in which elements get serialized. Looking again at the `ZREVRANGE z 0 -1` example from earlier, where the desired result is `z`, `m`, `f`, `c`, `a`, the `ListSerializer` will iterate from `0` to `4`, but instead of appending elements as it finds them, it'll prepend them. It will first find `a`, at index `0`, and will add it to the string serializing the resp array, and it will then find `c`, prepending it and so on, until it prepends `z`. If scores are to be included, it knows how to do that as well, the same way we did earlier for `ZRANGE`. The process is similar in the `ZSet` case, if the `@reverse` flag is set to `true`, we use `members.prepend` instead of `members.<<` to accumulate elements. ### Reverse Range by Score and Lex #### ZREVRANGEBYLEX Next is the `ZREVRANGEBYLEX` command, which has the following format according to the [Redis Documentation][redis-doc-zrevrangebylex]: ``` ZREVRANGEBYLEX key max min [LIMIT offset count] ``` `min` and `max` have the same format we used in the `ZRANGEBYLEX` and `ZREMRANGEBYLEX` commands, and note how their order is reversed, the `max` boundary is specified first here. ``` ruby module BYORedis # ... class ZRevRangeByLexCommand < BaseCommand def call SortedSetUtils.generic_range_by_lex(@db, @args, reverse: true) end def self.describe Describe.new('zrevrangebylex', -4, [ 'readonly' ], 1, 1, 1, [ '@read', '@sortedset', '@slow' ]) end end end ``` _listing 10.58 The `ZRevRangeByLexCommand` class_ We call `generic_range_by_lex`, but this time we set the `reverse` flag to `true`, which changes how the arguments are read: ``` ruby module BYORedis module SortedSetUtils # ... def self.generic_range_by_lex(db, args, reverse: false) # A negative count means "all of them" options = { offset: 0, count: -1 } Utils.assert_args_length_greater_than(2, args) key = args.shift if reverse max = args.shift min = args.shift else min = args.shift max = args.shift end range_spec = Utils.validate_lex_range_spec(min, max) parse_range_by_lex_options(args, options) unless args.empty? sorted_set = db.lookup_sorted_set(key) if options[:offset] < 0 EmptyArrayInstance elsif sorted_set options[:withscores] = false options[:reverse] = reverse SortedSetSerializerBy.new(sorted_set, range_spec, **options, &:member) else EmptyArrayInstance end end # ... end # ... end ``` _listing 10.59 The `generic_range_by_lex` class method for the `SortedSetUtils` module_ We read `min` and `max` in the reverse order, `max` first if `reverse` is true, and this is the only difference. The `reverse` flag is forwarded to `SortedSetSerializerBy` when we call it: `SortedSetSerializerBy.new(sorted_set, range_spec, **options, &:member)` We ignored it earlier, but looking at the `@reverse` branch of the `serialize_zset` method in `SortedSetSerializerBy`, we now need a new method in `SortedArray`, `last_index_in_range`: ``` ruby module BYORedis # ... class SortedSetSerializerBy # ... def serialize_zset members = [] if @reverse start_index = @sorted_set.underlying.array.last_index_in_range(@range_spec, &@block) if start_index.nil? raise "Unexpectedly failed to find last index in range for #{ self }" end indices = start_index.downto(0) else start_index = @sorted_set.underlying.array.first_index_in_range(@range_spec, &@block) if start_index.nil? raise "Unexpectedly failed to find first index in range for #{ self }" end indices = start_index.upto(@sorted_set.cardinality - 1) end # ... end def serialize_list if @reverse iterator = List.right_to_left_iterator(@sorted_set.underlying) else iterator = List.left_to_right_iterator(@sorted_set.underlying) end members = [] entered_range = false while iterator.cursor && @count != 0 member = iterator.cursor.value if @range_spec.in_range?(@block.call(member)) entered_range ||= true if @offset == 0 members << member.member members << Utils.float_to_string(member.score) if @withscores @count -= 1 else @offset -= 1 end elsif entered_range == true break end iterator.next end RESPArray.new(members).serialize end end end ``` _listing 10.60 The `serialize_zset` & `serialize_list` methods in the `SortedSetSerializerBy` class_ Let's look at `serialize_zset` first. The order of the range items is still what we'd expect, that is `@range_spec.max` is expected to be greater than or equal to `@range_spec.min`, using lexicographic order, but the "first" item in what we want to return is not the first item in the set to match the range, it's the _last_ one. Let's look at an example: ``` 127.0.0.1:6379> ZADD z 0 a 0 b 0 c 0 d 0 e 0 f (integer) 6 127.0.0.1:6379> ZRANGEBYLEX z - + 1) "a" 2) "b" 3) "c" 4) "d" 5) "e" 6) "f" 127.0.0.1:6379> ZREVRANGEBYLEX z + - 1) "f" 2) "e" 3) "d" 4) "c" 5) "b" 6) "a" 127.0.0.1:6379> ZREVRANGEBYLEX z [e [b 1) "e" 2) "d" 3) "c" 4) "b" ``` The set `z` has the elements `a`, `b`, `c`, `d`, `e` and `f`. When we request the range `+ -`, we get the whole set, starting from the member with the greater value in lexicographic order, `z`, down to the smallest one, `a`. The next example is what interests us here, the range is `[e [b`, that is, from `e`, to `b`, inclusive. But remember that the range spec always needs to maintain the condition `min <= max`, so the range spec we created is actually one where `min` is `b`, and `max` is `e`, because we read the arguments in the reversed order, `max` first. The layout of the `SortedSet` is roughly the following, ignoring the score since they're all `0`: ```ruby ["a", "b", "c", "d", "e", "f"] ``` If we were to call `first_index_in_range` with the range spec for `[b [e`, we'd get `1`, the index of `b`, but since we need to return `e`, `d`, `c`, `b`, the first index we want is `4`, the index of `e`. This is why we call `last_index_in_range`, it'll give us just what we need. And once we have the index of the last index, which is where we want to start iterating from, we create an enumerator that goes the other way, down to `0`, with `start_index.downto(0)`. The rest of the method is the same, we iterate over all the indices in the range, we check if the item is in the range, and as soon as we find an item that is not, we exit the loop, while taking into account the values of `@count` and `@offset`. Let's take a look at the `last_index_in_range` method: ``` ruby module BYORedis class SortedArray # ... def last_index_in_range(range_spec) return nil if empty? first_index_outside = @underlying.bsearch_index do |existing_element| compare = range_spec.compare_with_max(yield(existing_element)) if range_spec.max_exclusive? compare >= 0 # existing_element.score > max else compare > 0 # existing_element.score >= max end end case first_index_outside when nil then @underlying.size - 1 # last when 0 then nil # the max of the range is smaller than the smallest item else first_index_outside - 1 end end end end ``` _listing 10.61 The `SortedArray#last_index_in_range` method_ We use `bsearch_index` in a similar way we used it in `first_index_in_range` with a few differences. We compare each value with `compare_with_max` instead of `compare_with_min`, and the condition related to the exclusivity of the `max` boundary are reversed. Once again, it's easier to look at an example in `irb`: ``` ruby irb(main):001:0> set = [ 'a', 'b', 'c', 'd', 'e', 'f' ] irb(main):002:0> set.bsearch_index { |x| x >= 'e' } => 4 irb(main):003:0> set.bsearch_index { |x| x > 'e' } => 5 irb(main):004:0> set.bsearch_index { |x| x >= 'f' } => 5 irb(main):005:0> set.bsearch_index { |x| x > 'f' } => nil ``` In all the examples we get the leftmost index, if it exists, for which the condition is `true`, in the first case, the smallest index where the value is greater than or equal to `e` is `4`, because `set[4] == 'e'`, and if we swap the condition to be strict, then it return `5`, because the element at index `5`, `f`, is the first one to be strictly greater than `e`. If we translate that to the inclusive/exclusive cases we're trying to handle, we can see that the result are almost what we want, just off by one to the right. If the upper boundary is exclusive, `(e`, then the last index would be `3`, and if it is inclusive, `[e`, then it would be `4`. We can obtain these values by using the `>=` operator in the exclusive case and the `>` operator in the inclusive case, and subtracting one to the result. There's a small edge case we need to handle, what if the set does not contain an element that is outside the set, then the last element in the set would be the last in the range. This is what the last example above demonstrates, the `set` array does not contain a value greater than `f`, and returns `nil`, and in this case, because we have nothing we can subtract `1` to to obtain the last index, we need to handle this specific case. This logic is what the `case/when` conditions at the end of `last_index_in_range` handle. There is also a special case where the value returned would be `0`, in which case we don't want to return `-1` and want to return `0` instead. The following is an example that could potentially trigger this path but that will be prevented in practice by the `no_overlap_with_range?` check. ```ruby irb(main):011:0> '0' < 'a' # this is included as a reminder that in lex order '0' < 'a' => true irb(main):012:0> set.bsearch_index { |x| x >= '0' } => 0 irb(main):013:0> set.bsearch_index { |x| x > '0' } => 0 ``` In both cases the range does not overlap with the set, the max value of the range, `'0'` is lower than the mininum value of the set, `'a'`, and we return `nil`, none of the set members is within the range. #### ZREVRANGEBYSCORE Next is the `ZREVRANGEBYSCORE` command, which has the following format according to the [Redis Documentation][redis-doc-zrevrangebylex]: ``` ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count] ``` `min` and `max` have the same format we used in the `ZRANGEBYSCORE` and `ZREMRANGEBYSCORE` commands, and note how their order is reversed, the `max` boundary is specified first. We'll first create the `ZRevRangeByScoreCommand` class: ``` ruby module BYORedis # ... class ZRevRangeByScoreCommand < BaseCommand def call SortedSetUtils.generic_range_by_score(@db, @args, reverse: true) end def self.describe Describe.new('zrevrangebyscore', -4, [ 'readonly' ], 1, 1, 1, [ '@read', '@sortedset', '@slow' ]) end end end ``` _listing 10.62 The `ZRevRangeByScoreCommand` class_ We call `generic_range_by_score` with the `reverse` flag set to `true`, let's look at how the flag is handled in `generic_range_by_score`: ``` ruby module BYORedis module SortedSetUtils # ... def self.generic_range_by_score(db, args, reverse: false) # A negative count means "all of them" options = { offset: 0, count: -1, withscores: false } Utils.assert_args_length_greater_than(2, args) key = args.shift if reverse max = args.shift min = args.shift else min = args.shift max = args.shift end # ... end # ... end # ... end ``` _listing 10.63 Handling of the `reverse` flag in the `SortedSetUtils.generic_range_by_score` class method_ Things are very similar to `generic_range_by_lex`, if `reverse` is `true`, we read `max` first, and we then create the range spec with these values. And that's it ... yes, everything else "just works". The code path is essentially the same as in `ZRANGEBYSCORE`, but the `reverse` flag will make sure that either the `List` or the `ZSet` are serialized in the reverse order, returning the desired result to the client. #### ZREVRANK `ZREVRANK` is simpler since it only deals with a single set member and returns its rank as if the set was sorted from highest scores to lowest: ``` 127.0.0.1:6379> ZADD z 0 a 0 b 0 c 0 d 0 e 0 f (integer) 6 127.0.0.1:6379> ZRANGE z 0 -1 1) "a" 2) "b" 3) "c" 4) "d" 5) "e" 6) "f" 127.0.0.1:6379> ZRANK z a (integer) 0 127.0.0.1:6379> ZRANK z e (integer) 4 127.0.0.1:6379> ZREVRANGE z 0 -1 1) "f" 2) "e" 3) "d" 4) "c" 5) "b" 6) "a" 127.0.0.1:6379> ZREVRANK z a (integer) 5 127.0.0.1:6379> ZREVRANK z e (integer) 1 ``` Let's create the `ZRevRankCommand` class: ``` ruby module BYORedis # ... class ZRevRankCommand < BaseCommand def call Utils.assert_args_length(2, @args) sorted_set = @db.lookup_sorted_set(@args[0]) if sorted_set RESPSerializer.serialize(sorted_set.rev_rank(@args[1])) else NullBulkStringInstance end end def self.describe Describe.new('zrevrank', 3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@sortedset', '@fast' ]) end end end ``` _listing 10.64 The `ZRevRankCommand` class_ We nee to add the `rev_rank` method in `RedisSortedSet`: ``` ruby module BYORedis class RedisSortedSet # ... def rev_rank(member) member_rank = rank(member) cardinality - 1 - member_rank if member_rank end # ... end end ``` _listing 10.65 The `RedisSortedSet#rev_rank` method_ We don't need to change the order of the set to get the reversed rank of a member, we can use its "regular" rank, that we get with `rank(member)` and subtract it to the the cardinality of the set, and subtract one to that. With the example from above, the rank of `a` in the set is `0`, and the cardinality of `z` is `6`, `6 - 0 - 1 == 5`, the correct result. It also works for `e`, which has a rank of `4` and a "revrank" of `1`: `6 - 4 - 1 == 1`. ## Pop Commands We mentioned earlier the pop commands as ways to remove members from a sorted set. `ZPOPMIN` removes the element with the lowest score, and returns it and `ZPOPMAX` does the same with the member with the highest score. Similarly to how we implemented `BLPOP`, `BRPOP` and `BRPOPLPUSH` in [Chapter 7][chapter-7], we are going to add the two blocking variants of `ZPOPMIN` & `ZPOPMAX`: `BZPOPMIN` & `BZPOPMAX`. The semantics are similar to the blocking list commands, a timeout is given, where `0` means infinite, and the server will block the client until a value can be returned or until the timeout expires. The format of `ZPOPMAX` is the following according to the [Redis Documentation][redis-doc-zpopmax]: ``` ZPOPMAX key [count] ``` `count` _must_ be an integer and has a default value of `1`. Negative values are accepted but turn the command in a no-op since an array cannot have a negative number of items, so Redis always returns an empty array. Let's start with the `ZPopMaxCommand` class: ``` ruby module BYORedis module SortedSetUtils # ... def self.generic_zpop(db, args) Utils.assert_args_length_greater_than(0, args) key = args.shift count = args.shift raise RESPSyntaxError unless args.empty? count = if count.nil? 1 else Utils.validate_integer(count) end sorted_set = db.lookup_sorted_set(key) popped = [] if sorted_set popped = db.generic_pop(key, sorted_set, count) do yield sorted_set, count end end RESPArray.new(popped) end end # ... class ZPopMaxCommand < BaseCommand def call SortedSetUtils.generic_zpop(@db, @args) do |sorted_set, count| sorted_set.pop_max(count) end end def self.describe Describe.new('zpopmax', -2, [ 'write', 'fast' ], 1, 1, 1, [ '@write', '@sortedset', '@fast' ]) end end end ``` _listing 10.66 The `ZPopMaxCommand` class_ We already know we have to implement two very similar commands, `ZPOPMAX` and `ZPOPMIN`, and both accept the same options, so we use the `generic_zpop` method to encapsulate all the logic that can be shared. The command handles the argument validation, as well as using a default value for `count` and calls `yield` with the `sorted_set` loaded from memory and the `count` value parsed an `Integer`. Elements are always returned with their scores when popped, so we'll need to make sure to include when returning it. The `popped` variable is expected to be an array from the result of `yield` and is returned back to the client. Back in `ZPopMaxCommand#call`, we call `RedisSortedSet#pop_max` from the block with the variables given to us by `generic_zpop`. And we now need to add the `RedisSortedSet#pop_max` method: ``` ruby module BYORedis class RedisSortedSet # ... def pop_max(count) case @underlying when List then generic_pop(count) { @underlying.right_pop&.value } when ZSet generic_pop(count) do max = @underlying.array.pop @underlying.dict.delete(max.member) if max max end else raise "Unknown type for #{ @underlying }" end end # ... private # ... def generic_pop(count) popped = [] return popped if count < 0 while count > 0 min = yield if min popped.push(min.member, min.score) count -= 1 else break end end popped end end end ``` _listing 10.67 The `RedisSortedSet#pop_max` method_ Once again trying to always be one step ahead, we use a generic method that will be useful when implementing `ZPOPMIN`, `generic_pop`, to which we pass the `count` value. This method handles the negative count scenario and returns an empty array right away in this case. Otherwise, it keeps iterating until `count` reaches `0`, at each step we `yield` back to the caller, which in this case is either a call to `@underlying.right_pop` if we're dealing with a `List` or `@underlying.array.pop` followed by a call to `Dict#delete` if we're dealing with a `ZSet`. In either case, the `Pair` instance is returned and `generic_pop` aggregates it in `popped`, and decrements `count`. If the previous iteration deleted the last element in the set, we'll receive `nil` from `yield`, and in this case we must stop iterating right away, there's nothing else to pop. Next up is `ZPopMinCommand`: ``` ruby module BYORedis # ... class ZPopMinCommand < BaseCommand def call SortedSetUtils.generic_zpop(@db, @args) do |sorted_set, count| sorted_set.pop_min(count) end end def self.describe Describe.new('zpopmin', -2, [ 'write', 'fast' ], 1, 1, 1, [ '@write', '@sortedset', '@fast' ]) end end end ``` _listing 10.68 The `ZPopMinCommand` class_ The only different with `ZPopMaxCommand` is that the block given to `generic_zpop` calls `pop_min` instead of `pop_max`, let's add the command to `RedisSortedSet`: ``` ruby module BYORedis class RedisSortedSet # ... def pop_min(count) case @underlying when List then generic_pop(count) { @underlying.left_pop&.value } when ZSet generic_pop(count) do min = @underlying.array.shift @underlying.dict.delete(min.member) if min min end else raise "Unknown type for #{ @underlying }" end end # ... end end ``` _listing 10.69 The `RedisSortedSet#pop_min` method_ The block we give to `generic_pop` is the one that actually performs the pop operation and in this case we use `List#left_pop` to remove the element with the smallest rank or `Array#shift` for a `ZSet`. We return the `Pair` instance in either case to let `generic_pop` handle everything for us and return the list of deleted pairs. ### Blocking Commands Both blocking commands have identical formats according to the [Redis Documentation for `BZPOPMIN`][redis-doc-bzpopmin]: ``` BZPOPMIN key [key ...] timeout ``` and the [Redis Documentation for `BZPOPMAX`][redis-doc-bzpopmin] ``` BZPOPMAX key [key ...] timeout ``` Let's go ahead and add both classes, `BZPopMaxCommand` & `BZPopMinCommand`: ``` ruby module BYORedis module SortedSetUtils # ... def self.generic_bzpop(db, args, operation) Utils.assert_args_length_greater_than(1, args) timeout = Utils.validate_timeout(args.pop) args.each do |set_name| sorted_set = db.lookup_sorted_set(set_name) next if sorted_set.nil? popped = db.generic_pop(set_name, sorted_set, 1) do yield sorted_set end return RESPArray.new([ set_name ] + popped) end Server::BlockedState.new( BlockedClientHandler.timeout_timestamp_or_nil(timeout), args, operation) end end # ... class BZPopMaxCommand < BaseCommand def call SortedSetUtils.generic_bzpop(@db, @args, :zpopmax) do |sorted_set| sorted_set.pop_max(1) end end def self.describe Describe.new('bzpopmax', -3, [ 'write', 'noscript', 'fast' ], 1, -2, 1, [ '@write', '@sortedset', '@fast', '@blocking' ]) end end class BZPopMinCommand < BaseCommand def call SortedSetUtils.generic_bzpop(@db, @args, :zpopmin) do |sorted_set| sorted_set.pop_min(1) end end def self.describe Describe.new('bzpopmin', -3, [ 'write', 'noscript', 'fast' ], 1, -2, 1, [ '@write', '@sortedset', '@fast', '@blocking' ]) end end end ``` _listing 10.70 The `BZPopMinCommand` & `BZPopMaxCommand` classes_ Let's ignore the blocking behavior for now, if any of sets for the given keys exist, we want to pop from it, either with `pop_min` or `pop_max`. We only need to pop one element so we set the count argument to `1` with `.pop_min(1)` and `.pop_max(1)`. This is what we call from the block we give to `generic_bzpop`, but let's look at what this method does in details. Once the `timeout` value is validated, we iterate over all the arguments one by one, each time we load the set, and jump to the next one if it's `nil`. If it is not `nil`, we yield it back to the caller, which as we've just seen will call the appropriate pop method, and we exit the loop, returning the value that was popped. There's no blocking behavior in this case. In the case where we exhausted the list of all arguments, we want to block until one of these sets receives an element with `ZADD`, which is very similar to the `BLPOP` and `BRPOP` behavior, but with sorted sets this time. We are going to reuse a lot of the `BlockedClientHandler` logic, but we need to make it aware of sorted sets now, back then it only knew about lists, but first we return an instance of `BlockedState`, with the result of `timeout_timestamp_or_nil`, a method we introduced in [Chapter 7][chapter-7], that either converts the float timeout value by adding the value to the current time or return `nil`, indicating an infinite timeout. The last two arguments are `args` and `operation`. `args` has the all the sorted set keys, and `operation` is either the symbol `:zpopmin` or the symbol `:zpopmax`. The server class already knows how to handle `BlockedState` instances with the `block_client` method, and will add it to its internal `client_timeouts` sorted array. Let's take a a look at all the changes in the `BlockedClientHandler` class. As a reminder, the `handle_client` method is called from the `Server` class, from the `handle_clients_blocked_on_keys` method, which is called after each command is processed. ``` ruby module BYORedis class BlockedClientHandler def initialize(server, db) # ... end def self.timeout_timestamp_or_nil(timeout) if timeout == 0 nil else Time.now + timeout end end def handle(key) clients = @db.blocking_keys[key] list_or_set = @db.data_store[key] raise "Unexpected empty list/sorted set for #{ key }" if list_or_set&.empty? unblocked_clients = serve_client_blocked_on(key, list_or_set, clients) @db.blocking_keys.delete(key) if clients.empty? unblocked_clients end private def pop_operation(key, list, operation, target) case operation when :lpop RESPArray.new([ key, @db.left_pop_from(key, list) ]) when :rpop RESPArray.new([ key, @db.right_pop_from(key, list) ]) when :rpoplpush raise "Expected a target value for a brpoplpush handling: #{ key }" if target.nil? ListUtils.common_rpoplpush(@db, key, target, list) when :zpopmax RESPArray.new([ key ] + @db.pop_max_from(key, list)) when :zpopmin RESPArray.new([ key ] + @db.pop_min_from(key, list)) else raise "Unknown pop operation #{ operation }" end end def rollback_operation(key, response, operation, target_key) case operation when :lpop element = response.underlying_array[1] list = @db.lookup_list_for_write(key) list.left_push(element) when :rpop element = response.underlying_array[1] list = @db.lookup_list_for_write(key) list.right_push(element) when :rpoplpush list = @db.lookup_list_for_write(key) target_list = @db.lookup_list(target_key) element = target_list.left_pop @db.data_store.delete(target_key) if target_list.empty? list.right_push(element.value) when :zpopmax, :zpopmin sorted_set = @db.lookup_sorted_set_for_write(key) member = response.underlying_array[1] score = response.underlying_array[2] sorted_set.add(score, member) else raise "Unknown pop operation #{ operation }" end end def handle_client(client, key, list_or_set) blocked_state = client.blocked_state # The client is expected to be blocked on a set of keys, we unblock it based on the key # arg, which itself comes from @db.ready_keys, which is populated when a key that is # blocked on receives a push # So we pop (left or right for list, min or max for a set) at key, and send the response # to the client if client.blocked_state response = pop_operation(key, list_or_set, blocked_state.operation, blocked_state.target) serialized_response = response.serialize @logger.debug "Writing '#{ serialized_response.inspect } to #{ client }" unless Utils.safe_write(client.socket, serialized_response) # If we failed to write the value back, we put the element back in the list or set rollback_operation(key, response, blocked_state.operation, blocked_state.target) @server.disconnect_client(client) return end else @logger.warn "Client was not blocked, weird!: #{ client }" return end true end def serve_clients_blocked_on_lists(key, list_or_set, clients) generic_serve_clients(clients, list_or_set) do |client, clients_waiting_on_different_type| if is_client_blocked_on_list?(client) handle_client(client, key, list_or_set) else clients_waiting_on_different_type << client nil end end end def serve_clients_blocked_on_sorted_sets(key, list_or_set, clients) generic_serve_clients(clients, list_or_set) do |client, clients_waiting_on_different_type| if is_client_blocked_on_sorted_set?(client) handle_client(client, key, list_or_set) else clients_waiting_on_different_type << client nil end end end def generic_serve_clients(clients, list_or_set) unblocked_clients = [] clients_waiting_on_different_type = [] cursor = clients.left_pop while cursor client = cursor.value unblocked_clients << client if yield(client, clients_waiting_on_different_type) if list_or_set.empty? break else cursor = clients.left_pop end end return unblocked_clients, clients_waiting_on_different_type end def serve_client_blocked_on(key, list_or_set, clients) unblocked_clients = [] clients_waiting_on_different_type = List.new case list_or_set when List then unblocked_clients, clients_waiting_on_different_type = serve_clients_blocked_on_lists(key, list_or_set, clients) when RedisSortedSet unblocked_clients, clients_waiting_on_different_type = serve_clients_blocked_on_sorted_sets(key, list_or_set, clients) else @logger.warn "Found neither a list or sorted set: #{ key } / #{ list_or_set }" raise "Found nil or neither a list or sorted set: #{ key } / #{ list_or_set }" end # Take all the clients we set aside and add them back clients_waiting_on_different_type.each do |client| clients.right_push(client) end unblocked_clients end def is_client_blocked_on_list?(client) return false unless client.blocked_state [ :lpop, :rpop, :rpoplpush ].include?(client.blocked_state.operation) end def is_client_blocked_on_sorted_set?(client) return false unless client.blocked_state [ :zpopmax, :zpopmin ].include?(client.blocked_state.operation) end end end ``` _listing 10.71 The updates to the `BlockedClientHandler` class for sorted sets_ `handle` is called with the key of a collection, either a sorted set or a list, that was just added. The same way we used to, we get the list of all clients blocked for that key, through the `@db.blocking_keys` dictionary and we also get the actual collection, from `@db.data_store`, which is still of an unknown type at this point. It could either be a `List` or a `SortedSet`. We call `serve_client_blocked_on` with all the variable we just created. In `serve_client_blocked_on` we check for the type `list_or_set` and call the appropriate method depending on what we find, `serve_clients_blocked_on_lists` or `serve_clients_blocked_on_sorted_sets`. Each of these methods make use of the generic `generic_serve_clients` method, in which we left pop from the `clients` list, to get the client who is first in line. The `clients` list acts a queue where elements are right pushed and left popped to use a FIFO mechanism. We also create a new list, `clients_waiting_on_different_type` which will become handy shortly. Because we might be able to unblock more than one client, we iterate over all the nodes in client, and for each of them we yield back to either `serve_clients_blocked_on_sorted_sets` or `serve_clients_blocked_on_lists`. We need to check which type of keys the client was blocked for. If they ended up in the blocked queue because of `BLPOP`, `BRPOP` or `BRPOPLPUSH`, they need any of the keys they're blocked on to become a new list, and if they were blocked because of a `BZPOPMIN` or `BZPOPMAX` command, they need it to be a sorted. An example will illustrate this clearly: ``` 127.0.0.1:6379> BLPOP something something-else 0 ``` While this client is blocked, if I open another `redis-cli` and run the following: ``` 127.0.0.1:6379> SET something 123 OK 127.0.0.1:6379> ZADD something-else 0 a 0 b (integer) 2 ``` Then the first client is still blocked, because neither `something` or `something-else` were created as a `List`. The same goes if a client is blocked on a sorted set, it will only unblock if one the keys is created as a sorted set. We check for this with the methods `is_client_blocked_on_list?` and `is_client_blocked_on_sorted_set?` which both look at the `operation` attribute of the `BlockedState` object to determine which type of object the client is waiting for. If they match, that is if the client is waiting for a `List` and `list_or_set` is a `List`, or the other way around for sorted sets, then we proceed and call `handle_client`, otherwise we accumulate the clients in a different array, to make sure they are not deleted from the queue and so they are eventually unblocked in the future. `handle_client` returns a boolean, because it might actually fail to unblock the client in some uncommon edge cases. `generic_serve_clients` accumulates the unblocked clients in the `unblocked_clients` array, and it returns it, alongside all the clients that were waiting for the the other type. These two arrays are handled in `serve_client_blocked_on`, where we iterate through `clients_waiting_on_different_type` to put them back in the queue, and `unblocked_clients` is returned to `handle`. `handle_client` has been updated as well, mainly to rename the variable `list` to `list_or_set`, but the actual changes are in the `pop_operation` and `rollback_operation` methods. These methods use a `case/when` against the `operation` attribute to determine what to do. We need to add branches for `:zpopmax` and `:zpopmin` in order to be able to perform the right pop operation when a sorted set is created and we're in the process of unblocking a client. For `:zpopmax` we call `RESPArray.new([ key ] + @db.pop_max_from(key, list_or_set))` and for `:zpopmin` we call `RESPArray.new([ key ] + @db.pop_min_from(key, list_or_set))`. The array returned in each case is a three-element array with the name of the sorted array, the key, and the member/score pair. The key is required because a client might pass more than a single key to block on and without returning it, they wouldn't know which of the keys triggered the unblocking. We need to add these two methods to the `DB` class: ``` ruby module BYORedis class DB # ... def pop_max_from(key, sorted_set) generic_pop(key, sorted_set) do sorted_set.pop_max(1) end end def pop_min_from(key, sorted_set) generic_pop(key, sorted_set) do sorted_set.pop_min(1) end end # ... end end ``` _listing 10.72 The `pop_min_from` and `pop_max_from` methods in the `DB` class_ Both methods wrap the specific pop method from `RedisSet` and use `generic_pop` to make sure that if the popped element was the last one the sorted set is deleted from the database In the `rollback_operation` we can handle both operations the same way since calling `RedisSortedSet#add` will insert the element at the correct location. This wraps up the blocking commands. We now have three more small commands to add to complete this chapter. ## Misc commands There are three more commands left to add to complete all the sorted set commands. Let's start with `ZCOUNT` which counts the number of elements in the given score range. Its format is the following according to the [Redis Documentation][redis-doc-zcount]: ``` ZCOUNT key min max ``` We kept the simplest commands for last, this one takes three arguments, the key of the sorted set and the `min` and `max` values using the same semantic as we've seen in `ZRANGEBYSCORE`, that is we can use the exclusive prefix `(`. ``` ruby module BYORedis module SortedSetUtils # ... def self.generic_count(db, args) Utils.assert_args_length(3, args) key = args[0] min = args[1] max = args[2] sorted_set = db.lookup_sorted_set(key) count = yield(sorted_set, min, max) || 0 RESPInteger.new(count) end end # ... class ZCountCommand < BaseCommand def call SortedSetUtils.generic_count(@db, @args) do |sorted_set, min, max| range_spec = Utils.validate_score_range_spec(min, max) sorted_set&.count_in_score_range(range_spec) end end def self.describe Describe.new('zcount', 4, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@sortedset', '@fast' ]) end end end ``` _listing 10.73 The `ZCountCommand` class_ We use the `generic_count` method from `ZCountCommand`, because we'll be able to use later with `ZLEXCOUNT`. The generic method validates the argument array length, looks up the sorted set and yields the value back to the `call` method, and return what the block returns, as an `Integer`, which is the count value. The `min` and `max` value are sent back to the caller with `yield` because their handling will depend on the type of range we're expecting. With this command we need to treat them as range score items and in `ZLEXCOUNT` we will treat them as lex range items. We use `validate_score_range_spec` to create a new instance of `GenericRangeSpec`, specific to scores, and pass it to `count_in_score_range_spec` on `RedisSortedSet`: ``` ruby module BYORedis class RedisSortedSet # ... def count_in_score_range(range_spec) return 0 if range_spec.empty? || no_overlap_with_range?(range_spec) { |pair, _| pair.score } case @underlying when List then count_in_score_range_list(range_spec) when ZSet then @underlying.count_in_score_range(range_spec) else raise "Unknown type for #{ @underlying }" end end # ... private def generic_count_list(range_spec) count = 0 entered_range = false @underlying.each do |pair| in_range = range_spec.in_range?(yield(pair)) if in_range entered_range ||= true count += 1 elsif entered_range break end end count end def count_in_score_range_list(range_spec) generic_count_list(range_spec, &:score) end end end ``` _listing 10.74 The `RedisSortedSet#count_in_score_range` method_ The first two lines try to return early if the range spec is empty or if there's no overlap with the set, otherwise we call `count_in_score_range_list` or `ZSet#count_in_score_range`. Let's in `RedisSortedSet` and look at the list method. Most of the work is performed by the `generic_count_list` method, which iterates from the left to right with `each`, and keeps track of when it enters the range with the `entered_range` boolean. Determining if an element is in range is done by calling `in_range?` with the range spec, with the value returned by `yield(pair)`, which in this case returns the `score` attribute of `pair`. We keep incrementing the `count` variable as long as we find elements in the range, and as soon as we find an element outside of the range, we exit early, since there's no point in continuing iterating at this point. The `ZSet` case can be optimized thanks to the `SortedArray` class: ``` ruby module BYORedis class ZSet # ... def count_in_score_range(range_spec) generic_count(range_spec, &:score) end private # It is more than recommended to check that there is some overlap between the range_spec and # this set RedisSortedSet provides that with the no_overlap_with_range? method def generic_count(range_spec, &block) first_in_range_index = @array.first_index_in_range(range_spec, &block) last_in_range_index = @array.last_index_in_range(range_spec, &block) # We need to add 1 because the last index - the first index is off by one: # < 1, 2, 3, 4, 5>, with the range 2, 4, has the indices 1 & 3, 3 - 1 + 1 == 3 # If 4 had been specified as exclusive with (4, then the result should be 2, because # only the scores 2 & 3 (at index 1 & 2) fit in that range, and 2 - 1 + 1 == 2 last_in_range_index - first_in_range_index + 1 end end end ``` _listing 10.75 The `ZSet#count_in_score_range` method_ `ZSet#count_in_score_range` acts very similarly to `count_in_rank_range_list`, it is a wrapper around the method that actually does the work, `generic_count` in this case, with a block that returns the `score` attribute of a `Pair` instance. `generic_count` uses methods we've created before on `SortedArray`, `first_index_in_range` and `last_index_in_range`, which will both be "fast" by relying on `bsearch_index` under the hood. What's important to note is that it won't require a full iteration of the array, and each call to `bsearch_index` will have a O(logn) time complexity, making the time complexity of `generic_count` O(2logn), which happens to be on the same ballpark than O(logn). Put simply, the number of steps it takes to complete this method will grow as the set grows, but the growth will not be near to a linear growth, essentially, it will slow down "slowly". Once we have the first and last index, we can subtract them and add one to get the number of items in the range. We could have chosen a different approach, to only call `first_index_in_range`, to "jump" to the first element in the range, and to keep counting from there until we find an element outside the range. This alternative approach might actually be more efficient for very small ranges, within a very large sorted sets. In this case the binary search approach, while always being more efficient than a full scan, will require a lot of iterations to reach the element it's trying to find, but if the range is really small, it might actually be really fast to advance by that many items in the range and return that small count. Being able to find an acceptable threshold is complicated, and would require a lot of manual testing to find appropriate values. There would be a potential problem by _always_ using this alternative approach, we _could_ trigger a very slow count if the range was really big, say, more than a million items, we'd be looping a million times. The approach we picked might not always be the best but it will never be terrible thanks to the O(logn) time complexity of the binary search, which is at least a good starting point. An approximation of the number of steps required to find an element with `bsearch_index` can be done by using the log2n function, the [binary logarithm][wikipedia-binary-logarithm]. `log2n(1,000,000) ~= 19`. This is because at first the binary search operates on the full array, `1,000,000` items, it then slices it in half and looks at `500,000`, and so on, and after doing that `19` times, there should only be one or two items left. This tells us that in the worst case scenario, calling `first_index_in_range` and then `last_index_in_range` would require about `~38` iterations to retrieve both items, which is _way_ less than iterating a million times to count items one by one! The `ZLEXCOUNT` command is very similar, except that it works with a lexicographic range instead of a score range, its format is the following according to the [Redis Documentation][redis-doc-zlexcount]: ``` ZLEXCOUNT key min max ``` Let's create the `ZLexCountCommand` class: ``` ruby module BYORedis # ... class ZLexCountCommand < BaseCommand def call SortedSetUtils.generic_count(@db, @args) do |sorted_set, min, max| range_spec = Utils.validate_lex_range_spec(min, max) sorted_set&.count_in_lex_range(range_spec) end end def self.describe Describe.new('zlexcount', 4, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@sortedset', '@fast' ]) end end end ``` _listing 10.76 The `ZLexCountCommand` class_ We call `generic_count` the same way we did with `ZCOUNT`, but this time we use `validate_lex_range_spec` with the `min` and `max` variable, to create an instance of `GenericRangeSpec` specific to lexicographic order. We then call `count_in_lex_range` from `RedisSortedSet`: ``` ruby module BYORedis class RedisSortedSet # ... def count_in_lex_range(range_spec) return 0 if range_spec.empty? || no_overlap_with_range?(range_spec) { |pair, _| pair.member } case @underlying when List then count_in_lex_range_list(range_spec) when ZSet then @underlying.count_in_lex_range(range_spec) else raise "Unknown type for #{ @underlying }" end end # ... private # ... def count_in_lex_range_list(range_spec) generic_count_list(range_spec, &:member) end end end ``` _listing 10.77 The `RedisSortedSet#count_in_lex_range` method_ `count_in_lex_range` is very similar to `count_in_rank_range`, with the same early return check, and also delegates to two methods, `count_in_lex_range_list` and `ZSet#count_in_lex_range`. Both have these methods make use of the generic methods we created earlier and are very concise. `count_in_lex_range_list` can use `generic_count_list`, which does the iteration and counting work and only need a block to tell it what attribute to use from `Pair` instances. The same goes for `ZSet#count_in_lex_range`, which uses `generic_count` giving it the range spec to use, and telling it to use the `pair` attribute from the `Pair` instances: ``` ruby module BYORedis class ZSet # ... def count_in_lex_range(range_spec) generic_count(range_spec, &:member) end # ... end end ``` _listing 10.78 The `ZSet#count_in_range` method_ This wraps up the `ZLEXCOUNT` method. Finally, the `ZINCRBY` command increments the score of a member by the given increment value, its format is the following according to the [Redis Documentation][redis-doc-zincrby]: ``` ZINCRBY key increment member ``` The command is very similar to `HINCRBYFLOAT`, and performs a floating point increment, with all the infinity and `NaN` handling it requires. Let's create the `ZIncrByCommand` class: ``` ruby module BYORedis # ... class ZIncrByCommand < BaseCommand def call Utils.assert_args_length(3, @args) incr = Utils.validate_float(@args[1], 'ERR value is not a valid float') key = @args[0] member = @args[2] sorted_set = @db.lookup_sorted_set_for_write(key) new_score = sorted_set.increment_score_by(member, incr) RESPBulkString.new(Utils.float_to_string(new_score)) rescue InvalidFloatString RESPError.new('ERR hash value is not a float') rescue FloatNaN RESPError.new('ERR resulting score is not a number (NaN)') end def self.describe Describe.new('zincrby', 4, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@sortedset', '@fast' ]) end end end ``` _listing 10.79 The `ZIncrByCommand` class_ Once the sorted set is loaded, we call `RedisSortedSet#increment_score_by`: ``` ruby module BYORedis class RedisSortedSet # ... def increment_score_by(member, increment) current_score = score(member) || BigDecimal(0) new_score = Utils.add_or_raise_if_nan(current_score, increment) add(new_score, member) new_score end # ... end end ``` _listing 10.80 The `RedisSortedSet#increment_score_by` method_ If the result of `score(member)` is `nil`, which would happen if `member` is not already in the set, then we default it to `0`. Once loaded, we _safely_ add the `increment` value to it. Redis does not store `NaN` values so we use the method from `Utils` to raise a `FloatNaN` error if this happens. The new score is then either added or updated with the `add` method, depending on whether or not `member` was already in the set, but `add` knows how to take care of that. The `FloatNaN` exception is handled in the command class and returns the appropriate error message in that case, otherwise the result is returned as a string, because RESP2 does not have support for floating numbers. ## Conclusion You can find the code [on GitHub][github-code-link] We have now implemented all the native data types, with the exception of Streams. In the next chapter we will add support for the bitmap related commands, which operate on string values but almost behave as a different data type. [github-code-link]:https://github.com/pjambet/redis-in-ruby/tree/master/code/chapter-10 [redis-conf-zset-max-entries]:https://github.com/redis/redis/blob/6.0.0/redis.conf#L1525 [redis-conf-zset-max-value]:https://github.com/redis/redis/blob/6.0.0/redis.conf#L1526 [skiplist-paper]:https://15721.courses.cs.cmu.edu/spring2018/papers/08-oltpindexes1/pugh-skiplists-cacm1990.pdf [redis-sorted-set-commands]:https://redis.io/commands#sorted_set [chapter-8]:/post/chapter-8-adding-hash-commands/ [chapter-7]:/post/chapter-7-adding-list-commands/ [chapter-6]:/post/chapter-6-building-a-hash-table/ [ruby-doc-array-zip]:https://ruby-doc.org/core-2.7.1/Array.html#zip-method [redis-doc-zrangebyscore]:http://redis.io/commands/zrangebyscore [redis-doc-zremrangebyrank]:http://redis.io/commands/zremrangebyrank [ruby-doc-integer-spaceship]:https://ruby-doc.org/core-2.7.1/Integer.html#3C-3D-3E-method [ruby-doc-bigdecimal-spaceship]:https://ruby-doc.org/stdlib-2.7.1/libdoc/bigdecimal/rdoc/BigDecimal.html#3C-3D-3E-method [ruby-doc-proc-parameters]:https://ruby-doc.org/core-2.7.1/Proc.html#parameters-method [ruby-doc-proc-arity]:https://ruby-doc.org/core-2.7.1/Proc.html#arity-method [ruby-doc-string-spaceship]:https://ruby-doc.org/core-2.7.1/String.html#3C-3D-3E-method [redis-doc-zremrangebylex]:http://redis.io/commands/zremrangebylex [redis-doc-zremrangebyscore]:http://redis.io/commands/zremrangebyscore [redis-doc-zrevrange]:http://redis.io/commands/zrevrange [redis-doc-zrevrangebylex]:http://redis.io/commands/zrevrangebylex [redis-doc-zpopmax]:http://redis.io/commands/zpopmax [redis-doc-bzpopmax]:http://redis.io/commands/bzpopmax [redis-doc-bzpopmin]:http://redis.io/commands/bzpopmin [redis-doc-zcount]:http://redis.io/commands/zcount [redis-doc-zlexcount]:http://redis.io/commands/zlexcount [redis-doc-zincrby]:http://redis.io/commands/zincrby [redis-doc-zinterstore]:http://redis.io/commands/zinterstore [redis-doc-zinter]:http://redis.io/commands/zinter [redis-doc-zrange]:http://redis.io/commands/zrange [redis-doc-zrangebylex]:http://redis.io/commands/zrangebylex [redis-doc-zadd]:http://redis.io/commands/zadd [redis-src-tzset]:https://github.com/antirez/redis/blob/6.0.0/src/t_zset.c [wikipedia-e-notation]:https://en.wikipedia.org/wiki/Scientific_notation#E_notation [wikipedia-binary-prefix]:https://en.wikipedia.org/wiki/Binary_prefix [redis-src-server-panic]:https://github.com/redis/redis/blob/6.0.0/src/server.h#L441 [google-group-zdiff-comment]:https://groups.google.com/g/redis-db/c/Ti93ilzdyYw/m/jCo1QrMLgncJ [wikipedia-binary-logarithm]:https://en.wikipedia.org/wiki/Binary_logarithm <file_sep>/content/post/chapter-13-geo-commands.md --- title: "Chapter 13 Adding Geo Commands" date: 2020-10-17T18:17:58-04:00 lastmod: 2020-10-17T18:17:58-04:00 draft: true comment: false keywords: [] summary: "" --- <!--more--> GEOADD GEODIST GEOHASH GEOPOS GEORADIUS GEORADIUSBYMEMBER <file_sep>/content/post/chapter-4-adding-missing-options-to-set.md --- title: "Chapter 4 - Adding the missing options to the SET command" date: 2020-07-23T10:27:27-04:00 lastmod: 2020-07-23T10:27:27-04:00 draft: false keywords: [] summary: "In this chapter we add the missing features to the SET command we implemented in chapter 2, EX, PX, NX, XX & KEEPTTL" comment: false --- ## What we'll cover We implemented a simplified version of the `SET` command in [Chapter 2][chapter-2], in this chapter we will complete the command by implementing all [its options][redis-doc-set]. Note that we're still not following the [Redis Protocol][redis-protocol], we will address that in the next chapter. ## Planning our changes The [`SET`][redis-doc-set] commands accepts the following options: - EX seconds -- Set the specified expire time, in seconds. - PX milliseconds -- Set the specified expire time, in milliseconds. - NX -- Only set the key if it does not already exist. - XX -- Only set the key if it already exists. - KEEPTTL -- Retain the Time To Live (TTL) associated with the key As noted in the documentation, there is some overlap with some of the options above and the following commands: [SETNX][redis-doc-setnx], [SETEX][redis-doc-setex], [PSETEX][redis-doc-psetex]. As of this writing these three commands are not officially deprecated, but the documentation mentions that it might happen soon. Given that we can access the same features through the `NX`, `EX` & `PX` options respectively, we will not implement these three commands. `SET a-key a-value EX 10` is equivalent to `SETEX a-key 10 a-value`, which we can demonstrate in a `redis-cli` session: ``` 127.0.0.1:6379> SET a-key a-value EX 10 OK 127.0.0.1:6379> TTL "a-key" (integer) 8 127.0.0.1:6379> SETEX a-key 10 a-value OK 127.0.0.1:6379> TTL "a-key" (integer) 8 ``` [`TTL`][redis-doc-ttl] returned 8 in both cases, because it took me about 2s to type the `TTL` command, and by that time about 8s were left, of the initial 10. ### The EX & PX options Both EX & PX options are followed by one argument, an integer for the number of the seconds and milliseconds specifying how long the key will be readable for. Once the duration has elapsed, the key is deleted, and calling `GET` would return `(nil)` as if it was never set or explicitly deleted by the `DEL` command. When a key is set with either of these two options, or through the `SETEX` & `PSETEX` commands, but we are ignoring these for the sake of simplicity, Redis adds the key to different dictionary, internally called [`db->expires`][redis-source-db-expires] in the C code. This dictionary is dedicated to storing keys with a TTL, the key is the same key and the value is the timestamp of the expiration, in milliseconds. Redis uses two approaches to delete keys with a TTL. The first one is a lazy approach, when reading a key, it checks if it exists in the `expires` dictionary, if it does and the value is lower than the current timestamp in milliseconds, it deletes the key and does not proceed with the read. {{% admonition info "\"Lazy\" \& \"Eager\"" %}} The terms lazy is often used in programming, it describes an operation that is put on the back-burner and delayed until it absolutely has to be performed. In the context of Redis, it makes sense to describe the eviction strategy described above as lazy since Redis might still store keys that are effectively expired and will only guarantee their deletion until they are accessed past their expiration timestamp. The opposite approach is "eager", where an operation is performed as soon as possible, whether or not it could be postponed. {{% /admonition %}} The other one is a more proactive approach, Redis periodically scans a subset of the list of keys with a TTL value and deletes the expired one. This action, performed in the [`serverCron`][redis-source-server-cron] function is part of the [event loop][redis-doc-event-loop]. The event loop is defined in `ae.c` and starts in the `aeMain` function, it continuously executes the `aeProcessEvents` function in a while loop, until the `stop` flag is set to `1`, which essentially never happens when the server is running under normal circumstances. The `aeStop` function is the only function doing this and it is only used in `redis-benchmark.c` & `example-ae.c`. `aeProcessEvents` is a fairly big function, it would be hard to summarize it all here, but it first uses the `aeApiPoll` function, which is what we covered in the previous chapter. It processes the events from the poll result, if any and then calls `processTimeEvents`. Redis maintains a list of time events, as described in the event loop documentation page, for periodic task. When the server is initialized, one time event is created, for the `serverCron` function. This function is responsible for a lot of things, this is how it is described in the [source code][redis-source-server-cron-comments]: > This is our timer interrupt, called server.hz times per second.\ > Here is where we do a number of things that need to be done asynchronously.\ > For instance: > - Active expired keys collection (it is also performed in a lazy way on lookup). > - Software watchdog. > - Update some statistic. > - Incremental rehashing of the DBs hash tables. > - Triggering BGSAVE / AOF rewrite, and handling of terminated children. > - Clients timeout of different kinds. > - Replication reconnection. > - Many more... We're only interested in the first item in this list for now, the active expiration of keys. Redis runs the event loop on a single thread. This means that each operation performed in the event loop effectively blocks the ones waiting to be processed. Redis tries to optimize for this by making all the operations performed in the event loop "fast". This is one of the reasons why the documentation provides the time complexity for each commands. Most commands are O(1), and commands like [`KEYS`][redis-doc-keys], with an O(n) complexity are not recommended in a production environment, it would prevent the server from processing any incoming commands while iterating through all the keys. If Redis were to scan all the keys in the expires dictionary on every iteration of the event loop it would be an O(n) operation, where n is the number of keys with a TTL value. Put differently, as you add keys with a TTL, you would slow down the process of active expiration. To prevent this, Redis only scans the expires up to certain amount. The `activeExpireCycle` contains a lot of optimizations that we will not explore for now for the sake of simplicity. One of these optimizations takes care of maintaining statistics about the server, among those Redis keeps track of an estimate of the number of keys that are expired but not yet deleted. Using this it will attempt to expire more keys to try to keep this number under control and prevent it from growing too fast if keys start expiring faster than the normal rate at which they get deleted. `serverCron` is first added to the time events with a time set to 1ms in the future. The return value of functions executed as time events dictates if it is removed from the time event queue or if it is rescheduled in the future. `serverCron` returns a value based on the frequency set as config. By default 100ms. That means that it won't run more than 10 times per second. I think that it's worth stopping for a second to recognize the benefits of having two eviction strategies for expired keys. The lazy approach gets the job done as it guarantees that no expired keys will ever be returned, but if a key is set with a TTL and is never read again it would unnecessarily sit in memory, using space. The incremental active approach solves this problem, while still being optimized for speed and does not pause the server to clean all the keys. {{% admonition info "Big O Notation" %}} The [Big O Notation][big-o-notation] is used to describe the time complexity of operations. In other words, it describes how much slower, or not, an operation would be, as the size of the elements it operates on increases. The way that I like to think about it is to transcribe the O notation to a function with a single parameter n, that returns the value inside the parentheses after O. So O(n) — which is the complexity of the [`KEYS`][redis-doc-keys] command — would become `def fn(n); n; end;` if written in Ruby, or `let fn = (n) => n` in javascript. O(1) — which is the complexity of the [`SET`][redis-doc-set] command — would be `def fn(n); 1; end;`, O(logn) — which is the complexity of the [`ZADD`][redis-doc-zadd] command — would become `def fn(n); Math.log(n); end;` and O(n^2) — as far as I know, no Redis command has such complexity — would become `def fn(n); n.pow(2); end;`. We can play with these functions to illustrate the complexity of the different commands. `SET` has a time complexity of O(1), commonly referred to as constant time. Regardless of the number of keys stored in Redis, the operations required to fulfill a `SET` command are the same, so whether we are operating on an empty Redis server or one with millions of keys, it'll take a similar amount of time. With the function defined above we can see that, if n is the number of keys, `fn(n)` will always return `1`, regardless of n. On the other hand `KEYS` has a complexity of O(n), where n is the number of keys stored in Redis. It's important to note that n is always context dependent and should therefore always be specified, which Redis does on each command page. In comparison, [`DEL`][redis-doc-del] is also documented with having a time complexity of O(n), but, and this is the important part, where n is _the number of keys given to the command_. Calling `DEL a-key` has therefore a time complexity of O(1), and runs in constant time. `KEYS` iterates through all the items in Redis and return all the keys. With the function defined above, we can see that `fn(1)` will return `1`, `fn(10)`, `10`, and so on. What this tells us is that the time required to execute `KEYS` will grow proportionally to the value of n. Lastly, it's important to note that this does not necessarily mean that `KEYS` ran on a server with 100 items will be exactly 100 times slower than running against a server with one key. There are some operations that will have to be performed regardless, such as parsing the command and dispatching to the `keysCommand` function. These are in the category of "fixed cost", they always have to be performed. If it takes 1ms to run those and then 0.1ms per key — these are only illustrative numbers —, it would take Redis 1.1ms to run `KEYS` for one key and 10.1ms with 100 keys. It's not exactly 100 times more, but it is in the order of 100 times more. {{% /admonition %}} ### The NX, XX & KEEPTTL options These options are easier to implement compared to the previous two given that they are not followed by a value. Additionally, their behavior does not require implementing more components to the server, beyond a few conditions in the method that takes care of storing the key and the value specified by the `SET` command. Most of the complexity resides in the validations of the command, to make sure that it has a valid format. ### Adding validation Prior to adding these options, validating the `SET` command did not require a lot of work. In its simple form, it requires a key and value. If both are present, the command is valid, if one is missing, it is a "wrong number of arguments" error. This rule still applies but we need to add a few more to support the different combinations of possible options. These are the rules we now need to support: - You can only specify one of the PX or EX options, not both. Note that the `redis-cli` has a user friendly interface that hints at this constraint by displaying the following `key value [EX seconds|PX milliseconds] [NX|XX] [KEEPTTL]` when you start typing `SET`. The `|` character between `EX seconds` & `PX milliseconds` expresses the `OR` condition. - Following the hints from redis-cli, we can only specify `NX` or `XX`, not both. - The redis-cli hint does not make this obvious, but you can only specify `KEEPTTL` if neither `EX` or `PX` or present. The following command `SET 1 2 EX 1 KEEPTTL` is invalid and returns `(error) ERR syntax error` It's also worth mentioning that the order of options does not matter, both commands are equivalent: ``` SET a-key a-value NX EX 10 ``` ``` SET a-key a-value EX 10 NX ``` But the following would be invalid, `EX` must be followed by an integer: ``` SET a-key a-value EX NX 10 ``` ## Let's write some code! We are making the following changes to the server: - Add our own, simplified event loop, including support for time events - Accepts options for the expiration related options, `EX` & `PX` - Accepts options for the presence or absence of a key, `NX` & `XX` - Delete expired keys on read - Setting a key without `KEEPTTL` removes any previously set TTL - Implement the `TTL` & `PTTL` commands as they are useful to use alongside keys with a TTL I'm giving you the complete code first and we'll look at the interesting parts one by one afterwards: ``` ruby require 'socket' require 'timeout' require 'logger' LOG_LEVEL = ENV['DEBUG'] ? Logger::DEBUG : Logger::INFO require_relative './expire_helper' require_relative './get_command' require_relative './set_command' require_relative './ttl_command' require_relative './pttl_command' class RedisServer COMMANDS = { 'GET' => GetCommand, 'SET' => SetCommand, 'TTL' => TtlCommand, 'PTTL' => PttlCommand, } MAX_EXPIRE_LOOKUPS_PER_CYCLE = 20 DEFAULT_FREQUENCY = 10 # How many times server_cron runs per second TimeEvent = Struct.new(:process_at, :block) def initialize @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @clients = [] @data_store = {} @expires = {} @server = TCPServer.new 2000 @time_events = [] @logger.debug "Server started at: #{ Time.now }" add_time_event(Time.now.to_f.truncate + 1) do server_cron end start_event_loop end private def add_time_event(process_at, &block) @time_events << TimeEvent.new(process_at, block) end def nearest_time_event now = (Time.now.to_f * 1000).truncate nearest = nil @time_events.each do |time_event| if nearest.nil? nearest = time_event elsif time_event.process_at < nearest.process_at nearest = time_event else next end end nearest end def select_timeout if @time_events.any? nearest = nearest_time_event now = (Time.now.to_f * 1000).truncate if nearest.process_at < now 0 else (nearest.process_at - now) / 1000.0 end else 0 end end def start_event_loop loop do timeout = select_timeout @logger.debug "select with a timeout of #{ timeout }" result = IO.select(@clients + [@server], [], [], timeout) sockets = result ? result[0] : [] process_poll_events(sockets) process_time_events end end def process_poll_events(sockets) sockets.each do |socket| begin if socket.is_a?(TCPServer) @clients << @server.accept elsif socket.is_a?(TCPSocket) client_command_with_args = socket.read_nonblock(1024, exception: false) if client_command_with_args.nil? @clients.delete(socket) elsif client_command_with_args == :wait_readable # There's nothing to read from the client, we don't have to do anything next elsif client_command_with_args.strip.empty? @logger.debug "Empty request received from #{ client }" else commands = client_command_with_args.strip.split("\n") commands.each do |command| response = handle_client_command(command.strip) @logger.debug "Response: #{ response }" socket.puts response end end else raise "Unknown socket type: #{ socket }" end rescue Errno::ECONNRESET @clients.delete(socket) end end end def process_time_events @time_events.delete_if do |time_event| next if time_event.process_at > Time.now.to_f * 1000 return_value = time_event.block.call if return_value.nil? true else time_event.process_at = (Time.now.to_f * 1000).truncate + return_value @logger.debug "Rescheduling time event #{ Time.at(time_event.process_at / 1000.0).to_f }" false end end end def handle_client_command(client_command_with_args) @logger.debug "Received command: #{ client_command_with_args }" command_parts = client_command_with_args.split command_str = command_parts[0] args = command_parts[1..-1] command_class = COMMANDS[command_str] if command_class command = command_class.new(@data_store, @expires, args) command.call else formatted_args = args.map { |arg| "`#{ arg }`," }.join(' ') "(error) ERR unknown command `#{ command_str }`, with args beginning with: #{ formatted_args }" end end def server_cron start_timestamp = Time.now keys_fetched = 0 @expires.each do |key, _| if @expires[key] < Time.now.to_f * 1000 @logger.debug "Evicting #{ key }" @expires.delete(key) @data_store.delete(key) end keys_fetched += 1 if keys_fetched >= MAX_EXPIRE_LOOKUPS_PER_CYCLE break end end end_timestamp = Time.now @logger.debug do sprintf( "Processed %i keys in %.3f ms", keys_fetched, (end_timestamp - start_timestamp) * 1000) end 1000 / DEFAULT_FREQUENCY end end ``` _listing 4.1: server.rb_ ``` ruby class SetCommand ValidationError = Class.new(StandardError) CommandOption = Struct.new(:kind) CommandOptionWithValue = Struct.new(:kind, :validator) OPTIONS = { 'EX' => CommandOptionWithValue.new( 'expire', ->(value) { validate_integer(value) * 1000 }, ), 'PX' => CommandOptionWithValue.new( 'expire', ->(value) { validate_integer(value) }, ), 'KEEPTTL' => CommandOption.new('expire'), 'NX' => CommandOption.new('presence'), 'XX' => CommandOption.new('presence'), } ERRORS = { 'expire' => '(error) ERR value is not an integer or out of range', } def self.validate_integer(str) Integer(str) rescue ArgumentError, TypeError raise ValidationError, '(error) ERR value is not an integer or out of range' end def initialize(data_store, expires, args) @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @data_store = data_store @expires = expires @args = args @options = {} end def call key, value = @args.shift(2) if key.nil? || value.nil? return "(error) ERR wrong number of arguments for 'SET' command" end parse_result = parse_options if !parse_result.nil? return parse_result end existing_key = @data_store[key] if @options['presence'] == 'NX' && !existing_key.nil? '(nil)' elsif @options['presence'] == 'XX' && existing_key.nil? '(nil)' else @data_store[key] = value expire_option = @options['expire'] # The implied third branch is if expire_option == 'KEEPTTL', in which case we don't have # to do anything if expire_option.is_a? Integer @expires[key] = (Time.now.to_f * 1000).to_i + expire_option elsif expire_option.nil? @expires.delete(key) end 'OK' end rescue ValidationError => e e.message end private def parse_options while @args.any? option = @args.shift option_detail = OPTIONS[option] if option_detail option_values = parse_option_arguments(option, option_detail) existing_option = @options[option_detail.kind] if existing_option return '(error) ERR syntax error' else @options[option_detail.kind] = option_values end else return '(error) ERR syntax error' end end end def parse_option_arguments(option, option_detail) case option_detail when CommandOptionWithValue option_value = @args.shift option_detail.validator.call(option_value) when CommandOption option else raise "Unknown command option type: #{ option_detail }" end end end ``` _listing 4.2: set_command.rb_ ``` ruby class GetCommand def initialize(data_store, expires, args) @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @data_store = data_store @expires = expires @args = args end def call if @args.length != 1 "(error) ERR wrong number of arguments for 'GET' command" else key = @args[0] ExpireHelper.check_if_expired(@data_store, @expires, key) @data_store.fetch(key, '(nil)') end end end ``` _listing 4.3: get_command.rb_ ``` ruby class PttlCommand def initialize(data_store, expires, args) @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @data_store = data_store @expires = expires @args = args end def call if @args.length != 1 "(error) ERR wrong number of arguments for 'PTTL' command" else key = @args[0] ExpireHelper.check_if_expired(@data_store, @expires, key) key_exists = @data_store.include? key if key_exists ttl = @expires[key] if ttl (ttl - (Time.now.to_f * 1000)).round else -1 end else -2 end end end end ``` _listing 4.4: pttl_command.rb_ ``` ruby class TtlCommand def initialize(data_store, expires, args) @data_store = data_store @expires = expires @args = args end def call if @args.length != 1 "(error) ERR wrong number of arguments for 'TTL' command" else pttl_command = PttlCommand.new(@data_store, @expires, @args) result = pttl_command.call.to_i if result > 0 (result / 1000.0).round else result end end end end ``` _listing 4.5: ttl_command.rb_ ``` ruby module ExpireHelper def self.check_if_expired(data_store, expires, key) expires_entry = expires[key] if expires_entry && expires_entry < Time.now.to_f * 1000 logger.debug "evicting #{ key }" expires.delete(key) data_store.delete(key) end end def self.logger @logger ||= Logger.new(STDOUT).tap do |l| l.level = LOG_LEVEL end end end ``` _listing 4.6: expire_helper.rb_ ### The changes #### Splitting it the logic in multiple files The `server.rb` file started getting pretty big so we extracted the logic for `GET` & `SET` to different files, and gave them their own classes. #### Time events In order to implement the eviction logic for keys having an expiration, we refactored how we call the `IO.select` method. Our implementation is loosely based on the one built in Redis, [ae][redis-doc-ae]. The `RedisServer` — renamed from `BasicServer` in the previous chapters — starts the event loop in its constructor. The event loop is a never ending loop that calls `select`, processes all the incoming events and then process time events, if any need to be processed. We introduced the `TimeEvent` class, defined as follows: ``` ruby TimeEvent = Struct.new(:process_at, :block) ``` The `process_at` field is an `Integer` that represents the timestamp, in milliseconds, for when the event should be processed. The `block` field is the actual code that will be run. For now, there's only one type of events, `server_cron`. It is first added to the `@time_events` list with a `process_at` value set to 1ms in the future. Time events can be either one-off, they'll run only once, or repeating, they will be rescheduled at some point in the future after being processed. This behavior is driven by the return value of the `block` field. If the block returns `nil`, the time event is removed from the `@time_events` list, if it returns an integer `return_value`, the event is rescheduled for `return_value` milliseconds in the future, by changing the value of `process_at`. By default the `server_cron` method is configured with a frequency of 10 Hertz (hz), which means it will run up to 10 times per second, or put differently, every 100ms. This is why the return value of `server_cron` is `1000 / DEFAULT_FREQUENCY` — 1000 is the number of milliseconds, if frequency was 20, it would return 50, as in, it should run every 50ms. This behavior makes sure that we don't run the `server_cron` method too often, it effectively gives a higher priority to handling client commands, and new clients connecting. #### Select timeout When we introduced `IO.select` in [Chapter 3][chapter-3-select], we used it without the timeout argument. This wasn't a problem then because the server had nothing else to do. It would either need to accept a new client, or reply to a client command, and both would be handled through `select`. The server needs to do something else beside waiting on `select` now, run the time events when they need to be processed. In order to do so, Redis uses a timeout with its abstraction over select and other multiplexing libraries, `aeApiPoll`. Redis can, under some conditions, use no timeout, which we're going to ignore for now, for the sake of simplicity. When using a timeout, Redis makes sure that waiting on the timeout will not delay any future time events that should be processed instead of waiting on `select`. In order to achieve this, Redis looks at all the time events and finds the nearest one, and sets a timeout equivalent to the time between now and that event. This guarantees that even if there's no activity between now and when the next time event should be processed, redis will stop waiting on `aeApiPoll` and process the time events. We're replicating this logic in the `select_timeout` method. It starts by delegating the task of finding the nearest time event through the `nearest_time_event`, which iterates through all the time events in the `@time_events` array and find the one with the smallest value for `process_at`. In concrete terms, in `RedisServer`, `server_cron` runs every 100ms, so when we call `IO.select`, the next time event will be at most 100ms in the future. The timeout given to `select` will be a value between 0 and 100ms. #### Parsing options Probably one of the most complicated changes introduced in this chapter, at least for me as I was implementing it. The logic is in the `SetCommand` class. We first define all the possible options in the `OPTIONS` constant. Each option is a key/value pair where the key is the option as expected in the command string and the value is an instance of `CommandOption` or `CommandOptionWithValue`. After extracting and validating the first three elements of the string, respectively, the `SET` string, followed by the key and the value, we split the rest on spaces and process them from left to right, with the `shift` method. For every option we find, we look up the `OPTIONS` hash to retrieve the matching `CommandOption` or `CommandOptionWithValue` instance. If `nil` is returned, it means that the given option is invalid, this is a syntax error. Note that once again, for the sake of simplicity, we did not implement case insensitive commands the way Redis does. If the an option is found, but we had already found one of the same kind, `presence` or `expire`, this is also a syntax error. This check allows us to consider the following commands as invalid: ``` SET key value EX 1 PX 2 SET key value EX 1 KEEPTTL SET key value NX XX ``` Finally, we attempt to parse the option argument, if necessary, only `EX` and `PX` have an argument, the others one do not, this is why we use two different classes here. `parse_option_arguments` will return the option itself if we found an option that should not be followed by an argument, that is either `NX`, `XX` or `KEEPTTL`. If we found one of the other two options, `option_detail` will be an instance of `CommandOptionWithValue`, we use `shift` once again to obtain the next element in the command string and feed it to the validator block. The validator blocks are very similar for the options, they both validate that the string is a valid integer, but the `EX` validator multiplies the final result by 1000 to convert the value from seconds to milliseconds. The values are then stored in the `@options` hash, with either the `presence` or `expire` key, based on the `kind` value. This allows us to read from the `@options` hash in the call method to apply the logic required to finalize the implementation of these options. If `@options['presence']` is set to `NX` and there is already a value at the same key, we return `nil` right away. Similarly if it is set to `XX` and there is no key, we also return nil. Finally, we always set the value for the key in the `@data_store` hash, but the behavior regarding the secondary hash, `@expires`, is different depending on the value of `@options['expire']`. If it is set to an integer, we use this integer and add it to the current time, in milliseconds, in the `@expires` hash. If the value is nil, it means that `KEEPTTL` was not passed, so we remove any value that may have previously been set by a previous `SET` command with the same key and value for either `PX` or `EX`. **Why not use a regular expression?** Good question! The short answer is that after spending some time trying to use a regular expression, it did not feel easier, as a reference this where I got, just before I gave up: ``` ruby /^SET \d+ \d+ (?:EX (?<ex>\d+)|PX (?<px>\d+)|KEEPTTL)?(:? ?(?<nx-or-xx>NX|XX))?(?: (?:EX (?<ex>\d+)|PX (?<px>\d+)))?$/ ``` This regexp works for some cases but incorrectly considers the following as valid, Redis cannot process a `SET` command with `KEEPTTL` and `EX 1`: ``` SET 1 2 KEEPTTL XX EX 1 ``` It _might_ be possible to use a regular expression here, given that the grammar of the `SET` command does not allow that many permutations but even if it is, I don't think it'll be simpler than the solution we ended up with. For reference, [this is how Redis does it][redis-source-parse-set-options], in a way that it conceptually not that far from how we ended up doing it here. The main difference is that in the Redis source, it is one function, whereas we opted to separate the definition of the options, in the `OPTIONS` constant, from the actual code that consumes the characters from the string received from the client. I find the separated option a bit more readable and easier to reason about, but the approach used by Redis is definitely more efficient as there are less "things" being allocated, no extra resources to define what the options look like, just strings. #### Lazy evictions The `server_cron` time event takes care of cleaning up expired key every 100ms, but we also want to implement the "lazy eviction", the same way Redis does. That is, if `server_cron` hasn't had the chance to evict an expired key yet, and the server receives a `GET` command for the same key, we want to return nil and evict the key instead of returning it. This logic is implemented in the `ExpireHelper` module , in the `check_if_expired` method. This method checks if there is an entry in the `@expires` hash, and if there is it compares its value, a timestamp in milliseconds with the current time. If the value in `@expires` is smaller, the key is expired and it deletes it. This will cause the `GetCommand`, `TtlCommand` & `PttlCommand` classes to return `(nil)` even if `server_cron` hasn't had a chance to delete the expired keys. #### New commands: TTL & PTTL We added two new commands, `TTL` & `PTTL`. Both return the ttl of the given key as an integer, if it exists, the difference is that `TTL` returns the value in seconds, whereas `PTTL` returns it in milliseconds. Given the similarity of these two commands, we only implemented the logic in the `PttlCommand` class, and reused from the `TtlCommand` class where we transform the value in milliseconds to a value in seconds before returning it. #### Logger As the complexity of the codebase grew, it became useful to add logging statements. Such statements could be simple calls to `puts`, `print` or `p`, but it is useful to be able to conditionally turn them on and off based on their severity. Most of the logs we added are only useful when debugging an error and are otherwise really noisy. All these statements are logged with `@logger.debug`, and the severity of the logger is set based on the `DEBUG` environment variable. This allows us to enable all the debug logs by adding the `DEBUG=t` statement before running the server: ``` bash DEBUG=true ruby -r"./server" -e "RedisServer.new" ``` ### And a few more tests We changed a lot of code and added more features, this calls for more tests. We added a special instruction, `sleep <duration>` to allow us to easily write tests for the `SET` command with any of the expire based options. For instance, to test that `SET key value PX 100` actually works as expected, we want to wait at least 100ms, and assert that `GET key` returns `(nil)` instead of `value`. We also added a new way to specify assertion, with the syntax `[ 'PTTL key', '2000+/-20' ]`. This is useful for the `PTTL` command because it would be impossible to know exactly how long it'll take the computer running the tests to execute the `PTTL` command after running the `SET` command. We can however estimate a reasonable range. In this case, we are assuming that the machine running the test will take less than 20ms to run `PTTL` by leveraging the minitest assertion `assert_in_delta`. I also added the option to set the `DEBUG` environment variable, which you can use when running all the tests or an individual test: ``` bash // All tests: DEBUG=t ruby test.rb // Any values will work, even "false", as long as it's not nil // Or a specific test DEBUG=t ruby test.rb --name "RedisServer::SET#test_0005_handles the PX option with a valid argument" ``` There is now a `begin/rescue` for `Interrupt` in the forked process. This is to prevent an annoying stacktrace from being logged when we kill the process with `Process.kill('INT', child)` after sending all the commands to the server. ``` ruby require 'minitest/autorun' require 'timeout' require 'stringio' require './server' describe 'RedisServer' do # ... def with_server child = Process.fork do unless !!ENV['DEBUG'] # We're effectively silencing the server with these two lines # stderr would have logged something when it receives SIGINT, with a complete stacktrace $stderr = StringIO.new # stdout would have logged the "Server started ..." & "New client connected ..." lines $stdout = StringIO.new end begin RedisServer.new rescue Interrupt => e # Expected code path given we call kill with 'INT' below end end yield ensure if child Process.kill('INT', child) Process.wait(child) end end def assert_command_results(command_result_pairs) with_server do command_result_pairs.each do |command, expected_result| if command.start_with?('sleep') sleep command.split[1].to_f next end begin socket = connect_to_server socket.puts command response = socket.gets # Matches "2000+\-10", aka 2000 plus or minus 10 regexp_match = expected_result.match /(\d+)\+\/-(\d+)/ if regexp_match # The result is a range assert_in_delta regexp_match[1].to_i, response.to_i, regexp_match[2].to_i else assert_equal expected_result + "\n", response end ensure socket.close if socket end end end end # ... describe 'TTL' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'TTL', '(error) ERR wrong number of arguments for \'TTL\' command' ], ] end it 'returns the TTL for a key with a TTL' do assert_command_results [ [ 'SET key value EX 2', 'OK'], [ 'TTL key', '2' ], [ 'sleep 0.5' ], [ 'TTL key', '1' ], ] end it 'returns -1 for a key without a TTL' do assert_command_results [ [ 'SET key value', 'OK' ], [ 'TTL key', '-1' ], ] end it 'returns -2 if the key does not exist' do assert_command_results [ [ 'TTL key', '-2' ], ] end end describe 'PTTL' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'PTTL', '(error) ERR wrong number of arguments for \'PTTL\' command' ], ] end it 'returns the TTL in ms for a key with a TTL' do assert_command_results [ [ 'SET key value EX 2', 'OK'], [ 'PTTL key', '2000+/-20' ], # Initial 2000ms +/- 20ms [ 'sleep 0.5' ], [ 'PTTL key', '1500+/-20' ], # Initial 2000ms, minus ~500ms of sleep, +/- 20ms ] end it 'returns -1 for a key without a TTL' do assert_command_results [ [ 'SET key value', 'OK' ], [ 'PTTL key', '-1' ], ] end it 'returns -2 if the key does not exist' do assert_command_results [ [ 'PTTL key', '-2' ], ] end end # ... describe 'SET' do # ... it 'handles the EX option with a valid argument' do assert_command_results [ [ 'SET 1 3 EX 1', 'OK' ], [ 'GET 1', '3' ], [ 'sleep 1' ], [ 'GET 1', '(nil)' ], ] end it 'rejects the EX option with an invalid argument' do assert_command_results [ [ 'SET 1 3 EX foo', '(error) ERR value is not an integer or out of range'] ] end it 'handles the PX option with a valid argument' do assert_command_results [ [ 'SET 1 3 PX 100', 'OK' ], [ 'GET 1', '3' ], [ 'sleep 0.1' ], [ 'GET 1', '(nil)' ], ] end it 'rejects the PX option with an invalid argument' do assert_command_results [ [ 'SET 1 3 PX foo', '(error) ERR value is not an integer or out of range'] ] end it 'handles the NX option' do assert_command_results [ [ 'SET 1 2 NX', 'OK' ], [ 'SET 1 2 NX', '(nil)' ], ] end it 'handles the XX option' do assert_command_results [ [ 'SET 1 2 XX', '(nil)'], [ 'SET 1 2', 'OK'], [ 'SET 1 2 XX', 'OK'], ] end it 'removes ttl without KEEPTTL' do assert_command_results [ [ 'SET 1 3 PX 100', 'OK' ], [ 'SET 1 2', 'OK' ], [ 'sleep 0.1' ], [ 'GET 1', '2' ], ] end it 'handles the KEEPTTL option' do assert_command_results [ [ 'SET 1 3 PX 100', 'OK' ], [ 'SET 1 2 KEEPTTL', 'OK' ], [ 'sleep 0.1' ], [ 'GET 1', '(nil)' ], ] end it 'accepts multiple options' do assert_command_results [ [ 'SET 1 3 NX EX 1', 'OK' ], [ 'GET 1', '3' ], [ 'SET 1 3 XX KEEPTTL', 'OK' ], ] end it 'rejects with more than one expire related option' do assert_command_results [ [ 'SET 1 3 PX 1 EX 2', '(error) ERR syntax error'], [ 'SET 1 3 PX 1 KEEPTTL', '(error) ERR syntax error'], [ 'SET 1 3 KEEPTTL EX 2', '(error) ERR syntax error'], ] end it 'rejects with both XX & NX' do assert_command_results [ [ 'SET 1 3 NX XX', '(error) ERR syntax error'], ] end end # ... end ``` ## Conclusion The `SET` commands implemented by `RedisServer` now behaves the same way it does with Redis. Well, almost. Let's take a look at what happens if we were to use `redis-cli` against our own server. Let's start by running our server with ``` bash ruby -r"./server" -e "RedisServer.new" ``` and in another shell open `redis-cli` on port 2000: ``` bash redis-cli -p 2000 ``` And type the following: ``` SET key value EX 200 ``` And boom! It crashes! ``` Error: Protocol error, got "(" as reply type byte ``` This is because `RedisServer` does not implement the [Redis Protocol, RESP][redis-protocol]. This is what the next chapter is all about. At the end of chapter 5 we will be able to use `redis-cli` against our own server. Exciting! ## Code As usual, the code [is available on GitHub](https://github.com/pjambet/redis-in-ruby/tree/master/code/chapter-4). ## Appendix A: Links to the Redis source code If you're interested in digging into the Redis source code but would like some pointers as to where to start, you've come to the right place. The Redis source code is really well architected and overall relatively easy to navigate, so you are more than welcome to start the adventure on your own. That being said, it did take me a while to find the locations of functions I was interested in, such as: "where does redis handle the eviction of expired keys", and a few others. Before jumping in the code, you might want to read this article that explains some of the main data structures used by Redis: http://blog.wjin.org/posts/redis-internal-data-structure-dictionary.html. In no particular orders, the following is a list of links to the Redis source code on GitHub, for features related to the implementation of keys with expiration: ### Handling of the SET command: - `server.c` defines all the commands in `redisCommand`: https://github.com/antirez/redis/blob/6.0.0/src/server.c#L182 - `t_string.c` defines the handler in `setCommand`: https://github.com/antirez/redis/blob/6.0.0/src/t_string.c#L97-L147 - `t_string.c` defines a more specific handlers after options are parsed where expire values are handled: https://github.com/antirez/redis/blob/6.0.0/src/t_string.c#L71-L79 & https://github.com/antirez/redis/blob/6.0.0/src/t_string.c#L89 - `db.c` defines the `setExpire` function: https://github.com/antirez/redis/blob/6.0.0/src/db.c#L1190-L1206 ### Key deletion in `serverCron` - `server.c` defines the handler for `GET`: https://github.com/antirez/redis/blob/6.0.0/src/server.c#L187-L189 - `t_string.c` defines the handler for `getCommand`: https://github.com/antirez/redis/blob/6.0.0/src/t_string.c#L179-L181 & the generic one: https://github.com/antirez/redis/blob/6.0.0/src/t_string.c#L164-L177 - `db.c` defines `lookupKeyReadOrReply`: https://github.com/antirez/redis/blob/6.0.0/src/db.c#L163-L167 - `db.c` defines `lookupKeyRead` https://github.com/antirez/redis/blob/6.0.0/src/db.c#L143-L147 as well as `lookupKeyReadWithFlags`: https://github.com/antirez/redis/blob/6.0.0/src/db.c#L149-L157 - `db.c` defines `expireIfNeeded`: https://github.com/antirez/redis/blob/6.0.0/src/db.c#L1285-L1326 - `expire.c` defines `activeExpireCycleTryExpire` which implements the deletion of expired keys: https://github.com/antirez/redis/blob/6.0.0/src/expire.c#L35-L74 - `expire.c` defines `activeExpireCycle` which implement the sampling of keys and the logic to make sure that there are not too many expired keys in the `expires` dict: https://github.com/redis/redis/blob/6.0.0/src/expire.c#L123 ## Appendix B: Playing with RedisServer using `nc` If you want to manually interact with the server, an easy way is to use `nc`, the same way we used in [Chapter 1][chapter-1]. `nc` has no awareness of the Redis command syntax, so it will not stop you from making typos: ``` bash > nc localhost 2000 GET 1 (nil) SET 1 2 OK GET 1 2 SET 1 2 EX 5 OK GET 1 2 GET 1 2 GET 1 (nil) SET 1 2 XX (nil) SET 1 2 NX OK SET 1 2 XX OK DEL 1 (error) ERR unknown command `DEL`, with args beginning with: `1`, SET 1 2 PX 100 OK SET 1 2 XX (nil) ``` [chapter-1]:/post/chapter-1-basic-server/ [chapter-2]:/post/chapter-2-respond-to-get-and-set/ [chapter-3-select]:/post/chapter-3-multiple-clients/#lets-use-select [redis-protocol]:https://redis.io/topics/protocol [redis-doc-set]:https://redis.io/commands/set [redis-doc-del]:https://redis.io/commands/del [redis-doc-setnx]:https://redis.io/commands/setnx [redis-doc-setex]:https://redis.io/commands/setex [redis-doc-psetex]:https://redis.io/commands/psetex [redis-doc-zadd]:http://redis.io/commands/zadd [redis-doc-ttl]:http://redis.io/commands/ttl [redis-doc-pttl]:http://redis.io/commands/pttl [redis-doc-event-loop]:https://redis.io/topics/internals-rediseventlib [redis-doc-keys]:https://redis.io/commands/keys [redis-source-server-cron]:https://github.com/antirez/redis/blob/6.0.0/src/server.c#1849 [redis-source-server-cron-comments]:https://github.com/antirez/redis/blob/6.0.0/src/server.c#L1826-L1838 [big-o-notation]:https://en.wikipedia.org/wiki/Big_O_notation [redis-doc-ae]:https://redis.io/topics/internals-rediseventlib [wikipedia-syntax]:https://en.wikipedia.org/wiki/Syntax_(programming_languages) [redis-source-db-expires]:https://github.com/redis/redis/blob/6.0.0/src/server.h#L645 [redis-source-parse-set-options]:https://github.com/redis/redis/blob/6.0.0/src/t_string.c#L97-L147 <file_sep>/content/_index.md --- title: "Rebuilding Redis in Ruby" date: 2020-05-23T10:27:27-04:00 lastmod: 2020-05-23T10:27:27-04:00 draft: false keywords: [] description: "Introduction to Redis in Ruby and who the book is for" tags: [] categories: [] --- # Welcome! This website is a free online book about rebuilding [Redis™*](https://redis.io/) in Ruby, from scratch. It is still a work in progress, the first ten chapters are currently available, and you can see the planned table of content on the [chapters page](/chapters). Start reading the first [chapter below](#posts), or head to the [chapters list](/chapters/) ## Who is this for? This online book is aimed at people with some programming experience. I am assuming a reasonable level of familiarity with programming concepts such as conditions, loops, classes as well as some understanding of networking. Readers should already have heard of protocols such as [HTTP][http] and [TCP][tcp] and I think it would help to have already worked with those. Anyone who worked with a web application, regardless of the language, should have enough experience to read this book. If you've worked with a server backend in Ruby, Python, Javascript, or literally anything else, or did frontend work involving fetch and/or ajax, this should be enough! Lastly, readers should also be familiar with [threads][wikipedia-threads] and [processes][wikipedia-processes]. No expertise is required, and I am far from being an expert on the topic, but if you've never heard of these, I would advise to glance at the linked wikipedia pages, and to potentially explore the APIs of your favorite languages. Most languages provide tools to interact with threads and processes. Ruby, which we'll be using in this book, has [a Thread class][ruby-doc-thread] and [a Process class][ruby-doc-process]. I am writing this book aiming for it to be useful to five years ago me, when I had about 2 and 3 years of professional experience. I majored in computer science, so back then I had already a few years of experience with programming. That being said, a degree in CS is definitely not required to read this. On a spectrum from beginner to expert, I would say that this book lands somewhere in the middle, but leaning towards beginner, slightly to the left, so intermediate-ish. [http]:https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol [tcp]:https://en.wikipedia.org/wiki/Transmission_Control_Protocol [wikipedia-threads]:https://en.wikipedia.org/wiki/Thread_(computing) [wikipedia-processes]:https://en.wikipedia.org/wiki/Process_(computing) [ruby-doc-thread]:https://ruby-doc.org/core-2.7.1/Thread.html [ruby-doc-process]:https://ruby-doc.org/core-2.7.1/Process.html _\* Redis is a trademark of Redis Labs Ltd. Any rights therein are reserved to Redis Labs Ltd. Any use by this website is for referential purposes only and does not indicate any sponsorship, endorsement or affiliation between Redis and this website_ <file_sep>/code/chapter-5/pttl_command.rb module BYORedis class PttlCommand def initialize(data_store, expires, args) @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @data_store = data_store @expires = expires @args = args end def call if @args.length != 1 RESPError.new("ERR wrong number of arguments for 'PTTL' command") else key = @args[0] ExpireHelper.check_if_expired(@data_store, @expires, key) key_exists = @data_store.include? key value = if key_exists ttl = @expires[key] if ttl (ttl - (Time.now.to_f * 1000)).round else -1 end else -2 end RESPInteger.new(value) end end def self.describe [ 'pttl', 2, # arity # command flags [ 'readonly', 'random', 'fast' ].map { |s| RESPSimpleString.new(s) }, 1, # position of first key in argument list 1, # position of last key in argument list 1, # step count for locating repeating keys # acl categories: https://github.com/antirez/redis/blob/6.0/src/server.c#L161-L166 [ '@keyspace', '@read', '@fast' ].map { |s| RESPSimpleString.new(s) }, ] end end end <file_sep>/code/chapter-10/set_commands.rb require_relative './redis_set' module BYORedis module SetUtils def self.generic_sinter(db, args) sets = args.map do |set_key| set = db.lookup_set(set_key) return RedisSet.new if set.nil? set end RedisSet.intersection(sets) end def self.generic_set_store_operation(db, args) Utils.assert_args_length_greater_than(1, args) destination_key = args.shift sets = args.map { |other_set| db.lookup_set(other_set) } new_set = yield sets if new_set.empty? db.data_store.delete(destination_key) else db.data_store[destination_key] = new_set end RESPInteger.new(new_set.cardinality) end end class SAddCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) key = @args.shift new_member_count = 0 set = @db.lookup_set_for_write(key) @args.each do |member| added = set.add(member) new_member_count += 1 if added end RESPInteger.new(new_member_count) end def self.describe Describe.new('sadd', -3, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@set', '@fast' ]) end end class SCardCommand < BaseCommand def call Utils.assert_args_length(1, @args) set = @db.lookup_set(@args[0]) cardinality = set.nil? ? 0 : set.cardinality RESPInteger.new(cardinality) end def self.describe Describe.new('scard', 2, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@set', '@fast' ]) end end class SDiffCommand < BaseCommand def call Utils.assert_args_length_greater_than(0, @args) sets = @args.map { |other_set| @db.lookup_set(other_set) } RESPArray.new(RedisSet.difference(sets).members) end def self.describe Describe.new('sdiff', -2, [ 'readonly', 'sort_for_script' ], 1, -1, 1, [ '@read', '@set', '@slow' ]) end end class SDiffStoreCommand < BaseCommand def call SetUtils.generic_set_store_operation(@db, @args) do |sets| RedisSet.difference(sets) end end def self.describe Describe.new('sdiffstore', -3, [ 'write', 'denyoom' ], 1, -1, 1, [ '@write', '@set', '@slow' ]) end end class SInterCommand < BaseCommand def call Utils.assert_args_length_greater_than(0, @args) intersection = SetUtils.generic_sinter(@db, @args) RESPArray.new(intersection.members) end def self.describe Describe.new('sinter', -2, [ 'readonly', 'sort_for_script' ], 1, -1, 1, [ '@read', '@set', '@slow' ]) end end class SInterStoreCommand < BaseCommand def call SetUtils.generic_set_store_operation(@db, @args) do SetUtils.generic_sinter(@db, @args) end end def self.describe Describe.new('sinterstore', -3, [ 'write', 'denyoom' ], 1, -1, 1, [ '@write', '@set', '@slow' ]) end end class SUnionCommand < BaseCommand def call Utils.assert_args_length_greater_than(0, @args) sets = @args.map { |set_key| @db.lookup_set(set_key) }.compact RESPArray.new(RedisSet.union(sets).members) end def self.describe Describe.new('sunion', -2, [ 'readonly', 'sort_for_script' ], 1, -1, 1, [ '@read', '@set', '@slow' ]) end end class SUnionStoreCommand < BaseCommand def call SetUtils.generic_set_store_operation(@db, @args) do |sets| RedisSet.union(sets) end end def self.describe Describe.new('sunionstore', -3, [ 'write', 'denyoom' ], 1, -1, 1, [ '@write', '@set', '@slow' ]) end end class SIsMemberCommand < BaseCommand def call Utils.assert_args_length(2, @args) set = @db.lookup_set(@args[0]) if set presence = set.member?(@args[1]) ? 1 : 0 RESPInteger.new(presence) else RESPInteger.new(0) end end def self.describe Describe.new('sismember', 3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@set', '@fast' ]) end end class SMIsMemberCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) set = @db.lookup_set(@args.shift) members = @args if set.nil? result = Array.new(members.size, 0) else result = members.map do |member| set.member?(member) ? 1 : 0 end end RESPArray.new(result) end def self.describe Describe.new('smismember', -3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@set', '@fast' ]) end end class SMembersCommand < BaseCommand def call Utils.assert_args_length(1, @args) set = @db.lookup_set(@args[0]) RESPArray.new(set.members) end def self.describe Describe.new('smembers', 2, [ 'readonly', 'sort_for_script' ], 1, 1, 1, [ '@read', '@set', '@slow' ]) end end class SMoveCommand < BaseCommand def call Utils.assert_args_length(3, @args) source_key = @args[0] source = @db.lookup_set(source_key) member = @args[2] destination = @db.lookup_set_for_write(@args[1]) if source.nil? result = 0 else removed = @db.remove_from_set(source_key, source, member) if removed destination.add(member) result = 1 else result = 0 end end RESPInteger.new(result) end def self.describe Describe.new('smove', 4, [ 'write', 'fast' ], 1, 2, 1, [ '@write', '@set', '@fast' ]) end end class SPopCommand < BaseCommand def call Utils.assert_args_length_greater_than(0, @args) raise RESPSyntaxError if @args.length > 2 if @args[1] count = Utils.validate_integer(@args[1]) return RESPError.new('ERR index out of range') if count < 0 end key = @args[0] set = @db.lookup_set(key) if set popped_members = @db.generic_pop(key, set) do if count.nil? set.pop else set.pop_with_count(count) end end RESPSerializer.serialize(popped_members) elsif count.nil? NullBulkStringInstance else EmptyArrayInstance end end def self.describe Describe.new('spop', -2, [ 'write', 'random', 'fast' ], 1, 1, 1, [ '@write', '@set', '@fast' ]) end end class SRandMemberCommand < BaseCommand def call Utils.assert_args_length_greater_than(0, @args) raise RESPSyntaxError if @args.length > 2 count = Utils.validate_integer(@args[1]) if @args[1] set = @db.lookup_set(@args[0]) if set if count.nil? random_members = set.random_member else random_members = set.random_members_with_count(count) end RESPSerializer.serialize(random_members) elsif count.nil? NullBulkStringInstance else EmptyArrayInstance end end def self.describe Describe.new('srandmember', -2, [ 'readonly', 'random' ], 1, 1, 1, [ '@read', '@set', '@slow' ]) end end class SRemCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) key = @args.shift set = @db.lookup_set(key) remove_count = 0 if set @args.each do |member| remove_count += 1 if @db.remove_from_set(key, set, member) end end RESPInteger.new(remove_count) end def self.describe Describe.new('srem', -3, [ 'write', 'fast' ], 1, 1, 1, [ '@write', '@set', '@fast' ]) end end end <file_sep>/code/chapter-7/test/list_test.rb # coding: utf-8 require_relative './test_helper' describe 'BYORedis - List commands' do describe 'LRANGE' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'LRANGE a', '-ERR wrong number of arguments for \'LRANGE\' command' ], [ 'LRANGE a b', '-ERR wrong number of arguments for \'LRANGE\' command' ], [ 'LRANGE a b c d', '-ERR wrong number of arguments for \'LRANGE\' command' ], ] end it 'fails if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'LRANGE not-a-list 0 -1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'fails it start & stop are not integers' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LRANGE a not-a-number not-a-number', '-ERR value is not an integer or out of range' ], [ 'LRANGE a 0 not-a-number', '-ERR value is not an integer or out of range' ], [ 'LRANGE a not-a-number -1', '-ERR value is not an integer or out of range' ], ] end it 'returns the whole list with 0 -1' do assert_command_results [ [ 'LPUSH a g f e d c b', ':6' ], [ 'LRANGE a 0 -1', [ 'b', 'c', 'd', 'e', 'f', 'g' ] ], ] end it 'handles negative indexes as starting from the right side' do assert_command_results [ [ 'LPUSH a d c b', ':3' ], [ 'LRANGE a -3 2', [ 'b', 'c', 'd' ] ], [ 'LRANGE a -2 1', [ 'c' ] ], [ 'LRANGE a -2 2', [ 'c', 'd' ] ], [ 'LRANGE a -1 2', [ 'd' ] ], ] end it 'works with out of bounds indices' do assert_command_results [ [ 'LPUSH a b c d', ':3' ], [ 'LRANGE a 2 22', [ 'b' ] ], ] assert_command_results [ [ 'LPUSH a b c d', ':3' ], [ 'LRANGE a -6 0', [ 'd' ] ], ] end it 'returns an empty array for out of order boundaries' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LRANGE a 2 1', [] ], [ 'LRANGE a -1 -2', [] ], ] end it 'returns sublists' do assert_command_results [ [ 'LPUSH a f e d c b', ':5' ], [ 'LRANGE a 1 1', [ 'c' ] ], [ 'LRANGE a 1 3', [ 'c', 'd', 'e' ] ], [ 'LRANGE a 3 4', [ 'e', 'f' ] ], [ 'LRANGE a 3 100', [ 'e', 'f' ] ], ] end end describe 'LPUSH' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'LPUSH a', '-ERR wrong number of arguments for \'LPUSH\' command' ], ] end it 'fails if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'LPUSH not-a-list a', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'creates a list for a non existing key' do assert_command_results [ [ 'LPUSH a b', ':1' ], ] end it 'returns the number of elements in the list after insert' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LPUSH a c', ':2' ], [ 'LPUSH a d', ':3' ], ] end it 'handles multiple keys' do assert_command_results [ [ 'LPUSH a b c d e', ':4' ], [ 'LPUSH a f g', ':6' ], ] end end describe 'LPUSHX' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'LPUSHX', '-ERR wrong number of arguments for \'LPUSHX\' command' ], [ 'LPUSHX a', '-ERR wrong number of arguments for \'LPUSHX\' command' ], ] end it 'fails if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'LPUSHX not-a-list a', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'does nothing a non existing key' do assert_command_results [ [ 'LPUSHX a b', ':0' ], ] end it 'returns the number of elements in the list after insert' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LPUSHX a b', ':2' ], [ 'LPUSHX a c', ':3' ], [ 'LPUSHX a d', ':4' ], ] end it 'handles multiple keys' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LPUSHX a c d e', ':4' ], [ 'LPUSHX a f g', ':6' ], ] end end describe 'RPUSH' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'RPUSH a', '-ERR wrong number of arguments for \'RPUSH\' command' ], ] end it 'fails if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'RPUSH not-a-list a', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'creates a list for a non existing key' do assert_command_results [ [ 'RPUSH a b', ':1' ], ] end it 'returns the number of elements in the list after insert' do assert_command_results [ [ 'RPUSH a b', ':1' ], [ 'RPUSH a c', ':2' ], [ 'RPUSH a d', ':3' ], [ 'LRANGE a 0 -1', [ 'b', 'c', 'd' ] ], ] end it 'handles multiple keys' do assert_command_results [ [ 'RPUSH a b c d e', ':4' ], [ 'LRANGE a 0 -1', [ 'b', 'c', 'd', 'e' ] ], [ 'RPUSH a f g', ':6' ], [ 'LRANGE a 0 -1', [ 'b', 'c', 'd', 'e', 'f', 'g' ] ], ] end end describe 'RPUSHX' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'RPUSHX', '-ERR wrong number of arguments for \'RPUSHX\' command' ], [ 'RPUSHX a', '-ERR wrong number of arguments for \'RPUSHX\' command' ], ] end it 'fails if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'RPUSHX not-a-list a', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'does nothing a non existing key' do assert_command_results [ [ 'RPUSHX a b', ':0' ], ] end it 'returns the number of elements in the list after insert' do assert_command_results [ [ 'RPUSH a b', ':1' ], [ 'RPUSHX a b', ':2' ], [ 'RPUSHX a c', ':3' ], [ 'RPUSHX a d', ':4' ], [ 'LRANGE a 0 -1', [ 'b', 'b', 'c', 'd' ] ], ] end it 'handles multiple keys' do assert_command_results [ [ 'RPUSH a b', ':1' ], [ 'RPUSHX a c d e', ':4' ], [ 'LRANGE a 0 -1', [ 'b', 'c', 'd', 'e' ] ], [ 'RPUSHX a f g', ':6' ], [ 'LRANGE a 0 -1', [ 'b', 'c', 'd', 'e', 'f', 'g' ] ], ] end end describe 'LLEN' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'LLEN', '-ERR wrong number of arguments for \'LLEN\' command' ], [ 'LLEN a b', '-ERR wrong number of arguments for \'LLEN\' command' ], ] end it 'returns an error if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'LLEN not-a-list', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns 0 for non existing keys' do assert_command_results [ [ 'LLEN not-a-thing', ':0' ], ] end it 'returns the size of the list' do assert_command_results [ [ 'LPUSH a b c d', ':3' ], [ 'LLEN a', ':3' ], ] end end describe 'LPOP' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'LPOP', '-ERR wrong number of arguments for \'LPOP\' command' ], [ 'LPOP a b', '-ERR wrong number of arguments for \'LPOP\' command' ], ] end it 'returns an error if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'LPOP not-a-list', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns nil for non existing keys' do assert_command_results [ [ 'LPOP not-a-thing', BYORedis::NULL_BULK_STRING ], ] end it 'returns the head of list and removes it from the list' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LPOP a', 'b' ], [ 'LLEN a', ':0' ], [ 'LPUSH a c b', ':2' ], [ 'LPOP a', 'b' ], [ 'LLEN a', ':1' ], [ 'LPUSH a b 1 2 3', ':5' ], [ 'LPOP a', '3' ], [ 'LRANGE a 0 -1', [ '2', '1', 'b', 'c' ] ], ] end it 'deletes the key/value pair after popping the last element' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'TYPE a', '+list' ], [ 'LPOP a', 'b' ], [ 'TYPE a', '+none' ], ] end end describe 'RPOP' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'RPOP', '-ERR wrong number of arguments for \'RPOP\' command' ], [ 'RPOP a b', '-ERR wrong number of arguments for \'RPOP\' command' ], ] end it 'returns an error if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'RPOP not-a-list', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns nil for non existing keys' do assert_command_results [ [ 'RPOP not-a-thing', BYORedis::NULL_BULK_STRING ], ] end it 'returns the tail of list and removes it from the list' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'RPOP a', 'b' ], [ 'LLEN a', ':0' ], [ 'LPUSH a c b', ':2' ], [ 'RPOP a', 'c' ], [ 'LLEN a', ':1' ], [ 'LPUSH a b 1 2 3', ':5' ], [ 'RPOP a', 'b' ], [ 'LRANGE a 0 -1', [ '3', '2', '1', 'b' ] ], ] end it 'deletes the key/value pair after popping the last element' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'TYPE a', '+list' ], [ 'RPOP a', 'b' ], [ 'TYPE a', '+none' ], ] end end describe 'RPOPLPUSH' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'RPOPLPUSH', '-ERR wrong number of arguments for \'RPOPLPUSH\' command' ], [ 'RPOPLPUSH a', '-ERR wrong number of arguments for \'RPOPLPUSH\' command' ], [ 'RPOPLPUSH a b c', '-ERR wrong number of arguments for \'RPOPLPUSH\' command' ], ] end it 'returns an error if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'RPOPLPUSH not-a-list not-a-list', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns nil for non existing keys' do assert_command_results [ [ 'RPOPLPUSH not-a-thing not-a-thing', BYORedis::NULL_BULK_STRING ], ] end it 'works with the same list, it rotates it' do assert_command_results [ [ 'LPUSH source c b a', ':3' ], [ 'LRANGE source 0 -1', [ 'a', 'b', 'c' ] ], [ 'RPOPLPUSH source source', 'c' ], [ 'LRANGE source 0 -1', [ 'c', 'a', 'b' ] ], ] # Also works with a single element assert_command_results [ [ 'LPUSH source a', ':1' ], [ 'LRANGE source 0 -1', [ 'a' ] ], [ 'RPOPLPUSH source source', 'a' ], [ 'LRANGE source 0 -1', [ 'a' ] ], ] end it 'creates the destination list if it does not exist' do assert_command_results [ [ 'LPUSH source a', ':1' ], [ 'RPOPLPUSH source destination', 'a' ], [ 'LRANGE source 0 -1', [] ], [ 'LRANGE destination 0 -1', [ 'a' ] ], ] end it 'returns the tail of the source and pushes it to the head of the destination' do assert_command_results [ [ 'RPUSH source a b c', ':3' ], [ 'RPUSH destination 1 2 3', ':3' ], [ 'RPOPLPUSH source destination', 'c' ], [ 'LRANGE source 0 -1', [ 'a', 'b' ] ], [ 'LRANGE destination 0 -1', [ 'c', '1', '2', '3' ] ], [ 'RPOPLPUSH source destination', 'b' ], [ 'LRANGE source 0 -1', [ 'a' ] ], [ 'LRANGE destination 0 -1', [ 'b', 'c', '1', '2', '3' ] ], ] end end describe 'LTRIM' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'LTRIM', '-ERR wrong number of arguments for \'LTRIM\' command' ], [ 'LTRIM a', '-ERR wrong number of arguments for \'LTRIM\' command' ], [ 'LTRIM a b', '-ERR wrong number of arguments for \'LTRIM\' command' ], [ 'LTRIM a b c d', '-ERR wrong number of arguments for \'LTRIM\' command' ], ] end it 'fails if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'LTRIM not-a-list 0 -1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'fails it start & stop are not integers' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LTRIM a not-a-number not-a-number', '-ERR value is not an integer or out of range' ], [ 'LTRIM a 0 not-a-number', '-ERR value is not an integer or out of range' ], [ 'LTRIM a not-a-number -1', '-ERR value is not an integer or out of range' ], ] end it 'does nothing with 0 -1' do assert_command_results [ [ 'LPUSH a g f e d c b', ':6' ], [ 'LTRIM a 0 -1', '+OK' ], [ 'LRANGE a 0 -1', [ 'b', 'c', 'd', 'e', 'f', 'g' ] ], ] end it 'handles negative indexes as starting from the right side for start' do assert_command_results [ [ 'LPUSH a d c b', ':3' ], [ 'LTRIM a -3 2', '+OK' ], [ 'LRANGE a 0 -1', [ 'b', 'c', 'd' ] ], ] end it 'handles negative indexes as starting from the right side for end' do assert_command_results [ [ 'LPUSH a d c b', ':3' ], [ 'LTRIM a -1 2', '+OK' ], [ 'LRANGE a 0 -1', [ 'd' ] ], ] end it 'works with out of bounds indices' do assert_command_results [ [ 'RPUSH a b c d', ':3' ], [ 'LTRIM a 2 22', '+OK' ], [ 'LRANGE a 0 -1', [ 'd' ] ] ] end it 'deletes the list for out of order boundaries' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LTRIM a 2 1', '+OK' ], [ 'TYPE a', '+none' ], [ 'LPUSH a b', ':1' ], [ 'LTRIM a -1 -2', '+OK' ], [ 'TYPE a', '+none' ], ] end it 'only keeps the sublist indicated by the range' do assert_command_results [ [ 'RPUSH a b c d e f', ':5' ], [ 'LTRIM a 1 1', '+OK' ], [ 'LRANGE a 0 -1', [ 'c' ] ], ] assert_command_results [ [ 'RPUSH a b c d e f', ':5' ], [ 'LTRIM a 1 3', '+OK' ], [ 'LRANGE a 0 -1', [ 'c', 'd', 'e' ] ], ] assert_command_results [ [ 'RPUSH a b c d e f', ':5' ], [ 'LTRIM a 3 4', '+OK' ], [ 'LRANGE a 0 -1', [ 'e', 'f' ] ], ] assert_command_results [ [ 'RPUSH a b c d e f', ':5' ], [ 'LTRIM a 3 100', '+OK' ], [ 'LRANGE a 0 -1', [ 'e', 'f' ] ], ] end end describe 'LSET' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'LSET', '-ERR wrong number of arguments for \'LSET\' command' ], [ 'LSET a', '-ERR wrong number of arguments for \'LSET\' command' ], [ 'LSET a b', '-ERR wrong number of arguments for \'LSET\' command' ], [ 'LSET a b c d', '-ERR wrong number of arguments for \'LSET\' command' ], ] end it 'returns an error if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'LSET not-a-list 0 new-value', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns and error if index is not an integer' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LSET a not-a-number new-value', '-ERR value is not an integer or out of range' ], ] end it 'returns an error for non existing keys' do assert_command_results [ [ 'LSET not-a-thing 0 new-value', '-ERR no such key' ], ] end it 'replaces the element at the given index' do assert_command_results [ [ 'RPUSH a b c d', ':3' ], [ 'LSET a 1 new-value', '+OK' ], [ 'LRANGE a 0 -1', [ 'b', 'new-value', 'd' ] ], ] end it 'replaces the element at the given starting from the end with a negative index' do assert_command_results [ [ 'RPUSH a b c d', ':3' ], [ 'LSET a -1 new-value', '+OK' ], [ 'LSET a -2 another-new-value', '+OK' ], [ 'LRANGE a 0 -1', [ 'b', 'another-new-value', 'new-value' ] ], ] end it 'returns an error for out of range indexes' do assert_command_results [ [ 'RPUSH a b c d', ':3' ], [ 'LSET a 3 new-value', '-ERR index out of range' ], [ 'LSET a 4 new-value', '-ERR index out of range' ], [ 'LSET a -4 new-value', '-ERR index out of range' ], [ 'LSET a -5 new-value', '-ERR index out of range' ], ] end end describe 'LREM' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'LREM', '-ERR wrong number of arguments for \'LREM\' command' ], [ 'LREM a', '-ERR wrong number of arguments for \'LREM\' command' ], [ 'LREM a b', '-ERR wrong number of arguments for \'LREM\' command' ], [ 'LREM a b c d', '-ERR wrong number of arguments for \'LREM\' command' ], ] end it 'returns an error if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'LREM not-a-list 0 new-value', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns and error if index is not an integer' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LREM a not-a-number b', '-ERR value is not an integer or out of range' ], ] end it 'returns 0 if no nodes are equal to element' do assert_command_results [ [ 'RPUSH a b c d', ':3' ], [ 'LREM a 0 e', ':0' ], ] end it 'returns 0 for non existing keys' do assert_command_results [ [ 'LREM not-a-thing 0 new-value', ':0' ], ] end it 'removes the first n nodes equal to element from the end with a positive index' do assert_command_results [ [ 'RPUSH a b c d b e f b g h', ':9' ], [ 'LREM a 2 b', ':2' ], [ 'LRANGE a 0 -1', [ 'c', 'd', 'e', 'f', 'b', 'g', 'h' ] ], [ 'LREM a 2 b', ':1' ], [ 'LRANGE a 0 -1', [ 'c', 'd', 'e', 'f', 'g', 'h' ] ], ] end it 'removes the first n nodes equal to element from the end with a negative index' do assert_command_results [ [ 'RPUSH a b c d b e f b g h', ':9' ], [ 'LREM a -2 b', ':2' ], [ 'LRANGE a 0 -1', [ 'b', 'c', 'd', 'e', 'f', 'g', 'h' ] ], [ 'LREM a 2 b', ':1' ], [ 'LRANGE a 0 -1', [ 'c', 'd', 'e', 'f', 'g', 'h' ] ], ] end it 'removes all elements if count is 0' do assert_command_results [ [ 'RPUSH a b c d b e f b g h', ':9' ], [ 'LREM a 0 b', ':3' ], [ 'LRANGE a 0 -1', [ 'c', 'd', 'e', 'f', 'g', 'h' ] ], [ 'LREM a 0 b', ':0' ], [ 'LRANGE a 0 -1', [ 'c', 'd', 'e', 'f', 'g', 'h' ] ], ] end end describe 'LPOS' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'LPOS', '-ERR wrong number of arguments for \'LPOS\' command' ], [ 'LPOS a', '-ERR wrong number of arguments for \'LPOS\' command' ], [ 'LPOS a b c', '-ERR syntax error' ], [ 'LPOS a b RANK', '-ERR syntax error' ], [ 'LPOS a b RANK 1 COUNT', '-ERR syntax error' ], [ 'LPOS a b COUNT 1 RANK', '-ERR syntax error' ], [ 'LPOS a b MAXLEN 1 COUNT', '-ERR syntax error' ], [ 'LPOS a b COUNT 1 MAXLEN', '-ERR syntax error' ], ] end it 'returns nil if the key does not exist' do assert_command_results [ [ 'LPOS not-a-thing 0', BYORedis::NULL_BULK_STRING ], ] end it 'returns an error if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'LPOS not-a-list 0', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns and error if count is not an integer' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LPOS a b COUNT not-a-number', '-ERR value is not an integer or out of range' ], ] end it 'returns and error if rank is not an integer' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LPOS a b RANK not-a-number', '-ERR value is not an integer or out of range' ], ] end it 'returns and error if maxlen is not an integer' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LPOS a b MAXLEN not-a-number', '-ERR value is not an integer or out of range' ], ] end it 'returns the 0-index position of the element in the list' do assert_command_results [ [ 'RPUSH a b c d', ':3' ], [ 'LPOS a c', ':1' ], ] end it 'returns nil if the element is not in the list' do assert_command_results [ [ 'RPUSH a b c d', ':3' ], [ 'LPOS a e', BYORedis::NULL_BULK_STRING ], ] end it 'returns the position of the nth element with the RANK option' do assert_command_results [ [ 'RPUSH a b c b d', ':4' ], [ 'LPOS a b RANK 1', ':0' ], [ 'LPOS a b RANK 2', ':2' ], [ 'LPOS a b RANK 3', BYORedis::NULL_BULK_STRING ], ] end it 'returns the position of the nth element from the right with a negative RANK option' do assert_command_results [ [ 'RPUSH a b c b d', ':4' ], [ 'LPOS a b RANK -1', ':2' ], [ 'LPOS a b RANK -2', ':0' ], [ 'LPOS a b RANK -3', BYORedis::NULL_BULK_STRING ], ] end it 'returns an error with a rank of 0' do assert_command_results [ [ 'RPUSH a b c b d', ':4' ], [ 'LPOS a b RANK 0', '-ERR RANK can\'t be zero: use 1 to start from the first match, 2 from the second, ...' ], ] end it 'returns an error with a negative count' do assert_command_results [ [ 'RPUSH a b c b d', ':4' ], [ 'LPOS a b COUNT -1', '-ERR COUNT can\'t be negative' ], ] end it 'returns an error with a negative maxlen' do assert_command_results [ [ 'RPUSH a b c b d', ':4' ], [ 'LPOS a b MAXLEN -1', '-ERR MAXLEN can\'t be negative' ], ] end it 'returns an array on indexes for the first n matches with the count option' do assert_command_results [ [ 'RPUSH a b c b d', ':4' ], [ 'LPOS a b COUNT 1', "*1\r\n:0\r\n" ], [ 'LPOS a b COUNT 2', "*2\r\n:0\r\n:2\r\n" ], [ 'LPOS a b COUNT 3', "*2\r\n:0\r\n:2\r\n" ], ] end it 'returns an array on indexes for all the matches with 0 as the count option' do assert_command_results [ [ 'RPUSH a b c b d', ':4' ], [ 'LPOS a b COUNT 0', "*2\r\n:0\r\n:2\r\n" ], ] end it 'returns the first n elements after the rank with both count and rank' do assert_command_results [ [ 'RPUSH a b c b d b', ':5' ], [ 'LPOS a b COUNT 1 RANK 1', "*1\r\n:0\r\n" ], [ 'LPOS a b COUNT 2 RANK 1', "*2\r\n:0\r\n:2\r\n" ], [ 'LPOS a b COUNT 3 RANK 1', "*3\r\n:0\r\n:2\r\n:4\r\n" ], [ 'LPOS a b COUNT 4 RANK 1', "*3\r\n:0\r\n:2\r\n:4\r\n" ], [ 'LPOS a b COUNT 1 RANK 2', "*1\r\n:2\r\n" ], [ 'LPOS a b COUNT 2 RANK 2', "*2\r\n:2\r\n:4\r\n" ], [ 'LPOS a b COUNT 3 RANK 2', "*2\r\n:2\r\n:4\r\n" ], [ 'LPOS a b COUNT 1 RANK 3', "*1\r\n:4\r\n" ], [ 'LPOS a b COUNT 2 RANK 3', "*1\r\n:4\r\n" ], [ 'LPOS a b COUNT 1 RANK 4', "*0\r\n" ], ] end it 'returns an array on indexes for the last n matches with the count option and a negative RANK' do assert_command_results [ [ 'RPUSH a b c b d b', ':5' ], [ 'LPOS a b COUNT 1 RANK -1', "*1\r\n:4\r\n" ], [ 'LPOS a b COUNT 2 RANK -1', "*2\r\n:4\r\n:2\r\n" ], [ 'LPOS a b COUNT 3 RANK -1', "*3\r\n:4\r\n:2\r\n:0\r\n" ], [ 'LPOS a b COUNT 4 RANK -1', "*3\r\n:4\r\n:2\r\n:0\r\n" ], [ 'LPOS a b COUNT 1 RANK -2', "*1\r\n:2" ], [ 'LPOS a b COUNT 2 RANK -2', "*2\r\n:2\r\n:0" ], [ 'LPOS a b COUNT 3 RANK -2', "*2\r\n:2\r\n:0" ], [ 'LPOS a b COUNT 1 RANK -3', "*1\r\n:0" ], [ 'LPOS a b COUNT 2 RANK -3', "*1\r\n:0" ], [ 'LPOS a b COUNT 1 RANK -4', "*0\r\n" ], ] end it 'returns an empty array when count is specified and not matches are found' do assert_command_results [ [ 'RPUSH a b c b d', ':4' ], [ 'LPOS a e COUNT 0', [] ], ] end it 'only scans n element with the MAXLEN option' do assert_command_results [ [ 'RPUSH a b c b d b', ':5' ], [ 'LPOS a b MAXLEN 3 COUNT 3', "*2\r\n:0\r\n:2\r\n" ], [ 'LPOS a b MAXLEN 2 COUNT 3', "*1\r\n:0\r\n" ], ] end it 'only scans n element starting from the end with the MAXLEN option and a negative rank' do assert_command_results [ [ 'RPUSH a b c b d b', ':5' ], [ 'LPOS a b MAXLEN 5 COUNT 3 RANK -1', "*3\r\n:4\r\n:2\r\n:0\r\n" ], [ 'LPOS a b MAXLEN 4 COUNT 3 RANK -1', "*2\r\n:4\r\n:2\r\n" ], [ 'LPOS a b MAXLEN 3 COUNT 3 RANK -1', "*2\r\n:4\r\n:2\r\n" ], [ 'LPOS a b MAXLEN 2 COUNT 3 RANK -1', "*1\r\n:4\r\n" ], [ 'LPOS a b MAXLEN 1 COUNT 3 RANK -1', "*1\r\n:4\r\n" ], ] end end describe 'LINSERT' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'LINSERT', '-ERR wrong number of arguments for \'LINSERT\' command' ], [ 'LINSERT a', '-ERR wrong number of arguments for \'LINSERT\' command' ], [ 'LINSERT a b', '-ERR wrong number of arguments for \'LINSERT\' command' ], [ 'LINSERT a b c', '-ERR wrong number of arguments for \'LINSERT\' command' ], [ 'LINSERT a b c d', '-ERR syntax error' ], [ 'LINSERT a b c d e', '-ERR wrong number of arguments for \'LINSERT\' command' ], [ 'LINSERT a before c d e', '-ERR wrong number of arguments for \'LINSERT\' command' ], [ 'LINSERT a after c d e', '-ERR wrong number of arguments for \'LINSERT\' command' ], ] end it 'returns 0 if the key does not exist' do assert_command_results [ [ 'LINSERT not-a-thing BEFORE 0 a', ':0' ], [ 'LINSERT not-a-thing AFTER 0 a', ':0' ], ] end it 'returns an error if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'LINSERT not-a-list BEFORE a a', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], [ 'LINSERT not-a-list AFTER a a', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'inserts the new element before the pivot with BEFORE and returns the new size' do assert_command_results [ [ 'RPUSH a b c d', ':3' ], [ 'LINSERT a BEFORE c new-element', ':4' ], [ 'LRANGE a 0 -1', [ 'b', 'new-element', 'c', 'd' ] ], [ 'LINSERT a BEFORE b new-head', ':5' ], [ 'LRANGE a 0 -1', [ 'new-head', 'b', 'new-element', 'c', 'd' ] ], ] end it 'inserts the new element after the pivot with AFTER and returns the new size' do assert_command_results [ [ 'RPUSH a b c d', ':3' ], [ 'LINSERT a AFTER c new-element', ':4' ], [ 'LRANGE a 0 -1', [ 'b', 'c', 'new-element', 'd' ] ], [ 'LINSERT a AFTER d new-tail', ':5' ], [ 'LRANGE a 0 -1', [ 'b', 'c', 'new-element', 'd', 'new-tail' ] ], ] end it 'returns -1 if the pivot is not found' do assert_command_results [ [ 'RPUSH a b c d', ':3' ], [ 'LINSERT a BEFORE e new-element', ':-1' ], [ 'LRANGE a 0 -1', [ 'b', 'c', 'd' ] ], [ 'LINSERT a AFTER e new-element', ':-1' ], [ 'LRANGE a 0 -1', [ 'b', 'c', 'd' ] ], ] end end describe 'LINDEX' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'LINDEX', '-ERR wrong number of arguments for \'LINDEX\' command' ], [ 'LINDEX a', '-ERR wrong number of arguments for \'LINDEX\' command' ], [ 'LINDEX a b c', '-ERR wrong number of arguments for \'LINDEX\' command' ], ] end it 'returns nil if the key does not exist' do assert_command_results [ [ 'LINDEX not-a-thing 0', BYORedis::NULL_BULK_STRING ], ] end it 'returns an error if index is not an integer' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LINDEX a b', '-ERR value is not an integer or out of range' ], [ 'LINDEX a 1.0', '-ERR value is not an integer or out of range' ], ] end it 'returns nil if the index is out of range' do assert_command_results [ [ 'LPUSH a b', ':1' ], [ 'LINDEX a 1', BYORedis::NULL_BULK_STRING ], [ 'LINDEX a -2', BYORedis::NULL_BULK_STRING ], ] end it 'returns an error if the key is not a list' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'LINDEX not-a-list 0', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns the value at the given index' do assert_command_results [ [ 'RPUSH a b c d', ':3' ], [ 'LINDEX a 0', 'b' ], [ 'LINDEX a 1', 'c' ], [ 'LINDEX a 2', 'd' ], ] end it 'handles negative indexes' do assert_command_results [ [ 'RPUSH a b c d', ':3' ], [ 'LINDEX a -1', 'd' ], [ 'LINDEX a -2', 'c' ], [ 'LINDEX a -3', 'b' ], ] end end describe 'BLPOP' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'BLPOP', '-ERR wrong number of arguments for \'BLPOP\' command' ], [ 'BLPOP a', '-ERR wrong number of arguments for \'BLPOP\' command' ], ] end it 'returns an error if the last argument is not an integer or a float' do assert_command_results [ [ 'BLPOP a b', '-ERR timeout is not a float or out of range' ], [ 'BLPOP a 1.b', '-ERR timeout is not a float or out of range' ], ] end it 'returns an error if the first non nil value is not a key' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'BLPOP a b not-a-list 1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns the popped element of the first non empty list and its name' do assert_command_results [ [ 'RPUSH a a1 a2 a3', ':3' ], [ 'BLPOP a 1', [ 'a', 'a1' ] ], [ 'LRANGE a 0 -1', [ 'a2', 'a3' ] ], [ 'RPUSH b b1 b2 b3', ':3' ], [ 'BLPOP b a 1', [ 'b', 'b1' ] ], [ 'BLPOP a b 1', [ 'a', 'a2' ] ], [ 'LRANGE a 0 -1', [ 'a3' ] ], [ 'LRANGE b 0 -1', [ 'b2', 'b3' ] ], ] end it 'handles the case where the blocked client disconnects before the end of the timeout' do with_server do |socket| socket.write to_query('BLPOP', 'a', '0.2') socket.close sleep 0.2 # Check that the server is still here! socket = TCPSocket.new 'localhost', 2000 socket.write to_query('GET', 'a') response = read_response(socket, read_timeout: 0.2) assert_equal("$-1\r\n", response) end end it 'does nothing when the blocked client disconnects before one of lists it was blocked receives an element' do with_server do |socket| socket.write to_query('BLPOP', 'a', '0.2') socket.close sleep 0.01 # Sleep long enough to give time to the server to handle the disconnect socket2 = TCPSocket.new 'localhost', 2000 socket2.write to_query('RPUSH', 'a', 'a1', 'a2') response = read_response(socket2, read_timeout: 0.2) assert_equal(":2\r\n", response) socket2.write to_query('LPOP', 'a') response = read_response(socket2, read_timeout: 0.2) # Checking that a1 was not popped since the client that asked for it disconnected assert_equal("$2\r\na1\r\n", response) end end it 'blocks up to timeout seconds and returns nil if all list are empty' do with_server do |server_socket| start_time = Time.now server_socket.write to_query('BLPOP', 'a', '0.1') response = read_response(server_socket, read_timeout: 0.2) duration = Time.now - start_time assert_equal("*-1\r\n", response) assert_operator(duration, :>=, 0.1) end end it 'clears the blocked states after a timeout' do with_server do |server_socket| start_time = Time.now server_socket.write to_query('BLPOP', 'a', '0.1') response = read_response(server_socket, read_timeout: 0.2) duration = Time.now - start_time assert_equal("*-1\r\n", response) server_socket.write to_query('LPUSH', 'a', 'a1') response2 = read_response(server_socket) assert_equal(":1\r\n", response2) assert_operator(duration, :>=, 0.1) end end it 'blocks indefinitely with a timeout of 0' do assert_infinite_timeout(blocking_command: 'BLPOP', list_names: [ 'a', 'b' ]) end it 'blocks and returns if the first list receives elements during the timeout' do assert_blocking_behavior(blocking_command: 'BLPOP', list_names: [ 'a', 'b' ], timeout: 0.5, push_commands: [ 'RPUSH a a1' ], expected_response: "*2\r\n$1\r\na\r\n$2\r\na1\r\n", pushed_to_list_name: 'a') end it 'blocks and returns if the second list receives elements during the timeout' do assert_blocking_behavior(blocking_command: 'BLPOP', list_names: [ 'a', 'b' ], timeout: 0.5, push_commands: [ 'RPUSH b b1' ], expected_response: "*2\r\n$1\r\nb\r\n$2\r\nb1\r\n", pushed_to_list_name: 'b') end it 'accumulates commands while blocked' do assert_command_accumulation(blocking_command: 'BLPOP a b 0.6', expected_response: "*-1\r\n+OK\r\n$1\r\nb\r\n") end it 'handles back to back blocking commands with buffering' do assert_back_to_back_blocking_commands_before_timeout( blocking_command: 'BLPOP', expected_response1: "*2\r\n$1\r\na\r\n$2\r\na1\r\n", expected_response2: "*2\r\n$1\r\na\r\n$2\r\na2\r\n" ) end it 'handles back to back blocking commands after a timeout' do assert_back_to_back_blocking_commands_after_timeout( blocking_command: 'BLPOP' ) end it 'processes buffered commands after being unblocked' do # Three responses: [ a, a1 ], +OK & 1 assert_buffer_commands_processing( blocking_command: 'BLPOP', expected_response: "*2\r\n$1\r\na\r\n$2\r\na1\r\n+OK\r\n$1\r\n1\r\n" ) end it 'can unblock as many clients as possible' do assert_multiple_clients_unblocked(blocking_command: 'BLPOP', expected_results: [ "*2\r\n$1\r\na\r\n$2\r\na1\r\n", "*2\r\n$1\r\na\r\n$2\r\na2\r\n", "*2\r\n$1\r\na\r\n$2\r\na3\r\n", ]) end end describe 'BRPOP' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'BRPOP', '-ERR wrong number of arguments for \'BRPOP\' command' ], [ 'BRPOP a', '-ERR wrong number of arguments for \'BRPOP\' command' ], ] end it 'returns an error if the last argument is not an integer or a float' do assert_command_results [ [ 'BRPOP a b', '-ERR timeout is not a float or out of range' ], [ 'BRPOP a 1.b', '-ERR timeout is not a float or out of range' ], ] end it 'returns an error if the first non nil value is not a key' do assert_command_results [ [ 'SET not-a-list 1', '+OK' ], [ 'BRPOP a b not-a-list 1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns the popped element of the first non empty list and its name' do assert_command_results [ [ 'RPUSH a a1 a2 a3', ':3' ], [ 'BRPOP a 1', [ 'a', 'a3' ] ], [ 'LRANGE a 0 -1', [ 'a1', 'a2' ] ], [ 'RPUSH b b1 b2 b3', ':3' ], [ 'BRPOP b a 1', [ 'b', 'b3' ] ], [ 'BRPOP a b 1', [ 'a', 'a2' ] ], [ 'LRANGE a 0 -1', [ 'a1' ] ], [ 'LRANGE b 0 -1', [ 'b1', 'b2' ] ], ] end it 'does nothing when the blocked client disconnects before one of lists it was blocked receives an element' do with_server do |socket| socket.write to_query('BRPOP', 'a', '0.2') socket.close sleep 0.01 # Sleep long enough to give time to the server to handle the disconnect socket2 = TCPSocket.new 'localhost', 2000 socket2.write to_query('RPUSH', 'a', 'a1', 'a2') response = read_response(socket2, read_timeout: 0.2) assert_equal(":2\r\n", response) socket2.write to_query('RPOP', 'a') response = read_response(socket2, read_timeout: 0.2) # Checking that a1 was not popped since the client that asked for it disconnected assert_equal("$2\r\na2\r\n", response) end end it 'blocks up to timeout seconds and returns nil if all list are empty' do with_server do |server_socket| start_time = Time.now server_socket.write to_query('BRPOP', 'a', '0.1') response = read_response(server_socket, read_timeout: 0.2) duration = Time.now - start_time assert_equal("*-1\r\n", response) assert_operator(duration, :>=, 0.1) end end it 'blocks indefinitely with a timeout of 0' do assert_infinite_timeout(blocking_command: 'BRPOP', list_names: [ 'a', 'b' ]) end it 'blocks and returns if the first list receives elements during the timeout' do assert_blocking_behavior(blocking_command: 'BRPOP', list_names: [ 'a', 'b' ], timeout: 0.5, push_commands: [ 'RPUSH a a1' ], expected_response: "*2\r\n$1\r\na\r\n$2\r\na1\r\n", pushed_to_list_name: 'a') end it 'blocks and returns if the second list receives elements during the timeout' do assert_blocking_behavior(blocking_command: 'BRPOP', list_names: [ 'a', 'b' ], timeout: 0.5, push_commands: [ 'RPUSH b b1' ], expected_response: "*2\r\n$1\r\nb\r\n$2\r\nb1\r\n", pushed_to_list_name: 'b') end it 'accumulates commands while blocked' do assert_command_accumulation(blocking_command: 'BRPOP a b 0.6', expected_response: "*-1\r\n+OK\r\n$1\r\nb\r\n") end it 'handles back to back blocking commands with buffering' do assert_back_to_back_blocking_commands_before_timeout( blocking_command: 'BRPOP', expected_response1: "*2\r\n$1\r\na\r\n$2\r\na1\r\n", expected_response2: "*2\r\n$1\r\na\r\n$2\r\na2\r\n" ) end it 'handles back to back blocking commands after a timeout' do assert_back_to_back_blocking_commands_after_timeout( blocking_command: 'BRPOP' ) end it 'can unblock as many clients as possible' do assert_multiple_clients_unblocked(blocking_command: 'BRPOP', expected_results: [ "*2\r\n$1\r\na\r\n$2\r\na3\r\n", "*2\r\n$1\r\na\r\n$2\r\na2\r\n", "*2\r\n$1\r\na\r\n$2\r\na1\r\n", ]) end it 'processes buffered commands after being unblocked' do # Three responses: [ a, a1 ], +OK & 1 assert_buffer_commands_processing( blocking_command: 'BRPOP', expected_response: "*2\r\n$1\r\na\r\n$2\r\na2\r\n+OK\r\n$1\r\n1\r\n" ) end end describe 'BRPOPLPUSH' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'BRPOPLPUSH', '-ERR wrong number of arguments for \'BRPOPLPUSH\' command' ], [ 'BRPOPLPUSH a b', '-ERR wrong number of arguments for \'BRPOPLPUSH\' command' ], [ 'BRPOPLPUSH a b c d', '-ERR wrong number of arguments for \'BRPOPLPUSH\' command' ], ] end it 'returns an error if the last argument is not an integer or a float' do assert_command_results [ [ 'BRPOPLPUSH a b foo', '-ERR timeout is not a float or out of range' ], [ 'BRPOPLPUSH a b 1.b', '-ERR timeout is not a float or out of range' ], ] end it 'blocks up to timeout seconds and returns nil if all list are empty' do with_server do |server_socket| start_time = Time.now server_socket.write to_query('BRPOPLPUSH', 'source', 'destination', '0.1') response = read_response(server_socket, read_timeout: 0.2) duration = Time.now - start_time assert_equal("*-1\r\n", response) assert_operator(duration, :>=, 0.1) end end it 'blocks and pops/pushes when source receives a push' do with_server do |socket| socket2 = TCPSocket.new 'localhost', 2000 Thread.new do # Wait enough for the first blocking command to be received sleep 0.02 socket2.write to_query('RPUSH', 'source', 'something', 'else') end socket.write to_query('BRPOPLPUSH', 'source', 'destination', '0.5') sleep 0.01 # Wait enough so that the server receives and processes the first command response = read_response(socket) assert_equal("$4\r\nelse\r\n", response) socket.write to_query('LRANGE', 'source', '0', '-1') response = read_response(socket) assert_equal("*1\r\n$9\r\nsomething\r\n", response) socket.write to_query('LRANGE', 'destination', '0', '-1') response = read_response(socket) assert_equal("*1\r\n$4\r\nelse\r\n", response) end end it 'blocks and pops/pushes when source receives a push' do with_server do |socket| socket2 = TCPSocket.new 'localhost', 2000 Thread.new do # Wait enough for the first blocking command to be received sleep 0.02 socket2.write to_query('RPUSH', 'a', 'a1') end socket.write to_query('BRPOPLPUSH', 'a', 'a', '0.5') sleep 0.01 # Wait enough so that the server receives and processes the first command response = read_response(socket) assert_equal("$2\r\na1\r\n", response) socket.write to_query('LRANGE', 'a', '0', '-1') response = read_response(socket) assert_equal("*1\r\n$2\r\na1\r\n", response) end end it 'blocks and returns if the source receives elements during the timeout' do assert_blocking_behavior(blocking_command: 'BRPOPLPUSH', list_names: [ 'source', 'destination' ], timeout: 0.5, push_commands: [ 'LPUSH source a1' ], expected_response: "$2\r\na1\r\n", pushed_to_list_name: 'source') assert_blocking_behavior(blocking_command: 'BRPOPLPUSH', list_names: [ 'source', 'destination' ], timeout: 0.5, push_commands: [ 'LPUSH another-list a1', 'RPOPLPUSH another-list source' ], expected_response: "$2\r\na1\r\n", pushed_to_list_name: 'source') assert_blocking_behavior(blocking_command: 'BRPOPLPUSH', list_names: [ 'source', 'destination' ], timeout: 0.5, push_commands: [ 'LPUSH another-list a1', 'BRPOPLPUSH another-list source 1' ], expected_response: "$2\r\na1\r\n", pushed_to_list_name: 'source') end it 'blocks indefinitely with a timeout of 0' do assert_infinite_timeout(blocking_command: 'BRPOPLPUSH', list_names: [ 'a', 'b' ]) end it 'handles back to back blocking commands with buffering' do assert_back_to_back_blocking_commands_before_timeout( blocking_command: 'BRPOPLPUSH', expected_response1: "$2\r\na1\r\n", expected_response2: "$2\r\na2\r\n" ) end it 'handles back to back blocking commands after a timeout' do assert_back_to_back_blocking_commands_after_timeout( blocking_command: 'BRPOPLPUSH' ) end it 'can unblock as many clients as possible' do assert_multiple_clients_unblocked(blocking_command: 'BRPOPLPUSH', expected_results: [ "$2\r\na3\r\n", "$2\r\na2\r\n", "$2\r\na1\r\n", ]) end it 'processes buffered commands after being unblocked' do # Three responses: a2, +OK & 1 assert_buffer_commands_processing( blocking_command: 'BRPOPLPUSH', expected_response: "$2\r\na2\r\n+OK\r\n$1\r\n1\r\n" ) end # TODO: These tests are the same RPOPLPUSH, use a shared helper it 'returns the tail of the source and pushes it to the head of the destination' do assert_command_results [ [ 'RPUSH source a b c', ':3' ], [ 'RPUSH destination 1 2 3', ':3' ], [ 'BRPOPLPUSH source destination 1', 'c' ], [ 'LRANGE source 0 -1', [ 'a', 'b' ] ], [ 'LRANGE destination 0 -1', [ 'c', '1', '2', '3' ] ], [ 'BRPOPLPUSH source destination 1', 'b' ], [ 'LRANGE source 0 -1', [ 'a' ] ], [ 'LRANGE destination 0 -1', [ 'b', 'c', '1', '2', '3' ] ], ] end it 'works with the same list, it rotates it' do assert_command_results [ [ 'LPUSH source c b a', ':3' ], [ 'LRANGE source 0 -1', [ 'a', 'b', 'c' ] ], [ 'BRPOPLPUSH source source 1', 'c' ], [ 'LRANGE source 0 -1', [ 'c', 'a', 'b' ] ], ] # Also works with a single element assert_command_results [ [ 'LPUSH source a', ':1' ], [ 'LRANGE source 0 -1', [ 'a' ] ], [ 'BRPOPLPUSH source source 1', 'a' ], [ 'LRANGE source 0 -1', [ 'a' ] ], ] end it 'creates the destination list if it does not exist' do assert_command_results [ [ 'LPUSH source a', ':1' ], [ 'BRPOPLPUSH source destination 1', 'a' ], [ 'LRANGE source 0 -1', [] ], [ 'LRANGE destination 0 -1', [ 'a' ] ], ] end end def assert_blocking_behavior(blocking_command:, list_names:, timeout:, push_commands:, expected_response:, pushed_to_list_name:) with_server do |socket1| socket2 = TCPSocket.new 'localhost', 2000 # Create a thread that will sleep for 200ms and push an element to the second list # the first client is blocked on, b Thread.new do sleep timeout / 2.5 # 200ms for a 500ms timeout push_commands.each do |push_command| socket2.write to_query(*push_command.split) end end start_time = Time.now full_blocking_command = [ blocking_command ] + list_names + [ timeout.to_s ] socket1.write to_query(*full_blocking_command) sleep timeout / 5 # 100ms for a 500ms timeout # First assert that we're still blocked after 100ms, there's nothing to read response1 = socket1.read_nonblock(1024, exception: false) assert_equal(:wait_readable, response1) response = read_response(socket1, read_timeout: timeout * 2) duration = Time.now - start_time assert_equal(expected_response, response) # Finally, we confirm that it took less than the BLPOP timeout to complete assert_operator(duration, :<=, timeout) # And a sanity check to kind of make sure that it lasted long enough to do _something_ assert_operator(duration, :>=, 0.1) # Once we checked everything, let's just check that the state of the server is fine # There were bugs where the server was not cleaning up empty lists and subsequent pops # would fail socket1.write to_query('BLPOP', pushed_to_list_name, '0.05') response2 = read_response(socket1, read_timeout: 0.1) assert_equal(BYORedis::NULL_ARRAY, response2) end end def assert_command_accumulation(blocking_command:, expected_response:) with_server do |socket| start_time = Time.now socket.write to_query(*blocking_command.split) # Nothing to read right after the write response1 = socket.read_nonblock(1024, exception: false) assert_equal(:wait_readable, response1) sleep 0.1 # Still nothing to read right after 100ms response2 = socket.read_nonblock(1024, exception: false) assert_equal(:wait_readable, response2) socket.write to_query('SET', 'a', 'b') # Nothing to read right after the write response3 = socket.read_nonblock(1024, exception: false) assert_equal(:wait_readable, response3) sleep 0.1 # Still nothing to read after 100ms response4 = socket.read_nonblock(1024, exception: false) assert_equal(:wait_readable, response4) socket.write to_query('GET', 'a') # Nothing to read right after the write response5 = socket.read_nonblock(1024, exception: false) assert_equal(:wait_readable, response5) sleep 0.1 # Still nothing to right after 100ms response6 = socket.read_nonblock(1024, exception: false) assert_equal(:wait_readable, response6) # Sleep 500ms to let the BLPOP timeout expire and give time to the server to serve # the pending commands sleep 0.5 final_response = socket.read_nonblock(1024, exception: false) duration = Time.now - start_time # Three responses: # - empty array, for BLPOP # - +OK for the SET a b command # - The string 'b' for the GET a command assert_equal(expected_response, final_response) # Sanity check on the time, greater than 800s since BLPOP waits for 600 and we give a # large buffer of 200ms for the server to server the other 2 assert_operator(duration, :<=, 0.9) assert_operator(duration, :>=, 0.8) end end def assert_back_to_back_blocking_commands_before_timeout(blocking_command:, expected_response1:, expected_response2:) with_server do |socket| socket2 = TCPSocket.new 'localhost', 2000 Thread.new do # Wait enough for the first blocking command to be received sleep 0.01 socket2.write to_query('RPUSH', 'a', 'a1') # Wait enough for the result of the first command to be received and read sleep 0.05 socket2.write to_query('RPUSH', 'a', 'a2') end socket.write to_query(blocking_command, 'a', 'b', '0.5') sleep 0.01 # Wait enough so that the server receives and processes the first command # before receiving the second one socket.write to_query(blocking_command, 'a', 'b', '0.5') sleep 0.01 response = read_response(socket) assert_equal(expected_response1, response) # Wait enough for the second RPUSH to be received sleep 0.05 response2 = read_response(socket) assert_equal(expected_response2, response2) end end def assert_back_to_back_blocking_commands_after_timeout(blocking_command:) with_server do |socket| socket.write to_query(blocking_command, 'a', 'b', '0.1') socket.write to_query(blocking_command, 'a', 'b', '0.1') sleep 0.15 response = read_response(socket) assert_equal("*-1\r\n", response) sleep 0.15 response2 = read_response(socket) assert_equal("*-1\r\n", response2) end end def assert_multiple_clients_unblocked(blocking_command:, expected_results:) with_server do |socket1| socket2 = TCPSocket.new 'localhost', 2000 socket3 = TCPSocket.new 'localhost', 2000 socket4 = TCPSocket.new 'localhost', 2000 socket1.write to_query(blocking_command, 'a', 'b', '0.1') sleep 0.01 socket2.write to_query(blocking_command, 'a', 'b', '0.1') sleep 0.01 socket3.write to_query(blocking_command, 'a', 'b', '0.1') socket4.write to_query('RPUSH', 'a', 'a1', 'a2', 'a3') response1 = read_response(socket1) assert_equal(expected_results[0], response1) response2 = read_response(socket2) assert_equal(expected_results[1], response2) response3 = read_response(socket3) assert_equal(expected_results[2], response3) end end def assert_buffer_commands_processing(blocking_command:, expected_response:) with_server do |socket1| socket2 = TCPSocket.new 'localhost', 2000 socket1.write to_query(blocking_command, 'a', 'b', '1') socket1.write to_query('SET', 'a', '1') socket1.write to_query('GET', 'a') socket2.write to_query('RPUSH', 'a', 'a1', 'a2') # Leave enough time to the server to write back all three responses sleep 0.1 response1 = socket1.read_nonblock(1024, exception: false) assert_equal(expected_response, response1) end end def assert_infinite_timeout(blocking_command:, list_names:) with_server do |socket| parts = [ blocking_command ] + list_names + [ '0' ] socket.write to_query(*parts) sleep 0.25 # 250 ms is long enough, no need to wait for ... you know, infinity response = read_response(socket) assert_nil(response) end end end <file_sep>/code/chapter-2/client.rb require 'socket' class BasicClient COMMANDS = [ "GET", "SET", ] def get(key) socket = TCPSocket.new 'localhost', 2000 result = nil socket.puts "GET #{ key }" result = socket.gets socket.close result end def set(key, value) socket = TCPSocket.new 'localhost', 2000 result = nil socket.puts "SET #{ key } #{ value }" result = socket.gets socket.close result end end <file_sep>/code/chapter-7/ttl_command.rb module BYORedis class TtlCommand < BaseCommand def call Utils.assert_args_length(1, @args) pttl_command = PttlCommand.new(@db, @args) result = pttl_command.execute_command.to_i if result > 0 RESPInteger.new((result / 1000.0).round) else RESPInteger.new(result) end end def self.describe Describe.new('ttl', 2, [ 'readonly', 'random', 'fast' ], 1, 1, 1, [ '@keyspace', '@read', '@fast' ]) end end end <file_sep>/code/chapter-8/dict.rb require_relative './siphash' require_relative './dict_entry' require_relative './hash_table' module BYORedis class Dict INITIAL_SIZE = 4 MAX_SIZE = 2**63 attr_reader :hash_tables def initialize @hash_tables = [ HashTable.new(0), HashTable.new(0) ] @rehashidx = -1 end def used main_table.used + rehashing_table.used end def empty? used == 0 end def rehash_milliseconds(millis) start = Time.now.to_f * 1000 rehashes = 0 while rehash(100) == 1 rehashes += 100 time_ellapsed = Time.now.to_f * 1000 - start break if time_ellapsed > millis end rehashes end def resize return if rehashing? minimal = main_table.used minimal = INITIAL_SIZE if minimal < INITIAL_SIZE expand(minimal) end def include?(key) !get_entry(key).nil? end # Dangerous method that can create duplicate if used incorrectly, should only be called if # get_entry was previously called and returned nil # Explain that calling add while rehashing can create a race condition def add(key, value) index = key_index(key) # Only happens if we didn't check the presence before calling this method return nil if index == -1 rehash_step if rehashing? hash_table = rehashing? ? rehashing_table : main_table entry = hash_table.table[index] entry = entry.next while entry && entry.key != key if entry.nil? entry = DictEntry.new(key, value) entry.next = hash_table.table[index] hash_table.table[index] = entry hash_table.used += 1 else raise "Unexpectedly found an entry with same key when trying to add #{ key } / #{ value }" end end def set(key, value) entry = get_entry(key) if entry entry.value = value false else add(key, value) true end end alias []= set def get_entry(key) return if main_table.used == 0 && rehashing_table.used == 0 rehash_step if rehashing? hash = SipHash.digest(RANDOM_BYTES, key) iterate_through_hash_tables_unless_rehashing do |hash_table| index = hash & hash_table.sizemask entry = hash_table.table[index] while entry return entry if entry.key == key entry = entry.next end end nil end def get(key) get_entry(key)&.value end alias [] get def delete(key) return if main_table.used == 0 && rehashing_table.used == 0 rehash_step if rehashing? hash_key = SipHash.digest(RANDOM_BYTES, key) iterate_through_hash_tables_unless_rehashing do |hash_table| index = hash_key & hash_table.sizemask entry = hash_table.table[index] previous_entry = nil while entry if entry.key == key if previous_entry previous_entry.next = entry.next else hash_table.table[index] = entry.next end hash_table.used -= 1 return entry.value end previous_entry = entry entry = entry.next end end nil end def each return if main_table.used == 0 && rehashing_table.used == 0 start_index = rehashing? ? @rehashidx : 0 main_table.table[start_index..-1].each do |bucket| next if bucket.nil? until bucket.nil? yield bucket.key, bucket.value bucket = bucket.next end end return unless rehashing? rehashing_table.each do |bucket| next if bucket.nil? until bucket.nil? yield bucket.key, bucket.value bucket = bucket.next end end end def keys keys = [] each do |key, _| keys << key end keys end def values values = [] each do |_, value| values << value end values end def needs_resize?(min_fill: 10) size = slots size > INITIAL_SIZE && ((used * 100) / size < min_fill) end private def slots hash_tables[0].size + hash_tables[1].size end def main_table @hash_tables[0] end def rehashing_table @hash_tables[1] end def expand(size) return if rehashing? || main_table.used > size real_size = next_power(size) return if real_size == main_table.size new_hash_table = HashTable.new(real_size) # Is this the first initialization? If so it's not really a rehashing # we just set the first hash table so that it can accept keys. if main_table.table.nil? @hash_tables[0] = new_hash_table else @hash_tables[1] = new_hash_table @rehashidx = 0 end end # In the Redis codebase, they extensively use the following pattern: # for (table = 0; table <= 1; table++) { # ... # if (!dictIsRehashing(d)) break; # } # This is common for many operations, such as finding or deleting an item in the dict, # we first need to look at the main table, the first table, but we haven't found in the # first one, we should look in the rehashing table, the second one, but only if we're in # the process of rehashing. # Taking advantage of Ruby blocks, we can write this helper method instead def iterate_through_hash_tables_unless_rehashing @hash_tables.each do |hash_table| yield hash_table break unless rehashing? end end def key_index(key) expand_if_needed hash = SipHash.digest(RANDOM_BYTES, key) index = nil iterate_through_hash_tables_unless_rehashing do |hash_table| index = hash & hash_table.sizemask entry = hash_table.table[index] while entry # The key is already present in the hash so there's no valid index where to add it if entry.key == key return -1 else entry = entry.next end end end index end def rehash(n) empty_visits = n * 10 return 0 unless rehashing? while n > 0 && main_table.used != 0 n -= 1 entry = nil while main_table.table[@rehashidx].nil? @rehashidx += 1 empty_visits -= 1 return 1 if empty_visits == 0 end entry = main_table.table[@rehashidx] while entry next_entry = entry.next idx = SipHash.digest(RANDOM_BYTES, entry.key) & rehashing_table.sizemask entry.next = rehashing_table.table[idx] rehashing_table.table[idx] = entry main_table.used -= 1 rehashing_table.used += 1 entry = next_entry end main_table.table[@rehashidx] = nil @rehashidx += 1 end # Check if we already rehashed the whole table if main_table.used == 0 @hash_tables[0] = rehashing_table @hash_tables[1] = HashTable.new(0) @rehashidx = -1 0 else # There's more to rehash 1 end end def rehashing? @rehashidx != -1 end def expand_if_needed return if rehashing? if main_table.empty? expand(INITIAL_SIZE) elsif main_table.used >= main_table.size expand(main_table.size * 2) end end def next_power(size) # Ruby has practically no limit to how big an integer can be, because under the hood the # Integer class allocates the necessary resources to go beyond what could fit in a 64 bit # integer. # That being said, let's still copy what Redis does, since it makes sense to have an # explicit limit about how big our Dicts can get i = INITIAL_SIZE return MAX_SIZE if size >= MAX_SIZE loop do return i if i >= size i *= 2 end end def rehash_step rehash(1) end end end <file_sep>/code/chapter-1/client.c #include <stdio.h> // For printf #include <netdb.h> // For AF_INET, SOCK_STREAM, sockaddr_in #include <stdlib.h> // For exit #include <string.h> // For bzero #include <sys/socket.h> // For connect #include <arpa/inet.h> // For inet_addr #include <unistd.h> // for close #define MAX 80 #define PORT 2000 #define SA struct sockaddr int main() { int server_socket_file_descriptor; struct sockaddr_in server_address; // socket create and varification server_socket_file_descriptor = socket(AF_INET, SOCK_STREAM, 0); if (server_socket_file_descriptor == -1) { printf("socket creation failed...\n"); exit(0); } else { printf("Socket successfully created..\n"); } bzero(&server_address, sizeof(server_address)); // assign IP, PORT server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = inet_addr("127.0.0.1"); server_address.sin_port = htons(PORT); // connect the client socket to server socket if (connect(server_socket_file_descriptor, (SA*)&server_address, sizeof(server_address)) != 0) { printf("connection with the server failed...\n"); exit(0); } else { printf("connected to the server..\n"); } char message_buffer[MAX] = "Hello, this is Client"; write(server_socket_file_descriptor, message_buffer, sizeof(message_buffer)); bzero(message_buffer, sizeof(message_buffer)); read(server_socket_file_descriptor, message_buffer, sizeof(message_buffer)); printf("From Server: %s", message_buffer); // close the socket close(server_socket_file_descriptor); } <file_sep>/content/post/chapter-1-basic-server.md --- title: "Chapter 1 - A basic TCP server" date: 2020-05-16T15:54:30-04:00 lastmod: 2020-06-25T10:25:41-04:00 comment: false draft: false summary: > This chapter will cover the creation of a TCP server in ruby, as well as how to interact with it with `netcat`, a utility bundled with macOS and linux. We will briefly look at concurrency and parallelism and how threads can impact the behavior of our server. --- ## What we'll cover This chapter will cover the creation of a TCP server in ruby, as well as how to interact with it with the `netcat` utility , available as `nc` on linux and macOS. We will briefly look at concurrency and parallelism and how threads can impact the behavior of our server. ## Introduction The goal of this book is to implement a Redis-like server, "from scratch". At the time of this writing Redis supports 8 different [data types][redis-data-types], dozens of commands related to those data types as well as many features in the [Administration][redis-administration] category, such as Redis Sentinel for High Availability. I will start with a heavily simplified version of Redis, and slowly add more features, trying to get as close as possible to what Redis supports today. I'm choosing Ruby for this book for no other reasons that I like it, and I find it fun to play with. Ruby is often characterized as a "slow language" but performance is not a big concern here. While I will make sure to make sound implementation choices, the goal is to learn more about Redis, Ruby, networking, OS signals and so on and not to produce a production ready software. ## A note about "from scratch" "From scratch" can be a an ambiguous term, especially with a language like Ruby that provides so many features out of the box. My goal with this book is to rely exclusively on the Ruby standard library. At the time of this writing, April 2020, the latest Ruby version is 2.7.1. ## And now, let's write some code The main Redis component is `redis-server`, which is an executable that starts a TCP server. When experimenting with Redis, it is common to use `redis-cli`, which is an executable that starts a REPL client that connects to a redis server. By default Redis runs on localhost, on port 6379. The official Ruby documentation shows the following example for the [TCPServer class][ruby-tcp-server]: {{< highlight ruby >}} require 'socket' server = TCPServer.new 2000 # Server bind to port 2000 loop do client = server.accept # Wait for a client to connect client.puts "Hello !" client.puts "Time is #{Time.now}" client.close end {{< / highlight >}} Followed by the following example and comment: "A more usable server (serving multiple clients)" ``` ruby require 'socket' server = TCPServer.new 2000 loop do Thread.start(server.accept) do |client| client.puts "Hello !" client.puts "Time is #{Time.now}" client.close end end ``` I will ignore the second example for now because concurrency/parallelism is a complicated topic and I want to address it in depth later. So, for now, let's focus on the first example, line by line: First, we require `'socket'`. Ruby's require syntax has always been weird to me, especially compared to more explicit ones like Python's for instance. After a bit of browsing through the Ruby source code, my guess is that this `require` call will add all the constants defined in the c files [in the `lib/socket/` folder of the ruby source code][ruby-source-socket] to `$LOAD_PATH`, making a bunch of classes such as [`Addrinfo`][ruby-source-addrinfo], [`UnixServer`][ruby-source-unixserver], [`UNIXSocket`][ruby-source-unixsocket], [`UDPSocket`][ruby-source-udpsocket], [`TCPSocket`][ruby-source-tcpsocket], [`TCPServer`][ruby-source-tcpserver] & [`SOCKSocket`][ruby-source-sockssocket]. You can try this on your own in an `irb` shell, requiring any of these constants would fail with a `NameError` before calling `require 'socket'` and would work afterwards: ``` ruby irb(main):001:0> TCPSocket Traceback (most recent call last): # [truncated] NameError (uninitialized constant TCPSocket) irb(main):002:0> UNIXServer Traceback (most recent call last): # [truncated] NameError (uninitialized constant UNIXServer) irb(main):003:0> require 'socket' => true irb(main):004:0> TCPSocket => TCPSocket irb(main):005:0> UNIXServer => UNIXServer ``` The next line creates a new `TCPServer` instance, listening on port 2000. The documentation for new [is the following][ruby-tcp-server-new]: ``` new([hostname], port) => tcpserver Creates a new server socket bound to port. If hostname is given, the socket is bound to it. Internally, ::new calls getaddrinfo() function to obtain addresses. If getaddrinfo() returns multiple addresses, ::new tries to create a server socket for each address and returns first one that is successful. ``` What the documentation implies is that the `hostname` argument is optional and that omitting it runs on `localhost` by default. Great, so now we have a TCP server running on `localhost:2000`, but is it actually doing anything? Let's see. We can run a server in an `irb` shell: ``` ruby irb(main):001:0> require 'socket' => true irb(main):002:0> TCPServer.new 2000 => #<TCPServer:fd 10, AF_INET6, ::, 2000> # Note that fd value might be different on your system. ``` Let's take look at what these values after `TCPServer:` mean: *`fd 10`* `fd` stands for File Descriptor, if you're interested you can see all the descriptors used by a process on macOS with the `lsof` tool: `lsof -p <process id>`. We can use `pgrep` to get the process id (often called pid) of the `irb` session we started the server from. There was only one result on my machine, 86096, but if you have more than one `irb` session running, you can use `ps aux <pid>` to get more info about a specific process, like its start timestamp for instance. This is what the last line looked like for me, and we can see that there is an open file with the value 10 for FD. ``` bash [...] ruby 86096 pierre 10u IPv6 0x80d76e9380eb855d 0t0 TCP *:callbook (LISTEN) ``` *`2000`* This is the port value, which we passed as an argument to the constructor *`AF_INET6` & `::`* I wasn't exactly sure what the two values in the middle were, `AF_INET6` & `::`, so I first tried to figure out how this string was built by looking at where the `inspect` method came from on the `TCPServer` instance: ``` bash irb(main):002:0> server = TCPServer.new(2000) irb(main):003:0> server.method(:inspect) => #<Method: TCPServer(IPSocket)#inspect()> irb(main):004:0> server.method(:inspect).source_location => nil ``` Great, and not so great, the `method` method tells us that `inspect` comes the `IPSocket` class, but `source_location` doesn't help us at all, let's keep digging. `TCPServer` inherits from `TCPSocket`, which itself inherits from `IPSocket`. The [`inspect`][ruby-ipsocket-inspect] method on `IPSocket` is defined as a C function in [`ipsocket.c`][ruby-source-ipsocket]. It looks like the values come from the `addr` function, which according to [the ruby documentation][ruby-ipsocket-addr]: "Returns the local address as an array which contains address_family, port, hostname and numeric_address." A bit of Googling about `AF_INET6` [confirmed this][so-af-inet6], `AF` stands for Address Family, and INET mean Internet Protocol v4, INET6 means Internet Protocol v6. `::` has a [special meaning][four-zeroes-ip] for IPv6 addresses, equivalent to 0.0.0.0 for IPv4. --- Back to our server, if you still have a terminal open, where you ran `TCPServer.new 2000` in an `irb` shell, now open a new terminal and run `nc localhost 2000`. `nc`, which is the cli for the `netcat` utility, is used for, according to its `man` page: "[...] just about anything under the sun involving TCP or UDP". `telnet` is another similar tool, but it does not come bundled with macOS by default, that being said, it is only a `brew install` away. Running `nc localhost 2000` should "hang", nothing is happening and you cannot type more commands in the shell. Feel free to exit with `Ctrl-C`. It would otherwise never end, unless you stop the server running in the other shell, either with the `close` method or by closing the `irb` session. You can confirm that it did indeed do something, because if you try it with an unused port, such as 2001, it should return right away, with an exit code of 1, aka, an error. If it hangs on port 2001 as well, it might be because you have something running on port 2001 on your machine. `nc` has a `-w` flag, to specify a timeout, you can see all available flags with `nc -h`. You can experiment yourself by running the same command, with a value for `-w`. Running `nc -w 5 localhost 2000` will wait for 5 seconds and exit with a status of 0 after that. Regardless of the environment, I think it's an overall best practice to set timeouts when dealing with network calls like HTTP requests. While it is unlikely that a server would have such a blatant bad behavior as the one we currently have, accept a request and do absolutely nothing with it, it is entirely possible that a server would take a very long time to return a response, if a spike in incoming traffic is causing the server to become unresponsive for instance. In this case, it might be beneficial for the client to abort after the timeout, instead of waiting. {{% admonition info "Exit Status" %}} Quoting the [wikipedia page][wikipedia-exit-status]: > The exit status of a process in computer programming is a small number passed from a child process (or callee) to a parent process (or caller) when it has finished executing a specific procedure or delegated task. > > [...] > > POSIX-compatible systems typically use a convention of zero for success and nonzero for error Some terminals are configured to show the exit status, some do it only for non zero codes, but you can always use `echo $?` to see the status of the last command. Running `ls` followed by `echo $?` should output `0`. If you've seen C code, the `main` function's signature is `int main()` because the value returned by `main` is the value used as the exit status, unless you call `exit` explicitly. So this is why you might see `return 0` at the end of the `main` function in a C program, it means "return success". It also seems common to use `exit(EXIT_SUCCESS)` or `exit(EXIT_FAILURE)`. Some codes [have special meanings][exit-codes], such as 127 meaning "Command not found" and 130 "Script terminated by Control-C". Exit statuses are not specific to POSIX systems as documented on [Wikipedia][wikipedia-exit-status]. {{% /admonition %}} Let's dive a bit deeper by passing the verbose flag, `-v`: `nc -v localhost 2000`: ``` bash found 0 associations found 1 connections: 1: flags=82<CONNECTED,PREFERRED> outif lo0 src 127.0.0.1 port 53022 dst 127.0.0.1 port 2000 rank info not available TCP aux info available Connection to localhost port 2000 [tcp/callbook] succeeded! ``` So it did connect, and it does nothing, because our server was just started, but it wasn't instructed to do anything with the incoming connection. `loop` in Ruby starts an infinite loop, nothing special here, it is common for a server to start and never end. Think about Redis for a minute, once the server is running, we want it to run forever, we don't expect it to stop unless told to do so. An infinite loop makes perfect sense for a use case like that. The next line is really interesting, and probably one of the most interesting ones in this small snippet: `server.accept`. Let's go back to `irb` for a moment, because it makes it easier to experiment with these methods, one at a time. ``` ruby irb(main):001:0> require 'socket' => true irb(main):002:0> s = TCPServer.new 2000 irb(main):003:0> s.accept ``` The `accept` method does not return. The documentation is sadly very succinct: > Accepts an incoming connection. It returns a new TCPSocket object. What it doesn't tell us is that it effectively a "blocking" method. This can technically be inferred by the presence of another method on `TCPServer`, [`accept_nonblock`][ruby-accept-nonblock], which, according to the documentation: > Accepts an incoming connection using accept(2) after O_NONBLOCK is set for the underlying file descriptor. It returns > an accepted TCPSocket for the incoming connection. We'll look closer at `accept_nonblock` in a later chapter. Let's go back to our second shell, note that the hanging `nc localhost 2000` ended if you closed the first `irb` shell. What happened is that the server closed the connection, and the client, `nc`, stopped as well. Let's re-run the same command, `nc localhost 2000`. We'll see a very similar output we saw above, saying that the connection succeeded. The main difference is that the hanging `accept` call in `irb` now returned, with a `TCPSocket` instance. Let's get a reference to this socket with `socket = _` (`_` is a reference to the last value returned in `irb`) and send something to our client: `socket.puts "Hey!"`. If you go back to the terminal where you ran `nc`, you should see "Hey!". Let's now close the connection with `socket.close` and we can observer that the `nc` calls returned, with an exit code of 0, aka, success. And that's it, we went through the official example of `TCPServer`. The example starts a TCP server on port 2000, and then enters an infinite loop, it first waits for an incoming connection, and does nothing else until a client connects, once a client connects, it writes "Hello !" first and then the current time and finally closes the connection, and starts over. If you remember, at the beginning we briefly looked at the second example in the documentation, using `Thread.start`. The justification for this example was that it was more usable by being able to serve multiple clients. There is indeed a major issue with the initial example, it can only serve one client at a time. If you were to put the example in a file, say, `server.rb` and run it with `ruby server.rb`, it would start one process, one thread and start executing the loop. The second example improves the situation by passing the result of the blocking operation, `server.accept`, to a new thread and letting it handle the client. There are a few important things to note here. First, ruby does not support lazy arguments, so when we write `Thread.start(server.accept)`, we first need to evaluate the argument, and only then will `start` be called, with the result of the evaluation. What that means for our example is that the loop starts, then blocks until a client connects, and once the client is connected, the resulting socket is passed to `Thread.start`. Let's illustrate this with an example, we'll simulate a slow server by adding a `sleep` call. Still in `irb`, run the following: ``` ruby loop { socket = server.accept; socket.write "Hello"; sleep 5; socket.close } ``` This is almost identical to the first example, except that the main thread sleeps for five seconds before closing the socket. Back to the other terminal, run `nc localhost 2000` again, and you'll see "Hello" being printed almost instantly, followed by the process hanging for five seconds and then exiting. While it is hanging, open a terminal and run the same command, `nc localhost 2000`, if you see "Hello" right away, it might be because the five seconds elapsed in the previous terminal. Feel free to close the infinite loop in `irb` with Ctrl-C and increase the value to 10 seconds or more and experiment with this. What this shows us is that while the server is busy dealing with a client, even if it doesn't do anything and just sleeps, all other incoming clients are effectively waiting to be served. The second example improves on this as can be seen in `irb` if you run the following instead: ``` ruby loop { Thread.start(server.accept) { |socket| socket.write "Hello" sleep 5 socket.close } } ``` Running the same manual test, we should see that both `nc localhost 2000` calls get the "Hello" response, and then they proceed to both wait for five seconds until the server closes the socket. This is because each client is being handled by a different thread. The first client will trigger the first `server.accept` call to return, resulting in a second thread being started (second thread because the initial program is itself running in a thread as well). While the second thread is sleeping, the main thread is not blocked anymore, it passed the socket to the second thread and is back at being blocked on `server.accept`. When the second client connects, the same thing happens, a new thread is started, and it's being given the newly created socket. We have a server that can server multiple clients at one, which is great. That being said, there is a big problem with this approach. Threads are not unlimited, if we were to create more and more threads, we could be at risk of slowing down the whole system. Using multiple threads is something that needs to be done very carefully and it can easily lead to race conditions. As mentioned earlier, concurrency and parallelism are both complicated topics and we'll try to cover them in future chapters. ## Conclusion We now know how to run a basic TCP server, it can write strings to its clients and then close the connection, that's it. That being said, as we'll see in future chapters, we can do a lot with that. We also looked at the limitation of a single threaded approach, and while we could use threads to improve the situation, we are purposefully not doing it for now, to keep our example simple and improve it one step at a time. In the next chapter we'll create a server class and make it read input from clients, and respond to `GET` and `SET`, in their most basic forms, we won't implement things like TTL or other options, ### Appendix - A C implementation of the server I was interested to see what a lower level implementation would be like, so I tried to put together an example in C, of a server, listening on port 2000, and writing data back to clients when they connect. Here is the code. {{% admonition info "Using gcc" %}} Note: If you do not have `gcc` installed your machine, you can install in on macOS with the following command: `xcode-select --install`, if you're on a different OS, I'll let you search, this should be a fairly common questions and have lots of answers on stackoverflow and the likes. {{% /admonition %}} The code I'm sharing here is a simplified version of the client/server code available on [GeeksforGeeks][geeks-for-geeks-server-client]: Server: ``` c #include <stdio.h> // For printf #include <netdb.h> // For bind, listen, AF_INET, SOCK_STREAM, socklen_t, sockaddr_in, INADDR_ANY #include <stdlib.h> // For exit #include <string.h> // For bzero #include <unistd.h> // For close & write #include <errno.h> // For errno, duh! #include <arpa/inet.h> // For inet_ntop #define MAX 80 #define PORT 2000 #define SA struct sockaddr int main() { socklen_t client_address_length; int server_socket_file_descriptor, client_socket_file_descriptor; struct sockaddr_in server_address, client_address; // socket create and verification server_socket_file_descriptor = socket(AF_INET, SOCK_STREAM, 0); if (server_socket_file_descriptor == -1) { printf("socket creation failed...\n"); exit(0); } else { printf("Socket successfully created..\n"); } bzero(&server_address, sizeof(server_address)); // assign IP, PORT server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = htons(PORT); // Binding newly created socket to given IP and verification if ((bind(server_socket_file_descriptor, (SA*)&server_address, sizeof(server_address))) != 0) { printf("socket bind failed... : %d, %d\n", server_socket_file_descriptor, errno); exit(0); } else { printf("Socket successfully bound..\n"); } // Now server is ready to listen and verification if ((listen(server_socket_file_descriptor, 5)) != 0) { printf("Listen failed...\n"); exit(0); } else { printf("Server listening..\n"); } client_address_length = sizeof(client_address); // Accept the data packet from client and verification client_socket_file_descriptor = accept(server_socket_file_descriptor, (SA*)&client_address, &client_address_length); if (client_socket_file_descriptor < 0) { printf("server accept failed: %d,%d...\n", client_socket_file_descriptor, errno); exit(0); } else { printf("server accept the client...\n"); char human_readable_address[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &client_address.sin_addr, human_readable_address, sizeof(human_readable_address)); printf("Client address: %s\n", human_readable_address); } char message_buffer[MAX]; read(client_socket_file_descriptor, message_buffer, sizeof(message_buffer)); printf("From Client: %s\n", message_buffer); bzero(message_buffer, MAX); strcpy(message_buffer, "Hello, this is Server!"); write(client_socket_file_descriptor, message_buffer, sizeof(message_buffer)); // After chatting close the socket printf("Closing server_socket_file_descriptor\n"); close(server_socket_file_descriptor); } ``` Client: ``` c #include <stdio.h> // For printf #include <netdb.h> // For AF_INET, SOCK_STREAM, sockaddr_in #include <stdlib.h> // For exit #include <string.h> // For bzero #include <sys/socket.h> // For connect #include <arpa/inet.h> // For inet_addr #include <unistd.h> // for close #define MAX 80 #define PORT 2000 #define SA struct sockaddr int main() { int server_socket_file_descriptor; struct sockaddr_in server_address; // socket create and verification server_socket_file_descriptor = socket(AF_INET, SOCK_STREAM, 0); if (server_socket_file_descriptor == -1) { printf("socket creation failed...\n"); exit(0); } else { printf("Socket successfully created..\n"); } bzero(&server_address, sizeof(server_address)); // assign IP, PORT server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = inet_addr("127.0.0.1"); server_address.sin_port = htons(PORT); // connect the client socket to server socket if (connect(server_socket_file_descriptor, (SA*)&server_address, sizeof(server_address)) != 0) { printf("connection with the server failed...\n"); exit(0); } else { printf("connected to the server..\n"); } char message_buffer[MAX] = "Hello, this is Client"; write(server_socket_file_descriptor, message_buffer, sizeof(message_buffer)); bzero(message_buffer, sizeof(message_buffer)); read(server_socket_file_descriptor, message_buffer, sizeof(message_buffer)); printf("From Server: %s", message_buffer); // close the socket close(server_socket_file_descriptor); } ``` As usual, let's run a few manual tests, but since this is C, we first need to compile this: ``` bash $ gcc server.c -o server $ gcc client.c -o client ``` We're going to need two shells, start the server in the first one, `./server`. It should log the following: ``` bash Socket successfully created.. Socket successfully bound.. Server listening.. ``` Note that, as we saw previously when creating a server from Ruby, it is "hanging" and hasn't returned yet. In the other shell, run the client: `./client`, you should see the following output: ``` bash $ ./client Socket successfully created.. connected to the server.. From Server: Hello, this is Server! ``` And if you return to the other shell, where the server was running, you can see that it now returned and logged a few more things before doing so: ``` bash server accept the client... Client address: 127.0.0.1 From Client: Hello, this is Client Closing server_socket_file_descriptor ``` It works! A server, that waits until a client connects, reads what the client sent and writes a message back, and once all of that is done, exits. Doing a step by step walk through of the client and server code is both a little bit out of scope and frankly something that I am not really capable of doing at the moment. That being said, I thought it would be interesting to visualize a similar-ish implementation to get a rough idea of what Ruby does for us under the hood. ### Code The code from this chapter is [available on GitHub](https://github.com/pjambet/redis-in-ruby/tree/master/code/chapter-1) [redis-data-types]:https://redis.io/topics/data-types-intro [redis-administration]:https://redis.io/documentation#administration [ruby-tcp-server]:http://ruby-doc.org/stdlib-2.7.1/libdoc/socket/rdoc/TCPServer.html [ruby-source-socket]:https://github.com/ruby/ruby/tree/v2_7_1/ext/socket [ruby-source-addrinfo]:https://github.com/ruby/ruby/blob/v2_7_1/ext/socket/raddrinfo.c#L2689 [ruby-source-unixserver]:https://github.com/ruby/ruby/blob/v2_7_1/ext/socket/unixserver.c#L118 [ruby-source-unixsocket]:https://github.com/ruby/ruby/blob/v2_7_1/ext/socket/unixsocket.c#L584 [ruby-source-udpsocket]:https://github.com/ruby/ruby/blob/v2_7_1/ext/socket/udpsocket.c#L238 [ruby-source-tcpsocket]:https://github.com/ruby/ruby/blob/v2_7_1/ext/socket/tcpsocket.c#L88 [ruby-source-tcpserver]:https://github.com/ruby/ruby/blob/v2_7_1/ext/socket/tcpserver.c#L139 [ruby-source-sockssocket]:https://github.com/ruby/ruby/blob/v2_7_1/ext/socket/sockssocket.c#L68 [ruby-source-ipsocket]:https://github.com/ruby/ruby/blob/v2_7_1/ext/socket/ipsocket.c#L206 [so-af-inet6]:https://stackoverflow.com/a/1594039/919641 [geeks-for-geeks-server-client]:https://www.geeksforgeeks.org/tcp-server-client-implementation-in-c/ [ruby-tcp-server-new]:https://ruby-doc.org/stdlib-2.7.1/libdoc/socket/rdoc/TCPServer.html#method-c-new [ruby-ipsocket-inspect]:http://ruby-doc.org/stdlib-2.7.1/libdoc/socket/rdoc/IPSocket.html#method-i-inspect [ruby-ipsocket-addr]:http://ruby-doc.org/stdlib-2.7.1/libdoc/socket/rdoc/IPSocket.html#method-i-addr [four-zeroes-ip]:https://en.wikipedia.org/wiki/0.0.0.0 [wikipedia-exit-status]:https://en.wikipedia.org/wiki/Exit_status#POSIX [exit-codes]:https://tldp.org/LDP/abs/html/exitcodes.html [ruby-accept-nonblock]:http://ruby-doc.org/stdlib-2.7.1/libdoc/socket/rdoc/TCPServer.html#method-i-accept_nonblock <file_sep>/config.toml baseURL = "https://redis.pjam.me" languageCode = "en" defaultContentLanguage = "en" title = "Rebuilding Redis in Ruby" preserveTaxonomyNames = true enableRobotsTXT = true enableEmoji = true theme = "even" enableGitInfo = false # use git commit log to generate lastmod record # Syntax highlighting by Chroma. NOTE: Don't enable `highlightInClient` and `chroma` at the same time! pygmentsOptions = "linenos=false" pygmentsCodefences = true pygmentsUseClasses = true pygmentsCodefencesGuessSyntax = true hasCJKLanguage = false paginate = 5 disqusShortname = "redis-in-ruby" # disqus_shortname googleAnalytics = "" # UA-XXXXXXXX-X copyright = "" # default: author.name ↓ [author] # essential name = "<NAME>" [sitemap] # essential changefreq = "weekly" priority = 0.5 filename = "sitemap.xml" [[menu.main]] # config your menu name = "Home" weight = 10 identifier = "home" url = "/" # [[menu.main]] # name = "Archives" # weight = 30 # identifier = "archives" # url = "/post/" [[menu.main]] name = "Discussion" weight = 30 identifier = "discussion" url = "/discussion/" # [[menu.main]] # name = "Tags" # weight = 30 # identifier = "tags" # url = "/tags/" # [[menu.main]] # name = "Categories" # weight = 40 # identifier = "categories" # url = "/categories/" [[menu.main]] name = "Table of Contents" weight = 20 identifier = "chapters" url = "/chapters/" [[menu.main]] name = "About" weight = 40 identifier = "about" url = "/about/" [params] version = "4.x" # Used to give a friendly message when you have an incompatible update debug = false # If true, load `eruda.min.js`. See https://github.com/liriliri/eruda since = "2020" # use public git repo url to link lastmod git commit, enableGitInfo should be true. gitRepo = "" # site info (optional) keywords = ["Redis", "Ruby", "Programming"] description = "Rebuilding Redis in Ruby, for fun and profit" # paginate of archives, tags and categories archivePaginate = 20 # show 'xx Posts In Total' in archive page ? showArchiveCount = false # The date format to use; for a list of valid formats, see https://gohugo.io/functions/format/ dateFormatToUse = "2006-01-02" # show word count and read time ? moreMeta = false # Syntax highlighting by highlight.js highlightInClient = false # Some global options, you can also close or open something in front matter for a single post, see more information from `archetypes/default.md`. toc = true autoCollapseToc = false # Auto expand and collapse toc fancybox = true # see https://github.com/fancyapps/fancybox # mathjax mathjax = false # see https://www.mathjax.org/ mathjaxEnableSingleDollar = false mathjaxEnableAutoNumber = false mathjaxUseLocalFiles = false # You should install mathjax in `your-site/static/lib/mathjax` postMetaInFooter = false # contain author, lastMod, markdown link, license linkToMarkDown = false # Only effective when hugo will output .md files. contentCopyright = '' # e.g. '<a rel="license noopener" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank">CC BY-NC-ND 4.0</a>' googleVerification = "" # Google Verification # Link custom CSS and JS assets # (relative to /static/css and /static/js respectively) customCSS = [] customJS = [] uglyURLs = false # please keep same with uglyurls setting [params.publicCDN] # load these files from public cdn enable = true jquery = '<script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="<KEY> crossorigin="anonymous"></script>' slideout = '<script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="<KEY> crossorigin="anonymous"></script>' # fancyboxJS = '<script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="<KEY> crossorigin="anonymous"></script>' # fancyboxCSS = '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="<KEY> crossorigin="anonymous">' timeagoJS = '<script src="https://cdn.jsdelivr.net/npm/timeago.js@3.0.2/dist/timeago.min.js" integrity="<KEY> crossorigin="anonymous"></script>' timeagoLocalesJS = '<script src="https://cdn.jsdelivr.net/npm/timeago.js@3.0.2/dist/timeago.locales.min.js" integrity="<KEY> crossorigin="anonymous"></script>' # flowchartDiagramsJS = '<script src="https://cdn.jsdelivr.net/npm/raphael@2.2.7/raphael.min.js" integrity="sha256-67By+NpOtm9ka1R6xpUefeGOY8kWWHHRAKlvaTJ7ONI=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/flowchart.js@1.8.0/release/flowchart.min.js" integrity="<KEY> crossorigin="anonymous"></script>' # sequenceDiagramsCSS = '<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/bramp/js-sequence-diagrams@2.0.1/dist/sequence-diagram-min.css" integrity="<KEY>" crossorigin="anonymous">' # sequenceDiagramsJS = '<script src="https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.js" integrity="<KEY> crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/snapsvg@0.5.1/dist/snap.svg-min.js" integrity="<KEY> crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/underscore@1.8.3/underscore-min.js" integrity="<KEY> crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/gh/bramp/js-sequence-diagrams@2.0.1/dist/sequence-diagram-min.js" integrity="<KEY>" crossorigin="anonymous"></script>' # Display a message at the beginning of an article to warn the readers that it's content may be outdated. [params.outdatedInfoWarning] enable = false hint = 30 # Display hint if the last modified time is more than these days ago. warn = 180 # Display warning if the last modified time is more than these days ago. [params.gitment] # Gitment is a comment system based on GitHub issues. see https://github.com/imsun/gitment owner = "" # Your GitHub ID repo = "" # The repo to store comments clientId = "" # Your client ID clientSecret = "" # Your client secret [params.utterances] # https://utteranc.es/ owner = "" # Your GitHub ID repo = "" # The repo to store comments [params.gitalk] # Gitalk is a comment system based on GitHub issues. see https://github.com/gitalk/gitalk owner = "" # Your GitHub ID repo = "" # The repo to store comments clientId = "" # Your client ID clientSecret = "" # Your client secret # Valine. # You can get your appid and appkey from https://leancloud.cn # more info please open https://valine.js.org # [params.valine] # enable = false # appId = '你的appId' # appKey = '你的appKey' # notify = false # mail notifier , https://github.com/xCss/Valine/wiki # verify = false # Verification code # avatar = 'mm' # placeholder = '说点什么吧...' # visitor = false [params.flowchartDiagrams]# see https://blog.olowolo.com/example-site/post/js-flowchart-diagrams/ enable = false options = "" [params.sequenceDiagrams] # see https://blog.olowolo.com/example-site/post/js-sequence-diagrams/ enable = false options = "" # default: "{theme: 'simple'}" [params.busuanzi] # count web traffic by busuanzi enable = false siteUV = true sitePV = true pagePV = true [params.reward] enable = true buymeacoffeelink = "https://www.buymeacoffee.com/pjam" buymeacoffee = "https://img.buymeacoffee.com/api/?name=pjam&size=150&bg-image=bmc" # wechat = "/path/to/your/wechat-qr-code.png" # alipay = "/path/to/your/alipay-qr-code.png" [params.social] # a-email = "mailto:<EMAIL>" b-stack-overflow = "https://stackoverflow.com/users/919641/pjam" c-twitter = "https://twitter.com/pierre_jambet" g-github = "https://github.com/pjambet/" # See https://gohugo.io/about/hugo-and-gdpr/ [privacy] [privacy.googleAnalytics] anonymizeIP = true # 172.16.31.10 -> 192.168.3.11 [privacy.youtube] privacyEnhanced = true # 将下面这段配置取消注释可以使 hugo 生成 .md 文件 # Uncomment these options to make hugo output .md files. #[mediaTypes] # [mediaTypes."text/plain"] # suffixes = ["md"] # #[outputFormats.MarkDown] # mediaType = "text/plain" # isPlainText = true # isHTML = false # #[outputs] # home = ["HTML", "RSS"] # page = ["HTML", "MarkDown"] # section = ["HTML", "RSS"] # taxonomy = ["HTML", "RSS"] # taxonomyTerm = ["HTML"] # From: https://github.com/olOwOlo/hugo-theme-even/issues/198 # Related: https://gohugo.io/news/0.60.0-relnotes/ [markup.goldmark.renderer] unsafe = true [markup] [markup.tableOfContents] # startLevel = 1 endLevel = 3 <file_sep>/code/chapter-10/test/hash_test.rb # coding: utf-8 require_relative './test_helper' describe 'BYORedis - Hash commands' do describe 'HSET' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'HSET', '-ERR wrong number of arguments for \'HSET\' command' ], [ 'HSET h', '-ERR wrong number of arguments for \'HSET\' command' ], [ 'HSET h f1', '-ERR wrong number of arguments for \'HSET\' command' ], [ 'HSET h f1 v1 f2', '-ERR wrong number of arguments for \'HSET\' command' ], [ 'HSET h f1 v1 f2 v2 f3', '-ERR wrong number of arguments for \'HSET\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-hash 1', '+OK' ], [ 'HSET not-a-hash f1 v1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'creates a hash if necessary' do assert_command_results [ [ 'TYPE h', '+none' ], [ 'HSET h f1 v1', ':1' ], [ 'TYPE h', '+hash' ], ] end it 'works with strings longer than the limit' do test_with_config_values(hash_max_ziplist_value: [ '1' ]) do assert_command_results [ [ 'HSET h f1 v1 f2 v2', ':2' ], [ 'HSET h f2 k2', ':0' ], [ 'HSET h f2 k2-a', ':0' ], [ 'HSET h f2 k2-b f3 k3', ':1' ], ] end end it 'returns the number of fields that were added' do test_with_config_values(hash_max_ziplist_entries: [ '512', '1' ]) do assert_command_results [ [ 'HSET h f1 v1 f2 v2', ':2' ], [ 'HSET h f2 k2', ':0' ], [ 'HSET h f2 k2-a', ':0' ], [ 'HSET h f2 k2-b f3 k3', ':1' ], ] end end end describe 'HGETALL' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'HGETALL', '-ERR wrong number of arguments for \'HGETALL\' command' ], [ 'HGETALL h a', '-ERR wrong number of arguments for \'HGETALL\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-hash 1', '+OK' ], [ 'HGETALL not-a-hash', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an empty array if the hash does not exist' do assert_command_results [ [ 'HGETALL h', '*0' ], ] end it 'returns all the field/value pairs in a flat array' do test_with_config_values(hash_max_ziplist_entries: [ '512', '1' ]) do assert_command_results [ [ 'HSET h f1 v1 f2 v2', ':2' ], [ 'HGETALL h', unordered([ 'f1', 'v1', 'f2', 'v2' ]) ], ] end end end describe 'HGET' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'HGET', '-ERR wrong number of arguments for \'HGET\' command' ], [ 'HGET h', '-ERR wrong number of arguments for \'HGET\' command' ], [ 'HGET h f a', '-ERR wrong number of arguments for \'HGET\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-hash 1', '+OK' ], [ 'HGET not-a-hash f1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns a nil string if the hash does not exist' do assert_command_results [ [ 'HGET h f1', BYORedis::NULL_BULK_STRING ], ] end it 'returns a nil string if the field does not exist in the hash' do assert_command_results [ [ 'HSET h f1 v1', ':1' ], [ 'HGET h f2', BYORedis::NULL_BULK_STRING ], ] end it 'returns the value for the given hash/field' do test_with_config_values(hash_max_ziplist_entries: [ '512', '1' ]) do assert_command_results [ [ 'HSET h f1 v1 f2 v2', ':2' ], [ 'HGET h f1', 'v1' ], [ 'HGET h f2', 'v2' ], [ 'HGET h f3', BYORedis::NULL_BULK_STRING ], ] end end end describe 'HDEL' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'HDEL', '-ERR wrong number of arguments for \'HDEL\' command' ], [ 'HDEL h', '-ERR wrong number of arguments for \'HDEL\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-hash 1', '+OK' ], [ 'HDEL not-a-hash f1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns the number of fields that were deleted from the hash' do test_with_config_values(hash_max_ziplist_entries: [ '512', '1' ]) do assert_command_results [ [ 'HSET h f1 v1 f2 v2 f3 v3', ':3' ], [ 'HDEL h f1 not-a-field f2', ':2' ], ] end end it 'removes the hash from the keyspace if it is empty' do test_with_config_values(hash_max_ziplist_entries: [ '512', '1' ]) do assert_command_results [ [ 'HSET h f1 v1 f2 v2', ':2' ], [ 'HDEL h f1 f2', ':2' ], [ 'TYPE h', '+none' ], ] end end it 'returns 0 if the hash does not exist' do assert_command_results [ [ 'HDEL h f1', ':0' ], ] end end describe 'HEXISTS' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'HEXISTS', '-ERR wrong number of arguments for \'HEXISTS\' command' ], [ 'HEXISTS h', '-ERR wrong number of arguments for \'HEXISTS\' command' ], [ 'HEXISTS h a b', '-ERR wrong number of arguments for \'HEXISTS\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-hash 1', '+OK' ], [ 'HEXISTS not-a-hash f1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns 0 if the hash does not exist' do assert_command_results [ [ 'HEXISTS h f1', ':0' ], ] end it 'returns 0 if the field does not exist in the hash' do assert_command_results [ [ 'HSET h f1 v1 f2 v2', ':2' ], [ 'HEXISTS h not-a-field', ':0' ], ] end it 'returns 1 if the field exists in the hash' do assert_command_results [ [ 'HSET h f1 v1 f2 v2', ':2' ], [ 'HEXISTS h f2', ':1' ], ] end end describe 'HINCRBY' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'HINCRBY', '-ERR wrong number of arguments for \'HINCRBY\' command' ], [ 'HINCRBY h', '-ERR wrong number of arguments for \'HINCRBY\' command' ], [ 'HINCRBY h a', '-ERR wrong number of arguments for \'HINCRBY\' command' ], [ 'HINCRBY h a b c', '-ERR wrong number of arguments for \'HINCRBY\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-hash 1', '+OK' ], [ 'HINCRBY not-a-hash f1 1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns the new value, as a RESP integer of the value for the field, after the incr' do assert_command_results [ [ 'HSET h f1 1 f2 2', ':2' ], [ 'HINCRBY h f1 99', ':100' ], [ 'HINCRBY h f2 99', ':101' ], ] end it 'returns an error if the value for the field is not an integer' do assert_command_results [ [ 'HSET h f1 not-an-int a-float 1.0', ':2' ], [ 'HINCRBY h f1 1', '-ERR hash value is not an integer' ], [ 'HINCRBY h a-float 1', '-ERR hash value is not an integer' ], ] end it 'returns an error if the increment is not an integer' do assert_command_results [ [ 'HINCRBY h f2 not-an-int', '-ERR value is not an integer or out of range' ], [ 'HINCRBY h f2 1.0', '-ERR value is not an integer or out of range' ], ] end it 'creates a new field/value pair with a value of 0 if the field does not exist' do assert_command_results [ [ 'HSET h f1 v1', ':1' ], [ 'HINCRBY h f2 10', ':10' ], ] end it 'creates a new hash and a new field/value pair with a value of 0 if the hash does not exist' do assert_command_results [ [ 'HINCRBY h f1 1', ':1' ], [ 'DEL h', ':1' ], [ 'HINCRBY h f1 100', ':100' ], ] end it 'handles a min overflow' do assert_command_results [ [ 'HSET h close-to-min -9223372036854775807', ':1' ], [ 'HINCRBY h close-to-min -2', '-ERR increment or decrement would overflow' ], ] end it 'handles a max overflow' do assert_command_results [ [ 'HSET h close-to-max 9223372036854775806', ':1' ], [ 'HINCRBY h close-to-max 2', '-ERR increment or decrement would overflow' ], ] end end describe 'HINCRBYFLOAT' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'HINCRBYFLOAT', '-ERR wrong number of arguments for \'HINCRBYFLOAT\' command' ], [ 'HINCRBYFLOAT h', '-ERR wrong number of arguments for \'HINCRBYFLOAT\' command' ], [ 'HINCRBYFLOAT h a', '-ERR wrong number of arguments for \'HINCRBYFLOAT\' command' ], [ 'HINCRBYFLOAT h a b c', '-ERR wrong number of arguments for \'HINCRBYFLOAT\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-hash 1', '+OK' ], [ 'HINCRBYFLOAT not-a-hash f1 1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns the new value, as a RESP string of the value for the field, after the incr' do assert_command_results [ [ 'HSET h a 1.0', ':1' ], [ 'HINCRBYFLOAT h a 0.34', '1.34' ], ] end it 'returns an error if the value for the field is not a number' do assert_command_results [ [ 'HSET h f1 not-an-int a-float 1.0', ':2' ], [ 'HINCRBYFLOAT h f1 1', '-ERR hash value is not a float' ], ] end it 'returns an error if the increment is not a number (float or int)' do assert_command_results [ [ 'HINCRBYFLOAT h f1 a', '-ERR value is not a valid float' ], ] end it 'returns an error if the result is nan or infinity' do assert_command_results [ [ 'HSET h f1 1', ':1' ], [ 'HINCRBYFLOAT h f1 inf', '-ERR increment would produce NaN or Infinity' ], [ 'HINCRBYFLOAT h f1 +inf', '-ERR increment would produce NaN or Infinity' ], [ 'HINCRBYFLOAT h f1 infinity', '-ERR increment would produce NaN or Infinity' ], [ 'HINCRBYFLOAT h f1 +infinity', '-ERR increment would produce NaN or Infinity' ], [ 'HINCRBYFLOAT h f1 -inf', '-ERR increment would produce NaN or Infinity' ], [ 'HINCRBYFLOAT h f1 -infinity', '-ERR increment would produce NaN or Infinity' ], [ 'HSET h f1 inf', ':0' ], # inf + inf = inf [ 'HINCRBYFLOAT h f1 inf', '-ERR increment would produce NaN or Infinity' ], # inf + -inf = NaN [ 'HINCRBYFLOAT h f1 -inf', '-ERR increment would produce NaN or Infinity' ], ] end it 'creates a new field/value pair with a value of 0 if the field does not exist' do assert_command_results [ [ 'HSET h f2 v2', ':1' ], [ 'HINCRBYFLOAT h f1 1.2', '1.2' ], ] end it 'creates a new hash and a new field/value pair with a value of 0 if the hash does not exist' do assert_command_results [ [ 'HINCRBYFLOAT h f1 1.2', '1.2' ], ] end end describe 'HKEYS' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'HKEYS', '-ERR wrong number of arguments for \'HKEYS\' command' ], [ 'HKEYS h f1', '-ERR wrong number of arguments for \'HKEYS\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-hash 1', '+OK' ], [ 'HKEYS not-a-hash', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an empty array if the hash does not exist' do assert_command_results [ [ 'HKEYS h', BYORedis::EMPTY_ARRAY ], ] end it 'returns an array of all the fields in the hash' do test_with_config_values(hash_max_ziplist_entries: [ '512', '1' ]) do assert_command_results [ [ 'HSET h f1 v1 f2 v2', ':2' ], [ 'HKEYS h', unordered([ 'f1', 'f2' ]) ], ] end end end describe 'HLEN' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'HLEN', '-ERR wrong number of arguments for \'HLEN\' command' ], [ 'HLEN h f1', '-ERR wrong number of arguments for \'HLEN\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-hash 1', '+OK' ], [ 'HLEN not-a-hash', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns 0 if the hash does not exist' do assert_command_results [ [ 'HLEN h', ':0' ], ] end it 'returns the number of field/value pairs in the hash' do test_with_config_values(hash_max_ziplist_entries: [ '512', '1' ]) do assert_command_results [ [ 'HSET h f1 v1 f2 v2', ':2' ], [ 'HLEN h', ':2' ], ] end end end describe 'HMGET' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'HMGET', '-ERR wrong number of arguments for \'HMGET\' command' ], [ 'HMGET h', '-ERR wrong number of arguments for \'HMGET\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-hash 1', '+OK' ], [ 'HMGET not-a-hash a b c', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an array with nil values if the hash does not exist' do assert_command_results [ [ 'HMGET h a b c', [ nil, nil, nil ] ], ] end it 'returns an array of all the values for the given fields in the hash' do assert_command_results [ [ 'HSET h f1 v1 f2 v2 f3 v3', ':3' ], [ 'HMGET h f1 f3', [ 'v1', 'v3' ] ], ] end it 'returns an array including nil values for non existing fields' do assert_command_results [ [ 'HSET h f1 v1 f2 v2 f3 v3', ':3' ], [ 'HMGET h f1 not-a-thing f3 neither-is-this', [ 'v1', nil, 'v3', nil ] ], ] end end describe 'HSETNX' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'HSETNX', '-ERR wrong number of arguments for \'HSETNX\' command' ], [ 'HSETNX h', '-ERR wrong number of arguments for \'HSETNX\' command' ], [ 'HSETNX h f', '-ERR wrong number of arguments for \'HSETNX\' command' ], [ 'HSETNX h f v a', '-ERR wrong number of arguments for \'HSETNX\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-hash 1', '+OK' ], [ 'HSETNX not-a-hash f1 v1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'does nothing if the field already exists' do assert_command_results [ [ 'HSET h f1 v1 f2 v2 f3 v3', ':3' ], [ 'HSETNX h f1 new-value', ':0' ], [ 'HGET h f1', 'v1' ], ] end it 'returns 1 if the hash does not exist' do assert_command_results [ [ 'HSETNX h f1 new-value', ':1' ], [ 'HGET h f1', 'new-value' ], ] end it 'returns 1 if the field does not exist' do assert_command_results [ [ 'HSET h f1 v1 f2 v2 f3 v3', ':3' ], [ 'HSETNX h new-field new-value', ':1' ], [ 'HGET h new-field', 'new-value' ], ] end end describe 'HSTRLEN' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'HSTRLEN', '-ERR wrong number of arguments for \'HSTRLEN\' command' ], [ 'HSTRLEN h', '-ERR wrong number of arguments for \'HSTRLEN\' command' ], [ 'HSTRLEN h a b', '-ERR wrong number of arguments for \'HSTRLEN\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-hash 1', '+OK' ], [ 'HSTRLEN not-a-hash f1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns 0 if the field does not exist' do assert_command_results [ [ 'HSET h f1 v1 f2 v2 f3 v3', ':3' ], [ 'HSTRLEN h not-a-thing', ':0' ], ] end it 'returns 0 if the hash does not exist' do assert_command_results [ [ 'HSTRLEN h not-a-thing', ':0' ], ] end it 'returns the length of the string stored for the given field' do assert_command_results [ [ 'HSET h f1 v1 f2 v2 f4 v3 a-long-string aaaaaaaaaa an-emoji 👋 another-one 🤷‍♂️', ':6' ], [ 'HSTRLEN h f1', ':2' ], [ 'HSTRLEN h a-long-string', ':10' ], [ 'HSTRLEN h an-emoji', ':4' ], [ 'HSTRLEN h another-one', ':13' ], ] end end describe 'HVALS' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'HVALS', '-ERR wrong number of arguments for \'HVALS\' command' ], [ 'HVALS a b', '-ERR wrong number of arguments for \'HVALS\' command' ], ] end it 'fails if the key is not a hash' do assert_command_results [ [ 'SET not-a-hash 1', '+OK' ], [ 'HVALS not-a-hash', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an empty array if the hash does not exist' do assert_command_results [ [ 'HVALS h', [] ], ] end it 'returns an array of all the values in the hash' do test_with_config_values(hash_max_ziplist_entries: [ '512', '1' ]) do assert_command_results [ [ 'HSET h f1 v1 f2 v2', ':2' ], [ 'HVALS h', unordered([ 'v1', 'v2' ]) ], ] end end end end <file_sep>/code/chapter-4/pttl_command.rb class PttlCommand def initialize(data_store, expires, args) @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @data_store = data_store @expires = expires @args = args end def call if @args.length != 1 "(error) ERR wrong number of arguments for 'PTTL' command" else key = @args[0] ExpireHelper.check_if_expired(@data_store, @expires, key) key_exists = @data_store.include? key if key_exists ttl = @expires[key] if ttl (ttl - (Time.now.to_f * 1000)).round else -1 end else -2 end end end end <file_sep>/code/chapter-8/redis_hash.rb module BYORedis class RedisHash ListEntry = Struct.new(:key, :value) def initialize @underlying = List.new end def empty? @underlying.empty? end def keys case @underlying when List then keys_list when Dict then @underlying.keys else raise "Unknown structure type: #{ @underlying }" end end def values case @underlying when List then values_list when Dict then @underlying.values else raise "Unknown structure type: #{ @underlying }" end end def length case @underlying when List then @underlying.size when Dict then @underlying.used else raise "Unknown structure type: #{ @underlying }" end end def set(key, value) max_string_length = Config.get_config(:hash_max_ziplist_value) convert_list_to_dict if @underlying.is_a?(List) && (key.length > max_string_length || value.length > max_string_length) case @underlying when List then added = set_list(key, value) if @underlying.size + length > Config.get_config(:hash_max_ziplist_entries) convert_list_to_dict end added when Dict then @underlying.set(key, value) else raise "Unknown structure type: #{ @underlying }" end end alias []= set def get_all case @underlying when List then get_all_list when Dict then get_all_dict else raise "Unknown structure type: #{ @underlying }" end end def get(field) case @underlying when List then get_list(field) when Dict then @underlying[field] else raise "Unknown structure type: #{ @underlying }" end end alias [] get def delete(field) case @underlying when List then was_deleted = delete_from_list(field) when Dict then was_deleted = !@underlying.delete(field).nil? if was_deleted && length - 1 == Config.get_config(:hash_max_ziplist_entries) convert_dict_to_list elsif @underlying.needs_resize? @underlying.resize end else raise "Unknown structure type: #{ @underlying }" end was_deleted end private def set_list(key, value) iterator = List.left_to_right_iterator(@underlying) while iterator.cursor && iterator.cursor.value.key != key iterator.next end if iterator.cursor.nil? @underlying.right_push(ListEntry.new(key, value)) true else iterator.cursor.value.value = value false end end def get_all_list iterator = List.left_to_right_iterator(@underlying) pairs = [] while iterator.cursor pairs.push(iterator.cursor.value.key, iterator.cursor.value.value) iterator.next end pairs end def get_all_dict pairs = [] @underlying.each do |key, value| pairs.push(key, value) end pairs end def get_list(field) iterator = List.left_to_right_iterator(@underlying) while iterator.cursor return iterator.cursor.value.value if iterator.cursor.value.key == field iterator.next end end def convert_list_to_dict dict = Dict.new iterator = List.left_to_right_iterator(@underlying) while iterator.cursor dict[iterator.cursor.value.key] = iterator.cursor.value.value iterator.next end @underlying = dict end def convert_dict_to_list list = List.new @underlying.each do |key, value| list.right_push(ListEntry.new(key, value)) end @underlying = list end def delete_from_list(field) was_deleted = false iterator = List.left_to_right_iterator(@underlying) while iterator.cursor if iterator.cursor.value.key == field @underlying.remove_node(iterator.cursor) return true end iterator.next end was_deleted end def keys_list iterator = List.left_to_right_iterator(@underlying) keys = [] while iterator.cursor keys << iterator.cursor.value.key iterator.next end keys end def values_list iterator = List.left_to_right_iterator(@underlying) values = [] while iterator.cursor values << iterator.cursor.value.value iterator.next end values end end end <file_sep>/code/chapter-10/test/skiplist_unit_test.rb require_relative './test_helper' require_relative '../skiplist' describe BYORedis::SkipList do it 'can create an empty list' do list = new_list assert(list) end it 'can add elements to a list' do list = new_list list.insert(10, '10') list.insert(5, '5') list.insert(20, '20') list.insert(30, '30') list.insert(40, '40') list.insert(50, '50') list.insert(60, '60') list.insert(70, '70') list.insert(80, '80') list.insert(90, '90') list.insert(90, '90-2') list.insert(-1, 'neg one') assert_equal(12, list.length) end def new_list BYORedis::SkipList.new end end <file_sep>/content/post/chapter-3-multiple-clients.md --- title: "Chapter 3 - Multiple Clients" date: 2020-07-06 lastmod: 2020-07-06T11:55:02-04:00 draft: false keywords: [] comment: false summary: "In this chapter we will add support for efficient handling of multiple clients connected simultaneously. We will first isolate the problematic elements of the current implementation and explore different solutions before getting to the final one using the select syscall" --- ## What we'll cover In this chapter we will add support for efficient handling of multiple clients connected simultaneously. We will first isolate the problematic elements of the current implementation and explore different solutions before getting to the final one using the [`select`][select-syscall] syscall. ## First problem, accepting multiple clients Let's start with the new client problem. Our goal is the following: Regardless of the state of the server, or what it might be doing, or whether other clients are already connected, new clients should be able to establish a new connection, and keep the connection open as long as they wish, until they either disconnect on purpose or a network issue occurs. We want our server to keep client connections alive until clients disconnect. This is what Redis does, it keeps the connection alive until the client closes the connection, either explicitly with the [QUIT][redis-documentation-quit] command or as a side effect of the process that had started the connection being stopped. Let's do this by removing the `client.close` line, we will add it back when we add a handler for the `QUIT` command, but let's set that aside for now. This is what the main server loop looks like now, after removing the `client.close` line: ``` ruby loop do client = server.accept puts "New client connected: #{ client }" client_command_with_args = client.gets if client_command_with_args && client_command_with_args.strip.length > 0 response = handle_client_command(client_command_with_args) client.puts response else puts "Empty request received from #{ client }" end end ``` The server starts, waits for a client to connect, and then handles the requests from that client, nothing changed. Once the server is done writing the response back, it starts doing the same thing again, waiting for a new client to connect, not keeping track of the first client. As far as the server knows, this client is still connected, but we have no way of reading future commands from this one client now. Because we're not closing the connection after writing back a response, we need the server to keep track of all the clients that are currently connected. ``` ruby # ... def initialize @clients = [] end # ... loop do client = server.accept @clients << client puts "New client connected: #{ client }" # ... end ``` Every time a client connects, we add it to the `@clients` array. The rest of the loop is the same, when the first iteration ends, we go back to the beginning and wait for a new client. But what if the first client sends a request in the meantime? Future commands from the first client will be ignored for two reasons. First, the server is currently waiting, potentially forever, for a new client to connect. Even though we did save the client object in the `@clients` array, we never actually read from this array. It is starting to look like waiting for clients to connect and trying to handle connected clients in the same loop is quite problematic, especially with all these blocking calls that potentially wait forever. One approach could be to timebox these blocking calls, to make sure they don't block the server while there might be other things to do, such as responding to another client. We could start a second thread, make it loop until either a new client connects or an arbitrary duration has elapsed and raise an exception when it has: ``` ruby timeout = Time.now.to_f + 5 server_accepted = false Thread.abort_on_exception = true Thread.new do while server_accepted == false sleep 0.001 if Time.now.to_f > timeout raise "Timeout!" end end end server.accept server_accepted = true ``` We create a new thread that will loop as long as the `server.accept` has not returned or until five seconds have elapsed. This means that the call to accept will not run for more than five seconds. The `abort_on_exception` setting is necessary, otherwise an uncaught exception in a Thread does not propagate to the parent thread, the thread would silently fail, not interrupting the `accept` call. Any clients connecting to the server within five seconds will prevent the `"Timeout!"` exception from being thrown, because the `server_accepted` flag will be set to `true`. As it turns out, we don't have to write this, Ruby gives us the [`Timeout` module][ruby-doc-timeout], which does pretty much the same thing, and throws an exception if the block hasn't finished after the given timeout: ``` rubyn require 'timeout' Timeout.timeout(5) do server.accept end ``` The Timeout module has received [a fair amount of criticism][sidekiq-timeout-blog] of the past few years. There are a few other posts out there if you search for the following keywords: "ruby timeout module dangerous" and we should absolutely follow their recommendation. Looking back at our primitive timeout implementation above, if the second thread enters the `if Time.now.to_f > timeout` condition, it will then throw an exception, but it is entirely possible that a client would connect at the exact same time, and the exception being thrown by the second thread would interrupt the parent thread, as it is creating the connection and effectively prevent the server from completing the `accept` call. The odds would be fairly unlikely, but it would still be possible. Another more important issue is the impact on performance. Using timeouts means that the server could end up waiting a lot, while being blocked. If a client connects and sends two commands, we would want the server to respond as fast as possible to both of these commands. Ideally in a matter of milliseconds, this is what the real Redis would do. But with the timeout approach we were looking at, the server would accept the connection, read the first command, respond to it, and then loop again, waiting for a new connection, while the client is waiting for the response to the second command. ``` +---------+ +---------+ | Client | | Server | +---------+ +---------+ | | | | Accepting Clients with a timeout | |--------------------------------- | | | | |<-------------------------------- | | | Connects | |----------------------->| | | ------------------\ | |-| Client accepted | | | |-----------------| | | | "GET 1" | |----------------------->| | | | | Processing GET command | |----------------------- | | | | |<---------------------- | | | "(nil)" | |<-----------------------| | | ------------------------------------\ | |-| Back to the beginning of the loop | | | |-----------------------------------| | | | "SET name pierre" | |----------------------->| | | | | Accepting Clients with a timeout | |--------------------------------- | | | | |<-------------------------------- | | ---------------------------------\ | |-| No clients found after timeout | | | |--------------------------------| | | | | Processing SET command | |----------------------- | | | | |<---------------------- | | | "OK" | |<-----------------------| | | ``` _figure 3.1: A sequence diagram showing the unnecessary delay introduced by the timeout approach_ We fixed the blocked problem, but the server is still inefficient. Even a short timeout on connect, like 10ms, would still add a delay of 10ms to the `SET` command in the example above. We can improve this. Let's try another approach to allow the server to accept new clients while still being able to handle incoming requests from connected clients. We are going to create a second thread, dedicated to accepting new clients, the main loop will now only be used to read from clients and write responses back: ``` ruby def initialize @clients = [] @data_store = {} server = TCPServer.new 2000 puts "Server started at: #{ Time.now }" Thread.new do loop do new_client = server.accept @clients << new_client end end loop do @clients.each do |client| begin client_command_with_args = client.gets if client_command_with_args.nil? @clients.delete(client) elsif client_command_with_args.strip.empty? puts "Empty request received from #{ client }" else response = handle_client_command(client_command_with_args) client.puts response end rescue Errno::ECONNRESET @clients.delete(client) end end end end ``` Let's go through the main changes: ### `Thread.new` in the constructor As soon as the server starts, we create a new thread, which does only one thing, accept new clients. This second thread starts an infinite loop, inside the loop we call `accept`, and block until it returns a new client. When we do receive a new client, we add it to the `@clients` instance variable, so that it can be used from the main thread, in the main loop. By moving the blocking call to `accept` to a different thread, we're not blocking the main loop with the `accept` call anymore. There are still issues with this implementation, `gets` is also a blocking call. We're improving things one step at a time. ### `client_command_with_args.nil?` The main loop is pretty different now. We start by iterating through the `@clients` array. The idea being that on each iteration of `loop`, we want to give each of the connected clients a chance to be handled. A `nil` value returned by gets means that we reached the end of the file, often called `EOF`. We can learn more about this in the documentation of the `eof?` method defined on [`IO`][ruby-doc-io-eof?], it is describes as: > Returns true if ios is at end of file that means there are no more data to read. The stream must be opened for reading or an IOError will be raised. In our case, we will see a `nil` value if the client either explicitly closed the connection with the `close` method on `IO` or if the process that started the connection was killed. This condition is essentially a first check to make sure that the client referenced by the `client` variable is still connected. One way to think about it is to imagine a phone call, if you started a phone call, left your phone on your desk to go pick up a pen and came back, you would probably resume by asking something like: "Are you still there?" and only if the person on the other end says yes, you would proceed to continue the conversation, if you don't hear anything, you would assume they hung up. If you only know smartphones, then this analogy might not make a lot of sense, because the screen would tell you if the call is still on. Believe me, there were phones without screens at some point, but you could also imagine that the screen was locked when you picked up the phone. Work with me here, please! If `gets` returns `nil`, there's no one on the other end anymore, the client hung up, we remove the entry from the list of connected clients. ### rescue ECONNRESET I am honestly not entirely sure about all the conditions that can cause this error, but I was able to trigger it if the client disconnects while we're blocked on the `gets` call, but only once some data was previously sent. In this case an `Errno::ECONNRESET` exception is raised. We catch it and remove the client we were handling when this happens, as it means that the connection cannot be used anymore. To reproduce this error, you can start the server with `ruby -r"./server_accept_thread" -e "BasicServer.new"` and run the following in an `irb` shell: ``` irb(main):051:0> socket = TCPSocket.new 'localhost', 2000 irb(main):052:0> socket.puts "GET 1" => nil irb(main):053:0> socket.close ``` {{% admonition info "Clients, Servers and failures" %}} When dealing with clients & servers, that is, code running in different processes, and potentially not running on the same machine, it is important to remember that a piece of code running on one machine can never really be sure that the other ones are in the state that they expect. The main difference with running code in a single process is that when two pieces of code run in difference processes, they do not share memory, you can't create a variable in one, and read its value from the other. On top of that, each process has its own life cycle, one process might be stopped, for various reasons, while the other might still be running. In concrete terms, it means that when we write code that will run on the server part, which is what we're doing here, we always have to keep in mind that a client that has connected in the past, may have disconnected by the time the server tries to communicate with it. There might be various reasons, to name a few, the client may have explicitly closed the connection, a network issue may have happened, causing the connection to be accidentally closed, or maybe the client code had an internal error, such as an exception being thrown and the process died. After creating the `client` variable, we have absolutely no guarantee that the client process on the other side is still connected. It is reasonable to assume that the client is still connected soon after when we call `client.gets`, and while unlikely, it's still important to keep in mind that the network communication might still fail. But what about later on, on the next iteration, and so on? We always have to expect that things might fail if we want our server to handle all the possible scenarios it might find itself in. This is what the check for `nil` and what the `rescue Errno::ECONNRESET` do. {{% /admonition %}} ### The rest The `else` branch inside the main loop is identical to what we started this chapter with, we use the blocking method `gets` to read from the client, and we write back a response. ### Still problematic We made a lot progress but there are still many issues with the last version we looked at. `gets` is a blocking call, and we iterate over the connected clients sequentially. If two clients connect to the server, client1 first and client2 second, but client1 never sends a command, client2 will never get a chance to communicate with the server. The server will wait forever on the `client.gets` call for client1. We need to fix this. ## Trying timeouts again There are different ways to make sure that all the connected clients get a chance to communicate with the server and to send their commands. Let's start with an approach we looked at earlier, timeouts. The pros and cons of using timeouts here are the same as they were when explored it as an option to prevent `accept` from blocking the server. It would be fairly inefficient to do so, even with a short timeout, we would wait for the timeout duration on each client, even when there's nothing to read. It might be fine with a handful of clients, but with a hundred clients, even a short timeout would be problematic. Even with a timeout of 10ms, if all the clients are waiting, not sending any commands, and only the 100th connected client sends a command, it would have to wait 990ms (99 clients * 10 ms) before its command is read by the server. I don't think it is that interesting to spend that much time with this approach since we've already established that it wasn't a good one, but you can experiment with it if you're interested. It is [in the `code` folder on GitHub][gets-with-timeout-gh] ## Read without blocking The title of this section says it all, we are going to use a non-blocking alternative, the explicitly named [`read_nonblock`][ruby-doc-io-read-nonblock]. A key difference is that it requires an int argument to set the maximum number of bytes that will be read from the socket. For reasons that I can't explain, it seems to be common practice to set it as a power of two. We could set it to a very low value, like 4, but then we wouldn't be able to read a whole `SET` command in one call. `SET 1 2` is seven bytes long. We could also set it to a very high value, like 4,294,967,296 (2^32), but then we would expose ourselves to instantiating a String of up to that length if a client decided to send one that large. As a quick non-scientific example, this would require about 4GB of RAM on the machine running the server. I confirmed this by opening an `irb` shell and monitoring its memory usage, either with `ps aux <pid>`, `top -o MEM` on macOS (`top -o %MEM` on linux) or the Activity Monitor app on macOS, creating a 1,000,000,000 byte long string, with `"a" * 1_000_000_000;`. The semi-colon is important, it returns `nil` and does not try to print the string to the terminal, which would take a little while. I then watched the memory consumption jump from a few megabytes to about one gigabyte. It seems to be common to choose an arbitrary length, one that is "long enough". Let's pick 256 for now, because we never expect commands to be longer than seven bytes for now, 256 gives us a lot to play with for now. ``` ruby def initialize # ... loop do @clients.each do |client| client_command_with_args = client.read_nonblock(256, exception: false) if client_command_with_args.nil? @clients.delete(client) elsif client_command_with_args == :wait_readable # There's nothing to read from the client, we don't have to do anything next elsif client_command_with_args.strip.empty? puts "Empty request received from #{ client }" else response = handle_client_command(client_command_with_args.strip) client.puts response end end end end ``` Only the content of the main loop changed. It starts the same way, by iterating through the `@clients` array, but the content of the `each` loop is different. We start by calling `read_nonblock`, with 256 as the `maxlen` argument. The default behavior of `read_nonblock` is to throw different exceptions when encountering eof and when nothing can be read, the `exception: false` argument allows us to instead only rely on the return value: - If the value is `nil`, we reached `EOF`. It would have raised `EOFError` without the `exception: false` argument - If the value is the symbol `:wait_readable`, there is nothing to read at the moment. It would have raised `IO::WaitReadable` without the `exception: false` argument. - Otherwise, it returns up to 256 bytes read from the socket A major improvement! No more explicit timeouts. That being said, we're still being fairly inefficient by manually cycling through all the clients. Sure, we're not doing that much if there's nothing to read, but we're still doing _something_, calling `read_nonblock`, when we would ideally not do anything given that there's nothing to read. There's a syscall for that! `select`, described in `man 2 select` as: > select() examines the I/O descriptor sets whose addresses are passed in readfds, writefds, and errorfds to see if some of their descriptors are ready for reading, are ready for writing, or have an exceptional condition pending, respectively ## Let's use `select` The `select` syscall is available in Ruby as a class method on the `IO` class : [`IO.select`][ruby-doc-io-select]. It is *blocking by default* and accepts between one and four arguments and returns an array containing three items, each of them being an array as well. Let's look closely at what all these arrays mean: - The first argument is mandatory, it is an array of sockets, `select` will look through all of them and, for each socket that has _something_ that can be read, will return it in the first of the three arrays returned. - The second argument is optional, it is also an array of sockets. `select` will look through all of them and, for each socket that can be written to, will return it in the second of the three arrays returned. - The third argument is optional as well, it is again an array of sockets. `select` will look through all of them and, for each socket that have pending exceptions, will return it in the third of the three arrays returned. - The fourth argument is optional. By default `select` is blocking, this argument is an integer telling `select` the maximum duration to wait for, and it will return `nil` if it wasn't able to return anything in time. {{% admonition warning "Third argument to select" %}} As of this writing, I am not aware of any conditions that would cause a socket to "have a pending exception". I will update this chapter if I learn more about it. {{% /admonition %}} The main use case we're interested in is the one related to the first argument. Our `@clients` array is a list of socket. If we pass it to `select` as the first argument, it will return a list of sockets that can be read from. In Chapter 1 we mentioned how setting timeouts is often a best practice. Here is a good example of when a timeout is not needed. It does not matter if our server waits forever to read for clients, it would only happen if no clients are sending commands. By blocking forever here we're not preventing the server from doing else, we're waiting because there is nothing else to do. ``` ruby def initialize # ... loop do # Selecting blocks, so if there's no client, we don't have to call it, which would # block, we can just keep looping if @clients.empty? next end result = IO.select(@clients) result[0].each do |client| client_command_with_args = client.read_nonblock(1024, exception: false) if client_command_with_args.nil? @clients.delete(client) elsif client_command_with_args == :wait_readable # There's nothing to read from the client, we don't have to do anything next elsif client_command_with_args.strip.empty? puts "Empty request received from #{ client }" else response = handle_client_command(client_command_with_args.strip) client.puts response end end end end ``` It's worth mentioning that the `each` loop that we removed did not exactly disappear, we delegated the iteration to the operating system. We have to assume that `select` does something similar internally, it has to iterate over the given array of file descriptors and do something with them. The difference is that by delegating such operation to the OS, we're not reinventing the wheel but we're also relying on an implementation that we can assume is well optimized. There's one more problem, and I swear, the next version will be the last one in this chapter. As previously mentioned, `select` blocks by default. If one clients connects, and never sends a command, the call to `IO.select` will never return. Meanwhile the thread dedicated to accepting new clients is still accepting clients, appending them to the `@clients` array. We could use the timeout argument, handle the case where the return value is nil, but as we discussed through the chapter, using a timeout would be inefficient. Imagine that two clients connect around the same time, the first one to connect does not send a command, the second one does. Regardless of the timeout, the second client would have to wait for the timeout to ellapse until the server acknowledges it. It would be great if the server could be more reactive, and not wait for timeouts. And the solution is ... `select`, again! I know, I know, this was anticlimactic, but `select` is very versatile. ## `select` everything Accepting a client is actually a different form of reading from a socket, so if we pass a server socket in the first array to `IO.select`, it will be returned if a new client attempted to connect. Let's demonstrate this in `irb`: ``` irb(main):001:0> require 'socket' => true irb(main):002:0> server = TCPServer.new(2000) irb(main):003:0> IO.select [server] => [[#<TCPServer:fd 10, AF_INET6, ::, 2000>], [], []] ``` The `select` call will only return after a client connects to the server. In the previous example, I used our good friend `nc` from Chapter 1: `nc -v localhost 2000`. Let's use this to remove the `accept` thread: ``` ruby def initialize @clients = [] @data_store = {} server = TCPServer.new 2000 puts "Server started at: #{ Time.now }" loop do result = IO.select(@clients + [server]) result[0].each do |socket| if socket.is_a?(TCPServer) @clients << server.accept elsif socket.is_a?(TCPSocket) client_command_with_args = socket.read_nonblock(1024, exception: false) if client_command_with_args.nil? puts "Found a client at eof, closing and removing" @clients.delete(socket) elsif client_command_with_args == :wait_readable # There's nothing to read from the client, we don't have to do anything next elsif client_command_with_args.strip.empty? puts "Empty request received from #{ socket }" else response = handle_client_command(client_command_with_args.strip) socket.puts response end else raise "Unknown socket type: #{ socket }" end end end end ``` And we finally have it, on each iteration we check if any of the connected clients has sent anything as well as whether or not there are new clients attempting to connect. ## But what about the real Redis? I'm glad you asked, we haven't mentioned Redis in a while, you know, the thing we're trying to replicate. So, how does Redis handle its clients? Well, I don't know if you're going to like the answer, but ... it depends. Redis uses different multiplexers (`select` is described in the man page as doing "synchronous I/O mutiplexing"), and tries to find the most efficient one. `select` is [apparently known to have limitations][select-problems] and seems to be limited to 1024 sockets. While it is not a problem for us to be limited to 1023 connected clients (keeping one for the server), it is reasonable to imagine that Redis would want to support more. It turns out that there are better alternatives, [kqueue][kqueue] on macOS and BSD, [epoll][epoll] on linux and evport on Solaris (I could not find a link for it). Redis defines its own event library, [`ae`][redis-ae], in the [`ae.c` file][redis-source-ae]. The interface for `ae` is then implemented with each of the libraries mentioned above, [in `ae_epoll.c`][ae-epoll], [in `ae_kqueue.c`][ae-kqueue], [in `ae_evport.c`][ae-evport] and [in `ae_select.c`][ae-select]. Redis [defines constants depending on what is available at compile time][redis-source-multiplexer-constants] and chooses the implementation [in server.c][redis-source-multiplexer-choice]. So, does Redis use `select`, probably not, but it could, if nothing else is available on the system it is being compiled on. The important part is that even if it doesn't, it uses alternatives that are conceptually similar to `select`. ## Conclusion It took a while and explored a few different options, with threads and timeouts, only to discard them all and use `select` for everything. That may seem like a waste of time but it is not, I think it's extremely important to look at what the alternatives are to fully understand and appreciate the benefit of a given solution. In the next chapter we'll add more commands to the server to make it a little bit closer to the real Redis server. ### Code The code from this chapter is [available on GitHub](https://github.com/pjambet/redis-in-ruby/tree/master/code/chapter-3) [redis-documentation-quit]:https://redis.io/commands/quit [select-syscall]:https://man7.org/linux/man-pages/man2/select.2.html [sidekiq-timeout-blog]:https://www.mikeperham.com/2015/05/08/timeout-rubys-most-dangerous-api/ [redis-source-multiplexer-choice]:https://github.com/redis-io/redis/blob/6.0.0/src/ae.c#L47-L61 [redis-source-multiplexer-constants]:https://github.com/redis-io/redis/blob/6.0.0/src/config.h#L76-L90 [ruby-doc-io-eof?]:http://ruby-doc.org/core-2.7.1/IO.html#eof-3F-method [gets-with-timeout-gh]:https://github.com/pjambet/redis-in-ruby/blob/master/code/chapter-3/server_accept_thread_and_gets_timeout.rb [ruby-doc-io-read-nonblock]:http://ruby-doc.org/core-2.7.1/IO.html#read_nonblock-method [ruby-doc-io-select]:http://ruby-doc.org/core-2.7.1/IO.html#select-method [select-problems]:http://www.moythreads.com/wordpress/2009/12/22/select-system-call-limitation/ [kqueue]:https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2 [epoll]:https://linux.die.net/man/4/epoll [redis-ae]:https://redis.io/topics/internals-rediseventlib [redis-source-ae]:https://github.com/redis/redis/blob/6.0.0/src/ae.c [ae-epoll]:https://github.com/redis-io/redis/blob/6.0.0/src/ae_epoll.c [ae-select]:https://github.com/redis-io/redis/blob/6.0.0/src/ae_select.c [ae-kqueue]:https://github.com/redis-io/redis/blob/6.0.0/src/ae_kqueue.c [ae-evport]:https://github.com/redis-io/redis/blob/6.0.0/src/ae_evport.c [ruby-doc-timeout]:http://ruby-doc.org/stdlib-2.7.1/libdoc/timeout/rdoc/Timeout.html <file_sep>/content/post/chapter-7-adding-list-commands.md --- title: "Chapter 7 Adding List Commands" date: 2020-10-02T17:25:58-04:00 lastmod: 2020-10-02T17:26:03-04:00 draft: false comment: false keywords: [] summary: "In this chapter we add support for a new data type, Lists. We implement all the commands related to lists, such as LPUSH, LRANGE & LLEN." --- ## What we'll cover So far we've mainly worked with Strings, and arrays of Strings. A command is received as an array of Strings. `GET` accepts a String and return a String, or a nil String. `SET` works with two Strings, a key and a value. We've also handled a few integers here and there, like for the result value of the `TTL` & `PTTL` commands. We are going to add full support for List related commands in this chapter. ## Redis Data Types When it comes to key/value pairs stored in the main keyspace, that is, the `@data_store` `Dict` instance, Redis supports [other data types][redis-data-types-doc] beside Strings: - Lists: An ordered collection of one or more Strings, sorted by order of insertion. - Sets: An unordered collection of unique Strings - Sorted Sets: An ordered collection of unique Strings. Strings are always added with a score, a float value, and the set orders them by their score. Uniqueness is enforced for the String value, multiple elements can have the same score. An example would be a list of user names, sorted by their age. The usernames are unique, but not the age: `{ <'pierre', 30>, <'james', 31>, <'jane', 32>, <'john', 32> }` - Hashes: An unordered collection of key/value pairs, where keys are unique. Keys and values are Strings. This is essentially the same data type we implemented in [Chapter 6][chapter-6]. - Bit arrays (or bitmaps): This one is slightly different than the other data types as it uses Strings under the hood, but through dedicated commands allows users to perform operations using said Strings as arrays of bits. An example of such command is `BITOP AND dest-key k1 k2`, which will perform an `AND` operation between the values at keys `k1` and `k2` and store the value in `dest-key`. - HyperLogLogs: A HyperLogLog (HLL for short) is a data structure optimized to trade space for efficiency when counting elements in a set. The main operation of an HLL is to count the number of unique elements. The result might not be exact, but the storage used by HLLs will always be extremely small regardless of how many items were counted. Similarly to Bit arrays, HLLs are implemented using Strings. A Set could be used to achieve a similar count operation, the difference being that the set will store each element, allowing it to return an accurate count, at the cost of its memory footprint being proportional to the size of the set. A HyperLogLog in Redis cannot grow larger than 12,288 (12k) bytes. - Streams: An append-only collection, conceptually similar to a log structure. Elements are key/value pairs and are by default ordered by the time they were added to the stream. Streams are a fairly complicated data structure, well documented on [the official website][redis-streams-doc] and will not be covered in this book. _Note about empty collections: Lists, Sets, Sorted Sets & Hashes cannot be empty, once the last element is deleted, the collection is removed from the keyspace._ _Note about integers: Redis handles integers in a way that can seem confusing. The type of a value is never specified, it is always a String. Whether you send the command `SET a-string-key a-string` or `SET an-integer-key 100`, the value is sent as a string. Internally Redis knows whether or not what was received as a String can be treated as an integer. In some cases it will optimize the way it stores the data based on whether or not it is an integer. There are even commands that will only work if a value can be treated as a number, such as the [INCR][redis-doc-incr] command._ **List related terms** Let's clarify some list related terms first. A list is often represented as a left to right sequence of elements. The left-most element is called the _head_ and the right-most element is called the _tail_. It is also common to use the term "tail" to describe all the elements after the head. According to this definition, the tail is another list, empty if the list itself has zero or one element, non empty otherwise. This is not the definition we'll use throughout this book. An empty list has no _head_ and no _tail_, or it could be said that they're both nil. For a one-element list, the _head_ and the _tail_ are equal. Elements can be added or removed from either side, left or right, as well as from within the list. Adding elements is commonly referred to as a _push_ and removing elements as a _pop_. The terms _shift_ and _unshift_ are also used, where _shift_ commonly means popping an element to the left of the list and _unshift_ pushing an element to the left. Finally, the terms _append_ & _prepend_ can also be used. In this context _append_ is similar to a right _push_, and _prepend_ is similar to a left _push_, or _unshift_. **Lists and other data structures** Lists can be used as the backing data structures for various more specific structures such as [queues][wikipedia-queues] and [stacks][wikipedia-stacks]. A list can be used as a queue by implementing the push operation as a "left push", that is, new elements are added to the left of the list, and the new element becomes the head of the list. Elements are removed with a "right pop", that is, elements are removed from the right of the list, the tail is removed and the element that preceded the tail becomes the new tail. This satisfies the **F**irst **I**n **F**irst **O**ut constraint of a queue. A list can be used as a stack by implementing the push operation as a "right push", that is, new elements are added to the right of the list, and the new element becomes the new tail. Elements are removed as a "right pop", similarly to how we described a queue above. This satisfies the **L**ast **I**n **F**irst **O**ut constraint of a stack. The choice of right and left in these two examples is arbitrary but also very common within western countries where languages are read and written left to right. Identical data structures could be implemented by reversing the side of each operations. A queue could be implemented by pushing new elements with a right push and removing them with a left pop. A stack could be implemented by pushing new elements with a left push and removing them with a left pop. **Redis List commands** Redis supports [eighteen list related commands][list-commands-docs]: - **LINDEX**: Gets an element by its index - **LINSERT**: Inserts an element - **LLEN**: Returns the length of the list - **LPOP**: Removes an element on the left of the list - **LPOS**: Returns the position of one or elements - **LPUSH**: Adds an element to the left of the list, creating it if needed - **LPUSHX**: Same as LPUSH, but does not create a new list if it doesn't already exist - **LRANGE**: Returns elements from the list - **LREM**: Removes one or more elements from the list - **LSET**: Replaces an element in a list - **LTRIM**: Keeps a subset of the list - **RPOP**: Removes an element on the right of the list - **RPOPLPUSH**: Removes an element to the right of a list and adds it to the left of another list - **RPUSH**: Adds an element to the right of the list, creating it if needed - **RPUSHX**: Same as RPUSH, but does not create a new list if it doesn't already exist - **BLPOP**: Blocking variant of LPOP - **BRPOP**: Blocking variant of RPOP - **BRPOPLPUSH**: Blocking variant of RPOPLPUSH ## How does Redis do it We've actually already implemented a list in the previous chapter to handle hash collisions and store multiple pairs in the same bucket. We could use a similar structure to implement all the list commands detailed previously but the list we used for the `Dict` implementation has a few limitations with regards to performance that would be problematic in some cases. **The need for a doubly linked list** The following is what we used to create a list of entries in a bucket: ``` ruby module BYORedis class DictEntry attr_accessor :next, :value attr_reader :key def initialize(key, value) @key = key @value = value @next = nil end end end ``` _listing 7.1 The linked list used for the `Dict` class_ We used the `class` syntax to control which getters and setters we wanted to be generated, with `attr_accessor` & `attr_reader`, but it could be simplified as the following: ``` ruby Node = Struct.new(:value, :next) ``` _listing 7.2 The Node struct_ Given the nature of Ruby's type system, `value` could be anything, and could therefore be a key/value pair if we passed a two-element array such as `[ 'a-key', 'a-value' ]`. This implementation is a "singly linked list". Each node has one "link" to its successor in the list, the `next` attribute in the previous example. If the link value is empty, then there's no successor and the element is the last one in the list. One problem with this approach is that adding or deleting an element at the end of list requires to iterate through the whole list, which will become slower and slower as the list grows. We covered this problem in the previous chapter when we explained the need for growing the hash table. A solution to this problem is to use what is commonly called a sentinel node, essentially a way to hold a reference to the tail of the list, for easy access to it, this would look like this: ``` ruby class List def initialize @head = nil @tail = nil end def prepend(element) # The new node is created with its next value set to @head, if @head was nil, the list was # empty, and new_node is now the head, its next value will also be nil. # If @head was not nil, new_node now points to what used to be the head new_node = Node.new(element, @head) # The head of the list is now the new node @head = new_node if @tail.nil? # If @tail is nil, the list was empty, and has now one element, the head and the tail are # the same node @tail = new_node end new_node end def append(element) # new_node will be the new tail, so its next value must be nil new_node = Node.new(element, nil) if @tail @tail.next = new_node else # If the list is empty, both @head and @tail are nil @head = @tail end # Update the @tail value to now point to new_node @tail = new_node new_node end end ``` _listing 7.3 A singly linked list with prepend & append operations_ The append operation is now O(1) with this implementation, it will require the same amount of steps regardless of the size of the list, it runs in constant time. While this is a big win, another common list operation, removing the tail, also known as right pop, cannot be optimized from O(n) to O(1) with this approach: ``` ruby def right_pop # If @tail is nil, the list is empty return nil if @tail.nil? # When the list has only one element, @head will be equal to @tail. In this case, popping from # the right or the left is effectively the same, and we can do so by setting both variables to # nil. The list is now empty if @head == @tail @head = nil @tail = nil nil elsif @head.next == @tail # If the second element, the one pointed at by @head.next is equal to @tail, the list has # only two elements @head.next = nil tail = @tail @tail = @head tail else # We now need a reference to the element pointing at @tail, so we can set its next value to # nil, instead of @tail, and set @tail to it, doing so will require iterating through all # the element in the list: cursor = @head.next # The number of steps this loop will go through is proportional to the size of the list, # making this method O(n) while cursor.next != @tail cursor = cursor.next end # We exited the loop, so the condition cursor.next == @tail is now true cursor.next = nil tail = @tail @tail = cursor tail end end ``` _listing 7.4 right_pop operation for a singly linked list_ We could keep going down this road, and optimize the `right_pop` method by adding a third instance variable to the `List` class, one that always holds a value the second to last node. With such a value we would not have to iterate through the list in the `else` branch. Maintaining the value would require a few more steps in the `append`, `prepend` & `pop` operations to always keep it pointing at the second to last element. This would still not allow us to efficiently implement all operations. The `LRANGE` command is used to return elements in the list, given two values `start` & `stop`. `LRANGE list 0 1` means "return the first two items of the list `list`, the one at index 0 and the one at index 1. `LRANGE list 0 3` means "return the first four items, the ones at indices 0, 1, 2 & 3, or put differently, all items between index 0 and 3. But the `LRANGE` command also supports a different syntax, with negative indices, to count elements starting from the tail. -1 means the last element in the list, -2, the second to last, and so on. Using this syntax we can return all the elements in the list with `LRANGE 0 -1`. We could also return the last three elements of the list with `LRANGE -3 -1`. The main benefit of negative indices is that you don't need to know the size of the list to return the last n elements. In the previous examples, if we knew the list had 10 elements, we could have used `LRANGE 7 9` to return the last three elements. But if an 11th element is added to the list, we would need to now send `LRANGE 8 10`. Using the negative index syntax, we can always use `LRANGE -3 -1`, regardless of the size of the list. As we've already discussed a few times, Redis should be able to handle really big data sets, in the case of lists, ideally ones with thousands, and even millions of elements. Being able to return the last n elements of large lists should ideally not require to iterate through the whole list, which, sadly, with a singly linked list, we'd be forced to do. A solution to this problem is to use a doubly linked list, one where each node contains a link to the next element but also one to the previous element. It's important to address right away that this approach comes with an important trade-off, we're now storing twice as much metadata per node, in exchange for potential speedups. A doubly linked list can be implemented with the following Ruby struct: ``` ruby DoublyLinkedNode = Struct.new(:value, :prev_node, :next_node) ``` _listing 7.5 The Doubly Linked List Struct_ We can now use this `DoublyLinkedNode` class in combination with the sentinel approach to implement the `LRANGE` command in an efficient manner: ``` ruby def range(start, stop) # The complete range method, which handles all the possible edge cases is implemented later # on, we're only showing a simplified version here, to highlight the benefits of the doubly # linked list # The "real" method should handle the case where only one of the two bounds is negative, such # as LRANGE 0 -1 list_subset = [] if start < 0 && stop < 0 && start <= stop current_index = -1 cursor = @tail while current_index >= start if current_index <= stop list_subset.prepend(cursor.value) end cursor = cursor.prev_node current_index -= 1 end end list_subset end ``` _listing 7.6 A partial range method implementation leveraging a doubly linked list_ As detailed in the comment, the previous example is not complete, but it shows how we can use the `prev_node` field to iterate from right to left instead of being forced to iterated from left to right with a singly linked list. We can also simplify the `right_pop` method. The `prev_node` field on each node removes the need for a third instance variable to hold the second to last node. ``` ruby def right_pop return if @tail.nil? tail = @tail @tail = @tail.prev_node if @tail @tail.next_node = nil else # If the list had only element, we removed it and the list is now empty, @tail is now nil # and we also need to set @head to nil @head = nil end tail end ``` _listing 7.7 The right_pop operation leveraging a doubly linked list_ Redis uses a doubly linked list approach, for the reasons we mentioned above, but it uses a more optimized version to reduce memory usage. On a 64-bit CPU, which is what most modern CPUs use, a pointer is a 64-bit integer, which uses 8 bytes (8 * 8 = 64 bits). So regardless of what the node actually stores, you need two pointers per node, one for the next node, one for the previous node, that's 16 bytes, per node. In a common case where each node would store an integer, which in C can have different sizes, as small as one byte and as big as 8, it means that even if you're storing a large integer, one that takes 8 bytes, you end up with 16 bytes of metadata, for 8 bytes of actual data. The problem is potentially even worse if you're storing smaller integer, say that the integers stored are small, 2 bytes for instance, you would end up with a node of 18 bytes where only 2 bytes are the actual data. This problem might not seem too bad with small lists but as the list grows, it would cause the server to waste a lot of memory to store these pointers. Redis uses two data structures to optimize for this problem. At the top level, it uses a structure it calls Quicklist, which is a doubly linked list where each element is a Ziplist. A Ziplist is a compact optimization of a doubly linked list that does not suffer from the metadata storage problem we described. Briefly summarizing a Ziplist is a complicated task, but it is conceptually close to how arrays work. It allocates a contiguous chunk of memory with `malloc(3)`. A key difference is that all elements in an array have the same size, so there's not need for metadata beyond the size of the array. If you're trying to get the 5th element in an array, you do so by multiplying the size of an element in the array by five, and use the value as an offset from the beginning of the array, and the value you found at that location is the fifth element in the array. Elements can have different sizes with a Ziplist, small integers, with a value between 0 and 12 will only use one byte, whereas larger integers, with values greater than 2,147,483,647 - the maximum value of an int32_t, which uses 4 bytes - will require 9 total bytes, 8 bytes for the value, an int64_t, and one byte of metadata. These variations in element sizes, which allows for greater optimizations, small elements take a small amount of space, means that the list needs to store some metadata to allow traversal of the list and access to the different elements. [Appendix A][appendix-a] explains in more details about Ziplist works, but does not provide a Ruby implementation. The Ziplist approach also shares some similarities with how SQL database systems organize data into pages. For reference [this page][postgres-page-layout] of the Postgres documentation explains in details the page layout. A key difference is that pages have a fixed size, whereas a ziplist will grow until it reaches its max size. The similarity is in the fact that they both operate on a set amount of memory which starts with some metadata followed by the actual data, organized in a compact sequence. The reason why Redis does not exclusively uses Ziplists is because as Ziplists grow, update operations such as adding or removing elements, become more and more costly. This mixed approach allows Redis to benefit from the best of both worlds, the quicklist maintains a list of ziplists, which actually hold the elements in the list. Each ziplist has a maximum size, and when it reaches it, a new ziplist node is created in the parent quicklist. This implementation is fairly complex so for the sake of simplicity we will use the basic doubly linked list approach shown above in this chapter. _The quicklist/ziplist approach might be implemented in a future chapter_ It is now time to add support for all the list commands to our server. ## Handling Incorrect Types Now that our server is about to handle more than one type, Strings and Lists, we need to consider the type of each key/value pair when processing commands. For instance, if a pair is first created as a String, with the `SET` command, calling `LLEN` on it, which attempts to return the length of a List, is invalid: ``` 127.0.0.1:6379> SET a-string a-value OK 127.0.0.1:6379> LLEN a-string (error) WRONGTYPE Operation against a key holding the wrong kind of value ``` Some commands work regardless of the type of the pair, such as `TTL` and `PTTL`: ``` 127.0.0.1:6379> TTL a-string (integer) -1 127.0.0.1:6379> RPUSH a-list 1 (integer) 1 127.0.0.1:6379> TTL a-list (integer) -1 ``` Redis has a [`TYPE`][redis-doc-type-command] command that can be used to return the type of a pair, the possible return values are: `string`, `list`, `set`, `zset`, `hash` and `stream`. If the key does not exist, it returns `none`. Let's add support for the `TYPE` command. So far we've repeated some code between all the commands, let's improve this by defining a `BaseCommand` class: ``` ruby module BYORedis class BaseCommand def initialize(data_store, expires, args) @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @data_store = data_store @expires = expires @args = args end def call raise NotImplementedError end end end ``` _listing 7.8 The BaseCommand class, parent of all command classes_ We can now define the `TypeCommand` class, which inherits from `BaseCommand`: ``` ruby module BYORedis class TypeCommand < BaseCommand def call Utils.assert_args_length(1, @args) key = @args[0] ExpireHelper.check_if_expired(@db, key) value = @db.data_store[key] case value when nil RESPSimpleString.new('none') when String RESPSimpleString.new('string') else raise "Unknown type for #{ value }" end end end end ``` _listing 7.9 The TypeCommand class_ The command is not that useful for now, it either returns `none` or `string`. We will add a new branch to the `case/when` statement when we add the `List` type. The next step is to add it to the `COMMANDS` constant in the `Server` class: ``` ruby # ... require_relative './pttl_command' require_relative './type_command' require_relative './command_command' module BYORedis class Server COMMANDS = Dict.new COMMANDS.set('command', CommandCommand) # ... COMMANDS.set('type', TypeCommand) MAX_EXPIRE_LOOKUPS_PER_CYCLE = 20 # ... end end ``` _listing 7.10 Updates to the Server class to support the TYPE command_ All the command classes we've created need `describe` class method, which is in turn used by the `CommandCommand` class to return the description of the command. The approach worked well so far but it is a bit verbose, and as we add more commands, becomes more and more annoying. Let's simplify this process with a struct, `Describe`, defined in `BaseCommand`: ``` ruby module BYORedis class BaseCommand Describe = Struct.new(:name, :arity, :flags, :first_key_position, :last_key_position, :step_count, :acl_categories) do def serialize [ name, arity, flags.map { |flag| RESPSimpleString.new(flag) }, first_key_position, last_key_position, step_count, acl_categories.map { |category| RESPSimpleString.new(category) }, ] end end end # ... end ``` _listing 7.11 The Describe Struct defined in the BaseCommand class_ We need to update the `CommandCommand` class as well, to use this new class: ``` ruby module BYORedis class CommandCommand < BaseCommand # ... def call RESPArray.new(SORTED_COMMANDS.map { |command_class| command_class.describe.serialize }) end def self.describe Describe.new('command', -1, [ 'random', 'loading', 'stale' ], 0, 0, 0, [ '@slow', '@connection' ]) end end end ``` _listing 7.12 The CommandCommand class using the Describe Struct_ We can now define the `self.describe` method in the `TypeCommand` with the following: ``` ruby module BYORedis class TypeCommand < BaseCommand ... def self.describe Describe.new('type', 2, [ 'readonly', 'fast' ], 1, 1, 1, [ '@keyspace', '@read', '@fast' ]) end end end ``` _listing 7.13 The TypeCommand class using the Describe struct_ We also need to update all the existing command classes: `DelCommand`, `GetCommand`, `SetCommand`, `TtlCommand`, & `PTtlCommand`. Doing so is fairly mechanical and is therefore not included here. You can find all the code from this chapter on [GitHub][code-github] ## Adding List Commands Now that we've explored the landscape of lists in Redis, it's time to add these functionalities to our server. We're going to start with the two commands that allow us to create a list, `LPUSH` & `RPUSH`. ### Creating a list with LPUSH & RPUSH There are two commands that allow clients to create a list, `LPUSH` & `RPUSH`. If the given key does not already exist and only one new element is passed to the command, they behave identically, they create a list and add the given element to it. The difference with this two commands occurs when the list already exists and has some elements in it or if multiple elements are passed. `LPUSH` adds them to the **L**eft and `RPUSH` adds them to the **R**ight. Both commands accepts one or more values, ``` 127.0.0.1:6379> LPUSH a-list a b c d (integer) 4 127.0.0.1:6379> LRANGE a-list 0 -1 1) "d" 2) "c" 3) "b" 4) "a" ``` In the previous example we can see that `LPUSH` added four elements to the newly created list `a-list`. It first added `a`, then `b` to the left, as the new head, and then `c` and `d` to the left as well, the final list is `[ 'd', 'c', 'b', 'a' ]`. We can try the same example but with `RPUSH`: ``` 127.0.0.1:6379> DEL a-list (integer) 1 127.0.0.1:6379> RPUSH a-list a b c d (integer) 4 127.0.0.1:6379> LRANGE a-list 0 -1 1) "a" 2) "b" 3) "c" 4) "d" ``` The subsequent elements, `b`, `c` & `d` were added as new tails, to the right, and the final list is: `[ 'a', 'b', 'c', 'd' ]`. Finally, if the key already exists and is not a List, Redis returns an error: ``` 127.0.0.1:6379> SET a b OK 127.0.0.1:6379> LPUSH a a (error) WRONGTYPE Operation against a key holding the wrong kind of value 127.0.0.1:6379> RPUSH a a (error) WRONGTYPE Operation against a key holding the wrong kind of value ``` Because most of the list commands will be small and related to each other, instead of creating one file per command as we've done so far, this time we'll create a single file `list_commands.rb` and define all the command classes in there. Let's start with `LPUSH`. Before creating the `LPushCommand`, we will start by reorganizing how the `Server` class and the different command classes interact with each other. So far we've passed the `@data_store` and `@expires` `Dict` instances, as well as the command arguments, to each command class. We will need to create more data structures to handle various list related commands, so to simplify this, we will wrap all these data structures inside a `DB` class. It's worth noting that this approach is conceptually similar to how the code is organized in the Redis codebase. Redis defines a [C struct for a DB type][redis-source-db-type]. The process of a looking up a list is slightly different than it is from a String. For commands such as `RPUSH` & `LPUSH`, we want to see if a list exists for the given key, but if it doesn't exist, we want to create a new list. Let's create a method in the `DB` class for this purpose: ``` ruby module BYORedis class DB attr_reader :data_store, :expires attr_writer :ready_keys def initialize @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @data_store = Dict.new @expires = Dict.new end def lookup_list(key) list = @data_store[key] raise WrongTypeError if list && !list.is_a?(List) list end def lookup_list_for_write(key) list = lookup_list(key) if list.nil? list = List.new @data_store[key] = list end list end end end ``` _listing 7.14 The new DB class_ We'll define the `WrongTypeError` shortly, when we add a few other utility methods. Let's now refactor the `BaseCommand` class to use the DB class: ``` ruby module BYORedis class BaseCommand # ... def initialize(db, args) @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @db = db @args = args end end end ``` _listing 7.15 Updates to the BaseCommand class to support the DB class_ And finally, let's update the `Server` class: ``` ruby # ... module BYORedis class Server # ... def initialize @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @clients = Dict.new @db = DB.new @server = TCPServer.new 2000 # ... end # ... def handle_client_command(command_parts) @logger.debug "Received command: #{ command_parts }" command_str = command_parts[0] args = command_parts[1..-1] command_class = COMMANDS[command_str.downcase] if command_class command = command_class.new(@db, args) command.call else # ... end end # ... end end ``` _listing 7.16 Updates to the Server class to support the DB class_ Both `LPUSH` & `RPUSH` accept at least two arguments, the key and one or more elements to add. The validation of the number of arguments is very similar across commands, so let's create a helper method for that. Let's first create a `Utils` module and add it there: ``` ruby module BYORedis InvalidArgsLength = Class.new(StandardError) do def resp_error(command_name) RESPError.new("ERR wrong number of arguments for '#{ command_name }' command") end end WrongTypeError = Class.new(StandardError) do def resp_error RESPError.new('WRONGTYPE Operation against a key holding the wrong kind of value') end end module Utils def self.assert_args_length(args_length, args) if args.length != args_length raise InvalidArgsLength, "Expected #{ args_length }, got #{ args.length }: #{ args }" end end def self.assert_args_length_greater_than(args_length, args) if args.length <= args_length raise InvalidArgsLength, "Expected more than #{ args_length } args, got #{ args.length }: #{ args }" end end end end ``` _listing 7.17 The new Utils module_ We can now call `Utils.assert_args_length_greater_than(1, @args)` to validate the number of arguments for the `LPUSH` & `RPUSH` commands. Doing so will raise a `InvalidArgsLength` exception. Let's add a `rescue` statement for this exception, as well as for the `WrongTypeError` we used earlier in the `DB` class. Let's do this in the `BaseCommand` so that all classes benefit from it: ``` ruby module BYORedis class BaseCommand # ... def execute_command call rescue InvalidArgsLength => e @logger.debug e.message command_name = self.class.describe.name.upcase e.resp_error(command_name) rescue WrongTypeError => e e.resp_error end def call raise NotImplementedError end end end ``` _listing 7.18 Updates to the BaseCommand class to catch shared exceptions_ This is an application of the [template method pattern][template-method-pattern]. The base class defines logic around the `call` method, and it is up to the subclasses to define the actual logic of the `call` method. We need to update the `Server` class to now call the `execute_command` method instead: ``` ruby module BYORedis class Server # ... def handle_client_command(command_parts) @logger.debug "Received command: #{ command_parts }" command_str = command_parts[0] args = command_parts[1..-1] command_class = COMMANDS[command_str.downcase] if command_class command = command_class.new(@db, args) command.execute_command else # ... end end end end ``` _listing 7.19 Updates to the Server class to use the execute_command method_ We already know we are going need a very similar feature soon, for the `RPUSH` command, so we're first defining a set of shared methods: ``` ruby module BYORedis module ListUtils def self.common_lpush(list, elements) elements.each { |element| list.left_push(element) } RESPInteger.new(list.size) end def self.common_rpush(list, elements) elements.each { |element| list.right_push(element) } RESPInteger.new(list.size) end def self.common_find(args) Utils.assert_args_length_greater_than(1, args) yield args[0] end def self.find_or_create_list(db, args) common_find(args) do |key| db.lookup_list_for_write(key) end end end end ``` With all this refactoring out of the way, we can now define the `LPushCommand`: ``` ruby require_relative './list' module BYORedis class LPushCommand < BaseCommand def call list = ListUtils.find_or_create_list(@db, @args) values = @args[1..-1] ListUtils.common_lpush(list, values) end def self.describe Describe.new('lpush', -3, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write','@list', '@fast' ]) end end end ``` _listing 7.20 Adding list_commands.rb and the `LPushCommand` class_ We first use `Utils.assert_args_length_greater_than` to validate that we have at least two arguments. We then lookup a list, creating it if doesn't exist and failing if the key already exists and is of a different type. Finally, we iterate over all the remaining arguments and push them to the left of the list with `list.left_push` and return the size of list. There's a major problem, the `List` class does not exist yet! Let's address this now: ``` ruby module BYORedis class List ListNode = Struct.new(:value, :prev_node, :next_node) attr_accessor :head, :tail, :size def initialize @head = nil @tail = nil @size = 0 end def left_push(value) new_node = ListNode.new(value, nil, @head) if @head.nil? @tail = new_node else @head.prev_node = new_node end @head = new_node @size += 1 end end end ``` _listing 7.21 The `List` class_ The class defines a doubly linked list, similar to what we shown earlier in the chapter. The list is initialized with a size of 0, and nil values for `@head` and `@tail`. The `left_push` method behaves differently depending on whether the list was empty or not. We start by creating a new node, with the given value, and setting the `prev_node` attribute to `nil`, given that the new element will be the new head, it does not have a previous element in the list. The next element is set to `@head`, which may be `nil` if the list was empty. If the list was empty, which we check with `if @head.nil?`, then the new element is also the tail of the list, and we update the `@tail` attribute as such. Otherwise, we update the old head's previous node, which is still the value held by `@head`, to the new node. In other words, the old head now has a previous element in the list. Finally, we update `@head` to the new node and increment the size of the list. We need to require the `list_commands` file in the `server.rb` file as well as adding `LPushCommand` to the `COMMANDS` constant: ``` ruby # ... require_relative './list_commands' # ... module BYORedis class Server COMMANDS = Dict.new COMMANDS.set('command', CommandCommand) COMMANDS.set('del', DelCommand) COMMANDS.set('get', GetCommand) COMMANDS.set('set', SetCommand) COMMANDS.set('ttl', TtlCommand) COMMANDS.set('pttl', PttlCommand) COMMANDS.set('lpush', LPushCommand) # ... end end ``` _listing 7.22 Updates to the Server class to support the LPUSH command_ Now that lists can be added to the keyspace, let's handle `List` values in the `ListCommand` class: ``` ruby module BYORedis class TypeCommand < BaseCommand def call # ... case value when nil RESPSimpleString.new('none') when String RESPSimpleString.new('string') when List RESPSimpleString.new('list') else raise "Unknown type for #{ value }" end end # ... end end ``` _listing 7.23 Update to the TypeCommand to support the List type_ The `RPushCommand` is very similar to the `LPushCommand`: ``` ruby module BYORedis # ... class RPushCommand < BaseCommand def call list = ListUtils.find_or_create_list(@db, @args) values = @args[1..-1] ListUtils.common_rpush(list, values) end def self.describe Describe.new('rpush', -3, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@list', '@fast' ]) end end end ``` _listing 7.24 The RPushCommand class_ The class is almost identical to `LPushCommand`, except that we call `right_push` on the list instead, so let's add this method to the `List` class: ``` ruby module BYORedis class List # ... def right_push(value) new_node = ListNode.new(value, @tail, nil) if @head.nil? @head = new_node else @tail.next_node = new_node end @tail = new_node @size += 1 end end end ``` _listing 7.25 The List#right_push method_ The `right_push` method is also similar to `left_push` and also behaves differently whether or not the list was empty. We start by creating the new node, where the previous node value is set to what the tail was. If the list was empty, this value will be `nil` and the new element will be the only element in the list, otherwise its previous node value will point at the old tail. If the list was empty, we also need to update the head value. Otherwise, we need to update the next node value of the old tail to point to the new node. Finally, we update the value of `@tail` and increment the size of list. **The \*X variants, LPUSHX & RPUSHX** There are two more commands, almost identical to `LPUSH` & `RPUSH`, `LPUSHX` & `RPUSHX`. The only difference is that these two commands only push new elements to the list if it already exists. If the list does not already exist, it returns 0, otherwise it returns the new size of the list, like `LPUSH` & `RPUSH` do. Given that these commands share a good amount of logic, let's add a few more helpers to the `ListUtils` module: ``` ruby module BYORedis # ... module ListUtils # ... def self.find_list(db, args) common_find(args) do |key| db.lookup_list(key) end end def self.common_xpush(list) if list.nil? RESPInteger.new(0) else yield end end end # ... end ``` _listing 7.26 The ListUtils module_ We can now create the `LPushXCommand` and `RPushXCommand` classes: ``` ruby module BYORedis # ... class LPushXCommand < BaseCommand def call list = ListUtils.find_list(@db, @args) values = @args[1..-1] ListUtils.common_xpush(list) do ListUtils.common_lpush(list, values) end end def self.describe Describe.new('lpushx', -3, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@list', '@fast' ]) end end end ``` _listing 7.27 The LPushXCommand_ The only difference is that we call `@db.lookup_list(key)` instead of `@db.lookup_list_for_write(key)`. ``` ruby module BYORedis # ... class RPushXCommand < BaseCommand def call list = ListUtils.find_list(@db, @args) values = @args[1..-1] ListUtils.common_xpush(list) do ListUtils.common_rpush(list, values) end end def self.describe Describe.new('rpushx', -3, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@list', '@fast' ]) end end end ``` _listing 7.28 The RPushXCommand_ We now have four List related commands, which allow us to add elements to a list, but we don't have any way to read the content of the list. This is what the `LRANGE` command was created for. ### Reading a list with LRANGE The `LRANGE` command accepts three arguments, a key, a start index and a stop index. It returns all the elements in the list stored at the given key, between the start and stop indices. As discussed earlier in the chapter, it supports a special syntax, with negative indices, to index element from the right instead of from the left. Another important piece of the `LRANGE` command is that it does not return errors for out of bound indices or for out of order start and stop values. Let's look at few examples first. ``` 127.0.0.1:6379> RPUSH a-list a b c d e f (integer) 6 ``` The `a-list` list contains the following elements, `[ 'a', 'b', 'c', 'd', 'e', 'f' ]`. The index of the element, `'f'` is 5, but `LRANGE` silently ignores this if we ask for all the elements up to index 10 for instance: ``` 127.0.0.1:6379> LRANGE a-list 0 10 1) "a" 2) "b" 3) "c" 4) "d" 5) "e" 6) "f" ``` It returned all the elements in the given range, and ignored the fact that there are no elements between index 6 and 10. The same logic works the other way, with negative indices, `'f'` is at index `-1`, and `'a'` is at index `-6`. There is no element at index `-7` and beyond: ``` 127.0.0.1:6379> LRANGE a-list -10 -6 1) "a" ``` And Redis returns empty arrays if the whole request is outside the list: ``` 127.0.0.1:6379> LRANGE a-list -10 -7 (empty array) 127.0.0.1:6379> LRANGE a-list 6 10 (empty array) ``` Finally, the following commands don't make any sense, since the start value is after the stop value, and Redis returns an empty array in this case: ``` 127.0.0.1:6379> LRANGE a-list 2 1 (empty array) 127.0.0.1:6379> LRANGE a-list -1 -2 (empty array) ``` Let's implement the logic for the `LRANGE` command: ``` ruby module BYORedis # ... class LRangeCommand < BaseCommand def call Utils.assert_args_length(3, @args) key = @args[0] start = OptionUtils.validate_integer(@args[1]) stop = OptionUtils.validate_integer(@args[2]) list = @db.lookup_list(key) if list.nil? EmptyArrayInstance else ListSerializer.new(list, start, stop) end end def self.describe Describe.new('lrange', 4, [ 'readonly' ], 1, 1, 1, [ '@read', '@list', '@slow' ]) end end end ``` _listing 7.29 The LRange Command_ We use another argument length validator, in this case we always require three arguments. We then need to validate that the second and third arguments are integers, we do so with a new validator method, `validate_integer`: ``` ruby module BYORedis ValidationError = Class.new(StandardError) do def resp_error RESPError.new(message) end end module OptionUtils def self.validate_integer(str) Integer(str) rescue ArgumentError, TypeError raise ValidationError, 'ERR value is not an integer or out of range' end def self.validate_float(str, field_name) Float(str) rescue ArgumentError, TypeError raise ValidationError, "ERR #{ field_name } is not a float or out of range" end end end ``` _listing 7.30 The OptionsUtils module_ The module also includes a `validate_float` method, which is very similar to the `validate_integer` method. We will need the `validate_float` method later on in this chapter. Similarly to `InvalidArgsLength`, we need to handle `ValidationError` in the `execute_command` method in `BaseCommand`: ``` ruby module BYORedis class BaseCommand # ... def execute_command call rescue InvalidArgsLength => e @logger.debug e.message command_name = self.class.describe.name.upcase e.resp_error(command_name) rescue WrongTypeError, ValidationError => e e.resp_error end end end ``` _listing 7.31 Updates to the BaseCommand class to support ValidationError exceptions_ We delegate the actual serialization logic to a dedicated class, `ListSerializer`, given that the logic requires the handling of many edge cases. Let's look at the class: ``` ruby module BYORedis # ... class ListSerializer attr_reader :start, :stop, :list attr_writer :start, :stop def initialize(list, start, stop) @list = list @start = start @stop = stop end def serialize @stop = @list.size + @stop if @stop < 0 @start = @list.size + @start if @start < 0 @stop = @list.size - 1 if @stop >= @list.size @start = 0 if @start < 0 return EmptyArrayInstance.serialize if @start > @stop response = '' size = 0 distance_to_head = @start distance_to_tail = @list.size - @stop if distance_to_head <= distance_to_tail iterator = List.left_to_right_iterator(@list) within_bounds = ->(index) { index >= @start } stop_condition = ->(index) { index > @stop } accumulator = ->(value) { response << RESPBulkString.new(value).serialize } else iterator = List.right_to_left_iterator(@list) within_bounds = ->(index) { index <= @stop } stop_condition = ->(index) { index < @start } accumulator = ->(value) { response.prepend(RESPBulkString.new(value).serialize) } end until stop_condition.call(iterator.index) if within_bounds.call(iterator.index) accumulator.call(iterator.cursor.value) size += 1 end iterator.next end response.prepend("*#{ size }\r\n") end end end ``` _listing 7.32 `ListSerializer` in list.rb_ The class implements an interface similar to the classes in `resp_types.rb`, which allows us to return it from the `call` method, and let the `Server` class call `.serialize` on the value returned by `execute_command`. The `serialize` method is fairly long, so let's look at it one line at a time: The first two lines take care of negative indices. If either `start` or `stop` are negative, we convert them to a 0-based index by adding the negative value to the size of list. Let's illustrate this with an example. ``` ruby list = [ 'a', 'b', 'c' ] # list.size == 3 stop = -1 stop = 3 + stop # stop == 2 list[stop] == 'c' # stop is the last index of the array start = -2 start = 3 + start # start == 1 list[start] == 'b' # start is the second to last index of the array ``` The next two lines take care of out of bound indices. If `stop` is greater than the last index of the list, `size - 1`, then we set it to that value. There's no need to keep iterating once we reached the last element. Similarly, if stop is lower than `0`, we set it to `0`, there is no element before the one at index `0`, so there's no need to look there. Once the indices have been sanitized, we can return early if `start > stop`, as we've shown above, this is nonsensical and we return an empty array right away. The next step is an optimization to speed up the iteration process. Depending on the values of `start` & `stop`, it might be more interesting to start iterating from the head of the list, or from the tail. Imagine a list with one million elements it would be great if `LRANGE -1 -1`, which returns the tail of the list, would run in O(1) time, and not in O(n) time. Our `List` class holds a reference to the tail, so it is feasible to return it without iterating through the list. We achieve this with the `distance_to_head` & `distance_to_tail` variables. If `start` is `0`, there is no need for "empty iterations" to reach the first element we need to return, but if `start` were, say, 100, we would need to iterate 100 times to reach the first element we need to return. The same goes for `distance_to_tail`, if `list.size - stop` is equal to 0, the last element of the list needs to be returned, so there's no need for empty iterations, but if stop were, say, 2, in a list of 100 elements, we'd need 98 empty iterations from the right to reach the last element that needs to be returned. If `distance_to_head` is smaller than `distance_to_tail`, it'll be faster to reach the sublist that needs to be returned if we start from the head, and if `distance_to_tail` is smaller, then it'll be faster to start from the tail. We could have written two `while/until` loops in each branch of the `if/else` condition, but instead we chose to define a few `proc`s that will determine the direction of the iteration, so that we can write a single loop below. Because this is a common pattern across list commands, we define an `Iterator` struct as well as two helpers to return the two common iterators: ``` ruby module BYORedis class List # ... Iterator = Struct.new(:cursor, :index, :cursor_iterator, :index_iterator) do def next self.cursor = cursor_iterator.call(cursor) self.index = index_iterator.call(index) end end # ... def self.left_to_right_iterator(list) # cursor, start_index, iterator, index_iterator Iterator.new(list.head, 0, ->(node) { node.next_node }, ->(i) { i + 1 }) end def self.right_to_left_iterator(list) # cursor, start_index, iterator, index_iterator Iterator.new(list.tail, list.size - 1, ->(node) { node.prev_node }, ->(i) { i - 1 }) end # ... end end ``` _listing 7.33 The new Iterator class in the List class_ We define the starting index for the iteration, `0` in the left to right iteration, `size - 1` for a left to right iteration. The `cursor` attribute of the `Iterator` instance will be set to each node of the list, its initial value is `list.head` if we start from the left and `list.tail` if we start from the right. The `cursor_iterator` attribute is a proc that determines how to get the following node in the list. If we're iterating from left to right, we need to get the node at `next_node`, and if we're iterating from right to left, we need to get the node at `prev_node`. Similarly, `index_iterator` is a proc that updates the current index value, it increments it for a left to right iteration and decrements it for a right to left iteration. `within_bounds` is a proc that returns a boolean for an index, which indicates if the current index is within the bounds of the requested range. If we're iterating from left to right, as soon as the current index reaches the value of `start`, we need to start accumulating the elements we find. The condition is different for a right to left iteration, we need to start accumulating elements as soon as the current index is lower or equal to stop. Let's look at few examples to illustrate this: ``` ruby list = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ] # size is 7, last index is 6 ``` If `start` is `1` and `stop` is `2`, the returned list should be `[ 'b', 'c' ]` and we'll start iterating from the head. `index` will be initialized at `0`, on the next iteration it'll be `1`, which will cause the `within_bounds` proc to return `true` since `1 >= 1`. On the next iteration `index` will be two and `within_bounds` will return `true` again. On the next iteration `index` will be 3, which it outside the bounds of the given range, so we could return at this point. We achieve this with the `stop_condition` proc. In this example it'll be `index > stop`, and since `3 > 2`, the `until` loop will stop. The accumulation process works with the `response` string. In a left to right iteration we append new values to this string with `<<` and in a right to left operation we prepend to it with the `prepend` method. The last step of the method is to add the size of the RESP array at the beginning of the string, to follow the RESP protocol. We do this with `response.prepend("*#{ size }\r\n")`. Now that we can add elements to a list, and read elements from a list, it's time to add commands to remove elements. ### Removing items with LPOP & RPOP The main two commands to remove elements from a list are `LPOP` & `RPOP`. `LPOP` pops an element from the **L**eft and `RPOP` pops an element from the **R**ight. Both commands accept a single arguments, the key for the list. If a pair exists for this key, but is not a list, an error is returned. If no pairs exist, a `nil` string is returned. Redis does not keep empty lists in memory, as can be shown in the next example, so if the last element is popped form the list, we need to remove the pair from `@db.data_store`: ``` 127.0.0.1:6379> RPUSH a-list a b (integer) 2 127.0.0.1:6379> LPOP a-list "a" 127.0.0.1:6379> LPOP a-list "b" 127.0.0.1:6379> TYPE a-list none ``` Let's create the `LPopCommand` class, but first, similarly to how we approached the `LPUSH` & `RPUSH` commands, we know we're going to need very similar functionality with `LPOP` & `RPOP`, so let's define shared methods in `ListUtils` first: ``` ruby module BYORedis # ... module ListUtils # ... def self.common_pop(db, args) Utils.assert_args_length(1, args) key = args[0] list = db.lookup_list(key) if list.nil? NullBulkStringInstance else value = yield key, list RESPBulkString.new(value) end end end # ... class LPopCommand < BaseCommand def call ListUtils.common_pop(@db, @args) do |key, list| @db.left_pop_from(key, list) end end def self.describe Describe.new('lpop', 2, [ 'write', 'fast' ], 1, 1, 1, [ '@write', '@list', '@fast' ]) end end end ``` _listing 7.34 The LPopCommand using a shared method from ListUtils_ We could call the not implemented yet `left_pop` method from the `call` method directly, but because the process of checking if the list is now empty and removing it from the keyspace is so common, we wrap this logic in the `DB#left_pop_from` method. Let's create this method: ``` ruby module BYORedis class DB # ... def left_pop_from(key, list) generic_pop_wrapper(key, list) do list.left_pop end end private def generic_pop_wrapper(key, list) popped = yield @data_store.delete(key) if list.empty? if popped popped.value else @logger.warn("Unexpectedly popped from an empty list or a nil value: #{ key }") nil end end end end ``` _listing 7.35 The proxy method in the DB class to handle deletions of empty lists_ `left_pop_from` starts by calling `generic_pop_wrapper` with the `key` & `list` values as well as with a block calling `left_pop` on the list. `generic_pop_wrapper` allows us to define logic that is agnostic of which pop operations we're performing. It starts by calling `yield`, which is assuming to pop a value from the list, either from the left or from the right. It then proceeds to delete the list from `@data_store` if the list is now empty. It is expected that `popped` will never be `nil`, since we only keep non-empty lists in `@data_store`, but as a way to be extra cautious, we log a warning and return `nil` if `popped` happened to be `nil`. We can now define `RPopCommand`: ``` ruby module BYORedis # ... class RPopCommand < BaseCommand def call ListUtils.common_pop(@db, @args) do |key, list| @db.right_pop_from(key, list) end end def self.describe Describe.new('rpop', 2, [ 'write', 'fast' ], 1, 1, 1, [ '@write', '@list', '@fast' ]) end end end ``` _listing 7.36 The RPopCommand class_ Let's also define `right_pop_from` in `DB`: ``` ruby module BYORedis class DB # ... def right_pop_from(key, list) generic_pop_wrapper(key, list) do list.right_pop end end end end ``` _listing 7.37 The proxy method in the DB class to handle empty list deletions after a right pop_ ### Removing from a list and adding to another with RPOPLPUSH A common use case for Redis is to use lists as queues, where elements are added from the left, with `LPUSH`, and removes from the right, with `RPOP`, this makes the list a FIFO, **F**irst **I**n **F**irst **O**ut, queue, where the order of insertion defines the order of processing. For an extra layer of reliability, it can be convenient to keep the popped element in another list to make sure that even if the process in charge of processing the message fails to complete it, the message won't be lost and will still be in the processing queue. **A use case for `RPOPLPUSH`** An example of such use case is an e-commerce site with a subscription component. Let's imagine that there is a system in charge of processing subscriptions, each day at 1am it processes the subscriptions for the day, creating orders for customers and charging them for the amount of the order. We could implement this process by calling `LPUSH` for each subscription that needs to be processed that day and having one or worker processes continuously calling `RPOP` for that list. Each message would contain enough information to process the order. This approach of queuing messages for processing by separate workers is fairly common as it allows for easy scaling of the number of workers. It only needs a single process to run on a schedule, find all the subscriptions that need to be processed and adds them to the queue. On the other end of the queue, there could be one or more workers, picking up messages and processing them. There could even be an auto-scaling systems that adds workers based on the size of the queues. If tens of thousand of subscriptions need to be processed, many workers could be started to speed up the process. Now, imagine that the system in charge of handling the payment portion is having some issues and is causing some errors, we would still want to process these orders later on, when the payment system is back online. This is where the idea of a queue dedicated to keeping the items being processed is useful. The worker processes would call `RPOP`, and before processing the message, would call `LPUSH` to add the message to the processing queue. With this approach, regardless of what happens to the worker, the message is safe in the processing list. There might be another process in charge of scanning the processing list and retrying the message at a later point. If no errors happen, the worker must delete the message from the processing queue, to signify that it is fully processed. The problem with this approach is that things can still go wrong, networks encounter issues, and there is no guarantee that the `LPUSH` operation will work, even if the `RPOP` operation was successful. In other words, with `RPOP`, the messages leaves the Redis server completely, and even if we try to put it back with `RPUSH`, this is not guaranteed to succeed. Another worst-case scenario, which is not that uncommon in my experience, is that something goes wrong on the client side, after receiving the message from `RPOP` but before sending it back with `RPUSH`. There are different ways in which _something_ could go wrong, like an unhandled exception for instance. That being said, many workers are setup with some `try/catch`/`begin/rescue` wrappers to handle such cases, but the likelihood of a bug is still there. Additionally, with some platforms such as the JVM, it is also possible to observe exceptions such as `OutOfMemoryError`. These errors are usually rare, but still likely to happen, at _some_ point, for any large enough project. This is the problem that `RPOPLPUSH` solves, in one operation, it pops an element from the right of a list, and pushes it to the left of another. The message never leaves Redis. **The `RPopLPushCommand` class** If the source key is nil, a `nil` string is returned, and if it exists but is not a list, an error is returned. Otherwise, it pops an element, again deleting the list from the keyspace if the list ends up empty, and pushes the element to the destination. Destination is created if it does not already exist, and an error is returned if it already exists and is not a list: ``` ruby module BYORedis class RPopLPushCommand < BaseCommand def call Utils.assert_args_length(2, @args) source_key = @args[0] source = @db.lookup_list(source_key) if source.nil? NullBulkStringInstance else destination_key = @args[1] if source_key == destination_key && source.size == 1 source_tail = source.head.value else destination = @db.lookup_list_for_write(destination_key) source_tail = @db.right_pop_from(source_key, source) destination.left_push(source_tail) end RESPBulkString.new(source_tail) end end def self.describe Describe.new('rpoplpush', 3, [ 'write', 'denyoom' ], 1, 2, 1, [ '@write', '@list', '@slow' ]) end end end ``` _listing 7.38 The RPopLPushCommand class_ We do not use any new methods here. We initially call `lookup_list` for the source list, and return early if it doesn't exist. We then call `lookup_list_for_write` for the destination, creating the list if it does not already exist. We then pop from the source, with the `right_pop_from` method, which deletes the list if it is now empty, and then call `left_push` to the `destination` list. The returned value is the element that was popped and pushed. It's worth nothing that `RPOPLPUSH` can be used with the same list as source and destination, which ends up moving the tail of the list to the head. This creates an edge case if the list has a single element, if so, we don't have to do anything, and we can simply return the head of the list, or the tail, since they're the same value. We have to do this because otherwise calling `@db.right_pop_from(source_key, source)` would cause the deletion of the list, which we want to avoid. ### A bunch of useful utility commands Redis defines a few more list commands: **`LINDEX` - The element at a given index** `LINDEX` accepts two arguments, a key and the index of the element we want to return. Similarly to `LRANGE`, `LINDEX` accept negative indices. If there is an existing pair and it is not a list, an error is returned. If the index is out of bounds, a `nil` string is returned. ``` ruby module BYORedis # ... class LIndexCommand < BaseCommand def call Utils.assert_args_length(2, @args) key = @args[0] index = OptionUtils.validate_integer(@args[1]) list = @db.lookup_list(key) if list.nil? NullBulkStringInstance else value_at_index = list.at_index(index) if value_at_index RESPBulkString.new(value_at_index) else NullBulkStringInstance end end end def self.describe Describe.new('lindex', 3, [ 'readonly' ], 1, 1, 1, [ '@read', '@list', '@slow' ]) end end end ``` _listing 7.39 The LIndex class_ Let's add the `List#at_index` method: ``` ruby module BYORedis class List # ... def at_index(index) index += @size if index < 0 return if index >= @size || index < 0 distance_to_head = index distance_to_tail = @size - index if distance_to_head <= distance_to_tail iterator = List.left_to_right_iterator(self) else iterator = List.right_to_left_iterator(self) end while iterator.cursor return iterator.cursor.value if iterator.index == index iterator.next end end end end ``` _listing 7.40 The List#index method_ The `at_index` method makes use of the `Iterator` helpers, since we also want to iterate from the right side if the given index is closer to the tail. We also perform the same sanitation step to transform a negative index into a positive 0-based index. **`LPOS` - The index (or indices) of element(s) matching the argument** The `LPOS` command supports three options: `COUNT`, `MAXLEN` & `RANK`. `COUNT` determines the maximum number of elements that can be returned if multiple elements match the argument. By default `LPOS` returns one or zero index, for the first element being equal to the argument, starting from the left, but if `COUNT` is given, it returns an array, empty if no elements were found, or containing all the indices of element being equal to the argument. `RANK` can be used to skip some matches and return the n-th one, from the left with a positive rank and from the right with a negative rank. A rank value cannot be zero or negative, and a rank value of 1 is the default, return the first match starting from the head. A rank value of -1 will return the last match. A rank value of 2 will return the second match, from the left, and -2, the second to last element, or second element from the right, and so on. The last option, `MAXLEN`, can be used to limit the number of elements that will be scanned. By default `LPOS` will scan up to the whole list, but with `MAXLEN n`, it will stop after n elements. The options can be combined, for instance `LPOS a-list element RANK -1 MAXLEN 10` will only look at the last ten elements of the list when trying to find the index of element. ``` ruby module BYORedis ZeroRankError = Class.new(StandardError) do def message 'ERR RANK can\'t be zero: use 1 to start from the first match, 2 from the second, ...' end end NegativeOptionError = Class.new(StandardError) do def initialize(field_name) @field_name = field_name end def message "ERR #{ @field_name } can\'t be negative" end end # ... class LPosCommand < BaseCommand def initialize(db, args) super @count = nil @maxlen = nil @rank = nil end def call Utils.assert_args_length_greater_than(1, @args) key = @args.shift element = @args.shift list = @db.lookup_list(key) parse_arguments unless @args.empty? if list.nil? NullBulkStringInstance else position = list.position(element, @count, @maxlen, @rank) if position.nil? NullBulkStringInstance elsif position.is_a?(Array) RESPArray.new(position) else RESPInteger.new(position) end end rescue ZeroRankError, NegativeOptionError => e RESPError.new(e.message) end def self.describe Describe.new('lpos', -3, [ 'readonly' ], 1, 1, 1, [ '@read', '@list', '@slow' ]) end private def parse_arguments until @args.empty? option_name = @args.shift option_value = @args.shift raise RESPSyntaxError if option_value.nil? case option_name.downcase when 'rank' rank = OptionUtils.validate_integer(option_value) raise ZeroRankError if rank == 0 @rank = rank when 'count' count = OptionUtils.validate_integer(option_value) raise NegativeOptionError, 'COUNT' if count < 0 @count = count when 'maxlen' maxlen = OptionUtils.validate_integer(option_value) raise NegativeOptionError, 'MAXLEN' if maxlen < 0 @maxlen = maxlen else raise RESPSyntaxError end end end end end ``` _listing 7.41 The LPosCommand class_ The `LPosCommand` class takes care of parsing the list of arguments and storing the values in the `@count`, `@maxlen` & `@rank` instance variables. We perform a few validations to make sure that if a rank is given it is an integer, but not zero and that `MAXLEN` & `COUNT` are positive integers. We add the `RESPSyntaxError` class to the `utils.rb` file now that we need to use it from more than one command, for `SET` & `LPOS`. ``` ruby module BYORedis # ... RESPSyntaxError = Class.new(StandardError) do def message 'ERR syntax error' end end # ... end ``` _listing 7.42: Adding `RESPSyntaxError` to utils.rb_ We also need to add it to the list of exceptions rescued in `BaseCommand`. ``` ruby module BYORedis class BaseCommand # ... def execute_command call rescue InvalidArgsLength => e @logger.debug e.message command_name = self.class.describe.name.upcase e.resp_error(command_name) rescue WrongTypeError, RESPSyntaxError, ValidationError => e e.resp_error end end end ``` _listing 7.43 Updates to the BaseCommand class to support RESPSyntaxError exceptions_ The actual logic is in the `List#position` method: ``` ruby module BYORedis class List # ... def position(element, count, maxlen, rank) return if count && count < 0 return if @size == 0 return if rank && rank == 0 match_count = 0 maxlen = @size if maxlen == 0 || maxlen.nil? indexes = [] if count if rank.nil? || rank >= 0 iterator = List.left_to_right_iterator(self) else iterator = List.right_to_left_iterator(self) end while iterator.cursor if (rank.nil? || rank >= 0) && iterator.index >= maxlen break elsif (rank && rank < 0) && (@size - iterator.index - 1) >= maxlen break end if element == iterator.cursor.value match_count += 1 reached_rank_from_head = rank && rank > 0 && match_count >= rank reached_rank_from_tail = rank && rank < 0 && match_count >= (rank * -1) if rank.nil? || reached_rank_from_head || reached_rank_from_tail return iterator.index if indexes.nil? indexes << iterator.index end return indexes if indexes && indexes.size == count end iterator.next end indexes end end end ``` _listing 7.44 The List#position method_ There's a lot going on in `List#position`, let's break it down one step at a time: The first three lines are sanity checks for the three optional arguments, if any of these values are invalid, there's no need to continue. We initialize a variable to count the number of matches, `match_count`. We also give `maxlen` a default value of the size of the list if it wasn't set. If a count value is given then we instantiate an array to store all the indices that need to be returned. If no rank is given or if rank is positive, we create a left to right iterator, otherwise we create a right to left iterator, we then iterate through the list with the newly created iterator. If we are in a left to right iteration, checked with the `if (rank.nil? || rank >= 0)` condition, we can stop iterating once the index of the iterator reached `maxlen`, we've seen enough elements, there's no need to continue. We perform a similar check in the case of a right to left iteration, checked with `if (rank && rank < 0)`, but this time we know that we've seen enough elements if `@size - iterator.index - 1` is greater than or equal to `maxlen`. Using a list of size 10 as an example, if `maxlen` is set to 3, and rank is negative, we need to inspect the last three values, at index 9, 8 & 7. So once we reach index 6, `10 - 6 - 1` is equal to `3`, which is the value of `maxlen` and the loop will exit. If neither of these conditions match, we need to keep going through the list. If the current element does not equal `element`, we can jump to the next element in the list, and ignore it, otherwise, we found a match, and the steps to take depend on the `rank` and `maxlen` arguments. Regardless of the arguments value, we found a new match, so we increment `match_count`. If a rank value was given, we need to check if the current match should be accounted for based on the rank value. In other words, we might have to ignore the match. For instance, if rank is 3, and this is the first match, we need to ignore the match, neither `reached_rank_from_head` or `reached_rank_from_tail` will be initialized. On the other hand, if we're dealing with the third match, then `reached_rank_from_head` will be true. The `reached_rank_from_tail` variable works the same way but for negative ranks. If no rank was given, or if either of the two previous variables was set to true, we have found a valid match. If `indexes` is nil, there's no array to accumulate the values into, no count was given and we can return right away. Otherwise, we add the match to the `indexes` variable. Once these checks have been performed for the rank value, we need to check if we can return right away, which is the case if no count was given, or if there is a count and we have found enough matches. **`LINSERT` - Add a new element before or an after an element in the list** `LINSERT` inserts a new element before or after a given pivot. If no values in the list match the pivot, it does nothing and return -1. ``` ruby module BYORedis class LInsertCommand < BaseCommand def call Utils.assert_args_length(4, @args) if ![ 'before', 'after' ].include?(@args[1].downcase) raise RESPSyntaxError else position = @args[1].downcase == 'before' ? :before : :after end pivot = @args[2] element = @args[3] list = @db.lookup_list(@args[0]) return RESPInteger.new(0) if list.nil? new_size = if position == :before list.insert_before(pivot, element) else list.insert_after(pivot, element) end RESPInteger.new(new_size) end def self.describe Describe.new('linsert', 5, [ 'write', 'denyoom' ], 1, 1, 1, [ '@write', '@list', '@slow' ]) end end end ``` _listing 7.45 The LInsertCommand_ The `LInsertCommand` class parses the list of arguments to see if the new element needs to be added before or after the pivot and delegates the operation to the `List` class. We now need to add the `List#insert_before` and `List#insert_after` methods: ``` ruby module BYORedis class List # ... def insert_before(pivot, element) generic_insert(pivot) do |node| new_node = ListNode.new(element, node.prev_node, node) if @head == node @head = new_node else node.prev_node.next_node = new_node end node.prev_node = new_node end end def insert_after(pivot, element) generic_insert(pivot) do |node| new_node = ListNode.new(element, node, node.next_node) if @tail == node @tail = new_node else node.next_node.prev_node = new_node end node.next_node = new_node end end private def generic_insert(pivot) cursor = @head while cursor break if cursor.value == pivot cursor = cursor.next_node end if cursor.nil? -1 else @size += 1 yield cursor @size end end end end ``` _listing 7.46 The List#insert_before & List#insert_after methods_ The first step is the same for each method, and we share the logic in the `generic_insert` method. We iterate from the left, until we find the pivot, the difference occurs when we do find the pivot. In the `insert_before` case, we create a new node with the new value, with its `prev_node` value to the node that was before the pivot, `node.prev_node` and its `next_node` value to the pivot, `node`. If the pivot was not the head, it will have a `prev_node` value, and we need to update the `next_node` value on that node to now point to the new node. Otherwise, if it was the head, then we need to update the `@head` reference to be the new node. The element preceding the pivot is now the new node with `node.prev_node = new_node`. The logic in `insert_after` is quite similar. We start by creating a new node, where `prev_node` is set to the pivot, `node`, and its `next_node` is set to the element that follows the pivot, `node.next_node`. If the pivot was the tail, then we need to update the `@tail` reference, otherwise, we need to update the `prev_node` value of the element following pivot to now point to the new node, `node.next_node.prev_node = new_node`. The element following the pivot is now the new node with `node.next_node = new_node`. **`LLEN` - Return the length of a list** The `LLenCommand` class is more straightforward than the previous ones. It takes a single argument, the key for the list, and returns its length, or 0 if the list does not exist: ``` ruby module BYORedis class LLenCommand < BaseCommand def call Utils.assert_args_length(1, @args) key = @args[0] list = @db.lookup_list(key) if list.nil? RESPInteger.new(0) else RESPInteger.new(list.size) end end def self.describe Describe.new('llen', 2, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@list', '@fast' ]) end end end ``` _listing 7.47 The LLenCommand class_ **`LREM` - Remove one more element from a list** The `LRemCommand` commands accepts three arguments, the key for the list, a count value and the element that we intend to remove. The meaning of the count argument is the following: - count > 0: Remove elements equal to element moving from head to tail. - count < 0: Remove elements equal to element moving from tail to head. - count = 0: Remove all elements equal to element. ``` ruby module BYORedis class LRemCommand < BaseCommand def call Utils.assert_args_length(3, @args) key = @args[0] count = OptionUtils.validate_integer(@args[1]) element = @args[2] list = @db.lookup_list(key) if list.nil? RESPInteger.new(0) else RESPInteger.new(list.remove(count, element)) end end def self.describe Describe.new('lrem', 4, [ 'write' ], 1, 1, 1, [ '@write', '@list', '@slow' ]) end end end ``` _listing 7.48 The LRemCommand class_ The `LRemCommand` classes performs the necessary validations, such as validating that the value for count is an integer, and then delegates the actual removal operation to the `List#remove` method: ``` ruby module BYORedis class List def remove(count, element) delete_count = 0 if count >= 0 iterator = List.left_to_right_iterator(self) else iterator = List.right_to_left_iterator(self) end while iterator.cursor cursor = iterator.cursor if cursor.value == element if @head == cursor @head = cursor.next_node else cursor.prev_node.next_node = cursor.next_node end if @tail == cursor @tail = cursor.prev_node else cursor.next_node.prev_node = cursor.prev_node end delete_count += 1 @size -= 1 if count != 0 && (delete_count == count || delete_count == (count * -1)) break end end iterator.next end delete_count end end end ``` _listing 7.49 The List#remove method_ The first steps should look familiar at this point. Because of the difference in logic between a negative or positive/zero count, we will need to iterate from the left or the right, and create the necessary iterator. The main loop does nothing if the current element does not match the given element we want to remove. If there is a match, we always start by deleting the node. The deletion step in a doubly linked list requires a few steps: - If the cursor is the head, then we update the head to be the element following the cursor - Otherwise we update the `next_node` value of the element preceding the cursor, to point at the element following the cursor - If the cursor is the tail, then we update the list to be the element preceding the cursor - Otherwise we update the `prev_node` value of the element following the cursor to the element preceding the cursor Finally, we increment the `delete_count` variable, and decrement the size of the list. The last step of the loop is to check if we should exit based on the count value. If count is zero, we have to iterate through the whole list to delete all matches, so we do not break early. Otherwise, we stop if we have deleted enough elements. **`LSET` - Update the value of the element at the given index** The `LSET` command takes three arguments, the key for the list, the index of the element to be updated, and the new value. `ERR index out of range` is returned if the index is out of range. If the key does not exist, it returns the `ERR no such key` error. Like many of the previous commands, `LSET` supports negative indices. ``` ruby module BYORedis class LSetCommand < BaseCommand def call Utils.assert_args_length(3, @args) key = @args[0] index = OptionUtils.validate_integer(@args[1]) new_value = @args[2] list = @db.lookup_list(key) if list.nil? RESPError.new('ERR no such key') elsif list.set(index, new_value) OKSimpleStringInstance else RESPError.new('ERR index out of range') end end def self.describe Describe.new('lset', 4, [ 'write', 'denyoom' ], 1, 1, 1, [ '@write', '@list', '@slow' ]) end end end ``` _listing 7.50 The LSetCommand class_ The `LSetCommand` class performs the necessary validations, and delegates the update process to the `List#set` method. If the method returns `nil`, then `LSetCommand#call` returns the out of range error back to the `Server` class. ``` ruby module BYORedis class List # ... def set(index, new_value) # Convert a negative index index += @size if index < 0 return if index < 0 || index >= @size distance_from_head = index distance_from_tail = @size - index - 1 if distance_from_head <= distance_from_tail iterator = List.left_to_right_iterator(self) else iterator = List.right_to_left_iterator(self) end while iterator.index != index iterator.next end iterator.cursor.value = new_value end end end ``` _listing 7.51 The List#set method_ Like the previous commands supporting negative indices, we first convert the index to a 0-based index and return `nil` if the index is out of bounds. We then perform the same optimizations we performed earlier to decide if we should initiate the iteration from the head or from the tail. Finally, we iterate until we reach the desired index and update the value in place. **`LTRIM` - Keep a subset of the list and discard the rest** The last utility command is `LTRIM`, it accepts three arguments, the key for the list, a start index and a stop index. It only keeps the elements in the range delimited by the start and stop indices, all other elements are discarded. If the range is empty, then the list is deleted. Like other commands, it supports negative indices. ``` ruby module BYORedis class LTrimCommand < BaseCommand def call Utils.assert_args_length(3, @args) key = @args[0] start = OptionUtils.validate_integer(@args[1]) stop = OptionUtils.validate_integer(@args[2]) list = @db.lookup_list(key) if list @db.trim(key, list, start, stop) end OKSimpleStringInstance end def self.describe Describe.new('ltrim', 4, [ 'write' ], 1, 1, 1, [ '@write', '@list', '@slow' ]) end end end ``` _listing 7.52 The LTrimCommand class_ The `LTrimCommand` class validates that the start and stop indices are integer, and delegates the trim operation to the `DB#trim` method. It always returns `+OK`, even if the list does not exist. We now need to add the `DB#trim` & `List#trim` methods: ``` ruby module BYORedis class DB # ... def trim(key, list, start, stop) list.trim(start, stop) @data_store.delete(key) if list.empty? end end end ``` _listing 7.53 The DB#trim proxy method to handle deletions of empty lists_ The `DB#trim` method deletes the list from the database if the resulting list is empty. ``` ruby module BYORedis class List # ... def trim(start, stop) current_head = @head # Convert negative values stop = @size + stop if stop < 0 stop = @size - 1 if stop >= @size start = @size + start if start < 0 start = 0 if start < 0 if start >= @size || start > stop @size = 0 @head = nil @tail = nil return end return if start == 0 && stop == @size - 1 distance_to_start = start distance_to_stop = @size - stop - 1 if distance_to_start <= distance_to_stop iterator = List.left_to_right_iterator(self) target_index = start else iterator = List.right_to_left_iterator(self) target_index = stop end new_head = nil new_tail = nil while iterator.index != target_index iterator.next end # We reached the closest element, either start or stop # We first update either the head and the nail and then find the fastest way to get to the # other boundary if target_index == start new_head = iterator.cursor target_index = stop # We reached start, decide if we should keep going right from where we are or start from # the tail to reach stop if distance_to_stop < stop - iterator.index iterator = List.right_to_left_iterator(self) end else new_tail = iterator.cursor target_index = start # We reached stop, decide if we should keep going left from where we are or start from # the head to reach start if distance_to_start < iterator.index - start iterator = List.left_to_right_iterator(self) end end while iterator.index != target_index iterator.next end # We now reached the other boundary if target_index == start new_head = iterator.cursor else new_tail = iterator.cursor end @head = new_head @head.prev_node = nil # If start == stop, then there's only element left, and new_tail will not have been set # above, so we set here if start == stop new_tail = new_head @size = 1 else # Account for the elements dropped to the right @size -= (@size - stop - 1) # Account for the elements dropped to the left @size -= start end @tail = new_tail @tail.next_node = nil end end end ``` _listing 7.54 The List#trim method_ We perform the usual steps with negative indices, converting to 0-based indices. We then check if they're out of order and if so, clear the list right away, there's no need to iterate in this case. We also check that if `start == 0 && stop == -1`, in this case, there is nothing to do, we can keep the list as is. This method is pretty long and pretty verbose in order to minimize the number of empty iterations required to reach the nodes at indices `start` & `stop`. The algorithm can be described as: - First, find the fastest node to get to. It is `start` if the distance between the head and `start` is lower than the distance between `stop` and the tail. It is `stop` otherwise. - Once the closest node is reached, try to reach the second boundary in the most efficient manner, there are four options: - if the node we reached is `start`, we can reach `stop` in two ways: - continue with the same iterator if `stop` is closer to the iterator than it is from the tail - iterate from the tail with a new iterator otherwise - if the node we reached is `stop`, we can reach `start` in two ways: - continue with the same iterator if `start` is closer to the iterator than it is from the head - iterate from the head with a new iterator otherwise - Once we found each nodes, we update `@head` & `@tail` accordingly and adjust the size to accommodate for the dropped nodes. This algorithm means that calling `LTRIM 997 998` on a 1,000 element list will start from the right, reach the `stop` node in one iteration, and continue with the same iterator to reach the `start` node. Likewise, calling `LTRIM 1 2` on a 1,000 element list will start from the left, reach the `start` node in one iteration and continue with the same iterator to reach the `stop` node. Finally, calling `LTRIM 1 998` on a 1,000 element list will start from the left, reach the `start` node in one iteration and create a new iterator, to start from the tail to reach the `stop` node in one iteration. We've now implemented most of the commands, there are only three more commands, that implement existing logic, but in a blocking manner. ### The blocking variants, BLPOP, BRPOP & BRPOPLPUSH The last three commands we need to implement are almost identical to `LPOP`, `RPOP` & `RPOPLPUSH`, with the difference that they are **B**locking. Let's start with the `BLPOP` command. It accepts two arguments or more. The first one is the key for a list, and the last one must be a number, integer or float, which is the timeout the command can block for. It accepts more than one list keys. The following are valid `BLPOP` commands: `BLPOP a 1`, `BLPOP a b c 1.2`. But the following is invalid `BLPOP a b`, `b` is not a valid number and cannot be used to describe a timeout. It's worth noting that since keys can be numbers, which Redis represents at Strings internally, the following is valid `BLPOP 1 1`. It means: "Block for up to 1s for the key '1'". A timeout value of `0` means an infinite timeout. The server will only unblock the client if a new element is added to one of the lists it is blocked on. Redis looks at all the keys from left to right, and as soon as it finds a list, it will pop an element from the left and return it, alongside the key, so that the client knows which list the element was popped from: ``` 127.0.0.1:6379> LPUSH b b1 (integer) 1 127.0.0.1:6379> BLPOP a b 1 1) "b" 2) "b1" ``` In the previous example, if the list at key `a` had contained at least one element, it would have been returned instead. The blocking behavior happens when all the lists are empty, in this case Redis will not send a response to the client, effectively blocking it. Any other commands received while blocked will be accumulated and replied to once the blocking operation is unblocked. There are three conditions that can unblock a client: - One of the keys the client is blocked on receives a push before the timeout expires - The timeout expires before any of the list receives a push - The client disconnects before any of the two previous conditions are met In the first case, the return value is the same as if the command returned right away without blocking, it returns the key of the list and the element that was popped. In the second case, it returns a nil array. In the last example, the client disconnects, so whether one of the list receives a push, or the timeout expires, nothing will happen, the server needs to clear its internal state to make sure it doesn't actually pop any elements since there's no clients to send the data to. Let's look at an example: Let's block for 100 seconds in one session and close it with `Ctrl-C` right after starting it: ``` 127.0.0.1:6379> BLPOP a 100 ^C ``` Reopen another `redis-cli` shell and push a value to the list `a`: ``` 127.0.0.1:6379> RPUSH a a1 (integer) 1 127.0.0.1:6379> LRANGE a 0 -1 1) "a1" ``` If all went well, we did perform all these operations under 100s, but the element we pushed to the list `a` was not popped, because when the client disconnected, the server knew that there was no client blocked anymore. If we'd perform the same operations with two sessions, without closing the first one, this is what would happen: ``` 127.0.0.1:6379> BLPOP a 100 ``` In a second session: ``` 127.0.0.1:6379> RPUSH a a1 (integer) 1 ``` And back in the first session, we see the result of `BLPOP` alongside the amount of time it was blocked for thanks to `redis-cli`: ``` 127.0.0.1:6379> BLPOP a 100 1) "a" 2) "a1" (19.50s) ``` If we let the timeout expire, we can see that the server returns a nil array: ``` 127.0.0.1:6379> BLPOP a 1 (nil) (1.05s) ``` Note that `redis-cli` displays nil strings and nil arrays the same way, with `(nil)`, we can see which one it is with `nc`: ``` bash > nc -c localhost 6379 BLPOP a 1 *-1 ``` **Blocking operations use cases** Before implementing the command, it's worth stopping to discuss the benefits of the blocking variants. There are two main benefits to the blocking variants of the `LPOP`, `RPOP` & `RPOPLPUSH` commands: - It reduces the latency between the moment when an element is pushed to a list and when it is read by a client - It reduces the number of potential "empty"/"useless" commands between clients and the server **Latency improvement** The latency improvement aspect is interesting if there is a benefit to elements added to the list being popped and sent to a client as fast as possible. A common example of such system is a web application processing jobs in the background. Let's use a password reset flow as an example. It is not unusual for web applications to offer a password reset flow, so that users can reset their passwords if they forgot it. The idea is that a user provides their email address and they'll receive an email providing information about the steps to take to reset their password. While it could be considered over-engineered, it's not unusual for web applications to use a background worker process system to implement such flow. The motivation behind this approach is that web applications often rely on third party providers to actually send emails, such as SendGrid, MailChimp or Braze. While often reliable, it is always possible that the APIs provided by these services occasionally fail, but once the email address has been read, the requests can be retried until it finally succeeds, this is where a background worker can be useful. The web server receives the email from the client, queues the request in Redis with an `LPUSH` command, and returns a successful response to the client. The user will see a successful response even though the email might not have yet been actually sent. It is then up to a background worker to fetch the message from the list, with `RPOP` and attempt to actually send the email, retrying if it fails. In this scenario, we'd like the worker to pick up the message as soon as the message is pushed, but without a blocking variant, the only option we have is to use a polling mechanism. The worker issues sends `RPOP` commands, if something is returned, it processes it, otherwise, it optionally waits and issues another `RPOP` command. Rinse & repeat. The problem with this approach is that if we program our workers to wait after receiving an empty response, to prevent spamming the server with unnecessary work, we could end up with a delay between when a message is pushed and when it is popped. Let's imagine that workers wait thirty seconds after each empty pop, if we're unlucky, a worker might send a pop command right before the message is pushed and only process it thirty seconds later. While the impact in this example might be minimal, a thirty second delay for an email could be considered negligible, the fastest we process the email, the more likely we are to prevent confusion for the user. Any delays might cause confusion on their end, wondering if the process worked as expected. **Empty responses reduction** One approach that could improve the problem mentioned in the previous section would be to reduce the wait time between each poll. We started with thirty seconds in the previous example, and could decide to reduce is to one hundred milliseconds. With such a short interval, we would we be guarantee to process the email within 100 milliseconds of the user requesting it. The problem is that the worker is now sending up to 10 requests per second, for a system that might see less than one message per minute. This approach would create a lot of empty responses and effectively send a lot of useless commands. While Redis is optimized to process responses fast, no commands to process will always be faster that some. The blocking variants avoid these issues by blocking the clients until an element is available, or until the timeout expires. With this approach, and with a long enough timeout, the number of empty responses can be reduced to almost zero. A worker would send the `RPOP email-reset-queue 60` command, to either get directly a message from the `email-reset-queue` or wait up to 60s until a message is added to the queue. An empty response would only happen if no customers request a password reset within 60s. The blocking commands also solve the latency issue since there's now no delay between the moment when the message is pushed to the queue and when it is received by a worker. **Blocking commands caveats** There are some caveats that should be considered when using blocking commands. Redis will accumulate any further commands sent while the client that initiated the command is blocked. This means that if the application that communicates with Redis needs to perform other related operations, it would need to create a new connection. This can be a problem for applications using connection pooling. The idea behind connection pooling is that an application will create a bunch of connections, the pool, and keep them available for future use. This removes the need for opening and closing connections, which is unnecessary since once a response has been sent, the same connection can be reused to send a different command. This approach is particularly useful for web application where one or more processes or threads might be running to serve all the incoming HTTP requests. Let's use a multi-threaded web server as an example, running 100 threads. Let's imagine that about a tenth of the incoming requests require a connection to Redis. A naive approach would be give each thread a connection, but this would be wasteful, given that most connections would be idle most of the time based on the 10% example we defined above. Instead, we could create a smaller number of connections, in a pool, and make each thread take a connection from the pool, use it and return it to the pool. Concurrency access concerns are really important here as only one thread should use a connection to prevent unexpected things to happen, such as two threads writing their own command to the connection, it would be impossible to read the responses and assign them to each thread. Now, while connection pools are great to avoid creating too many connections and reuse existing connections to prevent unnecessary work with closing and creating connections, there might be issues if the pool has a fixed size and cannot grow. Different connection pool libraries might provide different features, but it is very common to have a maximum size of connections. The [connection_pool][connection-pool-gh] gem is a common library in Ruby, and [HikariCP][hikari-cp-gh] is a very popular one in Java, both use fixed size pools. In our example, if the pool was created with ten connections, and nine threads send a `BLPOP` command with a long timeout, only one connection is left available for the other ninety threads, which would cause delay as each of these threads would need to wait for the previous command to complete. **The `BLPopCommand` class** Implementing the blocking behavior will require some changes to the `Server` class, but let's start by adding the `BLPopCommand` class in `list_commands.rb`: ``` ruby module BYORedis module ListUtils # ... def self.timeout_timestamp_or_nil(timeout) if timeout == 0 nil else Time.now + timeout end end def self.common_bpop(db, args, operation) Utils.assert_args_length_greater_than(1, args) timeout = OptionUtils.validate_float(args.pop, 'timeout') list_names = args list_names.each do |list_name| list = db.lookup_list(list_name) next if list.nil? popped = yield list_name, list return RESPArray.new([ list_name, popped ]) end BYORedis::Server::BlockedState.new(ListUtils.timeout_timestamp_or_nil(timeout), list_names, operation) end end # ... class BLPopCommand < BaseCommand def call ListUtils.common_bpop(@db, @args, :lpop) do |list_name, list| @db.left_pop_from(list_name, list) end end def self.describe Describe.new('blpop', -3, [ 'write', 'noscript' ], 1, -2, 1, [ '@write', '@list', '@slow', '@blocking' ]) end end end ``` _listing 7.55 The BLPopCommand using a shared method from ListUtils_ Most of the code in the `common_bpop` method uses existing methods, the only difference is if none of the lists in `list_names` exist, we return an instance of `BlockedState`. This is a new struct defined in the `Server` class: ``` ruby module BYORedis class Server # ... BlockedState = Struct.new(:timeout, :keys, :operation, :target, :client) # ... end end ``` _listing 7.56 The BlockedState Struct_ The `BlockedState` struct allows us to store information about blocked clients in the `Server` class. This is necessary to handle both timeouts and unblocking clients when lists they are blocked on are pushed to and a response should be sent to the blocked clients. We also need to remember which type of operation was initially sent, so that we use `left_pop` or `right_pop` when it is time to unblock the client. The `process_poll_events` method is starting to get big, so we're extracting logic from it when processing client buffers. ``` ruby module BYORedis class Server # ... def process_poll_events(sockets) sockets.each do |socket| if socket.is_a?(TCPServer) socket = safe_accept_client next unless socket @clients[socket.fileno.to_s] = Client.new(socket) elsif socket.is_a?(TCPSocket) client = @clients[socket.fileno.to_s] # ... if client_command_with_args.nil? # ... else client.buffer += client_command_with_args process_client_buffer(client) end else raise "Unknown socket type: #{ socket }" end end end def process_client_buffer(client) split_commands(client.buffer) do |command_parts| return if client.blocked_state response = handle_client_command(command_parts) if response.is_a?(BlockedState) block_client(client, response) else @logger.debug "Response: #{ response.class } / #{ response.inspect }" serialized_response = response.serialize @logger.debug "Writing: '#{ serialized_response.inspect }'" unless Utils.safe_write(client.socket, serialized_response) disconnect_client(client) end handle_clients_blocked_on_keys end end rescue IncompleteCommand # Not clearing the buffer or anything rescue ProtocolError => e client.socket.write e.serialize disconnect_client(client) end def block_client(client, blocked_state) if client.blocked_state @logger.warn "Client was already blocked: #{ blocked_state }" return end blocked_state.client = client # Add the state to the client client.blocked_state = blocked_state if blocked_state.timeout @db.client_timeouts << blocked_state end # Add this client to the list of clients waiting on this key blocked_state.keys.each do |key| client_list = @db.blocking_keys[key] if client_list.nil? client_list = List.new @db.blocking_keys[key] = client_list end client_list.right_push(client) end end # ... end end ``` _listing 7.57 The blocking related method in the Server class_ The `blocked_state` instance is only added to `client_timeouts` if there is a timeout. If the client specified a value of `0`, then the server will never unblock the client after a timeout and there is therefore no need to keep track of it here. We added a new method to the `Utils` module, to wrap the logic around writing to a socket, while handling potential exceptions if the socket was closed and the write operation fails: ``` ruby module BYORedis module Utils # ... def self.safe_write(socket, message) socket.write(message) true rescue Errno::ECONNRESET, Errno::EPIPE false end end end ``` _listing 7.58 The Utils.safe_write helper method_ The `block_client` method is making use of a few new elements. First it stores the `BlockedState` instance in the client, so we need to update the `Client` struct to add a new attribute: ``` ruby module BYORedis class Server # ... Client = Struct.new(:socket, :buffer, :blocked_state) do attr_reader :id def initialize(socket) @id = socket.fileno.to_s self.socket = socket self.buffer = '' end end # ... end end ``` _listing 7.59 Updates to the Client Struct to support_ We also need to add a few more data structures to the `DB` class, namely: `ready_keys`, `:blocking_keys`, `client_timeouts` & `unblocked_clients`. The first two, `ready_keys` and `blocking_keys`, are `Dict` instances. With `ready_keys` we use a `Dict` even though we only care about keys, and will use `nil` for all values. The purpose of this dictionary is essentially to be a set, a collection that does not store duplicates. Whenever a list receives a push, we will add the list's key to `ready_keys` if it was blocked on. There is no need to store this information more than once, so using a `Dict` as a set works perfectly. We will be able to know if it was blocked by inspecting `blocking_keys`. `blocking_keys` is also a dictionary where keys will be keys of lists that are being blocked on, and the values will be lists of clients blocked. By using a list as the value and appending to the list, we can maintain an order so that the first client to block for a key will be the first client to receive a response when elements will be pushed to the list. `client_timeouts` is necessary to handle clients that should receive an empty response if the timeout expired before elements were pushed to the list. Without an extra data structure to store timeouts, we would have to iterate over all the connected clients, and manually inspect their `blocked_state` attribute to check if it expired or not. This would be extremely inefficient, especially given that we need to perform this check on each iteration of the event loop. This operation would have an O(n) complexity, where n is the number of connected clients. If no clients are blocked, even if thousands of clients are connected, we want to be able to know that there's no need to check for expired clients. This is the problem that the `client_timeouts` attribute on `DB` solves. It is a sorted array, which we provide an implementation for in [Appendix B][appendix-b] Whenever a blocked command is received and there is no element to return right away, a `BlockedState` instance will be pushed to `client_timeouts` unless the timeout was `0`. Using a regular array to store these `BlockedState` instances would already be an improvement compared to the scenario described above. We would only check if clients are expired within the set of blocked clients, but we would still have to check all the clients, one by one, to see if they are expired or not. This is also a O(n) operation, where n is the number of blocked clients. Using a sorted array turns the operation into an O(1) operation, we can inspect the first element in the sorted array, if it is not expired, there's no need to inspect any other clients, we know their expiration is later than the first one. If the first client in the sorted array is expired, we need to handle it as such and look at the next element, and stop as soon as we find a non expired client. Using a sorted array also helps with the cleanup tasks required once a client was unblocked after the list it was blocked on received a push. When this happens, we need to remove the client from the `client_timeouts` list since it is not blocked anymore. The sorted array class guarantees that this operation happens in O(logn) time, where n is the number of blocked clients, instead of O(n) if the array was not sorted. This implementation is a deviation from the Redis one. Redis uses a [Radix Tree][wikipedia-radix-tree] to store client timeouts. A Radix tree provides similar time complexity for the iteration of clients from the ones with the earliest expirations, but it provides a better time complexity for the deletion use case. We decided to not implement a Radix tree here given the complexity of such implementation. A sorted array provides a good middle ground approach, by being fairly short to implement and still being a great improvement compared to a regular array. Finally, `unblocked_clients` is a `List` instance, which will be appended to when clients are unblocked, either because their timeouts expired or if the list they were blocked on received a push. Regardless of the reason, we need to check if the client sent commands while it was blocked, and process them. ``` ruby module BYORedis class DB attr_reader :data_store, :expires, :ready_keys, :blocking_keys, :client_timeouts, :unblocked_clients attr_writer :ready_keys def initialize @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @data_store = Dict.new @expires = Dict.new @ready_keys = Dict.new @blocking_keys = Dict.new @client_timeouts = SortedArray.new(:timeout) @unblocked_clients = List.new end # ... end end ``` _listing 7.60 New data structures in the DB class_ --- At this point, once we're done processing a `BLPOP` command, we stored the `BlockedState` information in `client_timeouts` and in the `Client` instance. We also added a new entry if necessary in `blocking_keys`, where the value is a list containing the client that issued the `BLPOP` command. We're now ready to handle the two possible outcomes for a blocked client. Either its timeout expires, in which case we return a `nil` array, and process any commands sent while blocked. If one of the lists the client was blocked on receives a push before the timeout expires, we return the head of the list to the client, alongside the list key and also process any commands sent while blocked. **Handling timeouts** Let's first add two new steps to the event loop, `handle_blocked_clients_timeout` and `process_unblocked_clients`: ``` ruby module BYORedis class Server # ... def start_event_loop loop do handle_blocked_clients_timeout process_unblocked_clients timeout = select_timeout @logger.debug "select with a timeout of #{ timeout }" result = IO.select(client_sockets + [ @server ], [], [], timeout) sockets = result ? result[0] : [] process_poll_events(sockets) process_time_events end end # ... end end ``` _listing 7.61 Updates to the event loop in the Server class to handle blocked client timeouts_ We now start each iteration of the event loop by first checking if any of the blocked clients are expired, and then processing any commands sent while blocked. As mentioned in the previous section, the time complexity of these two methods is important since they would otherwise add a delay at the beginning of each event loop iteration. ``` ruby module BYORedis class Server # ... def handle_blocked_clients_timeout @db.client_timeouts.delete_if do |blocked_state| client = blocked_state.client if client.blocked_state.nil? @logger.warn "Unexpectedly found a non blocked client in timeouts: #{ client }" true elsif client.blocked_state.timeout < Time.now @logger.debug "Expired timeout: #{ client }" unblock_client(client) unless Utils.safe_write(client.socket, NullArrayInstance.serialize) @logger.warn "Error writing back to #{ client }: #{ e.message }" disconnect_client(client) end true else # Impossible to find more later on since client_timeouts is sorted break end end end def unblock_client(client) if client.socket.closed? @logger.warn 'RETURNING EARLY' return end @db.unblocked_clients.right_push client return if client.blocked_state.nil? # Remove this client from the blocking_keys lists client.blocked_state.keys.each do |key2| list = @db.blocking_keys[key2] if list list.remove(1, client) @db.blocking_keys.delete(key2) if list.empty? end end client.blocked_state = nil end def process_unblocked_clients return if @db.unblocked_clients.empty? cursor = @db.unblocked_clients.left_pop while cursor client = cursor.value if @clients.include?(client.id) process_client_buffer(client) else @logger.warn "Unblocked client #{ client } must have disconnected" end cursor = @db.unblocked_clients.left_pop end end end end ``` _listing 7.62 Updates to the Server class to process timeouts for blocked clients_ We need to add one more piece of logic to the server with regards to timeouts. If a client disconnects before its timeout expired, we want to clean things of up so that we don't keep track of this client anymore. We need to more that deleting the client from the `@clients` array in `process_poll_events`. ``` ruby module BYORedis class Server # ... def safe_accept_client @server.accept rescue Errno::ECONNRESET, Errno::EPIPE => e @logger.warn "Error when accepting client: #{ e }" nil end def safe_read(client) client.socket.read_nonblock(1024, exception: false) rescue Errno::ECONNRESET, Errno::EPIPE disconnect_client(client) end def process_poll_events(sockets) sockets.each do |socket| if socket.is_a?(TCPServer) socket = safe_accept_client next unless socket @clients[socket.fileno.to_s] = Client.new(socket) elsif socket.is_a?(TCPSocket) client = @clients.find { |client| client.socket == socket } client_command_with_args = socket.read_nonblock(1024, exception: false) client = @clients[socket.fileno.to_s] client_command_with_args = safe_read(client) if client_command_with_args.nil? disconnect_client(client) elsif client_command_with_args == :wait_readable # There's nothing to read from the client, we don't have to do anything next elsif client_command_with_args.empty? @logger.debug "Empty request received from #{ socket }" else # ... end end end end def disconnect_client(client) @clients.delete(client.id) @db.unblocked_clients.remove(1, client) if client.blocked_state @db.client_timeouts.delete(client.blocked_state) client.blocked_state.keys.each do |key| list = @db.blocking_keys[key] if list list.remove(1, client) @db.blocking_keys.delete(key) if list.empty? end end end client.socket.close end # ... end end ``` _listing 7.63 Updates to the Server class to handle clients disconnection_ **Handling blocked clients before timeout** We need another handler, for when a list that is being blocked on, for instance either `a` or `b` after receiving `BLPOP a b 1`, receives a push and is created. New lists are always created from `DB#lookup_list_for_write`, so let's add a condition there, that will notify that one key that is being blocked on can now be used to unblock one or more clients: ``` ruby module BYORedis class DB def lookup_list_for_write(key) list = lookup_list(key) if list.nil? list = List.new @data_store[key] = list if @blocking_keys[key] @ready_keys[key] = nil end end list end end end ``` _listing 7.64 Updates to the DB#lookup_list_for_write to notify for list creation_ `blocking_keys` is populated when we process the result of a blocking command. It is a dictionary that contains a list of clients blocked for that key. When a new list is created, we inspect `blocking_keys`, if there's no entry, then no clients are blocked on this key, on the other hand, if there is one or more clients, then we know that the key is being blocked on and we add it to `@ready_keys`. The value of the pair does not matter here, we only care about having an entry in the dictionary. ``` ruby module BYORedis class Server # ... def initialize @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @clients = Dict.new @db = DB.new @blocked_client_handler = BlockedClientHandler.new(self, @db) @server = TCPServer.new 2000 @time_events = [] @logger.debug "Server started at: #{ Time.now }" add_time_event(Time.now.to_f.truncate + 1) do server_cron end start_event_loop end # ... def handle_clients_blocked_on_keys return if @db.ready_keys.used == 0 @db.ready_keys.each do |key, _| unblocked_clients = @blocked_client_handler.handle(key) unblocked_clients.each do |client| unblock_client(client) end end @db.ready_keys = Dict.new end end end ``` _listing 7.65 Blocked client handling in the Server class_ `handle_clients_blocked_on_keys` is called from `process_poll_events`, after processing the commands from the clients. If the command did not result in the creation of a list, then nothing will happen, no clients can be unblocked. If the command did create a list, then `@db.ready_keys` will have received elements and `@blocked_client_handler.handle` will be called for each of these keys. The code in charge of handling blocked client lives in its own class, `BlockedClientHandler`. ``` ruby module BYORedis class BlockedClientHandler def initialize(server, db) @server = server @db = db @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL end def handle(key) clients = @db.blocking_keys[key] unblocked_clients = [] list = @db.data_store[key] if !list || !list.is_a?(List) @logger.warn "Something weird happened, not a list: #{ key } / #{ list }" raise "Unexpectedly found nothing or not a list: #{ key } / #{ list }" end raise "Unexpected empty list for #{ key }" if list.empty? cursor = clients.left_pop while cursor client = cursor.value if handle_client(client, key, list) unblocked_clients << client end if list.empty? break else cursor = clients.left_pop end end @db.blocking_keys.delete(key) if clients.empty? unblocked_clients end def handle_client(client, key, list) blocked_state = client.blocked_state # The client is expected to be blocked on a set of keys, we unblock it based on the key # arg, which itself comes from @db.ready_keys, which is populated when a key that is # blocked on receives a push # So we pop (left or right) from the list at key, and send the response to the client if client.blocked_state response = pop_operation(key, list, blocked_state.operation, blocked_state.target) serialized_response = response.serialize @logger.debug "Writing '#{ serialized_response.inspect } to #{ client }" unless Utils.safe_write(client.socket, serialized_response) # If we failed to write the value back, we put the element back in the list rollback_operation(key, response, blocked_state.operation, blocked_state.target) @server.disconnect_client(client) return end else @logger.warn "Client was not blocked, weird!: #{ client }" return end true end private def pop_operation(key, list, operation, target) case operation when :lpop RESPArray.new([ key, @db.left_pop_from(key, list) ]) when :rpop RESPArray.new([ key, @db.right_pop_from(key, list) ]) when :rpoplpush raise "Expected a target value for a brpoplpush handling: #{ key }" if target.nil? ListUtils.common_rpoplpush(@db, key, target, list) else raise "Unknown pop operation #{ operation }" end end def rollback_operation(key, response, operation, target_key) list = @db.lookup_list_for_write(key) case operation when :lpop element = response.underlying_array[1] list.left_push(element) when :rpop element = response.underlying_array[1] list.right_push(element) when :rpoplpush target_list = @db.lookup_list(target_key) element = target_list.left_pop @db.data_store.delete(target_key) if target_list.empty? list.right_push(element.value) else raise "Unknown pop operation #{ operation }" end end end end ``` _listing 7.66 The BlockedClientHandler class_ This is the final step required to handle blocked clients. We are processing all the keys that can be used to unblock clients. A command can push more than one element, so we might be able to unblock more than one client. We start this process by getting the list of blocked clients for this key, in `@db.blocked_clients`. Clients are added with right push operations, so we use `left_pop` here to get them in order of insertions. The first client to block on this list will be processed first. We also get the recently created list that will pop elements from to unblock clients. For each client, we call `handle_client`. In `handle_client` we pop an element from the list, according to the operation that the client blocked with, either `left_pop` or `right_pop`, and we send the response back to the client. In case of a failure, we return the element back to the list and disconnect the client. Back in `BlockedClientHandler#handler`, we accumulate a list of clients that were unblocked, which will in turn be returned to the `Server` class. This list is used to call `unblock_client`, which will flag the client to be processed in case there were accumulated commands sent while blocked. We then check if the list is empty, if it is, we cannot unblock anymore clients and exit the iteration. Otherwise we continue and unblock the next client. `unblock_client` also takes care of cleaning up the server state. Now that a client is unblocked, it should not be in any of the lists in `@db.blocking_keys`. We also need remove the entry in the sorted array of timeouts. If we were able to unblock all the clients, we remove the key from `blocking_keys`. With all these changes, we can implement the similar `BRPopCommand` class: ``` ruby module BYORedis # ... class BRPopCommand < BaseCommand def call ListUtils.common_bpop(@db, @args, :rpop) do |list_name, list| @db.right_pop_from(list_name, list) end end def self.describe Describe.new('brpop', -3, [ 'write', 'noscript' ], 1, -2, 1, [ '@write', '@list', '@slow', '@blocking' ]) end end end ``` The implementation is almost identical to `BLPopCommand`. The last class to add is `BRPopLPushCommand`: ``` ruby module BYORedis module ListUtils # ... def self.common_rpoplpush(db, source_key, destination_key, source) if source_key == destination_key && source.size == 1 source_tail = source.head.value else destination = db.lookup_list_for_write(destination_key) source_tail = db.right_pop_from(source_key, source) destination.left_push(source_tail) end RESPBulkString.new(source_tail) end end # ... class RPopLPushCommand < BaseCommand def call Utils.assert_args_length(2, @args) source_key = @args[0] source = @db.lookup_list(source_key) if source.nil? NullBulkStringInstance else destination_key = @args[1] ListUtils.common_rpoplpush(@db, source_key, destination_key, source) end end # ... end end # ... class BRPopLPushCommand < BaseCommand def call Utils.assert_args_length(3, @args) source_key = @args[0] source = @db.lookup_list(source_key) timeout = OptionUtils.validate_float(@args[2], 'timeout') destination_key = @args[1] if source.nil? BYORedis::Server::BlockedState.new(ListUtils.timeout_timestamp_or_nil(timeout), [ source_key ], :rpoplpush, destination_key) else ListUtils.common_rpoplpush(@db, source_key, destination_key, source) end end def self.describe Describe.new('brpoplpush', 4, [ 'write', 'denyoom', 'noscript' ], 1, 2, 1, [ '@write', '@list', '@slow', '@blocking' ]) end end end ``` The code here is almost identical to the one in `RPopLPushCommand`, with the difference that it returns `BlockedState` instance if the source list does not exist. One difference with the previous two commands is that we need to store the target of the pop, the list in which we'll push the element to. We also extracted some shared logic between `RPopLPushCommand` & `BRPopLPushCommand` to `ListUtils.common_rpoplpush` to prevent code repetition. This shared code is important as it handles the edge case where both `source` & `destination` are the same list and only contains one element. ## Tests We added a few more test files in this chapter, and placed all of them in the `test/` sub folder, we also added and a task in `Rakefile` to run all the tests: ``` ruby require 'rake/testtask' Rake::TestTask.new do |t| t.pattern = 'test/*test.rb' end ``` _listing 7.67 Rakefile content_ The new test files allow us to easily run a sub section of the test suite, the following is a list of the new files: - `list_test.rb` - `dict_unit_test.rb` - `command_test.rb` - `sorted_array_unit_test.rb` - `list_unit_test.rb` We can run all the tests with `rake test`, or single files with `ruby list_test.rb` for instance. ## Conclusion In this chapter we added full list support to our Server. We also added the `TYPE` command which allows us to inspect the type of values added to the database. The current types are `string`, `list` and `none` if the given key does not exist. We also made a lot of changes to the server to support blocking commands. In the next chapter we'll add support for another Redis data type, Hashes. ### Code You can find the code [on GitHub][code-github] ## Appendix A: Ziplist Deep Dive Ziplists are implemented in the [`ziplist.h`][redis-source-ziplist-h] & [`ziplist.c`][redis-source-ziplist-c] files. The [`ziplist.c`][redis-source-ziplist-c] file contains a great explanation of how ziplists work. In this appendix we provide a few more details as well as some examples. Ziplists were added to Redis in 2014 by Twitter engineers who apparently needed a more compact data structure to store Twitter timelines, essentially lists of ids. You can read more about it on the [Pull Request page on GitHub][ziplist-gh-pr] and on the blog of one of the authors [here][ziplist-part-1] and [there][ziplist-part-2]. A ziplist is a contiguous chunk of memory, that can store integers and strings, with the following layout: ``` <zlbytes> <zltail> <zllen> <entry> <entry> ... <entry> <zlend> ``` - `zlbytes` is an unsigned 32-bit integer (uint32_t), which describes the number of bytes used by the ziplist, including itself. - `ztail` is also an unsigned 32-bit integer, which is an offset to the last element in the list. It serves a purpose similar to `@tail` in the implementation used in this chapter. - `zllen` is an unsigned 16-bit integer (uint16_t), it keeps count of the number of entries. Because it is an unsigned 16 bit integer, its maximum value is 65,535 (2^16 - 1). In order to allow ziplist to hold more elements, this ziplist implementation knows that the maximum value that can be described by this integer is 65,534 (2^16 - 2), and if the value of the integer is 65,535, it will scan the whole list to count the number of items. In practice, Redis caps the size of the ziplists it creates, the default is 2Kb, and this scenario is extremely unlikely to happen. - `zlend` is a single byte (uint8_t), and is set to 255, the maximum value of a byte, 2^8 - 1, or `1111 1111` / `FF` in binary and hexadecimal representations respectively. The following elements are the actual entries in the list. Each entry has the following layout: ``` <prevlen> <encoding> <entry-data> ``` - `prevlen` represents the length of the previous entry, allowing for right to left. It serves a purpose similar to the `prev_node` attribute in the list used in this chapter, but uses a dynamic size and will often be smaller. If the length of the previous entry in bytes is smaller than 254 bytes, prevlen will be stored in a single byte (uint8_t). The maximum value of a uint8_t is 255 (2^8 - 1). Otherwise, it will consumes 5 bytes, the first byte will be set to 254, the maximum value of a byte, and the following. As a reminder, 255 cannot be used since this value is used to flag the end of the list. This means that an entry cannot have a length greater than what can fit in a 32 bit integer, since the length is stored over 4 bytes, 32 bits. This sets the maximum length of a string stored by a ziplist to 4,294,967,295 (2^32 - 1). Which is, admittedly, a very large string. - `encoding` describes how the entry data is actually stored. It will take either one, two or five bytes. The first two bits of the encoding determines the type, `11` means an integer, and anything else, that is either `00`, `01` or `10`, means a string. **String encoding** - If the encoding starts with `00`, then the encoding itself will only occupy a single byte. This means that we can only use the remaining 6 bits of the encoding byte to encode the length of the string. The maximum value that can be encoded with 6 bits is 63 (2^6 - 1). This means that if the encoding byte is `0000 0001`, the string that is stored has a length of 1. With `0000 0100`, the string has a length of 4, and with `0011 1111`, it has a length of 63. - If the encoding starts with `01`, then the encoding occupies two bytes, which leaves us with 14 bits, the 6 bits of the first byte, and the 8 bits of the second bytes. This encoding can describe a string with a length up to 16,383 (2^14 - 1). As an examples, `0100 0001 0000 0000` describes a string of length 256. - If the encoding starts with `10`, then the encoding will use five bytes. The 6 extra bits of the first byte are not used since we can use the other four bytes to hold a 32-bit value, which is the maximum length of a string in a ziplist. This encoding will only be used if strings have a length greater than 16,383. **Integer encoding** There are six variants of the integer encoding: - If the encoding is `1100 0000`, it describes a signed integer that occupies 2 bytes (int16_t), which value can go up to 32,767 (2^15 - 1) - If the encoding is `1101 0000`, it describes a signed integer that occupies 4 bytes (int32_t), which value can go up to 2,147,483,648 (2^31 - 1) - If the encoding is `1110 0000`, it describes a signed integer that occupies 8 bytes (int64_t), which value can go up to 18,446,744,073,709,551,616 (2^63 - 1) - If the encoding is `1111 0000`, it describes a signed integer that occupies 3 bytes (24 bits), which value can go up to 8,388,607 (2^23 - 1) - If the encoding is `1111 1110`, it describes a signed integer that occupies 1 byte (8 bits), which value can go up to 128 (2^7 - 1) - Finally, if the first four bits are `1111`, then the last four bits are used to hold an unsigned integer value itself. This means that technically we'd be bound to storing integers from 0 up to 15 (2^4 - 1), but the reality is actually more restrictive. We cannot store 0 because `1111 0000` means the 3 byte encoding described above. We also cannot store 15, because `1111` would make the whole byte `1111 1111` and this value, 255, is reserved for the end of list marker. We also cannot store 14, `1110`, because `1111 1110` means the 1 byte encoding described above. This narrows the range of possible values from 1 (`0001`) to 13 (`1101`). Redis actually applies an offset here, to allow numbers from 0 to 12 to be stored with this encoding, so if you store 0 in a Ziplist, it actually stores 1, if you store 12, it actually stores 13. Storing -1 or 13 would require the next encoding type, the one using a full extra byte. **The `DEBUG ZIPLIST` command** Redis provides a few commands for debug purposes. One of them prints details about the ziplist if the key is itself stored as a ziplist. As it turns out, a list is never stored as a ziplist, it is always a quicklist of ziplists. But other Redis data types can use ziplists, for instance, a hash with a few items, less than 512 entries and the values are shorter than 64 bytes. Note that depending on how you run Redis on your machine, things will be different. The `DEBUG ZIPLIST` command does not print the results in the REPL but instead prints them on standard out. I often run a manually built from source Redis, which makes it easy to get the logs since they are by default printed to the terminal where you started the server, but if you run Redis through homebrew, the logs will be located somewhere else. Let's try it: ``` 127.0.0.1:6379> hset foo name pierre (integer) 1 127.0.0.1:6379> DEBUG ZIPLIST foo Ziplist structure printed on stdout ``` And on stdout: ``` {total bytes 25} {num entries 2} {tail offset 16} { addr 0x7f8f1350d8ca, index 0, offset 10, hdr+entry len: 6, hdr len 2, prevrawlen: 0, prevrawlensize: 1, payload 4 bytes: 00|04|6e|61|6d|65| [str]name } { addr 0x7f8f1350d8d0, index 1, offset 16, hdr+entry len: 8, hdr len 2, prevrawlen: 6, prevrawlensize: 1, payload 6 bytes: 06|06|70|69|65|72|72|65| [str]pierre } {end} ``` The previous shows an example of a ziplist containing two items, each is a string. The first entry occupies 6 bytes, and the second one eight. Let's look closer at all the bytes: The first byte, `00`, represents the length of the previous item, which is zero since this is the head of the list. The second byte is `04`, which is the first encoding byte. The encoding can be between one and 5 bytes, so we need to look at the values, bit by bit, to determine which encoding it is, which will tell us how the data is stored. `04` has the following binary representation: `0000 0100`. Looking at the "String encoding" section above, this fits in the first bullet point, a string described with a single byte, because it starts with `00`. We then need to look at the other six bytes to determine the length of the string, `000100` is the number four, so the string has a length of four. The last four bytes in the first entry are `00`, `04`, `6e`, `61`, `6d` & `65`. The string stored is `name`, which holds four bytes: `6e`, `61`, `6d` & `65`. The values are the ascii representation of the letters `n`, `a`, `m` & `e`. We need to continue as long as we don't encounter the `FF` byte, or `255`. The next six bytes are `06`, `06`, `70`, `69`, `65`, `72`, `72` & `65`. The first byte is the length of the previous item, `06`, the hex representation of the number 6, which is what we found when looking at the previous entry, so far so good. The second byte is the first byte of the encoding, `06`, or `0000 0110` in binary. Similarly as for the previous string, `00` tells us it's a string with a length lower than 63, and we can see it has a length of 6. The next six bytes represent the letters `p`, `i`, `e`, `r`, `r`, & `e` in ASCII and the whole entry has a length of 8. We can now see why the `total bytes` value is 25, 4 for the `zlbytes` field, 4 for the `zltail` field, 2 for the `zllen` field, 6 for the first entry and 8 for the second entry and 1 for the end of list marker: `4 + 4 + 2 + 6 + 8 + 1 = 25`. A basic doubly linked list would have required 20 bytes for the first node, 2 8-byte pointers and 4 bytes of data, 22 bytes for the second node, 2 8-byte pointers and 6 bytes of data, as well as 16 bytes for the head and tail pointers, for a grand total of 62. In this small example a ziplist is less than half the size! The problem with ziplists is that adding and removing element require a reallocation of memory, and insertions/deletions in the middle of the list become expensive as the list grows since the whole list needs to be rearranged. The `tail offset` field is 16 since the list header occupies 10 bytes, 4, 4 & 2, and the first item takes 6, that's 16. Let's look at two more examples, one with an integer, and one with a string using a different encoding: ``` 127.0.0.1:6379> hset foo age 30 (integer) 1 127.0.0.1:6379> DEBUG ZIPLIST foo ``` The following is the debug information, the first two entries are the same as previously and were omitted. ``` {total bytes 33} {num entries 4} {tail offset 29} ... { addr 0x7f8681004338, index 2, offset 24, hdr+entry len: 5, hdr len 2, prevrawlen: 8, prevrawlensize: 1, payload 3 bytes: 08|03|61|67|65| [str]age } { addr 0x7f868100433d, index 3, offset 29, hdr+entry len: 3, hdr len 2, prevrawlen: 5, prevrawlensize: 1, payload 1 bytes: 05|fe|1e| [int]30 } {end} ``` Looking at the new bytes, `08` is the length of the previous entry, 8, `03` is the encoding for `age`, a string of length 3, and the three following bytes are the three letters. For the last entry, the length of the previous entry is 5, and the encoding is `fe`, or `1111 1110` in binary. This is the one byte integer encoding, which makes sense given that 30 is too big to use the "encoded within encoding header" approach, where the max value is 12 and is small enough to fit within a single byte, where the max value is 127. If we had set the age to 128, the bytes would have been `05`, `c0`,`80` & `00`. `c0` is the hex representation of 192/`1100 0000`, which represents the 2 byte signed integer encoding, which is why it is followed by two bytes, `80` & `00`. `80` is the hex representation of `1000 0000`, aka 128. Note that 128 is encoded as `80` `00` and not `00` `80`. This is because Redis represents integers as little endian in Ziplists, the least significant bytes come first. There are two exceptions where integers are stored in big endian, for two of the different string encoding, the one using two bytes and the one using five bytes. Let's now look at a sixty-four byte long string: ``` 127.0.0.1:6379> hset foo 64-char-string aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa (integer) 0 127.0.0.1:6379> DEBUG ZIPLIST foo ``` The following is the debug information: ``` {total bytes 116} {num entries 6} {tail offset 48} ... { addr 0x7f867f705880, index 4, offset 32, hdr+entry len: 16, hdr len 2, prevrawlen: 3, prevrawlensize: 1, payload 14 bytes: 03|0e|36|34|2d|63|68|61|72|2d|73|74|72|69|6e|67| [str]64-char-string } { addr 0x7f867f705890, index 5, offset 48, hdr+entry len: 67, hdr len 3, prevrawlen: 16, prevrawlensize: 1, payload 64 bytes: 10|40|40|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61|61| [str]aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... } {end} ``` Looking at the last entry, we see that the length of the previous entry is `10`, which the hexadecimal representation of the number 16. As a quick reminder, this is because the two characters represent 4 bits each, `1` represents `0001` and 0 is `0000`, and the byte `0001 0000` is the value 16, 2^4. The string `"64-char-string"` has 14 characters, and there are two more bytes, one of the `prevlen` field, and one for the encoding. That's 16. The encoding takes two bytes for the last entry, `40` & `40`. `40` is the representation of the number 64, or `0100 0000` in binary. The first two bits of the encoding are `01`, so we know that the overall encoding will use two bytes, and the length of the string will use 14 of the 16 bytes. These 14 bits are: `00 0000 0100 000`, which is the number 64, the length of the string coming up next. Finally, we can see that if we set a string with a length longer than 64, Redis will convert the hash from a Ziplist to a Hash table ``` 127.0.0.1:6379> hset foo 64-char-string aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa11 (integer) 0 127.0.0.1:6379> DEBUG ZIPLIST foo (error) ERR Not an sds encoded string. 127.0.0.1:6379> DEBUG OBJECT foo Value at:0x7f867f62f8e0 refcount:1 encoding:hashtable serializedlength:47 lru:7660156 lru_seconds_idle:36 ``` Note that the error message is incorrect, it should say: "Not a ziplist encoded object". This was fixed in a more [recent version of Redis][gh-my-commit]. ## Appendix B: Sorted Array The following is a sorted array implementation that provides O(logn) `push/<<` & `delete`. The implementation uses a plain Ruby array as the underlying storage, which it delegates most of its operations to. Elements are kept sorted in the `push/<<` method by using the built-in `bsearch_index` method. Using this method, we compute the index at which the element should be added in the array and maintain the ordering. The delete method also relies on `bsearch_index` to find the index of the elements it needs to remove. Given that multiple elements could meet the conditions, it needs to find all the indices for the elements that should be removed. `bsearch_index` will return the leftmost index of an element that should be deleted, and we keep looking to the right as look as we find matching elements and mark them for deletion. The `SortedArray` is meant to be used to hold classes holding multiple attributes, such as `Struct`s, and order them based on one their fields. Its main use case in the `BYORedis` codebase is to store `BlockedState` instances, sorted by their timeouts. ``` ruby module BYORedis class SortedArray def initialize(field) @underlying = [] @field = field.to_sym end def push(new_element) if @underlying.empty? index = 0 else index = @underlying.bsearch_index do |element| element.send(@field) >= new_element.send(@field) end end index = @underlying.size if index.nil? @underlying.insert(index, new_element) end alias << push def [](index) @underlying[index] end def size @underlying.size end def shift @underlying.shift end def delete_if(&block) @underlying.delete_if(&block) end def delete(element) index = @underlying.bsearch_index { |x| x.send(@field) >= element.send(@field) } return if index.nil? element_at_index = @underlying[index] first_index_to_delete = nil number_of_items_to_delete = 0 while element_at_index if element_at_index == element first_index_to_delete ||= index number_of_items_to_delete += 1 end index += 1 next_element = @underlying[index] if next_element && next_element.send(@field) == element.send(@field) element_at_index = next_element else break end end @underlying.slice!(first_index_to_delete, number_of_items_to_delete) end end end ``` _listing 7.68 The SortedArray class_ The following is a test suite for the two main methods of the `SortedArray` class, `push/<<` & `delete`: ``` ruby # coding: utf-8 require_relative './test_helper' require_relative './sorted_array' describe BYORedis::SortedArray do TestStruct = Struct.new(:a, :timeout) describe 'push/<<' do it 'appends elements while keeping the array sorted' do sorted_array = new_array(:timeout) sorted_array << TestStruct.new('a', 1) sorted_array << TestStruct.new('b', 2) sorted_array << TestStruct.new('c', 10) sorted_array << TestStruct.new('d', 20) sorted_array << TestStruct.new('e', 15) sorted_array << TestStruct.new('f', 8) assert_equal(6, sorted_array.size) assert_equal(1, sorted_array[0].timeout) assert_equal(2, sorted_array[1].timeout) assert_equal(8, sorted_array[2].timeout) assert_equal(10, sorted_array[3].timeout) assert_equal(15, sorted_array[4].timeout) assert_equal(20, sorted_array[5].timeout) end end describe 'delete' do it 'deletes the element from the array' do sorted_array = new_array(:timeout) sorted_array << TestStruct.new('a', 10) sorted_array << TestStruct.new('b1', 20) sorted_array << TestStruct.new('b2', 20) sorted_array << TestStruct.new('b3', 20) sorted_array << TestStruct.new('c', 30) # array is now a, b3, b2, b1, c sorted_array.delete(TestStruct.new('d', 40)) # no-op sorted_array.delete(TestStruct.new('b1', 20)) assert_equal(4, sorted_array.size) assert_equal(10, sorted_array[0].timeout) assert_equal(TestStruct.new('b3', 20), sorted_array[1]) assert_equal(TestStruct.new('b2', 20), sorted_array[2]) assert_equal(30, sorted_array[3].timeout) end end def new_array(field) BYORedis::SortedArray.new(field) end end ``` _listing 7.69 Basic unit tests for the SortedArray class_ [code-github]:https://github.com/pjambet/redis-in-ruby/tree/master/code/chapter-7 [list-commands-docs]:https://redis.io/commands#list [redis-data-types-doc]:https://redis.io/topics/data-types-intro [chapter-6]:/post/chapter-6-building-a-hash-table/ [redis-streams-doc]:https://redis.io/topics/streams-intro [postgres-page-layout]:https://www.postgresql.org/docs/current/storage-page-layout.html [redis-doc-type-command]:http://redis.io/commands/type [redis-source-db-type]:https://github.com/antirez/redis/blob/6.0.0/src/server.h#L640-L653 [template-method-pattern]:https://en.wikipedia.org/wiki/Template_method_pattern [appendix-b]:#appendix-b-sorted-array [appendix-a]:#appendix-a-ziplist-deep-dive [wikipedia-radix-tree]:https://en.wikipedia.org/wiki/Radix_tree [wikipedia-queues]:https://en.wikipedia.org/wiki/Queue_(abstract_data_type) [wikipedia-stacks]:https://en.wikipedia.org/wiki/Stack_(abstract_data_type) [connection-pool-gh]:https://github.com/mperham/connection_pool [hikari-cp-gh]:https://github.com/brettwooldridge/HikariCP [redis-source-ziplist-h]:https://github.com/antirez/redis/blob/6.0.0/src/ziplist.h [redis-source-ziplist-c]:https://github.com/antirez/redis/blob/6.0.0/src/ziplist.c [gh-my-commit]:https://github.com/redis/redis/commit/d52ce4ea1aa51457aed1d63a5bf784f94b2768c3 [ziplist-gh-pr]:https://github.com/redis/redis/pull/2143 [ziplist-part-1]:https://matt.sh/redis-quicklist [ziplist-part-2]:https://matt.sh/redis-quicklist-visions [redis-doc-incr]:https://redis.io/commands/incr <file_sep>/code/chapter-9/types.rb require 'delegate' module BYORedis NullArray = Class.new do def serialize "*-1\r\n" end end NullArrayInstance = NullArray.new NullBulkString = Class.new do def serialize "$-1\r\n" end end NullBulkStringInstance = NullBulkString.new RESPError = Class.new(SimpleDelegator) do def serialize "-#{ self }\r\n" end end RESPInteger = Class.new(SimpleDelegator) do def serialize ":#{ self }\r\n" end end RESPSimpleString = Class.new(SimpleDelegator) do def serialize "+#{ self }\r\n" end end OKSimpleString = RESPSimpleString.new('OK') RESPBulkString = Class.new(SimpleDelegator) do def serialize "$#{ bytesize }\r\n#{ self }\r\n" end end RESPArray = Class.new(SimpleDelegator) do def serialize serialized_items = map do |item| case item when RESPSimpleString, RESPBulkString item.serialize when String RESPBulkString.new(item).serialize when Integer RESPInteger.new(item).serialize when Array RESPArray.new(item).serialize end end "*#{ length }\r\n#{ serialized_items.join }" end end end <file_sep>/code/chapter-10/test/sorted_set_test.rb # coding: utf-8 require_relative './test_helper' describe 'Sorted Set Commands' do describe 'ZADD' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZADD', '-ERR wrong number of arguments for \'ZADD\' command' ], [ 'ZADD 2.0', '-ERR wrong number of arguments for \'ZADD\' command' ], ] end it 'validates the options' do assert_command_results [ [ 'ZADD z a a', '-ERR value is not a valid float' ], # Weirdly enough, if the score is a valid option, it returns a syntax error # and not a "not a valid float" error [ 'ZADD z nx a', '-ERR syntax error' ], [ 'ZADD z xx a', '-ERR syntax error' ], [ 'ZADD z ch a', '-ERR syntax error' ], [ 'ZADD z incr a', '-ERR syntax error' ], [ 'ZADD z 1.0 a 2.0', '-ERR syntax error' ], [ 'ZADD z 1.0 a incr b', '-ERR value is not a valid float' ], [ 'ZADD z 1.0 a inc b', '-ERR value is not a valid float' ], [ 'ZADD z NX inc 1.0 a 2.0 a', '-ERR syntax error' ], # Typo, inc instead of incr [ 'ZADD z NX XX 1.0 a 2.0 a', '-ERR XX and NX options at the same time are not compatible' ], [ 'ZADD z INCR 1.0 a 2.0 a', '-ERR INCR option supports a single increment-element pair' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZADD not-a-set 2.0 a', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'creates a zset if needed' do test_with_config_values(zset_max_ziplist_entries: [ '128', '2' ]) do assert_command_results [ [ 'ZADD z 2.0 a', ':1' ], [ 'ZRANGE z 0 -1 WITHSCORES', [ 'a', '2' ] ], [ 'TYPE z', '+zset' ], ] end end it 'adds or updates to the set/list' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 a 3.0 b', ':2' ], [ 'ZADD z 2.0 a 4.0 e 0.0 z', ':2' ], [ 'ZADD z 10.0 a 0.1 x 28e1 e', ':1' ], [ 'ZRANGE z 0 -1 WITHSCORES', [ 'z', '0', 'x', '0.1', 'b', '3', 'a', '10', 'e', '280' ] ], ] end end it 'adds or updates the given elements' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 a 3.0 b', ':2' ], [ 'ZADD z 2.0 a 4.0 e 0.0 z', ':2' ], [ 'ZADD z 10.0 a 0.1 x 28e1 e', ':1' ], [ 'ZRANGE z 0 -1 WITHSCORES', [ 'z', '0', 'x', '0.1', 'b', '3', 'a', '10', 'e', '280' ] ], ] end end it 'handles the NX option by not updating existing elements' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 a 3.0 b', ':2' ], [ 'ZADD z NX 1.0 a', ':0' ], [ 'ZADD z NX NX 1.0 a', ':0' ], # doesn't matter if NX is duplicated [ 'ZRANGE z 0 -1 WITHSCORES', [ 'a', '2', 'b', '3' ] ], ] end end it 'handles the XX option by only updating and never adding elements' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 a 3.0 b', ':2' ], [ 'ZADD z XX 1.0 a 10.0 z', ':0' ], [ 'ZADD z XX XX 1.0 a 10.0 z', ':0' ], # doesn't matter if XX is duplicated [ 'ZRANGE z 0 -1 WITHSCORES', [ 'a', '1', 'b', '3' ] ], ] end end it 'handles the CH option by returning the count of added and CHanged elements' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 a 3.0 b', ':2' ], [ 'ZADD z CH XX 1.0 a 10.0 z', ':1' ], [ 'ZRANGE z 0 -1 WITHSCORES', [ 'a', '1', 'b', '3' ] ], [ 'ZADD z CH 11.0 a 10.0 z', ':2' ], [ 'ZRANGE z 0 -1 WITHSCORES', [ 'b', '3', 'z', '10', 'a', '11' ] ], ] end end it 'handles the INCR option by incrementing the existing score' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 a 3.0 b', ':2' ], [ 'ZADD z INCR 1.0 a', '3' ], [ 'ZRANGE z 0 -1 WITHSCORES', [ 'a', '3', 'b', '3' ] ], [ 'ZADD z INCR 1.1 a', '4.1' ], [ 'ZRANGE z 0 -1 WITHSCORES', [ 'b', '3', 'a', '4.1' ] ], [ 'ZADD z INCR CH 1.1 a', '5.2' ], # CH is ignored with INCR [ 'ZRANGE z 0 -1 WITHSCORES', [ 'b', '3', 'a', '5.2' ] ], # There was a bug at some point where this would incorrectly add a new a instead of # updating it [ 'ZADD z 1 a', ':0' ], [ 'ZRANGE z 0 -1 WITHSCORES', [ 'a', '1', 'b', '3' ] ], [ 'ZADD z INCR 1 1', '1' ], [ 'ZADD z INCR 1 1', '2' ], [ 'ZADD z INCR XX 1 1', '3' ], [ 'ZADD z INCR NX 1 1', BYORedis::NULL_BULK_STRING ], [ 'ZADD z INCR inf a', 'inf' ], [ 'ZADD z INCR -inf a', '-ERR resulting score is not a number (NaN)' ], ] end end it 'handles the INCR option by defaulting a non existing member to a 0 score' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z INCR 2.0 a', '2' ], [ 'ZRANGE z 0 -1 WITHSCORES', [ 'a', '2' ] ], [ 'ZADD z INCR 1.1 a', '3.1' ], # There was a bug at some point where the Dict was not getting updated [ 'ZSCORE z a', '3.1' ], [ 'ZRANGE z 0 -1 WITHSCORES', [ 'a', '3.1' ] ], ] end end end describe 'ZCARD' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZCARD', '-ERR wrong number of arguments for \'ZCARD\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZCARD not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns 0 for a non existing zset' do assert_command_results [ [ 'ZCARD z', ':0' ], ] end it 'returns the size of the zset' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 32 john 45.1 z', ':4' ], [ 'ZCARD z', ':4' ], ] end end end describe 'ZRANGE' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZRANGE', '-ERR wrong number of arguments for \'ZRANGE\' command' ], [ 'ZRANGE z', '-ERR wrong number of arguments for \'ZRANGE\' command' ], [ 'ZRANGE z 0', '-ERR wrong number of arguments for \'ZRANGE\' command' ], ] end it 'validates the options' do assert_command_results [ [ 'ZRANGE z 0 1 WITHSCORE', '-ERR syntax error' ], [ 'ZRANGE z 0 1 WITHSCORES a', '-ERR syntax error' ], ] end it 'validates that start and stop are integers' do assert_command_results [ [ 'ZRANGE z a 1 WITHSCORE', '-ERR value is not an integer or out of range' ], [ 'ZRANGE z 0 a WITHSCORES a', '-ERR value is not an integer or out of range' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZRANGE not-a-set 0 -1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns the whole sorted set with 0 -1' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 b 1.0 a 5.1 e 4.0 d', ':4' ], [ 'ZRANGE z 0 -1', [ 'a', 'b', 'd', 'e' ] ], ] end end it 'returns the whole sorted including set with 0 -1 and withscores' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 b 1.0 a 5.1 e 4.0 d', ':4' ], [ 'ZRANGE z 0 -1 withscores', [ 'a', '1', 'b', '2', 'd', '4', 'e', '5.1' ] ], ] end end it 'handles negative indexes as starting from the right side' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 b 1.0 a 5.1 e', ':3' ], [ 'ZRANGE z -3 2', [ 'a', 'b', 'e' ] ], [ 'ZRANGE z -2 1', [ 'b' ] ], [ 'ZRANGE z -2 2', [ 'b', 'e' ] ], [ 'ZRANGE z -1 2', [ 'e' ] ], ] end end it 'works with out of bounds indices' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 b 1.0 a 5.1 e', ':3' ], [ 'ZRANGE z 2 22', [ 'e' ] ], [ 'ZRANGE z -6 0', [ 'a' ] ], ] end end it 'returns an empty array for out of order boundaries' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b', ':1' ], [ 'ZRANGE z 2 1', [] ], [ 'ZRANGE z -1 -2', [] ], ] end end it 'returns subsets' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 b 1.0 a 5.1 e 10.1 f 200.1 z', ':5' ], [ 'ZRANGE z 1 1', [ 'b' ] ], [ 'ZRANGE z 1 3', [ 'b', 'e', 'f' ] ], [ 'ZRANGE z 3 4', [ 'f', 'z' ] ], [ 'ZRANGE z 3 100', [ 'f', 'z' ] ], ] end end end describe 'ZRANGEBYLEX' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZRANGEBYLEX', '-ERR wrong number of arguments for \'ZRANGEBYLEX\' command' ], [ 'ZRANGEBYLEX z', '-ERR wrong number of arguments for \'ZRANGEBYLEX\' command' ], [ 'ZRANGEBYLEX z a', '-ERR wrong number of arguments for \'ZRANGEBYLEX\' command' ], [ 'ZRANGEBYLEX z a', '-ERR wrong number of arguments for \'ZRANGEBYLEX\' command' ], ] end it 'validates the options' do assert_command_results [ [ 'ZRANGEBYLEX z a b LIMIT', '-ERR min or max not valid string range item' ], [ 'ZRANGEBYLEX z [a [b LIMIT', '-ERR syntax error' ], [ 'ZRANGEBYLEX z [a [b LIMIT a', '-ERR syntax error' ], [ 'ZRANGEBYLEX z [a [b LIMIT 0', '-ERR syntax error' ], [ 'ZRANGEBYLEX z [a [b LIMIT 0 a', '-ERR value is not an integer or out of range' ], [ 'ZRANGEBYLEX z [a [b LIMIT a 1', '-ERR value is not an integer or out of range' ], [ 'ZRANGEBYLEX z [a [b LIMIT 0 1 a', '-ERR syntax error' ], ] end it 'validates the format of min and max' do assert_command_results [ [ 'ZRANGEBYLEX z a b', '-ERR min or max not valid string range item' ], [ 'ZRANGEBYLEX z [a b', '-ERR min or max not valid string range item' ], [ 'ZRANGEBYLEX z a (b', '-ERR min or max not valid string range item' ], [ 'ZRANGEBYLEX z - b', '-ERR min or max not valid string range item' ], [ 'ZRANGEBYLEX z a +', '-ERR min or max not valid string range item' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZRANGEBYLEX not-a-set [a [b', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns all elements with - +' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z', ':5' ], [ 'ZRANGEBYLEX z - +', [ 'a', 'b', 'e', 'f', 'z' ] ], ] end end it 'returns an empty array with + -' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z', ':5' ], [ 'ZRANGEBYLEX z + -', [] ], ] end end it 'returns all elements in the range' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':7' ], [ 'ZRANGEBYLEX z - [e', [ 'a', 'b', 'bb', 'bbb', 'e' ] ], [ 'ZRANGEBYLEX z - (e', [ 'a', 'b', 'bb', 'bbb' ] ], [ 'ZRANGEBYLEX z [b [e', [ 'b', 'bb', 'bbb', 'e' ] ], [ 'ZRANGEBYLEX z (b [e', [ 'bb', 'bbb', 'e' ] ], [ 'ZRANGEBYLEX z (bb [e', [ 'bbb', 'e' ] ], [ 'ZRANGEBYLEX z (b +', [ 'bb', 'bbb', 'e', 'f', 'z' ] ], [ 'ZRANGEBYLEX z [b +', [ 'b', 'bb', 'bbb', 'e', 'f', 'z' ] ], [ 'ZRANGEBYLEX z [bbb +', [ 'bbb', 'e', 'f', 'z' ] ], ] end end it 'handles the limit offset count options' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':7' ], [ 'ZRANGEBYLEX z - [e LIMIT 0 2', [ 'a', 'b' ] ], [ 'ZRANGEBYLEX z - [e LIMIT 1 2', [ 'b', 'bb' ] ], [ 'ZRANGEBYLEX z - [e LIMIT 2 2', [ 'bb', 'bbb' ] ], [ 'ZRANGEBYLEX z - [e LIMIT 3 2', [ 'bbb', 'e' ] ], [ 'ZRANGEBYLEX z - [e LIMIT 4 2', [ 'e' ] ], [ 'ZRANGEBYLEX z - [e LIMIT 5 2', [] ], ] end end it 'handles the limit offset count options with a negative count' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':7' ], [ 'ZRANGEBYLEX z - (e LIMIT 0 -1', [ 'a', 'b', 'bb', 'bbb' ] ], [ 'ZRANGEBYLEX z - (e LIMIT 0 -2', [ 'a', 'b', 'bb', 'bbb' ] ], ] end end end describe 'ZRANGEBYSCORE' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZRANGEBYSCORE', '-ERR wrong number of arguments for \'ZRANGEBYSCORE\' command' ], [ 'ZRANGEBYSCORE z', '-ERR wrong number of arguments for \'ZRANGEBYSCORE\' command' ], [ 'ZRANGEBYSCORE z m', '-ERR wrong number of arguments for \'ZRANGEBYSCORE\' command' ], ] end it 'validates the options' do assert_command_results [ [ 'ZRANGEBYSCORE z a b', '-ERR min or max is not a float' ], [ 'ZRANGEBYSCORE z a b withscore', '-ERR min or max is not a float' ], [ 'ZRANGEBYSCORE z a b limit', '-ERR min or max is not a float' ], [ 'ZRANGEBYSCORE z a b limit a', '-ERR min or max is not a float' ], [ 'ZRANGEBYSCORE z a b limit a b', '-ERR min or max is not a float' ], [ 'ZRANGEBYSCORE z 0 1 limi', '-ERR syntax error' ], [ 'ZRANGEBYSCORE z 0 1 limit', '-ERR syntax error' ], [ 'ZRANGEBYSCORE z 0 1 limit a', '-ERR syntax error' ], [ 'ZRANGEBYSCORE z 0 1 limit 0', '-ERR syntax error' ], [ 'ZRANGEBYSCORE z 0 1 limit a b', '-ERR value is not an integer or out of range' ], [ 'ZRANGEBYSCORE z 0 1 limit 0 b', '-ERR value is not an integer or out of range' ], [ 'ZRANGEBYSCORE z 0 1 limit a 0', '-ERR value is not an integer or out of range' ], [ 'ZRANGEBYSCORE z 0 1 withscor', '-ERR syntax error' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZRANGEBYSCORE not-a-set 0 -1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an empty array for nonsensical ranges' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZRANGEBYSCORE z 1 0', [] ], ] end end it 'returns all the elements with a score in the range (inclusive), ordered low to high' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZRANGEBYSCORE z 0 1', [] ], [ 'ZRANGEBYSCORE z 1 4', [ 'a', 'b', 'bb', 'bbb' ] ], [ 'ZRANGEBYSCORE z 5 100', [ 'e', 'f', 'z' ] ], ] end end it 'includes the scores with the withscores options' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZRANGEBYSCORE z 0 1 WITHSCORES', [] ], [ 'ZRANGEBYSCORE z 1 4 WITHSCORES', [ 'a', '1.1', 'b', '2.2', 'bb', '2.22', 'bbb', '2.222' ] ], [ 'ZRANGEBYSCORE z 5 100 WITHSCORES', [ 'e', '5.97', 'f', '6.12345', 'z', '26.2' ] ], ] end end it 'supports -inf and +inf as min/max values' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZRANGEBYSCORE z -inf 1', [] ], [ 'ZRANGEBYSCORE z -infinity 1', [] ], [ 'ZRANGEBYSCORE z -inf 4', [ 'a', 'b', 'bb', 'bbb' ] ], [ 'ZRANGEBYSCORE z -infinity 4', [ 'a', 'b', 'bb', 'bbb' ] ], [ 'ZRANGEBYSCORE z -infinity infinity', [ 'a', 'b', 'bb', 'bbb', 'e', 'f', 'z' ] ], [ 'ZRANGEBYSCORE z 5 inf', [ 'e', 'f', 'z' ] ], [ 'ZRANGEBYSCORE z 5 +inf', [ 'e', 'f', 'z' ] ], [ 'ZRANGEBYSCORE z 5 infinity', [ 'e', 'f', 'z' ] ], [ 'ZRANGEBYSCORE z 5 +infinity', [ 'e', 'f', 'z' ] ], ] end end it 'filters the result with the limit (offset/count) options' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZRANGEBYSCORE z 1 4 LIMIT 0 1', [ 'a' ] ], [ 'ZRANGEBYSCORE z 1 4 LIMIT 1 2', [ 'b', 'bb' ] ], ] end end it 'handles both limit and withscores options' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZRANGEBYSCORE z 1 4 WITHSCORES LIMIT 0 1', [ 'a', '1.1' ] ], [ 'ZRANGEBYSCORE z 1 4 LIMIT 1 2 WITHSCORES', [ 'b', '2.2', 'bb', '2.22' ] ], ] end end it 'accepts exclusive intervals' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZRANGEBYSCORE z 1 (2.2', [ 'a' ] ], [ 'ZRANGEBYSCORE z 1 (2.22', [ 'a', 'b' ] ], ] end end end describe 'ZINTER' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZINTER', '-ERR wrong number of arguments for \'ZINTER\' command' ], [ 'ZINTER a', '-ERR wrong number of arguments for \'ZINTER\' command' ], [ 'ZINTER 1', '-ERR wrong number of arguments for \'ZINTER\' command' ], [ 'ZINTER 2 z', '-ERR syntax error' ], [ 'ZINTER 2 z1 z2 z3', '-ERR syntax error' ], [ 'ZINTER 0', '-ERR wrong number of arguments for \'ZINTER\' command' ], [ 'ZINTER 0 z', '-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE' ], [ 'ZINTER -1 z1', '-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE' ], ] end it 'validates the options' do assert_command_results [ [ 'ZINTER a z1', '-ERR value is not an integer or out of range' ], [ 'ZINTER 2 z1 z2 WEIGHTS', '-ERR syntax error' ], [ 'ZINTER 2 z1 z2 WEIGHTS 0', '-ERR syntax error' ], [ 'ZINTER 2 z1 z2 WEIGHTS 0 0 0', '-ERR syntax error' ], [ 'ZINTER 2 z1 z2 AGGREGATE', '-ERR syntax error' ], [ 'ZINTER 2 z1 z2 AGGREGATE A', '-ERR syntax error' ], [ 'ZINTER 2 z1 z2 AGGREGATE SUM A', '-ERR syntax error' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZINTER 1 not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an empty array if any of the sets do not exist' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZINTER 2 z1 z2', [] ], ] end end it 'returns the full set with a single input' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZINTER 1 z1', [ 'a', 'b', 'e', 'f' ] ], ] end end it 'returns the intersection of all the sets' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZINTER 2 z1 z2', [ 'a', 'b' ] ], [ 'ZINTER 2 z1 z1', [ 'a', 'b', 'e', 'f' ] ], ] end end it 'includes the scores with withscores' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZINTER 2 z1 z2 WITHSCORES', [ 'a', '101.1', 'b', '202.2' ] ], ] end end it 'returns the intersection summing scores with aggregate sum' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZINTER 2 z1 z2 WITHSCORES AGGREGATE SUM', [ 'a', '101.1', 'b', '202.2' ] ], ] end end it 'returns the intersection with the min score with aggregate min' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZINTER 2 z1 z2 WITHSCORES AGGREGATE MIN', [ 'a', '1.1', 'b', '2.2' ] ], ] end end it 'returns the intersection with the max score with aggregate max' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZINTER 2 z1 z2 WITHSCORES AGGREGATE MAX', [ 'a', '100', 'b', '200' ] ], ] end end it 'uses the weights multiplier with the weights option' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZINTER 2 z1 z2 WITHSCORES AGGREGATE SUM WEIGHTS 2 2', [ 'a', '202.2', 'b', '404.4' ] ], [ 'ZINTER 2 z1 z2 WITHSCORES AGGREGATE MIN WEIGHTS 2 2', [ 'a', '2.2', 'b', '4.4' ] ], [ 'ZINTER 2 z1 z2 WITHSCORES AGGREGATE MAX WEIGHTS 2 2', [ 'a', '200', 'b', '400' ] ], [ 'ZINTER 2 z1 z2 WITHSCORES AGGREGATE MAX WEIGHTS 2 inf', [ 'a', 'inf', 'b', 'inf' ] ], ] end end it 'handles infinity * 0 with the weights option' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 0 b 0 a 1 c', ':3' ], [ 'ZADD z2 1 b 2 a 3 c', ':3' ], [ 'ZINTER 2 z1 z2 WITHSCORES WEIGHTS inf 1', [ 'b', '1', 'a', '2', 'c', 'inf' ] ], [ 'ZINTER 2 z1 z2 WITHSCORES WEIGHTS inf 1 AGGREGATE MIN', [ 'a', '0', 'b', '0', 'c', '3' ] ], [ 'ZINTER 2 z1 z2 WITHSCORES WEIGHTS inf 1 AGGREGATE MAX', [ 'b', '1', 'a', '2', 'c', 'inf' ] ], ] end end it 'accepts regular sets as inputs with a default score of 1.0' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'SADD z2 bb b a', ':3' ], [ 'ZINTER 2 z1 z2 WITHSCORES', [ 'a', '2.1', 'b', '3.2' ] ], ] end end it 'converts NaNs to 0 when aggregating' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 inf a -inf b', ':2' ], [ 'ZADD z2 -inf a inf b', ':2' ], [ 'ZINTER 2 z1 z2 WITHSCORES', [ 'a', '0', 'b', '0' ] ], ] end end end describe 'ZINTERSTORE' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZINTERSTORE', '-ERR wrong number of arguments for \'ZINTERSTORE\' command' ], [ 'ZINTERSTORE d', '-ERR wrong number of arguments for \'ZINTERSTORE\' command' ], [ 'ZINTERSTORE 1', '-ERR wrong number of arguments for \'ZINTERSTORE\' command' ], [ 'ZINTERSTORE d 1', '-ERR wrong number of arguments for \'ZINTERSTORE\' command' ], [ 'ZINTERSTORE d 2 z', '-ERR syntax error' ], [ 'ZINTERSTORE d 2 z1 z2 z3', '-ERR syntax error' ], [ 'ZINTERSTORE d 0', '-ERR wrong number of arguments for \'ZINTERSTORE\' command' ], [ 'ZINTERSTORE d 0 z', '-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE' ], [ 'ZINTERSTORE d -1 z1', '-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE' ], ] end it 'validates the options' do assert_command_results [ [ 'ZINTERSTORE d a z1', '-ERR value is not an integer or out of range' ], [ 'ZINTERSTORE d 2 z1 z2 WEIGHTS', '-ERR syntax error' ], [ 'ZINTERSTORE d 2 z1 z2 WEIGHTS 0', '-ERR syntax error' ], [ 'ZINTERSTORE d 2 z1 z2 WEIGHTS 0 0 0', '-ERR syntax error' ], [ 'ZINTERSTORE d 2 z1 z2 AGGREGATE', '-ERR syntax error' ], [ 'ZINTERSTORE d 2 z1 z2 AGGREGATE A', '-ERR syntax error' ], [ 'ZINTERSTORE d 2 z1 z2 AGGREGATE SUM A', '-ERR syntax error' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZINTERSTORE dest 1 not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns 0 and does not create a new set if any of the sets do not exist' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZINTERSTORE dest 2 z1 z2', ':0' ], [ 'TYPE dest', '+none' ], ] end end it 'returns the full set with a single input' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZINTERSTORE dest 1 z1', ':4' ], [ 'ZRANGE dest 0 -1', [ 'a', 'b', 'e', 'f' ] ], ] end end # Weird, but hey, that's how it is it 'accepts but ignores the WITHSCORES option' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZINTERSTORE dest 1 z1 WITHSCORES', ':4' ], [ 'ZRANGE dest 0 -1', [ 'a', 'b', 'e', 'f' ] ], ] end end it 'returns the intersection of all the sets' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZINTERSTORE dest 2 z1 z2', ':2' ], [ 'ZRANGE dest 0 -1', [ 'a', 'b' ] ], ] end end it 'returns the intersection summing scores with aggregate sum' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZINTERSTORE dest 2 z1 z2 AGGREGATE SUM', ':2' ], [ 'ZRANGE dest 0 -1 WITHSCORES', [ 'a', '101.1', 'b', '202.2' ] ], ] end end it 'returns the intersection with the min score with aggregate min' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZINTERSTORE dest 2 z1 z2 AGGREGATE MIN', ':2' ], [ 'ZRANGE dest 0 -1 WITHSCORES', [ 'a', '1.1', 'b', '2.2' ] ], ] end end it 'returns the intersection with the max score with aggregate max' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZINTERSTORE dest 2 z1 z2 AGGREGATE MAX', ':2' ], [ 'ZRANGE dest 0 -1 WITHSCORES', [ 'a', '100', 'b', '200' ] ], ] end end it 'uses the weights multiplier with the weights option' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZINTERSTORE dest 2 z1 z2 AGGREGATE SUM WEIGHTS 2 2', ':2' ], [ 'ZRANGE dest 0 -1 WITHSCORES', [ 'a', '202.2', 'b', '404.4' ] ], [ 'ZINTERSTORE dest 2 z1 z2 AGGREGATE MIN WEIGHTS 2 2', ':2' ], [ 'ZRANGE dest 0 -1 WITHSCORES', [ 'a', '2.2', 'b', '4.4' ] ], [ 'ZINTERSTORE dest 2 z1 z2 AGGREGATE MAX WEIGHTS 2 2', ':2' ], [ 'ZRANGE dest 0 -1 WITHSCORES', [ 'a', '200', 'b', '400' ] ], ] end end it 'accepts regular sets as inputs with a default score of 1.0' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'SADD z2 bb b a', ':3' ], [ 'ZINTERSTORE dest 2 z1 z2', ':2' ], [ 'ZRANGE dest 0 -1 WITHSCORES', [ 'a', '2.1', 'b', '3.2' ] ], ] end end end describe 'ZUNION' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZUNION', '-ERR wrong number of arguments for \'ZUNION\' command' ], [ 'ZUNION a', '-ERR wrong number of arguments for \'ZUNION\' command' ], [ 'ZUNION 1', '-ERR wrong number of arguments for \'ZUNION\' command' ], [ 'ZUNION 2 z', '-ERR syntax error' ], [ 'ZUNION 2 z1 z2 z3', '-ERR syntax error' ], [ 'ZUNION 0', '-ERR wrong number of arguments for \'ZUNION\' command' ], [ 'ZUNION 0 z', '-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE' ], [ 'ZUNION -1 z1', '-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE' ], ] end it 'validates the options' do assert_command_results [ [ 'ZUNION a z1', '-ERR value is not an integer or out of range' ], [ 'ZUNION 2 z1 z2 WEIGHTS', '-ERR syntax error' ], [ 'ZUNION 2 z1 z2 WEIGHTS 0', '-ERR syntax error' ], [ 'ZUNION 2 z1 z2 WEIGHTS 0 0 0', '-ERR syntax error' ], [ 'ZUNION 2 z1 z2 AGGREGATE', '-ERR syntax error' ], [ 'ZUNION 2 z1 z2 AGGREGATE A', '-ERR syntax error' ], [ 'ZUNION 2 z1 z2 AGGREGATE SUM A', '-ERR syntax error' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZUNION 1 not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'ignores empty inputs' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZUNION 2 z1 z2', [ 'a', 'b', 'e', 'f' ] ], ] end end it 'returns the full set with a single input' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZUNION 1 z1', [ 'a', 'b', 'e', 'f' ] ], ] end end it 'returns the union of all the sets' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZUNION 2 z1 z2', [ 'bb', 'bbb', 'e', 'f', 'z', 'a', 'b' ] ], [ 'ZUNION 2 z1 z1', [ 'a', 'b', 'e', 'f' ] ], ] end end it 'includes the scores with withscores' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZUNION 2 z1 z2 WITHSCORES', [ 'bb', '2.22', 'bbb', '2.222', 'e', '5.97', 'f', '6.12345', 'z', '26.2', 'a', '101.1', 'b', '202.2' ] ], ] end end it 'returns the union summing scores with aggregate sum' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZUNION 2 z1 z2 WITHSCORES AGGREGATE SUM', [ 'bb', '2.22', 'bbb', '2.222', 'e', '5.97', 'f', '6.12345', 'z', '26.2', 'a', '101.1', 'b', '202.2' ] ], ] end end it 'returns the union with the min score with aggregate min' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZUNION 2 z1 z2 WITHSCORES AGGREGATE MIN', [ 'a', '1.1', 'b', '2.2', 'bb', '2.22', 'bbb', '2.222', 'e', '5.97', 'f', '6.12345', 'z', '26.2' ] ], ] end end it 'returns the union with the max score with aggregate max' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZUNION 2 z1 z2 WITHSCORES AGGREGATE MAX', [ 'bb', '2.22', 'bbb', '2.222', 'e', '5.97', 'f', '6.12345', 'z', '26.2', 'a', '100', 'b', '200' ] ], ] end end it 'uses the weights multiplier with the weights option' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZUNION 2 z1 z2 WITHSCORES AGGREGATE SUM WEIGHTS 2 2', [ 'bb', '4.44', 'bbb', '4.444', 'e', '11.94', 'f', '12.2469', 'z', '52.4', 'a', '202.2', 'b', '404.4' ] ], [ 'ZUNION 2 z1 z2 WITHSCORES AGGREGATE MIN WEIGHTS 2 2', [ 'a', '2.2', 'b', '4.4', 'bb', '4.44', 'bbb', '4.444', 'e', '11.94', 'f', '12.2469', 'z', '52.4' ] ], [ 'ZUNION 2 z1 z2 WITHSCORES AGGREGATE MAX WEIGHTS 2 2', [ 'bb', '4.44', 'bbb', '4.444', 'e', '11.94', 'f', '12.2469', 'z', '52.4', 'a', '200', 'b', '400' ] ], ] end end it 'accepts regular sets as inputs with a default score of 1.0' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'SADD z2 z bb bbb b a', ':5' ], [ 'ZUNION 2 z1 z2 WITHSCORES', [ 'bb', '1', 'bbb', '1', 'z', '1', 'a', '2.1', 'b', '3.2', 'e', '5.97', 'f', '6.12345' ] ], ] end end it 'handles infinity * 0 with the weights option' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 0 b 0 a 1 c', ':3' ], [ 'ZADD z2 1 b 2 a 3 c', ':3' ], [ 'ZUNION 2 z1 z2 WITHSCORES WEIGHTS inf 1', [ 'b', '1', 'a', '2', 'c', 'inf' ] ], [ 'ZUNION 2 z1 z2 WITHSCORES WEIGHTS inf 1 AGGREGATE MIN', [ 'a', '0', 'b', '0', 'c', '3' ] ], [ 'ZUNION 2 z1 z2 WITHSCORES WEIGHTS inf 1 AGGREGATE MAX', [ 'b', '1', 'a', '2', 'c', 'inf' ] ], ] end end it 'converts NaNs to 0 when aggregating' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 inf a -inf b', ':2' ], [ 'ZADD z2 -inf a inf b', ':2' ], [ 'ZUNION 2 z1 z2 WITHSCORES', [ 'a', '0', 'b', '0' ] ], ] end end end describe 'ZUNIONSTORE' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZUNIONSTORE', '-ERR wrong number of arguments for \'ZUNIONSTORE\' command' ], [ 'ZUNIONSTORE d', '-ERR wrong number of arguments for \'ZUNIONSTORE\' command' ], [ 'ZUNIONSTORE 1', '-ERR wrong number of arguments for \'ZUNIONSTORE\' command' ], [ 'ZUNIONSTORE d 1', '-ERR wrong number of arguments for \'ZUNIONSTORE\' command' ], [ 'ZUNIONSTORE d 2 z', '-ERR syntax error' ], [ 'ZUNIONSTORE d 2 z1 z2 z3', '-ERR syntax error' ], [ 'ZUNIONSTORE d 0', '-ERR wrong number of arguments for \'ZUNIONSTORE\' command' ], [ 'ZUNIONSTORE d 0 z', '-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE' ], [ 'ZUNIONSTORE d -1 z1', '-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE' ], ] end it 'validates the options' do assert_command_results [ [ 'ZUNIONSTORE d a z1', '-ERR value is not an integer or out of range' ], [ 'ZUNIONSTORE d 2 z1 z2 WEIGHTS', '-ERR syntax error' ], [ 'ZUNIONSTORE d 2 z1 z2 WEIGHTS 0', '-ERR syntax error' ], [ 'ZUNIONSTORE d 2 z1 z2 WEIGHTS 0 0 0', '-ERR syntax error' ], [ 'ZUNIONSTORE d 2 z1 z2 AGGREGATE', '-ERR syntax error' ], [ 'ZUNIONSTORE d 2 z1 z2 AGGREGATE A', '-ERR syntax error' ], [ 'ZUNIONSTORE d 2 z1 z2 AGGREGATE SUM A', '-ERR syntax error' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZUNIONSTORE dest 1 not-a-set', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'ignores non existing sorted sets' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZUNIONSTORE dest 2 z1 z2', ':4' ], [ 'ZRANGE dest 0 -1', [ 'a', 'b', 'e', 'f' ] ], ] end end it 'returns the full set with a single input' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZUNIONSTORE dest 1 z1', ':4' ], [ 'ZRANGE dest 0 -1', [ 'a', 'b', 'e', 'f' ] ], ] end end # Weird, but hey, that's how it is it 'accepts but ignores the WITHSCORES option' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZUNIONSTORE dest 1 z1 WITHSCORES', ':4' ], [ 'ZRANGE dest 0 -1', [ 'a', 'b', 'e', 'f' ] ], ] end end it 'returns the union of all the sets' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZUNIONSTORE dest 2 z1 z2', ':7' ], [ 'ZRANGE dest 0 -1', [ 'bb', 'bbb', 'e', 'f', 'z', 'a', 'b' ] ], ] end end it 'returns the union summing scores with aggregate sum' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZUNIONSTORE dest 2 z1 z2 AGGREGATE SUM', ':7' ], [ 'ZRANGE dest 0 -1 WITHSCORES', [ 'bb', '2.22', 'bbb', '2.222', 'e', '5.97', 'f', '6.12345', 'z', '26.2', 'a', '101.1', 'b', '202.2' ] ], ] end end it 'returns the union with the min score with aggregate min' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZUNIONSTORE dest 2 z1 z2 AGGREGATE MIN', ':7' ], [ 'ZRANGE dest 0 -1 WITHSCORES', [ 'a', '1.1', 'b', '2.2', 'bb', '2.22', 'bbb', '2.222', 'e', '5.97', 'f', '6.12345', 'z', '26.2' ] ], ] end end it 'returns the union with the max score with aggregate max' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZUNIONSTORE dest 2 z1 z2 AGGREGATE MAX', ':7' ], [ 'ZRANGE dest 0 -1 WITHSCORES', [ 'bb', '2.22', 'bbb', '2.222', 'e', '5.97', 'f', '6.12345', 'z', '26.2', 'a', '100', 'b', '200' ] ], ] end end it 'uses the weights multiplier with the weights option' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'ZADD z2 26.2 z 2.22 bb 2.222 bbb 200.0 b 100.0 a', ':5' ], [ 'ZUNIONSTORE dest 2 z1 z2 AGGREGATE SUM WEIGHTS 2 2', ':7' ], [ 'ZRANGE dest 0 -1 WITHSCORES', [ 'bb', '4.44', 'bbb', '4.444', 'e', '11.94', 'f', '12.2469', 'z', '52.4', 'a', '202.2', 'b', '404.4' ] ], [ 'ZUNIONSTORE dest 2 z1 z2 AGGREGATE MIN WEIGHTS 2 2', ':7' ], [ 'ZRANGE dest 0 -1 WITHSCORES', [ 'a', '2.2', 'b', '4.4', 'bb', '4.44', 'bbb', '4.444', 'e', '11.94', 'f', '12.2469', 'z', '52.4' ] ], [ 'ZUNIONSTORE dest 2 z1 z2 AGGREGATE MAX WEIGHTS 2 2', ':7' ], [ 'ZRANGE dest 0 -1 WITHSCORES', [ 'bb', '4.44', 'bbb', '4.444', 'e', '11.94', 'f', '12.2469', 'z', '52.4', 'a', '200', 'b', '400' ] ], ] end end it 'accepts regular sets as inputs with a default score of 1.0' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z1 2.2 b 1.1 a 5.97 e 6.12345 f', ':4' ], [ 'SADD z2 z bb bbb b a', ':5' ], [ 'ZUNIONSTORE dest 2 z1 z2', ':7' ], [ 'ZRANGE dest 0 -1 WITHSCORES', [ 'bb', '1', 'bbb', '1', 'z', '1', 'a', '2.1', 'b', '3.2', 'e', '5.97', 'f', '6.12345' ] ], ] end end end describe 'ZRANK' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZRANK', '-ERR wrong number of arguments for \'ZRANK\' command' ], [ 'ZRANK z', '-ERR wrong number of arguments for \'ZRANK\' command' ], [ 'ZRANK z m1 m2', '-ERR wrong number of arguments for \'ZRANK\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZRANK not-a-set m', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns a nil string if the zset does not exist' do assert_command_results [ [ 'ZRANK not-a-set a', BYORedis::NULL_BULK_STRING ], ] end it 'returns a nil string if the zset does not contain the member' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a', ':2' ], [ 'ZRANK z c', BYORedis::NULL_BULK_STRING ], ] end end it 'returns the rank (0-based index) of the member' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a', ':2' ], [ 'ZRANK z a', ':0' ], [ 'ZRANK z b', ':1' ], ] end end end describe 'ZSCORE' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZSCORE', '-ERR wrong number of arguments for \'ZSCORE\' command' ], [ 'ZSCORE z', '-ERR wrong number of arguments for \'ZSCORE\' command' ], [ 'ZSCORE z m1 m2', '-ERR wrong number of arguments for \'ZSCORE\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZSCORE not-a-set m', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns a nil string if the zset does not exist' do assert_command_results [ [ 'ZSCORE not-a-set a', BYORedis::NULL_BULK_STRING ], ] end it 'returns a nil string if the zset does not contain the member' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a', one_of([ ':0', ':2' ]) ], [ 'ZSCORE z c', BYORedis::NULL_BULK_STRING ], ] end end it 'returns the score of the member as a string' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a', ':2' ], [ 'ZSCORE z a', '1.1' ], [ 'ZSCORE z b', '2.2' ], ] end end end describe 'ZMSCORE' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZMSCORE', '-ERR wrong number of arguments for \'ZMSCORE\' command' ], [ 'ZMSCORE z', '-ERR wrong number of arguments for \'ZMSCORE\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZMSCORE not-a-set m', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an array of nil strings if the zset does not exist' do assert_command_results [ [ 'ZMSCORE z a b c', [ nil, nil, nil ] ], ] end it 'returns a nil string for each member not present in the set' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a', ':2' ], [ 'ZMSCORE z c', [ nil ] ], ] end end it 'returns the score of the member as a string for each member present in the set' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a', ':2' ], [ 'ZMSCORE z a', [ '1.1' ] ], [ 'ZMSCORE z b', [ '2.2' ] ], [ 'ZMSCORE z c', [ nil ] ], [ 'ZMSCORE z b a', [ '2.2', '1.1' ] ], [ 'ZMSCORE z a b', [ '1.1', '2.2' ] ], [ 'ZMSCORE z a c b', [ '1.1', nil, '2.2' ] ], ] end end end describe 'ZREM' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZREM', '-ERR wrong number of arguments for \'ZREM\' command' ], [ 'ZREM z', '-ERR wrong number of arguments for \'ZREM\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZREM not-a-set m', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns 0 if the zset does not exist' do assert_command_results [ [ 'ZREM not-a-set a', ':0' ], ] end it 'returns 0 for non existing keys' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 26.2 z', ':3' ], [ 'ZREM z c d e', ':0' ], ] end end it 'returns the number of deleted members' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 26.2 z', ':3' ], [ 'ZREM z z b e', ':2' ], ] end end end describe 'ZREMRANGEBYLEX' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZREMRANGEBYLEX', '-ERR wrong number of arguments for \'ZREMRANGEBYLEX\' command' ], [ 'ZREMRANGEBYLEX z', '-ERR wrong number of arguments for \'ZREMRANGEBYLEX\' command' ], [ 'ZREMRANGEBYLEX z min', '-ERR wrong number of arguments for \'ZREMRANGEBYLEX\' command' ], [ 'ZREMRANGEBYLEX z min max a', '-ERR wrong number of arguments for \'ZREMRANGEBYLEX\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZREMRANGEBYLEX not-a-set [a [a', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'validates the format of min and max' do assert_command_results [ [ 'ZREMRANGEBYLEX z a b', '-ERR min or max not valid string range item' ], [ 'ZREMRANGEBYLEX z [a b', '-ERR min or max not valid string range item' ], [ 'ZREMRANGEBYLEX z a (b', '-ERR min or max not valid string range item' ], [ 'ZREMRANGEBYLEX z - b', '-ERR min or max not valid string range item' ], [ 'ZREMRANGEBYLEX z a +', '-ERR min or max not valid string range item' ], ] end it 'returns 0 if the zset does not exist' do assert_command_results [ [ 'ZREMRANGEBYLEX not-a-set [a [a', ':0' ], ] end it 'returns 0 if no keys are in range' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 13.1 f', ':3' ], [ 'ZREMRANGEBYLEX z [v [z', ':0' ], ] end end it 'removes all the items in the lex range' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':7' ], [ 'ZREMRANGEBYLEX z - [e', ':5' ], [ 'ZRANGE z 0 -1', [ 'f', 'z' ] ], ] assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':5' ], [ 'ZREMRANGEBYLEX z - (e', ':4' ], [ 'ZRANGE z 0 -1', [ 'e', 'f', 'z' ] ], ] assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':4' ], [ 'ZREMRANGEBYLEX z [b [e', ':4' ], [ 'ZRANGE z 0 -1', [ 'a', 'f', 'z' ] ], ] assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':4' ], [ 'ZREMRANGEBYLEX z (b [e', ':3' ], [ 'ZRANGE z 0 -1', [ 'a', 'b', 'f', 'z' ] ], ] assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':3' ], [ 'ZREMRANGEBYLEX z (bb [e', ':2' ], [ 'ZRANGE z 0 -1', [ 'a', 'b', 'bb', 'f', 'z' ] ], ] assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':2' ], [ 'ZREMRANGEBYLEX z (b +', ':5' ], [ 'ZRANGE z 0 -1', [ 'a', 'b' ] ], ] assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':5' ], [ 'ZREMRANGEBYLEX z [b +', ':6' ], [ 'ZRANGE z 0 -1', [ 'a' ] ], ] assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':6' ], [ 'ZREMRANGEBYLEX z [bbb +', ':4' ], [ 'ZRANGE z 0 -1', [ 'a', 'b', 'bb' ] ], ] end end end describe 'ZREMRANGEBYRANK' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZREMRANGEBYRANK', '-ERR wrong number of arguments for \'ZREMRANGEBYRANK\' command' ], [ 'ZREMRANGEBYRANK z', '-ERR wrong number of arguments for \'ZREMRANGEBYRANK\' command' ], [ 'ZREMRANGEBYRANK z 0', '-ERR wrong number of arguments for \'ZREMRANGEBYRANK\' command' ], [ 'ZREMRANGEBYRANK z 0 1 a', '-ERR wrong number of arguments for \'ZREMRANGEBYRANK\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZREMRANGEBYRANK not-a-set 0 1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'validates the format of min and max' do assert_command_results [ [ 'ZREMRANGEBYRANK z a b', '-ERR value is not an integer or out of range' ], [ 'ZREMRANGEBYRANK z 0 b', '-ERR value is not an integer or out of range' ], [ 'ZREMRANGEBYRANK z a 1', '-ERR value is not an integer or out of range' ], ] end it 'returns 0 if the zset does not exist' do assert_command_results [ [ 'ZREMRANGEBYRANK not-a-set 0 1', ':0' ], ] end it 'returns 0 if no keys are in range' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 13.1 f', ':3' ], [ 'ZREMRANGEBYRANK z 30 40', ':0' ], [ 'ZREMRANGEBYRANK z 2 0', ':0' ], ] end end it 'removes all the items in the lex range' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':7' ], [ 'ZREMRANGEBYRANK z 0 4', ':5' ], [ 'ZRANGE z 0 -1', [ 'f', 'z' ] ], ] assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':5' ], [ 'ZREMRANGEBYRANK z 0 3', ':4' ], [ 'ZRANGE z 0 -1', [ 'e', 'f', 'z' ] ], ] assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':4' ], [ 'ZREMRANGEBYRANK z 1 4', ':4' ], [ 'ZRANGE z 0 -1', [ 'a', 'f', 'z' ] ], ] assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':4' ], [ 'ZREMRANGEBYRANK z 2 4', ':3' ], [ 'ZRANGE z 0 -1', [ 'a', 'b', 'f', 'z' ] ], ] assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':3' ], [ 'ZREMRANGEBYRANK z 2 3', ':2' ], [ 'ZRANGE z 0 -1', [ 'a', 'b', 'e', 'f', 'z' ] ], ] assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':2' ], [ 'ZREMRANGEBYRANK z 1 -1', ':6' ], [ 'ZRANGE z 0 -1', [ 'a' ] ], ] assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':6' ], [ 'ZREMRANGEBYRANK z 2 -1', ':5' ], [ 'ZRANGE z 0 -1', [ 'a', 'b' ] ], ] assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':5' ], [ 'ZREMRANGEBYRANK z 3 -1', ':4' ], [ 'ZRANGE z 0 -1', [ 'a', 'b', 'bb' ] ], ] end end end describe 'ZREMRANGEBYSCORE' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZREMRANGEBYSCORE', '-ERR wrong number of arguments for \'ZREMRANGEBYSCORE\' command' ], [ 'ZREMRANGEBYSCORE z', '-ERR wrong number of arguments for \'ZREMRANGEBYSCORE\' command' ], [ 'ZREMRANGEBYSCORE z 0', '-ERR wrong number of arguments for \'ZREMRANGEBYSCORE\' command' ], [ 'ZREMRANGEBYSCORE z 0 1 a', '-ERR wrong number of arguments for \'ZREMRANGEBYSCORE\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZREMRANGEBYSCORE not-a-set 0 1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'validates the format of min and max' do assert_command_results [ [ 'ZREMRANGEBYSCORE z a b', '-ERR min or max is not a float' ], [ 'ZREMRANGEBYSCORE z 0 b', '-ERR min or max is not a float' ], [ 'ZREMRANGEBYSCORE z a 1', '-ERR min or max is not a float' ], ] end it 'returns 0 if the zset does not exist' do assert_command_results [ [ 'ZREMRANGEBYSCORE not-a-set 0 1', ':0' ], ] end it 'returns 0 if no keys are in range' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 13.1 f', ':3' ], [ 'ZREMRANGEBYSCORE z 30 40', ':0' ], [ 'ZREMRANGEBYSCORE z 2 0', ':0' ], ] end end it 'removes all the items in the score range' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.5 e 6.6 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZREMRANGEBYSCORE z 0 4', ':4' ], [ 'ZRANGE z 0 -1', [ 'e', 'f', 'z' ] ], ] assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.5 e 6.6 f 26.2 z 2.22 bb 2.222 bbb', ':4' ], [ 'ZREMRANGEBYSCORE z 0 2.22', ':3' ], [ 'ZRANGE z 0 -1', [ 'bbb', 'e', 'f', 'z' ] ], ] assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.5 e 6.6 f 26.2 z 2.22 bb 2.222 bbb', ':3' ], [ 'ZREMRANGEBYSCORE z 2 4', ':3' ], [ 'ZRANGE z 0 -1', [ 'a', 'e', 'f', 'z' ] ], ] assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.5 e 6.6 f 26.2 z 2.22 bb 2.222 bbb', ':3' ], [ 'ZREMRANGEBYSCORE z 0 100', ':7' ], [ 'ZRANGE z 0 -1', [] ], ] assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.5 e 6.6 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZREMRANGEBYSCORE z 3 +inf', ':3' ], [ 'ZRANGE z 0 -1', [ 'a', 'b', 'bb', 'bbb' ] ], ] assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.5 e 6.6 f 26.2 z 2.22 bb 2.222 bbb', ':3' ], [ 'ZREMRANGEBYSCORE z 3 inf', ':3' ], [ 'ZRANGE z 0 -1', [ 'a', 'b', 'bb', 'bbb' ] ], ] assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.5 e 6.6 f 26.2 z 2.22 bb 2.222 bbb', ':3' ], [ 'ZREMRANGEBYSCORE z 3 infinity', ':3' ], [ 'ZRANGE z 0 -1', [ 'a', 'b', 'bb', 'bbb' ] ], ] assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.5 e 6.6 f 26.2 z 2.22 bb 2.222 bbb', ':3' ], [ 'ZREMRANGEBYSCORE z 3 +infinity', ':3' ], [ 'ZRANGE z 0 -1', [ 'a', 'b', 'bb', 'bbb' ] ], ] assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.5 e 6.6 f 26.2 z 2.22 bb 2.222 bbb', ':3' ], [ 'ZREMRANGEBYSCORE z -inf 7', ':6' ], [ 'ZRANGE z 0 -1', [ 'z' ] ], ] assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.5 e 6.6 f 26.2 z 2.22 bb 2.222 bbb', ':6' ], [ 'ZREMRANGEBYSCORE z -infinity 7', ':6' ], [ 'ZRANGE z 0 -1', [ 'z' ] ], ] end end it 'accepts exclusive intervals' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZREMRANGEBYSCORE z 1 (2.2', ':1' ], [ 'ZRANGE z 0 -1', [ 'b', 'bb', 'bbb', 'e', 'f', 'z' ] ], ] assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':1' ], [ 'ZREMRANGEBYSCORE z 1 (26.2', ':6' ], [ 'ZRANGE z 0 -1', [ 'z' ] ], ] end end end describe 'ZREVRANGE' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZREVRANGE', '-ERR wrong number of arguments for \'ZREVRANGE\' command' ], [ 'ZREVRANGE z', '-ERR wrong number of arguments for \'ZREVRANGE\' command' ], [ 'ZREVRANGE z 0', '-ERR wrong number of arguments for \'ZREVRANGE\' command' ], ] end it 'validates the options' do assert_command_results [ [ 'ZREVRANGE z 0 1 WITHSCORE', '-ERR syntax error' ], [ 'ZREVRANGE z 0 1 WITHSCORES a', '-ERR syntax error' ], ] end it 'validates that start and stop are integers' do assert_command_results [ [ 'ZREVRANGE z a 1 WITHSCORE', '-ERR value is not an integer or out of range' ], [ 'ZREVRANGE z 0 a WITHSCORES a', '-ERR value is not an integer or out of range' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZREVRANGE not-a-set 0 -1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns the whole sorted set with 0 -1' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 b 1.0 a 5.1 e 4.0 d', ':4' ], [ 'ZREVRANGE z 0 -1', [ 'e', 'd', 'b', 'a' ] ], ] end end it 'returns the whole sorted including set with 0 -1 and withscores' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 b 1.0 a 5.1 e 4.0 d', ':4' ], [ 'ZREVRANGE z 0 -1 withscores', [ 'e', '5.1', 'd', '4', 'b', '2', 'a', '1' ] ], [ 'ZREVRANGE z 0 1 withscores', [ 'e', '5.1', 'd', '4' ] ], ] end end it 'handles negative indexes as starting from the right side' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 b 1.0 a 5.1 e', ':3' ], [ 'ZREVRANGE z -3 2', [ 'e', 'b', 'a' ] ], [ 'ZREVRANGE z -2 1', [ 'b' ] ], [ 'ZREVRANGE z -2 2', [ 'b', 'a' ] ], [ 'ZREVRANGE z -1 2', [ 'a' ] ], ] end end it 'works with out of bounds indices' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 b 1.0 a 5.1 e', ':3' ], [ 'ZREVRANGE z 2 22', [ 'a' ] ], [ 'ZREVRANGE z -6 0', [ 'e' ] ], ] end end it 'returns an empty array for out of order boundaries' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b', ':1' ], [ 'ZREVRANGE z 2 1', [] ], [ 'ZREVRANGE z -1 -2', [] ], ] end end it 'returns subsets' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.0 b 1.0 a 5.1 e 10.1 f 200.1 z', ':5' ], [ 'ZREVRANGE z 1 1', [ 'f' ] ], [ 'ZREVRANGE z 1 3', [ 'f', 'e', 'b' ] ], [ 'ZREVRANGE z 3 4', [ 'b', 'a' ] ], [ 'ZREVRANGE z 3 100', [ 'b', 'a' ] ], ] end end end describe 'ZREVRANGEBYLEX' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZREVRANGEBYLEX', '-ERR wrong number of arguments for \'ZREVRANGEBYLEX\' command' ], [ 'ZREVRANGEBYLEX z', '-ERR wrong number of arguments for \'ZREVRANGEBYLEX\' command' ], [ 'ZREVRANGEBYLEX z a', '-ERR wrong number of arguments for \'ZREVRANGEBYLEX\' command' ], [ 'ZREVRANGEBYLEX z a', '-ERR wrong number of arguments for \'ZREVRANGEBYLEX\' command' ], ] end it 'validates the options' do assert_command_results [ [ 'ZREVRANGEBYLEX z a b LIMIT', '-ERR min or max not valid string range item' ], [ 'ZREVRANGEBYLEX z [a [b LIMIT', '-ERR syntax error' ], [ 'ZREVRANGEBYLEX z [a [b LIMIT a', '-ERR syntax error' ], [ 'ZREVRANGEBYLEX z [a [b LIMIT 0', '-ERR syntax error' ], [ 'ZREVRANGEBYLEX z [a [b LIMIT 0 a', '-ERR value is not an integer or out of range' ], [ 'ZREVRANGEBYLEX z [a [b LIMIT a 1', '-ERR value is not an integer or out of range' ], [ 'ZREVRANGEBYLEX z [a [b LIMIT 0 1 a', '-ERR syntax error' ], ] end it 'validates the format of min and max' do assert_command_results [ [ 'ZREVRANGEBYLEX z a b', '-ERR min or max not valid string range item' ], [ 'ZREVRANGEBYLEX z [a b', '-ERR min or max not valid string range item' ], [ 'ZREVRANGEBYLEX z a (b', '-ERR min or max not valid string range item' ], [ 'ZREVRANGEBYLEX z - b', '-ERR min or max not valid string range item' ], [ 'ZREVRANGEBYLEX z a +', '-ERR min or max not valid string range item' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZREVRANGEBYLEX not-a-set [a [b', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns all elements with + -' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z', ':5' ], [ 'ZREVRANGEBYLEX z + -', [ 'z', 'f', 'e', 'b', 'a' ] ], ] end end it 'returns an empty array with - +' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z', ':5' ], [ 'ZREVRANGEBYLEX z - +', [] ], ] end end it 'returns all elements in the range' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':7' ], [ 'ZREVRANGEBYLEX z [e -', [ 'e', 'bbb', 'bb', 'b', 'a' ] ], [ 'ZREVRANGEBYLEX z (e -', [ 'bbb', 'bb', 'b', 'a' ] ], [ 'ZREVRANGEBYLEX z [e [b', [ 'e', 'bbb', 'bb', 'b' ] ], [ 'ZREVRANGEBYLEX z [e (b', [ 'e', 'bbb', 'bb' ] ], [ 'ZREVRANGEBYLEX z [e (bb', [ 'e', 'bbb' ] ], [ 'ZREVRANGEBYLEX z + (b', [ 'z', 'f', 'e', 'bbb', 'bb' ] ], [ 'ZREVRANGEBYLEX z + [b', [ 'z', 'f', 'e', 'bbb', 'bb', 'b' ] ], [ 'ZREVRANGEBYLEX z + [bbb', [ 'z', 'f', 'e', 'bbb' ] ], ] end end it 'handles the limit offset count options' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':7' ], [ 'ZREVRANGEBYLEX z [e - LIMIT 0 2', [ 'e', 'bbb' ] ], [ 'ZREVRANGEBYLEX z [e - LIMIT 1 2', [ 'bbb', 'bb' ] ], [ 'ZREVRANGEBYLEX z [e - LIMIT 2 2', [ 'bb', 'b' ] ], [ 'ZREVRANGEBYLEX z [e - LIMIT 3 2', [ 'b', 'a' ] ], [ 'ZREVRANGEBYLEX z [e - LIMIT 4 2', [ 'a' ] ], [ 'ZREVRANGEBYLEX z [e - LIMIT 5 2', [] ], ] end end it 'handles the limit offset count options with a negative count' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':7' ], [ 'ZREVRANGEBYLEX z (e - LIMIT 0 -1', [ 'bbb', 'bb', 'b', 'a' ] ], [ 'ZREVRANGEBYLEX z (e - LIMIT 0 -2', [ 'bbb', 'bb', 'b', 'a' ] ], ] end end end describe 'ZREVRANGEBYSCORE' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZREVRANGEBYSCORE', '-ERR wrong number of arguments for \'ZREVRANGEBYSCORE\' command' ], [ 'ZREVRANGEBYSCORE z', '-ERR wrong number of arguments for \'ZREVRANGEBYSCORE\' command' ], [ 'ZREVRANGEBYSCORE z m', '-ERR wrong number of arguments for \'ZREVRANGEBYSCORE\' command' ], ] end it 'validates the options' do assert_command_results [ [ 'ZREVRANGEBYSCORE z a b', '-ERR min or max is not a float' ], [ 'ZREVRANGEBYSCORE z a b withscore', '-ERR min or max is not a float' ], [ 'ZREVRANGEBYSCORE z a b limit', '-ERR min or max is not a float' ], [ 'ZREVRANGEBYSCORE z a b limit a', '-ERR min or max is not a float' ], [ 'ZREVRANGEBYSCORE z a b limit a b', '-ERR min or max is not a float' ], [ 'ZREVRANGEBYSCORE z 0 1 limi', '-ERR syntax error' ], [ 'ZREVRANGEBYSCORE z 0 1 limit', '-ERR syntax error' ], [ 'ZREVRANGEBYSCORE z 0 1 limit a', '-ERR syntax error' ], [ 'ZREVRANGEBYSCORE z 0 1 limit 0', '-ERR syntax error' ], [ 'ZREVRANGEBYSCORE z 0 1 limit a b', '-ERR value is not an integer or out of range' ], [ 'ZREVRANGEBYSCORE z 0 1 limit 0 b', '-ERR value is not an integer or out of range' ], [ 'ZREVRANGEBYSCORE z 0 1 limit a 0', '-ERR value is not an integer or out of range' ], [ 'ZREVRANGEBYSCORE z 0 1 withscor', '-ERR syntax error' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZREVRANGEBYSCORE not-a-set 0 -1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an empty array for nonsensical ranges' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZREVRANGEBYSCORE z 0 1', [] ], ] end end it 'returns all the elements with a score in the range (inclusive), ordered high to low' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZREVRANGEBYSCORE z 1 0', [] ], [ 'ZREVRANGEBYSCORE z 4 1', [ 'bbb', 'bb', 'b', 'a' ] ], [ 'ZREVRANGEBYSCORE z 100 5', [ 'z', 'f', 'e' ] ], ] end end it 'includes the scores with the withscores options' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZREVRANGEBYSCORE z 1 0 WITHSCORES', [] ], [ 'ZREVRANGEBYSCORE z 4 1 WITHSCORES', [ 'bbb', '2.222', 'bb', '2.22', 'b', '2.2', 'a', '1.1' ] ], [ 'ZREVRANGEBYSCORE z 100 5 WITHSCORES', [ 'z', '26.2', 'f', '6.12345', 'e', '5.97' ] ], ] end end it 'supports -inf and +inf as min/max values' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZREVRANGEBYSCORE z 1 -inf', [] ], [ 'ZREVRANGEBYSCORE z 1 -infinity', [] ], [ 'ZREVRANGEBYSCORE z 4 -inf', [ 'bbb', 'bb', 'b', 'a' ] ], [ 'ZREVRANGEBYSCORE z 4 -infinity', [ 'bbb', 'bb', 'b', 'a' ] ], [ 'ZREVRANGEBYSCORE z infinity -infinity', [ 'z', 'f', 'e', 'bbb', 'bb', 'b', 'a' ] ], [ 'ZREVRANGEBYSCORE z inf 5', [ 'z', 'f', 'e' ] ], [ 'ZREVRANGEBYSCORE z +inf 5', [ 'z', 'f', 'e' ] ], [ 'ZREVRANGEBYSCORE z infinity 5', [ 'z', 'f', 'e' ] ], [ 'ZREVRANGEBYSCORE z +infinity 5', [ 'z', 'f', 'e' ] ], ] end end it 'filters the result with the limit (offset/count) options' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZREVRANGEBYSCORE z 4 1 LIMIT 0 1', [ 'bbb' ] ], [ 'ZREVRANGEBYSCORE z 4 1 LIMIT 1 2', [ 'bb', 'b' ] ], ] end end it 'handles both limit and withscores options' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a 5.97 e 6.12345 f 26.2 z 2.22 bb 2.222 bbb', ':7' ], [ 'ZREVRANGEBYSCORE z 4 1 WITHSCORES LIMIT 0 1', [ 'bbb', '2.222' ] ], [ 'ZREVRANGEBYSCORE z 4 1 LIMIT 1 2 WITHSCORES', [ 'bb', '2.22', 'b', '2.2' ] ], ] end end end describe 'ZREVRANK' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZREVRANK', '-ERR wrong number of arguments for \'ZREVRANK\' command' ], [ 'ZREVRANK z', '-ERR wrong number of arguments for \'ZREVRANK\' command' ], [ 'ZREVRANK z m1 m2', '-ERR wrong number of arguments for \'ZREVRANK\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZREVRANK not-a-set m', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns a nil string if the zset does not exist' do assert_command_results [ [ 'ZREVRANK not-a-set a', BYORedis::NULL_BULK_STRING ], ] end it 'returns a nil string if the zset does not contain the member' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a', ':2' ], [ 'ZREVRANK z c', BYORedis::NULL_BULK_STRING ], ] end end it 'returns the rank (0-based index) of the member' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 2.2 b 1.1 a', ':2' ], [ 'ZREVRANK z a', ':1' ], [ 'ZREVRANK z b', ':0' ], ] end end end describe 'ZPOPMAX' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZPOPMAX', '-ERR wrong number of arguments for \'ZPOPMAX\' command' ], [ 'ZPOPMAX z a a', '-ERR syntax error' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZPOPMAX not-a-set 1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an empty arrat if the zset does not exist' do assert_command_results [ [ 'ZPOPMAX not-a-set', BYORedis::EMPTY_ARRAY ], ] end it 'validates that count is an integer' do assert_command_results [ [ 'ZPOPMAX z a', '-ERR value is not an integer or out of range' ], ] end it 'does nothing with a 0 or negative count' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 3.333 c 2.2 b 1.1111 a', ':3' ], [ 'ZPOPMAX z 0', BYORedis::EMPTY_ARRAY ], [ 'ZRANGE z 0 -1', [ 'a', 'b', 'c' ] ], ] end end it 'returns the member with the max score, as a 2-element array, and remove it' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 3.333 c 2.2 b 1.1111 a', ':3' ], [ 'ZPOPMAX z', [ 'c', '3.333' ] ], [ 'ZRANGE z 0 -1', [ 'a', 'b' ] ], [ 'ZPOPMAX z', [ 'b', '2.2' ] ], [ 'ZRANGE z 0 -1', [ 'a' ] ], [ 'ZPOPMAX z', [ 'a', '1.1111' ] ], [ 'ZRANGE z 0 -1', [] ], [ 'TYPE z', '+none' ], ] end end it 'removes up to count pairs, sorted from high to low scores' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 3.333 c 2.2 b 1.1111 a', ':3' ], [ 'ZPOPMAX z 10', [ 'c', '3.333', 'b', '2.2', 'a', '1.1111' ] ], [ 'ZRANGE z 0 -1', BYORedis::EMPTY_ARRAY ], [ 'TYPE z', '+none' ], ] assert_command_results [ [ 'ZADD z 3.333 c 2.2 b 1.1111 a', ':3' ], [ 'ZPOPMAX z 2', [ 'c', '3.333', 'b', '2.2' ] ], [ 'ZRANGE z 0 -1', [ 'a' ] ], ] end end end describe 'ZPOPMIN' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZPOPMIN', '-ERR wrong number of arguments for \'ZPOPMIN\' command' ], [ 'ZPOPMIN z a a', '-ERR syntax error' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZPOPMIN not-a-set 1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns an empty arrat if the zset does not exist' do assert_command_results [ [ 'ZPOPMIN not-a-set', BYORedis::EMPTY_ARRAY ], ] end it 'validates that count is an integer' do assert_command_results [ [ 'ZPOPMIN z a', '-ERR value is not an integer or out of range' ], ] end it 'does nothing with a 0 or negative count' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 3.333 c 2.2 b 1.1111 a', ':3' ], [ 'ZPOPMIN z 0', BYORedis::EMPTY_ARRAY ], [ 'ZRANGE z 0 -1', [ 'a', 'b', 'c' ] ], ] end end it 'returns the member with the max score, as a 2-element array, and remove it' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 3.333 c 2.2 b 1.1111 a', ':3' ], [ 'ZPOPMIN z', [ 'a', '1.1111' ] ], [ 'ZRANGE z 0 -1', [ 'b', 'c' ] ], [ 'ZPOPMIN z', [ 'b', '2.2' ] ], [ 'ZRANGE z 0 -1', [ 'c' ] ], [ 'ZPOPMIN z', [ 'c', '3.333' ] ], [ 'ZRANGE z 0 -1', [] ], [ 'TYPE z', '+none' ], ] end end it 'removes up to count pairs, sorted from low to high scores' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 3.333 c 2.2 b 1.1111 a', ':3' ], [ 'ZPOPMIN z 10', [ 'a', '1.1111', 'b', '2.2', 'c', '3.333' ] ], [ 'ZRANGE z 0 -1', BYORedis::EMPTY_ARRAY ], [ 'TYPE z', '+none' ], ] assert_command_results [ [ 'ZADD z 3.333 c 2.2 b 1.1111 a', ':3' ], [ 'ZPOPMIN z 2', [ 'a', '1.1111', 'b', '2.2' ] ], [ 'ZRANGE z 0 -1', [ 'c' ] ], ] end end end describe 'BZPOPMAX' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'BZPOPMAX', '-ERR wrong number of arguments for \'BZPOPMAX\' command' ], [ 'BZPOPMAX z', '-ERR wrong number of arguments for \'BZPOPMAX\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'BZPOPMAX not-a-set 1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'validates that timeout is a float' do assert_command_results [ [ 'BZPOPMAX z a', '-ERR timeout is not a float or out of range' ], [ 'BZPOPMAX z -inf', '-ERR timeout is negative' ], [ 'BZPOPMAX z -infinity', '-ERR timeout is negative' ], [ 'BZPOPMAX z infinity', '-ERR timeout is negative' ], [ 'BZPOPMAX z +infinity', '-ERR timeout is negative' ], [ 'BZPOPMAX z inf', '-ERR timeout is negative' ], [ 'BZPOPMAX z +inf', '-ERR timeout is negative' ], ] end it 'returns the member with the max score from the first non empty set, as a 2-element array, and remove it' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 3.333 c 2.2 b 1.1111 a', ':3' ], [ 'BZPOPMAX z1 z2 z z3 1', [ 'z', 'c', '3.333' ] ], [ 'ZRANGE z 0 -1', [ 'a', 'b' ] ], [ 'ZADD z2 123 John 456 Jane', ':2' ], [ 'BZPOPMAX z1 z2 1', [ 'z2', 'Jane', '456' ] ], [ 'BZPOPMAX z1 z 1', [ 'z', 'b', '2.2' ] ], [ 'ZRANGE z 0 -1', [ 'a' ] ], [ 'BZPOPMAX z3 z 1', [ 'z', 'a', '1.1111' ] ], [ 'ZRANGE z 0 -1', [] ], [ 'TYPE z', '+none' ], ] end end it 'blocks up to timeout and returns a nil array' do with_server do |socket| socket.write(to_query('BZPOPMAX', 'z', '0.2')) assert_nil(read_response(socket, read_timeout: 0.05)) # Still blocked after 200ms, we give up and call it a success! assert_equal(BYORedis::NULL_ARRAY, read_response(socket, read_timeout: 0.3)) end end it 'blocks forever with a 0 timeout' do with_server do |socket| socket.write(to_query('BZPOPMAX', 'z', '0')) # Still blocked after 200ms, we give up and call it a success! assert_nil(read_response(socket, read_timeout: 0.2)) end end it 'returns a pair if any of the sets receives an element before timeout' do with_server do |socket| socket2 = TCPSocket.new 'localhost', 2000 th = Thread.new do sleep 0.05 # Enough time for the BZPOPMAX to be processed socket2.write(to_query('ZADD', 'z', '4.0', 'd', '1.0', 'a')) socket2.close end socket.write(to_query('BZPOPMAX', 'z', '0.5')) th.join assert_equal("*3\r\n$1\r\nz\r\n$1\r\nd\r\n$1\r\n4\r\n", read_response(socket)) end end end describe 'BZPOPMIN' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'BZPOPMIN', '-ERR wrong number of arguments for \'BZPOPMIN\' command' ], [ 'BZPOPMIN z', '-ERR wrong number of arguments for \'BZPOPMIN\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'BZPOPMIN not-a-set 1', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'validates that timeout is a float' do assert_command_results [ [ 'BZPOPMIN z a', '-ERR timeout is not a float or out of range' ], [ 'BZPOPMIN z -inf', '-ERR timeout is negative' ], [ 'BZPOPMIN z -infinity', '-ERR timeout is negative' ], [ 'BZPOPMIN z infinity', '-ERR timeout is negative' ], [ 'BZPOPMIN z +infinity', '-ERR timeout is negative' ], [ 'BZPOPMIN z inf', '-ERR timeout is negative' ], [ 'BZPOPMIN z +inf', '-ERR timeout is negative' ], ] end it 'returns the member with the max score from the first non empty set, as a 2-element array, and remove it' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 3.333 c 2.2 b 1.1111 a', ':3' ], [ 'BZPOPMIN z1 z2 z z3 1', [ 'z', 'a', '1.1111' ] ], [ 'ZRANGE z 0 -1', [ 'b', 'c' ] ], [ 'BZPOPMIN z1 z2 z z3 1', [ 'z', 'b', '2.2' ] ], [ 'BZPOPMIN z1 z2 z z3 1', [ 'z', 'c', '3.333' ] ], [ 'TYPE z', '+none' ], ] end end it 'blocks up to timeout and returns a nil array' do with_server do |socket| socket.write(to_query('BZPOPMIN', 'z', '0.2')) assert_nil(read_response(socket, read_timeout: 0.05)) assert_equal(BYORedis::NULL_ARRAY, read_response(socket, read_timeout: 0.3)) end end it 'blocks forever with a 0 timeout' do with_server do |socket| socket.write(to_query('BZPOPMIN', 'z', '0')) # Still blocked after 200ms, we give up and call it a success! assert_nil(read_response(socket, read_timeout: 0.2)) end end it 'returns a pair if any of the sets receives an element before timeout' do with_server do |socket| socket2 = TCPSocket.new 'localhost', 2000 th = Thread.new do sleep 0.05 # Enough time for the BZPOPMIN to be processed socket2.write(to_query('ZADD', 'z', '4.0', 'd', '1.0', 'a')) socket2.close end socket.write(to_query('BZPOPMIN', 'z', '0.5')) th.join assert_equal("*3\r\n$1\r\nz\r\n$1\r\na\r\n$1\r\n1\r\n", read_response(socket)) end end end describe 'ZCOUNT' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZCOUNT', '-ERR wrong number of arguments for \'ZCOUNT\' command' ], [ 'ZCOUNT z', '-ERR wrong number of arguments for \'ZCOUNT\' command' ], [ 'ZCOUNT z a', '-ERR wrong number of arguments for \'ZCOUNT\' command' ], [ 'ZCOUNT z a b c', '-ERR wrong number of arguments for \'ZCOUNT\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZCOUNT not-a-set 1 2', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'validates that min and max are floats' do assert_command_results [ [ 'ZCOUNT z a b', '-ERR min or max is not a float' ], [ 'ZCOUNT z 1 b', '-ERR min or max is not a float' ], [ 'ZCOUNT z a 1', '-ERR min or max is not a float' ], ] end it 'returns 0 if min and max are out of order' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 1.1 a 3.3 c 2.2 b', ':3' ], [ 'ZCOUNT z +inf -inf', ':0', ], ] end end it 'returns 0 if the sorted set does not exist' do assert_command_results [ [ 'ZCOUNT z -inf +inf', ':0', ], ] end it 'returns the number of members in the range' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 1.1 a 3.3 c 2.2 b', ':3' ], [ 'ZCOUNT z -inf 2.2', ':2', ], [ 'ZCOUNT z 1.1 2.2', ':2', ], [ 'ZCOUNT z -inf +inf', ':3', ], [ 'ZCOUNT z -inf -inf', ':0', ], [ 'ZCOUNT z +inf +inf', ':0', ], ] end end it 'accepts exclusive intervals' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 1.1 a 3.3 c 2.2 b', ':3' ], [ 'ZCOUNT z (2.2 +inf', ':1', ], [ 'ZCOUNT z 1.1 (3.3', ':2', ], ] end end end describe 'ZLEXCOUNT' do it 'handles an unexpected number of arguments' do assert_command_results [ [ 'ZLEXCOUNT', '-ERR wrong number of arguments for \'ZLEXCOUNT\' command' ], [ 'ZLEXCOUNT z', '-ERR wrong number of arguments for \'ZLEXCOUNT\' command' ], [ 'ZLEXCOUNT z a', '-ERR wrong number of arguments for \'ZLEXCOUNT\' command' ], [ 'ZLEXCOUNT z a b c', '-ERR wrong number of arguments for \'ZLEXCOUNT\' command' ], ] end it 'returns an error if the key is not a set' do assert_command_results [ [ 'SET not-a-set 1', '+OK' ], [ 'ZLEXCOUNT not-a-set - +', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'validates the format of min and max' do assert_command_results [ [ 'ZLEXCOUNT z a b', '-ERR min or max not valid string range item' ], [ 'ZLEXCOUNT z [a b', '-ERR min or max not valid string range item' ], [ 'ZLEXCOUNT z a (b', '-ERR min or max not valid string range item' ], [ 'ZLEXCOUNT z - b', '-ERR min or max not valid string range item' ], [ 'ZLEXCOUNT z a +', '-ERR min or max not valid string range item' ], ] end it 'returns 0 if min and max are out of order' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 1.1 a 3.3 c 2.2 b', ':3' ], [ 'ZLEXCOUNT z + -', ':0', ], ] end end it 'returns 0 if the sorted set does not exist' do assert_command_results [ [ 'ZLEXCOUNT z - +', ':0', ], ] end it 'returns the number of members in the range' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z 0 bb 0 bbb', ':7' ], [ 'ZLEXCOUNT z - [e', ':5' ], [ 'ZLEXCOUNT z - (e', ':4' ], [ 'ZLEXCOUNT z [b [e', ':4' ], [ 'ZLEXCOUNT z (b [e', ':3' ], [ 'ZLEXCOUNT z (bb [e', ':2' ], [ 'ZLEXCOUNT z (b +', ':5' ], [ 'ZLEXCOUNT z [b +', ':6' ], [ 'ZLEXCOUNT z [bbb +', ':4' ], [ 'ZLEXCOUNT z - +', ':7', ], [ 'ZLEXCOUNT z - -', ':0', ], [ 'ZLEXCOUNT z + +', ':0', ], ] end end it 'returns all elements with - +' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z', ':5' ], [ 'ZLEXCOUNT z - +', ':5' ], ] end end it 'returns an empty array with + -' do test_with_config_values(zset_max_ziplist_entries: [ '128', '1' ]) do assert_command_results [ [ 'ZADD z 0 b 0 a 0 e 0 f 0 z', ':5' ], [ 'ZLEXCOUNT z + -', ':0' ], ] end end end describe 'ZINCRBY' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'ZINCRBY', '-ERR wrong number of arguments for \'ZINCRBY\' command' ], [ 'ZINCRBY z', '-ERR wrong number of arguments for \'ZINCRBY\' command' ], [ 'ZINCRBY z a', '-ERR wrong number of arguments for \'ZINCRBY\' command' ], [ 'ZINCRBY z a b c', '-ERR wrong number of arguments for \'ZINCRBY\' command' ], ] end it 'fails if the key is not a zset' do assert_command_results [ [ 'SET not-a-zset 1', '+OK' ], [ 'ZINCRBY not-a-zset 1 a', '-WRONGTYPE Operation against a key holding the wrong kind of value' ], ] end it 'returns the new value, as a RESP string of the value for the field, after the incr' do assert_command_results [ [ 'ZADD z 1.0 a 3.0 c 2.0 b', ':3' ], [ 'ZINCRBY z 0.34 a', '1.34' ], ] end it 'returns an error if the increment is not a number (float or int)' do assert_command_results [ [ 'ZADD z 1.0 a 3.0 c 2.0 b', ':3' ], [ 'ZINCRBY z a a', '-ERR value is not a valid float' ], ] end it 'creates a new field/value pair with a value of 0 if the field does not exist' do assert_command_results [ [ 'ZADD z 1.0 a 3.0 c 2.0 b', ':3' ], [ 'ZINCRBY z 5.2 d', '5.2' ], [ 'ZRANGE z 0 -1', [ 'a', 'b', 'c', 'd' ]], ] end it 'creates a new hash and a new field/value pair with a value of 0 if the hash does not exist' do assert_command_results [ [ 'TYPE z', '+none' ], [ 'ZINCRBY z 1.2 a', '1.2' ], [ 'TYPE z', '+zset' ], ] end it 'allows adding inf to inf' do assert_command_results [ [ 'ZINCRBY z inf a', 'inf' ], [ 'ZINCRBY z +inf a', 'inf' ], ] end it 'fails to subtract inf from inf' do assert_command_results [ [ 'ZINCRBY z inf a', 'inf' ], [ 'ZINCRBY z -inf a', '-ERR resulting score is not a number (NaN)' ], ] end end describe 'blocking commands for lists and sets' do it 'handles being blocked for a key that is then created with a different type' do begin socket2 = nil with_server do |socket| socket2 = TCPSocket.new 'localhost', 2000 thread = Thread.new do sleep 0.1 socket2.write(to_query('RPUSH', 'z', '1', '2')) read_response(socket2) socket2.write(to_query('TYPE', 'z')) assert_equal('+list', read_response(socket2).strip) socket2.write(to_query('DEL', 'z')) assert_equal(':1', read_response(socket2).strip) sleep 0.2 socket2.write(to_query('ZADD', 'z', '0', 'a')) assert_equal(':1', read_response(socket2).strip) end socket.write(to_query('BZPOPMAX', 'z', '0')) assert_nil(read_response(socket)) sleep 0.1 assert_equal(BYORedis::RESPArray.new([ 'z', 'a', '0' ]).serialize, read_response(socket)) thread.join end ensure socket2&.close end end end end <file_sep>/code/chapter-4/ttl_command.rb class TtlCommand def initialize(data_store, expires, args) @data_store = data_store @expires = expires @args = args end def call if @args.length != 1 "(error) ERR wrong number of arguments for 'TTL' command" else pttl_command = PttlCommand.new(@data_store, @expires, @args) result = pttl_command.call.to_i if result > 0 (result / 1000.0).round else result end end end end <file_sep>/code/chapter-8/config.rb module BYORedis module Config UnsupportedConfigParameter = Class.new(StandardError) UnknownConfigType = Class.new(StandardError) DEFAULT = { hash_max_ziplist_entries: 512, hash_max_ziplist_value: 64, } @config = DEFAULT.clone def self.set_config(key, value) key = key.to_sym existing_config = @config[key] raise UnsupportedConfigParameter, key unless existing_config case existing_config when Integer @config[key] = Utils.string_to_integer(value) else raise UnknownConfigType, "#{ key }/#{ value }" end end def self.get_config(key) @config[key.to_sym] end end end <file_sep>/content/post/chapter-2-respond-to-get-and-set.md --- title: "Chapter 2 - Respond to Get and Set" date: 2020-05-17T21:28:17-04:00 lastmod: 2020-06-25T14:27:12-04:00 comment: false summary: > In this chapter, we'll build on the foundations we established in the previous chapter. We now know how to start a TCP server using the built-in `TCPServer` class. In this chapter we'll build a basic client using another built-in class, `TCPSocket`. We'll then make the server actually usable by making it respond to two commands, `GET` and `SET`." --- ## What we'll cover In this chapter, we'll build on the foundations we established in the previous chapter. We now know how to start a TCP server using the built-in `TCPServer` class. In this chapter we'll build a basic client using another built-in class, `TCPSocket`. We'll then make the server actually usable by making it respond to two commands, `GET` and `SET`. ## Let's write some code We're going to start by wrapping the code to start a server in a class, because this will make it easier to add functionality later on. Here's the code we'll use for now. ``` ruby require 'socket' class BasicServer def initialize server = TCPServer.new 2000 puts "Server started at: #{ Time.now }" loop do client = server.accept puts "New client connected: #{ client }" client.puts "Hello !" client.puts "Time is #{ Time.now }" client.close end end end ``` We can test this by saving this code in a ruby file, say `server.rb`, and run it with: ```ruby ruby -r "./server" -e "BasicServer.new" ``` We're using this one-liner as a temporary workaround while we don't have an easy way to start the server, with an executable, which would allow to do something like: `./simple-ruby-redis-server`. The command means, run a ruby process, first require the `server.rb` file located in the same folder, and then execute the following command, `BasicServer.new`. We should see a line indicating that the server started, with the current time. Let's confirm that the server is running as expected by running, in a different shell: `nc localhost 2000`, the output should be similar to the following, with a different date: ``` Hello ! Time is 2020-04-18 10:54:10 -0400 ``` You should also see a line in the shell where you started your server, indicating that a client successfully connected: ``` New client connected: #<TCPSocket:0x00007fd83108f9d8> ``` The string after `TCPSocket:0x` will very likely be different on your machine, ruby's default [`to_s`](https://ruby-doc.org/core-2.7.1/Object.html#method-i-to_s) method uses the object id, which is pretty much always gonna be different. ### Reading from the socket in the client So, now that we confirmed that our `BasicServer` class runs correctly, let's connect to it in ruby instead of using `nc`. The direct parent class of `TCPServer` is `TCPSocket`, and according to the documentation: > TCPSocket represents a TCP/IP client socket. So far we've been using the code examples provided in the documentation, we can still do that here, we can paste the lines one by one: ``` ruby irb(main):001:0> require 'socket' => true ``` We already know what this line does, and we can confirm that there is [a file, tcpsocket.c](https://github.com/ruby/ruby/blob/v2_7_1/ext/socket/tcpsocket.c#L88), in the `ruby/ext/socket/` folder, that defines `TCPSocket`. Moving on. ``` ruby irb(main):002:0> s = TCPSocket.new 'localhost', 2000 ``` This line creates a new socket for the given host and port. It requires that a socket is listening on the other side, which you can confirm by either running this before starting your server, by killing your server and re-running this, or by changing the port value to a port that is unused, like 2001. You should see a Connection refused error: `Errno::ECONNREFUSED (Connection refused - connect(2) for "localhost" port 2000)`. `connect(2)` in the previous error message refers to the connect system call. The number 2 refers to the section of the manual, which is an optional argument to the `man` command. It turns out there is no other man page for connect, so you can run `man connect` to learn more about it, or you can be explicit and ask for a specific section, with `man 2 connect`. This is useful for other pages, such as `write`, `man write` returns the page for `write(1)`, but there is also an `write` system call, which you can read the documentation for with `man 2 write`. {{% admonition info "System Calls" %}} As we start adding more features, we'll see more "system calls", often called syscalls, [to quote Wikipedia][wikipedia-syscall]: > In computing, a system call (commonly abbreviated to syscall) is the programmatic way in which a computer program > requests a service from the kernel of the operating system on which it is executed. So far we've implicitly seen two syscalls - `accept`: This is how you connect to existing socket - `socket`: This is how we created the server in the previous chapter There are many syscalls, [this is list on linux][linux-syscalls], there are similarities but the list is different [on macOS][macos-syscalls]. {{% /admonition %}} Let's now look at the `while` loop from the documentation of `TCPSocket`: ``` ruby while (line = s.gets) != nil do puts line end # This is different from the doc, but adapted to a one-liner ``` After running it in `irb`, the output should be: ``` ruby irb(main):003:0> while (line = s.gets) != nil do puts line end Hello ! Time is 2020-04-18 20:34:34 -0400 => nil ``` We used a new method, [`gets`](https://ruby-doc.org/core-2.7.1/IO.html#method-i-gets), its documentation states: > Reads the next "line" from the I/O stream; lines are separated by sep. A separator of nil reads the entire contents, > and a zero-length separator reads the input a paragraph at a time (two successive newlines in the input separate > paragraphs). The stream must be opened for reading or an IOError will be raised. The line read in will be returned and > also assigned to $_. Returns nil if called at end of file. If the first argument is an integer, or optional second > argument is given, the returning string would not be longer than the given value in bytes. As we can see, we were able to connect to the server, on `localhost`, over port 2000, and we were able to read what the server wrote with the `gets` method, one line at a time. In true Ruby fashion, there are a few different ways to read from the socket, the example we just looked at used `gets`, which is defined on `IO`, but if you look at the `IO` documentation, you'll find a few other similar methods, `read`, `read_nonblock`, `readline` & `readlines` to name a few. Exploring the differences between these methods is left as an exercise to the reader. OK, I have to admit, I always wanted to write that. I hate when books/posts do that. But seriously, it's a little bit off topic for now, so we'll get back to it later, `read` can be convenient because it does not require a max length argument as some of the others methods do and defaults to reading the whole thing, aka until it reaches `EOF`, as opposed to doing it line by line like `gets` and `readline` do. As we'll see later on, it's also quite convenient sometimes to read a whole line received through a socket, whereas `read` will keep on reading until it sees `EOF`, which basically means, until the stream is closed. There are at least two other methods, which map closely to system calls, `recvfrom` on `IPSocket` and `recv` on `BasicSocket`. So `gets` it is for now. Let's close this `irb` session and kill the server with `Ctrl-C` for now, and create a new file, `client.rb` with the following content: ``` ruby require 'socket' socket = TCPSocket.new 'localhost', 2000 message = "" message << new_line while new_line = socket.gets puts message ``` And with this last step, we now have a way to exercise what we went through without going through `irb`, first we can start the server with the following command: `ruby -r "./server" -e "BasicServer.new"` The `-r` option from ruby, according to `ruby -h`, is used to "require the library before executing your script". So by passing a relative path, we require the content of the `server.rb` file. The `-e` option is used to "one line of script. Several -e's allowed. [...]". Omitting the `-r` option would fail with a `NameError` because ruby wouldn't be able to find a definition for `BasicServer`. In another shell, run `ruby client.rb` and you will see an output similar to what we saw earlier, `Hello !`, followed by a string containing the time when the server received the connection. Now that we can connect to a server, let's see how to send data. This is a necessary step since we want clients to send `GET` and `SET` requests, and have the server respond accordingly. ### Sending data from the client Let's assume that our server is still running, we can start by sending a string with `nc` with the following command: `echo -n "Hello Server, this is Client" | nc localhost 2000`. The output is still the same, minus the time difference. So let's make some changes to the server to print what we received from the client. As a reminder, our server is an instance of TCPServer, which happens to be a subclass of `TCPSocket`. This is great news, because that means that we can read what the client sent the same way we read what the server sent to the client. This is also an indication that at the end of the day, the client and the server have a lot in common. A socket is open on each side, one of the main differences is that the `TCPServer` class adds the `accept` and `listen` methods, which we can't do with a `TCPSocket`. Let's add a print statement to the server code: ``` ruby loop do client = server.accept puts "New client connected: #{ client }" client_message = client.read if client_message puts "Message received from #{ client }: #{ client_message }" end client.puts "Hello !" client.puts "Time is #{ Time.now }" client.close end ``` Let's close our server if it was still running, with Ctrl-C, and restart it. And re-run the previous `nc` command. The output for the client is the same, we didn't change anything there, but our server logs now show a new line: ``` Server started at: 2020-04-26 20:52:13 -0400 New client connected: #<TCPSocket:0x00007fb879931f78> Message received from #<TCPSocket:0x00007fb879931f78>: Hello Server, this is Client # This is new! ``` Perfect! So it looks like we have all the pieces we need for now: - We can create a client that can connect to our server - The client can send data to the server - The server can read the data sent from the client and write data back - The client can read the data it received from the server ### Wrapping up We want our server to understand two commands, `GET` and `SET`, for the sake of simplicity, let's focus on their most basic versions. `GET` takes one argument, the key name, and return its value if it exists and `(nil)` otherwise. Note that this is purposefully different from the [Redis Protocol](https://redis.io/topics/protocol#resp-bulk-strings). We'll focus on actual redis compatibility later on, once we have a stronger foundation for our implementation. `SET` takes two arguments, the key value and the key name. It sets the value accordingly, erasing the previous value if there was one. All other command will return the following string `` (error) ERR unknown command `foo`, with args beginning with: <args> ``, where \<args\> is everything that follows the command, aka, everything after the first space. We are not performing any other validations for now, again, to focus on having a basic implementation. We'll make it more robust later on. ``` ruby require 'socket' class BasicServer COMMANDS = [ "GET", "SET", ] def initialize @data_store = {} server = TCPServer.new 2000 puts "Server started at: #{ Time.now }" loop do client = server.accept puts "New client connected: #{ client }" client_command_with_args = client.gets if client_command_with_args && client_command_with_args.strip.length > 0 response = handle_client_command(client_command_with_args) client.puts response else puts "Empty request received from #{ client }" end client.close end end private def handle_client_command(client_command_with_args) command_parts = client_command_with_args.split command = command_parts[0] args = command_parts[1..-1] if COMMANDS.include?(command) if command == "GET" if args.length != 1 "(error) ERR wrong number of arguments for '#{ command }' command" else @data_store.fetch(args[0], "(nil)") end elsif command == "SET" if args.length != 2 "(error) ERR wrong number of arguments for '#{ command }' command" else @data_store[args[0]] = args[1] 'OK' end end else formatted_args = args.map { |arg| "`#{ arg }`," }.join(" ") "(error) ERR unknown command `#{ command }`, with args beginning with: #{ formatted_args }" end end end ``` The key element of this implementation is that we initialize an empty `Hash` when creating a new instance of `BasicServer`, and this is what we use to store the data when responding to `SET` requests. Using a `Hash` here could almost be considered "cheating". If you have already looked at the Redis source code, a big part of its implementation is related to how data is stored, and since it's written in C, it can't "just" say: "throw this value, for this key, in this existing data structure and call it a day". That being said, as already mentioned multiple times, we're taking an incremental approach. For now we're focusing on how to integrate the networking parts of our client/server architecture, how to exchange information, and while we're busy with this, Ruby's built-in `Hash` class is a amazing, it supports, among many other, the two main features we need: [`[]`](https://ruby-doc.org/core-2.7.1/Hash.html#method-i-5B-5D) & [`[]=`](https://ruby-doc.org/core-2.7.1/Hash.html#method-i-5B-5D-3D). Redis uses the [SipHash algorithm][wikipedia-siphash], as we can see in the [`siphash.c` file][redis-siphash-file], and as it turns out, this seems to be what [Ruby uses][ruby-source-siphash] as well! I say _seem_ here because by browsing the code I couldn't really confirm that siphash was used in `hash.c`. And here is the client code: ``` ruby require 'socket' class BasicClient COMMANDS = [ "GET", "SET", ] def get(key) socket = TCPSocket.new 'localhost', 2000 result = nil socket.puts "GET #{ key }" result = socket.gets socket.close result end def set(key, value) socket = TCPSocket.new 'localhost', 2000 result = nil socket.puts "SET #{ key } #{ value }" result = socket.gets socket.close result end end ``` Let's confirm that it works as expected, as usual, let's start the server in one shell and run commands from another one with `irb -r "./client"` ``` irb(main):001:0> client = BasicClient.new irb(main):002:0> client.get 1 => "(nil)\n" irb(main):003:0> client.get 2 => "(nil)\n" irb(main):004:0> client.set 1, 2 => "2\n" irb(main):005:0> client.set 2, 3 => "3\n" irb(main):006:0> client.get 1 => "2\n" irb(main):007:0> client.get 2 => "3\n" ``` ## A few tests I apologize if you're a TDD enthusiast because what I'm about to do might make you cringe. Now that we have added these features and manually tested that they worked, we're going to add a few tests. I'm using minitest, because I like how easy it is to setup. Yes, I know, I am technically already breaking the rules I laid out in the "from scratch" section of the first chapter, but we're talking about tests here. While it might be interesting to write a testing library from scratch, and I might do that at some point, I think it's ok to leverage a library and focus on the main task, building a Redis server. And while minitest is a gem, it [has been included by default][ruby-minitest] in ruby for a while now (at least since 2.0), so I'm not _really_ breaking the rules! ``` ruby require 'minitest/autorun' require 'timeout' require 'stringio' require './server' describe 'BasicServer' do def connect_to_server socket = nil # The server might not be ready to listen to accepting connections by the time we try to connect from the main # thread, in the parent process. Using timeout here guarantees that we won't wait more than 1s, which should # more than enough time for the server to start, and the retry loop inside, will retry to connect every 10ms # until it succeeds Timeout::timeout(1) do loop do begin socket = TCPSocket.new 'localhost', 2000 break rescue sleep 0.01 end end end socket end def with_server child = Process.fork do # We're effectively silencing the server with these two lines # stderr would have logged something when it receives SIGINT, with a complete stacktrace $stderr = StringIO.new # stdout would have logged the "Server started ..." & "New client connected ..." lines $stdout = StringIO.new BasicServer.new end yield ensure if child Process.kill('INT', child) Process.wait(child) end end def assert_command_results(command_result_pairs) with_server do command_result_pairs.each do |command, expected_result| begin socket = connect_to_server socket.puts command response = socket.gets assert_equal response, expected_result + "\n" ensure socket.close if socket end end end end describe 'when initialized' do it 'listens on port 2000' do with_server do # lsof stands for "list open files", see for more info https://stackoverflow.com/a/4421674 lsof_result = `lsof -nP -i4TCP:2000 | grep LISTEN` assert_match "ruby", lsof_result end end end describe 'GET' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'GET', '(error) ERR wrong number of arguments for \'GET\' command' ], ] end it 'returns (nil) for unknown keys' do assert_command_results [ [ 'GET 1', '(nil)' ], ] end it 'returns the value previously set by SET' do assert_command_results [ [ 'SET 1 2', 'OK' ], [ 'GET 1', '2'] ] end end describe 'SET' do it 'handles unexpected number of arguments' do assert_command_results [ [ 'SET', '(error) ERR wrong number of arguments for \'SET\' command' ], ] end it 'returns OK' do assert_command_results [ [ 'SET 1 3', 'OK' ], ] end end describe 'Unknown commands' do it 'returns an error message' do assert_command_results [ [ 'NOT A COMMAND', '(error) ERR unknown command `NOT`, with args beginning with: `A`, `COMMAND`,' ], ] end end end ``` There are a few oddities in there, most of them are documented inline, but the main approach is that for each test, we create a new process with `Process.fork`, and we start the server in the new process. We then connect to it from the original process, and send commands over the TCP connection. ## Conclusion Well, that was a lot, but we now have a nice base to build from. There are many things we can do from now, but one that I think is important is to start thinking about how it would handle multiple clients. There are a few major flaws with the current implementation, one of them being that once a client connects, it will block until it receives a new line from the client that just connected, or until the client disconnects. We can reproduce this behavior by opening a third shell, requiring `socket` and creating a new socket connected to `localhost` over port 2000. Now go back to the `irb` console we used previously to test our client and try to call `get` or `set`. It will hang. This is because the server is running a single thread, and that thread is waiting for `client.gets` to return something. We have two ways to make `gets` return, either send a new line with `puts` from the newly created socket, or close it, with `close`. The `BasicClient` works around this issue by never keeping a connection open, when you call `get` or `set`, it starts from scratch, establishes a new connection, sends the command, reads the response, and closes the socket. Effectively killing the connection. This works for now, but is fairly wasteful, TCP connections can stay open and be reused. Let's illustrate this right now, with a non scientific quick benchmark: We'll start by adding a logging statement to the `get` method in the client class, to observe how long it takes to connect to the server, send a command, and get a response: ``` ruby def get(key) t0 = Time.now # ... puts "Time elapsed: #{ (Time.now - t0)*1000 }ms" result end ``` Results vary a lot from one run to another on my machine, but I'm getting in the 1ms to 1.8ms range, ish. Remember that both the client and server are running on the same machine, we would see very different numbers if these were running on different machines. Note: This is something I am really interested in and might take a few minutes to spin up two EC2 instances and see what the numbers are on AWS. Let's now see what it looks like to run two `GET` commands, sequentially: ``` ruby def two_full_gets(key) t0 = Time.now get(key) get(key) puts "Time elapsed: #{ (Time.now - t0)*1000 }ms" end ``` Interestingly I am consistently seeing the second `get` call to be 40% to 100% faster than the first one. After running it a dozen of times, I am seeing results in the 1.6ms to 4ms range. Let's end this quick test by running two gets, over the same connection! ``` ruby def two_gets_a_single_connection(key) t0 = Time.now socket = TCPSocket.new 'localhost', 2000 result = nil socket.puts "GET #{ key }" socket.puts "GET #{ key }" result = socket.gets socket.close puts "Time elapsed: #{ (Time.now - t0)*1000 }ms" result end ``` Again, I ran this about a dozen times, and saw it as low as .982ms and never above 1.4ms. This makes sense, establishing a connection is not free. When we create an instance of `TCPSocket`, ruby delegates to the OS through the `socket` syscall and it attempts to establish a network connection. All of that work is done twice in the first example, and only once in the second example. And once again, it is fair to assume that the difference would be even bigger with two different hosts, because to establish a connection, TCP packets would have to actually travel from one host to the other, over the network, instead of on the same physical machine. The next chapter will look at what our options are to make sure that our server can keep client connections open and still serve all its clients efficiently, without blocking like the current implementation does. ### Code The code from this chapter is [available on GitHub](https://github.com/pjambet/redis-in-ruby/tree/master/code/chapter-2) [wikipedia-syscall]:https://en.wikipedia.org/wiki/System_call [linux-syscalls]:https://man7.org/linux/man-pages/man2/syscalls.2.html [macos-syscalls]:https://opensource.apple.com/source/xnu/xnu-1504.3.12/bsd/kern/syscalls.master [wikipedia-siphash]:https://en.wikipedia.org/wiki/SipHash [redis-siphash-file]:https://github.com/antirez/redis/blob/bf3a67be437e6a3cd5189116d9ad628492db0c4d/src/siphash.c [ruby-source-siphash]:https://github.com/ruby/ruby/blob/v2_7_1/siphash.h [ruby-minitest]:https://github.com/ruby/ruby/tree/v2_7_1/tool/lib/minitest <file_sep>/code/chapter-10/db.rb module BYORedis class DB attr_reader :data_store, :expires, :ready_keys, :blocking_keys, :client_timeouts, :unblocked_clients attr_writer :ready_keys def initialize @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL flush end def flush @data_store = Dict.new @expires = Dict.new @ready_keys = Dict.new @blocking_keys = Dict.new @client_timeouts = SortedArray.by_fields(:timeout) @unblocked_clients = List.new end def lookup_string(key) string_value = @data_store[key] raise WrongTypeError if string_value && !string_value.is_a?(String) string_value end def lookup_list(key) list = @data_store[key] raise WrongTypeError if list && !list.is_a?(List) list end def lookup_list_for_write(key) list = lookup_list(key) if list.nil? list = List.new @data_store[key] = list if @blocking_keys[key] @ready_keys[key] = nil end end list end def lookup_hash(key) hash = @data_store[key] raise WrongTypeError if hash && !hash.is_a?(RedisHash) hash end def lookup_hash_for_write(key) hash = lookup_hash(key) if hash.nil? hash = RedisHash.new @data_store[key] = hash end hash end def lookup_set(key) set = @data_store[key] raise WrongTypeError if set && !set.is_a?(RedisSet) set end def lookup_set_for_write(key) set = lookup_set(key) if set.nil? set = RedisSet.new @data_store[key] = set end set end def lookup_sorted_set(key) sorted_set = @data_store[key] raise WrongTypeError if sorted_set && !sorted_set.is_a?(RedisSortedSet) sorted_set end def lookup_sorted_set_or_set(key) set = @data_store[key] raise WrongTypeError if set && !set.is_a?(RedisSortedSet) && !set.is_a?(RedisSet) set end def lookup_sorted_set_for_write(key) sorted_set = lookup_sorted_set(key) if sorted_set.nil? sorted_set = RedisSortedSet.new @data_store[key] = sorted_set if @blocking_keys[key] @ready_keys[key] = nil end end sorted_set end def pop_max_from(key, sorted_set) generic_pop(key, sorted_set) do sorted_set.pop_max(1) end end def pop_min_from(key, sorted_set) generic_pop(key, sorted_set) do sorted_set.pop_min(1) end end def left_pop_from(key, list) generic_pop(key, list) do list.left_pop.value end end def right_pop_from(key, list) generic_pop(key, list) do list.right_pop.value end end def trim(key, list, start, stop) list.trim(start, stop) @data_store.delete(key) if list.empty? end def delete_from_hash(key, hash, fields) delete_count = 0 fields.each do |field| delete_count += (hash.delete(field) == true ? 1 : 0) end @data_store.delete(key) if hash.empty? delete_count end def remove_from_set(key, set, member) removed = set.remove(member) @data_store.delete(key) if set.empty? removed end def generic_pop(key, collection) popped = yield @data_store.delete(key) if collection.empty? if popped popped else @logger.warn( "Popped from an empty collection or a nil value: #{ key }/#{ collection.class }") nil end end end end <file_sep>/code/chapter-5/ttl_command.rb module BYORedis class TtlCommand def initialize(data_store, expires, args) @data_store = data_store @expires = expires @args = args end def call if @args.length != 1 RESPError.new("ERR wrong number of arguments for 'TTL' command") else pttl_command = PttlCommand.new(@data_store, @expires, @args) result = pttl_command.call.to_i if result > 0 RESPInteger.new((result / 1000.0).round) else RESPInteger.new(result) end end end def self.describe [ 'ttl', 2, # arity # command flags [ 'readonly', 'random', 'fast' ].map { |s| RESPSimpleString.new(s) }, 1, # position of first key in argument list 1, # position of last key in argument list 1, # step count for locating repeating keys # acl categories: https://github.com/antirez/redis/blob/6.0/src/server.c#L161-L166 [ '@keyspace', '@read', '@fast' ].map { |s| RESPSimpleString.new(s) }, ] end end end <file_sep>/code/chapter-10/get_command.rb module BYORedis class GetCommand < BaseCommand def call Utils.assert_args_length(1, @args) key = @args[0] ExpireHelper.check_if_expired(@db, key) value = @db.lookup_string(key) if value.nil? NullBulkStringInstance else RESPBulkString.new(value) end end def self.describe Describe.new('get', 2, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@string', '@fast' ]) end end end <file_sep>/code/chapter-10/pttl_command.rb module BYORedis class PttlCommand < BaseCommand def call Utils.assert_args_length(1, @args) key = @args[0] ExpireHelper.check_if_expired(@db, key) key_exists = @db.data_store.include? key value = if key_exists entry = @db.expires[key] if entry ttl = entry (ttl - (Time.now.to_f * 1000)).round else -1 end else -2 end RESPInteger.new(value) end def self.describe Describe.new('pttl', 2, [ 'readonly', 'random', 'fast' ], 1, 1, 1, [ '@keyspace', '@read', '@fast' ]) end end end <file_sep>/code/chapter-10/list.rb module BYORedis class List ListNode = Struct.new(:value, :prev_node, :next_node) do def remove if prev_node prev_node.next_node = next_node end if next_node next_node.prev_node = prev_node end self.next_node = nil self.prev_node = nil end end Iterator = Struct.new(:cursor, :index, :cursor_iterator, :index_iterator) do def next self.cursor = cursor_iterator.call(cursor) self.index = index_iterator.call(index) end end attr_accessor :head, :tail, :size def initialize @head = nil @tail = nil @size = 0 end def self.left_to_right_iterator(list) # cursor, start_index, iterator, index_iterator Iterator.new(list.head, 0, ->(node) { node.next_node }, ->(i) { i + 1 }) end def self.right_to_left_iterator(list) # cursor, start_index, iterator, index_iterator Iterator.new(list.tail, list.size - 1, ->(node) { node.prev_node }, ->(i) { i - 1 }) end def each(&block) raise 'No block given' unless block iterator = List.left_to_right_iterator(self) while iterator.cursor block.call(iterator.cursor.value) iterator.next end end def empty? @size == 0 end def left_push(value) new_node = ListNode.new(value, nil, @head) if @head.nil? @tail = new_node else @head.prev_node = new_node end @head = new_node @size += 1 end def right_push(value) new_node = ListNode.new(value, @tail, nil) if @head.nil? @head = new_node else @tail.next_node = new_node end @tail = new_node @size += 1 end def left_pop return nil if @size == 0 old_head = @head @size -= 1 @head = @head.next_node @head.prev_node = nil if @head @tail = nil if @size == 0 old_head end def right_pop return nil if @size == 0 old_tail = @tail @size -= 1 @tail = @tail.prev_node @tail.next_node = nil if @tail @head = nil if @size == 0 old_tail end def trim(start, stop) # Convert negative values stop = @size + stop if stop < 0 stop = @size - 1 if stop >= @size start = @size + start if start < 0 start = 0 if start < 0 if start >= @size || start > stop @size = 0 @head = nil @tail = nil return end return if start == 0 && stop == @size - 1 distance_to_start = start distance_to_stop = @size - stop - 1 if distance_to_start <= distance_to_stop iterator = List.left_to_right_iterator(self) target_index = start else iterator = List.right_to_left_iterator(self) target_index = stop end new_head = nil new_tail = nil while iterator.index != target_index iterator.next end # We reached the closest element, either start or stop # We first update either the head and the nail and then find the fastest way to get to the # other boundary if target_index == start new_head = iterator.cursor target_index = stop # We reached start, decide if we should keep going right from where we are or start from # the tail to reach stop if distance_to_stop < stop - iterator.index iterator = List.right_to_left_iterator(self) end else new_tail = iterator.cursor target_index = start # We reached stop, decide if we should keep going left from where we are or start from # the head to reach start if distance_to_start < iterator.index - start iterator = List.left_to_right_iterator(self) end end while iterator.index != target_index iterator.next end # We now reached the other boundary if target_index == start new_head = iterator.cursor else new_tail = iterator.cursor end @head = new_head @head.prev_node = nil # If start == stop, then there's only element left, and new_tail will not have been set # above, so we set here if start == stop new_tail = new_head @size = 1 else # Account for the elements dropped to the right @size -= (@size - stop - 1) # Account for the elements dropped to the left @size -= start end @tail = new_tail @tail.next_node = nil end def set(index, new_value) # Convert a negative index index += @size if index < 0 return if index < 0 || index >= @size distance_from_head = index distance_from_tail = @size - index - 1 if distance_from_head <= distance_from_tail iterator = List.left_to_right_iterator(self) else iterator = List.right_to_left_iterator(self) end while iterator.index != index iterator.next end iterator.cursor.value = new_value end def remove_node(node) if @head == node @head = node.next_node end if @tail == node @tail = node.prev_node end node.remove @size -= 1 end def remove(count, element) delete_count = 0 if count >= 0 iterator = List.left_to_right_iterator(self) else iterator = List.right_to_left_iterator(self) end while iterator.cursor cursor = iterator.cursor if cursor.value == element if @head == cursor @head = cursor.next_node else cursor.prev_node.next_node = cursor.next_node end if @tail == cursor @tail = cursor.prev_node else cursor.next_node.prev_node = cursor.prev_node end delete_count += 1 @size -= 1 if count != 0 && (delete_count == count || delete_count == (count * -1)) break end end iterator.next end delete_count end def position(element, count, maxlen, rank) return if count && count < 0 return if @size == 0 return if rank && rank == 0 match_count = 0 maxlen = @size if maxlen == 0 || maxlen.nil? indexes = [] if count if rank.nil? || rank >= 0 iterator = List.left_to_right_iterator(self) else iterator = List.right_to_left_iterator(self) end while iterator.cursor if (rank.nil? || rank >= 0) && iterator.index >= maxlen break elsif (rank && rank < 0) && (@size - iterator.index - 1) >= maxlen break end if element == iterator.cursor.value match_count += 1 if rank reached_rank_from_head = rank > 0 && match_count >= rank reached_rank_from_tail = rank < 0 && match_count >= (rank * -1) end if rank.nil? || reached_rank_from_head || reached_rank_from_tail return iterator.index if indexes.nil? indexes << iterator.index end return indexes if indexes && indexes.size == count end iterator.next end indexes end def insert_before_node(pivot_node, element) new_node = ListNode.new(element, pivot_node.prev_node, pivot_node) if @head == pivot_node @head = new_node else pivot_node.prev_node.next_node = new_node end pivot_node.prev_node = new_node @size += 1 end def insert_before(pivot, element) generic_insert(pivot) do |node| insert_before_node(node, element) end end def insert_after(pivot, element) generic_insert(pivot) do |node| new_node = ListNode.new(element, node, node.next_node) if @tail == node @tail = new_node else node.next_node.prev_node = new_node end node.next_node = new_node @size += 1 end end def at_index(index) index += @size if index < 0 return if index >= @size || index < 0 distance_to_head = index distance_to_tail = @size - index if distance_to_head <= distance_to_tail iterator = List.left_to_right_iterator(self) else iterator = List.right_to_left_iterator(self) end while iterator.cursor return iterator.cursor.value if iterator.index == index iterator.next end end private def generic_insert(pivot) cursor = @head while cursor break if cursor.value == pivot cursor = cursor.next_node end if cursor.nil? -1 else yield cursor @size end end end class ListSerializer def initialize(list, start, stop) @list = list @start = start @stop = stop end def serialize_with_accumulators(left_to_right_accumulator, right_to_left_accumulator) @stop = @list.size + @stop if @stop < 0 @start = @list.size + @start if @start < 0 @stop = @list.size - 1 if @stop >= @list.size @start = 0 if @start < 0 return EmptyArrayInstance.serialize if @start > @stop response = '' size = 0 distance_to_head = @start distance_to_tail = @list.size - @stop if distance_to_head <= distance_to_tail iterator = List.left_to_right_iterator(@list) within_bounds = ->(index) { index >= @start } stop_condition = ->(index) { index > @stop } accumulator = left_to_right_accumulator else iterator = List.right_to_left_iterator(@list) within_bounds = ->(index) { index <= @stop } stop_condition = ->(index) { index < @start } accumulator = right_to_left_accumulator end until stop_condition.call(iterator.index) if within_bounds.call(iterator.index) size += accumulator.call(iterator.cursor.value, response) end iterator.next end response.prepend("*#{ size }\r\n") end def serialize serialize_with_accumulators( lambda do |value, response| response << RESPBulkString.new(value).serialize 1 end, lambda do |value, response| response.prepend(RESPBulkString.new(value).serialize) 1 end, ) end end end <file_sep>/code/chapter-8/resp_types.rb module BYORedis RESPError = Struct.new(:message) do def serialize "-#{ message }\r\n" end end RESPInteger = Struct.new(:underlying_integer) do def serialize ":#{ underlying_integer }\r\n" end def to_i underlying_integer.to_i end end RESPSimpleString = Struct.new(:underlying_string) do def serialize "+#{ underlying_string }\r\n" end end OKSimpleStringInstance = Object.new.tap do |obj| OK_SIMPLE_STRING = "+OK\r\n".freeze def obj.serialize OK_SIMPLE_STRING end end RESPBulkString = Struct.new(:underlying_string) do def serialize "$#{ underlying_string.bytesize }\r\n#{ underlying_string }\r\n" end end NullBulkStringInstance = Object.new.tap do |obj| NULL_BULK_STRING = "$-1\r\n".freeze def obj.serialize NULL_BULK_STRING end end RESPArray = Struct.new(:underlying_array) do def serialize serialized_items = underlying_array.map do |item| case item when RESPSimpleString, RESPBulkString item.serialize when String RESPBulkString.new(item).serialize when Integer RESPInteger.new(item).serialize when Array RESPArray.new(item).serialize when nil NULL_BULK_STRING end end "*#{ underlying_array.length }\r\n#{ serialized_items.join }" end end EmptyArrayInstance = Object.new.tap do |obj| EMPTY_ARRAY = "*0\r\n".freeze def obj.serialize EMPTY_ARRAY end end NullArrayInstance = Object.new.tap do |obj| NULL_ARRAY = "*-1\r\n".freeze def obj.serialize NULL_ARRAY end end end <file_sep>/code/chapter-8/config_command.rb module BYORedis class ConfigCommand < BaseCommand def call if @args[0] != 'SET' && @args[0] != 'GET' message = "ERR Unknown subcommand or wrong number of arguments for '#{ @args[0] }'. Try CONFIG HELP." RESPError.new(message) elsif @args[0] == 'GET' Utils.assert_args_length(2, @args) value = Config.get_config(@args[1].to_sym) return RESPBulkString.new(Utils.integer_to_string(value)) elsif @args[0] == 'SET' Utils.assert_args_length_greater_than(2, @args) @args.shift # SET @args.each_slice(2) do |key, value| raise RESPSyntaxError if key.nil? || value.nil? Config.set_config(key, value) end end OKSimpleStringInstance end def self.describe Describe.new('config', -2, [ 'admin', 'noscript', 'loading', 'stale' ], 0, 0, 0, [ '@admin', '@slow', '@dangerous' ]) end end end <file_sep>/code/chapter-10/test/sorted_set_unit_test.rb require_relative './test_helper' require_relative '../config' describe BYORedis::RedisSortedSet do before do BYORedis::Config.reset_defaults! end it 'can create an empty set' do sorted_set = new_sorted_set assert(sorted_set) end describe 'when using a list under the hood' do it 'can add elements to a set' do sorted_set = new_sorted_set sorted_set.add(BigDecimal(10), '10') sorted_set.add(BigDecimal(20), 'twenty') sorted_set.add(BigDecimal(5.001, 4), 'five-ish') sorted_set.add(BigDecimal(5.001, 4), 'five') assert_equal(4, sorted_set.cardinality) assert_equal( [ [ 'five', '5.001' ], [ 'five-ish', '5.001' ], [ '10', '10' ], [ 'twenty', '20' ], ], sorted_set_to_a(sorted_set) ) end it 'reorders the set after a score update' do sorted_set = new_sorted_set sorted_set.add(10, '10') sorted_set.add(20, 'twenty') sorted_set.add(5, 'five') assert_equal(3, sorted_set.cardinality) assert_equal( [ [ 'five', '5' ], [ '10', '10' ], [ 'twenty', '20' ], ], sorted_set_to_a(sorted_set) ) sorted_set.add(21, '10') # Yeah, it's confusing. The member '10' now has the score 21 assert_equal(3, sorted_set.cardinality) assert_equal( [ [ 'five', '5' ], [ 'twenty', '20' ], [ '10', '21' ], ], sorted_set_to_a(sorted_set) ) sorted_set.add(20, '10') # Yeah, it's confusing. The member '10' now has the score 20 assert_equal(3, sorted_set.cardinality) assert_equal( [ [ 'five', '5' ], [ '10', '20' ], [ 'twenty', '20' ], ], sorted_set_to_a(sorted_set) ) sorted_set.add(100, 'five') assert_equal(3, sorted_set.cardinality) assert_equal( [ [ '10', '20' ], [ 'twenty', '20' ], [ 'five', '100' ], ], sorted_set_to_a(sorted_set) ) end it 'can remove elements from a set' do sorted_set = new_sorted_set sorted_set.add(10, 'ten') sorted_set.add(11, 'eleven') sorted_set.add(0, 'zero') sorted_set.remove('ten') assert_equal(2, sorted_set.cardinality) assert_equal( [ [ 'zero', '0' ], [ 'eleven', '11' ], ], sorted_set_to_a(sorted_set) ) end it 'can return a sub range of elements, sorted by score' do sorted_set = new_sorted_set sorted_set.add(10, 'ten') sorted_set.add(11, 'eleven') sorted_set.add(0, 'zero') assert_equal(3, sorted_set.cardinality) range_spec = BYORedis::RedisSortedSet::GenericRangeSpec.rank_range_spec(0, 1, sorted_set.cardinality) serializer = BYORedis::SortedSetRankSerializer.new(sorted_set, range_spec, withscores: true) assert_equal( BYORedis::RESPArray.new([ 'zero', '0', 'ten', '10' ]).serialize, serializer.serialize) range_spec = BYORedis::RedisSortedSet::GenericRangeSpec.rank_range_spec(2, 2, sorted_set.cardinality) serializer = BYORedis::SortedSetRankSerializer.new(sorted_set, range_spec, withscores: true) assert_equal( BYORedis::RESPArray.new([ 'eleven', '11' ]).serialize, serializer.serialize) end end describe 'when using a sorted_set, a dict and a sorted array, under the hood' do before do BYORedis::Config.set_config(:zset_max_ziplist_entries, '2') end it 'can add elements' do sorted_set = new_sorted_set sorted_set.add(10, 'ten') sorted_set.add(11, 'eleven') sorted_set.add(0, 'zero') assert_equal(3, sorted_set.cardinality) assert_equal( [ [ 'zero', '0' ], [ 'ten', '10' ], [ 'eleven', '11' ], ], sorted_set_to_a(sorted_set) ) end it 'maintains the order when updating the score of existing elements' do sorted_set = new_sorted_set sorted_set.add(10, 'ten') sorted_set.add(11, 'eleven') sorted_set.add(0, 'zero') sorted_set.add(-1, 'ten') assert_equal(3, sorted_set.cardinality) assert_equal( [ [ 'ten', '-1' ], [ 'zero', '0' ], [ 'eleven', '11' ], ], sorted_set_to_a(sorted_set) ) end it 'can delete elements' do sorted_set = new_sorted_set sorted_set.add(10, 'ten') sorted_set.add(11, 'eleven') sorted_set.add(0, 'zero') sorted_set.remove('ten') assert_equal(2, sorted_set.cardinality) assert_equal( [ [ 'zero', '0' ], [ 'eleven', '11' ], ], sorted_set_to_a(sorted_set) ) end it 'can return a sub range of element, sorted by score' do sorted_set = new_sorted_set sorted_set.add(10, 'ten') sorted_set.add(11, 'eleven') sorted_set.add(0, 'zero') assert_equal(3, sorted_set.cardinality) range_spec = BYORedis::RedisSortedSet::GenericRangeSpec.rank_range_spec(0, 1, sorted_set.cardinality) serializer = BYORedis::SortedSetRankSerializer.new(sorted_set, range_spec, withscores: true) assert_equal( BYORedis::RESPArray.new([ 'zero', '0', 'ten', '10' ]).serialize, serializer.serialize) range_spec = BYORedis::RedisSortedSet::GenericRangeSpec.rank_range_spec(2, 2, sorted_set.cardinality) serializer = BYORedis::SortedSetRankSerializer.new(sorted_set, range_spec, withscores: true) assert_equal( BYORedis::RESPArray.new([ 'eleven', '11' ]).serialize, serializer.serialize) end end it 'switches to a ZSet if the members are too long' do BYORedis::Config.set_config(:zset_max_ziplist_value, '2') sorted_set = new_sorted_set sorted_set.add(10, 't') assert_equal(BYORedis::List, sorted_set.underlying.class) sorted_set.add(10, 'more than two') assert_equal(BYORedis::ZSet, sorted_set.underlying.class) end def new_sorted_set BYORedis::RedisSortedSet.new end def sorted_set_to_a(sorted_set) members = [] sorted_set.each do |pair| members << [ pair.member, BYORedis::Utils.float_to_string(pair.score) ] end members end end <file_sep>/code/chapter-9/test/utils_test.rb require_relative './test_helper' describe BYORedis::Utils do describe 'string_to_integer' do it 'returns an error with an empty string' do assert_raises BYORedis::InvalidIntegerString do BYORedis::Utils.string_to_integer('') end end it 'returns an error for just a - sign' do assert_raises BYORedis::InvalidIntegerString do BYORedis::Utils.string_to_integer('-') end end it 'returns an error with a float' do error = assert_raises BYORedis::InvalidIntegerString do BYORedis::Utils.string_to_integer('1.0') end assert_equal("Not a number: '46' / '.'", error.message) end it 'returns an error with a leading zero' do assert_raises BYORedis::InvalidIntegerString do BYORedis::Utils.string_to_integer('01') end assert_raises BYORedis::InvalidIntegerString do BYORedis::Utils.string_to_integer('-01') end end it 'returns 0 with "0"' do assert_equal(0, BYORedis::Utils.string_to_integer('0')) end it 'works with a string representing a non overflowing integer' do assert_equal(256, BYORedis::Utils.string_to_integer('256')) assert_equal(9_223_372_036_854_775_807, BYORedis::Utils.string_to_integer('9223372036854775807')) # 2^63 - 1 end it 'raises an overflow' do error = assert_raises BYORedis::IntegerOverflow do BYORedis::Utils.string_to_integer('18446744073709551616') # 2^64 end assert_equal('Overflow before +', error.message) error = assert_raises BYORedis::IntegerOverflow do BYORedis::Utils.string_to_integer('9223372036854775808') # 2^63 end assert_equal('Too big for a long long', error.message) error = assert_raises BYORedis::IntegerOverflow do BYORedis::Utils.string_to_integer('-9223372036854775809') # 2^63 end assert_equal('Too small for a long long', error.message) error = assert_raises BYORedis::IntegerOverflow do BYORedis::Utils.string_to_integer('18446744073709551620') # 2^64 + 2 end assert_equal('Overflow before *', error.message) end it 'handles negative numbers' do assert_equal(-1, BYORedis::Utils.string_to_integer('-1')) assert_equal(-9_223_372_036_854_775_808, BYORedis::Utils.string_to_integer('-9223372036854775808')) # -1 * 2^63 end end describe 'integer_to_string' do it 'works with 0' do assert_equal('0', BYORedis::Utils.integer_to_string(0)) end it 'works with positive numbers' do assert_equal('1', BYORedis::Utils.integer_to_string(1)) assert_equal('9223372036854775807', BYORedis::Utils.integer_to_string(9_223_372_036_854_775_807)) end it 'works with negative numbers' do assert_equal('-1', BYORedis::Utils.integer_to_string(-1)) assert_equal('-9223372036854775808', BYORedis::Utils.integer_to_string(-9_223_372_036_854_775_808)) end end end <file_sep>/code/chapter-10/del_command.rb module BYORedis class DelCommand < BaseCommand def initialize(db, args) @db = db @args = args end def call Utils.assert_args_length_greater_than(0, @args) keys = @args deleted_count = 0 keys.each do |key| entry = @db.data_store.delete(key) if entry != nil @db.expires.delete(key) deleted_count += 1 end end RESPInteger.new(deleted_count) end def self.describe Describe.new('del', -2, [ 'write' ], 1, -1, 1, [ '@keyspace', '@write', '@slow' ]) end end end <file_sep>/code/chapter-8/hash_commands.rb require_relative './redis_hash' module BYORedis class HSetCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) key = @args.shift raise InvalidArgsLength unless @args.length.even? hash = @db.lookup_hash_for_write(key) count = 0 @args.each_slice(2).each do |pair| key = pair[0] value = pair[1] count += 1 if hash.set(key, value) end RESPInteger.new(count) end def self.describe Describe.new('hset', -4, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@hash', '@fast' ]) end end class HGetAllCommand < BaseCommand def call Utils.assert_args_length(1, @args) hash = @db.lookup_hash(@args[0]) if hash.nil? pairs = [] else pairs = hash.get_all end RESPArray.new(pairs) end def self.describe Describe.new('hgetall', 2, [ 'readonly', 'random' ], 1, 1, 1, [ '@read', '@hash', '@slow' ]) end end class HDelCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) key = @args.shift hash = @db.lookup_hash(key) delete_count = 0 if hash delete_count += @db.delete_from_hash(key, hash, @args) end RESPInteger.new(delete_count) end def self.describe Describe.new('hdel', -3, [ 'write', 'fast' ], 1, 1, 1, [ '@write', '@hash', '@fast' ]) end end class HExistsCommand < BaseCommand def call Utils.assert_args_length(2, @args) hash = @db.lookup_hash(@args[0]) if hash.nil? RESPInteger.new(0) else value = hash[@args[1]] if value.nil? RESPInteger.new(0) else RESPInteger.new(1) end end end def self.describe Describe.new('hexists', 3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@hash', '@fast' ]) end end class HGetCommand < BaseCommand def call Utils.assert_args_length(2, @args) hash = @db.lookup_hash(@args[0]) if hash.nil? NullBulkStringInstance else key = @args[1] value = hash[key] if value.nil? NullBulkStringInstance else RESPBulkString.new(value) end end end def self.describe Describe.new('hget', 3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@hash', '@fast' ]) end end class HIncrByCommand < BaseCommand def call Utils.assert_args_length(3, @args) incr = Utils.validate_integer(@args[2]) key = @args[0] field = @args[1] hash = @db.lookup_hash_for_write(key) value = hash[field] if value.nil? value = 0 else value = Utils.string_to_integer(value) end if (incr < 0 && value < 0 && incr < (LLONG_MIN - value)) || (incr > 0 && value > 0 && incr > (LLONG_MAX - value)) raise IntegerOverflow else new_value = value + incr end hash[field] = Utils.integer_to_string(new_value) RESPInteger.new(new_value) rescue InvalidIntegerString RESPError.new('ERR hash value is not an integer') rescue IntegerOverflow RESPError.new('ERR increment or decrement would overflow') end def self.describe Describe.new('hincrby', 4, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@hash', '@fast' ]) end end class HIncrByFloatCommand < BaseCommand def call Utils.assert_args_length(3, @args) incr = Utils.validate_float(@args[2], 'ERR value is not a valid float') key = @args[0] field = @args[1] hash = @db.lookup_hash_for_write(key) value = hash[field] if value.nil? value = BigDecimal(0) else value = Utils.validate_float(value, 'ERR hash value is not a float') end new_value = value + incr if new_value.nan? || new_value.infinite? RESPError.new('ERR increment would produce NaN or Infinity') else new_value_as_string = Utils.float_to_string(new_value) hash[field] = new_value_as_string RESPBulkString.new(new_value_as_string) end rescue InvalidFloatString RESPError.new('ERR hash value is not a float') end def self.describe Describe.new('hincrbyfloat', 4, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@hash', '@fast' ]) end end class HKeysCommand < BaseCommand def call Utils.assert_args_length(1, @args) hash = @db.lookup_hash(@args[0]) if hash.nil? EmptyArrayInstance else RESPArray.new(hash.keys) end end def self.describe Describe.new('hkeys', 2, [ 'readonly', 'sort_for_script' ], 1, 1, 1, [ '@read', '@hash', '@slow' ]) end end class HLenCommand < BaseCommand def call Utils.assert_args_length(1, @args) hash = @db.lookup_hash(@args[0]) hash_length = 0 unless hash.nil? hash_length = hash.length end RESPInteger.new(hash_length) end def self.describe Describe.new('hlen', 2, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@hash', '@fast' ]) end end class HMGetCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) key = @args.shift hash = @db.lookup_hash(key) if hash.nil? responses = Array.new(@args.length) else responses = @args.map do |field| hash[field] end end RESPArray.new(responses) end def self.describe Describe.new('hmget', -3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@hash', '@fast' ]) end end class HSetNXCommand < BaseCommand def call Utils.assert_args_length(3, @args) key = @args[0] field = @args[1] value = @args[2] hash = @db.lookup_hash_for_write(key) if hash[field] RESPInteger.new(0) else hash[field] = value RESPInteger.new(1) end end def self.describe Describe.new('hsetnx', 4, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@hash', '@fast' ]) end end class HStrLenCommand < BaseCommand def call Utils.assert_args_length(2, @args) key = @args[0] field = @args[1] hash = @db.lookup_hash(key) value_length = 0 unless hash.nil? value = hash[field] value_length = value.length unless value.nil? end RESPInteger.new(value_length) end def self.describe Describe.new('hstrlen', 3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@hash', '@fast' ]) end end class HValsCommand < BaseCommand def call Utils.assert_args_length(1, @args) hash = @db.lookup_hash(@args[0]) if hash.nil? EmptyArrayInstance else RESPArray.new(hash.values) end end def self.describe Describe.new('hvals', 2, [ 'readonly', 'sort_for_script' ], 1, 1, 1, [ '@read', '@hash', '@slow' ]) end end end <file_sep>/content/post/chapter-11-bitmaps.md --- title: "Chapter 11 Adding Bitmaps Commands" date: 2020-10-17T18:17:39-04:00 lastmod: 2020-10-17T18:17:39-04:00 draft: true comment: false keywords: [] summary: "" --- <!--more--> https://redis.io/topics/data-types-intro#bitmaps BITCOUNT BITFIELD BITOP BITPOS GETBIT SETBIT <file_sep>/code/chapter-7/test/test_helper.rb require 'minitest/autorun' require 'timeout' require 'stringio' require 'logger' ENV['LOG_LEVEL'] = 'FATAL' unless ENV['LOG_LEVEL'] require_relative '../server' def connect_to_server socket = nil # The server might not be ready to listen to accepting connections by the time we try to connect from the main # thread, in the parent process. Using timeout here guarantees that we won't wait more than 1s, which should # more than enough time for the server to start, and the retry loop inside, will retry to connect every 10ms # until it succeeds Timeout.timeout(1) do loop do begin socket = TCPSocket.new 'localhost', 2000 break rescue sleep 0.01 end end end socket end def with_server child = Process.fork do unless !!ENV['DEBUG'] # We're effectively silencing the server with these two lines # stderr would have logged something when it receives SIGINT, with a complete stacktrace $stderr = StringIO.new # stdout would have logged the "Server started ..." & "New client connected ..." lines $stdout = StringIO.new end begin BYORedis::Server.new rescue Interrupt # Expected code path given we call kill with 'INT' below end end server_socket = connect_to_server yield server_socket ensure server_socket&.close if child Process.kill('INT', child) begin Timeout.timeout(1) do Process.wait(child) end rescue Timeout::Error Process.kill('KILL', child) end end end # The arguments in an array of array of the form # [ # [ [ "COMMAND-PART-I", "COMMAND-PART-II", ... ], "EXPECTED_RESULT" ], # ... # ] def assert_multipart_command_results(multipart_command_result_pairs) with_server do |server_socket| multipart_command_result_pairs.each do |command, expected_result| command.each do |command_part| server_socket.write command_part # Sleep for one milliseconds to give a chance to the server to read # the first partial command sleep 0.001 end response = read_response(server_socket) if response.length < expected_result.length # If the response we got is shorter, maybe we need to give the server a bit more time # to finish processing everything we wrote, so give it another shot sleep 0.1 response += read_response(server_socket) end assert_response(expected_result, response) end end end def assert_command_results(command_result_pairs) with_server do |server_socket| command_result_pairs.each do |command, expected_result| if command.is_a?(String) && command.start_with?('sleep') sleep command.split[1].to_f next end command_string = if command.start_with?('*') command else BYORedis::RESPArray.new(command.split).serialize end server_socket.write command_string response = read_response(server_socket) assert_response(expected_result, response) end end end def assert_response(expected_result, response) assertion_match = expected_result&.match(/(\d+)\+\/-(\d+)/) if expected_result.is_a?(String) if assertion_match response_match = response.match(/\A:(\d+)\r\n\z/) assert response_match[0] assert_in_delta assertion_match[1].to_i, response_match[1].to_i, assertion_match[2].to_i else if expected_result&.is_a?(Array) expected_result = BYORedis::RESPArray.new(expected_result).serialize elsif expected_result && !%w(+ - : $ *).include?(expected_result[0]) # Convert to a Bulk String unless it is a simple string (starts with a +) # or an error (starts with -) expected_result = BYORedis::RESPBulkString.new(expected_result).serialize end if expected_result && !expected_result.end_with?("\r\n") expected_result += "\r\n" end if expected_result.nil? assert_nil response else assert_equal expected_result, response end end end def read_response(server_socket, read_timeout: 0.1) response = nil loop do select_res = IO.select([ server_socket ], [], [], read_timeout) last_response = server_socket.read_nonblock(1024, exception: false) if last_response == :wait_readable || last_response.nil? || select_res.nil? break else if response.nil? response = last_response else response += last_response end break if response.length < 1024 end end response&.force_encoding('utf-8') rescue Errno::ECONNRESET response&.force_encoding('utf-8') end def to_query(*command_parts) BYORedis::RESPArray.new(command_parts).serialize end <file_sep>/content/post/chapter-9-adding-set-commands.md --- title: "Chapter 9 Adding Set Commands" date: 2020-11-10T09:01:31-05:00 lastmod: 2020-11-10T09:01:42-05:00 draft: false comment: false keywords: [] summary: "In this chapter we add support for one more data type, Sets. We implement most of the SET commands such as SADD, SINTER, SUNION and SDIFF" --- ## What we'll cover Our server now supports Strings, albeit not all string commands are implemented, Lists and Hashes. Redis supports three more native data types, Sets, Sorted Sets and Streams. Streams being a recent addition to Redis, and being a fairly complicated topic, will not be covered in this book. Other data types exists, such as Bitmaps, HyperLogLog and Geospatial items, but all of these are implemented on top of the String native type. In this chapter we will add support for the Set type. Conceptually a Set is a collection of unique items, and can therefore not contain duplicates. A common operation for Sets, beside the ability to add items to a set, is testing for the presence of an item. Such operation would ideally require constant time, that is a complexity of O(1). Wikipedia defines [a set][wikipedia-set-type] as: > In computer science, a set is an abstract data type that can store unique values, without any particular order. Sets, in computer science are very similar to [Finite Sets][wikipedia-finite-sets] in Mathematics. Redis Sets only store strings. Given these constraints, it looks like our `Dict` data structure would be a great fit to implement an API for Sets. The `Dict` class stores key/value pairs, where keys are strings, so we wouldn't even need to add any values in the dict, adding key/value pairs with `nil` values would be sufficient. It is interesting to consider that many data structures can be used to provide a set API. For instance Ruby arrays can be used as set with the following methods: ``` ruby def new_set [] end def include?(set, member) set.include?(member) end def add(set, member) if include?(set, member) false else set << member true end end ``` _listing 9.1 A Set using a Ruby array_ These three methods do provide the API for a set, but the performance, especially in the worst case scenario, will degrade quickly as the set grows. The `include?` method needs to iterate over the entire array to return `false`, so calling `include?` for a member that is not in the array, will _always_ require a full iteration of the array. The `List` class we created in [Chapter 7][chapter-7] could also be used to implement a set but would suffer from the exact same performance issues. Ruby has a [`Set` class][ruby-set-class], but we will not use it to follow the "build from scratch" approach we've been using so far. Redis supports [sixteen set commands][redis-set-commands]: - **SADD**: Add one or more members to a set, creating it if necessary - **SCARD**: Return the _cardinality_ of the set, the number of members - **SDIFF**: Compute the difference of sets, from left to right - **SDIFFSTORE**: Same as SDIFF but store the result in another key instead of returning it - **SINTER**: Compute the intersection of all given sets - **SINTERSTORE**: Same as `SINTER` but store the result in another key instead of returning it - **SUNION**: Compute the union of all given sets - **SUNIONSTORE**: Same as `SUNION` but store the result in another key instead of returning it - **SISMEMBER**: Return `0` or `1` depending on whether or not the given member is in the given set - **SMEMBERS**: Return all the members of the given set - **SMISMEMBER** (_new in 6.2.0_): Variadic version of `SISMEMBER`, that is, it accepts multiple arguments and returns an array - **SMOVE**: Move a member from one set to another - **SPOP**: Remove _a_ member from the given set - **SRANDMEMBER**: Return _a_ member from the given set, but leave it in the set - **SREM**: Remove the given member from the given set - **SSCAN**: Similar to `SCAN`, `HSCAN` & `ZSCAN`. We will not implement it for the same reason we did not implement `HSCAN` in [Chapter 8][chapter-8] ## How does Redis do it? As mentioned in the previous chapter, the set commands are implemented in the [`t_set.c`][redis-src-tset] file, in which Redis uses two different data structures to store the data. As long as the elements, also called members in a set, can be represented as integers, and that the size of the set if below the [`set-max-intset-entries`][redis-config-max-intset-entries] config value, which has a default value of `512`, Redis uses an intset, and otherwise uses the dictionary from `dict.c`. We already created the `Dict` class in [Chapter 6][chapter-6], but the intset is a new data structure. Using an `IntSet` provides two interesting benefits, the memory footprint of the set is smaller, and most set operations will be faster than with a `dict` when the number of members is small. Note that while sets do not have to be ordered, int sets are actually ordered, which is how it provides a reasonably fast way to check for the existence of an element in a set, through binary search. Everything is a string in a `dict`, this means that the number `1` would be stored as the character `'1'`, which uses one byte of memory, eight bits, and the number `1,000` would be stored as the string `'1000'` and use four bytes, thirty two bits. This means that large numbers, such as, `1,000,000,000,000`, one trillion, which is composed of thirteen digits, would use thirteen bytes, one hundred and four bits. Storing these values as 64-bit integers would improve things for large numbers, one trillion would only require sixty four bits instead of one hundred and four, but it would actually make things worse for small numbers. If we were to store the number one as a 64-bit integer, it would use sixty four bits instead of eight if we stored it as a character. Redis' `intset` type uses an `encoding` variable, which determine the size of the integers stored. Because the `intset` structure uses an array, it has to use the same underlying type for all elements. This is what allows indexed access in O(1) time. If we want to access the element at index `i`, we can multiply `i` by the size of the variables stored in the array, and we'll land on the i-th element. The content of the `intset` is an array of `int8_t`, so that each element uses exactly one byte. This allows Redis to store all the integers in this array, in 8-bit chunks, the actual length of each integer is determined by the encoding of the `intset`. Redis uses three possible encoding values, `int16_t`, `int_32_t` & `int64_t`, respectively 16-bit integers, 32-bit integers, and 64-bit integers. When an `intset` is created, its encoding is set to 16-bit integers. Whenever new members are added to the set, Redis tries to find the smallest encoding that can hold the value. `int16_t` can range from `-2^15` to `2^15 - 1`, `-32,768` to `32,767`, `int32_t` from `-2^31` to `2^31 - 1`, `-2,147,483,648` to `2,147,483,647` and `int64_t` from `-2^63` to `2^63 - 1`, `-9,223,372,036,854,775,808` to `9,223,372,036,854,775,807`. With this approach, storing numbers between `0` & `9` would still be more expensive, because they would be store as 16-bit integers, but we're already breaking even for negative numbers from `-1` to `-9`, and we're saving space for numbers lower than or equal to `-10`, which would use three bytes as strings, and only use two as 16-bit integers, and for numbers greater than or equal to `100`. The benefits become even greater as the number grow in either direction. Speed wise, the benefits are the same that what we discussed in the previous chapter in the ziplist vs dict section. Using an `intset` will gradually become slower as the `intset` grows, but all operations will be really fast when the number of members is small. Large `intset` structure suffer from the same issues than ziplists and become slow to manipulate as they grow, because the whole memory chunk needs to be reallocated and items within it moved, to make space for new elements. The intset functionalities are implemented in [`intset.c`][redis-src-intset]. An intset is essentially a sorted array of integers. We already implemented a sorted array, the `SortedArray` class, but the requirements are a little bit different here so we will create an `IntSet` class to mimic the Redis behavior. As mentioned in the previous section, a dictionary provide a solid foundation to implement the Set API. It turns out that this is exactly what Redis does. When handling the `SADD` command, if the underlying data structure is a `dict`, it calls the `dictAdd` function with the member as the key, and nothing as the value, this is done in the [`setTypeAdd` function][redis-src-dictadd]. Our `Dict` class already exists, and will only require a few changes, to make sure that it handles entries with `nil` values without any hiccups, on the other hand, we need to build an `IntSet` class from scratch, so let's get to it. ### The IntSet data structure Because the intset structure uses a sorted array, this makes the time complexity of a lookup O(logn), which will be worse than O(1) when the array gets bigger. Additionally, because arrays are contiguous chunks of memory, inserting an element requires a lot of work, to shift all the elements to the right of the new element. This makes arrays more and more expensive to manipulate as they grow in size, and explains why Redis only uses it if sets contain `512` items or less. Redis stores all values in little endian in an intset. This means that the number `1`, which has the following binary representation as a 16-bit integer: ``` ruby irb(main):025:0> ('%016b' % 1).chars.each_slice(8).map { |byte| byte.join }.join(' ') => "00000000 00000001" ``` The two bytes, `\x00` & `\x01` need to be reversed in little endian, because the least significant bytes come first, so the bytes of `1`, in little endian are `[ "\x01", "\x00" ]`. Let's look at a larger example, the representation of `1,000,000` as a 32-bit integer: ``` ruby irb(main):027:0> ('%032b' % 1_000_000).chars.each_slice(8).map { |byte| byte.join }.join(' ') => "00000000 00001111 01000010 01000000" ``` The big endian bytes are `[ "\x00", "\x0F", "\x42", "\x40" ]`, and `[ "\x40", "\x42", "\x0F", "\x00 ]` as little endian. Another way to play with these values is to use the [`Array#pack`][ruby-doc-array-pack] method, with the `l` format, which is the format for signed 32-bit integer, which uses the native endianness of the platform by default, but can be forced to use big endian with `l>` and little endian with `l<`: ``` ruby irb(main):043:0> [1_000_000].pack('l') => "@B\x0F\x00" irb(main):044:0> [1_000_000].pack('l>') => "\x00\x0FB@" irb(main):045:0> [1_000_000].pack('l<') => "@B\x0F\x00" ``` This example illustrates that the default endianness of my machine, a macbook pro, is little endian. Note that some of these bytes don't look like the others, `"@"` & `"B"` vs `"\x0F"` and `"\x00"`. This is because Ruby attempts to display the characters as ASCII by default, and it turns out that `"\x42"` is the hex representation of the decimal `66`, the character `'B'` in ASCII and `"\x40"` is the hex representation of the decimal `64`, the character `'@'` in ASCII. Our class will implement the following public methods: - `add(member)` - `cardinality` - `each` - `contains?(member)` - `members` - `pop` - `random_member` - `empty?` - `remove(member)` The methods above will allow us to implement all the Set related commands. All the following methods are implemented in the `int_set.rb` file, under the `BYORedis::IntSet` class, let's start with the constructor and the `add` method: ``` ruby module BYORedis class IntSet INT16_MIN = -2**15 # -32,768 INT16_MAX = 2**15 - 1 # 32,767 INT32_MIN = -2**31 # -2,147,483,648 INT32_MAX = 2**31 - 1 # 2,147,483,647 INT64_MIN = -2**63 # -9,223,372,036,854,775,808 INT64_MAX = 2**63 - 1 # 9,223,372,036,854,775,807 # Each of the constant value represents the number of bytes used to store an integer ENCODING_16_BITS = 2 ENCODING_32_BITS = 4 ENCODING_64_BITS = 8 def initialize @underlying_array = [] @encoding = ENCODING_16_BITS end def add(member) raise "Member is not an int: #{ member }" unless member.is_a?(Integer) # Ruby's Integer can go over 64 bits, but this class can only store signed 64 bit integers # so we use this to reject out of range integers raise "Out of range integer: #{ member }" if member < INT64_MIN || member > INT64_MAX encoding = encoding_for_member(member) return upgrade_and_add(member) if encoding > @encoding # search always returns a value, either the position of the item or the position where it # should be inserted position = search(member) return false if get(position) == member move_tail(position, position + 1) if position < size set(position, member) true end private def set(position, member) @encoding.times do |i| index = (position * @encoding) + i @underlying_array[index] = ((member >> (i * 8)) & 0xff).chr end end def move_tail(from, to) @underlying_array[(to * @encoding)..-1] = @underlying_array[(from * @encoding)..-1] end def search(member) min = 0 max = size - 1 mid = -1 current = -1 # the index is always 0 for an empty array return 0 if empty? if member > get(max) return size elsif member < get(min) return 0 end while max >= min mid = (min + max) >> 1 current = get(mid) if member > current min = mid + 1 elsif member < current max = mid - 1 else break end end if member == current mid else min end end def get(position) get_with_encoding(position, @encoding) end def get_with_encoding(position, encoding) return nil if position >= size bytes = @underlying_array[position * encoding, encoding] # bytes is an array of bytes, in little endian, so with the small bytes first # We could iterate over the array and "assemble" the bytes into in a single integer, # by performing the opposite we did in set, that is with the following # # bytes.lazy.with_index.reduce(0) do |sum, (byte, index)| # sum | (byte << (index * 8)) # end # # But doing do would only work if the final result was positive, if the first bit of the # last byte was a 1, then the number we're re-assembling needs to be a negative number, we # could do so with the following: # # negative = (bytes[-1] >> 7) & 1 == 1 # # And at the end of the method, we could apply the following logic to obtain the value, # get the 1 complement, with `~` and add 1. We also need to apply a mask to make sure that # the 1 complement result stays within the bounds of the current encoding # For instance, with encoding set to 2, the mask would be 0xffff, which is 65,535 # # if negative # mask = (2**(encoding * 8) - 1) # v = -1 * ((~v & mask) + 1) # end # # Anyway, we can use the pack/unpack methods to let Ruby do that for us, calling # bytes.pack('C*') will return a string of bytes, for instance, the number -128 is stored # in the intset as [ 128, 255 ], calling, `.pack('C*')` returns "\x80\xFF". Next up, we # pick the right format, 's' for 16-bit integers, 'l' for 32 and 'q' for 64 and we let # Ruby put together the bytes into the final number. # The result of unpack is an array, but we use unpack1 here, which is a shortcut to # calling unpack() followed by [0] # # What this whole thing tells us is that we could have used `.pack('s').bytes` in the # set method, but using >> 8 is more interesting to understand actually what happens! format = case encoding when ENCODING_16_BITS then 's' when ENCODING_32_BITS then 'l' when ENCODING_64_BITS then 'q' end bytes.join.unpack1(format) end def encoding_for_member(member) if member < INT32_MIN || member > INT32_MAX ENCODING_64_BITS elsif member < INT16_MIN || member > INT16_MAX ENCODING_32_BITS else ENCODING_16_BITS end end def upgrade_and_add(member) current_encoding = @encoding current_size = size new_size = current_size + 1 @encoding = encoding_for_member(member) prepend = member < 0 ? 1 : 0 @underlying_array[(new_size * @encoding) - 1] = nil # Allocate a bunch of nils # Upgrade back to front while (current_size -= 1) >= 0 value = get_with_encoding(current_size, current_encoding) # Note the use of the prepend variable to shift all elements one cell to the right in # the case where we need to add the new member as the first element in the array set(current_size + prepend, value) end if prepend == 1 set(0, member) else set(size - 1, member) end true end end end ``` _listing 9.2 The `IntSet#add` method, and all the private methods it requires_ The `add` method starts with a few checks to make sure that we can indeed add the given member to the set. If the value is not an integer or is out of range, we reject it right away. The next step is to find the smallest encoding that can fit `member`. Once we found the encoding, either `2`, `4` or `8`, we compare it to the current encoding of the set. If the new encoding is greater, then we know that `member` is either going to be the smallest entry in the set, or the largest, because it would otherwise have used the same encoding. The `upgrade_and_add` method takes care of migrating all current elements to the new encoding, and inserts the new member, either at index `0` or as the last element in the array. Let's look at the three main steps of the `upgrade_and_add` method, first it increases the size of the array, with `@underlying_array[(new_size * @encoding) - 1] = nil`, which pads the array to the right with `nil` values until the new size, let's look at an example: ``` ruby irb(main):029:0> l = ["\x01", "\x00", "\x02", "\x00"] ``` This array is what the `@underlying_array` of an `IntSet` storing the values `1` and `2` would be. `"\x01"` and `"\x00"` is the little endian representation of the number `1` in a 16-bit integer, `0000 0001 0000 0000`. The first byte, `0000 0001`, written as `0x01` in the Ruby hex literal syntax is the byte for the number `1`, since `2^0 == 1`. The second byte, the most significant one only contains zeroes: `0000 0000`. If the number had been `258`, the two bytes would have been `0000 0010 0000 0001`. The first byte is the least significant one, `0000 0010`, these are the bits between index `0` and `7`, representing the number `2`, and the most significant one is `0000 0001`, the bits between index `8` and `15`, representing the number `1`. Putting it all together we get `2^1 + 2^8 == 258`. Another way to write this number is `"\x02\x01"` `"\x02"`, `"\x00"`, is the little endian representation of the number `2`, `0000 0010 0000 0000`, written as `0x0002` as a hex literal. Note that hex literals in Ruby follow the "natural" order and assume big-endian. So `0x0002` returns `1`, whereas `0x0200` returns `512`, because `0000 0010 0000 0000` is `512` in big endian, `2^9 == 512`. If we were to increase the encoding to 32-bit, to store numbers larger than `32,767`, each number would now need to use four bytes, so the array would now need to be `12` item long, `4 bytes x 3 members`, as we can see, calling `l[11]` adds all the `nil` values: ``` ruby irb(main):030:0> l[11] = nil irb(main):031:0> l => ["\x01", "\x00", "\x02", "\x00", nil, nil, nil, nil, nil, nil, nil, nil] ``` The next step, upgrading all the elements, is done in the `while` loop. In our previous example, `current_size` would be `1`. Calling `get_with_encoding(2, 2)` would read the numbers `2` and `0`, and return `2`. Calling `set(1 + 0, 2)` would insert the four bytes representing `2` at the right place in the array. If we were to add `32,768`, then `prepend` would be `0`. The `set` method splits the number into the number of bytes for the encoding, with the new encoding being `4`, to store numbers as 32-bit integer, we would iterate four times with the `@encoding.times` loop. In the first iteration `index` would be `(1 * 4) + 0`, `4` and the value would be `"\x01"` because `((member >> 0) 0xff).chr` returns `"\x01"` if member is `1`. `0xFF` acts as a mask here, it is the hex literal for the number `255`, a byte of only ones, we could have written `0b11111111`, it just happens to be easier to use `0xff`, but they're identical. We use `0xff` in combination of the bitwise `AND` operator, `&`, which effectively only selects the rightmost byte of any numbers. We call `.chr`, which is equivalent to calling `.pack('C')`. This allows us transform the `Integer` instance into a one-byte string. As we've already discussed, Ruby has a special handling for numbers, which is why it can handle numbers greater than what a 64-bit integer can handle, but it also means that we don't have any direct visibility in what is actually allocated when we have an instance of the `Integer` class. Using `.pack('C')` treats the number in the array as an 8-bit integer, a byte. What we get in return is a one-character string, representing the byte value. Let's look at an example: ``` ruby irb(main):001:0> [1].pack('C') => "\x01" irb(main):002:0> 1.chr => "\x01" irb(main):003:0> [255].pack('C') => "\xFF" irb(main):004:0> 255.chr => "\xFF" irb(main):005:0> [128].pack('C') => "\x80" irb(main):006:0> [1].pack('C') => "\x01" irb(main):007:0> [255].pack('C') => "\xFF" irb(main):008:0> [128].pack('C') => "\x80" irb(main):009:0> [128].pack('C').size => 1 irb(main):010:0> [128].pack('C').chars => ["\x80"] ``` Even though it looks like the strings returned by `pack`/`chr` contains four characters, a double-quoted Ruby string handles the `\x` prefix in a special way, and as we can see with the last two examples, it only contains a single character. The next iteration would give `index` the value `5`, and set the value `0` at index `5`. The last two iterations would set the value `0` for index `6` and `7`. Back to `upgrade_and_add`, the `while` loop would run one more time with `current_size == 0` and upgrade the encoding of `1`. After the while loop the array would contain the following, the existing inters have been migrated from 16-bit integers to 32-bit integers, in little endian, which result in right padding them with bytes containing zeroes: ``` ruby [ "\x01", "\x00", "\x00", "\x00", "\x02", "\x00", "\x00", "\x00", nil, nil, nil, nil, ] ``` The last step of the method is to add the new member, in this example `prepend` is not set to `1` and it is inserted as the last item with `set(size - 1, member)`, where `size == 3`. `set` will split `32,768` into four bytes, which would be represented in big endian as the four bytes: `0x00`, `0x00`, `0x80`, & `0x00`: ``` ruby # '%032b' % 32_768 => MSB LSB (Most Significant Byte/Least Significant Byte) |-------| |-------| |-------| |-------| 7 0 7 0 7 0 7 0 (indices within each byte) ∨ ∨ ∨ ∨ ∨ ∨ ∨ ∨ 0000 0000 0000 0000 1000 0000 0000 0000 ∧ ∧ ∧ ∧ ∧ 31 15 11 3 0 (indices within a 32-bit integer) ``` The only `1` in the previous binary number is at index `15`, `2^15 = 32,768`. The four bytes have the decimal values, `0`, `0`, `128` & `0`. The second byte from the right have the value `128` because within that byte, the only `1` is at index `7` and `2^7 = 128`. Redis stores these numbers in little endian, so we store them in reverse order with the least significant bytes first: `[ 0, 128, 0, 0 ]`. The hex literal representation of `128` is `0x80`. With that, the final value of `@underlying_array` is: ``` ruby [ "\x01", "\x00", "\x00", "\x00", "\x02", "\x00", "\x00", "\x00", "\x00", "\x80", "\x00", "\x00", ] ``` The next step in `add` is to search for `member` in the array, which we do with the `search` method. The method always returns an integer, which is either the position of `member` in the array or the position where it should be inserted. The `search` method uses a divide and conquer approach to find the element. First, it checks if the element should go at the front of the array, if the new member is smaller than the element at index 0, or at the end of the array if it is greater than the last element in array. If neither of these checks are true, we look at the value at index `mid`, because we know that the array is sorted, we compare that value with `member`, if it is greater than `member`, then we know that `member` will either be on the left side, or not present and we set the `max` to `mid - 1`, effectively narrowing the range to the left side of the array. We perform the opposite operation if the value at index `mid` is lower than `member`, then we want to keep searching on the right half of the array, and we do so with `min = mid + 1`. We stop iterating if neither of these checks are true, that is, if `current == member`, in which case `mid` is the index of `member`. The other condition causing the loop to exit is if `min` becomes greater than `max`, which means that we did not find `member` in the array, in which case `min` is the index where it should be inserted. Let's look at an example to illustrate this: ``` ruby array = [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65] ``` The variable `array` contains twelve elements, so `min` will start at `0`, `max` at `11` and `mid` & `current` at `-1`. If we were to search for `56`, we would enter the `while` loop and set `mid` to `(min + max) >> 1`, which is `(0 + 11) >> 1`, `5`, this is because `11` is `0b1011` in binary, and shifting it to the right one time results in `101`, `2^0 + 2^2`, `5`. `array[5] == 35`, so `member > current` and we set `min` to `mid + 1`, `6`. Using a bitwise right shift of `1` is a "trick" to divide a number by two. Let's look at an example to illustrate it. With the previous example, `min` is `0`, `max` is `11`. Given that the array has an even number of items, there's no index where there would be the same number of elements to the left and to the right, but we can still use the integer division to find an index that is close to that, `11 / 2 == 5`, so far so good. ``` 1011 (11) >> 1 ---- 0101 (5) ``` This property, that shifting by one to the right is the same as dividing by two happens to be the result from how we represent numbers in binary. A `1` in binary represent a power of two, so `11` is binary is really the sum of `2^0`, `2^1` & `2^3`. Shifting by one to the right returns the number that is the sum of `2^0` and `2^1`, which happens to be the result of an integer division by two. This also works with even numbers: ``` 1100 (10) >> 1 ---- 0110 (6) ``` Tada! If it feels a little bit like magic, I encourage you to experiment with different numbers, either on paper or with `irb`, it took me a little while until it "clicked". Back to the `search` method. On the next iteration `mid` becomes `8`, because `(6 + 11) >> 1` is `0b10001 >> 1`, which is `0b1000`, `8`. `array[8] == 50`, so we set `min` to `9`. On the next iteration, `mid` becomes `10`, because `(9 + 11) >> 1` is `0b10100 >> 1`, `0b1010`, `10`. `array[10] == 60`, so this time we set `max` to `mid - 1`, `9`. On the next and last iteration, `mid` is `9`, because `(9 + 9) >> 1` is `0b10010 >> 1`, `0b1001`, `9`. `array[9] == 55`, so `min` becomes `10`, and the loop exits because `min > max`. `9` happens to be the index where `56` should be inserted to maintain the array sorted. Reading values from the array, which is what the `get` method does, is more complicated than in a regular array. Our set members span across multiple cells in the array, because each cell contains one byte. So a member spans across two cells with the 16-bit encoding, four with the 32-bit encoding and eight with the 64-bit encoding. The `get_with_encoding` method grabs all the bytes and uses the `unpack1` method to reconstruct the integer from its byte parts. Ruby knows how to convert the bytes based on the format string, `s` means `signed short integer`, `int16_t`, `l` means `signed long integer`, `int32_t` and `q` means `signed long long integer`, `int64_t`. These methods give us the foundation to write the remaining methods, let's look at `each`, `members`, `empty?` & `size`: ``` ruby module BYORedis class IntSet # ... def empty? @underlying_array.empty? end def each(&block) members.each(&block) end def members size.times.map do |index| get(index) end end def size @underlying_array.size / @encoding end alias cardinality size alias card cardinality private # ... end end ``` _listing 9.3 The `empty?`, `each`, `members` and `size` methods in the `IntSet` class_ The `empty?` method relies on the `Array#empty?` method, we don't need to change anything to its default behavior. The `size` method uses `Array#size` and divides the result by the size of encoding. This is because with the 16-bit encoding each integer will be split over two elements in the array, four elements with 32-bit and eight elements with 64-bit. `members` uses `size` to determine how many times to iterate with the `Integer#times` method and passes the index to the `get` method we wrote earlier, which knows how to reassemble multiple array items into integers. Doing this in the block to `map` returns an array of `Integer` instances. Finally the `each` method forwards its `block` argument to `Array#each` on the result of `members`. An important method of the `IntSet` class is the `include?` method, which we can express in terms of `search` and `get`: ``` ruby module BYORedis class IntSet # ... def include?(member) return false if member.nil? index = search(member) get(index) == member end alias member? include? # ... end end ``` _listing 9.4 The `IntSet#include?` method, aliased to `member?`_ `pop` and `rand_member` are very similar, we use `Kernel#rand` with `size` as the exclusive upper boundary, which returns an index we can feed to `get` to return any elements of the set. In the `pop` case we do want to remove the item from the set and we do so with `Array#slice!`. This method takes two argument, the first one is the start index of the range we wish to delete and the second one is the length of the range. `remove` uses `Array#slice!` in a similar way to how `pop` does it: ``` ruby module BYORedis class IntSet # ... def pop rand_index = rand(size) value = get(rand_index) @underlying_array.slice!(rand_index * @encoding, @encoding) value end def random_member rand_index = rand(size) get(rand_index) end def remove(member) index = search(member) if get(index) == member @underlying_array.slice!(index * @encoding, @encoding) true else false end end private # ... end end ``` _listing 9.5 The `pop`, `random_member` and `remove` methods in the `IntSet` class_ And with this the `IntSet` class is now feature complete. ## Adding Set commands ### Creating a Set with `SADD` Let's start the same way we started in the previous in chapters, with the ability to create a new element in the main keyspace. Sets are created with the `SADD` command, which usually adds members to a set, if necessary, and creates a set if the key is not already used by a value of a different type. ``` ruby require_relative './redis_set' module BYORedis class SAddCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) key = @args.shift new_member_count = 0 set = @db.lookup_set_for_write(key) @args.each do |member| added = set.add(member) new_member_count += 1 if added end RESPInteger.new(new_member_count) end def self.describe Describe.new('sadd', -3, [ 'write', 'denyoom', 'fast' ], 1, 1, 1, [ '@write', '@set', '@fast' ]) end end end ``` _listing 9.6 The `SAddCommand` class_ The structure of the `call` method for the `SAddCommand` class is similar to `HSet` in the previous chapter. The first argument is the key for the hash, and the following arguments are the members to add to the set. Once the set is loaded, we iterate over the argument and use the `RedisSet#add` method. In the previous chapter we created the `RedisHash` class, so let's create the `RedisSet` class, with the `add` method: ``` ruby module BYORedis class RedisSet attr_reader :underlying def initialize @underlying = IntSet.new end def add(member) case @underlying when IntSet int_member = convert_to_int_or_nil(member) if int_member added = @underlying.add(int_member) if added && cardinality + 1 > Config.get_config(:set_max_intset_entries) convert_intset_to_dict end added else convert_intset_to_dict @underlying.set(member, nil) end when Dict then @underlying.set(member, nil) else raise "Unknown type for structure: #{ @underlying }" end end private def convert_intset_to_dict dict = Dict.new @underlying.each do |member| dict[Utils.integer_to_string(member)] = nil end @underlying = dict end def convert_to_int_or_nil(member) Utils.string_to_integer(member) rescue InvalidIntegerString nil end end end ``` _listing 9.7 The `RedisSet#add` method_ We are going to use the same `case/when` pattern we introduced in the previous chapter but for `IntSet` and `Dict` instead of `List` and `Dict`. In the `add` method, if `@underlying` is an `IntSet` then we start by checking if the new member is a string that represents an integer by calling the `convert_to_int_or_nil` method. This method uses the `Utils.string_to_integer` method we introduced in the previous chapter. If `member` can be converted to an integer, then we proceed with the `IntSet` instance and call the `IntSet#add` method. If the element was added to the set, that is, if it was not already in the set, then we check the cardinality of the set to see if it exceeded the `set_max_intset_entries` config value. If it did, the set is now too big to be an `IntSet` and we convert it to a `Dict`. Luckily the conversion from `IntSet` to `Dict`, which we perform in the `convert_intset_to_dict` private method, does not require a lot of steps. We create a new `Dict` instance, and then iterate through all the `IntSet` members with the `IntSet#each` method and use the `Dict#set` method through its `[]=` alias to add the members to the `Dict`. We only need the keys, so we set the value to `nil` for each new `DictEntry` we add. If `@underlying` is an `IntSet`, but the new member cannot be represented as an integer, such as the string `'abc'`, then we convert the `IntSet` to a `Dict`, regardless of its current size, and add the new member with `Dict#set`. We don't use the `[]=` alias here because doing so ignores the method's return value, and we want `RedisSet#add` to return the boolean returned by `Dict#set`, indicating whether or not the member was added to the set. Finally, if `@underlying` is a `Dict`, which would be `true` in two cases, the set is either too big to be an `IntSet`, more than 512 members by default, or a member that cannot be converted to an integer was previously added. Regardless, we're now dealing with a `Dict` and we call `Dict#set` to add the member to the set. Back to `SAddCommand`, we now need to add the `lookup_set_for_write` method to the `DB` class: ``` ruby module BYORedis class DB # ... def lookup_set(key) set = @data_store[key] raise WrongTypeError if set && !set.is_a?(RedisSet) set end def lookup_set_for_write(key) set = lookup_set(key) if set.nil? set = RedisSet.new @data_store[key] = set end set end end end ``` _listing 9.8 The `DB#lookup_set_for_write` method_ Now that we introduced a new type, `set`, we need to update the `TypeCommand`: ``` ruby module BYORedis class TypeCommand < BaseCommand def call Utils.assert_args_length(1, @args) key = @args[0] ExpireHelper.check_if_expired(@db, key) value = @db.data_store[key] case value when nil then RESPSimpleString.new('none') when String then RESPSimpleString.new('string') when List then RESPSimpleString.new('list') when RedisHash then RESPSimpleString.new('hash') when RedisSet then RESPSimpleString.new('set') else raise "Unknown type for #{ value }" end end # ... end end ``` _listing 9.9 Adding `set` to the `TypeCommand` class_ In the next section we will add the six commands implementing set operations, namely difference, union and intersection, and their `*STORE` variants. ### Set operations with SDIFF, SINTER, SUNION and their *STORE variants **Set difference** ``` ruby module BYORedis # ... class SDiffCommand < BaseCommand def call Utils.assert_args_length_greater_than(0, @args) sets = @args.map { |other_set| @db.lookup_set(other_set) } RESPArray.new(RedisSet.difference(sets).members) end def self.describe Describe.new('sdiff', -2, [ 'readonly', 'sort_for_script' ], 1, -1, 1, [ '@read', '@set', '@slow' ]) end end end ``` _listing 9.10 The `SDiffCommand` class_ The `SDIFF` command performs the "set difference" operation, starting with the leftmost set, it then iterates through all the other sets and removes their members from the first set, if it contained them, let's look at some examples: ``` bash 127.0.0.1:6379> SADD s1 2 4 6 8 10 12 (integer) 6 127.0.0.1:6379> SADD s2 1 2 3 4 (integer) 4 127.0.0.1:6379> SADD s3 5 6 7 8 9 10 11 12 13 (integer) 9 127.0.0.1:6379> SDIFF s1 1) "2" 2) "4" 3) "6" 4) "8" 5) "10" 6) "12" 127.0.0.1:6379> SDIFF s1 s2 1) "6" 2) "8" 3) "10" 4) "12" 127.0.0.1:6379> SDIFF s1 s2 s3 (empty array) 127.0.0.1:6379> TYPE s4 none 127.0.0.1:6379> SDIFF s1 s4 1) "2" 2) "4" 3) "6" 4) "8" 5) "10" 6) "12" ``` Set difference is also called relative complement in [set theory][wikipedia-set-relative-complement]. The difference of single set always returns the same set, you can compare it to subtracting `0` to any number, the result is always the same number. In the second example, we compute the difference of `s1` and `s2`, in other words we subtract all the elements in `s2` from `s1`, so we remove `1`, `2`, `3`, & `4` from `s1`. We end up with `6`, `8`, `10` & `12`. `2` & `4` were removed and `1` & `3` were ignored since they were not present in `s1`. In the last example, we start with the same operation from the second example, we subtract `s2` from `s1`, and we subtract `s3` from that result. Removing `5`, `6`, `7`, `8`, `9`, `10`, `11`, `12` & `13` from the intermediary set containing `6`, `8`, `10` & `12` yields an empty set. Non existing sets are treated as empty sets, which are ignored in the difference operation, similar to a subtraction by zero. The difference operation is performed on multiple sets, and return a new set, which makes implementing it as an instance method a little bit odd since it operates on multiple sets, as opposed to a single set like most other instance methods. We therefore implement it as a class method on the `RedisSet` class: ``` ruby module BYORedis class RedisSet # ... def self.difference(sets) first_set = sets[0] return RedisSet.new if first_set.nil? # Decide which algorithm to use # # Algorithm 1 is O(N*M) where N is the size of the element first set # and M the total number of sets. # # Algorithm 2 is O(N) where N is the total number of elements in all # the sets. algo_one_work = 0 algo_two_work = 0 sets.each do |other_set| algo_one_work += sets[0].cardinality algo_two_work += other_set ? other_set.cardinality : 0 end # Directly from Redis: # Algorithm 1 has better constant times and performs less operations # if there are elements in common. Give it some advantage: algo_one_work /= 2 diff_algo = (algo_one_work <= algo_two_work) ? 1 : 2 if diff_algo == 1 if sets.length > 1 sets[0..0] + sets[1..-1].sort_by! { |s| -1 * s.cardinality } end difference_algorithm1(sets) else difference_algorithm2(sets) end end end end ``` _listing 9.11 The `RedisSet.difference` class method_ Redis uses two different algorithms to perform the set difference operation, while it not possible to know for sure which one will be more efficient, it tries to guess, depending on the size of the sets, which one will be faster. The first algorithm works by iterating through the first set, and for each element, we look into each other set, as soon we find the element, we stop and move to the next element in the first set. If we make it through all the other sets without finding the element, we add the member to a new set, acting the result set. In other words, the main criteria dictating the "cost" of this algorithm is the size of the first set. The bigger the first set, the more iteration we'll have to perform. The second algorithm works by creating a new set with all the elements from the first set and then iterate through all the elements in all the other sets, removing each member from the new set. The "cost" of this algorithm is the sum of the cardinalities of all the sets, given that each set will be iterated once. Redis gives the first algorithm an edge because it seems like it tends to be faster, what this means in practice is that algorithm 2 will only be picked if the first set is significantly bigger than every other sets, in which case we know that its performance would not be ideal by having to iterate over all the items in the first set no matter what and through all the other sets for each member in the first set, and we have a potential shortcut with algorithm 2. ``` ruby module BYORedis class RedisSet # ... def self.difference_algorithm1(sets) return RedisSet.new if sets.empty? || sets[0].nil? dest_set = RedisSet.new sets[0].each do |element| i = 0 other_sets = sets[1..-1] while i < other_sets.length other_set = other_sets[i] # There's nothing to do when one of the sets does not exist next if other_set.nil? # If the other set contains the element then we know we don't want to add element to # the diff set break if other_set == self break if other_set.member?(element) i += 1 end if i == other_sets.length dest_set.add(element) end end dest_set end private_class_method :difference_algorithm1 def self.difference_algorithm2(sets) return self if sets.empty? || sets[0].nil? dest_set = RedisSet.new # Add all the elements from the first set to the new one sets[0].each do |element| dest_set.add(element) end # Iterate over all the other sets and remove them from the first one sets[1..-1].each do |set| set.each do |member| dest_set.remove(member) end end dest_set end private_class_method :difference_algorithm2 def include?(member) return false if member.nil? case @underlying when IntSet then if member.is_a?(Integer) member_as_int = member else member_as_int = Utils.string_to_integer_or_nil(member) end if member_as_int @underlying.member?(member_as_int) else false end when Dict then @underlying.member?(member) else raise "Unknown type for structure #{ @underlying }" end end alias member? include? # ... end end ``` _listing 9.12 The `difference_algorithm1` & `difference_algorithm2` class methods in `RedisSet`_ Each of these two methods does not need to be exposed and we make them private with `private_class_method`. The `difference_algorithm1` method implements the first algorithm described above where the first set is iterated over, and all the other sets are iterated over as long as the current member of the first set is not found. We need to add the `include?` method, aliased to `member?` to check for the presence of a member in a set. The `IntSet` case of `include?` needs to account for the fact that the argument might already be an `Integer` or might be a `String` representing an `Integer`. We add the `Utils.string_to_integer_or_nil` method to help for this: ``` ruby module BYORedis module Utils # ... def self.string_to_integer_or_nil(string) begin string_to_integer(string) rescue InvalidIntegerString nil end end # ... end end ``` _listing 9.13 The `string_to_integer_or_nil` method in the `Utils` module_ In the `Dict` case of `RedisSet#include?` we delegate to the `Dict#include?` method, through its `member?` alias, which implements the exact interface we need, so let's add the alias: ``` ruby module BYORedis class Dict # ... def include?(key) !get_entry(key).nil? end alias member? include? # ... end end ``` _listing 9.14 Adding the `Dict#member?` aliased to `Dict#include?`_ The second algorithm intends to provide an alternative in case the first set is significantly larger than the other sets. The next command, `SDIFFSTORE` is similar to `SDIFF`, with the difference being that the result is stored in the given key, and the return value is the cardinality of that set. We have two other very similar methods coming next with `SINTERSTORE` & `SUNIONSTORE` so we're using a helper method with the shared logic: ``` ruby module BYORedis module SetUtils # ... def self.generic_set_store_operation(db, args) Utils.assert_args_length_greater_than(1, args) destination_key = args.shift sets = args.map { |other_set| db.lookup_set(other_set) } new_set = yield sets if new_set.empty? db.data_store.delete(destination_key) else db.data_store[destination_key] = new_set end RESPInteger.new(new_set.cardinality) end end # ... class SDiffStoreCommand < BaseCommand def call SetUtils.generic_set_store_operation(@db, @args) do |sets| RedisSet.difference(sets) end end def self.describe Describe.new('sdiffstore', -3, [ 'write', 'denyoom' ], 1, -1, 1, [ '@write', '@set', '@slow' ]) end end end ``` _listing 9.15 The `SDiffStoreCommand` class_ The `SDiffStoreCommand` class is extremely similar to `SDiffCommand`, with the exception that it needs to handle an extra argument at the beginning of the argument list, for the destination key. It then stores the result set at that key, or delete what was there before if the result set is empty. Finally, it returns the cardinality of the result set. **Set Union** The next set operation we will implement is [set union][wikipedia-set-union], which is defined as: > The union of two sets A and B is the set of elements which are in A, in B, or in both A and B Let's start by creating the `SUnionCommand` class: ``` ruby module BYORedis # ... class SUnionCommand < BaseCommand def call Utils.assert_args_length_greater_than(0, @args) sets = @args.map { |set_key| @db.lookup_set(set_key) }.compact RESPArray.new(RedisSet.union(sets).members) end def self.describe Describe.new('sunion', -2, [ 'readonly', 'sort_for_script' ], 1, -1, 1, [ '@read', '@set', '@slow' ]) end end end ``` _listing 9.16 The `SUnionCommand` class_ We are implementing the `union` method as a class method on `RedisSet` for the same reasons we decided to implement `difference` as a class method. ``` ruby module BYORedis class RedisSet # ... def self.union(sets) if sets.empty? RedisSet.new else union_set = RedisSet.new sets.each do |set| set.each { |member| union_set.add(member) } end union_set end end # ... end end ``` The set union operation is simpler, we iterate over all sets, over all of their members and add each member to a new set, once we're done, we return the set. Similarly to how we first added the `SDIFF` command followed by the `SDIFFSTORE` command, we're now adding the `SUnionStoreCommand` class. ``` ruby module BYORedis # ... class SUnionStoreCommand < BaseCommand def call SetUtils.generic_set_store_operation(@db, @args) do |sets| RedisSet.union(sets) end end def self.describe Describe.new('sunionstore', -3, [ 'write', 'denyoom' ], 1, -1, 1, [ '@write', '@set', '@slow' ]) end end end ``` _listing 9.17 The `SUnionStoreCommand` class_ **Set Intersection** The final set operation we're going to implement is [set intersection][wikipedia-set-intersection], with the `SINTER` command. Set intersection is defined as: > In mathematics, the intersection of two sets A and B, denoted by A ∩ B, is the set containing all elements of A that also belong to B (or equivalently, all elements of B that also belong to A). ``` ruby module BYORedis module SetUtils def self.generic_sinter(db, args) sets = args.map do |set_key| set = db.lookup_set(set_key) return RedisSet.new if set.nil? set end RedisSet.intersection(sets) end end # ... class SInterCommand < BaseCommand def call Utils.assert_args_length_greater_than(0, @args) intersection = SetUtils.generic_sinter(@db, @args) RESPArray.new(intersection.members) end def self.describe Describe.new('sinter', -2, [ 'readonly', 'sort_for_script' ], 1, -1, 1, [ '@read', '@set', '@slow' ]) end end end ``` _listing 9.18 The `SInterCommand` class_ The logic in `SInterCommand` shares a lot of logic with `SInterStoreCommand`, which we'll create next, so we go ahead and create a method with the shared logic `BYORedis::SetUtils.generic_sinter`. In order to implement this method, we need the `intersection` class method on the `RedisSet` class, but before calling this method, we do return early if any of the given keys does not exist. This is an important shortcut, when computing the intersection of sets, if any of the sets is empty, we know that the final result will be an empty sets, and non existing sets are treated as empty sets. ``` ruby module BYORedis class RedisSet # ... def self.intersection(sets) # Sort the sets smallest to largest sets.sort_by!(&:cardinality) intersection_set = RedisSet.new # Iterate over the first set, if we find a set that does not contain it, discard sets[0].each do |member| present_in_all_other_sets = true sets[1..-1].each do |set| unless set.member?(member) present_in_all_other_sets = false break end end # Otherwise, keep intersection_set.add(member) if present_in_all_other_sets end intersection_set end # ... end end ``` _listing 9.19 The `RedisSet.intersection` class method_ Set intersection is not as straightforward as set union but is not at complicated as set difference. We start by sorting all the sets from smallest to largest. Doing the sorting is a small optimization because we have to iterate over all the elements of at least one set, so we might as well pick the smaller one for that. Once the sets are sorted, we pick the first one, the smallest one, and iterate over all its members, for each member we check its presence in all other sets, as soon as this check is false, we continue to the next member. This is because the result set of the intersection only contains elements present in all the sets. If we make it through all the sets, then the member is indeed present in all sets and we add it to the result set. The last set operation command on our list is `SINTERSTORE`, we've seen this pattern two times already by now. We use the `SetUtils.generic_set_store_operation` method the same way we did previously: ``` ruby module BYORedis # ... class SInterStoreCommand < BaseCommand def call SetUtils.generic_set_store_operation(@db, @args) do SetUtils.generic_sinter(@db, @args) end end def self.describe Describe.new('sinterstore', -3, [ 'write', 'denyoom' ], 1, -1, 1, [ '@write', '@set', '@slow' ]) end end end ``` _listing 9.20 The `SInterStoreCommand` class_ With `SInterStoreCommand` completed, we've now implemented all the set operation commands, `SUNION`, `SINTER` & `SDIFF`, and their `*STORE` variants. ### Membership related operations **SMEMBERS** The `SMEMBERS` command returns all the members of a set. Sets do not guarantee ordering, so we can just return members without having to worry about ordering. Let's create the `SMembersCommand`: ``` ruby module BYORedis # ... class SMembersCommand < BaseCommand def call Utils.assert_args_length(1, @args) set = @db.lookup_set(@args[0]) RESPArray.new(set.members) end def self.describe Describe.new('smembers', 2, [ 'readonly', 'sort_for_script' ], 1, 1, 1, [ '@read', '@set', '@slow' ]) end end end ``` _listing 9.21 The `SMembersCommand` class_ We need to add the `RedisSet#members` command: ``` ruby module BYORedis class RedisSet # ... def members case @underlying when IntSet then @underlying.members.map { |i| Utils.integer_to_string(i) } when Dict then @underlying.keys else raise "Unknown type for structure #{ @underlying }" end end # ... end end ``` _listing 9.22 The `RedisSet#members` method_ In the `IntSet` case we call the `IntSet#members` methods, and convert all in `Integer` instances to `String` with the `Utils.integer_to_string` method. In the `Dict` case we can directly return from the already existing `Dict#keys` method. The conversion to strings in the `IntSet` case is to follow the behavior of the Redis command, as the following example shows, even if the set is an `intset`, Redis converts the value to RESP strings before returning them: ``` bash 127.0.0.1:6379> SADD s 1 2 3 (integer) 3 127.0.0.1:6379> DEBUG OBJECT s Value at:0x7f88e7004130 refcount:1 encoding:intset serializedlength:15 lru:11187844 lru_seconds_idle:3 127.0.0.1:6379> SMEMBERS s 1) "1" 2) "2" 3) "3" ``` The quotes around the numbers show us that the array members are indeed strings, and `redis-cli` would prefix them with `(integer)` otherwise, but we can use `nc` to confirm the type of the elements of the array: ``` bash > echo "SMEMBERS s" | nc -c localhost 6379 *3 $1 1 $1 2 $1 3 ``` **SISMEMBER** `SISMEMBER` returns an integer acting as a boolean, `1` for `true` and `0` for `false`, depending on the presence of the given member in the set: ``` ruby module BYORedis # ... class SIsMemberCommand < BaseCommand def call Utils.assert_args_length(2, @args) set = @db.lookup_set(@args[0]) if set presence = set.member?(@args[1]) ? 1 : 0 RESPInteger.new(presence) else RESPInteger.new(0) end end def self.describe Describe.new('sismember', 3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@set', '@fast' ]) end end end ``` _listing 9.23 The `SIsMemberCommand` class_ We delegate the actual work of checking if the set contains the given member to the `RedisSet#member?` method which we added earlier when adding the `SDIFF` command. **SMISMEMBER** _(New in 6.2.0)_ ``` ruby module BYORedis # ... class SMIsMemberCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) set = @db.lookup_set(@args.shift) members = @args if set.nil? result = Array.new(members.size, 0) else result = members.map do |member| set.member?(member) ? 1 : 0 end end RESPArray.new(result) end def self.describe Describe.new('smismember', -3, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@set', '@fast' ]) end end end ``` _listing 9.24 The `SMIsMemberCommand` class_ This command uses the same method from `RediSet` we used in `SIsMemberCommand`, but inside the `map` method, which we use to return an array of integers acting as booleans, `1` if the member is in the set, `0` if it isn't. **SCARD** ``` ruby module BYORedis # ... class SCardCommand < BaseCommand def call Utils.assert_args_length(1, @args) set = @db.lookup_set(@args[0]) cardinality = set.nil? ? 0 : set.cardinality RESPInteger.new(cardinality) end def self.describe Describe.new('scard', 2, [ 'readonly', 'fast' ], 1, 1, 1, [ '@read', '@set', '@fast' ]) end end end ``` _listing 9.25 The `SCardCommand` class_ The command delegates to the `RedisSet#cardinality` method: ``` ruby module BYORedis class RedisSet # ... def cardinality case @underlying when IntSet then @underlying.cardinality when Dict then @underlying.used else raise "Unknown type for structure #{ @underlying }" end end # ... end end ``` _listing 9.26 The `RedisSet#cardinality` method_ Both `IntSet` and `Dict` already have methods that return what we need here, so we call them and return their results directly. **SRANDMEMBER** ``` ruby module BYORedis # ... class SRandMemberCommand < BaseCommand def call Utils.assert_args_length_greater_than(0, @args) raise RESPSyntaxError if @args.length > 2 count = Utils.validate_integer(@args[1]) if @args[1] set = @db.lookup_set(@args[0]) if set if count.nil? random_members = set.random_member else random_members = set.random_members_with_count(count) end RESPSerializer.serialize(random_members) elsif count.nil? NullBulkStringInstance else EmptyArrayInstance end end def self.describe Describe.new('srandmember', -2, [ 'readonly', 'random' ], 1, 1, 1, [ '@read', '@set', '@slow' ]) end end end ``` _listing 9.27 The `SRandMemberCommand` class_ In this command we extract the `count` option, if present, and decide which method to call on `RediSet` depending on whether or not it was passed. We perform this check here because the logic behind getting a single random element, which is what `RediSet#random_member` does, is significantly simpler than getting multiple random elements, which is what `RedisSet#random_members_with_count` does. On top of that, the return type of the command is different, it is either `nil` or a single element in the first case and is an array, empty or not, otherwise We could check for the type of the `random_members` variable in the `call` method, and call `RESPBulkString.new` on it, or `RESPArray.new`, depending on its type. There is a slightly better approach, as in, easier to reuse in different places, which is what the `JSON.generate` method from the standard library does: ``` ruby irb(main):005:0> JSON.generate(1) => "1" irb(main):006:0> JSON.generate({a: 1, b: 2}) => "{\"a\":1,\"b\":2}" irb(main):007:0> JSON.generate([1,2,3]) => "[1,2,3]" irb(main):008:0> JSON.generate('a') => "\"a\"" ``` With `generate`, you can pass anything that can be serialized, and it'll return the serialized value for you. And while, yes, Ruby also provides `to_json` methods of most types, and it returns the same result: ``` ruby irb(main):010:0> {a: 1, b: 2}.to_json => "{\"a\":1,\"b\":2}" ``` I personally prefer the first approach as it avoids crowding objects with many methods, and instead separate functionalities across different classes/objects. Both options work, I happen to prefer the first one, so let's mimic it with `RESPSerializer`: ``` ruby module BYORedis # ... class RESPSerializer def self.serialize(object) case object when Array then RESPArray.new(object) when RedisSet then RESPArray.new(object.members) when List then ListSerializer.new(object) when Integer then RESPInteger.new(object) when String then RESPBulkString.new(object) when Dict pairs = [] object.each { |k, v| pairs.push(k, v) } RESPArray.new(pairs) when nil then NullBulkStringInstance else raise "Unknown object for RESP serialization #{ object }" end end end end ``` With this class we can now call `RESPSerializer.new(object)` with any objects that can be serialized to RESP, without having to know its exact type. If we happen to know the type of the object we're dealing, we might as well call its specific RESP serializer, which is what we'll keep doing through the rest of the book. Getting a random element from an `IntSet` does not require as many steps as it does for a `Dict`. Given that the structure behind an `IntSet` is an array, we can pick a random index, between `0` and `size - 1`, and return the element at that index. As long as the random function we use is "random enough", the element returned will be random. We're using quotes here because the topic of randomness if fairly complicated, luckily Ruby does a lot of the heavy lifting for us, with the `Kernel.rand` method and the `SecureRandom` module. The difference between the two different approaches is a little bit out of scope for now, and we'll be using `Kernel.rand` since it is sufficient for our needs. On the other hand, getting a random entry for a set using a `Dict` is way more complicated. It might seem similar at first glance, the data structure powering a hash table is also an array, but some buckets might be empty, so we cannot "just" pick a random index and return the value stored there, given that it could be empty. This problem is not insurmountable, we can add some form of retry logic, until a non empty bucket is found. We also need to take into account that the `Dict` might be in the middle of the rehashing process, in which case the buckets will be split across two different hash tables. Finally, even if we dealt with these issues, there is still a major issue, buckets contain zero or more entries, and given the nature of the SipHash algorithm, there is no way to expect the distribution of entries across buckets. In practical terms, this means for a hash of size 8, containing 6 entries, it is entirely possible that five buckets are empty, two contain one element each and that the last bucket contain the other four elements. This means that even after finding a non empty bucket, we now need to select a random entry within that bucket if it contains more than one. Doing so works in the sense of being able to potentially return any of the values contained in the hash, but it completely obliterates the distribution of the result. Ideally, as we call `SRANDMEMBER` multiple times, the distribution of the returned element should trend towards the perfect proportion. Using the example from above, if a set contains six elements, each element should have a probability of `1/6` to be returned, but the approach described above might be completely off, let's look at an example. Note that these examples assume that the `Kernel.rand` has a perfect distribution, which is not the case, computers cannot be perfectly random, but it is pretty close as the following example shows: ``` ruby distribution = Hash.new { |h, k| h[k] = 0 } times = 100_000 times.times do distribution[rand(1..6)] += 1 end p Hash[distribution.map { |k, v| [k, v / times.to_f] }] ``` The previous script returned the following on my machine, the result should be different but pretty close on another machine, or as you run it multiple times: ``` ruby {1=>0.17011, 2=>0.16645, 6=>0.16604, 5=>0.16696, 4=>0.1657, 3=>0.16474} ``` The perfect distribution would be `0.166666667`, so it's not _that_ far. For example, running the same example with `times = 1_000_000` instead returned closer results as expected, the more we run it, the more the results will get closer to the perfect distribution: ``` ruby {3=>0.166954, 4=>0.16658, 5=>0.16693, 2=>0.166722, 1=>0.166075, 6=>0.166739} ``` Back to the distribution problem in a hash table, the previous example we mentioned looked like the following, five empty buckets, two with one member each and one with four. ``` s = { nil, nil, nil, nil, nil, < 1 >, < 2 >, < 3, 4, 5, 6 > } ``` Each of the bucket has about `1/6` chance of getting picked, but we'll retry as long we pick an empty bucket, so given that there are three non-empty buckets, each of these has about 1/3 change of getting picket. The problem is if the last one get picked, then we need to roll the die one more time, and this time each item will have about 1/4 chance of getting picked, bringing the probabilities of each elements to the following: ``` 1 => 1/3 ~= 0.333333333 2 => 1/3 ~= 0.333333333 3 => 1/3 * 1/4 = 1/24 ~= 0.083333333 4 => 1/3 * 1/4 = 1/24 ~= 0.083333333 5 => 1/3 * 1/4 = 1/24 ~= 0.083333333 6 => 1/3 * 1/4 = 1/24 ~= 0.083333333 ``` To attempt addressing this problem Redis uses two functions, `dictGetSomeKeys` and `dictGetFairRandomKey`. It also uses a third function, `dictGetRandomKey`, which implements the logic we described previously, only as a backup, in case `dictGetSomeKeys` fails to return any keys. This approach alleviates some of the issues we described earlier by first randomly selecting keys through the dictionary, putting them in a flat array, and only then picking one random index in this array. Let's add these methods to our `Dict` class ``` ruby module BYORedis class Dict # ... GETFAIR_NUM_ENTRIES = 15 def fair_random_entry entries = get_some_entries(GETFAIR_NUM_ENTRIES) if entries.empty? random_entry else entries[rand(0...entries.size)] end end private def get_some_entries(count) entries = [] stored = 0 count = used if count > used maxsteps = count * 10 count.times { rehash_step } if rehashing? tables = rehashing? ? 2 : 1 maxsizemask = main_table.sizemask if tables > 1 && rehashing_table.sizemask > maxsizemask maxsizemask = rehashing_table.sizemask end i = rand(0..maxsizemask) empty_len = 0 while stored < count && maxsteps iterate_through_hash_tables_unless_rehashing do |hash_table| # If we're in the process of rehashing, up to the indexes already visited in the main # table during the rehashing, there are no populated buckets so we can skip in the # main table, all the indexes between 0 and @rehashidx - 1 if rehashing? && hash_table == main_table && i < @rehashidx if i >= rehashing_table.size i = @rehashidx else next end end next if i >= hash_table.size # Out of range for this table hash_entry = hash_table.table[i] # Count contiguous empty bucket and jump to other locations if they reach 'count' # with a minimum of 5 if hash_entry.nil? empty_len += 1 if empty_len >= 5 && empty_len > count i = rand(0..maxsizemask) empty_len = 0 end else empty_len = 0 while hash_entry entries << hash_entry hash_entry = hash_entry.next stored += 1 return entries if stored == count end end end i = (i + 1) & maxsizemask # increment and wraparound if needed maxsteps -= 1 end entries end def random_entry return if used == 0 rehash_step if rehashing? hash_entry = nil if rehashing? # There are no elements indexes from 0 to rehashidx-1 so we know the only places we can # find an element are in main_table[rehashidx..-1] and anywhere in the rehashing table # We generate the random_index between the total number of slots (the two sizes), minus # the rehashing index. An example, we're growing from 8 to 16 buckets, that's 24 total # slots, now let's imagine that @rehashidx is 4, we generate an index between 0 and 20 # (excluded), and we add 4 to it, that means that we _never_ have a value under 4. # If the random index is 8 or more, we need to look in the rehashing table, but we need # adjust it by removing 8, the size of the main table to it, so say it was initially 19, # plus four, that' 23, minus 8, that's 15, the last bucket in the rehashing table. # If the random index is between 4 and 7, then we look directly in the main table while hash_entry.nil? max = slots - @rehashidx random_index = @rehashidx + SecureRandom.rand(max) hash_entry = if random_index >= main_table.size rehashing_table.table[random_index - main_table.size] else main_table.table[random_index] end end else while hash_entry.nil? random_index = SecureRandom.rand(main_table.size) hash_entry = main_table.table[random_index] end end # Now that we found a non empty bucket, we need to pick a random element from it, but if # there's only one item, we can save some time and return right away return hash_entry if hash_entry.next.nil? list_length = 0 original_hash_entry = hash_entry while hash_entry list_length += 1 hash_entry = hash_entry.next end random_list_index = SecureRandom.rand(list_length) hash_entry = original_hash_entry random_list_index.times do hash_entry = hash_entry.next end hash_entry end end end ``` _listing 9.28 The new random methods in the `Dict` class_ The three methods we just added to the `Dict` class implement this better approach to retrieving a random key/value pair. `fair_random_entry` is the only public one and attempts to use the result from `get_some_entries`, but due to the nature of the hash table, it is possible that `get_some_keys` fails to return any keys, in which case we fall back to `random_entry`, which suffers from the distribution above outlined above, but still returns _a_ random element, just not _that_ random. Now that `Dict` is updated, we can implement `random_member` and `random_members_with_count` in the `RedisSet` class: ``` ruby module BYORedis class RedisSet # How many times bigger should be the set compared to the requested size # for us to don't use the "remove elements" strategy? Read later in the # implementation for more info. # See: https://github.com/antirez/redis/blob/6.0.0/src/t_set.c#L609-L612 SRANDMEMBER_SUB_STRATEGY_MUL = 3 # ... def random_members_with_count(count) return [] if count.nil? || count == 0 # Case 1: Count is negative, we return that many elements, ignoring duplicates if count < 0 members = [] (-count).times do members << random_member end return members end # Case 2: Count is positive and greater than the size, we return the whole thing return self if count >= cardinality # For both case 3 & 4 we need a new set new_set_content = Dict.new # Case 3: Number of elements in the set is too small to grab n random distinct members # from it so we instead pick random elements to remove from it # Start by creating a new set identical to self and then remove elements from it if count * SRANDMEMBER_SUB_STRATEGY_MUL > cardinality size = cardinality each { |member| new_set_content.add(member, nil) } while size > count random_entry = new_set_content.fair_random_entry new_set_content.delete(random_entry.key) size -= 1 end return new_set_content.keys end # Case 4: The number of elements in the set is big enough in comparison to count so we # do the "classic" approach of picking count distinct elements added = 0 while added < count member = random_member added += 1 if new_set_content.add(member, nil) end new_set_content.keys end def random_member case @underlying when IntSet then Utils.integer_to_string(@underlying.random_member) when Dict then @underlying.fair_random_entry.key else raise "Unknown type for structure #{ @underlying }" end end # ... end end ``` _listing 9.29 The `random_member` and `random_member_with_count` methods in the `RedisSet` class_ The `random_members_with_count` method breaks down the possible scenarios in four different possibilities. "Case 1" is for a negative `count` value, in which case duplicates are allowed, so we can iterate as many times as needed and select a random member at each step, without having to worry about anything else. "Case 2" is if `count` is greater than the size of the set, in which case we don't actually need to select any random members and we can return the whole set. We differentiate between "Case 3" and "Case 4" depending on how close `count` is to the size of the set. The idea being that because we can't return duplicates, it might take a while to pick `n` random members if `n` is really close to the size of the set. Let's look at an example with a set of size `10`, the numbers `1` to `10`. If we call `SRANDMEMBER set 9`, we want to return nine random members, but doing so would require many tries. Each of the member has a `1/10` change of getting picked, so the first pick will get a random member, but on the second try we have a `1/10` chance of picking the same element, in which case we'd need to try again. As we fill up the result dict, the odds of picking only one of the few non selected members will be really small. This case if avoided with the `if count * SRANDMEMBER_SUB_STRATEGY_MUL > cardinality` condition. The constant is set to `15`, so with a `count` value of `10` and a set containing `15` elements, the condition will be true, `10 * 15 > 15`. The condition would only be `false` with a large enough set and a small enough `count` value, such as `100` and `2`, `2 * 15 > 100 == false`. So, in "Case 3", we instead create a new dict with all the elements from the set, and remove random members until its size reaches `count`. "Case 4" is the most straightforward approach, we keep looping and picking random members, until we've picked `count` unique members. ### Removing elements **SPOP** ``` ruby module BYORedis # ... class SPopCommand < BaseCommand def call Utils.assert_args_length_greater_than(0, @args) raise RESPSyntaxError if @args.length > 2 if @args[1] count = Utils.validate_integer(@args[1]) return RESPError.new('ERR index out of range') if count < 0 end key = @args[0] set = @db.lookup_set(key) if set popped_members = @db.generic_pop(key, set) do if count.nil? set.pop else set.pop_with_count(count) end end RESPSerializer.serialize(popped_members) elsif count.nil? NullBulkStringInstance else EmptyArrayInstance end end def self.describe Describe.new('spop', -2, [ 'write', 'random', 'fast' ], 1, 1, 1, [ '@write', '@set', '@fast' ]) end end end ``` _listing 9.30 The `SPopCommand` class_ Similarly to `SRANDMEMBER`, `SPOP` accepts a `count` argument, describing how many items can be returned, contrary to `SRANDMEMBER`, `SPOP` does not accept negative `count` values, and a value of `0` is effectively a no-op, no members are popped. We renamed the `DB#generic_pop_wrapper` that used to only work with `List` instances to `generic_pop` and we use it with `RedisSet` instances now. We now need to add `RedisSet#pop` and `RedisSet#pop_with_count`: ``` ruby module BYORedis class RedisSet # ... # How many times bigger should be the set compared to the remaining size # for us to use the "create new set" strategy? Read later in the # implementation for more info. # See: https://github.com/antirez/redis/blob/6.0.0/src/t_set.c#L413-416 SPOP_MOVE_STRATEGY_MUL = 5 # ... def pop case @underlying when IntSet then @underlying.pop.to_s when Dict then random_entry = @underlying.fair_random_entry @underlying.delete(random_entry.key) random_entry.key else raise "Unknown type for structure #{ @underlying }" end end def pop_with_count(count) return [] if count.nil? || count == 0 # Case 1: count is greater or equal to the size of the set, we return the whole thing if count >= cardinality all_members = members clear return all_members end remaining = cardinality - count if remaining * SPOP_MOVE_STRATEGY_MUL > count # Case 2: Count is small compared to the size of the set, we "just" pop random elements count.times.map { pop } else # Case 3: count is big and close to the size of the set, and remaining is small, we do # the reverse, we pick remaining elements, and they become the new set new_set = RedisSet.new remaining.times { new_set.add(pop) } # We have removed all the elements that will be left in the set, so before swapping # them, we store all the elements left in the set, which are the ones that will end up # popped result = members # Now that we have saved all the members left, we clear the content of the set and copy # all the items from new_set, which are the ones left clear new_set.each { |member| add(member) } result end end # ... end end ``` _listing 9.31 The `pop` & `pop_with_count` methods in `RedisSet`_ `pop` is straightforward in the `IntSet` case given that we already implemented the `IntSet#pop` method, we can call it and directly return from it. On the other hand, the `Dict` case is trickier and we now use the newly created `Dict#fair_random_entry` method, to find which entry to delete from the set. `pop_with_count` is optimized to handle a few different edge cases elegantly. We label "Case 1" the case where the `count` value is greater than or equal to the cardinality of the set, and can return all the members, and clear the set. In the case where count is anywhere between `1` and `cardinality - 1`, we do need to find random elements to remove from the set and return them. While it may seem like a simple problem at first, just iterate `count` times and pop a random element at each iteration, the reality is a little bit more complicated. The problem is that the process of popping random element can get expensive if the `count` number is very large, so instead we use an arbitrary threshold and if count is big enough that it is too close to the cardinality of the set, we reverse the process. We only pop the number of elements that should be left in the set, set them aside, extract all the remaining elements from the set, return them and add back the small set of remaining elements in the set. Looking at a set of 10 elements as an example, if `count` is `9`, then `remaining * SPOP_MOVE_STRATEGY_MUL` is `5`, which is not greater than `9`, so we fall in "Case 3". In the case where `count` is `8`, then `2 * 5 = 10`, which is greater than count, so we pop eight times from the set, that's "Case 2". **SREM** ``` ruby module BYORedis # ... class SRemCommand < BaseCommand def call Utils.assert_args_length_greater_than(1, @args) set = @db.lookup_set(@args.shift) remove_count = 0 if set @args.each do |member| remove_count += 1 if @db.remove_from_set(key, set, member) end end RESPInteger.new(remove_count) end def self.describe Describe.new('srem', -3, [ 'write', 'fast' ], 1, 1, 1, [ '@write', '@set', '@fast' ]) end end end ``` _listing 9.32 The `SRemCommand` class_ `SREM` relies on `DB#remove_from_set`, let's add it: ``` ruby module BYORedis class DB # ... def remove_from_set(key, set, member) removed = set.remove(member) @data_store.delete(key) if set.empty? removed end # ... end end ``` Let's now add `RedisSet#remove` to complete the `SREM` implementation: ``` ruby module BYORedis class RedisSet # ... def remove(member) case @underlying when IntSet member_as_integer = Utils.string_to_integer_or_nil(member) if member_as_integer @underlying.remove(member_as_integer) else false end when Dict then !@underlying.delete_entry(member).nil? else raise "Unknown type for structure #{ @underlying }" end end # ... end end ``` _listing 9.33 The `RedisSet#remove` method_ Up until now the `Dict#remove` method used to return the value of the deleted pair, or `nil` if the dict did not contain the given key. The problem with this approach is that if the value stored in the `Dict` was `nil`, the caller would not be able to differentiate the successful deletion of a pair, or a "miss" if the dictionary did not contain the key. Similarly to how we initially implemented the `get` method by using the lower level method `get_entry`, we are adding the `delete_entry` method, which returns the full `DictEntry` instance for a successful deletion. With this change, callers can now know that a `nil` value is indeed a miss whereas a `DictEntry` instance, regardless of what the value of the `value` field is, is a successful deletion. ``` ruby module BYORedis class Dict # ... def delete_entry(key) return if main_table.used == 0 && rehashing_table.used == 0 rehash_step if rehashing? hash_key = SipHash.digest(RANDOM_BYTES, key) iterate_through_hash_tables_unless_rehashing do |hash_table| index = hash_key & hash_table.sizemask entry = hash_table.table[index] previous_entry = nil while entry if entry.key == key if previous_entry previous_entry.next = entry.next else hash_table.table[index] = entry.next end hash_table.used -= 1 return entry end previous_entry = entry entry = entry.next end end nil end def delete(key) delete_entry(key)&.value end # ... end end ``` _listing 9.34 The `delete` & `delete_entry` methods in the `Dict` class_ The `delete` method is now written in terms of `delete_entry`. The `&.` operator allows us to concisely return `nil` from `delete` if `delete_entry` returned `nil` itself, in the case where the `Dict` does not contain `key`. If the `value` field of the `DictEntry` is `nil`, then callers of `delete` have no way of differentiating a miss, when the `Dict` does not contain `key`, and a successful deletion. If this is important to the callers, which in the case in `SRemCommand`, then callers can use `delete_entry` instead. **SMOVE** `SMOVE` is used to remove a member from a set and add it to another ``` ruby module BYORedis # ... class SMoveCommand < BaseCommand def call Utils.assert_args_length(3, @args) source_key = @args[0] source = @db.lookup_set(source_key) member = @args[2] destination = @db.lookup_set_for_write(@args[1]) if source.nil? result = 0 else removed = @db.remove_from_set(source_key, source, member) if removed destination.add(member) result = 1 else result = 0 end end RESPInteger.new(result) end def self.describe Describe.new('smove', 4, [ 'write', 'fast' ], 1, 2, 1, [ '@write', '@set', '@fast' ]) end end end ``` _listing 9.35 The `SMoveCommand` class_ If the `source` set does not exist, there is nothing to do since we have no set to remove `member` from. If it does exist, then we call `DB#remove_from_set`, which we added earlier for the `SREM` command, if it returns `true` then we add the `member` in `destination`. Note that we return `1` as long as `member` was found in `source`, even if it was already in `destination`. This wraps up the last set command! ## Conclusion You can find the code [on GitHub][github-code]. With set commands implemented, we now have one last native data type left, sorted sets, and this is what [Chapter 10][chapter-10] will cover. ## Appendix A: A more idiomatic `IntSet` The `IntSet` class we created earlier in the Chapter was trying to replicate as much as possible the logic used in `intset.c` in Redis, at the cost of not being really idiomatic Ruby. If we were to set aside the encoding, and use the Ruby `Integer` class as provided, we can end up with a simpler implementation: ``` ruby module BYORedis class IntSet def initialize @underlying_array = [] end def add(member) raise "Member is not an int: #{ member }" unless member.is_a?(Integer) index = @underlying_array.bsearch_index { |x| x >= member } if index.nil? @underlying_array.append(member) true elsif @underlying_array[index] == member false else @underlying_array.insert(index, member) true end end # ... end end ``` _listing 9.36 The `initialize` & `add` methods in the `IntSet` class_ The first thing we do in `add` is check that the argument is indeed an `Integer`, and abort if it isn't. It is up to callers of these methods to do the due diligence of calling this method with the correct argument type. The next step is to find where in the array should the new element be added, and we use the [`bsearch_index`][ruby-doc-bsearch-index] method for that. By giving the block `{ |x| x >= member }` block to the method, it will return the smallest index of an element that is greater than or equal to `member`. If no elements are greater than or equal to `member`, then it returns `nil`. Based on these cases, there are three cases we need to consider, the first one, if `index` is `nil`, means that no elements in the array are greater than or equal to `member`, in other words, `member` is now the member with the largest value, and we should add it at the end of the array. This is what we do with the `Array#append` method. Next is the case where `index` is not `nil`, and in this case there are two options, the value at `index` is either equal to `member`, or greater than `member`. If the value is equal to `member`, it means that there is already an `Integer` in the array with the same value as `member`, and it means that we have nothing to do, the member is already present. The last case is if the value at `index` is greater than `member`. `bsearch_index` guarantees that if returned the smallest index of all the values greater than `member`, so we need to add `member` right before this element, and this is what [`Array#insert`][ruby-doc-insert] does, it inserts the given value before the element with the given index. The next main method is the ability to check for the presence of a member in the set, this is what the `include?` method does: ``` ruby def include?(member) return false if member.nil? !@underlying_array.bsearch { |x| member <=> x }.nil? end alias member? include? ``` _listing 9.37 The `IntSet#include?` method_ We're following Ruby's `Set` class naming convention here, naming the method `include?`, also accessible through the `member?` alias. We'll use the `member?` method throughout this chapter to use the same language used by the Redis commands such as `SISMEMBER`. The `include?` methods relies almost exclusively on the [`bsearch`][ruby-doc-bsearch] method, which we've indirectly explored previously through its close sibling [`bsearch_index`][ruby-doc-bsearch-index]. Both methods use a similar API, the difference being that `bsearch` returns an element from the array whereas `bsearch_index` returns the index of an element. Both could have been used here given that the returned value itself is not that important, we already really care whether or not the result is `nil`. These `bsearch` methods have two modes of operation, which can be a bit confusing these the mode is decided implicitly depending on the return value of the block passed to the method. The two modes are `find-minimum` & `find-any`. We've only used the `find-minimum` mode so far, by passing the block `{ |x| member <=> x }` to the method, we end up using the `find-any` mode, because the `Integer#<=>` method returns an integer, `-1`, `0` or `1`. The Ruby documentation of the method is surprisingly not clear at describing the behavior of this mode, on the other hand the man page of `bsearch(3)`, accessible with `man 3 bsearch`, which is what the `find-any` mode is based after is a little bit more helpful: > The contents of the array should be in ascending sorted order according to the comparison function referenced by compar. > > The compar routine is expected to have two arguments which point to the key object and to an array member, in that order. It should return an integer which is less than, equal to, or greater than zero if the key object is found, respectively, to be less than, to match, or be greater than the array member. We need to "translate" this description given that it describes the `C` function, not the Ruby one, but the `compar` function is essentially very similar to the block argument, and the `key` object is the argument to the method, `member` in the `include?` method. With that said, what the documentation tells us is that the block should return `0` if both values are equal, a negative value if `member` is less than `x`, and a positive value if `member` is greater than `x`. The `<=>`, often called "spaceship operator", does exactly that! Using this block, `bsearch` will return the value if it finds it, or `nil` if it can't find it. Let's now add the ability to remove an element from a set with the `remove` method: ``` ruby def remove(member) index = @underlying_array.bsearch_index { |x| member <=> x } if index @underlying_array.delete_at(index) true else false end end ``` _listing 9.38 The `IntSet#remove` method_ The `method` method uses the `bsearch_index` method in a way almost identical to how the `include?` method uses the `bsearch` method. By using the `Interger#<=>` method, we will either receive the index of `member` in the array, or `nil`. If `index` is `nil`, there's nothing to remove, so we can return `false` and call it a day. On the other hand, if `index` is not `nil`, we use the `Array#delete_at` method, which deletes the element at the given index. Let's now add the `pop` and `random_member` methods, which both behave very similarly, with the exception that `random_member` does not remove any elements from the array: ``` ruby # ... def pop rand_index = rand(@underlying_array.size) @underlying_array.delete_at(rand_index) end def random_member rand_index = rand(@underlying_array.size) @underlying_array[rand_index] end ``` _listing 9.39 The `pop`, & `random_member` methods in the `IntSet` class_ Finally, we need a few more methods to provide an easy to use API for the `IntSet` class, namely, the methods `empty?` to check if the sets is empty or not, `members`, to return all the members in the set, `cardinality`, to return the size of the set, and `each`, to provide a way to iterate over all the members in the set. Ruby gives us tools that allow us to provide these methods without having to explicitly define them. We're using the [`Forwardable` module][ruby-doc-forwardable] to delegate some methods directly to the `Array` instance, `@underlying_array`. We're also using the `alias` keyword to provide some of these methods through the same naming conventions used in Redis. We also use the `attr_reader` approach to create an accessor for the `@underlying_array` instance variable, and alias it to `members` to provide a more explicit method name: ``` ruby require 'forwardable' module BYORedis class IntSet extend Forwardable attr_reader :underlying_array def_delegators :@underlying_array, :empty?, :each, :size alias cardinality size alias card cardinality alias members underlying_array def initialize @underlying_array = [] end # ... end end ``` _listing 9.40 The `members`, `empty?`, `each` & `cardinality` methods in the `IntSet` class_ And with these aliases, we now have completed the `IntSet` class, let's now use it, in combination with the `Dict` class, to implement the Set commands, starting with the one allowing us to create a new set. [redis-set-commands]:https://redis.io/commands#set [redis-src-tset]:https://github.com/redis/redis/blob/6.0.0/src/t_set.c [redis-config-max-intset-entries]:https://github.com/redis/redis/blob/6.0.0/redis.conf#L1520 [redis-src-intset]:https://github.com/redis/redis/blob/6.0.0/src/intset.c [wikipedia-finite-sets]:https://en.wikipedia.org/wiki/Finite_set [wikipedia-set-type]:https://en.wikipedia.org/wiki/Set_(abstract_data_type) [chapter-8]:/post/chapter-8-adding-hash-commands/ [redis-src-dictadd]:https://github.com/redis/redis/blob/6.0.0/src/t_set.c#L79 [ruby-doc-bsearch]:https://ruby-doc.org/core-2.7.1/Array.html#bsearch-method [ruby-doc-forwardable]:https://ruby-doc.org/stdlib-2.7.1/libdoc/forwardable/rdoc/Forwardable.html [ruby-doc-bsearch]:https://ruby-doc.org/core-2.7.1/Array.html#bsearch-method [ruby-doc-bsearch-index]:https://ruby-doc.org/core-2.7.1/Array.html#bsearch_index-method [ruby-doc-insert]:https://ruby-doc.org/core-2.7.1/Array.html#insert-method [wikipedia-set-relative-complement]:https://en.wikipedia.org/wiki/Complement_(set_theory)#Relative_complement [wikipedia-set-union]:https://en.wikipedia.org/wiki/Union_(set_theory) [wikipedia-set-intersection]:https://en.wikipedia.org/wiki/Intersection_(set_theory) [github-code]:https://github.com/pjambet/redis-in-ruby/tree/master/code/chapter-9 [chapter-10]:/post/chapter-10-adding-sorted-set-commands/ [chapter-6]:/post/chapter-6-building-a-hash-table/ [ruby-set-class]:https://ruby-doc.org/stdlib-2.7.1/libdoc/set/rdoc/Set.html [chapter-7]:/post/chapter-7-adding-list-commands/ [ruby-doc-array-pack]:https://ruby-doc.org/core-2.7.1/Array.html#pack-method <file_sep>/content/post/chapter-16-transactions.md --- title: "Chapter 16 Transactions" date: 2020-10-17T18:18:40-04:00 lastmod: 2020-10-17T18:18:40-04:00 draft: true comment: false keywords: [] summary: "" --- <!--more--> DISCARD EXEC MULTI UNWATCH WATCH <file_sep>/code/chapter-1/server.rb require 'socket' server = TCPServer.new 2000 # Server bind to port 2000 loop do client = server.accept # Wait for a client to connect client.puts 'Hello !' client.puts "Time is #{Time.now}" client.close end <file_sep>/code/chapter-10/sorted_array.rb require 'forwardable' module BYORedis class SortedArray extend Forwardable def_delegators :@underlying, :[], :delete_if, :size, :each, :delete_at, :shift, :bsearch_index, :map, :each_with_index, :pop, :empty?, :slice! def self.by_fields(*fields) SortedArray.new do |array_element, new_element| comparison = nil fields.each do |field| comparison = new_element.send(field) <=> array_element.send(field) # As long as the members are equal for field, we keep comparing if comparison == 0 next else break end end comparison end end def initialize(&block) @underlying = [] @block = block end def push(new_element) if @underlying.empty? index = 0 else index = @underlying.bsearch_index do |element| @block.call(element, new_element) <= 0 end end index = @underlying.size if index.nil? @underlying.insert(index, new_element) end alias << push def index(element) if @underlying.empty? nil else @underlying.bsearch_index do |existing_element| @block.call(existing_element, element) end end end def delete(element) index = index(element) return if index.nil? element_at_index = @underlying[index] first_index_to_delete = nil number_of_items_to_delete = 0 while element_at_index if element_at_index == element first_index_to_delete ||= index number_of_items_to_delete += 1 end index += 1 next_element = @underlying[index] if next_element && @block.call(next_element, element_at_index) == 0 element_at_index = next_element else break end end @underlying.slice!(first_index_to_delete, number_of_items_to_delete) end def first_index_in_range(range_spec) return nil if empty? @underlying.bsearch_index do |existing_element| compare = range_spec.compare_with_min(yield(existing_element)) if range_spec.min_exclusive? compare > 0 # existing_element.score > min else compare >= 0 # existing_element.score >= min end end end def last_index_in_range(range_spec) return nil if empty? first_index_outside = @underlying.bsearch_index do |existing_element| compare = range_spec.compare_with_max(yield(existing_element)) if range_spec.max_exclusive? compare >= 0 # existing_element.score > max else compare > 0 # existing_element.score >= max end end case first_index_outside when nil then @underlying.size - 1 # last when 0 then nil # the max of the range is smaller than the smallest item else first_index_outside - 1 end end end end <file_sep>/code/chapter-9/dict_entry.rb module BYORedis class DictEntry attr_accessor :next, :value attr_reader :key def initialize(key, value) @key = key @value = value @next = nil end end end <file_sep>/code/chapter-6/expire_helper.rb module BYORedis module ExpireHelper def self.check_if_expired(data_store, expires, key) expires_entry = expires[key] if expires_entry && expires_entry < Time.now.to_f * 1000 logger.debug "evicting #{ key }" expires.delete(key) data_store.delete(key) end end def self.logger @logger ||= Logger.new(STDOUT).tap do |l| l.level = LOG_LEVEL end end end end <file_sep>/code/chapter-5/get_command.rb module BYORedis class GetCommand def initialize(data_store, expires, args) @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @data_store = data_store @expires = expires @args = args end def call if @args.length != 1 RESPError.new("ERR wrong number of arguments for 'GET' command") else key = @args[0] ExpireHelper.check_if_expired(@data_store, @expires, key) value = @data_store[key] if value.nil? NullBulkStringInstance else RESPBulkString.new(value) end end end def self.describe [ 'get', 2, # arity # command flags [ 'readonly', 'fast' ].map { |s| RESPSimpleString.new(s) }, 1, # position of first key in argument list 1, # position of last key in argument list 1, # step count for locating repeating keys # acl categories: https://github.com/antirez/redis/blob/6.0/src/server.c#L161-L166 [ '@read', '@string', '@fast' ].map { |s| RESPSimpleString.new(s) }, ] end end end <file_sep>/code/chapter-10/redis_set.rb require_relative './int_set' require_relative './dict' module BYORedis class RedisSet # How many times bigger should be the set compared to the requested size # for us to don't use the "remove elements" strategy? Read later in the # implementation for more info. # See: https://github.com/antirez/redis/blob/6.0.0/src/t_set.c#L609-L612 SRANDMEMBER_SUB_STRATEGY_MUL = 3 # How many times bigger should be the set compared to the remaining size # for us to use the "create new set" strategy? Read later in the # implementation for more info. # See: https://github.com/antirez/redis/blob/6.0.0/src/t_set.c#L413-416 SPOP_MOVE_STRATEGY_MUL = 5 def initialize @underlying = IntSet.new end def self.intersection(sets) # Sort the sets smallest to largest sets.sort_by!(&:cardinality) intersection_set = RedisSet.new # Iterate over the first set, if we find a set that does not contain it, discard sets[0].each do |member| present_in_all_other_sets = true sets[1..-1].each do |set| unless set.member?(member) present_in_all_other_sets = false break end end # Otherwise, keep intersection_set.add(member) if present_in_all_other_sets end intersection_set end def self.union(sets) if sets.empty? RedisSet.new else union_set = RedisSet.new sets.each do |set| set&.each { |member| union_set.add(member) } end union_set end end def self.difference(sets) first_set = sets[0] return RedisSet.new if first_set.nil? # Decide which algorithm to use algo_one_work = 0 algo_two_work = 0 sets.each do |other_set| algo_one_work += sets[0].cardinality algo_two_work += other_set ? other_set.cardinality : 0 end # Directly from Redis: # Algorithm 1 has better constant times and performs less operations # if there are elements in common. Give it some advantage: algo_one_work /= 2 diff_algo = (algo_one_work <= algo_two_work) ? 1 : 2 if diff_algo == 1 if sets.length > 1 sets[0..0] + sets[1..-1].sort_by! { |s| -1 * s.cardinality } end difference_algorithm1(sets) else difference_algorithm2(sets) end end def self.difference_algorithm1(sets) return RedisSet.new if sets.empty? || sets[0].nil? dest_set = RedisSet.new sets[0].each do |element| i = 0 other_sets = sets[1..-1] while i < other_sets.length other_set = other_sets[i] # There's nothing to do when one of the sets does not exist next if other_set.nil? # If the other set contains the element then we know we don't want to add element to # the diff set break if other_set == self break if other_set.member?(element) i += 1 end if i == other_sets.length dest_set.add(element) end end dest_set end private_class_method :difference_algorithm1 def self.difference_algorithm2(sets) return self if sets.empty? || sets[0].nil? dest_set = RedisSet.new # Add all the elements from the first set to the new one sets[0].each do |element| dest_set.add(element) end # Iterate over all the other sets and remove them from the first one sets[1..-1].each do |set| set.each do |member| dest_set.remove(member) end end dest_set end private_class_method :difference_algorithm2 def add(member) case @underlying when IntSet int_member = convert_to_int_or_nil(member) if int_member added = @underlying.add(int_member) if added && cardinality + 1 > Config.get_config(:set_max_intset_entries) convert_intset_to_dict end added else convert_intset_to_dict @underlying.set(member, nil) end when Dict then @underlying.set(member, nil) else raise "Unknown type for structure: #{ @underlying }" end end def cardinality case @underlying when IntSet then @underlying.cardinality when Dict then @underlying.used else raise "Unknown type for structure #{ @underlying }" end end def members case @underlying when IntSet then @underlying.members.map { |i| Utils.integer_to_string(i) } when Dict then @underlying.keys else raise "Unknown type for structure #{ @underlying }" end end def pop case @underlying when IntSet then Utils.integer_to_string(@underlying.pop) when Dict then random_entry = @underlying.fair_random_entry @underlying.delete(random_entry.key) random_entry.key else raise "Unknown type for structure #{ @underlying }" end end def pop_with_count(count) return [] if count.nil? || count == 0 # Case 1: count is greater or equal to the size of the set, we return the whole thing if count >= cardinality all_members = members clear return all_members end remaining = cardinality - count if remaining * SPOP_MOVE_STRATEGY_MUL > count # Case 2: Count is small compared to the size of the set, we "just" pop random elements count.times.map { pop } else # Case 3: count is big and close to the size of the set, and remaining is small, we do # the reverse, we pick remaining elements, and they become the new set new_set = RedisSet.new remaining.times { new_set.add(pop) } # We have removed all the elements that will be left in the set, so before swapping # them, we store all the elements left in the set, which are the ones that will end up # popped result = members # Now that we have saved all the members left, we clear the content of the set and copy # all the items from new_set, which are the ones left clear new_set.each { |member| add(member) } result end end def random_members_with_count(count) return [] if count.nil? || count == 0 # Case 1: Count is negative, we return that many elements, ignoring duplicates if count < 0 members = [] (-count).times do members << random_member end return members end # Case 2: Count is positive and greater than the size, we return the whole thing return self if count >= cardinality # For both case 3 & 4 we need a new set new_set_content = Dict.new # Case 3: Number of elements in the set is too small to grab n random distinct members # from it so we instead pick random elements to remove from it # Start by creating a new set identical to self and then remove elements from it if count * SRANDMEMBER_SUB_STRATEGY_MUL > cardinality size = cardinality each { |member| new_set_content.add(member, nil) } while size > count random_entry = new_set_content.fair_random_entry new_set_content.delete(random_entry.key) size -= 1 end return new_set_content.keys end # Case 4: The number of elements in the set is big enough in comparison to count so we # do the "classic" approach of picking count distinct elements added = 0 while added < count member = random_member added += 1 if new_set_content.add(member, nil) end new_set_content.keys end def random_member case @underlying when IntSet then Utils.integer_to_string(@underlying.random_member) when Dict then @underlying.fair_random_entry.key else raise "Unknown type for structure #{ @underlying }" end end def empty? case @underlying when IntSet then @underlying.empty? when Dict then @underlying.used == 0 else raise "Unknown type for structure #{ @underlying }" end end def include?(member) return false if member.nil? case @underlying when IntSet then if member.is_a?(Integer) member_as_int = member else member_as_int = Utils.string_to_integer_or_nil(member) end if member_as_int @underlying.member?(member_as_int) else false end when Dict then @underlying.member?(member) else raise "Unknown type for structure #{ @underlying }" end end alias member? include? def each(&block) case @underlying when IntSet then @underlying.each { |i| block.call(Utils.integer_to_string(i)) } when Dict then @underlying.each(&block) else raise "Unknown type for structure #{ @underlying }" end end def remove(member) case @underlying when IntSet member_as_integer = Utils.string_to_integer_or_nil(member) if member_as_integer @underlying.remove(member_as_integer) else false end when Dict then !@underlying.delete_entry(member).nil? else raise "Unknown type for structure #{ @underlying }" end end private def clear @underlying = IntSet.new end def convert_intset_to_dict dict = Dict.new @underlying.each do |member| dict[Utils.integer_to_string(member)] = nil end @underlying = dict end def convert_to_int_or_nil(member) Utils.string_to_integer(member) rescue InvalidIntegerString nil end end end <file_sep>/code/chapter-4/server.rb require 'socket' require 'timeout' require 'logger' LOG_LEVEL = ENV['DEBUG'] ? Logger::DEBUG : Logger::INFO require_relative './expire_helper' require_relative './get_command' require_relative './set_command' require_relative './ttl_command' require_relative './pttl_command' class RedisServer COMMANDS = { 'GET' => GetCommand, 'SET' => SetCommand, 'TTL' => TtlCommand, 'PTTL' => PttlCommand, } MAX_EXPIRE_LOOKUPS_PER_CYCLE = 20 DEFAULT_FREQUENCY = 10 # How many times server_cron runs per second TimeEvent = Struct.new(:process_at, :block) def initialize @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @clients = [] @data_store = {} @expires = {} @server = TCPServer.new 2000 @time_events = [] @logger.debug "Server started at: #{ Time.now }" add_time_event(Time.now.to_f.truncate + 1) do server_cron end start_event_loop end private def add_time_event(process_at, &block) @time_events << TimeEvent.new(process_at, block) end def nearest_time_event now = (Time.now.to_f * 1000).truncate nearest = nil @time_events.each do |time_event| if nearest.nil? nearest = time_event elsif time_event.process_at < nearest.process_at nearest = time_event else next end end nearest end def select_timeout if @time_events.any? nearest = nearest_time_event now = (Time.now.to_f * 1000).truncate if nearest.process_at < now 0 else (nearest.process_at - now) / 1000.0 end else 0 end end def start_event_loop loop do timeout = select_timeout @logger.debug "select with a timeout of #{ timeout }" result = IO.select(@clients + [@server], [], [], timeout) sockets = result ? result[0] : [] process_poll_events(sockets) process_time_events end end def process_poll_events(sockets) sockets.each do |socket| begin if socket.is_a?(TCPServer) @clients << @server.accept elsif socket.is_a?(TCPSocket) client_command_with_args = socket.read_nonblock(1024, exception: false) if client_command_with_args.nil? @clients.delete(socket) elsif client_command_with_args == :wait_readable # There's nothing to read from the client, we don't have to do anything next elsif client_command_with_args.strip.empty? @logger.debug "Empty request received from #{ client }" else commands = client_command_with_args.strip.split("\n") commands.each do |command| response = handle_client_command(command.strip) @logger.debug "Response: #{ response }" socket.puts response end end else raise "Unknown socket type: #{ socket }" end rescue Errno::ECONNRESET @clients.delete(socket) end end end def process_time_events @time_events.delete_if do |time_event| next if time_event.process_at > Time.now.to_f * 1000 return_value = time_event.block.call if return_value.nil? true else time_event.process_at = (Time.now.to_f * 1000).truncate + return_value @logger.debug "Rescheduling time event #{ Time.at(time_event.process_at / 1000.0).to_f }" false end end end def handle_client_command(client_command_with_args) @logger.debug "Received command: #{ client_command_with_args }" command_parts = client_command_with_args.split command_str = command_parts[0] args = command_parts[1..-1] command_class = COMMANDS[command_str] if command_class command = command_class.new(@data_store, @expires, args) command.call else formatted_args = args.map { |arg| "`#{ arg }`," }.join(' ') "(error) ERR unknown command `#{ command_str }`, with args beginning with: #{ formatted_args }" end end def server_cron start_timestamp = Time.now keys_fetched = 0 @expires.each do |key, _| if @expires[key] < Time.now.to_f * 1000 @logger.debug "Evicting #{ key }" @expires.delete(key) @data_store.delete(key) end keys_fetched += 1 if keys_fetched >= MAX_EXPIRE_LOOKUPS_PER_CYCLE break end end end_timestamp = Time.now @logger.debug do sprintf( "Processed %i keys in %.3f ms", keys_fetched, (end_timestamp - start_timestamp) * 1000) end 1000 / DEFAULT_FREQUENCY end end <file_sep>/code/chapter-1/server.c #include <stdio.h> // For printf #include <netdb.h> // For bind, listen, AF_INET, SOCK_STREAM, socklen_t, sockaddr_in, INADDR_ANY #include <stdlib.h> // For exit #include <string.h> // For bzero #include <unistd.h> // For close & write #include <errno.h> // For errno, duh! #include <arpa/inet.h> // For inet_ntop #define MAX 80 #define PORT 2000 #define SA struct sockaddr int main() { socklen_t client_address_length; int server_socket_file_descriptor, client_socket_file_descriptor; struct sockaddr_in server_address, client_address; // socket create and verification server_socket_file_descriptor = socket(AF_INET, SOCK_STREAM, 0); if (server_socket_file_descriptor == -1) { printf("socket creation failed...\n"); exit(0); } else { printf("Socket successfully created..\n"); } bzero(&server_address, sizeof(server_address)); // assign IP, PORT server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = htons(PORT); // Binding newly created socket to given IP and verification if ((bind(server_socket_file_descriptor, (SA*)&server_address, sizeof(server_address))) != 0) { printf("socket bind failed... : %d, %d\n", server_socket_file_descriptor, errno); exit(0); } else { printf("Socket successfully binded..\n"); } // Now server is ready to listen and verification if ((listen(server_socket_file_descriptor, 5)) != 0) { printf("Listen failed...\n"); exit(0); } else { printf("Server listening..\n"); } client_address_length = sizeof(client_address); // Accept the data packet from client and verification client_socket_file_descriptor = accept(server_socket_file_descriptor, (SA*)&client_address, &client_address_length); if (client_socket_file_descriptor < 0) { printf("server acccept failed: %d,%d...\n", client_socket_file_descriptor, errno); exit(0); } else { printf("server acccept the client...\n"); char human_readable_address[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &client_address.sin_addr, human_readable_address, sizeof(human_readable_address)); printf("Client address: %s\n", human_readable_address); } char message_buffer[MAX]; read(client_socket_file_descriptor, message_buffer, sizeof(message_buffer)); printf("From Client: %s\n", message_buffer); bzero(message_buffer, MAX); strcpy(message_buffer, "Hello, this is Server!"); write(client_socket_file_descriptor, message_buffer, sizeof(message_buffer)); // After chatting close the socket printf("Closing server_socket_file_descriptor\n"); close(server_socket_file_descriptor); } <file_sep>/README.md # Rebuilding Redis in Ruby The hugo code for [Rebuilding Redis in Ruby](https://redis.pjam.me) # Current status The project's code follows an iterative approach where each chapter continues where the previous one left off. The latest completed Chapter is [on Sorted Sets](code/chapter-10/). # Running locally You can run the server locally with the following command from inside the corresponding chapter folder: `ruby -r"./server" -e "BYORedis::Server.new"`. By default it runs on port 2000. It starts a Redis Protocol compliant server, which you can interact with any Redis clients, such as `redis-cli`: ``` sh > redis-cli -p 2000 127.0.0.1:2000> SET a b OK 127.0.0.1:2000> GET a "b" ``` <file_sep>/content/post/chapter-6-building-a-hash-table.md --- title: "Chapter 6 Building a Hash Table" date: 2020-08-31T16:25:47-04:00 lastmod: 2020-08-31T16:25:52-04:00 draft: false comment: false keywords: [] summary: "In this chapter we will write our own hash table. This will allow to remove uses of the Ruby Hash class and use our Dict class, built from scratch." --- ## What we'll cover So far we've been using the Ruby [`Hash`][ruby-doc-hash] class as the main storage mechanism for the key/value pairs received through the `SET` command. We also use it for the secondary dictionary necessary to implement the TTL related options of the `SET` command. We store the expiration timestamp of keys with TTLs, which allows us to know whether a key is expired or not. Redis is written in C, which does not provide a collection similar to Ruby's `Hash`. In C, you only get one collection out of the box, [arrays][c-doc-array]. Redis implements its own dictionary collection, in [`dict.c`][github-link-dict]. Because the dictionary data structure is so central to how Redis functions, we will replace the use of the Ruby `Hash` class with a `Dict` class we will build from scratch. We will also add the `DEL` command, the ability to delete keys is really important to Redis. Having the `DEL` command will also allow us to easily play with our `Dict` class to make sure that it handles deletion operations correctly. We are not adding any new features in this chapter, beside the `DEL` command, we're rewriting a key part of the system with lower level elements. Given that Redis' `dict` data structure relies on arrays, we will still use the Ruby [`Array` class][ruby-doc-array]. We could have reimplemented the `Array` class, and you'll find an example in [Appendix A](#appendix-a-array-from-scratch-in-ruby), but arrays in C are not specific to Redis. On the other hand, the structure defined in [`dict.c`][github-link-dict] is. Let's get to it. ## Maps, Dictionaries, Associative Arrays This chapter covers hash tables, which is one way of implementing a data structure commonly called Map, Dictionary or Associative Array. I will use the term "Dictionary" as I find that "Map" can be confusing, especially when working with languages providing a `map` function/method, such as Ruby! From my experience the term associative array, while very explicit, is not as common. The basic definition of such data structure is one that holds zero or more key/value pairs, where a key cannot appear more than once. A key operation (pun intended!) of a dictionary is the ability to retrieve a value given a key. The returned value is either empty if no element with such keys exists in the map, or the value mapped to the key if it exists. Some definitions also include the ability to add, update or delete key/value pairs, which is not provided in immutable versions, where such operations would result in the creation of a new dictionary. The immutable versions will implement similar operations returning a new structure instead of modifying it. There are multiple ways of implementing a data structure providing these operations. A naive and fairly inefficient version could be to use an array where each element is a key value pair: ``` ruby def set(map, key, value) map.each do |pair| pair_key = pair[0] # Override the value if the key is already present if key == pair_key pair[1] = value return pair end end pair = [key, value] map << pair pair end def lookup(map, key) map.each do |pair_key, pair_value| return pair_value if key == pair_key end return end ``` _listing 6.1: A basic dictionary using an array_ Given these functions, `set` & `lookup`, we could use them with an array: ``` ruby map = [] set(map, "key-1", "value-1") # => ["key-1", "value-1"] set(map, "key-2", "value-2") # => ["key-2", "value-2"] set(map, "key-2", "value-3") # => ["key-2", "value-3"] lookup(map, "key-1") # => "value-1" lookup(map, "key-2") # => "value-2" lookup(map, "key-3") # => nil ``` This approach works from an API standpoint, but it would show performance issues as we keep adding elements to the array. Because we must prevent duplicated keys, we need to iterate through the whole array every time we attempt to add a new pair if the key is not already present. This `set` implementation is an O(n) operation, where n is the number of pairs in the dictionary. The amount of time required to add an element is proportional to the size of the collection. A lookup might not always require a complete scan of the array, if we're lucky and find the key before the end, but it might, in the worst case scenario. The `lookup` operation is therefore also an O(n) operation. For Redis, which should be able to handle hundreds of thousand of keys, even millions, and potentially billions, these performance issues are not acceptable. One common implementation that addresses these performance issues is a hash table. Another possible implementation is a tree map, which uses a tree structure to store elements. For instance, the Java [`TreeMap` class][java-doc-tree-map] uses a Red-Black tree to maintain the underlying tree balanced. One of the benefits of a tree map compared to a hash table is that it stores elements in order, whereas a hash table does not. In the next section we will learn how hash tables implement these operations in a more time efficient manner. Before moving on and abandoning this implementation, it's really important to note that while this implementation would not perform well with large collections, it might actually be one of the most efficient options for very small collections, such as with one or two pairs, thanks to its simplicity. If the array is small, finding an element requires very few steps and little memory overhead. As a matter of fact, the [Scala standard library][scala-map-optimization] does something similar for dictionaries with up to four pairs, it has special case classes meant to handle these fixed sized dictionaries, allowing them to be really fast as there's no need for hashing or anything else. ## Hash Tables Hash tables are available in many programming languages as part of their standard libraries. Python has [`dict`][python-dict], Java has [`HashMap`][java-hashmap], Scala has [`Map`][scala-map], Elixir has [`Map`][elixir-map], Rust has [`HashMap`][rust-hashmap], Ruby's `Hash` class is a hash table implementation too. You get it, they're almost everywhere. Hash tables can be implemented in different ways, [the wikipedia article][wikipedia-hash-table] shows a few different examples. The one we'll explore in this chapter uses a collision resolution called separate chaining. But why do we need collision resolution? To answer this we first need to look at the central element of a hash table, its hash function. A [hash function][wikipedia-hash-function] must obey a few properties, one of the most important ones being determinism, in other words, identical inputs should result in identical outputs. To explain why, let's look at how the hashing function is used through a pseudo code implementation of a hash table: ``` function new_node(key, value, next_node) return Node(key, value, next_node) function update_node(node, new_value) return Node(node.key, new_value) function create_hash_table() table = allocate_array_of_arbitrary_initial_size() return table function add_or_update_key_value_pair(table, key, value) hash = hash_function(key) index = hash % table.size node = table[index] if node == null table[index] = new_node(key, value, null) else while node != null && node.key != key node = node.next_node if node.nil? existing_node = table[index] table[index] = new_node(key, value, existing_node) else update_node(node, value) function lookup_key(table, key) hash = hash_function(key) index = hash % table.size if table[index] == null return null else node = table[index] while node != null if node.key == key return key else node = node.next_node return null ``` _listing 6.2: Pseudo-code hash table_ The `new_node` function acts as the entry point of a linked list. A node contains a key, a value, and a next node value. If the next node value is null, the element is the last one in the list. Prepending - a fancy word for "adding at the beginning" - an element to such list is done by first creating a single node list and then a second one, with the `next_node` value set to the first one: ``` node1 = new_node(key1, value1, null) node2 = new_node(key2, value2, node1) ``` In this example `node1` is a list with a single node, and `node2` is a list with two nodes. The first node is the one with the key `key2` and the value `value2`, its `next_node` value is equal to `node1`, which has the key `key1` and value `value1`, it does not have a `next_node` value and is the last element of the list. `update_node` works with an existing node and changes its value. It is a useful function when we find an existing pair with a matching key in `add_or_update_key_value_pair`. We explore this other function in more details below. `create_hash_table` does only one thing, it allocates an array of arbitrary size. We purposefully do not define this function here. The size is not really important, as long as it creates a non empty array. The implementation of the allocation is also not really relevant to this example. Most operating systems provide such features, it's therefore fair to assume that it would use the allocation operations provided by the operating system. [`malloc`][c-malloc] is a function in the C standard library that does provide the ability to manually allocate memory. `add_or_update_key_value_pair` does more work and let's walk through it, one line at a time. It takes three parameters, the table we want to insert the pair into, the key and the value. We first call `hash_function` with `key`. We'll dive deeper into what an implementation of `hash_function` looks like later, but for now, let's assume it returns an integer. Because the hash function is unaware of the size of the array, the returned value might be larger than the size of the array. We use the modulo operation to convert the hash value returned by `hash_function` into a number between `0` and `table.size - 1`. We can now use the result of the modulo operation as an index. That's why we have the `create_hash_table` function, to make sure that table is initialized with empty slots. These slots are often called buckets in hash table lingo. If the bucket is empty, then we create a new node, add it to the bucket and we're done. If the bucket is not empty, then things are more complicated. There are two distinct cases to consider if there is already an item at the location obtained through the hash function. One of the nodes in the bucket might have the same key, in this case we want to override its value with the new value. This the case where we want to update an element in the array instead of adding it. The other one is that the nodes already present might all have a different key, in which case we want to keep all the existing nodes and add the new one. This the case where we want to add a new pair, and **is called a collision**. Let's illustrate with an example. Let's set the initial size of the array to 4, all the buckets are empty: ``` ruby table = [nil, nil, nil, nil] ``` Let's define a hash function, that returns the length of the input string: ``` ruby function hash_function(string) return string.length ``` If we first call `add_or_update_key_value_pair` with the key `"a"` and the value `"b"`, `hash_function` will return `1`, the length of the string `"a"`. `1 % 4` returns `1,` so we add the pair at index `1`: ``` ruby table = [nil, Node("a", "b", nil), nil, nil] ``` Let's call `add_or_update_key_value_pair` with the pair `"cd"`/`"e"`, the length of `"cd"` is `2`, `2 % 4` is `2`, we insert the pair at index `2`: ``` ruby table = [nil, Node("a", "b", nil), Node("cd", "e", nil), nil] ``` Let's now call `add_or_update_key_value_pair` with `"fg"`/`"h"`. The length of `"fg`" is `2`, but there's already a pair at index `2`. Because we want to keep all pairs we need a solution to resolve this collision. There are different strategies available to us here, and the one we're going to use is called "separate chaining". The essence of this strategy is that each bucket contains a linked list of values. So in the previous example, we insert the new element at the beginning of the list at index `2`. Note that prepending an element to a linked list is an O(1) operation, it takes the same amount of time regardless of the size of the list. This is the list once the operation is completed: ``` ruby table = [nil, Node("a", "b", nil), Node("fg", "h", "Node("cd", "e", nil)), nil] ``` `lookup_key` is very similar to `add_or_update_key_value_pair`. We use the same process to find which bucket the key should be in. If the bucket is empty, we return `null`, the key is not present in the dictionary. On the other hand, if the bucket is not empty, we need to look through the list until we find the node with the key argument. If we don't find any, the key is not present in the dictionary. **Trying to avoid collisions** The `hash_function` we used in the previous works well as an example because of its simplicity but it would not be practical in the real world. To keep hash tables efficient, we want to reduce the number of collisions as much as possible. This is because iterating through the linked list is inefficient, if there are a lot of collisions, it could take a long time to loop through all the items in the bucket. This is where the [uniformity property][wikipedia-hash-function-uniformity] of a hash function is really important. Uniformity helps reduce the likelihood of collision. In the previous example, if a hypothetical hash function had returned the values `1`, `2` & `3`, respectively, instead of `1`, `2` & `2`, there wouldn't have been any conflicts. Collisions are also related to the size of the underlying array. Regardless of the uniformity of the hash function, if the underlying array has a size n, storing n + 1 items cannot happen without at least one collision. One approach would be to start by allocating a very large amount of memory, but this can be wasteful, because there could be a lot of memory allocated, but unused. Many hash table implementation have mechanisms to adjust the size as needed, and it turns out that Redis does this too, as we'll see in the next section. A good hash function that provides uniformity means that both operations `add/update` & `lookup` have an O(1) time complexity, meaning that the number of steps is always the same regardless of the number of elements already present. We first hash the value, transform it to an index and use the matching bucket. On the other hand, a bad hash function without uniformity would make these operations O(n). In the absolute worst case scenario, all keys would land in the same bucket, and the number of operations required would depend on the number of elements already present in the linked list in the bucket. **Back to determinism** Now that we know how the result of a hash function is used, that is, it determines the location of a key/value pair in the underlying array, let's go back to the determinism element of a hash function. Let's demonstrate why we need determinism by showing what would happen with a hash function that is not deterministic. In Ruby, each object is given an object id, in the following examples, the two variables `str1` & `str2` are different instances, each holding the same value, and are therefore considered equal, but have different `object_id` values: ``` ruby str1 = "hello" str2 = "hello" str1.object_id # => 180 str2.object_id # => 200 # The object_id values might be different on your machine, they are assigned at runtime # and will therefore differ if you've created more Ruby objects beforehand for instance str1 == str2 # => true ``` Let's define a wrong hash function, which returns its input's `object_id`: ``` ruby def hash_function(object) object.object_id end ``` Let's manually walk through a small example, let's start by creating a hash table of size 3 and add the pair `a-key/a-value` to it. Let's re-use the same `object_id` from the previous example, and assume that `a-key` would have returned `180`. `180 % 3 = 0`, so we insert the new node at index `0`: ``` ruby table = [Node("a-key", "a-value", nil), nil, nil] ``` And let's now call the lookup function with a different string holding the same value, and, reusing the previous example data again, assume that its object id is 200, `200 % 3 = 2`. The lookup would look at the bucket at index 2, find a `nil` value and return nil, whereas the table does contain a pair with the key `a-key`. A deterministic hash function prevents this. **Common Hash Functions** In order for a hash table implementation to be efficient, it needs a good hash function. Hash functions come in different flavors, as shown [on wikipedia][wikipedia-list-of-hash-functions]: - Cyclic redundancy checks - Checksums - Universal hash function families - Non-cryptographic - Keyed cryptographic - Unkeyed cryptographic Some of the functions in the "Unkeyed cryptographic hash functions" category are pretty common. MD5 used to be very common to verify the integrity of a file downloaded over the internet. You would download the file, compute the md5 of the file locally and compare it against the md5 published by the author of the file. It is common to see sha256 used instead nowadays. This is what the [Downloads page on ruby-lang.org][ruby-downloads] does! For a long time sha1 was the default algorithm used by git to hash commits and other objects. It now supports multiple algorithms such as sha256. This change was required after researchers proved that it was possible to forge two different inputs resulting in the same sha1 hash. Redis uses SipHash which is in the "Keyed cryptographic hash functions" category. We will look closer at the SipHash algorithm below. All Ruby objects implement a `hash` method, which happens to use the Siphash algorithm, the same algorithm Redis uses! ``` ruby str1 = "hello" str2 = "hello" # Note that the hash value is partially computed from a random value and will therefore be different # on your machine # It will also be different if you restart irb str1.hash # => 2242191710387986831 str2.hash # => 2242191710387986831 ``` Now that we know what a hash function is, how it used to implement a hash table, let's look at how things work in Redis. ## How does Redis do it? Redis uses three data structures to implement a dictionary, `dict`, `dictht` & `dictEntry`, the following diagram, from [wjin.org][wjin-blog], shows how they each relate to each other: ![Diagram of Redis' dict data structure](/img/redis_dict.png) It's important to note that dictionaries are used in multiple places in the Redis codebase, but there are two main ones for each database, the one holding all the top-level key/value pairs, such as the ones added with `SET` and other commands creating pairs, and the `expires` dictionary, used to store key TTLs. If you're not used to C, don't worry too much about it for now, we're not going to look too closely at pointers and other C specific features. Our implementation supports a single database, but Redis can handle multiple databases. A database in Redis represents a set of key/value pairs it is defined as the following C struct: ``` c typedef struct redisDb { dict *dict; /* The keyspace for this DB */ dict *expires; /* Timeout of keys with a timeout set */ dict *blocking_keys; /* Keys with clients waiting for data (BLPOP)*/ dict *ready_keys; /* Blocked keys that received a PUSH */ dict *watched_keys; /* WATCHED keys for MULTI/EXEC CAS */ int id; /* Database ID */ long long avg_ttl; /* Average TTL, just for stats */ unsigned long expires_cursor; /* Cursor of the active expire cycle. */ list *defrag_later; /* List of key names to attempt to defrag one by one, gradually. */ } redisDb; ``` _listing 6.3: The C struct for redisDB defined in [dict.c](https://github.com/antirez/redis/blob/6.0.0/src/server.h#L644-L654)_ We will ignore all the fields but the first two for now. We can see that the two fields, `dict` & `expires` are both of the same type: `dict`. `dict` is defined in [`dict.h`][redis-source-dict]: ``` c typedef struct dict { dictType *type; void *privdata; dictht ht[2]; long rehashidx; /* rehashing not in progress if rehashidx == -1 */ unsigned long iterators; /* number of iterators currently running */ } dict; ``` _listing 6.4: The C struct for dict_ Once again, in order to keep things as simple as possible, we will ignore some fields, specifically, `privdata` & `iterators`. The `dictType` struct is used to configure the behavior of a `dict` instance, such as using a different hash function for instance. It is defined as: ``` c typedef struct dictType { uint64_t (*hashFunction)(const void *key); void *(*keyDup)(void *privdata, const void *key); void *(*valDup)(void *privdata, const void *obj); int (*keyCompare)(void *privdata, const void *key1, const void *key2); void (*keyDestructor)(void *privdata, void *key); void (*valDestructor)(void *privdata, void *obj); } dictType; ``` _listing 6.5: The C struct for dictType defined in [dict.c](https://github.com/antirez/redis/blob/6.0.0/src/dict.h#L58-L65)_ The syntax used in this struct is different because the members are function pointers. That's about as far as we'll go with C in this chapter. Redis does this to allow a form of configuration of a `dict` instance. It has the ability to create two dictionaries with potentially two different hash function implementation. We don't need this level of flexibility at the moment so we will not implement these features for now. The most interesting element of the `dict` struct for us is the `dictht` array. `ht` here stands for **H**ash **T**able. `ht[2]` means that the struct member is named `ht` and is an array of size two. Essentially, each `dict` instance has two hash tables, `ht[0]` & `ht[1]`. `dictht` is defined as follows: ``` c /* This is our hash table structure. Every dictionary has two of this as we * implement incremental rehashing, for the old to the new table. */ typedef struct dictht { dictEntry **table; unsigned long size; unsigned long sizemask; unsigned long used; } dictht; ``` _listing 6.6: The C struct for dictht defined in [dict.c](https://github.com/antirez/redis/blob/6.0.0/src/dict.h#L67-L74)_ The comment tells us why a dict has two tables, for rehashing. To explain rehashing, we first need to explain the first member of `dictht`: `dictEntry **table`. The double star syntax, a pointer to pointer, is not that interesting to us at the moment, it is one way of defining an array of `dictEntry` with dynamic size, one that can be set at runtime. We then need to look at the `dictEntry` struct: ``` c typedef struct dictEntry { void *key; union { void *val; uint64_t u64; int64_t s64; double d; } v; struct dictEntry *next; } dictEntry; ``` _listing 6.7: The C struct for dictEntry defined in [dict.c](https://github.com/antirez/redis/blob/6.0.0/src/dict.h#L47-L56)_ `dictEntry` is a linked list, a common term for a structure like this one is "a node". It contains a key, `key`, a value, `v` and a link to the next element in the list, `next`. Because `dictEntry **table` is an array with a dynamic size, we also need the `size` member. `used` is a counter, that starts at `0` and that is incremented when items are added, and decremented when items are removed. `sizemask` is an integer value, which is initialized at `0` if `size` is also `0`, but is otherwise always set to `size - 1`. To understand the need for the `sizemask` member, let's look back at our pseudo code implementation from above. We can see that a very common operation is to use `hash_value % array_size`. This operation converts a value, potentially larger than the array size, to one that is between `0` and `size - 1`, allowing us to use the result as an index for the underlying array. The modulo operation, `%`, is not that costly, but it does require a few steps, an integer division, followed by a multiplication and a subtraction: `c - (c/m*m)`. Let confirm with an example: ``` ruby c = 469513 m = 143317 c % m # => 39562 c - (c/m*m) # => 39562 ``` Given how crucial this operation is to the performance of a hash table, every operation relies on it to find the bucket index, it is valuable to attempt to optimize it. It turns out that if, and only if, the modulus (the second part of the modulo operation, `b` in `a % b`, the size of the array in the hash table) is a power of two, then the modulo can be computed in a single operation with the bitwise `AND`/`&` operator: ``` a & (b-1) ``` Let's illustrate this with a few examples, if the backing array of the hash table is of size 4, then: ``` 0 % 4 = 0, 0 & 3 = 0 1 % 4 = 1, 1 & 3 = 1 2 % 4 = 2, 2 & 3 = 2 3 % 4 = 3, 3 & 3 = 3 4 % 4 = 0, 4 & 3 = 0 5 % 4 = 1, 5 & 3 = 1 ... ``` It might help to visualize the number as binary, let's use 4 bit integers for readability. The binary representation of 4 is `0100` and 3 is `0011`, so `0 & 3` can be represented as: ``` 0000 &0011 = 0000 (0) ``` The following shows the visualization of `1 & 3`, `2 & 3`, `3 & 3`, `4 & 3` & `5 & 3`. ``` 0001 (1) | 0010 (2) | 0011 (3) | 0100 (4) | 0101 (5) &0011 | &0011 | &0011 | &0011 | &0011 = | = | = | = | = 0001 (1) | 0010 (2) | 0011 (3) | 0000 (0) | 0001 (1) ``` In order to take advantage of this property, Redis always picks a size that is a power of two for the backing array. By setting `sizemask` to `size - 1`, Redis can efficiently compute the index of any keys once it obtained its hash value. This is a part of the code for `dictFind`: ``` c dictEntry *dictFind(dict *d, const void *key) { // ... h = dictHashKey(d, key); for (table = 0; table <= 1; table++) { idx = h & d->ht[table].sizemask; he = d->ht[table].table[idx]; // ... } return NULL; } ``` _listing 6.8: excerpt of dictFind_ `h` is the value returned by the hash function and `d->ht[table].sizemask` is how Redis accesses the `sizemask` value for its hash table. `idx` is the index indicating the location of the bucket. Redis then looks into the array to inspect the bucket with `he = d->ht[table].table[idx]` (`he` stands for **h**ash **e**ntry). **Rehashing** Now that we looked at the data structures that Redis uses to implement its `dict` type, we need to look at the rehashing process. A new dictionary in Redis is always empty, the backing table, the `table` member, is set to `NULL` and the `size`, `sizemask` and `used` members are all set to 0: ``` c // https://github.com/antirez/redis/blob/6.0.0/src/dict.c#L102-L108 static void _dictReset(dictht *ht) { ht->table = NULL; ht->size = 0; ht->sizemask = 0; ht->used = 0; } // https://github.com/antirez/redis/blob/6.0.0/src/dict.c#L121-L131 int _dictInit(dict *d, dictType *type, void *privDataPtr) { _dictReset(&d->ht[0]); _dictReset(&d->ht[1]); d->type = type; d->privdata = privDataPtr; d->rehashidx = -1; d->iterators = 0; return DICT_OK; } ``` _listing 6.9: C code for \_dictReset & \_dictInit_ Whenever Redis adds a new key/value pair to a dictionary, it first checks if the dictionary should be expanded. The main reason causing a dict to expand is if the number of items in it, the `used` member, is greater than or equal to the size of the dict, the `size` member. This will always be true for an empty dictionary since both are initialized to 0. This will also be true every time the number of items reaches the size of the dict. When the dict is of size 4, once 4 items are added, the next addition will trigger a resize. This is necessary to limit the likelihood of collisions, because as we discussed, collisions slow down the hash table. If the array contains four buckets and the table needs to store five items, it will at best have one collision. If we resize the array to contain eight buckets, then it is possible to store the five items without any collisions. As mentioned earlier, in order to take advantage of the "fast modulo for a power of two value through bitwise AND" property, Redis will always choose a power of two for the size. The smallest non empty size is 4, and it will grow through power of twos from there on: 8, 16, 32, 64 and so on. All the way up to `LONG_MAX + 1`, `9,223,372,036,854,775,808`, also written as `9.223372036854776e+18` in the exponential notation. That's 9.2 billion billions, Yes it's a huge number! {{% admonition info "Why LONG_MAX + 1" %}} Redis uses `LONG_MAX + 1` as the maximum value for a dict size. `LONG_MAX` is a constant defined in the C header file `limits.h` and is set to `9,223,372,036,854,775,807`. We can see that it's not a power of two by looking at the right most digit, `7`, it's not even, so we already know that it's not a power of two. All power of two are even numbers since by definition, we obtain them by multiplying `2`s. This big number is a 64-bit integer, where all bits are `1`s, except the first one: ``` 0111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 ``` The first bit is a 0 because LONG_MAX is a signed integer, that is it can be negative of positive. Signed integers use the first bit to determine the sign, `0` for positive, `1` for negative. The other bound is `LONG_MIN`, set to `-9,223,372,036,854,775,808`, which has the following binary representation: ``` 1000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 ``` This representation of signed numbers is called [Two's complement][twos-complement], there are other representations but two's complement is a very common one. The only larger number that can fit in a 64-bit integer, is the unsigned max value, where all bits, even the first one, are used to encode the integer value, it's called `ULONG_MAX`, `U` stands for **u**signed here, and is set to: `18,446,744,073,709,551,615`, `2^64 - 1` . As we did before, we can see that it's not a power of two, `5`, the last digit, is not even. This is its binary representation, 64 `1`s: ``` 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 ``` It means that if we want to use power of two numbers, then the largest one we can get to is `2^63`. The max value we can encode in a 64 bit integer is `2^64 - 1`, one short, so we have to stop one power of two below, hence setting the upper bound to `LONG_MAX + 1`, aka, `2^63`. {{% /admonition %}} Back in [Chapter 4][chapter-4] we talked about Big O notation and time complexity. The bottom line being that since Redis processes incoming commands sequentially, a slow operation would effectively back the queue. You can think of it as someone taking a long time to go through checkout at a grocery store. The longer they take, the more likely it is that the queue of customers waiting in line increases. Resizing a hash table is essentially an `O(n)` operation, the time it takes to do it is proportional to n, the number of elements in the hash table. In other words, the more elements in the table, the longer it'll take to resize it. And as we just saw, Redis hash tables can get big, really big! Forcing all the clients in the queue to wait while we resize the table is far from desirable. Enter rehashing! Rehashing is the process Redis uses to incrementally, in small steps, resize the table, while still allowing other operations to be processed, and this is why it uses two hash tables per dictionary. Let's look at how rehashing works through an example. Note that resizing the array is technically not necessary to store the items given that each entry in the array, the buckets, are linked lists. This means that even an array of size 4 could store millions and billions of key/value pairs. The problem is that the performance would suffer drastically, iterating through that many items in a linked list would take a very long time. With millions of items, it could easily take multiple seconds. - The Redis server starts, the main dict is initialized with two hash tables, both empty - The server receives a SET command, it needs to expand the dictionary. - It finds the next power of two that will be enough to fit all the elements, it needs to store one element, so it uses the minimum value 4. - It allocates the main array, `ht[0]`, with a size of 4, and adds the first key/value pair - The second, third & fourth values are added without any issues. `used` is now set to 4 - A fifth SET command is received, Redis decides to resize the dict. - The resize process allocates a new table, big enough to store all the items, for which the size is a power of two. It selects the next power of two, 8. - The new table is assigned to the secondary table, the rehashing one, `ht[1]` - The dict is now a rehashing state. In this state, all new keys are added to the rehashing table. - The dict has now 2 tables, where 4 keys are in the first table and 1 is in the second one. - While in this state, many operations, such as key lookups will look at both tables. For instance a GET command will first look at the first table, and if it doesn't find the item, will look at the rehashing table, and only if the items can't be find in either table, will return NULL. - While in rehashing state, many commands, such as key lookups or key additions, will perform a single step of rehashing. The `server_cron` time event we looked at in Chapter 3 also attempts to rehash dictionaries that needs to. - The rehashing process starts at index 0, looks at the first table, and if it finds an item, moves it to the second table. It then moves to index 1, until it iterated through the entire table - Once it's done, it makes the rehashing table the primary, resets the rehashing table to an empty table and exits the rehashing state This process allows Redis to resize dictionaries in small steps, while not preventing clients to send commands in the meantime. Rehashing is also used to reduce the size of a dictionary. If the number of keys, the `used` member, goes below 1/10th of the `size` value, that is, only 10% of the dictionary is used, Redis will try to find a better size to fit the keys. That is, it will find the smallest power of two that is greater than or equal to `used`. This is also performed in `server_cron`, as a time event and prevents Redis from unnecessarily using memory. If you want to dig deeper in the Redis implementation, here are few interesting functions you can start with: - [`dictCreate`](https://github.com/redis/redis/blob/6.0.0/src/dict.c#L111) - [`dictExpand`](https://github.com/redis/redis/blob/6.0.0/src/dict.c#L147) - [`dictAdd`](https://github.com/redis/redis/blob/6.0.0/src/dict.c#L265) - [`dictFind`](https://github.com/redis/redis/blob/6.0.0/src/dict.c#L476) - [`dictResize`](https://github.com/redis/redis/blob/6.0.0/src/dict.c#L135) - [`dictRehash`](https://github.com/redis/redis/blob/6.0.0/src/dict.c#L188) - [`dictRehashMillisecond`](https://github.com/redis/redis/blob/6.0.0/src/dict.c#L241) ### The SipHash hash function The last thing we need to look at before building our own hash table is the hash function. Redis has been using the SipHash algorithm since version 5.0. Before that it had been using the MurmurHash2 algorithm as of version 2.5. And before that, it used a simple version from <NAME> called [djb2][hash-djb2]. The SipHash algorithm is described in this paper: [SipHash: a fast short-input PRF paper][siphash-paper]. One of the benefits of SipHash is that it offers strong protection against attacks such as [hash flooding][hash-flooding]. The implementation of the SipHash algorithm is quite complicated. The one used by Redis is in the [`siphash.c` file][redis-source-siphash] and a Ruby implementation is provided in [Appendix B][appendix-b]. What is important to note is that Siphash requires a key, usually coming from random bytes, to compute a hash value. This means that unlike md5 or sha1, which always return the same value for the same input, siphash will return the same value, if, and only if, the key is the same. This is essentially a simplified explanation of how the hash flooding protection works. If Redis were to use md5 as its hashing function, I could try to guess what the hash value used to compute the index would be. Let's see that with an example: The md5 hash for the string `a` is the string `0cc175b9c0f1b6a831c399e269772661`: ``` ruby Digest::MD5.hexdigest("a") # => 0cc175b9c0f1b6a831c399e269772661 ``` The result is a 32 character string representing a 128-bit (16 bytes) result. Because most CPUs use 64-bit integers as their largest types, the result we just saw is actually the hex representation of two 64 bit integers. Let's illustrate this with the `pack` and `unpack` method. The string is a hex string, so we need to look at each pair of characters. We call `hex` on each pair, which returns the integer value. For instance `'00'.hex` returns `0`, `'ff'.hex` returns `255`, the maximum value of an 8-bit integer - a byte. We then call `.pack('c16')` which returns a string representing all the bits concatenated together. We use `'c16'` because the result of `.map(&:hex)` is an array of 16 bytes. Finally `.unpack('QQ')` looks at the string of bytes and tries to convert to two 64 bit integers. We use `'QQ'`, which is identical to `'Q2'`, because a string of 16 bytes can be unpacked to two 64-bit integer. One 64-bit integer is composed of 8 bytes - a byte contains 8 bits, so 8 bytes contain 64 bits - so 16 bytes can be unpacked to two 64-bit integers. ``` ruby bytes = "0cc175b9c0f1b6a831c399e269772661".scan(/../).map(&:hex).pack('c16') # => "\f\xC1u\xB9\xC0\xF1\xB6\xA81\xC3\x99\xE2iw&a" bytes.unpack("QQ") # => [12157170054180749580, 7000413967451013937] ``` The previous code was adapted from [this blog post](https://anthonylewis.com/2011/02/09/to-hex-and-back-with-ruby/) A simpler example might help illustrate this: ``` ruby "ffff0000ffff0000ffff0000ffff0000".scan(/../).map(&:hex) => [255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0] [255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0].pack('c16') => "\xFF\xFF\x00\x00\xFF\xFF\x00\x00\xFF\xFF\x00\x00\xFF\xFF\x00\x00" "\xFF\xFF\x00\x00\xFF\xFF\x00\x00\xFF\xFF\x00\x00\xFF\xFF\x00\x00".unpack('QQ') => [281470681808895, 281470681808895] ``` We can play with `pack` and `unpack` a little bit more to confirm that these two 64-bit integers we got are the two elements of the md5 result: ``` ruby [12157170054180749580].pack("Q").unpack("H16") => ["0cc175b9c0f1b6a8"] [7000413967451013937].pack("Q").unpack("H16") => ["31c399e269772661"] ``` `12157170054180749580` represents the first 64 bits of the md5 value, by calling `.pack('Q')` we convert it to a string representing all these bits back to back, and convert it back to a string of 16 hex characters with `.unpack('H16')`. We can confirm that `0cc175b9c0f1b6a` is the first half of `0cc175b9c0f1b6a831c399e269772661` and that `31c399e269772661` is the second half. We can also look at the actual 64 bits with `unpack('B64')` ``` ruby [12157170054180749580].pack('Q').unpack('B64') => ["0000110011000001011101011011100111000000111100011011011010101000"] [7000413967451013937].pack('Q').unpack('B64') => ["0011000111000011100110011110001001101001011101110010011001100001"] ``` Back to our hypothetical use of md5 as a hash function in Redis. Given that we would only use a single integer to apply the modulo to, we could pick either the first one or last one, let's arbitrarily pick the second one, just because. If I sent the command `SET a-key a-value`, the hash value of `a-key` is the 64 bit integer `7000413967451013937`. This knowledge can be used to forge special requests and maximize the chances of collisions, potentially causing performance issues to the hash table. With a keyed algorithm such as Siphash, it's impossible to infer what the hash value would be if the server uses random bytes as the key. We can demonstrate this with Ruby, which also uses Siphash by running `"a".hash` in an `irb` shell, closing and reopening `irb`, the `hash` value will be different. This is because Ruby initializes random bytes at startup that it then uses to compute siphash values. Siphash was added to Redis in [this commit](https://github.com/redis/redis/commit/adeed29a99dcd0efdbfe4dbd5da74e7b01966c67). SipHash returns a 64 bit integer, so we can use the value directly instead of going trough all the steps we had to go through with md5. ## Our own `Dict` class ### `Dict`, `HashTable` & `DictEntry` We previously looked at the main data structures used in the Redis code base to implement a hash table. We will reimplement a simplified version of those, let's start with the two small ones, `DictEntry` & `HashTable`: ``` ruby module BYORedis class DictEntry attr_accessor :next, :value attr_reader :key def initialize(key, value) @key = key @value = value @next = nil end end end ``` _listing 6.10: The DictEntry class_ ``` ruby module Redis class HashTable attr_reader :table, :size, :sizemask attr_accessor :used def initialize(size) @table = size == 0 ? nil : Array.new(size) @size = size @sizemask = size == 0 ? 0 : size - 1 @used = 0 end def empty? @size == 0 end def each return unless @table @table.each end end end ``` _listing 6.11: The HashTable class_ `@table` in `HashTable` will contain instances of `DictEntry`, which is our linked list implementation to handle collisions. We could have defined `DictEntry` as a `Struct`, but the explicit `class` has one small benefit, it allows us to not define a setter for the `key` attribute. As already discussed, because Ruby is Ruby, where most things are mutable, it does not mean that a `key` attribute will always be the same, but at least it prevents reassignment. The value can still be changed by updating the value in place: ``` ruby dict_entry = BYORedis::DictEntry.new("a-key", "a-value") # => nil dict_entry # => #<BYORedis::DictEntry:0x00007fd577a17c60 @key="a-key", @value="a-value", @next=nil> dict_entry.key.gsub!("a", "A") # => "A-key" dict_entry # => #<BYORedis::DictEntry:0x00007fd577a17c60 @key="A-key", @value="a-value", @next=nil> dict_entry.key # => "A-key" ``` Let's now create the main class, `Dict`: ``` ruby require_relative './siphash' require_relative './dict_entry' require_relative './hash_table' module BYORedis class Dict INITIAL_SIZE = 4 MAX_SIZE = 2**63 attr_reader :hash_tables def initialize @hash_tables = [ HashTable.new(0), HashTable.new(0) ] @rehashidx = -1 end # ... end end ``` _listing 6.12: The Dict class_ Our `Dict` class does not require any arguments, it is initialized with two empty hash tables, and a rehash index set to `-1`, indicating that it is not in a rehashing state. The rehashing index is used to keep track of the progress throughout rehashing. Its value will change from `0` to `@hash_tables[0].size - 1` as we rehash the table, and reset to `-1` when completed. The first method we need to add to the `Dict` class is `add`, it will be used to add an element to a dictionary. This is needed for the `SET` command. This method always expects the called to check that the key is not already present and will fail if it finds a matching key. ``` ruby # dict.rb module BYORedis class Dict # ... def add(key, value) index = key_index(key) # Only happens if we didn't check the presence before calling this method return nil if index == -1 rehash_step if rehashing? hash_table = rehashing? ? rehashing_table : main_table entry = hash_table.table[index] entry = entry.next while entry && entry.key != key if entry.nil? entry = DictEntry.new(key, value) entry.next = hash_table.table[index] hash_table.table[index] = entry hash_table.used += 1 else raise "Unexpectedly found an entry with same key when trying to add #{ key } / #{ value }" end end alias []= add end end ``` _listing 6.13: The add method in the Dict class_ The method is very similar to the pseudo code we looked at earlier in `add_or_update_key_value_pair`. We first obtain the index for the key, aka the location of the bucket the key should go into. We then perform a rehash step if we're in rehashing state. We select which table the key will end up in depending on whether or not we are in rehashing state. If we are, the key will be added to the rehashing table, otherwise it is added to the main table. The next step is to inspect the bucket at the `index` position, if it is not empty we look through all the items in the bucket to check if one of the entries has the same key. If we find an entry with the same key, we don't need to create a new entry, we can just update the existing entry with the new value. The number of elements in the dictionary does not change. On the other hand, if we didn't find an entry with the same key, we need to create a new entry for the new key/value pair. First, we instantiate `DictEntry` with `key` & `value`, then we need to add it to the linked list. There are essentially two valid options for us here, either append the element to the list or prepend it. Prepending to a linked list is a constant time operation O(1), whereas appending is proportional to the size of list, it is an O(n) operation. Let's illustrate with an example, we'll start by creating a list with three elements ``` ruby entry1 = BYORedis::DictEntry.new(1, 'value-1') # => nil entry2 = BYORedis::DictEntry.new(2, 'value-2') # => nil entry3 = BYORedis::DictEntry.new(3, 'value-3') # => nil entry1.next = entry2 # => nil entry2.next = entry3 # => nil entry1 # => #<BYORedis::DictEntry:0x00007fd57403dbc0 @key=1, @value="value-1", @next=#<BYORedis::DictEntry:0x00007fd577a3eb58 @key=2, @value="value-2", @next=#<BYORedis::DictEntry:0x00007fd5779c3d90 @key=3, @value="value-3", @next=nil>>> ``` Now that the list is created, let's assume we only have a single variable for the list, `list`, which is equal to `entry1` in the previous example, prepending a new node is done as follows: ``` ruby new_entry = BYORedis::DictEntry.new(99, 'value-99') # => nil new_entry.next = list # => nil list = new_entry # => nil list # => #<BYORedis::DictEntry:0x00007fd5779b8878 @key=99, @value="value-99", @next=#<BYORedis::DictEntry:0x00007fd57403dbc0 @key=1, @value="value-1", @next=#<BYORedis::DictEntry:0x00007fd577a3eb58 @key=2, @value="value-2", @next=#<BYORedis::DictEntry:0x00007fd5779c3d90 @key=3, @value="value-3", @next=nil>>>> ``` This process can be repeated regardless of the size of the list. On the other hand, to append an element, we first need to find the last element, here is how we do it: ``` ruby new_entry = BYORedis::DictEntry.new(99, 'value-99') # => nil current_entry = list # => nil current_entry = current_entry.next while current_entry.next != nil # => nil current_entry.next = new_entry # => nil list # => #<BYORedis::DictEntry:0x00007fd57403dbc0 @key=1, @value="value-1", @next=#<BYORedis::DictEntry:0x00007fd577a3eb58 @key=2, @value="value-2", @next=#<BYORedis::DictEntry:0x00007fd5779c3d90 @key=3, @value="value-3", @next=#<BYORedis::DictEntry:0x00007fd5779b8878 ...>>>> ``` The third line iterates through all the elements in the list. The more elements, the longer it'll take. Some linked list implementations work around this issue by always maintaining a pointer to the last element. Back to our collision handling, even though appending has a worst time complexity compared to prepending, O(n) vs O(1), given that we need to iterate through all the items in the list anyway, to make sure the key does not already exist, we could have kept a variable pointing at the last element. Redis chooses the prepend option with the assumption that it might be common for recently added items to be accessed more frequently. If this assumption holds true, future lookups would find the key/value pair early in the list, instead of having to iterate through the end of the list. The lines `entry.next = hash_table.table[index]` & `hash_table.table[index] = entry` insert the new entry as the head of the list. The first one makes the new entry point at the old head of the list. If it was null, then the `next` value will still be null and the new entry will be the only element in the list. If it wasn't null, then `next` in the new entry now points at the old head, which itself, points at the rest of the list. We're not losing anything, great! The second line is necessary so that the head of list in the bucket points at the new entry. The last line, `hash_table.used += 1`, increments the counter of how many items are in the dictionary. Finally, we use the Ruby `alias` keyword to create an alias for `add` to `[]=`. This allows us to use a `Dict` instance similarly to how we use a Ruby `Hash`: ``` ruby dict = Dict.new # The following two are equivalent, the same method is called, Dict#add: dict.set(1, 2) dict[1] = 2 ``` We used a few private methods that we should now look more closely at: `main_table`, `rehashing_table` & `key_index` ``` ruby # dict.rb module BYORedis class Dict # ... private def main_table @hash_tables[0] end def rehashing_table @hash_tables[1] end def key_index(key) expand_if_needed hash = SipHash.digest(RANDOM_BYTES, key) index = nil iterate_through_hash_tables_unless_rehashing do |hash_table| index = hash & hash_table.sizemask entry = hash_table.table[index] while entry # The key is already present in the hash so there's no valid index where to add it if entry.key == key return -1 else entry = entry.next end end end index end # In the Redis codebase, they extensively use the following pattern: # for (table = 0; table <= 1; table++) { # ... # if (!dictIsRehashing(d)) break; # } # This is common for many operations, such as finding or deleting an item in the dict, # we first need to look at the main table, the first table, but we haven't found in the # first one, we should look in the rehashing table, the second one, but only if we're in # the process of rehashing. # Taking advantage of Ruby blocks, we can write this helper method instead def iterate_through_hash_tables_unless_rehashing @hash_tables.each do |hash_table| yield hash_table break unless rehashing? end end end end ``` _listing 6.14: helper methods in the Dict class_ `main_table` and `rehashing_table` are used as aliases of `@hash_tables[0]` and `@hash_tables[1]`. `key_index` is used to return the index representing the location of the bucket for the given key. It first calls `expand_if_needed`, which we'll explore in the next section about rehashing. Once the dictionary has been resized if needed, it computes the hash value using the `SipHash` class. The code for the siphash algorithm is available in [Appendix B][appendix-b]. Once we obtained the hash value, we need to convert it to an index within the boundaries of the backing array, with the modulo operation, or as we discussed earlier, the bitwise AND operation. Before doing that, we need to take into account which table the bucket should go into, if we're not in a rehashing state, it should go in the main table, if we are, it should go to the rehashing table. This process of first inspecting the main table, and the rehashing table, only if we're in rehashing state is so common that we added a helper method for that, `iterate_through_hash_tables_unless_rehashing`. This method replaces the common pattern in the Redis C codebase using a `for` loop and a conditional `break` statement at the end of the first iteration. We instead leverage the Ruby block syntax to always `yield` back the main table to the caller, and only `yield` the rehashing table if we're in a rehashing state. The implication for `key_index` is that if we're in a rehashing state, we'll first find the index in the first table, but `iterate_through_hash_tables_unless_rehashing` will `yield` a second time and `index` will end up being an index for the rehashing table. `key_index` is used to find the index of the bucket where a new entry should be added and it therefore does not make sense to return a value if an entry already exists with the same key. In such cases we'll need to update the existing entry, which we'll cover soon. This is necessary because of the rehashing process, which is explained below as well. In short, during rehashing, keys will be present in two different tables, the main one and the rehashing, and clearly separating the process of adding a new entry and updating an existing one allows to guarantees keys are unique. The `digest` method in the `SipHash` class requires a 16-byte key composed of random bytes. Redis does generates these with the [`getRandomBytes` function][redis-source-get-random-bytes], which attempts to use `/dev/urandom/` and defaults to a weaker seed based on the current time and the pid of the server if `/dev/urandom` is not accessible. Ruby's `SecureRandom` module provides a `random_bytes` method which uses `/dev/urandom` under the hood, so let's use it: ``` ruby # server.rb require 'socket' require 'logger' require 'strscan' require 'securerandom' LOG_LEVEL = ENV['DEBUG'] ? Logger::DEBUG : Logger::INFO RANDOM_BYTES = SecureRandom.bytes(16) # ... ``` _listing 6.15: Initialization of the random byte in server.rb_ Now that we implemented the `set` method, and its alias, `[]=`, we need to add the `get` method, which will be used by the `GET` command, to retrieve an element from a dictionary based on its key. ``` ruby module BYORedis class Dict def used main_table.used + rehashing_table.used end def get_entry(key) return if main_table.used == 0 && rehashing_table.used == 0 rehash_step if rehashing? hash = SipHash.digest(RANDOM_BYTES, key) iterate_through_hash_tables_unless_rehashing do |hash_table| index = hash & hash_table.sizemask entry = hash_table.table[index] while entry return entry if entry.key == key entry = entry.next end end nil end def get(key) get_entry(key)&.value end alias [] get def include?(key) !get_entry(key).nil? end def each return if main_table.used == 0 && rehashing_table.used == 0 start_index = rehashing? ? @rehashidx : 0 main_table.table[start_index..-1].each do |bucket| next if bucket.nil? until bucket.nil? yield bucket.key, bucket.value bucket = bucket.next end end return unless rehashing? rehashing_table.each do |bucket| next if bucket.nil? until bucket.nil? yield bucket.key, bucket.value bucket = bucket.next end end end end end ``` _listing 6.16: get, include? and each method in Dict.rb_ The `get` method is a small wrapper around the lower level `get_entry` method. This lower level method is necessary to support `nil` as values. Without it, calling `dict.get(key)` would return `nil` if the key is not present, but also if it is present, but the value is `nil`. With `get_entry`, we will only receive `nil` when the key is not present, and will receive an instance of `DictEntry` otherwise. `get_entry` starts with an early `return` statement if both tables are empty. If that's the case, there's no need to continue, we know the key is not present in the table. The next step is similar to `add`, we perform a single rehash step if we're in a rehashing state. The approach allows Redis to incrementally work its way through the rehashing process, without affecting too much the performance of other operations. A single rehashing step does not require a lot of work, and will have a negligible impact on the performance of get, but it has the important benefits of advancing the rehashing process. Once again, we follow a pattern similar to the pseudo code `lookup_key` from earlier in the chapter, we start by computing the hash value of the key. Once we have the hash value, we first need to look at the main table, and if we're in a rehashing state, at the second table as well. We do this with the same helper method as previously, `iterate_through_hash_tables_unless_rehashing`. `hash & hash_table.sizemask` returns the location of the bucket for the key. There might be more than one item in the bucket, because of potential collisions, so we need to iterate through all of them and compare their key with the `key` argument. We do this with the `while` loop. If we do find a matching key, we abort early and return the value associated with that key. If we inspected all the element in the main table bucket, and potentially in the rehashing table bucket, and did not find any matches, we return nil. The key is not in the hash table. Similarly to what we did with `add` and `[]=`, we alias `get` to `[]`, which allows us to use the same syntax we use for `Hash` instances: ``` ruby dict = Dict.new # The following are equivalent, the same method is called: dict.get(1) dict[1] ``` There is a use case where we only care about the presence of a key in a dictionary, but not about the value, this is what the `include?` method does. We do not need to reimplement the logic, we reuse the `get` method, discard its value and return a boolean instead. Now that we have the `get_entry` method, we can define the `set` method which performs the "add or update" operation, and update the `[]=` alias to point at `set` and not at `add` anymore. ``` ruby module BYORedis class Dict # ... def set(key, value) entry = get_entry(key) if entry entry.value = value else add(key, value) end end alias []= set # ... end end ``` _listing 6.17: The `set` method in Dict.rb aliased to `[]=`_ Finally we add the `each` method, which will `yield` all the key/value pairs in the hash table. This time we do not use the `iterate_through_hash_tables_unless_rehashing`. This is because we're using a small optimization technique to avoid iterating over buckets we know are empty. If we are in rehashing state, then we know that all buckets between `0` and the value in `@rehashidx` excluded have been rehashed and the values are empty. In a table of size `16`, if `@rehashidx` is set to `5`, it means that the buckets at index `0`, `1`, `2`, `3` & `4` have been migrated and we don't need to inspect them. For the rehashing table, we iterate through the backing array with the `each` method on `HashTable`, which itself delegates `each` to its `Array` instance. There is no need to yield back empty buckets, so we continue to the next bucket if we find an empty one. For each non empty bucket, we iterate through the linked list of entries and `yield` all of them. ### Resizing and rehashing When `Dict` is initialized, it creates two instances of `HashTable`, each with an empty array. We need to implement the rehashing mechanism to allow the tables to grow and shrink as needed. The `add` method we discussed in the previous section starts by calling `expand_if_needed`: ``` ruby # dict.rb module BYORedis class Dict INITIAL_SIZE = 4 # ... def expand_if_needed return if rehashing? if main_table.empty? expand(INITIAL_SIZE) elsif main_table.used >= main_table.size expand(main_table.used * 2) end end # ... end end ``` _listing 6.18: expand_if_needed in the Dict class_ If we are already in the process of rehashing the dict, then we can abort early, the process will continue incrementally, there's nothing else we should do until rehashing is over. If the table is empty we call `expand` with `INITIAL_SIZE`, which is set to `4`, otherwise we call it with a capacity set to twice the current size of the dictionary. Note that the `used` member can be greater than the `size` member. `size` determines the size of the array in the hash table, in other words how many buckets are in the table, and each bucket can contain more than one value because it uses a linked list to store elements. This means that we might increase by more than twice the current size, since we rely on the number of items in the dict, not the current size, to determine the new size. Let's now take a look at the expand method: ``` ruby # dict.rb def expand(size) return if rehashing? || main_table.used > size real_size = next_power(size) return if real_size == main_table.size new_hash_table = HashTable.new(real_size) # Is this the first initialization? If so it's not really a rehashing # we just set the first hash table so that it can accept keys. if main_table.table.nil? @hash_tables[0] = new_hash_table else @hash_tables[1] = new_hash_table @rehashidx = 0 end end def next_power(size) # Ruby has practically no limit to how big an integer can be, because under the hood the # Integer class allocates the necessary resources to go beyond what could fit in a 64 bit # integer. # That being said, let's still copy what Redis does, since it makes sense to have an # explicit limit about how big our Dicts can get i = INITIAL_SIZE return MAX_SIZE if size >= MAX_SIZE loop do return i if i >= size i *= 2 end end def rehashing? @rehashidx != -1 end ``` _listing 6.19: expand, next_power and rehashing? methods in the Dict class_ Similarly to `resize`, if we're already in the process of rehashing, we can abort early. We also abort early if the number of items in the array is greater than the new size. In this case, there's no point in resizing the table, it would be too small. We use the `next_power` method to find the next power of two that is greater or equal to the new size. This method is used to maintain the size of the array as of power of two to leverage the bitwise AND operation to compute a modulo. We then perform another sanity check, if the "real size", the power of two, is equal to the current size, then there's no point in going through a rehashing process, the table is already at the desired size. Now that we performed all the checks, we create a new hash table of the desired size and make it the rehashing table by assigning it to `@hash_tables[1]`. We do have to consider the case where this is the first call to `expand`, in which case both tables are empty, and there's nothing to rehash so we directly assign the newly created hash table to the main table, `@hash_tables[0]`. If there are elements to rehash, we flag the dict as being in a rehashing state by setting `@rehashidx` to `0`. This instance variable acts as a pointer to the next element that should be rehashed in the main table. By being different than `-1`, the dict is now considered in rehashing state. This is what the `rehashing?` method does. In the case where there are elements to rehash, the `expand` method does not actually rehash any of them. It only prepares the dictionary for rehashing. The actual rehashing is performed in two different places. Many operations, such as set and get, will perform a single rehashing step before performing the rest of the operation. The other place where rehashing happens is through the `server_cron` time event we discussed in [Chapter 3][chapter-3]. ``` ruby # dict.rb def rehash_step rehash(1) end def rehash(n) empty_visits = n * 10 return 0 unless rehashing? while n > 0 && main_table.used != 0 n -= 1 entry = nil while main_table.table[@rehashidx].nil? @rehashidx += 1 empty_visits -= 1 return 1 if empty_visits == 0 end entry = main_table.table[@rehashidx] while entry next_entry = entry.next idx = SipHash.digest(RANDOM_BYTES, entry.key) & rehashing_table.sizemask entry.next = rehashing_table.table[idx] rehashing_table.table[idx] = entry main_table.used -= 1 rehashing_table.used += 1 entry = next_entry end main_table.table[@rehashidx] = nil @rehashidx += 1 end # Check if we already rehashed the whole table if main_table.used == 0 @hash_tables[0] = rehashing_table @hash_tables[1] = HashTable.new(0) @rehashidx = -1 0 else # There's more to rehash 1 end end ``` _listing 6.20: rehashing related methods in the Dict class_ `rehash_step` calls `rehash` with the parameter 1. The parameter to `rehash` dictates how many items it will rehash, that is, move from the main table to the rehashing one. Let's look at the method one line at a time. We start by initializing the `empty_visits` variables to `n * 10`. `n`, the method parameter is the number of elements we want to move to the rehashing table. Because of the nature of a hash table, when iterating through the buckets, from the one at index 0 until the one at index `size - 1`, we don't know how many empty buckets we'll find. In order to prevent any potential slowness in the rehashing process, Redis uses an upper bound for the number of empty visits. This is especially important when reducing the size of a hash table, which we'll explore next. In this case the table we're rehashing might be very scarcely populated and there might be many consecutive empty buckets. By using `empty_visits`, we ensure that the rehashing step has a known upper bound. The next step is a sanity check, if we are not rehashing, we should exit right away, there's nothing else to do. Note that we're using the same semantics as Redis here, a return value of 0 indicates that all elements are rehashed, 1 indicates that there are more elements to rehash. The `while` loop is the main piece of the method, it iterates as long a `n` is greater than 0 and as long as there are items left in the main table. The second part of the condition is a quick shortcut we attempt to take at the end of the rehashing process. After rehashing the last element in the main table, there might still be a few extra empty buckets in the array, but since we know the table does not have any more elements left by looking at the `used` variable, we stop instead of iterating through the last empty buckets. The first step of the loop is to decrement `n`, this is a very important part of the loop that dictates the number of iterations. We also initialize an `entry` variable that will be used to iterate through the entries of a bucket. `@rehashidx` is initialized at 0 when the rehashing process starts, so we use it as the index to look through the buckets in the main table. As long as we find empty buckets, we increment the `empty_visits` variable and increment `@rehashidx` to keep moving along in the main table. If `empty_visits` reaches 0, we stop the rehashing process, we're already spent too much time iterating through empty buckets. Note that the next call to rehash will be able to continue where we left off since it will use `@rehashidx`. This inner `while` loop will stop as soon as we encounter a non empty bucket, and we set `entry` to the first entry of the bucket when that happens. As we already established, we might be dealing with more than one entries, so we use another inner `while` loop to iterate through all the entries in the linked list. For each of these entries, we first store the following entry in the `next_entry` variable and then compute the index of the entry in the rehashing table. The next few lines perform the actual move of the entry from one table to the other, similarly to how we inserted an entry in the `add` method earlier. We make the `next` attribute of the `entry` variable point at the bucket in the rehashing table with `entry.next = rehashing_table.table[idx]`. This might either set the value to `nil` if the bucket in the rehashing table was empty, or would otherwise be the head of the list if it was not empty. `rehashing_table.table[idx] = entry` is taking care of making the bucket in the rehashing table point at the `entry` variable, making it the new head of the list. We then decrement `used` in the main table and increment it in the rehashing table. Finally, in order to keep iterating through the entries in the bucket from the main table, we set `entry` to `next_entry`, which will repeat these steps with the next entry in the list. Once we've moved all the entries in the bucket, one rehashing step is completed, we explicitly empty the bucket with `main_table.table[@rehashidx] = nil` and increment `@rehashidx` so that the next iteration of the outer `while` loop continues iterating through the main table. Once `n` rehashing steps have been performed, we check a few final details. If `used` reached 0 in the main table, we're done with the rehashing process, the main table is empty. We set `@hash_tables[0]` to the new rehashing table, effectively promoting it from rehashing table to main table, and reset the rehashing table to an empty table. Resetting `@rehashidx` to `-1` marks the end of the rehashing process. We return 1 otherwise, indicating that the rehashing process is not done. The use of `rehash_step` makes sure that rehashing keeps happening, one step at a time, but large tables might require many rehash steps, up to millions of steps. Redis uses the `server_cron` time event to perform rehashing in larger steps, in order to speed up the rehashing process. This is especially useful if the server is idle for a while. If Redis would only perform rehashing steps when receiving commands, it would not make any progress while idle. This approach prevents this and takes advantage of the idle time to do so cleanup work. Let's add a call to a new method, `databases_cron` in `server_cron` in `server.rb`: ``` ruby # server.rb def server_cron # ... databases_cron 1000 / DEFAULT_FREQUENCY end def databases_cron @data_store.resize if ht_needs_resize(@data_store) @expires.resize if ht_needs_resize(@expires) @data_store.rehash_milliseconds(1) @expires.rehash_milliseconds(1) end def slots(dict) dict.hash_tables[0].size + dict.hash_tables[1].size end def size(dict) dict.hash_tables[0].used + dict.hash_tables[1].used end def ht_needs_resize(dict) size = slots(dict) used = size(dict) size > Dict::INITIAL_SIZE && ((used * 100) / size < HASHTABLE_MIN_FILL) end ``` _listing 6.21: databases_cron method in the Server class_ `databases_cron` performs two operations on the two dictionaries in the `Server` class, `@data_store`, that holds all the key/value pairs, and `@expires` which keeps track of the keys with TTLs. For each of these dictionaries, if first calls `resize`, which we've explored in the previous section, only if it thinks the dictionary needs to be resized. A dictionary needs to be resized if the number of items in the dictionary is less than 10% of the size of the dictionary. Beside the `EX` & `PX` options, we have not yet implemented commands to delete keys, such as the `DEL` command, but we will soon. Once the `DEL` command is implemented, key/value pairs can be removed from a dictionary, meaning that a dictionary that grew to a given size might become too big at some point. Let's look at an example: ``` ruby dict = BYORedis::Dict.new dict.hash_tables[0].size # => 0 dict.hash_tables[1].size # => 0 dict.add("1", "2") # => 1 dict.hash_tables[0].size # => 4 # We're calling to_s because Dict only works with strings and i is an Integer 100.times { |i| dict.add(i.to_s, i.to_s) } # => 100 dict.hash_tables[0].size # => 128 ``` In the previous examples, the main table grew to a size of 128, if we were to delete all items but one, we would end up with only one non empty bucket, while the other 127 would be empty. With small values like those it might not seem like a big difference, but as we saw earlier, Redis' dict can grow to billions of keys, so efficiently using memory is important. If the dictionaries need resizing, calling `resize` will find a good size for the dictionary and start the rehashing process. The next step is to call `rehash_milliseconds`. We've already explained why it's important for Redis to maintain an upper bound to all the operations that blocks other clients in the queue. By calling `rehash_milliseconds(1)`, Redis tries to do as much rehashing as possible and stops once one millisecond has elapsed. This means that in the most pessimistic scenario possible, a client would send a command right after Redis enters the `rehash_milliseconds(1)` call, effectively blocking this client for at least one millisecond. This behavior is considered acceptable by Redis, but it can be disabled through the `activerehashing` config value. We have not yet implemented any form of configuration so we will assume that all clients of our server are ok with this behavior. ``` ruby # dict.rb def rehash_milliseconds(millis) start = Time.now.to_f * 1000 rehashes = 0 while rehash(100) == 1 rehashes += 100 time_elapsed = Time.now.to_f * 1000 - start break if time_elapsed > millis end rehashes end def resize return if rehashing? minimal = main_table.used minimal = INITIAL_SIZE if minimal < INITIAL_SIZE expand(minimal) end ``` _listing 6.22: rehash_milliseconds and resize methods in the Dict class_ ### No more `Hash` & `{}` Equipped with our `Dict` class, we can now remove all instances of `Hash` and replace them with `Dict`. We lose a little bit syntax wise, we cannot use the `Hash` literal syntax with `{ key: value }`, but overall, things are not that different: ``` ruby # server.rb module BYORedis class Server COMMANDS = Dict.new COMMANDS.set('command', CommandCommand) COMMANDS.set('del', DelCommand) COMMANDS.set('get', GetCommand) COMMANDS.set('set', SetCommand) COMMANDS.set('ttl', TtlCommand) COMMANDS.set('pttl', PttlCommand) # ... def initialize @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @clients = [] @data_store = Dict.new @expires = Dict.new # ... end # ... end end ``` _listing 6.23: Replacing usages of Hash with Dict in the Server class_ The `SetCommand` class was using a `Hash` to store the configuration values of the possible options. We replace it similarly to what we did for the `COMMANDS` constant in `server.rb`: ``` ruby # set_command.rb module BYORedis class SetCommand OPTIONS = Dict.new OPTIONS.set( 'ex', CommandOptionWithValue.new( 'expire', ->(value) { validate_integer(value) * 1000 }, ) ) OPTIONS.set( 'px', CommandOptionWithValue.new( 'expire', ->(value) { validate_integer(value) }, ) ) OPTIONS.set( 'xx', CommandOption.new('presence') ) OPTIONS.set( 'nx', CommandOption.new('presence') ) OPTIONS.set( 'keepttl', CommandOption.new('expire') ) # ... def initialize(data_store, expires, args) # ... @options = Dict.new end # ... end end ``` _listing 6.24: Replacing usages of Hash with Dict in the SetCommand class_ **Changing `@clients` to a Dict** Up until now the `@clients` in the `Server` class was an Array, which worked fine for small list of clients but would be problematic for largest lists of clients. When we process the results of `IO.select`, we use the returned sockets to find the matching clients within the connected clients. This is an O(n) operation with an array. We can use our new `Dict` class to turn it into an O(1) operation. It's worth nothing that the performance will be worse for a small number of clients given the overhead of the `Dict` class, but the performance won't change regardless of the number of connected clients. Each socket has a `fileno` which returns the numeric file descriptor of the socket. This number will be different for each socket and we can therefore use it as a key to identify sockets in the `Dict`. ``` ruby module BYORedis class Server # ... Client = Struct.new(:socket, :buffer, :blocked_state) do attr_reader :id def initialize(socket) @id = socket.fileno.to_s self.socket = socket self.buffer = '' end end # ... def initialize @logger = Logger.new(STDOUT) @logger.level = LOG_LEVEL @clients = Dict.new # ... end # ... def client_sockets sockets = [] @clients.each { |_, client| sockets << client.socket } sockets end # ... def process_poll_events(sockets) sockets.each do |socket| begin if socket.is_a?(TCPServer) socket = @server.accept @clients[socket.fileno.to_s] = Client.new(socket) elsif socket.is_a?(TCPSocket) client = @clients[socket.fileno.to_s] client_command_with_args = socket.read_nonblock(1024, exception: false) if client_command_with_args.nil? @clients.delete(socket.fileno.to_s) socket.close elsif client_command_with_args == :wait_readable # There's nothing to read from the client, we don't have to do anything next elsif client_command_with_args.empty? @logger.debug "Empty request received from #{ socket }" else # ... end else raise "Unknown socket type: #{ socket }" end rescue Errno::ECONNRESET @clients.delete(socket.fileno.to_s) rescue IncompleteCommand # Not clearing the buffer or anything next rescue ProtocolError => e socket.write e.serialize socket.close @clients.delete(socket.fileno.to_s) end end end # ... end end ``` ### Adding the `DEL` command As mentioned earlier in this chapter, the only option we currently have for keys to be deleted is to set them with a TTL with the `EX` & `PX` options. It will be more convenient to manually test the behavior of our new `Dict` class with a more explicit option. The [`DEL`][redis-doc-del] command is very useful in that aspect, it accepts one or more keys as its arguments and attempts to delete them. It returns an integer representing the number of keys that were deleted: ``` ruby module BYORedis class DelCommand def initialize(data_store, expires, args) @data_store = data_store @expires = expires @args = args end def call if @args.empty? RESPError.new("ERR wrong number of arguments for 'GET' command") else keys = @args deleted_count = 0 keys.each do |key| entry = @data_store.delete(key) if entry != nil # If there was a key, then we need to delete its TTL if it had one: @expires.delete(key) deleted_count += 1 end end RESPInteger.new(deleted_count) end end def self.describe [ 'del', -2, # arity # command flags [ RESPSimpleString.new('write') ], 1, # position of first key in argument list -1, # position of last key in argument list 1, # step count for locating repeating keys # acl categories: https://github.com/antirez/redis/blob/6.0.0/src/server.c#L161-L166 [ '@keyspace', '@write', '@slow' ].map { |s| RESPSimpleString.new(s) }, ] end end end ``` _listing 6.25: The new DelCommand class_ The `DelCommand` class implements the behavior of the command, as well as defining the data for the `COMMAND` command, but it mainly relies on a non existing method on the `Dict` class, `delete`. Let's add it: ``` ruby # dict.rb def delete(key) return if main_table.used == 0 && rehashing_table.used == 0 rehash_step if rehashing? hash_key = SipHash.digest(RANDOM_BYTES, key) iterate_through_hash_tables_unless_rehashing do |hash_table| index = hash_key & hash_table.sizemask entry = hash_table.table[index] previous_entry = nil while entry if entry.key == key if previous_entry previous_entry.next = entry.next else hash_table.table[index] = entry.next end hash_table.used -= 1 return entry end previous_entry = entry entry = entry.next end end end ``` _listing 6.26: The delete method in the Dict class_ The logic in `delete` is similar to the `add` method. We start with a shortcut we've already seen, if the table is empty, there's no need to go any further, we can stop right there. We perform a rehashing step if needed, to keep the rehashing process moving and then we get the hash value for the key. The key we're attempting to delete might be in the main table or the rehashing table, so we use our helper method `iterate_through_hash_tables_unless_rehashing` to help with this. For each hash table we look at, we obtain the index and inspect the bucket at that location. If the bucket is empty, then there's nothing else to do, the key is not present in this table. If the bucket is not empty, we need to iterate through all the entries and compare the keys of these entries with the method argument. If there's a match we found the entry we need to delete, this is what the `while` loop is doing. If there is a match, the `if entry.key == key` condition, we need to handle two cases, whether or not the entry we want to delete is the first entry in the bucket. We use the `previous_entry` variable to keep track of the previous entry as we iterate through the entry list in the bucket. Once we find a match, this allows us to know if the entry we're trying to delete was the first one or not, if `previous_entry` is `nil`, then it is the first one. In this case the deleting process is to make the head of the bucket, `hash_table.table[index]`, point at the next element in the list. If `entry` was the only element, its `next` value would be `nil`, and the bucket would now be empty. If `entry` was the head of list with more than one element, then the bucket now starts with what was the second element in the list, the entry which `next` is to in `entry`. If `previous_entry` is not `nil`, then `entry` is not at the head of the list and the deletion process requires us to change `previous_entry.next` to now skip over `entry` since we want to remove it from the list, and point to the entry in `entry.next`. This entry might be nil or not, and it does not matter to us. If it was `nil`, then it means that `entry` was the last element in the list, and by changing `previous_entry.next` to `nil`, `previous_entry` is now the last entry. If it wasn't `nil`, then `previous_entry` now points to the element `entry` is pointing to, and no entries point at `entry` anymore, it's now floating on its own and is not part of the list anymore. In a language with manual memory management, such as C, we would also need to explicitly free the memory, but we're in Ruby, so we'll let the garbage collector do its job. Whether or not the entry was the first one in the bucket, it's now deleted, we decrement the `used` counter and return. ## Conclusion In this chapter we dived into hash tables, how Redis uses them and how to implement one in Ruby, in order to replace the `Hash` class. In the [next Chapter][chapter-7] we will add new commands to handle a new data type, Lists. See you there. ## Appendix A: Array from scratch in Ruby This implementation use the fiddle gem which is packaged alongside Ruby. Fiddle provides an interface to libffi, which is a C library that allows code in one language to call code in another language. Here we use the `Fiddle::Pointer` class with the `malloc` method to explicitly allocate memory. This implementation only works with strings and does not support resizing. `PTR_SIZE` is constant set to `::Fiddle::SIZEOF_LONG`, which is 8 on most modern machines. This size is in bytes, and since a byte holds 8 bits, we can see that a long is 64 bits here. When initialized, we call `Fiddle::Pointer.malloc(PTR_SIZE * size)` to allocate enough memory to store n pointers, where n is the given size. Adding an element, beside the sanity checks around the size and the type requires the following step: - We obtain a pointer to the given string with `Pointer.to_ptr(str)` - We compute the location of the next element in the array and save it in `offset`. If the array is empty it's gonna be `0`, if there's one element, it'll be `8`, etc ... - We use the `[]=` notation of the `Pointer` class to write the 8 bytes representing the address of the given string, which is what the value of `ptr.ref`. This is similar to the `&` operator used to return the address of variable. - We increment the size by one. The `get` method is similar, we transform the index to an offset by multiplying it by the size of a pointer, 8. And we read a whole pointer, 8 bytes, from there, with the `[]` method of the `Pointer` class. We use `.unpack('Q')` on the result because the `[]` method of `Pointer` returns a string of 8 bytes, representing the 64-bit integer holding the address of the string stored in the array. But we need the actual integer value, to pass to `Pointer.new`, and that's what `unpack('Q')` does, it "unpacks" the string to a `long long`, a 64-bit integer, and returns that as an array, so we grab the first element with `[0]`. `to_s` on `Pointer` is smart enough to read all the bytes until it finds a null byte and return the result as a Ruby string, great, so we don't have to deal with that! ``` ruby require 'fiddle' class BYOArray < BasicObject PTR_SIZE = ::Fiddle::SIZEOF_LONG def initialize(max_size) @max_size = max_size @current_size = 0 @beginning_address = ::Fiddle::Pointer.malloc(PTR_SIZE * max_size) end def add(str) ::Kernel.raise 'Array is full' if @current_size == @max_size ::Kernel.raise 'Expected a string' unless str.is_a?(::String) ptr = ::Fiddle::Pointer.to_ptr(str) offset = @current_size * PTR_SIZE # 0 at first, then 8, 16, etc ... @beginning_address[offset, PTR_SIZE] = ptr.ref @current_size += 1 self end def get(i) return nil if i < 0 || i >= @current_size address = @beginning_address[i * PTR_SIZE, PTR_SIZE].unpack('Q')[0] ::Fiddle::Pointer.new(address).to_s end def to_s "Size: #{ @current_size }" end end ``` _listing 6.27: A Ruby implementation of an Array structure_ ``` ruby ary = BYOArray.new(2) ::Kernel.puts ary.add("foo") ::Kernel.puts ary.add("bar") ::Kernel.puts ary.get(0) ::Kernel.puts ary.get(1) ::Kernel.puts ary.get(2) ::Kernel.puts ary.add("bar") ``` _Note that this is a very very rough sketch of how `Fiddle` can be used to allocate memory from Ruby in an array-like manner. Among probably other issues, a huge problem with this implementation is that the memory allocated in the constructor is never de-allocated. `Fiddle` exposes a `free` method, but since Ruby objects are deallocated by the Garbage Collector, it is non-trivial to figure out how and when to call `free`. The `ObjectSpace` module has a `define_finalizer` method which can be used to define a proc that will be called when the object is garbage collected. This [StackOverflow answer][stack-overflow-object-finalizer] shows an example of how it can be used:_ ```ruby class MyClass def initialize ObjectSpace.define_finalizer( self, self.class.method(:finalize).to_proc ) end def MyClass.finalize(id) puts "Object #{id} dying at #{Time.new}" end end ``` _listing 6.28: Using define\_finalizer to register a callback on object destruction_ ## Appendix B: A Ruby implementation of SipHash The following is adapted from the [`siphash` gem][siphash-gem]. The gem implements the 2-4 version, and the version below implements the same one Redis uses, 1-2. These two numbers, named `c` & `d` in the [siphash paper][siphash-paper] represent the number of compression steps and finalization steps. Variants with higher number of compression and finalization steps are supposed to provide a higher security at the cost of being slower. The following is a quote from the Redis implementation: > We use SipHash 1-2. This is not believed to be as strong as the suggested 2-4 variant, but AFAIK there are not trivial attacks against this reduced-rounds version, and it runs at the same speed as Murmurhash2 that we used previously, why the 2-4 variant slowed down Redis by a 4% figure more or less. ``` ruby # Credit to https://github.com/emboss/siphash-ruby/blob/master/lib/siphash.rb class SipHash # Ruby's Integer class allows numbers by going passed the max value of a 64 bit integer, # by encoding the value across multiple 64-bit integers under the hood. In order to make # sure that the values we deal with stay within the 64-bit range, we use the following # constant as the right operand of an AND bitwise operation MASK_64 = 0xffffffffffffffff def self.digest(key, msg, compress_rounds: 1, finalize_rounds: 2) new(key, msg, compress_rounds, finalize_rounds).digest end def initialize(key, msg, compress_rounds, finalize_rounds) @msg = msg @compress_rounds = compress_rounds @finalize_rounds = finalize_rounds # These are the four 64-bit integers of internal state. The initial values are based on the # arbitrary string: "somepseudorandomlygeneratedbytes" # "somepseu".split('').map(&:ord).map { |b| b.to_s(16) }.join # => "736f6d6570736575" # The 64-bit value is 8317987319222330741, its binary representation is: # 0111 0011 0110 1111 0110 1101 0110 0101 0111 0000 0111 0011 0110 0101 0111 0101 # Which we can obtain with # "736f6d6570736575".scan(/../).map { |h| h.hex } # => [115, 111, 109, 101, 112, 115, 101, 117] # [115, 111, 109, 101, 112, 115, 101, 117].pack('c8') # => "somepseu" # "somepseu".unpack('Q>') # => 8317987319222330741 # '%064b' % 8317987319222330741 # => # 0111 0011 0110 1111 0110 1101 0110 0101 0111 0000 0111 0011 0110 0101 0111 0101 # # Note that we used 'Q>' which tells unpack to assume big-endianness. Using the default of # Q< would have returned the same 8 bytes but in the opposite order, from right to left: # "somepseu".unpack('Q<') # => 8459294401660546931 # '%064b' % 8459294401660546931 # => # 0111 0101 0110 0101 0111 0011 0111 0000 0110 0101 0110 1101 0110 1111 0111 0011 # These are the same bytes but in different order, the character s is the following 8 bits: # ('%08b' % 's'.ord).scan(/..../).join(' ') # => "0111 0011" # And the character o is: # ('%08b' % 'o'.ord).scan(/..../).join(' ') # => "0110 1111" # # We can see that in the big endian version, these two bytes are on the left side, and # they're on the right side with the little endian version # # "dorandom".split('').map(&:ord).map { |b| b.to_s(16) }.join # => "646f72616e646f6d" # "lygenera".split('').map(&:ord).map { |b| b.to_s(16) }.join # => "6c7967656e657261" # "tedbytes".split('').map(&:ord).map { |b| b.to_s(16) }.join # => "7465646279746573" @v0 = 0x736f6d6570736575 @v1 = 0x646f72616e646f6d @v2 = 0x6c7967656e657261 @v3 = 0x7465646279746573 # The key argument is a 16 byte string, which we want to unpack to two 64-bit integers. # A byte contains 8 bits, so one 64-bit integer is composed of 8 bytes, and one 16 byte # string can be unpacked to two 64-bit integers. # The first line grabs the first 8 bytes with the slice method, and calls unpack with the # Q< argument. Q means that Ruby will attempt to unpack as a long, and < is the explicit # way of telling it to unpack it as little endian, which is the default on many modern CPUs k0 = key.slice(0, 8).unpack('Q<')[0] # This line does the same thing with the last 8 bytes of the key k1 = key.slice(8, 8).unpack('Q<')[0] # The ^ Ruby operator is the XOR bitwise operation, a ^= b is equivalent to a = a ^ b # These four lines initialize the four 64-bit integers of internal state with the two # parts of the secret, k0 and k1 @v0 ^= k0 @v1 ^= k1 @v2 ^= k0 @v3 ^= k1 end def digest iter = @msg.size / 8 # Compression step iter.times do |i| m = @msg.slice(i * 8, 8).unpack('Q<')[0] compress(m) end # Compression of the last characters m = last_block(iter) compress(m) # Finalization step finalize # Digest result @v0 ^ @v1 ^ @v2 ^ @v3 end private # This function might look a little bit complicated at first, it implements this section of # the compression part of paper, 2.2: # where m w-1 includes the last 0 through 7 bytes of m followed by null bytes and ending with a # byte encoding the positive integer b mod 256 def last_block(iter) # We initialize last as a 64-bit integer where the leftmost byte, the 8 bits to the left are # set to the length of the input. 8 bits can only encode a value up to 255, so if the length # is more than 255, the extra bites are discarded, for a length of 11, last would look like # 0000 1011 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 000 00000 # 11 is encoded as 1011 as binary, calling << 56 on it pushes it 56 bits to the left last = (@msg.size << 56) & MASK_64 left = @msg.size % 8 off = iter * 8 # At this point, we've applied the compress step to all the 8 byte chunks in the input # string, but if the length was not a multiple of 8, there might be between 1 & 7 more bytes # we have not compressed yet. # For instance, if the string was 'hello world', the length is 11. The digest method would # have computed an iter value of 1, because 11 / 8 => 1, and called compress once, with the # first 8 bytes, obtained with the slice method, 'hello world'.slice(0, 8) => 'hello wo' # We still need to compress the last 3 bytes, 'rld' # In this example, left will be 3, and off 8 # Note that this case/when statement is written to optimize for readability, there are ways # to express the same instructions with less code case left when 7 last |= @msg[off + 6].ord << 48 last |= @msg[off + 5].ord << 40 last |= @msg[off + 4].ord << 32 last |= @msg[off + 3].ord << 24 last |= @msg[off + 2].ord << 16 last |= @msg[off + 1].ord << 8 last |= @msg[off].ord when 6 last |= @msg[off + 5].ord << 40 last |= @msg[off + 4].ord << 32 last |= @msg[off + 3].ord << 24 last |= @msg[off + 2].ord << 16 last |= @msg[off + 1].ord << 8 last |= @msg[off].ord when 5 last |= @msg[off + 4].ord << 32 last |= @msg[off + 3].ord << 24 last |= @msg[off + 2].ord << 16 last |= @msg[off + 1].ord << 8 last |= @msg[off].ord when 4 last |= @msg[off + 3].ord << 24 last |= @msg[off + 2].ord << 16 last |= @msg[off + 1].ord << 8 last |= @msg[off].ord when 3 # In the example documented above, this is the branch of the case/when we would # end up in. last is initially set to: # 0000 1011 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 000 00000 # @msg[off + 2] is the character d, calling ord returns its integer value, 100 # We shift it 16 bits to the left, effectively inserting as the 6th byte starting # from the left, or third from the right: # 0000 1011 0000 0000 0000 0000 0000 0000 0000 0000 0110 0100 0000 0000 0000 0000 last |= @msg[off + 2].ord << 16 # @msg[off + 1]is the character l, ord returns 108, and we insert it as the 7th byte # from the left, or second from the right: last |= @msg[off + 1].ord << 8 # Finally, @msg[off] is the character r, with the ord value 100, and we insert it as the # byte from the left, or first from the right: # 0000 1011 0000 0000 0000 0000 0000 0000 0000 0000 0110 0100 0110 1100 0111 0010 last |= @msg[off].ord when 2 last |= @msg[off + 1].ord << 8 last |= @msg[off].ord when 1 last |= @msg[off].ord when 0 last else raise "Something unexpected happened with the r value: #{ r }, should be between 0 & 7" end # Last is now a 64 bit integer containing the length of the input and the last bytes, if any: last end # rotl64 is the left rotation, also called circular shift: # https://en.wikipedia.org/wiki/Circular_shift def rotl64(num, shift) ((num << shift) & MASK_64) | (num >> (64 - shift)) end # This is the main step of the siphash algorithm. A big difference with the C implementation # in the Redis codebase is the use of & MASK_64. As explained above, it is used to apply an # upper bounds to the results as Ruby would allow them to go past the max value of 64-bit # integer: 2^64 - 1 def sip_round @v0 = (@v0 + @v1) & MASK_64 @v2 = (@v2 + @v3) & MASK_64 @v1 = rotl64(@v1, 13) @v3 = rotl64(@v3, 16) @v1 ^= @v0 @v3 ^= @v2 @v0 = rotl64(@v0, 32) @v2 = (@v2 + @v1) & MASK_64 @v0 = (@v0 + @v3) & MASK_64 @v1 = rotl64(@v1, 17) @v3 = rotl64(@v3, 21) @v1 ^= @v2 @v3 ^= @v0 @v2 = rotl64(@v2, 32) end def compress(m) @v3 ^= m @compress_rounds.times { sip_round } @v0 ^= m end def finalize @v2 ^= 0xff @finalize_rounds.times { sip_round } end end ``` _listing 6.29: A Ruby implementation of the siphash 1-2 algorithm_ [java-doc-tree-map]:https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html [wikipedia-hash-table]:https://en.wikipedia.org/wiki/Hash_table [wikipedia-hash-function]:https://en.wikipedia.org/wiki/Hash_function [wikipedia-list-of-hash-functions]:https://en.wikipedia.org/wiki/List_of_hash_functions [wikipedia-hash-function-uniformity]:https://en.wikipedia.org/wiki/Hash_function#Uniformity [wikipedia-md5]:https://en.wikipedia.org/wiki/MD5 [wikipedia-sha-1]:https://en.wikipedia.org/wiki/SHA-1 [wikipedia-sha-2]:https://en.wikipedia.org/wiki/SHA-256 [chapter-4]:/post/chapter-4-adding-missing-options-to-set/ [redis-source-dict]:https://github.com/antirez/redis/blob/6.0.0/src/dict.h#L76-L82 [hash-djb2]:http://www.cse.yorku.ca/~oz/hash.html [hash-flooding]:https://131002.net/siphash/siphashdos_appsec12_slides.pdf [redis-source-siphash]:https://github.com/redis/redis/blob/6.0.0/src/siphash.c [appendix-b]:#appendix-b-a-ruby-implementation-of-siphash [ruby-downloads]:https://www.ruby-lang.org/en/downloads/ [ruby-doc-hash]:http://ruby-doc.org/core-2.7.1/Hash.html [ruby-doc-array]:http://ruby-doc.org/core-2.7.1/Array.html [c-doc-array]:https://www.tutorialspoint.com/cprogramming/c_arrays.htm [github-link-dict]:https://github.com/redis/redis/blob/6.0.0/src/dict.c [siphash-paper]:https://131002.net/siphash/siphash.pdf [chapter-7]:/ [siphash-gem]:https://github.com/emboss/siphash-ruby [scala-map-optimization]:https://github.com/scala/scala/blob/2.13.x/src/library/scala/collection/immutable/Map.scala#L241 [wjin-blog]:http://blog.wjin.org/posts/redis-internal-data-structure-dictionary.html [python-dict]:https://docs.python.org/3/tutorial/datastructures.html#dictionaries [java-hashmap]:https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/HashMap.html [rust-hashmap]:https://doc.rust-lang.org/beta/std/collections/struct.HashMap.html [elixir-map]:https://hexdocs.pm/elixir/Map.html [scala-map]:https://docs.scala-lang.org/overviews/collections-2.13/maps.html [c-malloc]:https://en.wikipedia.org/wiki/C_dynamic_memory_allocation [twos-complement]:https://en.wikipedia.org/wiki/Two%27s_complement [redis-doc-del]:https://redis.io/commands/del [redis-source-get-random-bytes]:https://github.com/antirez/redis/blob/6.0.0/src/util.c#L620 [chapter-3]:/post/chapter-3-multiple-clients/ [stack-overflow-object-finalizer]:https://stackoverflow.com/a/156264/919641 <file_sep>/code/chapter-10/zset.rb module BYORedis class ZSet attr_reader :dict, :array def initialize @dict = Dict.new @array = SortedArray.by_fields(:score, :member) end def cardinality @array.size end def add(score, member, options) unless [ nil, :nx, :xx ].include?(options[:presence]) raise "Unknown presence value: #{ options[:presence] }" end entry = @dict.get_entry(member) if entry return false if options[:presence] == :nx if entry.value != score || options[:incr] existing_pair = new_pair(entry.value, member) index = @array.index(existing_pair) if index.nil? raise "Failed to find #{ member }/#{ entry.value } in #{ @array.inspect }" end array_element = @array[index] if array_element != existing_pair raise "Failed to find #{ member }/#{ entry.value } in #{ @array.inspect }" end new_score = options[:incr] ? Utils.add_or_raise_if_nan(entry.value, score) : score next_member = @array[index + 1] prev_member = @array[index - 1] if (next_member.nil? || next_member.score > new_score || (next_member.score == new_score && next_member.member > member)) && (prev_member.nil? || prev_member.score < new_score || (prev_member.score == new_score && prev_member.member < member)) array_element.score = new_score else @array.delete_at(index) @array << new_pair(new_score, member) end entry.value = new_score end if options[:incr] new_score else options[:ch] # false by default end else return false if options[:presence] == :xx @array << new_pair(score, member) @dict[member] = score if options[:incr] score else true end end end def remove_member(member) entry = @dict.delete_entry(member) return false unless entry index = @array.index(new_pair(entry.value, member)) @array.delete_at(index) true end def remove_lex_range(range_spec) generic_remove(range_spec, &:member) end def remove_rank_range(start, stop) removed = @array.slice!(start..stop) return 0 if removed.nil? removed.each do |pair| @dict.delete(pair.member) end removed.size end def remove_score_range(range_spec) generic_remove(range_spec, &:score) end def count_in_lex_range(range_spec) generic_count(range_spec, &:member) end def count_in_score_range(range_spec) generic_count(range_spec, &:score) end private # It is more than recommended to check that there is some overlap between the range_spec and # this set RedisSortedSet provides that with the no_overlap_with_range? method def generic_count(range_spec, &block) first_in_range_index = @array.first_index_in_range(range_spec, &block) last_in_range_index = @array.last_index_in_range(range_spec, &block) # We need to add 1 because the last index - the first index is off by one: # < 1, 2, 3, 4, 5>, with the range 2, 4, has the indices 1 & 3, 3 - 1 + 1 == 3 last_in_range_index - first_in_range_index + 1 end def new_pair(score, member) RedisSortedSet::Pair.new(score, member) end def generic_remove(range_spec, &block) first_in_range_index = @array.first_index_in_range(range_spec, &block) last_in_range_index = first_in_range_index (first_in_range_index.upto(@array.size - 1)).each do |rank| pair = @array[rank] in_range = range_spec.in_range?(yield(pair)) if in_range last_in_range_index = rank else break end end remove_rank_range(first_in_range_index, last_in_range_index) end end end <file_sep>/code/chapter-1/server-thread.rb require 'socket' server = TCPServer.new 2000 loop do Thread.start(server.accept) do |client| client.puts 'Hello !' client.puts "Time is #{Time.now}" client.close end end <file_sep>/code/chapter-9/test/sorted_array_unit_test.rb # coding: utf-8 require_relative './test_helper' require_relative '../sorted_array' describe BYORedis::SortedArray do TestStruct = Struct.new(:a, :timeout) describe 'push/<<' do it 'appends elements while keeping the array sorted' do sorted_array = new_array(:timeout) sorted_array << TestStruct.new('a', 1) sorted_array << TestStruct.new('b', 2) sorted_array << TestStruct.new('c', 10) sorted_array << TestStruct.new('d', 20) sorted_array << TestStruct.new('e', 15) sorted_array << TestStruct.new('f', 8) assert_equal(6, sorted_array.size) assert_equal(1, sorted_array[0].timeout) assert_equal(2, sorted_array[1].timeout) assert_equal(8, sorted_array[2].timeout) assert_equal(10, sorted_array[3].timeout) assert_equal(15, sorted_array[4].timeout) assert_equal(20, sorted_array[5].timeout) end end describe 'delete' do it 'deletes the element from the array' do sorted_array = new_array(:timeout) sorted_array << TestStruct.new('a', 10) sorted_array << TestStruct.new('b1', 20) sorted_array << TestStruct.new('b2', 20) sorted_array << TestStruct.new('b3', 20) sorted_array << TestStruct.new('c', 30) # array is now a, b3, b2, b1, c sorted_array.delete(TestStruct.new('d', 40)) # no-op sorted_array.delete(TestStruct.new('b1', 20)) assert_equal(4, sorted_array.size) assert_equal(10, sorted_array[0].timeout) assert_equal(TestStruct.new('b3', 20), sorted_array[1]) assert_equal(TestStruct.new('b2', 20), sorted_array[2]) assert_equal(30, sorted_array[3].timeout) end end def new_array(field) BYORedis::SortedArray.new(field) end end <file_sep>/code/chapter-7/test/dict_unit_test.rb require_relative './test_helper' require_relative '../dict' describe 'Dict' do describe 'set' do it 'adds a new pair if the key is not already present' do dict = new_dict assert_equal('1', dict['a'] = '1') assert_equal('1', dict['a']) assert_equal(1, dict.used) end it 'overrides the existing value if the key is already present' do dict = new_dict([ 'a', '1' ]) assert_equal('2', dict['a'] = '2') assert_equal('2', dict['a']) assert_equal(1, dict.used) end it 'prevents duplicates even while rehashing' do dict = new_dict([ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ], [ 'd', '4' ], [ 'e', '5' ], [ 'f', '6' ], [ 'g', '7' ], [ 'h', '8' ]) dict['i'] = '9' # Trigger rehashing with a 9th element # Find an element that has not been rehashed not_yet_rehashed_entry = dict.hash_tables[0].table.reject(&:nil?)[-1] # Override that entry, and make sure it does not incorrectly add it to the rehashing table # instead dict[not_yet_rehashed_entry.key] = 'something else' pairs = [] dict.each do |key, value| pairs << [ key, value ] end # We only know at runtime which key we changed, so compute the expected result then expected_pairs = [ [ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ], [ 'd', '4' ], [ 'e', '5' ], [ 'f', '6' ], [ 'g', '7' ], [ 'h', '8' ], [ 'i', '9' ] ] updated_entry = expected_pairs.find { |p| p[0] == not_yet_rehashed_entry.key } updated_entry[1] = 'something else' assert_equal(expected_pairs, pairs.sort) end end describe 'get' do it 'returns nil if the key is not present' do dict = new_dict assert_nil(dict['a']) end it 'returns the value if the key is present' do dict = new_dict([ 'a', '1' ]) dict['b'] = '2' assert_equal('2', dict['b']) end end describe 'delete' do it 'returns nil if the key is not present' do dict = new_dict([ 'a', '1' ]) assert_nil(dict.delete('b')) end it 'removes the key/value pair is the key is present' do dict = new_dict([ 'a', '1' ]) assert_equal('1', dict.delete('a')) assert_nil(dict['a']) assert_equal(0, dict.used) end end describe 'each' do it 'iterates over all elements in the dict' do dict = new_dict([ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ]) pairs = [] dict.each do |key, value| pairs << [ key, value ] end assert_equal([ [ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ] ], pairs.sort) end it 'iterates over all elements in the dict while rehashing' do dict = new_dict([ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ], [ 'd', '4' ]) dict['e'] = '5' pairs = [] dict.each do |key, value| pairs << [ key, value ] end assert_equal([ [ 'a', '1' ], [ 'b', '2' ], [ 'c', '3' ], [ 'd', '4' ], [ 'e', '5' ] ], pairs.sort) end end def new_dict(*pairs) dict = BYORedis::Dict.new pairs.each do |pair| dict[pair[0]] = pair[1] end dict end end <file_sep>/code/chapter-7/option_utils.rb module BYORedis ValidationError = Class.new(StandardError) do def resp_error RESPError.new(message) end end module OptionUtils def self.validate_integer(str) Integer(str) rescue ArgumentError, TypeError raise ValidationError, 'ERR value is not an integer or out of range' end def self.validate_float(str, field_name) Float(str) rescue ArgumentError, TypeError raise ValidationError, "ERR #{ field_name } is not a float or out of range" end end end
5eb2d24a147fba66d4120a13bfad4ac7bf9836b1
[ "Markdown", "C", "Ruby", "TOML" ]
95
Ruby
pjambet/redis-in-ruby
f9e416f3c1e9e4ddf3dc6e94b125e165b2c72bcf
db955c3c9e81c328691c0f222bf3b4cde286575b
refs/heads/master
<repo_name>GoranSmernic/GoranSmernic-Final<file_sep>/src/main/java/hr/algebra/models/Size.java package hr.algebra.models; public enum Size { SMALL, BIG } <file_sep>/src/main/java/hr/algebra/models/Bus.java package hr.algebra.models; public class Bus extends Vehicle { public Bus(FuelType fuelType, float fuelPercentage) { super(fuelType, fuelPercentage, 70, Size.BIG); } @Override public String toString() { return "Bus - " + this.getString(); } } <file_sep>/src/main/java/hr/algebra/Solid.java package hr.algebra; import hr.algebra.Utilities.Utils; import hr.algebra.models.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Solid { public static void main(String[] args) throws IOException { printHr(); System.out.println("Unesite broj malih vlakova: "); int smallTrainNumber = Integer.parseInt(readLine()); System.out.println("Unesite broj velikih vlakova: "); int bigTrainNaumber = Integer.parseInt(readLine()); System.out.println("Unesite broj vozila: "); int vehicleNumer = Integer.parseInt(readLine()); printHr(); Employee poorGuy = new Employee("Poor", (float) 0.1); Employee richGuy = new Employee("Rich", (float) 0.11); List<SmallTrain> smallTrains = new ArrayList(); List<BigTrain> bigTrains = new ArrayList(); generateSmallTrains(smallTrains, smallTrainNumber); generateBigTrains(bigTrains, bigTrainNaumber); fillSmallTrains(smallTrains, poorGuy, richGuy, vehicleNumer); fillBigTrains(bigTrains, poorGuy, richGuy, vehicleNumer); printHr(); printHr(); System.out.println(poorGuy); printHr(); System.out.println(richGuy); printHr(); } private static String readLine() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); return reader.readLine(); } private static void fillSmallTrains(List<SmallTrain> trains, Employee e1, Employee e2, int vehicleNumer) { int index = 0; for (Train train : trains) { for (int i = 0; i < vehicleNumer; i++) { Vehicle vehicle = Utils.getRandomVehicle(); if (train.addVehicle(vehicle)) { if (index % 2 == 0) { e1.driveVehicle(vehicle); } else { e2.driveVehicle(vehicle); } System.out.println(vehicle.toString() + " On train: " + trains.toString()); index++; } } } } private static void fillBigTrains(List<BigTrain> trains, Employee e1, Employee e2, int vehicleNumer) { int index = 0; for (Train train : trains) { for (int i = 0; i < vehicleNumer; i++) { Vehicle vehicle = Utils.getRandomVehicle(); if (train.addVehicle(vehicle)) { if (index % 2 == 0) { e1.driveVehicle(vehicle); } else { e2.driveVehicle(vehicle); } System.out.println(vehicle.toString() + " On train: " + trains.toString()); index++; } } } } private static void generateSmallTrains(List<SmallTrain> smallTrains, int smallTrainNumber) { for (int i = 0; i < smallTrainNumber; i++) { smallTrains.add(new SmallTrain()); } } private static void generateBigTrains(List<BigTrain> bigTrains, int bigTrainNaumber) { for (int i = 0; i < bigTrainNaumber; i++) { bigTrains.add(new BigTrain()); } } private static void printHr() { System.out.println("-----------------------------------------------------------------------------------------"); } } <file_sep>/src/main/java/hr/algebra/models/FuelType.java package hr.algebra.models; public enum FuelType { BATTERY, GAS } <file_sep>/src/main/java/hr/algebra/models/Vehicle.java package hr.algebra.models; public class Vehicle { private FuelType fuelType; private float fuelPercentage; private float price; private Size size; public Vehicle(FuelType fuelType, float fuelPercentage, float price, Size size) { this.fuelType = fuelType; this.fuelPercentage = fuelPercentage; this.price = price; this.size = size; } public Size getSize() { return size; } public void setSize(Size size) { this.size = size; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public FuelType getFuelType() { return fuelType; } public void setFuelType(FuelType fuelType) { this.fuelType = fuelType; } public float getFuelPercentage() { return fuelPercentage; } public void setFuelPercentage(float fuelPercentage) { this.fuelPercentage = fuelPercentage; } public String getString() { return "size: " + size + ", fuelType: " + fuelType + ", fuelPercentage: " + fuelPercentage + ", price: " + price + "kn"; } } <file_sep>/src/main/java/hr/algebra/Utilities/Utils.java package hr.algebra.Utilities; import hr.algebra.Factories.Factory; import hr.algebra.models.*; import java.util.Random; public class Utils { public static int getRandomInt(int min, int max) { return (new Random().nextInt((max - min) + 1) + min); } public static Size getRandomSize() { int temp = getRandomInt(0, 1); if (getRandomInt(0, 1) == 0) { return Size.BIG; } return Size.SMALL; } public static FuelType getRandomFuelType() { if (getRandomInt(0, 1) == 0) { return FuelType.BATTERY; } return FuelType.GAS; } public static float getRandomFuelPercentage() { return ((float) getRandomInt(1, 100) / 100); } public static Vehicle getRandomVehicle() { FuelType ft = getRandomFuelType(); float fp = getRandomFuelPercentage(); int temp = getRandomInt(0, 2); switch (temp) { case 0: return Factory.getVehicle(ft, fp, VehicleType.CAR); case 1: return Factory.getVehicle(ft, fp, VehicleType.TRUCK); case 2: return Factory.getVehicle(ft, fp, VehicleType.VAN); } return Factory.getVehicle(ft, fp, VehicleType.BUS); } } <file_sep>/src/main/java/hr/algebra/models/SmallTrain.java package hr.algebra.models; public class SmallTrain extends Train { public SmallTrain() { super(Size.SMALL, 8); } @Override public String toString() { return "BigTrain - " + getString(); } }
ec3876c8fc70a8de7f1008f97beb09705769b083
[ "Java" ]
7
Java
GoranSmernic/GoranSmernic-Final
4f407f5ef27399f9c0c060fab79ec000cb13c127
7e699bf7d973177986436ec9df074dc5d00d1acb
refs/heads/master
<file_sep>package and06c.lektion4; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; import com.google.android.gms.location.LocationListener; import android.annotation.SuppressLint; //import and06c.lektion1.NoteLocation; //import and06c.lektion1.GatherActivity.NoteLocationListener; import android.app.Service; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.text.format.Time; import android.util.Log; public class LocationService extends Service { static int Counter=0; static long Duration=0; public Date start, stop; //static long diffInSeconds=0,diffInMinutes=0,diffInHours=0; //private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); private static final String TAG = LocationService.class.getSimpleName(); private static NoteLocation lastLocation; private LocationManager locationManager; private NoteLocationListener locationListener; private long startTime; // --> ESA private int minTime = 5000; // Millisekunden private int minDistance = 0; private IBinder binder = new LocationServiceBinder(); @Override public IBinder onBind(Intent intent) { Counter++; this.start = new Date(); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, minTime, minDistance, locationListener); Log.d(TAG, "Geodatenerfassung gestartet (onBind)"); return binder; } // IBinder-Implementierung /*class LocationServiceBinder extends Binder { public LocationService getService() { return LocationService.this; } }*/ class LocationServiceBinder extends Binder { public NoteLocation getLastLocation() { return lastLocation; } public void stopTimer() { stop = new Date(); long TimeSpent = stop.getTime() - start.getTime(); Duration += TimeUnit.MILLISECONDS.toSeconds(TimeSpent); } } /*public NoteLocation getLastLocation() { return lastLocation; }*/ public LocationService() { } @Override public void onCreate() { super.onCreate(); locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE); locationListener = new NoteLocationListener(); startTime = System.currentTimeMillis(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub //lastLocation = new NoteLocation(37.422006,-122.084895, 200); /*locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, minTime, minDistance, locationListener);*/ return START_STICKY; // Implementierung nach "onBind" verlagert // Methode kann wegfallen } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); locationManager.removeUpdates((android.location.LocationListener) locationListener); Log.d(TAG, "Erfassung von Geodaten beendet(onDestroy)"); } class NoteLocationListener implements android.location.LocationListener { @Override public void onLocationChanged(Location location) { lastLocation = new NoteLocation( location.getLatitude(), location.getLongitude(), (int)location.getAltitude()); // TODO: "lastLocation" später in DB speichern! *) // Vorerst nur loggen: Log.d(TAG, lastLocation.toString()); } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status, Bundle extras) { } } }
41134e9e0db4848cd341cc48316ca0af777221cd
[ "Java" ]
1
Java
sohrabhejazi/AND06C_Lektion4
b5ef13278c2e98ed0f543ebcdf56ed09f81b140c
7c2b46d8759931c319ab47d835b41fcc26dcd94e
refs/heads/main
<file_sep># Django-REST-2 API View Concept
4edba79a1c26519d4acec2c705fad672a81d7008
[ "Markdown" ]
1
Markdown
Farukh-Basle/Django-REST-2
b245b496f46a5fe992a47428a44d31299314c42c
393fea2ce70f8832800b145440c85d69deeb132a
refs/heads/master
<file_sep>import unittest def with_extra_space(arr): output = [] for index in range(len(arr)): n = arr.pop(0) result = 1 for e in arr: result *= e arr.append(n) output.append(result) return output class TestCaseMethods(unittest.TestCase): def test_with_extra_space(self): self.assertEqual(with_extra_space([1, 2, 3, 4]), [24, 12, 8, 6]) if __name__ == '__main__': unittest.main() <file_sep>import unittest def sort(n): arr = [1, 2, 3, 4, 5] i = arr.index(n) return arr[i::-1] + arr[i + 1:] class TestCaseMethods(unittest.TestCase): def test_case_1(self): self.assertEqual(sort(4), [4, 3, 2, 1, 5]) def test_case_2(self): self.assertEqual(sort(3), [3, 2, 1, 4, 5]) if __name__ == '__main__': unittest.main() <file_sep># wys1203.github.io<file_sep>import unittest """ Try to come up as many solutions as you can A = "hello, how are you" B = "are" if find then return the leading index of B else return -1 """ def figure_out_index_of_substr(substr): mainstr = "hello, how are you" c = substr[0] for i, char in enumerate(mainstr): if char == c: if mainstr[i:i + len(substr)] == substr: return i return -1 class TestCaseMethods(unittest.TestCase): def test_case_1(self): r = figure_out_index_of_substr("are") self.assertEqual(r, 11) def test_case_2(self): r = figure_out_index_of_substr("abr") self.assertEqual(r, -1) if __name__ == '__main__': unittest.main() <file_sep>import unittest def pick(s): n = [] for c in set(s): if s.count(c) == 1: n.append(s.index(c)) if len(n) > 0: return min(n) else: return -1 class TestCaseMethods(unittest.TestCase): def test_pick_case_1(self): self.assertEqual(pick("leetcode"), 0) def test_pick_case_2(self): self.assertEqual(pick("loveleetcode"), 2) def test_pick_case_3(self): self.assertEqual(pick(""), -1) def test_pick_case_4(self): self.assertEqual(pick("z"), 0) def test_pick_case_5(self): self.assertEqual(pick("cc"), -1) def test_pick_case_6(self): self.assertEqual(pick("aaddadaaaa"), -1) if __name__ == '__main__': unittest.main() <file_sep>import unittest """ n % 3 == 0 -> 3x n % 5 == 0 -> 5x n % 3 == 0 and n % 5 == 0 -> 3x5x """ def sort(): result = [] n = 0 while n <= 100: n += 1 if n * 3 <= 100: result.append("3x") if n * 5 <= 100: result.append("5x") if n * 5 * 3 <= 100: result.append("3x5x") return result class TestCaseMethods(unittest.TestCase): def setUp(self): arr = sort() self.my3x = arr.count("3x") self.my5x = arr.count("5x") self.my3x5x = arr.count("3x5x") def test_number_of_solution(self): nums_3x = 0 nums_5x = 0 nums_3x5x = 0 for i in range(1, 101): if i % 3 == 0: nums_3x += 1 if i % 5 == 0: nums_5x += 1 if i % (3 * 5) == 0: nums_3x5x += 1 self.assertEqual(nums_3x, self.my3x) self.assertEqual(nums_5x, self.my5x) self.assertEqual(nums_3x5x, self.my3x5x) if __name__ == '__main__': unittest.main() <file_sep>import unittest def sort(n): arr = [1, 2, 3, 4, 5] n = arr.pop(arr.index(n)) return [n] + arr class TestCaseMethods(unittest.TestCase): def test_case_1(self): self.assertEqual(sort(3), [3, 1, 2, 4, 5]) def test_case_2(self): self.assertEqual(sort(4), [4, 1, 2, 3, 5]) if __name__ == '__main__': unittest.main() <file_sep>import unittest def my_solution(nums): """ :type nums: List[int] :rtype: int """ nums.sort() for i, n in enumerate(nums): if i != n: return i return i + 1 def func2(nums): return set(list(range(len(nums) + 1))).difference(set(nums)).pop() def func3(nums): s = int((len(nums) + 1) * len(nums) / 2) return s - sum(nums) class TestCaseMethods(unittest.TestCase): def test_case_1(self): self.assertEqual(my_solution([0]), 1) self.assertEqual(func2([0]), 1) self.assertEqual(func3([0]), 1) def test_case_2(self): self.assertEqual(my_solution([0, 1]), 2) self.assertEqual(func3([0, 1]), 2) self.assertEqual(func3([0, 1]), 2) def test_case_3(self): self.assertEqual(my_solution([1, 0]), 2) self.assertEqual(func3([1, 0]), 2) self.assertEqual(func3([1, 0]), 2) def test_case_4(self): self.assertEqual(my_solution([0, 1, 2, 4]), 3) self.assertEqual(func3([0, 1, 2, 4]), 3) self.assertEqual(func3([0, 1, 2, 4]), 3) if __name__ == '__main__': unittest.main() <file_sep>import unittest def move_zeros(arr): zeros = 0 for i in range(len(arr)): if arr[i] == 0: zeros += 1 else: arr[i - zeros] = arr[i] arr[len(arr) - zeros:] = [0] * zeros return arr class TestCaseMethods(unittest.TestCase): def test_move_zeros(self): self.assertEqual(move_zeros([0, 1, 0, 3, 12]), [1, 3, 12, 0, 0]) if __name__ == '__main__': unittest.main()
516d018bb216cd830aa56fad3cfbd46fff6dc1e2
[ "Markdown", "Python" ]
9
Python
wys1203/wys1203.github.io
0007d45c1bdf07e94729f59d3e213edc27e77030
874cc39f9247d0c484028265c5ec7a7a8dfeb724
refs/heads/master
<repo_name>AlexAegis/avl<file_sep>/test/avl-number.spec.ts import { expect } from 'chai'; import { Tree } from '../src/tree.class'; describe('AVL Number tests', () => { let tree: Tree; beforeEach(() => { tree = new Tree(); tree.push(2); tree.push(1); tree.push(0); tree.push(3); tree.push(4); }); it('should not be able to insert an already added number to the tree', () => { const lengthBeforeAdd = tree.length; expect(tree.push(1)).to.be.not.ok; expect(tree.length).to.be.equal(lengthBeforeAdd); }); it('should be able to check if a number is in the tree', () => { expect(tree.has(3)).to.be.ok; expect(tree.has(0)).to.be.ok; }); it('should be able to return a number if its in the tree', () => { expect(tree.get(3)).to.be.ok; expect(tree.get(0)).to.equal(0); }); it('should be able to return undefined if its not in the tree', () => { expect(tree.get(-1)).to.be.not.ok; }); it('should be able to return the largest value', () => { expect(tree.max()).to.equal(4); }); it('should be able to return the smallest value', () => { expect(tree.min()).to.equal(0); }); it('should be able to return the smallest value even if its a negative', () => { expect(tree.push(-1)).to.be.true; expect(tree.push(-3)).to.be.true; expect(tree.push(-2)).to.be.true; expect(tree.push(-2)).to.be.false; expect(tree.min()).to.equal(-3); }); }); <file_sep>/test/avl.spec.ts import { expect } from 'chai'; import { Tree } from '../src/tree.class'; describe('AVL Tree', () => { it('should be constructable without generics', () => { const tree = new Tree(); expect(tree).to.be.ok; }); it('should be constructable with only key generic', () => { const tree = new Tree<number>(); expect(tree).to.be.ok; }); it('should be able to push numbers in', () => { const tree = new Tree(); tree.push(1); tree.push(2); tree.push(3); tree.push(4); expect(tree.length).to.equal(4); }); it('should be able to sort the numbers on push', () => { const tree = new Tree(); tree.push(4); tree.push(2); tree.push(3); tree.push(1); let i = 1; for (const n of tree) { expect(n).to.equal(i); i++; } }); }); <file_sep>/src/error/convert.error.ts export class ConvertError extends Error { constructor() { super('Cannot convert, no sufficient conversion method. Either use a Convertable or supply a converter'); } } <file_sep>/.github/contributing.md # Contributing to Inversify ## Setup 1 - Clone your fork of the repository: ```bash git clone https://github.com/AlexAegis/avl.git ``` ## Guidelines - Please try to [combine multiple commits before pushing](http://stackoverflow.com/questions/6934752/combining-multiple-commits-before-pushing-in-git) - Please use `TDD` when fixing bugs. This means that you should write a unit test that fails because it reproduces the issue, then fix the issue finally run the test to ensure that the issue has been resolved. This helps us to prevent fixed bugs from happening again in the future. - Please keep the test coverage at 100%. Write additional unit test if necessary <file_sep>/test/avl-height.spec.ts import { expect } from 'chai'; import { Tree } from '../src/tree.class'; describe('AVL Height tests', () => { const minHeight = (n: number) => Math.ceil(Math.log2(n + 1)); const maxHeight = (n: number) => Math.floor(1.44 * Math.log2(n + 2) - 0.328); let tree: Tree; beforeEach(() => { tree = new Tree(); }); it('should stay between the allowed heights while plugging in a lot of numbers', () => { for (let i = -50; i <= 50; i = i + 2) { expect(tree.push(i)).to.be.true; expect(tree.height).to.be.gte(minHeight(tree.length)); expect(tree.height).to.be.lte(maxHeight(tree.length)); } for (let i = 51; i >= -50; i = i - 2) { expect(tree.push(i)).to.be.true; expect(tree.height).to.be.gte(minHeight(tree.length)); expect(tree.height).to.be.lte(maxHeight(tree.length)); } }); }); <file_sep>/test/model/basic-comparable.class.ts export class BasicComparable { public n: number; public constructor(n: number) { this.n = n; } public compareTo(other: BasicComparable): number { return this.n - other.n; } public toString(): string { return `{type: ${typeof this} n: ${this.n}}`; } } <file_sep>/src/error/compare.error.ts export class CompareError extends Error { constructor() { super('Cannot compare, no sufficient comparing method. Either use a Comparable or supply a comparator'); } } <file_sep>/src/helper/hash.function.ts /** * This produces unique numbers for every string. * Since there are 222 different characters for each letter, the value of it must be raised one of 222's powers. * The numbers can get quite large. */ export function hashString(s: string): number { return ( s && [...s] .filter(n => n !== undefined) .reduce((acc, next, i, array) => (acc += next.charCodeAt(0) * Math.pow(222, array.length - i - 1)), 0) ); } export function hashOrReturn(s: string | number): number { if (typeof s === 'number') { return s as number; } else { hashString(s); } } <file_sep>/test/model/basic-convertable.class.ts import { Basic } from './basic.class'; import { Convertable } from '../../src/interface/convertable.interface'; export class BasicConvertable extends Basic implements Convertable { convertTo(): number { return this.n; } } <file_sep>/test/model/basic-convertable-to-comparable.class.ts import { Convertable } from './../../src/interface/convertable.interface'; import { Coord } from './coord.class'; export class BasicConvertableToComparable implements Convertable<Coord> { constructor(private coord: Coord) {} convertTo(): Coord { return this.coord; } } <file_sep>/test/avl-move.spec.ts import { expect } from 'chai'; import { Tree } from '../src/tree.class'; import { BasicComparable } from './model/basic-comparable.class'; describe('AVL Move tests', () => { let tree: Tree<BasicComparable, number>; beforeEach(() => { tree = new Tree<BasicComparable, number>(); tree.set(new BasicComparable(1), 1); tree.set(new BasicComparable(2), 2); tree.set(new BasicComparable(3), 3); tree.set(new BasicComparable(4), 4); }); it('should be able to keep its reference', () => { const originalNode = tree.getNode(new BasicComparable(3)); const newKey = new BasicComparable(7); const result = tree.moveNode(originalNode.key, newKey); const resultNode = tree.getNode(newKey); expect(originalNode).to.equal(resultNode); expect(result).to.be.true; }); it('should fail when moving to an existing key', () => { const originalNode = tree.getNode(new BasicComparable(3)); const newKey = new BasicComparable(4); const result = tree.moveNode(originalNode.key, newKey); const resultNode = tree.getNode(newKey); expect(originalNode).to.not.equal(resultNode); expect(result).to.not.be.true; }); }); <file_sep>/src/index.ts export { Tree } from './tree.class'; export { Node } from './node.class'; export { Enclosing } from './type/enclosing.type'; export { Comparable } from './interface/comparable.interface'; export { Convertable } from './interface/convertable.interface'; <file_sep>/src/type/enclosing.type.ts export interface Enclosing<T> { last: T; first: T; } <file_sep>/readme.md # [AVL Tree](https://en.wikipedia.org/wiki/AVL_tree) [![Build Status](https://travis-ci.com/AlexAegis/avl.svg?branch=master)](https://travis-ci.com/AlexAegis/avl) [![npm (scoped)](https://img.shields.io/npm/v/@alexaegis/avl.svg?style=popout)](https://www.npmjs.com/package/@alexaegis/avl) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/35d7fb5b31c9407094abf49fc445cc48)](https://www.codacy.com/app/AlexAegis/avl?utm_source=github.com&utm_medium=referral&utm_content=AlexAegis/avl&utm_campaign=Badge_Grade) [![Maintainability](https://api.codeclimate.com/v1/badges/35161dd7d57e3759381a/maintainability)](https://codeclimate.com/github/AlexAegis/avl/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/35161dd7d57e3759381a/test_coverage)](https://codeclimate.com/github/AlexAegis/avl/test_coverage) [![Known Vulnerabilities](https://snyk.io/test/github/AlexAegis/avl/badge.svg?targetFile=package.json)](https://snyk.io/test/github/AlexAegis/avl?targetFile=package.json) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier) [![Greenkeeper badge](https://badges.greenkeeper.io/AlexAegis/avl.svg)](https://greenkeeper.io/) Flexible [AVL Tree](./src/main/tree.class.ts) for TypeScript and JavaScript ### Install with NPM ```bash npm i @alexaegis/avl ``` ### Import and Create ```TypeScript import { Tree } from '@alexaegis/avl'; const tree = new Tree<Key, Value>(); // Create tree.set(key, value); // Set const result: Value = tree.get(key) // Get ``` ## Usage Although the typing does not enforce the key to have a `compareTo` method (to allow using any type of object as keys, not just what you created and have control over) The tree will throw runtime errors if it can't order the keys. > The most basic case is that the key is a string or a number, then the value itself can be directly converted to a string or a number (Implicit or explicit, either having a `convertTo(): K` method on the objects prototyle or supply a converter function to the Tree object), and then if the key is an object it has to be comparable (Implicit or explicit, either having a `comparable(a: K, b: K): number` method on the objects prototype or supply a converter function to the Tree object) > These functions you supply will al have their this value bound to the object the are getting applied on. For this reason if you want to use `this` in you `comparator` and/or `converter` methods use regular functions instead of lambdas. ## Implicit keys - Comparable, Comparator if the object you are using as a key contains a compareTo(T) method then it will work just fine ```TypeScript class Key { constructor(public key: number) {} } const tree = new Tree<Key, Value>(); tree.set(new Key(2), new Value(4)); // Cannot compare error ``` ### Using a Comparable ```TypeScript class Key implements Comparable<Key> { constructor(public key: number) {} compareTo(other: Key): number { return this.key - other.key; } } const tree = new Tree<Key, Value>(); tree.set(new Key(2), new Value(4)); // 👌 the key will be valid ``` ### Using a Comparator Very important, if using a lambda as a comparator you cant use the `this` keyword in it (as usual), and the only type of comparator you can write is the 'two argumen' one as seen below. But you can use this if you use a regular anonym function. This will act the same as the one you would write while implementing the interface. There is an optional second argument here too, that's gonna be the same as a. But you don't need to use it. ```TypeScript class Key { constructor(public key: number) {} } let tree = new Tree<Key, Value>((a: Key, b: Key) => a.key - b.key); // Using Lambdas // Because of the fancy inner binding, you can even write this. It's basically the same tree = new Tree<Key, Value>(function (b: Key) { return this.key - b.key; }); tree.set(new Key(2), new Value(4)); // 👌 the key will be valid ``` ## Explicit keys - Convertable, Converter ### Using a Convertable > Only using Converters/Convertables allows the usage of the push method! You can even convert to a comparable! ```TypeScript const tree = new Tree<Value>(); tree.push(new Value(4)); // Cannot convert error ``` ```TypeScript export class Value implements Convertable { constructor(public n: number) {} convertTo(): number | string { return this.n; } } const tree = new Tree<Value>(); tree.push(new Value(4)); // 👌 the key will be 4 ``` ### Using a Converter Alternatively you can supply a function to act as the converter ```TypeScript export class Value { constructor(public n: number) {} } export class AnotherValue { constructor(public n: number) {} } const tree = new Tree<number, Value>(undefined, (val: Value) => val.n); tree.push(new Value(4)); tree.push(new AnotherValue(1)); // You can do messy things like this without implementing a single interface ``` ### Using a Convertable that converts to a Comparable This is great when you have a bunch of objects you want to quickly access by keys that are encapsulated within the object. ```TypeScript export class Coord implements Comparable<Coord> { constructor(public x: number = 0, public y: number = 0) {} compareTo(other: Coord): number { return this.y === other.y ? this.x - other.x : this.y - other.y; } } export class BasicConvertableToComparable implements Convertable<Coord> { constructor(private coord: Coord) {} convertTo(): Coord { return this.coord; } } const tree: Tree<Coord, BasicConvertableToComparable>; tree.push(new BasicConvertableToComparable(new Coord(1, 1))); tree.get(new Coord(1, 1)); // The BasicConvertableToComparable object you pushed in ``` ### Searching nearest values for missing keys You can search for either nearest on left and nearest on right values if the one you search for might be missing. ```typescript const tree = new Tree<number, number>(); tree.set(1, 1); tree.set(2, 2); tree.set(4, 4); tree.set(8, 8); tree.set(7, 7); tree.set(10, 10); tree.set(14, 14); tree.set(12, 12); const last = tree.lastBefore(13.66); // 12 const first = tree.firstFrom(13.66); // 14 const enclosing = tree.enclosing(13.66); // {last: 12, first: 14} // When you might need the keys too const lastNode = tree.lastNodeBefore(13.66); // Node {h: 1, k: 12, v: 12} const firstNode = tree.firstNodeFrom(13.66); // Node {h: 2, k: 14, v: 14, …} const enclosingNodes = tree.enclosingNodes(13.66); // Object {last: Node {h: 1, k: 12, v: 12}, first: Node {h: 2, k: 14, v: 14, …}} ``` For more examples check the [mocha tests](./src/test/) --- ## Technologies ### [Node 10](https://nodejs.org/en/) > **JavaScript** runtime ### [NPM](https://www.npmjs.com/) > **Package manager** for Node ### [TypeScript](https://www.typescriptlang.org/) > **Typed superset** of JavaScript ### [TSLint](https://palantir.github.io/tslint/) > **Linting** tool ### [Mocha](https://mochajs.org/) > **Behaviour driven testing** framework ### [Chai](https://www.chaijs.com/) > **Assertion** library ### [Istanbul](https://istanbul.js.org/) > **Code coverage** tool ## Recommendations ### [Visual Studio Code](https://code.visualstudio.com/) > **IDE** for everything. [Settings](./.vscode/) ### [Fira Code](https://github.com/tonsky/FiraCode) > **Font** with ligatures ## Services ### [Travis CI](https://travis-ci.com/) > **Continuous Integration** solution ### [Codacy](https://codacy.com/) > **Code Quality** monitoring ### [Code Climate](https://codeclimate.com/) > **Maintainability and Coverage** reports ### [Snyk](https://snyk.io/) > **Vulnerability** detection ### [Shields.io](https://shields.io/#/) > **Badges** to look cool <file_sep>/test/avl-object-comparable.spec.ts import { expect } from 'chai'; import { Tree } from '../src/tree.class'; import { BasicComparable } from './model/basic-comparable.class'; describe('Comparable tests', () => { let tree: Tree<BasicComparable, number>; beforeEach(() => { tree = new Tree<BasicComparable, number>(); tree.set(new BasicComparable(1), 1); tree.set(new BasicComparable(2), 2); tree.set(new BasicComparable(3), 3); tree.set(new BasicComparable(4), 4); }); it('should not be able to insert an already added object to the tree', () => { const lengthBeforeAdd = tree.length; tree.set(new BasicComparable(2), 2); expect(tree.length).to.be.equal(lengthBeforeAdd); }); it('should be able to check is a number is in the tree', () => { expect(tree.has(new BasicComparable(3))).to.be.ok; }); it('should be able to check is a number is not the tree', () => { expect(tree.has(new BasicComparable(-3))).to.be.not.ok; }); it('should be able to put mutliple value at once using the put method', () => { const val = [ { key: new BasicComparable(-10), value: -10 }, { key: new BasicComparable(-20), value: -20 }, { key: new BasicComparable(-30), value: -30 }, { key: new BasicComparable(-40), value: -40 }, { key: new BasicComparable(-50), value: -50 }, { key: new BasicComparable(50), value: 50 }, { key: new BasicComparable(40), value: 40 }, { key: new BasicComparable(30), value: 30 }, { key: new BasicComparable(20), value: 20 }, { key: new BasicComparable(10), value: 10 } ]; expect(tree.put(...val)).to.be.true; }); it('should be return false when even one of the keys is a duplicate', () => { const val = [ { key: new BasicComparable(-10), value: -10 }, { key: new BasicComparable(-20), value: -20 }, { key: new BasicComparable(-30), value: -30 }, { key: new BasicComparable(-40), value: -40 }, { key: new BasicComparable(50), value: -50 }, { key: new BasicComparable(50), value: 50 }, { key: new BasicComparable(40), value: 40 }, { key: new BasicComparable(30), value: 30 }, { key: new BasicComparable(20), value: 20 }, { key: new BasicComparable(10), value: 10 } ]; expect(tree.put(...val)).to.be.false; }); it('should be able to remove elements', () => { const originalLength = tree.length; tree.remove(new BasicComparable(2)); const afterRemoveLength = tree.length; expect(originalLength).to.not.equal(afterRemoveLength); expect(originalLength - 1).to.equal(afterRemoveLength); }); }); <file_sep>/test/avl-remove.spec.ts import { expect } from 'chai'; import { Tree } from '../src/tree.class'; describe('AVL Number tests', () => { let tree: Tree; beforeEach(() => { tree = new Tree(); tree.push(2); tree.push(1); tree.push(0); tree.push(3); tree.push(4); }); it('should be able to remove a leaf', () => { const lengthBefore = tree.length; expect(tree.remove(0)).to.be.equal(0); expect(tree.remove(10)).to.be.not.ok; expect(tree.length).to.equal(lengthBefore - 1); }); it('should be able to remove a middle node', () => { const lengthBefore = tree.length; expect(tree.remove(2)).to.be.equal(2); expect(tree.length).to.equal(lengthBefore - 1); }); it('should be able to remove the root node', () => { const lengthBefore = tree.length; tree.remove(1); expect(tree.length).to.equal(lengthBefore - 1); }); }); <file_sep>/test/avl-object-convertable.spec.ts import { BasicConvertable } from './model/basic-convertable.class'; import { expect } from 'chai'; import { Tree } from '../src/tree.class'; describe('Bad Converter and Convertable tests, where the interface takes priority', () => { let tree: Tree<any, BasicConvertable>; beforeEach(() => { tree = new Tree<BasicConvertable>(); tree.push(new BasicConvertable(1)); tree.push(new BasicConvertable(2)); tree.push(new BasicConvertable(3)); tree.push(new BasicConvertable(4)); }); it('should not be able to insert an already added object to the tree', () => { const lengthBeforeAdd = tree.length; tree.push(new BasicConvertable(2)); expect(tree.length).to.be.equal(lengthBeforeAdd); }); it('should be able to check is a number is in the tree', () => { expect(tree.has(3)).to.be.ok; }); it('should be able to check is a number is not the tree', () => { expect(tree.has(-1)).to.be.not.ok; }); }); <file_sep>/test/avl-coord.spec.ts import { Coord } from './model/coord.class'; import { expect } from 'chai'; import { Tree } from '../src/tree.class'; import { Basic } from './model/basic.class'; describe('Coord tests', () => { let tree: Tree<Coord, Basic>; beforeEach(() => { tree = new Tree<Coord, Basic>(); tree.set(new Coord(7, 5), new Basic(7)); tree.set(new Coord(4, 1), new Basic(3)); tree.set(new Coord(1, 3), new Basic(6)); tree.set(new Coord(3, 2), new Basic(5)); tree.set(new Coord(2, 1), new Basic(2)); tree.set(new Coord(1, 1), new Basic(1)); tree.set(new Coord(5, 1), new Basic(4)); tree.print(); }); it('should not be able to use push when the value is not convertable or primitive and there is no converter', () => { expect(tree.push.bind(tree, new Basic(2))).to.throw(Error); }); it('should be able to remove an element with no children', () => { tree.print(); expect(tree.remove(new Coord(1, 1)).n).to.be.equal(1); expect(tree.length).to.be.equal(6); }); it('should be able to remove an element with two children', () => { expect(tree.remove(new Coord(1, 3)).n).to.be.equal(6); expect(tree.length).to.be.equal(6); }); it('should be able to remove an element with one children', () => { expect(tree.remove(new Coord(2, 1)).n).to.be.equal(2); expect(tree.length).to.be.equal(6); }); it('should be in reading order', () => { let i = 1; for (const n of tree) { expect(n.n).to.equal(i); i++; } }); it('should stay in reading order even when using the forEach loop', () => { let i = 1; tree.forEach((v, index) => { expect(v.n).to.equal(i); expect(index + 1).to.equal(i); i++; }); }); it('should stay in reading order after converted to an array', () => { let i = 1; for (const n of tree.toArray()) { expect(n.n).to.equal(i); i++; } }); it('should be in reversed reading order when using the reverse generator', () => { let i = 7; for (const n of tree.reverse()) { expect(n.n).to.equal(i); i--; } }); it('should stay in reversed reading order even when using the forEachReversed loop', () => { let i = 7; tree.forEachReversed((v, index) => { expect(v.n).to.equal(i); expect(7 - index).to.equal(i); i--; }); }); }); <file_sep>/test/avl-object-converter.spec.ts import { expect } from 'chai'; import { Tree } from '../src/tree.class'; import { Basic } from './model/basic.class'; describe('Converter tests', () => { let tree: Tree<any, Basic>; beforeEach(() => { tree = new Tree<any, Basic>(undefined, function(basic: Basic) { return basic.n; }); tree.push(new Basic(1)); tree.push(new Basic(2)); tree.push(new Basic(3)); tree.push(new Basic(4)); }); it('should not be able to insert an already added object to the tree', () => { const lengthBeforeAdd = tree.length; tree.push(new Basic(2)); expect(tree.length).to.be.equal(lengthBeforeAdd); }); it('should be able to check is a number is in the tree', () => { expect(tree.has(3)).to.be.ok; }); it('should be able to check is a number is not the tree', () => { expect(tree.has(-1)).to.be.not.ok; }); }); <file_sep>/test/model/basic.class.ts export class Basic { public n: number; constructor(n: number) { this.n = n; } toString(): string { return `{type: ${typeof this} n: ${this.n}}`; } } <file_sep>/test/model/coord.class.ts import { Comparable } from '../../src/interface/comparable.interface'; export class Coord implements Comparable<Coord> { constructor(public x: number = 0, public y: number = 0) {} toString(): string { return JSON.stringify(this); } /** * compareTo Example * This is just a little draft for the test. * I do not recomment doing this as it does not take overflow into account * Might be fine with bigints */ compareTo(other: Coord): number { return this.y === other.y ? this.x - other.x : this.y - other.y; } } <file_sep>/src/node.class.ts import { Convertable } from './interface/convertable.interface'; import { Comparable } from './interface/comparable.interface'; import { jsonObject, jsonMember } from 'typedjson'; import { Tree } from './tree.class'; import { hashOrReturn } from './helper/hash.function'; @jsonObject export class Node< K extends number | string | V | Comparable<K> | any = number | string, V extends number | string | Convertable<K> | any = any > { constructor(k?: K, v?: V) { this.k = k; this.v = v; } public get key(): K { return this.k; } public get value(): V { return this.v; } public get height(): number { return this.h; } @jsonMember private l: Node<K, V>; @jsonMember private r: Node<K, V>; @jsonMember({ constructor: Number }) private h = 1; @jsonMember public k: K; @jsonMember public v: V; /** * Inspired by @mxcl 's [tweet](https://twitter.com/mxcl/status/608682016205344768) */ public invert(): void { if (this.l) this.l.invert(); if (this.r) this.r.invert(); [this.r, this.l] = [this.l, this.r]; } /** * Generator function * that returns all the values of the nodes below and this in an ascending order */ public *[Symbol.iterator](): IterableIterator<V> { if (this.l) yield* this.l; if (this.k !== undefined) yield this.v; if (this.r) yield* this.r; } /** * Generator function * that returns all the values of the nodes below and this in an descending order */ public *reverse(): IterableIterator<V> { if (this.r) yield* this.r.reverse(); if (this.k !== undefined) yield this.v; if (this.l) yield* this.l.reverse(); } public *nodes(): IterableIterator<Node<K, V>> { if (this.l) yield* this.l.nodes(); yield this; if (this.r) yield* this.r.nodes(); } public *reverseNodes(): IterableIterator<Node<K, V>> { if (this.r) yield* this.r.reverseNodes(); yield this; if (this.l) yield* this.l.reverseNodes(); } /** * Returns/ the first element. * Complexity: O(1) */ public first(): Node<K, V> { if (this.l) return this.l.first(); else return this; } /** * Returns the last element. * Complexity: O(1) */ public last(): Node<K, V> { if (this.r) return this.r.last(); else return this; } /** * Calculates the height of the node. A leafs (node without either a left or a right node) height is */ private updateHeight(): void { this.h = 1 + Math.max(this.l ? this.l.h : 0, this.r ? this.r.h : 0); } /** * Searches for a Node containing a key * @returns the value or undefined if its not found */ public search( k: K, comparator: (a: K, b: K) => number, treeRefForNearestSearch?: Tree<K, V> // Only used when searching for nearest values as it contains temporary fields. ): Node<K, V> { // When searching for nearest values, simply track each value we are traversing while searching as we always touch them on traversal const comparatorResult: number = comparator && comparator.apply(k, comparator.length === 1 ? [this.k, k] : [k, this.k]); if (treeRefForNearestSearch) { const difference = comparatorResult === undefined ? hashOrReturn(k as any) - hashOrReturn(this.k as any) : comparatorResult; if (difference >= 0 && Math.abs(treeRefForNearestSearch.differenceFromRight) >= Math.abs(difference)) { treeRefForNearestSearch.nearestFromLeft = this; treeRefForNearestSearch.differenceFromLeft = difference; } if (difference <= 0 && Math.abs(treeRefForNearestSearch.differenceFromLeft) >= Math.abs(difference)) { treeRefForNearestSearch.nearestFromRight = this; treeRefForNearestSearch.differenceFromRight = difference; } } if (comparatorResult !== undefined ? comparatorResult < 0 : k < this.k) { if (this.l) return this.l.search(k, comparator, treeRefForNearestSearch); } else if (comparatorResult !== undefined ? comparatorResult > 0 : k > this.k) { if (this.r) return this.r.search(k, comparator, treeRefForNearestSearch); } else return this; } /** * Sets the key to a specific value. Inserts the node in a key-order respecting manner * @returns the new root */ public set( k: K, v: V, reporter: { success: boolean }, comparator: (a: K, b: K) => number, existing?: Node<K, V> ): Node<K, V> { const comparatorResult: number = comparator && comparator.apply(k, comparator.length === 1 ? [this.k, k] : [k, this.k]); if (comparatorResult !== undefined ? comparatorResult < 0 : k < this.k) { if (this.l) this.l = this.l.set(k, v, reporter, comparator, existing); else this.l = existing !== undefined ? existing : new Node<K, V>(k, v); } else if (comparatorResult !== undefined ? comparatorResult > 0 : k > this.k) { if (this.r) this.r = this.r.set(k, v, reporter, comparator, existing); else this.r = existing !== undefined ? existing : new Node<K, V>(k, v); } else { if (existing === undefined) { this.k = k; this.v = v; } if (reporter) reporter.success = false; } this.updateHeight(); return this.rebalance(); } public lower(node: Node<K, V>, comparator: (a: K, b: K) => number) {} /** * Removes a node from the tree. * Reports the removed value in the reporter object * @returns the new root */ public remove(k: K, reporter: { removed: V }, comparator: (a: K, b: K) => number): Node<K, V> { const comparatorResult: number = comparator && comparator.apply(k, comparator.length === 1 ? [this.k, k] : [k, this.k]); if (comparatorResult !== undefined ? comparatorResult < 0 : k < this.k) { if (this.l) this.l = this.l.remove(k, reporter, comparator); } else if (comparatorResult !== undefined ? comparatorResult > 0 : k > this.k) { if (this.r) this.r = this.r.remove(k, reporter, comparator); } else { if (reporter) reporter.removed = this.v; if (!this.l && !this.r) { return undefined; } else if (this.l ? !this.r : this.r) { return this.l || this.r; } else { const llast = this.l.last(); this.v = llast.v; this.k = llast.k; this.l = this.l.remove(llast.k, undefined, comparator); } } this.updateHeight(); return this.rebalance(); } /** * Rebalances the tree below the node if the height differences are too big */ private rebalance(): Node<K, V> { const lh = this.l ? this.l.h : 0; const rh = this.r ? this.r.h : 0; if (lh > rh + 1) { if (((this.l && this.l.l && this.l.l.h) || 0) > ((this.l && this.l.r && this.l.r.h) || 0)) { return this.rrotate(); } else return this.lrrotate(); } else if (rh > lh + 1) { if (((this.r && this.r.r && this.r.r.h) || 0) > ((this.r && this.r.l && this.r.l.h) || 0)) { return this.lrotate(); } else return this.rlrotate(); } else return this; } /** * Performs a right-left rotation */ private rlrotate(): Node<K, V> { this.r = this.r.rrotate(); return this.lrotate(); } /** * Performs a left-right rotation */ private lrrotate(): Node<K, V> { this.l = this.l.lrotate(); return this.rrotate(); } /** * Performs a right rotation on the tree */ private rrotate(): Node<K, V> { const root: Node<K, V> = this.l; this.l = root.r; root.r = this; this.updateHeight(); if (this.r) this.r.updateHeight(); root.updateHeight(); return root; } /** * Performs a right rotation on the tree */ private lrotate(): Node<K, V> { const root: Node<K, V> = this.r; this.r = root.l; root.l = this; this.updateHeight(); if (this.l) this.l.updateHeight(); root.updateHeight(); return root; } public toString(): string { return `l: ${this.l ? this.l.k : '-'} k: ${this.k} r: ${this.r ? this.r.k : '-'}`; } } <file_sep>/src/tree.class.ts import 'reflect-metadata'; import { Constructor, TypedJSON, jsonMember, jsonObject, toJson } from 'typedjson'; import { CompareError } from './error/compare.error'; import { ConvertError } from './error/convert.error'; import { Comparable } from './interface/comparable.interface'; import { Convertable } from './interface/convertable.interface'; import { Node } from './node.class'; import { Enclosing } from './type/enclosing.type'; /** * AVL Tree */ @jsonObject @toJson export class Tree< K extends number | string | V | Comparable<K> | any = number | string, V extends number | string | Convertable<K> | any = any > { /** * Creates an instance of AVL. Can set a converter from here. */ public constructor(private _comparator?: (a: K, b: K) => number, private _converter?: (value: V) => K) {} /** * Sums up how many nodes there are in the Tree */ public get length(): number { let c = 0; for (const v of this) c++; return c; } set comparator(comparator: (a: K, b: K) => number) { this._comparator = comparator; } get comparator(): (a: K, b: K) => number { return this._comparator; } set converter(converter: (value: V) => K) { this._converter = converter; } get converter(): (value: V) => K { return this._converter; } /** * Returns the current height of the tree */ public get height(): number { return this.root ? this.root.height : 0; } @jsonMember private root: Node<K, V>; differenceFromRight = Infinity; differenceFromLeft = Infinity; nearestFromRight: Node<K, V>; nearestFromLeft: Node<K, V>; /** * ! WARNING: Limited capabilities! * ! The converted tree must use Objects (Not Numbers, not Strings, Objects) * ! on both the key and value to be working * ! (Workaround: use wrapper objects) * ! It also can't restore the explicit converter and comparator functions * ! as JavaScript can't parse functions (reliably) * ! (Workaround: use implicit converters and comparables) * * * The first limitation I believe can be improved with the Reflection-metadata API * * which is included in this project but not used as I couldn't make TypedJSON work * * with that. Feel free to contact me if you know a solution on supplying the constructor * * reference dynamically while the tree is building so it can be used when stringifying * * Bit tricky to use. You have to supply the constructor of the key and the value. If it's a primitive * you can just leave it undefined * example: * * ```typescript * const tree = Tree.parse<number, Basic>(treeAsString, undefined, Basic); * ``` * If those subtypes are also generic (and annotated by TypedJSON) you can add extra knownTypes after the initial two too. */ public static parse< K extends number | string | V | Comparable<K> | any = number | string, V extends number | string | Convertable<K> | any = any >( tree: string, keyType?: Constructor<K>, valueType?: Constructor<V>, ...extra: Array<Constructor<any>> ): Tree<K, V> { return TypedJSON.parse<Tree<K, V>>(tree, Tree, { knownTypes: [Number, String, keyType, valueType, ...extra].filter((val) => val !== undefined), }); } /** * Please don't use this for the love of god */ public invert(): void { if (this.root) this.root.invert(); } public enclosing(k: K): Enclosing<V> { return { last: this.lastBefore(k), first: this.firstFrom(k) }; } public enclosingNodes(k: K): Enclosing<Node<K, V>> { this.nearestFromRight = undefined; this.nearestFromLeft = undefined; this.differenceFromRight = Infinity; this.differenceFromLeft = Infinity; if (!this.root) { return; } else { const fin = this.finalOperators(k); this.root.search(fin.key, fin.comp, this); return { last: this.nearestFromLeft, first: this.nearestFromRight }; } } public lastBefore(k: K): V { const lastNode = this.lastNodeBefore(k); return lastNode && lastNode.v; } public lastNodeBefore(k: K): Node<K, V> { return this.enclosingNodes(k).last; } /** * Returns the first value it founds on key or after that */ public firstFrom(k: K): V { const firstNode = this.firstNodeFrom(k); return firstNode && firstNode.v; } /** * Returns the first node it founds on key or after that */ public firstNodeFrom(k: K): Node<K, V> { return this.enclosingNodes(k).first; } /** * Because it's marked with @ToJSon we can sumply use JSON.stringify. * I'm putting this method here for brevity */ public stringify(): string { const typeResolver = (sourceObject: any, knownTypes: Map<string, Function>) => { if (sourceObject.__type) return knownTypes.get(sourceObject.__type); }; return TypedJSON.stringify<Tree<K, V>>(this, Tree, { typeResolver: typeResolver }); } /** * The push method tries to convert the value into a number to use it as a Key * if it has a convertTo method (suggested, but not necessarily by the Convertable interface) * it will use that. If not, but you've set a converter */ public push(...input: Array<V>): boolean { let res = true; for (const v of input) { res = res && this.set(v as K & V, v); } return res; } /** * Return true if every key is contained */ public has(...keys: Array<K>): boolean { let result = true; for (const key of keys) { const fin = this.finalOperators(key); if (this.root) result = result && this.root.search(fin.key, fin.comp) !== undefined; } return result; } /** * Return true if any of the key is contained */ public any(...keys: Array<K>): boolean { let result = false; for (const key of keys) { const fin = this.finalOperators(key); if (this.root) result = result || this.root.search(fin.key, fin.comp) !== undefined; } return result; } /** * Returns with the value on the supplied key. undefined if there is no value on that key */ public get(key: K): V { const node = this.getNode(key); return node ? node.v : undefined; } /** * Returns with the node on the supplied key. undefined if there is no node on that key */ public getNode(key: K): Node<K, V> { const fin = this.finalOperators(key); return this.root && this.root.search(fin.key, fin.comp); } public remove(key: K): V { const fin = this.finalOperators(key); if (this.root) { const report = { removed: undefined as V }; this.root = this.root.remove(fin.key, report, fin.comp); return report.removed; } } /** * sets a key to a value */ public set(key: K, value: V): boolean { const fin = this.finalOperators(key); if (!this.root) { this.root = new Node<K, V>(fin.key, value); return true; } else { const report = { success: true }; this.root = this.root.set(fin.key, value, report, fin.comp); return report.success; } } private finalOperators(k: K): { key: K; comp: (a: K, b: K) => number } { // 1) Explicit comparator const result = { key: undefined as K, comp: this.comparator }; // 2) Implicit comparator if (result.comp === undefined && (k as unknown as Comparable<K>).compareTo) { result.comp = (k as unknown as Comparable<K>).compareTo; } if (!result.comp) { result.key = this.convert(k as V & K); // 3) Explicit convert 4) Implicit convert (Can throw ConvertError) } else { result.key = k; // 5) As is } if (!result.comp && result.key === undefined) { throw new CompareError(); } return result; } /** * Tries to convert the value. If its a convertable it will use it's inner converter. * If not, it tries to use the supplied converter in the ops. * Or optionally you can supply a converter method, but this wont be saved into the Tree * If you want a permament converter use the opts or just set the converter field of the Tree * TODO: bigint option if supported */ private convert(value: (V & K) | Convertable<K>): K { let k: K; if (typeof value === 'number' || typeof value === 'string') k = value as K; if (k === undefined && this.converter) k = this.converter.bind(value)(value); if (k === undefined && (value as Convertable<K>).convertTo) k = (value as Convertable<K>).convertTo(); if (k !== undefined) return k; throw new ConvertError(); } /** * Sets multiple values to multiple keys */ public put(...input: { key: K; value: V }[]): boolean { let result = true; for (const { key: k, value: v } of input) { result = result && this.set(k, v); } return result; } /** * Returns the first element. */ public min(): V { return this.root ? this.root.first().value : undefined; } /** * Returns the last element. */ public max(): V { return this.root ? this.root.last().value : undefined; } /** * Returns the first node. */ public first(): Node<K, V> { return this.root && this.root.first(); } /** * Returns the last node. */ public last(): Node<K, V> { return this.root && this.root.last(); } /** * This method will move the node object found at the key to the correct position in the tree. * This does not reconstruct the object. * * If you try to move the node to an key thats already exists the method will do nothing */ public moveNode(from: K, to: K): boolean { const fin = this.finalOperators(to); const node = this.getNode(from); const toNode = this.getNode(to); if (this.root && node && !toNode) { const report = { success: true }; this.remove(node.key); node.k = to; this.root = this.root.set(node.k, node.v, report, fin.comp, node); return report.success; } else return false; } /** * Calls a function on each element of the Tree, in order. * There is an optional index */ public forEach(callback: (value: V, index?: number) => void): void { let i = 0; for (const item of this) { callback(item as V, i); i++; } } /** * Calls a function on each element of the Tree, in order. * There is an optional index */ public forEachReversed(callback: (value: V, index?: number) => void): void { let i = 0; for (const item of this.reverse()) { callback(item as V, i); i++; } } /** * Iterate through the values in ascending order */ public *[Symbol.iterator](): IterableIterator<V> { if (this.root) yield* this.root; } /** * Iterate through the values in descending order */ public *reverse(): IterableIterator<V> { if (this.root) yield* this.root.reverse(); } public *nodes(): IterableIterator<Node<K, V>> { if (this.root) yield* this.root.nodes(); } public *reverseNodes(): IterableIterator<Node<K, V>> { if (this.root) yield* this.root.reverseNodes(); } public toArray(): Array<V> { const arr: Array<V> = []; for (const v of this) arr.push(v); return arr; } /** * Debugging * */ public print(): void { for (const node of this.root.nodes()) { console.log(`${'-'.repeat(node.height * 7)} ${node.toString()}`); } } } <file_sep>/test/avl-convertable-to-comparable.spec.ts import { BasicConvertableToComparable } from './model/basic-convertable-to-comparable.class'; import { Coord } from './model/coord.class'; import { expect } from 'chai'; import { Tree } from '../src/tree.class'; describe('Coord tests', () => { let tree: Tree<Coord, BasicConvertableToComparable>; const object = new BasicConvertableToComparable(new Coord(1, 1)); beforeEach(() => { tree = new Tree<Coord, BasicConvertableToComparable>(); }); it('should be able to push in an object thats key is encapsulated in the stored object', () => { tree.push(new BasicConvertableToComparable(new Coord(1, 2))); tree.push(new BasicConvertableToComparable(new Coord(1, 3))); tree.push(new BasicConvertableToComparable(new Coord(1, 4))); tree.push(new BasicConvertableToComparable(new Coord(1, 5))); tree.push(object); tree.push(new BasicConvertableToComparable(new Coord(1, 6))); tree.push(new BasicConvertableToComparable(new Coord(1, 7))); expect(tree.get(new Coord(1, 1))).to.equal(object); expect(tree.length).to.equal(7); }); }); <file_sep>/src/interface/convertable.interface.ts export interface Convertable<T = number> { convertTo(): T; }
c68c902f8c4c55674038db8794dc648f7ce5347f
[ "Markdown", "TypeScript" ]
25
TypeScript
AlexAegis/avl
6a55ad1c4151e0c366d15dadab452b14abaa8be1
9cfd27f4d8d88a0c69a891690e3a8fa25199efd1
refs/heads/master
<file_sep>Job Plus is an interactive web page for users to search job positions and provide users with personalized job recommendation Link: http://3.15.204.180/jupiter Login: username: user007 passpord: <PASSWORD> Key Points: 1. Created three java servlets with Restful API to handle HTTP request and responses 2. Retrieved job information with Github API and used MonkeyLearn API for key word extraction from job descriptions 3. Transformed and stored the job info (company name, position, location, etc) into MySQL database and deployed it to Amazon RDS for scalability and simplicity 4. Researched multiple recommendation systems and designed a content-based algorithm for job recommendation based on users’ search history and saved favorite jobs 5. Deployed to Amazon EC2 for better performance <file_sep>package external; import java.util.ArrayList; import java.util.List; import java.util.ArrayList; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import com.monkeylearn.ExtraParam; import com.monkeylearn.MonkeyLearn; import com.monkeylearn.MonkeyLearnException; import com.monkeylearn.MonkeyLearnResponse; public class MonkeyLearnClient { public static void main(String[] arg) throws MonkeyLearnException { String[] textList = {"I love minkang", "<NAME> has shared a photo of the spacesuit designed by SpaceX. This is the second image shared of the new design and the first to feature the spacesuit’s full-body look"}; List<List<String>> keywords = extractKeyWords(textList); for (List<String> wList : keywords) { for (String w : wList) { System.out.println(w); } System.out.println(); } } private static final String API_KEY = "<KEY>"; //batch processing public static List<List<String>> extractKeyWords(String[] data) throws MonkeyLearnException{ if (data == null || data.length == 0) { return new ArrayList<>(); } MonkeyLearn ml = new MonkeyLearn(API_KEY); //extraParam[] ??? String modelId = "ex_YCya9nrn"; MonkeyLearnResponse res = ml.extractors.extract(modelId, data); return getKeywords(res.arrayResult); } //turn JSONArray into List<List<String>> private static List<List<String>> getKeywords (JSONArray array){ List<List<String>> result = new ArrayList<>(); for (int i = 0; i < array.size(); i++) { List<String> keywords = new ArrayList<>(); JSONArray keyWordArray = (JSONArray) array.get(i); for (int j = 0; j < keyWordArray.size(); j++) { // casting? JSONObject object = (JSONObject) keyWordArray.get(j); String keyword = (String) object.get("keyword"); keywords.add(keyword); } result.add(keywords); } return result; } }
02af349e1f718590db0f858d1e6ddd25536a2041
[ "Markdown", "Java" ]
2
Markdown
qg2154/JobRecommend
168351f37fbc96ec957c52577c1425d0854c0bfa
e47626cf8295a96cd71f34186f925333bba4142d
refs/heads/master
<file_sep>""" Utilities to make Swift look like a regular file system """ import os import swiftclient import io import re import logging import tempfile from swiftclient.service import SwiftService, SwiftError, SwiftUploadObject from swiftclient.multithreading import OutputManager from swiftclient.exceptions import ClientException from keystoneauth1 import session from keystoneauth1.identity import v3 from tornado.web import HTTPError from traitlets import default, HasTraits, Unicode, Any, Instance from .callLogging import * #from pprint import pprint class SwiftFS(HasTraits): container = Unicode(os.environ.get('CONTAINER', 'demo')) storage_url = Unicode( help="The base URL for containers", default_value='http://example.com', config=True ) delimiter = Unicode("/", help="Path delimiter", config=True) root_dir = Unicode("/", config=True) log = logging.getLogger('SwiftFS') def __init__(self, **kwargs): super(self.__class__, self).__init__(**kwargs) # With the python swift client, the connection is automagically # created using environment variables (I know... horrible or what?) self.log.info("using swift container `%s`", self.container) # open connection to swift container self.swift = SwiftService() # make sure container exists try: result = self.swift.post(container=self.container) except SwiftError as e: self.log.error("creating container %s", e.value) raise HTTPError(404,e.value) if not result["success"]: msg = "could not create container %s"%self.container self.log.error(msg) raise HTTPError(404,msg) # see 'list' at https://docs.openstack.org/developer/python-swiftclient/service-api.html # Returns a list of all objects that start with the prefix given # Of course, in a proper heirarchical file-system, list-dir only returns the files # in that dir, so we need to filter the list to me ONLY those objects where the # 'heirarchical' bit of the name stops at the path given # The method has 2 modes: 1 when the list of names is returned with the full # path-name, and one where the name is just the "file name" @LogMethodResults() def listdir(self, path="", with_prefix=False, this_dir_only=True): """ list all the "files" in the "directory" for the given path. If the 'this_dir_only' is False (it is True by default), then the full list of all objects in that path are returned (needed for a rename, for example) returns a list of dictionaries for each object: {'bytes': 11, 'hash': '3e25960a79dbc69b674cd4ec67a72c62', 'last_modified': '2017-06-06T08:55:36.473Z', 'name': 'foo/bar/thingamy.bob'} """ files = [] # Get all objects that match the known path path = self.clean_path(path) _opts = {'prefix': path} try: dir_listing = self.swift.list(container=self.container, options=_opts) for page in dir_listing: # each page is up to 10,000 items if page["success"]: files.extend(page["listing"]) # page is returning a list else: raise page["error"] except SwiftError as e: self.log.error("SwiftFS.listdir %s", e.value) if this_dir_only: # make up the pattern to compile into our regex engine regex_delim = re.escape(self.delimiter) if len(path) > 0: regex_path = re.escape(path.rstrip(self.delimiter)) pattern = '^({0}{1}[^{1}]+{1}?|{0})$'.format(regex_path, regex_delim) else: pattern = '^[^{0}]+{0}?$'.format(regex_delim) self.log.debug("restrict directory pattern is: `%s`", pattern) regex = re.compile(pattern, re.UNICODE) new_files = [] for f in files: if regex.match(f['name']): new_files.append(f) files = new_files return files # We can 'stat' files, but not directories @LogMethodResults() def isfile(self, path): if path is None or path == '': self.log.debug("SwiftFS.isfile has no path, returning False") return False _isfile = False if not path.endswith(self.delimiter): path = self.clean_path(path) try: response = self.swift.stat(container=self.container, objects=[path]) except Exception as e: self.log.error("SwiftFS.isfile %s", e.value) for r in response: if r['success']: _isfile = True else: self.log.error('Failed to retrieve stats for %s' % r['object']) break return _isfile # We can 'list' direcotries, but not 'stat' them @LogMethodResults() def isdir(self, path): # directories mush have a trailing slash on them. # The core code seems to remove any trailing slash, so lets add it back # on if not path.endswith(self.delimiter): path = path + self.delimiter # Root directory checks if path == self.delimiter: # effectively root directory self.log.debug("SwiftFS.isdir found root dir - returning True") return True _isdir = False path = self.clean_path(path) _opts = {} if re.search('\w', path): _opts = {'prefix': path} try: self.log.debug("SwiftFS.isdir setting prefix to '%s'", path) response = self.swift.list(container=self.container, options=_opts) except SwiftError as e: self.log.error("SwiftFS.isdir %s", e.value) for r in response: if r['success']: _isdir = True else: self.log.error('Failed to retrieve stats for %s' % path) break return _isdir @LogMethod() def cp(self, old_path, new_path): self._copymove(old_path, new_path, with_delete=False) @LogMethod() def mv(self, old_path, new_path): self._copymove(old_path, new_path, with_delete=True) @LogMethod() def remove_container(self): response = {} try: response = self.swift.stat(container=self.container) except SwiftError as e: self.log.error("SwiftFS.remove_container %s", e.value) if 'success' in response and response['success'] == True : try: response = self.swift.delete(container=self.container) except SwiftError as e: self.log.error("SwiftFS.remove_container %s", e.value) for r in response: self.log.debug("SwiftFS.rm action: `%s` success: `%s`", r['action'], r['success']) @LogMethod() def rm(self, path, recursive=False): if path in ["", self.delimiter]: self.do_error('Cannot delete root directory', code=400) return False if not (self.isdir(path) or self.isfile(path)): return False if recursive: for f in self._walk_path(path, dir_first=True): self.log.debug("SwiftFS.rm recurse into `%s`", f) self.rm(f) self.log.info("SwiftFS.rm and now remove `%s`", path) self.rm(path) else: self.log.info("SwiftFS.rm not recursing for `%s`", path) files = self.listdir(path) isEmpty=True if len(files) > 1: isEmpty=False if len(files)==1 and files[0]['name']!=path: isEmpty=False if not isEmpty: self.do_error("directory %s not empty" % path, code=400) path = self.clean_path(path) try: response = self.swift.delete(container=self.container, objects=[path]) except SwiftError as e: self.log.error("SwiftFS.rm %s", e.value) return False for r in response: self.log.debug("SwiftFS.rm action: `%s` success: `%s`", r['action'], r['success']) return True @LogMethod() def _walk_path(self, path, dir_first=False): if not dir_first: yield path for f in self.listdir(path): if not dir_first: yield f['name'] if self.guess_type(f['name']) == 'directory': for ff in self._walk_path(f['name'], dir_first=dir_first): yield ff if dir_first: yield f['name'] if dir_first: yield path # core function to copy or move file-objects # does clever recursive stuff for directory trees @LogMethod() def _copymove(self, old_path, new_path, with_delete=False): # check parent directory exists self.checkParentDirExists(new_path) for f in self._walk_path(old_path): new_f = f.replace(old_path, new_path, 1) if self.guess_type(f) == 'directory': self.mkdir(new_f) else: old_path = self.clean_path(old_path) new_path = self.clean_path(new_path) try: response = self.swift.copy(self.container, [f], {'destination': self.delimiter + self.container + self.delimiter + new_f}) except SwiftError as e: self.log.error(e.value) raise for r in response: if r["success"]: if r["action"] == "copy_object": self.log.debug( "object %s copied from /%s/%s" % (r["destination"], r["container"], r["object"]) ) if r["action"] == "create_container": self.log.debug( "container %s created" % r["container"] ) else: if "error" in r and isinstance(r["error"], Exception): raise r["error"] # we always test for delete: file or directory... if with_delete: self.rm(old_path, recursive=True) # Directories are just objects that have a trailing '/' @LogMethod() def mkdir(self, path): path = path.rstrip(self.delimiter) path = path + self.delimiter self._do_write(path, None) # This works by downloading the file to disk then reading the contents of # that file into memory, before deleting the file # NOTE this is reading text files! # NOTE this really only works with files in the local direcotry, but given # local filestore will disappear when the docker ends, I'm not too bothered. @LogMethod() def read(self, path): if self.guess_type(path) == "directory": msg = "cannot read from path %s: it is a directory"%path self.do_error(msg, code=400) content = '' fhandle,localFile = tempfile.mkstemp(prefix="swiftfs_") os.close(fhandle) path = self.clean_path(path) try: response = self.swift.download(container=self.container, objects=[path],options={"out_file":localFile}) except SwiftError as e: self.log.error("SwiftFS.read %s", e.value) return '' for r in response: if r['success']: self.log.debug("SwiftFS.read: using local file %s",localFile) with open(localFile) as lf: content = lf.read() os.remove(localFile) return content # Write is 'upload' and 'upload' needs a "file" it can read from # We use io.StringIO for this @LogMethod() def write(self, path, content): if self.guess_type(path) == "directory": msg = "cannot write to path %s: it is a directory"%path self.do_error(msg, code=400) #path = self.clean_path(path) # If we can't make the directory path, then we can't make the file! #success = self._make_intermedate_dirs(path) self._do_write(path, content) @LogMethod() def _make_intermedate_dirs(self, path): # we loop over the path, checking for an object at every level # of the hierachy, except the last item (which may be a file, # or a directory itself path_parts = re.split(self.delimiter, path) current_path = '' for p in path_parts[:-1]: this_path = current_path + p + self.delimiter if self.isfile(this_path): self.log.error( "SwiftFS._make_intermedate_dirs failure: dir exists at path `%s`" % this_path) return False if not self.isdir(this_path): self.log.debug("SwiftFS._make_intermedate_dirs making directory") self._do_write(this_path, None) current_path = this_path return True @LogMethod() def _do_write(self, path, content): # check parent directory exists self.checkParentDirExists(path) type = self.guess_type(path) things = [] if type == "directory": self.log.debug("SwiftFS._do_write create directory") things.append(SwiftUploadObject(None, object_name=path)) else: self.log.debug("SwiftFS._do_write create file/notebook from '%s'", content) output = io.BytesIO(content.encode('utf-8')) things.append(SwiftUploadObject(output, object_name=path)) # Now do the upload path = self.clean_path(path) try: response = self.swift.upload(self.container, things) except SwiftError as e: self.log.error("SwiftFS._do_write swift-error: %s", e.value) raise except ClientException as e: self.log.error("SwiftFS._do_write client-error: %s", e.value) raise for r in response: self.log.debug("SwiftFS._do_write action: '%s', response: '%s'", r['action'], r['success']) @LogMethodResults() def guess_type(self, path, allow_directory=True): """ Guess the type of a file. If allow_directory is False, don't consider the possibility that the file is a directory. Parameters ---------- path: string """ _type = '' if path.endswith(".ipynb"): _type = "notebook" elif allow_directory and path.endswith(self.delimiter): _type = "directory" elif allow_directory and self.isdir(path): _type = "directory" else: _type = "file" return _type @LogMethod() def clean_path(self, path): # strip of any leading '/' path = path.lstrip(self.delimiter) if self.guess_type(path) == 'directory': # ensure we have a / at the end of directory paths path = path.rstrip(self.delimiter)+self.delimiter if path == self.delimiter: path = '' return path @LogMethodResults() def checkParentDirExists(self,path): """checks if the parent directory of a path exists""" p = path.strip(self.delimiter) p = p.split(self.delimiter)[:-1] p = self.delimiter.join(p) self.log.debug("SwiftFS.checkDirExists: directory name %s",p) if not self.isdir(p): self.do_error('parent directory does not exist %s'%p, code=400) @LogMethod() def do_error(self, msg, code=500): self.log.error(msg) raise HTTPError(code, msg) class SwiftFSError(Exception): def do_error(self, msg, code=500): raise HTTPError(code, msg) pass class NoSuchFile(SwiftFSError): def __init__(self, path, *args, **kwargs): super(NoSuchFile, self).__init__(*args, **kwargs) self.path = path <file_sep>""" Decorator for logging all method calls of a class """ import logging import sys __all__ = ['LogMethod','LogMethodResults'] class LogMethod(object): def __init__(self,log=None,logResult=False): self.log = logging.getLogger('CallLog') self.logResult = logResult def __call__(self,oFunc): def loggedFunction(*args,**kwargs): fName = args[0].__class__.__name__ + '.' + oFunc.__name__ if hasattr(args[0],'log'): log = args[0].log else: log = self.log msg = 'calling %s('%fName for a in args[1:]: msg+=repr(a)+',' for k in kwargs: msg+='%s=%s,'%(k,repr(kwargs[k])) if msg[-1] == ',': msg = msg[:-1] msg +=')' log.debug(msg) results = oFunc(*args,**kwargs) if self.logResult: log.debug('%s returned: %s',fName,repr(results)) return results return loggedFunction class LogMethodResults(LogMethod): def __init__(self,log=None): super(LogMethodResults,self).__init__(log=log,logResult=True) if __name__ == '__main__': logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) class TestClass(object): @LogMethod() def a(self,b): print ('hello',b) @LogMethodResults() def add(self,a,b): return a+b class TestClass2(object): def __init__(self,log): self.log = log @LogMethod() def add(self,a,b): return a+b t = TestClass() t.a('magi') t.a(['a','b']) print (t.add(10,2)) t2 = TestClass2(logging.getLogger('test')) print (t2.add(10,2)) <file_sep>jupyter python-swiftclient python-keystoneclient keystoneauth1 traitlets requests nose mock <file_sep># SwiftContents A back-end ContentsManager implementation for Jupyter which writes data to the Swift impliemtnation on OpenStack. ## This is probably not what you want it to be! It wanted to be a transparent, drop-in replacement for Jupyter standard filesystem-backed storage system. It wanted to implement a Jupyter Contents Manager to save all your notebooks, regular files, directories structure directly to an OpenStack Volume ### Expected behaviour I would expect a cell with f = open('my_file.txt', w) f.write('hello world') f.close to write to the cloud storage ### Actual behaviour The above code writes to local file-store - which I think is broken behaviour... ## How it works Swift is an object store. The documentation says _do not treat swift as a filestore_ .... but, hey, we can ignore that, can't we? So each _user_ has their own **container** within the store (and the SwiftClient package restricts access to specific containers). Each file is just an object in the store, and objects are refered to with a resource path. Quoting https://docs.openstack.org/developer/swift/api/object_api_v1_overview.html >For example, for the flowers/rose.jpg object in the images container in the 12345678912345 account, the resource path is: > > `/v1/12345678912345/images/flowers/rose.jpg` > >Notice that the object name contains the / character. This slash does not indicate that Object Storage has a sub-hierarchy called flowers because containers do not store objects in actual sub-folders. However, the inclusion of / or a similar convention inside object names enables you to create pseudo-hierarchical folders and directories. ... therefore we can simply create (and re-create) objects to represent files (and a directory is a path with just one object: `.`) ### Conventions * There's just one account that authenticates to Swift * Each notebook user (well, `uuid`, probably obfuscated) has their own container * Each user is is responsible for organising their own data * A directory is just an object whos path ends in a slash: `/images/flowers/` * A file is just an object whos path does **not** end in a slash: `/images/flowers/rose.jpg` ### Further info My main reference for Swift has been https://docs.openstack.org/developer/python-swiftclient/service-api.html My main reference for `ContentsManager` has been http://jupyter-notebook.readthedocs.io/en/latest/extending/contents.html * `ContentsManager.get` => `swift.download( container=container, objects=objects)` * `ContentsManager.save` => `swift.upload(container, objs + dir_markers)` * `ContentsManager.delete_file` => `swift.delete(container=container, objects=objects)` * `ContentsManager.rename_file` => `swift.copy(container, ["a"], ["b"])` * `ContentsManager.file_exists` => `swift.stat(container=container, objects=objects)` - ensure there's no longer path (?somehow?) * `ContentsManager.dir_exists` => (as `file_exists`) * `ContentsManager.is_hidden` => (we can't hide files.. _always returns false_ ) ## Prerequisites Write access (valid credentials) to an OpenStack system, with existing Volumes. ## Installation ``` $ git clone https://github.com/edina/SwiftContentsManager.git $ cd SwiftContentsmanager $ pip install -r requirements.txt $ pip install . ``` ## Testing Testing has been written to run in a Docker Container - thus be an isolated environment. The testing is also written to delete the tested container after each test. The code currently [5th July 2017] passes local test and the Notebook _ContentManager_ test suite ``` docker build -t testing/swifttest . docker run --rm -it -e OS_AUTH_URL='aaa' \ -e OS_PROJECT_ID='bbb' \ -e OS_PROJECT_NAME='ccc' \ -e OS_REGION_NAME='ddd' \ -e OS_USER_DOMAIN_NAME='eee' \ -e OS_USERNAME='fff' \ -e OS_PASSWORD='ggg' \ -e OS_IDENTITY_API_VERSION='v3' \ -e OS_INTERFACE='public' \ -e CONTAINER='testing' naas/swifttest ``` ### Testing whilst developing Change the `docker run` command to include a _volume_: ``` docker run --rm -it -e OS_AUTH_URL='aaa' \ -e OS_PROJECT_ID='bbb' \ -e OS_PROJECT_NAME='ccc' \ -e OS_REGION_NAME='ddd' \ -e OS_USER_DOMAIN_NAME='eee' \ -e OS_USERNAME='fff' \ -e OS_PASSWORD='ggg' \ -e OS_IDENTITY_API_VERSION='v3' \ -e OS_INTERFACE='public' \ -e CONTAINER='testing' \ -v $(realpath .):/home/jovyan/work/SwiftContentsManager test/swifttest /bin/bash ``` and this means you can run tests with extra parameters: ``` py.test --debug swiftcontents/tests/test_swiftmanager.py > debug.out 2>&1 ``` or ``` nosetests --logging-level=DEBUG swiftcontents/tests/test_swiftmanager.py > debug.out 2>&1 ``` (and you can review `debug.out` on your local workstation disk) or even edit the code locally and re-install it: ``` pip uninstall swiftcontentsmanager pip install . ``` to update the installed code on the Docker & re-run the tests (or, even better: ``` pip uninstall swiftcontentsmanager pip install -e . ``` ... where `-e` means the installation is _editable_ and to re-compile for each run) ### Running just one test There are times when you want to run just one test, rather than the whole suite: ``` py.test -v --debug -k test_modified_date swiftcontents/tests/test_swiftmanager.py > debug.out 2>&1 ``` or ``` nosetests --verbose --logging-level=DEBUG swiftcontents/tests/test_swiftmanager.py:SwiftContentsManagerTestCase.test_modified_date > debug.out 2>&1 ``` ## Todo 1. Work out why file-access is not using the ContentManager, and make expected behaviour work as expected! 2. Work out how to have access via an authenticating token, rather than having a username & password written into environment variables This code is effectively abandoned at this time - however I'd be delighted if someone could take it up & sort out the two items above! ## See also 1. [PGContents](https://github.com/quantopian/pgcontents) - _The_ reference 2. [S3Contents](https://github.com/danielfrg/S3Contents) (my inspiration for this code), [s3nb](https://github.com/monetate/s3nb) or [s3drive](https://github.com/stitchfix/s3drive) <file_sep>import os import shutil from pprint import pprint from swiftcontents.ipycompat import TestContentsManager from swiftcontents import SwiftContentsManager from tempfile import TemporaryDirectory from tornado.web import HTTPError # Basic concept: # Each file is an object # Each directory is an object # Each object's "path" is the full directory-path for that object (thus faking # a directory structure # When an object is created, we ensure all intermediate directory objects exist # and if they don't, we create them # When we delete an object, we ensure that that path lists only one object (ie # that it is a file, or an empty directory # When we rename a file, we can rename that file # When we rename a directory, we need to rename every object that contains that # path-part class Test_SwiftContentsManager(TestContentsManager): maxDiff = None _temp_dir = TemporaryDirectory() def setUp(self): self.contents_manager = SwiftContentsManager() def tearDown(self): #pass self.contents_manager.swiftfs.remove_container() def make_dir(self, api_path): self.contents_manager.make_dir(api_path) # This needs to be removed or else we'll run the main IPython tests as well. del TestContentsManager <file_sep>from .swiftmanager import SwiftContentsManager <file_sep>import os import json import mimetypes import logging from datetime import datetime from dateutil.parser import parse from pprint import pprint from tornado.web import HTTPError from traitlets import default, Unicode, List from base64 import b64decode from swiftcontents.swiftfs import SwiftFS, SwiftFSError, NoSuchFile from swiftcontents.ipycompat import ContentsManager from swiftcontents.ipycompat import reads, from_dict from swiftcontents.callLogging import * DUMMY_CREATED_DATE = datetime.now( ) NBFORMAT_VERSION = 4 class SwiftContentsManager(ContentsManager): # Initialise the instance def __init__(self, *args, **kwargs): super(SwiftContentsManager, self).__init__(*args, **kwargs) self.swiftfs = SwiftFS(log=self.log) @LogMethodResults() def make_dir(self, path): """Create a directory """ if self.file_exists(path) or self.dir_exists(path): self.already_exists(path) else: self.swiftfs.mkdir(path) @LogMethodResults() def get(self, path, content=True, type=None, format=None): """Retrieve an object from the store, named in 'path' named parameters ---------- content : boolean. whether we want the actual content or not type: ['notebook', 'directory', 'file'] specifies what type of object this is format: /dunno/ """ if type is None: type = self.swiftfs.guess_type(path) if type not in ["directory","notebook","file"]: msg = "Unknown type passed: '{}'".format(type) self.do_error(msg) if type == 'directory': exists = self.dir_exists(path) else: exists = self.file_exists(path) if not exists: self.no_such_entity(path) # construct accessor name from type # eg file => _get_file func = getattr(self,'_get_'+type) metadata = self.swiftfs.listdir(path) # now call the appropriate function, with the parameters given response = func(path=path, content=content, format=format, metadata=metadata) return response @LogMethodResults() def save(self, model, path): """Save a file or directory model to path. """ if "type" not in model: self.do_error("No model type provided", 400) if "content" not in model and model["type"] != "directory": self.do_error("No file content provided", 400) if model["type"] not in ("file", "directory", "notebook"): self.do_error("Unhandled contents type: %s" % model["type"], 400) try: if model["type"] == "notebook": validation_message = self._save_notebook(model, path) elif model["type"] == "file": validation_message = self._save_file(model, path) else: validation_message = self._save_directory(path) except Exception as e: self.log.error("swiftmanager.save Error while saving file: %s %s", path, e, exc_info=True) self.do_error("Unexpected error while saving file: %s %s" % (path, e), 500) # Read back content to verify save self.log.debug("swiftmanager.save getting file to validate: `%s`, `%s`", path, model["type"] ) returned_model = self.get(path, type=model["type"], content=False) if validation_message is not None: returned_model["message"] = validation_message return returned_model @LogMethod() def delete_file(self, path): """Delete the file or directory at path. """ if self.file_exists(path) or self.dir_exists(path): self.swiftfs.rm(path) else: self.no_such_entity(path) @LogMethod() def rename_file(self, old_path, new_path): """Rename a file or directory. NOTE: This method is unfortunately named on the base class. It actually moves a file or a directory. """ if self.file_exists(new_path) or self.dir_exists(new_path): self.already_exists(new_path) elif self.file_exists(old_path) or self.dir_exists(old_path): self.log.debug("swiftmanager.rename_file: Actually renaming '%s' to '%s'", old_path, new_path) self.swiftfs.mv(old_path, new_path) else: self.no_such_entity(old_path) @LogMethodResults() def file_exists(self, path): return self.swiftfs.isfile(path) @LogMethodResults() def dir_exists(self, path): return self.swiftfs.isdir(path) # Swift doesn't do "hidden" files, so this always returns False @LogMethodResults() def is_hidden(self, path): """Is path a hidden directory or file? """ return False @LogMethod() def list_checkpoints(self, path): pass @LogMethodResults() def delete(self, path): self.delete_file(path) # We can rename_file, or mv directories @LogMethod() def rename(self, old_path, new_path): self.rename_file( old_path, new_path ) @LogMethod() def do_error(self, msg, code=500): raise HTTPError(code, msg) @LogMethod() def no_such_entity(self, path): self.do_error("swiftmanager.no_such_entity called: [{path}]".format(path=path), 404) @LogMethod() def already_exists(self, path): thing = "File" if self.file_exists(path) else "Directory" note = "{thing} already exists: [{path}]".format(thing=thing, path=path) self.do_error(note, 409) @LogMethodResults() def _get_directory(self, path, content=True, format=None, metadata={}): return self._directory_model_from_path(path, content=content, metadata=metadata) @LogMethodResults() def _get_notebook(self, path, content=True, format=None, metadata={}): return self._notebook_model_from_path(path, content=content, format=format, metadata=metadata) @LogMethodResults() def _get_file(self, path, content=True, format=None, metadata={}): return self._file_model_from_path(path, content=content, format=format, metadata=metadata) @LogMethodResults() def _directory_model_from_path(self, path, content=False, metadata={}): model = base_directory_model(path) if content: if not self.dir_exists(path): self.no_such_entity(path) model["format"] = "json" model["content"] = self._convert_file_records(metadata) return model @LogMethodResults() def _notebook_model_from_path(self, path, content=False, format=None, metadata={} ): """ Build a notebook model from database record. """ # path = to_api_path(record['parent_name'] + record['name']) model = base_model(path) model['type'] = 'notebook' if isinstance(metadata,list): metadata = metadata[0] if 'last_modified' in metadata : model['last_modified'] = model['created'] = parse(metadata['last_modified']) else: model['last_modified'] = model['created'] = DUMMY_CREATED_DATE if content: if not self.swiftfs.isfile(path): self.no_such_entity(path) file_content = self.swiftfs.read(path) nb_content = reads(file_content, as_version=NBFORMAT_VERSION) self.mark_trusted_cells(nb_content, path) model["format"] = "json" model["content"] = nb_content self.validate_notebook_model(model) return model @LogMethodResults() def _file_model_from_path(self, path, content=False, format=None, metadata={}): """ Build a file model from object. """ model = base_model(path) model['type'] = 'file' if isinstance(metadata,list): metadata = metadata[0] if 'last_modified' in metadata : model['last_modified'] = model['created'] = parse(metadata['last_modified']) else: model['last_modified'] = model['created'] = DUMMY_CREATED_DATE if content: try: content = self.swiftfs.read(path) except NoSuchFile as e: self.no_such_entity(e.path) except SwiftFSError as e: self.do_error(str(e), 500) model["format"] = format or "text" model["content"] = content model["mimetype"] = mimetypes.guess_type(path)[0] or "text/plain" if format == "base64": model["format"] = format or "base64" model["content"] = b64decode(content) return model @LogMethodResults() def _convert_file_records(self, records): """ Applies _notebook_model_from_swift_path or _file_model_from_swift_path to each entry of `paths`, depending on the result of `guess_type`. """ ret = [] for r in records: self.log.debug("swiftmanager._convert_file_records iterating: '%s'" % r) type_ = "" # Each record is a dictionary thus: # {'hash': 'd41d8cd98f00b204e9800998ecf8427e', 'bytes': 0, 'last_modified': '2017-05-31T09:20:22.224Z', 'name': 'foo/file.txt'} # in which case, we if not isinstance(r, str): path = r['name'] type_ = self.swiftfs.guess_type( path ) self.log.debug("swiftmanager._convert_file_records type is: '%s' [ %s]" % (type_, r) ) if type_ == "notebook": ret.append(self._notebook_model_from_path(path, content=False, metadata=r)) elif type_ == "file": ret.append(self._file_model_from_path(path, content=False, metadata=r)) elif type_ == "directory": ret.append(self._directory_model_from_path(path, content=False, metadata=r)) else: self.do_error("Unknown file type %s for file '%s'" % (type_, path), 500) return ret @LogMethodResults() def _save_notebook(self, model, path): nb_contents = from_dict(model['content']) self.check_and_sign(nb_contents, path) file_contents = json.dumps(model["content"]) self.swiftfs.write(path, file_contents) self.validate_notebook_model(model) return model.get("message") @LogMethod() def _save_file(self, model, path): file_contents = model["content"] self.swiftfs.write(path, file_contents) @LogMethod() def _save_directory(self, path): self.swiftfs.mkdir(path) @LogMethodResults() def _get_os_path(self, path): """A method for converting an object path into File System Path. It seems that os_path's are required to map to file-store paths, so they need to exist if looked for. """ current_dir = '' # Walk the tree, making a directory at each level. for p in path.split('/'): if len(current_dir) > 1 : current_dir = current_dir + '/' + p else: current_dir = p # poke to make this level... try: self.make_dir(current_dir) except HTTPError as e: # dir exists continue return current_dir @LogMethod() def base_model(path): p = path.split('/') name = p.pop() if len(name)==0 and len(p)>0: name = p.pop()+'/' return { "name": name, "path": path.lstrip('/'), "writable": True, "last_modified": None, "created": None, "content": None, "format": None, "mimetype": None, } @LogMethodResults() def base_directory_model(path): delimiter = '/' model = base_model(path) model.update( type="directory", last_modified=DUMMY_CREATED_DATE, created=DUMMY_CREATED_DATE, path = model['path'].strip('/'), name = model['name'].strip('/') ) return model <file_sep>FROM jupyter/base-notebook MAINTAINER NaaS Project <<EMAIL>> USER root RUN apt-get update && apt-get install -yq --no-install-recommends \ vim \ build-essential \ python3-dev \ less \ && apt-get clean && \ rm -rf /var/lib/apt/lists/* RUN pip install nose pytest pytest-cov python-coveralls COPY . SwiftContentsManager/ WORKDIR SwiftContentsManager RUN pip install -r requirements.txt RUN pip install . CMD py.test swiftcontents/tests/test_swiftmanager.py <file_sep>import logging from nose.tools import assert_equals, assert_not_equals, assert_raises, assert_true, assert_false,assert_set_equal, assert_not_in from swiftcontents.swiftfs import SwiftFS, HTTPError, SwiftError # list of dirs to make # note, directory names must end with a / testDirectories = ['temp/', 'temp/bar/', 'temp/bar/temp/', 'temp/bar/temp/bar/', 'temp/bar/temp/bar/foo/', 'temp/bar/temp/bar/foo/bar/', 'temp/baz/', 'temp/baz/temp/', 'temp/baz/temp/bar/', 'temp/baz/temp/bar/foo/', 'temp/baz/temp/bar/foo/bar/'] testFileName = 'hello.txt' testFileContent = 'Hello world' # construct a dictionary containing all directories and their entries testTree = {} for d in testDirectories: pcomponents = d[:-1].split('/') for i in range(len(pcomponents)): parent = '/'.join(pcomponents[:i])+'/' child = pcomponents[i]+'/' if parent not in testTree: testTree[parent] = set() for pc in [parent+child,parent+testFileName]: if pc.startswith('/'): pc = pc[1:] testTree[parent].add(pc) log = logging.getLogger('TestSwiftFS') class Test_SwiftNoFS(object): def __init__(self): self.swiftfs = SwiftFS() def teardown(self): log.info('tidy up directory structure') self.swiftfs.rm(testDirectories[0], recursive=True) self.swiftfs.remove_container() def guess_type(self,gtype): log.info('testing guess_type %s',gtype) def test_guess_type_notebook(self): log.info('testing guess_type notebook') assert_equals (self.swiftfs.guess_type('foo.ipynb'), 'notebook') assert_not_equals (self.swiftfs.guess_type('foo/'), 'notebook') assert_not_equals (self.swiftfs.guess_type('foo'), 'notebook') assert_not_equals (self.swiftfs.guess_type('foo/', allow_directory=False), 'notebook') def test_guess_type_directory(self): log.info('testing guess_type directory') assert_not_equals (self.swiftfs.guess_type('foo.ipynb'), 'directory') assert_equals (self.swiftfs.guess_type('foo/'), 'directory') assert_not_equals (self.swiftfs.guess_type('foo'), 'directory') assert_not_equals (self.swiftfs.guess_type('foo/', allow_directory=False), 'directory') def test_guess_type_file(self): log.info('testing guess_type directory') assert_not_equals (self.swiftfs.guess_type('foo.ipynb'), 'file') assert_not_equals (self.swiftfs.guess_type('foo/'), 'file') assert_equals (self.swiftfs.guess_type('foo'), 'file') assert_equals (self.swiftfs.guess_type('foo/', allow_directory=False), 'file') def test_clean_path(self): log.info('testing clean path') assert_equals (self.swiftfs.clean_path('foo/'), 'foo/') assert_equals (self.swiftfs.clean_path('foo'), 'foo') assert_equals (self.swiftfs.clean_path('/foo/'), 'foo/') assert_equals (self.swiftfs.clean_path('/foo'), 'foo') def test_do_error(self): log.info('test do_error') assert_raises(HTTPError,self.swiftfs.do_error,"test error") def test_directory(self): log.info('test creating a directory') p = 'a_test_dir/' self.swiftfs.mkdir(p) log.info('test directory exists') assert_true (self.swiftfs.isdir(p)) assert_false(self.swiftfs.isfile(p)) log.info('test various variations including slashes in directory name') assert_true (self.swiftfs.isdir('a_test_dir')) assert_true (self.swiftfs.isdir('/a_test_dir')) assert_true (self.swiftfs.isdir('/a_test_dir/')) log.info('test directory can be deleted') self.swiftfs.rm(p) log.info('test directory is gone') assert_false (self.swiftfs.isdir(p)) log.info('test creating a directory in a non existant path') p = 'temp_does_not_exist/a_test_dir' assert_raises(HTTPError,self.swiftfs.mkdir,p) def test_file(self): log.info('test create a file') p = 'a_test_file.txt' self.swiftfs._do_write(p, testFileContent) assert_false (self.swiftfs.isdir(p)) assert_true (self.swiftfs.isfile(p)) log.info('test file can be deleted') self.swiftfs.rm(p) log.info('test file is gone') assert_false (self.swiftfs.isfile(p)) def test_read_write(self): log.info('test reading from and writing to a file') testString = "hello, world - magi was here" p = testFileName self.swiftfs.write(p,testString) result = self.swiftfs.read(p) assert_equals(testString,result) def test_write_wrong_path(self): log.info('test writing to a non existant path') testString = "hello, world - magi was here" for t in ['temp_does_not_exist/','temp/temp_does_not_exist/']: p = t+testFileName assert_raises(HTTPError,self.swiftfs.write,p,testString) def test_write_directory(self): log.info('test writing to a directory') p = 'a_test_dir/' self.swiftfs.mkdir(p) assert_raises(HTTPError,self.swiftfs.write,p,testFileContent) self.swiftfs.rm(p) def test_read_directory(self): log.info('test reading from a directory') p = 'a_test_dir/' self.swiftfs.mkdir(p) assert_raises(HTTPError,self.swiftfs.read,p) self.swiftfs.rm(p) class Test_SwiftFS(object): def __init__(self): self.swiftfs = SwiftFS() def setup(self): log.info('setting up directory structure') for d in testDirectories: self.swiftfs.mkdir(d) log.info('create a bunch of files') self.swiftfs._do_write(testFileName, testFileContent) for d in testDirectories: p = d+testFileName self.swiftfs._do_write(p, testFileContent) def teardown(self): log.info('tidy up directory structure') self.swiftfs.remove_container() def test_setup(self): log.info('check all directories exist') for d in testDirectories: assert_true(self.swiftfs.isdir(d)) assert_false(self.swiftfs.isfile(d)) log.info('check all test files exist') for d in testDirectories: p = d+testFileName assert_true(self.swiftfs.isfile(p)) def test_delete_container(self): log.info('Confirm we can delete the container') self.swiftfs.remove_container() assert_raises(SwiftError, lambda: self.swiftfs.swift.stat(container=self.swiftfs.container)) self.swiftfs.swift.post(container=self.swiftfs.container) # remake the container, else teardown barfs def test_listdir_normalmode(self): log.info('check listdir in normal mode') for d in testTree: results = set() for r in self.swiftfs.listdir(d): results.add(r['name']) assert_set_equal(results,testTree[d]) def test_listdir_allfiles(self): log.info('check listdir returning all files') results = set() expected = set() for r in self.swiftfs.listdir(testDirectories[0],this_dir_only=False): results.add(r['name']) expected.add(testFileName) for d in testDirectories[1:]: expected.add(d) expected.add(d+testFileName) def test_listdir_allroot(self): log.info('check listdir returning all files starting at root') results = set() expected = set() for r in self.swiftfs.listdir('/',this_dir_only=False): results.add(r['name']) expected.add(testFileName) for d in testDirectories: expected.add(d) expected.add(d+testFileName) assert_set_equal(results,expected) def test_listdir_dirnames(self): log.info('check listdir can handle the various variations of directories with slashes') for d in ['/temp','/temp/','temp','temp/']: results = set() for r in self.swiftfs.listdir(d): results.add(r['name']) assert_set_equal(results,testTree['temp/']) def test_copy_file(self): log.info('test copying a file') fName = testDirectories[0]+testFileName cName = fName+'_b' assert_false (self.swiftfs.isfile(cName)) self.swiftfs.cp(fName,cName) assert_true (self.swiftfs.isfile(cName)) def test_copy_file_parent(self): log.info('test copying a file to a non-existant directory') fName = testDirectories[0]+testFileName for t in ['temp_does_not_exist/','temp/temp_does_not_exist/']: assert_raises(HTTPError,self.swiftfs.cp,fName,t+testFileName) assert_raises(HTTPError,self.swiftfs.mv,fName,t+testFileName) def test_delete_file(self): log.info('test deleting a file') fName = testDirectories[0]+testFileName assert_true (self.swiftfs.isfile(fName)) self.swiftfs.rm(fName) assert_false (self.swiftfs.isfile(fName)) log.info('check deleted file is no longer in directory') results = set() for r in self.swiftfs.listdir(testDirectories[0]): results.add(r['name']) assert_not_in(fName,results) def test_move_file(self): log.info('test moving a file') fName = testDirectories[0]+testFileName cName = fName+'_b' assert_false (self.swiftfs.isfile(cName)) self.swiftfs.mv(fName,cName) assert_true (self.swiftfs.isfile(cName)) assert_false (self.swiftfs.isfile(fName)) def test_copy_directory(self): log.info('test copying a directory') source = 'temp/bar/' destination = 'temp/copy_of_bar/' expected = set() for d in testDirectories: expected.add(d) expected.add(d+testFileName) if d.startswith(source): nd = d.replace(source,destination,1) expected.add(nd) expected.add(nd+testFileName) expected.add(testFileName) self.swiftfs.cp(source,destination) results = set() for r in self.swiftfs.listdir('/',this_dir_only=False): results.add(r['name']) assert_set_equal(results,expected) def test_move_directory(self): log.info('test moving a directory') source = 'temp/bar/' destination = 'temp/copy_of_bar/' expected = set() for d in testDirectories: if d.startswith(source): nd = d.replace(source,destination,1) expected.add(nd) expected.add(nd+testFileName) else: expected.add(d) expected.add(d+testFileName) expected.add(testFileName) self.swiftfs.mv(source,destination) results = set() for r in self.swiftfs.listdir('/',this_dir_only=False): results.add(r['name']) assert_set_equal(results,expected) def test_delete_directory(self): log.info("check that deleting a non-empty directory fails") p = 'temp/bar/temp/bar/foo/bar/' assert_raises(HTTPError,self.swiftfs.rm,p) self.swiftfs.rm(p+testFileName) assert_true(self.swiftfs.rm(p)) <file_sep>import logging from nose.tools import assert_equals, assert_not_equals, assert_raises, assert_true, assert_false import os import json import shutil from pprint import pprint from swiftcontents.ipycompat import TestContentsManager from swiftcontents import SwiftContentsManager from swiftcontents.swiftfs import SwiftError from tempfile import TemporaryDirectory from tornado.web import HTTPError log = logging.getLogger('TestSwiftFManager') # list of dirs to make # note, directory names must end with a / testDirectories = ['temp/', 'temp/bar/', 'temp/bar/temp/', 'temp/bar/temp/bar/', 'temp/bar/temp/bar/foo/', 'temp/bar/temp/bar/foo/bar/', 'temp/baz/', 'temp/baz/temp/', 'temp/baz/temp/bar/', 'temp/baz/temp/bar/foo/', 'temp/baz/temp/bar/foo/bar/'] testFileName = 'hello.txt' testFileContent = 'Hello world' testNotebookName = 'hello.ipynb' testNotebookContent = {"metadata": {}, "nbformat_minor": 2, "cells": [], "nbformat": 4} class Test_SwiftManager(object): def __init__(self): self.swiftmanager = SwiftContentsManager() # Creates a bunch of directories & files def setUp(self): log.info('setting up directory structure') for d in testDirectories: self.swiftmanager.swiftfs.mkdir(d) log.info('create a bunch of files') for d in testDirectories: p = d+testFileName self.swiftmanager.swiftfs.write(p, testFileContent) # removes the stuff setup, and tests it's gone! def teardown(self): log.info('tidy up directory structure') self.swiftmanager.swiftfs.remove_container() # Test the central error-handler def test_do_error(self): sm = self.swiftmanager log.info("test_do_error starting") assert_raises(HTTPError, lambda: sm.do_error('error_text', 501)) # really? Oh, OK then... assert_raises(HTTPError, lambda: sm.do_error('error_text', 999)) # Test no_such_entity works def test_no_such_entity(self): sm = self.swiftmanager log.info("test_ no_such_entity starting") assert_raises(HTTPError, lambda: sm.no_such_entity(testDirectories[1]) ) # Test already_exists happens, and distinguishes between files & directories def test_already_exists(self): sm = self.swiftmanager log.info("test_already_exists starting") path = testDirectories[1] + testFileName assert_raises(HTTPError, lambda: sm.already_exists(path) ) path = path+ testFileName assert_raises(HTTPError, lambda: sm.already_exists(path) ) # the last directory in the test suite should test true as a directory, and false as a file def test_dir_exists(self): sm = self.swiftmanager log.info("test_dir_exists starting") exists_dir = testDirectories[-1] exists_file = exists_dir + testFileName assert_true(sm.dir_exists(exists_dir)) assert_false(sm.dir_exists(exists_file)) # the last file in the test suite should test true as a file, and false as a directory def test_file_exists(self): sm = self.swiftmanager log.info("test_file_exists starting") exists_dir = testDirectories[-1] exists_file = exists_dir + testFileName assert_true(sm.file_exists(exists_file)) assert_false(sm.dir_exists(exists_file)) # is_hidden is hard-coded to be false def test_is_hidden(self): sm = self.swiftmanager log.info("test_is_hidden starting") exists_dir = testDirectories[-1] exists_file = exists_dir + testFileName assert_false(sm.is_hidden(exists_file)) assert_false(sm.is_hidden(exists_dir)) # tests make_dir. success if make, fail if it already exists def test_make_dir(self): sm = self.swiftmanager log.info("test_make_dir starting") path = testDirectories[1].rstrip('/') + '_b/' sm.make_dir(path) assert_true(sm.dir_exists(path)) # can't make a directory if it exists aleady assert_raises(HTTPError, lambda: sm.make_dir(path)) # fails on an unknown type def test_get_unknown(self): sm = self.swiftmanager log.info("test_get_unknown starting") path = testDirectories[0] assert_raises(HTTPError, lambda: sm.get(path, type='random_text', content=None) ) # tests getting a directory: with & without content; with & without the type value defined def test_get_directory(self): sm = self.swiftmanager log.info("test_get_directory starting") path = testDirectories[0] # Specify it's a directory data = sm.get(path, type='directory', content=False) assert_true( data['content'] == None) data = sm.get(path, type='directory', content=True) assert_true( len(data['content']) > 0) # code deduces it's a directory data = sm.get(path, content=False) assert_true( data['content'] == None) data = sm.get(path, content=True) assert_true( len(data['content']) > 0) # tests getting a file: with & without content; with & without the type value defined def test_get_file(self): sm = self.swiftmanager log.info("test_get_file starting") path = testDirectories[0]+testFileName # Specify it's a file data = sm.get(path, type='file', content=False) assert_true( data['content'] == None) data = sm.get(path, type='file', content=True) assert_true( data['content'] == testFileContent) # deduce it's a file data = sm.get(path, content=False) assert_true( data['content'] == None) data = sm.get(path, content=True) assert_true( data['content'] == testFileContent) # tests getting a notebook: with & without content; with & without the type value defined def test_get_notebook(self): sm = self.swiftmanager log.info("test_get_notebook starting") path = testDirectories[0]+testNotebookName self.swiftmanager.swiftfs.write(path, json.dumps(testNotebookContent) ) # Specify it's a notebook data = sm.get(path, type='notebook', content=False) assert_true( data['content'] == None) data = sm.get(path, type='notebook', content=True) assert_true( data['content'] == testNotebookContent ) # deduce it's a notebook data = sm.get(path, content=False) assert_true( data['content'] == None) data = sm.get(path, content=True) assert_true( data['content'] == testNotebookContent) # tests that save raises errors for no type given & invalid type given def test_save_errors(self): sm = self.swiftmanager log.info("test_save_errors starting") path = testDirectories[1]+testFileName+'_2' # fail: no type given model={'content': testFileContent} assert_raises(HTTPError, lambda: sm.save(model, path) ) # fail: invalid type given model={'content': testFileContent, 'type': 'random_text'} assert_raises(HTTPError, lambda: sm.save(model, path) ) # tests saving a directory (with & without a trailing slash) def test_save_directory(self): sm = self.swiftmanager log.info("test_save_directory starting") path = testDirectories[1].rstrip('/')+'_2/' model={'type': 'directory'} returned_model = sm.save(model, path) assert_true( returned_model['path'] == path.rstrip('/') ) assert_true( sm.dir_exists(path) ) # note the trailing slash exists for the object, but not in the path path = testDirectories[1].rstrip('/')+'_3' returned_model = sm.save(model, path) assert_true( returned_model['path'] == path) assert_true( sm.dir_exists(path + '/') ) # tests saving a file def test_save_file(self): sm = self.swiftmanager log.info("test_save_file starting") path = testDirectories[1]+testFileName+'_2' model={'content': testFileContent, 'type': 'file'} returned_model = sm.save(model, path) assert_true( sm.file_exists(path) ) # tests saving a notebook def test_save_notebook(self): sm = self.swiftmanager log.info("test_save_notebook starting") path = testDirectories[1] + testNotebookName model={'content': testNotebookContent, 'type': 'notebook'} returned_model = sm.save(model, path) assert_true( sm.file_exists(path) ) # Get the model with 'content' data = sm.get(path) assert_true( data['content'] == testNotebookContent ) def test_rename_file(self): sm = self.swiftmanager log.info("test_rename_file starting") from_path = testDirectories[1]+testFileName to_path = testDirectories[1]+testFileName+'_2' # rename non-existant file should fail assert_raises(HTTPError, lambda: sm.rename_file(to_path, to_path) ) # rename to an existing file should fail assert_raises(HTTPError, lambda: sm.rename_file(from_path, from_path) ) assert_true( sm.file_exists(from_path) ) assert_false( sm.file_exists(to_path) ) sm.rename_file(from_path, to_path) assert_false( sm.file_exists(from_path) ) assert_true( sm.file_exists(to_path) ) def test_rename(self): sm = self.swiftmanager log.info("test_rename starting") from_path = testDirectories[1]+testFileName to_path = testDirectories[1]+testFileName+'_2' # rename non-existant file should fail assert_raises(HTTPError, lambda: sm.rename_file(to_path, to_path) ) # rename to an existing file should fail assert_raises(HTTPError, lambda: sm.rename_file(from_path, from_path) ) assert_true( sm.file_exists(from_path) ) assert_false( sm.file_exists(to_path) ) sm.rename_file(from_path, to_path) assert_false( sm.file_exists(from_path) ) assert_true( sm.file_exists(to_path) ) def test_delete_file(self): sm = self.swiftmanager log.info("test_delete_file starting") path = testDirectories[1]+testFileName assert_true( sm.file_exists(path) ) sm.delete_file(path) assert_false( sm.file_exists(path) ) def test_delete(self): sm = self.swiftmanager log.info("test_delete starting") path = testDirectories[1]+testFileName assert_true( sm.file_exists(path) ) sm.delete_file(path) assert_false( sm.file_exists(path) )
00a934726b3ea8fa9e30589529cc6b2642ae049b
[ "Markdown", "Python", "Text", "Dockerfile" ]
10
Python
edina/SwiftContentsManager
81c39843c05999c445eb459fcc41bdaab41e5ccf
d3b337bc4e18b6e664cfc40bfb84127ddb88c125
refs/heads/master
<file_sep>package Client; import java.util.Scanner; public class ClientDriver{ public static void main (String args[]){ /* Scanner scan = new Scanner(System.in); System.out.println("Server port Number:"); int port = scan.nextInt(); System.out.println("Server ip address:"); String address = scan.next(); System.out.println("Connecting server..."); **/ String address = "127.0.0.1"; int port = 8000; Client c = new Client(address,port); if(c.ready)c.start(); } } <file_sep>package Server; import java.net.Socket; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import utility.Communicator; public class WorkerThread implements Runnable { private Socket con; private ArrayList<String> account; private ArrayList<String> history; private double balance = 100000; public WorkerThread(Socket connection){ account = new ArrayList<String>(); history = new ArrayList<String>(); this.con=connection; } @Override public void run() { final DecimalFormat df=new DecimalFormat("#.##"); Communicator c = new Communicator(con); //first exchange of data,read user identification String username=" ",md5Password =" "; String msg = c.read(); if(msg!=null){ String[] p = msg.split(";"); username = p[0]; md5Password=p[1]; } //accept if(Server.database.containsKey(username)){ if(Server.database.get(username).equals(md5Password)){ c.send("successful"); }else{ c.send("rejected"); } } while(true){ msg =c.read(); if(msg==null)msg=" "; if(msg.substring(0, 2).equalsIgnoreCase("**")){ switch(msg.charAt(2)){ //clinet activity list; case '1': String s=""; for(int i = 500001; i < 500006; i ++){ s +=i+" "+Market.getStocks().get(i)+"^"; } c.send(s); break; case '2': //clinet activity view; c.send("$"+ df.format(Market.getPrice(Integer.parseInt(msg.substring(4))))); break; case '3': //clinet activity buy; String[] parts = msg.substring(4).split("\\^"); final int bid; final int bamount; final double bprice; final int btime; if(parts.length==2){ bid = Integer.parseInt(parts[0]); bamount =Integer.parseInt(parts[1]); double singlePrice =Market.getPrice(bid); double totalPrice = singlePrice*bamount; if(totalPrice>balance){ c.send("transaction field, insufficient fund"); }else{ addToAccount(bid,bamount,singlePrice); balance -=totalPrice; c.send("transaction succeed at $"+df.format(singlePrice)+" Total cost -$"+df.format(totalPrice)+" Current balance $"+df.format(balance)); history.add("buying "+bamount +" Stock("+bid+") succeed at $"+df.format(singlePrice)+" Total cost -$"+df.format(totalPrice)+" balance $"+df.format(balance)); } }else if( parts.length==4){ bid = Integer.parseInt(parts[0]); bamount =Integer.parseInt(parts[1]); bprice = Double.parseDouble(parts[2]); btime =Integer.parseInt(parts[3]); double totalPrice = bprice*bamount; if(totalPrice>balance){ c.send("transaction field, insufficient fund"); }else{ c.send("Buying request is now on the system valid for "+btime+" sec, please check you account history to see if this is successful"); Thread buy = new Thread(new Runnable(){ public void run(){ boolean succeed=false; for (int i = 0; i<btime/2;i++){ double singlePrice =Market.getPrice(bid); if(singlePrice<=bprice){ double totalPrice = singlePrice*bamount; if(balance<totalPrice)break; balance -=totalPrice; addToAccount(bid,bamount,singlePrice); history.add("buying "+bamount +" Stock("+bid+") succeed at $"+df.format(singlePrice)+" Total cost -$"+df.format(totalPrice)+" balance $"+df.format(balance)); succeed=true; break; } try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(!succeed)history.add("buying request timeout:"+bamount +"Stock("+bid+") at $"+bprice); } }); buy.start(); } } break; //clinet activity sell; case '4': String[] sparts = msg.substring(4).split("\\^"); final int sid; final int samount; final double sprice; final int stime; if(sparts.length==2){ sid = Integer.parseInt(sparts[0]); samount =Integer.parseInt(sparts[1]); double singlePrice =Market.getPrice(sid); double totalPrice = singlePrice*samount; int totalAmount = numOfStock(sid); if(totalAmount ==-1){ c.send("transaction field, you dont have stock "+sid); } else if(samount>totalAmount){ c.send("transaction field, you dont have enough stock"); }else{ removeFromAccount(sid,samount); balance +=totalPrice; c.send("transaction succeed at $"+df.format(singlePrice)+" Total imcome +$"+df.format(totalPrice)+" Current balance $"+df.format(balance)); history.add("Selling "+samount +" Stock("+sid+") succeed at $"+df.format(singlePrice)+" Total income +$"+df.format(totalPrice)+" balance $"+df.format(balance)); } }else if( sparts.length==4){ sid = Integer.parseInt(sparts[0]); samount =Integer.parseInt(sparts[1]); sprice = Double.parseDouble(sparts[2]); stime =Integer.parseInt(sparts[3]); int totalAmount = numOfStock(sid); if(totalAmount ==-1){ c.send("transaction field, you dont have stock "+sid); } else if(samount>totalAmount){ c.send("transaction field, you dont have enough stock"); }else{ c.send("Selling request is now on the system valid for "+stime+" sec, please check you account history to see if this is successful"); Thread sell = new Thread(new Runnable(){ public void run(){ boolean succeed=false; for (int i = 0; i<stime/2;i++){ double singlePrice =Market.getPrice(sid); if(singlePrice>=sprice){ double totalPrice = singlePrice*samount; if(!removeFromAccount(sid,samount))break; balance +=totalPrice; history.add("selling "+samount +"Stock("+sid+") succeed at $"+df.format(singlePrice)+" Total income +$"+df.format(totalPrice)+" balance $"+df.format(balance)); succeed=true; break; } try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(!succeed)history.add("selling request timeout:"+samount +"Stock("+sid+") at $"+sprice); } }); sell.start(); } } break; //clinet activity account; case '5': String ss=""; ss +="Current Balance :"+balance+"#"; ss +="Stock Amount Average Price #"; ss +="------------------------------------ #"; for(String a :account){ ss +=a+"#"; } ss+="Transaction History #"; for(String h :history){ ss +=h+"#"; } c.send(ss); break; default: break; } } } } private boolean removeFromAccount(int sid, int samount) { boolean succeed= false; for(String s :account){ int index=0; if(Integer.parseInt(s.substring(0, 6))==sid){ ; String [] p = s.split("\\^"); int amount = Integer.parseInt(p[1]); double price = Double.parseDouble(p[2]); if(samount > amount){ }else if(samount ==amount){ account.remove(index); succeed=true; }else{ int newAmount = amount -samount; double newPrice = price; account.remove(index); account.add(sid+"^"+newAmount+"^"+newPrice); succeed=true; } break; } index++; } return succeed; } private void addToAccount(int bid, int bamount ,double singlePrice){ boolean exist =false; for(String s :account){ int index=0; if(Integer.parseInt(s.substring(0, 6))==bid){ exist = true; String [] p = s.split("\\^"); int amount = Integer.parseInt(p[1]); double price = Double.parseDouble(p[2]); int newAmount = amount +bamount; double newPrice = (amount*price +bamount*singlePrice)/newAmount; account.remove(index); account.add(bid+"^"+newAmount+"^"+newPrice); break; } index++; } if(!exist)account.add(bid+"^"+bamount+"^"+singlePrice); } private int numOfStock(int bid){ boolean exist =false; int num=-1; for(String s :account){ if(Integer.parseInt(s.substring(0, 6))==bid){ exist = true; String [] p = s.split("\\^"); num = Integer.parseInt(p[1]); break; } } if(!exist){ return num; }else{ return num; } } }
e02c4721f88190840b5ae862fe1d46d1732f018f
[ "Java" ]
2
Java
s3265176/secure-network
7dbf5bce67577dbd8f896f2d9cf3746c87c90d4e
4ed5e88fbb5cb4c1a106ff4aef360c7d0c59d744
refs/heads/main
<repo_name>jenniferlee1818/supervised-installer<file_sep>/homeassistant-supervised/DEBIAN/postrm #!/usr/bin/env bash set -e function info { echo -e "\e[32m[info] $*\e[39m"; } function warn { echo -e "\e[33m[warn] $*\e[39m"; } function error { echo -e "\e[31m[error] $*\e[39m"; exit 1; } # Undo diversions dpkg-divert --package homeassistant-supervised --remove --rename \ --divert /etc/NetworkManager/NetworkManager.conf.real /etc/NetworkManager/NetworkManager.conf dpkg-divert --package homeassistant-supervised --remove --rename \ --divert /etc/NetworkManager/system-connections/default.real /etc/NetworkManager/system-connections/default dpkg-divert --package homeassistant-supervised --remove --rename \ --divert /etc/docker/daemon.json.real /etc/docker/daemon.json dpkg-divert --package homeassistant-supervised --remove --rename \ --divert /etc/network/interfaces.real /etc/network/interfaces
822692e84a74466b607fc012c16e9d5ff5074558
[ "Shell" ]
1
Shell
jenniferlee1818/supervised-installer
a13eda0e54f6bae3f65632b43121d0cff95ed091
af0214a90a5f4a6235aaf7d74dfb884c3e5c332b
refs/heads/master
<file_sep>import React, { Component } from 'react'; import { Dialog } from '@material-ui/core'; class DialogBox extends Component { state = { open: false } static getDerivedStateFromProps(props, state) { return state = { open: props.open } } render() { return ( <Dialog open={this.state.open}> <div className="dialog_alert"> <div>{this.props.title}</div> <div>{this.props.msg}</div> </div> </Dialog> ); } } export default DialogBox;<file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import PageTop from './../utils/page_top'; import { getProductDetail, clearPayload } from './../../redux/actions/products_actions'; import { CLEAR_PRODUCT_DETAIL } from './../../redux/actions/types'; import ProductInfo from './ProductInfo'; import { CircularProgress } from '@material-ui/core'; import ProductImgs from './ProductImgs'; import { addToUserCart } from './../../redux/actions/user_actions'; import DialogBox from './../utils/dialogBox'; class Product extends Component { state = { openDialog: false } componentDidMount() { const id = this.props.match.params.id; this.props.dispatch(getProductDetail(id)).then(() => { if (!this.props.products.productDetail) { this.props.history.push('/'); } }); } componentWillUnmount() { this.props.dispatch(clearPayload(CLEAR_PRODUCT_DETAIL)); } addToCartHandler = (id) => { this.props.user.userData.isAuth ? this.props.dispatch(addToUserCart(id)) : this.setState({ openDialog: true }, () => { setTimeout(() => { this.setState({ openDialog: false }); }, 3000); }); } render() { const product = this.props.products.productDetail; return ( <div> <PageTop title='Product detail' /> <div className="container"> { product ? <div className="product_detail_wrapper"> <div className="left"> <div style={{width:'500px'}}> <ProductImgs product={product} /> </div> </div> <div className="right"> <ProductInfo product={product} addToCart={(id) => this.addToCartHandler(id)} /> </div> </div> : <div className="main_loader"> <CircularProgress style={{color:'#00bcd4'}} thickness={7} /> </div> } </div> <DialogBox open={this.state.openDialog} title='Atention!!!' msg='You need to log in to add products to you cart' /> </div> ); } } const mapStateToProps = (state) => { return { products: state.products, user: state.user } } export default connect(mapStateToProps)(Product);<file_sep>export const LOGIN_USER = 'LOGIN_USER'; export const LOGOUT_USER = 'LOGOUT_USER'; export const REGISTER_USER = 'REGISTER_USER'; export const AUTH_USER = 'AUTH_USER'; export const ADD_TO_USER_CART = 'ADD_TO_USER_CART'; export const REMOVE_FROM_USER_CART = 'REMOVE_FROM_USER_CART'; export const GET_USER_CART_ITEMS = 'GET_USER_CART_ITEMS'; export const SUCCESS_USER_BUY = 'SUCCESS_USER_BUY'; export const UPDATE_USER_DATA = 'UPDATE_USER_DATA'; export const CLEAR_UPDATE_USER_DATA = 'CLEAR_UPDATE_USER_DATA'; export const GET_PRODUCTS_BY_SELL = 'GET_PRODUCTS_BY_SELL'; export const GET_PRODUCTS_BY_ARRIVAL = 'GET_PRODUCTS_BY_ARRIVAL'; export const GET_PRODUCTS_TO_SHOP = 'GET_PRODUCTS_TO_SHOP'; export const ADD_PRODUCT = 'ADD_PRODUCT'; export const CLEAR_PRODUCT = 'CLEAR_PRODUCT'; export const GET_PRODUCT_DETAIL = 'GET_PRODUCT_DETAIL'; export const CLEAR_PRODUCT_DETAIL = 'CLEAR_PRODUCT_DETAIL'; export const GET_BRANDS = 'GET_BRANDS'; export const GET_WOODS = 'GET_WOODS'; export const ADD_BRAND = 'ADD_BRAND'; export const ADD_WOOD = 'ADD_WOOD'; export const CLEAR_BRAND = 'CLEAR_BRAND'; export const CLEAR_WOOD = 'CLEAR_WOOD'; export const GET_SITE_DATA = 'GET_SITE_DATA'; export const UPDATE_SITE_DATA = 'UPDATE_SITE_DATA';<file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import FontAwesomeIcon from '@fortawesome/react-fontawesome'; import { faFrown, faSmile } from '@fortawesome/fontawesome-free-solid'; import UserLayout from './../../hoc/UserLayout'; import { getCartItems, removeFromUserCart, successUserBuy } from '../../redux/actions/user_actions'; import ProductBlock from '../utils/User/ProductBlock'; import Paypal from './../utils/paypal'; class Cart extends Component { state = { loading: true, total: 0, showTotal: false, showSuccess: false, } componentDidMount() { let cartItems = []; let user = this.props.user; if (user.userData.cart && user.userData.cart.length > 0) { user.userData.cart.forEach(item => { cartItems.push(item.id); }); this.props.dispatch(getCartItems(cartItems, user.userData.cart)).then(() => { if (this.props.user.cartDetail.length > 0) { this.calcTotal(this.props.user.cartDetail); } }); } } calcTotal = (cartDetail) => { let total = 0; cartDetail.forEach(item => { total += parseInt(item.price, 10) * item.quantity; }); this.setState({ total, showTotal: true }); } removeFromCart = (id) => { this.props.dispatch(removeFromUserCart(id)).then(() => { if (this.props.user.cartDetail.length <= 0) { this.setState({ showTotal: false }); } else { this.calcTotal(this.props.user.cartDetail); } }); } showNoItemMessage = () => ( <div className="cart_no_items"> <FontAwesomeIcon icon={faFrown}/> <div> You don't have items in your cart </div> </div> ) transErr = (data) => { console.log(data); } transCanceled = (data) => { console.log(data); } transSuccess = (data) => { this.props.dispatch(successUserBuy({ cartDetail: this.props.user.cartDetail, paymentData: data })).then(() => { if (this.props.user.successBuy) { this.setState({ showTotal: false, showSuccess: true }); } }) } render() { return ( <UserLayout> <div> <h1>My cart</h1> <div className="user_cart"> <ProductBlock products={this.props.user} type='cart' removeItem={(id) => this.removeFromCart(id)} /> { this.state.showTotal ? <div> <div className="user_cart_sum"> <div> Total amount: ${this.state.total} </div> </div> </div> : this.state.showSuccess ? <div className="cart_no_items"> <FontAwesomeIcon icon={faSmile}/> <div> THANK YOU. </div> <div> Your order is complete. </div> </div> : this.showNoItemMessage() } </div> { this.state.showTotal ? <div className="paypal_button_container"> <Paypal toPay={this.state.total} transErr={(data) => this.transErr(data)} transCanceled={(data) => this.transCanceled(data)} onSuccess={(data) => this.transSuccess(data)} /> </div> : null } </div> </UserLayout> ); } } const mapStateToProps = (state) => { return { user: state.user } } export default connect(mapStateToProps)(Cart);<file_sep>import React from 'react'; import UserLayout from './../../hoc/UserLayout'; import UpdatePersonaNfo from './UpdatePersonaNfo'; const UpdateProfile = () => { return ( <UserLayout> <h1>Profile</h1> <UpdatePersonaNfo/> </UserLayout> ); }; export default UpdateProfile;<file_sep>import React from 'react'; import MyButton from './../utils/buttom'; const Home_Promotions = (props) => { const promotions = { img: '/images/featured/featured_home_3.jpg', lineOne: 'Up to 40% off', lineTwo: 'In second hand guitars', linkTitle: 'Shop now', linkTo: '/shop', } const renderPromotions = () => ( promotions ? <div className="home_promotion_img" style={{ background:`url(${promotions.img})` }}> <div className="tag title">{promotions.lineOne}</div> <div className="tag low_title">{promotions.lineTwo}</div> <div> <MyButton type='default' title={promotions.linkTitle} linkTo={promotions.linkTo} addStyles={{ margin:'10px 0 0 0' }} /> </div> </div> : null ) return ( <div className='home_promotion'> {renderPromotions()} </div> ); }; export default Home_Promotions;<file_sep>import React from 'react'; import FontAwesomeIcon from '@fortawesome/react-fontawesome'; import { faTruck, faCheck, faTimes } from '@fortawesome/fontawesome-free-solid'; import MyButton from './../utils/buttom'; const ProductInfo = (props) => { const showProdTags = (product) => ( <div className="product_tags"> { product.shipping ? <div className="tag"> <div><FontAwesomeIcon icon={faTruck}/></div> <div className="tag_text"> <div>Free shipping</div> <div>And return</div> </div> </div> : null } { product.available ? <div className="tag"> <div><FontAwesomeIcon icon={faCheck}/></div> <div className="tag_text"> <div>Available</div> <div>in store</div> </div> </div> : <div className="tag"> <div><FontAwesomeIcon icon={faTimes}/></div> <div className="tag_text"> <div>Not available</div> <div>in store</div> </div> </div> } </div> ) const showProdActions = (product) => ( <div className="product_actions"> <div className="price">{product.price} €</div> <div className="cart"> <MyButton type='add_to_cart_link' runAction={() => props.addToCart(product._id)} /> </div> </div> ) const showProdSpecs = (product) => ( <div className="product_specifications"> <h2>Specs</h2> <div> <div className="item"><strong>Frets:</strong> {product.frets}</div> <div className="item"><strong>Wood:</strong> {product.wood.name}</div> </div> </div> ) const product = props.product; return ( <div> <h1>{product.brand.name} {product.name}</h1> <p> {product.description} </p> {showProdTags(product)} {showProdActions(product)} {showProdSpecs(product)} </div> ); }; export default ProductInfo;<file_sep>import React from 'react'; import { Switch, Route } from 'react-router-dom'; import Layout from './hoc/Layout'; import Auth from './hoc/Auth'; import Home from './components/Home'; import RegisterLogin from './components/RegisterLogin/index'; import Register from './components/RegisterLogin/Register'; import UserDashboard from './components/User/index'; import Shop from './components/Shop/index'; import AddProducts from './components/User/Admin/AddProducts'; import ManageCategories from './components/User/Admin/ManageCategories'; import Product from './components/Product/index'; import Cart from './components/User/Cart'; import UpdateProfile from './components/User/UpdateProfile'; import ManageSite from './components/User/Admin/ManageSite'; import PageNotFound from './components/utils/page_not_found'; import AddFile from './components/User/Admin/AddFile'; import ForgotPassword from './components/User/ResetPassword/index'; import ResetPassword from './components/User/ResetPassword/ResetPassword'; const Routes = () => { return ( <Layout> <Switch> <Route path='/user/dashboard' exact component={Auth(UserDashboard, true)}/> <Route path='/user/cart' exact component={Auth(Cart, true)}/> <Route path='/user/profile' exact component={Auth(UpdateProfile, true)}/> <Route path='/admin/add_product' exact component={Auth(AddProducts, true)}/> <Route path='/admin/manage_categories' exact component={Auth(ManageCategories, true)}/> <Route path='/admin/site_info' exact component={Auth(ManageSite, true)}/> <Route path='/admin/add_file' exact component={Auth(AddFile, true)}/> <Route path='/register' exact component={Auth(Register, false)}/> <Route path='/register_login' exact component={Auth(RegisterLogin, false)}/> <Route path='/forgot_password' exact component={Auth(ForgotPassword, false)}/> <Route path='/reset_password/:token' exact component={Auth(ResetPassword, false)}/> <Route path='/shop' exact component={Auth(Shop, null)}/> <Route path='/product_detail/:id' exact component={Auth(Product, null)}/> <Route path='/' exact component={Auth(Home, null)}/> <Route component={Auth(PageNotFound)}/> </Switch> </Layout> ) } export default Routes; <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import UserLayout from './../../../hoc/UserLayout'; import FormField from './../../utils/Form/FormField'; import { update, generateData, isFormValid, populateOptionsFields, resetFields } from '../../utils/Form/FormActions'; import { getBrands, getWoods, addProducts, clearPayload } from './../../../redux/actions/products_actions'; import { fretsSelect } from '../../utils/Form/fixed_categories'; import FileUpload from './../../utils/Form/FileUpload'; import { CLEAR_PRODUCT } from './../../../redux/actions/types'; class AddProducts extends Component { state = { formError: false, formSuccess: false, formData: { images: { value: [], validation: { required: false, }, valid: true, touched: false, validationMessage: '', showLabel: false, }, name: { element: 'input', value: '', config: { label: 'Product name', name: 'name_input', type: 'text', placeholder: 'Enter the name of the product', }, validation: { required: true, }, valid: false, touched: false, validationMessage: '', showLabel: true, }, description: { element: 'textarea', value: '', config: { label: 'Product description', name: 'description_input', type: 'text', placeholder: 'Enter the description of the product', }, validation: { required: true, }, valid: false, touched: false, validationMessage: '', showLabel: true, }, price: { element: 'input', value: '', config: { label: 'Product price', name: 'price_input', type: 'number', placeholder: 'Enter the price of the product', }, validation: { required: true, }, valid: false, touched: false, validationMessage: '', showLabel: true, divider: 'form_devider', }, brand: { element: 'select', value: '', config: { label: 'Product brand', name: 'brand_input', type: 'text', placeholder: 'Select the brand of the product', options: [] }, validation: { required: true, }, valid: false, touched: false, validationMessage: '', showLabel: true, }, shipping: { element: 'select', value: '', config: { label: 'Product shipping', name: 'shipping_input', type: 'text', placeholder: 'Select the shipping of the product', options: [ {key:true,value:'Yes'}, {key:false,value:'No'}, ] }, validation: { required: true, }, valid: false, touched: false, validationMessage: '', showLabel: true, }, available: { element: 'select', value: '', config: { label: 'Product available in stock', name: 'available_input', type: 'text', placeholder: 'Select if the product is available', options: [ {key:true,value:'Yes'}, {key:false,value:'No'}, ] }, validation: { required: true, }, valid: false, touched: false, validationMessage: '', showLabel: true, divider: 'form_devider', }, wood: { element: 'select', value: '', config: { label: 'Product wood', name: 'wood_input', type: 'text', placeholder: 'Select the wood of the product', options: [] }, validation: { required: true, }, valid: false, touched: false, validationMessage: '', showLabel: true, }, frets: { element: 'select', value: '', config: { label: 'Product frets', name: 'frets_input', type: 'text', placeholder: 'Select the frets of the product', options: fretsSelect }, validation: { required: true, }, valid: false, touched: false, validationMessage: '', showLabel: true, divider: 'form_devider', }, publish: { element: 'select', value: '', config: { label: 'Product publish in website', name: 'publish_input', type: 'text', placeholder: 'Select if the product is publish', options: [ {key:true,value:'Public'}, {key:false,value:'Hidden'}, ] }, validation: { required: true, }, valid: false, touched: false, validationMessage: '', showLabel: true, }, } } componentDidMount() { const formData = this.state.formData; this.props.dispatch(getBrands()).then(() => { const newFormData = populateOptionsFields(formData, this.props.products.brands, 'brand'); this.updateFields(newFormData); }); this.props.dispatch(getWoods()).then(() => { const newFormData = populateOptionsFields(formData, this.props.products.woods, 'wood'); this.updateFields(newFormData); }); } updateForm = (element) => { const newFormData = update(element, this.state.formData, 'products'); this.setState({ formError: false, formData: newFormData, }); } resetFieldHandler = () => { const formData = resetFields(this.state.formData); this.setState({ formError: false, formSuccess: true, formData }); setTimeout(() => { this.setState({ formSuccess: false }, () => this.props.dispatch(clearPayload(CLEAR_PRODUCT))); }, 3000); } submitForm = (event) => { event.preventDefault(); let dataToSubmit = generateData(this.state.formData, 'products'); let formIsValid = isFormValid(this.state.formData, 'products'); if (formIsValid) { this.props.dispatch(addProducts(dataToSubmit)).then(() => { if (this.props.products.addProduct.success) { this.resetFieldHandler(); } else { this.setState({ formError: true }); } }); } else { this.setState({ formError: true }); } } updateFields = (formData) => { this.setState({ formData }); } imagesHandler = (images) => { const formData = {...this.state.formData}; formData['images'].value = images; this.setState({ formData }); } renderForm = (formData) => { let keys = []; Object.keys(formData).forEach((key) => { keys.push(key); }); return this.renderFields(formData, keys); } renderFields = (formData, keys) => ( <div> { keys.map(key => ( <div key={`${key}parent`}> { key === 'images' ? <FileUpload imagesHandler={(images) => this.imagesHandler(images)} reset={this.state.formSuccess} /> : <FormField key={key} id={key} formData={formData[key]} change={(element) => this.updateForm(element)} /> } { formData[key].divider ? <div key={`${key}_divider`} className={formData[key].divider}></div> : null } </div> )) } </div> ) render() { return ( <UserLayout> <div> <h1>Add product</h1> <form onSubmit={(event) => this.submitForm(event)}> {this.renderForm(this.state.formData)} { this.state.formSuccess ? <div className="form_success"> Success </div> : null } { this.state.formError ? <div className="error_label"> Please check your data </div> : null } <button onClick={(event) => this.submitForm(event)}> Add product </button> </form> </div> </UserLayout> ); } } function mapStateToProps(state) { return { user: state.user, products: state.products } } export default connect(mapStateToProps)(AddProducts);<file_sep>const express = require('express'); // Models const { Brand } = require('../models/brand'); const { Wood } = require('../models/wood'); // Middlewares const { auth } = require('../middleware/auth'); const { admin } = require('../middleware/admin'); const app = express(); //============================================================= // BRANDS //============================================================= app.post('/api/category/brand', auth, admin, (req, res) => { const brand = new Brand(req.body); brand.save((err, doc) => { if (err) return res.json({success: false, err}); res.status(200).json({ success: true, brand: doc }); }); }); app.get('/api/category/brands', (req, res) => { Brand.find({}, (err, brands) => { if (err) return res.status(400).send(err); res.status(200).json({ success: true, brands }); }); }); //============================================================= // WOODS //============================================================= app.post('/api/category/wood', auth, admin, (req, res) => { const wood = new Wood(req.body); wood.save((err, doc) => { if (err) return res.json({success: false, err}); res.status(200).json({ success: true, wood: doc }); }); }); app.get('/api/category/woods', (req, res) => { Wood.find({}, (err, woods) => { if (err) return res.status(400).send(err); res.status(200).json({ success: true, woods }); }); }); module.exports = app;
48f7e1eb773095b2c9343189593e47275f20fbdb
[ "JavaScript" ]
10
JavaScript
alfonzzo7/React2_Waves
c3726c36f1f4368f79882309a953a326e5de40b3
3b7b77f6383c4a93aae8a737853911ccf648f754
refs/heads/master
<file_sep>package main import ( "encoding/csv" "flag" "fmt" "html/template" "io" "math" "os" "regexp" "sort" "strconv" "strings" "github.com/pkg/errors" ) var outRound = flag.Int("outround", 1, "output round") func main() { flag.Parse() if flag.NArg() != 2 { fmt.Println(`usages: 1. wfsports start names.csv : generates the first pairings as round1.csv 1a. wfsports -outround=2 start names.csv : generates pairings as round2.csv 2. wfsports next roundN.csv : generates the next pairings as round{N+1}.csv or declares the winner 3. wfsports show roundN.csv : outputs an HTML page displaying the pairings for round N 3. wfsports startfinals : generates round11.csv from round1.csv ... round10.csv The CSV files do not have headers. names.csv has only a single column: the names of the players. roundN.csv has three columns: player1,player2,winner. `) os.Exit(1) } command := flag.Arg(0) filename := flag.Arg(1) if err := run(command, filename); err != nil { fmt.Printf("wfsports: error: %v\n", err) os.Exit(1) } } func run(command, filename string) error { switch command { case "start": return start(filename) case "next": return next(filename) case "show": return show(filename) case "startfinals": return startfinals() default: return fmt.Errorf("unrecognized command: %s, want start or next", command) } } func start(filename string) error { recs, err := getRecords(filename) if err != nil { return errors.Wrap(err, "getting records") } // Randomize order of the names by making them the keys of a map. namesMap := make(map[string]bool) for _, r := range recs { namesMap[r[0]] = true } var names []string for name := range namesMap { names = append(names, name) } switch len(names) { case 0: return errors.New("no players listed") case 1: fmt.Println(names[0], "is the winner!") default: roundFilename := fmt.Sprintf("round%d.csv", *outRound) if err := generateRoundFile(roundFilename, names); err != nil { return errors.Wrap(err, "generating round file") } fmt.Println("wrote", roundFilename) } return nil } type player struct { name string wins int } func startfinals() error { playerWins := make(map[string]int) for i := 1; i <= 10; i++ { filename := fmt.Sprintf("round%d.csv", i) recs, err := getRecords(filename) if err != nil { return errors.Wrap(err, "getting records") } for _, r := range recs { w := r[2] playerWins[w]++ } } var players []player for p, w := range playerWins { players = append(players, player{name: p, wins: w}) } // Take the top 32 players if len(players) >= 32 { sort.Slice(players, func(i, j int) bool { return players[i].wins > players[j].wins }) players = players[:32] } // Randomize order of the names by making them the keys of a map. namesMap := make(map[string]bool) for _, p := range players { namesMap[p.name] = true } var names []string for name := range namesMap { names = append(names, name) } switch len(names) { case 0: return errors.New("no players listed") case 1: fmt.Println(names[0], "is the winner!") default: roundFilename := "round11.csv" if err := generateRoundFile(roundFilename, names); err != nil { return errors.Wrap(err, "generating round file") } fmt.Println("wrote", roundFilename) } return nil } var roundRx = regexp.MustCompile(`round(\d+).csv`) func next(doneRoundFilename string) error { recs, err := getRecords(doneRoundFilename) if err != nil { return errors.Wrap(err, "getting records") } // Get the winners of the done round, and randomize their order by // making them the keys of a map. namesMap := make(map[string]bool) for _, r := range recs { namesMap[r[2]] = true } var names []string for name := range namesMap { names = append(names, name) } switch len(names) { case 0: return errors.New("no players listed") case 1: fmt.Println(names[0], "is the winner!") default: m := roundRx.FindStringSubmatch(doneRoundFilename) if len(m) != 2 { return fmt.Errorf("given filename %s failed to match pattern %s", doneRoundFilename, roundRx) } k, err := strconv.Atoi(m[1]) if err != nil { return fmt.Errorf("given filename %s has an integer part that somehow doesn't parse (%v), probably a bug", doneRoundFilename, err) } roundFilename := fmt.Sprintf("round%d.csv", k+1) if err := generateRoundFile(roundFilename, names); err != nil { return errors.Wrap(err, "generating round file") } fmt.Println("wrote", roundFilename) } return nil } func show(roundFilename string) error { recs, err := getRecords(roundFilename) if err != nil { return errors.Wrap(err, "getting records") } for i := range recs { // Eliminate the winner column, because we aren't displaying winners here. recs[i] = recs[i][:2] } t, err := template.New("show").Parse(` <!DOCTYPE html> <html> <head> <style> #players { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; border-collapse: collapse; width: 100%; } #players td, #customers th { border: 1px solid #ddd; padding: 8px; } #players tr:nth-child(even){background-color: #f2f2f2;} #players tr:hover {background-color: #ddd;} #players th { padding-top: 12px; padding-bottom: 12px; text-align: left; background-color: #4CAF50; color: white; } </style> </head> <body> <table id="players"> <tr> <th>Player 1</th> <th>Player 2</th> </tr> {{range .}} <tr> {{range .}} <td>{{.}}</td> {{end}} </tr> {{end}} </table> </body> </html> `) if err != nil { return errors.Wrap(err, "parsing HTML template") } htmlFilename := "table.html" f, err := os.Create(htmlFilename) if err != nil { return errors.Wrap(err, "creating HTML output file") } defer f.Close() if err := t.Execute(f, recs); err != nil { return errors.Wrap(err, "executing template") } fmt.Println("wrote", htmlFilename) return nil } func generateRoundFile(roundFilename string, names []string) error { roundFile, err := os.Create(roundFilename) if err != nil { return errors.Wrap(err, "creating round file") } defer roundFile.Close() n := roundDownToPowerOfTwo(len(names)) // Output pairings so that n players are playing. if n > 1 { for i := 0; i < n; i += 2 { fmt.Fprintf(roundFile, "%s,%s,\n", names[i], names[i+1]) } } // Output trivial matches where the remaining players play against themselves and win. for i := n; i < len(names); i++ { fmt.Fprintf(roundFile, "%s,%s,%s\n", names[i], names[i], names[i]) } return nil } // roundDownToPowerOfTwo finds the closest power of 2 below n. func roundDownToPowerOfTwo(k int) int { return int(math.Pow(2.0, math.Floor(math.Log2(float64(k))))) } func getRecords(filename string) ([][]string, error) { f, err := os.Open(filename) if err != nil { return nil, errors.Wrap(err, "opening CSV file") } defer f.Close() r := csv.NewReader(f) var recs [][]string line := 1 for { record, err := r.Read() if err == io.EOF { break } if err != nil { return nil, errors.Wrap(err, "reading line of CSv") } for _, name := range record { if len(strings.TrimSpace(name)) == 0 { return nil, fmt.Errorf("empty name encountered on line %d", line) } } recs = append(recs, record) line++ } return recs, nil } <file_sep># wfsports: WeFunder Sports challenge Start by running ``` $ wfsports start names.csv ``` This outputs a file called round1.csv. Each row of this file has the names of two players competing in this round. As the organizer, you get to add the name of the winner to each of the rows once the round is done. If the number of players isn't a power of two, there will be some players who get a free pass to go to the next round. They will show up in rows like `Alice,Alice,Alice`, meaning that Alice has played against her self and won. After entering the winners in round1.csv, run ``` $ wfsports next round1.csv ``` That will make random pairs of winners from round 1 and output round2.csv in the same format as round1.csv. Once they play each other, you as the organizer get to add the winners' names as in round1, and repeat running `wfsports next round2.csv` and repeat the process until someone wins the whole tournament. To display the players for round N on the projector, run this (on Mac): ``` $ wfsports show roundN.csv $ open table.html ``` ## 10 rounds of random pairing followed by selecting the top 32 players for ## single elimination finals Start by running the following: ``` $ for i in $(seq 10); do wfsports -outround=$i start names.csv; done wrote round1.csv wrote round2.csv ... wrote round10.csv ``` Then play round 1 according to round1.csv, recording the winners to round1.csv. Then play round 2 according to round1.csv, recording the winners to round2.csv. ... up to round 10. Then run ``` wfsports startfinals ``` which will generate round11.csv. Play round 11, record the winners to round11.csv, then run ``` wfsports next round11.csv ``` and proceed as before for single elimination.
c2f41d73f152a72defcb1e76d20dc6e4f6a161f4
[ "Markdown", "Go" ]
2
Go
ijt/wfsports
5358d23b3d9309f87350c3ecc8880f17ff95af9f
12c69200a43ecafa0c9fca46e7212cc00e1b31ef
refs/heads/master
<repo_name>abagmut/FileTemplateSwift<file_sep>/Cocoa Touch Class.xctemplate/UIViewControllerSwift/___FILEBASENAME___ViewController.swift // // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ // import UIKit class ___FILEBASENAMEASIDENTIFIER___ViewController: ___VARIABLE_cocoaTouchSubclass___ { override func loadView() { view = ___FILEBASENAMEASIDENTIFIER___View() } } <file_sep>/Cocoa Touch Class.xctemplate/UIViewControllerSwift/___FILEBASENAME___View.swift // // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ // import UIKit class ___FILEBASENAMEASIDENTIFIER___View: UIView { required init(coder aDecoder: NSCoder){ fatalError("init(coder:) has not been implemented") } init() { super.init(frame: CGRectZero) } }
25397af7714ce0d1f3afd37f62a22498dca9d763
[ "Swift" ]
2
Swift
abagmut/FileTemplateSwift
277a34a34c73d450d5ec18607bd5a0dc13bae577
2c6b8e390549f467ce7a22579dd59d1757dcdd02
refs/heads/main
<file_sep>package main import ( "database/sql" "log" "os" "github.com/gin-gonic/gin" "github.com/jadoreran/inception/domain" "github.com/jadoreran/inception/provider" "github.com/jadoreran/inception/repository" "github.com/jadoreran/inception/service" _ "github.com/mattn/go-sqlite3" ) func main() { os.Remove("inception.db") file, err := os.Create("inception.db") if err != nil { log.Println(err.Error()) } file.Close() db, _ := sql.Open("sqlite3", "./inception.db") defer db.Close() createTable(db) repository := repository.NewPaymentRepository(db) provider := provider.NewOmise() service := service.NewService(repository, provider) r := gin.Default() r.POST("/payment", func(c *gin.Context) { data := &domain.Payment{} c.Bind(data) payment := domain.NewPayment(data.Amount, data.Currency, data.Source) id, err := service.CreatePayment(payment) if err != nil { log.Println(err) c.JSON(404, gin.H{ "error": err, }) } else { c.JSON(200, gin.H{ "payload": id, }) } }) r.GET("/payment/:id", func(c *gin.Context) { id := c.Param("id") payment, err := service.FindPaymentByID(id) if err != nil { log.Println(err) c.JSON(404, gin.H{ "error": err, }) } else { c.JSON(200, gin.H{ "payload": payment, }) } }) r.GET("/payments", func(c *gin.Context) { payments, err := service.SearchPayments() if err != nil { log.Println(err) c.JSON(404, gin.H{ "error": err, }) } else { c.JSON(200, gin.H{ "payload": payments, }) } }) r.Run() } func createTable(db *sql.DB) { sqlStmt := ` create table payments ( id text PRIMARY KEY, amount integer not null, currency text not null, source text not null, created_at datetime not null, updated_at datetime not null); ` stmt, err := db.Prepare(sqlStmt) if err != nil { log.Println(err.Error()) } stmt.Exec() } <file_sep>package domain import ( "time" ) // Payment struct type Payment struct { ID string `json:"id"` Amount int `json:"amount"` Currency string `json:"currency"` Source string `json:"source"` UpdatedAt *time.Time `db:"updated_at" json:"updatedAt"` CreatedAt *time.Time `db:"created_at" json:"createdAt"` } // NewPayment Create a new payment object func NewPayment(amount int, currency string, source string) *Payment { return &Payment{ Amount: amount, Currency: currency, Source: source, } } <file_sep>package provider import ( "log" "github.com/omise/omise-go" "github.com/omise/omise-go/operations" ) const ( omisePublicKey = "pkey_test_5msppk1y7gre58fgshk" omiseSecretKey = "skey_test_5msppk1y79ktkwocson" ) // Provider interface type Provider interface { CreateCharge(amount int64, currency string, sourceType string) error } // Omise struct type Omise struct { } // NewOmise a new Omise payment object func NewOmise() *Omise { return &Omise{} } // CreateCharge use type as source func (*Omise) CreateCharge(amount int64, currency string, sourceType string) error { client, err := omise.NewClient(omisePublicKey, omiseSecretKey) if err != nil { log.Println(err) return err } // Creates a charge from the token source, createSource := &omise.Source{}, &operations.CreateSource{ Amount: amount, Currency: currency, Type: sourceType, } if err := client.Do(source, createSource); err != nil { log.Println(err) return err } charge, createCharge := &omise.Charge{}, &operations.CreateCharge{ Amount: amount, Currency: currency, ReturnURI: "http://www.example.com", Source: source.ID, } if err := client.Do(charge, createCharge); err != nil { log.Println(err) return err } return nil } <file_sep>package repository import ( "database/sql" "log" "time" "github.com/google/uuid" "github.com/jadoreran/inception/domain" ) // Store interface type Store interface { Insert(p *domain.Payment) (string, error) GetByID(id string) (*domain.Payment, error) Search() (*[]domain.Payment, error) } // PaymentRepository struct type PaymentRepository struct { database *sql.DB } // NewPaymentRepository Create a new repository func NewPaymentRepository(database *sql.DB) *PaymentRepository { return &PaymentRepository{database: database} } // Insert a new record func (r *PaymentRepository) Insert(p *domain.Payment) (string, error) { tx, err := r.database.Begin() if err != nil { log.Println(err) return "", err } stmt, err := tx.Prepare(`INSERT INTO payments(id, amount, currency, source, created_at, updated_at) VALUES (?, ?, ?, ?, datetime('now'), datetime('now'))`) if err != nil { log.Println(err) } defer stmt.Close() id := uuid.New() _, err = stmt.Exec(id, p.Amount, p.Currency, p.Source) if err != nil { log.Println(err) return "", err } tx.Commit() return id.String(), nil } // GetByID get a single payment func (r *PaymentRepository) GetByID(id string) (*domain.Payment, error) { stmt, err := r.database.Prepare("select * from payments where id = ?") if err != nil { log.Println(err) return nil, err } defer stmt.Close() var ID string var amount int var currency string var source string var createdAt *time.Time var updatedAt *time.Time err = stmt.QueryRow(id).Scan(&ID, &amount, &currency, &source, &createdAt, &updatedAt) if err != nil { log.Println(err) return nil, err } return &domain.Payment{ ID: ID, Amount: amount, Currency: currency, Source: source, CreatedAt: createdAt, UpdatedAt: updatedAt, }, nil } // Search payments func (r *PaymentRepository) Search() (*[]domain.Payment, error) { payments := []domain.Payment{} rows, err := r.database.Query("select * from payments") if err != nil { log.Println(err) return nil, err } defer rows.Close() for rows.Next() { var ID string var amount int var currency string var source string var createdAt *time.Time var updatedAt *time.Time err = rows.Scan(&ID, &amount, &currency, &source, &createdAt, &updatedAt) if err != nil { log.Println(err) return nil, err } payments = append(payments, domain.Payment{ ID: ID, Amount: amount, Currency: currency, Source: source, CreatedAt: createdAt, UpdatedAt: updatedAt, }) } err = rows.Err() if err != nil { log.Println(err) return nil, err } return &payments, nil } <file_sep>module github.com/jadoreran/inception go 1.14 require ( github.com/gin-gonic/gin v1.6.3 github.com/google/uuid v1.2.0 github.com/mattn/go-sqlite3 v1.14.6 github.com/omise/omise-go v1.0.5 ) <file_sep>package service_test import ( "log" "testing" "github.com/jadoreran/inception/domain" "github.com/jadoreran/inception/provider" "github.com/jadoreran/inception/repository" ) // Provider struct type omiseTest struct { } // CreateCharge use type as source func (*omiseTest) CreateCharge(amount int64, currency string, sourceType string) error { return nil } // fakePaymentRepository struct type paymentRepositoryTest struct { } // GetByID get a single payment func (*paymentRepositoryTest) Insert(p *domain.Payment) (string, error) { return "", nil } // GetByID get a single payment func (*paymentRepositoryTest) GetByID(id string) (*domain.Payment, error) { return nil, nil } // GetByID get a single payment func (*paymentRepositoryTest) Search() (*[]domain.Payment, error) { return nil, nil } // fakePaymentServicer struct type paymentServiceTest struct { repository repository.Store provider provider.Provider } // newFakePaymentService Create a new repository func newPaymentServiceTest(r repository.Store, p provider.Provider) *paymentServiceTest { return &paymentServiceTest{repository: r, provider: p} } // CreatePayment a new payment func (s *paymentServiceTest) CreatePayment(p *domain.Payment) (string, error) { err := s.provider.CreateCharge(int64(p.Amount), p.Currency, p.Source) if err != nil { log.Println(err) return "", err } id, err := s.repository.Insert(p) if err != nil { log.Println(err) return "", err } return id, nil } func TestCreatePayment(t *testing.T) { repository := &paymentRepositoryTest{} provider := &omiseTest{} service := newPaymentServiceTest(repository, provider) payment := domain.Payment{} _, err := service.CreatePayment(&payment) if err != nil { t.Error(err) } } <file_sep>package service import ( "log" "github.com/jadoreran/inception/domain" "github.com/jadoreran/inception/provider" "github.com/jadoreran/inception/repository" ) // PaymentServicer interface type PaymentServicer interface { CreatePayment(p *domain.Payment) (string, error) } // PaymentService struct type PaymentService struct { repository repository.Store provider provider.Provider } // NewService Create a new repository func NewService(r repository.Store, p provider.Provider) *PaymentService { return &PaymentService{repository: r, provider: p} } // CreatePayment a new payment func (s *PaymentService) CreatePayment(p *domain.Payment) (string, error) { err := s.provider.CreateCharge(int64(p.Amount), p.Currency, p.Source) if err != nil { log.Println(err) return "", err } id, err := s.repository.Insert(p) if err != nil { log.Println(err) return "", err } return id, nil } // FindPaymentByID find a single payment record func (s *PaymentService) FindPaymentByID(id string) (*domain.Payment, error) { payment, err := s.repository.GetByID(id) if err != nil { log.Println(err) return nil, err } return payment, nil } // SearchPayments and return list of payments func (s *PaymentService) SearchPayments() (*[]domain.Payment, error) { payments, err := s.repository.Search() if err != nil { log.Println(err) return nil, err } return payments, nil }
7978050532ee50f0082f4129b791f5cc444f1c28
[ "Go Module", "Go" ]
7
Go
jadoreran/inception
c15809348f110aa121d200a4f87224debb58a9ae
3c017e19e6e5a8e6882da1f47141a6ce335ca899
refs/heads/main
<file_sep>import { useApolloClient, useQuery } from '@apollo/client' import React from 'react' import { Link, withRouter } from 'react-router-dom' import styled from 'styled-components' import { IS_LOGGED_IN } from '../gql/query' import Spinner from './Spinner' const StyledHeader = styled.header` @media (max-width: ${({ theme }) => theme.tablet}) { padding-right: 5rem; } @media (max-width: ${({ theme }) => theme.mobile}) { flex-direction: column; align-items: flex-start; padding: 0; } display: flex; justify-content: space-between; align-items: center; padding-right: 1rem; a { padding: 1rem 0; } ` const Button = styled.button` @media (max-width: ${({ theme }) => theme.mobile}) { margin-bottom: 1rem; margin-left: 1rem; } ` const Header = ({ history }) => { const client = useApolloClient() const { data, loading, error } = useQuery(IS_LOGGED_IN, { fetchPolicy: 'cache-only', }) if (loading) return ( <> <Spinner /> </> ) if (error) return ( <> <p>Error!</p> </> ) return ( <> <StyledHeader> <h1>Buy/sell stocks</h1> {data && data.isLoggedIn ? ( <> <Button id="logout" onClick={() => { localStorage.removeItem('jsramverkProjectTradingToken') client.resetStore() client.writeQuery({ query: IS_LOGGED_IN, data: { isLoggedIn: false }, }) history.push('/') }} > logout </Button> </> ) : ( <p> <Link to={'/login'}>Sign In</Link> or{' '} <Link to={'/register'}>Sign Up</Link> </p> )} </StyledHeader> </> ) } export default withRouter(Header) <file_sep>import { useQuery } from '@apollo/client' import React from 'react' import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom' import Layout from '../components/Layout' import { IS_LOGGED_IN } from '../gql/query' import Login from '../login' import Register from '../register' import Account from './account' import Buy from './buy' import Deposit from './deposit' import Home from './home' import Sell from './sell' import Users from './users' import Spinner from '../components/Spinner' const Pages = (props) => { return ( <> <Router> <Layout> <Route exact path="/"> <Home data={props.data} maxDataPoints={props.numberOfGraphPoints} /> </Route> <Route path="/users" component={Users} /> <Route path="/register" component={Register} /> <Route path="/login" component={Login} /> <PrivateRoute path="/buy" lastData={props.lastData} component={Buy} /> <PrivateRoute path="/sell" component={Sell} /> <PrivateRoute path="/account" component={Account} /> <PrivateRoute path="/deposit" component={Deposit} /> </Layout> </Router> </> ) } const PrivateRoute = ({ component: Component, ...rest }) => { const { data, loading, error } = useQuery(IS_LOGGED_IN, { fetchPolicy: 'cache-only', }) if (loading) return <Spinner /> if (error) return <p>Error!</p> return ( <Route {...rest} render={(props) => data.isLoggedIn === true ? ( <Component {...props} {...rest} /> ) : ( <Redirect to={{ pathname: '/login', state: { from: props.location }, }} /> ) } /> ) } export default Pages <file_sep>beforeEach(() => { cy.visit('/') }) describe('Test the app', () => { const home = '.homeLink' const users = '.usersLink' const buyStocks = '.buyLink' const sellStocks = '.sellLink' const account = '.accountLink' const deposit = '.depositLink' const login = '[href="/login"]' const logout = '#logout' const hamburger = '#burger' const register = '[href="/register"]' const username = 'richard' const email = '<EMAIL>' const password = '<PASSWORD>' const numberOfLinksWhenNotLoggedIn = 2 const numberOfLinksWhenLoggedIn = 6 const stocksInAccount = '#root > div > div.wrapper > main > div div' it('has two links in navigation bar', () => { cy.get('#root > div > div > nav > ul > li').should( 'have.length', numberOfLinksWhenNotLoggedIn ) }) it('has no users registered', () => { cy.get(users).click({ multiple: true, force: true }) cy.url().should('eq', `${Cypress.config().baseUrl}users`) cy.get('main > p').should('contain', 'no users registered') }) it('fails log in when not registered', () => { cy.get(login).click() cy.login(email, password) cy.url().should('eq', `${Cypress.config().baseUrl}login`) }) it('fails to access private route', () => { cy.visit('/account') cy.url().should('eq', `${Cypress.config().baseUrl}login`) }) it('fails registering a user with short password', () => { cy.get(register).click() cy.register(username, email, '123') cy.url().should('eq', `${Cypress.config().baseUrl}register`) }) it('registers a user', () => { cy.visit('/users') cy.url().should('eq', `${Cypress.config().baseUrl}users`) cy.get('main > p').should('contain', 'no users registered') cy.get(register).click() cy.register(username, email, password) cy.url().should('eq', Cypress.config().baseUrl) cy.visit('/users') cy.url().should('eq', `${Cypress.config().baseUrl}users`) cy.get('main > div').should('have.length', 1) }) it('logs in', () => { cy.get(login).click() cy.login(email, password) cy.url().should('eq', Cypress.config().baseUrl) cy.get('#root > div > div > nav > ul > li').should( 'have.length', numberOfLinksWhenLoggedIn ) }) it('has one user registered', () => { cy.get(users).click({ multiple: true, force: true }) cy.url().should('eq', `${Cypress.config().baseUrl}users`) cy.get('main > div').should('have.length', 1) }) it('registers another user', () => { cy.get(register).click() cy.register('cypress', '<EMAIL>', password) cy.url().should('eq', Cypress.config().baseUrl) }) it('has two users registered', () => { cy.get(users).click({ multiple: true, force: true }) cy.url().should('eq', `${Cypress.config().baseUrl}users`) cy.get('main > div').should('have.length', 2) }) it('deposits', () => { cy.visit('/login') cy.login(email, password) cy.url().should('eq', Cypress.config().baseUrl) cy.visit('/deposit') cy.url().should('eq', `${Cypress.config().baseUrl}deposit`) cy.get('input').type('10000').type('{enter}') cy.url().should('eq', `${Cypress.config().baseUrl}account`) cy.get('#root > div > div.wrapper > main > div > div > span').should( 'contain', '10000.00' ) }) it('logs in and logs out', () => { cy.visit('/login') cy.login(email, password) cy.url().should('eq', Cypress.config().baseUrl) cy.get(logout).click() cy.url().should('eq', Cypress.config().baseUrl) }) it('uses the hamburger menu', () => { cy.viewport('iphone-6') // Set viewport to 375px x 667px cy.visit('/login') cy.login(email, password) cy.url().should('eq', Cypress.config().baseUrl) cy.get(hamburger).click() cy.get(home).click({ multiple: true, force: true }) cy.url().should('eq', Cypress.config().baseUrl) cy.get(hamburger).click() cy.get(users).click({ multiple: true, force: true }) cy.url().should('eq', `${Cypress.config().baseUrl}users`) cy.get(hamburger).click() cy.get(buyStocks).click({ multiple: true, force: true }) cy.url().should('eq', `${Cypress.config().baseUrl}buy`) cy.get(hamburger).click() cy.get(sellStocks).click({ multiple: true, force: true }) cy.url().should('eq', `${Cypress.config().baseUrl}sell`) cy.get(hamburger).click() cy.get(account).click({ multiple: true, force: true }) cy.url().should('eq', `${Cypress.config().baseUrl}account`) cy.get(hamburger).click() cy.get(deposit).click({ multiple: true, force: true }) cy.url().should('eq', `${Cypress.config().baseUrl}deposit`) }) it('buys and sells stocks', () => { cy.visit('/login') cy.url().should('eq', `${Cypress.config().baseUrl}login`) cy.login(email, password) cy.wait(500) cy.visit('/deposit') cy.url().should('eq', `${Cypress.config().baseUrl}deposit`) cy.get('input').type('99999999').type('{enter}') cy.visit('/buy') cy.get('#stock').select('Princesstårta') cy.get('input').type('1').type('{enter}') cy.url().should('eq', `${Cypress.config().baseUrl}account`) cy.get(stocksInAccount).should('have.length', 2) cy.visit('/buy') cy.get('#stock').select('Princesstårta') cy.get('input').type('1').type('{enter}') cy.url().should('eq', `${Cypress.config().baseUrl}account`) cy.get(stocksInAccount).should('have.length', 2) cy.visit('/buy') cy.get('#stock').select('Mandelkubb') cy.get('input').type('1').type('{enter}') cy.url().should('eq', `${Cypress.config().baseUrl}account`) cy.get(stocksInAccount).should('have.length', 3) cy.visit('/buy') cy.get('#stock').select('Dammsugare') cy.get('input').type('1').type('{enter}') cy.url().should('eq', `${Cypress.config().baseUrl}account`) cy.get(stocksInAccount).should('have.length', 4) cy.visit('/buy') cy.get('#stock').select('Kanelbulle') cy.get('input').type('1').type('{enter}') cy.url().should('eq', `${Cypress.config().baseUrl}account`) cy.get(stocksInAccount).should('have.length', 5) cy.visit('/sell') cy.get('#stock').select('Kanelbulle') cy.get('input').type('1').type('{enter}') cy.url().should('eq', `${Cypress.config().baseUrl}account`) cy.get(stocksInAccount).should('have.length', 4) cy.visit('/sell') cy.get('#stock').select('Dammsugare') cy.get('input').type('1').type('{enter}') cy.url().should('eq', `${Cypress.config().baseUrl}account`) cy.get(stocksInAccount).should('have.length', 3) cy.visit('/sell') cy.get('#stock').select('Mandelkubb') cy.get('input').type('1').type('{enter}') cy.url().should('eq', `${Cypress.config().baseUrl}account`) cy.get(stocksInAccount).should('have.length', 2) cy.visit('/sell') cy.get('#stock').select('Princesstårta') cy.get('input').type('2').type('{enter}') cy.url().should('eq', `${Cypress.config().baseUrl}account`) cy.get(stocksInAccount).should('have.length', 1) }) }) <file_sep>import { gql } from '@apollo/client' export const SIGNUP_USER = gql` mutation signUp($username: String!, $email: String!, $password: String!) { jwt: signUp(username: $username, email: $email, password: $password) } ` export const SIGNIN_USER = gql` mutation signIn($username: String, $email: String, $password: String!) { jwt: signIn(username: $username, email: $email, password: $password) } ` export const DEPOSIT = gql` mutation addFunds($amount: Int!) { balance: addFunds(amount: $amount) } ` export const BUY_STOCK = gql` mutation buyStock($stock: String!, $amount: Float!) { myStocks: buyStock(stock: $stock, amount: $amount) { name amount balance } } ` export const SELL_STOCK = gql` mutation sellStock($stock: String!, $amount: Float!) { myStocks: sellStock(stock: $stock, amount: $amount) { name amount balance } } ` <file_sep>import { useApolloClient, useMutation } from '@apollo/client' import React, { useState, useEffect } from 'react' import { DEPOSIT } from '../gql/mutation' import { CHECK_BALANCE } from '../gql/query' import Spinner from '../components/Spinner' import styled from 'styled-components' import Button from '../components/Button' const Form = styled.form` display: flex; flex-direction: column; align-items: center; ` const Deposit = (props) => { const client = useApolloClient() useEffect(() => { document.title = 'Deposit' }, []) const [amount, setAmount] = useState('') const [deposit, { loading, error }] = useMutation(DEPOSIT, { onCompleted: (data) => { client.writeQuery({ query: CHECK_BALANCE, data, }) }, onError: (error) => { console.error(error) }, }) const onChange = (event) => { setAmount(Number(event.target.value)) } const onSubmit = (event) => { event.preventDefault() deposit({ variables: { amount, }, }) setAmount('') props.history.push('/account') } return ( <> <Form onSubmit={onSubmit}> <label htmlFor="amount">Amount:</label> <input type="number" name="amount" required="required" onChange={onChange} placeholder="amount" value={amount} min="1" /> <Button type="submit">Deposit</Button> </Form> {loading && <Spinner />} {error && <p>Error depositing!</p>} </> ) } export default Deposit <file_sep>import { useApolloClient, useLazyQuery, useMutation } from '@apollo/client' import { v4 as uuidv4 } from 'uuid' import React, { useEffect, useState } from 'react' import { SELL_STOCK } from '../gql/mutation' import { MY_STOCKS, STOCKS_AND_BALANCE } from '../gql/query' import Spinner from '../components/Spinner' import styled from 'styled-components' import Button from '../components/Button' const Form = styled.form` display: flex; flex-direction: column; align-items: center; ` const Sell = ({ history }) => { useEffect(() => { document.title = 'Sell stocks' }, []) const client = useApolloClient() const [availableStocks, setAvailableStocks] = useState([]) const [amount, setAmount] = useState('') const [stock, setStock] = useState('') const [getStocks, { data: stockNames }] = useLazyQuery(MY_STOCKS, { fetchPolicy: 'cache-only', }) const [sellStock, { loading: loadingSale, error: errorSale }] = useMutation( SELL_STOCK, { onCompleted: (data) => { const stocksBefore = client.readQuery({ query: STOCKS_AND_BALANCE, }) const stocksWithoutNewData = stocksBefore.myStocks.filter( (stock) => stock.name !== data.myStocks.name ) const updatedStocks = [ ...stocksWithoutNewData, { name: data.myStocks.name, amount: data.myStocks.amount }, ] const updatedStocksFiltered = updatedStocks.filter( (stock) => stock.amount !== 0 ) client.writeQuery({ query: STOCKS_AND_BALANCE, data: { balance: data.myStocks.balance, myStocks: updatedStocksFiltered, }, }) history.push('/account') }, onError: (err) => { // TODO: Send to notify component console.error(err.message) }, } ) const [ stocksAvailable, { loading: loadingStocks, error: errorStocks }, ] = useLazyQuery(MY_STOCKS, { onCompleted: (data) => { const stockNames = data.myStocks.map((stock) => stock.name) setAvailableStocks(stockNames) client.writeQuery({ query: MY_STOCKS, data: stockNames, }) }, }) // Get stocks and balance in order to have it in the cache for // when the sale completes const [getStocksAndBalance] = useLazyQuery(STOCKS_AND_BALANCE) useEffect(() => { let isMounted = true if (isMounted) { getStocksAndBalance() stocksAvailable() getStocks() setAvailableStocks( stockNames ? stockNames.myStocks.map((stock) => stock.name) : [] ) } return () => { isMounted = false } }, [getStocks, stockNames, stocksAvailable, getStocksAndBalance]) const onChangeAmount = (event) => { setAmount(Number(event.target.value)) } const onChangeStock = (event) => { setStock(event.target.value) } const onSubmit = (event) => { event.preventDefault() if (stock && amount) { sellStock({ variables: { stock, amount, }, }) } } let selectedStockAmount if (stockNames) { selectedStockAmount = stockNames.myStocks .filter((item) => item.name === stock) .map((item) => item.amount)[0] } return ( <> <Form onSubmit={onSubmit}> <label htmlFor="stock">Stock:</label> <select value={stock} required name="stock" id="stock" onChange={onChangeStock} onBlur={onChangeStock} > <option value="" disabled> --- Select stock to sell --- </option> {availableStocks.map((stock) => ( <option key={uuidv4()} value={stock}> {stock} </option> ))} </select> <label htmlFor="amount">Amount:</label> <input type="number" name="amount" required="required" onChange={onChangeAmount} placeholder="amount" value={amount} min="1" step="1" max={selectedStockAmount} /> <Button type="submit">Sell stock</Button> </Form> {loadingSale && <Spinner />} {loadingStocks && <Spinner />} {errorSale && <div>{errorSale.message}</div>} {errorStocks && <div>{errorStocks.message}</div>} </> ) } export default Sell <file_sep>import React, { useState } from 'react' import styled from 'styled-components' import Button from './Button' const Form = styled.form` display: flex; flex-direction: column; align-items: center; ` const UserForm = ({ formType, action }) => { const [values, setValues] = useState() const onChange = (event) => { setValues({ ...values, [event.target.name]: event.target.value, }) } const onSubmit = (event) => { event.preventDefault() action({ variables: { ...values, }, }) } return ( <> {formType === 'register' ? <h2>Sign up</h2> : <h2>Sign in</h2>} <Form onSubmit={onSubmit}> {formType === 'register' && ( <> <label htmlFor="username">Username:</label> <input type="text" required="required" name="username" placeholder="username" onChange={onChange} /> </> )} <label htmlFor="email">Email:</label> <input type="email" required="required" name="email" placeholder="email" onChange={onChange} /> <label htmlFor="password">Password:</label> <input type="password" required="required" name="password" placeholder="<PASSWORD>" onChange={onChange} /> <Button type="submit">Submit</Button> </Form> </> ) } export default UserForm <file_sep>import React from 'react' import ReactDOM from 'react-dom' import './index.css' import App from './App' import { ApolloClient, ApolloProvider, HttpLink, InMemoryCache, split, } from '@apollo/client' import { WebSocketLink } from '@apollo/client/link/ws' import { getMainDefinition } from '@apollo/client/utilities' import { setContext } from 'apollo-link-context' import { IS_LOGGED_IN } from './gql/query' const authLink = setContext((_, { headers }) => { const token = localStorage.getItem('jsramverkProjectTradingToken') if (token) { return { headers: { ...headers, authorization: token ? token : null, }, } } return { headers } }) const uri = process.env.NODE_ENV === 'production' ? 'https://trading-api.sonnerberg.me/api' : 'http://localhost:4000/api' const httpLink = new HttpLink({ uri, }) const cache = new InMemoryCache({ typePolicies: { Query: { fields: { myStocks: { merge: false, }, }, }, }, }) const wsLink = new WebSocketLink({ uri: process.env.NODE_ENV === 'production' ? 'wss://trading-api.sonnerberg.me/subscription' : 'ws://localhost:4000/subscription', options: { reconnect: true, }, }) const splitLink = split( ({ query }) => { const definition = getMainDefinition(query) return ( definition.kind === 'OperationDefinition' && definition.operation === 'subscription' ) }, wsLink, authLink.concat(httpLink) ) const client = new ApolloClient({ link: splitLink, cache, resolvers: {}, connectToDevTools: true, }) const data = { isLoggedIn: Boolean(localStorage.getItem('jsramverkProjectTradingToken')), } cache.writeQuery({ query: IS_LOGGED_IN, data, }) client.onResetStore(() => cache.writeQuery({ query: IS_LOGGED_IN, data: { isLoggedIn: false }, }) ) ReactDOM.render( <React.StrictMode> <ApolloProvider client={client}> <App /> </ApolloProvider> </React.StrictMode>, document.getElementById('root') ) <file_sep>import React from 'react' import { withRouter } from 'react-router-dom' import Navigation from '../Navigation' import { StyledMenu } from './BurgerMenu.styled' const BurgerMenu = ({ open, setOpen }) => { return ( <StyledMenu open={open}> <Navigation setOpen={setOpen} /> </StyledMenu> ) } export default withRouter(BurgerMenu) <file_sep># Frontend [jsramverk.se - Projekt](https://jsramverk.se/project) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/sonnerberg/jsramverk-project-frontend/badges/quality-score.png?b=main)](https://scrutinizer-ci.com/g/sonnerberg/jsramverk-project-frontend/?branch=main) [![Code Coverage](https://scrutinizer-ci.com/g/sonnerberg/jsramverk-project-frontend/badges/coverage.png?b=main)](https://scrutinizer-ci.com/g/sonnerberg/jsramverk-project-frontend/?branch=main) [![Build Status](https://scrutinizer-ci.com/g/sonnerberg/jsramverk-project-frontend/badges/build.png?b=main)](https://scrutinizer-ci.com/g/sonnerberg/jsramverk-project-frontend/build-status/main) [![Build Status](https://travis-ci.com/sonnerberg/jsramverk-project-frontend.svg?branch=main)](https://travis-ci.com/sonnerberg/jsramverk-project-frontend) ## Technology choices During the start of the summer of 2020 I came across a book that I found very interesting which is called [JavaScript Everywhere](https://www.oreilly.com/library/view/javascript-everywhere/9781492046974/). During the same time period I came across GraphQL for the first time in the Massive Open Online Course (MOOC) [FullstackOpen](https://fullstackopen.com/en/part8). When it came time for the project in the course [jsramverk.se](https://jsramverk.se/) I decided to try to make use of Apollo and GraphQL, both tools being described in both JavaScript Everywhere and at FullstackOpen. The reason for choosing GraphQL over REST is mostly because I think GraphQL seems to be an interesting technology that I wanted to try out. This project felt like a good opportuinty to get my feet wet. ### [@apollo/client - npm](https://www.npmjs.com/package/@apollo/client) To consume my GraphQL backend I have used `@apollo/client` as it was described in both [JavaScript Everywhere](https://www.oreilly.com/library/view/javascript-everywhere/9781492046974/) and at [FullstackOpen](https://fullstackopen.com/en/part8). While developing my frontend I learned first hand about how fast the JavaScript eco system changes. Even though the book JavaScript Everywhere is quite new it used a technique called `writeData` that since then has been deprecated. I had to resort to reading the documentation and instead use `writeQuery` and `readQuery`. Something else had also changed since the version of Apollo used in the book and that was that the use of `useQuery` together with pushing the user to another page using `history` in `react-router-dom` would give errors. I had to read up about how to sort this behaviour out and ultimaltely used a trick with `useLazyQuery`. This presented another issue as the lazy query would not keep my pages updated. This led me to having to use the Apollo cache a lot for updating my components. This felt similar to what I had previously done using [redux - npm](https://www.npmjs.com/package/redux) and in the end the results are good as the application works with fewer requests sent to the server. ### [apollo-link-context - npm](https://www.npmjs.com/package/apollo-link-context) This package was described in [JavaScript Everywhere](https://www.oreilly.com/library/view/javascript-everywhere/9781492046974/) and is used to use a header for requests to check that a user is authenticated. ### [d3 - npm](https://www.npmjs.com/package/d3) `d3` was used to create graphs of the real time prices of stocks changing. I had earlier come across `d3` at [freeCodeCamp](https://www.freecodecamp.org/) and was fortunate to find some good YouTube-tutorials for how to use `d3` with React hooks. ### [normalize-url - npm](https://www.npmjs.com/package/normalize-url) `normalize.css` is used to reset styles for the application to have a clean slate to work from. ### [react - npm](https://www.npmjs.com/package/react) and [react-router-dom - npm](https://www.npmjs.com/package/react-router-dom) React is my framework of choice. This is mostly due to its popularity and the fact that I had learned some React at [freeCodeCamp](https://www.freecodecamp.org/) and [Full stack open 2020](https://fullstackopen.com/en) prior to starting this course. I want to dig in to React before attempting to use other frameworks like Vue or Angular. ### [styled-components - npm](https://www.npmjs.com/package/styled-components) `styled-components` are used to style my appication. I have used it earlier in [Full stack open 2020](https://fullstackopen.com/en). I think that I would have gotten a more aesthetically pleasing result by using something like [react-bootstrap - npm](https://www.npmjs.com/package/react-bootstrap) [@material-ui/core - npm](https://www.npmjs.com/package/@material-ui/core) or [@chakra-ui/core - npm](https://www.npmjs.com/package/@chakra-ui/core). But I still decided to dig deeper into `styled-components` and do things "myself". I really like how it is possible to create scoped styles and the ability to use a ThemeProvider to conditionally apply styles. ### [styled-icons - npm](https://www.npmjs.com/package/styled-icons) I have only used in icon from this package so it is actually way to large to use but I still feel that it is worthful to know how to use the package. ### [uuid - npm](https://www.npmjs.com/package/uuid) I have used the `uuid` package to create keys for react components that are unique. ### [cypress - npm](https://www.npmjs.com/package/cypress) Even though the use of `selenium` has been suggested in the course I decided to instead use `cypress`. I came across `cypress` in [Full stack open 2020](https://fullstackopen.com/en) and I prefer it over `selenium` mainly because the docs are a lot easier to read. Another advantage of `cypress` is that it is fairly easy to get code coverage, something I was not able to pull off when trying out `selenium` earlier. ## Test use cases - Register users - Log in user - Log out user - Buy stocks - Sell stocks - Deposit funds ## Attribution - “JavaScript Everywhere by <NAME> (O’Reilly). Copyright 2020 <NAME>, 978-1-492-04698-1.” - [The Muratorium - Using React (Hooks) with D3](https://www.youtube.com/playlist?list=PLDZ4p-ENjbiPo4WH7KdHjh_EMI7Ic8b2B) - [Fullstackopen - Part 8 (GrahpQL)](https://fullstackopen.com/en/part8) - [Freecodecamp](https://www.freecodecamp.org/news/how-to-keep-your-footer-where-it-belongs-59c6aa05c59c/) <file_sep>import React from 'react' import styled from 'styled-components' import { MarkGithub } from 'styled-icons/octicons' const StyledFooter = styled.footer` position: absolute; bottom: 0; width: 100%; height: 3vh; ` const FooterContent = styled.div` display: flex; flex-direction: column; align-items: center; justify-content: center; ` const Footer = () => { return ( <> <StyledFooter> <FooterContent> <a href="https://www.github.com/sonnerberg"> <MarkGithub size={16} /> </a> <p>&copy; <NAME></p> </FooterContent> </StyledFooter> </> ) } export default Footer <file_sep>import React, { useRef, useState } from 'react' import Burger from '../components/Burger' import Menu from '../components/BurgerMenu' import { useOnClickOutside } from '../burgerHook' import Header from './Header' import Footer from './Footer' import Navigation from './Navigation' import styled from 'styled-components' const Div = styled.div` @media (max-width: ${({ theme }) => theme.tablet}) { display: none; } ` const Wrapper = styled.div` padding-bottom: 2.5rem; ` const Layout = ({ children }) => { const [open, setOpen] = useState(false) const node = useRef() useOnClickOutside(node, () => setOpen(false)) return ( <Wrapper> <div ref={node}> <Burger open={open} setOpen={setOpen} /> <Menu open={open} setOpen={setOpen} /> </div> <Header /> <Div> <Navigation /> </Div> <div className="wrapper"> {/* <Navigation /> */} <main>{children}</main> </div> <Footer /> </Wrapper> ) } export default Layout <file_sep>import React from 'react' import styled from 'styled-components' const Loader = styled.div` border: 6px solid #f3f3f3; border-top: 6px solid #3498db; border-radius: 50%; width: 5vw; height: 5vw; animation: spin 1.5s normal infinite; @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } ` const LoaderContainer = styled.div` display: flex; flex-direction: column; align-items: center; justify-content: center; ` const Spinner = () => { return ( <> <LoaderContainer> <Loader /> </LoaderContainer> </> ) } export default Spinner <file_sep>import { useApolloClient, useMutation } from '@apollo/client' import React from 'react' import { SIGNUP_USER } from './gql/mutation' import Spinner from './components/Spinner' import UserForm from './components/UserForm' import { IS_LOGGED_IN } from './gql/query' const Register = ({ history }) => { const client = useApolloClient() const [signUp, { loading, error }] = useMutation(SIGNUP_USER, { onCompleted: (data) => { localStorage.setItem('jsramverkProjectTradingToken', data.jwt) client.writeQuery({ query: IS_LOGGED_IN, data: { isLoggedIn: true }, }) history.push('/') }, onError: (err) => { console.error(err.message) }, }) return ( <> <UserForm action={signUp} formType="register" /> {loading && <Spinner />} {error && <p>Error creating account!</p>} </> ) } export default Register <file_sep>import { createGlobalStyle } from 'styled-components' import normalize from 'normalize.css' export default createGlobalStyle` ${normalize} body { background: ${({ theme }) => theme.primaryDark}; color: ${({ theme }) => theme.primaryLight}; padding: 5px; } #root { position: relative; min-height: 95.9vh; } ` <file_sep>import { useApolloClient, useLazyQuery, useMutation } from '@apollo/client' import { v4 as uuidv4 } from 'uuid' import React, { useEffect, useState } from 'react' import { BUY_STOCK } from '../gql/mutation' import { AVAILABLE_STOCKS, STOCKS_AND_BALANCE } from '../gql/query' import Spinner from '../components/Spinner' import styled from 'styled-components' import Button from '../components/Button' const Form = styled.form` display: flex; flex-direction: column; align-items: center; ` const Flex = styled.div` display: flex; flex-direction: column; align-items: center; ` const Buy = (props) => { const client = useApolloClient() const [availableStocks, setAvailableStocks] = useState([]) const [amount, setAmount] = useState('') const [stock, setStock] = useState('') const [getStocks, { data: stockNames }] = useLazyQuery(AVAILABLE_STOCKS, { fetchPolicy: 'cache-only', }) const [ buyStock, { loading: loadingPurchase, error: errorPurchase }, ] = useMutation(BUY_STOCK, { onCompleted: (data) => { const stocksBefore = client.readQuery({ query: STOCKS_AND_BALANCE, }) const stocksWithoutNewData = stocksBefore.myStocks.filter( (stock) => stock.name !== data.myStocks.name ) const updatedStocks = [ ...stocksWithoutNewData, { name: data.myStocks.name, amount: data.myStocks.amount }, ] client.writeQuery({ query: STOCKS_AND_BALANCE, data: { balance: data.myStocks.balance, myStocks: updatedStocks, }, }) props.history.push('/account') }, onError: (err) => { // TODO: Send to notify component console.error(err.message) }, }) const [ stocksAvailable, { loading: loadingStocks, error: errorStocks }, ] = useLazyQuery(AVAILABLE_STOCKS, { onCompleted: (data) => { const stockNames = data.stocks.map((stock) => stock.name) setAvailableStocks(stockNames) client.writeQuery({ query: AVAILABLE_STOCKS, data: stockNames, }) }, onError: (error) => { console.error(error.message) }, }) // Get stocks and balance in order to have it in the cache for // when the purchase completes const [getStocksAndBalance, { data: stocksAndBalance }] = useLazyQuery( STOCKS_AND_BALANCE ) useEffect(() => { let isMounted = true if (isMounted) { getStocksAndBalance() stocksAvailable() getStocks() setAvailableStocks( stockNames ? stockNames.stocks.map((stock) => stock.name) : [] ) } return () => { isMounted = false } }, [getStocks, stockNames, getStocksAndBalance, stocksAvailable]) useEffect(() => { document.title = 'Buy stocks' }, []) const onChangeAmount = (event) => { setAmount(Number(event.target.value)) } const onChangeStock = (event) => { setStock(event.target.value) } const onSubmit = (event) => { event.preventDefault() if (stock && amount) { buyStock({ variables: { stock, amount, }, }) } } let totalPrice let priceNow if (props.lastData) { priceNow = props.lastData.filter((item) => item.name === stock) if (Array.isArray(priceNow) && priceNow.length > 0) { priceNow = priceNow[0].price totalPrice = priceNow * amount } } return ( <> <Form onSubmit={onSubmit}> <label htmlFor="stock">Stock:</label> <select value={stock} required name="stock" id="stock" onChange={onChangeStock} onBlur={onChangeStock} > <option value="" disabled> --- Select stock to buy --- </option> {availableStocks.map((stock) => ( <option key={uuidv4()} value={stock}> {stock} </option> ))} </select> <label htmlFor="amount">Amount:</label> <input type="number" name="amount" required="required" onChange={onChangeAmount} placeholder="amount" value={amount} min="1" step="1" /> <Button type="submit" disabled={ stocksAndBalance ? totalPrice > stocksAndBalance.balance : false } > Buy stock </Button> </Form> {props.lastData .filter((data) => data.name === stock) .map((stock) => { totalPrice = (stock.price * 1000000 * amount) / 1000000 return ( <Flex key={uuidv4()}> <div> Price: {stock.price} per {stock.name}. </div> <div>Total price: {totalPrice}</div> </Flex> ) })} {loadingPurchase && <Spinner />} {loadingStocks && <Spinner />} {errorPurchase && <div>{errorPurchase.message}</div>} {errorStocks && <div>{errorStocks.message}</div>} </> ) } export default Buy <file_sep>import { axisBottom, axisRight, curveCardinal, line, scaleLinear, select, } from 'd3' import React, { useLayoutEffect, useRef, useState } from 'react' import styled from 'styled-components' const Svg = styled.svg` display: block; width: 100%; margin-left: '1rem'; overflow: visible; & .path { stroke: ${({ theme }) => theme.primaryLight}; } ` const Div = styled.div` margin: 1rem; margin-right: 2.5rem; margin-bottom: 4.5rem; max-width: 500px; ` const H2 = styled.h2` text-align: center; font-size: 1.1rem; ` const useResizeObserver = (ref) => { const [dimensions, setDimensions] = useState(null) useLayoutEffect(() => { const observeTarget = ref.current const resizeObserver = new ResizeObserver((entries) => { entries.forEach((entry) => { setDimensions(entry.contentRect) }) }) resizeObserver.observe(observeTarget) return () => { resizeObserver.unobserve(observeTarget) } }, [ref]) return dimensions } export const Graph = ({ stock, numberOfGraphPoints }) => { const svgRef = useRef() const wrapperRef = useRef() const values = stock.values.slice(-numberOfGraphPoints) const dimensions = useResizeObserver(wrapperRef) const xDomain = 10 useLayoutEffect(() => { const svg = select(svgRef.current) if (!dimensions) return const xScale = scaleLinear() .domain([0, values.length < xDomain ? xDomain - 1 : values.length - 1]) .range([0, dimensions.width]) const yScale = scaleLinear() .domain([Math.min(...values) - 10, Math.max(...values) + 10]) .range([dimensions.height, 0]) const xAxis = axisBottom(xScale).ticks(5) svg .select('.x-axis') .style('transform', `translateY(${dimensions.height}px)`) .call(xAxis) const yAxis = axisRight(yScale).ticks(5) svg .select('.y-axis') .style('transform', `translateX(${dimensions.width}px)`) .call(yAxis) const myLine = line() .x((value, index) => xScale(index)) .y(yScale) .curve(curveCardinal) svg .selectAll('.line') .data([values]) .join('path') .attr('class', 'line') .attr('d', (value) => myLine(value)) .attr('fill', 'none') .attr('stroke', 'blue') }, [values, dimensions]) return ( <> <Div ref={wrapperRef}> <H2>{stock.name}</H2> <Svg ref={svgRef}> <g className="x-axis" /> <g className="y-axis" /> </Svg> </Div> </> ) } <file_sep>import { useApolloClient, useMutation } from '@apollo/client' import React from 'react' import { SIGNIN_USER } from './gql/mutation' import UserForm from './components/UserForm' import { IS_LOGGED_IN } from './gql/query' import styled from 'styled-components' import Spinner from './components/Spinner' const StyledLogin = styled.div` display: flex; flex-direction: column; align-items: center; ` const Login = ({ history }) => { const client = useApolloClient() const [signIn, { loading, error }] = useMutation(SIGNIN_USER, { onCompleted: (data) => { localStorage.setItem('jsramverkProjectTradingToken', data.jwt) client.writeQuery({ query: IS_LOGGED_IN, data: { isLoggedIn: true }, }) history.push('/') }, onError: (error) => { console.error(error.message) }, }) return ( <StyledLogin> <UserForm action={signIn} formType="login" /> {loading && <Spinner />} {error && <p>Error signing in!</p>} </StyledLogin> ) } export default Login <file_sep>import { useQuery } from '@apollo/client' import React from 'react' import { Link } from 'react-router-dom' import styled from 'styled-components' import { IS_LOGGED_IN } from '../gql/query' import Spinner from './Spinner' const Li = styled.li` list-style-type: none; margin-left: -40px; @media (min-width: ${({ theme }) => theme.tablet}) { width: 130px; a { padding: 2rem 0; } } ` const Ul = styled.ul` @media (min-width: ${({ theme }) => theme.tablet}) { display: flex; } padding-bottom: 1.5rem; ` const Navigation = ({ setOpen }) => { const { data, loading, error } = useQuery(IS_LOGGED_IN, { fetchPolicy: 'cache-only', }) const closeMenu = () => { if (setOpen) setOpen(false) } if (loading) return ( <> <Spinner /> </> ) if (error) return ( <> <p>Error!</p> </> ) return ( <> <nav> <Ul style={{ justifyContent: data && data.isLoggedIn ? 'space-evenly' : 'flex-start', marginLeft: data && data.isLoggedIn ? '' : '2rem', }} > <Li> <Link to="/" onClick={closeMenu} className="homeLink"> <span aria-hidden="true" role="img"> 📈 </span> Home </Link> </Li> <Li> <Link to="/users" onClick={closeMenu} className="usersLink"> <span aria-hidden="true" role="img"> 👥 </span> Users </Link> </Li> {data && data.isLoggedIn && ( <> <Li> <Link to="/buy" onClick={closeMenu} className="buyLink"> <span aria-hidden="true" role="img"> 💸 </span> Buy stocks </Link> </Li> <Li> <Link to="/sell" onClick={closeMenu} className="sellLink"> <span aria-hidden="true" role="img"> 💵 </span> Sell stocks </Link> </Li> <Li> <Link to="/account" onClick={closeMenu} className="accountLink"> <span aria-hidden="true" role="img"> 🏦 </span> Account </Link> </Li> <Li> <Link to="/deposit" onClick={closeMenu} className="depositLink"> <span aria-hidden="true" role="img"> 💳 </span> Deposit </Link> </Li> </> )} </Ul> </nav> </> ) } export default Navigation <file_sep>REACT_APP_API_URI=<URI of GraphQL here> <file_sep>import React, { useEffect, useState } from 'react' import GlobalStyle from './components/GlobalStyle' import './App.css' import Pages from './pages' import { useApolloClient, useLazyQuery, useSubscription } from '@apollo/client' import { PERSON_ADDED, STOCKS_UPDATED } from './gql/subscription' import { GET_USERS } from './gql/query' import { ThemeProvider } from 'styled-components' import { theme } from './theme' const App = () => { const [data, setData] = useState([]) const [lastData, setLastData] = useState([]) const [fetchUsers] = useLazyQuery(GET_USERS) useEffect(() => { let mounted = true if (mounted) { fetchUsers() } return () => { mounted = false } }, [fetchUsers]) // TODO: Get history for database const client = useApolloClient() const maxArraySize = 365 useSubscription(STOCKS_UPDATED, { onSubscriptionData: ({ subscriptionData }) => { setLastData( subscriptionData.data.stocksUpdated.map((stock) => ({ name: stock.name, price: stock.startingPoint, })) ) if (Array.isArray(data) && data.length === 0) { setData( subscriptionData.data.stocksUpdated.map((stock) => ({ name: stock.name, values: [stock.startingPoint], })) ) } else { setData( subscriptionData.data.stocksUpdated.map((stock, index) => ({ name: stock.name, values: [...data[index]['values'], stock.startingPoint].slice( -maxArraySize ), })) ) } }, }) useSubscription(PERSON_ADDED, { onSubscriptionData: ({ subscriptionData }) => { // This function runs twice for some reason try { const usersBefore = client.readQuery({ query: GET_USERS }) // Do not add same username twice const lastuserNameExisting = usersBefore.users[usersBefore.users.length - 1].username const usernameIncoming = subscriptionData.data.personAdded.username const usernameSame = lastuserNameExisting === usernameIncoming if (!usernameSame) { client.writeQuery({ query: GET_USERS, data: { users: [...usersBefore.users, subscriptionData.data.personAdded], }, }) } } catch (err) { // This is the first user to be added client.writeQuery({ query: GET_USERS, data: { users: [subscriptionData.data.personAdded], }, }) } }, }) // TODO: Make hamburger: https://css-tricks.com/hamburger-menu-with-a-side-of-react-hooks-and-styled-components/ return ( <ThemeProvider theme={theme}> <GlobalStyle /> <Pages data={data} numberOfGraphPoints={maxArraySize} lastData={lastData} /> </ThemeProvider> ) } export default App
d6be4c0de4be012789e34d2bbbfe09a42fbfbc10
[ "JavaScript", "Markdown", "Shell" ]
21
JavaScript
sonnerberg/jsramverk-project-frontend
eb85abfaac3e8f72d36e694f3c8655ff76c3fa14
8d4ae24dc7ecdce65b6003910475406729d31412
refs/heads/master
<repo_name>dundee/homebrew-taps<file_sep>/gdu.rb class Gdu < Formula desc "Disk usage analyzer with console interface written in Go" homepage "https://github.com/dundee/gdu" url "https://github.com/dundee/gdu/archive/v2.2.0.tar.gz" sha256 "94f4faaee6c1676b73bb75f031cc3d004b8df713fb12d1dfc90ed592bf302df7" license "MIT" depends_on "go" => :build def install system "go", "build", *std_go_args, "-ldflags", "-s -w -X main.AppVersion=v#{version}" end test do assert_match version.to_s, shell_output("#{bin}/gdu -v") assert_match "colorized", shell_output("#{bin}/gdu --help 2>&1") end end <file_sep>/README.md # Homebrew tap Includes formula for: * [gdu](https://github.com/dundee/gdu)
d87fb55190f7c972b94d333bfc544a16a2a5f3ba
[ "Markdown", "Ruby" ]
2
Ruby
dundee/homebrew-taps
7c32c8ce99019ae08803b4759944cc899c5a7ce9
4efd02156f38ec7080eb724bba5a5ba2b4edfd2a
refs/heads/master
<file_sep>#include<stdio.h> #include"calc.h" #define TAMANO 10 // maximo tamaño de la pila. int e=0; float pila[TAMANO]; void push(float n){//inicio --- introduce a la pila if(e<TAMANO) pila[e++]=n; else printf("error pila lleno, ,no puede efetuarse push %g\n",n); }//fin float pop(void){// pop extrae el valor superior de la pila if(e>0) return pila[--e]; else{ printf("error pila vacia\n"); return 0.0; } }//fin <file_sep>#include<stdio.h> #include<stdlib.h> #include"calc.h" #define MAXIMOOPERADOR 100 int main(){ int tipo; float op2; char s[MAXIMOOPERADOR]; while(( tipo = getop(s) ) != EOF ){ switch(tipo){ case NUMBER : push(atof(s)); break; case'+': push( pop() + pop() ); break; case '*': push( pop() * pop() ); break; case '-': op2=pop(); push( pop() - op2 ); break; case '/': op2=pop(); if (op2 == 0.0) printf("error: divisor cero\n"); else push( pop() / op2 ); break; case '\n': printf("Respuesta: %.8g\n", pop() ); break; default: printf("error, comando desconocido %s\n",s); break; } } return 0; } <file_sep>#include<stdio.h> #include<ctype.h> #include"calc.h" int getch(void); void ungetch(int); int getop(char s[]){//inicio ------- getop obtiene el siguiente operador u operando int i,c; while((s[0] = c = getch() ) == ' ' || c == '\t') ; s[1] = '\0'; if (!isdigit(c) && c != '.') return c; // no es un numero i=0; if(isdigit(c)) // reune la parte entera while(isdigit (s[++i] = c = getch() )); ; if(c == '.') // reune la parte ffraccionaria while(isdigit (s[++i] = c = getch() )) ; s[i] = '\0'; if( c != EOF ) ungetch(c); return NUMBER; }//fin <file_sep>#define NUMBER'0' void push(float); float pop(void); int getop(char []); int getch(void); void ungetch(int); <file_sep>#include<stdio.h> #include<stdlib.h>// para el atof y para el atoi #define MAXIMOOPERADOR 100 #define NUMBER '0' int getop(char[]); void push(float); float pop(void); // calculadora polaca inversa. int main(){ int tipo; float op2; char s[MAXIMOOPERADOR]; while(( tipo = getop(s) ) != EOF ){ switch(tipo){ case NUMBER : push(atof(s)); break; case'+': push( pop() + pop() ); break; case '*': push( pop() * pop() ); break; case '-': op2=pop(); push( pop() - op2 ); break; case '/': op2=pop(); if (op2 == 0.0) printf("error: divisor cero\n"); else push( pop() / op2 ); break; case '\n': printf("Respuesta: %.8g\n", pop() ); break; default: printf("error, comando desconocido %s\n",s); break; } } return 0; } // cunado utilizamos la libreria ctype.h /* isdigit ---------> verifica si es un digito isalpha-----------> verifica si es una letra is punct ----------> es signo de puntuacion isispace ----------> si es espacio en blanco */ #define TAMANO 10 // maximo tamaño de la pila. int e=0; float pila[TAMANO]; void push(float n){//inicio --- introduce a la pila if(e<TAMANO) pila[e++]=n; else printf("error pila lleno, ,no puede efetuarse push %g\n",n); }//fin float pop(void){// pop extrae el valor superior de la pila if(e>0) return pila[--e]; else{ printf("error pila vacia\n"); return 0.0; } }//fin #include<ctype.h> int getch(void); void ungetch(int); int getop(char s[]){//inicio ------- getop obtiene el siguiente operador u operando int i,c; while((s[0] = c = getch() ) == ' ' || c == '\t') ; s[1] = '\0'; if (!isdigit(c) && c != '.') return c; // no es un numero i=0; if(isdigit(c)) // reune la parte entera while(isdigit (s[++i] = c = getch() )); ; if(c == '.') // reune la parte ffraccionaria while(isdigit (s[++i] = c = getch() )) ; s[i] = '\0'; if( c != EOF ) ungetch(c); return NUMBER; }//fin #define SC 100 char buf[SC]; // buffer para ungetch int ll=0; // siguiente posicion libre de ll. int getch(void){//inicio-------obtine un posible ya regresado caracteres1 if (ll > 0) return buf[--ll]; else return getchar(); }//fin void ungetch(int c){//inicio ------- regresa caractrer de la entrada if ( ll >= SC) printf("ungetch:demasiados caracteres \n"); else buf[ll++] = c; } <file_sep>#include<stdio.h> #define SC 100 char buf[SC]; // buffer para ungetch int ll=0; // siguiente posicion libre de ll. int getch(void){//inicio-------obtine un posible ya regresado caracteres1 if (ll > 0) return buf[--ll]; else return getchar(); }//fin void ungetch(int c){//inicio ------- regresa caractrer de la entrada if ( ll >= SC) printf("ungetch:demasiados caracteres \n"); else buf[ll++] = c; }
1d03568a123b845af76582b82fe4cb88f0700352
[ "C" ]
6
C
JorgeAlfredoT/calculadora
4cafe6e50d6362972e166d6ace10506e19159fa8
7a199d34e2dcc1d8c97427b96ea212bf67ec597b
refs/heads/master
<repo_name>js13kGames/lost-treasures<file_sep>/src.js 'use strict' var M = Math, D = document, W = window, FA = Float32Array, text, gl, im = new FA([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), pm, vm = new FA(im), cm = new FA(im), nm = new FA(16), mvp = new FA(im), m = new FA(16), far = 75, skyColor = [.43, .73, .96, 1], lightDirection = [.5, .5, 1], program, seaProgram, seaHalf, sea, floor, player, entitiesLength = 0, entities = [], coins, coinsFound = 0, width, height, now, factor, last, first, pointersLength, pointersX = [], pointersY = [], keysDown = [] M.PI2 = M.PI2 || M.PI / 2 M.TAU = M.TAU || M.PI * 2 // from https://github.com/toji/gl-matrix function invert(out, a) { var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32, // calculate the determinant d = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06 if (!d) { return null } d = 1.0 / d out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * d out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * d out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * d out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * d out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * d out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * d out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * d out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * d out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * d out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * d out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * d out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * d out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * d out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * d out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * d out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * d } // from https://github.com/toji/gl-matrix function multiply(out, a, b) { var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15] // cache only the current line of the second matrix var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3] out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30 out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31 out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32 out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33 b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7] out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30 out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31 out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32 out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33 b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11] out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30 out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31 out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32 out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33 b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15] out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30 out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31 out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32 out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33 } // from https://github.com/toji/gl-matrix function rotate(out, a, rad, x, y, z) { var len = M.sqrt(x * x + y * y + z * z), s, c, t, a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, b00, b01, b02, b10, b11, b12, b20, b21, b22 if (M.abs(len) < 0.000001) { return } len = 1 / len x *= len y *= len z *= len s = M.sin(rad) c = M.cos(rad) t = 1 - c a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3] a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7] a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11] // construct the elements of the rotation matrix b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c // perform rotation-specific matrix multiplication out[0] = a00 * b00 + a10 * b01 + a20 * b02 out[1] = a01 * b00 + a11 * b01 + a21 * b02 out[2] = a02 * b00 + a12 * b01 + a22 * b02 out[3] = a03 * b00 + a13 * b01 + a23 * b02 out[4] = a00 * b10 + a10 * b11 + a20 * b12 out[5] = a01 * b10 + a11 * b11 + a21 * b12 out[6] = a02 * b10 + a12 * b11 + a22 * b12 out[7] = a03 * b10 + a13 * b11 + a23 * b12 out[8] = a00 * b20 + a10 * b21 + a20 * b22 out[9] = a01 * b20 + a11 * b21 + a21 * b22 out[10] = a02 * b20 + a12 * b21 + a22 * b22 out[11] = a03 * b20 + a13 * b21 + a23 * b22 if (a !== out) { // if the source and destination differ, copy the unchanged last row out[12] = a[12] out[13] = a[13] out[14] = a[14] out[15] = a[15] } } // from https://github.com/toji/gl-matrix function scale(out, a, x, y, z) { out[0] = a[0] * x out[1] = a[1] * x out[2] = a[2] * x out[3] = a[3] * x out[4] = a[4] * y out[5] = a[5] * y out[6] = a[6] * y out[7] = a[7] * y out[8] = a[8] * z out[9] = a[9] * z out[10] = a[10] * z out[11] = a[11] * z out[12] = a[12] out[13] = a[13] out[14] = a[14] out[15] = a[15] } // from https://github.com/toji/gl-matrix function translate(out, a, x, y, z) { if (a === out) { out[12] = a[0] * x + a[4] * y + a[8] * z + a[12] out[13] = a[1] * x + a[5] * y + a[9] * z + a[13] out[14] = a[2] * x + a[6] * y + a[10] * z + a[14] out[15] = a[3] * x + a[7] * y + a[11] * z + a[15] } else { var a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23 a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3] a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7] a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11] out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03 out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13 out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23 out[12] = a00 * x + a10 * y + a20 * z + a[12] out[13] = a01 * x + a11 * y + a21 * z + a[13] out[14] = a02 * x + a12 * y + a22 * z + a[14] out[15] = a03 * x + a13 * y + a23 * z + a[15] } } // from https://github.com/toji/gl-matrix function transpose(out, a) { if (out === a) { var a01 = a[1], a02 = a[2], a03 = a[3], a12 = a[6], a13 = a[7], a23 = a[11] out[1] = a[4] out[2] = a[8] out[3] = a[12] out[4] = a01 out[6] = a[9] out[7] = a[13] out[8] = a02 out[9] = a12 out[11] = a[14] out[12] = a03 out[13] = a13 out[14] = a23 } else { out[0] = a[0] out[1] = a[4] out[2] = a[8] out[3] = a[12] out[4] = a[1] out[5] = a[5] out[6] = a[9] out[7] = a[13] out[8] = a[2] out[9] = a[6] out[10] = a[10] out[11] = a[14] out[12] = a[3] out[13] = a[7] out[14] = a[11] out[15] = a[15] } } function dist(a, x, y, z) { var dx = a[12] - x, dy = a[13] - y, dz = a[14] - z return dx*dx + dy*dy + dz*dz } function drawModel(mm, model, uniforms, color) { multiply(mvp, vm, mm) multiply(mvp, pm, mvp) // we need to invert and transpose the model matrix so the // normals are scaled correctly invert(nm, mm) transpose(nm, nm) gl.uniformMatrix4fv(uniforms.mvp, gl.FALSE, mvp) gl.uniformMatrix4fv(uniforms.nm, gl.FALSE, nm) gl.uniform4fv(uniforms.color, color) gl.drawElements(gl.TRIANGLES, model.count, gl.UNSIGNED_SHORT, 0) } function bindModel(attribs, model) { gl.bindBuffer(gl.ARRAY_BUFFER, model.vertices) gl.vertexAttribPointer(attribs.vertex, 3, gl.FLOAT, gl.FALSE, 0, 0) gl.bindBuffer(gl.ARRAY_BUFFER, model.normals) gl.vertexAttribPointer(attribs.normal, 3, gl.FLOAT, gl.FALSE, 0, 0) gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, model.indicies) } function drawSea() { gl.useProgram(seaProgram) var uniforms = seaProgram.uniforms, attribs = seaProgram.attribs gl.uniform3fv(uniforms.light, lightDirection) gl.uniform4fv(uniforms.sky, skyColor) gl.uniform1f(uniforms.far, far) gl.uniform1f(uniforms.time, (now - first) / 500) gl.uniform1f(uniforms.radius, seaHalf) var model = sea.model bindModel(attribs, model) drawModel(sea.matrix, model, uniforms, sea.color) } function drawPlayer(uniforms, attribs) { // render player with separate matrix because the // view matrix is generated from the player matrix translate(m, player.matrix, 0, player.depth, 0) rotate(m, m, player.tilt + M.sin(player.roll += .1 * factor) * (.05 - player.v / (player.maxSpeed * 10)), .2, .2, 1) var model = player.model bindModel(attribs, model) drawModel(m, model, uniforms, player.color) if (player.v != 0) { rotate(m, m, now * .005, 0, 0, 1) } model = player.prop bindModel(attribs, model) drawModel(m, model, uniforms, player.color) } function drawFloor(uniforms, attribs) { var model = floor.model, matrix = floor.matrix bindModel(attribs, model) drawModel(matrix, model, uniforms, floor.color) } function draw() { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) gl.useProgram(program) var uniforms = program.uniforms, attribs = program.attribs gl.uniform3fv(uniforms.light, lightDirection) gl.uniform4fv(uniforms.sky, skyColor) gl.uniform1f(uniforms.far, far) drawFloor(uniforms, attribs) var pm = player.matrix, px = pm[12], py = player.depth, pz = pm[14] for (var model, i = entitiesLength; i--;) { var e = entities[i] if (e.found) { continue } var em = e.matrix if (e.isTreasure && dist(em, px, py, pz) < 8) { e.found = true if (++coinsFound == coins) { text.innerHTML = 'You found all coins!<br/>' + '<a href="javascript:newGame()">Play again?</a>' } else { text.innerText = 'Found a coin! ' + (coins - coinsFound) + ' left ...' } continue } if (model != e.model) { model = e.model bindModel(attribs, model) } drawModel(em, model, uniforms, e.color) if (e.update) { e.update() } } drawPlayer(uniforms, attribs) // draw transparent objects over opaque ones and from back to front drawSea() } function updateView(p) { invert(vm, p) translate(m, im, 0, 6, -30) multiply(vm, m, vm) } function getFloorOffset(x, z) { var fm = floor.model, size = fm.size x = ((x + floor.radius) / floor.mag) | 0 z = ((z + floor.radius) / floor.mag) | 0 if (x < 0 || x > size || z < 0 || z > size) { return -1 } return (M.abs(z * size + x) | 0) % fm.heightMap.length } function addToFloor(x, z, h) { var offset = getFloorOffset(x, z) floor.model.heightMap[offset] += h } function getFloorHeight(x, z) { var offset = getFloorOffset(x, z) return offset < 0 ? 0 : floor.model.heightMap[offset] } function alignSea(x, z) { var sm = sea.matrix, ss = sea.mag, sr = sea.radius, sx = M.round(x / sr) * sr, sz = M.round(z / sr) * sr translate(sm, im, sx, 0, sz) scale(sm, sm, ss, 1, ss) } function move(p, step) { translate(p, p, 0, 0, step) var fr = floor.radius, x = p[12], z = p[14] if (x < -fr || x > fr || z < -fr || z > fr) { if (!text.warning) { text.innerHTML = '<span class="Warning">You left the dive area!<span>' text.warning = true } } else if (text.warning) { text.innerText = '' text.warning = false } alignSea(x, z) } function turn(p, rad) { rotate(p, p, rad, 0, 1, 0) player.tilt += rad * 4 } function input() { if (keysDown[82]) { W.location.reload(true) } var p = player.matrix, s = player.maxSpeed, a = player.maxTurn if (player.v != 0) { move(p, -player.v) player.v *= .94 if (M.abs(player.v) < .01) { player.v = 0 } } if (player.tilt != 0) { player.tilt *= .75 if (M.abs(player.tilt) < .01) { player.tilt = 0 } } var forward = false, backward = false, left = false, right = false, dive = false if (pointersLength > 0) { var bw = width / 5 for (var i = pointersLength; i--;) { switch (pointersX[i] / bw | 0) { case 0: left = true break case 1: forward = true break case 2: dive = true break case 3: backward = true break case 4: right = true break } } } else { forward = keysDown[87] || keysDown[38] || keysDown[75], backward = keysDown[83] || keysDown[40] || keysDown[74], left = keysDown[65] || keysDown[37] || keysDown[72], right = keysDown[68] || keysDown[39] || keysDown[76], dive = keysDown[32] } if (left) { turn(p, a) } else if (right) { turn(p, -a) } else { s *= 1.5 } if (backward) { player.v = -s / 2 } else if (forward || left || right) { player.v = s } var h = getFloorHeight(p[12], p[14]), d = player.depth - 2 if (dive && h < d) { player.depth -= .05 } else if (!dive || h - 2 > d) { player.depth *= .98 if (M.abs(player.depth) < .2) { player.depth = 0 } } updateView(p) } function run() { requestAnimationFrame(run) now = Date.now() factor = (now - last) / 16 last = now input() draw() } function setPointer(event, down) { if (!down) { pointersLength = event.touches ? event.touches.length : 0 } else if (event.touches) { var touches = event.touches pointersLength = touches.length for (var i = pointersLength; i--;) { var t = touches[i] pointersX[i] = t.pageX pointersY[i] = t.pageY } } else { pointersLength = 1 pointersX[0] = event.pageX pointersY[0] = event.pageY } event.preventDefault() event.stopPropagation() event.cancelBubble = true event.returnValue = false } function pointerUp(event) { setPointer(event, false) } function pointerMove(event) { setPointer(event, pointersLength) } function pointerDown(event) { setPointer(event, true) } function setKey(event, down) { keysDown[event.keyCode] = down event.preventDefault() } function keyUp(event) { setKey(event, false) } function keyDown(event) { setKey(event, true) } function setProjectionMatrix() { var aspect = width / height, near = .1, r = near - far, f = 1 / M.tan(M.PI * .125) pm = new FA([ f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (far + near) / r, -1, 0, 0, (2 * far * near) / r, 0]) } function resize() { width = gl.canvas.clientWidth height = gl.canvas.clientHeight gl.canvas.width = width gl.canvas.height = height gl.viewport(0, 0, width, height) setProjectionMatrix() } function cacheUniformLocations(program, uniforms) { if (program.uniforms === undefined) { program.uniforms = {} } for (var i = 0, l = uniforms.length; i < l; ++i) { var name = uniforms[i] program.uniforms[name] = gl.getUniformLocation(program, name) } } function cacheAttribLocations(program, attribs) { if (program.attribs === undefined) { program.attribs = {} } for (var i = 0, l = attribs.length; i < l; ++i) { var name = attribs[i] program.attribs[name] = gl.getAttribLocation(program, name) gl.enableVertexAttribArray(program.attribs[name]) } } function compileShader(src, type) { var shader = gl.createShader(type) gl.shaderSource(shader, src) gl.compileShader(shader) return gl.getShaderParameter(shader, gl.COMPILE_STATUS) ? shader : null } function linkProgram(vs, fs) { var p = gl.createProgram() if (p) { gl.attachShader(p, vs) gl.attachShader(p, fs) gl.linkProgram(p) if (!gl.getProgramParameter(p, gl.LINK_STATUS)) { gl.deleteProgram(p) p = null } } return p } function buildProgram(vertexSource, fragmentSource) { var p, vs, fs if ((vs = compileShader(vertexSource, gl.VERTEX_SHADER))) { if ((fs = compileShader(fragmentSource, gl.FRAGMENT_SHADER))) { p = linkProgram(vs, fs) gl.deleteShader(fs) } gl.deleteShader(vs) } return p } function calculateNormals(vertices, indicies) { var normals = [] for (var i = 0, l = indicies.length; i < l;) { var a = indicies[i++] * 3, b = indicies[i++] * 3, c = indicies[i++] * 3, x1 = vertices[a], y1 = vertices[a + 1], z1 = vertices[a + 2], x2 = vertices[b], y2 = vertices[b + 1], z2 = vertices[b + 2], x3 = vertices[c], y3 = vertices[c + 1], z3 = vertices[c + 2], ux = x2 - x1, uy = y2 - y1, uz = z2 - z1, vx = x3 - x1, vy = y3 - y1, vz = z3 - z1, nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx normals[a] = nx normals[a + 1] = ny normals[a + 2] = nz normals[b] = nx normals[b + 1] = ny normals[b + 2] = nz normals[c] = nx normals[c + 1] = ny normals[c + 2] = nz } return normals } function createModel(vertices, indicies) { var model = {count: indicies.length} model.vertices = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, model.vertices) gl.bufferData(gl.ARRAY_BUFFER, new FA(vertices), gl.STATIC_DRAW) model.normals = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, model.normals) gl.bufferData(gl.ARRAY_BUFFER, new FA(calculateNormals(vertices, indicies)), gl.STATIC_DRAW) model.indicies = gl.createBuffer() gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, model.indicies) gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indicies), gl.STATIC_DRAW) return model } function calculateMapIndicies(size) { var indicies = [] for (var i = 0, z = 1; z < size; ++z) { for (var x = 1; x < size; ++x) { // counter-clockwise order indicies.push(i) indicies.push(i + size) indicies.push(i + 1) indicies.push(i + 1) indicies.push(i + size) indicies.push(i + size + 1) ++i } ++i } return indicies } function expandToHorizon(vertices, offset, lower) { for (var i = 0, l = vertices.length; i < l; ++i) { if (vertices[i] == -offset) { vertices[i] = -1000 } else if (vertices[i] == offset) { vertices[i] = 1000 } else { continue } if (!lower) { continue } else if (i % 3 == 0) { vertices[i + 1] = -1000 } else if (i % 3 == 2) { vertices[i - 1] = -1000 } } } // from http://www.playfuljs.com/realistic-terrain-in-130-lines/ function createHeightMap(size, roughness) { var map = new FA(size * size), max = size - 1 function offset(x, y) { return (size * y + x) | 0 } function set(x, y, value) { if (x == max || y == max) { value = get(x % max, y % max) } map[offset(x, y)] = value } function get(x, y) { return map[offset(x % max, y % max)] } var v = M.random() set(0, 0, v) set(max, 0, v) set(max, max, v) set(0, max, v) function square(x, y, step, offset) { var average = get(x - step, y - step) + get(x + step, y - step) + get(x + step, y + step) + get(x - step, y + step) set(x, y, average / 4 + offset) } function diamond(x, y, step, offset) { var a = 0, i = 0 if (x - step > -1) { a += get(x - step, y); ++i } if (y - step > -1) { a += get(x, y - step); ++i } if (x + step < size) { a += get(x + step, y); ++i } if (y + step < size) { a += get(x, y + step); ++i } set(x, y, a / i + offset) } for (var step = max;;) { var x, y, half = step >> 1, scale = roughness * step / max if (half < 1) { break } for (y = half; y < max; y += step) { for (x = half; x < max; x += step) { square(x, y, half, M.random() * scale * 2 - scale) } } for (y = 0; y <= max; y += half) { for (x = (y + half) % step; x <= max; x += step) { diamond(x, y, half, M.random() * scale * 2 - scale) } } step = half } return map } function createSeaModel(power) { var vertices = [], size = M.pow(2, power) + 1, mapSize = 2 * size - 1, offset = mapSize >> 1, z = 0 for (var i = 1, base = 4, untilLast = size - 1; z < untilLast; ++z, i += mapSize * 3) { for (var x = 0; x < untilLast; ++x) { vertices.push(x - offset) vertices.push(M.random() * .5 - .5) vertices.push(z - offset) } // copy first column to make it seamless vertices.push(x - offset) vertices.push(vertices[i]) vertices.push(z - offset) // copy terrain into second column to form a 2x2 map for (var x = 1, last = size - 1; x < size; ++x) { vertices.push(last + x - offset) vertices.push(vertices[base]) vertices.push(z - offset) base += 3 } base += size * 3 } // copy first row to make it seamless for (var i = 1, x = 0; x < mapSize; ++x, i += 3) { vertices.push(x - offset) vertices.push(vertices[i]) vertices.push(z - offset) } // and copy all of the above for the second row for (var base = (mapSize * 3) + 1, untilLast = size - 1, z = 0; z < untilLast; ++z) { for (var x = 0; x < mapSize; ++x) { vertices.push(x - offset) vertices.push(vertices[base]) vertices.push(size + z - offset) base += 3 } } expandToHorizon(vertices, offset) var model = createModel(vertices, calculateMapIndicies(mapSize)) model.radius = offset seaHalf = offset return model } function createFloorModel(power, roughness, amplification) { var vertices = [], size = M.pow(2, power) + 1, offset = size >> 1, max = .5 var heightMap = createHeightMap(size, roughness) for (var i = 0, z = 0; z < size; ++z) { for (var x = 0; x < size; ++x) { var h = heightMap[i++] * amplification max = M.max(max, h) vertices.push(x - offset) vertices.push(h) vertices.push(z - offset) } } expandToHorizon(vertices, offset, true) var model = createModel(vertices, calculateMapIndicies(size)) model.heightMap = heightMap model.size = size model.radius = offset model.max = max return model } function mirrorModel(vertices, indicies) { var n = vertices.length / 3 for (var i = 0, l = vertices.length; i < l;) { vertices.push(-vertices[i++]) vertices.push(vertices[i++]) vertices.push(vertices[i++]) } for (var i = 0, l = indicies.length; i < l; i += 3) { indicies.push(n + indicies[i + 2]) indicies.push(n + indicies[i + 1]) indicies.push(n + indicies[i]) } } function createPropModel() { var vertices = [ 0.0, 0.536, 3.258, -0.464, 0.268, 3.258, -0.536, 0.0, 3.258, -0.268, -0.464, 3.258, 0.0, -0.536, 3.258, 0.464, -0.268, 3.258, 0.536, 0.0, 3.258, 0.268, 0.464, 3.258, 0.0, 0.0, 3.258, 0.0, 0.536, 3.294, -0.464, 0.268, 3.294, -0.536, 0.0, 3.294, -0.268, -0.464, 3.294, 0.0, -0.536, 3.294, 0.464, -0.268, 3.294, 0.536, 0.0, 3.294, 0.268, 0.464, 3.294, 0.0, 0.0, 3.294, ], indicies = [ 1, 8, 2, 3, 8, 4, 6, 5, 8, 7, 8, 0, 10, 11, 17, 12, 13, 17, 15, 17, 14, 16, 9, 17, 6, 8, 17, 8, 17, 13, 4, 13, 12, 8, 17, 9, 8, 17, 11, 5, 6, 15, 7, 16, 17, 1, 10, 17, 0, 9, 16, 3, 12, 17, 2, 11, 10, 8, 5, 14, ] return createModel(vertices, indicies) } function createBoatModel() { var vertices = [ 0.200, -0.380, -2.459, 0.200, 0.0, -2.565, 0.470, -0.268, -2.459, 0.700, -0.496, -2.217, 0.853, -0.649, -1.202, 0.907, -0.702, -0.005, 0.853, -0.649, 1.192, 0.700, -0.496, 2.207, 0.470, -0.268, 2.885, 0.582, 0.0, -2.459, 0.907, 0.0, -2.217, 1.123, 0.0, -1.202, 1.200, 0.0, -0.005, 1.123, 0.0, 1.192, 0.907, 0.0, 2.207, 0.582, 0.0, 2.885, 0.470, 0.268, -2.459, 0.700, 0.496, -2.217, 0.853, 0.649, -1.202, 0.907, 0.702, -0.005, 0.853, 0.649, 1.192, 0.700, 0.496, 2.207, 0.470, 0.268, 2.885, 0.200, 0.0, 3.076, 0.200, 0.380, -2.459, 0.200, 0.702, -2.217, 0.391, 0.918, -1.202, 0.391, 0.993, 0.277, 0.200, 0.918, 1.192, 0.200, 0.702, 2.207, 0.200, 0.380, 2.885, 0.200, -0.702, -2.217, 0.200, -0.918, -1.202, 0.200, -0.993, -0.005, 0.200, -0.918, 1.192, 0.200, -0.702, 2.207, 0.200, -0.380, 2.885, 0.0, -0.380, -2.459, 0.0, 0.0, -2.565, 0.0, 0.0, 3.076, 0.0, 0.380, -2.459, 0.0, 0.702, -2.217, 0.0, 0.918, -1.202, 0.0, 0.993, 0.277, 0.0, 0.918, 1.192, 0.0, 0.702, 2.207, 0.0, 0.380, 2.885, 0.0, -0.702, -2.217, 0.0, -0.918, -1.202, 0.0, -0.993, -0.005, 0.0, -0.918, 1.192, 0.0, -0.702, 2.207, 0.0, -0.380, 2.885, 0.279, 1.761, -1.202, 0.279, 1.761, -0.005, 0.0, 1.761, -1.202, 0.0, 1.761, -0.005, 0.122, 1.919, -1.039, 0.122, 1.919, -0.477, 0.0, 1.919, -1.039, 0.0, 1.919, -0.477, ], indicies = [ 23, 36, 8, 35, 6, 7, 32, 5, 33, 0, 3, 31, 36, 7, 8, 34, 5, 6, 31, 4, 32, 0, 1, 2, 8, 14, 15, 6, 12, 13, 3, 11, 4, 2, 1, 9, 23, 8, 15, 7, 13, 14, 4, 12, 5, 2, 10, 3, 12, 20, 13, 11, 17, 18, 9, 1, 16, 23, 15, 22, 13, 21, 14, 12, 18, 19, 10, 16, 17, 14, 22, 15, 23, 22, 30, 20, 29, 21, 19, 26, 27, 17, 24, 25, 21, 30, 22, 20, 27, 28, 18, 25, 26, 16, 1, 24, 23, 52, 36, 32, 47, 31, 33, 48, 32, 24, 41, 25, 34, 49, 33, 25, 42, 26, 34, 51, 50, 1, 40, 24, 43, 54, 56, 36, 51, 35, 23, 46, 39, 28, 43, 44, 0, 38, 1, 28, 45, 29, 31, 37, 0, 29, 46, 30, 56, 58, 60, 27, 53, 54, 42, 53, 26, 57, 60, 58, 55, 57, 53, 53, 58, 54, 35, 34, 6, 32, 4, 5, 0, 2, 3, 36, 35, 7, 34, 33, 5, 31, 3, 4, 8, 7, 14, 6, 5, 12, 3, 10, 11, 7, 6, 13, 4, 11, 12, 2, 9, 10, 12, 19, 20, 11, 10, 17, 13, 20, 21, 12, 11, 18, 10, 9, 16, 14, 21, 22, 20, 28, 29, 19, 18, 26, 17, 16, 24, 21, 29, 30, 20, 19, 27, 18, 17, 25, 23, 39, 52, 32, 48, 47, 33, 49, 48, 24, 40, 41, 34, 50, 49, 25, 41, 42, 34, 35, 51, 1, 38, 40, 43, 27, 54, 36, 52, 51, 23, 30, 46, 28, 27, 43, 0, 37, 38, 28, 44, 45, 31, 47, 37, 29, 45, 46, 56, 54, 58, 27, 26, 53, 42, 55, 53, 57, 59, 60, 55, 59, 57, 53, 57, 58, ] mirrorModel(vertices, indicies) return createModel(vertices, indicies) } function createCoinModel() { var vertices = [ 0.0, 0.063, -0.637, 0.588, -0.063, -0.243, 0.637, -0.063, 0.0, 0.588, -0.063, 0.243, 0.450, -0.063, 0.450, 0.243, -0.063, 0.588, 0.0, -0.063, 0.637, 0.0, -0.063, -0.637, 0.0, 0.063, 0.637, 0.243, 0.063, 0.588, 0.450, 0.063, 0.450, 0.588, 0.063, 0.243, 0.637, 0.063, 0.0, 0.588, 0.063, -0.243, 0.450, 0.063, -0.450, 0.243, 0.063, -0.588, 0.450, -0.063, -0.450, 0.243, -0.063, -0.588, ], indicies = [ 14, 17, 15, 12, 1, 13, 10, 3, 11, 8, 5, 9, 15, 7, 0, 13, 16, 14, 11, 2, 12, 9, 4, 10, 10, 14, 8, 17, 4, 5, 14, 16, 17, 12, 2, 1, 10, 4, 3, 8, 6, 5, 15, 17, 7, 13, 1, 16, 11, 3, 2, 9, 5, 4, 8, 9, 10, 10, 11, 12, 12, 13, 14, 14, 15, 0, 0, 8, 14, 10, 12, 14, 6, 7, 17, 17, 16, 1, 1, 2, 3, 3, 4, 17, 5, 6, 17, 17, 1, 3, ] mirrorModel(vertices, indicies) return createModel(vertices, indicies) } function createPyramidModel() { // will have shared normals! return createModel([ // tip 0, 1, 0, // bottom -1, -1, -1, 1, -1, -1, -1, -1, 1, 1, -1, 1],[ // front 0, 3, 4, // right 0, 4, 2, // back 0, 1, 2, // left 0, 3, 1, // bottom 1, 3, 2, 2, 3, 4]) } function createPlayer() { player = { model: createBoatModel(), prop: createPropModel(), matrix: new FA(im), color: [1, 1, 1, 1], roll: 0, v: 0, depth: 0, tilt: 0, maxSpeed: .15, maxTurn: .01 } } function createEntities() { var pyramids = [[-10, -40, 9], [-15, -25, 5]] for (var i in pyramids) { var x = pyramids[i][0], z = pyramids[i][1], s = pyramids[i][2], h = s * .66 translate(m, im, x, getFloorHeight(x, z), z) scale(m, m, s, h, s) addToFloor(x, z, h) entities.push({ model: createPyramidModel(), matrix: new FA(m), color: [.3, .2, .1, 1] }) } var coinModel = createCoinModel(), coinColor = [1, .6, .1, 1], fs = floor.model.size * floor.mag * .35, r = fs * .5 for (var i = 0; i < coins; ++i) { var x = -r + M.random() * fs, z = -r + M.random() * fs, y = getFloorHeight(x, z) + 2 translate(m, im, x, y, z) rotate(m, m, M.random() * M.TAU, 1, 1, 1) entities.push({ model: coinModel, matrix: new FA(m), color: coinColor, found: false, isTreasure: true, update: function() { rotate(this.matrix, this.matrix, .01, 1, 1, 1) } }) } entitiesLength = entities.length } function createSea() { var model = createSeaModel(6), mag = 1.75 sea = { model: model, matrix: new FA(im), color: [.4, .7, .8, .3], radius: model.radius * mag, mag: mag } alignSea(0, 0) } function createFloor(mag) { var amp = 14, model = createFloorModel(5, .6, amp), hm = model.heightMap, base = -(10 + model.max) for (var i = hm.length; i--;) { hm[i] = base + hm[i] * amp } translate(m, im, 0, base, 0) scale(m, m, mag, 1, mag) floor = { model: model, matrix: new FA(m), color: [.3, .2, .1, 1], radius: model.radius * mag, mag: mag, amp: amp, base: base } } function newGame() { coins = 1 + ((M.random() * 9) | 0) coinsFound = 0 text.innerText = 'Find ' + coins + ' lost coins!' text.warning = true createFloor(11) createEntities() player.matrix = new FA(im) player.roll = 0 player.v = 0 player.depth = 0 player.tilt = 0 updateView(player.matrix) } function cacheLocations() { var attribs = ['vertex', 'normal'], uniforms = ['mvp', 'nm', 'light', 'color', 'sky', 'far'] cacheAttribLocations(program, attribs) cacheUniformLocations(program, uniforms) cacheAttribLocations(seaProgram, attribs) uniforms.push('time') uniforms.push('radius') cacheUniformLocations(seaProgram, uniforms) } function createPrograms() { var fs = D.getElementById('FragmentShader').textContent return (program = buildProgram( D.getElementById('VertexShader').textContent, fs)) && (seaProgram = buildProgram( D.getElementById('SeaVertexShader').textContent, fs)) } function getContext() { for (var canvas = D.getElementById('Canvas'), ctx, types = ['webgl', 'experimental-webgl'], l = types.length, i = 0; i < l; ++i) { if ((ctx = canvas.getContext(types[i], {alpha: false}))) { return ctx } } } function init() { if (!(text = D.getElementById('Text')) || !(gl = getContext()) || !createPrograms()) { alert('WebGL not available') return } cacheLocations() createSea() createPlayer() newGame() gl.enable(gl.DEPTH_TEST) gl.enable(gl.BLEND) gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) gl.clearColor(skyColor[0], skyColor[1], skyColor[2], skyColor[3]) W.onresize = resize resize() D.onkeydown = keyDown D.onkeyup = keyUp D.onmousedown = pointerDown D.onmousemove = pointerMove D.onmouseup = pointerUp D.onmouseout = pointerUp if ('ontouchstart' in D) { D.ontouchstart = pointerDown D.ontouchmove = pointerMove D.ontouchend = pointerUp D.ontouchleave = pointerUp D.ontouchcancel = pointerUp } last = Date.now() - 16 first = last run() } W.onload = init <file_sep>/README.md # Lost Treasures A game about diving for coins in shallow waters for [js13kGames][js13kgames] 2017. The Theme was "lost". Play it [here][play]. [js13kgames]: http://js13kgames.com/entries/2017 [play]: http://hhsw.de/sites/proto/js13k2017/
dc2ff27a9d0ff52f151f8d5075f3ff270d48084f
[ "JavaScript", "Markdown" ]
2
JavaScript
js13kGames/lost-treasures
3cd34b5dbc7b332764e730233c983800d970b28f
c4b413f32cc4084c912348972923ea726b99d8f7
refs/heads/master
<file_sep>REACT_APP_NOT_SECRET_CODE= REACT_APP_INFURA_KEY= REACT_APP_TREZOR_MANIFEST_EMAIL= REACT_APP_TREZOR_MANIFEST_URL= REACT_APP_FORTMATIC_KEY_RINKEBY= REACT_APP_PORTIS_DAPP_ID= REACT_APP_PORTIS_NETWORK= REACT_APP_ETHERSCAN_KEY= <file_sep>import React from "react"; import { Heading, Text, Modal, Box, Button, } from "rimble-ui"; import ModalCard from './ModalCard'; export default function ApproveModal(props) { const { isOpen, closeModal, onClick, tokenName, baseTokenName } = props; const isRedeeming = tokenName.charAt(0) === 'c'; return ( <Modal isOpen={isOpen}> <ModalCard closeFunc={closeModal}> <ModalCard.Body> <Box mt={3} mb={3}> <Heading color={'black'} fontSize={[4, 5]}>Enabling {tokenName} tokens</Heading> <Text fontSize={[2, 3]} my={3}> What it means? </Text> <Text fontSize={1}> Currently {tokenName} tokens are in your wallet and you are the one and only owner of them. </Text> <Text fontSize={1}> By clicking on ENABLE you are allowing the Idle contract to actually move {tokenName} on your behalf so we can forward them on various lending protocols. </Text> <Text fontSize={[2, 3]} my={3}>You need to enable {tokenName} tokens to:</Text> <Text fontSize={1}> <ul> {isRedeeming ? <li>Redeem {baseTokenName} plus interest</li>: <li>Lend {tokenName} tokens</li> } </ul> </Text> </Box> </ModalCard.Body> <ModalCard.Footer> <Button onClick={onClick} borderRadius={4}> ENABLE {tokenName} </Button> </ModalCard.Footer> </ModalCard> </Modal> ); } <file_sep>const { expectEvent, singletons, constants, BN, expectRevert } = require('openzeppelin-test-helpers'); const { ZERO_ADDRESS } = constants; const IdleDAI = artifacts.require('IdleDAI'); const TestableIdleDAI = artifacts.require('TestableIdleDAI'); const IdleHelp = artifacts.require('IdleHelp'); const cDAIMock = artifacts.require('cDAIMock'); const iDAIMock = artifacts.require('iDAIMock'); const DAIMock = artifacts.require('DAIMock'); const BNify = n => new BN(String(n)); contract('TestableIdleDAI (internal functions exposed as public)', function ([_, registryFunder, creator, nonOwner, someone]) { beforeEach(async function () { this.DAIMock = await DAIMock.new({from: creator}); this.cDAIMock = await cDAIMock.new(this.DAIMock.address, someone, {from: creator}); this.iDAIMock = await iDAIMock.new(this.DAIMock.address, someone, {from: creator}); this.one = new BN('1000000000000000000'); this.ETHAddr = '0x0000000000000000000000000000000000000000'; this.IdleHelp = await IdleHelp.new(); await TestableIdleDAI.link(IdleHelp, this.IdleHelp.address); // this.erc1820 = await singletons.ERC1820Registry(registryFunder); this.token = await TestableIdleDAI.new( this.cDAIMock.address, this.iDAIMock.address, this.DAIMock.address, { from: creator } ); }); it('_mintCTokens', async function () { const DAIBalance = await this.DAIMock.balanceOf(creator); const expectedBalance = BNify('1000').mul(this.one); assert.equal(BNify(DAIBalance).toString(), expectedBalance.toString(), 'DAI balance is correct for owner'); // owner transfers 1 DAI to the contract await this.DAIMock.transfer(this.token.address, this.one, {from: creator}); const res = await this.token._mintCTokens.call(this.one, { from: creator }); res.should.be.bignumber.equal(new BN('5000000000')); // 50 cToken await this.token._mintCTokens(this.one, { from: creator }); const cDAIBalance = await this.cDAIMock.balanceOf(this.token.address); cDAIBalance.should.be.bignumber.equal(new BN('5000000000')); // 50 cToken // test that DAI are not present in this.token }); it('_mintITokens', async function () { const DAIBalance = await this.DAIMock.balanceOf(creator); const expectedBalance = BNify('1000').mul(this.one); assert.equal(BNify(DAIBalance).toString(), expectedBalance.toString(), 'DAI balance is correct for owner'); // owner transfers 1 DAI to the contract await this.DAIMock.transfer(this.token.address, this.one, {from: creator}); const res = await this.token._mintITokens.call(this.one, { from: creator }); res.should.be.bignumber.equal(this.one); // 1 iToken await this.token._mintITokens(this.one, { from: creator }); const iDAIBalance = await this.iDAIMock.balanceOf(this.token.address); iDAIBalance.should.be.bignumber.equal(this.one); // 1 iToken // test that DAI are not present in this.token }); it('_redeemCTokens', async function () { const DAIBalance = await this.DAIMock.balanceOf(creator); const expectedBalance = BNify('1000').mul(this.one); assert.equal(BNify(DAIBalance).toString(), expectedBalance.toString(), 'DAI balance is correct for owner'); // owner transfers 1 DAI to the contract await this.DAIMock.transfer(this.token.address, this.one, {from: creator}); // owner transfers 100 DAI to the contract await this.DAIMock.transfer(this.cDAIMock.address, BNify('100').mul(this.one), {from: creator}); await this.token._mintCTokens(this.one, { from: creator }); const cDAIBalance = await this.cDAIMock.balanceOf(this.token.address); cDAIBalance.should.be.bignumber.equal(new BN('5000000000')); // 50 cToken await this.cDAIMock.setExchangeRateStoredForTest(); const res = await this.token._redeemCTokens.call(cDAIBalance, this.token.address, { from: creator }); res.should.be.bignumber.equal(new BN('1100000000000000000')); await this.token._redeemCTokens(cDAIBalance, this.token.address, { from: creator }); const DAIBalanceAfter = await this.DAIMock.balanceOf(this.token.address); DAIBalanceAfter.should.be.bignumber.equal(new BN('1100000000000000000')); // test that DAI are not present in this.token }); it('_redeemCTokens to Address', async function () { const DAIBalance = await this.DAIMock.balanceOf(creator); const expectedBalance = BNify('1000').mul(this.one); assert.equal(BNify(DAIBalance).toString(), expectedBalance.toString(), 'DAI balance is correct for owner'); // owner transfers 1 DAI to the contract await this.DAIMock.transfer(this.token.address, this.one, {from: creator}); // owner transfers 100 DAI to the contract await this.DAIMock.transfer(this.cDAIMock.address, BNify('100').mul(this.one), {from: creator}); await this.token._mintCTokens(this.one, { from: creator }); const cDAIBalance = await this.cDAIMock.balanceOf(this.token.address); cDAIBalance.should.be.bignumber.equal(new BN('5000000000')); // 50 cToken await this.cDAIMock.setExchangeRateStoredForTest(); const res = await this.token._redeemCTokens.call(cDAIBalance, creator, { from: creator }); res.should.be.bignumber.equal(new BN('1100000000000000000')); await this.token._redeemCTokens(cDAIBalance, creator, { from: creator }); const DAIBalanceAfter = await this.DAIMock.balanceOf(creator); DAIBalanceAfter.should.be.bignumber.equal(new BN('900100000000000000000')); // test that DAI are not present in this.token }); it('_redeemITokens', async function () { const DAIBalance = await this.DAIMock.balanceOf(creator); const expectedBalance = BNify('1000').mul(this.one); assert.equal(BNify(DAIBalance).toString(), expectedBalance.toString(), 'DAI balance is correct for owner'); // owner transfers 1 DAI to the contract await this.DAIMock.transfer(this.token.address, this.one, {from: creator}); // owner transfers 100 DAI to the contract await this.DAIMock.transfer(this.iDAIMock.address, BNify('100').mul(this.one), {from: creator}); const res = await this.token._redeemITokens.call(this.one, this.token.address, { from: creator }); res.should.be.bignumber.equal(this.one); // 1 iDAI await this.token._redeemITokens(this.one, this.token.address, { from: creator }); const DAIBalanceAfter = await this.DAIMock.balanceOf(this.token.address); DAIBalanceAfter.should.be.bignumber.equal(this.one.mul(new BN('2'))); // 2 DAI (one was sent before) // test that DAI are not present in this.token }); }); <file_sep>import React, { Component } from 'react'; import { Flex, Icon, Text, Heading } from 'rimble-ui' // import styles from './Faquestion.module.scss'; class Faquestion extends Component { state = { isShowingAnswer: false }; toggleAnswer(e) { e.preventDefault(); this.setState(state => ({...state, isShowingAnswer: !state.isShowingAnswer})); }; render() { return ( <Flex pt={(this.props.pt || this.props.pt === 0) ? this.props.pt : [2, 4]} flexDirection={['column']} alignItems={'baseline'} justifyContent={'center'}> <Heading.h4 fontFamily={'sansSerif'} style={{cursor: 'pointer'}} fontWeight={2} color={this.state.isShowingAnswer ? 'blue' : 'copyColor'} pt={(this.props.pt || this.props.pt === 0) ? this.props.pt : 2} pb={2} my={0} onClick={this.toggleAnswer.bind(this)}> <Flex alignItems={'center'}> <Icon name={this.state.isShowingAnswer ? 'Close' : 'Add'} color={this.state.isShowingAnswer ? 'blue' : 'copyColor'} size={"1.5em"} mr={[2]} /> {this.props.question} </Flex> </Heading.h4> {this.state.isShowingAnswer && <Text.p textAlign={'justify'} fontSize={[2,3]}> {this.props.answer} </Text.p> } </Flex> ); } } export default Faquestion; <file_sep># Idle - Get the best out of your lend, with just one token Live demo on Mainnet [https://idle.finance](https://idle.finance) This is a PoC for Gitcoin Beyond Blockchain Hackathon. (Use at your own risk) We are tokeninzing the **best interest rate** across different lending protocols on the Ethereum money market. This product allows investor to optimize profitability. By buying and holding **IdleDAI** (an ERC20) tokens your underlying DAI position will be automatically rebalanced when the best rate changes to always give you the most profitable return. Currently we are integrated with Compound V2 and Fulcrum and we are supporting DAI stablecoin as first asset. ## Decentralized rebalance Every time a user interacts with the platform (mint or redeem idleTokens), there will being an **automated rebalance** of the whole pool, if needed. If, for sometime, there are no interactions with the contract and users spot an higher rate than the Idle current tracked one, there will be an available action that allows users to rebalance the entire pool position In order to optimize their personal returns, users are encouraged to rebalance their own positions, rebalancing consequently also all the others. We will also periodically rebalance Idle pool, if any interaction with the contract has not been done for long time. It can be considered a sort of decentralized rebalance and uses the Adam Smith' invisible hand principle, which can be summarised as the unintended social benefits of an individual's self-interested actions. In this case, this will be the users willingness to earn the highest yield on the market. ## Edge cases #### Interest Rate Slippage During the rebalancing process, we are converting the entire pool from one protocol to another, potentially lowering the target interest rate, with the possible scenario where this rate falls below the previous one. We planned to implement a preventive check in order to get rid of this issue. #### Failed iTokens Redeem When redeeming IdleTokens, there is the possibility that Fulcrum' liquidity won't be enough. In that case user will be entiteled to redeem the remaining funds directly on Fulcrum contract. ## Next steps: - Implement solutions for edge cases - Other assets integrations - Other lending protocols integrations - Improve further UI/UX on boarding - Direct fiat-to-crypto gateway ## Built with - truffle-react - web3-react (for Fortmatic, Metamask, Portis, Trezor and Ledger integration) - rimble-ui - Compound V2 - Fulcrum ## Made by @bugduino @samster91 @panteo92 @lucaguglielmi <file_sep>import React from "react"; import { Heading, Text, Box, Flex, Icon } from "rimble-ui"; function TransactionFeeModal(props) { return ( <Box> <Heading.h2 fontSize={[4, 5]}>Transaction fees</Heading.h2> <Text my={3} fontSize={[2, 3]}> You need to pay a fee to use the Ethereum blockchain. This pays for someone to process your transaction and store the data. </Text> <Heading.h4 fontSize={[2, 3]}>What are you paying for?</Heading.h4> <Flex flexDirection={['column', 'row']} justifyContent={"space-between"} my={[0, 4]}> <Box flex={'1 1'} width={1} mt={[3, 0]} mb={[4, 0]} mr={4}> <Flex justifyContent={"center"} mb={3}> <Icon name="Fingerprint" color="primary" size="4em" /> </Flex> <Heading fontSize={2}>Undeniable proof</Heading> <Text fontSize={1}> You get a public record of any funds you send or receive, a bit like a deed for a house. </Text> </Box> <Box flex={'1 1'} width={1} mt={[3, 0]} mb={[4, 0]} mr={4}> <Flex justifyContent={"center"} mb={3}> <Icon name="EnhancedEncryption" color="primary" size="4em" /> </Flex> <Heading fontSize={2}>Unbreakable encryption</Heading> <Text fontSize={1}> Your funds can only ever go to your intended recipients. </Text> </Box> <Box flex={'1 1'} width={1} mt={[3, 0]} mb={[4, 0]} mr={4}> <Flex justifyContent={"center"} mb={3}> <Icon name="AccountBalance" color="primary" size="4em" /> <Icon name="NotInterested" color="primary" size="4em" /> </Flex> <Heading fontSize={2}>Unparalleled control</Heading> <Text fontSize={1}> You can pay or get paid without using any banks or companies. </Text> </Box> </Flex> </Box> ); } export default TransactionFeeModal; <file_sep>import React from "react"; import styled from 'styled-components' import { Text, Table, Pill, Link, Flex } from "rimble-ui"; const TransactionTable = styled(Table)` & { display: block; width: 100%; overflow: auto; border-width: 0; } th, td { border: solid; border-width: 1px; border-color: inherit; padding: 0 1.5rem; } `; class TransactionsCard extends React.Component { // TODO store and retrieve past txs // this.state = { // storedTxs: null // }; // // componentDidMount() { // const txs = this.props.transactions; // const storedTxs = JSON.parse(localStorage.getItem('storedTxs')); // // } render() { let title = ''; if (Object.keys(this.props.transactions).length < 1 && this.props.balance && parseFloat(this.props.balance) <= 0) { title = "No activity yet. Lend some assets to start a transaction. " ; } else if (Object.keys(this.props.transactions).length >= 1) { title = "Activities" } return ( <Flex px={4} mx={'auto'} flexDirection={'column'}> <Text my={2} fontWeight={3} textAlign={"center"}> {title} </Text> <TransactionTable> <thead> {Object.keys(this.props.transactions).length > 0 ? ( <tr> <th>Method</th> <th>Status</th> <th>Created</th> <th>Updated</th> <th>Confirmations</th> <th>txHash</th> </tr> ) : null} </thead> <tbody> {Object.keys(this.props.transactions).map((keyName, keyIndex) => { let txHash = ""; if (this.props.transactions[keyName].transactionHash) { txHash = this.props.transactions[ keyName ].transactionHash.toString(); // const txStart = txHash.substr(0, 7); // const txEnd = txHash.substr(txHash.length - 4); // txHash = txStart + "..." + txEnd; } let eventCreated = new Date(this.props.transactions[keyName].created); let eventUpdated = new Date(this.props.transactions[keyName].lastUpdated); const method = this.props.transactions[keyName].method; let humanMethod; switch (method) { case 'mintIdleToken': humanMethod = 'Lend' break; case 'redeemIdleToken': humanMethod = 'Redeem' break; default: humanMethod = method; } const status = this.props.transactions[keyName].status; let color; switch (status) { case 'success': color = 'green'; break; case 'error': color = 'red'; break; default: color = 'dark-gray'; } return ( <tr key={keyIndex}> <td> <code> {humanMethod} </code> </td> <td> <Pill color={color}> {status} </Pill> </td> <td> {eventCreated.toDateString()} </td> <td> {eventUpdated.toTimeString()} </td> <td> {this.props.transactions[keyName].confirmationCount} </td> <td> <Link href={'https://etherscan.io/tx/'+txHash} target={'_blank'}> {txHash} </Link> </td> </tr> ); })} </tbody> </TransactionTable> </Flex> ); } } export default TransactionsCard; <file_sep>import React, { Component } from "react"; import { Button, Image, Flex, Text } from 'rimble-ui'; import styles from './CryptoButton.module.scss'; // export default function ImageTextBox(props) { class CryptoButton extends Component { state = { selected: false }; render() { return ( <Button mainColor="white" contrastColor="#5e5e5e" borderRadius={2} mx={[2, 3]} my={[1]} fontSize={2} onClick={this.props.handleClick} className={[styles.button, this.props.isSelected && styles.button_selected]}> <Flex alignItems={'center'}> <Image mr={[2]} className={[styles.image]} src={'images/btn-'+this.props.label+'.svg'} /> <Text.span className={[styles.text]}>{this.props.label.toUpperCase()}</Text.span> </Flex> </Button> ); } } export default CryptoButton; <file_sep>import { Connectors } from "web3-react"; import TrezorApi from "trezor-connect"; // import WalletConnectApi from "@walletconnect/web3-subprovider"; import FortmaticApi from "fortmatic"; import PortisApi from "@portis/web3"; const { InjectedConnector, NetworkOnlyConnector, TrezorConnector, LedgerConnector, // WalletConnectConnector, FortmaticConnector, PortisConnector } = Connectors; const env = process.env; const supportedNetworkURLs = { 1: `https://mainnet.infura.io/v3/${env.REACT_APP_INFURA_KEY}` }; const manifestEmail = env.REACT_APP_TREZOR_MANIFEST_EMAIL; // trezor const manifestAppUrl = env.REACT_APP_TREZOR_MANIFEST_URL; // trezor const defaultNetwork = 1; // mainnet // const defaultNetwork = 4; // rinkeby const fortmaticApiKey = env.REACT_APP_FORTMATIC_KEY_RINKEBY; const portisDAppId = env.REACT_APP_PORTIS_DAPP_ID; const portisNetwork = env.REACT_APP_PORTIS_NETWORK; const Injected = new InjectedConnector({ supportedNetworks: [1] }); const Infura = new NetworkOnlyConnector({ providerURL: supportedNetworkURLs[1] }); const Trezor = new TrezorConnector({ api: TrezorApi, supportedNetworkURLs, defaultNetwork, manifestEmail, manifestAppUrl }); const Ledger = new LedgerConnector({ supportedNetworkURLs, defaultNetwork }); // const WalletConnect = new WalletConnectConnector({ // api: WalletConnectApi, // bridge: "https://bridge.walletconnect.org", // supportedNetworkURLs, // defaultNetwork // }); const Fortmatic = new FortmaticConnector({ api: FortmaticApi, apiKey: fortmaticApiKey, logoutOnDeactivation: false }); const Portis = new PortisConnector({ api: PortisApi, dAppId: portisDAppId, network: portisNetwork }); export default { Injected, Infura, Fortmatic, Trezor, Ledger, // WalletConnect, Portis }; <file_sep>const { expectEvent, singletons, constants, BN, expectRevert } = require('openzeppelin-test-helpers'); const { ZERO_ADDRESS } = constants; const IdleDAI = artifacts.require('IdleDAI'); const TestableIdleDAI = artifacts.require('TestableIdleDAI'); const IdleHelp = artifacts.require('IdleHelp'); const cDAIMock = artifacts.require('cDAIMock'); const iDAIMock = artifacts.require('iDAIMock'); const DAIMock = artifacts.require('DAIMock'); const BNify = n => new BN(String(n)); contract('IdleDAI', function ([_, registryFunder, creator, nonOwner, someone, foo]) { beforeEach(async function () { this.DAIMock = await DAIMock.new({from: creator}); this.cDAIMock = await cDAIMock.new(this.DAIMock.address, someone, {from: creator}); this.iDAIMock = await iDAIMock.new(this.DAIMock.address, someone, {from: creator}); this.one = new BN('1000000000000000000'); this.ETHAddr = '0x0000000000000000000000000000000000000000'; this.IdleHelp = await IdleHelp.new(); await IdleDAI.link(IdleHelp, this.IdleHelp.address); // this.erc1820 = await singletons.ERC1820Registry(registryFunder); this.token = await IdleDAI.new( this.cDAIMock.address, this.iDAIMock.address, this.DAIMock.address, { from: creator } ); }); it('has a name', async function () { (await this.token.name()).should.equal('IdleDAI'); }); it('has a symbol', async function () { (await this.token.symbol()).should.equal('IDLEDAI'); }); it('has a cDAI addr', async function () { (await this.token.cToken()).should.equal(this.cDAIMock.address); }); it('has a iDAI addr', async function () { (await this.token.iToken()).should.equal(this.iDAIMock.address); }); it('has a DAI addr', async function () { (await this.token.token()).should.equal(this.DAIMock.address); }); it('has blocksInAYear', async function () { (await this.token.blocksInAYear()).toString().should.equal((new BN('2102400')).toString()); }); it('has minRateDifference', async function () { (await this.token.minRateDifference()).toString().should.equal((new BN('100000000000000000')).toString()); }); it('allows onlyOwner to setMinRateDifference ', async function () { const val = new BN('1e18'); await this.token.setMinRateDifference(val, { from: creator }); (await this.token.minRateDifference()).toString().should.equal(val.toString()); await expectRevert.unspecified(this.token.setMinRateDifference(val, { from: nonOwner })); }); it('allows onlyOwner to setBlocksInAYear ', async function () { const val = new BN('1e18'); await this.token.setBlocksInAYear(val, { from: creator }); (await this.token.blocksInAYear()).toString().should.equal(val.toString()); await expectRevert.unspecified(this.token.setBlocksInAYear(val, { from: nonOwner })); }); it('allows onlyOwner to setToken ', async function () { const val = '0x0000000000000000000000000000000000000001'; await this.token.setToken(val, { from: creator }); (await this.token.token()).should.equal(val); await expectRevert.unspecified(this.token.setToken(val, { from: nonOwner })); }); it('allows onlyOwner to setIToken ', async function () { const val = '0x0000000000000000000000000000000000000001'; await this.token.setIToken(val, { from: creator }); (await this.token.iToken()).should.equal(val); await expectRevert.unspecified(this.token.setIToken(val, { from: nonOwner })); }); it('allows onlyOwner to setCToken ', async function () { const val = '0x0000000000000000000000000000000000000001'; await this.token.setCToken(val, { from: creator }); (await this.token.cToken()).should.equal(val); await expectRevert.unspecified(this.token.setCToken(val, { from: nonOwner })); }); it('rebalance method should set bestToken if current best token is address(0)', async function () { await this.token.rebalance({ from: creator }); const bestToken = await this.token.bestToken({ from: creator }); bestToken.should.be.equal(this.cDAIMock.address); }); it('rebalance method should not rebalance if it\'s not needed', async function () { // first rebalance to set from address(0) to cToken await this.token.rebalance({ from: creator }); const bestToken = await this.token.bestToken({ from: creator }); bestToken.should.be.equal(this.cDAIMock.address); // second rebalance should not change bestToken await this.token.rebalance({ from: creator }); const bestToken2 = await this.token.bestToken({ from: creator }); bestToken2.should.be.equal(this.cDAIMock.address); }); it('rebalance should change bestToken if rates are changed', async function () { // Needed for testing, owner transfers 100 DAI to the contract await this.DAIMock.transfer(this.cDAIMock.address, BNify('100').mul(this.one), {from: creator}); // first rebalance to set from address(0) to cToken await this.token.rebalance({ from: creator }); const bestToken = await this.token.bestToken({ from: creator }); bestToken.should.be.equal(this.cDAIMock.address); await this.cDAIMock.setSupplyRatePerBlockForTest({ from: creator }); // second rebalance should change bestToken await this.token.rebalance({ from: creator }); const bestToken2 = await this.token.bestToken({ from: creator }); bestToken2.should.be.equal(this.iDAIMock.address); }); it('rebalance should convert the entire pool if rates are changed (from cToken to iToken)', async function () { // Needed for testing, owner transfers 100 DAI to the contract const oneCToken = new BN('100000000'); // 10**8 -> 1 cDAI await this.DAIMock.transfer(this.cDAIMock.address, BNify('100').mul(this.one), {from: creator}); await this.cDAIMock.transfer(this.token.address, BNify('50').mul(oneCToken), {from: someone}); // first rebalance to set from address(0) to cToken await this.token.rebalance({ from: creator }); const bestToken = await this.token.bestToken({ from: creator }); bestToken.should.be.equal(this.cDAIMock.address); (await this.iDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(new BN('0')); await this.cDAIMock.setSupplyRatePerBlockForTest({ from: creator }); // second rebalance changes bestToken to iToken and convert the pool await this.token.rebalance({ from: creator }); const bestToken2 = await this.token.bestToken({ from: creator }); bestToken2.should.be.equal(this.iDAIMock.address); (await this.iDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(new BN('998231572268577347')); (await this.cDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(new BN('0')); }); it('rebalance should convert the entire pool if rates are changed (from iToken to cToken)', async function () { await this.cDAIMock.setSupplyRatePerBlockForTest({ from: creator }); // Needed for testing, owner transfers 100 DAI to the contract await this.DAIMock.transfer(this.iDAIMock.address, BNify('100').mul(this.one), {from: creator}); // Needed for testing, someone transfers 1 iDAI to the contract await this.iDAIMock.transfer(this.token.address, this.one, {from: someone}); // first rebalance to set from address(0) to iToken await this.token.rebalance({ from: creator }); const bestToken = await this.token.bestToken({ from: creator }); bestToken.should.be.equal(this.iDAIMock.address); (await this.cDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(new BN('0')); await this.cDAIMock.resetSupplyRatePerBlockForTest({ from: creator }); // second rebalance changes bestToken to iToken and convert the pool await this.token.rebalance({ from: creator }); const bestToken2 = await this.token.bestToken({ from: creator }); bestToken2.should.be.equal(this.cDAIMock.address); const oneCToken = new BN('100000000'); // 10**8 -> 1 cDAI (await this.cDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(oneCToken.mul(new BN('50'))); // error on TestableIdleDAI when using _burn in iDAIMock // (await this.iDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(new BN('0')); }); it('claimITokens', async function () { const oneCToken = new BN('100000000'); // 10**8 -> 1 cDAI // Needed for testing, owner transfers 100 DAI to the contract await this.DAIMock.transfer(this.iDAIMock.address, BNify('100').mul(this.one), {from: creator}); await this.DAIMock.transfer(this.cDAIMock.address, BNify('100').mul(this.one), {from: creator}); await this.cDAIMock.transfer(this.token.address, BNify('50').mul(oneCToken), {from: someone}); // first rebalance to set from address(0) to cToken await this.token.rebalance({ from: creator }); const bestToken = await this.token.bestToken({ from: creator }); bestToken.should.be.equal(this.cDAIMock.address); (await this.iDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(new BN('0')); await this.cDAIMock.setSupplyRatePerBlockForTest({ from: creator }); // second rebalance changes bestToken to iToken and convert the pool const claimedTokens = await this.token.claimITokens.call({ from: creator }); claimedTokens.should.be.bignumber.equal(this.one); await this.token.claimITokens({ from: creator }); // It makes a rebalance so new bestToken is iDAI const bestToken2 = await this.token.bestToken({ from: creator }); bestToken2.should.be.equal(this.iDAIMock.address); (await this.cDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(new BN('0')); (await this.iDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(new BN('1998231572268577347')); }); it('mintIdleToken when bestToken is address(0)', async function () { const oneCToken = new BN('100000000'); // 10**8 -> 1 cDAI // Needed for testing, owner transfers 100 DAI to the contract // await this.DAIMock.transfer(this.iDAIMock.address, BNify('100').mul(this.one), {from: creator}); // await this.DAIMock.transfer(this.cDAIMock.address, BNify('100').mul(this.one), {from: creator}); // await this.cDAIMock.transfer(this.token.address, BNify('50').mul(oneCToken), {from: someone}); // approve idleDAI as DAI spender, one DAI await this.DAIMock.approve(this.token.address, this.one, {from: creator}); const mintedIdleTokens = await this.token.mintIdleToken.call(this.one, { from: creator }); mintedIdleTokens.should.be.bignumber.equal(this.one); await this.token.mintIdleToken(this.one, { from: creator }); // first it rebalances and set from address(0) to cToken const bestToken = await this.token.bestToken({ from: creator }); bestToken.should.be.equal(this.cDAIMock.address); // Idle contract has 50 cDAI (await this.cDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(BNify('50').mul(oneCToken)); // caller has 1 idleDAI (await this.token.balanceOf(creator)).should.be.bignumber.equal(this.one); }); it('mintIdleToken when bestToken does not changes', async function () { // Needed for testing, owner transfers 100 DAI to the contract // await this.DAIMock.transfer(this.iDAIMock.address, BNify('100').mul(this.one), {from: creator}); // await this.cDAIMock.transfer(this.token.address, BNify('50').mul(oneCToken), {from: someone}); // ====== First interaction (initialization rate = 1DAI : 1idleDAI) const oneCToken = new BN('100000000'); // 10**8 -> 1 cDAI // approve idleDAI as DAI spender, one DAI await this.DAIMock.approve(this.token.address, this.one, {from: creator}); const mintedIdleTokens = await this.token.mintIdleToken.call(this.one, { from: creator }); mintedIdleTokens.should.be.bignumber.equal(this.one); await this.token.mintIdleToken(this.one, { from: creator }); // first it rebalances and set from address(0) to cToken const bestToken = await this.token.bestToken({ from: creator }); bestToken.should.be.equal(this.cDAIMock.address); // Idle contract has 50 cDAI (await this.cDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(BNify('50').mul(oneCToken)); // caller has 1 idleDAI (await this.token.balanceOf(creator)).should.be.bignumber.equal(this.one); // Set new rates for testing await this.cDAIMock.setExchangeRateStoredForTest(); await this.cDAIMock.setMintValueForTest(); // Now the nav is 50 * 0.022 = 1.1 DAI // creator gives 5 DAI to nonOwner await this.DAIMock.transfer(nonOwner, this.one.mul(new BN('5')), {from: creator}); // creator gives 100 DAI to cDAI await this.DAIMock.transfer(this.cDAIMock.address, BNify('100').mul(this.one), {from: creator}); // ====== Other interaction await this.DAIMock.approve(this.token.address, this.one, {from: nonOwner}); // after the tx we will have: // 1 / 0.022 = 45.45454545 cDAI more in the pool // curr priceIdle = 1.1/1 = 1.1 DAI // so he will get 1/1.1 = 0.90909090 IDLEDAI // call should always be before the tx! const otherIdleTokens = await this.token.mintIdleToken.call(this.one, { from: nonOwner }); otherIdleTokens.should.be.bignumber.equal(new BN('909090909090909090')); // 0.9090 Idle await this.token.mintIdleToken(this.one, { from: nonOwner }); (await this.token.balanceOf(nonOwner)).should.be.bignumber.equal(new BN('909090909090909090')); (await this.cDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(new BN('9545454545')); // 95.4545 ERC20Detailed (await this.DAIMock.balanceOf(nonOwner)).should.be.bignumber.equal(BNify('4').mul(this.one)); // Set new rates for testing await this.cDAIMock.setNewExchangeRateStoredForTest(); // Now the nav is 95.4545 * 0.03 = 2.8636363499999997 DAI // so idlePrice = nav / supply = 2.8636363499999997 / 1.9090909 = 1.5 // ====== Other interaction // creator gives 5 DAI to foo await this.DAIMock.transfer(foo, this.one.mul(new BN('5')), {from: creator}); await this.DAIMock.approve(this.token.address, this.one, {from: foo}); // after the tx we will have: // 1 / 0.03 = 33.333333 cDAI more in the pool // curr priceIdle = 2.8636363499999997/1.9090909090 = 1.5 DAI more or less // so he will get 1/1.5 = 0.6666666666666666 IDLEDAI more or less // call should always be before the tx! const fooIdleTokens = await this.token.mintIdleToken.call(this.one, { from: foo }); fooIdleTokens.should.be.bignumber.equal(new BN('666666666698412698')); // 0.66666 Idle await this.token.mintIdleToken(this.one, { from: foo }); // (await this.token.balanceOf(foo)).should.be.bignumber.equal(new BN('666666666698412698')); // 128.787878 (await this.cDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(new BN('12878787878')); // 128.787878 (await this.DAIMock.balanceOf(foo)).should.be.bignumber.equal(BNify('4').mul(this.one)); }); it('mintIdleToken when bestToken does change (a rebalance happens)', async function () { // ====== First interaction (initialization rate = 1DAI : 1idleDAI) const oneCToken = new BN('100000000'); // 10**8 -> 1 cDAI // approve idleDAI as DAI spender, one DAI await this.DAIMock.approve(this.token.address, this.one, {from: creator}); const mintedIdleTokens = await this.token.mintIdleToken.call(this.one, { from: creator }); mintedIdleTokens.should.be.bignumber.equal(this.one); await this.token.mintIdleToken(this.one, { from: creator }); // first it rebalances and set from address(0) to cToken const bestToken = await this.token.bestToken({ from: creator }); bestToken.should.be.equal(this.cDAIMock.address); // Idle contract has 50 cDAI (await this.cDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(BNify('50').mul(oneCToken)); // caller has 1 idleDAI (await this.token.balanceOf(creator)).should.be.bignumber.equal(this.one); // ====== End First interaction (initialization rate = 1DAI : 1idleDAI) // Set new rates for testing await this.cDAIMock.setExchangeRateStoredForTest(); await this.cDAIMock.setMintValueForTest(); // Now the pool nav is 50 * 0.022 = 1.1 DAI // creator gives 100 DAI to cDAI await this.DAIMock.transfer(this.cDAIMock.address, BNify('100').mul(this.one), {from: creator}); // Set new rates for testing -> now iToken has the best rate await this.cDAIMock.setSupplyRatePerBlockForTest({ from: creator }); // now on fulcrum 2.9% apr and on compound 0.69% await this.iDAIMock.setPriceForTest({ from: creator }); // 1 iDAI = 1.5 DAI // current nav (cDAI) = 50 * 0.022 = 1.1 DAI // so idlePrice = nav / supply = 1.1 / 1 = 1.1 // ====== Other interaction // creator gives 5 DAI to foo await this.DAIMock.transfer(foo, this.one.mul(new BN('5')), {from: creator}); await this.DAIMock.approve(this.token.address, this.one, {from: foo}); // after the tx we will have: // first we redeem cDAI in DAI 50 * 0.022 = 1.1 DAI // then we convert 1.1 DAI in 1.1/1.5 = 0.73333333333 iDAI // then use the new DAI given from foo (1 DAI) to mint iDAI for the pool and idleDAI for foo // currTokenPrice = 0.73333333333 * 1.5 / 1IdleDAI = 1.1 DAI // so we mint 1DAI / 1.5 (iDAI price) = 0.66666666666 iDAI // and user get 1 DAI / tokenPrice = 1/1.1 = 0.90909090909 idleDAI // totalSupply = 1.90909090909 idleDAI // currTokenPrice = (0.73333333333 + 0.66666666666) * 1.5 / 1.90909090909 = 1.1 // always 1.1 given the fact that iDAI rate is the same // call should always be before the tx! const fooIdleTokens = await this.token.mintIdleToken.call(this.one, { from: foo }); fooIdleTokens.should.be.bignumber.equal(new BN('909090909090909091')); // 0.909090 Idle await this.token.mintIdleToken(this.one, { from: foo }); // (await this.iDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(new BN('1399999999999999999')); // 1.399999999989999900 (await this.token.balanceOf(foo)).should.be.bignumber.equal(new BN('909090909090909091')); (await this.token.totalSupply()).should.be.bignumber.equal(new BN('1909090909090909091')); // 1.909090 (await this.DAIMock.balanceOf(foo)).should.be.bignumber.equal(BNify('4').mul(this.one)); }); it('redeemIdleToken', async function () { // Needed for testing, owner transfers 100 DAI to the contract // await this.DAIMock.transfer(this.iDAIMock.address, BNify('100').mul(this.one), {from: creator}); // await this.cDAIMock.transfer(this.token.address, BNify('50').mul(oneCToken), {from: someone}); // ====== First interaction (initialization rate = 1DAI : 1idleDAI) const oneCToken = new BN('100000000'); // 10**8 -> 1 cDAI // approve idleDAI as DAI spender, one DAI await this.DAIMock.approve(this.token.address, this.one, {from: creator}); const mintedIdleTokens = await this.token.mintIdleToken.call(this.one, { from: creator }); mintedIdleTokens.should.be.bignumber.equal(this.one); await this.token.mintIdleToken(this.one, { from: creator }); // first it rebalances and set from address(0) to cToken const bestToken = await this.token.bestToken({ from: creator }); bestToken.should.be.equal(this.cDAIMock.address); // Idle contract has 50 cDAI (await this.cDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(BNify('50').mul(oneCToken)); // caller has 1 idleDAI (await this.token.balanceOf(creator)).should.be.bignumber.equal(this.one); // Set new rates for testing await this.cDAIMock.setExchangeRateStoredForTest(); // Now the nav is 50 * 0.022 = 1.1 await this.cDAIMock.setMintValueForTest(); await this.DAIMock.transfer(nonOwner, this.one.mul(new BN('5')), {from: creator}); await this.DAIMock.transfer(this.cDAIMock.address, BNify('100').mul(this.one), {from: creator}); // ====== Other interaction await this.DAIMock.approve(this.token.address, this.one, {from: nonOwner}); // call should always be before the tx! const otherIdleTokens = await this.token.mintIdleToken.call(this.one, { from: nonOwner }); otherIdleTokens.should.be.bignumber.equal(new BN('909090909090909090')); // 0.9090 Idle await this.token.mintIdleToken(this.one, { from: nonOwner }); (await this.token.balanceOf(nonOwner)).should.be.bignumber.equal(new BN('909090909090909090')); (await this.cDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(new BN('9545454545')); // 95.4545 ERC20Detailed (await this.DAIMock.balanceOf(nonOwner)).should.be.bignumber.equal(BNify('4').mul(this.one)); // ====== Now creator redeems // call should always be before the tx! const currOwnerBalanceIdleDAI = await this.DAIMock.balanceOf(creator); currOwnerBalanceIdleDAI.should.be.bignumber.equal(new BN('894000000000000000000')); // 1.1 DAI const daiRedeemed = await this.token.redeemIdleToken.call(await this.token.balanceOf(creator), { from: creator }); // **** WARNING: there are some rounding issues this should be 1100000000000000000 ? daiRedeemed.should.be.bignumber.equal(new BN('1099999999780000000')); // 1.1 DAI // daiRedeemed.should.be.bignumber.equal(new BN('1100000000000000000')); // 1.1 DAI // redeem all balance of 1IdleDAI await this.token.redeemIdleToken((await this.token.balanceOf(creator)), { from: creator }); const currOwnerBalanceDAI = await this.DAIMock.balanceOf(creator); // creator has no idleDAI (await this.token.balanceOf(creator)).should.be.bignumber.equal(new BN('0')); // idle contract has 45.45 cDAI (of nonOwner) // **** WARNING: there are some rounding issues this should be 1100000000000000000 ? (await this.cDAIMock.balanceOf(this.token.address)).should.be.bignumber.equal(new BN('4545454546')); // 45.4545 ERC20Detailed // **** WARNING: there are some rounding issues this should be 1100000000000000000 ? (await this.DAIMock.balanceOf(creator)).should.be.bignumber.equal(currOwnerBalanceIdleDAI.add(new BN('1099999999780000000'))); // (await this.DAIMock.balanceOf(creator)).should.be.bignumber.equal(currOwnerBalanceDAI.add(new BN('1100000000000000000'))); }); }); <file_sep>import React, { Component } from 'react'; import { Image, Flex, Box, Heading, Button, Link, Text } from 'rimble-ui' import BigNumber from 'bignumber.js'; import styles from './Landing.module.scss'; import LandingForm from '../LandingForm/LandingForm'; import IconFlexRow from '../IconFlexRow/IconFlexRow'; import Faq from '../Faq/Faq'; import NewsletterForm from '../NewsletterForm/NewsletterForm'; class Landing extends Component { state = {}; async componentDidUpdate(prevProps) { let prevContract = (prevProps.contracts.find(c => c.name === 'IdleDAI') || {}).contract; let contract = (this.props.contracts.find(c => c.name === 'IdleDAI') || {}).contract; if (contract && prevContract !== contract) { console.log('Getting APR'); await this.getAprs(); } } // utilities trimEth = eth => { return this.BNify(eth).toFixed(6); }; BNify = s => new BigNumber(String(s)); toEth(wei) { return this.props.web3.utils.fromWei( (wei || 0).toString(), "ether" ); } toWei(eth) { return this.props.web3.utils.toWei( (eth || 0).toString(), "ether" ); } getAprs = async () => { let aprs = await this.genericIdleCall('getAPRs'); this.setState({ [`compoundRate`]: aprs ? (+this.toEth(aprs[0])).toFixed(2) : '0.00', [`fulcrumRate`]: aprs ? (+this.toEth(aprs[1])).toFixed(2) : '0.00', [`maxRate`]: aprs ? (+this.toEth(Math.max(aprs[0],aprs[1]))).toFixed(2) : '0.00', needsUpdate: false }); }; genericContractCall = async (contractName, methodName, params = []) => { let contract = this.props.contracts.find(c => c.name === contractName); contract = contract && contract.contract; if (!contract) { console.log('Wrong contract name', contractName); return; } const value = await contract.methods[methodName](...params).call().catch(error => { console.log(`${contractName} contract method ${methodName} error: `, error); this.setState({ error }); }); return value; } // Idle genericIdleCall = async (methodName, params = []) => { return await this.genericContractCall('IdleDAI', methodName, params).catch(err => { console.error('Generic Idle call err:', err); }); } startLending = async e => { this.props.updateSelectedTab(e, '1'); window.location.href = '#invest'; } render() { const { network } = this.props; return ( <Box style={{ paddingBottom: !network.isCorrectNetwork ? "8em" : "0" }} > <Box className={[styles.headerContainer]} pt={['2em', '2em']}> <Box className={[styles.bgContainer,styles.bg1]} display={['none','block']}></Box> <Box className={[styles.bgContainer,styles.bg2]} display={['none','block']}></Box> <Box position={'relative'} zIndex={10}> <Flex flexDirection={'column'} alignItems={['center','flex-start']} maxWidth={["50em", "50em"]} mx={['auto', 6]} pb={3} px={[2,0]} textAlign={['center','left']} pt={['10vh', '20vh']}> <Heading.h1 fontFamily={'sansSerif'} lineHeight={'1.1em'} mb={'0.5em'} fontSize={['2.5em',7]} textAlign={['center','left']}> Get the best out of your lend, with just one token </Heading.h1> <Heading.h2 fontWeight={'400'} lineHeight={['1.4em', '2em']} fontSize={[3,4]} textAlign={['center','left']}> We connect different lending protocols with a decentralized rebalance process to always give you the best available rate </Heading.h2> <Button onClick={e => this.startLending(e)} className={[styles.button]} size={this.props.isMobile ? 'medium' : 'large'} contrastColor={'blue'} mainColor={'white'} fontSize={[2, 4]} px={[4, 5]} mt={[4, 4]} mb={[5, '70vh']} > START LENDING </Button> </Flex> <Box id='invest' position={'relative'} width={['auto','100%']} mt={['0','-250px']}> <Box position={'absolute'} zIndex={'0'} width={'100%'} height={'50%'} top={'50%'} left={'0'} backgroundColor={'#f7f7f7'}></Box> <Box position={'relative'} zIndex={'1'}> <LandingForm accountBalanceDAI={this.props.accountBalanceDAI} isMobile={this.props.isMobile} updateSelectedTab={this.props.updateSelectedTab} selectedTab={this.props.selectedTab} /> </Box> </Box> </Box> </Box> <Box className={[styles.graySection]} pt={0}> <Box maxWidth={['50em','70em']} mx={[3, 'auto']} pt={0} pb={[4, 0]}> <IconFlexRow image={'images/feature-1.png'} title='100% non-custodial, thanks to our contract.' linkHref={'https://etherscan.io/address/0xAcf651Aad1CBB0fd2c7973E2510d6F63b7e440c9#code'} linkText='Smart contract' /> <IconFlexRow image={'images/feature-2.png'} title='Fully decentralized, thanks to our users.' handleClick={e => this.props.updateSelectedTab(e,'3')} linkHref={'#invest'} linkText='Rebalance process' /> <IconFlexRow image={'images/feature-3.png'} title='No hidden fees, best things in life are free!' linkHref={'#how-it-works'} linkText='See how it works' /> </Box> </Box> { /* <Box className={[styles.graySection]} pt={0}> <Flex maxWidth={'100%'} flexDirection={['column','row']}> <Box position={'relative'} width={[1, 1/2]} p={[4,6]} backgroundColor={'blue'} color={'white'}> <Heading.h3 fontFamily={'sansSerif'} fontSize={[5,6]} mb={[3,4]}>Asset Managers</Heading.h3> <Heading.h4 fontWeight={1} lineHeight={2}> Enhance profitability for your customers and optimize portfolio returns. </Heading.h4> <Box display={['none','block']}> <Button onClick={e => this.startLending(e)} borderRadius={4} size={'large'} mainColor={'lightBlue'} contrastColor={'blue'} fontWeight={2} fontSize={[2,3]} px={[4,5]} mt={[4,4]}>INVEST NOW</Button> </Box> <Box display={['block','none']}> <Button onClick={e => this.startLending(e)} borderRadius={4} size={'medium'} mainColor={'lightBlue'} contrastColor={'blue'} fontWeight={2} fontSize={[2,3]} px={[4,5]} mt={[4,4]}>INVEST NOW</Button> </Box> </Box> <Box position={'relative'} width={[1, 1/2]} overflow={['hidden','visible']} p={[4,6]} backgroundColor={'white'} color={'blue'}> <Box className={styles.skewBg}></Box> <Box position={'relative'} zIndex={2}> <Heading.h3 fontFamily={'sansSerif'} fontSize={[5,6]} mb={[3,4]}>Retail Investors</Heading.h3> <Heading.h4 color={'black'} fontWeight={1} lineHeight={2}> Are you a yield seeker? Make your money grows at the fastest pace on the market. </Heading.h4> <Box display={['none','block']}> <Button onClick={e => this.startLending(e)} borderRadius={4} size={'large'} mainColor={'blue'} contrastColor={'white'} fontWeight={2} fontSize={[2,3]} px={[4,5]} mt={[3,4]}>START EARNING</Button> </Box> <Box display={['block','none']}> <Button onClick={e => this.startLending(e)} borderRadius={4} size={'medium'} mainColor={'blue'} contrastColor={'white'} fontWeight={2} fontSize={[2,3]} px={[4,5]} mt={[3,4]}>START EARNING</Button> </Box> </Box> </Box> </Flex> </Box> */ } <Box id='how-it-works' pb={[0,6]}> <Box> <Heading.h2 fontFamily={'sansSerif'} fontSize={[5,6]} textAlign={'center'} py={[4,5]} alignItems={'center'} my={0}> How it Works </Heading.h2> <Flex flexDirection={['column','column']} alignItems={'center'}> <Flex alignItems={'center'} flexDirection={'column'} width={1}> <Flex flexDirection={['column','row']}> <Flex width={[1,1/2]} justifyContent={'flex-end'} borderRight={[0,'1px solid #eee']}> <Box position={'relative'} className={styles.bulletCard} width={[1,2/3]} mr={[0,'45px']} mb={[2,4]}> <Text lineHeight={'50px'} fontSize={'22px'} color={'white'} position={'absolute'} display={'block'} className={[styles.bulletPoint,styles.bulletRight]}>1</Text> <Heading.h3 pt={[2]} textAlign={['center','right']} fontFamily={'sansSerif'} fontSize={[4,5]} mb={[2,3]} color={'blue'}> Lend your assets </Heading.h3> <Heading.h4 fontSize={[2,3]} px={[3,0]} textAlign={['center','right']} fontWeight={2} lineHeight={1.5}> Connect your Ethereum wallet and lend some idle crypto assets to get started. You will receive IdleTokens representing your contract pool share. </Heading.h4> </Box> </Flex> <Flex width={[1,1/2]}></Flex> </Flex> <Flex flexDirection={['column','row']}> <Flex width={[1,1/2]} borderRight={[0,'1px solid #eee']}></Flex> <Flex width={[1,1/2]} justifyContent={'flex-start'}> <Box position={'relative'} className={styles.bulletCard} width={[1,2/3]} ml={[0,'45px']} mb={[2,4]}> <Text lineHeight={'50px'} fontSize={'22px'} color={'white'} position={'absolute'} display={'block'} className={[styles.bulletPoint,styles.bulletLeft]}>2</Text> <Heading.h3 pt={[2]} textAlign={['center','left']} fontFamily={'sansSerif'} fontSize={[4,5]} mb={[2,3]} color={'blue'}> Earn interests </Heading.h3> <Heading.h4 fontSize={[2,3]} px={[3,0]} textAlign={['center','left']} fontWeight={2} lineHeight={1.5}> Your funds will be automatically allocated among the best available interest bearing tokens. You will immediately start earning compounded interest with a block-per-block pace. </Heading.h4> </Box> </Flex> </Flex> <Flex flexDirection={['column','row']}> <Flex width={[1,1/2]} justifyContent={'flex-end'} borderRight={[0,'1px solid #eee']}> <Box position={'relative'} className={styles.bulletCard} width={[1,2/3]} mr={[0,'45px']} mb={[2,4]}> <Text lineHeight={'50px'} fontSize={'22px'} color={'white'} position={'absolute'} display={'block'} className={[styles.bulletPoint,styles.bulletRight]}>3</Text> <Heading.h3 pt={[2]} textAlign={['center','right']} fontFamily={'sansSerif'} fontSize={[4,5]} mb={[2,3]} color={'blue'}> Decentralized rebalance </Heading.h3> <Heading.h4 fontSize={[2,3]} px={[3,0]} textAlign={['center','right']} fontWeight={2} lineHeight={1.5}> Every interaction with Idle, made by any user, rebalances the entire pool if needed. If the current tracked rate is not the actual best, you have the power to rebalance on behalf of all users. One for all, all for one. </Heading.h4> </Box> </Flex> <Flex width={[1,1/2]}></Flex> </Flex> <Flex flexDirection={['column','row']}> <Flex width={[1,1/2]} borderRight={[0,'1px solid #eee']} height={[0,'125px']}></Flex> <Flex width={[1,1/2]} justifyContent={'flex-start'}> <Box position={'relative'} className={styles.bulletCard} width={[1,2/3]} ml={[0,'45px']}> <Text lineHeight={'50px'} fontSize={'22px'} color={'white'} position={'absolute'} display={'block'} className={[styles.bulletPoint,styles.bulletLeft]}>4</Text> <Heading.h3 pt={[2]} textAlign={['center','left']} fontFamily={'sansSerif'} fontSize={[4,5]} mb={[2,3]} color={'blue'}> Easy Redeem </Heading.h3> <Heading.h4 fontSize={[2,3]} px={[3,0]} textAlign={['center','left']} fontWeight={2} lineHeight={1.5}> At anytime you can redeem your invested assets and get back your increased funds, automatically rebalancing the pool if needed. Kudos for you. </Heading.h4> </Box> </Flex> </Flex> </Flex> </Flex> </Box> </Box> <Box position={'relative'} className={[styles.graySection]} pb={[4,6]}> <Box className={[styles.bgContainer,styles.bgHeart]}></Box> <Box position={'relative'} maxWidth={['35em','80em']} mx={'auto'}> <Heading.h2 fontFamily={'sansSerif'} fontSize={[5, 6]} textAlign={'center'} py={[4,5]} alignItems={'center'} my={0}> Get the best APR, always. </Heading.h2> <Flex alignItems={['normal','flex-end']} flexDirection={['column','row']}> <Box width={[1,3/10]}> <Box p={[4,5]} pb={0} backgroundColor={'white'} color={'black'} boxShadow={1} borderBottom={'15px solid'} borderColor={'blue'}> <Heading.h3 textAlign={['center']} fontFamily={'sansSerif'} fontSize={[3,4]} mb={[2,3]} color={'blue'}> <Image src={'images/compound-mark-green.png'} className={styles.platformLogo} /> Compound DAI </Heading.h3> <Heading.h4 textAlign={['center']} fontWeight={1} lineHeight={2} fontSize={[2,3]}> Current lending interest rate on Compound V2. </Heading.h4> <Heading.h2 fontFamily={'sansSerif'} textAlign={'center'} fontWeight={2} fontSize={[6,8]} mb={[4,0]}>{this.state.compoundRate}%</Heading.h2> </Box> </Box> <Box width={[1,4/10]} p={[4,5]} pb={0} backgroundColor={'blue'} color={'white'} boxShadow={1} borderBottom={'15px solid'} borderColor={'white'}> <Heading.h3 textAlign={['center']} fontFamily={'sansSerif'} fontSize={[4,5]} mb={[2,3]}> <Image src={'images/idle-mark.png'} className={styles.platformLogo} /> Idle DAI </Heading.h3> <Heading.h4 textAlign={['center']} fontWeight={1} lineHeight={2} fontSize={[2,3]}> We will always get the best rate, thanks to our users and the decentralized rebalance process. </Heading.h4> <Heading.h2 fontFamily={'sansSerif'} textAlign={'center'} fontWeight={2} fontSize={[8,10]} mb={[4,0]}>{this.state.maxRate}%</Heading.h2> <Box justifyContent={'center'} alignItems={'center'} textAlign={'center'} display={['none','flex']}> <Button onClick={e => this.startLending(e)} borderRadius={4} size={'large'} mainColor={'lightBlue'} contrastColor={'blue'} fontWeight={2} fontSize={[2,3]} px={[4,5]} mt={[2,4]} mb={[3,3]}>START EARNING</Button> </Box> <Box justifyContent={'center'} alignItems={'center'} textAlign={'center'} display={['flex','none']}> <Button onClick={e => this.startLending(e)} borderRadius={4} size={'medium'} mainColor={'lightBlue'} contrastColor={'blue'} fontWeight={2} fontSize={[2,3]} px={[4,5]} mt={[2,4]} mb={[3,3]}>START EARNING</Button> </Box> </Box> <Box width={[1,3/10]}> <Box p={[4,5]} pb={0} backgroundColor={'white'} color={'black'} boxShadow={1} borderBottom={'15px solid'} borderColor={'blue'}> <Heading.h3 textAlign={['center']} fontFamily={'sansSerif'} fontSize={[3,4]} mb={[2,3]} color={'blue'}> <Image src={'images/fulcrum-mark.png'} className={styles.platformLogo} /> Fulcrum DAI </Heading.h3> <Heading.h4 textAlign={['center']} fontWeight={1} lineHeight={2} fontSize={[2,3]}> Current lending interest rate on Fulcrum. </Heading.h4> <Heading.h2 fontFamily={'sansSerif'} textAlign={'center'} fontWeight={2} fontSize={[6,8]} mb={[4,0]}>{this.state.fulcrumRate}%</Heading.h2> </Box> </Box> </Flex> </Box> </Box> <Box id="faq" pb={[4,6]}> <Box maxWidth={'50em'} mx={'auto'} px={[3,5]}> <Heading.h2 fontFamily={'sansSerif'} fontSize={[5, 6]} textAlign={'center'} pt={[4,5]} pb={[2,3]} alignItems={'center'} my={0}> Stay up to date </Heading.h2> <Heading.h4 textAlign={['center']} fontWeight={1} lineHeight={2} fontSize={[2,3]} mb={[3,4]}> Sign up for the newsletter to get the latest Idle news </Heading.h4> <NewsletterForm /> </Box> </Box> <Box id="faq" pb={[4,6]} className={[styles.graySection]}> <Box maxWidth={['50em','70em']} mx={'auto'} px={[3,5]}> <Faq /> </Box> </Box> <Box backgroundColor={'darkBlue'} py={[2,3]} px={[2,3]}> <Flex flexDirection={['column','row']} alignItems={'center'} justifyContent={'space-between'}> <Flex flexDirection={['column']} mt={[2, 0]} alignItems={['center','baseline']} justifyContent={'flex-end'}> <Box ml={[0,3]} mb={[0,2]}> <Text color={'white'} textAlign={['center','left']}>Built on:</Text> </Box> <Flex flexDirection={['row']}> <Link href="https://www.ethereum.org/" target="_blank"> <Image src="images/ethereum.png" height={['1.3em', '2em']} mx={[1,3]} my={[2,0]} /> </Link> <Link href="https://app.compound.finance" target="_blank"> <Image src="images/compound-light.png" height={['1.3em', '2em']} mx={[1,3]} my={[2,0]} /> </Link> <Link href="https://fulcrum.trade" target="_blank"> <Image src="images/fulcrum.svg" height={['1.3em', '2em']} mx={[1,3]} my={[2,0]} /> </Link> </Flex> </Flex> <Flex flexDirection={['column']} mt={[2, 0]} alignItems={['center','flex-end']} justifyContent={'flex-end'}> <Box mr={[0,3]} mb={[0,2]}> <Text color={'white'} textAlign={['center','right']}>Explore:</Text> </Box> <Flex flexDirection={['row']}> <Link href="https://twitter.com/idlefinance" target="_blank"> <Image src="images/twitter-logo.png" height={'2em'} mx={[2,3]} my={[2,0]} /> </Link> <Link href="https://t.me/idlefinance" target="_blank"> <Image src="images/telegram-logo.png" height={'2em'} mx={[2,3]} my={[2,0]} /> </Link> <Link href="https://discord.gg/mpySAJp" target="_blank"> <Image src="images/discord-logo.png" height={'2em'} mx={[2,3]} my={[2,0]} /> </Link> <Link href="https://medium.com/@idlefinance" target="_blank"> <Image src="images/medium-logo.png" height={'2em'} mx={[2,3]} my={[2,0]} /> </Link> <Link href="https://github.com/bugduino/idle" target="_blank"> <Image src="images/github-logo.png" height={'2em'} mx={[2,3]} my={[2,0]} /> </Link> <Link href="https://etherscan.io/address/0xAcf651Aad1CBB0fd2c7973E2510d6F63b7e440c9#code" target="_blank"> <Image src="images/etherscan.png" height={'2em'} mx={[2,3]} my={[2,0]} /> </Link> </Flex> </Flex> </Flex> </Box> </Box> ); } } export default Landing; <file_sep>import React from "react"; import { Heading, Text, Modal, Box, Flex, QR, Button, PublicAddress } from "rimble-ui"; import ModalCard from './ModalCard'; import { useWeb3Context } from 'web3-react' import BigNumber from 'bignumber.js'; export default function (props) { const context = useWeb3Context(); const { account, accountBalance, accountBalanceDAI, isOpen, closeModal } = props; const BNify = s => new BigNumber(String(s)); const trimEth = eth => { return BNify(eth).toFixed(6); }; const setConnector = async connectorName => { if (localStorage) { localStorage.setItem('walletProvider', ''); } return await context.setConnector(connectorName); }; return ( <Modal isOpen={isOpen}> <ModalCard closeFunc={closeModal}> <ModalCard.Body> <Flex width={["auto", "40em"]} flexDirection={'column'} alignItems={'center'} justifyContent={'center'}> <Heading.h2 textAlign={'center'} mb={[2, 3]}> Account overview </Heading.h2> <Flex flexDirection={'column'} alignItems={'center'} justifyContent={'center'}> {account && <QR value={props.account} renderAs={'svg'} /> } <Box style={{'wordBreak': 'break-word'}}> <PublicAddress label="" address={props.account} /> </Box> </Flex> <Box> <Heading.h4 textAlign={'center'}>Balance</Heading.h4> <Text my={3} fontSize={3}> {trimEth(accountBalance)} ETH </Text> <Text my={3} fontSize={3}> {trimEth(accountBalanceDAI)} DAI </Text> </Box> </Flex> </ModalCard.Body> <ModalCard.Footer> {(context.active || (context.error && context.connectorName)) && ( <Button mt={[1, 2]} size={'medium'} px={'80px'} borderRadius={4} onClick={async () => await setConnector('Infura')}> {context.active ? "Log out wallet" : "Reset"} </Button> )} </ModalCard.Footer> </ModalCard> </Modal> ); } <file_sep>import React from "react"; import { Heading, Text, Icon, Modal, Flex, Box, Link, Button } from "rimble-ui"; import ModalCard from './ModalCard'; import TransactionFeeModal from "./TransactionFeeModal"; import Web3ConnectionButtons from "../../Web3ConnectionButtons/Web3ConnectionButtons"; class ConnectionModal extends React.Component { // TODO save pref in localstorage and do not show 'Before connecting' info every time state = { showTxFees: false, showConnectionButtons: false, newToEthereum: false }; toggleShowTxFees = e => { console.log("showTxFees", this.state.showTxFees); e.preventDefault(); this.setState({ showTxFees: !this.state.showTxFees }); }; toggleShowConnectionButtons = e => { e.preventDefault(); this.setState({ showConnectionButtons: !this.state.showConnectionButtons }); const showConnectionButtons = this.getShowConnectionButtons(); if (localStorage) { if (showConnectionButtons){ localStorage.removeItem('showConnectionButtons'); } else { localStorage.setItem('showConnectionButtons', true); } } }; resetModal = e => { if (localStorage) { localStorage.removeItem('showConnectionButtons'); } this.setState({ showConnectionButtons: false, newToEthereum: false }); }; getShowConnectionButtons = () => { return localStorage ? localStorage.getItem('showConnectionButtons') : this.state.showConnectionButtons; } toggleNewtoEthereum = e => { e.preventDefault(); this.setState({ newToEthereum: !this.state.newToEthereum }); }; renderModalContent = () => { const showConnectionButtons = this.getShowConnectionButtons(); const newToEthereum = this.state.newToEthereum; if (showConnectionButtons) { return ( <Box width={1}> <Heading fontSize={[4, 5]} mb={[3, 4]} textAlign='center'> Connect with: </Heading> <Web3ConnectionButtons size={'large'} /> </Box> ); } if (newToEthereum) { return ( <React.Fragment> <Box mt={4} mb={5}> <Heading fontSize={[4, 5]}>Let's create your first Ethereum wallet</Heading> <Text fontSize={[2, 3]} my={3}> Managing ethereum wallet could be intimidating, but we are making it seamless by integrating the Portis wallet provider. After clicking the button below you will create you first Ethereum wallet and you'll be ready to start your journey into Idle. </Text> </Box> <Flex alignItems={"center"}> <Web3ConnectionButtons size={'large'} onlyPortis={true} registerPage={true} /> </Flex> </React.Fragment> ); } return ( <React.Fragment> {/* Start primary content */} <Box mt={4} mb={5}> <Heading fontSize={[4, 5]}>Before you connect</Heading> <Text fontSize={[2, 3]} my={3}> Connecting lets you use Idle via your Ethereum account. </Text> </Box> <Flex flexDirection={['column', 'row']} justifyContent={"space-between"} my={[0, 4]} > <Box flex={'1 1'} width={1} mt={[3, 0]} mb={[4, 0]} mr={4}> <Flex justifyContent={"center"} mb={3}> <Icon name="Public" color="primary" size="4em" /> </Flex> <Heading fontSize={2}>The blockchain is public</Heading> <Text fontSize={1}> Your Ethereum account activity is public on the blockchain. Choose an account you don’t mind being linked with your activity here. </Text> </Box> <Box flex={'1 1'} width={1} mt={[3, 0]} mb={[4, 0]} mr={4}> <Flex justifyContent={"center"} mb={3}> <Icon name="AccountBalanceWallet" color="primary" size="4em" /> </Flex> <Heading fontSize={2}>Have some Ether for fees</Heading> <Text fontSize={1} mb={3}> You’ll need Ether to pay transaction fees. Buy Ether from exchanges like Coinbase or directly via enabled wallet such as Portis or Dapper. </Text> <Link title="Learn about Ethereum transaction fees" as={"a"} color={'primary'} hoverColor={'primary'} href="#" onClick={this.toggleShowTxFees} > What are transaction fees? </Link> </Box> <Box flex={'1 1'} width={1} mt={[3, 0]} mb={[4, 0]}> <Flex justifyContent={"center"} mb={3}> <Icon name="People" color="primary" size="4em" /> </Flex> <Heading fontSize={2}>Have the right account ready</Heading> <Text fontSize={1}> If you have multiple Ethereum accounts, check that the one you want to use is active in your browser. </Text> </Box> </Flex> {/* End Modal Content */} </React.Fragment> ); } renderFooter = () => { const showConnectionButtons = this.getShowConnectionButtons(); const newToEthereum = this.state.newToEthereum; return ( <ModalCard.Footer> { showConnectionButtons || newToEthereum ? ( <Link title="Read instructions" color={'primary'} hoverColor={'primary'} href="#" onClick={this.resetModal} > Read instructions </Link> ) : ( <Flex flexDirection={['column', 'row']} width={1} justifyContent={['space-around']}> <Button onClick={this.toggleShowConnectionButtons} borderRadius={4}> CONNECT </Button> <Button onClick={this.toggleNewtoEthereum} borderRadius={4}> I AM NEW TO ETHEREUM </Button> </Flex> ) } </ModalCard.Footer> ); } closeModal = () => { this.setState({ showTxFees: false, showConnectionButtons: false, newToEthereum: false }); this.props.closeModal(); } render() { return ( <Modal isOpen={this.props.isOpen}> <ModalCard closeFunc={this.closeModal}> {this.state.showTxFees === false ? ( <React.Fragment> <ModalCard.Body> {this.renderModalContent()} </ModalCard.Body> {this.renderFooter()} </React.Fragment> ) : ( <ModalCard.Body> <TransactionFeeModal /> <ModalCard.BackButton onClick={this.toggleShowTxFees} /> </ModalCard.Body> )} </ModalCard> </Modal> ); } } export default ConnectionModal; <file_sep>import React, { Component } from "react"; import Web3 from "web3"; // uses latest 1.x.x version import Web3Provider from 'web3-react'; import { Web3Consumer } from 'web3-react' import connectors from './connectors'; import theme from "../theme"; // import styles from './App.module.scss'; import { ThemeProvider, Box } from 'rimble-ui'; import RimbleWeb3 from "../utilities/RimbleWeb3"; import Header from "../utilities/components/Header"; import Landing from "../Landing/Landing"; import Web3Debugger from "../Web3Debugger/Web3Debugger"; class App extends Component { state = { genericError: null, width: window.innerWidth, route: "default", // or 'onboarding' selectedTab: '1' }; async selectTab(e, tabIndex) { // e.preventDefault(); this.setState(state => ({...state, selectedTab: tabIndex})); } componentWillMount() { window.addEventListener('resize', this.handleWindowSizeChange); } componentWillUnmount() { window.removeEventListener('resize', this.handleWindowSizeChange); } handleWindowSizeChange = () => { this.setState({ width: window.innerWidth }); }; // Optional parameters to pass into RimbleWeb3 config = { requiredConfirmations: 1, accountBalanceMinimum: 0, // in ETH for gas fees requiredNetwork: 1 // Mainnet // requiredNetwork: 3 // Ropsten }; showRoute(route) { this.setState({ route }); }; render() { const isMobile = this.state.width <= 768; return ( <ThemeProvider theme={theme}> <Web3Provider connectors={connectors} libraryName={'web3.js'} web3Api={Web3} > <Web3Consumer> {context => { return ( <RimbleWeb3 config={this.config} context={context}> <RimbleWeb3.Consumer> {({ needsPreflight, web3, account, contracts, accountBalance, accountBalanceDAI, accountBalanceLow, initAccount, initContract, rejectAccountConnect, userRejectedConnect, accountValidated, accountValidationPending, rejectValidation, userRejectedValidation, validateAccount, connectAndValidateAccount, modals, network, transaction }) => ( <Box> <Header account={account} isMobile={isMobile} accountBalance={accountBalance} accountBalanceDAI={accountBalanceDAI} accountBalanceLow={accountBalanceLow} initAccount={initAccount} rejectAccountConnect={rejectAccountConnect} userRejectedConnect={userRejectedConnect} accountValidated={accountValidated} accountValidationPending={accountValidationPending} rejectValidation={rejectValidation} userRejectedValidation={userRejectedValidation} validateAccount={validateAccount} connectAndValidateAccount={connectAndValidateAccount} handleMenuClick={this.selectTab.bind(this)} modals={modals} network={network} /> {this.state.route === "onboarding" ? ( <Web3Debugger web3={web3} account={account} accountBalance={accountBalance} accountBalanceDAI={accountBalanceDAI} accountBalanceLow={accountBalanceLow} initAccount={initAccount} rejectAccountConnect={rejectAccountConnect} userRejectedConnect={userRejectedConnect} accountValidated={accountValidated} accountValidationPending={accountValidationPending} rejectValidation={rejectValidation} userRejectedValidation={userRejectedValidation} validateAccount={validateAccount} connectAndValidateAccount={connectAndValidateAccount} modals={modals} network={network} transaction={transaction} /> ) : null} {this.state.route === "default" ? ( <Landing web3={web3} contracts={contracts} isMobile={isMobile} account={account} accountBalance={accountBalance} accountBalanceDAI={accountBalanceDAI} accountBalanceLow={accountBalanceLow} updateSelectedTab={this.selectTab.bind(this)} selectedTab={this.state.selectedTab} network={network} /> ) : null} </Box> )} </RimbleWeb3.Consumer> </RimbleWeb3> ); }} </Web3Consumer> </Web3Provider> </ThemeProvider> ); } } export default App; <file_sep>import React, { Component } from "react"; import { Heading, Box, Flex, Form, Button, Image, Link } from 'rimble-ui' import styles from './CryptoInput.module.scss'; class CryptoInput extends Component { render() { const convertedValue = !isNaN(this.props.trimEth(this.props.IdleDAIPrice)) && !!this.props.IdleDAIPrice ? '~'+this.props.BNify(this.props.defaultValue/this.props.IdleDAIPrice).toFixed(2)+' idleDAI' : ''; return ( <> <Flex maxWidth={['90%','40em']} borderRadius={'2rem'} border={'1px solid'} alignItems={'center'} borderColor={'#ccc'} p={0} mt={['0','1em']} mx={'auto'} > <Box width={[1/10]}> <Image src="images/btn-dai.svg" height={this.props.height} ml={['0.5em','1em']} /> </Box> <Box width={[6/10, 5/10]}> <Form.Input style={{ paddingLeft: '1em', paddingRight: '1em' }} placeholder={`Enter DAI Amount`} value={this.props.defaultValue} type="number" borderRadius='2rem' border='0' borderColor='transparent' boxShadow='none !important' min={0} height={this.props.height} step={0.01} fontSize={[2, 4]} width={'100%'} bg={'transparent'} color={this.props.color} className={[styles.mainInput]} onChange={this.props.handleChangeAmount} /> </Box> <Box display={['none','block']} width={2/10}> <Form.Input style={{ paddingLeft: '0', paddingRight: '10px', textAlign: 'right' }} readOnly={'readOnly'} placeholder={''} value={convertedValue} type="text" border='0' borderColor='transparent' boxShadow='none !important' min={0} height={this.props.height} step={0.01} fontSize={[1, 1]} width={'100%'} bg={'transparent'} color={'grey'} className={[styles.mainInput]} /> </Box> <Box width={[3/10, 2/10]}> <Button onClick={this.props.handleClick} className={[styles.button]} size={this.props.isMobile ? 'medium' : 'large'} mainColor={'blue'} fontWeight={2} fontSize={[2,3]} px={this.props.isMobile ? [2,3] : [4,5]} my={0} width={1} disabled={this.props.disableLendButton ? 'disabled' : false}>LEND</Button> </Box> </Flex> <Flex maxWidth={['90%','40em']} justifyContent={'space-between'} mt={[2, 2]} mb={[2,3]} mx={'auto'}> <Box pl={'5%'}> <Heading.h5 color={'darkGray'} fontWeight={1} fontSize={1}> {!this.props.isMobile ? !isNaN(this.props.trimEth(this.props.IdleDAIPrice)) && !!this.props.IdleDAIPrice && `1 idleDAI = ${this.props.trimEth(this.props.IdleDAIPrice)} DAI` : convertedValue } </Heading.h5> </Box> { this.props.account && !isNaN(this.props.trimEth(this.props.accountBalanceDAI)) && <Box pr={['5%','20%']}> <Heading.h5 color={'darkGray'} fontWeight={1} fontSize={1}> <Link color={'darkGray'} hoverColor={'darkGray'} fontWeight={1} fontSize={1} lineHeight={'1.25'} onClick={ e => this.props.useEntireBalance(this.props.accountBalanceDAI) }> Balance: {!this.props.isMobile ? parseFloat(this.props.accountBalanceDAI).toFixed(6) : parseFloat(this.props.accountBalanceDAI).toFixed(2) } DAI</Link> </Heading.h5> </Box> } </Flex> <Flex justifyContent={'center'}> <Heading.h5 mt={[1, 2]} color={'darkGray'} fontWeight={1} fontSize={1} textAlign={'center'}> *This is beta software. Use at your own risk. </Heading.h5> </Flex> </> ); } } export default CryptoInput; <file_sep>import React, { Component } from 'react'; import { Link } from 'rimble-ui' import styles from './MenuLink.module.scss'; class MenuLink extends Component { render() { return ( <Link onClick={this.props.handleClick} className={[styles.link]} href={this.props.linkSrc} color={'white'} hoverColor={'white'} activeColor={'white'} fontSize={[3,4]} pr={[3,4]} fontWeight={2}>{this.props.linkText}</Link> ); } } export default MenuLink; <file_sep>const { expectEvent, singletons, constants, BN, expectRevert } = require('openzeppelin-test-helpers'); const { ZERO_ADDRESS } = constants; const IdleDAI = artifacts.require('IdleDAI'); const TestableIdleDAI = artifacts.require('TestableIdleDAI'); const IdleHelp = artifacts.require('IdleHelp'); const cDAIMock = artifacts.require('cDAIMock'); const iDAIMock = artifacts.require('iDAIMock'); const DAIMock = artifacts.require('DAIMock'); const BNify = n => new BN(String(n)); contract('IdleHelp', function ([_, registryFunder, creator, nonOwner, someone]) { beforeEach(async function () { this.DAIMock = await DAIMock.new({from: creator}); this.cDAIMock = await cDAIMock.new(this.DAIMock.address, someone, {from: creator}); this.iDAIMock = await iDAIMock.new(this.DAIMock.address, someone, {from: creator}); this.one = new BN('1000000000000000000'); this.ETHAddr = '0x0000000000000000000000000000000000000000'; this.blocksInAYear = new BN('2102400'); this.minRateDifference = new BN('500000000000000000'); this.IdleHelp = await IdleHelp.new(); await IdleDAI.link(IdleHelp, this.IdleHelp.address); }); it('can getAPRs', async function () { const res = await this.IdleHelp.getAPRs( this.cDAIMock.address, this.iDAIMock.address, this.blocksInAYear ); const rate = new BN('32847953230'); res[0].should.be.bignumber.equal(rate.mul(this.blocksInAYear).mul(new BN('100'))); res[1].should.be.bignumber.equal(new BN('2927621524103328230')); }); it('getBestRateToken returns cToken apr if has the highest apr', async function () { const res = await this.IdleHelp.getBestRateToken( this.cDAIMock.address, this.iDAIMock.address, this.blocksInAYear ); const rate = new BN('32847953230'); res[0].should.be.equal(this.cDAIMock.address); res[1].should.be.bignumber.equal(rate.mul(this.blocksInAYear).mul(new BN('100'))); res[2].should.be.bignumber.equal(new BN('2927621524103328230')); }); it('getBestRateToken returns iToken if has the highest apr', async function () { await this.iDAIMock.setSupplyInterestRateForTest(); const res = await this.IdleHelp.getBestRateToken( this.cDAIMock.address, this.iDAIMock.address, this.blocksInAYear ); const rate = new BN('32847953230'); res[0].should.be.equal(this.iDAIMock.address); res[1].should.be.bignumber.equal((new BN('2927621524103328230')).mul(new BN('4'))); res[2].should.be.bignumber.equal(rate.mul(this.blocksInAYear).mul(new BN('100'))); }); it('rebalanceCheck should not rebalance if current bestToken is still the best token', async function () { const res = await this.IdleHelp.rebalanceCheck( this.cDAIMock.address, this.iDAIMock.address, this.cDAIMock.address, this.blocksInAYear, this.minRateDifference ); res[0].should.be.equal(false); res[1].should.be.equal(this.cDAIMock.address); }); it('rebalanceCheck should rebalance if current bestToken is not set', async function () { const res = await this.IdleHelp.rebalanceCheck( this.cDAIMock.address, this.iDAIMock.address, this.ETHAddr, // address(0) this.blocksInAYear, this.minRateDifference ); res[0].should.be.equal(true); res[1].should.be.equal(this.cDAIMock.address); }); it('rebalanceCheck should rebalance if current bestToken is not the best token and rate difference is > minRateDifference', async function () { await this.iDAIMock.setSupplyInterestRateForTest(); const res = await this.IdleHelp.rebalanceCheck( this.cDAIMock.address, this.iDAIMock.address, this.cDAIMock.address, this.blocksInAYear, this.minRateDifference ); res[0].should.be.equal(true); res[1].should.be.equal(this.iDAIMock.address); }); it('rebalanceCheck should not rebalance if rate difference is < minRateDifference', async function () { await this.iDAIMock.setSupplyInterestRateForTest(); const res = await this.IdleHelp.rebalanceCheck( this.cDAIMock.address, this.iDAIMock.address, this.cDAIMock.address, this.blocksInAYear, this.minRateDifference.mul(new BN('30')) ); res[0].should.be.equal(false); res[1].should.be.equal(this.iDAIMock.address); }); it('getPriceInToken returns token price when bestToken is cToken', async function () { const oneCToken = new BN('100000000'); const totalSupply = (new BN('20')).mul(this.one); const poolSupply = new BN('1000').mul(oneCToken); const res = await this.IdleHelp.getPriceInToken( this.cDAIMock.address, this.iDAIMock.address, this.cDAIMock.address, totalSupply, poolSupply ); // const exchangeRate = await this.cDAIMock.exchangeRateStored(); // const navPool = exchangeRate.mul(poolSupply).div(this.one); // const tokenPrice = navPool.div(totalSupply.div(this.one)); res.should.be.bignumber.equal(this.one); // => == this.one }); it('getPriceInToken returns token price when bestToken is cToken and rates changed', async function () { // first tokens minted when 1 cDAI was 0.02 DAI const oneCToken = new BN('1000<PASSWORD>0'); let totalSupply = (new BN('20')).mul(this.one); let poolSupply = new BN('1000').mul(oneCToken); // now we set 1 cDAI to 0.022 DAI await this.cDAIMock.setExchangeRateStoredForTest(); const res = await this.IdleHelp.getPriceInToken( this.cDAIMock.address, this.iDAIMock.address, this.cDAIMock.address, totalSupply, poolSupply ); // const exchangeRate = await this.cDAIMock.exchangeRateStored(); // console.log(exchangeRate.toString()) // const navPool = exchangeRate.mul(poolSupply).div(this.one); // console.log(navPool.toString()) // const tokenPrice = navPool.div(totalSupply.div(this.one)); // console.log(tokenPrice.toString()); res.should.be.bignumber.equal(new BN('1100000000000000000')); // we simulate a buy of 11 DAI so 11/1.1 = 10 IDleDAI totalSupply = (new BN('30')).mul(this.one); // 11 DAI = 11/ 0.022 = 500 in cDAI poolSupply = new BN('1500').mul(oneCToken); // now we set 1 cDAI to 0.03 DAI await this.cDAIMock.setNewExchangeRateStoredForTest(); // so nav = 1500 * 0.03 = 45 DAI // so res should be 45/30 = 1.5 const res2 = await this.IdleHelp.getPriceInToken( this.cDAIMock.address, this.iDAIMock.address, this.cDAIMock.address, totalSupply, poolSupply ); res2.should.be.bignumber.equal(new BN('1500000000000000000')); // we now simulate someone removing 20 IDLEDAI totalSupply = (new BN('10')).mul(this.one); poolSupply = new BN('500').mul(oneCToken); // nav = 500 * 0.03 = 15 DAI // so price should be 15/10 = 1.5 const res3 = await this.IdleHelp.getPriceInToken( this.cDAIMock.address, this.iDAIMock.address, this.cDAIMock.address, totalSupply, poolSupply ); res3.should.be.bignumber.equal(new BN('1500000000000000000')); }); it('getPriceInToken returns token price when bestToken is iToken', async function () { const totalSupply = new BN('1000'); const poolSupply = new BN('1000'); const res = await this.IdleHelp.getPriceInToken( this.cDAIMock.address, this.iDAIMock.address, this.iDAIMock.address, totalSupply, poolSupply ); const price = await this.iDAIMock.tokenPrice(); const navPool = price.mul(poolSupply); const tokenPrice = navPool.div(totalSupply); res.should.be.bignumber.equal(tokenPrice); }); }); <file_sep>import React from "react"; import { Flex, Icon, Box, Text, QR } from "rimble-ui"; import ShortHash from "./ShortHash"; import BigNumber from 'bignumber.js'; class AccountOverview extends React.Component { BNify = s => new BigNumber(String(s)); trimEth = (eth, to) => { return this.BNify(eth).toFixed(to); }; render() { const roundedBalance = this.trimEth(this.props.accountBalance, 4); const roundedDAIBalance = this.trimEth(this.props.accountBalanceDAI, 2); return ( <Flex alignItems={"flex-start"} style={{cursor: 'pointer'}} mx={3} my={2} onClick={this.props.toggleModal}> {!this.props.isMobile && <Box> {this.props.hasQRCode && <Flex mr={3} p={1}> <QR value={this.props.account} size={50} renderAs={'svg'} /> </Flex> } <Box> <Text fontSize={1} color={'white'}> User: &nbsp; <ShortHash fontSize={1} color={'white'} hash={this.props.account} /> </Text> <Text fontSize={1} color={this.props.accountBalanceLow ? 'white' : 'white'} > {isNaN(roundedBalance) ? '0' : roundedBalance} ETH {roundedDAIBalance && !isNaN(roundedDAIBalance) ? `, ${roundedDAIBalance} DAI` : ', 0 DAI'} </Text> </Box> </Box> } <Icon name='AccountCircle' size={'45'} ml={2} mt={[0, 0]} color='white' /> </Flex> ); } } export default AccountOverview; <file_sep>import React from "react"; import { Heading, Text, Modal, Box } from "rimble-ui"; import ModalCard from './ModalCard'; import NewsletterForm from '../../NewsletterForm/NewsletterForm'; export default function MaxCapModal(props) { const { isOpen, closeModal, maxCap, currSupply } = props; const humanCurrSupply = +(currSupply.div(1e18)).toFixed(2); const maxMintable = +(maxCap.minus(currSupply.div(1e18))).toFixed(2); return ( <Modal isOpen={isOpen}> <ModalCard closeFunc={closeModal}> <ModalCard.Body> <Box mt={3} mb={3}> <Heading color={'black'} fontSize={[4, 5]}>Max deposit reached</Heading> <Text fontSize={[2, 3]} my={3}> {currSupply.div(1e18).gte(maxCap) ? `The max amount of ${maxCap.toString()} IdleDAI have currently been reached, so new deposits are now paused.` : `The current supply of IdleDAI is ${humanCurrSupply} (MAX CAP: ${maxCap.toString()} IdleDAI) so the max amount mintable is ${maxMintable}, try with a lower amount.` } </Text> <Text fontSize={[2, 3]} my={3}> This is still a Beta version, we are currently working on a new and improved rebalance process which would scale better for large amount of funds. You can come back later to check if others have redeemed their position or subscribe to our newsletter to be notified when the new version is ready. </Text> <NewsletterForm /> </Box> </ModalCard.Body> </ModalCard> </Modal> ); } <file_sep>'use strict'; require('babel-register'); require('babel-polyfill'); require('chai/register-should'); const path = require("path"); require('dotenv').config(); const HDWalletProvider = require("truffle-hdwallet-provider"); const INFURA_KEY = process.env["INFURA_KEY"]; module.exports = { contracts_build_directory: path.join(__dirname, "client/src/contracts"), compilers: { solc: { version: "0.5.2", optimizer: { enabled: true, runs: 1 } } }, networks: { local: { host: '127.0.0.1', port: 8545, network_id: '*' }, ropsten: { provider() { return new HDWalletProvider(process.env["TESTNET_MNEMONIC"], `https://ropsten.infura.io/v3/${INFURA_KEY}`) }, gasPrice: 7000000000, // 7 gwei network_id: 3 }, rinkeby: { provider() { return new HDWalletProvider(process.env["TESTNET_MNEMONIC"], `https://rinkeby.infura.io/v3/${INFURA_KEY}`) }, gasPrice: 7000000000, // 7 gwei network_id: 4 }, live: { provider() { return new HDWalletProvider(process.env["MAINNET_MNEMONIC"], `https://mainnet.infura.io/v3/${INFURA_KEY}`); }, gasPrice: 3000000000, // 3 gwei network_id: 1 } }, mocha: { useColors: true, // reporter: 'eth-gas-reporter', // reporterOptions : { // currency: 'EUR', // gasPrice: 5, // onlyCalledMethods: false // } } }; <file_sep>const TransactionToastMessages = { initialized: { message: "{action} request initialized", secondaryMessage: "Confirm with your wallet provider", actionHref: "", actionText: "", variant: "default", icon: "InfoOutline" }, started: { message: "{action} request submitted", secondaryMessage: "Confirm with your wallet provider", actionHref: "", actionText: "", variant: "default", icon: "InfoOutline" }, pending: { message: "Processing {action} request...", secondaryMessage: "This may take a few minutes", actionHref: "", actionText: "", variant: "processing", icon: "InfoOutline" }, confirmed: { message: "First block confirmed", secondaryMessage: "Your {action} request is in progress", actionHref: "", actionText: "", variant: "processing", icon: 'CheckCircle' }, success: { message: "{action} request completed", variant: "success", icon: 'CheckCircle' }, error: { message: "{action} request failed", secondaryMessage: "Could not complete transaction.", actionHref: "", actionText: "", variant: "failure", icon: "Block" } }; export default TransactionToastMessages; <file_sep>import React, { Component } from 'react'; // import styles from './LandingForm.module.scss'; import { Box } from "rimble-ui"; import RimbleWeb3 from "../utilities/RimbleWeb3"; import TransactionToastUtil from "../utilities/TransactionToastUtil"; import SmartContractControls from "../SmartContractControls/SmartContractControls"; class LandingForm extends Component { render() { return ( <RimbleWeb3.Consumer> {({ contracts, account, transactions, initContract, initAccount, initWeb3, getAccountBalance, contractMethodSendWrapper, web3, network }) => ( <Box maxWidth={["50em", "70em"]} mx={"auto"}> <SmartContractControls web3={web3} accountBalanceDAI={this.props.accountBalanceDAI} isMobile={this.props.isMobile} updateSelectedTab={this.props.updateSelectedTab} selectedTab={this.props.selectedTab} network={network} contracts={contracts} account={account} transactions={transactions} initContract={initContract} initWeb3={initWeb3} getAccountBalance={getAccountBalance} contractMethodSendWrapper={contractMethodSendWrapper} /> <TransactionToastUtil transactions={transactions} /> </Box> )} </RimbleWeb3.Consumer> ); } } export default LandingForm;
80a4d2686a0d8bb534be24bd54bcfe1facbddf32
[ "JavaScript", "Markdown", "Shell" ]
22
Shell
cleancoindev/idle
5ebd2ba5c5cb681dacd3f998b3fa46798cf7a668
f3d25162bef172f9b8944d877fefb5bd28a389df
refs/heads/master
<repo_name>mzgubic/learn-GBR<file_sep>/gbr.py import numpy as np import pandas as pd import scipy.optimize as spo import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import GradientBoostingRegressor from sklearn.datasets.samples_generator import make_blobs from sklearn.model_selection import train_test_split class LossFunction: def __init__(self): pass class MeanSquareLoss(LossFunction): def __call__(self, y, y_pred): return 0.5 * np.mean((y - y_pred)**2) def negative_gradient(self, y, y_pred): return y - y_pred class GBR: def __init__(self, loss, learning_rate=0.1, n_estimators=2, criterion='friedman_mse', random_state='42', max_depth=3): if loss == 'ls': self.loss = MeanSquareLoss() self.n_estimators = n_estimators self.random_state = random_state self.learning_rate = learning_rate self.max_depth = max_depth self.estimators = [] # estimators self.gammas = [] # and their weights self.criterion = criterion def fit(self, X, y): # fit the initial tree #print('Fitting 1 st estimator in the sequence') self.estimators.append(DecisionTreeRegressor(criterion=self.criterion, random_state=self.random_state, max_depth=self.max_depth)) self.gammas.append(1.0) self.estimators[0].fit(X, y) pred_y_vals = self.estimators[0].predict(X) # fit the rest of them for i in range(2, self.n_estimators): #print() #print('Fitting', i, 'th estimator in the sequence') tree_i = DecisionTreeRegressor(criterion=self.criterion, random_state=self.random_state, max_depth=self.max_depth) # fit the tree y_prev_pred = self.predict(X, n=i-1) y_i = self.loss.negative_gradient(y, y_prev_pred) tree_i.fit(X, y_i) # fit the normalisation factor y_pred_i = tree_i.predict(X) def loss(gamma): return self.loss(y, y_prev_pred + gamma*y_pred_i) best_gamma = spo.minimize(loss, 1.0).x[0] # append the fitted values (estimators and gamma factors) self.estimators.append(tree_i) self.gammas.append(best_gamma*self.learning_rate) def predict(self, X, n=None): # predict on all if it is not specified if n==None: n = len(self.estimators) #print(' Called to predict {n}.'.format(n=n)) # sum predictions over all classifiers up to n predictions = np.zeros(shape=X.shape[0]) for i, est in enumerate(self.estimators): if i == n: break #print(' Predicting estimator {i}/{n}.'.format(i=i+1, n=n)) preds = est.predict(X) predictions += self.gammas[i] * preds #print(' Current predictions', predictions[:5]) return predictions def plot_decision_surface(clf, X, y, plot_step = 0.05, cmap='coolwarm', figsize=(12,8)): """Plot the prediction of clf on X and y, visualize training points""" print("##########################") print("Plotting decision boundary") vmin = np.min(y) vmax = np.max(y) plt.figure(figsize=figsize) x0_grid, x1_grid = np.meshgrid(np.arange(X[:, 0].min() - 1, X[:, 0].max() + 1, plot_step), np.arange(X[:, 1].min() - 1, X[:, 1].max() + 1, plot_step)) y_pred_grid = clf.predict(np.stack([x0_grid.ravel(), x1_grid.ravel()],axis=1)).reshape(x1_grid.shape) plt.contourf(x0_grid, x1_grid, y_pred_grid, cmap=cmap, vmin=vmin, vmax=vmax) y_pred = clf.predict(X) plt.scatter(*X.T, c=y, cmap=cmap, marker='x', vmin=vmin, vmax=vmax) plt.colorbar() plt.show() def main(): # create synthetic data random_state = 42 np.random.seed(random_state) N = 1000 N_groups = 3 X, y = make_blobs(n_samples=N, centers=N_groups, n_features=2, center_box=(-5, 5), random_state=random_state) y = y + np.random.normal(0, 0.1, y.shape[0]) X_train, X_test, y_train, y_test = train_test_split(X, y) # model parameters max_depth = 3 n_estimators = 100 criterion='friedman_mse' learning_rate = 0.1 # choose the model kwargs = {'loss':'ls', 'random_state':random_state, 'n_estimators':n_estimators, 'max_depth':max_depth, 'criterion':criterion, 'learning_rate':learning_rate} home_cooked_gbr = GBR(**kwargs) sklearn_gbr = GradientBoostingRegressor(**kwargs) # train the models home_cooked_gbr.fit(X_train, y_train) sklearn_gbr.fit(X_train, y_train) # visualise the data plot_decision_surface(home_cooked_gbr, X_train, y_train) plot_decision_surface(sklearn_gbr, X_train, y_train) # see how the model does on the test set home_pred_y = home_cooked_gbr.predict(X_test) sklearn_pred_y = sklearn_gbr.predict(X_test) print('Test loss for home cooked:', home_cooked_gbr.loss(y_test, home_pred_y)) print('Test loss for sklearn :', home_cooked_gbr.loss(y_test, sklearn_pred_y)) if __name__ == '__main__': main()
09425f031d8fb2501338716843bb6211860b9466
[ "Python" ]
1
Python
mzgubic/learn-GBR
2aef45eaab97729ffd570b54755c47a65d26300e
c4f79f25a58635569c3defa62ad164bf3e7e1d53
refs/heads/master
<file_sep>#100DaysofCode Day 6 apple_stock <- c(109.49, 109.90, 109.11, 109.95, 111.03, 112.12, 113.95, 113.30, 115.19, 115.19, 115.82, 115.97, 116.64, 116.95, 117.06, 116.29, 116.52, 117.26, 116.76, 116.73, 115.82) plot(apple_stock, type = "p") plot(apple_stock, type = "l") title(main = "Apple Stock Prices", col.main = "purple") #Vector Math dan <- c(100, 200, 150) rob <- c(50, 75, 100) sum(dan + rob) # Weights and returns micr_ret <- 7 sony_ret <- 9 micr_weight <- .2 sony_weight <- .8 # Portfolio return portf_ret <- (micr_ret * micr_weight) + (sony_ret * sony_weight) portf_ret # Weights, returns, and company names ret <- c(7, 9) weight <- c(.2, .8) companies <- c("Microsoft", "Sony") # Assign company names to your vectors names(ret) <- companies names(weight) <- companies # Multiply the returns and weights together ret_X_weight <- ret * weight # Print ret_X_weight ret_X_weight # Sum to get the total portfolio return portf_ret <- sum(ret_X_weight) # Print portf_ret portf_ret # Vector Subsetting twelve_months <- c(5, 2, 3, 7, 8, 3, 5, 9, 1, 4, 6, 3) names(twelve_months) <- month.name twelve_months[1] twelve_months[3:7] twelve_months [c(1, 2, 3)] twelve_months [c("January", "May", "June")] twelve_months[-1] <file_sep># -*- coding: utf-8 -*- """ Created on Sat May 26 13:10:38 2018 @author: D """ # prize is number you're looking for prize = 5 # make a guess guess = input("Pick a number between 1 and 10: \n") guess = int(guess) while prize != guess: if guess > prize: print("Your guess is too high") guess = input("Pick a number between 1 and 10: \n") guess = int(guess) elif guess < prize: print("Your guess is too low") guess = input("Pick a number between 1 and 10: \n") guess = int(guess) print("You Picked Correctly! Congratulations!")<file_sep># -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ a = 12345.23567 print('%.0f'%a) print ("Change since yesterday: %+.3f" % 1.5) print("Todays temperature will be: %.3f" % 7.25) data = ("John", "Doe", 53.44) format_string = "Hello" mystring = "hello" myfloat = 10.0 myint = 20 print("String: %s" % mystring) print("Float: %.1f" % myfloat) print("Integer: %d" % myint) print(data [0]) print(format_string, data[0], data[1], ". Your daily balance is:", data[2]) print(format_string, "%s" % data[0]) numbers = [] #creates an empty list strings = [] names = ["John", "Eric", "Jessica"] #creates a list with three things in it numbers.append(1) #adds numbers to the numbers list numbers.append(2) numbers.append(3) strings.append("hello") #adds words to the strings list strings.append("world") second_name = names[1] #stores the second item in names list to the variable print(numbers) print(strings) print("The second name on the names list is %s" % second_name) <file_sep># OneHundredDaysOfCode Snipets, files and projects from my #100DaysOfCode journey <file_sep># -*- coding: utf-8 -*- """ Created on Mon May 28 11:41:37 2018 @author: D """ # prints the word backwards fruit = "banana" length_fruit = len(fruit) index = length_fruit count = 0 # takes each letter of the word and prints on a separate line in reverse order while count < length_fruit: letter = fruit[index -1] print (letter) index = index - 1 count = count +1 # defines the function def fun_with_fruit(fruit, a_letter): word = fruit count = 0 print("The name of the fruit is: ", fruit, "and the letter is: ", a_letter) for letter in word: if letter == a_letter: count = count + 1 # checks for grammar if count == 1: print("The total number of", a_letter,"'s in", fruit, "is:", count) else: print("The total number of", a_letter,"'s in", fruit, "are:", count) # calls the function fun_with_fruit("banana", 'n') fun_with_fruit("strawberry", 'r') fun_with_fruit("kiwi", 'k') <file_sep># -*- coding: utf-8 -*- # Spyder Editor tenths = input("Please enter a number between 0 and 1: ") score = float(tenths) while score > 1: print("That is not a valid response!") tenths = input("Please enter a number between 0 and 1: ") score = float(tenths) if score >= 0.9: print("You made an A!") elif score >=0.8: print("You made a B") elif score >= 0.7: print("You made a C") elif score >= 0.6: print("You made a D :-P") elif score < 0.6: print("You failed! You got an F!")
136568843166807462c4cbeefb428c56d54a1d9a
[ "Markdown", "Python", "R" ]
6
R
ds-anguistech/OneHundredDaysOfCode
6d01f4860448c52e7ba68d2cf4cf08ded4254ab6
b6225f867c290f64d9c0f515274cdc67bed96b61
refs/heads/master
<repo_name>cocoZero/CodePush<file_sep>/README.md # CodePush cordova-hot-code-push test <file_sep>/www/js/directives.js angular.module('starter.echart', []) .directive('echart', function ($rootScope,BranchDataProvider) { return { restrict: 'EA', template: '<div ></div>', replace: true, scope: { data: "=", call: "&" //调用外部实现函数 }, link: function (scope, element, attrs) { console.log('3242424'); var dom = element[0], ndParent = element.parent()[0], parentWidth, parentHeight, width, height, chart; var canResize = false; function setOptions(params) { console.log('3223'); if (scope.data) { getSize(); if (chart) { chart.clear(); }else { chart = echarts.init(dom); canResize = true; } var options = BranchDataProvider.branchData(); chart.setOption(options); } } setOptions(''); var watchDate=scope.$watch(function () {return $rootScope.parentData}, function (value) { console.log("link内部----我接收到了改变"); }); var watchData=scope.$watch(function(){return scope.data},function(newVal,oldVal){ if(newVal!=oldVal){ if(scope.data && scope.data.reportIndex){ getReportIndex(); getDate.get(defaultParams,$rootScope.selectedDateFull,attrs); setOptions(defaultParams); }else { setOptions(scope.data); } } }); function getSize() { ndParent = element.parent()[0]; chartWidth = dom.clientWidth; chartHeight = dom.clientHeight; dom.style.width = 0; dom.style.height = 0; parentWidth = ndParent.clientWidth; parentHeight = ndParent.clientHeight; if (parentWidth > 1024) { parentWidth = null; } currentWidth = parseInt(attrs.width) || parentWidth || chartWidth || 200; currentHeight = parseInt(attrs.height) || parentHeight || chartHeight || 200; dom.style.width = currentWidth + 'px'; dom.style.height = currentHeight + 'px'; if (currentWidth == chartWidth && currentHeight == chartHeight || !canResize) { return false; } return true; } scope.$on('$destroy',function () { watchData(); }); } } }) .directive('helloWorld', function() { return { restrict: 'E', template: '<div>Hi 我是林炳文~~~</div>', replace: true }; })
58879285b7dc4b1545a8d2d1145924b37780e949
[ "Markdown", "JavaScript" ]
2
Markdown
cocoZero/CodePush
6e953da5e025c2644a986ac4cbf8482ed87f4dfc
fada0d65e473e0469742a47c3ed4edc748aeea3e
refs/heads/master
<file_sep># GuessingGame Elliot's Guessing Game <file_sep>// function() { // declare variables function constructor(correctAnswer, loopCount, nameGuess){ this.correctAnswer = correctAnswer; this.loopCount = loopCount; this.nameGuess = nameGuess; } // test user input var ElliotSimpson = new constructor("thomas", 1, prompt("Guess Elliot's middle name if you dare!")); // var TristanConant = new constructor("maurice", 1, prompt("Guess Tristan's middle name if you dare!")); "Cool runnings: Yo, you dead mon?" // <NAME> "he's the tank engine!" // <NAME> "it's French" while ElliotSimpson.nameGuess != ElliotSimpson.correctAnswer); { ElliotSimpson.nameGuess = prompt("Hint: my initials are E.T. You have incorretly guessed " + ElliotSimpson.loopCount + " times!"); ElliotSimpson.loopCount++; } alert("Congratulations! You can now call me an extra terrestrial!"); //} () console.log = ()
e11dd98a536734116b282ff51aebe81a448e81d3
[ "Markdown", "JavaScript" ]
2
Markdown
IAmTheElliot/GuessingGame
f8bb308fda6785b7468fd1fdcc4627338785f141
12f221488c1afcfee415f371edf61bd2acd40fdf
refs/heads/master
<repo_name>melfuechec/expensify-budget-app<file_sep>/readme.md expenses tracking app made with react, redux, express, firebase, heroku, webpack, react router, <file_sep>/src/components/ExpensesDashboard.js import React from 'react'; import ExpenesList from "./ExpenseList"; import ExpenesListFilters from "./ExpenseListFilters"; const ExpenseDashboardPage = () => { return ( <div> <ExpenesListFilters /> <ExpenesList /> </div> ) } export default ExpenseDashboardPage
9a053a2a04f2f17b011a2df2890f8ca2d831cf54
[ "Markdown", "JavaScript" ]
2
Markdown
melfuechec/expensify-budget-app
f3f44c416c987f50bdb6ccc777b3785aabdb04d2
842677f30e6c71eed4588605243204ddf1904b9d
refs/heads/master
<repo_name>anthrod/tfpong<file_sep>/dqn_pong.py # -*- coding: utf-8 -*- import gym import cv2 import wrappers import tf_dqn import random import tensorflow as tf from tensorflow.keras import datasets, layers, models import argparse import time import numpy as np from numpy import matlib import collections import sys DEFAULT_ENV_NAME = "PongNoFrameskip-v4" MEAN_REWARD_BOUND = 19.5 GAMMA = 0.99 BATCH_SIZE = 32 REPLAY_SIZE = 10000 LEARNING_RATE = 1e-4 SYNC_TARGET_FRAMES = 1000 REPLAY_START_SIZE = 10000 EPSILON_DECAY_LAST_FRAME = 10**5 EPSILON_START = 1.0 EPSILON_FINAL = 0.02 Experience = collections.namedtuple('Experience', field_names=['state', 'action', 'reward', 'done', 'new_state']) class ExperienceBuffer: def __init__(self, capacity): self.buffer = collections.deque(maxlen=capacity) def __len__(self): return len(self.buffer) def append(self, experience): self.buffer.append(experience) def sample(self, batch_size): indices = np.random.choice(len(self.buffer), batch_size, replace=False) states, actions, rewards, dones, next_states = zip(*[self.buffer[idx] for idx in indices]) return np.array(states), np.array(actions), np.array(rewards, dtype=np.float32), \ np.array(dones, dtype=np.uint8), np.array(next_states) class Agent: def __init__(self, env, exp_buffer): self.env = env self.exp_buffer = exp_buffer self._reset() def _reset(self): self.state = env.reset() self.total_reward = 0.0 def play_step(self, net, epsilon=0.0): done_reward = None if np.random.random() < epsilon: action = env.action_space.sample() else: state_a = np.array([self.state], copy=False) q_vals_v = net.model(state_a) action = int(tf.math.argmax(q_vals_v,1)[0]) # do step in the environment new_state, reward, is_done, _ = self.env.step(action) self.total_reward += reward exp = Experience(self.state, action, reward, is_done, new_state) self.exp_buffer.append(exp) self.state = new_state if is_done: done_reward = self.total_reward self._reset() return done_reward def get_loss(batch, tgt_net, net): states, actions, rewards, dones, next_states = batch not_dones = -1.0*np.asarray(dones) + 1.0 rewards_v = tf.Variable(np.asarray(rewards), dtype=tf.float32) not_dones_v = tf.Variable(np.asarray(not_dones), dtype=tf.float32) gammas_v = tf.Variable( GAMMA*np.ones(not_dones.shape), dtype=tf.float32 ) gammas_v = tf.math.multiply(not_dones_v, gammas_v) next_state_input = np.asarray(next_states) next_state_values = tgt_net.model(next_state_input) next_state_values = tf.math.reduce_max(next_state_values, axis=1) next_state_values = tf.math.multiply(next_state_values, gammas_v) state_action_expected_values = tf.math.add(rewards_v, next_state_values) state_action_expected_values = tf.stop_gradient(state_action_expected_values) action_indices = np.transpose(np.concatenate((np.arange(BATCH_SIZE), actions)).reshape(2,BATCH_SIZE)) batch_states = np.asarray(states) state_action_values = net.model(batch_states) state_action_taken_values = tf.gather_nd(state_action_values, action_indices) loss = tf.keras.losses.mean_squared_error(state_action_expected_values, state_action_taken_values) return loss if __name__ == "__main__": print(str(tf.config.experimental.list_physical_devices('GPU'))) env = wrappers.make_env('PongNoFrameskip-v4') net = tf_dqn.DQN((4,84,84), env.action_space.n) tgt_net = tf_dqn.DQN((4,84,84), env.action_space.n) #writer = SummaryWriter(comment="-" + args.env) buffer = ExperienceBuffer(REPLAY_SIZE) agent = Agent(env, buffer) epsilon = EPSILON_START total_rewards = [] frame_idx = 0 ts_frame = 0 ts = time.time() best_mean_reward = None #cv2.namedWindow("State", cv2.WINDOW_NORMAL) #cv2.resizeWindow("State",600,600) #cv2.imshow("State", agent.state[0]) #cv2.waitKey() while True: frame_idx += 1 epsilon = max(EPSILON_FINAL, EPSILON_START - frame_idx / EPSILON_DECAY_LAST_FRAME) reward = agent.play_step(net, epsilon) #cv2.imshow("State", agent.state[0]) #cv2.waitKey(int(1000/90)) if reward is not None: total_rewards.append(reward) speed = (frame_idx - ts_frame) / (time.time() - ts) ts_frame = frame_idx ts = time.time() mean_reward = np.mean(total_rewards[-100:]) print("%d: done %d games, mean reward %.3f, eps %.2f, speed %.2f f/s" % ( frame_idx, len(total_rewards), mean_reward, epsilon, speed )) if best_mean_reward is None or best_mean_reward < mean_reward: #ref_net.model.set_weights(net.model.get_weights()) if best_mean_reward is not None: print("Best mean reward updated %.3f -> %.3f" % (best_mean_reward, mean_reward)) best_mean_reward = mean_reward if mean_reward > 15: print("Solved in %d frames!" % frame_idx) break if len(buffer) < REPLAY_START_SIZE: continue if frame_idx % SYNC_TARGET_FRAMES == 0: tgt_net.model.set_weights(net.model.get_weights()) batch = buffer.sample(BATCH_SIZE) with tf.GradientTape() as tape: pretrain_loss = get_loss(batch, tgt_net, net) gradients = tape.gradient(pretrain_loss, net.model.trainable_variables) net.optimizer.apply_gradients(zip(gradients, net.model.trainable_variables)) #posttrain_loss = get_loss(batch, tgt_net, net) #print(str(pretrain_loss) + " " + str(posttrain_loss)) cv2.destroyAllWindows() <file_sep>/README.md # tfpong Messing around with AI Gym Pong and Tensorflow 2 <file_sep>/tf_dqn.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 19 08:32:19 2019 @author: anthrod """ import tensorflow as tf from tensorflow import keras from tensorflow.keras import datasets, layers, models, optimizers import numpy as np import random class DQN: def __init__(self, input_shape, num_outputs, learning_rate=1e-4): self.model = models.Sequential( layers=[ layers.Conv2D(32, (8,8), activation='relu', strides=(4,4), input_shape=(input_shape[0], input_shape[1], input_shape[2]), data_format="channels_first", use_bias=True), layers.Conv2D(64, (4,4), activation='relu', strides=(2,2), use_bias=True), layers.Conv2D(64, (3,3), activation='relu', strides=(1,1), use_bias=True), layers.Flatten(), layers.Dense(512, activation='relu', use_bias=True), layers.Dense(num_outputs, use_bias=True) ] ) self.optimizer = optimizers.Adam(learning_rate=learning_rate, epsilon=1e-8) #self.model.compile(self.optimizer) #print(self.model.summary()) if __name__ == "__main__": input_shape = (84, 84, 4) output_shape = 3 net = DQN(input_shape, output_shape) import wrappers env = wrappers.make_env('PongNoFrameskip-v4') env.reset() state = env.step(random.choice([0,1,2])) print(net.forward(np.asarray(state[0]).reshape(1,84,84,4)))
5b1935c41b579c416af913ec7fa33084c5a7d464
[ "Markdown", "Python" ]
3
Python
anthrod/tfpong
b9b157745c8b642c1049085b563cacf214446d2d
27452674cd17af0f4d2ad727af4cb2a13e55bedb
refs/heads/master
<repo_name>ferrello/CI_LISP<file_sep>/README.md # Channel Islands Lisp Implement a compiler using flex (lex) and bison (yacc). The implementation will span several stages; each stage will add a feature to the interpreter. The later stages are much more challenging than the initial stages. :exclamation: Only completed to Task 7 ! ## Author > <NAME> > CSU Channel Islands > COMP 232 - Programming Languages ## Tasks ### Task 1 - Math We will be constructing and evaluating abstract syntax trees representing the Cambridge Polish Notation input. :exclamation: Results of DOUBLE_TYPE that are whole numbers will be converted to INT_TYPE to remove trailing zeros. `> (add 1 2)` `> (mult 2.5 3)` `> (pow 16 3.5)` `> (hypot 3 4)` ### Task 2 - Variables Extends the Bison (yacc) grammar to accommodate variables that in Lisp jargon are called symbols. Variables exist in potentially nested scopes that can be defined by the let section construct preceding CILisp s-expressions. Each symbol assumes a value represented by the associated s-expression. A symbol can be any number of small and capital letters. :exclamation: Results of DOUBLE_TYPE that are whole numbers will be converted to INT_TYPE to remove trailing zeros. `> ((let (x 1))(neg x))` `> (add ((let (abc 1)) (sub 3 abc)) 4)` `> ((let (abc 1)) (sub ((let (abc 2) (de 3)) (add abc de)) abc))` ### Task 3 - Type Casting Extend the capabilities of ciLisp by adding type-casting. The types apply to numbers and symbol definitions. The type of a symbol may (optionally) be assigned in the extended let section that now allows specifying types of symbols. Similarly, the type of a number literal may be assigned. The type of more complicated s-expressions has to be derived during evaluation of the expression from the types of its elements. `> (mult ((let (double a 1) (int b 2)) (add a b)) (sqrt 2))` `> (add ((let (int a ((let (double b 2)) (mult b (sqrt 10))))) (div a 2)) ((let (c 5)) (sqrt c)))` ### Task 4 - Print Expression Extend the capabilities of ciLisp by adding a unary print function. The print function should display the value of the s-expression in the format depending on the type of the expression. Printing should happen when the f_expr is evaluated, NOT when the function ast node is created. When said f_expr is evaluated, the returned RET_VAL should be the result of evaluating the printed s_expr. `> (print s_expr)` ### Task 5 - Parameter Lists Expands the capability of ciLisp by adding support for parameter lists of arbitrary length. The number of parameters in the list of parameters must meet the needs of the function. If there are too few parameters provided, the evaluator should issue a runtime error: `Error :: <function> :: Too few parameters for the function` and return the value of NAN. If more than necessary parameters are provided for a given function, then the evaluator should use as many as appropriate, and issue a runtime warning: `Warning :: <function> :: Too many parameters for the function`. The operations of addition and multiplication should accommodate any number of parameters. Print should print the values of all s-expressions in the list in one line separated by spaces and return the value of the last s-expression in the list as its own value. ``` > ((let (int a 1)(double b 2))(print a b 3)) => 1 2.000000 3 RET_VAL :: INT_TYPE :: 3 ``` ### Task 6 - Conditional Expressions Expands the capability of ciLisp by adding conditional expressions and capability to read user provided and random values Add read as a parameter-less function that takes values from the user. The user should be prompted to enter a value by displaying a prompt: ``` > ((let (int a (read)) (double b (read)) (c (read)) (d (read))) (print a b c d)) Read := 5 Read := 5.5 Read := 6 Read := 6.5 => 5 5.500000 6 6.500000 RET_VAL :: DOUBLE_TYPE :: 6.500000 ``` Add rand as a function that generates pseudo-random numbers. The function does not take any parameters, and generates a random double value between 0 and 1. Note that the C function rand creates a random integer from 0 to RAND_MAX, so typecasting and division by RAND_MAX with this function can be used to create a random double in the range 0 to 1. It can be called as follows: `((let (a 0)) (cond (less (rand) 0.5) (add a 1) (sub a 1)))` Add comparison functions equal, less, and greater. The functions return 1 if the condition holds, and 0 otherwise. So (less (rand) 0.5) returns 1 if the randomly generated number is less than 0.5, and returns 0 otherwise. Added cond function that checks if the first s-expression is true (non-zero). If so, then the next expression is evaluated and returned. Otherwise, the third s-expression is evaluated and returned. `((let (myA (read))(myB (rand)))(cond (less myA myB) (print myA) (print myB)))` ### Task 7 - User Defined Function Expands the capability of ciLisp by adding support for user-defined functions. Function definitions should be placed in the let section. A function should have a positive number of formal arguments (symbols). The body of the function is an expression that may use formal parameters. Similarly to the use of let and cond, the lambda keyword should be used just for parsing. `((let (double myFunc lambda (x y) (mult (add x 5) (sub y 2)))) (sub (myFunc 3 5) 2))` `((let (f lambda (x y) (add x y)))(f (sub 5 2) (mult 2 3))) ` ### Task 8 - Recursive User Defined Function :exclamation: Did not complete!<file_sep>/src/ciLisp.c // Name: <NAME> // Lab: CILisp - Task 7 // Date: 12/2/19 // Course: COMP 232 - Programming Languages #include "ciLisp.h" void yyerror(char *s) { // Note stderr that normally defaults to stdout, but can be redirected: ./src 2> src.log // CLion will display stderr in a different color from stdin and stdout fprintf(stderr, "\nERROR: %s\n", s); //exit(1); } RET_VAL eval(AST_NODE *node) { // RET_VAL (NUM_AST_NODE) with defaults RET_VAL result = {INT_TYPE, NAN}; // Check for NULL AST_NODE if (NULL == node) return result; // Based on node's AST_NODE_TYPE perform equivalent evaluation switch (node->type) { case NUM_NODE_TYPE: result = evalNumNode(&node->data.number); break; case FUNC_NODE_TYPE: result = evalFuncNode(&node->data.function); break; case COND_NODE_TYPE: result = evalCondNode(&node->data.condition); break; case SYMBOL_NODE_TYPE: result = evalSymNode(node->data.symbol.ident, node); break; default: yyerror("Invalid AST_NODE_TYPE, probably invalid writes somewhere!"); } return result; } RET_VAL evalNumNode(NUM_AST_NODE *number) { // RET_VAL (NUM_AST_NODE) with defaults RET_VAL result = {INT_TYPE, NAN}; // Set RET_VAL's value, check for DOUBLE_TYPE result.value = number->value; if (DOUBLE_TYPE == number->type) result.type = DOUBLE_TYPE; return result; } RET_VAL evalFuncNode(FUNC_AST_NODE *funcNode) { // RET_VAL (NUM_AST_NODE) with defaults RET_VAL result = {INT_TYPE, NAN}; // Check for NULL funcNode, before use if (NULL == funcNode) return result; checkParameters(funcNode->oper, funcNode->opList); RET_VAL op1 = eval(funcNode->opList); RET_VAL op2 = eval(funcNode->opList->next); switch (funcNode->oper) { case NEG_OPER: result.value = -op1.value; break; case ABS_OPER: result.value = fabs(op1.value); break; case SQRT_OPER: result.value = sqrt(op1.value); break; case EXP_OPER: result.value = exp(op1.value); break; case EXP2_OPER: result.value = exp2(op1.value); break; case LOG_OPER: if (result.value == 0.0) puts("Why you log a zero!?"); result.value = log(op1.value); break; case CBRT_OPER: result.value = cbrt(op1.value); break; case SUB_OPER: result.value = op1.value - op2.value; break; case DIV_OPER: if (op2.value == 0.0) puts("Why you divide by zero!?"); result.value = op1.value / op2.value; break; case REMAINDER_OPER: if (op2.value == 0.0) puts("Why you divide by zero!?"); result.value = fmod(op1.value, op2.value); break; case POW_OPER: result.value = pow(op1.value, op2.value); break; case MAX_OPER: result.value = op1.value > op2.value ? op1.value : op2.value; break; case MIN_OPER: result.value = op1.value < op2.value ? op1.value : op2.value; break; case HYPOT_OPER: result.value = hypot(op1.value, op2.value); break; case EQUAL_OPER: result.value = op1.value == op2.value ? 1 : 0; break; case LESS_OPER: result.value = op1.value < op2.value ? 1 : 0; break; case GREATER_OPER: result.value = op1.value > op2.value ? 1 : 0; break; case ADD_OPER: case MULT_OPER: result = multaryOperation(op1, funcNode->oper, funcNode->opList->next); break; case PRINT_OPER: result = printExpression(funcNode->opList); return result; case CUSTOM_OPER: result = customOperation(funcNode); default: // Returns {INT_TYPE, NAN}, should never occur break; } if (DOUBLE_TYPE == op1.type || DOUBLE_TYPE == op2.type) result.type = DOUBLE_TYPE; else result.value = floor(result.value); return result; } RET_VAL evalCondNode(COND_AST_NODE *condition) { RET_VAL result = eval(condition->cond); if (true == result.value) return eval(condition->valid); else return eval(condition->invalid); } RET_VAL evalSymNode(char *ident, AST_NODE *parent) { // Base case, symbol not found in outer scopes if (parent == NULL) { message(2, ident); return (RET_VAL) {INT_TYPE, NAN}; } SYMBOL_TABLE_NODE *currSymTabNode = parent->symbolTable; // Search current scope for symbol while (currSymTabNode != NULL) { if (strcmp(ident, currSymTabNode->ident) == 0) { RET_VAL result = eval(currSymTabNode->value); // Check for a data type. If there is a data type, then assure // that the AST_NODE value has the same explicit data type provided. if (INT_TYPE == currSymTabNode->dataType && DOUBLE_TYPE == result.type) { // Throw a warning when explicitly converting a DOUBLE_TYPE value to INT_TYPE message(3, currSymTabNode->ident); // Floor the double value for INT_TYPE result.value = floor(result.value); // Set result's type as the explicit data type result.type = currSymTabNode->dataType; } if (DOUBLE_TYPE == currSymTabNode->dataType && INT_TYPE == result.type) result.type = DOUBLE_TYPE; return result; } // Move to next SYMBOL_TABLE_NODE currSymTabNode = currSymTabNode->next; } // Recursively search parent's symbol table return evalSymNode(ident, parent->parent); } RET_VAL multaryOperation(RET_VAL result, OPER_TYPE operation, AST_NODE *opList) { AST_NODE *currOp = opList; while (NULL != currOp) { RET_VAL op = eval(currOp); switch (operation) { case ADD_OPER: result.value += op.value; break; case MULT_OPER: result.value *= op.value; break; default: break; } // Check for DOUBLE_TYPE if (DOUBLE_TYPE == op.type) result.type = DOUBLE_TYPE; // Move to the next opList AST_NODE currOp = currOp->next; } return result; } RET_VAL printExpression(AST_NODE *opList) { RET_VAL result = {INT_TYPE, NAN}; printf("%s", "=> "); AST_NODE *currOpNode = opList; while (NULL != currOpNode) { result = eval(currOpNode); switch (result.type) { case INT_TYPE: printf("%ld ", (long) result.value); break; case DOUBLE_TYPE: printf("%lf ", result.value); break; default: break; } currOpNode = currOpNode->next; } puts(""); return result; } RET_VAL customOperation(FUNC_AST_NODE *function) { RET_VAL result = {INT_TYPE, NAN}; // Lambda Function Definition SYMBOL_TABLE_NODE *lambda = evalLambda(function->ident, function->opList); if (NULL == lambda) return result; SYMBOL_TABLE_NODE *currArg = lambda->value->argumentTable; AST_NODE *currOp = function->opList; while (NULL != currOp) { result = eval(currOp); currArg->value = initASTNode(); currArg->value->type = NUM_NODE_TYPE; currArg->value->data.number.value = result.value; currArg->value->data.number.type = result.type; currArg = currArg->next; currOp = currOp->next; } result = eval(lambda->value); return result; } SYMBOL_TABLE_NODE *evalLambda(char *ident, AST_NODE *parent) { // Base case, lambda not found in outer scopes if (parent == NULL) { message(4, ident); return NULL; } SYMBOL_TABLE_NODE *currArgTabNode = parent->symbolTable; // Search current scope for lambda while (NULL != currArgTabNode) { if (strcmp(ident, currArgTabNode->ident) == 0) { return currArgTabNode; } currArgTabNode = currArgTabNode->next; } // Recursively search parent's symbol table return evalLambda(ident, parent->parent); } void checkParameters(OPER_TYPE operation, AST_NODE *opList) { switch (operation) { case NEG_OPER ... CBRT_OPER: if (NULL != opList->next) message(1, funcNames[operation]); break; case SUB_OPER ... GREATER_OPER: if (opList->next == NULL) message(0, funcNames[operation]); else if (opList->next->next != NULL) message(1, funcNames[operation]); break; case ADD_OPER: case MULT_OPER: case CUSTOM_OPER: if (opList->next == NULL) message(0, funcNames[operation]); break; default: break; } } void printRetVal(RET_VAL result) { // Based on NUM_TYPE of RET_VAL print accordingly if (isnan(result.value) == 0) { switch (result.type) { case INT_TYPE: printf("%ld\n", (long) result.value); break; case DOUBLE_TYPE: printf("%lf\n", result.value); break; default: break; } } } void freeNode(AST_NODE *node) { if (NULL == node) return; switch (node->type) { case NUM_NODE_TYPE: break; case FUNC_NODE_TYPE: freeNode(node->data.function.opList->next); free(node->data.function.ident); freeNode(node->data.function.opList); break; case COND_NODE_TYPE: freeNode(node->data.condition.cond); freeNode(node->data.condition.valid); freeNode(node->data.condition.invalid); break; case SYMBOL_NODE_TYPE: free(node->data.symbol.ident); break; } freeSymbolTable(node->symbolTable); freeSymbolTable(node->argumentTable); free(node); } void freeSymbolTable(SYMBOL_TABLE_NODE *node) { if (NULL == node) return; // free(node->ident); // freeNode(node->value); // freeSymbolTable(node->next); // free(node); } void message(short type, char *data) { switch (type) { case 0: printf("Error :: Too few parameters for the function \"%s\". " "First parameter will be passed to calculate result!\n", data); break; case 1: printf("Warning :: Too many parameters for the function \"%s\"\n", data); break; case 2: printf("Error :: Symbol not found in scope \"%s\"\n", data); break; case 3: printf("Warning :: Precision loss in the assignment for variable \"%s\"\n", data); break; case 4: printf("Error :: Lambda not found in scope \"%s\"\n", data); break; default: break; } }<file_sep>/src/ciLisp.h // Name: <NAME> // Lab: CILisp - Task 7 // Date: 12/2/19 // Course: COMP 232 - Programming Languages #ifndef __cilisp_h_ #define __cilisp_h_ // ****************** // PreProcess // ****************** #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <math.h> #include <stdbool.h> #include "ciLispParser.h" #define BUF_LEN 64 // ****************** // Flex/Bison // ****************** int yylex(void); void yyerror(char *); static char *funcNames[] = { "neg", "abs", "sqrt", "exp", "exp2", "log", "cbrt", "sub", "div", "remainder", "pow", "max", "min", "hypot", "equal", "less", "greater", "add", "mult", "print", "read", "rand", ""}; // Enum of all AST_FUNCTION_NODE operators. // Must be in sync with funcs in resolveFunc() typedef enum oper { NEG_OPER, ABS_OPER, SQRT_OPER, EXP_OPER, EXP2_OPER, LOG_OPER, CBRT_OPER, SUB_OPER, DIV_OPER, REMAINDER_OPER, POW_OPER, MAX_OPER, MIN_OPER, HYPOT_OPER, EQUAL_OPER, LESS_OPER, GREATER_OPER, ADD_OPER, MULT_OPER, PRINT_OPER, READ_OPER, RAND_OPER, CUSTOM_OPER = 255 } OPER_TYPE; // ****************** // Abstract Tree // ****************** // Types of Abstract Syntax Tree nodes. typedef enum { NUM_NODE_TYPE, FUNC_NODE_TYPE, COND_NODE_TYPE, SYMBOL_NODE_TYPE } AST_NODE_TYPE; // Types of numeric values typedef enum { NO_TYPE, INT_TYPE, DOUBLE_TYPE } NUM_TYPE; // Types of symbol type typedef enum { VARIABLE_TYPE, LAMBDA_TYPE, ARG_TYPE } SYMBOL_TYPE; // Node to store a number. typedef struct { NUM_TYPE type; double value; } NUM_AST_NODE; // RET_VAL with NUM_AST_NODE structure for eval return types (readability) typedef NUM_AST_NODE RET_VAL; // Node to store a function call with its inputs typedef struct { OPER_TYPE oper; // ENUM Type char *ident; // Custom function identifier struct ast_node *opList; // Linked-list of arguments } FUNC_AST_NODE; // Node to store a symbol table (LL) node with its data typedef struct symbol_table_node { SYMBOL_TYPE type; // VAR, ARG, LAMBDA Type NUM_TYPE dataType; // INT_TYPE or DOUBLE_TYPE char *ident; // Symbol Identifier struct ast_node *value; // Any AST_NODE_TYPE value struct symbol_table_node *next; // Pointer to next symbol table (LL) node } SYMBOL_TABLE_NODE; // Node to store a symbol with its identifier typedef struct symbol_ast_node { char *ident; } SYMBOL_AST_NODE; typedef struct cond_ast_node { struct ast_node *cond; // Type of condition: Read, Rand, Greater, Less, Equal struct ast_node *valid; // To eval if a condition is non-zero struct ast_node *invalid; // To eval if a condition is zero } COND_AST_NODE; // Generic Abstract Syntax Tree node. Stores the type of node, // and reference to the corresponding specific node. typedef struct ast_node { AST_NODE_TYPE type; // NUM, FUNC, SYMBOL SYMBOL_TABLE_NODE *symbolTable; // AST_NODE holds a scoped symbol table (LL) SYMBOL_TABLE_NODE *argumentTable; // AST_NODE holds a scoped symbol table (LL) struct ast_node *parent; // AST_NODE points to a parent AST_NODE (for outer scope) union { NUM_AST_NODE number; // Holds NUM_AST_NODE to store a number FUNC_AST_NODE function; // Holds FUNC_AST_NODE to store an operation COND_AST_NODE condition; // Holds a COND_AST_NODE to store a condition SYMBOL_AST_NODE symbol; // Holds SYMBOL_AST_NODE to reference a symbol } data; struct ast_node *next; } AST_NODE; // ****************** // Functions // ****************** RET_VAL eval(AST_NODE *); RET_VAL evalNumNode(NUM_AST_NODE *); RET_VAL evalFuncNode(FUNC_AST_NODE *); RET_VAL evalCondNode(COND_AST_NODE *); RET_VAL evalSymNode(char *, AST_NODE *); RET_VAL multaryOperation(RET_VAL, OPER_TYPE, AST_NODE *); RET_VAL printExpression(AST_NODE *); RET_VAL customOperation(FUNC_AST_NODE *); SYMBOL_TABLE_NODE *evalLambda(char *, AST_NODE *); void checkParameters(OPER_TYPE, AST_NODE *); void printRetVal(RET_VAL); void freeNode(AST_NODE *); void freeSymbolTable(SYMBOL_TABLE_NODE *); void message(short, char *); static inline AST_NODE *initASTNode() { AST_NODE *node = NULL; // Allocate space for AST_NODE, otherwise error if ((node = calloc(1, sizeof(AST_NODE))) == NULL) yyerror("Memory allocation failed!"); // Note: For real world systems, calloc will zero out (point to NULL) // every field of the AST_NODE. return node; } static inline SYMBOL_TABLE_NODE *initSTNode() { SYMBOL_TABLE_NODE *node = NULL; // Allocate space for AST_NODE, otherwise error if ((node = calloc(1, sizeof(SYMBOL_TABLE_NODE))) == NULL) yyerror("Memory allocation failed!"); // Note: For real world systems, calloc will zero out (point to NULL) // every field of the SYMBOL_TABLE_NODE. return node; } static inline OPER_TYPE resolveFunc(char *funcName) { int i = 0; while (funcNames[i][0] != '\0') { if (strcmp(funcNames[i], funcName) == 0) return i; i++; } return CUSTOM_OPER; } #endif
622189bd25326a954831208a08b40e9283a62dd9
[ "Markdown", "C" ]
3
Markdown
ferrello/CI_LISP
0fdb624f5d9f6fed6e56fcf90967be1690164597
7280ffff8d4a8da36b3e857b87fd057ebbf67153
refs/heads/master
<repo_name>abhihyder/arrayFundamentals<file_sep>/array_count_values.php <?php /* The array_count_values() function counts all the values of an array. Syntax: array_count_values(array) */ $a=array("A","Cat","Dog","A","Dog"); print_r(array_count_values($a)); ?><file_sep>/array_key_exists.php <?php /* The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist. Syntax array_key_exists(key, array) */ $a=array("Volvo"=>"XC90","BMW"=>"X5"); if (array_key_exists("Volvo",$a)) { echo "Key exists!"; } else { echo "Key does not exist!"; } ?><file_sep>/array_combine.php <?php /* The array_combine() function creates an array by using the elements from one "keys" array and one "values" array. Note: Both arrays must have equal number of elements! Syntax: array_combine(keys, values) */ $fname=array("Ranar","Zaher","Rony"); $age=array("35","37","43"); $c=array_combine($fname,$age); print_r($c); ?><file_sep>/array_change_key_case.php <?php /* array change key case function Syntex: array_change_key_case(array, CASE_LOWER/UPPER); */ $y=array("ahmed"=>20, "badhon"=>22, "choton"=>24, "dhrubo"=>21); $x=array_change_key_case($y, CASE_UPPER); foreach($x as $name=>$age){ echo $name." age ".$age."<br>"; } $y1=array("Ahmed"=>20, "Badhon"=>22, "Choton"=>24, "Dhrubo"=>21); $x1=array_change_key_case($y1, CASE_LOWER); foreach($x1 as $name1=>$age1){ echo $name1." age ".$age1."<br>"; } ?><file_sep>/array_keys.php <?php /* The array_keys() function returns all keys of an array containing the keys. Syntax array_keys(array, value, strict) */ $a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander"); print_r(array_keys($a)); ?><file_sep>/array_column.php <?php /* The array_column() function returns the values from a single column in the input array. Syntex: array_column(array, column_key, index_key) */ $a = array( array( 'id' => 5698, 'first_name' => 'Peter', 'last_name' => 'Griffin' ), array( 'id' => 4767, 'first_name' => 'Ben', 'last_name' => 'Smith' ), array( 'id' => 3809, 'first_name' => 'Joe', 'last_name' => 'Doe' ) ); $last_name = array_column($a, 'last_name', 'id'); // or $last_name = array_column($a, 'last_name'); print_r($last_name)."<br>"; ?><file_sep>/array_diff_assoc.php <?php /* The array_diff_assoc() function compares the keys and values of first array ( 1st mantion in the function) with other one (or more) arrays, and returns the differences. Syntax array_diff_assoc(array1,array2,array3...) */ $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("e"=>"red","f"=>"green","g"=>"blue", "h"=>"white"); $result=array_diff_assoc($a1,$a2); print_r($result); ?>
71f228621fd2e9a898e9be44ae51fe35fd8e5d9d
[ "PHP" ]
7
PHP
abhihyder/arrayFundamentals
bcf4e73ea295453f35aa5c82299a87939be4b312
979a764b3bd12637ff3b3a32c8c78b9c7f0eadf0
refs/heads/master
<file_sep># Android-Things-PCA9685 Android-Things library for PCA9685 PWM Chip and Servos <file_sep>include ':app', ':libPCA9685' <file_sep>// Top-level build file where you can add configuration options common to all sub-projects/modules. ext { compileSdkVersion = 27 buildToolsVersion = "28.0.1" sdkVersion = 27 supportVersion = "27.1.1" thingsVersion = "1.0" espressoVersion = "3.0.0" testRunnerVersion = "1.0.0" mockitoVersion = "2.8.9" annotationsVersion = "4.3.1" constraintLayoutVersion = "1.1.0" permissionHelperVersion = "1.1.0" version = getTheVersion() buildNumber = getTheBuildNumber() // // bintrayRepo = 'maven' // publishedGroupId = 'nz.org.winters' // siteUrl = 'https://github.com/wintersandroid/Android-Things-PCA9685' // artifact = "libPCA9685" // libraryDescription = "PCA9685 Servo Lib for Android Things" // libraryVersion = getTheVersion() } buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.1.3' classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } def static getBuildMajor(){ return 1 } def getTheVersion() { def buildMajor = getBuildMajor() def buildNumber = getTheBuildNumber() if( buildNumber == 0) { return "${buildMajor}.${buildNumber}-SNAPSHOT" }else{ return "${buildMajor}.${buildNumber}" } } def getTheBuildNumber(){ return hasProperty('BUILD_NUMBER') ? BUILD_NUMBER.toInteger() : 0 } //def getBintrayUser(){ // return hasProperty('BINTRAY_USER') ? BINTRAY_USER : "" //} // //def getBintrayApiKey(){ // return hasProperty('BINTRAY_KEY') ? BINTRAY_KEY : "" //} <file_sep>package nz.org.winters.android.libpca9685; import android.support.annotation.NonNull; import android.util.Log; import com.google.android.things.pio.I2cDevice; import com.google.android.things.pio.PeripheralManager; import java.io.Closeable; import java.io.IOException; import java.util.List; /** * Created by mathew on 18/01/17. * Copyright 2017 <NAME> */ @SuppressWarnings({"WeakerAccess", "unused","squid:S00115", "squid:S1068"}) public class PCA9685 implements Closeable{ public static final byte PCA9685_ADDRESS = 0x40; private static final int MODE1 = 0x00; private static final int MODE2 = 0x01; private static final int SUBADR1 = 0x02; // NOSONAR private static final int SUBADR2 = 0x03; // NOSONAR private static final int SUBADR3 = 0x04; // NOSONAR private static final int PRESCALE = 0xFE; private static final int LED0_ON_L = 0x06; private static final int LED0_ON_H = 0x07; private static final int LED0_OFF_L = 0x08; private static final int LED0_OFF_H = 0x09; private static final int ALL_LED_ON_L = 0xFA; private static final int ALL_LED_ON_H = 0xFB; private static final int ALL_LED_OFF_L = 0xFC; private static final int ALL_LED_OFF_H = 0xFD; // Bits private static final int RESTART = 0x80; // NOSONAR private static final int SLEEP = 0x10; private static final int ALLCALL = 0x01; private static final int INVRT = 0x10; // NOSONAR private static final int OUTDRV = 0x04; private static final String TAG = PCA9685.class.getName(); private I2cDevice i2cDevice; public PCA9685(byte address, @NonNull PeripheralManager manager) throws IOException, InterruptedException { List<String> deviceList = manager.getI2cBusList(); if (deviceList.isEmpty()) { i2cDevice = null; Log.i(TAG, "No I2C bus available on this device."); } else { Log.i(TAG, "List of available devices: " + deviceList); try { i2cDevice = manager.openI2cDevice(deviceList.get(0), address); if (i2cDevice != null) { setAllPwm(0, 0); i2cDevice.writeRegByte(MODE2, (byte) OUTDRV); i2cDevice.writeRegByte(MODE1, (byte) ALLCALL); Thread.sleep(5); // #wait for oscillator byte mode1 = i2cDevice.readRegByte(MODE1); mode1 = (byte) (mode1 & ~SLEEP); //#wake up (reset sleep) i2cDevice.writeRegByte(MODE1, mode1); Thread.sleep(5); //#wait for oscillator setPwmFreq(50); // good default. } } catch (IOException e) { Log.d(TAG, "IO Error " + e.getMessage()); e.printStackTrace(); // NOSONAR throw e; } catch (InterruptedException e) { Log.d(TAG, "Error in sleep " + e.getMessage()); e.printStackTrace(); // NOSONAR throw e; } } } public void setPwmFreq(int freqHz) throws IOException { try { double prescaleval = 25000000.0; //# 25MHz prescaleval /= 4096.0; //# 12-bit prescaleval /= freqHz; prescaleval -= 1.0; Log.d(TAG, String.format("Setting PWM frequency to %d Hz", freqHz)); Log.d(TAG, String.format("Estimated pre-scale: %.4f", prescaleval)); int prescale = (int) Math.floor(prescaleval + 0.5); Log.d(TAG, String.format("Final pre-scale: %d", prescale)); byte oldmode = i2cDevice.readRegByte(MODE1); byte newmode = (byte) ((oldmode & 0x7F) | 0x10); //#sleep i2cDevice.writeRegByte(MODE1, newmode); //#go to sleep i2cDevice.writeRegByte(PRESCALE, (byte) prescale); i2cDevice.writeRegByte(MODE1, oldmode); Thread.sleep(5); i2cDevice.writeRegByte(MODE1, (byte) (oldmode | 0x80)); } catch (IOException e) { Log.d(TAG, "IO Error " + e.getMessage()); e.printStackTrace(); // NOSONAR throw e; } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } public void setPwm(int channel, int on, int off) throws IOException { if (i2cDevice != null && channel >= 0 && channel < 16) { try { i2cDevice.writeRegByte(LED0_ON_L + 4 * channel, (byte) (on & 0xFF)); i2cDevice.writeRegByte(LED0_ON_H + 4 * channel, (byte) (on >> 8)); i2cDevice.writeRegByte(LED0_OFF_L + 4 * channel, (byte) (off & 0xFF)); i2cDevice.writeRegByte(LED0_OFF_H + 4 * channel, (byte) (off >> 8)); } catch (IOException e) { e.printStackTrace(); // NOSONAR throw e; } } } public void setAllPwm(int on, int off) throws IOException { if (i2cDevice != null) { try { i2cDevice.writeRegByte(ALL_LED_ON_L, (byte) (on & 0xFF)); i2cDevice.writeRegByte(ALL_LED_ON_H, (byte) (on >> 8)); i2cDevice.writeRegByte(ALL_LED_OFF_L, (byte) (off & 0xFF)); i2cDevice.writeRegByte(ALL_LED_OFF_H, (byte) (off >> 8)); } catch (IOException e) { e.printStackTrace(); // NOSONAR throw e; } } } @Override public void close() throws IOException { if (i2cDevice != null) { i2cDevice.close(); } } } <file_sep>package nz.org.winters.android.androidthingspca9685; import android.content.Context; import android.content.SharedPreferences; /** * Created by mathew on 17/01/17. * Copyright 2017 <NAME> */ class AppPrefs { private final SharedPreferences sharedPref; AppPrefs(Context context){ sharedPref = context.getSharedPreferences("test",Context.MODE_PRIVATE); } int selectedChannel() { return sharedPref.getInt("selectedChannel",0); } void selectedChannel(int value) { SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt("selectedChannel",value); editor.apply(); } String channelAnglesLeft() { return sharedPref.getString("channelAnglesLeft",""); } String channelAnglesRight() { return sharedPref.getString("channelAnglesRight",""); } void channelAnglesLeft(String value){ SharedPreferences.Editor editor = sharedPref.edit(); editor.putString("channelAnglesLeft",value); editor.apply(); } void channelAnglesRight(String value){ SharedPreferences.Editor editor = sharedPref.edit(); editor.putString("channelAnglesRight",value); editor.apply(); } } <file_sep>apply plugin: 'com.android.application' android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig { applicationId "nz.org.winters.android.androidthingspca9685" targetSdkVersion rootProject.ext.sdkVersion minSdkVersion rootProject.ext.sdkVersion versionCode rootProject.ext.buildNumber versionName rootProject.ext.version testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation 'com.google.code.findbugs:jsr305:3.0.1' compileOnly "com.google.android.things:androidthings:${rootProject.ext.thingsVersion}" // annotationProcessor "org.androidannotations:androidannotations:${rootProject.ext.annotationsVersion}" // implementation "org.androidannotations:androidannotations-api:${rootProject.ext.annotationsVersion}" implementation "com.android.support:appcompat-v7:${rootProject.ext.supportVersion}" implementation "com.github.k0shk0sh:PermissionHelper:${rootProject.ext.permissionHelperVersion}" implementation("com.appyvet:materialrangebar:1.3", { exclude group: "com.android.support" }) implementation 'com.google.guava:guava:23.0-android' implementation fileTree(include: ['*.jar'], dir: 'libs') androidTestImplementation("com.android.support.test.espresso:espresso-core:${rootProject.ext.espressoVersion}", { exclude group: "com.android.support", module: "support-annotations" }) testImplementation 'junit:junit:4.12' implementation project(path: ':libPCA9685') } <file_sep>apply plugin: 'com.android.library' android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig { targetSdkVersion rootProject.ext.sdkVersion minSdkVersion rootProject.ext.sdkVersion versionCode rootProject.ext.buildNumber versionName rootProject.ext.version testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } testOptions { unitTests.returnDefaultValues = true } } dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) compileOnly "com.google.android.things:androidthings:${rootProject.ext.thingsVersion}" implementation "com.android.support:support-annotations:${rootProject.ext.supportVersion}" testImplementation "com.google.android.things:androidthings:${rootProject.ext.thingsVersion}" testImplementation "junit:junit:4.12" testImplementation "com.android.support:support-annotations:${rootProject.ext.supportVersion}" testImplementation "com.android.support.test:runner:${rootProject.ext.testRunnerVersion}" testImplementation "com.android.support.test:rules:${rootProject.ext.testRunnerVersion}" testImplementation "org.mockito:mockito-core:${rootProject.ext.mockitoVersion}" } apply from: 'publish.gradle' <file_sep>package nz.org.winters.android.libpca9685; import android.support.annotation.NonNull; import com.google.android.things.pio.PeripheralManager; import java.io.IOException; /** * Created by mathew on 6/01/17. * Copyright 2017 <NAME> */ @SuppressWarnings({"WeakerAccess", "SameParameterValue", "unused"}) public class PCA9685Servo extends PCA9685 { private int minPwm; private int maxPwm; private int minAngle; private int maxAngle; public PCA9685Servo(byte address, @NonNull PeripheralManager manager) throws IOException, InterruptedException { super(address, manager); } public void setServoMinMaxPwm(int minAngle, int maxAngle, int minPwm, int maxPwm) { this.maxPwm = maxPwm; this.minPwm = minPwm; this.minAngle = minAngle; this.maxAngle = maxAngle; } public void setServoAngle(int channel, int angle) throws IOException { setPwm(channel, 0, map(angle, minAngle, maxAngle, minPwm, maxPwm)); } public int map(int x, int inMin, int inMax, int outMin, int outMax) { return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin; } }
f142e5d2e3c20a90c7c8356f830d344a0aa39f7c
[ "Markdown", "Java", "Gradle" ]
8
Markdown
wintersandroid/Android-Things-PCA9685
6da7d9d3d20f3dc98612b1642a5d80f614d0e65d
7f8c748dfafe2c172602d6f30d77712aaad5e23b
refs/heads/master
<repo_name>giddygitau/food-app-d2-assessment<file_sep>/src/controllers/food_items_controller.js const { FoodItem } = require("../models/food_items_model"); class FoodItemsController { static async getAll(req, res, next) { const allFoodItems = await FoodItem.find(); return res.status(200).send({ foodItems: allFoodItems }); } static async getOne(req, res, next) { const { foodItemId } = req.params; const foodItem = await FoodItem.findOne({ _id: foodItemId }); return res.status(200).send(foodItem); } static async create(req, res, next) { const { name } = req.body; console.log("name", name); const createdFoodItem = await FoodItem.create({ name }); if (createdFoodItem) { return res.status(201).send({ createdFoodItem }); } } } module.exports = FoodItemsController; <file_sep>/config/env_variables.js module.exports = { adminMobile: process.env.ADMIN_MOBILE, adminPassword: <PASSWORD>, databaseURL: process.env.DATABASE_URL, env: process.env.NODE_ENV, port: process.env.PORT, secretKey: process.env.SECRET_KEY }; <file_sep>/src/routes/food_items_routes.js const router = require("express").Router(); const FoodItemsController = require("../controllers/food_items_controller"); const { isAdmin, isLoggedIn } = require("../middleware/auth"); router .route("/") .get(FoodItemsController.getAll) .post(isAdmin, FoodItemsController.create); router.route("/:foodItemId").get(isLoggedIn, FoodItemsController.getOne); module.exports = router; <file_sep>/src/routes/orders_routes.js const router = require("express").Router(); const OrdersController = require("../controllers/orders_controller"); const { isAdmin, isLoggedIn } = require("../middleware/auth"); router .route("/") .get(isLoggedIn, OrdersController.getAll) .post(isLoggedIn, OrdersController.create); router .route("/:orderId") .get(isAdmin, OrdersController.getOne) .patch(OrdersController.edit); module.exports = router; <file_sep>/src/routes/user_routes.js const router = require("express").Router(); const UserController = require("../controllers/user_controller"); const { isAdmin } = require("../middleware/auth"); router .route("/") .get(isAdmin, UserController.getAll) .post(UserController.create); router.route("/login").post(UserController.login); module.exports = router; <file_sep>/src/controllers/user_controller.js const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); const { User } = require("../models/user_model"); const { secretKey } = require("../../config/env_variables"); const Boom = require("boom"); class UserController { static async getAll(req, res, next) { const allUsers = await User.find(); return res.status(200).send({ allUsers }); } static create(req, res, next) { const { mobileNumber, password } = req.body; // hash password const salt = bcrypt.genSaltSync(10); const hash = bcrypt.hashSync(password, salt); User.create({ mobileNumber, password: hash }) .then(newUser => { if (newUser) { return res.status(201).send(newUser); } }) .catch(next); } static async login(req, res, next) { const { mobileNumber, password } = req.body; // find if user with supplied mobile number is in DB const user = await User.findOne({ mobileNumber }); if (!user) return next(Boom.unauthorized("Invalid credentials")); // Compare password const validPassword = bcrypt.compareSync(password, user.password); if (!validPassword) return next(Boom.unauthorized("Invalid credentials")); // give token const token = jwt.sign( { userId: user._id, isAdmin: user.isAdmin }, secretKey ); res.status(200).send({ access_token: token }); } } module.exports = UserController; <file_sep>/src/models/orders_model.js const mongoose = require("mongoose"); const Schema = mongoose.Schema; const { FoodItemSchema } = require("./food_items_model"); const { UserSchema } = require("./user_model"); const OrderSchema = new Schema({ user: { _id: mongoose.SchemaTypes.ObjectId, mobile: String }, foodItem: { _id: mongoose.SchemaTypes.ObjectId, name: String }, paid: { type: Boolean, default: false }, delivered: { type: Boolean, default: false } }); const Order = mongoose.model("Order", OrderSchema); module.exports = Order; <file_sep>/README.md # Food Ordering API A RESTful API for ordering food ## Getting Started These instructions will get you a copy of the project up and running on your local machine for development purposes. ### Prerequisites ``` node v8.11.3 or higher ``` ### Installing Run the following commands to install the project locally. ``` $ git clone https://github.com/giddygitau/food-app-d2-assessment.git food-app ``` ``` $ cd food-app && npm install ``` ### Configurations Set the environment variables in the .env.example file to their appropriate values. ``` NODE_ENV - This refers to the environment that the project is running in PORT - The port you want your server to run on DATABASE_URL - A url string to your database ``` ##### Creating an Admin The app contains a script to create admins. It takes the credentials supplied in the environment variables and creates an admin using them. To run the create admin script, execute the following command ``` npm run seed:admin ``` The created admin can now create other users and food items. #### Running the app ``` npm start ``` ### Usage ##### Tools You can use any tool you please to access the Library service API as long as it supports all the HTTP verbs that you need. `cURL`, `Postman` and `Insomnia` are good examples ##### Endpoints | Endpoint | Allowed Methods | Functionality | | ----------------- | --------------- | ------------------------------------------ | | `/users` | POST | Create a user | | `/users/login` | POST | Login a user | | `/food_items` | GET, POST | Create a food item, Fetch all foods | | `/food_items/:id` | GET | Fetch a single food item | | `/orders` | GET, POST | Fetch all orders, Create order | | `/orders/id` | GET, PATCH | Fetch single order, Mark as paid,delivered | ##### Endpoint Payload Format Creating a user: **POST** `/users` also Login **POST** `/users/login` ``` { "mobileNumber": "", "password": "" } ``` Create food item **POST** `/food_items` ``` { "name": "" } ``` Create order **POST** `/orders` ``` { "foodItemId": "" } ``` Mark order as `delivered` or `paid` **PATCH** `/orders/:orderId` ``` { "delivered": "", "paid": "" } ``` #### Deployment A demo of this app is deployed [here](https://fooddeliverapp.herokuapp.com) <file_sep>/src/controllers/orders_controller.js const Boom = require("boom"); const Order = require("../models/orders_model"); const { User } = require("../models/user_model"); const { FoodItem } = require("../models/food_items_model"); class OrdersController { static async getAll(req, res, next) { const orders = await Order.find({ "user._id": req.user }); return res.send({ orders }); } static async create(req, res, next) { const user = await User.findOne({ _id: req.user }); const foodItem = await FoodItem.findOne({ _id: req.body.foodItemId }); const orderer = { _id: user._id, mobileNumber: user.mobileNumber }; // create and save order, using user data and item data from DB const order = await Order.create({ user: orderer, foodItem }); // return order return res.status(201).send({ order }); } static async getOne(req, res, next) { const { orderId } = req.params; const order = await Order.findOne({ _id: orderId }); return res.status(200).send(order); } static edit(req, res, next) { const { orderId } = req.params; const { delivered, paid } = req.body; Order.findById(orderId) .then(order => { if (!order) return next(Boom.notFound("Order with specified ID does not exist")); order.delivered = delivered || order.delivered; order.paid = paid || order.paid; return res.status(200).send(order); }) .catch(next); } } module.exports = OrdersController;
ba7568ebc3662dbbe0b56c507f6905c5cfe9dab7
[ "JavaScript", "Markdown" ]
9
JavaScript
giddygitau/food-app-d2-assessment
5dc8185cecb6e60a2f00ef800fc5c89512ebfd5f
0f052b7db4121d0cdc9c74c0f8adc46a664b18b4
refs/heads/master
<file_sep>import React from "react"; import ReactDOM from "react-dom"; import { ApolloClient } from "apollo-client"; import { createHttpLink } from "apollo-link-http"; import { setContext } from "apollo-link-context"; import { InMemoryCache } from "apollo-cache-inmemory"; import { ApolloProvider, Query } from "react-apollo"; import gql from "graphql-tag"; import "./index.css"; import { BrowserRouter, Route, Switch, Link } from 'react-router-dom'; const httpLink = createHttpLink({ uri: "https://api.github.com/graphql" }); const authLink = setContext((_, { headers }) => { const token = process.env.REACT_APP_TOKEN; return { headers: { ...headers, authorization: token ? `Bearer ${token}` : "" } }; }); const client = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache() }); const gitHubQuery = gql` query { user (login: "torvalds") { repositories(first: 100) { nodes { id name updatedAt createdAt isPrivate url } } } } `; class Repo extends React.Component { constructor(props) { super(props); this.state = { date: '', currentDate: new Date(), } this.getLiveDate = this.getLiveDate.bind(this); } componentDidMount() { this._isMounted = true; setInterval(this.getLiveDate, 10); } componentWillUnmount() { this._isMounted = false; } getLiveDate() { var date = this.state.currentDate - new Date(this.props.updatedAt); var years = Math.floor(date/3.154e+10); date = date - years*3.154e+10; var months = Math.floor(date/2.628e+9); date = date - months*2.628e+9; var days = Math.floor(date/8.64e+7); date = date - days*8.64e+7; var hours = Math.floor(date/3.6e+6); date = date - hours*3.6e+6; var minutes = Math.floor(date/60000); this._isMounted && this.setState({date: days + " дней, " + months + " месяцев, " + years + " лет, " + hours + " часов, " + minutes + " минут назад", currentDate: new Date()}); } getDate(d) { return this.state.currentDate - new Date(d); } render () { return ( <div className="Repo" href="#/"> <li>{this.props.name}</li> <span>{"Последний апдейт: " + (this.getDate(this.props.updatedAt) < 60000 ? "только что" : this.getDate(this.props.updatedAt) < 3.6e+6 ? (Math.round(this.getDate(this.props.updatedAt) / 60000) + " минут назад") : this.getDate(this.props.updatedAt) < 8.64e+7 ? (Math.round(this.getDate(this.props.updatedAt) / 3.6e+6) + " часов назад") : this.state.date)}</span> </div> ) } } class App extends React.Component { constructor(props) { super(props); this.state = { repos: [], query: gitHubQuery, } } liveSearch(e) { var newQuery = gql` query { user(login: "${e.target.value !== "" ? e.target.value : "torvalds"}") { repositories(first: 100) { nodes { id name updatedAt createdAt isPrivate url } } } } `; client .query({ query: gitHubQuery }) .then(result => this.setState({query: newQuery})); } render () { return ( <ApolloProvider client={client}> <div className="App"> <Link to={"/"}> <input placeholder="Имя пользователя..." type="text" onKeyUp={(e) => this.liveSearch(e)}/> </Link> <Query query={this.state.query}> {({ loading, error, data }) => ( loading ? <p>Loading...</p> : error ? <p>Error...</p> : <Switch> <Route path="/about/:id" component={({match}) => data.user.repositories.nodes.find((el) => el.id === match.params.id) ? <ul className="Page"> <li onClick={() => this.liveSearch()}> <h3>Имя репозитория</h3> <h4>{data.user.repositories.nodes.find((el) => el.id === match.params.id).name}</h4> </li> <li> <h3>ID репозитория</h3> <h4>{data.user.repositories.nodes.find((el) => el.id === match.params.id).id}</h4> </li> <a href={data.user.repositories.nodes.find((el) => el.id === match.params.id).url}> <h3>URL репозитория</h3> <h4>{data.user.repositories.nodes.find((el) => el.id === match.params.id).url}</h4> </a> <li> <h3>Дата создания репозитория</h3> <h4>{new Date(data.user.repositories.nodes.find((el) => el.id === match.params.id).createdAt).toString().split(" GMT")[0]}</h4> </li> <li> <h3>Тип репозитория</h3> <h4>{data.user.repositories.nodes.find((el) => el.id === match.params.id).isPrivate ? "Закрытый" : "Публичный"}</h4> </li> </ul> : null } /> <Route path="/" exact component={() => <section> { <ul> { data.user.repositories.nodes.map((el, i) => <Link key={i} to={"/about/" + el.id}> <Repo name={el.name} updatedAt={el.updatedAt}></Repo> </Link> ) } </ul> } </section> } /> </Switch> )} </Query> </div> </ApolloProvider> ); } } const rootElement = document.getElementById("root"); ReactDOM.render(<BrowserRouter><App /></BrowserRouter>, rootElement);<file_sep>## Add your personal GitHub token in .env, restart the development server after changing this environment variable. ## Available Scripts In the project directory, you can run: ### `npm install` ### `npm start` Runs the app in the development mode.<br /> Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
ad67ce8da86817b3ac603eb81c46f399ae8beda7
[ "JavaScript", "Markdown" ]
2
JavaScript
yerenkoff/GraphQL
4195f0b56261fba575fdffd85892eeb290aec5e4
d5df6cf7ccee269c1f4a552dc9187641b0a99e7e
refs/heads/master
<repo_name>mat-sz/WebAppSignatureExtension<file_sep>/build.ts import { resolve } from 'path'; import { removeSync, mkdirpSync, copySync } from 'fs-extra'; import { sync as spawnSync } from 'cross-spawn'; import 'colors'; const BUILD_DIR = resolve('./build'); const logStep = (step: string) => console.log(('> ' + step).blue); const buildTSSubproject = (name: string) => { logStep(name + ': Building TypeScript subproject...'); spawnSync(resolve('./node_modules/.bin/tsc'), [], { env: { ...process.env, INLINE_RUNTIME_CHUNK: 'false', GENERATE_SOURCEMAP: 'false', }, cwd: resolve('./', name), stdio: 'inherit', shell: true, }); }; const copyBuildFiles = (name: string) => { logStep(name + ': Copying build files...'); const targetDirectory = resolve(BUILD_DIR, name); mkdirpSync(targetDirectory); copySync(resolve('./', name, 'build'), targetDirectory, { overwrite: true, recursive: true, }); }; const subprojects = [{ name: 'contentscript', type: 'ts' }]; logStep('Removing build directory...'); try { removeSync(BUILD_DIR); } catch {} logStep('Creating a build directory...'); try { mkdirpSync(BUILD_DIR); } catch {} for (let subproject of subprojects) { switch (subproject.type) { case 'ts': buildTSSubproject(subproject.name); break; default: throw new Error('Unsupported subproject type: ' + subproject.type); } copyBuildFiles(subproject.name); } logStep('Copying public files...'); copySync(resolve('./public'), BUILD_DIR, { overwrite: true, recursive: true, });
0ecf588738d36b30b18c4ecb814910c9f1d44db1
[ "TypeScript" ]
1
TypeScript
mat-sz/WebAppSignatureExtension
958f17fa4bb6b3338bc45c9ad6d5e24c90c2d47a
5993d26d91da11bb4698dee89bcb7a8a897a82d3
refs/heads/master
<file_sep>// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.siyeh.ig.controlflow; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.JavaTokenType; import com.intellij.psi.PsiBinaryExpression; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiExpression; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiUtil; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.PsiReplacementUtil; import com.siyeh.ig.psiutils.CommentTracker; import com.siyeh.ig.psiutils.EquivalenceChecker; import com.siyeh.ig.psiutils.ParenthesesUtils; import com.siyeh.ig.psiutils.SideEffectChecker; import org.jetbrains.annotations.NotNull; import java.util.Arrays; /** * @author <NAME> */ public class ExpressionMayBeFactorizedInspection extends BaseInspection { @NotNull @Override protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message("if.may.be.factorized.problem.descriptor"); } @Override public BaseInspectionVisitor buildVisitor() { return new ExpressionMayBeFactorizedVisitor(null); } private static class ExpressionMayBeFactorizedVisitor extends BaseInspectionVisitor { private ExpressionMayBeFactorizedFix expressionMayBeFactorizedFix; private ExpressionMayBeFactorizedVisitor(ExpressionMayBeFactorizedFix expressionMayBeFactorizedFix) { this.expressionMayBeFactorizedFix = expressionMayBeFactorizedFix; } @Override public void visitBinaryExpression(PsiBinaryExpression expression) { super.visitBinaryExpression(expression); final IElementType tokenType = expression.getOperationTokenType(); if (!Arrays.asList(JavaTokenType.OROR, JavaTokenType.ANDAND, JavaTokenType.OR, JavaTokenType.AND).contains(tokenType)) { return; } final PsiExpression lhs = PsiUtil.skipParenthesizedExprDown(expression.getLOperand()); final PsiExpression rhs = PsiUtil.skipParenthesizedExprDown(expression.getROperand()); if (!(lhs instanceof PsiBinaryExpression) || !(rhs instanceof PsiBinaryExpression)) { return; } final PsiBinaryExpression lBinaryExpression = (PsiBinaryExpression)lhs; final PsiBinaryExpression rBinaryExpression = (PsiBinaryExpression)rhs; final IElementType lTokenType = lBinaryExpression.getOperationTokenType(); final IElementType rTokenType = rBinaryExpression.getOperationTokenType(); if (!Arrays.asList(JavaTokenType.OROR, JavaTokenType.ANDAND, JavaTokenType.OR, JavaTokenType.AND).contains(lTokenType) || !lTokenType.equals(rTokenType) || tokenType.equals(lTokenType) || lBinaryExpression.getOperands().length != 2 || rBinaryExpression.getOperands().length != 2 ) { return; } final PsiExpression llExpression = PsiUtil.skipParenthesizedExprDown(lBinaryExpression.getLOperand()); final PsiExpression lrExpression = PsiUtil.skipParenthesizedExprDown(lBinaryExpression.getROperand()); final PsiExpression rlExpression = PsiUtil.skipParenthesizedExprDown(rBinaryExpression.getLOperand()); final PsiExpression rrExpression = PsiUtil.skipParenthesizedExprDown(rBinaryExpression.getROperand()); if (llExpression == null || lrExpression == null || rlExpression == null || rrExpression == null) { return; } if (Arrays.asList(JavaTokenType.OR, JavaTokenType.AND).contains(lTokenType) || (!SideEffectChecker.mayHaveSideEffects(lrExpression) && !SideEffectChecker.mayHaveSideEffects(rlExpression) && !SideEffectChecker.mayHaveSideEffects(rrExpression))) { if (EquivalenceChecker.getCanonicalPsiEquivalence().expressionsAreEquivalent(llExpression, rlExpression) && !SideEffectChecker.mayHaveSideEffects(llExpression)) { warnOrFix(expression, lBinaryExpression, llExpression, lrExpression, rrExpression, true); } else if (EquivalenceChecker.getCanonicalPsiEquivalence().expressionsAreEquivalent(llExpression, rrExpression) && !SideEffectChecker.mayHaveSideEffects(llExpression)) { warnOrFix(expression, lBinaryExpression, llExpression, lrExpression, rlExpression, true); } else if (EquivalenceChecker.getCanonicalPsiEquivalence().expressionsAreEquivalent(lrExpression, rlExpression) && !SideEffectChecker.mayHaveSideEffects(lrExpression)) { warnOrFix(expression, lBinaryExpression, lrExpression, llExpression, rrExpression, false); } else if (EquivalenceChecker.getCanonicalPsiEquivalence().expressionsAreEquivalent(lrExpression, rrExpression) && !SideEffectChecker.mayHaveSideEffects(lrExpression)) { warnOrFix(expression, lBinaryExpression, lrExpression, llExpression, rlExpression, false); } } } private void warnOrFix(@NotNull PsiBinaryExpression visitedElement, @NotNull PsiBinaryExpression lBinaryExpression, @NotNull PsiExpression duplicateExpression, @NotNull PsiExpression thenExpression, @NotNull PsiExpression elseExpression, boolean isFactorizedExpressionFirst) { if (expressionMayBeFactorizedFix == null) { registerError(visitedElement); } else { expressionMayBeFactorizedFix.effectivelyDoFix(visitedElement, lBinaryExpression, duplicateExpression, thenExpression, elseExpression, isFactorizedExpressionFirst); } } } @Override protected InspectionGadgetsFix buildFix(Object... infos) { ExpressionMayBeFactorizedFix expressionMayBeFactorizedFix = new ExpressionMayBeFactorizedFix(); expressionMayBeFactorizedFix.expressionMayBeFactorizedVisitor = new ExpressionMayBeFactorizedVisitor(expressionMayBeFactorizedFix); return expressionMayBeFactorizedFix; } private static class ExpressionMayBeFactorizedFix extends InspectionGadgetsFix { private ExpressionMayBeFactorizedVisitor expressionMayBeFactorizedVisitor; @Override @NotNull public String getFamilyName() { return InspectionGadgetsBundle.message("if.may.be.factorized.quickfix"); } @Override protected void doFix(Project project, ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); if (!(element instanceof PsiBinaryExpression)) { return; } expressionMayBeFactorizedVisitor.visitBinaryExpression((PsiBinaryExpression)element); } private void effectivelyDoFix(@NotNull PsiBinaryExpression visitedElement, @NotNull PsiBinaryExpression lBinaryExpression, @NotNull PsiExpression duplicateExpression, @NotNull PsiExpression thenExpression, @NotNull PsiExpression elseExpression, boolean isFactorizedExpressionFirst) { CommentTracker commentTracker = new CommentTracker(); if (isFactorizedExpressionFirst) { PsiReplacementUtil.replaceExpression(visitedElement, getTextBeforeAnOperator(duplicateExpression, lBinaryExpression, commentTracker) + getTextForOperator(lBinaryExpression) + " (" + getTextBeforeAnOperator(thenExpression, visitedElement, commentTracker) + getTextForOperator(visitedElement) + getTextBeforeAnOperator(elseExpression, visitedElement, commentTracker) + ')', commentTracker); } else { PsiReplacementUtil.replaceExpression(visitedElement, '(' + getTextBeforeAnOperator(thenExpression, visitedElement, commentTracker) + getTextForOperator(visitedElement) + getTextBeforeAnOperator(elseExpression, visitedElement, commentTracker) + ") " + getTextForOperator(lBinaryExpression) + getTextBeforeAnOperator(duplicateExpression, lBinaryExpression, commentTracker), commentTracker); } } private static String getTextBeforeAnOperator(@NotNull PsiExpression expression, @NotNull PsiBinaryExpression lBinaryExpression, @NotNull CommentTracker commentTracker) { return ParenthesesUtils.getText(commentTracker.markUnchanged(expression), Arrays.asList(JavaTokenType.ANDAND, JavaTokenType.AND).contains(lBinaryExpression.getOperationTokenType()) ? ParenthesesUtils.AND_PRECEDENCE : ParenthesesUtils.OR_PRECEDENCE); } private static String getTextForOperator(@NotNull PsiBinaryExpression psiBinaryExpression) { final IElementType tokenType = psiBinaryExpression.getOperationTokenType(); if (JavaTokenType.OROR.equals(tokenType)) { return "||"; } if (JavaTokenType.ANDAND.equals(tokenType)) { return "&&"; } if (JavaTokenType.OR.equals(tokenType)) { return "|"; } if (JavaTokenType.AND.equals(tokenType)) { return "&"; } return null; } } } <file_sep>// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.progress import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.UsefulTestCase.assertInstanceOf import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.concurrency.Semaphore import junit.framework.TestCase.assertTrue import junit.framework.TestCase.fail import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Job import org.junit.Rule import org.junit.Test import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit class CancellationTest { @Rule @JvmField val application: ApplicationRule = ApplicationRule() private val TIMEOUT_MS: Long = 1000 private fun neverEndingStory(): Nothing { while (true) { ProgressManager.checkCanceled() Thread.sleep(1) } } @Test fun `job cancellation makes checkCanceled throw CE`() { val lock = Semaphore(1) val job = Job() val future = AppExecutorUtil.getAppExecutorService().submit { withJob(job) { lock.up() neverEndingStory() } } assertTrue(lock.waitFor(TIMEOUT_MS)) job.cancel() try { future.get(TIMEOUT_MS, TimeUnit.MILLISECONDS) fail("ExecutionException expected") } catch (e: ExecutionException) { assertInstanceOf(e.cause, CancellationException::class.java) } } } <file_sep>// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.refactoring.introduceParameter import com.intellij.psi.PsiParameter fun onClickCallback(psiParameter: PsiParameter): () -> Unit { return { psiParameter.navigate(true) } }
e21b771c39a419a0b9c55da356d8863ba26389ed
[ "Java", "Kotlin" ]
3
Java
cpovirk/intellij-community
30eb439398b10f1209403c6e3ab0632db6212e22
a2baf22cccfdc163c952f95d9f02f5871230f1d1
refs/heads/master
<file_sep># Deprecated This add-on is already integrated into ofxGui in the current master and will be part of the 0.10.0 release. # ofxInputField Text and number input field for openFrameworks extending ofxGui. So in contrast to ofxTextInputField it works out of the box with ofxGui (but also only there). ofxInputField can be used as an alternative to ofxSlider to define numbers more precicly or to ofxLabel to have editable labels. The mouse and keyboard controls are elaborated in detail. Check out the example with an int, float and string version ofxInputField. Dependencies ---- * ofxGui (core addon) <file_sep>#pragma once #include "ofxBaseGui.h" template<typename Type> class ofxInputField : public ofxBaseGui{ friend class ofPanel; public: ofxInputField(); ~ofxInputField(); ofxInputField(ofParameter<Type> _val, float width = defaultWidth, float height = defaultHeight); ofxInputField* setup(ofParameter<Type> _val, float width = defaultWidth, float height = defaultHeight); ofxInputField* setup(const std::string& _name, Type _val, Type _min, Type _max, float width = defaultWidth, float height = defaultHeight); ofxInputField* setup(const std::string& _name, Type _val); void setMin(Type min); Type getMin(); void setMax(Type max); Type getMax(); virtual bool mouseMoved(ofMouseEventArgs & args); virtual bool mousePressed(ofMouseEventArgs & args); virtual bool mouseDragged(ofMouseEventArgs & args); virtual bool mouseReleased(ofMouseEventArgs & args); virtual bool mouseScrolled(ofMouseEventArgs & args); void registerKeyEvents(); void unregisterKeyEvents(); virtual bool keyPressed(ofKeyEventArgs & args); virtual bool keyReleased(ofKeyEventArgs & args); template<class ListenerClass, typename ListenerMethod> void addListener(ListenerClass * listener, ListenerMethod method){ value.addListener(listener,method); } template<class ListenerClass, typename ListenerMethod> void removeListener(ListenerClass * listener, ListenerMethod method){ value.removeListener(listener,method); } Type operator=(Type v); operator const Type & (); ofAbstractParameter & getParameter(); protected: virtual void render(); ofParameter<Type> value; bool bGuiActive, bMousePressed; bool mouseInside; bool setValue(float mx, float my, bool bCheck); virtual void generateDraw(); virtual void generateText(); void valueChanged(Type & value); ofPath bg; ofVboMesh textMesh; bool bRegisteredForKeyEvents; std::string input; float inputWidth; bool bChangedInternally; void parseInput(); int insertKeystroke(const std::string & character); int insertAlphabetic(const std::string & character); int mousePressedPos; //set by mouse interaction bool hasSelectedText(); float selectStartX, selectionWidth; //calculated from select indices int selectStartPos, selectEndPos; void calculateSelectionArea(int selectIdx1, int selectIdx2); virtual void drawSelectedArea(); virtual void drawCursor(); virtual void drawFocusedBB(); virtual void drawMesh(); int pressCounter; void leaveFocus(); }; typedef ofxInputField<float> ofxFloatField; typedef ofxInputField<int> ofxIntField; typedef ofxInputField<string> ofxTextField; <file_sep>#include "ofxInputField.h" #include "ofGraphics.h" template<typename Type> ofxInputField<Type>::ofxInputField(){ bChangedInternally = false; bGuiActive = false; bMousePressed = false; mouseInside = false; bRegisteredForKeyEvents = false; mousePressedPos = -1; selectStartX = -1; selectStartPos = -1; selectEndPos = -1; pressCounter = 0; inputWidth = 0; selectionWidth = 0; } template<typename Type> ofxInputField<Type>::~ofxInputField(){ value.removeListener(this,&ofxInputField::valueChanged); } template<typename Type> ofxInputField<Type>::ofxInputField(ofParameter<Type> _val, float width, float height){ setup(_val,width,height); } template<typename Type> ofxInputField<Type>* ofxInputField<Type>::setup(ofParameter<Type> _val, float width, float height){ value.makeReferenceTo(_val); input = ofToString(value); inputWidth = getTextBoundingBox(input,0,0).width; b.x = 0; b.y = 0; b.width = width; b.height = height; bGuiActive = false; setNeedsRedraw(); value.addListener(this,&ofxInputField::valueChanged); registerMouseEvents(); registerKeyEvents(); pressCounter = 0; return this; } template<typename Type> ofxInputField<Type>* ofxInputField<Type>::setup(const std::string& _name, Type _val, Type _min, Type _max, float width, float height){ value.set(_name,_val,_min,_max); return setup(value,width,height); } template<typename Type> ofxInputField<Type>* ofxInputField<Type>::setup(const std::string& _name, Type _val){ value.set(_name,_val); return setup(value); } template<typename Type> void ofxInputField<Type>::setMin(Type min){ value.setMin(min); } template<typename Type> Type ofxInputField<Type>::getMin(){ return value.getMin(); } template<typename Type> void ofxInputField<Type>::setMax(Type max){ value.setMax(max); } template<typename Type> Type ofxInputField<Type>::getMax(){ return value.getMax(); } template<typename Type> void ofxInputField<Type>::calculateSelectionArea(int selectIdx1, int selectIdx2){ std::string preSelectStr, selectStr; if(selectIdx1 <= selectIdx2){ selectStartPos = selectIdx1; selectEndPos = selectIdx2; }else{ selectStartPos = selectIdx2; selectEndPos = selectIdx1; } float preSelectWidth = 0; if(selectStartPos > 0){ preSelectStr.assign(input,0,selectStartPos); preSelectWidth = getTextBoundingBox(preSelectStr,0,0).width; } selectStartX = b.width - textPadding - inputWidth + preSelectWidth; if(hasSelectedText()){ selectStr.assign(input,selectStartPos,selectEndPos-selectStartPos); selectionWidth = getTextBoundingBox(selectStr,0,0).width; } } template<typename Type> bool ofxInputField<Type>::mouseMoved(ofMouseEventArgs & args){ mouseInside = isGuiDrawing() && b.inside(ofPoint(args.x,args.y)); return mouseInside; } template<typename Type> bool ofxInputField<Type>::mousePressed(ofMouseEventArgs & args){ if(b.inside(args.x,args.y)){ bMousePressed = true; if(!bGuiActive){ bGuiActive = true; } float cursorX = args.x - (b.x + b.width - textPadding - inputWidth); int cursorPos = ofMap(cursorX,0,inputWidth,0,input.size(),true); mousePressedPos = cursorPos; calculateSelectionArea(cursorPos, cursorPos); pressCounter++; }else{ if(bGuiActive){ leaveFocus(); } } return false; } template<typename Type> bool ofxInputField<Type>::mouseDragged(ofMouseEventArgs & args){ if(!bGuiActive || !bMousePressed) return false; float cursorX = args.x - (b.x + b.width - textPadding - inputWidth); int cursorPos = ofMap(cursorX,0,inputWidth,0,input.size(),true); calculateSelectionArea(mousePressedPos,cursorPos); return false; } template<typename Type> bool ofxInputField<Type>::mouseReleased(ofMouseEventArgs & args){ // if(bUpdateOnEnterOnly){ // value.enableEvents(); // } if(bGuiActive){ if(pressCounter == 1 && !hasSelectedText()){ //activated panel without selecting an area => select all calculateSelectionArea(0, input.size()); } } bMousePressed = false; return false; } template<typename Type> void ofxInputField<Type>::registerKeyEvents(){ if(bRegisteredForKeyEvents == true){ return; // already registered. } bRegisteredForKeyEvents = true; ofRegisterKeyEvents(this, OF_EVENT_ORDER_BEFORE_APP); } template<typename Type> void ofxInputField<Type>::unregisterKeyEvents(){ if(bRegisteredForKeyEvents == false){ return; // not registered. } ofUnregisterKeyEvents(this, OF_EVENT_ORDER_BEFORE_APP); bRegisteredForKeyEvents = false; } template<typename Type> bool ofxInputField<Type>::keyPressed(ofKeyEventArgs & args){ if(bGuiActive && !bMousePressed){ ofLogNotice("ofxInputField::keyPressed") << args.key; int newCursorIdx = -1; if(args.key >= '0' && args.key <= '9'){ int digit = args.key - '0'; newCursorIdx = insertKeystroke(ofToString(digit)); }else if(args.key == '.' ){ newCursorIdx = insertKeystroke("."); }else if(args.key == OF_KEY_BACKSPACE || args.key == OF_KEY_DEL){ if(hasSelectedText()){ input.erase(selectStartPos,selectEndPos-selectStartPos); newCursorIdx = selectStartPos; parseInput(); }else{ int deleteIdx = -1; if(args.key == OF_KEY_BACKSPACE){ deleteIdx = selectStartPos-1; }else if(args.key == OF_KEY_DEL){ deleteIdx = selectStartPos; } //erase char if valid deleteIdx if(deleteIdx >= 0 && deleteIdx < input.size()){ input.erase(deleteIdx,1); newCursorIdx = deleteIdx; parseInput(); } } }else if(args.key == OF_KEY_LEFT){ if(hasSelectedText()){ newCursorIdx = selectStartPos; }else{ newCursorIdx = selectStartPos == 0 ? 0 : selectStartPos-1; } }else if(args.key == OF_KEY_RIGHT){ if(hasSelectedText()){ newCursorIdx = selectEndPos; }else{ newCursorIdx = selectStartPos == input.size() ? input.size() : selectStartPos+1; } }else if(args.key == OF_KEY_RETURN){ leaveFocus(); }else if(args.key >= '!' && args.key <= '~'){ newCursorIdx = insertAlphabetic(ofToString((char)args.key)); } if(newCursorIdx != -1){ //set cursor calculateSelectionArea(newCursorIdx,newCursorIdx); } return true; } return false; } template<typename Type> bool ofxInputField<Type>::keyReleased(ofKeyEventArgs & args){ return bGuiActive && !bMousePressed; } template<typename Type> int ofxInputField<Type>::insertKeystroke(const std::string & character){ if(hasSelectedText()){ input.erase(selectStartPos,selectEndPos-selectStartPos); } input.insert(selectStartPos,character); parseInput(); return selectStartPos + 1; } template<typename Type> int ofxInputField<Type>::insertAlphabetic(const std::string & character){ return -1; //cursor or selection area stay the same } template<> int ofxInputField<string>::insertAlphabetic(const std::string & character){ return insertKeystroke(character); } template<typename Type> typename std::enable_if<std::is_integral<Type>::value, Type>::type getRange(Type min, Type max, float width){ double range = max - min; range /= width*4; return std::max(range,1.0); } template<typename Type> typename std::enable_if<std::is_floating_point<Type>::value, Type>::type getRange(Type min, Type max, float width){ double range = max - min; range /= width*4; return range; } template<typename Type> bool ofxInputField<Type>::mouseScrolled(ofMouseEventArgs & args){ if(mouseInside || bGuiActive){ if(args.y>0 || args.y<0){ double range = getRange(value.getMin(),value.getMax(),b.width); Type newValue = value + ofMap(args.y,-1,1,-range, range); newValue = ofClamp(newValue,value.getMin(),value.getMax()); value = newValue; } return true; }else{ return false; } } template<> bool ofxInputField<string>::mouseScrolled(ofMouseEventArgs & args){ if(mouseInside || bGuiActive){ return true; }else{ return false; } } template<typename Type> Type ofxInputField<Type>::operator=(Type v){ value = v; return v; } template<typename Type> ofxInputField<Type>::operator const Type & (){ return value; } template<typename Type> void ofxInputField<Type>::generateDraw(){ bg.clear(); bg.setFillColor(thisBackgroundColor); bg.setFilled(true); bg.rectangle(b); generateText(); } template<typename Type> void ofxInputField<Type>::generateText(){ string valStr = input; textMesh = getTextMesh(getName(), b.x + textPadding, b.y + b.height / 2 + 4); textMesh.append(getTextMesh(valStr, b.x + b.width - textPadding - getTextBoundingBox(valStr,0,0).width, b.y + b.height / 2 + 4)); } template<typename Type> void ofxInputField<Type>::render(){ bg.draw(); if(bGuiActive){ drawFocusedBB(); if(hasSelectedText()){ drawSelectedArea(); }else{ drawCursor(); } } drawMesh(); } template<typename Type> bool ofxInputField<Type>::hasSelectedText(){ return selectStartPos != selectEndPos; } template<typename Type> void ofxInputField<Type>::drawMesh(){ ofBlendMode blendMode = ofGetStyle().blendingMode; if(blendMode!=OF_BLENDMODE_ALPHA){ ofEnableAlphaBlending(); } ofSetColor(thisTextColor); bindFontTexture(); textMesh.draw(); unbindFontTexture(); ofColor c = ofGetStyle().color; ofSetColor(c); if(blendMode!=OF_BLENDMODE_ALPHA){ ofEnableBlendMode(blendMode); } } template<typename Type> void ofxInputField<Type>::drawSelectedArea(){ ofPushStyle(); ofSetColor(thisFillColor); ofFill(); ofDrawRectangle( selectStartX+b.x, b.y+1, selectionWidth, b.height-2 ); ofPopStyle(); } template<typename Type> void ofxInputField<Type>::drawCursor(){ ofPushStyle(); ofSetColor(thisTextColor); ofDrawLine( selectStartX+b.x, b.y, selectStartX+b.x, b.y+b.height ); ofPopStyle(); } template<typename Type> void ofxInputField<Type>::drawFocusedBB(){ ofPushStyle(); ofSetColor(thisTextColor); ofDrawLine( selectStartX+b.x, b.y, selectStartX+b.x, b.y+b.height ); ofPopStyle(); } template<typename Type> bool ofxInputField<Type>::setValue(float mx, float my, bool bCheck){ return false; } template<typename Type> ofAbstractParameter & ofxInputField<Type>::getParameter(){ return value; } template<typename Type> void ofxInputField<Type>::parseInput(){ bChangedInternally = true; Type tmpVal = ofToFloat(input); if(tmpVal < getMin()){ tmpVal = getMin(); }else if(tmpVal > getMax()){ tmpVal = getMax(); } value = tmpVal; } template<> void ofxInputField<string>::parseInput(){ bChangedInternally = true; value = input; } template<typename Type> void ofxInputField<Type>::valueChanged(Type & value){ if(bChangedInternally){ bChangedInternally = false; inputWidth = getTextBoundingBox(input,0,0).width; }else{ input = ofToString(value); inputWidth = getTextBoundingBox(input,0,0).width; if(bGuiActive){ int cursorPos = input.size(); calculateSelectionArea(cursorPos,cursorPos); } } setNeedsRedraw(); } template<typename Type> void ofxInputField<Type>::leaveFocus(){ bGuiActive = false; pressCounter = 0; input = ofToString(value); inputWidth = getTextBoundingBox(input,0,0).width; setNeedsRedraw(); } template class ofxInputField<int8_t>; template class ofxInputField<uint8_t>; template class ofxInputField<int16_t>; template class ofxInputField<uint16_t>; template class ofxInputField<int32_t>; template class ofxInputField<uint32_t>; template class ofxInputField<int64_t>; template class ofxInputField<uint64_t>; template class ofxInputField<float>; template class ofxInputField<double>; template class ofxInputField<string>; <file_sep>#pragma once #include "ofMain.h" #include "ofxGui.h" #include "ofxInputField.h" class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void exit(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); void circleResolutionChanged(int & circleResolution); bool bHide; ofxFloatField radius; ofxIntField circleResolution; ofxTextField textField; ofxColorSlider color; ofxVec2Slider center; ofxToggle filled; ofxButton twoCircles; ofxPanel gui; };
2d425892a82a980e4c0bb427a7ba1489fb5713fa
[ "Markdown", "C++" ]
4
Markdown
fx-lange/ofxInputField
c4f16b64c85bdae91fa157a7866c202488d450c2
19a5002e5e0dbac4632c4ce5f67c18f94850abe3
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; namespace PInvokeFinder { public class Program { static List<string> paths; static List<string> pinvokes; public static void Main(string[] args) { ShowHeader(); if (!ParseArguments(args)) { ShowUsage(); return; } pinvokes = new List<string>(); foreach (var path in paths) { Console.WriteLine($"Analyzing {path}..."); AnalyzePath(path); } Console.WriteLine(); Console.WriteLine($"Done. Found {pinvokes.Count} p/invokes"); Console.WriteLine(); foreach (var m in pinvokes) { Console.WriteLine(m); } } private static void AnalyzePath(string path) { try { using (var stream = File.OpenRead(path)) using (var peFile = new PEReader(stream)) { var mr = peFile.GetMetadataReader(); foreach (var methodHandle in mr.MethodDefinitions) { var method = mr.GetMethodDefinition(methodHandle); if (((method.Attributes & MethodAttributes.PinvokeImpl) == MethodAttributes.PinvokeImpl) || ((method.Attributes & MethodAttributes.UnmanagedExport) == MethodAttributes.UnmanagedExport)) { pinvokes.Add($"[{path}]\t{GetMethodName(method, mr)}"); } } } } catch (Exception) { Console.WriteLine($"WARNING: {path} does not appear to be a valid managed assembly"); } } private static string GetMethodName(MethodDefinition method, MetadataReader mr) { var nameComponents = new List<string>(); if (method.Name != null) { nameComponents.Add(mr.GetString(method.Name)); } var declTypeHandle = method.GetDeclaringType(); TypeDefinition declType = mr.GetTypeDefinition(declTypeHandle); while (!declTypeHandle.IsNil) { declType = mr.GetTypeDefinition(declTypeHandle); nameComponents.Add(mr.GetString(declType.Name)); declTypeHandle = declType.GetDeclaringType(); } if (declType.Namespace!= null) nameComponents.Add(mr.GetString(declType.Namespace)); return string.Join(".", nameComponents.Where(s => !string.IsNullOrWhiteSpace(s)).Reverse()); } private static bool ParseArguments(string[] args) { paths = new List<string>(); if (args.Length < 1) { return false; } foreach (string a in args) { if (File.Exists(a)) { paths.Add(a); } else if (Directory.Exists(a)) { paths.AddRange(Directory.GetFiles(a, "*.dll", SearchOption.AllDirectories)); paths.AddRange(Directory.GetFiles(a, "*.exe", SearchOption.AllDirectories)); } else { Console.WriteLine($"WARNING: Path not found {a}"); } } if (paths.Count < 1) { Console.WriteLine("ERROR: No files found to analyze"); return false; } return true; } private static void ShowUsage() { Console.WriteLine("Usage: PInvokeFinder.exe <path to binary or directory>"); } private static void ShowHeader() { Console.WriteLine("-------------------"); Console.WriteLine("- P/Invoke Finder -"); Console.WriteLine("-------------------"); Console.WriteLine(); } } }
a3b73785e94d4e1599200be7d28509d17eccc1a0
[ "C#" ]
1
C#
PlumpMath/PInvokeFinder
be99e99b3836e2657274584b13b12fc02a461a71
7a08b48908671d028d194302d14c44f0e3d70593
refs/heads/master
<repo_name>sandygrand/CSV_TO_SchemaTable<file_sep>/app/src/main/java/sandy/csvproject/MainActivity.java package sandy.csvproject; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sendcsvdata(); } public List<CsvSample> csvSamples=new ArrayList<>(); public void sendcsvdata(){ InputStream ips= getResources().openRawResource(R.raw.file); BufferedReader reader=new BufferedReader(new InputStreamReader(ips, Charset.forName("UTF-8"))); String rline=""; try { while((rline=reader.readLine())!=null){ Log.d("MyActivity","Line :"+rline); String[] tokens=rline.split(","); CsvSample sample=new CsvSample(); sample.setId(tokens[0]); sample.setName(tokens[1]); sample.setNum(Long.parseLong(tokens[2])); sample.setAddress(tokens[3]); csvSamples.add(sample); Log.d("MyActivity","Created "+sample); Log.d("MyActivity","Id is --------- "+sample.getId()); Log.d("MyActivity","Name is --------- "+sample.getName()); Log.d("MyActivity","Number is --------- "+sample.getNum()); Log.d("MyActivity","Address is --------- "+sample.getAddress()); String id=sample.getId(); String name=sample.getName(); long num=sample.getNum(); String address=sample.getAddress(); BackgroundWorker bw=new BackgroundWorker(this); bw.execute(sample); } } catch (IOException e) { Log.wtf("MyActivity","Error reading line from File"+rline,e); e.printStackTrace(); } } }<file_sep>/README.md # CSV_TO_SchemaTable This API reads the contents of the CSV file in /raw folder and then parses it for individual data. It then sends it to server side script via an Asynchronous Background class 'BackgroundWorker'. That class sends the data in key-value pairs to the PHP file on server. The PHP file then performs the insert operation on to the schema table. Note :The PHP files named 'send.php','conn1.php' are placed in the root directory here but they are on the server in real time. <file_sep>/send.php <?php require "conn1.php"; $user_id = $_POST["id"]; $user_name= $_POST["name"]; $user_addr = $_POST["addr"]; $user_num= $_POST["num"]; $mysql_qry = "insert into csvdata values ('$user_id','$user_name','$user_num','$user_addr')"; $result = mysqli_query($conn ,$mysql_qry); echo "Entry Success"; ?>
85e288c66513c024cc185723c58075c3a763552f
[ "Markdown", "Java", "PHP" ]
3
Java
sandygrand/CSV_TO_SchemaTable
bd3578d38a2657af85ebc4f33c2ba307bd4b9b57
3f9dfc6126e4addf00fd126ef202fdd9b35e2380
refs/heads/master
<file_sep>#include <bits/stdc++.h> using namespace std; bool is_rev (string s, string r) { for (int i = 0;i<s.length();i++) { if (s[i] != r[r.length() - 1 - i]) { return false; } } return true; } bool is_palin (string s) { for (int i = 0;i<s.length();i++) { if (s[i] != s[s.length()-1-i]) { return false; } } return true; } int main () { string s; while(getline(cin,s)) { bool palin, reverse; string rs = ""; for (int i = 0;i<s.length();i++) { if ( s[i] == 'A' || s[i] == 'H' || s[i] == 'I' || s[i] == 'M' || s[i] == 'O' || s[i] == 'T' || s[i] == 'U' || s[i] == 'V' || s[i] == 'W' || s[i] == 'X' || s[i] == 'Y' || s[i] == '1' || s[i] == '8' ) { rs += s[i]; } else if (s[i] == 'E') { rs += '3'; } else if (s[i] == 'J') { rs += 'L'; } else if (s[i] == 'L') { rs += 'J'; } else if (s[i] == 'S') { rs += '2'; } else if (s[i] == 'Z') { rs += '5'; } else if (s[i] == '2') { rs += 'S'; } else if (s[i] == '3') { rs += 'E'; } else if (s[i] == '5') { rs += 'Z'; } else { rs += '-'; } } reverse = is_rev(s,rs); palin = is_palin(s); if (!reverse && !palin) { cout<<s<<" -- is not a palindrome."<<endl; } else if (!reverse && palin) { cout<<s<<" -- is a regular palindrome."<<endl; } else if (reverse && !palin) { cout<<s<<" -- is a mirrored string."<<endl; } else if (reverse && palin) { cout<<s<<" -- is a mirrored palindrome."<<endl; } cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; map <string,int> Arr; string s; for (int i=0;i<n;i++) { cin>>s; if (Arr.find(s)!= Arr.end()) { Arr[s]++; } else { Arr[s] = 1; } } string result; int max = -1; for (map <string, int> :: iterator it = Arr.begin(); it != Arr.end(); it++) { if (it -> second > max) { max = it -> second; result = it -> first; } } cout<<result<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int dist(pair< int, int> x, pair <int, int> y) { return (abs(x.first - y.first) + abs(x.second - y.second)); } int main (){ int tests; cin>>tests; while (tests--) { pair <int, int> villagers_pos; pair <int, int> don_pos; cin >> villagers_pos.first >> villagers_pos.second; cin >> don_pos.first >> don_pos.second; int don_steps; int villagers_steps; cin >> don_steps; vector <pair<int, int> > don(don_steps+1); don[0] = don_pos; for (int i = 1; i < don_steps + 1; i++) { cin >> don[i].first >> don[i].second; } cin >> villagers_steps; vector <pair<int, int> > villagers(villagers_steps + 1); villagers[0] = villagers_pos; for (int i = 1; i < villagers_steps + 1; i++) { cin >> villagers[i].first >> villagers[i].second; } int i = 0; int j = 0; bool flag = true; while(j < don_steps && i < villagers_steps) { if (don[j] == don[j+1]) { j+= 1; continue; } if (villagers[i] == villagers[i+1]) { i += 1; continue; } int collision_dist = dist(villagers[i], don[j]); if (collision_dist % 2 == 1) { i += 1; j += 1; continue; } int steps = min(dist(villagers[i], villagers[i+1]), min(dist(don[j], don[j+1]), collision_dist/2)); if (villagers[i].first > villagers[i+1].first) { villagers[i].first -= steps; } else if (villagers[i].first < villagers[i+1].first) { villagers[i].first += steps; } else if (villagers[i].second > villagers[i+1].second) { villagers[i].second -= steps; } else if (villagers[i].second < villagers[i+1].second) { villagers[i].second += steps; } if (don[j].first > don[j+1].first) { don[j].first -= steps; } else if (don[j].first < don[j+1].first) { don[j].first += steps; } else if (don[j].second > don[j+1].second) { don[j].second -= steps; } else if (don[j].second < don[j+1].second) { don[j].second += steps; } if (don[j] == villagers[i]) { if (don[j] == don[don_steps]) { break; } flag = false; break; } } if (flag) cout << "Yes" << endl; else cout << "No" << endl; if (tests > 0) cout << endl; } return 0; } <file_sep>#include<stdio.h> int main () { long long int n,i,m,j; scanf("%lld",&n); for (i=0;i<n;i++) { long long int sum=0; long long int t; scanf("%lld",&m); for (j=0;j<m;j++) { scanf("%lld",&t); sum+=t%m; } if (sum%m==0) printf("YES\n"); else printf("NO\n"); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> arr(n-1); for (int i=0;i<n-1;i++) { cin>>arr[i]; } int a,b; cin>>a>>b; int sum = 0; for (int i = a-1;i<b-1;i++) { sum+=arr[i]; } cout<<sum<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { string s; cin>>s; cout<<25*(s.length() + 1) + 1<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { int n; cin>>n; if (n>=0) { cout<<n<<endl; } else { n = (-1)*n; int a = n%10; int b = (n/10)%10; n/=10; n -= (n)%10; n+=min(a,b); if (n>0) cout<<"-"<<n<<endl; else cout<<"0"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool valid(int i, int j) { if (i >= 0 && i<7 && j >= 0 && j<7) { return true; } else { return false; } } int main () { int n; cin>>n; cout<<"HI Q OUTPUT"<<endl; while(n--) { vector<int> input; int ele; cin>>ele; while(ele!=0) { input.push_back(ele); cin>>ele; } int res = 0; if (input.size() == 0 ) { cout<<res<<endl; continue; } int arr[7][7] = { { 0, 0, 1, 2, 3, 0, 0}, { 0, 0, 4, 5, 6, 0, 0}, { 7, 8, 9,10,11,12,13}, {14,15,16,17,18,19,20}, {21,22,23,24,25,26,27}, { 0, 0,28,29,30, 0, 0}, { 0, 0,31,32,33, 0, 0} }; int brr[7][7]; map <int, pair<int,int> > dic; for (int i = 0;i<7;i++) { for (int j = 0;j<7;j++) { if (arr[i][j]!=0) dic[arr[i][j]] = make_pair(i,j); } } for (int i = 0;i<7;i++) { for (int j = 0;j<7;j++) { brr[i][j] = 0; } } for (int i = 0;i<input.size();i++) { brr[dic[input[i]].first][dic[input[i]].second] = 1; } while (1) { vector <pair<int,int> > moves; map <pair<int,int>,int > temp; for (int a = 0;a<input.size();a++) { int t = input[a]; int i = dic[t].first; int j = dic[t].second; if (valid(i-1,j) && arr[i-1][j] != 0 && brr[i-1][j] == 1 && valid(i-2,j) && arr[i-2][j] != 0 && brr[i-2][j] == 0) { moves.push_back(make_pair(arr[i-2][j],t)); temp[make_pair(arr[i-2][j],t)] = arr[i-1][j]; } if (valid(i+1,j) && arr[i+1][j] != 0 && brr[i+1][j] == 1 && valid(i+2,j) && arr[i+2][j] != 0 && brr[i+2][j] == 0) { moves.push_back(make_pair(arr[i+2][j],t)); temp[make_pair(arr[i+2][j],t)] = arr[i+1][j]; } if (valid(i,j+1) && arr[i][j+1] != 0 && brr[i][j+1] == 1 && valid(i,j+2) && arr[i][j+2] != 0 && brr[i][j+2] == 0) { moves.push_back(make_pair(arr[i][j+2],t)); temp[make_pair(arr[i][j+2],t)] = arr[i][j+1]; } if (valid(i,j-1) && arr[i][j-1] != 0 && brr[i][j-1] == 1 && valid(i,j-2) && arr[i][j-2] != 0 && brr[i][j-2] == 0) { moves.push_back(make_pair(arr[i][j-2],t)); temp[make_pair(arr[i][j-2],t)] = arr[i][j-1]; } } if (moves.size() == 0) { for (int i = 0;i<input.size();i++) { res += input[i]; } break; } sort(moves.rbegin(), moves.rend()); int target = moves[0].first; int source = moves[0].second; int intermediate = temp[moves[0]]; input.erase(find(input.begin(), input.end(), source)); input.erase(find(input.begin(), input.end(), intermediate)); input.push_back(target); brr[dic[target].first][dic[target].second] = 1; brr[dic[intermediate].first][dic[intermediate].second] = 0; brr[dic[source].first][dic[source].second] = 0; } cout<<res<<endl; } cout<<"END OF OUTPUT"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; int l,h,w; int cnt = 0; for (int i = 0; i < n; i++) { ISTREAM>>l>>h>>w; cnt++; if (l<=20 && w<= 20 && h<= 20) { cout<<"Case "<<cnt<<": good"<<endl; } else cout<<"Case "<<cnt<<": bad"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; for (int i=0; i<n;i++ ) { int a,b; cin>>a>>b; cout<<(a/3)*(b/3)<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int k; string s; cin>>s>>k; vector <int> A(26); int max = -1; for(int i=0;i<26;i++) { cin>>A[i]; if (A[i]>max) max = A[i]; } int res = 0; int last; for (int i=0;i<s.length();i++) { int check = s[i] - 97; res+=(i+1)*A[check]; last = i; } for (int i=0;i<k;i++) { res+= (last+1)*max; last++; } cout<<res+ k*max<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> A(12); for (int i=0;i<12;i++) { cin>>A[i]; } sort(A.begin(),A.end()); int sum = 0; int i = 11; int cnt = 0; while (i>=0 && sum<n) { sum += A[i]; i--; cnt++; } if (sum <n) cout<<"-1"<<endl; else cout<<cnt<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int x1,y1; cin>>x1>>y1; int x2,y2; cin>>x2>>y2; printf("%.4f\n",sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) )); return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> arr(n); for (int i = 0; i<n; i++ ) { cin>>arr[i]; } int s,t; cin>>s>>t; if (s>t) { s = s+t; t = s - t; s = s - t; } int sum1=0,sum2=0; for (int i = 0; i < n; i++) { if (i>=s-1 && i<t-1) { sum1 += arr[i]; } else { sum2 += arr[i]; } } cout<<min(sum1,sum2)<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { vector <int> counts(1000001, -1); int i = 1; while (i < 1000001) { int cnt = 0; unsigned int bck = i; while (bck != 1) { if (bck < 1000001 && counts[bck] != -1) { cnt += counts[bck]; bck = 1; break; } if (bck % 2 == 1) { bck = 3*bck + 1; } else { bck /= 2; } cnt += 1; } counts[i] = cnt; i += 1; } int n, t; while (cin >> n >> t) { int maxi = -1; for (i = min(n, t); i <= max(n, t); i++) { maxi = max(maxi, counts[i]); } cout << n << " " << t << " " << maxi + 1 << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; n+= (int)(n%2 == 0); for (int i = n; i < n+12; i+=2) { cout<<i<<endl; } return 0; }<file_sep>#include<iostream> #include<vector> using namespace std; int main (void) { int n,k; cin>>n>>k; int t=n/k; int i; vector <int> co; int temp; for (i=0;i<n;i++) { cin>>temp; co.push_back(temp); } int j; int minsum=99999999; int index=1; for (i=0;i<k;i++) { int sum=co[i]; for (j=i+k;j<n;j+=k){ sum+=co[j]; } if (sum<minsum) {minsum=sum;index = i+1;} } cout<<index<<endl; } <file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int main () { int t; cin >> t; while (t--) { vector <pair <int, int> > waiting2(20, make_pair(0,0)); vector <pair <int, int> > waiting3(20, make_pair(0,0)); vector <int> waiting; vector <int> go_out; map <int, int> res; int n; cin >> n; while (n != 99) { waiting2[n-1] = make_pair(n-1, 1); waiting.push_back(n); cin >> n; } string inp; getline(cin, inp); getline(cin, inp); while(inp != "") { ss.str(""); ss.clear(); ss.str(inp); ss >> n; go_out.push_back(n); getline(cin, inp); } for (auto i:go_out) { int bck = i; int ctr = 0; while (waiting2[bck - 1].second == 0 && ctr < 20) { bck -= 1; if (bck < 1) bck+= 20; ctr += 1; } waiting2[bck - 1].second = 0; res[waiting2[bck-1].first] = i; int d = i - bck; if (d < 0) d += 20; for (int j = 0; j < 20; j++) { waiting3[j].first = waiting2[j].first; waiting3[j].second = waiting2[j].second; } for (int j = 0; j < waiting2.size(); j++) { int temp = j + d; temp %= 20; waiting2[temp].second = waiting3[j].second; waiting2[temp].first = waiting3[j].first; } } for (auto i: waiting) { if (res.find(i-1) == res.end()) { cout << "Original position " << i << " did not park" << endl; } else { cout << "Original position " << i << " parked in " << res[i-1] <<endl; } } if (t > 0 ) cout<< endl; } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; string s; cin >>s; while (k--) { for (int i=0;i<n-1; i++ ) { if (s[i] == 'B' && s[i+1] =='G') { s[i] = 'G'; s[i+1] = 'B'; i++; } } } cout<<s<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int temp; for (int i=0;i<10;i++) { cin>>temp; if (temp<=0) temp = 1; cout<<"X["<<i<<"] = "<<temp<<endl; } return 0; }<file_sep>#include<iostream> #include<vector> using namespace std; int main (void) { int n, k; int i; cin>>n>>k; vector<int> ans; for ( i=1;i<n+1;i++) { ans.push_back(i); } if (k==n) { cout<<-1<<endl; return 0; } if (k==1 && n==1) { cout<<-1<<endl; return 0; } k=n-k; if (n==1||k==1) { for (i=0;i<n;i++) { cout<<ans[i]<<' '; } cout<<endl; return 0; } if (k%2==0){ for (i=0;i<k;i+=2) { ans[i]=ans[i]+ans[i+1]; ans[i+1]=ans[i]-ans[i+1]; ans[i]=ans[i]-ans[i+1]; } } if (k%2==1 && k>1){ int temp=ans[0]; ans[0]=ans[2]; ans[2]=ans[1]; ans[1]=temp; for (i=3;i<k;i+=2) { ans[i]=ans[i]+ans[i+1]; ans[i+1]=ans[i]-ans[i+1]; ans[i]=ans[i]-ans[i+1]; } } for (i=0;i<n;i++) { cout<<ans[i]<<' '; } cout<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; bool valid(int i,int j) { if (i >= 0 && i<=7 && j >= 0 && j<= 7) { return true; } else { return false; } } int main () { int n; cin>>n; for (int ii = 0;ii<n;ii++) { vector <string> board(8); char player[2]; player[0] = 'W'; player[1] = 'B'; char pl; char move; for (int i = 0; i < 8; i++) { cin>>board[i]; } int p; cin>>pl; if (pl == 'W') { p = 0; } else { p = 1; } while (1) { cin>>move; vector <pair <int,int> > avlbl_moves; if (move == 'Q') { for (int i = 0; i < 8; i++) { cout<<board[i]<<endl; } break; } for (int i = 0;i<8;i++) { for (int j = 0;j<8;j++) { bool success = false; if (board[i][j] == '-') { for (int xdel = -1; xdel < 2; xdel++) { for (int ydel= -1; ydel<2; ydel++) { if (xdel == 0 && ydel == 0) continue; if (success == false && valid(i+xdel,j+ydel) && board[i+xdel][j+ydel] == player[p^1]) { int i1 = i + 2*xdel; int j1 = j + 2*ydel; while (valid(i1,j1) && board[i1][j1]!='-') { if (board[i1][j1] == player[p]) { success = true; break; } i1 += xdel; j1 += ydel; } } } } } if (success == true) { avlbl_moves.push_back(make_pair(i+1,j+1)); } } } if (move == 'L') { for (int i = 0;i<avlbl_moves.size();i++) { cout<<"("<<avlbl_moves[i].first<<","<<avlbl_moves[i].second<<")"; if (i < avlbl_moves.size()-1) { cout<<" "; } } if (avlbl_moves.size() == 0) { cout<<"No legal move."; } cout<<endl; } else if (move == 'M') { int x,y,num; cin>>num; x = num/10 - 1; y = num%10 - 1; bool flag = false; for (int i = 0;i<avlbl_moves.size();i++) { if (x+1 == avlbl_moves[i].first && y+1 == avlbl_moves[i].second) flag = true; } if (flag == false) { p^=1; } vector <pair<int,int> > pos; for (int xdel = -1;xdel<2;xdel++) { for(int ydel = -1;ydel <2;ydel++) { x = num/10 - 1; y = num%10 - 1; if (valid(x+xdel,y+ydel) && board[x+xdel][y+ydel] == player[p^1]) { pos.push_back(make_pair(x,y)); x += xdel; y += ydel; while (valid(x,y) && board[x][y] == player[p^1]) { pos.push_back(make_pair(x,y)); x += xdel; y += ydel; } if (valid(x,y) && board[x][y] == player[p]) { for (int i=0;i<pos.size();i++) { board[pos[i].first][pos[i].second] = player[p]; } } pos.clear(); } } } int white = 0; int black = 0; for (int i=0;i<8;i++) { for (int j=0;j<8;j++) { if (board[i][j] == 'W') white++; else if (board[i][j] == 'B') black++; } } printf("Black - %2d White - %2d\n",black,white); p^=1; } else if (move == 'P') { for (int i = 0;i<8;i++) { cout<<board[i]<<endl; } } } if (ii < n-1) { cout<<endl; } board.clear(); } return 0; }<file_sep>#include<iostream> using namespace std; int main(void) { int n; int i; cin>>n; int a,b,c,d; int flag=0; for (i=0;i<4;i++) { cin>>a>>b>>c>>d; if (a+c<=n) { cout<<i+1<<" "<<a<<" "<<n-a<<endl; flag=1; break; } else if (a+d<=n) { cout<<i+1<<" "<<a<<" "<<n-a<<endl; flag=1; break; } else if (b+d<=n) { cout<<i+1<<" "<<b<<" "<<n-b<<endl; flag=1; break; } else if(b+c<=n) { cout<<i+1<<" "<<b<<" "<<n-b<<endl; flag=1; break; } } if (flag==0) cout<<"-1"<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int main() { string inp; getline(cin, inp); while (inp != "*") { ss.str(""); ss.clear(); ss.str(inp); vector <string> measure; string ele; getline(ss, ele, '/'); int cnt = 0; while(getline(ss, ele, '/')) { int scr = 0; for (int i = 0;i < ele.length();i++) { if (ele[i] == 'W') { scr += 64; } else if (ele[i] == 'H') { scr += 32; } else if (ele[i] == 'Q') { scr += 16; } else if (ele[i] == 'E') { scr += 8; } else if (ele[i] == 'S') { scr += 4; } else if (ele[i] == 'T') { scr += 2; } else if (ele[i] == 'X') { scr += 1; } if (scr > 64) break; } if (scr == 64) { cnt += 1; } } cout<<cnt<<endl; getline(cin, inp); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int m,n; cin>>m>>n; if (min(m,n)%2 == 1) cout<<"Akshat\n"; else cout<<"Malvika\n"; return 0; } <file_sep>#/usr/bin/python def fibo_gen(maxi=4000000): a,b=0,1 while(a<maxi): yield a a,b=b,a+b sig=0 for i in fibo_gen(): if i%2==0: sig+=i print sig <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n; cin>>n; vector<pair<int,int> > students(n); int maxi = -1*(INT_MAX); int ele; vector <int> elements(n); for (int i = 0;i<n;i++) { cin>>ele; maxi = max(ele,maxi); students[i].first = maxi; students[i].second = ele; } int mini = INT_MAX; for (int i = n-1;i>=0;i--) { mini = min(students[i].second,mini); students[i].second = mini; } int max_diff = -1*INT_MAX; for (int i = 0;i<n-1;i++) { max_diff = max(max_diff,students[i].first - students[i+1].second); } cout<<max_diff<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } vector <int> factors; for (int i=1;i*i<=n;i++) { if (n%i == 0) { factors.push_back(i); if (i<n/i) factors.push_back(n/i); } } sort(factors.begin(),factors.end()); int maxi = -2147483646; for (int i=0;i<factors.size();i++) { if (n/factors[i] <3) { continue; } // cout<<"trying: "<<factors[i]<<endl; for (int j = 0; j<factors[i];j++) { // cout<<"from index: "<<j<<endl; int sum = 0; for (int k=j; k<n;k+=factors[i]) { sum += Arr[k]; } // cout<<"sum is:"<<sum<<endl; if (sum>= maxi) maxi = sum; } } cout<<maxi<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { while (1) { int n; cin>>n; if (n==0) break; string s; cin>>s; int flag = 0; int ind = -1; int mini = INT_MAX; for (int i = 0; i < n; i++) { if (s[i] == 'R') { ind = i; flag =1; } else if (s[i] == 'D' && flag == 1) { mini = min(mini,i - ind); flag = 0; } else if (s[i] == 'Z') { flag = 2; break; } } ind = -1; flag = 0; for (int i = 0; i < n; i++) { if (s[i] == 'D') { ind = i; flag =1; } else if (s[i] == 'R' && flag == 1) { mini = min(mini,i - ind); flag = 0; } else if (s[i] == 'Z') { flag = 2; break; } } if (flag == 2) cout<<0<<endl; else cout<<mini<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,b,n; cin>>a>>b>>n; while ( true ) { if (n == 0) { cout <<"1"; break; } n -= __gcd(a,n); if (n == 0) { cout <<"0"; break; } n -= __gcd(b,n); } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <long long int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } long long int beg = Arr[n-1]/2 + (int)(Arr[n-1]%2 != 0); for (int i = n-2;i>=0;i--) { beg = (Arr[i] + beg)/2 + (int)((Arr[i] + beg)%2!= 0); } cout<<beg<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int s1,s2,s3,s4; cin>>s1>>s2>>s3>>s4; set <int> test; test.insert(s1); test.insert(s2); test.insert(s3); test.insert(s4); cout<<4 - test.size()<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int compare(string a,string b) { for (int i = 0; i < min(a.length(),b.length()); ++i) { if (a[i]<b[i]) { return -1; } else if (a[i]>b[i]) { return 1; } } if (a.length() > b.length() ) { return 1; } else { return -1; } } int main() { int n; cin>>n; vector < pair <string,string> > names(n); vector <string> res; string a,b; for (int i=0;i<n;i++) { cin>>a>>b; if (compare(a,b)>0) { names[i].first = b; names[i].second = a; } else { names[i].first = a; names[i].second = b; } } vector <int> qry(n); for (int i=0;i<n;i++) { cin>>qry[i]; qry[i]-=1; } res.push_back(names[qry[0]].first); // cout<<res[0]<<endl; for (int i=1;i<n;i++) { if (compare(names[qry[i]].first,res[i-1])>0) { res.push_back(names[qry[i]].first); } else if (compare(names[qry[i]].second,res[i-1])>0) { res.push_back(names[qry[i]].second); } else { cout<<"NO"<<endl; return 0; } } cout<<"YES"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; int primes[] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53}; cin>>n>>m; for (int i=0;;i++) { if (primes[i] == n && primes[i+1]!= m) { cout<<"NO"<<endl; return 0; } else if (primes[i] == n && primes[i+1]== m) { cout<<"YES"<<endl; return 0; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int ano = n/365; int mo = (n%365)/30; int day = (n%365)%30; cout<<ano<<" ano(s)"<<endl; cout<<mo<<" mes(es)"<<endl; cout<<day<<" dia(s)"<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k,l,c,d,p,nl,np; cin>>n>>k>>l>>c>>d>>p>>nl>>np; int drink = (k*l)/(n*nl); int lemon = (c*d)/n; int salt = p/(n*np); cout<<min(min(drink,lemon),salt)<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int tt; cin>>tt; while (tt--) { int n,t,m; cin>>n>>t>>m; queue <pair<int,int> > left; queue <pair<int,int> > right; int ele; string dir; int ind = 0; for (int i = 0;i<m;i++) { cin>>ele>>dir; if (dir == "left") { left.push(make_pair(ind,ele)); ind++; } else if (dir == "right") { right.push(make_pair(ind,ele)); ind++; } } left.push(make_pair(ind++,99999999)); right.push(make_pair(ind++,99999999)); int tim = 0; int flag = 0; vector <pair<int,int> > res; while (left.size() > 1 || right.size() > 1) { pair <int,int> temp1 = left.front(); pair <int,int> temp2 = right.front(); // cout<<"time is: "<<tim<<endl; if (flag == 0) { if (left.size() == 1 || (temp1.second > temp2.second && temp1.second > tim) ) { tim = max(tim,temp2.second); tim += t; flag ^= 1; } else { tim = max(tim,temp1.second); int count = 0; while (left.size()!=1 && temp1.second <= tim ) { left.pop(); count++; res.push_back(make_pair(temp1.first,tim+t)); temp1 = left.front(); if (count == n) { break; } } tim += t; flag ^= 1; } } else if (flag == 1) { if (right.size() == 1 || (temp2.second > temp1.second && temp2.second > tim) ) { tim = max(tim,temp1.second); tim += t; flag ^= 1; } else { tim = max(tim,temp2.second); int count = 0; while (right.size() != 1 && temp2.second <= tim ) { right.pop(); count++; res.push_back(make_pair(temp2.first,tim+t)); temp2 = right.front(); if (count == n) { break; } } tim += t; flag ^= 1; } } } sort(res.begin(), res.end()); for (int i = 0;i<res.size();i++) { cout<<res[i].second<<endl; } if (tt > 0) { cout<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool is_leap(int y) { if (y % 400 == 0) return true; if (y % 100 == 0) return false; if (y % 4 == 0) return true; return false; } int main (){ int t; cin>>t; map <string, int> month_to_i{{"January", 0},{"February", 1}, {"March", 2}, {"April", 3}, {"May", 4}, {"June", 5}, {"July", 6}, {"August", 7}, {"September", 8}, {"October", 9}, {"November", 10}, {"December", 11}}; int idx = 0; while(t--) { cout<<"Case "<<++idx<<": "; string month1; string month2; char c; int day1; int day2; int year1; int year2; cin >> month1 >> day1 >> c >> year1; cin >> month2 >> day2 >> c >> year2; int m1 = month_to_i[month1]; int m2 = month_to_i[month2]; int t1 = day1 + m1 * 30; int t2 = day2 + m2 * 30; int leaps = 0; if (year1 == year2) { if (is_leap(year1) && t1 < 60 && t2 > 58) { leaps += 1; } } if (year1 < year2) { if (is_leap(year1) && t1 < 60) { leaps += 1; } if (is_leap(year2) && t2 > 58) { leaps += 1; } } year1 += 1; year2 -= 1; while (year1 <= year2 && (year1 + 1) % 400 != 0) { if (is_leap(year1)) { leaps += 1; } year1 += 1; } while (year2 > year1 && (year2 - 1) % 400 != 0) { if (is_leap(year2)) { leaps += 1; } year2 -= 1; } if (year2 - year1 - 2 == 0) { leaps += 1; } if (year2 - year1 - 2>= 400){ leaps += ((year2 - year1 - 2)/400)*97; leaps += 1; } cout<<leaps<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int i=0; int count = 0; for (;i<s.length();) { char t = s[i]; int t2 = 0; while (s[i] == t && t2<5) { i++; t2++; } count++; } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; cin>>n; int arr[10][10]; for (int i = 0 ;i<n;i++) { for (int j = 0;j<n;j++) { if (i == 0 || j == 0 ) { arr[i][j] = 1; } else { arr[i][j] = arr[i-1][j] + arr[i][j-1]; } } } cout<<arr[n-1][n-1]<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { map <string, string> di; map <string, int> di_cnt; string s; cin >> s; while(s != "#") { string r = ""; vector <char> temp; for (int i = 0; i < s.length(); i++) { if (s[i] >= 97) temp.push_back(s[i] - 32); else temp.push_back(s[i]); } sort(temp.begin(), temp.end()); for (auto i:temp) { r += i; } di[r] = s; if (di_cnt.find(r) != di_cnt.end()) { di_cnt[r] += 1; } else { di_cnt[r] = 1; } cin >> s; } vector <string > res; for (auto i:di_cnt) { if (i.second == 1) { res.push_back(di[i.first]); } } sort(res.begin(), res.end()); for (auto i:res) { cout << i << endl; } return 0; } <file_sep>#include<stdio.h> int main() { int n,i,j,m; scanf("%d",&n); for (i=0;i<n;i++) { scanf("%d",&m); int men[m]; int women[m]; int menh[11]={0}; int womenh[11]={0}; for (j=0;j<m;j++) { scanf("%d",&men[j]); menh[men[j]]++; } for (j=0;j<m;j++) { scanf("%d",&women[j]); womenh[women[j]]++; } int t1=10; int t2=10; int sum=0; while (t1!=0) { if (menh[t1]==0) { t1-=1; continue; } if (womenh[t2]==0) { t2-=1; continue; } sum+=t1*t2; menh[t1]-=1; womenh[t2]-=1; } printf("%d\n",sum); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { char s[1000000]; int n; int counter = 0; while(scanf("%s",s)!=EOF) { counter++; cin>>n; int a,b; int len = strlen(s); if (len == 0) break; vector<int> aux(len); aux[0] = s[0] - 48; for (int i = 1;i<len;i++) { aux[i] = aux[i-1] + s[i] - 48; } cout<<"Case "<<counter<<":"<<endl; for (int i = 0; i < n; i++) { int sum = 0; cin>>a>>b; if (a>b) swap(a,b); if (a == 0) { sum = aux[b]; } else { sum = aux[b] - aux[a-1]; } if (sum == 0 || sum == b-a+1) { cout<<"Yes"<<endl; } else { cout<<"No"<<endl; } } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int n,k; cin>>n>>k; string word; cin>>word; vector <int> hsh(26,0); for (int i=0;i<word.length();i++) { hsh[word[i] - 65]++; } vector <long long int> t; for (int i=0;i<26;i++) { if (hsh[i]>0) { t.push_back(hsh[i]); } } sort(t.begin(),t.end(),greater<int>()); long long int count = 0; int c = 0; while ( k>0) { if (t[c] < k ) { count += t[c]*t[c]; } else { count += k*k; break; } k-=t[c]; c++; } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int four = 0; if (s[0]=='4') { cout<<"NO"<<endl; return 0; } for (int i=0;i<s.length();i++) { if (s[i] != '1' && s[i]!='4') { cout<<"NO"<<endl; return 0; } if (s[i] == '4') { four++; if (four>2) { cout<<"NO"<<endl; return 0; } } else { four = 0; } } cout<<"YES"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; string command; int source, destination; string type; vector <vector <int> > boxes(n); vector <int> track(n); for (int i = 0; i < n; i++) { boxes[i].push_back(i); track[i] = i; } while (cin >> command) { if (command == "quit") { break; } cin >> source >> type >> destination; int s1 = track[source]; int d1 = track[destination]; if (s1 == d1) { continue; } if (command == "move") { if (type == "over") { while(boxes[s1].back() != source) { track[boxes[s1].back()] = boxes[s1].back(); boxes[boxes[s1].back()].push_back(boxes[s1].back()); boxes[s1].pop_back(); } track[boxes[s1].back()] = d1; boxes[d1].push_back(source); boxes[s1].pop_back(); } else if (type == "onto") { while(boxes[s1].back() != source) { track[boxes[s1].back()] = boxes[s1].back(); boxes[boxes[s1].back()].push_back(boxes[s1].back()); boxes[s1].pop_back(); } while(boxes[d1].back() != destination) { track[boxes[d1].back()] = boxes[d1].back(); boxes[boxes[d1].back()].push_back(boxes[d1].back()); boxes[d1].pop_back(); } track[boxes[s1].back()] = d1; boxes[d1].push_back(source); boxes[s1].pop_back(); } } else if (command == "pile") { if (type == "over") { vector <int> temp; while(boxes[s1].back() != source) { track[boxes[s1].back()] = d1; temp.push_back(boxes[s1].back()); boxes[s1].pop_back(); } track[boxes[s1].back()] = d1; boxes[d1].push_back(source); boxes[s1].pop_back(); while (!temp.empty()) { boxes[d1].push_back(temp.back()); temp.pop_back(); } } else if (type == "onto") { vector <int> temp; while(boxes[d1].back() != destination) { track[boxes[d1].back()] = boxes[d1].back(); boxes[boxes[d1].back()].push_back(boxes[d1].back()); boxes[d1].pop_back(); } while(boxes[s1].back() != source) { track[boxes[s1].back()] = d1; temp.push_back(boxes[s1].back()); boxes[s1].pop_back(); } track[boxes[s1].back()] = d1; boxes[d1].push_back(source); boxes[s1].pop_back(); while (!temp.empty()) { boxes[d1].push_back(temp.back()); temp.pop_back(); } } } } for (int i = 0; i < n; i++) { cout << i << ":"; for (int j = 0; j < boxes[i].size(); j++) { cout << " " << boxes[i][j]; } cout << endl; } return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int flag1=0,flag2=0; if (s[0] < 97) { for (int i = 1; i< s.length(); i++) { if (s[i] >= 97) { cout<<s<<endl; flag1 = 1; break; } } if (flag1 == 0) { for (int i=0;i<s.length();i++) { if (s[i]<97) s[i]+=32; else s[i]-=32; } cout<<s<<endl; } } else { for (int i=1; i<s.length(); i++ ) { if (s[i] >=97) { cout<<s<<endl; flag2=1; break; } } if (flag2 == 0) { for (int i=0 ; i<s.length(); i++ ) { if (s[i]<97) s[i]+=32; else s[i]-=32; } cout<<s<<endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int integer(string s) { int res = 0; for (auto i:s) { res = res*10 + (i - 48); } return res; } stringstream ss; double epsilon = 0.000001; int main() { int p, g; cin >> p >> g; map <string, double> votes; string name; double vote; while(p--) { cin >> name >> vote; votes[name] = vote; } string inp; getline(cin, inp); string element; int idx = 0; while(g--) { getline(cin, inp); ss.str(""); ss.clear(); ss.str(inp); vector <string> vals; while (ss >> element) { vals.push_back(element); } double vote_sum = 0.0; for (int i = 0; i < (int)vals.size() - 2; i += 2) { vote_sum += votes[vals[i]]; } int guess = integer(vals.back()); string oper = vals[(int)vals.size() - 2]; if (oper == ">") { if (vote_sum - guess > epsilon) { cout << "Guess #" << ++idx << " was correct." << endl; } else { cout << "Guess #" << ++idx << " was incorrect." << endl; } } else if (oper == "<") { if (guess - vote_sum > epsilon) { cout << "Guess #" << ++idx << " was correct." << endl; } else { cout << "Guess #" << ++idx << " was incorrect." << endl; } } else if (oper == ">=") { if (vote_sum - guess > -0.0000001) { cout << "Guess #" << ++idx << " was correct." << endl; } else { cout << "Guess #" << ++idx << " was incorrect." << endl; } } else if (oper == "<=") { if (guess - vote_sum >= -0.0000001) { cout << "Guess #" << ++idx << " was correct." << endl; } else { cout << "Guess #" << ++idx << " was incorrect." << endl; } } else if (oper == "=") { if (abs(vote_sum - guess) < 0.0000001) { cout << "Guess #" << ++idx << " was correct." << endl; } else { cout << "Guess #" << ++idx << " was incorrect." << endl; } } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; int temp; int max = -1; int max_i = -1; for (int i = 0 ; i <n;i++) { cin>>temp; temp = temp/m + (int)(temp%m != 0); if (temp >= max) { max = temp; max_i = i+1; } } cout<<max_i<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool palin(vector <char> test) { for (int i = 0;i<test.size();i++) { if (test[i] != test[test.size() - 1 - i]) { return false; } } return true; } int main () { string s; getline(cin,s); while (s != "DONE") { vector <char> test; for (int i = 0;i<s.length();i++) { if (s[i] == ',' || s[i] == ' ' || s[i] == '.' || s[i] == '!' || s[i] == '?') continue; else if (s[i] >= 97) test.push_back(s[i] - 32); else test.push_back(s[i]); } if (palin(test)) { cout<<"You won't be eaten!\n"; } else { cout<<"Uh oh..\n"; } getline(cin,s); } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { string s; vector <string> board; int flag; int counter = 0; while (1) { counter++; flag = 1; for (int i = 0;i<8;i++) { cin>>s; board.push_back(s); for (int j = 0; j<8; j++) { if (board[i][j] != '.') flag = 0; } } if (flag == 1) break; int pB = 0; int pW = 0; for (int i = 0;i<8;i++) { for (int j = 0;j<8;j++) { if (board[i][j] == 'k') { if (i < 7 && j < 7 && board[i+1][j+1] == 'P') { pB = 1; } else if (i < 7 && j > 0 && board[i+1][j-1] == 'P') { pB = 1; } else if (i < 6 && j <7 && board[i+2][j+1] == 'N') { pB = 1; } else if (i < 6 && j > 0 && board[i+2][j-1] == 'N') { pB = 1; } else if (i < 7 && j < 6 && board[i+1][j+2] == 'N') { pB = 1; } else if (i < 7 && j > 1 && board[i+1][j-2] == 'N') { pB = 1; } else if (i > 1 && j > 0 && board[i-2][j-1] == 'N') { pB = 1; } else if (i > 1 && j < 7 && board[i-2][j+1] == 'N') { pB = 1; } else if (i > 0 && j < 6 && board[i-1][j+2] == 'N') { pB = 1; } else if (i > 0 && j > 1 && board[i-1][j-2] == 'N') { pB = 1; } //rooks int k = 0; for (k = 1; i+k<8 ;k++) { if (board[i+k][j]!='.') break; } if (i + k <=7 && (board[i+k][j] == 'R' || board[i+k][j] == 'Q')) { pB = 1; } k = 0; for (k = 1; i-k>=0 ;k++) { if (board[i-k][j]!='.') break; } if (i - k >= 0 && (board[i-k][j] == 'R' || board[i-k][j] == 'Q')) { pB = 1; } k = 0; for (k = 1; j-k>=0 ;k++) { if (board[i][j-k]!='.') break; } if (j - k >= 0 && (board[i][j-k] == 'R' || board[i][j-k] == 'Q')) { pB = 1; } k = 0; for (k = 1; j+k<8 ;k++) { if (board[i][j+k]!='.') break; } if (j + k <=7 && (board[i][j+k] == 'R' || board[i][j+k] == 'Q')) { pB = 1; } //bishops k = 0; for (k = 1; i+k<8 && j+k <8 ;k++) { if (board[i+k][j+k]!='.') break; } if (i + k <=7 && j+k <=8 && (board[i+k][j+k] == 'B' || board[i+k][j+k] == 'Q')) { pB = 1; } k = 0; for (k = 1; i-k>=0 && j-k>= 0;k++) { if (board[i-k][j-k]!='.') break; } if (i - k >= 0 && j-k>=0 && (board[i-k][j-k] == 'B' || board[i-k][j-k] == 'Q')) { pB = 1; } k = 0; for (k = 1; i+k <8 && j-k>=0 ;k++) { if (board[i+k][j-k]!='.') break; } if (j - k >= 0 && i+k<=7 && (board[i+k][j-k] == 'B' || board[i+k][j-k] == 'Q')) { pB = 1; } k = 0; for (k = 1; i-k>=0 && j+k<8 ;k++) { if (board[i-k][j+k]!='.') break; } if (i - k >=0 && j + k<=7 && (board[i-k][j+k] == 'B' || board[i-k][j+k] == 'Q')) { pB = 1; } } if (board[i][j] == 'K') { if (i > 0 && j > 0 && board[i-1][j-1] == 'p') { pW = 1; } else if (i > 0 && j < 7 && board[i-1][j+1] == 'p') { pW = 1; } else if (i < 6 && j <7 && board[i+2][j+1] == 'n') { pW = 1; } else if (i < 6 && j > 0 && board[i+2][j-1] == 'n') { pW = 1; } else if (i < 7 && j < 6 && board[i+1][j+2] == 'n') { pW = 1; } else if (i < 7 && j > 1 && board[i+1][j-2] == 'n') { pW = 1; } else if (i > 1 && j > 0 && board[i-2][j-1] == 'n') { pW = 1; } else if (i > 1 && j < 7 && board[i-2][j+1] == 'n') { pW = 1; } else if (i > 0 && j < 6 && board[i-1][j+2] == 'n') { pW = 1; } else if (i > 0 && j > 1 && board[i-1][j-2] == 'n') { pW = 1; } //rooks int k = 0; for (k = 1; i+k<8 ;k++) { if (board[i+k][j]!='.') break; } if (i + k <=7 && (board[i+k][j] == 'r' || board[i+k][j] == 'q')) { pW = 1; } k = 0; for (k = 1; i-k>=0 ;k++) { if (board[i-k][j]!='.') break; } if (i - k >= 0 && (board[i-k][j] == 'r' || board[i-k][j] == 'q')) { pW = 1; } k = 0; for (k = 1; j-k>=0 ;k++) { if (board[i][j-k]!='.') break; } if (j - k >= 0 && (board[i][j-k] == 'r' || board[i][j-k] == 'q')) { pW = 1; } k = 0; for (k = 1; j+k<8 ;k++) { if (board[i][j+k]!='.') break; } if (j + k <=7 && (board[i][j+k] == 'r' || board[i][j+k] == 'q')) { pW = 1; } //bishops k = 0; for (k = 1; i+k<8 && j+k <8 ;k++) { if (board[i+k][j+k]!='.') break; } if (i + k <=7 && j+k <=8 && (board[i+k][j+k] == 'b' || board[i+k][j+k] == 'q')) { pW = 1; } k = 0; for (k = 1; i-k>=0 && j-k>= 0;k++) { if (board[i-k][j-k]!='.') break; } if (i - k >= 0 && j-k>=0 && (board[i-k][j-k] == 'b' || board[i-k][j-k] == 'q')) { pW = 1; } k = 0; for (k = 1; i+k <8 && j-k>=0 ;k++) { if (board[i+k][j-k]!='.') break; } if (j - k >= 0 && i+k<=7 && (board[i+k][j-k] == 'b' || board[i+k][j-k] == 'q')) { pW = 1; } k = 0; for (k = 1; i-k>=0 && j+k<8 ;k++) { if (board[i-k][j+k]!='.') break; } if (i - k >=0 && j + k<=7 && (board[i-k][j+k] == 'b' || board[i-k][j+k] == 'q')) { pW = 1; } } } } cout<<"Game #"<<counter; if (pB) cout<<": black king is in check."<<endl; else if (pW) cout<<": white king is in check."<<endl; else cout<<": no king is in check."<<endl; board.clear(); } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s1; cin>>s1; string s2; cin>>s2; string s3; cin>>s3; vector <int> check(26,0); for (int i=0;i<s1.length();i++) { int t = s1[i] - 65; check[t]++; } for (int i=0;i<s2.length();i++) { int t = s2[i] - 65; check[t]++; } for (int i=0;i<s3.length();i++) { int t = s3[i] - 65; check[t]--; } for (int i=0;i<26;i++) { if (check[i] != 0) { cout<<"NO\n"; return 0; } } cout<<"YES\n"; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; string clean(string s) { string res = ""; for (auto i:s) { if ((i <= 'z' && i >= 'a') || (i >= 'A' && i <= 'Z')) { res += i; } else { res += " "; } } return res; } stringstream ss; int main() { int n; cin >> n; while (n--) { int c; cin >> c; map <string, vector<string> > word_cata; map <string, int> limit; vector <string> order; while(c--) { string cata; int w, p; cin >> cata >> w >> p; string key_word; limit[cata] = p; order.push_back(cata); set <string> temp; while(w--) { cin >> key_word; if (temp.find(key_word) == temp.end()) { word_cata[key_word].push_back(cata); temp.insert(key_word); } } } string inp; getline(cin, inp); map <string, int> results; vector <string> ordering; set <string> consider; while(getline(cin, inp)) { if (inp == "") { break; } inp = clean(inp); ss.str(""); ss.clear(); ss.str(inp); string word; while(ss >> word) { string word1 = clean(word); if (word_cata.find(word1) != word_cata.end() && consider.find(word1) == consider.end()) { consider.insert(word1); for (auto ii:word_cata[word1]) { if (results.find(ii) == results.end()) { ordering.push_back(ii); } results[ii] += 1; } } } } vector <string> otpt; for (auto i:order) { if (results[i] >= limit[i]) { otpt.push_back(i); } } for (int i = 0; i < otpt.size(); i++) { cout << otpt[i]; if (i < otpt.size() - 1) { cout << ","; } } if (otpt.empty()) { cout << "SQF Problem."; } cout << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { float a,b; cin>>a>>b; if (a == 0.0 && b == 0.0) { cout<<"Origem"<<endl; } else if (b == 0) { cout<<"Eixo X"<<endl; } else if (a == 0) { cout<<"Eixo Y"<<endl; } else if (a>0 && b>0) { cout<<"Q1"<<endl; } else if (a<0 && b>0) { cout<<"Q2"<<endl; } else if (a<0 && b<0) { cout<<"Q3"<<endl; } else if (a>0 && b<0) { cout<<"Q4"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { vector <double> a(3); for (int i=0;i<3;i++) { cin>>a[i]; } sort(a.begin(), a.end()); if (a[0] + a[1]<= a[2]) { cout<<"NAO FORMA TRIANGULO"<<endl; } else { if ( abs(a[0]*a[0] + a[1]*a[1] - a[2]*a[2]) <0.00001 ) { cout<<"TRIANGULO RETANGULO"<<endl; } else if (a[0]*a[0] + a[1]*a[1] - a[2]*a[2] <0) { cout<<"TRIANGULO OBTUSANGULO"<<endl; } else if (a[0]*a[0] + a[1]*a[1] - a[2]*a[2] >0) { cout<<"TRIANGULO ACUTANGULO"<<endl; } if (a[0] == a[2]) { cout<<"TRIANGULO EQUILATERO"<<endl; } else if (a[0] == a[1] || a[1] == a[2] ) { cout<<"TRIANGULO ISOSCELES"<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s1 = ""; string s2 = ""; string s,c; cin>>s; cin>>c; int flag = 0; for (int i=0;i<s.length(); i++) { if (s[i] == '|') { flag =1; continue; } if (flag == 0) { s1 += s[i]; } else { s2 += s[i]; } } int swap = 0; string mini,maxi; if (s1.length() < s2.length()) { mini = s1; maxi = s2; } else { swap = 1; mini = s2; maxi = s1; } int diff = maxi.length() - mini.length(); if (c.length() < diff) { cout<<"Impossible"<<endl; return 0; } int counter = 0; while (mini.length() < maxi.length()) { mini += c[counter]; counter++; } if ( (c.length() - counter)%2 != 0) { cout<<"Impossible"<<endl; return 0; } while (counter < c.length() ) { mini += c[counter++]; maxi += c[counter++]; } if (swap == 0) { cout<<mini<<"|"<<maxi<<endl; } else { cout<<maxi<<"|"<<mini<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int integer(string s) { int a; ss.str(""); ss.clear(); ss.str(s); ss >> a; return a; } int main() { string inp; unordered_map <string, string> ledger; while (getline(cin, inp)) { string code = ""; for (int i = 0;i < 3; i++) { code += inp[i]; } string remaining = ""; if (code == "000") { break; } for (int i = 3; i < inp.length(); i++) { remaining += inp[i]; } ledger[code] = remaining; inp = ""; } map <string, map <string, int> > transactions; while (getline(cin, inp)) { string code = ""; for (int i = 0;i < 3; i++) { code += inp[i]; } if (code == "000") { break; } string code1 = ""; for (int i = 3;i < 6; i++) { code1 += inp[i]; } string b = ""; for (int i = 6; i < inp.length();i++) { b += inp[i]; } transactions[code][code1] = integer(b); } for (auto i:transactions) { int sum1 = 0; for (auto j:i.second) { sum1 += j.second; } sum1 *= -1; if (sum1 != 0) { cout<<"*** Transaction "<<i.first<<" is out of balance ***"<<endl; for (auto j:i.second) { cout<<j.first<<" "; cout.width(31); cout<<left<<ledger[j.first]; cout<<" "; cout<<fixed<<setprecision(2); cout.width(9); cout<<right<<(double)j.second/100<<endl; } cout<<999<<" "; cout.width(31); cout<<left<<"Out of Balance"; cout<<" "; cout.width(9); cout<<right<<(double)sum1/100<<endl; cout << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; int temp; set <int> check; vector <int> inp(n); vector <int> Arr(n+1); for (int i=0;i<n;i++) { cin>>inp[i]; } for (int i=n-1;i>=0;i--) { check.insert(inp[i]); Arr[i] = (int)check.size(); } for (int i=0;i<m;i++) { cin>>temp; cout<<Arr[temp-1]<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; cin>>n; int ele; while(n!=0) { priority_queue<int> seq; for (int i = 0;i<n;i++) { cin>>ele; seq.push(-1*ele); } int cost = 0; while (seq.size()!=1) { int t1 = -1*seq.top();seq.pop(); int t2 = -1*seq.top();seq.pop(); cost += t1+t2; seq.push(-1*(t1+t2)); } cout<<cost<<endl; cin>>n; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s1; string s2; cin>>s1; cin>>s2; for (int i=0;i<s1.length();i++) { if (s1[i] != s2[s2.length()-1-i]) { cout<<"NO\n"; return 0; } } cout<<"YES\n"; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; int a, b, c; int idx = 0; while(cin >> n) { if (n == 0) { break; } vector <pair<int, int> > arr(n); for (int i = 0; i < n; i++) { cin >> a >> b >> c; arr[i] = make_pair(a, c - b); } cout << "Case #" << ++idx << ":" << endl; int maxi; int mini; while(1) { maxi = -1; mini = INT_MAX; for (auto i:arr) { maxi = max(i.first, maxi); mini = min(i.first, mini); } if (maxi == mini || maxi >= 10000) { break; } for (int i = 0; i < n; i++) { if (arr[i].first < maxi) { arr[i].first += arr[i].second; maxi = max(arr[i].first, maxi); } } } if (maxi >= 10000) { cout << "Unknown bugs detected." << endl; } else { cout << "The actual year is " << maxi << "." << endl; } cout << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,b; cin>>a>>b; printf("%.3f\n",(a*b)/(12.0)); return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int integer(string s) { int res = 0; for (int i = 0; i < s.length(); i++) { res = res * 10 + (s[i] - 48); } return res; } int main () { int n; string s; while(getline(cin, s)) { n = integer(s); if (n == 0) { break; } int v = 0; int mini = INT_MAX; for (int i = 0;i < n; i++) { getline(cin, s); int l = -1; int r = 26; for (int j = 0; j < 25; j++) { if (s[j] == ' ') { l = j; break; } } for (int j = 24; j >= 0; j--) { if (s[j] == ' ') { r = j; break; } } int diff = r - l + 1; if (diff == 28) { diff = 0; } v += diff; mini = min(mini, diff); } cout << v - (n * mini) << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; int idx = 0; while (t--) { cout<<"Case "<<++idx<<": "; long long int tax = 0LL; int n; cin >> n; // cout<<n<<endl; if (n <= 180000) { cout<<0<<endl; continue; } // first slab n = n - min(n, 180000); // second slab tax += (long long int)min(n, 300000) * 10; n -= min(n, 300000); // third slab tax += (long long int)min(n, 400000) * 15; n -= min(n, 400000); // fourth slab tax += (long long int)min(n, 300000) * 20; n -= min(n, 300000); // fifth slab tax += (long long int)(n) * 25; tax = tax/100 + (int)(tax%100 != 0); cout << max(tax, 2000LL)<<endl; } return 0; } <file_sep>#/usr/bin/python n=995/5 n1 = 999/3 n2 = 990/15 s = n*(1000)/2 s+= n1*1002/2 s -= n2*1005/2 print s <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; int idx = 0; while (t--) { char c; int n; cin >> c >> c >> n; bool flag = true; vector <vector <long long int> > grid(n, vector <long long int> (n, 0)); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> grid[i][j]; if (grid[i][j] < 0) { flag = false; } } } if (flag == false) { cout << "Test #" << ++idx << ": Non-symmetric." << endl; continue; } flag = true; for (int i = 0; i <= n/2; i++) { flag = true; for (int j = 0; j < n; j++) { if (grid[i][j] != grid[n-i-1][n-j-1]) { flag = false; break; } } if (flag == false) { break; } } if (flag) { cout << "Test #" << ++idx << ": Symmetric." << endl; } else { cout << "Test #" << ++idx << ": Non-symmetric." << endl; } } return 0; } <file_sep>#/usr/bin/python def fun(n): if n==0: return str(0) if n==1: return '' b=str(bin(n))[2:][::-1] t=[] for i in range(len(b)): if b[i]=='1': t.append(i) t.reverse() s='' for i in t: k1=fun(int(i)) if k1: s=s+'2('+k1+ ')+' else: s=s+'2+' s=s[0:-1] return (s) list=[137,1315,73,136,255,1384,16385] for i in list: a=fun(i) print str(i)+'='+a <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; while(1) { cin>>n; if (n==-1) { break; } int count = 0; cout<<"Round "<<n<<endl; string s1,s2; cin>>s1>>s2; int arr[26] = {0}; int uniq = 0; for (int i = 0;i<s1.length();i++) { if (arr[s1[i]-97] == 0) { uniq++; } arr[s1[i]-97] +=1; } for (int i = 0;i<s2.length();i++) { if (arr[s2[i]-97] == 0) { count++; arr[s2[i]-97] = -1; } else if (arr[s2[i]-97] != -2 && arr[s2[i]-97]!=-1){ arr[s2[i]-97] = -2; uniq--; } if (uniq == 0) break; } if (uniq == 0 && count<7) cout<<"You win."<<endl; else if (count>= 7) cout<<"You lose."<<endl; else if (uniq!=0) cout<<"You chickened out."<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; cin>>n; int res = 1; for (int i = n;i>=1;i--) res*=i; cout<<res<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s[8] = {"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"}; string inp; int n; cin>>n; cin>>inp; for (int i=0;i<8;i++) { int flag = 0; if (s[i].length() != n) continue; for (int j = 0;j<n;j++) { if (inp[j] == '.') continue; if (inp[j] != s[i][j]) { flag = 1; break; } } if (flag ==0 ) { cout<<s[i]<<endl; return 0; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int onedist(string s) { if (s.length() == 4) return 9; int cnt = 0; string test = "one"; for (unsigned int i = 0;i<s.length(); i++) { if (s[i]!=test[i]) cnt++; } return cnt; } int twodist(string s) { if (s.length() == 4) return 9; int cnt = 0; string test = "two"; for (unsigned int i = 0;i<s.length(); i++) { if (s[i]!=test[i]) cnt++; } return cnt; } int threedist(string s) { if (s.length() == 3) return 9; int cnt = 0; string test = "three"; for (unsigned int i = 0;i<s.length(); i++) { if (s[i]!=test[i]) cnt++; } return cnt; } int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; string s; for (int i = 0; i < n; i++) { ISTREAM>>s; int a = onedist(s); int b = twodist(s); int c = threedist(s); if (min(min(a,b),c) == a) cout<<1<<endl; else if (min(min(a,b),c) == b) cout<<2<<endl; else if (min(min(a,b),c) == c) cout<<3<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string a,b; cin>>a>>b; pair <int,int> from,to; from.first = a[0] - 97; from.second = a[1] - 48; to.first = b[0] - 97; to.second = b[1] - 48; int h = to.first - from.first; int v = to.second - from.second; int count = 0; string s = ""; while (v*h != 0) { count++; if (v<0 && h< 0) { s+="LD\n"; h++; v++; } else if (v<0 && h>0) { s+="RD\n"; v++; h--; } else if (v>0 && h>0) { s+="RU\n"; v--; h--; } else if (v>0 && h<0) { s+="LU\n"; v--; h++; } } while (h<0) { count++; s+="L\n"; h++; } while (h>0) { count++; s+="R\n"; h--; } while (v<0) { count++; s+="D\n"; v++; } while (v>0) { count++; s+="U\n"; v--; } cout<<count<<endl<<s; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int a,b,c,d; long long int sum = 0; for (int i = 0; i < n; i++) { cin>>a>>b>>c>>d; sum += (abs(c-a)+1)*(abs(d-b)+1); } cout<<sum<<endl; return 0; }<file_sep>import json from pprint import pprint from urllib2 import Request, urlopen, URLError from string import * request = Request('http://uhunt.felix-halim.net/api/cpbook/3') def slug(s): s = s.strip() s = s.lower() s = s.replace(' ', '-') test = set(digits + ascii_letters) res = "" for i in s: if i in test or i == '-': res += i return res try: response = urlopen(request) book = eval(response.read()) for chapter in book: print chapter['title'] topics = chapter['arr'] for topic in topics: print topic['title'] subtopics = topic['arr'] for i in subtopics: print i[0] for j in i[1:]: url = "http://uhunt.felix-halim.net/api/p/num/" + str(abs(j)) request = Request(url) response = urlopen(request) response = eval(response.read()) print str(abs(j)) + "," + slug(response['title']) print "" except URLError, e: print 'No kittez. Got an error code:', e <file_sep>#include<iostream> using namespace std; int main (void) { int n,k; cin>>n>>k; for (int i =0; i<n;i++ ){ for (int j=0;j<n;j++) { if (i==j) cout<<k<<' '; else cout<<'0'<<' '; } cout<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s1; string s2; cin>>s1>>s2; if (s1.length() != s2.length()) { cout<<"NO\n"; return 0; } for (int i=0;i<s1.length()-1;i+=2) { int t1 = (s1[i] - 48)^(s1[i+1] - 48); int t2 = (s1[i] - 48)|(s1[i+1] - 48); int t3 = s2[i] - 48; //cout<<t1<<" "<< t2 <<" "<< t3 <<" "<< t4 <<endl; if ( t1 == t3 || max(t1,t2) != max(t3,t4) ) { cout<<"NO\n"; return 0; } } cout<<"YES\n"; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; string inp; getline(cin, inp); getline(cin, inp); while(t--) { int total_length = 0; int word_count = 0; map <string, int> hashes; map <int, vector<string> > data; getline(cin, inp); while (inp != "") { word_count += 1; total_length += (int)inp.length(); data[inp.length()].push_back(inp); getline(cin, inp); } int result_length = (total_length * 2) / word_count; for (auto i:data) { for (auto j:i.second) { bool flag = true; for (auto k:data[result_length - i.first]) { if (i.first * 2 == result_length && k == j && flag) { flag = false; continue; } hashes[j+k] += 1; hashes[k+j] += 1; } } } int max_val = -1; string res; for (auto i:hashes) { if (i.second > max_val) { max_val = i.second; res = i.first; } } cout << res << endl; if (t > 0) { cout << endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int code; int quant; cin>>code>>quant; if (code == 1) printf("Total: R$ %.2f",quant*4.00); else if (code == 2) printf("Total: R$ %.2f",quant*4.50); else if (code == 3) printf("Total: R$ %.2f",quant*5.00); else if (code == 4) printf("Total: R$ %.2f",quant*2.00); else if (code == 5) printf("Total: R$ %.2f",quant*1.50); printf("\n"); return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int cnt = 0; int n,m; cin>>n; while(1) { if (n == 0) break; cin>>m; vector <string> crossword(n); for (int i = 0;i<n;i++) { cin>>crossword[i]; } vector < vector<int> > helper(n,vector<int> (m,0)); int counter = 0; for (int i = 0;i<n;i++) { for (int j = 0;j<m;j++) { if (crossword[i][j]!= '*'&& (j == 0 || crossword[i][j-1] == '*')) { counter++; helper[i][j] = counter; } else if (crossword[i][j]!= '*' && (i == 0 || crossword[i-1][j] == '*')) { counter++; helper[i][j] = counter; } } } vector <pair <int,string> > across; vector <pair <int,string> > down; for (int i = 0;i<n;i++) { for (int j = 0;j<m;j++) { if (crossword[i][j] != '*' && (j == 0 || crossword[i][j-1] == '*')) { string s = ""; int temp = j; while (temp < m && crossword[i][temp] != '*') { s += crossword[i][temp]; temp++; } if (s.length() > 0) across.push_back(make_pair(helper[i][j],s)); } } } for (int j = 0;j<m;j++) { for (int i = 0;i<n;i++) { if (crossword[i][j] != '*' && (i == 0 || crossword[i-1][j] == '*')) { string s = ""; int temp = i; while (temp < n && crossword[temp][j] != '*') { s += crossword[temp][j]; temp++; } if (s.length() > 0) down.push_back(make_pair(helper[i][j],s)); } } } cnt++; printf("puzzle #%d:\n",cnt); sort(down.begin(), down.end()); printf("Across\n"); for (int i = 0;i<across.size();i++) { printf(" %2d.",across[i].first); cout<<across[i].second<<endl; } printf("Down\n"); for (int i=0;i<down.size();i++) { printf(" %2d.",down[i].first); cout<<down[i].second<<endl; } cin>>n; if (n!=0) cout<<endl; } return 0; }<file_sep>#include<iostream> #include<vector> #include<algorithm> using namespace std; int main(void) { int n,i; cin>>n; int num[100]={0}; int temp; int onecount=0,doublecount; for (i=0;i<2*n;i++) { cin>>temp; num[temp]++; } vector <int> d; for (i=10;i<100;i++) { if (num[i]==1) onecount++; else if (num[i]==2) onecount+=2; else if (num[i]>2) d.push_back(num[i]); } sort(d.begin(),d.end()); doublecount=2*n-onecount; int x; int cnt=0; for (i=0;i<d.size();i++) { x+=d[i]/2 -1; if (d[i]%2==1){ cnt++; } } x+=cnt/2; if (cnt%2==0) cout<<(n-x)*(n-x)<<endl; else cout<<(n-x-1)*(n-x)<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { double a,b,c,d; cin>>a>>b>>c>>d; a = max(3*a/10,a - a*c/250); b = max(3*b/10,b - b*d/250); if (a>b) cout<<"Misha"<<endl; else if (a<b) cout<<"Vasya"<<endl; else cout<<"Tie"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { vector <int> Arr; Arr.push_back(1); Arr.push_back(2); Arr.push_back(3); cout<<Arr.top()<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; while (t--) { int n,s,q; cin>>n>>s>>q; int ele; vector <queue <int> > station(n); for (int i = 0;i<n;i++) { int n1; cin>>n1; for (int j = 0;j<n1;j++) { cin>>ele; station[i].push(ele); } } bool flag = true; int i = 0; int cost = -2; stack <int> st; while (flag) { bool flag2 = true; for (int j = 0;j<n;j++) { if (!station[j].empty()) { flag2 = false; } } if (flag2 == true && st.empty()) break; cost += 2; if (i == n) i = 0; while(!st.empty() ) { ele = st.top(); if (ele != i+1 ) { if (station[i].size() < q) { station[i].push(ele); cost +=1; st.pop(); } else { break; } } else { cost += 1; st.pop(); } } while(st.size() < s && station[i].size() > 0) { ele = station[i].front(); st.push(ele); cost+=1; station[i].pop(); } i += 1; } cout<<cost<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; vector < vector<int> > piles; int ele; int maxi = 0; for (int i = 0;i<n;i++) { cin>>ele; if (ele > maxi) maxi = ele; vector <int> t(ele,0); piles.push_back(t); } int color = 1; for (int i = 0;i<maxi;i++) { if (color > k) { cout<<"NO"<<endl; return 0; } int cnt = 0; for(int j = 0; j < n; j++) { if (i >= piles[j].size()) { continue; } piles[j][i] = color; cnt++; } if (cnt < n) color++; } cout<<"YES"<<endl; for (int i = 0; i < n; i++) { for (int j = 0;j<piles[i].size();j++) { cout<<piles[i][j]<<" "; } cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int n; cin >> n; int cnt = 0; while (n!=0) { if (n%10 == 7 || n%10 == 4) cnt++; n/=10; } if (cnt == 7 || cnt ==4) { cout<<"YES\n"; } else cout<<"NO\n"; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool is_num(char c) { if (c > 47 && c < 58) { return true; } return false; } int main () { int n; cin >> n; string inp; getline(cin,inp); int idx = 0; while (n != 0) { vector < vector < char> > terminal(10, vector<char> (10, ' ')); pair <int, int> cursor = make_pair(0, 0); bool insert_mode = false; while(n--) { getline(cin, inp); for (int i = 0; i < inp.length(); i++) { if (inp[i] == '^') { char c = inp[i+1]; if (c == 'b') { cursor.second = 0; } else if (c == 'c') { for (int j = 0;j < 10;j++) { for (int k = 0; k < 10; k++) { terminal[j][k] = ' '; } } } else if (c == 'd') { if (cursor.first < 9) { cursor.first += 1; } } else if (c == 'e') { for (int j = cursor.second; j < 10; j++) { terminal[cursor.first][j] = ' '; } } else if (c == 'h') { cursor = make_pair(0,0); } else if (c == 'i') { insert_mode = true; } else if (c == 'l') { if (cursor.second > 0) { cursor.second -= 1; } } else if (c == 'o') { insert_mode = false; } else if (c == 'r') { if (cursor.second < 9) { cursor.second += 1; } } else if (c == 'u') { if (cursor.first > 0) { cursor.first -= 1; } } else if (c == '^') { if (insert_mode) { int temp = cursor.second; for (int j = 9; j > temp; j--) { terminal[cursor.first][j] = terminal[cursor.first][j-1]; } terminal[cursor.first][cursor.second] = '^'; if (cursor.second < 9) { cursor.second += 1; } } else { terminal[cursor.first][cursor.second] = '^'; if (cursor.second < 9) { cursor.second += 1; } } } else if (is_num(c)) { char d = inp[i + 2]; cursor.first = c - 48; cursor.second = d - 48; i += 1; } i += 1; } else { if (insert_mode) { int temp = cursor.second; for (int j = 9; j > temp; j--) { terminal[cursor.first][j] = terminal[cursor.first][j-1]; } terminal[cursor.first][cursor.second] = inp[i]; } else { terminal[cursor.first][cursor.second] = inp[i]; } if (cursor.second < 9) { cursor.second += 1; } } } } cout<<"Case "<<++idx<<endl; cout<<"+----------+"<<endl; for (int i = 0;i < 10; i++) { cout<<'|'; for (int j = 0;j < 10; j++) { cout<<terminal[i][j]; } cout<<'|'<<endl; } cout<<"+----------+"<<endl; cin >> n; getline(cin,inp); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; void determine(string i, map<string, vector <string> > &parents, map<string,string> &characteristic) { if (characteristic.find(parents[i][0]) == characteristic.end()) { determine(parents[i][0], parents, characteristic); } if (characteristic.find(parents[i][1]) == characteristic.end()) { determine(parents[i][1], parents, characteristic); } if (characteristic.find(parents[i][0]) != characteristic.end() && characteristic.find(parents[i][1]) != characteristic.end()) { if ((characteristic[parents[i][0]] == "dominant" && characteristic[parents[i][1]] == "dominant") || (characteristic[parents[i][0]] == "dominant" && characteristic[parents[i][1]] == "recessive") || (characteristic[parents[i][0]] == "recessive" && characteristic[parents[i][1]] == "dominant")) { characteristic[i] = "dominant"; } else if (characteristic[parents[i][0]] == "dominant" || characteristic[parents[i][1]] == "dominant" || (characteristic[parents[i][0]] != "non-existent" && characteristic[parents[i][1]] != "non-existent")) { characteristic[i] = "recessive"; } else { characteristic[i] = "non-existent"; } } } string find_characteristic(string i, map<string, vector <string>> &parents, map<string,string> &characteristic) { if (characteristic.find(i) == characteristic.end()) { determine(i, parents, characteristic); } return characteristic[i]; } int main () { int n; cin >> n; string a, b; map <string, string> characteristic; map <string, vector <string> > parents; set <string> people; while (n--) { cin >> a >> b; if (b == "dominant" || b == "recessive" || b == "non-existent") { characteristic[a] = b; } else { parents[b].push_back(a); people.insert(b); } people.insert(a); } for (auto i:people) { cout << i << " " << find_characteristic(i, parents, characteristic) << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } int maxi = -1; int temp; for (int i=0;i<n;i++) { for (int j = i;j<n;j++) { int count = 0; for (int k=0;k<n;k++) { if (k>= i && k<= j) temp = 1- Arr[k]; else temp = Arr[k]; if (temp == 1) count++; } if (count>maxi) maxi = count; } } cout<<maxi<<endl; return 0; }<file_sep>#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <cstdlib> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> using namespace std; /* Head ends here */ class ExerciseMachine { public: int getPercentages(string time); int gcd (int a, int b); }; int ExerciseMachine::getPercentages(string time) { int hours=(time[0]-48)*10+(time[1]-48); int minutes=(time[3]-48)*10+(time[4]-48); int seconds = (time[6]-48)*10 +(time[7]-48); seconds=hours*3600 + minutes*60+ seconds; return gcd(seconds,100)-1; } int ExerciseMachine::gcd(int a,int b) { if (b==0) return a; return gcd(b,a%b); } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; int mini=999999999,maxi=-1; int temp; for (int i=0;i<n;i++) { cin>>temp; if (temp<mini) mini = temp; if (temp>maxi) maxi = temp; } int maxi2 = 2*mini; for (int i=0 ;i<m;i++) { cin>>temp; if (temp<=max(maxi,maxi2)) { cout<<-1<<endl; return 0; } } cout<<max(maxi,maxi2)<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); for (int i = 0; i < n; ++i) { cin>>Arr[i]; } int count = 0; int flag = 0; for (int i=0;i<n;i++) { if (Arr[i] == i) { count++; } else if (i == Arr[Arr[i]]) { flag = 1; } } if (flag == 1) cout<<count+2<<endl; else cout<<min(count+1,n)<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int p,n; cin>>p>>n; vector <int> p_num(p,0); int temp; for (int i=0;i<n;i++) { cin>>temp; p_num[temp%p]+=1; if (p_num[temp%p] == 2) { cout<<i+1<<endl; return 0; } } cout<<-1<<endl; return 0; }<file_sep>#include<stdio.h> int main() { int n,i; scanf("%d",&n); while (n!=0) { int a[100002]; int b[100002]; for (i=1;i<n+1;i++) { scanf("%d",&a[i]); b[a[i]]=i; } int flag=0; for (i=1;i<n+1;i++) { if (a[i]!=b[i]) { flag=1; break; } } if(flag==0) printf("ambiguous\n"); else printf("not ambiguous\n"); scanf("%d",&n); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<int> arr(n); if (n == 1) { cout<<1<<endl<<1<<endl; } else if (n == 2) { cout<<1<<endl<<1<<endl; } else if (n == 3) { cout<<2<<endl<<"1 3"<<endl; } else if (n == 4) { cout<<4<<endl<<"2 4 1 3"<<endl; } else { cout<<n<<endl; int counter = 1; for (int i=0;i<n;i+=2) { arr[i]=counter++; } for (int i = 1;i<n;i+=2) { arr[i]=counter++; } for (auto i :arr) { cout<<i<<" "; } cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; float a,b,c; cout << fixed << setprecision(1); for (int i = 0; i < n; i++) { cin >> a >> b >> c; cout << (2 * a + 3 * b + 5 * c) / 10 << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int s; long double p; while(1) { cin>>s>>p; if (s + p == 0) break; long long int root = (long long int)sqrt(p); if (root*root < p) root += 1; if (root % 2 == 0) root += 1; long long int delta = root*root - p; long long int baser, basec; baser = (s + 1)/2 + (root - 1)/2; basec = baser; if (delta == 0) { cout<<"Line = "<<baser<<", column = "<<basec<<"."<<endl; } else { if (delta - (root-1) > 0) { baser -= root - 1; delta -= root - 1; } else { baser -= delta; delta = 0; } if (delta - (root-1) > 0) { basec -= root - 1; delta -= root - 1; } else { basec -= delta; delta = 0; } if (delta - (root-1) > 0) { baser += root - 1; delta -= root - 1; } else { baser += delta; delta = 0; } if (delta - (root-1) > 0) { basec += root - 1; delta -= root - 1; } else { basec += delta; delta = 0; } cout<<"Line = "<<baser<<", column = "<<basec<<"."<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int k; cin>>k; string s; cin>>s; vector <int> h(26,0); for (int i=0;i<s.length();i++) { h[s[i]-97]++; } string res = ""; for (int i=0;i<26;i++) { if (h[i] == 0) continue; else if (h[i]%k != 0) { cout<<"-1"<<endl; return 0; } else { for (int j=0;j<h[i]/k;j++) { res+=(char)(i+97); } } } for (int i=0;i<k;i++) { cout<<res; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; vector <int> ab; vector <int> ba; for (int i = 0; i < s.length()-1; i++) { if (s[i] == 'A' && s[i+1] == 'B') ab.push_back(i); else if (s[i] == 'B' && s[i+1] == 'A') ba.push_back(i); } for (int i = 0;i< ab.size();i++) { for (int j = 0; j < ba.size(); j++) { if (ba[j] > ab[i] + 1 || ba[j] + 1 < ab[i]) { cout<<"YES"<<endl; return 0; } } } cout<<"NO"<<endl; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { while (1) { vector <int> delta; int a,b,c; cin>>a>>b>>c; delta.push_back(a); delta.push_back(b); if (a == 0 && b == 0) { break; } while (c != 0) { delta.push_back(c); cin>>c; } vector <int > times(delta.size(),0); bool flag = false; int rangea,rangeb; do { int mint = times[0]; int min_delta = delta[0]; for (int i = 0;i<times.size();i++) { if (times[i] + delta[i] - 5 < mint + min_delta) { mint = times[i]; min_delta = delta[i]; } } for (int i = 0;i< times.size();i++) { if (times[i] + delta[i] >= mint + 2*min_delta) { continue; } times[i] = times[i] + delta[i]*2; } rangea = times[0]; rangeb = times[0] + delta[0] - 5; for (int i = 1; i< times.size();i++) { rangea = max(rangea,times[i]); rangeb = min(rangeb,times[i] + delta[i] - 5); } if (rangea >= 19000) { break; } } while (rangea >= rangeb); if (rangea >= 19000) { printf("Signals fail to synchronise in 5 hours\n"); } else { printf ("%02d:%02d:%02d\n",rangea/3600,(rangea - (rangea/3600)*3600)/60,rangea%60); } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; string tens[] = {"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}; string ones[] = {"zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen", "fourteen","fifteen", "sixteen", "seventeen","eighteen","nineteen"}; cin>>n; if (n<20) { cout<<ones[n]<<endl; return 0; } cout<<tens[n/10 -2]; if (n%10!=0) { cout<<"-"<<ones[n%10]<<endl; return 0; } cout<<endl; return 0; } <file_sep>#include<stdio.h> #include<math.h> int main() { int n; scanf("%d",&n); int i; int t=sqrt(n); int sum=(t*(t+1))/2; for (i=t+1;i<=n;i++) { sum+=n/(i); } printf ("%d\n",sum); return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<int> arr(n); for (int i = 0; i < n; i++) { cin>>arr[i]; } vector<string> matrix(n); for (int i = 0;i<n;i++) { cin>>matrix[i]; } for (int i = 0;i<n;i++) { for (int j = 0;j < n; j++) { if (matrix[i][j] != '1') continue; for (int k = 0;k <n;k++) { if (matrix[j][k] == '1') { matrix[i][k] = '1'; } } } } int i; int flag; int super = 1; while (super){ i = 0; super = 0; while (i < n) { /* for (int id = 0;id<n;id++) { cout<<arr[id]<<" "; } cout<<endl; */ int j = 0; flag = 0; int swapper = -1; int maxi = -1; while (j < n) { if (matrix[i][j] == '1' && ( (i < j && arr[i] > arr[j] && arr[i] - arr[j] > maxi) || (i > j && arr[i]<arr[j] && arr[j] - arr[i] > maxi)) ){ maxi = abs(arr[i] - arr[j]); swapper = j; } j++; } if (swapper != -1) { arr[i] = arr[i] + arr[swapper]; arr[swapper] = arr[i] - arr[swapper]; arr[i] = arr[i] - arr[swapper]; flag = 1; super = 1; } if (flag == 0) { i++; } } } for (int i = 0;i<n;i++) { cout<<arr[i]<<" "; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { set <char> check; string s; getline(cin,s); for (int i=0;i<s.length();i++) { if (s[i]>='a' && s[i]<='z') check.insert(s[i]); } cout<<check.size()<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; vector<string> cards(52); for (int i = 0; i < n; i++) { for (int j = 0; j < 52; j++) { ISTREAM>>cards[j]; } int it = 26; int score = 0; int jumps = 0; for (int j = 0; j < 3; j++) { //cout<<cards[it]<<endl; char c = cards[it][0]; if (c>='2' && c<='9') { score += c - 48; it -= 10 - (c - 48); jumps += 10 - (c - 48); } else score +=10; it--; jumps +=1; } //cout<<cards[it]<<" "<<score<<" "<<it<<" "<<jumps<<endl; cout<<"Case "<<i+1<<": "; if (score-1 <= it) cout<<cards[score-1]<<endl; else { cout<<cards[score+jumps-1]<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n, t; int idx = 0; while(cin >> n >> t) { if (n + t == 0) { break; } vector <string> names(n); vector < vector <int> > transactions(n, vector <int> (n, 0)); map < string, int> r_names; for (int i = 0; i < n; i++) { cin >> names[i]; r_names[names[i]] = i; } string a, b; int cash; for (int i = 0; i < t; i++) { cin >> a >> b >> cash; transactions[r_names[b]][r_names[a]] += cash; } for (int i = 1; i < n; i++) { for (int j = 1; j < n; j++) { transactions[i][0] += transactions[i][j]; transactions[0][j] += transactions[i][j]; transactions[i][j] = 0; } } cout <<"Case #"<<++idx<<endl; int ctr = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (transactions[i][j] != 0 && transactions[j][i] != 0) { transactions[i][j] -= transactions[j][i]; transactions[j][i] = 0; } if (transactions[i][j] < 0) { transactions[j][i] = -1*transactions[i][j]; transactions[i][j] = 0; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (transactions[i][j] > 0) { ctr += 1; cout << names[i] << " " << names[j] << " " << transactions[i][j]<<endl; } } } cout << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { string s; cin>>s; int a,b; priority_queue <vector <int> > arr; while (s!="#") { cin>>a>>b; vector <int> temp(3); temp[0] = -1*b; temp[1] = -1*a; temp[2] = b; arr.push(temp); cin>>s; } int k; cin>>k; for (int i = 0;i<k;i++) { vector <int> temp = arr.top(); cout<<-1*temp[1]<<endl; temp[0] -= temp[2]; arr.pop(); arr.push(temp); } return 0; }<file_sep>for _ in range(input()): n=raw_input() si = n.count('6') ei = n.count('8') ni = n.count('9') te = n.count('0') print si+2*ei+ni+te <file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; vector <int> readints(string s) { vector <int> res; int ele; ss.str(""); ss.clear(); ss.str(s); while (ss >> ele) { res.push_back(ele); } return res; } vector <string> readstr(string s) { vector <string> res; string ele; ss.str(""); ss.clear(); ss.str(s); while (ss >> ele) { res.push_back(ele); } return res; } int integer(string s) { int res = 0; for (int i = 0; i < s.length(); i++) { res = res * 10 + (s[i] - 48); } return res; } int main() { string inp; int t; getline(cin, inp); t = integer(inp); while(t--) { getline(cin, inp); getline(cin, inp); vector <int> perm = readints(inp); getline(cin, inp); vector <string> vals = readstr(inp); int sz = (int)vals.size(); vector <pair<int, string> > res(sz); for (int i = 0; i < sz; i++) { res[i] = make_pair(perm[i], vals[i]); } sort(res.begin(), res.end()); for (int i = 0;i < sz; i++) { cout<<res[i].second<<endl; } if (t > 0) { cout<<endl; } } } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int h,m; while (1) { scanf("%d:%d",&h,&m); if (h + m == 0) { break; } float mdeg = m*6; float hdeg = h*30 + 0.5*m; float res = abs(mdeg - hdeg); if (res > 180) res = 360-res; printf("%.3f\n",res); } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; cout<<min(n,min(m,(m+n)/3))<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif float j = 1; for (float i = 0; i <= 2.1; i+=0.2) { cout<<"I="<<i<<" J="<<j<<endl; cout<<"I="<<i<<" J="<<j+1<<endl; cout<<"I="<<i<<" J="<<j+2<<endl; j+=0.2; } return 0; }<file_sep>global matrix,h,w,maxi,check h,w = [int(x) for x in raw_input().split()] counter = 0 maxi = 0 def process_matrix(x_y,s): global maxi if x_y[0]<(h-1) and matrix[x_y[0]+1][x_y[1]]==chr(ord(s)+1) and check[x_y[0]+1][x_y[1]]==0: process_matrix([x_y[0]+1,x_y[1]],chr(ord(s)+1)) if x_y[0]>0 and matrix[x_y[0]-1][x_y[1]]==chr(ord(s)+1) and check[x_y[0]-1][x_y[1]]==0: process_matrix([x_y[0]-1,x_y[1]],chr(ord(s)+1)) if x_y[1]<(w-1) and matrix[x_y[0]][x_y[1]+1]==chr(ord(s)+1) and check[x_y[0]][x_y[1]+1]==0: process_matrix([x_y[0],x_y[1]+1],chr(ord(s)+1)) if x_y[1]>0 and matrix[x_y[0]][x_y[1]-1]==chr(ord(s)+1) and check[x_y[0]][x_y[1]-1]==0: process_matrix([x_y[0],x_y[1]-1],chr(ord(s)+1)) if x_y[0]<(h-1) and x_y[1]<(w-1) and matrix[x_y[0]+1][x_y[1]+1]==chr(ord(s)+1) and check[x_y[0]+1][x_y[1]+1]==0: process_matrix([x_y[0]+1,x_y[1]+1],chr(ord(s)+1)) if x_y[0]<(h-1) and x_y[1]>0 and matrix[x_y[0]+1][x_y[1]-1]==chr(ord(s)+1) and check[x_y[0]+1][x_y[1]-1]==0: process_matrix([x_y[0]+1,x_y[1]-1],chr(ord(s)+1)) if x_y[0]>0 and x_y[1]>0 and matrix[x_y[0]-1][x_y[1]-1]==chr(ord(s)+1) and check[x_y[0]-1][x_y[1]-1]==0: process_matrix([x_y[0]-1,x_y[1]-1],chr(ord(s)+1)) if x_y[0]>0 and x_y[1]<(w-1) and matrix[x_y[0]-1][x_y[1]+1]==chr(ord(s)+1) and check[x_y[0]-1][x_y[1]+1]==0: process_matrix([x_y[0]-1,x_y[1]+1],chr(ord(s)+1)) if ord(s)-ord('A')+1>maxi: maxi = ord(s) - ord('A')+1 check[x_y[0]][x_y[1]]=1 return maxi while h!=0 or w!=0: counter+=1 matrix=[] tups = [] check=[] for i in range(h): temp=[] st = list(raw_input()) for j in range(w): temp.append(0) if st[j]=='A': tups.append([i,j]) matrix.append(st) check.append(temp) maxj = 0 maxi = 0 for i in tups: maxi = process_matrix(i,'A') if maxi > maxj: maxj = maxi print "Case",str(counter)+":",maxj h,w = [int(x) for x in raw_input().split()] <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> H(n); vector <int> A(301,0); int temp; for(int i=0;i<n;i++) { cin>>H[i]>>temp; A[temp]++; } int sum = 0; for (int i=0;i<n;i++) { sum+=A[H[i]]; } cout<<sum<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int Arr[n][n]; int row[n][n]; int col[n][n]; for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { cin>>Arr[i][j]; } } for (int i=0;i<n;i++) { int sum = 0; for (int j=0;j<n;j++) { sum +=Arr[i][j]; } for (int j=0;j<n;j++) { row[i][j] = sum; } } for (int i=0;i<n;i++) { int sum = 0; for (int j=0;j<n;j++) { sum +=Arr[j][i]; } for (int j=0;j<n;j++) { col[j][i] = sum; } } int count = 0; for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { if (col[i][j] > row[i][j]) { count++; } } } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { cout<<"KABIR"<<endl; /* int n; cin>>n; vector<string> setters(n); for (int i = 0; i < n; i++) { cin>>setters[i]; } int m; cin>>m; vector<string> grid(m); for (int i = 0; i < m; i++) { cin>>grid[i]; } map <vector<char> ,int> dic; for (int id = 0; id < n; id++) { vector<char> v; for (int i = 0; i < setters[id].length(); i++) { v.push_back(setters[id][i]); } sort(v.begin(), v.end()); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { vector<char> w; if(j + v.size() <= 9) { for (int k = j; k < j+v.size(); k++) { w.push_back(grid[i][k]); } sort(w.begin(), w.end()); if (v == w) { cout<<i<<" "<<j<<" accross"<<endl; for(auto ij:v) cout<<ij;cout<<endl; dic[v]++; } } w.clear(); if(i + v.size() <= 9) { for (int k = i; k < i+v.size(); k++) { w.push_back(grid[k][j]); } sort(w.begin(), w.end()); if (v == w) { cout<<i<<" "<<j<<" down"<<endl; for(auto ij:v) cout<<ij;cout<<endl; dic[v]++; } } } } } for (map <vector<char>, int> :: iterator it = dic.begin(); it!=dic.end(); it++) { for (auto id:it->first) cout<<id; cout<<" "<<it->second<<endl; } */ return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int sum = 0; int temp; for (int i=0;i<n;i++) { cin>>temp; sum+=temp; } int count = 0; for (int i = 1;i<=5;i++) { if ((sum + i)%(n+1) == 1) continue; count++; } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif long long int fact(long long int n) { long long int res = 1; if (n == 0) return res; for (int i = 1;i <= n;i++) { res*=i; } return res; } int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif long long int a,b; while (scanf("%lld %lld",&a,&b)!=EOF) { cout<<fact(a) + fact(b)<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; set <string> res; void fun (string r,stack <char> pushpa, string a, string b,int i1,int c) { if (i1 >= a.length()) return; for (int i = i1;i<a.length();i++) { pushpa.push(a[i]); r+='1'; while(!pushpa.empty() && pushpa.top() == b[c]) { fun(r,pushpa,a,b,i+1,c); r+='0'; pushpa.pop(); c++; } } if (pushpa.empty()) { res.insert(r); } } int main () { string a,b; while (getline(cin,a)) { getline(cin,b); res.clear(); stack <char> pushpa; string r = ""; if (a.length() == b.length()) fun(r,pushpa,a,b,0,0); vector <string> res2; for (auto i:res) { res2.push_back(i); } cout<<"["<<endl; for (int i = res2.size()-1; i>= 0; i--) { for (int j = 0;j<res2[i].length();j++) { if (res2[i][j] == '0') cout<<"o"; else cout<<"i"; if (j < res2[i].length()-1) cout<<" "; } cout<<endl; } cout<<"]"<<endl; } return 0; }<file_sep>#include<stdio.h> int main() { int t,i,ng,nm; scanf("%d",&t); int j,k; for (i=0;i<t;i++) { scanf("%d %d",&ng,&nm); int max1=0;int max2=0; for (j=0;j<ng;j++) { scanf("%d",&k); if ( k> max1 ) { max1=k; } } for (j=0;j<nm;j++) { scanf("%d",&k); if ( k> max2 ) { max2=k; } } if (max2>max1) printf("MechaGodzilla\n"); else if (max1>=max2)printf("Godzilla\n"); else printf("uncertain\n"); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; int r, c, p; cin >> t; while (t--) { cin >> r >> c >> p; int X = 0; int Y = 0; vector <pair<int, int> > ppl(p); for (int i = 0; i < p; i++) { cin >> ppl[i].first; cin >> ppl[i].second; X += ppl[i].first; Y += ppl[i].second; } X /= p; Y /= p; vector <pair <int, pair<int, int> > > dist(p); for (int i = 0; i < p; i++) { int d = abs(ppl[i].first - X) + abs(ppl[i].second - Y); dist[i] = make_pair(d, ppl[i]); } sort(dist.begin(), dist.end()); int min_d = INT_MAX; pair <int, int> res = make_pair(INT_MAX, INT_MAX); for (int i = 0; i < min(p, 1000000); i++) { pair <int, int> candidate = dist[i].second; int d = 0; for (int i = 0; i < p; i++) { d += abs(ppl[i].first - candidate.first) + abs(ppl[i].second - candidate.second); } if (d < min_d) { min_d = d; res = candidate; } else if (d == min_d && candidate.first < res.first) { res = candidate; } else if (d == min_d && candidate.first == res.first && candidate.second < res.second) { res = candidate; } } cout << "(Street: " << res.first << ", Avenue: " << res.second << ")" << endl; } return 0; } <file_sep>#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <cstdlib> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> using namespace std; class BinaryCode { public: vector <string> decode(string s); }; vector <string> BinaryCode::decode(string s){ string a=s; string dummy="NONE"; vector <string> output; int n=s.length(); int flag1=0; int flag2=0; if (n==1 and s[0]=='1') { output.push_back(dummy); output.push_back(a); return output; } else if (n==1 and s[0]=='0') { output.push_back(a); output.push_back(dummy); return output; } else if (n==1) { output.push_back(dummy); output.push_back(dummy); return output; } a[0]='0'; a[1]=s[0]-a[0]+48; for (int i=2;i<n;i++){ a[i]=s[i-1]-(a[i-1]+a[i-2])+96; } if (s[n-1]!=(a[n-1]+a[n-2])-48) flag1++; for (int i=0;i<n;i++) { if (a[i]!='0' && a[i]!='1') { flag1++; break; } } if (flag1==0) output.push_back(a); else output.push_back(dummy); a[0]='1'; a[1]=s[0]-a[0]+48; for (int i=2;i<n;i++) { a[i]=s[i-1]-(a[i-1]+a[i-2])+96; } if (s[n-1]!=(a[n-1]+a[n-2])-48) flag2++; for (int i=0;i<n;i++) { if (a[i]!='0' && a[i]!='1') { flag2++; break; } } if (flag2==0) output.push_back(a); else output.push_back(dummy); return output; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; double l; ISTREAM>>n>>l; vector<double> arr(n); for (int i = 0; i < n; i++) { ISTREAM>>arr[i]; } sort(arr.begin(), arr.end()); double maxd = 0.0; for (int i=1;i<n;i++) { if (arr[i] - arr[i-1] > maxd ) { maxd = arr[i] - arr[i-1]; } } cout<<setprecision(9)<<max(maxd/2,max(arr[0],l-arr[n-1]))<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; if (s == "vertebrado") { cin>>s; if (s == "ave") { cin>>s; if (s == "carnivoro") { cout<<"aguia"<<endl; } else if (s == "onivoro") { cout<<"pomba"<<endl; } } else if (s == "mamifero") { cin>>s; if (s == "herbivoro") { cout<<"vaca"<<endl; } else if (s == "onivoro") { cout<<"homem"<<endl; } } } else if (s == "invertebrado") { cin>>s; if (s == "inseto") { cin>>s; if (s == "hematofago") { cout<<"pulga"<<endl; } else if (s == "herbivoro") { cout<<"lagarta"<<endl; } } else if (s == "anelideo") { cin>>s; if (s == "hematofago") { cout<<"sanguessuga"<<endl; } else if (s == "onivoro") { cout<<"minhoca"<<endl; } } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool palin(string s) { for (int i = 0;i<s.length();i++) { if (s[i] != s[s.length()- 1 - i]) { return false; } } return true; } int main () { int n; cin>>n; getchar(); for (int it =0; it<n;it++) { cout<<"Case #"<<it+1<<":"<<endl; string s; getline(cin,s); string t = ""; for (int i = 0;i<s.length();i++) { if (s[i] >= 65 && s[i] <= 90) { t += s[i]; } else if (s[i] >= 97 && s[i] <= 122) { t += s[i] - 32; } } int ck = sqrt(t.length()); if (ck * ck != t.length()) { cout<<"No magic :("<<endl; continue; } vector< string> grid; for (int i = 0;i<ck;i++) { string temp= ""; for (int j = i*ck;j<(i+1)*ck;j++) { temp+= t[j]; } grid.push_back(temp); } string s1 = ""; string s2 = ""; string s3 = ""; string s4 = ""; for (int i= 0;i<ck;i++) { s1 += grid[i]; } for (int i = ck-1;i>=0;i--) { for (int j = ck-1;j>= 0;j--) { s2 += grid[i][j]; } } for (int i = 0;i<ck;i++) { for (int j = 0;j<ck;j++) { s3 += grid[j][i]; } } for (int i = ck - 1;i >= 0;i--) { for (int j = ck - 1;j>=0;j--) { s4 += grid[j][i]; } } if (palin(s1) && palin(s2) && palin(s3) && palin(s4)) { cout<<ck<<endl; } else { cout<<"No magic :("<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; string temp; cin>>temp; vector <string> A; A.push_back(temp); for (int i=1;i<n;i++) { cin>>temp; if (temp!=A[A.size()-1]) A.push_back(temp); } cout<<A.size(); return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; vector <string> rotate(vector <string> &grid) { int n = (int)grid.size(); vector <string> res; for (int i = 0; i < n; i++) { string t = ""; for (int j = n - 1; j >= 0; j--) { t += grid[j][i]; } res.push_back(t); } return res; } vector <string> reflection(vector <string> &grid) { int n = (int)grid.size(); vector <string> res; for (int i = n - 1; i >= 0; i--) { res.push_back(grid[i]); } return res; } bool cmp (vector <string> &a, vector <string> b) { int n = (int)a.size(); for (int i = 0; i < n; i++) { if (a[i] != b[i]) { return false; } } return true; } int main() { int n; int idx = 0; while(cin >> n) { vector <string> grid_init(n); vector <string> grid_final(n); for (int i = 0; i < n; i++) { cin >> grid_init[i] >> grid_final[i]; } cout << "Pattern " << ++idx << " was "; if (cmp(grid_init, grid_final)) { cout << "preserved." << endl; continue; } vector <string> new_grid = rotate(grid_init); if (cmp(new_grid, grid_final)) { cout << "rotated 90 degrees." << endl; continue; } new_grid = rotate(new_grid); if (cmp(new_grid, grid_final)) { cout << "rotated 180 degrees." << endl; continue; } new_grid = rotate(new_grid); if (cmp(new_grid, grid_final)) { cout << "rotated 270 degrees." << endl; continue; } new_grid = reflection(grid_init); if (cmp(new_grid, grid_final)) { cout << "reflected vertically." << endl; continue; } new_grid = rotate(new_grid); if (cmp(new_grid, grid_final)) { cout << "reflected vertically and rotated 90 degrees." << endl; continue; } new_grid = rotate(new_grid); if (cmp(new_grid, grid_final)) { cout << "reflected vertically and rotated 180 degrees." << endl; continue; } new_grid = rotate(new_grid); if (cmp(new_grid, grid_final)) { cout << "reflected vertically and rotated 270 degrees." << endl; continue; } cout << "improperly transformed." << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; int res = n; int wra = res; while(wra>=m){ res += wra/m; wra = wra/m + wra%m; } cout<<res<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; set <int> factorize (int n) { set <int> res; for (int i = 1; i <= n; i++) { if (n % i == 0) { res.insert(i); res.insert(n / i); } if (i * i >= n) { break; } } return res; } int main() { int t; cin >> t; int C, R; int idx = 0; while (t--) { cout << "Case #" << ++idx << ":"; cin >> C >> R; if (C == R) { cout << " " << 0 << endl; continue; } set <int> factors = factorize(C - R); for (auto i:factors) { if (C % i == R) { cout << " " << i; } } cout << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; cin>>n; vector<int> arr(n); for (int i = 0; i < n; i++) { ISTREAM>>arr[i]; } int globalmin = INT_MAX; for (int i = 1; i < n-1; i++) { int max = 0; for (int j = 0; j< n-1; j++) { int t = j + 1; if (t == i) { t+=1; } if (arr[t] - arr[j] > max) max = arr[t] - arr[j]; } if (max < globalmin) globalmin = max; } cout<<globalmin<<endl; return 0; }<file_sep>#include "bits/stdc++.h" using namespace std; int main () { int t; cin>>t; int pos,val,suit; while(t--) { int n_shuffle; cin>>n_shuffle; vector <int> cards(52); for (int i = 0;i<52;i++) { cards[i] = i+1; } vector <int> shuffles[n_shuffle]; for (int i = 0;i<n_shuffle;i++) { for (int j = 0;j<52;j++) { cin>>pos; shuffles[i].push_back(pos); } } char st[100]; gets(st); while(gets(st)) { if (!st[0]) break; int k=0; int len = strlen(st); for (int i = 0; i<len; i++) { k *= 10; k += st[i]-48; } k-=1; vector <int> new_cards(52); for (int i = 0;i<52;i++) { pos = shuffles[k][i]; //if (i<pos-1) swap(cards[i],cards[pos-1]); new_cards[i] = cards[pos-1]; } for (int i = 0; i < 52; i++) { cards[i] = new_cards[i]; } } for (int i=0;i<52;i++) { val = (cards[i]-1)%13; suit = (cards[i]-1)/13; if (val == 12) cout<<"Ace"; else if (val == 11) cout<<"King"; else if (val == 10) cout<<"Queen"; else if (val == 9) cout<<"Jack"; else cout<<val+2; if (suit == 0) cout<<" of Clubs"<<endl; else if (suit == 1) cout<<" of Diamonds"<<endl; else if (suit == 2) cout<<" of Hearts"<<endl; else if (suit == 3) cout<<" of Spades"<<endl; } if (t!=0) cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { string s; while(getline(cin,s)) { deque <char> st; int it = 0; bool flag = false; while (it < s.length()) { if ((isalpha(s[it]) || s[it] == '_') ) { st.push_back(s[it]); it += 1; continue; } else if (s[it] == ']') { it+=1; continue; } else if (s[it] == '[' ) { it += 1; string t = ""; while (it < s.length() && (isalpha(s[it]) || s[it] == '_')) { t += s[it]; it += 1; } for (int i = t.length() -1 ;i >= 0;i--) { st.push_front(t[i]); } if (it >= s.length() || s[it] == ']') {it+=1;continue;} else if (s[it] == '[') { continue; } } } for (auto i:st) { cout<<i; } cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n,m; while(cin>>n>>m) { vector <int> arr(n); map<int,vector<int> > dic; for (int i = 0;i<n;i++) { cin>>arr[i]; dic[arr[i]].push_back(i+1); } int k,v; for (int i = 0;i<m;i++) { cin>>k>>v; if (dic.find(v) == dic.end() || k>dic[v].size()) { cout<<0<<endl; } else { cout<<dic[v][k-1]<<endl; } } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int a,b; int lasta,lastb; cin>>lasta>>lastb; int cnt = 1; int maxcnt = 1; for (int i=1;i<n;i++) { cin>>a>>b; if (a==lasta && b == lastb) { cnt++; } else { cnt= 1; } if (cnt>maxcnt) maxcnt = cnt; lasta = a; lastb = b; } cout<<maxcnt<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,b,c,d; cin>>a>>b>>c>>d; if (b>c && d>a && (c+d)>(a+b) && c>0 && d>0 && a%2 == 0) cout<<"Valores aceitos"<<endl; else cout<<"Valores nao aceitos"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; for (int i=0; i<t ; i++) { int n; cin>>n; int mini= 999999999,maxi= 0,temp; for (int j=0;j<n;j++) { cin>>temp; if (temp>maxi) maxi = temp; if (temp<mini) mini = temp; } cout <<(maxi - mini)*2<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int digicnt (int n) { int cnt = 0; while (n!= 0) { n/=10; cnt++; } return cnt; } int main() { int n; int two[] = {1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912}; cin>>n; while (n!= 0) { int max = digicnt(two[2*(n-1)]); for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { int temp = i+j; int spc = max - digicnt(two[temp]); for (int k=0;k<spc;k++) { cout<<" "; } cout<<two[temp]; if (j<n-1) cout<<" "; } cout<<endl; } printf("\n"); cin>>n; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int matrix[101][101]; int a,b; void fill(int i,int j) { if (i > 0 && matrix[i-1][j]!=-1) matrix[i-1][j] += 1; if (j > 0 && matrix[i][j-1]!=-1) matrix[i][j-1] += 1; if (i < a-1 && matrix[i+1][j]!=-1) matrix[i+1][j] += 1; if (j < b-1 && matrix[i][j+1]!=-1) matrix[i][j+1] += 1; if (i > 0 && j < b-1 && matrix[i-1][j+1]!=-1) matrix[i-1][j+1] += 1; if (i < a-1 && j < b-1 && matrix[i+1][j+1]!=-1) matrix[i+1][j+1] += 1; if (i < a-1 && j > 0 && matrix[i+1][j-1]!=-1) matrix[i+1][j-1] += 1; if (i > 0 && j > 0 && matrix[i-1][j-1]!=-1) matrix[i-1][j-1] += 1; } int main() { int counter = 0; cin>>a>>b; while(1) { counter += 1; for (int i = 0;i<a;i++) { for (int j = 0;j<b;j++) { matrix[i][j] = 0; } } string temp; for (int i = 0;i<a;i++) { cin>>temp; for (int j = 0;j<b;j++) { if (temp[j] == '*') matrix[i][j] = -1; } } for (int i = 0;i<a;i++) { for (int j=0;j<b;j++) { if (matrix[i][j] == -1) fill(i,j); } } cout << "Field #" << counter << ":" << endl; for (int i = 0;i<a;i++) { for (int j = 0;j<b;j++) { if (matrix[i][j] == -1) cout<<'*'; else cout<<matrix[i][j]; } cout << endl; } cin >> a >> b; if (a == 0 && b == 0) { break; } else { cout<<endl; } } } <file_sep>#include "bits/stdc++.h" using namespace std; int main() { int k,q,q2; while(scanf("%d",&k)!=EOF) { scanf("%d %d",&q,&q2); int k_i, q_i, q2_i, k_j, q_j, q2_j; if (k == q) { cout<<"Illegal state"<<endl; continue; } q_i = q/8; q_j = q%8; q2_i = q2/8; q2_j = q2%8; k_i = k/8; k_j = k%8; if ((q_i != q2_i && q_j != q2_j) || (q == q2)){ cout<<"Illegal move"<<endl; continue; } if (q_i == q2_i && q_i == k_i) { if (q_j <= k_j && k_j <= q2_j) { cout<<"Illegal move"<<endl; continue; } else if (q2_j <= k_j && k_j <= q_j) { cout<<"Illegal move"<<endl; continue; } } else if (q_j == q2_j && q_j==k_j) { if (q_i <= k_i && k_i <= q2_i) { cout<<"Illegal move"<<endl; continue; } else if (q2_i <= k_i && k_i <= q_i) { cout<<"Illegal move"<<endl; continue; } } if (((q2_i == k_i -1 || q2_i == k_i + 1) && q2_j == k_j) || ((q2_j == k_j -1 || q2_j == k_j + 1) && q2_i == k_i)) { cout<<"Move not allowed"<<endl; continue; } int arr[8][8]; for (int i = 0;i<8;i++) { for (int j = 0;j<8;j++) { arr[i][j] = 0; } } for (int i = 0;i < 8; i++) { arr[i][q2_j] = 1; arr[q2_i][i] = 1; } if ((k_j >0 && arr[k_i][k_j-1] == 0) || (k_j < 7 && arr[k_i][k_j +1]== 0) || (k_i >0 && arr[k_i - 1][k_j] == 0) || (k_i<7 && arr[k_i+1][k_j] == 0)) { cout<<"Continue"<<endl; } else { cout<<"Stop"<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; int p,q; int cnt = 0; cin >> n; for (int i=0;i<n;i++) { cin>>p>>q; if (p<q) { cnt++; } } cout<<cnt; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,s,t; cin>>n>>s>>t; vector <int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } int count = 0; for (int i=0;i<=n;i++) { if (s == t) { break; } s = Arr[s-1]; count++; } if (count == n+1) cout<<"-1"<<endl; else cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool comp(pair <long long int, long long int> a, pair <long long int, long long int> b) { if (a.first < b.first) { return true; } else if (a.first == b.first) { if (abs(a.second) % 2 == 1 && b.second % 2 == 0) { return true; } else if (abs(a.second) % 2 == 1 && abs(b.second) % 2 == 1 && a.second > b.second) { return true; } else if (a.second % 2 == 0 && b.second % 2 == 0 && a.second < b.second) { return true; } else { return false; } } else { return false; } } int main() { long long int N, M; while(cin >> N >> M) { cout << N << " " << M << endl; if (N + M == 0) { break; } vector <pair<long long int, long long int> > arr(N); for (int i = 0; i < N; i++) { cin >> arr[i].second; arr[i].first = arr[i].second % M; } sort(arr.begin(), arr.end(), comp); for (auto i:arr) { cout << i.second << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; bool isPrime ( int n) { bool flag = true; for (int i=2; ; i++) { if ( i*i>n ) { break; } if (n % i == 0 ) { return false; } } return flag; } int main() { int n; cin>>n; if ( n%2 == 0 ) { cout<<"4 "<<n-4<<endl; } else if (n%3 == 0) { cout<<"6 "<<n - 6<<endl; } else { if (isPrime(n-8) ) { cout<<"9 "<<n-9<<endl; } else { cout<<"8 "<<n-8<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int g, p; while(cin >> g >> p) { if (g + p == 0) { break; } vector <vector <int> > races(g, vector <int> (p, 0)); for (int i = 0; i < g; i++) { for (int j = 0; j < p; j++) { cin >> races[i][j]; } } int s; cin >> s; for (int i = 0; i < s; i++) { vector <int> score(p, 0); vector <int> score_prix(p, 0); int k; cin >> k; for (int j = 0; j < k; j++) { cin >> score[j]; } for (int i1 = 0; i1 < g; i1++) { for (int j1 = 0; j1 < p; j1++) { score_prix[j1] += score[races[i1][j1]-1]; } } int maxi = -1; vector <int> winners; for (int i1 = 0; i1 < p; i1++) { if (score_prix[i1] > maxi) { maxi = score_prix[i1]; winners = {i1}; } else if (score_prix[i1] == maxi) { winners.push_back(i1); } } for (int i1 = 0; i1 < (int)winners.size(); i1++) { cout << winners[i1] + 1; if (i1 < (int)winners.size() - 1) cout << " "; } cout << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int d, dd, mm, yyyy; cin >> d >> dd >> mm >> yyyy; while (d + dd + mm + yyyy > 0) { struct tm t = {0}; t.tm_year = yyyy - 1900; t.tm_mon = mm-1; t.tm_mday = dd; t.tm_hour = 0; t.tm_min = 0; t.tm_sec = 0; time_t timeSinceEpoch = mktime(&t); time_t timet = timeSinceEpoch + 24LL*3600LL*d; struct tm* nowStruct = localtime(&timet); int year = nowStruct->tm_year + 1900; int month = nowStruct->tm_mon + 1; int day = nowStruct->tm_mday; cout<<day<<" "<<month<<" "<< year << endl; cin >> d >> dd >> mm >> yyyy; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; for (int i = 0;i<t;i++) { string s; int inv = 0; cin>>s; for (int j = 0;j<s.length()-1;j++) { if (s[j]!=s[j+1]) { inv++; } } if (s[s.length()-1] == '-') inv++; cout<<"Case #"<<i+1<<": "<<inv<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int h1,m1,h2,m2; while (1) { ISTREAM>>h1>>m1>>h2>>m2; if (h1 == 0 && m1 == 0 && h2 == 0 && m2 == 0) { break; } int t1 = h1 * 60 + m1; int t2 = h2*60 + m2; if (t2 - t1 < 0) { cout<<t2 - t1 + 24*60<<endl; } else { cout<<t2 - t1<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int r,c; cin>>r>>c; vector <int> affected_r(r,0); vector <int> affected_c(c,0); for (int i=0;i<r;i++) { string s; cin>>s; for (int j=0;j<c;j++) { if (s[j] == 'S') { affected_c[j] = 1; affected_r[i] = 1; } } } int count_r = 0; int count_c = 0; for (int i=0;i<r;i++) { if (affected_r[i]==0) { count_r++; } } for (int i=0;i<c;i++) { if (affected_c[i]==0) { count_c++; } } cout<<count_r*c + count_c*(r-count_r)<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; vector <string> res; vector <string> result; void fun (int init, vector <string> &dic, unordered_map <char,int> querry) { for (int i = init;i<dic.size();i++) { unordered_map <char,int> temp; string word = dic[i]; for (int j = 0; j < word.size(); j++) { if (temp.find(word[j]) == temp.end()) { temp[word[j]] = 1; } else { temp[word[j]] += 1; } } bool flag = true; for (auto ii:temp) { if (ii.second > querry[ii.first]) { flag = false; break; } } if (flag) { for (auto ii:temp) { querry[ii.first] -= ii.second; } res.push_back(word); fun(i+1, dic, querry); for (auto ii:temp) { querry[ii.first] += ii.second; } res.pop_back(); } } int sum = 0; for (auto i:querry) { sum += i.second; } if (sum == 0) { string r = ""; sort(res.begin(), res.end()); for (int i = 0;i < res.size();i++) { r = r + res[i]; if (i < res.size() -1 ) { r = r + " "; } } result.push_back(r); } } int main () { string s; cin >> s; vector <string> dictionary; while (s != "#") { dictionary.push_back(s); cin >> s; } getline(cin, s); getline(cin, s); while (s != "#") { stringstream ss(s); vector <string> sorted_querry; string t1; while (ss >> t1) { sorted_querry.push_back(t1); } sort(sorted_querry.begin(), sorted_querry.end()); string t = ""; for (int i = 0; i < sorted_querry.size(); i++) { t = t + sorted_querry[i]; if (i < sorted_querry.size() -1) { t = t + " "; } } unordered_map <char, int> querry; for (int i = 0; i < s.length(); i++) { if (s[i] == ' ') continue; if (querry.find(s[i]) == querry.end()) { querry[s[i]] = 1; } else { querry[s[i]] += 1; } } vector <string> dic; for (int i = 0; i < dictionary.size(); i++) { unordered_map <char,int> temp; string word = dictionary[i]; for (int j = 0; j < word.size(); j++) { if (temp.find(word[j]) == temp.end()) { temp[word[j]] = 1; } else { temp[word[j]] += 1; } } bool flag = true; for (auto ii:temp) { if (ii.second > querry[ii.first]) { flag = false; break; } } if (flag) { dic.push_back(word); } } res.clear(); result.clear(); fun(0, dic, querry); sort(result.begin(), result.end()); for (auto i: result) { if (i == t) continue; cout << s << " = " << i << endl; } getline(cin, s); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int n; cin>>n; vector<int> arr(n); vector<int> aux(n,0); for (int i = 0; i < n; i++) { cin>>arr[i]; } int id = 0; sort(arr.begin(), arr.end()); for (int i = 0; i < s.length()/2; i++) { while (id < n && arr[id]<=i+1) id++; if(id%2==1) swap(s[i], s[s.size() - i - 1]); } cout<<s<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; vector <int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } sort(Arr.begin(),Arr.end()); int sum = 0; for (int i= n-1;i>=0;i-=k) { sum += (Arr[i] -1)*2; } cout<<sum<<endl; return 0; }<file_sep>#include<stdio.h> int i; int p(int a,int b) { int j; int temp=a; if (b==0)b=4; for (j=1;j<b;j++) {a*=temp;} return a%10; } int main () { int n; scanf("%d",&n); for (i=0;i<n;i++) { int a,b; scanf("%d %d",&a,&b); if (b==0) printf("1\n"); else if (a==0) printf("0\n"); else printf("%d\n",p(a,b%4)); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int a=0,b=0; if (s[0] == '0') a = 2; else if (s[0] == '1') a = 7; else if (s[0] == '2') a = 2; else if (s[0] == '3') a = 3; else if (s[0] == '4') a = 3; else if (s[0] == '5') a = 4; else if (s[0] == '6') a = 2; else if (s[0] == '7') a = 5; else if (s[0] == '8') a = 1; else if (s[0] == '9') a = 2; if (s[1] == '0') b = 2; else if (s[1] == '1') b = 7; else if (s[1] == '2') b = 2; else if (s[1] == '3') b = 3; else if (s[1] == '4') b = 3; else if (s[1] == '5') b = 4; else if (s[1] == '6') b = 2; else if (s[1] == '7') b = 5; else if (s[1] == '8') b = 1; else if (s[1] == '9') b = 2; cout<<a*b<<endl; return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector <int> A(n); int onec = 0; int twoc = 0; int threec = 0; int fourc = 0; for (int i=0; i<n; i++) { cin>> A[i]; if (A[i] == 1) onec++; else if (A[i] == 2) twoc++; else if (A[i] == 3) threec++; else if (A[i] == 4) fourc++; } int res = 0; res += fourc; if (threec > onec ) { res +=threec; onec =0; } else { res+= threec; onec -=threec; } res += twoc/2; twoc = twoc%2; if (twoc ==1 ) { res+=1; onec = max(0,onec-2); } res+= onec/4; if (onec%4 >0) res+=1; cout<<res; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif string s; int cnt = 0; while (1) { ISTREAM>>s; cnt++; if (s == "#") break; if (s == "HELLO") cout<<"Case "<<cnt<<": ENGLISH"<<endl; else if (s == "HOLA") cout<<"Case "<<cnt<<": SPANISH"<<endl; else if (s == "HALLO") cout<<"Case "<<cnt<<": GERMAN"<<endl; else if (s == "BONJOUR") cout<<"Case "<<cnt<<": FRENCH"<<endl; else if (s == "CIAO") cout<<"Case "<<cnt<<": ITALIAN"<<endl; else if (s == "ZDRAVSTVUJTE") cout<<"Case "<<cnt<<": RUSSIAN"<<endl; else cout<<"Case "<<cnt<<": UNKNOWN"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int div[] = {4,7,47,74,477,474,747,774,447,744,444,777}; for (int i=0; i<12 ; i++ ) { if (n % div[i] == 0) { cout<<"YES\n"; return 0; } } cout<<"NO\n"; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { int s,n; cin>>s>>n; vector < pair<int,int> > dragon(n); for (int i=0;i<n ; i++) { cin>>dragon[i].first>>dragon[i].second; } sort(dragon.begin(),dragon.end()); bool flag = true; for (int i=0;i<n;i++) { if (dragon[i].first >= s) { cout<<"NO"<<endl; flag = false; break; } else { s+=dragon[i].second; } } if (flag) { cout<<"YES"<<endl; } return 0; }<file_sep>#include<stdio.h> int main (void) { long long int n; scanf("%lld",&n); if ((n&(n-1))==0)printf("TAK\n"); else printf("NIE\n"); return 0; } <file_sep>#include<iostream> #include<cstring> using namespace std; int main (void) { int i; int n,k,t; int count; int anum; cin>>n>>k; int a[11]; int cnt=0; for (i=0;i<n;i++) { count=0; cin>>anum; for (int j =0; j<k+1;j++) a[j]=0; while(anum!=0) { t=anum%10; if (t<=k && a[t]==0) {count++;a[t]=1;} anum/=10; } if (count==k+1) cnt++; } cout<<cnt<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; int w, n; while (t--) { cin >> w>> n; int x, ww; int total_dist = 0; int truck_weight = 0; int idx=0; for (int i = 0;i <n;i++) { cin >> x >> ww; assert (ww <= w); if (truck_weight + ww < w) { truck_weight += ww; } else if (truck_weight + ww == w) { truck_weight = 0; if (i < n-1) total_dist += x*2; } else { total_dist += x*2; truck_weight = ww; if (ww == w && i < n-1) { truck_weight = 0; total_dist += x*2; } } } cout<<total_dist + x*2<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; while (1) { cin>>n; if (n == 0) break; vector < vector < vector < int> > > states; vector < vector < vector < int> > > moves; vector < vector<int> > grid(n, vector <int> (n,0)); vector < vector<int> > grid_l90(n, vector <int> (n,0)); vector < vector<int> > grid_r90(n, vector <int> (n,0)); vector < vector<int> > grid_180(n, vector <int> (n,0)); states.push_back(grid); int a,b,a_l90,b_l90,a_r90,b_r90,a_180,b_180; char c; bool winner = false; for (int i = 0;i<2*n;i++) { cin>>a>>b>>c; a--;b--; a_l90 = n-b-1; b_l90 = a; a_r90 = b; b_r90 = n-a-1; a_180 = n-a-1; b_180 = n-b-1; if (c == '+') { grid[a][b] = 1; grid_l90[a_l90][b_l90] = 1; grid_r90[a_r90][b_r90] = 1; grid_180[a_180][b_180] = 1; } else if (c == '-') { grid[a][b] = 0; grid_l90[a_l90][b_l90] = 0; grid_r90[a_r90][b_r90] = 0; grid_180[a_180][b_180] = 0; } if (winner == false) { for (int j = 0;j<states.size();j++) { bool flag = true; for (int k = 0;k<n;k++) { for (int l = 0;l<n;l++) { if (states[j][k][l] != grid[k][l]) { flag = false; } } } if (flag == true) { if (i%2 == 0) { cout<<"Player 2 wins on move "<<i + 1<<endl; } else { cout<<"Player 1 wins on move "<<i + 1<<endl; } winner = true; break; } } } states.push_back(grid); states.push_back(grid_l90); states.push_back(grid_r90); states.push_back(grid_180); } if (winner == false) { cout<<"Draw"<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; vector <string > chomp(string line) { ss.str(""); ss.clear(); ss.str(line); vector <string> res; string word; while(ss >> word) { res.push_back(word); } return res; } int main () { int t; int size_x, size_y; cin >> t; while (t--) { int n; cin >> n; string sentence; vector < vector<string> > slide; getline(cin, sentence); for (int i = 0; i < n; i++) { getline(cin, sentence); vector <string> words = chomp(sentence); slide.push_back(words); } cin >> size_x >> size_y; int font = 28; bool doable = false; while (font > 7) { doable = true; int line = 0; int y_dim = size_y; int x_dim = size_x; bool line_first_word; for (int i = 0; i < (int)slide.size(); i++) { line_first_word = true; for (int j = 0; j < (int)slide[i].size(); j++) { string w = slide[i][j]; if (!line_first_word) { x_dim -= font; } if (font > y_dim || font*(int)w.length() > size_x) { doable = false; break; } if ((font * (int)w.length()) > x_dim) { x_dim = size_x; line += 1; y_dim -= font; line_first_word = true; } if (font > y_dim) { doable = false; break; } if (font * (int)w.length() <= x_dim) { x_dim -= font*(int)w.length(); line_first_word = false; } } x_dim = size_x; y_dim -= font; if (y_dim < 0 || x_dim <0) { doable = false; } if (!doable) break; } if (doable) { break; } font -= 1; } if (doable) { cout << font << endl; } else { cout << "No solution" << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; string s[n]; for (int i= 0;i<n;i++) { cin>>s[i]; } for (int i=0;i<n;i++) { for (int j=0;j<m;j++) { if (s[i][j] == '.') { if ((i+j)%2 == 0) s[i][j] = 'W'; else s[i][j] = 'B'; } } } for (int i=0;i<n;i++) { cout<<s[i]<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif string s; int cnt = 0; while(1) { ISTREAM>>s; cnt++; if (s == "*") { break; } if (s == "Hajj") cout<<"Case "<<cnt<<": Hajj-e-Akbar"<<endl; else if (s == "Umrah") cout<<"Case "<<cnt<<": Hajj-e-Asghar"<<endl; } return 0; }<file_sep>#include<stdio.h> #include<math.h> int main() { int n; float ans; scanf("%d",&n); while (n!=0){ ans=n*(n/M_PI)/2; printf("%.2f\n",ans); scanf("%d",&n); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,d; cin>>n>>d; int arr[n]; for (int i=0;i<n;i++ ) { cin>>arr[i]; } int sum = 0; for (int i=0;i<n;i++) { sum+=arr[i]; } int time = sum + (n-1)*10; if (time > d) cout<<"-1"; else cout<< (d - sum)/5; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; bool op(char c) { if (c == '+' || c == '-' || c == '*' || c == '/' || c == '@') { return true; } return false; } int main() { string inp; bool flag = true; while(cin >> inp) { if (flag == false) { cout << endl; } if (flag == true) { flag = false; } string resister = ""; string operand = ""; char operatorr; int stk = 0; for (int i = 0; i < inp.length(); i++) { if (op(inp[i])) { operatorr = inp[i]; if (operatorr == '+') { if (resister != "" && operand != "") { cout << "A " << operand << endl; operand = ""; } else if (resister != "" && operand == "") { cout << "A $" << --stk << endl; } } else if (operatorr == '-') { if (resister != "" && operand != "") { cout << "S " << operand << endl; operand = ""; } else if (resister != "" && operand == "") { cout << "N" << endl; cout << "A $" << --stk << endl; } } else if (operatorr == '/') { if (resister != "" && operand != "") { cout << "D " << operand <<endl; operand = ""; } else if (resister != "" && operand == "") { cout << "ST $" << stk++ << endl; cout << "L $" << stk - 2 << endl; cout << "D $" << stk - 1 << endl; --stk;--stk; } } else if (operatorr == '*') { if (resister != "" && operand != "") { cout << "M " << operand << endl; operand = ""; } else if (resister != "" && operand == "") { cout << "M $" << --stk << endl; } } else if (operatorr == '@') { if (resister != "" && operand == "") { cout << "N" << endl; } else if (resister != "" && operand != "") { cout << "ST $" << stk++ << endl; resister = operand; cout << "L " << resister << endl; operand = ""; cout << "N" <<endl; } } } else { if (resister == "" && operand == "") { resister = inp[i]; cout << "L " << resister << endl; } else if (resister != "" && operand == "") { operand = inp[i]; } else if (resister != "" && operand != "") { cout << "ST $" << stk++ << endl; resister = operand; operand = inp[i]; cout << "L " << resister << endl; } } } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin >> s; int small = 0; int big = 0; for (int i=0;i<s.length();i++) { if (s[i]>=97 and s[i]<=122) { small++; } else if (s[i]>=65 and s[i]<=90) { big++; } } if (small<big) { for (int i=0;i<s.length();i++) { if (s[i]>=97 and s[i]<=122) { s[i]-=32; } } } else if (small>=big) { for (int i=0;i<s.length();i++) { if (s[i]>=65 and s[i]<=90) { s[i]+=32; } } } cout<<s<<endl; return 0; }<file_sep>#include<iostream> using namespace std; int main() { int n,p; cin >> n; p = n/2; for (int i=0 ; i < p ; i++ ) { for (int j=i ; j < p ; j++ ) { cout<<"*"; } for (int j=0; j< 2*i+1; j++) { cout<<"D"; } for (int j=i ; j < p ; j++ ) { cout<<"*"; } cout<<endl; } for (int j=0 ; j< n ; j++ ) { cout<<"D"; } cout <<endl; for (int i=0 ; i < p ; i++ ) { for (int j=0 ; j <= i ; j++ ) { cout<<"*"; } for (int j=0; j<2*p - 2*i - 1; j++) { cout<<"D"; } for (int j=0 ; j<= i ; j++ ) { cout<<"*"; } cout<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int i = 1,j = 60; while (j>=0) { cout<<"I="<<i<<" J="<<j<<endl; j-=5; i+=3; } return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; int main() { int n; cin >>n; for (int i = 0; i < n; i++) { for (int j=n-i;j>0;j--) { cout<<" "; } cout<<"0"; for (int j=1;j<=i;j++) { cout<<" "<<j; } if (i>0) cout<<" "; for (int j=i-1; j>0; j--) { cout<<j<<" "; } if (i>0) cout<<"0"; cout<<endl; } for (int i = 0; i <=n ; i++) { for (int j = 0; j < i; j++ ) { cout<<" "; } cout<<"0"; for (int j = 1; j<=n-i ; j++) { cout<<" "<<j; } if (i<n) cout<<" "; for (int j = n-i-1 ; j>0 ; j--) { cout<<j<<" "; } if (n-i>0) cout<<"0"; cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,b,c; cin>>a>>b; int t[6]; t[0] = b-a; t[1] = t[0] - b; t[2] = t[1] - t[0]; t[3] = -t[0]; t[4] = -t[1]; t[5] = -t[2]; cin>>c; int res; if (c == 1) { res=a; } else if (c == 2) { res = b; } else { res = t[(c-3)%6]; } while (res<1000000007) res+= 1000000007; cout<<res%1000000007<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int it = 0; int i; for (i=0;i<s.length();i++) { if (s[i]=='0') { it = i; break; } } for (i=0;i<s.length();i++) { if (i == it) continue; cout<<s[i]; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n; vector <int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } cin>>m; vector <int> Brr(m); for (int i=0;i<m;i++) { cin>>Brr[i]; } int maxi = -1; int maxi_count = 0; for (int i=0;i<n;i++) { for (int j=0;j<m;j++) { if (Brr[j]%Arr[i] == 0) { if (Brr[j]/Arr[i] > maxi ) { maxi = Brr[j]/Arr[i]; maxi_count = 1; } else if (Brr[j]/Arr[i] == maxi) { maxi_count++; } } } } cout<<maxi_count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int m,n; int wall_cost; int bumper_count; int x_pos, y_pos, val, cost; int ball_points; int total_points = 0; scanf("%d %d",&m, &n); scanf("%d",&wall_cost); scanf("%d",&bumper_count); vector < vector<int> > grid(n, vector <int> (m,0)); vector < vector<int> > grid_val(n, vector <int> (m,0)); vector < vector<int> > grid_cost(n, vector <int> (m,0)); for (int i = 0;i<bumper_count;i++) { scanf("%d %d %d %d",&x_pos,&y_pos,&val,&cost); x_pos-=1;y_pos-=1; grid[y_pos][x_pos] = 1; grid_val[y_pos][x_pos] = val; grid_cost[y_pos][x_pos] = cost; } while (scanf("%d",&x_pos)!=EOF) { scanf("%d %d %d",&y_pos,&val,&cost); x_pos-=1;y_pos-=1; ball_points = 0; while(1) { if (val == 0) { if (x_pos < m - 2 && grid[y_pos][x_pos+1]==0) { x_pos+=1; cost-=1; } else if (x_pos == m-2){ val=3; cost -= wall_cost; cost -= 1; } else if (grid[y_pos][x_pos+1]!=0) { val=3; cost -=1; if (cost > 0) { ball_points += grid_val[y_pos][x_pos+1]; cost -= grid_cost[y_pos][x_pos+1]; } } } else if (val == 1) { if (y_pos < n - 2 && grid[y_pos+1][x_pos]==0) { y_pos+=1; cost-=1; } else if (y_pos == n-2){ val=0; cost -= wall_cost; cost -= 1; } else if (grid[y_pos+1][x_pos]!=0) { val=0; cost -= 1; if (cost > 0) { ball_points += grid_val[y_pos+1][x_pos]; cost -= grid_cost[y_pos+1][x_pos]; } } } else if (val == 2) { if (x_pos > 1 && grid[y_pos][x_pos-1]==0) { x_pos-=1; cost-=1; } else if (x_pos == 1){ val=1; cost -= wall_cost; cost -= 1; } else if (grid[y_pos][x_pos-1]!=0) { val=1; cost -= 1; if (cost > 0) { ball_points += grid_val[y_pos][x_pos-1]; cost -= grid_cost[y_pos][x_pos-1]; } } } else if (val == 3) { if (y_pos > 1 && grid[y_pos-1][x_pos]==0) { y_pos-=1; cost-=1; } else if (y_pos == 1){ val=2; cost -= wall_cost; cost -= 1; } else if (grid[y_pos-1][x_pos]!=0) { val=2; cost -= 1; if (cost > 0) { ball_points += grid_val[y_pos-1][x_pos]; cost -= grid_cost[y_pos-1][x_pos]; } } } if (cost<=0) { printf("%d\n",ball_points); total_points+=ball_points; break; } } } printf("%d\n",total_points); return 0; }<file_sep>#print reduce(lambda x,y:x+y,filter(lambda x:x>0,[input()for _ in range(input())])) s=0 for _ in range(input()): k=input() if k>0: s+=k print s <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; vector <int> A(n); for (int i=0;i<n;i++) { cin>>A[i]; } sort(A.begin(),A.end()); int sum = 0; for (int i = 0;i<m;i++) { if (A[i]<0) { sum+=A[i]; } else break; } cout<<(-1)*sum<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,b,c; cin>>a>>b>>c; int c1 = sqrt((b*c)/a); int b1 = b/c1; int a1 = a/b1; cout<<4*(a1 + b1+ c1)<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; long long int n = s.length(); vector <long long int> pos; for (long long int i=0;i<=n-4;i++) { if (s[i] == 'b' && s[i+1]== 'e' && s[i+2] == 'a' && s[i+3]=='r') { pos.push_back(i); } } long long int prev = 0; long long int sum = 0; for (int i=0;i<pos.size();i++) { sum += (pos[i]-prev+1)*(n - (pos[i]+3)); prev = pos[i]+1; } cout<<sum<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,t; cin>>n; vector<int> arr(101,0); for (int i = 1; i < n+1; i++) { for (int j = 1; j < n+1; j++) { cin>>t; if (t==1) { arr[i] = 1; } else if (t == 2) { arr[j] = 1; } else if (t == 3) { arr[i] = 1; arr[j] = 1; } } } int count = 0; for (int i = 1;i<n+1;i++) { if (arr[i] == 0) { count++; } } cout<<count<<endl; for (int i = 1;i<n+1;i++) { if (arr[i] == 0) { cout<<i<<" "; } } if (count != 0) { cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; for (int i = 0;i<n;i++) { string s; cin>>s; int month = (s[0]-48)*10 + (s[1] - 48); int day = (s[2]-48) * 10 + (s[3] - 48); int year = (s[4]-48) *1000 + (s[5] - 48)*100 + (s[6] - 48) *10 + (s[7]-48); struct tm t = {0}; t.tm_year = year; t.tm_mon = month - 1; t.tm_mday = day; t.tm_hour = 0; t.tm_min = 0; t.tm_sec = 0; time_t timeSinceEpoch = mktime(&t); time_t timet = timeSinceEpoch + 24LL*3600LL*280; struct tm* nowStruct = localtime(&timet); day = nowStruct->tm_mday; month = nowStruct->tm_mon + 1; year = nowStruct->tm_year; printf("%d %02d/%02d/%04d ",i+1,month,day,year); if (month == 1) { if (day >= 21) { cout<<"aquarius"<<endl; } else { cout<<"capricorn"<<endl; } } else if (month == 2) { if (day >= 20) { cout<<"pisces"<<endl; } else { cout<<"aquarius"<<endl; } } else if (month == 3) { if (day >= 21) { cout<<"aries"<<endl; } else { cout<<"pisces"<<endl; } } else if (month == 4) { if (day >= 21) { cout<<"taurus"<<endl; } else { cout<<"aries"<<endl; } } else if (month == 5) { if (day >= 22) { cout<<"gemini"<<endl; } else { cout<<"taurus"<<endl; } } else if (month == 6) { if (day >= 22) { cout<<"cancer"<<endl; } else { cout<<"gemini"<<endl; } } else if (month == 7) { if (day >= 23) { cout<<"leo"<<endl; } else { cout<<"cancer"<<endl; } } else if (month == 8) { if (day >= 22) { cout<<"virgo"<<endl; } else { cout<<"leo"<<endl; } } else if (month == 9) { if (day >= 24) { cout<<"libra"<<endl; } else { cout<<"virgo"<<endl; } } else if (month == 10) { if (day >= 24) { cout<<"scorpio"<<endl; } else { cout<<"libra"<<endl; } } else if (month == 11) { if (day >= 23) { cout<<"sagittarius"<<endl; } else { cout<<"scorpio"<<endl; } } else if (month == 12) { if (day >= 23) { cout<<"capricorn"<<endl; } else { cout<<"sagittarius"<<endl; } } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; if (n <= 2) { cout<<-1<<endl; return 0; } for (int i=n;i>0;i--) { cout<<i<<" "; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { float temp; for (int i=0;i<100;i++) { cin>>temp; if (temp<=10) { cout<<"A["<<i<<"] = "<<temp<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int palindrome(int n) { string s = ""; while (n != 0) { s += n%10 + 48; n/=10; } for (int i = 0;i< s.length();i++) { if (s[i] != s[s.length() -1 -i]) return false; } return true; } int main () { int n; cin >> n; while (n--) { string s; cin>>s; int num = (s[0]-48)*1000 + (s[1]-48)*100 + (s[3]-48)*10 + (s[4] - 48) + 1; if (num % 100 == 60) { num += 40; } if (num/100 == 24) { num = 0; } while (!palindrome(num)) { num+=1; if (num%100 == 60) { num += 40; } if (num/100 == 24) { num = 0; } } if (num < 10) cout<<"00:0"<<num<<endl; else if (num < 100) cout<<"00:"<<num<<endl; else if (num < 1000) { cout<<"0"<<num/100<<":"; if (num%100 < 10) cout<<"0"; cout<<num%100<<endl; } else { cout<<num/100<<":"; if (num%100 <10) cout<<"0"; cout<<num%100<<endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif string hex(int n) { int cnt = 0; string res = ""; while (n!=0) { cnt++; if (n%16<10) { res+=n%16 +48; } else if (n%16 == 10) { res+='A'; } else if (n%16 == 11) { res+='B'; } else if (n%16 == 12) { res+='C'; } else if (n%16 == 13) { res+='D'; } else if (n%16 == 14) { res+='E'; } else if (n%16 == 15) { res+='F'; } n/=16; } if (cnt == 1) res+='0'; if (cnt == 0) res += "00"; return res; } int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; string s; for (int i = 0; i < n; i++) { ISTREAM>>s; cout<<"Case "<<i+1<<": "; vector<int> p(100,0); int it = 0; for (unsigned int j = 0; j < s.length(); j++) { if (s[j]=='.') { // cout<<p[it]<<" "; continue; } else if (s[j] == '<') { it--; if (it<0) it+= 100; } else if (s[j] == '>') { it++; it%=100; } else if (s[j] == '+') { p[it]++; p[it]%=256; } else if (s[j] == '-') { p[it]--; if (p[it]<0) p[it] += 256; } } string s1; for (int j = 0;j<99;j++) { s1 = hex(p[j]); cout<<s1[1]<<s1[0]<<" "; } s1 = hex(p[99]); cout<<s1[1]<<s1[0]<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int i = 0; int n; cin>>n; for (int i=0;i<1000;i++) { cout<<"N["<<i<<"] = "<<i%n<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; vector <int> A(m); for (int i=0;i<m;i++) { cin>>A[i]; } sort(A.begin(),A.end()); int mindiff = INT_MAX; for (int i=0;i+n-1<m;i++) { if (A[i+n-1]-A[i] < mindiff) mindiff = A[i+n-1]-A[i]; } cout<<mindiff<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; int low = 1; int high = k + 1; while (1) { cout<<low<<" "; cout<<high<<" "; high--; low++; if (low == high) { cout<<low<<" "; break; } else if (low > high) break; //if (low == high) break; } for (int i=k+2;i<=n;i++) { cout<<i<<" "; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; set <int> incorrect; for (int i = 1; i <= n; i++) { incorrect.insert(i); } set <int> correct; for (int i = 0; i < k; i++) { int cnt; cin >> cnt; char sign; vector <int> weights(cnt*2); for (int i = 0; i< 2*cnt; i++) { cin >> weights[i]; } cin >> sign; if (sign == '=') { for (auto i:weights) { correct.insert(i); } } } for (auto i: correct) { incorrect.erase(i); } if ((int)incorrect.size() == 1) { cout<<*incorrect.begin()<<endl; } else { cout<<0<<endl; } if (t > 0) { cout << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main (){ int n; cin>>n; vector<int> arr(n); for (int i = 0; i < n; i++) { cin>>arr[i]; } int cost = arr[0] + 1; for (int i = 1; i < n; i++) { cost+= abs(arr[i]-arr[i-1])+2; } cout<<cost<<endl; return 0; }<file_sep>#/usr/bin/python def check(s,s1): if(s=='+' and s1 in list('-*/^')): return -1 elif(s == '-' and s1 in list('*/^')): return -1 elif(s == '*' and s1 in list('/^')): return -1 elif(s=='/' and s1 in list('^')): return -1 else: return 1 def fun(s): stack=[] que=[] for i in s: if i in list('abcdefghijklmnopqrstuvwxyz'): stack.append(i) elif i in list('+-*/^'): if(que.count('+')==0 and que.count('-')==0 and que.count('*')==0 and que.count('/')==0 and que.count('^')==0): que.append(i) else: t1=check(i,que[-1]) if(t1<=0): stack.append(i) else: que.append(i) elif i in list('('): que.append(i) elif i in list(')'): k=que.pop() while(k!='('): stack.append(k) k=que.pop() while(len(que)!=0): k=que.pop() stack.append(k) ans="".join(stack) print(ans) n=raw_input() n=int(n) for cnt in range(0,n): s=raw_input() fun(s) <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s1,s2; cin>>s1>>s2; for (int i=0;i<s1.length();i++) { int c1 = s1[i] - 48; int c2 = s2[i] - 48; cout<<(c1+c2)%2; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif string s[16] = {"Happy", "birthday", "to", "you","Happy", "birthday","to","you","Happy", "birthday","to","Rujia","Happy","birthday","to","you"}; int n; ISTREAM>>n; vector<string> names(n); for (int i = 0; i < n; i++) { ISTREAM>>names[i]; } int cnt = 0; int j = 0; while (j<n) { cout<<names[j]<<": "<<s[cnt]<<endl; cnt++; j++; cnt%=16; } j = 0; while (cnt < 16) { cout<<names[j]<<": "<<s[cnt]<<endl; cnt++; j++; j%=n; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector <int> arr(n); for (int i = 0; i < n; i++) { cin >> arr[i]; } int timer = 0; queue <pair<int, int> > qq; for (int i = 0; i < n; i++) { qq.push(make_pair(arr[i], i)); } sort(arr.begin(), arr.end()); while (true) { pair <int, int> temp = qq.front(); qq.pop(); if (temp.first == arr.back()) { timer += 1; if (temp.second == m) { break; } arr.pop_back(); } else { qq.push(temp); } } cout << timer << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; while(t--) { int n; cin>>n; vector <int> data(n); map<int,int> dic; int maxi = 0; for (int i = 0; i<n;i++) { cin>>data[i]; } int aux = 0; int cnt = 0; for (int i = 0;i<n;i++) { if (dic.find(data[i]) == dic.end()) { cnt++; dic[data[i]] = i; if (cnt > maxi) { maxi = cnt; } } else { for (int j = aux;j<dic[data[i]];j++) { dic.erase(data[j]); cnt--; } aux = dic[data[i]] + 1; dic.erase(dic[data[i]]); dic[data[i]] = i; } } cout<<maxi<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector< pair<int,int> > arr(n); for (int i = 0; i < n; i++) { cin>>arr[i].first; arr[i].second = i; } sort(arr.rbegin(), arr.rend()); vector<int> res(n); res[arr[0].second] = 1; for (int i = 1; i < n; i++) { if (arr[i].first == arr[i-1].first) { res[arr[i].second] = res[arr[i-1].second]; } else { res[arr[i].second] = i+1; } } for (int i = 0;i<n;i++) cout<<res[i]<<" "; cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,d; int c; cin>>n>>d; vector <int > arr(n); for (int i=0;i<n;i++) { cin>>arr[i]; } sort(arr.begin(),arr.end()); cin>>c; int i=0; int profit = 0; for (i=0;i<min(c,n);i++) { profit+=arr[i]; } if (c>n) { profit -= d*(c-n); } cout<<profit<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int a,b; ISTREAM>>a>>b; while (a!=0 && b!=0) { if (a>0 && b>0 ) cout<<"primeiro"<<endl; else if (a<0 && b<0) cout<<"terceiro"<<endl; else if (a>0 && b<0) cout<<"quarto"<<endl; else if (a<0 && b>0) cout<<"segundo"<<endl; ISTREAM>>a>>b; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int p, c; int idx = 0; while (cin >> p >> c) { if (p + c == 0) break; unordered_map <int, int> ignore; unordered_map <int, int> urgent; deque <int> qq; for (int i = 1; i <= min(p, c); i++) { qq.push_back(i); } char command; int value; cout << "Case " << ++idx << ":" << endl; bool flag = false; for (int i = 0; i < c; i++) { cin >> command; if (command == 'E') { cin >> value; qq.push_front(value); ignore[value] += 1; urgent[value] = 1; } else { while (ignore[qq.front()] > 0 && urgent[qq.front()] == 0) { ignore[qq.front()] -= 1; qq.pop_front(); } urgent[qq.front()] = 0; cout << qq.front() << endl; qq.push_back(qq.front()); qq.pop_front(); } } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { vector <float> Arr(3); vector <float> Brr(3); cout<<fixed<<setprecision(1); for (int i=0;i<3;i++) { cin>>Arr[i]; Brr[i] = Arr[i]; } sort(Arr.begin(), Arr.end()); if (Arr[0]+Arr[1]>Arr[2]) { cout<<"Perimetro = "<<Arr[0]+ Arr[1] + Arr[2]<<endl; } else { cout<<"Area = "<<(Brr[0] + Brr[1])*Brr[2]/2<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; while(cin >> n) { if (n == 0) { break; } queue <int> cards; for (int i = 1; i <= n; i++) { cards.push(i); } vector <int> discards; while(cards.size() >= 2) { discards.push_back(cards.front()); cards.pop(); cards.push(cards.front()); cards.pop(); } cout << "Discarded cards:"; for (int i = 0; i < (int)discards.size(); i++) { cout << " " << discards[i]; if (i < (int)discards.size() - 1) { cout << ","; } } cout << endl; cout << "Remaining card: "; cout << cards.front() << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; long long int rev(long long int n) { long long int res = 0LL; while(n!=0LL) { res = res*10LL + n%10LL; n/=10LL; } return res; } bool palin(long long int n) { vector <int> temp; while(n != 0) { temp.push_back(n%10LL); n/=10LL; } for (int i = 0;i<temp.size();i++) { if (temp[i] != temp[temp.size()-1-i]) { return false; } } return true; } int main () { int t; cin>>t; while(t--) { long long int n; cin>>n; int cnt = 0; do { n = n + rev(n); cnt++; if (cnt> 1000) { break; } } while (!palin(n)); cout<<cnt<<" "<<n<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int k; string s; cin>>k; cin>>s; vector <string> res; int i = 0; int cnt = 0; vector <int> hs(26); while (i<s.length()) { string t = ""; t+=s[i]; hs[s[i]-97] = 1; i++; while(i<s.length() && hs[s[i]-97]==1) { t+=s[i]; i++; } res.push_back(t); cnt++; } if (cnt < k) { cout<<"NO"<<endl; return 0; } cout<<"YES"<<endl; for (int i = 0;i<k-1;i++) { cout<<res[i]<<endl; } for (int i = k-1;i<res.size();i++) { cout<<res[i]; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { set <int> a; set <int> b; int n; scanf ("%d",&n); int p; for (int i=0;i<n;i++) { scanf("%d",&p); a.insert(p); int n1; scanf("%d",&n1); for (int j=0;j<n1;j++) { scanf ("%d",&p); b.insert(p); } } set <int> result; set_difference(b.begin(), b.end(), a.begin(), a.end(),inserter(result, result.end())); cout<<result.size()<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; int counter = 1; for (int i=0;i<n;i++) { cout<<counter<<" "<<counter+1<<" "<<counter+2<<" PUM"<<endl; counter+=4; } return 0; } <file_sep>#include<stdio.h> #include<string.h> int main() { char s[110]; int a[110]; a[0]=0; int i; while (scanf("%s",&s)!=EOF) { int len=strlen(s); if(len==1 && (s[0]=='1'|| s[0]=='0')) {printf("%s\n",s); continue;} for (i=0;i<len;i++) { a[i+1]=s[i]-'0'; } int t=len; int car=0; int temp; while (a[t]==0) { a[t]=9; t-=1; } a[t]-=1; t=len; while (t!=0) { temp=(a[t]*2)+car; a[t]=temp%10; car=temp/10; t--; } a[t]+=car; for (i=0;i<=len;i++) { if (a[i]==0 && i==0 ) continue; printf("%d",a[i]); } printf("\n"); a[0]=0; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; cin>>n; string s; cin>>s; int z = 0; int o = 0; for (int i = 0;i< s.length(); i++ ) { if (s[i] == '0') z++; else o++; } cout<<abs(o-z)<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; string s; cin>>s; for (int i=0;i<n;i++) { if (s[i]!='4' && s[i]!='7') { cout<<"NO"<<endl; return 0; } } int sum1 = 0; int sum2 = 0; for (int i=0;i<n/2;i++) { sum1+= (s[i] - 48); } for (int i=n/2;i<n;i++) { sum2+= (s[i] - 48); } if (sum1!=sum2) { cout<<"NO"<<endl; } else { cout<<"YES"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int temp; ISTREAM>>temp; int sum = 0; int cnt = 0; while(temp>=0) { sum+=temp; cnt++; ISTREAM>>temp; } cout<<fixed<<setprecision(2); cout<<sum/(cnt*1.0)<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { vector <int> moves; int ele; cin>>ele; while (ele != 0) { moves.push_back(ele); cin>>ele; } int p_count = 0; cin>>p_count; while (p_count != 0) { vector <int> player(p_count,0); vector <int> jumps(101,0); vector <int> skip(101,0); int a,b; cin>>a>>b; while (a != 0 || b != 0) { jumps[a] = b; cin>>a>>b; } for (int i = 0;i<101;i++) { if (jumps[i] == 0) { jumps[i] = i; } } cin>>ele; while (ele != 0) { if (ele > 0) { skip[ele] = 1; } else if (ele < 0){ skip[-1*ele] = -1; } cin>>ele; } int cnt = 0; vector <int> ski(p_count,0); vector <int> stay(p_count,0); bool flag = true; int p = 0; int move; for (int i = 0;i<moves.size();i++) { if (p == p_count) p = 0; if (ski[p] == 1) { ski[p] = 0; p+=1; continue; } move = player[p] + moves[i]; if (skip[move] == 1 && stay[p] == 0) { stay[p] = 1; } else if (skip[move] == 1 && stay[p] == 1) { stay[p] = 0; } if (skip[move] == -1) { ski[p] = 1; } if (move > 100) { move -= moves[i]; } move = jumps[move]; if (move == 100) { cout<<p+1<<endl; break; } player[p] = move; if (stay[p]!=1) p+=1; } cin>>p_count; } }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { stack<int> S; int T; scanf("%d",&T); int comm; int x; while(T--) { scanf("%d",&comm); switch(comm){ case 1: if (S.empty()) printf("1\n"); else printf("0\n"); break; case 2: scanf("%d",&x); S.push(x); break; case 3: printf("%d\n",S.top()); break; case 4: S.pop(); break; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int x,y; cin>>x>>y; if (x>y) swap(x,y); for (int i = 0;i<y;i++) { int t1 = i*5 + 2; int t2 = i*5 + 3; if (t1>x && t1 <y) { cout<<t1<<endl; } if (t2>x && t2 <y) { cout<<t2<<endl; } if (t2>y) break; } return 0; } <file_sep>#include<stdio.h> #include<string.h> int len; int k; void copy (char *s, int len) { for (k=len/2 -1; k>=0 ;k--) { s[len-1-k]=s[k]; } } int less(char *s,int len) { int flag=0; for (k=len/2 -1; k>=0 ;k--) { if (s[k]==s[len-k-1]) continue; else if (s[k] > s[len-k-1]) {flag = 1;break; } else if ( s[k] < s[len-k-1]) {flag = 2;break; } } return flag; } int inc(char *s, int len) { k=len/2; s[k-1]+=1; int flag=0; while(s[k-1]==':'){ if (k==1) {flag=1; break;} s[k-1]='0'; k-=1; s[k-1]+=1; } return flag; } int inco(char *s, int len) { k=len/2; s[k]+=1; int flag=0; while(s[k]==':'){ if (k==0) {flag=1; break;} s[k]='0'; k-=1; s[k]+=1; } return flag; } void zero(char *s,int len){ s[0]='1'; for (k=0;k<len;k++) { s[k+1]='0'; } s[k]='1'; s[k+1]='\0'; } int palin(char *s,int len) { } int main() { char a[1000000]; int n,i; int len; scanf("%d",&n); int parity=0; int flag9=0; for (i=0;i<n;i++) { scanf("%s",&a); len=strlen(a); switch (len%2) { case 0: parity=less(a,len); if (parity==1) { copy(a,len); } else if (parity ==2 ) { flag9=inc(a,len); if (flag9==1) { zero(a,len);} else { copy(a,len); } } else if (parity ==0 ) { flag9=inc(a,len); if (flag9==1) { zero(a,len);} else { copy(a,len); } } printf("%s\n",a); break; case 1: parity=less(a,len); if (parity==1) { copy(a,len); } else if (parity ==2 ) { flag9=inco(a,len); if (flag9==1) { zero(a,len);} else { copy(a,len); } } else if (parity ==0 ) { flag9=inco(a,len); if (flag9==1) { zero(a,len);} else { copy(a,len); } } printf("%s\n",a); break; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int a,b; cin>>a>>b; long long int counter = 0; while (a != 0 ) { if (a<b) swap(a,b); counter += a/b; a = a%b; } cout<<counter<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; if (n<=3) { cout<<"NO"<<endl; return 0; } cout<<"YES"<<endl; vector <int > Arr; for (int i = 1;i<=n; i++) { Arr.push_back(i); } int a,b; while (Arr.size() != 1) { a = Arr[Arr.size() - 1]; Arr.pop_back(); b = Arr[Arr.size() - 1]; Arr.pop_back(); if (a == 1) { cout<<a<<" * "<<b<<" = "<<a*b<<endl; Arr.push_back(a*b); } else if (a > 5) { cout<<a<<" - "<<b<<" = "<<a-b<<endl; Arr.push_back(a-b); } else if (a == 4) { cout<<"4 * 3 = 12"<<endl; cout<<"12 * 2 = 24"<<endl; cout<<"24 * 1 = 24"<<endl; return 0; } else if (a == 5) { cout<<a<<" * "<<b<<" = "<<a*b<<endl; Arr.push_back(a*b); cout<<"20 + 3 = 23"<<endl; cout<<"23 + 2 = 25"<<endl; cout<<"25 - 1 = 24"<<endl; return 0; } } return 0; }<file_sep>def pow_mod(x, y, z): number=[[1,1],[1,0]] while y: if y & 1: number = matmult(number,x,z) y >>= 1 x = matmult(x,x,z) return number def matmult(a,b,m): zip_b = zip(*b) return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a, col_b))%m for col_b in zip_b] for row_a in a] a=[[1,1],[1,0]] a1=a t=input() for i in range(t): n,m=[int(x) for x in raw_input().split()] print (pow_mod(a,m+2,1000000007)[1][1] - pow_mod(a,n+1,1000000007)[1][1])%1000000007 <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int no_of_cases; cin >> no_of_cases; int idx = 0; while(no_of_cases--) { int no_of_friends; cin >> no_of_friends; map <int, set<int> > collection; map <int, int> global_counts; for (int i = 0; i < no_of_friends; i++) { int no_of_stamp; cin >> no_of_stamp; int stamp; for (int j = 0; j < no_of_stamp; j++) { cin >> stamp; if (collection[i].find(stamp) != collection[i].end()) { continue; } global_counts[stamp] += 1; collection[i].insert(stamp); } } map <int, int> result; int total = 0; for (auto i:collection) { for (auto j: i.second) { if (global_counts[j] == 1) { result[i.first] += 1; total += 1; } } } cout << "Case " << ++idx << ":"; for (int i = 0; i < no_of_friends; i++) { cout << " " << fixed << setprecision(6) << (double)(((double)result[i]*100)/(double)total) << '%'; } cout << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int a,b; int sum_up = 0,sum_down = 0; int flag = 0; for (int i=0;i<n;i++) { cin>>a>>b; sum_up += a; sum_down +=b; if ((a+b)%2 == 1) flag = 1; } if (sum_up%2 == 1 && sum_down%2 == 1 && flag == 1) { cout<<1<<endl; return 0; } else if (sum_down%2 == 0 && sum_up%2 == 0) { cout<<0<<endl; } else { cout<<-1<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <string> s(n); for (int i=0;i<n;i++) { cin>>s[i]; } char a = s[0][0]; char b = s[0][1]; if (a == b) { cout<<"NO"<<endl; return 0; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if ( (i == j || (i+j)%(n-1) == 0) && s[i][j] != a ) { cout<<"NO"<<endl; return 0; } else if ( (i != j && (i+j)%(n-1) != 0 ) && s[i][j]!=b) { cout<<"NO"<<endl; return 0; } } } cout<<"YES"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int x,y; ISTREAM>>x>>y; int counter = 1; while(counter<=y) { cout<<counter; if (counter%x == 0) cout<<endl; else cout<<" "; counter++; } return 0; }<file_sep>#include<stdio.h> int main() { float n; float m[300]; int i; float cnt=1; m[0]=0; float tmp=0; for (i=1;i<300;i++) { tmp+=1/(cnt+1); m[i]=tmp; cnt+=1; } int min=0; int max=300; int mid; scanf ("%f",&n); while (n>0.00) { while (max-min>1) { mid= ( min + max )/2; if ( m[mid] > n ) { max=mid; } else if ( m[mid] < n ) { min = mid; } } if(m[mid]<n) mid++; printf("%d card(s)\n",mid); scanf ("%f",&n); min=0; max=300; } return 0; } <file_sep>import math def is_square(apositiveint): x = apositiveint // 2 seen = set([x]) while x * x != apositiveint: x = (x + (apositiveint // x)) // 2 if x in seen: return False seen.add(x) return True n=10**6 sum1=0 for b in range(2,10000,2): for c in range(b,100000,2): if b==0 and c==0: continue t=b**2 + c**2 + (b**2)*(c**2) if t>10**12: break if (t%4!=0): continue t/=4 if is_square(t): sum1+=int(math.sqrt(t)) print b,c,math.sqrt(t),sum1 print sum1 <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } sort(Arr.begin(),Arr.end()); Arr[0] = Arr[0] + Arr[n-1]; Arr[n-1] = Arr[0] - Arr[n-1]; Arr[0] = Arr[0] - Arr[n-1]; for (int i=0;i<n;i++) { cout<<Arr[i]<<" "; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int m,n; while (scanf("%d%d",&m,&n)!=EOF) { vector < vector<pair<int,int> > > cols(n); for (int i = 0;i<m;i++) { int n1; cin>>n1; vector <int> idx(n1); vector <int> val(n1); for (int j= 0;j<n1;j++) { cin>>idx[j]; } for (int j = 0;j<n1;j++) { cin>>val[j]; } for (int j = 0;j<n1;j++) { cols[idx[j]-1].push_back(make_pair(i,val[j])); } } cout<<n<<" "<<m<<endl; for (int i = 0;i<n;i++) { cout<<cols[i].size(); if (cols[i].size() != 0) cout<<" "; for (int j = 0;j<cols[i].size();j++) { cout<<cols[i][j].first+1; if (j<cols[i].size()-1) cout<<" "; } cout<<endl; for (int j = 0;j<cols[i].size();j++) { cout<<cols[i][j].second; if (j < cols[i].size()-1) cout<<" "; } cout<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; cin >> n; string inp, inp1, inp2; getline(cin, inp); unordered_map <string, string> slogan; while(n--) { getline(cin, inp1); getline(cin, inp2); slogan[inp1] = inp2; } int m; cin >> m; getline(cin, inp); while (getline(cin, inp1)) { cout << slogan[inp1] << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { while (1) { string s; cin>>s; if (s == "#") break; if (next_permutation(s.begin(), s.end())) { cout<<s<<endl; } else { cout<<"No Successor"<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int temp; int sum= 0; for (int i=0;i<n;i++) { cin>>temp; sum += temp; } cout<<(float)sum/(float)n<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<int> A(n); int min = INT_MAX; int mini = -1; int i; for (i=0;i<n;i++) { cin>>A[i]; } i = 0; while (i+1 < n && A[i]<=A[i+1]) i++; if (i==n-1) { cout<<"0\n"; return 0; } int res = i; int check = A[0]; int cnt = 0; while (i<n-1) { if (A[n-1-cnt]<= check) { check = A[n-1-cnt]; cnt++; } else { cout<<"-1\n"; return 0; } i++; } cout<<cnt<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,p1,p2,ele; deque <int> player1; deque <int> player2; cin>>n; cin>>p1; for (int i = 0; i < p1; i++) { cin>>ele; player1.push_front(ele); } cin>>p2; for (int i = 0; i < p2; i++) { cin>>ele; player2.push_front(ele); } int cnt = 0; while (!player1.empty() && !player2.empty()) { cnt++; int e1 = player1.back(); int e2 = player2.back(); player1.pop_back(); player2.pop_back(); if (e1 > e2) { player1.push_front(e2); player1.push_front(e1); } else if (e2 > e1) { player2.push_front(e1); player2.push_front(e2); } if (cnt>1000) break; } if (cnt>1000) { cout<<-1<<endl; return 0; } cout<<cnt<<" "; if (player1.empty()) cout<<2<<endl; else cout<<1<<endl; return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> check(n+1); int temp; for (int i=1;i<=n;i++) { cin>>temp; check[temp] = i; } for (int i=1 ;i<=n; i++) { cout<<check[i]<<" "; } }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; int temp; int cnt = 0; while(1) { ISTREAM>>n; if (n == 0) { break; } cnt++; int z = 0; int p = 0; for (int i = 0; i < n; i++) { ISTREAM>>temp; if (temp == 0) { z++; } else p++; } cout<<"Case "<<cnt<<": "<<p - z<<endl; } return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; int main() { string s; cin>>s; string s1 = ""; s1 += s[0]; for (int i = 1;i<s.length();i++) { if (s[i] == s1[s1.length()-1]) continue; s1 += s[i]; } int q; cin>>q; for (int i = 0;i<q;i++) { string t; cin>>t; string t1 = ""; t1+=t[0]; for (int j = 1;j<t.length();j++ ) { if (t[i] == t1[t1.length()-1]) continue; t1 += t[i]; } int j = 0,k = 0; int ind = -1; while (j < s1.length() && k<t1.length()) { if (s1[j] == t1[k]) { if (ind == -1) ind = j; j++; k++; } else { j++; } } if (k!= t.length()) cout<<"Not Matched"<<endl; else { cout<<"Matched "<<ind<<" "<<j-1<<endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a, b, c, d; while(scanf("%d %d %d %d", &a, &b, &c, &d) == 4) { if (a == 0 && b == 0 && c == 0 && d == 0) { break; } cout << 720 + ((a + 40 - b) % 40) * 9 + 360 + ((40 - b + c) % 40) * 9 + ((c + 40 - d) % 40) * 9 << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; for (int i = 0;i<t;i++) { int k,c,s; //2 3 2 cin>>k>>c>>s; cout<<"Case #"<<i+1<<": "; for (int it = 1;it<=k;it++) { cout<<it; if (it < k) cout<<" "; } cout<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin >> t; while (t--) { int n; cin>>n; map <string, vector<string> > dic; string s; for (int i = 0; i < n; i++) { cin >> s; string t = s; sort(t.begin(), t.end()); dic[t].push_back(s); } cin >> s; while(s != "END") { string t = s; sort(t.begin(), t.end()); cout << "Anagrams for: " << s << endl; if (dic.find(t) == dic.end()) { cout << "No anagrams for: " << s << endl; } else { int it = 1; for (auto i:dic[t]) { cout << " " << it++ << ") " << i << endl; } } cin >> s; } if(t > 0) { cout << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int twenty_five = 0; int fifty = 0; int temp; for (int i=0;i<n;i++){ cin>>temp; if (temp == 25) twenty_five++; else if (temp == 50) { if (twenty_five==0) { cout<<"NO"<<endl; return 0; } fifty++; twenty_five--; } else if (temp == 100) { if (twenty_five>0 && fifty>0) { twenty_five--; fifty--; } else if (twenty_five>2) { twenty_five-=3; } else { cout<<"NO"<<endl; return 0; } } } cout<<"YES"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int n; cin>>n; vector <long long int> arr(n); for (int i=0;i<n;i++) { cin>>arr[i]; } sort(arr.begin(),arr.end()); long long int sum = arr[n-1]*n; for (long long int i = n-2; i>=0;i--) { sum += arr[i]* (i+2); } cout<<sum<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; int a1,a2,a3; int b1,b2,b3; cin>>a1>>a2>>a3; cin>>b1>>b2>>b3; cin>>n; int sum_cup = a1 + a2 + a3; int sum_med = b1 + b2 + b3; if ((n - (sum_cup/5 + (int)(sum_cup%5 != 0)) - (sum_med/10 + (int)(sum_med%10 != 0))) >= 0 ) { cout<<"YES"<<endl; } else { cout<<"NO"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int bin(int n) { int cnt = 0; while (n!=0) { n/=10; cnt++; } return cnt; } int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif string s; while(1) { ISTREAM>>s; if (s == "END") { break; } if (s == "1") { cout<<1<<endl; continue; } vector<int> v; v.push_back(s.length()); int i = 1; while (1) { v.push_back(bin(v[i-1])); if (v[i] == v[i-1]) break; i++; } cout<<i+1<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool is_int(string s) { for (int i = 0;i < s.length(); i++) { if (s[i] > 57 || s[i] < 48) { return false; } } return true; } stringstream ss; int main() { int n; string aa; getline(cin,aa); ss.str(aa); ss>>n; ss.str(""); ss.clear(); string a, b; int p; string source; set <string> multi; unordered_map <string, set<pair<int, string> > > dic1; unordered_map <string, set<pair<int, string> > > dic2; while(n--) { getline(cin, aa); ss.str(aa); if (aa[0] == ' ') { ss >> p; ss >> b; } else { ss >> a; ss >> p; ss >> b; source = a; } ss.str(""); ss.clear(); string new_a = source; if (source[0] == '*') { new_a = ""; for (int i = 2; i < source.length();i++) { new_a += source[i]; } dic2[new_a].insert(make_pair(p,b)); } else { dic1[new_a].insert(make_pair(p,b)); } } // for (auto i:dic) { // cout<<i.first<<" "<<i.second.size()<<endl; // } char x; string q; getline(cin, aa); ss.str(aa); ss>>x; // cout<<"Answering"<<endl; map <string, bool> status; while (x != 'X') { int priority = INT_MAX; ss >> q; if (x == 'U') { status[q] = true; ss.str(""); ss.clear(); getline(cin, aa); ss.str(aa); ss >> x; continue; } if (x == 'D') { status[q] = false; ss.str(""); ss.clear(); getline(cin, aa); ss.str(aa); ss >> x; continue; } string backup_q = q; set <pair <int, string> > res; if (dic1.find(q) != dic1.end()) { set <pair <int, string> > temp = dic1[q]; for (auto i:temp) { if (status.find(i.second) == status.end() || status[i.second]) { // cout<<" "<<i.second; res.insert(i); priority = min(i.first, priority); break; } } } string new_q = ""; int pos = 0; for (;pos<q.length();pos++) { if (q[pos] == '.') { break; } } pos += 1; for (; pos < q.length();pos++) { new_q += q[pos]; } q = new_q; while (q != "") { if (dic2.find(q) != dic2.end()) { set <pair <int, string> > temp = dic2[q]; for (auto i:temp) { if ((status.find(i.second) == status.end() || status[i.second]) && i.first < priority){ // cout<<" "<<i.second; res.insert(i); priority = i.first; } } } string new_q = ""; int pos = 0; for (;pos<q.length();pos++) { if (q[pos] == '.') { break; } } pos += 1; for (; pos < q.length();pos++) { new_q += q[pos]; } q = new_q; } cout << backup_q << " =>"; for (auto i:res) { cout<<" "<<i.second; break; } cout<<endl; ss.str(""); ss.clear(); getline(cin, aa); ss.str(aa); ss >> x; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int temp; int five = 0; int zero = 0; for (int i = 0 ; i<n; i++) { cin>>temp; if (temp ==0) { zero++; } else if (temp == 5) { five++; } } if (five/9 == 0 && zero>0) { cout<<0<<endl; } else if (zero == 0) { cout<<"-1"<<endl; } else { for (int i = 0;i < 9*(five/9) ; i++ ) { cout<<"5"; } for (int i=0;i<zero;i++) { cout<<"0"; } cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,t,c; cin>>n>>t>>c; vector <int> A(n); for (int i=0;i<n;i++) { cin>>A[i]; } int troll = 0; for (int i=0;i<c;i++) { if (A[i] > t ) troll++; } int cnt= 0; for (int i=0;i+c<n;i++) { if (troll == 0 ) cnt++; if (A[i] > t) { troll--; } if (A[i+c] > t) troll++; } if (troll == 0 )cnt++; cout<<cnt<<endl; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k,p; cin>>n>>k>>p; vector <int> arr(n); vector <int> odd; vector <int> even; for (int i=0;i<n;i++) { cin>>arr[i]; if (arr[i]%2==0) { even.push_back(arr[i]); } else odd.push_back(arr[i]); } if (k-p > (int)odd.size() ) { cout<<"NO"; return 0; } int ox = (int)odd.size() - (k-p); if (ox%2!=0) { cout<<"NO"; return 0; } int ex = p- (int)even.size(); if (ex>ox/2) { cout<<"NO"; return 0; } cout<<"YES"<<"\n"; for (int i=0;i<min(p,(int)even.size());i++) { cout<<"1 "<<even[i]<<"\n"; } int counter=0; while (ex>0) { cout<<"2 "<<odd[counter]<<" "<<odd[counter+1]<<"\n"; counter+=2; ex-=1; } for (;counter < k-p-1;counter++) { cout<<"1 "<<odd[counter]<<"\n"; } int remaining = 0; if ( (int)even.size()-p > 0 ) remaining +=(int)even.size()-p; if ((int)odd.size()>counter) remaining +=(int)odd.size()-counter; cout<<remaining<<" "; for (int i=p;i<(int)even.size();i++ ) cout<<even[i]<<" "; for (int i=counter;i<(int)odd.size() ; i++) cout<<odd[i]<<" "; cout<<"\n"; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; string t; string p =""; cin>>s>>t; int count = 0; for (int i = 0; i < s.length(); i++) { if (s[i] != t[i]) count++; } if (count%2 == 1) cout<<"impossible"<<endl; else { count/=2; for (int i = 0;i < s.length(); i++) { if (count>0 && s[i]!=t[i]) { p+=t[i]; count--; } else { p+=s[i]; } } cout<<p<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; int h,m; cin>>n; char c; map<string, float> dic = {{"UTC", 0.0}, {"GMT", 0.0}, {"BST", 1.0}, {"IST", 1.0}, {"WET", 0.0}, {"WEST", 1.0}, {"CET", 1.0}, {"CEST", 2.0}, {"EET", 2.0}, {"EEST", 3.0}, {"MSK", 3.0}, {"MSD", 4.0}, {"AST", -4.0}, {"ADT", -3.0}, {"NST", -3.5}, {"NDT", -2.5}, {"EST", -5.0}, {"EDT", -4.0}, {"CST", -6.0}, {"CDT", -5.0}, {"MST", -7.0}, {"MDT", -6.0}, {"PST", -8.0}, {"PDT", -7.0}, {"HST", -10.0}, {"AKST", -9.0}, {"AKDT", -8.0}, {"AEST", 10.0}, {"AEDT", 11.0}, {"ACST", 9.5}, {"ACDT", 10.5}, {"AWST", 8.0}}; int delta; while(n--) { string s; cin>>s; string t1, t2; if (s == "noon") { cin>>t1>>t2; delta = 720 + (dic[t2] - dic[t1])*60; } else if (s == "midnight") { cin>>t1>>t2; delta = (dic[t2] - dic[t1])*60; } else { stringstream ss(s); ss>>h>>c>>m; delta = h*60 + m; cin>>s; if (s[0] == 'p' && h < 12) delta += 720; if (s[0] == 'a' && h == 12) delta -= 720; cin>>t1>>t2; delta += (dic[t2] - dic[t1])*60; } if (delta < 0) delta += 1440; delta %= 1440; int parity = 0; if (delta == 0) { cout<<"midnight"<<endl; continue; } if (delta == 720) { cout<<"noon"<<endl; continue; } h = delta/60; m = delta%60; if (delta > 720) { parity = 1; } if (delta >= 780) { h -= 12; } if (h == 0) h = 12; cout<<h<<":"<<(m<10?"0":"")<<m<<" "; if (parity == 0) cout<<"a.m."<<endl; else cout<<"p.m."<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int temp; int par=0,impar = 0,pos = 0,neg = 0; for (int i = 0; i < 5; i++) { ISTREAM>>temp; if (temp%2==0) { par++; } else { impar++; } if (temp>0) { pos++; } else if (temp<0){ neg++; } } cout<<par<<" valor(es) par(es)"<<endl; cout<<impar<<" valor(es) impar(es)"<<endl; cout<<pos<<" valor(es) positivo(s)"<<endl; cout<<neg<<" valor(es) negativo(s)"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n,m; ISTREAM>>n>>m; for (int i= 0; i < n; i++) { if (i%2 == 0) { for (int j = 0;j < m; j++ ) { cout<<"#"; } cout<<endl; } else { if (i%4 == 1) { for (int j = 0;j < m - 1; j++) { cout<<"."; } cout<<"#"<<endl; } else { cout<<"#"; for (int j = 0;j < m - 1; j++) { cout<<"."; } cout<<endl; } } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { float a,b,c,d; float avg; cin>>a>>b>>c>>d; cout<<fixed<<setprecision(1); avg = (2*a + 3*b + 4*c + d)/10; cout<<"Media: "<<avg<<endl; if (avg >= 7.0) { cout<<"Aluno aprovado."<<endl; } else if (avg < 5.0) { cout<<"Aluno reprovado."<<endl; } else { cout<<"Aluno em exame."<<endl; float e; cin>>e; cout<<"Nota do exame: "<<e<<endl; avg = (avg + e)/2; if (avg >= 5.0) { cout<<"Aluno aprovado."<<endl; } else { cout<<"Aluno reprovado."<<endl; } cout<<"Media final: "<<avg<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; for (int i = 0;i<t;i++) { int k,c,s; //2 3 2 cin>>k>>c>>s; if (c == 1 && s < k) cout<<"Case #"<<i+1<<": IMPOSSIBLE"<<endl; else if (c == 1) { cout<<"Case #"<<i+1<<": "; for (int it = 1;it<=k;it++) { cout<<it; if (it < k) cout<<" "; } cout<<endl; } else if (k == 1) { cout<<"Case #"<<i+1<<": "<<"1"<<endl; } else if (k == 2) { cout<<"Case #"<<i+1<<": "<<"2"<<endl; } else if (k%2 == 0 && (k/2)%2==0) { if (s < k/2) cout<<"Case #"<<i+1<<": IMPOSSIBLE"<<endl; else { cout<<"Case #"<<i+1<<": "; for (int it = (k*k)/2 - k/4 +1;it<(k*k)/2 + k/4 +1;it++) { cout<<it; if (it < (k*k)/2 + k/4) cout<<" "; } cout<<endl; } } else if (k%2 == 0){ if (s<k/2+1) cout<<"Case #"<<i+1<<": IMPOSSIBLE"<<endl; else { cout<<"Case #"<<i+1<<": "; for (int it = (k*k)/2 - k/2 + 2;it<(k*k)/2 + k/2;it++) { cout<<it; if (it < (k*k)/2 + k/2 -1) cout<<" "; } cout<<endl; } } else if (k == 3) { if (s < 2) cout<<"Case #"<<i+1<<": IMPOSSIBLE"<<endl; else cout<<"Case #"<<i+1<<": "<<"2 3"<<endl; } else { if (s < k - 2) cout<<"Case #"<<i+1<<": IMPOSSIBLE"<<endl; else { cout<<"Case #"<<i+1<<": "; for (int it = k * (k/2) - k/2 + 1; it < k*(k/2) + k/2;it++) { cout<<it; if (it < k*(k/2) + k/2 -1) cout<<" "; } cout<<endl; } } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int v, v0; while (cin>>v>>v0) { if (v == 0 && v0 == 0) break; double factor1 = 1; double max_l = -1; double max_f = -1; bool flag = false; for (int i = 1;i <= v;i++) { factor1 = (double)i; if (v/factor1 > v0) { double length = factor1*0.3*sqrt(v/factor1 - v0); if (abs(length - max_l) < 0.000001 && factor1 != max_f) { flag = true; } else if (length > max_l) { max_f = factor1; max_l = length; flag = false; } } } if (max_l <= 0 || flag) cout<<0<<endl; else cout<<max_f<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d\n",&n); vector<char> Arr; int len; for (int it=0;it<n;it++) { string s; getline(cin,s); len = s.length(); for (int i=0;i<len;i++) { Arr.push_back(s[i]); } for (int i=0;i<len;i++) { if ((Arr[i]<=122 && Arr[i]>=97) || (Arr[i]>=65 && Arr[i]<=90 )) { Arr[i] = Arr[i] + 3; } } for (int i=0; i< (len+1)/2; i++) { Arr[i] = Arr[i] - 1; } for (int i= len-1;i>=0;i--) { cout<<Arr[i]; } cout<<endl; Arr.clear(); } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int x1,y1; int x2,y2; cin>>x1>>y1>>x2>>y2; if (x1 == x2) { cout<<x1+ y2 - y1<<" "<<y1<<" "<<x1+ y2 - y1<<" "<<y2<<endl; } else if (y1 == y2) { cout<<x1<<" "<<y1 + x2-x1<<" "<<x2<<" "<<y2 + x2 - x1<<endl; } else if (x2-x1 == y2 - y1) { cout<<x1<<" "<<y1 + (x2-x1)<<" "<<x2<<" "<<y2 - (x2 - x1)<<endl; } else if (x2-x1 == y1 - y2) { cout<<x1<<" "<<y1 - (x2-x1)<<" "<<x2<<" "<<y2 + (x2 - x1)<<endl; } else { cout<<-1<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { float temp; int pos = 0; for (int i=0;i<6;i++) { cin>>temp; if (temp>0) pos++; } cout<<pos<<" valores positivos"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int memo[220][25]; int items[25][25]; int money,counts; int dp(int mon, int cnts) { if (mon < 0) { return -999999; } if (cnts == counts) { return money - mon; } if (memo[mon][cnts]!=-1) return memo[mon][cnts]; int ans = -1; for (int i = 1; i <= items[cnts][0]; i++) { ans = max(ans,dp(mon - items[cnts][i],cnts+1)); } memo[mon][cnts] = ans; return ans; } int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; for (int i = 0; i < n; i++) { ISTREAM>>money>>counts; for (int j= 0;j<counts;j++) { ISTREAM>>items[j][0]; for (int k = 1; k<= items[j][0]; k++) { ISTREAM>>items[j][k]; } } memset(memo,-1,sizeof(memo)); int ans = dp(money,0); if (ans <= 0) { cout<<"no solution"<<endl; } else { cout<<ans<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; long long int pow1(long long int a,long long int b) { if (b<0) return 0; if (b==0) return 1; long long int n = a; for (long long int it = 1;it<b;it++) { n*=a; } return n; } int main() { long long int n; cin>>n; long long int m = 0; long long int temp; for (long long int i = 1; i < 12; i+=1) { long long int k = i; temp = pow1(10,k) - 1; if (n >= temp) m+= k*pow1(10l,k-1)*9; else { m+=(n - (pow1(10l,k-1)-1))*k; break; } if(n == temp) break; } cout<<m<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; while(1) { cin>>n; if (n == 0) break; int top = 1; int north = 2; int west = 3; int south = 5; int east = 4; int bottom = 6; int top1,north1,west1,south1,east1,bottom1; string temp; while(n--) { cin>>temp; if (temp == "north") { top1 = south; north1 = top; south1 = bottom; bottom1 = north; east1 = east; west1 = west; } else if (temp == "east") { top1 = west; north1 = north; south1 = south; bottom1 = east; east1 = top; west1 = bottom; } else if (temp == "south") { top1 = north; north1 = bottom; south1 = top; bottom1 = south; east1 = east; west1 = west; } else if (temp == "west") { top1 = east; north1 = north; south1 = south; bottom1 = west; east1 = bottom; west1 = top; } north = north1; south = south1; east = east1; west = west1; top = top1; bottom = bottom1; } cout<<top<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; cin>>n; while (n!= 0) { int a; cin>>a; while (a != 0) { vector <int> train; for (int i = 0;i<n;i++) { train.push_back(a); cin>>a; } int c = 0; stack <int> pushpa; for (int i = 1;i<=n;i++) { pushpa.push(i); while(!pushpa.empty() && pushpa.top() == train[c]) { pushpa.pop(); c++; } } if (pushpa.empty()) cout<<"Yes"<<endl; else { cout<<"No"<<endl; } train.clear(); } cin>>n; cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { int n, m; cin >> n >> m; multiset <int> m1; multiset <int> m2; int element; for(int i = 0; i < n; i++) { cin >> element; m1.insert(element); } for (int i = 0; i < m; i++) { cin >> element; m2.insert(element); } multiset <int> to_remove; for (auto i:m1) { if (m2.find(i) != m2.end()) { to_remove.insert(i); m2.erase(m2.find(i)); } } cout << (int)m1.size() + (int)m2.size() - (int)to_remove.size()<< endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; map <int, vector<int> > edge; int max1 = 1; int dfs(int r) { if (edge.find(r)!= edge.end()) { int cnt; int maxii = -1; for (int i = 0;i < edge[r].size();i++) { cnt = 1+dfs(edge[r][i]); if (cnt > maxii ) maxii = cnt; } return maxii; } else { return 1; } } int main() { int n; cin>>n; int node; vector<int> roots; for (int i = 1;i<=n;i++) { cin>>node; if (node!= -1) { edge[node].push_back(i); } else { roots.push_back(i); } } int count; int maxi = 1; for (int i = 0;i<roots.size();i++) { count = dfs(roots[i]); if (count>maxi) maxi = count; } cout<<maxi<<endl; return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; int check; cin>>check; int prev = check; long long int res = check - 1; for (int i=0 ; i<m-1; i++) { cin>>check; if ( check >= prev ) { res += check - prev; } else { res += n - prev; res += check; } prev = check; } cout<<res<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,s; cin>>n>>s; int max = -1; for (int i=0;i<n;i++) { int a,b; cin>>a>>b; if (s>a and b > 0 ) { if (100 - b>max) max = 100-b; } else if (s >= a && b == 0) { if (0>max) max = 0; } } cout<<max<<endl; return 0; }<file_sep>#include<iostream> #include<vector> using namespace std; int main (void) { int n,k; int i; cin>>n>>k; int mink=0; vector <int> arr; int temp; int kz=1; for (i=0;i<k;i++) { cin>>temp; arr.push_back(temp); mink+=temp; } int curr=mink; for (i=k;i<n;i++) { cin>>temp; arr.push_back(temp); curr=curr-arr[i-k]+temp; if (curr <mink ) {mink=curr; kz=i-k+2; } } cout<<kz<<endl; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<long long int> x(n); vector<long long int> y(n); for (int i = 0;i<n;i++) { cin>>x[i]>>y[i]; } sort(x.begin(), x.end()); sort(y.begin(), y.end()); long long int t = max(abs(x[0]-x[n-1]),abs(y[0]-y[n-1])); cout<<t*t<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; vector<int> Arr(3); int cnt = 0; for (int i = 0; i < n; i++) { cnt++; ISTREAM>>Arr[0]>>Arr[1]>>Arr[2]; sort(Arr.begin(), Arr.end()); cout<<"Case "<<cnt<<": "<<Arr[1]<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int matrix[101][101]; int helper[101] = {0}; void bfs(int i,int n) { helper[i] = 1; for (int j = 0;j<n;j++) { if (matrix[i][j] == 1 && helper[j] == 0) { bfs(j,n); } } } int main() { int n,m; cin>>n>>m; map < int, vector<int> > langs; int temp; int flag = 0; for (int i = 0 ; i < n; i++) { cin>>temp; int temp1; for (int j = 0;j<temp; j++) { cin>>temp1; flag = 1; langs[temp1].push_back(i); } } for (int i = 0;i<n;i++) { for (int j = 0;j<n;j++) { matrix[i][j] = 0; } } for (map <int, vector<int> > :: iterator it = langs.begin(); it!=langs.end();it++) { for (int i = 0;i< langs[it->first].size();i++) { for (int j = 0;j< langs[it->first].size();j++) { if (i == j) continue; matrix[langs[it->first][i]][langs[it->first][j]] = 1; matrix[langs[it->first][j]][langs[it->first][i]] = 1; } } } int counter = 0; for (int i = 0;i < n;i++) { if (helper[i] == 0) { counter+=1; bfs(i,n); } } if (flag == 1) cout<<counter - 1<<endl; else cout<<counter<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; pair <int, int> split(string s) { int a, b; stringstream ss; ss.str(""); ss.clear(); ss.str(s); ss >> a; ss >> b; return make_pair(a, b); } int main() { int t; cin >> t; string inp; getline(cin, inp); getline(cin, inp); while (t--) { int p, n; getline(cin, inp); set < set< int> > result; pair<int, int> item = split(inp); p = item.first; n = item.second; map <int, set<int> > opinions; getline(cin, inp); while(inp != "") { pair<int, int> item = split(inp); opinions[item.first].insert(item.second); getline(cin, inp); } int cnt = 0; for (auto i: opinions) { cnt += 1; result.insert(i.second); } int res = (int)result.size(); if (cnt < p) res += 1; cout << res << endl; if (t > 0) { cout << endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int n,v; cin>>n>>v; vector <long long int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; cout<<v<<" "<<Arr[i]<<endl; v+=v-Arr[i]; if (v < 0 ) cout<<"bakchodi "<<Arr[i]<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; vector < pair<int,int> > Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i].first>>Arr[i].second; } double sigma = 0.0; for (int i=1;i<n;i++) { double d1 = (Arr[i].first - Arr[i-1].first); double d2 = (Arr[i].second - Arr[i-1].second); sigma += sqrt(d1*d1 + d2*d2); } printf("%.7lf",(sigma*k)/50); return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; while (cin >> n) { if (n == 0) { break; } vector <int> stations(n); for (int i = 0; i < n; i++) { cin >> stations[i]; } sort(stations.begin(), stations.end()); int can_go_to = 0; bool flag = true; for (int i = 0; i < n; i++) { if (stations[i] > can_go_to) { flag = false; break; } else { can_go_to = stations[i] + 200; } } if (can_go_to < 1422) { flag = false; } if (flag == false) { cout << "IMPOSSIBLE" << endl; continue; } can_go_to -= 1422; for (int i = 0; i < n; i++) { stations[i] = 1422 - stations[i]; } reverse(stations.begin(), stations.end()); for (int i = 0; i < n; i++) { if (stations[i] > can_go_to) { flag = false; break; } else { can_go_to = stations[i] + 200; } } if (flag == false) { cout << "IMPOSSIBLE" << endl; } else { cout << "POSSIBLE" << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } sort(Arr.begin(),Arr.end()); for (int k = 1;k<=100;k++) { int flag = 0; for (int j=0;j<n;j++) { if (Arr[j] < j/k) { flag = 1; break; } } if (flag == 0) { cout<<k<<endl; return 0; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; int count = 0; for (int a = 0;a*a<=n;a++) { int b = n - a*a; if (b*b + a == m) { count++; } } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m,a,b; cin>>n>>m>>a>>b; if (m*a<=b) cout<<n*a<<endl; else cout<<min((n/m)*b + (n%m)*a,(n/m)*b + (int)(n%m != 0)*b)<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int integer(string s) { int res; ss.str(""); ss.clear(); ss.str(s); ss >> res; return res; } string small(string s) { string res = ""; for (int i = 0; i < (int)s.length(); i++) { if ((int)s[i] <= 90 && (int)s[i] >= 65) { res += (char)((int)s[i] + 32); } else { res += s[i]; } } return res; } int main() { int t; string inp; int n; string tournament_name; int m; getline(cin, inp); t = integer(inp); while (t--) { getline(cin, tournament_name); getline(cin, inp); n = integer(inp); int n1 = n; map <string, string> ranker; map <string, int> ranks; map <int, string> rev_ranks; while (n1--) { getline(cin, inp); ranker[small(inp)] = inp; } int cnt = 0; for (auto i:ranker) { ranks[i.second] = cnt; rev_ranks[cnt] = i.second; cnt += 1; } vector <vector <int> > tournament(n, vector<int> (9,0)); for (int i = 0; i < n; i++) { tournament[i][5] = i; } getline(cin, inp); m = integer(inp); while (m--) { char tmp; string player1; string player2; int goal1; int goal2; getline(cin, inp); ss.str(""); ss.clear(); ss.str(inp); getline(ss, player1, '#'); ss >> goal1; ss >> tmp; ss >> goal2; ss >> tmp; getline(ss, player2); /* 0 is points 1 is wins 2 goal delta 3 is goal scored 4 is games played 5 team id 6 draw 7 lose 8 goal taken */ if (goal1 > goal2) { tournament[ranks[player1]][0] += (-1) * 3; tournament[ranks[player1]][1] += (-1) * 1; // wins tournament[ranks[player1]][2] += (-1) * (goal1 - goal2); tournament[ranks[player1]][3] += (-1) * goal1; tournament[ranks[player1]][4] += 1; tournament[ranks[player1]][8] += goal2; tournament[ranks[player2]][2] += (-1) * (goal2 - goal1); tournament[ranks[player2]][3] += (-1) * goal2; tournament[ranks[player2]][4] += 1; tournament[ranks[player2]][7] += 1; tournament[ranks[player2]][8] += goal1; // goal taken } else if (goal1 == goal2) { tournament[ranks[player1]][0] += (-1) * 1; tournament[ranks[player1]][3] += (-1) * goal1; tournament[ranks[player1]][4] += 1; tournament[ranks[player1]][6] += 1; tournament[ranks[player1]][8] += goal2; tournament[ranks[player2]][0] += (-1) * 1; tournament[ranks[player2]][3] += (-1) * goal2; tournament[ranks[player2]][4] += 1; tournament[ranks[player2]][6] += 1; tournament[ranks[player2]][8] += goal1; } else if (goal1 < goal2) { tournament[ranks[player2]][0] += (-1) * 3; tournament[ranks[player2]][1] += (-1) * 1; // wins tournament[ranks[player2]][2] += (-1) * (goal2 - goal1); tournament[ranks[player2]][3] += (-1) * goal2; tournament[ranks[player2]][4] += 1; tournament[ranks[player2]][8] += goal1; tournament[ranks[player1]][2] += (-1) * (goal1 - goal2); tournament[ranks[player1]][3] += (-1) * goal1; tournament[ranks[player1]][4] += 1; tournament[ranks[player1]][7] += 1; tournament[ranks[player1]][8] += goal2; // goal taken } } sort(tournament.begin(), tournament.end()); cout << tournament_name << endl; for (int i = 0; i < n; i++) { cout << i + 1 << ") " << rev_ranks[tournament[i][5]] << " " << (-1) * tournament[i][0] << "p" << ", " << tournament[i][4] << "g (" << (-1) * tournament[i][1] << "-" << tournament[i][6] << "-" << tournament[i][7] << "), " << (-1) * tournament[i][2] << "gd (" << (-1) * tournament[i][3] << "-" << tournament[i][8] << ")" << endl; } if (t > 0) { cout << endl; } } return 0; } <file_sep>#include<stdio.h> int main() { int n,i; int p[100000]; for (i=0;i<12;i++) { p[i]=i; } for (i=12;i<100000;i++) { p[i]=p[i/2]+p[i/3]+p[i/4]; } while (scanf("%d",&n)!=EOF) { if ( n<100000 ) { printf("%d\n",p[n]); } else { int a[100000]; a[0]=n; int m1,m2,m3; int counter=0; long long int sum=0; while (counter!=-1) { if ( a[counter] < 100000 ){ sum+=p[a[counter]]; counter--; continue; } m1=a[counter]/2; m2=a[counter]/3; m3=a[counter]/4; if ( m1+m2+m3>a[counter] ) { a[counter++]=m1; a[counter++]=m2; a[counter]=m3; } } printf("%lld\n",sum); } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int N; ISTREAM>>N; int n; int m; char c; for (int i = 0; i < N; i++) { ISTREAM>>c>>m>>n; if (c == 'r' || c == 'Q') { cout<<min(n,m)<<endl; } else if (c == 'K') { cout<<(n/2 + n%2) * (m/2 + m%2)<<endl; } else if (c == 'k') { cout<<(n*m)/2 + (m*n)%2<<endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; vector <pair<int,int> > compressor(vector <pair<int,int> > hand) { map <int,int> h_val; for (int i = 0;i<5;i++) { h_val[hand[i].first] += 1; } vector <pair<int,int> >vals; for (auto it:h_val) { vals.push_back(make_pair(it.second,it.first)); } sort(vals.begin(), vals.end()); return vals; } bool is_flush(vector <pair<int,int > > hand) { int clr = hand[0].second; for (int i = 0;i<5;i++) { if (clr != hand[i].second) { return false; } } return true; } bool is_straight(vector <pair<int,int > > hand) { vector<int> num(5); for (int i = 0;i<5;i++) { num[i] = hand[i].first; } sort(num.begin(), num.end()); int base = num[0]; for (int i = 0;i<5;i++) { if (base != num[i]) { return false; } base++; } return true; } int check_level(vector <pair<int,int > > h1, vector <pair<int,int > > h2) { vector<int> num1(5); vector<int> num2(5); for (int i = 0;i<5;i++) { num1[i] = h1[i].first; num2[i] = h2[i].first; } sort(num1.begin(), num1.end()); sort(num2.begin(), num2.end()); int p1_level = 999,p2_level = 999; if (is_flush(h1) && is_straight(h1)) p1_level = 1; if (is_flush(h2) && is_straight(h2)) p2_level = 1; if (p1_level == 1 && p2_level != 1) return 1; else if (p2_level == 1 && p1_level != 1) return 2; else if (p1_level == 1 && p2_level == 1) { if (num1[4] > num2[4]) return 1; else if (num1[4] < num2[4]) return 2; else return 3; } vector <pair<int,int> > vals1 = compressor(h1); vector <pair<int,int> > vals2 = compressor(h2); int len1 = vals1.size(); int len2 = vals2.size(); if (vals1[len1-1].first == 4) p1_level = 2; if (vals2[len2-1].first == 4) p2_level = 2; if (p1_level == 2 && p2_level != 2) return 1; else if (p2_level == 2 && p1_level != 2) return 2; else if (p1_level == 2 && p2_level == 2) { for (int i = len1-1;i>=0;i--) { if (vals1[i].second > vals2[i].second) return 1; else if (vals1[i].second < vals2[i].second) return 2; } return 3; } if (vals1[len1-1].first == 3 && vals1[len1-2].first==2) p1_level = 3; if (vals2[len2-1].first == 3 && vals2[len2-2].first==2) p2_level = 3; if (p1_level == 3 && p2_level != 3) return 1; else if (p2_level == 3 && p1_level != 3) return 2; else if (p1_level == 3 && p2_level == 3) { for (int i = len1-1;i>=0;i--) { if (vals1[i].second > vals2[i].second) return 1; else if (vals1[i].second < vals2[i].second) return 2; } return 3; } if (is_flush(h1)) p1_level = 4; if (is_flush(h2)) p2_level = 4; if (p1_level == 4 && p2_level != 4) return 1; else if (p2_level == 4 && p1_level != 4) return 2; else if (p1_level == 4 && p2_level == 4) { for (int i = 4;i>=0;i--) { if (num1[i] > num2[i]) return 1; else if (num1[i] < num2[i]) return 2; } return 3; } if (is_straight(h1)) p1_level = 5; if (is_straight(h2)) p2_level = 5; if (p1_level == 5 && p2_level != 5) return 1; else if (p2_level == 5 && p1_level != 5) return 2; else if (p1_level == 5 && p2_level == 5) { if (num1[4]>num2[4]) return 1; else if (num1[4] < num2[4]) return 2; else return 3; } if (vals1[len1-1].first == 3) p1_level = 6; if (vals2[len2-1].first == 3) p2_level = 6; if (p1_level == 6 && p2_level != 6) return 1; else if (p2_level == 6 && p1_level != 6) return 2; else if (p1_level == 6 && p2_level == 6) { for (int i = len1-1;i>=0;i--) { if (vals1[i].second > vals2[i].second) return 1; else if (vals1[i].second < vals2[i].second) return 2; } return 3; } if (vals1[len1-1].first == 2 && vals1[len1-2].first==2) p1_level = 7; if (vals2[len2-1].first == 2 && vals2[len2-2].first==2) p2_level = 7; if (p1_level == 7 && p2_level != 7) return 1; else if (p2_level == 7 && p1_level != 7) return 2; else if (p1_level == 7 && p2_level == 7) { for (int i = len1-1;i>=0;i--) { if (vals1[i].second > vals2[i].second) return 1; else if (vals1[i].second < vals2[i].second) return 2; } return 3; } if (vals1[len1-1].first == 2) p1_level = 8; if (vals2[len2-1].first == 2) p2_level = 8; if (p1_level == 8 && p2_level != 8) return 1; else if (p2_level == 8 && p1_level != 8) return 2; else if (p1_level == 8 && p2_level == 8) { for (int i = len1-1;i>=0;i--) { if (vals1[i].second > vals2[i].second) return 1; else if (vals1[i].second < vals2[i].second) return 2; } return 3; } for (int i = len1-1;i>=0;i--) { if (vals1[i].second > vals2[i].second) return 1; else if (vals1[i].second < vals2[i].second) return 2; } return 3; } int main() { char s[30]; while (gets(s)) { vector < pair<int,int> > player1; vector < pair<int,int> > player2; int val,suit; int p1_level = 0,p2_level = 0; bool p1_flush,p2_flush; bool p1_straight,p2_straight; for (int i = 0;i<30;i++) { if (s[i] == 'A') val = 14; else if (s[i] == 'K') val = 13; else if (s[i] == 'Q') val = 12; else if (s[i] == 'J') val = 11; else if (s[i] == 'T') val = 10; else val = s[i] - 48; if (s[i+1] == 'C') suit = 1; else if (s[i+1] == 'H') suit = 2; else if (s[i+1] == 'D') suit = 3; else if (s[i+1] == 'S') suit = 4; if (i<15) player1.push_back(make_pair(val,suit)); else player2.push_back(make_pair(val,suit)); i+=2; } int win = check_level(player1,player2); if (win == 2) cout<<"White wins."<<endl; else if (win == 1) cout<<"Black wins."<<endl; else cout<<"Tie."<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; int t; int temp; for (int i = 0; i < n; i++) { cout<<"Case "<<i+1<<": "; ISTREAM>>t; int mile = 0; int juice = 0; for (int j = 0; j < t; j++) { ISTREAM>>temp; mile += (temp+1)/30 + (int)((temp+1)%30 != 0); juice += (temp + 1)/60 + (int)((temp+1)%60 != 0); } mile*=10; juice*= 15; if (mile <= juice) { cout <<"Mile"<<" "; } if (juice <= mile) { cout<<"Juice"<<" "; } cout<<min(mile,juice)<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int a,b; while (1) { ISTREAM>>a>>b; if (a == 0 && b == 0) { break; } cout<<a+b<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,v; cin>>n>>v; vector <int> res; for (int i=0;i<n;i++) { int k; int flag = 0; cin>>k; for (int j=0;j<k;j++) { int temp; cin>>temp; if (flag==0 && v>temp) { res.push_back(i); flag = 1; } } } cout<<res.size()<<endl; for (int i = 0;i<res.size();i++) { cout<<res[i]+1<<" "; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; cin>>n; vector<int> mini(3); vector<int> maxi(3); for (int i = 0; i < 3; i++) { cin>>mini[i]>>maxi[i]; } int a = min(maxi[0],n - (mini[1] + mini[2])); int b = min(maxi[1],n - a - mini[2]); int c = n - a-b; cout<<a<<" "<<b<<" "<<c<<endl; }<file_sep>#include <bits/stdc++.h> using namespace std; int counter; vector <int> arr; int b,c; bool comp(vector <int> brr) { int cnt = 0; int cnt2=0; for (int i = 0;i<brr.size();i++) { if (arr[i] == brr[i]) cnt2++; } vector <int> temp1(10,0); vector <int> temp2(10,0); for (int i = 0;i<arr.size();i++) { temp1[arr[i]]++; } for (int i = 0;i<brr.size();i++) { temp2[brr[i]]++; } for (int i = 0;i<temp1.size();i++) { cnt+= min(temp1[i],temp2[i]); } if (cnt == b+c && cnt2 == b) return true; else return false; } vector<vector<int>> generateK(int k, vector<vector<int>> acc) { if(k == 0) return acc; vector<vector<int>> result; for(int digit = 1; digit < 10; ++digit) { for(int i = 0; i < acc.size(); ++i) { vector<int> tmp = acc[i]; tmp.push_back(digit); result.push_back(tmp); } } return generateK(k - 1, result); } int main() { int t; cin>>t; string a; while(t--) { cin>>a>>b>>c; vector <int> brr; arr.clear(); for (int i = 0;i<a.length();i++) { arr.push_back(a[i]-48); brr.push_back(1); } counter = 0; vector <vector<int> > res = generateK(arr.size(), vector<vector<int>>(1, vector<int>())); for(int i = 0; i < res.size(); ++i) { if (comp(res[i])) counter++; } cout << counter << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; int idx = 0; while(t--) { cout<<"Case "<<++idx<<": "; int h11, m11, h12, m12; int h21, m21, h22, m22; char c; cin >> h11 >> c >> m11 >> h12 >> c >> m12; cin >> h21 >> c >> m21 >> h22 >> c >> m22; int t1 = h11*60 + m11; int t2 = h12*60 + m12; int w1 = h21*60 + m21; int w2 = h22*60 + m22; if ((w1 >= t1 && w1 <= t2) || (w2 >= t1 && w2 <= t2) || (w1 <= t1 && w2>=t2)) cout<<"Mrs Meeting"<<endl; else cout<<"Hits Meeting"<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; if ( k>n ) { cout<<"-1\n"; return 0; } vector <int> A(n); for (int i=0;i<n;i++) { cin>>A[i]; } sort(A.begin(),A.end()); cout<<A[A.size()-k]<<" "<<A[A.size()-k]<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; /* Warning no spaces in testcases */ stringstream ss; int main() { int t; string inp; cin>> t; int l1; int l2; string symb; getline(cin, inp); int idx = 0; while (t--) { getline(cin, inp); ss.str(""); ss.clear(); ss.str(inp); ss >> l1; ss >> symb; if (symb.length() > 3) { l2 = symb[3] - 48; } else { l2 = 0; } cout<<"Case "<<++idx<<": "<<l1*0.5 + l2*0.05<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; int r, c, p; cin >> t; while (t--) { cin >> r >> c >> p; vector <int> X(p); vector <int> Y(p); for (int i = 0; i < p; i++) { cin >> X[i]; cin >> Y[i]; } sort(X.begin(), X.end()); sort(Y.begin(), Y.end()); int mid = (p-1)/2; cout << "(Street: " << X[mid] << ", Avenue: " << Y[mid] << ")" << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,c; while (1) { cin>>a; if (a == 0) break; cin>>c; vector<int> arr(c); vector <int> helper; int count = 0; for (int i = 0; i < c; i++) { cin>>arr[i]; } count = a - arr[0]; for (int i = 1; i < c; i++) { if (arr[i]>=arr[i-1]) continue; count+=arr[i-1] - arr[i]; } cout<<count<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,x; cin>>n>>x; int a,b; int counter = 1; int sum = 0; for (int i = 0;i<n;i++) { cin>>a>>b; while (counter + x <= a) counter += x; sum += b+1 - counter; counter = b+1; } cout<<sum<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { string s; int casen = 0; while (cin>>s) { if (s == "end") { break; } casen++; cout<<"Case "<<casen<<": "; vector <stack <char> > trans; for (int i = 0;i<s.length();i++) { bool flag = false; for (int j = 0;j < trans.size();j++) { if (trans[j].top() >= s[i]) { trans[j].push(s[i]); flag = true; break; } } if (flag == false) { stack <char> new_s; new_s.push(s[i]); trans.push_back(new_s); } } cout<<trans.size()<<endl; } return 0; }<file_sep>while(1): n=int(input()) if n==0: break string=input() row=len(string)//n t=[] for j in range(0,row): s1=[] for i in range(j*n,j*n+n): s1.append(string[i]) if j%2==1: s1.reverse() t.append(s1) ans=[] for i in range(0,n): for j in t: ans.append(j[i]) ans="".join(ans) print(ans) <file_sep>#include<stdio.h> int main(){ int i,j; int test; int cnt=1; int primelist[3500]={0}; primelist[0]=2; for (i=3;i<32000;i=i+2) { test=1; for (j=0;j<3500;j++) { if (primelist[j]==0) break; else if (primelist[j]*primelist[j]>i) break; else if (i%primelist[j]==0) {test=0; break;} } if(test==1) primelist[cnt++]=i; } int num; int n,m; scanf("%d",&num); for (i=0;i<num;i++) { scanf("%d %d",&m,&n); int k,k1,k2; if (m<2) m=2; int primes[100000]={0}; int t=n-m; for (j=0;j<3402;j++){ if (primelist[j]*primelist[j]>n) break; if (m%primelist[j]==0) {k1=m/primelist[j];} else {k1=m/primelist[j] + 1;} if (n%primelist[j]==0) {k2=n/primelist[j];} else {k2=n/primelist[j];} for (k=k1;k<=k2;k++) { if (k==1) continue; primes[k*primelist[j]-m]=1; } } for (j=0;j<t+1;j++) { if(primes[j]==0) { printf("%d\n",j+m); } } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { vector <int> par; vector <int> impar; int temp; for (int i=0;i<15;i++) { cin>>temp; if (temp%2 == 0) { par.push_back(temp); } else { impar.push_back(temp); } if (par.size() == 5) { for (int i=0;i<5;i++ ) { cout<<"par["<<i<<"] = "<<par[i]<<endl; } par.clear(); } if (impar.size() == 5) { for (int i=0;i<5;i++ ) { cout<<"impar["<<i<<"] = "<<impar[i]<<endl; } impar.clear(); } } for (int i=0;i<impar.size();i++ ) { cout<<"impar["<<i<<"] = "<<impar[i]<<endl; } for (int i=0;i<par.size();i++ ) { cout<<"par["<<i<<"] = "<<par[i]<<endl; } return 0; } <file_sep>#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { int n,k; cin >>n>>k; vector <int> A(n); for (int i=0;i<n; i++) { cin >> A[i]; } sort(A.begin(),A.end()); int cnt = 0; for ( int i = 0 ; i<n; i++) { if (A[i] >= A[n-k] && A[i]>0) cnt++; } cout<<cnt<<endl; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; for (int i = 0; i < n; i++) { cout<<"Case #"<<i+1<<":"<<endl; vector<string> res; string s; int v; int max = -1; for (int j = 0; j < 10; j++) { ISTREAM>>s>>v; if (v>max) { max = v; res.clear(); res.push_back(s); } else if (v == max) { res.push_back(s); } } for (unsigned int j=0;j<res.size();j++) { cout<<res[j]<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool comp(string a , string b) { string t1 = a + b; string t2 = b + a; return t1 > t2; } int main() { int n; while(cin >> n) { if (n == 0) { break; } vector <string> vals(n); for (int i = 0; i < n; i++) { cin >> vals[i]; } sort(vals.begin(), vals.end(), comp); for (int i = 0; i < n; i++) { cout << vals[i]; } cout << endl; } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; int main() { string s; cin>>s; for (int i = 0; i < s.length() ; i++){ if (s[i] < 97) s[i]+= 32; if (s[i] != 'a' && s[i]!='e' && s[i]!='i' && s[i]!='o' && s[i]!='u' && s[i]!='y') cout<<"."<<s[i]; } cout<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; int idx = 0; while(cin >> n) { if (n == 0) { break; } vector <int> arr(n); for (int i = 0;i < n; i++) { cin>> arr[i]; } int sum1 = accumulate(arr.begin(), arr.end(), 0); int each = sum1 / n; int cnt = 0; for (int i = 0; i < n; i++) { cnt += max(0, arr[i] - each); } cout<<"Set #"<<++idx<<endl; cout<<"The minimum number of moves is "<<cnt<<"."<<endl; cout<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> A(n); int sum = 0; for(int i=0;i<n;i++) { cin>>A[i]; sum += A[i]; } while(true) { for (int i = 0;i<n-1;i++) { if (A[i]>0) { A[i]--; sum--; cout<<"P"; } cout<<"R"; } if (sum == 0) break; for (int i = n-1;i>0;i--) { if (A[i]>0) { A[i]--; sum--; cout<<"P"; } cout<<"L"; } if (sum ==0) break; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; string s; cin>>s; int count= 0; for (int i=0;i<n;i++) { if (s[i] == '1') { count++; } else { break; } } if (count<n) count++; cout<<count<<endl; return 0; }<file_sep>#include<iostream> #define MOD 10000007 using namespace std; long long fast_exp(long long int base, int exp) { long long res=1; while(exp>0) { if(exp%2==1) res=(res*base)%MOD; base=(base*base)%MOD; exp/=2; } return res%MOD; } int main () { long long int n,k; cin>>n>>k; while(n!=0 || k!=0) { cout<<(fast_exp(n,k) + fast_exp(n,n) + 2*(fast_exp(n-1,k) + fast_exp(n-1,n-1) ) + MOD )%MOD<<endl; cin>>n>>k; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; cin >> n; string st; getchar(); getline(cin, st); while (n--) { getline(cin, st); map <string, vector <string> > dic; vector <string> input; while (st.length() > 0) { input.push_back(st); getline(cin,st); } sort(input.begin(), input.end()); vector <pair< string, string> > res; for (int i = 0;i<input.size();i++) { for (int j = 0;j<input.size();j++) { if (i == j) continue; string t1 = input[i]; string t2 = input[j]; if (t1 > t2) { continue; } if (t1 == t2 && i > j) { continue; } string r1 = ""; string r2 = ""; vector <char> tmp1; vector <char> tmp2; for (auto k:t1) { if (k != ' ') { tmp1.push_back(k); } } for (auto k:t2) { if (k != ' ') { tmp2.push_back(k); } } sort (tmp1.begin(), tmp1.end()); sort (tmp2.begin(), tmp2.end()); for (auto k:tmp1) { r1+=k; } for (auto k:tmp2) { r2+=k; } if (r1 == r2) { res.push_back(make_pair(t1,t2)); } } } for (auto i: res) { cout << i.first << " = " << i.second << endl; } if (n > 0) { cout << endl; } dic.clear(); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; string str(int n) { string res = ""; while (n != 0) { res += n%10 + 48; n /= 10; } reverse(res.begin(), res.end()); return res; } int main () { int n; while (cin>>n) { vector <string> res; int cnt = 0; string s; for (int i = n + 1; i <= 2*n;i++) { if ((i*n)%(i - n) == 0) { cnt++; s = "1/" + str(n) + " = 1/" + str((i*n)/(i - n)) + " + 1/" + str(i); res.push_back(s); } } cout<<cnt<<endl; for (auto i:res) { cout<<i<<endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; int idx = 0; while(cin >> n) { if (n < 0) { break; } vector <int> created(12); vector <int> usage(12); for (int i = 0; i < 12; i++) { cin >> created[i]; } for (int i = 0; i < 12; i++) { cin >> usage[i]; } cout << "Case " << ++idx << ":" << endl; for (int i = 0; i < 12; i++) { if (usage[i] > n) { cout << "No problem. :(" << endl; } else { cout << "No problem! :D" << endl; n -= usage[i]; } n += created[i]; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; vector <int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } sort(Arr.begin(),Arr.end()); int count = 0; while (count<n && Arr[count]<=5-k) { count++; } cout<<count/3<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int ind = -1; int maxi = -9999; for (int i = 0; i < s.length(); i++) { if ( ( (s[i]-48)%2 == 0) && (s[s.length() - 1] - 48) - (s[i] - 48) > 0 ){ ind = i; break; } else if ( ( (s[i]-48)%2 == 0) ) { ind = i; } } if (ind == -1) cout<<ind<<endl; else { for (int i = 0;i<ind;i++) { cout<<s[i]; } cout<<s[s.length()-1]; for (int i= ind+1;i<s.length()-1;i++) { cout<<s[i]; } cout<<s[ind]<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; string t; cin>>s>>t; vector<int> sA(26,0); vector<int> sa(26,0); vector<int> tA(26,0); vector<int> ta(26,0); for (int i = 0; i < s.length(); i++) { int tmp = (int)s[i]; if (tmp<91) { sA[tmp - 65]++; } else { sa[tmp - 97]++; } } for (int i = 0; i < t.length(); i++) { int tmp = (int)t[i]; if (tmp<91) { tA[tmp - 65]++; } else { ta[tmp - 97]++; } } int yay = 0; int whoops = 0; for (int i = 0; i < 26; i++) { if (sa[i] <= ta[i]) { yay+=sa[i]; ta[i] -= sa[i]; sa[i] = 0; } else { yay+=ta[i]; sa[i] -= ta[i]; ta[i] = 0; } if (sA[i] <= tA[i]) { yay+=sA[i]; tA[i] -= sA[i]; sA[i] = 0; } else { yay+=tA[i]; sA[i] -= tA[i]; tA[i] = 0; } whoops += min(tA[i],sa[i]); whoops += min(ta[i],sA[i]); } cout<<yay<<" "<<whoops<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <pair <int,int> > Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i].first>>Arr[i].second; } sort(Arr.begin(),Arr.end()); int l = min(Arr[0].first,Arr[0].second); for (int i=1;i<n;i++) { if (min(Arr[i].first,Arr[i].second) >= l) l = min(Arr[i].first,Arr[i].second); else l = max(Arr[i].first,Arr[i].second); } cout<<l<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); vector <int> dup(n); for (int i = 0; i<n;i++) { cin>>Arr[i]; dup[i] = Arr[i]; } sort(dup.begin(),dup.end()); //cout<<"sort finished"<<endl; int start,end; int sort_flag = 0; for (int i=0;i<n;i++) { if (Arr[i] != dup[i]) { sort_flag = 1; start = i; break; } } if (sort_flag == 0) { cout<<"yes"<<endl; cout<<"1 1"<<endl; return 0; } //cout<<"start found "<<start<<endl; for (int i=n-1;i>=0;i--) { if (Arr[i] != dup[i]) { end = i; break; } } //cout<<"end found "<<end<<endl; int t1 = start, t2 = end; while (start <= t2) { if (Arr[start] != dup[end]) { cout<<"no"<<endl; return 0; } start++; end--; } cout<<"yes"<<endl; cout<<t1+1<<" "<<t2+1<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector < pair<int,int> > coordinates(n); vector < pair<int,int> > y_coordinates(n); for (int i=0;i<n;i++) { cin>>coordinates[i].first; cin>>coordinates[i].second; y_coordinates[i].first = coordinates[i].second; y_coordinates[i].second = coordinates[i].first; } sort(coordinates.begin(),coordinates.end()); sort(y_coordinates.begin(),y_coordinates.end()); vector < pair<int,int> > x_iter; vector < pair<int,int> > y_iter; for (int i=1;i<n-1;i++) { if (coordinates[i].first == coordinates[i-1].first && coordinates[i].first == coordinates[i+1].first) { vector <int> temp(3); temp[0] = coordinates[i-1].second; temp[1] = coordinates[i].second; temp[2] = coordinates[i+1].second; sort(temp.begin(),temp.end()); if (temp[1]>temp[0] && temp[1]<temp[2]) { x_iter.push_back(make_pair(coordinates[i].first,temp[1])); } } } for (int i=1;i<n-1;i++) { if (y_coordinates[i].first == y_coordinates[i-1].first && y_coordinates[i].first == y_coordinates[i+1].first) { vector <int> temp(3); temp[0] = y_coordinates[i-1].second; temp[1] = y_coordinates[i].second; temp[2] = y_coordinates[i+1].second; sort(temp.begin(),temp.end()); if (temp[1]>temp[0] && temp[1]<temp[2]) { y_iter.push_back(make_pair(temp[1],y_coordinates[i].first)); } } } // cout<<"Printing X"<<endl; int count = 0; for (int i=0;i<x_iter.size();i++) { // cout<<x_iter[i].first<<" "<<x_iter[i].second<<endl; if (find (y_iter.begin(),y_iter.end(),x_iter[i]) != y_iter.end()) { count++; } } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; cin>>n; string s; map<char,int> phone; for (int i = 2;i<=6;i++) { for (int j = 0;j<3;j++) { phone[(char)97+(i-2)*3 + j] = j+1; } } for (int i = 112; i< 116;i++) { phone[(char)i] = i - 111; } for (int i = 116; i< 119;i++) { phone[(char)i] = i - 115; } for (int i = 119;i<123;i++) { phone[(char)i] = i-118; } getchar(); for (int i = 1;i<=n;i++) { getline(cin,s); int counts = 0; for (int i = 0;i<s.length();i++) { if (s[i] == ' ') counts++; else counts+=phone[s[i]]; } cout<<"Case #"<<i<<": "<<counts<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; cout<<n+m-1<<endl; for (int i = 1;i<=m;i++) { cout<<"1 "<<i<<endl; } for (int i=2;i<=n;i++) { cout<<i<<" 1"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; cin>>n; int a = 0; int b = 1; if (n == 1) cout<<0<<endl; else if (n == 2) cout<<"0 1"<<endl; else { cout<<"0 1 "; for (int i = 2;i<n-1;i++) { cout<<a+b<<" "; int temp = a+b; a = b; b = temp; } cout<<a+b<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); int hundred = 0; int twohundred = 0; int sum = 0; for (int i=0;i<n;i++) { cin>>Arr[i]; if (Arr[i] == 100) hundred++; else if (Arr[i] == 200) twohundred++; } if (twohundred%2 == 0 && hundred%2== 0 ) cout<<"YES"<<endl; else if (twohundred%2 == 1 && hundred%2 == 0 && hundred>=2) cout<<"YES"<<endl; else cout<<"NO"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; for (int i=1;i<=n;i++) { cout<<i<<" "<<i*i<<" "<<i*i*i<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int k,l; cin>>k>>l; long long int temp=k; int count = 0; while (temp< l) { temp*=k; count++; } if (temp == l) { cout<<"YES"<<endl<<count<<endl; } else { cout<<"NO"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int matrix[3][3]; int sum = 0; int row[3] = {0}; for (int i = 0;i<3;i++) { for (int j = 0; j < 3; j++) { cin>>matrix[i][j]; sum+= matrix[i][j]; row[i] += matrix[i][j]; } } for (int i = 0; i < 3; i++) { matrix[i][i] = sum/2 - row[i]; } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout<<matrix[i][j]<<" "; } cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; int t1, t2, final, att, ct1, ct2, ct3; int idx = 0; while(t--) { cin >> t1 >> t2 >> final >> att >> ct1 >> ct2 >> ct3; int sum = t1 + t2 + final + att + (ct1 + ct2 + ct3 - min(min(ct1, ct2), ct3))/2; cout << "Case " << ++idx << ": "; if (sum >= 90) { cout << "A" << endl; } else if (sum >= 80) { cout << "B" << endl; } else if (sum >= 70) { cout << "C" << endl; } else if (sum >= 60) { cout << "D" << endl; } else { cout << "F" << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int make_int(string d) { int n = 0; for (int i = 0;i<d.length();i++) { n = n*10 + d[i] - 48; } return n; } int sum_string(string s) { int sum = 0; for (int i = 0;i<s.length();i++) { sum += (s[i] - 48); } return sum; } bool check_mod4(string s) { if (s.length() < 6) { int n = make_int(s); return (n % 4 == 0); } else { int n = (s[s.length() - 2]-48)*10 + (s[s.length() - 1] - 48); return (n%4 == 0); } } bool check_mod100(string s) { if (s.length() < 6) { int n = make_int(s); return (n %100 == 0); } else { int n = 0; for (int i = s.length() - 3;i < s.length();i++) { n = n*10 + (s[i] - 48); } return (n%100 == 0); } } bool check_mod400 (string s) { if (s.length() < 6) { int n = make_int(s); return (n % 400 == 0); } else { int n = 0; for (int i = s.length() - 4;i < s.length();i++) { n = n * 10 + (s[i] - 48); } return (n % 400 == 0); } } bool check_mod15 (string s) { if (sum_string(s) % 3 == 0 && (s[s.length() - 1] - 48)%5 == 0) return true; else return false; } bool check_mod55(string s) { int odd = 0; int even = 0; for (int i = 0;i<s.length();i+=2) { even += (s[i] - 48); } for (int i = 1;i< s.length();i+=2) { odd += (s[i] - 48); } if (abs(odd - even) % 11 == 0 && (s[s.length() - 1] - 48)%5 == 0 ) return true; else return false; } int main () { string n; cin>>n; while (1) { bool flag = false; bool mod4 = check_mod4(n); // cout<<mod4<<endl; bool mod55 = check_mod55(n); // cout<<mod55<<endl; bool mod15 = check_mod15(n); // cout<<mod15<<endl; bool mod400 = check_mod400(n); // cout<<mod400<<endl; bool mod100 = check_mod100(n); // cout<<mod100<<endl; bool leap = (mod400 || mod4 && !mod100); if (leap) { cout<<"This is leap year."<<endl; flag = true; } if (mod15) { cout<<"This is huluculu festival year."<<endl; flag = true; } if (leap && mod55) { cout<<"This is bulukulu festival year."<<endl; flag = true; } if (!flag) { cout<<"This is an ordinary year."<<endl; } if (cin>>n) { cout<<endl; } else { break; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int R, C, N; int r, c; int r0, c0; int idx = 0; while (cin >> R >> C >> N) { if (R + C + N == 0) { break; } set <int> rows; set <int> cols; for (int i = 0; i < N; i++) { cin >> r >> c; rows.insert(r); cols.insert(c); } cin >> r0 >> c0; cout << "Case " << ++idx << ": "; if (rows.find(r0) == rows.end() && cols.find(c0) == cols.end()) { cout << "Escaped again! More 2D grid problems!" << endl; } else if (r0 > 0 && rows.find(r0 - 1) == rows.end() && cols.find(c0) == cols.end()) { cout << "Escaped again! More 2D grid problems!" << endl; } else if (r0 < R - 1 && rows.find(r0 + 1) == rows.end() && cols.find(c0) == cols.end()){ cout << "Escaped again! More 2D grid problems!" << endl; } else if (c0 < C - 1 && rows.find(r0) == rows.end() && cols.find(c0 + 1) == cols.end()){ cout << "Escaped again! More 2D grid problems!" << endl; } else if (c0 > 0 && rows.find(r0) == rows.end() && cols.find(c0 - 1) == cols.end()){ cout << "Escaped again! More 2D grid problems!" << endl; } else { cout << "Party time! Let's find a restaurant!" << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; int arr[n][m]; vector<int> max(m,-1); vector<int> counts(m,0); string input; vector<int> winners(n,0); for (int i=0;i<n;i++) { cin>>input; for (int j = 0;j<m;j++) { int t = input[j] - 48; arr[i][j] = t; } } for (int i = 0;i<m;i++) { vector <int> temp; int max = -1; for (int j=0;j<n;j++) { if (arr[j][i]>max) { max = arr[j][i]; temp.clear(); temp.push_back(j); } else if (arr[j][i] == max) { temp.push_back(j); } } for ( int j= 0;j<temp.size();j++) { winners[temp[j]]++; } } int count = 0; for (int i=0;i<n;i++) { if (winners[i] > 0) { count++; } } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int N,B,H,W; while (cin>>N>>B>>H>>W) { int cost; int min_cost = INT_MAX; for (int ii = 0; ii < H;ii++) { vector <int> beds(W); cin>>cost; int max_bed = 0; for (int i = 0;i < W; i++) { cin>>beds[i]; max_bed = max(max_bed, beds[i]); } if (max_bed >= N && cost*N <= B) { min_cost = min(min_cost, cost*N); } } if (min_cost <= B) cout<<min_cost<<endl; else cout<<"stay home"<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int temp; for (int i = 0; i < n; i++) { cin >> temp; if (temp == 0) { cout<<"NULL"<<endl; continue; } if (temp%2==0) { cout<<"EVEN "; } else { cout<<"ODD "; } if (temp<0) { cout<<"NEGATIVE"<<endl; } else { cout<<"POSITIVE"<<endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; long long int inti(char a, char b) { return (a-48ll)*10ll + b-48ll; } int main () { string s; while(cin>>s) { long long int hh = inti(s[0], s[1]); long long int mm = inti(s[2], s[3]); long long int ss = inti(s[4], s[5]); long long int cc = inti(s[6], s[7]); long double tt1 = (hh*3600ll + mm*60ll + ss)*100ll + cc; tt1 *= 125ll; tt1 /= 108ll; long long int tt = (int)round(tt1); long long int h = tt/1000000; cout<<h; tt %= 1000000; int m = tt/10000; cout<<(m<10?"0":"")<<m; tt %= 10000; int s1 = tt/100; cout<<(s1<10?"0":"")<<s1; tt %= 100; cout<<(tt<10?"0":"")<<tt<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int time_delta(int t2,int t1) { int delta; delta = t2 - t1; if (delta < 0) delta+= 1440; return delta; } int main () { int t; cin>>t; int idx = 0; while(t--) { cout<<"Case "<<++idx<<": "; int n; int h,m; char c; cin>>n; cin>>h>>c>>m; int t1 = h*60 + m; int h2, m2; int delta; int mini = INT_MAX; while (n--) { cin>>h2>>c>>m2; cin>>delta; mini = min(mini, time_delta(h2*60 + m2, t1) + delta); } cout<<mini<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m,k; cin>>n>>m>>k; vector <int> Arr(m); int fedor; for (int i=0;i<m;i++) { cin>>Arr[i]; } cin>>fedor; int count = 0; vector <int> fedor_bits; for (int i = 0;i<20;i++) { fedor_bits.push_back(fedor%2); fedor/=2; } for (int i = 0;i<m;i++) { vector <int> temp_bits; int temp = Arr[i]; for (int j = 0;j<20;j++) { temp_bits.push_back(temp%2); temp/=2; } int check = 0; for (int j=0;j<20;j++) { if (fedor_bits[j] != temp_bits[j]) check++; } if (check<=k) count++; } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; map<string, int> score; vector <pair <string, int> > Arr(n); map <string,int> winners; string s; int v; string winner; int max=-1100000000; int iter = -1; for (int i=0;i<n;i++) { cin>>s>>v; Arr[i].first = s; Arr[i].second = v; if (score.find(s)!= score.end()) { score[s] +=v; } else { score[s] = v; } } for (map<string,int>::iterator it=score.begin(); it!=score.end(); ++it) { if (it -> second > max) { max = it -> second; winners.clear(); winners[it -> first] = 1; } else if (it -> second == max) { winners[it -> first]=1; } } score.clear(); for (int i=0;i<n;i++) { s = Arr[i].first; v = Arr[i].second; if (score.find(s)!= score.end()) { score[s] +=v; if (score[s]>= max && winners.find(s) != winners.end()) { cout<<s<<endl; return 0; } } else { score[s] = v; if (score[s]>= max && winners.find(s) != winners.end() ) { cout<<s<<endl; return 0; } } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { cin.sync_with_stdio(0);cin.tie(0); int t; int idx = 0; while (cin >> t) { if (t == 0) { break; } int team_count; int element; map <int, int> user_to_team; map <int, queue<int> > data; queue <int> global; for (int i = 0; i < t; i++) { cin >> team_count; for (int j = 0; j < team_count; j++) { cin >> element; user_to_team[element] = i; } } cout << "Scenario #" << ++idx << endl; string command; while (cin >> command) { if (command == "STOP") { break; } else if (command == "DEQUEUE") { cout << data[global.front()].front() << endl; data[global.front()].pop(); if (data[global.front()].empty()) { global.pop(); } } else if (command == "ENQUEUE") { cin >> element; int team = user_to_team[element]; if (data.find(team) == data.end() || data[team].empty()) { global.push(team); data[team].push(element); } else { data[team].push(element); } } } cout << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int n,r,avg; cin>>n>>r>>avg; long long int a,b; vector< pair<long long int,long long int> > v(n); long long int sum = 0; for (int i = 0; i < n; i++) { cin>>a>>b; v[i].first = b; v[i].second = a; sum += a; } sum = avg * n - sum; if (sum <= 0) { cout<<0<<endl; return 0; } sort(v.begin(), v.end()); int id = 0; long long int counter = 0; while (sum>0) { if (r - v[id].second >0) { counter+= min(r - v[id].second,sum)*v[id].first; sum -= min(r - v[id].second,sum); } id++; } cout<<counter<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> A(n); for (int i=0;i<n;i++) { cin>>A[i]; } long long int cnt = 0; sort(A.begin(),A.end()); for (int i=1;i<=n;i++) { cnt+=abs(i-A[i-1]); } cout<<cnt<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { double a, b; while(cin>>a>>b) { cout<<a<<" "<<b<<" "; double t = (43200*(86400-a))/abs(a-b); t = fmod(t,43200); int h = (int)(t/3600); int m = (int)round((fmod(t,3600)/60)); if (m == 60) { h += 1; m = 0; } h %= 12; if (h == 0) { h = 12; } cout<<((h<10)?"0":"")<<h<<":"<<((m<10)?"0":"")<<m<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; bool isDistinct(int a) { set <int> check; int cnt = 0; while(a!=0) { check.insert(a%10); a/=10; cnt++; } if (cnt == check.size()) { return true; } else { return false; } } int main() { int n; cin>>n; n++; while(!isDistinct(n)) n++; cout<<n; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { char c; cin>>c; string s1,s2; pair<int,int> temp; while (1) { if (c == '#') break; cin>>s1>>s2; s1+=s2; int index; if (c == 'S') { index = 1; } else if (c == 'W') { index = 2; } else if (c == 'N') { index = 3; } else if (c == 'E') { index = 0; } vector < pair<int,int> > players[4]; for(int i = 0; i < 104; i += 2) { if (s1[i] == 'C') { temp.first = 0; } else if (s1[i] == 'D') { temp.first = 1; } else if (s1[i] == 'S') { temp.first = 2; } else if (s1[i] == 'H') { temp.first = 3; } if (s1[i+1] == 'T') { temp.second = 10; } else if (s1[i+1] == 'J') { temp.second = 11; } else if (s1[i+1] == 'Q') { temp.second = 12; } else if (s1[i+1] == 'K') { temp.second = 13; } else if (s1[i+1] == 'A') { temp.second = 14; } else { temp.second = s1[i+1] - 48; } players[index].push_back(temp); index = (index+1)%4; } for (int i = 0; i < 4; i++) { if (i == 0) cout<<"S: "; else if (i == 1) cout<<"W: "; else if (i == 2) cout<<"N: "; else if (i == 3) cout<<"E: "; sort(players[i].begin(),players[i].end()); for (int j = 0; j < players[i].size(); j++) { temp = players[i][j]; if (temp.first == 0) cout<<'C'; else if (temp.first == 1) cout<<'D'; else if (temp.first == 2) cout<<'S'; else if (temp.first == 3) cout<<'H'; if (temp.second == 10) cout<<'T'; else if (temp.second == 11) cout<<'J'; else if (temp.second == 12) cout<<'Q'; else if (temp.second == 13) cout<<'K'; else if (temp.second == 14) cout<<'A'; else cout<<temp.second; if (j!=12) cout<<' '; } players[i].clear(); cout<<endl; } cin>>c; } return 0; } //Room numbers are 22221188 or 22660000. Report this. <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int temp; cin>>temp; int max = temp; int min = temp; int cnt = 0; for (int i=1;i<n;i++) { cin>>temp; if (temp > max) { max = temp; cnt++; } else if (temp < min) { min = temp; cnt++; } } cout<<cnt<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; while (t--) { int d; cin>>d; string s; int a,b; multimap<string, pair<int,int> > database; while (d--) { cin>>s>>a>>b; database.insert(make_pair(s,make_pair(a,b))); } int q; cin>>q; int p; while(q--) { cin>>p; string res = ""; for (auto i:database) { if (i.second.first <= p && p <= i.second.second) { if (res == "") res = i.first; else { res = ""; break; } } } if (res == "") { cout<<"UNDETERMINED"<<endl; } else { cout<<res<<endl; } } if (t > 0) cout<<endl; } return 0; } <file_sep>/* No need to use any formatting, everything can be space separated, don't even care to fill the voids with spaces as in the case of unknowns. Only check if gievn code is STD, and number is valid. Similarly for ISD. */ #include <bits/stdc++.h> using namespace std; stringstream ss; bool is_isd(string s) { if (s[0] == '0' && s[1] == '0' && s.length() > 2) { return true; } return false; } bool is_std(string s) { if (s[0] == '0' && s.length() > 1) { return true; } return false; } void print_invalid(string s, int d) { cout << s << " " << "Unknown" << " " << d << " " << "-1.00" << endl; } void print_local(string s, int d) { cout << s << " " << "Local" << " " << s << " " << d << " " << 0.00 << " " << 0.00 << endl; } int main () { map <string, pair<string, int> > codes; string inp; while(1) { getline(cin, inp); if (inp == "000000") { break; } ss.str(""); ss.clear(); ss.str(inp); string code1; string code2; string region = ""; ss >> code1; getline(ss, code2); int cost = 0; int i = 1; for (; i < code2.length(); i++) { if (code2[i] != '$') { region += code2[i]; } else { break; } } i += 1; for (; i< code2.length(); i++) { cost = cost*10 + (code2[i] - 48); } codes[code1] = make_pair(region, cost); } while (1) { getline(cin, inp); if (inp == "#") { break; } string code1; int duration; ss.str(""); ss.clear(); ss.str(inp); ss >> code1 >> duration; string code = ""; if (code1[0] != '0') { print_local(code1, duration); continue; } cout << fixed << setprecision(2); bool flag = true; bool invalid = false; for (int i = 0; i < code1.length();) { code += code1[i]; string temp = ""; for (int j = i + 1; j < code1.length(); j++) { temp += code1[j]; } if ((is_isd(code) && codes.find(code) != codes.end() && temp.length() >= 4 && temp.length() <= 10) || (is_std(code) && codes.find(code) != codes.end() && temp.length() >= 4 && temp.length() <= 7)){ flag = false; cout << code1 << " " << codes[code].first << " " << temp << " " << duration << " "; cout << (double)codes[code].second/100 << " " << ((double)codes[code].second*duration)/100; cout << endl; break; } i+=1; } if (flag) { print_invalid(code1, duration); } } return 0; } <file_sep>#/usr/bin/python for i in range(0,10): n=input() m=input() n=int(n) m=int(m) if n%2==1: n1=n//2+m//2+1 n2=n-n1 elif n%2==0: n1=n//2+m//2 n2=n-n1 print(n1) print(n2) <file_sep>#include<bits/stdc++.h> using namespace std; int main() { string s; cin >> s; if (s.length() == 1) { int n = s[0] - 48; if (n%4 == 0) cout<<"4\n"; else cout<<"0\n"; } else { int a = s[s.length()-1] - 48; int b = s[s.length()-2] - 48; if ((b*10 + a)%4 == 0) cout<<"4\n"; else cout<<"0\n"; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k; queue<int> q; vector <int> out; while (1) { cin>>n>>k; vector <int> ppl(n+1,40); if (n == 0 && k == 0) { break; } for(int i = 1;i<=n;i++) { q.push(i); } int dispense = 1; int store = 0; while (!q.empty()) { int person = q.front(); q.pop(); if (dispense == k+1) dispense = 1; int temp = ppl[person]; store += dispense; dispense++; cout<<person<<" "<<temp<<" "<<store<<" "<<dispense<<endl; ppl[person] -= min(store,ppl[person]); store -= min(temp,store); if (ppl[person]>0) q.push(person); else out.push_back(person); } for (int i = 0;i<out.size();i++) { cout<<out[i]<<" "; } cout<<endl; ppl.clear(); out.clear(); } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif string s; ISTREAM>>s; if (s[0] != '9' && (9 - (s[0]-48)) < (s[0] - 48) ) { s[0] = 48 + '9' - s[0]; } for (int i = 1; i < s.length();i++) { if ((9 - (s[i]-48)) < (s[i] - 48)) { s[i] = 48 + '9' - s[i]; } } cout<<s<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME bool isPrime(int n) { for (int i = 2;i*i<=n;i++) { if (n%i == 0) { return false; } } return true; } #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; int temp; ISTREAM>>n; for (int i=0;i<n;i++) { ISTREAM>>temp; if (isPrime(temp)) { cout<<temp<<" eh primo"<<endl; } else { cout<<temp<<" nao eh primo"<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; while (scanf("%d",&n) != EOF) { for (int i=0;i<n;i++) { for (int j = 0;j<n;j++) { if (j == n - i - 1) { cout<<"2"; } else if (i == j) { cout<<"1"; } else { cout<<"3"; } } cout<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector <int> numbers(n); vector <int> get_nums(m); for(int i = 0; i < n; i++) { cin >> numbers[i]; } for(int i = 0; i < m; i++) { cin >> get_nums[i]; } multiset <int> left; multiset <int> right; int element_count = 0; int ind = 0; int pop_counter = 1; for (int i = 0; i < m; i++) { while(element_count < get_nums[i]) { if (left.empty() || numbers[ind] < *left.rbegin()) { left.insert(numbers[ind++]); } else { right.insert(numbers[ind++]); } element_count += 1; } while((int)left.size() > pop_counter) { right.insert(*left.rbegin()); left.erase(left.find(*left.rbegin())); } while((int)left.size() < pop_counter) { left.insert(*right.begin()); right.erase(right.find(*right.begin())); } cout << *left.rbegin() << endl; pop_counter += 1; } if (t > 0) { cout << endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int val (char c) { if (c == 'X') return 10; else if (c == '/') return 11; else return c - 48; } int main () { string s; getline(cin,s); while (s != "Game Over") { vector < char> moves; vector <int> scores; for (int i = 0;i<s.length();i++) { if (s[i] != ' ') { moves.push_back(s[i]); } } int cnt = 0; int score = 0; for (int i = 0;i<moves.size();i++) { if (val(moves[i]) == 10 && cnt < 10) { score += 10; int t1 = val(moves[i+1]); int t2 = val(moves[i+2]); if (t2 == 11) score += 10; else score += t1 + t2; } else if (cnt < 10){ int t1 = val(moves[i]); int t2 = val(moves[i+1]); if (t2 == 11) { score += 10; score += val(moves[i+2]); } else { score += t1 + t2; } i+=1; } cnt++; } cout<<score; cout<<endl; getline(cin,s); } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main (){ int t; cin >> t; int idx = 0; double c, n; while(t--) { cout<<"Case "<<++idx<<": "; cin >> c >> n; c = ((((9*c)/5 + 32 + n) -32)*5)/9; cout<<fixed<<setprecision(2)<<c<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin >> t; int h,m; char c; while (t--) { cin>>h>>c>>m; int m_mod = (60 - m)%60; int h_mod = 12 - h; if (m_mod > 0) { h_mod -= 1; } if (h_mod <= 0) h_mod += 12; cout<<(h_mod < 10?"0":"")<< h_mod << ":" << (m_mod < 10?"0":"") << m_mod << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; struct classcomp { bool operator() (const char& lhs, const char& rhs) const {return 0;} }; int main (){ int n; cin >> n; int code, note, m, b, t; while (n != -1) { multimap < int, vector <int>, classcomp > dic; for (int i = 0; i < n;i++) { vector <int> temp; cin >> code >> note >> m >> b >> t; t = (t/30); if (t%2 == 1) { t+= 1; } t *= 30; if (t == 480) { t = 0; b += 1; } if (b == 5) { m += 1; b = 1; } temp.push_back(code); temp.push_back(m); temp.push_back(b); temp.push_back(t); if (code == 1) { dic.insert(make_pair(note, temp)); } else { multimap <int, vector <int> , classcomp >::iterator it1; for (multimap <int, vector <int> , classcomp >::iterator it = dic.begin(); it != dic.end(); it++) { if (it -> first == note) { it1 = it; } } vector <int> rr = it1->second; if (temp[1] == rr[1] && temp[2] == rr[2] && temp[3] == rr[3]) { dic.erase(it1); } else { dic.insert(make_pair(note, temp)); } } } cout<<dic.size()<<endl; for (auto i:dic) { cout << i.second[0] << " " << i.first << " " << i.second[1] << " " << i.second[2] << " " << i.second[3] << endl; } cin >> n; } cout<<-1<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; for (int i = 1; i < n-k; ++i) { cout<<i<<" "; } for (int i=n; i>=n-k;i--) { cout<<i<<" "; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { std::ios::sync_with_stdio(false); int sz; cin >> sz; int idx = 0; while(sz != 0) { cout<<"Output for data set "<<++idx<<", "<<sz<<" bytes:"<<endl; int n; int sum_till_now = 0; int buffer = 0; int i = 0; int ctr = 0; while(sum_till_now < sz) { cin >> n; sum_till_now += n; buffer += n; i+= 1; if (i%5 == 0) { cout<<" Time remaining: "; if (buffer == 0) { cout<<"stalled"<<endl; } else { cout<<ceil((double)((sz - sum_till_now)*5)/(double)buffer)<<" seconds"<<endl;; } buffer = 0; } ctr+= 1; } cout<<"Total time: "<<ctr<<" seconds"<<endl; cout<<endl; cin >> sz; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int N; while(1) { ISTREAM>>N; if (N == 0) break; string s = "+x"; string n; for (int i = 0; i < N-1; i++) { //cout<<s<<endl; ISTREAM>>n; if (n == "No") { continue; } else if (s[1] == 'x') { s[1] = n[1]; if (n[0] != s[0]) s[0] = '-'; else s[0] = '+'; } else if (s[1] == n[1]) { s[1] = 'x'; if (n[0] != s[0]) s[0] = '+'; else s[0] = '-'; } } cout<<s<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; while (cin >> n) { vector <int> arr(n); for (int i = 0; i < n; i++) { cin >> arr[i]; } sort(arr.begin(), arr.end()); int cnt1; int cnt2; int median; int median1; int median2; if (n % 2 == 0) { int A = arr[(n - 1) / 2]; int B = arr[n / 2]; median = A; vector <int>:: iterator low = lower_bound(arr.begin(), arr.end(), A); vector <int>:: iterator high = upper_bound(arr.begin(), arr.end(), B); cnt1 = high - low; cnt2 = B - A + 1; } else { median = arr[n / 2]; vector <int>:: iterator low = lower_bound(arr.begin(), arr.end(), median); vector <int>:: iterator high = upper_bound(arr.begin(), arr.end(), median); cnt1 = high - low; cnt2 = 1; } cout << median << " " << cnt1 << " " << cnt2 << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; class UFDS { private: int size; vector <int> parent; vector <int> rank; vector <int> counts; public: UFDS(int n) { size = n; parent.assign(size, 0); counts.assign(size, 1); for(int i = 0; i < size; i++) { parent[i] = i; } } int findset(int a) { return (parent[a] == a?a:(parent[a] = findset(parent[a]))); } bool is_same_set(int a, int b) { return findset(a) == findset(b); } void union_set(int a, int b) { int x = findset(a); int y = findset(b); if (!is_same_set(a, b)) { parent[x] = y; counts[y] = counts[y] + counts[x]; } } int result() { int maxi = -1; for (int i = 0; i < size; i++) { maxi = max(maxi, counts[i]); } return maxi; } }; int main() { int n,r; while(cin >> n >> r) { if (n + r == 0) { break; } map <string, int> name_map; string name, name1; for(int i = 0; i < n; i++) { cin >> name; name_map[name] = i; } UFDS case1(n); for(int i = 0; i < r; i++) { cin >> name >> name1; case1.union_set(name_map[name], name_map[name1]); } cout << case1.result() << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; cin>>n; long long int ele; int n1; multiset<long long int>::iterator it; while (n!=0) { long long int cost = 0; multiset <long long int> cont; for (int i = 0;i<n;i++) { cin>>n1; for (int j = 0;j<n1;j++) { cin>>ele; cont.insert(ele); } cost += *cont.rbegin() - *cont.begin(); it = cont.begin(); cont.erase(it); it = cont.end(); it--; cont.erase(it); } cout<<cost<<endl; cin>>n; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; int n; int ele; cin >> t; int idx = 0; while (t--) { set <int> frst; set <int> scond; set <int> thrd; set <int> i_frst; set <int> i_scond; set <int> i_thrd; cin >> n; for (int i = 0; i < n; i++) { cin >> ele; frst.insert(ele); } cin >> n; for (int i = 0; i < n; i++) { cin >> ele; scond.insert(ele); } cin >> n; for (int i = 0; i < n; i++) { cin >> ele; thrd.insert(ele); } for (auto i:frst) { if (scond.find(i) == scond.end() && thrd.find(i) == thrd.end()) { i_frst.insert(i); } } for (auto i:scond) { if (frst.find(i) == frst.end() && thrd.find(i) == thrd.end()) { i_scond.insert(i); } } for (auto i:thrd) { if (frst.find(i) == frst.end() && scond.find(i) == scond.end()) { i_thrd.insert(i); } } int maxi = - 1; maxi = max(maxi, (int)i_frst.size()); maxi = max(maxi, (int)i_scond.size()); maxi = max(maxi, (int)i_thrd.size()); cout<<"Case #"<<++idx<<":"<<endl; if ((int)i_frst.size() == maxi) { cout << 1 << " " << (int)i_frst.size(); for (auto i: i_frst) { cout << " " << i; } cout << endl; } if ((int)i_scond.size() == maxi) { cout << 2 << " " << (int)i_scond.size(); for (auto i: i_scond) { cout << " " << i; } cout << endl; } if ((int)i_thrd.size() == maxi) { cout << 3 << " " << (int)i_thrd.size(); for (auto i: i_thrd) { cout << " " << i; } cout << endl; } } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; int main() { int n; cin >>n; int check[] = {0,5,15,35,75,155,315,635,1275,2555,5115,10235,20475,40955,81915,163835,327675,655355,1310715,2621435,5242875,10485755,20971515,41943035,83886075,167772155,335544315,671088635,1342177275}; string gentlemen [] = {"Sheldon", "Leonard", "Penny", "Rajesh", "Howard"}; int subtract = 0; int i = 0; while ( check[i] < n ) { subtract = check[i]; i++; } int num = n - subtract; int den = (check[i-1]/5)+1; int res = num/den + (int)(num%den > 0); cout<<gentlemen[res-1]<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<int > arr(n); vector<int > brr(n); for (int i = 0; i < n; i++) { cin>>arr[i]; } int a = arr[0]; for (int i = 0;i<n;i++) { if (i%2==0) brr[i] = (arr[i]-a +n)%n; else brr[i] = (arr[i] + a)%n; } int flag = 0; for (int i = 0;i<n;i++) { if (brr[i]!=i) { flag = 1; break; } } if (flag == 0) { cout<<"Yes"<<endl; return 0; } a = n - arr[0]; for (int i = 0;i<n;i++) { if (i%2==0) brr[i] = (arr[i]+a)%n; else brr[i] = (arr[i] +n - a)%n; } flag = 0; for (int i = 0;i<n;i++) { if (brr[i]!=i) { flag = 1; break; } } if (flag == 0) { cout<<"Yes"<<endl; return 0; } cout<<"No"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; string s; for (int i = 0; i < n; i++) { ISTREAM>>s; int l = s.length(); if (s == "4" || s == "78" || s=="1") cout<<"+"<<endl; else if (s[l-1] == '5' && s[l-2] == '3') cout<<"-"<<endl; else if (s[0] == '9' && s[l-1] == '4') cout<<"*"<<endl; else if (s[0] == '1' && s[1] == '9' && s[2] == '0') cout<<"?"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int t,res; for (int i = 1; i < 55; i++) { t = (i*(i+1)*(i+2))/6; if (t>n) break; res = i; } cout<<res<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; map <string, string> split(string s) { map <string, string> res; int flag = 0; string r1 = ""; string r2 = ""; for (int i = 1; i < s.length() - 1; i++) { if (flag == 0) { if (s[i] == ':') { flag ^= 1; continue; } r1 += s[i]; } else { if (s[i] == ',') { flag ^= 1; res[r1] = r2; r1 = ""; r2 = ""; continue; } r2 += s[i]; } } if (s.length() > 2) { res[r1] = r2; } return res; } int main() { int t; cin >> t; string inp1, inp2; while(t--) { bool flag = false; cin >> inp1 >> inp2; map <string, string> m1 = split(inp1); map <string, string> m2 = split(inp2); set <string> deleted; set <string> modi; set <string> inserted; for (auto i:m1) { if (m2.find(i.first) == m2.end()) { flag = true; deleted.insert(i.first); } else if (m2[i.first] != m1[i.first]) { flag = true; modi.insert(i.first); } } for (auto i:m2) { if (m1.find(i.first) == m1.end()) { flag = true; inserted.insert(i.first); } } // cout << "yo" << endl; if (!flag) { cout << "No changes" << endl; } else { if (!inserted.empty()) { cout << "+"; for (auto i:inserted) { if (i == *inserted.rbegin()) { cout << i << endl; } else { cout << i << ","; } } } if (!deleted.empty()) { cout << "-"; for (auto i:deleted) { if (i == *deleted.rbegin()) { cout << i << endl; } else { cout << i << ","; } } } if (!modi.empty()) { cout << "*"; for (auto i:modi) { if (i == *modi.rbegin()) { cout << i << endl; } else { cout << i << ","; } } } } cout << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n,t; ISTREAM>>n>>t; vector <int> arr(n); for (int i = 0; i < n-1; i++) { ISTREAM>>arr[i]; } int flag = 0; int i = 0; while (i < n) { if (i+1 == t) { flag = 1; break; } if (i+1 > t) break; i += arr[i]; } if (flag == 0) cout<<"NO"<<endl; else cout<<"YES"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif double S = 0.0; double i=1.0; double j=1.0; while (i<=39) { S+=i/j; i+=2; j*=2; } cout<<fixed<<setprecision(2); cout<<S<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; bool flag = false; while(scanf("%d",&n)!= EOF) { if (flag == true) cout<<endl; else flag = true; vector <int> capacity(n); int total_capacity = 0; int cargo_weight = 0; for (int i = 0;i<n;i++) { cin>>capacity[i]; total_capacity += capacity[i]; } vector <int> items(n,0); vector <vector<int> > ship(n); getchar(); int p; cin>>p; int wt; vector<int> wts; int total_cargo = 0; for (int i = 0;i<p;i++) { cin>>wt; wts.push_back(wt); total_cargo += wt; } for (auto wt:wts) { int kmin = 0; vector <int> possible_cargo; for (int i = 0;i<n;i++) { if (items[i] < items[kmin]) { kmin = i; possible_cargo.clear(); possible_cargo.push_back(i); } else if (items[i] == items[kmin]) { possible_cargo.push_back(i); } } // for (auto i:possible_cargo) { // cout<<i<<" "; // } // cout<<endl; vector <int> possible_cargo2; kmin = 0; for (auto i:possible_cargo) { if (capacity[i] > kmin) { kmin = capacity[i]; possible_cargo2.clear(); possible_cargo2.push_back(i); } else if (capacity[i] == kmin) { possible_cargo2.push_back(i); } } // for (auto i: possible_cargo2) { // cout<<i<<" "; // } // cout<<endl; int selected = possible_cargo2[0]; if (wt > capacity[selected]) { break; } ship[selected].push_back(wt); cargo_weight += wt; capacity[selected] -= wt; items[selected]+=1; } int kmin = 0; for (int i = 0;i<n;i++) { if (ship[i].size()>kmin) { kmin = ship[i].size(); } } for (int i = 0;i<n;i++) { for (int j = ship[i].size(); j<kmin;j++) { ship[i].push_back(-1); } } for (int i = kmin - 1;i>= 0;i--) { for (int j = 0;j<n;j++) { if (ship[j][i] == -1) cout<<":"; else cout<<ship[j][i]; if (i >= 0 && j<n-1) cout<<" "; } cout<<endl; } for (int i = 0;i<2*n-1;i++) { cout<<"="; } cout<<endl; for (int i = 1;i<=n;i++) { cout<<i; if (i<n) cout<<" "; } cout<<endl; cout<<endl; cout<<"cargo weight: "<<cargo_weight<<endl; cout<<"unused weight: "<<total_capacity - cargo_weight<<endl; cout<<"unloaded weight: "<<total_cargo - cargo_weight<<endl; getchar(); } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,b,c; cin>>a>>b>>c; cout<<max(max(max(a*b*c,a*(b+c)),(a+b)*c),(a+b+c))<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int k,n,w; cin>>k>>n>>w; cout<<max((k*w*(w+1))/2 - n,0)<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { float n; cin>>n; float inc; cout<<fixed<<setprecision(2); if (n >= 0 && n <= 400.0 ) { inc = (15*n)/100; cout<<"Novo salario: "<<n+inc<<endl; cout<<"Reajuste ganho: "<<inc<<endl; cout<<"Em percentual: 15 %"<<endl; } else if (n > 400 && n <= 800.0 ) { inc = (12*n)/100; cout<<"Novo salario: "<<n+inc<<endl; cout<<"Reajuste ganho: "<<inc<<endl; cout<<"Em percentual: 12 %"<<endl; } else if (n > 800 && n <= 1200.0 ) { inc = (10*n)/100; cout<<"Novo salario: "<<n+inc<<endl; cout<<"Reajuste ganho: "<<inc<<endl; cout<<"Em percentual: 10 %"<<endl; } else if (n > 1200 && n <= 2000.0 ) { inc = (7*n)/100; cout<<"Novo salario: "<<n+inc<<endl; cout<<"Reajuste ganho: "<<inc<<endl; cout<<"Em percentual: 7 %"<<endl; } else if (n > 2000) { inc = (4*n)/100; cout<<"Novo salario: "<<n+inc<<endl; cout<<"Reajuste ganho: "<<inc<<endl; cout<<"Em percentual: 4 %"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int a,b,c,d; while (cin>>a>>b>>c>>d) { if (a + b + c + d == 0) break; int t1 = a*60 + b; int t2 = c*60 + d; int t = t2 - t1; if (t < 0) t+= 1440; cout<<t<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; string small(string s) { string res = ""; for (int i = 0; i < (int)s.length(); i++) { if ((int)s[i] <= 90 && (int)s[i] >= 65) { res += (char)((int)s[i] + 32); } else { res += s[i]; } } return res; } int main() { int n; int m; string inp; bool flag = false; while (cin >> n >> m) { if (n + m == 0) { break; } if (flag == false) { flag = true; } else { cout << endl; } int n1 = n; map <string, string> ranker; map <string, int> ranks; map <int, string> rev_ranks; while (n1--) { cin >> inp; ranker[small(inp)] = inp; } int cnt = 0; for (auto i:ranker) { ranks[i.second] = cnt; rev_ranks[cnt] = i.second; cnt += 1; } vector <vector <int> > tournament(n, vector<int> (9,0)); for (int i = 0; i < n; i++) { tournament[i][3] = i; } int total_points = 0; while (m--) { char tmp; string player1; string player2; int goal1; int goal2; cin >> player1 >> goal1 >> tmp >> goal2 >> player2; /* 0 is points 1 goal delta 2 is goal scored 3 is wins 4 team id 5 is games played 6 draw 7 lose 8 goal taken */ if (goal1 > goal2) { tournament[ranks[player1]][0] += (-1) * 3; tournament[ranks[player1]][4] += (-1) * 1; // wins tournament[ranks[player1]][1] += (-1) * (goal1 - goal2); tournament[ranks[player1]][2] += (-1) * goal1; tournament[ranks[player1]][5] += 1; tournament[ranks[player1]][8] += goal2; tournament[ranks[player2]][1] += (-1) * (goal2 - goal1); tournament[ranks[player2]][2] += (-1) * goal2; tournament[ranks[player2]][5] += 1; tournament[ranks[player2]][7] += 1; tournament[ranks[player2]][8] += goal1; // goal taken } else if (goal1 == goal2) { total_points -= 1; tournament[ranks[player1]][0] += (-1) * 1; tournament[ranks[player1]][2] += (-1) * goal1; tournament[ranks[player1]][5] += 1; tournament[ranks[player1]][6] += 1; tournament[ranks[player1]][8] += goal2; tournament[ranks[player2]][0] += (-1) * 1; tournament[ranks[player2]][2] += (-1) * goal2; tournament[ranks[player2]][5] += 1; tournament[ranks[player2]][6] += 1; tournament[ranks[player2]][8] += goal1; } else if (goal1 < goal2) { tournament[ranks[player2]][0] += (-1) * 3; tournament[ranks[player2]][4] += (-1) * 1; // wins tournament[ranks[player2]][1] += (-1) * (goal2 - goal1); tournament[ranks[player2]][2] += (-1) * goal2; tournament[ranks[player2]][5] += 1; tournament[ranks[player2]][8] += goal1; tournament[ranks[player1]][1] += (-1) * (goal1 - goal2); tournament[ranks[player1]][2] += (-1) * goal1; tournament[ranks[player1]][5] += 1; tournament[ranks[player1]][7] += 1; tournament[ranks[player1]][8] += goal2; // goal taken } } sort(tournament.begin(), tournament.end()); int rank; pair <pair <int, int>, int> past; for (int i = 0; i < n; i++) { if (i == 0) { past = make_pair(make_pair(tournament[i][0], tournament[i][1]), tournament[i][2]); rank = i + 1; } else { pair <pair <int, int>, int> curr = make_pair(make_pair(tournament[i][0], tournament[i][1]), tournament[i][2]); if (curr > past) { rank = i + 1; past = curr; } else { rank = -1; } } if (rank > 0) { cout.width(2); cout << right << rank << "."; } else { cout << " "; } cout.width(16); cout << right << rev_ranks[tournament[i][3]]; cout.width(4); cout << right << (-1) * tournament[i][0]; cout.width(4); cout << right << tournament[i][5]; cout.width(4); cout << right << (-1) * tournament[i][2]; cout.width(4); cout << right << tournament[i][8]; cout.width(4); cout << right << (-1) * tournament[i][1]; cout.width(7); if ((-1)*tournament[i][4] + tournament[i][6] + tournament[i][7] > 0) { cout << right << fixed << setprecision(2) << (double)((-100)*tournament[i][0]) / (double)((-3)*tournament[i][4] + 3*tournament[i][6] + 3*tournament[i][7]); } else { cout << right << "N/A"; } cout << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int arr[26] = {0}; int n; cin>>n; string s; cin>>s; for (int i = 0;i<s.length();i++) { if (s[i] >=97) s[i] -= 32; arr[s[i] - 65] = 1; } int flag = 0; for (int i=0;i<26;i++) { if (arr[i] == 0) { cout<<"NO"<<endl; flag = 1; break; } } if (flag == 0) cout<<"YES"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; while (t--) { int k; cin>>k; map<char,int> dic; char c; int v; for (int i = 0;i<k;i++) { cin>>c>>v; dic[c] = v; } int l; cin>>l; string s; int cost = 0; getchar(); for (int i = 0;i<l;i++) { getline(cin,s); for (int j = 0;j<s.length();j++) { if (dic.find(s[j])!= dic.end()) { cost += dic[s[j]]; } } } printf("%d.%02d$\n",cost/100,cost%100); } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int sum1 = 0; int sum2 = 0; int sum3 = 0; int t1,t2,t3; for (int i=0;i<n;i++) { cin>>t1>>t2>>t3; sum1+=t1; sum2+=t2; sum3+=t3; } if (sum1 == 0 && sum2 == 0 && sum3 == 0) cout<<"YES\n"; else cout<<"NO\n"; return 0; }<file_sep>#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <cstdlib> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> using namespace std; class CCipher { public: string decode (string cipherText, int shift); }; string CCipher::decode(string CipherText, int shift) { shift%=26; for (int i=0;i<CipherText.length();i++ ) { char t=(CipherText[i]-65-shift)%26; if (t<0) t=26+t; CipherText[i]=t+65; } return CipherText; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { int d1,d2; int h1,m1,s1; int h2,m2,s2; string Dia; char colon; #if defined (SUBLIME) std::ifstream ifile("stdin.input"); #endif ISTREAM>>Dia>>d1; ISTREAM>>h1>>colon>>m1>>colon>>s1; ISTREAM>>Dia>>d2; ISTREAM>>h2>>colon>>m2>>colon>>s2; int t1 = h1*3600 + m1*60 + s1; int t2 = h2*3600 + m2*60 + s2; int d = d2 - d1; int t = t2 - t1; if (t<0) { t+=24*3600; d--; } int h = t/3600; int m = (t%3600)/60; int s = (t%3600)%60; cout<<d<<" dia(s)"<<endl; cout<<h<<" hora(s)"<<endl; cout<<m<<" minuto(s)"<<endl; cout<<s<<" segundo(s)"<<endl; return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int max = 0; int so_far = 0; for (int i=0;i<n;i++) { int a,b; cin>>a>>b; so_far+=(b-a); if (so_far>max) max = so_far; } cout<<max<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { vector <string> cards(13); while (cin>>cards[0]) { for (int i = 1; i < 13; i++) { cin>>cards[i]; } map <char, vector<char> > hand; vector <char> colors = {'C', 'D', 'H', 'S'}; for (int i = 0; i < 13; i++) { hand[cards[i][1]].push_back(cards[i][0]); } map <char, bool> suits; for (auto i:colors) { suits[i] = false; } int hand_score = 0; int extra = 0; char win = 'O'; int max_suit_size = 0; for (auto ii:colors) { vector <char> i = hand[ii]; if (i.size() <= 1) { extra += 2; } else if (i.size() == 2) { extra += 1; } bool king = false; bool queen = false; bool jack = false; bool ace = false; int suit_score = 0; int suit_size = i.size(); for (auto j:i) { if (j == 'A') { ace = true; suits[ii] = true; } if (j == 'K') { king = true; suit_score += 3; if (suit_size == 1) { suit_score -= 1; } else { suits[ii] = true; } } else if (j == 'Q') { queen = true; suit_score += 2; if (suit_size <= 2) { suit_score -= 1; } else { suits[ii] = true; } } else if (j == 'J') { jack = true; suit_score += 1; if (suit_size <= 3) suit_score -= 1; } else if (j == 'A') { ace = true; suit_score += 4; } } hand_score += suit_score; if (suit_size >= max_suit_size) { win = ii; max_suit_size = suit_size; } } if (suits['D'] && suits['H'] && suits['S'] && suits['C'] && hand_score >= 16) { cout<<"BID NO-TRUMP"<<endl; } else if (hand_score + extra < 14) { cout<<"PASS"<<endl; } else if (hand_score + extra>= 14) { cout<<"BID "<<win<<endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; string clean (string s) { string res = ""; for (auto i:s) { if (i == 44 || i == 46 || i == 58 || i == 59 || i == 33 || i == 63 || i == 34 || i == 32 || i == 40 || i == 41 || i == 10 || i == 9) { continue; } else if (i <= 90 && i >= 65) { res += (char)(i + 32); } else { res += i; } } return res; } int main() { string s; while (cin >> s) { if (s == "****END_OF_INPUT****") { break; } map <string, int> inp; inp[clean(s)] += 1; int total_words = 1; while(cin >> s) { if (s == "****END_OF_TEXT****") { break; } inp[clean(s)] += 1; total_words += 1; } double e = 0; for (auto i:inp) { e += i.second*log10((double)total_words/(double)i.second); } e /= (double)total_words; double e_rel = (e*100)/log10(total_words); cout << total_words << " " << fixed << setprecision(1) << e << " " << (int)round(e_rel) << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { vector <int> Arr(6); for (int i=0;i<6;i++) { cin>>Arr[i]; } sort(Arr.begin(),Arr.end()); for (int i=0;i<3;i++) { if (Arr[i] == Arr[i+3]) { if (Arr[(i+4)%6] == Arr[(i+5)%6]) { cout<<"Elephant\n"; return 0; } else { cout<<"Bear\n"; return 0; } } } cout<<"Alien\n"; return 0; }<file_sep>#include<stdio.h> int main() { long int i,j; long int a,b,c; scanf ("%ld %ld %ld",&a,&b,&c); while ( !(a == 0 && b==0 && c==0 ) ) { if ( b-c==a-b ) { c+=c-b; printf("AP %ld\n",c); } else if ( c/b == b/a && c%b==0) { c*=c/b; printf("GP %ld\n",c); } else if ( b/c == a/b && b%c==0) { c/=b/c; printf("GP %ld\n",c); } scanf ("%ld %ld %ld",&a,&b,&c); } return 0; } <file_sep>#include<stdio.h> int main () { int n; scanf("%d",&n); while (n!=0) { int cnt=0; int i=1; int ptr=0; int t; int stack[1000]; while (cnt!=n) { scanf("%d",&t); if ( t==i ) { i++; while ( stack[ptr-1]==i ) { i++; ptr--; } } else { stack[ptr++]=t; } cnt++; } if ( i==n+1 ) { printf("yes\n"); } else printf("no\n"); scanf("%d",&n); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin >> t; int idx = 0; while(t--) { int n; cin >> n; string subject; int days; unordered_map <string, int> friend_homework; for (int i = 0; i < n; i++) { cin >> subject >> days; friend_homework[subject] = days; } int d; cin >> d; cin >> subject; cout << "Case " << ++idx << ": "; if (friend_homework.find(subject) == friend_homework.end() || friend_homework[subject] > d + 5) { cout << "Do your own homework!" << endl; } else if (friend_homework[subject] > d) { cout << "Late" << endl; } else { cout << "Yesss" << endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; vector <int> res; for (int i=0;i<s.length();i++) { if (s[i] == '1' || s[i]=='2' || s[i] == '3') res.push_back(s[i]-48); } sort(res.begin(),res.end()); cout<<res[0]; for (int i=1;i<res.size();i++) { cout<<"+"<<res[i]; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s[4]; for (int i=0;i<4;i++) { cin>>s[i]; } for (int i=0;i<3;i++) { for (int j=0;j<3;j++) { int black = 0; int blank = 0; if (s[i][j] == '#') black++; else blank++; if (s[i][j+1] == '#') black++; else blank++; if (s[i+1][j] == '#') black++; else blank++; if (s[i+1][j+1] == '#') black++; else blank++; if (black >= 3 || blank >= 3) { cout<<"YES"<<endl; return 0; } } } cout<<"NO"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; cin>>n; for (int i = 0;i<n;i++) { vector <string> tictac(3); cin>>tictac[0]; cin>>tictac[1]; cin>>tictac[2]; int xcnt = 0; int ocnt = 0; bool owin = false; bool xwin = false; for (int j = 0;j<3;j++) { for (int k = 0;k<3;k++) { if (tictac[j][k] == 'X') xcnt++; else if (tictac[j][k] == 'O') ocnt++; } } for (int j = 0;j < 3;j++) { char temp1 = 'X'; char temp2 = 'O'; bool flag = true; for (int k = 0;k < 3; k++) { if (tictac[j][k] != temp1) flag = false; } if (flag == true) xwin = true; flag = true; for (int k = 0;k < 3; k++) { if (tictac[j][k] != temp2) flag = false; } if (flag == true) owin = true; flag = true; for (int k = 0;k < 3; k++) { if (tictac[k][j] != temp1) flag = false; } if (flag == true) xwin = true; flag = true; for (int k = 0;k < 3; k++) { if (tictac[k][j] != temp2) flag = false; } if (flag == true) owin = true; } if (tictac[0][0] == 'X' && tictac[1][1] == 'X' && tictac[2][2] == 'X') xwin = true; if (tictac[0][0] == 'O' && tictac[1][1] == 'O' && tictac[2][2] == 'O') owin = true; if (tictac[2][0] == 'X' && tictac[1][1] == 'X' && tictac[0][2] == 'X') xwin = true; if (tictac[2][0] == 'O' && tictac[1][1] == 'O' && tictac[0][2] == 'O') owin = true; if (xwin == true && owin== true) cout<<"no"<<endl; else if (xwin == true && xcnt != ocnt + 1) cout<<"no"<<endl; else if (owin == true && xcnt != ocnt) cout<<"no"<<endl; else if (xcnt == ocnt || xcnt == ocnt+1) cout<<"yes"<<endl; else cout<<"no"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m,k; cin>>n>>m>>k; for (int i=0;i<n;i++) { int temp; cin>>temp; if (temp==1) { m--; } else if (temp == 2) { if (k>0) { k--; } else m--; } } int res=0; if (0-m>0) res+=abs(m); if (0-k>0) res+=abs(k); cout<<res<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; string clean(string s) { string res = ""; for (auto i:s) { if (i <= 122 && i >= 97) { res += i; } else { res += " "; } } return res; } stringstream ss; int main() { std::ios::sync_with_stdio(false); int t; cin >> t; string inp; getline(cin, inp); int idx = 0; while (t--) { getline(cin, inp); vector <string> document; string word; unordered_map <string, int> rolling_window; while(inp != "END") { inp = clean(inp); ss.str(""); ss.clear(); ss.str(inp); while (ss >> word) { document.push_back(word); } getline(cin, inp); } set <string> unique_words(document.begin(), document.end()); int unique_words_size = (int)unique_words.size(); int document_length = (int)document.size(); int start = 0; int ending = 0; int min_length = INT_MAX; pair <int, int> result; while(start != document_length) { while(rolling_window.size() != unique_words_size) { if (ending == document_length) { break; } rolling_window[document[ending]] += 1; ending += 1; } if (rolling_window.size() == unique_words_size && ending - start < min_length) { min_length = ending - start; result = make_pair(start+1, ending); } rolling_window[document[start]] -= 1; if (rolling_window[document[start]] == 0) { rolling_window.erase(document[start]); } start += 1; } cout << "Document " << ++idx <<": " << result.first << " " << result.second << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int a,b; for (int i = 0; i < n; i++) { cin>>a>>b; if (a>b) swap(a,b); int sum = 0; for (int i=a+1;i<b;i++) { if (abs(i)%2L==1) sum+=i; } cout<<sum<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; vector <int> month_to_i {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; vector <string> weekday {"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}; for (int i = 1;i <= 12;i++) { month_to_i[i] = month_to_i[i] + month_to_i[i-1]; } while (t--) { int m, d; cin >> m >> d; int days = (month_to_i[m-1] + d - 1)%7; cout << weekday[days] << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; char matrix[51][51]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin>>matrix[i][j]; } } int count = 0; for (int i = 0; i < n-1; i++) { for (int j = 0; j < m-1; j++) { vector<char> vrr(4); vrr[0] = matrix[i][j]; vrr[1] = matrix[i][j+1]; vrr[2] = matrix[i+1][j+1]; vrr[3] = matrix[i+1][j]; sort(vrr.begin(), vrr.end()); string temp = ""; temp +=vrr[0]; temp +=vrr[1]; temp +=vrr[2]; temp +=vrr[3]; if (temp == "acef") count++; } } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif long long int a; cin>>a; cout<<a%2L<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { double r,x,y,x1,y1; cin>>r>>x>>y>>x1>>y1; double dist = sqrt((x1 - x)*(x1-x) + (y1 - y)*(y1 - y)); cout<<(int)ceil(dist/(2*r))<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int arr[] = {1,2,3,4,5}; long long int mat[5][5]; for (int i=0;i<5;i++) { for (int j=0;j<5;j++) { cin>>mat[i][j]; } } int maxi = -1; long long int happiness; do { happiness = 0; for (int i = 0; i < 5; i++) { for (int j = i;j+1<5;j+=2) { happiness += mat[arr[j]-1][arr[j+1]-1]; happiness += mat[arr[j+1]-1][arr[j]-1]; } } if (happiness>maxi) { maxi = happiness; } }while(next_permutation(arr,arr+5)); cout<<maxi<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; int in = 0; int out = 0; int temp; for (int i=0;i<n;i++) { ISTREAM>>temp; if (temp>= 10 && temp<=20) { in++; } else out++; } cout<<in<<" in"<<endl; cout<<out<<" out"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main (){ int t; cin>>t; int it = 0; while (t--) { cout<<"Case #"<<++it<<": "; string t1; string t2; cin>>t1>>t2; char c; int d1, m1, y1; int d2, m2, y2; stringstream ss(t1); ss >> d1 >> c >> m1 >> c >> y1; stringstream ss1(t2); ss1 >> d2 >> c >> m2 >> c >> y2; int y = y1 - y2; int m = m1 - m2; int d = d1 - d2; int delta = y * 360 + m * 30 + d; if (delta < 0) cout<<"Invalid birth date"<<endl; else if (delta >= 131*360) cout<<"Check birth date"<<endl; else cout<<delta/360<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin >>n; string s; for (int i=0;i<n;i++) { cin>>s; int flag = 0; for (int j=0;j<s.length();j++) { if (flag == 0 && s[j] == 'R') flag=1; else if (flag == 1 && s[j]<= '9' && s[j]>='0') flag=2; else if (flag == 2 && s[j]== 'C') { flag=3; break; } } if (flag == 3) { int j=1; int t = 0; while (s[j]<= '9' && s[j]>='0') { t = t*10 + s[j] - 48; j++; } if (s[j] == 'C') { j++; } int t1 = 0; while (s[j]<= '9' && s[j]>='0') { t1 = t1*10 + s[j] - 48; j++; } string column = ""; while(t1>0) { t1-=1; int temp = t1%26; column+=(char)(temp+65); t1 = t1/26; } for (int j=column.length() - 1 ; j >= 0 ;j--) { cout<<column[j]; } cout<<t<<endl; } else { string column = ""; int j = 0; int col = 0; while (s[j] >= 65 && s[j]<=90) { column+= s[j]; col = col*26 + s[j] - 64; j++; } int t = 0; while (s[j]<= '9' && s[j]>='0') { t = t*10 + s[j] - 48; j++; } cout<<"R"<<t<<"C"<<col<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n,c; vector <int > primes(1007,0); for (int i = 2; i < 1005;i++) { if (primes[i] == 1) continue; for (int j = i*2; j < 1005;j += i) { primes[j] = 1; } } while(scanf("%d %d",&n,&c)!= EOF) { vector <int> output; for (int i = 1; i <= n; i++) { if (primes[i] == 0) { output.push_back(i); } } int pivot = output.size()/2; int a = max(pivot - c + (int)output.size()%2,0); int b = min(pivot + c,(int)output.size()); cout<<n<<" "<<c<<": "; for (int i = a;i<b;i++) { cout<<output[i]; if (i < b-1) cout<<" "; } cout<<endl<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif string s; while (ISTREAM>>s) { int row = 0,col = 0; char board[8][8]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { board[i][j] = '0'; } } for (unsigned int i = 0; i < s.length(); i++) { if (s[i] == '/') { row++; col = 0; } else if (s[i] >= '1' && s[i] <= '8') { col += s[i] - 48; } else { board[row][col] = s[i]; col++; } } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (board[i][j] == 'p') { if (i<7 && j<7 && board[i+1][j+1] == '0') board[i+1][j+1] = '1'; if (i<7 && j>0 && board[i+1][j-1] == '0') board[i+1][j-1] = '1'; } if (board[i][j] == 'P') { if (i>0 && j<7 && board[i-1][j+1] == '0') board[i-1][j+1] = '1'; if (i>0 && j>0 && board[i-1][j-1] == '0') board[i-1][j-1] = '1'; } if (board[i][j] == 'r' || board[i][j] == 'R' || board[i][j] == 'Q' || board[i][j] == 'q') { for (int k = j+1; k < 8; k++) { if (board[i][k] != '0' && board[i][k] != '1') break; board[i][k] = '1'; } for (int k = j-1; k >= 0 ; k--) { if (board[i][k] != '0' && board[i][k] != '1') break; board[i][k] = '1'; } for (int k = i+1; k < 8; k++) { if (board[k][j] != '0' && board[k][j] != '1') break; board[k][j] = '1'; } for (int k = i-1; k >= 0 ; k--) { if (board[k][j] != '0' && board[k][j] != '1') break; board[k][j] = '1'; } } if (board[i][j] == 'n' || board[i][j] == 'N') { if (i-2>=0 && j-1>=0 && board[i-2][j-1] == '0') board[i-2][j-1] = '1'; if (i-2>=0 && j+1<8 && board[i-2][j+1] == '0') board[i-2][j+1] = '1'; if (i-1>=0 && j-2>=0 && board[i-1][j-2] == '0') board[i-1][j-2] = '1'; if (i+1<8 && j-2>=0 && board[i+1][j-2] == '0') board[i+1][j-2] = '1'; if (i+2<8 && j-1>=0 && board[i+2][j-1] == '0') board[i+2][j-1] = '1'; if (i+2<8 && j+1<8 && board[i+2][j+1] == '0') board[i+2][j+1] = '1'; if (i+1<8 && j+2<8 && board[i+1][j+2] == '0') board[i+1][j+2] = '1'; if (i-1>=0 && j+2<8 && board[i-1][j+2] == '0') board[i-1][j+2] = '1'; } if (board[i][j] == 'q' || board[i][j] == 'Q' || board[i][j] == 'b' || board[i][j] == 'B') { for (int k = i+1, l = j+1; k<8 && l<8; k++,l++) { if (board[k][l] != '0' && board[k][l] != '1') break; board[k][l] = '1'; } for (int k = i-1, l = j-1; k>=0 && l>=0; k--,l--) { if (board[k][l] != '0' && board[k][l] != '1') break; board[k][l] = '1'; } for (int k = i+1, l = j-1; k<8 && l>=0; k++,l--) { if (board[k][l] != '0' && board[k][l] != '1') break; board[k][l] = '1'; } for (int k = i-1, l = j+1; k>=0 && l<8; k--,l++) { if (board[k][l] != '0' && board[k][l] != '1') break; board[k][l] = '1'; } } if (board[i][j] == 'k' || board[i][j] == 'K') { if (i<7 && j<7 && board[i+1][j+1] == '0') board[i+1][j+1] = '1'; if (i<7 && j>0 && board[i+1][j-1] == '0') board[i+1][j-1] = '1'; if (i>0 && j<7 && board[i-1][j+1] == '0') board[i-1][j+1] = '1'; if (i>0 && j>0 && board[i-1][j-1] == '0') board[i-1][j-1] = '1'; if (i<7 && board[i+1][j] == '0') board[i+1][j] = '1'; if (i-1>=0 && board[i-1][j] == '0') board[i-1][j] = '1'; if (j<7 && board[i][j+1] == '0') board[i][j+1] = '1'; if (j-1>=0 && board[i][j-1] == '0') board[i][j-1] = '1'; } } } int cnt = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (board[i][j] == '0') { cnt++; } } } cout<<cnt<<endl; } return 0; }<file_sep>#include<stdio.h> int main() { int n,i; scanf("%d",&n); for (i=0;i<n;i++) { int x,y; scanf("%d %d",&x,&y); if (x<2 && y!=x) { printf("No Number\n"); } else if (x%2==0) { if (y==x) printf("%d\n",(2*x)); else if (y==(x-2)) printf("%d\n",(2*x)-2); else printf("No Number\n"); } else if (x%2==1) { if (y==x) printf("%d\n",(2*x)-1); else if (y==(x-2)) printf("%d\n",(2*x)-3); else printf("No Number\n"); } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; string s[12] = {"January","February","March","April","May","June","July","August","September","October","November","December"}; cout<<s[n-1]<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; string s; getchar(); for (int i = 0; i < n; i++) { getline(cin,s); int male = 0; int female = 0; int l = s.length(); for (int i = 0; i < l; i++) { if (s[i] == 'M') male++; else if (s[i] == 'F') female++; } if (male == female && (male + female) > 2 )cout<<"LOOP"<<endl; else cout<<"NO LOOP"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int a,b,c,d; while (1) { cin>>a>>b>>c>>d; if (a == 0 && b == 0 && c == 0 && d == 0) { break; } if (a == c && b == d) cout<<0<<endl; else if (abs (a-c) == abs(b - d)) cout<<1<<endl; else if (a == c || b == d) cout<<1<<endl; else cout<<2<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { float temp; int pos = 0; float sum = 0; for (int i=0;i<6;i++) { cin>>temp; if (temp>0) { pos++; sum += temp; } } cout<<fixed<<setprecision(1); cout<<pos<<" valores positivos"<<endl; cout<<sum/pos<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; string s; cin>>s; vector <int> keys(26,0); int counter = 0; for (int i = 0;i<2*(n-1);i+=2) { keys[s[i]-97]++; if (keys[s[i+1]-65]>0) keys[s[i+1]-65]--; else counter++; } cout<<counter<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int p=0; int c; int crime = 0; cin>>c; if (c>0 ) p+=min(c,10); else crime += c; for (int i=1;i<n;i++) { cin>>c; if (c>0) p+=min(c,10); else { if (p+c>0) p +=c; else { crime+= c+p; p= 0; } } } cout<<(-1)*crime<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int n = s.length(); int N = pow(2,n); while (n>0) { if (s[s.length()-n]=='7') N += pow(2,n-1); n--; } cout<<N-1<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool did_win(vector <vector <int> > grid) { int check_v, check_h; for (int i = 0;i<5;i++) { check_h = 0; check_v = 0; for (int j = 0;j<5;j++) { if (grid[i][j] == 1) check_h++; if (grid[j][i] == 1) check_v++; } if (check_h == 5 || check_v == 5) { return true; } } check_h = 0; check_v = 0; for (int i = 0;i < 5;i++) { if (grid[i][i] == 1) check_h++; if (grid[i][5 - i - 1] == 1) check_v++; } if (check_h == 5 || check_v == 5) return true; return false; } int main () { int t; cin>>t; while (t--) { vector < vector<int> > bingo(5,vector<int> (5,0)); vector < vector<int> > check(5,vector<int> (5,0)); for (int i = 0;i<5;i++) { for (int j = 0;j<5;j++) { if (i == 2 && j == 2) { continue; } cin>>bingo[i][j]; } } check[2][2] = 1; vector <int> moves(75); for (int i = 0;i<75;i++) { cin>>moves[i]; } bool win = false; for (int i = 0;i<moves.size();i++) { int ele = moves[i]; for (int j = 0; j<5;j++) { for (int k = 0;k<5;k++) { if (bingo[j][k] == ele) { check[j][k] = 1; } } } if (did_win(check)) { cout<<"BINGO after "<<i+1<<" numbers announced"<<endl; break; } } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int N; cin>>N; for (int i=0;i<N;i++) { long long int n,n1; char op; cin>>n>>op; while (op != '=') { cin>>n1; if (op=='+') n+=n1; else if (op =='*') n*=n1; else if (op =='-') n-=n1; else if (op =='/') n/=n1; cin>>op; } cout<<n<< "\n"; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int main () { std::ios::sync_with_stdio(false); string a, b; string inp; getline(cin, inp); unordered_map <string, string> dic; while(inp != "") { ss.str(""); ss.clear(); ss.str(inp); ss >> a >> b; dic[b] = a; getline(cin, inp); } while (getline(cin, inp)) { if (dic.find(inp) != dic.end()) { cout << dic[inp] << endl; } else { cout << "eh" << endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int digicnt (int n) { int cnt = 0; while (n!= 0) { n/=10; cnt++; } return cnt; } int main() { int n; cin>>n; while(n) { for (int i = 0;i<n ; i++ ) { for (int j = 0;j<n-1;j++) { for (int k = 0;k<3 - digicnt(min(min(i,j)+1,min(n-i,n-j)));k++ ) cout<<" "; cout<<min(min(i,j)+1,min(n-i,n-j))<<" "; } cout<<" 1"<<endl; } cout<<endl; cin>>n; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; vector <vector <int> > factor(int n) { vector <vector<int>> res; vector <int> temp; for (int i = 2; i * i <= n; i++) { temp.clear(); if (n % i == 0) { temp.push_back(i); temp.push_back(n / i); res.push_back(temp); } } return res; } int main() { cin.sync_with_stdio(0);cin.tie(0); int n; while (1) { cin >> n; set <vector <int> > result; vector <vector <int> > temp; if (n == 0) { break; } temp = factor(n); for (auto i: temp) { result.insert(i); } bool flag = true; while(flag) { vector <vector <int> > new_temp; flag = false; for (int i = 0; i < (int)temp.size(); i++) { vector <int> tt1 = temp[i]; for (auto jj:factor(tt1.back())) { flag = true; vector <int> tt2 = temp[i]; tt2.pop_back(); tt2.push_back(jj[0]); tt2.push_back(jj[1]); new_temp.push_back(tt2); sort(tt2.begin(), tt2.end()); result.insert(tt2); } } temp = new_temp; } cout << (int)result.size() << endl; for (auto i:result) { for (int j = 0; j < (int)i.size(); j++) { cout << i[j]; if (j < (int)i.size() - 1) { cout << " "; } } cout << endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n+1); for (int i=1;i<=n;i++) { cin>>Arr[i]; } int q; cin>>q; for (int i=0;i<q;i++) { int a,b; cin>>a>>b; if (a>1) { Arr[a-1] += b-1; } if (a<n) { Arr[a+1] += Arr[a]-b; } Arr[a] = 0; } for (int i=1;i<=n;i++) { cout<<Arr[i]<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int R; cin>>R; printf("VOLUME = %.3f\n",(4/3.0)*3.14159*R*R*R); return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; cin>>n; int sheets; while (1) { if (n == 0) { break; } cout<<"Printing order for "<<n<<" pages:"<<endl; sheets = n/4 + (n%4==0?0:1); vector <vector <int> > book(2*sheets,vector<int> (2,0)); for (int i = 0;i<2*sheets;i++) { if (i+1 > n) break; book[i][(i+1)&1] = i+1; } int temp = 2*sheets+1; for (int i = 2*sheets-1;i>=0;i--) { if (temp >n) break; book[i][i&1] = temp++; } for (int i = 0;i<book.size();i++) { if (book[i][0] + book[i][1] == 0) continue; cout<<"Sheet "<<i/2 + 1; if (i%2 == 0) cout<<", front: "; else cout<<", back : "; if (book[i][0] == 0) cout<<"Blank, "; else cout<<book[i][0]<<", "; if (book[i][1] == 0) cout<<"Blank\n"; else cout<<book[i][1]<<endl; } cin>>n; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int b,s; while (1) { cin>>b>>s; if (b + s == 0) { break; } vector <int> hashl(b+2,0); vector <int> hashr(b+2,0); for (int i = 1;i<=b;i++) { hashl[i] = i-1; hashr[i] = i+1; } int t1,t2; for (int i = 0;i<s;i++) { cin>>t1>>t2; int left = hashl[t1]; int right = hashr[t2]; hashr[left] = right; hashl[right] = left; if (left < 1) { cout<<"*"<<" "; } else { cout<<left<<" "; } if (right <= b) { cout<<right<<endl; } else { cout<<"*"<<endl; } } cout<<"-"<<endl; } return 0; } <file_sep>#!/usr/bin global a def c(n): if n==1: return 1 if a[n]!=1: return a[n] min1=999999 for i in range(1,n/2+1): if (c(i)+c(n-1))<min1: min1=c(i)+c(n-i) a[n]=min1 return a[n] a=[1]*500 print c(4) <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t,n,s; cin>>t; int a,b,c,d; while(t--) { cin>>n; cin>>s; while (n--) { cin>>a>>b>>c>>d; if (c > s || d > s) cout<<"no move"<<endl; else if (a ==c && b == d) cout<<"0"<<endl; else if ((a + b)%2 != (c+d)%2) cout<<"no move"<<endl; else if (abs(c-a) == abs(d-b)) cout<<"1"<<endl; else cout<<"2"<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int t; ISTREAM>>t; for (int i = 0; i < t; i++) { int n; ISTREAM>>n; vector<int> Arr(n); for (int j = 0; j < n-1; j++) { ISTREAM>>Arr[j]; } int start = 0; int beststart = start; int endi = 0; int length = 0; int bestlength = 0; int bestend = endi; long long int sum = 0; long long int ans = 0; for (int j = 0; j < n-1; j++) { sum +=Arr[j]; if (sum <0) { start = j+1; endi = j+2; sum = 0; length = 0; } else { length++; } if (sum > ans ||(sum >= ans && length > bestlength) ) { ans = sum; beststart = start; endi = j+1; bestend = endi; bestlength = length; } } if (ans > 0) { cout<<"The nicest part of route "<<i+1<<" is between stops "<<beststart+1<<" and "<<bestend+1<<endl; } else { cout<<"Route "<<i+1<<" has no nice parts"<<endl; } //cout<<start<<" "<<end<<endl; } return 0; }<file_sep>#include<stdio.h> #include<string.h> int main() { long long int a[50]; int i; a[0]=1; a[1]=2; for (i=2;i<50;i++) { a[i]=a[i-1]+a[i-2]; } char n[5001]; scanf("%s",&n); while (n[0]!='0') { int t1=0; int p=strlen(n); int cnt=0; int flag1=0; long long int sum=1; while (cnt!=p) { if( n[cnt]=='1' || n[cnt]=='2' ) { t1++; flag1=1; } else if (flag1==1 && n[cnt]=='0' && p==2 ){ sum*=a[t1-1]; t1=0; flag1=0; } else if (flag1==1 && n[cnt-2]>='3' && n[cnt-2]<='9' && n[cnt]=='0'){ sum*=a[t1-1]; t1=0; flag1=0; } else if (flag1==1 && n[cnt-1]=='1' && n[cnt]<='9' && n[cnt]>='3'){ sum*=a[t1]; t1=0; flag1=0; } else if (flag1==1 && n[cnt-1]=='1' && n[cnt]=='0'){ if(t1>1){ sum*=a[t1-2];} else sum*=a[t1-1]; t1=0; flag1=0; } else if (flag1==1 && n[cnt-1]=='2' && n[cnt]<='6' && n[cnt]>='3'){ sum*=a[t1]; t1=0; flag1=0; } else if (flag1==1 && n[cnt-1]=='2' && n[cnt]=='0'){ if(t1>1){ sum*=a[t1-2];} else sum*=a[t1-1]; t1=0; flag1=0; } else if (flag1==1){ sum*=a[t1-1]; t1=0; } else { t1=0; } cnt++; } if (t1!=0)sum*=a[t1-1]; printf("%lld\n",sum); scanf("%s",&n); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; long long int my_pow(long long int base, long long int exp) { long long int res = 1; for (int i = 0; i < exp; i++) { res *= base; if (res > 5000000) { break; } } return res; } int main() { long long int t; long long int n; cin >> t; while(t--) { vector <long long int> arr; int sz = 0; while (cin >> n) { if (n == 0) { break; } arr.push_back(n); sz += 1; } sort(arr.begin(), arr.end()); long long int sum = 0; for (int i = sz - 1; i >= 0; i--) { long long int tmp = my_pow(arr[i], sz - i); if (tmp > 5000000) { sum = 5000001; break; } sum += 2 * tmp; if (sum > 5000000) { break; } } if (sum > 5000000) { cout << "Too expensive" << endl; } else { cout << sum << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; vector <int> numbers; map <int, int> freq; while (cin >> n) { if (freq.find(n) == freq.end()) { freq[n] = 1; numbers.push_back(n); } else { freq[n] += 1; } } for (auto i:numbers) { cout << i << " " << freq[i] << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int n,x; cin>>n>>x; vector <long long int> C(n); for (int i=0;i<n;i++) { cin>>C[i]; } sort (C.begin(), C.end()); long long int sum = 0; for (int i=0;i<n;i++) { sum += C[i]*x; if (x>1) { x--; } } cout<<sum; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } int p1 = 0; int p2 = Arr.size() - 1; int sareja = 0; int dima = 0; for (int i = 0;i<n;i++ ) { if (Arr[p1] > Arr[p2]) { if (i%2 == 0) { sareja+=Arr[p1++]; } else { dima+=Arr[p1++]; } } else { if (i%2 == 0) { sareja+=Arr[p2--]; } else { dima+=Arr[p2--]; } } } cout<<sareja<<" "<<dima<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; long long int integer(string s) { long long int res = 0; for (int i = 0; i < 32; i++) { res *= 2; if (s[i] == '1') { res += 1; } } return res; } string bin(long long int n) { string res = ""; for (int i = 0;i < 32; i++) { res += (char)((n % 2) + 48); n /= 2; } reverse(res.begin(), res.end()); return res; } int main() { long long int n; while(cin >> n) { long long int n1 = n; if (n < 0) { n += 4294967296; } string s = bin(n); string new_s; for (int i = 24; i < 32; i++) { new_s += s[i]; } for (int i = 16; i < 24; i++) { new_s += s[i]; } for (int i = 8; i < 16; i++) { new_s += s[i]; } for (int i = 0; i < 8; i++) { new_s += s[i]; } long long int res = integer(new_s); cout << n1 << " converts to "; if (new_s[0] == '1') { cout << res - 4294967296 << endl; } else { cout << res << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; class UFDS { private: int size; vector <int> parent; vector <int> rank; vector <int> counts; public: UFDS(int n) { size = n; parent.assign(n, 0); counts.assign(n, 1); rank.assign(n, 0); for (int i = 0; i < n; i++) { parent[i] = i; } } int findset(int a) { return (a == parent[a])? a: parent[a] =(findset(parent[a])); } bool is_same_set(int a, int b) { return findset(a) == findset(b); } void union_set(int a, int b) { if (!is_same_set(a, b)) { int x = findset(a); int y = findset(b); if (rank[x] > rank[y]) { parent[y] = x; counts[x] += counts[y]; } else { parent[x] = y; counts[y] += counts[x]; if (rank[x] == rank[y]) { rank[y]++; } } } } int find_maxi() { int maxi = -1; for (int i = 0; i < size; i++) { if (i == parent[i]) { maxi = max(maxi, counts[i]); } } return maxi; } }; int main() { int t; cin >> t; while(t--) { int n, m; int a, b; cin >> n >> m; UFDS case1(n); for (int i = 0; i < m; i++) { cin >> a >> b; case1.union_set(a - 1, b - 1); } cout << case1.find_maxi() << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n,m; cin>>n>>m; while (n + m != 0) { set<int> alpha; int ele; int cnt= 0; for (int i = 0;i<n;i++) { cin>>ele; alpha.insert(ele); } for (int i = 0;i<m;i++) { cin>>ele; if (alpha.find(ele)!=alpha.end()) { cnt++; } } cout<<cnt<<endl; cin>>n>>m; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,c; cin>>n>>c; vector <int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } int maxdiff = 0; for (int i=0;i<n-1;i++) { if (Arr[i] - Arr[i+1] - c>maxdiff) { maxdiff = Arr[i] - Arr[i+1] - c; } } cout<<maxdiff<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int odd_iter = 0; int odd = 0, even= 0,temp; int even_iter = 0; for (int i=0;i<n;i++) { cin>>temp; if (temp%2 == 0) { even_iter = i+1; even++; } else { odd_iter = i+1; odd++; } } if (odd>1) { cout<<even_iter<<endl; } else { cout<<odd_iter<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; int a,b,c; for (int i = 0; i < n; i++) { ISTREAM>>a>>b>>c; int temp = (c*(2* max(a,b) - min(a,b)))/(a+b); if (a < b) { cout<<max(0,c - temp)<<endl; } else { cout<<temp<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; string t; cin>>s>>t; int h1 = (s[0]-48)*10 + (s[1]- 48); int m1 = (s[3]-48)*10 + (s[4]- 48); int h2 = (t[0]-48)*10 + (t[1]- 48); int m2 = (t[3]-48)*10 + (t[4]- 48); int h = h1 - h2; int m = m1 - m2; if (m<0) { m = 60 + m; h--; } if (h<0) { h = 24+h; } if (h<10) cout<<"0"; cout<<h<<":"; if (m<10) cout<<"0"; cout<<m<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { vector <int> a(3); vector <int> b(3); for (int i = 0;i<3;i++) { cin>>a[i]; b[i] = a[i]; } sort(a.begin(), a.end()); for (int i=0;i<3;i++) { cout<<a[i]<<endl; } cout<<endl; for (int i=0;i<3;i++) { cout<<b[i]<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int idx = 0; while(n--) { double temp; double sum = 0.0; double fraction; int sum_int; for (int i = 0; i<12;i++) { cin >> temp; sum += temp; } sum /= 12; sum_int = (int)sum; fraction = sum - sum_int; cout<<++idx<< " $"; vector <int> vals; while(sum_int != 0) { vals.push_back(sum_int%1000); sum_int /= 1000; } if (vals.size() == 1) { cout<<fixed<<setprecision(2)<<sum<<endl; continue; } reverse(vals.begin(), vals.end()); cout<<vals[0]; for (int i = 1;i < vals.size()-1;i++) { cout<<","; if (vals[i] < 100) cout<<"0"; if (vals[i] < 10) cout<<"0"; cout<<vals[i]; } cout << ","; if (vals.back() < 100) cout << "0"; if (vals.back() < 10) cout << "0"; cout<<fixed<<setprecision(2)<<vals.back() + fraction<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int digicnt (int n) { int cnt = 0; while (n!= 0) { n/=10; cnt++; } return cnt; } int main() { int n; cin>>n; while(n) { for (int i = 0;i<n;i++ ) { for (int j = i+ 1;j > 1; j-- ) { for (int k = 0;k<3-digicnt(j);k++) cout<<" "; cout<<j<<" "; } for (int j = 1 ;j < n - i; j++ ) { for (int k = 0;k<3-digicnt(j);k++) cout<<" "; cout<<j<<" "; } for (int k = 0;k<3-digicnt(n - i);k++) cout<<" "; cout<<n-i<<endl; } cout<<endl; cin>>n; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main(){ int a,b; cin>>a>>b; int t = 7 - max(a,b); cout<<t/__gcd(t,6)<<"/"<<6/__gcd(t,6)<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { vector<float> Arr; float temp; int flag = 1; while (flag == 1) { while (Arr.size()<2) { cin >> temp; if (temp >= 0.0 && temp <= 10.0) { Arr.push_back(temp); } else { cout<<"nota invalida"<<endl; } } cout<<fixed<<setprecision(2); cout<<"media = "<<(Arr[0] + Arr[1])/2.0<<endl; Arr.clear(); cout<<"novo calculo (1-sim 2-nao)"<<endl; cin >> flag; while(flag!=1 && flag!= 2) { cout<<"novo calculo (1-sim 2-nao)"<<endl; cin >> flag; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; bool iscapital(string s) { if (isupper(s[0])) { return true; } else { return false; } } bool issmall(string s) { if (islower(s[0])) { return true; } else { return false; } } int main() { string inp; while(getline(cin, inp)) { if (inp == "0") { break; } vector <string> projects; map <string, set<string> > records; string current_project = inp; projects.push_back(current_project); map <string, string> reverse_lookup; set <pair<int, string> > result; while(getline(cin, inp)) { if (inp == "1") { break; } if (iscapital(inp)) { current_project = inp; projects.push_back(current_project); } else if (issmall(inp)) { if (records[current_project].find(inp) != records[current_project].end()) { continue; } if (reverse_lookup.find(inp) == reverse_lookup.end()) { records[current_project].insert(inp); reverse_lookup[inp] = current_project; } else { records[reverse_lookup[inp]].erase(inp); } } } for (auto i:projects) { result.insert(make_pair(-1*(int)records[i].size(), i)); } for (auto i:result) { cout << i.second << " " << -1*i.first << endl; } } return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int temp; int count = 0; for (int i=0;i<n;i++) { int cnt = 0; for (int j = 0; j<3 ; j++) { cin>>temp; if (temp ==1) cnt++; } if (cnt>1) count++; } cout<<count<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector < pair <int,int> > Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i].first; Arr[i].second = i+1; } sort(Arr.begin(),Arr.end()); vector <int> swapper; for (int i = 0;i<n-1;i++) { if (Arr[i].first == Arr[i+1].first) { swapper.push_back(i); } } if ((int)swapper.size()<2) { cout<<"NO"<<endl; return 0; } cout<<"YES"<<endl; for (int i=0;i<n;i++) { cout<<Arr[i].second<<" "; } cout<<endl; for (int i=0;i<n;) { if (i == swapper[0]) { cout<<Arr[i+1].second<<" "<<Arr[i].second<<" "; i+=2; } else { cout<<Arr[i].second<<" "; i+=1; } } cout<<endl; for (int i=0;i<n;) { if (i == swapper[1]) { cout<<Arr[i+1].second<<" "<<Arr[i].second<<" "; i+=2; } else { cout<<Arr[i].second<<" "; i+=1; } } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> negative; vector <int> positive; vector <int> zero; int temp; for (int i=0;i<n;i++) { cin>>temp; if (temp<0) { negative.push_back(temp); } else if (temp == 0) { zero.push_back(temp); } else { positive.push_back(temp); } } if (positive.size() == 0) { int temp = negative[negative.size() - 1]; positive.push_back(temp); negative.pop_back(); temp = negative[negative.size() - 1]; positive.push_back(temp); negative.pop_back(); } if (negative.size()%2 == 0) { int temp = negative[negative.size()-1]; negative.pop_back(); zero.push_back(temp); } cout<<negative.size()<<" "; for (int i=0;i<negative.size();i++) { cout<<negative[i]<<" "; } cout<<endl; cout<<positive.size()<<" "; for (int i=0;i<positive.size();i++) { cout<<positive[i]<<" "; } cout<<endl; cout<<zero.size()<<" "; for (int i=0;i<zero.size();i++) { cout<<zero[i]<<" "; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int N; scanf("%d",&N); for (int j=0;j<N;j++) { long long int x,y,z; long long int a,n,d; scanf("%lld %lld %lld",&x,&y,&z); n= 2*z/(x+y); d=(y-x)/(n-5); a=x-2*d; printf("%lld\n",n); for (int i=0;i<n;i++) { printf("%lld",a); a+=d; i==n-1?printf("\n"):printf(" "); } } return 0; } <file_sep>#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <cstdlib> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> using namespace std; class RectangularGrid { public: long long countRectangles(int width, int height); long long nc2(long long n); }; long long RectangularGrid::countRectangles(int width, int height) { long long int rec=nc2(width+1)*nc2(height+1); if (height<width ){ height= height + width; width=height-width; height = height-width; } long long int sq= (width*(width+1)*(3*height-width + 1))/6; return rec-sq; } long long RectangularGrid::nc2(long long n) { return (n*(n-1))/2; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,t; cin>>n>>t; vector<int> arr(n); for (int i = 0; i < n; i++) { cin>>arr[i]; } int i1 = 0; int i2 = 0; int sum = 0; int max = -1; while (i1 < n) { while (i2 < n && sum + arr[i2] <= t) { sum += arr[i2]; i2++; } if (i2 - i1 > max) max = i2 - i1; sum-=arr[i1]; i1++; } cout<<max<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int h = n/3600; int m = (n%3600)/60; int s = (n%3600)%60; cout<<h<<":"<<m<<":"<<s<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int sum = 0; vector <int> A(n); for (int i=0;i<n;i++) { cin>>A[i]; sum += A[i]; } sort(A.begin(),A.end()); int cnt = 0; int s1 = 0; for (int i=A.size()-1;i>=0;i--) { s1+= A[i]; cnt++; if (s1>sum/2) break; } cout<<cnt<<endl; return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; int main() { int flag0=0,flag1=0; string s; cin>>s; int zc = 0,nc = 0; for (int i=0;i<s.length();i++) { if (s[i] == '0' && flag0==1) { zc++; } else if (s[i] == '0' && flag0==0) { zc = 1; nc = 0; flag0 = 1; flag1 = 0; } else if (s[i] == '1' && flag1==1) { nc++; } else if (s[i] == '1' && flag1==0) { nc = 1; zc = 0; flag0 = 0; flag1 = 1; } if (zc == 7 || nc == 7) break; } if (zc == 7 || nc == 7) { cout<<"YES\n"; } else cout<<"NO\n"; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string name1; string name2; while (getline(cin,name1)) { getline(cin,name2); float s1 = 0; int l1 = name1.length(); for (int i = 0; i < l1; i++) { if (name1[i] <= 122 && name1[i]>= 97) { s1 += name1[i] - 96; } else if (name1[i] <= 90 && name1[i]>= 65) { s1 += name1[i] - 64; } } while(s1>9){ int sum = 0; while(s1>0) { sum+=(int)s1%10; s1/=10; } s1 = sum; } float s2 = 0; int l2 = name2.length(); for (int i = 0; i < l2; i++) { if (name2[i] <= 122 && name2[i]>= 97) { s2 += name2[i] - 96; } else if (name2[i] <= 90 && name2[i]>= 65) { s2 += name2[i] - 64; } } while(s2>9){ int sum = 0; while(s2>0) { sum+=(int)s2%10; s2/=10; } s2 = sum; } double mini = min(s1,s2); double maxi = max(s1,s2); cout<<fixed<<setprecision(2); cout<<(mini*100)/maxi<<" %"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int x1,y1,x2,y2; while (1) { ISTREAM>>x1>>y1>>x2>>y2; if (x1 == 0 && y1 == 0 && x2 == 0 && y2 == 0) { break; } if (y1 == y2 && x1 == x2) cout<<0<<endl; else if (abs (y1 - y2) == abs(x1 - x2)) cout<<1<<endl; else if (x1 == x2 || y1==y2) cout<<1<<endl; else cout<<2<<endl; } return 0; }<file_sep>#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <cstdlib> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> using namespace std; class YahtzeeScore { public: int maxPoints(vector<int> toss); }; int YahtzeeScore::maxPoints(vector<int> toss) { int max=0; int a[7]={0}; for (int i=0;i<toss.size();i++) { a[toss[i]]++; } for (int i=1;i<7;i++) { if (a[i]*i>max) max=a[i]*i; } return max; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a, n; cin >> a >> n; while(n <= 0) { cin >> n; } int sum = a; for (int i = a+1; i < a+n; i++) { sum+=i; } cout<<sum<<endl; return 0; } <file_sep>#include<stdio.h> int main() { int t,i; scanf("%d",&t); long long int n; for (i=0;i<t;i++) { scanf("%lld",&n); n=(n*(n+2)*((2*n)+1))/8; printf("%lld\n",n); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; for (int i = 0;i<t;i++) { int n; cin>>n; float score = 0; int oudler = 0; string s; while (n--) { cin>>s; if (s == "fool") { oudler++; score += 4.5; continue; } if (s == "one" || s == "twenty-one") { oudler++; score += 4.5; } else if (s == "king") { score+=4.5; } else if (s == "queen") { score += 3.5; } else if (s == "knight") { score += 2.5; } else if (s == "jack") { score += 1.5; } else { score += 0.5; } cin>>s; cin>>s; } cout<<"Hand #"<<i+1<<endl; if (oudler == 3) { if (score < 36) { cout<<"Game lost by "<<36 - score<<" point(s)."<<endl; } else { cout<<"Game won by "<<score - 36<<" point(s)."<<endl; } } else if (oudler == 2) { if (score < 41) { cout<<"Game lost by "<<41 - score<<" point(s)."<<endl; } else { cout<<"Game won by "<<score - 41<<" point(s)."<<endl; } } else if (oudler == 1) { if (score < 51) { cout<<"Game lost by "<<51 - score<<" point(s)."<<endl; } else { cout<<"Game won by "<<score - 51<<" point(s)."<<endl; } } else { if (score < 56) { cout<<"Game lost by "<<56 - score<<" point(s)."<<endl; } else { cout<<"Game won by "<<score - 56<<" point(s)."<<endl; } } if (i < t-1) cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int m,n; while (1) { ISTREAM>>m>>n; if (m == 0 && n == 0) { break; } else if (m == 0 || n==0) { cout<<0; } else if (m>=3 && n>=3) { cout<<(n*m)/2 + (m*n)%2; } else if (m == 1 || n == 1) { cout<<max(m,n); } else if (m==2 && n == 2) { cout<<"4"; } else if (m == 2 || n == 2) { int t = max(m,n); if (t%2== 0 && (t/2)%2 == 1) cout<<max(m,n) + 2; else cout<<max(m,n) + max(m,n)%2; } cout<<" knights may be placed on a "<<m<<" row "<<n<<" column board."<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { std::setlocale(LC_ALL, "en_US.UTF-8"); std::setlocale(LC_NUMERIC, "en_US"); int a,b; cin>>a>>b; if (a>b) swap(a,b); int sum = 0; for (int i=a+1;i<b;i++) { if (abs(i)%2L==1) sum+=i; } cout<<sum<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool valid (string check) { for (int i = 1; i < (int)check.length(); i++) { if (check[i] <= check[i-1]) return false; } return true; } int main() { bool flag1 = true; map <string, int> dic; int counter = 1; for (int i1 = 0; i1 <= 26; i1++) { for (int i2 = 0; i2 <= 26; i2++) { if (i1 > 0 && i2 <= i1) continue; for (int i3 = 0; i3 <= 26; i3++) { if (i2 > 0 && i3 <= i2) continue; for (int i4 = 0; i4 <= 26; i4++) { if (i3 > 0 && i4 <= i3) continue; for (int i5 = 1; i5 <= 26; i5++) { if (i4 > 0 && i5 <= i4) continue; string t = ""; if (i1 != 0) { t += (char)(96 + i1); } if (i2 != 0) { t += (char)(96 + i2); } if (i3 != 0) { t += (char)(96 + i3); } if (i4 != 0) { t += (char)(96 + i4); } if (i5 != 0) { t += (char)(96 + i5); } dic[t] = counter; counter += 1; } } } } } string check; while (cin >> check) { if (valid(check)) { cout << dic[check] << endl; } else { cout << 0 << endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int fibo[] = {0,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,165580141,267914296,433494437,701408733,1134903170,1836311903}; long long int n; cin>>n; for (int i=0;i<45;i++) { for (int j=i;j<45;j++) { for (int k=j;k<45;k++) { if (fibo[i] + fibo[j] + fibo[k] == n) { cout<<fibo[i]<<" "<<fibo[j]<<" "<<fibo[k]<<endl; return 0; } } } } cout<<"I'm too stupid to solve this problem"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; for (int i = 0; i < n; i++) { int t; int a,b; ISTREAM>>t; if (t<=0) { cout<<"no"<<endl<<endl; continue; } ISTREAM>>a>>b; int temp = a - b; int flag = 0; for (int j = 1; j < t; j++) { ISTREAM>>a>>b; if (a - b!= temp) { flag = 1; } } if (flag == 0) cout<<"yes"<<endl; else cout<<"no"<<endl; if (i< n-1) cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { double n; cin>>n; cout<<fixed<<setprecision(4); for (int i=0;i<100;i++) { cout<<"N["<<i<<"] = "<<n<<endl; n/=2; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,x0,y0; cin>>n>>x0>>y0; set < pair<int,int> > slopes; int x,y; int num,den; for (int i = 0;i<n;i++) { cin>>x>>y; num = y - y0; den = x - x0; int temp; if (num == 0 && den == 0) { continue; } else { temp = __gcd(num,den); } num /= temp; den /= temp; slopes.insert(make_pair(num,den)); } cout<<slopes.size()<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n, c; int max_val; int min_val; int idx = 0; while(1) { cin>>c>>n; if (n + c == 0) { break; } cout<<"Election #"<<++idx<<endl; vector <vector <int> > ballot(n,vector<int> (c,0)); vector <bool> valid(n); int valid_counter = 0; for (int i = 0;i<n;i++) { for (int j = 0;j < c;j++) { cin >> ballot[i][j]; } reverse(ballot[i].begin(), ballot[i].end()); set <int> check; for (auto ii:ballot[i]) { check.insert(ii); } if (check.size() == c && *check.rbegin() == c && *check.begin() == 1) { valid[i] = true; valid_counter += 1; } else { valid[i] = false; } } if (valid_counter < n) { cout<<" "<<n - valid_counter<<" bad ballot(s)"<<endl; } vector <int> deleted(c, 0); while (1) { vector <int> counters(c,0); for (int i = 0; i < n; i++) { if(!valid[i]) { continue; } counters[ballot[i].back() - 1] += 1; } vector <int> max_index; max_val = -1; vector <int> min_index; min_val = INT_MAX; for (int i = 0;i < c; i++) { if (deleted[i]) { continue; } if (counters[i] > max_val) { max_val = counters[i]; max_index.clear(); max_index.push_back(i); } else if (counters[i] == max_val) { max_index.push_back(i); } if (counters[i] < min_val) { min_val = counters[i]; min_index.clear(); min_index.push_back(i); } else if (counters[i] == min_val) { min_index.push_back(i); } } // cout<<min_index[0] + 1<<endl; deleted[min_index[0]] = 1; if (max_val > valid_counter/2) { cout<<" Candidate "<<max_index[0]+1<<" is elected."<<endl; break; } if ((int)max_index.size() > 1 && max_val*(int)max_index.size() == valid_counter) { cout<<" The following candidates are tied: "; for (int i = 0;i< max_index.size();i++) { cout << max_index[i] + 1; if (i < max_index.size() - 1) cout<< " "; } cout << endl; break; } for (int i = 0;i < n; i++) { while (deleted[ballot[i].back()-1]) { ballot[i].pop_back(); } } } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <string> mapi(n); for (int i=0;i<n;i++) { cin>>mapi[i]; } int res[100][100]; for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { res[i][j] = 0; } } for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { if (mapi[i][j] == 'o') { if (j>0) { res[i][j-1]++; } if (j<n-1) { res[i][j+1]++; } if (i>0) { res[i-1][j]++; } if (i<n-1) { res[i+1][j]++; } } } } int flag = 0; for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { if (res[i][j]%2 != 0) { flag = 1; } } } if (flag == 0) { cout<<"YES"<<endl; } else { cout<<"NO"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string a,b; int n; while (1) { cin>>n; if (n == 0) { break; } vector <int> arr(11,1); while(1) { cin>>a>>b; if (b == "high") { for (int i = n;i<=10;i++) { arr[i] = 0; } } else if (b == "low") { for (int i = 0;i<=n;i++) { arr[i] = 0; } } else if (b == "on") { if (arr[n] == 0) cout<<"Stan is dishonest"<<endl; else cout<<"Stan may be honest"<<endl; arr.clear(); break; } cin>>n; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n,k; cin>>n>>k; vector< pair<int,int> > vp(n); for (int i=0;i<n;i++) { cin>>vp[i].first; vp[i].second = i+1; } sort(vp.begin(), vp.end()); int sum = 0; vector<int> v; for (int i = 0; i < n; i++) { sum += vp[i].first; if (sum > k) break; v.push_back(vp[i].second); } cout<<v.size()<<endl; for (unsigned int i=0;i<v.size();i++) { cout<<v[i]<<" "; } cout<<endl; return 0; }<file_sep>n,x = [int(x) for x in raw_input().split()] C = map(int,raw_input().split()) C.sort() sum = 0 for i in C: sum += x*i x-=1 print sum <file_sep>#include <bits/stdc++.h> using namespace std; vector <string> rrotate(vector <string> grid) { vector <string> newgrid; for (auto i:grid) { newgrid.push_back(i); } int n = newgrid.size(); for (int i = 0;i<n;i++) { for (int j = 0;j<n;j++) { newgrid[i][j] = grid[n-j-1][i]; } } return newgrid; } int main () { int N,n; while (1) { cin>>N>>n; if (N + n == 0) { break; } vector <string> big(N); vector <string> small(n); for (int i = 0;i<N;i++) { cin>>big[i]; } for (int i = 0;i<n;i++) { cin>>small[i]; } vector<string> rotate1 = rrotate(small); vector<string> rotate2 = rrotate(rotate1); vector<string> rotate3 = rrotate(rotate2); vector<int> cnt(4); for (int i = 0;i<N;i++) { if (i + n > N) break; for (int j = 0;j<N;j++) { if (j + n > N) break; bool match1 = true; bool match2 = true; bool match3 = true; bool match4 = true; for (int k = 0;k<n;k++) { for (int l = 0;l<n;l++) { if (small[k][l] != big[i+k][j+l]) { match1 = false; } if (rotate1[k][l] != big[i+k][j+l]) { match2 = false; } if (rotate2[k][l] != big[i+k][j+l]) { match3 = false; } if (rotate3[k][l] != big[i+k][j+l]) { match4 = false; } } } if (match1 == true) cnt[0]++; if (match2 == true) cnt[1]++; if (match3 == true) cnt[2]++; if (match4 == true) cnt[3]++; } } for (int i = 0; i < 4;i++) { cout<<cnt[i]; if (i<3) cout<<" "; } cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; while (cin>>n) { stack<int> st; queue<int> que; priority_queue <int> pq; int type,ele; bool st_flag = true; bool que_flag = true; bool pq_flag = true; for (int i = 0; i < n; i++) { cin>>type>>ele; if (type == 1) { st.push(ele); que.push(ele); pq.push(ele); } else if (type == 2) { if (st.empty()) { st_flag = false; que_flag = false; pq_flag = false; continue; } int t1 = st.top(); int t2 = que.front(); int t3 = pq.top(); if (ele != t1) { st_flag = false; } if (ele != t2) { que_flag = false; } if (ele != t3) { pq_flag = false; } st.pop();que.pop();pq.pop(); } } if (!st_flag && !que_flag && !pq_flag) { cout<<"impossible"<<endl; } else if (st_flag && !que_flag && !pq_flag) { cout<<"stack"<<endl; } else if (que_flag && !st_flag && !pq_flag) { cout<<"queue"<<endl; } else if (pq_flag && !st_flag && !que_flag) { cout<<"priority queue"<<endl; } else { cout<<"not sure"<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string name; double a,b; cin>>name; cin>>a>>b; printf("TOTAL = R$ %.2f\n",a+0.15*b); return 0; }<file_sep>#include<iostream> #include<vector> using namespace std; void fun(int n){ int godama=n/5; int ichdama=n%5; if (godama>0) cout<<"-O|"; else cout<<"O-|"; for (int i=0;i<ichdama;i++) cout<<"O"; cout<<"-"; for (int i=ichdama;i<4;i++) cout<<"O"; cout<<endl; } int main (void) { int n; int i,j; cin>>n; if (n==0) {fun(0);return 0;} int digits[10]; i=0; while(n>0) { digits[i]=n%10; n/=10; i++; } n=i; for (j=0;j<n;j++) { fun(digits[j]); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string home; string away; cin>>home; cin>>away; int n; cin>>n; vector<int> arr(100,0); vector<int> brr(100,0); int minute; char ch; int num; char col; for (int i=0;i<n;i++) { cin>>minute>>ch>>num>>col; if (ch == 'h') { if (arr[num] == -1) continue; if (col == 'y') { arr[num]+=1; } else if (col == 'r') { arr[num] += 2; } if (arr[num] >= 2) { cout<<home<<" "<<num<<" "<<minute<<endl; arr[num] = -1; } } else if (ch == 'a') { if (brr[num] == -1) continue; if (col == 'y') { brr[num]+=1; } else if (col == 'r') { brr[num] += 2; } if (brr[num] >= 2) { cout<<away<<" "<<num<<" "<<minute<<endl; brr[num] = -1; } } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; cout<<(n/2)*3 + (int)(n%2 != 0)<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; for (int i=0;i<n;i++) { int a,b; cin>>a>>b; if (a < b) cout<<"<"<<endl; else if (a > b) cout<<">"<<endl; else if (a == b) cout<<"="<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; string rev(string s, int n) { for (int i = 0; i < (int)s.length(); i+=n) { reverse(s.begin() + i, s.begin() + i + n); } return s; } int main() { int n; cin >> n; while (n != 0) { string s; cin >> s; cout<< rev(s, ((int)s.length())/n) << endl; cin >> n; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; int sum = 0; int t; string s; for (int i = 0; i < n; i++) { ISTREAM>>s; if (s == "donate") { ISTREAM>>t; sum+= t; } else if (s == "report") { cout<<sum<<endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; int m; int c; int cnt = 0; while (ISTREAM>>n) { if (cnt != 0) cout<<endl; cnt++; vector < pair <string, int> > record(n); string s; for (int i = 0; i < n; i++) { ISTREAM>>record[i].first; record[i].second = 0; } for (int i = 0; i < n; i++) { ISTREAM>>s>>m>>c; for (int j = 0; j < n; j++) { if (record[j].first == s && c>0) { record[j].second -= (m - m%c); } } for (int j = 0; j < c; j++) { ISTREAM>>s; for (int k = 0; k < n; k++) { if (record[k].first == s) { record[k].second += m/c; } } } } for (int i = 0; i < n; i++) { cout<<record[i].first<<" "<<record[i].second<<endl; } record.clear(); } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int count(vector <vector<int>> &arr) { int sum1 = 0; for (auto i:arr) { for (auto j:i) { sum1 += j; } } return sum1; } int main () { int t; int n; cin >> t; while (t--) { cin >> n; vector <int> arr(n); vector <int> brr(n); vector <vector <int> > grid1(n, vector<int> (n,0)); //max vector <vector <int> > grid2(n, vector<int> (n,0)); //min for (int i = 0; i < n; i++) { cin >> arr[i]; grid2[i][0] = arr[i]; for (int j = 0; j < n; j++) { grid1[i][j] = arr[i]; } } for (int i = 0; i < n; i++) { cin >> brr[i]; for (int j = 0; j < n; j++) { grid1[j][i] = min(brr[i], grid1[j][i]); } } for (int i = 0; i < n; i++) { int ele = brr[i]; int ind = -1; for (int j = n-1; j >= 0; j--) { if (grid2[j][i] == ele && ind == -1) { ind = j; } else { if (i < n-1) { grid2[j][i+1] = grid2[j][i]; } grid2[j][i] = 0; } } } // fix for the front side for (int i = 0; i < n; i++) { int ele = arr[i]; bool flag = true; for (int j = 0; j < n; j++) { if (grid2[i][j] == ele) { flag = false; break; } } if (flag) { for (int j = 0; j < n; j++) { if (grid2[i][j] == 0 && brr[j] >= ele) { grid2[i][j] = ele; break; } } } } // fix for the right side. for (int i = 0; i < n; i++) { int ele = brr[i]; bool flag = true; for (int j = n-1; j >= 0; j--) { if (grid2[j][i] == ele) { flag = false; break; } } if (flag) { for (int j = n - 1; j >= 0; j--) { if (grid2[j][i] == 0 && arr[j] >= ele) { grid2[j][i] = ele; break; } } } } cout << "Matty needs at least " << count(grid2) <<" blocks, and can add at most " << count(grid1) - count(grid2) << " extra blocks." << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int code1, item1; float p1; int code2, item2; float p2; cin>>code1>>item1>>p1; cin>>code2>>item2>>p2; printf("VALOR A PAGAR: R$ %.2f\n", item1*p1 + item2*p2); return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<int> arr(n); for (int i = 0; i < n; i++) { cin>>arr[i]; } sort(arr.begin(), arr.end()); int count = 0; for (int i = 1;i<n;i++) { if (arr[i] <= arr[i-1]) { count+= arr[i-1] - arr[i] + 1; arr[i]=arr[i-1]+1; } } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; while (t--) { string s; vector <string> edges; cin>>s; while (s[0] != '*') { edges.push_back(s); cin>>s; } cin>>s; map <char,int> dic; int ind = 0; for(int i = 0;i<s.length();i+=2) { dic[s[i]] = ind; ind++; } vector < vector <int> > graph(ind); for (int i = 0;i<edges.size();i++) { int a = dic[edges[i][1]]; int b = dic[edges[i][3]]; graph[a].push_back(b); graph[b].push_back(a); } vector <int> visited(ind,1); int akon = 0; int tree = 0; for (int i = 0;i<ind;i++) { if (visited[i] == 0) { continue; } if (graph[i].size() == 0) { akon++; visited[i] = 0; continue; } tree++; stack <int> ss; ss.push(i); visited[i] = 0; while (!ss.empty()) { int crr = ss.top();ss.pop(); visited[crr] = 0; for (int j = 0;j<graph[crr].size();j++) { if (visited[graph[crr][j]] != 0) { ss.push(graph[crr][j]); } } } } cout<<"There are "<<tree<<" tree(s) and "<<akon<<" acorn(s)."<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int adder = (int)n%2!=0; cout<<(n/2)*(n/2) + (n/2 + adder)*(n/2+adder)<<endl; for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { if ((i+j)%2 == 0) { cout<<"C"; } else { cout<<"."; } } cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; int cnt = 1; while (m>=cnt) { m -= cnt; cnt++; if (cnt>n) cnt %= n; } cout<<m<<endl; return 0; }<file_sep>#include<stdio.h> int main() { int a,d; int i; int at,de1,de2,at2; int min1,min2; scanf("%d %d",&a,&d); while( a!=0 && d!=0 ) { at2=99999; de2=99999; min1=99999; min2=99999; for (i=0;i<a;i++) { scanf("%d",&at); if (at<=min1) { at2=min1; min1=at; } else if (at>min1 && at<at2) { at2=at; } } for (i=0;i<d;i++) { scanf("%d",&de1); if (de1<=min2) { de2=min2; min2=de1; } else if(de1>min2 && de1<de2) { de2=de1; } } if ((min1>=de2)||(min1==min2&&min1==de2)) printf("N\n"); else printf("Y\n"); scanf("%d %d",&a,&d); } return 0; } <file_sep>for _ in range(input()): print pow(2,input()+1,1298074214633706835075030044377087)-1 <file_sep>#include <bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { int n,m; cin>>n>>m; char matrix[n][m]; for (int i=0;i<n;i++) { for (int j=0;j<m;j++) { cin>>matrix[i][j]; } } int eat = 0; for (int i=0;i<n;i++) { for (int j=0;j<m;j++) { if (matrix[i][j] == 'P') { if (i>0 && matrix[i-1][j] == 'W') { eat++; matrix[i-1][j] = '.'; } else if (j>0 && matrix[i][j-1] == 'W') { eat++; matrix[i][j-1] = '.'; } else if (i<n-1 && matrix[i+1][j] == 'W') { eat++; matrix[i+1][j] = '.'; } else if (j<m-1 && matrix[i][j+1] == 'W') { eat++; matrix[i][j+1] = '.'; } } } } cout<<eat<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d",&n); while (n != 0) { int o1, o2; cin>>o1>>o2; int c1,c2; for (int i = 0 ; i < n ; i++) { cin>>c1>>c2; c1-=o1; c2-=o2; if (c1 == 0 || c2 ==0) { cout<<"divisa"<<endl; } else if (c1>0 && c2>0) { cout<<"NE"<<endl; } else if (c1<0 && c2>0) { cout<<"NO"<<endl; } else if (c1<0 && c2<0) { cout<<"SO"<<endl; } else if (c1>0 && c2<0) { cout<<"SE"<<endl; } } scanf("%d",&n); } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<long long int> arr(n); for (int i = 0; i < n; i++) { cin>>arr[i]; } sort(arr.begin(), arr.end()); long long int sum = 0; int cnt = 0; for (int i = 0; i < n; i++) { if (arr[i]>=sum) { cnt++; sum += arr[i]; } } cout<<cnt<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool valid (int i, int j) { if (i>=0 && i < 3 && j >= 0 && j < 3) { return true; } else { return false; } } bool undone(vector <string> s) { for (int i = 0;i<3;i++) { if (s[i] != "000") return true; } return false; } void doit(vector<string> &grid) { vector <string> temp; for (int i = 0;i<3;i++) { temp.push_back(grid[i]); } for (int i = 0;i<3;i++) { for (int j = 0;j<3;j++) { int cnt = 0; if (valid(i-1,j) && temp[i-1][j] == '1') cnt+=1; if (valid(i+1,j) && temp[i+1][j] == '1') cnt+=1; if (valid(i,j-1) && temp[i][j-1] == '1') cnt+=1; if (valid(i,j+1) && temp[i][j+1] == '1') cnt+=1; if (cnt%2 == 0) { grid[i][j] = '0'; } else { grid[i][j] = '1'; } } } } int main () { int t; cin>>t; while(t--) { vector<string> grid(3); for (int i = 0;i<3;i++) { cin>>grid[i]; } int cnt = 0; while (undone(grid)) { doit(grid); cnt++; } cout<<cnt-1<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; int alcohol=0,gasoline=0,diesel=0; while(1) { ISTREAM>>n; if (n == 1) alcohol++; else if (n==2) gasoline++; else if (n==3) diesel++; else if (n==4) break; } cout<<"MUITO OBRIGADO"<<endl; cout<<"Alcool: "<<alcohol<<endl; cout<<"Gasolina: "<<gasoline<<endl; cout<<"Diesel: "<<diesel<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; vector <int> calc(int t1, int t2) { int val1 = max(0, min(t2, 1080) - max(t1, 480)); int val2 = max(0, min(t2, 1320) - max(t1, 1080)); int val3 = max(0, min(t2, 1440) - max(t1, 1320)); int val4 = max(0, min(t2, 480) - max(t1, 0)); return {val1, val2, val3 + val4}; } int main () { char inp; string number; int h1, m1, h2, m2; map <char, vector <double> > data = { {'A', {0.10, 0.06, 0.02}}, {'B', {0.25, 0.15, 0.05}}, {'C', {0.53, 0.33, 0.13}}, {'D', {0.87, 0.47, 0.17}}, {'E', {1.44, 0.80, 0.30}} }; while (cin >> inp) { if (inp == '#') { break; } cin >> number >> h1 >> m1 >> h2 >> m2; int t1 = h1*60 + m1; int t2 = h2*60 + m2; double cost = 0; vector <double> rates = data[inp]; vector <int> res(3); if (t1 == t2) { res[0] = 600; res[1] = 240; res[2] = 600; } else if (t1 > t2) { vector <int> res1 = calc(t1, 1440); vector <int> res2 = calc(0, t2); res[0] = res1[0] + res2[0]; res[1] = res1[1] + res2[1]; res[2] = res1[2] + res2[2]; } else { res = calc(t1, t2); } cout<<fixed<<setprecision(2); cout.width(10); cout<<right<<number; cout.width(6); cout<<right<<res[0]; cout.width(6); cout<<right<<res[1]; cout.width(6); cout<<right<<res[2]; cout.width(3); cout<<right<<inp; cout.width(8); cout<<right<<res[0] * rates[0] + res[1] * rates[1] + res[2] * rates[2]<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int N; cin>>N; vector <int> numbers(N); vector <int> A; vector <int> B; for (int i=0;i<N;i++) { cin>>numbers[i]; } for (int i = 0 ; i < N ; i++) { for (int j = 0 ; j < N ; j++) { for (int k = 0 ; k < N ; k++) { A.push_back(numbers[i]*numbers[j] + numbers[k]); } } } sort(A.begin(),A.end()); for (int i = 0 ; i < N ; i++) { if (numbers[i]==0) continue; for (int j = 0 ; j < N ; j++) { for (int k = 0 ; k < N ; k++) { B.push_back(numbers[i]*(numbers[j] + numbers[k])); } } } sort(B.begin(),B.end()); int count = 0; int i=0, j=0; while(i < A.size() && j < B.size()) { if (A[i]<B[j]) i++; else if (A[i]>B[j]) j++; else { int c1=1, c2=1; while (A[i+1]==A[i] && i<A.size() ) {i++;c1++;} while (B[j+1]==B[j] && j<B.size() ) {j++;c2++;} count+=c1*c2 ; i++; j++; } } cout<<count<<"\n"; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; double temp; for (int i = 0; i < n; i++) { ISTREAM>>temp; int cnt = 0; while(temp>1) { temp/=2; cnt++; } cout<<cnt<<" dias"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int b,n; int x,y,z; while (1) { ISTREAM>>b>>n; int flag = 0; if (b == 0 && n == 0) { break; } vector<int> banks(b); for (int i = 0; i < b; i++) { ISTREAM>>banks[i]; } for (int i = 0; i < n; i++) { ISTREAM>>x>>y>>z; banks[x-1]-=z; banks[y-1]+=z; } for (int i = 0; i < b; i++) { if (banks[i]<0) { flag = 1; } } if (flag == 1) { cout<<"N"<<endl; } else { cout<<"S"<<endl; } banks.clear(); } return 0; } <file_sep>#include<stdio.h> int main () { long long int i,n; long long int a=192; long long int d=250; scanf("%lld",&n); long long int m; for (i=0;i<n;i++) { scanf("%lld",&m); printf("%lld\n",a+((m-1)*d)); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); for (int i=0;i<n;i++) { cin >> Arr[i]; } sort(Arr.begin(),Arr.end()); int count = 1; int max_count = -1; int global_count = 0; int prev = Arr[0]; for (int i=1;i<=n;i++) { if (i<n && Arr[i] == Arr[i-1]) { count++; } else { if (count>max_count) { max_count = count; } count = 1; global_count++; } } cout<<max_count<<" "<<global_count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif bool isPerfect(int n) { int sum = 0; for (int i=1;i*i<=n;i++) { if (n%i == 0) { sum += i; sum += n/i; } if (i*i == n) sum -= i; } if (sum == 2*n) return true; return false; } int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; int temp; for (int i = 0; i < n; i++) { ISTREAM>>temp; if (isPerfect(temp)) cout<<temp<<" eh perfeito"<<endl; else cout<<temp<<" nao eh perfeito"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; int temp; while(1) { cin>>n>>m; vector <int> brr(m); vector <int> arr(n+1,0); if (n == 0 && m == 0) break; for (int i = 0;i < m;i++) { cin>>brr[i]; } for (int i = 0;i<m;i++) { for (int j = 0;j<m;j++) { arr[abs(brr[i] - brr[j])]++;; } } bool flag = true; for (int i = 0;i< n+1;i++) { if (arr[i]== 0) flag = false; } if (flag) cout<<"Y"<<endl; else cout<<"N"<<endl; arr.clear(); brr.clear(); } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; int n; cin >> t; while (t--) { cin >> n; vector <pair<int, int> > arr(n); for (int i = 0; i < n; i++) { cin >> arr[i].first; if (arr[i].first < 0) { arr[i].second = 1; arr[i].first *= -1; } else { arr[i].second = 0; } } sort(arr.begin(), arr.end()); int beg1 = 0; int beg2 = 1; int cnt1 = 0; int cnt2 = 0; for (int i = 0; i < n; i++) { if (arr[i].second == beg1) { cnt1 += 1; beg1 ^= 1; } if (arr[i].second == beg2) { cnt2 += 1; beg2 ^= 1; } } cout << max(cnt1, cnt2) << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; class UFDS { private: int size; vector <int> rank; vector <int> parent; vector <int> debt; public: UFDS(int n) { size = n; rank.assign(n, 0); parent.assign(n, 0); debt.assign(n, 0); for (int i = 0; i < n; i++) { parent[i] = i; } } void update_debt(vector <int> &dbt) { for (int i = 0; i < size; i++) { debt[i] = dbt[i]; } } int findset(int a) { return (a == parent[a]?a:(parent[a] = findset(parent[a]))); } bool is_same_set(int a, int b) { return findset(a) == findset(b); } void union_set(int a, int b) { int x = findset(a); int y = findset(b); if (!is_same_set(x, y)) { if (rank[x] > rank[y]) { parent[y] = x; } else { parent[x] = y; if (rank[x] == rank[y]) { rank[y]++; } } } } bool result() { vector <int> res(size, 0); for (int i = 0; i < size; i++) { int x = findset(i); res[x] += debt[i]; } for (auto it:res) { if (it != 0) { return false; } } return true; } }; int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; UFDS case1(n); vector <int> dbt(n); for (int i = 0; i < n; i++) { cin >> dbt[i]; } case1.update_debt(dbt); int a, b; for (int i = 0; i < m; i++) { cin >> a >> b; case1.union_set(a, b); } if (case1.result()) { cout << "POSSIBLE" << endl; } else { cout << "IMPOSSIBLE" << endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int max = -1; for (int i=0;i<n;i++) { int temp; cin>>temp; if (temp>max) max = temp; } cout<<max<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int n,k; cin>>n>>k; if (n%2 == 0) { if (k<=n/2) cout<<2*k - 1<<endl; else cout<<2*(k - n/2)<<endl; } else { if (k<=(n+1)/2) cout<<2*k - 1<<endl; else cout<<2*(k - (n+1)/2)<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int n; cin >> n; vector <int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } long long int count1 = 1; sort(Arr.begin(),Arr.end()); long long int maxdiff = Arr[n-1] - Arr[0]; if (maxdiff == 0) { cout<<"0 "<<(n*(n-1))/2; return 0; } for (int i=1; i<n; i++) { if (Arr[i] != Arr[0]) { break; } count1++; } long long int count2 = 1; for (int i=n-2; i>0; i--) { if (Arr[i] != Arr[n-1]) { break; } count2++; } cout<<maxdiff<<" "<<count1*count2<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int mini = INT_MAX; vector <int> res1; void fun(int init, vector <int> &arr, vector <int> &res, int N) { for (int i = init; i<arr.size();i++) { if (arr[i] <= N) { res.push_back(arr[i]); fun(i+1,arr,res,N-arr[i]); } } if (N < mini) { mini = N; res1.clear(); for (auto i:res) { res1.push_back(i); } } res.pop_back(); } int main () { int N; while (cin>>N) { mini = INT_MAX; int n; cin>>n; vector <int> arr(n); for (int i = 0;i<n;i++) { cin>>arr[i]; } vector <int> res; fun(0,arr,res,N); for (auto i:res1) cout<<i<<" "; cout<<"sum:"<<accumulate(res1.begin(), res1.end(),0)<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; if (n%2==0 && n>2) cout<<"YES"; else cout<<"NO"; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; int n, i, k; int val; int active_till; int active_from; int inactive; int ignored; int idx = 0; while (t--) { cin >> n >> i >> k; active_from = 0; active_till = active_from + i; inactive = 0; ignored = 0; while (n--) { cin>>val; if (val < active_till && val >= active_from) { active_till = val + i; } else if (val >= active_till) { active_from = val + k; active_till = active_from + i; inactive += 1; } else if (val < active_from) { ignored += 1; } } cout<<"Case "<<++idx<<": "<<inactive<<" "<<ignored<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; cout<<n<<" "; for (int i = 1; i<n ; i++ ) { cout<<i<<" "; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main(){ int n; while(1){ cin>>n; if(n==0) break; vector<vector <int> > mat(n,vector<int> (n)); // Use 2D vector whats all this will tell some day. Just remember for now:) for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cin>>mat[i][j]; } } vector <int> row_sum(n,0); vector <int> col_sum(n,0); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ row_sum[i] += mat[i][j]; col_sum[i] += mat[j][i]; } } int rcnt = 0; int ccnt = 0; int rind = -1; int cind = -1; for (int i = 0;i<n;i++) { if (row_sum[i]%2==1) { rcnt++; rind = i; } if (col_sum[i]%2 == 1) { ccnt++; cind = i; } } if (rcnt == 0 && ccnt == 0) { cout<<"OK"<<endl; } else if (rcnt == 1 && ccnt == 1) { cout<<"Change bit ("<<rind+1<<","<<cind+1<<")"<<endl; } else { cout<<"Corrupt"<<endl; } } }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<int> arr(n); vector<int> brr(n-1); vector<int> crr(n-2); for (int i = 0; i < n; i++) { cin>>arr[i]; } for (int i = 0; i < n-1; i++) { cin>>brr[i]; } for (int i = 0; i < n-2; i++) { cin>>crr[i]; } sort(arr.begin(), arr.end()); sort(brr.begin(), brr.end()); sort(crr.begin(), crr.end()); int flag = 0; for (int i = 0; i < n-1; i++) { if (arr[i]!=brr[i]) { cout<<arr[i]<<endl; flag = 1; break; } } if (flag == 0) cout<<arr[n-1]<<endl; flag = 0; for (int i = 0; i < n-2; i++) { if (brr[i]!=crr[i]) { cout<<brr[i]<<endl; flag = 1; break; } } if (flag == 0) cout<<brr[n-2]<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a, b, c; vector <int> buildings(10000, 0); int maxc = -1; while(cin >> a >> b >> c) { for (int i = a; i < c; i++) { buildings[i] = max(buildings[i], b); } maxc = max(maxc, c); } int prev = buildings[1]; bool flag = true; for (int i = 1; i <= maxc; ) { if (flag) { flag = false; } else { cout << " "; } cout << i << " " << prev; while(prev == buildings[i]) { i += 1; } prev = buildings[i]; } cout << endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int counter = 1; while (n) { vector < pair <int,int> > Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i].first>>Arr[i].second; } double sum1=0, sum2 = 0; cout<<"Cidade# "<<counter <<":"<<endl; for (int i=0;i<n;i++) { sum1+=Arr[i].first; sum2+=Arr[i].second; int t1 = Arr[i].second/Arr[i].first; Arr[i].second = Arr[i].first; Arr[i].first = t1; } sort(Arr.begin(), Arr.end()); int sum = Arr[0].second; int t = Arr[0].first; for (int i=1;i<n;i++) { if (Arr[i].first == t) { sum += Arr[i].second; } else { cout<<sum<<"-"<<t<<" "; t = Arr[i].first; sum = Arr[i].second; } } cout<<sum<<"-"<<t<<endl; printf("Consumo medio: %.2lf m3.\n",floor((sum2/sum1)*100)/100.0); cin>>n; if (n>0) cout<<endl; counter++; Arr.clear(); } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int Arr[11][4] = {0}; for (int i = 0;i<11;i++) { for (int j = 0;j<4;j++) { if (n == 0) { break; } if (i > 0 && j == 2) { continue; } Arr[i][j] = 1; n--; } } cout<<"+------------------------+"<<endl; cout<<"|"; for (int i=0;i<11;i++) { if (Arr[i][0] == 1) { cout<<"O."; } else { cout<<"#."; } } cout<<"|D|)"<<endl; cout<<"|"; for (int i=0;i<11;i++) { if (Arr[i][1] == 1) { cout<<"O."; } else { cout<<"#."; } } cout<<"|.|"<<endl; if (Arr[0][2] == 1) cout<<"|O.......................|"<<endl; else cout<<"|#.......................|"<<endl; cout<<"|"; for (int i=0;i<11;i++) { if (Arr[i][3] == 1) { cout<<"O."; } else { cout<<"#."; } } cout<<"|.|)"<<endl; cout<<"+------------------------+"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { float a, b; cin >> a >> b; printf("MEDIA = %.5f\n", (3.5 * a + 7.5 * b) / 11); return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int tt; cin>>tt; while (tt--) { int l,m; cin>>l>>m; l*= 100; queue <int> left; queue <int> right; int ele; string dir; for (int i = 0;i<m;i++) { cin>>ele>>dir; if (dir == "left") { left.push(ele); } else if (dir == "right") { right.push(ele); } } left.push(99999999); right.push(99999999); int flag = 0; int count = 0; while (left.size() > 1 || right.size() > 1) { int len = l; if (flag == 0) { while (left.size()!=1 && left.front() <= len ) { len -= left.front(); left.pop(); } count++; flag ^= 1; } else if (flag == 1) { while (right.size() != 1 && right.front() <= len ) { len -= right.front(); right.pop(); } count++; flag ^= 1; } } cout<<count<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool valid (int a,int b,int n,int m) { if (a >= 0 && a < n && b >= 0 && b<m) { return true; } else { return false; } } int main () { int t; cin>>t; int n,m,c; while (t--) { cin >> n >> m >> c; vector<string> grid(n); for (int i = 0; i < n; i++) { cin>>grid[i]; } while (c--) { vector<string> new_grid; for (int i = 0; i <n; i++) { string temp = ""; for (int j = 0;j<m;j++) { char ch = grid[i][j]; if (ch == 'R') ch = 'P'; else if (ch == 'S') ch = 'R'; else if (ch == 'P') ch = 'S'; if (valid(i-1,j,n,m) && grid[i-1][j] == ch) { temp += ch; } else if (valid(i+1,j,n,m) && grid[i+1][j] == ch) { temp += ch; } else if (valid(i,j+1,n,m) && grid[i][j+1] == ch) { temp += ch; } else if (valid(i,j-1,n,m) && grid[i][j-1] == ch) { temp += ch; } else { temp += grid[i][j]; } } new_grid.push_back(temp); } for (int i = 0;i<n;i++) { for (int j = 0;j<m;j++) { grid[i][j] = new_grid[i][j]; } } } for (int i = 0;i<n;i++ ) { cout<<grid[i]<<endl; } if (t > 0) cout<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; bool myfunction (string s1, string s2) { for (int i = 0; i < s1.length(); i++) { char t1 = s1[i]; char t2 = s2[i]; if (t2 >= 97) { t2 -= 32; } if (t1 >= 97) { t1 -= 32; } if (t1 < t2) { return true; } else if (t1 > t2) { return false; } else if (s1[i] < s2[i]) { return true; } else if (s1[i] > s2[i]) { return false; } } } string str(vector <char> t) { string res = ""; for (auto i:t) { res += i; } return res; } int main () { int n; cin >> n; while (n--) { string s; cin >> s; set <string> some; vector <char> t1; for (auto i:s) { t1.push_back(i); } sort(t1.begin(), t1.end()); do { some.insert(str(t1)); } while (next_permutation(t1.begin(), t1.end())); vector <string> res; for (auto i:some) { res.push_back(i); } sort(res.begin(), res.end(), myfunction); for (auto i: res) { cout << i << endl; } } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; int main () { int n,m,k; int a,b; int flag = 0; cin>>n>>m>>k; int matrix[n][m]; for (int i=0;i<n;i++) { for (int j=0;j<m;j++) { matrix[i][j] = 0; } } for (int i=0;i<k;i++) { cin>>a>>b; a--; b--; matrix[a][b] = 1; if (((a>0 && matrix[a-1][b] == 1) && (a>0 && b > 0 && matrix[a-1][b-1]==1) && (b>0 && matrix[a][b-1] == 1) ) || ( (a>0 && matrix[a-1][b] == 1) && (a>0 && b < m-1 && matrix[a-1][b+1]==1) && (b<m-1 && matrix[a][b+1]==1) ) || ( (a<n-1 && matrix[a+1][b]==1) && (a<n-1 && b>0 && matrix[a+1][b-1]==1) && (b>0 && matrix[a][b-1]==1) ) || ( (a<n-1 && matrix[a+1][b]==1) && (a<n-1 && b<m-1 && matrix[a+1][b+1] == 1) && (b<m-1 && matrix[a][b+1]==1) ) ) { cout<<i+1<<endl; flag = 1; break; } } if (flag == 0) cout<<"0"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { vector <unsigned long long int> Fib(61); Fib[0] = 0;Fib[1] = 1; for (int i=2;i<61;i++) { Fib[i] = Fib[i-1] + Fib[i-2]; } int n; cin>>n; long long int temp; for (int i=0;i<n;i++) { cin>>temp; cout<<"Fib("<<temp<<") = "<<Fib[temp]<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int maxi = -9; int temp; int pos = -1; for (int i = 0; i < 100; i++) { cin >> temp; if (temp>maxi) { maxi = temp; pos = i+1; } } cout << maxi << endl; cout << pos << endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int fun(int n) { int sum1 = 0; while(n!= 0) { sum1 += n%10; n/=10; } return sum1; } int main () { int t; cin >> t; while(t--) { string card = ""; string s; for(int i = 0; i < 4; i++) { cin >> s; card += s; } int even = 0; for (int i = 0 ; i < 16;i+=2) { even += fun((card[i] - 48)*2); } int odd = 0; for (int i = 1;i < 16; i+=2) { odd += (card[i] - 48); } if((even + odd)%10== 0) { cout<<"Valid"<<endl; } else { cout<<"Invalid"<<endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int n,m; cin>>n>>m; long long int t = n-(m-1); long long int maxi = (t*(t-1))/2; if (n%m == 0) { t = n/m; cout<<m* ((t*(t-1))/2)<<" "<<maxi<<endl; } else { t = n/m; long long int temp = (m-(n%m))*((t*(t-1))/2); t += 1; temp += (n%m)*((t*(t-1))/2); cout<<temp<<" "<<maxi<<endl; } /* if (ones >= 0) { cout<<twos<<" "<<maxi<<endl; } else if (ones <0) { twos = m-1; t = n - m + 1; cout<<twos + (t*(t-1))/2<<" "<<maxi<<endl; }*/ return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; string s; int cnt = 0; for (int i=0; i < n; i++ ) { cin >> s; if (s[0] == '+' || s[2] == '+') cnt++; else cnt--; } cout <<cnt; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,x,y; cin>>n>>x>>y; if (y*n < x*100) { cout<<"0"<<endl; } else { cout<<max(0,(y*n - x*100)/100 + (int)((y*n - x*100)%100 != 0))<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; if (n%2 == 1) { cout<<"-1"<<endl; return 0; } for (int i = 1; i <= n/2; i++ ) { cout<<2*i<<" "<<2*i-1<<" "; } cout<<endl; return 0; }<file_sep>#include "bits/stdc++.h" using namespace std; int main () { while (1) { int a,b; cin>>a>>b; if (a == 0 && b == 0) { break; } int val; set <int> a_val; set <int> b_val; for (int i = 0;i<a;i++) { cin>>val; a_val.insert(val); } for (int i = 0;i<b;i++) { cin>>val; b_val.insert(val); } int uni_a = 0; int uni_b = 0; for (auto i:a_val) { if (b_val.find(i)==b_val.end()) { uni_a++; } } for (auto i:b_val) { if (a_val.find(i) == a_val.end()) { uni_b++; } } cout<<min(uni_a,uni_b)<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> #include <unordered_set> using namespace std; int main() { int n; cin>>n; int t; pair <int,int> A[n]; vector<int> v(n); for (int i=0;i<n;i++) { cin>>A[i].first; A[i].second = i; } sort(A,A+n); int maxi=-1; for (int i=0;i<n;i++) { maxi = max(A[i].first,maxi+1); v[A[i].second] = maxi; } for (int i=0;i<n;i++) cout<<v[i]<<" "; cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> typedef unsigned long long int LL; using namespace std; LL C(LL n,LL r) { if(r > n / 2) r = n - r; // because C(n, r) == C(n, n - r) LL ans = 1; int i; for(i = 1; i <= r; i++) { ans *= n - r + i; ans /= i; } return ans; } int main() { LL n,m,t; cin>>n>>m>>t; LL sum = 0; for (int i=4;i<=n;i++) { if (t-i<1) break; if (t-i>m) continue; sum += C(n,i)*C(m,t-i); } cout<<sum<<endl; return 0; }<file_sep>#include<stdio.h> #include<math.h> int main() { int n,i; int m; int root,number,num,den,diff; scanf("%d",&n); for (i=0;i<n;i++) { scanf("%d",&m); root=(sqrt(1+(8*m))-1)/2; number=(root*(root+1))/2; if (root%2==0) { num=root; den=1; diff=m-number; if (diff==1) { num+=1; } else if (diff > 1 ){ num+=1; num=num-(diff-1); den=den+diff-1; } } else { num=1; den=root; diff=m-number; if (diff==1) { den+=1; } else if (diff > 1 ){ den+=1; num=num+diff-1; den=den-(diff-1); } } printf("TERM %d IS %d/%d\n",m,num,den); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { std::setlocale(LC_ALL, "en_US.UTF-8"); std::setlocale(LC_NUMERIC, "en_US"); double R; cin >> R; printf("A=%.4lf\n", 3.14159 * (R * R)); return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; int r, c, m , n; int idx = 0; while (t--) { cin >> r >> c >> m >> n; vector <string> grid(r); for (int i = 0; i < r; i++) { cin >> grid[i]; } vector <int> counts(26, 0); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { counts[grid[i][j] - 65] += 1; } } int maxi = -1; for (int i = 0; i < 26; i++) { maxi = max(counts[i], maxi); } int cnt = 0; for (int i = 0; i < 26; i++) { if (counts[i] == maxi) { cnt += 1; } } cout << "Case " << ++idx << ": "; cout << m * cnt * maxi + n * (r * c - cnt * maxi) << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; string t; cin>>s>>t; vector<char> arr(s.length()); vector<char> brr(t.length()); int ha[26] = {0}; int hb[26] = {0}; for (int i = 0;i < s.length();i++) { arr[i] = s[i]; ha[arr[i]-'a']++; } for (int i = 0;i < t.length();i++) { brr[i] = t[i]; hb[brr[i]-'a']++; } sort(arr.begin(), arr.end()); sort(brr.begin(), brr.end()); int possible_array = 0; if (s.length()<t.length()) { cout<<"need tree"<<endl; return 0; } if (s.length() == t.length()) { possible_array = 1; } int subset_flag = 1; for (int i = 0;i<26;i++) { if (ha[i] < hb[i]) { subset_flag = 0; break; } } if (subset_flag == 1 && possible_array == 1) { cout<<"array"<<endl; return 0; } int id = 0; int substring_flag = 0; for (int i = 0;i<t.length();i++) { while (id<s.length() && s[id]!= t[i]) id++; if (s[id] == t[i]) { substring_flag++; id++; } } if (substring_flag == t.length()) { cout<<"automaton"<<endl; return 0; } if (subset_flag== 1 ) cout<<"both"<<endl; else { cout<<"need tree"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; int temp; int lucky; int count = 0; for (int i=0;i<n;i++) { cin>>temp; lucky =0; while (temp!=0) { int x = temp%10; if (x == 4 || x == 7) lucky++; temp/=10; } if (lucky<=k) count++; } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; int t; for (int i = 0; i < n; i++) { ISTREAM>>t; vector<int> h(t); for (int j = 0; j < t; j++) { ISTREAM>>h[j]; } int high = 0; int low = 0; for (int j = 1; j < t; j++) { if (h[j] > h[j-1]) high++; else if (h[j]<h[j-1]) low++; } cout<<"Case "<<i+1<<": "<<high<<" "<<low<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Check(n+1,0); int a,b; cin>>a; for (int i=0;i<a;i++) { int temp; cin>>temp; Check[temp] = 1; } cin>>b; for (int i=0;i<b;i++) { int temp; cin>>temp; Check[temp] = 1; } int flag = 1; for (int i=1;i<n+1;i++) { if (Check[i] == 0) { flag = 0; cout<<"Oh, my keyboard!\n"; break; } } if (flag == 1) { cout<<"I become the guy.\n"; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int a,b,s; ISTREAM>>a>>b>>s; int steps = s - (abs(a)+abs(b)); if (steps >= 0 && steps%2 == 0) { cout<<"Yes"<<endl; } else { cout<<"No"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool leap(int y) { if (y % 400 == 0) return true; if (y % 100 == 0) return false; if (y % 4 == 0) return true; return false; } int days_in_month(vector <int> &days, int y, int m) { if (leap(y) && m == 1) { return 29; } else { return days[m]; } } int main() { int t; cin >> t; string s; int k; int it = 0; map <string, int> month = {{"January", 0}, {"February", 1}, {"March", 2}, {"April", 3}, {"May", 4}, {"June", 5}, {"July", 6}, {"August", 7}, {"September", 8}, {"October", 9}, {"November", 10}, {"December", 11}}; map <int, string> rev_month; for (auto i: month) { rev_month[i.second] = i.first; } vector <int> days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; while(t--) { cout<<"Case "<<++it<<": "; int y, d, m; char c; string mon; cin>>s; cin>>k; stringstream ss(s); ss>>y>>c; getline(ss,mon,'-'); m = month[mon]; ss>>d; int m_days = days_in_month(days, y, m); k -= m_days - d + 1; d = 1; m += 1; if (m == 12) { y += 1; m = 0; } while (m > 0) { m -= 1; k += days_in_month(days, y, m); } while (k > 365) { if (leap(y)) { k -= 366; } else { k -= 365; } y += 1; } while (k > days[m]) { k -= days_in_month(days, y, m); m += 1; } d += k; if (d > days_in_month(days, y, m)) { d = 1; m += 1; } if (m == 12) { y += 1; m = 0; } cout << y << "-" << rev_month[m] << "-" << (d<10?"0":"") << d << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; int n; int cnter = 0; while(t--) { cnter++; cin>>n; bool flag = true; set<int> temp; int cnt = 1; int n1 = n; while (flag) { int k = n; while (k!=0) { temp.insert(k%10); k/=10; } if (temp.size() == 10) { cout<<"Case #"<<cnter<<": "<<n<<endl; flag = false; break; } n+=n1; cnt++; if (cnt >= 100) break; } if (flag) cout<<"Case #"<<cnter<<": INSOMNIA"<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int maxi = -1; vector <long long int> Arr(n); for (int i = 0; i < n; ++i) { cin>>Arr[i]; if (Arr[i]>maxi) maxi = Arr[i]; } vector <long long int> c(maxi+2,0); for (int i=0;i<n;i++) { c[Arr[i]] +=Arr[i]; } vector <long long int> dp(maxi+2); dp[0] = 0; dp[1] = c[0]; for (int i=2;i<maxi+2;i++) { dp[i] = max(dp[i-1],dp[i-2] + c[i-1]); } cout<<dp[maxi+1]<<endl; return 0; }<file_sep>n=input() n=int(n) a=[0] temp=1 for i in range(1,101): temp*=i a.append(temp) for i in range(0,n): k=input() print a[int(k)] <file_sep>#include <bits/stdc++.h> using namespace std; int g(int n,int k) { if (n == 1) return 0; return (g(n-1,k) + k )%n; } int main() { int counter = 1; int n; cin>>n; for (int i=0;i<n;i++) { int n,k; cin>>n>>k; cout<<"Case "<<counter<<": "<<g(n,k) + 1<<endl; counter++; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,b; cin>>a>>b; printf("%.3f km/l\n",((1.0)*a)/b); return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int a,b; while (1) { ISTREAM>>a>>b; if (a == -1 && b == -1) break; if (a>b) swap(a,b); cout<<min(b - a,a - b + 100)<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; if (n == 1 && k == 1) { cout<<"a"<<endl; return 0; } if (k>n || k == 1) { cout<<"-1"<<endl; return 0; } int others = k-2; for (int i = 0;i<n - others;i++) { if (i%2 == 0) cout<<"a"; else cout<<"b"; } char c = 'c'; for (int i=0;i<others;i++) { cout<<c; c++; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int main () { string s; vector <string> res; string temp; int N, M; int X, Y; int X1, X2, Y1, Y2; char C, A; string fname; int idx; bool flag = true; stack < pair<int, int> > pushpa; pair <int, int> tp; char tc; vector <vector <int> > visited; while(flag) { getline(cin, s); ss.str(""); ss.clear(); ss.str(s); ss >> C; switch (C) { case 'X' : flag = false; break; case 'I' : ss >> M >> N; temp = ""; for (int i = 0;i < M; i++) { temp += "O"; } res.clear(); res.resize(N, temp); break; case 'C' : for (int i = 0;i < res.size();i++) { for (int j = 0;j < res[i].size();j++) { res[i][j] = 'O'; } } break; case 'L' : ss >> X >> Y >> A; res[Y-1][X-1] = A; break; case 'V' : ss >> X >> Y1 >> Y2 >> A; if (Y1 > Y2) swap(Y1, Y2); for (int i = Y1 - 1; i < Y2; i++) { res[i][X-1] = A; } break; case 'H' : ss >> X1 >> X2 >> Y >> A; if (X1 > X2) swap(X1, X2); for (int i = X1 - 1; i < X2; i++) { res[Y-1][i] = A; } break; case 'K' : ss >> X1 >> Y1 >> X2 >> Y2 >> A; if (X1 > X2) swap(X1, X2); if (Y1 > Y2) swap(Y1, Y2); for (int i = Y1-1; i< Y2;i++) { for (int j = X1 - 1; j < X2; j++) { res[i][j] = A; } } break; case 'F' : visited.clear(); visited.resize(N, vector <int> (M, 0)); ss >> X >> Y >> A; tc = res[Y-1][X-1]; pushpa.push(make_pair(X-1, Y-1)); while (!pushpa.empty()) { tp = pushpa.top(); pushpa.pop(); res[tp.second][tp.first] = A; visited[tp.second][tp.first] = 1; if (tp.second - 1 >= 0 && res[tp.second - 1][tp.first] == tc && !visited[tp.second - 1][tp.first]) { pushpa.push(make_pair(tp.first, tp.second - 1)); } if (tp.second + 1 < N && res[tp.second + 1][tp.first] == tc && !visited[tp.second + 1][tp.first]) { pushpa.push(make_pair(tp.first, tp.second + 1)); } if (tp.first - 1 >= 0 && res[tp.second][tp.first - 1] == tc && !visited[tp.second][tp.first - 1]) { pushpa.push(make_pair(tp.first - 1, tp.second)); } if (tp.first + 1 < M && res[tp.second][tp.first + 1] == tc && !visited[tp.second][tp.first + 1]) { pushpa.push(make_pair(tp.first + 1, tp.second)); } } break; case 'S' : ss >> fname; cout << fname << endl; for (int i = 0; i < res.size(); i++) { cout<<res[i]<<endl; } break; default : break; } } } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k,t; int ele; cin>>n>>k; vector< vector<int> > arr; int cnt = 0; int links = 0; for (int i = 0;i<k;i++) { cin>>t; vector<int> temp(t); for (int j = 0;j<t;j++) { cin>>temp[j]; } vector <int> t1; t1.push_back(temp[0]); for (int j=1;j<t;j++) { if (temp[j]!=temp[j-1]+1) {arr.push_back(t1);cnt++;t1.clear();t1.push_back(temp[j]);} else t1.push_back(temp[j]); } arr.push_back(t1); } for (int i = 0;i<arr.size();i++) { if (arr[i][0] == 1) cnt+=1; else cnt+=2*(arr[i].size()-1) + 1; } cout<<cnt-1<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m,c; int counter = 0; while (1) { cin>>n>>m>>c; if (n + m + c == 0) break; counter++; vector<int> arr(n+1); vector<int> aux(n+1,0); for (int i = 1; i < n+1; i++) { cin>>arr[i]; } int t,sum = 0; int max = -1; for (int i = 0; i < m; i++) { cin>>t; aux[t]^=1; if (aux[t] == 1) { sum+=arr[t]; } else { sum -= arr[t]; } if (sum > max) max = sum; } cout<<"Sequence "<<counter<<endl; if (max > c) cout<<"Fuse was blown."<<endl; else { cout<<"Fuse was not blown."<<endl; cout<<"Maximal power consumption was "<<max<<" amperes."<<endl; } cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; string s; vector <pair <int,int> > res; for (int i=0;i<n;i++) { res.clear(); cin>>s; for (int i=0;i<12;i++) { if (s[i]=='X') { res.push_back(make_pair(1,12)); break; } } for (int i=0;i<6;i+=1) { if (s[i]=='X' && s[i+6]== 'X') { res.push_back(make_pair(2,6)); break; } } for (int i=0;i<4;i+=1) { if (s[i]=='X' && s[i+4]== 'X' && s[i+8]=='X') { res.push_back(make_pair(3,4)); break; } } for (int i=0;i<3;i+=1) { if (s[i]=='X' && s[i+3]== 'X' && s[i+6]=='X' && s[i+9]=='X') { res.push_back(make_pair(4,3)); break; } } for (int i=0;i<2;i+=1) { if (s[i]=='X' && s[i+2]== 'X' && s[i+4]=='X' && s[i+6]=='X' && s[i+8] =='X' && s[i+10]=='X') { res.push_back(make_pair(6,2)); break; } } int flag = 0; for (int i=0;i<12;i+=1) { if (s[i]!='X' ) { flag =1; break; } } if (flag == 0) res.push_back(make_pair(12,1)); cout<<res.size()<<" "; for (int i = 0; i<res.size();i++) { cout<<res[i].first<<"x"<<res[i].second<<" "; } cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif long long int temp; ISTREAM>>temp; while(temp!=0) { if (abs(temp)%2 == 1) temp++; long long int sum = 0; for (long long int i = temp;i<= temp+8;i+=2) { sum += i; } cout<<sum<<endl; ISTREAM>>temp; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int Arr[5][5]; for (int i=0;i<5;i++) { for (int j=0;j<5;j++) { Arr[i][j] = 0; } } int temp; for (int i=1;i<=3;i++) { for (int j=1;j<=3;j++) { cin>>temp; if (temp%2 == 1) { Arr[i][j] ^= 1; Arr[i-1][j] ^= 1; Arr[i][j-1] ^= 1; Arr[i+1][j] ^= 1; Arr[i][j+1] ^= 1; } } } for (int i=1;i<=3;i++) { for (int j=1;j<=3;j++) { cout<<1 - Arr[i][j]; } cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int t; for (int i = 0; i < s.length(); i++) { t = s[i] - 48; if (t%8 == 0) { cout<<"YES"<<endl; cout<<t<<endl; return 0; } } for (int i = 0; i < s.length()-1; i++) { t = s[i] - 48; for (int j = i+1; j < s.length(); j++) { int temp = t*10 + s[j]- 48; if (temp%8 == 0) { cout<<"YES"<<endl; cout<<temp<<endl; return 0; } } } for (int i = 0; i < (int)(s.length() - 2); i++) { t = s[i] - 48; for (int j = i+1; j < s.length()-1; j++) { int temp = t*10 + s[j]- 48; for (int k = j+1;k<s.length();k++) { int temp2 = temp*10 + s[k] - 48; if (temp2%8 == 0) { cout<<"YES"<<endl; cout<<temp2<<endl; return 0; } } } } cout<<"NO"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int value (string s) { if (s[0] <= '9' && s[0] >= '2') { return s[0] - '0' - 1; } else if (s[0] == 'T') { return 9; } else if (s[0] == 'J') { return 10; } else if (s[0] == 'Q') { return 11; } else if (s[0] == 'K') { return 12; } else if (s[0] == 'A') { return 0; } else { return -1; } } int main() { string s; cin >> s; while (s != "#") { vector <string> card(52); vector <vector <pair<string,bool> > > clock(13,vector<pair<string,bool> >()); card[0] = s; clock[0].push_back(make_pair(card[0],false)); for (int i = 1; i < 52; i++) { cin >> card[i]; } reverse(card.begin(), card.end()); for (int i = 0;i<52;i++) { clock[i%13].push_back(make_pair(card[i],false)); } pair <string,bool> start = clock[12].back(); clock[12].pop_back(); int cnt = 0; while (!start.second) { cnt += 1; int pos = value(start.first); if (clock[pos].back().second == true) { break; } start.second = true; clock[pos].insert(clock[pos].begin(), start); start = clock[pos].back(); clock[pos].pop_back(); } cout<<((cnt<10)?"0":"")<<cnt<<","<<start.first<<endl; cin >> s; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int flag =0; for (int i=0;i<s.length();i++) { if (flag == 0 && s[i] == 'h') flag++; else if (flag == 1 && s[i] == 'e') flag++; else if (flag == 2 && s[i] == 'l') flag++; else if (flag == 3 && s[i] == 'l') flag++; else if (flag == 4 && s[i] == 'o') flag++; } if (flag == 5 ) cout<<"YES\n"; else cout<<"NO\n"; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #define SIZE 700 #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif class Bignum{ int no[SIZE]; public: Bignum operator *(Bignum& x){ // overload the * operator /* 34 x 46 ------- 204 // these values are stored in the 136 // two dimensional array mat[][]; ------- 1564 // this the value stored in "Bignum ret" */ Bignum ret; int carry=0; int mat[2*SIZE+1][2*SIZE]={0}; for(int i=SIZE-1;i>=0;i--){ for(int j=SIZE-1;j>=0;j--){ carry += no[i]*x.no[j]; if(carry < 10){ mat[i][j-(SIZE-1-i)]=carry; carry=0; } else{ mat[i][j-(SIZE-1-i)]=carry%10; carry=carry/10; } } } for(int i=1;i<SIZE+1;i++){ for(int j=SIZE-1;j>=0;j--){ carry += mat[i][j]+mat[i-1][j]; if(carry < 10){ mat[i][j]=carry; carry=0; } else{ mat[i][j]=carry%10; carry=carry/10; } } } for(int i=0;i<SIZE;i++) ret.no[i]=mat[SIZE][i]; return ret; } Bignum (){ for(int i=0;i<SIZE;i++) no[i]=0; } Bignum (string _no){ for(int i=0;i<SIZE;i++) no[i]=0; int index=SIZE-1; for(int i=_no.length()-1;i>=0;i--,index--){ no[index]=_no[i]-'0'; } } void print(){ int start=0; for(int i=0;i<SIZE;i++) if(no[i]!=0){ start=i; break; // find the first non zero digit. store the index in start. } for(int i=start;i<SIZE;i++) // print the number starting from start till the end of array. cout<<no[i]; cout<<endl; return; } bool operator >(Bignum &b ) { int start1=0; for(int i=0;i<SIZE;i++) { if(no[i]!=0){ start1=i; break; } } int start2 = 0; for(int i=0;i<SIZE;i++) { if(b.no[i]!=0){ start2=i; break; } } if (start1 > start2) { return false; } else if (start1 <start2) { return true; } while (1) { if (no[start1] == b.no[start2]) continue; else if (no[start1] > b.no[start2]) return true; else return false; } return 0; } }; int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif vector<int> v; int t; while(ISTREAM>>t) { while (t!= -999999) { v.push_back(t); ISTREAM>>t; } Bignum max("-9999999"); for (unsigned int i = 0;i<v.size();i++) { cout<<v[i]<<" "; Bignum p("1"); for (unsigned int j = i; j<v.size();j++) { string temp = ""; int te = v[j]; while (te!=0) { temp += te+48; } string n1=""; for (int k = temp.length()-1; k >= 0; k--) { n1+=temp[k]; } Bignum n2(n1); p=p*n2; if ( p > max) { max = p; } } } cout<<endl; v.clear(); max.print(); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; string t; cin>>s>>t; int count = 0; for (int i=0;i<t.length();i++) { if (s[count] == t[i]) { count++; } } cout<<count+1<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int lcm (int a,int b) { a = a/__gcd(a,b); return a*b; } int main() { int x,y,a,b; cin>>x>>y>>a>>b; int l = lcm(x,y); int t = (l*(b/l) - l*((a/l) + (int)(a%l != 0)))/l; cout<<max(0,t+1)<<endl; return 0; }<file_sep>#/usr/bin/python from math import * n=600851475143 def factors(n): for i in range(2,int(sqrt(n))): if n%i==0: yield i while n%i==0: n/=i for i in factors(n): i=i print i <file_sep>#include<bits/stdc++.h> using namespace std; vector<string> &split(const string &s, char delim, vector<string> &elems) { stringstream ss(s); string item; while (getline(ss, item, delim)) { elems.push_back(item); } return elems; } vector<string> split(const string &s, char delim) { vector<string> elems; split(s, delim, elems); return elems; } int main() { int n; cin>>n; vector <string> A; string cmd; string path; for (int i = 0;i<n;i++) { cin>>cmd; if (cmd == "pwd") { cout<<"/"; for (int j=0 ; j<A.size(); j++) { cout<<A[j]<<"/"; } cout<<endl; } else if (cmd == "cd") { cin>>path; vector <string> tokens = split(path,'/'); if (tokens[0].empty()) { A.erase(A.begin(),A.end()); } for (int j=0;j<tokens.size();j++) { if (tokens[j] == ".." && A.size() > 0 ) { A.pop_back(); } else if (!tokens[j].empty()){ A.push_back(tokens[j]); } } } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { string s; cin >> s; map <string, set<string> > dic; while (s != "XXXXXX") { string t = s; sort(t.begin(), t.end()); dic[t].insert(s); cin >> s; } cin >> s; while(s != "XXXXXX") { string t = s; sort(t.begin(), t.end()); if (dic.find(t) == dic.end()) { cout<<"NOT A VALID WORD"<<endl; } else { for (auto i:dic[t]) { cout << i << endl; } } cout << "******" << endl; cin >> s; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif string s; int white = 0; int black = 0; for (int i = 0;i<8;i++) { cin>>s; for (int j = 0; j < s.length(); j++) { if (s[j] == 'p') black+=1; else if (s[j] == 'P') white+=1; else if (s[j] == 'n') black+=3; else if (s[j] == 'N') white+=3; else if (s[j] == 'b') black+=3; else if (s[j] == 'B') white+=3; else if (s[j] == 'r') black+=5; else if (s[j] == 'R') white+=5; else if (s[j] == 'q') black+=9; else if (s[j] == 'Q') white+=9; } } if (black > white) cout<<"Black"<<endl; else if (black == white) cout<<"Draw"<<endl; else cout<<"White"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int m; cin>>m; vector <int> Arr(m); int total = 0; for (int i=0;i<m;i++) { cin>>Arr[i]; total += Arr[i]; } int l,r; cin>>l>>r; int sum = 0; for (int i= 0;i<m;i++) { sum+= Arr[i]; if (sum>=l && sum <=r && (total - sum) >= l && (total - sum) <= r) { cout<<i+2<<endl; return 0; } } cout<<0<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); vector <int> res; for (int i=0;i<n;i++) { cin>>Arr[i]; if (Arr[i] == 1) { res.push_back(i); } } if (res.size() == 0) { cout<<0<<endl; return 0; } int count = 1; for (int i=1;i<res.size(); i++) { if (res[i] == res[i-1] + 1) { count++; } else { count+=2; } } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int a,b; ISTREAM>>a>>b; while (a!=b) { if (a<b) cout<<"Crescente"<<endl; else cout<<"Decrescente"<<endl; ISTREAM>>a>>b; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int t; for (int i=0;i<n;i++) { cin >>t; if (360%(180-t) == 0) cout<<"YES\n"; else cout<<"NO\n"; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; vector<int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } int count = 0; int trips = 0; for (int i=0;i<n;i++) { if (count + Arr[i]>m) { trips++; count = 0; } count += Arr[i]; } if (count > 0) { trips++; } cout<<trips<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a[4]; for (int i=0;i<4;i++) { cin>>a[i]; } string s; cin>>s; long long int sum = 0; for (int i=0;i<s.length();i++) { sum+=a[(int)s[i]-49]; } cout<<sum<<endl; return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> A(n); int maxi = 0; int mini = n-1; for (int i=0; i<n ;i++) { cin>>A[i]; } for (int i=0;i<n;i++) { if (A[i]>A[maxi]) maxi = i; if (A[i]<=A[mini]) mini = i; } int res = maxi + (n-1)-mini; if (maxi > mini) res -=1; cout<<res<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; int n; int m; int a, b; string ele; cin >> t; int idx = 0; while (t--) { cin >> n; vector <vector <int> > grid(n, vector <int> (n, 0)); for (int i = 0; i < n; i++) { cin >> ele; for (int j = 0; j < n; j++) { grid[i][j] = ele[j] - 48; } } vector <int> rows(n); vector <int> cols(n); for (int i = 0; i < n; i++) { rows[i] = i; cols[i] = i; } int trans = 0; int inc = 0; cin >> m; for (int i = 0; i < m; i++) { cin >> ele; if (ele == "transpose") { trans ^= 1; } else if (ele == "row") { cin >> a >> b; if (trans) { swap(cols[a-1], cols[b-1]); } else { swap(rows[a-1], rows[b-1]); } } else if (ele == "col") { cin >> a >> b; if (trans) { swap(rows[a-1], rows[b-1]); } else { swap(cols[a-1], cols[b-1]); } } else if (ele == "inc") { inc += 1; } else if (ele == "dec") { inc -= 1; } } cout << "Case #" << ++idx << endl; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (trans) { cout << (10 + grid[rows[j]][cols[i]] + inc) % 10; } else { cout << (10 + grid[rows[i]][cols[j]] + inc) % 10; } } cout << endl; } cout << endl; } return 0; } <file_sep># Why did you write this then? What technique is this? while (1): try: a,b = input().split() b = int(b) a = list(a) flag = False if a[0] == '0': flag = True k = (len(a) - a.index('.') - 1)*b a.remove('.') a = ''.join(a) i1 = int(a) res = str(pow(i1,b)) if flag == True: print('.' + (k - len(res))*'0' + res) else: int_part = res[0:-k] dec_part = res[-k:] cnt = 0 temp = -1 while dec_part[temp] == '0': cnt += 1 temp-=1 print (res[0:-k] + "." + str(dec_part)[:len(dec_part)-cnt]) except: break <file_sep>#include <bits/stdc++.h> using namespace std; int main () { string s; cin>>s; vector <int> Arr(s.length(),0); for (int i=1;i<s.length();i++) { Arr[i] = (int)(s[i] == s[i-1]) + Arr[i-1]; } int q; cin>>q; int a,b; for (int i=0;i<q;i++) { cin>>a>>b; a--;b--; cout<<Arr[b] - Arr[a]<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int main() { string inp; getline(cin, inp); while (inp != "-") { double fatc = 0; double protienc = 0; double sugarc = 0; double starchc = 0; double alcoholc = 0; while(inp != "-") { ss.str(""); ss.clear(); ss.str(inp); vector <double> vals(5, 0); vector <char> type(5); for (int i = 0;i < 5; i++) { ss >> vals[i] >> type[i]; } if (type[0] == 'C') { fatc += vals[0]; } else if (type[0] == 'g') { vals[0] *= 9; fatc += vals[0]; } if (type[1] == 'C') { protienc += vals[1]; } else if (type[1] == 'g') { vals[1] *= 4; protienc += vals[1]; } if (type[2] == 'C') { sugarc += vals[2]; } else if (type[2] == 'g') { vals[2] *= 4; sugarc += vals[2]; } if (type[3] == 'C') { starchc += vals[3]; } else if (type[3] == 'g') { vals[3] *= 4; starchc += vals[3]; } if (type[4] == 'C') { alcoholc += vals[4]; } else if (type[4] == 'g') { vals[4] *= 7; alcoholc += vals[4]; } int non_percent_vals = 0; int percent = 0; for (int i = 0;i<5;i++) { if(type[i] == '%') { percent += vals[i]; } else { non_percent_vals += vals[i]; } } double total = (double)(non_percent_vals*100)/(double)(100 - percent); for (int i = 0;i < 5; i++) { if (type[i] == '%') { vals[i] = (total * vals[i])/100; if (i == 0) { fatc += vals[i]; } else if (i == 1) { protienc += vals[i]; } else if (i == 2) { sugarc += vals[i]; } else if (i == 3) { starchc += vals[i]; } else if (i == 4) { alcoholc += vals[i]; } } } getline(cin, inp); } cout<<round((fatc*100)/(fatc + protienc + sugarc + starchc + alcoholc))<<"%"<<endl; getline(cin, inp); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int time_cal(string s) { return (s[0]-48)*60 + (s[2]-48) * 10 + (s[3]-48); } stringstream ss; int main() { int t; string inp; cin >> t; getline(cin, inp); getline(cin, inp); while (t--) { int max_team = -1; vector <vector<int> > teams_time(26, vector <int> (7, 0)); vector <vector<int> > teams_solved(26, vector <int> (7, 0)); vector <int> playing(26, 0); vector <vector<int> > leaderboard; int team_id; char problem_id; string time; char status; vector <vector <int> > data; while(getline(cin, inp)) { if (inp == "") { break; } ss.str(""); ss.clear(); ss.str(inp); ss >> team_id >> problem_id >> time >> status; int st = 0; if (status == 'Y') { st = 1; } vector <int> temp = {time_cal(time), team_id, problem_id - 65, st}; data.push_back(temp); } sort(data.begin(), data.end()); for (auto it:data) { int tm = it[0]; int tid = it[1]; int pid = it[2]; int st = it[3]; max_team = max(max_team, tid); // cout << tm << " " << tid << " " << pid << " " << st << endl; if (teams_solved[tid][pid] == 1) { continue; } playing[tid] = 1; if (st == 1) { teams_solved[tid][pid] = 1; teams_time[tid][pid] += tm; } else if (st == 0){ teams_time[tid][pid] += 20; } } for (int i = 1; i <= max_team; i++) { int solved_count = 0; int timer = 0; for (int j = 0; j < 7; j++) { if (teams_solved[i][j] == 1) { solved_count += 1; timer += teams_time[i][j]; } } vector <int> temp = {-1*solved_count, timer, i}; leaderboard.push_back(temp); } sort(leaderboard.begin(), leaderboard.end()); int idx = 1; leaderboard[0].push_back(idx); for (int i = 1; i < (int)leaderboard.size(); i++) { if (-1*leaderboard[i][0] == -1*leaderboard[i-1][0] && leaderboard[i][1] == leaderboard[i-1][1]) { leaderboard[i].push_back(idx); } else { leaderboard[i].push_back(i+1); idx = i+1; } } cout << "RANK" << " " << "TEAM" << " " << "PRO/SOLVED" << " " << "TIME" << endl; for (int i = 0; i < (int)leaderboard.size(); i++) { cout.width(4); cout << right << leaderboard[i][3] << " "; cout.width(4); cout << right << leaderboard[i][2]; if (leaderboard[i][1] > 0) { cout << " "; cout.width(4); cout << right << -1*leaderboard[i][0] << " "; cout << " "; cout.width(4); cout << right << leaderboard[i][1]; } cout << endl; } if (t > 0) { cout << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string a,b,c,d; cin>>a>>b>>c>>d; int ar[4]; ar[0] = a.length() - 2; ar[1] = b.length() - 2; ar[2] = c.length() - 2; ar[3] = d.length() - 2; char sol; int f1 = 0,f2 = 0; for (int i = 0;i<4;i++) { if (2*ar[i]<=ar[(i+1)%4] && 2*ar[i]<=ar[(i+2)%4] && 2*ar[i]<=ar[(i+3)%4]) { sol = (char)(65 + i); f1 = 1; } } for (int i = 0;i<4;i++) { if (ar[i]>=2*ar[(i+1)%4] && ar[i]>=2*ar[(i+2)%4] && ar[i]>=2*ar[(i+3)%4]) { sol = (char)(65 + i); f2 = 1; } } if (f1^f2) { cout<<sol<<endl; } else { cout<<"C"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<int> gents(n); for (int i=0;i<n;i++) { cin>>gents[i]; } sort(gents.begin(), gents.end()); int m; cin>>m; vector <int> ladies(m); for (int i=0;i<m;i++) { cin>>ladies[i]; } sort(ladies.begin(), ladies.end()); int t1 = 0, t2 = 0; int count = 0; while (t1 < n && t2 < m) { if (abs(gents[t1] - ladies[t2]) <= 1) { t1++; t2++; count++; } else if (gents[t1] < ladies[t2] - 1) { t1++; } else if (gents[t1] > ladies[t2] + 1) { t2++; } } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; while (cin>>n) { int nc = pow(2,n); vector <int> edges(nc); vector <int> neighboursum(nc); for (int i = 0;i<nc;i++) { cin>>edges[i]; } for (int i = 0;i<nc;i++) { int sum = 0; for (int j = 0;j<n;j++) { sum += edges[(i^(int)(pow(2,j)))]; } neighboursum[i] = sum; } vector <int> max_neighbour(nc); for (int i = 0;i<nc;i++) { int maxi = -1; for (int j = 0;j<n;j++) { maxi = max(maxi,neighboursum[i] + neighboursum[(i^(int)(pow(2,j)))]); } max_neighbour[i] = maxi; } int maxc = -1; for (int i = 0;i<nc;i++) { if (max_neighbour[i]>maxc) { maxc = max_neighbour[i]; } } cout<<maxc<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; cout<<"Lumberjacks:"<<endl; for (int i = 0; i < n; i++) { vector<int> Arr(10); vector<int> Brr(10); for (int j = 0; j < 10; j++) { ISTREAM>>Arr[j]; Brr[j] = Arr[j]; } int flag = 0; sort(Arr.begin(), Arr.end()); for (int j = 0; j < 10; j++) { if (Arr[j]!=Brr[j]) { flag = 1; break; } } if (flag == 0) cout<<"Ordered"<<endl; else { sort(Arr.rbegin(), Arr.rend()); flag = 0; for (int j = 0; j < 10; j++) { if (Arr[j]!=Brr[j]) { flag = 1; break; } } if (flag == 0) cout<<"Ordered"<<endl; } if (flag == 1) cout<<"Unordered"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int main() { int t; string inp; getline(cin, inp); ss.str(""); ss.clear(); ss.str(inp); ss >> t; getline(cin, inp); while (t--) { getline(cin, inp); int time = 0; int bait = 0; int fish = 0; int fish_time = 0; bool first_fish = true; int last_fish_time = 0; last_fish_time = 0; while(inp != "") { if (inp == "fish") { if (bait > 1) { if (first_fish || (fish_time >= 20 && (time - last_fish_time) >= 70)) { fish += 1; bait -= 2; last_fish_time = time; first_fish = false; fish_time = 0; } else { fish_time += 10; } } time += 10; } else if (inp == "bait") { if (bait < 6) { bait += 1; } time += 10; } else { time += 10; } getline(cin, inp); } cout << fish << endl; if (t > 0) { cout << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; while(cin >> s) { int sz = (int)s.length(); string t = s; int cnt = 0; vector <string> final = {s}; while (prev_permutation(t.begin(), t.end())) { if (cnt >= 10) { break; } cnt += 1; final.push_back(t); } cnt = 0; while(next_permutation(s.begin(), s.end())) { if (cnt >= 10) { break; } cnt += 1; final.push_back(s); } sort(final.begin(), final.end()); int maxi = -1; string res_word = ""; for (auto word:final) { int d = INT_MAX; for (int j = 1; j < sz; j++) { d = min(d, abs(word[j] - word[j-1])); } if (d > maxi) { maxi = d; res_word = word; } } cout << res_word << maxi << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,b; scanf("%d %d",&a,&b); while(a!=-1 || b!=-1) { if (a>b) std::swap(a,b); if (a==0) { printf("%d\n",b); } else if (a==1) { printf("%d\n",(b+(b%2))/2); } else if (b%(a+1)==0) { a++; printf("%d\n",b/(a)); } else printf("%d\n",b/(a+1)+1); scanf("%d %d",&a,&b); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,b; cin>>a>>b; if (a>0 && b>0) { cout<<0<<" "<<a+b<<" "<<a+b<<" "<<0<<endl; } else if (a>0 && b<0){ cout<<0<<" "<<-1*(a+abs(b))<<" "<<a+abs(b)<<" "<<0<<endl; } else if (a<0 && b>0) { cout<<-1*(abs(a)+b)<<" "<<0<<" "<<0<<" "<<abs(a) + b<<endl; } else { cout<<-1*(abs(a)+abs(b))<<" "<<0<<" "<<0<<" "<<-1*(abs(a) + abs(b))<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; while(cin>>n) { vector <int> arr(n); vector <int> check(n,0); for (int i = 0;i<n;i++) { cin>>arr[i]; } bool flag= true; for (int i = 1;i<n;i++) { int val = abs(arr[i] - arr[i-1]); if ( val > n-1) { flag = false; break; } check[val] = 1; } for (int i = 1;i<n;i++) { if (check[i] != 1) { flag = false; break; } } if (flag) cout<<"Jolly"<<endl; else cout<<"Not jolly"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<int> arr(n); vector<int> brr(n,0); for (int i = 0;i<n;i++) { cin>>arr[i]; } int count = 0; for (int i = 0; i < n; i++) { if (arr[i] > n || brr[arr[i]-1] != 0 ) { count++; } else { brr[arr[i]-1] = 1; } } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; typedef pair<string, string> myPair_type; struct mypair_comp { bool operator() (myPair_type const& lhs, myPair_type const& rhs) { return lhs.first < rhs.first; } }; string small(string s) { string res = ""; for (int i = 0; i < s.length(); i++) { if (s[i] == ' ' || (s[i] >= 97 && s[i] <= 122)) { res += s[i]; } else { res += s[i] + 32; } } return res; } string large(string s) { string res = ""; for (int i = 0; i < s.length(); i++) { if (s[i] >= 65 && s[i] <= 90) { res += s[i]; } else { res += s[i] - 32; } } return res; } string fun(int k, string t, string s) { bool flag = false; int wc = 0; for (int i = 0; i < (int)s.length(); i++) { if (s[i] == ' ') { if (flag == true) { wc += 1; } flag = false; } else { if (flag == false && wc == k) { for (int j = i; j < i + t.length(); j++) { s[j] = t[j-i]; } break; } flag = true; } } return s; } stringstream ss; int main() { set <string> ignored; string s; while (getline(cin, s)) { if (s == "::") { break; } ignored.insert(s); } vector <pair<string, string> > res; while (getline(cin, s)) { ss.str(""); ss.clear(); ss.str(s); string ele; string res_temp = ""; vector <string> temp; while (ss >> ele) { temp.push_back(small(ele)); } for (int i = 0; i < (int)temp.size(); i++) { if (ignored.find(temp[i]) == ignored.end()) { res.push_back(make_pair(temp[i], fun(i, large(temp[i]), small(s)))); } } } stable_sort(res.begin(), res.end(), mypair_comp()); for (auto i:res) { cout<< i.second << endl; } return 0; } <file_sep>#include<stdio.h> #include<string.h> long long int fun(char *a,int t) { int n=0; int k; for (k=0;k<t;k++) { n*=10; n=n+a[k]-'0'; } return n; } int main() { char a[50]; char b[50]; char c[50]; int n; int j; scanf("%d ",&n); for (j=0;j<n;j++) { scanf("%s + %s = %s ",a,b,c); int f1=0; int i; for (i=0;i<strlen(a);i++) { if (!isdigit(a[i]) ) {f1=1; break;} } for (i=0;i<strlen(b);i++) { if (f1!=0) break; if (!isdigit(b[i]) ) {f1=2; break;} } for (i=0;i<strlen(c);i++) { if (f1!=0) break; if (!isdigit(c[i]) ) {f1=3; break;} } if (f1==1) { long long int b1=fun(b,strlen(b)); long long int c1=fun(c,strlen(c)); long long int a1=c1-b1; printf("%lld + %lld = %lld\n",a1,b1,c1); } else if (f1==2) { long long int a1=fun(a,strlen(a)); long long int c1=fun(c,strlen(c)); long long int b1=c1-a1; printf("%lld + %lld = %lld\n",a1,b1,c1); } else if (f1==3) { long long int a1=fun(a,strlen(a)); long long int b1=fun(b,strlen(b)); long long int c1=b1+a1; printf("%lld + %lld = %lld\n",a1,b1,c1); } else { long long int a1=fun(a,strlen(a)); long long int b1=fun(b,strlen(b)); long long int c1=fun(c,strlen(c)); printf("%lld + %lld = %lld\n",a1,b1,c1); } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; bool check(int n) { if (n<0) n*= -1; while (n != 0) { if (n%10 == 8) return true; n/=10; } return false; } int main() { int n; cin>>n; int t = n; n+=1; while (!check(n)) { n++; } cout<<n - t<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int a,b,c; while(scanf("%d %d %d",&a,&b,&c)!=EOF) { if (a != b && a!= c) { cout<<"A"<<endl; } else if (b != a && b!= c) { cout<<"B"<<endl; } else if (c != a && c!=b) { cout<<"C"<<endl; } else { cout<<"*"<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool same(vector <string> a, vector <string> b) { for (int i = 1; i<a.size(); i++) { if (!(a[i] == b[i] || a[i] == "*")) { return false; } } return true; } int main () { int t; string originator; int n; int idx = 0; while(cin >> t) { cout << "Scenario # " << ++idx << endl; map<string, vector <vector <string> > > routing; while (t--) { cin >> originator >> n; for (int i = 0; i < n; i++) { vector <string> temp(5); for (int j = 0; j < 5; j++) { cin >> temp[j]; } routing[originator].push_back(temp); } } cin >> n; for (int i = 0; i < n; i++) { vector <string> query(5); for (int j = 0; j < 5; j++) { cin >> query[j]; } string source = query[0]; string destination; map <string, bool> touched; for (auto maps:routing) { touched[maps.first] = false; } cout<<i+1; while (1) { bool found = false; if (touched[source]) { cout << " -- circular routing detected by "<< source << endl; break; } for (auto maps: routing[source]) { if (same(maps, query)) { destination = maps[0]; found = true; break; } } if (!found) { cout<<" -- unable to route at "<< source << endl; break; } if (source == destination) { cout<<" -- delivered to "<< source << endl; break; } else { touched[source] = true; source = destination; } } } cout << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int m,n; ISTREAM>>m>>n; while(m>0 && n>0) { int sum = 0; if (m>n) swap(m,n); for (int i=m;i<n+1;i++) { cout<<i<<" "; sum += i; } cout<<"Sum="<<sum<<endl; ISTREAM>>m>>n; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; class UFDS { private: int size; vector <int> parent; vector <int> rank; vector <int> enemy; public: UFDS(int n) { parent.assign(n,0); rank.assign(n, 0); enemy.assign(n, -1); for (int i = 0; i < n; i++) { parent[i] = i; } } void print_parent() { for(auto i:parent) { cout << i << " "; } cout << endl; } void print_enemy() { for(auto i:enemy) { cout << i << " "; } cout << endl; } int findset(int a) { return (parent[a] == a?a:(parent[a] = findset(parent[a]))); } int findenemy(int a) { return (parent[a] == a?enemy[a]:enemy[a] = findenemy(parent[a])); } bool is_same_set(int a, int b) { return findset(a) == findset(b); } void friend_set(int a, int b) { if (a == -1 || b == -1) { return; } int x = findset(a); int y = findset(b); if(!is_same_set(x, y)) { if (rank[x] > rank[y]) { parent[y] = x; } else { parent[x] = y; if (rank[x] == rank[y]) { rank[y]++; } } } } int make_friend(int a, int b) { int x = findset(a); int y = findset(b); int x1 = findenemy(a); int y1 = findenemy(b); // cout << x << " " << y << endl; if (findenemy(x) == y || findenemy(y) == x) { return -1; } friend_set(x, y); friend_set(x1, y1); if (x1 != -1) { enemy[findset(x)] = findset(x1); enemy[findset(x1)] = findset(x); } if (y1 != -1) { enemy[findset(y)] = findset(y1); enemy[findset(y1)] = findset(y); } return 1; } int enemy_set(int a, int b) { if (is_same_set(a, b)) { return -1; } int x = findenemy(a); int y = findenemy(b); int x1 = findset(a); int y1 = findset(b); friend_set(x, y1); friend_set(y, x1); enemy[findset(x1)] = findset(y1); enemy[findset(y1)] = findset(x1); return 1; } int is_friend(int a, int b) { return is_same_set(a, b); } int is_enemy(int a, int b) { int x = findset(a); int y = findset(b); return findenemy(x) == y || findenemy(y) == x; } }; int main() { int n; cin >> n; UFDS case1(n); int a, b, c; cin >> a >> b >> c; while(a + b + c != 0) { if (a == 1) { int r = case1.make_friend(b, c); if (r == -1) { cout << -1 << endl; } } else if (a == 2) { int r = case1.enemy_set(b, c); if (r == -1) { cout << -1 << endl; } } else if (a == 3) { if (case1.is_friend(b, c)) { cout << 1 << endl; } else { cout << 0 << endl; } } else if (a == 4) { if (case1.is_enemy(b, c)) { cout << 1 << endl; } else { cout << 0 << endl; } } cin >> a >> b >> c; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string st; int flag; flag = 0; while( getline(cin,st) ) { cout<<st; cout<<"\n"; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int count = 0; int n; cin>>n; for (int i=2;i<=n; i++ ) { int t = i; int c = 0; for (int j = 2; j <= i/2;j++) { if (t%j==0) { c++; while (t%j == 0) t/=j; } } if (c == 2) count++; } cout<<count<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; int t; int s; for (int i = 0; i < n; i++) { ISTREAM>>t; int max = -1; for (int j = 0; j < t; j++) { ISTREAM>>s; if (s>max) max = s; } cout<<"Case "<<i+1<<": "<<max<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { vector <int> Arr(20); for (int i=0;i<20;i++) { cin>>Arr[i]; } for (int i=0;i<20;i++) { cout<<"N["<<i<<"] = "<<Arr[19-i]<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; map<vector<int>, string> dates; string name; while (t--) { cin >> name; vector <int> temp(3); for (int i = 2; i >= 0; i--) { cin >> temp[i]; } dates[temp] = name; } cout << dates.rbegin()->second << endl; cout << dates.begin()->second << endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; vector<string> arr(n); for (int i = 0;i<n;i++) { cin>>arr[i]; } int counter = 0; vector<int> helper(n,0); for (int j = 0; j < m; j++) { int flag = 0; for (int i = 1; i < n; i++) { if (helper[i-1]==0 && arr[i][j] < arr[i-1][j] ) { counter++; flag = 1; break; } else if (helper[i-1] == 0 && arr[i][j] == arr[i-1][j]) { flag = 2; } } if (flag == 2) { for (int i = 1; i < n; i++) { if (arr[i][j] > arr[i-1][j]) helper[i-1] = 1; } } if (flag == 0) { break; } } cout<<counter<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { pair < <int,int>,<int> > x; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int main () { int t; int reg_id; int val; string s; getline(cin, s); ss.str(""); ss.clear(); ss.str(s); ss >> t; getline(cin, s); int n; while (t--) { vector < int> RAM; vector <int> resister(10, 0); getline(cin, s); while(s != "") { ss.str(""); ss.clear(); ss.str(s); ss >> n; RAM.push_back(n % 1000); getline(cin, s); } int it = 0; bool flag = true; int itr = 0; while (1) { int instruction = RAM[it]/100; itr += 1; bool inc_flag = true; switch (instruction) { case 0: reg_id = (RAM[it] % 100) / 10; val = RAM[it] % 10; if (resister[val] != 0){ it = resister[reg_id]; inc_flag = false; } break; case 1: if (RAM[it] == 100) { flag = false; } break; case 2: reg_id = (RAM[it] % 100) / 10; val = RAM[it] % 10; resister[reg_id] = val; break; case 3: reg_id = (RAM[it] % 100) / 10; val = RAM[it] % 10; resister[reg_id] = (resister[reg_id] + val) % 1000; break; case 4: reg_id = (RAM[it] % 100) / 10; val = RAM[it] % 10; resister[reg_id] = (resister[reg_id] * val) % 1000; break; case 5: reg_id = (RAM[it] % 100) / 10; val = RAM[it] % 10; resister[reg_id] = resister[val]; break; case 6: reg_id = (RAM[it] % 100) / 10; val = RAM[it] % 10; resister[reg_id] = (resister[reg_id] + resister[val])%1000; break; case 7: reg_id = (RAM[it] % 100) / 10; val = RAM[it] % 10; resister[reg_id] = (resister[reg_id] * resister[val])%1000; break; case 8: reg_id = (RAM[it] % 100) / 10; val = RAM[it] % 10; resister[reg_id] = RAM[resister[val]]; break; case 9: reg_id = (RAM[it] % 100) / 10; val = RAM[it] % 10; RAM[resister[val]] = resister[reg_id]; break; } if (!flag) break; if (inc_flag) { it += 1; } } cout << itr << endl; if (t > 0) { cout << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { unsigned long long n, m ,a; cin>>n>>m>>a; cout<<(n/a+(n%a==0?0:1))*(m/a+(m%a==0?0:1))<<"\n"; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n1,n2,k1,k2; cin>>n1>>n2>>k1>>k2; if (n1<=n2) { cout<<"Second"<<endl; } else { cout<<"First"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,b; cin>>a>>b; if (b - a >0) { cout<<"O JOGO DUROU "<<b-a<<" HORA(S)"<<endl; } else { cout<<"O JOGO DUROU "<<b-a+24<<" HORA(S)"<<endl; } return 0; }<file_sep>from math import factorial as f n=input() print f(n)+2**n - n <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int k; int m; while(1) { ISTREAM>>k; if (k == 0) break; ISTREAM>>m; vector<int> courses(k); for (int i = 0; i < k; i++) { ISTREAM>>courses[i]; } int c,r; int flag = 0; for (int i = 0; i < m; i++) { ISTREAM>>c>>r; int crs; int cnt = 0; for (int j = 0; j < c; j++) { ISTREAM>>crs; if (find(courses.begin(),courses.end(),crs)!=courses.end()) cnt++; } if (cnt<r) { flag = 1; } } if (flag == 0) cout<<"yes"<<endl; else cout<<"no"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,b,c; cin>>a>>b>>c; int ab = (a + b + abs(a-b))/2; int bc = (b + c + abs(b - c))/2; int ac = (ab + bc + abs(ab - bc))/2; cout<<ac<<" eh o maior"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int months; double downpayment; double loan; int t; while (1) { vector<double> arr(100,0); ISTREAM>>months>>downpayment>>loan>>t; if (months < 0) { break; } double value = loan; int temp; double r; int it = 0; for (int i=0;i<t;i++) { ISTREAM>>temp>>r; for (int j = it+1;j<temp;j++) { arr[j] = arr[j-1]; } arr[temp] = r; it = temp; } for (int j = temp+1;j<100;j++) { arr[j] = arr[j-1]; } int cnt = 1; double instalment = loan/months; value = (value+downpayment)*(1 - arr[0]); while (value<=loan) { value = value*(1 - arr[cnt]); cnt++; loan -= instalment; } cnt--; if (cnt == 1) cout<<cnt<<" month"<<endl; else cout<<cnt<<" months"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; #define endl '\n' stringstream ss; int main () { // std::ios::sync_with_stdio(false); int t, n; string inp; getline(cin, inp); ss.str(""); ss.clear(); ss.str(inp); ss >> t; getline(cin, inp); vector <string> names; vector < vector <int > > ballot; vector <int> deleted; while (t--) { getline(cin, inp); ss.str(""); ss.clear(); ss.str(inp); ss >> n; names.clear(); names.resize(n); for (int i = 0; i< n;i++) { getline(cin, names[i]); } getline(cin, inp); ballot.clear(); deleted.clear(); deleted.resize(n+1, 0); while (inp != "") { ss.str(""); ss.clear(); ss.str(inp); vector <int> temp(n); for (int i = 0; i < n; i++) { ss >> temp[i]; } reverse(temp.begin(), temp.end()); ballot.push_back(temp); getline(cin, inp); } vector <int> maxs; vector < pair< int, int> >cnt1; while(1) { map <int, int> cnt; for (int i = 0; i < (int)ballot.size(); i++) { if(!ballot[i].empty()) { cnt[ballot[i].back()] += 1; } } cnt1.clear(); for (auto i: cnt) { cnt1.push_back(make_pair(i.second,i.first)); } if(cnt1.size() == 0) { break; } sort(cnt1.begin(), cnt1.end()); maxs.clear(); auto temp2 = *cnt1.rbegin(); int maxi = temp2.first; auto temp1 = *cnt1.begin(); int mini = temp1.first; for (int i = 1;i<=n;i++) { if (cnt[i] == 0) deleted[i] = 1; } for (auto ii:cnt1) { if (ii.first == mini) { deleted[ii.second] = 1; } if (ii.first == maxi) { maxs.push_back(ii.second); } } if (maxi > (int)(ballot.size()/2)) break; for (int i = 0; i< (int)ballot.size();i++) { while (!ballot[i].empty() && deleted[ballot[i].back()]) { ballot[i].pop_back(); } } } for (auto i:maxs) { cout<<names[i-1]<<endl; } if (t > 0) cout<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int i=0; int flag =0; int n = s.length(); while(i<n) { if (i<n-2 && s[i] == 'W' && s[i+1] == 'U' && s[i+2]=='B') { i=i+3; if (flag == 1) { cout<<" "; flag = 0; } continue; } cout<<s[i]; flag = 1; i++; } cout<<endl; return 0; }<file_sep>#!/usr/bin global a a=[0]*51 def f(m,n): solutions=1 if (n>m): return solutions if a[m]!=0: return a[m] for startpos in range(0,m-n+1): # solutions+=1 solutions += f(m-startpos - n,n) a[m]=solutions return solutions t1=f(50,4)-1 a=[0]*51 t2=f(50,3)-1 a=[0]*51 t3=f(50,2)-1 print t1+t2+t3 <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; double pa,pb; double ga,gb; for (int i=0;i<n;i++) { cin>>pa>>pb; cin>>ga>>gb; int t=0; while(pa<=pb) { t++; pa += pa*(ga/100); pa = floor(pa); pb += pb*(gb/100); pb = floor(pb); if (t == 102) { break; } } /* long long int t = (log(pa) - log(pb))/(log(1 + gb/100) - log(1 + ga/100)); t = (long long int)(t) +1; */ if (t>100) { cout<<"Mais de 1 seculo."<<endl; } else { cout<<t<<" anos."<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool move_possible(string a, string b) { if (a[0] == b[0] || a[1] == b[1]) { return true; } else { return false; } } int main() { cin.sync_with_stdio(0);cin.tie(0); string card; while (1) { vector <vector<string> > deck(52); cin >> card; if (card == "#") { break; } deck[0].push_back(card); for (int i = 1; i < 52; i++) { cin >> card; deck[i].push_back(card); } bool flag = true; while (flag) { flag = false; for (int i = 0; i < (int)deck.size(); i++) { if (i > 2 && move_possible(deck[i].back(), deck[i - 3].back())) { flag = true; deck[i - 3].push_back(deck[i].back()); deck[i].pop_back(); if (deck[i].empty()) { deck.erase(deck.begin() + i); } break; } else if (i > 0 && move_possible(deck[i].back(), deck[i - 1].back())) { flag = true; deck[i - 1].push_back(deck[i].back()); deck[i].pop_back(); if (deck[i].empty()) { deck.erase(deck.begin() + i); } break; } } } vector <int> result; for (int i = 0; i < 52; i++) { if (!deck[i].empty()) { result.push_back((int)deck[i].size()); } } if (result.size() == 1) { cout << (int)result.size() << " pile remaining:"; } else { cout << (int)result.size() << " piles remaining:"; } for (auto i: result) { cout <<" " << i; } cout << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif string s; char s1; int n; int t; scanf("%d",&n); for (int i = 0; i < n; i++) { scanf("%d",&t); scanf("%c",&s1); int pos = 0; vector<int> cmd; for (int j = 0; j < t; j++) { getline(cin,s); if (s == "LEFT") { pos -= 1; cmd.push_back(-1); } else if (s == "RIGHT") { pos +=1; cmd.push_back(1); } else { int ind = 0; for (unsigned int k = 8;k<s.length();k++) { ind *= 10; ind += s[k] - 48; } pos += cmd[ind - 1]; cmd.push_back(cmd[ind-1]); } } cout<<pos<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; long long int summation(long long int n) { return (n*(n+1))/2; } long long int fast_exp(long long int base,long long int exp) { long long res = 1; while(exp > 0) { if(exp % 2 == 1) res = (res * base); base = (base * base); exp /= 2; } return res; } long long int polynomial(vector<long long int> &poly, long long int n) { long long int sum = 0; for (long long int i = 0;i < poly.size();i++) { sum += poly[i]*fast_exp(n,i); } return sum; } int main () { int C; cin>>C; while(C--) { int degree; cin>>degree; vector <long long int> poly(degree + 1); for (int i = 0;i< degree + 1;i++) { cin>>poly[i]; } long long int D; cin>>D; long long int K,k; cin>>k; K = k/D; bool flag = false; if (k%D == 0) flag = true; //cout<<K<<endl; long long int mid = 1; long long int left = 0; long long int right = 1500; while (left < right) { mid = (left + right)/2; if (D*summation(mid) > k) { right = mid - 1; } else if (D*summation(mid) <= k){ left = mid + 1; } } if (mid <= 3) mid = 1; else mid -= 2; while (D*summation(mid) < k) mid += 1; cout<<polynomial(poly, mid)<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { std::setlocale(LC_ALL, "en_US.UTF-8"); std::setlocale(LC_NUMERIC, "en_US"); float money; cin>>money; float tax; cout<<fixed<<setprecision(2); if (money>4500) { tax = (money - 4500)*(28.0/100.0) + 270 + 80; } else if (money>3000) { tax = (money - 3000)*(18.0/100.0) + 80; } else if (money>2000) { tax = (money - 2000)*(8.0/100.0); } else { tax = 0.00; } cout<<"R$ "<<tax<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; long long int my_pow(long long int base, long long int exp) { long long int res = 1; for (int i = 0; i < exp; i++) { res *= base; } return res; } int main() { int t; int n, k; cin >> t; while(t--) { cin >> n >> k; vector <int> arr(32); vector <int> lol = {0, 1, 1, 0}; int res = 0; for (int i = 0; i < 32; i++) { arr[i] = lol[(k % my_pow(2, i + 2))/my_pow(2, i)]; } for (int i = 31; i >= 0; i--) { res *= 2; if (arr[i] == 1) { res += 1; } } cout << res << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; queue <int> q; int step = -1; q.push(n); queue <int> q1; vector<int> visited(100000,0); visited[n] = 1; while (1) { step++; while (!q.empty()) { n = q.front(); q.pop(); if (n == m) break; if (n==0) continue; if (!visited[n-1]) { visited[n-1]=1; q1.push(n-1); } if (n<m && !visited[2*n]) { visited[2*n]=1; q1.push(2*n); } } q.swap(q1); if (n==m) break; } cout<<step<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,q; int temp; cin>>n>>q; int cas = 1; while(n+q!=0) { cout<<"CASE# "<<cas<<":"<<endl; vector <int > Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } sort(Arr.begin(), Arr.end()); for (int i=0;i<q;i++) { cin>>temp; //cout<<Arr.size()<<endl; vector <int>::iterator t = find(Arr.begin(), Arr.end(),temp); if (t == Arr.end()) cout<<temp<<" not found"<<endl; else cout<<temp<<" found at "<<distance(Arr.begin(),t)+1<<endl; } Arr.clear(); cin>>n>>q; cas++; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin>>n>>m; int temp; vector <int> Arr(n,0); for (int i=0;i<m;i++) { cin>>temp; for (int j=temp-1;j<n;j++) { if (Arr[j] == 0) { Arr[j] = temp; } } } for (int i=0;i<n;i++) { cout<<Arr[i]<<" "; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int aux[10][10]; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { aux[i][j] = 0; } } int n = s.length(); for (int i = 0; i < n; i++) { int t = s[i]-48; for (int j = 0; j < t; j++) { aux[j][i] = 1; } } vector<int> res; for (int i = 0; i < 9; i++) { int t = 0; for (int j = 0; j < n; j++) { t = t*10 + aux[i][j]; } if (t>0) res.push_back(t); } cout<<res.size()<<endl; for (auto i:res) cout<<i<<" "; cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(7); for (int i=0;i<7;i++) { cin>>Arr[i]; } int sum = 0; int i = 0; while(n>0) { n-= Arr[i]; i++; i%=7; } if (i==0) i=7; cout<<i<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { float Arr[12][12]; int row; cin>>row; char flag; cin>>flag; float sum = 0; cout<<fixed<<setprecision(1); for (int i=0;i<12;i++) { for (int j=0;j<12;j++) { cin>>Arr[i][j]; if (i == row) sum+= Arr[i][j]; } } if (flag == 'S') cout<<sum<<endl; else cout<<sum/12<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; cin>>n; int ele; while (n!=0) { map <set<int> , int> dic; for (int i = 0;i<n;i++) { set<int> temp; for (int j = 0;j<5;j++) { cin>>ele; temp.insert(ele); } if (dic.find(temp) != dic.end()) { dic[temp] += 1; } else { dic[temp] = 1; } } int maxi = -1; int cnt = 0; for (auto i:dic) { if (i.second > maxi) { maxi = i.second; cnt = 1; } else if (i.second == maxi) { cnt++; } } cout<<cnt*maxi<<endl; cin>>n; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); int mini = INT_MAX; for (int i=0;i<n;i++) { cin>>Arr[i]; if (Arr[i]<mini) mini = Arr[i]; } int flag = 0; while(flag == 0) { flag = 1; for (int i=0;i<n;i++) { if (Arr[i]> mini) { Arr[i]%= mini; if (Arr[i] == 0) Arr[i] += mini; if (Arr[i]<mini) mini = Arr[i]; flag = 0; } } } cout <<mini*n<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; vector <int> arr(n); int sum = 0; for ( int i = 0;i<n;i++) { cin>>arr[i]; sum += arr[i]; } cout<<abs(sum)/k + (int)(sum%k != 0)<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; cin>>n; vector< pair<int,int> > arr(n); int neg = 0; int pos = 0; int neg_sum = 0; int pos_sum = 0; for (int i = 0; i < n; i++) { cin>>arr[i].first>>arr[i].second; if (arr[i].first < 0) { neg++; neg_sum += arr[i].second; } else if (arr[i].first > 0 ) { pos++; pos_sum += arr[i].second; } } sort(arr.begin(), arr.end()); if (neg == pos) { cout<<neg_sum + pos_sum<<endl; } else if (neg < pos) { for (int i = neg; i < 2*neg + 1; i++) { neg_sum += arr[i].second; } cout<<neg_sum<<endl; } else if (neg > pos) { for (int i = neg-1; i >= neg -pos -1; i--) { pos_sum += arr[i].second; } cout<<pos_sum<<endl; } return 0; } <file_sep>cnt = 1 for _ in range(input()): st = list(raw_input()) res = "" for i in st: if len(res) == 0 or i < res[0]: res += str(i) elif i >= res[0]: res = str(i) + res print "Case #" + str(cnt) +": " +res cnt+=1 <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; int ele; while (t--) { vector <vector <int> > wall; for(int i = 0; i < 5; i++) { vector <int> temp(2*i + 1, 0); for (int j = 0; j < i+1; j++) { cin >> temp[2*j]; } vector <int> temp1(2*i + 2, 0); wall.push_back(temp); if (i < 4) { wall.push_back(temp1); } } wall[8][1] = (wall[6][0] - (wall[8][0] + wall[8][2]))/2; wall[8][3] = (wall[6][2] - (wall[8][2] + wall[8][4]))/2; wall[8][5] = (wall[6][4] - (wall[8][4] + wall[8][6]))/2; wall[8][7] = (wall[6][6] - (wall[8][6] + wall[8][8]))/2; for (int i = 8; i > 0; i--) { for (int j = 0; j < i; j++) { wall[i-1][j] = wall[i][j] + wall[i][j+1]; } } for (int i = 0; i < (int)wall.size(); i++) { for (int j = 0; j < (int)wall[i].size(); j++) { cout << wall[i][j]; if (j < (int)wall[i].size() - 1) { cout << " "; } } cout << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); int index = -1; int mini = 999999999; for (int i=0;i<n;i++) { cin>>Arr[i]; if (Arr[i]<mini) { mini = Arr[i]; index = i; } } cout<<"Menor valor: "<<mini<<endl; cout<<"Posicao: "<<index<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; bool chkone(string s) { int count = 0; if (s[0] == 'o') { count++; } if (s[1] == 'n') { count++; } if (s[2] == 'e') { count++; } if (count >= 2) return true; return false; } int main () { int t; cin>>t; string s; while (t--) { cin>>s; if (s.length() == 5) { cout<<3<<endl; } else if (chkone(s)) { cout<<1<<endl; } else { cout<<2<<endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int time_calc(int mon, int day, int hour, int min) { return mon*31*24*60 + day*24*60 + hour*60 + min; } int main() { int t; string number_plate; string time_stamp; int month; int day; int hour; int minute; string behavior; int kilometer; string inp; getline(cin, inp); ss.str(""); ss.clear(); ss.str(inp); ss >> t; getline(cin, inp); while(t--) { getline(cin, inp); ss.str(""); ss.clear(); ss.str(inp); vector <int> tariff_24(24); for (int i = 0; i < 24; i++) { ss >> tariff_24[i]; } map <string, map <int, vector<int> > > event; while (getline(cin, inp)) { if (inp == "") { break; } ss.str(""); ss.clear(); ss.str(inp); ss >> number_plate >> time_stamp >> behavior >> kilometer; month = (time_stamp[0] - 48) * 10 + (time_stamp[1] - 48); day = (time_stamp[3] - 48) * 10 + (time_stamp[4] - 48); hour = (time_stamp[6] - 48) * 10 + (time_stamp[7] - 48); minute = (time_stamp[9] - 48) * 10 + (time_stamp[10] - 48); if (behavior[1] == 'n' || behavior[1] == 'N') { event[number_plate][time_calc(month, day, hour, minute)] = {0, kilometer, tariff_24[hour]}; } else if (behavior[1] == 'x' || behavior[1] == 'X') { event[number_plate][time_calc(month, day, hour, minute)] = {1, kilometer}; } } for (auto i:event) { double cost = 0.0; int current_rate = 0; int kimi1 = 0; int kimi2 = 0; bool begin_flag = false; bool control_flag = false; for (auto j:i.second) { if (j.second[0] == 0) { begin_flag = true; current_rate = j.second[2]; kimi1 = j.second[1]; } else if (j.second[0] == 1 && begin_flag == true) { begin_flag = false; kimi2 = j.second[1]; cost += 1 + (double)(abs(kimi1 - kimi2)*current_rate)/100.0; control_flag = true; } } if (control_flag) { cout << i.first << " $" << fixed << setprecision(2) << 2 + cost << endl; } } if (t > 0) { cout << endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s[8]; for (int i=0;i<8;i++) { cin>>s[i]; } int W = 0, B = 0; for (int i=0;i<8;i++) { int flag; if (s[i][0] == 'B') { flag = 1; } else { flag = 0; } for (int j=1;j<8;j++) { if ((j+flag)%2 == 0 && s[i][j] != 'W') { cout<<"NO"<<endl; return 0; } else if ((j+flag)%2 == 1 && s[i][j] != 'B') { cout<<"NO"<<endl; return 0; } } } cout<<"YES"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int counter(string s) { int ele; ss.str(""); ss.clear(); ss.str(s); int res = 0; while (ss >> ele) { res += 1; } return res; } int main () { ios::sync_with_stdio(false); int t; cin >> t; while (t--) { int n; cin >> n; string inp; getline(cin, inp); vector <int> res; int mini = INT_MAX; for(int i = 0; i < n; i++) { getline(cin, inp); // cout << inp << endl; int cnt = counter(inp); if (cnt < mini) { res = {i + 1}; mini = cnt; } else if (cnt == mini) { res.push_back(i + 1); } } for (int i = 0; i < (int)res.size(); i++) { cout << res[i]; if (i < res.size() - 1) { cout << " "; } } cout << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int n; do { scanf("%lld",&n); if (n==-1) break; long double t=sqrt(1+4*(n-1)/3); if (t-(long long int)t==0 && (long long int)t%2==1) printf("Y\n"); else printf("N\n"); }while(1); return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int findset(int i, vector <int> pa) { if (i == pa[i]) return i; else return pa[i] = findset(pa[i],pa); } int union_f(int i, int j, vector <int > pa) { return findset(i,pa) == findset(j,pa); } int main() { int t; cin>>t; string s; while(t--) { int n; cin>>n; getchar(); vector <int> parent(n+1); vector <int> rank(n+1); for (int i=1;i<=n;i++) { parent[i] = i; rank[i] = 0; } string c; int a,b; int win = 0; int lose = 0; getline(cin,s); while(s.length() != 0) { stringstream ss(s); ss>>c>>a>>b; if (c == "c") { int t1 = findset(a,parent); int t2 = findset(b,parent); if (union_f(t1,t2,parent)) { getline(cin,s); continue; } if (rank[t1] > rank[t2]) { parent[t2] = t1; } else { parent[t1] = t2; if (rank[t1] == rank[t2]){ rank[t2]++; } } } else if (c == "q") { if (union_f(a,b,parent)) { win++; } else { lose++; } } getline(cin,s); } cout<<win<<","<<lose<<endl; if (t>0) cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int > Arr(n); int sum = 0; int temp; for (int i=0;i<n;i++) { cin>>temp; sum+=temp; Arr[i] = sum; } int q; cin>>q; for (int i=0;i<q;i++) { cin>>temp; vector<int>::iterator res; res = lower_bound (Arr.begin(), Arr.end(), temp); cout<<1+res - Arr.begin()<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int temp; int odd_count = 0,even_count = 0; for (int i = 0; i < n; ++i) { cin>>temp; if (temp%2==0) { even_count++; } else { odd_count++; } } if (odd_count%2 == 1) { cout<<odd_count<<endl; } else { cout<<even_count<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int h,d; double u,f; while (1) { ISTREAM>>h>>u>>d>>f; if (h == 0) break; f = (double)u*f/100; double pos = 0; int day = 0; while (pos <= h && pos >=0) { day++; pos += u; if (pos >h) break; pos -= d; u -= f; u = max(0.0,u); } if (pos>h) { cout<<"success on day "<<day<<endl; } else if (pos<0) { cout<<"failure on day "<<day<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; if (s.length() < 11) { cout<<"NO"<<endl; return 0; } for (int i = 0; i < 11; i++) { string t = ""; for (int j = 0; j < i; j++) { t += s[j]; } for (int j = s.length()- (10- i); j < s.length(); j++) { t+=s[j]; } if (t == "CODEFORCES") { cout<<"YES"<<endl; return 0; } } cout<<"NO"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { double a; cin>>a; int b = (int)a; cout<<"NOTAS:"<<endl; if (b>=100) { cout<<b/100<<" nota(s) de R$ 100.00"<<endl; b%=100; } else cout<<"0 nota(s) de R$ 100.00"<<endl; if (b>=50) { cout<<b/50<<" nota(s) de R$ 50.00"<<endl; b%=50; } else cout<<"0 nota(s) de R$ 50.00"<<endl; if (b>=20) { cout<<b/20<<" nota(s) de R$ 20.00"<<endl; b%=20; } else cout<<"0 nota(s) de R$ 20.00"<<endl; if (b>=10) { cout<<b/10<<" nota(s) de R$ 10.00"<<endl; b%=10; } else cout<<"0 nota(s) de R$ 10.00"<<endl; if (b>=5) { cout<<b/5<<" nota(s) de R$ 5.00"<<endl; b%=5; } else cout<<"0 nota(s) de R$ 5.00"<<endl; if (b>=2) { cout<<b/2<<" nota(s) de R$ 2.00"<<endl; b%=2; } else cout<<"0 nota(s) de R$ 2.00"<<endl; cout<<"MOEDAS:"<<endl; if (b>=1) { cout<<b/1<<" moeda(s) de R$ 1.00"<<endl; b%=1; } else cout<<"0 moeda(s) de R$ 1.00"<<endl; b = (a*100 - (int)a*100); if (b>=50) { cout<<b/50<<" moeda(s) de R$ 0.50"<<endl; b%=50; } else cout<<"0 moeda(s) de R$ 0.50"<<endl; if (b>=25) { cout<<b/25<<" moeda(s) de R$ 0.25"<<endl; b%=25; } else cout<<"0 moeda(s) de R$ 0.25"<<endl; if (b>=10) { cout<<b/10<<" moeda(s) de R$ 0.10"<<endl; b%=10; } else cout<<"0 moeda(s) de R$ 0.10"<<endl; if (b>=5) { cout<<b/5<<" moeda(s) de R$ 0.05"<<endl; b%=5; } else cout<<"0 moeda(s) de R$ 0.05"<<endl; if (b>=1) { cout<<b<<" moeda(s) de R$ 0.01"<<endl; b%=1; } else cout<<"0 moeda(s) de R$ 0.01"<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; double find_average(multiset <int> arr) { double sum = 0; for (auto i: arr) { sum += (double)i; } return sum/(double)arr.size(); } double find_average(vector <double> arr) { return (double)accumulate(arr.begin(), arr.end(),0)/(double)arr.size(); } double find_sd(vector <double> arr) { double mean = find_average(arr); double sum = 0; for (int i = 0; i < arr.size(); i++) { sum += (mean - arr[i])*(mean - arr[i]); } return sqrt(sum/(double)arr.size()); } int main() { int t; int n, c; double class_mean; double standard_deviation; int delta; cout << "MAKING THE GRADE OUTPUT" << endl; cin>>t; while(t--) { cin>>n>>c; int ele; vector <multiset<int> > scores(n); vector <int> bonus(n); vector <int> absent(n); vector <double> average(n); vector <int> grade(n); for (int i = 0; i < n; i++) { for(int j = 0;j < c;j++) { cin >> ele; scores[i].insert(ele); } cin >> bonus[i]; cin >> absent[i]; } if (c > 2) { for (int i = 0;i<n;i++) { scores[i].erase(scores[i].begin()); } } for (int i = 0;i < n; i++) { average[i] = find_average(scores[i]); } class_mean = find_average(average); standard_deviation = find_sd(average); for (int i = 0;i < n; i++) { average[i] += (bonus[i]/2)*3; } for (int i = 0;i < n;i++) { if (average[i] >= class_mean + standard_deviation) { grade[i] = 4; } else if (average[i] >= class_mean) { grade[i] = 3; } else if (average[i] >= class_mean - standard_deviation) { grade[i] = 2; } else if (average[i] < class_mean - standard_deviation) { grade[i] = 1; } } for (int i = 0; i < n; i++) { if (absent[i] == 0) { grade[i] = min(4, grade[i] + 1); } else { int delta = absent[i]/4; grade[i] = max(0, grade[i] - delta); } } cout << fixed <<setprecision(1)<<(double)accumulate(grade.begin(), grade.end(), 0)/(double)n<<endl; } cout << "END OF OUTPUT" << endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int w, h, n; int x1, y1, x2, y2; while (cin >> w >> h >> n) { if (w + h + n == 0) { break; } vector <vector <int> > board(h, vector <int> (w, 0)); for (int i = 0; i < n; i++) { cin >> x1 >> y1 >> x2 >> y2; for (int ii = min(y1, y2); ii <= max(y1, y2); ii++) { for (int jj = min(x1, x2); jj <= max(x1, x2); jj++) { board[ii-1][jj-1] = 1; } } } int white = 0; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (board[i][j] == 0) { white += 1; } } } if (white == 0) { cout << "There is no empty spots." << endl; } else if (white == 1) { cout << "There is one empty spot." << endl; } else { cout << "There are " << white << " empty spots." << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; class UFDS { private: int size; vector <int> parent; vector <int> rank; public: UFDS(int n) { size = n; parent.assign(n, 0); rank.assign(n, 0); for (int i = 0; i < size; i++) { parent[i] = i; } } int findset(int a) { return (a == parent[a]?a:(parent[a] = findset(parent[a]))); } bool is_same_set(int a, int b) { return findset(a) == findset(b); } void union_set(int a, int b) { int x = findset(a); int y = findset(b); if (!is_same_set(x, y)) { if (rank[x] > rank[y]) { parent[y] = x; } else { parent[x] = y; if (rank[x] == rank[y]) { rank[y]++; } } } } int count_sars() { int counter = 0; for (int i = 0; i < size; i++) { if (findset(i) == findset(0)) { counter += 1; } } return counter; } }; int main() { int n, m; while(cin >> n >> m) { if (n + m == 0) { break; } UFDS case1(n); int k; int ele1, ele2; for (int i = 0; i < m; i++) { cin >> k; cin >> ele1; for (int j = 0; j < k - 1; j++) { cin >> ele2; case1.union_set(ele1, ele2); } } cout << case1.count_sars() << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; string findset(string i, unordered_map <string, string> &pa) { if (i == pa[i]) return i; else { return pa[i] = findset(pa[i],pa); } } bool union_f(string i, string j, unordered_map <string, string> &pa) { return findset(i,pa) == findset(j,pa); } int main () { int t; int n; cin>>t; while (t--) { cin>>n; unordered_map <string,string> parent; unordered_map <string,int> rank; unordered_map <string,int> cnt; string a,b; while (n--) { cin>>a>>b; if (parent.find(a) == parent.end()) { parent[a] = a; rank[a] = 0; cnt[a] = 1; } if (parent.find(b) == parent.end()) { parent[b] = b; rank[b] = 0; cnt[b] = 1; } string t1 = findset(a,parent); string t2 = findset(b,parent); if (union_f(t1,t2,parent)) { printf("%d\n",cnt[findset(a,parent)]); continue; } if (rank[t1] > rank[t2]) { parent[t2] = t1; cnt[t1] += cnt[t2]; } else { parent[t1] = t2; if (rank[t1] == rank[t2]){ rank[t2]++; } cnt[t2] += cnt[t1]; } printf("%d\n",cnt[findset(a,parent)]); } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; float a,b; cout<<fixed<<setprecision(1); for (int i = 0; i < n; i++) { ISTREAM>>a>>b; if (b == 0) cout<<"divisao impossivel"<<endl; else cout<<a/b<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; vector <int> readints(string s) { vector <int> res; int ele; ss.str(""); ss.clear(); ss.str(s); while (ss >> ele) { res.push_back(ele); } return res; } int main (){ string inp; int idx = 0; while(getline(cin, inp)) { vector <int> vals; vals = readints(inp); int sz = (int)vals.size(); vector <pair<int, int> > val_pair(sz); for (int i = 0; i< sz; i++) { val_pair[i] = make_pair(0, vals[i] - 5); } bool first_iter = true; while (1) { bool increment = false; int max_begin = -1; int min_end = INT_MAX; for (int i = 0; i < sz; i++) { max_begin = max(max_begin, val_pair[i].first); min_end = min(min_end, val_pair[i].second); } for (int i = 0; i < sz; i++) { if (val_pair[i].second <= max_begin) { val_pair[i].first += 2*vals[i]; val_pair[i].second = val_pair[i].first + vals[i] - 5; increment = true; } } if (increment) { first_iter = false; continue; } if (!increment && first_iter && max_begin == 0) { first_iter = false; for (int i = 0; i< sz; i++) { if (val_pair[i].second == min_end) { val_pair[i].first += 2*vals[i]; val_pair[i].second = val_pair[i].first + vals[i] - 5; } } continue; } int mini = INT_MAX; int maxi = -1; for (int i = 0; i < sz; i++) { maxi = max(maxi, val_pair[i].first); mini = min(mini, val_pair[i].second); } if (maxi > 3600) { cout<<"Set "<<++idx<<" is unable to synch after one hour."<<endl; break; } if (mini - maxi > 0) { cout << "Set " << ++idx << " synchs again at " << maxi / 60 << " minute(s) and " << maxi % 60 << " second(s) after all turning green." << endl; break; } } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; int t1,t2; while(t--) { int a, b, c; cin>>a>>b>>c; vector <int> jumps(100,0); vector <int> arr(a,1); for (int i = 0;i<b;i++) { cin>>t1>>t2; jumps[t1] = t2; } int cnt = 0; vector<int> moves(c); for (int i = 0;i<c;i++) { cin>>moves[i]; } for (int i = 0;i<c;i++) { t1 = moves[i]; arr[cnt] += t1; if (jumps[arr[cnt]]!=0) arr[cnt] = jumps[arr[cnt]]; if (arr[cnt] >= 100) { arr[cnt] = 100; break; } cnt += 1; if (cnt == a) cnt = 0; } for (int i = 0;i<a;i++) { cout<<"Position of player "<<i+1<<" is "<<arr[i]<<"."<<endl; } } return 0; }<file_sep>/* Just a little bit optimised O(n^2) will work. I know this code is wrong but O(n), still AC and still same runtime :P */ #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; int idx = 0; while (t--) { int n; cin >> n; vector <int> gas(n); vector <int> dist(n); vector <int> diff(n); for (int i = 0; i < n; i++) { cin >> gas[i]; } for (int i = 0; i < n; i++) { cin >> dist[i]; } for (int i = 0; i < n; i++) { diff[i] = gas[i] - dist[i]; } int sum = 0; for (int i = n-1; i >= 0; i--) { sum += diff[i]; } cout<<"Case "<<++idx<<": "; if (sum < 0) { cout << "Not possible" << endl; continue; } int pos = 0; for (int i = 0; i < n;i++) { if (diff[i] > 0) { pos = i; break; } } int endi = (pos - 1 + n) % n; int pos2 = pos; vector <int> new_diff(n); while (pos != endi) { new_diff[pos] = diff[pos]; pos += 1; pos %= n; } vector <pair<int, int>> sec; sec.push_back(make_pair(diff[0], 0)); sum = 0; pos = pos2; while (pos != n) { if (sum < 0 && diff[pos] > 0) { sec.push_back(make_pair(sum, pos2)); sum = diff[pos]; pos2 = pos; } else { sum += diff[pos]; } pos += 1; } cout << "Possible from station " << pos2 + 1 << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; vector <int> vals; while(getline(cin,s)) { int i1 = 0; int i2 = 0; string inp = ""; for (int i = 0;i < s.length();i++) { if (s[i] != ' ') { i1 = i; break; } } for (int i = s.length() - 1; i >= 0; i--) { if (s[i] != ' ') { i2 = i; break; } } for (int i = i1;i <= i2;i++) { if (i < s.length()) { inp += s[i]; } } vals.clear(); for (int i = 0;i < inp.length(); i++) { if (inp[i] >= 48 && inp[i] <= 57) { vals.push_back(inp[i] - 48); } else if (inp[i] == 'X' || inp[i] == 'x') { vals.push_back(10); } else if (inp[i] == '-') { continue; } else { vals.push_back(-1); } } if (vals.size() != 10) { cout<<inp<<" is incorrect."<<endl; continue; } bool flag = true; for (int i = 0;i < 10; i++) { if (vals[i] == 10 && i < 9) { flag = false; } if (vals[i] < 0) { flag = false; } } if (!flag) { cout<<inp<<" is incorrect."<<endl; continue; } vector <int> s1(10); vector <int> s2(10); int sum1 = 0; for (int i = 0;i < 10; i++) { sum1 += vals[i]; s1[i] = sum1; } sum1 = 0; for (int i = 0;i < 10; i++) { sum1 += s1[i]; s2[i] = sum1; } if(s2[9] % 11 != 0) { cout<<inp<<" is incorrect."<<endl; } else { cout<<inp<<" is correct."<<endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { double a,b,c; cin>>a>>b>>c; double d = b*b - 4*a*c; if (d<0) { cout<<"Impossivel calcular"<<endl; return 0; } double r2 = -b + sqrt(d); double r1 = -b - sqrt(d); if (r1 != 0 && r2 != 0) { printf("R1 = %.5lf\n",(2*c)/r1); printf("R2 = %.5lf\n",(2*c)/r2); return 0; } printf("Impossivel calcular\n"); return 0; }<file_sep>#include "bits/stdc++.h" using namespace std; int main () { string card; deque<string> p[2]; deque<string> table; while (1) { p[0].clear(); p[1].clear(); table.clear(); cin>>card; if (card[0] == '#') break; p[0].push_back(card); for (int i = 0;i <51;i++) { cin>>card; if (i%2==0) p[1].push_back(card); else p[0].push_back(card); } int counter = 1; int chance = 0; int table_flag = 0; int count = 0; while (1) { if (chance == 0 && p[0].empty()) { cout<<"1"; if (p[1].size()<10) cout<<" "; else if (p[1].size()<100) cout<<" "; cout<<p[1].size()<<endl; break; } else if (chance ==1 && p[1].empty()) { cout<<"2"; if(p[0].size()<10) cout<<" "; else if (p[0].size()<100) cout<<" "; cout<<p[0].size()<<endl; break; } counter--; string a = p[chance].back(); p[chance].pop_back(); table.push_front(a); // cout<<a<<endl; if (a[1] == 'A') { table_flag = 1; chance^=1; counter = 4; } else if (a[1] == 'K') { chance^=1; counter = 3; table_flag = 1; } else if (a[1] == 'Q') { chance^=1; counter = 2; table_flag = 1; } else if (a[1] == 'J') { chance^=1; counter = 1; table_flag = 1; } if (counter == 0) { chance^=1; counter = 1; if (table_flag == 1) { table_flag = 0; while(!table.empty()) { p[chance].push_front(table.back()); table.pop_back(); } } } } } return 0; }<file_sep>#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <cstdlib> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> using namespace std; int main (void) { int n,m; cin>>n; cin>>m; int arr[m]; for (int i=0;i<m;i++) { cin>>arr[i]; } sort(arr, arr+m); if (arr[0]==1 || arr[m-1]==n) { cout<<"NO"<<endl; return 0; } int flag=0; for (int i=0;i<m-2;i++){ if (arr[i+2]-arr[i+1] + arr[i+1]-arr[i] ==2 ) { cout<<"NO"<<endl; flag=1; break; } } if (flag==0) cout<<"YES"<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; int b,sg,sb; multiset<int>::iterator it; while(t--) { cin>>b>>sg>>sb; multiset <int> green; multiset <int> blue; int ele; for (int i = 0;i<sg;i++) { cin>>ele; green.insert(ele); } for (int i = 0;i<sb;i++) { cin>>ele; blue.insert(ele); } while (!blue.empty() && !green.empty()) { vector <int> arr; vector <int> brr; for (int i = 0;i < b;i++) { if (green.empty() || blue.empty()) { break; } int t1 = *green.rbegin(); int t2 = *blue.rbegin(); arr.push_back(t1); brr.push_back(t2); it = green.end(); it--; green.erase(it); it = blue.end(); it--; blue.erase(it); } for (int i = 0;i<arr.size();i++) { int t = min(arr[i],brr[i]); arr[i] -= t; brr[i] -= t; } for (int i = 0;i<arr.size();i++) { if (arr[i] != 0) { green.insert(arr[i]); } if (brr[i] != 0) { blue.insert(brr[i]); } } } if (green.empty() && blue.empty()) { cout<<"green and blue died"<<endl; } else if (blue.empty()) { cout<<"green wins"<<endl; vector <int> temp; for (auto i:green) { temp.push_back(i); } for (int i = temp.size() - 1; i >= 0;i--) { cout<<temp[i]<<endl; } } else if (green.empty()) { cout<<"blue wins"<<endl; vector <int> temp; for (auto i:blue) { temp.push_back(i); } for (int i = temp.size() - 1; i >= 0;i--) { cout<<temp[i]<<endl; } } if (t > 0) { cout<<endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int green(vector <int> &arr, int bin) { return arr[3*bin + 0] + arr[3*bin + 2]; } int brown(vector <int> &arr, int bin) { return arr[3*bin + 1] + arr[3*bin + 2]; } int clear(vector <int> &arr, int bin) { return arr[3*bin + 0] + arr[3*bin + 1]; } int main () { vector <int> arr(9); while (cin>>arr[0]) { for (int i = 1;i<9;i++) { cin>>arr[i]; } int mini = INT_MAX; string out; int t; t = brown(arr,0) + clear(arr,1) + green(arr,2); if (t < mini) { mini = t; out = "BCG"; } t = brown(arr,0) + green(arr,1) + clear(arr,2); if (t < mini) { mini = t; out = "BGC"; } t = clear(arr,0) + brown(arr,1) + green(arr,2); if (t < mini) { mini = t; out = "CBG"; } t = clear(arr,0) + green(arr,1) + brown(arr,2); if (t < mini) { mini = t; out = "CGB"; } t = green(arr,0) + brown(arr,1) + clear(arr,2); if (t < mini) { mini = t; out = "GBC"; } t = green(arr,0) + clear(arr,1) + brown(arr,2); if (t < mini) { mini = t; out = "GCB"; } cout<<out<<" "<<mini<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; string capital(string s) { string res = ""; for (auto i:s) { res += toupper(i); } return res; } int main() { int t; cin >> t; int m, n, b; string binder; while(t--) { getline(cin, binder); getline(cin, binder); cin >> m >> n >> b; unordered_map <string, int> prices; string item; int cost; set <pair<int, string> > result; for (int i = 0; i < m; i++) { cin >> item >> cost; prices[item] = cost; } for (int i = 0; i < n; i++) { string recipe; getline(cin, recipe); getline(cin, recipe); int no_of_ingredients; cin >> no_of_ingredients; int counts; int net_cost = 0; for (int j = 0; j < no_of_ingredients; j++) { cin >> item >> counts; net_cost += (prices[item] * counts); } if (net_cost <= b) { result.insert(make_pair(net_cost, recipe)); } } cout << capital(binder) << endl; for (auto i:result) { cout << i.second << endl; } if (result.empty()) { cout << "Too expensive!" << endl; } cout << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int m,n; cin>>m>>n; int matrix[m][n]; int new_matrix[m][n]; int matrix2[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { new_matrix[i][j] = 1; } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { matrix2[i][j] = 0; } } for (int i = 0;i<m;i++) { for (int j = 0; j < n; j++) { cin>>matrix[i][j]; } } for (int i = 0;i<m;i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == 0) { for (int k = 0;k < m;k++) { new_matrix[k][j] = 0; } for (int k = 0;k < n;k++) { new_matrix[i][k] = 0; } } } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (new_matrix[i][j]== 1) { for (int k = 0;k < m;k++) { matrix2[k][j] = 1; } for (int k = 0;k < n;k++) { matrix2[i][k] = 1; } } } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] != matrix2[i][j]) { cout<<"NO"<<endl; return 0; } } } cout<<"YES"<<endl; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cout<<new_matrix[i][j]<<" "; } cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; int counter = 0; while (1) { cin>>n; if (n == 0) break; counter++; vector <int> arr(n); vector <int> hash1(10,0); for (int i = 0; i < n;i++) { cin>>arr[i]; hash1[arr[i]]++; } vector <int> brr(n); bool exit_flag = false; cout<<"Game "<<counter<<":"<<endl; while (1) { int strong = 0; vector<int> hash2(10,0); for (int i = 0; i < n; i++) { cin>>brr[i]; if (arr[i] == brr[i]) strong++; hash2[brr[i]]++; if (brr[i] == 0) { exit_flag = true; } } if (exit_flag) break; int weak = 0; for (int i = 0;i<10;i++) { weak+=min(hash2[i],hash1[i]); } cout<<" ("<<strong<<","<<weak-strong<<")"<<endl; brr.clear(); hash2.clear(); } arr.clear(); hash1.clear(); } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); int mini = INT_MAX; int mini_index = 0; for (int i=0;i<n;i++) { cin>>Arr[i]; if (Arr[i] <mini) { mini = Arr[i]; mini_index = i+1; } else if (Arr[i] == mini) { mini_index = 0; } } if (mini_index == 0) { cout<<"Still Rozdil"<<endl; } else cout<<mini_index<<endl; return 0; }<file_sep>#include<stdio.h> #include<strings.h> int main() { int n,i,j,m; scanf("%d",&n); while (n!=-1) { int a[n]; int sum=0; int avg; int ans=0; for (i=0;i<n;i++) { scanf("%d",&a[i]); sum+=a[i]; } if (sum%n!=0) { printf("-1\n"); } else { avg=sum/n; for (i=0;i<n;i++) { if (a[i]>avg) { ans+= (a[i]-avg); } } printf("%d\n",ans); } scanf("%d",&n); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int main() { int t; string s; cin >> t; getline(cin, s); multimap <string, int> finder; vector <vector <string> > records; int idx = 0; string dept; while (t--) { getline(cin, dept); while (getline(cin, s)) { if (s == "") { break; } ss.str(""); ss.clear(); ss.str(s); string c; vector <string> row = {dept}; while(getline(ss, c, ',')) { row.push_back(c); } records.push_back(row); finder.insert(make_pair(row[3], idx)); idx += 1; } } for (auto i:finder) { vector <string> temp = records[i.second]; cout << "----------------------------------------" << endl; cout << temp[1] << " " << temp[2] << " " << temp[3] << endl; cout << temp[4] << endl; cout << "Department: " << temp[0] << endl; cout << "Home Phone: " << temp[5] << endl; cout << "Work Phone: " << temp[6] << endl; cout << "Campus Box: " << temp[7] << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif long long int fact(int n) { if (n == 0 || n == 1) { return 1; } return n*fact(n-1); } int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; cin>>n; string s; ISTREAM>>s; vector <int> prod; for (int i = 0; i< s.length();i++) { int t = s[i] - 48; if (t!= 0 && t!= 1) { prod.push_back(t); } } sort(prod.begin(), prod.end()); int t; vector<int> res; while (prod.size()>0) { t = prod.back(); prod.pop_back(); if (t == 9) { res.push_back(7); res.push_back(3); res.push_back(3); res.push_back(2); } else if (t == 8) { res.push_back(7); res.push_back(2); res.push_back(2); res.push_back(2); } else if (t == 6) { res.push_back(5); res.push_back(3); } else if (t == 4) { res.push_back(2); res.push_back(2); res.push_back(3); } else { res.push_back(t); } } sort(res.rbegin(), res.rend()); for (int i = 0; i < res.size(); i++) { cout<<res[i]; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int l_o= 0, r_o = 0; int t1,t2; for (int i=0;i<n;i++) { cin>>t1>>t2; if (t1 == 1) { l_o++; } if (t2 == 1) { r_o++; } } cout<<min(l_o,n - l_o) + min(r_o, n- r_o)<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; class Date { private: int day; int month; int year; vector <int> days_in_month{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; public: Date(int d = 0, int m = 0, int y = 0) { day = d; month = m - 1; year = y; } bool is_leap() { if (this->year % 400 == 0) return true; if (this->year % 100 == 0) return false; if (this->year % 4 == 0) return true; return false; } int days_month(int m) { if (this->is_leap() && this->month == 1) { return 29; } else { return days_in_month[month]; } } Date next_day() { Date new_day; new_day.day = this->day + 1; new_day.month = this->month; new_day.year = this->year; if (new_day.day > days_month(new_day.month)) { new_day.day = 1; new_day.month += 1; } if (new_day.month == 12) { new_day.month = 0; new_day.year += 1; } return new_day; } bool is_equal(Date d) { if (this->day == d.day && this->month == d.month && this->year == d.year) { return true; } return false; } void print () { cout << day << endl; } }; int main() { int t; cin >> t; int d, m, y, bill1, bill2; while (t != 0) { cin >> d >> m >> y >> bill1; Date day1(d, m, y); t--; int cnt = 0; int sum = 0; while(t--) { Date temp = day1.next_day(); cin >> d >> m >> y >> bill2; Date day2(d, m, y); if (temp.is_equal(day2)) { cnt += 1; sum += bill2 - bill1; } day1 = day2; bill1 = bill2; } cout << cnt << " " << sum << endl; cin >> t; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; while (cin>>n) { int m; cin>>m; string s; cin>>s; map<char,int> awake; map<char,vector<char> > graph; int awake_cnt = 0; for (int i = 0;i<3;i++) { awake[s[i]] = 1; awake_cnt++; } string temp; for (int i = 0;i<m;i++) { cin>>temp; graph[temp[0]].push_back(temp[1]); graph[temp[1]].push_back(temp[0]); } int yrs = 0; while (1) { bool ex_flag = true; if (awake_cnt == n) { cout<<"WAKE UP IN, "<<yrs<<", YEARS"<<endl; break; } yrs++; vector <char> who; for (auto i: graph) { if (awake.find(i.first)!= awake.end()) { continue; } int t_cnt = 0; for (int j = 0;j<i.second.size();j++) { if (awake.find(i.second[j])!= awake.end()) { t_cnt++; } } if (t_cnt >= 3) { who.push_back(i.first); ex_flag = false; } } for (int i = 0;i<who.size();i++) { awake[who[i]] = 1; awake_cnt++; } if (ex_flag == true) { cout<<"THIS BRAIN NEVER WAKES UP"<<endl; break; } } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; int n, m; cin >> t; int ele; while(t--) { cin >> n >> m; vector <int> arr(pow(2, n), 0); for (int i = 0; i < m; i++) { cin >> ele; arr[ele - 1] = 1; } int result_res = 0; for (int i = 0; i < n; i++) { vector <int> res; for (int j = 0; j < arr.size(); j += 2) { result_res += arr[j] ^ arr[j+1]; res.push_back(arr[j] & arr[j+1]); } arr.clear(); arr = res; } cout << result_res << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int md(string d) { int n = 0; for (int i = 0;i<d.length() - 1;i++) { n = n*10 + d[i] - 48; } return n; } int main () { int t; cin>>t; cout<<t<<endl; vector <string> months = {"pop", "no", "zip", "zotz", "tzec", "xul", "yoxkin", "mol", "chen", "yax", "zac", "ceh", "mac", "kankin", "muan", "pax", "koyab", "cumhu", "uayet"}; vector <string> dates = {"imix", "ik", "akbal", "kan", "chicchan", "cimi", "manik", "lamat", "muluk", "ok", "chuen", "eb", "ben", "ix", "mem", "cib", "caban", "eznab", "canac", "ahau"}; unordered_map <string, int> dic_month; for (int i = 0;i < months.size();i++) { dic_month[months[i]] = i; } while (t--) { string a, b; int n; cin>>a>>b>>n; int days = md(a) + n*365 + dic_month[b]*20; int new_y = days/260; int new_d = days%13; string new_m = dates[days%20]; cout<<new_d + 1<<" "<<new_m<<" "<<new_y<<endl; } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; map <string, string> arr; string a,b; for (int i = 0;i<m;i++) { cin>>a>>b; if (a.length()<=b.length()) { arr[a] = a; } else { arr[a] = b; } } for (int i = 0;i<n;i++) { cin>>a; cout<<arr[a]<<" "; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; int k; cin>>s>>k; int n = s.length()/k; if (s.length()%k!=0) { cout<<"NO"<<endl; return 0; } int flag = 0; for (int i = 0;i<k;i++) { int ix = i*n; for (int j = ix; j < ix + n; j++) { if (s[j]!=s[ix+n-(j-ix)-1]) { cout<<"NO"<<endl; return 0; } } } cout<<"YES"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int cnt; int fib(int n) { cnt++; if (n == 0) { return 0; } else if (n == 1) return 1; else return fib(n-1) + fib(n-2); } int main() { int n; cin>>n; int temp; for (int i=0;i<n;i++) { cin>>temp; cnt = 0; int f = fib(temp); cout<<"fib("<<temp<<") = "<<cnt-1<<" calls = "<<f<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; bool valid (int a, int b, int m, int n) { if (a >= 0 && a < m && b >= 0 && b<n) { return true; } else { return false; } } bool check(vector <vector <int> > &grid, int a, int b, int ele, int m, int n) { if (valid(a,b, m, n) == false) { return false; } if (grid[a][b] == -1) { return false; } if (valid (a-1,b,m,n) && grid[a-1][b] == ele ) { return true; } else if (valid(a, b-1,m,n) && grid[a][b-1] == ele) { return true; } else if (valid(a+1, b,m,n) && grid[a+1][b] == ele) { return true; } else if (valid(a,b+1,m,n) && grid[a][b+1] == ele) { return true; } else { return false; } } void delelemt(vector <vector <int> > &grid, int a, int b, int ele,int m,int n) { grid[a][b] = -1; if (valid(a-1,b,m,n) && grid[a-1][b]==ele) { delelemt(grid,a-1,b,ele,m,n); } if (valid(a+1,b,m,n) && grid[a+1][b]==ele) { delelemt(grid,a+1,b,ele,m,n); } if (valid(a,b-1,m,n) && grid[a][b-1]==ele) { delelemt(grid,a,b-1,ele,m,n); } if (valid(a,b+1,m,n) && grid[a][b+1]==ele) { delelemt(grid,a,b+1,ele,m,n); } } void cleanup(vector <vector <int> > &grid, int m, int n) { vector < vector <int> > temp; for (int j = 0;j<n;j++) { vector<int> t; for (int i = 0;i<m;i++) { if (grid[i][j] != -1) { t.push_back(grid[i][j]); } } if (t.size()>0) { temp.push_back(t); } } for (int j = 0;j<temp.size();j++) { for (int i = 0;i<temp[j].size();i++) { grid[i][j] = temp[j][i]; } for (int i = temp[j].size();i<m;i++) { grid[i][j] = -1; } } for (int j = temp.size();j<n;j++) { for (int i = 0;i<m;i++) { grid[i][j] = -1; } } } int main () { int counter = 0; int m,n; cin>>m>>n; while (1) { if (m == 0 || n == 0) { break; } vector < vector <int> > grid(m,vector<int> (n,0)); for (int i = 0;i<m;i++) { for (int j = 0;j<n;j++) { cin>>grid[i][j]; } } int ma, mb; while (1) { cin>>ma>>mb; if (ma == 0 || mb == 0) { break; } ma--;mb--; if (valid(ma,mb,m,n) && check(grid,ma,mb,grid[ma][mb],m,n)) { delelemt(grid,ma,mb,grid[ma][mb],m,n); cleanup(grid,m,n); } } bool flag = false; for (int i = 0;i<m;i++) { for (int j = 0;j<n;j++) { if (grid[i][j] != -1) { flag = true; } } } counter++; cout<<"Grid "<<counter<<"."<<endl; if (flag == false) { cout<<" Game Won"<<endl; } else { for (int i = m-1;i>=0;i--) { cout<<" "; for (int j = 0;j<n;j++) { if (grid[i][j]==-1) { cout<<" "; if (j < n-1) cout<<" "; } else { cout<<grid[i][j]<<" "; } } cout<<endl; } } cin>>m>>n; if (!(m == 0 || n == 0)) { cout<<endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int a,b; ISTREAM>>a>>b; if (a>b) swap(a,b); int sum = 0; for (int i=a;i<=b;i++) { if (i%13!=0) sum+=i; } cout<<sum<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int a,b; while(scanf("%lld%lld",&a,&b)!=EOF) { cout<<(a^b)<<endl; } return 0; }<file_sep>#include<stdio.h> int main() { int i,j,n,w,b; int brr[1000]; int sum; int max; int ind; int count; scanf("%d",&n); for ( i=0;i<n;i++ ) { scanf("%d %d",&w,&b); for ( j=0;j<b;j++ ) { scanf("%d",&brr[j]); } sum = 0; count=0; while ( sum<w ) { count++; max=0; for (j=0;j<b;j++ ){ if ( brr[j]>max ) { max=brr[j]; ind=j; } } brr[ind]=0; sum+=max; if (count>b) break; } printf ("Scenario #%d:\n",i+1); if (sum>=w) printf("%d\n",count); else printf("impossible\n"); printf("\n"); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; for (int i = 0;i<t;i++) { int n,j; cin>>n>>j; int start = 10; cout<<start<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; string clear(string s) { string res = ""; int ctr = 0; for (int i = 0; i < s.length(); i++) { if (ctr == 3) { res += '-'; ctr += 1; } if (s[i] >= 48 && s[i] <= 57) { res += s[i]; ctr += 1; } else if (s[i] == 'A' || s[i] == 'B' || s[i] == 'C') { res += '2'; ctr += 1; } else if (s[i] == 'D' || s[i] == 'E' || s[i] == 'F') { res += '3'; ctr += 1; } else if (s[i] == 'G' || s[i] == 'H' || s[i] == 'I') { res += '4'; ctr += 1; } else if (s[i] == 'J' || s[i] == 'K' || s[i] == 'L') { res += '5'; ctr += 1; } else if (s[i] == 'M' || s[i] == 'N' || s[i] == 'O') { res += '6'; ctr += 1; } else if (s[i] == 'P' || s[i] == 'R' || s[i] == 'S') { res += '7'; ctr += 1; } else if (s[i] == 'T' || s[i] == 'U' || s[i] == 'V') { res += '8'; ctr += 1; } else if (s[i] == 'W' || s[i] == 'X' || s[i] == 'Y') { res += '9'; ctr += 1; } } return res; } int main() { int t; cin >> t; int n; while (t--) { cin >> n; string s; map <string, int> dic; while (n--) { cin >> s; string s1 = clear(s); dic[s1] += 1; } bool flag = true; for (auto i:dic) { if (i.second > 1) { flag = false; cout<<i.first << " " << i.second<<endl; } } if (flag) { cout << "No duplicates." << endl; } if (t > 0) { cout << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; static inline std::string &ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return s; } static inline std::string &rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } static inline std::string &trim(std::string &s) { return ltrim(rtrim(s)); } int main () { string inp; set<pair<string, string> > lib; map <string, string> dic; set <pair<string, string> > deposit; while (getline(cin, inp)) { inp = trim(inp); if (inp == "END") { break; } string title = ""; string name = ""; int pos = 1; while (inp[pos] != '"') { title += inp[pos]; pos+= 1; } pos += 5; while(pos < (int)inp.length()) { name += inp[pos]; pos += 1; } name = trim(name); title = trim(title); lib.insert(make_pair(name, title)); dic[title] = name; } // sort(lib.begin(), lib.end()); while(getline(cin, inp)) { inp = trim(inp); if (inp == "END") { break; } inp += ' '; string command = ""; string name = ""; int pos = 0; while(inp[pos] != ' ') { command += inp[pos]; pos += 1; } command = trim(command); if (command == "SHELVE") { for (auto i:deposit) { lib.insert(i); if (i == *lib.begin()) { cout << "Put \"" << i.second << "\" first" << endl; continue; } set <pair< string, string> > :: iterator it = lib.begin(); for (set<pair<string, string> >:: iterator it1 = lib.begin(); it1 != lib.end(); it1++) { if (*it1 == i) { break; } it = it1; } cout << "Put \"" << i.second << "\" after \"" << it->second << "\"" << endl; } deposit.clear(); cout<<"END"<<endl; continue; } pos += 2; while(inp[pos] != '"') { name += inp[pos]; pos += 1; } name = trim(name); if (command == "BORROW") { lib.erase(make_pair(dic[name], name)); } else if (command == "RETURN") { string auth = dic[name]; pair <string, string> cmp = make_pair(auth, name); deposit.insert(cmp); } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int t; cin>>t; string s; getline(cin,s); getline(cin,s); while (t--) { int cnt = 0; getline(cin,s); map<string,int> dic; while (s.length() != 0) { cnt+= 1; if (dic.find(s)!= dic.end()) { dic[s] += 1; } else { dic[s] = 1; } getline(cin,s); } for (auto i:dic) { cout<<i.first<<" "; printf("%.4f\n",(double)i.second*100/(double)cnt); } if (t > 0) cout<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int arr[1400007] = {0}; int main() { vector <int> primes; for (int i=2;i<1400000;i++) { if (arr[i]==1) continue; primes.push_back(i); for (int j = 2*i;j < 1400000;j+=i) { arr[j] = 1; } } int n; cin>>n; for (int i=0;i<n;i++) { cout<<primes[i]<<" "; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { string a,b; cin>>a>>b; int t1 = 0; int t2 = 0; int num1 = 0; int num2 = 0; long long int num = 0; for (int i=0;i<a.length();i++) { int t = a[i] - 48; if ( t != 0 ) { t1*=10; t1+=t; } num1*=10; num1+=t; } for (int i=0;i<b.length();i++) { int t = b[i] - 48; if ( t != 0 ) { t2*=10; t2+=t; } num2*=10; num2+=t; } num = num1 + num2; long long int t3 = 0; while (num!=0) { int t = num%10; if (t != 0) { t3*=10; t3+=t; } num/=10; } num = t3; t3 = 0; while (num!=0) { t3*=10; t3+=num%10; num/=10; } if (t1 + t2 == t3) { cout<<"YES"<<endl; } else { cout<<"NO"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; vector<int> arr(n); //weights vector<int> brr(m); //ordering for (int i = 0; i < n; i++) { cin>>arr[i]; } for (int i = 0; i < m; i++) { cin>>brr[i]; } int helper[501] = {0}; vector<int> crr; //unique ordering for (int i = 0 ;i< brr.size();i++) { if (helper[brr[i]] != 1) { crr.push_back(brr[i]); helper[brr[i]] = 1; } } int cost = 0; for (int i = 0;i<m;i++) { vector<int>::iterator it; it = crr.begin(); while (*it!=brr[i]) { cost += arr[*it-1]; it++; } crr.erase(it); crr.insert ( crr.begin() , brr[i] ); } cout<<cost<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; long long int C(int n, int r) { long long int res = 1; for (int i=n;i>r;i--) { res*=i; } for (int i = 1;i<=n-r;i++) { res/=i; } return res; } int main() { string s1; string s2; cout << fixed << setprecision(9); cin>>s1; cin>>s2; int pos1=0; for (int i=0;i<s1.length();i++) { if (s1[i] == '+') pos1++; else pos1--; } int pos2 = 0; int d = 0; for (int i=0;i<s2.length();i++) { if (s2[i] == '+') pos2++; else if (s2[i] == '-') pos2--; else d++; } int more = abs(pos1 - pos2); if (d-more<0 || (d - more )%2==1) { cout<<0.000000000<<endl; return 0; } int n = (d - more)/2 + more; cout<<C(d,n)/powl(2,d)<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int a; int b; cin>>a; cin>>b; while (b<=a) cin>>b; int cnt = 0; int sum = 0; while (sum<b) { sum+=a; a++; cnt++; } cout<<cnt<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int l = s.length(); int n; cin>>n; vector<int> v(n); for (int i = 0; i < n; i++) { cin>>v[i]; } sort(v.begin(), v.end()); vector<int> arr; arr.push_back(v[0]); int cnt = 0; for (int i = 1; i < n; i++) { if (v[i] == arr[cnt] || arr[cnt] == 0) { arr[cnt]^=v[i]; } else { arr.push_back(v[i]); cnt++; } } vector<int> brr; for (int i = arr.size()-1; i > -1; i--) { if (arr[i] == 0) continue; brr.push_back(l-arr[i]+1); } int ix = 0; int flip = 0; for (int i = 0; i < l/2; i++) { if (arr[ix] != 0 && ix < arr.size() && i == arr[ix]-1) { flip^=1; ix++; } if (flip == 0) cout<<s[i]; else cout<<s[l-i-1]; if (arr[ix] == 0) ix++; } ix = 0; for (int i = l/2; i < l; i++) { if (ix < brr.size() && i == brr[ix]) { flip^=1; ix++; } if (flip == 0) cout<<s[i]; else cout<<s[l-i-1]; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin >>n>>m; int sum=n; while (n>=m) { sum += n/m; n = n/m + n%m; } cout<<sum<<endl; return 0; } <file_sep>from __future__ import division while(1): try: a, b = map(int, raw_input().split()) print a,b, t = (43200*(86400-a))/abs(a-b) t %= 43200 h = int(t/3600) m = int(round((t%3600)/60)) if m == 60: h += 1 m = 0 h %= 12 if h == 0: h = 12 print str(h).zfill(2) + ":" + str(m).zfill(2) except: break <file_sep>#include <bits/stdc++.h> using namespace std; int len; int main() { stack <char> s1; string s; cin>>s; len=s.length(); if (s.length()%2==1) { cout<<"No\n"; return 0; } s1.push(s[0]); int flag=0; int i=1; while(i<s.length()) { if(s[i]!=s1.top() ) { s1.push(s[i]); i++; continue; } if (s[i]==s1.top()){ s1.pop(); i++; } if (s1.empty() && i<len-1) { s1.push(s[i]); i++; } } if (s1.empty()) cout<<"Yes\n"; else cout<<"No\n"; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; int temp; while(1) { ISTREAM>>n; if (n == 0) break; int mary = 0; int john = 0; for (int i = 0; i < n; i++) { ISTREAM>>temp; if (temp == 0) { mary++; } else john++; } cout<<"Mary won "<<mary<<" times and John won "<<john<<" times"<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; while (scanf("%d",&n)!=EOF) { if (n == 0) cout<<"vai ter copa!"<<endl; else cout<<"vai ter duas!"<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; vector <pair<int,int> > Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i].first>>Arr[i].second; Arr[i].second *= -1; } sort(Arr.rbegin(),Arr.rend()); cout<<count(Arr.begin(), Arr.end(), Arr[k-1])<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; long long int digisum(long long int n) { long long int sum = 0; while (n != 0) { sum += n%10; n/=10; } return sum; } long long int pow (long long int a,long long int b) { long long int temp = 1; for (int i=0;i<b;i++) { temp*= a; } return temp; } int main() { long long int a,b,c; cin>>a>>b>>c; int count = 0; vector <int> res; for (long long int i = 1;i<82;i++) { long long int temp = b*pow(i,a) + c; if (temp>999999999) continue; if (i == digisum(temp)) { count++; res.push_back(temp); } } cout<<count<<endl; if (count == 0) return 0; for (int i=0;i<res.size();i++) { cout<<res[i]<<" "; } cout<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; cin>>n; string s; getchar(); getline(cin,s); int c,p,t; char d; bool flag = true; while(n--) { vector < vector<int> > score(101,vector<int> (10,0)); vector < vector<int> > time_penalty(101,vector<int> (10,0)); vector < int > player(101,0); if (flag == true) { flag = false; } else { cout<<endl; } vector <vector <int> > input; while (1) { getline(cin,s); if (s.length() == 0) break; stringstream ss(s); ss>>c>>p>>t>>d; player[c] = 1; vector <int> tt; tt.push_back(t); tt.push_back(c); tt.push_back(p); if (d == 'I') { tt.push_back(-1); } else if (d == 'C') { tt.push_back(1); } else { tt.push_back(0); } input.push_back(tt); } sort(input.begin(), input.end()); for (int i = 0;i<input.size();i++) { // cout<<input[i][0]<<" "<<input[i][1]<<" "<<input[i][2]<<" "<<input[i][3]<<endl; if (input[i][3] == 1 && score[input[i][1]][input[i][2]]!= 1) { score[input[i][1]][input[i][2]] = 1; time_penalty[input[i][1]][input[i][2]] += input[i][0]; } else if (input[i][3] == -1 && score[input[i][1]][input[i][2]]!= 1) { time_penalty[input[i][1]][input[i][2]] += 20; } } vector <vector<int> > ans; for (int i = 0;i<101;i++) { int t_score = 0; int t_penalty = 0; for (int j = 0;j<10;j++) { if (score[i][j] == 1) { t_score+=1; t_penalty += time_penalty[i][j]; } } if(player[i] == 1) { vector <int> temp; temp.push_back((-1)*t_score); temp.push_back(t_penalty); temp.push_back(i); ans.push_back(temp); } } sort(ans.begin(), ans.end()); for (int i = 0;i<ans.size();i++) { cout<<ans[i][2]<<" "<<(-1)*ans[i][0]<<" "<<ans[i][1]<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); int chest = 0; int biceps = 0; int back = 0; for (int i=0;i<n;i++) { cin>>Arr[i]; if (i%3 == 0) chest += Arr[i]; else if (i%3 == 1) biceps += Arr[i]; else if (i%3 == 2) back += Arr[i]; } if (chest>biceps && chest>back) cout<<"chest"<<endl; else if (biceps>chest && biceps>back) cout<<"biceps"<<endl; else if (back>biceps && back>chest) cout<<"back"<<endl; return 0; }<file_sep>#include<stdio.h> int main (void) { int n; scanf("%d",&n); if (n%10==0) printf ("2\n"); else printf("1\n%d",n%10); return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int l,r; cin>>l>>r; //Stage 1 long long int temp = l + (int)(l%2!=0); if (temp+2 <= r) { cout<<temp<<" "<<temp+1<<" "<<temp+2<<endl; } else { cout<<-1<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif vector <int> cards(52); vector <int> girl(3); vector <int> boy(2); while (1) { for (int i = 0; i < 52; i++) { cards[i] = 0; } for (int i = 0; i < 3; i++) { ISTREAM>>girl[i]; if (girl[0] == 0) break; cards[girl[i]-1] = 1; } if (girl[0] == 0) break; ISTREAM>>boy[0]; ISTREAM>>boy[1]; cards[boy[0]-1] = 1; cards[boy[1]-1] = 1; sort(girl.rbegin(), girl.rend()); sort(boy.rbegin(), boy.rend()); int flag = 0; if ( boy[1] > girl[0] ) { for (int i = 0; i < 52; i++) { if (cards[i] == 0) { flag = 1; cout<<i+1<<endl; break; } } } else if (boy[0]>girl[0] ){ if ((boy[1]<girl[2]) || (boy[1]<girl[1] && boy[1]>girl[2] )) { for (int i=girl[0];i<52;i++) { if (cards[i] == 0) { flag =1; cout<<i+1<<endl; break; } } } else if (boy[1]>girl[1]) { for (int i=girl[1];i<52;i++) { if (cards[i] == 0) { flag =1; cout<<i+1<<endl; break; } } } } else if (boy[0]<girl[0] ){ if (boy[1]>girl[1]) for (int i=girl[1];i<52;i++) { if (cards[i] == 0) { flag =1; cout<<i+1<<endl; break; } } } if (flag == 0) cout<<"-1"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int g(int n) { if (n<10) return n; int t = 0; while(n!=0) { t+=n%10; n/=10; } return g(t); } int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; while (1) { ISTREAM>>n; if (n == 0) { break; } cout<<g(n)<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int t; int n, m; cin >> t; while(t--) { cin >> n >> m; vector <vector <int> > incidence_matrix(n, vector <int> (m, 0)); bool flag = true; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> incidence_matrix[i][j]; } } set <pair<int, int> > global_nodes; for (int i = 0; i < m; i++) { set <int> nodes; for (int j = 0; j < n; j++) { if (incidence_matrix[j][i] == 1) { nodes.insert(j); } } if ((int)nodes.size() != 2) { flag = false; } else { pair<int, int> temp = make_pair(*nodes.begin(), *nodes.rbegin()); if (global_nodes.find(temp) != global_nodes.end()) { flag = false; } else { global_nodes.insert(temp); } } } if (flag) { cout << "Yes" << endl; } else { cout << "No" << endl; } } return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; int main() { string s; cin>>s; for (int i=0;i<s.length(); i++) { if (s[i] == 'H' || s[i] == 'Q' || s[i] == '9' ) { cout<<"YES\n"; return 0; } } cout<<"NO\n"; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; string s; map <string,int> arr; for (int i = 0;i<n;i++) { cin>>s; arr[s]+=1; } int maxi = 0; for (auto i : arr) { if (i.second > maxi) maxi = i.second; } cout<<maxi<<endl; return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; int main() { long long int m,n; cin>>m>>n; if (m%2 == 0 || n%2 ==0) cout<<(m*n)/2; else if (m%2==1) cout<<(((m-1)*n)/2) + (n/2); else if (n%2 == 1) cout<<(((n-1)*m)/2) + (m/2); cout<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s,t; cin>>s; cin>>t; int i = s.length()-1; while (s[i] == 'z') i--; s[i]+=1; i+=1; while (i <= s.length() - 1) { s[i] = 'a'; i++; } i = s.length()-1; while (s[i] == t[i] && i>=0) { i--; } if (i == -1) { cout<<"No such string"<<endl; } else cout<<s<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int a,b; int inter= 0; int gremio = 0; int draw = 0; int flag = 1; while (flag == 1) { ISTREAM>>a>>b; if (a>b) inter++; else if (a<b) gremio++; else draw++; cout<<"Novo grenal (1-sim 2-nao)"<<endl; ISTREAM>>flag; } cout<<gremio+inter+draw<<" grenais"<<endl; cout<<"Inter:"<<inter<<endl; cout<<"Gremio:"<<gremio<<endl; cout<<"Empates:"<<draw<<endl; if (inter>gremio) cout<<"Inter venceu mais"<<endl; else if (gremio>inter) cout<<"Gremio venceu mais"<<endl; else cout<<"Nao houve vencedor"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } sort(Arr.begin(),Arr.end()); int flag = 0; int count = 0; int prev; for (int i=0;i<n;i++) { if (Arr[i] == 0 ) continue; if (flag == 0) { flag = 1; prev = Arr[i]; } else if (flag == 1 && Arr[i] == prev) { flag = 2; count++; } else if ( (flag == 1||flag ==2) && Arr[i] != prev) { flag = 1; prev = Arr[i]; } else if (flag == 2 && Arr[i] == prev) { cout<<-1<<endl; return 0; } } cout<<count<<endl; return 0; }<file_sep>#/usr/bin/python def palin(s): s=list(s) flag=0 for i in range(len(s)/2): if s[i]!=s[0-1-i]: flag=1 break if flag==0: return 1 else: return 0 for i in range(999,900,-1): for j in range(999,900,-1): if palin(str(i*j)): print i,j,i*j <file_sep>#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <cstdlib> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> using namespace std; class Time { public: string whatTime (int time); }; string Time::whatTime(int time) { string a; int hours=time/3600; time%=3600; int minutes=time/60; time%=60; int seconds=time; std::ostringstream out; out<<hours<<":"<<minutes<<":"<<seconds; a=out.str(); return a; } <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif for (int i = 1; i < 10; i+=2) { int j = 7; cout<<"I="<<i<<" J="<<j<<endl; cout<<"I="<<i<<" J="<<j-1<<endl; cout<<"I="<<i<<" J="<<j-2<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,b; cin>>a>>b; int t1,t2; int fp = 0; int sp = 0; int dr = 0; for (int i=1;i<=6;i++) { t1 = abs(i-a); t2 = abs(i-b); if (t1>t2) { sp++; } else if (t1 == t2) { dr++; } else if (t2>t1) { fp++; } } cout<<fp<<" "<<dr<<" "<<sp<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,m; cin>>a>>m; while (m%2 == 0 ) m /= 2; if (a%m == 0) { cout<<"Yes"<<endl; } else { cout<<"No"<<endl; } return 0; }<file_sep>from string import * def slug(s): s = s.strip() s = s.lower() s = s.replace(' ', '-') test = set(digits + ascii_letters) res = "" for i in s: if i in test or i == '-': res += i return res for _ in range(input()): s = raw_input().split() i = s[0] s = '-'.join(s[1:]) print i + "," + slug(s) <file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; int temp; char cr; int C = 0; int R = 0; int S = 0; for (int i = 0; i < n; i++) { ISTREAM>>temp>>cr; if (cr == 'R') { R += temp; } else if (cr == 'S') { S+=temp; } else if (cr == 'C') { C+=temp; } } cout<<"Total: "<<R+C+S<<" cobaias"<<endl; cout<<"Total de coelhos: "<<C<<endl; cout<<"Total de ratos: "<<R<<endl; cout<<"Total de sapos: "<<S<<endl; cout<<fixed<<setprecision(2); cout<<"Percentual de coelhos: "<<(C*100.0)/(R+C+S)<<" %"<<endl; cout<<"Percentual de ratos: "<<(R*100.0)/(R+C+S)<<" %"<<endl; cout<<"Percentual de sapos: "<<(S*100.0)/(R+C+S)<<" %"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; #define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif vector<float> Arr; float temp; while (Arr.size()<2) { ISTREAM>>temp; if (temp >= 0.0 && temp <= 10.0) { Arr.push_back(temp); } else { cout<<"nota invalida"<<endl; } } cout<<fixed<<setprecision(2); cout<<"media = "<<(Arr[0] + Arr[1])/2.0<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int h1,m1,m; cin>>h1>>m1; m = h1*60 + m1; int h2,m2,m3; cin>>h2>>m2; m3 = h2*60 + m2; int diff = m3 - m; if (diff <0 ){ diff += 24*60; } int h = diff/60; m = diff%60; cout<<"O JOGO DUROU "<<h<<" HORA(S) E "<<m<<" MINUTO(S)"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int temp; int cnt=0; for (int i = 0; i < 5; i++) { ISTREAM>>temp; if (temp%2==0) { cnt++; } } cout<<cnt<<" valores pares"<<endl; return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; int main () { long long int n; cin>>n; cout<<(n*n*n + 5*n)/6<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n,m; cin>>n>>m; while (n + m != 0) { vector <int> busy(1000009,0); int a,b,c; bool flag = true; for (int i1 = 0;i1<n;i1++) { cin>>a>>b; if (flag == false) { continue; } for (int i = a;i< b;i++) { if (busy[i] != 0) flag = false; else busy[i] = 1; } } for (int i1 = 0;i1<m;i1++) { cin>>a>>b>>c; if (flag == false) { continue; } int delta1 = a; int delta2 = b; for (int i = 0; ;i++) { delta1 = a + i*c; delta2 = delta1 + b - a; if (delta1 > 1000000) break; delta2 = min(delta2,1000001); for (int j = delta1;j < delta2;j++) { if (busy[j] != 0) flag = false; else busy[j] = 1; } } } if (flag == true) { cout<<"NO CONFLICT"<<endl; } else { cout<<"CONFLICT"<<endl; } cin>>n>>m; busy.clear(); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; long long int pivot = s.find('^'); long long int left = 0; long long int right = 0; for (long long int i = 0; i<pivot;i++) { if (s[i] >= 48 && s[i]<= 57) { left += (s[i]-48)*(pivot - i); } } for (long long int i = pivot; i<s.length();i++) { if (s[i] >= 48 && s[i]<= 57) { right += (s[i]-48)*(i - pivot); } } if (left == right) cout<<"balance"<<endl; else if (left < right) cout<<"right"<<endl; else cout<<"left"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { float a, b, c; cin >> a >> b >> c; printf("MEDIA = %.1f\n", (2 * a + 3 * b + 5 * c) / 10); return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; vector<int> arr(26,0); for (int i = 0; i < s.length(); i++) { arr[s[i]-'a']++; } int bad = 0; for (int i = 0;i<26;i++) { if (arr[i]%2 == 1) bad++; } if ( bad == 0 || bad%2 == 1) cout<<"First"<<endl; else cout<<"Second"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { char dir; string a = "qwertyuiopasdfghjkl;zxcvbnm,./"; string res = ""; cin>>dir; string s; cin>>s; if (dir == 'R') { for (int i=0;i<s.length();i++) { for (int j = 1;j<a.length();j++) { if (a[j] == s[i]) { res+=a[j-1]; } } } } else if (dir == 'L') { for (int i=0;i<s.length();i++) { for (int j = 0;j<a.length()-1;j++) { if (a[j] == s[i]) { res+=a[j+1]; } } } } cout<<res<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int m,s; cin>>m>>s; string matrix[101][901]; string natrix[101][901]; for (int i = 1; i <=m; i++) { matrix[i][0] = "-1"; natrix[i][0] = "-1"; } matrix[1][0] = "0"; matrix[1][1] = "1"; natrix[1][0] = "0"; natrix[1][1] = "1"; for (int i=1;i<=m;i++) { if (i>1) { matrix[i][1] = matrix[i-1][1] + "0"; natrix[i][1] = natrix[i-1][1] + "0"; } for (int j= 2 ;j<=s;j++) { if (j>9*i) { matrix[i][j] = "-1"; natrix[i][j] = "-1"; continue; } int k = i-1; matrix[i][j] = matrix[i][j-1]; while(matrix[i][j][k] == '9') { k--; } matrix[i][j][k] += 1; k = 0; natrix[i][j] = natrix[i][j-1]; while(natrix[i][j][k] == '9') { k++; } natrix[i][j][k] += 1; } } cout<<matrix[m][s]<<" "<<natrix[m][s]<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <int> Arr(n); vector <int> Brr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; Brr[i] = Arr[i]; } sort(Brr.begin(), Brr.end()); vector < pair<int,int> > res; for (int i=0;i<n;i++) { if (Arr[i]!=Brr[i]) { vector <int>::iterator it; it = find(Arr.begin() + i,Arr.end(),Brr[i]); int pos = distance(Arr.begin() ,it); swap(Arr[i],Arr[pos]); res.push_back(make_pair(i,pos)); } } cout<<res.size()<<endl; for (int i=0;i<res.size();i++) { cout<<res[i].first<<" "<<res[i].second<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; char matrix[n][n]; for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { cin>>matrix[i][j]; } } for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { if (matrix[i][j] == '#') { matrix[i][j] = '.'; if (matrix[i+1][j] == '#') { matrix[i+1][j] = '.'; } else { cout<<"NO\n"; return 0; } if (matrix[i+1][j+1] == '#') { matrix[i+1][j+1] = '.'; } else { cout<<"NO\n"; return 0; } if (matrix[i+1][j-1] == '#') { matrix[i+1][j-1] = '.'; } else { cout<<"NO\n"; return 0; } if (matrix[i+2][j] == '#') { matrix[i+2][j] = '.'; } else { cout<<"NO\n"; return 0; } } } } cout<<"YES\n"; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; multiset <long long int> arr1; multiset <long long int> arr2; vector <long long int> inp; while (cin>>n) { inp.push_back(n); } if (inp.size() >= 1) { cout<<inp[0]<<endl; } if (inp.size() >= 2) { cout<<(inp[0] + inp[1])/2<<endl; } if (inp.size() >= 3) { long long int a = inp[0]; long long int b = inp[1]; if (a > b) swap(a,b); arr1.insert(a); arr2.insert(b); int cnt = 2; for (int i = 2;i<inp.size();i++) { long long int val = inp[i]; if (val <= *arr2.begin()) { arr1.insert(val); } else if (val > *arr1.rbegin()) { arr2.insert(val); } if (arr1.size() > arr2.size()) { arr2.insert(*arr1.rbegin()); arr1.erase(*arr1.rbegin()); } if (arr2.size() > arr1.size()+1) { arr1.insert(*arr2.begin()); arr2.erase(*arr2.begin()); } cnt += 1; if (cnt %2 == 0) { cout<<(*arr1.rbegin() + *arr2.begin())/2<<endl; } else { cout<<*arr2.begin()<<endl; } } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; string s; cin>>s; vector <int> A(n); vector <int> B(n); for (int i=0;i<n;i++) { A[i] = s[i] - 48; } for (int i=n;i<2*n;i++) { B[i-n] = s[i] -48; } sort(A.begin(),A.end()); sort(B.begin(),B.end()); int g = 0; int l = 0; for (int i=0;i<n;i++) { if (A[i]>B[i]) g++; else if (A[i]<B[i]) l++; if (g*l>0) break; } if (g == n || l == n) cout<<"YES\n"; else cout<<"NO\n"; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; int temp,cnt; for (int i = 0; i < n; i++) { ISTREAM>>temp>>cnt; if(abs(temp)%2==0) temp++; int sum = 0; for (int j = temp; j < temp+2*cnt; j+=2) { sum+=j; } cout<<sum<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int matrix[101][101]; int a; void fill(int i,int j) { if (i > 0 && matrix[i-1][j]!=-1) matrix[i-1][j] += 1; if (j > 0 && matrix[i][j-1]!=-1) matrix[i][j-1] += 1; if (i < a-1 && matrix[i+1][j]!=-1) matrix[i+1][j] += 1; if (j < a-1 && matrix[i][j+1]!=-1) matrix[i][j+1] += 1; if (i > 0 && j < a-1 && matrix[i-1][j+1]!=-1) matrix[i-1][j+1] += 1; if (i < a-1 && j < a-1 && matrix[i+1][j+1]!=-1) matrix[i+1][j+1] += 1; if (i < a-1 && j > 0 && matrix[i+1][j-1]!=-1) matrix[i+1][j-1] += 1; if (i > 0 && j > 0 && matrix[i-1][j-1]!=-1) matrix[i-1][j-1] += 1; } int main() { int t; cin>>t; while(t--) { cin>>a; vector<string> click(a); for (int i = 0;i<a;i++) { for (int j = 0;j<a;j++) { matrix[i][j] = 0; } } string temp; for (int i = 0;i<a;i++) { cin>>temp; for (int j = 0;j<a;j++) { if (temp[j] == '*') matrix[i][j] = -1; } } for (int i = 0;i<a;i++) { for (int j=0;j<a;j++) { if (matrix[i][j] == -1) fill(i,j); } } bool bomb = false; for (int i = 0;i<a;i++) { cin>>click[i]; } for (int i = 0;i<a;i++) { for (int j = 0;j<a;j++) { if (click[i][j] == 'x' && matrix[i][j] == -1) bomb = true; } } for (int i = 0;i<a;i++) { for (int j = 0;j<a;j++) { if (click[i][j] == 'x' && matrix[i][j] == -1) cout<<'*'; else if (click[i][j] == 'x') cout<<matrix[i][j]; else if (bomb == true and matrix[i][j] == -1)cout<<'*'; else cout<<"."; } cout << endl; } if (t > 0) { cout << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; string clean(vector <string> &vs) { string res = ""; for (int i = 0;i< vs.size();i++) { for (int j = 0;j<vs[i].size();j++) { if (vs[i][j] > 47 && vs[i][j] < 58) { res += vs[i][j]; } } } return res; } stringstream ss; int main () { int n1, n2; int idx = 0; while (1) { string inp; getline(cin, inp); ss.str(""); ss.clear(); ss.str(inp); ss >> n1; if (n1 == 0) break; cout<<"Run #"<<++idx<<": "; vector <string> set1(n1); for (int i = 0;i < n1; i++) { getline(cin, set1[i]); } getline(cin, inp); ss.str(""); ss.clear(); ss.str(inp); ss >> n2; vector <string> set2(n2); for (int i = 0;i < n2;i++) { getline(cin, set2[i]); } bool flag = false; if (n1 == n2) { flag = true; for (int i = 0;i<n1;i++) { if (set1[i] != set2[i]) { flag = false; break; } } } if (flag) { cout<<"Accepted"<<endl; } else { string s1 = clean(set1); string s2 = clean(set2); if (s1 == s2) { cout<<"Presentation Error"<<endl; } else { cout<<"Wrong Answer"<<endl; } } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; string str(long long int a) { string r = ""; while (a != 0) { r+=a%10 + 48; a/=10; } return r; } void print(long long int a,long long int b) { string s1,s2; s1 = str(a); s2 = str(b); if (a == b) { cout<<"0"<<a<<endl; return; } int i; cout<<"0"; for (i = s1.length()-1;i>= 0;i--) { if (s1[i] == s2[i]) cout<<s1[i]; else { break; } } for (int k = i;k>= 0; k--) { cout<<s1[k]; } cout<<"-"; for (int k = i;k>=0;k--) { cout<<s2[k]; } cout<<endl; } int main () { int n; int cnt = 1; while(1) { cin>>n; if (n == 0) { break; } cout<<"Case "<<cnt++<<":"<<endl; vector <long long int> inp; long long int ele; for (int i = 0;i<n;i++) { cin>>ele; inp.push_back(ele); } int i = 0; int j; while (i < inp.size()) { for (j = i+1;j<inp.size();j++) { if (inp[j] == inp[i] + j-i) { continue; } else { break; } } print(inp[i], inp[j-1]); i = j; if (j == n) break; } cout<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; string s; map <string,int> hash; for (int i=0;i<n;i++) { cin>>s; if (hash.count(s) == 0) { hash[s] = 1; cout<<"OK"<<endl; } else { hash[s]++; cout<<s<<hash[s]-1<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; cin>>n; vector<int> v(n); vector<int> one; vector<int> two; vector<int> three; for (int i=0;i<n;i++) { cin>>v[i]; if (v[i] == 1) { one.push_back(i+1); } else if (v[i] == 2) { two.push_back(i+1); } else if (v[i]== 3) { three.push_back(i+1); } } int cnt = min (one.size(),min(two.size(),three.size())); cout<<cnt<<endl; for (int i=0;i<cnt;i++) { cout<<one[i]<<" "<<two[i]<<" "<<three[i]<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; string s; cin>>s; int flag = 1; int i,j,del; for (del = 1; del<=25;del++) { for (i = 0;i<s.length();i++) { flag = 1; for (j = 0;j<5;j++) { if (i + j*del>= s.length()) { flag = 0; break; } if (s[i + j*del] == '.') { flag = 0; break; } } if (flag == 1) { cout<<"yes"<<endl; return 0; } } } cout<<"no"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; int numMoves = n/2 + (int)(n%2!=0); int minMoves = (numMoves/m + (int)(numMoves%m != 0))*m; if (minMoves>=numMoves && minMoves <= n) { cout<<minMoves<<endl; } else { cout<<-1<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a,b,p; cin>>a; while (a) { cin>>b>>p; int x = (a*b*100)/p; cout<<(int)sqrt(x)<<endl; cin>>a; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; string s1; string s2; cin>>n>>s1>>s2; int cnt = 0; for (int i = 0;i<n;i++) { int t1 = s1[i] - 48; int t2 = s2[i] - 48; int t = abs(t1 - t2); int u = abs(10-t); cnt+=min(t,u); } cout<<cnt<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { double S = 0; for (int i = 1; i < 101; i++) { S += 1.0/i; } cout << fixed << setprecision(2); cout << S << endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int convert(string s) { int a, b; char c; ss.str(""); ss.clear(); ss.str(s); ss >> a >> c >> b; return a*60 + b; } int main () { int n; int idx = 0; while (cin >> n) { int start = 0; int endi = 0; string starting; string ending; string remaining; int s1 = 600; int e1 = 1080; int max_begin = -1; int max_delta = -1; vector <pair <int, int> > meetings(n); for (int i = 0;i < n;i++) { cin >> starting >> ending; start = convert(starting); endi = convert(ending); meetings[i] = make_pair(start, endi); // cout << start <<" " << endi<<endl; getline(cin, remaining); } sort(meetings.begin(), meetings.end()); for (int i = 0; i < n; i++) { start = meetings[i].first; endi = meetings[i].second; if (start - s1 > max_delta) { max_delta = start - s1; max_begin = s1; } s1 = endi; } if (e1 - endi > max_delta) { max_delta = e1 - endi; max_begin = endi; } int h = max_begin/60; int m = max_begin%60; cout << "Day #"<<++idx<<": the longest nap starts at " << h <<":"<<(m<10?"0":"")<< m<<" " << "and will last for "; if (max_delta/60>0) { cout<<max_delta/60<<" hours and "; } cout<<max_delta%60<<" minutes."<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; set <int> Arr; vector <int> Brr(n); for (int i=0;i<n;i++) { cin>>Brr[i]; Arr.insert(Brr[i]); } int size = Arr.size(); for (set <int> :: iterator it = Arr.begin(); it != Arr.end(); it++) { if (count(Brr.begin(), Brr.end(), *it) > n/2 + (int)(n%2 != 0 )) { cout<<"NO"<<endl; return 0; } } cout<<"YES"<<endl; return 0; }<file_sep>#include <vector> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <limits> #include <tuple> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; class PeopleCircle { public: string order(int numMales, int numFemales, int K) { char arr[numMales + numFemales]; for (int i=0;i<numMales + numFemales;i++ ){ arr[i]='M'; } int len= numMales + numFemales; arr[len]='\0'; int pos = len - 1; for (int i=0; i< numFemales; i++ ) { for (int c=0;c<K;) { pos = (pos+1)%len; if (arr[pos]=='M') c++; } arr[pos]='F'; } return string(arr); } }; <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; int max = -999999999; for (int i=0;i<n;i++) { int f,t; int temp; cin>>f>>t; if (t>k) { f = f - (t-k); } if (f>max) max = f; } cout<<max<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n,p; int cnt = 1; ISTREAM>>n>>p; while (1) { if (n == 0 && p == 0) { break; } cout<<"RFP #"<<cnt<<endl; cnt++; string s; char c; scanf("%c",&c); for (int i = 0; i < n; i++) { getline(ISTREAM,s); // cout<<s<<endl; } double amt; int item; int max_item = -1; double min_amt = INT_MAX; string res; for (int i = 0;i<p;i++) { getline(ISTREAM,s); ISTREAM>>amt>>item; if (item>max_item) { max_item = item; res = s; min_amt = amt; } else if (item == max_item && amt<min_amt) { min_amt = amt; res = s; } // cout<<s<<endl; scanf("%c",&c); for (int j = 0;j < item;j++) { getline(ISTREAM,s); // cout<<s<<endl; } } cout<<res<<endl; ISTREAM>>n>>p; if (n == 0 && p == 0) { break; } else { cout<<endl; } } return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; #define MOD 10006 struct trie_node { char c; struct trie_node *child[26]; int loose; int win; }; typedef struct trie_node tnode; tnode *make_node() { tnode *X = (tnode *)malloc(sizeof(tnode)); X->win = -1; X->loose = -1; for(int i=0 ; i< 26 ; i++) X->child[i] = NULL; return X; } tnode * insert_TRIE(tnode *root, string s) { tnode *root1 = root; for(int i=0; i< s.length() ; i++) { int val = s[i] - 'a'; if(root->child[val] == NULL) { root->child[val] = make_node(); root = root->child[val]; } else { root = root->child[val]; } } return root1; } void dfs_TRIE_win(tnode *root) { if(root->win != -1) return; int t = 0; for(int i=0 ; i< 26 ; i++) { if( root->child[i] != NULL) t=1; } if(t==0) { root->win = 0; //cout<<"here "<<endl; return; } for(int i=0 ; i< 26 ; i++) { if( root->child[i] != NULL) { dfs_TRIE_win(root->child[i]); } } for(int i=0 ; i< 26 ; i++) { if(root->child[i] != NULL) { if(root->child[i]->win == 0) { root->win = 1; return; } } } root->win = 0; return; } void dfs_TRIE_loose(tnode *root) { if(root->loose != -1) return; int t = 0; for(int i=0 ; i< 26 ; i++) { if( root->child[i] != NULL) t=1; } if(t==0) { root->loose = 1; //cout<<"here "<<endl; return; } for(int i=0 ; i< 26 ; i++) { if( root->child[i] != NULL) { dfs_TRIE_loose(root->child[i]); } } for(int i=0 ; i< 26 ; i++) { if(root->child[i] != NULL) { if(root->child[i]->loose == 0) { root->loose = 1; return; } } } root->loose = 0; return; } int main() { int n,k; cin>>n>>k; string str; tnode *root = (tnode *)malloc(sizeof(tnode)); root->win = -1; root->loose = -1; for(int i=0 ; i< n ; i++) { cin>>str; root = insert_TRIE(root,str); } dfs_TRIE_win(root); dfs_TRIE_loose(root); int Win_val = root->win; int Los_val = root->loose; cout<<Win_val<<" "<<Los_val<<endl; if( Win_val == 0) { cout<<"Second"<<endl; return 0; } if(Los_val == 0) { if(k%2 == 0) cout<<"Second"<<endl; else cout<<"First"<<endl; return 0; } if(Win_val != 0 && Los_val != 0) { cout<<"First"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main () { int n; while (cin >> n) { int maxl = -1; vector <string> words(n); for (int i = 0; i < n; i++) { cin >> words[i]; maxl = max(maxl, (int)words[i].length()); } sort(words.begin(), words.end()); int w = 1 + (60 - maxl)/(maxl + 2); int l = n / w + (int)(n % w != 0); vector < vector < string> > grid(l, vector <string> (w, "")); int cnt = 0; for (int i = 0; i < w; i++) { for (int j = 0; j < l; j++) { if (cnt == n) { break; } grid[j][i] = words[cnt++]; } } for (int i = 0; i < 60; i++) { cout << "-"; } cout << endl; for (int i = 0; i < l; i++) { for (int j = 0; j < w; j++) { cout << grid[i][j]; if (j < w - 1) { for (int k = (int)grid[i][j].length(); k < maxl + 2; k++) { cout << " "; } } else { for (int k = (int)grid[i][j].length(); k < maxl; k++) { cout << " "; } } } cout << endl; } } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; int main () { int n; cin>>n; string s; cin>>s; int count = 0; for (int i=0; i<n-1 ; i++ ) { if (s[i] == s[i+1]) { count++; } } cout<<count; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; //#define SUBLIME #if defined SUBLIME # define ISTREAM ifile #else # define ISTREAM cin #endif int main() { #if defined (SUBLIME) ifstream ifile("stdin.input"); #endif int n; ISTREAM>>n; string s; int arr[10] = {6,2,5,5,4,5,6,3,7,6}; for (int i = 0; i < n; i++) { ISTREAM>>s; int sum = 0; for (int j = 0; j < (int)s.length(); j++) { sum += arr[s[j]-48]; } cout<<sum<<" leds"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool palin(string s) { for (int i = 0;i<s.length();i++) { if (s[i] != s[s.length() - 1 - i ]) return false; } return true; } int main () { string s; while (getline(cin,s)) { set <string> chk; for (int i = 0;i<s.length();i++) { for (int j = i;j < s.length(); j++) { string temp = ""; for (int k = i; k <j+1; k++ ) { temp+=s[k]; } chk.insert(temp); } } int cnt = 0; for (auto i:chk) { if (palin(i)) { cnt++; } } cout<<"The string '"<<s<<"' contains "<<cnt<<" palindromes."<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int n,m; bool valid (int i, int j, vector<string> &grid,int idel,int jdel) { if (i + idel< 0 || i + idel >= n || j + jdel < 0 || j + jdel >= m) { return false; } else if (grid[i + idel][j + jdel] == '1') { return false; } else { return true; } } pair <int,int> direction_change(int i, int j) { if (i == 0 && j == 1) { return make_pair(-1,0); } else if (i == 1 && j == 0) { return make_pair(0,1); } else if (i == -1 && j == 0) { return make_pair(0,-1); } else if(i == 0 && j == -1) { return make_pair(1,0); } } pair<int, int> right_dir(int i, int j) { if (i == 0 && j == 1) { return make_pair(1,0); } else if (i == 1 && j == 0) { return make_pair(0,-1); } else if (i == -1 && j == 0) { return make_pair(0,1); } else if(i == 0 && j == -1) { return make_pair(-1,0); } } void trace(vector<vector<int> > &trace_m ,vector <string> &grid, int posi, int posj, int idel, int jdel) { pair <int, int> dir = right_dir(idel,jdel); trace_m[posi][posj] += 1; while (!valid (posi, posj,grid,dir.first,dir.second)) { dir = direction_change(dir.first,dir.second); } if (posi + dir.first == n-1 && posj + dir.second == 0) return; trace(trace_m,grid,posi + dir.first, posj + dir.second,dir.first,dir.second); } using namespace std; int main () { cin>>n>>m; while (n + m > 0) { vector <string> grid(n); vector <vector <int> > trace_m(n,vector<int> (m,0)); for (int i = 0;i<n;i++) { cin>>grid[i]; } for (int i = 0;i<n;i++) { for (int j = 0;j<m;j++) { if (grid[i][j] == '1') { trace_m[i][j] = 5; } } } trace(trace_m,grid,n-1,0,0,1); vector <int > cnt(5,0); for (int i = 0;i<n;i++) { for (int j = 0;j<m;j++) { if (grid[i][j] == '1') continue; if (trace_m[i][j] > 4) continue; cnt[trace_m[i][j]]+=1; } } for (int i = 0;i<5;i++) { printf("%3d",cnt[i]); } cout<<endl; cin>>n>>m; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { float a, b, c; cin>>a>>b>>c; printf("TRIANGULO: %.3f\n",0.5*a*c); printf("CIRCULO: %.3f\n",3.14159*c*c); printf("TRAPEZIO: %.3f\n",0.5*(a+b)*c); printf("QUADRADO: %.3f\n",b*b); printf("RETANGULO: %.3f\n",a*b); return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int a[5]; int sum = 0; for (int i=0;i<5;i++) { cin>>a[i]; sum+=a[i]; } if (sum!= 0 && sum%5 == 0){ cout<<sum/5<<endl; } else cout<<"-1"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { float a; cin>>a; if (a>= 0 && a<= 25.0) cout<<"Intervalo [0,25]\n"; else if (a>25 && a<= 50.0) cout<<"Intervalo (25,50]\n"; else if (a>50 && a<= 75.0) cout<<"Intervalo (50,75]\n"; else if (a>75 && a<= 100.0) cout<<"Intervalo (75,100]\n"; else cout<<"Fora de intervalo\n"; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int parity(string a) { if (a[a.length() - 1] == '+') { return 1; } else if (a[a.length() - 1] == '-') { return -1; } } string stripl(string a) { string res = ""; for (int i = 0;i<a.length()-1;i++) { res+=a[i]; } return res; } int value (string s) { if (s == "O") { return 0; } else if (s == "AB") { return 1; } else if (s == "B") { return 2; } else if (s == "A") { return 3; } } bool myfun (string s1, string s2) { string ss1 = stripl(s1); string ss2 = stripl(s2); if (ss1 == ss2) return s1 > s2; else return value(ss1) < value(ss2); } int main () { string a,b,c; int cnt = 1; while (1) { cin>>a>>b>>c; if (a == "E" && b == "N" && c == "D") { break; } cout<<"Case "<<cnt++<<": "; set <string> child[2]; int aparity; int bparity; set <string> parent; if (a != "?" && b != "?") { aparity = parity(a); bparity = parity(b); a = stripl(a); b = stripl(b); vector <string> temp; temp.push_back(a); temp.push_back(b); for (int i = 0;i<2;i++) { string a1 = temp[i]; if (a1 == "AB") { child[i].insert("A"); child[i].insert("B"); } else if (a1 == "A") { child[i].insert("A"); child[i].insert("O"); } else if (a1 == "B") { child[i].insert("B"); child[i].insert("O"); } else if (a1 == "O") { child[i].insert("O"); } } set<string> chld; vector <string> vc1; vector <string> vc2; for (auto i:child[0]) { vc1.push_back(i); } for (auto i:child[1]) { vc2.push_back(i); } for (int i = 0;i<vc1.size();i++) { for (int j = 0;j<vc2.size();j++) { string s1 = vc1[i]; string s2 = vc2[j]; if (s1 > s2) { string t = s1; s1 = s2; s2 = t; } string s = s1 + s2; if (s == "AO" || s == "AA") { if (aparity == -1 && bparity == -1) { chld.insert("A-"); } else { chld.insert("A-"); chld.insert("A+"); } } else if (s == "BO" || s== "BB") { if (aparity == -1 && bparity == -1) { chld.insert("B-"); } else { chld.insert("B-"); chld.insert("B+"); } } else if (s == "AB") { if (aparity == -1 && bparity == -1) { chld.insert("AB-"); } else { chld.insert("AB-"); chld.insert("AB+"); } } else if (s == "OO") { if (aparity == -1 && bparity == -1) { chld.insert("O-"); } else { chld.insert("O-"); chld.insert("O+"); } } } } cout<<a<<((aparity == 1)?"+ ":"- "); cout<<b<<((bparity == 1)?"+ ":"- "); vector <string> res; for (auto i:chld) { res.push_back(i); } sort(res.begin(), res.end(),myfun); if (res.size() == 1) { cout<<res[0]; } else { cout<<"{"; for (int i = 0;i<res.size();i++) { cout<<res[i]; if (i < res.size() - 1) { cout<<", "; } } cout<<"}"; } cout<<endl; } else { bool impossible = false; string imp = a=="?"?b:a; int cparity = parity(c); int impparity = parity(imp); imp = stripl(imp); c = stripl(c); if (c == "A") { if (imp == "B") { if (cparity == 1 && impparity == -1) { parent.insert("A+"); parent.insert("AB+"); } else { parent.insert("A+"); parent.insert("AB+"); parent.insert("AB-"); parent.insert("A-"); } } else if (imp == "AB" || imp == "A") { if (cparity == 1 && impparity == -1) { parent.insert("A+"); parent.insert("AB+"); parent.insert("O+"); parent.insert("B+"); } else { parent.insert("B+"); parent.insert("B-"); parent.insert("A+"); parent.insert("AB+"); parent.insert("AB-"); parent.insert("A-"); parent.insert("O+"); parent.insert("O-"); } } else if (imp == "O") { if (cparity == 1 && impparity == -1) { parent.insert("A+"); parent.insert("AB+"); } else { parent.insert("A+"); parent.insert("A-"); parent.insert("AB+"); parent.insert("AB-"); } } } else if (c == "O") { if (imp == "AB") { impossible = true; } else if (imp == "O") { if (cparity == 1 && impparity == -1) { parent.insert("B+"); parent.insert("A+"); parent.insert("O+"); } else { parent.insert("B+"); parent.insert("B-"); parent.insert("A-"); parent.insert("A+"); parent.insert("O+"); parent.insert("O-"); } } else if (imp == "A" || imp == "B") { if (cparity == 1 && impparity == -1) { parent.insert("O+"); parent.insert("A+"); parent.insert("B+"); } else { parent.insert("O+"); parent.insert("O-"); parent.insert("A+"); parent.insert("B+"); parent.insert("A-"); parent.insert("B-"); } } } else if (c == "B") { if (imp == "A") { if (cparity == 1 && impparity == -1) { parent.insert("B+"); parent.insert("AB+"); } else { parent.insert("AB+"); parent.insert("AB-"); parent.insert("B+"); parent.insert("B-"); } } else if (imp == "AB" || imp == "B" ) { if (cparity == 1 && impparity == -1) { parent.insert("B+"); parent.insert("A+"); parent.insert("AB+"); parent.insert("O+"); } else { parent.insert("A+"); parent.insert("A-"); parent.insert("AB+"); parent.insert("AB-"); parent.insert("B+"); parent.insert("B-"); parent.insert("O+"); parent.insert("O-"); } } else if (imp == "O") { if (cparity == 1 && impparity == -1) { parent.insert("B+"); parent.insert("AB+"); } else { parent.insert("B+"); parent.insert("B-"); parent.insert("AB+"); parent.insert("AB-"); } } } else if (c == "AB") { if (imp == "O") { impossible = true; } if (imp == "A") { if (cparity == 1 && impparity == -1) { parent.insert("B+"); parent.insert("AB+"); } else { parent.insert("B+"); parent.insert("B-"); parent.insert("AB-"); parent.insert("AB+"); } } else if (imp == "B") { if (cparity == 1 && impparity == -1) { parent.insert("A+"); parent.insert("AB+"); } else { parent.insert("A+"); parent.insert("A-"); parent.insert("AB-"); parent.insert("AB+"); } } else if (imp == "AB") { if (cparity == 1 && impparity == -1) { parent.insert("B+"); parent.insert("A+"); parent.insert("AB+"); } else { parent.insert("A+"); parent.insert("A-"); parent.insert("B+"); parent.insert("B-"); parent.insert("AB-"); parent.insert("AB+"); } } } if (a != "?") cout<<a<<" "; if (impossible == true) { cout<<"IMPOSSIBLE "; if (a == "?") cout<<b<<" "; cout<<c<<((cparity==1)?"+":"-"); cout<<endl; continue; } vector <string> res; for (auto i:parent) { res.push_back(i); } sort(res.begin(), res.end(),myfun); if (res.size() == 1) cout<<res[0]<<" "; else { cout<<"{"; for (int i = 0;i<res.size();i++) { cout<<res[i]; if (i < res.size()-1) cout<<", "; } cout<<"} "; } if (a == "?") cout<<b<<" "; cout<<c<<((cparity==1)?"+":"-"); cout<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; int i; int u,v; scanf("%d %d",&n,&m); if (m!=n-1) { printf("NO\n"); return 0; } int check[10001]={0}; for (int i=0;i<m;i++) { scanf("%d %d",&u,&v); if(check[u]&&check[v]) { printf("NO\n"); return 0; } else { check[u]=1; check[v]=1; } } printf("YES\n"); return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m,ele; cin>>n>>m; vector<int> boys(n,0); vector<int> girls(m,0); int b,g; cin>>b; for (int i = 0; i < b; i++) { cin>>ele; boys[ele] = 1; } cin>>g; for (int i = 0; i < g; i++) { cin>>ele; girls[ele] = 1; } for (int i = 0;i<2*m*n;i++) { boys[i%n]|=girls[i%m]; girls[i%m]|=boys[i%n]; } for (int i = 0; i < n; i++) { if (boys[i]==0) { cout<<"No"<<endl; return 0; } } for (int i = 0; i < m; i++) { if (girls[i]==0) { cout<<"No"<<endl; return 0; } } cout<<"Yes"<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int find_set(int i, vector<int> &p) { return (p[i] == i) ? i: (p[i] = find_set(p[i], p)); } bool is_same_set(int i, int j, vector<int> &p) { return find_set(i, p) == find_set(j, p); } void union_join(int i, int j, vector <int> &r, vector<int> &p) { if (!is_same_set(i, j, p)) { int x = find_set(i, p); int y = find_set(j, p); if (r[x] > r[y]) { p[y] = x; } else { p[x] = y; if (r[x] == r[y]) { r[y]++; } } } } int main() { int idx = 0; while (1) { int n, m; int a, b; cin >> n >> m; if (n + m == 0) { break; } cout << "Case " << ++idx << ": "; vector <int> p(n,0); vector <int> r(n,0); for (int i = 0; i < n; i++) { p[i] = i; } for (int i = 0; i < m; i++) { cin >> a >> b; union_join(a-1, b-1, r, p); } int count = 0; for (int i = 0; i < n; i++) { if (p[i] == i) { count += 1; } } cout << count << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int m, n; cin >> m >> n; string s; int val; unordered_map <string, int> dic; while (m--) { cin >> s >> val; dic[s] = val; } while (n--) { cin >> s; val = 0; while (s != ".") { val += dic[s]; cin >> s; } cout << val << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int T; int N, M, S; int n, m; cin >> T; bool flag; while (T--) { cin >> N >> M >> S; vector <string> major_grid(N); for (int i = 0;i < N; i++) { cin >> major_grid[i]; } while (S--) { cin >> n >> m; vector <string> small_grid(n); int min_i = INT_MAX; int max_i = -1; vector <int> non_empty; for (int i = 0; i < n; i++) { cin >> small_grid[i]; flag = false; for (int j = 0;j < m;j++) { if (small_grid[i][j] == '*') { min_i = min(min_i, j); flag = true; break; } } if (flag) { non_empty.push_back(i); } for (int j = m-1; j >= 0;j--) { if (small_grid[i][j] == '*') { max_i = max(max_i, j); break; } } } int begi, endi; if (non_empty.size() == 0) { begi = 0; endi = 0; } else { begi = non_empty[0]; endi = non_empty.back(); } vector <string> parse_grid; for (int i = begi; i <= endi; i++) { string temp = ""; for (int j = min_i; j <= max_i; j++) { temp += small_grid[i][j]; } parse_grid.push_back(temp); } int n_n = parse_grid.size(); int m_m = parse_grid[0].size(); bool flag = false; for (int i = 0;i < N - n_n + 1; i++) { for (int j = 0; j < M - m_m + 1; j++) { flag = true; for (int k = i; k < i + n_n; k++) { for (int l = j; l < j + m_m; l++) { if (parse_grid[k-i][l-j] == '.') continue; if (major_grid[k][l] != parse_grid[k - i][l - j]) { flag = false; break; } } if (flag == false) { break; } } if (flag == true) { cout << "Yes" << endl; break; } } if (flag == true) { break; } } if (flag == false) { cout << "No" << endl; } } cout << endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector< pair< pair<int,int>, int > > v(n); int minind = -1; int ind = -1; int mini = INT_MAX; int maxi = -1; int a,b; for (int i = 0; i < n; i++) { cin>>v[i].first.first>>v[i].first.second; v[i].second = i+1; } sort(v.begin(), v.end()); mini = v[0].first.first; ind = v[0].second; int i = 0; while (v[i].first.first == mini ) { if (v[i].first.second>maxi) { maxi = v[i].first.second; ind = v[i].second; } i++; } for (int i = 0;i<n;i++) { if (v[i].first.second > maxi) { cout<<"-1"<<endl; return 0; } } cout<<ind<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; for (int i=0;i<n;i++) { int a,b,c,d; char op,sl; int t1,t2; cin>>a>>sl>>b>>op>>c>>sl>>d; if (op == '*') { t1 = a*c; t2 = b*d; } else if (op == '/') { t1 = a*d; t2 = b*c; } else if (op == '+') { t1 = a*d + b*c; t2 = b*d; } else if (op == '-') { t1 = a*d - b*c; t2 = b*d; } cout<<t1<<"/"<<t2<<" = "<<t1/__gcd(abs(t1),t2)<<"/"<<t2/__gcd(abs(t1),t2)<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; string f(char c, map<char, char> &dic) { string res = ""; if(dic.find(c) != dic.end()) { res += dic[c]; } else { res = ""; } return res; } string clean(string s, map <char, char> &dic) { string res = ""; res += f(s[0],dic); for (int i = 1;i < s.length(); i++) { if (f(s[i], dic) != f(s[i-1], dic)) { res += f(s[i], dic); } } return res; } int main() { string inp; map <char, char> dic = { {'B', '1'}, {'F', '1'}, {'P', '1'}, {'V', '1'}, {'C', '2'}, {'G', '2'}, {'J', '2'}, {'K', '2'}, {'Q', '2'}, {'S', '2'}, {'X', '2'}, {'Z', '2'}, {'D', '3'}, {'T', '3'}, {'L', '4'}, {'M', '5'}, {'N', '5'}, {'R', '6'} }; while(cin >> inp) { cout<<clean(inp, dic)<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; bool valid (int i, int j, int r, int c) { if (i >= 0 && i < r && j >= 0 && j < c) { return true; } return false; } int main() { int n, r, c, k; while (cin >> n >> r >> c >> k) { if (n + r + c + k == 0) { break; } vector <vector <int> > land(r, vector <int> (c, 0)); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { cin >> land[i][j]; } } for (int ii = 0; ii < k; ii++) { vector <vector <int> > new_land(r, vector <int> (c, 0)); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (valid(i + 1, j, r, c) && (land[i][j] - 1 + n) % n == land[i + 1][j]) { new_land[i][j] = (n + land[i][j] - 1) % n; } else if (valid(i - 1, j, r, c) && (land[i][j] - 1 + n) % n == land[i - 1][j]) { new_land[i][j] = (n + land[i][j] - 1) % n; } else if (valid(i, j + 1, r, c) && (land[i][j] - 1 + n) % n == land[i][j + 1]) { new_land[i][j] = (n + land[i][j] - 1) % n; } else if (valid(i, j - 1, r, c) && (land[i][j] - 1 + n) % n == land[i][j - 1]) { new_land[i][j] = (n + land[i][j] - 1) % n; } else { new_land[i][j] = land[i][j]; } } } for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { land[i][j] = new_land[i][j]; } } } for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { cout << land[i][j]; if (j < c - 1) { cout << " "; } } cout << endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; char fun(char i) { if (i <= 'z' && i >= 'a') { return i; } else if (i >= 'A' && i <= 'Z') { return i + 32; } else { return ' '; } } string clean(string s) { string res = ""; bool flag = false; for (auto i:s) { if (flag) { flag = false; if (i == '\n') { continue; } else { res += '-'; res += fun(i); } } else if (i == '-'){ flag = true; } else { res += fun(i); } } return res; } stringstream ss; int main () { string inp; getline(cin, inp, '\0'); inp = clean(inp); ss.str(inp); set <string> dic; string word; while (ss >> word) { dic.insert(word); } for (auto i:dic) { cout << i << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; class UnionFind { private: vector<int> parent; vector<int> rank; int size; public: UnionFind(int n) { size = n; rank.assign(n, 0); parent.assign(n, 0); for (int i = 0; i < n; i++) { parent[i] = i; } } int find_set(int i) { return (parent[i] == i) ? i:(parent[i] = find_set(parent[i])); } bool is_same_set(int i, int j) { return find_set(i) == find_set(j); } void union_join(int i, int j) { if (!is_same_set(i, j)) { int x = find_set(i); int y = find_set(j); if (rank[x] > rank[y]) { parent[y] = x; } else { parent[x] = y; if (rank[x] == rank[y]) { rank[y]++; } } } } int result() { int it = 0; for (int i = 0; i < size; i++) { if (parent[i] == i) { it += 1; } } return it; } }; int main() { int idx = 0; while (1) { int n, m; int a, b; cin >> n >> m; if (n + m == 0) { break; } cout << "Case " << ++idx << ": "; UnionFind case1(n); for (int i = 0; i < m; i++) { cin >> a >> b; case1.union_join(a-1, b-1); } cout << case1.result() << endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool valid (int i,int j) { if (i >= 0 && i<=4 && j >= 0 && j<= 4) { return true; } else { return false; } } int main() { string s; string moves; getline(cin,s); int counter = 1; while (s.length()!=1 && s[0] != 'Z') { vector <string> board; board.push_back(s); for (int i = 0;i<4;i++) { getline(cin,s); board.push_back(s); } pair<int,int> blank; for (int i=0;i<5;i++) { for(int j=0;j<5;j++) { if (board[i][j] == ' ') { blank.first = i; blank.second = j; } } } bool flag = true; do { getline(cin,moves); for (int i = 0; i< moves.length();i++) { if (moves[i] == 'A') { if (!valid(blank.first-1,blank.second)) { flag = false; break; } board[blank.first][blank.second] = board[blank.first-1][blank.second]; board[blank.first-1][blank.second] = ' '; blank.first--; } else if (moves[i] == 'B') { if (!valid(blank.first+1,blank.second)) { flag = false; break; } board[blank.first][blank.second] = board[blank.first+1][blank.second]; board[blank.first+1][blank.second] = ' '; blank.first++; } else if (moves[i] == 'R') { if (!valid(blank.first,blank.second+1)) { flag = false; break; } board[blank.first][blank.second] = board[blank.first][blank.second+1]; board[blank.first][blank.second+1] = ' '; blank.second++; } else if (moves[i] == 'L') { if (!valid(blank.first,blank.second-1)) { flag = false; break; } board[blank.first][blank.second] = board[blank.first][blank.second-1]; board[blank.first][blank.second-1] = ' '; blank.second--; } else if (moves[i] != '0') { flag = false; break; } } } while (moves[moves.length() - 1] != '0'); cout<<"Puzzle #"<<counter<<":"<<endl; counter++; if (flag == true) { for (int i=0;i<5;i++) { for (int j = 0; j<5; j++) { cout<<board[i][j]; if (j<4) cout<<" "; } cout<<endl; } } else { cout<<"This puzzle has no final configuration."<<endl; } getline(cin,s); if (s.length()!=1 && s[0]!='Z') { cout<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; int max = 0; int ind = 0; for (int i = 0;i<=n;i++) { if (n- 2*i >= 0 && 2*n - i*4 >= 0 && 2*n - i*3 <= m && n-i>max) { max = n-i; ind = i; } } n = n + m; m = n - m; n = n - m; for (int i = 0;i<=n;i++) { if (n- 2*i >= 0 && 2*n - i*4 >= 0 && 2*n - i*3 <= m && n-i>max) { max = n-i; ind = i; } } cout<<max<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool check(int num, string s) { int left = 0; int right = 0; for (int i = 0;i<s.length()/2;i++) { left = left*10 + s[i] - 48; } for (int i = s.length()/2; i < s.length(); i++) { right = right*10 + s[i] - 48; } if ((left + right)*(left + right) == num) { return true; } else { return false; } } string ms(int num, int d) { string s = ""; for (int i = 0;i<d;i++) { s += "0"; } int j = s.length() - 1; while (num != 0) { s[j--] = num%10 + 48; num /= 10; } return s; } int main () { map <int, vector <string> > res; for (int i = 1;i < 5; i++) { for (int j = 0; j< pow(10,i);j++) { int sq = j*j; string sqs = ms(sq,i*2); if (check(sq,sqs)) { res[2*i].push_back(sqs); } } } int t; while(cin>>t) { for (auto i:res[t]) { cout<<i<<endl; } } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main () { long long int n; cin>>n; while (n != 0) { vector <int> a1; vector <int> a2; int ii = 0; for (long long int i = 0;(1LL<<i )<= n;i++) { if ((n&(1LL<<i)) == (1LL<<i)) { if (ii == 0) { a1.push_back(i); } else { a2.push_back(i); } ii ^= 1; } } long long int res1 = 0; long long int res2 = 0; for (int i = 0; i < a1.size();i++) { res1 += (1<<a1[i]); } for (int i = 0; i < a2.size();i++) { res2 += (1<<a2[i]); } cout<<res1<<" "<<res2<<endl; cin>>n; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; char toLower(char a) { if (a <'a') a+=32; return a; } int main() { string a; string b; cin>>a; cin>>b; int i=0; while (toLower(a[i]) == toLower(b[i])) { i++; if (i==a.length()) break; } if (i == a.length()) cout<<"0\n"; else if (toLower(a[i]) < toLower(b[i]) ) cout<<"-1\n"; else cout<<"1\n"; return 0; } <file_sep>#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <cstdlib> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> using namespace std; /* Head ends here */ class ImageDithering { public: int count(string dithered,vector<string> screen); }; int ImageDithering::count(string dithered, vector <string> screen) { int count=0; for (int i=0;i<screen.size();i++) { for (int j=0;j<screen[i].length();j++) { for (int k=0;k<dithered.length();k++) { if (screen[i][j]==dithered[k]) { count++; break; } } } } return count; } <file_sep>#include <bits/stdc++.h> using namespace std; long long int psq(long long int n) { long long int t = sqrtl(n); if (t*t == n ) { return t; } else if ((t+1)*(t+1)==n){ return t+1; } else if ((t-1)*(t-1) == n) { return t-1; } return 0; } int main() { int n; cin>>n; int a[1000006] = {0}; a[0] = 1;a[1] = 1; for (long long int i=2;i<1000002;i++) { if (a[i]== 1) continue; for (long long int j = i*i;j < 1000002; j+=i) { a[j] = 1; } } long long int temp; for (int i=0;i<n;i++) { cin>>temp; if (psq(temp) && a[psq(temp)] == 0) { cout<<"YES"<<endl; } else { cout<<"NO"<<endl; } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { long long int n; cin>>n; if (n%2==0) cout<<n/2<<endl; else cout<<n/2 -n<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int main() { string inp; getline(cin, inp); vector <string> notes = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}; vector <int> scales = {0, 2, 4, 5, 7, 9, 11}; vector <set<string> > all; for (int i = 0;i<12;i++) { set<string> temp; for (int j = 0; j< 7; j++) { temp.insert(notes[(scales[j] + i)%12]); } all.push_back(temp); } while(inp != "END") { ss.str(""); ss.clear(); ss.str(inp); set <string> new_v; string note; while(ss>>note) { new_v.insert(note); } vector <string> res; for (int i = 0;i<12;i++) { bool flag = true; for (auto j:new_v) { if (all[i].find(j) == all[i].end()) { flag = false; break; } } if(flag == true) { res.push_back(notes[i]); } } for (int i = 0; i< res.size();i++) { cout<<res[i]; if(i < res.size()-1) cout<<" "; } cout << endl; getline(cin, inp); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int A[5][5]; int t; for (int i=0;i<5;i++) { for (int j=0;j<5;j++) { cin>>t; if (t == 1) { cout<<abs(i-2) + abs(j-2)<<endl; } } } return 0; }<file_sep>#include<stdio.h> #include<math.h> int main(){ long long int n,i; scanf("%lld",&n); for (i=0 ; i<n ; i++){ long long int num,count; long long int arg; count=0; scanf("%lld",&num); arg=1; while(num>=pow(5,arg)){ count+=num/pow(5,arg++); } printf("%lld\n",count); } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; bool valid(int i, int j) { if (i >= 0 && i < 20 && j >= 0 && j < 20) { return true; } return false; } int main(){ int t; int n; int a, b; string inp; getline(cin, inp); ss.str(""); ss.clear(); ss.str(inp); ss >> t; getline(cin, inp); while (t--) { getline(cin, inp); string temp = " "; vector <string> grid(20, temp); vector <string> grid_2(20, temp); ss.str(""); ss.clear(); ss.str(inp); ss >> n; assert (n > 0); getline(cin, inp); while (inp != "") { ss.str(""); ss.clear(); ss.str(inp); ss >> a >> b; grid[a-1][b-1] = 'O'; getline(cin, inp); } while (n--) { cout << "********************" << endl; for (int i = 0; i< 20; i++) { cout << grid[i] << endl; } for (int i = 0; i < 20; i++) { grid_2[i] = temp; } for (int i = 0; i < 20; i++) { for (int j = 0; j < 20; j++) { int cnt = 0; for (int deltax = -1; deltax <= 1; deltax++) { for (int deltay = -1; deltay <= 1; deltay++) { if (deltay == 0 && deltax == 0) continue; if (!valid(i + deltax, j + deltay)) continue; if (grid[i + deltax][j + deltay] == 'O') cnt += 1; } } if (grid[i][j] == ' ' && cnt == 3) { grid_2[i][j] = 'O'; } else if (grid[i][j] == 'O' && (cnt == 2 || cnt == 3)) { grid_2[i][j] = 'O'; } else { grid_2[i][j] = ' '; } } } for (int i = 0;i < 20; i++) { grid[i] = grid_2[i]; } } cout << "********************" << endl; if (t > 0) { cout << endl; } } return 0; } <file_sep>#for _ in range(10): a=list(raw_input());print 2**(a.count('T')+a.count('D')+a.count('L')+a.count('F')) for _ in range(10): print 2**len(filter(lambda x:x in 'TDLF',list(raw_input()))) <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n, r; cin >> n >> r; map <string, vector <int>> arr; map <string, vector <pair <int, int > > > bounds; string name; int base; int sz; int dim; for (int i = 0;i < n;i++) { cin >> name; cin >> base >> sz >> dim; arr[name].push_back(base); arr[name].push_back(sz); arr[name].push_back(dim); int u, l; for (int j = 0; j < dim; j++) { cin >> u >> l; bounds[name].push_back(make_pair(u, l)); } } vector <int> dims; int ele; for (int i = 0; i < r; i++) { dims.clear(); cin >> name; sz = arr[name][2]; for (int j = 0; j < sz; j++) { cin >> ele; dims.push_back(ele); } vector <int> c_arr(sz+1, 0); c_arr[sz] = arr[name][1]; for (int j = sz-1; j > 0; j--) { c_arr[j] = c_arr[j+1]*(bounds[name][j].second - bounds[name][j].first + 1); } int diff = 0; for (int j = 1; j <= sz; j++) { diff += c_arr[j] * bounds[name][j-1].first; } c_arr[0] = arr[name][0] - diff; int sum = c_arr[0]; for (int j = 1; j <= sz; j++) { sum += c_arr[j] * dims[j-1]; } cout<<name<<"["; for (int j = 0; j < sz; j++) { cout<<dims[j]; if (j < sz - 1) { cout << ", "; } } cout<<"] = "<<sum<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; stringstream ss; int main () { string scale; string inp; map<string, vector <string> > notes = { {"C", {"C", "D", "E", "F", "G", "A", "B"}}, {"Db", {"Db", "Eb", "F", "Gb", "Ab", "Bb", "C"}}, {"D", {"D", "E", "F#", "G", "A", "B", "C#"}}, {"Eb", {"Eb", "F", "G", "Ab", "Bb", "C", "D"}}, {"E", {"E", "F#", "G#", "A", "B", "C#", "D#"}}, {"F", {"F", "G", "A", "Bb", "C", "D", "E"}}, {"Gb", {"Gb", "Ab", "Bb", "Cb", "Db", "Eb", "F"}}, {"G", {"G", "A", "B", "C", "D", "E", "F#"}}, {"Ab", {"Ab", "Bb", "C", "Db", "Eb", "F", "G"}}, {"A", {"A", "B", "C#", "D", "E", "F#", "G#"}}, {"Bb", {"Bb", "C", "D", "Eb", "F", "G", "A"}}, {"B", {"B", "C#", "D#", "E", "F#", "G#", "A#"}} }; while (getline(cin, scale)) { getline(cin, inp); ss.str(""); ss.clear(); ss.str(inp); string qq; cout<<"Key of "<<scale<<endl; vector <string> note = notes[scale]; while(getline(ss, qq, ';')) { string key = ""; string dir = ""; string step = ""; int i = 0; for (; qq[i] != ' '; ) { key += qq[i]; i+= 1; } i+= 1; for (; qq[i] != ' '; ) { dir += qq[i]; i+= 1; } i+= 1; for (; i < qq.length(); i++) { step += qq[i]; } int start = -1; for (int i = 0; i < note.size(); i++) { if (note[i] == key) { start = i; } } if (start == -1) { cout<<key<<": invalid note for this key"<<endl; continue; } if (step == "SECOND") { if (dir == "UP") { cout <<key<<": UP SECOND > "<<note[(start + 1)%7]<<endl; } else if (dir == "DOWN") { cout <<key<<": DOWN SECOND > "<<note[(start + 7 - 1)%7]<<endl; } } else if (step == "THIRD") { if (dir == "UP") { cout <<key<<": UP THIRD > "<<note[(start + 2)%7]<<endl; } else if (dir == "DOWN") { cout <<key<<": DOWN THIRD > "<<note[(start + 7 - 2)%7]<<endl; } } else if (step == "FOURTH") { if (dir == "UP") { cout <<key<<": UP FOURTH > "<<note[(start + 3)%7]<<endl; } else if (dir == "DOWN") { cout <<key<<": DOWN FOURTH > "<<note[(start + 7 - 3)%7]<<endl; } } else if (step == "FIFTH") { if (dir == "UP") { cout <<key<<": UP FIFTH > "<<note[(start + 4)%7]<<endl; } else if (dir == "DOWN") { cout <<key<<": DOWN FIFTH > "<<note[(start + 7 - 4)%7]<<endl; } } else if (step == "SIXTH") { if (dir == "UP") { cout <<key<<": UP SIXTH > "<<note[(start + 5)%7]<<endl; } else if (dir == "DOWN") { cout <<key<<": DOWN SIXTH > "<<note[(start + 7 - 5)%7]<<endl; } } else if (step == "SEVENTH") { if (dir == "UP") { cout <<key<<": UP SEVENTH > "<<note[(start + 6)%7]<<endl; } else if (dir == "DOWN") { cout <<key<<": DOWN SEVENTH > "<<note[(start + 7 - 6)%7]<<endl; } } else if (step == "OCTAVE") { if (dir == "UP") { cout <<key<<": UP OCTAVE > "<<note[(start + 7)%7]<<endl; } else if (dir == "DOWN") { cout <<key<<": DOWN OCTAVE > "<<note[(start + 7 - 7)%7]<<endl; } } } cout<<endl; } return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; int main() { int k,l,m,n,d; cin>>k>>l>>m>>n>>d; vector <int> check(d+1,0); for (int i = k;i<=d;i+=k) check[i] = 1; for (int i = l;i<=d;i+=l) check[i] = 1; for (int i = m;i<=d;i+=m) check[i] = 1; for (int i = n;i<=d;i+=n) check[i] = 1; int cnt = 0; for (int i=1;i<=d;i++) if (check[i]==1) cnt++; cout<<cnt<<endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int temp; vector <int> negs; vector <int> pos; long long int zero=0; for (int i=0;i<n;i++) { cin>>temp; if (temp<0) negs.push_back((-1)*temp); else if (temp>0) pos.push_back(temp); else zero++; } sort(pos.begin(),pos.end()); sort(negs.begin(),negs.end()); long long int counter = 0; for (int i=1;i<=10;i++) { long long int a = count(pos.begin(),pos.end(),i); long long int b = count(negs.begin(),negs.end(),i); counter+= a*b; } counter += (zero*(zero-1))/2; cout<<counter<<endl; return 0; }
34f2081361c2cdb28649db5c311b23ae45729867
[ "C", "Python", "C++" ]
764
C++
shashank21j/CompetitiveProgramming
5e905ad7f59f36541baaa669391eba667f291a45
bd7d1516bda0047162293f62e78a8f3134021454
refs/heads/master
<file_sep>package alms_box.donation_box; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; import alms_box.user.UserRepository; import alms_box.user.User; import alms_box.exceptions.NotFoundException; @RestController public class DonationBoxController { private final DonationBoxRepository donationBoxRepository; private final UserRepository userRepository; DonationBoxController(DonationBoxRepository donationBoxRepository, UserRepository userRepository) { this.donationBoxRepository = donationBoxRepository; this.userRepository = userRepository; } // Aggregate root @GetMapping("/donation_boxes") List<DonationBox> all() { return donationBoxRepository.findAll(); } @PostMapping("/donation_boxes") DonationBox newDonation(@RequestBody DonationBox newDonationBox) { Long user_id = newDonationBox.getAdmin().getId(); User donation_user = userRepository.findById(user_id) .orElseThrow(() -> new NotFoundException(user_id)); newDonationBox.setAdmin(donation_user); return donationBoxRepository.save(newDonationBox); } // Single item @GetMapping("/donation_boxes/{id}") DonationBox one(@PathVariable Long id) { return donationBoxRepository.findById(id) .orElseThrow(() -> new NotFoundException(id)); } @PutMapping("/donation_boxes/{id}") DonationBox replaceDonation(@RequestBody DonationBox newDonation, @PathVariable Long id) { return donationBoxRepository.findById(id) .map(DonationBox -> { DonationBox.setAdmin(newDonation.getAdmin()); DonationBox.setBeneficiary(newDonation.getBeneficiary()); DonationBox.setName(newDonation.getName()); DonationBox.setDescription(newDonation.getDescription()); return donationBoxRepository.save(DonationBox); }) .orElseGet(() -> { newDonation.setId(id); return donationBoxRepository.save(newDonation); }); } @DeleteMapping("/donation_boxes/{id}") void deleteDonation(@PathVariable Long id) { donationBoxRepository.deleteById(id); } } <file_sep>AlmsBox is a test project using RESTful services and Java 11 to practice creating backend Java applications <file_sep>package alms_box.user; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import alms_box.donation.Donation; import java.util.List; public interface UserRepository extends JpaRepository<User, Long> { @Query("SELECT u.donations FROM User u WHERE u.id = :id") List<Donation> listDonations(@Param("id") Long id); } <file_sep>package alms_box.user; import java.util.Objects; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import alms_box.donation.Donation; import alms_box.donation_box.DonationBox; @Entity public class User { @Id @GeneratedValue private Long id; @OneToMany(mappedBy = "user") private List<Donation> donations; @OneToMany(mappedBy = "admin") private List<DonationBox> donation_boxes_admin; @OneToMany(mappedBy = "beneficiary") private List<DonationBox> donation_boxes_beneficiary; private String username; private String email; private String password; private int account_balance; protected User() { } User(String email, String password) { this.email = email; this.password = password; } // Getters and setters public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getAccount_balance() { return account_balance; } public void setAccount_balance(int account_balance) { this.account_balance = account_balance; } // Utility methods public void deductBalance(int deduction) { if(this.account_balance > deduction){ this.account_balance -= deduction; } else{this.account_balance = 0;} } public void addBalance(int increase) { this.account_balance+=increase; } // Method overrides @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; User User = (User) o; return Objects.equals(this.id, User.id) && Objects.equals(this.email, User.email) && Objects.equals(this.password, User.password); } @Override public int hashCode() { return Objects.hash(this.username, this.password); } @Override public String toString() { return String.format("%s (%s)", this.username, this.email); } } <file_sep>package alms_box.donation_box; import org.springframework.data.jpa.repository.JpaRepository; public interface DonationBoxRepository extends JpaRepository<DonationBox, Long> { }
093673b9fcd2582ec1bef7b439a668d3ab8e627e
[ "Markdown", "Java" ]
5
Java
a-baidulin/java_test
56c1e127f6f2e630463d3103e894a4ffb168979f
73f8a61844cb03e71fa17842fc7f2f9854f7f790
refs/heads/master
<repo_name>igor-sweet/StupidQuestion-revo<file_sep>/core/components/stupidquestion/model/stupidquestion/stupidquestion.class.php <?php /** * StupidQuestion - Userfriendly Captcha for MODX Revolution * * StupidQuestion 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 2 of the License, or (at your option) any * later version. * * StupidQuestion 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 * StupidQuestion; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @package stupidquestion * @subpackage classfile * @author <NAME> <<EMAIL>> * @copyright Copyright 2010-2013, <NAME> * * StupidQuestion class. */ if (!class_exists('JavaScriptPacker')) { include $corePath . 'model/packer/class.JavaScriptPacker.php'; } include $corePath . 'model/chunkie/chunkie.class.inc.php'; if (!class_exists('stupidQuestion')) { class stupidQuestion { /** * The collection of output strings * * @var array $output * @access public */ public $output; /** * The answer of the stupid question * * @var string $answer * @access public */ public $answer; /** * The formfield that has to be posted containing $answer * * @var string $formfield * @access public */ public $formfield; /** * The MODX object * * @var mixed $modx * @access private */ private $modx; /** * The stupidQuestion settings * * @var array $settings * @access private */ private $settings; /** * The stupidQuestion templates * * @var array $templates * @access private */ private $templates; /** * The core path to the stupidQuestion installation * * @var string $template * @access private */ private $corePath = ''; /** * stupidQuestion constructor * * @param mixed $modx The MODX object * @param array $options The options for this stupidQuestion. */ function __construct($modx, $options = array()) { $this->output = array(); $this->answer = ''; $this->formfield = ''; $this->modx = &$modx; $this->settings = array(); $this->templates = array(); $this->corePath = $this->modx->getOption('stupidquestion.core_path', null, MODX_CORE_PATH . 'components/stupidquestion/'); $this->prepareSettings($options); $this->prepareTemplates($options); $this->setQuestion(); } /** * Research an existing file by name, filetype and extension. The file * is searched in $type based folder with the following file name * $name.$type.$extension * * @access private * @param string $name The main name of the file * @param string $type The type of the file * @param string $extension The extension of the file * @return string An existing file name otherwise an error message */ private function researchFile($name, $type = 'config', $extension = '.inc.php') { $folder = (substr($type, -1) != 'y') ? $type . 's/' : substr($folder, 0, -1) . 'ies/'; $allowedFile = glob($this->corePath . $folder . '*.' . $type . $extension); $configs = array(); foreach ($allowedFile as $config) { $configs[] = preg_replace('=.*/' . $folder . '([^.]*).' . $type . $extension . '=', '$1', $config); } if (in_array($name, $configs)) { $output = $this->corePath . $folder . $name . '.' . $type . $extension; } else { if (file_exists($this->corePath . $folder . 'default.' . $type . $extension)) { $output = $this->corePath . $folder . 'default.' . $type . $extension; } else { $output = 'Allowed ' . $name . ' and default stupidQuestion ' . $type . ' file "' . $this->corePath . $folder . 'default.' . $type . $extension . '" not found. Did you upload all files?'; } } return $output; } /** * Prepare the settings for stupidQuestion * * @access private * @param array $options The options for this stupidQuestion. */ private function prepareSettings($options = array()) { $language = $this->modx->getOption('language', $options, 'en'); $answer = $this->modx->getOption('answer', $options, ''); $this->modx->getService('lexicon', 'modLexicon'); $saveCultureKey = $this->modx->getOption('cultureKey'); $this->modx->setOption('cultureKey', $language); $this->modx->lexicon->load('stupidquestion:default'); $this->settings['questions_first'] = $this->modx->fromJson($this->modx->lexicon('stupidquestion.questions_first')); $this->settings['questions_second'] = $this->modx->fromJson($this->modx->lexicon('stupidquestion.questions_second')); $this->settings['questions'] = array_merge($this->settings['questions_first'], $this->settings['questions_second']); $this->settings['intro'] = $this->modx->fromJson($this->modx->lexicon('stupidquestion.intro')); if ($answer == '') { $this->settings['answer'] = $this->modx->fromJson($this->modx->lexicon('stupidquestion.answer')); } else { $this->settings['answer'] = $this->modx->fromJson($answer); } $this->settings['formFields'] = $this->modx->fromJson($this->modx->lexicon('stupidquestion.formFields')); $this->settings['required'] = $this->modx->lexicon('stupidquestion.required'); $this->settings['requiredMessage'] = $this->modx->lexicon('stupidquestion.requiredMessage'); $this->modx->setOption('cultureKey', $saveCultureKey); return; } /** * Prepare the templates for stupidQuestion * * @access private * @param array $options The options for this stupidQuestion. */ private function prepareTemplates($options = array()) { $this->templates['formcode'] = $this->modx->getOption('formcode', $options, '@FILE ' . $this->researchFile('formcode', 'template', '.html'), true); $this->templates['jscode'] = $this->modx->getOption('jscode', $options, '@FILE ' . $this->researchFile('jscode', 'template', '.js'), true); $this->templates['jswrapper'] = '@FILE ' . $this->researchFile('jswrapper', 'template', '.js'); return; } /** * Set the session and generate the output * * @access private */ private function setQuestion() { // Random values $randQuestion = rand(0, count($this->settings['questions']) - 1); $randIntro = rand(0, count($this->settings['intro']) - 1); $randAnswer = rand(0, count($this->settings['answer']) - 1); $randFormField = rand(0, count($this->settings['formFields']) - 1); // reset session if $_POST is not filled if (!count($_POST)) { unset($_SESSION['StupidQuestion'], $_SESSION['StupidQuestionFormField'], $_SESSION['StupidQuestionAnswer']); } // get $_POST and replace values with session values if (isset($_SESSION['StupidQuestion'])) { foreach ($this->settings['formFields'] as $formKey => $formField) { if (in_array($formField, array_keys($_POST))) { $randQuestion = $_SESSION['StupidQuestion']; $randAnswer = $_SESSION['StupidQuestionAnswer']; $randFormField = $formKey; } } } $_SESSION['StupidQuestion'] = $randQuestion; $_SESSION['StupidQuestionFormField'] = $randFormField; $_SESSION['StupidQuestionAnswer'] = $randAnswer; // prepare form placeholder/script placeholder values $answer = explode(' ', $this->settings['answer'][$randAnswer]); $value = ($randQuestion < count($this->settings['questions_first'])) ? $answer[0] : $answer[1]; $othervalue = ($randQuestion < count($this->settings['questions_first'])) ? $answer[1] : $answer[0]; $frage = $this->settings['questions'][$randQuestion]; $formField = $this->settings['formFields'][$randFormField]; // parse stupid question template and javscript template $parser = new revoChunkie($this->templates['jscode']); $parser->createVars(array( 'id' => $formField, 'othervalue' => $othervalue, 'value' => $value )); $jsCode = $parser->render(); $parser = new revoChunkie('@INLINE ' . $this->settings['intro'][$randIntro]); $parser->createVars(array( 'question' => $frage . $this->settings['answer'][$randAnswer] )); $question = $parser->render(); $parser = new revoChunkie($this->templates['formcode']); $parser->createVars(array( 'id' => $formField, 'value' => $value, 'question' => $question, 'required' => $this->settings['required'], 'requiredMessage' => $this->settings['requiredMessage'] )); $this->output['htmlCode'] = $parser->render(); $this->answer = $value; $this->formfield = $formField; $packer = new JavaScriptPacker($jsCode, 'Normal', true, false); $parser = new revoChunkie($this->templates['jswrapper']); $parser->createVars(array( 'packed' => trim($packer->pack()) )); $this->output['jsCode'] = $parser->render(); return; } /** * Check $_POST for the answer * * @access public * @param string $basepath The basepath @FILE is prefixed with. * @return boolean True if stupid question is answered right. */ public function checkAnswer() { if (count($_POST) > 0 && $_POST[$this->formfield] != $this->answer) { $this->output['errorMessage'] = $this->settings['requiredMessage']; return false; } else { $this->output['errorMessage'] = ''; return true; } } } } ?> <file_sep>/core/components/stupidquestion/lexicon/de/default.inc.php <?php /** * StupidQuestion - Userfriendly Captcha for MODX Revolution * * StupidQuestion 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 2 of the License, or (at your option) any * later version. * * StupidQuestion 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 * StupidQuestion; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @package stupidquestion * @subpackage lexicon * @author <NAME> <<EMAIL>> * @copyright Copyright 2010-2013, <NAME> * * German Lexicon Entries for StupidQuestion */ $_lang['stupidquestion.questions_first'] = '["der Vorname von ", "das erste Wort von "]'; $_lang['stupidquestion.questions_second'] = '["der Nachname von ", "das letzte Wort von "]'; $_lang['stupidquestion.intro'] = '["Wie lautet [[+question]]?", "Was ist [[+question]]?", "Fangfrage: [[+question:ucfirst]] lautet:", "Dumme Frage: [[+question:ucfirst]] ist:"]'; $_lang['stupidquestion.answer'] = '["<NAME>", "<NAME>", "<NAME>", "<NAME>"]'; $_lang['stupidquestion.formFields'] = '["dumme-frage", "bloede-frage", "fangfrage", "bottrap", "nur-eine-frage"]'; $_lang['stupidquestion.required'] = 'benötigt'; $_lang['stupidquestion.requiredMessage'] = 'Bitte beantworten Sie die Frage richtig.'; ?><file_sep>/README.md stupidQuestion ================================================================================ Userfriendly Captcha for MODX Revolution Features: -------------------------------------------------------------------------------- StupidQuestion is a simple but effective and userfriendly captcha solution for FormIt. A stupid question (i.e. 'What is the given name of <NAME>?') is inserted in the form template. The form field is filled and hidden by a javascript that is packed by a javascript packer. The packer scrambles the code and because of the input name contains different counts of hyphens the right answer is not placed at the same position. The filling bots have to execute javascript - a lot don't do that. Installation: -------------------------------------------------------------------------------- MODX Package Management Usage -------------------------------------------------------------------------------- The snippet has to be used as FormIt preHook and hook. ``` [[!FormIt? &preHooks=`StupidQuestion,...` &hooks=`StupidQuestion,...` ... ``` with the following properties Property | Description | Default ---- | ----------- | ------- stupidQuestionAnswers | Answers for the stupid question (JSON encoded array of \'forename name\' combinations) | language dependent stupidQuestionLanguage | Language of the stupid question | en stupidQuestionFormcode | Template chunk for the stupid question html form field | the content of the file `formcode.template.html` in the folder `{core}/components/stupidquestion/templates` stupidQuestionScriptcode | Template chunk for the filling javascript | the content of the file `jscode.template.js` the folder `{core}/components/stupidquestion/templates` stupidQuestionRegister | Move the filling javascript to the end of the html body | false stupidQuestionNoScript | Remove the filling javascript | false If you want to change the html code for the stupid question form field, put this default code in a chunk and modify it: ```html <div> <label for="[[+id]]">[[+question]]</label> <input type="text" name="[[+id]]" id="[[+id]]" [[!+fi.error.[[+id]]:notempty=`class="error"`]]/><span class="small">([[+required]])</span>[[!+fi.error.[[+id]]]]<br /> </div> ``` If you want to change the answers you could use this english lexicon setting as example: ``` ["<NAME>", "<NAME>", "<NAME>", "<NAME>"] ``` All language specific strings could be changed by editing the lexicon entries in the stupidquestion namespace. Use the existing placeholders in these entries. Don't forget to place the [[!+formit.stupidquestion_html]] placeholder in the form code. Notes: -------------------------------------------------------------------------------- 1. Uses: PHP packer implementation on http://joliclic.free.fr/php/javascript-packer/en/ 2. Bases on a captcha idea of Peter Kröner: http://www.peterkroener.de/dumme-frage-captchas-automatisch-ausfuellen/ <file_sep>/core/components/stupidquestion/lexicon/en/default.inc.php <?php /** * StupidQuestion - Userfriendly Captcha for MODX Revolution * * StupidQuestion 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 2 of the License, or (at your option) any * later version. * * StupidQuestion 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 * StupidQuestion; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @package stupidquestion * @subpackage lexicon * @author <NAME> <<EMAIL>> * @copyright Copyright 2010-2013, <NAME> * * English Lexicon Entries for StupidQuestion */ $_lang['stupidquestion.questions_first'] = '["the given name of ", "the first word of "]'; $_lang['stupidquestion.questions_second'] = '["the family name of ", "the last word of "]'; $_lang['stupidquestion.intro'] = '["What is [[+question]]?", "What\'s [[+question]]?", "Trick question: [[+question:ucfirst]] reads:", "Stupid question: [[+question:ucfirst]] is:"]'; $_lang['stupidquestion.answer'] = '["<NAME>", "<NAME>", "<NAME>", "<NAME>"]'; $_lang['stupidquestion.formFields'] = '["stupid-question", "silly-question", "trickquestion", "bottrap", "only-one-question", "please-answer-this"]'; $_lang['stupidquestion.required'] = 'required'; $_lang['stupidquestion.requiredMessage'] = 'Please answer the question right.'; ?><file_sep>/_build/data/properties/properties.stupidquestion.php <?php /** * StupidQuestion - Userfriendly Captcha for MODX Revolution * * Copyright 2010-2012 by <NAME> <<EMAIL>> * * StupidQuestion 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 2 of the License, or (at your option) any * later version. * * StupidQuestion 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 * StupidQuestion; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @package stupidquestion * @subpackage build * @author <NAME> <<EMAIL>> * @copyright Copyright 2010-2013, <NAME> * * Properties for the StupidQuestion snippet. */ $properties = array( array( 'name' => 'stupidQuestionAnswers', 'desc' => 'prop_stupidquestion.stupidQuestionAnswers', 'type' => 'textfield', 'options' => '', 'value' => '', 'lexicon' => 'stupidquestion:properties', ), array( 'name' => 'stupidQuestionLanguage', 'desc' => 'prop_stupidquestion.stupidQuestionLanguage', 'type' => 'textfield', 'options' => '', 'value' => 'en', 'lexicon' => 'stupidquestion:properties', ), array( 'name' => 'stupidQuestionFormcode', 'desc' => 'prop_stupidquestion.stupidQuestionFormcode', 'type' => 'textfield', 'options' => '', 'value' => '', 'lexicon' => 'stupidquestion:properties', ), array( 'name' => 'stupidQuestionScriptcode', 'desc' => 'prop_stupidquestion.stupidQuestionScriptcode', 'type' => 'textfield', 'options' => '', 'value' => '', 'lexicon' => 'stupidquestion:properties', ), array( 'name' => 'stupidQuestionRegister', 'desc' => 'prop_stupidquestion.stupidQuestionRegister', 'type' => 'combo-boolean', 'options' => '', 'value' => false, 'lexicon' => 'stupidquestion:properties', ), array( 'name' => 'stupidQuestionNoScript', 'desc' => 'prop_stupidquestion.stupidQuestionNoScript', 'type' => 'combo-boolean', 'options' => '', 'value' => false, 'lexicon' => 'stupidquestion:properties', ) ); return $properties;<file_sep>/core/components/stupidquestion/lexicon/en/properties.inc.php <?php /** * StupidQuestion - Userfriendly Captcha for MODX Revolution * * StupidQuestion 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 2 of the License, or (at your option) any * later version. * * StupidQuestion 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 * StupidQuestion; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @package stupidquestion * @subpackage lexicon * @author <NAME> <<EMAIL>> * @copyright Copyright 2010-2013, <NAME> * * Properties English Lexicon Entries for StupidQuestion */ $_lang['prop_stupidquestion.stupidQuestionAnswers'] = 'Answers for the stupid question (JSON encoded array of \'forename name\' combinations)'; $_lang['prop_stupidquestion.stupidQuestionLanguage'] = 'Language of the stupid question'; $_lang['prop_stupidquestion.stupidQuestionFormcode'] = 'Template chunk for the stupid question html form field (defaults to the content of the file \'{core}/components/stupidquestion/templates/formcode.template.html\')'; $_lang['prop_stupidquestion.stupidQuestionScriptcode'] = 'Template chunk for the filling javascript (defaults to the content of the file \'{core}/components/stupidquestion/templates/jscode.template.js\')'; $_lang['prop_stupidquestion.stupidQuestionRegister'] = 'Move the filling javascript to the end of the html body'; $_lang['prop_stupidquestion.stupidQuestionNoScript'] = 'Remove the filling javascript'; <file_sep>/core/components/stupidquestion/elements/snippets/snippet.stupidquestion.php <?php /** * StupidQuestion - Userfriendly Captcha for MODX Revolution * * StupidQuestion 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 2 of the License, or (at your option) any * later version. * * StupidQuestion 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 * StupidQuestion; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @package stupidquestion * @subpackage snippetfile * @author <NAME> <<EMAIL>> * @copyright Copyright 2010-2013, <NAME> * @version 0.7.2 * * StupidQuestion snippet. */ $corePath = $modx->getOption('stupidquestion.core_path', null, MODX_CORE_PATH . 'components/stupidquestion/'); $options = array(); $options['answers'] = $modx->getOption('stupidQuestionAnswers', $scriptProperties, ''); $options['language'] = $modx->getOption('stupidQuestionLanguage', $scriptProperties, 'en'); $options['formcode'] = $modx->getOption('stupidQuestionFormcode', $scriptProperties, ''); $options['scriptcode'] = $modx->getOption('stupidQuestionScriptcode', $scriptProperties, ''); $options['register'] = (boolean) $modx->getOption('stupidQuestionRegister', $scriptProperties, false); $options['noscript'] = (boolean) $modx->getOption('stupidQuestionNoScript', $scriptProperties, false); // Init class include $corePath . 'model/stupidquestion/stupidquestion.class.php'; if (!isset($modx->stupidQuestion)) { $modx->stupidQuestion = new stupidQuestion($modx, $options); } if (!$options['noscript']) { if (!$options['register']) { $modx->stupidQuestion->output['htmlCode'] .= $modx->stupidQuestion->output['jsCode']; } else { $modx->regClientScript($modx->stupidQuestion->output['jsCode']); } } $modx->setPlaceholder('formit.stupidquestion_html', $modx->stupidQuestion->output['htmlCode']); if (!$modx->stupidQuestion->checkAnswer()) { $hook->addError($modx->stupidQuestion->formfield, $modx->stupidQuestion->output['errorMessage']); return false; } return true; ?> <file_sep>/core/components/stupidquestion/lexicon/de/properties.inc.php <?php /** * StupidQuestion - Userfriendly Captcha for MODX Revolution * * StupidQuestion 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 2 of the License, or (at your option) any * later version. * * StupidQuestion 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 * StupidQuestion; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @package stupidquestion * @subpackage lexicon * @author <NAME> <<EMAIL>> * @copyright Copyright 2010-2013, <NAME> * * Properties German Lexicon Entries for StupidQuestion */ $_lang['prop_stupidquestion.stupidQuestionAnswers'] = 'Antworten auf die Dumme Frage (JSON codiertes Array mit \'Vorname Name\' Kombinationen)'; $_lang['prop_stupidquestion.stupidQuestionLanguage'] = 'Sprache der Dummen Frage'; $_lang['prop_stupidquestion.stupidQuestionFormcode'] = 'Template Chunk für den HTML-Code des Formularfelds (Standard: Inhalt der Datei \'core/components/stupidquestion/templates/formcode.template.html\')'; $_lang['prop_stupidquestion.stupidQuestionScriptcode'] = 'Template Chunk für das ausfüllende Javascript (Standard: Inhalt der Datei \'core/components/stupidquestion/templates/jscode.template.js\')'; $_lang['prop_stupidquestion.stupidQuestionRegister'] = 'Verschiebe das ausfüllende Javascript an das Ende des HTML-Body'; $_lang['prop_stupidquestion.stupidQuestionNoScript'] = 'Entferne das ausfüllende Javascript';
384dc9d764126dbf7f98c97639c9d1febf78ba19
[ "Markdown", "PHP" ]
8
PHP
igor-sweet/StupidQuestion-revo
8c2d094051671a6aead0e9c058906546ad7737c9
be902e05829cecfacf45ddc4fee23220f38ac280
refs/heads/master
<repo_name>changer0/LineBreakTextView<file_sep>/app/src/main/java/com/lulu/firstchaptertextview/MainActivity.kt package com.lulu.firstchaptertextview import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView.text = "第1章 楔子:琴乱\r\n" + "T市标致性的最高的富丽堂皇的建筑物,也是T市最著名的五星级酒店,皇朝酒店。\r\n" + " 一楼的自助餐厅里人满为患。\r\n" + " 明晓殊端着一个小盘子越过人群走向角落里的一处没人坐的位置。\r\n" + " 就喜欢那里的安静,坐下去,仿佛置身于所有人之外的感觉,她只是在赏众生百相。\r\n" + " 优雅的夹了一块苹果沙拉放入口中,苹果是她最喜欢的水果之一。\r\n" + " 轻轻的咀嚼着,可是,突然间,她的唇齿停下了动作,目光不由自主的落在大门前踩着红地毯正徐徐走进皇朝的男人身上。\r\n" + " 倒抽了一口冷气,怎么也没想到会在这样的地方遇见柯以威。\r\n" + " 明晓殊先是静静的看了那个男人足有三秒钟,然后,悄然起身,直奔洗手间。\r\n" + " 不爱,那就不要遇见,更不要相见。\r\n" + " 她走得是那么的急那么的快。\r\n" + " 一袭湖水蓝的晚礼服被她拖曳着裙摆,从背后看过去,宛然就是一道绝美的风景。\r\n" + " 高跟鞋踩在地毯上发出嗒嗒嗒的闷响声,却,居然有另一道声音在她身后仿佛在配合着她的脚步声一样,就连节奏都随着她的或快或慢着。\r\n" + " 也是一个要去洗手间的人吧。\r\n" + " 就要到了,可是,眼见着前面有一间琴房,门还大敞着,她突然间的不想去洗手间了,脚步一移,顷刻间就进了琴房。\r\n" + " 白色的钢琴座落在还算宽敞的琴室里,孤单的就象是童话故事里被王子遗弃了的公主,她走过去,手指轻轻落在琴键上,立刻发出动人的琴声,美极了。\r\n" + " 那琴声勾着她的手痒了起来,就想要弹上一曲,娱已而已,这里,没有观众。\r\n" + " 一首《因为爱情》,她陶醉在其中,若是再有王菲的歌声配合着,那该有多美呢。\r\n" + " 可,当她的心还沉浸在那美妙的音乐中时,突的,肩膀上一沉,一只手不轻不重却根本让她无法抗拒的扳过了她的身体。\r\n" + " 一张邪魅而惑人的俊容放大在她的眼中,明明是为了躲他才进了这琴房的,却不想,她终还是没有躲过。\r\n" + " 心口,如小鹿般的乱撞着,身子突的被提起,然后,整个人被压倒在琴上。\r\n" + " 黑白色的键子继续奏响,却只剩下了杂乱无章,甚至,敲着她的心飞快的咚咚的跳动着。\r\n" + " 男人修长的手指勾起了她小巧的下巴,“说吧,谁让你走的?”\r\n" + " 她轻轻一笑,面对他的质问,她突的从容了,淡淡的开口,“我们,没有任何约定,而且,我不爱你。”\r\n" + " “是吗?”男人扬起轻笑,露出一截白色的牙齿,居然让他看起来该死的兴感极了。\r\n" + " “是。”她不犹豫的给他答案,脑子里在转着的却是要怎么办才能逃离他的掌控,他是豹子,白天夜晚他都有用不完的精力,她必须得智取。\r\n" + " 男人又是一笑,只是这一次带了点揶揄的味道,“可你的身体很爱很爱我。”很爱很爱,这四个字他念出来的时候重重的,让她的身体不由自主的就一颤。\r\n" + " “不……没……没有……”\r\n" + " “要不,试试?”低声说过,他的唇已经俯下,落在她的唇上轻吻着,就象是在吻着他的宝贝一样,而同时,他的一手缓缓拉起她晚礼服的下摆……\r\n" + " “啊……不要……”\r\n" + " “呵呵,还说不爱,美美,你有反应了……”他的手指移到了她的面前,他指腹上的那抹湿润让她顿时红透了半边的脸,垂下眼睑,她哀求的道:“别……别在这里,琴……”琴声还在响,响彻琴室,让她的心随之而慌乱着。\r\n" + " “可我就想在这里。”就在明晓殊半眯着眸子还在想着要怎么逃离身上的男人的时候,男人的身体徐徐俯下……\r\n" + " “啊……”她惊叫,可是回应她的只有一个又一个杂乱无章的音符,琴上的乱,乱了谁人的一颗心……\r\n" + " (本章完)" val dm = this.applicationContext.resources .displayMetrics //textView.isNeedTitle = false textView.lineBreak(dm.widthPixels) //textView.maxLines = 3 setMaxHeight.setOnClickListener{ if (textView.maxHeight == 300) { textView.maxHeight = Int.MAX_VALUE } else { textView.maxHeight = 300 } } } } <file_sep>/app/src/main/java/com/lulu/firstchaptertextview/LineBreakTextView.kt package com.lulu.firstchaptertextview import android.content.Context import android.graphics.Canvas import android.text.TextPaint import android.util.AttributeSet import android.util.Log import android.view.View /** * @author zhanglulu on 2019/12/9. * for 断行 TextView 排版 绘制 <br/> * 使用方式: <br/> * 1. 设置文本 text * 2. 排版 lineBreak */ private const val TAG = "LineBreakTextView" class LineBreakTextView : View { /** * 段首缩进 字符数 */ public var paragraphIndentSize = 2 /** * 标题间距 倍数 */ public var titleSpacingMultiplier = 2.0f /** * 段间距 倍数 */ public var paragraphSpacingMultiplier = 1.5f /** * 正文间距 倍数 */ public var lineSpacingMultiplier = 1.0f /** * 最大行数 */ public var maxLines = Int.MAX_VALUE set(value) { field = value //重新测量 requestLayout() } /** * 最大高度 */ public var maxHeight = Int.MAX_VALUE set(value) { field = value //重新测量 requestLayout() } /** * 文字大小 */ public var textSize = 48f set(value) { field = value textPaint.textSize = value } /** * 文字颜色 */ public var textColor = 0x000000 set(value) { field = value textPaint.color = value } /** * 文字透明度 */ public var textAlpha = 255 set(value) { field = value textPaint.alpha = value } /** * 是否需要标题 */ public var isNeedTitle = true /** * 标题文字大小 */ public var titleSize = 50f set(value) { field = value titlePaint.textSize = value } /** * 标题文字颜色 */ public var titleColor = 0x000000 set(value) { field = value titlePaint.color = value } /** * 标题文字透明度 */ public var titleAlpha = 255 set(value) { field = value titlePaint.alpha = value } /** * 文字位置 */ private val textPositions = ArrayList<TextPosition>() /** * 行 Y 坐标 */ private val textLineYs = ArrayList<Float>() /** * 布局高度 */ private var layoutHeight = 0f /** * 文本内容 */ var text = "" set(value) { field = value textCharArray = value.toCharArray() } private var textCharArray: CharArray?= null private var textPaint: TextPaint = TextPaint() private var titlePaint: TextPaint = TextPaint() constructor(ctx: Context) : super(ctx) {init(ctx)} constructor(ctx: Context, attrs: AttributeSet) : super(ctx,attrs) {init(ctx)} constructor(ctx: Context, attrs: AttributeSet, defStyleAttr : Int) : super(ctx,attrs, defStyleAttr) {init(ctx)} private fun init(ctx: Context) { textPaint.color = textColor textPaint.alpha = textAlpha textPaint.textSize = textSize textPaint.isAntiAlias = true//抗锯齿 titlePaint.color = titleColor titlePaint.alpha = titleAlpha titlePaint.textSize = titleSize titlePaint.isFakeBoldText = true titlePaint.isAntiAlias = true//抗锯齿 } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val width = MeasureSpec.getSize(widthMeasureSpec) var height = MeasureSpec.getSize(heightMeasureSpec) if (layoutHeight > 0 ) { height = layoutHeight.toInt() } if (getLines() > maxLines && maxLines - 1 > 0) { val textBottomH = textPaint.fontMetrics.bottom.toInt() height = (textLineYs[maxLines-1]).toInt() + paddingBottom + textBottomH } if (height > maxHeight) { height = maxHeight } setMeasuredDimension(width, height) } /** * 绘制 */ override fun draw(canvas: Canvas?) { super.draw(canvas) for (i in 0 until textPositions.size) { val textPosition = textPositions[i] val paint = if (textPosition.type == TextPosition.TITLE) { titlePaint } else { textPaint } canvas?.drawText(textPosition.text, textPosition.x, textPosition.y, paint) } } /** * 排版 */ public fun lineBreak(maxWidth: Int) { val availableWidth = maxWidth - paddingRight textLineYs.clear() textPositions.clear() //X 的初始化位置 val initX = paddingLeft.toFloat() var curX = initX var curY = paddingTop.toFloat() var isNeedCheckParagraphHeadEmptyChar = false//是否检查段首空白字符 val titleFontMetrics = titlePaint.fontMetrics val textFontMetrics = textPaint.fontMetrics val lineHeight = textFontMetrics.bottom - textFontMetrics.top //首行是否为标题 var textType = if (isNeedTitle) { curY -= titleFontMetrics.top//指定顶点坐标 TextPosition.TITLE } else { curY -= textFontMetrics.top//指定顶点坐标 TextPosition.NORMAL } val size = textCharArray?.size size?.let { var i = 0 while (i < size) { val textPosition = TextPosition() val c = textCharArray?.get(i) if (isNeedCheckParagraphHeadEmptyChar) { //空白字符判断 if (c == ' ' || c == '\u0020' || c == '\u3000') { i++ continue } } //当前文字宽度 val cW = if (textType == TextPosition.TITLE) { titlePaint.measureText(c.toString()) } else { textPaint.measureText(c.toString()) } //位置保存点 textPosition.x = curX textPosition.y = curY textPosition.text = c.toString() textPosition.type = textType //curX 向右移动一个字 curX += cW isNeedCheckParagraphHeadEmptyChar = false if (isParagraph(textCharArray, i)) { textLineYs.add(curY) //如果是段落,再移动一位 i++ curX = initX + textPaint.measureText("中") * paragraphIndentSize//段首缩进 //根据不同的文字类型设置不同的行高 curY += if (textType == TextPosition.TITLE) { (lineHeight * titleSpacingMultiplier) } else { (lineHeight * paragraphSpacingMultiplier) } isNeedCheckParagraphHeadEmptyChar = true //除了首段,后续段落都为 Normal textType = TextPosition.NORMAL } else if (isNeedNewLine(textCharArray, i, curX, availableWidth)) { textLineYs.add(curY) //断行需要回溯 curX = initX curY += lineHeight * lineSpacingMultiplier } textPositions.add(textPosition) //移动下一个游标 i++ } curY += paddingBottom layoutHeight = curY + textFontMetrics.bottom//应加上后面的Bottom Log.d(TAG, "总行数: ${textLineYs.size}" ) } } /** * 是否需要另起一行 */ private fun isNeedNewLine( charArray: CharArray?, curIndex: Int, curX: Float, maxWith: Int ) : Boolean{ charArray?.let { if (charArray.size <= curIndex+1) {//需要判断下一个 char return false } //判断下一个 char 是否到达边界 if (curX + textPaint.measureText(charArray[curIndex+1].toString()) > maxWith) { return true } } if (curX > maxWith) { return true } return false } /** * 是否是段落 */ private fun isParagraph(charArray: CharArray?, curIndex: Int): Boolean { charArray?.let { if (charArray.size <= curIndex+1) {//需要判断下一个 char return false } if (charArray[curIndex] == '\r' && charArray[curIndex+1] == '\n') { return true } } return false } /** * 获取当前的行数 */ public fun getLines(): Int { return textLineYs.size } /** * 当前文字位置 */ class TextPosition { companion object { const val NORMAL = 0x0 const val TITLE = 0x1 } var text = "" var x = 0f var y = 0f var type = NORMAL } } <file_sep>/settings.gradle include ':app' rootProject.name='FirstChapterTextView' <file_sep>/README.md ### 开始前 > 前几天做了一个需求(首章漏出),要求对一段文字可以进行分段且可以设置它的段间距,行间距等属性,大致需要以下功能点 ![LineBreakTextView 功能点](https://gitee.com/luluzhang/ImageCDN/raw/master/blog/20200120100936.png) #### 实现思路 基本的实现思路就是将每个文字进行排版布局,计算出当前文字的位置,绘制在 View 上。 ![](https://gitee.com/luluzhang/ImageCDN/raw/master/blog/20200120144421.png) #### 准备知识点 根据上述的实现思路我们需要准备下面的知识点: **canvas.drawText(x,y) 的位置问题:** 首先 x 值,有两种: - 当你的 Paint 设置为myPaint.setTextAlign(Paint.Align.LEFT),x 就是文字最左侧到当前 view 左边距的距离 - 当你的 Paint 设置为myPaint.setTextAlign(Paint.Align.CENTER),x 就是文字中央到当前 view 左边距的距离。 x 值比较容易确认,默认是为 Paint.Align.LEFT,但 y 的值并不是 text 的顶部,而是以 baseline 为基准的,y 是基线到当前 view 顶部的距离(请看下图)。 ![文字在 View 上绘制的位置](https://gitee.com/luluzhang/ImageCDN/raw/master/blog/20200120122126.png) 可以用下面代码获取到图中对应的 top,ascent,descent,bottom ``` FontMetrics fontMetrics = mPaint.getFontMetrics(); fontMetrics.top; fontMetrics.ascent; fontMetrics.descent; fontMetrics.bottom; ``` 所有的四个值都是以基线baseLine为基准来计算的。==baseline 以上的就是负的;以下的是正的。== 根据上面的值我们就可以指定 y 的位置: 中间位置 ``` float baselineY = centerY + (fontMetrics.bottom-fontMetrics.top)/2 - fontMetrics.bottom ``` 顶部位置 ``` float baselineY = Y - fontMetrics.top; ``` ![文字在 View 上绘制的 y 的 位置](https://gitee.com/luluzhang/ImageCDN/raw/master/blog/20200120114719.png) ### LineBreadkTextView 的实现 > 具备上面的内容,我们就可以是实现支持段落的 TextView 了。 首先写一个 LineBreakTextView 继承自 View,重写必要方法 ``` class LineBreakTextView : View { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) //... } override fun draw(canvas: Canvas?) { super.draw(canvas) //... } } ``` #### 排版 为了能够确认每个文字的位置我们添加一个用来描述当前文字位置的实体内部类,并声明一个全局的List: ``` /** * 文字位置 */ private val textPositions = ArrayList<TextPosition>() class TextPosition { companion object { const val NORMAL = 0x0 const val TITLE = 0x1 } var text = "" var x = 0f var y = 0f var type = NORMAL } ``` > 其中 type 用来表示是标题还是正文 在 LineBreakTextView 中添加 lineBreak(maxWidth: Int) 方法,用来排版,并声明两个局部变量用 curX curY 用来表示当前文字的位置 ``` public fun lineBreak(maxWidth: Int) { val availableWidth = maxWidth - paddingRight textLineYs.clear() textPositions.clear() //X 的初始化位置 val initX = paddingLeft.toFloat() var curX = initX var curY = paddingTop.toFloat() //... } ``` 取出标题和正文的 fontMetrics,方便后面使用,并计算出正文的 1 倍行高 ``` public fun lineBreak(maxWidth: Int) { //... val titleFontMetrics = titlePaint.fontMetrics val textFontMetrics = textPaint.fontMetrics val lineHeight = textFontMetrics.bottom - textFontMetrics.top //... } ``` textType 用来确认当前文字类型,结合之前描述通过指定文字顶部位置的方式来确认文字的 y 位置 ``` public fun lineBreak(maxWidth: Int) { //... //首行是否为标题 var textType = if (isNeedTitle) { curY -= titleFontMetrics.top//指定顶点坐标 TextPosition.TITLE } else { curY -= textFontMetrics.top//指定顶点坐标 TextPosition.NORMAL } //... } ``` 准备工作做完之后开始计算文字位置,并保存在 textPositions 中 ,下面代码用来计算 x 的位置: ``` /** * 文本内容 */ var text = "" set(value) { field = value textCharArray = value.toCharArray() } ``` ``` public fun lineBreak(maxWidth: Int) { //... val size = textCharArray?.size size?.let { var i = 0 while (i < size) { val textPosition = TextPosition() val c = textCharArray?.get(i) //... //当前文字宽度 val cW = if (textType == TextPosition.TITLE) { titlePaint.measureText(c.toString()) } else { textPaint.measureText(c.toString()) } //位置保存点 textPosition.x = curX textPosition.y = curY textPosition.text = c.toString() textPosition.type = textType //curX 向右移动一个字 curX += cW //... textPositions.add(textPosition) //移动下一个游标 i++ } curY += paddingBottom layoutHeight = curY + textFontMetrics.bottom//应加上后面的Bottom } //... } ``` 仔细观察会发现,上面的代码并没有断行的情况,接下来通过计算 y 的位置来生成断行后的 x 的位置 y 的位置相对复杂,因为还有考虑行高和段高等问题, isParagraph 该方法是来判断是否是段末,如果是段末则 x 位置设置段首缩进,y 根据当前文字类型设置段高,isNeedNewLine 方法用来判断文字是否到达行末,如果到达之后,x 位置回溯到初始位置,y 则设置正文行高 ``` //... //curX 向右移动一个字 curX += cW if (isParagraph(textCharArray, i)) { //如果是段落,再移动一位 i++ curX = initX + textPaint.measureText("中") * paragraphIndentSize//段首缩进 //根据不同的文字类型设置不同的行高 curY += if (textType == TextPosition.TITLE) { (lineHeight * titleSpacingMultiplier) } else { (lineHeight * paragraphSpacingMultiplier) } //除了首段,后续段落都为 Normal textType = TextPosition.NORMAL } else if (isNeedNewLine(textCharArray, i, curX, availableWidth)) { textLineYs.add(curY) //断行需要回溯 curX = initX curY += lineHeight * lineSpacingMultiplier } //... ``` 下面是两个方法的具体实现 ``` /** * 是否需要另起一行 */ private fun isNeedNewLine( charArray: CharArray?, curIndex: Int, curX: Float, maxWith: Int ) : Boolean{ charArray?.let { if (charArray.size <= curIndex+1) {//需要判断下一个 char return false } //判断下一个 char 是否到达边界 if (curX + textPaint.measureText(charArray[curIndex+1].toString()) > maxWith) { return true } } if (curX > maxWith) { return true } return false } /** * 是否是段落 */ private fun isParagraph(charArray: CharArray?, curIndex: Int): Boolean { charArray?.let { if (charArray.size <= curIndex+1) {//需要判断下一个 char return false } if (charArray[curIndex] == '\r' && charArray[curIndex+1] == '\n') { return true } } return false } ``` #### 测量 针对咱们的 LineBreakTextView 只需关心当前 View 的高度 为了实现可以设置 maxLines 需要记录下每一行的 y 坐标 ``` /** * 行 Y 坐标 */ private val textLineYs = ArrayList<Float>() ``` 记录 y 坐标 ``` public fun lineBreak(maxWidth: Int) { textLineYs.clear() //... if (isParagraph(textCharArray, i)) { textLineYs.add(curY) //... } else if (isNeedNewLine(textCharArray, i, curX, availableWidth)) { textLineYs.add(curY) //... } //... } ``` 完成测量 ``` override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val width = MeasureSpec.getSize(widthMeasureSpec) var height = MeasureSpec.getSize(heightMeasureSpec) if (layoutHeight > 0 ) { height = layoutHeight.toInt() } if (getLines() > maxLines && maxLines - 1 > 0) { val textBottomH = textPaint.fontMetrics.bottom.toInt() height = (textLineYs[maxLines-1]).toInt() + paddingBottom + textBottomH } if (height > maxHeight) { height = maxHeight } setMeasuredDimension(width, height) } ``` #### 绘制 绘制相对简单些,在完成了排版之后,位置都已经记录了下来直接画在 canvas 上即可。 ``` override fun draw(canvas: Canvas?) { super.draw(canvas) for (i in 0 until textPositions.size) { val textPosition = textPositions[i] val paint = if (textPosition.type == TextPosition.TITLE) { titlePaint } else { textPaint } canvas?.drawText(textPosition.text, textPosition.x, textPosition.y, paint) } } ``` ### 效果展示 在布局中添加 LineBreakTextView,在 Activity 中做如下设置: ``` override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView.text = "第1章 楔子:琴乱\r\n...." val dm = this.applicationContext.resources .displayMetrics textView.lineBreak(dm.widthPixels) } ``` 效果图 ![效果图](https://gitee.com/luluzhang/ImageCDN/raw/master/blog/20200120160623.jpg) ### Github 地址 https://github.com/changer0/LineBreakTextView
ba6703123ceac84669168b2f74fe11659ad97f9d
[ "Markdown", "Kotlin", "Gradle" ]
4
Kotlin
changer0/LineBreakTextView
db3048b84e50af11febbb33cb2499ce78e768c43
9a804423fde9632a83d1a061e7a2d2ade2f065f6
refs/heads/master
<repo_name>wuyohee2004/tornadoapp<file_sep>/myweb/blog/views.py from django.shortcuts import render_to_response # Create your views here. from django.http import HttpResponseRedirect from models import * def home(request): # print request # print '+'*100 # print dir(request) # print '+'*100 # print request.environ['USERNAME'] return render_to_response('index.html') def blog(request,id): # temp_str = "The Blog ID is {{ blog_id }}" # t = Template(temp_str) # c = Context({'blog_id':id}) # html = t.render(c) article = Article.objects.get(id=id) comments = Comment.objects.filter(Article=id).order_by("-id").all() print comments return render_to_response('blog.html',{'article':article,'comments':comments}) # return HttpResponse(html) def add(request): if request.method == 'POST': content = request.POST.get('content',None) title = request.POST.get('title',None) new = Article(content=content.encode("utf-8"),title=title.encode("utf-8")) new.save() return HttpResponseRedirect('/list/') return render_to_response('add.html',{'method_str':request.method}) def list(request): articles = Article.objects.order_by("-id").all() return render_to_response('list.html',{'articles':articles}) def comment_add(request): if request.method== 'POST': article_id = request.POST.get('article','') detail = request.POST.get('detail','') print detail if article_id and detail: comment = Comment() comment.Article = Article(id = article_id) comment.detail = detail comment.save() return HttpResponseRedirect('/blog/topic_%s' % article_id) <file_sep>/test.py #coding:utf-8 import re print re.compile(ur"@([\u4E00-\u9FA5\w-]+)").findall(u"@童鞋们@123 @_abd")<file_sep>/project_tornado/myweb.py import os import signal import logging from tornado import web,ioloop from tornado import options is_closing = False def signal_handler(signum, frame): global is_closing logging.info('exiting...') is_closing = True def try_exit(): global is_closing if is_closing: # clean up here ioloop.IOLoop.instance().stop() logging.info('exit success') class MainHandler(web.RequestHandler): def get(self): self.write("Hello get") def post(self): self.write("Hello post") def put(self): self.write("Hello put") # def delete(self): # self.write("Hello delete") if __name__ == "__main__": settings = { 'debug':True, 'static_path':os.path.join(os.path.dirname(__file__),"static"), 'template_path':os.path.join(os.path.dirname(__file__),"templates"), } application = web.Application([ (r"/",MainHandler), ],**settings) options.parse_command_line() signal.signal(signal.SIGINT, signal_handler) application.listen(8888) ioloop.PeriodicCallback(try_exit, 100).start() ioloop.IOLoop.instance().start() <file_sep>/myweb/blog/models.py from django.db import models # Create your models here. # <primitive> # CREATE TABLE "article"( # "id" serial NOT NULL PRIMARY KEY, # "title" varchar(30) NOT NULL, # "content" text NOT NULL, # ); #<orm> class Article(models.Model): title = models.CharField(max_length=30) content = models.TextField() class Comment(models.Model): Article = models.ForeignKey(Article,related_name="article_comment") detail = models.TextField()<file_sep>/project_tornado/auth.py #coding-utf-8 import os import re import time import tornado.auth import tornado.escape import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web from tornado.options import define, options from pymongo import errors as mongoerr from settings import db define("port", default=8888, help="run on the given port", type=int) def get_tags(content):#tornado default input always encode to utf-8 r = re.compile(ur"@([\u4E00-\u9FA5\w-]+)") return r.findall(content) class BaseHandler(tornado.web.RequestHandler): def get_current_user(self): return self.get_secure_cookie("user") class WeiboHandler(BaseHandler): @tornado.web.authenticated def get(self): return self.render("weibo_add.html") @tornado.web.authenticated def post(self): result = self.get_argument("content",None) print get_tags(result) db.weibo.insert({"content":result,"user":self.get_current_user(),"ts":time.time()}) self.write(result) class MainHandler(BaseHandler): @tornado.web.authenticated def get(self): name = tornado.escape.xhtml_escape(self.current_user) self.write("Hello, " + name) # self.write("<br><br><a href=\"/auth/logout\">Log out</a>") class UserInfoHandler(BaseHandler): @tornado.web.authenticated def get(self): user = self.get_current_user() self.render("userinfo.html" , **{"user":user}) class RegisterHandler(BaseHandler): def get(self): self.render("register.html") def post(self): account = self.get_argument("account") password = self.get_argument("password") if account == '' or password == '': self.write("Username or Password not filled!") elif db.user.find({"account":account}).count() > 0: return self.write("<h1>User Already Registered! Don't duplicate apply.</h1>") else: db.user.insert({"account":account,"password":<PASSWORD>}) self.set_secure_cookie("user",account) self.redirect("/user") class UsersHandler(BaseHandler): @tornado.web.authenticated def get(self): # users = db.user.find({"account":{"$ne":self.get_current_user()}}) #ne is str not in result followed_users = db.follow.find({"user":self.get_current_user()},{"follow_user":1}) filter_users = [follow["follow_user"] for follow in followed_users] filter_users.append(self.get_current_user()) users = db.user.find({"account":{"$nin":filter_users}})#nin is not in list self.render("user_list.html",**{"users":users}) class FollowHandler(BaseHandler): @tornado.web.authenticated def get(self): user = self.get_argument("follow_user",None) if not user: return self.redirect("/users") try: db.follow.insert({"follow_user":user,"user":self.get_current_user()}) except mongoerr.DuplicateKeyError: return self.write("Already followed: %s" % user) return self.redirect("/followed") class FollowedHandler(BaseHandler): @tornado.web.authenticated def get(self): followed_users = db.follow.find({"user":self.get_current_user()}) self.render("followed_user.html",**{"followed_users":followed_users}) # class AuthHandler(BaseHandler, tornado.auth.GoogleMixin): # @tornado.web.asynchronous # def get(self): # if self.get_argument("openid.mode", None): # self.get_authenticated_user(self.async_callback(self._on_auth)) # return # self.authenticate_redirect() # # def _on_auth(self, user): # if not user: # raise tornado.web.HTTPError(500, "Google auth failed") # self.set_secure_cookie("user", tornado.escape.json_encode(user)) # self.redirect("/") class LoginHandler(BaseHandler): def get(self): self.render("login.html") def post(self): # self.clear_cookie("user") account,password = '','' try: account = self.get_argument("account") password = self.get_argument("password") except tornado.web.HTTPError: pass user = db.user.find_one({"account":account},{"account":1,"password":1}) print user if account =='' or password =='': return self.write("password or username not filled!") # elif db.user.find({"account":account,"password":password}).count() == 0: # return self.write("password or username invalid! Please input correctly") elif not user: return self.write("User dosn't existed!") elif user['password'] != password: return self.write("wrong password!") self.set_secure_cookie("user",self.get_argument("account")) self.redirect("/user") settings = { "cookie_secret":"<KEY> "login_url":"/login", # "xsrf_cookies": True, "template_path":os.path.join(os.path.dirname(__file__), "templates"), "static_path":os.path.join(os.path.dirname(__file__), "static"), } Application = tornado.web.Application([ (r"/", MainHandler), (r"/login", LoginHandler), (r"/weibo/add", WeiboHandler), (r"/register", RegisterHandler), (r"/user", UserInfoHandler), (r"/users", UsersHandler), (r"/follow", FollowHandler), (r"/followed", FollowedHandler), ],**settings) def main(): tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(Application) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__": main() re.compile(ur"@([\u4E00-\u9FA5\w-]+?)") <file_sep>/project_tornado/chat/test.py import os print os.path.join(os.path.dirname(__file__), "static.js")<file_sep>/settings.py #coding-utf-8 from pymongo import MongoClient client = MongoClient('localhost',27017) db = client['weibo'] <file_sep>/spider_1.py #coding=utf-8 import urllib import json from bs4 import BeautifulSoup as bs # html = urllib.urlopen('http://search.jd.com/Search?keyword=%E7%94%B7%E9%9E%8B&enc=utf-8#keyword=%E7%94%B7%E9%9E%8B&enc=utf-8&qrst=UNEXPAND&qk=title_key%2C%2C%E7%94%B7%E9%9E%8B&rt=1&stop=1&sttr=1&cid2=11730&click=2-11730&psort=&page=2').read() # print html # # content = html.decode('gbk') # t = open('temp.html','w') # t.write(html) # t.close() # JD Search Url: # 'http://search.jd.com/Search?keyword=%E7%94%B7%E9%9E%8B&enc=utf-8&rt=1&page=2' # JD JSON: # http://p.3.cn/prices/mgets?skuids=J_860275,J_1168467,J_1102758,J_1096008,J_833315,J_1074152,J_1266675,J_1074153,J_1062989,J_1229308,J_1082433,J_1102752,J_1134530,J_1102727,J_1242910,J_1257557,J_1074151,J_1134535,J_1084906755,J_1096007,J_1183079,J_1102755,J_1102764,J_1063013,J_1266674,J_1074894,J_1435902426,J_1378682319,J_1093367,J_1133172534&area=2_2811_0_0&type=1&callback=jsonp1424075501802&_=1424075501981 # JD list in: # <div class="m psearch prebuy plist-n7 no-preview gl-type-6" id="plist"> # <ul class="list-h clearfix" tpl="1"> # <li sku="860275"> # <div class="lh-wrap"> # <div class="p-img"> # <a target="_blank" href="http://item.jd.com/1459465605.html" onclick="searchlog(1,1459465605,0,2,'','')"> # <img width="220" height="220" data-img="1" src="http://img10.360buyimg.com/n7/jfs/t757/166/716382293/302509/8661b643/54d2e8c0N37b54d3f.jpg" class="err-product"> # </a> def get_content_from_jd(keyword,page=1): url = 'http://search.jd.com/Search?' params = {'keyword':keyword,'page':page,'rt':1,'enc':'utf-8'} data = urllib.urlencode(params) r = urllib.urlopen(url+data) content = r.read() r.close() return content # print get_content_from_jd("3d电视") #*ids = (可迭代) def get_price_from_ds(*ids): url = 'http://p.3.cn/prices/mgets?' params = {'skuids':','.join(['J_%s'%id for id in ids]),'type':1} data = urllib.urlencode(params) opener = urllib.urlopen(url + data) response = opener.read() opener.close() return json.loads(response) def get_res_from_jd(keyword,page=1): #返回一个{id:xx,price:xx,detail:xx,title:xx} pass if __name__ == "__main__": content = get_content_from_jd(keyword="纸尿裤",page=4) soup = bs(content) mids = soup.find_all(sku=True) # print mids[0],"\n","+"*200,"\n",mids[1] ids = [mid['sku'] for mid in mids] # print ids prices = get_price_from_ds(*ids) # print prices res = [] for mid in mids: data = {} data['id'] = mid['sku'] data['img'] = mid.find('img')['data-lazyload'] aobj = mid.find(class_ = 'p-name').find('a') data['url'] = aobj['href'] data['title'] = aobj.text.strip() data['price'] = filter(lambda price:price['id']=='J_%s'%data['id'],prices)[0]['p'] data['ori_price'] = filter(lambda price:price['id']=='J_%s'%data['id'],prices)[0]['m'] res.append(data) # print(res) for prod in res: print prod['title'] print prod['id'] print prod['price'] print prod['ori_price'] print prod['img']<file_sep>/main.py #coding=utf-8 # # from weibo import APIClient # #1.生成URL过程 # APP_KEY = '1173024669' # APP_SECRET = '<KEY>' # CALLBACK_URL = 'http://e.com/weibo/callback' # # client = APIClient(app_key=APP_KEY,app_secret=APP_SECRET,redirect_uri=CALLBACK_URL) # url = client.get_authorize_url() # # print url # # #2.授权成功后会跳到callback url,并传一个code参数 # code = url.web.framework.request.get('code') # r = client.request_access_token(code) # access_token = r.access_token # 新浪返回的token,类似<PASSWORD> # expires_in = r.expires_in # token过期的UNIX时间:http://zh.wikipedia.org/wiki/UNIX%E6%97%B6%E9%97%B4 # # TODO: 在此可保存access token # client.set_access_token(access_token, expires_in) import wmi def sys_version(): conn = wmi.WMI(computer='192.168.2.2',user=r'.\jin',password='111') a=conn.Win32_Process.Create(CommandLine='query user') print(a) if __name__ == '__main__': user=r'JIN-PC\jin' print user sys_version()
31bf8d55985718ff975ef681ee112e15007f60e1
[ "Python" ]
9
Python
wuyohee2004/tornadoapp
27f6add4a95ae1883391331a86ec9900f8d1b382
8cdff646f5910e4f32f8124b14a3ab8ad200f021
refs/heads/master
<repo_name>Deep-Akash/CalculatorAPIGateway<file_sep>/src/main/java/com/calculator/calculatorapigateway/user/service/UserService.java package com.calculator.calculatorapigateway.user.service; import com.calculator.calculatorapigateway.user.service.exception.APIBaseException; import com.calculator.calculatorapigateway.user.service.model.APIResponse; import com.calculator.calculatorapigateway.user.service.model.User; import com.calculator.calculatorapigateway.user.service.service.CalculatorConnectionService; import com.calculator.calculatorapigateway.user.service.service.PropertyProviderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private PropertyProviderService propertyProviderService; @Autowired private CalculatorConnectionService calculatorConnectionService; public User getUser(String emailId) throws APIBaseException { APIResponse response = calculatorConnectionService.GET(propertyProviderService.getUserServiceFetchURL().concat(emailId)); if (!response.getSuccess()){ throw new APIBaseException(response.getCode(),response.getMessage()); } return User.buildFromData(response.getData()); } } <file_sep>/src/main/resources/application.properties zuul.routes.calculator.url=http://localhost:8080 ribbon.eureka.enabled=false server.port=8089
3b4930b0a0d14bde676bfb0e6b9a79db22cbe698
[ "Java", "INI" ]
2
Java
Deep-Akash/CalculatorAPIGateway
d095c4bcc5d81269ff7b142e4fb62421d186b6c4
8eea42a26296b544b514988799bfe1532fbac2a5
refs/heads/master
<file_sep>package com.gestionhotel.gestionhotel; public class Aeffacer { }
d02b5d682624268212e31894761720106b43f5a3
[ "Java" ]
1
Java
gestionhotel/TP2
25e48be887dbb6f65e4f5215633f3b20f1354bae
94064171577f2cfebb8a0917020ab3f68e9af7b3