How to use wheel method in Puppeteer

Best JavaScript code snippet using puppeteer

wheel_builder.py

Source:wheel_builder.py Github

copy

Full Screen

1"""Orchestrator for building wheels from InstallRequirements.2"""3import logging4import os.path5import re6import shutil7from pip._internal.models.link import Link8from pip._internal.operations.build.wheel import build_wheel_pep5179from pip._internal.operations.build.wheel_legacy import build_wheel_legacy10from pip._internal.utils.logging import indent_log11from pip._internal.utils.misc import ensure_dir, hash_file, is_wheel_installed12from pip._internal.utils.setuptools_build import make_setuptools_clean_args13from pip._internal.utils.subprocess import call_subprocess14from pip._internal.utils.temp_dir import TempDirectory15from pip._internal.utils.typing import MYPY_CHECK_RUNNING16from pip._internal.utils.urls import path_to_url17from pip._internal.vcs import vcs18if MYPY_CHECK_RUNNING:19 from typing import (20 Any, Callable, Iterable, List, Optional, Tuple,21 )22 from pip._internal.cache import WheelCache23 from pip._internal.req.req_install import InstallRequirement24 BinaryAllowedPredicate = Callable[[InstallRequirement], bool]25 BuildResult = Tuple[List[InstallRequirement], List[InstallRequirement]]26logger = logging.getLogger(__name__)27_egg_info_re = re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.IGNORECASE)28def _contains_egg_info(s):29 # type: (str) -> bool30 """Determine whether the string looks like an egg_info.31 :param s: The string to parse. E.g. foo-2.132 """33 return bool(_egg_info_re.search(s))34def _should_build(35 req, # type: InstallRequirement36 need_wheel, # type: bool37 check_binary_allowed, # type: BinaryAllowedPredicate38):39 # type: (...) -> bool40 """Return whether an InstallRequirement should be built into a wheel."""41 if req.constraint:42 # never build requirements that are merely constraints43 return False44 if req.is_wheel:45 if need_wheel:46 logger.info(47 'Skipping %s, due to already being wheel.', req.name,48 )49 return False50 if need_wheel:51 # i.e. pip wheel, not pip install52 return True53 # From this point, this concerns the pip install command only54 # (need_wheel=False).55 if req.editable or not req.source_dir:56 return False57 if not check_binary_allowed(req):58 logger.info(59 "Skipping wheel build for %s, due to binaries "60 "being disabled for it.", req.name,61 )62 return False63 if not req.use_pep517 and not is_wheel_installed():64 # we don't build legacy requirements if wheel is not installed65 logger.info(66 "Using legacy 'setup.py install' for %s, "67 "since package 'wheel' is not installed.", req.name,68 )69 return False70 return True71def should_build_for_wheel_command(72 req, # type: InstallRequirement73):74 # type: (...) -> bool75 return _should_build(76 req, need_wheel=True, check_binary_allowed=_always_true77 )78def should_build_for_install_command(79 req, # type: InstallRequirement80 check_binary_allowed, # type: BinaryAllowedPredicate81):82 # type: (...) -> bool83 return _should_build(84 req, need_wheel=False, check_binary_allowed=check_binary_allowed85 )86def _should_cache(87 req, # type: InstallRequirement88):89 # type: (...) -> Optional[bool]90 """91 Return whether a built InstallRequirement can be stored in the persistent92 wheel cache, assuming the wheel cache is available, and _should_build()93 has determined a wheel needs to be built.94 """95 if req.editable or not req.source_dir:96 # never cache editable requirements97 return False98 if req.link and req.link.is_vcs:99 # VCS checkout. Do not cache100 # unless it points to an immutable commit hash.101 assert not req.editable102 assert req.source_dir103 vcs_backend = vcs.get_backend_for_scheme(req.link.scheme)104 assert vcs_backend105 if vcs_backend.is_immutable_rev_checkout(req.link.url, req.source_dir):106 return True107 return False108 assert req.link109 base, ext = req.link.splitext()110 if _contains_egg_info(base):111 return True112 # Otherwise, do not cache.113 return False114def _get_cache_dir(115 req, # type: InstallRequirement116 wheel_cache, # type: WheelCache117):118 # type: (...) -> str119 """Return the persistent or temporary cache directory where the built120 wheel need to be stored.121 """122 cache_available = bool(wheel_cache.cache_dir)123 assert req.link124 if cache_available and _should_cache(req):125 cache_dir = wheel_cache.get_path_for_link(req.link)126 else:127 cache_dir = wheel_cache.get_ephem_path_for_link(req.link)128 return cache_dir129def _always_true(_):130 # type: (Any) -> bool131 return True132def _build_one(133 req, # type: InstallRequirement134 output_dir, # type: str135 build_options, # type: List[str]136 global_options, # type: List[str]137):138 # type: (...) -> Optional[str]139 """Build one wheel.140 :return: The filename of the built wheel, or None if the build failed.141 """142 try:143 ensure_dir(output_dir)144 except OSError as e:145 logger.warning(146 "Building wheel for %s failed: %s",147 req.name, e,148 )149 return None150 # Install build deps into temporary directory (PEP 518)151 with req.build_env:152 return _build_one_inside_env(153 req, output_dir, build_options, global_options154 )155def _build_one_inside_env(156 req, # type: InstallRequirement157 output_dir, # type: str158 build_options, # type: List[str]159 global_options, # type: List[str]160):161 # type: (...) -> Optional[str]162 with TempDirectory(kind="wheel") as temp_dir:163 assert req.name164 if req.use_pep517:165 assert req.metadata_directory166 wheel_path = build_wheel_pep517(167 name=req.name,168 backend=req.pep517_backend,169 metadata_directory=req.metadata_directory,170 build_options=build_options,171 tempd=temp_dir.path,172 )173 else:174 wheel_path = build_wheel_legacy(175 name=req.name,176 setup_py_path=req.setup_py_path,177 source_dir=req.unpacked_source_directory,178 global_options=global_options,179 build_options=build_options,180 tempd=temp_dir.path,181 )182 if wheel_path is not None:183 wheel_name = os.path.basename(wheel_path)184 dest_path = os.path.join(output_dir, wheel_name)185 try:186 wheel_hash, length = hash_file(wheel_path)187 shutil.move(wheel_path, dest_path)188 logger.info('Created wheel for %s: '189 'filename=%s size=%d sha256=%s',190 req.name, wheel_name, length,191 wheel_hash.hexdigest())192 logger.info('Stored in directory: %s', output_dir)193 return dest_path194 except Exception as e:195 logger.warning(196 "Building wheel for %s failed: %s",197 req.name, e,198 )199 # Ignore return, we can't do anything else useful.200 if not req.use_pep517:201 _clean_one_legacy(req, global_options)202 return None203def _clean_one_legacy(req, global_options):204 # type: (InstallRequirement, List[str]) -> bool205 clean_args = make_setuptools_clean_args(206 req.setup_py_path,207 global_options=global_options,208 )209 logger.info('Running setup.py clean for %s', req.name)210 try:211 call_subprocess(clean_args, cwd=req.source_dir)212 return True213 except Exception:214 logger.error('Failed cleaning build dir for %s', req.name)215 return False216def build(217 requirements, # type: Iterable[InstallRequirement]218 wheel_cache, # type: WheelCache219 build_options, # type: List[str]220 global_options, # type: List[str]221):222 # type: (...) -> BuildResult223 """Build wheels.224 :return: The list of InstallRequirement that succeeded to build and225 the list of InstallRequirement that failed to build.226 """227 if not requirements:228 return [], []229 # Build the wheels.230 logger.info(231 'Building wheels for collected packages: %s',232 ', '.join(req.name for req in requirements), # type: ignore233 )234 with indent_log():235 build_successes, build_failures = [], []236 for req in requirements:237 cache_dir = _get_cache_dir(req, wheel_cache)238 wheel_file = _build_one(239 req, cache_dir, build_options, global_options240 )241 if wheel_file:242 # Update the link for this.243 req.link = Link(path_to_url(wheel_file))244 req.local_file_path = req.link.file_path245 assert req.link.is_wheel246 build_successes.append(req)247 else:248 build_failures.append(req)249 # notify success/failure250 if build_successes:251 logger.info(252 'Successfully built %s',253 ' '.join([req.name for req in build_successes]), # type: ignore254 )255 if build_failures:256 logger.info(257 'Failed to build %s',258 ' '.join([req.name for req in build_failures]), # type: ignore259 )260 # Return a list of requirements that failed to build...

