text stringlengths 184 4.48M |
|---|
/*
if(true){
const myName ='vaish'
}
console.log(myName) //here it throws an error it says myName is not defined
*/
/*
if(true){
const myName ='vaish'
console.log(myName) //vaish
//so let and const declared variables can only be accessed in the block they are declared in
}
*/
/* function scope --> which dictates that variables declared inside the function are not accessible from outside the function*/
/*
if(true){
const myName ='vaish'
console.log(myName)
}
function testFn()
{
const myName ="surya"
console.log(myName)
}
testFn() op-->//vaish
// surya
//(here isthat both myName variables have different scopenyname within if block is vaish whereas within test function is surya
// even thogh they have the same variable name)
*/
/* global scope --> is the scope outside any block or a function. a global scope variable is accessible both inside a block
as well as a function
*/
// const myNum =100
// if(true){
// const myName ='vaish'
// console.log(myName)
// console.log(myNum)
// }
// function testFn()
// {
// const myName ="surya"
// console.log(myName)
// console.log(myNum)
// }
// testFn()
/*
op:
vaish
100
surya
100
*/
const myNum =100
const myName='batman'
if(true){
const myName ='vaish'
console.log(myName)
console.log(myNum)
}
function testFn()
{
const myName ="surya"
console.log(myName)
console.log(myNum)
}
testFn()
/* op: so globally declared variable will not overwrite block or function scoped variable
vaish
100
surya
100
*/ |
import React, {useEffect, useState} from "react";
import {Table} from "react-bootstrap";
import {getUsers} from "../services/UserService";
import '../App.css';
import Pagination from "./Pagination";
import pagination from "./Pagination";
const Home = () => {
const [users, setUsers] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const [usersPerPage] = useState(3);
useEffect(() => {
let mounted = true;
getUsers()
.then(data => {
if (mounted) {
setUsers(data)
}
})
return () => mounted = false
}, []);
// get current users
const indexOfLastUser = currentPage * usersPerPage;
const indexOfFirstUser = indexOfLastUser - usersPerPage;
const currentUsers = users.slice(indexOfFirstUser, indexOfLastUser);
// change page
const paginate = pageNumber => setCurrentPage(pageNumber);
return (
<div className="row side-row">
<Table striped bordered hover>
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Gender</th>
<th>City</th>
</tr>
</thead>
<tbody>
{currentUsers.map((user) =>
<tr key={user.user_id}>
<td>{user.user_id}</td>
<td>{user.first_name}</td>
<td>{user.last_name}</td>
<td>{user.age}</td>
<td>{user.gender}</td>
<td>{user.city}</td>
</tr>
)}
</tbody>
</Table>
<Pagination usersPerPage={usersPerPage} totalUsers={users.length} paginate={paginate} />
</div>
);
}
export default Home; |
/* import React from "react";
class Contador extends React.Component {
} */
import React, { Component } from "react";
import './Contador.css'
import Display from "./Display";
import PassoForm from "./PassoForm";
import Botoes from "./Botoes";
export default class Contador extends Component {
/* constructor(props) {
super(props)
this.state = {
passo: props.passo,
valor: 0
}
} */
state = {
passo: this.props.passo || 1,
valor: this.props.valor || 0,
//valor: 0
}
inc = () => {
this.setState({
valor: this.state.valor + this.state.passo
})
}
dec = () => {
this.setState({
valor: this.state.valor - this.state.passo
})
}
mudarPasso = (novoPasso) => {
this.setState({
passo: novoPasso
})
}
render() {
return (
<div className="Contador">
<h2>Contador</h2>
{/* <div>
<label for="passoInput">Passo: </label>
<input id="passoInput" type="number"
value={this.state.passo}
onChange={e => this.setState({ passo: +e.target.value })}/>
</div> */}
<PassoForm passo={this.state.passo}
onPassoChange={this.mudarPasso}></PassoForm>
<Display valor={this.state.valor}></Display>
<Botoes onInc={this.inc} onDec={this.dec}></Botoes>
{/* <div>
<button onClick={this.inc}>+</button>
<button onClick={this.dec}>-</button>
</div> */}
</div>
)
}
} |
---
title: "[New] Find Rich Ambiance for Video Content"
date: 2024-05-31T12:45:17.619Z
updated: 2024-06-01T12:45:17.619Z
tags:
- ai video
- ai youtube
categories:
- ai
- youtube
description: "This Article Describes [New] Find Rich Ambiance for Video Content"
excerpt: "This Article Describes [New] Find Rich Ambiance for Video Content"
keywords: "\"Ambiance Rich Video,Vivid Video Setting,High-Quality Cinematics,Immersive Visuals,Luxe Themes Videos,Stunning Scene Design,Premium Filming Atmosphere\""
thumbnail: https://www.lifewire.com/thmb/g1kkp8ne6jm5E7rMiTd4CMgu2Fw=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/GettyImages-642981042-5a903651a18d9e0037d31742.jpg
---
## Find Rich Ambiance for Video Content
# Download Free Sound Effects for YouTubers

##### Richard Bennett
Oct 26, 2023• Proven solutions
[0](#commentsBoxSeoTemplate)
Whether you’re making a short film and need sounds to go with your action sequences, or just want some fun noises for your vlog or challenge video, it’s easy to find great sound effects you can use for free online.
Here are 7 places to download free sound effects! Or, if you’re interested in making your own, click here to jump to ‘[Make Your Own Sound Effects](#makeeffects)’.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
## Part 1: YouTube Free Sound Effects Download
#### 1. [Filmora Sound Effects](https://tools.techidaily.com/wondershare/filmora/download/)
Filmora Video Editor provides you with a huge library of free sound effects without download from anywhere else. There are 25 pieces of sound effect available in Filmora, such as transition swoosh, cinematic horn, beep sound and phone ring.

If you do not see the sound effect you want in Filmora, you can also go to the online effect store to find out more sound effects. The sounds are in.wav or mp3 files, so you do not have to use them inside Filmora only. They’re free to use for everyone after downloading, no matter what video editor you use.

The Filmstock audio effect library covers sound effects in different categories: nature sounds, animal sounds, movie sounds, gun sounds, fireworks, bird sounds, cricket sounds, wet sounds, dog barking, water sounds, guitar sounds, city sounds, monster sounds, laughing sounds, dinosaur sounds, fart sounds, pet sounds, dog sounds, car sounds, video game, and thunderstorm.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
#### 2. [Freesound](https://freesound.org/)
Sounds on Freesound are uploaded by users under various Creative Commons licenses (some may require attribution, some may not allow commercial use).

The easiest way to browse the sounds on Freesound is probably to click into Sounds in the top menu, and then ‘Browse tags’ in the menu on the right of your screen. All of the tags on the site will be displayed, and the most commonly used ones will be biggest. The tags include what the sounds are meant to be (i.e. percussion or thunder) and what type of sounds they are (i.e. field-recording or synth).
#### 3. [PacDV](http://www.pacdv.com/sounds/index.html)
PacDV has been producing sound effects since 2001\. You can browse and download sounds individually from their site, or download all at once in a huge bundle. You can use all the sounds for free (you just can’t sell them or provide direct download links to other people).

On the left of the website there’s a menu where you can choose what kinds of sound effects you’re interested in. The categories are:
**Ambience:** this is where you’ll find general background sounds, like ‘car interior’ or ‘grocery store’. Even when nothing in particular is happening, locations have sounds. This is also where you’ll find things like crowd noises.
**Domestic:** these are sounds you hear around the home, like sounds related to doors and appliances.
**Interfaces:** a lot of tech sounds live here, like beeps and clicks. Beeps are all titled ‘Beep’, but nothing else is really labeled beyond being called ‘Interface Sound’. You just have to listen and find out.
**Machines:** a variety of different machine sounds can be found here, from power tools like chainsaws and drills to things like typewriters or paper shredders.
**Mechanical:** this is where you’ll find sounds associated with cameras, coin slots, zippers, and more.
**People:** laughing, clapping, footsteps and even farts – this is where you’ll find human sounds.
**Transportation:** these sounds are all related to vehicles, be they cars or airplanes.
**Voices:** here you’ll find voices saying common things like ‘hi’, ‘aaah’, or ‘come on’.
**Music:** PacDV also has a selection of royalty free music. If you use it in your video, you need to give them credit by including Music by <www.pacdv.com/sounds/> in your video description.
**Miscellaneous:** sounds that don’t quite fit into other categories.
#### 4. [Sound Bible](http://soundbible.com/royalty-free-sounds-1.html)
The sounds on Sound Bible are either in the public domain, which means anyone can use them for anything without restriction, or licensed under the Creative Commons Attribution 3.0 License, which means you just need to provide a credit for the person who created the effect you use. When you click on sound effects on Sound Bible you’ll be able to see whether the effect is Public Domain or Attribution 3.0, and it will tell you who the sound was recorded by. Both public domain and Attribution 3.0 sounds are available for commercial use.

This site has a search function, so if you want dog sounds you can search for ‘dog’. This might be easier than trying to pick the category closest to what you’re looking for and just scrolling through, like you do on some sites.
Sound Bible is updated about 3 times a week, so you can always check back for fresh sounds.
#### 5. [Sound Gator](http://www.soundgator.com/)
Sound Gator has a huge number of sound effects divided into too many categories to list (24). The categories tend to be very specific, like ‘drink sound effects’ or ‘phone sound effects. If you don’t see a category that sounds like what you’re looking for, make sure to check under Misc Sound Effects because there are 68 Mp3#s in there for everything from tools to static.

You can sort the sound effects on Sound Gator by date added, popularity, top rated, runtime, top favorites, or most discussed.
#### 6. [Sounds Crate](https://sfx.productioncrate.com/)
Sounds Crate is part of the larger Production Crate which provides all kinds of resources to creators for free (you can upgrade to a paid account to access exclusive content, but there’s a lot of great content available for free). The categories available on Sounds Crate are:

**Ambient:** room tones and general background noises from nature or cities.
**Animal:** includes things like puppy barks and angry cats.
**Blades and Metal:** you’ll find sounds from swords, chains, and other metal implements here.
**Crashes and Debris:** perfect for action, this is where you’ll find sounds associated with destruction.
**Electricity:** things like electrical blasts and charges can be found here.
**Electronics:** any sound made by anything electrical, like beeps and appliance sounds.
**Explosions and Bangs:** if you have a visual explosion effect, you’ll probably need to combine it with something from here.
**Fight:** find sounds associated with action sequences, like whooshes and punches.
**Gun Related:** everything from reloads to gunshots.
**Impact:** any kind of thud or shattering sound.
**Lock n’ Load:** although there are some ‘gun checking’ sounds in here, it’s mostly clothing related sounds like zippers and Velcro.
**Movement:** wind sounds and whooshes.
**People:** sounds humans make, from voices to footsteps.
**Sci-Fi SFX:** zaps, beeps, and sci-fi ambience.
**Vehicle:** includes both common vehicles like cars and less-common vehicles like tanks.
**Weapons:** both modern weapons like missiles and old-timey things like arrows.
#### 7. [Zapsplat](https://www.zapsplat.com/)
Zapsplat claims to be the fastest growing free sound effects library on the internet. With more than 23,999 professional sounds, and more being added every week, they might just be right. The owner of the site, Alan McKinney, adds 500 sound effects every week by himself and the site also accepts sounds from contributors. All of their sounds were recorded using professional equipment and then edited to make them perfect.

You can even send Alan a message and request specific sound effects if you can’t already find what you want on the site.
On Zapsplat you can browse 26 categories including fantasy, warfare, and animals for individual sounds. Or, you can visit the Free SFX Packs section and download a set of related sounds together. Packs include ‘Magic Wand’, ‘Science Fiction Alarms’, and ‘Cartoon Boings’.
## Part 2: Make Your Own Sound Effects for YouTube Videos
Here are some easy ways you can make your own sound effects at home.
#### 1\. Making Natural Sounds
**Fire** using cellophane. Just crinkle the cellophane wrap to create a sound like a crackling fire. Chip bags work too.
**Rain** using rice. Sprinkle rice (or birdseed) onto a thin metal sheet.
Alternatively for rain, you could record the sound of bacon frying.
**Wind** using a Ziploc. Fill a large ziplock with air and then open the bag a bit and force the air out.
**Thunder** with aluminum. Just shake a sheet of aluminum to make a thunder sound.
#### 2\. Making Action or Sci-Fi Sounds
**Ticking Bomb** with a clock. Any clock that ticks will do.
**Hits/Blows** with a pillow. Hit a pillow to make a sound like a body blow. For really hard hits, you might want to whack a sofa cushion with a broomstick.
**Bones breaking** with celery. Just snap the celery stalks in half.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
##### Richard Bennett
Oct 26, 2023• Proven solutions
[0](#commentsBoxSeoTemplate)
Whether you’re making a short film and need sounds to go with your action sequences, or just want some fun noises for your vlog or challenge video, it’s easy to find great sound effects you can use for free online.
Here are 7 places to download free sound effects! Or, if you’re interested in making your own, click here to jump to ‘[Make Your Own Sound Effects](#makeeffects)’.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
## Part 1: YouTube Free Sound Effects Download
#### 1. [Filmora Sound Effects](https://tools.techidaily.com/wondershare/filmora/download/)
Filmora Video Editor provides you with a huge library of free sound effects without download from anywhere else. There are 25 pieces of sound effect available in Filmora, such as transition swoosh, cinematic horn, beep sound and phone ring.

If you do not see the sound effect you want in Filmora, you can also go to the online effect store to find out more sound effects. The sounds are in.wav or mp3 files, so you do not have to use them inside Filmora only. They’re free to use for everyone after downloading, no matter what video editor you use.

The Filmstock audio effect library covers sound effects in different categories: nature sounds, animal sounds, movie sounds, gun sounds, fireworks, bird sounds, cricket sounds, wet sounds, dog barking, water sounds, guitar sounds, city sounds, monster sounds, laughing sounds, dinosaur sounds, fart sounds, pet sounds, dog sounds, car sounds, video game, and thunderstorm.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
#### 2. [Freesound](https://freesound.org/)
Sounds on Freesound are uploaded by users under various Creative Commons licenses (some may require attribution, some may not allow commercial use).

The easiest way to browse the sounds on Freesound is probably to click into Sounds in the top menu, and then ‘Browse tags’ in the menu on the right of your screen. All of the tags on the site will be displayed, and the most commonly used ones will be biggest. The tags include what the sounds are meant to be (i.e. percussion or thunder) and what type of sounds they are (i.e. field-recording or synth).
#### 3. [PacDV](http://www.pacdv.com/sounds/index.html)
PacDV has been producing sound effects since 2001\. You can browse and download sounds individually from their site, or download all at once in a huge bundle. You can use all the sounds for free (you just can’t sell them or provide direct download links to other people).

On the left of the website there’s a menu where you can choose what kinds of sound effects you’re interested in. The categories are:
**Ambience:** this is where you’ll find general background sounds, like ‘car interior’ or ‘grocery store’. Even when nothing in particular is happening, locations have sounds. This is also where you’ll find things like crowd noises.
**Domestic:** these are sounds you hear around the home, like sounds related to doors and appliances.
**Interfaces:** a lot of tech sounds live here, like beeps and clicks. Beeps are all titled ‘Beep’, but nothing else is really labeled beyond being called ‘Interface Sound’. You just have to listen and find out.
**Machines:** a variety of different machine sounds can be found here, from power tools like chainsaws and drills to things like typewriters or paper shredders.
**Mechanical:** this is where you’ll find sounds associated with cameras, coin slots, zippers, and more.
**People:** laughing, clapping, footsteps and even farts – this is where you’ll find human sounds.
**Transportation:** these sounds are all related to vehicles, be they cars or airplanes.
**Voices:** here you’ll find voices saying common things like ‘hi’, ‘aaah’, or ‘come on’.
**Music:** PacDV also has a selection of royalty free music. If you use it in your video, you need to give them credit by including Music by <www.pacdv.com/sounds/> in your video description.
**Miscellaneous:** sounds that don’t quite fit into other categories.
#### 4. [Sound Bible](http://soundbible.com/royalty-free-sounds-1.html)
The sounds on Sound Bible are either in the public domain, which means anyone can use them for anything without restriction, or licensed under the Creative Commons Attribution 3.0 License, which means you just need to provide a credit for the person who created the effect you use. When you click on sound effects on Sound Bible you’ll be able to see whether the effect is Public Domain or Attribution 3.0, and it will tell you who the sound was recorded by. Both public domain and Attribution 3.0 sounds are available for commercial use.

This site has a search function, so if you want dog sounds you can search for ‘dog’. This might be easier than trying to pick the category closest to what you’re looking for and just scrolling through, like you do on some sites.
Sound Bible is updated about 3 times a week, so you can always check back for fresh sounds.
#### 5. [Sound Gator](http://www.soundgator.com/)
Sound Gator has a huge number of sound effects divided into too many categories to list (24). The categories tend to be very specific, like ‘drink sound effects’ or ‘phone sound effects. If you don’t see a category that sounds like what you’re looking for, make sure to check under Misc Sound Effects because there are 68 Mp3#s in there for everything from tools to static.

You can sort the sound effects on Sound Gator by date added, popularity, top rated, runtime, top favorites, or most discussed.
#### 6. [Sounds Crate](https://sfx.productioncrate.com/)
Sounds Crate is part of the larger Production Crate which provides all kinds of resources to creators for free (you can upgrade to a paid account to access exclusive content, but there’s a lot of great content available for free). The categories available on Sounds Crate are:

**Ambient:** room tones and general background noises from nature or cities.
**Animal:** includes things like puppy barks and angry cats.
**Blades and Metal:** you’ll find sounds from swords, chains, and other metal implements here.
**Crashes and Debris:** perfect for action, this is where you’ll find sounds associated with destruction.
**Electricity:** things like electrical blasts and charges can be found here.
**Electronics:** any sound made by anything electrical, like beeps and appliance sounds.
**Explosions and Bangs:** if you have a visual explosion effect, you’ll probably need to combine it with something from here.
**Fight:** find sounds associated with action sequences, like whooshes and punches.
**Gun Related:** everything from reloads to gunshots.
**Impact:** any kind of thud or shattering sound.
**Lock n’ Load:** although there are some ‘gun checking’ sounds in here, it’s mostly clothing related sounds like zippers and Velcro.
**Movement:** wind sounds and whooshes.
**People:** sounds humans make, from voices to footsteps.
**Sci-Fi SFX:** zaps, beeps, and sci-fi ambience.
**Vehicle:** includes both common vehicles like cars and less-common vehicles like tanks.
**Weapons:** both modern weapons like missiles and old-timey things like arrows.
#### 7. [Zapsplat](https://www.zapsplat.com/)
Zapsplat claims to be the fastest growing free sound effects library on the internet. With more than 23,999 professional sounds, and more being added every week, they might just be right. The owner of the site, Alan McKinney, adds 500 sound effects every week by himself and the site also accepts sounds from contributors. All of their sounds were recorded using professional equipment and then edited to make them perfect.

You can even send Alan a message and request specific sound effects if you can’t already find what you want on the site.
On Zapsplat you can browse 26 categories including fantasy, warfare, and animals for individual sounds. Or, you can visit the Free SFX Packs section and download a set of related sounds together. Packs include ‘Magic Wand’, ‘Science Fiction Alarms’, and ‘Cartoon Boings’.
## Part 2: Make Your Own Sound Effects for YouTube Videos
Here are some easy ways you can make your own sound effects at home.
#### 1\. Making Natural Sounds
**Fire** using cellophane. Just crinkle the cellophane wrap to create a sound like a crackling fire. Chip bags work too.
**Rain** using rice. Sprinkle rice (or birdseed) onto a thin metal sheet.
Alternatively for rain, you could record the sound of bacon frying.
**Wind** using a Ziploc. Fill a large ziplock with air and then open the bag a bit and force the air out.
**Thunder** with aluminum. Just shake a sheet of aluminum to make a thunder sound.
#### 2\. Making Action or Sci-Fi Sounds
**Ticking Bomb** with a clock. Any clock that ticks will do.
**Hits/Blows** with a pillow. Hit a pillow to make a sound like a body blow. For really hard hits, you might want to whack a sofa cushion with a broomstick.
**Bones breaking** with celery. Just snap the celery stalks in half.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
##### Richard Bennett
Oct 26, 2023• Proven solutions
[0](#commentsBoxSeoTemplate)
Whether you’re making a short film and need sounds to go with your action sequences, or just want some fun noises for your vlog or challenge video, it’s easy to find great sound effects you can use for free online.
Here are 7 places to download free sound effects! Or, if you’re interested in making your own, click here to jump to ‘[Make Your Own Sound Effects](#makeeffects)’.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
## Part 1: YouTube Free Sound Effects Download
#### 1. [Filmora Sound Effects](https://tools.techidaily.com/wondershare/filmora/download/)
Filmora Video Editor provides you with a huge library of free sound effects without download from anywhere else. There are 25 pieces of sound effect available in Filmora, such as transition swoosh, cinematic horn, beep sound and phone ring.

If you do not see the sound effect you want in Filmora, you can also go to the online effect store to find out more sound effects. The sounds are in.wav or mp3 files, so you do not have to use them inside Filmora only. They’re free to use for everyone after downloading, no matter what video editor you use.

The Filmstock audio effect library covers sound effects in different categories: nature sounds, animal sounds, movie sounds, gun sounds, fireworks, bird sounds, cricket sounds, wet sounds, dog barking, water sounds, guitar sounds, city sounds, monster sounds, laughing sounds, dinosaur sounds, fart sounds, pet sounds, dog sounds, car sounds, video game, and thunderstorm.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
#### 2. [Freesound](https://freesound.org/)
Sounds on Freesound are uploaded by users under various Creative Commons licenses (some may require attribution, some may not allow commercial use).

The easiest way to browse the sounds on Freesound is probably to click into Sounds in the top menu, and then ‘Browse tags’ in the menu on the right of your screen. All of the tags on the site will be displayed, and the most commonly used ones will be biggest. The tags include what the sounds are meant to be (i.e. percussion or thunder) and what type of sounds they are (i.e. field-recording or synth).
#### 3. [PacDV](http://www.pacdv.com/sounds/index.html)
PacDV has been producing sound effects since 2001\. You can browse and download sounds individually from their site, or download all at once in a huge bundle. You can use all the sounds for free (you just can’t sell them or provide direct download links to other people).

On the left of the website there’s a menu where you can choose what kinds of sound effects you’re interested in. The categories are:
**Ambience:** this is where you’ll find general background sounds, like ‘car interior’ or ‘grocery store’. Even when nothing in particular is happening, locations have sounds. This is also where you’ll find things like crowd noises.
**Domestic:** these are sounds you hear around the home, like sounds related to doors and appliances.
**Interfaces:** a lot of tech sounds live here, like beeps and clicks. Beeps are all titled ‘Beep’, but nothing else is really labeled beyond being called ‘Interface Sound’. You just have to listen and find out.
**Machines:** a variety of different machine sounds can be found here, from power tools like chainsaws and drills to things like typewriters or paper shredders.
**Mechanical:** this is where you’ll find sounds associated with cameras, coin slots, zippers, and more.
**People:** laughing, clapping, footsteps and even farts – this is where you’ll find human sounds.
**Transportation:** these sounds are all related to vehicles, be they cars or airplanes.
**Voices:** here you’ll find voices saying common things like ‘hi’, ‘aaah’, or ‘come on’.
**Music:** PacDV also has a selection of royalty free music. If you use it in your video, you need to give them credit by including Music by <www.pacdv.com/sounds/> in your video description.
**Miscellaneous:** sounds that don’t quite fit into other categories.
#### 4. [Sound Bible](http://soundbible.com/royalty-free-sounds-1.html)
The sounds on Sound Bible are either in the public domain, which means anyone can use them for anything without restriction, or licensed under the Creative Commons Attribution 3.0 License, which means you just need to provide a credit for the person who created the effect you use. When you click on sound effects on Sound Bible you’ll be able to see whether the effect is Public Domain or Attribution 3.0, and it will tell you who the sound was recorded by. Both public domain and Attribution 3.0 sounds are available for commercial use.

This site has a search function, so if you want dog sounds you can search for ‘dog’. This might be easier than trying to pick the category closest to what you’re looking for and just scrolling through, like you do on some sites.
Sound Bible is updated about 3 times a week, so you can always check back for fresh sounds.
#### 5. [Sound Gator](http://www.soundgator.com/)
Sound Gator has a huge number of sound effects divided into too many categories to list (24). The categories tend to be very specific, like ‘drink sound effects’ or ‘phone sound effects. If you don’t see a category that sounds like what you’re looking for, make sure to check under Misc Sound Effects because there are 68 Mp3#s in there for everything from tools to static.

You can sort the sound effects on Sound Gator by date added, popularity, top rated, runtime, top favorites, or most discussed.
#### 6. [Sounds Crate](https://sfx.productioncrate.com/)
Sounds Crate is part of the larger Production Crate which provides all kinds of resources to creators for free (you can upgrade to a paid account to access exclusive content, but there’s a lot of great content available for free). The categories available on Sounds Crate are:

**Ambient:** room tones and general background noises from nature or cities.
**Animal:** includes things like puppy barks and angry cats.
**Blades and Metal:** you’ll find sounds from swords, chains, and other metal implements here.
**Crashes and Debris:** perfect for action, this is where you’ll find sounds associated with destruction.
**Electricity:** things like electrical blasts and charges can be found here.
**Electronics:** any sound made by anything electrical, like beeps and appliance sounds.
**Explosions and Bangs:** if you have a visual explosion effect, you’ll probably need to combine it with something from here.
**Fight:** find sounds associated with action sequences, like whooshes and punches.
**Gun Related:** everything from reloads to gunshots.
**Impact:** any kind of thud or shattering sound.
**Lock n’ Load:** although there are some ‘gun checking’ sounds in here, it’s mostly clothing related sounds like zippers and Velcro.
**Movement:** wind sounds and whooshes.
**People:** sounds humans make, from voices to footsteps.
**Sci-Fi SFX:** zaps, beeps, and sci-fi ambience.
**Vehicle:** includes both common vehicles like cars and less-common vehicles like tanks.
**Weapons:** both modern weapons like missiles and old-timey things like arrows.
#### 7. [Zapsplat](https://www.zapsplat.com/)
Zapsplat claims to be the fastest growing free sound effects library on the internet. With more than 23,999 professional sounds, and more being added every week, they might just be right. The owner of the site, Alan McKinney, adds 500 sound effects every week by himself and the site also accepts sounds from contributors. All of their sounds were recorded using professional equipment and then edited to make them perfect.

You can even send Alan a message and request specific sound effects if you can’t already find what you want on the site.
On Zapsplat you can browse 26 categories including fantasy, warfare, and animals for individual sounds. Or, you can visit the Free SFX Packs section and download a set of related sounds together. Packs include ‘Magic Wand’, ‘Science Fiction Alarms’, and ‘Cartoon Boings’.
## Part 2: Make Your Own Sound Effects for YouTube Videos
Here are some easy ways you can make your own sound effects at home.
#### 1\. Making Natural Sounds
**Fire** using cellophane. Just crinkle the cellophane wrap to create a sound like a crackling fire. Chip bags work too.
**Rain** using rice. Sprinkle rice (or birdseed) onto a thin metal sheet.
Alternatively for rain, you could record the sound of bacon frying.
**Wind** using a Ziploc. Fill a large ziplock with air and then open the bag a bit and force the air out.
**Thunder** with aluminum. Just shake a sheet of aluminum to make a thunder sound.
#### 2\. Making Action or Sci-Fi Sounds
**Ticking Bomb** with a clock. Any clock that ticks will do.
**Hits/Blows** with a pillow. Hit a pillow to make a sound like a body blow. For really hard hits, you might want to whack a sofa cushion with a broomstick.
**Bones breaking** with celery. Just snap the celery stalks in half.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
##### Richard Bennett
Oct 26, 2023• Proven solutions
[0](#commentsBoxSeoTemplate)
Whether you’re making a short film and need sounds to go with your action sequences, or just want some fun noises for your vlog or challenge video, it’s easy to find great sound effects you can use for free online.
Here are 7 places to download free sound effects! Or, if you’re interested in making your own, click here to jump to ‘[Make Your Own Sound Effects](#makeeffects)’.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
## Part 1: YouTube Free Sound Effects Download
#### 1. [Filmora Sound Effects](https://tools.techidaily.com/wondershare/filmora/download/)
Filmora Video Editor provides you with a huge library of free sound effects without download from anywhere else. There are 25 pieces of sound effect available in Filmora, such as transition swoosh, cinematic horn, beep sound and phone ring.

If you do not see the sound effect you want in Filmora, you can also go to the online effect store to find out more sound effects. The sounds are in.wav or mp3 files, so you do not have to use them inside Filmora only. They’re free to use for everyone after downloading, no matter what video editor you use.

The Filmstock audio effect library covers sound effects in different categories: nature sounds, animal sounds, movie sounds, gun sounds, fireworks, bird sounds, cricket sounds, wet sounds, dog barking, water sounds, guitar sounds, city sounds, monster sounds, laughing sounds, dinosaur sounds, fart sounds, pet sounds, dog sounds, car sounds, video game, and thunderstorm.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)
#### 2. [Freesound](https://freesound.org/)
Sounds on Freesound are uploaded by users under various Creative Commons licenses (some may require attribution, some may not allow commercial use).

The easiest way to browse the sounds on Freesound is probably to click into Sounds in the top menu, and then ‘Browse tags’ in the menu on the right of your screen. All of the tags on the site will be displayed, and the most commonly used ones will be biggest. The tags include what the sounds are meant to be (i.e. percussion or thunder) and what type of sounds they are (i.e. field-recording or synth).
#### 3. [PacDV](http://www.pacdv.com/sounds/index.html)
PacDV has been producing sound effects since 2001\. You can browse and download sounds individually from their site, or download all at once in a huge bundle. You can use all the sounds for free (you just can’t sell them or provide direct download links to other people).

On the left of the website there’s a menu where you can choose what kinds of sound effects you’re interested in. The categories are:
**Ambience:** this is where you’ll find general background sounds, like ‘car interior’ or ‘grocery store’. Even when nothing in particular is happening, locations have sounds. This is also where you’ll find things like crowd noises.
**Domestic:** these are sounds you hear around the home, like sounds related to doors and appliances.
**Interfaces:** a lot of tech sounds live here, like beeps and clicks. Beeps are all titled ‘Beep’, but nothing else is really labeled beyond being called ‘Interface Sound’. You just have to listen and find out.
**Machines:** a variety of different machine sounds can be found here, from power tools like chainsaws and drills to things like typewriters or paper shredders.
**Mechanical:** this is where you’ll find sounds associated with cameras, coin slots, zippers, and more.
**People:** laughing, clapping, footsteps and even farts – this is where you’ll find human sounds.
**Transportation:** these sounds are all related to vehicles, be they cars or airplanes.
**Voices:** here you’ll find voices saying common things like ‘hi’, ‘aaah’, or ‘come on’.
**Music:** PacDV also has a selection of royalty free music. If you use it in your video, you need to give them credit by including Music by <www.pacdv.com/sounds/> in your video description.
**Miscellaneous:** sounds that don’t quite fit into other categories.
#### 4. [Sound Bible](http://soundbible.com/royalty-free-sounds-1.html)
The sounds on Sound Bible are either in the public domain, which means anyone can use them for anything without restriction, or licensed under the Creative Commons Attribution 3.0 License, which means you just need to provide a credit for the person who created the effect you use. When you click on sound effects on Sound Bible you’ll be able to see whether the effect is Public Domain or Attribution 3.0, and it will tell you who the sound was recorded by. Both public domain and Attribution 3.0 sounds are available for commercial use.

This site has a search function, so if you want dog sounds you can search for ‘dog’. This might be easier than trying to pick the category closest to what you’re looking for and just scrolling through, like you do on some sites.
Sound Bible is updated about 3 times a week, so you can always check back for fresh sounds.
#### 5. [Sound Gator](http://www.soundgator.com/)
Sound Gator has a huge number of sound effects divided into too many categories to list (24). The categories tend to be very specific, like ‘drink sound effects’ or ‘phone sound effects. If you don’t see a category that sounds like what you’re looking for, make sure to check under Misc Sound Effects because there are 68 Mp3#s in there for everything from tools to static.

You can sort the sound effects on Sound Gator by date added, popularity, top rated, runtime, top favorites, or most discussed.
#### 6. [Sounds Crate](https://sfx.productioncrate.com/)
Sounds Crate is part of the larger Production Crate which provides all kinds of resources to creators for free (you can upgrade to a paid account to access exclusive content, but there’s a lot of great content available for free). The categories available on Sounds Crate are:

**Ambient:** room tones and general background noises from nature or cities.
**Animal:** includes things like puppy barks and angry cats.
**Blades and Metal:** you’ll find sounds from swords, chains, and other metal implements here.
**Crashes and Debris:** perfect for action, this is where you’ll find sounds associated with destruction.
**Electricity:** things like electrical blasts and charges can be found here.
**Electronics:** any sound made by anything electrical, like beeps and appliance sounds.
**Explosions and Bangs:** if you have a visual explosion effect, you’ll probably need to combine it with something from here.
**Fight:** find sounds associated with action sequences, like whooshes and punches.
**Gun Related:** everything from reloads to gunshots.
**Impact:** any kind of thud or shattering sound.
**Lock n’ Load:** although there are some ‘gun checking’ sounds in here, it’s mostly clothing related sounds like zippers and Velcro.
**Movement:** wind sounds and whooshes.
**People:** sounds humans make, from voices to footsteps.
**Sci-Fi SFX:** zaps, beeps, and sci-fi ambience.
**Vehicle:** includes both common vehicles like cars and less-common vehicles like tanks.
**Weapons:** both modern weapons like missiles and old-timey things like arrows.
#### 7. [Zapsplat](https://www.zapsplat.com/)
Zapsplat claims to be the fastest growing free sound effects library on the internet. With more than 23,999 professional sounds, and more being added every week, they might just be right. The owner of the site, Alan McKinney, adds 500 sound effects every week by himself and the site also accepts sounds from contributors. All of their sounds were recorded using professional equipment and then edited to make them perfect.

You can even send Alan a message and request specific sound effects if you can’t already find what you want on the site.
On Zapsplat you can browse 26 categories including fantasy, warfare, and animals for individual sounds. Or, you can visit the Free SFX Packs section and download a set of related sounds together. Packs include ‘Magic Wand’, ‘Science Fiction Alarms’, and ‘Cartoon Boings’.
## Part 2: Make Your Own Sound Effects for YouTube Videos
Here are some easy ways you can make your own sound effects at home.
#### 1\. Making Natural Sounds
**Fire** using cellophane. Just crinkle the cellophane wrap to create a sound like a crackling fire. Chip bags work too.
**Rain** using rice. Sprinkle rice (or birdseed) onto a thin metal sheet.
Alternatively for rain, you could record the sound of bacon frying.
**Wind** using a Ziploc. Fill a large ziplock with air and then open the bag a bit and force the air out.
**Thunder** with aluminum. Just shake a sheet of aluminum to make a thunder sound.
#### 2\. Making Action or Sci-Fi Sounds
**Ticking Bomb** with a clock. Any clock that ticks will do.
**Hits/Blows** with a pillow. Hit a pillow to make a sound like a body blow. For really hard hits, you might want to whack a sofa cushion with a broomstick.
**Bones breaking** with celery. Just snap the celery stalks in half.
[ ](https://tools.techidaily.com/wondershare/filmora/download/) [ ](https://tools.techidaily.com/wondershare/filmora/download/)

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
## Redefining Your Viewing Experience: YouTube Playlist Shuffle
We often create playlists on YouTube for different moods, genres, and occasions, but you may want to change the order of the videos or songs in your list. This is where the shuffling feature can help you.
Shuffling your YouTube playlist is an excellent way to mix things up and play various videos or songs from different channels without manually selecting each one.
But if you don't know how to use the "Shuffle" feature, we'll show you **how to shuffle YouTube playlists** on PCs, phones, and TVs. So, keep reading to start randomizing your YouTube playlist to mix up your music or video collection!
## How To Shuffle YouTube Playlist On PCs/Phones/TVs?
Whether it's a mix of our favorite songs, a set of dance videos to help get us through our workout, or a compilation of cat videos that never fail to make us smile, we all have that one go-to playlist we want to listen to over and over again.
But sometimes, even our favorite playlist can feel a little stale. That's when it's time to shuffle things up and give the playlist a fresh new feel.
To help you with this, we've provided step-by-step tutorials to help you shuffle Youtube playlists on your computer, phone, or Smart TV without having much trouble.
### Part 1\. How to Shuffle YouTube Playlist on PC?
Here is the step-by-step guide that can help you quickly shuffle your YouTube playlist on your PC, whether it's before playback while watching, or from the Library:
#### How To Shuffle the Playlist Before Playlist Playback
The following is a quick rundown of the steps you need to take to shuffle the playlist before playback:
**Step 1**: First, open a browser on your PC to visit the [**YouTube**](https://www.youtube.com/)website and log in to your account using your credentials.
**Step 2**: Now, click the **"Menu"** (hamburger) icon on the top left of the **YouTube home page** and select your playlist from the menu.

**Step 3:** On the next page, click the **"Shuffle"** button next to the **"Play All"** option in the playlist details section to **randomize your YouTube playlist.**
That's about it! Your videos/songs will now play in random order.
#### How To Shuffle The Playlist While Listening
To learn how to shuffle a YouTube playlist while listening to your favorite songs, do the following steps in sequence:
**Step 1**: Launch your preferred browser on your PC and head to the **"YouTube"** homepage.
**Step 2**: Now, use the search icon to find your favorite song's playlist or choose from the left **"Menu"** panel, and click **"Play All"** to listen to the music.
**Step 3:** When you start playing, you'll find your playlist next to the video player. Click the crisscrossed arrows **"Shuffle"** icon below the playlist title, and the songs will start playing randomly instead of in proper order.

#### How To Shuffle The Playlist In the Library
If you want to randomize your YouTube playlist in the library section, follow these step-by-step instructions:
**Step 1:** In the first step, head to the [**YouTube**](https://www.youtube.com/) website using your preferred browser on the PC and sign in to your account.
**Step 2:** Click the **"Library"** option from the left side panel on the **YouTube homepage** and scroll down to the **"Playlists"** section.
**Step 3**: In the next step, find your playlist and click the **"View Full Playlist"** option below. This will take you to the playlist page.
**Step 4:** Finally, on the playlist page, click the **"Shuffle"** option next to **"Play All"** in the details section. Now, when you start watching the videos in the playlist, they will play randomly.

### Part 2\. How To Shuffle YouTube Playlist On Handy?
It is possible to shuffle your YouTube playlist on your handy (iPhone or Android) with the following workarounds.
#### How To Shuffle The Playlist Before Playlist Playback/From Library
The following steps will help you shuffle your favorite playlists before playlist playback or from the Library:
**Step 1**: If the YouTube app is not installed on your phone, head to the "[App Store](https://apps.apple.com/us/app/youtube-watch-listen-stream/id544007664)" or "Google[Play Store](https://play.google.com/store/apps/details?id=com.google.android.youtube&hl=en&gl=US)" and install the app.
**Step 2:** Now, launch the YouTube app on your handy and tap the **"Library"** option at the bottom right corner of the app's home screen.
**Step 3:** Now, scroll down to the **"Playlist"** section and tap the playlist you want to shuffle. On the playlist screen, tap **"Shuffle"** next to the **"Play All"** option, and that's it!

You can now enjoy your favorite videos and songs in a new order.
#### How To Shuffle The Playlist While Listening
To change the order of your favorite songs in the YouTube playlist while listening to it on your mobile device, do the following steps:
**Step 1:** First, open the **"YouTube"** app on your device and log into your account if you are not signed in already.
**Step 2:** On the app's home screen, tap the **"Search"** bar, type the playlist name, and tap to open it to start listening to your favorite songs.
**Step 3**: You will find the playlist available under the video player. Simply tap the crisscrossed arrows **"Shuffle"** icon below the playlist's title.

That's all to it! Now you can enjoy your YouTube playlist in totally random order.
### Part 3\. How To Shuffle YouTube Playlist on TV?
The YouTube app is also available on smart TVs, which many people find to be a more enjoyable experience than watching YouTube videos on a small screen.
However, unfortunately, there is no way to shuffle a YouTube playlist on a Smart TV. This is a feature that is currently only available on the YouTube website and apps.
But if your Smart TV comes with a built-in Chromecast option, you can screen mirror the YouTube app on your TV and shuffle the playlist to your liking in the following way:
**Step 1**: In the first step, make sure your Smart TV and mobile device are connected to the same internet connection.
**Step 2:** In the next step, launch the YouTube app on your device, and access your playlist under the **"Library"** tab. Tap the **"Shuffle"** icon in the playlist details section and play your playlist
**Step 3**: In the final step, tap the **"Cast"** icon at the top-right of the screen and select your TV from the list to cast to.

Now you can enjoy randomly listen to your favorite songs on a more prominent display without getting bored.
**Note:**
_You can also use other streaming devices like Firestick or Apple Airplay to cast YouTube on your Smart TV._
## A Bouns Tip: How To Make a Music Video by Yourself?
We hope you have found appropriate solutions to shuffle your YouTube Playlist. Besides, supposing you are a music and YouTube lover, do you want to create videos with your favourite music? If yes, you can watch the video we have prepared for you. In this video, you will learn how to easily use a user-friendly video editor, Filmora, to make music videos!
In this comprehensive guide, we've provided a detailed step-by-step guide to show you **how to shuffle YouTube playlists** on your computer, mobile device, or Smart TV.
Hopefully, you've found this article informative and can now enjoy watching or listening to your favorite video/song in a random order in your YouTube playlist.
We often create playlists on YouTube for different moods, genres, and occasions, but you may want to change the order of the videos or songs in your list. This is where the shuffling feature can help you.
Shuffling your YouTube playlist is an excellent way to mix things up and play various videos or songs from different channels without manually selecting each one.
But if you don't know how to use the "Shuffle" feature, we'll show you **how to shuffle YouTube playlists** on PCs, phones, and TVs. So, keep reading to start randomizing your YouTube playlist to mix up your music or video collection!
## How To Shuffle YouTube Playlist On PCs/Phones/TVs?
Whether it's a mix of our favorite songs, a set of dance videos to help get us through our workout, or a compilation of cat videos that never fail to make us smile, we all have that one go-to playlist we want to listen to over and over again.
But sometimes, even our favorite playlist can feel a little stale. That's when it's time to shuffle things up and give the playlist a fresh new feel.
To help you with this, we've provided step-by-step tutorials to help you shuffle Youtube playlists on your computer, phone, or Smart TV without having much trouble.
### Part 1\. How to Shuffle YouTube Playlist on PC?
Here is the step-by-step guide that can help you quickly shuffle your YouTube playlist on your PC, whether it's before playback while watching, or from the Library:
#### How To Shuffle the Playlist Before Playlist Playback
The following is a quick rundown of the steps you need to take to shuffle the playlist before playback:
**Step 1**: First, open a browser on your PC to visit the [**YouTube**](https://www.youtube.com/)website and log in to your account using your credentials.
**Step 2**: Now, click the **"Menu"** (hamburger) icon on the top left of the **YouTube home page** and select your playlist from the menu.

**Step 3:** On the next page, click the **"Shuffle"** button next to the **"Play All"** option in the playlist details section to **randomize your YouTube playlist.**
That's about it! Your videos/songs will now play in random order.
#### How To Shuffle The Playlist While Listening
To learn how to shuffle a YouTube playlist while listening to your favorite songs, do the following steps in sequence:
**Step 1**: Launch your preferred browser on your PC and head to the **"YouTube"** homepage.
**Step 2**: Now, use the search icon to find your favorite song's playlist or choose from the left **"Menu"** panel, and click **"Play All"** to listen to the music.
**Step 3:** When you start playing, you'll find your playlist next to the video player. Click the crisscrossed arrows **"Shuffle"** icon below the playlist title, and the songs will start playing randomly instead of in proper order.

#### How To Shuffle The Playlist In the Library
If you want to randomize your YouTube playlist in the library section, follow these step-by-step instructions:
**Step 1:** In the first step, head to the [**YouTube**](https://www.youtube.com/) website using your preferred browser on the PC and sign in to your account.
**Step 2:** Click the **"Library"** option from the left side panel on the **YouTube homepage** and scroll down to the **"Playlists"** section.
**Step 3**: In the next step, find your playlist and click the **"View Full Playlist"** option below. This will take you to the playlist page.
**Step 4:** Finally, on the playlist page, click the **"Shuffle"** option next to **"Play All"** in the details section. Now, when you start watching the videos in the playlist, they will play randomly.

### Part 2\. How To Shuffle YouTube Playlist On Handy?
It is possible to shuffle your YouTube playlist on your handy (iPhone or Android) with the following workarounds.
#### How To Shuffle The Playlist Before Playlist Playback/From Library
The following steps will help you shuffle your favorite playlists before playlist playback or from the Library:
**Step 1**: If the YouTube app is not installed on your phone, head to the "[App Store](https://apps.apple.com/us/app/youtube-watch-listen-stream/id544007664)" or "Google[Play Store](https://play.google.com/store/apps/details?id=com.google.android.youtube&hl=en&gl=US)" and install the app.
**Step 2:** Now, launch the YouTube app on your handy and tap the **"Library"** option at the bottom right corner of the app's home screen.
**Step 3:** Now, scroll down to the **"Playlist"** section and tap the playlist you want to shuffle. On the playlist screen, tap **"Shuffle"** next to the **"Play All"** option, and that's it!

You can now enjoy your favorite videos and songs in a new order.
#### How To Shuffle The Playlist While Listening
To change the order of your favorite songs in the YouTube playlist while listening to it on your mobile device, do the following steps:
**Step 1:** First, open the **"YouTube"** app on your device and log into your account if you are not signed in already.
**Step 2:** On the app's home screen, tap the **"Search"** bar, type the playlist name, and tap to open it to start listening to your favorite songs.
**Step 3**: You will find the playlist available under the video player. Simply tap the crisscrossed arrows **"Shuffle"** icon below the playlist's title.

That's all to it! Now you can enjoy your YouTube playlist in totally random order.
### Part 3\. How To Shuffle YouTube Playlist on TV?
The YouTube app is also available on smart TVs, which many people find to be a more enjoyable experience than watching YouTube videos on a small screen.
However, unfortunately, there is no way to shuffle a YouTube playlist on a Smart TV. This is a feature that is currently only available on the YouTube website and apps.
But if your Smart TV comes with a built-in Chromecast option, you can screen mirror the YouTube app on your TV and shuffle the playlist to your liking in the following way:
**Step 1**: In the first step, make sure your Smart TV and mobile device are connected to the same internet connection.
**Step 2:** In the next step, launch the YouTube app on your device, and access your playlist under the **"Library"** tab. Tap the **"Shuffle"** icon in the playlist details section and play your playlist
**Step 3**: In the final step, tap the **"Cast"** icon at the top-right of the screen and select your TV from the list to cast to.

Now you can enjoy randomly listen to your favorite songs on a more prominent display without getting bored.
**Note:**
_You can also use other streaming devices like Firestick or Apple Airplay to cast YouTube on your Smart TV._
## A Bouns Tip: How To Make a Music Video by Yourself?
We hope you have found appropriate solutions to shuffle your YouTube Playlist. Besides, supposing you are a music and YouTube lover, do you want to create videos with your favourite music? If yes, you can watch the video we have prepared for you. In this video, you will learn how to easily use a user-friendly video editor, Filmora, to make music videos!
In this comprehensive guide, we've provided a detailed step-by-step guide to show you **how to shuffle YouTube playlists** on your computer, mobile device, or Smart TV.
Hopefully, you've found this article informative and can now enjoy watching or listening to your favorite video/song in a random order in your YouTube playlist.
We often create playlists on YouTube for different moods, genres, and occasions, but you may want to change the order of the videos or songs in your list. This is where the shuffling feature can help you.
Shuffling your YouTube playlist is an excellent way to mix things up and play various videos or songs from different channels without manually selecting each one.
But if you don't know how to use the "Shuffle" feature, we'll show you **how to shuffle YouTube playlists** on PCs, phones, and TVs. So, keep reading to start randomizing your YouTube playlist to mix up your music or video collection!
## How To Shuffle YouTube Playlist On PCs/Phones/TVs?
Whether it's a mix of our favorite songs, a set of dance videos to help get us through our workout, or a compilation of cat videos that never fail to make us smile, we all have that one go-to playlist we want to listen to over and over again.
But sometimes, even our favorite playlist can feel a little stale. That's when it's time to shuffle things up and give the playlist a fresh new feel.
To help you with this, we've provided step-by-step tutorials to help you shuffle Youtube playlists on your computer, phone, or Smart TV without having much trouble.
### Part 1\. How to Shuffle YouTube Playlist on PC?
Here is the step-by-step guide that can help you quickly shuffle your YouTube playlist on your PC, whether it's before playback while watching, or from the Library:
#### How To Shuffle the Playlist Before Playlist Playback
The following is a quick rundown of the steps you need to take to shuffle the playlist before playback:
**Step 1**: First, open a browser on your PC to visit the [**YouTube**](https://www.youtube.com/)website and log in to your account using your credentials.
**Step 2**: Now, click the **"Menu"** (hamburger) icon on the top left of the **YouTube home page** and select your playlist from the menu.

**Step 3:** On the next page, click the **"Shuffle"** button next to the **"Play All"** option in the playlist details section to **randomize your YouTube playlist.**
That's about it! Your videos/songs will now play in random order.
#### How To Shuffle The Playlist While Listening
To learn how to shuffle a YouTube playlist while listening to your favorite songs, do the following steps in sequence:
**Step 1**: Launch your preferred browser on your PC and head to the **"YouTube"** homepage.
**Step 2**: Now, use the search icon to find your favorite song's playlist or choose from the left **"Menu"** panel, and click **"Play All"** to listen to the music.
**Step 3:** When you start playing, you'll find your playlist next to the video player. Click the crisscrossed arrows **"Shuffle"** icon below the playlist title, and the songs will start playing randomly instead of in proper order.

#### How To Shuffle The Playlist In the Library
If you want to randomize your YouTube playlist in the library section, follow these step-by-step instructions:
**Step 1:** In the first step, head to the [**YouTube**](https://www.youtube.com/) website using your preferred browser on the PC and sign in to your account.
**Step 2:** Click the **"Library"** option from the left side panel on the **YouTube homepage** and scroll down to the **"Playlists"** section.
**Step 3**: In the next step, find your playlist and click the **"View Full Playlist"** option below. This will take you to the playlist page.
**Step 4:** Finally, on the playlist page, click the **"Shuffle"** option next to **"Play All"** in the details section. Now, when you start watching the videos in the playlist, they will play randomly.

### Part 2\. How To Shuffle YouTube Playlist On Handy?
It is possible to shuffle your YouTube playlist on your handy (iPhone or Android) with the following workarounds.
#### How To Shuffle The Playlist Before Playlist Playback/From Library
The following steps will help you shuffle your favorite playlists before playlist playback or from the Library:
**Step 1**: If the YouTube app is not installed on your phone, head to the "[App Store](https://apps.apple.com/us/app/youtube-watch-listen-stream/id544007664)" or "Google[Play Store](https://play.google.com/store/apps/details?id=com.google.android.youtube&hl=en&gl=US)" and install the app.
**Step 2:** Now, launch the YouTube app on your handy and tap the **"Library"** option at the bottom right corner of the app's home screen.
**Step 3:** Now, scroll down to the **"Playlist"** section and tap the playlist you want to shuffle. On the playlist screen, tap **"Shuffle"** next to the **"Play All"** option, and that's it!

You can now enjoy your favorite videos and songs in a new order.
#### How To Shuffle The Playlist While Listening
To change the order of your favorite songs in the YouTube playlist while listening to it on your mobile device, do the following steps:
**Step 1:** First, open the **"YouTube"** app on your device and log into your account if you are not signed in already.
**Step 2:** On the app's home screen, tap the **"Search"** bar, type the playlist name, and tap to open it to start listening to your favorite songs.
**Step 3**: You will find the playlist available under the video player. Simply tap the crisscrossed arrows **"Shuffle"** icon below the playlist's title.

That's all to it! Now you can enjoy your YouTube playlist in totally random order.
### Part 3\. How To Shuffle YouTube Playlist on TV?
The YouTube app is also available on smart TVs, which many people find to be a more enjoyable experience than watching YouTube videos on a small screen.
However, unfortunately, there is no way to shuffle a YouTube playlist on a Smart TV. This is a feature that is currently only available on the YouTube website and apps.
But if your Smart TV comes with a built-in Chromecast option, you can screen mirror the YouTube app on your TV and shuffle the playlist to your liking in the following way:
**Step 1**: In the first step, make sure your Smart TV and mobile device are connected to the same internet connection.
**Step 2:** In the next step, launch the YouTube app on your device, and access your playlist under the **"Library"** tab. Tap the **"Shuffle"** icon in the playlist details section and play your playlist
**Step 3**: In the final step, tap the **"Cast"** icon at the top-right of the screen and select your TV from the list to cast to.

Now you can enjoy randomly listen to your favorite songs on a more prominent display without getting bored.
**Note:**
_You can also use other streaming devices like Firestick or Apple Airplay to cast YouTube on your Smart TV._
## A Bouns Tip: How To Make a Music Video by Yourself?
We hope you have found appropriate solutions to shuffle your YouTube Playlist. Besides, supposing you are a music and YouTube lover, do you want to create videos with your favourite music? If yes, you can watch the video we have prepared for you. In this video, you will learn how to easily use a user-friendly video editor, Filmora, to make music videos!
In this comprehensive guide, we've provided a detailed step-by-step guide to show you **how to shuffle YouTube playlists** on your computer, mobile device, or Smart TV.
Hopefully, you've found this article informative and can now enjoy watching or listening to your favorite video/song in a random order in your YouTube playlist.
We often create playlists on YouTube for different moods, genres, and occasions, but you may want to change the order of the videos or songs in your list. This is where the shuffling feature can help you.
Shuffling your YouTube playlist is an excellent way to mix things up and play various videos or songs from different channels without manually selecting each one.
But if you don't know how to use the "Shuffle" feature, we'll show you **how to shuffle YouTube playlists** on PCs, phones, and TVs. So, keep reading to start randomizing your YouTube playlist to mix up your music or video collection!
## How To Shuffle YouTube Playlist On PCs/Phones/TVs?
Whether it's a mix of our favorite songs, a set of dance videos to help get us through our workout, or a compilation of cat videos that never fail to make us smile, we all have that one go-to playlist we want to listen to over and over again.
But sometimes, even our favorite playlist can feel a little stale. That's when it's time to shuffle things up and give the playlist a fresh new feel.
To help you with this, we've provided step-by-step tutorials to help you shuffle Youtube playlists on your computer, phone, or Smart TV without having much trouble.
### Part 1\. How to Shuffle YouTube Playlist on PC?
Here is the step-by-step guide that can help you quickly shuffle your YouTube playlist on your PC, whether it's before playback while watching, or from the Library:
#### How To Shuffle the Playlist Before Playlist Playback
The following is a quick rundown of the steps you need to take to shuffle the playlist before playback:
**Step 1**: First, open a browser on your PC to visit the [**YouTube**](https://www.youtube.com/)website and log in to your account using your credentials.
**Step 2**: Now, click the **"Menu"** (hamburger) icon on the top left of the **YouTube home page** and select your playlist from the menu.

**Step 3:** On the next page, click the **"Shuffle"** button next to the **"Play All"** option in the playlist details section to **randomize your YouTube playlist.**
That's about it! Your videos/songs will now play in random order.
#### How To Shuffle The Playlist While Listening
To learn how to shuffle a YouTube playlist while listening to your favorite songs, do the following steps in sequence:
**Step 1**: Launch your preferred browser on your PC and head to the **"YouTube"** homepage.
**Step 2**: Now, use the search icon to find your favorite song's playlist or choose from the left **"Menu"** panel, and click **"Play All"** to listen to the music.
**Step 3:** When you start playing, you'll find your playlist next to the video player. Click the crisscrossed arrows **"Shuffle"** icon below the playlist title, and the songs will start playing randomly instead of in proper order.

#### How To Shuffle The Playlist In the Library
If you want to randomize your YouTube playlist in the library section, follow these step-by-step instructions:
**Step 1:** In the first step, head to the [**YouTube**](https://www.youtube.com/) website using your preferred browser on the PC and sign in to your account.
**Step 2:** Click the **"Library"** option from the left side panel on the **YouTube homepage** and scroll down to the **"Playlists"** section.
**Step 3**: In the next step, find your playlist and click the **"View Full Playlist"** option below. This will take you to the playlist page.
**Step 4:** Finally, on the playlist page, click the **"Shuffle"** option next to **"Play All"** in the details section. Now, when you start watching the videos in the playlist, they will play randomly.

### Part 2\. How To Shuffle YouTube Playlist On Handy?
It is possible to shuffle your YouTube playlist on your handy (iPhone or Android) with the following workarounds.
#### How To Shuffle The Playlist Before Playlist Playback/From Library
The following steps will help you shuffle your favorite playlists before playlist playback or from the Library:
**Step 1**: If the YouTube app is not installed on your phone, head to the "[App Store](https://apps.apple.com/us/app/youtube-watch-listen-stream/id544007664)" or "Google[Play Store](https://play.google.com/store/apps/details?id=com.google.android.youtube&hl=en&gl=US)" and install the app.
**Step 2:** Now, launch the YouTube app on your handy and tap the **"Library"** option at the bottom right corner of the app's home screen.
**Step 3:** Now, scroll down to the **"Playlist"** section and tap the playlist you want to shuffle. On the playlist screen, tap **"Shuffle"** next to the **"Play All"** option, and that's it!

You can now enjoy your favorite videos and songs in a new order.
#### How To Shuffle The Playlist While Listening
To change the order of your favorite songs in the YouTube playlist while listening to it on your mobile device, do the following steps:
**Step 1:** First, open the **"YouTube"** app on your device and log into your account if you are not signed in already.
**Step 2:** On the app's home screen, tap the **"Search"** bar, type the playlist name, and tap to open it to start listening to your favorite songs.
**Step 3**: You will find the playlist available under the video player. Simply tap the crisscrossed arrows **"Shuffle"** icon below the playlist's title.

That's all to it! Now you can enjoy your YouTube playlist in totally random order.
### Part 3\. How To Shuffle YouTube Playlist on TV?
The YouTube app is also available on smart TVs, which many people find to be a more enjoyable experience than watching YouTube videos on a small screen.
However, unfortunately, there is no way to shuffle a YouTube playlist on a Smart TV. This is a feature that is currently only available on the YouTube website and apps.
But if your Smart TV comes with a built-in Chromecast option, you can screen mirror the YouTube app on your TV and shuffle the playlist to your liking in the following way:
**Step 1**: In the first step, make sure your Smart TV and mobile device are connected to the same internet connection.
**Step 2:** In the next step, launch the YouTube app on your device, and access your playlist under the **"Library"** tab. Tap the **"Shuffle"** icon in the playlist details section and play your playlist
**Step 3**: In the final step, tap the **"Cast"** icon at the top-right of the screen and select your TV from the list to cast to.

Now you can enjoy randomly listen to your favorite songs on a more prominent display without getting bored.
**Note:**
_You can also use other streaming devices like Firestick or Apple Airplay to cast YouTube on your Smart TV._
## A Bouns Tip: How To Make a Music Video by Yourself?
We hope you have found appropriate solutions to shuffle your YouTube Playlist. Besides, supposing you are a music and YouTube lover, do you want to create videos with your favourite music? If yes, you can watch the video we have prepared for you. In this video, you will learn how to easily use a user-friendly video editor, Filmora, to make music videos!
In this comprehensive guide, we've provided a detailed step-by-step guide to show you **how to shuffle YouTube playlists** on your computer, mobile device, or Smart TV.
Hopefully, you've found this article informative and can now enjoy watching or listening to your favorite video/song in a random order in your YouTube playlist.
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="8358498916"
data-ad-format="auto"
data-full-width-responsive="true"></ins> |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.uvigo.esei.pro2.core;
import java.io.FileOutputStream;
import java.io.IOException;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.ParsingException;
import nu.xom.Serializer;
/**
*
* @author Nani
*/
public class Libro extends Referencia {
public static enum tipoFormato {
ELECTRONICO, PAPEL
};
private String editorial;
private String isbn;
private tipoFormato formato;
/**
* XML tags
*/
private static final String ISBN_TAG = "isbn";
private static final String FORMATO_TAG = "formato";
private static final String EDITORIAL_TAG = "editorial";
public static final String LIBRO_TAG = "libro";
public Libro(String editorial, String isbn, tipoFormato formato, String autores, String titulo, int ano) {
super(autores, titulo, ano);
this.editorial = editorial;
this.isbn = isbn;
this.formato = formato;
}
public Libro(String editorial, String isbn, String formato, String autores, String titulo, int ano) {
super(autores, titulo, ano);
this.editorial = editorial;
this.isbn = isbn;
this.formato = getEnumValue(titulo);
}
public Libro(Element e) throws ParsingException {
this(
e.getFirstChildElement(EDITORIAL_TAG).getValue(),
e.getFirstChildElement(ISBN_TAG).getValue(),
e.getFirstChildElement(FORMATO_TAG).getValue(),
e.getFirstChildElement(AUTORES_TAG).getValue(),
e.getFirstChildElement(TITULO_TAG).getValue(),
Integer.parseInt(e.getFirstChildElement(ANO_TAG).getValue())
);
if (e.getFirstChildElement(EDITORIAL_TAG) == null
|| e.getFirstChildElement(ISBN_TAG) != null
|| e.getFirstChildElement(FORMATO_TAG) == null
|| e.getFirstChildElement(AUTORES_TAG) == null
|| e.getFirstChildElement(TITULO_TAG) == null
|| e.getFirstChildElement(ANO_TAG) == null) {
throw new ParsingException("XML incorrecto");
}
}
private tipoFormato getEnumValue(String value) {
tipoFormato toret = null;
switch (value.toLowerCase()) {
case "electronico":
toret = tipoFormato.ELECTRONICO;
break;
case "papel":
toret = tipoFormato.PAPEL;
break;
}
return toret;
}
public String getEditorial() {
return editorial;
}
public String getIsbn() {
return isbn;
}
public tipoFormato getFormato() {
return formato;
}
public void setEditorial(String editorial) {
this.editorial = editorial;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public void setFormato(tipoFormato formato) {
this.formato = formato;
}
@Override
public String toString() {
StringBuilder toret = new StringBuilder();
toret.append("Referencia Libro.\n");
toret.append(super.toString());
toret.append("\tEditorial: ");
toret.append(getEditorial());
toret.append("\tISBN: ");
toret.append(getIsbn());
toret.append("\tFormato: ");
toret.append(getFormato());
return toret.toString();
}
public Element toDOM() {
Element ref = super.toDOM();
ref.setLocalName(LIBRO_TAG);
Element editorialNode = new Element(EDITORIAL_TAG);
editorialNode.appendChild(this.editorial);
Element isbnNode = new Element(ISBN_TAG);
isbnNode.appendChild(this.isbn);
Element formatoNode = new Element(FORMATO_TAG);
formatoNode.appendChild(this.formato.name());
// Crear el documento
ref.appendChild(editorialNode);
ref.appendChild(isbnNode);
ref.appendChild(formatoNode);
return ref;
}
} |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ejb.container.interceptor.security.api;
import java.security.Principal;
import java.util.Collection;
import java.util.Map;
import javax.ejb.EJBAccessException;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import javax.resource.spi.IllegalStateException;
import org.jboss.as.core.security.api.UserPrincipal;
import org.jboss.as.security.api.ConnectionSecurityContext;
import org.jboss.as.security.api.ContextStateCache;
import org.jboss.logging.Logger;
import org.jboss.security.SimplePrincipal;
/**
* The server side security interceptor responsible for handling any security identity propagated from the client.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
* @author Josef Cacek
*/
public class ServerSecurityInterceptor {
private static final Logger LOGGER = Logger.getLogger(ServerSecurityInterceptor.class);
static final String DELEGATED_USER_KEY = ServerSecurityInterceptor.class.getName() + ".DelegationUser";
@AroundInvoke
public Object aroundInvoke(final InvocationContext invocationContext) throws Exception {
Principal desiredUser = null;
UserPrincipal connectionUser = null;
Map<String, Object> contextData = invocationContext.getContextData();
if (contextData.containsKey(DELEGATED_USER_KEY)) {
desiredUser = new SimplePrincipal((String) contextData.get(DELEGATED_USER_KEY));
Collection<Principal> principals = ConnectionSecurityContext.getConnectionPrincipals();
if (principals != null) {
for (Principal current : principals) {
if (current instanceof UserPrincipal) {
connectionUser = (UserPrincipal) current;
break;
}
}
} else {
throw new IllegalStateException("Delegation user requested but no user on connection found.");
}
}
ContextStateCache stateCache = null;
try {
if (desiredUser != null && connectionUser != null
&& (desiredUser.getName().equals(connectionUser.getName()) == false)) {
try {
// The final part of this check is to verify that the change does actually indicate a change in user.
// We have been requested to switch user and have successfully identified the user from the connection
// so now we attempt the switch.
stateCache = ConnectionSecurityContext.pushIdentity(desiredUser, new CurrentUserCredential(connectionUser.getName()));
} catch (Exception e) {
LOGGER.error("Failed to switch security context for user", e);
// Don't propagate the exception stacktrace back to the client for security reasons
throw new EJBAccessException("Unable to attempt switching of user.");
}
}
return invocationContext.proceed();
} finally {
// switch back to original security context
if (stateCache != null) {
ConnectionSecurityContext.popIdentity(stateCache);
}
}
}
} |
import { ProductCardContainer, ProductFooter, ProductTags } from "./styled";
import { useEffect, useState } from "react";
import { api } from "../../../../services/api";
import { AddToCartQtd } from "../../../../components/AddToCartQtd";
import { CartProps } from '../../../../contexts/cartContext'
export function ProductCard({ data }: { data: CartProps }) {
const imageUrl = `${api.defaults.baseURL}/files/${data.image}`
const [tags, setTags] = useState<CartProps>()
const [quantity, setQuantity] = useState<number>(0)
useEffect(() => {
async function fetchProduct() {
const response = await api.get(`/products/${data.id}`);
setTags(response.data);
}
fetchProduct();
}, [data.id]);
function handleIncreaseQty() {
setQuantity(prevstate => prevstate + 1)
}
function handleDecreaseQty() {
if (quantity > 0) setQuantity(prevstate => prevstate - 1)
}
return (
<ProductCardContainer>
<img src={imageUrl} alt="" />
<ProductTags>
{tags?.ingredients?.map((tag, index) => (
<span key={index}>{tag.name}</span>
))}
</ProductTags>
<h1>{data.name}</h1>
<p>{data.description}</p>
<ProductFooter>
<span>R$<strong>{data.price}</strong></span>
<AddToCartQtd
data={data}
quantity={quantity}
onIncrease={handleIncreaseQty}
onDecrease={handleDecreaseQty} />
</ProductFooter>
</ProductCardContainer>
)
} |
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
use HasFactory;
protected $fillable = [
'id',
'user_id',
'first_name',
'last_name',
'job_title',
'city',
'country'
];
/**
* Devuelve el usuario asociado a un customer.
*/
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
/**
* Devuelve los order de un customer determinado.
*/
public function orders()
{
return $this->hasMany(Order::class, 'customer_id');
}
} |
import { useParams, Navigate } from 'react-router-dom';
import apartments from '../datas/apartments.json';
import Profile from '../components/Profile.jsx';
import Collapse from '../components/Collapse.jsx';
import ElementsList from '../components/ElementsList.jsx';
import Rating from '../components/Rating.jsx';
import Slideshow from '../components/Slideshow.jsx';
import BrowserTabTitle from '../components/BrowserTabTitle.jsx';
export default function ApartmentDetails() {
let { id } = useParams();
let apartmentToDisplay = apartments.find(
(apartment) => apartment.id === id,
);
if (!apartmentToDisplay) {
return <Navigate to="/error404" replace />;
}
return (
<>
<BrowserTabTitle tabTitle={'Fiche descriptive - Appartement'} />
<Slideshow
pictures={apartmentToDisplay.pictures}
title={apartmentToDisplay.title}
/>
<section className="apartment">
<div className="apartment-header">
<div className="group-location">
<h1>{apartmentToDisplay.title}</h1>
<h2>{apartmentToDisplay.location}</h2>
<div className="tags">
<ElementsList
list={apartmentToDisplay.tags}
typeList="row"
/>
</div>
</div>
<div className="group-profile">
<Rating rating={apartmentToDisplay.rating} />
<Profile host={apartmentToDisplay.host} />
</div>
</div>
<div className="apartment-description">
<Collapse title="Description">
{apartmentToDisplay.description}
</Collapse>
<Collapse title="Equipements">
<ElementsList
list={apartmentToDisplay.equipments}
typeList="column"
/>
</Collapse>
</div>
</section>
</>
);
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Destructuring</title>
</head>
<body>
<script>
//menggunakan destructuring pada array untuk mengambil data
{
const nama = ["Dzikri", "Fauzi", "Ramdhani", "lala", "lulu", "lele"];
//dengan menggunakan cara biasa
const firstName = nama[0];
const middleName = nama[1];
const lastName = nama [2];
console.log(firstName);
console.log(middleName);
console.log(lastName);
//dengan menggunakan destructuring array
const [namaAwal, namaTengah, namaAkhir, ...lainnya] = nama;
console.log(namaAwal);
console.log(namaTengah);
console.log(namaAkhir);
console.log(lainnya);
}
//menggunakan destructuring pada objek
{
const person = {
firstName : "Dzikri",
middleName : "Fauzi",
lastName : "Ramdhani",
alamat : {
jalan : "Ki Akdar",
kota : "Tangerang",
negara : "Indonesia",
},
hobi : "Ngewibu",
kesukaan : "Game"
}
const {firstName, middleName, lastName , alamat : {jalan, kota, negara}, ...lainnya} = person;
console.log(firstName);
console.log(middleName);
console.log(lastName);
console.log(jalan);
console.log(kota);
console.log(negara);
console.log(lainnya);
}
//menggunakan destructuring pada parameter
{
function displayPerson({firstName, middleName, lastName}){
console.log(firstName);
console.log(middleName);
console.log(lastName);
}
const person = {
firstName : "Dzikri",
middleName : "Fauzi",
lastName : "Ramdhani"
}
displayPerson(person);
}
//menggunakan destructuring pada array parameter
{
function sum([first, second]){
return first + second;
}
console.log(sum([10,10]));
console.log(sum([20,20]));
}
//defaullt value pada destructuring
//default value juga dapat digunakan pada object
{
const name = ["Dzikri", , "Fauzi"];
const [firstName, middleName= "Joko", lastName="Ramdhani"] = name;
console.log(firstName);
console.log(middleName);
console.log(lastName);
}
//mengubah nama variabel pada destructuring
//caranya menggunakan titik dua di belakang destructuringnya dan diikuti nama variable yang diinginkan
{
const person = {
firstName : "Dzikri",
middleName : "Fauzi",
lastName : "Ramdhani",
}
const {firstName : namaDepan , middleName : namaTengah, lastName : namaBelakang} = person;
console.log(namaDepan);
console.log(namaTengah);
console.log(namaBelakang);
}
</script>
</body>
</html> |
import React, { Component } from "react";
import axios from "axios";
export default class Search extends Component {
search = () => {
// 获取输入结构并重命名
const {
keyWordEle: { value: keyWord },
} = this;
this.props.updateAppState({
isLoading: true,
isFirst: false
})
axios.get(`https://api.github.com/search/users?q=${keyWord}`).then(
(res) => {
// console.log("成功", res.data);
this.props.updateAppState({
isLoading: false,
users: res.data.items
})
},
(error) => {
this.props.updateAppState({
isLoading: false,
err: error.message
})
}
);
};
render() {
return (
<section className="jumbotron">
<h3 className="jumbotron-heading">Search Github Users</h3>
<div>
<input
type="text"
ref={(c) => (this.keyWordEle = c)}
placeholder="输入关键字"
/>
<button onClick={this.search}>Search</button>
</div>
</section>
);
}
} |
#include "variadic_functions.h"
#include <stdarg.h>
#include <stdio.h>
/**
*print_numbers - function that prints numbers
*@separator: separates between numbers
*@n: the number of arguments
*
*/
void print_numbers(const char *separator, const unsigned int n, ...)
{
unsigned int i;
int res;
va_list ap;
va_start(ap, n);
for (i = 0; i < n; i++)
{
res = va_arg(ap, int);
printf("%d", res);
if (i < (n - 1) && separator != NULL)
printf("%s", separator);
}
va_end(ap);
printf("\n");
} |
//{ Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
class Solution{
public:
void insertbottom(stack<int>&s, int element)
{
if(s.empty())
{
s.push(element);
return;
}
int item=s.top();
s.pop();
insertbottom(s,element);
s.push(item);
}
void Reverse(stack<int> &St){
if(St.empty())
return;
int item=St.top();
St.pop();
Reverse(St);
insertbottom(St,item);
}
};
//{ Driver Code Starts.
int main(){
int T;
cin>>T;
while(T--){
int N;
cin>>N;
stack<int> St;
for(int i=0;i<N;i++){
int x;
cin>>x;
St.push(x);
}
Solution ob;
ob.Reverse(St);
vector<int>res;
while(St.size())
{
res.push_back(St.top());
St.pop();
}
for(int i = res.size()-1;i>=0;i--)
{
cout<<res[i]<<" ";
}
cout<<endl;
}
}
// } Driver Code Ends |
---
permalink: api/reference_element_api_getfipsreport.html
sidebar: sidebar
keywords: fips,report,get,getting,getfipsreport,feature,support
summary: È possibile utilizzare il metodo GetFipsReport per controllare lo stato di supporto della funzionalità di crittografia FIPS 140-2 di tutti i nodi nel cluster di storage.
---
= GetFipsReport
:allow-uri-read:
:icons: font
:imagesdir: ../media/
[role="lead"]
È possibile utilizzare `GetFipsReport` Metodo per verificare lo stato di supporto della funzione di crittografia FIPS 140-2 di tutti i nodi nel cluster di storage.
== Parametro
Questo metodo non ha alcun parametro di input.
== Valori restituiti
Questo metodo ha i seguenti valori restituiti:
|===
| Nome | Descrizione | Tipo
a|
risultato
a|
Oggetto JSON contenente lo stato del supporto delle funzionalità FIPS 140-2 per ogni nodo e le informazioni sugli errori per ogni nodo che non ha risposto alla query.
a|
xref:reference_element_api_fipsreport.adoc[FipsReport]
|===
== Esempio di richiesta
Le richieste per questo metodo sono simili all'esempio seguente:
[listing]
----
{
"method": "GetFipsReport",
"params": {},
"id" : 1
}
----
== Esempio di risposta
Questo metodo restituisce una risposta simile all'esempio seguente:
[listing]
----
{
"id": 1,
"result": {
"nodes": [
{
"nodeID": 1,
"fipsDrives": "None",
"httpsEnabled": true
},
{
"nodeID": 3,
"fipsDrives": "None",
"httpsEnabled": true
}
],
"errorNodes": [
{
"nodeID": 2,
"error": {
"message": "The RPC timed out.",
"name": "xRpcTimeout"
}
}
]
}
}
----
== Novità dalla versione
10.3 |
function do_preprocessing(config_file, num)
%%% Function to copy the raw images for the source directory into the
%%% directory for the experiment and perform various normalizations on them
%%% in the process.
%%% Currently the function normalizes all images to a fixed size
%%% (specificed in Preprocessing.Image_Size) using the axis specified in
%%% Preprocessing.Axis_For_Resizing (either 'x' or 'y').
%% Also rescales file containing ground thruth locations of objects
%% within the scene. File name that holds locations of objects is
%% specified in Global.Ground_Truth_Name. The variable in the file
%% is gt_bounding_boxes which is a 1 x nImages (of that class) cell
%% array, each element holding a 4 x nInstances (per image) matrix, with
%% the bounding box for each instance within the image. The format is:
%% [top_left_x top_left_y width height];
%% (should originally be in subdirectories of IMAGE_DIR, but will be
%% copied to RUN_DIR by do_preprocessing.m)
%%% All images are put into the RUNDIR/Global.Image_Dir_Name directory in one
%%% big collection; i.e. all images from all classes will be in the same directory
%%% R.Fergus (fergus@csail.mit.edu) 8/9/05.
%%% evaluate global configuration file
eval(config_file);
%%% reset frame counter
frame_counter = 0;
test_counter = 0;
%%% Remove 'images' and 'test_images' dirs
outdir = char(string(RUN_DIR)+'/'+Global.Image_Dir_Name);
if exist(outdir,'dir')
rmdir(outdir,'s');
end
mkdir(outdir);
outdir = char(TEST_DIR);
if exist(outdir,'dir')
rmdir(outdir,'s');
end
%%% make directory in experimental dir. for images
[s,m1,m2]=mkdir(RUN_DIR,Global.Image_Dir_Name);
%%%% Go through each of the categories
files = dir(IMAGE_DIR);
dirFlags = [files.isdir];
subFolders = files(dirFlags);
pat_range = 149;
pat_offset = 13;
patients_processed = 0;
fprintf("Performing do_preprocessing on test/training images");
for pat = 1 : pat_range
pat_num = "";
if pat < pat_offset
pat_num = "-1_"+pat;
else
pat_num = int2str(pat - pat_offset);
end
pat_dir = IMAGE_DIR + "/patient" + pat_num;
% Check that our patient exists before trying to load files
% Don't include test patient in training images - we will handle this
% later
num_processed = 0;
if exist(pat_dir, 'dir') && pat_num ~= HEALTHY_PATIENTS(num)
fprintf("Patient %s: ", pat_num);
patients_processed = patients_processed + 1;
for cat = 1 : Categories.Number
%%% Generate filenames for images
in_file_names = dir(char(pat_dir+'/'+Categories.Name(cat)));
for frame = 3:length(in_file_names)
file_name = string(in_file_names(frame).folder) + '/' + string(in_file_names(frame).name);
%%% read image in
im = imread(char(file_name));
%%% find out size of image
[imy,imx,imz] = size(im);
%%% Resize image, proved Preprocessing.Image_Size isn't zero
%%% in which case, do nothing.
if (Preprocessing.Image_Size>0)
%%% Figure out scale factor for resizing along appropriate axis
if strcmp(Preprocessing.Axis_For_Resizing,'x')
scale_factor = Preprocessing.Image_Size / imx;
elseif strcmp(Preprocessing.Axis_For_Resizing,'y')
scale_factor = Preprocessing.Image_Size / imy;
else
error('Unknown axis');
end
%%% Rescale image using bilinear scaling
im = imresize(im,scale_factor,Preprocessing.Rescale_Mode);
else
scale_factor = 1;
end
outdir = char(string(RUN_DIR)+'/'+Global.Image_Dir_Name+'/'+Categories.Name(cat));
if ~exist(outdir,'dir')
mkdir(outdir);
end
%%% increment frame counter
frame_counter = frame_counter + 1;
num_processed = num_processed + 1;
%%% Now save out to directory.
fname = char(string(RUN_DIR)+'/'+Global.Image_Dir_Name+'/'+Categories.Name(cat)+'/'+Global.Image_File_Name+prefZeros(frame_counter,Global.Num_Zeros)+Global.Image_Extension);
imwrite(im,fname,Global.Image_Extension(2:end));
%if (mod(frame_counter,10)==0)
% fprintf('.');
%end
end
end
fprintf("DONE\n");
%fprintf("\nPatient "+pat_num+": "+int2str(num_processed)+" images processed\tTotal: "+int2str(frame_counter)+"\n");
elseif pat_num == HEALTHY_PATIENTS(num) % put test patient data into sub folder
fprintf("Patient %s: ", pat_num);
for cat = 1 : Categories.Number
cat_dir = char(string(TEST_DIR) + '/' + Categories.Name(cat));
if exist(cat_dir,'dir')
rmdir(cat_dir,'s');
end
mkdir(cat_dir);
%%% Generate filenames for images
in_file_names = dir(char(pat_dir+'/'+Categories.Name(cat)));
for frame = 3:length(in_file_names)
file_name = string(in_file_names(frame).folder) + '/' + string(in_file_names(frame).name);
%%% read image in
im = imread(char(file_name));
%%% find out size of image
[imy,imx,imz] = size(im);
%%% Resize image, proved Preprocessing.Image_Size isn't zero
%%% in which case, do nothing.
if (Preprocessing.Image_Size>0)
%%% Figure out scale factor for resizing along appropriate axis
if strcmp(Preprocessing.Axis_For_Resizing,'x')
scale_factor = Preprocessing.Image_Size / imx;
elseif strcmp(Preprocessing.Axis_For_Resizing,'y')
scale_factor = Preprocessing.Image_Size / imy;
else
error('Unknown axis');
end
%%% Rescale image using bilinear scaling
im = imresize(im,scale_factor,Preprocessing.Rescale_Mode);
else
scale_factor = 1;
end
test_counter = test_counter + 1;
%%% Now save out to directory.
fname = char(string(TEST_DIR)+'/'+Categories.Name(cat)+'/'+Global.Image_File_Name+prefZeros(test_counter,Global.Num_Zeros)+Global.Image_Extension);
imwrite(im,fname,Global.Image_Extension(2:end));
end
end
fprintf("DONE\n");
end
end |
/*
* Copyright (c) 2014-2017 National Technology and Engineering
* Solutions of Sandia, LLC. Under the terms of Contract DE-NA0003525
* with National Technology and Engineering Solutions of Sandia, LLC,
* the U.S. Government retains certain rights in this software.
*
* 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.
*
* 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 THE COPYRIGHT
* HOLDER 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.
*/
#include <tracktable/Domain/Terrestrial.h>
#include <iostream>
#include <fstream>
int test_point_reader(int expected_num_points, const char* filename)
{
std::ifstream infile;
infile.open(filename);
int num_points = 0;
int error_count = 0;
typedef tracktable::domain::terrestrial::trajectory_point_reader_type point_reader_type;
point_reader_type read_points(infile);
read_points.set_real_field_column("heading", 5);
read_points.set_string_field_column("string_test", 0);
read_points.set_time_field_column("timestamp_test", 1);
read_points.set_real_field_column("numeric_test", 2);
for (point_reader_type::iterator iter = read_points.begin();
iter != read_points.end();
++iter)
{
++num_points;
tracktable::domain::terrestrial::trajectory_point_type next_point(*iter);
if (next_point.object_id() != next_point.string_property("string_test"))
{
std::cout << "ERROR: Expected object ID ("
<< next_point.object_id()
<< ") and string property ("
<< next_point.string_property("string_test")
<< ") to match on point "
<< num_points << "\n";
++error_count;
}
if (next_point.timestamp() != next_point.timestamp_property("timestamp_test"))
{
std::cout << "ERROR: Expected timestamp ("
<< next_point.timestamp()
<< ") and timestamp property ("
<< next_point.timestamp_property("timestamp_test")
<< ") to match on point "
<< num_points << "\n";
++error_count;
}
if (next_point.longitude() != next_point.real_property("numeric_test"))
{
std::cout << "ERROR: Expected longitude ("
<< next_point.longitude()
<< ") and numeric property ("
<< next_point.real_property("numeric_test")
<< ") to match on point "
<< num_points << "\n";
++error_count;
}
#if 0
std::cout << "next point: object_id "
<< next_point.object_id()
<< ", timestamp "
<< next_point.timestamp()
<< ", position ("
<< next_point.longitude()
<< ", "
<< next_point.latitude()
<< "), "
<< "heading "
<< next_point.heading()
<< ", string test "
<< next_point.property("string_test")
<< ", timestamp test "
<< next_point.property("timestamp_test")
<< ", numeric test "
<< next_point.property("numeric_test")
<< "\n";
#endif
}
std::cout << "test_trajectory_point_reader: Read "
<< num_points
<< " points from file "
<< filename << "\n";
if (num_points != expected_num_points)
{
std::cout << "ERROR: We expected to see "
<< expected_num_points << " points"
<< " but actually saw "
<< num_points << ".\n";
++error_count;
}
else
{
std::cout << "SUCCESS: We found the expected number of points ("
<< num_points << ")" << std::endl;
}
return error_count;
}
// ----------------------------------------------------------------------
int main(int argc, char* argv[])
{
int error_count = 0;
if (argc != 3)
{
std::cerr << "usage: "
<< argv[0] << " expected_num_points file_to_read.txt\n";
return 1;
}
int expected_num_points = atoi(argv[1]);
char* filename = argv[2];
error_count += test_point_reader(expected_num_points, filename);
std::cout << "Returning exit code " << error_count << "\n";
return error_count;
} |
package com.demo.englishdectionary.data.local.words800
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface Words800Dao {
@Query("SELECT * FROM words800entity WHERE id = :letter")
fun getWordsStartingWith(letter: Char): Flow<Words800Entity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert800Word(words800Entity: Words800Entity)
@Query("SELECT COUNT(*) FROM words800entity")
suspend fun getWordCount(): Int
} |
/**
* ***************************************************************************** Copyright (c) 2000,
* 2014 IBM Corporation and others. All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 which accompanies this
* distribution, and is available at http://www.eclipse.org/legal/epl-v10.html
*
* <p>Contributors: IBM Corporation - initial API and implementation
* *****************************************************************************
*/
package org.eclipse.jdt.internal.corext.dom;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
import org.eclipse.jdt.core.dom.ArrayType;
import org.eclipse.jdt.core.dom.CheASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Dimension;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.IAnnotationBinding;
import org.eclipse.jdt.core.dom.IExtendedModifier;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.InfixExpression;
import org.eclipse.jdt.core.dom.InfixExpression.Operator;
import org.eclipse.jdt.core.dom.LambdaExpression;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.NodeFinder;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.TypeParameter;
import org.eclipse.jdt.core.dom.UnionType;
import org.eclipse.jdt.core.dom.VariableDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.rewrite.ImportRewrite;
import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext;
/**
* JDT-UI-internal helper methods to create new {@link ASTNode}s. Complements <code>AST#new*(..)
* </code> and <code>ImportRewrite#add*(..)</code>.
*/
public class ASTNodeFactory {
private static final String STATEMENT_HEADER = "class __X__ { void __x__() { "; // $NON-NLS-1$
private static final String STATEMENT_FOOTER = "}}"; // $NON-NLS-1$
private static final String TYPE_HEADER = "class __X__ { abstract "; // $NON-NLS-1$
private static final String TYPE_FOOTER = " __f__(); }}"; // $NON-NLS-1$
private static final String TYPEPARAM_HEADER = "class __X__ { abstract <"; // $NON-NLS-1$
private static final String TYPEPARAM_FOOTER = "> void __f__(); }}"; // $NON-NLS-1$
private static class PositionClearer extends GenericVisitor {
public PositionClearer() {
super(true);
}
@Override
protected boolean visitNode(ASTNode node) {
node.setSourceRange(-1, 0);
return true;
}
}
private ASTNodeFactory() {
// no instance;
}
public static ASTNode newStatement(AST ast, String content) {
StringBuffer buffer = new StringBuffer(STATEMENT_HEADER);
buffer.append(content);
buffer.append(STATEMENT_FOOTER);
CheASTParser p = CheASTParser.newParser(ast.apiLevel());
p.setSource(buffer.toString().toCharArray());
CompilationUnit root = (CompilationUnit) p.createAST(null);
ASTNode result =
ASTNode.copySubtree(
ast, NodeFinder.perform(root, STATEMENT_HEADER.length(), content.length()));
result.accept(new PositionClearer());
return result;
}
public static Name newName(AST ast, String qualifiedName) {
return ast.newName(qualifiedName);
}
public static TypeParameter newTypeParameter(AST ast, String content) {
StringBuffer buffer = new StringBuffer(TYPEPARAM_HEADER);
buffer.append(content);
buffer.append(TYPEPARAM_FOOTER);
CheASTParser p = CheASTParser.newParser(ast.apiLevel());
p.setSource(buffer.toString().toCharArray());
CompilationUnit root = (CompilationUnit) p.createAST(null);
List<AbstractTypeDeclaration> list = root.types();
TypeDeclaration typeDecl = (TypeDeclaration) list.get(0);
MethodDeclaration methodDecl = typeDecl.getMethods()[0];
TypeParameter tp = (TypeParameter) methodDecl.typeParameters().get(0);
ASTNode result = ASTNode.copySubtree(ast, tp);
result.accept(new PositionClearer());
return (TypeParameter) result;
}
public static Type newType(AST ast, String content) {
StringBuffer buffer = new StringBuffer(TYPE_HEADER);
buffer.append(content);
buffer.append(TYPE_FOOTER);
CheASTParser p = CheASTParser.newParser(ast.apiLevel());
p.setSource(buffer.toString().toCharArray());
CompilationUnit root = (CompilationUnit) p.createAST(null);
List<AbstractTypeDeclaration> list = root.types();
TypeDeclaration typeDecl = (TypeDeclaration) list.get(0);
MethodDeclaration methodDecl = typeDecl.getMethods()[0];
ASTNode type = methodDecl.getReturnType2();
ASTNode result = ASTNode.copySubtree(ast, type);
result.accept(new PositionClearer());
return (Type) result;
}
/**
* Returns an {@link ArrayType} that adds one dimension to the given type node. If the given node
* is already an ArrayType, then a new {@link Dimension} without annotations is inserted at the
* first position.
*
* @param type the type to be wrapped
* @return the array type
* @since 3.10
*/
public static ArrayType newArrayType(Type type) {
if (type instanceof ArrayType) {
Dimension dimension = type.getAST().newDimension();
ArrayType arrayType = (ArrayType) type;
arrayType.dimensions().add(0, dimension); // first dimension is outermost
return arrayType;
} else {
return type.getAST().newArrayType(type);
}
}
/**
* Returns the new type node corresponding to the type of the given declaration including the
* extra dimensions.
*
* @param ast The AST to create the resulting type with.
* @param declaration The variable declaration to get the type from
* @return a new type node created with the given AST.
*/
public static Type newType(AST ast, VariableDeclaration declaration) {
return newType(ast, declaration, null, null);
}
/**
* Returns the new type node corresponding to the type of the given declaration including the
* extra dimensions. If the type is a {@link UnionType}, use the LUB type. If the <code>
* importRewrite</code> is <code>null</code>, the type may be fully-qualified.
*
* @param ast The AST to create the resulting type with.
* @param declaration The variable declaration to get the type from
* @param importRewrite the import rewrite to use, or <code>null</code>
* @param context the import rewrite context, or <code>null</code>
* @return a new type node created with the given AST.
* @since 3.7.1
*/
public static Type newType(
AST ast,
VariableDeclaration declaration,
ImportRewrite importRewrite,
ImportRewriteContext context) {
if (declaration instanceof VariableDeclarationFragment
&& declaration.getParent() instanceof LambdaExpression) {
return newType(
(LambdaExpression) declaration.getParent(),
(VariableDeclarationFragment) declaration,
ast,
importRewrite,
context);
}
Type type = ASTNodes.getType(declaration);
if (declaration instanceof SingleVariableDeclaration) {
Type type2 = ((SingleVariableDeclaration) declaration).getType();
if (type2 instanceof UnionType) {
ITypeBinding typeBinding = type2.resolveBinding();
if (typeBinding != null) {
if (importRewrite != null) {
type = importRewrite.addImport(typeBinding, ast, context);
return type;
} else {
String qualifiedName = typeBinding.getQualifiedName();
if (qualifiedName.length() > 0) {
type = ast.newSimpleType(ast.newName(qualifiedName));
return type;
}
}
}
// XXX: fallback for intersection types or unresolved types: take first type of union
type = (Type) ((UnionType) type2).types().get(0);
return type;
}
}
type = (Type) ASTNode.copySubtree(ast, type);
List<Dimension> extraDimensions = declaration.extraDimensions();
if (!extraDimensions.isEmpty()) {
ArrayType arrayType;
if (type instanceof ArrayType) {
arrayType = (ArrayType) type;
} else {
arrayType = ast.newArrayType(type, 0);
type = arrayType;
}
arrayType.dimensions().addAll(ASTNode.copySubtrees(ast, extraDimensions));
}
return type;
}
private static Type newType(
LambdaExpression lambdaExpression,
VariableDeclarationFragment declaration,
AST ast,
ImportRewrite importRewrite,
ImportRewriteContext context) {
IMethodBinding method = lambdaExpression.resolveMethodBinding();
if (method != null) {
ITypeBinding[] parameterTypes = method.getParameterTypes();
int index = lambdaExpression.parameters().indexOf(declaration);
ITypeBinding typeBinding = parameterTypes[index];
if (importRewrite != null) {
return importRewrite.addImport(typeBinding, ast, context);
} else {
String qualifiedName = typeBinding.getQualifiedName();
if (qualifiedName.length() > 0) {
return newType(ast, qualifiedName);
}
}
}
// fall-back
return ast.newSimpleType(ast.newSimpleName("Object")); // $NON-NLS-1$
}
/**
* Returns the new type node representing the return type of <code>lambdaExpression</code>
* including the extra dimensions.
*
* @param lambdaExpression the lambda expression
* @param ast the AST to create the return type with
* @param importRewrite the import rewrite to use, or <code>null</code>
* @param context the import rewrite context, or <code>null</code>
* @return a new type node created with the given AST representing the return type of <code>
* lambdaExpression</code>
* @since 3.10
*/
public static Type newReturnType(
LambdaExpression lambdaExpression,
AST ast,
ImportRewrite importRewrite,
ImportRewriteContext context) {
IMethodBinding method = lambdaExpression.resolveMethodBinding();
if (method != null) {
ITypeBinding returnTypeBinding = method.getReturnType();
if (importRewrite != null) {
return importRewrite.addImport(returnTypeBinding, ast);
} else {
String qualifiedName = returnTypeBinding.getQualifiedName();
if (qualifiedName.length() > 0) {
return newType(ast, qualifiedName);
}
}
}
// fall-back
return ast.newSimpleType(ast.newSimpleName("Object")); // $NON-NLS-1$
}
/**
* Returns an expression that is assignable to the given type. <code>null</code> is returned if
* the type is the 'void' type.
*
* @param ast The AST to create the expression for
* @param type The type of the returned expression
* @param extraDimensions Extra dimensions to the type
* @return the Null-literal for reference types, a boolean-literal for a boolean type, a number
* literal for primitive types or <code>null</code> if the type is void.
*/
public static Expression newDefaultExpression(AST ast, Type type, int extraDimensions) {
if (extraDimensions == 0 && type.isPrimitiveType()) {
PrimitiveType primitiveType = (PrimitiveType) type;
if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.BOOLEAN) {
return ast.newBooleanLiteral(false);
} else if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.VOID) {
return null;
} else {
return ast.newNumberLiteral("0"); // $NON-NLS-1$
}
}
return ast.newNullLiteral();
}
/**
* Returns an expression that is assignable to the given type binding. <code>null</code> is
* returned if the type is the 'void' type.
*
* @param ast The AST to create the expression for
* @param type The type binding to which the returned expression is compatible to
* @return the Null-literal for reference types, a boolean-literal for a boolean type, a number
* literal for primitive types or <code>null</code> if the type is void.
*/
public static Expression newDefaultExpression(AST ast, ITypeBinding type) {
if (type.isPrimitive()) {
String name = type.getName();
if ("boolean".equals(name)) { // $NON-NLS-1$
return ast.newBooleanLiteral(false);
} else if ("void".equals(name)) { // $NON-NLS-1$
return null;
} else {
return ast.newNumberLiteral("0"); // $NON-NLS-1$
}
}
return ast.newNullLiteral();
}
/**
* Returns a list of newly created Modifier nodes corresponding to the given modifier flags.
*
* @param ast The AST to create the nodes for.
* @param modifiers The modifier flags describing the modifier nodes to create.
* @return Returns a list of nodes of type {@link Modifier}.
*/
public static List<Modifier> newModifiers(AST ast, int modifiers) {
return ast.newModifiers(modifiers);
}
/**
* Returns a list of newly created Modifier nodes corresponding to a given list of existing
* modifiers.
*
* @param ast The AST to create the nodes for.
* @param modifierNodes The modifier nodes describing the modifier nodes to create. Only nodes of
* type {@link Modifier} are looked at and cloned. To create a full copy of the list consider
* to use {@link ASTNode#copySubtrees(AST, List)}.
* @return Returns a list of nodes of type {@link Modifier}.
*/
public static List<Modifier> newModifiers(
AST ast, List<? extends IExtendedModifier> modifierNodes) {
List<Modifier> res = new ArrayList<Modifier>(modifierNodes.size());
for (int i = 0; i < modifierNodes.size(); i++) {
Object curr = modifierNodes.get(i);
if (curr instanceof Modifier) {
res.add(ast.newModifier(((Modifier) curr).getKeyword()));
}
}
return res;
}
public static Expression newInfixExpression(
AST ast, Operator operator, ArrayList<Expression> operands) {
if (operands.size() == 1) return operands.get(0);
InfixExpression result = ast.newInfixExpression();
result.setOperator(operator);
result.setLeftOperand(operands.get(0));
result.setRightOperand(operands.get(1));
result.extendedOperands().addAll(operands.subList(2, operands.size()));
return result;
}
public static Type newCreationType(
AST ast,
ITypeBinding typeBinding,
ImportRewrite importRewrite,
ImportRewriteContext importContext) {
if (typeBinding.isParameterizedType()) {
Type baseType =
newCreationType(ast, typeBinding.getTypeDeclaration(), importRewrite, importContext);
ParameterizedType parameterizedType = ast.newParameterizedType(baseType);
for (ITypeBinding typeArgument : typeBinding.getTypeArguments()) {
parameterizedType
.typeArguments()
.add(newCreationType(ast, typeArgument, importRewrite, importContext));
}
return parameterizedType;
} else if (typeBinding.isParameterizedType()) {
Type elementType =
newCreationType(ast, typeBinding.getElementType(), importRewrite, importContext);
ArrayType arrayType = ast.newArrayType(elementType, 0);
while (typeBinding.isArray()) {
Dimension dimension = ast.newDimension();
IAnnotationBinding[] typeAnnotations = typeBinding.getTypeAnnotations();
for (IAnnotationBinding typeAnnotation : typeAnnotations) {
dimension
.annotations()
.add(importRewrite.addAnnotation(typeAnnotation, ast, importContext));
}
arrayType.dimensions().add(dimension);
typeBinding = typeBinding.getComponentType();
}
return arrayType;
} else if (typeBinding.isWildcardType()) {
ITypeBinding bound = typeBinding.getBound();
typeBinding = (bound != null) ? bound : typeBinding.getErasure();
return newCreationType(ast, typeBinding, importRewrite, importContext);
} else {
return importRewrite.addImport(typeBinding, ast, importContext);
}
}
} |
@testable import Book
import XCTest
final class BookTests: XCTestCase {
private var bookUrl: URL {
get throws {
guard let url = URL(string: "https://books.apple.com/Fus/Fbook/F12-rules-for-life") else {
throw URLError(.badURL)
}
return url
}
}
func test_init() throws {
let title = "12 rules for life"
let author = "Jordan B. Peterson"
let released = Date.now
let genre = "Nonfiction"
let url = try bookUrl
let book = Book(
title: title,
author: author,
released: released,
genre: genre,
url: url
)
XCTAssertEqual(book.title, title)
XCTAssertEqual(book.author, author)
XCTAssertEqual(book.released, released)
XCTAssertEqual(book.genre, genre)
XCTAssertEqual(book.url, url)
XCTAssertEqual(book.id, "\(author):\(title)")
}
} |
// https://stackoverflow.com/a/11832950
export function round(float: number, { precision }: { precision: number } = { precision: 0 }) {
const magnitude = 10 ** precision
return Math.round((float + Number.EPSILON) * magnitude) / magnitude
}
export function clamp(float: number, { min, max }: { min: number, max: number }) {
return Math.min(Math.max(float, min), max)
}
if (import.meta.vitest) {
const { expect, it: test } = import.meta.vitest
//// test("round", () => {
//// expect(round(-1)).toBe(-1)
//// expect(round(-0.5)).toBe(-0.5)
//// expect(round(-0.25)).toBe(-0.25)
//// expect(round(-0.125)).toBe(-0.125)
//// expect(round(-0.0625)).toBe(-0.0625)
//// expect(round(-0.03125)).toBe(-0.0313)
////
//// expect(round(1)).toBe(1)
//// expect(round(0.5)).toBe(0.5)
//// expect(round(0.25)).toBe(0.25)
//// expect(round(0.125)).toBe(0.125)
//// expect(round(0.0625)).toBe(0.0625)
//// expect(round(0.03125)).toBe(0.0313)
//// })
test("clamp", () => {
expect(clamp(+0, { min: -1, max: 1 })).toEqual(+0)
expect(clamp(-1, { min: -1, max: 1 })).toEqual(-1)
expect(clamp(-1, { min: -2, max: 1 })).toEqual(-1)
expect(clamp(+1, { min: -2, max: 1 })).toEqual(+1)
expect(clamp(+2, { min: -2, max: 1 })).toEqual(+1)
})
} |
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const usersModel_1 = __importDefault(require("../model/usersModel"));
const jwt = require('jsonwebtoken');
class usersController {
constructor() {
this.login = (req, res) => {
const { email, password } = req.body;
this.model.login(email, password, (status) => {
switch (status) {
case 1:
console.log('Entre 1');
const token = jwt.sign({ email: email }, process.env.TOKEN_SECRET, { expiresIn: '7d', algorithm: "HS256" });
res.header('auth-token', token).json({ error: null, data: { email, token } });
break;
case 0:
console.log('Entre 0');
return res.status(401).json({ error: true, message: 'Email o contraseña incorrecta!' });
case -1:
console.log('Entre -1');
return res.status(500).json({ error: true, message: 'Algo ha salido mal al realizar el registro!' });
}
});
};
this.register = (req, res) => {
const { email, password } = req.body;
this.model.register(email, password, (error) => {
if (!error) {
return res.status(200).json({ error: false, message: 'Registro exitóso!' });
}
else {
const usedEmailError = error.keyPattern['email'];
if (usedEmailError) {
return res.status(409).json({ error: true, message: 'El correo ya se encuentra en uso!' });
}
return res.status(500).json({ error: true, message: 'Algo ha salido mal al realizar el registro!' });
}
});
};
this.getProducts = (req, res) => {
this.model.getProducts((error, row) => {
if (error) {
return res.status(500).json({ error: true, message: 'Algo ha salido mal al realizar la inserción!' });
}
if (Object.keys(row).length != 0) {
return res.status(200).json(row);
}
return res.status(200).json({ error: false, message: 'No hay productos favoritos por el momento!' });
});
};
this.addFavorites = (req, res) => {
const { products } = req.body;
const email = req.body.user["email"];
this.model.addFavorites(email, products, (status) => {
switch (status) {
case 1:
return res.status(200).json({ error: false, message: 'Inserción exitosa!' });
case 0:
return res.status(200).json({ error: true, message: 'El producto ingresado no es válido!' });
case -1:
return res.status(500).json({ error: true, message: 'Algo ha salido mal al realizar la inserción!' });
}
});
};
this.getFavorites = (req, res) => {
const email = req.body.user["email"];
this.model.getFavorites(email, (error, row) => __awaiter(this, void 0, void 0, function* () {
if (error) {
return res.status(500).json({ error: true, message: 'Algo ha salido mal al realizar la consulta de favoritos para este usuario!' });
}
if (Object.keys(row).length != 0) {
const ids = JSON.parse(JSON.stringify(row))[0]['favorites'];
const favorites = [];
for (let i = 0; i < ids.length; i++) {
yield this.model.getProduct(parseInt(ids[i]), (productError, product) => {
if (!productError) {
favorites.push(product);
}
else {
return res.status(500).json({ error: true, message: 'Algo ha salido mal al realizar la consulta de favoritos para este usuario!' });
}
});
}
return res.status(200).json(favorites);
}
return res.status(200).json({ error: false, message: 'No hay productos favoritos por el momento!' });
}));
};
this.getProductImage = (req, res) => {
const { id } = req.params;
this.model.getProductImage(parseInt(id), (row) => {
if (row != '') {
res.download(row);
}
else {
return res.status(404).json({ error: true, message: 'No existen productos con ese id!' });
}
});
};
this.verifyToken = (req, res, next) => {
const { authorization } = req.headers;
if (!authorization) {
return res.status(401).json({ error: true, message: 'No se ha proporcionado un token de acceso. Acceso denegado!' });
}
const bearerToken = authorization.split(' ')[1];
try {
const decodedToken = jwt.verify(bearerToken, process.env.TOKEN_SECRET);
req.body.user = decodedToken;
next();
}
catch (error) {
if (error instanceof jwt.TokenExpiredError) {
res.status(200).json({ error: true, message: 'El token ha expirado!' });
}
res.status(406).json({ error: true, message: 'EL token no es válido!' });
}
};
this.model = new usersModel_1.default();
}
}
exports.default = usersController; |
different commits and see how they are displayed on the Github website. Even though all the commands below will be pushed using exclusively the f4k3usr Github account, some of the commits will look like they were submitted by my real pjbgf account— however, bear in mind that my real credentials were not at all used.
To start, let’s assume that the git settings are already setup for f4k3usr user:
git config --global user.email "f4k3usr--REDACTED--"
git config --global user.name "f4k3usr"
To spoof a commit you only need to force an author, setting it to the email of the target Github account to be spoofed. In order to find a target, just go through the repository’s history:
git log
Take note of the information contained on the Author field, that is the author we will impersonate.
spoofing a commit (the wrong way)
Simply force an author through the —-author flag. If you follow this commands with a git log , it will look like it worked just fine.
# amend README.md
echo $'\nPotentially malicious changes 1.' >> README.md
# stage changes
git add .
# commit using details of target user
git commit --author="Paulo Gomes <paulo--REDACTED-->" -m "Add spoof attempt 1"
spoofing a commit properly
Github can detect when the author details are not the same as the Github account details on the machine, in order to make it harder to spot the spoofing, temporarily change the user name and email account before committing changes:
# amend README.md
echo $'\nNew line by f4k3usr pretending to be someone else.' >> README.md
# stage changes
git add .
# ensure all account details are linked to the account you are spoofing
git config --global user.email "paulo--REDACTED--"
git config --global user.name "Paulo Gomes"
# commit using details of target user
git commit -m "Add spoof attempt 2"
Add a legit commit
Here’s just an example of a legit commit, after reverting the account details:
# reset to original settings
git config --global user.email "f4k3usr--REDACTED--"
git config --global user.name "f4k3usr"
# amend README.md
echo $'\nLegit f4k3usr changes.' >> README.md
# stage changes
git add .
# commit using details of target user
git commit -m "Add legit commit"
Did it work?
Executing git log shows exactly what we would expect locally:
What about remotely? What happens when we push all changes up using f4k3usr credentials?
Notice that on the first attempt, as the author’s details differed from the user account defined globally, Github identifies this and shows that pjbgf committed changes through the f4k3usr account. However, the one in the middle worked perfectly, so you can’t really tell that it was not committed by my real account.
What can you do about it?
Git and Github supports signed commits, using a private GPG key to cryptographically generate a hash of your changes, which can then be verified by the public key you have assigned to your GPG account. Once you have it all setup, any “verified commit” you push to origin will visually be marked accordingly.
To achieve this we will need to:
Create a GPG key.
Add the GPG public key to your Github account.
Start signing your commits.
Creating a GPG key
The example below is based on MacOS, if you have a different operational system, you will need to rely in our best friend google. :)
Install the GPG tools from https://gpgtools.org/ then open it. The name of the app is GPG Keychain. It is quite straightforward to use it, click New and a new modal form will appear:
Make sure you use the same email address as your Github account. Also, in order to protect your private key, ensure you use a strong password.
Once created, it will ask whether you want to publish your public key. I personally chose not to, as this is not necessary for this feature to work.
Right click on the key generated and select Copy. This will send to your clipboard your public key, which will look similar to the below:
---BEGIN PGP PUBLIC KEY BLOCK---
mQINBFpHkdjsuaihhiduhUDSHAIdyA&DTSAYDFYASUDUJDHSAKHDJAHDKAHSDJKAHDJKAHJKDHAkDHKL61qVi9+Mh+1bUU6xJ3IZWMYLdF9xKs3kmfFp…
---END PGP PUBLIC KEY BLOCK---
Add GPG Key to Github Account
Go to the SSH and GPG keys of your Github account (https://github.com/settings/keys) and click on New GPG Key. A new page will open up, simply paste your public key and click Add GPG key.
Start signing commits
To start with, you may want to manually sign yours changes by using the -S flag in the commit command:
git commit -S -m "My commit message."
Once you commit, you will be asked your GPG password, so access to your private key can be gained. This should only happen once per session.
Now if you are happy to have all your commits being signed from now on, you can define that on your global settings:
git config --global commit.gpgsign true
Now all your commits will be GPG signed. :)
What if I have multiple GPG keys?
If you have multiple GPG keys matching your Github email account, you will also have to specify which key should git use. That information is based on the Key Id that can be found on the GPG Keychain app. An easy way to get it is by right clicking on the key generated and clicking on Export…
The value that appears in parenthesis is what we need to copy and paste for the next command. Please notice that the one I am copying above is the one generated by GPGTools. You certainly want to use the one you have generated instead.
git config --global user.signingkey 00D026C4
Spotting the difference
Yep, from now on your commits are verified and will visually look like this on Github:
You can also verify locally through your git log:
git log --show-signature -1
Final thoughts…
You certainly can block malicious code from entering your master branch in several ways, one of which, with branch policies forcing Pull Requests. Also, by having a very limited amount number of trust-worthy users who actually have permissions on that branch.
However, non repudiation is essential to assure integrity and the origin of data. Without signed commits it is quite hard to be sure a commit was made by whoever has their name on it, unless we are talking about a private repo which only one person have access to it.
Depending on the access a malicious user has, it would be child’s play to create a backdoor in a new commit, mark it as authored by a prolific developer within the project and then hide it by rewriting git history.
Given the effort required to implement GPG signed commits and what it brings in return, it feels like a no-brainer feature — you should just use it. If nothing else, this gives you the right to repudiate any commits that were not signed by yourself! ;) |
package me.hapyl.fight.game.attribute.temper;
import com.google.common.collect.Maps;
import me.hapyl.fight.game.attribute.AttributeType;
import me.hapyl.fight.game.attribute.EntityAttributes;
import me.hapyl.fight.game.entity.LivingGameEntity;
import me.hapyl.fight.util.collection.ConcurrentTable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* A map (a table, rather) of tempers and their values.
* <p>
* A map is structured like a table:
* <pre>
* Temper
* |------|--------|---------|
* Type | | Attack | Defense |
* |------|--------|---------|
* | A | 69 | 0 |
* |------|--------|---------|
* | B | 0.1 | 1 |
* |------|--------|---------|
* </pre>
* Where two keys point to a single value.
* <p>
* Type can hold as many different tempers and tempers can hold as many different types.
* But only ony single temper and one single type can point to the same value.
* <p>
* Temper <code>A</code> can modify as many types as there are, but will override the existing type.
*/
public final class AttributeTemperTable implements Iterable<TemperData> {
private final ConcurrentTable<Temper, AttributeType, AttributeTemper> tempers;
private final EntityAttributes attributes;
public AttributeTemperTable(EntityAttributes attributes) {
this.attributes = attributes;
this.tempers = new ConcurrentTable<>();
}
public void add(@Nonnull Temper temper, @Nonnull AttributeType type, double value, int duration, boolean isBuff, @Nullable LivingGameEntity applier) {
if (tempers.contains(temper, type)) {
remove(temper, type);
}
tempers.put(temper, type, new AttributeTemper(value, duration, isBuff, applier) {
@Override
public void run() {
remove(temper, type);
attributes.triggerUpdate(type);
}
});
}
public double get(@Nonnull AttributeType type) {
return get(null, type);
}
public double get(@Nonnull Temper temper) {
return get(temper, null);
}
/**
* Gets the temper values for the gives temper and/or type.
* This method accepts either both values, one or none. Though if
* none are provided, the return value is always 0.0d.
* <ul>
* <li>
* Providing <b>only the temper</b> will look for all the values done by that temper.
* </li>
* <li>
* Providing <b>only the type</b> will look for all the values done to that type.
* </li>
* <li>
* Providing <b>both temper and type</b> will only look for values done by that temper to that type.
* </li>
* </ul>
*
* @param temper - Temper.
* @param type - Type.
* @return the values done by either temper/type or both.
*/
public double get(@Nullable Temper temper, @Nullable AttributeType type) {
double total = 0.0d;
if (temper == null && type == null) {
return total;
}
for (AttributeTemper at : tempers.matchOR(temper, type)) {
total += at.value;
}
return total;
}
public boolean has(Temper temper) {
return tempers.containsRow(temper);
}
public boolean has(Temper temper, AttributeType type) {
return tempers.contains(temper, type);
}
public void cancelAll() {
tempers.forEach(AttributeTemper::cancel);
tempers.clear();
}
@Nonnull
@Override
public Iterator<TemperData> iterator() {
final Map<Temper, TemperData> map = Maps.newHashMap();
tempers.entrySet().forEach(entry -> {
final ConcurrentTable.Cell<Temper, AttributeType> cell = entry.getKey();
final Temper temper = cell.row();
final AttributeTemper attributeTemper = entry.getValue();
map.compute(temper, (t, d) -> {
(d = d != null ? d : new TemperData(temper)).values.put(cell.column(), attributeTemper);
return d;
});
});
return map.values().iterator();
}
public boolean isEmpty() {
return tempers.isEmpty();
}
public void cancel(@Nonnull Temper temper) {
final Collection<AttributeTemper> attributeTempers = tempers.removeAll(temper);
attributeTempers.forEach(AttributeTemper::cancel);
}
public void putAll(@Nonnull AttributeTemperTable table) {
tempers.putAll(table.tempers);
}
public void clear() {
tempers.clear();
}
private void remove(@Nonnull Temper temper, @Nonnull AttributeType type) {
final AttributeTemper remove = tempers.remove(temper, type);
if (remove == null) {
return;
}
remove.cancel();
tempers.remove(temper, type);
}
} |
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../data/model/image_model.dart';
import '../provider/state/image_state.dart';
import '../repository/image_repository.dart';
final imageControllerProvider =
StateNotifierProvider<ImageListController, ImageState>((ref) {
final repository = ref.watch(imageRepositoryProvider);
return ImageListController(repository: repository);
});
class ImageListController extends StateNotifier<ImageState> {
// ImageListController(super.state);
final ImageRepository _repository;
ImageListController({
required ImageRepository repository,
}) : _repository = repository,
super(ImageState.initial()) {
loadImages('bird');
}
void loadImages(String searchKeyword) async {
if (state.maxLoaded) {
return;
}
if (state.loading) {
return;
}
state = state.copyWith(keyword: searchKeyword);
state = state.copyWith(loading: true);
try {
Map<String, String> param = {
'query': state.keyword,
'per_page': '30',
'page': state.page.toString()
};
final response =
await _repository.getImage(param: param, endPoint: '/search/photos');
state = state.copyWith(responseCode: response.statusCode);
if (response.statusCode == 200) {
var imageResult = ImageSearchResult.fromJson(response.data);
final imageList = imageResult.results;
if (imageList != null) {
if (imageList.isEmpty) {
state = state.copyWith(
maxLoaded: true,
loading: false,
errorMessage: 'No Data Found!');
}else {
state = state.copyWith(
imageList: [...state.imageList, ...imageList],
loading: false,
errorMessage: '',
page: state.page + 1);
}
} else {
state = state.copyWith(
loading: false, errorMessage: '${response.statusCode} Error');
}
}
} catch (e) {
state = state.copyWith(
loading: false, errorMessage: 'No Internet Connection!');
}
}
} |
namespace RepoM.Api.Tests.IO.Methods;
using RepoM.Api.IO.Methods;
using FluentAssertions;
using Xunit;
public class IsNullMethodTests
{
private readonly IsNullMethod _sut = new();
[Theory]
[InlineData("IsNull", true)]
[InlineData("isnull", true)]
[InlineData("IsNullx", false)]
[InlineData("", false)]
[InlineData(null, false)]
public void CanHandle_ShouldReturnExpected(string? method, bool expectedResult)
{
// arrange
// act
var result = _sut.CanHandle(method!);
// assert
_ = result.Should().Be(expectedResult);
}
[Fact]
public void Handle_ShouldReturnTrue_WhenAnArgumentsIsNull1()
{
// arrange
// act
var result = _sut.Handle("IsNull", null!);
// assert
_ = result.Should().BeOfType<bool>();
_ = result.Should().Be(true);
}
[Fact]
public void Handle_ShouldReturnTrue_WhenAnArgumentsIsNull2()
{
// arrange
// act
var result = _sut.Handle("IsNull", new object?[] { null!, });
// assert
_ = result.Should().BeOfType<bool>();
_ = result.Should().Be(true);
}
[Fact]
public void Handle_ShouldReturnTrue_WhenAnArgumentsIsNull3()
{
// arrange
// act
var result = _sut.Handle("IsNull", null!, null!);
// assert
_ = result.Should().BeOfType<bool>();
_ = result.Should().Be(true);
}
[Theory]
[InlineData("string")]
[InlineData(12)]
[InlineData(true)]
[InlineData(false)]
public void Handle_ShouldReturnTrue_WhenAnArgumentsIsNull4(object notNullValue)
{
// arrange
// act
var result = _sut.Handle("IsNull", null!, notNullValue, null!);
// assert
_ = result.Should().BeOfType<bool>();
_ = result.Should().Be(true);
}
[Theory]
[InlineData("string")]
[InlineData(12)]
[InlineData(true)]
[InlineData(false)]
public void Handle_ShouldReturnFalse_WhenAllArgumentsAreNotNull1(object notNullValue)
{
// arrange
// act
var result = _sut.Handle("IsNull", notNullValue);
// assert
_ = result.Should().BeOfType<bool>();
_ = result.Should().Be(false);
}
[Theory]
[InlineData("string")]
[InlineData(12)]
[InlineData(true)]
[InlineData(false)]
public void Handle_ShouldReturnFalse_WhenAllArgumentsAreNotNull2(object notNullValue)
{
// arrange
// act
var result = _sut.Handle("IsNull", "first param", notNullValue);
// assert
_ = result.Should().BeOfType<bool>();
_ = result.Should().Be(false);
}
} |
{
NameGenerator
@author(Name <jan@subkonstrukt.at>)
@abstract(a short description)
@created(2017-07-07)
this is supposed to give somehow usefull names for things that could spawn
inspired by http://www.godpatterns.com/2005/09/name-generators-for-npcs-to-populate.html
the plants are fixed and are based on the wikipedia article about fake plants(! lel)
@lastmod(2017-07-10)
}
UNIT NameGen;
INTERFACE
USES
MlObj;
TYPE
NameGenerator = ^TNameGenerator;
TNameGenerator = OBJECT(MLObjectObj)
PRIVATE
_plantNames : ARRAY[0..117] OF STRING;
_animalEndings : ARRAY[0..13] OF STRING;
_landEndings : ARRAY[0..24] OF STRING;
_v : ARRAY[0..4] OF CHAR;
_c : ARRAY[0..19] OF CHAR;
FUNCTION Consonant : CHAR;
FUNCTION Vocal : CHAR;
FUNCTION LocationEnding : STRING;
FUNCTION AnimalEnding : STRING;
PROCEDURE SeedFakePlants;
PROCEDURE SeedStringChains;
FUNCTION BuildMarkovChain : STRING;
PUBLIC
CONSTRUCTOR Init;
DESTRUCTOR Done; VIRTUAL;
FUNCTION LocationName : STRING;
FUNCTION AnimalName : STRING;
FUNCTION PlantName : STRING;
END;
FUNCTION NewNameGenerator : NameGenerator;
IMPLEMENTATION
FUNCTION NewNameGenerator : NameGenerator;
VAR
n : NameGenerator;
BEGIN
New(n,Init);
NewNameGenerator := n;
END;
CONSTRUCTOR TNameGenerator.Init;
BEGIN
INHERITED Init;
Register('NameGenerator', 'MLObject');
SeedFakePlants;
SeedStringChains;
END;
FUNCTION TNameGenerator.LocationName : STRING;
VAR
i : INTEGER;
BEGIN
i := Random(High(_landEndings));
LocationName := BuildMarkovChain + _landEndings[i];
END;
FUNCTION TNameGenerator.AnimalName : STRING;
VAR
i : INTEGER;
BEGIN
i := Random(High(_animalEndings));
AnimalName := BuildMarkovChain + _animalEndings[i];
END;
FUNCTION TNameGenerator.PlantName : STRING;
VAR
i : INTEGER;
BEGIN
i := Random(High(_plantNames));
PlantName := _plantNames[i];
END;
DESTRUCTOR TNameGenerator.Done;
BEGIN
INHERITED Done;
END;
FUNCTION TNameGenerator.BuildMarkovChain : STRING;
VAR
len,i : INTEGER;
chain : STRING;
BEGIN
chain := '';
len := Random(2) + 1;
FOR i := 1 TO len DO BEGIN
chain := chain + Consonant + Vocal + Consonant;
END;
chain[1] := upCase(chain[1]);
BuildMarkovChain := chain;
END;
FUNCTION TNameGenerator.Consonant : CHAR;
VAR
i : INTEGER;
BEGIN
i := Random(High(_c));
Consonant := _c[i];
END;
FUNCTION TNameGenerator.Vocal : CHAR;
VAR
i : INTEGER;
BEGIN
i := Random(High(_v));
Vocal := _v[i];
END;
FUNCTION TNameGenerator.LocationEnding : STRING;
VAR
i : INTEGER;
BEGIN
i := Random(High(_landEndings));
LocationEnding := _landEndings[i];
END;
FUNCTION TNameGenerator.AnimalEnding : STRING;
VAR
i : INTEGER;
BEGIN
i := Random(High(_animalEndings));
AnimalEnding := _animalEndings[i];
END;
PROCEDURE TNameGenerator.SeedStringChains;
BEGIN
_animalEndings[0] := 'avis'; _animalEndings[1] := 'cetus';
_animalEndings[2] := 'derm'; _animalEndings[3] := 'erpeton';
_animalEndings[4] := 'felis'; _animalEndings[5] := 'ia';
_animalEndings[6] := 'maia'; _animalEndings[7] := 'mimus';
_animalEndings[8] := 'morph'; _animalEndings[9] := 'zoa';
_animalEndings[10] := 'nyx'; _animalEndings[11] := 'pus';
_animalEndings[12] := 'odon'; _animalEndings[13] := 'lophus';
_landEndings[0] := 'bank'; _landEndings[1] := 'barrow';
_landEndings[2] := 'cliff'; _landEndings[3] := 'crook';
_landEndings[4] := 'down'; _landEndings[5] := 'hurst';
_landEndings[6] := 'tor'; _landEndings[7] := 'burn';
_landEndings[8] := 'mere'; _landEndings[9] := 'latch';
_landEndings[10] := 'marsh'; _landEndings[11] := 'ness';
_landEndings[12] := 'wick'; _landEndings[13] := 'thorpe';
_landEndings[14] := 'cote'; _landEndings[15] := 'sett';
_landEndings[16] := 'combe'; _landEndings[17] := 'croft';
_landEndings[18] := 'thwaite'; _landEndings[19] := 'minster';
_landEndings[20] := 'kirk'; _landEndings[21] := 'heath';
_landEndings[22] := 'lea'; _landEndings[23] := 'ford';
_landEndings[24] := 'stoke'; _landEndings[24] := 'ton';
_v[0] := 'a'; _v[1] := 'e'; _v[2] := 'i'; _v[3] := 'o'; _v[4] := 'u';
_c[0] := 'b'; _c[1] := 'c'; _c[2] := 'd'; _c[3] := 'f'; _c[4] := 'g';
_c[5] := 'h'; _c[6] := 'j'; _c[7] := 'k'; _c[8] := 'l'; _c[9] := 'n';
_c[10] := 'm'; _c[11] := 'p'; _c[12] := 'r'; _c[13] := 't'; _c[14] := 's';
_c[15] := 'v'; _c[16] := 'y'; _c[17] := 'z'; _c[18] := 'x'; _c[19] := 'w';
END;
PROCEDURE TNameGenerator.SeedFakePlants;
BEGIN
(* well yeah those are static whatever *)
_plantNames[0] := 'Adele'; _plantNames[1] := 'Aechmea asenionii '; _plantNames[2] := 'Akarso'; _plantNames[3] := 'Alraune'; _plantNames[4] := 'Arctus Mandibus'; _plantNames[5] := 'Audrey Jr.'; _plantNames[6] := 'Aum plant'; _plantNames[7] := 'Avern'; _plantNames[8] := 'Axis '; _plantNames[9] := 'Bat-thorn'; _plantNames[10] := 'Biollante'; _plantNames[11] := 'Black Mercy'; _plantNames[12] := 'Blister plants'; _plantNames[13] := 'Blood Grass '; _plantNames[14] := 'Blood Orchid '; _plantNames[15] := 'Bloodflower'; _plantNames[16] := 'Bob'; _plantNames[17] := 'Broxlorthian Squidflower'; _plantNames[18] := 'Cactacae'; _plantNames[19] := 'Candypop Bud'; _plantNames[20] := 'Carnifern'; _plantNames[21] := 'Chamalla'; _plantNames[22] := 'Chuck the Plant'; _plantNames[23] := 'Cleopatra'; _plantNames[24] := 'Crazee Dayzees'; _plantNames[25] := 'Cow plant (Laganaphyllis simnovorii) '; _plantNames[26] := 'Deathbottle'; _plantNames[27] := 'Dyson tree'; _plantNames[28] := 'Echo Flower Elowan'; _plantNames[29] := 'Eon Rose '; _plantNames[30] := 'Flaahgra'; _plantNames[31] := 'Flossberry'; _plantNames[32] := 'Flower of Life '; _plantNames[33] := 'Flowey Genesis Trees'; _plantNames[34] := 'Gijera'; _plantNames[35] := 'Gingold'; _plantNames[36] := 'Giraluna'; _plantNames[37] := 'Gloria Margagora GQuan Eth'; _plantNames[38] := 'Carter Green, the Vegetable Man'; _plantNames[39] := 'Grippers'; _plantNames[40] := 'Happy plant'; _plantNames[41] := 'Hearts Desire'; _plantNames[42] := 'Hybernia tree'; _plantNames[43] := 'Inkvine'; _plantNames[44] := 'Integral Trees'; _plantNames[45] := 'Juran'; _plantNames[46] := 'Jurai Royal Trees'; _plantNames[47] := 'Jacks Beanstalk'; _plantNames[48] := 'Katterpod Trappersnappers'; _plantNames[49] := 'Kite-Eating Tree'; _plantNames[50] := 'Krynoid'; _plantNames[51] := 'Kyrt'; _plantNames[52] := 'Lashers'; _plantNames[53] := 'Lovelies'; _plantNames[54] := 'Mangaboos'; _plantNames[55] := 'Mariphasa lupina lumina (Wolf Flower) '; _plantNames[56] := 'Metarex'; _plantNames[57] := 'Moon Disc'; _plantNames[58] := 'Mors ontologica'; _plantNames[59] := 'Mushroom trees'; _plantNames[60] := 'Night-blooming Mock Orchid'; _plantNames[61] := 'Night Howler Crocus'; _plantNames[62] := 'Obernut'; _plantNames[63] := 'Omega Flowey Paopu Fruit Deku Baba Papadalupapadipu Deku Scrubs Peahat'; _plantNames[64] := 'Peruvian Puff Pepper'; _plantNames[65] := 'Peya'; _plantNames[66] := 'Pikmin'; _plantNames[67] := 'Piranha Plant '; _plantNames[68] := 'PP-34'; _plantNames[69] := 'Principal Malaysian Palmgrass'; _plantNames[70] := 'Priphea Flowers'; _plantNames[71] := 'Protoanthus'; _plantNames[72] := 'Pseudobushiahugiflora'; _plantNames[73] := 'Quadrotriticale'; _plantNames[74] := 'Rangdo'; _plantNames[75] := 'Re-annual plants'; _plantNames[76] := 'Red weed'; _plantNames[77] := 'Rroamal'; _plantNames[78] := 'Rytt'; _plantNames[79] := 'Sapient Pearwood'; _plantNames[80] := 'SapSac'; _plantNames[81] := 'Seedrians'; _plantNames[82] := 'Senzu Bean'; _plantNames[83] := 'Shimmerweed'; _plantNames[84] := 'Snake vine'; _plantNames[85] := 'Solar Complexus Americanus'; _plantNames[86] := 'Spitfire Tree'; _plantNames[87] := 'Sser'; _plantNames[88] := 'Stage trees'; _plantNames[89] := 'Sorichra'; _plantNames[90] := 'Stinky'; _plantNames[91] := 'Strangleweed'; _plantNames[92] := 'Sukebind Moonflower Sunflower Supox utricularia'; _plantNames[93] := 'Tangle grass'; _plantNames[94] := 'Tanna leaves'; _plantNames[95] := 'Tava beans'; _plantNames[96] := 'Tellurian'; _plantNames[97] := 'Tesla trees'; _plantNames[98] := 'Thunder Spud'; _plantNames[99] := 'Tirils'; _plantNames[100] := 'Trama root '; _plantNames[101] := 'Traversers'; _plantNames[102] := 'Treant'; _plantNames[103] := 'Tree-of-Life'; _plantNames[104] := 'Treeships'; _plantNames[105] := 'Triffids'; _plantNames[106] := 'Truffula tree'; _plantNames[107] := 'Tumtum tree'; _plantNames[108] := 'Une'; _plantNames[109] := 'Vines'; _plantNames[110] := 'Vul nut vine'; _plantNames[111] := 'Wakeflower'; _plantNames[112] := 'Whistling leaves'; _plantNames[113] := 'White Claudia'; _plantNames[114] := 'Wildvine'; _plantNames[115] := 'Witchblood'; _plantNames[116] := 'Wroshyr trees'; _plantNames[117] := 'Yangala-Cola ';
END;
END. |
import { useRouter } from 'expo-router'
import useEntryFlow from 'hooks/useEntryFlow'
import { Pressable } from 'react-native'
import { Text, XStack } from 'tamagui'
import { Feed } from 'types'
import Favicon from 'components/Favicon'
export default function SourceItem({
item,
onPress,
}: {
item: Feed
onPress?: () => void
}) {
const router = useRouter()
const { entries } = useEntryFlow()
const unreadCount =
entries.filter((t) => !t.read && t.feedUrl === item.url).length || 0
return (
<Pressable
onPress={() => {
router.push({
pathname: 'shared/feed',
params: {
url: encodeURIComponent(item.url),
from: 'feeds',
},
})
}}
style={{ marginTop: 4 }}
>
<XStack
space={8}
alignItems="center"
paddingVertical={12}
backgroundColor="$background"
px={12}
mx={16}
borderRadius={4}
>
<Favicon favicon={item.favicon} />
<XStack flex={1} alignItems="center" justifyContent="space-between">
<Text
fontSize={16}
maxWidth={180}
numberOfLines={1}
ellipsizeMode="tail"
color="$color11"
>
{item.title}
</Text>
<Text fontSize={14} color="$gray9Light">
{unreadCount}
</Text>
</XStack>
</XStack>
</Pressable>
)
} |
import {User} from "../entities";
import ApiError from "../exceptions/ApiError";
import {UserDto} from "../dtos/userDto";
import jwtService from "./jwtService";
import {compare, hash} from "bcryptjs";
class UserService {
async registration(phone: string, password: string, name?: string) {
const existingUser = await User.findOne({where: {phone}});
if (existingUser) {
throw ApiError.BadRequest('User with this phone already exists', 'user_already_exists');
}
const hashPassword = await hash(password, 5);
const user = await User.create({phone, password: hashPassword, name});
await user.save();
const userDto = new UserDto(user);
const tokens = jwtService.generateTokens({...userDto}, '24h');
await jwtService.saveToken(userDto.id, tokens.refreshToken);
return {...tokens, user};
}
async login(phone: string, password: string) {
const user = await User.findOne({where: {phone}});
if (!user) {
throw ApiError.BadRequest('User with this phone does not exist', 'user_does_not_exist');
}
const isPasswordEquals = await compare(password, user.password);
if (!isPasswordEquals) {
throw ApiError.BadRequest('Incorrect password', 'incorrect_password');
}
const userDto = new UserDto(user);
const tokens = jwtService.generateTokens({...userDto}, '24h');
await jwtService.saveToken(userDto.id, tokens.refreshToken);
return {...tokens, user};
}
async logout(refreshToken: string) {
return await jwtService.removeToken(refreshToken);
}
async refresh(refreshToken: string) {
if (!refreshToken) {
throw ApiError.UnauthorizedError();
}
const userData: any = jwtService.verifyRefreshToken(refreshToken);
const token = await jwtService.findToken(refreshToken);
if (!token || !userData) {
throw ApiError.UnauthorizedError();
}
const user = await User.findOne({where: {id: userData.id}});
if (!user) {
throw ApiError.UnauthorizedError();
}
const userDto = new UserDto(user);
const tokens = jwtService.generateTokens({...userDto}, '24h');
await jwtService.saveToken(userDto.id, tokens.refreshToken);
return {...tokens, user: userDto};
}
}
export default new UserService(); |
public static void main(String[] args) throws IOException {
OptionParser parser = new OptionParser();
parser.accepts("help", "print usage information");
parser.accepts("cluster", "[REQUIRED] path to cluster xml config file").withRequiredArg().describedAs("cluster.xml");
parser.accepts("stores", "[REQUIRED] path to stores xml config file").withRequiredArg().describedAs("stores.xml");
parser.accepts("name", "[REQUIRED] store name").withRequiredArg().describedAs("store name");
parser.accepts("buffer", "[REQUIRED] number of key/value pairs to buffer in memory").withRequiredArg().ofType(Integer.class);
parser.accepts("input", "[REQUIRED] input file to read from").withRequiredArg().describedAs("input-file");
parser.accepts("output", "[REQUIRED] directory to output stores to").withRequiredArg().describedAs("output directory");
parser.accepts("threads", "number of threads").withRequiredArg().ofType(Integer.class);
parser.accepts("chunks", "number of store chunks per store").withRequiredArg().ofType(Integer.class);
parser.accepts("io-buffer-size", "size of i/o buffers in bytes").withRequiredArg().ofType(Integer.class);
parser.accepts("temp-dir", "temporary directory for sorted file pieces").withRequiredArg().describedAs("temp dir");
OptionSet options = parser.parse(args);
if (options.has("help")) {
parser.printHelpOn(System.out);
System.exit(0);
}
Set<String> missing = CmdUtils.missing(options, "cluster", "stores", "name", "buffer", "input", "output");
if (missing.size() > 0) {
System.err.println("Missing required arguments: " + Joiner.on(", ").join(missing));
parser.printHelpOn(System.err);
System.exit(1);
}
String clusterFile = (String) options.valueOf("cluster");
String storeDefFile = (String) options.valueOf("stores");
String storeName = (String) options.valueOf("name");
int sortBufferSize = (Integer) options.valueOf("buffer");
String inputFile = (String) options.valueOf("input");
File outputDir = new File((String) options.valueOf("output"));
int numThreads = CmdUtils.valueOf(options, "threads", 2);
int numChunks = CmdUtils.valueOf(options, "chunks", 2);
int ioBufferSize = CmdUtils.valueOf(options, "io-buffer-size", 1000000);
File tempDir = new File(CmdUtils.valueOf(options, "temp-dir", System.getProperty("java.io.tmpdir")));
try {
JsonReader reader = new JsonReader(new BufferedReader(new FileReader(inputFile), ioBufferSize));
Cluster cluster = new ClusterMapper().readCluster(new BufferedReader(new FileReader(clusterFile)));
StoreDefinition storeDef = null;
List<StoreDefinition> stores = new StoreDefinitionsMapper().readStoreList(new BufferedReader(new FileReader(storeDefFile)));
for (StoreDefinition def : stores) {
if (def.getName().equals(storeName))
storeDef = def;
}
if (storeDef == null)
Utils.croak("No store found with name \"" + storeName + "\"");
if (!outputDir.exists())
Utils.croak("Directory \"" + outputDir.getAbsolutePath() + " does not exist.");
RoutingStrategy routingStrategy = new RoutingStrategyFactory().updateRoutingStrategy(storeDef, cluster);
new JsonStoreBuilder(reader, cluster, storeDef, routingStrategy, outputDir, tempDir, sortBufferSize, numThreads, numChunks, ioBufferSize).build();
} catch (FileNotFoundException e) {
Utils.croak(e.getMessage());
}
} |
/*
* Copyright (c) 2006 Kapelonis Kostis <kkapelon@freemail.gr>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Project Elevate - Core
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
#include <glib.h>
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <gdk/gdkkeysyms.h>
#include <cairo.h>
#include "gfx.h"
#include "integrator.h"
#include "engine.h"
#include "parser.h"
#include "files.h"
#define HEIGHT 800
#define WIDTH 800
/*
* Non-Gui stuff goes here
*/
typedef struct data_model
{
char cmd[80];
Engine *engine;
}dm_t;
/*
* GUI stuff goes here
*/
typedef struct win {
GtkWidget *drawing_area; //Canvas
dm_t dm; //Data model
gint mode; //What state is the interface now (e.g. input or not)
Integrator *input_box_fx; /* Percent*/
} win_t;
/* Possible modes */
#define MODE_NORMAL 1
#define MODE_INPUT 2
static void scale_for_aspect_ratio (cairo_t * cr, int widget_width, int widget_height);
static cairo_t * begin_paint (GdkDrawable *window);
static void end_paint (cairo_t *cr);
static void draw_decors(cairo_t *cr,const gchar* file);
static void draw_canvas(GtkWidget *widget,win_t *win);
static gboolean win_expose_event (GtkWidget *widget, GdkEventExpose *event, gpointer data);
static gint on_key_press (GtkWidget * widget, GdkEventKey * event, gpointer data);
static GtkWidget *create_window (win_t *as);
static gint timeout_callback (gpointer data);
static void draw_status(cairo_t *cr,win_t *win);
/*
* Reads all modules from the filesystem
* and creates the application window
*/
int main (int argc, char *argv[])
{
win_t closure;
gtk_init (&argc, &argv);
/* Elevate modules */
closure.dm.engine = create_capabilities();
closure.dm.cmd[0]='\0';
/* GUI init */
closure.drawing_area = create_window (&closure);
closure.mode = MODE_NORMAL;
/* Integrators */
closure.input_box_fx = Integrator_create();
Integrator_set(closure.input_box_fx,0);
Integrator_target(closure.input_box_fx,101); //this is percent that we need to reach until 100
/* Show the GUI to the user */
gtk_widget_show_all (gtk_widget_get_toplevel (closure.drawing_area));
/* Create animation thread at 25fps*/
g_timeout_add (40, timeout_callback, &closure);
gtk_main();
return 0;
}
/*
* Draws the static background for the window
*/
static void draw_background(cairo_t *cr)
{
cairo_pattern_t *pat;
cairo_save(cr);
/* Gradient pattern from white to light blue */
pat = cairo_pattern_create_linear (0.0, 0.0, 0.0,100);
cairo_pattern_add_color_stop_rgb(pat, 0, 0.98, 0.98, 0.98);
cairo_pattern_add_color_stop_rgb(pat, 100, 0.65, 0.77, 0.79);
cairo_rectangle (cr, 0, 0, 100, 100); //Covers the whole screen
cairo_set_source (cr, pat);
cairo_fill (cr);
cairo_pattern_destroy (pat);
/* Decors on the corners */
cairo_set_source_rgb (cr, 0, 0, 0);
cairo_set_line_width (cr, 0.5);
cairo_move_to(cr,2,7);
cairo_rel_line_to(cr,0,-5);
cairo_rel_line_to(cr,5,0);
cairo_stroke(cr);
cairo_move_to(cr,98,7);
cairo_rel_line_to(cr,0,-5);
cairo_rel_line_to(cr,-5,0);
cairo_stroke(cr);
/* Window status */
draw_rounded_rect(cr,20,-10,60,16,3);
/* Current Context */
draw_rounded_rect(cr,1,91,98,8,4);
cairo_restore(cr);
}
/*
* Renders the content of the main window
*/
static void draw_canvas(GtkWidget *widget,win_t *win)
{
cairo_t *cr;
cr = begin_paint (widget->window);
/*
* Scale the canvas so that all co-ordinates
* can be 0-100 regardless of the size of the window
*/
cairo_scale(cr,WIDTH/100,HEIGHT/100);
/* Step 1 Static window contents */
draw_background(cr);
/* Step 2 Draw messages, tasks and context */
draw_status(cr,win);
end_paint (cr);
}
static void draw_status(cairo_t *cr,win_t *win)
{
/* First the output messages */
draw_messages_box(cr,"Messages go here",5);
/* No need to draw command line if it is not needed */
if(win->mode == MODE_INPUT)
{
gfloat fx_number = Integrator_get(win->input_box_fx);
draw_input_box (cr, win->dm.cmd, fx_number /100.0); //Convert it to percent
}
}
/*
* Callback that is run when a key is pressed
*/
static gint on_key_press (GtkWidget * widget, GdkEventKey * event, gpointer data)
{
win_t *closure = (win_t *)data;
gchar *input = NULL;
switch (event->keyval)
{
case GDK_Escape:
memset(closure->dm.cmd,0,80); //Clear the command line
closure->mode = MODE_NORMAL;
break;
case GDK_BackSpace:
if(strlen(closure->dm.cmd) > 0)
closure->dm.cmd[strlen(closure->dm.cmd)-1] = '\0';
break;
case GDK_Return:
input = g_strdup(closure->dm.cmd);
memset(closure->dm.cmd,0,80); //Clear the command line
start_parsing(input,closure->dm.engine);
g_free(input);
closure->mode = MODE_NORMAL;
break;
default:
g_print("Got %s\n",event->string);
strncat(closure->dm.cmd,event->string,80);
closure->mode = MODE_INPUT;
Integrator_set(closure->input_box_fx,0);
break;
}
g_print("command is now %s\n",closure->dm.cmd);
return TRUE;
}
/*
* Scales the window each time it is resized
*/
static void scale_for_aspect_ratio (cairo_t * cr, int widget_width, int widget_height)
{
double scalex;
double scaley;
scaley = ((double) widget_height) / HEIGHT;
scalex = ((double) widget_width) / WIDTH;
cairo_scale (cr, scalex, scaley);
}
/*
* Prapares the cairo context each time
* a frame is rendered
*/
static cairo_t * begin_paint (GdkDrawable *window)
{
gint width, height;
cairo_t *cr;
gdk_drawable_get_size (window, &width, &height);
cr = gdk_cairo_create(window);
scale_for_aspect_ratio (cr, width, height);
return cr;
}
/*
* Cleans up the cairo context when the frame
* is finished
*/
static void end_paint (cairo_t *cr)
{
cairo_destroy (cr);
}
/*
* Callback that is run by GTK whenever there is an expose
* event
*/
static gboolean win_expose_event (GtkWidget *widget, GdkEventExpose *event, gpointer data)
{
win_t *closure = (win_t *)data;
draw_canvas(widget,closure);
return TRUE;
}
/*
* Creates the main GTK window and
* sets some basic window operations
*/
static GtkWidget *create_window (win_t *as)
{
GtkWidget *window;
GtkWidget *da;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Project Elevate");
g_signal_connect (window, "destroy",
G_CALLBACK (gtk_main_quit), &window);
da = gtk_drawing_area_new ();
/* set a minimum size */
gtk_widget_set_size_request (da, HEIGHT/2, WIDTH/2);
gtk_window_set_default_size(GTK_WINDOW(window),HEIGHT,WIDTH);
gtk_container_add (GTK_CONTAINER (window), da);
g_signal_connect (da, "expose_event", G_CALLBACK (win_expose_event), as);
g_signal_connect (window, "key_press_event", G_CALLBACK (on_key_press), as);
return da;
}
/*
* Animation thread. It just
* redraws the main window
*/
static gint timeout_callback (gpointer data)
{
win_t *closure = data;
/* Advance all integrators */
Integrator_update(closure->input_box_fx);
gtk_widget_queue_draw (closure->drawing_area);
return TRUE; //Keep this timer active
} |
using UnityEngine;
namespace SPWN // SpawnCampGames.com
{
/// <summary>
/// Utility class for calculating global transformation data of a GameObject and its parent hierarchy.
/// </summary>
public static class GlobalTransform
{
/// <summary>
/// Calculates the global position, rotation, and scale of a transform.
/// </summary>
/// <param name="core">The transform to calculate the global transformation for.</param>
/// <param name="globalPosition">The global position of the transform.</param>
/// <param name="globalRotation">The global rotation of the transform in Euler angles.</param>
/// <param name="globalScale">The global scale of the transform.</param>
public static void GetGlobalTransform(Transform core, out Vector3 globalPosition, out Vector3 globalRotation, out Vector3 globalScale)
{
// Set the global position and rotation
globalPosition = core.position;
globalRotation = core.rotation.eulerAngles;
// Calculate the global scale manually
globalScale = CalculateGlobalScale(core);
}
/// <summary>
/// Calculates the global scale of a transform considering its parent hierarchy.
/// </summary>
/// <param name="core">The transform to calculate the global scale for.</param>
/// <returns>The global scale of the transform.</returns>
private static Vector3 CalculateGlobalScale(Transform core)
{
Vector3 scale = core.localScale;
Transform currentCore = core.parent;
// Iterate through parent transforms, multiplying their scales
while (currentCore != null)
{
scale.Scale(currentCore.localScale);
currentCore = currentCore.parent;
}
return scale;
}
}
} |
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:student_link/constant.dart';
import 'package:student_link/models/users/user.dart';
import 'package:http/http.dart' as http;
import '../../../login/auth.dart';
class RequestUsersMap {
static const String _baseUrl = Request.endpoint;
static Future<List<User>> getUsers(
double latitude, double longitude, BuildContext context) async {
final String fullUrl = '$_baseUrl/map/$longitude/$latitude';
final AuthService authService = AuthService();
String? token = await authService.getToken();
try {
final response = await http.get(
Uri.parse(fullUrl),
headers: {
'Token': token!,
'Content-Type': 'application/json',
},
);
if (response.statusCode == 200) {
Map<String, dynamic> body = jsonDecode(response.body);
print(response.body);
List<dynamic> usersData = body['users'];
List<User> users =
usersData.map((userJson) => User.fromJson(userJson)).toList();
return users;
} else {
throw Exception('Errore durante la richiesta: ${response.statusCode}');
}
} catch (e) {
//TODO: DA ERRORE QUANDO IL TOKEN NON è VALIDO, VERIFICARE IL REFRESH
await authService.logout(context);
// Effettua il logout dell'utente
throw Exception('Errore durante la richiesta: $e');
}
}
} |
// createSlice For Create State And Required Methods For Articles Delete/Update/create/read
import { createSlice } from "@reduxjs/toolkit";
// Import Fetching Data Function
import { fetchBlogs } from "./actions";
// Fetching Data Statuses Object
export const STATUSES = {
IDLE: "idle",
LOADING: "Loading",
ERROR: "error",
};
const blogSlice = createSlice({
name: "blogs-slice", // Slice Name
initialState: {
page: 1,
blogs: [], // Blogs Array To Contains Articles Data
status: STATUSES.IDLE, // Status Of Fetching Data With Default Value
},
reducers: {
searchForArticle(state, action) {
const searchQuery = action.payload;
const regex = new RegExp(searchQuery, "i"); // 'i' flag for case-insensitive search
console.log(action.payload);
state.blogs = state.blogs.filter(
(item) => regex.test(item?.title) || regex.test(item?.author)
);
},
// Delete Articles Using Filter And The Required Articles Id
deleteArticle(state, action) {
state.blogs = state.blogs.filter(
(item) => item.source.id != action.payload
);
},
// Create New Articles Using Title , Description And Generated New ID
createArticle(state, action) {
const { title, description } = action.payload;
// Get the last element's source ID and increment it by 1 for the new ID
const newElementId =
state.blogs.length > 0
? state.blogs[state.blogs.length - 1].source.id + 1
: 1;
// Create the new element
const newElement = {
author: "Magdy Mohammed",
source: { id: newElementId },
title,
description,
publishedAt: new Date().toISOString(),
};
// Add the new element to the front of the array
state.blogs.push(newElement);
},
// Update Article Function Using id And Assign New Title And Description
updateArticle(state, action) {
const { id, editedTitle, editedDescription } = action.payload;
state.blogs = state.blogs.map((item) => {
if (item.source.id == id) {
return {
...item,
title: editedTitle, // Corrected property name
description: editedDescription, // Corrected property name
};
}
return item;
});
},
incrementPage(state) {
state.page = state.page + 1;
},
},
// Extra Reducers For Control Every Step In Fetching Data
extraReducers: (builder) => {
builder
.addCase(fetchBlogs.pending, (state) => {
state.status = STATUSES.LOADING;
})
.addCase(fetchBlogs.fulfilled, (state, action) => {
state.status = STATUSES.IDLE;
if (state.page == 1) {
state.blogs = action.payload;
} else {
state.blogs = [...state.blogs, ...action.payload];
}
})
.addCase(fetchBlogs.rejected, (state) => {
state.status = STATUSES.ERROR;
});
},
});
// Export Create/Update/Delete Action To Use It In Buttons
export const {
deleteArticle,
updateArticle,
createArticle,
searchForArticle,
incrementPage,
} = blogSlice.actions;
// Export The Blog Reducer For Combined Inside rootReducer
export default blogSlice.reducer; |
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/pasteleria.css">
<meta name="description" content="El sitio web esta hecho para ver un amplia gamma del mundo de la pasteleria y poder hacer pedidos">
<meta name="keywords" content="PUDINES, ORANGUTAN, PASTELERIA, PASTELES">
<title>Inicio</title>
</head>
<body>
<!-- NAVAR -->
<header>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid ">
<a class="navbar-brand" href="index.html">
<img src="imagenes/Logo.png" alt="" width="100" height="100" class="d-inline-block align-text-top">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav justify-content-end">
<a class="nav-link active" aria-current="page" href="index.html"><h1>PASTELERIA DEL ORGANGUTAN</h1></a>
<a class="nav-link" href="index.html">Inicio</a>
<a class="nav-link" href="tienda.html">Tienda</a>
<a class="nav-link" href="#">Nosotros</a>
</div>
</div>
</div>
</nav>
</header>
<!-- PRESENTACION -->
<main>
<article>
<div class="card mb-3 text-center" style="max-width: 700px;">
<div class="row g-0">
<div class="col-md-4">
<img src="imagenes/chef-orangutan.webp" class="img-fluid rounded-start" alt="...">
</div>
<div class="col-md-8">
<div class="card-body">
<h2 class="card-title">Sobre Nosotros</h2>
<p class="card-text">Nuestra pasteleria fue hecha especialmente por los mejores pasteleros orangutanes de las mejores selvas solamente para servirles en el arte de la pasteleria</p>
</div>
</div>
</div>
</div>
</article>
<!-- SEPARADOR -->
<div class="row mb12">
<img src="imagenes/separadonpng.png" alt="">
</div>
<!-- MUESTRA DE LA TIENDA -->
<div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="imagenes/pastel-de-vainilla-con-avena-perfecto.jpg" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="imagenes/Tarta-de-frutillas.png" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="imagenes/maxresdefault.jpg" class="d-block w-100" alt="...">
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Anterior</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Siguiente</span>
</button>
</div>
<!-- BOTON PARA IR A LA TIENDA -->
<div class="text-center centrado-boton">
<button type="button" class="btn btn-outline-success btn-lg">Ir Tienda</button>
</div>
<!-- SEPARADOR -->
<div class="row mb12">
<img src="imagenes/separadonpng.png" alt="">
</main>
<!-- UBICACION -->
<div class="row">
<iframe class="col-lg-5 mapa" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d15701.4272642525!2d76.63124335144308!3d10.313308883381845!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3b07f9528de567f5%3A0xec40bdc96c17ffdc!2sPULIYILAPPARA!5e0!3m2!1ses!2sar!4v1653959607461!5m2!1ses!2sar" width="300" height="400" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>
<div class="card border-light mb-3" style="max-width: 18rem;">
<div class="card-header"><h2>Ubicacion</h3></div>
<div class="card-body">
<p class="card-text"> Encuentranos en nuestra hermosa jungla junto </p>
</div>
</div>
</div>
<!-- FOOTER -->
<footer class="conteiner-fluid row">
<div class="row">
<div class="col-lg-4">
<div class="redes col-lg-4">
<h2>SIGUENOS EN NUESTRAS REDES!!!</h2>
<i class="fa-brands fa-facebook"></i>
<i class="fa-brands fa-whatsapp"></i>
<i class="fa-brands fa-instagram"></i>
</div>
</div>
<div class="col-lg-4">
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Expedita mollitia ea aliquam. Expedita nulla animi maiores quae</p>
</div>
<div class="col-lg-4">
<img src="imagenes/Logo.png" class="img-fluid logo" alt="">
</div>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html> |
# coding=utf-8
# rewritten, Copyright (c) 2021, Ming Ding. All rights reserved.
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Transformer."""
import math
import copy
import torch
import torch.nn.functional as F
from apex.normalization.fused_layer_norm import FusedLayerNorm
from SwissArmyTransformer import mpu
from .initialize import get_model_parallel_world_size
from .layers import ColumnParallelLinear, RowParallelLinear, VocabParallelEmbedding
from .mappings import gather_from_model_parallel_region, copy_to_model_parallel_region
from deepspeed.runtime.activation_checkpointing.checkpointing import checkpoint
from .utils import divide, sqrt, scaled_init_method, unscaled_init_method, gelu
from .utils import split_tensor_along_last_dim
class LayerNorm(FusedLayerNorm):
def __init__(self, *args, pb_relax=False, **kwargs):
super().__init__(*args, **kwargs)
self.pb_relax = pb_relax
def forward(self, x):
if not self.pb_relax:
return super().forward(x)
return super().forward(x / (x.abs().max().detach() / 8))
def standard_attention(query_layer, key_layer, value_layer, attention_mask,
attention_dropout=None, log_attention_weights=None, scaling_attention_score=True, **kwargs):
# We disable the PB-relax-Attention and only changes the order of computation, because it is enough for most of training.
# The implementation in the paper can be done very easily, if you really need it to train very deep transformers.
if scaling_attention_score:
query_layer = query_layer / math.sqrt(query_layer.shape[-1])
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
if log_attention_weights is not None:
attention_scores += log_attention_weights
if not (attention_mask.shape[-2] == 1 and (attention_mask > 0).all()):
# if auto-regressive, skip
attention_scores = torch.mul(attention_scores, attention_mask) - \
10000.0 * (1.0 - attention_mask)
attention_probs = F.softmax(attention_scores, dim=-1)
if attention_dropout is not None:
if mpu.get_cuda_rng_tracker is not None:
with mpu.get_cuda_rng_tracker().fork():
attention_probs = attention_dropout(attention_probs)
else:
attention_probs = attention_dropout(attention_probs)
context_layer = torch.matmul(attention_probs, value_layer)
return context_layer
class SelfAttention(torch.nn.Module):
def __init__(self, hidden_size, num_attention_heads,
attention_dropout_prob, output_dropout_prob,
init_method, layer_id, hidden_size_per_attention_head=None, output_layer_init_method=None, bias=True,
hooks={}):
super(SelfAttention, self).__init__()
# Set output layer initialization if not provided.
if output_layer_init_method is None:
output_layer_init_method = init_method
self.hooks = hooks
self.layer_id = layer_id
# Per attention head and per partition values.
world_size = get_model_parallel_world_size()
self.hidden_size = hidden_size
if hidden_size_per_attention_head is None:
self.hidden_size_per_attention_head = divide(hidden_size, num_attention_heads)
else:
self.hidden_size_per_attention_head = hidden_size_per_attention_head
self.num_attention_heads_per_partition = divide(num_attention_heads, world_size)
self.inner_hidden_size = num_attention_heads * self.hidden_size_per_attention_head
self.hidden_size_per_partition = self.hidden_size_per_attention_head * self.num_attention_heads_per_partition
# Strided linear layer.
self.query_key_value = ColumnParallelLinear(
hidden_size,
3 * self.inner_hidden_size,
stride=3,
gather_output=False,
init_method=init_method,
bias=bias,
module=self,
name="query_key_value"
)
self.attention_dropout = torch.nn.Dropout(attention_dropout_prob)
self.dense = RowParallelLinear(
self.inner_hidden_size,
hidden_size,
input_is_parallel=True,
init_method=output_layer_init_method,
bias=bias,
module=self,
name="dense"
)
self.output_dropout = torch.nn.Dropout(output_dropout_prob)
def _transpose_for_scores(self, tensor):
"""Transpose a 3D tensor [b, s, np*hn] into a 4D tensor with
size [b, np, s, hn].
"""
new_tensor_shape = tensor.size()[:-1] + \
(self.num_attention_heads_per_partition,
self.hidden_size_per_attention_head)
tensor = tensor.view(*new_tensor_shape)
return tensor.permute(0, 2, 1, 3)
def forward(self, hidden_states, mask, *args, **kw_args):
if 'attention_forward' in self.hooks:
return self.hooks['attention_forward'](hidden_states, mask, **kw_args)
else:
attention_fn = standard_attention
if 'attention_fn' in self.hooks:
attention_fn = self.hooks['attention_fn']
mixed_raw_layer = self.query_key_value(hidden_states)
(mixed_query_layer,
mixed_key_layer,
mixed_value_layer) = split_tensor_along_last_dim(mixed_raw_layer, 3)
dropout_fn = self.attention_dropout if self.training else None
query_layer = self._transpose_for_scores(mixed_query_layer)
key_layer = self._transpose_for_scores(mixed_key_layer)
value_layer = self._transpose_for_scores(mixed_value_layer)
context_layer = attention_fn(query_layer, key_layer, value_layer, mask, dropout_fn, **kw_args)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
context_layer = context_layer.view(*new_context_layer_shape)
output = self.dense(context_layer)
if self.training:
output = self.output_dropout(output)
return output
class CrossAttention(torch.nn.Module):
"""Parallel cross-attention layer for Transformer"""
def __init__(self, hidden_size, num_attention_heads, attention_dropout_prob, output_dropout_prob, init_method,
layer_id, hidden_size_per_attention_head=None, output_layer_init_method=None, bias=True, hooks={}):
super().__init__()
# Set output layer initialization if not provided.
if output_layer_init_method is None:
output_layer_init_method = init_method
self.hooks = hooks
self.layer_id = layer_id
# Per attention head and per partition values.
world_size = get_model_parallel_world_size()
self.hidden_size = hidden_size
if hidden_size_per_attention_head is None:
self.hidden_size_per_attention_head = divide(hidden_size, num_attention_heads)
else:
self.hidden_size_per_attention_head = hidden_size_per_attention_head
self.num_attention_heads_per_partition = divide(num_attention_heads, world_size)
self.inner_hidden_size = num_attention_heads * self.hidden_size_per_attention_head
self.hidden_size_per_partition = self.hidden_size_per_attention_head * self.num_attention_heads_per_partition
# Strided linear layer.
self.query = ColumnParallelLinear(hidden_size, self.inner_hidden_size,
gather_output=False,
init_method=init_method, bias=bias, module=self, name="query")
self.key_value = ColumnParallelLinear(hidden_size, 2 * self.inner_hidden_size,
stride=2,
gather_output=False,
init_method=init_method, bias=bias, module=self, name="key_value")
# Dropout. Note that for a single iteration, this layer will generate
# different outputs on different number of parallel partitions but
# on average it should not be partition dependent.
self.attention_dropout = torch.nn.Dropout(attention_dropout_prob)
# Output.
self.dense = RowParallelLinear(
self.inner_hidden_size,
hidden_size,
input_is_parallel=True,
init_method=output_layer_init_method, bias=bias, module=self, name="dense")
self.output_dropout = torch.nn.Dropout(output_dropout_prob)
def _transpose_for_scores(self, tensor):
"""Transpose a 3D tensor [b, s, np*hn] into a 4D tensor with
size [b, np, s, hn].
"""
new_tensor_shape = tensor.size()[:-1] + \
(self.num_attention_heads_per_partition,
self.hidden_size_per_attention_head)
tensor = tensor.view(*new_tensor_shape)
return tensor.permute(0, 2, 1, 3)
def forward(self, hidden_states, cross_attention_mask, encoder_outputs, **kw_args):
# hidden_states: [b, s, h]
if 'cross_attention_forward' in self.hooks:
return self.hooks['cross_attention_forward'](hidden_states, cross_attention_mask, encoder_outputs, **kw_args)
else:
attention_fn = standard_attention
if 'attention_fn' in self.hooks:
attention_fn = self.hooks['attention_fn']
mixed_query_layer = self.query(hidden_states)
mixed_x_layer = self.key_value(encoder_outputs)
(mixed_key_layer, mixed_value_layer) = split_tensor_along_last_dim(mixed_x_layer, 2)
dropout_fn = self.attention_dropout if self.training else None
# Reshape and transpose [b, np, s, hn]
query_layer = self._transpose_for_scores(mixed_query_layer)
key_layer = self._transpose_for_scores(mixed_key_layer)
value_layer = self._transpose_for_scores(mixed_value_layer)
context_layer = attention_fn(query_layer, key_layer, value_layer, cross_attention_mask, dropout_fn,
cross_attention=True, **kw_args)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
# [b, s, hp]
context_layer = context_layer.view(*new_context_layer_shape)
# Output. [b, s, h]
output = self.dense(context_layer)
if self.training:
output = self.output_dropout(output)
return output
class MLP(torch.nn.Module):
def __init__(self, hidden_size, output_dropout_prob, init_method, inner_hidden_size=None,
output_layer_init_method=None, layer_id=None, hooks={}, bias=True, activation_func=gelu):
super(MLP, self).__init__()
self.layer_id = layer_id
self.activation_func = activation_func
# Set output layer initialization if not provided.
if output_layer_init_method is None:
output_layer_init_method = init_method
self.hooks = hooks
# Project to 4h.
self.hidden_size = hidden_size
if inner_hidden_size is None:
inner_hidden_size = 4 * hidden_size
self.inner_hidden_size = inner_hidden_size
self.dense_h_to_4h = ColumnParallelLinear(
self.hidden_size,
self.inner_hidden_size,
gather_output=False,
init_method=init_method,
bias=bias,
module=self,
name="dense_h_to_4h"
)
# Project back to h.
self.dense_4h_to_h = RowParallelLinear(
self.inner_hidden_size,
self.hidden_size,
input_is_parallel=True,
init_method=output_layer_init_method,
bias=bias,
module=self,
name="dense_4h_to_h"
)
self.dropout = torch.nn.Dropout(output_dropout_prob)
def forward(self, hidden_states, **kw_args):
if 'mlp_forward' in self.hooks:
output = self.hooks['mlp_forward'](hidden_states, **kw_args)
else:
intermediate_parallel = self.dense_h_to_4h(hidden_states)
intermediate_parallel = self.activation_func(intermediate_parallel)
output = self.dense_4h_to_h(intermediate_parallel)
if self.training:
output = self.dropout(output)
return output
class BaseTransformerLayer(torch.nn.Module):
def __init__(
self,
hidden_size,
num_attention_heads,
attention_dropout_prob,
output_dropout_prob,
layernorm_epsilon,
init_method,
layer_id,
inner_hidden_size=None,
hidden_size_per_attention_head=None,
output_layer_init_method=None,
sandwich_ln=True,
layernorm=LayerNorm,
is_decoder=False,
use_bias=True,
activation_func=gelu,
hooks={}
):
super(BaseTransformerLayer, self).__init__()
# Set output layer initialization if not provided.
if output_layer_init_method is None:
output_layer_init_method = init_method
self.layer_id = layer_id
self.is_decoder = is_decoder
self.hooks = hooks
# Layernorm on the input data.
self.input_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
# Self attention.
self.attention = SelfAttention(
hidden_size,
num_attention_heads,
attention_dropout_prob,
output_dropout_prob,
init_method,
layer_id,
hidden_size_per_attention_head=hidden_size_per_attention_head,
output_layer_init_method=output_layer_init_method,
bias=use_bias,
hooks=hooks
)
# Layernorm on the input data.
self.post_attention_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
self.sandwich_ln = sandwich_ln
if sandwich_ln:
self.third_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
self.fourth_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
# Cross attention.
if self.is_decoder:
self.cross_attention = CrossAttention(
hidden_size,
num_attention_heads,
attention_dropout_prob,
output_dropout_prob,
init_method,
layer_id,
hidden_size_per_attention_head=hidden_size_per_attention_head,
output_layer_init_method=output_layer_init_method,
bias=use_bias,
hooks=hooks
)
self.post_cross_attention_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
self.mlp = MLP(
hidden_size,
output_dropout_prob,
init_method,
inner_hidden_size=inner_hidden_size,
output_layer_init_method=output_layer_init_method,
bias=use_bias,
layer_id=layer_id,
activation_func=activation_func,
hooks=hooks
)
def forward(self, hidden_states, mask, *args, **kw_args):
'''
hidden_states: [batch, seq_len, hidden_size]
mask: [(1, 1), seq_len, seq_len]
'''
# Layer norm at the begining of the transformer layer.
layernorm_output1 = self.input_layernorm(hidden_states)
# Self attention.
attention_output = self.attention(layernorm_output1, mask, **kw_args)
# Third LayerNorm
if self.sandwich_ln:
attention_output = self.third_layernorm(attention_output)
# Residual connection.
layernorm_input = hidden_states + attention_output
# Layer norm post the self attention.
layernorm_output = self.post_attention_layernorm(layernorm_input)
if self.is_decoder:
encoder_outputs = kw_args['encoder_outputs']
if encoder_outputs is not None:
assert 'cross_attention_mask' in kw_args
# Cross attention
attention_output = self.cross_attention(layernorm_output, **kw_args)
# Residual connection.
layernorm_input = layernorm_input + attention_output
# Layer norm post the cross attention
layernorm_output = self.post_cross_attention_layernorm(layernorm_input)
# MLP.
mlp_output = self.mlp(layernorm_output, **kw_args)
# Fourth LayerNorm
if self.sandwich_ln:
mlp_output = self.fourth_layernorm(mlp_output)
# Second residual connection.
output = layernorm_input + mlp_output
return output, kw_args['output_this_layer'], kw_args['output_cross_layer']
class BaseTransformer(torch.nn.Module):
def __init__(self,
num_layers,
vocab_size,
hidden_size,
num_attention_heads,
max_sequence_length,
embedding_dropout_prob,
attention_dropout_prob,
output_dropout_prob,
checkpoint_activations,
checkpoint_num_layers=1,
layernorm_epsilon=1.0e-5,
init_method_std=0.02,
inner_hidden_size=None,
hidden_size_per_attention_head=None,
sandwich_ln=True,
parallel_output=True,
is_decoder=False,
use_bias=True,
activation_func=gelu,
layernorm=LayerNorm,
init_method=None,
hooks={}
):
super(BaseTransformer, self).__init__()
# recording parameters
self.is_decoder = is_decoder
self.parallel_output = parallel_output
self.checkpoint_activations = checkpoint_activations
self.checkpoint_num_layers = checkpoint_num_layers
self.max_sequence_length = max_sequence_length
self.hooks = copy.copy(hooks) # hooks will be updated each forward
# create embedding parameters
self.embedding_dropout = torch.nn.Dropout(embedding_dropout_prob)
self.word_embeddings = VocabParallelEmbedding(
vocab_size, hidden_size, init_method=unscaled_init_method(0.02))
# position embedding
self.position_embeddings = torch.nn.Embedding(max_sequence_length, hidden_size)
torch.nn.init.normal_(self.position_embeddings.weight, mean=0.0, std=init_method_std)
# create all layers
if init_method is None:
self.output_layer_init_method = scaled_init_method(init_method_std, num_layers)
self.init_method = unscaled_init_method(init_method_std)
else:
self.output_layer_init_method = init_method
self.init_method = init_method
def get_layer(layer_id):
return BaseTransformerLayer(
hidden_size,
num_attention_heads,
attention_dropout_prob,
output_dropout_prob,
layernorm_epsilon,
self.init_method,
layer_id,
inner_hidden_size=inner_hidden_size,
hidden_size_per_attention_head=hidden_size_per_attention_head,
output_layer_init_method=self.output_layer_init_method,
is_decoder=self.is_decoder,
sandwich_ln=sandwich_ln,
layernorm=layernorm,
use_bias=use_bias,
activation_func=activation_func,
hooks=self.hooks
)
self.layers = torch.nn.ModuleList(
[get_layer(layer_id) for layer_id in range(num_layers)])
# Final layer norm before output.
self.final_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
def forward(self, input_ids, position_ids, attention_mask, *,
output_hidden_states=False, **kw_args):
# sanity check
assert len(input_ids.shape) == 2
batch_size, query_length = input_ids.shape
if attention_mask is None:
attention_mask = torch.ones(1, 1, device=input_ids.device).type_as(
next(self.parameters())
) # None means full attention
assert len(attention_mask.shape) == 2 or \
len(attention_mask.shape) == 4 and attention_mask.shape[1] == 1
# embedding part
if 'word_embedding_forward' in self.hooks:
hidden_states = self.hooks['word_embedding_forward'](input_ids, **kw_args)
else: # default
hidden_states = self.word_embeddings(input_ids)
# debug
assert hidden_states.shape[1] == attention_mask.shape[-1], f'hidden_states.shape: {hidden_states.shape}, ' \
f'attention_mask.shape: {attention_mask.shape}'
if 'position_embedding_forward' in self.hooks:
position_embeddings = self.hooks['position_embedding_forward'](position_ids, **kw_args)
else:
assert len(position_ids.shape) <= 2
assert position_ids.shape[-1] == query_length
position_embeddings = self.position_embeddings(position_ids)
if position_embeddings is not None:
hidden_states = hidden_states + position_embeddings
hidden_states = self.embedding_dropout(hidden_states)
# initial output_cross_layer
if 'cross_layer_embedding_forward' in self.hooks:
output_cross_layer = self.hooks['cross_layer_embedding_forward'](hidden_states, **kw_args)
else:
output_cross_layer = {}
output_per_layers = []
if self.checkpoint_activations:
# define custom_forward for checkpointing
def custom(start, end, kw_args_index, cross_layer_index):
def custom_forward(*inputs):
layers_ = self.layers[start:end]
x_, mask = inputs[0], inputs[1]
# recover kw_args and output_cross_layer
flat_inputs = inputs[2:]
kw_args, output_cross_layer = {}, {}
for k, idx in kw_args_index.items():
kw_args[k] = flat_inputs[idx]
for k, idx in cross_layer_index.items():
output_cross_layer[k] = flat_inputs[idx]
# -----------------
output_per_layers_part = []
for i, layer in enumerate(layers_):
if 'layer_forward' in self.hooks:
layer_ret = self.hooks['layer_forward'](
x_, mask, layer_id=layer.layer_id,
**kw_args, **output_cross_layer,
output_this_layer={}, output_cross_layer={}
)
else:
layer_ret = layer(
x_, mask, layer_id=layer.layer_id,
**kw_args, **output_cross_layer,
output_this_layer={}, output_cross_layer={}
)
if torch.is_tensor(layer_ret): # only hidden_states
x_, output_this_layer, output_cross_layer = layer_ret, {}, {}
elif len(layer_ret) == 2: # hidden_states & output_this_layer
x_, output_this_layer = layer_ret
output_cross_layer = {}
elif len(layer_ret) == 3:
x_, output_this_layer, output_cross_layer = layer_ret
assert isinstance(output_this_layer, dict)
assert isinstance(output_cross_layer, dict)
if output_hidden_states:
output_this_layer['hidden_states'] = x_
output_per_layers_part.append(output_this_layer)
# flatten for re-aggregate keywords outputs
flat_outputs = []
for output_this_layer in output_per_layers_part:
for k in output_this_layer:
# TODO add warning for depth>=2 grad tensors
flat_outputs.append(output_this_layer[k])
output_this_layer[k] = len(flat_outputs) - 1
for k in output_cross_layer:
flat_outputs.append(output_cross_layer[k])
output_cross_layer[k] = len(flat_outputs) - 1
# --------------------
# return x_, output_per_layers_part, output_cross_layer, flat_outputs
# fix bug
return (x_, output_per_layers_part, output_cross_layer, *flat_outputs)
return custom_forward
# prevent to lose requires_grad in checkpointing.
# To save memory when only finetuning the final layers, don't use checkpointing.
if self.training:
hidden_states.requires_grad_(True)
l, num_layers = 0, len(self.layers)
chunk_length = self.checkpoint_num_layers
output_this_layer = []
while l < num_layers:
args = [hidden_states, attention_mask]
# flatten kw_args and output_cross_layer
flat_inputs, kw_args_index, cross_layer_index = [], {}, {}
for k, v in kw_args.items():
flat_inputs.append(v)
kw_args_index[k] = len(flat_inputs) - 1
for k, v in output_cross_layer.items():
flat_inputs.append(v)
cross_layer_index[k] = len(flat_inputs) - 1
# --------------------
# hidden_states, output_per_layers_part, output_cross_layer, flat_outputs = \
# checkpoint(custom(l, l + chunk_length, kw_args_index, cross_layer_index), *args, *flat_inputs)
# fix bug
hidden_states, output_per_layers_part, output_cross_layer, *flat_outputs = \
checkpoint(custom(l, l + chunk_length, kw_args_index, cross_layer_index), *args, *flat_inputs)
# recover output_per_layers_part, output_cross_layer
for output_this_layer in output_per_layers_part:
for k in output_this_layer:
output_this_layer[k] = flat_outputs[output_this_layer[k]]
for k in output_cross_layer:
output_cross_layer[k] = flat_outputs[output_cross_layer[k]]
# --------------------
output_per_layers.extend(output_per_layers_part)
l += chunk_length
else:
output_this_layer = []
for i, layer in enumerate(self.layers):
args = [hidden_states, attention_mask]
if 'layer_forward' in self.hooks: # customized layer_forward
layer_ret = self.hooks['layer_forward'](*args, layer_id=torch.tensor(i),
**kw_args,
**output_cross_layer,
output_this_layer={}, output_cross_layer={}
)
else:
layer_ret = layer(*args, layer_id=torch.tensor(i), **kw_args, **output_cross_layer,
output_this_layer={}, output_cross_layer={})
if torch.is_tensor(layer_ret): # only hidden_states
hidden_states, output_this_layer, output_cross_layer = layer_ret, {}, {}
elif len(layer_ret) == 2: # hidden_states & output_this_layer
hidden_states, output_this_layer = layer_ret
output_cross_layer = {}
elif len(layer_ret) == 3:
hidden_states, output_this_layer, output_cross_layer = layer_ret
if output_hidden_states:
output_this_layer['hidden_states'] = hidden_states
output_per_layers.append(output_this_layer)
# Final layer norm.
logits = self.final_layernorm(hidden_states)
if 'final_forward' in self.hooks:
logits_parallel = self.hooks['final_forward'](logits, **kw_args)
else:
logits_parallel = copy_to_model_parallel_region(logits)
logits_parallel = F.linear(logits_parallel, self.word_embeddings.weight)
if not self.parallel_output:
logits_parallel = gather_from_model_parallel_region(logits_parallel)
outputs = [logits_parallel]
outputs.extend(output_per_layers)
return outputs |
"""controller for course level"""
# pylint: disable=redefined-builtin,broad-exception-raised
import os
import json
from services.lu_inference import LearningUnitService
from services.validations import check_valid_request
from common.utils.kf_job_app import (kube_create_job,
kube_get_namespaced_deployment_image_path)
from common.utils.logging_handler import Logger
from config import (JOB_NAMESPACE, GCP_PROJECT, CONTAINER_NAME,
DEPLOYMENT_NAME, BATCH_JOB_LIMITS, BATCH_JOB_REQUESTS)
class LearningUnitController():
"""controller class for learning unit level"""
learning_unit = LearningUnitService()
@staticmethod
def create_lu_controller_method(parent_id, request_body):
"""controller method to create a learning unit"""
if parent_id:
return LearningUnitController.learning_unit.create_learning_unit(
parent_id, request_body)
else:
raise Exception("learning objective id is missing in the URL")
@staticmethod
async def update_lu_controller_method(id, request_body):
"""controller method to update a learning unit"""
if id:
return await LearningUnitController.learning_unit.update_learning_unit(
id, request_body)
else:
raise Exception("learning unit ID is missing in the URL")
@staticmethod
def get_lu_controller_method(id):
"""controller method to get a learning unit by id"""
if id:
return LearningUnitController.learning_unit.get_learning_unit(id)
else:
raise Exception("learning unit ID is missing in the URL")
@staticmethod
def get_all_lu_controller_method(parent_id):
"""controller method to get all learning units"""
if parent_id:
return LearningUnitController.learning_unit.get_all_learning_units(
parent_id)
else:
raise Exception("learning objective ID is missing in the URL")
@staticmethod
def delete_lu_controller_method(id):
"""controller method to delete a learning unit"""
if id:
return LearningUnitController.learning_unit.delete_learning_unit(id)
else:
raise Exception("learning unit ID is missing in the URL")
@staticmethod
def create_lu_from_lo_controller_method(lo_id, request_body):
Logger.info("Request Body for batch Job: {}".format(request_body))
check_valid_request({"id": lo_id})
if lo_id:
request_body["lo_id"] = lo_id
request_body["title"] = "Learning_Unit_Generation_{}".format(lo_id)
image_path = kube_get_namespaced_deployment_image_path(DEPLOYMENT_NAME,
CONTAINER_NAME,
JOB_NAMESPACE,
GCP_PROJECT)
job_specs = {
"container_image": image_path,
"type": "course-ingestion_learning-units",
"input_data": json.dumps(request_body),
"limits": BATCH_JOB_LIMITS,
"requests": BATCH_JOB_REQUESTS
}
env_vars = {"GCP_PROJECT": GCP_PROJECT,
"DATABASE_PREFIX": os.getenv("DATABASE_PREFIX", "")}
return kube_create_job(job_specs, JOB_NAMESPACE, env_vars)
else:
raise Exception("Learning Objective ID is missing in the URL") |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common/libs/utils/users.h"
#include <grp.h>
#include <pwd.h>
#include <sys/types.h>
#include <unistd.h>
#include <algorithm>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <ostream>
#include <string>
#include <vector>
#include <android-base/file.h>
#include <android-base/logging.h>
#include "common/libs/utils/contains.h"
namespace cuttlefish {
namespace {
std::vector<gid_t> GetSuplementaryGroups() {
int num_groups = getgroups(0, nullptr);
if (num_groups < 0) {
LOG(ERROR) << "Unable to get number of suplementary groups: "
<< std::strerror(errno);
return {};
}
std::vector<gid_t> groups(num_groups + 1);
int retval = getgroups(groups.size(), groups.data());
if (retval < 0) {
LOG(ERROR) << "Error obtaining list of suplementary groups (list size: "
<< groups.size() << "): " << std::strerror(errno);
return {};
}
return groups;
}
} // namespace
gid_t GroupIdFromName(const std::string& group_name) {
struct group grp{};
struct group* grp_p{};
std::vector<char> buffer(100);
int result = 0;
while(true) {
result = getgrnam_r(group_name.c_str(), &grp, buffer.data(), buffer.size(),
&grp_p);
if (result != ERANGE) {
break;
}
buffer.resize(2*buffer.size());
}
if (result == 0) {
if (grp_p != nullptr) {
return grp.gr_gid;
} else {
// Caller may be checking with non-existent group name
return -1;
}
} else {
LOG(ERROR) << "Unable to get group id for group " << group_name << ": "
<< std::strerror(result);
return -1;
}
}
bool InGroup(const std::string& group) {
auto gid = GroupIdFromName(group);
if (gid == static_cast<gid_t>(-1)) {
return false;
}
if (gid == getegid()) {
return true;
}
auto groups = GetSuplementaryGroups();
return Contains(groups, gid);
}
Result<std::string> SystemWideUserHome(const uid_t uid) {
// getpwuid() is not thread-safe, so we need a lock across all calls
static std::mutex getpwuid_mutex;
std::string home_dir;
{
std::lock_guard<std::mutex> lock(getpwuid_mutex);
const auto entry = getpwuid(uid);
if (entry) {
home_dir = entry->pw_dir;
}
endpwent();
if (home_dir.empty()) {
return CF_ERRNO("Failed to find the home directory using " << uid);
}
}
std::string home_realpath;
if (!android::base::Realpath(home_dir, &home_realpath)) {
return CF_ERRNO("Failed to convert " << home_dir << " to its Realpath");
}
return home_realpath;
}
Result<std::string> SystemWideUserHome() {
return SystemWideUserHome(getuid());
}
} // namespace cuttlefish |
library("tidyverse") # Load tidyverse package
library(gtools)
#Create a list with the alpha and beta(missing - LATER)
#Alpha data list
Base_alpha <- list.files(path = "/home/constantin/windows/", pattern="boot_base_alpha", recursive = TRUE)
Base_alpha <- mixedsort(Base_alpha)
Base_alpha
#Alpha-error list
Error_alpha <- list.files(path = "/home/constantin/windows/", pattern="errors_alpha", recursive = TRUE)
Error_alpha <- mixedsort(Error_alpha)
Error_alpha
#Beta data list
Base_beta <- list.files(path = "/home/constantin/windows/", pattern="boot_base_beta.txt", recursive = TRUE)
Base_beta <- mixedsort(Base_beta)
Base_beta
#Beta-error list
Error_beta <- list.files(path = "/home/constantin/windows/", pattern="errors_beta", recursive = TRUE)
Error_beta <- mixedsort(Error_beta)
Error_beta
################################################# Alpha plot
y_list = list()
x_list = list()
y.sd_list = list()
x <- (-5)
for (i in 1:length(Base_alpha)){
#print(Base_alpha[i])
setwd("/home/constantin/windows")
y <- read.table(gsub(" ", "/t", Base_alpha[i]))[2]
y.sd <- read.table(gsub(" ", "/t", Error_alpha[i]))[2]
x <- x+5
#Transform de frame.value in numeric
y = as.numeric(as.character(y))
y.sd = as.numeric(as.character(y.sd))
#print(y)
#print(y.sd)
#print(x)
#Create list
y_list <- append(y_list, y)
y.sd_list <- append(y.sd_list, y.sd)
x_list <- append(x_list, x)
}
#Create a matrix with alpha data
data_A <- list(x_list, y_list, y.sd_list)
mtrx_A <- matrix(unlist(data_A), ncol = 3, nrow = length(y_list))
mtrx_A
#Create a table
library(MASS)
write.matrix(mtrx_A,file="Mat_A.csv")
Mat_A <- read_table("Mat_A.csv", col_names = FALSE)
#PLOT
pdf(file="saving_plot_alpha.pdf")
# The errorbars overlapped, so use position_dodge to move them horizontally
pd <- position_dodge(0.1) # move them .05 to the left and right
p<- ggplot(Mat_A, aes(x=X1, y=X2), col="green") +
geom_line(position=pd) +
geom_point(position=pd, size=3, shape=21, fill="white")+
geom_errorbar(aes(ymin=X2-X3, ymax=X2+X3), colour="black", width=.1, position=pd)+
ggtitle("DNA methylation (Alpha)") +
xlab("%") +
ylab("Alpha")
print(p)
dev.off()
################################################# Beta plot
y_list = list()
x_list = list()
y.sd_list = list()
x <- (-5)
for (i in 1:length(Base_beta)){
#print(Base_beta[i])
setwd("/home/constantin/windows")
y <- read.table(gsub(" ", "/t", Base_beta[i]))[2]
y.sd <- read.table(gsub(" ", "/t", Error_beta[i]))[2]
x <- x+5
#Transform de frame.value in numeric
y = as.numeric(as.character(y))
y.sd = as.numeric(as.character(y.sd))
#print(y)
#print(y.sd)
#print(x)
#Create list
y_list <- append(y_list, y)
y.sd_list <- append(y.sd_list, y.sd)
x_list <- append(x_list, x)
}
#Create a matrix with beta data
data_B <- list(x_list, y_list, y.sd_list)
mtrx_B <- matrix(unlist(data_B), ncol = 3, nrow = length(y_list))
mtrx_B
#Create a table
library(MASS)
write.matrix(mtrx_B,file="Mat_B.csv")
Mat_B <- read_table("Mat_B.csv", col_names = FALSE)
#PLOT
pdf(file="saving_plot_beta.pdf")
# The errorbars overlapped, so use position_dodge to move them horizontally
pd <- position_dodge(0.1) # move them .05 to the left and right
p<- ggplot(Mat_B, aes(x=X1, y=X2), col="green") +
geom_line(position=pd) +
geom_point(position=pd, size=3, shape=21, fill="white")+
geom_errorbar(aes(ymin=X2-X3, ymax=X2+X3), colour="black", width=.1, position=pd)+
ggtitle("DNA methylation (Beta)") +
xlab("%") +
ylab("Beta")
print(p)
dev.off() |
"use client";
import React, { useContext } from "react";
import { HomeContext } from "./context/HomeContext";
import { FaPause, FaPlay } from "react-icons/fa";
import videos, { Video } from "./data/video";
import { AiFillSound } from "react-icons/ai";
import { convertTimeToString } from "./utils/Utils";
export default function Home() {
const {
videoURL,
playing,
totalTime,
currentTime,
videoRef,
canvasRef,
playPause,
configCurrentTime,
configVideo,
playSound,
configFilter
} = useContext(HomeContext);
const volumeControl = (e: React.ChangeEvent<HTMLInputElement>) => {
const volume = parseFloat(e.target.value);
playSound(volume);
};
return (
<main className="mx-auto w-[65%] mt-2 flex">
<div className="w-[640px] mr-1">
<h1 className="font-bold text-black">
Home {videoURL} - {playing ? "true" : "false"}
</h1>
<video width={640} ref={videoRef} controls src={videoURL} hidden></video>
<canvas className="w-full h-[380px]" ref={canvasRef}></canvas>
<div className="bg-white flex">
<input className="appearance-none w-full h-3 bg-gray-200 rounded-full
[&::-webkit-slider-runnable-track]:appearance-none
[&::-webkit-slider-thumb]:appearance-none
[&::-webkit-slider-runnable-track]:bg-[black]
[&::-webkit-slider-thumb]:h-[10px]
[&::-webkit-slider-thumb]:w-[10px]
[&::-webkit-slider-thumb]:bg-[blue]
[&::-webkit-slider-thumb]:rounded-full"
type="range"
min={0}
max={totalTime}
value={currentTime}
onChange={(e) => configCurrentTime(Number(e.target.value))}
></input>
<div className="ml-4">
<AiFillSound />
</div>
<input
className="appearance-none w-16 ml-2 h-3 bg-gray-200 rounded-full"
type="range"
min={0}
max={1}
step={0.1}
onChange={volumeControl}
></input>
</div>
<button className="mt-4" onClick={playPause}>
{playing ? <FaPause /> : <FaPlay />}
</button>
<select onChange={(e) => configFilter(Number(e.target.value))}>
<option selected value={0}>Verde</option>
<option value={1}>Azul</option>
<option value={2}>vermelho</option>
<option value={3}>Preto e Branco</option>
</select>
{convertTimeToString(currentTime)}/{convertTimeToString(totalTime)}
</div>
<div className="w-[35%] h-[100vh]">
{videos.map((video: Video, index) => {
return (
<button className="w-full" onClick={(e) => configVideo(index)} key={index}>
<img
className="w-full h-[200px] mb-1"
src={video.imageURL}
alt={`Thumbnail ${index}`}
/>
</button>
);
})}
</div>
</main>
);
} |
import React from 'react';
import { useFormik } from 'formik';
import { useNavigate } from "react-router-dom";
import sma from '../assets/sma.png'
import Button from '../elements/Button';
import bg from '../assets/bg.jpeg'
const validate = values => {
const errors = {};
if (!values.password) {
errors.password = 'Required';
} else if (values.password.length < 8) {
errors.password = 'Your password must be at least 8 characters';
}
if (!values.username) {
errors.username = 'Required';
}
return errors;
};
const Login = () => {
const navigate = useNavigate()
const formik = useFormik({
initialValues: {
username: '',
password: '',
},
validate,
onSubmit: values => {
if(values.username == "admin" && values.password == "admin123"){
// alert(JSON.stringify(values, null, 2));
// console.log(email);
navigate('/menuAdmin', {replace:true})
}else{
navigate('/menuUtama', {replace:true})
}
},
});
return (
<div className='col-12 d-flex' style={{height:'100vh', backgroundImage:`url(${bg})`, backgroundRepeat: 'no-repeat',
backgroundSize: 'cover'}}>
<div className='col-6 col-lg-4 m-auto rounded' style={{backgroundColor:'var(--secondary)'}}>
<div className='mb-3 col-6 col-lg-4 m-auto'>
<img src={sma} alt="SMA" />
</div>
<h1 className='text-center mb-4'>LOGIN</h1>
<form onSubmit={formik.handleSubmit}>
{/* <form> */}
<div className='d-flex p-3'>
<label htmlFor='username' className='me-4 ' >Username</label>
<input
id='username'
name='username'
type='text'
className='form-control'
onChange={formik.handleChange}
// value={''}
/>
{formik.errors.email ? <div className='text-danger fw-light '>{formik.errors.email}</div> : null}
</div>
<div className='mt-3 d-flex p-3'>
<label htmlFor='password' className='me-4 '>Password</label>
<input
id='password'
name='password'
type='password'
className='form-control'
onChange={formik.handleChange}
/>
{formik.errors.password ? <div className='text-danger fw-light'>{formik.errors.password}</div> : null}
</div>
<div className='d-flex justify-content-end col-12 p-3 gap-4 mt-4'>
<Button
text={'Login'}
type={'submit'}
/>
<Button
text={'Cancel'}
type={'button'}
/>
</div>
</form>
</div>
</div>
);
};
export default Login |
<?php // $Id$
/**
* @file template.preprocess-page.inc
*/
/**
* Override or insert variables into page templates.
*
* @param $vars
* A sequential array of variables to pass to the theme template.
* @param $hook
* The name of the theme function being called.
*/
global $theme, $theme_info, $user, $language;
// Don't display empty help from node_help().
if ($vars['help'] == "<div class=\"help\"> \n</div>") {
$vars['help'] = '';
}
// Remove sidebars if disabled e.g., for Panels.
if (!$vars['show_blocks']) {
$vars['left'] = '';
$vars['right'] = '';
}
// Set variables for the logo and site name for easy printing in templates.
$vars['logo_alt_text'] = check_plain(variable_get('site_name', '')) .' '. t('logo');
$vars['logo_img'] = $vars['logo'] ? '<img src="'. check_url($vars['logo']) .'" alt="'. $vars['logo_alt_text'] .'" title="'. t('Home page') .'"/>' : '';
$vars['linked_site_logo'] = $vars['logo_img'] ? l($vars['logo_img'], '<front>', array('attributes' => array('rel' => 'home'), 'title' => t('Home page'), 'html' => TRUE)) : '';
$vars['linked_site_name'] = $vars['site_name'] ? l($vars['site_name'], '<front>', array('attributes' => array('rel' => 'home'), 'title' => t('Home page'))) : '';
// Set variables for the primary and secondary links.
$primary_menu_links = $vars['primary_links'];
$secondary_menu_links = $vars['secondary_links'];
// Standard primary and secondary links.
if (!empty($primary_menu_links)) {
$vars['primary_menu'] = theme('links', $primary_menu_links, array('class' => 'primary-links clearfix'));
}
if (!empty($secondary_menu_links)) {
$vars['secondary_menu'] = theme('links', $secondary_menu_links, array('class' => 'secondary-links clearfix'));
}
// Output the primary and secondary menus as regular menu trees.
if (!empty($primary_menu_links) && theme_get_setting('primary_links_tree')) {
$primary_tree_menu = menu_tree_all_data('primary-links');
$vars['primary_menu'] = menu_tree_output($primary_tree_menu);
}
if (!empty($secondary_menu_links) && theme_get_setting('secondary_links_tree')) {
$secondary_tree_menu = menu_tree_all_data('secondary-links');
$vars['secondary_menu'] = menu_tree_output($secondary_tree_menu);
}
// Attribution.
$vars['attribution'] = "<div id=\"attribution\">Besøk <a href=\"http://drupalnorge.no\">Drupal Norge</a>, det offisielle norske nettsted for Drupal</div>" ;
// Body classes - manipulate for our own ends, in Drupal 7 we can drop most of these shenanagins.
$classes = explode(' ', $vars['body_classes']);
// Section class - use the path alias otherwise all nodes will be in "section-node".
if (theme_get_setting('cleanup_classes_section')) {
$path_alias = drupal_get_path_alias($_GET['q']);
if (!$vars['is_front']) {
list($section, ) = explode('/', $path_alias, 2);
$classes[] = safe_string('section-'. $section);
}
}
// Unset Drupals page-arg(0) class.
if ($index = array_search(preg_replace('![^abcdefghijklmnopqrstuvwxyz0-9-_]+!s', '', 'page-'. drupal_strtolower(arg(0))), $classes)) {
unset($classes[$index]);
}
// Replace left and right with first and last - better support for RTL.
$classes = str_replace('sidebar-left', 'sidebar-first', $classes);
$classes = str_replace('sidebar-right', 'sidebar-last', $classes);
// .front and .not-front classes.
if (in_array('front', $classes)) {
theme_get_setting('cleanup_classes_front') ? '' : $classes = str_replace('front', '', $classes);
}
if (in_array('not-front', $classes)) {
theme_get_setting('cleanup_classes_front') ? '' : $classes = str_replace('not-front', '', $classes);
}
// User status classes.
if (in_array('logged-in', $classes)) {
theme_get_setting('cleanup_classes_user_status') ? '' : $classes = str_replace('logged-in', '', $classes);
}
if (in_array('not-logged-in', $classes)) {
theme_get_setting('cleanup_classes_user_status') ? '' : $classes = str_replace('not-logged-in', '', $classes);
}
// Node type classes.
if (in_array('node-type-'. $vars['node']->type, $classes)) {
theme_get_setting('cleanup_classes_node_type') ? '' : $classes = str_replace('node-type-'. $vars['node']->type, '', $classes);
}
if (!$vars['is_front']) {
// Replacement for Drupals page-arg(0) class, instead we print page-$normal_page.
if (theme_get_setting('cleanup_classes_normal_path')) {
$normal_path = drupal_get_normal_path($_GET['q']);
$classes[] = safe_string('page-'. $normal_path);
}
// Groundwork can use this class to restyle the blocks page.
if (arg(2) == 'block') {
$classes[] = 'page-block';
}
// Add extra classes for node add, edit and delete pages.
if (theme_get_setting('cleanup_classes_add_edit_delete')) {
if (arg(0) == 'node') {
if (arg(1) == 'add') {
$classes[] = 'node-add'; // Add .node-add class.
}
elseif (is_numeric(arg(1)) && (arg(2) == 'edit' || arg(2) == 'delete')) {
$classes[] = 'node-'. arg(2);
}
}
}
}
// Language specific body class.
if (theme_get_setting('cleanup_classes_language')) {
if (function_exists('locale')) {
$classes[] = 'lang-'. $language->language;
}
}
// $classes is the varaible that holds the page classes, printed in page tpl files.
$vars['classes'] = trim(implode(' ', $classes));
// Layout settings - set the page width and layout method.
if (theme_get_setting('layout_enable_settings') == 'on') {
$method = theme_get_setting('layout_method');
$sidebar_last_width = theme_get_setting('layout_sidebar_last_width');
$sidebar_first_width = theme_get_setting('layout_sidebar_first_width');
if ($vars['language']->dir == 'ltr') {
$left = 'left';
$right = 'right';
}
if ($vars['language']->dir == 'rtl') {
$left = 'right';
$right = 'left';
}
if ($method == '0') {
$push_right = $sidebar_last_width;
$push_left = $sidebar_first_width;
$pull_right = $sidebar_last_width;
$styles = array();
$styles[] = '.two-sidebars .content-inner{margin-'. $left .':'. $push_left .'px; margin-'. $right .':'. $push_right .'px;}';
$styles[] = '.sidebar-first .content-inner{margin-'. $left .':'. $push_left .'px; margin-'. $right .':0;}';
$styles[] = '.sidebar-last .content-inner{margin-'. $right .':'. $push_right .'px; margin-'. $left .':0;}';
$styles[] = '#sidebar-first{width:'. $sidebar_first_width .'px;margin-'. $left .':-100%;}';
$styles[] = '#sidebar-last{width:'. $sidebar_last_width .'px;margin-'. $left .':-'. $pull_right .'px;}';
}
if ($method == '1') {
$content_margin = $sidebar_last_width + $sidebar_first_width;
$push_right = $sidebar_last_width;
$push_left = $sidebar_first_width;
$left_margin = $sidebar_last_width + $sidebar_first_width;
$right_margin = $sidebar_last_width;
$styles = array();
$styles[] = '.two-sidebars .content-inner{margin-'. $right .':'. $content_margin .'px;margin-'. $left .':0;}';
$styles[] = '.sidebar-first .content-inner{margin-'. $right .':'. $push_left .'px;margin-'. $left .':0;}';
$styles[] = '.sidebar-last .content-inner{margin-'. $right .':'. $push_right .'px;margin-'. $left .':0;}';
$styles[] = '#sidebar-first{width:'. $sidebar_first_width .'px;margin-'. $left .':-'. $left_margin .'px;}';
$styles[] = '#sidebar-last{width:'. $sidebar_last_width .'px;margin-'. $left .':-'. $right_margin .'px;}';
$styles[] = '.sidebar-first #sidebar-first{width:'. $sidebar_first_width .'px;margin-'. $left .':-'. $sidebar_first_width .'px;}';
}
if ($method == '2') {
$content_margin = $sidebar_last_width + $sidebar_first_width;
$left_margin = $sidebar_first_width;
$right_margin = $sidebar_last_width;
$push_right = $sidebar_first_width;
$styles = array();
$styles[] = '.two-sidebars .content-inner{margin-'. $left .':'. $content_margin .'px;margin-'. $right .':0;}';
$styles[] = '.sidebar-first .content-inner{margin-'. $left .':'. $left_margin .'px;margin-'. $right .':0;}';
$styles[] = '.sidebar-last .content-inner{margin-'. $left .':'. $right_margin .'px;margin-'. $right .':0;}';
$styles[] = '#sidebar-first{width:'. $sidebar_first_width .'px; margin-'. $left .': -100%;}';
$styles[] = '#sidebar-last{width:'. $sidebar_last_width .'px; margin-'. $left .': -100%;}';
$styles[] = '.two-sidebars #sidebar-last {width:'. $sidebar_last_width .'px; position: relative;'. $left .':'. $push_right .'px;}';
}
$styles ? $vars['gw_layout'] = implode('', $styles) : '';
$vars['layout_settings'] = '<style type="text/css">'. $vars['gw_layout_width'] . $vars['gw_layout'] .'</style>';
}
// Display mission statement on all pages.
if (theme_get_setting('mission_statement_pages') == 'all') {
$vars['mission'] = theme_get_setting('mission', FALSE);
}
// Show $theme_info output using krumo.
if (module_exists('devel') && theme_get_setting('show_theme_info') == 1) {
dsm($theme_info); /* Use dsm, kpr messes up IE */
}
// Check whether help is disabled.
if (theme_get_setting('gw_admin_hide_help')) {
unset($vars['help']);
}
// Hide search theme form label
if ($vars['search_box']) {
$vars['toggle_label'] = ' class="hide-label"';
}
$vars['user_bar'] = gw_user_bar(); |
import { buildLogger, logger as pluginLogger } from "../../src/plugins/logger.plugin";
describe('plugins/logger.plugin.ts', () => {
test('buildLogger should return a function logger', () => {
const logger = buildLogger('test')
expect(typeof logger.log).toBe('function')
expect(typeof logger.error).toBe('function')
})
test("Test 'buildLogger' with empty string", () => {
const logger = buildLogger('')
expect(typeof logger.log).toBe('function')
expect(typeof logger.error).toBe('function')
})
test("Test 'log' with empty string", () => {
const logger = buildLogger('test')
const mockLog = jest.spyOn(pluginLogger, 'log')
logger.log('')
expect(mockLog).toHaveBeenCalledWith('info',
expect.objectContaining({ level: 'info', message: '', service: 'test' }))
})
test("Test 'error' with empty string", () => {
const logger = buildLogger('test')
const mockError = jest.spyOn(pluginLogger, 'error')
logger.error('')
expect(mockError).toHaveBeenCalledWith('error',
expect.objectContaining({ message: '', service: 'test' }))
})
}) |
import '/backend/backend.dart';
import '/components/app_bar_custom_copy_widget.dart';
import '/flutter_flow/flutter_flow_animations.dart';
import '/flutter_flow/flutter_flow_icon_button.dart';
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'track_application_model.dart';
export 'track_application_model.dart';
class TrackApplicationWidget extends StatefulWidget {
const TrackApplicationWidget({
super.key,
required this.appliedJobRef,
required this.jobCollectionRef,
});
final DocumentReference? appliedJobRef;
final DocumentReference? jobCollectionRef;
@override
State<TrackApplicationWidget> createState() => _TrackApplicationWidgetState();
}
class _TrackApplicationWidgetState extends State<TrackApplicationWidget>
with TickerProviderStateMixin {
late TrackApplicationModel _model;
final scaffoldKey = GlobalKey<ScaffoldState>();
final animationsMap = <String, AnimationInfo>{};
@override
void initState() {
super.initState();
_model = createModel(context, () => TrackApplicationModel());
animationsMap.addAll({
'containerOnPageLoadAnimation': AnimationInfo(
trigger: AnimationTrigger.onPageLoad,
effectsBuilder: () => [
ScaleEffect(
curve: Curves.easeInOut,
delay: 0.0.ms,
duration: 600.0.ms,
begin: const Offset(0.0, 0.0),
end: const Offset(1.0, 1.0),
),
FadeEffect(
curve: Curves.easeInOut,
delay: 0.0.ms,
duration: 600.0.ms,
begin: 0.0,
end: 1.0,
),
],
),
});
WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {}));
}
@override
void dispose() {
_model.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return StreamBuilder<AppliedJobRecord>(
stream: AppliedJobRecord.getDocument(widget.appliedJobRef!),
builder: (context, snapshot) {
// Customize what your widget looks like when it's loading.
if (!snapshot.hasData) {
return Scaffold(
backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
body: Center(
child: SizedBox(
width: 50.0,
height: 50.0,
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
FlutterFlowTheme.of(context).primary,
),
),
),
),
);
}
final trackApplicationAppliedJobRecord = snapshot.data!;
return GestureDetector(
onTap: () => _model.unfocusNode.canRequestFocus
? FocusScope.of(context).requestFocus(_model.unfocusNode)
: FocusScope.of(context).unfocus(),
child: Scaffold(
key: scaffoldKey,
backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
body: Container(
width: 449.0,
height: 832.0,
decoration: BoxDecoration(
color: FlutterFlowTheme.of(context).primaryBackground,
),
child: Stack(
children: [
Align(
alignment: const AlignmentDirectional(0.0, -1.0),
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
Stack(
children: [
Align(
alignment: const AlignmentDirectional(0.0, -1.0),
child: wrapWithModel(
model: _model.appBarCustomCopyModel,
updateCallback: () => setState(() {}),
child: const AppBarCustomCopyWidget(),
),
),
Align(
alignment: const AlignmentDirectional(0.0, 1.0),
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
10.0, 1.0, 10.0, 0.0),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Align(
alignment:
const AlignmentDirectional(0.0, -0.29),
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
0.0, 40.0, 0.0, 0.0),
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment:
MainAxisAlignment.center,
crossAxisAlignment:
CrossAxisAlignment.center,
children: [
Align(
alignment: const AlignmentDirectional(
-0.94, -0.39),
child: FlutterFlowIconButton(
borderColor:
FlutterFlowTheme.of(context)
.accent1,
borderRadius: 20.0,
borderWidth: 2.0,
buttonSize: 40.0,
fillColor:
FlutterFlowTheme.of(context)
.accent1,
icon: Icon(
Icons.chevron_left,
color: FlutterFlowTheme.of(
context)
.primaryText,
size: 24.0,
),
onPressed: () async {
context.pushNamed(
'auth_2_Profile');
},
),
),
Text(
'TRACK APPLICATION',
style:
FlutterFlowTheme.of(context)
.headlineLarge
.override(
fontFamily: 'Outfit',
letterSpacing: 0.0,
),
),
],
),
),
),
],
),
),
),
],
),
].addToEnd(const SizedBox(height: 100.0)),
),
),
Align(
alignment: const AlignmentDirectional(0.0, -1.0),
child: Padding(
padding:
const EdgeInsetsDirectional.fromSTEB(0.0, 150.0, 0.0, 0.0),
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Align(
alignment: const AlignmentDirectional(0.0, 0.0),
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
0.0, 5.0, 0.0, 3.0),
child: StreamBuilder<JobCollectionRecord>(
stream: JobCollectionRecord.getDocument(
widget.jobCollectionRef!),
builder: (context, snapshot) {
// Customize what your widget looks like when it's loading.
if (!snapshot.hasData) {
return Center(
child: SizedBox(
width: 50.0,
height: 50.0,
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(
FlutterFlowTheme.of(context)
.primary,
),
),
),
);
}
final containerJobCollectionRecord =
snapshot.data!;
return Material(
color: Colors.transparent,
elevation: 10.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: Container(
width: 353.0,
height: 162.0,
decoration: BoxDecoration(
color: const Color(0x92210790),
boxShadow: [
BoxShadow(
blurRadius: 5.0,
color: FlutterFlowTheme.of(context)
.secondaryText,
offset: const Offset(
1.0,
1.0,
),
spreadRadius: 1.0,
)
],
borderRadius:
BorderRadius.circular(15.0),
border: Border.all(
color: const Color(0x92210790),
width: 1.0,
),
),
alignment: const AlignmentDirectional(0.0, 0.0),
child: Stack(
children: [
StreamBuilder<CompanyProfileRecord>(
stream: CompanyProfileRecord
.getDocument(
containerJobCollectionRecord
.companyRef!),
builder: (context, snapshot) {
// Customize what your widget looks like when it's loading.
if (!snapshot.hasData) {
return Center(
child: SizedBox(
width: 50.0,
height: 50.0,
child:
CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<
Color>(
FlutterFlowTheme.of(
context)
.primary,
),
),
),
);
}
final columnCompanyProfileRecord =
snapshot.data!;
return Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment:
MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.center,
children: [
Stack(
children: [
Align(
alignment:
const AlignmentDirectional(
-1.0, -1.0),
child: Padding(
padding:
const EdgeInsets.all(
10.0),
child: Row(
mainAxisSize:
MainAxisSize
.max,
mainAxisAlignment:
MainAxisAlignment
.start,
children: [
Align(
alignment:
const AlignmentDirectional(
-1.0,
-1.0),
child: Material(
color: Colors
.transparent,
elevation:
1.0,
shape:
RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(
15.0),
),
child:
Container(
width: 70.0,
height:
70.0,
decoration:
BoxDecoration(
color: FlutterFlowTheme.of(
context)
.secondaryBackground,
image:
DecorationImage(
fit: BoxFit
.cover,
image:
CachedNetworkImageProvider(
columnCompanyProfileRecord
.logoUrl,
),
),
borderRadius:
BorderRadius.circular(
15.0),
shape: BoxShape
.rectangle,
),
),
),
),
Align(
alignment:
const AlignmentDirectional(
-1.0,
0.0),
child: Padding(
padding: const EdgeInsetsDirectional
.fromSTEB(
15.0,
0.0,
0.0,
0.0),
child: Column(
mainAxisSize:
MainAxisSize
.max,
crossAxisAlignment:
CrossAxisAlignment
.start,
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
0.0,
0.0,
0.0,
10.0),
child:
Text(
containerJobCollectionRecord
.jName,
style: FlutterFlowTheme.of(context)
.bodyLarge
.override(
fontFamily: 'Readex Pro',
color: const Color(0xFFF7FAFC),
letterSpacing: 0.0,
fontWeight: FontWeight.w800,
),
),
),
Align(
alignment: const AlignmentDirectional(
-1.0,
0.0),
child: StreamBuilder<
CompanyProfileRecord>(
stream:
CompanyProfileRecord.getDocument(containerJobCollectionRecord.companyRef!),
builder:
(context, snapshot) {
// Customize what your widget looks like when it's loading.
if (!snapshot.hasData) {
return Center(
child: SizedBox(
width: 50.0,
height: 50.0,
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
FlutterFlowTheme.of(context).primary,
),
),
),
);
}
final textCompanyProfileRecord =
snapshot.data!;
return Text(
textCompanyProfileRecord.cName,
style: FlutterFlowTheme.of(context).bodyMedium.override(
fontFamily: 'Readex Pro',
color: const Color(0xFFF7FAFC),
letterSpacing: 0.0,
),
);
},
),
),
],
),
),
),
],
),
),
),
],
),
Padding(
padding:
const EdgeInsetsDirectional
.fromSTEB(10.0, 0.0,
10.0, 10.0),
child: Row(
mainAxisSize:
MainAxisSize.max,
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
Material(
color: Colors
.transparent,
elevation: 3.0,
shape:
RoundedRectangleBorder(
borderRadius:
BorderRadius
.circular(
15.0),
),
child: Container(
width: 90.0,
height: 38.0,
decoration:
BoxDecoration(
color: const Color(
0x8B3217A9),
borderRadius:
BorderRadius
.circular(
15.0),
border:
Border.all(
color: const Color(
0xFE3217A9),
width: 1.0,
),
),
child: Align(
alignment:
const AlignmentDirectional(
0.0, 0.0),
child: Text(
containerJobCollectionRecord
.jCategory,
style: FlutterFlowTheme.of(
context)
.bodyMedium
.override(
fontFamily:
'Readex Pro',
color: const Color(
0xFFF7FAFC),
letterSpacing:
0.0,
),
),
),
),
),
Material(
color: Colors
.transparent,
elevation: 3.0,
shape:
RoundedRectangleBorder(
borderRadius:
BorderRadius
.circular(
15.0),
),
child: Container(
width: 90.0,
height: 38.0,
decoration:
BoxDecoration(
color: const Color(
0x8B3217A9),
borderRadius:
BorderRadius
.circular(
15.0),
border:
Border.all(
color: const Color(
0xFE3217A9),
width: 1.0,
),
),
child: Align(
alignment:
const AlignmentDirectional(
0.0, 0.0),
child: Text(
containerJobCollectionRecord
.jType,
style: FlutterFlowTheme.of(
context)
.bodyMedium
.override(
fontFamily:
'Readex Pro',
color: const Color(
0xFFF7FAFC),
letterSpacing:
0.0,
),
),
),
),
),
Material(
color: Colors
.transparent,
elevation: 3.0,
shape:
RoundedRectangleBorder(
borderRadius:
BorderRadius
.circular(
15.0),
),
child: Container(
width: 90.0,
height: 38.0,
decoration:
BoxDecoration(
color: const Color(
0x8B3217A9),
borderRadius:
BorderRadius
.circular(
15.0),
border:
Border.all(
color: const Color(
0xFE3217A9),
width: 1.0,
),
),
child: Align(
alignment:
const AlignmentDirectional(
0.0, 0.0),
child: Text(
containerJobCollectionRecord
.jPosition,
style: FlutterFlowTheme.of(
context)
.bodyMedium
.override(
fontFamily:
'Readex Pro',
color: const Color(
0xFFF7FAFC),
letterSpacing:
0.0,
),
),
),
),
),
].divide(const SizedBox(
width: 10.0)),
),
),
Padding(
padding:
const EdgeInsetsDirectional
.fromSTEB(15.0, 0.0,
15.0, 0.0),
child: Row(
mainAxisSize:
MainAxisSize.max,
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
Align(
alignment:
const AlignmentDirectional(
-1.0, 0.0),
child: Text(
containerJobCollectionRecord
.location,
style: FlutterFlowTheme
.of(context)
.bodyMedium
.override(
fontFamily:
'Readex Pro',
color: const Color(
0xFFF7FAFC),
fontSize:
12.0,
letterSpacing:
0.0,
fontWeight:
FontWeight
.w600,
),
),
),
Align(
alignment:
const AlignmentDirectional(
-1.0, 0.0),
child: Text(
'PKR ${containerJobCollectionRecord.jSalary.toString()} /yr',
style: FlutterFlowTheme
.of(context)
.bodyMedium
.override(
fontFamily:
'Readex Pro',
color: const Color(
0xFFF7FAFC),
fontSize:
12.0,
letterSpacing:
0.0,
fontWeight:
FontWeight
.w600,
),
),
),
].divide(const SizedBox(
width: 10.0)),
),
),
],
);
},
),
],
),
),
).animateOnPageLoad(animationsMap[
'containerOnPageLoadAnimation']!);
},
),
),
),
Align(
alignment: const AlignmentDirectional(-1.0, 0.0),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
'APPLICATION STATUS',
style: FlutterFlowTheme.of(context)
.bodyLarge
.override(
fontFamily: 'Readex Pro',
letterSpacing: 0.0,
fontWeight: FontWeight.w800,
),
),
),
),
Expanded(
child: StreamBuilder<List<TrackDataRecord>>(
stream: queryTrackDataRecord(
queryBuilder: (trackDataRecord) =>
trackDataRecord
.where(
'ref',
isEqualTo: widget.appliedJobRef,
)
.where(
'user_ref',
isEqualTo:
trackApplicationAppliedJobRecord
.userRef,
),
),
builder: (context, snapshot) {
// Customize what your widget looks like when it's loading.
if (!snapshot.hasData) {
return Center(
child: SizedBox(
width: 50.0,
height: 50.0,
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(
FlutterFlowTheme.of(context).primary,
),
),
),
);
}
List<TrackDataRecord>
columnTrackDataRecordList = snapshot.data!;
return Column(
mainAxisSize: MainAxisSize.max,
children: List.generate(
columnTrackDataRecordList.length,
(columnIndex) {
final columnTrackDataRecord =
columnTrackDataRecordList[columnIndex];
return Column(
mainAxisSize: MainAxisSize.max,
children: [
Padding(
padding:
const EdgeInsetsDirectional.fromSTEB(
13.0, 10.0, 10.0, 0.0),
child: Row(
mainAxisSize: MainAxisSize.max,
children: [
const SizedBox(
height: 30.0,
child: VerticalDivider(
thickness: 3.0,
color: Color(0xFE3217A9),
),
),
Expanded(
child: Padding(
padding: const EdgeInsetsDirectional
.fromSTEB(
20.0, 0.0, 0.0, 0.0),
child: Text(
columnTrackDataRecord
.updateMessage,
style: FlutterFlowTheme.of(
context)
.bodyLarge
.override(
fontFamily:
'Readex Pro',
letterSpacing: 0.0,
fontWeight:
FontWeight.bold,
),
),
),
),
],
),
),
Builder(
builder: (context) {
if (columnTrackDataRecord
.isAccepted) {
return const Align(
alignment: AlignmentDirectional(
-1.0, 0.0),
child: Padding(
padding: EdgeInsetsDirectional
.fromSTEB(
8.0, 0.0, 0.0, 0.0),
child: Icon(
Icons.offline_pin,
color: Color(0xFF0FDE0F),
size: 30.0,
),
),
);
} else if (columnTrackDataRecord
.isUnderReview) {
return const Align(
alignment: AlignmentDirectional(
-1.0, 0.0),
child: Padding(
padding: EdgeInsetsDirectional
.fromSTEB(
7.0, 0.0, 0.0, 0.0),
child: Icon(
Icons
.remove_red_eye_rounded,
color: Color(0xFB210790),
size: 30.0,
),
),
);
} else {
return const Align(
alignment: AlignmentDirectional(
-1.0, 0.0),
child: Padding(
padding: EdgeInsetsDirectional
.fromSTEB(
7.0, 0.0, 0.0, 0.0),
child: Icon(
Icons.close_sharp,
color: Color(0xFFFF0509),
size: 30.0,
),
),
);
}
},
),
Padding(
padding:
const EdgeInsetsDirectional.fromSTEB(
13.0, 0.0, 10.0, 0.0),
child: Row(
mainAxisSize: MainAxisSize.max,
children: [
const SizedBox(
height: 30.0,
child: VerticalDivider(
thickness: 3.0,
color: Color(0xFE3217A9),
),
),
Expanded(
child: Padding(
padding: const EdgeInsetsDirectional
.fromSTEB(
20.0, 0.0, 0.0, 0.0),
child: Text(
dateTimeFormat(
'MMMMEEEEd',
columnTrackDataRecord
.time!),
style: FlutterFlowTheme.of(
context)
.bodyMedium
.override(
fontFamily:
'Readex Pro',
letterSpacing: 0.0,
),
),
),
),
],
),
),
],
);
}).divide(const SizedBox(height: 0.0)),
);
},
),
),
].divide(const SizedBox(height: 10.0)),
),
),
),
],
),
),
),
);
},
);
}
} |
import {Button, Card, CardFooter, CardHeader, Image} from '@nextui-org/react'
import React from 'react'
import Student from '../static-images/student-signup.jpg';
import Teacher from '../assets/teacher.png';
import Recruiter from '../assets/recruiter.jpeg';
import BackgroundImage from '../assets/welcomeBackground.svg';
import {PiStudentFill} from "react-icons/pi";
import {LiaChalkboardTeacherSolid} from "react-icons/lia";
import {MdWork} from "react-icons/md";
import {useNavigate} from "react-router-dom";
export default function Welcome() {
const navigate = useNavigate();
return (
<div className="min-h-screen w-screen relative bg-purple-950 overflow-y-auto">
<img src={BackgroundImage} alt="Background Image"
className="w-full h-full absolute top-0 left-0 object-cover opacity-50"/>
<div
className="w-full h-full p-20 flex flex-col lg:flex-row justify-items-center justify-center gap-4">
<Card isFooterBlurred className="h-[300px] col-span-12 sm:col-span-7 flex-1">
<CardHeader className="absolute z-10 top-1 flex-col items-start">
<p className="text-tiny text-white/60 uppercase font-bold">STUDENT</p>
<h4 className="text-white/90 font-medium text-xl">Start learning</h4>
</CardHeader>
<Image
removeWrapper
alt="Relaxing app background"
className="z-0 w-full h-full object-cover"
src={Student}
style={{
filter: 'brightness(0.5)'
}}
/>
<CardFooter
className="absolute bg-black/40 bottom-0 z-10 border-t-1 border-default-600 dark:border-default-100">
<div className="flex flex-grow gap-2 items-center">
<PiStudentFill
className="w-10 h-11"
/>
<div className="flex flex-col">
<p className="text-tiny text-white/60"> Take courses and quiz yourself</p>
</div>
</div>
<Button color="primary" radius="full" size="sm" onClick={() => navigate('/signup/student')}>Become
a Student</Button>
</CardFooter>
</Card>
<Card isFooterBlurred className="h-[300px] col-span-12 sm:col-span-7 flex-1">
<CardHeader className="absolute z-10 top-1 flex-col items-start">
<p className="text-tiny text-white/60 uppercase font-bold">TEACHER</p>
<h4 className="text-white/90 font-medium text-xl">Start teaching</h4>
</CardHeader>
<Image
removeWrapper
alt="Relaxing app background"
className="z-0 w-full h-full object-cover"
src={Teacher}
style={{
filter: 'brightness(0.5)'
}}
/>
<CardFooter
className="absolute bg-black/40 bottom-0 z-10 border-t-1 border-default-600 dark:border-default-100">
<div className="flex flex-grow gap-2 items-center">
<LiaChalkboardTeacherSolid
className="w-10 h-11"
/>
<div className="flex flex-col">
<p className="text-tiny text-white/60">Post courses and quiz students</p>
</div>
</div>
<Button color="primary" radius="full" size="sm" onClick={() => navigate('/signup/teacher')}>Become
a Teacher</Button>
</CardFooter>
</Card>
<Card isFooterBlurred className="h-[300px] col-span-12 sm:col-span-7 flex-1">
<CardHeader className="absolute z-10 top-1 flex-col items-start">
<p className="text-tiny text-white/60 uppercase font-bold">RECRUITER</p>
<h4 className="text-white/90 font-medium text-xl">Start recruiting</h4>
</CardHeader>
<Image
removeWrapper
alt="Relaxing app background"
className="z-0 w-full h-full object-cover"
src={Recruiter}
style={{
filter: 'brightness(0.5)'
}}
/>
<CardFooter
className="absolute bg-black/40 bottom-0 z-10 border-t-1 border-default-600 dark:border-default-100">
<div className="flex flex-grow gap-2 items-center">
<MdWork
className="w-10 h-11"
/>
<div className="flex flex-col">
<p className="text-tiny text-white/60">Find the best candidates</p>
</div>
</div>
<Button color="primary" radius="full" size="sm" onClick={() => navigate('/signup/recruiter')}>Become
a Recruiter</Button>
</CardFooter>
</Card>
</div>
</div>
)
} |
package io.unitycatalog.server.base.table;
import io.unitycatalog.client.ApiException;
import io.unitycatalog.client.model.*;
import io.unitycatalog.server.base.BaseCRUDTest;
import io.unitycatalog.server.base.ServerConfig;
import io.unitycatalog.server.base.schema.SchemaOperations;
import io.unitycatalog.server.persist.FileUtils;
import io.unitycatalog.server.persist.HibernateUtil;
import io.unitycatalog.server.persist.dao.ColumnInfoDAO;
import io.unitycatalog.server.persist.dao.TableInfoDAO;
import io.unitycatalog.server.utils.TestUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.*;
import java.io.IOException;
import java.util.*;
import static org.junit.Assert.*;
public abstract class BaseTableCRUDTest extends BaseCRUDTest {
protected SchemaOperations schemaOperations;
protected TableOperations tableOperations;
protected static final Map<String, String> PROPERTIES = Map.of("prop1", "value1", "prop2", "value2");
protected static final String TABLE_NAME = "uc_test_table";
protected static final String TABLE_FULL_NAME = TestUtils.CATALOG_NAME + "." + TestUtils.SCHEMA_NAME + "." + TABLE_NAME;
private String schemaId = null;
@Before
public void setUp() {
super.setUp();
schemaOperations = createSchemaOperations(serverConfig);
tableOperations = createTableOperations(serverConfig);
cleanUp();
}
protected abstract SchemaOperations createSchemaOperations(ServerConfig serverConfig);
protected abstract TableOperations createTableOperations(ServerConfig serverConfig);
protected void cleanUp() {
try {
if (tableOperations.getTable(TABLE_FULL_NAME) != null) {
tableOperations.deleteTable(TABLE_FULL_NAME);
}
} catch (Exception e) {
// Ignore
}
try {
if (schemaOperations.getSchema(TestUtils.SCHEMA_FULL_NAME) != null) {
schemaOperations.deleteSchema(TestUtils.SCHEMA_FULL_NAME);
}
} catch (Exception e) {
// Ignore
}
super.cleanUp();
}
protected void createCommonResources() throws ApiException {
// Common setup operations such as creating a catalog and schema
catalogOperations.createCatalog(TestUtils.CATALOG_NAME, "Common catalog for tables");
SchemaInfo schemaInfo = schemaOperations.createSchema(new CreateSchema().name(TestUtils.SCHEMA_NAME).catalogName(TestUtils.CATALOG_NAME));
schemaId = schemaInfo.getSchemaId();
}
@Test
public void testTableCRUD() throws IOException, ApiException {
Assert.assertThrows(Exception.class, () -> tableOperations.getTable(TABLE_FULL_NAME));
createCommonResources();
// Create a table
System.out.println("Testing create table..");
ColumnInfo columnInfo1 = new ColumnInfo().name("as_int").typeText("INTEGER")
.typeJson("{\"type\": \"integer\"}")
.typeName(ColumnTypeName.INT).typePrecision(10).typeScale(0).position(0)
.comment("Integer column").nullable(true);
ColumnInfo columnInfo2 = new ColumnInfo().name("as_string").typeText("VARCHAR(255)")
.typeJson("{\"type\": \"string\", \"length\": \"255\"}")
.typeName(ColumnTypeName.STRING).position(1)
.comment("String column").nullable(true);
CreateTable createTableRequest = new CreateTable()
.name(TABLE_NAME)
.catalogName(TestUtils.CATALOG_NAME)
.schemaName(TestUtils.SCHEMA_NAME)
.columns(List.of(columnInfo1, columnInfo2))
.properties(PROPERTIES)
.comment(TestUtils.COMMENT)
.storageLocation("/tmp/stagingLocation")
.tableType(TableType.EXTERNAL)
.dataSourceFormat(DataSourceFormat.DELTA);
TableInfo tableInfo = tableOperations.createTable(createTableRequest);
assertEquals(TABLE_NAME, tableInfo.getName());
Assert.assertEquals(TestUtils.CATALOG_NAME, tableInfo.getCatalogName());
Assert.assertEquals(TestUtils.SCHEMA_NAME, tableInfo.getSchemaName());
assertNotNull(tableInfo.getTableId());
// Get table
System.out.println("Testing get table..");
TableInfo tableInfo2 = tableOperations.getTable(TABLE_FULL_NAME);
assertEquals(TABLE_NAME, tableInfo2.getName());
Assert.assertEquals(TestUtils.CATALOG_NAME, tableInfo2.getCatalogName());
Assert.assertEquals(TestUtils.SCHEMA_NAME, tableInfo2.getSchemaName());
Assert.assertEquals(FileUtils.convertRelativePathToURI("/tmp/stagingLocation"), tableInfo2.getStorageLocation());
Assert.assertEquals(TableType.EXTERNAL, tableInfo2.getTableType());
Assert.assertEquals(DataSourceFormat.DELTA, tableInfo2.getDataSourceFormat());
assertNotNull(tableInfo2.getCreatedAt());
assertNotNull(tableInfo2.getTableId());
Collection<ColumnInfo> columnInfos2 = tableInfo2.getColumns();
assertEquals(2, columnInfos2.size());
assertEquals(1, columnInfos2.stream().filter(c -> c.getName().equals("as_int")).count());
assertEquals(1, columnInfos2.stream().filter(c -> c.getName().equals("as_string")).count());
// List tables
System.out.println("Testing list tables..");
Iterable<TableInfo> tableInfos = tableOperations.listTables(TestUtils.CATALOG_NAME, TestUtils.SCHEMA_NAME);
assertTrue(TestUtils.contains(tableInfos, tableInfo2, (table) -> {
assertNotNull(table.getName());
return table.getName().equals(TABLE_NAME) && table.getSchemaName().equals(TestUtils.SCHEMA_NAME)
&& table.getCatalogName().equals(TestUtils.CATALOG_NAME) /*&& table.getComment().equals(COMMENT)*/
&& table.getColumns().stream().anyMatch(c -> c.getName().equals("as_int"))
&& table.getColumns().stream().anyMatch(c -> c.getName().equals("as_string"));
}));
// Delete table
System.out.println("Testing delete table..");
tableOperations.deleteTable(TABLE_FULL_NAME);
assertThrows(Exception.class, () -> tableOperations.getTable(TABLE_FULL_NAME));
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
Transaction tx = session.beginTransaction();
UUID tableId = UUID.randomUUID();
TableInfoDAO managedTableInfo = TableInfoDAO.builder()
.name( TABLE_NAME)
.schemaId(UUID.fromString(schemaId))
.comment(TestUtils.COMMENT)
.url("/tmp/managedStagingLocation")
.type(TableType.MANAGED.name())
.dataSourceFormat(DataSourceFormat.DELTA.name())
.id(tableId)
.createdAt(new Date())
.updatedAt(new Date())
.build();
ColumnInfoDAO columnInfoDAO1 = ColumnInfoDAO.builder()
.name("as_int")
.typeText("INTEGER")
.typeJson("{\"type\": \"integer\"}")
.typeName(ColumnTypeName.INT.name())
.typePrecision(10)
.typeScale(0)
.ordinalPosition((short)0)
.comment("Integer column")
.nullable(true)
.tableId(managedTableInfo)
.build();
ColumnInfoDAO columnInfoDAO2 = ColumnInfoDAO.builder()
.name("as_string")
.typeText("VARCHAR(255)")
.typeJson("{\"type\": \"string\", \"length\": \"255\"}")
.typeName(ColumnTypeName.STRING.name())
.ordinalPosition((short)1)
.comment("String column")
.nullable(true)
.tableId(managedTableInfo)
.build();
managedTableInfo.setColumns(List.of(columnInfoDAO1, columnInfoDAO2));
session.persist(managedTableInfo);
session.flush();
tx.commit();
} catch (Exception e) {
fail(e.getMessage());
}
System.out.println("Testing get managed table..");
TableInfo managedTable = tableOperations.getTable(TABLE_FULL_NAME);
assertEquals(TABLE_NAME, managedTable.getName());
Assert.assertEquals(TestUtils.CATALOG_NAME, managedTable.getCatalogName());
Assert.assertEquals(TestUtils.SCHEMA_NAME, managedTable.getSchemaName());
Assert.assertEquals(FileUtils.convertRelativePathToURI("/tmp/managedStagingLocation"), managedTable.getStorageLocation());
Assert.assertEquals(TableType.MANAGED, managedTable.getTableType());
Assert.assertEquals(DataSourceFormat.DELTA, managedTable.getDataSourceFormat());
assertNotNull(managedTable.getCreatedAt());
assertNotNull(managedTable.getTableId());
System.out.println("Testing list managed tables..");
List<TableInfo> managedTables = tableOperations.listTables(TestUtils.CATALOG_NAME, TestUtils.SCHEMA_NAME);
TableInfo managedListTable = managedTables.get(0);
assertEquals(TABLE_NAME, managedListTable.getName());
Assert.assertEquals(TestUtils.CATALOG_NAME, managedListTable.getCatalogName());
Assert.assertEquals(TestUtils.SCHEMA_NAME, managedListTable.getSchemaName());
Assert.assertEquals(FileUtils.convertRelativePathToURI("/tmp/managedStagingLocation"), managedListTable.getStorageLocation());
Assert.assertEquals(TableType.MANAGED, managedListTable.getTableType());
Assert.assertEquals(DataSourceFormat.DELTA, managedListTable.getDataSourceFormat());
assertNotNull(managedListTable.getCreatedAt());
assertNotNull(managedListTable.getTableId());
// Delete managed table
System.out.println("Testing delete table..");
tableOperations.deleteTable(TABLE_FULL_NAME);
assertThrows(Exception.class, () -> tableOperations.getTable(TABLE_FULL_NAME));
}
} |
<!--
@component
@param {number} [lines=1] - Lines property, Default: `1`
@param {string} [width="100%"] - CSS string denoting width of the Skeleton
**Examples:** `10px` | `5rem` | `100vh`, Default: `"100%"`
@param {string} [height="auto"] - CSS string denoting height of the Skeleton
**Examples:** `10px` | `5rem` | `100vh` | `auto`, Default: `"auto"`
@param {string} [radius="0px"] - CSS string denoting border-radius of the Skeleton
**Examples:** `10px` | `5rem`, Default: `"0px"`
@param {boolean} [circle=false] - Whether the Skeleton should be rendered as a circle.
If this is set to `true`, the `radius` property will be ignored., Default: `false`
@param {ColorOptions} [color=] - Color of the Skeleton lines, Default: ``
@param {string} [class=""] - CSS class for Skeleton, Default: `""`
-->
<!-- eslint-disable-next-line no-unused-vars -->
{#each { length: lines } as _, i}
<span
class="kws-skeleton is-{color} {klass}"
style="width:{width};height:{height};border-radius:{border_radius}">
‌
</span>
{/each}
<script>
/**
* @typedef {import('@kws3/ui/types').ColorOptions} ColorOptions
*/
export let /**
* Number of lines of text to display.
*/
lines = 1,
/**
* CSS string denoting width of the Skeleton
* **Examples:** `10px` | `5rem` | `100vh`
*/
width = "100%",
/**
* CSS string denoting height of the Skeleton
* **Examples:** `10px` | `5rem` | `100vh` | `auto`
*/
height = "auto",
/**
* CSS string denoting border-radius of the Skeleton
* **Examples:** `10px` | `5rem`
*/
radius = "0px",
/**
* Whether the Skeleton should be rendered as a circle.
* If this is set to `true`, the `radius` property will be ignored.
*/
circle = false,
/**
* Color of the Skeleton lines
* @type {ColorOptions}
*/
color = "";
/**
* CSS class for Skeleton
* @type {string}
*/
let klass = "";
export { klass as class };
$: border_radius = circle ? "50%" : radius;
</script> |
/*
* Copyright (c) 2004-2022, University of Oslo
* 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 name of the HISP project 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 THE COPYRIGHT OWNER 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.
*/
package org.nmcpye.am.tracker;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.nmcpye.am.activity.Activity;
import org.nmcpye.am.comment.Comment;
import org.nmcpye.am.dataelement.DataElement;
import org.nmcpye.am.organisationunit.OrganisationUnit;
import org.nmcpye.am.program.Program;
import org.nmcpye.am.program.ProgramStage;
import org.nmcpye.am.programrule.ProgramRule;
import org.nmcpye.am.programrule.ProgramRuleService;
import org.nmcpye.am.relationship.RelationshipType;
import org.nmcpye.am.trackedentity.TrackedEntityAttribute;
import org.nmcpye.am.trackedentity.TrackedEntityType;
import org.nmcpye.am.tracker.domain.*;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.stream.Collectors;
/**
* NMCP Extended
* This class "collects" identifiers from all input objects. This resulting map
* of all identifiers will then be used to "preheat/cache" all the objects
* needed into memory to speed up the validation process.
* <p>
* The metadata identifiers can be of different idSchemes as specified by the
* user on import.
*
* @author Morten Olav Hansen <mortenoh@gmail.com>
* @see org.nmcpye.am.tracker.preheat.DefaultTrackerPreheatService
*/
@Component
@RequiredArgsConstructor
public class TrackerIdentifierCollector {
private final ProgramRuleService programRuleService;
public Map<Class<?>, Set<String>> collect(TrackerImportParams params) {
final Map<Class<?>, Set<String>> identifiers = new HashMap<>();
collectTrackedEntities(identifiers, params.getTrackedEntities());
collectEnrollments(identifiers, params.getEnrollments());
collectEvents(identifiers, params.getEvents());
collectRelationships(identifiers, params.getRelationships());
collectProgramRulesFields(identifiers);
return identifiers;
}
private void collectProgramRulesFields(Map<Class<?>, Set<String>> map) {
// collecting program rule dataElement/attributes deliberately using
// UIDs
// Rule engine rules only know UIDs, so we need to be able to get
// dataElements/attributes from rule actions
// out of the preheat using UIDs
List<ProgramRule> programRules = programRuleService.getProgramRulesLinkedToTeaOrDe();
Set<String> dataElements = programRules.stream()
.flatMap(pr -> pr.getProgramRuleActions().stream())
.filter(a -> Objects.nonNull(a.getDataElement()))
.map(a -> a.getDataElement().getUid())
.collect(Collectors.toSet());
dataElements.forEach(de -> addIdentifier(map, DataElement.class, de));
Set<String> attributes = programRules.stream()
.flatMap(pr -> pr.getProgramRuleActions().stream())
.filter(a -> Objects.nonNull(a.getAttribute()))
.map(a -> a.getAttribute().getUid())
.collect(Collectors.toSet());
attributes.forEach(attribute -> addIdentifier(map, TrackedEntityAttribute.class, attribute));
}
private void collectTrackedEntities(Map<Class<?>, Set<String>> identifiers, List<TrackedEntity> trackedEntities) {
trackedEntities.forEach(trackedEntity -> {
addIdentifier(identifiers, TrackedEntity.class, trackedEntity.getTrackedEntity());
addIdentifier(identifiers, TrackedEntityType.class, trackedEntity.getTrackedEntityType());
addIdentifier(identifiers, OrganisationUnit.class, trackedEntity.getOrgUnit());
collectEnrollments(identifiers, trackedEntity.getEnrollments());
trackedEntity.getAttributes()
.forEach(attribute -> addIdentifier(identifiers, TrackedEntityAttribute.class,
attribute.getAttribute()));
});
}
private void collectEnrollments(Map<Class<?>, Set<String>> identifiers, List<Enrollment> enrollments) {
enrollments.forEach(enrollment -> {
addIdentifier(identifiers, TrackedEntity.class, enrollment.getTrackedEntity());
addIdentifier(identifiers, Enrollment.class, enrollment.getEnrollment());
addIdentifier(identifiers, Program.class, enrollment.getProgram());
addIdentifier(identifiers, OrganisationUnit.class, enrollment.getOrgUnit());
// NMCP
addIdentifier(identifiers, Activity.class, enrollment.getActivity());
collectNotes(identifiers, enrollment.getNotes());
collectEvents(identifiers, enrollment.getEvents());
enrollment.getAttributes().forEach(attribute -> addIdentifier(identifiers, TrackedEntityAttribute.class,
attribute.getAttribute()));
});
}
private void collectNotes(Map<Class<?>, Set<String>> identifiers, List<Note> notes) {
notes.forEach(
note -> {
if (!StringUtils.isEmpty(note.getNote()) && !StringUtils.isEmpty(note.getValue())) {
addIdentifier(identifiers, Comment.class, note.getNote());
}
});
}
private void collectEvents(Map<Class<?>, Set<String>> identifiers, List<Event> events) {
events.forEach(event -> {
addIdentifier(identifiers, Enrollment.class, event.getEnrollment());
addIdentifier(identifiers, Event.class, event.getEvent());
addIdentifier(identifiers, Program.class, event.getProgram());
addIdentifier(identifiers, ProgramStage.class, event.getProgramStage());
addIdentifier(identifiers, OrganisationUnit.class, event.getOrgUnit());
// NMCP
addIdentifier(identifiers, Activity.class, event.getActivity());
// event.getAttributeCategoryOptions()
// .forEach(s -> addIdentifier(identifiers, CategoryOption.class, s));
//
// addIdentifier(identifiers, CategoryOptionCombo.class, event.getAttributeOptionCombo());
event.getDataValues()
.forEach(dv -> addIdentifier(identifiers, DataElement.class, dv.getDataElement()));
collectNotes(identifiers, event.getNotes());
});
}
private void collectRelationships(Map<Class<?>, Set<String>> identifiers, List<Relationship> relationships) {
relationships.forEach(relationship -> {
addIdentifier(identifiers, Relationship.class, relationship.getRelationship());
addIdentifier(identifiers, RelationshipType.class, relationship.getRelationshipType());
if (Objects.nonNull(relationship.getFrom())) {
addIdentifier(identifiers, TrackedEntity.class, relationship.getFrom().getTrackedEntity());
addIdentifier(identifiers, Enrollment.class, relationship.getFrom().getEnrollment());
addIdentifier(identifiers, Event.class, relationship.getFrom().getEvent());
}
if (Objects.nonNull(relationship.getTo())) {
addIdentifier(identifiers, TrackedEntity.class, relationship.getTo().getTrackedEntity());
addIdentifier(identifiers, Enrollment.class, relationship.getTo().getEnrollment());
addIdentifier(identifiers, Event.class, relationship.getTo().getEvent());
}
});
}
private <T> void addIdentifier(Map<Class<?>, Set<String>> identifiers, Class<T> klass,
MetadataIdentifier identifier) {
addIdentifier(identifiers, klass, identifier == null ? null : identifier.getIdentifierOrAttributeValue());
}
private <T> void addIdentifier(Map<Class<?>, Set<String>> identifiers, Class<T> klass, String identifier) {
if (StringUtils.isEmpty(identifier) || identifiers == null || klass == null) {
return;
}
identifiers
.computeIfAbsent(klass, k -> new HashSet<>())
.add(identifier);
}
} |
import { REPLY_OWNER_CONTEXT_ERROR } from "../../../commons/constants/domains/replies/reply-owner-context-error";
import { ReplyOwnerContext } from "./reply-owner.context";
describe("ReplyOwnerContext entities", () => {
it("should be able to create the replyOwnerContext object correctly", () => {
const payload = {
id: "reply-123",
owner: "user-123",
};
const { id, owner } = new ReplyOwnerContext(payload);
expect(id).toEqual(payload.id);
expect(owner).toEqual(payload.owner);
});
it("should throw an error if there is a missing property", () => {
const payload = {};
expect(() => new ReplyOwnerContext(payload)).toThrow(
REPLY_OWNER_CONTEXT_ERROR.MISSING_PROPERTY
);
});
it("should throw an error if there is a property with invalid an data type", () => {
const payload = {
id: 123,
};
expect(() => new ReplyOwnerContext(payload)).toThrow(
REPLY_OWNER_CONTEXT_ERROR.INVALID_DATA_TYPE
);
});
}); |
#ifndef BOOK_H_
#define BOOK_H_
#include <string>
using namespace std;
/***** Complete this file. *****/
/**
* The Book class.
*/
class Book
{
public:
/**
* Book categories.
*/
enum class Category { FICTION, HISTORY, TECHNICAL, NONE };
/**
* Default constructor.
*/
Book();
/**
* Constructor.
*/
Book(string isbn, string last, string first, string title, string category);
/**
* Destructor.
*/
~Book();
const string& getFirst() const;
void setFirst(const string& first);
const string& getIsbn() const;
void setIsbn(const string& isbn);
const string& getLast() const;
void setLast(const string& last);
const string& getTitle() const;
void setTitle(const string& title);
const string& getCategory() const;
void setCategory(const string& category);
/***** Complete the public members. *****/
private:
string isbn, last, first, title;
string category;
/***** Complete the private members. *****/
//operator over loading
friend ostream& operator <<(ostream& out, Book& a );
friend istream& operator >>(istream& out, Book& a );
};
#endif /* EMPLOYEE_H_ */ |
#############################################
# IUCN Status Category and Population Trend #
#############################################
library(rredlist)
library(tidyverse)
#####################################
# FUNCTION
retrieve_IUCN_data <- function(speciesList){
IUCN_status <- data.frame(Species = character(), Status = character(),
Trend = character(), stringsAsFactors=FALSE)
for(sp in speciesList){
UICN_search <- rl_search(name = sp)
if (length(UICN_search$result) == 0){
IUCN_status_sp <- data.frame(Species = sp,
Status = 'NA',
Trend = 'NA', stringsAsFactors=FALSE)
IUCN_status <- rbind(IUCN_status, IUCN_status_sp)
cat(sp,'----- CHECK\n')
}
else {
IUCN_status_sp <- data.frame(Species = UICN_search$result$scientific_name,
Status = UICN_search$result$category,
Trend = UICN_search$result$population_trend, stringsAsFactors=FALSE)
IUCN_status <- rbind(IUCN_status, IUCN_status_sp)
}
}
return(IUCN_status)
}
#####################################
# RUN
# 1) Species List
canids <- c('Cerdocyon thous', 'Lycalopex gymnocercus', 'Chrysocyon brachyurus', 'AnyWrong species')
canids_IUCN_data <- retrieve_IUCN_data(canids)
## The fuction will print in console
# AnyWrong species ----- CHECK
canids_IUCN_data
# Species Status Trend
# 1 Cerdocyon thous LC Stable
# 2 Lycalopex gymnocercus LC Stable
# 3 Chrysocyon brachyurus NT Unknown
# 4 AnyWrong species NA NA
# 2) Data from table
mammals <- read_csv('speciesList.csv')
mammlas_IUCN_data <- retrieve_IUCN_data(mammals$Species)
## The fuction will print in console
# Leopardus braccatus ----- CHECK
# Puma yagouaroundi ----- CHECK
# No species ----- CHECK
mammlas_IUCN_data
# Species Status Trend
# 1 Mazama gouazoubira LC Decreasing
# 2 Axis axis LC Unknown
# 3 Sus scrofa LC Unknown
# 4 Cerdocyon thous LC Stable
# 5 Chrysocyon brachyurus NT Unknown
# 6 Lycalopex gymnocercus LC Stable
# 7 Leopardus wiedii NT Decreasing
# 8 Leopardus braccatus NA NA
# 9 Leopardus geoffroyi LC Stable
# 10 Puma yagouaroundi NA NA
# 11 Lontra longicaudis NT Decreasing
# 12 Conepatus chinga LC Decreasing
# 13 Galictis cuja LC Unknown
# 14 Procyon cancrivorus LC Decreasing
# 15 Dasypus novemcinctus LC Stable
# 16 Euphractus sexcinctus LC Stable
# 17 Cabassous tatouay LC Unknown
# 18 Didelphis albiventris LC Stable
# 19 Lepus europaeus LC Decreasing
# 20 Cuniculus paca LC Stable
# 21 No species NA NA
# 22 Hydrochoerus hydrochaeris LC Stable
# 23 Tamandua tetradactyla LC Unknown |
<div
x-data="imagesPicker()"
x-init="handleInit"
x-ref="imagesPicker"
class="images-picker"
>
<input
x-ref="inputFile"
class="images-picker__input"
type="file"
name="{{$name ?? 'files'}}[]"
accept="image/*"
multiple
x-on:change="handleChange"
/>
<div class="images-picker__add-btn" x-on:click="$refs.inputFile.click()">
<i class="ti-plus"></i>
</div>
<template x-for="(image, index) in images">
<div class="images-picker__image">
<img x-bind:src="URL.createObjectURL(image)" alt="">
<button type="button" x-on:click="handleDelete(index)">×</button>
</div>
</template>
<template x-for="image in currentImages">
<div class="images-picker__image">
<img x-bind:src="image.path" alt="">
<button type="button" x-on:click="handleDeleteCurrentImg(image)">×</button>
</div>
</template>
</div>
@once
@push('scriptsBeforeApp')
<script>
const imagesPicker = () => ({
currentImages: [],
images: [],
dataTransfer: new DataTransfer(),
handleInit() {
this.currentImages = @json($currentImages);
},
handleChange(e) {
for (let file of e.target.files) {
this.dataTransfer.items.add(file);
this.images.push(file);
};
e.target.files = this.dataTransfer.files;
},
async handleDelete(index) {
swal({
title: '¿Está seguro?',
text: 'No podrá revertir esta acción',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#e6b034',
confirmButtonText: 'Si, eliminarla!',
}, () => {
this.dataTransfer.items.remove(index);
this.images.splice(index, 1);
this.$refs.inputFile.files = this.dataTransfer.files;
});
},
async handleDeleteCurrentImg(image) {
const urlToDelete = @json($urlToDelete);
const urlToDeleteIdPlaceholder = @json($urlToDeleteIdPlaceholder);
const finalUrl = urlToDelete.replace(urlToDeleteIdPlaceholder, image.id);
swal({
title: '¿Está seguro?',
text: 'No podrá revertir esta acción',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#e6b034',
confirmButtonText: 'Si, eliminarla!',
}, async () => {
await axios.delete(finalUrl);
this.currentImages = this.currentImages.filter((_image) => _image.id !== image.id);
});
}
});
</script>
@endpush
@endonce |
import React from 'react';
import { CloseButton } from '../../CloseButton';
import { FeedbackType, feedbackTypes } from '..';
import { ArrowLeft, Camera } from 'phosphor-react';
import { ScreenshotButton } from '../ScreenshotButton';
import { api } from '../../../lib/api';
import { Loading } from '../../Loading';
interface FeedbackContentStepProps {
feedbackType: FeedbackType;
onFeedbackRestartRequested: () => void;
onFeedbackSent: () => void;
}
export function FeedbackContentStep(
{
feedbackType,
onFeedbackRestartRequested,
onFeedbackSent,
}: FeedbackContentStepProps) {
const feedbackTypeInfo = feedbackTypes[feedbackType];
const [screenshot, setScreenshot] = React.useState<string | null>(null);
const [comment, setComment] = React.useState('');
const [isSendingFeedback, setIsSendingFeedback] = React.useState(false);
async function handleSubmitFeedback(event: React.FormEvent) {
event.preventDefault();
setIsSendingFeedback(true);
await api.post('feedbacks', {
type: feedbackTypeInfo.title,
screenshot,
comment
});
setIsSendingFeedback(false);
onFeedbackSent();
}
return (
<>
<header>
<button
type="button"
className="top-5 left-5 absolute text-zinc-400 hover:text-zinc-100"
onClick={() => onFeedbackRestartRequested()}
>
<ArrowLeft weight="bold" className="w-4 h-4"/>
</button>
<span className="text-xl leading-6 flex items-center gap-2">
<img className="w-6 h-6" src={feedbackTypeInfo.image.source} alt={feedbackTypeInfo.image.alt} />
{feedbackTypeInfo.title}
</span>
<CloseButton/>
</header>
<form className="my-4 w-full" onSubmit={handleSubmitFeedback}>
<textarea
onChange={(event) => setComment(event.target.value)}
className="min-w-[304px] w-full min-h-[112px] text-sm placeholder-zinc-400 text-zinc-100 border-zinc-600 bg-transparent rounded-md focus:border-brand-500 focus:ring-brand-500 focus:ring-1 resize-none focus:outline-none scrollbar scrollbar-thumb-zinc-600 scrollbar-thin"
placeholder="Conte com detalhes o que está acontecendo"
>
</textarea>
<footer className="flex gap-2 mt-2">
<ScreenshotButton onScreenshotTook={setScreenshot} screenshot={screenshot}/>
<button
type="submit"
className="p-2 bg-brand-500 rounded-md border-transparent flex-1 flex justify-center items-center text-sm hover:bg-brand-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-zinc-900 focus:ring-brand-500 transition-colors disabled:opacity-50 disabled:hover:bg-brand-500"
disabled={comment.length === 0 || isSendingFeedback}
>
{ isSendingFeedback ? <Loading/> : 'Enviar feedback'}
</button>
</footer>
</form>
</>
);
} |
//
// SearchViewController.swift
// Root
//
// Created by Jayden Garrick on 1/13/18.
// Copyright © 2018 Jayden Garrick. All rights reserved.
//
import UIKit
import MapKit
protocol SearchViewControllerDelegate : class {
func updateLongLat(long: Double, lat: Double)
}
class SearchViewController: UIViewController {
// MARK: - Variables and Constants
var searchCompleter = MKLocalSearchCompleter()
var searchResults = [MKLocalSearchCompletion]()
weak var delegate: SearchViewControllerDelegate?
@IBOutlet var swipteGest: UIScreenEdgePanGestureRecognizer!
@IBOutlet weak var searchResultsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
searchCompleter.delegate = self
}
// MARK: - IBActions
@IBAction func cancelButtonTapped(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func swipeLeft(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
extension SearchViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchCompleter.queryFragment = searchText
}
}
extension SearchViewController: MKLocalSearchCompleterDelegate {
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
searchResults = completer.results
searchResultsTableView.reloadData()
}
func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) {
// handle error
}
func highlightedText(_ text: String, inRanges ranges: [NSValue], size: CGFloat) -> NSAttributedString {
let attributedText = NSMutableAttributedString(string: text)
let regular = UIFont.systemFont(ofSize: size)
attributedText.addAttribute(NSAttributedStringKey.font, value:regular, range:NSMakeRange(0, text.count))
let bold = UIFont.boldSystemFont(ofSize: size)
for value in ranges {
attributedText.addAttribute(NSAttributedStringKey.font, value:bold, range:value.rangeValue)
}
return attributedText
}
}
extension SearchViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResults.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let searchResult = searchResults[indexPath.row]
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
cell.textLabel?.attributedText = highlightedText(searchResult.title, inRanges: searchResult.titleHighlightRanges, size: 17.0)
cell.detailTextLabel?.attributedText = highlightedText(searchResult.subtitle, inRanges: searchResult.subtitleHighlightRanges, size: 12.0)
return cell
}
}
extension SearchViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let completion = searchResults[indexPath.row]
let searchRequest = MKLocalSearchRequest(completion: completion)
let search = MKLocalSearch(request: searchRequest)
search.start { (response, error) in
guard let response = response else { return }
let coordinate = response.mapItems[0].placemark.coordinate
let longitude = coordinate.longitude
let latitude = coordinate.latitude
print(String(describing: coordinate))
self.delegate?.updateLongLat(long: longitude, lat: latitude)
}
dismiss(animated: true, completion: nil)
}
} |
import type { SharedDevConfig, NormalizedSharedDevConfig } from './dev';
import type { SharedHtmlConfig, NormalizedSharedHtmlConfig } from './html';
import type {
SharedOutputConfig,
NormalizedSharedOutputConfig,
} from './output';
import type {
SharedSourceConfig,
NormalizedSharedSourceConfig,
} from './source';
import type {
SharedSecurityConfig,
NormalizedSharedSecurityConfig,
} from './security';
import type {
SharedPerformanceConfig,
NormalizedSharedPerformanceConfig,
} from './performance';
import type { SharedExperimentsConfig } from './experiments';
import type { SharedToolsConfig } from './tools';
import type { DeepReadonly } from '../utils';
/**
* The shared Builder Config.
* Can be used with webpack-provider or rspack-provider.
* */
export interface SharedBuilderConfig {
dev?: SharedDevConfig;
html?: SharedHtmlConfig;
source?: SharedSourceConfig;
output?: SharedOutputConfig;
security?: SharedSecurityConfig;
performance?: SharedPerformanceConfig;
experiments?: SharedExperimentsConfig;
tools?: SharedToolsConfig;
}
export type SharedNormalizedConfig = DeepReadonly<{
dev: NormalizedSharedDevConfig;
html: NormalizedSharedHtmlConfig;
source: NormalizedSharedSourceConfig;
output: NormalizedSharedOutputConfig;
security: NormalizedSharedSecurityConfig;
performance: NormalizedSharedPerformanceConfig;
tools: SharedToolsConfig;
}>;
export * from './dev';
export * from './html';
export * from './output';
export * from './source';
export * from './security';
export * from './performance';
export * from './experiments';
export * from './tools'; |
<?php
namespace Illuminate\Cache;
use Illuminate\Contracts\Cache\Store;
class TaggedCache extends Repository
{
use RetrievesMultipleKeys;
/**
* The tag set instance.
*
* @var \Illuminate\Cache\TagSet
*/
protected $tags;
/**
* Create a new tagged cache instance.
*
* @param \Illuminate\Contracts\Cache\Store $store
* @param \Illuminate\Cache\TagSet $tags
* @return void
*/
public function __construct(Store $store, TagSet $tags)
{
parent::__construct($store);
$this->tags = $tags;
}
/**
* Increment the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function increment($key, $value = 1)
{
$this->store->increment($this->itemKey($key), $value);
}
/**
* Decrement the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function decrement($key, $value = 1)
{
$this->store->decrement($this->itemKey($key), $value);
}
/**
* Remove all items from the cache.
*
* @return bool
*/
public function flush()
{
$this->tags->reset();
return true;
}
/**
* {@inheritdoc}
*/
protected function itemKey($key)
{
return $this->taggedItemKey($key);
}
/**
* Get a fully qualified key for a tagged item.
*
* @param string $key
* @return string
*/
public function taggedItemKey($key)
{
return sha1($this->tags->getNamespace()).':'.$key;
}
/**
* Fire an event for this cache instance.
*
* @param string $event
* @return void
*/
protected function event($event)
{
parent::event($event->setTags($this->tags->getNames()));
}
/**
* Get the tag set instance.
*
* @return \Illuminate\Cache\TagSet
*/
public function getTags()
{
return $this->tags;
}
} |
import { combineReducers } from 'redux'
import { configureStore } from '@reduxjs/toolkit'
import { StateType } from 'typesafe-actions'
// それぞれ slice.reducer を default export している前提
import accountSlice from './AccountSlice'
import NavigationSlice from './NavigationSlice'
import UtilSlice from './UtilSlice'
import calendarSlice from './CalendarSlice'
import createProjectSlice from './CreateProjectSlice'
import layoutSlice from './LayoutSlice'
import cacheSlice from './CacheSlice'
const reducer = combineReducers({
nav: NavigationSlice,
util: UtilSlice,
account: accountSlice,
calendar: calendarSlice,
createProject: createProjectSlice,
layout: layoutSlice,
cache: cacheSlice,
})
const store = configureStore({
reducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
immutableCheck: false,
serializableCheck: false,
}),
})
export default store
export type StoreType = StateType<typeof reducer> |
import { ITooyeaTextureImages } from "@tooyea/types";
import { fabric } from "fabric";
import { TooyeaRepeatGroup } from "./elements/repeat-group";
import { asyncGetImageFromURL, asyncClone } from "./utils/index";
export class TooyeaCanvasOperator {
constructor({
el,
images,
updateCanvas,
}: {
el: HTMLElement | string;
images: ITooyeaTextureImages;
// 更新画布事件
updateCanvas: Function;
}) {
// 挂载画布
(typeof el === "string" ? document.getElementById(el) : el).append(
this.canvasDom
);
this.fabricCanvas = new fabric.Canvas(this.canvasDom);
this.fabricCanvas.on("mouse:up", (options) => {
console.log("mouse:up事件:", options);
updateCanvas();
});
this.baseImages = images;
this.updateCanvas = updateCanvas;
}
id: string;
meshId: string;
textureId: string;
canvasDom: HTMLCanvasElement = document.createElement("canvas");
// fabric canvas对象
fabricCanvas: fabric.Canvas;
// 静态图片资源地址
baseImages: ITooyeaTextureImages;
// 画布上的素材资源
elements: fabric.Object[] = [];
widgets = [];
updateCanvas: Function;
// #region 复制粘贴
private async _paste(
clipboard: fabric.Object,
offset: {
x: number;
y: number;
}
): Promise<fabric.Object> {
const clonedObj = await asyncClone(clipboard);
clonedObj.set({
left: clonedObj.left + offset.x,
top: clonedObj.top + offset.y,
evented: true,
});
if (clonedObj.type === "activeSelection") {
// active selection needs a reference to the canvas.
clonedObj.canvas = this.fabricCanvas;
// this should solve the unselectability
clonedObj.setCoords();
}
return clonedObj;
}
async paste(
clipboard: fabric.Object,
offset: {
x: number;
y: number;
} = { x: 20, y: 20 }
): Promise<fabric.Object> {
const clonedObj = await this._paste(clipboard, offset);
this.fabricCanvas.setActiveObject(clonedObj);
if (clonedObj.type === "activeSelection") {
// @ts-ignore
clonedObj.forEachObject((obj) => {
this.fabricCanvas.add(obj);
});
} else {
this.fabricCanvas.add(clonedObj);
}
this.updateCanvas();
return clonedObj;
}
copy(target: fabric.Object = this.fabricCanvas.getActiveObject()) {
target.clone((cloned) => {
this.paste(cloned);
});
}
// #endregion
// 初始化图片资源
async initCanvasImages() {
const { overlayImageSrc, backgroundColor, backgroundImageSrc } =
this.baseImages;
if (overlayImageSrc) {
const overlayImg = await asyncGetImageFromURL(overlayImageSrc);
this.fabricCanvas.setWidth(overlayImg.width, {
backstoreOnly: true,
});
this.fabricCanvas.setHeight(overlayImg.height, {
backstoreOnly: true,
});
this.fabricCanvas.setOverlayImage(
overlayImg,
this.fabricCanvas.renderAll.bind(this.fabricCanvas)
);
}
if (backgroundImageSrc) {
const backgroundImg = await asyncGetImageFromURL(backgroundImageSrc);
this.fabricCanvas.setBackgroundImage(
backgroundImg,
this.fabricCanvas.renderAll.bind(this.fabricCanvas)
);
}
if (backgroundColor) {
this.fabricCanvas.setBackgroundColor(
backgroundColor,
this.fabricCanvas.renderAll.bind(this.fabricCanvas)
);
}
}
// 往画布上新增图片
async addImage(imgSource: string) {
const image = await asyncGetImageFromURL(imgSource);
this.elements.push(image);
image.on("moving", (options) => {
this.updateCanvas();
});
image.on("scaling", (options) => {
this.updateCanvas();
});
image.on("rotating", (options) => {
this.updateCanvas();
});
this.fabricCanvas.add(image);
setTimeout(() => {
this.updateCanvas();
}, 100);
}
// 将图片设置成平铺的组
async createRepeatGroupFromElement(
targetElement: fabric.Object = this.fabricCanvas.getActiveObject(),
options?: {
rowGap: number;
columnGap: number;
rowNumber: number;
columnNumber: number;
}
) {
const repeatGroup = new TooyeaRepeatGroup(
targetElement,
options,
this.updateCanvas.bind(this),
this._paste.bind(this)
);
await repeatGroup.initGroup();
this.fabricCanvas.add(repeatGroup.group);
this.fabricCanvas.remove(targetElement);
this.updateCanvas();
}
// 设置背景图
async setBackgroundImage(imgSrc: string) {
const backgroundImg = await asyncGetImageFromURL(imgSrc);
this.fabricCanvas.setBackgroundImage(
backgroundImg,
this.fabricCanvas.renderAll.bind(this.fabricCanvas)
);
}
// 设置背景色
setBackgroundColor(backgroundColor: string) {
this.fabricCanvas.setBackgroundColor(
backgroundColor,
this.fabricCanvas.renderAll.bind(this.fabricCanvas)
);
this.updateCanvas();
}
}
// 背景图转前景图
function t(canvas: HTMLCanvasElement) {
const ctx = canvas.getContext("2d");
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
function invertColors(data) {
for (var i = 0; i < data.length; i += 4) {
if (data[i + 3] === 0) {
data[i] = 255;
data[i + 1] = 255;
data[i + 2] = 255;
data[i + 3] = 255;
} else {
data[i] = 0;
data[i + 1] = 0;
data[i + 2] = 0;
data[i + 3] = 0;
}
}
}
invertColors(imageData.data);
ctx.putImageData(imageData, 0, 0);
} |
<template>
<div class="panel-content">
<div class="panel-top">
<div class="panel-title">
<h1>История</h1>
</div>
<div class="panel-nav">
<NavSearch v-model="search" />
<NavFilter
v-model="sort"
:sort-list="sortList"
/>
<div class="exel">
<a
href="#"
@click.prevent="getExcel"
>Выгрузить в exel</a>
</div>
</div>
</div>
<div class="panel-info">
<table>
<tbody>
<tr>
<th>Номер заказа</th>
<th>Дата</th>
<th>Сумма</th>
<th>Имя и телефон</th>
<th>Адрес</th>
<th>Статус</th>
</tr>
<tr
v-for="order in filteredOrders"
:key="order.id"
>
<td>{{ order.id }}</td>
<td>{{ formatDate(order.createdAt) }}</td>
<td>{{ formatCurrency(order.total) }}</td>
<td>{{ order.user.name }} ❘ {{ formatPhoneNumber(order.user.phone) }}</td>
<td>{{ renderAddress(order.address) }}</td>
<td>
<span
:class="`status-${order.status}`"
class="status"
>{{
ADMIN_ORDER_STATUSES[order.status]
}}</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
import { ADMIN_ORDER_STATUSES } from '@/config/common.js';
import {
downloadFile, formatCurrency, formatDate, formatPhoneNumber, renderAddress,
} from '@/lib/common.js';
import NavSearch from '../../components/admin/NavSearch.vue';
import NavFilter from '../../components/admin/NavFilter.vue';
export default {
name: 'History',
components: { NavFilter, NavSearch },
layout: 'admin',
middleware: ['authenticated'],
data() {
return {
orders: [],
search: '',
sort: null,
//
ADMIN_ORDER_STATUSES,
sortList: [
{ title: 'Новые клиенты', value: 'new' },
{ title: 'Постоянные клиенты', value: 'old' },
{ title: 'По росту цены', value: 'price-asc' },
{ title: 'По убыванию цены', value: 'price-desc' },
{ title: 'По дате рождения', value: 'birthday' },
{ title: 'Мужчины', value: 'man' },
{ title: 'Женщины', value: 'woman' },
],
};
},
async fetch() {
try {
const { data } = await this.$axios.get('/api/order', {
headers: {
Authorization: `Barer ${this.$store.getters['auth/token']}`,
},
});
this.orders = data;
} catch (e) {
await this.$router.push('/admin');
}
},
computed: {
filteredOrders() {
let { orders } = this;
if (this.sort) {
switch (this.sort) {
// price-asc price-desc birthday man woman
case 'new':
orders.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
break;
case 'old':
orders.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
break;
case 'price-asc':
orders.sort((a, b) => a.total - b.total);
break;
case 'price-desc':
orders.sort((a, b) => b.total - a.total);
break;
case 'man':
orders.sort((a, _) => (a.user.gender === 'male' ? 1 : -1));
break;
case 'woman':
orders.sort((a, _) => (a.user.gender === 'female' ? 1 : -1));
break;
case 'birthday':
orders.sort((a, b) => {
if (!a.user.birthday || !b.user.birthday) {
return 0;
}
return new Date(b.user.birthday) - new Date(a.user.birthday);
});
break;
default:
orders = this.orders;
}
} else {
orders = this.orders;
}
if (this.search.length) {
orders = orders.filter((order) => order.user.phone.toLowerCase().includes(this.search.toLowerCase()));
}
return orders;
},
},
methods: {
formatPhoneNumber(phone) {
return formatPhoneNumber(phone);
},
formatDate(date) {
return formatDate(date, { hasTime: true });
},
formatCurrency(number) {
return formatCurrency(number);
},
renderAddress(address) {
return renderAddress(address);
},
async getExcel() {
try {
const { data, headers } = await this.$axios.get('/api/admin/excel/orders', { responseType: 'arraybuffer' });
downloadFile(data, 'orders.xlsx', headers['content-type']);
} catch (e) {
console.log(e);
}
},
},
};
</script> |
---
title: Microsoft Intune 中适用于 Windows 10 设备的电子邮件设置 - Azure | Microsoft Docs
description: 创建使用 Exchange 服务器的设备配置电子邮件配置文件,并从 Azure Active Directory 检索属性。 还可启用 SSL,并使用 Microsoft Intune 在 Windows 10 设备上同步电子邮件和日程安排。
keywords: ''
author: MandiOhlinger
ms.author: mandia
manager: dougeby
ms.date: 05/14/2020
ms.topic: reference
ms.service: microsoft-intune
ms.subservice: configuration
ms.localizationpriority: medium
ms.technology: ''
ms.suite: ems
search.appverid: MET150
ms.custom: intune-azure
ms.collection: M365-identity-device-management
ms.openlocfilehash: 0cd3505d0a0067adfe9082d7aa3882f3421a2183
ms.sourcegitcommit: 48005a260bcb2b97d7fe75809c4bf1552318f50a
ms.translationtype: HT
ms.contentlocale: zh-CN
ms.lasthandoff: 05/15/2020
ms.locfileid: "83429599"
---
# <a name="email-profile-settings-for-devices-running-windows-10-in-microsoft-intune"></a>Microsoft Intune 中适用于运行 Windows 10 的设备的电子邮件配置文件设置
使用电子邮件配置文件设置可以在运行 Windows 10 及更高版本的设备上配置邮件应用。
## <a name="before-you-begin"></a>在开始之前
[创建配置文件](email-settings-configure.md)。
## <a name="email-settings"></a>电子邮件设置
- **电子邮件服务器**:输入 Exchange 服务器的主机名。 例如,输入 `outlook.office365.com`。
- **帐户名**:输入电子邮件帐户的显示名称。 该名称将显示在用户的设备上。
- **AAD 中的用户名属性**:此名称是 Intune 从 Azure Active Directory (AAD) 获取的属性。 Intune 将动态生成此配置文件使用的用户名。 选项包括:
- **用户主体名称**:获取名称,如 `user1` 或 `user1@contoso.com`。
- **主 SMTP 地址**:获取格式为电子邮件地址的名称,如 `user1@contoso.com`。
- **SAM 帐户名**:需要域,如 `domain\user1`。 此外请输入:
- **用户域名源**:选择“AAD”(Azure Active Directory) 或“自定义” 。
从“AAD”获取属性时,还请输入:
- **AAD 中的用户域名属性**:选择获取用户的“完整域名”或“NetBIOS 名称”属性。
使用“自定义”属性时,还请输入:
- **要使用的自定义域名**:输入 Intune 用于域名的值,如 `contoso.com` 或 `contoso`。
- **AAD 中的电子邮件地址属性**:Intune 从 Azure Active Directory (AAD) 获取此属性。 选择用户电子邮件地址的生成方式。 选项包括:
- **用户主体名称**:使用完整的主体名称作为电子邮件地址,如 `user1@contoso.com` 或 `user1`。
- **主 SMTP 地址**:使用主 SMTP 地址登录 Exchange,如 `user1@contoso.com`。
### <a name="security"></a>安全
- **SSL**:选择“启用”后,可在发送电子邮件、接收电子邮件以及与 Exchange 服务器通信时使用安全套接字层 (SSL) 通信。 “禁用”不需要 SSL。
### <a name="synchronization"></a>同步
- **要同步的电子邮件数**:选择你想要同步的电子邮件天数。 设置为“未配置”(默认)时,Intune 不会更改或更新此设置。 选择“无限制”,以同步所有可用的电子邮件。
- **同步计划**:选择设备同步 Exchange 服务器中数据的计划。 还可以选择“当邮件到达时”,这会在邮件达到时立即同步数据。 或者,选择“手动”,以便设备用户开始同步。
设置为“未配置”(默认)时,Intune 不会更改或更新此设置。
### <a name="content-sync"></a>内容同步
- **要同步的内容类型**:请选择想要同步到设备的内容类型。 选项包括:
- **联系人**:“开”会同步联系人。 “关”不会自动同步联系人。 用户手动同步。
- **日历**:“开”会同步日历。 “关”不会自动同步联系人。 用户手动同步。
- **任务**:“开”会同步任务。 “关”不会自动同步任务。 用户手动同步。
## <a name="next-steps"></a>后续步骤
还可以在 [Android](email-settings-android.md)、[Android Enterprise](email-settings-android-enterprise.md)、[iOS/iPadOS](email-settings-ios.md) 上配置电子邮件设置。
[了解有关 Intune 中电子邮件设置的详细信息](email-settings-configure.md)。
[分配配置文件](device-profile-assign.md)并[监视其状态](device-profile-monitor.md)。 |
import React, { useEffect, useState } from "react";
import { calendarIcon } from "Base/SVG";
import { motion } from "framer-motion";
import Slider from "react-slick";
const flexibleDatesList = [
{
id: "1",
date: "Mar 9 - Mar 18",
day: "Sab - Lun • 8 notti",
price: "156€",
save: "76€",
},
{
id: "2",
date: "Mar 8 - Mar 17",
day: "Ven - Dom • 8 notti",
price: "180€",
save: "52€",
},
{
id: "3",
date: "Mar 8 - Mar 17",
day: "Ven - Dom • 8 notti",
price: "180€",
save: "52€",
},
{
id: "4",
date: "Mar 9 - Mar 18",
day: "Sab - Lun • 8 notti",
price: "156€",
save: "76€",
},
{
id: "5",
date: "Mar 8 - Mar 17",
day: "Ven - Dom • 8 notti",
price: "180€",
save: "52€",
},
{
id: "6",
date: "Mar 8 - Mar 17",
day: "Ven - Dom • 8 notti",
price: "180€",
save: "52€",
},
];
export default function FlexibleDates() {
const [faq, setFaq] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const settings = {
slidesToShow: 3,
slidesToScroll: 1,
infinite: false,
arrows: true,
dots: false,
responsive: [
{
breakpoint: 1000,
settings: {
slidesToShow: 2,
slidesToScroll: 1,
},
},
{
breakpoint: 700,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
},
},
],
};
return (
<div className="flexibleDates__wrapper">
<div className="auto__container">
<div className="flexibleDates">
<div
className={"flexibleDates__head " + (faq ? "active" : "")}
onClick={() => {
setFaq(!faq);
setIsLoading(true);
setTimeout(() => {
setIsLoading(false);
}, 2000);
}}
>
<div className="flexibleDates__head-icon">{calendarIcon}</div>
<div className="flexibleDates__head-text">
<h5>Date Flessibili?</h5>
<p>Compara prezzi e risparmia</p>
</div>
</div>
{faq &&
(isLoading ? (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.4 }}
exit={{ opacity: 0 }}
className="flexibleDates__body"
>
<Slider {...settings} className="flexibleDates__body-slider">
{[0, 1, 2, 3].map((item, index) => {
return (
<a href="#" className="flexibleDates__item" key={index}>
<div className="flexibleDates__item-col">
<h6 className="placeholder"></h6>
<p className="placeholder"></p>
</div>
<div className="flexibleDates__item-col">
<h5 className="placeholder"></h5>
<p className="placeholder"></p>
</div>
</a>
);
})}
</Slider>
</motion.div>
) : (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.4 }}
exit={{ opacity: 0 }}
className="flexibleDates__body"
>
<Slider {...settings} className="flexibleDates__body-slider">
{flexibleDatesList.map((item, index) => {
return <FlexibleDatesItem {...item} key={index} />;
})}
</Slider>
</motion.div>
))}
</div>
</div>
</div>
);
}
const FlexibleDatesItem = (props) => {
return (
<a href="#" className="flexibleDates__item">
<div className="flexibleDates__item-col">
<h6>{props.date}</h6>
<p>{props.day}</p>
</div>
<div className="flexibleDates__item-col">
<h5>{props.price}</h5>
<p className="green">
Risparmi <b>{props.save} </b>
</p>
</div>
</a>
);
}; |
package com.viaversion.viaversion.libs.fastutil.objects;
import java.util.function.*;
import java.io.*;
import com.viaversion.viaversion.libs.fastutil.*;
import java.util.*;
public class Object2ObjectOpenHashMap<K, V> extends AbstractObject2ObjectMap<K, V> implements Serializable, Cloneable, Hash
{
private static final long serialVersionUID = 0L;
private static final boolean ASSERTS = false;
protected transient K[] key;
protected transient V[] value;
protected transient int mask;
protected transient boolean containsNullKey;
protected transient int n;
protected transient int maxFill;
protected final transient int minN;
protected int size;
protected final float f;
protected transient Object2ObjectMap.FastEntrySet<K, V> entries;
protected transient ObjectSet<K> keys;
protected transient ObjectCollection<V> values;
public Object2ObjectOpenHashMap(final int expected, final float f) {
if (f <= 0.0f || f >= 1.0f) {
throw new IllegalArgumentException("Load factor must be greater than 0 and smaller than 1");
}
if (expected < 0) {
throw new IllegalArgumentException("The expected number of elements must be nonnegative");
}
this.f = f;
final int arraySize = HashCommon.arraySize(expected, f);
this.n = arraySize;
this.minN = arraySize;
this.mask = this.n - 1;
this.maxFill = HashCommon.maxFill(this.n, f);
this.key = (K[])new Object[this.n + 1];
this.value = (V[])new Object[this.n + 1];
}
public Object2ObjectOpenHashMap(final int expected) {
this(expected, 0.75f);
}
public Object2ObjectOpenHashMap() {
this(16, 0.75f);
}
public Object2ObjectOpenHashMap(final Map<? extends K, ? extends V> m, final float f) {
this(m.size(), f);
this.putAll(m);
}
public Object2ObjectOpenHashMap(final Map<? extends K, ? extends V> m) {
this(m, 0.75f);
}
public Object2ObjectOpenHashMap(final Object2ObjectMap<K, V> m, final float f) {
this(m.size(), f);
this.putAll((Map<? extends K, ? extends V>)m);
}
public Object2ObjectOpenHashMap(final Object2ObjectMap<K, V> m) {
this(m, 0.75f);
}
public Object2ObjectOpenHashMap(final K[] k, final V[] v, final float f) {
this(k.length, f);
if (k.length != v.length) {
throw new IllegalArgumentException("The key array and the value array have different lengths (" + k.length + " and " + v.length + ")");
}
for (int i = 0; i < k.length; ++i) {
this.put(k[i], v[i]);
}
}
public Object2ObjectOpenHashMap(final K[] k, final V[] v) {
this(k, v, 0.75f);
}
private int realSize() {
return this.containsNullKey ? (this.size - 1) : this.size;
}
private void ensureCapacity(final int capacity) {
final int needed = HashCommon.arraySize(capacity, this.f);
if (needed > this.n) {
this.rehash(needed);
}
}
private void tryCapacity(final long capacity) {
final int needed = (int)Math.min(1073741824L, Math.max(2L, HashCommon.nextPowerOfTwo((long)Math.ceil(capacity / this.f))));
if (needed > this.n) {
this.rehash(needed);
}
}
private V removeEntry(final int pos) {
final V oldValue = this.value[pos];
this.value[pos] = null;
--this.size;
this.shiftKeys(pos);
if (this.n > this.minN && this.size < this.maxFill / 4 && this.n > 16) {
this.rehash(this.n / 2);
}
return oldValue;
}
private V removeNullEntry() {
this.containsNullKey = false;
this.key[this.n] = null;
final V oldValue = this.value[this.n];
this.value[this.n] = null;
--this.size;
if (this.n > this.minN && this.size < this.maxFill / 4 && this.n > 16) {
this.rehash(this.n / 2);
}
return oldValue;
}
@Override
public void putAll(final Map<? extends K, ? extends V> m) {
if (this.f <= 0.5) {
this.ensureCapacity(m.size());
}
else {
this.tryCapacity(this.size() + m.size());
}
super.putAll(m);
}
private int find(final K k) {
if (k == null) {
return this.containsNullKey ? this.n : (-(this.n + 1));
}
final K[] key = this.key;
int pos;
K curr;
if ((curr = key[pos = (HashCommon.mix(k.hashCode()) & this.mask)]) == null) {
return -(pos + 1);
}
if (k.equals(curr)) {
return pos;
}
while ((curr = key[pos = (pos + 1 & this.mask)]) != null) {
if (k.equals(curr)) {
return pos;
}
}
return -(pos + 1);
}
private void insert(final int pos, final K k, final V v) {
if (pos == this.n) {
this.containsNullKey = true;
}
this.key[pos] = k;
this.value[pos] = v;
if (this.size++ >= this.maxFill) {
this.rehash(HashCommon.arraySize(this.size + 1, this.f));
}
}
@Override
public V put(final K k, final V v) {
final int pos = this.find(k);
if (pos < 0) {
this.insert(-pos - 1, k, v);
return this.defRetValue;
}
final V oldValue = this.value[pos];
this.value[pos] = v;
return oldValue;
}
protected final void shiftKeys(int pos) {
final K[] key = this.key;
int last = 0;
Label_0006:
while (true) {
pos = ((last = pos) + 1 & this.mask);
K curr;
while ((curr = key[pos]) != null) {
final int slot = HashCommon.mix(curr.hashCode()) & this.mask;
Label_0097: {
if (last <= pos) {
if (last >= slot) {
break Label_0097;
}
if (slot > pos) {
break Label_0097;
}
}
else if (last >= slot && slot > pos) {
break Label_0097;
}
pos = (pos + 1 & this.mask);
continue;
}
key[last] = curr;
this.value[last] = this.value[pos];
continue Label_0006;
}
break;
}
key[last] = null;
this.value[last] = null;
}
@Override
public V remove(final Object k) {
if (k == null) {
if (this.containsNullKey) {
return this.removeNullEntry();
}
return this.defRetValue;
}
else {
final K[] key = this.key;
int pos;
K curr;
if ((curr = key[pos = (HashCommon.mix(k.hashCode()) & this.mask)]) == null) {
return this.defRetValue;
}
if (k.equals(curr)) {
return this.removeEntry(pos);
}
while ((curr = key[pos = (pos + 1 & this.mask)]) != null) {
if (k.equals(curr)) {
return this.removeEntry(pos);
}
}
return this.defRetValue;
}
}
@Override
public V get(final Object k) {
if (k == null) {
return this.containsNullKey ? this.value[this.n] : this.defRetValue;
}
final K[] key = this.key;
int pos;
K curr;
if ((curr = key[pos = (HashCommon.mix(k.hashCode()) & this.mask)]) == null) {
return this.defRetValue;
}
if (k.equals(curr)) {
return this.value[pos];
}
while ((curr = key[pos = (pos + 1 & this.mask)]) != null) {
if (k.equals(curr)) {
return this.value[pos];
}
}
return this.defRetValue;
}
@Override
public boolean containsKey(final Object k) {
if (k == null) {
return this.containsNullKey;
}
final K[] key = this.key;
int pos;
K curr;
if ((curr = key[pos = (HashCommon.mix(k.hashCode()) & this.mask)]) == null) {
return false;
}
if (k.equals(curr)) {
return true;
}
while ((curr = key[pos = (pos + 1 & this.mask)]) != null) {
if (k.equals(curr)) {
return true;
}
}
return false;
}
@Override
public boolean containsValue(final Object v) {
final V[] value = this.value;
final K[] key = this.key;
if (this.containsNullKey && Objects.equals(value[this.n], v)) {
return true;
}
int i = this.n;
while (i-- != 0) {
if (key[i] != null && Objects.equals(value[i], v)) {
return true;
}
}
return false;
}
@Override
public V getOrDefault(final Object k, final V defaultValue) {
if (k == null) {
return this.containsNullKey ? this.value[this.n] : defaultValue;
}
final K[] key = this.key;
int pos;
K curr;
if ((curr = key[pos = (HashCommon.mix(k.hashCode()) & this.mask)]) == null) {
return defaultValue;
}
if (k.equals(curr)) {
return this.value[pos];
}
while ((curr = key[pos = (pos + 1 & this.mask)]) != null) {
if (k.equals(curr)) {
return this.value[pos];
}
}
return defaultValue;
}
@Override
public V putIfAbsent(final K k, final V v) {
final int pos = this.find(k);
if (pos >= 0) {
return this.value[pos];
}
this.insert(-pos - 1, k, v);
return this.defRetValue;
}
@Override
public boolean remove(final Object k, final Object v) {
if (k == null) {
if (this.containsNullKey && Objects.equals(v, this.value[this.n])) {
this.removeNullEntry();
return true;
}
return false;
}
else {
final K[] key = this.key;
int pos;
K curr;
if ((curr = key[pos = (HashCommon.mix(k.hashCode()) & this.mask)]) == null) {
return false;
}
if (k.equals(curr) && Objects.equals(v, this.value[pos])) {
this.removeEntry(pos);
return true;
}
while ((curr = key[pos = (pos + 1 & this.mask)]) != null) {
if (k.equals(curr) && Objects.equals(v, this.value[pos])) {
this.removeEntry(pos);
return true;
}
}
return false;
}
}
@Override
public boolean replace(final K k, final V oldValue, final V v) {
final int pos = this.find(k);
if (pos < 0 || !Objects.equals(oldValue, this.value[pos])) {
return false;
}
this.value[pos] = v;
return true;
}
@Override
public V replace(final K k, final V v) {
final int pos = this.find(k);
if (pos < 0) {
return this.defRetValue;
}
final V oldValue = this.value[pos];
this.value[pos] = v;
return oldValue;
}
@Override
public V computeIfAbsent(final K key, final Object2ObjectFunction<? super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
final int pos = this.find(key);
if (pos >= 0) {
return this.value[pos];
}
if (!mappingFunction.containsKey(key)) {
return this.defRetValue;
}
final V newValue = (V)mappingFunction.get(key);
this.insert(-pos - 1, key, newValue);
return newValue;
}
@Override
public V computeIfPresent(final K k, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
final int pos = this.find(k);
if (pos < 0) {
return this.defRetValue;
}
final V newValue = (V)remappingFunction.apply((Object)k, (Object)this.value[pos]);
if (newValue == null) {
if (k == null) {
this.removeNullEntry();
}
else {
this.removeEntry(pos);
}
return this.defRetValue;
}
return this.value[pos] = newValue;
}
@Override
public V compute(final K k, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
final int pos = this.find(k);
final V newValue = (V)remappingFunction.apply((Object)k, (Object)((pos >= 0) ? this.value[pos] : null));
if (newValue == null) {
if (pos >= 0) {
if (k == null) {
this.removeNullEntry();
}
else {
this.removeEntry(pos);
}
}
return this.defRetValue;
}
final V newVal = newValue;
if (pos < 0) {
this.insert(-pos - 1, k, newVal);
return newVal;
}
return this.value[pos] = newVal;
}
@Override
public V merge(final K k, final V v, final BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
final int pos = this.find(k);
if (pos < 0 || this.value[pos] == null) {
if (v == null) {
return this.defRetValue;
}
this.insert(-pos - 1, k, v);
return v;
}
else {
final V newValue = (V)remappingFunction.apply((Object)this.value[pos], (Object)v);
if (newValue == null) {
if (k == null) {
this.removeNullEntry();
}
else {
this.removeEntry(pos);
}
return this.defRetValue;
}
return this.value[pos] = newValue;
}
}
@Override
public void clear() {
if (this.size == 0) {
return;
}
this.size = 0;
this.containsNullKey = false;
Arrays.fill(this.key, null);
Arrays.fill(this.value, null);
}
@Override
public int size() {
return this.size;
}
@Override
public boolean isEmpty() {
return this.size == 0;
}
@Override
public Object2ObjectMap.FastEntrySet<K, V> object2ObjectEntrySet() {
if (this.entries == null) {
this.entries = new MapEntrySet();
}
return this.entries;
}
@Override
public ObjectSet<K> keySet() {
if (this.keys == null) {
this.keys = new KeySet();
}
return this.keys;
}
@Override
public ObjectCollection<V> values() {
if (this.values == null) {
this.values = new AbstractObjectCollection<V>() {
@Override
public ObjectIterator<V> iterator() {
return new ValueIterator();
}
@Override
public ObjectSpliterator<V> spliterator() {
return new ValueSpliterator();
}
@Override
public void forEach(final Consumer<? super V> consumer) {
if (Object2ObjectOpenHashMap.this.containsNullKey) {
consumer.accept((Object)Object2ObjectOpenHashMap.this.value[Object2ObjectOpenHashMap.this.n]);
}
int pos = Object2ObjectOpenHashMap.this.n;
while (pos-- != 0) {
if (Object2ObjectOpenHashMap.this.key[pos] != null) {
consumer.accept((Object)Object2ObjectOpenHashMap.this.value[pos]);
}
}
}
@Override
public int size() {
return Object2ObjectOpenHashMap.this.size;
}
@Override
public boolean contains(final Object v) {
return Object2ObjectOpenHashMap.this.containsValue(v);
}
@Override
public void clear() {
Object2ObjectOpenHashMap.this.clear();
}
};
}
return this.values;
}
public boolean trim() {
return this.trim(this.size);
}
public boolean trim(final int n) {
final int l = HashCommon.nextPowerOfTwo((int)Math.ceil(n / this.f));
if (l >= this.n || this.size > HashCommon.maxFill(l, this.f)) {
return true;
}
try {
this.rehash(l);
}
catch (OutOfMemoryError cantDoIt) {
return false;
}
return true;
}
protected void rehash(final int newN) {
final K[] key = this.key;
final V[] value = this.value;
final int mask = newN - 1;
final K[] newKey = (K[])new Object[newN + 1];
final V[] newValue = (V[])new Object[newN + 1];
int i = this.n;
int j = this.realSize();
while (j-- != 0) {
while (key[--i] == null) {}
int pos;
if (newKey[pos = (HashCommon.mix(key[i].hashCode()) & mask)] != null) {
while (newKey[pos = (pos + 1 & mask)] != null) {}
}
newKey[pos] = key[i];
newValue[pos] = value[i];
}
newValue[newN] = value[this.n];
this.n = newN;
this.mask = mask;
this.maxFill = HashCommon.maxFill(this.n, this.f);
this.key = newKey;
this.value = newValue;
}
public Object2ObjectOpenHashMap<K, V> clone() {
Object2ObjectOpenHashMap<K, V> c;
try {
c = (Object2ObjectOpenHashMap)super.clone();
}
catch (CloneNotSupportedException cantHappen) {
throw new InternalError();
}
c.keys = null;
c.values = null;
c.entries = null;
c.containsNullKey = this.containsNullKey;
c.key = this.key.clone();
c.value = this.value.clone();
return c;
}
@Override
public int hashCode() {
int h = 0;
int j = this.realSize();
int i = 0;
int t = 0;
while (j-- != 0) {
while (this.key[i] == null) {
++i;
}
if (this != this.key[i]) {
t = this.key[i].hashCode();
}
if (this != this.value[i]) {
t ^= ((this.value[i] == null) ? 0 : this.value[i].hashCode());
}
h += t;
++i;
}
if (this.containsNullKey) {
h += ((this.value[this.n] == null) ? 0 : this.value[this.n].hashCode());
}
return h;
}
private void writeObject(final ObjectOutputStream s) throws IOException {
final K[] key = this.key;
final V[] value = this.value;
final EntryIterator i = new EntryIterator();
s.defaultWriteObject();
int j = this.size;
while (j-- != 0) {
final int e = i.nextEntry();
s.writeObject(key[e]);
s.writeObject(value[e]);
}
}
private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
this.n = HashCommon.arraySize(this.size, this.f);
this.maxFill = HashCommon.maxFill(this.n, this.f);
this.mask = this.n - 1;
final Object[] key2 = new Object[this.n + 1];
this.key = (K[])key2;
final K[] key = (K[])key2;
final Object[] value2 = new Object[this.n + 1];
this.value = (V[])value2;
final V[] value = (V[])value2;
int i = this.size;
while (i-- != 0) {
final K k = (K)s.readObject();
final V v = (V)s.readObject();
int pos;
if (k == null) {
pos = this.n;
this.containsNullKey = true;
}
else {
for (pos = (HashCommon.mix(k.hashCode()) & this.mask); key[pos] != null; pos = (pos + 1 & this.mask)) {}
}
key[pos] = k;
value[pos] = v;
}
}
private void checkTable() {
}
final class MapEntry implements Object2ObjectMap.Entry<K, V>, Map.Entry<K, V>, Pair<K, V>
{
int index;
MapEntry(final int index) {
this.index = index;
}
MapEntry() {
}
@Override
public K getKey() {
return Object2ObjectOpenHashMap.this.key[this.index];
}
@Override
public K left() {
return Object2ObjectOpenHashMap.this.key[this.index];
}
@Override
public V getValue() {
return Object2ObjectOpenHashMap.this.value[this.index];
}
@Override
public V right() {
return Object2ObjectOpenHashMap.this.value[this.index];
}
@Override
public V setValue(final V v) {
final V oldValue = Object2ObjectOpenHashMap.this.value[this.index];
Object2ObjectOpenHashMap.this.value[this.index] = v;
return oldValue;
}
@Override
public Pair<K, V> right(final V v) {
Object2ObjectOpenHashMap.this.value[this.index] = v;
return this;
}
@Override
public boolean equals(final Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
final Map.Entry<K, V> e = (Map.Entry<K, V>)o;
return Objects.equals(Object2ObjectOpenHashMap.this.key[this.index], e.getKey()) && Objects.equals(Object2ObjectOpenHashMap.this.value[this.index], e.getValue());
}
@Override
public int hashCode() {
return ((Object2ObjectOpenHashMap.this.key[this.index] == null) ? 0 : Object2ObjectOpenHashMap.this.key[this.index].hashCode()) ^ ((Object2ObjectOpenHashMap.this.value[this.index] == null) ? 0 : Object2ObjectOpenHashMap.this.value[this.index].hashCode());
}
@Override
public String toString() {
return Object2ObjectOpenHashMap.this.key[this.index] + "=>" + Object2ObjectOpenHashMap.this.value[this.index];
}
}
private abstract class MapIterator<ConsumerType>
{
int pos;
int last;
int c;
boolean mustReturnNullKey;
ObjectArrayList<K> wrapped;
private MapIterator() {
this.pos = Object2ObjectOpenHashMap.this.n;
this.last = -1;
this.c = Object2ObjectOpenHashMap.this.size;
this.mustReturnNullKey = Object2ObjectOpenHashMap.this.containsNullKey;
}
abstract void acceptOnIndex(final ConsumerType p0, final int p1);
public boolean hasNext() {
return this.c != 0;
}
public int nextEntry() {
if (!this.hasNext()) {
throw new NoSuchElementException();
}
--this.c;
if (this.mustReturnNullKey) {
this.mustReturnNullKey = false;
return this.last = Object2ObjectOpenHashMap.this.n;
}
final K[] key = Object2ObjectOpenHashMap.this.key;
while (--this.pos >= 0) {
if (key[this.pos] != null) {
return this.last = this.pos;
}
}
this.last = Integer.MIN_VALUE;
K k;
int p;
for (k = this.wrapped.get(-this.pos - 1), p = (HashCommon.mix(k.hashCode()) & Object2ObjectOpenHashMap.this.mask); !k.equals(key[p]); p = (p + 1 & Object2ObjectOpenHashMap.this.mask)) {}
return p;
}
public void forEachRemaining(final ConsumerType action) {
if (this.mustReturnNullKey) {
this.mustReturnNullKey = false;
this.acceptOnIndex(action, this.last = Object2ObjectOpenHashMap.this.n);
--this.c;
}
final K[] key = Object2ObjectOpenHashMap.this.key;
while (this.c != 0) {
if (--this.pos < 0) {
this.last = Integer.MIN_VALUE;
K k;
int p;
for (k = this.wrapped.get(-this.pos - 1), p = (HashCommon.mix(k.hashCode()) & Object2ObjectOpenHashMap.this.mask); !k.equals(key[p]); p = (p + 1 & Object2ObjectOpenHashMap.this.mask)) {}
this.acceptOnIndex(action, p);
--this.c;
}
else {
if (key[this.pos] == null) {
continue;
}
this.acceptOnIndex(action, this.last = this.pos);
--this.c;
}
}
}
private void shiftKeys(int pos) {
final K[] key = Object2ObjectOpenHashMap.this.key;
int last = 0;
Label_0009:
while (true) {
pos = ((last = pos) + 1 & Object2ObjectOpenHashMap.this.mask);
K curr;
while ((curr = key[pos]) != null) {
final int slot = HashCommon.mix(curr.hashCode()) & Object2ObjectOpenHashMap.this.mask;
Label_0112: {
if (last <= pos) {
if (last >= slot) {
break Label_0112;
}
if (slot > pos) {
break Label_0112;
}
}
else if (last >= slot && slot > pos) {
break Label_0112;
}
pos = (pos + 1 & Object2ObjectOpenHashMap.this.mask);
continue;
}
if (pos < last) {
if (this.wrapped == null) {
this.wrapped = new ObjectArrayList<K>(2);
}
this.wrapped.add(key[pos]);
}
key[last] = curr;
Object2ObjectOpenHashMap.this.value[last] = Object2ObjectOpenHashMap.this.value[pos];
continue Label_0009;
}
break;
}
key[last] = null;
Object2ObjectOpenHashMap.this.value[last] = null;
}
public void remove() {
if (this.last == -1) {
throw new IllegalStateException();
}
if (this.last == Object2ObjectOpenHashMap.this.n) {
Object2ObjectOpenHashMap.this.containsNullKey = false;
Object2ObjectOpenHashMap.this.key[Object2ObjectOpenHashMap.this.n] = null;
Object2ObjectOpenHashMap.this.value[Object2ObjectOpenHashMap.this.n] = null;
}
else {
if (this.pos < 0) {
Object2ObjectOpenHashMap.this.remove(this.wrapped.set(-this.pos - 1, null));
this.last = -1;
return;
}
this.shiftKeys(this.last);
}
final Object2ObjectOpenHashMap this$0 = Object2ObjectOpenHashMap.this;
--this$0.size;
this.last = -1;
}
public int skip(final int n) {
int i = n;
while (i-- != 0 && this.hasNext()) {
this.nextEntry();
}
return n - i - 1;
}
}
private final class EntryIterator extends MapIterator<Consumer<? super Object2ObjectMap.Entry<K, V>>> implements ObjectIterator<Object2ObjectMap.Entry<K, V>>
{
private MapEntry entry;
@Override
public MapEntry next() {
return this.entry = new MapEntry(this.nextEntry());
}
@Override
final void acceptOnIndex(final Consumer<? super Object2ObjectMap.Entry<K, V>> action, final int index) {
action.accept(this.entry = new MapEntry(index));
}
@Override
public void remove() {
super.remove();
this.entry.index = -1;
}
}
private final class FastEntryIterator extends MapIterator<Consumer<? super Object2ObjectMap.Entry<K, V>>> implements ObjectIterator<Object2ObjectMap.Entry<K, V>>
{
private final MapEntry entry;
private FastEntryIterator() {
this.entry = new MapEntry();
}
@Override
public MapEntry next() {
this.entry.index = this.nextEntry();
return this.entry;
}
@Override
final void acceptOnIndex(final Consumer<? super Object2ObjectMap.Entry<K, V>> action, final int index) {
this.entry.index = index;
action.accept(this.entry);
}
}
private abstract class MapSpliterator<ConsumerType, SplitType extends MapSpliterator<ConsumerType, SplitType>>
{
int pos;
int max;
int c;
boolean mustReturnNull;
boolean hasSplit;
MapSpliterator() {
this.pos = 0;
this.max = Object2ObjectOpenHashMap.this.n;
this.c = 0;
this.mustReturnNull = Object2ObjectOpenHashMap.this.containsNullKey;
this.hasSplit = false;
}
MapSpliterator(final int pos, final int max, final boolean mustReturnNull, final boolean hasSplit) {
this.pos = 0;
this.max = Object2ObjectOpenHashMap.this.n;
this.c = 0;
this.mustReturnNull = Object2ObjectOpenHashMap.this.containsNullKey;
this.hasSplit = false;
this.pos = pos;
this.max = max;
this.mustReturnNull = mustReturnNull;
this.hasSplit = hasSplit;
}
abstract void acceptOnIndex(final ConsumerType p0, final int p1);
abstract SplitType makeForSplit(final int p0, final int p1, final boolean p2);
public boolean tryAdvance(final ConsumerType action) {
if (this.mustReturnNull) {
this.mustReturnNull = false;
++this.c;
this.acceptOnIndex(action, Object2ObjectOpenHashMap.this.n);
return true;
}
final K[] key = Object2ObjectOpenHashMap.this.key;
while (this.pos < this.max) {
if (key[this.pos] != null) {
++this.c;
this.acceptOnIndex(action, this.pos++);
return true;
}
++this.pos;
}
return false;
}
public void forEachRemaining(final ConsumerType action) {
if (this.mustReturnNull) {
this.mustReturnNull = false;
++this.c;
this.acceptOnIndex(action, Object2ObjectOpenHashMap.this.n);
}
final K[] key = Object2ObjectOpenHashMap.this.key;
while (this.pos < this.max) {
if (key[this.pos] != null) {
this.acceptOnIndex(action, this.pos);
++this.c;
}
++this.pos;
}
}
public long estimateSize() {
if (!this.hasSplit) {
return Object2ObjectOpenHashMap.this.size - this.c;
}
return Math.min(Object2ObjectOpenHashMap.this.size - this.c, (long)(Object2ObjectOpenHashMap.this.realSize() / (double)Object2ObjectOpenHashMap.this.n * (this.max - this.pos)) + (long)(this.mustReturnNull ? 1 : 0));
}
public SplitType trySplit() {
if (this.pos >= this.max - 1) {
return null;
}
final int retLen = this.max - this.pos >> 1;
if (retLen <= 1) {
return null;
}
final int myNewPos = this.pos + retLen;
final int retPos = this.pos;
final int retMax = myNewPos;
final SplitType split = this.makeForSplit(retPos, retMax, this.mustReturnNull);
this.pos = myNewPos;
this.mustReturnNull = false;
this.hasSplit = true;
return split;
}
public long skip(long n) {
if (n < 0L) {
throw new IllegalArgumentException("Argument must be nonnegative: " + n);
}
if (n == 0L) {
return 0L;
}
long skipped = 0L;
if (this.mustReturnNull) {
this.mustReturnNull = false;
++skipped;
--n;
}
final K[] key = Object2ObjectOpenHashMap.this.key;
while (this.pos < this.max && n > 0L) {
if (key[this.pos++] != null) {
++skipped;
--n;
}
}
return skipped;
}
}
private final class EntrySpliterator extends MapSpliterator<Consumer<? super Object2ObjectMap.Entry<K, V>>, EntrySpliterator> implements ObjectSpliterator<Object2ObjectMap.Entry<K, V>>
{
private static final int POST_SPLIT_CHARACTERISTICS = 1;
EntrySpliterator() {
}
EntrySpliterator(final int pos, final int max, final boolean mustReturnNull, final boolean hasSplit) {
super(pos, max, mustReturnNull, hasSplit);
}
@Override
public int characteristics() {
return this.hasSplit ? 1 : 65;
}
@Override
final void acceptOnIndex(final Consumer<? super Object2ObjectMap.Entry<K, V>> action, final int index) {
action.accept((Object)new MapEntry(index));
}
@Override
final EntrySpliterator makeForSplit(final int pos, final int max, final boolean mustReturnNull) {
return new EntrySpliterator(pos, max, mustReturnNull, true);
}
}
private final class MapEntrySet extends AbstractObjectSet<Object2ObjectMap.Entry<K, V>> implements Object2ObjectMap.FastEntrySet<K, V>
{
@Override
public ObjectIterator<Object2ObjectMap.Entry<K, V>> iterator() {
return new EntryIterator();
}
@Override
public ObjectIterator<Object2ObjectMap.Entry<K, V>> fastIterator() {
return new FastEntryIterator();
}
@Override
public ObjectSpliterator<Object2ObjectMap.Entry<K, V>> spliterator() {
return new EntrySpliterator();
}
@Override
public boolean contains(final Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
final Map.Entry<?, ?> e = (Map.Entry<?, ?>)o;
final K k = (K)e.getKey();
final V v = (V)e.getValue();
if (k == null) {
return Object2ObjectOpenHashMap.this.containsNullKey && Objects.equals(Object2ObjectOpenHashMap.this.value[Object2ObjectOpenHashMap.this.n], v);
}
final K[] key = Object2ObjectOpenHashMap.this.key;
int pos;
K curr;
if ((curr = key[pos = (HashCommon.mix(k.hashCode()) & Object2ObjectOpenHashMap.this.mask)]) == null) {
return false;
}
if (k.equals(curr)) {
return Objects.equals(Object2ObjectOpenHashMap.this.value[pos], v);
}
while ((curr = key[pos = (pos + 1 & Object2ObjectOpenHashMap.this.mask)]) != null) {
if (k.equals(curr)) {
return Objects.equals(Object2ObjectOpenHashMap.this.value[pos], v);
}
}
return false;
}
@Override
public boolean remove(final Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
final Map.Entry<?, ?> e = (Map.Entry<?, ?>)o;
final K k = (K)e.getKey();
final V v = (V)e.getValue();
if (k == null) {
if (Object2ObjectOpenHashMap.this.containsNullKey && Objects.equals(Object2ObjectOpenHashMap.this.value[Object2ObjectOpenHashMap.this.n], v)) {
Object2ObjectOpenHashMap.this.removeNullEntry();
return true;
}
return false;
}
else {
final K[] key = Object2ObjectOpenHashMap.this.key;
int pos;
K curr;
if ((curr = key[pos = (HashCommon.mix(k.hashCode()) & Object2ObjectOpenHashMap.this.mask)]) == null) {
return false;
}
if (!curr.equals(k)) {
while ((curr = key[pos = (pos + 1 & Object2ObjectOpenHashMap.this.mask)]) != null) {
if (curr.equals(k) && Objects.equals(Object2ObjectOpenHashMap.this.value[pos], v)) {
Object2ObjectOpenHashMap.this.removeEntry(pos);
return true;
}
}
return false;
}
if (Objects.equals(Object2ObjectOpenHashMap.this.value[pos], v)) {
Object2ObjectOpenHashMap.this.removeEntry(pos);
return true;
}
return false;
}
}
@Override
public int size() {
return Object2ObjectOpenHashMap.this.size;
}
@Override
public void clear() {
Object2ObjectOpenHashMap.this.clear();
}
@Override
public void forEach(final Consumer<? super Object2ObjectMap.Entry<K, V>> consumer) {
if (Object2ObjectOpenHashMap.this.containsNullKey) {
consumer.accept((Object)new BasicEntry((K)Object2ObjectOpenHashMap.this.key[Object2ObjectOpenHashMap.this.n], (V)Object2ObjectOpenHashMap.this.value[Object2ObjectOpenHashMap.this.n]));
}
int pos = Object2ObjectOpenHashMap.this.n;
while (pos-- != 0) {
if (Object2ObjectOpenHashMap.this.key[pos] != null) {
consumer.accept((Object)new BasicEntry((K)Object2ObjectOpenHashMap.this.key[pos], (V)Object2ObjectOpenHashMap.this.value[pos]));
}
}
}
@Override
public void fastForEach(final Consumer<? super Object2ObjectMap.Entry<K, V>> consumer) {
final BasicEntry<K, V> entry = new BasicEntry<K, V>();
if (Object2ObjectOpenHashMap.this.containsNullKey) {
entry.key = Object2ObjectOpenHashMap.this.key[Object2ObjectOpenHashMap.this.n];
entry.value = Object2ObjectOpenHashMap.this.value[Object2ObjectOpenHashMap.this.n];
consumer.accept(entry);
}
int pos = Object2ObjectOpenHashMap.this.n;
while (pos-- != 0) {
if (Object2ObjectOpenHashMap.this.key[pos] != null) {
entry.key = Object2ObjectOpenHashMap.this.key[pos];
entry.value = Object2ObjectOpenHashMap.this.value[pos];
consumer.accept(entry);
}
}
}
}
private final class KeyIterator extends MapIterator<Consumer<? super K>> implements ObjectIterator<K>
{
public KeyIterator() {
}
@Override
final void acceptOnIndex(final Consumer<? super K> action, final int index) {
action.accept((Object)Object2ObjectOpenHashMap.this.key[index]);
}
@Override
public K next() {
return Object2ObjectOpenHashMap.this.key[this.nextEntry()];
}
}
private final class KeySpliterator extends MapSpliterator<Consumer<? super K>, KeySpliterator> implements ObjectSpliterator<K>
{
private static final int POST_SPLIT_CHARACTERISTICS = 1;
KeySpliterator() {
}
KeySpliterator(final int pos, final int max, final boolean mustReturnNull, final boolean hasSplit) {
super(pos, max, mustReturnNull, hasSplit);
}
@Override
public int characteristics() {
return this.hasSplit ? 1 : 65;
}
@Override
final void acceptOnIndex(final Consumer<? super K> action, final int index) {
action.accept((Object)Object2ObjectOpenHashMap.this.key[index]);
}
@Override
final KeySpliterator makeForSplit(final int pos, final int max, final boolean mustReturnNull) {
return new KeySpliterator(pos, max, mustReturnNull, true);
}
}
private final class KeySet extends AbstractObjectSet<K>
{
@Override
public ObjectIterator<K> iterator() {
return new KeyIterator();
}
@Override
public ObjectSpliterator<K> spliterator() {
return new KeySpliterator();
}
@Override
public void forEach(final Consumer<? super K> consumer) {
if (Object2ObjectOpenHashMap.this.containsNullKey) {
consumer.accept((Object)Object2ObjectOpenHashMap.this.key[Object2ObjectOpenHashMap.this.n]);
}
int pos = Object2ObjectOpenHashMap.this.n;
while (pos-- != 0) {
final K k = Object2ObjectOpenHashMap.this.key[pos];
if (k != null) {
consumer.accept((Object)k);
}
}
}
@Override
public int size() {
return Object2ObjectOpenHashMap.this.size;
}
@Override
public boolean contains(final Object k) {
return Object2ObjectOpenHashMap.this.containsKey(k);
}
@Override
public boolean remove(final Object k) {
final int oldSize = Object2ObjectOpenHashMap.this.size;
Object2ObjectOpenHashMap.this.remove(k);
return Object2ObjectOpenHashMap.this.size != oldSize;
}
@Override
public void clear() {
Object2ObjectOpenHashMap.this.clear();
}
}
private final class ValueIterator extends MapIterator<Consumer<? super V>> implements ObjectIterator<V>
{
public ValueIterator() {
}
@Override
final void acceptOnIndex(final Consumer<? super V> action, final int index) {
action.accept((Object)Object2ObjectOpenHashMap.this.value[index]);
}
@Override
public V next() {
return Object2ObjectOpenHashMap.this.value[this.nextEntry()];
}
}
private final class ValueSpliterator extends MapSpliterator<Consumer<? super V>, ValueSpliterator> implements ObjectSpliterator<V>
{
private static final int POST_SPLIT_CHARACTERISTICS = 0;
ValueSpliterator() {
}
ValueSpliterator(final int pos, final int max, final boolean mustReturnNull, final boolean hasSplit) {
super(pos, max, mustReturnNull, hasSplit);
}
@Override
public int characteristics() {
return this.hasSplit ? 0 : 64;
}
@Override
final void acceptOnIndex(final Consumer<? super V> action, final int index) {
action.accept((Object)Object2ObjectOpenHashMap.this.value[index]);
}
@Override
final ValueSpliterator makeForSplit(final int pos, final int max, final boolean mustReturnNull) {
return new ValueSpliterator(pos, max, mustReturnNull, true);
}
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Complete Responsive Online Study Website Design Tutorial</title>
<!-- google fonts cdn link -->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600&display=swap" rel="stylesheet">
<!-- font awesome cdn link -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css">
<!-- custom css file link -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- header section starts -->
<header>
<div id="menu" class="fas fa-bars"></div>
<a href="#" class="logo"><i class="fas fa-user-graduate"></i>LOGO</a>
<nav class="navbar">
<ul>
<li><a class="active" href="#home">home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#course">Courses</a></li>
<li><a href="#teacher">Teacher</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<div id="login" class="fas fa-user-circle"></div>
</header>
<!-- header section ends -->
<!-- login form -->
<div class="login-form">
<form action="">
<h3>login</h3>
<input type="email" placeholder="username" class="box">
<input type="password" placeholder="password" class="box">
<p>forget password? <a href="#">click here</a></p>
<p>don't have an account? <a href="#">register now</a></p>
<input type="submit" class="btn" value="login">
<i class="fas fa-times"></i>
</form>
</div>
<!-- home section starts -->
<section class="home" id="home">
<h1>education from home</h1>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Ipsum neque aliquid similique error velit placeat vitae accusantium est nam magnam?</p>
<a href="#"><button class="btn">get started</button></a>
</section>
<!-- home section ends -->
<!-- about section starts -->
<section class="about" id="about">
<div class="image">
<img src="images/Studying-cuate.png" alt="">
</div>
<div class="content">
<h3>why choose us?</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam aperiam quaerat dolor voluptas nobis voluptates illum? Inventore voluptas dolore voluptates.</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ex delectus ducimus dignissimos pariatur. Amet sed distinctio earum dolorum nulla, in obcaecati aliquid modi quos magni ducimus culpa nobis laudantium incidunt.</p>
<a href="#"><button class="btn">learn more</button></a>
</div>
</section>
<!-- about section ends -->
<!-- course section starts -->
<section class="course" id="course">
<h1 class="heading">Our popular courses</h1>
<div class="box-container">
<div class="box">
<img src="images/frontend.jpg" alt="">
<h3 class="price">$100</h3>
<div class="content">
<div class="stars">
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star-half"></i>
</div>
<a href="#" class="title">Learn front end development</a>
<p>Front-end web development is the development of the graphical user interface of a website, through the use of HTML, CSS, and JavaScript, so that users can view and interact with that website.</p>
<div class="info">
<h3> <i class="far fa-clock"></i> 45 hours </h3>
<h3> <i class="far fa-calendar-alt"></i> 6 months </h3>
<h3> <i class="fas fa-book"></i> 12 modules </h3>
</div>
</div>
</div>
<div class="box">
<img src="images/backend.png" alt="">
<h3 class="price">$200</h3>
<div class="content">
<div class="stars">
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star-half"></i>
</div>
<a href="#" class="title">Learn backend end development</a>
<p> Backend Development is also known as server-side development. It is everything that the users don't see and contains behind-the-scenes activities that occur when performing any action on a website.</p>
<div class="info">
<h3> <i class="far fa-clock"></i> 50 hours </h3>
<h3> <i class="far fa-calendar-alt"></i> 6 months </h3>
<h3> <i class="fas fa-book"></i> 15 modules </h3>
</div>
</div>
</div>
<div class="box">
<img src="images/cloud.jpg" alt="">
<h3 class="price">$90</h3>
<div class="content">
<div class="stars">
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star-half"></i>
</div>
<a href="#" class="title">Learn Cloud computing</a>
<p>Cloud computing is a general term for anything that involves delivering hosted services over the internet. Cloud computing infrastructure involves the hardware and software components required for proper implementation of a cloud computing model.</p>
<div class="info">
<h3> <i class="far fa-clock"></i> 46 hours </h3>
<h3> <i class="far fa-calendar-alt"></i> 6 months </h3>
<h3> <i class="fas fa-book"></i> 10 modules </h3>
</div>
</div>
</div>
<div class="box">
<img src="images/artificial.jpg" alt="">
<h3 class="price">$150</h3>
<div class="content">
<div class="stars">
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star-half"></i>
</div>
<a href="#" class="title">Learn artificial intelligence</a>
<p>Artificial intelligence is the ability of a computer or a robot controlled by a computer to do tasks that are usually done by humans because they require human intelligence and discernment.There are four types: reactive, limited memory, theory of mind, and self-aware</p>
<div class="info">
<h3> <i class="far fa-clock"></i> 48 hours </h3>
<h3> <i class="far fa-calendar-alt"></i> 6 months </h3>
<h3> <i class="fas fa-book"></i> 12 modules </h3>
</div>
</div>
</div>
<div class="box">
<img src="images/machine.png" alt="">
<h3 class="price">$50</h3>
<div class="content">
<div class="stars">
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star-half"></i>
</div>
<a href="#" class="title">Learn Machine learning</a>
<p>Machine learning is the study of computer algorithms that can improve automatically through experience and by the use of data.Algorithms build a model based on sample data, known as training data.</p>
<div class="info">
<h3> <i class="far fa-clock"></i> 25 hours </h3>
<h3> <i class="far fa-calendar-alt"></i> 5 months </h3>
<h3> <i class="fas fa-book"></i> 11 modules </h3>
</div>
</div>
</div>
<div class="box">
<img src="images/cyber.png" alt="">
<h3 class="price">$50</h3>
<div class="content">
<div class="stars">
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star-half"></i>
</div>
<a href="#" class="title">Learn Cyber Security</a>
<p>Cyber security is the application of technologies, processes and controls to protect systems, networks, programs, devices and data from cyber attacks.</p>
<div class="info">
<h3> <i class="far fa-clock"></i> 30 hours </h3>
<h3> <i class="far fa-calendar-alt"></i> 7 months </h3>
<h3> <i class="fas fa-book"></i> 12 modules </h3>
</div>
</div>
</div>
</div>
</section>
<!-- course section ends -->
<!-- teacher section starts -->
<section class="teacher" id="teacher">
<h1 class="heading">our expert teachers</h1>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. At non explicabo tempora modi, reprehenderit ratione sunt ea porro tenetur officiis alias sapiente praesentium voluptas cumque quo maiores dolores totam ex.</p>
<a href="#"><button class="btn">learn more</button></a>
</section>
<!-- teacher section ends -->
<!-- contact section starts -->
<section class="contact" id="contact">
<h1 class="heading">contact us</h1>
<div class="row">
<form action="">
<input type="text" placeholder="full name" class="box">
<input type="email" placeholder="your email" class="box">
<input type="password" placeholder="your password" class="box">
<input type="number" placeholder="your number" class="box">
<textarea name="" id="" cols="30" rows="10" class="box address" placeholder="your address"></textarea>
<input type="submit" class="btn" value="send now">
</form>
<div class="image">
<img src="images/contact-img.png" alt="">
</div>
</div>
</section>
<!-- contact section ends -->
<!-- footer section starts -->
<div class="footer">
<div class="box-container">
<div class="box">
<h3>branch locations</h3>
<a href="#">India</a>
<a href="#">USA</a>
<a href="#">france</a>
<a href="#">russia</a>
</div>
<div class="box">
<h3>quick links</h3>
<a href="#">home</a>
<a href="#">about</a>
<a href="#">course</a>
<a href="#">teachers</a>
<a href="#">contact</a>
</div>
<div class="box">
<h3>contact info</h3>
<p> <i class="fas fa-map-marker-alt"></i> mumbai, india 400104. </p>
<p> <i class="fas fa-envelope"></i> example@gmail.com </p>
<p> <i class="fas fa-phone"></i> +123-456-7890 </p>
</div>
</div>
<h1 class="credit">created by <a href="#">mr. web designer</a> all rights reserved. </h1>
</div>
<!-- footer section ends -->
<!-- jquery cdn link -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- custom js file link -->
<script src="script.js"></script>
</body>
</html> |
/*******************************************************************************
* Copyright (c) 2013 -- WPI Suite
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Chris Casola
* JPage
******************************************************************************/
package edu.wpi.cs.wpisuitetng.modules.defecttracker.search.controllers;
import javax.swing.JOptionPane;
import edu.wpi.cs.wpisuitetng.modules.defecttracker.models.Defect;
import edu.wpi.cs.wpisuitetng.modules.defecttracker.search.observers.RetrieveAllDefectsRequestObserver;
import edu.wpi.cs.wpisuitetng.modules.defecttracker.search.views.SearchDefectsView;
import edu.wpi.cs.wpisuitetng.network.Network;
import edu.wpi.cs.wpisuitetng.network.Request;
import edu.wpi.cs.wpisuitetng.network.RequestObserver;
import edu.wpi.cs.wpisuitetng.network.models.HttpMethod;
/**
* Controller to handle retrieving all defects from the server and
* displaying them in the {@link SearchDefectsView}
*/
public class RetrieveAllDefectsController {
/** The search defects view */
protected SearchDefectsView view;
/** The defects data retrieved from the server */
protected Defect[] data = null;
/**
* Constructs a new RetrieveAllDefectsController
*
* @param view the search defects view
*/
public RetrieveAllDefectsController(SearchDefectsView view) {
this.view = view;
}
/**
* Sends a request for all of the defects
*/
public void refreshData() {
final RequestObserver requestObserver = new RetrieveAllDefectsRequestObserver(this);
Request request;
request = Network.getInstance().makeRequest("defecttracker/defect", HttpMethod.GET);
request.addObserver(requestObserver);
request.send();
}
/**
* This method is called by the {@link RetrieveAllDefectsRequestObserver} when the
* response is received
*
* @param defects an array of defects returned by the server
*/
public void receivedData(Defect[] defects) {
if (defects.length > 0) {
// save the data
this.data = defects;
// set the column names
String[] columnNames = {"ID", "Title", "Description", "Creator", "Assignee", "Status", "Created", "Last Modified"};
view.getSearchPanel().getResultsPanel().getModel().setColumnNames(columnNames);
// put the data in the table
Object[][] entries = new Object[defects.length][columnNames.length];
for (int i = 0; i < defects.length; i++) {
entries[i][0] = String.valueOf(defects[i].getId());
entries[i][1] = defects[i].getTitle();
entries[i][2] = defects[i].getDescription();
entries[i][3] = defects[i].getCreator().getName();
if (defects[i].getAssignee() != null) {
entries[i][4] = defects[i].getAssignee().getName();
}
else {
entries[i][4] = "";
}
entries[i][5] = defects[i].getStatus().toString();
entries[i][6] = defects[i].getCreationDate();
entries[i][7] = defects[i].getLastModifiedDate();
}
view.getSearchPanel().getResultsPanel().getModel().setData(entries);
view.getSearchPanel().getResultsPanel().getModel().fireTableStructureChanged();
}
else {
// do nothing, there are no defects
}
}
/**
* This method is called by the {@link RetrieveAllDefectsRequestObserver} when an
* error occurs retrieving the defects from the server.
*/
public void errorReceivingData(String error) {
JOptionPane.showMessageDialog(view, "An error occurred retrieving defects from the server. " + error,
"Error Communicating with Server", JOptionPane.ERROR_MESSAGE);
}
} |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This file may have been modified by The KubeAdmiral Authors
("KubeAdmiral Modifications"). All KubeAdmiral Modifications
are Copyright 2023 The KubeAdmiral Authors.
*/
package healthcheck
import (
"net/http"
"sync"
"sigs.k8s.io/controller-runtime/pkg/healthz"
)
type MutableHealthCheckHandler struct {
handler http.Handler
mu sync.RWMutex
readyzHandler *healthz.Handler
livezHandler *healthz.Handler
}
func NewMutableHealthCheckHandler() *MutableHealthCheckHandler {
h := &MutableHealthCheckHandler{
mu: sync.RWMutex{},
readyzHandler: &healthz.Handler{Checks: map[string]healthz.Checker{}},
livezHandler: &healthz.Handler{Checks: map[string]healthz.Checker{}},
}
mux := http.NewServeMux()
mux.Handle("/readyz", http.StripPrefix("/readyz", h.readyzHandler))
mux.Handle("/readyz/", http.StripPrefix("/readyz/", h.readyzHandler))
mux.Handle("/livez", http.StripPrefix("/livez", h.livezHandler))
mux.Handle("/livez/", http.StripPrefix("/livez/", h.livezHandler))
h.handler = mux
return h
}
func (h *MutableHealthCheckHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
h.mu.RLock()
defer h.mu.RUnlock()
h.handler.ServeHTTP(writer, request)
}
func (h *MutableHealthCheckHandler) AddReadyzChecker(name string, checker healthz.Checker) {
h.mu.Lock()
defer h.mu.Unlock()
h.readyzHandler.Checks[name] = checker
}
func (h *MutableHealthCheckHandler) AddLivezChecker(name string, checker healthz.Checker) {
h.mu.Lock()
defer h.mu.Unlock()
h.livezHandler.Checks[name] = checker
}
func (h *MutableHealthCheckHandler) RemoveReadyzChecker(name string) {
h.mu.Lock()
defer h.mu.Unlock()
delete(h.readyzHandler.Checks, name)
}
func (h *MutableHealthCheckHandler) RemoveLivezChecker(name string) {
h.mu.Lock()
defer h.mu.Unlock()
delete(h.livezHandler.Checks, name)
}
var _ http.Handler = &MutableHealthCheckHandler{} |
/****************************************************************
* 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.james.jmap.cassandra.filtering;
import java.util.List;
import java.util.Objects;
import org.apache.james.jmap.api.filtering.Rule;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
public class RuleDTO {
public static class ConditionDTO {
public static ConditionDTO from(Rule.Condition condition) {
return new ConditionDTO(
condition.getField().asString(),
condition.getComparator().asString(),
condition.getValue());
}
private final String field;
private final String comparator;
private final String value;
@JsonCreator
public ConditionDTO(@JsonProperty("field") String field,
@JsonProperty("comparator") String comparator,
@JsonProperty("value") String value) {
this.field = field;
this.comparator = comparator;
this.value = value;
}
public String getField() {
return field;
}
public String getComparator() {
return comparator;
}
public String getValue() {
return value;
}
public Rule.Condition toCondition() {
return Rule.Condition.of(
Rule.Condition.Field.of(field),
Rule.Condition.Comparator.of(comparator),
value);
}
@Override
public final boolean equals(Object o) {
if (o instanceof ConditionDTO) {
ConditionDTO other = (ConditionDTO) o;
return Objects.equals(this.field, other.field)
&& Objects.equals(this.comparator, other.comparator)
&& Objects.equals(this.value, other.value);
}
return false;
}
@Override
public final int hashCode() {
return Objects.hash(field, comparator, value);
}
}
public static class ActionDTO {
public static class AppendInMailboxesDTO {
public static AppendInMailboxesDTO from(Rule.Action.AppendInMailboxes appendInMailboxes) {
return new AppendInMailboxesDTO(appendInMailboxes.getMailboxIds());
}
@JsonCreator
public AppendInMailboxesDTO(@JsonProperty("mailboxIds") List<String> mailboxIds) {
this.mailboxIds = ImmutableList.copyOf(mailboxIds);
}
private final List<String> mailboxIds;
public List<String> getMailboxIds() {
return mailboxIds;
}
public Rule.Action.AppendInMailboxes toAppendInMailboxes() {
return Rule.Action.AppendInMailboxes.withMailboxIds(mailboxIds);
}
@Override
public final boolean equals(Object o) {
if (o instanceof AppendInMailboxesDTO) {
AppendInMailboxesDTO that = (AppendInMailboxesDTO) o;
return Objects.equals(this.mailboxIds, that.mailboxIds);
}
return false;
}
@Override
public final int hashCode() {
return Objects.hash(mailboxIds);
}
}
public static ActionDTO from(Rule.Action action) {
return new ActionDTO(AppendInMailboxesDTO.from(action.getAppendInMailboxes()));
}
@JsonCreator
public ActionDTO(@JsonProperty("appendIn") AppendInMailboxesDTO appendIn) {
this.appendIn = appendIn;
}
private final AppendInMailboxesDTO appendIn;
public AppendInMailboxesDTO getAppendIn() {
return appendIn;
}
public Rule.Action toAction() {
return Rule.Action.of(appendIn.toAppendInMailboxes());
}
@Override
public final boolean equals(Object o) {
if (o instanceof ActionDTO) {
ActionDTO actionDTO = (ActionDTO) o;
return Objects.equals(this.appendIn, actionDTO.appendIn);
}
return false;
}
@Override
public final int hashCode() {
return Objects.hash(appendIn);
}
}
public static ImmutableList<Rule> toRules(List<RuleDTO> ruleDTOList) {
Preconditions.checkNotNull(ruleDTOList);
return ruleDTOList.stream()
.map(RuleDTO::toRule)
.collect(ImmutableList.toImmutableList());
}
public static ImmutableList<RuleDTO> from(List<Rule> rules) {
Preconditions.checkNotNull(rules);
return rules.stream()
.map(RuleDTO::from)
.collect(ImmutableList.toImmutableList());
}
public static RuleDTO from(Rule rule) {
return new RuleDTO(rule.getId().asString(),
rule.getName(),
ConditionDTO.from(rule.getCondition()),
ActionDTO.from(rule.getAction()));
}
private final String id;
private final String name;
private final ConditionDTO conditionDTO;
private final ActionDTO actionDTO;
@JsonCreator
public RuleDTO(@JsonProperty("id") String id,
@JsonProperty("name") String name,
@JsonProperty("condition") ConditionDTO conditionDTO,
@JsonProperty("action") ActionDTO actionDTO) {
this.name = name;
this.conditionDTO = conditionDTO;
this.actionDTO = actionDTO;
Preconditions.checkNotNull(id);
this.id = id;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public ConditionDTO getCondition() {
return conditionDTO;
}
public ActionDTO getAction() {
return actionDTO;
}
public Rule toRule() {
return Rule.builder()
.id(Rule.Id.of(id))
.name(name)
.condition(conditionDTO.toCondition())
.name(name)
.action(actionDTO.toAction())
.build();
}
@Override
public final boolean equals(Object o) {
if (o instanceof RuleDTO) {
RuleDTO ruleDTO = (RuleDTO) o;
return Objects.equals(this.id, ruleDTO.id)
&& Objects.equals(this.name, ruleDTO.name)
&& Objects.equals(this.conditionDTO, ruleDTO.conditionDTO)
&& Objects.equals(this.actionDTO, ruleDTO.actionDTO);
}
return false;
}
@Override
public final int hashCode() {
return Objects.hash(id, name, conditionDTO, actionDTO);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("id", id)
.toString();
}
} |
syntax = "proto3";
option go_package = "proto/ratelimiter";
package ratelimiter;
import "google/api/annotations.proto";
service RateLimitService {
rpc CreateRateLimiter (CreateRateLimiterRequest) returns (RateLimiter){
option (google.api.http) = {
post: "/ratelimiter"
body: "rateLimiter"
};
}
rpc GetRateLimiter (GetRateLimiterRequest) returns (RateLimiter){
option (google.api.http) = {
get: "/ratelimiter/{id}"
};
}
rpc GetAllRateLimiters(EmptyRequest) returns (ListOfRateLimiters){
option (google.api.http) = {
get: "/ratelimiter"
};
}
rpc UpdateRateLimiter (UpdateRateLimiterRequest) returns (RateLimiter){
option (google.api.http) = {
put: "/ratelimiter"
body: "rateLimiter"
};
}
rpc DeleteRateLimiter (DeleteRateLimiterRequest) returns (DeleteRateLimiterResponse){
option (google.api.http) = {
delete: "/ratelimiter/{id}"
};
}
rpc CanRateLimiterAllowRequest(AllowRequest) returns (AllowResponse){
option (google.api.http) = {
get: "/ratelimiter/allow/{id}"
};
}
}
message RateLimiter {
string id = 1;
string name = 2;
string userName = 3;
string type = 4;
int64 reqPerSec = 5;
int64 burst = 6;
}
message EmptyRequest{}
message ListOfRateLimiters{
repeated RateLimiter limiters = 1;
}
message CreateRateLimiterRequest{
RateLimiter rateLimiter = 1;
}
message UpdateRateLimiterRequest{
RateLimiter rateLimiter = 1;
}
message GetRateLimiterRequest {
string id = 1;
}
message DeleteRateLimiterRequest {
string id = 1;
}
message DeleteRateLimiterResponse{
bool deleted = 1;
}
message AllowRequest {
string id = 1;
}
message AllowResponse{
bool allowed = 1;
} |
= Data Affinity
Data affinity ensures that related entries exist on the same member. If related data is on the same member, operations can
be executed without the cost of extra network calls and extra wire data. This feature is provided by using the same partition keys for related data.
== PartitionAware
**Co-location of related data and computation**
Hazelcast has a standard way of finding out which member owns/manages each key object.
The following operations are routed to the same member, since all them are operating based on the same key `"key1"`.
[source,java]
----
HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
Map mapA = hazelcastInstance.getMap( "mapA" );
Map mapB = hazelcastInstance.getMap( "mapB" );
Map mapC = hazelcastInstance.getMap( "mapC" );
// since map names are different, operation will be manipulating
// different entries, but the operation will take place on the
// same member since the keys ("key1") are the same
mapA.put( "key1", value );
mapB.get( "key1" );
mapC.remove( "key1" );
// lock operation will still execute on the same member
// of the cluster since the key ("key1") is same
hazelcastInstance.getLock( "key1" ).lock();
// distributed execution will execute the 'runnable' on the
// same member since "key1" is passed as the key.
hazelcastInstance.getExecutorService().executeOnKeyOwner( runnable, "key1" );
----
When the keys are the same, entries are stored on the same member.
But we sometimes want to have related entries stored on the same member, such as a customer and his/her order entries.
We would have a customers map with customerId as the key and an orders map with orderId as the key.
Since customerId and orderId are different keys, a customer and
his/her orders may fall into different members in your cluster. So how can we have them stored on the same member?
We create an affinity between customer and orders. If we make them part of the same partition then
these entries will be co-located. We achieve this by making `orderKey` s `PartitionAware`.
[source,java]
----
include::ROOT:example$/performance/OrderKey.java[tag=orderkey]
----
Notice that OrderKey implements `PartitionAware` and that `getPartitionKey()` returns the `customerId`.
These make sure that the `Customer` entry and its ``Order``s are stored on the same member.
[source,java]
----
HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
Map mapCustomers = hazelcastInstance.getMap( "customers" );
Map mapOrders = hazelcastInstance.getMap( "orders" );
// create the customer entry with customer id = 1
mapCustomers.put( 1, customer );
// now create the orders for this customer
mapOrders.put( new OrderKey( 21, 1 ), order );
mapOrders.put( new OrderKey( 22, 1 ), order );
mapOrders.put( new OrderKey( 23, 1 ), order );
----
Assume that you have a customers map where `customerId` is the key and the customer object is the value.
You want to remove one of the customer orders and return the number of remaining orders.
Here is how you would normally do it.
[source,java]
----
public static int removeOrder( long customerId, long orderId ) throws Exception {
IMap<Long, Customer> mapCustomers = instance.getMap( "customers" );
IMap mapOrders = hazelcastInstance.getMap( "orders" );
mapCustomers.lock( customerId );
mapOrders.remove( new OrderKey(orderId, customerId) );
Set orders = orderMap.keySet(Predicates.equal( "customerId", customerId ));
mapCustomers.unlock( customerId );
return orders.size();
}
----
There are a couple of things you should consider.
* There are four distributed operations there: lock, remove, keySet, unlock. Can you reduce
the number of distributed operations?
* The customer object may not be that big, but can you not have to pass that object through the
wire? Think about a scenario where you set order count to the customer object for fast access, so you
should do a get and a put, and as a result, the customer object is passed through the wire twice.
Instead, why not move the computation over to the member (JVM) where your customer data resides.
Here is how you can do this with distributed executor service.
. Send a `PartitionAware` `Callable` task.
. `Callable` does the deletion of the order right there and returns with the remaining
order count.
. Upon completion of the `Callable` task, return the result (remaining order count). You
do not have to wait until the task is completed; since distributed executions are asynchronous,
you can do other things in the meantime.
Here is an example code.
[source,java]
----
HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
public int removeOrder(long customerId, long orderId) throws Exception {
IExecutorService executorService = hazelcastInstance.getExecutorService("ExecutorService");
OrderDeletionTask task = new OrderDeletionTask(customerId, orderId);
Future<Integer> future = executorService.submit(task);
int remainingOrders = future.get();
return remainingOrders;
}
public static class OrderDeletionTask
implements Callable<Integer>, PartitionAware, Serializable, HazelcastInstanceAware {
private long orderId;
private long customerId;
private HazelcastInstance hazelcastInstance;
public OrderDeletionTask() {
}
public OrderDeletionTask(long customerId, long orderId) {
this.customerId = customerId;
this.orderId = orderId;
}
@Override
public Integer call() {
IMap<Long, Customer> customerMap = hazelcastInstance.getMap("customers");
IMap<OrderKey, Order> orderMap = hazelcastInstance.getMap("orders");
customerMap.lock(customerId);
Predicate predicate = Predicates.equal("customerId", customerId);
Set<OrderKey> orderKeys = orderMap.localKeySet(predicate);
int orderCount = orderKeys.size();
for (OrderKey key : orderKeys) {
if (key.orderId == orderId) {
orderCount--;
orderMap.delete(key);
}
}
customerMap.unlock(customerId);
return orderCount;
}
@Override
public Object getPartitionKey() {
return customerId;
}
@Override
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
this.hazelcastInstance = hazelcastInstance;
}
}
----
The following are the benefits of doing the same operation with distributed `ExecutorService` based on the key:
* only one distributed execution (`executorService.submit(task)`), instead of four
* less data is sent over the wire
* less lock duration, i.e., higher concurrency, for the `Customer` entry since
lock/update/unlock cycle is done locally (local to the customer data)
[[partitioningstrategy]]
== Partitioning Strategies
Another way of storing the related data on the same location is using/implementing
the class `PartitioningStrategy`. Normally (if no partitioning strategy is defined),
Hazelcast finds the partition of a key first by converting the object to binary and then by hashing this binary.
If a partitioning strategy is defined, Hazelcast injects the key to the strategy and
the strategy returns an object out of which the partition is calculated by hashing it.
Hazelcast offers the following out-of-the-box partitioning strategies:
* `DefaultPartitioningStrategy`: Default strategy. It checks whether the key implements `PartitionAware`.
If it implements, the object is converted to binary and then hashed, to find the partition of the key.
* `StringPartitioningStrategy`: Works only for string keys. It uses the string after `@` character as the partition ID.
For example, if you have two keys `ordergroup1@region1` and `customergroup1@region1`,
both `ordergroup1` and `customergroup1` fall into the partition where `region1` is located.
* `StringAndPartitionAwarePartitioningStrategy`: Works as the combination of the above two strategies.
If the key implements `PartitionAware`, it works like the `DefaultPartitioningStrategy`.
If it is a string key, it works like the `StringPartitioningStrategy`.
You can configure the partitioning strategies:
* for each map, or
* globally (applied to all the data structures in your cluster).
NOTE: The per map and global partitioning strategies are supported on the member side.
Hazelcast Java clients only support the global strategy.
=== Per Map Partitioning Strategy Configuration
The following shows example configurations. For the declarative configurations (XML, YAML), you use the `partition-strategy` element.
For the programmatic approach, you use the `setPartitioningStrategyClass()` method.
[tabs]
====
XML::
+
--
[source,xml]
----
<hazelcast>
...
<map name="myMap">
<partition-strategy>
com.hazelcast.partition.strategy.StringAndPartitionAwarePartitioningStrategy
///OR
///YourCustomPartitioningStrategyClass <1>
</partition-strategy>
</map>
...
</hazelcast>
----
--
YAML::
+
[source,yaml]
----
hazelcast:
map:
myMap:
partition-strategy: com.hazelcast.partition.strategy.StringAndPartitionAwarePartitioningStrategy
# OR
# partition-strategy: YourCustomPartitioningStrategyClass <1>
----
Java Member API::
+
[source,java]
----
Config config = new Config();
MapConfig mapConfig = config.getMapConfig("myMap");
PartitioningStrategyConfig psConfig = mapConfig.getPartitioningStrategyConfig();
psConfig.setPartitioningStrategyClass( "StringAndPartitionAwarePartitioningStrategy" );
// OR
psConfig.setPartitioningStrategy(YourCustomPartitioningStrategy); <1>
...
----
====
<1> You can define your own partition strategy by implementing the class https://docs.hazelcast.org/docs/{full-version}/javadoc/com/hazelcast/partition/PartitioningStrategy.html[`PartitioningStrategy`]. To enable your implementation, add the full class name to your Hazelcast configuration using either
the declarative or programmatic approach, as exemplified above.
NOTE: All the cluster members must have the same partitioning strategy configurations.
=== Global Partitioning Strategy Configuration
You can also set a global strategy which is applied to all the data structures in your cluster.
This can be done by setting the `hazelcast.partitioning.strategy.class` property.
The following shows example configurations.
[tabs]
====
XML::
+
--
[source,xml]
----
<hazelcast>
...
<properties>
<property name="hazelcast.partitioning.strategy.class">
com.hazelcast.partition.strategy.StringAndPartitionAwarePartitioningStrategy
</property>
</properties>
...
</hazelcast>
----
--
YAML::
+
[source,yaml]
----
hazelcast:
properties:
hazelcast.partitioning.strategy.class: com.hazelcast.partition.strategy.StringAndPartitionAwarePartitioningStrategy
----
Java Member/Client API::
+
[source,java]
----
Config config = new Config();
config.setProperty( "hazelcast.partitioning.strategy.class", "com.hazelcast.partition.strategy.StringAndPartitionAwarePartitioningStrategy" );
----
====
You can specify the aforementioned out-of-the-box strategies or your custom
partitioning strategy.
You can also use other system property configuring options as explained in the
xref:configuration:configuring-with-system-properties.adoc[Configuring with System Properties section].
=== Attribute Based Partitioning Strategy
Attribute based partitioning (`AttributePartitioningStrategy`) is a strategy such that the map entries having the same partition keys live in the same cluster member.
It can be configured per map only, and cannot be used globally.
To configure this strategy for a map, you can provide the `partitioning-attributes` configuration property under the `map` element. If this property is provided, it will automatically supersede `partitioning-strategy` (if any one of them is configured as explained in the previous sections) and the strategy will be set to `AttributePartitioningStrategy`. Note that, when provided, `partitioning-attributes` should contain at least one attribute name.
Dynamic configuration is supported, which means that you can add or change the configuration of this strategy without restarting the cluster.
It is important to note that `AttributePartitioningStrategy` is ONLY supported on the member-side.
Overall, `AttributePartitioningStrategy` is a powerful tool for partitioning data across a cluster in Hazelcast. By following the guidelines above, you can easily configure it for your specific use case.
==== Example Usage
Here is an example flow that shows how attribute based partitioning strategy works.
This example assumes that you have a map named `myMap` of type `IMap<Person, Long>` where `Person` has `{ public Long id; public String name; public Long orgId; }`.
. Start a cluster by providing a map configuration that includes the attributes `id` and `name` (or you can add this configuration while a cluster is running).
+
[tabs]
====
XML::
+
--
[source,xml]
----
<hazelcast>
<map name="myMap">
<partition-attributes>
<attribute>id</attribute>
<attribute>name</attribute>
</partition-attributes>
...
</map>
</hazelcast>
----
--
YAML::
+
[source,yaml]
----
hazelcast:
map:
myMap:
partition-attributes:
- name: "id"
- name: "name"
...
----
====
. When data is added to the map using the `put` method, the strategy configured for this map is used to determine the partition ID of the new entry. Specifically, the `AttributePartitioningStrategy` extracts the `id` and `name` attributes from the given object, and creates an `Object[]` array out of them. This partition key is then used by the member logic to calculate the partition ID of the new entry.
+
To give an example, assume that you have a key/value pair `Person(1, "John", 3), 1`, where `id`=`1`, `name`=`John`, and `orgId`=`3`.
+
Add this map entry using `myMap.put(new Person(1, "John", 3), 1);`. The key of this entry (`new Person(1, "John", 3)`) will be passed to the configured strategy.
. The `AttributePartitioningStrategy` that is configured for this map takes the key and only extracts the `id` and `name` attributes from it (`1` and `John`), and creates the {1, "John"} partition key.
. The member logic then calculates the partition ID out of the `{1, "John"}` partition key, and puts the entry to the cluster member which has the calculated partition ID.
. A new entry having the same partition key will be put to the same cluster member.
When you want to query for an entry with the key `new Person(1, "John", 3)`, the exact same turn of events described above occurs, except the operation will be `get` instead of `put`. |
from .. import constants, logger
from . import base_classes, api
class Object(base_classes.BaseNode):
"""Class that wraps an object node"""
def __init__(self, node, parent=None, type=None):
logger.debug("Object().__init__(%s)", node)
base_classes.BaseNode.__init__(self, node, parent=parent, type=type)
if self.node:
self._node_setup()
else:
self._root_setup()
@property
def data(self):
"""
:return: returns the data block of the node
"""
return api.data(self.node)
def _init_camera(self):
"""Initialize camera attributes"""
logger.debug("Object()._init_camera()")
self[constants.FAR] = api.camera.far(self.data)
self[constants.NEAR] = api.camera.near(self.data)
if self[constants.TYPE] == constants.PERSPECTIVE_CAMERA:
self[constants.ASPECT] = api.camera.aspect(self.data)
self[constants.FOV] = api.camera.fov(self.data)
elif self[constants.TYPE] == constants.ORTHOGRAPHIC_CAMERA:
self[constants.LEFT] = api.camera.left(self.data)
self[constants.RIGHT] = api.camera.right(self.data)
self[constants.TOP] = api.camera.top(self.data)
self[constants.BOTTOM] = api.camera.bottom(self.data)
#@TODO: need more light attributes. Some may have to come from
# custom blender attributes.
def _init_light(self):
"""Initialize light attributes"""
logger.debug("Object()._init_light()")
self[constants.COLOR] = api.light.color(self.data)
self[constants.INTENSITY] = api.light.intensity(self.data)
if self[constants.TYPE] != constants.DIRECTIONAL_LIGHT:
self[constants.DISTANCE] = api.light.distance(self.data)
if self[constants.TYPE] == constants.SPOT_LIGHT:
self[constants.ANGLE] = api.light.angle(self.data)
def _init_mesh(self):
"""Initialize mesh attributes"""
logger.debug("Object()._init_mesh()")
mesh = api.object.mesh(self.node, self.options)
node = self.scene.geometry(mesh)
if node:
self[constants.GEOMETRY] = node[constants.UUID]
else:
msg = "Could not find Geometry() node for %s"
logger.error(msg, self.node)
def _node_setup(self):
"""Parse common node attributes of all objects"""
logger.debug("Object()._node_setup()")
self[constants.NAME] = api.object.name(self.node)
transform = api.object.matrix(self.node, self.options)
matrix = []
for col in range(0, 4):
for row in range(0, 4):
matrix.append(transform[row][col])
self[constants.MATRIX] = matrix
self[constants.VISIBLE] = api.object.visible(self.node)
self[constants.TYPE] = api.object.node_type(self.node)
if self.options.get(constants.MATERIALS):
logger.info("Parsing materials for %s", self.node)
material_name = api.object.material(self.node)
if material_name:
logger.info("Material found %s", material_name)
material_inst = self.scene.material(material_name)
self[constants.MATERIAL] = material_inst[constants.UUID]
else:
logger.info("%s has no materials", self.node)
casts_shadow = (constants.MESH,
constants.DIRECTIONAL_LIGHT,
constants.SPOT_LIGHT)
if self[constants.TYPE] in casts_shadow:
logger.info("Querying shadow casting for %s", self.node)
self[constants.CAST_SHADOW] = \
api.object.cast_shadow(self.node)
if self[constants.TYPE] == constants.MESH:
logger.info("Querying shadow receive for %s", self.node)
self[constants.RECEIVE_SHADOW] = \
api.object.receive_shadow(self.node)
camera = (constants.PERSPECTIVE_CAMERA,
constants.ORTHOGRAPHIC_CAMERA)
lights = (constants.AMBIENT_LIGHT,
constants.DIRECTIONAL_LIGHT,
constants.AREA_LIGHT, constants.POINT_LIGHT,
constants.SPOT_LIGHT, constants.HEMISPHERE_LIGHT)
if self[constants.TYPE] == constants.MESH:
self._init_mesh()
elif self[constants.TYPE] in camera:
self._init_camera()
elif self[constants.TYPE] in lights:
self._init_light()
if self.options.get(constants.HIERARCHY, False):
for child in api.object.children(self.node, self.scene.valid_types):
if not self.get(constants.CHILDREN):
self[constants.CHILDREN] = [Object(child, parent=self)]
else:
self[constants.CHILDREN].append(Object(child, parent=self))
def _root_setup(self):
"""Applies to a root/scene object"""
logger.debug("Object()._root_setup()")
self[constants.MATRIX] = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0,
1, 0, 0, 0, 0, 1] |
/**
* The MIT License (MIT)
*
* Igor Zinken 2023 - https://www.igorski.nl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
<template>
<div class="pattern-order-list">
<label
class="pattern-order-list__label"
v-t="'patternOrder'"
></label>
<button
:title="$t('previous')"
:disabled="!canNavBack"
type="button"
class="pattern-order-list__navigate-button pattern-order-list__navigate-button_left"
@click="handleBackClick()"
><</button>
<pattern-order-entry
v-for="(entry) in visibleEntries"
:key="`e_${entry.name}_${entry.index}`"
:name="entry.name"
:index="entry.index"
:active="entry.active"
:editing="entry.editing"
@select="handleEntryClick( $event )"
@toggle-edit-mode="toggleEditMode( $event, entry )"
>
<template v-if="entry.editing">
<button
type="button"
v-t="'repeat'"
class="pattern-order-entry__context-menu-button"
@click="repeatPattern( entry )"
></button>
<button
type="button"
v-t="'delete'"
:disabled="!canDelete"
class="pattern-order-entry__context-menu-button"
@click="deletePattern( entry )"
></button>
</template>
</pattern-order-entry>
<button
:title="$t('next')"
:disabled="!canNavNext"
type="button"
class="pattern-order-list__navigate-button pattern-order-list__navigate-button_right"
@click="handleNextClick()"
>></button>
<button
:title="$t('edit')"
type="button"
class="pattern-order-list__edit-button"
@click="handleEditClick()"
><img src="@/assets/icons/icon-pencil.svg" :alt="$t('edit')" /></button>
</div>
</template>
<script lang="ts">
import { mapState, mapGetters, mapMutations, type Store } from "vuex";
import Actions from "@/definitions/actions";
import ModalWindows from "@/definitions/modal-windows";
import createAction from "@/model/factories/action-factory";
import type { EffluxPatternOrder } from "@/model/types/pattern-order";
import PatternOrderUtil from "@/utils/pattern-order-util";
import PatternOrderEntry from "./components/pattern-order-entry.vue";
import messages from "./messages.json";
type WrappedPatternOrderEntry = {
pattern: number; // index of pattern in pattern list
name: string;
index: number; // index of pattern within order list
active: boolean;
editing: boolean;
};
const TOTAL_PER_PAGE = 5;
export default {
i18n: { messages },
components: {
PatternOrderEntry,
},
data: () => ({
editableEntry: -1,
offset: 0,
}),
computed: {
...mapState({
activeSong : state => state.song.activeSong,
}),
...mapGetters([
"activeOrderIndex",
]),
entries(): WrappedPatternOrderEntry[] {
return this.activeSong.order
.map(( pattern: number, index: number ) => ({
pattern,
index,
name: this.activeSong.patterns[ pattern ].name,
active: this.activeOrderIndex === index,
editing: this.editableEntry === index,
}));
},
visibleEntries(): WrappedPatternOrderEntry[] {
const sliceOffset = this.visibleRangeStart;
return this.entries.slice( sliceOffset, sliceOffset + TOTAL_PER_PAGE );
},
canDelete(): boolean {
return this.entries.length > 1;
},
canNavBack(): boolean {
return this.offset > 0;
},
canNavNext(): boolean {
return ( this.visibleRangeStart + TOTAL_PER_PAGE ) < this.entries.length;
},
visibleRangeStart(): number {
return this.offset * TOTAL_PER_PAGE;
},
},
watch: {
activeOrderIndex( value: number ) {
if ( value < this.visibleRangeStart || value >= this.visibleRangeStart + TOTAL_PER_PAGE ) {
this.offset = Math.floor( value / TOTAL_PER_PAGE );
}
},
},
methods: {
...mapMutations([
"gotoPattern",
"openModal",
"replacePatternOrder",
"setActiveOrderIndex",
]),
repeatPattern( entry: WrappedPatternOrderEntry ): void {
const newOrder = [ ...this.activeSong.order ];
const tail = newOrder.splice( entry.index + 1 );
this.updateOrder([ ...newOrder, entry.pattern, ...tail ]);
this.stopEditing();
},
deletePattern( entry: WrappedPatternOrderEntry ): void {
this.updateOrder( PatternOrderUtil.removePatternAtIndex( this.activeSong.order, entry.index ) );
this.stopEditing();
},
toggleEditMode( isEditing: boolean, entry: WrappedPatternOrderEntry ): void {
if ( !isEditing ) {
return this.stopEditing();
}
this.editableEntry = entry.index;
},
stopEditing(): void {
this.editableEntry = -1;
},
updateOrder( order: EffluxPatternOrder ): void {
createAction( Actions.UPDATE_PATTERN_ORDER, { store: this.$store, order });
if ( this.activeOrderIndex >= order.length ) {
this.setActiveOrderIndex( order.length - 1 );
}
},
handleEditClick(): void {
this.openModal( ModalWindows.PATTERN_ORDER_WINDOW );
},
handleBackClick(): void {
this.offset = Math.max( 0, this.offset - 1 );
},
handleNextClick(): void {
this.offset += 1;
},
handleEntryClick( orderIndex: number ): void {
this.gotoPattern({ orderIndex, song: this.activeSong });
},
}
};
</script>
<style lang="scss" scoped>
@import "@/styles/mixins";
.pattern-order-list {
display: flex;
align-items: center;
&__label {
margin-right: $spacing-small;
@include toolFont();
}
&__navigate-button {
@include toolFont();
&_left {
margin-right: $spacing-xsmall;
}
&_right {
margin-left: $spacing-xxsmall;
}
}
&__edit-button {
@include button();
padding: $spacing-xsmall $spacing-small;
margin: $spacing-small;
}
}
</style> |
package handler
import (
"encoding/json"
"net/http"
"github.com/leonardfreitas/golang-cloud-run/internal/usecase"
)
type GetPlaceTemperaturesHandler struct {
uc usecase.GetPlaceForecast
}
func NewGetPlaceTemperaturesHandler(uc usecase.GetPlaceForecast) GetPlaceTemperaturesHandler {
return GetPlaceTemperaturesHandler{
uc: uc,
}
}
func (h *GetPlaceTemperaturesHandler) Handle(w http.ResponseWriter, r *http.Request) {
cep := r.URL.Query().Get("cep")
output, err := h.uc.Execute(cep)
if err != nil {
if err == usecase.ErrInvalidInput {
http.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
if err == usecase.ErrPostalCodeNotFound || err == usecase.ErrWeatherNotFound {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = json.NewEncoder(w).Encode(output)
if err == usecase.ErrPostalCodeNotFound || err == usecase.ErrWeatherNotFound {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
} |
package com.example.toy_jetpack
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
data class Message(
val author: String,
val body: String
)
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MessageCard(Message("Android", "Jetpack Compose"))
}
}
}
//
@Composable
fun MessageCard(msg: Message) {
Row(modifier = Modifier.padding(all = 8.dp)) {
Image(
painter = painterResource(R.drawable.test_image),
contentDescription = "Contact profile picture",
modifier = Modifier
.size(40.dp)//크기
.clip(CircleShape)//모양 둥글게!
)
Spacer(modifier = Modifier.width(8.dp))//플러터에
Column {
Text(text = msg.author)
Spacer(modifier = Modifier.height(4.dp))//띄우기(간격 생성)
Text(text = msg.body)
}
}
}
@Preview
@Composable
fun PreviewMessageCard() {
MessageCard(
msg = Message(
"Colleague",
"Hey, take a look at Jetpack Compose, it's great!"
)
)
} |
# Todo List
**Todo List** is an App that lets Users keep records of tasks they wish to accomplish.
# Description
The ToDo-List App is an App that can help Users to organize and keep track of their daily Tasks and Goals. There is also the option to add Reminders for specific Tasks that the User wishes to accomplish. This Project also demonstrates the use of some of the core libraries in Android such as StateFlows, SharedPreferences from the Preferences Manager, viewBinding and so on.
# Screenshots
<img src="FirstPicture.jpg" width=400> <img src="SecondPicture.jpg" width=400>
<img src="ThirdPicture.jpg" width=400> <img src="FourthPicture.jpg" width=400>
## Architecture
- The Architecture used in this Project is the [MVC Architecture](https://www.freecodecamp.org/news/the-model-view-controller-pattern-mvc-architecture-and-frameworks-explained/)
## About
- This App allows for the Simple creation of Tasks.
- You can set the Date and Time for a being Task created.
- User can set Reminders for one or more Tasks.
- Tasks can be easily searched for, sorted and hidden.
### Developed With
- [Fragments](https://developer.android.com/guide/fragments) - The fragments represents a portion of our App's UI.
- [LiveData](https://developer.android.com/topic/libraries/architecture/livedata) - LiveData is an observable data holder class.
- [ViewBinding](https://developer.android.com/topic/libraries/view-binding) - View binding is a feature that allows you to more easily write code that interacts with views.
- [RecyclerView.Adapter](https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.Adapter) - Adapters provide a binding from an app-specific data set to views that are displayed within a RecyclerView.
- [Room](https://developer.android.com/training/data-storage/room) - Room Database used for storing data.
- [Notifications](https://developer.android.com/guide/topics/ui/notifiers/notifications) - A notification is a message that Android displays outside your app's UI to provide the user with reminders.
- [AlarmManager](https://developer.android.com/reference/android/app/AlarmManager) - This is a class that provides access to alarm system services.
- [Flows](https://developer.android.com/kotlin/flow) - Flows is a DataType in Kotlin that can be used to emit multiple values sequentially.
- [JetPackDataStore](https://medium.com/androiddevelopers/introduction-to-jetpack-datastore-3dc8d74139e7) - DataStore is a Jetpack data storage library that provides a safe and consistent way to store small amounts of data. |
#region Copyright Notice & License Information
//
// Memory.cs
//
// Author:
// Matthew Davey <matthew.davey@dotbunny.com>
//
// Copyright (c) 2013 dotBunny Inc. (http://www.dotbunny.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace Hydrogen
{
/// <summary>
/// Additional static functions used to extend existing Memory support inside of Unity.
/// </summary>
public static class Memory
{
/// <summary>
/// Perform a deep Copy of the object.
/// </summary>
/// <returns>The copied object.</returns>
/// <typeparam name="T">Object Type</typeparam>
/// <param name="source">The object instance to copy.</param>
public static T Clone<T> (this T source)
{
if (!typeof(T).IsSerializable) {
throw new ArgumentException ("The type must be serializable.", "source");
}
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals (source, null)) {
return default(T);
}
IFormatter formatter = new BinaryFormatter ();
Stream stream = new MemoryStream ();
using (stream) {
formatter.Serialize (stream, source);
stream.Seek (0, SeekOrigin.Begin);
return (T)formatter.Deserialize (stream);
}
}
}
} |
import { ImageBackgroundProviderBase } from '$backgrounds/common-image/provider-base';
import { logger } from '$lib/logger';
import { storage } from '$stores/storage';
import pDebounce from 'p-debounce';
import type { Settings } from './settings';
import { minutesToMilliseconds, secondsToMilliseconds, millisecondsToSeconds } from 'date-fns';
import { PUBLIC_PEXELS_API_KEY } from '$env/static/public';
import { ImageResizeType } from '$lib/cdn';
const LocalSettingsKey = 'PexelsBackgroundProvider_LocalSettings';
const log = logger.getSubLogger({ prefix: ['Backgrounds', 'Pexels', 'Provider'] });
interface LocalSettings {
lastChangedTime: number;
lastSrc: string | undefined | null;
pool: string[];
currentPage: number;
totalPages: number;
}
function pickBetterUrl(src: string | undefined | null, node: HTMLElement, resizeType: ImageResizeType) {
if (!src) return '';
const width = node.clientWidth;
const height = node.clientHeight;
let resizeTypeArgValue: string;
switch (resizeType) {
case ImageResizeType.Contain:
resizeTypeArgValue = 'contain';
break;
case ImageResizeType.Cover:
resizeTypeArgValue = 'crop';
break;
default:
resizeTypeArgValue = 'crop';
break;
}
return `${src}?fit=${resizeTypeArgValue}&h=${height}&w=${width}`;
}
export class PexelsBackgroundProvider extends ImageBackgroundProviderBase<Settings> {
#localSettings: LocalSettings | undefined;
#unsubscribe!: () => void;
get canGoNext() {
return true;
}
async apply(abortSignal: AbortSignal) {
let initialized = false;
super.apply(abortSignal);
if (!this.#localSettings) {
this.#localSettings = (await storage.local.get(LocalSettingsKey))[LocalSettingsKey] || {
lastChangedTime: 0,
pool: [],
};
}
const interval = setInterval(() => {
this.#update(abortSignal);
}, minutesToMilliseconds(1));
const forceRefresh = () => {
this.#localSettings!.pool = [];
this.#localSettings!.currentPage = 0;
this.#localSettings!.totalPages = 0;
this.#localSettings!.lastChangedTime = 0;
};
const updateDeb = pDebounce(() => this.#update(abortSignal), secondsToMilliseconds(1));
const updateDebWithRefresh = () => {
if (initialized) {
forceRefresh();
updateDeb();
}
};
const searchTermUnsubsribe = this.settings.searchTerms.subscribe(updateDebWithRefresh);
const resizeTypeUnsubscribe = this.settings.resizeType.subscribe(() => updateDeb());
const resizeObserver = new ResizeObserver(() => updateDeb());
resizeObserver.observe(this.node);
this.#unsubscribe = () => {
clearInterval(interval);
searchTermUnsubsribe();
resizeTypeUnsubscribe();
resizeObserver.unobserve(this.node);
};
initialized = true;
this.#update(abortSignal);
}
forceUpdate(abortSignal: AbortSignal): void {
this.#localSettings!.lastChangedTime = 0;
this.#update(abortSignal);
}
readonly #update = pDebounce.promise(async (abortSignal: AbortSignal) => {
if (abortSignal.aborted) {
return;
}
this.setImage(pickBetterUrl(this.#localSettings!.lastSrc, this.node, this.settings.resizeType.value));
const timeSinceLastChange = millisecondsToSeconds(Date.now() - this.#localSettings!.lastChangedTime);
if (navigator.onLine && timeSinceLastChange >= this.settings.updateInterval.value) {
try {
if (this.#localSettings!.pool.length <= 0) {
if (this.#localSettings!.currentPage < this.#localSettings!.totalPages) {
this.#localSettings!.currentPage++;
} else {
this.#localSettings!.currentPage = 1;
}
const requestUri = this.settings.searchTerms.value
? `https://api.pexels.com/v1/search?query=${encodeURIComponent(this.settings.searchTerms.value)}&`
: 'https://api.pexels.com/v1/curated?';
const response = await fetch(`${requestUri}per_page=50&page=${this.#localSettings!.currentPage}`, {
headers: {
Authorization: PUBLIC_PEXELS_API_KEY,
},
signal: abortSignal,
}).then(r => r.json());
if (!Array.isArray(response?.photos)) {
throw new Error('Unexpected response');
}
this.#localSettings!.pool = response.photos.map((m: any) => m.src.original);
this.#localSettings!.totalPages = Math.ceil(response.total_results / response.per_page);
}
const randomIndex = Math.floor(Math.random() * this.#localSettings!.pool.length);
this.#localSettings!.lastSrc = this.#localSettings!.pool.splice(randomIndex, 1)[0];
this.#localSettings!.lastChangedTime = Date.now();
await storage.local.set({ [LocalSettingsKey]: this.#localSettings });
if (abortSignal.aborted) {
return;
}
this.setImage(pickBetterUrl(this.#localSettings!.lastSrc, this.node, this.settings.resizeType.value));
} catch (e) {
log.warn(e);
}
}
});
destroy() {
super.destroy();
this.#unsubscribe();
}
} |
import { ChangeEvent } from "react"
import { TaskType } from "./Todolist"
import { EditableSpan } from "./EditableSpan"
import IconButton from "@mui/material/IconButton"
import DeleteIcon from '@mui/icons-material/Delete'
import Checkbox from "@mui/material/Checkbox"
import styled from "styled-components"
import List from "@mui/material/List"
import ListItem from "@mui/material/ListItem"
type TasksListPropsType = {
todoListID: string
tasks: TaskType[]
removeTask: (todoListID: string, taskId: string) => void
changeStatus: (todoListID: string, taskID: string, newStatus: boolean) => void
changeTask: (taskID: string, title: string) => void
}
export const TasksList = (props: TasksListPropsType) => {
return (
props.tasks.length ?
<List
sx={{
width: '100%',
maxWidth: 300,
bgcolor: 'background.paper',
position: 'relative',
overflow: 'auto',
maxHeight: 250,
'& ul': { padding: 0 },
}}
>
{props.tasks.map((task) => {
const onClickRemoveTaskHandler = () => {
props.removeTask(props.todoListID, task.id)
}
const onChangeTaskStatusHandler = (e: ChangeEvent<HTMLInputElement>) => {
props.changeStatus(props.todoListID, task.id, e.currentTarget.checked)
}
const taskClass = task.isDone ? "task-is-done" : "task"
const changeTaskHandler = (title: string) => {
props.changeTask(task.id, title)
}
return (
<ListItem key={task.id} className={taskClass}>
<Checkbox
checked={task.isDone}
onChange={onChangeTaskStatusHandler}
/>
<EditableSpan title={task.title} changeTitle={changeTaskHandler} />
<IconButton aria-label="delete" size="small" onClick={onClickRemoveTaskHandler}>
<DeleteIcon fontSize="inherit" />
</IconButton>
</ListItem>
)
})}
</List>
:
<EmptyMessage>Your tasks list is empty!</EmptyMessage>
)
}
const EmptyMessage = styled.span`
margin: 15px 0;
` |
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AddBeans">
<include
android:id="@+id/ab_toolbar"
layout="@layout/toolbar_add"/>
<!-- TODO: add asterisks to the required fields + explanation -->
<ScrollView
android:id="@+id/ab_scroll_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:padding="5dp"
app:layout_constraintBottom_toTopOf="@+id/ab_bottom_buttons"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/ab_toolbar"
app:layout_constraintVertical_bias="1.0">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Name card -->
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp"
app:cardCornerRadius="10dp"
app:cardElevation="8dp">
<RelativeLayout
android:id="@+id/ab_name_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="7dp">
<TextView
android:id="@+id/ab_beans_name_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="4dp"
android:layout_marginBottom="4dp"
android:text="@string/ab_name_label"
android:textColor="@color/red"
android:textSize="24sp" />
<ImageButton
android:id="@+id/ab_add_photo_btn"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentEnd="true"
android:contentDescription="@string/add_photo"
android:src="@drawable/ic_add_photo" />
<EditText
android:id="@+id/ab_beans_name"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="@id/ab_beans_name_label"
android:hint="@string/ab_hint_name"
android:inputType="textPersonName"
android:padding="4dp"
android:textSize="22sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
<!-- Roaster Card -->
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp"
app:cardCornerRadius="10dp"
app:cardElevation="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="7dp">
<TextView
android:id="@+id/ab_roaster_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="7dp"
android:layout_marginTop="7dp"
android:layout_marginEnd="7dp"
android:layout_marginBottom="7dp"
android:text="@string/ab_roaster_label"
android:textColor="@color/red"
android:textSize="24sp" />
<EditText
android:id="@+id/ab_roaster_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ab_roaster_label"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:hint="@string/ab_hint_roaster"
android:textSize="20sp" />
<TextView
android:id="@+id/ab_roast_degree"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ab_roaster_name"
android:layout_marginStart="7dp"
android:layout_marginTop="7dp"
android:layout_marginEnd="7dp"
android:layout_marginBottom="7dp"
android:text="@string/ab_roast_degree_label"
android:textSize="24sp" />
<com.google.android.material.slider.Slider
android:id="@+id/ab_roast_degree_slider"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/ab_roast_degree"
android:stepSize="1"
android:valueFrom="0"
android:valueTo="5" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
<!-- Beans Specs Card -->
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp"
app:cardCornerRadius="10dp"
app:cardElevation="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="7dp">
<TextView
android:id="@+id/ab_beans_specs_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp"
android:text="@string/ab_beans_specs_label"
android:textSize="24sp" />
<CheckBox
android:id="@+id/ab_check_decaf"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ab_beans_specs_label"
android:text="@string/ab_decaf_label"
android:textSize="20sp"
android:layout_marginStart="10dp"/>
<CheckBox
android:id="@+id/ab_check_flavour"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ab_check_decaf"
android:text="@string/ab_flavour_check_label"
android:textSize="20sp"
android:layout_marginStart="10dp"/>
<EditText
android:id="@+id/ab_flavour"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ab_check_flavour"
android:enabled="false"
android:hint="@string/ab_hint_flavour"
android:inputType="textPersonName"
android:padding="4dp"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/ab_origin_label"
android:layout_below="@id/ab_flavour"
android:id="@+id/ab_origin_label"
android:textSize="24sp"
android:layout_marginStart="7dp"/>
<RadioGroup
android:id="@+id/ab_blend_origin_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ab_origin_label"
android:orientation="vertical">
<RadioButton
android:id="@+id/ab_blend_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:text="@string/ab_blend_label"
android:textSize="20sp" />
<RadioButton
android:id="@+id/ab_single_origin_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:text="@string/ab_single_origin_label"
android:textSize="20sp" />
<RadioButton
android:id="@+id/ab_blend_origin_unknown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:text="@string/ab_blend_unknown"
android:textSize="20sp" />
</RadioGroup>
</RelativeLayout>
</androidx.cardview.widget.CardView>
<!-- Shopping card -->
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp"
app:cardCornerRadius="10dp"
app:cardElevation="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="7dp">
<TextView
android:id="@+id/ab_shopping"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="7dp"
android:layout_marginTop="7dp"
android:layout_marginEnd="7dp"
android:layout_marginBottom="7dp"
android:text="@string/ab_shopping_label"
android:textSize="24sp" />
<TextView
android:id="@+id/ab_link_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ab_shopping"
android:layout_margin="7dp"
android:text="@string/ab_link_label"
android:textSize="22sp" />
<EditText
android:id="@+id/ab_link_to_store"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ab_link_label"
android:hint="@string/ab_hint_url"
android:inputType="textUri"
android:padding="4dp"
android:textSize="20sp" />
<TextView
android:id="@+id/ab_cost_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ab_link_to_store"
android:layout_margin="7dp"
android:text="@string/ab_cost_label"
android:textSize="22sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ab_cost_label"
android:orientation="horizontal">
<EditText
android:id="@+id/ab_cost"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:hint="@string/ab_hint_price"
android:inputType="numberDecimal"
android:padding="4dp"
android:textSize="20sp" />
<Spinner
android:id="@+id/ab_currency_spinner"
android:layout_width="100dp"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
<!-- Rating card -->
<!-- TODO: add visual stars for the rating -->
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp"
app:cardCornerRadius="10dp"
app:cardElevation="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="7dp">
<TextView
android:id="@+id/ab_rating_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp"
android:text="@string/ab_rating_label"
android:textSize="24sp" />
<RatingBar
android:id="@+id/ab_rating_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ab_rating_label"
android:numStars="5" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp"
app:cardCornerRadius="10dp"
app:cardElevation="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="7dp">
<TextView
android:id="@+id/ab_notes_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp"
android:text="@string/ab_notes_label"
android:textSize="24sp" />
<EditText
android:id="@+id/ab_notes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ab_notes_label"
android:hint="@string/ab_hint_notes"
android:inputType="textMultiLine"
android:minLines="3" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</ScrollView>
<GridLayout
android:id="@+id/ab_bottom_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnCount="2"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<Button
android:id="@+id/ab_cancel_button"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_columnWeight="50"
android:layout_gravity="center_horizontal"
android:text="@string/cancel" />
<Button
android:id="@+id/ab_save_button"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_columnWeight="50"
android:layout_gravity="center_horizontal"
android:text="@string/save" />
</GridLayout>
</androidx.constraintlayout.widget.ConstraintLayout> |
import React from "react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import GoogleLogo from "../images/google.jpg";
import FacebookLogo from "../images/facebook.png";
import Screen from "../components/Screen";
import AuthFinder from "../apis/AuthFinder";
function Login(props) {
const navigate = useNavigate();
const [auth, setAuth] = useState({
email: "",
password: "",
});
const [emailError, setEmailError] = useState("");
const [passwordError, setPasswordError] = useState("");
const [loginError, setLoginError] = useState("");
const authUrl =
process.env.NODE_ENV === "production"
? "/auth"
: "http://localhost:8800/auth";
function google() {
window.open(authUrl + "/google", "_self");
}
function facebook() {
window.open(authUrl + "/facebook", "_self");
}
function handleRegister() {
navigate("/register");
}
function handleChange(e) {
setAuth((prev) => ({ ...prev, [e.target.name]: e.target.value }));
}
async function handleSubmit() {
try {
setEmailError("");
setPasswordError("");
setLoginError("");
if (auth.email === "") {
setEmailError("Please enter an email!");
}
if (auth.password === "") {
setPasswordError("Please enter a password!");
}
if (auth.email === "" || auth.password === "") {
throw Error("One or more fields are empty!");
}
await AuthFinder.post("/local", auth, {
withCredentials: true,
});
window.location.reload();
} catch (err) {
if (err.response && err.response.status === 401) {
setLoginError("Invalid email or password");
} else {
console.log(err);
}
}
}
return (
<Screen>
<div className="loginContainer">
<h1 className="loginTitle">Choose a Login Method</h1>
<div className="loginFieldsWrapper">
<div className="loginLeft">
<div className="loginSocialButton loginGoogle" onClick={google}>
<img src={GoogleLogo} alt="" className="loginIcon" />
Google
</div>
<div className="loginSocialButton loginFacebook" onClick={facebook}>
<img src={FacebookLogo} alt="" className="loginIcon" />
Facebook
</div>
</div>
<div className="loginCenter">
<div className="centerLine" />
<div className="or">OR</div>
</div>
<div className="loginRight">
<small className="errorText">{loginError}</small>
<input
className="loginInput"
type="email"
placeholder="abc@gmail.com"
onChange={handleChange}
name="email"
/>
<small className="errorText">{emailError}</small>
<input
className="loginInput"
type="password"
placeholder="Password"
onChange={handleChange}
name="password"
/>
<small className="errorText">{passwordError}</small>
<button className="loginButton loginSubmit" onClick={handleSubmit}>
Login
</button>
<div className="horizontalLine" />
<button
className="loginButton loginRegister"
onClick={handleRegister}
>
Register
</button>
</div>
</div>
</div>
</Screen>
);
}
export default Login; |
RECURSION:
time : O(2^N)+more
space : O(N)
code :
int helper(int idx, int cap ,vector<int> &profit, vector<int> &weight){
if(idx==0){
if(cap%weight[0]==0)
return profit[0]*cap/weight[0];
return 0;
}
int notTake = helper(idx-1 ,cap , profit , weight);
int take = 0;
if(weight[idx]<=cap){
take = helper(idx , cap-weight[idx],profit , weight)+profit[idx];
}
return max(notTake , take);
}
int unboundedKnapsack(int n, int w, vector<int> &profit, vector<int> &weight){
return helper(n-1 , w , profit , weight);
}
---------------------------------------------------------------------------------
MEMOIZATION :
time : O(N*cap)
space : O(N*cap)+O(N)
code :
int helper(int idx, int cap ,vector<int> &profit, vector<int> &weight,vector<vector<int>>&dp){
if(idx==0){
if(cap%weight[0]==0)
return profit[0]*cap/weight[0];
return 0;
}
if(dp[idx][cap]!=-1)return dp[idx][cap];
int notTake = helper(idx-1 ,cap , profit , weight,dp);
int take = 0;
if(weight[idx]<=cap){
take = helper(idx , cap-weight[idx],profit , weight,dp)+profit[idx];
}
return dp[idx][cap] = max(notTake , take);
}
int unboundedKnapsack(int n, int w, vector<int> &profit, vector<int> &weight){
vector<vector<int>>dp(n,vector<int>(w+1,-1));
return helper(n-1 , w , profit , weight,dp);
}
---------------------------------------------------------------------------------
TABULATION:
time : O(N*cap)
space : O(N*cap)
code :
int unboundedKnapsack(int n, int w, vector<int> &profit, vector<int> &weight){
vector<vector<int>>dp(n,vector<int>(w+1,0));
for(int cap =0; cap<=w; cap++){
if(cap%weight[0]==0)
dp[0][cap] = profit[0]*cap/weight[0];
}
for(int idx =1; idx<n; idx++){
for(int cap=1; cap<=w; cap++){
int notTake = dp[idx-1][cap];
int take = 0;
if(weight[idx]<=cap){
take = dp[idx][cap-weight[idx]]+profit[idx];
}
dp[idx][cap] = max(notTake , take);
}
}
return dp[n-1][w];
}
--------------------------------------------------------------------------------------------------------
SPACE OPTIMIZATION:
time : O(n*cap)
space : O(2*cap)
code :
int unboundedKnapsack(int n, int w, vector<int> &profit, vector<int> &weight){
vector<int>curr(w+1,0),prev(w+1,0);
for(int cap =0; cap<=w; cap++){
if(cap%weight[0]==0)
curr[cap] = profit[0]*cap/weight[0];
}
for(int idx =1; idx<n; idx++){
swap(curr ,prev);
for(int cap=1; cap<=w; cap++){
int notTake = prev[cap];
int take = 0;
if(weight[idx]<=cap){
take = curr[cap-weight[idx]]+profit[idx];
}
curr[cap] = max(notTake , take);
}
}
return curr[w];
}
------------------------------------------------------------------------------------------- |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
# news_api/models.py
class Article(models.Model):
id = models.CharField(primary_key=True, max_length=32)
title = models.CharField(max_length=200)
author = models.CharField(max_length=100, null=True, blank=True)
description = models.TextField()
url = models.URLField()
url_to_image = models.URLField(null=True, blank=True)
published_at = models.DateTimeField(null=True, blank=True) # Allow null values
source_name = models.CharField(max_length=100)
def __str__(self):
return self.title
class Like(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
article = models.ForeignKey(Article, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
class Bookmark(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
article = models.ForeignKey(Article, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True) |
import { useState } from 'react';
import LogoTitle from '../../assets/images/logo-title.png'
import { Link } from 'react-router-dom'
import './index.scss';
import AnimatedLetters from '../AnimatedLetters';
import { useEffect } from 'react';
import MyPhoto from '../../assets/images/my-photo.jpg'
import Logo from './Logo'
import Loader from 'react-loaders'
const Home = () => {
const [letterClass, setLetterClass] = useState('text-animate')
const nameArray = ['a', 'n','i', 'a']
const jobArray = ['W','e','b','', 'D','e','v','l','o','p','e','r','.']
useEffect(() => {
setTimeout (() => {
setLetterClass('text-animate-hover')
}, 4000)
}, [])
return (
<>
<div className="container home-page">
<div className="text-zone">
<h1>
<span className={letterClass}>H</span>
<span className={`${letterClass} _12`}>i,</span>
<br />
<span className={`${letterClass} _13`}>I</span>
<span className={`${letterClass} _14`}>'m</span>
<img src={LogoTitle} alt='name'/>
<AnimatedLetters
letterClass={letterClass}
strArray={nameArray}
idx={15}
/>
<br />
<AnimatedLetters
letterClass={letterClass}
strArray={jobArray}
idx={22}
/>
</h1>
<h2>Frontend Developer / YouTuber / JavaScript Expert / Designer</h2>
<Link to='/contact' className='flat-button'>CONTACT ME</Link>
</div>
<div className='my-photo'>
<img src={MyPhoto} alt='my photo'/>
</div>
</div>
<Loader type='pacman'/>
</>
);
}
export default Home |
# [605. 种花问题](https://leetcode.cn/problems/can-place-flowers/description/)
## 说明
> 假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
> 给你一个整数数组 flowerbed 表示花坛,由若干 0 和 1 组成,其中 0 表示没种植花,1 表示种植了花。另有一个数 n ,能否在不打破种植规则的情况下种入 n 朵花?能则返回 true ,不能则返回 false 。
> 示例 1:
> > ```
> > 输入:flowerbed = [1,0,0,0,1], n = 1
> > 输出:true
> > ```
> 示例 2:
> > ```
> > 输入:flowerbed = [1,0,0,0,1], n = 2
> > 输出:false
>> ```
## 题解思路
- 连续的三个0值才算可以种花
-边界虚构出两个0值即可
## 代码
```java
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = 0, len = flowerbed.length;
for (int i = 0; i < len; i++) {
int l = i <=0 ? 0 : flowerbed[i-1];
int r = i >= len-1 ? 0 : flowerbed[i+1];
if (flowerbed[i] == 0 && l == 0 && r == 0) {
count++;
flowerbed[i] = 1;
}
}
return count >= n;
}
}
``` |
#include <iostream>
class Treap {
private:
struct Node {
int64_t key;
int64_t priority;
int64_t size;
Node* left;
Node* right;
Node* parent;
int64_t result;
explicit Node(int64_t key)
: key(key), priority(std::rand()), size(1), left(nullptr), right(nullptr), parent(nullptr) {
}
};
Node* root_ = nullptr;
int64_t Size(Node* node) {
return node ? node->size : 0;
}
void FixNode(Node* node) {
if (node) {
node->size = 1 + Size(node->left) + Size(node->right);
}
}
Node* Merge(Node* t_1, Node* t_2) {
if (!t_1) {
return t_2;
}
if (!t_2) {
return t_1;
}
if (t_1->priority < t_2->priority) {
t_1->right = Merge(t_1->right, t_2);
t_1->right->parent = t_1;
FixNode(t_1);
return t_1;
}
t_2->left = Merge(t_1, t_2->left);
t_2->left->parent = t_2;
FixNode(t_2);
return t_2;
}
std::pair<Node*, Node*> Split(Node* t, const int64_t& key_0) {
if (!t) {
return std::make_pair(nullptr, nullptr);
}
if (t->key < key_0) {
auto lr = Split(t->right, key_0);
auto l = lr.first;
auto r = lr.second;
t->right = l;
if (l) {
l->parent = t;
}
if (r) {
r->parent = nullptr;
}
FixNode(t);
return std::make_pair(t, r);
}
auto lr = Split(t->left, key_0);
auto l = lr.first;
auto r = lr.second;
t->left = r;
if (r) {
r->parent = t;
}
if (l) {
l->parent = nullptr;
}
FixNode(t);
return std::make_pair(l, t);
}
Node* Find(Node* x, int64_t key) {
if (x == nullptr) {
return x;
}
if (x->key == key) {
return x;
}
if (x->key > key) {
return Find(x->left, key);
}
return Find(x->right, key);
}
void Next(Node* x, int64_t key, int64_t& next) {
if (x == nullptr) {
return;
}
if (key >= x->key) {
return Next(x->right, key, next);
}
if (key < x->key) {
next = x->key;
return Next(x->left, key, next);
}
}
void Prev(Node* x, int64_t key, int64_t& prev) {
if (x == nullptr) {
return;
}
if (key > x->key) {
prev = x->key;
return Prev(x->right, key, prev);
}
if (key <= x->key) {
return Prev(x->left, key, prev);
}
}
Node* Insert(Node* root, Node* node) { // node->key not in treap
auto p = Split(root, node->key);
auto t_1 = p.first;
auto t_2 = p.second;
return Merge(Merge(t_1, node), t_2);
}
Node* Erase(Node* root, const int64_t& key) {
auto p_1 = Split(root, key);
auto t_less = p_1.first;
auto t_eq_more = p_1.second;
int64_t up = key;
Next(root_, key, up);
up = up == key ? key + 1 : up;
auto p_2 = Split(t_eq_more, up);
auto t_key = p_2.first;
auto t_more = p_2.second;
delete t_key;
return Merge(t_less, t_more);
}
int64_t CountLeft(Node* x) {
if (x->left) {
return x->left->size;
}
return 0;
}
Node* Kth(Node* x, int64_t k) {
if (x == nullptr) {
return x;
}
if (CountLeft(x) == k) {
return x;
}
if (CountLeft(x) > k) {
return Kth(x->left, k);
}
return Kth(x->right, k - CountLeft(x) - 1);
}
void ClearS(Node* x) {
if (x != nullptr) {
ClearS(x->left);
ClearS(x->right);
delete x;
}
}
public:
bool Exists(int64_t key) {
Node* x = Find(root_, key);
return x != nullptr && x->key == key;
}
void Insert(const int64_t& key) {
auto node = new Node(key);
if (!Exists(key)) {
root_ = Insert(root_, node);
}
}
void Erase(const int64_t& key) {
if (Exists(key)) {
root_ = Erase(root_, key);
}
}
int64_t GetNext(const int64_t& key) {
int64_t next = INT64_MIN;
Next(root_, key, next);
return next;
}
int64_t GetPrev(const int64_t& key) {
int64_t prev = INT64_MIN;
Prev(root_, key, prev);
return prev;
}
int64_t GetKth(const int64_t& idx) {
auto node = Kth(root_, idx);
if (node) {
return node->key;
}
return INT64_MIN;
}
void Clear() {
ClearS(root_);
}
};
void ProcessingRequests(Treap& treap) {
std::string command;
while ((std::cin >> command)) {
int64_t x = 0;
std::cin >> x;
if (command == "insert") {
treap.Insert(x);
} else if (command == "delete") {
treap.Erase(x);
} else if (command == "exists") {
std::cout << (treap.Exists(x) ? "true" : "false") << "\n";
} else if (command == "next") {
auto next = treap.GetNext(x);
if (next != INT64_MIN) {
std::cout << next << "\n";
} else {
std::cout << "none\n";
}
} else if (command == "prev") {
auto prev = treap.GetPrev(x);
if (prev != INT64_MIN) {
std::cout << prev << "\n";
} else {
std::cout << "none\n";
}
} else if (command == "kth") {
auto kth = treap.GetKth(x);
if (kth != INT64_MIN) {
std::cout << kth << "\n";
} else {
std::cout << "none\n";
}
}
}
}
int main() {
Treap treap;
ProcessingRequests(treap);
treap.Clear();
return 0;
} |
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import promise from 'redux-promise';
import './style.css';
import 'bootstrap';
import './scss/app.scss';
import reducers from './reducers';
import SiteIndex from './components/site_index.js';
import SiteBlog from './components/site_blog.js';
import SiteContact from './components/site_contact.js';
import NavigationBar from './containers/navigation_bar';
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<div className = 'site-bg'>
<NavigationBar />
<Switch>
<Route path='/blog' component={SiteBlog} />
<Route path='/contact' component={SiteContact} />
<Route path='/' component={SiteIndex} />
</Switch>
</div>
</BrowserRouter>
</Provider>
, document.querySelector('.container')); |
from database.models import Student
from database.query import is_user
from database.manipulate import commmit_student
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
CallbackQueryHandler,
CommandHandler,
Filters,
ConversationHandler,
MessageHandler,
)
# start handler
def start(update, bot):
exist = is_user(update.effective_user.id)
if exist:
reply_keyboard = [
[InlineKeyboardButton(text="Customer Support", callback_data="customer_feedback")],
[InlineKeyboardButton(text="Make Order", callback_data="make_order")],
[InlineKeyboardButton(text="Manage Cart", callback_data="manage_cart")],
[InlineKeyboardButton(text="Change Delivery Location", callback_data="edit_room")]
]
markup = InlineKeyboardMarkup(reply_keyboard)
bot.bot.send_message(
chat_id=update.effective_chat.id,
text="""
Welcome to Byte & Crunch! \n How may we be of assistance to you?
""",
reply_markup=markup
)
else:
reply_keyboard = [
[InlineKeyboardButton(text="Let's Go!", callback_data="is_customer")],
]
markup = InlineKeyboardMarkup(reply_keyboard)
bot.bot.send_message(
chat_id=update.message.chat_id,
text="Welcome to Byte & Crunch Telegram Bot!",
reply_markup=markup,
)
return 0
#is customer
def setup_customer(update, bot):
query = update.callback_query
message = query.edit_message_text(
text="""
Thank you for chooosing Byte & Crunch!
\nWe need some information before you can continue to ordering your food!
\nLet's start with your name!
"""
)
bot.user_data["start_id"] = message.message_id
return "mat_no"
def enter_mat_no(update, bot):
name = update.message
bot.user_data["user_type"] = Student(name=name.text)
bot.bot.delete_message(chat_id=update.effective_chat.id,message_id=name.message_id)
bot.bot.delete_message(chat_id=update.effective_chat.id,message_id= bot.user_data["start_id"])
message = bot.bot.send_message(
chat_id=update.effective_chat.id,
text="Next is your matric.no! \n please send your matric.no!"
)
bot.user_data["start_id"] = message.message_id
return "email_"
def enter_email(update, bot):
matno = update.message
bot.user_data["user_type"].matno = matno.text
bot.bot.delete_message(chat_id=update.effective_chat.id,message_id=matno.message_id)
bot.bot.delete_message(chat_id=update.effective_chat.id,message_id= bot.user_data["start_id"])
message = bot.bot.send_message(
chat_id=update.effective_chat.id,
text="What's your email address?"
)
bot.user_data["start_id"] = message.message_id
return "room_address"
def enter_room_address(update, bot):
email = update.message
bot.user_data["user_type"].email = email.text
bot.bot.delete_message(chat_id=update.effective_chat.id,message_id=email.message_id)
bot.bot.delete_message(chat_id=update.effective_chat.id,message_id= bot.user_data["start_id"])
message = bot.bot.send_message(
chat_id=update.effective_chat.id,
text="Where's your hall and room👀👀👀? \n This is delivery location(can be changed later in settings)"
)
bot.user_data["start_id"] = message.message_id
return "confirm_details"
def confirm_details(update, bot):
room = update.message
user = bot.user_data["user_type"]
bot.user_data["user_type"].room = room.text
bot.bot.delete_message(chat_id=update.effective_chat.id,message_id=room.message_id)
bot.bot.delete_message(chat_id=update.effective_chat.id,message_id= bot.user_data["start_id"])
name , matno, email = user.name, user.matno, user.email
reply_keyboard = [
[InlineKeyboardButton(text="Yes, Submit!", callback_data="save")],
[InlineKeyboardButton(text="No, Re-enter Details", callback_data="return")],
]
mark_up = InlineKeyboardMarkup(reply_keyboard)
message = bot.bot.send_message(
chat_id=update.effective_chat.id,
text=f"""
Here's what you entered: \n
Name =>{name}
Matric No => {matno}
Email => {email}
Room details => {room.text}
Is this all correct?
""",
reply_markup=mark_up,
)
bot.user_data["start_id"] = message.message_id
return "submit"
# save user to database
def submit(update, bot):
bot.user_data["cart"] = {}
bot.user_data["cart_total"] = 0
user_type = bot.user_data['user_type']
user_type.userid = update.effective_user.id
if update.callback_query.data == "save":
query = update.callback_query
commmit_student(user_type)
reply_keyboard = [
[
InlineKeyboardButton(text="Back to home!", callback_data="start")
]
]
markup = InlineKeyboardMarkup(reply_keyboard)
query.edit_message_text(
text="Account Created Successfully!",
reply_markup=markup
)
del bot.user_data['user_type']
del bot.user_data["start_id"]
return ConversationHandler.END
elif update.callback_query.data == "return":
message = bot.bot.send_message(
chat_id=update.effective_chat.id,
text="""
Please enter your full name!
""",
)
bot.user_data["start_id"] = message.message_id
return "mat_no"
return ConversationHandler.END
def home(update, bot):
query = update.callback_query
reply_keyboard = [
[InlineKeyboardButton(text="Customer Support", callback_data="customer_feedback")],
[InlineKeyboardButton(text="Make Order", callback_data="make_order")],
[InlineKeyboardButton(text="Manage Cart", callback_data="manage_cart")],
[InlineKeyboardButton(text="Change Delivery Location", callback_data="edit_room")]
]
markup = InlineKeyboardMarkup(reply_keyboard)
query.edit_message_text(
text="""
Welcome to Byte & Crunch! \n How may we be of assistance to you?
P.S
\n Hurry up though, we'll be shutting down 5:30pm!
""",
reply_markup=markup
)
def cancel(update,bot):
update.message.reply_text('Operation canceled')
return ConversationHandler.END
start_handler = CommandHandler("start", start, run_async=True)
setup_user_handler = ConversationHandler(
entry_points=[
CallbackQueryHandler(pattern="is_customer", callback=setup_customer, run_async=True)
],
states= {
"mat_no": [MessageHandler(Filters.all, enter_mat_no, run_async=True)],
"email_":[MessageHandler(Filters.all, enter_email, run_async=True)],
"room_address": [MessageHandler(Filters.all, enter_room_address, run_async=True)],
"confirm_details" : [MessageHandler(Filters.all, confirm_details, run_async=True)],
"submit": [CallbackQueryHandler(submit, run_async=True)]
},
fallbacks=[CommandHandler("cancel", cancel)]
)
back_to_home = CallbackQueryHandler(callback=home, pattern="start") |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/css/lightbox.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/js/lightbox.min.js"></script>
<title>Designs</title>
</head>
<body>
<nav>
<input type="checkbox" class="chk1">
<div class="heading">
<h1><span>MUNNA'S </span>DESIGN</h1>
</div>
<ul>
<li><a href="#home-section">Home</a></li>
<li><a href="#about-section">About</a></li>
<li><a href="#design-section">Designs</a></li>
<li><a href="#contact-section">Contact</a></li>
<!-- <div class="menu">
<label for="chk1">
<i class="fas fa-bars"></i>
</label>
</div> -->
</ul>
</nav>
<!-- home section -->
<section class="home-section" id="home-section">
<div class="home">
<h1 align="center">Mehendi Vibes!!</h1>
<a href="#gallery-container">Scroll to gallery</a>
</div>
<div class="image-container" id="image-container">
<div class="image1">
<img src="./image/henna.jpeg" alt="Image 1">
<img src="./image/henna.jpeg" alt="Image 2">
</div>
<div class="image3">
<img src="./image/henna.jpeg" alt="Image 3">
</div>
</div>
</section>
<!-- about me -->
<section class="about-section" id="about-section">
<div class="about">
<div class="aboutme">
<h2 align="center">About me</h2>
<img src="./image/henna.jpeg" alt="">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Doloremque dolores aspernatur atque voluptatem in eaque quos quibusdam, a temporibus vitae ab, sunt quo omnis? In reprehenderit eligendi optio molestiae nesciunt nostrum magni, esse non, natus sapiente reiciendis quos, consequatur impedit magnam voluptates corporis quae. Nam autem vero quasi vel laudantium. Lorem ipsum dolor sit, amet consectetur adipisicing elit. Animi, quam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia, optio!</p>
</div>
</div>
</section>
<!-- design section -->
<section id="design-section">
<div class="gallery-container" id="gallery-container">
<h2 align="center">OUR DESIGNS</h2>
<div class="gallery">
<div class="gallery-items">
<a href="./image/henna.jpeg" data-lightbox="gallery-item"><img src="./image/henna.jpeg" alt=""></a>
<a href="./image/henna.jpeg" data-lightbox="gallery-item"><img src="./image/henna.jpeg" alt=""></a>
<a href="./image/henna.jpeg" data-lightbox="gallery-item"><img src="./image/henna.jpeg" alt=""></a>
<a href="./image/henna.jpeg" data-lightbox="gallery-item"><img src="./image/henna.jpeg" alt=""></a>
<a href="./image/henna.jpeg" data-lightbox="gallery-item"><img src="./image/henna.jpeg" alt=""></a>
</div>
</div>
</div>
</section>
<!-- contact section -->
<section class="contact-section" id="contact-section">
<div class="contact">
<h2>Contact me</h2>
<div class="msg">
<form action="https://formspree.io/f/moqzryyn" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Email" required>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<button type="submit">Send Message</button>
</form>
</div>
</div>
</section>
<!-- footer section -->
<footer class="footer">
<div class="container">
<div class="footer-content">
<div class="contact-info">
<h4>Contact Information</h4>
<ul>
<li><i class="fas fa-envelope"></i>ra353473@gmail.com</li>
<li><i class="fas fa-phone"></i> +91 819-745-8962</li>
<li><i class="fas fa-map-marker-alt"></i>Mangalore</li>
</ul>
</div>
<div class="quick-links">
<h4>Quick Links</h4>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Designs</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</div>
<div class="footer-bottom">
<a href=" http://wa.me/+918197458962"><i class="fab fa-whatsapp"></i></a>
<a href="https://www.instagram.com/_.sh_eh_za_di._/"><i class="fab fa-instagram"></i></a>
<a href="http://github.com/munazzabegam"><i class="fab fa-github"></i></a>
<a href="http://www.linkedin.com/in/munazza-begam"><i class="fab fa-linkedin-square"></i></a>
<p>© 2023 Your Mehendi Website. All rights reserved.</p>
</div>
</div>
</footer>
</body>
</html> |
"use client"
import React, { useContext, useEffect } from 'react';
import Head from 'next/head';
import { useMetaMask } from "metamask-react";
import styles from '../styles/Home.module.css';
import Link from 'next/link';
export default function Homepage() {
const { status, connect, account } = useMetaMask();
useEffect(() => {
if (status === "unavailable") alert("MetaMask is not installed!");
}, [status]);
return (
<div className={styles.container}>
<Head>
<title>Student Certificate Blockchain Platform</title>
<meta name="description" content="A platform for managing student certificates on the blockchain" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>
Student Certificate Blockchain Platform
</h1>
<p className={styles.description}>
Connect your MetaMask wallet to get started
</p>
{status === "notConnected" && (
<button className={styles.button} onClick={connect}>Connect MetaMask</button>
)}
{status === "connected" && (
<div>
<p>Wallet connected: {account}</p>
<div className={styles.grid}>
<button className={styles.card}>
<Link href="/certificates">
<h2>Search Certificates →</h2>
<p>Find and verify student certificates.</p>
</Link>
</button>
<button className={styles.card}>
<Link href="/upload">
<h2>Upload Certificate →</h2>
<p>Upload a new student certificate to the blockchain.</p>
</Link>
</button>
</div>
</div>
)}
</main>
<footer className={styles.footer}>
Powered by <a href="https://ethereum.org">Ethereum</a>
</footer>
</div>
);
} |
package ohrman.max;
import java.util.Map;
import java.util.TreeMap;
public class Basket {
private final String name;
private final Map<StockItem, Integer> list;
public Basket(String name) {
this.name = name;
this.list = new TreeMap<>();
}
/**
* Method adds item of quantity to our Map called list
*
* @param item the stock item we want to add to the basket
* @param quantity amount of items to add to basket
*/
public void addToBasket(StockItem item, int quantity) {
if((item != null) && (quantity > 0)) {
int inBasket = list.getOrDefault(item, 0);
list.put(item, inBasket + quantity);
}
}
// For testing purposes
@Override
public String toString() {
StringBuilder s = new StringBuilder("\nShopping basket " + name + " contains " + list.size() + ((list.size() == 1) ? " item " : " items") + "\n");
double totalCost = 0.0;
for(Map.Entry<StockItem, Integer> item : list.entrySet() ) {
s.append(item.getKey()).append(". ").append(item.getValue()).append(" purchased\n");
totalCost += item.getKey().getPrice() * item.getValue();
}
return s + "Total cost " + totalCost;
}
} |
package com.example.restapi_skillfactory.controller;
import com.example.restapi_skillfactory.dto.UserBalanceDTO;
import com.example.restapi_skillfactory.mapper.OperationMapper;
import com.example.restapi_skillfactory.mapper.UserBalanceMapper;
import com.example.restapi_skillfactory.repository.OperationRepository;
import com.example.restapi_skillfactory.repository.UserBalanceRepository;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@Slf4j
public class UserBalanceControllerTest extends CommonTest {
@Autowired
private UserBalanceRepository userBalanceRepository;
@Autowired
private OperationRepository operationRepository;
@Autowired
private UserBalanceMapper userBalanceMapper;
@Autowired
private OperationMapper operationMapper;
@Override
@Test
@Order(0)
@DisplayName("GET /balance/{id} - получение баланса пользователя по ID")
protected void getBalance() throws Exception {
UserBalanceDTO userBalanceDTO = userBalanceMapper.mapToUserBalanceDTO(userBalanceRepository.findById(1).get());
int id = userBalanceDTO.getId();
String result = mvc.perform(MockMvcRequestBuilders.get("/balance/{id}", id)
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(userBalanceDTO))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is2xxSuccessful())
.andReturn()
.getResponse()
.getContentAsString();
log.info(result);
}
@Override
@Test
@Order(1)
@DisplayName("GET balance/list/{id} - получение списка операций пользователя за период")
protected void getOperationList() throws Exception {
int id = 1;
String result = mvc.perform(MockMvcRequestBuilders.get("/balance/list/{id}", id)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().is2xxSuccessful())
.andReturn()
.getResponse()
.getContentAsString();
log.info(result);
}
@Override
@Test
@Order(2)
@DisplayName("PUT balance/putMoney/{id} - пополнение баланса пользователя")
protected void putMoney() throws Exception {
int id = 2;
String result = mvc.perform(MockMvcRequestBuilders.put("/balance/putMoney/{id}?putMoney=100.20", id)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().is2xxSuccessful())
.andReturn()
.getResponse()
.getContentAsString();
log.info(result);
}
@Override
@Test
@Order(3)
@DisplayName("PUT balance/takeMoney/{id} - снятие денег с баланса пользователя")
protected void takeMoney() throws Exception {
int id = 2;
String result = mvc.perform(MockMvcRequestBuilders.put("/balance/takeMoney/{id}?takeMoney=40", id)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().is2xxSuccessful())
.andReturn()
.getResponse()
.getContentAsString();
log.info(result);
}
@Override
@Test
@Order(3)
@DisplayName("PUT balance/transferMoney?from=...&to=...&amount=... - снятие денег с баланса пользователя")
protected void transferMoney() throws Exception {
String result = mvc.perform(MockMvcRequestBuilders.put("/balance/transferMoney?from=2&to=1&amount=100")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().is2xxSuccessful())
.andReturn()
.getResponse()
.getContentAsString();
log.info(result);
}
} |
import { mustBeStringOrFail } from '../string.utils';
describe('StringUtils', () => {
describe('mustBeStringOrFail', () => {
const expectedErrorMessage = 'Provided value must be a string.';
describe('when no value is passed', () => {
it('should throw error', () => {
expect(() => mustBeStringOrFail()).toThrowError(expectedErrorMessage);
});
});
describe('when a value other than of string type is passed', () => {
it('should throw error if value is object', () => {
const value = {};
expect(() => mustBeStringOrFail(value as any)).toThrowError(
expectedErrorMessage,
);
});
it('should throw error if value is array', () => {
const value = [''];
expect(() => mustBeStringOrFail(value as any)).toThrowError(
expectedErrorMessage,
);
});
it('should throw error if value is function', () => {
const value = () => {};
expect(() => mustBeStringOrFail(value as any)).toThrowError(
expectedErrorMessage,
);
});
it('should throw error if value is boolean', () => {
const value = true;
expect(() => mustBeStringOrFail(value as any)).toThrowError(
expectedErrorMessage,
);
});
it('should throw error if value is undefined', () => {
const value = undefined;
expect(() => mustBeStringOrFail(value as any)).toThrowError(
expectedErrorMessage,
);
});
it('should throw error if value is null', () => {
const value = null;
expect(() => mustBeStringOrFail(value as any)).toThrowError(
expectedErrorMessage,
);
});
});
describe('when string value is passed', () => {
it('should return the passed string', () => {
const value = 'passed';
const result = mustBeStringOrFail(value);
expect(result).toBe(value);
});
});
});
}); |
#!/usr/bin/env perl
use exact -cli, -conf;
use QuizSage::Model::Meet;
use QuizSage::Model::Season;
use YAML::XS 'LoadFile';
my $opt = options( qw{
context|c=s
id|i=i
region|r=s
season|e=s
name|n=s
location|l=s
start|s=s
days|d=i
password|p=s
yaml|y=s
action|a=s
} );
$opt->{context} =
( not $opt->{context} ) ? '' :
( $opt->{context} =~ /^s/i ) ? 'season' :
( $opt->{context} =~ /^m/i ) ? 'meet' : '';
$opt->{action} =
( not $opt->{action} ) ? '' :
( $opt->{action} =~ /^b/i ) ? 'build' :
( $opt->{action} =~ /^d/i ) ? 'delete' : '';
pod2usage('Most provide valid context and either a season name or meet name or primary ID') unless (
$opt->{context} eq 'season' and $opt->{season} or
$opt->{context} eq 'meet' and $opt->{name} or
$opt->{context} and $opt->{id}
);
if ( $opt->{yaml} ) {
die "Unable to read YAML file: $opt->{yaml}\n" unless ( -r $opt->{yaml} );
$opt->{settings} = LoadFile( $opt->{yaml} ) or die "Unable to parse YAML file: $opt->{yaml}\n";
}
my $object = ( $opt->{context} eq 'season' ) ? QuizSage::Model::Season->new : QuizSage::Model::Meet->new;
my $season_id;
try {
$season_id = QuizSage::Model::Season->new->load({
name => $opt->{season},
maybe location => $opt->{region},
})->id if ( $opt->{context} eq 'meet' and $opt->{season} );
}
catch ($e) {
die $object->deat($e) . "\n";
}
my $data = {
maybe season_id => $season_id,
maybe name => $opt->{ ( $opt->{context} eq 'season' ) ? 'season' : 'name' },
maybe location => $opt->{location},
maybe start => $opt->{start},
maybe days => $opt->{days},
maybe passwd => $opt->{password},
maybe settings => $opt->{settings},
};
try {
$object->load(
( $opt->{id} )
? $opt->{id}
: { name => $opt->{ ( $opt->{context} eq 'season' ) ? 'season' : 'name' } }
)->save($data);
}
catch ($e) {
$object->create($data) unless ( $opt->{action} eq 'delete' );
}
if ( $opt->{action} and ( not $object or not $object->data ) ) {
die "Unable to $opt->{action} without loadable $opt->{context}\n";
}
elsif ( $opt->{action} eq 'delete' ) {
$object->delete;
}
elsif ( $opt->{action} and not $object->can( $opt->{action} ) ) {
die "Class $opt->{context} cannot $opt->{action}\n";
}
elsif ( $opt->{action} ) {
my $method = $opt->{action};
$object->$method;
}
=head1 NAME
setup.pl - Build and edit meets and seasons
=head1 SYNOPSIS
setup.pl OPTIONS
-c, --context CONTEXT # season | meet
-i, --id PRIMARY_KEY_ID
-r, --region SEASON_LOCATION
-e, --season SEASON_NAME
-n, --name MEET_NAME
-l, --location MEET_LOCATION
-s, --start DATETIME|EPOCH
-d, --days DURATION
-p, --password PASSWORD
-y, --yaml YAML_SETTINGS_FILE
-a, --action ACTION # build | delete
-h, --help
-m, --man
=head1 DESCRIPTION
This program will build and edit meets and seasons.
=head2 -c, --context
Run the program either in the "season" or "meet" context.
=head2 -i, --id
Primary key ID of the row of the C<context> desired.
=head2 -r, --region
Season location (or region) name.
=head2 -e, --season
Season name.
=head2 -n, --name
Meet name.
=head2 -l, --location
Location name.
=head2 -s, --start
Season or meet start date and time, either as some sort of parsable date/time
string (with or without timezone) or epoch.
=head2 -d, --days
Number of days of season or meet duration.
=head2 -p, --password
Officials' authorization password for a meet.
=head2 -y, --yaml
YAML source file for settings.
=head2 -a, --action
Execute a valid action. Valid actions are: "build" and "delete". |
import { GraphicItem, GraphicItemOpt } from "./GraphicItem";
import { GeoPoint } from "../../../Utils/GeoPoint";
import { GraphicGroup } from "./GraphicGroup";
/**
* @类型 外部使用类
* @描述 点几何体绘制对象
*/
export declare class PointGraphic extends GraphicItem {
protected _opt: PointGraphicOpt;
protected _type: string;
/**
* 初始化示例
* @param option 点几何体构造方法
* ```
* 示例代码
* let point = new GV.PointGraphic({position:new GV.GeoPoint(10,10)});
* viewer.graphicLayer.add(point);
* ```
*/
constructor(option: PointGraphicOpt);
/**
* @注意 所有item的基类方法,外部无需调用
* @描述 初始化方法,在父类执行add方法添加时被调用
*/
init(father: GraphicGroup): void;
/**
* 获取类型
*/
getType(): string;
/**
* 获取当前对象类型(给类型为只读属性)
*/
static readonly type: string;
/**
* 设置位置
* @return
* ```
* 示例代码
* let point.position = new GV.GeoPoint(10,10)
* ```
*/
position: GeoPoint;
/**
* 大小(单位:像素) (范围: >0 && <100)
*/
pixelSize: number;
/**
* 颜色
*/
color: any;
/**
* 外边框颜色
*/
outlineColor: any;
/**
* 外边框宽度
*/
outlineWidth: any;
/**
* 高度按照相对于什么
*/
heightReference: any;
/**
* 根据距离计算缩放大小
*/
scaleByDistance: any;
/**
* 是否深度检测
*/
isDepthTest: boolean;
/**
* 当前对象序列化成json数据
* ```
* 代码示例:
* const obj = item.toJson();
* ```
*/
toJson(): object;
}
/**
* 数据约束及默认值
*/
export declare class PointGraphicOpt extends GraphicItemOpt {
/**
* 位置
*/
position: GeoPoint;
/**
* 点的大小, (单位:像素) (范围: >0 && <500)
*/
pixelSize?: number;
/**
* 颜色 CssColor
*/
color?: string;
/**
* 外边框颜色宽度,(单位:像素) (范围: >0 && <500)
*/
outlineWidth?: number;
/**
* 外边框颜色 CssColor
*/
outlineColor?: string;
/**
* 根据距离视点范围和放大率范围计算放大倍数
*/
scaleByDistance?: Array<Number>;
/**
* 高度参照: 'clamp_to_ground' 完全贴合地面; 'none' 高度与地形无关; 'relative_to_ground' 真实高度=地形高度+高度值
*/
heightReference?: string;
/**
* 是否深度检测
*/
isDepthTest?: boolean;
} |
import { SlashCommand } from '../../structures/SlashCommand';
import { client, distube } from '../..';
import { ApplicationCommandOptionType } from 'discord.js';
import { formatTimeDisplay, trimString } from '../../utils';
export default new SlashCommand({
data: {
name: 'seek',
description: 'Przewija do podanego miejsca w piosence',
options: [
{
type: ApplicationCommandOptionType.Subcommand,
name: 'time',
description: 'Przewijaj do podanego czasu',
options: [
{
type: ApplicationCommandOptionType.String,
name: 'timestamp',
nameLocalizations: {
pl: 'czas',
},
description: 'Czas do jakiego przewinąć (w formacie HH:MM:SS lub MM:SS lub SS)',
max_length: 8,
required: true,
},
],
},
{
type: ApplicationCommandOptionType.Subcommand,
name: 'chapter',
description: 'Przewijaj do wybranego chapteru',
options: [
{
type: ApplicationCommandOptionType.String,
name: 'chapter',
description: 'Chapter do jakiego przewinąć',
required: true,
autocomplete: true,
},
],
},
],
dmPermission: false,
},
vcOnly: true,
queueRequired: true,
run: async ({ interaction, logger, queue }) => {
if (queue.songs[0].isLive) return interaction.reply({ content: 'Nie można przewijać live!', ephemeral: true, }).catch(err => logger.error(err));
let seekTime = -1;
if (interaction.options.getSubcommand() === 'time') {
const time = interaction.options.getString('timestamp');
const [ sec, min, hour ] = time.split(':').reverse();
const timeSecs = ( (parseInt(hour) * 3600) || 0 ) + ( (parseInt(min) * 60) || 0 ) + (parseInt(sec));
if (isNaN(timeSecs) || timeSecs < 0) return interaction.reply({ content: 'Użyj formatu HH:MM:SS czyli np jak chcesz przewinąć do 8 minuty i 20 sekundy piosenki wpisz 8:20', ephemeral: true, })
.catch(err => logger.error(err));
seekTime = timeSecs;
} else {
const time = parseInt(interaction.options.getString('chapter'));
if (isNaN(time) || time < 0) return interaction.reply({ content: 'Nie można przewinąć do podanego chapteru', ephemeral: true, })
.catch(err => logger.error(err));
seekTime = time;
}
const queueNew = queue.seek(seekTime);
if (queue.paused) queue.paused = false; // distube glitch bypass
interaction.reply({ content: `Przewinięto do \`${formatTimeDisplay(queueNew.currentTime)}\`!` })
.catch(err => logger.error(err));
},
getAutocompletes: async ({ interaction, logger }) => {
const queue = distube.getQueue(interaction.guildId);
if (!queue || !queue?.songs[0]) return interaction.respond([]);
if (!queue.songs[0].chapters) return interaction.respond([]);
const focused = interaction.options.getFocused().trim();
if (!focused) return interaction.respond(queue.songs[0].chapters.slice(0, 24).map(ch => { return { name: `${trimString(ch.title, 80)} - ${formatTimeDisplay(ch.start_time)}`, value: ch.start_time.toString() } } )); // queue.songs[0].chapters.slice(0, 24)
const filtered = queue.songs[0].chapters.filter(ch => ch.title.toLowerCase().includes(focused.toLocaleLowerCase()) );
interaction.respond(filtered.slice(0, 24).map(ch => { return { name: `${trimString(ch.title, 80)} - ${formatTimeDisplay(ch.start_time)}`, value: ch.start_time.toString() } }));
},
}); |
// _____ _ _ _ _ _ _
// | ___(_)_ __ ___ (_)_ __ | |_| |__ ___ | | __ _| | _____
// | |_ | | '__/ _ \ | | '_ \ | __| '_ \ / _ \ | | / _` | |/ / _ \
// | _| | | | | __/ | | | | | | |_| | | | __/ | |__| (_| | < __/
// |_| |_|_| \___| |_|_| |_| \__|_| |_|\___| |_____\__,_|_|\_\___|
//
//
// An scala implementation of the solo Tru'ng bots for the game
// Fire in the Lake, designed by Mark Herman and Volko Ruhnke
// published by GMT Games.
//
// Copyright (c) 2021 Curt Sellmer
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package fitl.cards
import scala.collection.immutable.ListMap
import fitl.FireInTheLake._
import fitl.EventHelpers._
import fitl.Bot
import fitl.Bot.{ US_Bot, ARVN_Bot, NVA_Bot, VC_Bot }
import fitl.Human
// Unshaded Text
// Soviet escalation matched: Place any 6 ARVN pieces anywhere in South Vietnam.
//
// Shaded Text
// Heavy divisions, big guns: NVA in any 3 spaces places enough Troops
// to double their number. It then free Bombards.
//
// Tips "Pieces" include Bases. For the unshaded Event, the executing
// Faction would decide the pieces and locations. For the shaded,
// NVA decides; in each selected space, place the same number of NVA
// Troops as are already there, then execute a Bombard Special Activity.
// The Bombard need not involve any of the Troops just placed.
object Card_049 extends EventCard(49, "Russian Arms",
DualEvent,
List(NVA, ARVN, VC, US),
ListMap(US -> (Ignored -> Unshaded),
ARVN -> (Performed -> Unshaded),
NVA -> (Ignored -> Shaded),
VC -> (Ignored -> Shaded))) {
def unshadedEffective(faction: Faction): Boolean = game.availablePieces.has(ARVNPieces)
def executeUnshaded(faction: Faction): Unit = {
val validSpaces = spaceNames(game.spaces filter (sp => isInSouthVietnam(sp.name)))
placePiecesOnMap(faction, 6, ARVNPieces, validSpaces)
}
def shadedEffective(faction: Faction): Boolean = false // Never executed by Bots
// Human player only
def executeShaded(faction: Faction): Unit = {
val candidates = spaceNames(game.spaces filter (_.pieces.has(NVATroops)))
val choices = candidates map (n => n -> n)
val num = choices.size min 3
val selectedSpaces = askMenu(choices, s"\nSelect ${amountOf(num, "space")} to double the amount of NVA Troops", numChoices = num)
println()
if (selectedSpaces.isEmpty)
log("There are no spaces with NVA Troops")
else {
loggingControlChanges {
for (name <- selectedSpaces) {
val sp = game.getSpace(name)
val numInSpace = sp.pieces.totalOf(NVATroops)
val num = Human.numToPlace(NVATroops, numInSpace)
placePieces(name, Pieces(nvaTroops = num))
}
}
}
log()
Human.doBombard(Params(event = true, free = true))
}
} |
<template>
<a-modal
:title="title"
:width="width"
:visible="visible"
:confirmLoading="confirmLoading"
@ok="handleOk"
@cancel="handleCancel"
:destroyOnClose="true"
cancelText="关闭">
<a-spin :spinning="confirmLoading">
<a-form :form="form">
<a-form-item label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol">
<a-input v-decorator="[ 'createBy', validatorRules.createBy]" placeholder="请输入创建人"></a-input>
</a-form-item>
<a-form-item label="创建日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
<j-date placeholder="请选择创建日期" v-decorator="[ 'createTime', validatorRules.createTime]" :trigger-change="true" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
</a-form-item>
<a-form-item label="更新人" :labelCol="labelCol" :wrapperCol="wrapperCol">
<a-input v-decorator="[ 'updateBy', validatorRules.updateBy]" placeholder="请输入更新人"></a-input>
</a-form-item>
<a-form-item label="更新日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
<j-date placeholder="请选择更新日期" v-decorator="[ 'updateTime', validatorRules.updateTime]" :trigger-change="true" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
</a-form-item>
<a-form-item label="所属部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
<a-input v-decorator="[ 'sysOrgCode', validatorRules.sysOrgCode]" placeholder="请输入所属部门"></a-input>
</a-form-item>
<a-form-item label="父级节点" :labelCol="labelCol" :wrapperCol="wrapperCol">
<j-tree-select
ref="treeSelect"
placeholder="请选择父级节点"
v-decorator="['pid', validatorRules.pid]"
dict="test_dev,id,id"
pidField="pid"
pidValue="0"
hasChildField="has_child">
</j-tree-select>
</a-form-item>
<a-form-item label="是否有子节点" :labelCol="labelCol" :wrapperCol="wrapperCol">
<j-dict-select-tag type="list" v-decorator="['hasChild', validatorRules.hasChild]" :trigger-change="true" dictCode="yn" placeholder="请选择是否有子节点"/>
</a-form-item>
<a-form-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
<a-input v-decorator="[ 'name', validatorRules.name]" placeholder="请输入名称"></a-input>
</a-form-item>
</a-form>
</a-spin>
</a-modal>
</template>
<script>
import { httpAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import JDate from '@/components/jeecg/JDate'
import JDictSelectTag from "@/components/dict/JDictSelectTag"
import JTreeSelect from '@/components/jeecg/JTreeSelect'
export default {
name: "TestDevModal",
components: {
JDate,
JDictSelectTag,
JTreeSelect
},
data () {
return {
form: this.$form.createForm(this),
title:"操作",
width:800,
visible: false,
model: {},
labelCol: {
xs: { span: 24 },
sm: { span: 5 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
confirmLoading: false,
validatorRules: {
createBy: {rules: [
]},
createTime: {rules: [
]},
updateBy: {rules: [
]},
updateTime: {rules: [
]},
sysOrgCode: {rules: [
]},
pid: {rules: [
]},
hasChild: {rules: [
]},
name: {rules: [
]},
},
url: {
add: "/demonstration/testDev/add",
edit: "/demonstration/testDev/edit",
},
expandedRowKeys:[],
pidField:"pid"
}
},
created () {
},
methods: {
add () {
this.edit({});
},
edit (record) {
this.form.resetFields();
this.model = Object.assign({}, record);
this.visible = true;
this.$nextTick(() => {
this.form.setFieldsValue(pick(this.model,'createBy','createTime','updateBy','updateTime','sysOrgCode','pid','hasChild','name'))
})
},
close () {
this.$emit('close');
this.visible = false;
},
handleOk () {
const that = this;
// 触发表单验证
this.form.validateFields((err, values) => {
if (!err) {
that.confirmLoading = true;
let httpurl = '';
let method = '';
if(!this.model.id){
httpurl+=this.url.add;
method = 'post';
}else{
httpurl+=this.url.edit;
method = 'put';
}
let old_pid = this.model[this.pidField]
let formData = Object.assign(this.model, values);
let new_pid = this.model[this.pidField]
console.log("表单提交数据",formData)
httpAction(httpurl,formData,method).then((res)=>{
if(res.success){
that.$message.success(res.message);
that.submitSuccess(formData,old_pid==new_pid)
}else{
that.$message.warning(res.message);
}
}).finally(() => {
that.confirmLoading = false;
that.close();
})
}
})
},
handleCancel () {
this.close()
},
popupCallback(row){
this.form.setFieldsValue(pick(row,'createBy','createTime','updateBy','updateTime','sysOrgCode','pid','hasChild','name'))
},
submitSuccess(formData,flag){
if(!formData.id){
let treeData = this.$refs.treeSelect.getCurrTreeData()
this.expandedRowKeys=[]
this.getExpandKeysByPid(formData[this.pidField],treeData,treeData)
this.$emit('ok',formData,this.expandedRowKeys.reverse());
}else{
this.$emit('ok',formData,flag);
}
},
getExpandKeysByPid(pid,arr,all){
if(pid && arr && arr.length>0){
for(let i=0;i<arr.length;i++){
if(arr[i].key==pid){
this.expandedRowKeys.push(arr[i].key)
this.getExpandKeysByPid(arr[i]['parentId'],all,all)
}else{
this.getExpandKeysByPid(pid,arr[i].children,all)
}
}
}
}
}
}
</script> |
import { ChevronDownIcon } from "@heroicons/react/outline";
import { signOut, useSession } from "next-auth/react";
import React, { useEffect, useState } from "react";
import { shuffle } from "lodash";
import { playlistIdState, playlistState } from "../atoms/playlistAtom";
import { useRecoilState, useRecoilValue } from "recoil";
import useSpotify from "../hooks/useSpotify";
import Songs from "./Songs";
const colors = [
"from-indigo-500",
"from-blue-500",
"from-green-500",
"from-red-500",
"from-yellow-500",
"from-pink-500",
"from-purple-500",
];
const Center = () => {
const { data: session } = useSession();
const spotifyApi = useSpotify();
const [color, setColor] = useState(colors[0]);
const playlistId = useRecoilValue(playlistIdState);
const [playlist, setPlaylist] = useRecoilState(playlistState);
useEffect(() => {
setColor(shuffle(colors).pop());
}, [playlistId]);
useEffect(() => {
const token = spotifyApi.getAccessToken();
if (token) {
spotifyApi
.getPlaylist(playlistId)
.then((data) => {
console.log("data.body", data.body);
setPlaylist(data.body);
})
.catch((error) => {
console.log("Something went wrong!");
});
}
}, [spotifyApi, playlistId]);
return (
<div className="flex-grow h-screen overflow-y-scroll scrollbar-hide">
<header className="absolute top-5 right-8">
<div
className="flex items-center bg-black text-white space-x-3 opacity-90 hover:opacity-80 cursor-pointer rounded-full p-1 pr-2"
onClick={signOut}
>
<img
className="rounded-full w-10 h-10"
src={session?.user?.image}
alt=""
/>
<h2>{session?.user?.name}</h2>
<ChevronDownIcon className="h-5 w-5" />
</div>
</header>
<section
className={`flex items-end space-x-7 bg-gradient-to-b to-black ${color} h-80 text-white p-8`}
>
<img
className="h-44 w-44 shadow-2xl"
src={playlist?.images?.[0]?.url}
alt=""
/>
<div>
<p>Playlist</p>
<h1 className="text-2xl md:text-3xl xl:text-5xl">{playlist?.name}</h1>
</div>
</section>
<div>
<Songs />
</div>
</div>
);
};
export default Center; |
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faBed,
faBath,
faUsers,
faStar,
} from "@fortawesome/free-solid-svg-icons";
import { Link, useLocation } from "react-router-dom";
import likeIcon from "../assets/icon.png";
import pinkLikeIcon from "../assets/pink-icon.png";
const ApartmentCard = ({
rental,
onDelete,
handleAddToFavourites,
favRentals,
}) => {
let location = useLocation();
return (
<div className="rental-unit">
<div className="img-box-rental">
<Link to={`/rentals/${rental.id}`}>
<img src={rental.picture_url.url} alt={`Photo of ${rental.name}`} />
</Link>
</div>
<div className="unit-description">
<div className="title">
<Link to={`/rentals/${rental.id}`}>
<h3>{rental.name}</h3>
</Link>
<h2 className="rating">
<FontAwesomeIcon icon={faStar} /> {rental.review_scores_rating}/100
</h2>
</div>
<p>
<b>Location:</b> {rental.city}, {rental.country}
</p>
<div className="unit-icons">
<p>
<FontAwesomeIcon icon={faBed} /> {rental.bedrooms}
</p>
<p>
<FontAwesomeIcon icon={faBath} /> {rental.bathrooms}
</p>
<p>
<FontAwesomeIcon icon={faUsers} /> {rental.accommodates}
</p>
</div>
<div className="price-rating">
<p className="price">{rental.price}€</p>
</div>
<div className="labels">
{rental.price <= 85 ? (
<p className="great-deal-label">Great Deal!</p>
) : rental.price >= 150 ? (
<p className="premium-label">
<strong>Premium</strong>
</p>
) : (
<span></span>
)}
{rental.review_scores_rating > 90 ? (
<p className="super-host-label">
<strong>Super Host!</strong>
</p>
) : (
<span></span>
)}
</div>
{location.pathname === "/favourites" ||
favRentals.includes(rental) ? null : (
<>
<button
className="btn-like"
onClick={() => {
handleAddToFavourites(rental);
}}
>
<img src={likeIcon} />
</button>
</>
)}
{(location.pathname === "/") & favRentals.includes(rental) ? (
<>
<button className="btn-like">
<img src={pinkLikeIcon} />
</button>
</>
) : null}
{location.pathname === "/favourites" ? null : (
<button onClick={() => onDelete(rental.id)} className="delete-btn">
Delete
</button>
)}
</div>
</div>
);
};
export default ApartmentCard; |
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:attendance_in/services/auth.dart';
import 'package:attendance_in/shared/constants.dart';
import 'package:attendance_in/shared/loading.dart';
class SignIn extends StatefulWidget {
final Function toggleView;
SignIn({required this.toggleView});
@override
State<SignIn> createState() => _SignInState();
}
class _SignInState extends State<SignIn> {
final AuthService _auth = AuthService();
final _formKey = GlobalKey<FormState>();
bool loading = false;
// Text Field State
String email = "";
String password = "";
String error = '';
bool isObscure = true; // Initially obscure the password
// Store the original entered email
String originalEmail = "";
// Controller for the email input in the reset password popup
TextEditingController _resetEmailController = TextEditingController();
@override
Widget build(BuildContext context) {
// Get the current date
String currentDate = DateFormat('dd-MM-yyyy').format(DateTime.now());
return loading
? Loading()
: Scaffold(
backgroundColor: Colors.teal[100],
appBar: AppBar(
backgroundColor: Colors.teal,
elevation: 0.0,
title: Text(
currentDate,
style: TextStyle(color: Colors.black),
),
actions: <Widget>[
TextButton.icon(
onPressed: () {
widget.toggleView();
},
icon: Icon(
Icons.person,
color: Colors.black,
),
label: Text(
"Register",
style: TextStyle(color: Colors.black),
),
)
],
),
body: Container(
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 50.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(height: 20.0),
Text(
"Log In to Attendance Inn",
style: TextStyle(
color: Colors.black,
fontSize: 24.0,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 20.0),
Form(
key: _formKey,
child: Column(
children: <Widget>[
TextFormField(
decoration: textInputDecoration.copyWith(
hintText: "Email",
icon: Icon(Icons.email, color: Colors.teal),
),
initialValue: originalEmail,
validator: (val) =>
val!.isEmpty ? "Enter an Email" : null,
onChanged: (val) {
setState(() {
email = val;
error = ''; // Clear the error when typing
});
},
),
SizedBox(height: 20.0),
TextFormField(
decoration: textInputDecoration.copyWith(
hintText: "Password",
icon: Icon(Icons.lock, color: Colors.teal),
suffixIcon: IconButton(
icon: Icon(
isObscure
? Icons.visibility
: Icons.visibility_off,
color: Colors.teal,
),
onPressed: () {
setState(() {
isObscure = !isObscure;
});
},
),
),
obscureText: isObscure,
validator: (val) => val!.length < 6
? "Strong Password 6 Characters+"
: null,
onChanged: (val) {
setState(() => password = val);
},
),
SizedBox(height: 20.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(
Colors.green),
padding: MaterialStateProperty.all<
EdgeInsetsGeometry>(
EdgeInsets.all(15),
),
),
child: Text(
"Log In",
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
onPressed: () async {
if (_formKey.currentState!.validate()) {
setState(() {
isObscure = true;
loading = true;
});
dynamic result =
await _auth.signInWithEmailAndPassword(
email, password);
if (result == null) {
setState(() {
error = "INVALID CREDENTIALS";
loading = false;
// Clear only the password field on error
_formKey.currentState?.reset();
email =
originalEmail; // Restore the original email
});
}
}
},
),
TextButton(
onPressed: () {
setState(() => isObscure = !isObscure);
_showForgotPasswordPopup();
},
child: Text(
"Forgot Password?",
style: TextStyle(
color: Colors.black,
fontSize: 16,
),
),
),
],
),
SizedBox(
height: 12.0,
),
Text(
error,
style: TextStyle(
color: Colors.red,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
],
),
),
],
),
),
);
}
// Function to show the "Forgot Password" popup
void _showForgotPasswordPopup() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Forgot Password"),
content: Column(
children: [
Text("Enter your registered email ID to reset your password:"),
SizedBox(height: 10),
TextFormField(
controller: _resetEmailController,
decoration: textInputDecoration.copyWith(
hintText: "Email",
icon: Icon(Icons.email, color: Colors.teal),
),
validator: (val) => val!.isEmpty ? "Enter an Email" : null,
),
],
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("Cancel"),
),
TextButton(
onPressed: () async {
String resetEmail = _resetEmailController.text.trim();
if (resetEmail.isNotEmpty) {
// Call the resetPassword method with the entered email
await _forgotPassword(resetEmail);
Navigator.of(context).pop();
setState(() => _resetEmailController.clear());
_showResetPasswordPopup();
}
},
child: Text("Send"),
),
],
);
},
);
}
// Function to handle the "Forgot Password" action
Future<void> _forgotPassword(String email) async {
// Implement Firebase reset password functionality
try {
await _auth.resetPassword(email);
} catch (e) {
print("Error sending reset password email: $e");
// Handle error, e.g., display an error message to the user
}
}
// Function to show a pop-up indicating that an email to reset the password has been sent
void _showResetPasswordPopup() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Password Reset Email Sent"),
content: Text(
"An email to reset your password has been sent to your registered email address."),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("OK"),
),
],
);
},
);
}
}
// import 'package:flutter/material.dart';
// import 'package:intl/intl.dart';
// import 'package:attendance_in/services/auth.dart';
// import 'package:attendance_in/shared/constants.dart';
// import 'package:attendance_in/shared/loading.dart';
// class SignIn extends StatefulWidget {
// final Function toggleView;
// SignIn({required this.toggleView});
// @override
// State<SignIn> createState() => _SignInState();
// }
// class _SignInState extends State<SignIn> {
// final AuthService _auth = AuthService();
// final _formKey = GlobalKey<FormState>();
// bool loading = false;
// // Text Field State
// String email = "";
// String password = "";
// String error = '';
// // Store the original entered email
// String originalEmail = "";
// // Controller for the email input in the reset password popup
// TextEditingController _resetEmailController = TextEditingController();
// @override
// Widget build(BuildContext context) {
// // Get the current date
// String currentDate = DateFormat('dd-MM-yyyy').format(DateTime.now());
// return loading
// ? Loading()
// : Scaffold(
// backgroundColor: Colors.teal[100],
// appBar: AppBar(
// backgroundColor: Colors.teal,
// elevation: 0.0,
// title: Text(
// currentDate,
// style: TextStyle(color: Colors.black),
// ),
// actions: <Widget>[
// TextButton.icon(
// onPressed: () {
// widget.toggleView();
// },
// icon: Icon(
// Icons.person,
// color: Colors.black,
// ),
// label: Text(
// "Register",
// style: TextStyle(color: Colors.black),
// ),
// )
// ],
// ),
// body: Container(
// padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 50.0),
// child: Column(
// crossAxisAlignment: CrossAxisAlignment.center,
// children: <Widget>[
// SizedBox(height: 20.0),
// Text(
// "Log In to Attendance Inn",
// style: TextStyle(
// color: Colors.black,
// fontSize: 24.0,
// fontWeight: FontWeight.bold,
// ),
// ),
// SizedBox(height: 20.0),
// Form(
// key: _formKey,
// child: Column(
// children: <Widget>[
// TextFormField(
// decoration: textInputDecoration.copyWith(
// hintText: "Email",
// icon: Icon(Icons.email, color: Colors.teal),
// ),
// initialValue: originalEmail,
// validator: (val) =>
// val!.isEmpty ? "Enter an Email" : null,
// onChanged: (val) {
// setState(() {
// email = val;
// error = ''; // Clear the error when typing
// });
// },
// ),
// SizedBox(height: 20.0),
// TextFormField(
// decoration: textInputDecoration.copyWith(
// hintText: "Password",
// icon: Icon(Icons.lock, color: Colors.teal),
// ),
// obscureText: true,
// validator: (val) => val!.length < 6
// ? "Strong Password 6 Characters+"
// : null,
// onChanged: (val) {
// setState(() => password = val);
// },
// ),
// SizedBox(height: 20.0),
// Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// ElevatedButton(
// style: ButtonStyle(
// backgroundColor:
// MaterialStateProperty.all<Color>(
// Colors.green),
// padding: MaterialStateProperty.all<
// EdgeInsetsGeometry>(
// EdgeInsets.all(15),
// ),
// ),
// child: Text(
// "Log In",
// style: TextStyle(
// color: Colors.black,
// fontSize: 18,
// fontWeight: FontWeight.bold,
// ),
// ),
// onPressed: () async {
// if (_formKey.currentState!.validate()) {
// setState(() => loading = true);
// dynamic result =
// await _auth.signInWithEmailAndPassword(
// email, password);
// if (result == null) {
// setState(() {
// error = "INVALID CREDENTIALS";
// loading = false;
// // Clear only the password field on error
// _formKey.currentState?.reset();
// email =
// originalEmail; // Restore the original email
// });
// }
// }
// },
// ),
// TextButton(
// onPressed: () {
// _showForgotPasswordPopup();
// },
// child: Text(
// "Forgot Password?",
// style: TextStyle(
// color: Colors.black,
// fontSize: 16,
// ),
// ),
// ),
// ],
// ),
// SizedBox(
// height: 12.0,
// ),
// Text(
// error,
// style: TextStyle(
// color: Colors.red,
// fontSize: 18.0,
// fontWeight: FontWeight.bold,
// ),
// ),
// ],
// ),
// ),
// ],
// ),
// ),
// );
// }
// // Function to show the "Forgot Password" popup
// void _showForgotPasswordPopup() {
// showDialog(
// context: context,
// builder: (BuildContext context) {
// return AlertDialog(
// title: Text("Forgot Password"),
// content: Column(
// children: [
// Text("Enter your registered email ID to reset your password:"),
// SizedBox(height: 10),
// TextFormField(
// controller: _resetEmailController,
// decoration: textInputDecoration.copyWith(
// hintText: "Email",
// icon: Icon(Icons.email, color: Colors.teal),
// ),
// validator: (val) => val!.isEmpty ? "Enter an Email" : null,
// ),
// ],
// ),
// actions: [
// TextButton(
// onPressed: () {
// Navigator.of(context).pop();
// },
// child: Text("Cancel"),
// ),
// TextButton(
// onPressed: () async {
// String resetEmail = _resetEmailController.text.trim();
// if (resetEmail.isNotEmpty) {
// // Call the resetPassword method with the entered email
// await _forgotPassword(resetEmail);
// Navigator.of(context).pop();
// _showResetPasswordPopup();
// }
// },
// child: Text("Send"),
// ),
// ],
// );
// },
// );
// }
// // Function to handle the "Forgot Password" action
// Future<void> _forgotPassword(String email) async {
// // Implement Firebase reset password functionality
// try {
// await _auth.resetPassword(email);
// } catch (e) {
// print("Error sending reset password email: $e");
// // Handle error, e.g., display an error message to the user
// }
// }
// // Function to show a pop-up indicating that an email to reset the password has been sent
// void _showResetPasswordPopup() {
// showDialog(
// context: context,
// builder: (BuildContext context) {
// return AlertDialog(
// title: Text("Password Reset Email Sent"),
// content: Text(
// "An email to reset your password has been sent to your registered email address."),
// actions: [
// TextButton(
// onPressed: () {
// Navigator.of(context).pop();
// },
// child: Text("OK"),
// ),
// ],
// );
// },
// );
// }
// } |
let count = 360; //30 529
let rock;
let paper;
let scissor;
let rocks = [];
let papers = [];
let scissors = [];
let numRocks = count;
let numPapers = count;
let numScissors = count;
let numOverall = count * 3;
let picks = ["Rock", "Paper", "Scissor"];
function preload() {
rock = loadImage("Draws/Rock.png");
paper = loadImage("Draws/Paper.png");
scissor = loadImage("Draws/Scissor.png");
}
function setup() {
createCanvas(1700, 2960); //24, 45
let node = new Node("Scissor");
for (let x = 130; x < 1570; x += 60) {
//670
for (let y = 130; y < 2700; y += 60) {
let done = false;
while (done == false) {
let pick = random(picks);
if (pick == "Rock") {
if (numRocks >= 1) {
done = true;
numRocks--;
append(rocks, new Node(rock, x, y));
}
}
if (pick == "Paper") {
if (numPapers >= 1) {
done = true;
numPapers--;
append(papers, new Node(paper, x, y));
}
}
if (pick == "Scissor") {
if (numScissors >= 1) {
done = true;
numScissors--;
append(scissors, new Node(scissor, x, y));
}
}
}
}
}
}
function draw() {
background(220);
for (let i = 0; i < rocks.length; i++) {
rocks[i].Update();
}
for (let i = 0; i < papers.length; i++) {
papers[i].Update();
}
for (let i = 0; i < scissors.length; i++) {
scissors[i].Update();
}
}
function Distance(x1, x2, y1, y2) {
return sqrt(sq(x1 - x2) + sq(y1 - y2));
}
class Node {
constructor(pick, x, y) {
this.pick = pick;
this.x = x;
this.y = y;
}
Update() {
image(this.pick, this.x, this.y);
this.Move();
}
ChangePick(pick) {
this.pick = pick;
}
Move() {
if (this.pick == rock) {
if (scissors.length > 0) {
let closest = scissors[0];
let closestVal = 0;
let distance = Distance(this.x, scissors[0].x, this.y, scissors[0].y);
for (let i = 0; i < scissors.length - 1; i++) {
let newDist = Distance(this.x, scissors[i].x, this.y, scissors[i].y);
if (newDist < distance) {
closest = scissors[i];
distance = newDist;
closestVal = i;
}
}
let maybe = round(random(0, 1000000));
if (maybe != 0) {
let randomDirectionX = random(-1, 1);
let randomDirectionY = random(-1, 1);
let length = sqrt(
randomDirectionX * randomDirectionX +
randomDirectionY * randomDirectionY
);
randomDirectionX /= length;
randomDirectionY /= length;
let movementSpeed = 1;
this.x += randomDirectionX * movementSpeed;
this.y += randomDirectionY * movementSpeed;
}
this.x += (closest.x - this.x) / distance / 2;
this.y += (closest.y - this.y) / distance / 2;
if (distance < 25) {
scissors.splice(closestVal, 1);
append(rocks, closest);
closest.ChangePick(this.pick);
}
} else {
let randomDirectionX = random(-1, 1);
let randomDirectionY = random(-1, 1);
let length = sqrt(
randomDirectionX * randomDirectionX +
randomDirectionY * randomDirectionY
);
randomDirectionX /= length;
randomDirectionY /= length;
let movementSpeed = 1;
this.x += randomDirectionX * movementSpeed;
this.y += randomDirectionY * movementSpeed;
}
}
if (this.pick == paper) {
if (rocks.length > 0) {
let closest = rocks[0];
let closestVal = 0;
let distance = Distance(this.x, rocks[0].x, this.y, rocks[0].y);
for (let i = 0; i < rocks.length - 1; i++) {
let newDist = Distance(this.x, rocks[i].x, this.y, rocks[i].y);
if (newDist < distance) {
closest = rocks[i];
distance = newDist;
closestVal = i;
}
}
let maybe = round(random(0, 1000000));
if (maybe != 0) {
let randomDirectionX = random(-1, 1);
let randomDirectionY = random(-1, 1);
let length = sqrt(
randomDirectionX * randomDirectionX +
randomDirectionY * randomDirectionY
);
randomDirectionX /= length;
randomDirectionY /= length;
let movementSpeed = 1;
this.x += randomDirectionX * movementSpeed;
this.y += randomDirectionY * movementSpeed;
}
this.x += (closest.x - this.x) / distance / 2;
this.y += (closest.y - this.y) / distance / 2;
if (distance < 25) {
rocks.splice(closestVal, 1);
append(papers, closest);
closest.pick = this.pick;
}
} else {
let randomDirectionX = random(-1, 1);
let randomDirectionY = random(-1, 1);
let length = sqrt(
randomDirectionX * randomDirectionX +
randomDirectionY * randomDirectionY
);
randomDirectionX /= length;
randomDirectionY /= length;
let movementSpeed = 1;
this.x += randomDirectionX * movementSpeed;
this.y += randomDirectionY * movementSpeed;
}
}
if (this.pick == scissor) {
if (papers.length > 0) {
let closest = papers[0];
let closestVal = 0;
let distance = Distance(this.x, papers[0].x, this.y, papers[0].y);
for (let i = 0; i < papers.length - 1; i++) {
let newDist = Distance(this.x, papers[i].x, this.y, papers[i].y);
if (newDist < distance) {
closest = papers[i];
distance = newDist;
closestVal = i;
}
}
let maybe = round(random(0, 1000000));
if (maybe != 0) {
let randomDirectionX = random(-1, 1);
let randomDirectionY = random(-1, 1);
let length = sqrt(
randomDirectionX * randomDirectionX +
randomDirectionY * randomDirectionY
);
randomDirectionX /= length;
randomDirectionY /= length;
let movementSpeed = 1;
this.x += randomDirectionX * movementSpeed;
this.y += randomDirectionY * movementSpeed;
}
this.x += (closest.x - this.x) / distance / 2;
this.y += (closest.y - this.y) / distance / 2;
if (distance < 25) {
papers.splice(closestVal, 1);
append(scissors, closest);
closest.pick = this.pick;
}
} else {
let randomDirectionX = random(-1, 1);
let randomDirectionY = random(-1, 1);
let length = sqrt(
randomDirectionX * randomDirectionX +
randomDirectionY * randomDirectionY
);
randomDirectionX /= length;
randomDirectionY /= length;
let movementSpeed = 1;
this.x += randomDirectionX * movementSpeed;
this.y += randomDirectionY * movementSpeed;
}
}
}
} |
// Copyright 2022 a76yyyy && CloudWeGo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
* @Author: a76yyyy q981331502@163.com
* @Date: 2022-06-12 13:09:59
* @LastEditors: a76yyyy q981331502@163.com
* @LastEditTime: 2022-06-19 00:03:39
* @FilePath: /tiktok/cmd/publish/command/publish_list.go
* @Description: 获取发布视频列表 操作业务逻辑
*/
package command
import (
"context"
"github.com/a76yyyy/tiktok/dal/db"
"github.com/a76yyyy/tiktok/dal/pack"
"github.com/a76yyyy/tiktok/kitex_gen/feed"
"github.com/a76yyyy/tiktok/kitex_gen/publish"
)
type PublishListService struct {
ctx context.Context
}
// NewPublishListService new PublishListService
func NewPublishListService(ctx context.Context) *PublishListService {
return &PublishListService{ctx: ctx}
}
// PublishList publish video.
func (s *PublishListService) PublishList(req *publish.DouyinPublishListRequest) (vs []*feed.Video, err error) {
videos, err := db.PublishList(s.ctx, req.UserId)
if err != nil {
return nil, err
}
vs, err = pack.Videos(s.ctx, videos, &req.UserId)
if err != nil {
return nil, err
}
return vs, nil
} |
import { Query } from "@/application/types";
import { rideEntityMock } from "@/slices/ride/entities/RideEntity.spec";
import { UpdateRideRepository } from "@/slices/ride/repositories";
import { mock, MockProxy } from "jest-mock-extended";
import MockDate from "mockdate";
import { updateRide, updateRideUsecase } from "./UpdateRideUseCase";
describe("updateRide", () => {
let fakeQuery: Query;
let testInstance: updateRide;
let updateRideRepository: MockProxy<UpdateRideRepository>;
beforeAll(async () => {
MockDate.set(new Date());
updateRideRepository = mock();
fakeQuery = {
fields: {
name: "name",
},
options: {},
};
updateRideRepository.updateRide.mockResolvedValue(rideEntityMock);
});
beforeEach(() => {
testInstance = updateRideUsecase(updateRideRepository);
});
afterAll(async () => {
MockDate.reset();
});
it("should call updateRide of updateRideRepository with correct values", async () => {
await testInstance(fakeQuery, rideEntityMock);
expect(updateRideRepository.updateRide).toHaveBeenCalledWith(fakeQuery, rideEntityMock);
expect(updateRideRepository.updateRide).toHaveBeenCalledTimes(1);
});
it("should return a new deleted ride when updateRideRepository deletes it", async () => {
const ride = await testInstance(fakeQuery, rideEntityMock);
expect(ride).toEqual(rideEntityMock);
});
it("should return null when updateRideRepository fails to insert", async () => {
updateRideRepository.updateRide.mockResolvedValue(null);
const ride = await testInstance(fakeQuery, rideEntityMock);
expect(ride).toBeNull();
});
it("should throw an error when updateRideRepository throws an error", async () => {
updateRideRepository.updateRide.mockRejectedValue(new Error("Error"));
await expect(testInstance(fakeQuery, rideEntityMock)).rejects.toThrowError("Error");
});
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.