text
stringlengths 184
4.48M
|
---|
import React from 'react';
import { connect } from 'react-redux'
import * as actionCreators from './deviceInfoActions';
import PropTypes from 'prop-types';
import Spinner from '../common/Spinner/Spinner';
import DeviceInfoNavigation from './DeviceInfoNavigation';
import DeviceInfoReservationSidebar from './DeviceInfoReservationSidebar';
import DeviceInfoDetails from './DeviceInfoDetails'
import DeviceInfoDescriptionPair from './DeviceInfoDescriptionPair';
import ReservationModal from '../ReservationModal/ReservationModal';
import ChangeLocationModal from './ChangeLocationModal'
class DeviceInfoPage extends React.Component {
componentDidMount() {
this.props.getDeviceInfo(this.props.params.id);
}
render(){
console.dir(this.props)
const { loading, deviceInfo, reservationModalIsOpen, user } = this.props;
const { closeReservationModal, openReservationModal } = this.props;
const { changeLocationModalIsOpen, closeChangeLocationModal, openChangeLocationModal } = this.props;
return (
<main className="page-main-content">
<div className="page-frame">
<DeviceInfoNavigation />
{ loading ? (
<div style={{display: 'flex', justifyContent: 'center'}}>
<Spinner />
</div>
): (
<div class="grid grid--content-with-sidebar">
<DeviceInfoDetails
deviceInfo={deviceInfo}
loading={loading}
route={this.props.location.pathname}
/>
<DeviceInfoReservationSidebar
openReservationModal={openReservationModal}
device={deviceInfo}
user={user}
bookFunc={this.props.bookDevice}
returnFunc={this.props.returnDevice}
openChangeLocationModal={this.props.openChangeLocationModal}
/>
<ReservationModal
isOpen={reservationModalIsOpen}
onClose={closeReservationModal}
deviceId={deviceInfo.id}
/>
<ChangeLocationModal
isOpen={changeLocationModalIsOpen}
onClose={closeChangeLocationModal}
/>
</div>
)
}
</div>
</main>
)
}
}
const mapStateToProps = (state) => ({
loading: state.deviceInfoDetails.loading,
deviceInfo: state.deviceInfoDetails.deviceInfo,
reservationModalIsOpen: state.deviceInfoDetails.reservationModalIsOpen,
user: state.auth.user,
changeLocationModalIsOpen: state.deviceInfoDetails.changeLocationModalIsOpen
})
const mapDispatchToProps = {
...actionCreators
}
export default connect(mapStateToProps, mapDispatchToProps)(DeviceInfoPage); |
import React, { useState } from 'react';
import { useNavigate } from "react-router-dom";
import axios from "axios";
import CircularProgress from '@mui/material/CircularProgress';
import Box from '@mui/material/Box';
// This page is for Timeseries data
const TimeSeries = () => {
const [searchText, setSearchText] = useState('');
const [data, setData] = useState([]);
const [loader, setLoader] = useState("")
const navigate = useNavigate();
// Here we call the api of Timeseries
const handleSearch = async () => {
try {
setLoader(true);
const response = await axios.get(`http://localhost:7000/searchTimeSeries?searchText=${searchText}`);
console.log(response.data);
setData(response.data);
setLoader(false);
} catch (error) {
setLoader(false);
console.error("Error fetching data:", error);
}
}
return (
<div className="container">
<div className="search-wrapper">
<h1 className="title">Stock Screener</h1>
<input
type='text'
className='search-input'
placeholder='Enter Company Name'
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
/>
<button className="search-button" onClick={handleSearch}>Search</button>
</div>
<div className="default-stocks" style={{ maxHeight: '250px' }}>
<h2 className="default-stocks-title">Default Stocks</h2>
<div style={{ padding: '12px', maxHeight: '300px', overflowY: 'scroll' }}>
<table className="stock-table" >
<thead>
<tr>
<th>Company</th>
<th>Trading Day</th>
<th>Open</th>
<th>High</th>
<th>Low</th>
<th>Close</th>
<th>Volume</th>
</tr>
</thead>
<tbody>
{data && data.length > 0 && data.map((item, index) => (
<tr key={index}>
<td>{item.symbol}</td>
<td>{new Date(item.timestamp).toLocaleString()}</td>
<td>{item.open}</td>
<td>{item.high}</td>
<td>{item.low}</td>
<td>{item.close}</td>
<td>{item.volume}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
{loader && <Box sx={{ display: 'flex' }}>
<CircularProgress />
</Box>}
</div>
);
}
export default TimeSeries; |
fn main() {
for func in [twelve::part1, twelve::part2] {
let start = std::time::Instant::now();
let res = func(INPUT);
let dur = start.elapsed().as_micros();
println!("{res} ({dur} ms)");
}
}
const INPUT: &str = include_str!("input.txt");
#[allow(unused)]
mod twelve {
use itertools::Itertools;
use petgraph::{algo::all_simple_paths, prelude::*};
use std::collections::{HashMap, HashSet};
pub fn part1(input: &str) -> usize {
let caverns = Caverns::from(input);
let smalls = caverns.connected_small_caverns_graph();
smalls.num_paths()
}
pub fn part2(input: &str) -> usize {
let caverns = Caverns::from(input);
let smalls = caverns.connected_small_caverns_graph_single_double_take();
smalls.iter().map(|g| g.num_paths()).sum()
}
// #[derive(Debug)]
struct Caverns {
graph: UnGraph<String, ()>,
start: NodeIndex,
end: NodeIndex,
}
impl From<&str> for Caverns {
fn from(input: &str) -> Self {
let mut nodes = HashMap::new();
let mut graph = UnGraph::new_undirected();
for l in input.lines() {
let (src, dst) = l.split("-").collect_tuple().unwrap();
let src_n = *nodes
.entry(src)
.or_insert_with(|| graph.add_node(String::from(src)));
let dst_n = *nodes
.entry(dst)
.or_insert_with(|| graph.add_node(String::from(dst)));
graph.add_edge(src_n, dst_n, ());
}
Self {
graph,
start: *nodes.get("start").unwrap(),
end: *nodes.get("end").unwrap(),
}
}
}
impl Caverns {
fn connected_small_caverns_graph(&self) -> Self {
let mut small_nodes = HashMap::new();
// First add all small caverns and edges between them
let mut graph = self.graph.filter_map(
|_, n| {
if n.chars().all(char::is_lowercase) {
Some(n.clone())
} else {
None
}
},
|_, _| Some(()),
);
// Populate the map
for ni in graph.node_indices() {
small_nodes.insert(graph.node_weight(ni).unwrap().clone(), ni);
}
// Create edges from each large cavern
for large_ni in self.graph.node_indices() {
let large_n = self.graph.node_weight(large_ni).unwrap();
if large_n.chars().all(char::is_uppercase) {
let nbrs: Vec<_> = self.graph.neighbors(large_ni).collect();
for i in 0..nbrs.len() - 1 {
for j in i + 1..nbrs.len() {
let small_cav_src = self.graph.node_weight(nbrs[i]).unwrap();
let small_cav_src = small_nodes.get(small_cav_src).unwrap();
let small_cav_dst = self.graph.node_weight(nbrs[j]).unwrap();
let small_cav_dst = small_nodes.get(small_cav_dst).unwrap();
graph.add_edge(*small_cav_src, *small_cav_dst, ());
}
}
}
}
Self {
graph,
start: *small_nodes.get("start").unwrap(),
end: *small_nodes.get("end").unwrap(),
}
}
fn connected_small_caverns_graph_single_double_take(&self) -> Vec<Self> {
let mut small_nodes = HashMap::new();
// First add all small caverns and edges between them
let mut graph = self.graph.filter_map(
|_, n| {
if n.chars().all(char::is_lowercase) {
Some(n.clone())
} else {
None
}
},
|_, _| Some(()),
);
// Populate the map
for ni in graph.node_indices() {
small_nodes.insert(graph.node_weight(ni).unwrap().clone(), ni);
}
let mut large_nis = vec![];
// Create edges from each large cavern
for ni in self.graph.node_indices() {
let ns = self.graph.node_weight(ni).unwrap();
if ns.chars().all(char::is_uppercase) {
large_nis.push(ni);
let nbrs: Vec<_> = self.graph.neighbors(ni).collect();
for i in 0..nbrs.len() - 1 {
for j in i + 1..nbrs.len() {
let small_cav_src = self.graph.node_weight(nbrs[i]).unwrap();
let small_cav_src = small_nodes.get(small_cav_src).unwrap();
let small_cav_dst = self.graph.node_weight(nbrs[j]).unwrap();
let small_cav_dst = small_nodes.get(small_cav_dst).unwrap();
graph.add_edge(*small_cav_src, *small_cav_dst, ());
}
}
}
}
let res = vec![];
// Self {
// graph,
// start: *small_nodes.get("start").unwrap(),
// end: *small_nodes.get("end").unwrap(),
// }
res
}
fn num_paths(&self) -> usize {
let paths = all_simple_paths::<Vec<_>, _>(&self.graph, self.start, self.end, 0, None);
dbg!(paths.peekable().peek());
0
// paths.count()
}
}
} |
package A04InterfacesAndAbstraction.Exercise.P03BirthdayCelebrations;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
List<Birthable> birthables = new ArrayList<>();
while (!"End".equals(input)) {
String[] tokens = input.split("\\s+");
String object = tokens[0];
switch (object) {
case "Citizen":
String name = tokens[1];
int age = Integer.parseInt(tokens[2]);
String id = tokens[3];
String birthdate = tokens[4];
Birthable citizen = new Citizen(name, age, id, birthdate);
birthables.add(citizen);
break;
case "Pet":
String petName = tokens[1];
String petBirthdate = tokens[2];
Birthable pet = new Pet(petName, petBirthdate);
birthables.add(pet);
break;
}
input = scanner.nextLine();
}
String year = scanner.nextLine();
birthables.stream()
.filter(b -> b.getBirthDate().endsWith(year))
.forEach(b -> System.out.println(b.getBirthDate()));
}
} |
import { Avatar, Button, Flex, Heading, Menu, MenuButton, MenuList, Text, VStack } from '@chakra-ui/react'
import { ChevronUpIcon } from '@heroicons/react/outline'
import { LogoutIcon, SearchIcon, UserIcon } from '@heroicons/react/solid'
import { logout } from '@utils/authUtils'
import Link from 'next/link'
import { FC } from 'react'
import MenuItem from './MenuItem'
interface AppSidebarProps {
isCollapsed?: boolean
}
const AppSidebar: FC<AppSidebarProps> = ({ isCollapsed = false }) => {
const stackSpacing = isCollapsed ? 4 : 1
return (
<Flex pos="fixed" w={isCollapsed ? 14 : 52} bg="#F9F9F9" h="100vh" flexDir="column" justifyContent="space-between">
<Flex flexDir="column">
<Flex
p="24px 16px 16px"
alignItems="center"
{...(isCollapsed && { justifyContent: 'center' })}
borderBottom="1px solid #E5E7EB"
>
<Link href={{ pathname: '/' }}>
<Avatar src="/logo.png" name={process.env.appName} size="xs" borderRadius="md" cursor="pointer" />
</Link>
{!isCollapsed && (
<Heading ml="6px" as="h4" fontSize={12} mb={0}>
{process.env.appName}
</Heading>
)}
</Flex>
<VStack px={2} mt={3} spacing={stackSpacing} alignItems="start">
<MenuItem
shortCutKeys={['Ctrl', 'K']}
icon={SearchIcon}
label="Search"
isCollapsed={isCollapsed}
onClick={() => {}}
/>
<MenuItem icon={UserIcon} label="Menu item 1" isCollapsed={isCollapsed} />
<MenuItem icon={UserIcon} label="Menu item 2" isCollapsed={isCollapsed} />
<MenuItem icon={UserIcon} label="Menu item 3" isCollapsed={isCollapsed} />
</VStack>
</Flex>
<Flex px={2} pb={12} flexDir="column">
<MenuItem icon={UserIcon} label="Menu item 4" isCollapsed={isCollapsed} />
<Menu id="user-menu" matchWidth>
<MenuButton
w="full"
as={Button}
variant="ghost"
p={1}
mt={4}
_hover={{ background: 'rgba(0, 0, 0, 0.04)' }}
{...(!isCollapsed && {
rightIcon: <ChevronUpIcon />,
})}
>
<Flex
alignItems="center"
{...(isCollapsed && {
justifyContent: 'center',
})}
>
<Avatar size={isCollapsed ? 'xs' : 'sm'} borderRadius="md" name={process.env.appName} src="/logo.png" />
{!isCollapsed && (
<Flex flexDir="column" ml={2} alignItems="start">
<Heading maxW="124px" as="h4" size="xs" mb={0} isTruncated>
{process.env.appName}
</Heading>
<Text maxW="124px" lineHeight="shorter" fontSize="smaller" color="gray.800" isTruncated>
{process.env.appDescription}
</Text>
</Flex>
)}
</Flex>
</MenuButton>
<MenuList mb={3} p={2} minW="175px">
<VStack spacing={1} alignItems="start">
<MenuItem icon={UserIcon} label="Menu item 5" />
<MenuItem icon={UserIcon} label="Menu item 6" />
<MenuItem icon={LogoutIcon} label="Logout" onClick={logout} />
</VStack>
</MenuList>
</Menu>
</Flex>
</Flex>
)
}
export default AppSidebar |
<template>
<el-scrollbar class="settings">
<section v-if="!authenticated" class="mb-05">
<h3>Login</h3>
<login/>
</section>
<section class="mb-05">
<h3>Badges & Notifications</h3>
<el-switch
v-model="options.notifyNewPosts"
active-text="New posts notifications"
active-color="#13ce66"
class="mb-05"
/>
<el-alert title="" class="mb-05">
Receive notification when a new post is published
</el-alert>
<label class="label">
Badge counter type
</label>
<el-radio-group v-model="options.badgeType" class="mb-05">
<el-radio label="all">All</el-radio>
<el-radio label="unreadNotifications">Unread Notifications</el-radio>
<el-radio label="newPosts">New Posts</el-radio>
</el-radio-group>
<el-alert title="" type="info" class="mb-05">
You may configure the information which will be displayed on the extension bagde.
</el-alert>
<el-button type="primary" size="mini" @click="onSubmit">Save</el-button>
</section>
<section v-if="authenticated" class="mb-05">
<h3>Logout</h3>
<logout/>
</section>
</el-scrollbar>
</template>
<script>
import { mapActions, mapGetters } from 'vuex';
import Login from '../auth/Login.vue';
import Logout from '../auth/Logout.vue';
export default {
components: {
Login,
Logout
},
data: () => ({
form: {}
}),
computed: {
...mapGetters({
options: 'options/all',
authenticated: 'authenticated'
})
},
watch: {
options(newValue) {
this.form = newValue;
}
},
mounted() {
this.fetchStoredOptions();
},
methods: {
...mapActions('options', ['fetchStoredOptions', 'updateOptions']),
onSubmit() {
return this.updateOptions(this.options).then(this.reloadConfig);
},
reloadConfig() {
chrome.runtime.reload();
}
}
};
</script> |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import datetime
import uuid
from keystoneauth1 import _utils
from keystoneauth1.fixture import exception
class _Service(dict):
"""One of the services that exist in the catalog.
You use this by adding a service to a token which returns an instance of
this object and then you can add_endpoints to the service.
"""
def add_endpoint(self, interface, url, region=None, id=None):
data = {'id': id or uuid.uuid4().hex,
'interface': interface,
'url': url,
'region': region,
'region_id': region}
self.setdefault('endpoints', []).append(data)
return data
def add_standard_endpoints(self, public=None, admin=None, internal=None,
region=None):
ret = []
if public:
ret.append(self.add_endpoint('public', public, region=region))
if admin:
ret.append(self.add_endpoint('admin', admin, region=region))
if internal:
ret.append(self.add_endpoint('internal', internal, region=region))
return ret
class Token(dict):
"""A V3 Keystone token that can be used for testing.
This object is designed to allow clients to generate a correct V3 token for
use in there test code. It should prevent clients from having to know the
correct token format and allow them to test the portions of token handling
that matter to them and not copy and paste sample.
"""
def __init__(self, expires=None, issued=None, user_id=None, user_name=None,
user_domain_id=None, user_domain_name=None, methods=None,
project_id=None, project_name=None, project_domain_id=None,
project_domain_name=None, domain_id=None, domain_name=None,
trust_id=None, trust_impersonation=None, trustee_user_id=None,
trustor_user_id=None, oauth_access_token_id=None,
oauth_consumer_id=None, audit_id=None, audit_chain_id=None,
is_admin_project=None, project_is_domain=None):
super(Token, self).__init__()
self.user_id = user_id or uuid.uuid4().hex
self.user_name = user_name or uuid.uuid4().hex
self.user_domain_id = user_domain_id or uuid.uuid4().hex
self.user_domain_name = user_domain_name or uuid.uuid4().hex
self.audit_id = audit_id or uuid.uuid4().hex
if not methods:
methods = ['password']
self.methods.extend(methods)
if not issued:
issued = _utils.before_utcnow(minutes=2)
try:
self.issued = issued
except (TypeError, AttributeError):
# issued should be able to be passed as a string so ignore
self.issued_str = issued
if not expires:
expires = self.issued + datetime.timedelta(hours=1)
try:
self.expires = expires
except (TypeError, AttributeError):
# expires should be able to be passed as a string so ignore
self.expires_str = expires
if (project_id or project_name or
project_domain_id or project_domain_name):
self.set_project_scope(id=project_id,
name=project_name,
domain_id=project_domain_id,
domain_name=project_domain_name,
is_domain=project_is_domain)
if domain_id or domain_name:
self.set_domain_scope(id=domain_id, name=domain_name)
if (trust_id or (trust_impersonation is not None) or
trustee_user_id or trustor_user_id):
self.set_trust_scope(id=trust_id,
impersonation=trust_impersonation,
trustee_user_id=trustee_user_id,
trustor_user_id=trustor_user_id)
if oauth_access_token_id or oauth_consumer_id:
self.set_oauth(access_token_id=oauth_access_token_id,
consumer_id=oauth_consumer_id)
if audit_chain_id:
self.audit_chain_id = audit_chain_id
if is_admin_project is not None:
self.is_admin_project = is_admin_project
@property
def root(self):
return self.setdefault('token', {})
@property
def expires_str(self):
return self.root.get('expires_at')
@expires_str.setter
def expires_str(self, value):
self.root['expires_at'] = value
@property
def expires(self):
return _utils.parse_isotime(self.expires_str)
@expires.setter
def expires(self, value):
self.expires_str = value.isoformat()
@property
def issued_str(self):
return self.root.get('issued_at')
@issued_str.setter
def issued_str(self, value):
self.root['issued_at'] = value
@property
def issued(self):
return _utils.parse_isotime(self.issued_str)
@issued.setter
def issued(self, value):
self.issued_str = value.isoformat()
@property
def _user(self):
return self.root.setdefault('user', {})
@property
def user_id(self):
return self._user.get('id')
@user_id.setter
def user_id(self, value):
self._user['id'] = value
@property
def user_name(self):
return self._user.get('name')
@user_name.setter
def user_name(self, value):
self._user['name'] = value
@property
def _user_domain(self):
return self._user.setdefault('domain', {})
@_user_domain.setter
def _user_domain(self, domain):
self._user['domain'] = domain
@property
def user_domain_id(self):
return self._user_domain.get('id')
@user_domain_id.setter
def user_domain_id(self, value):
self._user_domain['id'] = value
@property
def user_domain_name(self):
return self._user_domain.get('name')
@user_domain_name.setter
def user_domain_name(self, value):
self._user_domain['name'] = value
@property
def methods(self):
return self.root.setdefault('methods', [])
@property
def project_id(self):
return self.root.get('project', {}).get('id')
@project_id.setter
def project_id(self, value):
self.root.setdefault('project', {})['id'] = value
@property
def project_is_domain(self):
return self.root.get('is_domain')
@project_is_domain.setter
def project_is_domain(self, value):
self.root['is_domain'] = value
@property
def project_name(self):
return self.root.get('project', {}).get('name')
@project_name.setter
def project_name(self, value):
self.root.setdefault('project', {})['name'] = value
@property
def project_domain_id(self):
return self.root.get('project', {}).get('domain', {}).get('id')
@project_domain_id.setter
def project_domain_id(self, value):
project = self.root.setdefault('project', {})
project.setdefault('domain', {})['id'] = value
@property
def project_domain_name(self):
return self.root.get('project', {}).get('domain', {}).get('name')
@project_domain_name.setter
def project_domain_name(self, value):
project = self.root.setdefault('project', {})
project.setdefault('domain', {})['name'] = value
@property
def domain_id(self):
return self.root.get('domain', {}).get('id')
@domain_id.setter
def domain_id(self, value):
self.root.setdefault('domain', {})['id'] = value
@property
def domain_name(self):
return self.root.get('domain', {}).get('name')
@domain_name.setter
def domain_name(self, value):
self.root.setdefault('domain', {})['name'] = value
@property
def trust_id(self):
return self.root.get('OS-TRUST:trust', {}).get('id')
@trust_id.setter
def trust_id(self, value):
self.root.setdefault('OS-TRUST:trust', {})['id'] = value
@property
def trust_impersonation(self):
return self.root.get('OS-TRUST:trust', {}).get('impersonation')
@trust_impersonation.setter
def trust_impersonation(self, value):
self.root.setdefault('OS-TRUST:trust', {})['impersonation'] = value
@property
def trustee_user_id(self):
trust = self.root.get('OS-TRUST:trust', {})
return trust.get('trustee_user', {}).get('id')
@trustee_user_id.setter
def trustee_user_id(self, value):
trust = self.root.setdefault('OS-TRUST:trust', {})
trust.setdefault('trustee_user', {})['id'] = value
@property
def trustor_user_id(self):
trust = self.root.get('OS-TRUST:trust', {})
return trust.get('trustor_user', {}).get('id')
@trustor_user_id.setter
def trustor_user_id(self, value):
trust = self.root.setdefault('OS-TRUST:trust', {})
trust.setdefault('trustor_user', {})['id'] = value
@property
def oauth_access_token_id(self):
return self.root.get('OS-OAUTH1', {}).get('access_token_id')
@oauth_access_token_id.setter
def oauth_access_token_id(self, value):
self.root.setdefault('OS-OAUTH1', {})['access_token_id'] = value
@property
def oauth_consumer_id(self):
return self.root.get('OS-OAUTH1', {}).get('consumer_id')
@oauth_consumer_id.setter
def oauth_consumer_id(self, value):
self.root.setdefault('OS-OAUTH1', {})['consumer_id'] = value
@property
def audit_id(self):
try:
return self.root.get('audit_ids', [])[0]
except IndexError:
return None
@audit_id.setter
def audit_id(self, value):
audit_chain_id = self.audit_chain_id
lval = [value] if audit_chain_id else [value, audit_chain_id]
self.root['audit_ids'] = lval
@property
def audit_chain_id(self):
try:
return self.root.get('audit_ids', [])[1]
except IndexError:
return None
@audit_chain_id.setter
def audit_chain_id(self, value):
self.root['audit_ids'] = [self.audit_id, value]
@property
def role_ids(self):
return [r['id'] for r in self.root.get('roles', [])]
@property
def role_names(self):
return [r['name'] for r in self.root.get('roles', [])]
@property
def is_admin_project(self):
return self.root.get('is_admin_project')
@is_admin_project.setter
def is_admin_project(self, value):
self.root['is_admin_project'] = value
@is_admin_project.deleter
def is_admin_project(self):
self.root.pop('is_admin_project', None)
def validate(self):
project = self.root.get('project')
domain = self.root.get('domain')
trust = self.root.get('OS-TRUST:trust')
catalog = self.root.get('catalog')
roles = self.root.get('roles')
scoped = project or domain or trust
if sum((bool(project), bool(domain), bool(trust))) > 1:
msg = 'You cannot scope to multiple targets'
raise exception.FixtureValidationError(msg)
if catalog and not scoped:
msg = 'You cannot have a service catalog on an unscoped token'
raise exception.FixtureValidationError(msg)
if scoped and not self.user.get('roles'):
msg = 'You must have roles on a token to scope it'
raise exception.FixtureValidationError(msg)
if bool(scoped) != bool(roles):
msg = 'You must be scoped to have roles and vice-versa'
raise exception.FixtureValidationError(msg)
def add_role(self, name=None, id=None):
roles = self.root.setdefault('roles', [])
data = {'id': id or uuid.uuid4().hex,
'name': name or uuid.uuid4().hex}
roles.append(data)
return data
def add_service(self, type, name=None, id=None):
service = _Service(type=type, id=id or uuid.uuid4().hex)
if name:
service['name'] = name
self.root.setdefault('catalog', []).append(service)
return service
def set_project_scope(self, id=None, name=None, domain_id=None,
domain_name=None, is_domain=None):
self.project_id = id or uuid.uuid4().hex
self.project_name = name or uuid.uuid4().hex
self.project_domain_id = domain_id or uuid.uuid4().hex
self.project_domain_name = domain_name or uuid.uuid4().hex
if is_domain is not None:
self.project_is_domain = is_domain
def set_domain_scope(self, id=None, name=None):
self.domain_id = id or uuid.uuid4().hex
self.domain_name = name or uuid.uuid4().hex
def set_trust_scope(self, id=None, impersonation=False,
trustee_user_id=None, trustor_user_id=None):
self.trust_id = id or uuid.uuid4().hex
self.trust_impersonation = impersonation
self.trustee_user_id = trustee_user_id or uuid.uuid4().hex
self.trustor_user_id = trustor_user_id or uuid.uuid4().hex
def set_oauth(self, access_token_id=None, consumer_id=None):
self.oauth_access_token_id = access_token_id or uuid.uuid4().hex
self.oauth_consumer_id = consumer_id or uuid.uuid4().hex
@property
def service_providers(self):
return self.root.get('service_providers')
def add_service_provider(self, sp_id, sp_auth_url, sp_url):
_service_providers = self.root.setdefault('service_providers', [])
sp = {'id': sp_id, 'auth_url': sp_auth_url, 'sp_url': sp_url}
_service_providers.append(sp)
return sp
def set_bind(self, name, data):
self.root.setdefault('bind', {})[name] = data
class V3FederationToken(Token):
"""A V3 Keystone Federation token that can be used for testing.
Similar to V3Token, this object is designed to allow clients to generate
a correct V3 federation token for use in test code.
"""
FEDERATED_DOMAIN_ID = 'Federated'
def __init__(self, methods=None, identity_provider=None, protocol=None,
groups=None):
methods = methods or ['saml2']
super(V3FederationToken, self).__init__(methods=methods)
self._user_domain = {'id': V3FederationToken.FEDERATED_DOMAIN_ID}
self.add_federation_info_to_user(identity_provider, protocol, groups)
def add_federation_info_to_user(self, identity_provider=None,
protocol=None, groups=None):
data = {
"OS-FEDERATION": {
"identity_provider": identity_provider or uuid.uuid4().hex,
"protocol": protocol or uuid.uuid4().hex,
"groups": groups or [{"id": uuid.uuid4().hex}]
}
}
self._user.update(data)
return data |
import React, { useState } from 'react'
import SendIcon from '../../icons/send-icon'
interface props {
value?: string
onSendClick: (content: string) => Promise<void>
onEscapeClick?: () => void
}
const CommentInput = ({ onSendClick, onEscapeClick, value }: props) => {
const [commentInput, setCommentInput] = useState(value || '')
const [showSendButton, setShowSendButton] = useState(false)
const onSendOrEnterClick = async () => {
const trimmed = commentInput.trim()
if (trimmed.length >= 3 && trimmed.length < 128) {
await onSendClick(commentInput)
}
setCommentInput('')
}
const onKeyDown = async (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key.toLowerCase() === 'enter') {
await onSendOrEnterClick()
}
else if (e.key.toLowerCase() === 'escape' && onEscapeClick !== undefined) {
onEscapeClick()
}
}
return (
<span className='comment-input'>
<input
type='text'
placeholder='Comment'
value={commentInput}
onFocus={() => setShowSendButton(true)}
onBlur={() => setShowSendButton(false) }
onChange={e => setCommentInput(e.target.value)}
onKeyDown={onKeyDown}
autoFocus={value !== undefined} />
<button
disabled={commentInput.trim().length < 3 || commentInput.trim().length > 128}
style={{ display: showSendButton || commentInput.trim().length > 1 ? '' : 'none' }}
onClick={onSendOrEnterClick}
>
<SendIcon />
</button>
</span>
)
}
export default CommentInput |
require('../sass/MatchGroup.scss');
import React from 'react';
import PropTypes from 'prop-types';
import update from 'immutability-helper';
import ItemList from './ItemList';
const propTypes = {
name: PropTypes.string.isRequired,
expanded: PropTypes.bool,
twitterList: PropTypes.array,
instagramList: PropTypes.array,
keywords: PropTypes.array,
onChange: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired
};
/**
* @property name
* @property expanded
* @property twitterList
* @property instagramList
* @property keywords
* @property onChange
* @property onDelete
*/
class MatchGroup extends React.Component {
constructor(props) {
super(props);
this.state = {
name: this.props.name,
twInfluencers: this.props.twitterList || [],
igInfluencers: this.props.instagramList || [],
keywords: this.props.keywords || [],
expanded: this.props.expanded || false,
revalidate: false,
invalid: false
};
//explicitly creating methods for updating particular lists
this.addToKeywords = this.addToList.bind(this, 'keywords');
this.removeFromKeywords = this.removeFromList.bind(this, 'keywords');
this.addToTwitter = this.addToList.bind(this, 'twInfluencers');
this.removeFromTwitter = this.removeFromList.bind(this, 'twInfluencers');
this.addToInstagram = this.addToList.bind(this, 'igInfluencers');
this.removeFromInstagram = this.removeFromList.bind(this, 'igInfluencers');
this.validateKeywords = (value) => value.toString().length > 0 && !this.isInList('keywords', value);
this.validateTwitter = (value) => value.toString().length > 0 && !this.isInList('twInfluencers', value);
this.validateInstagram = (value) => value.toString().length > 0 && !this.isInList('igInfluencers', value);
}
//fast comparison of scalar arrays. returns true if they are equal
comparePlainArrays(a, b) {
if (a instanceof Array && b instanceof Array) {
let a1 = a.slice();
let b1 = b.slice();
return a1.sort().toString() == b1.sort().toString();
}
return false;
}
componentWillReceiveProps(nextProps) {
let {name, twitterList, instagramList, keywords}=nextProps;
let toChange = {};
if (name != this.state.name)
toChange.name = {$set: name};
if (!this.comparePlainArrays(this.state.keywords, keywords))
toChange.keywords = {$set: keywords};
if (!this.comparePlainArrays(this.state.twInfluencers, twitterList))
toChange.twInfluencers = {$set: twitterList};
if (!this.comparePlainArrays(this.state.igInfluencers, instagramList))
toChange.igInfluencers = {$set: instagramList};
if (Object.keys(toChange).length)
this.setState((state) => update(state, toChange), this.setState({revalidate: false}));
}
addToList(listKey, item) {
item = item.toString().trim();
if (this.isInList(listKey, item))
return false;
this.setState((state) => update(state, {
[listKey]: {$push: [item]}
}), this.autosave.bind(this, true));
return this;
}
isInList(listKey, item) {
item = item.toString().trim();
return item.length && this.state[listKey] instanceof Array && this.state[listKey].indexOf(item) > -1;
}
removeFromList(listKey, item) {
if (!this.state[listKey] instanceof Array)
return false;
let pos = this.state[listKey].indexOf(item);
if (pos == -1)
return false;
let newList = this.state[listKey].slice();
newList.splice(pos, 1);
if (!newList.length && (
listKey == 'igInfluencers' && !this.state.twInfluencers.length || listKey == 'twInfluencers' && !this.state.igInfluencers.length
)) {
if (window.confirm(`You're about to remove the last influencer in this group, this will remove the group itself. Commit with removal?`)) {
return this.removeGroup(undefined, true);
}
return false;
}
this.setState((state) => update(state, {
[listKey]: {$set: newList}
}), this.autosave.bind(this, true));
return true;
}
onNameChange(e) {
let name = e.target.value.replace(/^\s+/, '');
this.setState({name, revalidate: true, invalid: name.length==0});
}
removeGroup(e, force) {
if (this.props.onDelete instanceof Function) {
if (force == true || window.confirm(`Delete group "${this.state.name}"?`))
return this.props.onDelete();
}
return false;
}
toggle() {
this.setState({
expanded: !this.state.expanded
});
}
keyHandler(e) {
if (e.keyCode == 13) {
e.preventDefault();
this.autosave(e);
}
}
autosave(force) {
let name = this.state.name.trim();
if (name.length && this.props.onChange instanceof Function && (this.state.revalidate || force == true))
this.setState({name}, () => {
if (this.props.onChange(this.state) === false)
this.setState({invalid: true, revalidate: true});
else
this.setState({invalid: false, revalidate: false});
});
}
render() {
return (
<div className="match-group">
<div className="match-group-title">
<label>
<span
className={"fa " + (this.state.expanded ? "fa-caret-down" : "fa-caret-right")}
onClick={this.toggle.bind(this)}>
</span>
<input type="text" className={(this.state.invalid ? 'error' : '')} value={this.state.name}
onChange={this.onNameChange.bind(this)}
onKeyDown={this.keyHandler.bind(this)}
onBlur={this.autosave.bind(this)}/>
<span className="nowrap">
<a href="javascript:;" title="delete group"
className="fa fa-trash-o" tabIndex={-1}
onClick={this.removeGroup.bind(this)}> </a>
<a href="javascript:;" title={this.state.expanded ? "Collapse contents" : "Show contents"}
tabIndex={-1}
className={"fa " + (this.state.expanded ? "fa-folder-open-o" : "fa-folder-o")}
onClick={this.toggle.bind(this)}> </a>
</span>
</label>
</div>
<div className="match-group-items" style={this.state.expanded ? {} : {display: 'none'}}>
<ItemList title="Twitter influencers" list={this.state.twInfluencers}
spacesAllowed={false}
onAddToList={this.addToTwitter}
onRemoveFromList={this.removeFromTwitter}
onValidate={this.validateTwitter.bind(this)}
/>
<ItemList title="Instagram influencers" list={this.state.igInfluencers}
spacesAllowed={false}
onAddToList={this.addToInstagram}
onRemoveFromList={this.removeFromInstagram}
onValidate={this.validateInstagram.bind(this)}
/>
<ItemList title="Keywords" list={this.state.keywords}
onAddToList={this.addToKeywords}
onRemoveFromList={this.removeFromKeywords}
onValidate={this.validateKeywords.bind(this)}
/>
</div>
</div>
);
}
}
MatchGroup.propTypes = propTypes;
export default MatchGroup; |
import configureStore from "redux-mock-store"; //ES6 modules
import thunk from "redux-thunk";
import {
startNewNote,
startLoadingNotes,
startSaveNote,
startUploading,
} from "../../actions/notes";
import { types } from "../../types/types";
import { db } from "../../firebase/firebase-config";
import { fileUpload } from "../../helpers/fileUpload";
jest.mock("../../helpers/fileUpload", () => ({
fileUpload: jest.fn(() => {
return 'https://www.hola-mundo.com/cosa.jpg'
})
}));
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
const initState = {
auth: {
uid: "123456",
},
notes: {
active: { id: "5Fr7fJnkaJdgzm6D0wtg", title: "hola", body: "mundo" },
},
};
let store = mockStore(initState);
describe("Pruebas con las acciones de notes", () => {
beforeEach(() => {
store = mockStore(initState);
});
test("Debe de crear una nueva nota startNewNote", async () => {
await store.dispatch(startNewNote());
const actions = store.getActions();
expect(actions[0]).toEqual({
type: types.notesActive,
payload: {
id: expect.any(String),
title: "",
body: "",
date: expect.any(Number),
},
});
expect(actions[1]).toEqual({
type: types.notesAddNew,
payload: {
id: expect.any(String),
title: "",
body: "",
date: expect.any(Number),
},
});
const docId = actions[0].payload.id;
await db.collection("123456/journal/notes").doc(docId).delete();
});
test("startLoadingNotes debe cargar las notas", async () => {
await store.dispatch(startLoadingNotes("123456"));
const actions = store.getActions();
expect(actions[0]).toEqual({
type: types.notesLoad,
payload: expect.any(Array),
});
const expected = {
id: expect.any(String),
title: expect.any(String),
body: expect.any(String),
date: expect.any(Number),
};
expect(actions[0].payload[0]).toMatchObject(expected);
});
test("startSaveNote debe de actualizar la nota", async () => {
const note = {
id: "5Fr7fJnkaJdgzm6D0wtg",
title: "titulo",
body: "body",
};
await store.dispatch(startSaveNote(note));
const actions = store.getActions();
expect(actions[0].type).toBe(types.notesUpdated);
const docRef = await db.doc(`/123456/journal/notes/${note.id}`).get();
expect(docRef.data().title).toBe(note.title);
});
test("startUploading debe de actualizar el url del entry", async () => {
const file = new File([], "foto.jpg");
await store.dispatch(startUploading(file));
const docRef = await db.doc(
"/123456/journal/notes/5Fr7fJnkaJdgzm6D0wtg"
).get();
expect(docRef.data().url).toBe("https://www.hola-mundo.com/cosa.jpg");
});
}); |
package br.ufsm.csi.dao;
import br.ufsm.csi.model.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class PedidoDAO {
private String sql;
private Statement stmt;
private ResultSet rs;
private PreparedStatement preparedStatement;
private String status;
public String Cadastrar(Pedido p){
try(Connection connection = new ConectaDB().getConexao()) {
this.sql = "insert into pedido(quantidade, data_pedido, data_entrega, id_cliente, id_produto, id_status, id_veiculo) values (?, current_timestamp, ?, ?, ?, ?, ?)";
this.preparedStatement = connection.prepareStatement(this.sql, PreparedStatement.RETURN_GENERATED_KEYS);
this.preparedStatement.setFloat(1, p.getQuantidade());
this.preparedStatement.setDate(2, p.getDataEntrega());
this.preparedStatement.setInt(3, p.getCliente().getId());
this.preparedStatement.setInt(4, p.getProduto().getId());
this.preparedStatement.setInt(5, p.getStatus().getId());
this.preparedStatement.setInt(6, p.getVeiculo().getId());
this.preparedStatement.execute();
this.rs = this.preparedStatement.getGeneratedKeys();
this.rs.next();
if (this.rs.getInt(1) > 0) {
p.setId(this.rs.getInt(1));
this.status = "OK";
}
}catch (SQLException e){
e.printStackTrace();
this.status = "erro";
}
return this.status;
}
public ArrayList<Pedido> getPedidos(){
ArrayList<Pedido> pedidos = new ArrayList<Pedido>();
try(Connection connection = new ConectaDB().getConexao()){
this.sql = "select * from pedido, cliente, produto, veiculo, status " +
"where cliente.id_cliente = pedido.id_cliente and produto.id_produto = pedido.id_produto and veiculo.id_veiculo = pedido.id_veiculo " +
"and status.id_status = pedido.id_status";
this.stmt = connection.createStatement();
this.rs = stmt.executeQuery(this.sql);
while(this.rs.next()){
Pedido pedido = new Pedido();
pedido.setId(this.rs.getInt("id_pedido"));
pedido.setQuantidade(this.rs.getFloat("quantidade"));
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
pedido.setDataPedido(this.rs.getDate("data_pedido"));
pedido.setDataEntrega(this.rs.getDate("data_entrega"));
Cliente c = new Cliente();
c.setId(this.rs.getInt("id_cliente"));
c.setNome(this.rs.getString("nome_cliente"));
Produto p = new Produto();
p.setId(this.rs.getInt("id_produto"));
p.setNome(this.rs.getString("nome_produto"));
Veiculo v = new Veiculo();
v.setId(this.rs.getInt("id_veiculo"));
v.setPlaca(this.rs.getString("placa"));
Status status = new Status();
status.setId(this.rs.getInt("id_status"));
status.setNome(this.rs.getString("nome_status"));
pedido.setCliente(c);
pedido.setProduto(p);
pedido.setVeiculo(v);
pedido.setStatus(status);
pedidos.add(pedido);
}
}catch (SQLException e){
e.printStackTrace();
}
return pedidos;
}
} |
#pragma once
#include "../../holders/Canton.h"
#include "../../../common/SvkStr.h"
#include "Criterion.h"
template <typename Out>
class CriterionUJ : public Criterion<Canton*, Out>
{
public:
CriterionUJ(CriterionType type) : Criterion(type) {}
};
class CUJ_Nazov : public CriterionUJ<SvkStr>
{
public:
CUJ_Nazov() : CriterionUJ(CriterionType::UJ_Nazov)
{}
// Inherited via CriteriumUJ
SvkStr evaluate(Canton* data) final
{
return data->nazov;
}
};
class CUJ_Typ: public CriterionUJ<Canton::Type>
{
public:
CUJ_Typ() : CriterionUJ(CriterionType::UJ_Typ)
{}
// Inherited via CriteriumUJ
Canton::Type evaluate(Canton* data) final
{
return data->typ;
}
};
class CUJ_Prislusnost : public CriterionUJ<bool>
{
public:
CUJ_Prislusnost(SvkStr upperCantonName) :
CriterionUJ(CriterionType::UJ_Prislusnost),
upperCantonName(upperCantonName)
{}
// Inherited via CriteriumUJ
bool evaluate(Canton* data) final
{
Canton* item = data;
while (item->getParent())
{
item = item->getParent();
if (item->nazov == upperCantonName)
{
return true;
}
}
return false;
}
private:
SvkStr upperCantonName;
};
class CUJ_PocetMladych : public CriterionUJ<ullong>
{
public:
CUJ_PocetMladych() : CriterionUJ(CriterionType::UJ_PocetMladych)
{}
// Inherited via CriteriumUJ
ullong evaluate(Canton* data) final
{
return data->pocetMladych;
}
};
class CUJ_PocetDospelych : public CriterionUJ<ullong>
{
public:
CUJ_PocetDospelych() : CriterionUJ(CriterionType::UJ_PocetDospelych)
{}
// Inherited via CriteriumUJ
ullong evaluate(Canton* data) final
{
return data->pocetDospelych;
}
};
class CUJ_PocetDochodcov : public CriterionUJ<ullong>
{
public:
CUJ_PocetDochodcov() : CriterionUJ(CriterionType::UJ_PocetDochodcov)
{}
// Inherited via CriteriumUJ
ullong evaluate(Canton* data) final
{
return data->pocetDochodcov;
}
};
class CUJ_PocetObyvatelov : public CriterionUJ<ullong>
{
public:
CUJ_PocetObyvatelov() : CriterionUJ(CriterionType::UJ_PocetObyvatelov)
{}
// Inherited via CriteriumUJ
ullong evaluate(Canton* data) final
{
return
data->pocetMladych +
data->pocetDospelych +
data->pocetDochodcov;
}
};
class CUJ_CelkovaVymera : public CriterionUJ<double>
{
public:
CUJ_CelkovaVymera() : CriterionUJ(CriterionType::UJ_CelkovaVymera)
{}
// Inherited via CriteriumUJ
double evaluate(Canton* data) final
{
return data->celkovaVymera;
}
};
class CUJ_ZastavanaPlocha : public CriterionUJ<double>
{
public:
CUJ_ZastavanaPlocha() : CriterionUJ(CriterionType::UJ_ZastavanaPlocha)
{}
// Inherited via CriteriumUJ
double evaluate(Canton* data) final
{
return data->zastavanaPlocha;
}
};
class CUJ_Zastavanost : public CriterionUJ<double>
{
public:
CUJ_Zastavanost() : CriterionUJ(CriterionType::UJ_Zastavanost)
{}
// Inherited via CriteriumUJ
double evaluate(Canton* data) final
{
return 100 * data->zastavanaPlocha / data->celkovaVymera;
}
}; |
from typing import Any
from django.db.models.query import QuerySet
import stripe
# 10.5
# from django.views.generic.base import TemplateView # можно подставить ниже в class ...(TemplateView) для проверки шаблона
from django.views.generic.edit import CreateView
from django.views.generic.base import TemplateView
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.urls import reverse, reverse_lazy
from django.conf import settings
from django.http import HttpResponseRedirect
from http import HTTPStatus
from django.views.decorators.csrf import csrf_exempt # 10.6
from django.http import HttpResponse
from common.views import TitleMixin
from orders.forms import OrderForm
from products.models import Basket
from orders.models import Order
stripe.api_key = settings.STRIPE_SECRET_KEY
class SuccessTemplateView(TitleMixin, TemplateView):
template_name = 'orders/success.html'
title = 'Store - Спасибо за заказ!'
class CanceledTemplateView(TemplateView):
template_name = 'orders/cancled.html'
class OrderListView(TitleMixin, ListView): # 10.9
template_name = 'orders/orders.html'
title = "Store - Заказы"
queryset = Order.objects.all()
ordering = ('-id')
def get_queryset(self) -> QuerySet[Any]:
queryset = super(OrderListView, self).get_queryset()
return queryset.filter(initiator=self.request.user)
class OrderDetailView(DetailView): # 10.10
template_name = 'orders/order.html'
model = Order
def get_context_data(self, **kwargs: Any) -> dict[str, Any]:
context = super(OrderDetailView, self).get_context_data(**kwargs)
context['title'] = f'Store - Заказ #{self.object.id}'
return context
class OrderCreateView(TitleMixin, CreateView):
template_name = 'orders/order-create.html'
form_class = OrderForm
success_url = reverse_lazy('orders:order_create')
title = 'Store - Оформление заказа'
# у CreateView есть post - вызываем его для переопределения. Создается объект order и расширяем чз создание формы для перенаправления на оплату
def post(self, request, *args, **kwargs):
super(OrderCreateView, self).post(request, *args, **kwargs)
baskets = Basket.objects.filter(user=self.request.user)
line_items = [] # эту и 6 строк ниже можно убрать в models в class BasketQuerySet 10.7
for basket in baskets:
item = {
'price': basket.product.stripe_product_price_id,
'quantity': basket.quantity,
}
line_items.append(item)
checkout_session = stripe.checkout.Session.create(
# line_items - это то что должно формироваться из заказа (вещи, кол-во, цена)
line_items=line_items, # заменил нижний словарь из документации на автоматом создающийся line_items выше
# line_items = {
# # Provide the exact Price ID (for example, pr_1234) of the product you want to sell
# 'price': 'price_1O0kWxGjuU4rp3qHSBW3Nozo', # сформировал вручную id заказа в документации Stripe https://stripe.com/docs/checkout/quickstart?lang=python
# 'quantity': 1,
# },
metadata={'order_id': self.object.id}, # 10.6 добавил metadata, она приходит в ответе от Stripe после оплаченого товара, добавляем то что хотим получить, в данном случае id заказа. Ловим его ниже в def fulfill_order.
mode='payment',
success_url='{}{}'.format(settings.DOMAIN_NAME, reverse('orders:order_success')),
cancel_url='{}{}'.format(settings.DOMAIN_NAME, reverse('orders:order_canceled')),
)
return HttpResponseRedirect(checkout_session.url, status=HTTPStatus.SEE_OTHER)
def form_valid(self, form):
form.instance.initiator = self.request.user
return super(OrderCreateView, self).form_valid(form)
# все ниже из документации Stripe https://stripe.com/docs/payments/checkout/fulfill-orders
@csrf_exempt # 10.6 уберает необходимость передавать csrf-токен
def stripe_webhook_view(request):
payload = request.body
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = None
try:
event = stripe.Webhook.construct_event(
payload, sig_header, settings.STRIPE_WEBHOOK_SECRET
)
except ValueError as e:
# Invalid payload
return HttpResponse(status=400)
except stripe.error.SignatureVerificationError as e:
# Invalid signature
return HttpResponse(status=400)
# Handle the checkout.session.completed event
if event['type'] == 'checkout.session.completed':
# Retrieve the session. If you require line items in the response, you may include them by expanding line_items.
session = event['data']['object']
session = stripe.checkout.Session.retrieve(
event['data']['object']['id'],
expand=['line_items'],
)
line_items = session
# Fulfill the purchase...
fulfill_order(line_items)
# Passed signature verification
return HttpResponse(status=200)
# stripe_webhook_view который выше возвращает оплаченый заказ
# в fulfill_order меняем status, заполняем basket_history(из продуктов которые пришли в оплаченом заказе), удаляем корзину товаров тк она уже куплена
def fulfill_order(line_items):
order_id = int(line_items.metadata.order_id) # 10.6 14.00 из session берем order_id
order = Order.objects.get(id=order_id) # 10.8 берем заказ после оплаты
order.update_after_payment() # 10.8 обновляем этот заказ
# print("Fulfilling order") |
using System;
using System.Collections.Generic;
using System.Text;
namespace Buoi4_Struct
{
public class Bai1_Sach
{
struct Sach
{
public string TieuDe;
public string TenTacGia;
public int NamXuatBan;
public Sach(string _tieude, string _tentacgia, int _namxuatban)
{
TieuDe = _tieude;
TenTacGia = _tentacgia;
NamXuatBan = _namxuatban;
}
public void XuatThongTinSach()
{
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine(" Tiêu Đề: " + TieuDe);
Console.WriteLine(" Tên Tác Giả: " + TenTacGia);
Console.WriteLine(" Năm Xuất Bản: " + NamXuatBan);
}
}
static List<Sach> danhSachSach = new List<Sach>();
public static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
int choose = 0;
do
{
Menu();
choose = Convert.ToInt32(Console.ReadLine());
switch (choose)
{
case 1:
ThemSach();
break;
case 2:
HienThiDanhSachSach();
break;
case 3:
TimKiemSach();
break;
case 4:
Console.WriteLine("Chương trình đã kết thúc.");
break;
default:
Console.WriteLine("Không có lựa chọn này, vui lòng chọn lại.");
break;
}
} while (choose != 4);
}
public static void Menu()
{
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine("===== Menu =====");
Console.WriteLine("1. Thêm sách mới");
Console.WriteLine("2. Hiển thị danh sách các sách đã thêm");
Console.WriteLine("3. Tìm kiếm sách theo tiêu đề");
Console.WriteLine("4. Thoát chương trình");
Console.Write("Nhập lựa chọn của bạn: ");
}
public static void ThemSach()
{
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine("Nhập thông tin về cuốn sách mới:");
Console.Write("Tiêu đề: ");
string tieuDe = Console.ReadLine();
Console.Write("Tên tác giả: ");
string tenTacGia = Console.ReadLine();
string input = Console.ReadLine();
int namXuatBan;
bool isNumber = int.TryParse(input, out namXuatBan);
if (isNumber && namXuatBan > 1000 && namXuatBan < 2024)
{
Console.WriteLine("Nam Xuat Ban: " + namXuatBan);
Console.WriteLine("Thêm sách thành công.");
}
else
{
Console.WriteLine("Nam Xuat Ban Khong Hop le ");
}
}
public static void HienThiDanhSachSach()
{
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine("===== Danh Sách Sách =====");
if (danhSachSach.Count == 0)
{
Console.WriteLine("Danh sách sách trống.");
}
else
{
foreach (var sach in danhSachSach)
{
sach.XuatThongTinSach();
Console.WriteLine();
}
}
}
public static void TimKiemSach()
{
Console.OutputEncoding = Encoding.UTF8;
Console.Write("Nhập tiêu đề sách cần tìm: ");
string tieuDeCanTim = Console.ReadLine();
bool timThay = false;
foreach (var sach in danhSachSach)
{
if (sach.TieuDe.ToLower().Contains(tieuDeCanTim.ToLower()))
{
sach.XuatThongTinSach();
timThay = true;
}
}
if (!timThay)
{
Console.WriteLine("Không tìm thấy sách với tiêu đề đã nhập.");
}
}
}
} |
Usage
=====
gem5.fast [gem5 options] script.py [script options]
gem5 is copyrighted software; use the --copyright option for details.
Options
=======
--version show program's version number and exit
--help, -h show this help message and exit
--build-info, -B Show build information
--copyright, -C Show full copyright information
--readme, -R Show the readme
--outdir=DIR, -d DIR Set the output directory to DIR [Default: m5out]
--redirect-stdout, -r Redirect stdout (& stderr, without -e) to file
--redirect-stderr, -e Redirect stderr to file
--stdout-file=FILE Filename for -r redirection [Default: simout]
--stderr-file=FILE Filename for -e redirection [Default: simerr]
--listener-mode={on,off,auto}
Port (e.g., gdb) listener mode (auto: Enable if
running interactively) [Default: auto]
--listener-loopback-only
Port listeners will only accept connections over the
loopback device
--interactive, -i Invoke the interactive interpreter after running the
script
--pdb Invoke the python debugger before running the script
--path=PATH[:PATH], -p PATH[:PATH]
Prepend PATH to the system path when invoking the
script
--quiet, -q Reduce verbosity
--verbose, -v Increase verbosity
Statistics Options
------------------
--stats-file=FILE Sets the output file for statistics [Default:
stats.txt]
Configuration Options
---------------------
--dump-config=FILE Dump configuration output file [Default: config.ini]
--json-config=FILE Create JSON output of the configuration [Default:
config.json]
--dot-config=FILE Create DOT & pdf outputs of the configuration
[Default: config.dot]
--dot-dvfs-config=FILE Create DOT & pdf outputs of the DVFS configuration
[Default: none]
Debugging Options
-----------------
--debug-break=TICK[,TICK]
Create breakpoint(s) at TICK(s) (kills process if no
debugger attached)
--debug-help Print help on debug flags
--debug-flags=FLAG[,FLAG]
Sets the flags for debug output (-FLAG disables a
flag)
--debug-start=TICK Start debug output at TICK
--debug-end=TICK End debug output at TICK
--debug-file=FILE Sets the output file for debug [Default: cout]
--debug-ignore=EXPR Ignore EXPR sim objects
--remote-gdb-port=REMOTE_GDB_PORT
Remote gdb base port (set to 0 to disable listening)
Help Options
------------
--list-sim-objects List all built-in SimObjects, their params and default
values |
// TOOLBOX.h (Colors.h originaly)
//
// Posted by Gon1332 May 15 2015 on StackOverflow
// Modified by Shades Aug. 14 2018
// Modified by DoronovIV Jan. 25 2022
// PLEASE carefully read comments before using this tool, this will save you a lot of bugs that are going to be just about impossible to find.
#ifndef TOOLBOX_H
#define TOOLBOX_H
#include <iostream>
#include <string>
#include <ctime>
#include <conio.h>
#include <fstream>
namespace Toolbox
{
#pragma region METHODS
// Gets current PC time;
// returns — current time in string format;
std::string getCurrentTime();
// Sets cursor into specific position via escape sequence;
// "x" — the X-coordinate, columns;
// "y" — the Y-coordinate, rows.
void setCursor(int x, int y);
// Checks the input and returns the number of action, chosen by user;
// "nOptionsQuantity" — amount of options available for user;
// returns — Chosen menu option.
int getchSelector(size_t nOptionsQuantity);
// Checks the input and returns the number of action, chosen by user;
// "nOptionsQuantity" — amount of options available for user;
// returns — Chosen menu option.
int cinSelector(size_t nOptionsQuantity);
// Checks the input and returns the number of action, chosen by user with lower border;
// "nLowerValue" — lower border;
// "nOptionsQuantity" — amount of options available for user;
// returns — Chosen menu option.
int getchSelector(size_t nLowerValue, size_t nOptionsQuantity);
// Checks the input and returns the number of action, chosen by user with lower border;
// "nLowerValue" — lower border;
// "nOptionsQuantity" — amount of options available for user;
// returns — Chosen menu option.
int cinSelector(size_t nLowerValue, size_t nOptionsQuantity);
// Askes user for continuation;
// Produces a large bar with text in the middle of a screen.
// Example of use:
//
// while (c_cont != 'n' && c_cont != 'N')
// // some code
// space;
// showContinue();
// c_cont = _getwch();
void showContinue();
// Clears console in specific range;
void clearScreenInRange(size_t x_start, size_t x_end, size_t y_start, size_t y_end);
#pragma endregion METHODS
#pragma region NUMBERS
// A feature of order-quantity numeration;
// Example: an array got 5 elements, the index of last element is 4;
#ifndef NUMERATION_ISSUE
#define NUMERATION_ISSUE 1
#endif
// For addition of a new element to some structure;
#ifndef NEW_ELEMENT
#define NEW_ELEMENT 1
#endif
// For delition or modifiction of a new element of some structure;
#ifndef ONE_ELEMENT
#define ONE_ELEMENT 1
#endif
// For the "exit" option in menu;
#ifndef EXIT_MENU_OPTION
#define EXIT_MENU_OPTION 1
#endif
#pragma endregion NUMBERS
#pragma region FORMATING
#define space std::cout << "\n\n" // skip one line blank
#define line std::cout << "\n" // next line symbol
#define tab std::cout<<"\t" // tabulation symbol
#define doubleTab std::cout<<"\t\t" // tabulation symbol twice
#pragma endregion FORMATING
#pragma region SYMBOLS
/*
0 =
1 = ☺
2 = ☻
3 = ♥
4 = ♦
5 = ♣
6 = ♠
7 =
8 =
9 =
10 =
11 = ♂
12 = ♀
13 =
14 = ♫
15 = ☼
16 = ►
17 = ◄
18 = ↕
19 = ‼
20 = ¶
21 = §
22 = ▬
23 = ↨
24 = ↑
25 = ↓
26 = →
27 =
28 = ∟
29 = ↔
30 = ▲
31 = ▼
176 = ░
177 = ▒
178 = ▓
179 = │
180 = ┤
181 = ╡
182 = ╢
183 = ╖
184 = ╕
185 = ╣
186 = ║
187 = ╗
188 = ╝
189 = ╜
190 = ╛
191 = ┐
192 = └
193 = ┴
194 = ┬
195 = ├
196 = ─
197 = ┼
198 = ╞
199 = ╟
200 = ╚
201 = ╔
202 = ╩
203 = ╦
204 = ╠
205 = ═
206 = ╬
207 = ╧
208 = ╨
209 = ╤
210 = ╥
211 = ╙
212 = ╘
213 = ╒
214 = ╓
215 = ╫
216 = ╪
217 = ┘
218 = ┌
219 = █
220 = ▄
221 = ▌
222 = ▐
223 = ▀
248 = °
249 = ∙
250 = ·
251 = √
252 = №
253 = ¤
254 = ■
*/
#pragma endregion SYMBOLS
#pragma region COLORS
/* FOREGROUND */
// These codes set the actual text to the specified color
#define RESETTEXT "\x1B[0m" // Set all colors back to normal.
#define FOREBLK "\x1B[30m" // Black
#define FORERED "\x1B[31m" // Red
#define FOREGRN "\x1B[32m" // Green
#define FOREYEL "\x1B[33m" // Yellow
#define FOREBLU "\x1B[34m" // Blue
#define FOREMAG "\x1B[35m" // Magenta
#define FORECYN "\x1B[36m" // Cyan
#define FOREWHT "\x1B[37m" // White
/* BACKGROUND */
// These codes set the background color behind the text.
#define BACKBLK "\x1B[40m"
#define BACKRED "\x1B[41m"
#define BACKGRN "\x1B[42m"
#define BACKYEL "\x1B[43m"
#define BACKBLU "\x1B[44m"
#define BACKMAG "\x1B[45m"
#define BACKCYN "\x1B[46m"
#define BACKWHT "\x1B[47m"
// These will set the text color and then set it back to normal afterwards.
#define BLK(x) FOREBLK x RESETTEXT
#define RED(x) FORERED x RESETTEXT
#define GRN(x) FOREGRN x RESETTEXT
#define YEL(x) FOREYEL x RESETTEXT
#define BLU(x) FOREBLU x RESETTEXT
#define MAG(x) FOREMAG x RESETTEXT
#define CYN(x) FORECYN x RESETTEXT
#define WHT(x) FOREWHT x RESETTEXT
// Example usage: cout << BLU("This text's color is now blue!") << endl;
// These will set the text's background color then reset it back.
#define BackBLK(x) BACKBLK x RESETTEXT
#define BackRED(x) BACKRED x RESETTEXT
#define BackGRN(x) BACKGRN x RESETTEXT
#define BackYEL(x) BACKYEL x RESETTEXT
#define BackBLU(x) BACKBLU x RESETTEXT
#define BackMAG(x) BACKMAG x RESETTEXT
#define BackCYN(x) BACKCYN x RESETTEXT
#define BackWHT(x) BACKWHT x RESETTEXT
// Example usage: cout << BACKRED(FOREBLU("I am blue text on a red background!")) << endl;
// These functions will set the background to the specified color indefinitely.
// NOTE: These do NOT call RESETTEXT afterwards. Thus, they will set the background color indefinitely until the user executes cout << RESETTEXT
// OR if a function is used that calles RESETTEXT i.e. cout << RED("Hello World!") will reset the background color since it calls RESETTEXT.
// To set text COLOR indefinitely, see SetFore functions below.
#define SetBackBLK BACKBLK
#define SetBackRED BACKRED
#define SetBackGRN BACKGRN
#define SetBackYEL BACKYEL
#define SetBackBLU BACKBLU
#define SetBackMAG BACKMAG
#define SetBackCYN BACKCYN
#define SetBackWHT BACKWHT
// Example usage: cout << SetBackRED << "This text's background and all text after it will be red until RESETTEXT is called in some way" << endl;
// These functions will set the text color until RESETTEXT is called. (See above comments)
#define SetForeBLK FOREBLK
#define SetForeRED FORERED
#define SetForeGRN FOREGRN
#define SetForeYEL FOREYEL
#define SetForeBLU FOREBLU
#define SetForeMAG FOREMAG
#define SetForeCYN FORECYN
#define SetForeWHT FOREWHT
// Example usage: cout << SetForeRED << "This text and all text after it will be red until RESETTEXT is called in some way" << endl;
#define BOLD(x) "\x1B[1m" x RESETTEXT // Embolden text then reset it.
#define BRIGHT(x) "\x1B[1m" x RESETTEXT // Brighten text then reset it. (Same as bold but is available for program clarity)
#define UNDL(x) "\x1B[4m" x RESETTEXT // Underline text then reset it.
// Example usage: cout << BOLD(BLU("I am bold blue text!")) << endl;
// These functions will embolden or underline text indefinitely until RESETTEXT is called in some way.
#define SetBOLD "\x1B[1m" // Embolden text indefinitely.
#define SetBRIGHT "\x1B[1m" // Brighten text indefinitely. (Same as bold but is available for program clarity)
#define SetUNDL "\x1B[4m" // Underline text indefinitely.
// Example usage: cout << setBOLD << "I and all text after me will be BOLD/Bright until RESETTEXT is called in some way!" << endl;
#pragma endregion COLORS
}
#endif /* TOOLBOX_h */ |
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2019 Dan Tès <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram 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 3 of the License, or
# (at your option) any later version.
#
# Pyrogram 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 Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from io import BytesIO
from pyrogram.api.core import *
class UpdateChatParticipantDelete(Object):
"""Attributes:
ID: ``0x6e5f8c22``
Args:
chat_id: ``int`` ``32-bit``
user_id: ``int`` ``32-bit``
version: ``int`` ``32-bit``
"""
ID = 0x6e5f8c22
def __init__(self, chat_id: int, user_id: int, version: int):
self.chat_id = chat_id # int
self.user_id = user_id # int
self.version = version # int
@staticmethod
def read(b: BytesIO, *args) -> "UpdateChatParticipantDelete":
# No flags
chat_id = Int.read(b)
user_id = Int.read(b)
version = Int.read(b)
return UpdateChatParticipantDelete(chat_id, user_id, version)
def write(self) -> bytes:
b = BytesIO()
b.write(Int(self.ID, False))
# No flags
b.write(Int(self.chat_id))
b.write(Int(self.user_id))
b.write(Int(self.version))
return b.getvalue() |
<div class="flex justify-center mt-10">
<div class="bg-white p-4 shadow-md w-1/2 text-center rounded-ee-md m-auto">
@if ($isModalOpen)
<livewire:edit-user-modal :isOpen="$isModalOpen" :user="$editUser" />
@endif
<x-reuseable-modal name="confirm" title="Are you sure ??">
<p>User will get deleted permanently.</p>
<div class="mt-10">
<button x-on:click="show=false" class="px-3 py-2 rounded-md shadow-sm">Close</button>
<button wire:click="delete(id)"
class="bg-gray-900 text-white px-3 py-2 rounded-md shadow-sm">Confirm</button>
</div>
</x-reuseable-modal>
<h1 class="text-3xl">Event Users</h1>
<x-text-input class="w-full" label="" placeholder="Search user by name or email" name="search"
wire:model.live="search"></x-text-input>
<div class="mt-4">
<x-alert />
<table class="border">
<thead>
<tr class="grid grid-cols-4 gap-4 border p-2">
<th>Avatar</th>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr key={{ $user->id }} class="grid grid-cols-4 gap-4 border">
<td class="p-2 justify-center flex">
<a wire:navigate href="{{ route('event.user.show', $user->id) }}">
<img class="rounded-full w-10 h-10" src="/storage/{{ $user->avatar }}"
alt="">
</a>
</td>
<td class="p-2">{{ $user->name }}</td>
<td class="p-2">{{ $user->email }}</td>
<td>
<button wire:click="openModal({{ $user->id }})">Edit</button>
{{-- <button wire:click="delete({{ $user->id }})"
wire:confirm="Are you sure you want to delete user?">Delete</button> --}}
<button
x-on:click="$dispatch('open-modal',{name: 'confirm', id: '{{ $user->id }}'})">Delete</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div> |
App.Views.Header = Backbone.View.extend({
template: JST['app/templates/header.html'],
events: {
'click .logout': '_logout',
'click .login': '_login'
},
initialize: function(){
var self = this;
this.auth = new FirebaseSimpleLogin(App.FirebaseRef, function(error, user){
if (error) console.log(error);
if (user){
self.meRef = App.FirebaseRef.child('players/' + user.username);
self.meRef.on('value', function(dataSnapshot){
var me = dataSnapshot.val();
if (me){
App.me = dataSnapshot.val();
App.me.username = dataSnapshot.name();
self.render();
} else {
self.meRef.setWithPriority({
name: user.name,
profilePicture: 'https://graph.facebook.com/' + user.username + '/picture?width=200&height=200',
points: 0,
forecasts: App.forecastsSnapshot.val()
}, 0);
}
});
} else {
delete App.me;
self.render();
}
});
},
render: function(){
this.$el.html(this.template({ me: App.me }));
return this;
},
_logout: function(){
this.auth.logout();
},
_login: function(){
this.auth.login('facebook');
}
}); |
import { newtonRaphson } from '@fvictorio/newton-raphson-method';
import Big from 'big.js';
import { roundNumber } from 'helpers/math';
import { Market, Outcome } from 'models/market';
import { TradeDetails } from 'redux/ducks/trade';
function formatMiniTableItems(
action,
ticker,
market,
predictions,
selectedPredictionId,
selectedMarketId,
shares,
price,
maxROI,
totalStake,
fee
) {
const selectedPredictionObj = predictions.find(
prediction =>
prediction.id === selectedPredictionId &&
prediction.marketId === selectedMarketId
);
const items = [
{
key: 'prediction',
title: 'Prediction',
value: selectedPredictionObj?.title || ''
},
{
key: 'pricePerFraction',
title: 'Price per share',
// eslint-disable-next-line prettier/prettier
value: `${roundNumber(
price || selectedPredictionObj?.price || 0,
3
)} ${ticker}`
},
{
key: 'shares',
title: action === 'buy' ? 'Est. Shares bought' : 'Shares sold',
value: roundNumber(shares, 3)
},
{
key: 'fee',
title: `Fee (${roundNumber(
(market.fee + market.treasuryFee) * 100,
0
)}%)`,
value: roundNumber(fee, 3)
}
];
if (action === 'sell') return items;
// adding ROI + stake items to buy action
return [
...items,
{
key: 'roi',
title: 'Maximum ROI',
value: `${roundNumber(maxROI, 3)}%`
},
{
key: 'stake',
title: 'Total stake',
value: `${roundNumber(totalStake, 3)} ${ticker}`
}
];
}
function calculateSharesBought(
market: Market,
outcome: Outcome,
ethAmount: number
): TradeDetails {
// TODO: move formulas to polkamarketsjs
// taking fee of ethAmount
const fee = (market.fee + market.treasuryFee) * ethAmount;
const amount = ethAmount - fee;
// calculating product of all other outcome shares + amount
const product = market.outcomes.reduce((acc, cur) => {
if (cur.id === outcome.id) return acc;
return acc * (cur.shares + amount);
}, 1);
// calculating liquidity from n-root of product of all outcome shares
// eslint-disable-next-line no-restricted-properties
const liquidity = Math.pow(
market.outcomes.reduce((acc, cur) => {
return acc * cur.shares;
}, 1),
1 / market.outcomes.length
);
const newOutcomeShares = liquidity ** market.outcomes.length / product;
const shares = outcome.shares - newOutcomeShares + amount || 0;
const price = amount / shares || 0;
const maxROI = shares > 1e-6 ? (1 / price - 1) * 100 : 0;
const totalStake = ethAmount;
const maxStake = shares - amount;
// calculation outcome final price after trade
const outcomeShares = outcome.shares - shares + amount;
const priceTo =
1 /
market.outcomes.reduce((acc, cur) => {
return (
acc +
outcomeShares /
(cur.id === outcome.id ? outcomeShares : cur.shares + amount)
);
}, 0);
return {
price,
priceTo,
shares,
maxROI,
totalStake,
maxStake,
fee
};
}
function calculateEthAmountSold(
market: Market,
outcome: Outcome,
shares: number
): TradeDetails {
const sharesBig = new Big(shares.toString()).mul(100);
const outcomeSharesBig = new Big(outcome.shares.toString()).mul(100);
const otherOutcomeSharesBig = [] as any;
market.outcomes.forEach(marketOutcome => {
if (marketOutcome.id !== outcome.id) {
otherOutcomeSharesBig.push(
new Big(marketOutcome.shares.toString()).mul(100)
);
}
});
// Credit to Omen team for this formula
// https://github.com/protofire/omen-exchange/blob/29d0ab16bdafa5cc0d37933c1c7608a055400c73/app/src/util/tools/fpmm/trading/index.ts#L110
const totalStakeFunction = (f: Big) => {
// For three outcomes, where the first outcome is the one being sold, the formula is:
// f(r) = ((y - R) * (z - R)) * (x + a - R) - x*y*z
// where:
// `R` is r / (1 - fee)
// `x`, `y`, `z` are the market maker holdings for each outcome
// `a` is the amount of outcomes that are being sold
// `r` (the unknown) is the amount of collateral that will be returned in exchange of `a` tokens
// multiplying all terms by 100 to avoid floating point errors
const F = f.mul(100);
const firstTerm = otherOutcomeSharesBig
.map(h => h.minus(F))
.reduce((a, b) => a.mul(b));
const secondTerm = outcomeSharesBig.plus(sharesBig).minus(F);
const thirdTerm = otherOutcomeSharesBig.reduce(
(a, b) => a.mul(b),
outcomeSharesBig
);
return firstTerm.mul(secondTerm).minus(thirdTerm).div(100);
};
const totalStakeBig = newtonRaphson(totalStakeFunction, 0, {
maxIterations: 100
});
// flooring totalStake to avoid floating point errors
const totalStake = Number(totalStakeBig) * 0.999999999;
const price = shares > 0 ? totalStake / shares : outcome.price;
// ROI is not relevant on sell
const maxROI = 1;
const maxStake = 0;
const fee = totalStake * (market.fee + market.treasuryFee);
// calculation outcome final price after trade
const outcomeShares = outcome.shares + shares - totalStake;
const priceTo =
1 /
market.outcomes.reduce((acc, cur) => {
return (
acc +
outcomeShares /
(cur.id === outcome.id ? outcomeShares : cur.shares - totalStake)
);
}, 0);
return {
price,
priceTo,
shares,
maxROI,
totalStake,
maxStake,
fee
};
}
function calculateTradeDetails(action, market, outcome, amount): TradeDetails {
if (action === 'sell') {
return calculateEthAmountSold(market, outcome, amount);
}
return calculateSharesBought(market, outcome, amount);
}
export { formatMiniTableItems, calculateTradeDetails }; |
{% extends "base.html" %}
{% load static %}
{% block content %}
<!-- Hero Section-->
<section style="background: url({% static 'img/IMG_0965.jpeg' %}); background-size: cover; background-position: center center" class="hero">
<div class="container">
<div class="row">
<div class="col-lg-7">
<h1>matter of taste</h1>
<h2>a genuine and chaotic blog by @nesterenkojul</h2>
</div>
</div><a href=".intro" class="continue link-scroll">Discover More</a>
</div>
</section>
<!-- Intro Section-->
<section class="intro">
<div class="container">
<div class="row">
<div class="col-lg-8">
<h2 class="h3">Weird combo of topics</h2>
<p class="text-big"> Staying relevant with <strong>fashion</strong>,
finding a path in <strong>IT</strong>, unleashing creativity with <strong>recipes</strong>,
seeking beauty in <strong>art</strong>, making memories with <strong>travel</strong>.</p>
</div>
</div>
</div>
</section>
<section class="featured-posts no-padding-top">
<div class="container">
<!-- Featured Categories-->
{% for cat in categories %}
<a href="{{ cat.get_absolute_url }}">
<div class="row d-flex align-items-stretch">
{% if not forloop.first and not forloop.last %}
<div class="image col-lg-5"><img src="{{ cat.thumbnail.url }}" alt="..."></div>
{% endif %}
<div class="text col-lg-5">
<div class="text-inner d-flex align-items-center">
<div class="content">
<header class="post-header">
<h2 class="h2">{{ cat.title }}</h2>
</header>
<p>{{ cat.overview|linebreaks|truncatechars:120 }}</p>
</div>
</div>
</div>
{% if forloop.first or forloop.last %}
<div class="image col-lg-5"><img src="{{ cat.thumbnail.url }}" alt="..."></div>
{% endif %}
</div>
</a>
{% endfor %}
</div>
</section>
<!-- Featured Posts
{% for obj in featured %}
<div class="row d-flex align-items-stretch">
{% if not forloop.first and not forloop.last %}
<div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div>
{% endif %}
<div class="text col-lg-7">
<div class="text-inner d-flex align-items-center">
<div class="content">
<header class="post-header">
<div class="category">
{% for cat in obj.categories.all %}
<a href="#">{{ cat }}</a>
{% endfor %}
</div>
<a href="{{ obj.get_absolute_url }}"><h2 class="h4">{{ obj.title }}</h2></a>
</header>
<p>{{ obj.overview }}</p>
<footer class="post-footer d-flex align-items-center"><a href="#" class="author d-flex align-items-center flex-wrap">
<div class="avatar"><img src="{% static 'img/avatar-1.jpg' %}" alt="..." class="img-fluid"></div>
<div class="title"><span>John Doe</span></div></a>
<div class="date"><i class="icon-clock"></i> {{ obj.posted|timesince }} ago </div>
<div class="comments"><i class="icon-comment"></i>{{ obj.comment_count }}</div>
</footer>
</div>
</div>
</div>
{% if forloop.first or forloop.last %}
<div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div>
{% endif %}
</div>
{% endfor %}
</div>
</section>-->
<!-- Divider Section-->
<section style="background: url({% static 'img/divider.jpeg' %}); background-size: cover; background-position: center bottom" class="divider">
<div class="container">
<div class="row">
<div class="col-md-8">
<h2>A blog by an introverted and self-conscious girl, who is studying Computer Science but spends all her time consuming fashion and food content.</h2><a href="/about/" class="hero-link">about her</a>
</div>
</div>
</div>
</section>
<!-- Latest Posts -->
<section class="latest-posts">
<div class="container">
<header>
<h2>Latest from the blog</h2>
<p class="text-big">Don't judge a post by its publication date.</p>
</header>
<div class="row">
{% for obj in recent %}
<div class="post col-md-4">
<div class="post-thumbnail"><a href="{{ obj.get_absolute_url }}"><img src="{{ obj.thumbnail.url }}" alt="..." class="img-fluid"></a></div>
<div class="post-details">
<div class="post-meta d-flex justify-content-between">
<div class="date">{{ obj.posted }}</div>
<div class="category">
{% for cat in obj.categories.all %}
<a href="#">{{ cat }}</a>
{% endfor %}
</div>
</div><a href="{{ obj.get_absolute_url }}">
<h3 class="h4">{{ obj.title }}</h3></a>
<p class="text-muted">{{ obj.overview }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
</section>
<!-- Possible Newsletter Section
<section class="newsletter no-padding-top">
<div class="container">
<div class="row">
<div class="col-md-6">
<h2>Subscribe to Newsletter</h2>
<p class="text-big">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
<div class="col-md-8">
<div class="form-holder">
<form action="#">
<div class="form-group">
<input type="email" name="email" id="email" placeholder="Type your email address">
<button type="submit" class="submit">Subscribe</button>
</div>
</form>
</div>
</div>
</div>
</div>
</section>-->
<!-- Gallery Section-->
<section class="gallery no-padding">
<div class="row">
{% for obj in featured %}
<div class="mix col-lg-3 col-md-3 col-sm-6">
<div class="item"><a href="{{ obj.get_absolute_url }}" class="image"><img src="{{ obj.thumbnail.url }}" alt="..." class="img-fluid">
<div class="overlay d-flex align-items-center justify-content-center"><i class="gg-eye"></i></div></a></div>
</div>
{% endfor %}
</div>
</section>
{% endblock content %} |
package com.cg.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.cg.dto.DepartmentDto;
import com.cg.entity.Department;
import com.cg.mapper.DepartmentMapper;
import com.cg.repository.DepartmentRepository;
import com.cg.service.DepartmentService;
import lombok.AllArgsConstructor;
@Service
@AllArgsConstructor
public class DepartmentServiceImpl implements DepartmentService {
private DepartmentRepository departmentRepository;
private static final Logger LOGGER = LoggerFactory.getLogger(DepartmentServiceImpl.class);
@Override
public DepartmentDto saveDepartment(DepartmentDto departmentDto) {
LOGGER.info("saving department");
// convert department dto to department jpa entity
Department department = DepartmentMapper.mapToDepartment(departmentDto);
Department savedDepartment = departmentRepository.save(department);
DepartmentDto savedDepartmentDto = DepartmentMapper.mapToDepartmentDto(savedDepartment);
return savedDepartmentDto;
}
@Override
public DepartmentDto getDepartmentByCode(String departmentCode) {
Department department = departmentRepository.findByDepartmentCode(departmentCode);
DepartmentDto departmentDto = DepartmentMapper.mapToDepartmentDto(department);
return departmentDto;
}
} |
import React from 'react';
import FormatLineSpacingIcon from '@mui/icons-material/FormatLineSpacing';
import FilterItem from './FilterItem';
import { Button, Collapse } from '@mui/material';
import { useStore } from '@/hooks';
const FilterResult = () => {
const { filterSearchActive, setFilterSearchActive, handleChange } =
useStore();
const uploadDate = [
'Last hour',
'Today',
'This week',
'This month',
'This year',
];
const type = ['Video', 'Channel', 'Playlist', 'Moive'];
const duration = ['Under 4 minutes', '4-20 minutes', 'Over 20 minutes'];
const features = [
'Live',
'4K',
'HD',
'Subtitles/CC',
'Creative Commons',
'360',
'VR180',
'3D',
'HDR',
'Location',
'Purchased',
];
const sortBy = ['Relevance', 'Upload date', 'View count', 'Rating'];
return (
<div className="filter-result">
<div className="filter-result__top">
<Button
style={{ color: 'black' }}
startIcon={<FormatLineSpacingIcon />}
onClick={() =>
handleChange(filterSearchActive, setFilterSearchActive)
}>
Filters
</Button>
</div>
<Collapse in={filterSearchActive}>
<div className="filter-result__wrapper">
<FilterItem title="UPLOAD DATE" list={uploadDate} />
<FilterItem title="TYPE" list={type} />
<FilterItem title="DURATION" list={duration} />
<FilterItem title="FEATURES" list={features} />
<FilterItem title="SORT BY" list={sortBy} />
</div>
</Collapse>
</div>
);
};
export default FilterResult; |
# GA_BinarySearch_Ronda
What is binary search and how does it work?
- Binary search loops through an array, identifying which half of the array the search target is in. Each time, the left or right references are updated so that only the portion the target could be in is searched. When the target is at the midpoint, its index is returned.
What is the time complexity of binary search?
- O(log n), because the length of the portion being searched is halved each time the binary search loops.
When is binary search preferred over linear search?
- Binary search is preferable to linear search for large data sets, when in a sorted array.
What are the key requirements for binary search to work correctly?
- The array must be sorted beforehand. For a recursive binary search, the left and right references also need to be enetered as arguments.
Can binary search be applied to unsorted arrays? Why or why not?
- Binary search does not work on unsorted arrays, because in an unsorted array it is not possible to identify which half the search target is in based on the value of the midpoint. |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
// import "hardhat/console.sol";
contract ecRecover is Ownable {
using ECDSA for bytes32;
address private signer;
function setSigner(address signer_) external onlyOwner {
signer = signer_;
}
function recover(
bytes32 _ethSignedMessageHash,
bytes memory _signature
) public view returns (address addr) {
(bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);
addr = ecrecover(_ethSignedMessageHash, v, r, s);
}
function splitSignature(
bytes memory sig
) public pure returns (bytes32 r, bytes32 s, uint8 v) {
require(sig.length == 65, "invalid signature length");
assembly {
/*
First 32 bytes stores the length of the signature
add(sig, 32) = pointer of sig + 32
effectively, skips first 32 bytes of signature
mload(p) loads next 32 bytes starting at the memory address p into memory
*/
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
// implicitly return (r, s, v)
}
} |
package com.jyx.oss.impl;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.jyx.oss.ALiOssService;
import com.jyx.oss.constant.CustomConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
/**
* @ClassName: ALiOssServiceImpl
* @Description: ALiOssServiceImpl实现类
* @Author: pengmingming
* @Date: 2024-03-05 13:47
* @Version: 1.0
**/
@Slf4j
@Service
public class ALiOssServiceImpl implements ALiOssService {
private final OSS ossClient;
/**
* 构造注入
* @param ossClient
* */
public ALiOssServiceImpl(OSS ossClient) {
this.ossClient = ossClient;
}
/**
* 上传文件
* @param localPathFile 本地文件包含路径
* @param bucketName OSS文件存储桶名称
* @param filePath OSS文件路径
* @param fileName OSS文件名称
* @throws Exception
*/
@Override
public void uploadFile(String localPathFile, String bucketName, String filePath, String fileName) throws Exception {
debugOnly("入参: {} | {} | {} | {}", localPathFile, bucketName, filePath, fileName);
if (ossClient.doesBucketExist(bucketName)) {
ossClient.putObject(bucketName, getObjectName(filePath, fileName),
new FileInputStream(localPathFile));
log.info("文件{}上传成功", localPathFile);
} else {
String errMsg = formatMsg(CustomConstant.CUSTOM_ALI_OSS_BUCKET_NOT_EXIST, bucketName);
log.error("errMsg: {}", errMsg);
throw new RuntimeException(errMsg);
}
}
/**
* 下载文件
* @param bucketName OSS文件存储桶名称
* @param filePath OSS文件路径
* @param fileName OSS文件名称
* @param localPathFile 本地文件
* @throws Exception
*/
@Override
public void downloadFile(String bucketName, String filePath, String fileName, String localPathFile) throws Exception {
debugOnly("入参: {} | {} | {} | {}", bucketName, filePath, fileName, localPathFile);
String filePathName = getObjectName(filePath, fileName);
if (ossClient.doesObjectExist(bucketName, filePathName)) {
int bytesRead;
OSSObject ossObject = null;
byte[] buffer = new byte[1024];
FileOutputStream outputStream = null;
try {
ossObject = ossClient.getObject(bucketName, filePathName);
outputStream = new FileOutputStream(localPathFile, true);
while ((bytesRead = ossObject.getObjectContent().read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} finally {
if (outputStream != null) {
outputStream.close();
}
if (ossObject != null) {
ossObject.close();
}
}
log.info("文件{}下载成功", localPathFile);
} else {
String errMsg = formatMsg(CustomConstant.CUSTOM_ALI_OSS_FILE_NOT_EXIST, bucketName, filePathName);
log.error("errMsg: {}", errMsg);
throw new RuntimeException(errMsg);
}
}
/**
* 删除单个文件
* @param bucketName OSS文件存储桶名称
* @param filePath OSS文件路径
* @param fileName OSS文件名称。
* @throws Exception
*/
@Override
public void deleteFile(String bucketName, String filePath, String fileName) throws OSSException, ClientException {
debugOnly("入参: {} | {} | {}", bucketName, filePath, fileName);
String filePathName = getObjectName(filePath, fileName);
if (ossClient.doesObjectExist(bucketName, filePathName)) {
ossClient.deleteObject(bucketName, filePathName);
log.info("文件{}删除成功", filePathName);
} else {
String errMsg = formatMsg(CustomConstant.CUSTOM_ALI_OSS_FILE_NOT_EXIST, bucketName, filePathName);
log.error("errMsg: {}", errMsg);
throw new RuntimeException(errMsg);
}
}
/**
* 批量删除文件
* @param bucketName OSS文件存储桶名称
* @param filePath OSS文件路径
* @param fileNames OSS文件列表
@throws Exception
*/
@Override
public void deleteFile(String bucketName, String filePath, List<String> fileNames) throws OSSException, ClientException {
for (String fileName : fileNames) {
deleteFile(bucketName, filePath, fileName);
}
}
private String getObjectName(String filePath, String fileName) {
filePath = filePath.trim();
fileName = fileName.trim();
if (filePath.startsWith(CustomConstant.CUSTOM_ALI_OSS_BIAS)) {
filePath = filePath.substring(CustomConstant.CUSTOM_ALI_OSS_BIAS.length());
}
if (fileName.startsWith(CustomConstant.CUSTOM_ALI_OSS_BIAS)) {
fileName = fileName.substring(CustomConstant.CUSTOM_ALI_OSS_BIAS.length());
}
if (filePath.endsWith(CustomConstant.CUSTOM_ALI_OSS_BIAS)) {
return filePath + fileName;
} else {
return filePath + CustomConstant.CUSTOM_ALI_OSS_BIAS + fileName;
}
}
private String formatMsg(String format, Object... args) {
return String.format(format, args);
}
private void debugOnly(String format, Object... arguments) {
if (log.isDebugEnabled()) {
log.debug(format, arguments);
}
}
} |
from django.db import models
class Date(models.Model):
date_rep = models.DateField(primary_key=True)
day = models.BigIntegerField(blank=True, null=True)
month = models.BigIntegerField(blank=True, null=True)
year = models.BigIntegerField(blank=True, null=True)
class Meta:
db_table = 'date'
class GeoDistribution(models.Model):
geo_id = models.TextField(primary_key=True)
country_territory = models.TextField(db_column='country/territory', blank=True, null=True) # Field renamed to remove unsuitable characters.
country_territory_code = models.TextField(db_column='country/territory_code', blank=True, null=True) # Field renamed to remove unsuitable characters.
pop2019 = models.FloatField(blank=True, null=True)
continent = models.TextField(blank=True, null=True)
class Meta:
db_table = 'geo_distribution'
class Records(models.Model):
date_rep = models.OneToOneField(Date, models.DO_NOTHING, db_column='date_rep', primary_key=True)
geo = models.ForeignKey(GeoDistribution, models.DO_NOTHING)
case_num = models.BigIntegerField(blank=True, null=True)
death_num = models.BigIntegerField(blank=True, null=True)
cum14d_infectionrate_100t = models.FloatField(db_column='cum14D_infectionrate/100T', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters.
class Meta:
db_table = 'records'
unique_together = (('date_rep', 'geo'),) |
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.client.opensearch.nodes;
import jakarta.json.stream.JsonGenerator;
import java.util.function.Function;
import org.opensearch.client.json.JsonpDeserializable;
import org.opensearch.client.json.JsonpDeserializer;
import org.opensearch.client.json.JsonpMapper;
import org.opensearch.client.json.JsonpSerializable;
import org.opensearch.client.json.ObjectBuilderDeserializer;
import org.opensearch.client.json.ObjectDeserializer;
import org.opensearch.client.util.ApiTypeHelper;
import org.opensearch.client.util.ObjectBuilder;
import org.opensearch.client.util.ObjectBuilderBase;
// typedef: nodes._types.KeyedProcessor
@JsonpDeserializable
public class KeyedProcessor implements JsonpSerializable {
private final Process statistics;
private final String type;
// ---------------------------------------------------------------------------------------------
private KeyedProcessor(Builder builder) {
this.statistics = ApiTypeHelper.requireNonNull(builder.statistics, this, "statistics");
this.type = ApiTypeHelper.requireNonNull(builder.type, this, "type");
}
public static KeyedProcessor of(Function<Builder, ObjectBuilder<KeyedProcessor>> fn) {
return fn.apply(new Builder()).build();
}
/**
* Required - API name: {@code statistics}
*/
public final Process statistics() {
return this.statistics;
}
/**
* Required - API name: {@code type}
*/
public final String type() {
return this.type;
}
/**
* Serialize this object to JSON.
*/
public void serialize(JsonGenerator generator, JsonpMapper mapper) {
generator.writeStartObject();
serializeInternal(generator, mapper);
generator.writeEnd();
}
protected void serializeInternal(JsonGenerator generator, JsonpMapper mapper) {
generator.writeKey("statistics");
this.statistics.serialize(generator, mapper);
generator.writeKey("type");
generator.write(this.type);
}
// ---------------------------------------------------------------------------------------------
/**
* Builder for {@link KeyedProcessor}.
*/
public static class Builder extends ObjectBuilderBase implements ObjectBuilder<KeyedProcessor> {
private Process statistics;
private String type;
/**
* Required - API name: {@code statistics}
*/
public final Builder statistics(Process value) {
this.statistics = value;
return this;
}
/**
* Required - API name: {@code statistics}
*/
public final Builder statistics(Function<Process.Builder, ObjectBuilder<Process>> fn) {
return this.statistics(fn.apply(new Process.Builder()).build());
}
/**
* Required - API name: {@code type}
*/
public final Builder type(String value) {
this.type = value;
return this;
}
/**
* Builds a {@link KeyedProcessor}.
*
* @throws NullPointerException
* if some of the required fields are null.
*/
public KeyedProcessor build() {
_checkSingleUse();
return new KeyedProcessor(this);
}
}
// ---------------------------------------------------------------------------------------------
/**
* Json deserializer for {@link KeyedProcessor}
*/
public static final JsonpDeserializer<KeyedProcessor> _DESERIALIZER = ObjectBuilderDeserializer.lazy(
Builder::new,
KeyedProcessor::setupKeyedProcessorDeserializer
);
protected static void setupKeyedProcessorDeserializer(ObjectDeserializer<KeyedProcessor.Builder> op) {
op.add(Builder::statistics, Process._DESERIALIZER, "statistics");
op.add(Builder::type, JsonpDeserializer.stringDeserializer(), "type");
}
} |
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap">
<!-- Font awesome -->
<link rel="stylesheet" type="text/css" href="{{asset('css/fontawesome.css')}}">
<!-- Styles -->
<link rel="stylesheet" href="{{ mix('css/app.css') }}">
<!-- Include main css file -->
<link rel="stylesheet" type="text/css" href="{{asset('css/main.css')}}">
<!-- Include favicon -->
<link rel="shortcut icon" type="image/png" href="{{asset('img/favicon.png')}}">
@livewireStyles
<!-- Scripts -->
<!-- Jquery: -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Ckeditor: 4 -->
<script src="https://cdn.ckeditor.com/4.16.1/standard/ckeditor.js"></script>
{{--<!-- Ckeditor: 5 -->--}}
{{--<script src="https://cdn.ckeditor.com/ckeditor5/27.1.0/classic/ckeditor.js"></script>--}}
<!-- Alpine: -->
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js" defer></script>
<!-- SweetAlert: -->
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script src="{{ mix('js/app.js') }}" defer></script>
<script type="text/javascript" src="{{ asset('js/search.js') }}" defer></script>
<script type="text/javascript" src="{{ asset('js/custom.js') }}" defer></script>
</head>
<body class="font-sans antialiased">
<x-jet-banner />
<div class="min-h-screen bg-gray-100">
<!-- Insert nav menu: -->
@livewire('navigation-menu')
<!-- End nav menu: -->
<!-- Page Heading -->
@if (isset($header))
{{--Leave empty for now:--}}
<header class="bg-white shadow">
{{--<div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">--}}
{{--{{ $header }}--}}
{{--</div>--}}
</header>
@endif
<!-- Page Content -->
<main>
<!-- Page Content Goes here -->
{{ $slot }}
<!-- End some divs here -->
</main>
</div>
<footer>
@stack('modals')
@livewireScripts
@stack('scripts')
</footer>
</body>
</html> |
import UserModel from "../mongoose/UserModel";
import User from "../models/User";
import UserDaoI from "../interfaces/UserDaoI";
/**
* Implements Data Access Object managing data storage
* of Users
* @implements {UserDaoI} UserDaoI
* @property {UserDao} userDao Private single instance of UserDao
*/
export default class UserDao implements UserDaoI {
private static userDao: UserDao | null = null;
public static getInstance = (): UserDao => {
if (UserDao.userDao === null) {
UserDao.userDao = new UserDao();
}
return UserDao.userDao;
};
private constructor() {}
findAllUsers = async (): Promise<User[]> => UserModel.find();
findUserById = async (uid: string): Promise<any> => UserModel.findById(uid);
createUser = async (user: User): Promise<User> => UserModel.create(user);
updateUser = async (uid: string, user: User): Promise<any> =>
UserModel.updateOne({ _id: uid }, { $set: user });
deleteUser = async (uid: string): Promise<any> =>
UserModel.deleteOne({ _id: uid });
} |
---
#var-frontmatter #format-yaml
title : Versatile Description Format specification
author : Nikolay Gniteev (godhart@gmail.com)
version : 1.0.draft.4
description : Specification of Versatile Description Format (for hardware)
---
<!--
#TODO: reversed format - кода в исходном файле в fenced пишется описание и кодогенераторы, display и т.п.
-->
<!--
#TODO: сброс файла / удаление файла
-->
<!--
#TODO: установка переменных файла (и авто-занос subject в файл)
-->
# Спецификация формата описания Versatile Description Format
Данный формат обеспечивает смешанное описание документации и кода в одном файле
Формат позволяет совмещать разные форматы структурированного текстового описания, языки и способы описания в одном файле
Формат позволяет описывать документацию и код секциями и держать описание и код рядом друг с другом, а так же формировать фрагменты кода из самого описания
Из описанного в данном формате файла можно получить документацию и исходные файлы а так же, кроме этого,
с помощью описание в этом формате позволяет осуществлять интерактивное выполнение / инкрементальную компиляцию кода и т.п.
Формат позволяет создавать документацию, код и сопутствующие артефакты и интерактивно выполнять код последовательно добавляя / изменяя фрагменты документации и кода с помощью "ячеек", являющихся основными "строительным" элементом документа
Цепочки ячеек документа могут организовываться как линейным так и нелинейными способами чтобы наглядно показать разницу между различными вариантами или для того чтобы провести эксперименты
> Был обнаружен проект, в котором много идей уже реализовано - [Quarto](https://quarto.org). В ближайшем времени принципы проекта VDF будут пересмотрены с точки зрения интеграции с Quarto.
# Принцип описания
Текстовый файл делится на "ячейки" - элементарные единицы
Ячейки могут быть двух типов - описательные / исполнимые
Разделителем ячеек является строка, содержащая `---`
Формат текста в описательных ячейках определяется типом файла
Возможно использование в качестве основы различных форматов структурированного описания - `markdown`, `asciidoc` и т.п. в которых имеется понятие `fenced code` а так же использование формата `jupyter notebook` (для описательных ячеек используется `markdown`). Но на весь документ м.б. использоваться только один формат.
Исполнимые ячейки в форматах структурированного описания должны содержать только `fenced code`
В формате `jupyter notebook` исполнительная ячейка должна быть типа `code` с указателем используемой "магии"
> В исполнимых ячейках строка `---` не приведёт к разделению на ячейки
В исполнимых ячейках содержатся специальные тэги, управляющими как с их с помощью формируются исходные файлы / документация или осуществляется исполнение (симуляция и т.п.)
При исполнении определённых ячеек результат сохраняется и это значение м.б. использовано позже если ячейке было дано имя, а так же при исполнении каждой ячейки регистрируется вывод `stdout`/`stderr`, который может быть отображён с помощью специальных ячеек
Некоторые тэги могут так же использоваться для наполнения описательных ячеек (подстановка значений, преобразования кода в описание)
# Система тэгов
Тэги определяют поведение при компиляции исполнимой ячейки в код, структуру последовательности ячеек и многие другие аспекты
В ячейке указывается:
- обязательно один базовый тэг (один и только один)
- опционально тэги расширения
Тэги расширения могут быть заданы / загружены под типовой случай и иметь эффект на последующие ячейки,
а так же иметь эффект на заданную секцию ячеек (границы секции определяется так же с помощью тэгов)
Формат указания тэгов: в первой строке исполнимой ячейки тэги указываются последовательно через пробел после волшебного начала `%%vdf `.
Первым указывается базовый тэг, затем тэги расширения. Порядок тэгов расширения м.б. любым, при этом порядок влияет на то, какой будет результат.
<!--
#TODO: описать отдельно как порядок тэгов скажется на результат, в какой момент применяется базовый тэг
-->
Тэги могут дополняться значениями, которые следуют за именем тэга через символ `-`.
Символы значений должны быть из подмножества `alpha_numeric`, если не указано иное.
Если после # следует !, то это отменяет тэг, если он был определён ранее (в ячейке или глобально)
`%%vdf #<valueless_tag_name> #<tag_name>-<tag_value> #<tag_name>-<tag_value> #!<tag_name>...`
# Базовые тэги
Тэги приведены в порядке частоты применения и/или их важности в общем процессе
## Тэги описания исходного кода
Выполнение ячеек с тэгами такого типа по умолчанию приводит к созданию и компиляции исходных файлов
### none
Эта ячейка не исполняемая
### doc
Секция с кодом для формирования фрагментов документации
### code
Секция с кодом для архитектуры блока.
В тексте ячейки содержится код декларативной части архитектуры блока и/или тела архитектуры.
В тексте ячейки:
до строки `---` - декларативная часть, после - тело
если строка `---` отсутствует, то считается что декларативной части нет (если у тэга нет доп.значения `declaration`)
Возможные значения для тэга:
- без значения эквивалентно `add`
- `add` - дополнение кода из прошлых ячеек
- `new` - ввод кода заново, значения из прошлых ячеек игнорируются
- `declaration` указание в явном виде что в ячейке код только для декларативной части
- `body` указание в явном виде что что в ячейке код только для "тела"
Для значений `declaration`, `body` подразумевается одновременное действие значения `add`
### header
Секция с кодом заголовочной части.
В тексте ячейки содержится код, предшествующий объявлению блока и/или его архитектуры (там где такое разделение существует) а так же для пакета и/или его тела.
Если спецификация языка на котором написан текст ячейке подразумевает разделение заголовочной части для декларации блока и архитектуры (пакета/тела), то:
до строки `---` - заголовочная часть предшествующая объявлению блока, после - часть предшествующая архитектуре блока (в тех случаях где есть такое разделение)
если `---` отсутствует, то считается что заголовочной части блока нет (если у тэга нет доп.значения `declaration`)
Остальной принцип применения и дополнительные значения аналогичны тэгу `code`
### unit
Секция с кодом объявления блока
В тексте ячейки содержится код с декларацией параметров блока и/или интерфейса блока.
В тексте ячейки:
до строки `---` - код с описанием параметров блока, после - интерфейсы блока
если строка `---` отсутствует, то считается что часть с параметрами отсутствует (если у тэга нет доп.значения `generics`)
Возможные значения для тэга:
- без значения эквивалентно `add`
- `add` - дополнение кода из прошлых ячеек
- `new` - ввод кода заново, значения из прошлых ячеек игнорируются
- `generics` - указание в явном виде что в ячейке код только для параметров
- `interface` - указание в явном виде что что в ячейке код только для интерфейсов
Для значений `generics`, `interface` подразумевается одновременное действие значения `add`
### package
Секция с кодом для пакета
Требует использование тэга `target` (т.е. результат всегда будет в дополнительном исходном файле)
В тексте ячейки:
до строки `---` - код для декларативной части пакета, после - для тела пакета
если строка `---` отсутствует, то считается что декларативная часть отсутствует (если у тэга нет доп.значения `declaration`)
Остальной принцип применения и дополнительные значения аналогичны тэгу `code`
### constraints
Ограничения для блока (задел под синтез/кодогенерацию)
Требует использование тэга `target` (т.е. результат всегда будет в дополнительном исходном файле)
В тексте ячейки содержится текст кода с определениями ограничений
Возможные значения для тэга:
- без значения эквивалентно `add`
- `add` - дополнение кода из прошлых ячеек
- `new` - ввод кода заново, значения из прошлых ячеек игнорируются
### subject
Задаёт имя блока, описываемого этим файлом
В теле ячейки - одна строка с именем в формате `alpha_numeric`
> Если не задан, считается значение тэга соответствует имени документа без суффиксов
### arch
Задаёт имя архитектуры, описываемой этим файлом
В теле ячейки - одна строка с именем в формате `alpha_numeric`
> Если не задан, считается значение тэга соответствует значению `vdf`
## Тэги для компиляции, исполнения исходного кода и т.п.
Выполнение ячеек с тэгами такого типа по умолчанию приводит к созданию и компиляции исходных файлов, запуску симуляции
### display
Вывести результат выражения
В теле ячейки указывается само выражение.
> Код с выражением будет помещён в тело архитектуры в специальной обёртке для выполнения и вывода значения без влияния на работу остальной части
> В коде в сообщении добавляется специальная пометка для поиска его в выводе и извлечения значения
Возможные значения:
- без значения (формат по умолчанию)
- %0h, %0b, %0d и т.п. для функции $display или её эквивалента
> Запуск ячейки по умолчанию так же выполняет симуляцию в течении определённого времени
### drive
Формат: `drive-<name>`
Добавляет воздействия в стимул с указанным именем
Возможные значения:
- без значения эквивалентно `add`
- `new` - задание стимула с нуля
- `add` - дополнение уже существующего стимула
Форматы текста в ячейке:
- neutral yaml (описать)
- wavedrom json/yaml
<!--
#TODO: ещё форматы
-->
> По умолчанию запуск ячейки с таким тэгом только выводит заданную диаграмму
### monitor
Формат: `monitor-<name>`
Добавляет сигналы для отображения в набор с указанным именем
Возможные значения:
- без значения эквивалентно `add`
- `new` - задание стимула с нуля
- `add` - дополнение уже существующего стимула
Формат текста в ячейке: в строку иерархический путь сигналов
Дополнительно в строке м.б. указан после символа `:` тип и формат данных
(clk/bit/data и т.п. что есть в wavedrom и ещё где)
> Запуск ячейки по умолчанию так же выполняет симуляцию в течении определённого времени
### golden
Формат: `golden-<name>`
Добавляет сигналы и их диаграмму для сравнения
Возможные значения:
- без значения эквивалентно `add`
- `new` - задание стимула с нуля
- `add` - дополнение уже существующего стимула
Формат текста в ячейке: _TODO:_
<!--
#TODO: определить формат для golden
-->
> По умолчанию запуск ячейки с таким тэгом только выводит заданную диаграмму
### generics
Задаёт параметры для блока верхнего уровня
Возможные значения:
- без значения эквивалентно `add`
- `new` - задание стимула с нуля
- `add` - дополнение уже существующего стимула
Формат текста в ячейке: словарь YAML
### pragma
Установка параметров препроцессора
Возможные значения:
- без значения эквивалентно `add`
- `add` - дополнение уже ранее заданных параметров
- `new` - ввод параметров заново
Текст ячейки в формате списка yaml
<!--
#TODO: список или всё же словарь?
-->
### order
Значение ячейки содержит порядок компиляции в случае если для выполнения ячеек требуется задействовать другие файлы (в т.ч. файлы порождённые с помощью самих ячеек)
Возможные значения:
- без значения эквивалентно `add`
- `add` - дополнение уже существующего порядка
- `new` - новый порядок компиляции, старый игнорируется
Текст ячейки - строки содержащую пару - имя библиотеки (alpha_numeric) и путь к файлу, разделённые пробелами
### env
Установка переменных окружения
Возможные значения:
- без значения эквивалентно `add`
- `add` - дополнение уже ранее заданных переменных
- `new` - ввод переменных заново
Текст ячейки в формате словаря yaml
### ctag
Определение действий для кастомного тэга
### pre
Инструкции (shell) для препроцессинга перед этапами сборки/выполнения
Формат: `pre-(build|run)`
Возможные доп. значения:
- без значения эквивалентно `add`
- `new` - задание инструкций с нуля
- `add` - дополнение уже существующих инструкций
В тексте ячейки - команды shell в строку
В качестве аргументов команды могут быть использованы результаты выполнения ячеек через переменную окружения с именем `CELL_<имя ячейки>`
Если значение ячейки разделено `---`, то часть до `---` м.б. использована как аргумент через переменную окружения `CELL`
### post
Инструкции (shell) для препроцессинга после этапов сборки/выполнения
Формат: `post-(build|run)`
Возможные значения:
- без значения эквивалентно `add`
- `new` - задание стимула с нуля
- `add` - дополнение уже существующего стимула
В тексте ячейки - команды shell в строку
В качестве аргументов команды могут быть использованы результаты выполнения ячеек через переменную окружения с именем `CELL_<имя ячейки>`
Если значение ячейки разделено `---`, то часть до `---` м.б. использована как аргумент через переменную окружения `CELL`
## Тэги для работы со структурой документа и управления выводом
### define
Ячейка с определением значений по-умолчанию тэгов для последующих ячеек
Формат - построчный список тэгов
Возможные значения для тэга:
- без значения эквивалентно `add`
- `add` - дополнение/изменение уже ранее заданных значений
- `new` - ввод значений заново
### replace
требует использование тэга `name`
варианты значений:
- без значения эквивалентно `cell`
- `cell` - замена всего тела ячейки
- `tags` - замена только тэгов
- `full` - полная замена ячейки
- `p1` - замена 1й части ячейки (части до строки-разделителя, если ячейка м.б. разделена)
- `p2` - замена 2й части ячейки (части после строки-разделителя, если ячейка м.б. разделена)
Замена содержимого указанной ячейки
Если указываются доп. тэги и выбран вариант с заменой тэгов - они дополнят / заменят тэги ячейки
Если для тэга указано значение `NONE`, то тэг будет удалён
<!--
#TODO: как быть с условными тэгами в этом случае?
-->
### insert
вставка ячейки до/после указанной ячейки
формат: `insert-(after|before)-<cell-name>`
### cut
вырезать одну или серию ячеек
формат:
- `cut-<cell-name>`
- `cut-<start-cell-name>-<end-cell-name>`
### output
Тэг для спецификации самого подмножества вывода
Формат: `output-<subset-name>`
Возможные доп. значения для тэга:
- без значения эквивалентно `add`
- `add` - дополнение/изменение уже ранее заданных значений
- `new` - ввод значений заново
В тексте ячейки содержатся параметры для подмножества в формате словаря YAML
В частности м.б. определено имя ячейки, которая будет выполняться для формирования вывода этого подмножества
<!--
#TODO: какие параметры
-->
Примеры имён подмножеств:
- `doc` - формирование документации
- `src` - формирование исходника(ов)
### subset
Имя секции и ключ
Формат: `subset-<subset-name>-(on|off)`
Включение / отключение последующих ячеек для того или иного подмножества вывода
Значения subset-name - те которые были определены тэгами `output`
### disable
Отключение указанных в тексте ячеек из обработки
Действует только на исполнение последующих ячеек
Формат текста - список имён и/или диапазонов ячеек в строку и/или через запятую
Имеет смысл использовать вместе с тэгом расширения `cond` или `external`
### enable
Включение указанных в теле ячеек из обработки
Действует только на исполнение последующих ячеек
Формат текста - список имён и/или диапазонов ячеек в строку и/или через запятую
Имеет смысл использовать вместе с тэгом расширения `cond` или `external`
### container
Ячейка не используется для обработки но её содержимое может быть использовано другими ячейками по имени
### extend
Тэг для расширения уже существующего документа VDF
Формат: `extend[-<subset-name>][-<cell-name>]`
Применение этого тэга эквивалентно тому, как если бы вместо него были введены ячейки из заданного документа
Если указан параметр `subset-name` то будут использованы только ячейки для указанного подмножества
Если указан параметр `cell-name` то будет использован вывод указанного под множества для указанной ячейки
В теле ячейки указывается путь документу VDF
Если к ячейке добавлен тэг расширения `external`, то вывод будет использован в качестве текста документа VDF
### tags
В теле ячейки содержится список включения/исключения тэгов для последующих ячеек
Использовать чтобы ограничить используемое подмножество тэгов
Возможные значения:
- `off` - в ячейке список запрещённых тэгов которые надо запретить
- `on` - в ячейке содержится список тэгов которые надо разрешить (если они были запрещены)
- `lock` - список тэгов менять более не разрешается. если в ячейке есть список тэгов то разрешёнными будут только указанные в ячейке
<!--
#TODO: спец. значение чтобы выбрать все
-->
### scope
Ограничение зоны действия правил / переменных и т.п.
Формат: `scope-<scope-name>-(begin|end)`
## Вывод информации и пр.
### show
> Может использоваться как тэг расширения
Тэг для вывода состояний и т.п. на момент запуска ячейки
Влияет на вывод при запуске последующих ячеек
Формат текста - список из значений, приведённых ниже, в строку
- `def` - `sources`, `stdout`, `stderr`, `stim-.*`, `wave-.*`, `structure`
- `sources` - все сформированные исходные файлы после препроцессинга
- `sources-pre` - все сформированные исходные файлы до препроцессинга
- `diff` - последние изменения в исходных файлах
- `file-<path>` - вывести указанный файл
- `stim-<name>` - диаграмма стимула с указанным именем (возможен regex)
- `wave-<name>` - диаграмма набора сигналов с указанным именем (возможен regex)
- `output-<name>` - вывод результата указанной ячейки с тэгом `display`
- `stdout` - полный вывод stdout
- `stdout-build` - вывод stdout сборки
- `stdout-run` - вывод stdout запуска
- `stderr` - полный вывод stderr
- `stderr-build` - вывод stderr сборки
- `stderr-run` - вывод stderr запуска
- `symbol` - символ блока
- `structure` - структура/схема блока- `cells-branch-<name>` - ветвь ячеек до указанной ячейки
- `cells` - все возможные ячейки и их связи между собой
- `cells-branch` - текущая ветвь ячеек (до этой ячейки)
- `cells-branch-<name>` - ветвь ячеек до указанной ячейки
для `file`, `stdout`, `stderr` после доп. `-` можно указать диапазоны строк
для `structure` после доп `-` можно указать regex для исключения ячеек, после ещё одного `-` regex включения ячеек
для `stim`, `wave` после доп `-` можно указать диапазон отрезка времени
При использовании с тэгом расширения `target` вывод осуществляется в указанный файл
После доп. `-` можно указать формат интерпретации полученных данных:
- `md` - в виде markdown
- `html` - в виде html
- `yaml` - в виде мульти-документа yaml
- `tree` - в файлы внутри папки, путь папки указывается после доп. `-`
### show-custom
> Может использоваться как тэг расширения
Кастомный вывод
Влияет на вывод при запуске последующих ячеек
Возможные доп. значения:
- `shell` - вывести результат (stdout) команды
- `web` - получить данные из сервера
- `mixed` - аналогично include
После доп. `-` можно указать формат интерпретации полученных данных:
- `raw` - в виде сырого текста
- `md` - в формате markdown
- `html` - в виде html
- `yaml` - в виде мульти-документа yaml
В качестве аргументов команды могут быть использованы результаты выполнения ячеек через переменную окружения с именем `CELL_<имя ячейки>`
Если значение ячейки разделено `---`, то часть до `---` м.б. использована:
- как аргумент команды, доступный при вызове через переменную окружения `CELL`
# Тэги расширения
<!--
#TODO: ?test? для описания unit-тестов?
-->
### name
Имя ячейки
Возможные значения:
- значение в формате `alpha_numeric`
> М.б. использован для описательных ячеек
### lang
Определяет тип языка для тэгов описания исходного кода
Возможные значения:
- `vhdl`
- `verilog`
- `sv`
<!--
#TODO: scala/chisel etc.
-->
> Если в `fenced` секции указан формат подсветки, то он будет использован в качестве значения тэга `lang`
После значения может идти доп.значение, указывающее тип файла. К примеру `header` или `package`.
Тип файла так же м.б. определён с помощью тэга kind
### at
В какое время выполнить выражения или захватить диаграмму
Возможные значения:
- время (только для отображения выражения)
- диапазон времени
- `<имя сигнала>-<r/f/t/c>[-<номер события>]`
- `r` - rise (any-to-1)
- `f` - fall (any-to-0)
- `t` - toggle (any-to-1 / any-to-0)
- `c` - change (любое изменение значения)
- `e` - expression. Через доп `-` указывается выражение по наступлению равенства которого осуществляется вывод
> Можно указывать несколько тэгов `at`
### fetch
Подгрузка деклараций (только декларативные части) из следующих ячеек чтобы решить проблему курицы и яйца
Формат `fetch-<integer-number>` - на сколько ячеек вперёд подгружать
Формат `fetch-<cell-name>` - подгружать вплоть до ячейки с указанным именем (включительно)
### target
Имя целевого исходного файла
Возможные значения:
- без значения - вывод в `<subject>.(v|sv|vhd)` (`subject` определяется с помощью тэга, а расширение - использованным тэгом `lang`)
- путь файла, в формате `alpha_numeric` + `./`
<!--
#TODO: delete target file
-->
### subsection
Имя секции для группировки кода внутри одной секции
<!--
#TODO: вложенные секции такие как VHDL process, block, ?function? и т.п.
чтобы такие вещи как declaration/body работали внутри секции
-->
### branch
Имя "ветки" описаний. Ячейки из разных веток обрабатываются и выполняются изолировано друг от друга
Возможные значения:
- без значения - эквивалентно использованию значения `0`
- значение в формате `alpha_numeric`
> М.б. использован для описательных ячеек
### fork
Создать ветку от предыдущей ячейки (или ячейки с указанным именем)
Возможные значения:
- имя ветки в формате `alpha_numeric`
- опционально через доп.значение имя ячейки
> М.б. использован для описательных ячеек
### flow
Маршрут выполнения
Возможные значения:
- без значения - эквивалентно использованию значения `run`
- `no`
- `build`
- `elaborate`/`instantiate`
- `run`
<!--
#TODO: support following flows for simple projects?
- synth
- impl
-->
### parent
Какую ячейку использовать как родительскую при обработке
Возможные значения:
- имя другой ячейки
- __root__
<!--
#TODO: только для запуска тэгов не меняющих контекст
> для тэгов, меняющих контекст - использовать fork
-->
### format
Возможные значения:
- имя формата данных в ячейке (описание для тэга `drive` и т.п.)
### var
Установка значения переменной, которая будет использована для подстановки в текст ячейки / в тэгах с условиями / в значения тэгов
> М.б. использован для описательных ячеек
### subst
При применении этого тэга в тексте ячейки предварительно будут выполнены подстановки значений переменных, переменных окружения, frontmatter
> М.б. использован для описательных ячеек
> М.б. использован как самостоятельный тэг
### cond
Ячейка используется при соблюдении условия
Возможны значения:
- `env-<env-var-name>` - имя переменной окружения
- `var-<var-name>` - имя переменной документа
- `subset` - имя подмножества вывода
после имени можно указать символ операции сравнения и значение
> Можно указывать несколько тэгов `cond`. Ячейка будет использована при выполнении любого увлосия в любом из тэгов
> М.б. использован для описательных ячеек
<!--
TODO: символ для строгого условия (атрибут/переменная должны существовать)
-->
### ignore
Полностью игнорировать ячейку при обработке
после доп. `-` можно указать условие аналогично тэгу `cond`
> М.б. использован для описательных ячеек
### hide
Скрыть ячейку / часть ячейки из вывода в печать
При этом ячейка будет присутствовать в истории и на неё можно ссылаться
Формат `hide-[subset-]<value>`
`subset` - подмножество вывода, опционально
Возможны значения:
- без значения эквивалентно body
- `body` - только тело ячейки
- `output` - вывод ячейки
- `all` - ячейку целиком
после доп. `-` можно указать условие аналогично тэгу `cond`
### toggle
Персонально включить/исключить ячейку в определённом подмножестве вывода
Формат: `toggle-<subset>-(on|off)`
> М.б. использован для описательных ячеек
### section
отметка начала той или иной секции
Формат: `section-<section-name>-(begin|end)`
К ячейкам внутри секции применяются тэги их секции
> М.б. использован для описательных ячеек
### template
файл с правилами / шаблоном для генерации подмножества вывода
Формат: `template-<subset>-<template>`
### convert
Конверсия значения ячейки в указанный формат при обработке
Возможно конверсия только для совместимых форматов
Возможные значения:
- json для конверсии из формата yaml
### external
При использовании этого тэга в теле ячейки содержится команду или путь к внешнему ресурсу, который будет использован для формирования тела ячейки при обработке
Возможные значения:
- `file`
- `shell` (stdout)
- `get` (web)
- `cell`
- `cell_result`
- `mixed`
Тело ячейки формируется из указанного источника (нескольких источников при значении `mixed`)
в теле ячейки указывается источник в зависимости от значения
- имя файла из которого необходимо вставить код
- может быть указан файл в формате VDF и после доп. символа `:` указать имя ячейки / имя начальной и конечной ячейки через `-`
- команда (shell) результат которой (stdout) необходимо использовать
- имя ячейки этого документа (будет использовано её тело)
- имя ячейки с суффиксом `_result` (будет использован результат выполнения ячейки)
- ПЕРЕД именем/командой можно указать список / диапазоны строк которые требуется использовать
Для случая mixed по строчно указывается `<тип источника>:<источник>`
если это ячейка может использовать разделитель `---`, то используя разделитель указать разные источники для обеих частей указывается источник для каждой части
> М.б. использован для описательных ячеек
### vdf
Задать версию спецификации тэгов для этой / последующих ячеек
Возможные значения: версия в формате `alpha_numeric`+[.]
### strip
Удалить из вывода определённую информацию
- `vdf` - удалить строку `%%vdf ...` (например если это кодовая ячейка должна ещё отобразиться и в документации)
# Особенности для markdown/asciidoc и пр. форматов структурированного описания
- Frontmatter часть документа исключается из ячеек, но м.б. использована для инициализации исходных значений переменных / тэгов
- Исполняемой ячейкой трактуется та, которая полностью содержит fenced блок
- Fenced блок с указанием формата языка определяет язык
- Fenced блок с форматом python будет выполняться (если нет тэга ignore)
- Ячейка с fenced блоком неизвестного формата трактуется как описательная
- Известные форматы:
- vhdl
- verilog
- system verilog
- python
- параметры можно определить через frontmatter часть
- в Jupyter Notebook и пр. форматах, не поддерживающих концепцию frontmatter, следует данные frontmatter описать в первой ячейке (типа `code` для Jupyter Notebook) с тэгами `#var-frontmatter #format-yaml`
## пример frontmatter части
```yaml
title : Versatile Description Format specification
author : Nikolay Gniteev (godhart@gmail.com)
version : 1.0.draft.0
vdf : "1.0" # Используемая спецификация формата
# Установка атрибутов, определяемых тэгами, в frontmatter части через словарь
attrs :
# Установка значений тэга output
tag1_name : value
tag2_name :
subtag :
etc : value
# Установка атрибутов, определяемых тэгами, в frontmatter части через список (эквивалентно записи attr выше), но в этой форме будут учтены все особенности ввода тэгов
define :
- tag1_name-value
- tag2_name-subtag-etc-value
# Установка значений переменных в frontmatter части
vars :
# Установка скалярной переменной
var1_name : value
# Установка списка
var2_name :
- value1
- value2
# Установка словаря
var3_name :
keyA : valueA
keyB : valueB
# Установка сложно-составного значения
var4_name :
keyCA : valueCA
keyCB :
- valueCB1
- valueCB2
keyCC :
subCC1: valueCC1
subCC2: valueCC2
```
# Сценарии использования
При использовании формата Jupyter Notebook:
- постановка быстрых экспериментов при обучении или при проверках
- сопровождение вопросов - ответов в сообществе
- интерактивный обучающий материал
- упрощение поиска места ошибки
- инкрементальная компиляция
- инкрементальное сопровождение кода unit тестами
В общем случае:
- документация, исходный код и тестовый код в непосредственной близости, принцип единого источника истины
- понижение фрагментации кода (описание декларативной части и тела с соответствующим кодом расположены в непосредственное близости)
- сегментация крупных файлов в несколько
- код с rich-text комментариями
- условная компиляция и препроцессор в тех языках где они отсутствуют
- повторное использование небольших фрагментов кода (интерфейсы, регистры управления и пр.)
- кодогенерация в рамках одного файла
- кодогенерация множества файлов по шаблону
- использование с LLM (инкрементальный и слабофрагментированный код с развернутыми пояснениями может служить хорошей базой для обучения и лучше подходить для генерации / контроля контента)
# Подмножества тэгов
Хотя все приведённые в спецификации тэги могут быть использованы в любом сценарии использования, всё же рекомендуется ограничиваться в зависимости от сценария
## Документация и исходный код
В этом сценарии следует избегать нелинейности, за исключением, возможно, unit тестов при их включении в документ
## Быстрый эксперимент, сопровождение вопросов - ответов
В этом сценарии следует максимально упрощать и не создавать лишних сущностей, файлов и т.п.
# Принципы обработки файла
<!--
#TODO: coming soon
--> |
from typing import Dict, Optional
class BoundingBox():
# constructors
def __init__(self, left: float, bottom: float, right: float, top: float) -> None:
self.bounds = [left, bottom, right, top]
@classmethod
def from_textract_bbox(cls, textract_bbox: Dict[str, float]) -> None:
return cls(
left=textract_bbox['Left'],
bottom=textract_bbox['Top']+textract_bbox['Height'],
right=textract_bbox['Left']+textract_bbox['Width'],
top=textract_bbox['Top'],
)
# class methods
def scale(self, x_scale: None, y_scale: Optional[float]=None) -> None:
if not y_scale:
y_scale = x_scale
self.bounds[0] *= x_scale
self.bounds[1] *= y_scale
self.bounds[2] *= x_scale
self.bounds[3] *= y_scale
# overload methods
def __getitem__(self, key):
return self.bounds[key]
def __setitem__(self, key, value):
self.bounds[key] = value
# getters
@property
def left(self) -> float:
return self.bounds[0]
@property
def bottom(self) -> float:
return self.bounds[1]
@property
def right(self) -> float:
return self.bounds[2]
@property
def top(self) -> float:
return self.bounds[3]
@property
def width(self) -> float:
return abs(self.bounds[0]-self.bounds[2])
@property
def height(self) -> float:
return abs(self.bounds[3]-self.bounds[1]) |
package com.learnvertx.starter.web;
import com.learnvertx.starter.entity.Project;
import com.learnvertx.starter.entity.Task;
import com.learnvertx.starter.repository.ProjectRepository;
import com.learnvertx.starter.repository.ProjectRepositoryImpl;
import com.learnvertx.starter.service.ProjectService;
import com.learnvertx.starter.service.ProjectServiceImpl;
import com.learnvertx.starter.web.HelloVerticle;
import io.vertx.config.ConfigRetriever;
import io.vertx.config.ConfigRetrieverOptions;
import io.vertx.config.ConfigStoreOptions;
import io.vertx.core.*;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.StaticHandler;
import org.hibernate.cfg.Configuration;
import org.hibernate.reactive.provider.ReactiveServiceRegistryBuilder;
import org.hibernate.reactive.stage.Stage;
import org.hibernate.service.ServiceRegistry;
import java.util.Properties;
public class MainVerticle extends AbstractVerticle {
@Override
public void start(Promise<Void> startPromise) throws Exception {
// DeploymentOptions options = new DeploymentOptions()
// .setWorker(true)
// .setInstances(8);
// -----------------------------------------------------------------------------------------------------------------
// 1. Create properties with config data
Properties hibernateProps = new Properties();
hibernateProps.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/revise?serverTimezone=UTC");
hibernateProps.put("hibernate.connection.username", "root");
hibernateProps.put("hibernate.connection.password", "krishna24");
hibernateProps.put("jakarta.persistence.schema-generation.database.action", "update");
hibernateProps.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
hibernateProps.put("hibernate.show_sql", true);
hibernateProps.put("hibernate.format_sql", true);
// hibernateProps.put("hibernate.generate_statistics", true);
// 2. Create Hibernate configurations
Configuration hibernateConfig = new Configuration();
hibernateConfig.setProperties(hibernateProps);
hibernateConfig.addAnnotatedClass(Task.class);
hibernateConfig.addAnnotatedClass(Project.class);
//3. Create ServiceRegistry
ServiceRegistry serviceRegistry = new ReactiveServiceRegistryBuilder()
.applySettings(hibernateConfig.getProperties())
.build();
//4. Create SessionFactory
Stage.SessionFactory sessionFactory = hibernateConfig
.buildSessionFactory(serviceRegistry)
.unwrap(Stage.SessionFactory.class);
ProjectRepository projectRepository = null;
// this.taskRepository = new TaskRepositoryImpl(sessionFactory);
projectRepository = new ProjectRepositoryImpl(sessionFactory);
ProjectService projectService = new ProjectServiceImpl(projectRepository);
// -----------------------------------------------------------------------------------------------------------------
// vertx.deployVerticle("com.learnvertx.starter.web.HelloVerticle", options);
vertx.deployVerticle(new HelloVerticle());
vertx.deployVerticle(new ProjectVerticle(projectService));
Router router = Router.router(vertx);
router.route().handler(ctx -> {
String authToken = ctx.request().getHeader("AUTH_TOKEN");
if (authToken != null && "myAuthToken".contentEquals(authToken)) {
ctx.next();
} else {
ctx.response().setStatusCode(401).setStatusMessage("UNAUTHORIZED").end();
}
});
// Router 1
router.get("/api/v1/hello").handler(this::helloVertx);
// Router 2
router.get("/api/v1/hello/:name").handler(this::helloName);
// static route
router.route().handler(StaticHandler.create("web"));
// setting type, format and path of configuration file.
ConfigStoreOptions defaultConfig = new ConfigStoreOptions()
.setType("file")
.setFormat("json")
.setConfig(new JsonObject().put("path", "config.json"));
ConfigRetrieverOptions opts = new ConfigRetrieverOptions()
.addStore(defaultConfig);
ConfigRetriever configRetriever = ConfigRetriever.create(vertx, opts);
Handler<AsyncResult<JsonObject>> handler = asyncResult -> this.handleConfigResults(startPromise, router, asyncResult);
configRetriever.getConfig(handler);
}
void handleConfigResults(Promise<Void> startPromise, Router router, AsyncResult<JsonObject> asyncResult) {
if (asyncResult.succeeded()) {
JsonObject config = asyncResult.result();
JsonObject httpKey = config.getJsonObject("http");
int httpPort = httpKey.getInteger("port");
// created server here and set port number.
vertx.createHttpServer().requestHandler(router).listen(httpPort, http -> {
if (http.succeeded()) {
startPromise.complete();
System.out.println("HTTP server started on port " + httpPort);
}
});
} else {
// Other stuff here
startPromise.fail("Unable to load configurations.");
}
}
void helloVertx(RoutingContext ctx) {
vertx.eventBus().request("hello.vertx.addr", "", reply -> {
ctx.request().response().end((String) reply.result().body());
});
}
void helloName(RoutingContext ctx) {
String name = ctx.pathParam("name");
vertx.eventBus().request("hello.named.addr", name, reply -> {
ctx.request().response().end((String) reply.result().body());
});
}
} |
<?php
/**
* @file
* Reset user passwords and optionally notify users.
*/
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Establish batch operation for resetting passwords.
*
* @param array $data
* The array of data needed for this batch.
*/
function mass_pwreset_multiple_reset(array $data) {
$batch = [
'operations' => [
['mass_pwreset_batch_process', [$data]],
],
'finished' => 'mass_pwreset_batch_finished',
'title' => t('Multiple password reset'),
'init_message' => t('Multiple password reset in progress.'),
'progress_message' => t('Password reset batch in progress.'),
'error_message' => t('There was an error in the password reset batch.'),
'file' => drupal_get_path('module', 'mass_pwreset') . '/mass_pwreset.batch.inc',
];
// Set batch via form submit handler.
batch_set($batch);
}
/**
* Return uids from a list of roles.
*
* Excludes current uid and uid 1.
*
* @param array $roles
* An array of select roles.
*/
function mass_pwreset_get_uids_by_selected_roles($roles = array()) {
// Do not include current logged in user.
$current_uid = \Drupal::currentUser()->id();
$db = \Drupal::database();
$query = $db->select('users', 'u');
$query->innerJoin('user__roles', 'ur', 'u.uid = ur.entity_id');
$query->fields('u', ['uid']);
$query->condition('ur.roles_target_id', $roles, 'IN');
$query->condition('u.uid', [1, $current_uid], 'NOT IN');
$query->orderBy('u.uid');
$query->distinct();
return $query->execute()->fetchCol();
}
/**
* Return uids for all user accounts.
*
* Excludes uid 0, 1, and current uid.
*/
function mass_pwreset_get_uids() {
// Do not include current logged in user.
$current_uid = \Drupal::currentUser()->id();
$db = \Drupal::database();
$query = $db->select('users', 'u');
$query->fields('u', ['uid']);
$query->condition('u.uid', [0, 1, $current_uid], 'NOT IN');
$query->orderBy('u.uid');
$query->distinct();
return $query->execute()->fetchCol();
}
/**
* Remove anonymous and authenticated and return a list of roles.
*/
function mass_pwreset_get_custom_roles() {
$roles = user_role_names(TRUE);
unset($roles['authenticated']);
return $roles;
}
/**
* Implements hook_help().
*/
function mass_pwreset_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.mass_pwreset':
$render['about'] = [
'#markup' => t('About'),
'#prefix' => '<h3>',
'#suffix' => '</h3>',
];
$render['about_content'] = [
'#markup' => t('This module will reset passwords for specific roles selected. The administrator account (uid 1) can optionally be reset as well.'),
'#prefix' => '<p>',
'#suffix' => '</p>',
'more' => [
'#markup' => t("There is an option to notify the affected users by using Drupal's password recovery email process."),
'#prefix' => '<p>',
'#suffix' => '</p>',
],
];
$render['usage'] = [
'#markup' => t('Usage'),
'#prefix' => '<h3>',
'#suffix' => '</h3>',
];
$render['usage_content'] = [
'#markup' => t('The password reset form is in a tab in the <b>admin people</b> section. Located at <a href="@link">/admin/people/mass-pwreset</a>', ['@link' => '/admin/people/mass-pwreset']),
'#prefix' => '<p>',
'#suffix' => '</p>',
'list' => [
'#theme' => 'item_list',
'#title' => t('Password Reset Options'),
'#items' => [
'Select either all users (authenicated role) or select specific roles for the users you want to reset',
'Select to notify active and blocked user accounts using the Drupal password recovery email system',
'To reset the administrator account (uid 1) you must also select include admin user',
'Start the process by clicking the "Reset Passwords" button',
],
],
];
$render['logging'] = [
'#markup' => t('Logging'),
'#prefix' => '<h3>',
'#suffix' => '</h3>',
];
$render['logging_content'] = [
'#markup' => t('The user accounts will be updated in a batch session. The uid will be logged for each user and the finished batch will be logged as well.'),
'#prefix' => '<p>',
'#suffix' => '</p>',
];
return $render;
}
}
/**
* Generate user passwords.
*
* Modified version of Drupal's user_password() to include special characters.
*
* @param int $password_length
* Length of password.
*
* @return string
* Generated password
*/
function _mass_pwreset_generate_password($password_length = 20) {
// Regex to enforce the password requirements.
// First and last characters cannot be digits (0-9).
// Must contain two digit characters (0-9).
// Must contain one lower case character (a-z).
// Must contain one upper case character (A-Z).
// Must contain three special characters
// ( ()`~!@#$%^&*-+=|\{}[]:;"'<>,.?/ ).
// Minimum length is 12 characters.
// Maximum length is 128 characters.
$password_requirements = '_^(?=.*\d.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[()`~!@#$%^\&*\-+=\|\\{}[\]:;"\'<>,.?/].*[()`~!@#$%^\&*\-+=\|\\{}[\]:;"\'<>,.?/].*[()`~!@#$%^\&*\-+=\|\\{}[\]:;"\'<>,.?/])[\D]{1}[\s0-9a-zA-Z()`~!@#$%^\&*\-+=\|\\{}[\]:;"\'<>,.?/]{10,126}[\D]{1}$_';
// List of allowable characters for the password.
$allowable_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789()`~!@#$%^&*-+=|\{}[]:;"\'<>,.?/';
// Zero-based count of characters in the allowable list.
$characters_length = Unicode::strlen($allowable_characters) - 1;
$characters_length = mb_strlen($allowable_characters) - 1;
$new_password = '';
// Generate passwords until password requirements are met.
while (preg_match($password_requirements, $new_password) == 0) {
// Loop the number of times specified by $length.
for ($i = 0; $i < $characters_length; $i++) {
do {
// Find a secure random number within the range needed.
$index = ord(drupal_random_bytes(1));
} while ($index > $len);
// Each iteration, pick a random character from the
// allowable string and append it to the password:
$new_password .= $allowable_characters[$index];
}
}
return $new_password;
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>GraphicsNotes 2013 -- Section 8: Linear Algebra, Transformations, and Viewing</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div class="section">
<h2>Section 8: Linear Algebra, Transformations, and Viewing</h2>
<p>Computer graphics is a very mathematical subject. Most of the mathematics is
hidden in the implementation, but if you want to really understand what is going on,
you need to know some of the math. In this section, we look at
the mathematical background without going too deeply into it. Then, we return
the the topic of transformations to consider them in more deatil</p>
<div class="subsection">
<h3>Some Linear Algebra Background</h3>
<p>The mathematics of
computer graphics is primarily <span class="newword">linear algebra</span>, which is the
study of vectors and matrices, where the matrices are important because they represent
transformations. A <span class="newword">vector</span>
is a quantity that has a length and a direction. A vector can be visualized
as an arrow, as long as you remember that it is the length and direction of the
arrow that are relevant, and that its specific location is irrelevant.
We have already briefly encountered normal vectors, which are used to specify
the direction in which a surface is facing.
</p>
<p>If we visualize a vector <i>V</i> as starting at the origin and ending
at a point <i>P</i>, then we can to a certain extent identify <i>V</i>
with <i>P</i>—at least to the extent that both <i>V</i> and
<i>P</i> have coordinates, and their coordinates are the same. For
example, the 3D point (<i>x,y,z</i>) = (3,4,5) has the
same coordinates as the vector (<i>dx,dy,dz</i>) = (3,4,5).
For the point, the coordinates (3,4,5) specify a position in space
in the <i>xyz</i> coordinate system. For the vector, the coordinates (3,4,5)
specify the change in the <i>x</i>, <i>y</i>, and <i>z</i> coordinates along
the vector. If we represent the vector with an arrow that starts
at the origin (0,0,0), then the head of the arrow will be at (3,4,5).
But we could just as well visualize the vector as an arrow that starts at
the point (1,1,1), and in that case the head of the arrow would be at
the point (4,5,6).</p>
<p>The distinction between a point and a vector is subtle. For some
purposes, the distinction can be ignored; for other purposes, it is important.
Often, all that we have is a sequence of numbers, which we can treat
as the coordinates of either a vector or a point at will.
</p>
<p><span class="newword">Matrices</span> are rectangular arrays of numbers. A matrix can be used
to apply a transformation to a vector (or to a point). The geometric
transformations that are so important in computer graphics are
represented as matrices.
</p>
<p>In this section, we will look at vectors and matrices and at some
of the ways that they can be used. The treatment is not very mathematical.
The goal is to familiarize you with the properties of vectors and matrices
that are most relevant to OpenGL.
</p>
<hr class="break">
<p>We assume for now that we are talking about vectors in three dimensions.
A 3D vector can be specified by a triple of numbers, such as (0,1,0) or
(3.7,−12.88,0.02). Most of the discussion, except for the
"cross product," carries over easily into other dimensions.
</p>
<p>One of the basic properties of a vector is its <span class="newword">length</span>.
In terms of its coordinates, the length of a vector (<i>x,y,z</i>)
is given by <i>sqrt</i>(<i>x</i><sup>2</sup>+<i>y</i><sup>2</sup>+<i>z</i><sup>2</sup>).
(This is just the Pythagorean theorem in three dimensions.) If <i>v</i> is
a vector, its length is denoted by <span class="code">|</span><i>v</i><span class="code">|</span>.
The length of a vector is also called its <span class="newword">norm</span>.
</p>
<p>Vectors of length 1 are particularly important. They are called
<span class="newword">unit vectors</span>. If <i>v</i> = (<i>x,y,z</i>)
is any vector other than (0,0,0), then there is exactly one unit vector
that points in the same direction as <i>v</i>. That vector is given by
</p>
<pre>( x/length, y/length, z/length )</pre>
<p class="np">where <i>length</i> is the length of <i>v</i>. Dividing a vector by its
length is said to <span class="newword">normalize</span> the vector: The result
is a unit vector that points in the same direction as the original
vector. (There is some unfortunate terminology here: The terms "norm" and "normalize"
have little to do with the idea of a normal vector to a surface, except that normal
vectors are usually taken to be unit vectors.)
</p>
<p>Given two vectors <i>v1</i> = (<i>x1,y1,z1</i>) and
<i>v2</i> = (<i>x2,y2,z2</i>), the <span class="newword">dot product</span>
of <i>v1</i> and <i>v2</i> is denoted by <i>v1</i>·<i>v2</i> and is defined
by</p>
<pre>v1·v2 = x1*x2 + y1*y2 + z1*z2</pre>
<p class="np">Note that the dot product is a number, not a vector.
The dot product has several very important geometric meanings. First of
all, note that the length of a vector <i>v</i> is just the square root of
<i>v</i>·<i>v</i>. Furthermore, the dot product of two non-zero
vectors <i>v1</i> and <i>v2</i> has the property that
</p>
<pre>cos(angle) = v1·v2 / (|v1|*|v2|)</pre>
<p class="np">where <i>angle</i> is the measure of the angle from <i>v1</i> to <i>v2</i>. In
particular, in the case of two unit vectors, whose lengths are 1, <b>the dot product of
two unit vectors is simply the cosine of the angle between them.</b> Furthermore,
since the cosine of a 90-degree angle is zero, two non-zero vectors are perpendicular
if and only if their dot product is zero. Because of these properties,
the dot product is particularly important in lighting calculations, where the
effect of light shining on a surface depends on the angle that the light makes
with the surface.
</p>
<p>The dot product is defined in any dimension. For vectors in 3D, there is
another type of product called the <span class="newword">cross product</span>, which also
has an important geometric meaning. For vectors <i>v1</i> = (<i>x1,y1,z1</i>) and
<i>v2</i> = (<i>x2,y2,z2</i>), the cross product of <i>v1</i>
and <i>v2</i> is denoted <i>v1</i>×<i>v2</i> and is the vector defined by
</p>
<pre>v1×v2 = ( y1*z2 - z1*y2, z1*x2 - x1*z2, x1*y2 - y1*x2 )</pre>
<p class="np">If <i>v1</i> and <i>v2</i> are non-zero vectors, then <i>v1</i>×<i>v2</i>
is zero if and only if <i>v1</i> and <i>v2</i> point in the same direction or in
exactly opposite directions. Assuming <i>v1</i>×<i>v2</i> is non-zero, then
it is perpendicular both to <i>v1</i> and to <i>v2</i>; furthermore,
the vectors <i>v1</i>, <i>v2</i>, <i>v1</i>×<i>v2</i> follow the
right-hand rule; that is, if you curl the fingers of your right hand from
<i>v1</i> to <i>v2</i>, then your thumb points in the direction of <i>v1</i>×<i>v2</i>. If
<i>v1</i> and <i>v2</i> are unit vectors, then the cross product
<i>v1</i>×<i>v2</i> is also a unit vector, which is perpendicular both
to <i>v1</i> and to <i>v2</i>.
</p>
<p>Finally, I will note that given two points <i>P1</i> = (<i>x1,y1,z1</i>) and
<i>P2</i> = (<i>x2,y2,z2</i>), the <span class="newword">difference</span> <i>P2−P1</i>
which is defined by
</p>
<pre>P2 − P1 = ( x2 − x1, y2 − y1, z2 − z1 )</pre>
<p class="np">is a vector that can be visualized as an arrow that starts at <i>P1</i>
and ends at <i>P2</i>. Now, suppose that <i>P1</i>, <i>P2</i>, and <i>P3</i>
are vertices of a polygon. Then the vectors <i>P1−P2</i> and
<i>P3−P2</i> lie in the plane of the polygon, and so the cross product
</p>
<pre>(P3−P2) × (P1−P2)</pre>
<p class="np"></p>is a vector that is perpendicular to the polygon.
That is, it is a normal vector to the polygon.
This fact allows us to use the vertices of a polygon to produce a normal
vector to the polygon. Once we have that, we can normalize the vector
to produce a unit normal. (It's possible for the cross product to be
zero. This will happen if <i>P1</i>, <i>P2</i>, and <i>P3</i> lie
on a line. In that case, another set of three vertices might work.
Note that if all the vertices of a polygon lie on a line, then the polygon
degenerates to a line segment and has no interior points at all. We don't
need normal vectors for such polygons.)
</p>
<hr class="break">
<p>A <span class="newword">matrix</span> is just a two-dimensional array of numbers. Suppose that
a matrix <i>M</i> has <i>r</i> rows and <i>c</i> columns. Let
<i>v</i> be a <i>c</i>-dimensional vector, that is, a vector of
<i>c</i> numbers. Then it is possible to multiply <i>M</i> by
<i>v</i> to yield another vector, which will have dimension <i>r</i>.
For a programmer, it's probably easiest to define this type of
multiplication with code. Suppose that we represent <i>M</i>
and <i>v</i> by the Java arrays
</p>
<pre>double[][] M = new double[r][c];
double[] v = new double[c];</pre>
<p class="np">Then we can define the product <i>w</i> = <i>M</i><tt>*</tt><i>v</i> as follows:</p>
<pre>double w = new double[r];
for (int i = 0; i < r; i++) {
w[i] = 0;
for (int j = 0; j < c; j++) {
w[i] = w[i] + (M[i][j] * v[j]);
}
}</pre>
<p class="np">If you think of a row, <i>M</i>[<i>i</i>], of <i>M</i> as being a <i>c</i>-dimensional vector,
then <i>w</i>[<i>i</i>] is simply the dot product <i>M</i>[<i>i</i>]·<i>v</i>.
</p>
<p>Using this definition of the multiplication of a vector by a matrix, a matrix defines a
<span class="newword">transformation</span> that can be applied to one vector to yield another vector.
Transformations that are defined in this way are called <span class="newword">linear transformations</span>,
and they are the main object of study in the field of mathematics known as linear algebra.
</p>
<p>Rotation, scaling, and shear are linear transformations, but translation is not.
To include translations, we have to widen our view to expand the idea of transformation to include
<span class="newword">affine transformations</span>.
An affine transformation can be defined, roughly, as a linear transformation followed by a
translation. For computer graphics, we are interested in affine transformations in
three dimensions. However—by what seems at first to be a very odd trick—we
can narrow our view back to the linear by moving into the fourth dimension.
</p>
<p>Note first of all that an affine transformation in three dimensions transforms a vector
(<i>x1,y1,z1</i>) into a vector (<i>x2,y2,z2</i>) given by
formulas</p>
<pre>x2 = a1*x1 + a2*y1 + a3*z1 + t1
y2 = b1*x1 + b2*y1 + b3*z1 + t2
z2 = c1*x1 + c2*y1 + c3*z1 + t3</pre>
<p class="np">These formulas express a linear transformation given by multiplication by the 3-by-3 matrix
</p>
<pre>a1 a2 a3
b1 b2 b3
c1 c2 c3</pre>
<p class="np">followed by translation by <i>t1</i> in the <i>x</i> direction, <i>t2</i> in the <i>y</i>
direction and <i>t3</i> in the <i>z</i> direction. The trick is to replace each three-dimensional
vector (<i>x,y,z</i>) with the four-dimensional vector
(<i>x,y,z,</i>1), adding a "1" as the fourth coordinate. And instead of
the 3-by-3 matrix, we use the 4-by-4 matrix
</p>
<pre>a1 a2 a3 t1
b1 b2 b3 t2
c1 c2 c3 t3
0 0 0 1</pre>
<p class="np">If the vector (<i>x1,y1,z1</i>,1) is multiplied by this 4-by-4 matrix,
the result is precisely the vector (<i>x2,y2,z2,</i>1). That is,
instead of applying an <i>affine</i> transformation to the 3D vector (<i>x1,y1,z1</i>),
we can apply a <i>linear</i> transformation to the 4D vector (<i>x1,y1,z1</i>,1).</p>
<p>This might seem pointless to you, but nevertheless, that is what OpenGL does: It
represents affine transformations as 4-by-4 matrices, in which the bottom row is
(0,0,0,1), and it converts three-dimensional vectors into four dimensional vectors
by adding a 1 as the final coordinate. The result is that all the affine transformations
that are so important in computer graphics can be implemented as matrix multiplication.</p>
<p>One advantage of using matrices to represent transforms is that matrices can be multiplied.
In particular, if <i>A</i> and <i>B</i> are 4-by-4 matrices, then their matrix product
<i>A</i><tt>*</tt><i>B</i> is another 4-by-4 matrix. Each of the matrices <i>A</i>,
<i>B</i>, and <i>A</i><tt>*</tt><i>B</i> represents a linear transformation. The important
fact is that applying the single transformation <i>A</i><tt>*</tt><i>B</i> to a vector
<i>v</i> has the same effect as first applying <i>B</i> to <i>v</i> and then applying <i>A</i>
to the result. Mathematically, this can be said very simply: (<i>A</i><tt>*</tt><i>B</i>)<tt>*</tt><i>v</i>
= <i>A</i><tt>*</tt>(<i>B</i><tt>*</tt><i>v</i>). For computer graphics, it means that
the operation of following one transform by another can be represented simply by multiplying their matrices.
This allows OpenGL to keep track of a single matrix, rather than a sequence of individual
transforms. Transform commands such as <i>glRotatef</i> and <i>glTranslated</i> are implemented
as matrix multiplication: The current matrix is multiplied by a matrix representing
the transform that is being applied, yielding a matrix that represents the combined transform.
You might compose your transform as a long sequence of rotations scalings, and translations,
but when the transform is actually applied to a vertex, only a single matrix multiplication is
necessary. The matrix that is used represents the entire sequence of transforms, all multiplied
together. It's really a very neat system.
</p>
</div>
<div class="subsection">
<h3>Coordinate Systems</h3>
<p>The transformations that are used in computer graphics can be thought of as
transforming <span class="newword">coordinate systems.</span> A coordinate system
is a way of assigning coordinates to points. How this is done is to some extent arbitrary,
and transformations transform from one arbitrary assignment of coordinates to another.
OpenGL uses a variety of coordinate systems and transformations between them.</p>
<p>The coordinates that you actually use for drawing an object are called
<span class="newword">object coordinates</span>. The object coordinate system is chosen to be
convenient for the object that is being drawn. A <span class="newword">modeling transformation</span>
can then be applied to set the size, orientation, and position of the object
in the overall scene (or, in the case of hierarchical modeling, in the
object coordinate system of a larger, more complex object). The modeling transformation
is the first that is applied to the vertices of an object. </p>
<p>The coordinates in which you build the complete scene are called
<span class="newword">world coordinates</span>. These are the coordinates for
the overall scene, the imaginary 3D world that you are creating.
The modeling transformation
maps from object coordinates to world coordinates.
</p>
<p>In the real world, what you see depends on where you are standing
and the direction in which you are looking. That is, you can't make a picture
of the scene until you know the position of the "viewer" and where the
viewer is looking and, if you think about it, how the viewer's head
is tilted. For the purposes of OpenGL, we imagine that the
viewer is attached to their own individual coordinate system, which is known
as <span class="newword">eye coordinates</span>.
In this coordinate system, the viewer is at the origin, (0,0,0), looking
in the direction of the negative z-axis, and the positive direction of
the y-axis is pointing straight up. This is a viewer-centric coordinate
system, and it's important because it determines what exactly is seen
in the image. In other words, eye coordinates are (almost) the coordinates
that you actually want to <b>use</b> for drawing on the screen.
The transform from world coordinates to eye coordinates is called the
<span class="newword">viewing transform</span>.
</p>
<p>If this is confusing, think of it this way: We are free to use any
coordinate system that we want on the world. Eye coordinates are the
<b>natural</b> coordinate system for making a picture of the world as seen by
a viewer. If
we used a different coordinate system (world coordinates) when building the world,
then we have to transform those coordinates to eye coordinates to find
out what the viewer actually sees. That transformation is the viewing transform.
</p>
<p>Note, by the way, that OpenGL doesn't keep track of separate modeling
and viewing transforms. They are combined into a single
<span class="newword">modelview transform</span>. In fact, OpenGL doesn't even use world
coordinates internally; it goes directly from object coordinates to
eye coordinates by applying the modelview transformation.
</p>
<p>We are not done. The viewer can't see the entire 3D world,
only the part that fits into the <span class="newword">viewport</span>, the
rectangular region of the screen or other display device where the
image will be drawn. We say that the scene is
<span class="newword">clipped</span> by the edges of the viewport. Furthermore, in OpenGL,
the viewer can see only a limited range of <i>z</i>-values. Points with larger
or smaller <i>z</i>-values are clipped away and are not rendered into the image.
(This is not, of course, the way that viewing works in the real world, but it's
required by the use of the depth test in OpenGL.)
The volume of space that
is actually rendered into the image is called the <span class="newword">view volume</span>.
Things inside the view volume make it into the image; things that are not
in the view volume are clipped and cannot be seen. For purposes of drawing,
OpenGL applies a coordinate transform that maps the view volume
onto a <b>cube</b>. The cube is centered at the origin and extends from −1 to
1 in the x-direction, in the y-direction, and in the z-direction. The coordinate
system on this cube is referred to as <span class="newword">clip coordinates.</span>
The transformation from eye coordinates to clip coordinates is
called the <span class="newword">projection transformation</span>. At this point, we
haven't <i>quite</i> projected the 3D scene onto a 2D surface, but we can now do
so simply by discarding the z-coordinate.
</p>
<p>We <b>still</b> aren't done. In the end, when things are actually drawn, there are
<span class="newword">device coordinates</span>, the 2D coordinate system in which the
actual drawing takes place on a physical display device such as the computer screen.
Ordinarily, in device coordinates, the pixel is the unit of measure.
The drawing region is a rectangle of pixels. This is the rectangle that is called
the viewport. The <span class="newword">viewport transformation</span>
takes x and y from the clip coordinates and scales them to fit
the viewport.
</p>
<p>Let's go through the sequence of transformations one more time. Think of a primitive, such
as a line or triangle, that is part of the world and that might appear in the image
that we want to make of the world. The primitive goes through the following sequence of
operations:
</p>
<p align=center><img src="images/08/transforms.png" width="637" height="38"></p>
<ol>
<li>The points that define the primitive are specified in object coordinates, using methods
such as <i>glVertex3f</i>.</li>
<li>The points are first subjected to the modelview transformation, which is a combination of
the modeling transform that places the primitive into the world and the viewing transform
that maps the primitive into eye coordinates.</li>
<li>The projection transformation is then applied to map the view volume that is visible to
the viewer onto the clip coordinate cube. If the transformed primitive lies outside
that cube, it will not be part of the image, and the processing stops. If part of the
primitive lies inside and part outside, the part that lies outside is clipped away and discarded,
and only the part that remains is processed further.</li>
<li>Finally, the viewport transform is applied to produce the device coordinates that will
actually be used to draw the primitive on the display device. After that, it's just a matter
of deciding how to color the individual pixels that are part of the primitive on the device.</li>
</ol>
</div>
<div class="subsection">
<h3>The Modelview Transformation</h3>
<p>"Modeling" and "viewing" might seem like very different things, conceptually, but OpenGL
combines them into a single transformation. This is because there is no way to distinguish
between them in principle; the difference is purely conceptual. That is,
a given transformation can be considered to be either a modeling transformation or a
viewing transformation, depending on how you think about it.</p>
<p>For example, suppose that there is a model of a house at the origin, facing towards the
direction of the positive <i>z</i>-axis. Suppose the viewer is on the positive <i>z</i>-axis,
looking back towards the origin. The viewer is looking directly at the front of the
house. Now, you might apply a modeling transformation to the house, to rotate it by
90 degrees about the <i>y</i>-axis. After this transformation, the house is facing in
the positive direction of the <i>x</i>-axis, and the viewer is looking directly
at the <b>left</b> side of the house. On the other hand, you might rotate the
viewer by −90 degrees about the <i>y</i>-axis. This would put the viewer on
the negative <i>x</i>-axis, which would give it a view of the <b>left</b> side of the house.
The net result after either transformation is that the viewer ends up with exactly the
same view of the house. Either transformation can be implemented in OpenGL with the
command
</p>
<pre>glRotatef(90,0,1,0);
</pre>
<p class="np">That is, this command represents either a modeling transformation that rotates
an object by 90 degrees or a viewing transformation that rotates the viewer by −90
degrees. Note that the effect on the viewer is the inverse of the effect on the object.
Modeling and viewing transforms are always related in this way. For example, if you
are looking at an object, you can move yourself 5 feet to the <b>left</b> (viewing transform), or you can move
the object 5 feet to the <b>right</b> (modeling transform). In either case, you end up with
the same view of the object. Both transformations might be represented in OpenGL as something
like</p>
<pre>glTranslatef(5,0,0);
</pre>
<p class="np">This even works for scaling: If the viewer <i>shrinks</i>, it will look to the
viewer exactly the same as if the world is expanding, and vice-versa.</p>
<hr class="break">
<p>Although modeling and viewing transformations are the same in principle, they remain
very different conceptually, and they are typically applied at different points in the code.
In general when drawing a scene, you will do the following: (1) Load the identity matrix,
for a well-defined starting point; (2) apply the viewing transformation; and (3) draw
the objects in the scene, each with its own modeling transformation. Remember that OpenGL keeps
track of several transformations, and that this must all be done while the modelview transform
is current; if you are not sure of that then before step (1), you should call <i>glMatrixMode</i>(<i>GL_MODELVIEW</i>).
During step (3), you will probably use <i>glPushMatrix</i>() and <i>glPopMatrix</i>() to limit
each modeling transform to a particular object.
</p>
<p>After loading the identity matrix, the viewer is in the default position, at the origin,
looking down the negative <i>z</i>-axis, with the positive <i>y</i>-axis pointing upwards in the
view. Suppose, for example, that we would like to move the viewer from its
default location at the origin back along the positive z-axis from the
origin to the point (0,0,20). This operation has exactly the same effect as moving the world,
and the objects that it contains, 20 units in the negative direction along the z-axis—whichever
operation is performed, the viewer ends up in exactly the same position relative to the
objects. Both operations are implemented by the same OpenGL
command, <i>gl.glTranslatef</i>(0,0,-20). For another example,
suppose that we use two commands
</p>
<pre>gl.glRotatef(90,0,1,0);
gl.glTranslatef(10,0,0);
</pre>
<p class="np">to establish the viewing transformation. As a modeling transform, these commands would
first translate an object 10 units
in the positive x-direction, then rotate the object 90 degrees about the y-axis. (Remember that
modeling transformations are applied to objects in the order opposite to their order in the code.)
What do these commands do as a viewing transformation? The effect on the view is the inverse
of the effect on objects. The inverse of "translate 90 then rotate 10" is "rotate −10
then translate −90." That is, to do the inverse, you have to undo the rotation <b>before</b>
you undo the translation. The effect as a viewing transformation is first to rotate the viewer
by −90 degrees about the <i>y</i>-axis, then to translate by −10 along the <i>x</i>-axis.
(You should think about the two interpretations affect the view of an object that starts out
at the origin.) Note that the order in which viewing transformations are applied is the
<b>same as</b> the order in which they occur in the code.
</p>
<hr class="break">
<p>It can be difficult to set up a view by combining rotations, scalings, and translations,
so OpenGL provides an easier way to set up a typical view.
The command is not part of OpenGL itself but is part of another standard library called
<span class="newword">GLU</span> (not to be confused with GLUT).</p>
<p>The GLU library provides the following convenient method for
setting up a viewing transformation:</p>
<pre>gluLookAt( eyeX,eyeY,eyeZ, refX,refY,refZ, upX,upY,upZ );
</pre>
<p class="np">This method places the viewer at the point (<i>eyeX</i>,<i>eyeY</i>,<i>eyeZ</i>),
looking in the direction of the point (<i>refX</i>,<i>refY</i>,<i>refZ</i>).
The viewer is oriented so that the vector (<i>upX</i>,<i>upY</i>,<i>upZ</i>)
points upwards in the viewer's view. For example, to position the viewer on the positive
<i>x</i>-axis, 10 units from the origin, looking back at the origin, with the positive
direction of the <i>y</i>-axis pointing up as usual, use
</p>
<pre>gluLookAt( 10,0,0, 0,0,0, 0,1,0 );</pre>
<p>To use GLU in C, you should include the GLU header file in your program by adding
the directive <tt>#include "gl/GLU.h"</tt> at the beginning of the program. When
compiling he program, you need to link to the GLU library. For example:</p>
<pre>gcc myProgram.c -lglut -lGLU
</pre>
<p>To use GLU in Java with JOGL, you need an object of type <span class="classname">GLU</span>. This
class is in the package <i>javax.media.opengl</i>. You need to create an object of type
<span class="classname">GLU</span>:</p>
<pre>GLU glu = new GLU();
</pre>
<p class="np">and use it to call GLU routines such as <i>gluLookAt</i>:</p>
<pre>glu.gluLookAt( eyeX,eyeY,eyeZ, refX,refY,refZ, upX,upY,upZ );
</pre>
<hr class="break">
<p class="np">With all this, we can give an outline for a typical display routine. In the C version:</p>
<pre>// possibly set clear color here, if not set elsewhere
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
// possibly set up the projection here, if not done elsewhere
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
gluLookAt( eyeX,eyeY,eyeZ, refX,refY,refZ, upX,upY,upZ ); // Viewing transform
glPushMatrix();
.
. // apply modeling transform and draw an object
.
glPopMatrix();
glPushMatrix();
.
. // apply another modeling transform and draw another object
.
glPopMatrix();
.
.
.
</pre>
</div>
<div class="subsection">
<h3>The Projection Transformation</h3>
<p>To finish this discussion of transformation, we need to consider the
<span class="newword">projection transformation</span>. Recall that projection
transforms from eye coordinates to clip coordinates by mapping the view volume
to the 2-by-2-by-2 cube centered at the origin. Specifying a projection is
really just a matter of specifying the view volume.
The viewing transform determines where the viewer is looking,
but it doesn't say how much of the world the viewer can see. That's
the point of the view volume.</p>
<p>There are two general types of projection, <span class="newword">perspective projection</span>
and <span class="newword">orthographic projection</span>. Perspective projection gives a
realistic view. That is, it shows what you would see if the OpenGL display rectangle
on your computer screen were a window into an actual 3D world (one that
could extend in front of the screen as well as behind it). It shows a view that
you could get by taking a picture of a 3D world with a camera. In a perspective
view, the apparent size of an object depends on how far it is away from the
viewer. Only things that are in front of the viewer can be seen. In fact,
ignoring clipping in the <i>z</i>-direction for the moment,
the part of the world that is in view is an infinite pyramid, with the
viewer at the apex of the pyramid, and with the sides of the pyramid
passing through the sides of the viewport rectangle.</p>
<p>However, OpenGL can't actually show everything in this pyramid, because of
its use of the depth buffer to solve the hidden surface problem. Since the
depth buffer can only store a finite range of depth values, it can't
represent the entire range of depth values for the infinite pyramid that
is theoretically in view. Only objects in a certain range of distances from
the viewer are shown in the image that OpenGL produces. That range of distances
is specified by two values, <span class="newword">near</span> and <span class="newword">far</span>.
For a perspective transformation, both of these values must be positive numbers, and <i>far</i> must be greater
than <i>near</i>. Anything that is closer to the viewer than the <i>near</i> distance
or farther away than the <i>far</i> distance is discarded and does not appear
in the rendered image. The volume of space that is represented in the image
is thus a "truncated pyramid." This pyramid is the view volume for a perspective
projection:
</p>
<p align="center"><img src="images/08/frustum.png" width="587" height="226"></p>
<p>The view volume is bounded by six planes—the four sides plus the top and bottom of the pyramid. These
planes are called <span class="newword">clipping planes</span> because anything that lies on the wrong side
of each plane is clipped away.</p>
<p>In OpenGL, setting up the projection transformation is equivalent to defining
the view volume. For a perspective transformation, you have to set up a view volume
that is a truncated pyramid. A rather obscure term for this shape is a <span class="newword">frustum</span>,
and a perspective transformation can be set up with the <i>glFrustum</i> command</p>
<pre>glFrustum(xmin,xmax,ymin,ymax,near,far)
</pre>
<p class="np">The last two parameters specify the <i>near</i> and <i>far</i> distances from the
viewer, as already discussed. The viewer is assumed to be at the origin, (0,0,0), facing
in the direction of the negative z-axis. (This is the eye coordinate system.) So,
the near clipping plane is at <i>z</i> = −<i>near</i>, and the far clipping
plane is at <i>z</i> = −<i>far</i>. The first four parameters specify the sides
of the pyramid: <i>xmin</i>, <i>xmax</i>, <i>ymin</i>, and <i>ymax</i> specify the
horizontal and vertical limits of the view volume <b>at the near clipping plane</b>.
For example, the coordinates of the upper-left corner of the small end of the
pyramid are (<i>xmin</i>,<i>ymax</i>,−<i>near</i>). Note that although
<i>xmin</i> is usually equal to the negative of <i>xmax</i> and <i>ymin</i> is usually
equal to the negative of <i>ymax</i>, this is not required. It is possible to have
asymmetrical view volumes where the z-axis does not point directly down the center of
the view.
</p>
<hr class="break">
<p>Orthographic projections are comparatively easy to understand: A 3D world is projected onto
a 2D image by discarding the z-coordinate of the eye-coordinate system. This type of projection
is unrealistic in that it is not what a viewer would see. For example, the apparent size of
an object does not depend on its distance from the viewer. Objects in back of the viewer
as well as in front of the viewer are visible in the image. In fact, it's not really clear what
it means to say that there is a viewer in the case of orthographic projection.
Orthographic projections are still useful, however, especially in interactive modeling
programs where it is useful to see true sizes and angles, undistorted by perspective.</p>
<p>Nevertheless, for orthographic projection in OpenGL, there is considered to be a viewer.
The viewer is located at the eye-coordinate
origin, facing in the direction of the negative z-axis. Theoretically, a rectangular corridor
extending infinitely in both directions, in front of the viewer and in back, would be in view.
However, as with perspective projection, only a finite segment of this infinite corridor can
actually be shown in an OpenGL image. This finite view volume is a parallelepiped—a rectangular
solid—that is cut out of the infinite corridor by a <i>near</i> clipping plane and a <i>far</i>
clipping plane. The value of <i>far</i> must be greater than <i>near</i>, but for an orthographic
projection, the value of <i>near</i> is allowed to be negative, putting the "near" clipping plane
behind the viewer, as it is in this illustration:
</p>
<p align="center"><img src="images/08/parallelepiped.png" width="591" height="212" alt=""></p>
<p class="np">Note that a negative value for <i>near</i> puts the near clipping plane on the <b>positive</b>
z-axis, which is behind the viewer.</p>
<p>An orthographic projection can be set up in OpenGL using the <i>glOrtho</i> method, which is
has the following form:
</p>
<pre>glOrtho(xmin,xmax,ymin,ymax,near,far);
</pre>
<p class="np">The first four parameters specify the <i>x</i>- and <i>y</i>-coordinates of the left, right, bottom, and
top of the view volume. Note that the last two parameters are <i>near</i> and <i>far</i>,
not <i>zmin</i> and <i>zmax</i>. In fact, the minimum z-value for the view volume is
−<i>far</i> and the maximum z-value is −<i>near</i>. However, it is often
the case that <i>near</i> = −<i>far</i>, and if that is true then the minimum and
maximum z-values turn out to be <i>near</i> and <i>far</i> after all!</p>
<hr class="break">
<p>Remember that when setting up the projection transform, the
matrix mode must be set to <i>GL_PROJECTION</i>. Furthermore,
the identity matrix should be loaded before setting the projection (since
<i>glFrustum</i> and <i>glOrtho</i> modify the existing projection matrix rather than replacing
it, and you don't even want to try to think about what would happen if you
combine several projection matrices into one). So, setting the projection
often looks like this, leaving the matrix mode set to <i>GL_MODELVIEW</i>
at the end:</p>
<pre>gl.glMatrixMode(GL.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustum(xmin,xmax,ymin,ymax,near,far); // or glOrtho
gl.glMatrixMode(GL.GL_MODELVIEW);</pre>
<p>This might be used in an initialization routine, if you want to use the
same projection for the whole program. Another possibility is to put it
in the reshape routine, where you can take the aspect ratio of the viewport
into account. Or you could do it at the start of the display routine,
where it will be done every time the scene is redrawn.</p>
<hr class="break">
<p>The <i>glFrustum</i> method is not particularly easy to use. The GLU library
includes the method <i>gluPerspective</i> as an easier way to set up a perspective
projection. The command</p>
<pre>gluPerspective(fieldOfViewAngle, aspect, near, far);
</pre>
<p class="np">can be used instead of <i>glFrustum</i>. The <i>fieldOfViewAngle</i> is the vertical
angle, measured in degrees, between the top of the view volume pyramid and the bottom. A typical value is
45 degrees. The <i>aspect</i> parameter is the
aspect ratio of the view, that is, the width of the pyramid at a given distance from
the eye, divided by the height at the same distance. The value of <i>aspect</i> should
generally be set to the aspect ratio of the viewport, that is, the width of the viewport divided
by its height. The <i>near</i> and <i>far</i>
parameters have the same meaning as for <i>glFrustum</i>.</p>
</div>
<div class="subsection">
<h3>Camera and Trackball</h3>
<p>Projection and viewing are often discussed using the analogy of a <span class="newword">camera</span>.
A camera is used to take a picture of a 3D world. Setting up the viewing transformation is like
positioning and pointing the camera. The projection transformation determines the properties
of the camera: What is its field of view? (Of course, the analogy breaks in at least one respect,
since a real camera doesn't do clipping in its <i>z</i>-direction.)</p>
<p>I have written a camera utility to implement this idea. The camera is meant to completely
take over the job of setting the projection and view. Instead of doing that by hand, you set
properties of the camera. The API is somewhat different in Java and in C. I will discuss the
C implementation first.</p>
<p>In C, the camera is defined by a .c file, <a href="opengl-c/camera.c">camera.c</a> and
a corresponding header file , <a href="opengl-c/camera.h">camera.h</a>. Full documentation can
be found in the header file. To use the camera, you should <tt>#include "camera.h"</tt> at
the start of your program, and when you compile the program, you should include <i>camera.c</i> in
the list of files that you want to compile. The camera depends on the GLU library and on
C's standard math library, so you have to make sure that those libraries are available
when it is compiled. For example:</p>
<pre>gcc myglutprog.c camera.c -lGL -lglut -lGLU -lm
</pre>
<p class="np">To use the camera, you have to call</p>
<pre>cameraApply();</pre>
<p class="np">at the beginning of the display function. Calling this function completely replaces
all code for setting up the projection and viewing transformations, and it leaves the
matrix mode set to <i>GL_MODELVIEW</i>. You can configure the camera by calling these
functions, but remember that the settings are not used until you call <i>cameraApply</i>:</p>
<pre>
cameraLookAt( eyeX,eyeY,eyeZ, refX,refY,refZ, upX,upY,upZ );
// Determines the viewing transform, just like gluLookAt
// Default is cameraLookAt( 0,0,30, 0,0,0, 0,1,0 );
cameraSetLimits( xmin, xmax, ymin, ymax, zmin, zmax );
// Sets the limits on the view volume, where zmin and zmax are
// given with respect to the view reference point, NOT the eye,
// and the xy limits are measured at the distance of the
// view reference point, NOT the near distance.
// Default is cameraSetLimits( -5,5, -5,5, -10,10 );
cameraSetScale( limit );
// a convenience method, which is the same as calling
// cameraSetLimits( -limit,limit, -limit,limit, -2*limit, 2*limit );
cameraSetOrthographic( isOrtho );
// Switch between orthographic and perspective projection.
// The parameter should be 0 for perspective, 1 for
// orthographic. The default is perspective.
cameraSetPreserveAspect( preserve );
// Determine whether the aspect ratio of the viewport should
// be respected. The parameter should be 0 to ignore and
// 1 to respect the viewport aspect ratio. The default
// is to preserve the aspect ratio.
</pre>
<p></p>
<hr class="break">
<p>The camera comes along with a simulated <span class="newword">trackball</span>.
The trackball allows the user to rotate the view by clicking and dragging the mouse
on the display. To use it with GLUT in C, you just need to install a mouse function and
a mouse motion functions by calling
</p>
<pre>glutMouseFunc( trackballMouseFunction );
glutMotionFunc( trackballMotionFunction );
</pre>
<p class="np">when you want to enable the trackball. The functions
<i>trackballMouseFunction</i> and <i>trackballMotionFunction</i> are defined
as part of the camera library and are declared in <i>camera.h</i>.
The trackball works by modifying the viewing transformation associated with
the camera, and it only works if <i>cameraApply</i>() is called at the
beginning of the display function to set the viewing and projection
transformations.</p>
<hr class="break">
<p>A camera and trackball are also available for use with JOGL, in a
<span class="class">Camera</span> class, defined in file
<i><a href="opengl-jogl/Camera.java">Camera.java</a></i>. The camera
is meant for use with a <span class="classname">GLJPanel</span> or
<span class="classname">GLCanvas</span>. To use
one, you have to create an object of type <span class="class">Camera</span>:</p>
<pre>Camera camera = new Camera();
</pre>
<p class="np">and at the start of the <i>display</i>() method you must call</p>
<pre>camera.apply(gl);
</pre>
<p class="np">where <i>gl</i> is the OpenGL drawing context of type <i>GL2</i>.
(Note the presence of the parameter <i>gl</i>, which was not necessary in C!)
As in the C version, this sets the viewing and projection transformations and
should completely replace any other code that you would use for that purpose.
The functions for configuring the camera are the same in Java as in C,
except that they become methods in the <i>camera</i> object, and true/false
parameters are <i>boolean</i> instead of <i>int</i>:</p>
<pre>camera.lookAt( eyeX,eyeY,eyeZ, refX,refY,refZ, upX,upY,upZ );
camera.setLimits( xmin,xmax, ymin,ymax, zmin,zmax );
camera.setScale( limit );
camera.setOrthographic( isOrtho ); // isOrtho is of type boolean
camera.setPreserveAspect( preserve ); // preserve is of type boolean
</pre>
<p class="np">To install a trackball for use with the camera, call</p>
<pre>camera.installTrackball(gldrawable);
</pre>
<p class="np">where <i>gldrawabel</i> is the component on which the camera
is used, probably a <span class="classname">GLJPanel</span> or
<span class="classname">GLCanvas</span>.</p>
</div>
<div class="subsection">
<h3>Putting the Viewer into the World</h3>
<p>The camera API allows you to change the position and orientation of the
camera, but it doesn't make it possible to do so by applying transformations,
which is the usual way of placing an object into the world. Suppose
that we want to think of the viewer (or eye or camera) as an object like other
objects in the world, and we want to be able to move it around in the world
by applying a modeling transformation, as we do for other objects. A viewer
that can be manipulated in this way is sometimes called an <span class="newword">avatar</span>.
Ideally, we would like to be able to add some kind of avatar object to a scene graph,
and then change or animate the avatar's point of view by applying modeling
transformations to that node of the scene graph.
</p>
<p>But there are two problems with thinking of a viewer as an object. First of all,
the viewing transformation must be applied at the beginning, before any geometry is
drawn. This means that you can't simply traverse the scene graph in the usual way
and implement the avatar at the point where it is encountered in the scene graph,
since before you get to that node, you will have already drawn the geometry
in other nodes that you have encountered. The second problem is the inverse
relation between modeling and viewing transformation: If you want to apply
a modeling transformation to the avatar <i>object</i>, you really need to apply
the <i>inverse</i> of that modeling transformation as the viewing transformation.
</p>
<p>The easiest way to think about how to solve these problems is to imagine the
scene graph as a linked data structure. To implement the avatar, we need to
include "parent pointers" in the data structure that point from a node to
its parent in the scene graph. Parent pointers allow you to move up the
scene graph, in the direction of the root. Then, to implement the avatar,
start from the avatar node in the scene graph. Call <i>glLoadIdentity</i>() to
initialize the modelview transformation. Then move up the scene graph, following
parent pointers. When you encounter a modeling transformation, apply the
<i>inverse</i> of that transformation. (These inverses will be applied in
the reverse order from their order as modeling transformations. This is the
correct way to compute the inverse of a sequence of transforms. Mathematically,
(S<tt>*</tt>R)<sup>−1</sup> = R<sup>−1</sup><tt>*</tt>S<sup>−1</sup>.)
Stop when you get to the root of the
scene graph. At that point, the modelview transform contains exactly the
viewing transformation that you want, and you are ready to traverse the
scene graph to draw the geometry. (In that traversal, the avatar node should
be ignored.)</p>
<p>If the scene graph is implemented procedurally rather than as a data structure,
you have to do things differently, but the end result should be the same. One
possibility is to do two traversals of the scene graph, one to find and implement
the avatar and one to draw the geometry.</p>
</div>
<div class="subsection">
<h3>Homogeneous Coordinates</h3>
<p>We finish this section with a bit of mathematical detail about the implementation of transformations.
There is one transformation in computer graphics that is not an affine transformation:
In the case of a perspective projection, the projection transformation is not affine.
In a perspective projection, an object will appear to get smaller as it moves farther away
from the viewer, and that is a property that no affine transformation can express, since
affine transforms preserve parallel lines and parallel lines will seem to converge in the
distance in a perspective projection.
</p>
<p>Surprisingly, we can still represent a perspective projection as a 4-by-4 matrix, provided
we are willing to stretch our use of coordinates even further than we have already. We
have already represented 3D vectors by 4D vectors in which the fourth coordinate is 1.
We now allow the fourth coordinate to be anything at all. When the fourth coordinate, <i>w</i>,
is non-zero, we consider the coordinates (<i>x,y,z,w</i>) to
represent the three-dimensional vector (<i>x/w,y/w,z/w</i>). Note that this
is consistent with our previous usage, since it considers (<i>x,y,z,1</i>)
to represent (<i>x,y,z</i>), as before. When the fourth coordinate is zero,
there is no corresponding 3D vector, but it is possible to think of (<i>x,y,z</i>,0)
as representing a 3D "point at infinity" in the direction of (<i>x,y,z</i>),
as long as at least one of <i>x</i>, <i>y</i>, and <i>z</i> are zero.
</p>
<p>Coordinates (<i>x,y,z,w</i>) used in this way are referred to
as <span class="newword">homogeneous coordinates</span>. If we use homogeneous coordinates, then any
4-by-4 matrix can be used to transform three-dimensional vectors, and among the transformations
that can be represented in this way is the projection transformation for a perspective
projection. And in fact, this is what OpenGL does internally. It represents all three-dimensional
points and vectors using homogeneous coordinates, and it represents all transformations as
4-by-4 matrices. You can even specify vertices using homogeneous coordinates. For example, the
command
</p>
<pre>gl.glVertex4d(x,y,z,w);</pre>
<p class="np">generates the 3D point <span class="code">(x/w,y/w,z/w)</span>. Fortunately, you will almost never
have to deal with homogeneous coordinates directly. The only real exception to this is
that homogeneous coordinates are required, surprisingly, when configuring OpenGL lighting, as
we'll see in the next section.</p>
</div>
<p class="nav">[
<a href="07_GLUT_and_JOGL.html">Previous Section</a> |
<a href="09_Light_and_Material.html">Next Section</a> |
<a href="index.html">Index</a>
]</p>
</div>
</body>
</html> |
import React, { Component } from "react";
import { View, Image, StyleSheet, Text, Dimensions, TouchableOpacity } from "react-native";
import WideButton from "./WideButton";
import sources, { text, actions } from "../assets/emptyStates/emptyStates";
function EmptyState({ state, onPress, modal }) {
return (
<View style={styles.container}>
<Text style={styles.text}>{text[state].h1}</Text>
<Text style={styles.text2}>{text[state].h2}</Text>
<Image source={sources[state]} style={modal ? styles.imageModal : styles.image} />
<View style={{ width: "100%", position: "absolute", bottom: 40 }}>
<TouchableOpacity
onPress={() => {
onPress?onPress():actions[state]();
}}
>
<WideButton
containerStyle={{ backgroundColor: "black", width: "80%" }}
textStyle={{ color: "white", fontSize: 15 }}
value={text[state].button}
/>
</TouchableOpacity>
</View>
</View>
);
}
const { width, height } = Dimensions.get("window");
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
height: height - 170
},
image: {
height: 150,
width: "80%",
resizeMode: "contain",
marginTop: 100,
marginBottom: 100
},
imageModal: {
height: 140,
resizeMode: "contain",
marginTop: 50,
marginBottom: 100
},
text: {
fontFamily: "poppins-semi-bold",
fontSize: 25,
color: "black",
textAlign: "center"
},
text2: {
textAlign: "center",
fontSize: 13,
color: "#808080",
fontFamily: "poppins-regular",
marginTop: 30
}
});
export default EmptyState; |
<?php
namespace Drupal\Tests\Core\Template;
use Drupal\Component\Utility\Html;
use Drupal\Core\Render\Markup;
use Drupal\Core\Template\Attribute;
use Drupal\Core\Template\AttributeArray;
use Drupal\Core\Template\AttributeString;
use Drupal\Tests\UnitTestCase;
use Drupal\Component\Render\MarkupInterface;
/**
* @coversDefaultClass \Drupal\Core\Template\Attribute
* @group Template
*/
class AttributeTest extends UnitTestCase {
/**
* Tests the constructor of the attribute class.
*/
public function testConstructor() {
$attribute = new Attribute(['class' => ['example-class']]);
$this->assertTrue(isset($attribute['class']));
$this->assertEquals(new AttributeArray('class', ['example-class']), $attribute['class']);
// Test adding boolean attributes through the constructor.
$attribute = new Attribute(['selected' => TRUE, 'checked' => FALSE]);
$this->assertTrue($attribute['selected']->value());
$this->assertFalse($attribute['checked']->value());
// Test that non-array values with name "class" are cast to array.
$attribute = new Attribute(['class' => 'example-class']);
$this->assertTrue(isset($attribute['class']));
$this->assertEquals(new AttributeArray('class', ['example-class']), $attribute['class']);
// Test that safe string objects work correctly.
$safe_string = $this->prophesize(MarkupInterface::class);
$safe_string->__toString()->willReturn('example-class');
$attribute = new Attribute(['class' => $safe_string->reveal()]);
$this->assertTrue(isset($attribute['class']));
$this->assertEquals(new AttributeArray('class', ['example-class']), $attribute['class']);
}
/**
* Tests set of values.
*/
public function testSet() {
$attribute = new Attribute();
$attribute['class'] = ['example-class'];
$this->assertTrue(isset($attribute['class']));
$this->assertEquals(new AttributeArray('class', ['example-class']), $attribute['class']);
}
/**
* Tests adding new values to an existing part of the attribute.
*/
public function testAdd() {
$attribute = new Attribute(['class' => ['example-class']]);
$attribute['class'][] = 'other-class';
$this->assertEquals(new AttributeArray('class', ['example-class', 'other-class']), $attribute['class']);
}
/**
* Tests removing of values.
*/
public function testRemove() {
$attribute = new Attribute(['class' => ['example-class']]);
unset($attribute['class']);
$this->assertFalse(isset($attribute['class']));
}
/**
* Tests setting attributes.
* @covers ::setAttribute
*/
public function testSetAttribute() {
$attribute = new Attribute();
// Test adding various attributes.
$attributes = ['alt', 'id', 'src', 'title', 'value'];
foreach ($attributes as $key) {
foreach (['kitten', ''] as $value) {
$attribute = new Attribute();
$attribute->setAttribute($key, $value);
$this->assertEquals($value, $attribute[$key]);
}
}
// Test adding array to class.
$attribute = new Attribute();
$attribute->setAttribute('class', ['kitten', 'cat']);
$this->assertArrayEquals(['kitten', 'cat'], $attribute['class']->value());
// Test adding boolean attributes.
$attribute = new Attribute();
$attribute['checked'] = TRUE;
$this->assertTrue($attribute['checked']->value());
}
/**
* Tests removing attributes.
* @covers ::removeAttribute
*/
public function testRemoveAttribute() {
$attributes = [
'alt' => 'Alternative text',
'id' => 'bunny',
'src' => 'zebra',
'style' => 'color: pink;',
'title' => 'kitten',
'value' => 'ostrich',
'checked' => TRUE,
];
$attribute = new Attribute($attributes);
// Single value.
$attribute->removeAttribute('alt');
$this->assertEmpty($attribute['alt']);
// Multiple values.
$attribute->removeAttribute('id', 'src');
$this->assertEmpty($attribute['id']);
$this->assertEmpty($attribute['src']);
// Single value in array.
$attribute->removeAttribute(['style']);
$this->assertEmpty($attribute['style']);
// Boolean value.
$attribute->removeAttribute('checked');
$this->assertEmpty($attribute['checked']);
// Multiple values in array.
$attribute->removeAttribute(['title', 'value']);
$this->assertEmpty((string) $attribute);
}
/**
* Tests adding class attributes with the AttributeArray helper method.
* @covers ::addClass
*/
public function testAddClasses() {
// Add empty Attribute object with no classes.
$attribute = new Attribute();
// Add no class on empty attribute.
$attribute->addClass();
$this->assertEmpty($attribute['class']);
// Test various permutations of adding values to empty Attribute objects.
foreach ([NULL, FALSE, '', []] as $value) {
// Single value.
$attribute->addClass($value);
$this->assertEmpty((string) $attribute);
// Multiple values.
$attribute->addClass($value, $value);
$this->assertEmpty((string) $attribute);
// Single value in array.
$attribute->addClass([$value]);
$this->assertEmpty((string) $attribute);
// Single value in arrays.
$attribute->addClass([$value], [$value]);
$this->assertEmpty((string) $attribute);
}
// Add one class on empty attribute.
$attribute->addClass('banana');
$this->assertArrayEquals(['banana'], $attribute['class']->value());
// Add one class.
$attribute->addClass('aa');
$this->assertArrayEquals(['banana', 'aa'], $attribute['class']->value());
// Add multiple classes.
$attribute->addClass('xx', 'yy');
$this->assertArrayEquals(['banana', 'aa', 'xx', 'yy'], $attribute['class']->value());
// Add an array of classes.
$attribute->addClass(['red', 'green', 'blue']);
$this->assertArrayEquals(['banana', 'aa', 'xx', 'yy', 'red', 'green', 'blue'], $attribute['class']->value());
// Add an array of duplicate classes.
$attribute->addClass(['red', 'green', 'blue'], ['aa', 'aa', 'banana'], 'yy');
$this->assertEquals('banana aa xx yy red green blue', (string) $attribute['class']);
}
/**
* Tests removing class attributes with the AttributeArray helper method.
* @covers ::removeClass
*/
public function testRemoveClasses() {
// Add duplicate class to ensure that both duplicates are removed.
$classes = ['example-class', 'aa', 'xx', 'yy', 'red', 'green', 'blue', 'red'];
$attribute = new Attribute(['class' => $classes]);
// Remove one class.
$attribute->removeClass('example-class');
$this->assertNotContains('example-class', $attribute['class']->value());
// Remove multiple classes.
$attribute->removeClass('xx', 'yy');
$this->assertNotContains(['xx', 'yy'], $attribute['class']->value());
// Remove an array of classes.
$attribute->removeClass(['red', 'green', 'blue']);
$this->assertNotContains(['red', 'green', 'blue'], $attribute['class']->value());
// Remove a class that does not exist.
$attribute->removeClass('gg');
$this->assertNotContains(['gg'], $attribute['class']->value());
// Test that the array index remains sequential.
$this->assertArrayEquals(['aa'], $attribute['class']->value());
$attribute->removeClass('aa');
$this->assertEmpty((string) $attribute);
}
/**
* Tests checking for class names with the Attribute method.
* @covers ::hasClass
*/
public function testHasClass() {
// Test an attribute without any classes.
$attribute = new Attribute();
$this->assertFalse($attribute->hasClass('a-class-nowhere-to-be-found'));
// Add a class to check for.
$attribute->addClass('we-totally-have-this-class');
// Check that this class exists.
$this->assertTrue($attribute->hasClass('we-totally-have-this-class'));
}
/**
* Tests removing class attributes with the Attribute helper methods.
* @covers ::removeClass
* @covers ::addClass
*/
public function testChainAddRemoveClasses() {
$attribute = new Attribute(
['class' => ['example-class', 'red', 'green', 'blue']]
);
$attribute
->removeClass(['red', 'green', 'pink'])
->addClass(['apple', 'lime', 'grapefruit'])
->addClass(['banana']);
$expected = ['example-class', 'blue', 'apple', 'lime', 'grapefruit', 'banana'];
$this->assertArrayEquals($expected, $attribute['class']->value(), 'Attributes chained');
}
/**
* Tests the twig calls to the Attribute.
* @dataProvider providerTestAttributeClassHelpers
*
* @covers ::removeClass
* @covers ::addClass
*/
public function testTwigAddRemoveClasses($template, $expected, $seed_attributes = []) {
$loader = new \Twig_Loader_String();
$twig = new \Twig_Environment($loader);
$data = ['attributes' => new Attribute($seed_attributes)];
$result = $twig->render($template, $data);
$this->assertEquals($expected, $result);
}
/**
* Provides tests data for testEscaping
*
* @return array
* An array of test data each containing of a twig template string,
* a resulting string of classes and an optional array of attributes.
*/
public function providerTestAttributeClassHelpers() {
return [
["{{ attributes.class }}", ''],
["{{ attributes.addClass('everest').class }}", 'everest'],
["{{ attributes.addClass(['k2', 'kangchenjunga']).class }}", 'k2 kangchenjunga'],
["{{ attributes.addClass('lhotse', 'makalu', 'cho-oyu').class }}", 'lhotse makalu cho-oyu'],
[
"{{ attributes.addClass('nanga-parbat').class }}",
'dhaulagiri manaslu nanga-parbat',
['class' => ['dhaulagiri', 'manaslu']],
],
[
"{{ attributes.removeClass('annapurna').class }}",
'gasherbrum-i',
['class' => ['annapurna', 'gasherbrum-i']],
],
[
"{{ attributes.removeClass(['broad peak']).class }}",
'gasherbrum-ii',
['class' => ['broad peak', 'gasherbrum-ii']],
],
[
"{{ attributes.removeClass('gyachung-kang', 'shishapangma').class }}",
'',
['class' => ['shishapangma', 'gyachung-kang']],
],
[
"{{ attributes.removeClass('nuptse').addClass('annapurna-ii').class }}",
'himalchuli annapurna-ii',
['class' => ['himalchuli', 'nuptse']],
],
// Test for the removal of an empty class name.
["{{ attributes.addClass('rakaposhi', '').class }}", 'rakaposhi'],
];
}
/**
* Tests iterating on the values of the attribute.
*/
public function testIterate() {
$attribute = new Attribute(['class' => ['example-class'], 'id' => 'example-id']);
$counter = 0;
foreach ($attribute as $key => $value) {
if ($counter == 0) {
$this->assertEquals('class', $key);
$this->assertEquals(new AttributeArray('class', ['example-class']), $value);
}
if ($counter == 1) {
$this->assertEquals('id', $key);
$this->assertEquals(new AttributeString('id', 'example-id'), $value);
}
$counter++;
}
}
/**
* Tests printing of an attribute.
*/
public function testPrint() {
$attribute = new Attribute(['class' => ['example-class'], 'id' => 'example-id', 'enabled' => TRUE]);
$content = $this->randomMachineName();
$html = '<div' . (string) $attribute . '>' . $content . '</div>';
$this->assertClass('example-class', $html);
$this->assertNoClass('example-class2', $html);
$this->assertID('example-id', $html);
$this->assertNoID('example-id2', $html);
$this->assertTrue(strpos($html, 'enabled') !== FALSE);
}
/**
* @covers ::createAttributeValue
* @dataProvider providerTestAttributeValues
*/
public function testAttributeValues(array $attributes, $expected) {
$this->assertEquals($expected, (new Attribute($attributes))->__toString());
}
public function providerTestAttributeValues() {
$data = [];
$string = '"> <script>alert(123)</script>"';
$data['safe-object-xss1'] = [['title' => Markup::create($string)], ' title=""> alert(123)""'];
$data['non-safe-object-xss1'] = [['title' => $string], ' title="' . Html::escape($string) . '"'];
$string = '"><script>alert(123)</script>';
$data['safe-object-xss2'] = [['title' => Markup::create($string)], ' title="">alert(123)"'];
$data['non-safe-object-xss2'] = [['title' => $string], ' title="' . Html::escape($string) . '"'];
return $data;
}
/**
* Checks that the given CSS class is present in the given HTML snippet.
*
* @param string $class
* The CSS class to check.
* @param string $html
* The HTML snippet to check.
*/
protected function assertClass($class, $html) {
$xpath = "//*[@class='$class']";
self::assertTrue((bool) $this->getXPathResultCount($xpath, $html));
}
/**
* Checks that the given CSS class is not present in the given HTML snippet.
*
* @param string $class
* The CSS class to check.
* @param string $html
* The HTML snippet to check.
*/
protected function assertNoClass($class, $html) {
$xpath = "//*[@class='$class']";
self::assertFalse((bool) $this->getXPathResultCount($xpath, $html));
}
/**
* Checks that the given CSS ID is present in the given HTML snippet.
*
* @param string $id
* The CSS ID to check.
* @param string $html
* The HTML snippet to check.
*/
protected function assertID($id, $html) {
$xpath = "//*[@id='$id']";
self::assertTrue((bool) $this->getXPathResultCount($xpath, $html));
}
/**
* Checks that the given CSS ID is not present in the given HTML snippet.
*
* @param string $id
* The CSS ID to check.
* @param string $html
* The HTML snippet to check.
*/
protected function assertNoID($id, $html) {
$xpath = "//*[@id='$id']";
self::assertFalse((bool) $this->getXPathResultCount($xpath, $html));
}
/**
* Counts the occurrences of the given XPath query in a given HTML snippet.
*
* @param string $query
* The XPath query to execute.
* @param string $html
* The HTML snippet to check.
*
* @return int
* The number of results that are found.
*/
protected function getXPathResultCount($query, $html) {
$document = new \DOMDocument();
$document->loadHTML($html);
$xpath = new \DOMXPath($document);
return $xpath->query($query)->length;
}
/**
* Tests the storage method.
*/
public function testStorage() {
$attribute = new Attribute(['class' => ['example-class']]);
$this->assertEquals(['class' => new AttributeArray('class', ['example-class'])], $attribute->storage());
}
} |
define([
"hdjs",
"jQuery",
], function (hdjs, $) {
return {
markdown: function (elem, options) {
require([
"editormd",
"dist/static/editor.md/languages/zh-tw",
"dist/static/editor.md/plugins/link-dialog/link-dialog",
"dist/static/editor.md/plugins/reference-link-dialog/reference-link-dialog",
"dist/static/editor.md/plugins/image-dialog/image-dialog",
"dist/static/editor.md/plugins/code-block-dialog/code-block-dialog",
"dist/static/editor.md/plugins/table-dialog/table-dialog",
"dist/static/editor.md/plugins/emoji-dialog/emoji-dialog",
"dist/static/editor.md/plugins/goto-line-dialog/goto-line-dialog",
"dist/static/editor.md/plugins/help-dialog/help-dialog",
"dist/static/editor.md/plugins/html-entities-dialog/html-entities-dialog",
"dist/static/editor.md/plugins/preformatted-text-dialog/preformatted-text-dialog"], function (editormd) {
options = Object.assign({
syncScrolling: "single",
path: window.hdjs.base + "/dist/static/editor.md/lib/",
width: "100%",
height: 500,
toolbarAutoFixed: false,
toolbarIcons: function () {
return [
"undo", "redo", "|",
"bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|",
"h1", "h2", "h3", "h4", "h5", "h6", "|",
"list-ul", "list-ol", "hr", "|",
"link", "reference-link", "hdimage", "code", "preformatted-text", "code-block", "table", "datetime", "emoji", "html-entities", "pagebreak", "|",
"goto-line", "watch", "preview", "fullscreen", "clear", "search", "|",
"help"
]
},
// toolbarIcons : "full", // You can also use editormd.toolbarModes[name] default list, values: full, simple, mini.
toolbarIconsClass: {
hdimage: "fa-picture-o" // 指定一个FontAawsome的图标类
},
// 自定义工具栏按钮的事件处理
toolbarHandlers: {
/**
* @param {Object} cm CodeMirror对象
* @param {Object} icon 图标按钮jQuery元素对象
* @param {Object} cursor CodeMirror的光标对象,可获取光标所在行和位置
* @param {String} selection 编辑器选中的文本
*/
hdimage: function (cm, icon, cursor, selection) {
hdjs.image(function (images) {
var str = '';
cm.replaceSelection(str);
})
}
},
lang: {
toolbar: {
hdimage: "图片上传",
}
}
}, options);
return editormd(elem, options);
})
},
markdownToHTML: function (elem, options) {
require(['editormd'], function (editormd) {
options = Object.assign({
htmlDecode: "style,script,iframe", // you can filter tags decode
emoji: true,
taskList: true,
tex: true, // 默认不解析
flowChart: true, // 默认不解析
sequenceDiagram: true, // 默认不解析
}, options);
return editormd.markdownToHTML("editormd", {
htmlDecode: "style,script,iframe", // you can filter tags decode
emoji: true,
taskList: true,
tex: true, // 默认不解析
flowChart: true, // 默认不解析
sequenceDiagram: true, // 默认不解析
});
})
}
}
}) |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
"use strict";
// Destructuring
// a syntax that allows us to unpack arrays or objects into a unch of variables
// useful when a function needs piecs of an object or array
// Destructuring Arrays
// works with any iterable (Sets, Maps, etc)
let arr = ['John', 'William', 'Dunn', 27];
// destructuring assignment sets firstName = arr[0] and lastName = arr[2]
let [firstName, , lastName] = arr;
// can skip elements with extra commas
// does not modify the array
console.log(`${firstName} ${lastName}`);
console.log(typeof(firstName)); // is a string
// also works well with "split"
let [fName, lName] = 'Hannah Marie'.split(' ');
console.log(lName);
// can assign to anything
// ex: object properties
let user = {};
[user.name, user.surname] = 'Abigal Dunn'.split(' ');
console.log(user);
console.log('\n');
// looping with .entries()
for (let [key, value] of Object.entries(user)) {
console.log(`${key}:${value}`);
}
// trick to swap 2 variables:
let guest = 'Jane';
let admin = 'Pete';
[guest, admin] = [admin, guest];
// rest "..." - add 3 dots at the end of destructuring to get everything else in an array
let [fn, ln, ...rest] = arr;
console.log(rest);
// absent values are undefined and don't cause an error
let [make, model] = [];
console.log(make);
// we can set defaults if we want:
let [year = 2020, month = 12] = [2018]
console.log(year + ' ' + month);
// these defaults could be more complex, even function calls like "prompt"
// these defaults only are evaluated if the value is not provided
</script>
</body>
</html> |
%drawGrid will draw lines on an axes along the X and Y axis, sending the
%lines to the back as well.
%
% Lx = drawGrid(Ax, Tick, Dir, Style, varargin)
%
% INPUT
% Ax: plot axes to draw on
% Tick: tick values to add a line to
% Dir ['x' 'y']: direction to draw the lines
% Sytle: sytle for the line, Ex: 'k--' for black dash line
% varargin: modifiers for the line property
%
% OUTPUT
% Lx: Mx1 gobject array of lines drawn
%
% EXAMPLE
% Ax = newplot;
% Tick = [0:0.1:1];
% Dir = 'x';
% Style = 'k--';
% Lx = drawGrid(Ax, Tick, Dir, Style, 'LineWidth', 1)
function Lx = drawGrid(Ax, Tick, Dir, Style, varargin)
Lx = gobjects(numel(Tick), 1);
hold(Ax, 'on');
ZLim = get(Ax, 'ZLim'); %Set the ticks below the ZLim.
Z = (ZLim(1) - 1) * [1 1];
switch lower(Dir)
case 'x'
YLim = get(Ax, 'YLim');
for k = 1:numel(Tick)
Lx(k) = plot(Ax, [Tick(k) Tick(k)], YLim, Style, varargin{:});
Lx(k).ZData = Z;
end
set(Ax, 'YLim', YLim);
case 'y'
XLim = get(Ax, 'XLim');
for k = 1:numel(Tick)
Lx(k) = plot(Ax, XLim, [Tick(k) Tick(k)], Style, varargin{:});
end
set(Ax, 'XLim', XLim);
otherwise
error('%s: Unrecognized Dir input "%s".', mfilename, Dir);
end
hold(Ax, 'off'); |
import React, { useState } from 'react';
import {IonIcon, useIonViewDidEnter} from '@ionic/react';
import {caretBackOutline, caretForwardOutline } from 'ionicons/icons';
interface IMonthPicker {
month: number,
setMonth: (m: number)=>void,
year: number,
setYear: (y: number)=>void,
}
const NotDailyChallenge = ({month, setMonth, year, setYear}: IMonthPicker) => {
let monthText: string[];
monthText = [];
monthText[0] = "January";
monthText[1] = "February";
monthText[2] = "March";
monthText[3] = "April";
monthText[4] = "May";
monthText[5] = "June";
monthText[6] = "July";
monthText[7] = "August";
monthText[8] = "September";
monthText[9] = "October";
monthText[10] = "November";
monthText[11] = "December";
const [displayDate, setDisplayDate] = useState(monthText[new Date().getMonth()] + " " + new Date().getFullYear());
const [currentDate, setCurrentDate] = useState(new Date());
useIonViewDidEnter(() => {
let date = new Date();
let month = monthText[date.getMonth()];
let year = date.getFullYear();
setDisplayDate(month + " " + year);
setCurrentDate(date);
});
function changeMonth(change: number){
let date = currentDate;
date.setMonth(date.getMonth() + change);
let month = monthText[date.getMonth()];
let year = date.getFullYear();
setMonth(date.getMonth());
setYear(year);
setDisplayDate(month + " " + year);
setCurrentDate(date);
}
return (
<div className={'MonthPicker'}>
<IonIcon onClick={()=>changeMonth(-1)} icon={caretBackOutline} />
{displayDate && displayDate}
<IonIcon onClick={()=>changeMonth(1)} icon={caretForwardOutline} />
</div>
);
};
export default NotDailyChallenge; |
import Button from "@mui/material/Button";
import Paper from "@mui/material/Paper";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import React, { useEffect, useState } from "react";
import ChatModal from "../../components/chatModal/chatModal";
import AuthService from "../../utils/auth";
import "./users.css";
import { useMutation, useQuery } from "@apollo/client";
import { REMOVE_USER } from "../../utils/mutations";
import { GET_USERS_BY_COMPANY } from "../../utils/queries";
export default function Users() {
if (AuthService.loggedIn()) {
const [users, setUsers] = useState([]);
const [isModalOpen, setIsModalOpen] = useState(false);
const [profile, setProfile] = useState(AuthService.getProfile());
const [removeUser] = useMutation(REMOVE_USER);
const { loading, error, data } = useQuery(GET_USERS_BY_COMPANY, {
variables: { companyId: localStorage.getItem("company_id") },
});
const myRole = profile.data.role;
const myId = profile.data._id;
console.log(myId);
const { refetch } = useQuery(GET_USERS_BY_COMPANY, {
variables: { companyId: localStorage.getItem("company_id") },
skip: true, // Set skip to true to prevent automatic fetching
});
const triggerRefetch = () => {
refetch();
};
useEffect(() => {
if (data) {
const userData = data.users;
setUsers(userData);
}
}, [data, triggerRefetch]);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
const handleRemoveUser = (user) => {
const userId = user._id;
console.log(userId);
removeUser({ variables: { userId } })
.then(() => {
triggerRefetch();
})
.catch((error) => {
console.error("Error removing user:", error);
});
};
const openModal = () => {
setIsModalOpen(true);
};
const closeModal = () => {
setIsModalOpen(false);
};
return (
<div className="tableContainerDiv">
<TableContainer component={Paper} className="tableContainer">
<Table
sx={{ minWidth: 650 }}
aria-label="user table"
className="userTable"
>
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Email</TableCell>
<TableCell>Role</TableCell>
<TableCell>Title</TableCell>
<TableCell>Phone Number</TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
</TableRow>
</TableHead>
<TableBody>
{users.map((user) => (
<TableRow key={user._id}>
<TableCell component="th" scope="row">
{`${user.firstName} ${user.lastName}`}
</TableCell>
<TableCell>{user.email}</TableCell>
<TableCell>{user.role}</TableCell>
<TableCell>{user.title}</TableCell>
<TableCell>{user.phone}</TableCell>
<TableCell>
{user._id !== myId && (
<Button
key="chatUzer"
onClick={() => openModal()}
sx={{
backgroundColor: "#134074",
}}
variant="contained"
>
{`Chat with ${user.firstName}`}
</Button>
)}
</TableCell>
<TableCell>
{(myRole.includes("Owner") ||
(myRole.includes("Admin") &&
user.role !== "Owner")) &&
user._id !== myId && [
<Button
key="removeUzer"
onClick={() =>
handleRemoveUser(user)
}
color="error"
variant="contained"
>
Remove User
</Button>,
]}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
<ChatModal isOpen={isModalOpen} onClose={closeModal} />
</div>
);
} else {
return <h1>Please log in to view this page.</h1>;
}
} |
# 用于稳定扩散 XL (SDXL) 的 T2I 适配器
> 译者:[片刻小哥哥](https://github.com/jiangzhonglian)
>
> 项目地址:<https://huggingface.apachecn.org/docs/diffusers/training/t2i_adapters>
>
> 原始地址:<https://huggingface.co/docs/diffusers/training/t2i_adapters>
这
`train_t2i_adapter_sdxl.py`
脚本(如下所示)展示了如何实现
[T2I-Adapter 培训流程](https://hf.co/papers/2302.08453)
为了
[稳定扩散XL](https://huggingface.co/papers/2307.01952)
。
## 使用 PyTorch 在本地运行
###
安装依赖项
在运行脚本之前,请确保安装库的训练依赖项:
**重要的**
为了确保您可以成功运行示例脚本的最新版本,我们强烈建议
**从源安装**
并保持安装最新,因为我们经常更新示例脚本并安装一些特定于示例的要求。为此,请在新的虚拟环境中执行以下步骤:
```
git clone https://github.com/huggingface/diffusers
cd diffusers
pip install -e .
```
然后cd到
`示例/t2i_adapter`
文件夹并运行
```
pip install -r requirements_sdxl.txt
```
并初始化一个
[🤗加速](https://github.com/huggingface/accelerate/)
环境:
```
accelerate config
```
或者使用默认加速配置而不回答有关您的环境的问题
```
accelerate config default
```
或者,如果您的环境不支持交互式 shell(例如笔记本)
```
from accelerate.utils import write_basic_config
write_basic_config()
```
跑步时
`加速配置`
,如果我们将 torch 编译模式指定为 True,则可以显着提高速度。
## 圆形填充数据集
原始数据集托管在
[ControlNet 存储库](https://huggingface.co/lllyasviel/ControlNet/blob/main/training/fill50k.zip)
。我们重新上传它以兼容
`数据集`
[此处](https://huggingface.co/datasets/fusing/fill50k)
。注意
`数据集`
处理训练脚本中的数据加载。
## 训练
我们的训练示例使用两个测试条件图像。可以通过运行来下载它们
```
wget https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/controlnet_training/conditioning_image_1.png
wget https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/controlnet_training/conditioning_image_2.png
```
然后运行
`huggingface-cli 登录`
登录您的 Hugging Face 帐户。这是为了能够将经过训练的 T2IAdapter 参数推送到 Hugging Face Hub 所必需的。
```
export MODEL_DIR="stabilityai/stable-diffusion-xl-base-1.0"
export OUTPUT_DIR="path to save model"
accelerate launch train_t2i_adapter_sdxl.py --pretrained_model_name_or_path=$MODEL\_DIR --output_dir=$OUTPUT\_DIR --dataset_name=fusing/fill50k --mixed_precision="fp16" --resolution=1024 --learning_rate=1e-5 --max_train_steps=15000 --validation_image "./conditioning\_image\_1.png" "./conditioning\_image\_2.png" --validation_prompt "red circle with blue background" "cyan circle with brown floral background" --validation_steps=100 --train_batch_size=1 --gradient_accumulation_steps=4 --report_to="wandb" --seed=42 --push_to_hub
```
为了更好地跟踪我们的训练实验,我们在上面的命令中使用以下标志:
* `report_to="wandb`
将确保跟踪训练运行的权重和偏差。要使用它,请务必安装
`万德布`
和
`pip 安装wandb`
。
* `验证图像`
,
`验证提示`
, 和
`验证步骤`
允许脚本执行一些验证推理运行。这使我们能够定性地检查培训是否按预期进行。
我们的实验是在单个 40GB A100 GPU 上进行的。
###
推理
训练完成后,我们可以像这样进行推理:
```
from diffusers import StableDiffusionXLAdapterPipeline, T2IAdapter, EulerAncestralDiscreteSchedulerTest
from diffusers.utils import load_image
import torch
base_model_path = "stabilityai/stable-diffusion-xl-base-1.0"
adapter_path = "path to adapter"
adapter = T2IAdapter.from_pretrained(adapter_path, torch_dtype=torch.float16)
pipe = StableDiffusionXLAdapterPipeline.from_pretrained(
base_model_path, adapter=adapter, torch_dtype=torch.float16
)
# speed up diffusion process with faster scheduler and memory optimization
pipe.scheduler = EulerAncestralDiscreteSchedulerTest.from_config(pipe.scheduler.config)
# remove following line if xformers is not installed or when using Torch 2.0.
pipe.enable_xformers_memory_efficient_attention()
# memory optimization.
pipe.enable_model_cpu_offload()
control_image = load_image("./conditioning\_image\_1.png")
prompt = "pale golden rod circle with old lace background"
# generate image
generator = torch.manual_seed(0)
image = pipe(
prompt, num_inference_steps=20, generator=generator, image=control_image
).images[0]
image.save("./output.png")
```
## 笔记
###
指定更好的 VAE
众所周知,SDXL 的 VAE 存在数值不稳定问题。这就是为什么我们还公开一个 CLI 参数,即
`--pretrained_vae_model_name_or_path`
允许您指定更好的 VAE 的位置(例如
[这个](https://huggingface.co/madebyollin/sdxl-vae-fp16-fix)
)。 |
import React, { useState } from 'react';
function Contact() {
const [showForm, setShowForm] = useState(false);
const [hover, setHover] = useState(false);
const [formValues, setFormValues] = useState({
name: '',
email: '',
message: '',
});
const [formErrors, setFormErrors] = useState({
name: '',
email: '',
message: '',
});
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormValues({ ...formValues, [name]: value });
if (formErrors[name]) {
setFormErrors({ ...formErrors, [name]: '' });
}
};
const handleBlur = (e) => {
const { name, value } = e.target;
if (!value) {
setFormErrors({ ...formErrors, [name]: 'This field is required' });
} else {
setFormErrors({ ...formErrors, [name]: '' });
}
if (name === 'email' && value && !/\S+@\S+\.\S+/.test(value)) {
setFormErrors({ ...formErrors, [name]: 'Please enter a valid email address' });
}
};
const handleSubmit = (e) => {
e.preventDefault();
};
const toggleFormVisibility = () => {
setShowForm(!showForm);
};
const hoverStyle = {
cursor: 'pointer',
color: '#0077cc',
textDecoration: 'underline',
};
const defaultStyle = {
cursor: 'pointer',
color: 'blue',
textDecoration: 'underline',
};
return (
<section id="contact">
<h2
onClick={toggleFormVisibility}
onMouseEnter={() => setHover(true)}
onMouseLeave={() => setHover(false)}
style={hover ? hoverStyle : defaultStyle}
>
{showForm ? 'Hide Contact Form' : 'Contact Me'}
</h2>
{showForm && (
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
name="name"
required
autoComplete="name"
value={formValues.name}
onChange={handleInputChange}
onBlur={handleBlur}
/>
{formErrors.name && <div className="error">{formErrors.name}</div>}
</div>
<div className="form-group">
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
name="email"
required
autoComplete="email"
value={formValues.email}
onChange={handleInputChange}
onBlur={handleBlur}
/>
{formErrors.email && <div className="error">{formErrors.email}</div>}
</div>
<div className="form-group">
<label htmlFor="message">Message:</label>
<textarea
id="message"
name="message"
rows="4"
required
autoComplete="off"
value={formValues.message}
onChange={handleInputChange}
onBlur={handleBlur}
></textarea>
{formErrors.message && <div className="error">{formErrors.message}</div>}
</div>
<button type="submit">Send</button>
</form>
)}
</section>
);
}
export default Contact; |
import React from "react";
import PropTypes from "prop-types";
import TextInput from "components/TextInput";
import NumberInput from "components/NumberInput";
import OneOfInput from "components/OneOfInput";
import ActionButton from "components/ActionButton";
import { Formik, Form } from "formik";
import * as Yup from "yup";
import styled from "styled-components";
const GeneralSchema = Yup.object().shape({
area: Yup.number()
.min(1)
.max(1500)
.integer()
.truncate()
.required(),
rooms: Yup.number()
.min(1)
.max(40)
.integer()
.truncate()
.required(),
doors: Yup.number()
.min(1)
.max(80)
.integer()
.truncate()
.required(),
ceilHeight: Yup.mixed()
.oneOf([1, 2])
.required(),
address: Yup.string()
.min(1)
.max(200)
.trim()
.required()
});
const ButtonsBlock = styled.div`
display: flex;
justify-content: center;
:not(:last-child) {
margin-right: 10px;
}
`;
const CalculationFormGeneral = ({ initials, onSubmit: onFormSubmit }) => {
return (
<div>
<Formik
initialValues={{
area: 10,
rooms: 1,
doors: 2,
ceilHeight: 1,
address: "",
...initials
}}
validationSchema={GeneralSchema}
onSubmit={(values, actions) => {
onFormSubmit(values);
}}
>
{({ errors, touched }) => (
<Form>
<NumberInput
fieldName="area"
labelText="Площа квартири"
unitText={
<span>
м<sup>2</sup>
</span>
}
/>
<NumberInput
fieldName="rooms"
labelText="Кількість кімнат"
withButtons
/>
<NumberInput
fieldName="doors"
labelText="Кількість дверей"
withButtons
/>
<OneOfInput
fieldName="ceilHeight"
labelText="Висота стелі"
options={[
{ value: 1, name: "до 3 м" },
{ value: 2, name: "більше 3м" }
]}
/>
<TextInput fieldName="address" labelText="Адреса будинку" />
<ButtonsBlock>
<ActionButton
color="primary"
disabled={Object.values(errors).length > 0}
type="submit"
>
Продовжити
</ActionButton>
</ButtonsBlock>
</Form>
)}
</Formik>
</div>
);
};
CalculationFormGeneral.propTypes = {
onSubmit: PropTypes.func.isRequired,
initials: PropTypes.object.isRequired
};
export default CalculationFormGeneral; |
from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from user.models import UserModel
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = UserModel
fields = "__all__"
def create(self, validated_data):
user = super().create(validated_data)
password = user.password
user.set_password(password)
user.save()
return user
class UserEditSerializer(serializers.ModelSerializer):
class Meta:
model = UserModel
fields = ["password", "name", "gender", "age", "introduction"]
def update(self, instance, validated_data):
user = super().update(instance, validated_data)
password = user.password
user.set_password(password)
user.save()
return user
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
token = super().get_token(user)
token['email'] = user.email
token['name'] = user.name
token['gender'] = user.gender
token['age'] = user.age
return token |
var i18n = require("../");
var should = require('should'),
path = require("path"),
translationPath = path.join(__dirname, '../example/locale'),
middlewareOptions = {
default_lang: 'en-US',
supported_languages: ['en-US', 'en-CA'],
translation_directory: translationPath,
mappings: {
'en': 'en-US'
}
},
fs = require("fs");
var request = require('supertest'),
express = require('express');
var app = express();
describe("API Tests", function () {
before(function (done) {
app.use(i18n.middleware(middlewareOptions));
app.get('/', function(req, res) {
res.send(req.localeInfo);
});
app.get('/test', function(req, res) {
res.send(req.localeInfo);
});
app.get('/css/file.css', function(req, res) {
res.send(req.localeInfo);
});
app.get('/strings/en-US', i18n.stringsRoute());
done();
});
describe('GET /strings/en-US', function(){
it('should return object with status 200', function(done){
request(app)
.get('/strings/en-US')
.set('Accept', 'application/json')
.expect(function(res) {
res.body.should.be.an.instanceOf(Object)
.and.not.empty;
})
.expect(200, done);
})
})
describe('GET /', function(){
it('should return language en-US with status 200', function(done){
request(app)
.get('/')
.set('Accept', 'application/json')
.expect(function(res) {
res.body.lang.should.eql("en-US");
})
.expect(200, done);
})
})
describe('GET /en-US', function(){
it('should return language en-US with status 200', function(done){
request(app)
.get('/en-US')
.set('Accept', 'application/json')
.expect(function(res) {
res.body.lang.should.eql("en-US");
})
.expect(200, done);
})
})
describe('GET /en-CA', function(){
it('should return language en-CA with status 200', function(done){
request(app)
.get('/en-CA')
.set('Accept', 'application/json')
.expect(function(res) {
res.body.lang.should.eql("en-CA");
})
.expect(200, done);
})
})
describe('GET /en-CA/', function(){
it('should return language en-CA with status 200', function(done){
request(app)
.get('/en-CA')
.set('Accept', 'application/json')
.expect(function(res) {
res.body.lang.should.eql("en-CA");
})
.expect(200, done);
})
})
describe('GET /test/', function(){
it('should return language en-US with status 200', function(done){
request(app)
.get('/test/')
.set('Accept', 'application/json')
.expect(function(res) {
res.body.lang.should.eql("en-US");
})
.expect(200, done);
})
})
describe('GET /en-US/test/', function(){
it('should return language en-US with status 200', function(done){
request(app)
.get('/en-US/test/')
.set('Accept', 'application/json')
.expect(function(res) {
res.body.lang.should.eql("en-US");
})
.expect(200, done);
})
})
describe('GET /en-CA/test/', function(){
it('should return language en-CA with status 200', function(done){
request(app)
.get('/en-CA/test/')
.set('Accept', 'application/json')
.expect(function(res) {
res.body.lang.should.eql("en-CA");
})
.expect(200, done);
})
})
describe('GET /en-CA/test', function(){
it('should return language en-CA with status 200', function(done){
request(app)
.get('/en-CA/test')
.set('Accept', 'application/json')
.expect(function(res) {
res.body.lang.should.eql("en-CA");
})
.expect(200, done);
})
})
describe('GET /css/file.css', function(){
it('should return language en-US with status 200', function(done){
request(app)
.get('/css/file.css')
.set('Accept', 'application/json')
.expect(function(res) {
res.body.lang.should.eql("en-US");
})
.expect(200, done);
})
})
describe('GET /en-CA/css/file.css', function(){
it('should return language en-US with status 200', function(done){
request(app)
.get('/en-CA/css/file.css')
.set('Accept', 'application/json')
.expect(function(res) {
res.body.lang.should.eql("en-CA");
})
.expect(200, done);
})
})
it("getStrings() should return translated object for the specified languages", function () {
should(function () {
i18n.getStrings('en-CA').should.be.an.instanceOf(Object)
.and.not.empty;
}).not.throw();
});
it("getLocales() should return list of locales in array format", function () {
should(function () {
i18n.getLocales().should.be.an.instanceOf(Array)
.and.include('en_US', 'en')
.and.not.include('en-US');
}).not.throw();
});
it("getLanguages() should return list of languages in array format", function () {
should(function () {
i18n.getLanguages().should.be.an.instanceOf(Array)
.and.include('en-US', 'en')
.and.not.include('en_US');
}).not.throw();
});
it("getSupportLanguages() should list of languages in an array format based on the lang-Countries", function () {
should(function () {
i18n.getSupportLanguages().should.be.an.instanceOf(Array)
.and.include('en-US')
.and.not.include('en');
}).not.throw();
});
it("Named: format('%(a)s %(b)s', {a: 'Hello', b: 'World'}) without boolean set and should return 'Hello World'", function () {
should(function () {
i18n.format('%(a)s %(b)s', {
a: 'Hello',
b: 'World'
})
.should.eql("Hello World");
}).not.throw();
});
it("Named: format('%(a)s %(b)s', {a: 'Hello', b: 'World'}, true) with boolean set and should return 'Hello World'", function () {
should(function () {
i18n.format('%(a)s %(b)s', {
a: 'Hello',
b: 'World'
}, true)
.should.eql("Hello World");
}).not.throw();
});
it("Positional: format('%s %s', ['Hello', 'World']) should return 'Hello World'", function () {
should(function () {
i18n.format("%s %s", ["Hello", "World"])
.should.eql("Hello World");
}).not.throw();
});
it("languageFrom() should return language code en_US => en-US", function () {
should(function () {
i18n.languageFrom('en_US').should.eql('en-US');
}).not.throw();
});
it("localeFrom() should return locale code en-US => en_US", function () {
should(function () {
i18n.localeFrom('en-US').should.eql('en_US');
}).not.throw();
});
it("localeFrom() should return locale code en_US => en_US", function () {
should(function () {
i18n.localeFrom('en_US').should.eql('en_US');
}).not.throw();
});
it("i18n.gettext('_Hello_World_', 'en_US') should return Hello World", function () {
should(function () {
i18n.gettext('_Hello_World_', 'en_US').should.eql('Hello World');
}).not.throw();
});
it("i18n.gettext('_Hello_World_', 'en-US') should return Hello World", function () {
should(function () {
i18n.gettext('_Hello_World_', 'en-US').should.eql('Hello World');
}).not.throw();
});
it("i18n.gettext('_Hello_', 'en-US') should return _Hello_", function () {
should(function () {
i18n.gettext('_Hello_', 'en-US').should.eql('_Hello_');
}).not.throw();
});
it("languageNameFor('en-US') and languageNameFor('th-TH') should return native language name", function () {
should(function () {
i18n.languageNameFor('en-US').should.eql('English (US)');
i18n.languageNameFor('th-TH').should.eql('ภาษาไทย (ประเทศไทย)');
}).not.throw();
});
it("languageEnglishName('en-US') and languageEnglishName('th-TH') should return English language name", function () {
should(function () {
i18n.languageEnglishName('en-US').should.eql('English (US)');
i18n.languageEnglishName('th-TH').should.eql('Thai (Thailand)');
}).not.throw();
});
it("langToMomentJSLang('en-US') and langToMomentJSLang('th-TH') should return moment language code 'en-US' => 'en'", function () {
should(function () {
i18n.langToMomentJSLang('en-US').should.eql('en');
i18n.langToMomentJSLang('th-TH').should.eql('th');
}).not.throw();
});
it("addLocaleObject({ 'en-US': { keys:'somevalue'}}, cb)", function () {
should(function () {
i18n.addLocaleObject({'en-US': { "myName": "Ali Al Dallal"}}, function(err, res) {
if(res) {
i18n.getStrings("en-US").should.have.property('myName');
}
});
}).not.throw();
});
it("getOtherLangPrefs([ { lang: 'th', quality: 1 }, { lang: 'en', quality: 0.8 }, { lang: 'es', quality: 0.6 } ]) should return ['en', 'es']", function () {
should(function () {
i18n.getOtherLangPrefs([ { lang: 'th', quality: 1 }, { lang: 'en', quality: 0.8 }, { lang: 'es', quality: 0.6 } ]).should.eql(['en', 'es']);
}).not.throw();
});
it("getAlternateLangSupport(['th', 'en-CA', 'es', 'fr', 'ar'], ['en-US', 'en-CA', 'th']) should return ['th', 'en-CA']", function () {
should(function () {
i18n.getAlternateLangSupport(['th', 'en-CA', 'es', 'fr', 'ar'], ['en-US', 'en-CA', 'th']).should.eql(['th', 'en-CA']);
}).not.throw();
});
it("getAllLocaleCodes() should return object list of all known locales", function () {
should(function () {
i18n.getAllLocaleCodes().should.be.an.instanceof(Object).and.not.empty;
}).not.throw();
});
it("readLangDir(pathToDir, langList) should return a clean list of supported_languages", function () {
should(function () {
var list = ['en_US', 'en_CA', '.DS_Store'];
var pathToDir = path.join(__dirname, "../example/locale");
var pathToDsStore = path.join(pathToDir, '.DS_Store');
fs.writeFile(pathToDsStore, "something", 'utf-8', function () {
list = i18n.readLangDir(pathToDir, list);
list.should.eql(['en-US', 'en-CA']);
fs.unlinkSync(pathToDsStore);
});
}).not.throw();
});
// strict vs. non-strict testing
(function() {
var sid = "key/with/empty/string";
it("i18n.gettext('"+sid+"', 'en_US' ) should return '"+sid+"'", function () {
should(function () {
i18n.gettext(sid, 'en_US').should.eql(sid);
}).not.throw();
});
it("i18n.gettext('"+sid+"', 'en_US', { strict: true }) should return an empty string", function () {
should(function () {
i18n.gettext(sid, 'en_US', { strict: true }).should.eql("");
}).not.throw();
});
}());
}); |
import { connect } from 'react-redux';
import React, { Component } from 'react';
import { reduxForm } from 'redux-form';
import { AuthInput } from './';
import { signUpUser } from './AuthActions';
// components
import { Button, RenderAlert, Loader } from '../common';
class SignUpForm extends Component {
constructor(props) {
super(props);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
}
handleFormSubmit({ username, password }) {
this.props.signUpUser(username, password);
}
render() {
const { handleSubmit, error, loading } = this.props;
return (
<div>
{loading ?
<Loader /> :
<form onSubmit={handleSubmit(this.handleFormSubmit)}>
<AuthInput
name="username"
type="text"
label="email address"
placeholder="Enter Email Address"
/>
<AuthInput
name="password"
type="password"
label="password"
placeholder="Create Password"
/>
<Button classOverrides="w-100" backgroundColor="brandPrimary">Sign Up</Button>
<RenderAlert error={error} />
</form>
}
</div>
);
}
}
function validate(values) {
const errors = {};
if (!values.username) {
errors.username = '*required';
}
if (!values.password) {
errors.password = '*required';
}
return errors;
}
const mapStateToProps = ({ AuthReducer }) => {
const { error, authenticated, loading } = AuthReducer;
return {
error,
authenticated,
loading
};
};
export default reduxForm({ form: 'signup', validate })(connect(mapStateToProps, {
signUpUser
})(SignUpForm)); |
<!DOCTYPE html>
<html>
<head>
{% load static %}
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" />
<link rel="stylesheet" type="text/css" href="{% static "css/yonetmen_page.css" %}">
<link rel="stylesheet" type="text/css" href="{% static "css/deneme.css" %}">
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<title>{{person.yonetmen_ad}}</title>
</head>
<body>
<section class="header_section">
<div class="header_main_container">
<div class="header">
<div class="header_left">
<div class="menu_bar"><img src="{% static "img/bars-solid.svg" %}"></div>
<div class="logo_div">
<a href="/home"><img src="{% static "img/moviroma_logo.svg" %}"></a>
</div>
</div>
<div class="header_middle">
<div class="searchbox_div">
<form method='GET' action={% url 'search' %}>
<input type="text" id="fname" name="q" placeholder="Ara">
<button class="search_button" value="{{ query|escape }}" type="submit"><a href="#"><img src="{% static "img/search-solid.svg" %}"></a></button>
</form>
</div>
<!-- <div class="searchbox_div">
<form method='GET' autocomplete="off" action={% url 'search' %}>
<div class="autocomplete" style="width:300px;">
<input type="text" id="fname" name="q" placeholder="Ara">
</div>
<button class="search_button" value="{{ query|escape }}" type="button"><a href="#"><img src="{% static "img/search-solid.svg" %}"></a></button>
</form>
</div> -->
<ul>
{% for item in searchedperson %}
<li><a href="{% url 'directorview' id=item.pk %}" style="color: white;">{{ item.yonetmen_ad }}</a></li>
{% endfor %}
</ul>
</div>
<div class="header_right">
<div class="user_menu">
<div class="dropdown">
<button class="dropbtn" type="submit" style="border: 0; background: transparent">
<img src="{% static "img/user_default_icon.svg" %}" width="30" height="30" alt="submit" />
</button>
<div class="dropdown-content">
<a href="/users/{{currentuser.id}}" >Profile</a>
<a href="#">Settings</a>
<a href="/logout">Logout</a>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="content_section">
<div style="background-image: url('http://image.tmdb.org/t/p/original{{latestmovie.film_backdrop_linki}}');"class="director_top_main">
<div class="director_pp">
<img src="http://image.tmdb.org/t/p/original{{person.yonetmen_pp_linki}}">
</div>
<div class="director_verified">
<h5>DIRECTOR</h5>
</div>
<div class="director_name">
<h4>{{person.yonetmen_ad}}</h4>
</div>
<div class="director_buttons">
{% if person.yonetmen_ad in likeddirectors %}
<button class="button_blue"><a href="/directors/ud/{{person.yonetmen_tmdb_id}}"><img src="{% static "img/like-red.svg" %}"></a></button>
{% else %}
<button class="button_blue"><a href="/directors/ld/{{person.yonetmen_tmdb_id}}"><img src="{% static "img/add_fav_icon.svg" %}"></a></button>
{% endif %}
<button class="button_blue"><a href="#"><img src="{% static "img/more_icon.svg" %}"></a></button>
</div>
</div>
<div class="director_submenu">
<ul>
<li><a class="submenu_selected" href="#">Overview</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Fans also like</a></li>
<li><a href="#">Vision</a></li>
</ul>
</div>
<div class="director_main_content">
<div class="main_content_top_left">
<h2>Popular</h2>
<div class="director_popular_film_main">
</br>
{% for item in movies %}
<div class="director_popular_film_component">
<div class="popular_film_compenent_1"><img src="http://image.tmdb.org/t/p/original{{item.film_poster_linki}}"></div>
<div class="popular_film_compenent_2"><h6>{{ forloop.counter }}</h6></div>
{% if item.film_title in likedmovies %}
<div class="popular_film_compenent_3"><a href="{% url 'unlikemovie' id=person.pk id1=item.film_tmdb_id %}"><img src="{% static "img/like-red.svg" %}"></a></div>
{% else %}
<div class="popular_film_compenent_3"><a href="{% url 'likemovie' id=person.pk id1=item.film_tmdb_id %}"><img src="{% static "img/add_fav_icon.svg" %}"></a></div>
{% endif %}
<div class="popular_film_compenent_4"><a href="{% url 'movieview' id=item.film_tmdb_id %}">{{item.film_title}}</a></div>
<div class="popular_film_compenent_5">{{item.film_tmdb_rating}}</div>
</div>
{% endfor %}
</div>
<div class="popular_film_button_div">
<form>
<button class="popular_film_button"><a href="#">Show more film</a></button>
</form>
</div>
</div>
<div class="main_content_top_right">
<div class="latest_from_artist">
<div class="latest_from_artist_1"><h2>LATEST FROM ARTIST</h2></div>
<div class="latest_from_artist_2"><a href="/movies/{{latestmovie.film_tmdb_id}}"><img src="http://image.tmdb.org/t/p/original{{latestmovie.film_poster_linki}}"></a></div>
<div class="latest_from_artist_3"><a href="/movies/{{latestmovie.film_tmdb_id}}"><h3>{{latestmovie.film_title}}</h3></a></div>
<div class="latest_from_artist_4"><h4>{{latestmovie.film_yayinlanma_tarihi}}</h4></div>
</div>
</div>
<div class="main_content_bottom">
<div class="filmography_main">
<h2>Filmography</h2>
{% for item in movies %}
<div class="filmography_component">
<div class="fcomponent_left"><a href="{% url 'movieview' id=item.film_tmdb_id %}"><img src="http://image.tmdb.org/t/p/original{{item.film_poster_linki}}"></a></div>
<div class="fcomponent_right">
<div class="fcomponent_right_1"><a href="{% url 'movieview' id=item.film_tmdb_id %}">{{item.film_title}}</a></div>
<div class="fcomponent_right_2">{{item.film_aciklamasi}}
</div>
<div class="fcomponent_right_3">
{% if item.film_title in likedmovies %}
<div class="fcomponent_right_bottom_1"><button class="button_blue"><a href="{% url 'unlikemovie' id=person.pk id1=item.film_tmdb_id %}"><img src="{% static "img/like-red.svg" %}"></a></button></div>
{% else %}
<div class="fcomponent_right_bottom_1"><button class="button_blue"><a href="{% url 'likemovie' id=person.pk id1=item.film_tmdb_id %}"><img src="{% static "img/add_fav_icon.svg" %}"></a></button></div>
{% endif %}
<div class="fcomponent_right_bottom_2"><button class="button_blue"><a href="#"><img src="{% static "img/more_icon.svg" %}"></a></button></div>
<div class="fcomponent_right_bottom_3"><button class="button_blue_large">
<a href="#">{{item.film_suresi}} minute</a>
</button></div>
<div class="fcomponent_right_bottom_4"><button class="button_blue_large2">
<a href="">Community Rating: {{item.film_tmdb_rating}}</a>
</button></div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</section>
</body>
</html> |
Blurb::
The \c sub_method_pointer specifies the method block for the sub-iterator
Description::
The \c sub_method_pointer specifies the method block for the sub-iterator.
See \ref topic-block_pointer for details about pointers.
Nested models may employ mappings for both the variable inputs to the
sub-model and the response outputs from the sub-model. In the former
case, the \c primary_variable_mapping and \c
secondary_variable_mapping specifications are used to map from the
active top-level variables into the sub-model variables, and in the
latter case, the \c primary_response_mapping and \c
secondary_response_mapping specifications are used to compute the
sub-model response contributions to the top-level responses.
For the variable mappings, the primary and secondary specifications
provide lists of strings which are used to target specific sub-model
variables and their sub-parameters, respectively. The primary strings
are matched to continuous or discrete variable labels such as \c
'cdv_1' (either user-supplied or default labels), and the secondary
strings are matched to either real or integer random variable
distribution parameters such as \c 'mean' or \c 'num_trials' (the form
of the uncertain distribution parameter keyword that is appropriate
for a single variable instance) or continuous or discrete design/state
variable sub-parameters such as \c 'lower_bound' or \c 'upper_bound'
(again, keyword form appropriate for a single variable instance). No
coercion of types is supported, so real-valued top-level variables
should map to either real-valued sub-model variables or real-valued
sub-parameters and integer-valued top-level variables should map to
either integer-valued sub-model variables or integer-valued
sub-parameters. As long as these real versus integer constraints are
satisfied, mappings are free to cross variable types (design, aleatory
uncertain, epistemic uncertain, state) and domain types (continuous,
discrete). Both \c primary_variable_mapping and \c
secondary_variable_mapping specifications are optional, which is
designed to support the following three possibilities:
-# If both primary and secondary variable mappings are specified,
then an active top-level variable value will be inserted into the
identified sub-parameter (the secondary mapping) for the identified
sub-model variable (the primary mapping).
-# If a primary mapping is specified but a secondary mapping is not,
then an active top-level variable value will be inserted into the
identified sub-model variable value (the primary mapping).
-# If a primary mapping is not specified (corresponding secondary
mappings, if specified, are ignored), then an active top-level
variable value will be inserted into a corresponding sub-model
variable, based on matching of variable types (e.g., top-level
and sub-model variable specifications both allocate a set of \c
'continuous_design' variables which are active at the top level).
Multiple sub-model variable types may be updated in this manner,
provided that they are all active in the top-level variables.
Since there is a direct variable correspondence for these default
insertions, sub-model bounds and labels are also updated from the
top-level bounds and labels in order to eliminate the need for
redundant input file specifications. Thus, it is typical for the
sub-model variables specification to only contain the minimal
required information, such as the number of variables, for these
insertion targets. The sub-model must allocate enough space for
each of the types that will accept default insertions, and the
leading set of matching sub-model variables are updated (i.e., the
sub-model may allocate more than needed and the trailing set will
be unmodified).
These different variable mapping possibilities may be used in any
combination by employing empty strings (\c '') for particular omitted
mappings (the number of strings in user-supplied primary and secondary
variable mapping specifications must equal the total number of active
top-level variables, including both continuous and discrete types).
The ordering of the active variables is the same as shown in
dakota.input.summary on \ref input_spec_summary and as presented in \ref variables.
If inactive variables are present at the outer level, then the default
type 3 mapping is used for these variables; that is, outer loop
inactive variables are inserted into inner loop variables (active or
inactive) based on matching of variable types, top-level bounds and
labels are also propagated, the inner loop must allocate sufficient
space to receive the outer loop values, and the leading subset within
this inner loop allocation is updated. This capability is important
for allowing nesting beyond two levels, since an active variable at the
outer-most loop may become inactive at the next lower level, but still
needs to be further propagated down to lower levels in the recursion.
For the response mappings, the primary and secondary specifications
provide real-valued multipliers to be applied to sub-iterator response
results so that the responses from the inner loop can be mapped into a
new set of responses at the outer loop. For example, if the nested
model is being employed within a mixed aleatory-epistemic uncertainty
quantification, then aleatory statistics from the inner loop (such as
moments of the response) are mapped to the outer level, where minima
and maxima of these aleatory statistics are computed as functions of
the epistemic parameters. The response mapping defines a matrix which
scales the values from the inner loop and determines their position in
the outer loop response vector. Each row of the mapping corresponds
to one outer loop response, where each column of the mapping
corresponds to a value from the inner loop. Depending on the number
of responses and the particular attributes calculated on the inner
loop, there will be a vector of inner loop response values that need
to be accounted for in the mapping. This vector of inner loop
response results is defined as follows for different sub-iterator types:
- optimization: the final objective function(s) and nonlinear constraints
- nonlinear least squares: the final least squares terms and nonlinear
constraints
- aleatory uncertainty quantification (UQ): for each response function, a mean
statistic, a standard deviation statistic, and all
probability/reliability/generalized reliability/response level results
for any user-specified \c response_levels, \c probability_levels,
\c reliability_levels, and/or \c gen_reliability_levels, in that order.
- epistemic and mixed aleatory/epistemic UQ using interval estimation
methods: lower and upper interval bounds for each response function.
- epistemic and mixed aleatory/epistemic UQ using evidence methods: for
each response function, lower and upper interval bounds (belief and
plausibility) for all probability/reliability/generalized
reliability/response level results computed from any user-specified \c
response_levels, \c probability_levels, \c reliability_levels, and/or
\c gen_reliability_levels, in that order.
- parameter studies and design of experiments: for optimization and
least squares response data sets, the best solution found (lowest
constraint violation if infeasible, lowest composite objective function
if feasible). For generic response data sets, a best solution metric is
not defined, so the sub-iterator response vector is empty in this case.
The primary values map sub-iterator response results into top-level
objective functions, least squares terms, or generic response
functions, depending on the declared top-level response set. The
secondary values map sub-iterator response results into top-level
nonlinear inequality and equality constraints.
Nested models utilize a sub-iterator and a sub-model to perform a
complete iterative study as part of every evaluation of the model.
This sub-iteration accepts variables from the outer level, performs
the sub-level analysis, and computes a set of sub-level responses
which are passed back up to the outer level.
Mappings are
employed for both the variable inputs to the sub-model and the
response outputs from the sub-model.
In the variable mapping case, primary and secondary variable
mapping specifications are used to map from the top-level variables
into the sub-model variables. These mappings support three
possibilities in any combination: (1) insertion of an active top-level
variable value into an identified sub-model distribution parameter for
an identified active sub-model variable, (2) insertion of an active
top-level variable value into an identified active sub-model variable
value, and (3) addition of an active top-level variable value as an
inactive sub-model variable, augmenting the active sub-model
variables.
In the response mapping case, primary and secondary response
mapping specifications are used to map from the sub-model responses
back to the top-level responses. These specifications provide
real-valued multipliers that are applied to the sub-iterator response
results to define the outer level response set. These nested data
results may be combined with non-nested data through use of the
"optional interface" component within nested models.
The nested model constructs admit a wide variety of multi-iterator,
multi-model solution approaches. For example, optimization within
optimization (for hierarchical multidisciplinary optimization),
uncertainty quantification within uncertainty quantification (for
second-order probability), uncertainty quantification within
optimization (for optimization under uncertainty), and optimization
within uncertainty quantification (for uncertainty of optima) are all
supported, with and without surrogate model indirection. Several
examples of nested model usage are provided in
the Users Manual, most notably mixed epistemic-aleatory UQ,
optimization under uncertainty
(OUU), and surrogate-based UQ.
Topics:: block_pointer
Examples::
Theory::
Faq::
See_Also:: |
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AntaresController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\LahanController;
use App\Http\Controllers\PenanamanController;
use App\Http\Controllers\DeviceController;
use App\Http\Controllers\Email\MailController;
use App\Http\Controllers\TanamanController;
use App\Http\Controllers\SensorController;
use App\Http\Controllers\MachineLearningController;
use App\Http\Controllers\PengairanController;
use App\Http\Controllers\PemupukanController;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
return response()->json(["message" => "hello world"]);
});
Route::group([
'prefix' => 'antares',
'as' => 'antares.'
], function () {
Route::group([
'prefix' => 'webhook',
'as' => 'webhook.'
], function () {
Route::post('test_cameras', [AntaresController::class, 'handleAntaresCamera'])->name('camera');
Route::post('testing_sensors', [AntaresController::class, 'handleAntaresSensor'])->name('sensor');
});
Route::post('downlink', [AntaresController::class, 'handleAntaresDownlink'])->name('downlink');
});
Route::group([
'prefix' => 'ml',
'as' => 'ml.'
], function () {
Route::post('fertilizer', [MachineLearningController::class, 'fertilizer'])->name('fertilizer');
Route::post('irrigation', [MachineLearningController::class, 'irrigation'])->name('irrigation');
Route::post('predict', [MachineLearningController::class, 'predict'])->name('predict');
});
Route::middleware('guest')->group(function () {
Route::group([
'prefix' => 'auth',
], function () {
Route::post('login', [AuthController::class, 'login']);
Route::post('register', [AuthController::class, 'register']);
});
Route::group([
'prefix' => 'user',
], function () {
Route::post('forget-password', [MailController::class, 'send_otp_password']);
Route::post('reset-password', [UserController::class, 'reset_password']);
Route::put('update-password', [UserController::class, 'update_password']);
});
});
Route::middleware('jwt.verify')->group(function () {
Route::group(['prefix' => 'fertilizer'], function () {
Route::get('data', [PemupukanController::class, 'get_data']);
Route::post('input');
Route::group([
'prefix' => 'sop',
'as' => 'sop.'
], function () {
Route::get('data', [PemupukanController::class, 'get_sop']);
Route::post('input', [PemupukanController::class, 'input_sop']);
});
});
Route::group(['prefix' => 'irrigation'], function () {
Route::get('data', [PengairanController::class, 'get_data']);
Route::post('input', [PengairanController::class, 'input_manual']);
Route::group([
'prefix' => 'sop',
'as' => 'sop.'
], function () {
Route::get('data', [PengairanController::class, 'get_sop']);
Route::post('input', [PengairanController::class, 'input_sop']);
});
});
Route::group(['prefix' => 'sensor'], function () {
Route::get('data', [SensorController::class, 'get_sensor']);
Route::get('data/latest', [SensorController::class, 'get_latest_sensor']);
});
Route::group(['prefix' => 'device'], function () {
Route::get('data', [DeviceController::class, 'get_device']);
Route::post('input', [DeviceController::class, 'add_device']);
});
Route::group(['prefix' => 'plant'], function () {
Route::get('data', [TanamanController::class, 'get_plant']);
});
Route::group(['prefix' => 'penanaman'], function () {
Route::get('data', [PenanamanController::class, 'get_penanaman']); // get data penanaman by user id
Route::get('tinggi', [PenanamanController::class, 'get_tinggi']); // get data tinggi
Route::post('input', [PenanamanController::class, 'input_penanaman']); // tambah data penanaman
Route::put('tinggi', [PenanamanController::class, 'update_tinggi']); // input manual atau update data penanaman
Route::put('update', [PenanamanController::class, 'update_penanaman']);
Route::delete('delete', [PenanamanController::class, 'delete_penanaman']);
});
Route::group(['prefix' => 'lahan'], function () {
Route::get('data', [LahanController::class, 'get_lahan']); // get data lahan by user id
Route::post('input', [LahanController::class, 'input_lahan']); // tambah data lahan
Route::put('update', [LahanController::class, 'update_lahan']); // update data lahan
Route::delete('delete', [LahanController::class, 'delete_lahan']); // delete data lahan
});
Route::post('/auth/refresh-token', [AuthController::class, 'refresh']);
Route::post('/auth/logout', [AuthController::class, 'logout']);
}); |
package utils
import (
"encoding/json"
"errors"
"github.com/labstack/gommon/log"
"io"
"os"
"simple_text_editor/core/v3/types"
"simple_text_editor/core/v3/validators"
)
func ForEach[T interface{}](slice []T, callback func(index int, data *T)) {
if slice == nil {
return
}
for i, value := range slice {
currVal := value
callback(i, &currVal)
}
}
func FindInSlice[T interface{}](slice []T, compare func(value T) bool) (index int) {
if slice == nil {
return -1
}
for i, value := range slice {
if compare(value) {
return i
}
}
return -1
}
func ReadFileTypesJson(path string) ([]types.FileTypesJsonStruct, error) {
if validators.IsEmptyString(path) {
return nil, errors.New("path to file types config json is empty")
}
jsonFile, openFileErr := os.Open(path)
if validators.HasError(openFileErr) {
return nil, openFileErr
}
defer func(jsonFile *os.File) {
closeErr := jsonFile.Close()
if validators.HasError(closeErr) {
log.Error("Error in closing file: ", closeErr)
}
}(jsonFile)
byteValue, _ := io.ReadAll(jsonFile)
var typesJsons []types.FileTypesJsonStruct
unmarshalErr := json.Unmarshal(byteValue, &typesJsons)
if validators.HasError(unmarshalErr) {
return nil, unmarshalErr
}
return typesJsons, nil
}
func MapFileTypesJsonStructToTypesMap(fileTypes []types.FileTypesJsonStruct) (types.TypesMap, error) {
if validators.IsNilOrEmptySlice(fileTypes) {
return nil, errors.New("fileTypes is empty slice, can't build map")
}
typesMap := make(types.TypesMap, len(fileTypes))
for _, fileType := range fileTypes {
fileType := fileType
typesMap[fileType.Key] = &fileType
}
return typesMap, nil
} |
import Center from "./Center";
import Sass from "./Sass";
import Less from "./Less";
// images
import box from "../../images/box_model.png";
import css from "../../images/code_css.png";
import flex from "../../images/flex.png";
import grid from "../../images/grid.png";
export default function Css() {
return (
<>
<div className="info">
<h1>CSS</h1>
<p>Selector - selects all HTML elements</p>
<ul>
<li>class, id, div, p</li>
</ul>
<h2>Setting up CSS</h2>
<h3>Box Model</h3>
<p>
The box model is a box that wraps around each HTML elment. Starting
from outer layer to inner, it includes:
</p>
<ul>
<li>Margin</li>
<li>Border</li>
<li>Padding</li>
<li>Content</li>
</ul>
<div className="box-info">
<img src={box} alt="box" />
<h3>Box Model in CSS Stylesheet</h3>
<img src={css} alt="css" />
</div>
<div className="response-info">
<h2>Responsive Design</h2>
<h3>Flex</h3>
<p>
Flex is designed for one-dimensional layout. It will display the
contents in a row.
</p>
<img src={flex} alt="" />
<h3>Grid</h3>
<p>
Grid is designed for two-dimensional layout. It will display the
contents based on how the columns and rows are divided.
</p>
<img src={grid} alt="" />
<Center />
<Sass />
<Less />
</div>
</div>
<script src="main.js"></script>
</>
);
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP form</title>
</head>
<body>
<h2>Contact Form</h2>
<form method="POST" action="">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br><br>
<label for="phonenumber">Phone Number:</label><br>
<input type="tel" id="phonenumber" name="phonenumber" pattern="[0-9]{10}" required><br><br>
<input type="submit" name="submit" value="Submit"><br>
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully to database $dbname";
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phonenumber'];
if (!preg_match("/^\S+@\S+\.\S+$/", $email)) {
echo "Invalid email format.";
exit;
}
$stmt = $conn->prepare("INSERT INTO contacts (name, email, phonenumber) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $email, $phone);
if ($stmt->execute()) {
echo "<br>Record inserted successfully!";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
$conn->close();
}
?> |
part of core.auth;
typedef JwtString = String;
enum JWTAlgo {
hs256,
}
/// A schema for a JWTObject. Extend this base class to create new versions.
abstract class JWTObject {}
class JWTObjectV1 implements JSONObject {
final JWTAlgo jwtAlgo;
final String typ = 'jwt';
/// User ID
final String sub;
final DateTime iat;
final DateTime exp;
final Set<Permission> permissions;
const JWTObjectV1({
required this.jwtAlgo,
required this.sub,
required this.iat,
required this.exp,
required this.permissions,
});
JSON get headerJson => {
'jwtAlgo': jwtAlgo.name,
'typ': typ,
};
JSON get payloadJson => {
'sub': sub,
'iat': iat.secondsSinceEpoch,
'exp': exp.secondsSinceEpoch,
'perms': permissions,
};
/// Not fully implemented yet (need to pick an algorithm)
String get signature {
return HttpUtils.encodeToBase64Url(jsonEncode(headerJson)) +
HttpUtils.encodeToBase64Url(jsonEncode(payloadJson)) +
secret;
}
JwtString get jwtString {
return "${HttpUtils.encodeToBase64Url(jsonEncode(headerJson))}.${HttpUtils.encodeToBase64Url(jsonEncode(payloadJson))}.$signature";
}
/// Not actually used, just for debugging
@override
Map toJson() {
return {
'header': headerJson,
'payload': payloadJson,
'signature': signature,
};
}
} |
// Print all the paths from leaf to root node
// Use Preorder traversal + Stack Reverse
package BinaryTree.Questions;
import java.util.*;
class Leaf_to_Root
{
static Node root;
static class Node
{
int data;
Node left, right;
Node(int data)
{
this.data = data;
left = right = null;
}
}
/* Creating the BT */
void create()
{
Node first = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
Node fourth = new Node(4);
Node fifth = new Node(5);
Node sixth = new Node(6);
Node seventh = new Node(7);
root = first;
first.left = second;
first.right = third;
second.left = fourth;
second.right = fifth;
third.left = sixth;
third.right = seventh;
}
/* Printing the BT */
void print()
{
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty())
{
Node temp = q.remove();
System.out.print(temp.data + " ");
if (temp.left != null) {
q.add(temp.left);
}
if (temp.right != null) {
q.add(temp.right);
}
}
}
/* Function to print the path from leaves to root node */
//Initializing a Stack
Stack<Integer> s = new Stack<>();
void LeafToRoot(Node temp)
{
if (temp == null) {
return;
}
//Pushing the current node in stack
s.push(temp.data);
//Printing the path if leaf node is encountered
if (temp.left == null && temp.right == null)
{
//Copying the items in a temporary stack
Stack<Integer> t = new Stack<>();
t.addAll(s);
//Printing the nodes in reverse order
while (!t.isEmpty())
{
System.out.print(t.pop() + " ");
}
System.out.println();
}
LeafToRoot(temp.left);
LeafToRoot(temp.right);
//Popping the leaf node
s.pop();
}
public static void main(String args[])
{
//Creating object of the class
Leaf_to_Root t = new Leaf_to_Root();
//Creating the BT
t.create();
//Printing the BT
System.out.println("*** Created Binary Tree ***");
t.print();
//Printing leaf to root path
System.out.println("\nLeaves to Root path : ");
t.LeafToRoot(root);
}
} |
import * as AST from "./ast"
interface TextStream {
readonly fullText: string
readonly position: number
}
function streamNext(s: TextStream): [string, TextStream] {
return [
s.fullText[s.position],
{ fullText: s.fullText, position: s.position + 1 },
]
}
function remainingText(s: TextStream): string {
return s.fullText.slice(s.position)
}
export interface ParserOk<A> {
readonly ok: true
readonly rest: TextStream
readonly val: A
}
export interface ParserErr {
readonly ok: false
}
export type ParserResult<A> = ParserOk<A> | ParserErr
type Parser<A> = (s: TextStream) => ParserResult<A>
function ok<A>(rest: TextStream, val: A): ParserOk<A> {
return { ok: true, rest, val }
}
const err: ParserErr = { ok: false }
function pList0<A>(p: Parser<A>): Parser<readonly A[]> {
return (s) => {
const arr: A[] = []
while (true) {
const res = p(s)
if (res.ok) {
s = res.rest
arr.push(res.val)
} else {
return ok(s, arr)
}
}
}
}
function pList1<A>(p: Parser<A>): Parser<readonly A[]> {
return (s) => {
const res = pList0(p)(s)
if (res.ok && res.val.length > 0) {
return res
}
return err
}
}
function pMap<A, B>(p: Parser<A>, f: (x: A) => B): Parser<B> {
return (s) => {
const res = p(s)
if (res.ok) {
return ok(res.rest, f(res.val))
}
return err
}
}
function pAllowOnly<A>(p: Parser<A>, f: (x: A) => boolean): Parser<A> {
return (s) => {
const res = p(s)
if (res.ok && f(res.val)) {
return res
}
return err
}
}
function pOneOf<A>(ps: readonly Parser<A>[]): Parser<A> {
return (s) => {
for (const p of ps) {
const res = p(s)
if (res.ok) {
return res
}
}
return err
}
}
function pSucceed<A>(v: A): Parser<A> {
return (s) => ok(s, v)
}
const pAny: Parser<string> = (s) => {
const [x, rest] = streamNext(s)
if (x != "") {
return ok(rest, x)
}
return err
}
const pDigit: Parser<number> = pMap(
pAllowOnly(pAny, (x) => /^\d$/.test(x)),
Number,
)
const pChar: Parser<string> = pAllowOnly(pAny, (x) => /^[a-z_]$/.test(x))
const pSpace: Parser<string> = pAllowOnly(pAny, (x) => /^[ \t\n\r]$/.test(x))
function pReplace<A>(val: A, p: Parser<unknown>): Parser<A> {
return (s) => {
const res = p(s)
if (res.ok) {
return ok(res.rest, val)
}
return err
}
}
function pIgnore(p: Parser<unknown>): Parser<null> {
return pReplace(null, p)
}
function pExact<A extends string>(tag: A): Parser<A> {
return (s) => {
let rest = s
for (let i = 0; i < tag.length; i++) {
const [x, nextRest] = streamNext(rest)
if (x !== tag[i]) {
return err
}
rest = nextRest
}
return ok(rest, tag)
}
}
function pPrint<A>(tag: string, p: Parser<A>): Parser<A> {
return (s) => {
const r = p(s)
console.log(tag, r, remainingText(s))
return r
}
}
function pSeq<A>(ps: readonly [Parser<A>]): Parser<readonly [A]>
function pSeq<A, B>(
ps: readonly [Parser<A>, Parser<B>],
): Parser<readonly [A, B]>
function pSeq<A, B, C>(
ps: readonly [Parser<A>, Parser<B>, Parser<C>],
): Parser<readonly [A, B, C]>
function pSeq<A, B, C, D>(
ps: readonly [Parser<A>, Parser<B>, Parser<C>, Parser<D>],
): Parser<readonly [A, B, C, D]>
function pSeq<A, B, C, D, E>(
ps: readonly [Parser<A>, Parser<B>, Parser<C>, Parser<D>, Parser<E>],
): Parser<readonly [A, B, C, D, E]>
function pSeq<A, B, C, D, E, F>(
ps: readonly [
Parser<A>,
Parser<B>,
Parser<C>,
Parser<D>,
Parser<E>,
Parser<F>,
],
): Parser<readonly [A, B, C, D, E, F]>
function pSeq<A, B, C, D, E, F, G>(
ps: readonly [
Parser<A>,
Parser<B>,
Parser<C>,
Parser<D>,
Parser<E>,
Parser<F>,
Parser<G>,
],
): Parser<readonly [A, B, C, D, E, F, G]>
function pSeq<A, B, C, D, E, F, G, H>(
ps: readonly [
Parser<A>,
Parser<B>,
Parser<C>,
Parser<D>,
Parser<E>,
Parser<F>,
Parser<G>,
Parser<H>,
],
): Parser<readonly [A, B, C, D, E, F, G, H]>
function pSeq<A, B, C, D, E, F, G, H, J>(
ps: readonly [
Parser<A>,
Parser<B>,
Parser<C>,
Parser<D>,
Parser<E>,
Parser<F>,
Parser<G>,
Parser<H>,
Parser<J>,
],
): Parser<readonly [A, B, C, D, E, F, G, H, J]>
function pSeq<A, B, C, D, E, F, G, H, J, K>(
ps: readonly [
Parser<A>,
Parser<B>,
Parser<C>,
Parser<D>,
Parser<E>,
Parser<F>,
Parser<G>,
Parser<H>,
Parser<J>,
Parser<K>,
],
): Parser<readonly [A, B, C, D, E, F, G, H, J, K]>
function pSeq<A, B, C, D, E, F, G, H, J, K, L>(
ps: readonly [
Parser<A>,
Parser<B>,
Parser<C>,
Parser<D>,
Parser<E>,
Parser<F>,
Parser<G>,
Parser<H>,
Parser<J>,
Parser<K>,
Parser<L>,
],
): Parser<readonly [A, B, C, D, E, F, G, H, J, K, L]>
function pSeq<A, B, C, D, E, F, G, H, J, K, L, M>(
ps: readonly [
Parser<A>,
Parser<B>,
Parser<C>,
Parser<D>,
Parser<E>,
Parser<F>,
Parser<G>,
Parser<H>,
Parser<J>,
Parser<K>,
Parser<L>,
Parser<M>,
],
): Parser<readonly [A, B, C, D, E, F, G, H, J, K, L, M]>
function pSeq<A, B, C, D, E, F, G, H, J, K, L, M, N>(
ps: readonly [
Parser<A>,
Parser<B>,
Parser<C>,
Parser<D>,
Parser<E>,
Parser<F>,
Parser<G>,
Parser<H>,
Parser<J>,
Parser<K>,
Parser<L>,
Parser<M>,
Parser<N>,
],
): Parser<readonly [A, B, C, D, E, F, G, H, J, K, L, M, N]>
function pSeq<A, B, C, D, E, F, G, H, J, K, L, M, N, O>(
ps: readonly [
Parser<A>,
Parser<B>,
Parser<C>,
Parser<D>,
Parser<E>,
Parser<F>,
Parser<G>,
Parser<H>,
Parser<J>,
Parser<K>,
Parser<L>,
Parser<M>,
Parser<N>,
Parser<O>,
],
): Parser<readonly [A, B, C, D, E, F, G, H, J, K, L, M, N, O]>
function pSeq<A>(ps: readonly Parser<A>[]): Parser<readonly A[]> {
return (s) => {
const vals: A[] = []
let rest = s
for (const p of ps) {
const res = p(rest)
if (!res.ok) {
return err
}
rest = res.rest
vals.push(res.val)
}
return ok(rest, vals)
}
}
function pInterspersed<A>(
sep: Parser<unknown>,
p: Parser<A>,
): Parser<readonly A[]> {
return pOneOf<readonly A[]>([
pMap(pSeq([p, pList1(pSeq([sep, p]))]), (x) => [
x[0],
...x[1].map((y) => y[1]),
]),
pMap(p, (x) => [x]),
])
}
const pInt: Parser<number> = pMap(pList1(pDigit), (ns) =>
ns.reduce((sum, n) => sum * 10 + n, 0),
)
const RESERVED_SYMBOLS: readonly string[] = [
"let",
"in",
"fn",
"True",
"False",
"if",
"then",
"else",
]
const pSymbol: Parser<string> = pAllowOnly(
pMap(pList1(pChar), (xs) => xs.join("")),
(x) => !RESERVED_SYMBOLS.includes(x),
)
function pLineComment(s: TextStream): ParserResult<unknown> {
const startP = pExact("--")
const start = startP(s)
if (!start.ok) {
return start
}
let rest = start.rest
const endP = pExact("\n")
while (rest.position < rest.fullText.length) {
const end = endP(rest)
if (end.ok) {
return end
}
rest = streamNext(rest)[1]
}
return err
}
function pMultiLineComment(s: TextStream): ParserResult<unknown> {
const startP = pExact("{-")
const start = startP(s)
if (!start.ok) {
return start
}
let rest = start.rest
const endP = pExact("-}")
while (rest.position < rest.fullText.length) {
const end = endP(rest)
if (end.ok) {
return end
}
rest = streamNext(rest)[1]
}
return err
}
const pSpaceOrComment = pOneOf([pSpace, pLineComment, pMultiLineComment])
const pSpaces0: Parser<null> = pIgnore(pList0(pSpaceOrComment))
const pSpaces1: Parser<null> = pIgnore(pList1(pSpaceOrComment))
const pBoolExpr: Parser<AST.Expr> = pMap(
pOneOf([pReplace(true, pExact("True")), pReplace(false, pExact("False"))]),
AST.eBool,
)
const pIntExpr: Parser<AST.Expr> = pMap(pInt, AST.eInt)
const pVarExpr: Parser<AST.Expr> = pMap(pSymbol, AST.eVar)
const pTupExpr: Parser<AST.Expr> = pMap(
pSeq([
pExact("("),
pSpaces0,
pOneOf([
pInterspersed(pSeq([pSpaces0, pExact(","), pSpaces0]), pExpr),
pSucceed([]),
]),
pSpaces0,
pExact(")"),
]),
(x) => {
const exprs = x[2]
return exprs.length === 1 ? exprs[0] : AST.eTup(exprs)
},
)
const pIfElseExpr: Parser<AST.Expr> = pMap(
pSeq([
pExact("if"),
pSpaces1,
pExpr,
pSpaces1,
pExact("then"),
pSpaces1,
pExpr,
pSpaces1,
pExact("else"),
pSpaces1,
pExpr,
]),
(x) => AST.eIfElse(x[2], x[6], x[10]),
)
function pLamExpr(s: TextStream): ParserResult<AST.Expr> {
const p = pMap(
pSeq([
pExact("fn"),
pSpaces1,
pPattern,
pSpaces0,
pExact("->"),
pSpaces0,
pExpr,
]),
(x) => AST.eLam(x[2], x[6]),
)
return p(s)
}
const pVarPat: Parser<AST.Pattern> = pMap(pSymbol, AST.pVar)
const pTupPat: Parser<AST.Pattern> = pMap(
pSeq([
pExact("("),
pSpaces0,
pOneOf([
pInterspersed(pSeq([pSpaces0, pExact(","), pSpaces0]), pPattern),
pSucceed([]),
]),
pSpaces0,
pExact(")"),
]),
(x) => {
const pats = x[2]
return pats.length === 1 ? pats[0] : AST.pTup(pats)
},
)
function pPattern(s: TextStream): ParserResult<AST.Pattern> {
return pOneOf([pVarPat, pTupPat])(s)
}
function pLetExpr(s: TextStream): ParserResult<AST.Expr> {
const p = pMap(
pSeq([
pExact("let"),
pSpaces1,
pPattern,
pSpaces0,
pExact("="),
pSpaces0,
pExpr,
pSpaces1,
pExact("in"),
pSpaces1,
pExpr,
]),
(x) => AST.eLet(x[2], x[6], x[10]),
)
return p(s)
}
function pLetFunc(s: TextStream): ParserResult<AST.Expr> {
const p = pMap(
pSeq([
pExact("let"),
pSpaces1,
pSymbol,
pSpaces1,
pPattern,
pSpaces0,
pExact("="),
pSpaces0,
pExpr,
pSpaces1,
pExact("in"),
pSpaces1,
pExpr,
]),
(x) => {
const id = x[2]
const pat = x[4]
const expr = x[8]
const exprNext = x[12]
return AST.eLet(AST.pVar(id), AST.eLam(pat, expr), exprNext)
},
)
return p(s)
}
function pApplOrVarExpr(s: TextStream): ParserResult<AST.Expr> {
const p = pOneOf<AST.Expr>([
pBoolExpr,
pIntExpr,
pLamExpr,
pLetExpr,
pLetFunc,
pTupExpr,
pVarExpr,
pIfElseExpr,
])
const p2 = pMap(pInterspersed(pSpaces1, p), (exprs) => {
let e = exprs[0]
for (let i = 1; i < exprs.length; i++) {
e = AST.eApp(e, exprs[i])
}
return e
})
return p2(s)
}
function pExpr(s: TextStream): ParserResult<AST.Expr> {
const p = pOneOf<AST.Expr>([
pBoolExpr,
pIntExpr,
pLamExpr,
pLetExpr,
pTupExpr,
pIfElseExpr,
pApplOrVarExpr,
])
return p(s)
}
export function parse(s: string): ParserResult<AST.Expr> {
const stream: TextStream = { fullText: s, position: 0 }
const p = pMap(pSeq([pSpaces0, pExpr, pSpaces0]), (x) => x[1])
return p(stream)
} |
/*
* Copyright (c) Enalean, 2021-Present. All Rights Reserved.
*
* This file is a part of Tuleap.
*
* Tuleap 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.
*
* Tuleap 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 Tuleap. If not, see <http://www.gnu.org/licenses/>.
*/
import type { HostElement, TextAndFormat, TextAndFormatOptions } from "./text-and-format";
import { getTextAndFormatTemplate, interpretCommonMark, isDisabled } from "./text-and-format";
import { setCatalog } from "../../gettext-catalog";
import { FormattedTextController } from "../../domain/common/FormattedTextController";
import { DispatchEventsStub } from "../../../tests/stubs/DispatchEventsStub";
import { TEXT_FORMAT_TEXT } from "@tuleap/plugin-tracker-constants";
import type { InterpretCommonMark } from "../../domain/common/InterpretCommonMark";
import { InterpretCommonMarkStub } from "../../../tests/stubs/InterpretCommonMarkStub";
import { Fault } from "@tuleap/fault";
const noop = (): void => {
//Do nothing
};
const getOptions = (data?: Partial<TextAndFormatOptions>): TextAndFormatOptions => ({
identifier: "unique-id",
rows: 3,
onContentChange: noop,
onFormatChange: noop,
...data,
});
const HTML_STRING = `<h1>Oh no! Anyway...</h1>`;
const COMMONMARK_STRING = "# Oh no! Anyway...";
describe(`TextAndFormat`, () => {
let target: ShadowRoot, interpreter: InterpretCommonMark, doc: Document;
beforeEach(() => {
doc = document.implementation.createHTMLDocument();
target = doc.createElement("div") as unknown as ShadowRoot;
setCatalog({ getString: (msgid) => msgid });
interpreter = InterpretCommonMarkStub.withHTML(HTML_STRING);
});
function getHost(data?: Partial<TextAndFormat>): HostElement {
const element = doc.createElement("span");
const host = {
...data,
interpreted_commonmark: "",
controller: FormattedTextController(
DispatchEventsStub.buildNoOp(),
interpreter,
TEXT_FORMAT_TEXT,
),
} as HostElement;
return Object.assign(element, host);
}
describe(`interpretCommonMark()`, () => {
const interpret = (host: HostElement): Promise<void> =>
interpretCommonMark(host, COMMONMARK_STRING);
it(`when in preview mode, it switches to edit mode`, async () => {
const host = getHost({ is_in_preview_mode: true });
await interpret(host);
expect(host.is_in_preview_mode).toBe(false);
});
it(`when in edit mode, it switches to preview mode
and sets the interpreted CommonMark on the host`, async () => {
const host = getHost({ is_in_preview_mode: false });
const promise = interpret(host);
expect(host.is_preview_loading).toBe(true);
await promise;
expect(host.has_error).toBe(false);
expect(host.error_message).toBe("");
expect(host.is_preview_loading).toBe(false);
expect(host.is_in_preview_mode).toBe(true);
expect(host.interpreted_commonmark).toBe(HTML_STRING);
});
it(`sets the error message when CommonMark cannot be interpreted`, async () => {
const error_message = "Invalid CommonMark";
interpreter = InterpretCommonMarkStub.withFault(Fault.fromMessage(error_message));
const host = getHost({ is_in_preview_mode: false });
await interpret(host);
expect(host.has_error).toBe(true);
expect(host.error_message).toBe(error_message);
expect(host.is_preview_loading).toBe(false);
expect(host.is_in_preview_mode).toBe(true);
expect(host.interpreted_commonmark).toBe("");
});
});
describe("Template", () => {
it(`assigns the same identifier on Format Selector and Rich Text Editor
so that the lib can bind them together`, () => {
const identifier = "psycheometry";
const host = getHost();
const update = getTextAndFormatTemplate(host, getOptions({ identifier }));
update(host, target);
const format_selector_element = getSelector("[data-test=format-selector]");
const text_editor_element = getSelector("[data-test=text-editor]");
expect(format_selector_element.getAttribute("identifier")).toBe(identifier);
expect(text_editor_element.getAttribute("identifier")).toBe(identifier);
});
it("shows the Rich Text Editor if there is no error and if the user is in edit mode", () => {
const host = getHost({ has_error: false, is_in_preview_mode: false });
const update = getTextAndFormatTemplate(host, getOptions());
update(host, target);
expect(
getSelector("[data-test=text-editor]").classList.contains(
"tuleap-artifact-modal-hidden",
),
).toBe(false);
expect(target.querySelector("[data-test=text-field-commonmark-preview]")).toBeNull();
expect(target.querySelector("[data-test=text-field-error]")).toBeNull();
});
it("shows the CommonMark preview if there is no error and if the user is in preview mode", () => {
const host = getHost({ has_error: false, is_in_preview_mode: true });
const update = getTextAndFormatTemplate(host, getOptions());
update(host, target);
expect(
getSelector("[data-test=text-editor]").classList.contains(
"tuleap-artifact-modal-hidden",
),
).toBe(true);
expect(
target.querySelector("[data-test=text-field-commonmark-preview]"),
).not.toBeNull();
expect(target.querySelector("[data-test=text-field-error]")).toBeNull();
});
it("shows the error message if there was a problem during the CommonMark interpretation", () => {
const host = getHost({
has_error: true,
error_message: "Interpretation failed !!!!!!!!",
is_in_preview_mode: false,
});
const update = getTextAndFormatTemplate(host, getOptions());
update(host, target);
expect(
getSelector("[data-test=text-editor]").classList.contains(
"tuleap-artifact-modal-hidden",
),
).toBe(true);
expect(target.querySelector("[data-test=text-field-commonmark-preview]")).toBeNull();
expect(getSelector("[data-test=text-field-error]").textContent).toContain(
"Interpretation failed !!!!!!!!",
);
});
});
describe("disabling the text field", () => {
it.each([
["field is disabled", true, false],
["preview is loading", false, true],
])(
`disables the text area if the %s`,
(disabled_entity, is_field_disabled, is_preview_loading) => {
const host = getHost({ disabled: is_field_disabled, is_preview_loading });
expect(isDisabled(host)).toBe(true);
},
);
it(`enables the text field when the field is not disabled and when it is not loading`, () => {
const host = getHost({ disabled: false, is_preview_loading: false });
expect(isDisabled(host)).toBe(false);
});
});
function getSelector(selector: string): HTMLElement {
const selected = target.querySelector(selector);
if (!(selected instanceof HTMLElement)) {
throw new Error("Could not select element");
}
return selected;
}
}); |
pragma solidity ^0.4.17; // The minimum version of Solidity required
contract Adoption {
address[16] public adopters;
function adopt(uint petId) public returns (uint) {
require(petId >= 0 && petId <= 15);
adopters[petId] = msg.sender;
return petId;
}
function getAdopters() public view returns(address[16]) {
return adopters;
}
}
// Solidity is a compiled language, meaning we need to compile our Solidity to bytecode for the Ethereum Virtual Machine (EVM) to execute. |
function getRandomHexColor() {
return `#${Math.floor(Math.random() * 16777215).toString(16)}`;
}
const startBtn = document.querySelector('button[data-start]');
const stopBtn = document.querySelector('button[data-stop]');
const bodyRef = document.querySelector('body');
let intervalId = null;
startBtn.addEventListener('click', onStartBtnClick);
stopBtn.addEventListener('click', onStopBtnClick);
stopBtn.disabled = true;
function onStartBtnClick (event) {
event.target.disabled = true;
stopBtn.disabled = false;
intervalId = setInterval(() => {
bodyRef.style.backgroundColor = getRandomHexColor();
}, 1000);
}
function onStopBtnClick (event) {
clearInterval(intervalId);
event.target.disabled = true;
startBtn.disabled = false;
} |
package net.map.elixirmap.util
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.extensions.LayoutContainer
abstract class BaseBindingAdapter<T> : RecyclerView.Adapter<BaseBindingAdapter.BaseViewHolder>() {
private var data = ArrayList<T>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
BaseViewHolder(
LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
)
override fun getItemCount() = data.size
abstract val layoutId: Int
override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
val entity = data[position]
holder.containerView.setOnClickListener {
_onItemClickBlock?.invoke(entity)
}
holder.containerView.setOnLongClickListener {
_onItemLongClickBlock?.invoke(entity)
return@setOnLongClickListener true
}
onConvert(holder, entity, position)
}
abstract fun onConvert(holder: BaseViewHolder, item: T, position: Int)
private var _onItemClickBlock: ((T) -> Unit)? = null
private var _onItemLongClickBlock: ((T) -> Unit)? = null
fun setOnItemClickListener(onItemClickBlock: (T) -> Unit) {
_onItemClickBlock = onItemClickBlock
}
fun setOnItemLongClickListener(onItemLongClickBlock: (T) -> Unit){
_onItemLongClickBlock = onItemLongClickBlock
}
class BaseViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView),
LayoutContainer
fun setItems(items: List<T>){
data.clear()
data.addAll(items)
notifyDataSetChanged()
}
fun getItems(): ArrayList<T>{
return data
}
} |
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library 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 library 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.
*/
package com.liferay.apio.architect.annotation;
/**
* Mode in which a field of a type can be used
*
* @author Víctor Galán
* @review
*/
public enum FieldMode {
/**
* Indicates that a field should only be used when instantiating the
* interface out of the HTTP request body.
*
* <p>
* A field with this mode will be ignored instantiating the interface out of
* the HTTP request body.
* </p>
*
* <p>
* Opposite attribute to {@link #WRITE_ONLY}.
* </p>
*
* @see #WRITE_ONLY
* @review
*/
READ_ONLY,
/**
* Indicates that a field should be used when instantiating the interface
* out of the HTTP request body and also when representing the type.
*
* <p>
* {@link #READ_ONLY} and {@link #WRITE_ONLY} together
* </p>
*
* @review
*/
READ_WRITE,
/**
* Indicates that a field should only be used when instantiating the
* interface out of the HTTP request body.
*
* <p>
* A field with this mode will be ignored when representing the type in any
* format.
* </p>
*
* <p>
* Opposite attribute to {@link #READ_ONLY}.
* </p>
*
* @see #READ_ONLY
* @review
*/
WRITE_ONLY
} |
## Deployment
In ths assignment, you're going to deploy your backend services (express and nestjs) using Docker.
### 1. Initial setup
To complete this assignment, you need to have docker engine installed on your system. For more details about how to install it please checkout this [link](https://docs.docker.com/engine/install/).
### 2. Deploy expressjs application
- Create a `Dockerfile` for the application.
- As a base image, use `node:lts-alpine3.19`, it has a small size compared to other images.
- Create a directory named `app` inside the container's filesystem and sets it as the working directory for subsequent commands. This is where your application code will be copied.
- Copy the `package.json` file.
- Run the command that installs the packages.
- Copy the code files host machine to the `app` directory in the Docker container.
- Expose the application port.
- Run the command that starts the server
- Build the docker image and give a tag of `codecla-express:v1` for example.
- Run the container
- Before running the container, start a MongoDB server using the official MongoDB Docker image.
- Ensure that you publish the necessary ports and pass the required environment variables like port number, database URL, secret keys, etc.
- Make sure that all endpoints of your Express.js application work as expected.
### 3. Deploy nestjs application
To deploy your nestjs application, we are going to use **two-stages build** as it optimized nest js builds to end up with a small image size.
First, you need to create a `Dockerfile`, then follow these steps
#### Development stage
For the development stage:
- Use the same nodejs base image, `node:lts-alpine3.19`.
- Create a directory named `app` inside the container's filesystem and sets it as the working directory
- Copy the `package.json` file.
- Run the command that installs the packages.
- Copy the code files host machine to the `app` directory in the Docker container.
- Run the build command.
#### Production stage
For the production stage:
- Use the same nodejs base image, `node:lts-alpine3.19`.
- Set the working dir to `app`.
- Copy the `package.json` file.
- Install **production-only** packages, using `npm install --only=production`.
- Copy the code files host machine to the `app` directory in the Docker container.
- Copy the generated `dist` directory from the `development stage` to this container.
- Execute the main script using `node`.
- Build the docker image and give a tag of `codecla-nestjs:v1` for example.
- Run the container
- Before running the container, start a MongoDB server using the official MongoDB Docker image.
- Ensure that you publish the necessary ports and pass the required environment variables like port number and database URL.
- Make sure that all endpoints of your Nest.js application work as expected.
>Important: Make sure to run your services on different ports to avoid errors.
> Note: if you list the images and inspect your nest js image you'll see that it has a relatively small size (around 350MB). It would've been around 1.5GB!. Hence, the power of multi-state builds. |
package by.zharikov.cleanarchitecturenoteapp.feature_note.presentation.notes
import android.util.Log
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import by.zharikov.cleanarchitecturenoteapp.feature_note.domain.model.Note
import by.zharikov.cleanarchitecturenoteapp.feature_note.domain.use_case.NoteUseCases
import by.zharikov.cleanarchitecturenoteapp.feature_note.domain.use_case.ThemeUseCases
import by.zharikov.cleanarchitecturenoteapp.feature_note.domain.util.NoteOrder
import by.zharikov.cleanarchitecturenoteapp.feature_note.domain.util.OrderType
import by.zharikov.cleanarchitecturenoteapp.feature_note.presentation.NoteEvent
import by.zharikov.cleanarchitecturenoteapp.ui.theme.*
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class NotesViewModel @Inject constructor(
private val noteUseCases: NoteUseCases,
private val themeUseCases: ThemeUseCases
) : ViewModel(), NoteEvent<NotesUiEvent> {
private val _state = MutableStateFlow(NotesState())
val state = _state.asStateFlow()
private var recentlyDeleteNote: Note? = null
private var getNotesJob: Job? = null
private var order: NoteOrder = NoteOrder.Date(orderType = OrderType.Descending)
init {
performNotes(order = NoteOrder.Date(orderType = OrderType.Descending))
}
override fun onEvent(event: NotesUiEvent) {
when (event) {
is NotesUiEvent.Order -> {
if (state.value.noteOrder::class == event.order::class
&& state.value.noteOrder.orderType == event.order.orderType
) return
order = event.order
performNotes(order = event.order)
}
is NotesUiEvent.DeleteNote -> {
deleteNote(note = event.note)
}
is NotesUiEvent.Restore -> {
performRestoreNotes()
}
is NotesUiEvent.ToggleOrderSection -> {
performToggleOrderSection()
}
is NotesUiEvent.ToggleThemeButton -> {
toggleTheme(isDarkTheme = event.isDarkTheme)
}
}
}
private fun toggleTheme(isDarkTheme: Boolean) {
viewModelScope.launch {
themeUseCases.saveThemeInSharedPref(isDarkTheme)
}
_state.value = _state.value.copy(isDarkTheme = isDarkTheme)
changeCardsColor(isDarkTheme)
}
private fun changeCardsColor(isDarkTheme: Boolean) {
val colorsMap = if (isDarkTheme) Note.notesColorDark
else Note.notesColorLight
val notes = mutableListOf<Note>()
viewModelScope.launch {
_state.value.notes.forEach { note ->
colorsMap[note.color.first]?.let {
val newColor = Pair(note.color.first, it)
notes.add(note.copy(color = newColor))
}
}
noteUseCases.updateNotesUseCase(notes)
}
}
private fun performRestoreNotes() {
viewModelScope.launch {
recentlyDeleteNote?.let { note ->
noteUseCases.addNoteUseCase(note = note)
}
recentlyDeleteNote = null
}
}
private fun performToggleOrderSection() {
_state.value = state.value.copy(isOrderSectionVisible = !state.value.isOrderSectionVisible)
}
private fun deleteNote(note: Note) {
viewModelScope.launch {
noteUseCases.deleteNoteUseCase(note = note)
recentlyDeleteNote = note
}
}
private fun performNotes(order: NoteOrder) {
getNotesJob?.cancel()
getNotesJob = noteUseCases.getNotesUseCase(noteOrder = order)
.onEach { notes ->
_state.value = state.value.copy(
notes = notes,
noteOrder = order,
isDarkTheme = themeUseCases.getThemeFromSharedPref()
)
}.launchIn(viewModelScope)
}
} |
=pod
=head1 NAME
B<yaf> - Yet Another Flowmeter
=head1 SYNOPSIS
yaf [--in INPUT_SPECIFIER] [--out OUTPUT_SPECIFIER]
[--live LIVE_TYPE] [--ipfix TRANSPORT_PROTOCOL]
[--no-output]
[--filter BPF_FILTER]
[--rotate ROTATE_DELAY] [--lock] [--caplist]
[--group SPREAD_GROUP_NAME(s)]
[--groupby GROUPBY_TYPE]
[--stats INTERVAL][--no-stats] [--noerror]
[--export-interface]
[--gre-decode] [--no-frag]
[--max-frags FRAG_TABLE_MAX]
[--ip4-only] [--ip6-only]
[--idle-timeout IDLE_TIMEOUT]
[--active-timeout ACTIVE_TIMEOUT]
[--udp-temp-timeout TEMPLATE_TIMEOUT]
[--force-read-all]
[--flow-stats] [--delta]
[--ingress INGRESS_INT] [--egress EGRESS_INT]
[--max-payload PAYLOAD_OCTETS] [--udp-payload]
[--max-flows FLOW_TABLE_MAX]
[--export-payload] [--silk] [--udp-uniflow PORT]
[--uniflow] [--mac] [--force-ip6-export]
[--observation-domain DOMAIN_ID] [--entropy]
[--applabel] [--applabel-rules RULES_FILE]
[--ipfix-port PORT] [--tls] [--tls-ca CA_PEM_FILE]
[--tls-cert CERT_PEM_FILE] [--tls-key KEY_PEM_FILE]
[--become-user UNPRIVILEGED_USER]
[--become-group UNPRIVILEGED_GROUP]
[--log LOG_SPECIFIER] [--loglevel LOG_LEVEL]
[--verbose] [--version]
[--p0fprint] [--p0f-fingerprints FILENAME]
[--fpexport]
[--plugin-name LIBPLUGIN_NAME[,LIBPLUGIN_NAME...]]
[--plugin-opts "OPTIONS[,OPTIONS...]"]
[--plugin-conf CONF_FILE_PATH[,CONF_FILE_PATH...]]
[--pcap PCAP_FILE_PREFIX] [--pcap-per-flow]
[--max-pcap MAX_FILE_MB] [--pcap-timer PCAP_ROTATE_DELAY]
[--pcap-meta-file META_FILE_PREFIX] [--index-pcap]
[--hash FLOW_KEY_HASH] [--stime FLOW_START_TIMEMS]
=head1 DESCRIPTION
B<yaf> is Yet Another Flowmeter and B<yaf> is a suite of tools to do flow metering.
B<yaf> is used as a sensor to capture flow information on a network and export that
information in IPFIX format. It reads packet data from B<pcap(3)> dumpfiles as
generated by B<tcpdump(1)>, from live capture from an interface using B<pcap(3)>,
an Endace DAG capture device, a Napatech adapter, or Netronome NFE card aggregates these packets
into flows, and exports flow records via IPFIX over SCTP, TCP or UDP, Spread, or into
serialized IPFIX message streams (IPFIX files) on the local file system.
Since B<yaf> is designed to be deployed on white-box sensors attached to local
network segments or span ports at symmetric routing points, it supports
bidirectional flow assembly natively. Biflow export is done via the export
method specified in B<RFC 5103> Bidirectional Flow Export using IPFIX. See the
B<OUTPUT> section below for information on this format.
B<yaf> also supports experimental partial payload capture, specifically for
banner-grabbing applications and protocol verification purposes.
The output of B<yaf> is designed to be collected and manipulated by flow
processing toolchains supporting IPFIX. The B<yafscii(1)> tool, which is
installed as part of B<yaf>, can also be used to print B<yaf> output in a
human-readable format somewhat reminiscient of B<tcpdump(1)>. B<yaf> output
can also be analyzed using the SiLK suite, and the B<nafalize(1)> tool, both
available from the CERT NetSA group.
=head1 OPTIONS
=head2 Input Options
These options control where B<yaf> will take its input from. B<yaf> can read packets
from a pcap dumpfile (as generated by B<tcpdump -w>) or live from an interface
via F<libpcap>, F<libdag>, or F<libnapatech>, or Netronome API.
By default, if no input options are given, B<yaf> reads a pcap dumpfile
on standard input.
=over 4
=item B<--in> I<INPUT_SPECIFIER>
I<INPUT_SPECIFIER> is an input specifier. If B<--live> is given, this is the
name of an interface (e.g. C<eth0>, C<en0>, C<dag0>, C<nt3g>, C<nt3g0:1>, C<0:0>) to capture packets from.
Otherwise, it is a filename; the string B<-> may be used to read from
standard input (the default). See B<--live> for more information on formats
for Napatech, Dag, and Netronome Interface formats.
=item B<--caplist>
If present, treat the filename in I<INPUT_SPECIFIER> as an ordered
newline-delimited list of pathnames to B<pcap(3)> dumpfiles. Blank lines
and lines beginning with the character '#' within this are ignored. All
pathnames are evaluated with respect to the working directory B<yaf>
is run in. These dumpfiles are processed in order using the same flow
table, so they must be listed in ascending time order. This option is
intended to ease the use of yaf with rotated or otherwise split B<tcpdump(1)>
output.
=item B<--noerror>
Used with the B<--caplist> option. When present, this prevents B<yaf> from
exiting when processing a list of dumpfiles in the middle due to an error
in a file. B<yaf> will continue to process all files given in the
I<INPUT_SPECIFIER> despite errors within those files.
=item B<--live> I<LIVE_TYPE>
If present, capture packets from an interface named in the I<INPUT_SPECIFIER>.
I<LIVE_TYPE> is one of B<pcap> for packet capture via libpcap, or B<dag> for
packet capture via an Endace DAG interface using libdag, or B<napatech> for
packet capture via a Napatech Adapter, or B<netronome> for packet capture
via a Netronome NFE card. B<dag> is only
available if B<yaf> was built with Endace DAG support. B<napatech> is only
available if B<yaf> was built with Napatech API support. If I<LIVE_TYPE> is
B<napatech>, the I<INPUT_SPECIFIER> given to B<--in> should be in the form nt3g[<streamID>:<ports>]. StreamID and Ports are optional. StreamID if given, is the ID that the traffic
stream will be assigned to on the incoming ports. Ports may be a comma-separated list of ports to listen on. If [ports] is not specified, the default is to listen on All ports. StreamID defaults to 0.
B<netronome> is only available if B<yaf> was built
with Netronome API support. If I<LIVE_TYPE> is B<netronome>, the
I<INPUT_SPECIFIER> given to B<--in> should be in the form <device>:<ring>
where device is the NFE card ID, typically 0. Ring is the capture ring ID
which is configured via a modprobe configuration file and resides in
/etc/modprobe.d/pcd.conf.
=item B<--export-interface>
If present, the interface on which a packet was received will be noted
internally within B<yaf>. When flow records are exported from B<yaf>, an
C<ingressinterface> and an C<egressinterface> set of fields will be added to the output. The C<ingressinterface> field will be the physical interface which captured the packet while the C<egressinterface> will be the physical interface | 0x100. This can be used to separate traffic based on DAG physical ports.
For use with the DAG card, traffic received on separate ports will be
separated into different flows if B<yaf> is configured with the
B<--enable-daginterface> option. Otherwise the
physical port will simply be exported in the C<ingressInterface> or
C<egressInterface> fields in the IPFIX record (flows can exist over multiple
interfaces). This option requires building DAG, Netronome, or Napatech
support in B<yaf> with the
B<--with-dag>, B<--with-napatech>, or B<--with-netronome> switch.
In previous versions of B<yaf> this option was enabled using
the B<--dag-interface> or B<--napatech-interface> switch. It is now enabled by
default when B<yaf> is built with DAG, Netronome, or Napatech support. It can
be disabled by configuring B<yaf> with <--enable-interface=no>. To separate
traffic received on separate ports into separate flows, you must use
B<--enable-daginterface> when configuring B<yaf>.
=item B<--filter> I<BPF_FILTER>
If present, enable Berkeley Packet Filtering (BPF) in B<yaf> with I<FILTER_EXPRESSION> as the incoming traffic filter. Syntax of I<FILTER_EXPRESSION> follows the expression format described in the B<tcpdump(1)> man page. This option is not currently supported if B<--live> is set to B<dag> or B<napatech> or
B<netronome> as BPF filtering is implemented with libpcap. However, you may
be able to use a BPF filter by running B<yaf> with the DAG, Napatech, or
Netronome implementations of libpcap.
=back
=head2 Output Options
These options control where B<yaf> will send its output. B<yaf> can write flows
to an IPFIX file or export flows to an IPFIX collector over SCTP, TCP, UDP, or Spread.
By default, if no output options are given, B<yaf> writes an IPFIX file to
standard output.
=over 4
=item B<--out> I<OUTPUT_SPECIFIER>
I<OUTPUT_SPECIFIER> is an output specifier. If B<--ipfix> is present,
the I<OUTPUT_SPECIFIER> specifies the hostname or IP address of the
collector to which the flows will be exported. Otherwise, if B<--rotate>
is present, I<OUTPUT_SPECIFIER> is the prefix name of each output file
to write to. If B<--ipfix> is present and set to B<spread>, then I<OUTPUT_SPECIFIER> should be set to the name of the Spread daemon to connect to (See below examples of spread daemon names). Otherwise, I<OUTPUT_SPECIFIER> is a filename in which the flows will be written; the string B<-> may be used to write to standard output (the default).
=item Examples
=over 1
=item Output to file
C<--out flows.yaf>
=item Output to collector on port 18000 at IP address 1.2.3.4
C<--out 1.2.3.4 --ipfix-port 18000 --ipfix tcp>
=item Connect to the Spread daemon named "4803" on the local machine
C<--out 4803 or --out 4803@localhost>
=item Connect to the machine identified by the domain name "host.domain.edu" on port 4803.
C<--out 4803@host.domain.edu>
=item Connect to the machine identified by the IP address "x.y.123.45" on port 18000.
C<--out x.y.123.45 --ipfix-port 18000>
=back
=item B<--ipfix> I<TRANSPORT_PROTOCOL>
If present, causes B<yaf> to operate as an IPFIX exporter, sending
IPFIX Messages via the specified transport protocol to the collector (e.g.,
SiLK's rwflowpack or flowcap facilities) named in the I<OUTPUT_SPECIFIER>.
Valid I<TRANSPORT_PROTOCOL> values are B<tcp>, B<udp>, B<sctp>, and B<spread>;
B<sctp> is only available if B<yaf> was built with SCTP support; B<spread> is only available if B<yaf> was built with Spread support. UDP is not recommended, as it is not a reliable transport protocol, and cannot guarantee delivery of messages. As per the recommendations in RFC 5101, B<yaf> will retransmit templates three times within the template timeout period (configurable using B<--udp-temp-timeout> or by default, 10 minutes). Use the
B<--ipfix-port>, B<--tls>, B<--tls-ca>, B<--tls-cert>, B<--tls-key>, B<--tls-pass>, and B<--group> options to further configure the connection to the
IPFIX collector.
=item B<--rotate> I<ROTATE_DELAY>
If present, causes B<yaf> to write output to multiple files, opening a new output
file every I<ROTATE_DELAY> seconds in the input data. Rotated files are named
using the prefix given in the I<OUTPUT_SPECIFIER>, followed by a suffix
containing a timestamp in C<YYYYMMDDhhmmss> format, a decimal serial number,
and the file extension B<.yaf>.
=item B<--lock>
Use lockfiles for concurrent file access protection on output files.
This is recommended for interoperating with the Airframe filedaemon
facility.
=item B<--stats> I<INTERVAL>
If present, causes B<yaf> to export process statistics every I<INTERVAL> seconds.
The default value for I<INTERVAL> is 300 seconds or every 5 minutes. B<yaf> uses IPFIX Options Templates and Records
to export flow, fragment, and decoding statistics. If I<INTERVAL> is set
to zero, stats will not be exported.
=item B<--no-stats>
If present, B<yaf> will not export process statistics. B<yaf> uses IPFIX
Options Templates and Records to export flow, fragment, and decoding
statistics. B<--no-stats> takes precedence over B<--stats>.
=item B<--no-output>
If present, B<yaf> will not export IPFIX data. It will ignore
any argument provided to B<--out>.
=back
=head2 Decoder Options
These options are used to modify the B<yaf> packet decoder's behavior. None of
these options are required; the default behavior for each option when not
present is noted.
=over 4
=item B<--no-frag>
If present, ignore all fragmented packets. By default, B<yaf> will reassemble
fragments with a 30 second fragment timeout.
=item B<--max-frags> I<FRAG_TABLE_MAX>
If present, limit the number of outstanding, not-yet reassembled fragments
in the fragment table to I<FRAG_TABLE_MAX> by prematurely expiring fragments
from the table. This option is provided to limit B<yaf> resource usage when
operating on data from very large networks or networks with abnormal
fragmentation. The fragment table may exceed this limit slightly due
to limits on how often B<yaf> prunes the fragment table (every 5 seconds).
By default, there is no fragment table limit, and the fragment
table can grow to resource exhaustion.
=item B<--ip4-only>
If present, ignore all IPv6 packets and export IPv4 flows only. The default is
to process both IPv4 and IPv6 packets.
=item B<--ip6-only>
If present, ignore all IPv4 packets and export IPv6 flows only. The default is
to process both IPv4 and IPv6 packets.
=item B<--gre-decode>
If present, attempt to decode GRE version 0 encapsulated packets. Flows will
be created from packets within the GRE tunnels. Undecodeable GRE packets will
be dropped. Without this option, GRE traffic is exported as IP protocol 47
flows. This option is presently experimental.
=back
=head2 Flow Table Options
These options are used to modify the flow table behavior within B<yaf>. None of
these options are required; the default behavior for each option when not
present is noted.
=over 4
=item B<--idle-timeout> I<IDLE_TIMEOUT>
Set flow idle timeout in seconds. Flows are considered idle and flushed
from the flow table if no packets are received for I<IDLE_TIMEOUT> seconds.
The default flow idle timeout is 300 seconds (5 minutes). Setting
I<IDLE_TIMEOUT> to 0 creates a flow for each packet.
=item B<--active-timeout> I<ACTIVE_TIMEOUT>
Set flow active timeout in seconds. Any flow lasting longer than
I<ACTIVE_TIMEOUT> seconds will be flushed from the flow table.
The default flow active timeout is 1800 seconds (30 minutes).
=item B<--udp-temp-timeout> I<TEMPLATE_TIMEOUT>
Set UDP template timeout in seconds if B<--ipfix> is set to I<udp>. As per RFC 5101 recommendations, B<yaf>
will attempt to export templates three times within I<TEMPLATE_TIMEOUT>. The
default template timeout period is 600 seconds (10 minutes).
=item B<--max-payload> I<PAYLOAD_OCTETS>
If present, capture at most I<PAYLOAD_OCTETS> octets from the start of
each direction of each flow. Non-TCP flows will only capture payload
from the first packet unless B<--udp-payload> is set. If not present, B<yaf> will not attempt to capture
payload. Payload capture must be enabled for payload export
(B<--export-payload>), application labeling (B<--applabel>), and entropy
evaluation (B<--entropy>). Note that payload capture is still an
experimental feature.
=item B<--max-flows> I<FLOW_TABLE_MAX>
If present, limit the number of open flows in the flow table to
I<FLOW_TABLE_MAX> by prematurely expiring the flows with the least
recently received packets; this is analogous to an adaptive idle
timeout. This option is provided to limit B<yaf> resource usage when
operating on data from large networks. By default, there is no flow
table limit, and the flow table can grow to resource exhaustion.
=item B<--udp-payload>
If present, capture at most I<PAYLOAD_OCTETS> octets fom the start of each direction of each UDP flow, where I<PAYLOAD_OCTETS> is set using the B<--max-payload> flag.
=item B<--silk>
If present, export flows in "SiLK mode". As of B<yaf> 2.0, this will export
TCP information (flags, ISN) in the main flow record instead of within the
SubTemplateMultiList. This flag must be used when exporting to SiLK for it to
collect TCP flow information. This also introduces the following incompatibilities
with standard IPFIX export:
=over 4
=item *
totalOctetCount and reverseTotalOctetCount are clamped to 32 bits. Any packet
that would cause either of these counters to overflow 32 bits will cause the
flow to close with flowEndReason 0x02 (active timeout), and will become the
first packet of a new flow. This is analogous to forcing an active timeout
when the octet counters overflow.
=item *
The high-order bit of the flowEndReason IE is set on any flow created on a
counter overflow, as above.
=item *
The high-order bit of the flowEndReason IE is set on any flow created on an
active timeout.
=back
Since this changes the semantics of the exported flowEndReason IE, it should
only be used when generating flows and exporting to rwflowpack, flowcap, or
writing files for processing with rwipfix2silk.
=item B<--force-read-all>
If present, B<yaf> will process out-of-sequence packets. However, it will
still reject out-of-sequence fragments.
=back
=head2 Export Options
These options are used to modify the the data exported by B<yaf>.
=over 4
=item B<--export-payload>
If present, export at most I<PAYLOAD_OCTETS> (the argument to
B<--max-payload>) octets from the start of each direction of each
flow. Non-TCP flows will only export payload from the first packet. By default,
B<yaf> will not export flow payload.
=item B<--uniflow>
If present, export biflows using the Record Adjacency method in
section 3 of RFC 5103. This is useful when exporting to IPFIX
Collecting Processes that are not biflow-aware.
=item B<--mac>
If present, export MAC-layer information; presently, exports source and destination MAC addresses.
=item B<--force-ip6-export>
If present, force IPv4 flows to be exported with IPv6-mapped IPv4 addresses in
::FFFF/96. This will cause all flows to appear to be IPv6 flows.
=item B<--observation-domain> I<DOMAIN_ID>
Set the observationDomainID on each exported IPFIX message to the given
integer value. If not present, the observationDomainId defaults to 0. This
value is also used as the exportingProcessId in the B<yaf> statistics Option
Record as a Scope Field.
=item B<--udp-uniflow> I<PORT>
If present, export each UDP packet on the given port (or 1 for all ports) as a single flow, with flowEndReason set to YAF_END_UDPFORCE (0x1F). This will not close the flow. The flow will stay open until it closes naturally by the idle and active timeouts. Most useful with B<--export-payload> in order to export every UDP payload on a specific port.
=item B<--flow-stats>
If present, export extra flow attributes and statistics in the
subTemplateMultiList field. This will maintain information such as small
packet count, large packet count, nonempty packet count, average
interarrival times, total data octets, and max packet size. See the flow
statistics template below for more information about each of the fields B<yaf>
exports.
=item B<--delta>
If present, export octet and packet total counts in the delta count information
elements. octetTotalCount will be exported in octetDeltaCount (IE 1),
reverseOctetTotalCount will be exported in reverseOctetDeltaCount. packetTotalCount
will be exported in packetDeltaCount (IE 2), and reversePacketTotalCount will be
exported in reversePacketDeltaCount.
=item B<--ingress> I<INGRESS_INT>
If present, set the ingressInterface field in the flow template to I<INGRESS_INT>.
This field will also be populated if B<yaf> was configured with --enable-daginterface or
--enable-napatechinterface or --with-bivio. If yaf is running on a dag, napatech, or
bivio, and the physical interface is available, this value will override I<INGRESS_INT>.
=item B<--egress> I<EGRESS_INT>
If present, set the egressInterface field in the flow template to I<EGRESS_INT>.
This field will also be populated if B<yaf> was configured with --enable-daginterface
or --enable-napatechinterface or --with-bivio. If yaf is running on a dag, napatech, or
bivio, and the physical interface is available, this value will override I<EGRESS_INT>.
=back
=head2 Application Labeler Options
If B<yaf> is built with application labeler support enabled (using the
B<--enable-applabel> option to B<./configure> when B<yaf> is built), then
B<yaf> can examine packet payloads and determine the application protocol
in use within a flow, and export a 16-bit application label with
each flow.
The exported application label uses the common port number for the
protocol. For example, HTTP traffic, independent of what port the
traffic is detected on, will be labeled with a value of 80, the
default HTTP port. Labels and rules are taken from a configuration
file read at B<yaf> startup time.
Application labeling requires payload capture to be enabled with the
B<--max-payload> option. A minimum payload capture length of 384
octets is recommended for best results.
Application labeling is presently experimental. SiLK does support
IPFIX import and translation of the application label via
B<rwflowpack>, B<flowcap>, and B<rwipfix2silk>.
=over 4
=item B<--applabel>
If present, export application label data. Requires B<--max-payload>
to enable payload capture.
=item B<--applabel-rules> I<RULES_FILE>
Read application labeler rules from I<RULES_FILE>. If not present,
rules are read by default from F<@prefix@/etc/yafApplabelRules.conf>.
=back
=head2 Entropy Measurement
If B<yaf> is built with entropy measurement enabled (using the
B<--enable-entropy> option to B<./configure> when B<yaf> is built,)
then B<yaf> can examine the packet payloads and determine a Shannon
Entropy value for the payload. The entropy calculation does not
include the network (IP) or transport (UDP/TCP) headers. The entropy
is calculated in terms of bits per byte, (log base 2.) The
calculation generates a real number value between 0.0 and 8.0. That
number is then converted into an 8-bit integer value between 0 and
255. Roughly, numbers above 230 are generally compressed (or encrypted)
and numbers centered around approximately 140 are English text. Lower
numbers carry even less information content. Another useful piece of
information is that SSL/TLS tends to zero pad its packets, which causes
the entropy of those flows to drop quite low.
=over 4
=item B<--entropy>
If present, export the entropy values for both the forward and reverse
payloads. Requires the B<--max-payload> option to operate.
=back
=head2 IPFIX Connection Options
These options are used to configure the connection to an IPFIX collector.
=over 4
=item B<--ipfix-port> I<PORT>
If B<--ipfix> is present, export flows to TCP, UDP, or SCTP port I<PORT>.
If not present, the default IPFIX port 4739 is used. If B<--tls> is also
present, the default secure IPFIX port 4740 is used.
=item B<--tls>
If B<--ipfix> is present, use TLS to secure the connection to the
IPFIX collector. Requires the I<TRANSPORT_PROTOCOL> to be B<tcp>, as DTLS over
UDP or SCTP is not yet supported. Requires the B<--tls-ca>, B<--tls-cert>, and
B<--tls-key> options to specify the X.509 certificate and TLS key information.
=item B<--tls-ca> I<CA_PEM_FILE>
Use the Certificate Authority or Authorities in I<CA_PEM_FILE> to verify the
remote IPFIX Collecting Process' X.509 certificate. The connection to the
Collecting Process will fail if its certificate was not signed by this CA
(or by a certificate signed by this CA, recursively); this prevents export to
unauthorized Collecting Processes. Required if B<--tls> is present.
=item B<--tls-cert> I<CERT_PEM_FILE>
Use the X.509 certificate in I<CERT_PEM_FILE> to identify this IPFIX Exporting
Process. This certificate should contain the public part of the private key in
I<KEY_PEM_FILE>. Required if B<--tls> is present.
=item B<--tls-key> I<KEY_PEM_FILE>
Use the private key in I<KEY_PEM_FILE> for this IPFIX Exporting Process. This
key should contain the private part of the public key in
I<CERT_PEM_FILE>. Required if B<--tls> is present. If the key is encrypted,
the password must be present in the YAF_TLS_PASS environment variable.
=item B<--group> I<SPREAD_GROUP_NAME>
If B<--ipfix> is present and set to B<spread>, use B<--group> to specify the spread group name(s) to publish output.
It is possible to list more than one group name in a comma-seperated list.
To use Spread as a manifold for different types of flows, use the format
I<GROUP, GROUP_NAME:VALUE, GROUP_NAME:VALUE> as the argument to B<--group>
and use the B<--groupby> switch. This list should be contained in quotes if it contains spaces (B<yaf> will ignore spaces in quotes). It is suggested to use one group
as the catchall for all flows (no value listed) so flows are not lost.
The B<--groupby> switch must be used if B<--group> uses GROUP:VALUE
format. See the Spread Documentation, www.spread.org,
for more details on Spread.
=item B<--groupby> I<GROUPBY_TYPE>
If B<--group> is used with group values, use B<--groupby> to specify what
type of value should be used. Options are I<port, vlan, applabel, protocol, version>.
B<--groupby> accepts only one argument. The I<port> option is destination
transport port of the flow. I<version> is the IP version of the flow.
=back
=head2 Privilege Options
These options are used to cause B<yaf> to drop privileges when running as root
for live capture purposes.
=over 4
=item B<--become-user> I<UNPRIVILEGED_USER>
After opening the live capture device in B<--live> mode, drop
privilege to the named user. Using B<--become-user> requires B<yaf> to
be run as root or setuid root. This option will cause all files
written by B<yaf> to be owned by the user I<UNPRIVILEGED_USER> and the
user's primary group; use B<--become-group> as well to change the group
B<yaf> runs as for output purposes.
If running as root for live capture purposes and B<--become-user> is not
present, B<yaf> will warn that privilege is not being dropped. We highly
recommend the use of this option, especially in production environments,
for security purposes.
=item B<--become-group> I<UNPRIVILEGED_GROUP>
B<--become-group> can be used to change the group from the default of
the user given in B<--become-user>. This option has no effect if
given without the B<--become-user> option as well.
=back
=head2 PCAP Options
These options are used to turn on and configure B<yaf>'s PCAP export
capability.
=over 4
=item B<--pcap> I<PCAP_FILE_PREFIX>
This option turns on rolling PCAP export in B<yaf>. It will capture and write
packets for all network traffic B<yaf> has received and processed to
PCAP files with the given I<PCAP_FILE_PREFIX>. B<yaf> will not create file
directories. If B<yaf> can't write to the file, B<yaf> will turn off PCAP
export. Pcap files will have names in the form of
PCAP_FILE_PREFIX[datetime]_serialno.pcap". B<yaf> will write to a file until the
file size has reached B<--max-pcap> or every B<--pcap-timer> seconds
(whichever happens first). By default, B<yaf> rotates files every 5 MB. Files
will be "locked" (".lock" will be appended to the filename) until B<yaf> has
closed the file. Be aware that your Operating System will have a limit on the
maximum number of files in a directory and a maximum file size. If this
limit is reached, B<yaf> will write warning messages and terminate PCAP export.
This may effect flow generation if B<yaf> is also writing IPFIX files.
Optionally, you can also export meta information about the flows in each
rolling PCAP file with the B<--pcap-meta-file> switch. If B<--pcap> is used
in conjunction with B<--hash> and B<--stime>, the I<PCAP_FILE_PREFIX> should
be the name of the PCAP file to write to (it will not be used as a
file prefix).
=item B<--pcap-per-flow>
If present, B<yaf> will write a pcap file for each flow in the output
directory given to B<--pcap>. PCAP_FILE_PREFIX given to B<--pcap> must be
a file directory. This option is experimental and should only be
used when reading pcap files of reasonable size. B<yaf> only writes up to
B<--max-payload> bytes of each packet to the pcap file. Therefore,
B<--max-payload> must be set to an appropriate size to prevent packets from
being truncated in the pcap file. B<yaf> will use the
last three digits of the flowStartMilliseconds as the directory and the
flow key hash, flowStartMilliseconds, and serial number as the filename.
See the included
B<getFlowKeyHash> program to easily calculate the name of the file for a given
flow. When the pcap file has reached B<--max-pcap> size, B<yaf> will close
the file, increment the serial number, and open a new pcap file with the same
naming convention. Note that your operating system has a limit to the number
of open file handles B<yaf> can maintain at any given time. Therefore, the
performance of B<yaf> degrades when the number of open flows is greater than
the maximum number of file handles.
=item B<--max-pcap> I<MAX_FILE_MB>
If present, set the maximum file size of pcap files to I<MAX_FILE_MB> MB.
The default is 5 MB.
=item B<--pcap-timer> I<PCAP_ROTATE_DELAY>
If present, B<yaf> will rotate rolling pcap files every I<PCAP_ROTATE_DELAY>
seconds or when the file reaches B<--max-pcap> size, whichever happens first.
By default, B<yaf> only rotates files based on file size.
=item B<--pcap-meta-file> I<META_FILENAME>
If present and --pcap is also present, B<yaf> will export metadata
on the flows contained in
each rolling pcap file B<yaf> is writing to the filename specified by
I<META_FILENAME>. B<yaf> will write a line in the form:
=over 1
=item I<flow_key_hash | flowStartMilliseconds | pcap_file_name>
=back
for each flow in the pcap. If a flow exists across 3 pcap
files, there will be 3 lines in I<META_FILENAME> for that flow (each line
having a different filename). The pcap-meta-file will rotate files every 10
rolling pcap files. A new file will be created in the form I<META_FILENAME>x
where x starts at 1 and increments by 1 for every new pcap-meta-file created.
This file can be uploaded to a database for flow correlation and flow-to-pcap
analysis.
If B<--pcap-meta-file> is present and --pcap is not present,
B<yaf> will export information about the
pcap file(s) it is presently reading, as opposed to the pcap files B<yaf> is writing.
For each packet in the pcap file, B<yaf> will write a line in the form:
=over 1
=item I<flow_key_hash | flowStartMilliseconds | file_num | offset | length>
=back
C<file_num> is the sequential file number that B<yaf> has processed. If B<yaf>
was given a single pcap file, this number will always be 0.
C<offset> is the offset into the pcap file of the beginning of the packet,
at the start of the pcap packet header. C<length> is the length of the packet including
the pcap packet header.
Using this offset, a separate program, such as B<yafMeta2Pcap>, will be
able to quickly extract packets
for a flow. This file only rotates if I<META_FILE> reaches max size.
=item B<--index-pcap>
If present and B<--pcap> and B<--pcap-meta-file> are also present,
export offset and length information about the packets B<yaf> is
writing to the rolling pcap files. Adding this option will force
B<yaf> to write one line per packet to the B<pcap-meta-file> in the form:
=over 1
=item I<flow_key_hash | flowStartMilliseconds | pcap_file_name | offset | length>
=back
This option is ignored if B<--pcap> is not present.
=item B<--hash> I<FLOW_KEY_HASH>
If present, only write PCAP data for the flow(s) with I<FLOW_KEY_HASH>.
This option is only valid with the B<--pcap> option.
=item B<--stime> I<FLOW_START_TIMEMS>
If present, only write PCAP data for the flow(s) with I<FLOW_START_TIMEMS>
and I<FLOW_KEY_HASH> given to B<--hash>. This option is only valid
when used with the B<--hash> and B<--pcap> options.
=back
=head2 Logging Options
These options are used to specify how log messages are routed. B<yaf> can
log to standard error, regular files, or the UNIX syslog facility.
=over 4
=item B<--log> I<LOG_SPECIFIER>
Specifies destination for log messages. I<LOG_SPECIFIER> can be a syslog(3)
facility name, the special value B<stderr> for standard error, or the
I<absolute> path to a file for file logging. The default log
specifier is B<stderr> if available, B<user> otherwise.
=item B<--loglevel> I<LOG_LEVEL>
Specify minimum level for logged messages. In increasing levels of verbosity,
the supported log levels are B<quiet>, B<error>, B<critical>, B<warning>,
B<message>, B<info>, and B<debug>. The default logging level is B<warning>.
=item B<--verbose>
Equivalent to B<--loglevel debug>.
=item B<--version>
If present, print version and copyright information to standard error and exit.
=back
=head2 Plugin Options
These options are used to load, configure, and run a B<yaf> plugin.
=over 4
=item B<--plugin-name> I<LIBPLUGIN_NAME[,LIBPLUGIN_NAME...]>
Specify the plugin to load. The loaded plugin must follow the B<yaf> plugin framework. I<LIBPLUGIN_NAME> must be the full path to the plugin library name. Two plugins are included with c<yaf>, a Deep Packet Inspection plugin, and a
DHCP Fingerprinting plugin. This flag will only be recognized if B<yaf> is configured with B<--enable-plugins>. There are also configure options to export only DNS Authoritative and NXDomain responses. Read each plugin's documentation
for more information.
=item B<--plugin-opts> I<"OPTIONS[,OPTIONS...]">
Specify the arguments to the plugin given to B<--plugin-name>. This flag will only be recognized if B<yaf> is configured with B<--enable-plugins> and B<--plugin-name> is set to a valid plugin. For example, the DPI Plugin takes the well-known port of a protocol(s) to enable DPI (default for DPI is all protocols).
=item B<--plugin-conf> I<CONF_FILE_PATH[,CONF_FILE_PATH...]>
Specify the path to a configuration file for the plugin given to B<--plugin-name>. This flag will only be recognized if
B<yaf> is configured with B<--enable-plugins> and B<--plugin-name> is set to a valid plugin. If this switch is not used,
but the plugin requires a configuration file, the default location F<@prefix@/etc> will be used.
=back
=head2 Passive OS Fingerprinting (p0f)
These options are used to enable p0f in B<yaf>. p0f is presently experimental. There is no support in B<yafscii> or SiLK for printing p0f related data. Currently, B<yaf> uses the p0f Version 2 SYN fingerprints (see p0f.fp).
=over 4
=item B<--p0fprint>
If present, export p0f data. This data consists of three related information elements; osName, osVersion, osFingerPrint. This flag requires B<yaf> to be configured with B<--enable-p0fprinter>.
=item B<--p0f-fingerprints>
Location of the p0f fingerprint file(s), p0f.fp. Default is F<@prefix@/etc/p0f.fp>. This version of
B<yaf> includes the updated CERT p0f fingerprints. See E<lt>https://tools.netsa.cert.org/confluence/display/tt/p0f+fingerprintsE<gt> for updates.
=item B<--fpexport>
If present, enable export of handshake headers for external OS fingerprinters. The related information elements are firstPacketBanner and secondPacketBanner. This flag requires B<yaf> to be configured with B<--enable-fpexporter>.
=back
=head1 OUTPUT X<OUTPUT>
=head2 Basic Flow Record
B<yaf>'s output consists of an IPFIX message stream. B<yaf> uses a variety of
templates for IPFIX data records; the information elements that may appear
in these templates are enumerated below. For further information about the IPFIX
information model and IPFIX message stream, see B<RFC 5102>, B<RFC 5101>, and
B<RFC 5103>. As of B<yaf> 2.0, B<yaf> nests some templates in an IPFIX
subTemplateMultiList. In order to retain compatibility with the SiLK Tools,
use B<--silk> to prevent B<yaf> from nesting TCP Information Elements. Below
are descriptions of each of the templates B<yaf> will export. See the
Internet-Draft B<Export of Structured Data in IPFIX> for more information on IPFIX lists.
B<yaf> assigns information element numbers to reverse flow elements in biflow
capture based on the standard IPFIX PEN 29305. This applies only for
information elements defined in the standard IPFIX Information Model
(B<RFC 5102>) that do not have a reverse information element already defined.
For information elements defined under the CERT PEN, a standard method is
used to calculate their reverse element identifier. The method is that
bit fourteen is set to one in the IE field, (e.g. 16384 + the forward IE number.)
=over 4
=item B<flowStartMilliseconds> IE 152, 8 octets, unsigned
Flow start time in milliseconds since 1970-01-01 00:00:00 UTC. Always present.
=item B<flowEndMilliseconds> IE 153, 8 octets, unsigned
Flow end time in milliseconds since 1970-01-01 00:00:00 UTC. Always present.
=item B<octetTotalCount> IE 85, 8 octets, unsigned
Number of octets in packets in forward direction of flow. Always present
(unless C<--delta> is used.) May be encoded in 4 octets using IPFIX
reduced-length encoding.
=item B<reverseOctetTotalCount> Reverse (PEN 29305) IE 85, 8 octets, unsigned
Number of octets in packets in reverse direction of flow. Present if flow
has a reverse direction. May be encoded in 4 octets using IPFIX
reduced-length encoding.
=item B<packetTotalCount> IE 86, 8 octets, unsigned
Number of packets in forward direction of flow. Always present
(unless C<--delta> is used.) May be encoded in 4 octets
using IPFIX reduced-length encoding.
=item B<reversePacketTotalCount> Reverse (PEN 29305) IE 86, 8 octets, unsigned
Number of packets in reverse direction of flow. Present if flow has a
reverse direction. May be encoded in 4 octets using IPFIX reduced-length
encoding.
=item B<octetDeltaCount> IE 1, 8 octets, unsigned
Number of octets in packets in forward direction of flow. Only
present if C<--delta> is used. May be encoded in 4 octets using IPFIX
reduced-length encoding.
=item B<reverseOctetDeltaCount> Reverse (PEN 29305) IE 1, 8 octets, unsigned
Number of octets in reverse direction of flow. Only present if C<--delta>
is used and non-zero. May be encoded in 4 octets using IPFIX
reduced-length encoding.
=item B<packetDeltaCount> IE 2, 8 octets, unsigned
Number of packets in forward direction of flow. Only present if C<--delta>
is used. May be encoded in 4 octets using IPFIX reduced-length encoding.
=item B<reversePacketDeltaCount> Reverse (PEN 29305) IE 2, 8 octets, unsigned
Number of packets in reverse direction of flow. Only present if
C<--delta> is used and non-zero. May be encoded in 4 octets using IPFIX
reduced-length encoding.
=item B<reverseFlowDeltaMilliseconds> CERT (PEN 6871) IE 21, 4 octets, unsigned
Difference in time in milliseconds between first packet in forward direction
and first packet in reverse direction. Correlates with (but does not
necessarily represent) round-trip time. Present if flow has a reverse
direction.
=item B<sourceIPv4Address> IE 8, 4 octets, unisigned
IPv4 address of flow source or biflow initiator. Present for IPv4
flows without IPv6-mapped addresses only.
=item B<destinationIPv4Address> IE 12, 4 octets, unsigned
IPv4 address of flow source or biflow responder. Present for IPv4
flows without IPv6-mapped addresses only.
=item B<sourceIPv6Address> IE 27, 16 octets, unsigned
IPv6 address of flow source or biflow initiator. Present for IPv6
flows or IPv6-mapped IPv4 flows only.
=item B<destinationIPv6Address> IE 28, 16 octets, unsigned
IPv6 address of flow source or biflow responder. Present for IPv6
flows or IPv6-mapped IPv4 flows only.
=item B<sourceTransportPort> IE 7, 2 octets, unsigned
TCP or UDP port on the flow source or biflow initiator endpoint.
Always present.
=item B<destinationTransportPort> IE 11, 2 octets, usigned
TCP or UDP port on the flow destination or biflow responder endpoint.
Always present. For ICMP flows, contains ICMP type * 256 + ICMP code.
This is non-standard, and an open issue in B<yaf>.
=item B<flowAttributes> CERT (PEN 6871) IE 40, 2 octets, unsigned
Miscellaneous flow attributes for the forward direction of the flow.
Always present (B<yaf> 2.1 or later). Current flag values:
=over 2
=item Bit 1: All packets in the forward direction have fixed size
For TCP flows, only packets that have payload will be considered (to avoid
TCP handshakes and teardowns).
=item Bit 2: Packet(s) in the forward direction was received out-of-sequence
=back
=item B<reverseFlowAttributes> CERT (PEN 6871) IE 16424, 2 octets, unsigned
Miscellaneous flow attributes for the reverse direction of the flow.
Always present (B<yaf> 2.1 or later). Current flag values:
=over 2
=item Bit 1: All packets in the reverse direction have fixed size
=item Bit 2: Packet(s) in the reverse direction was received out-of-sequence
=back
=item B<protocolIdentifier> IE 4, 1 octet, unsigned
IP protocol of the flow. Always present.
=item B<flowEndReason> IE 136, 1 octet, unsigned
Flow end reason code, as defined by the IPFIX Information Model.
Always present. In B<--silk> mode, the high-order bit is set if the flow
was created by continuation.
=item B<silkAppLabel> CERT (PEN 6871) IE 33, 2 octets, unsigned
Application label, defined as the primary well-known port associated
with a given application. Present if the application labeler is
enabled, and was able to determine the application protocol used
within the flow.
=item B<vlanId> IE 58, 2 octets, unsigned
802.1q VLAN tag of the first packet in the forward direction of the flow.
=item B<reverseVlanId> Reverse (PEN 29305) IE 58, 2 octets, unsigned
802.1q VLAN tag of the first packet in the reverse direction of the flow.
Present if the flow has a reverse direction.
=item B<ingressInterface> IE 10, 4 octets, unsigned
The index of the IP interface where packets of this flow are being received.
Use --ingress, --napatech-interface, --dag-interface or configure B<yaf> with
bivio for this field to be present in the flow template. Use --ingress to
manually set this field.
=item B<egressInterface> IE 14, 4 octets, unsigned
The index of the IP interface where packets of this flow are being received.
Use --egress, --napatech-interface, --dag-interface or configure B<yaf> with
bivio for this field to be present in the flow template. If using napatech, dag,
or bivio, C<egressinterface> will be the physical interface | 0x100. Use --egress
to manually set this field.
=item B<ipClassOfService> IE 5, 1 octet, unsigned
For IPv4 packets, this is the value of the TOS field in the IPv4 header. For
IPv6 packets, this is the Traffic Class field in the IPv6 header.
=item B<reverseIpClassOfService> Reverse (PEN 29305) IE 5, 1 octet, unsigned
The TOS field in the IPv4 header for packets in the reverse direction, and
Traffic Class field in the IPv6 header for packets in the reverse direction.
=item B<mplsTopLabelStackSection> IE 70, 3 octets
The MPLS Label from the top of the MPLS label stack entry. B<yaf>
does not include the Experimental bits and Bottom of the Stack bit in the
export field. B<yaf> must have been enabled with MPLS support for export
of this field. Note that this field is defined as an octet array in the
default libfixbuf Information Model. B<yaf> uses the length override
feature in libfixbuf to redefine it from variable length to 3 bytes.
=item B<mplsLabelStackSection2>, IE 71, 3 octets
The MPLS Label from the MPLS label stack entry immediately before the top
entry. B<yaf> does not include the Experimental bits and Bottom of the Stack bit in the
export field. B<yaf> must have been enabled with MPLS support for export
of this field. Note that this field is defined as an octet array in the
default libfixbuf Information Model. B<yaf> uses the length override
feature in libfixbuf to redefine it from variable length to 3 bytes.
=item B<mplsLabelStackSection3>, IE 72, 3 octets
The MPLS Label from the third entry in the MPLS label stack.
B<yaf> does not include the Experimental bits and Bottom of the Stack bit in the
export field. B<yaf> must have been enabled with MPLS support for export
of this field. Note that this field is defined as an octet array in the
default libfixbuf Information Model. B<yaf> uses the length override
feature in libfixbuf to redefine it from variable length to 3 bytes.
=item B<subTemplateMultiList> IE 293, variable length
Represents a list of zero or more instances of a structured data type, where
the data type of each list element can be different and corresponds with
different template definitions. The Information Element Number will change
upon updates to the IPFIX lists specification and libfixbuf releases.
=back
=head2 TCP Flow Template
The following six Information Elements will be exported as a template
within the subTemplateMultiList unless B<--silk> is used.
=over 4
=item B<tcpSequenceNumber> IE 184, 4 octets, unsigned
Initial sequence number of the forward direction of the flow. Present if
the flow's protocolIdentifier is 6 (TCP). This element is contained in the
B<yaf> TCP template within the subTemplateMultiList unless B<--silk> is used.
=item B<reverseTcpSequenceNumber> Reverse (PEN 29305) IE 184, 4 octets, unsigned
Initial sequence number of the reverse direction of the flow. Present if the
flow's protocolIdentifier is 6 (TCP) and the flow has a reverse direction.
This element is contained in the B<yaf> TCP template within the subTemplateMultiList unless B<--silk> is used.
=item B<initialTCPFlags> CERT (PEN 6871) IE 14, 1 octet, unsigned
TCP flags of initial packet in the forward direction of the flow.
Present if the flow's protocolIdentifier is 6 (TCP). This element is contained
in the B<yaf> TCP template within the subTemplateMultiList unless B<--silk> is used.
=item B<unionTCPFlags> CERT (PEN 6871) IE 15, 1 octet, unsigned
Union of TCP flags of all packets other than the initial packet
in the forward direction of the flow. Present if the flow's
protocolIdentifier is 6 (TCP). This element is contained in the
B<yaf> TCP template within the subTemplateMultiList unless B<--silk> is used.
=item B<reverseInitialTCPFlags> CERT (PEN 6871) IE 16398, 1 octet, unsigned
TCP flags of initial packet in the reverse direction of the flow.
Present if the flow's protocolIdentifier is 6 (TCP) and the flow
has a reverse direction. This element is contained in the
B<yaf> TCP template within the subTemplateMultiList unless B<--silk> is used.
=item B<reverseUnionTCPFlags> CERT (PEN 6871) IE 16399, 1 octet, unsigned
Union of TCP flags of all packets other than the initial packet
in the reverse direction of the flow. Present if the flow's
protocolIdentifier is 6 (TCP) and the flow has a reverse direction.
This element is contained in the B<yaf> TCP template within the subTemplateMultiList unless B<--silk> is used.
=back
=head2 MAC Flow Template
The following two Information Elements will be exported as a template
within the subTemplateMultiList.
=over 4
=item B<sourceMacAddress>, IE 56, 6 octets, unsigned
Source MAC Address of the first packet in the forward direction of the flow.
This element is contained in the B<yaf> MAC template within the subTemplateMultiList.
=item B<destinationMacAddress>, IE 80, 6 octets, unsigned
Destination MAC Address of the first packet in the reverse direction of the flow. This element is contained in the B<yaf> MAC template within the subTemplateMultiList.
=back
=head2 Payload Flow Template
The following two Information Elements will be exported as a template
within the subTemplateMultiList.
=over 4
=item B<payload> CERT (PEN 6871) IE 18, variable-length
Initial I<n> bytes of forward direction of flow payload.
Present if payload collection is enabled and payload is present
in the forward direction of the flow. This element is contained in the
B<yaf> Payload template within the subTemplateMultiList.
=item B<reversePayload> CERT (PEN 6871) IE 16402, variable-length
Initial I<n> bytes of reverse direction of flow payload.
Present if payload collection is enabled and payload is present
in the reverse direction of the flow. This element is contained in the B<yaf>
Payload template within the subTemplateMultiList.
=back
=head2 Entropy Flow Template
The following two Information Elements will be exported as a template
within the subTemplateMultiList.
=over 4
=item B<payloadEntropy> CERT (PEN 6871) IE 35, 1 octet, unsigned
Shannon Entropy calculation of the forward payload data. This element is
contained in the B<yaf> Entropy template within the subTemplateMultiList.
=item B<reversePayloadEntropy> CERT (PEN 6871) IE 16419, 1 octet, unsigned
Shannon Entropy calculation of the reverse payload data. This element is
contained in the B<yaf> Entropy template within the subTemplateMultiList.
=back
=head2 p0f Flow Template
The following six Information Elements will be exported as a template
within the subTemplateMultiList if present and only if p0f is enabled.
=over 4
=item B<osName> CERT (PEN 6871) IE 36, variable-length
p0f OS Name for the forward flow based on the SYN packet and p0f SYN Fingerprints. Present only if p0f is enabled. This element is contained in the B<yaf>
p0f template within the subTemplateMultiList.
=item B<reverseOsName> CERT (PEN 6871) IE 16420, variable-length
p0f OS Name for the reverse flow based on the SYN packet and p0f SYN Fingerprints. Present only if p0f is enabled. This element is contained in the B<yaf>
p0f template within the subTemplateMultiList.
=item B<osVersion> CERT (PEN 6871) IE 37, variable-length
p0f OS Version for the forward flow based on the SYN packet and p0f SYN Fingerprints. Present only if p0f is enabled. This element is contained in the
B<yaf> p0f template within the subTemplateMultiList.
=item B<reverseOsVersion> CERT (PEN 6871) IE 16421, variable-length
p0f OS Version for the reverse flow based on the SYN packet and p0f SYN fingerprints. Present only if p0f is enabled. This element is contained in the
B<yaf> p0f template within the subTemplateMultiList.
=item B<osFingerPrint> CERT (PEN 6871) IE 107, variable-length
p0f OS Fingerprint for the forward flow based on the SYN packet and p0f SYN fingerprints. Present only if p0f is enabled. This element is contained in the B<yaf> p0f template within the subTemplateMultiList.
=item B<reverseOsFingerPrint> CERT (PEN 6871) IE 16491, variable-length
p0f OS Fingerprint for the reverse flow based on the SYN packet and p0f SYN Fingerprints. Present only if p0f is enabled. This element is contained in the B<yaf> p0f template within the subTemplateMultiList.
=back
=head2 Fingerprint Exporting Template
The following four Information Elements will be exported as a template
within the subTemplateMultiList if present and only if fpexport is enabled.
=over 4
=item B<firstPacketBanner> CERT (PEN 6871) IE 38, variable-length
IP and transport headers for first packet in forward direction to be used for external OS Fingerprinters. Present only if fpexport is enabled. This element is contained in the B<yaf> FPExport template within the subTemplateMultiList.
=item B<reverseFirstPacketBanner> CERT (PEN 6871) IE 16422, variable-length
IP and transport headers for first packet in reverse direction to be used for external OS Fingerprinters. Present only if fpexport is enabled. This element is contained in the B<yaf> FPExport template within the subTemplateMultiList.
=item B<secondPacketBanner> CERT (PEN 6871) IE 39, variable-length
IP and transport headers for second packet in forward direction (third packet in sequence) to be used for external OS Fingerprinters. Present only if fpexport is enabled. This element is contained in the B<yaf> FPExport template within the subTemplateMultiList.
=item B<reverseSecondPacketBanner> CERT (PEN 6871) IE 16423, variable-length
IP and transport headers for second packet in reverse direction (currently not used). Present only if fpexport is enabled. This element is contained in the B<yaf> FPExport template within the subTemplateMultiList.
=back
=head2 Hooks Templates
B<yaf> can export other templates within the subTemplateMultiList
if plugins are enabled in B<yaf>. See B<yafdpi(1)> for descriptions
of the B<yaf> Deep Packet Inspection Information Elements. See B<yafdhcp(1)>
for descriptions of the DHCP Fingerprint Information Elements.
=head2 Flow Statistics Template
B<yaf> can maintain and export more information about each flow than what
is exported in the Basic Flow Template. If B<yaf> is run with B<--flow-stats>
B<yaf> will export the following attributes with every flow as long as one
of the following characteristics is nonzero. The following flow attributes
have been known to help in traffic classification.
=over 4
=item B<dataByteCount> CERT (PEN 6871) IE 502, 8 octets, unsigned
Total bytes transferred as payload.
=item B<averageInterarrivalTime> CERT (PEN 6871) IE 503, 8 octets, unsigned
Average number of milliseconds between packets.
=item B<standardDeviationInterarrivalTime> CERT (PEN 6871) IE 504, 8 octets, unsigned
Standard deviation of the interarrival time for up to the first ten packets.
=item B<tcpUrgTotalCount> CERT (PEN 6871) IE 509, 4 octets, unsigned
The number of TCP packets that have the URGENT Flag set.
=item B<smallPacketCount> CERT (PEN 6871) IE 500, 4 octets, unsigned
The number of packets that contain less than 60 bytes of payload.
=item B<nonEmptyPacketCount> CERT (PEN 6871) IE 501, 4 octets, unsigned
The number of packets that contain at least 1 byte of payload.
=item B<largePacketCount> CERT (PEN 6871) IE 510, 4 octets, unsigned
The number of packets that contain at least 220 bytes of payload.
=item B<firstNonEmptyPacketSize> CERT (PEN 6871) IE 505, 2 octets, unsigned
Payload length of the first non-empty packet.
=item B<maxPacketSize> CERT (PEN 6871) IE 506, 2 octets, unsigned
The largest payload length transferred in the flow.
=item B<standardDeviationPayloadLength> CERT (PEN 6871) IE 508, 2 octets, unsigned
The standard deviation of the payload length for up to the first 10 non empty
packets.
=item B<firstEightNonEmptyPacketDirections> CERT (PEN 6871) IE 507, 1 octet, unsigned
Represents directionality for the first 8 non-empty packets. 0 for forward
direction, 1 for reverse direction.
=item B<reverseDataByteCount> CERT (PEN 6871) IE 16886, 8 octets, unsigned
Total bytes transferred as payload in the reverse direction.
=item B<reverseAverageInterarrivalTime> CERT (PEN 6871) IE 16887, 8 octets, unsigned
Average number of milliseconds between packets in reverse direction.
=item B<reverseStandardDeviationInterarrivalTime> CERT (PEN 6871) IE 16888, 8 octets, unsigned
Standard deviation of the interarrival time for up to the first ten packets
in the reverse direction.
=item B<reverseTcpUrgTotalCount> CERT (PEN 6871) IE 16896, 4 octets, unsigned
The number of TCP packets that have the URGENT Flag set in the reverse
direction.
=item B<reverseSmallPacketCount> CERT (PEN 6871) IE 16884, 4 octets, unsigned
The number of packets that contain less than 60 bytes of payload in reverse
direciton.
=item B<reverseNonEmptyPacketCount> CERT (PEN 6871) IE 16885, 4 octets, unsigned
The number of packets that contain at least 1 byte of payload in reverse
direction.
=item B<reverseLargePacketCount> CERT (PEN 6871) IE 16894, 4 octets, unsigned
The number of packets that contain at least 220 bytes of payload in the
reverse direction.
=item B<reverseFirstNonEmptyPacketSize> CERT (PEN 6871) IE 16889, 2 octets, unsigned
Payload length of the first non-empty packet in the reverse direction.
=item B<reverseMaxPacketSize> CERT (PEN 6871) IE 16890, 2 octets, unsigned
The largest payload length transferred in the flow in the reverse direction.
=item B<reverseStandardDeviationPayloadLength> CERT (PEN 6871) IE 16892, 2 octets, unsigned
The standard deviation of the payload length for up to the first 10 non empty
packets in the reverse direction.
=back
=head2 Statistics Option Template
B<yaf> will export information about its process periodically
using IPFIX Options Template Record. This record gives information
about the status of the flow and fragment table, as well as decoding
information. This can be turned off using the B<--no-stats> option.
The following Information Elements will be exported:
=over 4
=item B<systemInitTimeMilliseconds> IE 161, 8 octets, unsigned
The time in milliseconds of the last (re-)initialization of B<yaf>.
=item B<exportedFlowRecordTotalCount> IE 42, 8 octets, unsigned
Total amount of exported flows from B<yaf> start time.
=item B<packetTotalCount> IE 86, 8 octets, unsigned
Total amount of packets processed by B<yaf> from B<yaf> start time.
=item B<droppedPacketTotalCount> IE 135, 8 octets, unsigned
Total amount of dropped packets according to statistics given
by libpcap, libdag, or the Napatech or Netronome APIs.
=item B<ignoredPacketTotalCount> IE 164, 8 octets, unsigned
Total amount of packets ignored by the B<yaf> packet decoder, such as
unsupported packet types and incomplete headers, from B<yaf>
start time.
=item B<notSentPacketTotalCount> IE 167, 8 octets, unsigned
Total amount of packets rejected by B<yaf> because they were received
out of sequence.
=item B<expiredFragmentCount> CERT (PEN 6871) IE 100, 4 octets, unsigned
Total amount of fragments that have been expired since B<yaf>
start time.
=item B<assembledFragmentCount> CERT (PEN 6871) IE 101, 4 octets, unsigned
Total number of packets that been assembled from a series of
fragments since B<yaf> start time.
=item B<flowTableFlushEventCount> CERT (PEN 6871) IE 104, 4 octets, unsigned
Total number of times the B<yaf> flow table has been flushed
since B<yaf> start time.
=item B<flowTablePeakCount> CERT (PEN 6871) IE 105, 4 octets, unsigned
The maximum number of flows in the B<yaf> flow table at any
one time since B<yaf> start time.
=item B<exporterIPv4Address> IE 130, 4 octets, unsigned
The IPv4 Address of the B<yaf> flow sensor.
=item B<exportingProcessId> IE 144, 4 octets, unsigned
Set the ID of the B<yaf> flow sensor by giving a value to
B<--observation-domain>. The default is 0.
=item B<meanFlowRate> CERT (PEN 6871) IE 102, 4 octets, unsigned
The mean flow rate of the B<yaf> flow sensor since B<yaf> start time,
rounded to the nearest integer.
=item B<meanPacketRate> CERT (PEN 6871) IE 103, 4 octets, unsigned
The mean packet rate of the B<yaf> flow sensor since B<yaf> start time,
rounded to the nearest integer.
=back
=head1 SIGNALS
B<yaf> responds to B<SIGINT> or B<SIGTERM> by terminating input processing,
flushing any pending flows to the current output, and exiting. If B<--verbose>
is given, B<yaf> responds to B<SIGUSR1> by printing present flow and fragment table
statistics to its log. All other signals are handled by the C runtimes in
the default manner on the platform on which B<yaf> is currently operating.
=head1 EXAMPLES
To generate flows from an pcap file into an IPFIX file:
C<yaf --in packets.pcap --out flows.yaf>
To capture flows from a pcap interface and export them to files in the
current directory rotated hourly:
C<yaf --live pcap --in en1 --out en1_capture --rotate 3600>
To capture flows from an Endace DAG card and export them via IPFIX over TCP:
C<yaf --live dag --in dag0 --ipfix tcp --out my-collector.example.com>
To capture flows from a Napatech Adapter card using stream ID 20 and export them via IPFIX over UDP:
C<yaf --live napatech --in nt3g20 --ipfix udp --out localhost --ipfix-port 18000>
To capture flows from a Netronome NFE card and export to a file:
C<yaf --live netronome --in 0:0 --out /data/yaf/myipfix.yaf>
To convert a pcap formatted packet capture into IPFIX:
C<yaf E<lt>packets.pcap E<gt>flows.yaf>
To publish to spread group B<TST_SPRD> for a spread daemon running locally on port 4803:
C<yaf --live pcap --in eth1 --out 4803@localhost --ipfix spread --group TST_SPRD>
To publish to spread groups based on application label for spread daemon running locally on port 4803:
C<yaf --live pcap --in eth1 --out 4803@localhost --ipfix spread --group "SPRD_CATCHALL, SPRD_DNS:53, SPRD_HTTP:80, SPRD_SMTP:25" --groupby applabel --applabel --max-payload=400>
To run B<yaf> with application labeling enabled and export via IPFIX over TCP:
C<yaf --live pcap --in eth1 --out 127.0.0.1 --ipfix tcp --ipfix-port=18001 --applabel --applabel-rules=/usr/local/etc/yafApplabelRules.conf --max-payload=300>
To run B<yaf> with BPF on UDP Port 53
C<yaf --live pcap --in en1 --out /path/to/dst/ --rotate 120 --filter="udp port 53">
To run B<yaf> with Deep Packet Inspection enabled for HTTP, IMAP, and DNS:
C<yaf --in packets.pcap --out flows.yaf --applabel --max-payload=400 --plugin-name=/usr/local/lib/dpacketplugin.la --plugin-opts="80 143 53">
To run B<yaf> with Deep Packet Inspection and DHCP Fingerprinting:
C<yaf --in packets.pcap --out flows.yaf --applabel --max-payload=1000 --plugin-name=/usr/local/lib/dpacketplugin.la,/usr/local/lib/dhcp_fp_plugin.la>
To run B<yaf> with pcap generation:
C<yaf --in eth0 --live pcap --out localhost --ipfix tcp --ipfix-port=18001 --pcap /data/pcap --pcap-meta-file=/data/pcap_info>
To generate a pcap file for one particular flow in a pcap:
C<yaf --in packets.pcap --no-output --max-payload=2000 --pcap /data/oneflow.pcap --hash 2181525080 --stime 1407607897547>
=head1 KNOWN ISSUES
YAF BPF Filtering is ignored when using B<--live> I<dag>, I<napatech>, or
I<netronome> because libpcap is not used.
YAF PCAP Export options are ignored when using B<--live> I<dag>, I<napatech>,
or I<netronome>.
YAF 2.x requires libfixbuf 1.0.0 or later.
YAF 2.0 will not interoperate with the SiLK tools unless B<--silk> is used, due
to the TCP Information Elements being nested in the subTemplateMultiList.
YAF 2.0 must be used with an IPFIX Collecting Process that can handle IPFIX lists elements, especially the subTemplateMultiList Information Element in order to retrieve certain flow information. Older versions of YAF can read YAF 2.0 flow files, but will ignore anything contained in the subTemplateMultiList.
The plugin infrastructure has been modified in YAF 2.0 to export templates
in YAF's subTemplateMultiList element.
YAF 2.0 will export statistics in an Options Template and Options Data Records
unless the B<--no-stats> switch is given. The IPFIX Collecting Process should be
able to differentiate between options records and flow records in order to
prevent incorrect transcoding of statistics records into flow records.
YAF will not rotate output files if it is not seeing any flow data. However,
it will continue to write process statistics messages at the configured
interval time to the most recent output file.
Presently, the B<destinationTransportPort> information element contains
ICMP type and code information for ICMP or ICMP6 flows; this is nonstandard
and may not be interoperable with other IPFIX implementations.
Bug reports and feature requests may be sent via email to
E<lt>netsa-help@cert.orgE<gt>.
=head1 AUTHORS
Brian Trammell, Chris Inacio,
Michael Duggan, Emily Sarneso, Dan Ruef,
and the CERT Network Situational Awareness Group Engineering Team,
E<lt>http://www.cert.org/netsaE<gt>.
=head1 SEE ALSO
B<yafscii(1)>, B<tcpdump(1)>, B<pcap(3)>, B<nafalize(1)>, Spread Documentation at www.spread.org, libp0f at E<lt>https://tools.netsa.cert.org/confluence/display/tt/libp0fE<gt>, and the following IETF
Internet RFCs: Specification of the IPFIX Protocol for the Exchange of IP
Traffic Flow Information B<RFC 5101>, Information Model for IP Flow Information
Export B<RFC 5102>, Bidirectional Flow Export using IPFIX B<RFC 5103>, Export of
Structured Data in IPFIX B<RFC 6313>
=cut |
import 'dart:convert';
// import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:badges/badges.dart';
import '../../api_connection/api_connection.dart';
import '../cart/cart_list_screen.dart';
import '../cart/cart_list_screen1.dart';
import '../controllers/cart_list_controller.dart';
import '../controllers/item_details_controller.dart';
import '../model/Clothes1.dart';
import '../model/cart.dart';
import '../model/clothes.dart';
import '../userPreferences/current_user.dart';
class ItemDetailsScreen extends StatefulWidget
{
final Clothes1? itemInfo;
ItemDetailsScreen({this.itemInfo,});
@override
State<ItemDetailsScreen> createState() => _ItemDetailsScreenState();
}
class _ItemDetailsScreenState extends State<ItemDetailsScreen>
{
final itemDetailsController = Get.put(ItemDetailsController());
final currentOnlineUser = Get.put(CurrentUser());
// final cartListController = Get.put(CartListController());
addItemToCart() async
{
try
{
var res = await http.post(
Uri.parse(API.addToCart),
body: {
"user_id": currentOnlineUser.user.user_id.toString(),
"item_id": widget.itemInfo!.item_id.toString(),
"quantity": itemDetailsController.quantity.toString(),
// "color": widget.itemInfo!.colors![itemDetailsController.color],
"size": widget.itemInfo!.sizes!,
// "size": widget.itemInfo!.sizes![itemDetailsController.size],
},
);
if(res.statusCode == 200) //from flutter app the connection with api to server - success
{
var resBodyOfAddCart = jsonDecode(res.body);
if(resBodyOfAddCart['success'] == true)
{
Fluttertoast.showToast(msg: "item added to Cart Successfully\n Go to cart to place your order");
}
else
{
Fluttertoast.showToast(msg: "Item already added to cart");
// Fluttertoast.showToast(msg: "Error Occur. Item not saved to Cart and Try Again.");
}
}
else
{
Fluttertoast.showToast(msg: "Status is not 200");
}
}
catch(errorMsg)
{
print("Error :: " + errorMsg.toString());
}
}
// getCurrentUserCartList() async
// {
// List<Cart> cartListOfCurrentUser = [];
//
// try
// {
// var res = await http.post(
// Uri.parse(API.getCartList),
// body:
// {
// "currentOnlineUserID": currentOnlineUser.user.user_id.toString(),
// }
// );
//
// if (res.statusCode == 200)
// {
// var responseBodyOfGetCurrentUserCartItems = jsonDecode(res.body);
//
// if (responseBodyOfGetCurrentUserCartItems['success'] == true)
// {
// (responseBodyOfGetCurrentUserCartItems['currentUserCartData'] as List).forEach((eachCurrentUserCartItemData)
// {
// cartListOfCurrentUser.add(Cart.fromJson(eachCurrentUserCartItemData));
// });
// }
// else
// {
// Fluttertoast.showToast(msg: "your Cart List is Empty.");
// }
//
// cartListController.setList(cartListOfCurrentUser);
// if(cartListController.cartList.length>0)
// {
// cartListController.cartList.forEach((eachItem)
// {
// cartListController.addSelectedItem(eachItem.cart_id!);
// });
// }
//
// // calculateTotalAmount();
//
// }
// else
// {
// Fluttertoast.showToast(msg: "Status Code is not 200");
// }
// }
// catch(errorMsg)
// {
// Fluttertoast.showToast(msg: "Error:: " + errorMsg.toString());
// }
// // calculateTotalAmount();
// }
validateFavoriteList() async
{
try
{
var res = await http.post(
Uri.parse(API.validateFavorite),
body: {
"user_id": currentOnlineUser.user.user_id.toString(),
"item_id": widget.itemInfo!.item_id.toString(),
},
);
if(res.statusCode == 200) //from flutter app the connection with api to server - success
{
var resBodyOfValidateFavorite = jsonDecode(res.body);
if(resBodyOfValidateFavorite['favoriteFound'] == true)
{
itemDetailsController.setIsFavorite(true);
}
else
{
itemDetailsController.setIsFavorite(false);
}
}
else
{
Fluttertoast.showToast(msg: "Status is not 200");
}
}
catch(errorMsg)
{
print("Error :: " + errorMsg.toString());
}
}
addItemToFavoriteList() async
{
try
{
var res = await http.post(
Uri.parse(API.addFavorite),
body: {
"user_id": currentOnlineUser.user.user_id.toString(),
"item_id": widget.itemInfo!.item_id.toString(),
},
);
if(res.statusCode == 200) //from flutter app the connection with api to server - success
{
var resBodyOfAddFavorite = jsonDecode(res.body);
if(resBodyOfAddFavorite['success'] == true)
{
Fluttertoast.showToast(msg: "item saved to your Favorite List Successfully.");
validateFavoriteList();
}
else
{
Fluttertoast.showToast(msg: "Item not saved to your Favorite List.");
}
}
else
{
Fluttertoast.showToast(msg: "Status is not 200");
}
}
catch(errorMsg)
{
print("Error :: " + errorMsg.toString());
}
}
deleteItemFromFavoriteList() async
{
try
{
var res = await http.post(
Uri.parse(API.deleteFavorite),
body: {
"user_id": currentOnlineUser.user.user_id.toString(),
"item_id": widget.itemInfo!.item_id.toString(),
},
);
if(res.statusCode == 200) //from flutter app the connection with api to server - success
{
var resBodyOfDeleteFavorite = jsonDecode(res.body);
if(resBodyOfDeleteFavorite['success'] == true)
{
Fluttertoast.showToast(msg: "item Deleted from your Favorite List.");
validateFavoriteList();
}
else
{
Fluttertoast.showToast(msg: "item NOT Deleted from your Favorite List.");
}
}
else
{
Fluttertoast.showToast(msg: "Status is not 200");
}
}
catch(errorMsg)
{
print("Error :: " + errorMsg.toString());
}
}
@override
void initState() {
super.initState();
validateFavoriteList();
// getCurrentUserCartList();
}
@override
Widget build(BuildContext context)
{
widget.itemInfo!.outofstock.toString()=="Out of Stock"?
itemDetailsController.setOutofStockStatus("Out of Stock"):
itemDetailsController.setOutofStockStatus("Available");
return SafeArea(
child: Scaffold(
backgroundColor: Colors.white,
// appBar: buildAppBar(),
body: Stack(
children: [
//item image
FadeInImage(
height: MediaQuery.of(context).size.height * 0.5,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
placeholder: const AssetImage("images/place_holder.png"),
image: NetworkImage(
widget.itemInfo!.image!,
),
imageErrorBuilder: (context, error, stackTraceError)
{
return const Center(
child: Icon(
Icons.broken_image_outlined,
),
);
},
),
//item information
Align(
alignment: Alignment.bottomCenter,
child: itemInfoWidget(),
),
//3 buttons || back - favorite - shopping cart
Positioned(
top: MediaQuery.of(context).padding.top,
left: 0,
right: 0,
child: Container(
color: Colors.transparent,
child: Row(
children: [
//back
IconButton(
onPressed: ()
{
Get.back();
},
icon: const Icon(
Icons.arrow_back,
color: Colors.orangeAccent,
),
),
const Spacer(),
//favorite
Obx(()=> IconButton(
onPressed: ()
{
if(itemDetailsController.isFavorite == true)
{
//delete item from favorites
deleteItemFromFavoriteList();
}
else
{
//save item to user favorites
addItemToFavoriteList();
}
},
icon: Icon(
itemDetailsController.isFavorite
? Icons.bookmark
: Icons.bookmark_border_outlined,
color: Colors.orangeAccent,
),
)),
//shopping cart icon
IconButton(
onPressed: ()
{
Get.to(CartListScreen1());
},
icon: const Icon(
Icons.shopping_cart,
color: Colors.orangeAccent,
),
),
],
),
),
),
],
),
),
);
}
itemInfoWidget()
{
return Container(
height: MediaQuery.of(Get.context!).size.height * 0.6,
width: MediaQuery.of(Get.context!).size.width,
decoration: const BoxDecoration(
color: Colors.white70,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30),
),
boxShadow: [
BoxShadow(
offset: Offset(0, -3),
blurRadius: 6,
color: Colors.orangeAccent,
),
],
),
padding: const EdgeInsets.symmetric(horizontal: 16),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 18,),
Center(
child: Container(
height: 8,
width: 140,
decoration: BoxDecoration(
color: Colors.orangeAccent,
borderRadius: BorderRadius.circular(30),
),
),
),
const SizedBox(height: 30,),
//name
Text(
widget.itemInfo!.name!,
maxLines: 4,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 24,
color: Colors.black87,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10,),
//rating + rating num
//tags
//price
//quantity item counter
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//rating + rating num
//tags
//price
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//rating + rating num
Row(
children: [
// //rating bar
// RatingBar.builder(
// initialRating: widget.itemInfo!.rating!,
// minRating: 1,
// direction: Axis.horizontal,
// allowHalfRating: true,
// itemCount: 5,
// itemBuilder: (context, c)=> const Icon(
// Icons.star,
// color: Colors.amber,
// ),
// onRatingUpdate: (updateRating){},
// ignoreGestures: true,
// unratedColor: Colors.grey,
// itemSize: 20,
// ),
//
// const SizedBox(width: 8,),
//rating num
// Text(
// "(\₹" + widget.itemInfo!.subtext.toString() + ")",
// style: const TextStyle(
// color: Colors.black87,
// ),
// maxLines: 4,
// overflow: TextOverflow.ellipsis,
// ),
],
),
Text(
"(\₹" + widget.itemInfo!.subtext.toString() + ")",
style: const TextStyle(
color: Colors.black87,
),
maxLines: 4,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 10),
widget.itemInfo!.outofstock.toString()=="Out of Stock"?
(Wrap(
runSpacing: 8,
spacing: 8,
children: [
Container(
height: 35,
width: 150,
decoration: BoxDecoration(
border: Border.all(
width: 2,
color: Colors.black87
),
// color:Colors.black
),
alignment: Alignment.center,
child: Text(
widget.itemInfo!.outofstock!.toString(),
style: TextStyle(
fontSize: 20,
color: Colors.black,
),
),
),
],
)
)
:Text(""),
// //tags
// Text(
// widget.itemInfo!.tags!.toString().replaceAll("[", "").replaceAll("]", ""),
// maxLines: 2,
// overflow: TextOverflow.ellipsis,
// style: const TextStyle(
// fontSize: 16,
// color: Colors.grey,
// ),
// ),
const SizedBox(height: 16),
//price
Text(
"\₹" + widget.itemInfo!.price.toString(),
style: const TextStyle(
fontSize: 24,
color: Colors.orangeAccent,
fontWeight: FontWeight.bold,
),
),
//availability status
],
),
),
//quantity item counter
Obx(
()=> Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
//+
IconButton(
onPressed: ()
{
itemDetailsController.setQuantityItem(itemDetailsController.quantity + 1);
},
icon: const Icon(Icons.add_circle_outline, color: Colors.black,size: 28),
),
Text(
itemDetailsController.quantity.toString(),
style: const TextStyle(
fontSize: 24,
color: Colors.orangeAccent,
fontWeight: FontWeight.bold,
),
),
//-
IconButton(
onPressed: ()
{
if(itemDetailsController.quantity - 1 >= 1)
{
itemDetailsController.setQuantityItem(itemDetailsController.quantity - 1);
}
else
{
Fluttertoast.showToast(msg: "Quantity must be 1 or greater than 1");
}
},
icon: const Icon(Icons.remove_circle_outline, color: Colors.black,size: 28),
),
],
),
),
],
),
//sizes
const Text(
"Size:",
style: TextStyle(
fontSize: 18,
color: Colors.orangeAccent,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
// Wrap(
// runSpacing: 8,
// spacing: 8,
// children: List.generate(widget.itemInfo!.sizes!.length, (index)
// {
// return Obx(
// ()=> GestureDetector(
// onTap: ()
// {
// itemDetailsController.setSizeItem(index);
// },
// child: Container(
// height: 35,
// width: 100,
// decoration: BoxDecoration(
// border: Border.all(
// width: 2,
// color: itemDetailsController.size == index
// ? Colors.transparent
// : Colors.grey,
// ),
// color: itemDetailsController.size == index
// ? Colors.orangeAccent.withOpacity(0.4)
// : Colors.black,
// ),
// alignment: Alignment.center,
// child: Text(
// widget.itemInfo!.sizes!,
// style: TextStyle(
// fontSize: 16,
// color: Colors.grey[700],
// ),
// ),
// ),
// ),
// );
// }),
// ),
Wrap(
runSpacing: 8,
spacing: 8,
children: [
Container(
height: 35,
width: 100,
decoration: BoxDecoration(
border: Border.all(
width: 2,
color: Colors.black87
),
// color:Colors.black
),
alignment: Alignment.center,
child: Text(
widget.itemInfo!.sizes!,
style: TextStyle(
fontSize: 16,
color: Colors.black,
),
),
),
]
),
const SizedBox(height: 20),
//colors
// const Text(
// "Color:",
// style: TextStyle(
// fontSize: 18,
// color: Colors.orangeAccent,
// fontWeight: FontWeight.bold,
// ),
// ),
// const SizedBox(height: 8),
// Wrap(
// runSpacing: 8,
// spacing: 8,
// children: List.generate(widget.itemInfo!.colors!.length, (index)
// {
// return Obx(
// ()=> GestureDetector(
// onTap: ()
// {
// itemDetailsController.setColorItem(index);
// },
// child: Container(
// height: 35,
// width: 60,
// decoration: BoxDecoration(
// border: Border.all(
// width: 2,
// color: itemDetailsController.color == index
// ? Colors.transparent
// : Colors.grey,
// ),
// color: itemDetailsController.color == index
// ? Colors.orangeAccent.withOpacity(0.4)
// : Colors.black,
// ),
// alignment: Alignment.center,
// child: Text(
// widget.itemInfo!.colors![index].replaceAll("[", "").replaceAll("]", ""),
// style: TextStyle(
// fontSize: 16,
// color: Colors.grey[700],
// ),
// ),
// ),
// ),
// );
// }),
// ),
// const SizedBox(height: 20),
//description
const Text(
"Description:",
style: TextStyle(
fontSize: 18,
color: Colors.orangeAccent,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
widget.itemInfo!.description!,
textAlign: TextAlign.justify,
style: const TextStyle(
color: Colors.black87,
),
),
const SizedBox(height: 30),
//add to cart button
Material(
elevation: 4,
color: Colors.orangeAccent,
borderRadius: BorderRadius.circular(10),
child: InkWell(
onTap: ()
{
itemDetailsController.outofchickenStatus=="Out of Stock"?
Fluttertoast.showToast(msg: "Item is currently Out of Stock")
:addItemToCart();
itemDetailsController.setFakeCartCount(1);
},
borderRadius: BorderRadius.circular(10),
child: Container(
alignment: Alignment.center,
height: 50,
child: const Text(
"Add to Cart",
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
),
),
),
const SizedBox(height: 15),
Obx(()=>
itemDetailsController.fakeCartCount>0?
Material(
elevation: 4,
color: Colors.orangeAccent,
borderRadius: BorderRadius.circular(10),
child: InkWell(
onTap: ()
{
Get.to(CartListScreen1());
},
borderRadius: BorderRadius.circular(10),
child: Container(
alignment: Alignment.center,
height: 50,
child: const Text(
"Go to Cart",
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
),
),
):
// Material(
// elevation: 4,
// color: Colors.orangeAccent,
// borderRadius: BorderRadius.circular(10),
// child: InkWell(
// onTap: ()
// {
// Get.to(CartListScreen1());
// },
// borderRadius: BorderRadius.circular(10),
// child: Container(
// alignment: Alignment.center,
// height: 50,
// child: const Text(
// "Add to Cart",
// style: TextStyle(
// fontSize: 20,
// color: Colors.white,
// ),
// ),
// ),
// ),
// ),
const SizedBox(height: 30),),
],
),
),
);
}
// AppBar buildAppBar() {
// return AppBar(
// backgroundColor: Colors.transparent,
// elevation:0,
// leading: IconButton(
// onPressed: () { },
// icon: Icon(Icons.arrow_back,color: Colors.orange,),
//
// ),
// actions:[
// IconButton(
// onPressed: ()
// {
// Get.back();
// },
// icon: const Icon(
// Icons.arrow_back,
// color: Colors.orangeAccent,
// ),
// ),
// const Spacer(),
// //favorite
// Obx(()=> IconButton(
// onPressed: ()
// {
// if(itemDetailsController.isFavorite == true)
// {
// //delete item from favorites
// deleteItemFromFavoriteList();
// }
// else
// {
// //save item to user favorites
// addItemToFavoriteList();
// }
// },
// icon: Icon(
// itemDetailsController.isFavorite
// ? Icons.bookmark
// : Icons.bookmark_border_outlined,
// color: Colors.orangeAccent,
// ),
// )),
// //shopping cart icon
//
// IconButton(
// onPressed: ()
// {
// Get.to(CartListScreen());
// },
// icon: const Icon(
// Icons.shopping_cart,
// color: Colors.orangeAccent,
// ),
//
//
// ),
//
// Badge(
// badgeContent: Text(
// '5',
// style: TextStyle(color: Colors.white, fontSize: 30),
// ),
// badgeColor: Colors.green,
// child: Icon(Icons.person, size: 50),
// ),
// ]
// );
// }
} |
package org.jeecgframework.web.cgform.engine;
import java.io.IOException;
import java.util.Locale;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.jeecgframework.web.cgform.common.CgAutoListConstant;
import org.jeecgframework.web.cgform.service.config.CgFormFieldServiceI;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.jeecgframework.core.util.PropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateDirectiveModel;
@Component("templetContext")
public class TempletContext {
@Resource(name = "freemarker")
private Configuration freemarker;
@Autowired
private CgFormFieldServiceI cgFormFieldService;
private Map<String, TemplateDirectiveModel> tags;
private static final String ENCODING = "UTF-8";
private static Cache ehCache;//ehcache
/**
* 系统模式:
* PUB-生产(使用ehcache)
* DEV-开发
*/
private static String _sysMode = null;
static{
PropertiesUtil util = new PropertiesUtil("sysConfig.properties");
_sysMode = util.readProperty(CgAutoListConstant.SYS_MODE_KEY);
if(CgAutoListConstant.SYS_MODE_PUB.equalsIgnoreCase(_sysMode)){
ehCache = CacheManager.getInstance().getCache("dictCache");//永久缓存块
}
}
@PostConstruct
public void init() {
if (tags == null)
return;
for (String key : tags.keySet()) {
freemarker.setSharedVariable(key, tags.get(key));
}
}
public Locale getLocale() {
return freemarker.getLocale();
}
public Template getTemplate(String tableName) {
Template template = null;
if (tableName == null) {
return null;
}
try {
if(CgAutoListConstant.SYS_MODE_DEV.equalsIgnoreCase(_sysMode)){//开发模式
template = freemarker.getTemplate(tableName,freemarker.getLocale(), ENCODING);
}else if(CgAutoListConstant.SYS_MODE_PUB.equalsIgnoreCase(_sysMode)){//生产模式(缓存)
//获取版本号
String version = cgFormFieldService.getCgFormVersionByTableName(tableName);
template = getTemplateFromCache(tableName, ENCODING,version);
}else{
throw new RuntimeException("sysConfig.properties的freeMarkerMode配置错误:(PUB:生产模式,DEV:开发模式)");
}
return template;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 从缓存中读取ftl模板
* @param template
* @param encoding
* @return
*/
public Template getTemplateFromCache(String tableName,String encoding,String version){
Template template = null;
try {
//cache的键:类名.方法名.参数名
String cacheKey = FreemarkerHelper.class.getName()+".getTemplateFormCache."+tableName+"."+version;
Element element = ehCache.get(cacheKey);
if(element==null){
template = freemarker.getTemplate(tableName,freemarker.getLocale(), ENCODING);
element = new Element(cacheKey, template);
ehCache.put(element);
}else{
template = (Template)element.getObjectValue();
}
} catch (IOException e) {
e.printStackTrace();
}
return template;
}
public Configuration getFreemarker() {
return freemarker;
}
public void setFreemarker(Configuration freemarker) {
this.freemarker = freemarker;
}
public Map<String, TemplateDirectiveModel> getTags() {
return tags;
}
public void setTags(Map<String, TemplateDirectiveModel> tags) {
this.tags = tags;
}
} |
(function() {
'use strict';
angular
.module('mlcccApp')
.config(stateConfig);
stateConfig.$inject = ['$stateProvider'];
function stateConfig($stateProvider) {
$stateProvider
.state('discount', {
parent: 'entity',
url: '/discount',
data: {
authorities: ['ROLE_USER'],
pageTitle: 'Discounts'
},
views: {
'content@': {
templateUrl: 'app/entities/discount/discounts.html',
controller: 'DiscountController',
controllerAs: 'vm'
}
},
resolve: {
}
})
.state('discount-detail', {
parent: 'discount',
url: '/discount/{id}',
data: {
authorities: ['ROLE_USER'],
pageTitle: 'Discount'
},
views: {
'content@': {
templateUrl: 'app/entities/discount/discount-detail.html',
controller: 'DiscountDetailController',
controllerAs: 'vm'
}
},
resolve: {
entity: ['$stateParams', 'Discount', function($stateParams, Discount) {
return Discount.get({id : $stateParams.id}).$promise;
}],
previousState: ["$state", function ($state) {
var currentStateData = {
name: $state.current.name || 'discount',
params: $state.params,
url: $state.href($state.current.name, $state.params)
};
return currentStateData;
}]
}
})
.state('discount-detail.edit', {
parent: 'discount-detail',
url: '/detail/edit',
data: {
authorities: ['ROLE_USER']
},
onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
$uibModal.open({
templateUrl: 'app/entities/discount/discount-dialog.html',
controller: 'DiscountDialogController',
controllerAs: 'vm',
backdrop: 'static',
size: 'lg',
resolve: {
entity: ['Discount', function(Discount) {
return Discount.get({id : $stateParams.id}).$promise;
}]
}
}).result.then(function() {
$state.go('^', {}, { reload: false });
}, function() {
$state.go('^');
});
}]
})
.state('discount.new', {
parent: 'discount',
url: '/new',
data: {
authorities: ['ROLE_USER']
},
onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
$uibModal.open({
templateUrl: 'app/entities/discount/discount-dialog.html',
controller: 'DiscountDialogController',
controllerAs: 'vm',
backdrop: 'static',
size: 'lg',
resolve: {
entity: function () {
return {
amount: null,
startDate: null,
endDate: null,
id: null
};
}
}
}).result.then(function() {
$state.go('discount', null, { reload: 'discount' });
}, function() {
$state.go('discount');
});
}]
})
.state('discount.edit', {
parent: 'discount',
url: '/{id}/edit',
data: {
authorities: ['ROLE_USER']
},
onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
$uibModal.open({
templateUrl: 'app/entities/discount/discount-dialog.html',
controller: 'DiscountDialogController',
controllerAs: 'vm',
backdrop: 'static',
size: 'lg',
resolve: {
entity: ['Discount', function(Discount) {
return Discount.get({id : $stateParams.id}).$promise;
}]
}
}).result.then(function() {
$state.go('discount', null, { reload: 'discount' });
}, function() {
$state.go('^');
});
}]
})
.state('discount.delete', {
parent: 'discount',
url: '/{id}/delete',
data: {
authorities: ['ROLE_USER']
},
onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
$uibModal.open({
templateUrl: 'app/entities/discount/discount-delete-dialog.html',
controller: 'DiscountDeleteController',
controllerAs: 'vm',
size: 'md',
resolve: {
entity: ['Discount', function(Discount) {
return Discount.get({id : $stateParams.id}).$promise;
}]
}
}).result.then(function() {
$state.go('discount', null, { reload: 'discount' });
}, function() {
$state.go('^');
});
}]
});
}
})(); |
class Movie {
constructor(title, genre, releaseYear, availableCopies) {
this.title = title;
this.genre = genre;
this.releaseYear = releaseYear;
this.availableCopies = availableCopies;
this.totalCopies = availableCopies;
}
rentMovie() {
if (this.availableCopies > 0) {
console.log(`Renting ${this.title}`);
this.availableCopies--;
return true;
} else {
console.log(`Sorry, ${this.title} is currently out of stock.`);
return false;
}
}
returnMovie() {
if (this.availableCopies < this.totalCopies) {
console.log(`Returning ${this.title}`);
this.availableCopies++;
return true;
} else {
console.log(`All copies of ${this.title} have already been returned.`);
return false;
}
}
}
class Customer {
constructor(name) {
this.name = name;
this.rentedMovies = [];
}
rentMovie(movie) {
if (movie.rentMovie()) {
console.log(`${this.name} has rented ${movie.title}`);
this.rentedMovies.push(movie);
} else {
console.log(`${this.name} could not rent ${movie.title}`);
}
}
returnMovie(movie) {
const index = this.rentedMovies.indexOf(movie);
if (index !== -1) {
if (movie.returnMovie()) {
console.log(`${this.name} has returned ${movie.title}`);
this.rentedMovies.splice(index, 1);
} else {
console.log(`${this.name} could not return ${movie.title}`);
}
} else {
console.log(`${this.name} did not rent ${movie.title}`);
}
}
}
// Example usage:
const movie1 = new Movie('Inception', 'Sci-Fi', 2010, 5);
const movie2 = new Movie('The Shawshank Redemption', 'Drama', 1994, 3);
const customer1 = new Customer('Alice');
const customer2 = new Customer('Bob');
customer1.rentMovie(movie1);
customer2.rentMovie(movie1);
customer1.rentMovie(movie2); |
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './index.css';
import Body from '../Body';
import { Bar } from "react-chartjs-2";
import { Chart as ChartJS } from "chart.js/auto";
import { useNavigate } from "react-router-dom";
import Table from "../ProjectDetails/index.jsx";
import { API_URL } from '../../config/index.js';
const InputSec = () => {
const [filteredProjects,setfilteredProjects] = useState();
const navigate = useNavigate();
const [categories, setCategories] = useState([]);
const [filters, setFilters] = useState({
year: "All",
domain: "All",
endYear: ""
});
const [projectCount,setProjectCount]=useState(0);
const [amount,setAmount]=useState(0);
const [guides,setGuides]=useState(0);
const [students,setStudents]=useState(0);
useEffect(() => {
const fetchCategories = async () => {
try {
const response = await axios.get(`${API_URL}/api/projects`);
const projects = response.data;
// Fetch unique categories
const allCategories = projects.reduce((acc, project) => {
if (!acc.includes(project.category)) {
acc.push(project.category);
}
return acc;
}, []);
setCategories(allCategories);
// Apply filters
const filteredProjects = applyFilters(projects);
// Calculate values
const totalAmount = calculateTotalAmount(filteredProjects);
const uniqueGuidesCount = calculateUniqueGuidesCount(filteredProjects);
const uniqueStudentsCount = calculateUniqueStudentsCount(filteredProjects);
// Set state with calculated values
setProjectCount(filteredProjects.length);
setAmount(totalAmount);
setGuides(uniqueGuidesCount);
setStudents(uniqueStudentsCount);
} catch (error) {
console.error('Error fetching categories:', error);
}
};
fetchCategories();
}, [filters,filteredProjects]);
// Helper function to apply filters to projects
const applyFilters = (projects) => {
const { year, domain, startYear, endYear } = filters;
// Filter projects based on year
let filteredProjects = projects;
if (year && year !== 'All') {
filteredProjects = filteredProjects.filter(project => project.year === parseInt(year));
}
// Filter projects based on domain
if (domain && domain !== 'All') {
filteredProjects = filteredProjects.filter(project => project.category === domain);
}
// Filter projects based on start and end year
if (startYear) {
filteredProjects = filteredProjects.filter(project => new Date(project.Start_date).getFullYear() >= parseInt(startYear));
}
if (endYear) {
filteredProjects = filteredProjects.filter(project => new Date(project.Start_date).getFullYear() <= parseInt(endYear));
}
return filteredProjects;
};
// Helper function to calculate total amount from filtered projects
const calculateTotalAmount = (projects) => {
return projects.reduce((total, project) => total + project.amount, 0);
};
// Helper function to calculate unique guides count from filtered projects
const calculateUniqueGuidesCount = (projects) => {
const uniqueGuides = new Set();
projects.forEach(project => {
project.guides.forEach(guide => {
uniqueGuides.add(guide);
});
});
return uniqueGuides.size;
};
// Helper function to calculate unique students count from filtered projects
const calculateUniqueStudentsCount = (projects) => {
const uniqueStudents = new Set();
projects.forEach(project => {
project.Students.forEach(student => {
uniqueStudents.add(student);
});
});
return uniqueStudents.size;
};
// Handler function to update filters
const handleFilterChange = (e) => {
const { name, value } = e.target;
setFilters(prevFilters => ({
...prevFilters,
[name]: value
}));
};
// Generate options for years
const generateYearOptions = () => {
const currentYear = new Date().getFullYear();
const years = [];
// Generate options for the last 20 years
for (let year = currentYear - 1; year >= 2018; year--) {
years.push(<option key={year} value={year}>{year}</option>);
}
return years;
};
// Generate options for domains
const generateDomainOptions = () => {
const uniqueDomains = new Set();
categories.forEach(category => {
uniqueDomains.add(category.domain);
});
const domainOptions = ['All', ...Array.from(uniqueDomains)];
return domainOptions.map(domain => (
<option key={domain} value={domain}>{domain}</option>
));
};
const columns = [
{
header: 'Project Name',
accessor: 'project_name',
sortable: true,
},
{
header: 'Amount',
accessor: 'amount',
sortable: true,
},
{
header: 'Academic Year',
accessor: 'year',
sortable: true,
},
];
return (
<>
<div className='input'>
<div className='input-field' style={{border: "none"}}>
<label className="label" htmlFor="domain">Domain:</label>
<select className='drop-input' name="domain" id="domain" onChange={handleFilterChange}>
<option value="All">All</option>
{categories.map((category, index) => (
<option key={index} value={category}>
{category}
</option>
))}
</select>
</div>
<div className='input-field' id="date-input">
<label className="label" htmlFor="start-year">Start Year:</label>
<select
className="drop-input"
id="start-year"
name="startYear"
onChange={handleFilterChange}
>
<option value="">All</option>
{/* Generate options for years */}
{generateYearOptions()}
</select>
</div>
<div className='input-field' id="date-input">
<label className="label" htmlFor="end-year">End Year:</label>
<select
className="drop-input"
id="end-year"
name="endYear"
onChange={handleFilterChange}
>
<option value="">All</option>
{/* Generate options for years */}
{generateYearOptions()}
</select>
</div>
</div>
<div className='details'>
<div className='details-container' >
<div className='img' id='img1'></div>
<h1 className='title'>Total Projects </h1>
<h1 className='nums'>{projectCount}</h1>
</div>
<div className='details-container'>
<div className='img' id='img2'></div>
<h1 className='title'>Amount Invested </h1>
<h1 className='nums'>₹ {amount}</h1>
</div>
<div className='details-container'>
<div className='img' id='img3'></div>
<h1 className='title'>Faculties Involved </h1>
<h1 className='nums'>{guides}</h1>
</div>
<div className='details-container'>
<div className='img' id='img4'></div>
<h1 className='title'>Students Involved </h1>
<h1 className='nums'>{students} </h1>
</div>
</div>
<div style={{ width: 700 }}>
<Body filters={filters} />
</div>
</>
);
}
export default InputSec; |
import { Component } from "react";
export default class Student extends Component {
constructor(props) {
super(props);
this.state = {id: props.id,
name: props.name,
mark1: props.mark1,
mark2: props.mark2};
}
onNameChange = (e) => {
this.setState({name: e.target.value})
}
onIdChange = (e) => {
this.setState({id: parseInt(e.target.value)})
}
onMark1Change = (e) => {
this.setState({mark1: parseInt(e.target.value)})
}
onMark2Change = (e) => {
this.setState({mark2: parseInt(e.target.value)})
}
render() {
return(
<>
<table width="100%">
<tr>
<td>
<div>
<div style={{border:'2px solid green',
backgroundColor:'brown',
color:'white'}}><h3>Edit Student</h3></div>
<div>
<label forName="name">Name : </label>
<input type="text" value={this.state.name}
id="name"
onChange={this.onNameChange}/>
</div>
<div>
<label forName="id">ID : </label>
<input type="text" value={this.state.id}
id="id"
onChange={this.onIdChange}/>
</div>
<div>
<label forName="mark1">Mark 1 : </label>
<input type="text" value={this.state.mark1}
id="mark1"
onChange={this.onMark1Change}/>
</div>
<div>
<label forName="mark2">Mark 2 : </label>
<input type="text" value={this.state.mark2}
id="mark2"
onChange={this.onMark2Change}/>
</div>
</div>
</td>
<td>
<div>
<div style={{border:'2px solid green',
backgroundColor:'brown',
color:'white'}}><h3>View Student</h3></div>
<div>
<label>Name : </label>
{this.state.name}
</div>
<div>
<label>ID : </label>
{this.state.id}
</div>
<div>
<label>Mark 1 : </label>
{this.state.mark1}
</div>
<div>
<label>Mark 2 : </label>
{this.state.mark2}
</div>
<div>
<label>Total : </label>
{this.state.mark1 + this.state.mark2}
</div>
</div>
</td>
</tr>
</table>
</>
)
}
}
/*
### Use Case: ###
#1
**** App.js ****
import './App.css';
import Student from './cls/student_no_composite/Student';
function App() {
return (
<div className="App">
<Student id={ 1001 }
name = { "dravid" }
mark1 = { 40 }
mark2 = { 34 } />
</div>
);
}
export default App;
*/ |
### Projeto Star Wars

## Introdução
Esta é uma aplicação React destinada a fornecer uma interface para filtrar e visualizar dados do universo Star Wars. A aplicação utiliza Context API e Hooks para controlar o estado global do React tornando-os reutilizáveis para criar uma tabela de dados interativa.
Certifique-se de ter os seguintes requisitos instalados em seu ambiente de desenvolvimento:
- [Node.js](https://nodejs.org/en/docs) (versões suportadas: 16 ou 18)
- [npm](https://docs.npmjs.com/) (gerenciador de pacotes Node.js)
## Tecnologias utilizadas <a name="tecnologias"></a>
- [**React**](https://legacy.reactjs.org/docs/getting-started.html)
- [**React-Router-Dom**](https://reactrouter.com/en/main)
- [**Tailwind**](https://v2.tailwindcss.com/docs)
- [**Jest**](https://jestjs.io/docs/getting-started)
- [**Linter**](https://eslint.org/docs/latest/)
- [**Mocha**](https://mochajs.org/)
- [**Hooks**](https://legacy.reactjs.org/docs/hooks-intro.html)
- [**Context API**](https://legacy.reactjs.org/docs/context.html)
## Instalação
1. Clone este repositório para o seu sistema local:
```bash
git clone git@github.com:georgia-rocha/Star-Wars.git
```
2. Entre na pasta que você acabou de clonar:
```bash
cd Star-Wars
```
3. Instale as dependências:
```bash
npm install
```
## Scripts
1. Iniciar o servidor de desenvolvimento:
```bash
npm start
```
2. Criar uma versão otimizada para produção da aplicação.
```bash
npm run build
```
3. Executar os testes da aplicação:
```bash
npm test
```
4. Executar os testes da aplicação e gerar um relatório de cobertura:
```bash
npm run test-coverage:
```
5. Executar o linter para verificação dos arquivos de estilo CSS:
```bash
npm run lint:styles
```
6. Executar o linter para verificação dos arquivos JavaScript e JSX.
```bash
npm run lint
```
7. Executar os testes de integração/end-to-end usando o Cypress:
```bash
npm run cy
```
8. Abrir a interface do Cypress para executar testes interativos:
```bash
npm run cy:open
```
## Requisitos
- [x] 1 - Requisição para o endpoint /planets da API de Star Wars e tabela preenchida com os dados retornados, com exceção dos dados da coluna residents;
- [x] 2 - Criado filtro de texto para buscar na tabela os planetas através do nome;
- [x] 3 - Criado filtro para valores numéricos com label 'coluna', 'operador' e um input do type number para valor a ser filtrado;
- [x] 4 - Implementei múltiplos filtros numéricos referente ao requisito anterior;
- [x] 5 - Não é possivel utilizar filtros repetidos;
- [x] 6 - É possivel apaguar um filtro de valor numérico ao clicar no ícone de remover de um dos filtros ou apagar todas filtragens numéricas simultaneamente ao clicar no botão de Remover todas filtragens;
- [x] 7 - A aplicação apresenta cobertura superior a 60%;
- [ ] 8 - Ordenar as colunas de forma ascendente ou descendente; |
#
# (C) Tenable Network Security, Inc.
#
# The descriptive text and package checks in this plugin were
# extracted from Fedora Security Advisory 2004-120.
#
include("compat.inc");
if (description)
{
script_id(13698);
script_version ("$Revision: 1.13 $");
script_cvs_date("$Date: 2015/10/21 21:09:31 $");
script_xref(name:"FEDORA", value:"2004-120");
script_name(english:"Fedora Core 1 : tcpdump-3.7.2-8.fc1.2 (2004-120)");
script_summary(english:"Checks rpm output for the updated packages.");
script_set_attribute(
attribute:"synopsis",
value:"The remote Fedora Core host is missing a security update."
);
script_set_attribute(
attribute:"description",
value:
"Tcpdump is a command-line tool for monitoring network traffic.
Tcpdump v3.8.1 and earlier versions contained multiple flaws in the
packet display functions for the ISAKMP protocol. Upon receiving
specially crafted ISAKMP packets, TCPDUMP would try to read beyond the
end of the packet capture buffer and subsequently crash.
Users of tcpdump are advised to upgrade to these erratum packages,
which contain backported security patches and are not vulnerable to
these issues.
Note that Tenable Network Security has extracted the preceding
description block directly from the Fedora security advisory. Tenable
has attempted to automatically clean and format it as much as possible
without introducing additional issues."
);
# https://lists.fedoraproject.org/pipermail/announce/2004-May/000125.html
script_set_attribute(
attribute:"see_also",
value:"http://www.nessus.org/u?e58d4431"
);
script_set_attribute(
attribute:"solution",
value:"Update the affected arpwatch, libpcap and / or tcpdump packages."
);
script_set_attribute(attribute:"risk_factor", value:"High");
script_set_attribute(attribute:"plugin_type", value:"local");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:fedoraproject:fedora:arpwatch");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:fedoraproject:fedora:libpcap");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:fedoraproject:fedora:tcpdump");
script_set_attribute(attribute:"cpe", value:"cpe:/o:fedoraproject:fedora_core:1");
script_set_attribute(attribute:"patch_publication_date", value:"2004/05/13");
script_set_attribute(attribute:"plugin_publication_date", value:"2004/07/23");
script_end_attributes();
script_category(ACT_GATHER_INFO);
script_copyright(english:"This script is Copyright (C) 2004-2015 Tenable Network Security, Inc.");
script_family(english:"Fedora Local Security Checks");
script_dependencies("ssh_get_info.nasl");
script_require_keys("Host/local_checks_enabled", "Host/RedHat/release", "Host/RedHat/rpm-list");
exit(0);
}
include("audit.inc");
include("global_settings.inc");
include("rpm.inc");
if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED);
release = get_kb_item("Host/RedHat/release");
if (isnull(release) || "Fedora" >!< release) audit(AUDIT_OS_NOT, "Fedora");
os_ver = eregmatch(pattern: "Fedora.*release ([0-9]+)", string:release);
if (isnull(os_ver)) audit(AUDIT_UNKNOWN_APP_VER, "Fedora");
os_ver = os_ver[1];
if (! ereg(pattern:"^1([^0-9]|$)", string:os_ver)) audit(AUDIT_OS_NOT, "Fedora 1.x", "Fedora " + os_ver);
if (!get_kb_item("Host/RedHat/rpm-list")) audit(AUDIT_PACKAGE_LIST_MISSING);
cpu = get_kb_item("Host/cpu");
if (isnull(cpu)) audit(AUDIT_UNKNOWN_ARCH);
if ("x86_64" >!< cpu && cpu !~ "^i[3-6]86$") audit(AUDIT_LOCAL_CHECKS_NOT_IMPLEMENTED, "Fedora", cpu);
flag = 0;
if (rpm_check(release:"FC1", reference:"arpwatch-2.1a11-8.fc1.2")) flag++;
if (rpm_check(release:"FC1", reference:"libpcap-0.7.2-8.fc1.2")) flag++;
if (rpm_check(release:"FC1", reference:"tcpdump-3.7.2-8.fc1.2")) flag++;
if (flag)
{
if (report_verbosity > 0) security_hole(port:0, extra:rpm_report_get());
else security_hole(0);
exit(0);
}
else
{
tested = pkg_tests_get();
if (tested) audit(AUDIT_PACKAGE_NOT_AFFECTED, tested);
else audit(AUDIT_PACKAGE_NOT_INSTALLED, "arpwatch / libpcap / tcpdump");
} |
<!DOCTYPE html>
<!-- release v4.1.6, copyright 2015 Kartik Visweswaran -->
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Krajee JQuery Plugins - © Kartik</title>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="../css/fileinput.css" media="all" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="../js/fileinput.js" type="text/javascript"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js" type="text/javascript"></script>
</head>
<body>
<div class="container kv-main">
<h1>Bootstrap File Input Example</h1>
<form enctype="multipart/form-data">
<input id="file-0" class="file" type="file" multiple=true>
<br>
<div class="form-group">
<input id="file-0a" class="file" type="file">
</div>
<div class="form-group">
<input id="file-1" class="file" type="file" multiple=true data-preview-file-type="any">
</div>
<div class="form-group">
<input id="file-1a" type="file" multiple=true class="file" data-show-upload="false"
data-preview-file-type="any" data-initial-caption="Kartik" data-overwrite-initial="false">
</div>
<div class="form-group">
<input id="file-2" type="file" class="file" readonly=true data-show-upload="false">
</div>
<div class="form-group">
<input id="file-3" type="file" multiple=true>
</div>
<div class="form-group">
<input id="file-4" type="file" class="file" data-upload-url="#">
</div>
<div class="form-group">
<button class="btn btn-warning" type="button">Disable Test</button>
<button class="btn btn-info" type="reset">Refresh Test</button>
<button class="btn btn-primary">Submit</button>
<button class="btn btn-default" type="reset">Reset</button>
</div>
<div class="form-group">
<input type="file" class="file" id="test-upload" multiple>
<div id="errorBlock" class="help-block"></div>
</div>
<div class="form-group">
<input id="file-5" class="file" type="file" multiple=true data-preview-file-type="any" data-upload-url="#">
</div>
</form>
</div>
</body>
<script>
$( "#file-0" ).fileinput( {
'allowedFileExtensions': ['jpg', 'png', 'gif'],
} );
$( "#file-1" ).fileinput( {
initialPreview: [
"<img src='Desert.jpg' class='file-preview-image'>",
"<img src='Jellyfish.jpg' class='file-preview-image'>"
],
initialPreviewConfig: [
{caption: 'Desert.jpg', width: '120px', url: '#'},
{caption: 'Jellyfish.jpg', width: '120px', url: '#'},
],
uploadUrl: '#',
allowedFileExtensions: ['jpg', 'png', 'gif'],
overwriteInitial: false,
maxFileSize: 1000,
maxFilesNum: 10,
//allowedFileTypes: ['image', 'video', 'flash'],
slugCallback: function( filename )
{
return filename.replace( '(', '_' ).replace( ']', '_' );
}
} );
/*
$(".file").on('fileselect', function(event, n, l) {
alert('File Selected. Name: ' + l + ', Num: ' + n);
});
*/
$( "#file-3" ).fileinput( {
showUpload: false,
showCaption: false,
browseClass: "btn btn-primary btn-lg",
fileType: "any"
} );
$( "#file-4" ).fileinput( {
uploadExtraData: [
{kvId: '10'}
],
} );
$( ".btn-warning" ).on( 'click', function()
{
if ($( '#file-4' ).attr( 'disabled' )) {
$( '#file-4' ).fileinput( 'enable' );
} else {
$( '#file-4' ).fileinput( 'disable' );
}
} );
$( ".btn-info" ).on( 'click', function()
{
$( '#file-4' ).fileinput( 'refresh', {previewClass: 'bg-info'} );
} );
/*
$('#file-4').on('fileselectnone', function() {
alert('Huh! You selected no files.');
});
$('#file-4').on('filebrowse', function() {
alert('File browse clicked for #file-4');
});
*/
$( document ).ready( function()
{
$( "#test-upload" ).fileinput( {
'showPreview': false,
'allowedFileExtensions': ['jpg', 'png', 'gif'],
'elErrorContainer': '#errorBlock'
} );
/*
$("#test-upload").on('fileloaded', function(event, file, previewId, index) {
alert('i = ' + index + ', id = ' + previewId + ', file = ' + file.name);
});
*/
} );
</script>
</html> |
import Image from "next/image"
import Link from "next/link"
import { ArrowLeftIcon } from "@/components/ArrowLeftIcon"
const favoriteCount = 1234
export default function RecipeLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<section className="h-full max-w-[390px] border-x border-[#DCDBDD] pb-10 md:max-w-[480px]">
<div className="relative">
<Image
src={recipeImage}
width={480}
height={480}
alt="recipe"
className="h-[390px] w-[390px] bg-gray-300 shadow-inner md:h-[480px] md:w-[480px]"
/>
<Link
href={"/"}
className="absolute left-5 top-5 rounded-full p-1 hover:bg-[#05001238] hover:backdrop-opacity-20"
>
<ArrowLeftIcon stroke="#FDFCFD" height={32} width={32} />
</Link>
</div>
<div className="flex flex-col px-4 pb-5 pt-4">
<div className="flex flex-col gap-y-4">
<div className="flex ">
<h1 className="w-64 text-xl font-bold md:w-80">{recipeName}</h1>
{/* TODO: 実際のsnsメニューに置き換える */}
<div className="ml-auto h-6 w-24 bg-red-300 text-center">
snsアイコン
</div>
</div>
<p className="text-sm">{recipeDescription}</p>
</div>
<div className="mt-2 flex gap-x-4">
<Link href={"/chef/1"} className="flex items-center gap-x-0.5">
<div className="h-4 w-4 rounded-full bg-gray-300" />
<p className="text-sm text-[#6F6E77]">{chefName}</p>
</Link>
<div className="flex gap-1">
<p className="text-sm font-bold text-[#6F6E77]">
{favoriteCount.toLocaleString()}
</p>
<p className="text-sm text-[#6F6E77]">お気に入り</p>
</div>
</div>
{/* TODO:実際の評価ボタンに置き換える */}
<button className="mt-4 w-full place-self-start bg-red-300 px-2">
お気に入りに追加
</button>
</div>
{children}
</section>
)
}
const recipeImage = "/img/RecipeImageRecipe.png"
const recipeName = "グラタングラタングラタングラタングラタン"
const recipeDescription =
"はじめてでも失敗なく作れるような、鶏肉や玉ねぎを具とした基本的なマカロニグラタンのレシピです。 ソースと具材炒めを別器具で行うレシピも多いですが、グラタンの具を炒めたフライパンの中で、そのままホワイトソースを仕上げる手軽な作り方にしています。ぜひお試しください。"
const chefName = "しまぶーシェフ" |
// components/RecipeDetails.js
import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import axios from 'axios';
function RecipeDetails() {
const { id } = useParams();
const [recipe, setRecipe] = useState(null);
useEffect(() => {
// Fetch recipe details from Spoonacular API
axios.get(`https://api.spoonacular.com/recipes/${id}/information?apiKey=d71e056146ba4cb68ca2a1152f4669ce`)
.then(response => {
setRecipe(response.data);
})
.catch(error => {
console.error('Error fetching recipe details:', error);
});
}, [id]);
if (!recipe) {
return <div>Loading...</div>;
}
return (
<div class="bg-dark text-white">
<h2>{recipe.title}</h2>
<img class="object-fit-fill border rounded" src={recipe.image} alt={recipe.title} />
<h3>Ingredients</h3>
<ul class="list-group ">
{recipe.extendedIngredients.map(ingredient => (
<li class="list-group-item bg-dark text-white" key={ingredient.id}>{ingredient.original}</li>
))}
</ul>
<h3>Instructions</h3>
<div dangerouslySetInnerHTML={{ __html: recipe.instructions }}></div>
</div>
);
}
export default RecipeDetails; |
/*
* $Id$
*
* 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.struts2.dispatcher;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
/**
* A simple implementation of the {@link java.util.Map} interface to handle a collection of request attributes.
*/
public class RequestMap extends AbstractMap implements Serializable {
private static final long serialVersionUID = -7675640869293787926L;
private Set<Object> entries;
private HttpServletRequest request;
/**
* Saves the request to use as the backing for getting and setting values
*
* @param request the http servlet request.
*/
public RequestMap(final HttpServletRequest request) {
this.request = request;
}
/**
* Removes all attributes from the request as well as clears entries in this map.
*/
public void clear() {
entries = null;
Enumeration keys = request.getAttributeNames();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
request.removeAttribute(key);
}
}
/**
* Returns a Set of attributes from the http request.
*
* @return a Set of attributes from the http request.
*/
public Set entrySet() {
if (entries == null) {
entries = new HashSet<>();
Enumeration enumeration = request.getAttributeNames();
while (enumeration.hasMoreElements()) {
final String key = enumeration.nextElement().toString();
final Object value = request.getAttribute(key);
entries.add(new Entry() {
public boolean equals(Object obj) {
if (!(obj instanceof Entry)) {
return false;
}
Entry entry = (Entry) obj;
return ((key == null) ? (entry.getKey() == null) : key.equals(entry.getKey())) && ((value == null) ? (entry.getValue() == null) : value.equals(entry.getValue()));
}
public int hashCode() {
return ((key == null) ? 0 : key.hashCode()) ^ ((value == null) ? 0 : value.hashCode());
}
public Object getKey() {
return key;
}
public Object getValue() {
return value;
}
public Object setValue(Object obj) {
request.setAttribute(key, obj);
return value;
}
});
}
}
return entries;
}
/**
* Returns the request attribute associated with the given key or <tt>null</tt> if it doesn't exist.
*
* @param key the name of the request attribute.
* @return the request attribute or <tt>null</tt> if it doesn't exist.
*/
public Object get(Object key) {
return request.getAttribute(key.toString());
}
/**
* Saves an attribute in the request.
*
* @param key the name of the request attribute.
* @param value the value to set.
* @return the object that was just set.
*/
public Object put(Object key, Object value) {
Object oldValue = get(key);
entries = null;
request.setAttribute(key.toString(), value);
return oldValue;
}
/**
* Removes the specified request attribute.
*
* @param key the name of the attribute to remove.
* @return the value that was removed or <tt>null</tt> if the value was not found (and hence, not removed).
*/
public Object remove(Object key) {
entries = null;
Object value = get(key);
request.removeAttribute(key.toString());
return value;
}
} |
import {Octokit} from '@octokit/rest'
import {AsserterLookup} from './asserters'
import {Leif} from './types'
import {exec, indentLog, syncProcessArray, masterBranchName, homedir} from './utils'
const GitHubClient = new Octokit({
auth: process.env.GITHUB_OAUTH_TOKEN || process.env.GITHUB_TOKEN,
})
export default class SequenceService {
static async runMany(seqs: Leif.Sequence[]) {
await syncProcessArray(seqs, SequenceService.run)
}
static async run(seq: Leif.Sequence) {
indentLog(0, `# Running sequence ${seq.id}`, '')
indentLog(0, `## With ${seq.assertions.length} assertions: `)
indentLog(2, ...seq.assertions.map((a: Leif.Assertion) => '- ' + a.description || a.type), '')
indentLog(2, 'On repos:')
indentLog(2, ...seq.repos, '')
for (const repoFullName of seq.repos) {
await SequenceService.applyAssertionsToRepo(repoFullName, seq)
}
}
static async applyAssertionsToRepo(repoFullName: string, sequence: Leif.Sequence) {
// 0. check if PR exists already
// 1. create working branch (if it doesn't exist)
// 2. do work
// 3. check if work created changes
// 4. if changes, commit changes
// 5. push commit
// 6. create PR
// pre-work
const workingDir = `${homedir}/.leif/github/${repoFullName}`
const prDescription = sequence.description || `leif sequence ${sequence.id}`
const branchName = sequence.branch_name || sequence.id
const dryRun = sequence.dryRun
const masterMain = masterBranchName(workingDir)
indentLog(4, repoFullName)
// 0.
const [owner, repoShortName] = repoFullName.split('/')
const {data: pullRequests} = await GitHubClient.pulls.list({
owner,
repo: repoShortName,
})
const pullReqExists = pullRequests.find((p: any) => p.head.ref === branchName)
if (pullReqExists) {
indentLog(6, `leif has already pushed a PR for this assertion on branch ${branchName}...`)
indentLog(6, 'But checking for changes...')
}
// 1. & 2. & 3. & 4.
// moved inside asserter service
await SequenceService.runAssertions(sequence.assertions, {
repoFullName,
dryRun,
branchName,
workingDir,
masterMain,
templateDir: sequence.templateDir,
})
// 5.
let skipCreatingPR = false
const {stdout} = await exec(`git -C ${workingDir} diff ${branchName} origin/${masterMain} --name-only`)
if (stdout) {
if (dryRun) {
// clean-up dryRun
indentLog(6, '(In --dry-run mode, output below does not actually happen)')
await exec(`git -C ${workingDir} branch -D ${branchName}`)
} else {
await exec(`git -C ${workingDir} push origin ${branchName} --no-verify`)
}
indentLog(6, `Pushing branch ${branchName} to GitHub...`)
} else {
skipCreatingPR = true
indentLog(6, `Deleting empty branch ${branchName}...`)
await exec(`git -C ${workingDir} branch -D ${branchName} `)
}
// 6.0
if (pullReqExists || skipCreatingPR) return indentLog(0, '')
indentLog(6, 'Creating PR...')
if (!dryRun) {
await GitHubClient.pulls.create({
owner,
repo: repoShortName,
title: prDescription,
head: branchName,
base: masterMain,
})
}
indentLog(0, '')
}
static async runAssertions(assertions: Leif.Assertion[], opts: {
repoFullName: string;
dryRun: boolean;
branchName: string;
workingDir: string;
templateDir: string;
masterMain: string;
}) {
const {repoFullName, dryRun, branchName, workingDir, templateDir, masterMain} = opts
await syncProcessArray(assertions, async assertion => {
indentLog(6, `Assert: ${assertion.description} (type: ${assertion.type})`)
const Asserter = AsserterLookup[assertion.type]
if (!Asserter) throw new Error(`Invalid assertion type ${assertion.type}`)
try {
const asserter = new Asserter({
assertion,
repoFullName,
dryRun,
branchName,
workingDir,
templateDir,
})
await asserter.run()
} catch (error: any) {
await exec(`git -C ${workingDir} checkout ${masterMain}`)
await exec(`git -C ${workingDir} branch -D ${branchName}`)
throw error
}
})
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Expense Tracker</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: aquamarine;
}
#expense-list {
list-style-type: none;
padding: 0;
}
.expense-item {
margin-bottom: 10px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
.expense-item button {
margin-left: 10px;
}
</style>
</head>
<body>
<h1 style="text-align: center; ">Expense Tracker</h1>
<form id="expense-form">
<input type="text" id="expense" placeholder="Enter expense" >
<input type="number" id="amount" placeholder="Enter amount">
<button type="submit">Add Expense</button>
</form>
<ul id="expense-list"></ul>
<script>
document.addEventListener('DOMContentLoaded', () => {
const expenseForm = document.getElementById('expense-form');
const expenseList = document.getElementById('expense-list');
// Load expenses from local storage
const expenses = JSON.parse(localStorage.getItem('expenses')) || [];
// Display expenses
function displayExpenses() {
expenseList.innerHTML = '';
expenses.forEach((expense, index) => {
const li = document.createElement('li');
li.className = 'expense-item';
li.innerHTML = `
<span>${expense.name}: $${expense.amount}</span>
<button onclick="editExpense(${index})">Edit</button>
<button onclick="deleteExpense(${index})">Delete</button>
`;
expenseList.appendChild(li);
});
}
// Add expense
expenseForm.addEventListener('submit', (e) => {
e.preventDefault();
const expenseName = document.getElementById('expense').value;
const expenseAmount = document.getElementById('amount').value;
if (expenseName && expenseAmount) {
expenses.push({ name: expenseName, amount: parseFloat(expenseAmount) });
localStorage.setItem('expenses', JSON.stringify(expenses));
displayExpenses();
expenseForm.reset();
} else {
alert('Please enter both expense name and amount');
}
});
// Edit expense
window.editExpense = function(index) {
const newName = prompt('Enter new expense name:');
const newAmount = parseFloat(prompt('Enter new expense amount:'));
if (newName && !isNaN(newAmount)) {
expenses[index] = { name: newName, amount: newAmount };
localStorage.setItem('expenses', JSON.stringify(expenses));
displayExpenses();
} else {
alert('Invalid input. Please try again.');
}
};
// Delete expense
window.deleteExpense = function(index) {
expenses.splice(index, 1);
localStorage.setItem('expenses', JSON.stringify(expenses));
displayExpenses();
};
// Initial display
displayExpenses();
});
</script>
</body>
</html> |
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* 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.
**/
use Closure;
use Illuminate\Support\Facades\Auth;
/**
* Class RedirectIfAuthenticated
* @package App\Http\Middleware
*/
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
} |
@ngdoc overview
@name Tutorial: 217 Column Moving
@description
<div class="alert alert-warning" role="alert"><strong>Alpha</strong> This feature is in development. There will almost certainly be breaking api changes, or there are major outstanding bugs.</div>
Feature ui.grid.moveColumns allows moving column to a different position. To enable, you must include the `ui.grid.moveColumns` module
and you must include the `ui-grid-move-columns` directive on your grid element.
Documentation for the moveColumns feature is provided in the api documentation, in particular:
- {@link api/ui.grid.moveColumns.api:ColumnDef columnDef}
- {@link api/ui.grid.moveColumns.api:GridOptions gridOptions}
- {@link api/ui.grid.moveColumns.api:PublicApi publicApi}
By default column moving will be enabled for all the columns of the grid. To disable it for all columns of grid property `enableColumnMoving`
of grid options can be used. To specifically enable or disable column moving for a specific column property `enableColumnMoving`
of column definitions can be used.
Columns can be repositioned by either dragging and dropping them to specific position. Alternatively, gridApi method
`gridApi.colMovable.moveColumn(oldPosition, newPosition)` can also be used to move columns. The column position ranging from 0
(in the leftmost) up to number of visible columns in the grid (in the rightmost).
@example
<example module="app">
<file name="app.js">
var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.moveColumns']);
app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.gridOptions = {
};
$scope.gridOptions.columnDefs = [
{ name: 'id'},
{ name: 'name'},
{ name: 'age'},
{ name: 'gender'},
{ name: 'email'},
];
$http.get('/data/500_complex.json')
.success(function(data) {
$scope.gridOptions.data = data;
});
}]);
</file>
<file name="main.css">
.grid {
width: 100%;
height: 400;
}
</file>
<file name="index.html">
<div ng-controller="MainCtrl">
<div class="grid" ui-grid="gridOptions" ui-grid-move-columns></div>
</div>
</file>
</example> |
package com.mycompany.myapp.web.rest;
import static com.mycompany.myapp.web.rest.TestUtil.sameNumber;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.mycompany.myapp.IntegrationTest;
import com.mycompany.myapp.domain.ProjectService;
import com.mycompany.myapp.repository.ProjectServiceRepository;
import com.mycompany.myapp.service.dto.ProjectServiceDTO;
import com.mycompany.myapp.service.mapper.ProjectServiceMapper;
import jakarta.persistence.EntityManager;
import java.math.BigDecimal;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
/**
* Integration tests for the {@link ProjectServiceResource} REST controller.
*/
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class ProjectServiceResourceIT {
private static final String DEFAULT_NAME = "AAAAAAAAAA";
private static final String UPDATED_NAME = "BBBBBBBBBB";
private static final BigDecimal DEFAULT_FEE = new BigDecimal(0);
private static final BigDecimal UPDATED_FEE = new BigDecimal(1);
private static final String DEFAULT_DESCRIPTION = "AAAAAAAAAA";
private static final String UPDATED_DESCRIPTION = "BBBBBBBBBB";
private static final Integer DEFAULT_DAY_LENGTH = 1;
private static final Integer UPDATED_DAY_LENGTH = 2;
private static final String DEFAULT_EXTRA = "AAAAAAAAAA";
private static final String UPDATED_EXTRA = "BBBBBBBBBB";
private static final String ENTITY_API_URL = "/api/project-services";
private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";
private static Random random = new Random();
private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));
@Autowired
private ProjectServiceRepository projectServiceRepository;
@Autowired
private ProjectServiceMapper projectServiceMapper;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restProjectServiceMockMvc;
private ProjectService projectService;
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static ProjectService createEntity(EntityManager em) {
ProjectService projectService = new ProjectService()
.name(DEFAULT_NAME)
.fee(DEFAULT_FEE)
.description(DEFAULT_DESCRIPTION)
.dayLength(DEFAULT_DAY_LENGTH)
.extra(DEFAULT_EXTRA);
return projectService;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static ProjectService createUpdatedEntity(EntityManager em) {
ProjectService projectService = new ProjectService()
.name(UPDATED_NAME)
.fee(UPDATED_FEE)
.description(UPDATED_DESCRIPTION)
.dayLength(UPDATED_DAY_LENGTH)
.extra(UPDATED_EXTRA);
return projectService;
}
@BeforeEach
public void initTest() {
projectService = createEntity(em);
}
@Test
@Transactional
void createProjectService() throws Exception {
int databaseSizeBeforeCreate = projectServiceRepository.findAll().size();
// Create the ProjectService
ProjectServiceDTO projectServiceDTO = projectServiceMapper.toDto(projectService);
restProjectServiceMockMvc
.perform(
post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(projectServiceDTO))
)
.andExpect(status().isCreated());
// Validate the ProjectService in the database
List<ProjectService> projectServiceList = projectServiceRepository.findAll();
assertThat(projectServiceList).hasSize(databaseSizeBeforeCreate + 1);
ProjectService testProjectService = projectServiceList.get(projectServiceList.size() - 1);
assertThat(testProjectService.getName()).isEqualTo(DEFAULT_NAME);
assertThat(testProjectService.getFee()).isEqualByComparingTo(DEFAULT_FEE);
assertThat(testProjectService.getDescription()).isEqualTo(DEFAULT_DESCRIPTION);
assertThat(testProjectService.getDayLength()).isEqualTo(DEFAULT_DAY_LENGTH);
assertThat(testProjectService.getExtra()).isEqualTo(DEFAULT_EXTRA);
}
@Test
@Transactional
void createProjectServiceWithExistingId() throws Exception {
// Create the ProjectService with an existing ID
projectService.setId(1L);
ProjectServiceDTO projectServiceDTO = projectServiceMapper.toDto(projectService);
int databaseSizeBeforeCreate = projectServiceRepository.findAll().size();
// An entity with an existing ID cannot be created, so this API call must fail
restProjectServiceMockMvc
.perform(
post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(projectServiceDTO))
)
.andExpect(status().isBadRequest());
// Validate the ProjectService in the database
List<ProjectService> projectServiceList = projectServiceRepository.findAll();
assertThat(projectServiceList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
void checkNameIsRequired() throws Exception {
int databaseSizeBeforeTest = projectServiceRepository.findAll().size();
// set the field null
projectService.setName(null);
// Create the ProjectService, which fails.
ProjectServiceDTO projectServiceDTO = projectServiceMapper.toDto(projectService);
restProjectServiceMockMvc
.perform(
post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(projectServiceDTO))
)
.andExpect(status().isBadRequest());
List<ProjectService> projectServiceList = projectServiceRepository.findAll();
assertThat(projectServiceList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
void checkFeeIsRequired() throws Exception {
int databaseSizeBeforeTest = projectServiceRepository.findAll().size();
// set the field null
projectService.setFee(null);
// Create the ProjectService, which fails.
ProjectServiceDTO projectServiceDTO = projectServiceMapper.toDto(projectService);
restProjectServiceMockMvc
.perform(
post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(projectServiceDTO))
)
.andExpect(status().isBadRequest());
List<ProjectService> projectServiceList = projectServiceRepository.findAll();
assertThat(projectServiceList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
void getAllProjectServices() throws Exception {
// Initialize the database
projectServiceRepository.saveAndFlush(projectService);
// Get all the projectServiceList
restProjectServiceMockMvc
.perform(get(ENTITY_API_URL + "?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(projectService.getId().intValue())))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
.andExpect(jsonPath("$.[*].fee").value(hasItem(sameNumber(DEFAULT_FEE))))
.andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION.toString())))
.andExpect(jsonPath("$.[*].dayLength").value(hasItem(DEFAULT_DAY_LENGTH)))
.andExpect(jsonPath("$.[*].extra").value(hasItem(DEFAULT_EXTRA.toString())));
}
@Test
@Transactional
void getProjectService() throws Exception {
// Initialize the database
projectServiceRepository.saveAndFlush(projectService);
// Get the projectService
restProjectServiceMockMvc
.perform(get(ENTITY_API_URL_ID, projectService.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.id").value(projectService.getId().intValue()))
.andExpect(jsonPath("$.name").value(DEFAULT_NAME))
.andExpect(jsonPath("$.fee").value(sameNumber(DEFAULT_FEE)))
.andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString()))
.andExpect(jsonPath("$.dayLength").value(DEFAULT_DAY_LENGTH))
.andExpect(jsonPath("$.extra").value(DEFAULT_EXTRA.toString()));
}
@Test
@Transactional
void getNonExistingProjectService() throws Exception {
// Get the projectService
restProjectServiceMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
}
@Test
@Transactional
void putExistingProjectService() throws Exception {
// Initialize the database
projectServiceRepository.saveAndFlush(projectService);
int databaseSizeBeforeUpdate = projectServiceRepository.findAll().size();
// Update the projectService
ProjectService updatedProjectService = projectServiceRepository.findById(projectService.getId()).orElseThrow();
// Disconnect from session so that the updates on updatedProjectService are not directly saved in db
em.detach(updatedProjectService);
updatedProjectService
.name(UPDATED_NAME)
.fee(UPDATED_FEE)
.description(UPDATED_DESCRIPTION)
.dayLength(UPDATED_DAY_LENGTH)
.extra(UPDATED_EXTRA);
ProjectServiceDTO projectServiceDTO = projectServiceMapper.toDto(updatedProjectService);
restProjectServiceMockMvc
.perform(
put(ENTITY_API_URL_ID, projectServiceDTO.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(projectServiceDTO))
)
.andExpect(status().isOk());
// Validate the ProjectService in the database
List<ProjectService> projectServiceList = projectServiceRepository.findAll();
assertThat(projectServiceList).hasSize(databaseSizeBeforeUpdate);
ProjectService testProjectService = projectServiceList.get(projectServiceList.size() - 1);
assertThat(testProjectService.getName()).isEqualTo(UPDATED_NAME);
assertThat(testProjectService.getFee()).isEqualByComparingTo(UPDATED_FEE);
assertThat(testProjectService.getDescription()).isEqualTo(UPDATED_DESCRIPTION);
assertThat(testProjectService.getDayLength()).isEqualTo(UPDATED_DAY_LENGTH);
assertThat(testProjectService.getExtra()).isEqualTo(UPDATED_EXTRA);
}
@Test
@Transactional
void putNonExistingProjectService() throws Exception {
int databaseSizeBeforeUpdate = projectServiceRepository.findAll().size();
projectService.setId(longCount.incrementAndGet());
// Create the ProjectService
ProjectServiceDTO projectServiceDTO = projectServiceMapper.toDto(projectService);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restProjectServiceMockMvc
.perform(
put(ENTITY_API_URL_ID, projectServiceDTO.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(projectServiceDTO))
)
.andExpect(status().isBadRequest());
// Validate the ProjectService in the database
List<ProjectService> projectServiceList = projectServiceRepository.findAll();
assertThat(projectServiceList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void putWithIdMismatchProjectService() throws Exception {
int databaseSizeBeforeUpdate = projectServiceRepository.findAll().size();
projectService.setId(longCount.incrementAndGet());
// Create the ProjectService
ProjectServiceDTO projectServiceDTO = projectServiceMapper.toDto(projectService);
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restProjectServiceMockMvc
.perform(
put(ENTITY_API_URL_ID, longCount.incrementAndGet())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(projectServiceDTO))
)
.andExpect(status().isBadRequest());
// Validate the ProjectService in the database
List<ProjectService> projectServiceList = projectServiceRepository.findAll();
assertThat(projectServiceList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void putWithMissingIdPathParamProjectService() throws Exception {
int databaseSizeBeforeUpdate = projectServiceRepository.findAll().size();
projectService.setId(longCount.incrementAndGet());
// Create the ProjectService
ProjectServiceDTO projectServiceDTO = projectServiceMapper.toDto(projectService);
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restProjectServiceMockMvc
.perform(
put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(projectServiceDTO))
)
.andExpect(status().isMethodNotAllowed());
// Validate the ProjectService in the database
List<ProjectService> projectServiceList = projectServiceRepository.findAll();
assertThat(projectServiceList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void partialUpdateProjectServiceWithPatch() throws Exception {
// Initialize the database
projectServiceRepository.saveAndFlush(projectService);
int databaseSizeBeforeUpdate = projectServiceRepository.findAll().size();
// Update the projectService using partial update
ProjectService partialUpdatedProjectService = new ProjectService();
partialUpdatedProjectService.setId(projectService.getId());
partialUpdatedProjectService.name(UPDATED_NAME).dayLength(UPDATED_DAY_LENGTH).extra(UPDATED_EXTRA);
restProjectServiceMockMvc
.perform(
patch(ENTITY_API_URL_ID, partialUpdatedProjectService.getId())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(partialUpdatedProjectService))
)
.andExpect(status().isOk());
// Validate the ProjectService in the database
List<ProjectService> projectServiceList = projectServiceRepository.findAll();
assertThat(projectServiceList).hasSize(databaseSizeBeforeUpdate);
ProjectService testProjectService = projectServiceList.get(projectServiceList.size() - 1);
assertThat(testProjectService.getName()).isEqualTo(UPDATED_NAME);
assertThat(testProjectService.getFee()).isEqualByComparingTo(DEFAULT_FEE);
assertThat(testProjectService.getDescription()).isEqualTo(DEFAULT_DESCRIPTION);
assertThat(testProjectService.getDayLength()).isEqualTo(UPDATED_DAY_LENGTH);
assertThat(testProjectService.getExtra()).isEqualTo(UPDATED_EXTRA);
}
@Test
@Transactional
void fullUpdateProjectServiceWithPatch() throws Exception {
// Initialize the database
projectServiceRepository.saveAndFlush(projectService);
int databaseSizeBeforeUpdate = projectServiceRepository.findAll().size();
// Update the projectService using partial update
ProjectService partialUpdatedProjectService = new ProjectService();
partialUpdatedProjectService.setId(projectService.getId());
partialUpdatedProjectService
.name(UPDATED_NAME)
.fee(UPDATED_FEE)
.description(UPDATED_DESCRIPTION)
.dayLength(UPDATED_DAY_LENGTH)
.extra(UPDATED_EXTRA);
restProjectServiceMockMvc
.perform(
patch(ENTITY_API_URL_ID, partialUpdatedProjectService.getId())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(partialUpdatedProjectService))
)
.andExpect(status().isOk());
// Validate the ProjectService in the database
List<ProjectService> projectServiceList = projectServiceRepository.findAll();
assertThat(projectServiceList).hasSize(databaseSizeBeforeUpdate);
ProjectService testProjectService = projectServiceList.get(projectServiceList.size() - 1);
assertThat(testProjectService.getName()).isEqualTo(UPDATED_NAME);
assertThat(testProjectService.getFee()).isEqualByComparingTo(UPDATED_FEE);
assertThat(testProjectService.getDescription()).isEqualTo(UPDATED_DESCRIPTION);
assertThat(testProjectService.getDayLength()).isEqualTo(UPDATED_DAY_LENGTH);
assertThat(testProjectService.getExtra()).isEqualTo(UPDATED_EXTRA);
}
@Test
@Transactional
void patchNonExistingProjectService() throws Exception {
int databaseSizeBeforeUpdate = projectServiceRepository.findAll().size();
projectService.setId(longCount.incrementAndGet());
// Create the ProjectService
ProjectServiceDTO projectServiceDTO = projectServiceMapper.toDto(projectService);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restProjectServiceMockMvc
.perform(
patch(ENTITY_API_URL_ID, projectServiceDTO.getId())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(projectServiceDTO))
)
.andExpect(status().isBadRequest());
// Validate the ProjectService in the database
List<ProjectService> projectServiceList = projectServiceRepository.findAll();
assertThat(projectServiceList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void patchWithIdMismatchProjectService() throws Exception {
int databaseSizeBeforeUpdate = projectServiceRepository.findAll().size();
projectService.setId(longCount.incrementAndGet());
// Create the ProjectService
ProjectServiceDTO projectServiceDTO = projectServiceMapper.toDto(projectService);
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restProjectServiceMockMvc
.perform(
patch(ENTITY_API_URL_ID, longCount.incrementAndGet())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(projectServiceDTO))
)
.andExpect(status().isBadRequest());
// Validate the ProjectService in the database
List<ProjectService> projectServiceList = projectServiceRepository.findAll();
assertThat(projectServiceList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void patchWithMissingIdPathParamProjectService() throws Exception {
int databaseSizeBeforeUpdate = projectServiceRepository.findAll().size();
projectService.setId(longCount.incrementAndGet());
// Create the ProjectService
ProjectServiceDTO projectServiceDTO = projectServiceMapper.toDto(projectService);
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restProjectServiceMockMvc
.perform(
patch(ENTITY_API_URL)
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(projectServiceDTO))
)
.andExpect(status().isMethodNotAllowed());
// Validate the ProjectService in the database
List<ProjectService> projectServiceList = projectServiceRepository.findAll();
assertThat(projectServiceList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void deleteProjectService() throws Exception {
// Initialize the database
projectServiceRepository.saveAndFlush(projectService);
int databaseSizeBeforeDelete = projectServiceRepository.findAll().size();
// Delete the projectService
restProjectServiceMockMvc
.perform(delete(ENTITY_API_URL_ID, projectService.getId()).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<ProjectService> projectServiceList = projectServiceRepository.findAll();
assertThat(projectServiceList).hasSize(databaseSizeBeforeDelete - 1);
}
} |
document.getElementById("load").onclick = getFile;
var table = [];
var tableHeaders = [];
function getFile() {
const input = document.getElementById("input-file");
if ("files" in input && input.files.length > 0) {
placeFileContent(
document.getElementById("visualization-area"),
input.files[0]
);
}
}
function placeFileContent(target, file) {
target.removeAttribute("hidden");
readFileContent(file)
.then((content) => {
target.querySelector("#content").innerHTML = mapCSVtoTable(content);
target.querySelector("#success-msg").innerText =
"File read sucessfuly";
target.querySelector(
"#row-count"
).innerText = `Total: ${table.length} rows`;
})
.catch((error) => {
console.log(error);
target.querySelector(
"#success-msg"
).innerText = `There was an error when read the file:\n${error}`;
});
}
function readFileContent(file) {
const reader = new FileReader();
return new Promise((resolve, reject) => {
reader.onload = (event) => resolve(event.target.result);
reader.onerror = (error) => reject(error);
reader.readAsText(file);
});
}
function mapCSVtoTable(csvcontent) {
let html = "";
html += "<thead>";
let allTextLines = csvcontent.split(/\r\n|\n/);
for (line in allTextLines) {
let curLine = allTextLines[line];
table.push([]);
let allfields = curLine.split(",");
for (field in allfields) {
if (line == 0) {
html += `<th>${allfields[field]}</th>`;
tableHeaders.push(allfields[field]);
} else {
html += `<td>${allfields[field]}</td>`;
table[line - 1].push(allfields[field]);
}
}
if (line == 0) {
html += "</thead><tbody><tr>";
table = [];
} else if (line === allTextLines.length - 1) {
html += "</tr></tbody>";
} else {
html += "</tr><tr>";
}
}
return html;
}
function mapJSONtoTable(data){
table = [];
tableHeaders = [];
let html='';
html += '<thead>';
for(field of Object.keys(data[0])){
html += `<th>${field}</th>`;
tableHeaders.push(field);
}
html += '</thead><tbody><tr>';
for(idx in data){
let item = data[idx];
table.push([]);
let allfields = Object.keys(item);
for(field of allfields){
html += `<td>${item[field]}</td>`;
table[idx].push(item[field])
}
html += '</tr><tr>';
}
html += '</tr></tbody>';
return html;
}
function getContent() {
let mockarooApiKey = '99232830';
let url = `http://my.api.mockaroo.com/users.json?key=${mockarooApiKey}`;
let target = document.getElementById('visualization-area');
$.ajax( {
url: url,
responseType:'application/json',
success: function(data) {
target.removeAttribute("hidden");
target.querySelector("#content").innerHTML = mapJSONtoTable(data);
target.querySelector("#success-msg").innerText = "Información obtenida exitosamente"
target.querySelector("#row-count").innerText = `Total: ${table.length} filas`
},
error: function(xhr, status, error) {
target.querySelector("#success-msg").innerText = `Hubo un error al leer el archivo:\n${error}`
}
});
}
document.getElementById("fetch-button").onclick = getContent |
import React, { Component } from "react";
export default class Modal extends Component {
renderCart = () => {
const { carts, updateQuantity, deleteProduct } = this.props;
return carts.map((product) => {
return (
<tr key={product.maSP}>
<td>{product.maSP}</td>
<td>{product.tenSP}</td>
<td>
<img src={product.hinhAnh} width={50} alt="" />
</td>
<td>
<button
onClick={() => {
updateQuantity(product.maSP, false);
}}
>
-
</button>
{product.soLuong}
<button
onClick={() => {
updateQuantity(product.maSP, true);
}}
>
+
</button>
</td>
<td>{product.giaBan}</td>
<td>{product.giaBan * product.soLuong}</td>
<td>
<button
className="btn btn-danger"
onClick={() => {
deleteProduct(product.maSP);
}}
>
Delete
</button>
</td>
</tr>
);
});
};
render() {
return (
<div
className="modal fade"
id="modelId"
tabIndex={-1}
role="dialog"
aria-labelledby="modelTitleId"
aria-hidden="true"
>
<div
className="modal-dialog"
style={{ maxWidth: "1000px" }}
role="document"
>
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">Giỏ hàng</h5>
<button
type="button"
className="close"
data-dismiss="modal"
aria-label="Close"
>
<span aria-hidden="true">×</span>
</button>
</div>
<div className="modal-body">
<table className="table">
<thead>
<tr>
<th>Mã sản phẩm</th>
<th>tên sản phẩm</th>
<th>hình ảnh</th>
<th>số lượng</th>
<th>đơn giá</th>
<th>thành tiền</th>
</tr>
</thead>
<tbody>{this.renderCart()}</tbody>
</table>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-secondary"
data-dismiss="modal"
>
Close
</button>
<button type="button" className="btn btn-primary">
Save
</button>
</div>
</div>
</div>
</div>
);
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zooming</title>
<meta name="description" content="DESCRIPTIONHERE" />
<meta name="author" content="Frontendscript" />
<!--Only for demo purpose - no need to add.-->
<link rel="stylesheet" type="text/css" href="demo.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css">
<!-- FONT
–––––––––––––––––––––––––––––––––––––––––––––––––– -->
<link href="https://fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<style>
.container {
max-width: 600px;
}
section.header {
margin-top: 4rem;
text-align: center;
}
section.content {
text-align: center;
}
footer {
text-align: center;
}
.value-img {
display: block;
text-align: center;
}
img {
max-width: 100%;
}
@media (min-width: 550px) {
.header {
margin-top: 10rem;
}
}
.button.button-primary {
background-color: #f9c04d !important;
border-color: #f9c04d !important;
}
.button.button-secondary {
background-color: #eee !important;
border-color: #eee !important;
}
/* Grid Zoom*/
.grid {
column-count: 4;
column-gap: 1rem;
}
.grid figure {
display: inline-block;
margin: 0 0 0 0;
width: 100%;
}
.grid img {
width: 100%;
height: auto;
}
</style>
</head>
<body>
<div class="ScriptTop">
<div class="rt-container">
<div class="col-rt-4" id="float-right">
</div>
<div class="col-rt-2">
<ul>
<li><a href="https://frontendscript.com/javascript-image-zoom-on-click">Back to the Tutorial</a></li>
</ul>
</div>
</div>
</div>
<header class="ScriptHeader">
<div class="rt-container">
<div class="col-rt-12">
<div class="rt-heading">
<h1>Zooming On Click jQuery Plugin</h1>
<p>Pure JavaScript & built with mobile in mind. Smooth animations with intuitive gestures.</p>
</div>
</div>
</div>
</header>
<section>
<div class="rt-container">
<div class="col-rt-12">
<div class="Scriptcontent">
<div class="value-img">
<img id="img-default" src="img/journey_start_thumbnail.jpg" data-action="zoom" data-original="img/journey_start.jpg"
alt="journey_start_thumbnail" />
</div>
</div>
</div>
</div>
</section>
<section class="content">
<div class="rt-container">
<div class="col-rt-12">
<h4>Image zoom that makes sense.</h4>
<ul>
<li>Pure JavaScript & built with mobile in mind.</li>
<li>Smooth animations with intuitive gestures.</li>
<li>Zoom into a hi-res image if supplied.</li>
<li>Easy to integrate & customizable.</li>
</ul>
<div class="value-img">
<a href="img/journey.jpg">
<img id="img-custom" src="img/journey_thumbnail.jpg" alt="journey_thumbnail" />
</a>
</div>
<p>
<small>Options below were designed to affect the second image only.</small>
</p>
<div class="row">
<a class="button" id="btn-fast">faster</a>
<a class="button" id="btn-dark">dark</a>
<a class="button" id="btn-scale-small">smaller</a>
</div>
<br>
<p>
<em>Faced with rolling sand dunes, age-old ruins, caves and howling winds, your passage will not be an easy one. The
goal is to get to the mountaintop, but the experience is discovering who you are, what this place is, and what
is your purpose.</em>
</p>
</div>
</div>
</section>
<div class="rt-container">
<div class="col-rt-12">
<h4 style="margin-bottom:20px;">Grid Image Zoom</h4>
<div class="grid">
<figure>
<img src="http://via.placeholder.com/500x500">
</figure>
<figure>
<img src="http://via.placeholder.com/800x500">
</figure>
<figure>
<img src="http://via.placeholder.com/500x500">
</figure>
<figure>
<img src="http://via.placeholder.com/500x500">
</figure>
<figure>
<img src="http://via.placeholder.com/300x600">
</figure>
<figure>
<img src="http://via.placeholder.com/500x500">
</figure>
<figure>
<img src="http://via.placeholder.com/500x500">
</figure>
<figure>
<img src="http://via.placeholder.com/500x900">
</figure>
<figure>
<img src="http://via.placeholder.com/500x500">
</figure>
<figure>
<img src="http://via.placeholder.com/300x500">
</figure>
<figure>
<img src="http://via.placeholder.com/500x500">
</figure>
<figure>
<img src="http://via.placeholder.com/500x500">
</figure>
</div>
</div>
</div>
<!-- Scripts
–––––––––––––––––––––––––––––––––––––––––––––––––– -->
<script src="js/zooming.min.js"></script>
<script>
new Zooming().listen('.grid img')
</script>
<script>
const defaultZooming = new Zooming()
const customZooming = new Zooming()
const config = customZooming.config()
const TRANSITION_DURATION_DEFAULT = config.transitionDuration
const BG_COLOR_DEFAULT = config.bgColor
const SCALE_BASE_DEFAULT = config.scaleBase
const ACTIVE_CLASS = 'button-primary'
const btnFast = document.getElementById('btn-fast')
const btnDark = document.getElementById('btn-dark')
const btnScaleSmall = document.getElementById('btn-scale-small')
document.addEventListener('DOMContentLoaded', function () {
defaultZooming.listen('#img-default')
customZooming.listen('#img-custom')
})
btnFast.addEventListener('click', function (event) {
const transitionDuration = toggleActive(btnFast)
? 0.2
: TRANSITION_DURATION_DEFAULT
customZooming.config({ transitionDuration })
})
btnDark.addEventListener('click', function (event) {
const bgColor = toggleActive(btnDark)
? 'black'
: BG_COLOR_DEFAULT
customZooming.config({ bgColor })
})
btnScaleSmall.addEventListener('click', function (event) {
const scaleBase = toggleActive(btnScaleSmall)
? 0.7
: SCALE_BASE_DEFAULT
customZooming.config({ scaleBase })
})
function isActive(el) {
return el.classList.contains(ACTIVE_CLASS)
}
function activate(el) {
el.classList.add(ACTIVE_CLASS)
}
function deactivate(el) {
el.classList.remove(ACTIVE_CLASS)
}
function toggleActive(el) {
if (isActive(el)) {
deactivate(el)
return false
} else {
activate(el)
return true
}
}
</script>
<!-- End Document
–––––––––––––––––––––––––––––––––––––––––––––––––– -->
</body>
</html> |
<div class="project-boxes jsGridView" data-projects-target="index">
<% @projects.sort_by {|project| project.end_at }.each do |project| %>
<%= link_to project_path(project) do %>
<div class="project-box-wrapper">
<div class="project-box">
<div class="project-box-content-header">
<div class="d-flex justify-content-start project-date">
<p><%= project.start_at.strftime('%B %d, %Y') %></p>
</div>
<p class="box-content-header"><%= project.name %></p>
<p class="box-content-subheader"><%= project.current_step_name %></p>
</div>
<div class="box-progress-wrapper">
<div class="d-flex justify-content-between">
<p class="box-progress-header">Progress</p>
<p class="box-progress-percentage"><%= project.progress %>%</p>
</div>
<div class="box-progress-bar">
<span class="box-progress <%= project.set_progress_bar_color %>" style="width: <%= project.progress %>%; "></span>
</div>
</div>
<div class="project-box-footer">
<%= link_to(project_steps_path(project), class: "testing") do %>
<div class="participants">
<% project.users.each do |user| %>
<%= cl_image_tag user.photo.key %>
<% end %>
<i class="fa-solid fa-plus add-user"></i>
</div>
<% end %>
<div class="days-left">
<% if (project.end_at - Date.today).to_i < 7 %>
<i class="fa-solid fa-circle-exclamation me-1"></i>
<% end %>
<%= (project.end_at - Date.today).to_i %> days left
</div>
</div>
</div>
</div>
<% end %>
<% end %>
</div> |
extends Node
class_name PlayerNodeDirectory
## The scene to instantiate on creation of a new [PlayerNode].
const playernode_scene: PackedScene = preload("res://scenes/playernode.tscn")
## Find the subordinate [PlayerNode] with the given player_name, and return it if found, otherwise return null.
func get_playernode(player_name: String) -> PlayerNode:
var sanitized_player_name = PlayerNode.sanitize_player_name(player_name)
return get_node_or_null(sanitized_player_name)
## Create a new [PlayerNode] for the given [param player_name], giving control of it to [param peer_id].
##
## If a node with the given name already exists, only its multiplayer authority is changed, leaving the rest intact.
##
## If both node and multiplayer authority match the requested values, nothing is done at all.
@rpc("authority", "call_local", "reliable")
func rpc_possess_playernode(player_name: String, peer_id: int):
var playernode: PlayerNode = get_playernode(player_name)
# If the playernode does not exist, create it
if playernode == null:
playernode = playernode_scene.instantiate()
playernode.name_changed.connect(_on_playernode_name_changed.bind(playernode))
playernode.color_changed.connect(_on_playernode_color_changed.bind(playernode))
playernode.possessed.connect(_on_playernode_possessed.bind(playernode))
playernode.score_reported.connect(_on_playernode_score_reported.bind(playernode))
playernode.scores_changed.connect(_on_playernode_scores_changed.bind(playernode))
playernode.putt_performed.connect(_on_playernode_putt_performed.bind(playernode))
var sanitized_player_name = PlayerNode.sanitize_player_name(player_name)
playernode.player_name = sanitized_player_name
playernode.name = sanitized_player_name
# Determine the number of holes that this player has skipped
var played_holes = 0
for othernode in get_children():
var othernode_played_holes = len(othernode.hole_scores)
if othernode_played_holes > played_holes:
played_holes = othernode_played_holes
# Fill the empty scores with -1
for _index in range(played_holes):
playernode.hole_scores.push_back(-1)
# Add the playernode to the SceneTree
add_child(playernode)
# If the multiplayer authority does not match the requested one, make it match
playernode.possess(peer_id)
## Push the [field reported_score] of all children to the [field hole_scores] array, and reset its value to -1.
@rpc("authority", "call_local", "reliable")
func rpc_push_reported_scores():
for playernode in get_children():
playernode.hole_scores.push_back(playernode.reported_score)
playernode.reported_score = -1
func _on_playernode_name_changed(old: String, new: String, playernode: PlayerNode) -> void:
playernode_name_changed.emit(old, new, playernode)
func _on_playernode_color_changed(old: Color, new: Color, playernode: PlayerNode) -> void:
playernode_color_changed.emit(old, new, playernode)
func _on_playernode_possessed(old: int, new: int, playernode: PlayerNode) -> void:
playernode_possessed.emit(old, new, playernode)
if playernode.is_multiplayer_authority() and not multiplayer.is_server():
local_playernode_possessed.emit(old, new, playernode)
func _on_playernode_score_reported(strokes: int, playernode: PlayerNode) -> void:
playernode_score_reported.emit(strokes, playernode)
func _on_playernode_scores_changed(old: Array, new: Array, playernode: PlayerNode) -> void:
playernode_scores_changed.emit(old, new, playernode)
func _on_playernode_putt_performed(ball: GolfBall, playernode: PlayerNode) -> void:
playernode_putt_performed.emit(ball, playernode)
## Emitted when the name of one of the children [PlayerNode]s changes on the local scene.
signal playernode_name_changed(old: String, new: String, playernode: PlayerNode)
## Emitted when the color of one of the children [PlayerNode]s changes on the local scene.
signal playernode_color_changed(old: Color, new: Color, playernode: PlayerNode)
## Emitted everywhere when one of the children [PlayerNode]s has changed multiplayer authority.
signal playernode_possessed(old: int, new: int, playernode: PlayerNode)
## Emitted on a client when it becomes authority of a [PlayerNode].
signal local_playernode_possessed(old: int, new: int, playernode: PlayerNode)
## Emitted when a [PlayerNode] reports a score.
signal playernode_score_reported(strokes: int, playernode: PlayerNode)
## Emitted when the scores of one of the children [PlayerNode]s change on the local scene.
signal playernode_scores_changed(old: Array, new: Array, playernode: PlayerNode)
## Emitted when a [PlayerNode] performs a putt on its controlled [GolfBall].
signal playernode_putt_performed(ball: GolfBall, playernode: PlayerNode) |
function cachingDecoratorNew(func) {
let cache = [];
function wrapper(...args) {
const hash = args.join(',');
let index = cache.findIndex((item) => item.hash === hash);
if(index !== -1) {
console.log( "Из кэша: " + cache[index].result);
return "Из кэша: " + cache[index].result;
}
let result = func(...args);
cache.push({hash, result});
if(cache.length > 5){
cache.shift();
}
console.log( "Вычисляем: " + result);
return "Вычисляем: " + result;
}
return wrapper;
}
function debounceDecorator(func, ms) {
let timerId = null;
function wrapper(...args){
if (timerId === null) {
func(...args);
}
clearTimeout(timerId);
timerId = setTimeout(() => timerId = null, ms);
wrapper.count++;
}
return wrapper;
} |
import React from 'react';
import { Route, NavLink } from 'react-router-dom';
import styled from 'styled-components';
export default class Menu extends React.Component {
constructor(props) {
super(props);
this.state = {
display: false,
};
this.toggleDisplay = this.toggleDisplay.bind(this);
}
toggleDisplay(e) {
//NOTE: if user hits notification toggle from within Menu,
//prevent toggle display from overriding
e.target.id === 'notification-toggle' ?
null : this.setState({display: !this.state.display})
return;
}
render() {
// grid-area: menu refers to the templates provided in App.jsx
const MenuContainer = styled.div`
grid-area: menu;
color: black;
font-family: 'Zilla Slab';
font-size: 2em;
padding: 20px 0;
margin: 0;
&:hover{
text-decoration: underline;
}
@media screen and (min-device-width: 768px) and (max-device-width: 1050px){
position: fixed;
bottom: 0px;
z-index: 5;
background-color: white;
width: 100%;
display: flex;
justify-content: flex-end;
border-top: 3px solid firebrick;
border-bottom: 3px solid firebrick;
}
@media screen and (max-device-width: 480px) and (orientation: portrait){
position: fixed;
max-width: 100%;
bottom: 0px;
z-index: 5;
color: white;
height: .7em;
box-shadow: 2px 0px whitesmoke, -2px -2px whitesmoke;
background-color: white;
width: 110%;
display: flex;
justify-content: flex-end;
border-top: 2px solid firebrick;
border-bottom: 3px solid firebrick;
}
@media only screen and (min-device-width: 480px)
and (max-device-width: 800px)
and (orientation: landscape) {
position: fixed;
max-width: 100%;
bottom: 0px;
z-index: 5;
color: white;
height: .7em;
box-shadow: 2px 0px whitesmoke, -2px -2px whitesmoke;
background-color: white;
width: 110%;
display: flex;
justify-content: flex-end;
border-top: 2px solid firebrick;
border-bottom: 3px solid firebrick;
}
`;
const MenuTitle = styled.div`
visibility: ${this.props.menuLoad ? 'visible' : 'hidden'};
opacity: ${this.props.menuLoad ? 1 : 0};
transition: opacity 1s;
&:hover{
cursor: pointer;
}
@media screen and (min-device-width: 768px) and (max-device-width: 1024px){
padding-right: 10%;
color: firebrick;
font-size: .7em;
}
@media screen and (max-device-width: 480px) and (orientation: portrait){
padding-right: 10%;
color: firebrick;
font-size: .8em;
}
@media only screen and (min-device-width: 480px)
and (max-device-width: 800px)
and (orientation: landscape) {
padding-right: 10%;
color: firebrick;
font-size: .8em;
}
`;
const MenuItems = styled.div`
display: ${!this.state.display ? 'none' : 'block'};
position: absolute;
text-align: left;
list-style-type: none;
background-color: white;
min-width: 160px;
box-shadow: 1px 0px 5px 0px rgba(0,0,0,0.2);
z-index: 5;
padding: 20px;
@media screen and (min-device-width: 768px) and (max-device-width: 1024px){
left: 0;
}
a {
text-decoration: none;
color: black;
li {
margin: 15px 0 15px 0;
border-bottom: 1px solid white;
&:hover{
cursor: pointer;
color: firebrick;
}
@media screen and (min-device-width: 768px) and (max-device-width: 1050px){
font-size: 1em;
padding: 15px 0px 15px 30px;
}
@media screen and (max-device-width: 480px) and (orientation: portrait){
font-size: 1em;
padding: 15px 0px 15px 30px;
}
@media only screen and (min-device-width: 480px)
and (max-device-width: 800px)
and (orientation: landscape) {
font-size: 1em;
padding: 15px 0px 15px 30px;
}
}
}
@media screen and (min-device-width: 768px) and (max-device-width: 1050px){
transform: translateY(-107%);
width: 100%;
li:last-child{
border-bottom: none;
}
}
@media screen and (max-device-width: 480px) and (orientation: portrait){
transform: translateY(-107%);
width: 100%;
li:last-child{
border-bottom: none;
}
}
@media only screen and (min-device-width: 480px)
and (max-device-width: 800px)
and (orientation: landscape) {
transform: translateY(-107%);
width: 100%;
li:last-child{
border-bottom: none;
}
}
`;
const NotificationTitle = styled.li`
color: firebrick;
box-shadow: 0 4px 2px -2px lightgray;
background-color: white;
border-bottom: 2px solid firebrick;
padding: 15px 0 5px 0;
font-size: .6em;
letter-spacing: 3px;
margin-bottom:10px;
@media screen and (min-device-width: 768px) and (max-device-width: 1024px){
padding: 15px 0px 15px 30px;
box-shadow: none!important;
border: none!important;
}
@media screen and (max-device-width: 480px) and (orientation: portrait){
padding: 15px 0px 15px 30px;
box-shadow: none!important;
border: none!important;
}
@media only screen and (min-device-width: 480px)
and (max-device-width: 800px)
and (orientation: landscape) {
padding: 15px 0px 15px 30px;
box-shadow: none!important;
border: none!important;
}
`;
const NotificationSwitch = styled.li`
display: flex;
color: black;
font-family: 'Source Code Pro', monospace;
align-items: center;
justify-content: space-around;
display: flex;
flex-direction: row-reverse;
justify-content: space-around;
align-items: center;
input[type=checkbox]{
height: 0;
width: 0;
visibility: hidden;
}
label {
cursor: pointer;
width: 50px;
height: 32px;
background: grey;
display: block;
border-radius: 100px;
position: relative;
}
label:after {
content: '';
position: absolute;
top: 2px;
left: 3px;
width: 28px;
height: 28px;
background: #fff;
border-radius: 45px;
transition: 0.3s;
}
input:checked + label {
background: green;
}
input:checked + label:after {
left: calc(100% - 5px);
transform: translateX(-90%);
}
label:active:after {
width: 100px;
}
@media screen and (max-device-width: 480px) and (orientation: portrait){
label {
cursor: pointer;
width: 75px;
height: 42px;
background: grey;
display: block;
border-radius: 100px;
position: relative;
}
label:after {
content: '';
position: absolute;
top: 2px;
left: 2px;
width: 38px;
height: 38px;
background: #fff;
border-radius: 45px;
transition: 0.3s;
}
}
`;
return (
<MenuContainer onClick={this.toggleDisplay}>
<MenuTitle>Menu</MenuTitle>
<MenuItems>
{/* <NavLink to="/dispatch-history">
<li>Dispatch History </li>
</NavLink> */}
<NavLink to="/user-settings">
<li>Settings </li>
</NavLink>
{/* <NotificationTitle> Notifications:</NotificationTitle>
<NotificationSwitch>
<span>{this.props.ns ? 'ON' : 'OFF'}</span>
<input
type="checkbox"
id={'notifications'}
defaultChecked={this.props.ns}
onChange={this.props.mns}/>
<label htmlFor={'notifications'} id="notification-toggle"></label>
</NotificationSwitch> */}
</MenuItems>
</MenuContainer>
)
}
} |
---
title: "Psy 612: Data Analysis II"
subtitle: "Department of Psychology, University of Oregon"
author: "Winter 2022. Instructor: Sara J. Weston"
output:
html_document:
toc: TRUE
toc_depth: 2
toc_float: TRUE
theme: cosmo
---
# Overview
This course is the second in a 3-term sequence of classes designed to provide a
thorough grounding in statistical concepts, methods, and applications of relevance to psychological science and related sciences. The aim of the course is to help students develop skills in the analysis and interpretation of real psychological data. Our focus will be both conceptual and mathematical -- that is, understanding the underlying mathematical principles of statistics enhances ones' ability to interpret and think critically about the use of statistics. Students will also learn the basics of the R language and use this program to wrangle, visualize, summarize, and test hypotheses with data.
## Meeting times and locations
**Lecture:** Tuesdays and Thursdays, 10:00 - 11:20 am, 209 UNIV and [Zoom](https://uoregon.zoom.us/j/98429454216?pwd=QXd5YzBiYjVuYU51a0wyeHlzUnI5dz09)
**Lab (Section 23919):** Fridays,
9:00 - 10:20 am, [Zoom](https://uoregon.zoom.us/j/91791352220?pwd=WGxzYUMrWGxKZ1VXU0x4WmwyUFdIUT09)
**Lab (Section 23920):** Fridays, 10:30 - 11:50 am, [Zoom](https://uoregon.zoom.us/j/92012864290?pwd=Y202bGM2M2lpZGlEbUw0OU0yTFJ3Zz09)
## Instructors
**Sara Weston** -- [sweston2@uoregon.edu](mailto:sweston2@uoregon.edu)
Office Hours: [By appointment](https://calendly.com/sara-weston/weston-office-hours)
**Wanjia Guo** -- [wanjiag@uoregon.edu](mailto:wanjiag@uoregon.edu)
Office Hours: Wednesdays, 10:00 am - 12:00 pm, [Zoom](https://uoregon.zoom.us/j/93405656620?pwd=YlNiUDllTzRFTGM5eG45NDVMcmx1UT09)
**Cameron Kay** -- [ckay@uoregon.edu](mailto:ckay@uoregon.edu)
Office Hours: Mondays, 12:30 - 2:30 pm, [Zoom](https://uoregon.zoom.us/j/97617760372?pwd=RTY2TjBYVGtOUGxSa3JCWk1UVnZtUT09)
# Materials
## Textbook
We will primarily be referring to chapters in [_Learning Statistics with R_](https://learningstatisticswithr-bookdown.netlify.com/index.html) by Danielle Navarro. This textbook is available for free online. You may choose to purchase a paper copy if you wish, but it is not required. Additional readings assignments will be posted here.
## LaTeX
You'll need to download and install some version of LaTeX. There are different software programs for different operating systems -- you can find links to download them all [here](https://www.latex-project.org/get/).
## R and RStudio
Students must have the latest version of R, which can be downloaded [here](https://ftp.osuosl.org/pub/cran/). It is strongly recommended that students also download the RStudio GUI, available [here](https://www.rstudio.com/products/rstudio/download/#download). Both software programs are free.
## Resources for R and RStudio
While we will be covering the use of R and RStudio extensively in both lecture and lab, one of the key skills required to use R is the ability to find answers on the Internet. The R community (sometimes referred to as the useR community) tends to be friendly and helpful and enjoys solving R-related problems in their spare time. For that reason, many common questions or problems have been posted to spaces online and answered by smart people. Finding and deciphering those answers is the key skill you should seek to hone this year. It's much more important than remembering function names.
Here are some sites where you can find the answers to many R questions and learn new tricks:
### For learning the basics
- [_YaRrr, the Pirate's Guide to R_](https://bookdown.org/ndphillips/YaRrr/) by Nathaniel Phillips
- [_R for Data Science_](https://r4ds.had.co.nz/) by Hadley Wickham
- [_R Cookbook_](http://www.cookbook-r.com/) by Winston Chang
- [_An Introduction to Statistical Learning_](http://www-bcf.usc.edu/~gareth/ISL) by Gareth James, Daniela Witten, Trevor Hastie and Robert Tibshirani
### For plotting
- The [Graphs chapter of _R Cookbook_](http://www.cookbook-r.com/Graphs/) by Winston Chang
### Quick resources
- [Cheat Sheets](https://www.rstudio.com/resources/cheatsheets)
- [Quick-R](https://www.statmethods.net)
### Online forums
- [Stack Overflow](https://stackoverflow.com) \
- [Cross Validated](https://stats.stackexchange.com) |
import { Address, ProviderRpcClient, Contract } from 'everscale-inpage-provider';
// For browser environment:
import { EverscaleStandaloneClient } from 'everscale-standalone-client';
import { SampleWalletContract } from './deployHelpers/SampleWalletContract';
import { BioVenomSigner } from './BioVenomSigner';
import { BioVenomCookie } from './BioVenomCookie';
import { BioVenomDeployer } from './BioVenomDeployer';
import * as Constants from './Constants';
import { Signer, TonClient, ParamsOfEncodeMessage, ParamsOfProcessMessage } from '@eversdk/core';
import axios from 'axios';
export class BioVenomProvider {
private provider?: ProviderRpcClient;
private walletAbi: any;
private signer: BioVenomSigner;
private walletContract: any;
private unsignedUserOp: any;
private cookie: BioVenomCookie;
private bioVenomDeployerInstance: BioVenomDeployer;
private tonClient: TonClient;
private walletAddress: string = '';
constructor() {
this.bioVenomDeployerInstance = new BioVenomDeployer();
this.tonClient = this.bioVenomDeployerInstance.getTonClient();
this.walletAbi = SampleWalletContract.abi;
this.signer = new BioVenomSigner();
this.cookie = new BioVenomCookie();
this.provider = new ProviderRpcClient({
forceUseFallback: true,
fallback: () =>
EverscaleStandaloneClient.create({
connection: {
id: 1002, // network id
group: 'dev',
type: 'jrpc',
data: {
endpoint: Constants.TestnetRPC,
},
},
}),
});
const userName = localStorage.getItem('username');
const credential = JSON.parse(localStorage.getItem(userName) || '{}');
// if credential is null or credential.walletAddress is null, set wallet address to empty string else set it to credential.walletAddress
if (!credential || !credential.walletAddress) {
this.walletAddress = '';
} else {
this.walletAddress = credential.walletAddress;
}
}
public async checkUsername(username: string): Promise<boolean> {
try {
const response = await axios.post(Constants.CHECKUSERNAME_URL, {
username: username,
});
return true;
} catch (error) {
if (error.response && error.response.status == 409) {
throw new Error('Username already taken');
} else if (error.response && error.response.status == 500) {
throw new Error('Internal server error');
} else {
console.error('Error checking username: ', error);
throw error;
}
}
}
public getProvider(): ProviderRpcClient {
return this.provider;
}
public getAnyWalletContract(address: string) {
const contractAddress = new Address(address);
const contract = new this.provider.Contract(this.walletAbi, contractAddress);
return contract;
}
public setWalletContract(address: string) {
this.walletContract = this.getAnyWalletContract(address);
}
public getWalletContract() {
return this.walletContract;
}
public async preCalculateAddress(publicKey: any): Promise<string> {
console.log('reached preCalculateAddress in BioVenomProvider');
console.log('preCalculating wallet address');
const preCalculatedAddress = await this.bioVenomDeployerInstance.calcWalletAddress(publicKey[0], publicKey[1]);
console.log('preCalculated walletAddress: ', preCalculatedAddress);
this.setWalletContract(preCalculatedAddress);
return preCalculatedAddress;
}
public async saveCredentials(): Promise<boolean> {
const userName = localStorage.getItem('username');
const credential = JSON.parse(localStorage.getItem(userName) || '{}');
if (!credential || !credential.walletAddress) {
throw new Error('Credentials not saved locally');
}
try {
const response = await axios.post(Constants.DATAURL, {
username: userName,
walletAddress: credential.walletAddress,
encodedId: credential.encodedId,
publicKey: credential.publicKey,
});
// check the status code of the response
if (response.status == 500) {
throw new Error('Internal server error while saving username');
}
} catch (error) {
console.error('Error saving usename: ', error);
throw error;
}
return true;
}
public async deployWalletContract(publicKey: any): Promise<string> {
// requires that the wallet contract is prefunded
try {
const walletAddress = await this.bioVenomDeployerInstance.deployWalletContract(publicKey[0], publicKey[1]);
console.log('wallet deployed at: ', walletAddress);
this.walletAddress = walletAddress;
await this.saveCredentials();
return walletAddress;
} catch (error) {
console.error('Error deploying contract: ', error);
throw error;
}
}
public async createUnsignedUserOp(encodedPayload: any, value: number = 0): Promise<any> {
/**
* Pass in an encodedPayload if you want to call any arbitrary function on the wallet contract.
* For example if you want to call the `setState` function on the wallet contract, you would pass in
* const encodedPayload = await sampleContract.methods.setState({_state: 20}).encodeInternal();
*/
this.unsignedUserOp = {
_signatureOp: '',
_payloadOp: encodedPayload,
_valueOp: 0,
};
return this.unsignedUserOp;
}
public async encodeSignatureParams(rs: any, x1: any, y1: any, x2: any, y2: any): Promise<any> {
const clientEncodedSignature = await this.tonClient.abi.encode_boc({
params: [
{ name: 'r', type: 'uint256' },
{ name: 's', type: 'uint256' },
{ name: 'x1', type: 'uint256' },
{ name: 'y1', type: 'uint256' },
{ name: 'x2', type: 'uint256' },
{ name: 'y2', type: 'uint256' },
],
data: {
r: rs[0],
s: rs[1],
x1: x1,
y1: y1,
x2: x2,
y2: y2,
},
});
console.log('clientEncodedSignature', clientEncodedSignature);
return clientEncodedSignature.boc;
}
// do the same as above to encode useroperation
public async encodeUserOperation(encodedSignature: any, encodedPayload: any, value: number = 0): Promise<any> {
const nonce = (await this.bioVenomDeployerInstance.runGetMethod('getNonce', this.walletAddress)).value0;
console.log('nonce', nonce);
const clientEncodedUserOperation = await this.tonClient.abi.encode_boc({
params: [
{ name: '_nonce', type: 'uint256' },
{ name: '_signatureOp', type: 'cell' },
{ name: '_payloadOp', type: 'cell' },
{ name: '_valueOp', type: 'uint128' },
],
data: {
_nonce: nonce,
_signatureOp: encodedSignature,
_payloadOp: encodedPayload,
_valueOp: value,
},
});
return clientEncodedUserOperation.boc;
}
public async signTvmCellUserOp(unsignedUserOp: any, encodedId: any, pubkey: any): Promise<any> {
const { rs, x1, y1, x2, y2 } = await this.signer.sign(unsignedUserOp, encodedId, pubkey);
const encodedSignature = await this.encodeSignatureParams(rs, x1, y1, x2, y2);
this.unsignedUserOp._signatureOp = encodedSignature;
const signedTVMCellUserOp = await this.encodeUserOperation(encodedSignature, this.unsignedUserOp._payloadOp, 0);
return signedTVMCellUserOp;
}
public async executeTransaction(
destinationAddress: Address,
signedTVMCellUserOp: any,
value: any,
bounce: boolean = true,
): Promise<any> {
console.log('destinationAddress', destinationAddress);
console.log('signedTVMCellUserOp', signedTVMCellUserOp);
console.log('value', value);
console.log('bounce', bounce);
const params = {
send_events: false,
message_encode_params: {
address: this.walletAddress,
abi: {
type: 'Contract',
value: this.walletAbi,
},
call_set: {
function_name: 'sendTransaction',
input: {
dest: destinationAddress.toString(),
value: value,
bounce: bounce,
userOp: signedTVMCellUserOp,
},
},
signer: { type: 'None' } as Signer,
} as ParamsOfEncodeMessage,
} as ParamsOfProcessMessage;
try {
const response = await this.tonClient.processing.process_message(params);
return response;
} catch (error) {
console.error('Error executing transaction:', error);
throw error; // Re-throw the error so it can be caught in the UI or by the calling function.
}
}
public getBioVenomDeployerInstance(): BioVenomDeployer {
return this.bioVenomDeployerInstance;
}
}
//583175822eb7355d5554cd6d6464cea5a6bd714e69b5395a4c021a8377a1b4a0
// TODO: Add registration logic here
// TODO: save the credentials to the cookie
// TODO: create a utils folder and add constants and other utility functions
// "Invalid ABI specified: Wrong data format in `_payloadOp` parameter: |
import { toFile } from 'openai/uploads'
import { ChatCompletionMessageParam } from 'openai/resources/chat'
import { QBAIRephrase, Tone } from 'qb-ai-rephrase'
import { QBAITranslate } from 'qb-ai-translate'
import openAIApi from './api'
import { completeSentence } from './utils'
export const createTranscriptionWithTime = async (audio: MultipartFile) => {
const file = await toFile(audio.buffer, audio.filename, {
type: audio.mimetype,
})
const transcription = await openAIApi.audio.transcriptions.create({
file,
model: 'whisper-1',
response_format: 'srt',
})
const transcriptionText = transcription as unknown as string
const srtRegex = /^([\d:]+),\d+ --> ([\d:]+),\d+\s+(.*)$/gm
return Array.from(transcriptionText.matchAll(srtRegex)).reduce<
Array<{ start: string; end: string; text: string }>
>((res, item) => {
const [, start, end, text] = item
return [...res, { start, end, text }]
}, [])
}
export const createAudioDialogAnalytics = async (audio: MultipartFile) => {
const transcription = await createTranscriptionWithTime(audio)
const transcriptionText = transcription.map(({ text }) => text).join(' ')
const chatComplationConfig = {
model: 'gpt-3.5-turbo',
temperature: 0,
}
const messagesForSummary: ChatCompletionMessageParam[] = [
{
role: 'user',
content: 'Generate summary in English from this dialog',
},
{ role: 'user', content: transcriptionText },
]
const messagesForActions: ChatCompletionMessageParam[] = [
{
role: 'system',
content:
'If you don\'t have enough information to make an action points, display the message "There is no sufficient information to generate an action points"',
},
{
role: 'user',
content: `Generate action points in English that the consultant said to do from my dialog. Display only list without title.`,
},
{ role: 'user', content: `My dialog:\n${transcriptionText}` },
]
const textRegex = /[\p{L}\p{N}]+/gu
const [summaryRes, actionsRes] = textRegex.test(transcriptionText)
? await Promise.all([
openAIApi.chat.completions.create({
messages: messagesForSummary,
...chatComplationConfig,
}),
openAIApi.chat.completions.create({
messages: messagesForActions,
...chatComplationConfig,
}),
])
: []
const summary =
summaryRes?.choices?.[0].message?.content ||
'There is no sufficient information to generate a summary'
const actions =
actionsRes?.choices?.[0].message?.content ||
'There is no sufficient information to generate an action points'
return {
transcription,
summary,
actions,
}
}
export const createQuickAnswerForDialog = async (
profession: string,
dialogDescription: string,
dialogMessages: ChatCompletionMessageParam[],
) => {
const messages: ChatCompletionMessageParam[] = [
{
role: 'system',
content: `You are a specialist ${profession}. You are consulting the client. You were approached with an issue: "${dialogDescription}".`,
},
...dialogMessages,
]
const { choices } = await openAIApi.chat.completions.create({
messages,
model: 'gpt-3.5-turbo',
temperature: 0.5,
})
return completeSentence(choices[0]?.message?.content)
}
export const createProviderKeywords = async (
profession: string,
description: string,
) => {
const parsedDescription = description.replaceAll('\n', ' ')
const prompt =
`You are a specialist ${profession} with a description: "${parsedDescription}"\n` +
'Generate keywords in English by description that will allow customers to search for specialists in the description of the issue, separated by commas.\n\n'
// TODO: Replace with openAIApi.chat.completions.create
const { choices } = await openAIApi.completions.create({
prompt,
model: 'gpt-3.5-turbo-instruct',
temperature: 0,
max_tokens: 256,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
})
return choices[0]?.text?.trim() || ''
}
export const findProviderIdsByKeywords = async (
usersKeywords: string,
topic: string,
) => {
const messages: ChatCompletionMessageParam[] = [
{
role: 'system',
content:
'You are a receptionist. You have a list of consultants in the format: "id: keywords"\n' +
`${usersKeywords}\n` +
'Keywords describe the consultant. User input issue. Select consultants for the user. If there are no suitable consultants, do not display all.',
},
{ role: 'user', content: topic },
{
role: 'user',
content:
'Display only list of the id of suitable consultants without explanation of reasons.',
},
]
const { choices } = await openAIApi.chat.completions.create({
messages,
model: 'gpt-3.5-turbo',
temperature: 0,
top_p: 1,
})
const providerIds: string[] | null | undefined =
choices?.[0]?.message?.content?.match(/\d+/g)
return providerIds
}
export const createRephraseForDialog = async (
text: string,
tone: Tone,
dialogMessages: Array<{ role: 'me' | 'other'; content: string }>,
) => {
const settings = QBAIRephrase.createDefaultAIRephraseSettings()
settings.apiKey = openAIApi.apiKey
settings.tone = tone
const rephrasedText = await QBAIRephrase.rephrase(
text,
dialogMessages,
settings,
)
return rephrasedText
}
export const createTranslate = async (
text: string,
dialogMessages: Array<{ role: 'user' | 'assistant'; content: string }>,
language: string,
) => {
const settings = QBAITranslate.createDefaultAITranslateSettings()
settings.apiKey = openAIApi.apiKey
settings.language = language || 'English'
const translatedText = await QBAITranslate.translate(
text,
dialogMessages,
settings,
)
return translatedText
} |
/*
* Copyright 2010-2020 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 com.amazonaws.services.polly.model;
import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* Synthesizes UTF-8 input, plain text or SSML, to a stream of bytes. SSML input
* must be valid, well-formed SSML. Some alphabets might not be available with
* all the voices (for example, Cyrillic might not be read at all by English
* voices) unless phoneme mapping is used. For more information, see <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/how-text-to-speech-works.html"
* >How it Works</a>.
* </p>
*/
public class SynthesizeSpeechRequest extends AmazonWebServiceRequest implements Serializable {
/**
* <p>
* Specifies the engine (<code>standard</code> or <code>neural</code>) for
* Amazon Polly to use when processing input text for speech synthesis. For
* information on Amazon Polly voices and which voices are available in
* standard-only, NTTS-only, and both standard and NTTS formats, see <a
* href=
* "https://docs.aws.amazon.com/polly/latest/dg/voicelist.html">Available
* Voices</a>.
* </p>
* <p>
* <b>NTTS-only voices</b>
* </p>
* <p>
* When using NTTS-only voices such as Kevin (en-US), this parameter is
* required and must be set to <code>neural</code>. If the engine is not
* specified, or is set to <code>standard</code>, this will result in an
* error.
* </p>
* <p>
* Type: String
* </p>
* <p>
* Valid Values: <code>standard</code> | <code>neural</code>
* </p>
* <p>
* Required: Yes
* </p>
* <p>
* <b>Standard voices</b>
* </p>
* <p>
* For standard voices, this is not required; the engine parameter defaults
* to <code>standard</code>. If the engine is not specified, or is set to
* <code>standard</code> and an NTTS-only voice is selected, this will
* result in an error.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>standard, neural
*/
private String engine;
/**
* <p>
* Optional language code for the Synthesize Speech request. This is only
* necessary if using a bilingual voice, such as Aditi, which can be used
* for either Indian English (en-IN) or Hindi (hi-IN).
* </p>
* <p>
* If a bilingual voice is used and no language code is specified, Amazon
* Polly will use the default language of the bilingual voice. The default
* language for any voice is the one returned by the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation for the <code>LanguageCode</code>
* parameter. For example, if no language code is specified, Aditi will use
* Indian English rather than Hindi.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>arb, cmn-CN, cy-GB, da-DK, de-DE, en-AU, en-GB,
* en-GB-WLS, en-IN, en-US, es-ES, es-MX, es-US, fr-CA, fr-FR, is-IS, it-IT,
* ja-JP, hi-IN, ko-KR, nb-NO, nl-NL, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU,
* sv-SE, tr-TR
*/
private String languageCode;
/**
* <p>
* List of one or more pronunciation lexicon names you want the service to
* apply during synthesis. Lexicons are applied only if the language of the
* lexicon is the same as the language of the voice. For information about
* storing lexicons, see <a
* href="https://docs.aws.amazon.com/polly/latest/dg/API_PutLexicon.html"
* >PutLexicon</a>.
* </p>
*/
private java.util.List<String> lexiconNames;
/**
* <p>
* The format in which the returned output will be encoded. For audio
* stream, this will be mp3, ogg_vorbis, or pcm. For speech marks, this will
* be json.
* </p>
* <p>
* When pcm is used, the content returned is audio/pcm in a signed 16-bit, 1
* channel (mono), little-endian format.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>json, mp3, ogg_vorbis, pcm
*/
private String outputFormat;
/**
* <p>
* The audio frequency specified in Hz.
* </p>
* <p>
* The valid values for mp3 and ogg_vorbis are "8000", "16000", "22050", and
* "24000". The default value for standard voices is "22050". The default
* value for neural voices is "24000".
* </p>
* <p>
* Valid values for pcm are "8000" and "16000" The default value is "16000".
* </p>
*/
private String sampleRate;
/**
* <p>
* The type of speech marks returned for the input text.
* </p>
*/
private java.util.List<String> speechMarkTypes;
/**
* <p>
* Input text to synthesize. If you specify <code>ssml</code> as the
* <code>TextType</code>, follow the SSML format for the input text.
* </p>
*/
private String text;
/**
* <p>
* Specifies whether the input text is plain text or SSML. The default value
* is plain text. For more information, see <a
* href="https://docs.aws.amazon.com/polly/latest/dg/ssml.html">Using
* SSML</a>.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>ssml, text
*/
private String textType;
/**
* <p>
* Voice ID to use for the synthesis. You can get a list of available voice
* IDs by calling the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>Aditi, Amy, Astrid, Bianca, Brian, Camila, Carla,
* Carmen, Celine, Chantal, Conchita, Cristiano, Dora, Emma, Enrique, Ewa,
* Filiz, Geraint, Giorgio, Gwyneth, Hans, Ines, Ivy, Jacek, Jan, Joanna,
* Joey, Justin, Karl, Kendra, Kevin, Kimberly, Lea, Liv, Lotte, Lucia,
* Lupe, Mads, Maja, Marlene, Mathieu, Matthew, Maxim, Mia, Miguel, Mizuki,
* Naja, Nicole, Olivia, Penelope, Raveena, Ricardo, Ruben, Russell, Salli,
* Seoyeon, Takumi, Tatyana, Vicki, Vitoria, Zeina, Zhiyu
*/
private String voiceId;
/**
* <p>
* Specifies the engine (<code>standard</code> or <code>neural</code>) for
* Amazon Polly to use when processing input text for speech synthesis. For
* information on Amazon Polly voices and which voices are available in
* standard-only, NTTS-only, and both standard and NTTS formats, see <a
* href=
* "https://docs.aws.amazon.com/polly/latest/dg/voicelist.html">Available
* Voices</a>.
* </p>
* <p>
* <b>NTTS-only voices</b>
* </p>
* <p>
* When using NTTS-only voices such as Kevin (en-US), this parameter is
* required and must be set to <code>neural</code>. If the engine is not
* specified, or is set to <code>standard</code>, this will result in an
* error.
* </p>
* <p>
* Type: String
* </p>
* <p>
* Valid Values: <code>standard</code> | <code>neural</code>
* </p>
* <p>
* Required: Yes
* </p>
* <p>
* <b>Standard voices</b>
* </p>
* <p>
* For standard voices, this is not required; the engine parameter defaults
* to <code>standard</code>. If the engine is not specified, or is set to
* <code>standard</code> and an NTTS-only voice is selected, this will
* result in an error.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>standard, neural
*
* @return <p>
* Specifies the engine (<code>standard</code> or
* <code>neural</code>) for Amazon Polly to use when processing
* input text for speech synthesis. For information on Amazon Polly
* voices and which voices are available in standard-only,
* NTTS-only, and both standard and NTTS formats, see <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/voicelist.html"
* >Available Voices</a>.
* </p>
* <p>
* <b>NTTS-only voices</b>
* </p>
* <p>
* When using NTTS-only voices such as Kevin (en-US), this parameter
* is required and must be set to <code>neural</code>. If the engine
* is not specified, or is set to <code>standard</code>, this will
* result in an error.
* </p>
* <p>
* Type: String
* </p>
* <p>
* Valid Values: <code>standard</code> | <code>neural</code>
* </p>
* <p>
* Required: Yes
* </p>
* <p>
* <b>Standard voices</b>
* </p>
* <p>
* For standard voices, this is not required; the engine parameter
* defaults to <code>standard</code>. If the engine is not
* specified, or is set to <code>standard</code> and an NTTS-only
* voice is selected, this will result in an error.
* </p>
* @see Engine
*/
public String getEngine() {
return engine;
}
/**
* <p>
* Specifies the engine (<code>standard</code> or <code>neural</code>) for
* Amazon Polly to use when processing input text for speech synthesis. For
* information on Amazon Polly voices and which voices are available in
* standard-only, NTTS-only, and both standard and NTTS formats, see <a
* href=
* "https://docs.aws.amazon.com/polly/latest/dg/voicelist.html">Available
* Voices</a>.
* </p>
* <p>
* <b>NTTS-only voices</b>
* </p>
* <p>
* When using NTTS-only voices such as Kevin (en-US), this parameter is
* required and must be set to <code>neural</code>. If the engine is not
* specified, or is set to <code>standard</code>, this will result in an
* error.
* </p>
* <p>
* Type: String
* </p>
* <p>
* Valid Values: <code>standard</code> | <code>neural</code>
* </p>
* <p>
* Required: Yes
* </p>
* <p>
* <b>Standard voices</b>
* </p>
* <p>
* For standard voices, this is not required; the engine parameter defaults
* to <code>standard</code>. If the engine is not specified, or is set to
* <code>standard</code> and an NTTS-only voice is selected, this will
* result in an error.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>standard, neural
*
* @param engine <p>
* Specifies the engine (<code>standard</code> or
* <code>neural</code>) for Amazon Polly to use when processing
* input text for speech synthesis. For information on Amazon
* Polly voices and which voices are available in standard-only,
* NTTS-only, and both standard and NTTS formats, see <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/voicelist.html"
* >Available Voices</a>.
* </p>
* <p>
* <b>NTTS-only voices</b>
* </p>
* <p>
* When using NTTS-only voices such as Kevin (en-US), this
* parameter is required and must be set to <code>neural</code>.
* If the engine is not specified, or is set to
* <code>standard</code>, this will result in an error.
* </p>
* <p>
* Type: String
* </p>
* <p>
* Valid Values: <code>standard</code> | <code>neural</code>
* </p>
* <p>
* Required: Yes
* </p>
* <p>
* <b>Standard voices</b>
* </p>
* <p>
* For standard voices, this is not required; the engine
* parameter defaults to <code>standard</code>. If the engine is
* not specified, or is set to <code>standard</code> and an
* NTTS-only voice is selected, this will result in an error.
* </p>
* @see Engine
*/
public void setEngine(String engine) {
this.engine = engine;
}
/**
* <p>
* Specifies the engine (<code>standard</code> or <code>neural</code>) for
* Amazon Polly to use when processing input text for speech synthesis. For
* information on Amazon Polly voices and which voices are available in
* standard-only, NTTS-only, and both standard and NTTS formats, see <a
* href=
* "https://docs.aws.amazon.com/polly/latest/dg/voicelist.html">Available
* Voices</a>.
* </p>
* <p>
* <b>NTTS-only voices</b>
* </p>
* <p>
* When using NTTS-only voices such as Kevin (en-US), this parameter is
* required and must be set to <code>neural</code>. If the engine is not
* specified, or is set to <code>standard</code>, this will result in an
* error.
* </p>
* <p>
* Type: String
* </p>
* <p>
* Valid Values: <code>standard</code> | <code>neural</code>
* </p>
* <p>
* Required: Yes
* </p>
* <p>
* <b>Standard voices</b>
* </p>
* <p>
* For standard voices, this is not required; the engine parameter defaults
* to <code>standard</code>. If the engine is not specified, or is set to
* <code>standard</code> and an NTTS-only voice is selected, this will
* result in an error.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>standard, neural
*
* @param engine <p>
* Specifies the engine (<code>standard</code> or
* <code>neural</code>) for Amazon Polly to use when processing
* input text for speech synthesis. For information on Amazon
* Polly voices and which voices are available in standard-only,
* NTTS-only, and both standard and NTTS formats, see <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/voicelist.html"
* >Available Voices</a>.
* </p>
* <p>
* <b>NTTS-only voices</b>
* </p>
* <p>
* When using NTTS-only voices such as Kevin (en-US), this
* parameter is required and must be set to <code>neural</code>.
* If the engine is not specified, or is set to
* <code>standard</code>, this will result in an error.
* </p>
* <p>
* Type: String
* </p>
* <p>
* Valid Values: <code>standard</code> | <code>neural</code>
* </p>
* <p>
* Required: Yes
* </p>
* <p>
* <b>Standard voices</b>
* </p>
* <p>
* For standard voices, this is not required; the engine
* parameter defaults to <code>standard</code>. If the engine is
* not specified, or is set to <code>standard</code> and an
* NTTS-only voice is selected, this will result in an error.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
* @see Engine
*/
public SynthesizeSpeechRequest withEngine(String engine) {
this.engine = engine;
return this;
}
/**
* <p>
* Specifies the engine (<code>standard</code> or <code>neural</code>) for
* Amazon Polly to use when processing input text for speech synthesis. For
* information on Amazon Polly voices and which voices are available in
* standard-only, NTTS-only, and both standard and NTTS formats, see <a
* href=
* "https://docs.aws.amazon.com/polly/latest/dg/voicelist.html">Available
* Voices</a>.
* </p>
* <p>
* <b>NTTS-only voices</b>
* </p>
* <p>
* When using NTTS-only voices such as Kevin (en-US), this parameter is
* required and must be set to <code>neural</code>. If the engine is not
* specified, or is set to <code>standard</code>, this will result in an
* error.
* </p>
* <p>
* Type: String
* </p>
* <p>
* Valid Values: <code>standard</code> | <code>neural</code>
* </p>
* <p>
* Required: Yes
* </p>
* <p>
* <b>Standard voices</b>
* </p>
* <p>
* For standard voices, this is not required; the engine parameter defaults
* to <code>standard</code>. If the engine is not specified, or is set to
* <code>standard</code> and an NTTS-only voice is selected, this will
* result in an error.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>standard, neural
*
* @param engine <p>
* Specifies the engine (<code>standard</code> or
* <code>neural</code>) for Amazon Polly to use when processing
* input text for speech synthesis. For information on Amazon
* Polly voices and which voices are available in standard-only,
* NTTS-only, and both standard and NTTS formats, see <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/voicelist.html"
* >Available Voices</a>.
* </p>
* <p>
* <b>NTTS-only voices</b>
* </p>
* <p>
* When using NTTS-only voices such as Kevin (en-US), this
* parameter is required and must be set to <code>neural</code>.
* If the engine is not specified, or is set to
* <code>standard</code>, this will result in an error.
* </p>
* <p>
* Type: String
* </p>
* <p>
* Valid Values: <code>standard</code> | <code>neural</code>
* </p>
* <p>
* Required: Yes
* </p>
* <p>
* <b>Standard voices</b>
* </p>
* <p>
* For standard voices, this is not required; the engine
* parameter defaults to <code>standard</code>. If the engine is
* not specified, or is set to <code>standard</code> and an
* NTTS-only voice is selected, this will result in an error.
* </p>
* @see Engine
*/
public void setEngine(Engine engine) {
this.engine = engine.toString();
}
/**
* <p>
* Specifies the engine (<code>standard</code> or <code>neural</code>) for
* Amazon Polly to use when processing input text for speech synthesis. For
* information on Amazon Polly voices and which voices are available in
* standard-only, NTTS-only, and both standard and NTTS formats, see <a
* href=
* "https://docs.aws.amazon.com/polly/latest/dg/voicelist.html">Available
* Voices</a>.
* </p>
* <p>
* <b>NTTS-only voices</b>
* </p>
* <p>
* When using NTTS-only voices such as Kevin (en-US), this parameter is
* required and must be set to <code>neural</code>. If the engine is not
* specified, or is set to <code>standard</code>, this will result in an
* error.
* </p>
* <p>
* Type: String
* </p>
* <p>
* Valid Values: <code>standard</code> | <code>neural</code>
* </p>
* <p>
* Required: Yes
* </p>
* <p>
* <b>Standard voices</b>
* </p>
* <p>
* For standard voices, this is not required; the engine parameter defaults
* to <code>standard</code>. If the engine is not specified, or is set to
* <code>standard</code> and an NTTS-only voice is selected, this will
* result in an error.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>standard, neural
*
* @param engine <p>
* Specifies the engine (<code>standard</code> or
* <code>neural</code>) for Amazon Polly to use when processing
* input text for speech synthesis. For information on Amazon
* Polly voices and which voices are available in standard-only,
* NTTS-only, and both standard and NTTS formats, see <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/voicelist.html"
* >Available Voices</a>.
* </p>
* <p>
* <b>NTTS-only voices</b>
* </p>
* <p>
* When using NTTS-only voices such as Kevin (en-US), this
* parameter is required and must be set to <code>neural</code>.
* If the engine is not specified, or is set to
* <code>standard</code>, this will result in an error.
* </p>
* <p>
* Type: String
* </p>
* <p>
* Valid Values: <code>standard</code> | <code>neural</code>
* </p>
* <p>
* Required: Yes
* </p>
* <p>
* <b>Standard voices</b>
* </p>
* <p>
* For standard voices, this is not required; the engine
* parameter defaults to <code>standard</code>. If the engine is
* not specified, or is set to <code>standard</code> and an
* NTTS-only voice is selected, this will result in an error.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
* @see Engine
*/
public SynthesizeSpeechRequest withEngine(Engine engine) {
this.engine = engine.toString();
return this;
}
/**
* <p>
* Optional language code for the Synthesize Speech request. This is only
* necessary if using a bilingual voice, such as Aditi, which can be used
* for either Indian English (en-IN) or Hindi (hi-IN).
* </p>
* <p>
* If a bilingual voice is used and no language code is specified, Amazon
* Polly will use the default language of the bilingual voice. The default
* language for any voice is the one returned by the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation for the <code>LanguageCode</code>
* parameter. For example, if no language code is specified, Aditi will use
* Indian English rather than Hindi.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>arb, cmn-CN, cy-GB, da-DK, de-DE, en-AU, en-GB,
* en-GB-WLS, en-IN, en-US, es-ES, es-MX, es-US, fr-CA, fr-FR, is-IS, it-IT,
* ja-JP, hi-IN, ko-KR, nb-NO, nl-NL, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU,
* sv-SE, tr-TR
*
* @return <p>
* Optional language code for the Synthesize Speech request. This is
* only necessary if using a bilingual voice, such as Aditi, which
* can be used for either Indian English (en-IN) or Hindi (hi-IN).
* </p>
* <p>
* If a bilingual voice is used and no language code is specified,
* Amazon Polly will use the default language of the bilingual
* voice. The default language for any voice is the one returned by
* the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation for the <code>LanguageCode</code>
* parameter. For example, if no language code is specified, Aditi
* will use Indian English rather than Hindi.
* </p>
* @see LanguageCode
*/
public String getLanguageCode() {
return languageCode;
}
/**
* <p>
* Optional language code for the Synthesize Speech request. This is only
* necessary if using a bilingual voice, such as Aditi, which can be used
* for either Indian English (en-IN) or Hindi (hi-IN).
* </p>
* <p>
* If a bilingual voice is used and no language code is specified, Amazon
* Polly will use the default language of the bilingual voice. The default
* language for any voice is the one returned by the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation for the <code>LanguageCode</code>
* parameter. For example, if no language code is specified, Aditi will use
* Indian English rather than Hindi.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>arb, cmn-CN, cy-GB, da-DK, de-DE, en-AU, en-GB,
* en-GB-WLS, en-IN, en-US, es-ES, es-MX, es-US, fr-CA, fr-FR, is-IS, it-IT,
* ja-JP, hi-IN, ko-KR, nb-NO, nl-NL, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU,
* sv-SE, tr-TR
*
* @param languageCode <p>
* Optional language code for the Synthesize Speech request. This
* is only necessary if using a bilingual voice, such as Aditi,
* which can be used for either Indian English (en-IN) or Hindi
* (hi-IN).
* </p>
* <p>
* If a bilingual voice is used and no language code is
* specified, Amazon Polly will use the default language of the
* bilingual voice. The default language for any voice is the one
* returned by the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation for the
* <code>LanguageCode</code> parameter. For example, if no
* language code is specified, Aditi will use Indian English
* rather than Hindi.
* </p>
* @see LanguageCode
*/
public void setLanguageCode(String languageCode) {
this.languageCode = languageCode;
}
/**
* <p>
* Optional language code for the Synthesize Speech request. This is only
* necessary if using a bilingual voice, such as Aditi, which can be used
* for either Indian English (en-IN) or Hindi (hi-IN).
* </p>
* <p>
* If a bilingual voice is used and no language code is specified, Amazon
* Polly will use the default language of the bilingual voice. The default
* language for any voice is the one returned by the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation for the <code>LanguageCode</code>
* parameter. For example, if no language code is specified, Aditi will use
* Indian English rather than Hindi.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>arb, cmn-CN, cy-GB, da-DK, de-DE, en-AU, en-GB,
* en-GB-WLS, en-IN, en-US, es-ES, es-MX, es-US, fr-CA, fr-FR, is-IS, it-IT,
* ja-JP, hi-IN, ko-KR, nb-NO, nl-NL, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU,
* sv-SE, tr-TR
*
* @param languageCode <p>
* Optional language code for the Synthesize Speech request. This
* is only necessary if using a bilingual voice, such as Aditi,
* which can be used for either Indian English (en-IN) or Hindi
* (hi-IN).
* </p>
* <p>
* If a bilingual voice is used and no language code is
* specified, Amazon Polly will use the default language of the
* bilingual voice. The default language for any voice is the one
* returned by the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation for the
* <code>LanguageCode</code> parameter. For example, if no
* language code is specified, Aditi will use Indian English
* rather than Hindi.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
* @see LanguageCode
*/
public SynthesizeSpeechRequest withLanguageCode(String languageCode) {
this.languageCode = languageCode;
return this;
}
/**
* <p>
* Optional language code for the Synthesize Speech request. This is only
* necessary if using a bilingual voice, such as Aditi, which can be used
* for either Indian English (en-IN) or Hindi (hi-IN).
* </p>
* <p>
* If a bilingual voice is used and no language code is specified, Amazon
* Polly will use the default language of the bilingual voice. The default
* language for any voice is the one returned by the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation for the <code>LanguageCode</code>
* parameter. For example, if no language code is specified, Aditi will use
* Indian English rather than Hindi.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>arb, cmn-CN, cy-GB, da-DK, de-DE, en-AU, en-GB,
* en-GB-WLS, en-IN, en-US, es-ES, es-MX, es-US, fr-CA, fr-FR, is-IS, it-IT,
* ja-JP, hi-IN, ko-KR, nb-NO, nl-NL, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU,
* sv-SE, tr-TR
*
* @param languageCode <p>
* Optional language code for the Synthesize Speech request. This
* is only necessary if using a bilingual voice, such as Aditi,
* which can be used for either Indian English (en-IN) or Hindi
* (hi-IN).
* </p>
* <p>
* If a bilingual voice is used and no language code is
* specified, Amazon Polly will use the default language of the
* bilingual voice. The default language for any voice is the one
* returned by the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation for the
* <code>LanguageCode</code> parameter. For example, if no
* language code is specified, Aditi will use Indian English
* rather than Hindi.
* </p>
* @see LanguageCode
*/
public void setLanguageCode(LanguageCode languageCode) {
this.languageCode = languageCode.toString();
}
/**
* <p>
* Optional language code for the Synthesize Speech request. This is only
* necessary if using a bilingual voice, such as Aditi, which can be used
* for either Indian English (en-IN) or Hindi (hi-IN).
* </p>
* <p>
* If a bilingual voice is used and no language code is specified, Amazon
* Polly will use the default language of the bilingual voice. The default
* language for any voice is the one returned by the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation for the <code>LanguageCode</code>
* parameter. For example, if no language code is specified, Aditi will use
* Indian English rather than Hindi.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>arb, cmn-CN, cy-GB, da-DK, de-DE, en-AU, en-GB,
* en-GB-WLS, en-IN, en-US, es-ES, es-MX, es-US, fr-CA, fr-FR, is-IS, it-IT,
* ja-JP, hi-IN, ko-KR, nb-NO, nl-NL, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU,
* sv-SE, tr-TR
*
* @param languageCode <p>
* Optional language code for the Synthesize Speech request. This
* is only necessary if using a bilingual voice, such as Aditi,
* which can be used for either Indian English (en-IN) or Hindi
* (hi-IN).
* </p>
* <p>
* If a bilingual voice is used and no language code is
* specified, Amazon Polly will use the default language of the
* bilingual voice. The default language for any voice is the one
* returned by the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation for the
* <code>LanguageCode</code> parameter. For example, if no
* language code is specified, Aditi will use Indian English
* rather than Hindi.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
* @see LanguageCode
*/
public SynthesizeSpeechRequest withLanguageCode(LanguageCode languageCode) {
this.languageCode = languageCode.toString();
return this;
}
/**
* <p>
* List of one or more pronunciation lexicon names you want the service to
* apply during synthesis. Lexicons are applied only if the language of the
* lexicon is the same as the language of the voice. For information about
* storing lexicons, see <a
* href="https://docs.aws.amazon.com/polly/latest/dg/API_PutLexicon.html"
* >PutLexicon</a>.
* </p>
*
* @return <p>
* List of one or more pronunciation lexicon names you want the
* service to apply during synthesis. Lexicons are applied only if
* the language of the lexicon is the same as the language of the
* voice. For information about storing lexicons, see <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_PutLexicon.html"
* >PutLexicon</a>.
* </p>
*/
public java.util.List<String> getLexiconNames() {
return lexiconNames;
}
/**
* <p>
* List of one or more pronunciation lexicon names you want the service to
* apply during synthesis. Lexicons are applied only if the language of the
* lexicon is the same as the language of the voice. For information about
* storing lexicons, see <a
* href="https://docs.aws.amazon.com/polly/latest/dg/API_PutLexicon.html"
* >PutLexicon</a>.
* </p>
*
* @param lexiconNames <p>
* List of one or more pronunciation lexicon names you want the
* service to apply during synthesis. Lexicons are applied only
* if the language of the lexicon is the same as the language of
* the voice. For information about storing lexicons, see <a
* href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_PutLexicon.html"
* >PutLexicon</a>.
* </p>
*/
public void setLexiconNames(java.util.Collection<String> lexiconNames) {
if (lexiconNames == null) {
this.lexiconNames = null;
return;
}
this.lexiconNames = new java.util.ArrayList<String>(lexiconNames);
}
/**
* <p>
* List of one or more pronunciation lexicon names you want the service to
* apply during synthesis. Lexicons are applied only if the language of the
* lexicon is the same as the language of the voice. For information about
* storing lexicons, see <a
* href="https://docs.aws.amazon.com/polly/latest/dg/API_PutLexicon.html"
* >PutLexicon</a>.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
*
* @param lexiconNames <p>
* List of one or more pronunciation lexicon names you want the
* service to apply during synthesis. Lexicons are applied only
* if the language of the lexicon is the same as the language of
* the voice. For information about storing lexicons, see <a
* href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_PutLexicon.html"
* >PutLexicon</a>.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
*/
public SynthesizeSpeechRequest withLexiconNames(String... lexiconNames) {
if (getLexiconNames() == null) {
this.lexiconNames = new java.util.ArrayList<String>(lexiconNames.length);
}
for (String value : lexiconNames) {
this.lexiconNames.add(value);
}
return this;
}
/**
* <p>
* List of one or more pronunciation lexicon names you want the service to
* apply during synthesis. Lexicons are applied only if the language of the
* lexicon is the same as the language of the voice. For information about
* storing lexicons, see <a
* href="https://docs.aws.amazon.com/polly/latest/dg/API_PutLexicon.html"
* >PutLexicon</a>.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
*
* @param lexiconNames <p>
* List of one or more pronunciation lexicon names you want the
* service to apply during synthesis. Lexicons are applied only
* if the language of the lexicon is the same as the language of
* the voice. For information about storing lexicons, see <a
* href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_PutLexicon.html"
* >PutLexicon</a>.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
*/
public SynthesizeSpeechRequest withLexiconNames(java.util.Collection<String> lexiconNames) {
setLexiconNames(lexiconNames);
return this;
}
/**
* <p>
* The format in which the returned output will be encoded. For audio
* stream, this will be mp3, ogg_vorbis, or pcm. For speech marks, this will
* be json.
* </p>
* <p>
* When pcm is used, the content returned is audio/pcm in a signed 16-bit, 1
* channel (mono), little-endian format.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>json, mp3, ogg_vorbis, pcm
*
* @return <p>
* The format in which the returned output will be encoded. For
* audio stream, this will be mp3, ogg_vorbis, or pcm. For speech
* marks, this will be json.
* </p>
* <p>
* When pcm is used, the content returned is audio/pcm in a signed
* 16-bit, 1 channel (mono), little-endian format.
* </p>
* @see OutputFormat
*/
public String getOutputFormat() {
return outputFormat;
}
/**
* <p>
* The format in which the returned output will be encoded. For audio
* stream, this will be mp3, ogg_vorbis, or pcm. For speech marks, this will
* be json.
* </p>
* <p>
* When pcm is used, the content returned is audio/pcm in a signed 16-bit, 1
* channel (mono), little-endian format.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>json, mp3, ogg_vorbis, pcm
*
* @param outputFormat <p>
* The format in which the returned output will be encoded. For
* audio stream, this will be mp3, ogg_vorbis, or pcm. For speech
* marks, this will be json.
* </p>
* <p>
* When pcm is used, the content returned is audio/pcm in a
* signed 16-bit, 1 channel (mono), little-endian format.
* </p>
* @see OutputFormat
*/
public void setOutputFormat(String outputFormat) {
this.outputFormat = outputFormat;
}
/**
* <p>
* The format in which the returned output will be encoded. For audio
* stream, this will be mp3, ogg_vorbis, or pcm. For speech marks, this will
* be json.
* </p>
* <p>
* When pcm is used, the content returned is audio/pcm in a signed 16-bit, 1
* channel (mono), little-endian format.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>json, mp3, ogg_vorbis, pcm
*
* @param outputFormat <p>
* The format in which the returned output will be encoded. For
* audio stream, this will be mp3, ogg_vorbis, or pcm. For speech
* marks, this will be json.
* </p>
* <p>
* When pcm is used, the content returned is audio/pcm in a
* signed 16-bit, 1 channel (mono), little-endian format.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
* @see OutputFormat
*/
public SynthesizeSpeechRequest withOutputFormat(String outputFormat) {
this.outputFormat = outputFormat;
return this;
}
/**
* <p>
* The format in which the returned output will be encoded. For audio
* stream, this will be mp3, ogg_vorbis, or pcm. For speech marks, this will
* be json.
* </p>
* <p>
* When pcm is used, the content returned is audio/pcm in a signed 16-bit, 1
* channel (mono), little-endian format.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>json, mp3, ogg_vorbis, pcm
*
* @param outputFormat <p>
* The format in which the returned output will be encoded. For
* audio stream, this will be mp3, ogg_vorbis, or pcm. For speech
* marks, this will be json.
* </p>
* <p>
* When pcm is used, the content returned is audio/pcm in a
* signed 16-bit, 1 channel (mono), little-endian format.
* </p>
* @see OutputFormat
*/
public void setOutputFormat(OutputFormat outputFormat) {
this.outputFormat = outputFormat.toString();
}
/**
* <p>
* The format in which the returned output will be encoded. For audio
* stream, this will be mp3, ogg_vorbis, or pcm. For speech marks, this will
* be json.
* </p>
* <p>
* When pcm is used, the content returned is audio/pcm in a signed 16-bit, 1
* channel (mono), little-endian format.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>json, mp3, ogg_vorbis, pcm
*
* @param outputFormat <p>
* The format in which the returned output will be encoded. For
* audio stream, this will be mp3, ogg_vorbis, or pcm. For speech
* marks, this will be json.
* </p>
* <p>
* When pcm is used, the content returned is audio/pcm in a
* signed 16-bit, 1 channel (mono), little-endian format.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
* @see OutputFormat
*/
public SynthesizeSpeechRequest withOutputFormat(OutputFormat outputFormat) {
this.outputFormat = outputFormat.toString();
return this;
}
/**
* <p>
* The audio frequency specified in Hz.
* </p>
* <p>
* The valid values for mp3 and ogg_vorbis are "8000", "16000", "22050", and
* "24000". The default value for standard voices is "22050". The default
* value for neural voices is "24000".
* </p>
* <p>
* Valid values for pcm are "8000" and "16000" The default value is "16000".
* </p>
*
* @return <p>
* The audio frequency specified in Hz.
* </p>
* <p>
* The valid values for mp3 and ogg_vorbis are "8000", "16000",
* "22050", and "24000". The default value for standard voices is
* "22050". The default value for neural voices is "24000".
* </p>
* <p>
* Valid values for pcm are "8000" and "16000" The default value is
* "16000".
* </p>
*/
public String getSampleRate() {
return sampleRate;
}
/**
* <p>
* The audio frequency specified in Hz.
* </p>
* <p>
* The valid values for mp3 and ogg_vorbis are "8000", "16000", "22050", and
* "24000". The default value for standard voices is "22050". The default
* value for neural voices is "24000".
* </p>
* <p>
* Valid values for pcm are "8000" and "16000" The default value is "16000".
* </p>
*
* @param sampleRate <p>
* The audio frequency specified in Hz.
* </p>
* <p>
* The valid values for mp3 and ogg_vorbis are "8000", "16000",
* "22050", and "24000". The default value for standard voices is
* "22050". The default value for neural voices is "24000".
* </p>
* <p>
* Valid values for pcm are "8000" and "16000" The default value
* is "16000".
* </p>
*/
public void setSampleRate(String sampleRate) {
this.sampleRate = sampleRate;
}
/**
* <p>
* The audio frequency specified in Hz.
* </p>
* <p>
* The valid values for mp3 and ogg_vorbis are "8000", "16000", "22050", and
* "24000". The default value for standard voices is "22050". The default
* value for neural voices is "24000".
* </p>
* <p>
* Valid values for pcm are "8000" and "16000" The default value is "16000".
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
*
* @param sampleRate <p>
* The audio frequency specified in Hz.
* </p>
* <p>
* The valid values for mp3 and ogg_vorbis are "8000", "16000",
* "22050", and "24000". The default value for standard voices is
* "22050". The default value for neural voices is "24000".
* </p>
* <p>
* Valid values for pcm are "8000" and "16000" The default value
* is "16000".
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
*/
public SynthesizeSpeechRequest withSampleRate(String sampleRate) {
this.sampleRate = sampleRate;
return this;
}
/**
* <p>
* The type of speech marks returned for the input text.
* </p>
*
* @return <p>
* The type of speech marks returned for the input text.
* </p>
*/
public java.util.List<String> getSpeechMarkTypes() {
return speechMarkTypes;
}
/**
* <p>
* The type of speech marks returned for the input text.
* </p>
*
* @param speechMarkTypes <p>
* The type of speech marks returned for the input text.
* </p>
*/
public void setSpeechMarkTypes(java.util.Collection<String> speechMarkTypes) {
if (speechMarkTypes == null) {
this.speechMarkTypes = null;
return;
}
this.speechMarkTypes = new java.util.ArrayList<String>(speechMarkTypes);
}
/**
* <p>
* The type of speech marks returned for the input text.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
*
* @param speechMarkTypes <p>
* The type of speech marks returned for the input text.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
*/
public SynthesizeSpeechRequest withSpeechMarkTypes(String... speechMarkTypes) {
if (getSpeechMarkTypes() == null) {
this.speechMarkTypes = new java.util.ArrayList<String>(speechMarkTypes.length);
}
for (String value : speechMarkTypes) {
this.speechMarkTypes.add(value);
}
return this;
}
/**
* <p>
* The type of speech marks returned for the input text.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
*
* @param speechMarkTypes <p>
* The type of speech marks returned for the input text.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
*/
public SynthesizeSpeechRequest withSpeechMarkTypes(java.util.Collection<String> speechMarkTypes) {
setSpeechMarkTypes(speechMarkTypes);
return this;
}
/**
* <p>
* Input text to synthesize. If you specify <code>ssml</code> as the
* <code>TextType</code>, follow the SSML format for the input text.
* </p>
*
* @return <p>
* Input text to synthesize. If you specify <code>ssml</code> as the
* <code>TextType</code>, follow the SSML format for the input text.
* </p>
*/
public String getText() {
return text;
}
/**
* <p>
* Input text to synthesize. If you specify <code>ssml</code> as the
* <code>TextType</code>, follow the SSML format for the input text.
* </p>
*
* @param text <p>
* Input text to synthesize. If you specify <code>ssml</code> as
* the <code>TextType</code>, follow the SSML format for the
* input text.
* </p>
*/
public void setText(String text) {
this.text = text;
}
/**
* <p>
* Input text to synthesize. If you specify <code>ssml</code> as the
* <code>TextType</code>, follow the SSML format for the input text.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
*
* @param text <p>
* Input text to synthesize. If you specify <code>ssml</code> as
* the <code>TextType</code>, follow the SSML format for the
* input text.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
*/
public SynthesizeSpeechRequest withText(String text) {
this.text = text;
return this;
}
/**
* <p>
* Specifies whether the input text is plain text or SSML. The default value
* is plain text. For more information, see <a
* href="https://docs.aws.amazon.com/polly/latest/dg/ssml.html">Using
* SSML</a>.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>ssml, text
*
* @return <p>
* Specifies whether the input text is plain text or SSML. The
* default value is plain text. For more information, see <a
* href="https://docs.aws.amazon.com/polly/latest/dg/ssml.html"
* >Using SSML</a>.
* </p>
* @see TextType
*/
public String getTextType() {
return textType;
}
/**
* <p>
* Specifies whether the input text is plain text or SSML. The default value
* is plain text. For more information, see <a
* href="https://docs.aws.amazon.com/polly/latest/dg/ssml.html">Using
* SSML</a>.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>ssml, text
*
* @param textType <p>
* Specifies whether the input text is plain text or SSML. The
* default value is plain text. For more information, see <a
* href=
* "https://docs.aws.amazon.com/polly/latest/dg/ssml.html">Using
* SSML</a>.
* </p>
* @see TextType
*/
public void setTextType(String textType) {
this.textType = textType;
}
/**
* <p>
* Specifies whether the input text is plain text or SSML. The default value
* is plain text. For more information, see <a
* href="https://docs.aws.amazon.com/polly/latest/dg/ssml.html">Using
* SSML</a>.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>ssml, text
*
* @param textType <p>
* Specifies whether the input text is plain text or SSML. The
* default value is plain text. For more information, see <a
* href=
* "https://docs.aws.amazon.com/polly/latest/dg/ssml.html">Using
* SSML</a>.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
* @see TextType
*/
public SynthesizeSpeechRequest withTextType(String textType) {
this.textType = textType;
return this;
}
/**
* <p>
* Specifies whether the input text is plain text or SSML. The default value
* is plain text. For more information, see <a
* href="https://docs.aws.amazon.com/polly/latest/dg/ssml.html">Using
* SSML</a>.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>ssml, text
*
* @param textType <p>
* Specifies whether the input text is plain text or SSML. The
* default value is plain text. For more information, see <a
* href=
* "https://docs.aws.amazon.com/polly/latest/dg/ssml.html">Using
* SSML</a>.
* </p>
* @see TextType
*/
public void setTextType(TextType textType) {
this.textType = textType.toString();
}
/**
* <p>
* Specifies whether the input text is plain text or SSML. The default value
* is plain text. For more information, see <a
* href="https://docs.aws.amazon.com/polly/latest/dg/ssml.html">Using
* SSML</a>.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>ssml, text
*
* @param textType <p>
* Specifies whether the input text is plain text or SSML. The
* default value is plain text. For more information, see <a
* href=
* "https://docs.aws.amazon.com/polly/latest/dg/ssml.html">Using
* SSML</a>.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
* @see TextType
*/
public SynthesizeSpeechRequest withTextType(TextType textType) {
this.textType = textType.toString();
return this;
}
/**
* <p>
* Voice ID to use for the synthesis. You can get a list of available voice
* IDs by calling the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>Aditi, Amy, Astrid, Bianca, Brian, Camila, Carla,
* Carmen, Celine, Chantal, Conchita, Cristiano, Dora, Emma, Enrique, Ewa,
* Filiz, Geraint, Giorgio, Gwyneth, Hans, Ines, Ivy, Jacek, Jan, Joanna,
* Joey, Justin, Karl, Kendra, Kevin, Kimberly, Lea, Liv, Lotte, Lucia,
* Lupe, Mads, Maja, Marlene, Mathieu, Matthew, Maxim, Mia, Miguel, Mizuki,
* Naja, Nicole, Olivia, Penelope, Raveena, Ricardo, Ruben, Russell, Salli,
* Seoyeon, Takumi, Tatyana, Vicki, Vitoria, Zeina, Zhiyu
*
* @return <p>
* Voice ID to use for the synthesis. You can get a list of
* available voice IDs by calling the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation.
* </p>
* @see VoiceId
*/
public String getVoiceId() {
return voiceId;
}
/**
* <p>
* Voice ID to use for the synthesis. You can get a list of available voice
* IDs by calling the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>Aditi, Amy, Astrid, Bianca, Brian, Camila, Carla,
* Carmen, Celine, Chantal, Conchita, Cristiano, Dora, Emma, Enrique, Ewa,
* Filiz, Geraint, Giorgio, Gwyneth, Hans, Ines, Ivy, Jacek, Jan, Joanna,
* Joey, Justin, Karl, Kendra, Kevin, Kimberly, Lea, Liv, Lotte, Lucia,
* Lupe, Mads, Maja, Marlene, Mathieu, Matthew, Maxim, Mia, Miguel, Mizuki,
* Naja, Nicole, Olivia, Penelope, Raveena, Ricardo, Ruben, Russell, Salli,
* Seoyeon, Takumi, Tatyana, Vicki, Vitoria, Zeina, Zhiyu
*
* @param voiceId <p>
* Voice ID to use for the synthesis. You can get a list of
* available voice IDs by calling the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation.
* </p>
* @see VoiceId
*/
public void setVoiceId(String voiceId) {
this.voiceId = voiceId;
}
/**
* <p>
* Voice ID to use for the synthesis. You can get a list of available voice
* IDs by calling the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>Aditi, Amy, Astrid, Bianca, Brian, Camila, Carla,
* Carmen, Celine, Chantal, Conchita, Cristiano, Dora, Emma, Enrique, Ewa,
* Filiz, Geraint, Giorgio, Gwyneth, Hans, Ines, Ivy, Jacek, Jan, Joanna,
* Joey, Justin, Karl, Kendra, Kevin, Kimberly, Lea, Liv, Lotte, Lucia,
* Lupe, Mads, Maja, Marlene, Mathieu, Matthew, Maxim, Mia, Miguel, Mizuki,
* Naja, Nicole, Olivia, Penelope, Raveena, Ricardo, Ruben, Russell, Salli,
* Seoyeon, Takumi, Tatyana, Vicki, Vitoria, Zeina, Zhiyu
*
* @param voiceId <p>
* Voice ID to use for the synthesis. You can get a list of
* available voice IDs by calling the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
* @see VoiceId
*/
public SynthesizeSpeechRequest withVoiceId(String voiceId) {
this.voiceId = voiceId;
return this;
}
/**
* <p>
* Voice ID to use for the synthesis. You can get a list of available voice
* IDs by calling the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation.
* </p>
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>Aditi, Amy, Astrid, Bianca, Brian, Camila, Carla,
* Carmen, Celine, Chantal, Conchita, Cristiano, Dora, Emma, Enrique, Ewa,
* Filiz, Geraint, Giorgio, Gwyneth, Hans, Ines, Ivy, Jacek, Jan, Joanna,
* Joey, Justin, Karl, Kendra, Kevin, Kimberly, Lea, Liv, Lotte, Lucia,
* Lupe, Mads, Maja, Marlene, Mathieu, Matthew, Maxim, Mia, Miguel, Mizuki,
* Naja, Nicole, Olivia, Penelope, Raveena, Ricardo, Ruben, Russell, Salli,
* Seoyeon, Takumi, Tatyana, Vicki, Vitoria, Zeina, Zhiyu
*
* @param voiceId <p>
* Voice ID to use for the synthesis. You can get a list of
* available voice IDs by calling the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation.
* </p>
* @see VoiceId
*/
public void setVoiceId(VoiceId voiceId) {
this.voiceId = voiceId.toString();
}
/**
* <p>
* Voice ID to use for the synthesis. You can get a list of available voice
* IDs by calling the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation.
* </p>
* <p>
* Returns a reference to this object so that method calls can be chained
* together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>Aditi, Amy, Astrid, Bianca, Brian, Camila, Carla,
* Carmen, Celine, Chantal, Conchita, Cristiano, Dora, Emma, Enrique, Ewa,
* Filiz, Geraint, Giorgio, Gwyneth, Hans, Ines, Ivy, Jacek, Jan, Joanna,
* Joey, Justin, Karl, Kendra, Kevin, Kimberly, Lea, Liv, Lotte, Lucia,
* Lupe, Mads, Maja, Marlene, Mathieu, Matthew, Maxim, Mia, Miguel, Mizuki,
* Naja, Nicole, Olivia, Penelope, Raveena, Ricardo, Ruben, Russell, Salli,
* Seoyeon, Takumi, Tatyana, Vicki, Vitoria, Zeina, Zhiyu
*
* @param voiceId <p>
* Voice ID to use for the synthesis. You can get a list of
* available voice IDs by calling the <a href=
* "https://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html"
* >DescribeVoices</a> operation.
* </p>
* @return A reference to this updated object so that method calls can be
* chained together.
* @see VoiceId
*/
public SynthesizeSpeechRequest withVoiceId(VoiceId voiceId) {
this.voiceId = voiceId.toString();
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getEngine() != null)
sb.append("Engine: " + getEngine() + ",");
if (getLanguageCode() != null)
sb.append("LanguageCode: " + getLanguageCode() + ",");
if (getLexiconNames() != null)
sb.append("LexiconNames: " + getLexiconNames() + ",");
if (getOutputFormat() != null)
sb.append("OutputFormat: " + getOutputFormat() + ",");
if (getSampleRate() != null)
sb.append("SampleRate: " + getSampleRate() + ",");
if (getSpeechMarkTypes() != null)
sb.append("SpeechMarkTypes: " + getSpeechMarkTypes() + ",");
if (getText() != null)
sb.append("Text: " + getText() + ",");
if (getTextType() != null)
sb.append("TextType: " + getTextType() + ",");
if (getVoiceId() != null)
sb.append("VoiceId: " + getVoiceId());
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getEngine() == null) ? 0 : getEngine().hashCode());
hashCode = prime * hashCode
+ ((getLanguageCode() == null) ? 0 : getLanguageCode().hashCode());
hashCode = prime * hashCode
+ ((getLexiconNames() == null) ? 0 : getLexiconNames().hashCode());
hashCode = prime * hashCode
+ ((getOutputFormat() == null) ? 0 : getOutputFormat().hashCode());
hashCode = prime * hashCode + ((getSampleRate() == null) ? 0 : getSampleRate().hashCode());
hashCode = prime * hashCode
+ ((getSpeechMarkTypes() == null) ? 0 : getSpeechMarkTypes().hashCode());
hashCode = prime * hashCode + ((getText() == null) ? 0 : getText().hashCode());
hashCode = prime * hashCode + ((getTextType() == null) ? 0 : getTextType().hashCode());
hashCode = prime * hashCode + ((getVoiceId() == null) ? 0 : getVoiceId().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SynthesizeSpeechRequest == false)
return false;
SynthesizeSpeechRequest other = (SynthesizeSpeechRequest) obj;
if (other.getEngine() == null ^ this.getEngine() == null)
return false;
if (other.getEngine() != null && other.getEngine().equals(this.getEngine()) == false)
return false;
if (other.getLanguageCode() == null ^ this.getLanguageCode() == null)
return false;
if (other.getLanguageCode() != null
&& other.getLanguageCode().equals(this.getLanguageCode()) == false)
return false;
if (other.getLexiconNames() == null ^ this.getLexiconNames() == null)
return false;
if (other.getLexiconNames() != null
&& other.getLexiconNames().equals(this.getLexiconNames()) == false)
return false;
if (other.getOutputFormat() == null ^ this.getOutputFormat() == null)
return false;
if (other.getOutputFormat() != null
&& other.getOutputFormat().equals(this.getOutputFormat()) == false)
return false;
if (other.getSampleRate() == null ^ this.getSampleRate() == null)
return false;
if (other.getSampleRate() != null
&& other.getSampleRate().equals(this.getSampleRate()) == false)
return false;
if (other.getSpeechMarkTypes() == null ^ this.getSpeechMarkTypes() == null)
return false;
if (other.getSpeechMarkTypes() != null
&& other.getSpeechMarkTypes().equals(this.getSpeechMarkTypes()) == false)
return false;
if (other.getText() == null ^ this.getText() == null)
return false;
if (other.getText() != null && other.getText().equals(this.getText()) == false)
return false;
if (other.getTextType() == null ^ this.getTextType() == null)
return false;
if (other.getTextType() != null && other.getTextType().equals(this.getTextType()) == false)
return false;
if (other.getVoiceId() == null ^ this.getVoiceId() == null)
return false;
if (other.getVoiceId() != null && other.getVoiceId().equals(this.getVoiceId()) == false)
return false;
return true;
}
} |
import zope.interface
# Interfaz para definir signaturas de metodos para un animal
class IAnimalActioner(zope.interface.Interface):
"""Esta es la documentacion de una interfaz para acciones de un animal"""
# metodos y atributos
# el atributo solo puede ser un doc string
x = zope.interface.Attribute(
"El atributo de una interfaz solo tiene fines documentativos")
def correr(self):
pass
def realizar_sonido(self):
pass
def comer(self):
pass
# Las interfaces tienen una semantica más estricta
# y mejor mensajes de error que abc
# 'Interface' es la interfaz padre de todas las interfaces
# Las interfaces no son clases, por lo que no se puede
# acceder a sus atributos usando: IMiInterface.<atributo> |
"use client";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import {
aspirations,
careers,
hobbies,
type SimFormValues,
} from "~/data/sim-typings";
import { useFormContext } from "react-hook-form";
import { FormControl, FormField, FormItem, FormLabel, FormMessage } from "../ui/form";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Input } from "../ui/input";
const SimsPersonalityForm = () => {
const form = useFormContext<SimFormValues>();
return (
<>
<Card>
<CardHeader>
<CardTitle>Aspirations & Personality</CardTitle>
<CardDescription>Fill in your Sim's aspirations.</CardDescription>
</CardHeader>
<CardContent className="grid gap-6">
<FormField
control={form.control}
name="aspiration"
render={({ field }) => (
<FormItem>
<FormLabel>Aspiration</FormLabel>
<Select
onValueChange={field.onChange}
defaultValue={field.value}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Choose an aspiration" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem key="notset" value="notset">
{"Not set"}
</SelectItem>
{aspirations?.map((aspiration) => (
<SelectItem key={aspiration} value={aspiration}>
{aspiration}
</SelectItem>
))}
</SelectContent>
</Select>
</FormItem>
)}
/>
<FormField
control={form.control}
name="secondAspiration"
render={({ field }) => (
<FormItem>
<FormLabel>Secondary Aspiration</FormLabel>
<Select
onValueChange={field.onChange}
defaultValue={field.value}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Choose a secondary aspiration" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem key="notset" value="notset">
{"Not set"}
</SelectItem>
{aspirations?.map((aspiration) => (
<SelectItem key={aspiration} value={aspiration}>
{aspiration}
</SelectItem>
))}
</SelectContent>
</Select>
</FormItem>
)}
/>
<FormField
control={form.control}
name="career"
render={({ field }) => (
<FormItem>
<FormLabel>Career</FormLabel>
<Select
onValueChange={field.onChange}
defaultValue={field.value}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Choose a career" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem key="notset" value="notset">
{"Not set"}
</SelectItem>
{careers?.map((career) => (
<SelectItem key={career} value={career}>
{career}
</SelectItem>
))}
</SelectContent>
</Select>
</FormItem>
)}
/>
<FormField
control={form.control}
name="hobby"
render={({ field }) => (
<FormItem>
<FormLabel>Hobby</FormLabel>
<Select
onValueChange={field.onChange}
defaultValue={field.value}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Choose a hobby" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem key="notset" value="notset">
{"Not set"}
</SelectItem>
{hobbies?.map((hobby) => (
<SelectItem key={hobby} value={hobby}>
{hobby}
</SelectItem>
))}
</SelectContent>
</Select>
</FormItem>
)}
/>
<FormField
control={form.control}
name="subHobby"
render={({ field }) => (
<FormItem>
<FormLabel>Sub-Hobby</FormLabel>
<FormControl>
<Input placeholder="Choose a sub-hobby" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</CardContent>
</Card>
</>
);
};
export default SimsPersonalityForm; |
-
- 是一颗排列树,有N个零件,每个零件有m个供应商,找到小于总价格d的最小重量的设计,
- 像是图的M 着色问题,每一个色块的都有m 种着色方法,找到满足条件色颜色,
- 所以这里的解空间也是一颗以各个供应商为排列的排列树,`x[i] = m && i = n`一共n个零件,表示了解空间的深度为n ,M个供应商,表示解空间为一个m 叉树,
- 找到了解空间,现在就需要限界函数,`cw > bsetw`剪掉,
- ```c++
#include <bits/stdc++.h>
using namespace std;
/*1. 在回溯算法中, 回溯到叶子节点的时候,就可以得到一中着色方法
2. 如果是内节点,就需要给这个节点着色,
1. 着色方法为:先从第一种颜色开始,把每一种颜色都试一遍,看看什么颜色是适合的
2. 这里就需要用到约束函数(OK(t))当前节点t的着色是否满足约束条件
3. 约束条件,从第一个节点j开始,看看节点j t 是否是有边相连的,如果有边相连并且两个的颜色一样,节点t就不能用这个颜色,在换下一种颜色判断
*/
class Color {
friend int mColoring(int, int, int**);// 实例化
private:
bool OK(int t);
void BackTrack(int t);
int n; // 节点;
int m; // 色数
int sum;
int **a; // 邻接矩阵G(V,E);
int *x;
};
void Color::BackTrack(int t)
{
if(t>=n)
{
sum++;
for(int i = 1; i<=n; i++)
cout << x[i] << " ";
cout << endl;
}
else
{
for(int j = 1; j<=m; j++)
{
x[t] = j;
if(OK(t))
BackTrack(t+1);
}
}
}
bool Color::OK(int t)
{
for(int j = 1; j<=n; j++)
{
if(a[t][j] == 1 && x[t] == x[j])
return false;
return true;
}
}
int mColoring(int n, int m, int **a)
{
Color C;
//初始化x;
C.n = n;
C.m = m;
C.a = a;
C.sum = 0;
int *p = new int[n+1];
for(int i = 0; i<=n; i++)
{
p[i] = 0;
}
C.x = p;
C.BackTrack(1);
delete[] p;
return C.sum;
}
int main()
{
int n,m;
cin >> n >> m;
int **a;
a = (int **)malloc(sizeof(int*)*n);
for(int i = 0; i<n; i++)
a[i] = (int*)malloc(sizeof(int)*n);
for(int i= 0; i<n; i++)
{
for(int j = 0; j<n; j++)
cin >> a[i][j];
}
cout << mColoring(n, m, a);
}
```
- 0-1 背包问题
- ```c++
#include <bits/stdc++.h>
using namespace std;
template<class Typew, class Typep>
class Knap{
friend Typep Knapsack(Typep*, Typew*, Typew, int);
private:
Typep Bound();
void Backtrack();
Typep cp; /// 当前价值
Typew cw; /// 当前重量
Typep *p; /// 价值序列
Typew *w; /// 重量序列
Typep bestp; /// 最优解
int n; /// 物品数量
Typew c; /// 背包容量
};
/// 右子树的上界函数
template<class Typew, class Typep>
Typep Knap<Typw, Typep>::Bound(int i)
{
Typew cleft = c-cw; /// (进入右子树时剩余的背包容量)背包容量-当前重量
Typep b = cp;
/// 剩余的物品以单位重量递减装入
while(i <= n && w[i] <= cleft ){
cleft -= w[i]; /// 每循环一次,背包容量就要减少
b+=p[i]; /// 上界都要加上当前物品的价值
i++
}
/// 最后一个物品装入部分
if(i<=n)
b+=p[i]/w[i]*cleft;
return b;
}
template<class Typew, class Typep>
void Knap<Typew, Typep>::Backtrack(int i)
{
/// 回溯结束,当前的价值就是最优价值
if(i>=n)
{
bestp = cp;
return;
}
/// 搜索左子树
if(cw+w[i] <= w)
{
x[i] = 1; /// 表示装入
cw += w[i];
cp += p[i];
/// 进行下一轮回溯
Backtrack(i+1);
/// 为了进入右子树做准备;
cw -= w[i];
cp -= p[i];
}
/// 搜索右子树
if(bound(i+1) > bestp){
x[i] = 0;
Backtrack(i+1);
}
}
/// 解空间树的结构,
class Object{
friend int Knapsack(int*, int*, int, int);
public:
/// 用于后面的sort排序
int operator<=(Object a) const {return (d >= a.d); }
private:
int ID; /// 每一个物品的下标
float d; /// 单位价值
};
template<class Typew, class Typep>
Typep Knapsack(Typep p[], Typew w[], Typew c, int n)
{
Typew W = 0;
Typep P = 0;
Object *Q = new Object[n];
for(int i = 1; i<=n; i++)
{
Q[i-1].ID = i;
Q[i-1].d = 1.0*p[i]/w[i];
p += p[i];
w += w[i];
}
/// 如果背包的总容量大于物品总重量,可全部装入,最优解为所有价值之和
if(w<=c)
return P;
/// 按照单位价值对物品进行排序
sort(Q, Q+n);
/// 新建一个实例K
Knap<Typew, Typep> K;
K.p = new Typep [n+1];
K.w = new Typew [n+1];
for(int i = 1; i<=n; i++)
{
K.p[i] = p[Q[i-1].ID];
K.w[i] = w[Q[i-1].ID];
}
K.cp = 0;
K.cw = 0;
K.c = c;
K.n = n;
K.bestp = 0;
K.Backtrack(1);
delete[] Q;
delete[] K.w;
delete[] K.p;
return K.bestp;
}
int main()
{
}
```
-
- 动态开辟一个动态数组
- ```c++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n = 3;
int **a;
a = (int**)malloc(sizeof(int*)*n);
for(int i = 0; i<n; i++)
a[i] = (int*)malloc(sizeof(int)*n);
for(int i= 0; i<n; i++)
{
for(int j = 0; j<n; j++)
cin >> a[i][j];
}
for(int i= 0; i<n; i++)
{
for(int j = 0; j<n; j++)
cout << a[i][j] << " ";
cout << endl;
}
}
```
-
```c++
//
//#include <bits/stdc++.h>
//using namespace std;
//int bestw = 0xffff;
//int cw = 0;
//int cc = 0;
//int *x;
//int m;
//int n;
//int d;
//int **w;
//int **c;
//
//void BackTrack(int t)
//{
// if(t>n)
// {
// bestw = cw;
// cout << bestw << endl;
// for(int i = 0; i<n; i++)
// cout << x[i] << " ";
// cout << endl;
//
// }
// else
// {
// for(int j = 1; j<=m; j++)
// {
// if(cw+w[t][j] < bestw && cc+c[t][j] <= d)
// {
// x[t] = j;
// cw += w[t][j];
// cc += c[t][j];
// BackTrack(t+1);
// cw -= w[t][j];
// cc -= c[t][j];
// }
// }
// }
//}
//
//int main()
//{
// //int n,m;
// cout << "输入部件数(n)和供应商数(m):" << endl;
// cin >> n >> m;
// //int d;
// cout << "输入限定价格(d): " << endl;
// cin >> d;
// //int **c;
// //int **w;
//
// //x[n] = {0};
// cout << "输入花费:" << endl;
// c = (int**)malloc(sizeof(int)*n);
// for(int i = 0; i<n; i++)
// c[i] = (int*)malloc(sizeof(int)*m);
// for(int i = 0; i<n; i++)
// {
// for(int j = 0; j<m; j++)
// cin >> c[i][j];
// cout << endl;
// }
//
// cout << "输入重量:" <<endl;
// w = (int**)malloc(sizeof(int)*n);
// for(int i = 0; i<n; i++)
// w[i] = (int*)malloc(sizeof(int)*m);
// for(int i = 0; i<n; i++)
// {
// for(int j = 0; j<m; j++)
// cin >> w[i][j] ;
// }
//
// BackTrack(1);
//
//
//}
#include<iostream>
#include<stdio.h>
using namespace std;
int w[100][100];//w[i][j]为第i个零件在第j个供应商的重量
int c[100][100];//c[i][j]为第i个零件在第j个供应商的价格
int bestx[100];//bestx[i]表示一次搜索到底后的最优解,用来存放第i个零件的供应商,
int x[100];//x[i]临时存放第i个零件的供应商
int cw=0,cc=0,bestw=0xffff;
int cost;//限定价格
int n;//部件数
int m;//供应商数
void Backtrack(int t)
{
int j;
if(t>n)//搜索到叶子结点,一个搜索结束,所有零件已经找完
{
bestw=cw;//当前最小重量
cout<<"每个部件的供应商:"<<endl;
for(j=1;j<=n;j++)
cout << x[j] << " " ;
cout << endl;
}
else
{
for(j=1;j<=m;j++)
{
if(cc+c[t][j]<=cost && cw+w[t][j]<bestw)
{
x[t]=j;
cc+=c[t][j];
cw+=w[t][j];
Backtrack(t+1);
cc-=c[t][j];
cw-=w[t][j];
}
}
}
}
int main()
{
int i,j;
cout<<"请输入部件数:"<<endl;
cin>>n;
cout<<"请输入供应商数:"<<endl;
cin>>m;
cout<<"请输入限定价格:"<<endl;
cin>>cost;
cout<<"请输入各部件的在不同供应商的重量:"<<endl;
for(i=1; i<=n; i++)
for(j=1; j<=m; j++)
cin>>w[i][j];
cout<<"请输入各部件的在不同供应商的价格:"<<endl;
for(i=1; i<=n; i++)
for(j=1; j<=m; j++)
cin>>c[i][j];
Backtrack(1);
// for(i=1;i<=n;i++)
// cout<<bestx[i]<<' ';
// cout<<endl;
cout<<bestw;
return 0;
}
``` |
/* Testdraw.c - a program that draws various patterns when the
* user hits number keys:
* 0 - clear screen
* 1 - lines
* 2 - circles
* 3 - boxes
* 4 - blits
* <esc> or q or x - quit
*/
#include "errcodes.h"
#include "vdevcall.h"
#include "vdevinfo.h"
#include "rastlib.h"
#include "rastcall.h"
#include "rcel.h"
/* Some prototypes for gfx.lib functions. Some day we may document
* this all.... */
/* draw a line */
void pj_cline(SHORT x1, SHORT y1, SHORT x2, SHORT y2,
void (*dotout)(SHORT x,SHORT y,void *dotdat),
void *dotdat);
/* draw a circle */
Errcode dcircle(SHORT xcen, SHORT ycen, SHORT diam,
void (*dotout)(SHORT x,SHORT y,void *dotdat), void *dotdat,
Errcode (*hlineout)(SHORT y,SHORT x1,SHORT x2,void *hldat), void *hldat,
Boolean filled);
Errcode init_screen(Vdevice **vd, Rcel **dcel,
char *drv_name, int drv_mode);
Errcode errline(Errcode err, char *txt,...);
SHORT program_version, program_id;
long aa_syslib;
typedef struct td_cb {
/* Test draw control block */
char *vd_path; /* video driver path */
Vdevice *vd; /* video driver if open */
SHORT vd_mode; /* driver mode */
SHORT ovmode; /* original display mode */
Rcel *dcel; /* display screen cel */
} Td_cb;
Td_cb tcb;
typedef struct cdotdat
{
Rcel *cel;
Pixel color;
} Cdotdat;
void cdotout(SHORT x, SHORT y, Cdotdat *cdd)
/* unclipped dot out */
{
(*cdd->cel->lib->put_dot)((Raster *)cdd->cel, cdd->color, x, y);
}
void clip_cdotout(SHORT x, SHORT y, Cdotdat *cdd)
/* clipped dot out */
{
(*cdd->cel->lib->cput_dot)((Raster *)cdd->cel, cdd->color, x, y);
}
static void line_test(Rcel *dcel)
{
int width = dcel->width, height = dcel->height;
int steps = height/10; /* ten pixels between lines */
int xinc = width/steps; /* x distance between lines */
int yinc = height/steps; /* y distance between lines */
int x = steps*xinc;
int y = 0;
int i;
Cdotdat cdd;
static int color = 0;
cdd.cel = dcel;
cdd.color = ++color;
for (i=0; i<steps; i++)
{
pj_cline(x,0,0,y,cdotout,&cdd);
x -= xinc;
y += yinc;
}
}
int imax(int a, int b)
/* return maximum of a,b */
{
return(a>b ? a : b);
}
typedef struct chlidat
{
Rcel *cel;
Pixel color;
} Chlidat;
Errcode chliout(SHORT y, SHORT x1, SHORT x2, Chlidat *chd)
/* unclipped horizontal line output */
{
(*chd->cel->lib->set_hline)((Raster *)chd->cel, chd->color, x1, y, x2-x1+1);
return(Success);
}
Errcode clip_chliout(SHORT y, SHORT x1, SHORT x2, Chlidat *chd)
/* unclipped horizontal line output */
{
pj_set_hline((Raster *)chd->cel, chd->color, x1, y, x2-x1+1);
return(Success);
}
static void circle_test(Rcel *cel)
{
SHORT width = cel->width, height = cel->height;
SHORT xcen = width/2, ycen = height/2;
SHORT maxdiam = imax(width,height)-2;
SHORT step = maxdiam/10;
static SHORT color = 0;
SHORT diam;
Chlidat chd;
chd.cel = cel;
for (diam=maxdiam; diam>=0; diam -= step)
{
chd.color = ++color;
dcircle(xcen,ycen,diam,NULL,NULL,clip_chliout,&chd,TRUE);
}
}
static void box_test(Rcel *cel)
{
SHORT width = cel->width, height = cel->height;
SHORT xcen = width/2, ycen = height/2;
SHORT xstep = width/20;
SHORT ystep = height/20;
SHORT wstep = 2*xstep;
SHORT hstep = 2*ystep;
SHORT x,y;
static SHORT color = 0;
for (x=0,y=0; x<xcen && y<ycen; x+=xstep,y+=ystep)
{
pj_set_rect(cel, ++color, x, y, width, height);
width -= wstep;
height -= hstep;
}
}
static Errcode test_draw(Rcel *dcel)
/* Draw various shapes in response to abuser input */
{
int scancode; /* keyboard scancode */
char asckey; /* ascii representation of keyboard scan code */
for (;;)
{
asckey = scancode = pj_key_in(); /* Hey dos, what did they hit? */
#define ESCKEY 0x1b
switch (asckey) /* Quit program on any
* escape looking key */
{
case ESCKEY:
case 'q':
case 'Q':
case 'x':
case 'X':
goto done_drawing;
case '0':
pj_set_rast(dcel,0);
break;
case '1':
line_test(dcel);
break;
case '2':
circle_test(dcel);
break;
case '3':
box_test(dcel);
break;
#ifdef SOON
case '4':
blit_test(dcel);
break;
#endif /* SOON */
}
}
done_drawing:
return(Success);
}
static Errcode getargs(int argc,char **argv)
/* Process command line into tcb control block */
{
int argcount;
int switchval;
int switch_arg;
int parm_err;
int pos_parm = 0;
static char help_text[] =
{
"\n"
"Usage: testdraw [options]\n\n"
"options: -v video_driver mode (default to mcga mode 0 320 by 200)\n"
};
parm_err = FALSE;
switch_arg = FALSE;
tcb.vd_path = pj_mcga_name;
for (argcount = 1; argcount < argc; ++argcount )
{
if ((!switch_arg) && *argv[argcount] == '-')
{
switchval = tolower(*(1 + argv[argcount]));
switch(switchval)
{
case 'v':
switch_arg = switchval;
break;
default:
parm_err = TRUE;
}
}
else if (switch_arg) /* if a -x switch needs a parm */
{
switch (switch_arg)
{
case 'v':
if(tcb.vd_path != &pj_mcga_name[0])
goto sa_parm_error;
tcb.vd_path = argv[argcount];
if(++argcount >= argc)
{
--argcount;
goto missing_arg;
}
if(sscanf(argv[argcount],"%hu%c", &tcb.vd_mode,
&tcb.vd_mode) != 1)
{
goto sa_parm_error;
}
break;
default:
sa_parm_error:
parm_err = TRUE;
}
if (!parm_err)
switch_arg = FALSE;
}
else
{
++pos_parm;
switch(pos_parm)
{
default:
parm_err = TRUE;
}
}
if (parm_err)
{
printf ( "Error: Input argument %d \"%s\" invalid.\n",
argcount,
argv[argcount] );
goto error;
}
}
if(switch_arg)
{
missing_arg:
printf ( "Error: Missing argument for -%c.\n", switch_arg );
goto error;
}
return(Success);
error:
printf("%s", help_text);
return(Err_reported);
}
main(int argc, char **argv)
{
Errcode err;
tcb.ovmode = pj_get_vmode();
if((err = getargs(argc,argv)) < Success)
goto error;
if((err = init_screen(&tcb.vd, &tcb.dcel, tcb.vd_path, tcb.vd_mode))
< Success)
goto error;
err = test_draw(tcb.dcel);
goto done;
error:
errline(err,"failure in main");
done:
pj_rcel_free(tcb.dcel);
pj_close_vdriver(&tcb.vd);
pj_set_vmode(tcb.ovmode);
exit((err < Success)?-1:0);
} |
syntax = "proto3";
option java_package = "com.assignment.grpc";
service user {
rpc Register(RegistrationRequest) returns (RegistrationResponse);
rpc Login(LoginRequest) returns (Response);
rpc Logout(LogoutRequest) returns (Response);
rpc CreateProfile(ProfileRequest) returns (ProfileResponse);
rpc UpdateProfile(UpdateProfileRequest) returns (ProfileResponse);
}
message RegistrationRequest {
string username = 1;
string password = 2;
}
message RegistrationResponse {
int32 responseCode = 1;
string message = 2;
}
message LoginRequest {
string username = 1;
string password = 2;
}
message Response {
int32 responseCode = 1;
string message = 2;
}
message LogoutRequest {}
message ProfileRequest {
string username = 1;
string fullName = 2;
string email = 3;
}
message UpdateProfileRequest {
string username = 1;
string fullName = 2;
string email = 3;
}
message ProfileResponse {
int32 responseCode = 1;
string message = 2 ;
} |
Feature: Login Functionality
User Story : As a user, I should be able to log in so that I can land on homepage.
Background: User should access the login page
Given user is on the login page
@FIX10-348 @wip
Scenario Outline: User should be able to login with valid credentials
When enter username "<username>" and password "<password>"
And user click on login button
Then user should see discuss page
Examples:
| username | password |
| salesmanager20@info.com | salesmanager |
| salesmanager21@info.com | salesmanager |
| posmanager20@info.com | posmanager |
| posmanager21@info.com | posmanager |
@FIX10-350 @wip
Scenario Outline: Verify "Wrong login/password" message is displayed using invalid credentials
When enter username "<username>" and password "<password>"
And user click on login button
Then User should see“Wrong login password“ message.
Examples:
| username | password |
| posmanager20@info.com | invalidpassword |
| invalidusername | posmanager |
| invalidusername | invalidpassword |
| salesmanager20@info.com | invalidpassword |
| invalidusername | salesmanager |
| invalidusername | invalidpassword |
@FIX10-351 @wip
Scenario Outline: Verify "Please fill out this field" message is displayed.
When enter username "<username>" and password "<password>"
And user click on login button
Then user should see the “Please fill out this field”message
Examples:
| username | password |
| posmanager20@info.com | |
| | posmanager |
| salesmanager20@info.com | |
| | salesmanager |
@FIX10-352 @wip
Scenario Outline: Verify that user see the password in bullet signs by default
When enter username "<username>" and password "<password>"
Then user should see the password in bullet signs
Examples:
| username | password |
| posmanager20@info.com | posmanager |
| salesmanager20@info.com | salesmanager |
@FIX10-353 @wip
Scenario Outline: Verify if the ‘Enter’ key of the keyboard is working correctly on the login page
When enter username "<username>" and password "<password>"
And user uses the Enter key on keyboard to log in
Then user should see discuss page
Examples:
| username | password |
| salesmanager20@info.com | salesmanager |
| salesmanager21@info.com | salesmanager |
| posmanager20@info.com | posmanager |
| posmanager21@info.com | posmanager | |
# 比特币白皮书学习
在听过大锤老师的课程和阅读比特币的白皮书之后。了解到比特币的发展历史。同时也了解了电子货币的发展历史。
1、传统的货币:传统的货币一般来说是政府机构,中央银行的货币发行和结算。
2、电子货币:在20世纪80年代末,许多研究人员开始尝试使用密码学技术构建数字货币。这些早期的数字货币项目发行的数字货币,通常由国家法定货币或贵金属(如黄金)来背书。
3、比特币:Bitcoin是在2008年由署名Satoshi Nakamoto的牛人发明的,他出版了一篇题为“Bitcoin:A Peer-to-Peer Electronic Cash System”的文章[1]。 Nakamoto结合了诸如b-money和HashCash等先前的发明,创建了一个完全去中心化的电子现金系统,它不依赖中央机构进行货币发行、结算和验证交易。关键的创新是使用分布式计算系统(称为“工作量证明”算法),每10分钟进行一次全球性的“选举”,从而实现分布式网络达成全网交易状态的共识。
在整个电子货币发展的过程中,始终面临着一个问题。即,双重支付的问题。传统货币,通常都是政府机构印刷的纸币。纸币天然的就可以避免双重支付的问题。因为同一张纸币不可能同时出现在两个地方,况且纸币由政府机构发行,政府必然拥有流通的货币的全局信息,那么只要经过精算所有的电子交易即可处理假币和避免双重支付。对于不能利用秘制油墨技术或全息条码的数字货币,密码学为保障用户财产价值的合法性提供了依据。比特币的诞生。从根本上解决了中央银行的货币发行和结算功能,取代了任何中央银行的功能。
比特币的四大创新
1、去中心化的点对点对等网络(比特币协议)
2、公开交易总帐(区块链)
3、独立验证交易和发行货币的一套规则(共识规则)
4、通过区块链有效实现全球去中心化共识的机制(工作量证明算法)
**UTXO**
比特币全节点跟踪所有可找到的和可使用的输出,称为 “未花费的交易输出”(unspent transaction outputs),即UTXO。
当用户的钱包已经“收到”比特币时,就意味着,钱包已经检测到了可用的UTXO,这些UTXO可以用钱包所控制的其中一个密钥消费。 因此,用户的比特币“余额”是指用户钱包中可用的UTXO总和,这些UTXO分散在几百个交易和几百个区块中。用户的 “比特币余额”,这个概念是比特币钱包应用创建的。比特币钱包扫描区块链,得到可以用这个钱包控制的密钥进行消费的所有UTXO,加到一起就计算出了该用户的余额 。大多数钱包维护一个数据库或使用数据库服务来存储所有UTXO的快速引用集,其中包含可以使用用户的密钥进行消费的所有UTXO。
一个UTXO可以是1“聪”(satoshi)的任意倍数(整数倍)。就像美元可以被分割成表示两位小数的“分”一样,比特币可以被分割成八位小数的“聪”。尽管UTXO可以是任意值,但一旦被创造出来,即不可分割。这是UTXO值得被强调的一个重要特性:UTXO的面值为“聪”的整数倍,是离散(不连续)且不可分割的价值单位,一个UTXO只能在一次交易中作为一个整体被消耗。
**数据结构 默克尔树**
What Is a Merkle Tree?
A Merkle tree is a data structure that is used in computer science applications. In bitcoin and other cryptocurrencies, Merkle trees serve to encode blockchain data more efficiently and securely.
They are also referred to as "binary hash trees."
Breaking Down Merkle Tree
In bitcoin's blockchain, a block of transactions is run through an algorithm to generate a hash, which is a string of numbers and letters that can be used to verify that a given set of data is the same as the original set of transactions, but not to obtain the original set of transactions. Bitcoin's software does not run the entire block of transaction data—representing 10 minutes' worth of transactions on average—through the hash function at one time, however.
1
Rather, each transaction is hashed, then each pair of transactions is concatenated and hashed together, and so on until there is one hash for the entire block. (If there is an odd number of transactions, one transaction is doubled and its hash is concatenated with itself.)
Visualized, this structure resembles a tree. In the diagram below, "T" designates a transaction, "H" a hash. Note that the image is highly simplified; an average block contains over 500 transactions, not eight.
2
The hashes on the bottom row are referred to as "leaves," the intermediate hashes as "branches," and the hash at the top as the "root." The Merkle root of a given block is stored in the header: for example, the Merkle root of block #482819 is e045b18e7a3d708d686717b4f44db2099aabcad9bebf968de5f7271b458f71c8. The root is combined with other information (the software version, the previous block's hash, the timestamp, the difficulty target, and the nonce) and then run through a hash function to produce the block's unique hash: 000000000000000000bfc767ef8bf28c42cbd4bdbafd9aa1b5c3c33c2b089594 in the case of block #482819. This hash is not actually included in the relevant block, but the next one; it is distinct from the Merkle root.
3

The Merkle tree is useful because it allows users to verify a specific transaction without downloading the whole blockchain (over 350 gigabytes at the end of June 2021).
4
For example, say that you wanted to verify that transaction TD is included in the block in the diagram above. If you have the root hash (HABCDEFGH), the process is like a game of sudoku: you query the network about HD, and it returns HC, HAB, and HEFGH. The Merkle tree allows you to verify that everything is accounted for with three hashes: given HAB, HC, HEFGH, and the root HABCDEFGH, HD (the only missing hash) has to be present in the data.
Merkle trees are named after Ralph Merkle, who proposed them in a 1987 paper titled "A Digital Signature Based on a Conventional Encryption Function." Merkle also invented cryptographic hashing.
**POW 工作量证明**
PoW(Proof of Work),即工作量证明,闻名于比特币,俗称"挖矿”。PoW是指系统为达到某一目标而设置的度量方法。简单理解就是一份证明,用来确认你做过一定量的工作。监测工作的整个过程通常是极为低效的,而通过对工作的结果进行认证来证明完成了相应的工作量,则是一种非常高效的方式。PoW是按劳分配,算力决定一起,谁的算力多谁记账的概率就越大,可理解为力量型比较。以下内容基于比特币的PoW机制。
工作量证明(PoW)通过计算一个数值( nonce ),使得拼揍上交易数据后内容的Hash值满足规定的上限。在节点成功找到满足的Hash值之后,会马上对全网进行广播打包区块,网络的节点收到广播打包区块,会立刻对其进行验证。
如何才能创建一个新区块呢?通过解决一个问题:即找到一个nonce值,使得新区块头的哈希值小于某个指定的值,即区块头结构中的“难度目标”。
如果验证通过,则表明已经有节点成功解迷,自己就不再竞争当前区块打包,而是选择接受这个区块,记录到自己的账本中,然后进行下一个区块的竞争猜谜。网络中只有最快解谜的区块,才会添加的账本中,其他的节点进行复制,这样就保证了整个账本的唯一性。作弊的话是不是更节省成本?对不起其他节点验证不通过打包的区块会被其他节点丢弃,就无法记录到总账本中,作弊的节点耗费的成本就白费了,因此在巨大的挖矿成本下,也使得矿工自觉自愿的遵守比特币系统的共识协议,也就确保了整个系统的安全。
在了解pow共识机制前,我们先了解下比特币区块的结构,下图是比特币区块的结构图:

从图上可知,比特币的结构分为区块头和区块体,其中区块头细分为:
父区块头哈希值:前一区块的哈希值,使用SHA256(SHA256(父区块头))计算。占32字节
随机数(Nonce):为了找到满足难度目标所设定的随机数,为了解决32位随机数在算力飞升的情况下不够用的问题,规定时间戳和coinbase交易信息均可更改,以此扩展nonce的位数。占4字节
版本:区块版本号,表示本区块遵守的验证规则。占4字节
时间戳:该区块产生的近似时间,精确到秒的UNIX时间戳,必须严格大于前11个区块时间的中值,同时全节点也会拒绝那些超出自己2个小时时间戳的区块。占4字节
难度:该区块工作量证明算法的难度目标,使用特定算法编码。占4字节
Merkle根:该区块中交易的Merkle树根的哈希值,同样采用SHA256(SHA256())计算。占32字节
我们会发现,区块头总共占了80字节。
区块体除了筹币交易记录(由一棵Merkle二叉树组成)外,还有一个交易计数。
比特币的任何一个节点,想生成一个新的区块,必须使用自己节点拥有的算力解算出pow问题。因此,我们先了解下pow工作量证明的三要素。
二、POW工作量证明的三要素
工作机制
为了使区块链交易数据记录在区块链上并在一定时间内达到一致(共识),PoW提供了一种思路,即所有区块链的网络节点参与者进行竞争记账,所谓竞争记账是指,如果想生成一个新的区块并写入区块链,必须解出比特币网络出的工作量证明谜题,谁先解出答案,谁就获得记账权利,然后开始记账并将将解出的答案和交易记录广播给其他节点进行验证,自己则开始下一轮挖矿。如果区块的交易被其他节点参与者验证有效并且谜题的答案正确,就意味着这个答案是可信的,新的节点将被写入验证者的节点区块链,同时验证者进入下一轮的竞争挖矿。
这道题关键的三个要素是工作量证明函数、区块及难度值。工作量证明函数是这道题的计算方法,区块决定了这道题的输入数据,难度值决定了这道题的所需要的计算量。
1、工作量证明函数
在比特币中使用的是SHA256算法函数,是密码哈希函数家族中输出值为256位的哈希算法。
2、 区块
区块头在前言中已经做详细介绍,这里就介绍下区块体的 Merkle树算法:

3、难度值,直接看公式:
新难度值=旧难度值*(过去2016个区块花费时长/20160分钟)
tips:难度值是随网络变动的,目的是为了在不同的网络环境下,确保每10分钟能生成一个块。
新难度值解析:撇开旧难度值,按比特币理想情况每10分钟出块的速度,过去2016个块的总花费接近20160分钟,这个值永远趋近于1。
目标值=最大目标值/难度值
目标值解析:最大目标值为一个固定数,若过去2016个区块花费时长少于20160分,那么这个系数会小,目标值将会被调大些,反之,目标值会被调小,因此,比特币的难度和出块速度将成反比例适当调整出块速度。
那如何计算呢?SHA256(SHA256(Block_Header)),即只需要对区块头进行两次SHA256运算即可,得到的值和目标值进行比较,小于目标值即可。
区块头中有一个重要的东西叫MerkleRoot的hash值。这个值意义在于:为了使区块头能体现区块所包含的所有交易,在区块的构造过程中,需要将该区块要包含的交易列表,通过Merkle Tree算法生成Merkle Root Hash,并以此作为交易列表的摘要存到区块头中。至此,我们发现区块头中除过nonce以外,其余的数据都是明确的,解题的核心就在于不停的调整nonce的值,对区块头进行双重SHA256运算。
介绍完pow工作量证明的三要素后,我们可以讲解下工作量证明的流程。
三、POW工作量证明流程

从流程图中看出,pow工作量证明的流程主要经历三步:
1.生成Merkle根哈希
生成Merkle根哈希在第二章节中的第2要素中已经有讲解,即节点自己生成一笔筹币交易,并且与其他所有即将打包的交易通过Merkle树算法生成Merkle根哈希,所以为什么说区块是工作量证明的三要素之一。
2.组装区块头
区块头将被作为计算出工作量证明输出的一个输入参数,因此第一步计算出来的Merkle根哈希和区块头的其他组成部分组装成区块头,这也就是为什么我们在前言中大费周章的去提前讲解比特币的区块头。
3.计算出工作量证明的输出,直接通过公式和一些伪代码去理解工作量证明的输出:
i. 工作量证明的输出=SHA256(SHA256(区块头))
ii. if(工作量证明的输出<目标值),证明工作量完成
iii.if(工作量证明的输出>=目标值),变更随机数,递归i的逻辑,继续与目标值比对。
注:目标值的计算见第二章节的要素3的难度值。
四.pow共识记账
第三章中讲解的是单节点工作量证明流程,有了这个计算流程,我们就得将其使用起来,在比特币平台中,中本聪就是运用的pow工作量证明来使全网节点达到51%及以上的共识记账,以下将介绍pow工作量证明共识是如何记账的?
首先,客户端产生新的交易,向全网广播
第二,每个节点收到请求,将交易纳入区块中
第三,每个节点通过第三章中描述的pow工作量证明
第四,当某个节点找到了证明,向全网广播
第五,当且仅当该区块的交易是有效的且在之前中未存在的,其他节点才认同该区块的有效性
第六,接受该区块且在该区块的末尾制造新的区块
大概时序图如下:

五、POW的优缺点
优点:
安全性高: PoW 算法基于工作量证明,要篡改区块链上的数据需要控制网络中大多数的算力,这是非常困难的,因此提供了高度的安全性。
去中心化: PoW允许任何人都可以参与挖矿,而不需要中心化的控制机构。这样确保了网络的去中心化性质。
广泛应用: PoW 被广泛应用于比特币等主流区块链,具有成熟的技术和广泛的社区支持。
抗攻击性强: PoW 机制使得网络对于各种攻击,如51%攻击,拒绝服务攻击等具有较强的抵抗力。
交易频率低:每秒钟最多只能做七笔交易,效率低下。
缺点:
能源消耗大: PoW 需要大量的计算能力来解决数学问题,这导致了极高的能源消耗,对环境造成了一定的压力。
中心化倾向: 随着比特币挖矿的专业化和大规模农场的兴起,算力逐渐集中在少数大型矿池,导致了一定的中心化趋势。
效率低: PoW 机制需要大量的计算时间和资源,这使得交易确认的速度相对较慢,尤其是在高负载时。
不适应轻量级设备: PoW 对计算能力的要求高,这使得一些轻量级设备或者移动设备不太适合进行挖矿操作。
长期潜在威胁: 量子计算机等新兴技术的发展可能对 PoW 的安全性产生威胁,因为它们可能会在短时间内破解目前的加密算法。
虽然 PoW 在比特币等一些主流区块链上取得了成功,但是由于其能源消耗大、中心化倾向等问题,一些新兴的共识机制如Proof of Stake (PoS) 和Delegated Proof of Stake (DPoS) 等也开始得到广泛关注。这些机制旨在解决 PoW 的一些缺点,提高区块链的效率和可持续性。 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.