Full Screen

Full Screen

Car.js

Source:Car.js Github

copy

Full Screen

1/**2 * @author alteredq / http://alteredqualia.com/3 */4THREE.Car = function () {5 var scope = this;6 // car geometry manual parameters7 this.modelScale = 1;8 this.backWheelOffset = 2;9 this.autoWheelGeometry = true;10 // car geometry parameters automatically set from wheel mesh11 // - assumes wheel mesh is front left wheel in proper global12 // position with respect to body mesh13 // - other wheels are mirrored against car root14 // - if necessary back wheels can be offset manually15 this.wheelOffset = new THREE.Vector3();16 this.wheelDiameter = 1;17 // car "feel" parameters18 this.MAX_SPEED = 2200;19 this.MAX_REVERSE_SPEED = -1500;20 this.MAX_WHEEL_ROTATION = 0.6;21 this.FRONT_ACCELERATION = 1250;22 this.BACK_ACCELERATION = 1500;23 this.WHEEL_ANGULAR_ACCELERATION = 1.5;24 this.FRONT_DECCELERATION = 750;25 this.WHEEL_ANGULAR_DECCELERATION = 1.0;26 this.STEERING_RADIUS_RATIO = 0.0023;27 this.MAX_TILT_SIDES = 0.05;28 this.MAX_TILT_FRONTBACK = 0.015;29 // internal control variables30 this.speed = 0;31 this.acceleration = 0;32 this.wheelOrientation = 0;33 this.carOrientation = 0;34 // car rigging35 this.root = new THREE.Object3D();36 this.frontLeftWheelRoot = new THREE.Object3D();37 this.frontRightWheelRoot = new THREE.Object3D();38 this.bodyMesh = null;39 this.frontLeftWheelMesh = null;40 this.frontRightWheelMesh = null;41 this.backLeftWheelMesh = null;42 this.backRightWheelMesh = null;43 this.bodyGeometry = null;44 this.wheelGeometry = null;45 this.bodyMaterials = null;46 this.wheelMaterials = null;47 // internal helper variables48 this.loaded = false;49 this.meshes = [];50 // API51 this.enableShadows = function ( enable ) {52 for ( var i = 0; i < this.meshes.length; i ++ ) {53 this.meshes[ i ].castShadow = enable;54 this.meshes[ i ].receiveShadow = enable;55 }56 };57 this.setVisible = function ( enable ) {58 for ( var i = 0; i < this.meshes.length; i ++ ) {59 this.meshes[ i ].visible = enable;60 this.meshes[ i ].visible = enable;61 }62 };63 this.loadPartsJSON = function ( bodyURL, wheelURL ) {64 var loader = new THREE.JSONLoader();65 loader.load( bodyURL, function( geometry, materials ) { createBody( geometry, materials ) } );66 loader.load( wheelURL, function( geometry, materials ) { createWheels( geometry, materials ) } );67 };68 this.loadPartsBinary = function ( bodyURL, wheelURL ) {69 var loader = new THREE.BinaryLoader();70 loader.load( bodyURL, function( geometry, materials ) { createBody( geometry, materials ) } );71 loader.load( wheelURL, function( geometry, materials ) { createWheels( geometry, materials ) } );72 };73 this.updateCarModel = function ( delta, controls ) {74 // speed and wheels based on controls75 if ( controls.moveForward ) {76 this.speed = THREE.Math.clamp( this.speed + delta * this.FRONT_ACCELERATION, this.MAX_REVERSE_SPEED, this.MAX_SPEED );77 this.acceleration = THREE.Math.clamp( this.acceleration + delta, -1, 1 );78 }79 if ( controls.moveBackward ) {80 this.speed = THREE.Math.clamp( this.speed - delta * this.BACK_ACCELERATION, this.MAX_REVERSE_SPEED, this.MAX_SPEED );81 this.acceleration = THREE.Math.clamp( this.acceleration - delta, -1, 1 );82 }83 if ( controls.moveLeft ) {84 this.wheelOrientation = THREE.Math.clamp( this.wheelOrientation + delta * this.WHEEL_ANGULAR_ACCELERATION, - this.MAX_WHEEL_ROTATION, this.MAX_WHEEL_ROTATION );85 }86 if ( controls.moveRight ) {87 this.wheelOrientation = THREE.Math.clamp( this.wheelOrientation - delta * this.WHEEL_ANGULAR_ACCELERATION, - this.MAX_WHEEL_ROTATION, this.MAX_WHEEL_ROTATION );88 }89 // speed decay90 if ( ! ( controls.moveForward || controls.moveBackward ) ) {91 if ( this.speed > 0 ) {92 var k = exponentialEaseOut( this.speed / this.MAX_SPEED );93 this.speed = THREE.Math.clamp( this.speed - k * delta * this.FRONT_DECCELERATION, 0, this.MAX_SPEED );94 this.acceleration = THREE.Math.clamp( this.acceleration - k * delta, 0, 1 );95 } else {96 var k = exponentialEaseOut( this.speed / this.MAX_REVERSE_SPEED );97 this.speed = THREE.Math.clamp( this.speed + k * delta * this.BACK_ACCELERATION, this.MAX_REVERSE_SPEED, 0 );98 this.acceleration = THREE.Math.clamp( this.acceleration + k * delta, -1, 0 );99 }100 }101 // steering decay102 if ( ! ( controls.moveLeft || controls.moveRight ) ) {103 if ( this.wheelOrientation > 0 ) {104 this.wheelOrientation = THREE.Math.clamp( this.wheelOrientation - delta * this.WHEEL_ANGULAR_DECCELERATION, 0, this.MAX_WHEEL_ROTATION );105 } else {106 this.wheelOrientation = THREE.Math.clamp( this.wheelOrientation + delta * this.WHEEL_ANGULAR_DECCELERATION, - this.MAX_WHEEL_ROTATION, 0 );107 }108 }109 // car update110 var forwardDelta = this.speed * delta;111 this.carOrientation += ( forwardDelta * this.STEERING_RADIUS_RATIO )* this.wheelOrientation;112 // displacement113 this.root.position.x += Math.sin( this.carOrientation ) * forwardDelta;114 this.root.position.z += Math.cos( this.carOrientation ) * forwardDelta;115 // steering116 this.root.rotation.y = this.carOrientation;117 // tilt118 if ( this.loaded ) {119 this.bodyMesh.rotation.z = this.MAX_TILT_SIDES * this.wheelOrientation * ( this.speed / this.MAX_SPEED );120 this.bodyMesh.rotation.x = - this.MAX_TILT_FRONTBACK * this.acceleration;121 }122 // wheels rolling123 var angularSpeedRatio = 1 / ( this.modelScale * ( this.wheelDiameter / 2 ) );124 var wheelDelta = forwardDelta * angularSpeedRatio;125 if ( this.loaded ) {126 this.frontLeftWheelMesh.rotation.x += wheelDelta;127 this.frontRightWheelMesh.rotation.x += wheelDelta;128 this.backLeftWheelMesh.rotation.x += wheelDelta;129 this.backRightWheelMesh.rotation.x += wheelDelta;130 }131 // front wheels steering132 this.frontLeftWheelRoot.rotation.y = this.wheelOrientation;133 this.frontRightWheelRoot.rotation.y = this.wheelOrientation;134 };135 // internal helper methods136 function createBody ( geometry, materials ) {137 scope.bodyGeometry = geometry;138 scope.bodyMaterials = materials;139 createCar();140 };141 function createWheels ( geometry, materials ) {142 scope.wheelGeometry = geometry;143 scope.wheelMaterials = materials;144 createCar();145 };146 function createCar () {147 if ( scope.bodyGeometry && scope.wheelGeometry ) {148 // compute wheel geometry parameters149 if ( scope.autoWheelGeometry ) {150 scope.wheelGeometry.computeBoundingBox();151 var bb = scope.wheelGeometry.boundingBox;152 scope.wheelOffset.addVectors( bb.min, bb.max );153 scope.wheelOffset.multiplyScalar( 0.5 );154 scope.wheelDiameter = bb.max.y - bb.min.y;155 scope.wheelGeometry.center();156 }157 // rig the car158 var s = scope.modelScale,159 delta = new THREE.Vector3();160 var bodyFaceMaterial = new THREE.MeshFaceMaterial( scope.bodyMaterials );161 var wheelFaceMaterial = new THREE.MeshFaceMaterial( scope.wheelMaterials );162 // body163 scope.bodyMesh = new THREE.Mesh( scope.bodyGeometry, bodyFaceMaterial );164 scope.bodyMesh.scale.set( s, s, s );165 scope.root.add( scope.bodyMesh );166 // front left wheel167 delta.multiplyVectors( scope.wheelOffset, new THREE.Vector3( s, s, s ) );168 scope.frontLeftWheelRoot.position.add( delta );169 scope.frontLeftWheelMesh = new THREE.Mesh( scope.wheelGeometry, wheelFaceMaterial );170 scope.frontLeftWheelMesh.scale.set( s, s, s );171 scope.frontLeftWheelRoot.add( scope.frontLeftWheelMesh );172 scope.root.add( scope.frontLeftWheelRoot );173 // front right wheel174 delta.multiplyVectors( scope.wheelOffset, new THREE.Vector3( -s, s, s ) );175 scope.frontRightWheelRoot.position.add( delta );176 scope.frontRightWheelMesh = new THREE.Mesh( scope.wheelGeometry, wheelFaceMaterial );177 scope.frontRightWheelMesh.scale.set( s, s, s );178 scope.frontRightWheelMesh.rotation.z = Math.PI;179 scope.frontRightWheelRoot.add( scope.frontRightWheelMesh );180 scope.root.add( scope.frontRightWheelRoot );181 // back left wheel182 delta.multiplyVectors( scope.wheelOffset, new THREE.Vector3( s, s, -s ) );183 delta.z -= scope.backWheelOffset;184 scope.backLeftWheelMesh = new THREE.Mesh( scope.wheelGeometry, wheelFaceMaterial );185 scope.backLeftWheelMesh.position.add( delta );186 scope.backLeftWheelMesh.scale.set( s, s, s );187 scope.root.add( scope.backLeftWheelMesh );188 // back right wheel189 delta.multiplyVectors( scope.wheelOffset, new THREE.Vector3( -s, s, -s ) );190 delta.z -= scope.backWheelOffset;191 scope.backRightWheelMesh = new THREE.Mesh( scope.wheelGeometry, wheelFaceMaterial );192 scope.backRightWheelMesh.position.add( delta );193 scope.backRightWheelMesh.scale.set( s, s, s );194 scope.backRightWheelMesh.rotation.z = Math.PI;195 scope.root.add( scope.backRightWheelMesh );196 // cache meshes197 scope.meshes = [ scope.bodyMesh, scope.frontLeftWheelMesh, scope.frontRightWheelMesh, scope.backLeftWheelMesh, scope.backRightWheelMesh ];198 // callback199 scope.loaded = true;200 if ( scope.callback ) {201 scope.callback( scope );202 }203 }204 };205 function quadraticEaseOut( k ) { return - k * ( k - 2 ); }206 function cubicEaseOut( k ) { return --k * k * k + 1; }207 function circularEaseOut( k ) { return Math.sqrt( 1 - --k * k ); }208 function sinusoidalEaseOut( k ) { return Math.sin( k * Math.PI / 2 ); }209 function exponentialEaseOut( k ) { return k === 1 ? 1 : - Math.pow( 2, - 10 * k ) + 1; }...

Full Screen

Full Screen

wheel.py

Source:wheel.py Github

copy

Full Screen

...38 "Error decoding metadata for {}: {}".format(39 self._wheel_name, e40 )41 )42def pkg_resources_distribution_for_wheel(wheel_zip, name, location):43 # type: (ZipFile, str, str) -> Distribution44 """Get a pkg_resources distribution given a wheel.45 :raises UnsupportedWheel: on any errors46 """47 info_dir, _ = parse_wheel(wheel_zip, name)48 metadata_files = [49 p for p in wheel_zip.namelist() if p.startswith("{}/".format(info_dir))50 ]51 metadata_text = {} # type: Dict[str, bytes]52 for path in metadata_files:53 # If a flag is set, namelist entries may be unicode in Python 2.54 # We coerce them to native str type to match the types used in the rest55 # of the code. This cannot fail because unicode can always be encoded56 # with UTF-8.57 full_path = ensure_str(path)58 _, metadata_name = full_path.split("/", 1)59 try:60 metadata_text[metadata_name] = read_wheel_metadata_file(61 wheel_zip, full_path62 )63 except UnsupportedWheel as e:64 raise UnsupportedWheel(65 "{} has an invalid wheel, {}".format(name, str(e))66 )67 metadata = WheelMetadata(metadata_text, location)68 return DistInfoDistribution(69 location=location, metadata=metadata, project_name=name70 )71def parse_wheel(wheel_zip, name):72 # type: (ZipFile, str) -> Tuple[str, Message]73 """Extract information from the provided wheel, ensuring it meets basic74 standards.75 Returns the name of the .dist-info directory and the parsed WHEEL metadata.76 """77 try:78 info_dir = wheel_dist_info_dir(wheel_zip, name)79 metadata = wheel_metadata(wheel_zip, info_dir)80 version = wheel_version(metadata)81 except UnsupportedWheel as e:82 raise UnsupportedWheel(83 "{} has an invalid wheel, {}".format(name, str(e))84 )85 check_compatibility(version, name)...

Full Screen

Full Screen

AWSAutonomousVehicleIOT.py

Source:AWSAutonomousVehicleIOT.py Github

copy

Full Screen

1#!/usr/bin/python2# Replace aws_rest_endpoint with your AWS IoT endpoint dns name3# Replace the ca_path, cert_path and key_path with the credentials to you created with the AWS IoT service4# Replace your vehicleid and wheel_travel with your vehicle information5# DynamoDB TTL is set for 30 days for expiration6# battery_capacity is an arbitrary number7# Replace vehicle_topic with the AWS IoT that you want to send the telemetry to8import time9from time import sleep10import json11import random12import uuid13import datetime14import paho.mqtt.client as paho15import ssl16import rightfrontwheel17import leftfrontwheel18import rightrearwheel19import leftrearwheel20# Fill out this area with AWS account specific details21aws_rest_endpoint = "youriotendpoint.iot.us-east-1.amazonaws.com"22awsport = 888323# Location of Certificates24ca_path = "/home/pi/d2/creds/VeriSign-Class 3-Public-Primary-Certification-Authority-G5.pem"25cert_path = "/home/pi/d2/creds/avaws01.donkeycar.cert.pem"26key_path = "/home/pi/d2/creds/avaws01.donkeycar.private.key"27connflag = False28def on_connect(client, userdata, flags, rc):29 global connflag30 connflag = True31 print("Connection returned result: " + str(rc))32def on_message(client, userdata, msg):33 print(msg.topic+" "+str(msg.payload))34 print(Iot_Topic+str(msg.payload))35def getTime():36 currenttime = time.localtime()37 return (time.strftime("%Y%m%d%H%M%S", currenttime))38def drivetelemetry():39 vehicleid = "avaws01"40 actualtime = getTime()41 unixtime = str(datetime.datetime.now())42 event = uuid.uuid4()43 eventid = event.hex44 dynamodb_ttl = int(time.time()) + 259200045 wheel_travel = 9.546 feet = 1247 wheel_rotations_per_mile = 6336048 speed_reset = random.randint(1, 9)49 battery_capacity = 532050 right_front_wheel_rpm = int(rightfrontwheel.get_wheelrpm())51 right_front_wheel_odometer = round((rightfrontwheel.get_wheeldistance())/feet, 2)52 right_front_wheel_distance = right_front_wheel_rpm * wheel_travel53 right_front_wheel_mpm = right_front_wheel_distance / wheel_rotations_per_mile54 right_front_wheel_mph = right_front_wheel_mpm * 6055 right_front_wheel_speed = round(right_front_wheel_mph)56 right_front_wheel_data = {"right_front_speed": right_front_wheel_speed, "right_front_rpm": right_front_wheel_rpm, "right_front_wheel_odometer": right_front_wheel_odometer}57 left_front_wheel_rpm = int(leftfrontwheel.get_wheelrpm())58 left_front_wheel_odometer = round((leftfrontwheel.get_wheeldistance())/feet, 2)59 left_front_wheel_distance = left_front_wheel_rpm * wheel_travel60 left_front_wheel_mpm = left_front_wheel_distance / wheel_rotations_per_mile61 left_front_wheel_mph = left_front_wheel_mpm * 6062 left_front_wheel_speed = round(left_front_wheel_mph)63 left_front_wheel_data = {"left_front_speed": left_front_wheel_speed, "left_front_rpm": left_front_wheel_rpm, "left_front_wheel_odometer": left_front_wheel_odometer}64 right_rear_wheel_rpm = int(rightrearwheel.get_wheelrpm())65 right_rear_wheel_odometer = round((rightrearwheel.get_wheeldistance())/feet, 2)66 right_rear_wheel_distance = right_rear_wheel_rpm * wheel_travel67 right_rear_wheel_mpm = right_rear_wheel_distance / wheel_rotations_per_mile68 right_rear_wheel_mph = right_rear_wheel_mpm * 6069 right_rear_wheel_speed = round(right_rear_wheel_mph)70 right_rear_wheel_data = {"right_rear_speed": right_rear_wheel_speed, "right_rear_rpm": right_rear_wheel_rpm, "right_rear_wheel_odometer": right_rear_wheel_odometer}71 left_rear_wheel_rpm = int(leftrearwheel.get_wheelrpm())72 left_rear_wheel_odometer = round((leftrearwheel.get_wheeldistance())/feet, 2)73 left_rear_wheel_distance = left_rear_wheel_rpm * wheel_travel74 left_rear_wheel_mpm = left_rear_wheel_distance / wheel_rotations_per_mile75 left_rear_wheel_mph = left_rear_wheel_mpm * 6076 left_rear_wheel_speed = round(left_rear_wheel_mph)77 left_rear_wheel_data = {"left_rear_speed": left_rear_wheel_speed, "left_rear_rpm": left_rear_wheel_rpm, "left_rear_wheel_odometer": left_rear_wheel_odometer}78 vehicle_speed = int((right_front_wheel_speed + right_rear_wheel_speed + left_front_wheel_speed + left_rear_wheel_speed)/4)79 average_wheel_rpm = int((right_front_wheel_rpm + right_rear_wheel_rpm + left_front_wheel_rpm + left_rear_wheel_rpm)/4)80 vehicle_odometer = ((right_front_wheel_odometer + right_rear_wheel_odometer + left_front_wheel_odometer + left_rear_wheel_odometer)/4)81 remaining_power = int(battery_capacity - vehicle_odometer)82 engine_rpm = int(average_wheel_rpm * 11)83 # JSON Key/Value pairs of telemetry84 vehiclepayload = json.dumps(85 {86 "vehicleid": vehicleid,87 "eventid": eventid,88 "time": actualtime,89 "timestamp": unixtime,90 "average_wheel_rpm": average_wheel_rpm,91 "engine_rpm": engine_rpm,92 "vehicle_speed": vehicle_speed,93 "vehicle_odometer": vehicle_odometer,94 "remaining_power": remaining_power,95 "right_front_wheel_rpm": right_front_wheel_rpm,96 "left_front_wheel_rpm": left_front_wheel_rpm,97 "right_rear_wheel_rpm": right_rear_wheel_rpm,98 "left_rear_wheel_rpm": left_rear_wheel_rpm,99 "right_front_wheel_speed": right_front_wheel_speed,100 "left_front_wheel_speed": left_front_wheel_speed,101 "right_rear_wheel_speed": right_rear_wheel_speed,102 "left_rear_wheel_speed": left_rear_wheel_speed,103 "right_front_wheel_odometer": right_front_wheel_odometer,104 "left_front_wheel_odometer": left_front_wheel_odometer,105 "right_rear_wheel_odometer": right_rear_wheel_odometer,106 "left_rear_wheel_odometer": left_rear_wheel_odometer,107 "dynamodb_ttl": dynamodb_ttl108 }109 )110 # print (vehiclepayload)111 return(vehiclepayload)112# Logging can be enabled by uncommenting below113# def on_log(client, userdata, level, buf):114 # print(msg.topic+" "+str(msg.payload))115 # print(Iot_Topic +str(msg.payload))116mqttc = paho.Client()117mqttc.on_connect = on_connect118mqttc.on_message = on_message119# mqttc.on_log = on_log120mqttc.tls_set(ca_path, certfile=cert_path, keyfile=key_path, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)121mqttc.connect(aws_rest_endpoint, awsport, keepalive=60)122# Begin reading sensor telemetry123mqttc.loop_start()124# drivetelemetry()125for r in range(10000000):126 # Sending telemetry to AWS IoT Service127 vehicle_topic = "/topics/DonkeyCars/AVAWS01"128 telemetry_payload = drivetelemetry()129 print(telemetry_payload)130 mqttc.publish(vehicle_topic, telemetry_payload, 1)...

Full Screen

Full Screen

test_wheel.py

Source:test_wheel.py Github

copy

Full Screen

...4from os.path import exists5from pip.locations import write_delete_marker_file6from pip.status_codes import PREVIOUS_BUILD_DIR_ERROR7from tests.lib import pyversion8def test_pip_wheel_fails_without_wheel(script, data):9 """10 Test 'pip wheel' fails without wheel11 """12 result = script.pip(13 'wheel', '--no-index', '-f', data.find_links, 'simple==3.0',14 expect_error=True,15 )16 assert "'pip wheel' requires the 'wheel' package" in result.stderr17@pytest.mark.network18def test_pip_wheel_success(script, data):19 """20 Test 'pip wheel' success.21 """22 script.pip('install', 'wheel')23 result = script.pip(24 'wheel', '--no-index', '-f', data.find_links, 'simple==3.0',25 )26 wheel_file_name = 'simple-3.0-py%s-none-any.whl' % pyversion[0]27 wheel_file_path = script.scratch / wheel_file_name28 assert wheel_file_path in result.files_created, result.stdout29 assert "Successfully built simple" in result.stdout, result.stdout30@pytest.mark.network31def test_pip_wheel_downloads_wheels(script, data):32 """33 Test 'pip wheel' downloads wheels34 """35 script.pip('install', 'wheel')36 result = script.pip(37 'wheel', '--no-index', '-f', data.find_links, 'simple.dist',38 )39 wheel_file_name = 'simple.dist-0.1-py2.py3-none-any.whl'40 wheel_file_path = script.scratch / wheel_file_name41 assert wheel_file_path in result.files_created, result.stdout42 assert "Saved" in result.stdout, result.stdout43@pytest.mark.network44def test_pip_wheel_builds_when_no_binary_set(script, data):45 script.pip('install', 'wheel')46 data.packages.join('simple-3.0-py2.py3-none-any.whl').touch()47 # Check that the wheel package is ignored48 res = script.pip(49 'wheel', '--no-index', '--no-binary', ':all:', '-f', data.find_links,50 'simple==3.0')51 assert "Running setup.py bdist_wheel for simple" in str(res), str(res)52@pytest.mark.network53def test_pip_wheel_builds_editable_deps(script, data):54 """55 Test 'pip wheel' finds and builds dependencies of editables56 """57 script.pip('install', 'wheel')58 editable_path = os.path.join(data.src, 'requires_simple')59 result = script.pip(60 'wheel', '--no-index', '-f', data.find_links, '-e', editable_path61 )62 wheel_file_name = 'simple-1.0-py%s-none-any.whl' % pyversion[0]63 wheel_file_path = script.scratch / wheel_file_name64 assert wheel_file_path in result.files_created, result.stdout65@pytest.mark.network66def test_pip_wheel_builds_editable(script, data):67 """68 Test 'pip wheel' builds an editable package69 """70 script.pip('install', 'wheel')71 editable_path = os.path.join(data.src, 'simplewheel-1.0')72 result = script.pip(73 'wheel', '--no-index', '-e', editable_path74 )75 wheel_file_name = 'simplewheel-1.0-py%s-none-any.whl' % pyversion[0]76 wheel_file_path = script.scratch / wheel_file_name77 assert wheel_file_path in result.files_created, result.stdout78@pytest.mark.network79def test_pip_wheel_fail(script, data):80 """81 Test 'pip wheel' failure.82 """83 script.pip('install', 'wheel')84 result = script.pip(85 'wheel', '--no-index', '-f', data.find_links, 'wheelbroken==0.1',86 expect_error=True,87 )88 wheel_file_name = 'wheelbroken-0.1-py%s-none-any.whl' % pyversion[0]89 wheel_file_path = script.scratch / wheel_file_name90 assert wheel_file_path not in result.files_created, (91 wheel_file_path,92 result.files_created,93 )94 assert "FakeError" in result.stdout, result.stdout95 assert "Failed to build wheelbroken" in result.stdout, result.stdout96 assert result.returncode != 097@pytest.mark.network98def test_no_clean_option_blocks_cleaning_after_wheel(script, data):99 """100 Test --no-clean option blocks cleaning after wheel build101 """102 script.pip('install', 'wheel')103 build = script.venv_path / 'build'104 result = script.pip(105 'wheel', '--no-clean', '--no-index', '--build', build,106 '--find-links=%s' % data.find_links, 'simple',107 )108 build = build / 'simple'109 assert exists(build), "build/simple should still exist %s" % str(result)110@pytest.mark.network111def test_pip_wheel_source_deps(script, data):112 """...

Full Screen

Full Screen

_in_process.py

Source:_in_process.py Github

copy

Full Screen

...25 if obj_path:26 for path_part in obj_path.split('.'):27 obj = getattr(obj, path_part)28 return obj29def get_requires_for_build_wheel(config_settings):30 """Invoke the optional get_requires_for_build_wheel hook31 32 Returns [] if the hook is not defined.33 """34 backend = _build_backend()35 try:36 hook = backend.get_requires_for_build_wheel37 except AttributeError:38 return []39 else:40 return hook(config_settings)41def prepare_metadata_for_build_wheel(metadata_directory, config_settings):42 """Invoke optional prepare_metadata_for_build_wheel43 44 Implements a fallback by building a wheel if the hook isn't defined.45 """46 backend = _build_backend()47 try:48 hook = backend.prepare_metadata_for_build_wheel49 except AttributeError:50 return _get_wheel_metadata_from_wheel(backend, metadata_directory,51 config_settings)52 else:53 return hook(metadata_directory, config_settings)54WHEEL_BUILT_MARKER = 'PEP517_ALREADY_BUILT_WHEEL'55def _dist_info_files(whl_zip):56 """Identify the .dist-info folder inside a wheel ZipFile."""57 res = []58 for path in whl_zip.namelist():59 m = re.match(r'[^/\\]+-[^/\\]+\.dist-info/', path)60 if m:61 res.append(path)62 if res:63 return res64 raise Exception("No .dist-info folder found in wheel")65def _get_wheel_metadata_from_wheel(backend, metadata_directory, config_settings):66 """Build a wheel and extract the metadata from it.67 68 Fallback for when the build backend does not define the 'get_wheel_metadata'69 hook.70 """71 from zipfile import ZipFile72 whl_basename = backend.build_wheel(metadata_directory, config_settings)73 with open(os.path.join(metadata_directory, WHEEL_BUILT_MARKER), 'wb'):74 pass # Touch marker file75 whl_file = os.path.join(metadata_directory, whl_basename)76 with ZipFile(whl_file) as zipf:77 dist_info = _dist_info_files(zipf)78 zipf.extractall(path=metadata_directory, members=dist_info)79 return dist_info[0].split('/')[0]80def _find_already_built_wheel(metadata_directory):81 """Check for a wheel already built during the get_wheel_metadata hook.82 """83 if not metadata_directory:84 return None85 metadata_parent = os.path.dirname(metadata_directory)86 if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)):87 return None88 whl_files = glob(os.path.join(metadata_parent, '*.whl'))89 if not whl_files:90 print('Found wheel built marker, but no .whl files')91 return None92 if len(whl_files) > 1:93 print('Found multiple .whl files; unspecified behaviour. '94 'Will call build_wheel.')95 return None96 97 # Exactly one .whl file98 return whl_files[0]99def build_wheel(wheel_directory, config_settings, metadata_directory=None):100 """Invoke the mandatory build_wheel hook.101 102 If a wheel was already built in the prepare_metadata_for_build_wheel fallback, this103 will copy it rather than rebuilding the wheel.104 """105 prebuilt_whl = _find_already_built_wheel(metadata_directory)106 if prebuilt_whl:107 shutil.copy2(prebuilt_whl, wheel_directory)108 return os.path.basename(prebuilt_whl)109 return _build_backend().build_wheel(wheel_directory, config_settings,110 metadata_directory)111def get_requires_for_build_sdist(config_settings):112 """Invoke the optional get_requires_for_build_wheel hook113 Returns [] if the hook is not defined.114 """115 backend = _build_backend()116 try:117 hook = backend.get_requires_for_build_sdist118 except AttributeError:119 return []120 else:121 return hook(config_settings)122class _DummyException(Exception):123 """Nothing should ever raise this exception"""...

Full Screen

Full Screen

car_description.py

Source:car_description.py Github

copy

Full Screen

1import numpy as np2class Description:3 def __init__(self, overall_length, overall_width, rear_overhang, tyre_diameter, tyre_width, axle_track, wheelbase):4 5 """6 At initialisation7 :param overall_length: (float) vehicle's overall length [m]8 :param overall_width: (float) vehicle's overall width [m]9 :param rear_overhang: (float) distance between the rear bumper and the rear axle [m]10 :param tyre_diameter: (float) vehicle's tyre diameter [m]11 :param tyre_width: (float) vehicle's tyre width [m]12 :param axle_track: (float) vehicle's axle track [m]13 :param wheelbase: (float) vehicle's wheelbase [m]14 15 At every time step16 :param x: (float) x-coordinate of the vehicle's rear axle17 :param y: (float) y-coordinate of the vehicle's rear axle18 :param yaw: (float) vehicle's heading [rad]19 :param steer: (float) vehicle's steering angle [rad]20 21 :return outlines: (list) vehicle's outlines [x, y]22 :return fr_wheel: (list) vehicle's front-right axle [x, y]23 :return rr_wheel: (list) vehicle's rear-right axle [x, y]24 :return fl_wheel: (list) vehicle's front-left axle [x, y]25 :return rl_wheel: (list) vehicle's rear-right axle [x, y]26 """27 centre_to_wheel = axle_track / 228 centre_to_side = overall_width / 229 rear_axle_to_front_bumper = overall_length - rear_overhang30 vehicle_vertices = np.array([(-rear_overhang, centre_to_side),31 ( rear_axle_to_front_bumper, centre_to_side),32 ( rear_axle_to_front_bumper, -centre_to_side),33 (-rear_overhang, -centre_to_side)])34 wheel_vertices = np.array([(-tyre_diameter, tyre_width - centre_to_wheel),35 ( tyre_diameter, tyre_width - centre_to_wheel),36 ( tyre_diameter, -tyre_width - centre_to_wheel),37 (-tyre_diameter, -tyre_width - centre_to_wheel)])38 self.outlines = np.concatenate((vehicle_vertices, [vehicle_vertices[0]]))39 self.wheel_format = np.concatenate((wheel_vertices, [wheel_vertices[0]]))40 self.rl_wheel = np.copy(self.wheel_format)41 self.rl_wheel[:,1] *= -142 self.fl_wheel = np.copy(self.rl_wheel)43 self.fl_wheel[:, 0] += wheelbase 44 self.fr_wheel = np.copy(self.wheel_format)45 self.fr_wheel[:, 0] += wheelbase46 47 self.fr_wheel_centre = np.array([(self.fr_wheel[0][0] + self.fr_wheel[2][0]) / 2,48 (self.fr_wheel[0][1] + self.fr_wheel[2][1]) / 2])49 self.fl_wheel_centre = np.array([(self.fl_wheel[0][0] + self.fl_wheel[2][0]) / 2,50 (self.fl_wheel[0][1] + self.fl_wheel[2][1]) / 2])51 def get_rotation_matrix(self, angle):52 return np.array([( np.cos(angle), np.sin(angle)),53 (-np.sin(angle), np.cos(angle))])54 def transform(self, point, x, y, angle_vector):55 # Rotational transform56 point = point.dot(angle_vector).T57 # Position translation58 point[0,:] += x59 point[1,:] += y60 61 return point62 def plot_car(self, x, y, yaw, steer=0.0):63 # Rotation matrices64 yaw_vector = self.get_rotation_matrix(yaw)65 steer_vector = self.get_rotation_matrix(steer)66 fr_wheel = np.copy(self.fr_wheel)67 fl_wheel = np.copy(self.fl_wheel)68 # Rotate the wheels about its position69 fr_wheel -= self.fr_wheel_centre70 fl_wheel -= self.fl_wheel_centre71 fr_wheel = fr_wheel.dot(steer_vector)72 fl_wheel = fl_wheel.dot(steer_vector)73 fr_wheel += self.fr_wheel_centre74 fl_wheel += self.fl_wheel_centre75 outlines = self.transform(self.outlines, x, y, yaw_vector)76 fr_wheel = self.transform(fr_wheel, x, y, yaw_vector)77 fl_wheel = self.transform(fl_wheel, x, y, yaw_vector)78 rr_wheel = self.transform(self.wheel_format, x, y, yaw_vector)79 rl_wheel = self.transform(self.rl_wheel, x, y, yaw_vector)80 return outlines, fr_wheel, rr_wheel, fl_wheel, rl_wheel81def main():82 from matplotlib import pyplot as plt83 # Based on Tesla's model S 100D (https://www.car.info/en-se/tesla/model-s/model-s-100-kwh-awd-16457112/specs)84 overall_length = 4.9785 overall_width = 1.96486 tyre_diameter = 0.482687 tyre_width = 0.203288 axle_track = 1.66289 wheelbase = 2.9690 rear_overhang = (overall_length - wheelbase) / 291 colour = 'black'92 desc = Description(overall_length, overall_width, rear_overhang, tyre_diameter, tyre_width, axle_track, wheelbase)93 desc_plots = desc.plot_car(30.0, -10.0, np.pi/4, np.deg2rad(25))94 95 ax = plt.axes()96 ax.set_aspect('equal')97 for desc_plot in desc_plots:98 ax.plot(*desc_plot, color=colour)99 plt.show()100if __name__ == '__main__':...

Full Screen

Full Screen

vehicles.py

Source:vehicles.py Github

copy

Full Screen

1'''2BreezySLAM: Simple, efficient SLAM in Python3vehicles.py: odometry models for different kinds of vehicles4(currently just wheeled vehicles)5Copyright (C) 2014 Suraj Bajracharya and Simon D. Levy6This code is free software: you can redistribute it and/or modify7it under the terms of the GNU Lesser General Public License as 8published by the Free Software Foundation, either version 3 of the 9License, or (at your option) any later version.10This code is distributed in the hope that it will be useful, 11but WITHOUT ANY WARRANTY without even the implied warranty of12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the13GNU General Public License for more details.14You should have received a copy of the GNU Lesser General Public License 15along with this code. If not, see <http:#www.gnu.org/licenses/>.16'''17import math18class WheeledVehicle(object):19 '''20 An abstract class supporting ododmetry for wheeled robots. Your implementing21 class should provide the method:22 23 extractOdometry(self, timestamp, leftWheel, rightWheel) --> 24 (timestampSeconds, leftWheelDegrees, rightWheelDegrees) 25 '''26 27 def __init__(self, wheelRadiusMillimeters, halfAxleLengthMillimeters):28 '''29 wheelRadiusMillimeters radius of each odometry wheel 30 halfAxleLengthMillimeters half the length of the axle between the odometry wheels 31 '''32 self.wheelRadiusMillimeters = wheelRadiusMillimeters 33 self.halfAxleLengthMillimeters = halfAxleLengthMillimeters34 35 self.timestampSecondsPrev = None 36 self.leftWheelDegreesPrev = None37 self.rightWheelDegreesPrev = None38 39 def __str__(self):40 41 return '<Wheel radius=%f mm Half axle Length=%f mm>' % \42 (self.wheelRadiusMillimeters, self.halfAxleLengthMillimeters)43 44 def __repr__(self):45 46 return self.__str__()47 48 def computePoseChange(self, timestamp, leftWheelOdometry, rightWheelOdometry):49 '''50 Computes pose change based on odometry.51 52 Parameters:53 54 timestamp time stamp, in whatever units your robot uses 55 leftWheelOdometry odometry for left wheel, in whatever form your robot uses 56 rightWheelOdometry odometry for right wheel, in whatever form your robot uses57 58 Returns a tuple (dxyMillimeters, dthetaDegrees, dtSeconds)59 60 dxyMillimeters forward distance traveled, in millimeters61 dthetaDegrees change in angular position, in degrees62 dtSeconds elapsed time since previous odometry, in seconds63 ''' 64 dxyMillimeters = 065 dthetaDegrees = 066 dtSeconds = 067 68 timestampSecondsCurr, leftWheelDegreesCurr, rightWheelDegreesCurr = \69 self.extractOdometry(timestamp, leftWheelOdometry, rightWheelOdometry)70 71 if self.timestampSecondsPrev != None: 72 73 leftDiffDegrees = leftWheelDegreesCurr - self.leftWheelDegreesPrev74 rightDiffDegrees = rightWheelDegreesCurr - self.rightWheelDegreesPrev75 76 dxyMillimeters = self.wheelRadiusMillimeters * \77 (math.radians(leftDiffDegrees) + math.radians(rightDiffDegrees))78 79 dthetaDegrees = (float(self.wheelRadiusMillimeters) / self.halfAxleLengthMillimeters) * \80 (rightDiffDegrees - leftDiffDegrees)81 82 dtSeconds = timestampSecondsCurr - self.timestampSecondsPrev83 84 # Store current odometry for next time85 self.timestampSecondsPrev = timestampSecondsCurr 86 self.leftWheelDegreesPrev = leftWheelDegreesCurr87 self.rightWheelDegreesPrev = rightWheelDegreesCurr88 # Return linear velocity, angular velocity, time difference89 return dxyMillimeters, dthetaDegrees, dtSeconds ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 await page.waitForSelector('input[name="q"]');7 await page.type('input[name="q"]', 'puppeteer');8 await page.keyboard.press('Enter');9 await page.waitForSelector('input[name="q"]');10 await page.waitForSelector('div[id="rso"]');11 await page.evaluate(() => {12 window.scrollBy(0, window.innerHeight);13 });14 await page.waitForSelector('input[name="q"]');15 await page.waitForSelector('div[id="rso"]');16 await page.evaluate(() => {17 window.scrollBy(0, window.innerHeight);18 });19 await page.waitForSelector('input[name="q"]');20 await page.waitForSelector('div[id="rso"]');21 await page.evaluate(() => {22 window.scrollBy(0, window.innerHeight);23 });24 await page.waitForSelector('input[name="q"]');25 await page.waitForSelector('div[id="rso"]');26 await page.evaluate(() => {27 window.scrollBy(0, window.innerHeight);28 });29 await page.waitForSelector('input[name="q"]');30 await page.waitForSelector('div[id="rso"]');31 await page.evaluate(() => {32 window.scrollBy(0, window.innerHeight);33 });34 await page.waitForSelector('input[name="q"]');35 await page.waitForSelector('div[id="rso"]');36 await page.evaluate(() => {37 window.scrollBy(0, window.innerHeight);38 });39 await page.waitForSelector('input[name="q"]');40 await page.waitForSelector('div[id="rso"]');41 await page.evaluate(() => {42 window.scrollBy(0, window.innerHeight);43 });44 await page.waitForSelector('input[name="q"]');45 await page.waitForSelector('div[id="rso"]');46 await page.evaluate(() => {47 window.scrollBy(0, window.innerHeight);48 });49 await page.waitForSelector('input[name="q"]');50 await page.waitForSelector('div[id="rso"]');51})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const iPhone = puppeteer.devices['iPhone 6'];3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 await page.emulate(iPhone);7 await page.screenshot({path: 'example.png'});8 await browser.close();9})();10const puppeteer = require('puppeteer');11const iPhone = puppeteer.devices['iPhone 6'];12(async () => {13 const browser = await puppeteer.launch();14 const page = await browser.newPage();15 await page.emulate(iPhone);16 await page.screenshot({path: 'example.png'});17 await browser.close();18})();19const puppeteer = require('puppeteer');20(async () => {21 const browser = await puppeteer.launch();22 const page = await browser.newPage();23 await page.emulate({24 viewport: {25 },26 });27 await page.screenshot({path: 'example.png'});28 await browser.close();29})();30const puppeteer = require('puppeteer');31(async () => {32 const browser = await puppeteer.launch();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const path = require('path');3const fs = require('fs');4const { promisify } = require('util');5const writeFile = promisify(fs.writeFile);6(async () => {7 const browser = await puppeteer.launch();8 const page = await browser.newPage();9 await page.setViewport({ width: 1280, height: 800 });10 await page.type('input', 'puppeteer');11 await page.keyboard.press('Enter');12 await page.waitForNavigation();13 await page.screenshot({ path: 'test.png' });14 await page.pdf({ path: 'test.pdf', format: 'A4' });15 await browser.close();16})();17const puppeteer = require('puppeteer');18const path = require('path');19const fs = require('fs');20const { promisify } = require('util');21const writeFile = promisify(fs.writeFile);22(async () => {23 const browser = await puppeteer.launch();24 const page = await browser.newPage();25 await page.setViewport({ width: 1280, height: 800 });26 await page.type('input', 'puppeteer');27 await page.keyboard.press('Enter');28 await page.waitForNavigation();29 await page.screenshot({ path: 'test.png' });30 await page.pdf({ path: 'test.pdf', format: 'A4' });31 await browser.close();32})();33const puppeteer = require('puppeteer');34const path = require('path');35const fs = require('fs');36const { promisify } = require('util');37const writeFile = promisify(fs.writeFile);38(async () => {39 const browser = await puppeteer.launch();40 const page = await browser.newPage();41 await page.setViewport({ width: 1280, height: 800 });42 await page.type('input', 'puppeteer');43 await page.keyboard.press('Enter');44 await page.waitForNavigation();45 await page.screenshot({ path: 'test.png' });46 await page.pdf({ path: 'test.pdf', format: 'A4' });47 await browser.close();48})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4const file = path.join(__dirname, 'test.html');5(async () => {6 const browser = await puppeteer.launch();7 const page = await browser.newPage();8 const viewportHeight = page.viewport().height;9 let previousHeight = 0;10 while (previousHeight !== page.evaluate('document.body.scrollHeight')) {11 previousHeight = await page.evaluate('document.body.scrollHeight');12 await page.evaluate(_viewportHeight => {13 window.scrollBy(0, _viewportHeight);14 }, viewportHeight);15 await page.waitFor(500);16 }17 await page.evaluate(_ => {18 window.scrollTo(0, 0);19 });20 await page.screenshot({path: 'screenshot.png'});21 await browser.close();22})();

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful