text
stringlengths 184
4.48M
|
---|
import * as React from 'react';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import AddIcon from '@material-ui/icons/AddBox';
import axios from 'axios';
import config from '../../../../config';
import { IconButton } from '@mui/material';
export default function AddTransactionHistory({ row }) {
console.log(row.id);
const [open, setOpen] = React.useState(false);
const [textValue, setTextValue] = React.useState('');
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const handleAdd = async () => {
const { id, email, amount } = row;
let data = {
email: email,
amount: textValue,
};
await axios
.post(config.API_SERVER + `admin/addTransactionHistory/${id}`, data)
.then((res) => {
setOpen(false);
// console.log(res.data);
});
};
const onTextChange = async (e) => {
// e.preventDefault();
await setTextValue(e.target.value);
};
return (
<div>
<IconButton onClick={handleClickOpen}>
<AddIcon />
</IconButton>
<Dialog open={open} onClose={handleClose}>
<DialogTitle>Add Transaction History</DialogTitle>
<DialogContent>
<DialogContentText>
Enter the amount with increment or decrement sign
</DialogContentText>
<TextField
autoFocus
margin="dense"
id="amount"
onChange={onTextChange}
label="Enter Amount"
type="amount"
fullWidth
variant="standard"
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button onClick={handleAdd}>Add</Button>
</DialogActions>
</Dialog>
</div>
);
}
|
const prodData = require('../model/prodData');
const asyncHandler = require('express-async-handler');
const calculateSustainabilityScore = require('./../utils/calculateSustainabilityScore');
const carbonFootprintsCalc = require('./../utils/carbonFootprintsCalc');
// @desc Get score of the product
// @route GET /prodScore
// @access Private
const getProdScore = asyncHandler(async (req, res) => {
console.log(req.query)
const { Name } = req.query;
if (!Name) {
return res.status(400).json({ message: 'Product Name required' })
}
const prod = await prodData.find({ Name });
if (!prod || prod.length === 0) {
return res.status(400).json({ message: 'No such product exists' });
}
const sustainabilityScore = await calculateSustainabilityScore(prod[0])
const carbonFootprintsScore = await carbonFootprintsCalc(prod[0])
res.json({ sustainabilityScore, carbonFootprintsScore });
});
const createAProduct = asyncHandler(async (req, res) => {
const { Name, Description, RawMaterials, Company, Price, Type, ManufacturingProcess, Transportation, EnergyEfficiency, CarbonEmissions } = req.body;
const getDuplicateProduct = await prodData.find({ Name }).lean().exec();
if (getDuplicateProduct?.length) {
return res.status(409).json({ message: `Duplicate product name for ${Name}` });
}
const newProduct = { Name, Description, RawMaterials, Company, Price, Type, ManufacturingProcess, Transportation, EnergyEfficiency, CarbonEmissions };
const addedProduct = await prodData.create(newProduct)
if (addedProduct) {
res.status(200).json({ message: `${Name} created` })
} else {
res.status(400).json({ message: "Invalid product data recoreded." })
}
})
module.exports = { getProdScore, createAProduct }
|
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import *
###### ЛЕГКОВЫЕ АВТО ######
class CarRetrieveSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = '__all__'
class CarCreateSerializer(serializers.ModelSerializer):
user_create = serializers.HiddenField(default=serializers.CurrentUserDefault()) # поле user должно быть скрытым и автоматически заполняться данными текущего пользователя
class Meta:
model = Car
fields = '__all__'
read_only_fields = [
'id',
'user_create',
]
class CarUpdateSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = '__all__'
read_only_fields = [
'category',
'subcategory',
'user_create',
'grade',
]
def update(self, instance, validated_data):
# убираем ключи со значениями None из словаря
for key, value in list(validated_data.items()):
if value is None:
del validated_data[key]
instance.title = validated_data.get('title', instance.title)
instance.photo = validated_data.get('photo', instance.photo)
instance.brand = validated_data.get('brand', instance.brand)
instance.model = validated_data.get('model', instance.model)
instance.body_type = validated_data.get('body_type', instance.body_type)
instance.color = validated_data.get('color', instance.color)
instance.engine_type = validated_data.get('engine_type', instance.engine_type)
instance.drive_unit = validated_data.get('drive_unit', instance.drive_unit)
instance.transmission = validated_data.get('transmission', instance.transmission)
instance.engine_volume = validated_data.get('engine_volume', instance.engine_volume)
instance.year = validated_data.get('year', instance.year)
instance.mileage = validated_data.get('mileage', instance.mileage)
instance.air_conditioner = validated_data.get('air_conditioner', instance.air_conditioner)
instance.seat_heating = validated_data.get('seat_heating', instance.seat_heating)
instance.abs_esp_asr = validated_data.get('abs_esp_asr', instance.abs_esp_asr)
instance.regular_navigation = validated_data.get('regular_navigation', instance.regular_navigation)
instance.alloy_wheels = validated_data.get('alloy_wheels', instance.alloy_wheels)
instance.parctronic_camera = validated_data.get('parctronic_camera', instance.parctronic_camera)
instance.sunroof = validated_data.get('sunroof', instance.sunroof)
instance.theft_protection = validated_data.get('theft_protection', instance.theft_protection)
instance.xenon = validated_data.get('xenon', instance.xenon)
instance.cruise_control = validated_data.get('cruise_control', instance.cruise_control)
instance.aux_usb_bluetooth = validated_data.get('aux_usb_bluetooth', instance.aux_usb_bluetooth)
instance.state = validated_data.get('state', instance.state)
instance.vin = validated_data.get('vin', instance.vin)
instance.description = validated_data.get('description', instance.description)
instance.price = validated_data.get('price', instance.price)
instance.exchange = validated_data.get('exchange', instance.exchange)
instance.leasing = validated_data.get('leasing', instance.leasing)
instance.installment_plan = validated_data.get('installment_plan', instance.installment_plan)
instance.city = validated_data.get('city', instance.city)
instance.user_create = User.objects.latest('pk')
instance.save()
return instance
|
var
express = require( 'express' ),
routes = require('./routes'),
app = express(),
user = require('./routes/user'),
poet = require( './lib/poet' )( app );
// All default options, but shown for example
poet
.createPostRoute()
.createPageRoute()
.createTagRoute()
.createCategoryRoute()
.init();
app.set( 'view engine', 'ejs' );
app.set( 'views', __dirname + '/views' );
app.use( express.static( __dirname + '/public' ));
app.use( app.router );
app.get( '/', function ( req, res ) { res.render( 'index' ) });
app.get('/home', function(req, res){
res.render('home.ejs', {title: 'Space-Rocket Home'});
});
app.get('/team', function(req, res){
res.render('team.ejs', {title: 'Space-Rocket Team'});
});
app.get('/portfolio', function(req, res){
res.render('portfolio.ejs', {title: 'Space-Rocket Portfolio'});
});
app.get('/services', function(req, res){
res.render('services.ejs', {title: 'Space-Rocket Services'});
});
app.get('/blog', function(req, res){
res.render('blog.ejs', {title: 'Space-Rocket Blog'});
});
app.listen( 3000 );
|
var dog,sadDog,happyDog, database;
var foodS,foodStock;
var addFood;
var foodObj;
var lastFed;
//create feed and lastFed variable here
var feed;
var fedTime;
var bg;
function preload(){
sadDog=loadImage("Dog.png");
happyDog=loadImage("happy dog.png");
bg = loadImage("bg.png");
}
function setup() {
database = firebase.database();
console.log(database);
createCanvas(1000,400);
foodObj = new Food();
foodStock=database.ref('Food');
foodStock.on("value",readStock);
dog=createSprite(670,280,200,150);
dog.addImage(sadDog);
dog.scale=0.25;
//create feed the dog button here
feed = createButton("Feed the Dog");
feed.position(750,95);
feed.mousePressed(feedDog);
addFood=createButton("Add Food");
addFood.position(850,95);
addFood.mousePressed(addFoods);
}
function draw() {
background(bg);
foodObj.display();
//write code to read fedtime value from the database
fedTime = database.ref('FeedTime');
fedTime.on("value",function(data){
lastFed = data.val();
});
//write code to display text lastFed time here
if (lastFed>= 12){
textSize(30);
fill("black");
text("last Fed:" + lastFed % 12 +"PM", 50,70);
}
else if (lastFed ===0){
textSize(30);
fill("black");
text("last Fed : 12 AM" , 50,70);
}
else{
textSize(30);
fill("black");
text("last Fed :"+ lastFed + "AM" , 50,70);
}
drawSprites();
}
//function to read food Stock
function readStock(data){
foodS=data.val();
foodObj.updateFoodStock(foodS);
}
function feedDog(){
dog.addImage(happyDog);
//write code here to update food stock and last fed time
if(foodObj.getFoodStock()<= 0){
foodObj.updateFoodStock(foodObj.getFoodStock()*0)
}else{
foodObj.updateFoodStock(foodObj.getFoodStock()-1)
}
database.ref('/').update({
Food: foodObj.getFoodStock(),
FeedTime: hour()
})
}
//function to add food in stock
function addFoods(){
foodS++;
database.ref('/').update({
Food:foodS
})
}
|
# Learn Python 🐍
Collection of Python scripts organized by topics with code examples.
## Contents
#### Comprehension, Lambdas and High-order Functions
- [List Comprehension](https://github.com/fer-aguirre/learn-python/blob/master/comprehensions/list_comprehensions.ipynb)
- [Dictionary Comprehension](https://github.com/fer-aguirre/learn-python/blob/master/comprehensions/dict_comprehensions.ipynb)
- [Anonymous Function](https://github.com/fer-aguirre/learn-python/blob/master/functions/anonymous_functions.ipynb)
- [High-Order Functions](https://github.com/fer-aguirre/learn-python/blob/master/functions/high_order_functions.ipynb)
- [Data Filter Function](https://github.com/fer-aguirre/learn-python/blob/master/functions/data_filter.ipynb)
#### Error Handling
- [Exceptions](https://github.com/fer-aguirre/learn-python/blob/master/handle_errors/exceptions.ipynb)
- [Debugging with Exceptions](https://github.com/fer-aguirre/learn-python/blob/master/handle_errors/debugging_exceptions.py)
- [Assert Statements](https://github.com/fer-aguirre/learn-python/blob/master/handle_errors/assert_statements.ipynb)
- [Debugging with Assert Statements](https://github.com/fer-aguirre/learn-python/blob/master/handle_errors/debugging_assert.py)
- [Hangman Game](https://github.com/fer-aguirre/learn-python/blob/master/handle_errors/hangman_game.py)
#### Static Typing
- [Static Typing with Primitive Data Types](https://github.com/fer-aguirre/learn-python/blob/master/static_typing/st_data_types.ipynb)
- [Static Typing with Data Structures](https://github.com/fer-aguirre/learn-python/blob/master/static_typing/st_data_structures.ipynb)
- [Palindrome Function](https://github.com/fer-aguirre/learn-python/blob/master/static_typing/palindrome.py)
- [Prime Number Function](https://github.com/fer-aguirre/learn-python/blob/master/static_typing/prime_number.py)
- [Testing Methods](https://github.com/fer-aguirre/learn-python/blob/master/static_typing/test.py)
#### Object-Oriented Programming
- [Classes](https://github.com/fer-aguirre/learn-python/blob/master/object-oriented_programming/classes.ipynb)
- [Decomposition](https://github.com/fer-aguirre/learn-python/blob/master/object-oriented_programming/decomposition.ipynb)
- [Abstraction](https://github.com/fer-aguirre/learn-python/blob/master/object-oriented_programming/abstraction.ipynb)
- [Encapsulation](https://github.com/fer-aguirre/learn-python/blob/master/object-oriented_programming/encapsulation.ipynb)
#### Advanced Functions Concepts
- [Scopes](https://github.com/fer-aguirre/learn-python/blob/master/functions_concepts/scopes.ipynb)
- [Closures](https://github.com/fer-aguirre/learn-python/blob/master/functions_concepts/closures.ipynb)
- [Decorators](https://github.com/fer-aguirre/learn-python/blob/master/functions_concepts/decorators.ipynb)
- [Time Execution](https://github.com/fer-aguirre/learn-python/blob/master/functions_concepts/time_execution.py)
- [Custom Message](https://github.com/fer-aguirre/learn-python/blob/master/functions_concepts/custom_message.py)
- [Date Message](https://github.com/fer-aguirre/learn-python/blob/master/functions_concepts/date_message.py)
#### Advanced Data Structures
- [Iterators](https://github.com/fer-aguirre/learn-python/blob/master/iterators/iterators.ipynb)
- [Fibonacci](https://github.com/fer-aguirre/learn-python/blob/master/iterators/fibonacci.py)
- [Generators](https://github.com/fer-aguirre/learn-python/blob/master/generators/generators.ipynb)
- [Fibonacci](https://github.com/fer-aguirre/learn-python/blob/master/generators/fibonacci.py)
- [Fibonacci Limit](https://github.com/fer-aguirre/learn-python/blob/master/generators/fibonacci_limit.py)
- [Sets](https://github.com/fer-aguirre/learn-python/blob/master/sets/sets.ipynb)
- [Sets Operations](https://github.com/fer-aguirre/learn-python/blob/master/sets/sets_operations.ipynb)
- [Remove Duplicates](https://github.com/fer-aguirre/learn-python/blob/master/sets/remove_duplicates.py)
#### Modules
- [datetime](https://github.com/fer-aguirre/learn-python/blob/master/modules/datetime.ipynb)
- [pytz](https://github.com/fer-aguirre/learn-python/blob/master/modules/pytz.ipynb)
- [os](https://github.com/fer-aguirre/learn-python/blob/master/modules/os.ipynb)
- [pathlib](https://github.com/fer-aguirre/learn-python/blob/master/modules/pathlib.ipynb)
- [pyfilesystem2](https://github.com/fer-aguirre/learn-python/blob/master/modules/pyfilesystem2.ipynb)
- [pyhere](https://github.com/fer-aguirre/learn-python/blob/master/modules/pyhere.ipynb)
- [numpy](https://github.com/fer-aguirre/learn-python/blob/master/modules/numpy.ipynb)
- [pandas](https://github.com/fer-aguirre/learn-python/tree/master/modules/pandas)
- [Series, Indexing](https://github.com/fer-aguirre/learn-python/blob/master/modules/pandas/series_indexing.ipynb)
- [Pivot Table](https://github.com/fer-aguirre/learn-python/blob/master/modules/pandas/pivot_table.ipynb)
- [Select Data](https://github.com/fer-aguirre/learn-python/blob/master/modules/pandas/select_data.ipynb)
- [Data Types](https://github.com/fer-aguirre/learn-python/blob/master/modules/pandas/datatypes.ipynb)
- [Math Functions](https://github.com/fer-aguirre/learn-python/blob/master/modules/pandas/math_functions.ipynb)
#### Natural Language Processing
- [Introduction](https://github.com/fer-aguirre/learn-python/blob/master/nlp/introduction.ipynb)
- [Lexical Diversity](https://github.com/fer-aguirre/learn-python/blob/master/nlp/lexical_diversity.ipynb)
- [Language Statistics](https://github.com/fer-aguirre/learn-python/blob/master/nlp/language_statistics.ipynb)
- [N-grams](https://github.com/fer-aguirre/learn-python/blob/master/nlp/n-grams.ipynb)
- [Collocations](https://github.com/fer-aguirre/learn-python/blob/master/nlp/collocations.ipynb)
- [Lexical Resources](https://github.com/fer-aguirre/learn-python/blob/master/nlp/lexical_resources.ipynb)
- [WordNet](https://github.com/fer-aguirre/learn-python/blob/master/nlp/wordnet.ipynb)
- [Semantic Similarity](https://github.com/fer-aguirre/learn-python/blob/master/nlp/semantic_similarity.ipynb)
- [Processing Plain Text](https://github.com/fer-aguirre/learn-python/blob/master/nlp/process_plain_text.ipynb)
- [Part of Speech (POS) Tagging](https://github.com/fer-aguirre/learn-python/blob/master/nlp/pos_tagging.ipynb)
|
import React from 'react'
import NavbarHeader from './NavbarHeader'
import {AiOutlineHome} from 'react-icons/ai'
import {BsPeople} from 'react-icons/bs'
import {SlNotebook} from 'react-icons/sl'
import { VStack } from '@chakra-ui/react'
import NavbarSection from './NavbarSection'
const Navbar = () => {
return (
<VStack>
<NavbarHeader title={'Bills App'} />
<NavbarSection
label={'Navegação'}
options={[
{
icon: AiOutlineHome,
title: 'Home',
link: '/',
},
{
icon: BsPeople,
title: 'Credores',
link: '/credores'
},
{
icon: SlNotebook,
title: 'Dívidas',
link: '/dividas'
}
]}
/>
</VStack>
)
}
export default Navbar
|
import torch.nn as nn
import torch
import torch.nn.functional as F
from models.transformer.attention import MultiheadAttention2
def fill_with_neg_inf(t):
"""FP16-compatible function that fills a tensor with -inf."""
return t.float().fill_(float('-inf')).type_as(t)
class TransformerDecoder(nn.Module):
def __init__(self, num_layers, d_model, num_heads, dropout=0.0):
super().__init__()
self.decoder_layers = nn.ModuleList([
TransformerDecoderLayer(d_model, num_heads, dropout)
for _ in range(num_layers)
])
def buffered_future_mask(self, tensor):
dim = tensor.size(0)
if not hasattr(self, '_future_mask') or self._future_mask is None or self._future_mask.device != tensor.device:
self._future_mask = torch.triu(fill_with_neg_inf(tensor.new(dim, dim)), 1)
if self._future_mask.size(0) < dim:
self._future_mask = torch.triu(fill_with_neg_inf(self._future_mask.resize_(dim, dim)), 1)
return self._future_mask[:dim, :dim]
def forward(self, src, src_mask, tgt, tgt_mask):
non_pad_src_mask = None if src_mask is None else 1 - src_mask
non_pad_tgt_mask = None if tgt_mask is None else 1 - tgt_mask
if src is not None:
src = src.transpose(0, 1)
x = tgt.transpose(0, 1)
for layer in self.decoder_layers:
x, weight = layer(x, non_pad_tgt_mask,
src, non_pad_src_mask,
self.buffered_future_mask(x))
return x.transpose(0, 1)
class TransformerDecoderLayer(nn.Module):
def __init__(self, d_model, num_heads, dropout=0.0):
super().__init__()
d_model = d_model
num_heads = num_heads
self.dropout = dropout
self.self_attn = MultiheadAttention2(d_model, num_heads)
self.self_attn_layer_norm = nn.LayerNorm(d_model)
self.encoder_attn = MultiheadAttention2(d_model, num_heads)
self.encoder_attn_layer_norm = nn.LayerNorm(d_model)
self.fc1 = nn.Linear(d_model, d_model << 1)
self.fc2 = nn.Linear(d_model << 1, d_model)
self.final_layer_norm = nn.LayerNorm(d_model)
def forward(self, x, mask, encoder_out=None, encoder_mask=None, self_attn_mask=None):
res = x
x, weight = self.self_attn(x, x, x, mask, attn_mask=self_attn_mask)
x = F.dropout(x, p=self.dropout, training=self.training)
x = res + x
x = self.self_attn_layer_norm(x)
if encoder_out is not None:
res = x
x, weight = self.encoder_attn(x, encoder_out, encoder_out, encoder_mask)
x = F.dropout(x, p=self.dropout, training=self.training)
x = res + x
x = self.encoder_attn_layer_norm(x)
res = x
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = res + x
x = self.final_layer_norm(x)
return x, weight
class TransformerEncoder(nn.Module):
def __init__(self, num_layers, d_model, num_heads, dropout=0.0):
super().__init__()
self.encoder_layers = nn.ModuleList([
TransformerEncoderLayer(d_model, num_heads, dropout)
for _ in range(num_layers)
])
def forward(self, x, mask=None):
non_padding_mask = None if mask is None else 1 - mask
x = x.transpose(0, 1)
for layer in self.encoder_layers:
x = layer(x, non_padding_mask)
x = x.transpose(0, 1)
return x
class TransformerEncoderLayer(nn.Module):
def __init__(self, d_model, num_heads, dropout=0.0):
super().__init__()
d_model = d_model
num_heads = num_heads
self.dropout = dropout
self.attn_mask = None
self.self_attn = MultiheadAttention2(d_model, num_heads)
self.self_attn_layer_norm = nn.LayerNorm(d_model)
self.fc1 = nn.Linear(d_model, d_model << 1)
self.fc2 = nn.Linear(d_model << 1, d_model)
self.final_layer_norm = nn.LayerNorm(d_model)
def forward(self, x, mask):
dim = x.size(0)
attn_mask = None if self.attn_mask is None else self.attn_mask.cuda()[:dim, :dim]
res = x
x, weight = self.self_attn(x, x, x, mask, attn_mask=attn_mask)
x = F.dropout(x, p=self.dropout, training=self.training)
x = res + x
x = self.self_attn_layer_norm(x)
res = x
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = F.dropout(x, p=self.dropout, training=self.training)
x = res + x
x = self.final_layer_norm(x)
return x
class Transformer(nn.Module):
def __init__(self, d_model, num_heads, num_encoder_layers, num_decoder_layers, dropout=0.0):
super().__init__()
self.encoder = TransformerEncoder(num_encoder_layers, d_model, num_heads, dropout)
self.decoder = TransformerDecoder(num_decoder_layers, d_model, num_heads, dropout)
def forward(self, src, src_mask, tgt, tgt_mask):
enc_out = self.encoder(src, src_mask)
out = self.decoder(enc_out, src_mask, tgt, tgt_mask)
return out
class DualTransformer(nn.Module):
def __init__(self, d_model, num_heads, num_decoder_layers1, num_decoder_layers2, dropout=0.0):
super().__init__()
self.decoder1 = TransformerDecoder(num_decoder_layers1, d_model, num_heads, dropout)
self.decoder2 = TransformerDecoder(num_decoder_layers2, d_model, num_heads, dropout)
def forward(self, src1, src_mask1, src2, src_mask2, decoding=1, enc_out=None):
assert decoding in [1, 2]
if decoding == 1:
if enc_out is None:
enc_out = self.decoder2(None, None, src2, src_mask2)
out = self.decoder1(enc_out, src_mask2, src1, src_mask1)
elif decoding == 2:
if enc_out is None:
enc_out = self.decoder1(None, None, src1, src_mask1)
out = self.decoder2(enc_out, src_mask1, src2, src_mask2)
return enc_out, out
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.farmacia.jpamodel;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author jgcastillo
*/
@Entity
@Table(name = "usuario")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Usuario.findAll", query = "SELECT u FROM Usuario u")
, @NamedQuery(name = "Usuario.findById", query = "SELECT u FROM Usuario u WHERE u.id = :id")
, @NamedQuery(name = "Usuario.findByUsername", query = "SELECT u FROM Usuario u WHERE u.username = :username")
, @NamedQuery(name = "Usuario.findByPassword", query = "SELECT u FROM Usuario u WHERE u.password = :password")
, @NamedQuery(name = "Usuario.findByNombre", query = "SELECT u FROM Usuario u WHERE u.nombre = :nombre")
, @NamedQuery(name = "Usuario.findByApellido", query = "SELECT u FROM Usuario u WHERE u.apellido = :apellido")
, @NamedQuery(name = "Usuario.findByNivel", query = "SELECT u FROM Usuario u WHERE u.nivel = :nivel")})
public class Usuario implements Serializable {
private static final long serialVersionUID = 1L;
public static final int SUPER_ADMIN = 0;
public static final int ADMIN = 1;
public static final int USER = 2;
public static final int CONSULTA = 3;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@Column(name = "username")
private String username;
@Basic(optional = false)
@Column(name = "password")
private String password;
@Column(name = "nombre")
private String nombre;
@Column(name = "apellido")
private String apellido;
@Basic(optional = false)
@Column(name = "nivel")
private int nivel;
public Usuario() {
}
public Usuario(Integer id) {
this.id = id;
}
public Usuario(Integer id, String username, String password, int nivel) {
this.id = id;
this.username = username;
this.password = password;
this.nivel = nivel;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public int getNivel() {
return nivel;
}
public void setNivel(int nivel) {
this.nivel = nivel;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Usuario)) {
return false;
}
Usuario other = (Usuario) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "org.farmacia.jpamodel.Usuario[ id=" + id + " ]";
}
}
|
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:socon/utils/colors.dart';
import 'package:socon/utils/responsive_utils.dart';
import 'package:socon/views/modules/app_bar.dart';
import 'package:socon/views/modules/success_card.dart';
import '../../../utils/fontSizes.dart';
import '../../../utils/result_msg_type.dart';
import 'package:confetti/confetti.dart';
import '../../atoms/buttons.dart';
class ApprovalScreen extends StatefulWidget {
final String pathParameter;
ApprovalScreen(this.pathParameter, {Key? key}) : super(key: key);
@override
_ApprovalScreenState createState() => _ApprovalScreenState();
}
class _ApprovalScreenState extends State<ApprovalScreen> {
late String soconId;
@override
void initState() {
super.initState();
soconId = widget.pathParameter;
print("soconId 가져왔니 $soconId");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: null,
body: Center(
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Column(
children: [
SizedBox(
height:
ResponsiveUtils.getHeightWithPixels(context, 200),
),
Text(
"소콘소콘",
style: TextStyle(
color: AppColors.YELLOW,
fontSize: ResponsiveUtils.calculateResponsiveFontSize(
context,
FontSizes.LARGE,
),
fontFamily: "BagelFatOne",
),
),
SizedBox(height: 20),
Text(
"7,800원",
style: TextStyle(
fontSize:
ResponsiveUtils.calculateResponsiveFontSize(
context,
FontSizes.XXXXLARGE,
),
fontWeight: FontWeight.w800,
),
),
SizedBox(height: 40),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
buildInfoRow(context, "상품명", "육개장"),
buildInfoRow(context, "구매일", "2024-03-02"),
buildInfoRow(context, "유효기간", "2024-03-02"),
buildInfoRow(context, "사용처", "국밥집"),
],
),
SizedBox(height: 20),
],
),
SizedBox(
height:
ResponsiveUtils.getHeightWithPixels(context, 200),
),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
BasicButton(
text: "거절하기",
onPressed: () {},
color: "gray",
btnSize: 's',
textColor: "black",
),
BasicButton(
text: "승인하기",
btnSize: 's',
onPressed: () {
print("승인");
GoRouter.of(context)
.go("/approval/$soconId/success");
},
textColor: "white",
),
],
),
)
],
),
),
),
);
}
Widget buildInfoRow(BuildContext context, String label, String value) {
return Container(
width: ResponsiveUtils.getWidthWithPixels(context, 320),
padding: EdgeInsets.symmetric(horizontal: 25.0, vertical: 3.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
label,
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: ResponsiveUtils.calculateResponsiveFontSize(
context,
FontSizes.XXSMALL,
),
),
),
Text(
value,
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: ResponsiveUtils.calculateResponsiveFontSize(
context,
FontSizes.XXSMALL,
),
),
),
],
),
);
}
}
|
import React, { ReactNode, createContext, useReducer } from "react";
import rootReducer from "./store";
import { initialState } from "./initialState";
type AppState = typeof initialState
interface StoreContextType {
state: AppState;
dispatch: React.Dispatch<any>;
}
const defaultStoreContext: StoreContextType = {
state: initialState,
dispatch: () => {},
};
export const Store = createContext<StoreContextType>(defaultStoreContext)
interface StoreProviderProps {
children: ReactNode;
}
export function StoreProvider({ children }: StoreProviderProps) {
const [state, dispatch] = useReducer(rootReducer, initialState);
const value: StoreContextType = { state, dispatch };
return <Store.Provider value={value}>{children}</Store.Provider>;
}
|
/** @jsxImportSource @emotion/react */
import { useEffect } from 'react';
import { css } from '@emotion/react';
import { Navigation } from 'components/Navigation';
import { Card } from 'components/Card';
import { useAppContext } from 'utils/context';
import useFetch from 'hooks/useFetch';
import { NearbyStays } from 'components/NearbyStays';
const appContainerStyles = css`
display: flex;
flex-direction: column;
gap: var(--space-xl);
max-width: 1024px;
padding: var(--space-l);
margin: 0 auto;
font-family: var(--font-family);
`;
export const App = () => {
const { homes, setHomes, bookmarkedItems, setBookmarkedItems } =
useAppContext();
const URL =
'https://public.opendatasoft.com/api/explore/v2.1/catalog/datasets/airbnb-listings/records?limit=9&refine=country%3AIreland';
const fetchData = useFetch(URL);
useEffect(() => {
const { isLoading, data } = fetchData;
!isLoading && setHomes(data.results);
}, [fetchData, setHomes]);
const isItemBookmarked = (itemId: string) =>
!!bookmarkedItems.includes(itemId);
const handleBookmarking = (currentId: string) => {
const updatedBookmarkedItems = isItemBookmarked(currentId)
? bookmarkedItems.filter((item) => item !== currentId)
: [...bookmarkedItems, currentId];
setBookmarkedItems(updatedBookmarkedItems);
};
return (
<div css={appContainerStyles}>
<Navigation />
<NearbyStays>
{homes.map((home) => {
const { id, street, number_of_reviews, bedrooms, bathrooms, price } =
home;
const isBookmarked = isItemBookmarked(id);
const hasLowRates = price < 75;
const isUsuallyBooked = number_of_reviews > 10;
const shouldDisplayTag = hasLowRates || isUsuallyBooked;
return (
<Card.Root key={id}>
<Card.Container>
<Card.ContentLeft>
<Card.Title>{street}</Card.Title>
<Card.Meta
bedrooms={bedrooms}
bathrooms={bathrooms}
startDate="Nov 17"
endDate="Nov 19"
/>
</Card.ContentLeft>
<Card.ContentRight>
{shouldDisplayTag && (
<Card.Tag
isUsuallyBooked={isUsuallyBooked}
hasLowRates={hasLowRates}
/>
)}
<Card.Action
icon={Card.Icon}
isBookmarked={isBookmarked}
onClick={() => handleBookmarking(id)}
/>
</Card.ContentRight>
</Card.Container>
<Card.Footer total={`$${price * 2}`} />
</Card.Root>
);
})}
</NearbyStays>
</div>
);
};
export default App;
|
import React from "react";
import $ from "jquery";
import { useSelector } from "react-redux";
import { useState, useEffect } from "react";
import CoverIcon from "../svg/cover.svg";
import MixIcon from "../svg/karistir.svg";
import BackIcon from "../svg/geri.svg";
import PauseIcon from "../svg/pause.svg";
import PlayIcon from "../svg/play.svg";
import NextIcon from "../svg/next.svg";
import ReplyIcon from "../svg/replay.svg";
import HeartIcon from "../svg/heart.svg";
import FilledHeartIcon from "../svg/fillheart.svg";
import WindowRestoreIcon from "../svg/window-restore.svg";
import MicIcon from "../svg/microphone.svg";
import BarsIcon from "../svg/bars.svg";
import LinkIcon from "../svg/link.svg";
import MuteIcon from "../svg/mute.svg";
import VlowIcon from "../svg/volume-low.svg";
import VhighIcon from "../svg/volume-high.svg";
import MaxscaleIcon from "../svg/maxscale.svg";
const Footer = () => {
const { activeMusic } = useSelector((state) => ({
activeMusic: state.site.activeMusic,
}));
const [liked, setLiked] = useState(false);
const [clicked, setClicked] = useState(false);
const [time, setTime] = useState(0);
$(document).ready(function () {
const muteIcon = $("#mute-icon");
const volumeRange = $("#volume-range");
// let previousVolume = 100;
muteIcon.on("click", function () {
volumeRange.val(0);
muteIcon.attr("src", MuteIcon);
});
volumeRange.on("input", function () {
const volume = volumeRange.val();
if (volume === "0") {
muteIcon.attr("src", MuteIcon);
} else if (volume > 0 && volume < 120) {
muteIcon.attr("src", VlowIcon);
} else {
muteIcon.attr("src", VhighIcon);
}
});
});
useEffect(() => {
let interval = null;
if (clicked) {
interval = setInterval(() => {
setTime((prevTime) => prevTime + 1);
}, 1000);
} else {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [clicked]);
const formatTime = (time) => {
const minutes = Math.floor(time / 60)
.toString()
.padStart(1, "0");
const seconds = (time % 60).toString().padStart(2, "0");
return `${minutes}:${seconds}`;
};
const handleChange = (event) => {
setTime(parseInt(event.target.value));
};
return (
<div className=" h-[96px] bg-[#181818] flex ">
<div className="flex-none w-[250px] h-[96px] py-auto text-clip overflow-hidden relative">
<div className="flex">
<img
className="w-14 h-12 m-3 cursor-pointer mt-5"
src={activeMusic.imageData}
alt="cover"
></img>
<div className="text-white w-180 font-light cursor-pointer mt-6 ">
<span className=" text-white text-[14px] w-96 font-light mt-0 absolute hover:underline">
{activeMusic.title}
</span>
<div className="flex text-[12px] w-96 mt-5">
{activeMusic?.artists?.map((artist, index) => (
<span key={index} className=" mr-1 hover:underline">
{artist.name + ","}
</span>
))}
</div>
</div>
</div>
<div className="absolute h-16 top-0 -right-3 w-6 backdrop-blur-sm backdrop-filter "></div>
</div>
<div className="h-full w-[62px] flex-none cursor-pointer items-center">
<div className="flex items-center mt-7">
<div className="w-4 h-4 flex items-center justify-center m-2">
<img
className="hover:scale-125 hover:text-white"
src={liked ? FilledHeartIcon : HeartIcon}
alt="like"
onClick={() => setLiked(!liked)}
/>
</div>
<div className="w-3.5 h-3.5 flex items-center justify-center m-2 mt-2">
<img
className="hover:scale-125"
src={WindowRestoreIcon}
alt="like"
/>
</div>
</div>
</div>
<div className="w-full min-w-[260px] flex-grow-0 ">
<div className="flex justify-center mt-4 ">
<div className="w-4.5 h-4.5 flex items-center cursor-pointer justify-center ">
<img className=" mt-4 hover:scale-125" src={MixIcon} alt="mix" />
</div>
<div className="w-3.5 h-3.5 flex items-center cursor-pointer justify-center mt-2.5 ml-4 ">
<img className="hover:scale-125" src={BackIcon} alt="mix" />
</div>
<div className=" flex items-center justify-center cursor-pointer ml-4 bg-gray-200 rounded-full ">
<img
className="w-9 h-9 hover:scale-110"
src={clicked ? PauseIcon : PlayIcon}
alt="click"
onClick={() => setClicked(!clicked)}
/>
</div>
<div className="w-3.5 h-3.5 flex cursor-pointer items-center justify-center mt-2.5 ml-4 ">
<img className="hover:scale-125" src={NextIcon} alt="mix" />
</div>
<div className="w-4.5 h-4.5 flex cursor-pointer items-center justify-center mt-2.5 ml-4 ">
<img className="hover:scale-125" src={ReplyIcon} alt="mix" />
</div>
</div>
<div className="w-4/5 mx-auto">
<span className="text-gray-300 text-[11px] font-semibold left-0">
{formatTime(time)}
</span>
<div className="flex items-center justify-center bg-white rounded-full">
<input
type="range"
min="0"
max="240"
step="1"
value={time}
className="w-full h-1 bg-gray-300 rounded-lg hover:bg-green-600 appearance-none"
onChange={handleChange}
/>
</div>
</div>
</div>
<div className="right-0 max-w-[300px] min-w-[300px] flex-grow-0">
<div className="flex justify-center mt-7 ml-1 mr-4 right-0 ">
<div className="w-4 h-4 flex items-center cursor-pointer ">
<img className=" mt-4 hover:scale-125" src={MicIcon} alt="mix" />
</div>
<div className="w-4 h-4 flex ml-4 items-center cursor-pointer ">
<img className=" mt-4 hover:scale-125" src={BarsIcon} alt="mix" />
</div>
<div className="w-5 h-5 flex ml-4 items-center cursor-pointer ">
<img className=" mt-4 hover:scale-125" src={LinkIcon} alt="mix" />
</div>
<div className="w-4.5 h-4.5 flex ml-4 items-center cursor-pointer ">
<img
id="mute-icon"
className=" mt-4 hover:scale-125"
src={MuteIcon}
alt="mix"
/>
</div>
<div className="mt-4 ml-2 ">
<div className="flex items-center w-28 right-0 bg-white rounded-full">
<input
id="volume-range"
type="range"
min="0"
max="240"
step="1"
className=" h-1 w-28 bg-gray-300 rounded-lg hover:bg-green-600 appearance-none"
/>
</div>
</div>
<div className="w-4 h-4 flex ml-2 items-center cursor-pointer ">
<img
className=" mt-5 hover:scale-125"
src={MaxscaleIcon}
alt="mix"
/>
</div>
</div>
</div>
</div>
);
};
export default Footer;
|
import React, { useEffect, useState } from "react";
import { Line } from "react-chartjs-2";
// eslint-disable-next-line
import { Chart as ChartJS } from "chart.js/auto";
const Section2LineChartLast30Days = () => {
const [time, setTime] = useState();
const [totalDoses, setTotalDoses] = useState();
const [doseOne, setDoseOne] = useState();
const [doseTwo, setDoseTwo] = useState();
const [precautionDose, setPrecautionDose] = useState();
useEffect(() => {
const fetchData = async () => {
try {
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, "0"); // Adding +1 to account for zero-based months
const day = String(today.getDate()).padStart(2, "0");
const formattedDate = `${year}-${month}-${day}`;
// console.log(formattedDate);
const response = await fetch(
`https://api.cowin.gov.in/api/v1/reports/v2/getVacPublicReports?state_id=&district_id=&date=${formattedDate}`
);
const jsonData = await response.json();
// console.log(jsonData.vaccinationDoneByTime.map((item) => item.label));
setTime(
jsonData.last30DaysVaccination.map((item) => {
const dateStr = item.vaccine_date;
const date = new Date(dateStr);
const options = { day: "2-digit", month: "short" };
const formattedDate = date.toLocaleDateString("en-US", options);
console.log(formattedDate);
return formattedDate;
})
);
setTotalDoses(jsonData.last30DaysVaccination.map((item) => item.total));
setDoseOne(jsonData.last30DaysVaccination.map((item) => item.dose_1));
setDoseTwo(jsonData.last30DaysVaccination.map((item) => item.dose_2));
setPrecautionDose(
jsonData.last30DaysVaccination.map((item) => item.dose_pd)
);
} catch (error) {
console.log("Error fetching data:", error);
}
};
fetchData();
}, []);
const data = {
labels: time,
datasets: [
{
label: "Total Doses", // Name of the first line
data: totalDoses,
borderColor: "rgb(245,67,148)",
tension: 0.1,
fill: "start",
backgroundColor: "rgba(245,67,148,0.1)", // Fill color
// Name of the first line for the legend
},
{
label: "Dose One", // Name of the second line
data: doseOne,
borderColor: "rgb(255,152,0)",
tension: 0.1,
fill: "start",
backgroundColor: "rgba(255,152,0,0.1)", // Fill color
// Name of the second line for the legend
},
{
label: "Dose Two", // Name of the second line
data: doseTwo,
borderColor: "rgb(33,204,152)",
tension: 0.1,
fill: "start",
backgroundColor: "rgba(33,204,152,0.1)", // Fill color
// Name of the second line for the legend
},
{
label: "Precaution Dose", // Name of the second line
data: precautionDose,
borderColor: "rgb(18,173,6)",
tension: 0.1,
fill: "start",
backgroundColor: "rgba(18,173,6,0.1)", // Fill color
// Name of the second line for the legend
},
],
};
// const options = {
// scales: {
// y: {
// display: false, // Hide y-axis
// },
// x: {
// display: false, // Hide x-axis
// },
// },
// plugins: {
// legend: {
// display: false, // Hide legend
// },
// },
// maintainAspectRatio: false,
// };
const options = {
scales: {
x: {
display: true,
grid: {
color: "#00000005",
},
},
y: {
ticks: {
callback: (value) => {
return `${value / 1000}k`;
},
},
display: true,
// title: {
// display: true,
// text: "Number of Vaccinations",
// },
grid: {
color: "#00000005",
},
},
},
plugins: {
legend: {
labels: {
usePointStyle: true, // Use circular legend point style
},
position: "bottom",
},
tooltip: {
// callbacks: {
// label: (context) => {
// const label = context.dataset.label || "";
// const value1 = context.parsed.y || "";
// const value2 =
// context.datasetIndex === 0
// ? vaccinations2[context.dataIndex]
// : vaccinations1[context.dataIndex];
// return `${value1} ${value2}`;
// },
// },
},
},
maintainAspectRatio: false,
};
return <Line data={data} options={options} />;
};
export default Section2LineChartLast30Days;
|
#ifndef TSET_UNSORTED_FLEX_ARRAY_H
#define TSET_UNSORTED_FLEX_ARRAY_H
/** \file TSetUnsortedFlexArray.h
* \brief Deklarace typu SetUnsortedFlexArray a jeho API pro realizaci množiny pomocí nesetříděného flexibilního dynamicky alokovaného pole
* \author Petyovský
* \version 2024
* $Id: TSetUnsortedFlexArray.h 2711 2024-04-12 16:58:56Z petyovsky $
*/
#include <stdbool.h>
#include <stddef.h>
#include "TSetElement.h"
/** \defgroup TSetUnsortedFlexArray 2.1. SetUnsortedFlexArray
* \brief Deklarace typu SetUnsortedFlexArray a jeho funkcí (pro realizaci množiny pomocí nesetříděného flexibilního dynamicky alokovaného pole)
* \ingroup TSet
* \{
*/
/** \brief Deklarace privátního typu SetUnsortedFlexArray
*/
struct TSetUnsortedFlexArray;
//typedef size_t TSetUnsortedFlexArrayPos; ///< Definice typu pro pozici v SetUnsortedFlexArray
/** \brief Funkce zjišťující, zda flexibilní pole obsahuje element o zadané hodnotě
* \details Funkce (predikát) vracející \c bool hodnotu reprezentující test, zda flexibilní pole obsahuje zadanou hodnotu elementu.
* \param[in] aFlexArray Ukazatel na existující flexibilní pole
* \param[in] aValue Hodnota elementu hledaná v poli
* \param[in,out] aPosPtr Ukazatel na proměnnou určenou pro uložení pozice na hledaný element v poli (hodnota pozice je do paměti zapsána vždy tj. bez ohledu na výsledek hledání)
* \param[in] aSize Aktuální počet elementů ve flexibilním poli
* \retval -2 Pokud má pole nulovou délku, (\p *aPosPtr = 0)
* \retval -1 Pokud element nebyl v poli nalezen a hledaná hodnota elementu je menší, než hodnota na poslední platné pozici \p *aPosPtr
* \retval 0 Pokud element byl v poli nalezen a hledaná hodnota elementu je na pozici \p *aPosPtr
* \retval +1 Pokud element nebyl v poli nalezen a hledaná hodnota elementu je větší, než hodnota na poslední platné pozici \p *aPosPtr
* \note Pokud element s danou hodnotou nebyl nalezen, obsahuje \p *aPosPtr poslední platnou pozici, kde bylo hledání ukončeno.
* \attention Funkce ověřuje platnost obou ukazatelů \b pouze při překladu v režimu `Debug`, kdy pomocí `assert` hlásí běhovou chybu!
*/
int set_flex_array_search(const struct TSetUnsortedFlexArray *aFlexArray, TSetElement aValue, size_t *aPosPtr, size_t aSize);
/** \brief Vložení elementu do flexibilního pole
* \details Vkládá unikátní hodnotu elementu na konec flexibilního pole.
* \param[in,out] aFlexArrayPtr Ukazatel na místo v paměti, kde je ukazatel na flexibilní pole
* \param[in] aValue Hodnota elementu vkládaná do flexibilního pole
* \param[in] aSize Aktuální počet elementů ve flexibilním poli
* \return \c true pokud hodnota elementu nebyla v původním poli nalezena a pokud byla tato hodnota do pole následně úspěšně vložena
* \attention Funkce ověřuje platnost ukazatele \b pouze při překladu v režimu `Debug`, kdy pomocí `assert` hlásí běhovou chybu!
*/
bool set_flex_array_insert(struct TSetUnsortedFlexArray **aFlexArrayPtr, TSetElement aValue, size_t aSize);
/** \brief Odstranění elementu z flexibilního pole
* \details Odstraní hodnotu elementu z flexibilního pole.
* \param[in,out] aFlexArrayPtr Ukazatel na místo v paměti, kde je ukazatel na flexibilní pole
* \param[in] aValue Hodnota elementu odebíraného z flexibilního pole
* \param[in] aSize Aktuální počet elementů ve flexibilním poli
* \return \c true pokud hodnota elementu byla v původním poli nalezena a pokud byla tato hodnota z pole následně úspěšně odstraněna
* \attention Funkce ověřuje platnost ukazatele a parametru \p aSize \b pouze při překladu v režimu `Debug`, kdy pomocí `assert` hlásí běhovou chybu!
*/
bool set_flex_array_erase(struct TSetUnsortedFlexArray **aFlexArrayPtr, TSetElement aValue, size_t aSize);
/** \brief Deinicializace flexibilního pole
* \details Deinicializace a odalokace paměti flexibilního pole.
* \param[in,out] aFlexArray Ukazatel na flexibilní pole
*/
void set_flex_array_destroy(struct TSetUnsortedFlexArray *aFlexArray);
/** \brief Výpočet první platné pozice ve flexibilním poli
* \details Funkce vrací první pozici prvního platného elementu ve flexibilním poli.
* \param[in] aFlexArray Ukazatel na existující flexibilní pole
* \return Pozice (index) prvního platného elementu ve flexibilním poli
*/
size_t set_flex_array_begin_pos(const struct TSetUnsortedFlexArray *aFlexArray);
/** \brief Zjištění platnosti pozice ve flexibilním poli
* \details Funkce (predikát) vracející \c bool hodnotu definující platnost zadaného indexu do flexibilního pole.
* \param[in] aFlexArray Ukazatel na existující flexibilní pole
* \param[in] aPos Pozice (index) elementu ve flexibilním poli
* \param[in] aSize Aktuální počet elementů ve flexibilním poli
* \return \c true pokud je pozice platným indexem do flexibilního pole
*/
bool set_flex_array_is_valid_pos(const struct TSetUnsortedFlexArray *aFlexArray, size_t aPos, size_t aSize);
/** \brief Výpočet následující platné pozice ve flexibilním poli
* \details Výpočet pozice následujícího platného elementu ve flexibilním poli.
* \param[in] aFlexArray Ukazatel na existující flexibilní pole
* \param[in] aPos Pozice (index) aktuálního elementu ve flexibilním poli
* \return Pozice (index) následujícího platného elementu ve flexibilním poli
*/
size_t set_flex_array_next_pos(const struct TSetUnsortedFlexArray *aFlexArray, size_t aPos);
/** \brief Přečtení hodnoty elementu z flexibilního pole
* \details Přečte hodnotu elementu ze zadané pozice ve flexibilním poli.
* \param[in] aFlexArray Ukazatel na flexibilní pole
* \param[in] aPos Pozice (index) elementu ve flexibilním poli
* \return Hodnota elementu flexibilního pole na dané pozici.
* \attention Funkce ověřuje platnost ukazatele a parametru \p aSize \b pouze při překladu v režimu `Debug`, kdy pomocí `assert` hlásí běhovou chybu!
*/
TSetElement set_flex_array_value_at_pos(const struct TSetUnsortedFlexArray *aFlexArray, size_t aPos);
/** \} TSetUnsortedFlexArray */
#endif /* TSET_UNSORTED_FLEX_ARRAY_H */
|
package usrsql
object SQLLanguage {
sealed trait SQLExpression
enum SelectType:
case DISTINCT, ALL
// --------------------------------------------------
sealed trait SelectExpression
case object Star extends SelectExpression {
override def toString(): String = "*"
}
case class Columns(val columns: ColumnRef*) extends SelectExpression {
override def toString(): String =
columns.map(_.toString()).reduce(_ ++ ", " ++ _)
}
// --------------------------------------------------
sealed trait FromExpression
case class TableRef(val name: String, val original: Option[String])
extends FromExpression {
override def toString(): String =
if original.isDefined then s"(${original.get} AS $name)" else name
}
object TableRef {
def apply(o: String, n: String): TableRef = TableRef(n, Some(o))
def apply(n: String): TableRef = TableRef(n, None)
}
// or a SELECT
case class Join(val queries: FromExpression*) extends FromExpression {
override def toString(): String =
queries.map(_.toString()).reduce(_ ++ ", " ++ _)
}
// --------------------------------------------------
sealed trait Value
case class ColumnRef(val table: TableRef, val name: String) extends Value {
// possibly t1.* as well
override def toString(): String = s"$table.$name"
}
case class INT(val value: Int) extends Value
sealed trait Expression
// propositional
case object False extends Expression
case object True extends Expression
case class Not(val l: Expression) extends Expression {
override def toString(): String = s"!$l"
}
case class And(val l: Expression, val r: Expression) extends Expression {
override def toString(): String = s"($l /\\ $r)"
}
case class Or(val l: Expression, val r: Expression) extends Expression {
override def toString(): String = s"($l \\/ $r)"
}
case class Is(val l: Expression, val r: Expression) extends Expression {
override def toString(): String = s"($l is $r)"
}
extension (e: Expression) {
def unary_! = Not(e)
infix def /\(f: Expression) = And(e, f)
infix def \/(f: Expression) = Or(e, f)
infix def is(f: Expression) = Is(e, f)
}
// mathematical
case class Eq(val l: Value, val r: Value) extends Expression {
override def toString(): String = s"($l = $r)"
}
case class Leq(val l: Value, val r: Value) extends Expression {
override def toString(): String = s"($l <= $r)"
}
case class Lt(val l: Value, val r: Value) extends Expression {
override def toString(): String = s"($l < $r)"
}
extension (v: Value) {
infix def ===(w: Value) = Eq(v, w)
infix def <=(w: Value) = Leq(v, w)
infix def <(w: Value) = Lt(v, w)
}
case class Select(
val selectType: SelectType,
val selectExpression: SelectExpression,
val from: FromExpression,
val where: Expression,
val groupBy: Expression = True
) extends SQLExpression
with FromExpression {
override def toString(): String =
s"SELECT ${if selectType == SelectType.DISTINCT then "DISTINCT " else ""}" +
s"$selectExpression FROM $from WHERE $where${
if groupBy == True then "" else s" GROUP BY $groupBy"
}"
}
}
|
<div class="container">
<div class="row mt-4">
<div class="col-5 m-auto">
<h1>新規会員登録</h1>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= render "public/shared/error_messages", resource: resource %>
<div class='field'>
<%= f.label :名前(姓) %><br />
<%= f.text_field :last_name %>
</div>
<div class='field'>
<%= f.label :名前(名) %><br />
<%= f.text_field :first_name %>
</div>
<div class='field'>
<%= f.label :名前(セイ) %><br />
<%= f.text_field :last_name_kana %>
</div>
<div class='field'>
<%= f.label :名前(メイ) %><br />
<%= f.text_field :first_name_kana %>
</div>
<div class="field">
<%= f.label :メールアドレス %><br />
<%= f.email_field :email, autofocus: true, autocomplete: "email" %>
</div>
<div class='field'>
<%= f.label :郵便番号 %><br />
<%= f.text_field :post_code %>
</div>
<div class='field'>
<%= f.label :住所 %><br />
<%= f.text_field :address %>
</div>
<div class='field'>
<%= f.label :電話番号 %><br />
<%= f.text_field :phone_number %>
</div>
<div class="field">
<%= f.label :パスワード %>
<% if @minimum_password_length %>
<em>(<%= @minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "new-password" %>
</div>
<div class="field">
<%= f.label :パスワード(確認) %><br />
<%= f.password_field :password_confirmation, autocomplete: "new-password" %>
</div>
<div class="actions">
<%= f.submit "新規登録" %>
</div>
<% end %>
<div class="col-xs-12 mt-3">
<h4>
既に登録済みの方
</h4>
<div>
<%= link_to "こちら", new_customer_session_path %>からログインしてください。
</div>
</div>
</div>
</div>
</div>
|
package neko.convenient.nekoconvenientproduct8005.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.time.LocalDateTime;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
/**
* <p>
* spu信息表
* </p>
*
* @author NEKO
* @since 2023-04-01
*/
@Data
@Accessors(chain = true)
@TableName("spu_info")
public class SpuInfo implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.ASSIGN_ID)
private String spuId;
private String spuName;
private String spuDescription;
private String spuImage;
/**
* 分类id
*/
private Integer categoryId;
/**
* 分类名,冗余字段
*/
private String categoryName;
/**
* 商店id
*/
private String marketId;
private Boolean isPublish;
private Boolean isDelete;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
|
#include "main.h"
/**
* print_sign - Print the sign the number
* @n : checking the sign of the input
* Return: 1 if positive and 0 if zero if not then -1
*/
int print_sign(int n)
{
if (n > 0)
{
_putchar('+');
return (1);
}
else if (n == 0)
{
_putchar('0');
return (0);
}
else
{
_putchar('-');
return (-1);
}
}
|
package de.telran;
import java.util.Date;
public class User {
private String email;
private String password;
private String name;
private String lastName;
private Date birthDay;
public User(String email, String password, String name, String lastName, Date birthDay) {
this.email = email;
this.password = password;
this.name = name;
this.lastName = lastName;
this.birthDay = birthDay;
}
public User(String email, String password, String name) {
this.email = email;
this.password = password;
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static final class Builder {
private String email;
private String password;
private String name;
private String lastName;
private Date birthDay;
public Builder() {
}
public Builder withEmail(String email) {
this.email = email;
return this;
}
public Builder withPassword(String password) {
this.password = password;
return this;
}
public Builder withName(String name) {
this.name = name;
return this;
}
public Builder withLastName(String lastName) {
this.lastName = lastName;
return this;
}
public Builder withBirthDay(Date birthDay) {
this.birthDay = birthDay;
return this;
}
public User build() {
if (email ==null) {
throw new RuntimeException();
}
return new User(email, password, name, lastName, birthDay);
}
}
}
|
import React, { useEffect, useState } from 'react';
import LightControl from './components/lightcontrol';
import { getContactURL } from './credentials';
import { getAllLightInfo } from './fetch/GET';
export default function Main() {
const [lightState, setLightState] = useState({});
const [counter, setCounter] = useState(0)
const incrementCounter = () => {
const newCounter = counter + 1
setCounter(newCounter)
}
useEffect(() => {
const fetchLightState = async () => {
const lightState = await getAllLightInfo();
setLightState(lightState);
};
fetchLightState();
}, [counter]);
return (
<>
<div className='flex w-screen h-screen justify-center pt-10 bg-slate-900 text-white'>
<LightControl updated={incrementCounter} number={3} light={lightState['3']} />
<LightControl updated={incrementCounter} number={4} light={lightState['4']} />
<LightControl updated={incrementCounter} number={5} light={lightState['5']} />
</div>
</>
);
}
|
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import {RegisterComponent} from './register/register.component';
import { not } from '@angular/compiler/src/output/output_ast';
import { AllReciprComponent } from './all-recipr/all-recipr.component';
import { LogoutComponent } from './logout/logout.component';
import { AddRecipeComponent } from './add-recipe/add-recipe.component';
import { EditRecipeComponent } from './edit-recipe/edit-recipe.component';
const routes: Routes = [
{path:'login',component:LoginComponent},
{path:'logout',component:LogoutComponent},
{path:'all-recipe',component:AllReciprComponent},
{path:'register',component:RegisterComponent},
{path:'addRecipe',component:AddRecipeComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes,{useHash:true})],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
Graphical User Interface,GUI
GUI 开发包:
1、java.awt 包 – 主要提供字体/布局管理器
2、javax.swing 包[商业开发常用] – 主要提供各种组件(窗口/按钮/文本框)
3、java.awt.event 包 – 事件处理,后台功能的实现
javax.swing 包[商业开发常用]
Swing组件:
1、顶层容器:常用有JFrame,JDialog
JFrame:普通的窗口(绝大多数 Swing 图形界面程序使用 JFrame 作为顶层容器)
JDialog:对话框
2、中间容器:JPanel,JOptionPane,JScrollPane,JLayeredPane 等
JPanel (相当于div):一种轻量级面板容器组件(作为JFrame中间容器)
JScrollPane:带滚动条的,可以水平和垂直滚动的面板组件
JSplitPane:分隔面板
JTabbedPane:选项卡面板
JLayeredPane:层级面板
3、基本组件:JLabel,JButton,JTextField,JPasswordField,JRadioButton 等
JLabel:标签
JButton:按钮
JRadioButton:单选按钮
JCheckBox:复选框
JToggleButton:开关按钮
JTextField:文本框
JPasswordField:密码框
JTextArea:文本区域
JComboBox:下拉列表框
JList:列表
JProgressBar:进度条
JSlider:滑块
4、布局
FlowLayout 流式布局:从第一行开始,从左向右依次排列,碰到边界时转到下一行继续
构造函数:
FlowLayout() //使用默认参数
FlowLayout(int align) //设置对齐方式 LEFT、RIGHT、CENTER
FlowLayout(int align, int hgap, int vgap) //设置对齐方式、水平间距、垂直间距
BorderLayout 边界布局:将容器划分为EAST、WEST、SOUTH、NORTH、CENTER五个部分,每个部分可放置一个组件
构造函数:
BorderLayout() //使用默认参数
BorderLayout(int hgap, int vgap) //设置水平间距、垂直间距
放置组件时需指定位置:
container.add(Component comp, BorderLayout.SOUTH); //第二个参数是BorderLayout类的常量,指定组件位置
container.add(Component comp); //缺省位置时,默认为BorderLayout.CENTER,放在中间
一共5个位置,一个位置最多放1个组件,放置多个组件时,后放置的组件会覆盖之前放置的组件
GridLayout 网格布局:将容器划分为指定行数、列数的网格,每个格子的尺寸都相同,一个格子中放置一个组件,适合组件大小差不多的,比如放置计算器的按钮。
从左往右、从上往下依次放置
构造函数:
BorderLayout(int rows, int cols) //设置行数、列数
BorderLayout(int rows, int cols, int hgap, int vgap) //设置行数、列数、水平间距、垂直间距
BoxLayout:在一个方向上排列组件,从左往右水平排列,或者从上往下竖直排列
构造函数:
BoxLayout(container, axis); //第一个参数指定容器,第二个参数指定排列方向
BoxLayout.X_AXIS 水平排列,BoxLayout.Y_AXIS 竖直排列
X_AXIS:组件从左到右横向排列
Y_AXIS:组件从上到下纵向排列
LINE_AXIS:按照行的方式排列,可以从左到右也可以从右到左
PAGE_AXIS:按照页面的方式排列
CardLayout 卡片布局:将容器中的所有组件(通常是容器)当做一叠卡片,只显示一张卡片(一个组件)
构造函数:
CardLayout()
CardLayout(int hgap, int vgap) //设置卡片与容器(左右、上下)边界的的距离
使用步骤:
1、创建并指定布局管理器
CardLayout layout = new CardLayout(10,10);
container.setLayout(layout);
2、往容器中添加卡片
container.add("第一张", component1); //第一个参数是卡片名,String类型,唯一标识此张卡片,第二个参数是要添加的组件(卡片)
container.add("第二张", component2);
默认显示第一张卡片(最先添加的那张)
CardLayout对象可指定要显示的卡片:
first(container) //显示第一张卡片(最先放入的那张)。参数container是卡片所在的容器
last(container) //最后一张
previous(container) //前一张
next(container) //下一张
show(container, "卡片名") //特定的那张。第二个参数是添加卡片时指定的卡片名,唯一标识一张卡片
卡片是有顺序的,按照添加的顺序排列,最先添加的是第一张卡片
Java 2种方式管理布局:
使用布局管理器
绝对定位
绝对定位:
container.setLayout(null); //不使用布局管理器,清除默认的布局管理器
component1.setBounds(......); //手动为每个组件设置位置、尺寸
component2.setBounds(.....);
container.add(component1);
container.add(component2);
注:绝对定位很灵活、很简捷,可自由放置组件,但不跨平台。一般还是建议使用布局管理器
|
import $ from "jquery";
$(document).ready(function () {
document.querySelectorAll(".upload-input").forEach((inputElement) => {
const dropZoneElement = inputElement.closest(".custom-file");
dropZoneElement.addEventListener("click", (e) => {
inputElement.click();
});
inputElement.addEventListener("change", (e) => {
if (inputElement.files.length) {
updateThumbnail(dropZoneElement, inputElement.files[0]);
}
});
dropZoneElement.addEventListener("dragover", (e) => {
e.preventDefault();
dropZoneElement.classList.add("hover");
});
["dragleave", "dragend"].forEach((type) => {
dropZoneElement.addEventListener(type, (e) => {
dropZoneElement.classList.remove("hover");
});
});
dropZoneElement.addEventListener("drop", (e) => {
e.preventDefault();
if (e.dataTransfer.files.length) {
inputElement.files = e.dataTransfer.files;
updateThumbnail(dropZoneElement, e.dataTransfer.files[0]);
}
dropZoneElement.classList.remove("hover");
});
});
/**
* Updates the thumbnail on a drop zone element.
* @param {HTMLElement} dropZoneElement
* @param {File} file
*/
function updateThumbnail(dropZoneElement, file) {
let uploadFile = $(dropZoneElement).siblings('.upload-file');
let image = uploadFile.find('img');
let closeBtn = uploadFile.find('.upload-file__close');
const reader = new FileReader();
// Show thumbnail for image files
if (file.type.startsWith("image/")) {
reader.readAsDataURL(file);
reader.onload = () => {
$(dropZoneElement).addClass('close');
uploadFile.addClass('upload');
image.attr('src', reader.result);
closeBtn.on('click', () => {
$(dropZoneElement).removeClass('close');
uploadFile.removeClass('upload');
image.attr('src', '');
});
console.log(reader)
};
} else {
$(dropZoneElement).removeClass('close');
uploadFile.removeClass('upload');
}
}
});
|
use strict;
use warnings;
use Test::More;
use Test::Output;
use Path::Tiny ();
my $dir = Path::Tiny->tempdir;
# pod2usage calls exit
BEGIN {
no strict 'refs';
*{"CORE::GLOBAL::exit"} = sub { die "exit(@_)" };
}
use App::Wallflower;
plan tests => 4;
my $content = << "HTML";
<h1>Same</h1>
HTML
my $app = sub {
my $env = shift;
[
200,
[ 'Content-Type' => 'text/html', 'Content-Length' => length $content ],
[$content]
];
};
# quick test of new_with_options
my $awf;
stderr_like(
sub {
$awf = eval { App::Wallflower->new_with_options(); };
},
qr/^Missing required option: application/,
"expected error message for empty \@ARGV"
);
is( $awf, undef, "new_with_options() failed" );
# test App::Wallflower
$awf = App::Wallflower->new(
option => {
application => $app,
destination => $dir,
quiet => 1,
},
callbacks => [ sub { pass('callback after running the app') } ],
);
$awf->run;
my $result = do {
local $/;
my $file = Path::Tiny->new( $dir, 'index.html' );
open my $fh, '< :raw', $file or die "Can't open $file: $!";
<$fh>;
};
is( $result, $content, "read content from file" );
|
package com.prashant.smd.util;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.DecelerateInterpolator;
import androidx.core.content.ContextCompat;
import com.google.android.material.card.MaterialCardView;
import com.prashant.smd.R;
public class CProgressDialog {
private static Dialog dialog;
private static final int ANIMATION_DURATION = 600;
public static boolean isDialogShown = false;
public static void mShow(Context context) {
if (isDialogShown) {
return;
}
try {
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.cl_progress_bar_layout);
dialog.setCancelable(false);
} catch (Exception e) {
Log.e("Tag", "Error message", e);
return;
}
Window window = dialog.getWindow();
if (window != null) {
try {
window.setBackgroundDrawableResource(android.R.color.transparent);
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
window.setDimAmount(0.05f); // Adjust the transparency level as desired (0.0f - fully transparent, 1.0f - fully opaque)
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(context, R.color.white));
} catch (Exception e) {
Log.e("Tag", "Error message", e);
}
}
MaterialCardView dialogContainer = dialog.findViewById(R.id.dialog_container);
if (dialogContainer != null) {
dialogContainer.setAlpha(0f);
try {
dialog.show();
// Perform fade-in animation
dialogContainer.animate()
.alpha(1f)
.setDuration(ANIMATION_DURATION)
.setInterpolator(new DecelerateInterpolator())
.setListener(null);
isDialogShown = true;
} catch (Exception e) {
Log.e("Tag", "Error message", e);
dialog.dismiss();
dialog = null;
}
}
}
public static void mDismiss() {
if (dialog != null && dialog.isShowing()) {
MaterialCardView dialogContainer = dialog.findViewById(R.id.dialog_container);
if (dialogContainer != null) {
// Perform fade-out animation
dialogContainer.animate()
.alpha(0f)
.setDuration(ANIMATION_DURATION)
.setInterpolator(new DecelerateInterpolator())
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (dialog != null && dialog.isShowing()) {
try {
dialog.dismiss();
dialog = null;
} catch (Exception e) {
Log.e("Tag", "Error message", e);
}
}
}
});
}
}
isDialogShown = false;
}
}
|
#' @title Insert parameter and unit labels in different markup languges
#'
#' @description Given a user defined 'short-hand' code for a parameter, unit of parameter-unit combination this functions returns a label in the selected markup language.
#'
#' @details User defined 'short-hand' code for a parameters and units and their conversions into different markup languages are stored in a data file \code{data/definitions.csv}. Edit this file to add or adjust definitions. Short hand code can take any form, but may not contain R's reserved words (\url{http://cran.r-project.org/doc/manuals/r-release/R-lang.html#Reserved-words}). Parameter-unit combinations should be delimitated by a '.'
#'
#' @param sh User defined 'short-hand' code for a parameter, unit or 'parameter.unit' combination
#' @param output The desired markup languages to be returned
#' @param definitions A file path to a csv file containing definitions and markup conversions
#' @return A character string in the desired markup representing the requested label
#'
#' \code{uls} returns the quantity symbol
#'
#' @rdname insert_param_unit_labs
#' @examples
#' uls(sh="T", output="R")
#' uls(sh="T", output="md")
#' ulu("degC", output="R")
#' ulu("degC", output="md")
#' ul("T.degC", output="R")
#' ul("T.degC", output="md")
#' @export
uls <- function(sh, output="md", definitions=NULL){
if(is.null(definitions)){definitions <- system.file("extdata", package = "unitlabels")
definitions <- paste0(definitions,"/definitions.csv")}
definitions <- read.csv2(definitions, as.is = T)
if(grepl(".", sh, fixed=T)){sh <- strsplit(sh,".", fixed=T)[[1]][1]}
if(output=="R"){
out <-definitions[match(sh,definitions$sh.symbol),paste0("symbol.",output)]
out <- parse(text=out)
}
if(output=="md"){
out <-definitions[match(sh,definitions$sh.symbol),paste0("symbol.",output)]
#knitr::opts_chunk$set("results", "asis") <- "asis"
}
return(out)
}
#' @return \code{ulu} returns the quantity units in the specified markup
#' @rdname insert_param_unit_labs
#' @export
ulu <- function(sh, output="md", definitions=NULL){
if(is.null(definitions)){definitions <- system.file("extdata", package = "unitlabels")
definitions <- paste0(definitions,"/definitions.csv")}
definitions <- read.csv2(definitions, as.is = T)
if(grepl(".", sh, fixed=T)){sh <- strsplit(sh,".", fixed=T)[[1]][2]}
if(output=="R"){
out <-definitions[match(sh,definitions$sh.units),paste0("units.",output)]
out <- parse(text=out)
}
if(output=="md"){
out <-definitions[match(sh,definitions$sh.units),paste0("units.",output)]
#knitr::opts_chunk$set("results", "asis") <- "asis"
}
return(out)
}
#' @return \code{ul} returns the combined quantity-units in the specified markup
#' @rdname insert_param_unit_labs
#' @export
ul <- function(sh, output = "md", definitions = NULL) {
if (is.null(definitions)) {
definitions <- system.file("extdata", package = "unitlabels")
definitions <- paste0(definitions,"/definitions.csv")
}
definitions <- read.csv2(definitions, as.is = T)
sh <- strsplit(sh,"[.]")
get.lab <- function(sh,output) {
sy <-
definitions[match(sh[1],definitions$sh.symbol),paste0("symbol.",output)]
if(length(sh)==1){
out <- sy
if (output == "R") {
out <- parse(text = sy)
}
}else{
un <-
definitions[match(sh[2],definitions$sh.units),paste0("units.",output)]
if (output == "R") {
out <- parse(text = paste0(sy,"~(", un, ")"))
}
if (output == "md") {
out <- paste0(sy," (", un, ")")
}
}
return(out)
}
out <- unlist(lapply(sh, get.lab, output = output))
if (output == "R") {
out <- parse(text = out)
}
return(out)
}
|
package com.jyx.healthsys.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jyx.healthsys.entity.Role;
import com.jyx.healthsys.entity.RoleMenu;
import com.jyx.healthsys.mapper.RoleMapper;
import com.jyx.healthsys.mapper.RoleMenuMapper;
import com.jyx.healthsys.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author 金义雄
* @since 2023-02-23
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
@Resource
private RoleMenuMapper roleMenuMapper;
// 新增角色
@Override
@Transactional
public boolean addRole(Role role) {
LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(Role::getRoleName, role.getRoleName());
int count = this.baseMapper.selectCount(wrapper).intValue();
if (count>0){
return false;
}else{
this.baseMapper.insert(role);
// 写入角色菜单关系表
if (role.getMenuIdList() != null) {
for (Integer menuId : role.getMenuIdList()) {
roleMenuMapper.insert(new RoleMenu(null, role.getRoleId(), menuId));
}
}
}
return true;
}
// 根据角色ID查询角色信息
@Override
public Role getRoleById(Integer id) {
// 从角色表中获取角色信息
Role role = this.baseMapper.selectById(id);
// 获取角色关联的菜单ID列表
List<Integer> menuIdList = roleMenuMapper.getMenuIdListByRoleId(id);
// 将菜单ID列表设置到角色对象中
role.setMenuIdList(menuIdList);
return role;
}
// 更新角色信息
@Override
@Transactional
public void updateRole(Role role) {
// 修改角色表
this.baseMapper.updateById(role);
// 删除原有的权限
LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(RoleMenu::getRoleId, role.getRoleId());
roleMenuMapper.delete(wrapper);
// 新增角色的权限
if (role.getMenuIdList() != null) {
for (Integer menuId : role.getMenuIdList()) {
// 添加角色与菜单关系
roleMenuMapper.insert(new RoleMenu(null, role.getRoleId(), menuId));
}
}
}
@Override
@Transactional
public void deleteRoleById(Integer id) {
this.baseMapper.deleteById(id);
// 删除角色的权限
LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(RoleMenu::getRoleId, id);
roleMenuMapper.delete(wrapper);
}
}
|
export class SlugifyService {
private static readonly convert = new Map<string, string>([
["à", "a"],
["â", "a"],
["ä", "a"],
["é", "e"],
["è", "e"],
["ê", "e"],
["ë", "e"],
["î", "i"],
["ï", "i"],
["ô", "o"],
["ö", "o"],
["ò", "o"],
["û", "u"],
["ü", "u"],
["ù", "u"],
["ç", "c"],
["œ", "oe"],
["æ", "ae"],
["ø", "o"],
]);
private constructor() {}
static apply(sentence: string): string {
const SLUG_SEPARATOR = "-";
const spacesOrApostrophes = new RegExp("[ ']+", "gm");
const nonStandardChar = new RegExp("[^A-Za-z0-9]", "gm");
return sentence
.toLowerCase()
.replace(nonStandardChar, (char) => this.convert.get(char) ?? char)
.replace(spacesOrApostrophes, SLUG_SEPARATOR);
}
static applyOnOptional(sentence?: string): string | undefined {
return sentence ? this.apply(sentence) : undefined;
}
}
|
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
namespace boyutTaskAppAPI.Applicaton.Features.Commands.Auth;
public class VerifyCodeCommandHandler : IRequestHandler<VerifyCodeCommandRequest, bool>
{
private readonly IDistributedCache _distributedCache;
public VerifyCodeCommandHandler(IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
public async Task<bool> Handle(VerifyCodeCommandRequest request, CancellationToken cancellationToken)
{
try
{
if (string.IsNullOrWhiteSpace(request.PhoneNumber))
throw new Exception("PhoneNumber cannot be null");
var cachedCode = await _distributedCache.GetStringAsync(GetValidateCacheKey(request.PhoneNumber),
token: cancellationToken);
if (cachedCode == null)
{
// Kod bulunamadı
return false;
}
if (request.Code != cachedCode)
{
// Doğrulama kodu geçersiz
throw new Exception("Your verify code is not valid: " + request.Code);
}
// Başarılı doğrulama, önbellekten kaldırılıyor
await _distributedCache.RemoveAsync(GetValidateCacheKey(request.PhoneNumber), cancellationToken);
// İşlem başarılı
return true;
}
catch (Exception e)
{
throw new Exception("An error occurred during the verification process");
}
}
private static string GetValidateCacheKey(string phone)
{
return $"VALIDATION_KEY:{phone}";
}
}
|
namespace FoodFolio.WebApi.Entities;
public static class Seeder
{
public static void Seed(this WebApplication webApp)
{
using (var scope = webApp.Services.CreateScope())
{
using (var context = scope.ServiceProvider.GetRequiredService<FoodFolioDbContext>())
{
try
{
if (context.Database.CanConnect())
{
if (!context.Roles.Any())
{
var roles = CreateRoles();
context.Roles.AddRange(roles);
context.SaveChanges();
}
if (!context.Users.Any())
{
var adminRole = context.Roles.FirstOrDefault(r => r.Name == "Admin");
var users = CreateAdminUser(adminRole);
context.Users.AddRange(users);
context.SaveChanges();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
// throw;
}
}
}
}
private static IEnumerable<User> CreateAdminUser(Role role)
{
return new List<User>()
{
new User()
{
Email = "[email protected]",
FirstName = "admin",
LastName = "Admian",
PasswordHash = "", //TODO: Dodać
LastPasswordHash = "",
Role = role
}
};
}
private static IEnumerable<Role> CreateRoles()
{
return new List<Role>()
{
new Role()
{
Name = "Admin",
Description = "Admin user"
},
new Role()
{
Name = "User",
Description = "Default user"
}
};
}
}
|
import { useState } from "react";
import headerLogo from "../../assets/prfile.png";
import burguerOpen from "../../assets/hamburguer-vector.png";
import burguerClose from "../../assets/close-button.png";
import styleFor from "./header.module.css";
export default function Header() {
const [showButton, setWhichButton] = useState(false);
const handleChangeBtn = () => {
setWhichButton(!showButton);
};
const Links = () => {
const links = [
{ direction: "#about", siteId: "About" },
{ direction: "#services", siteId: "Servicios" },
{ direction: "#portfolio", siteId: "Portfolio" },
{ direction: "#contact", siteId: "Contacto" },
];
const handleLink = () => {
setWhichButton(false);
};
return (
<>
{links.map((l, index) => {
return (
<a key={index} href={l.direction} onClick={handleLink}>
{l.siteId}
</a>
);
})}
</>
);
};
return (
<>
<header className={`headerr ${styleFor["header"]}`}>
<div>
<a href="#">
<img src={headerLogo} className={styleFor["header-logo"]} />
</a>
</div>
<div className={styleFor["menu-desktop"]}>
<Links />
</div>
<div className={styleFor["menu-burger"]}>
{!showButton ? (
<button onClick={handleChangeBtn}>
<img
src={burguerOpen}
alt="menu"
className={styleFor["open-button-img"]}
/>
</button>
) : (
<>
<div className={styleFor["nav-menu"]}>
<div className={styleFor["nav-div_button"]}>
<button onClick={handleChangeBtn}>
<img
src={burguerClose}
alt="menu"
className={styleFor["close-button-img"]}
/>
</button>
</div>
<div className={styleFor["nav-options"]}>
<Links />
</div>
</div>
</>
)}
</div>
</header>
</>
);
}
|
use character::*;
pub fn wyrm() -> CharacterProfile {
CharacterProfile {
name: String::from("wyrm"),
abilities: Abilities::new(16, 4, 12),
category: CharacterCategory::Creature,
size: SizeCategory::Large,
intelligence: IntelligenceCategory::AnimalIntelligence,
traits: vec![Trait::Frightening, Trait::LandingFlyer],
natural_armour: Some(("scales", 2)),
natural_weapons: vec![
(
"bite, talons, & tail",
Weapon::new(Some(Die::D8), Vec::new()),
),
(
"fire breath",
Weapon::new(
Some(Die::D6),
vec![
WeaponKeyword::Range(2),
WeaponKeyword::Blast,
WeaponKeyword::FireDamage,
WeaponKeyword::UsageLimit("once per stretch"),
],
),
),
],
description: Some(String::from(
"A gigantic lizard-like winged creature, capable of breathing fire.",
)),
..Default::default()
}
}
pub fn troll() -> CharacterProfile {
CharacterProfile {
name: String::from("troll"),
abilities: Abilities::new(12, 4, 4),
category: CharacterCategory::Creature,
size: SizeCategory::Large,
intelligence: IntelligenceCategory::HumanIntelligence,
traits: vec![Trait::Frightening, Trait::Regeneration],
natural_armour: Some(("thick skin", 1)),
natural_weapons: Vec::new(),
assets: vec![Asset::from(Item::new(
Some("huge club"),
ItemKind::SimpleHugeWeapon,
Some("an extremely large club, impossible to use for a medium-sized character"),
))],
description: Some(String::from(
"A large, brutish, humanoid monster, capable of quick regeneration. Lives in swamps \
and feasts on rotten meat.",
)),
..Default::default()
}
}
|
%---------------------------------------------------------------------------%
% vim: ts=4 sw=4 et ft=mercury
%---------------------------------------------------------------------------%
%
% This is an interleaved version of reverse and length.
% Tests if we can introduce more than one accumulator.
%
:- module inter.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list.
:- import_module int.
main(!IO) :-
io.write_string("rl: ", !IO),
rl([1, 10, 100], Length, Reverse),
io.write(Length, !IO),
io.write_string(" ", !IO),
io.write_line(Reverse, !IO).
:- pred rl(list(T)::in, int::out, list(T)::out) is det.
rl(X, L, R) :-
X = [],
L = 0,
R = [].
rl(X, L, R) :-
X = [H | T],
rl(T, L0, R0),
L = L0 + 1,
Tmp = [H],
append(R0, Tmp, R).
|
const originUrl = window.location.origin;
document.getElementById('productionSelector').addEventListener('change', getTemplates);
async function getProductions() {
const url = `${originUrl}/api/productions`;
const productions = await fetchData(url, 'GET',null);
const productionSelector = document.getElementById('productionSelector');
productions.forEach(function(production) {
var option = document.createElement('option');
option.value = production.uid;
option.text = production.name;
productionSelector.add(option);
});
}
async function getTemplates() {
const productionUid = document.getElementById('productionSelector').value;
if (productionUid === "") return;
const url = `${originUrl}/api/templates/${productionUid}`;
const templates = await fetchData(url, 'GET', null);
const templatesContainer = document.getElementById('templatesContainer');
templatesContainer.innerHTML = '';
templates.forEach(function (template) {
const el = createTemplateHtml(template);
el.addEventListener('click', () => navigate(el.id));
templatesContainer.appendChild(el);
});
}
function createTemplateHtml(template){
const container = document.createElement('div'); // Create a temporary container
if(template.icon){
container.innerHTML = `
<div id=${template.uid} class="col-1 themed-grid-col">
<img src='data:image/png;base64,${template.icon}' alt='Template Icon'>
</div>`;
} else {
container.innerHTML = `
<div id=${template.uid} class="col-1 themed-grid-col">
${template.name}
</div>`;
}
// Return the first child of the container
return container.firstElementChild;
}
async function fetchData(url, method, msg) {
try {
const response = await fetch(url, {
method,
headers: {
'Content-Type': 'text/plain', // Adjust content type as needed
},
body: msg,
});
if (response.ok) {
const data = await response.json();
return data;
} else {
console.error(`Failed to ${method} data at URL: ${url}`);
}
} catch (error) {
console.error(`Error while fetching data at URL: ${url}`, error);
}
}
function navigate(templateId){
const url = `${originUrl}/templates/${templateId}.html`;
window.location.href = url;
}
getProductions();
|
import React, { useState } from 'react'
import { useNavigate } from 'react-router';
import { app, db } from '../redux/firebase';
import { createUserWithEmailAndPassword, getAuth, updateProfile } from 'firebase/auth';
import { Nav } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import { doc, setDoc, updateDoc } from 'firebase/firestore';
import { getCart } from '../redux/Action';
import { useDispatch } from 'react-redux';
const SignUp = () => {
const auth = getAuth(app)
const dispatch = useDispatch()
const initial = {
username: '',
email: '',
password: '',
}
const [input, setInput] = useState(initial)
const [errors, setErrors] = useState({})
const handleChange = (e) => {
const { name, value } = e.target;
setInput({ ...input, [name]: value });
}
const navigate = useNavigate()
function validate() {
let error = {}
if (input.username.length < 1) {
error.username = 'Enter Your Username'
}
if (input.email.length < 1) {
error.email = 'Enter Your Email'
}
if (input.password.length < 1) {
error.password = 'Enter Your Password'
}
return error;
}
const handleSubmit = async (e) => {
e.preventDefault()
const checkErrors = validate()
if (Object.keys(checkErrors).length > 0) {
setErrors(checkErrors)
} else {
await createUserWithEmailAndPassword(auth, input.email, input.password)
.then((userCredential) => {
console.log(userCredential)
updateProfile(auth.currentUser, {
displayName: input.username
}).then(async () => {
await setDoc(doc(db, "UserCart", auth.currentUser.uid), { cart: [] });
dispatch(getCart([]))
}).catch((error) => {
console.log(error)
});
})
navigate('/login')
setErrors({})
setInput(initial)
}
}
return (
<div className="form-container mx-auto mt-4">
<p className="title">Welcome</p>
<form className="form" onSubmit={(e) => handleSubmit(e)}>
<input type="text" className="input" name='username' placeholder="Username" value={input.username} onChange={handleChange} />
{errors.username && <span>{errors.username}</span>}
<input type="email" className="input" name='email' placeholder="Email" value={input.email} onChange={handleChange} />
{errors.email && <span>{errors.email}</span>}
<input type="password" className="input" name='password' placeholder="Password" value={input.password} onChange={handleChange} />
{errors.password && <span>{errors.password}</span>}
<button className="form-btn">Sign up</button>
</form>
<p className="sign-up-label d-flex">
Already have an account?<Nav.Link as={Link} to="/" className="sign-up-link text-success">Login</Nav.Link>
</p>
</div>
)
}
export default SignUp
|
<?php
session_start();
// Include config file
require_once "surveyDB.php";
// Check if the user is logged in and is an admin
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || !isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
header('Location: login.php');
exit;
}
// Check if survey_id is set in the query parameter
if (!isset($_GET['survey_id'])) {
die("Survey ID not specified.");
}
// Get the survey ID from the query parameter
$survey_id = intval($_GET['survey_id']);
// Fetch survey details
function fetchSurveyDetails($mysqli, $survey_id) {
$sql = "SELECT q.id AS question_id, q.text AS question_text, a.id AS answer_id, a.text AS answer_text,
(SELECT COUNT(*) FROM Responses r WHERE r.answer_id = a.id) AS answer_count
FROM Questions q
JOIN Answers a ON q.id = a.question_id
WHERE q.survey_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $survey_id);
$stmt->execute();
$result = $stmt->get_result();
$details = [];
while ($row = $result->fetch_assoc()) {
$details[] = $row;
}
$stmt->close();
return $details;
}
$survey_details = fetchSurveyDetails($mysqli, $survey_id);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Survey Details</title>
<link rel="stylesheet" href="css/styles.css"> <!-- Ensure this path is correct -->
<style>
.question-item {
margin-bottom: 20px;
}
.answer-item {
margin-left: 20px;
}
</style>
</head>
<body>
<div class="container">
<h1>Survey Details</h1>
<div class="scrollable-container">
<?php
$current_question_id = 0;
foreach ($survey_details as $detail):
if ($current_question_id != $detail['question_id']):
if ($current_question_id != 0):
echo "</div>";
endif;
$current_question_id = $detail['question_id'];
?>
<div class="question-item">
<strong><?php echo htmlspecialchars($detail['question_text']); ?></strong>
<?php endif; ?>
<div class="answer-item">
<?php echo htmlspecialchars($detail['answer_text']); ?> - <?php echo $detail['answer_count']; ?> selections
</div>
<?php endforeach; ?>
</div>
</div>
<button onclick="window.history.back()" class="btn">Back</button>
</div>
</body>
</html>
|
<!-- prettier-ignore -->
# vue-lazuload-img-plugin
vue loader 插件 —— 图片懒加载以及自动压缩(包括背景图、富文本)
> 🌟🌟🌟 **老项目优化利器, 无需动任何业务代码** 🌟🌟🌟,如`src`批量改成`data-src`之类的操作,
> <br />webpack 引入本插件即可实现全局图片性能优化,具体操作详见下文
压缩技术支持来自 —— [《阿里云 oss-图片高级压缩》](https://help.aliyun.com/document_detail/135444.html)
1. **有设置固定宽高时**`(如 <img width="200" /> )`
判断 图片过小时`minSize=64`不压缩,如 icon 图标
<br />判断 图片过大时`maxSize=16393`不压缩,oss 不支持压缩高/宽超过 16383px
2. **未设置固定高宽时**`(利用图片自身natural高宽占位渲染,常见于富文本)`
先 **渐进式加载**(1%质量图`q_1` ) 以获取占位宽高,并添加 `onload` 事件
<br /> 在 `onload` 事件中继续执行上述**【操作 1 】**
<img src="https://github.com/Learn-form-Zakas/vue-lazyload-img-plugin/blob/master/xmind/前端性能优化-图片.png"/>
## Install <a href="https://npmjs.org/package/vue-lazyload-img-plugin"><img alt="npm version" src="http://img.shields.io/npm/v/vue-lazyload-img-plugin.svg?style=flat-square"></a> <a href="https://npmjs.org/package/vue-lazyload-img-plugin"><img alt="npm dm" src="http://img.shields.io/npm/dm/vue-lazyload-img-plugin.svg?style=flat-square"></a>
```bash
npm i vue-lazyload-img-plugin
```
# 1. Vue 项目使用步骤
## 第一步 vue.config.js 配置
> 原理:利用 loader 将`<img src>`修改为`<img src='{thumbnail src}' data-src='{origin src}'>`
```js
// vue.config.js
const lazyloadImgVueConfig = require('vue-lazyload-img-plugin').LazyloadImgVueConfig
// ...
chainWebpack(config) {
// ...
lazyloadImgVueConfig(config,options);//options同webpack config
}
```
### 如果没有`vue.config.js`而是用的`webpack.config.js`配置
```js
// webpack config
const lazyloadImgWebpackLoader =
require("vue-lazyload-img-plugin").LazyloadImgWebpackLoader;
{
resolve: {
alias: {
'@': rootPath('src'),
vue$: 'vue/dist/vue.esm.js',
images: rootPath('src/assets/images'),
},
},
module: {
rules: [
lazyloadImgWebpackLoader(options:{alias:['@','vue$','images']}), //详见目录##config options
// 如果有配'vue-loader'请注释掉代码,否则会有loader重复冲突
// {
// test: /\.vue$/,
// loader: 'vue-loader',
// },
];
}
}
```
### config options
| 属性 | 描述 | 默认值 |
| ----- | ---------------- | ------ |
| alias | 图片路径资源别名 | [] |
---
## 第二步 Vue.use(plugin) 安装插件
> 原理:利用 plugin 在 vue 组件的 beforeCreate 阶段监听 img dom 的生成和可视区域监听
> 当 img 可视时,再将 origin 资源加载到当前 img 上
<b>`/main.js`文件</b>
```js
import { LazyLoadImgPlugin } from "vue-lazyload-img-plugin";
Vue.use(LazyLoadImgPlugin, pluginOptions); // options见目录#plugin options
```
### plugin options
| 属性 | 描述 | 默认值 |
| ------- | ---------------------------------- | ------------------- |
| host | **正则**匹配需要被应用的图床服务器 | 无,需必填 |
| reg | **正则**匹配需要被引用的图片类型 | `.jpg\|.jpeg\|.png` |
| maxSize | 接受压缩的最大图片尺寸 | 16383 |
| minSize | 接受压缩的最小图片尺寸 | 64 |
> `maxSize`说明: Maximum width and height allowed is 16383 pixels for converting webp.
---
# 2. html 标签属性补充
> 可在 html 标签内添加额外配置属性
| 属性 | 描述 | 默认值 |
| ------------- | ---------------------------------------------- | ------- |
| v-no-lazyload | 不接受懒加载 | `false` |
| v-no-compress | 不接受图片压缩 | `false` |
| v-no-compile | 在编译期间禁止改动,即不接受任何处理(vue 项目) | `false` |
```html
<!-- 图片不接受懒加载 -->
<img src="" v-no-lazyload />
<!-- 图片不接受压缩 -->
<img src="" v-no-compress />
<!-- 背景图片不接受懒加载和压缩 -->
<div style="background:url('')" v-no-lazyload v-no-compress></div>
<!-- 禁止本插件对此标签的任何改动 -->
<img src="" v-no-compile />
<!-- 只支持一层标签,暂不支持为父标签设置后影响子标签的行为 -->
<div style="background:url('')" v-no-compile></div>
<!-- 🌟 可通过主动添加query参数覆盖动态压缩参数 -->
<img
src="http://image-demo.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/resize,p_50"
/>
<!-- 富文本内所有图片不接受懒加载 -->
<div v-html="..." v-no-lazyload></div>
<!-- 富文本内所有图片和背景图都不支持压缩 -->
<div v-html="..." v-no-compress></div>
<!-- 禁止本插件对富文本有任何改动 -->
<div v-html="..." v-no-compile></div>
```
# 3. tips
1. 存在 DOM 操作时,请在`$nextTick`回调后执行
```js
mounted(){
this.$nextTick(() => {
// DOM操作
...
});
}
```
2. 图片源资源地址被存储在`data-origin-src`中
```js
// 可从这里获取源地址
img.dataset.originSrc;
```
3. 尽量做到预先指定图片的尺寸`<img width="" height="" />`
- 本插件可以减少一次服务器请求
- 可以减少重排(回流)可能造成的卡顿
4. 记得开启DNS预解析
```html
预解析CDN域名
<link rel="dns-prefetch" href="//img.alicdn.com">
强制开启HTTPS下的DNS预解析
<meta http-equiv="x-dns-prefetch-control" content="on">
```
|
<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<html lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<title>Filmy</title>
<style>
table{
font-family: Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 50%;
margin-left: auto;
margin-right: auto;
}
th, td{
border: 1px solid #ddd;
padding: 8px;
}
body{
text-align: center;
font-family: sans-serif;
background-color: #eee;
}
</style>
</head>
<body>
<h1>Wybierz datę aby wygenerować wynagrodzenia</h1>
<form action="/payroll-list" method="GET">
<label for="startDate">Od:</label>
<input type="date" id="startDate" name="startDate" min="2023-10-01" value="2023-10-01">
<br>
<br>
<label for="endDate">Do:</label>
<input type="date" id="endDate" name="endDate" min="2023-11-01" value="2023-11-01">
<br>
<br>
<button class="button" type="submit">Wyślij</button>
</form>
<c:if test="${not empty payrolls}">
<h2>Wypłaty</h2>
<table>
<caption>Wynagrodzenia w podanym terminie</caption>
<thead>
<tr>
<th>Imię i nazwisko pracownika</th>
<th>Wynagrodzenie</th>
</tr>
</thead>
<tbody>
<c:forEach items="${payrolls}" var="p">
<tr>
<td><c:out value="${p.employeeFirstName} ${p.employeeLastName}"/></td>
<td>${p.payroll}zł</td>
</tr>
</c:forEach>
</tbody>
</table>
</c:if>
<br>
<br>
<a href="/">strona główna</a>
</body>
</html>
|
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update]
before_action :require_user, except: [:new, :create]
before_action :require_same_user, only: [:show, :edit, :update]
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:notice] = "You are now registered!"
session[:user_slug] = @user.slug
redirect_to root_path
else
render :new
end
end
def show
end
def edit
end
def update
if @user.update(user_params)
flash[:notice] = "Your profile has been updated."
redirect_to user_path(@user)
else
render :edit
end
end
private
def user_params
params.require(:user).permit(:username, :email, :password, :timezone)
end
def set_user
@user = User.find_by slug: params[:id]
end
def require_same_user
if current_user != @user
access_denied
end
end
end
|
import React, { useState } from 'react';
import clsx from 'clsx';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import Drawer from '@material-ui/core/Drawer';
import CssBaseline from '@material-ui/core/CssBaseline';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import List from '@material-ui/core/List';
import Typography from '@material-ui/core/Typography';
import Divider from '@material-ui/core/Divider';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import ChevronLeftIcon from '@material-ui/icons/ChevronLeft';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import AccountCircleIcon from '@material-ui/icons/AccountCircle';
import { HashRouter as Router, Route, Switch, Redirect, BrowserRouter } from 'react-router-dom';
import { AppointmentOverview, ContentOverview, MembersOverview, FileUpload, CourseOverview } from '../pages';
import {CreateAppointment, UpdateAppointment} from '../components'
const drawerWidth = 240;
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
},
appBar: {
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
},
appBarShift: {
width: `calc(100% - ${drawerWidth}px)`,
marginLeft: drawerWidth,
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
},
menuButton: {
marginRight: theme.spacing(2),
},
hide: {
display: 'none',
},
drawer: {
width: drawerWidth,
flexShrink: 0,
},
drawerPaper: {
width: drawerWidth,
},
drawerHeader: {
display: 'flex',
alignItems: 'center',
padding: theme.spacing(0, 1),
// necessary for content to be below app bar
...theme.mixins.toolbar,
justifyContent: 'flex-end',
},
content: {
flexGrow: 1,
padding: theme.spacing(3),
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
marginLeft: -drawerWidth,
},
contentShift: {
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
marginLeft: 0,
},
menuTitle: {
flexGrow: 1,
},
profileButton: {
fontSize: '40px',
},
profileDiv: {
alignItems: 'center',
display: 'flex',
flexDirection: 'column',
'& p': {
marginTop: 0,
marginBottom: 0,
alignItems: 'center',
fontSize: '14px',
}
}
}));
function Menu(props) {
const classes = useStyles();
const theme = useTheme();
const [open, setOpen] = useState(false);
const handleDrawerOpen = () => {
setOpen(true);
};
const handleDrawerClose = () => {
setOpen(false);
};
const linkStyle = {
color: "white",
textDecoration: "none",
}
if (props.loggedUser === null || props.loggedUser === undefined) {
document.location.href = "https://sgse2021-ilias.westeurope.cloudapp.azure.com/users/login";
}
const renderAdminUserItems = (role) => {
if (role === 2) {
return <div>
<ListItem component="a" href="https://sgse2021-ilias.westeurope.cloudapp.azure.com/users/students" button key={'Studierende'}>
<ListItemText primary={'Studierende'} />
</ListItem>
<ListItem component="a" href="https://sgse2021-ilias.westeurope.cloudapp.azure.com/users/lecturers" button key={'Lehrende'}>
<ListItemText primary={'Lehrende'} />
</ListItem>
</div>
}
}
const getCourseOrResourceMenuItem = (role) => {
if(role === 2){
return <div>
<ListItem component="a" href="https://sgse2021-ilias.westeurope.cloudapp.azure.com/courses/courses/" button key={'Kurse'}>
<ListItemText primary={'Kurse'} />
</ListItem>
<ListItem component="a" href="https://sgse2021-ilias.westeurope.cloudapp.azure.com/courses/appointments/" button key={'Appointments'}>
<ListItemText primary={'Termine'} />
</ListItem>
</div>
} else {
return <ListItem component="a" href="https://sgse2021-ilias.westeurope.cloudapp.azure.com/resources/" button key={'Kurse'}>
<ListItemText primary={'Kurse'} />
</ListItem>
}
}
return (
<div className={classes.root}>
<CssBaseline />
<AppBar
position="fixed"
className={clsx(classes.appBar, {
[classes.appBarShift]: open,
})}
>
<Toolbar>
<IconButton
color="inherit"
aria-label="open drawer"
onClick={handleDrawerOpen}
edge="start"
className={clsx(classes.menuButton, open && classes.hide)}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" noWrap className={classes.menuTitle}>
<a href="/resources/" style={linkStyle}>Kurse</a>
</Typography>
<div className={classes.profileDiv}>
<IconButton href="/users/settings"><AccountCircleIcon className={classes.profileButton}></AccountCircleIcon></IconButton>
<p>{props.loggedUser.firstname + " " + props.loggedUser.lastname}</p>
</div>
</Toolbar>
</AppBar>
<Drawer
className={classes.drawer}
variant="persistent"
anchor="left"
open={open}
classes={{
paper: classes.drawerPaper,
}}
>
<div className={classes.drawerHeader}>
<IconButton onClick={handleDrawerClose}>
{theme.direction === 'ltr' ? <ChevronLeftIcon /> : <ChevronRightIcon />}
</IconButton>
</div>
<Divider />
<Router>
<List>
<ListItem component="a" href="https://sgse2021-ilias.westeurope.cloudapp.azure.com/users/" button key={'Startseite'}>
<ListItemText primary={'Startseite'} />
</ListItem>
<ListItem component="a" href="https://sgse2021-ilias.westeurope.cloudapp.azure.com/messages/" button key={'Nachrichten'}>
<ListItemText primary={'Nachrichten'} />
</ListItem>
{getCourseOrResourceMenuItem(props.loggedUser.role)}
<ListItem component="a" href="https://sgse2021-ilias.westeurope.cloudapp.azure.com/exams/" button key={'Prüfungen'}>
<ListItemText primary={'Prüfungen'} />
</ListItem>
{
renderAdminUserItems(props.loggedUser.role)
}
<ListItem component="a" href="https://sgse2021-ilias.westeurope.cloudapp.azure.com/booking/" button key={'Raumbelegung'}>
<ListItemText primary={'Raumbelegung'} />
</ListItem>
<ListItem component="a" href="https://sgse2021-ilias.westeurope.cloudapp.azure.com/users/logout" button key={'Ausloggen'}>
<ListItemText primary={'Ausloggen'} />
</ListItem>
</List>
</Router>
</Drawer>
<main className={clsx(classes.content, {
[classes.contentShift]: open,})}>
<div className={classes.drawerHeader} />
<Router basename="/resources">
<Switch>
<Route path="/" exact component={CourseOverview}/>
<Route path={`/course/:id/appointments`} exact component={AppointmentOverview} />
<Route path={`/course/:id/appointments/create`} exact component={CreateAppointment} />
<Route path={`/course/:id/appointments/update/:apId`} exact component={UpdateAppointment} />
<Route path={`/course/:id/members`} exact component={MembersOverview} />
<Route path={`/course/:id/`} exact component={ContentOverview} />
<Route path={`/course/:id/upload`} exact component={FileUpload} />
</Switch>
</Router>
</main>
</div>
)
}
export default Menu;
|
package com.hsa.pakcables.database.copy
//
//import android.app.Application
//import android.content.Context
//import android.content.SharedPreferences
//import androidx.datastore.core.DataStore
//import androidx.datastore.preferences.core.Preferences
//import androidx.datastore.preferences.core.stringPreferencesKey
//import androidx.datastore.preferences.preferencesDataStore
//import dagger.hilt.android.HiltAndroidApp
//
//import com.google.gson.Gson
//import com.ssasoft.korlezz.Service.DataPostService
//import com.ssasoft.korlezz.models.ProfileModel
//import com.ssasoft.korlezz.db.DataRepository
//import com.ssasoft.korlezz.db.KlozerzDB
//
//@HiltAndroidApp
//class KlozerzApplication: Application(){
//
//// /**
//// * Create the singleton [ImageLoader].
//// * This is used by [rememberImagePainter] to load images in the app.
//// */
//// override fun newImageLoader(): ImageLoader {
//// return ImageLoader.Builder(this)
//// .componentRegistry {
//// add(UnsplashSizingInterceptor)
//// }
//// .build()
//// }
//
//
// private val Context.userPreferencesDataStore: DataStore<Preferences> by preferencesDataStore(
// name = "user"
// )
// private val USER_EMAIL = stringPreferencesKey("user_email")
// private lateinit var me: KlozerzApplication
// override fun onCreate() {
// super.onCreate()
// me = this
// KlozerzDB.init(applicationContext)
// if(instance==null){
// instance=this
// }
// DataRepository.init(getDatabase()!!)
// val dataPostService = DataPostService(applicationContext)
//
// }
//
// companion object{
// var instance:KlozerzApplication?=null
// }
//
// fun getDatabase(): KlozerzDB? {
// return KlozerzDB.Companion.getInstance()
// }
//
// fun getRepository() : DataRepository?{
// return DataRepository.Companion.getInstance()
// }
//
//
// fun saveProfile(profileModel: ProfileModel?, token: String?): Boolean {
// val sharedPref: SharedPreferences = applicationContext.getSharedPreferences("credentials", MODE_PRIVATE)
// val editor = sharedPref.edit()
// editor.putString("profile", Gson().toJson(profileModel))
// editor.putString("token", token)
// return editor.commit()
// }
//
// fun getProfile(): ProfileModel {
// val sharedPref: SharedPreferences = applicationContext.getSharedPreferences("credentials", MODE_PRIVATE)
// val credentials = sharedPref.getString("profile", "")
// return Gson().fromJson(credentials, ProfileModel::class.java)
// }
//
//}
|
// React imports
import { FC } from "react";
// Style imports
import {
CustomButton,
} from './GreenButton.styles';
// Interfaces
interface GreenButtonProps {
label: string,
isSubmit?: boolean,
clickFunction?: () => void,
customStyle?: any,
}
const GreenButton: FC<GreenButtonProps> = ({ label, isSubmit, clickFunction, customStyle }: GreenButtonProps) => {
return (
<CustomButton style={customStyle} onClick={clickFunction} type={isSubmit ? "submit" : "button"}>
{label}
</CustomButton>
);
}
export default GreenButton;
|
import React, { useEffect } from 'react';
import { Feature } from '../../components';
import './features.css';
import Aos from 'aos'
import 'aos/dist/aos.css'
const featuresData = [
{
title: 'Improving end distrust instantly',
text: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium, consequuntur voluptatem! Esse reprehenderit cumque, at temporibus ex fugit error labore illo possimus natus, aut vitae?"
},
{
title: 'Become the tended active',
text: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium, consequuntur voluptatem! Esse reprehenderit cumque, at temporibus ex fugit error labore illo possimus natus, aut vitae?"
},
{
title: 'Message or am nothing',
text: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium, consequuntur voluptatem! Esse reprehenderit cumque, at temporibus ex fugit error labore illo possimus natus, aut vitae?"
},
{
title: 'Really boy law county',
text: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium, consequuntur voluptatem! Esse reprehenderit cumque, at temporibus ex fugit error labore illo possimus natus, aut vitae?"
},
]
const Features = () => {
useEffect(() => {
Aos.init({ duration: 600 })
}, [])
return (
<div className="gpt3__features section__padding" id="features">
<div data-aos="fade-right" className="gpt3__features-heading">
<h1 className="gradient__text">The Future is Now and you just need to realize it. Step into the Future Today & make it Happen.</h1>
<p>Request early access</p>
</div>
<div className="gpt3__features-container">
{featuresData.map((item, index) => (
<Feature title={item.title} text={item.text} key={item.title + index} />
))}
</div>
</div>
)
}
export default Features
|
<mat-radio-group aria-labelledby="example-radio-group-label" class="center-element"
[(ngModel)]="selectedSymbol" (change)="handleChange(selectedSymbol)">
<mat-radio-button class="example-radio-button" *ngFor="let symbol of symbols" [value]="symbol">
{{symbol}}
</mat-radio-button>
</mat-radio-group>
<div class="center-element">
<table mat-table [dataSource]="dataList" class="mat-elevation-z4">
<ng-container matColumnDef="reportDate">
<th mat-header-cell *matHeaderCellDef> Report Date </th>
<td mat-cell *matCellDef="let element"> {{ element.reportDate }} </td>
</ng-container>
<ng-container matColumnDef="longPositions">
<th mat-header-cell *matHeaderCellDef> Longs </th>
<td mat-cell *matCellDef="let element"> {{ element.longPositions }} </td>
</ng-container>
<ng-container matColumnDef="shortPositions">
<th mat-header-cell *matHeaderCellDef> Shorts </th>
<td mat-cell *matCellDef="let element"> {{ element.shortPositions }} </td>
</ng-container>
<ng-container matColumnDef="percentageLong">
<th mat-header-cell *matHeaderCellDef> % Long </th>
<td mat-cell *matCellDef="let element"> {{ element.percentageLong }} </td>
</ng-container>
<ng-container matColumnDef="percentageShort">
<th mat-header-cell *matHeaderCellDef> % Shorts </th>
<td mat-cell *matCellDef="let element"> {{ element.percentageShort }} </td>
</ng-container>
<ng-container matColumnDef="netPositions">
<th mat-header-cell *matHeaderCellDef> Net Positions </th>
<td mat-cell *matCellDef="let element"> {{ element.netPositions }} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;" [ngClass]="{hovered: row.hovered, highlighted: row.highlighted}" (mouseover)="row.hovered = true" (mouseout)="row.hovered = false"></tr>
</table>
</div>
|
<div class="d-flex justify-content-end">
<div class="col-12 col-md-3 mb-3 mt-3 pe-md-3">
<div class="input-group filterSearch w-md-25">
<input class="form-control form-control-sm" type="text" name="filterExpense" [(ngModel)]="filterExpense" placeholder="Filtro">
<span class="input-group-text"><i class="fas fa-search"></i></span>
</div>
</div>
</div>
<div class="row">
<div class="d-flex justify-content-center" *ngFor="let expense of Expense | paginate: { itemsPerPage: 5,
currentPage: page,
totalItems: totalLength} | filter:filterExpense; index as i">
<div class="col-10">
<div class="card expense-card mb-2">
<div class="card-header p-2 d-flex justify-content-between">
<ul class="ps-0 align-items-left expense-list-card">
<li><strong>{{ expense.despesa }}</strong></li>
<li>{{ expense.tipoDespesa }} | {{ expense.conta }}</li>
</ul>
<ul class="expense-list-card-actions">
<li>
<button type="button" class="btn btn-sm rounded-circle me-2 btn-warning" (click)="modalEditExpense(expense)">
<i class="fas fa-pen text-light h-100" title="Editar renda"></i>
</button>
<button type="button" class="btn btn-sm rounded-circle me-2 btn-danger" (click)="modalDeleteExpense(expense)">
<i class="fas fa-trash-alt h-100" title="Excluir renda"></i>
</button>
<button type="button" class="btn btn-sm rounded-circle me-2 btn-info text-light" popover="{{ expense.observacao }}"
popoverTitle="Observação" [outsideClick]="true" placement="top" [ngClass]="{'disabled': expense.observacao === '', 'btn-secondary': expense.observacao === '', 'btn-info': expense.observacao !== ''}">
<i class="fas fa-info h-100"></i>
</button>
</li>
</ul>
</div>
<div class="card-body expense-card-body">
<ul class="d-flex ps-0 justify-content-between mb-0">
<li>{{ expense.valorDespesa | currency : 'BRL' }}</li>
<li>{{ expense.dataDespesa | date: 'dd/MM/yyyy' }}</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<pagination-controls class="text-center expense-pagination"
(pageChange)="page = $event"
[hidden]="Expense?.length <= 5"
previousLabel=""
nextLabel="">
</pagination-controls>
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>Java Data Types</title>
<link rel="icon" href="images/ourjavalogo1.png">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<link rel="stylesheet" href="css/component.css">
<link rel="stylesheet" type="text/css" href="css/fstyle.css" />
<link rel="stylesheet" type="text/css" href="css/style1.css" />
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="css/navstyles.css" />
<link rel="stylesheet" type="text/css" href="css/Introductionstyle.css" />
<style>
body {
overflow-y: scroll;
}
img.nostyle {
border-radius: 30%;
}
img.logonavbar{
border-radius: 50%;
width:70px;
height: 70px;
box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
}
</style>
</head>
<header>
<nav>
<div id="brand">
<div id="logo"><img src="images/ourjavalogo1.png" class="logonavbar"></div>
<div id="word-mark"></div>
</div>
<div id="menu">
<div id="menu-toggle">
<div id="menu-icon">
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
</div>
</div>
</div>
</nav>
<div id="hero-section">
<div id="head-line"></div>
</div>
</header>
<body class="cbp-spmenu-push">
<div class="wrapper">
<div class="main"> <a href="#" class="btn left"><span class="left-open"></span>More </a> <a href="#" class="btn right"><span class="right-open"></span>More </a>
<div class="ui white button" id="showLeftPush"><i class="fas fa-bars"></i></button></div>
<h2> Java Data Types </h2>
<p>As stated in the previous chapter, Java variables must have a specified type. Data types in Java are divided into<span class = "datatype"> two types</span> :</p>
<ul>
<div class="javaul">
<li><span class = "datatype">Primitive data types</span> which include int, float, double, boolean, char & byte (Note there are more primitive data types, these are not necessary for the scope of this site).</li>
<li><span class = "datatype">Non-Primitive data types</span> which include Strings, arrays & classes (This will be covered in later chapters).</li>
</div>
</ul>
<h3>Primitive Data Types</h3>
<p>A primitive data type specifies the size and type of variable values, with no further methods, in total there are eight primitive data types in Java. We wil be covering six of these.
<br>
<br>
- <span class = "datatype">Byte</span> is a data type with a size of 1 bit that stores whole numbers in the range -128 to 127.
<br>
- <span class = "datatype">Int</span> is a data type which has a size of 4 bytes that can store whole numbers.
<br>
- <span class = "datatype">float</span> is a data type which has a size of 4 bytes that can store fractional numbers up to 7 digits.
<br>
- <span class = "datatype">char</span> is a data type which has a size of 2 bytes that can store a single character.
<br>
- <span class = "datatype">double</span> is a data type which has a size of 8 bytes that can store fractional numbers up to 15 digits.
<br>
- <span class = "datatype">boolean</span> is a data type which has a size of 1 bit that stores either a true or false value.
</p>
<h3>Numbers</h3>
<p>
<span class = "datatype">Primitive number types</span> are divided again into <span class = "datatype">two categories</span> :
<br>
- <span class = "datatype">Integer types</span> which store whole numbers that can be postive or negative, these include<span class = "datatype"> int & byte</span> in our case.
<br>
- <span class = "datatype">Float point types</span> which store numbers with a fractional element e.g. one or more decimals, there are two types of this,<span class = "datatype"> float & double</span>.
</p>
<h4>Byte</h4>
<p>As stated previously, the <span class = "datatype">byte</span> data type can store numbers from -128 to 127 which can be used instead of <span class = "datatype">int</span> if you know the range of values within the range of values of a <span class = "datatype">byte</span> data type.</p>
<p class = "codebox">
public class MyNewClass {
<br>
public static void main(String[] args) {
<br>
byte myByte = 100;
<br>
System.out.println(myByte);
<br>
}
<br>
}
</p>
<h4> Int</h4>
<p><span class = "datatype"> Int</span> is the preferred data type when we want to store a numeric value, it stores whole numeric values in a very large number range resulting in this data type being more versatile than <span class = "datatype">byte</span>. </p>
<p class = "codebox">
public class MyNewClass {
<br>
public static void main(String[] args) {
<br>
int myInt = 10000;
<br>
System.out.println(myInt);
<br>
}
<br>
}
</p>
<h3>Floating point types</h3>
<p><span class = "datatype">Should I use float or double?</span> The accuracy of a floating point value indicates how many digits it can have after a decimal point, since <span class = "datatype">double can have 15 digits after a decimal point</span> it is the preferred data value for floating point calculations.</p>
<h4>Double</h4>
<p> The <span class = "datatype">double data type</span> stores fractional numbers, note you should end a double value with <span class = "datatype">"d"</span> to differentiate it from a float value.</p>
<p class = "codebox">
public class MyNewClass {
<br>
public static void main(String[] args) {
<br>
double myDouble = 27.842345d;
<br>
System.out.println(myDouble);
<br>
}
<br>
}
</p>
<h4>Float</h4>
<p> The <span class = "datatype">float data type</span> stores fractional numbers, note you should end a float value with <span class = "datatype">"f"</span> to differentiate it from a float value.</p>
<p class = "codebox">
public class MyNewClass {
<br>
public static void main(String[] args) {
<br>
float myFloat = 27.843f;
<br>
System.out.println(myFloat);
<br>
}
<br>
}
</p>
<h3>Booleans</h3>
<p> The <span class = "datatype">boolean data type</span> store a value that can only be <span class = "datatype">true</span> or <span class = "datatype">false</span>. </p>
<p class = "codebox">
public class MyNewClass {
<br>
public static void main(String[] args) {
<br>
boolean myBoolean1 = true;
<br>
System.out.println(myBoolean1);
<br>
boolean myBoolean2 = false;
<br>
System.out.println(myBoolean2);
<br>
}
<br>
}
</p>
<h3>Characters</h3>
<p> The <span class = "datatype">char data type</span> stores a single character value that is surrounded by quotes <span class = "datatype">('')</span>.</p>
<p class = "codebox">
public class MyNewClass {
<br>
public static void main(String[] args) {
<br>
char myChar = 'A';
<br>
System.out.println(myChar);
<br>
}
<br>
}
</p>
<h3>Strings</h3>
<p> The <span class = "datatype">String data type</span> is used to store a sequence of characters surrounded by <span class = "datatype">double quotes ("")</span>. A String in java is actually a <span class = "datatype">non-primitive type</span>(Description of non-primitive types in right sidebar), because a string is an object that has <span class = "datatype">methods to perform operations on it</span>. You will learn about objects in a later section.</p>
<p class = "codebox">
public class MyNewClass {
<br>
public static void main(String[] args) {
<br>
String myString = "Welcome to the Java-Academy website";
<br>
System.out.println(myString);
<br>
}
<br>
}
</p>
</div>
<div class="sidebar left">
<h3>Additional Info</h3>
<p>
The footer on each page of our website contains additional information that may be useful to you, each footer is the same on each page. Our telephone and Fax number as well as email are located in the footer of the site along with links to useful external sites.
</p>
<img src="images/iconAdditonalinfo.png" width="400" height="400" class="nostyle">
<p>
In the footer there is links to Oracle who holds the rights to the java language. Stack Overflow, Geeks for Geeks, DZone and the Oracle help center are useful forums and tools for learning java. The link to the compiler which we use through-out the website is located here called J-Doodle, each program is wrote on this online compiler and is embedded into pages.
</p>
</div>
<div class="sidebar right">
<h3>Java Data Types</h3>
<p>
This page focuses on Java data types in more detail, concerning primitive & non-primitive data types with code examples.
</p>
<p>
Non-primitive data types are also known as reference types because they directly refer to an object. The main differences between a primitive and non-primitive data type are :
</p>
<ul>
<div class="javaul">
<li>Primitive data types are already defined within java. Non primitive data types are created by the programmer with the exception of String.</li>
<li>Non-primitive data types can call methods to perform operations on the object whereas primitive types cannot.</li>
<li>A primitive data type must have a value whereas a non-primitive can be null.</li>
<li>A non-primitive type starts with a uppercase letter while a primitive type starts with a lower case letter.</li>
<li>Non primitive data types all have the same size while a primitive types size depends on its data type.</li>
</ul>
</div>
</div>
<nav class="cbp-spmenu cbp-spmenu-vertical cbp-spmenu-left" id="cbp-spmenu-s1">
<h3>Java Academy</h3>
<a class = "active item" href="index.html">Home |</a>
<a class = "item" href="javadownloads.html">Java Downloads |</a>
<a class = "item" href="javaIntroduction.html">Java Introduction |</a>
<a class ="item" href="Exercisepage.html">Java Exercises |</a>
<a class = "item" href=" ">Code Examples |</a>
<a class = "item" href="History.html">Java History |</a>
<a class = "item" href="Quiz.html">Java Quiz |</a>
<a class = "item" href="HelpPage.html">Help |</a>
<a class = "item" href="IDEPage.html">IDES |</a>
<a class = "item" href="RealWExamples.html">Java Implemented |</a>
<a class = "item" href="Disclaimer.html">Disclaimer Page |</a>
</nav>
<footer>
<div class ="sectionf">
<div class="img-with-text">
<a href="Disclaimer.html">
<img class="Wit2" src="images/Wit.jpg" >
<p><h3>Disclaimer Page</h3></p>
</a>
</div>
<br>
<br>
</div>
<div class ="contactf">
<br>
Email: Izaac Doyle : [email protected]
<br>
Email: Evan Casey : [email protected]
<br>
</div>
<div class = "ui stackable grid">
<div class="mini"></div>
<div class="maxi">
<ul>
<h4>Java Academy</h4>
</ul>
<ul>
<li><a href="https://www.jdoodle.com/" target="_blank">Jdoodle</a></li>
<li><a href="https://codeinstitute.net/blog/top-tips-learning-java-programming/" target="_blank">Java Tips</a></li>
<li><a href="https://dzone.com/java-jdk-development-tutorials-tools-news" target="_blank">DZone</a></li>
</ul>
<ul>
<li><a href="https://docs.oracle.com/en/" target="_blank">Oracle Help Center</a></li>
<li><a href="https://www.geeksforgeeks.org/" target="_blank">Geeks for Geeks</a></li>
<li><a href="https://stackoverflow.com/" target="_blank">Stack Overflow</a></li>
</ul>
</div>
</footer>
<!-- end .wrapper -->
<script src="js/classie.js"></script>
<script src="js/main.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://www.jdoodle.com/assets/jdoodle-pym.min.js" type="text/javascript"></script>
<script>
jQuery(function($){
$('.btn.left').click(function(event){
event.preventDefault();
$('body').toggleClass('left');
});
$('.btn.right').click(function(event){
event.preventDefault();
$('body').toggleClass('right');
});
});
</script>
<script>
$( () => {
//On <a href="https://www.jqueryscript.net/tags.php?/Scroll/">Scroll</a> Functionality
$(window).scroll( () => {
var windowTop = $(window).scrollTop();
windowTop > 100 ? $('nav').addClass('navShadow') : $('nav').removeClass('navShadow');
windowTop > 100 ? $('ul').css('top','100px') : $('ul').css('top','160px');
});
//Click Logo To Scroll To Top
$('#logo').on('click', () => {
$('html,body').animate({
scrollTop: 0
},500);
});
//Smooth Scrolling Using Navigation Menu
$('a[href*="#"]').on('click', function(e){
$('html,body').animate({
scrollTop: $($(this).attr('href')).offset().top - 100
},500);
e.preventDefault();
});
//Toggle Menu
$('#menu-toggle').on('click', () => {
$('#menu-toggle').toggleClass('closeMenu');
$('ul').toggleClass('showMenu');
$('li').on('click', () => {
$('ul').removeClass('showMenu');
$('#menu-toggle').removeClass('closeMenu');
});
});
});
</script>
<script>//sidemenu left push
var menuLeft = document.getElementById('cbp-spmenu-s1' ),
showLeftPush = document.getElementById( 'showLeftPush' ),
body = document.body;
var menuLeft = document.getElementById('cbp-spmenu-s1' ),
body = document.body;
showLeftPush.onclick = function() {
classie.toggle( this, 'active' );
classie.toggle( body, 'cbp-spmenu-push-toright' );
classie.toggle( menuLeft, 'cbp-spmenu-open' );
disableOther( 'showLeftPush' );
};
function disableOther( button ) {
if( button !== 'showLeftPush' ) {
classie.toggle( showLeftPush, 'disabled' );
}
}
</script>
</body>
</html>
|
package simulator.view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.awt.Frame;
import javax.print.attribute.standard.JobMessageFromOperator;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.JToolBar;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import simulator.control.Controller;
import simulator.model.Event;
import simulator.model.RoadMap;
import simulator.model.TrafficSimObserver;
//Conceptually extending JToolbar would be a better fit.
//However, we did this way, extending JPanel because of
//instructions given on statement.
public class ControlPanel extends JPanel implements TrafficSimObserver {
private Controller _controller;
private boolean _stopped;
private JButton _fileOpenButton;
private JButton _contaminationButton;
private JButton _weatherButton;
private JButton _runButton;
private JButton _stopButton;
private JSpinner _tickSpinner;
private JButton _closeButton;
private JToolBar _toolbar;
private JFileChooser _fileChooser;
public ControlPanel(Controller controller)
{
_fileChooser = new JFileChooser();
_controller = controller;
_controller.addObserver(this);
_toolbar = new JToolBar();
_fileOpenButton = new JButton(new ImageIcon("resources/icons/open.png"));
_fileOpenButton.setToolTipText("Open events file");
//_fileOpenButton.setMaximumSize(new Dimension(50, 50));
_fileOpenButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loadFile();
}
});
_toolbar.add(_fileOpenButton);
_toolbar.addSeparator();
_contaminationButton = new JButton(new ImageIcon("resources/icons/co2class.png"));
_contaminationButton.setToolTipText("Add a new C02 change event");
//_contaminationButton.setMaximumSize(new Dimension(50, 50));
_contaminationButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
changeC02Class();
}
});
_toolbar.add(_contaminationButton);
_weatherButton = new JButton(new ImageIcon("resources/icons/weather.png"));
_weatherButton.setToolTipText("Add a new weather change event");
//_weatherButton.setMaximumSize(new Dimension(50, 50));
_weatherButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
changeWeather();
}
});
_toolbar.add(_weatherButton);
_toolbar.addSeparator();
_runButton = new JButton(new ImageIcon("resources/icons/run.png"));
_runButton.setToolTipText("Run the simulation");
//_runButton.setMaximumSize(new Dimension(50, 50));
_runButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
_stopped = false;
enableToolBar(false);
run_sim((Integer)_tickSpinner.getValue());
}
});
_toolbar.add(_runButton);
_stopButton = new JButton(new ImageIcon("resources/icons/stop.png"));
_stopButton.setToolTipText("Stop the simulation");
//_stopButton.setMaximumSize(new Dimension(50, 50));
_stopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
_stopped = true;
}
});
_toolbar.add(_stopButton);
_toolbar.addSeparator();
_toolbar.add(new JLabel("Ticks:"));
_tickSpinner = new JSpinner(new SpinnerNumberModel(10, 1, null, 1));
_tickSpinner.setToolTipText("Ticks to advance");
_tickSpinner.setMaximumSize(new Dimension(70, 35));
_tickSpinner.setPreferredSize(new Dimension(70, 35));
_toolbar.add(_tickSpinner);
//Visual separator indication
_toolbar.addSeparator();
_closeButton = new JButton(new ImageIcon("resources/icons/exit.png"));
//_closeButton.setMaximumSize(new Dimension(50, 50));
_closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showOptionDialog(ControlPanel.this.getParent(),
"Are sure you want to exit?", "Exit",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (n == 0) {
System.exit(0);
}
}
});
_toolbar.add(Box.createGlue());
_toolbar.add(_closeButton);
setLayout(new BorderLayout(0, 0));
add(_toolbar, BorderLayout.CENTER);
}
protected void changeWeather() {
ChangeWeatherDialog dialog = new ChangeWeatherDialog(null, _controller);
dialog.setVisible(true);
}
protected void changeC02Class() {
ChangeCO2ClassDialog dialog = new ChangeCO2ClassDialog(null, _controller);
dialog.setVisible(true);
}
protected void loadFile() {
try {
_fileChooser.setCurrentDirectory(new File("resources/examples"));
int res = _fileChooser.showOpenDialog(this);
switch(res)
{
case JFileChooser.CANCEL_OPTION:
//Removed this, it was annoying and not mandatory
//JOptionPane.showMessageDialog(this, "Cancelled", "Info", JOptionPane.INFORMATION_MESSAGE);
break;
case JFileChooser.APPROVE_OPTION:
_controller.reset();
_controller.loadEvents(new FileInputStream(_fileChooser.getSelectedFile()));
break;
default:
case JFileChooser.ERROR_OPTION:
//Show error message
throw new Exception();
}
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Error opening file", "Error", JOptionPane.ERROR_MESSAGE);
}
}
private void run_sim(int n) {
if (n > 0 && !_stopped) {
try {
_controller.run(1);
} catch (Exception e) {
// As an error dialog is created by whoever observes the controller onError, it is not necessary to do it here.
// If we wanted to have 2 dialogs, just uncomment the following lines.
//JOptionPane.showMessageDialog(new JFrame(), "Error while executing simulation. Simulation aborted.", "Error",
// JOptionPane.ERROR_MESSAGE);
enableToolBar(true);
_stopped = true;
return;
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
run_sim(n - 1);
}
});
} else {
enableToolBar(true);
_stopped = true;
}
}
private void enableToolBar(boolean b) {
_fileOpenButton.setEnabled(b);
_contaminationButton.setEnabled(b);
_weatherButton.setEnabled(b);
_runButton.setEnabled(b);
_closeButton.setEnabled(b);
}
private void stop() {
_stopped = true;
}
@Override
public void onAdvanceStart(RoadMap map, List<Event> events, int time) {
}
@Override
public void onAdvanceEnd(RoadMap map, List<Event> events, int time) {
}
@Override
public void onEventAdded(RoadMap map, List<Event> events, Event e, int time) {
}
@Override
public void onReset(RoadMap map, List<Event> events, int time) {
}
@Override
public void onRegister(RoadMap map, List<Event> events, int time) {
}
@Override
public void onError(String err) {
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"
type="text/javascript"
></script>
<title>Codewars exercise</title>
</head>
<body>
<!-- Task
Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering.
For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would
lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3].
Example
deleteNth ([1,1,1,1],2) // return [1,1]
deleteNth ([20,37,20,21],1) // return [20,37,21] -->
<script>
function deleteNth(arr, n) {
const result = [];
const helperObj = {};
arr.forEach((number) => {
if (helperObj[number]) {
if (helperObj[number] < n) {
helperObj[number] = helperObj[number] + 1;
result.push(number);
}
} else {
helperObj[number] = 1;
result.push(number);
}
});
console.log(result);
return result;
}
function tests(result, correctResult) {
return _.isEqual(result, correctResult)
? console.log("correct")
: console.log("uncorrect");
}
tests(deleteNth([20, 37, 20, 21], 1), [20, 37, 21]);
tests(deleteNth([1, 1, 3, 3, 7, 2, 2, 2, 2], 3), [
1,
1,
3,
3,
7,
2,
2,
2,
]);
</script>
</body>
</html>
|
import collections
import logging
import logging.config
import structlog
from common import config
from typing import Callable
import uuid
def _order_keys(logger, method_name, event_dict):
return collections.OrderedDict(
sorted(event_dict.items(), key=lambda item: (item[0] != "event", item))
)
def configure_logger(
log_to_console=True, color_console=True, log_to_file=True, filename=None
):
pre_chain = []
if structlog.contextvars:
pre_chain += [
structlog.contextvars.merge_contextvars,
]
pre_chain += [
structlog.stdlib.add_logger_name,
structlog.stdlib.add_log_level,
structlog.processors.TimeStamper(fmt="iso", utc=True),
_order_keys,
]
structlog.configure_once(
processors=pre_chain
+ [
structlog.stdlib.filter_by_level,
structlog.stdlib.PositionalArgumentsFormatter(),
structlog.processors.StackInfoRenderer(),
structlog.processors.format_exc_info,
structlog.processors.UnicodeDecoder(),
structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
],
wrapper_class=structlog.stdlib.BoundLogger,
context_class=dict,
logger_factory=structlog.stdlib.LoggerFactory(),
cache_logger_on_first_use=True,
)
handlers = {}
if log_to_console:
handlers["console"] = {"()": logging.StreamHandler, "formatter": "console"}
if log_to_file and filename:
handlers["file"] = {
"()": logging.handlers.RotatingFileHandler,
"filename": filename,
"formatter": "json",
"maxBytes": 25000000,
"backupCount": 100,
}
logging_config = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"console": {
"()": structlog.stdlib.ProcessorFormatter,
"processor": structlog.dev.ConsoleRenderer(colors=color_console),
"foreign_pre_chain": pre_chain,
},
"json": {
"()": structlog.stdlib.ProcessorFormatter,
"processor": structlog.processors.JSONRenderer(),
"foreign_pre_chain": pre_chain,
},
},
"handlers": handlers,
"loggers": {
"": {"propagate": True, "handlers": list(handlers.keys()), "level": "DEBUG"}
},
}
logging.config.dictConfig(logging_config)
def get_logger(filename):
# Rotate logfile before starting new logger
temporary_handler = logging.handlers.RotatingFileHandler(
filename=filename, backupCount=50
)
temporary_handler.doRollover()
configure_logger(filename=filename)
return structlog.get_logger()
def set_trace_id(function: Callable, trace_id: str) -> None:
global_var = function.__globals__
global_var["trace_id"] = trace_id
def log_function_calls(original_function):
trace_id = str(uuid.uuid4())
set_trace_id(original_function, trace_id)
function_name = f"{original_function.__module__}.{original_function.__name__}"
logger = custom_logger.bind(function_name=function_name, trace_id=trace_id)
def new_function(*args, **kwargs):
log_args=dict(kwargs)
for key in log_args.keys():
if hasattr(log_args[key], '__len__') and len(log_args[key]) > 5:
size=len(log_args[key])
log_args[key] = f'An object of size {size}'
logger.info("Function called", args=args, kwargs=log_args)
try:
result = original_function(*args, **kwargs)
except Exception as e:
logger.warning("Exception raised", error=str(e))
raise e
logger.info("Function returned", result=result)
return result
return new_function
def log_class_methods(Cls):
class NewCls:
def __init__(self, *args, **kwargs):
custom_logger.info("__init__ called", class_name=Cls.__name__, args=args, kwargs=kwargs)
self.oInstance = Cls(*args, **kwargs)
custom_logger.info("__init__ finished ", class_name=Cls.__name__, args=args, kwargs=kwargs)
def __getattribute__(self, s):
"""
this is called whenever any attribute of a NewCls object is accessed. This function first tries to
get the attribute off NewCls. If it fails then it tries to fetch the attribute from self.oInstance (an
instance of the decorated class). If it manages to fetch the attribute from self.oInstance, and
the attribute is an instance method then `time_this` is applied.
"""
try:
x = super(NewCls, self).__getattribute__(s)
except AttributeError:
pass
else:
return x
x = self.oInstance.__getattribute__(s)
if type(x) == type(self.__init__): # an instance method
return log_function_calls(x)
else:
return x
return NewCls
custom_logger = get_logger(config["log_file"])
|
import UIKit
struct FiboIterator: IteratorProtocol {
var state = (0, 1)
mutating func next() -> Int? {
let nextValue = state.0
state = (state.1,state.0+state.1)
return nextValue
}
}
func fiblIterrator() -> AnyIterator<Int> {
var state = (0, 1)
return AnyIterator{
let nextValue = state.0
state = (state.1,state.0+state.1)
return nextValue
}
}
struct Fibonacci: Sequence {
typealias Element = Int
func makeIterator() -> AnyIterator<Element> {
return AnyIterator(FiboIterator())
}
}
var iter = FiboIterator()
for _ in (1 ... 10) {
print(iter.next()!)
}
print("----------------------------------")
let fibs = Fibonacci()
var fibsIter1 = fibs.makeIterator()
var fibsIter2 = fibs.makeIterator()
while let value = fibsIter1.next() {
guard value < 10 else { break }
print("iter1: \(value)")
}
print("=======")
while let value = fibsIter2.next() {
guard value < 10 else { break }
print("iter1: \(value)")
}
print("----------------------------------")
let fibo1 = Fibonacci().prefix(10)
let fibo2 = Fibonacci().prefix(10).suffix(5)
print(Array(fibo1))
print(Array(fibo2))
print("--------------------------------")
let fiboArray = fibo1.split(whereSeparator: { $0 % 2 == 0})
fiboArray.forEach {
print(Array($0))
}
|
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Enums\News\Status;
use Illuminate\Support\Facades\DB;
class NewsSeeder extends Seeder
{
public function run(): void
{
DB::table('news')->insert($this->getData());
}
private function getData(): array {
$newsQty = 20;
$news = [];
for ($i = 0; $i <=$newsQty; $i++) {
$newId = $i+1;
$news[] = [
'title' => "title-$newId",
'description' => fake()->text(50),
'category_id' => fake()->randomDigitNotNull(),
'author' => fake()->userName(),
'image' => 'https://dummyimage.com/150',
'status' => Status::ACTIVE->value,
'created_at' => now()
];
}
return $news;
}
}
|
import ICarImagesRepository from '@models/cars/repositories/ICarImagesRepository';
import IStorageProvider from '@shared/container/providers/StorageProvider/IStorageProvider';
import { inject, injectable } from 'tsyringe';
interface IRequest {
car_id: string;
images_name: string[];
}
@injectable()
class UploadCarImagesUseCase {
constructor(
@inject('CarImagesRepository')
private carImagesRepository: ICarImagesRepository,
@inject('StorageProvider')
private storageProvider: IStorageProvider,
) {}
public async execute({ car_id, images_name }: IRequest): Promise<void> {
images_name.forEach(async image_name => {
await this.carImagesRepository.create({
car_id,
image_name,
});
await this.storageProvider.save(image_name, 'cars');
});
}
}
export default UploadCarImagesUseCase;
|
/**
* 專案名稱: wistroni40-sumk
* 部門代號: MLD500
* 檔案說明: 使用率範本
* @CREATE Monday, 8th November 2021 1:23:27 pm
* @author Steve Y Lin
* @contact [email protected] #1342
* -----------------------------------------------------------------------------
* @NOTE
*/
import * as schedule from 'node-schedule';
import { Observable, Subject } from 'rxjs';
import { map, mergeMap, tap } from 'rxjs/operators';
import {
Consumer,
ElasticBuilder,
HttpProducerAdapter,
Log4js,
LoggerAdapter,
Producer,
RetryProducerAdapter,
} from 'wistroni40-backend-utility';
import { DynamicClassFactory as Factory } from 'wistroni40-dynamic-class';
import { UsageConsumerAdapter } from '../consumer';
import {
UsageConfig,
UsageCount,
UsagePayload,
UsagePayloadEntity,
UsageResponse,
} from '../models';
import { Server } from '../server';
import { TimeUtility } from '../utils';
import { CoreTemplate } from './../../core';
import { UsageQueryExecutor } from './../executor';
import { QueryConditionBuilder } from './classes';
import { CustomUsage } from './custom-usage.template';
import { UsageType } from './models';
/**
* 使用率範本
*/
export abstract class UsageTemplate
implements CoreTemplate<UsagePayload>, CustomUsage
{
/**
* API 服務器
*/
private _server: Server;
/**
* 時間公用工具
*/
private _timeUtil = new TimeUtility();
/**
* 使用率保存清單
*/
private _usage = new Map<string, number>();
/**
* 上拋資料訂閱主題
*/
private _payload = new Subject<UsageResponse>();
/**
* 排程設定
*/
private _cron?: string;
/**
* 日誌
*/
protected logger: LoggerAdapter = new Log4js('USAGE');
/**
* 使用率類型
*/
public type: UsageType = 'Count';
/**
* @param config 服務設定檔
*/
constructor(protected config: UsageConfig) {
this._server = Server.instance(this, config.port);
}
/**
* 取得資料消費者
*
* @method private
* @param start 查詢開始時間
* @param plant 要查詢的廠別
* @return 回傳資料消費者
*/
private async consumer(
start: number,
plant?: string,
): Promise<Consumer<UsagePayload>> {
const plantList = plant ? [plant] : this.config.plant;
const usage = plantList.map(p => {
return new UsagePayloadEntity({
plant: p,
systemid: this.config.systemId,
cmpunitdesc: this.config.unit,
uploadtime: start,
});
});
return new UsageConsumerAdapter(usage);
}
/**
* 取得資料生產者
*
* @method private
* @return 回傳資料生產者
*/
private async producer(): Promise<Producer<UsagePayload>> {
return new HttpProducerAdapter(this.config.publishedApi);
}
/**
* 更新當日使用率
*
* @method public
* @param payload 使用率數據
* @param start 觸發開始時間
* @param ernd 觸發結束時間
* @return 回傳使用率數據
*/
public async update(
payload: UsagePayload,
start: number,
end: number,
): Promise<UsageCount> {
const executor = new UsageQueryExecutor(this.config);
const condition = new QueryConditionBuilder()
.setUsage(payload)
.setBetween(start, end)
.build();
const strategy = `Usage${this.type}QueryBuilder`;
const query = Factory.createInstance<ElasticBuilder>(strategy, condition);
const result = await executor.exec(query);
return result.length > 0 ? result[0] : { plant: '', count: 0 };
}
/**
* 客製查詢當日使用率
*
* @method public
* @param payload 使用率數據
* @param start 觸發開始時間
* @param ernd 觸發結束時間
* @return 回傳使用率數據
*/
public async query(
payload: UsagePayload,
start: number,
end: number,
): Promise<UsageCount> {
return { plant: '', count: 0 };
}
/**
* 路由至內建或客製的使用率查詢方式
*
* @method public
* @param payload 使用率數據
* @param start 觸發開始時間
* @param ernd 觸發結束時間
* @return 回傳使用率數據
*/
public async route(
payload: UsagePayload,
start: number,
end: number,
): Promise<UsagePayload> {
const usage =
this.type === 'Custom'
? await this.query(payload, start, end)
: await this.update(payload, start, end);
this._usage.set(payload.plant, usage.count);
return payload;
}
/**
* 設定實際使用量
*
* @method public
* @param payload 使用率數據
* @return 回傳添加實際使用量的使用率數據
*/
public setActualUsage(payload: UsagePayload): UsagePayload {
payload.actual = this._usage.get(payload.plant) ?? 0;
return payload;
}
/**
* 取得標準值
*
* @method public
* @param payload 使用率數據
* @param start 查詢開始時間
* @param end 查詢結束時間
* @return 回傳標準值
*/
public abstract target(
payload: UsagePayload,
start: number,
end: number,
): Promise<UsagePayload>;
/**
* 驗證使用率是否達標
*
* @method public
* @param payload 使用率數據
* @return 使用率數據
*/
public achieve(payload: UsagePayload): UsagePayload {
payload.status = payload.actual >= payload.target ? 1 : 0;
return payload;
}
/**
* 上拋資料
*
* @method public
* @param payload 使用率數據
*/
public async publish(payload: UsagePayload): Promise<void> {
const producer = await this.producer();
const retry = new RetryProducerAdapter(producer);
retry.publish(payload, error => {
this._payload.next({ error, result: payload });
});
}
/**
* 消費資料
*
* @method public
* @param start 觸發開始時間
* @param ernd 觸發結束時間
* @param plant 要查詢的廠別
*/
public async consume(
start: number,
end: number,
plant?: string,
): Promise<void> {
const consumer = await this.consumer(start, plant);
const consume$ = consumer.consume().pipe(
// 更新最新的使用率
mergeMap(usage => this.route(usage, start, end)),
// 添加實際使用量
map(usage => this.setActualUsage(usage)),
// 取得標準值
mergeMap(usage => this.target(usage, start, end)),
// 驗證使用率是否達標
map(usage => this.achieve(usage)),
// 發送數據
tap(usage => this.publish(usage)),
);
consume$.subscribe();
}
/**
* 執行流程
*
* @method public
* @param start 觸發開始時間
* @param ernd 觸發結束時間
* @param plant 要查詢的廠別
* @return 回傳流程執行結果
*/
public execute(
start?: number,
end?: number,
plant?: string,
): Observable<UsageResponse> {
this.logger.trace('Start usage service');
start = start || this._timeUtil.getYesterday();
end = end || this._timeUtil.getToday();
this.consume(start, end, plant);
return this._payload;
}
/**
* 設定排程執行使用率查詢
*
* @method public
* @param cron 排程
* @return 回傳流程執行結果
*/
public setSchedule(cron: string): Observable<UsageResponse> {
this._cron = cron;
schedule.scheduleJob(this._cron, () => this.execute());
return this._payload;
}
}
|
# Fashion-recommender-system
A Deep Learning based Fashion Recommender System using the ResNET50
Streamlit web application for a Fashion Recommender System and T-shirt Designer. Here is a breakdown of the key components and functionalities of the code:
1. Importing Libraries:
The code starts by importing various Python libraries, including Streamlit for building the web app, PIL (Pillow) for image manipulation, NumPy, TensorFlow for deep learning tasks, Scikit-learn for nearest neighbor recommendation, and other necessary modules.
2. Streamlit App Initialization:
It initializes a Streamlit app with the title "Fashion Recommender System and T-shirt Designer."
3. Upload T-shirt Image:
Users can upload a T-shirt image (JPEG or PNG with a transparent background). The uploaded image is displayed on the web app.
4. Customization Options:
Users can customize the T-shirt by uploading a logo with a transparent background, adjusting the logo size, and specifying the vertical position. When customization options are applied, the logo is added to the T-shirt, and the customized T-shirt is displayed.
5. Generate Clothes with DALL-E:
Users can input a prompt, select an image size, and generate clothes using the OpenAI DALL-E API. The generated clothes image is displayed on the web app.
6. Recommendation Section:
This section focuses on recommending outfits based on user preferences.
7. Feature Extraction and Recommendation:
Precomputed features and filenames are loaded from 'embeddings.pkl' and 'filenames.pkl.'
The ResNet-50 model is loaded for feature extraction. Features are extracted from uploaded images using this model.
A recommendation function is provided that finds similar images based on extracted features.
8. User Interaction for Recommendations:
Users can upload an image, specify the number of recommendations they want (between 1 and 50), and see recommended outfits based on their uploaded image.
9. File Saving and Error Handling:
There are functions to save uploaded files and handle potential errors during file upload.
10. OpenAI Integration:
The code utilizes the OpenAI DALL-E API to generate clothes images based on user prompts.
11. Streamlit Web App Interface:
The Streamlit app interface includes sidebars for customization options, generating clothes, and displaying recommendations.
12. Displaying Images:
Images (T-shirt, customized T-shirt, generated clothes, and recommended outfits) are displayed within the app using Streamlit's image display functionality.
Overall, this code combines image customization, AI-based image generation, and outfit recommendations in a single web application, making it a versatile tool for fashion enthusiasts. Users can upload T-shirt designs, customize them with logos, generate unique clothing items, and receive outfit recommendations based on their preferences.
|
import streamlit as st
import PIL.Image as Image
from io import BytesIO
import pandas as pd
from torchvision import transforms
from inference import label_to_food, preprocess_image, predict_V0, predict_V1, predict_V2, predict_V3
st.set_page_config(
page_title="Food-Vision",
page_icon="😋",
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'Report a bug': "https://github.com/pintoelson/food-vision-comparison/issues"
}
)
st.header('Food Vision', divider='rainbow')
st.write("These models are trained on the famous Food101 dataset. Here is the [link](https://github.com/pintoelson/food-vision-comparison/blob/main/classes.txt) with the types of foods the models are able to predict")
uploaded_file = st.file_uploader("Choose a file", type = ['png', 'jpg'])
preprocessed_image = None
if uploaded_file is not None:
# To read file as bytes:
bytes_data = uploaded_file.getvalue()
image = Image.open(BytesIO(bytes_data))
# st.image(image, caption='Uploaded image')
preprocessed_image = preprocess_image(image)
V3_column, V2_column, V1_column, V0_column = st.columns(4)
with V3_column:
if st.button('Predict with Model V3'):
if preprocessed_image != None:
with st.spinner('Wait for it...'):
label, confidence = predict_V3(preprocessed_image)
food = label_to_food(label)
st.success(f'Predicted {food} with a confidence of {confidence: .2f}%')
else:
st.write('Please upload an image')
with V2_column:
if st.button('Predict with Model V2'):
if preprocessed_image != None:
with st.spinner('Wait for it...'):
label, confidence = predict_V2(preprocessed_image)
food = label_to_food(label)
st.success(f'Predicted {food} with a confidence of {confidence: .2f}%')
else:
st.write('Please upload an image')
with V1_column:
if st.button('Predict with Model V1'):
if preprocessed_image != None:
with st.spinner('Wait for it...'):
label, confidence = predict_V1(preprocessed_image)
food = label_to_food(label)
st.success(f'Predicted {food} with a confidence of {confidence: .2f}%')
else:
st.write('Please upload an image')
with V0_column:
if st.button('Predict with Model V0'):
if preprocessed_image != None:
with st.spinner('Wait for it...'):
label, confidence = predict_V0(preprocessed_image)
food = label_to_food(label)
st.success(f'Predicted {food} with a confidence of {confidence: .2f}%')
else:
st.write('Please upload an image')
st.divider()
st.subheader("Model Comparison")
left_co, cent_co,last_co = st.columns([1,4,1])
data_df = pd.DataFrame(
{
"Models": ["3️⃣ V3","2️⃣ V2","1️⃣ V1","0️⃣ V0"],
"Description":["Transfer Learning with Resnet-101", "Transfer Learning with Effecient Net V2 S",
"Standard CNN", "Standard MLP"],
"Train Accuracy(Approximated %)": ["60", "45", "33", "11"],
"Early Stopping": ["❌", "✅", "✅", "✅"],
"LR Scheduler": [ "✅", "❌", "❌", "❌"]
}
)
with cent_co:
st.data_editor(
data_df,
hide_index=True,
)
st.divider()
st.subheader("Metric Comparison")
V3_met, V2_met, V1_met, V0_met = st.columns(4)
with V3_met:
st.image('metrics/model_V3.png', caption='Metrics for Model V3')
with V2_met:
st.image('metrics/model_V2.png', caption='Metrics for Model V2')
with V1_met:
st.image('metrics/model_V1.png', caption='Metrics for Model V1')
with V0_met:
st.image('metrics/model_V0.png', caption='Metrics for Model V0')
|
package main
import (
"fmt"
"log"
)
type ListNode struct {
Val int
Next *ListNode
}
func main() {
// Criando o primeiro nó da lista
primeiroNo := &ListNode{Val: 1}
// Criando o segundo nó da lista
segundoNo := &ListNode{Val: 2}
// Ligando o primeiro nó ao segundo nó
primeiroNo.Next = segundoNo
// Criando o terceiro nó da lista
terceiroNo := &ListNode{Val: 3}
// Ligando o segundo nó ao terceiro nó
segundoNo.Next = terceiroNo
reverseList(primeiroNo)
}
func reverseList(head *ListNode) *ListNode {
if head == nil || head.Next == nil { //Quando chegar no ultimo elemento, devolve ele
return head
}
result := reverseList(head.Next) // vai entrando em recursão até chegar no ultimo
log.Println(fmt.Sprintf("Head value: %d, Result value: %d", head.Val, result.Val))
head.Next.Next = head // adicionando o head ao next do "ultimo elemento", no exemplo: adicionando o '2' como NEXT do '3'
head.Next = nil // zerando o 'NEXT' do head
return result
}
|
package com.example.loginsignup
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.loginsignup.databinding.ActivityOpenNotesBinding
import com.example.loginsignup.databinding.DialogEditNoteBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class OpenNotes : AppCompatActivity(), NoteAdapter.OnItemClickListener {
private val binding by lazy {
ActivityOpenNotesBinding.inflate(layoutInflater)
}
private lateinit var databaseReference: DatabaseReference
private lateinit var auth: FirebaseAuth
private lateinit var recyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
recyclerView = binding.recylerview
recyclerView.layoutManager = LinearLayoutManager(this)
databaseReference = FirebaseDatabase.getInstance().reference
auth = FirebaseAuth.getInstance()
val currentUser = auth.currentUser
currentUser?.let { user ->
val noteReference = databaseReference.child("Users").child(user.uid).child("Notes")
noteReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val notelist = mutableListOf<AddNoteItem>()
for (noteSnapShot in snapshot.children) {
val note = noteSnapShot.getValue(AddNoteItem::class.java)
note?.let {
notelist.add(it)
}
}
notelist.reverse()
val adapter = NoteAdapter(notelist, this@OpenNotes)
recyclerView.adapter = adapter
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
override fun onEditClick(noteId: String, title: String, description: String) {
val dialogBinding = DialogEditNoteBinding.inflate(LayoutInflater.from(this))
val dialog = AlertDialog.Builder(this).setView(dialogBinding.root)
.setTitle("Edit Notes")
// .setPositiveButton("Save") { dialog, _ ->
// val newTitle = dialogBinding.etEditTitle.text.toString()
// val newDescription = dialogBinding.etEditDes.text.toString()
// editNoteDatabase(noteId, newTitle, newDescription)
// dialog.dismiss()
// }
// .setNegativeButton("Cancel") { dialog, _ ->
// dialog.dismiss()
// }
.create()
//if u want to edit the existing text then use this
// dialogBinding.etEditTitle.setText(title)
// dialogBinding.etEditDes.setText(description)
dialogBinding.btnSave.setOnClickListener{
val newTitle = dialogBinding.etEditTitle.text.toString()
val newDescription = dialogBinding.etEditDes.text.toString()
editNoteDatabase(noteId, newTitle, newDescription)
dialog.dismiss()
}
dialogBinding.btnCancel.setOnClickListener{
dialog.dismiss()
}
dialog.show()
}
private fun editNoteDatabase(noteId: String, newTitle: String, newDescription: String) {
val currentUser = auth.currentUser
currentUser?.let { user ->
val noteReference = databaseReference.child("Users")
.child(user.uid)
.child("Notes")
val updateNote = AddNoteItem(newTitle, newDescription, noteId)
noteReference.child(noteId).setValue(updateNote)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(this, "Note is Edited Successfully ✅", Toast.LENGTH_SHORT)
.show()
} else {
Toast.makeText(this, "Note is Edited Unsuccessfully ❌", Toast.LENGTH_SHORT)
.show()
}
}
}
}
override fun onDeleteClick(noteId: String) {
val currentUser = auth.currentUser
currentUser?.let { user ->
val noteReference = databaseReference.child("Users")
.child(user.uid)
.child("Notes")
noteReference.child(noteId).removeValue()
}
}
}
|
# Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import numpy as np
from omni.isaac.examples.base_sample import BaseSample
from omni.isaac.core.objects import DynamicCuboid
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.core.robots import Robot
import carb
import omni.appwindow # Contains handle to keyboard
# from omni.isaac.quadruped.robots import Unitree
from omni.isaac.examples.isaac_extension_examples.example6_custom_robot import Unitree
from omni.isaac.core.utils.nucleus import get_url_root
from omni.isaac.core.utils.nucleus import get_nvidia_asset_root_path
from omni.isaac.core.utils.prims import get_prim_at_path, define_prim
# Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html
class HelloWorld(BaseSample):
def __init__(self) -> None:
super().__init__()
self._world_settings["stage_units_in_meters"] = 1.0
self._world_settings["physics_dt"] = 1.0 / 400.0
self._world_settings["rendering_dt"] = 20.0 / 400.0
self._enter_toggled = 0
self._base_command = [0.0, 0.0, 0.0, 0]
self._event_flag = False
# bindings for keyboard to command
self._input_keyboard_mapping = {
# forward command
"NUMPAD_8": [1.5, 0.0, 0.0],
"UP": [1.5, 0.0, 0.0],
# back command
"NUMPAD_2": [-1.5, 0.0, 0.0],
"DOWN": [-1.5, 0.0, 0.0],
# left command
"NUMPAD_6": [0.0, -1.0, 0.0],
"RIGHT": [0.0, -1.0, 0.0],
# right command
"NUMPAD_4": [0.0, 1.0, 0.0],
"LEFT": [0.0, 1.0, 0.0],
# yaw command (positive)
"NUMPAD_7": [0.0, 0.0, 1.0],
"N": [0.0, 0.0, 1.0],
# yaw command (negative)
"NUMPAD_9": [0.0, 0.0, -1.0],
"M": [0.0, 0.0, -1.0],
}
return
def setup_scene(self) -> None:
world = self.get_world()
self._world.scene.add_default_ground_plane(
z_position=0,
name="default_ground_plane",
prim_path="/World/defaultGroundPlane",
static_friction=0.2,
dynamic_friction=0.2,
restitution=0.01,
)
self._go1 = world.scene.add(
Unitree(
prim_path="/World/Go1",
name="Go1",
position=np.array([0, 0, 0.400]),
physics_dt=self._world_settings["physics_dt"],
model="Go1Velo"
# model="Go1Pure"
)
)
return
async def setup_post_load(self) -> None:
self._world = self.get_world()
self._appwindow = omni.appwindow.get_default_app_window()
self._input = carb.input.acquire_input_interface()
self._keyboard = self._appwindow.get_keyboard()
# self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._sub_keyboard_event)
self._world.add_physics_callback("sending_actions", callback_fn=self.on_physics_step)
await self._world.play_async()
return
async def setup_pre_reset(self) -> None:
self._event_flag = False
return
async def setup_post_reset(self) -> None:
await self._world.play_async()
self._go1.check_dc_interface()
self._go1.set_state(self._go1._default_a1_state)
return
def on_physics_step(self, step_size) -> None:
if self._event_flag:
self._go1._qp_controller.switch_mode()
self._event_flag = False
# self._go1.advance(step_size, self._base_command)
self._go1.advance(step_size, self._base_command, auto_start=False)
def _sub_keyboard_event(self, event, *args, **kwargs) -> bool:
"""Subscriber callback to when kit is updated."""
# reset event
self._event_flag = False
# when a key is pressedor released the command is adjusted w.r.t the key-mapping
if event.type == carb.input.KeyboardEventType.KEY_PRESS:
# on pressing, the command is incremented
if event.input.name in self._input_keyboard_mapping:
self._base_command[0:3] += np.array(self._input_keyboard_mapping[event.input.name])
self._event_flag = True
# enter, toggle the last command
if event.input.name == "ENTER" and self._enter_toggled is False:
self._enter_toggled = True
if self._base_command[3] == 0:
self._base_command[3] = 1
else:
self._base_command[3] = 0
self._event_flag = True
elif event.type == carb.input.KeyboardEventType.KEY_RELEASE:
# on release, the command is decremented
if event.input.name in self._input_keyboard_mapping:
self._base_command[0:3] -= np.array(self._input_keyboard_mapping[event.input.name])
self._event_flag = True
# enter, toggle the last command
if event.input.name == "ENTER":
self._enter_toggled = False
# since no error, we are fine :)
return True
|
<div class="row">
<div class="col-6">
<h3>Exploring this with .call, .apply and .bind</h3>
<a
href="https://app.ultimatecourses.com/course/typescript-masterclass/exploring-this-with-call-apply-and-bind"
>
Ultime course. Exploring “this” with .call, .apply and .bind video
</a>
<p>
<b>.call</b>The .call invokes the function and method changes the
<b>this</b> scope of the function and pass some arguments as a string,
number, etc
</p>
<p>
<b>.apply</b>The .apply invokes the function and method changes the
<b>this</b> scope of the function and pass some arguments as an array
</p>
<p>
<b>.bind</b>The .bind doesn't invoke the function untill the function is
invoked and method changes the <b>this</b> scope of the function and pass
some arguments as a string, number, etc
</p>
</div>
<div class="col-6">
<h3>Arrow Functions and Lexical Scope</h3>
<a
href="https://app.ultimatecourses.com/course/typescript-masterclass/arrow-functions-and-lexical-scope"
>Arrow Functions and Lexical Scope</a
>
<p>Using <b>function() (lexical scope)</b> changes the scope</p>
<p>Using <b>() => (Arrow Function)</b> doesn't change the scope</p>
</div>
</div>
|
using MediatR;
using Moq;
using Takecontrol.Matches.Application.Contracts.Persistence.Matches;
using Takecontrol.Matches.Application.Contracts.Persistence.MatchPlayers;
using Takecontrol.Matches.Application.Contracts.Primitives;
using Takecontrol.Matches.Application.Features.Matches.Commands.JoinToMatch;
using Takecontrol.Matches.Domain.Models.MatchPlayers;
using Takecontrol.Matches.Domain.Models.MatchPlayers.ValueObjects;
using Takecontrol.Shared.Application.Exceptions;
using Takecontrol.Shared.Application.Messages.Matches;
using Takecontrol.Shared.Tests.Constants;
using Match = Takecontrol.Matches.Domain.Models.Matches.Match;
namespace Takecontrol.Matches.Application.Tests.Features.Matches.Commands.JoinToMatch;
[Trait("Category", Category.UnitTest)]
public class JoinToMatchCommandHandlerTests
{
private readonly Mock<IUnitOfWork> _unitOfWork;
private readonly Mock<IMatchReadRepository> _matchReadRepository;
private readonly Mock<IMatchPlayerReadRepository> _matchPlayerReadRepository;
public JoinToMatchCommandHandlerTests()
{
_unitOfWork = new();
_matchReadRepository = new();
_matchPlayerReadRepository = new();
}
[Fact]
public async Task Should_failed_when_player_is_trying_to_register_to_an_existing_match()
{
Match? match = null;
_matchReadRepository.Setup(x => x.GetByIdAsync(It.IsAny<Guid>()))
.ReturnsAsync(match);
var handler = new JoinToMatchCommandHandler(_unitOfWork.Object, _matchReadRepository.Object, _matchPlayerReadRepository.Object);
var command = new JoinToMatchCommand(Guid.NewGuid(), Guid.NewGuid());
await Assert.ThrowsAsync<NotFoundException>(async () => await handler.Handle(command, default!));
}
[Fact]
public async Task Should_failed_when_player_tries_to_register_in_a_closed_match()
{
var match = Match.Create(Guid.NewGuid(), Guid.NewGuid());
match.Close();
_matchReadRepository.Setup(x => x.GetByIdAsync(It.IsAny<Guid>()))
.ReturnsAsync(match);
var handler = new JoinToMatchCommandHandler(_unitOfWork.Object, _matchReadRepository.Object, _matchPlayerReadRepository.Object);
var command = new JoinToMatchCommand(Guid.NewGuid(), Guid.NewGuid());
await Assert.ThrowsAsync<ConflictException>(async () => await handler.Handle(command, default!));
}
[Fact]
public async Task Should_failed_when_player_was_already_registered_in_a_match()
{
var match = Match.Create(Guid.NewGuid(), Guid.NewGuid());
var matchPlayer = MatchPlayer.Create(Guid.NewGuid(), Guid.NewGuid());
_matchReadRepository.Setup(x => x.GetByIdAsync(It.IsAny<Guid>()))
.ReturnsAsync(match);
_matchPlayerReadRepository.Setup(x => x.GetMatchPlayerByPlayerIdAndMatchId(It.IsAny<Guid>(), It.IsAny<Guid>()))
.ReturnsAsync(matchPlayer);
var handler = new JoinToMatchCommandHandler(_unitOfWork.Object, _matchReadRepository.Object, _matchPlayerReadRepository.Object);
var command = new JoinToMatchCommand(Guid.NewGuid(), Guid.NewGuid());
await Assert.ThrowsAsync<ConflictException>(async () => await handler.Handle(command, default!));
}
[Fact]
public async Task Should_register_the_player_and_close_the_match_when_player_is_the_last_one_to_join()
{
var match = Match.Create(Guid.NewGuid(), Guid.NewGuid());
MatchPlayer? matchPlayer = null;
var matchPlayerForList = MatchPlayer.Create(Guid.NewGuid(), Guid.NewGuid());
var matchWriteRepository = new Mock<IAsyncWriteRepository<Match>>();
var matchPlayerWriteRepository = new Mock<IAsyncWriteRepository<MatchPlayer>>();
_matchReadRepository.Setup(x => x.GetByIdAsync(It.IsAny<Guid>()))
.ReturnsAsync(match);
_matchPlayerReadRepository.Setup(x => x.GetMatchPlayerByPlayerIdAndMatchId(It.IsAny<Guid>(), It.IsAny<Guid>()))
.ReturnsAsync(matchPlayer);
_matchPlayerReadRepository.Setup(x => x.GetMatchPlayersByMatchId(It.IsAny<Guid>()))
.ReturnsAsync(new List<MatchPlayer> { matchPlayerForList, matchPlayerForList, matchPlayerForList });
_unitOfWork.Setup(c => c.Repository<Match>()).Returns(matchWriteRepository.Object);
_unitOfWork.Setup(c => c.Repository<MatchPlayer>()).Returns(matchPlayerWriteRepository.Object);
var handler = new JoinToMatchCommandHandler(_unitOfWork.Object, _matchReadRepository.Object, _matchPlayerReadRepository.Object);
var command = new JoinToMatchCommand(Guid.NewGuid(), Guid.NewGuid());
var result = await handler.Handle(command, default);
Assert.Equal(result, Unit.Value);
_unitOfWork.Verify(x => x.Repository<Match>().Update(It.IsAny<Match>()), Times.Once);
_unitOfWork.Verify(x => x.Repository<MatchPlayer>().AddAsync(It.IsAny<MatchPlayer>()), Times.Once);
_unitOfWork.Verify(x => x.CompleteAsync(), Times.Once);
}
[Fact]
public async Task Should_register_the_player_and_match_will_remains_opened_when_player_is_not_the_last_one()
{
var match = Match.Create(Guid.NewGuid(), Guid.NewGuid());
MatchPlayer? matchPlayer = null;
var matchPlayerForList = MatchPlayer.Create(Guid.NewGuid(), Guid.NewGuid());
var matchWriteRepository = new Mock<IAsyncWriteRepository<Match>>();
var matchPlayerWriteRepository = new Mock<IAsyncWriteRepository<MatchPlayer>>();
_matchReadRepository.Setup(x => x.GetByIdAsync(It.IsAny<Guid>()))
.ReturnsAsync(match);
_matchPlayerReadRepository.Setup(x => x.GetMatchPlayerByPlayerIdAndMatchId(It.IsAny<Guid>(), It.IsAny<Guid>()))
.ReturnsAsync(matchPlayer);
_matchPlayerReadRepository.Setup(x => x.GetMatchPlayersByMatchId(It.IsAny<Guid>()))
.ReturnsAsync(new List<MatchPlayer> { matchPlayerForList, matchPlayerForList });
_unitOfWork.Setup(c => c.Repository<Match>()).Returns(matchWriteRepository.Object);
_unitOfWork.Setup(c => c.Repository<MatchPlayer>()).Returns(matchPlayerWriteRepository.Object);
var handler = new JoinToMatchCommandHandler(_unitOfWork.Object, _matchReadRepository.Object, _matchPlayerReadRepository.Object);
var command = new JoinToMatchCommand(Guid.NewGuid(), Guid.NewGuid());
var result = await handler.Handle(command, default);
Assert.Equal(result, Unit.Value);
_unitOfWork.Verify(x => x.Repository<MatchPlayer>().AddAsync(It.IsAny<MatchPlayer>()), Times.Once);
_unitOfWork.Verify(x => x.Repository<MatchPlayer>().Update(It.IsAny<MatchPlayer>()), Times.Never);
_unitOfWork.Verify(x => x.CompleteAsync(), Times.Once);
}
}
|
import React from "react";
import { withRouter } from 'react-router-dom'
import Card from "../../components/card";
import FormGroup from "../../components/form-group";
import SelectMenu from "../../components/selectMenu";
import LancamentosTable from "./lancamentosTable";
import LancamentoService from "../../app/service/lancamentoService";
import LocalStorageService from "../../app/service/localStorageService";
import * as messages from '../../components/toastr'
import {Dialog} from 'primereact/dialog'
import {Button} from 'primereact/button'
class ConsultaLancamentos extends React.Component {
state = {
ano: '',
mes: '',
tipo: '',
descricao: '',
showConfirmDialog: false,
lancamentoDeletar: {},
lancamentos: []
}
constructor() {
super();
this.service = new LancamentoService();
}
buscar = () => {
//console.log(this.state)
if(!this.state.ano) {
messages.mensagemErro('O preenchimento do campo Ano é obrigatório.')
return false;
}
const usuarioLogado = LocalStorageService.obterItem('_usuario_logado');
const lancamentoFiltro = {
ano: this.state.ano,
mes: this.state.mes,
tipo: this.state.tipo,
descricao: this.state.descricao,
usuario: usuarioLogado.id
}
this.service
.consultar(lancamentoFiltro)
.then(resposta => {
const lista = resposta.data;
if (lista.length < 1) {
messages.mensagemAlerta("Nenhum resultado encontrado!")
}
this.setState({lancamentos: lista})
})
.catch(error => {
console.log(error)
})
}
editar = (id) => {
console.log('Editando o lancamento: ',id);
this.props.history.push(`/cadastro-lancamentos/${id}`)
}
abrirConfirmacao = (lancamento) => {
console.log(lancamento);
console.log(lancamento.id);
this.lancamentoDeletar = lancamento;
console.log( this.lancamentoDeletar);
console.log( this.lancamentoDeletar.id);
//const lancamentoTeste = Lancamento;
//this.setState({lancamentoDeletar : lancamento})
//this.setState({showConfirmDialog : true, lancamentoDeletar : Lancamento});
//console.log(this.lancamentoDeletar);
this.setState({showConfirmDialog : true});
}
cancelarDelecao = () => {
this.lancamentoDeletar = {};
//this.setState({showConfirmDialog : false, lancamentoDeletar: {}})
this.setState({showConfirmDialog : false})
}
deletar = () => {
console.log('Deletando o lancamento: ',this.lancamentoDeletar);
console.log('Deletando o lancamento: ',this.lancamentoDeletar.id);
this.service
.deletar(this.lancamentoDeletar.id)
.then(response => {
const lancamentos = this.state.lancamentos;
const index = lancamentos.indexOf(this.lancamentoDeletar);
lancamentos.splice(index,1);
this.setState(lancamentos);
messages.mensagemSucesso('Lançamento deletado com sucesso!')
}).catch(error => {
messages.mensagemErro('Ocorreu um erro ao tentar deletar o lancamento!')
})
}
preparaFormularioCadastro = () => {
this.props.history.push('/cadastro-lancamentos')
}
alterarStatus = (lancamento, status) => {
this.service
.alterarStatus(lancamento.id, status)
.then( response => {
const lancamentos = this.state.lancamentos;
const index = lancamentos.indexOf(lancamento);
if(index !== -1) {
lancamento['status'] = status;
lancamento[index] = lancamento;
this.setState({lancamento})
}
messages.mensagemSucesso("Status atualizado com sucesso!")
})
}
render() {
const meses = this.service.obterListaMeses();
const tipos = this.service.obterListaTipos();
const confirmDialogFooter = (
<div>
<Button label="Confirmar" icon="pi pi-check" onClick={this.deletar} />
<Button label="Cancelar" icon="pi pi-times" onClick={this.cancelarDelecao} className="p-button-secondary"/>
</div>
)
//const lancamentos = [
// {id: 1, descricao: 'Salário', valor: 5000, mes: 1, tipo: 'Receita', status: 'Efetivado' }
// ]
return (
<Card title="Consulta Lançamentos">
<div className="row">
<div className="col-md-6">
<div className="bs-component">
<FormGroup htmlFor="inputAno" label="Ano: *">
<input tyoe="text"
className="form-control"
id="inputAno"
value={this.state.ano}
onChange={e => this.setState({ano: e.target.value})}
placeholder="Digite o Ano"/>
</FormGroup>
<FormGroup htmlFor="inputMes" label="Mês: ">
<SelectMenu id="inputMes"
value={this.state.mes}
onChange={e => this.setState({mes: e.target.value})}
className="form-control"
lista={meses} />
</FormGroup>
<FormGroup htmlFor="inputDesc" label="Descrição: *">
<input tyoe="text"
className="form-control"
id="inputDesc"
value={this.state.descricao}
onChange={e => this.setState({descricao: e.target.value})}
placeholder="Digite a Descrição"/>
</FormGroup>
<FormGroup htmlFor="inputTipo" label="Tipo Lançamento: ">
<SelectMenu id="inputTipo"
value={this.state.tipo}
onChange={e => this.setState({tipo: e.target.value})}
className="form-control"
lista={tipos} />
</FormGroup>
<br/>
<button onClick={this.buscar}
type="button"
className="btn btn-success">
<i className="pi pi-search"></i>Buscar</button>
<button onClick={this.preparaFormularioCadastro}
type="button"
className="btn btn-danger">
<i className="pi pi-plus"></i>Cadastrar</button>
</div>
</div>
</div>
<br />
<div className="row">
<div className="col-md-12">
<div className="bs-component">
<LancamentosTable lancamentos={this.state.lancamentos}
deleteAction={this.abrirConfirmacao}
editAction={this.editar}
alterarStatus={this.alterarStatus}/>
</div>
</div>
</div>
<div>
<Dialog header="Confirmação"
visible={this.state.showConfirmDialog}
style={{with: '50vw'}}
footer={confirmDialogFooter}
modal={true}
onHide={() => this.setState({showConfirmDialog: false})}>
Confirma a exclusão deste Lançamento?
</Dialog>
</div>
</Card>
)
}
}
export default withRouter(ConsultaLancamentos);
|
*{
font-family:'Roboto',sans-serif;
}
body{
margin:0;
}
/* FONTS */
$font-1 : 1em;
$font-2 : 2em;
$font-2-5 : 2.5em;
$font-3 : 3em;
$font-4 : 4em;
$font-5 : 5em;
/* COLORS */
$lightblue : #799bce;
$white : #FFF;
$blue : #5066ce;
$grey : #9da1a7;
$lightgrey : #eee;
/* MIXINS */
@mixin flex($type){
display:flex;
flex-direction:$type;
}
@mixin flex($type){
display:flex;
flex-direction:$type;
}
@mixin boxShadow{
-webkit-box-shadow: 0px 2px 15px -1px rgba(0,0,0,0.75);
-moz-box-shadow: 0px 2px 15px -1px rgba(0,0,0,0.75);
box-shadow: 0px 2px 15px -1px rgba(0,0,0,0.75);
}
@mixin pointer{
cursor:pointer;
}
@mixin transition{
transition:all 0.25s ease;
}
/* ---------------------- */
.mainContainer{
background-color:$lightblue;
width:100%;
min-height:100vh;
@include flex(row);
align-items:center;
&__pricingContainer{
width:60%;
@include flex(row);
flex-wrap:nowrap;
background-color:$white;
justify-content:center;
align-items:flex-start;
border-radius:8px;
margin:0 auto;
padding:40px;
@include boxShadow;
.mainContainer__columna{
text-align:center;
padding:20px 50px;
transition:all 0.25s ease;
border-radius:6px;
flex-grow: 1;
flex-basis: 0;
@include pointer;
@include transition;
&:hover{
background-color:$lightgrey;
}
& img{
width:80px;
}
& h2{
letter-spacing:6px;
font-weight:700;
color:$blue;
}
.columna__descripcion{
font-weight:700;
color:$grey;
min-height:50px;
}
.columna__precio{
color:$blue;
& span:first-child{
position:relative;
top:-15px;
right:-5px;
font-weight:700;
}
& span:last-child{
font-size:$font-2-5;
font-weight:bold;
}
}
}
}
}
@media (max-width:1200px){
.mainContainer{
&__pricingContainer{
width:85%;
}
}
}
@media (max-width:768px){
.mainContainer{
padding:30px 0;
&__pricingContainer{
width:80%;
padding:0;
align-items:center;
@include flex(column);
.mainContainer__columna{
h2{
margin:0;
}
.columna__descripcion{
margin:15px;
}
.columna__precio{
margin:0;
}
}
}
}
}
|
import React from 'react'
import './styles/App.css'
import { BrowserRouter } from 'react-router-dom'
import Navbar from './components/UI/Navbar/Navbar'
import { AppRouterIndex } from './router/router-index'
import { AuthContext } from './context/index-context'
function App() {
const [isAuth, setIsAuth] = React.useState(false)
const [isLoading, setLoading] = React.useState(true)
console.log(isLoading)
React.useEffect(() => {
if (localStorage.getItem('auth')) {
setIsAuth(true)
localStorage.setItem('auth', 'true')
}
setLoading(false)
}, [])
return (
<AuthContext.Provider value={{ isAuth, setIsAuth, setLoading }}>
<BrowserRouter>
<Navbar />
<AppRouterIndex /> {/* применяется после коммита 'Step #32'*/}
</BrowserRouter>
</AuthContext.Provider>
)
}
export default App
|
#pragma once
#include "Block.h"
#include <list>
namespace AnimData {
class StringListBlock : public Block {
std::vector<std::string> strings;
public:
StringListBlock() {}
StringListBlock(size_t size) { strings.reserve(size); }
StringListBlock(const std::vector<std::string>& _strings) :
strings(_strings)
{
}
void append(const std::string& file) {
strings.push_back(file);
}
void remove(int index) {
strings.erase(strings.begin() + index);
}
void setStrings(std::vector<std::string> strings) {
this->strings = strings;
}
virtual std::vector<std::string> getStrings() {
return strings;
}
virtual size_t size() {
return strings.size();
}
virtual void resize(size_t new_size) {
return strings.resize(new_size);
}
virtual void reserve(size_t new_size) {
return strings.reserve(new_size);
}
virtual std::string& operator[](int index) {
return strings[index];
}
void clear() {
strings.clear();
}
virtual std::string getBlock() {
std::string out = "";
if (strings.size() == 0) return out;
for (std::string s : strings) {
out += s + "\n";
}
return out;
}
virtual void parseBlock(scannerpp::Scanner& input) {
while (input.hasNextLine()) {
strings.push_back(input.nextLine());
}
}
};
}
|
import React from 'react'
import { List, Avatar, Space } from 'antd';
import { MessageOutlined, LikeOutlined, StarOutlined } from '@ant-design/icons';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import {remove} from './firebase';
// {
// href: '#',
// title: `ant design part ${i}`,
// avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
// description:
// 'Ant Design, a design language for background applications, is refined by Ant UED Team.',
// content:
// 'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.',
// photo:''
// }
const IconText = ({ icon, text }) => (
<Space>
{React.createElement(icon)}
{text}
</Space>
);
export default function Item({item}) {
return (
<List.Item
key={item.title}
actions={[
<a onClick={() => remove(item.id)}>
<IconText icon={LikeOutlined} text="156" key="list-vertical-like-o" />,
</a>
]}
extra={
item.photo && <img
width={272}
alt="logo"
src={item.photo}
/>
}
>
<List.Item.Meta
avatar={<Avatar src={item.user.photoUrl} />}
title={<a href={item.href}>{item.title}</a>}
description={item.description}
/>
{item.content}
</List.Item>
)
}
|
package specs
import (
"auth_ms/src/service"
"os"
"testing"
)
func TestHashPassword(t *testing.T) {
err := os.Setenv("ENCRYPT_SALT", "my_valid_salt")
if err != nil {
t.Error("failed to configure env")
}
defer os.Unsetenv("ENCRYPT_SALT")
password := "testpassword"
hashed, err := service.HashPassword(password)
if err != nil {
t.Errorf("Unexpected error hashing password: %s", err)
}
if hashed == "" {
t.Error("Expected non-empty hashed password, got empty string")
}
err = os.Setenv("ENCRYPT_SALT", "")
if err != nil {
t.Error("failed to configure env")
}
emptySaltHashed, emptySaltErr := service.HashPassword(password)
if emptySaltErr == nil {
t.Error("Expected error due to empty ENCRYPT_SALT, got nil")
}
if emptySaltHashed != "" {
t.Error("Expected empty hashed password, got non-empty string")
}
}
func TestVerifyPassword(t *testing.T) {
err := os.Setenv("ENCRYPT_SALT", "my_valid_salt")
if err != nil {
t.Error("failed to configure env")
}
defer os.Unsetenv("ENCRYPT_SALT")
password := "testpassword"
hashed, _ := service.HashPassword(password)
valid, err := service.VerifyPassword(password, hashed)
if err != nil {
t.Errorf("Unexpected error verifying password: %s", err)
}
if !valid {
t.Error("Expected valid password, got invalid")
}
err = os.Setenv("ENCRYPT_SALT", "")
if err != nil {
t.Error("failed to configure env")
}
emptySaltValid, emptySaltErr := service.VerifyPassword(password, hashed)
if emptySaltErr == nil {
t.Error("Expected error due to empty ENCRYPT_SALT, got nil")
}
if emptySaltValid {
t.Error("Expected invalid password due to empty ENCRYPT_SALT, got valid")
}
invalidHash := "invalidhash"
invalidHashValid, invalidHashErr := service.VerifyPassword(password, invalidHash)
if invalidHashErr == nil {
t.Error("Expected error due to invalid hash, got nil")
}
if invalidHashValid {
t.Error("Expected invalid password due to invalid hash, got valid")
}
}
|
import java.util.*;
/**
* Container class to different classes, that makes the whole
* set of classes one class formally.
*/
public class GraphTask {
public static void main(String[] args) {
GraphTask a = new GraphTask();
a.run();
}
/**
* Actual main method to run examples and everything.
*/
public void run() {
Graph g = new Graph("G");
g.createRandomSimpleGraph(5, 5);
System.out.println(g);
}
/**
* Vertex represents one point in a graph. It has Arcs that point to other vertices.
*/
class Vertex {
private String id;
private Vertex next;
private Arc first;
private int info = 0;
Vertex(String s, Vertex v, Arc e) {
id = s;
next = v;
first = e;
}
Vertex(String s) {
this(s, null, null);
}
public Arc getArc() {
return first;
}
@Override
public String toString() {
return id;
}
}
/**
* Arc represents one arrow in the graph. Two-directional edges are
* represented by two Arc objects (for both directions).
*/
class Arc {
private String id;
private Vertex target;
private Arc next;
Arc(String s, Vertex v, Arc a) {
id = s;
target = v;
next = a;
}
Arc(String s) {
this(s, null, null);
}
@Override
public String toString() {
return id;
}
}
/**
* A graph is made out of vertices and arcs.
* It contains all of the main functions for
* finding the smallest cycle and creating a graph.
*/
class Graph {
private String id;
private Vertex first;
private int info = 0;
private Vertex startingPoint;
Graph(String s, Vertex v) {
id = s;
first = v;
startingPoint = null;
}
Graph(String s) {
this(s, null);
}
@Override
public String toString() {
String nl = System.getProperty("line.separator");
StringBuffer sb = new StringBuffer(nl);
sb.append(id);
sb.append(nl);
Vertex v = first;
while (v != null) {
sb.append(v.toString());
sb.append(" -->");
Arc a = v.first;
while (a != null) {
sb.append(" ");
sb.append(a.toString());
sb.append(" (");
sb.append(v.toString());
sb.append("->");
sb.append(a.target.toString());
sb.append(")");
a = a.next;
}
sb.append(nl);
v = v.next;
}
return sb.toString();
}
public Vertex createVertex(String vid) {
Vertex res = new Vertex(vid);
res.next = first;
first = res;
return res;
}
public Arc createArc(String aid, Vertex from, Vertex to) {
Arc res = new Arc(aid);
res.next = from.first;
from.first = res;
res.target = to;
return res;
}
/**
* Create a connected undirected random tree with n vertices.
* Each new vertex is connected to some random existing vertex.
*
* @param n number of vertices added to this graph
*/
public void createRandomTree(int n) {
if (n <= 0)
return;
Vertex[] varray = new Vertex[n];
for (int i = 0; i < n; i++) {
varray[i] = createVertex("v" + String.valueOf(n - i));
if (i > 0) {
int vnr = (int) (Math.random() * i);
createArc("a" + varray[vnr].toString() + "_"
+ varray[i].toString(), varray[vnr], varray[i]);
createArc("a" + varray[i].toString() + "_"
+ varray[vnr].toString(), varray[i], varray[vnr]);
} else {
}
}
}
/**
* Create an adjacency matrix of this graph.
* Side effect: corrupts info fields in the graph
*
* @return adjacency matrix
*/
public int[][] createAdjMatrix() {
info = 0;
Vertex v = first;
while (v != null) {
v.info = info++;
v = v.next;
}
int[][] res = new int[info][info];
v = first;
while (v != null) {
int i = v.info;
Arc a = v.first;
while (a != null) {
int j = a.target.info;
res[i][j]++;
a = a.next;
}
v = v.next;
}
return res;
}
/**
* Create a connected simple (undirected, no loops, no multiple
* arcs) random graph with n vertices and m edges.
*
* @param n number of vertices
* @param m number of edges
*/
public void createRandomSimpleGraph(int n, int m) {
if (n <= 0)
return;
if (n > 2500)
throw new IllegalArgumentException("Too many vertices: " + n);
if (m < n - 1 || m > n * (n - 1) / 2)
throw new IllegalArgumentException
("Impossible number of edges: " + m);
first = null;
createRandomTree(n); // n-1 edges created here
Vertex[] vert = new Vertex[n];
Vertex v = first;
int c = 0;
while (v != null) {
vert[c++] = v;
v = v.next;
}
int[][] connected = createAdjMatrix();
int edgeCount = m - n + 1; // remaining edges
while (edgeCount > 0) {
int i = (int) (Math.random() * n); // random source
int j = (int) (Math.random() * n); // random target
if (i == j)
continue; // no loops
if (connected[i][j] != 0 || connected[j][i] != 0)
continue; // no multiple edges
Vertex vi = vert[i];
Vertex vj = vert[j];
createArc("a" + vi.toString() + "_" + vj.toString(), vi, vj);
connected[i][j] = 1;
createArc("a" + vj.toString() + "_" + vi.toString(), vj, vi);
connected[j][i] = 1;
edgeCount--; // a new edge happily created
}
}
/**
* Main function of the exercise
* Check if the given vertex could have a cycle then starts searching using other functions.
*
* @return List of vertices that are used in the final cycle
*/
public List<Arc> solveShortestCycle(String vertexID) {
this.startingPoint = strVertexToVertex(vertexID);
int numberOfArcs = 0;
List<Vertex> surroundingVertices = new ArrayList<>();
//Check how many arc the vertex has. If it finds less 2 arcs, then it can't be in a cycle.
Arc tempArc = startingPoint.getArc();
while (tempArc != null) {
surroundingVertices.add(tempArc.target);
numberOfArcs++;
tempArc = tempArc.next;
}
if (numberOfArcs < 2) {
System.out.println(String.format("Vertex: '%s' is not in a cycle", startingPoint.id));
return Collections.emptyList();
}
//Using given combinations we can create a list of all the possible paths.
List<int[]> allCombinations = generateCombinations(surroundingVertices);
//A Set so there are no repeats
Set<List<Vertex>> allPathsSet = new HashSet<>();
int[] vertexCombo;
//Generate all the combinations
for (int i = 0; i < allCombinations.size(); i++) {
vertexCombo = allCombinations.get(i);
allPathsSet.addAll(findAllPaths(surroundingVertices.get(vertexCombo[0]),
surroundingVertices.get(vertexCombo[1])));
}
ArrayList<List<Vertex>> allPathsList = new ArrayList<>(allPathsSet);
return findShortestCycle(allPathsList);
}
/**
* Create combinations based on the vertexes that are adjacent to the main vertex
*
* @return list of combinations
*/
public List<int[]> generateCombinations(List<Vertex> vertexList) {
int n = vertexList.size();
List<int[]> combinations = new ArrayList<>();
int[] combination = new int[2];
for (int i = 0; i < 2; i++) {
combination[i] = i;
}
while (combination[2 - 1] < n) {
combinations.add(combination.clone());
int t = 2 - 1;
while (t != 0 && combination[t] == n - 2 + t) {
t--;
}
combination[t]++;
for (int i = t + 1; i < 2; i++) {
combination[i] = combination[i - 1] + 1;
}
}
//returns the id combinations of the given vertices.
return combinations;
}
//https://www.baeldung.com/java-combinations-algorithm
/**
* Find all the cycles that pass through the given path.
*
* @return List of vertices that are used in the final cycle
*/
public List<Arc> findShortestCycle(ArrayList<List<Vertex>> paths) {
//filter out all the paths that include the starting point of the circle.
List<Vertex> tempVertexList = null;
ArrayList<List<Vertex>> cleanPathList = new ArrayList<>();
for (int i = 0; i < paths.size(); i++) {
tempVertexList = paths.get(i);
if (!tempVertexList.contains(startingPoint)) {
cleanPathList.add(tempVertexList);
}
}
int distance = Integer.MAX_VALUE / 4;
int buffDistance;
//Take the filtered list and find the smallest distance
for (int i = 0; i < cleanPathList.size(); i++) {
buffDistance = cleanPathList.get(i).size() + 1;
if (distance > buffDistance) {
tempVertexList = cleanPathList.get(i);
}
distance = Math.min(distance, cleanPathList.get(i).size() + 1);
}
//If distance didn't change from the MAX_VALUE then it means it's not in a cycle.
if (distance == Integer.MAX_VALUE / 4) {
System.out.println(String.format("Vertex: '%s' is not in a cycle", startingPoint.id));
return Collections.emptyList();
}
return findArcVariant(tempVertexList, distance);
}
/**
* Prints out the final answer and returns list of vertexes that were used ifn the list.
*
* @return List of vertices that are used in the final cycle
*/
public List<Arc> findArcVariant(List<Vertex> path, int distance) {
StringBuffer finalAnswer = new StringBuffer();
finalAnswer.append(startingPoint.id);
finalAnswer.append("->");
for (int i = 0; i < path.size(); i++) {
finalAnswer.append(path.get(i));
finalAnswer.append("->");
}
finalAnswer.append(startingPoint.id);
path.add(0, startingPoint);
path.add(startingPoint);
List<Arc> finalArcList = new ArrayList<>();
for (int i = 1; i < path.size(); i++) {
Arc tempArc = path.get(i - 1).first;
while (tempArc.next != null) {
if (tempArc.target == path.get(i)) {
finalArcList.add(tempArc);
}
tempArc = tempArc.next;
}
}
System.out.println((String.format("Length of the shortest cycle that passes through vertex '%s' is <%d>" +
" \n An example of such cycle: [%s]", startingPoint.id, distance, finalAnswer.toString())));
return finalArcList;
}
/**
* Find the shortest distance between two vertices using BFS (Breadth-First Search)
*
* @return list of available paths
*/
public Set<List<Vertex>> findAllPaths(Vertex start, Vertex end) {
Set<List<Vertex>> paths = new HashSet<>();
LinkedList<Vertex> queue = new LinkedList<>();
Set<Vertex> visited = new HashSet<>();
Map<Vertex, Vertex> parentVertices = new HashMap<>();
Vertex s = start;
visited.add(s);
queue.add(s);
// starts discovering new elements 1 by 1
while (!queue.isEmpty()) {
s = queue.poll();
Arc i = s.first;
while (i != null) {
Vertex n = i.target;
if (n == end) {
parentVertices.put(n, s);
List<Vertex> shortestPath = new ArrayList<>();
Vertex node = end;
if (node == parentVertices.get(parentVertices.get(node))) {
break;
}
while (node != null) {
shortestPath.add(node);
node = parentVertices.get(node);
}
Collections.reverse(shortestPath);
//The length of the path traveled must be at least 1
if (shortestPath.size() >= 1) {
paths.add(shortestPath);
}
}
//Check if we have already visited the node
if (!visited.contains(n)) {
parentVertices.put(n, s);
visited.add(n);
queue.add(n);
}
i = i.next;
}
}
return paths;
}
// https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/
/**
* Turns the given vertexID to the corresponding vertex;
*
* @return corresponding Vertex
*/
public Vertex strVertexToVertex(String vertexName) {
Vertex curVertex = first;
while (curVertex != null) {
if (curVertex.id.equals(vertexName)) {
return curVertex;
}
curVertex = curVertex.next;
}
// When a vertex match isn't returned throw an exception
throw new GraphException(String.format("%s vertex doesn't exist in this graph", vertexName));
}
}
}
class GraphException extends RuntimeException {
GraphException(String message) {
super(message);
}
}
|
import React from 'react';
// swiper
import { Swiper, SwiperSlide } from 'swiper/react';
// Swiper styles
import 'swiper/css';
import 'swiper/css/effect-fade';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import '../css/styles.css';
// modules
import { EffectFade, Navigation, Pagination } from 'swiper/modules';
import { Link } from 'react-router-dom';
// redux
import { useDispatch, useSelector } from 'react-redux';
import { deleteCard } from '../store/slices/productBasketslice';
const Basket = () => {
const { card } = useSelector((store) => store.card);
const dispatch = useDispatch()
return (
<div className='pt-36r pb-60r'>
<div className="container">
<h1 className="mb-60r">Savatcha</h1>
{/* products */}
<ul className="grid grid-cols-4 gap-8 max-1400:grid-cols-3 max-1050:grid-cols-2 max-730:grid-cols-1">
{
card.length > 0 ? card.map((product, index) => {
return (
<li key={index} className="flex flex-col w-full product hover:active-hover">
<Swiper className="product-img-swiper relative rounded-2.5xl w-full mb-4 max-730:h-96 h-310px max-470:h-64 max-360:h-223px"
effect={'fade'}
slidesPerView={1}
spaceBetween={30}
loop={true}
pagination={{
clickable: true,
}}
navigation={true}
modules={[EffectFade, Pagination, Navigation]}
>
{/* swiper images */}
{
product.images.map((img) => {
return (
img.id <= 3 &&
<SwiperSlide key={img.id} className="flex items-center justify-center relative">
<img className='absolute brightness-95 img w-full min-h-full object-cover object-center transition-transform-2' width={416} height={310} src={img.img} alt="furniture image" />
<div className="absolute tabs-wrapper top-5 right-5 transition-opacity-2">
<div className="flex-center space-x-3 ml-auto">
{
product.akciya &&
<span className="red-tab">Aksiya</span>
}
{
product.new &&
<span className="green-tab">yangi</span>
}
{
product.available &&
<span className="white-tab">mavjud</span>
}
{
product.order &&
<span className="gray-tab">sotuvda</span>
}
</div>
</div>
</SwiperSlide>
)
})
}
</Swiper>
{/* top */}
<div className="flex-c-b mb-2 text-regular-14 text-primary-gray-70">
<span>{product.type}</span>
<span>ID:{product.productId}</span>
</div>
{/* title */}
<h3 className="mb-4 text-regular-20">{product.productTitle}</h3>
{/* list */}
<ul className="text-regular-14 text-primary-gray-70 space-y-2.5 mb-auto">
<li className="flex items-end">
<span>Davlati</span>
<div className="grow border-t-2 mx-1 mb-0.5 border-primary-gray-70 border-dotted"></div>
<span>{product.details.country}</span>
</li>
<li className="flex items-end">
<span>Ustki material</span>
<div className="grow border-t-2 mx-1 mb-0.5 border-primary-gray-70 border-dotted"></div>
<ul className='flex-center gap-0.5'>
{
product.details.material.map(name => {
return (
<li key={name.id} className='after:ml-0.5 after:content-["/"] last:after:content-[""] after:text-primary-gray-70'>
{name.name}
</li>
)
})
}
</ul>
</li>
<li className="flex items-end">
<span>Ustki qalinlik</span>
<div className="grow border-t-2 mx-1 mb-0.5 border-primary-gray-70 border-dotted"></div>
<span>{product.details.thickness}</span>
</li>
</ul>
{/* price */}
<div className="flex-c-b max-440:flex-col max-440:items-start max-440:gap-6 mb-5 mt-4">
<div className="flex-end max-340:flex-col max-340:items-start gap-1">
<span className="inline-block text-regular-16 text-primary-gray-70 mr-1" >Narx:</span>
<p className="text-regular-20 mr-3">{product.parts[0].currentPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".")}so'm</p>
{/* old price aksiya price */}
{
product.parts[0].oldprice && <del className='text-regular-18 text-primary-gray-50'>{product.parts[0].oldprice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".")}so'm</del>
}
</div>
{/* btn */}
</div>
{/* buttons */}
<div className="flex flex-co w-full gap-2">
<Link to={`/catalog/${product.type.toLowerCase().replace(/\s+/g, '-')}/${product.productTitle.toLowerCase().replace(/\s+/g, '-')}`} className="flex-center justify-center red-btn py-2.5 px-5 w-full bg-primary-red-60">Buyurtma berish</Link>
<button onClick={() => dispatch(deleteCard(product))} className="red-btn py-2.5 px-8 bg-transparent border-2 border-primary-red-60 hover:bg-white hover:button-hovered">
<svg width={24} height={24} className='text-primary-red-60 transition-colors-2' clipRule="evenodd" fillRule="evenodd" strokeLinejoin="round" strokeMiterlimit="2" viewBox="0 0 24 24" fill='currentColor' xmlns="http://www.w3.org/2000/svg"><path d="m4.015 5.494h-.253c-.413 0-.747-.335-.747-.747s.334-.747.747-.747h5.253v-1c0-.535.474-1 1-1h4c.526 0 1 .465 1 1v1h5.254c.412 0 .746.335.746.747s-.334.747-.746.747h-.254v15.435c0 .591-.448 1.071-1 1.071-2.873 0-11.127 0-14 0-.552 0-1-.48-1-1.071zm14.5 0h-13v15.006h13zm-4.25 2.506c-.414 0-.75.336-.75.75v8.5c0 .414.336.75.75.75s.75-.336.75-.75v-8.5c0-.414-.336-.75-.75-.75zm-4.5 0c-.414 0-.75.336-.75.75v8.5c0 .414.336.75.75.75s.75-.336.75-.75v-8.5c0-.414-.336-.75-.75-.75zm3.75-4v-.5h-3v.5z" fillRule="nonzero" /></svg>
</button>
</div>
</li>
)
})
:
<p>Savatcha bo'sh. Mahsulotni savatga qo'shish uchun mahsulotning pastki qismidagi savatcha tugmasini bosing</p>
}
</ul>
</div>
</div>
)
};
export default Basket;
|
{% extends 'index.html' %}
{% load static %}
{% block body %}
<h1>Главная страница</h1>
{% if actual %}
<div class="row main-cat">
<h2 class="main-cat__title">Актуально сейчас</h2>
{% for ac in actual %}
<div class="event-item">
{% if ac.image %}
<img class="event-item__img" src="/media/{{ ac.image }}" alt="">
{% else %}
<img class="event-item__img" src={% static 'картинка.png' %} alt="">
{% endif %}
<h3 class="event-item__title"><a href="{% url 'event_detail' ac.id %}">{{ ac.title }}</a></h3>
<p class="event-item__anons">{{ ac.anons }}</p>
</div>
{% endfor %}
</div>
{% endif %}
{% if cinemas %}
<div class="row main-cat">
<h2 class="main-cat__title">Кино</h2>
{% for cinema in cinemas %}
<div class="event-item">
{% if cinema.image %}
<img class="event-item__img" src="/media/{{ cinema.image }}" alt="">
{% else %}
<img class="event-item__img" src={% static 'картинка.png' %} alt="">
{% endif %}
<h3 class="event-item__title"><a href="{% url 'event_detail' cinema.id %}">{{ cinema.title }}</a></h3>
<p class="event-item__anons">{{ cinema.anons }}</p>
</div>
{% endfor %}
</div>
{% endif %}
{% if theaters %}
<div class="row main-cat">
<h2 class="main-cat__title">Театры</h2>
{% for theater in theaters %}
<div class="event-item">
{% if theater.image %}
<img class="event-item__img" src="/media/{{ theater.image }}" alt="">
{% else %}
<img class="event-item__img" src={% static 'картинка.png' %} alt="">
{% endif %}
<h3 class="event-item__title"><a href="{% url 'event_detail' theater.id %}">{{ theater.title }}</a></h3>
<p class="event-item__anons">{{ theater.anons }}</p>
</div>
{% endfor %}
</div>
{% endif %}
{% endblock %}
|
import React, { useEffect, useState } from "react";
import "./Feed.css";
import Tweetbox from "./Tweetbox";
import Post from "./Post";
import db from "./firebase";
function Feed() {
const [posts, setposts] = useState([]);
useEffect(() => {
db.collection("posts")
.orderBy("timestamp", "desc")
.onSnapshot((snapshort) => {
setposts(snapshort.docs.map((doc) => doc.data()));
});
}, []);
return (
<div className="feed">
{" "}
{/*home */}
<div className="feed_header">
<h2>Home</h2>
</div>
<Tweetbox />
{/* Tweetbox */}
{/* post */}
{posts.map((post) => (
<Post
key={post.text}
displayName={post.displayName}
username={post.username}
verified={post.verified}
text={post.text}
image={post.image}
avatar={post.avatar}
/>
))}
</div>
);
}
export default Feed;
|
import '../../../models/message.dart';
import '../../../models/response_parameters.dart';
import '../../response.dart';
class ResponseSetGameScore extends Response<Object> {
ResponseSetGameScore(
{required bool ok,
String? description,
Object? result,
int? errorCode,
ResponseParameters? parameters})
: super(
ok: ok,
description: description,
result: result,
errorCode: errorCode,
parameters: parameters);
factory ResponseSetGameScore.fromJson(Map<String, dynamic> json) {
Object? jsonResult = json['result'];
Object? result;
if (jsonResult != null) {
result = jsonResult is Map<String, dynamic>
? Message.fromJson(jsonResult)
: jsonResult;
}
Map<String, dynamic>? jsonParameters = json['parameters'];
ResponseParameters? parameters;
if (jsonParameters != null) {
parameters = ResponseParameters.fromJson(jsonParameters);
}
return ResponseSetGameScore(
ok: json['ok'],
description: json['description'],
result: result,
errorCode: json['error_code'],
parameters: parameters);
}
}
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
abstract contract ERC721URIStorage is ERC721 {
mapping(uint => string) private _tokenURIs;
function tokenURI(
uint tokenId
)
public
view
virtual
override
_requireMinted(tokenId)
returns (string memory)
{
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
function _setTokenURI(
uint tokenId,
string memory _tokenURI
) internal virtual _requireMinted(tokenId) {
_tokenURIs[tokenId] = _tokenURI;
}
function _burn(uint tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
|
* File $Id$
* Project: ProWim
*
* $LastChangedDate: 2009-09-18 13:56:07 +0200 (Fr, 18 Sep 2009) $
* $LastChangedBy: wardi $
* $HeadURL: https://repository.ebcot.info/wivu/trunk/prowim-server/src/de/ebcot/prowim/datamodel/prowim/KnowledgeLink.java $
* $LastChangedRevision: 2415 $
*------------------------------------------------------------------------------
* (c) 07.08.2009 Ebcot Business Solutions GmbH. More info: http://www.ebcot.de
* All rights reserved. Use is subject to license terms.
*
*This file is part of ProWim.
ProWim is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ProWim 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 ProWim. If not, see <http://www.gnu.org/licenses/>.
Diese Datei ist Teil von ProWim.
ProWim ist Freie Software: Sie können es unter den Bedingungen
der GNU General Public License, wie von der Free Software Foundation,
Version 3 der Lizenz oder (nach Ihrer Option) jeder späteren
veröffentlichten Version, weiterverbreiten und/oder modifizieren.
ProWim wird in der Hoffnung, dass es nützlich sein wird, aber
OHNE JEDE GEWÄHELEISTUNG, bereitgestellt; sogar ohne die implizite
Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
Siehe die GNU General Public License für weitere Details.
Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*/
package org.prowim.datamodel.prowim;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang.Validate;
/**
* This is a data-object-class represents KnowledgeLink.
*
* @author Saad Wardi
* @version $Revision: 2415 $
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "KnowledgeLink", propOrder = { "hyperlink", "repository", "knowledgeObject" })
public class KnowledgeLink extends ProcessElement
{
private String hyperlink = "";
private String repository;
private String knowledgeObject;
/**
* Creates a KnowledgeLink.
*
* @param id {@link KnowledgeLink#setID(String)}
* @param name {@link KnowledgeLink#setName(String)}
* @param createTime {@link KnowledgeLink#setCreateTime(String)}
*/
protected KnowledgeLink(String id, String name, String createTime)
{
super(id, name, createTime);
}
/**
* This non-arg constructor is needed to bind this DataObject in EJB-Context. See the J2EE specification.
*/
protected KnowledgeLink()
{
super();
}
/**
* Returns the hyperlink (URL) of this knowledge link.
*
* @return the hyperlink, never null, can be ""
*/
public String getHyperlink()
{
return hyperlink;
}
/**
* Sets the hyperlink
*
* @param hyperlink the hyperlink to set
*/
public void setHyperlink(String hyperlink)
{
this.hyperlink = hyperlink;
}
/**
* {@link KnowledgeLink#setRepository(String)}
*
* @return the repository ID.
*/
public String getRepository()
{
return repository;
}
/**
* Sets the repository. The repository attribute is the ID in the ontology of the the data storage location (Wissensspeicher), example (Internet or shared folder)<br/>
* Example: repository name = Internet. repository ID = Wissensspeicher_20093513474728 See {@link KnowledgeRepository}
*
* @param repository not null the repository ID to set
*/
public void setRepository(String repository)
{
Validate.notNull(repository);
this.repository = repository;
}
/**
* Set the {@link KnowledgeObject} where this {@link KnowledgeLink} belong to.
*
* @param knowledgeObject the knowledgeObject to set
*/
public void setKnwoledgeObject(String knowledgeObject)
{
this.knowledgeObject = knowledgeObject;
}
/**
* Get the {@link KnowledgeObject} where this {@link KnowledgeLink} belong to.
*
* @return the knowledgeObject
*/
public String getKnowledgeObject()
{
return knowledgeObject;
}
}
|
import Swal from 'sweetalert2';
import { googleAuthProvider } from "../firebase/firebase-config";
import { getAuth, signInWithPopup, createUserWithEmailAndPassword, updateProfile, signInWithEmailAndPassword, signOut } from "firebase/auth";
import { types } from "../types/types"
import { finishLoading, startLoading } from "./ui";
import { cleaningNotes } from './notes';
export const startLoginEmailPassword = (email, password)=>{
return (dispatch)=>{
const auth = getAuth();
dispatch(startLoading());
signInWithEmailAndPassword(auth, email, password)
.then(({user}) => {
dispatch(login(user.uid, user.displayName));
dispatch(finishLoading())
})
.catch((error) => {
dispatch(finishLoading())
Swal.fire('Error', error.message, 'error')
});
}
}
export const startGoogleLogin = ()=>{
return(dispatch)=>{
const auth = getAuth();
signInWithPopup(auth, googleAuthProvider)
.then(({user}) =>{
dispatch(
login(user.uid, user.displayName)
)
})
}
}
export const startRegisterWithEmailPasswordName = (email, password, name)=>{
return (dispatch)=>{
const auth = getAuth();
createUserWithEmailAndPassword(auth, email, password)
.then(async({user}) => {
await updateProfile(auth.currentUser,{displayName: name})
dispatch(
login(user.uid, user.displayName)
)
})
.catch((error) => {
Swal.fire('Error', error.message, 'error');
});
}
}
export const login = (uid, displayName) =>({
type: types.login,
payload: {
uid,
displayName
}
})
export const startLogout = ()=>{
return async (dispatch)=>{
const auth = getAuth();
await signOut(auth);
dispatch(cleaningNotes());
dispatch(logout())
}
}
export const logout = ()=>({
type:types.logout
})
|
#' @export
fonkytonk3<-function(Funkyquest=trap, QUESTION="Test",
ordering=nombri,
len.wrap=10,
Title.Size=6,
Enquete.size=4,
legend.size=2,
text.size=2.5, iflegend=FALSE, marges.du.plot=c(5, 5, 5, 5),
widthcat=list("big"="3", "small"=c("1", "2")), leg.pos="top", ADD.MEAN=add.mean){
blanklab<-""
Funkyquest->df
df<-subset(df, !is.na(df$value)&df$value%in%ordering)
if(inherits(list.ech[[1]]$Q1.Nb.e1, "factor")){
df$value<-droplevels(x = df$value)
}
data.frame(prop.table(table(df$value, df$times, exclude=""), margin = 2))->df
df$Var1<-ordered(x = df$Var1, ordering)
df[order(df$Var2, match(df$Var1, ordering)),]->df
nrow(df)/length(unique(df$Var2))->length.each
df$times<-df$Var2
df$Var2<-c(rep(1, length.each), rep(1.5, length.each), rep(2, length.each),rep(2.5, length.each) )
df$text_y<-unlist(c(by(data = df$Freq[dim(df)[1]:1], INDICES = df$Var2, FUN = function(x){cumsum(x)-x/2} )))
df$xtext<-sapply(1:nrow(df), FUN = function(x){
if(df$Freq[x]<=0.02){
as.numeric(df$Var2[x])
}else{
as.numeric(df$Var2[x])
}
}
)
# enq1<-dim(pan1data)[1]
# enq2<-dim(pan2data)[1]
# enq3<-dim(pan3data)[1]
# enq4<-
df$blanc<-sapply(1:nrow(df), function(i){
if(df$Var1[i]=="Plus nombreuses"|df$Var1[i]=="S'accroitre"|df$Var1[i]=="Ne sait pas"|df$Var1[i]=="Se sont dégradées"|df$Var1[i]=="Plus difficile aujourd'hui"){"blanc"} else {"black"}
})
big<-widthcat[["big"]]
petit<-widthcat[["small"]]
df$widthcat<-sapply(1:nrow(df), function(i){
if(df$times[i]%in%petit#|df$Var2[i]!=max(df$Var2)
){0.4} else {
if(df$times[i]%in%big#|df$Var2[i]==max(df$Var2)
){0.9}}
}
)
if(ADD.MEAN==TRUE){
dfmean<-df %>%
group_by(Var1) %>%
summarise("Var2"=max(df$Var2)+0.5,"Freq"=mean(Freq), 'times'="moyenne")
dfmean$text_y<-unlist(c(by(data = dfmean$Freq[dim(dfmean)[1]:1], INDICES = dfmean$Var2, FUN = function(x){cumsum(x)-x/2} )))
dfmean$xtext<-sapply(1:nrow(dfmean), FUN = function(x){
if(dfmean$Freq[x]<=0.02){
as.numeric(dfmean$Var2[x])
}else{
as.numeric(dfmean$Var2[x])
}
}
)
dfmean$blanc<-sapply(1:nrow(dfmean), function(i){
if(dfmean$Var1[i]=="Plus nombreuses"|dfmean$Var1[i]=="S'accroitre"|dfmean$Var1[i]=="Ne sait pas"|dfmean$Var1[i]=="Se sont dégradées"|dfmean$Var1[i]=="Plus difficile aujourd'hui"){"blanc"} else {"black"}
})
dfmean$widthcat<-0.65*min(df$widthcat)
df<-rbind(df, dfmean)
}
df$ALPHA<-sapply(1:nrow(df), function(i){
if(df$times[i]=="moyenne"){
0
} else {1}
})
ggplot(data = df , aes(x=Var2, y = Freq, fill=Var1, width=widthcat, alpha=ALPHA))+
geom_bar(position = "fill",stat = "identity", width = 1) +
scale_fill_manual(name="",#wrap.it(QUESTION, len = len.wrap),
labels=paste(ordering, blanklab),
values=c(nega, stab, nesp, posi))+
scale_alpha_continuous(range=c(0.8, 1),guide = 'none')+
guides(fill=guide_legend(ncol=length(levels(df$Var1)),
reverse=TRUE))+
geom_text(aes(label=paste(round(Freq*100, 0), "%", sep=""),colour=factor(blanc),
y=rev(text_y), x=xtext, fill=Var1, fontface=2 ), size=text.size, force =1,
show.legend = FALSE)+
scale_color_manual(values=c(gray(level = 0), gray(level = 1)))+
scale_x_continuous(labels = unique(df[ , c("Var2", "times")])$times, breaks = unique(df[ , c("Var2", "times")])$Var2)+
coord_flip() +
theme_minimal()+
theme(axis.title = element_blank(), axis.text.x = element_blank())+
#annotate("text", x = c(1, 2, 3), y = 0, size=Enquete.size,
# label=c(paste("Enqu?te #1"),
# paste("Enqu?te #2"), paste("Enqu?te #3")
# ),
# family="Calibri Light", face="bold", hjust=0 )+
ggtitle(wrap.it(QUESTION, len = len.wrap))+
if(iflegend==TRUE){
theme(text= element_text(family="Calibri Light"),
legend.position= leg.pos,#legend.key.size = legend.size,
#legend.title = element_blank(),
#legend.text=element_text(size=legend.size, face="bold"),
#plot.title = element_text(family="Calibri Light" , face = "bold",
# size = Title.Size, hjust = 0, vjust=0, margin=margin(0,0,30,0))# plot.title = element_text(family = "sans", size = 18, margin=margin(0,0,30,0))
#legend.justification = c(0.5, 1),
#plot.margin=unit(marges.du.plot, "cm")
) } else {
theme(text= element_text(family="Calibri Light"),
legend.position= "hidden",
legend.title = element_blank(),
legend.text=element_text(size=legend.size),
plot.title = element_text(family="Calibri Light" , face = "bold",
size = Title.Size, hjust = 0, vjust=0),
legend.justification = c(0.5, 1)
) }
}
#
fonkytonk.repel<-function(varname.pattern="Q1.Nb", ordering=nombri, QUESTION="Test", len.wrap=10,
Title.Size=6,
Enquete.size=4,
legend.size=2,
text.size=2, iflegend=FALSE, marges.du.plot=c(1,0.2,0.5,0.2)){
pan1data[, c(names(pan1data)[grepl(pattern ="email.", x = names(pan1data))],
names(pan1data)[grepl(pattern =varname.pattern, x = names(pan1data))])]->df1
df1$enq<-"1"
pan2data[, c(names(pan2data)[grepl(pattern ="email.", x = names(pan2data))],
names(pan2data)[grepl(pattern =varname.pattern, x = names(pan2data))])]->df2
df2$enq<-"2"
c("email", "varna", "enq")->vecnam
names(df2)<-vecnam
names(df1)<-vecnam
df<-rbind(df1, df2)
df<-df[!is.na(df$varna), ]
#
data.frame(prop.table(table(df$varna, df$enq, exclude=""), margin = 2))->df
df$Var1<-ordered(x = df$Var1, ordering)
df[order(df$Var2, match(df$Var1, ordering)),]->df
df$text_y<-unlist(c(by(data = df$Freq[dim(df)[1]:1], INDICES = df$Var2, FUN = function(x){cumsum(x)-x/2} )))
df$xtext<-sapply(1:nrow(df), FUN = function(x){
if(df$Freq[x]<=0.02){
as.numeric(df$Var2[x])
}else{
as.numeric(df$Var2[x])
}
}
)
#enq1<-dim(pan1data)[1]
#enq2<-dim(pan2data)[1]
df$blanc<-sapply(1:nrow(df), function(i){
if(df$Var1[i]=="Plus nombreuses"|df$Var1[i]=="S'accroitre"|df$Var1[i]=="Ne sait pas"|df$Var1[i]=="Se sont d?grad?es"|df$Var1[i]=="Plus difficile aujourd'hui"){"blanc"} else {"black"}
})
ggplot(data = df , aes(x=Var2, y = Freq, fill=Var1))+
geom_bar(position = "fill",stat = "identity", width = 0.5) +
scale_fill_manual(name=wrap.it(QUESTION, len = len.wrap),
labels=paste(ordering, blanklab),
values=c(nega, stab, nesp, posi))+
guides(fill=guide_legend(ncol=length(levels(df$Var1)),
reverse=TRUE))+
geom_text_repel(aes(label=paste(round(Freq*100, 0), "%", sep=""),colour=factor(blanc),
y=rev(text_y), x=xtext, fill=Var1, fontface=2 ), size=text.size,
force =1,direction = "y",point.padding = NA,
show.legend = FALSE)+
scale_color_manual(values=c(gray(level = 0), gray(level = 1)))+
coord_flip() +
theme_void()+
annotate("text", x = c(1.5, 2.5), y = 0, size=Enquete.size,
label=c(paste("Enqu?te #1"),
paste("Enqu?te #2")
),
family="Calibri Light", face="bold", hjust=0 )+
ggtitle(wrap.it(QUESTION, len = len.wrap))+
if(iflegend==TRUE){
theme(text= element_text(family="Calibri Light"),
legend.position= "bottom",
legend.title = element_blank(),
legend.text=element_text(size=legend.size, face="bold"),
plot.title = element_text(family="Calibri Light" , face = "bold",
size = Title.Size, hjust = 0, vjust=0),
legend.justification = c(0.5, 1),
plot.margin=unit(marges.du.plot, "cm")
) } else {
theme(text= element_text(family="Calibri Light"),
legend.position= "hidden",
legend.title = element_blank(),
legend.text=element_text(size=legend.size),
plot.title = element_text(family="Calibri Light" , face = "bold",
size = Title.Size, hjust = 0, vjust=0),
legend.justification = c(0.5, 1)
) }
}
|
import { useEffect, useRef } from 'react';
import styles from './style.module.css';
import { gsap } from 'gsap';
import MagneticEffect from '../MagneticEffect';
interface Props {
children: React.ReactNode;
backgroundColor?: string;
className?: string;
onClick?: () => void;
}
const CircleButton: React.FC<Props> = ({
children,
backgroundColor = '#455CE9',
className = styles.roundedButton,
...props
}) => {
const circleRef = useRef(null);
const timeline = useRef(gsap.timeline({ paused: true }));
let timeoutId: NodeJS.Timeout | null = null;
useEffect(() => {
timeline.current
.to(
circleRef.current,
{ top: '-25%', width: '150%', duration: 0.4, ease: 'power3.in' },
'enter'
)
.to(circleRef.current, { top: '-150%', width: '125%', duration: 0.25 }, 'exit');
}, []);
const handleMouseEnter = () => {
if (timeoutId != null) {
clearTimeout(timeoutId);
}
timeline.current.tweenFromTo('enter', 'exit');
};
const handleMouseLeave = () => {
timeoutId = setTimeout(() => {
timeline.current.play();
}, 300);
};
return (
<MagneticEffect>
<div
className={className}
style={{ overflow: 'hidden' }}
{...props}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
{children}
<div ref={circleRef} style={{ backgroundColor }} className={styles.circle}></div>
</div>
</MagneticEffect>
);
};
export default CircleButton;
|
<template>
<div class="container">
<div class="table-name-container">
<h1>{{tableName}}</h1>
</div>
<hot-table :settings="settings" ref="hotTable"></hot-table>
</div>
</template>
<script>
import PanelBase from './PanelBase.vue'
import { HotTable } from '@handsontable/vue';
import { registerAllModules } from 'handsontable/registry';
// register Handsontable's modules
registerAllModules();
export default {
mixins: [PanelBase],
components: {
HotTable
},
data() {
return {
tableName: '-',
columnNames: ['','','','','',''],
rows: [
['','','','','',''],
['','','','','',''],
['','','','','',''],
['','','','','',''],
['','','','','',''],
['','','','','','']
],
settings: {
data: this.rows,
colHeaders: true,
rowHeaders: true,
width: "auto",
height: "auto",
manualColumnResize: true,
stretchH: 'all',
contextMenu: true,
licenseKey: 'non-commercial-and-evaluation'
}
}
},
computed: {
tableName() {
return this.app.descriptive_name
}
},
methods: {
handleResponse(response) {
if (response.statusCode >= 400) {
this.errors = response.body
} else {
try {
let r = response.body
this.setData(r)
} catch (error) {
this.errors = error
}
}
},
setData(r) {
this.rows = r.rows
this.columnNames = r.columnNames
this.$refs.hotTable.hotInstance.updateSettings({
data: this.rows,
colHeaders: this.columnNames
})
}
}
}
</script>
<style lang="scss" scoped>
@import '~handsontable/dist/handsontable.full.css';
.container {
width: 100%;
height: auto;
margin: 0;
}
</style>
|
<template>
<div class="index">
<FrontHeader />
<div v-if="info">
<PageTitle :title="`${info.name}`" />
<div v-if="info.ohp" class="m-3">
<b-link target="_blank" :href="`${info.ohp}`">公式ホームページ</b-link>
</div>
</div>
<div v-else>
<h3><b-spinner label="Loading..."></b-spinner></h3>
</div>
<p v-if="info && info.twitter_name">
<b-container>
<b-row align-h="center">
<b-col cols="10">
<a
class="twitter-timeline"
data-height="500"
data-lang="ja"
data-theme="dark"
:href="`https://twitter.com/${info.twitter_name}`"
>Tweets by {{ info.twitter_name }}</a
>
</b-col>
</b-row>
</b-container>
</p>
<p v-else>
<b-spinner label="Loading..."></b-spinner>
</p>
<p v-if="splitVideos.length > 0">
<b-container>
<b-row
v-for="splitVideo in splitVideos"
:key="splitVideo.index"
cols="2"
fluid
>
<b-col
v-for="video in splitVideo.videos"
:key="video.id"
align-h="center"
fluid
>
<b-card>
<div class="movie-thumbnail-list" @click="showModal(video.id)">
<b-card-img-lazy
thumbnail
:src="`https://i.ytimg.com/vi/${video.id}/hqdefault.jpg`"
>
</b-card-img-lazy>
<div class="_mask">
<div class="_text">
{{ video.title }}
</div>
<div class="_img">
<b-img-lazy fluid src="/img/movie_play.png"></b-img-lazy>
</div>
</div>
</div>
</b-card>
</b-col>
</b-row>
</b-container>
</p>
<p v-else>
<b-spinner label="Loading..."></b-spinner>
</p>
<b-modal
ref="moviePlayModal"
ok-only
ok-title="閉じる"
size="xl"
hide-header
hide-footer
body-bg-variant="dark"
>
<b-embed
type="iframe"
aspect="16by9"
:src="`https://www.youtube.com/embed/${modelVideoID}`"
allowfullscreen
></b-embed>
</b-modal>
<FrontFooter />
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted } from '@vue/composition-api'
import FrontHeader from '@/components/Header.vue'
import FrontFooter from '@/components/Footer.vue'
import PageTitle from '@/components/Title.vue'
import axios from 'axios'
interface ResponseVideo {
id: string;
title: string;
}
interface SpritVideo {
index: number;
videos: Array<ResponseVideo>;
}
interface ReactiveData {
info: any; // eslint-disable-line @typescript-eslint/no-explicit-any
splitVideos: Array<SpritVideo>;
moviePlayModal: any; // eslint-disable-line @typescript-eslint/no-explicit-any
modelVideoID: string;
}
export default defineComponent({
components: {
FrontHeader,
FrontFooter,
PageTitle
},
setup (_, context) {
const videoColumnNumber = 2
const code = context.root.$route.params.path
const state: ReactiveData = reactive({
info: null,
splitVideos: [],
moviePlayModal: null,
modelVideoID: ''
})
const showModal = (id: string) => {
state.modelVideoID = id
state.moviePlayModal.show()
}
const hideModal = () => {
state.moviePlayModal.hide()
}
const render = () => {
axios
.get(`${process.env.VUE_APP_API_ORIGIN}/maker/detail/${code}`, {
timeout: 5000
})
.then((res) => {
state.info = res.data
const twitterScript = document.createElement('script')
twitterScript.setAttribute(
'src',
'https://platform.twitter.com/widgets.js'
)
twitterScript.setAttribute('async', 'async')
document.head.appendChild(twitterScript)
})
.catch(() => {
alert('メーカーデータの取得に失敗しました')
})
axios
.get(`${process.env.VUE_APP_API_ORIGIN}/maker/videos/${code}`, {
timeout: 5000
})
.then((res) => {
const tmp: Array<SpritVideo> = []
res.data.forEach((element: ResponseVideo, index: number) => {
const key = Math.floor(index / videoColumnNumber)
if (!tmp[key]) {
tmp[key] = {
index: key,
videos: []
}
}
tmp[key].videos.push(element)
})
state.splitVideos = tmp
})
.catch(() => {
alert('メーカー動画データの取得に失敗しました')
})
}
onMounted(() => {
render()
})
return {
...toRefs(state),
showModal,
hideModal
}
}
})
</script>
<style>
.movie-thumbnail-list {
position: relative;
}
.movie-thumbnail-list ._mask {
position: absolute;
display: grid;
align-items: center;
justify-items: center;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: black;
opacity: 0.5;
}
.movie-thumbnail-list ._img {
position: absolute;
width: 30%;
}
.movie-thumbnail-list ._text {
position: absolute;
top: 5%;
left: 5%;
right: 5%;
color: white;
font-weight: bold;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
}
@media (orientation: portrait) {
.movie-thumbnail-list ._text {
font-size: 70%;
}
}
</style>
|
import 'package:flutter/material.dart';
import 'cadastro.dart';
import 'login.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => InicioPage(),
'/cadastro': (context) => CadastroPage(),
},
);
}
}
class InicioPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/inicio.png'),
fit: BoxFit.cover,
),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(height: 16),
ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, '/cadastro');
},
style: ElevatedButton.styleFrom(
primary: Color(0xFF97E366),
minimumSize: Size(200, 50),
side: BorderSide(width: 1, color: Colors.black),
),
child: Text(
'Cadastro',
style: TextStyle(color: Colors.black),
),
),
SizedBox(height: 16),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LoginPage()),
);
},
style: ElevatedButton.styleFrom(
primary: Color(0xFF97E366),
minimumSize: Size(200, 50),
side: BorderSide(width: 1, color: Colors.black),
),
child: Text(
'Login',
style: TextStyle(color: Colors.black),
),
),
],
),
),
),
);
}
}
|
import { Todo } from '../models';
import { ITodo } from '../interfaces';
export default class TodoService {
/**
* Create new todo
* @param description
* @param userId
* @param status
* @returns Promise Todo -> todo successfully created.
* @returns Promise undefined -> todo already exists.
*/
public static create
= async (userId: number, description: string, status: string)
: Promise<ITodo | undefined> => {
const date = Date().toLocaleString();
const todo = await Todo.create({ userId, description, date, status });
if (!todo.id) return undefined;
return {
id: todo.id,
userId,
description,
date,
status,
} as ITodo;
};
/**
* Find all todo list of user.
* @param userId
* @returns Promise Todo[] -> todo list
*/
public static findAll = async (userId: number): Promise<ITodo[]> => {
const todo = await Todo.findAll({ where: { userId }});
return todo as ITodo[];
};
/**
* Update one todo task.
* @param id
* @param description
* @param status
* @returns Promise Todo -> todo task updated.
* @returns Promise undefined -> todo not exists.
* @returns Promise null -> update failure.
*/
public static update
= async (id: number, description: string, status: string)
: Promise<ITodo | undefined | null> => {
const task = await Todo.findByPk(id);
if (!task) return undefined;
let todo;
if (status === '*') {
todo = await Todo.update({ description }, { where: { id }});
} else {
todo = await Todo.update({ description, status }, { where: { id }});
}
const [affectedCount] = todo;
if (affectedCount === 0) return null;
return {
id,
userId: task.userId,
description,
date: task.date,
status,
} as ITodo;
};
/**
* Delete one todo task.
* @param id
* @returns Promise 1 (number) -> todo task deleted.
* @returns Promise 0 (number) -> todo task not found.
*/
public static exclude = async (id: number): Promise<number> => {
const todo = await Todo.destroy({ where: { id }});
return todo;
};
}
|
# gopathdep
Manage your $GOPATH dependencies for your project.
To get a project setup with gopathdep, cd into the project's repo and record
its current dependencies: `gopathdep record`. This will create a
`pathdep.yaml` file at the root of the repo, which lists each dependency and
the desired commit. You can edit this file to specify a branch or tag, for
example: `branch: master` to always use the master branch of a particular
dependency, or `tag: v1.2` to always use the v1.2 tag.
You can check to see if your dependencies are what has been specified by doing
`gopathdep check`.
You can use `gopathdep apply` to apply your project's dependency requirements
to your $GOPATH. This will checkout packages to the specified
commit/tag/branch. If a dependency has modifications in it, gopathdep will
refuse to update that dependency and warn you about the inconsistency.
Note that this tool is not intended to work with the `vendor` directory. It is
intended to use your $GOPATH for this purpose instead. If you want to use the
vendor directory, I'd recommend using one of the other many dependency
management tools available.
|
import './Card.css'
import React from 'react';
const getColor = props => {
if (props.blue) {
return 'Blue';
};
if (props.green) {
return 'Green';
}
if (props.purple) {
return 'Purple';
}
if (props.red) {
return 'Red';
};
return 'TODO';
};
const Card = props => (
<div className={`Card ${getColor(props)}`} >
<div className='Header'>
<span className='Title'>
{props.title}
</span>
</div>
<div className='Content'>
{props.children}
</div>
</div >
);
export default Card;
|
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { logoutAction } from "../state/action/action";
const Dashboard = () => {
const dispatch = useDispatch();
const Navigate = useNavigate();
// Getting the states from Redux-Store | Obj destructuring
const {userEmail,userPassword} = useSelector (
(state) => state.LoginReducer
);
const logoutHandler = () => {
dispatch(logoutAction())
Navigate("/")
}
return (
<>
<div className="dashboard">
<br /><br /><br /><br />
<h1 className="lightSpeedIn">USER PROFILE</h1>
<br /><br /><br />
<h2 className="fadeInUp">EMAIL:</h2>
<br />
<h3 className="lightSpeedIn ">{userEmail}</h3>
<br />
<h2 className="fadeInUp">PASSWORD:</h2>
<br />
<h3 className="lightSpeedIn ">{userPassword}</h3>
<br /><br /><br />
<button className="LOGOUT lightSpeedIn" onClick={logoutHandler}>LOGOUT</button>
</div>
</>
)
}
export default Dashboard;
|
#include <Keyboard.h>
#include <Mouse.h>
const int deadZone = 24;
const int maxZone = 12;
const int joyXPin = A0; // Analog pin for X-axis of the joystick
const int joyYPin = A1; // Analog pin for Y-axis of the joystick
const int joyButtonPin = 4; // Digital pin for the joystick button
const int button1 = 2;
const int button2 = 3;
const int mode = 0;
const int greenLED = 10;
const int yellowLED = 11;
const int redLED = 12;
// mode, 0 = "mouse", joystick is mouse and joystick click is middle click. Button 1 = left click, Button 2 = right click
// mode, 1 = "wasd", joystick is wasd, mouse buttons are same.
// mode, 2 = "wasdcz", joystick is wasd, button 1 is c, button 2 is z, joystick is " "
// clicking and holding all buttons for 3 second changes mode
void setup() {
// Initialize the Keyboard and Mouse libraries
Keyboard.begin();
Mouse.begin();
Serial.begin(9600);
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
pinMode(joyButtonPin, INPUT_PULLUP); // Set the joystick button pin as input with an internal pull-up resistor
pinMode(greenLED, OUTPUT);
pinMode(yellowLED, OUTPUT);
pinMode(redLED, OUTPUT);
}
int applyDeadAndMax(int value){
value = value-512;
if (abs(value)<deadZone){
return 512;
} else if (value>1023-maxZone){
return 1023;
} else if (abs(value)<maxZone){
return 0;
}
return value+512;
}
int joystickHoriz() {
return applyDeadAndMax(analogRead(joyXPin));
}
int joystickVert() {
return applyDeadAndMax(analogRead(joyYPin));
}
bool joyPressed() {
return !digitalRead(joyButtonPin); // Corrected the function and added '!' to invert the button state
}
bool onePressed() {
return !digitalRead(button1);
}
bool twoPressed() {
return !digitalRead(button2);
}
void loop() {
// Read joystick values
int xValue = joystickHoriz();
int yValue = joystickVert();
// Print joystick and button state
Serial.print("X-Axis: ");
Serial.print(xValue);
Serial.print("\tY-Axis: ");
Serial.print(yValue);
Serial.print("\tButton: ");
Serial.print(joyPressed() ? "Pressed" : "Released");
Serial.print("\tButton1: ");
Serial.print(onePressed() ? "Pressed" : "Released");
Serial.print("\tButton2: ");
Serial.println(twoPressed() ? "Pressed" : "Released");
// Perform actions based on joystick and button state
// Here you can add logic to send keyboard and mouse input based on joystick/button state
// For example:
if (xValue < 400) {
// Keyboard.write('A'); // Send 'A' when joystick is moved to the left
// Turn on the green LED and wait for a short moment
digitalWrite(greenLED, HIGH);
delay(100); // 100 milliseconds (0.1 second) delay
// Turn off the green LED
digitalWrite(greenLED, LOW);
delay(50); // 50 milliseconds (0.05 second) delay
// Turn on the yellow LED and wait for a short moment
digitalWrite(yellowLED, HIGH);
delay(100); // 100 milliseconds (0.1 second) delay
// Turn off the yellow LED
digitalWrite(yellowLED, LOW);
delay(50); // 50 milliseconds (0.05 second) delay
// Turn on the red LED and wait for a short moment
digitalWrite(redLED, HIGH);
delay(100); // 100 milliseconds (0.1 second) delay
// Turn off the red LED
digitalWrite(redLED, LOW);
delay(50); // 50 milliseconds (0.05 second) delay
}
// You can add more logic for different joystick positions and button states
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Instagram</title>
<link rel="stylesheet" href="style.css">
<!--font awesome cdn(libraries ) for icons-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<header>
<div class="logo">
<img src="images/Facebook-Logo.png" alt="insta logo" width="100">
</div>
<div class="search-box">
<!--search icon-->
<i class="fa-solid fa-magnifying-glass"></i>
<!--to create search box-->
<input type="search" placeholder="Search">
</div>
<div>
<ul>
<li><a href="#"><i class="fa-solid fa-house"></i></a></li>
<li><a href="#"><i class="fa-brands fa-facebook-messenger"></i></a></li>
<li><a href="#"><i class="fa-regular fa-square-plus"></i></a></li>
<li><a href="#"><i class="fa-regular fa-compass"></i></a></li>
<li><a href="#"><i class="fa-regular fa-heart"></i></a></li>
<li><a href="#"><img src="images/keerthi profile.jpg" alt="profile"></a></li>
</ul>
</div>
</header>
<section>
<div class="left-side">
<div class="story">
<div class="stories">
<img src="images/andrew-ridley-jR4Zf-riEjI-unsplash.jpg" width="60" height="60" alt="story">
<p>Keerthi</p>
</div>
<div class="stories">
<img src="images/bruno-van-der-kraan--0QMJQfDD50-unsplash.jpg" width="60" height="60" alt="story">
<p>Ramakrishnan</p>
</div>
<div class="stories">
<img src="images/jordan-whitt-qGQNmBE7mYw-unsplash.jpg" width="60" height="60" alt="story">
<p>Amareswari</p>
</div>
</div>
<div class="posts">
<div class="post-title">
<div class="post-left">
<div class="image">
<img src="images/keerthi profile.jpg" alt="frd-profile" width="32" height="32">
</div>
<div class="details">
<p class="name">keerthana__ramakrishnan</p>
<p class="location">Coimbatore</p>
</div>
</div>
<div class="post-right">
<i class="fas fa-ellipsis-h"></i>
</div>
</div>
<div class="post-content">
<img src="images/tengyart-zLETygkHMvQ-unsplash.jpg" alt="frds-post" height="600" width="600">
</div>
<div class="post-footer">
<div class="like-share-comment">
<i class="fa-regular fa-heart"></i>
<i class="fa-regular fa-comment fa-flip-horizontal"></i>
<i class="fa-regular fa-paper-plane"></i>
</div>
<div class="save">
<i class="far fa-bookmark"></i>
</div>
</div>
<div class="post-footer-content">
<p class="likes">82 likes</p>
<p class="name">keerthana__ramakrishnan<span>#weekend</span></p>
<p class="comments">View all 3 comments</p>
<p class="posting-time">5 June 2022</p>
</div>
<div class="add-comment">
<div class="left-side">
<i class="far fa-smile-beam"></i>
<input type="text" placeholder="Add a comment...">
</div>
<div class="right-side">
<p>Post</p>
</div>
</div>
</div>
<div class="posts">
<div class="post-title">
<div class="post-left">
<div class="image">
<img src="images/dhana profile.jpg" alt="frd-profile" width="32" height="32">
</div>
<div class="details">
<p class="name">dhanashree_rd</p>
<p class="location">Japan</p>
</div>
</div>
<div class="post-right">
<i class="fas fa-ellipsis-h"></i>
</div>
</div>
<div class="post-content">
<img src="images/dhana.jpg" alt="frds-post" height="600" width="600">
</div>
<div class="post-footer">
<div class="like-share-comment">
<i class="fa-regular fa-heart"></i>
<i class="fa-regular fa-comment fa-flip-horizontal"></i>
<i class="fa-regular fa-paper-plane"></i>
</div>
<div class="save">
<i class="far fa-bookmark"></i>
</div>
</div>
<div class="post-footer-content">
<p class="likes">100 likes</p>
<p class="name">dhanashree_rd<span>#tokyo</span></p>
<p class="comments">View all 10 comments</p>
<p class="posting-time">23 hours ago</p>
</div>
<div class="add-comment">
<div class="left-side">
<i class="far fa-smile-beam"></i>
<input type="text" placeholder="Add a comment...">
</div>
<div class="right-side">
<p>Post</p>
</div>
</div>
</div>
<div class="posts">
<div class="post-title">
<div class="post-left">
<div class="image">
<img src="images/keith-misner-h0Vxgz5tyXA-unsplash.jpg" alt="frd-profile" width="32" height="32">
</div>
<div class="details">
<p class="name">keerthi__rkv</p>
<p class="location">Coimbatore</p>
</div>
</div>
<div class="post-right">
<i class="fas fa-ellipsis-h"></i>
</div>
</div>
<div class="post-content">
<img src="images/keerthi__rkv.jpg" alt="frds-post" height="600" width="600">
</div>
<div class="post-footer">
<div class="like-share-comment">
<i class="fa-regular fa-heart"></i>
<i class="fa-regular fa-comment fa-flip-horizontal"></i>
<i class="fa-regular fa-paper-plane"></i>
</div>
<div class="save">
<i class="far fa-bookmark"></i>
</div>
</div>
<div class="post-footer-content">
<p class="likes">150 likes</p>
<p class="name">keerthi__rkv<span>144p #keerthirkv</span></p>
<p class="comments">View all 14 comments</p>
<p class="posting-time">14 March</p>
</div>
<div class="add-comment">
<div class="left-side">
<i class="far fa-smile-beam"></i>
<input type="text" placeholder="Add a comment...">
</div>
<div class="right-side">
<p>Post</p>
</div>
</div>
</div>
<div class="posts">
<div class="post-title">
<div class="post-left">
<div class="image">
<img src="images/kalai profile.jpg" alt="frd-profile" width="32" height="32">
</div>
<div class="details">
<p class="name">kalai_rkv</p>
<p class="location">Bangalore</p>
</div>
</div>
<div class="post-right">
<i class="fas fa-ellipsis-h"></i>
</div>
</div>
<div class="post-content">
<img src="images/kalai.jpg" alt="frds-post" height="600" width="600">
</div>
<div class="post-footer">
<div class="like-share-comment">
<i class="fa-regular fa-heart"></i>
<i class="fa-regular fa-comment fa-flip-horizontal"></i>
<i class="fa-regular fa-paper-plane"></i>
</div>
<div class="save">
<i class="far fa-bookmark"></i>
</div>
</div>
<div class="post-footer-content">
<p class="likes">140 likes</p>
<p class="name">kalai_rkv<span>#kalairkv#cheeyapparawaterfalls#munnar</span></p>
<p class="comments">View all 12 comments</p>
<p class="posting-time">13 November 2022</p>
</div>
<div class="add-comment">
<div class="left-side">
<i class="far fa-smile-beam"></i>
<input type="text" placeholder="Add a comment...">
</div>
<div class="right-side">
<p>Post</p>
</div>
</div>
</div>
</div>
<div class="right-side">
<div class="profile-title">
<div class="profile-left">
<div class="image">
<img src="images/keerthi profile.jpg" alt="profile" width="56" height="56">
</div>
<div class="details">
<p class="name">Keerthana</p>
<p class="nickname">Keerthana__Ramakrishnan</p>
</div>
</div>
<div class="profile-right">
<p>Switch</p>
</div>
</div>
<div class="suggestions">
<p>Suggestions for you</p>
<p>See all</p>
</div>
<div class="suggestion-title">
<div class="suggestion-left">
<div class="image">
<img src="images/keerthi.jpg" alt="keerthi" width="32" height="32">
</div>
<div class="details">
<p class="name">Keerthana</p>
<p class="location">Coimbatore</p>
</div>
</div>
<div class="suggestion-right">
<p>Follow</p>
</div>
</div>
<div class="suggestion-title">
<div class="suggestion-left">
<div class="image">
<img src="images/dhana.jpg" alt="keerthi" width="32" height="32">
</div>
<div class="details">
<p class="name">DhanaShree</p>
<p class="location">Coimbatore</p>
</div>
</div>
<div class="suggestion-right">
<p>Follow</p>
</div>
</div>
<div class="suggestion-title">
<div class="suggestion-left">
<div class="image">
<img src="images/keerthi.jpg" alt="keerthi" width="32" height="32">
</div>
<div class="details">
<p class="name">keerthana</p>
<p class="location">Coimbatore</p>
</div>
</div>
<div class="suggestion-right">
<p>Follow</p>
</div>
</div>
</div>
</section>
</body>
</html>
|
/**
* Application entry point
* @file src/index.tsx
* @author John Carr
* @license MIT
*/
import './styles/index.css'
import '@fontsource/roboto/300.css'
import '@fontsource/roboto/400.css'
import '@fontsource/roboto/500.css'
import '@fontsource/roboto/700.css'
import React from 'react'
import { createRoot } from 'react-dom/client'
import { Provider } from 'react-redux'
import { store } from './state/store'
import Router from './Router'
import LayoutProvider from './components/Layout/Provider'
import reportWebVitals from './reportWebVitals'
const container = document.getElementById('root')!
const root = createRoot(container)
root.render(
<React.StrictMode>
<Provider store={store}>
<LayoutProvider>
<Router />
</LayoutProvider>
</Provider>
</React.StrictMode>
)
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals()
|
<script>
import { EditDatabaseData, GetDatabaseData } from '../../database.js'
import commonHeader from '@/components/commonHeader.vue'
export default{
components: {
commonHeader
},
data() {
return {
dataList: [],
selectedPriority: null,
obakes: [],
SelectedObake: ''
}
},
mounted() {
this.msgShow(),
this.getObakeList()
},
methods:{
back(year,month,day){
this.$router.push({
name: 'TaskPage',
query: {
year:year,
month:month,
day:day
}
})
},
async msgShow() {
const func = 'GetListAll';
const id = this.$route.query.task_id;
const args = {
tbl: "task",
where: `task_id = ${id}`,
};
const data = await GetDatabaseData(func, args);
this.dataList = data;
this.selectedPriority = data[0].priority_id;
},
async Update() {
try{
const tn = document.getElementById("task_name").value;
const td = document.getElementById("task_description").value;
const id = this.$route.query.task_id;
const oi = this.SelectedObake.obake_id;
const func = 'DbUpdate'
const args = {
tbl: "task",
records: {
task_name: tn,
task_description: td,
obake_id: oi,
},
where: `task_id = ${id}`,
}
await EditDatabaseData(func, args)
this.back(this.$route.query.year,this.$route.query.month,this.$route.query.day)
}catch(error){
console.error('エラーが発生しました:',error);
}
},
async getObakeList() {
const func = 'GetListAll'
const args = {
tbl: "obake",
where: "lock_id = 0"
}
const data = await GetDatabaseData(func, args)
this.obakes = data
},
weekend(dayOfWeek) {
if(dayOfWeek === "土"){
return 'saturday';
}else if(dayOfWeek === "日"){
return 'sunday';
}else{
return '';
}
},
parentImagePath(imagePath) {
const PathSplit = imagePath.split("/")
return require(`@/assets/img/${PathSplit[3]}`); // 変数を使用して画像のパスを指定
},
}
}
</script>
<template>
<commonHeader></commonHeader>
<h1 class="date" :class="weekend(this.$route.query.week)">{{ this.$route.query.month }}月{{ this.$route.query.day }}日({{ this.$route.query.week }})の課題</h1>
<div v-for="item in dataList" :key="item.id">
<input class="IUgrave" type="text" id="task_name" placeholder="タスク名を入力" :value="item.task_name" :class="weekend(this.$route.query.week)"><br>
<input class="IUgrave" type="text" id="task_description" placeholder="タスクの説明を入力" :value="item.task_description" :class="weekend(this.$route.query.week)"><br>
<select class="IUgrave" id="obake_id" :class="weekend(this.$route.query.week)" v-model="SelectedObake">
<option value="" disabled selected style="display:none;">お化けを選択</option>
<option v-for="obake in obakes" :key="obake.id" :value="obake">{{ obake.obake_id }}</option>
</select>
</div>
<h1 class="plus" @click="Update()" :class="weekend(this.$route.query.week)">この内容で課題を変更する</h1>
<div v-if="SelectedObake">
<img :src="parentImagePath(SelectedObake.obake_path)" width="100" height="100" />
</div>
</template>
|
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>Search Recipes</title>
<!-- 引入Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
body {
background-color: #f8f8f8;
color: #333;
font-family: Arial, sans-serif;
}
h2, h3 {
color: #444;
}
.table {
background-color: #fff;
}
.table th, .table td {
border: 1px solid #ddd;
}
.btn-primary {
background-color: #007bff;
border-color: #007bff;
}
.app-icon {
height: 150px;
width: 150px;
position: absolute;
top: 10px;
left: 10px;
}
</style>
</head>
<body class="container mt-4">
<img src="./resource/icon.png" class="app-icon"/>
<h2>Search Recipes</h2>
<form action="searchresult" method="get" class="form-inline mb-4">
<input type="text" name="name" value="${name}" class="form-control mr-2">
<input type="submit" value="Search" class="btn btn-primary">
</form>
<table class="table">
<thead class="thead-light">
<tr>
<th>Recipe ID</th>
<th>Name</th>
<th>Preparation Time</th>
<th>Method</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<c:forEach items="${recipesList}" var="recipe">
<tr>
<td>${recipe.recipeId}</td>
<td>${recipe.name}</td>
<td>${recipe.prepTime} minutes</td>
<td>${recipe.method}</td>
<td>
<form action="recipedetail" method="get">
<input type="hidden" name="recipeId" value="${recipe.recipeId}" />
<input type="submit" value="View Details" class="btn btn-info btn-sm" />
</form>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
|
<template>
<section class="text-gray-600 body-font overflow-hidden">
<div
class="relative isolate overflow-hidden bg-gray-900 px-6 py-24 sm:py-32 lg:px-8"
>
<img
src="https://images.unsplash.com/photo-1521737604893-d14cc237f11d?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&crop=focalpoint&fp-y=.8&w=2830&h=1500&q=80&blend=111827&sat=-100&exp=15&blend-mode=multiply"
alt=""
class="absolute inset-0 -z-10 h-full w-full object-cover"
/>
<div
class="hidden sm:absolute sm:-top-10 sm:right-1/2 sm:-z-10 sm:mr-10 sm:block sm:transform-gpu sm:blur-3xl"
aria-hidden="true"
>
<div
class="aspect-[1097/845] w-[68.5625rem] bg-gradient-to-tr from-[#ff4694] to-[#776fff] opacity-20"
style="
clip-path: polygon(
74.1% 44.1%,
100% 61.6%,
97.5% 26.9%,
85.5% 0.1%,
80.7% 2%,
72.5% 32.5%,
60.2% 62.4%,
52.4% 68.1%,
47.5% 58.3%,
45.2% 34.5%,
27.5% 76.7%,
0.1% 64.9%,
17.9% 100%,
27.6% 76.8%,
76.1% 97.7%,
74.1% 44.1%
);
"
></div>
</div>
<div
class="absolute -top-52 left-1/2 -z-10 -translate-x-1/2 transform-gpu blur-3xl sm:top-[-28rem] sm:ml-16 sm:translate-x-0 sm:transform-gpu"
aria-hidden="true"
>
<div
class="aspect-[1097/845] w-[68.5625rem] bg-gradient-to-tr from-[#ff4694] to-[#776fff] opacity-20"
style="
clip-path: polygon(
74.1% 44.1%,
100% 61.6%,
97.5% 26.9%,
85.5% 0.1%,
80.7% 2%,
72.5% 32.5%,
60.2% 62.4%,
52.4% 68.1%,
47.5% 58.3%,
45.2% 34.5%,
27.5% 76.7%,
0.1% 64.9%,
17.9% 100%,
27.6% 76.8%,
76.1% 97.7%,
74.1% 44.1%
);
"
></div>
</div>
<div class="mx-auto max-w-2xl text-center">
<h2 class="text-4xl font-bold tracking-tight text-white sm:text-6xl">
PANAFSTRAG Programmes
</h2>
<p class="mt-6 text-lg leading-8 text-gray-300">
Explore our programmes
</p>
</div>
</div>
<div class="container px-5 py-24 mx-auto">
<div class="flex flex-wrap w-full mb-20">
<div class="lg:w-1/2 w-full mb-6 lg:mb-0">
<h1
class="sm:text-3xl text-2xl font-medium title-font mb-2 text-gray-900"
>
PANAFSTRAG Programmes
</h1>
<div class="h-1 w-20 bg-indigo-500 rounded"></div>
</div>
</div>
<!-- <div class="flex flex-wrap -m-12">
<ActiveProgrammes
v-for="program in activeProgrammes"
:key="program._id"
:program="program"
/>
</div> -->
<div class="flex flex-wrap -m-12">
<PendingProgrammes
v-for="program in pendingProgrammes"
:key="program._id"
:program="program"
/>
</div>
<div class="flex flex-wrap -m-12">
<CompletedProgrammes
v-for="program in completedProgrammes"
:key="program._id"
:program="program"
/>
</div>
</div>
</section>
</template>
<script>
import ActiveProgrammes from "@/components/Programmes/Active.vue";
import PendingProgrammes from "@/components/Programmes/Pending.vue";
import CompletedProgrammes from "@/components/Programmes/Completed.vue";
// import community_programmes from '@/database/programmes.json'
import _ from "lodash";
export default {
name: "programme",
scrollToTop: true,
components: {
ActiveProgrammes,
PendingProgrammes,
CompletedProgrammes,
},
data() {
return {
isOpen: true,
programmes: null,
url: "https://panafstrag.onrender.com/api/panAfrica/programmes",
starting_date: null,
ending_date: null,
title: "Pan Africa programmes and conferences",
description:
"Pan Africa; Original thinking, research help add to human knowledge",
image:
"https://res.cloudinary.com/marquis/image/upload/v1668940037/enagoshtazxadezqqjrj.png",
};
},
head() {
return {
title: "PANAFSTRAG Programmes",
meta: [
{
hid: "twitter:title",
name: "twitter:title",
content: this.title,
},
{
hid: "twitter:description",
name: "twitter:description",
content: this.description,
},
{
hid: "twitter:image",
name: "twitter:image",
content: this.image,
},
{
hid: "twitter:image:alt",
name: "twitter:image:alt",
content: this.title,
},
{
hid: "og:title",
property: "og:title",
content: this.title,
},
{
hid: "og:description",
property: "og:description",
content: this.description,
},
{
hid: "og:image",
property: "og:image",
content: this.image,
},
{
hid: "og:image:secure_url",
property: "og:image:secure_url",
content: this.image,
},
{
hid: "og:image:alt",
property: "og:image:alt",
content: this.title,
},
],
};
},
methods: {
toggle() {
this.isOpen = !this.isOpen;
},
goBack() {
this.$router.go(-1);
},
timeFrame(program) {
if (program.status === "pending") {
let result = this.$moment(program.endDate).format("YYYY");
return result;
}
let startDay = this.$moment(program.startDate)
.format("YYYY-MMMM-Do")
.split("-")[2];
let endDay = this.$moment(program.endDate)
.format("YYYY-MMMM-Do")
.split("-")[2];
let month = this.$moment(program.endDate)
.format("YYYY-MMMM-Do")
.split("-")[1];
let year = this.$moment(program.endDate)
.format("YYYY-MM-DD")
.split("-")[0];
if (startDay === endDay) {
return `${endDay}, ${month}, ${year}`;
}
return `${startDay} to ${endDay}, ${month}, ${year}`;
},
},
computed: {
recentProgrammes() {
return this.programmes?.filter((p) => {
this.starting_date = p?.startDate;
this.ending_date = p?.endDate;
let endDate = this.$moment(p.endDate)
.format("YYYY-MM-DD")
.split("-")[0];
let currentDate = this.$moment(new Date())
.format("YYYY-MM-DD")
.split("-")[0];
return Number(currentDate) - Number(endDate) <= 2;
});
},
pendingProgrammes() {
return this.programmes?.filter((p) => {
return p.status === "pending";
});
},
completedProgrammes() {
return this.programmes?.filter((p) => {
return p.status === "completed";
});
},
activeProgrammes() {
return this.programmes?.filter((p) => {
return p.status === "active";
});
},
},
async mounted() {
try {
const response = await this.$axios.get("/data/programmes.json");
this.programmes = response.data;
} catch (error) {
console.error("Error fetching JSON data:", error);
}
},
};
</script>
|
import { EmployeeModel } from '../../domain/employee'
import { UpdateEmployeeModel } from '../../domain/usecases/updateEmployee'
import { DbUpdateEmployeeUseCase } from './dbUpdateEmployee'
import { UpdateEmployeeRepository } from '../protocols/updateEmployeeRepository'
const makeUpdateEmployeeRepositoryStub = (): UpdateEmployeeRepository => {
class UpdateEmployeeRepository implements UpdateEmployeeRepository {
async update(employeeData: UpdateEmployeeModel): Promise<EmployeeModel> {
const updatedModel = {
...employeeData,
}
return updatedModel
}
}
return new UpdateEmployeeRepository()
}
interface SutTypes {
sut: DbUpdateEmployeeUseCase
updateEmployeeRepositoryStub: UpdateEmployeeRepository
}
const makeSut = (): SutTypes => {
const updateEmployeeRepositoryStub = makeUpdateEmployeeRepositoryStub()
const sut = new DbUpdateEmployeeUseCase(updateEmployeeRepositoryStub)
return {
sut,
updateEmployeeRepositoryStub,
}
}
describe('DbUpdateEmployeeUseCase', () => {
it('Should call UpdateEmployeeRepository with correct values', async () => {
const { sut, updateEmployeeRepositoryStub } = makeSut()
const updateRepositoryStubSpy = jest.spyOn(
updateEmployeeRepositoryStub,
'update'
)
const employee = {
id: '1234',
nome: 'John',
idade: '30',
cargo: 'Chefia',
}
const updatedEmployee = await sut.execute(employee)
expect(updateRepositoryStubSpy).toHaveBeenCalledWith({
id: '1234',
nome: 'John',
idade: '30',
cargo: 'Chefia',
})
})
it('Should throw if UpdateEmployeeRepository throws', async () => {
const { sut, updateEmployeeRepositoryStub } = makeSut()
jest
.spyOn(updateEmployeeRepositoryStub, 'update')
.mockReturnValueOnce(
new Promise((resolve, reject) => reject(new Error()))
)
const employeeData = {
id: '1234',
nome: 'John',
idade: '30',
cargo: 'Chefia',
}
const promise = sut.execute(employeeData)
await expect(promise).rejects.toThrow()
})
it('Should return an Employee on sucess', async () => {
const { sut } = makeSut()
const employeeData = {
id: '1234',
nome: 'Thales',
idade: '28',
cargo: 'Desenvolvedor',
}
const employee = await sut.execute(employeeData)
expect(employee).toEqual({
id: '1234',
nome: 'Thales',
idade: '28',
cargo: 'Desenvolvedor',
})
})
})
|
package prettyTimer
import (
"fmt"
"math"
"sort"
"time"
)
type TimingStats struct {
Count int
TotalTime time.Duration
MinTime time.Duration
MaxTime time.Duration
Timings []time.Duration // To keep track of individual timings for percentile calculation
startTime time.Time // To keep track of the time when Start() is called
}
// Initialize a TimingStats instance with reasonable defaults
func NewTimingStats() *TimingStats {
return &TimingStats{
MinTime: time.Duration(math.MaxInt64), // Initialize to a high value
MaxTime: time.Duration(math.MinInt64), // Initialize to a low value
}
}
// Record a new timing
func (t *TimingStats) RecordTiming(duration time.Duration) {
t.Count++
t.TotalTime += duration
if duration < t.MinTime {
t.MinTime = duration
}
if duration > t.MaxTime {
t.MaxTime = duration
}
t.Timings = append(t.Timings, duration)
}
// Start the timer
func (t *TimingStats) Start() {
t.startTime = time.Now()
}
// Finish the timer and record the timing
func (t *TimingStats) Finish() {
elapsed := time.Since(t.startTime)
t.RecordTiming(elapsed)
}
// Calculate percentile
func (t *TimingStats) CalculatePercentile(percentile float64) time.Duration {
if t.Count == 0 {
return 0
}
sort.Slice(t.Timings, func(i, j int) bool { return t.Timings[i] < t.Timings[j] })
index := int(math.Ceil((percentile/100.0)*float64(len(t.Timings)))) - 1
if index < 0 {
return t.Timings[0]
}
return t.Timings[index]
}
// ANSI color codes
const (
Reset = "\033[0m"
Red = "\033[31m"
Green = "\033[32m"
Yellow = "\033[33m"
Blue = "\033[34m"
Purple = "\033[35m"
)
// Print stats to stdout
func (t *TimingStats) PrintStats() {
if t.Count == 0 {
fmt.Println(Red + "No timings recorded" + Reset)
return
}
avgTime := t.TotalTime / time.Duration(t.Count)
fmt.Printf(Green+"Min Time: %s, "+Yellow+"Max Time: %s, "+Purple+"Avg Time: %s, "+Blue+"Count: %d\n"+Reset, t.MinTime, t.MaxTime, avgTime, t.Count)
// Percentile calculations
fmt.Printf(Red+"50th: %s, "+Green+"90th: %s, "+Purple+"99th: %s\n"+Reset, t.CalculatePercentile(50), t.CalculatePercentile(90), t.CalculatePercentile(99))
}
// Return stats as struct
type Stats struct {
MinTime time.Duration
MaxTime time.Duration
AvgTime time.Duration
Count int
Percent50 time.Duration
Percent90 time.Duration
Percent99 time.Duration
}
// Return stats as struct
func (t *TimingStats) GetStats() Stats {
if t.Count == 0 {
return Stats{}
}
return Stats{
MinTime: t.MinTime,
MaxTime: t.MaxTime,
AvgTime: t.TotalTime / time.Duration(t.Count),
Count: t.Count,
Percent50: t.CalculatePercentile(50),
Percent90: t.CalculatePercentile(90),
Percent99: t.CalculatePercentile(99),
}
}
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import missingno as msno
plt.style.use('seaborn-darkgrid')
palette = plt.get_cmap('Set2')
train = pd.read_csv('_data/input/house-prices-advanced-regression-techniques/train.csv')
test = pd.read_csv('_data/input/house-prices-advanced-regression-techniques/test.csv')
train.head(10)
test.head(10)
train.info()
msno.bar(train.iloc[:, :40])
msno.bar(train.iloc[:, 40:])
train.iloc[:, :40].describe()
train.iloc[:, 40:-1].describe()
pd.DataFrame(train['SalePrice'].describe())
plt.figure(figsize=(12, 7))
sns.distplot(train['SalePrice']).set(ylabel=None, xlabel=None)
plt.title('House price distribution histogram', fontsize=18)
train['SalePrice'] = np.log1p(train['SalePrice'])
plt.figure(figsize=(12, 7))
sns.distplot(train['SalePrice'])
plt.title('House price distribution histogram after fix', fontsize=18)
corr_train = train.corr()
colormap = plt.cm.RdBu
plt.figure(figsize=(14, 12))
plt.title('Pearson correlation matrix between features', y=1, size=15)
sns.heatmap(corr_train, vmax=0.8, square=True, cmap=colormap)
train.head()
highest_corr_features = corr_train.index[abs(corr_train['SalePrice']) > 0.5]
plt.figure(figsize=(14, 12))
plt.title('Pearson correlation matrix between features and "SalePrice"', y=1, size=15)
sns.heatmap(train[highest_corr_features].corr(), linewidths=0.1, vmax=1.0, square=True, cmap=colormap, linecolor='white', annot=True)
SalePrice = pd.DataFrame(corr_train['SalePrice'].sort_values(ascending=False))
SalePrice
features = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'FullBath', 'YearBuilt']
sns.pairplot(train[features])
y_train = train['SalePrice']
test_id = test['Id']
data = pd.concat([train, test], axis=0, sort=False)
data = data.drop(['Id', 'SalePrice'], axis=1)
Total = data.isnull().sum().sort_values(ascending=False)
percent = (data.isnull().sum() / data.isnull().count()).sort_values(ascending=False)
missing_data = pd.concat([Total, percent], axis=1, keys=['Total', 'Percent'])
missing_data.head(25)
data.drop(missing_data[missing_data['Total'] > 5].index, axis=1, inplace=True)
print(data.isnull().sum().max())
numeric_missed = ['BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath', 'GarageArea', 'GarageCars']
for feature in numeric_missed:
data[feature].fillna(0, inplace=True)
categorical_missed = ['Exterior1st', 'Exterior2nd', 'SaleType', 'MSZoning', 'Electrical', 'KitchenQual']
for feature in categorical_missed:
data[feature].fillna(data[feature].mode()[0], inplace=True)
data['Functional'].fillna('Typ', inplace=True)
data.isnull().sum().max()
from scipy.stats import skew
numeric = data.dtypes[data.dtypes != 'object'].index
skewed = data[numeric].apply(lambda col: skew(col)).sort_values(ascending=False)
skewed = skewed[abs(skewed) > 0.5]
for feature in skewed.index:
data[feature] = np.log1p(data[feature])
data['TotalSF'] = data['TotalBsmtSF'] + data['1stFlrSF'] + data['2ndFlrSF']
data = pd.get_dummies(data)
data
x_train = data[:len(y_train)]
x_test = data[len(y_train):]
from sklearn.metrics import make_scorer
from sklearn.model_selection import KFold, cross_val_score
from sklearn.metrics import mean_squared_error
import xgboost as XGB
xgb_model = XGB.XGBRegressor(colsample_bytree=0.4603, gamma=0.0468, learning_rate=0.05, max_depth=3, min_child_weight=1.7817, n_estimators=2200, reg_alpha=0.464, reg_lambda=0.8571, subsample=0.5213, random_state=7, nthread=-1)
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { render } from '@testing-library/react';
import React from 'react';
import { RiskScoreEntity } from '../../../../../common/search_strategy';
import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features';
import { useSpaceId } from '../../../../common/hooks/use_space_id';
import { TestProviders } from '../../../../common/mock';
import { ChartContent } from './chart_content';
import { mockSeverityCount } from './__mocks__';
jest.mock('../../../../common/components/visualization_actions/visualization_embeddable');
jest.mock('../../../../common/hooks/use_experimental_features', () => ({
useIsExperimentalFeatureEnabled: jest.fn(),
}));
jest.mock('../../../../common/hooks/use_space_id', () => ({
useSpaceId: jest.fn(),
}));
describe('ChartContent', () => {
beforeEach(() => {
jest.clearAllMocks();
(useIsExperimentalFeatureEnabled as jest.Mock).mockReturnValue(false);
(useSpaceId as jest.Mock).mockReturnValue('default');
});
it('renders VisualizationEmbeddable when isChartEmbeddablesEnabled = true and dataExists = true', () => {
(useIsExperimentalFeatureEnabled as jest.Mock).mockReturnValue(true);
const { getByTestId } = render(
<ChartContent
dataExists={true}
kpiQueryId="mockQueryId"
riskEntity={RiskScoreEntity.host}
severityCount={undefined}
timerange={{ from: '2022-04-05T12:00:00.000Z', to: '2022-04-08T12:00:00.000Z' }}
/>
);
expect(getByTestId('visualization-embeddable')).toBeInTheDocument();
});
it('should not render VisualizationEmbeddable when dataExists = false', () => {
(useIsExperimentalFeatureEnabled as jest.Mock).mockReturnValue(true);
const { queryByTestId } = render(
<TestProviders>
<ChartContent
dataExists={false}
kpiQueryId="mockQueryId"
riskEntity={RiskScoreEntity.host}
severityCount={undefined}
timerange={{ from: '2022-04-05T12:00:00.000Z', to: '2022-04-08T12:00:00.000Z' }}
/>
</TestProviders>
);
expect(queryByTestId('visualization-embeddable')).not.toBeInTheDocument();
});
it('should not render VisualizationEmbeddable when spaceId = undefined', () => {
(useIsExperimentalFeatureEnabled as jest.Mock).mockReturnValue(true);
(useSpaceId as jest.Mock).mockReturnValue(undefined);
const { queryByTestId } = render(
<TestProviders>
<ChartContent
dataExists={false}
kpiQueryId="mockQueryId"
riskEntity={RiskScoreEntity.host}
severityCount={undefined}
timerange={{ from: '2022-04-05T12:00:00.000Z', to: '2022-04-08T12:00:00.000Z' }}
/>
</TestProviders>
);
expect(queryByTestId('visualization-embeddable')).not.toBeInTheDocument();
});
it('renders RiskScoreDonutChart when isChartEmbeddablesEnabled = false', () => {
const { getByTestId } = render(
<TestProviders>
<ChartContent
dataExists={true}
kpiQueryId="mockQueryId"
riskEntity={RiskScoreEntity.host}
severityCount={mockSeverityCount}
timerange={{ from: '2022-04-05T12:00:00.000Z', to: '2022-04-08T12:00:00.000Z' }}
/>
</TestProviders>
);
expect(getByTestId('risk-score-donut-chart')).toBeInTheDocument();
});
});
|
<template>
<q-layout view="lHh Lpr lff" class="shadow-2 rounded-borders">
<q-header elevated style="background-color: rgb(103,62,132)">
<q-toolbar>
<q-btn
flat
round
dense
icon="menu"
aria-label="Menu"
@click="drawer = !drawer"
/>
<q-toolbar-title>
Plantilla IEEN
</q-toolbar-title>
<div><q-btn flat label="Cerrar Sesión" text-color="white" /></div>
</q-toolbar>
</q-header>
<q-footer elevated class="bg-purple-ieen">
<q-toolbar>
<q-toolbar-title>Unidad Técnica de Informática y Estadística</q-toolbar-title>
</q-toolbar>
</q-footer>
<q-drawer
v-model="drawer"
show-if-above
:width="250"
:breakpoint="400"
class="text-black"
>
<q-scroll-area style="height: calc(100% - 130px); margin-top: 130px; border-right: 1px solid #ddd">
<q-list style="border-right: 1px solid #ddd">
<EssentialLink
v-for="link in essentialLinks"
:key="link.title"
v-bind="link"
/>
</q-list>
</q-scroll-area>
<q-img class="absolute-top" src="~assets/Fondo.png" style="height: 130px" >
<div class="absolute-bottom bg-transparent">
<q-avatar size="56px" class="q-mb-sm">
<img src="~assets/usuario.png">
</q-avatar>
<div class="text-weight-bold text-black">Nombre Usuario</div>
<div class=" text-black">Puesto en IEEN </div>
</div>
</q-img>
</q-drawer>
<q-page-container>
<router-view />
</q-page-container>
</q-layout>
</template>
<style lang="scss">
.text-purple-ieen{
color:#673E84 !important;
}
.bg-purple-ieen{
background: #673E84 !important;
}
.text-purple-ieen-1{
color:#863399 !important;
}
.bg-purple-ieen-1{
background: #863399 !important;
}
.text-purple-ieen-2{
color:#a25eb5 !important;
}
.bg-purple-ieen-2{
background: #a25eb5 !important;
}
.text-purple-ieen-3{
color:#bb83ca !important;
}
.bg-purple-ieen-3{
background: #bb83ca !important;
}
.text-pink-ieen-1{
color:#b32572 !important;
}
.bg-pink-ieen-1{
background: #b32572 !important;
}
.text-pink-ieen-2{
color:#cc5599 !important;
}
.bg-pink-ieen-2{
background: #cc5599 !important;
}
.text-pink-ieen-3{
color:#dd85ba !important;
}
.bg-pink-ieen-3{
background: #dd85ba !important;
}
.text-gray-ieen-1{
color:#76777a !important;
}
.bg-gray-ieen-1{
background: #76777a !important;
}
.text-gray-ieen-2{
color:#98989a !important;
}
.bg-gray-ieen-2{
background: #98989a !important;
}
.text-gray-ieen-3{
color:#b1b1b1 !important;
}
.bg-gray-ieen-3{
background: #b1b1b1 !important;
}
</style>
<script>
import EssentialLink from 'components/EssentialLink.vue'
const linksList = [
{
title: 'Componentes',
icon: 'grid_view',
link: {name:'botones'}
},
{
title: 'Colores',
icon: 'palette',
link: {name:'colores'}
},
{
title: 'Ejemplo 1',
icon: 'looks_one',
link: {name:'ejemplo1'}
},
{
title: 'Ejemplo 2',
icon: 'looks_two',
link: {name:'ejemplo2'}
},
]
import { defineComponent, ref } from 'vue'
export default defineComponent({
name: 'MainLayout',
components: {
EssentialLink
},
setup () {
const leftDrawerOpen = ref(false)
return {
leftDrawerOpen,
essentialLinks: linksList,
drawer: ref(false),
miniState: ref(false),
toggleLeftDrawer () {
leftDrawerOpen.value = !leftDrawerOpen.value
}
}
}
})
</script>
|
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\OrdersController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/
// Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
// return $request->user();
// });
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::get('/orders',[OrdersController::class,'index']);
Route::post('/add/order',[OrdersController::class,'store']);
Route::post('/update/{id}',[OrdersController::class,'update']);
Route::post('logout',[AuthController::class,'logout']);
Route::post('/delete/{id}',[OrdersController::class,'destroy']);
});
Route::post('login',[AuthController::class,'login']);
Route::post('register',[AuthController::class,'register']);
|
%$Id: $
\documentclass{mumie.article}
%$Id$
\begin{metainfo}
\name{
\lang{de}{Gauß-Verfahren}
\lang{en}{Gaussian elimination}
}
\begin{description}
This work is licensed under the Creative Commons License Attribution 4.0 International (CC-BY 4.0)
https://creativecommons.org/licenses/by/4.0/legalcode
\lang{de}{Beschreibung}
\lang{en}{}
\end{description}
\begin{components}
\component{generic_image}{content/rwth/HM1/images/g_img_00_video_button_schwarz-blau.meta.xml}{00_video_button_schwarz-blau}
\end{components}
\begin{links}
\link{generic_article}{content/rwth/HM1/T112neu_Lineare_Gleichungssysteme/g_art_content_41_gauss_verfahren.meta.xml}{gauss}
\end{links}
\creategeneric
\end{metainfo}
\begin{content}
\usepackage{mumie.ombplus}
\ombchapter{2}
\ombarticle{2}
\usepackage{mumie.genericvisualization}
\title{\lang{de}{Gauß-Verfahren über allgemeinen Körpern} \lang{en}{Gaussian elinimation over any field}}
\begin{block}[annotation]
\end{block}
\begin{block}[annotation]
Im Ticket-System: \href{http://team.mumie.net/issues/11196}{Ticket 11196}\\
\end{block}
\begin{block}[info-box]
\tableofcontents
\end{block}
\lang{de}{
Das \notion{Gauß-Verfahren} zum L\"osen linearer Gleichungssysteme (LGS) über den reellen Zahlen wurde bereits in
\link{gauss}{Teil 1} eingeführt.
Die Idee des Gauß-Verfahrens ist es, die Gleichungen des LGS (bzw. die Zeilen der zugehörigen erweiterten Koeffizientenmatrix)
so umzuformen, dass man am Ende
die Lösungsmenge des Gleichungssystems leicht angeben kann.
In diesem Abschnitt wird das Gauß-Verfahren für die erweiterte Koeffizientenmatrix wiederholt.
Allerdings werden die Koeffizienten nun über beliebigen Körpern $\mathbb{K}$ betrachtet.\\
Außerdem werden wir zeigen, wie man eine Menge von linearen Gleichungssystemen $Ax=b$ lösen kann,
bei denen sich jeweils nur der Vektor $b$ unterscheidet.\\
Im Folgenden betrachten wir stets ein lineares Gleichungssystem der Form
\begin{equation*}
\begin{mtable}[\cellaligns{ccccccccc}]
a_{11} x_1 & + & a_{12} x_2 & + & \cdots & + & a_{1n} x_n & = & b_1 \\
a_{21} x_1 & + & a_{22} x_2 & + & \cdots & + & a_{2n} x_n & = & b_2 \\
\vdots & & \vdots & & & & \vdots & & \vdots \\
a_{m1} x_1 & + & a_{m2} x_2 & + & \cdots & + & a_{mn} x_n & = & b_m
\end{mtable} \label{eq:lgs1}
\end{equation*}
mit Elementen $a_{ij}\in \mathbb{K}$ für $1 \leq i \leq m$ und $1 \leq j \leq n$ und $b_1, \ldots, b_m\in \mathbb{K}$, sowie die zugehörige erweiterte Koeffizientenmatrix
\begin{equation*}
(A \ \mid \ b) = \underbrace{\left( \begin{smallmatrix}
a_{11} & a_{12} & \cdots & a_{1n} & | & b_1\\
a_{21} & a_{22} & \cdots & a_{2n} & | &b_2\\
\vdots & \vdots & \ddots & \vdots & \mid &\vdots\\
a_{m1} & a_{m2} & \cdots & a_{mn} &| & b_m
\end{smallmatrix} \right) }_{
\in M(m,n+1;\mathbb{K})}.
\end{equation*}
Ziel des Gauß-Verfahrens ist es, eine Matrix schrittweise in Stufenform zu bringen und anschließend daraus die Lösungsmenge anzugeben.}
\lang{en}{
The \notion{Gaussian elimination} for solving linear system over the real numbers was already introduced in \link{gauss}{Part 1}.
The idea of the Gaussian elimination is to manipulate the equations of the system (or rather the rows of the corresponding augmented matrix)
into a form, which makes it easy to find the solution set.
This section reviews the Gaussian elimination for the augmented matrix, but the coefficients will be elements of any field $\mathbb{K}$.\\
Further on, we will see, how we can solve a set of linear equations $Ax=b$, that differs only in the vector $b$.
In the following linear systems will have the form
\begin{equation*}
\begin{mtable}[\cellaligns{ccccccccc}]
a_{11} x_1 & + & a_{12} x_2 & + & \cdots & + & a_{1n} x_n & = & b_1 \\
a_{21} x_1 & + & a_{22} x_2 & + & \cdots & + & a_{2n} x_n & = & b_2 \\
\vdots & & \vdots & & & & \vdots & & \vdots \\
a_{m1} x_1 & + & a_{m2} x_2 & + & \cdots & + & a_{mn} x_n & = & b_m
\end{mtable} \label{eq:lgs1}
\end{equation*}
with $a_{ij}\in \mathbb{K}$ for $1 \leq i \leq m$ and $1 \leq j \leq n$ and $b_1, \ldots, b_m\in \mathbb{K}$, plus the corresponding augmented coefficient matrix
\begin{equation*}
(A \ \mid \ b) = \underbrace{\left( \begin{smallmatrix}
a_{11} & a_{12} & \cdots & a_{1n} & | & b_1\\
a_{21} & a_{22} & \cdots & a_{2n} & | &b_2\\
\vdots & \vdots & \ddots & \vdots & \mid &\vdots\\
a_{m1} & a_{m2} & \cdots & a_{mn} &| & b_m
\end{smallmatrix} \right) }_{
\in M(m,n+1;\mathbb{K})}.
\end{equation*}
The aim of the Gaussian elimination is to manipulate the matrix step-by-step into the reduced echelon row form, from which the solution can be read.}
\section{\lang{de}{Die Stufenform}\lang{en}{Row echelon form}}
\begin{definition}[\lang{de}{Stufenform} \lang{en}{row echelon form}]\label{def:stufenformen}\label{stufenform}
\lang{de}{
Ein LGS liegt in \notion{Stufenform} vor, wenn für jede Gleichung die
%(lexikographisch)
erste auftretende Variable
in allen folgenden Gleichungen nicht mehr auftritt (oder die Gleichung gar keine Variablen enthält).\\
Betrachtet man die Stufenform der dazugehörigen erweiterten Koeffizientenmatrix, so hat diese die Form}
\lang{en}{
A linear system is in \notion{row echelon form}, if for each equation the leading term is not appearing in the following equations (i.e. the coefficient is zero).\\
The augmented matrix corresponding to a linear system in row echelon form has the following form}
\[ \begin{pmatrix}
a_{1} & \star & \cdots & \star & \star&| & b_1\\
0 & a_{2} & \cdots & \star & \star&| & b_2\\
\vdots & \, & \ddots & \, & \vdots&| & \vdots\\
0 & 0 & \cdots & a_{k} & \star&| & b_k\\
0 & 0 & \cdots & 0 & 0&| & \vdots \\
0 & 0 & \cdots & 0 & 0&| & b_{m}\\
\end{pmatrix},\]
\lang{de}{wobei der Eintrag $a_{i}$ jeweils dem ersten Koeffizienten ungleich Null der $i$-ten Gleichung entspricht. Diesen Koeffizienten nennen wir \notion{Stufenelement} (oder Stufeneintrag).
Der "$\star$" steht jeweils für einen beliebigen Eintrag.
Das LGS liegt in \notion{reduzierter Stufenform} vor, wenn die ersten auftretenden Variablen sogar in keiner anderen Gleichung
auftreten, also auch nicht in den darüber liegenden, und ihre Koeffizienten zusätzlich den Wert 1 besitzen.\\
Die entsprechende reduzierte Stufenform der erweiterten Koeffizientenmatrix hat damit die Form}
\lang{en}{where $a_{i}$ is the first non-zero coefficient of the $i$th row. This coefficient is called the \notion{leading coefficient} of the row/equation.
The "$\star$" here may be any element.
The linear system is in \notion{reduced row echelon form}, if the variable in the leading term do not appear in any other equation/row (not only in the following equations/rows)
and the leading coefficient of each row is 1.\\
The augmented matrix corresponding to a linear system in reduced row echelon form has the following form:}
\[ \begin{pmatrix}
1 & 0 & \cdots & 0 & \star&| & b_1\\
0 & 1 & \cdots & 0 & \star&| & b_2\\
\vdots & \, & \ddots & \, & \vdots &| & \vdots\\
0 & 0 & \cdots & 1 & \star&| & b_k\\
0 & 0 & \cdots & 0 & 0&| & \vdots \\
0 & 0 & \cdots & 0 & 0&| & b_{m}\\
\end{pmatrix}.\]
\lang{de}{Dabei ist zu beachten, dass nur die Einträge über und unter einem Stufenelement Null sein müssen.}
\lang{en}{It is important to note, that the elements below and above each leading coefficient must be zero.}
\end{definition}
\lang{de}{
In der Literatur spricht man oft präziser von der Zeilenstufenform.}
\begin{remark}
\lang{de}{
Falls eine Koeffizientenmatrix in Stufenform eine Nullzeile besitzt,
so ist die entsprechende Gleichung des LGS $0=b_i$.
In dieser Gleichung treten also keine Variablen mehr auf.}
\lang{en}{
If the augmented matrix in row echelon form contains a row of zero, the corresponding equation of the linear system is $0=b_i$.
This equation contains no variables.}\\
\end{remark}
\lang{de}{
\begin{example}
\begin{tabs*}
\tab{1. Beispiel}
Die erweiterte Koeffizientenmatrix
\[ \begin{pmatrix} -1 & 2 & 3 & | & 5 \\\textcolor{#0066CC}{0} & 1 & 4 & | & 11 \\\textcolor{#0066CC}{0} & \textcolor{#0066CC}{0} & -2 & | & -6 \end{pmatrix} \]
liegt in Stufenform vor, da die Einträge unter den Stufenelementen Null sind. \\
Es liegt aber keine reduzierte Stufenform vor, da zum einen die Stufenelemente nicht alle Wert 1 haben und die Einträge über ihnen nicht Null sind.
\[ \begin{pmatrix} \textcolor{#CC6600}{-1} & \textcolor{#CC6600}{2} & \textcolor{#CC6600}{3} & | & 5 \\0 & \textcolor{#0066CC}{1} & \textcolor{#CC6600}{4} & | & 11 \\0 & 0 & \textcolor{#CC6600}{-2} & | & -6 \end{pmatrix} \]
\tab{2. Beispiel}
Die erweiterte Koeffizientenmatrix
\[ \begin{pmatrix} 2 & -4-2i & | & 10 \\\textcolor{#CC6600}{6i} &6-12i & | & 30i \end{pmatrix} \]
über den komplexen Zahlen liegt nicht in Stufenform vor, da der Koeffizient $6i$ Null entsprechen müsste.\\
Anders verhält es sich bei der erweiterten Koeffizientenmatrix
\[ \begin{pmatrix} \textcolor{#0066CC}{1}& -2-i & | & 10 \\0 &0 & | & 0 \end{pmatrix}, \]
bei der der Koeffizient $a_{21}=0$ ist. Außerdem hat das Stufenelement hier den Wert 1 und es existieren keine darüber liegenden Einträge. Damit ist sie sogar in reduzierter Stufenform.
\tab{3. Beispiel}
Die erweiterte Koeffizientenmatrix
\[ \begin{pmatrix}1 & 2 &1 & -1 &| & 7 \\\textcolor{#0066CC}{0} & 1 &-1 & 0 &| & 1\\\textcolor{#0066CC}{0} &\textcolor{#0066CC}{0} &0 & 1 &| & -1 \end{pmatrix}\]
liegt in Stufenform vor, da die Einträge unter den Stufenelementen alle Null entsprechen.\\
Die Stufenform ist jedoch keine reduzierte Stufenform, obwohl die Stufenelemente den Wert 1 besitzen. Denn nicht alle Koeffizienten über den Stufenelementen sind Null.
\[ \begin{pmatrix}\textcolor{#0066CC}{1} & \textcolor{#CC6600}{2} &1 & \textcolor{#CC6600}{-1} &| & 7 \\0 & \textcolor{#0066CC}{1} &-1 & \textcolor{#0066CC}{0} &| & 1\\0 & 0 &0 & \textcolor{#0066CC}{1} &| & -1 \end{pmatrix}\]
\end{tabs*}
\end{example}}
\lang{en}{
\begin{example}
\begin{tabs*}
\tab{1. Example}
The augmented matrix
\[ \begin{pmatrix} -1 & 2 & 3 & | & 5 \\\textcolor{#0066CC}{0} & 1 & 4 & | & 11 \\\textcolor{#0066CC}{0} & \textcolor{#0066CC}{0} & -2 & | & -6 \end{pmatrix} \]
is in row echelon form, because the coefficients below the leading coefficients are zero. \\
The row echelon form is not reduced, because the coefficients of the leading terms have values $\neq 1$ and the entries above are non-zero.
\[ \begin{pmatrix} \textcolor{#CC6600}{-1} & \textcolor{#CC6600}{2} & \textcolor{#CC6600}{3} & | & 5 \\0 & \textcolor{#0066CC}{1} & \textcolor{#CC6600}{4} & | & 11 \\0 & 0 & \textcolor{#CC6600}{-2} & | & -6 \end{pmatrix} \]
\tab{2. Example}
The augmented matrix
\[ \begin{pmatrix} 2 & -4-2i & | & 10 \\\textcolor{#CC6600}{6i} &6-12i & | & 30i \end{pmatrix} \]
over the complex numbers is not in row echelon form, because the coefficient $6i$ should be zero.\\
The situations is different for the augmented matrix
\[ \begin{pmatrix} \textcolor{#0066CC}{1}& -2-i & | & 10 \\0 &0 & | & 0 \end{pmatrix}, \]
because we have $a_{21}=0$. The leading coefficient is 1 and there are no entries above it. For this reason, the matrix is even in reduced row echelon form.
\tab{3. Example}
The augmented matrix
\[ \begin{pmatrix}1 & 2 &1 & -1 &| & 7 \\\textcolor{#0066CC}{0} & 1 &-1 & 0 &| & 1\\\textcolor{#0066CC}{0} &\textcolor{#0066CC}{0} &0 & 1 &| & -1 \end{pmatrix}\]
is in row echelon form, because the entries below the leading coefficients are all zero.\\
The row echelon form is not reduced, although all the leading coefficients have the value 1, because there are non-zero entries above the pivots.
\[ \begin{pmatrix}\textcolor{#0066CC}{1} & \textcolor{#CC6600}{2} &1 & \textcolor{#CC6600}{-1} &| & 7 \\0 & \textcolor{#0066CC}{1} &-1 & \textcolor{#0066CC}{0} &| & 1\\0 & 0 &0 & \textcolor{#0066CC}{1} &| & -1 \end{pmatrix}\]
\end{tabs*}
\end{example}}
\lang{de}{
\begin{quickcheck}
\type{input.interval}
\field{rational}
\precision{3}
\field{real}
\begin{variables}
\randint[Z]{a}{2}{6}
\randint[Z]{b}{2}{8}
\randint[Z]{c}{2}{8}
\randint[Z]{d}{2}{8}
\end{variables}
\text{Für das lineare Gleichungssystem
\[ \begin{mtable}[\cellaligns{crcrcrcr}]
(I)&\var{a} \cdot x & - & \var{c} \cdot y & & &= & 0 \\
(II)& & & \var{b}\cdot y & + & \var{d} \cdot z&= & \var{a}
\end{mtable} \]
gilt: }
\begin{choices}{unique}
\begin{choice}
\text{Es liegt in Stufenform vor, aber nicht in reduzierter Stufenform.}
\solution{true}
\end{choice}
\begin{choice}
\text{Es liegt in reduzierter Stufenform vor.}
\solution{false}
\end{choice}
\begin{choice}
\text{Es liegt nicht in Stufenform vor.}
\solution{false}
\end{choice}
\end{choices}{unique}
\explanation{Das LGS liegt in Stufenform vor, da die Variable $x$ nur in der ersten Gleichung auftritt.\\
Es liegt aber nicht in reduzierter Stufenform vor, da die Variable $y$ (als erste Variable der zweiten Gleichung) ebenfalls in der ersten Gleichung auftaucht.
Zusätzlich besitzen die Stufenelemente nicht den Wert 1.}
\end{quickcheck}}
\lang{en}{
\begin{quickcheck}
\type{input.interval}
\field{rational}
\precision{3}
\field{real}
\begin{variables}
\randint[Z]{a}{2}{6}
\randint[Z]{b}{2}{8}
\randint[Z]{c}{2}{8}
\randint[Z]{d}{2}{8}
\end{variables}
\text{For the linear system
\[ \begin{mtable}[\cellaligns{crcrcrcr}]
(I)&\var{a} \cdot x & - & \var{c} \cdot y & & &= & 0 \\
(II)& & & \var{b}\cdot y & + & \var{d} \cdot z&= & \var{a}
\end{mtable} \]
holds: }
\begin{choices}{unique}
\begin{choice}
\text{The linear system is in row echelon form, but is not reduced.}
\solution{true}
\end{choice}
\begin{choice}
\text{The linear system is in reduced row echelon form.}
\solution{false}
\end{choice}
\begin{choice}
\text{The linear system is not in row echelon form.}
\solution{false}
\end{choice}
\end{choices}{unique}
\explanation{The linear system is in row echelon form, because the variable x is found only in the firs equations.
But the row echelon form is not reduced, since the variable $y$ (as the first variable in the second euqation) is also found in the first equation.
Further on, the pivot elements do not have the value 1.}
\end{quickcheck}}
%Im Allgemeinen sieht ein LGS in Stufenform dann folgendermaßen aus mit gewissen Zahlen $k$ ($1\leq k\leq m$) und
%$1\leq i_1<i_2<\ldots <i_k\leq n$, sowie $c_i\in \R\setminus \{0\}$ und $\tilde{a}_{ij}, \tilde{b}_i\in \R$:
%\begin{equation}\label{eq:lgs2}
% \begin{mtable}[\cellaligns{rrrrrrrrrrrrrrl}]
% c_1 x_{i_1} & + & \cdots & + & \tilde{a}_{1i_2}x_{i_2} & + & \cdots & &\cdots &&\cdots && \cdots & = & \tilde{b}_1 \\
% & & & & c_2 x_{i_2} & + & \cdots &+ & \tilde{a}_{2i_3}x_{i_3} & + &\cdots&& \cdots & = & \tilde{b}_2 \\
% & & & & & & & & c_3 x_{i_3} & + &\cdots&& \cdots & = & \tilde{b}_3 \\
% & & & & & & & & & & \vdots && & & \vdots \\
% & & & & & & & & & & c_k x_{i_k} & + & \cdots & = & \tilde{b}_k \\
% &&&&&&&&&&&& 0 & = & \tilde{b}_{k+1} \\
% &&&&&&&&&&&& \vdots & & \vdots \\
% &&&&&&&&&&&& 0 & = & \tilde{b}_{m}
%\end{mtable}
%\end{equation}
%In der reduzierten Stufenform sind zusätzlich die Koeffizienten über den $c$'s gleich Null.
\lang{de}{
Anhand der Stufenform lässt sich erkennen, ob ein LGS lösbar ist.}
\lang{en}{
From the row echelon form of a linear system we can tell whether it has solutions.}
%und sie lässt sich damit explizit durch Rückwärtseinsetzen berechnen.
\lang{de}{
\begin{theorem}[Lösbarkeit]\label{rule:loesung-parametrisiert}
Ein LGS ist genau dann lösbar,
wenn für die Stufenform (Definition \ref{stufenform})
seiner erweiterten Koeffizientenmatrix
entweder
%Ein LGS und ihre dazugehörige erweiterte Koeffizientenmatrix ist genau
%dann l"osbar, wenn für ihre Stufenform (\ref{stufenform}) entweder
\begin{itemize}
\item $k=m \ $ oder
\item${b}_{k+1}=\ldots = {b}_{m} =0$
\end{itemize}
gilt.\\
Lösbarkeit bedeutet also, dass nach Umformung in Stufenform keine Zeile der Form
$(0 ~$\cdots$~ 0 | b_i)$ mit $b_i \neq 0$
auftritt.
\end{theorem}}
\lang{en}{
\begin{theorem}[\lang{de}{Lösbarkeit} \lang{en}{Solvability}]\label{rule:loesung-parametrisiert}
A linear system is solvable if and only if we have for the row echelon form (Definition \ref{stufenform}) of the augmented matrix
either
%Ein LGS und ihre dazugehörige erweiterte Koeffizientenmatrix ist genau
%dann l"osbar, wenn für ihre Stufenform (\ref{stufenform}) entweder
\begin{itemize}
\item $k=m \ $ or
\item${b}_{k+1}=\ldots = {b}_{m} =0$.
\end{itemize}
Hence, solvability of a linear system corresponds to the non-existence any rows of the form $(0\ldots 0|bi)$ with $bi\neq 0$ in the row echelon form of the system.
\end{theorem}}
\lang{de}{
Ist ein LGS nicht lösbar, so gilt für seine Lösungsmenge $\mathbb{L}=\emptyset$.\\
Für die Bestimmung der Lösungsmenge eines lösbaren LGS gehen wir wie folgt vor.}
\lang{en}{
If a linear system is not solvable, then its solution set is $\mathbb{L}=\emptyset$.
We determine the solution set of a solvable linear system as follows:}
\lang{de}{
\begin{rule}[Bestimmung der Lösungsmenge]\label{rule:bestimmungDerLoesungsmenge}
Um die Lösungsmenge zu berechnen, stellt man die erweiterte Koeffizientenmatrix wieder als lineares Gleichungssystem dar.\\
Unbekannte, die als Koeffizienten einen Stufeneintrag besitzen, werden \notion{abhängige Variablen} genannt und folglich sind alle Unbekannten
ohne einen Stufeneintrag als Koeffizienten \notion{unabhängige} oder \notion{freie Variablen}.\\
Für letztere werden Parameter gewählt und
anschließend wird das Gleichungssystem nach den abhängigen Variablen durch \notion{Rückwärtseinsetzen} aufgelöst.\\
Ist das LGS in reduzierter Stufenform, so enthält jede Gleichung höchstens eine abhängige Variable und diese kann direkt in Abhängigkeit der Parameter abgelesen werden (falls vorhanden).
Besitzt ein lösbares LGS keine freien Variablen, so besteht die Lösungsmenge aus genau einem Lösungsvektor.
\end{rule}}
\lang{en}{
\begin{rule}[Determining the solution set]\label{rule:bestimmungDerLoesungsmenge}
For determining the solution of a linear system, it needs to be considered as a system of linear equations, instead of a matrix.\\
The leading variable of a row is called \notion{dependent variable} and all variables in non-leading terms are naturally called \notion{independent} or \notion{free variables}.\\
For those, we choose parameters to represent them and afterwards we solve the linear system in a process called \notion{back substitution}.\\
If the linear system is in reduced row echelon form, each non-zero equation contains at most one dependent variable and can be rearranged to give the solution of these dependent variables in terms of parameters (if existing).
If the linear system has no independent variables, then the solution set consists of exactly one solution vector.
\end{rule}}
\lang{de}{
Rückwärtseinsetzen bedeutet, dass man bei der letzten Gleichung beginnend alle Gleichungen von unten nach oben nach der
ersten auftretenden Variable l\"ost,
indem man alle bereits in Parametern ausgedrückten oder durch Werte berechneten Variablen in die darüber liegenden Gleichungen einsetzt.\\
Dadurch erhält man für alle Variablen Werte oder Ausdrücke in den Parametern.
\begin{remark}
Werden die freien bzw. abhängigen Variablen anders gewählt, so ändert sich die Lösungsmenge nicht. Sie erhält dadurch aber eine andere Darstellungsform.
\end{remark}}
\lang{en}{
Back substitution is a process, that dissolves all equations for its leading variables. We rearrange the last equation by expressing its leading variable in terms of the
parameters and substitute the calculated variable in the above equation, and so on.
Thereby all variables will be expressed in terms of the parameters.
\begin{remark}
Changing the (in-)dependent variables does not change the solution set, but the representation may change.
\end{remark}}
\begin{example} \label{gauss1}
\begin{tabs*}
\tab{\lang{de}{1. Beispiel} \lang{en}{1. Example}}
\lang{de}{
Im LGS
\begin{displaymath}
\begin{mtable}[\cellaligns{ccrcrcrcr}]
(I)&\qquad-&x&+&2y&+&3z&=&5\\
(II)&&&&y&+&4z&=&11\\
(III)&&&&&-&2z&=&-6
\end{mtable}
\end{displaymath}
ist jede Variable die erste auftretende Variable einer Gleichung. Es gibt daher keine freien Variablen, und für alle Variablen können
Werte berechnet werden.
Zun\"achst wird die dritte Gleichung nach der Variable $z$ aufgel\"ost.
\begin{displaymath}
(III) \qquad z=3
\end{displaymath}
Diesen Wert setzt man in die zweite Gleichung ein, um die Variable $y$ zu bestimmen.
\begin{displaymath}
(II) \qquad y+4\cdot3=11 \quad \Leftrightarrow \quad y=-1
\end{displaymath}
Anschlie{\ss}end werden beide Werte in die erste Gleichung eingesetzt, um daraus $x$ zu berechnen.
\begin{displaymath}
(I) \qquad -x+2\cdot(-1)+3\cdot3=5 \quad \Leftrightarrow \quad x=2
\end{displaymath}
Das LGS ist eindeutig l\"osbar und besitzt die L\"osungsmenge
\begin{displaymath}
\mathbb{L}=\left\{\begin{pmatrix}2\\ -1\\ 3\end{pmatrix} \right\}.
\end{displaymath}}
\lang{en}{
In the linear system
\begin{displaymath}
\begin{mtable}[\cellaligns{ccrcrcrcr}]
(I)&\qquad-&x&+&2y&+&3z&=&5\\
(II)&&&&y&+&4z&=&11\\
(III)&&&&&-&2z&=&-6
\end{mtable}
\end{displaymath}
each variable is the leading variable of an equation, which is why there are no independent variables. Hence, the value of each
variable can be determined.
First, the third equation is solved for the variable $z$:
\begin{displaymath}
(III) \qquad z=3
\end{displaymath}
This value is then substituted into the second equation in order to calculate the variable $y$:
\begin{displaymath}
(II) \qquad y+4\cdot3=11 \quad \Leftrightarrow \quad y=-1
\end{displaymath}
Next, both values are substituted into the first equation for solving it for $x$:
\begin{displaymath}
(I) \qquad -x+2\cdot(-1)+3\cdot3=5 \quad \Leftrightarrow \quad x=2
\end{displaymath}
The linear system is uniquely solvable and has the solution set:
\begin{displaymath}
\mathbb{L}=\left\{\begin{pmatrix}2\\ -1\\ 3\end{pmatrix} \right\}.
\end{displaymath}}
\tab{\lang{de}{2. Beispiel} \lang{en}{2. Example}}
\lang{de}{
Das LGS über den komplexen Zahlen
\[ \begin{mtable}[\cellaligns{crcrcr}]
(I)&\qquad x & - & (2+i) \cdot y & = & 5 \\
(II)& & & 0 & = & 0
\end{mtable} \]
ist lösbar, da es zwar eine Gleichung ohne Variablen gibt, diese aber $0=0$ entspricht, d.\,h. stets erfüllt ist. Diese Gleichung kann nun
weggelassen werden. In der verbliebenen Gleichung $(I)$ ist $x$ die erste Variable, also eine abhängige Variable und $y$ ist eine
freie Variable. Wir führen daher einen komplexen Parameter $r$ für $y$ ein, setzen also $y=r$.
Nun setzt man $y=r$ in die Gleichung $(I)$ ein, löst sie nach $x$ auf und erhält
\[ x=5+(2+i)r.\]
Die Lösungsmenge ist daher
\[ \mathbb{L}= \left\{ \begin{pmatrix}5+(2+i)r\\ r \end{pmatrix} \, \big| \, r\in \C \right\}
= \left\{ \begin{pmatrix}5\\ 0 \end{pmatrix}+r\cdot \begin{pmatrix} 2+i \\ 1 \end{pmatrix} \, \big| \, r\in \C \right\}. \]}
\lang{en}{
The linear system
\[ \begin{mtable}[\cellaligns{crcrcr}]
(I)&\qquad x & - & (2+i) \cdot y & = & 5 \\
(II)& & & 0 & = & 0
\end{mtable} \]
over the complex numbers is solvable. Though there is an equation without any variables, this equation is $0=$, i.e. always fulfilled.
This equation can be omitted.
In theremaining equationIn der verbliebenen Gleichung $(I)$ the variable $x$ is the first one and therefore a dependent variable.
$y$ is a free variable. We introduce the complex parameter $r$ for $y$ and set $y=r$.
We now subsitute $y=r$ in equation $(I)$, dissolve it for $x$ and we get
\[ x=5+(2+i)r.\]
Therefore the solution set is
\[ \mathbb{L}= \left\{ \begin{pmatrix}5+(2+i)r\\ r \end{pmatrix} \, \big| \, r\in \C \right\}
= \left\{ \begin{pmatrix}5\\ 0 \end{pmatrix}+r\cdot \begin{pmatrix} 2+i \\ 1 \end{pmatrix} \, \big| \, r\in \C \right\}. \] }
\tab{\lang{de}{3. Beispiel} \lang{en}{3. Example}}
\lang{de}{
Im LGS über $\mathbb{R}$
\[ \begin{mtable}[\cellaligns{crcrcrcrcr}]
(I)&\qquad x_1 & + & 2 \cdot x_2 &+ & x_3 & - & x_4 &= & 7 \\
(II)& & & x_2 &- & x_3 & & &= & 1 \\
(III)& & & & & & & x_4 &= & -1
\end{mtable} \]
sind die Variablen $x_1$, $x_2$ und $x_4$ die ersten auftretenden Variablen einer der Gleichungen. Dies sind also die abhängigen Variablen
und die Variable $x_3$ ist eine freie Variable. Wir setzen also $x_3=t$ mit einem reellen Parameter $t$, und rechnen die anderen Variablen
von unten nach oben aus. Die dritte Gleichung ist
\[ x_4=-1. \]
Für die zweite Gleichung gilt:
\[ x_2-t=1 \Leftrightarrow x_2=1+t. \]
Nun setzen wir die Ausdrücke für $x_2$, $x_3$ und $x_4$ in die erste Gleichung ein und lösen nach $x_1$ auf:
\[ x_1+2\cdot (1+t)+t- (-1)=7 \Leftrightarrow x_1=7-2\cdot (1+t)-t-1=4-3t. \]
Die Lösungsmenge ist daher:
\[ \mathbb{L}
= \left\{ \begin{pmatrix} 4-3t \\ 1+t \\t \\ -1\end{pmatrix} \, \big| \, t\in \R \right\}
= \left\{ \begin{pmatrix} 4 \\ 1 \\ 0 \\ -1\end{pmatrix}+ t\cdot \begin{pmatrix} -3\\ 1\\ 1\\ 0 \end{pmatrix} \, \big| \, t\in \R \right\}. \]}
\lang{en}{
In the linear system over $\mathbb{R}$,
\[ \begin{mtable}[\cellaligns{crcrcrcrcr}]
(I)&\qquad x_1 & + & 2 \cdot x_2 &+ & x_3 & - & x_4 &= & 7 \\
(II)& & & x_2 &- & x_3 & & &= & 1 \\
(III)& & & & & & & x_4 &= & -1
\end{mtable} \]
the variables $x_1$, $x_2$ and $x_4$ are the first one in one of the equatiosn.
They are then the dependent variables. $x_3$ is the free variable.
We set $x_3=t$ with $t\in\R$ and determine the other variables by back subituting.
The thrid equation is
\[ x_4=-1. \]
For the second equation we have:
\[ x_2-t=1 \Leftrightarrow x_2=1+t. \]
Now we subsitute the terms for $x_2$, $x_3$ and $x_4$ in the first equation and dissolve it for $x_1$:
\[ x_1+2\cdot (1+t)+t- (-1)=7 \Leftrightarrow x_1=7-2\cdot (1+t)-t-1=4-3t. \]
So, the solution set is:
\[ \mathbb{L}
= \left\{ \begin{pmatrix} 4-3t \\ 1+t \\t \\ -1\end{pmatrix} \, \big| \, t\in \R \right\}
= \left\{ \begin{pmatrix} 4 \\ 1 \\ 0 \\ -1\end{pmatrix}+ t\cdot \begin{pmatrix} -3\\ 1\\ 1\\ 0 \end{pmatrix} \, \big| \, t\in \R \right\}. \]}
\end{tabs*}
\end{example}
\section{\lang{de}{Gauß-Verfahren mit erweiterter Koeffizientenmatrix} \lang{en}{Gaussian elimination for the augmented matrix}}\label{sec:gauss-mit-matrizen}
\lang{de}{
Mit dem Gauß-Verfahren lässt sich jedes lineare Gleichungssystem systematisch in die beschriebene (reduzierte) Stufenform bringen.
Es stellt eine Verallgemeinerung des Additions-Verfahrens dar.}
\lang{en}{
The Gaussian elimination is an algorithm to systematically transform any linear system into (reduced) row echelon form. It is a generalisation of the addition method.}
\begin{definition} \label{def:Gauß-Verfahren}
\lang{de}{
Für das Gauß-Verfahren können folgende sogenannte \notion{elementare Umformungen} auf die Zeilen einer Matrix angewendet werden:}
\lang{en}{
The following are called \notion{elementary row operations} and can be utilized for the Gaussian elimination:}
\begin{itemize}
\item \lang{de}{Vertauschen zweier Zeilen.} \lang{en}{Exchanging/swapping two rows}
\item \lang{de}{Multiplikation einer Zeile mit einer Konstanten $c\neq 0$ mit $c \in \mathbb{K}$.} \lang{en}{Multiplication of a row with a number $c\neq0$}
\item \lang{de}{Addition (Subtraktion) eines $c$-fachen einer Zeile zu (von) einer anderen.} \lang{en}{Addition (or subtraction) of one multiple of a row to (from) another}
\end{itemize}
\end{definition}
\lang{de}{Bevor wir das Gauß-Verfahren betrachten, zunächst eine \textit{Vorbemerkungen}:}
\lang{en}{There are some \textit{preliminary premarks} to look at before considering the Gaussian elimination:}
\lang{de}{
\begin{itemize}
\item Zu Beginn betrachten wir die gesamte
erweiterte Koeffizientenmatrix.
\item Die Schritte des Verfahrens werden wiederholt auf
einer Teilmatrix durchgeführt.
Wenn im Folgenden z.\,B. von der ersten Zeile die Rede ist,
dann ist hiermit immer die erste Zeile
der aktuell betrachteten Teilmatrix gemeint.
\item Wir schreiben $(K)$ für alle Einträge der $k$-ten Zeile,
also $a_{k1}, a_{k2}, \ldots, a_{kn}$.
Handschriftlich adressiert man die Zeilen meist mit
römischen Zahlen: $(I)$, $(II)$, $\ldots$
\end{itemize}}
\lang{en}{
\begin{itemize}
\item First of all we consider the entire augmented matrix.
\item The steps of the elimination are repeatedly applied to a submatrix.
Hereinafter, when talking about e.g. the first row, we always talk about the first row of the currently used submatrix.
\item We write $(K)$ for all entries in the $k$th row,
so $a_{k1}, a_{k2}, \ldots, a_{kn}$.
When solving a linear system by hand, the rows a usually labelled with roman numerals:
römischen Zahlen: $(I)$, $(II)$, $\ldots$
\end{itemize}}
\begin{rule}[\lang{de}{Gauß-Verfahren} \lang{en}{The Gaussian elimination}]
\lang{de}{
\begin{enumerate}
\item[1.] Suche die erste Spalte, die auch Einträge ungleich $0$ enthält. Den Index dieser Spalte bezeichnen wir nun mit $j$.
\item[2.] Vertausche die Zeilen der Matrix ggf. so, dass in dieser Spalte der erste Koeffizient $a_{kj}$ nicht gleich $0$ ist.\\
Dieser Koeffizient entspricht dem Stufenelement dieser Zeile.
%\item Teile die erste Zeile durch den Koeffizienten der ersten Variablen.
\item[3.] Addiere jeweils geeignete Vielfache der ersten Zeile $(K)$ zu den darunter liegenden Zeilen $(L)$,
so dass alle anderen Koeffizienten dieser Spalte gleich $0$ werden:\\
Für alle $l$ mit $k<l$ forme die Zeile $(L)$ zu $(L)-\frac{a_{lj}}{a_{kj}}(K)$ um.
\item[4.] Die erste Zeile der aktuellen Teilmatrix wird nun
nicht mehr verändert.
Wir führen das Gauß-Verfahren ab Schritt~1 für eine neue
Teilmatrix fort: Diese besteht aus der zweiten bis zur letzten Zeile
der aktuellen Teilmatrix.
Das Verfahren wird beendet, wenn nur noch eine Zeile übrig ist
oder die linken Seiten der restlichen Zeilen alle gleich 0 sind.
\end{enumerate}}
\lang{en}{
\begin{enumerate}
\item[1.] Find the first non-zero column. The index of this column, we now call $j$.
\item[2.] If necessary, swap the rows so, that we have $a_{kj}\neq0$ for the first coefficient in the $j$th column.
This coefficient is now the leading element of this row.
%\item Teile die erste Zeile durch den Koeffizienten der ersten Variablen.
\item[3.] Add a suitable multiple of the first row $(K)$ to the rows $(L)$ below so, that all the other coefficients
in this row equal zero:\\
For all $l$ with $k<l$ transform the row $(L)$ to $(L)-\frac{a_{lj}}{a_{kj}}(K)$.
\item[4.] The first row of the current submatrix will not be changed any more. Continue (starting at step~1) with
the Gaussian elimination for a new submatrix, that consists of the second to the last row of the current submatrix.
The algorithm stops, if there is only one row left or the left sides of the remaining rows are all 0.
\end{enumerate}}
\lang{de}{
Die erweiterte Koeffizientenmatrix liegt nun in Stufenform vor.
Um eine reduzierte Stufenform zu erhalten, verfährt man nach dieser Umformung weiter:
\begin{enumerate}
\item[5.] Bringe jedes Stufenelement auf den Wert 1:\\
Teile dazu jede Zeile, bei der die linke Seite nicht komplett $0$ ist, durch ihren Stufeneintrag:\\
Für alle entsprechenden $l$ mit $l\geq 1$ forme die Zeile $(L)$ zu $\frac{1}{a_{lj}}(L)$ um.
\item[6.] Bringe alle Koeffizienten über einem Stufenelement auf den Wert 0.\\
Addiere dazu geeignete Vielfache der in 5. genannten Zeilen $(L)$ zu den darüber liegenden Zeilen $(K)$.\\
Für alle $k$ mit $1\leq k < l$ forme die Zeile $(K)$ zu $(K)-a_{kj}(L)$ um.
\end{enumerate}
\floatright{\href{https://api.stream24.net/vod/getVideo.php?id=10962-2-10841
&mode=iframe}{\image[75]{00_video_button_schwarz-blau}}}\\
}
\lang{en}{
We now have the augmented matrix in row echelon form.
To receive a reduced row echelon form, we must proceed with the following transformations:
\begin{enumerate}
\item[5.] Each leading element needs to have the value $1$:\\
Divide each row with a non-zero left side, by its leading element:\\
For all $l$ with $l\geq 1$ transform the row $(L)$ to $\frac{1}{a_{lj}}(L)$.
\item[6.] All coefficients above a leading element need to have value $0$:
Add suitable multiples of the row $(L)$, mentioned in 5., to the rows $(K)$ above.\\
For all $k$ with $1\leq k < l$ transform the row $(K)$ to $(K)-a_{kj}(L)$.
\end{enumerate}}
\end{rule}
\lang{de}{
\begin{remark}
Beim handschriftlichen Lösen eines LGS wird der Algorithmus
oft nicht streng umgesetzt.
Um Brüche zu vermeiden, werden im ersten Schritt die Zeilen
zum Beispiel so getauscht, dass der
%Koeffizient $a_{ik}=1$
Stufeneintrag gleich 1
ist.
Außerdem kann man in Schritt 3 beispielsweise anstelle
der Umformung $(L)-\frac{a_{lj}}{a_{kj}}(K)$
auch $-a_{kj}(L) + a_{lj}(K)$ verwenden.
Sowohl die Lösungsmenge als auch die reduzierte Stufenform
bleiben hierbei unverändert.
\end{remark}}
\lang{en}{
\begin{remark}
When solving a linear system by hand we slightly change the algorithm for convenience.
In the first step, the rows are swapped so, that the leading element is $1$ to avoid fractions.
In step 3, it is possible to use the transformation $-a_{kj}(L) + a_{lj}(K)$
instead of $(L)-\frac{a_{lj}}{a_{kj}}(K)$.
Both the solution set and the reduced row echelon form stay unmodified.
\end{remark}}
\begin{example}
\begin{tabs*}
\tab{\lang{de}{1. Beispiel} \lang{en}{2. Example}}
\lang{de}{
Für das LGS
\[ \begin{mtable}[\cellaligns{crcrcrcrcrl}]
(I)&\qquad x_1 &+& 2x_2 &+ &\phantom{3}x_3 &- &x_4 & = & 7 & \phantom{\qquad|\,\, -2\cdot \text{(II)}}\\
(II)& x_1 &+ &3x_2 & & & - & x_4 & = & 8& \\
(III)& -x_1 & & & - &3x_3 &+ &5x_4 & = & -9&
\end{mtable} \]
über $\mathbb{R}$ erhalten wir die folgende erweiterte Koeffizientenmatrix:
\[
\begin{pmatrix}
1 & 2 & 1 & -1 & | & 7\\
\textcolor{#CC6600}{1} & 3 & 0 & -1 &| & 8\\
\textcolor{#CC6600}{-1} & 0 & -3 & 5 &| & -9
% \rowops \add[-1]01 \add[+1]02
\end{pmatrix}
~
\begin{matrix}
\phantom{}\\
|-(I) + (II)\\
|(I) + (III)
\end{matrix}\]
Die erste Spalte enthält Koeffizienten ungleich $0$, sogar in der ersten Zeile, weshalb wir keine Zeilen tauschen müssen.
Subtrahieren der ersten Zeile von der zweiten und Addieren der ersten Zeile auf die dritte liefert
\[ \rightsquigarrow~~
\begin{pmatrix}
1 & 2 & 1 & -1 &| & 7\\
0 & 1 & -1& 0 &| & 1\\
0 & 2 & -2 & 4 & | & -2
% \rowops \add[-2]12
\end{pmatrix}.\]
Damit ist der erste Durchlauf fertig und man fährt genauso mit der Matrix aus der zweiten und dritten Zeile fort, schreibt aber
weiterhin die erste Zeile mit:
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{gray}{1} & \textcolor{gray}{2} & \textcolor{gray}{1} & \textcolor{gray}{-1} &\textcolor{gray}{|} & \textcolor{gray}{7}\\
0 & 1 & -1& 0 &| & 1\\
0 & \textcolor{#CC6600}{2} & -2 & 4 & | & -2
% \rowops \add[-2]12
\end{pmatrix}
~
\begin{matrix}
\phantom{}\\
\phantom{}\\
|(-2)(II) + (III)
\end{matrix}\]
Betrachtet man also nur die kleinere Matrix, enthält die erste Spalte nur $0$, aber die zweite nicht. Auch hier sind keine
Zeilen zu tauschen.
Dann wird das Doppelte der zweiten Zeile von der dritten subtrahiert
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{gray}{1} & \textcolor{gray}{2} & \textcolor{gray}{1} & \textcolor{gray}{-1} &\textcolor{gray}{|} & \textcolor{gray}{7}\\
0 & 1 & -1 & 0&| & 1\\
0 & 0 & 0 &4 &| & -4
% \rowops \mult[\frac{1}{4}]2
\end{pmatrix}, \]
wonach auch der zweite Durchlauf fertig ist und man die Stufenform erreicht hat.
Die Stufeneinträge sind im Folgenden blau markiert:
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{#0066CC}{1} & {2} & {1} &{-1} &{|} & {7}\\
0 & \textcolor{#0066CC}{1} & -1 & 0&| & 1\\
0 & 0 & 0 &\textcolor{#0066CC}{4} &| & -4
% \rowops \mult[\frac{1}{4}]2
\end{pmatrix}
~
\begin{matrix}
\phantom{}\\
\phantom{}\\
|\cdot \frac{1}{4} (III)
\end{matrix}\]
Für die reduzierte Stufenform teilen wir also die dritte Zeile durch $4$
\[
\rightsquigarrow~~\begin{pmatrix}
\textcolor{#0066CC}{1} & 2 & 1 & \textcolor{red}{-1} &| & 7\\
0 & \textcolor{#0066CC}{1} & -1 & 0&| & 1\\
0 & 0 & 0 &\textcolor{#0066CC}{1} &| & -1
\end{pmatrix}
~
\begin{matrix}
|(III)+(I)\\
\phantom{}\\
\phantom{}
\end{matrix}\]
und addieren die dritte Zeile auf die erste Zeile, um die rote $1$ über dem
letzten Stufeneintrag zu eliminieren,
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{#0066CC}{1} & \textcolor{#CC6600}{2} & 1 & 0 &| & 6\\
0 & \textcolor{#0066CC}{1} & -1 & 0&| & 1\\
0 & 0 & 0 &\textcolor{#0066CC}{1} &| & -1
% \rowops \add[-2]10
\end{pmatrix}
~
\begin{matrix}
|(-2)(II)+(I)\\
\phantom{}\\
\phantom{}
\end{matrix}\]
und subtrahieren schließlich das Doppelte der zweiten Zeile von der ersten,
um auch die rote $2$ zu eliminieren:
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{#0066CC}{1} & 0 & 3 & 0 &| & 4\\
0 & \textcolor{#0066CC}{1} & -1 & 0&| & 1\\
0 & 0 & 0 &\textcolor{#0066CC}{1} &| & -1
\end{pmatrix}
\]
Als Gleichungssystem ist dies dann
\[ \begin{mtable}[\cellaligns{crcrcrcrcrl}]
(I)&\qquad \phantom{+}x_1 &\phantom{+}& \phantom{2x_2} &+ &3x_3 &\phantom{-} & & = & 4 & \\
(II)& & &x_2 & - & x_3 & & & = & 1 & \\
(III)& & & & & & &\phantom{4}x_4 & = & -1&
\end{mtable} \]
und daraus lässt sich die Lösungsmenge direkt ablesen, indem man $x_3=t$ mit $t \in \R$ setzt:
\[ \mathbb{L}
= \left\{ \begin{pmatrix} 4-3t \\ 1+t \\t \\ -1\end{pmatrix} \, \big| \, t\in \R \right\}
= \left\{ \begin{pmatrix} 4 \\ 1 \\ 0 \\ -1\end{pmatrix}+ t\cdot \begin{pmatrix} -3\\ 1\\ 1\\ 0 \end{pmatrix} \, \big| \, t\in \R \right\} \]
.}
\lang{en}{
For the linear system
\[ \begin{mtable}[\cellaligns{crcrcrcrcrl}]
(I)&\qquad x_1 &+& 2x_2 &+ &\phantom{3}x_3 &- &x_4 & = & 7 & \phantom{\qquad|\,\, -2\cdot \text{(II)}}\\
(II)& x_1 &+ &3x_2 & & & - & x_4 & = & 8& \\
(III)& -x_1 & & & - &3x_3 &+ &5x_4 & = & -9&
\end{mtable} \]
over $\mathbb{R}$ we have the following augmented matrix:
\[
\begin{pmatrix}
1 & 2 & 1 & -1 & | & 7\\
\textcolor{#CC6600}{1} & 3 & 0 & -1 &| & 8\\
\textcolor{#CC6600}{-1} & 0 & -3 & 5 &| & -9
% \rowops \add[-1]01 \add[+1]02
\end{pmatrix}
~
\begin{matrix}
\phantom{}\\
|-(I) + (II)\\
|(I) + (III)
\end{matrix}\]
The first column contains non-zero coefficients in every row, even in the first one, which is why we do not need to swap rows.
Subtracting the first row from the second and adding the first row to the thirds yields
\[ \rightsquigarrow~~
\begin{pmatrix}
1 & 2 & 1 & -1 &| & 7\\
0 & 1 & -1& 0 &| & 1\\
0 & 2 & -2 & 4 & | & -2
% \rowops \add[-2]12
\end{pmatrix}.\]
The first cycle is done and we go on the same way with the resulting submatrix, but
continue to note the first row:
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{gray}{1} & \textcolor{gray}{2} & \textcolor{gray}{1} & \textcolor{gray}{-1} &\textcolor{gray}{|} & \textcolor{gray}{7}\\
0 & 1 & -1& 0 &| & 1\\
0 & \textcolor{#CC6600}{2} & -2 & 4 & | & -2
% \rowops \add[-2]12
\end{pmatrix}
~
\begin{matrix}
\phantom{}\\
\phantom{}\\
|(-2)(II) + (III)
\end{matrix}\]
Condering only the small matrix, the first column is a zero-column, but the second is not, so they do not need to be swapped.
The double of the second row is subtracted from the third
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{gray}{1} & \textcolor{gray}{2} & \textcolor{gray}{1} & \textcolor{gray}{-1} &\textcolor{gray}{|} & \textcolor{gray}{7}\\
0 & 1 & -1 & 0&| & 1\\
0 & 0 & 0 &4 &| & -4
% \rowops \mult[\frac{1}{4}]2
\end{pmatrix}.\]
The second cycle is done and the matrix is in row echelon form.
The leading elements are colored blue:
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{#0066CC}{1} & {2} & {1} &{-1} &{|} & {7}\\
0 & \textcolor{#0066CC}{1} & -1 & 0&| & 1\\
0 & 0 & 0 &\textcolor{#0066CC}{4} &| & -4
% \rowops \mult[\frac{1}{4}]2
\end{pmatrix}
~
\begin{matrix}
\phantom{}\\
\phantom{}\\
|\cdot \frac{1}{4} (III)
\end{matrix}\]
To receive the reduced row echelon form, we divide the third row by $4$
\[
\rightsquigarrow~~\begin{pmatrix}
\textcolor{#0066CC}{1} & 2 & 1 & \textcolor{red}{-1} &| & 7\\
0 & \textcolor{#0066CC}{1} & -1 & 0&| & 1\\
0 & 0 & 0 &\textcolor{#0066CC}{1} &| & -1
\end{pmatrix}
~
\begin{matrix}
|(III)+(I)\\
\phantom{}\\
\phantom{}
\end{matrix}\]
and add the result to the first row. So the red $1$ above the last leading element is eliminated
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{#0066CC}{1} & \textcolor{#CC6600}{2} & 1 & 0 &| & 6\\
0 & \textcolor{#0066CC}{1} & -1 & 0&| & 1\\
0 & 0 & 0 &\textcolor{#0066CC}{1} &| & -1
% \rowops \add[-2]10
\end{pmatrix}
~
\begin{matrix}
|(-2)(II)+(I)\\
\phantom{}\\
\phantom{}
\end{matrix}.\]
In the last step we substract the double of the first row from the first to eliminate the red $2$:
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{#0066CC}{1} & 0 & 3 & 0 &| & 4\\
0 & \textcolor{#0066CC}{1} & -1 & 0&| & 1\\
0 & 0 & 0 &\textcolor{#0066CC}{1} &| & -1
\end{pmatrix}
\]
This yields the system of linear equations as follows
\[ \begin{mtable}[\cellaligns{crcrcrcrcrl}]
(I)&\qquad \phantom{+}x_1 &\phantom{+}& \phantom{2x_2} &+ &3x_3 &\phantom{-} & & = & 4 & \\
(II)& & &x_2 & - & x_3 & & & = & 1 & \\
(III)& & & & & & &\phantom{4}x_4 & = & -1&
\end{mtable}.\]
Now the solution set can be read right away by subsituting $x_3=t$ with $t \in \R$:
\[ \mathbb{L}
= \left\{ \begin{pmatrix} 4-3t \\ 1+t \\t \\ -1\end{pmatrix} \, \big| \, t\in \R \right\}
= \left\{ \begin{pmatrix} 4 \\ 1 \\ 0 \\ -1\end{pmatrix}+ t\cdot \begin{pmatrix} -3\\ 1\\ 1\\ 0 \end{pmatrix} \, \big| \, t\in \R \right\} \]
.}
\tab{\lang{de}{2. Beispiel} \lang{en}{3. Example}}
\lang{de}{
Für das LGS über den komplexen Zahlen
\[ \begin{mtable}[\cellaligns{crcrcrcrl}]
(I)&\qquad ix_1 &+& (2+i)x_2 &+ &5x_3& = & 0 & \phantom{\qquad|\,\, -2\cdot \text{(II)}}\\
(II)& -x_1 &+ &(-1+2i)x_2 & + & 4ix_3 & = & 2i& \\
(III)& -3ix_1 & - & 6-3ix_2 & - &12x_3 &= & -6&
\end{mtable} \]
erhalten wir die folgende erweiterte Koeffizientenmatrix:
\[ \begin{pmatrix}
i & 2+i & 5 & | & 0\\
-1 & 2i-1 & 4i &| & 2i\\
-3i & -6-3i & -12 &| & -6
\end{pmatrix}
~
\begin{matrix}
\phantom{}\\
|(-i)(I)+(II)\\
|3(I)+(III)
\end{matrix}\]
Die erste Spalte enthält Koeffizienten ungleich $0$, sogar in der ersten Zeile, weshalb wir keine Zeilen tauschen müssen.
Die erste Zeile wird mit $-i$ multipliziert und anschließend zu der zweiten Zeile addiert.
Ebenso wird das Dreifache der ersten zu der dritten Zeile addiert.
\[
\rightsquigarrow~~\begin{pmatrix}
i & 2+i & 5 &| & 0\\
0 & 0 & -i &| & 2i\\
0 & 0 & 3 &| & -6
\end{pmatrix}\]
Damit ist der erste Durchlauf fertig und man fährt genauso mit der Matrix aus der zweiten und dritten Zeile fort, schreibt aber
weiterhin die erste Zeile mit:
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{gray}{i} & \textcolor{gray}{2+i} & \textcolor{gray}{5} & {|} & \textcolor{gray}{0}\\
0 & 0 & -i &| & 2i\\
0 & 0 & 3 &| & -6
\end{pmatrix}
~
\begin{matrix}
\phantom{}\\
\phantom{}\\
|(-3i)(II)+(III)
\end{matrix}\]
Betrachtet man also nur die kleinere Matrix, enthält die erste und die zweite Spalte nur Nullen.
In der dritten Spalte sind alle Koeffizienten nicht Null und müssen somit nicht getauscht werden.
Die zweite Zeile wird mit $-3i$ multipliziert und anschließend zur dritten Zeile addiert
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{gray}{i} & \textcolor{gray}{2+i} & \textcolor{gray}{5} & {|} & \textcolor{gray}{0}\\
0 & 0 & -i &| & 2i\\
0 & 0 & 0 &| & 0
\end{pmatrix}, \]
wonach auch der zweite Durchlauf fertig ist und man die Stufenform erreicht hat.
Die Stufeneinträge sind im Folgenden blau markiert:
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{#0066CC}{i} & {2+i} & {5} &{|} & {0}\\
0 & 0 & \textcolor{#0066CC}{-i}&| & 2i\\
0 & 0 & 0 &| & 0
\end{pmatrix}
~
\begin{matrix}
|(-i)(I)\\
|i(II)\\
\phantom{}
\end{matrix}\]
Um die Stufenelemente auf $1$ zu bringen, multiplizieren wir die erste Zeile mit $-i$ und die zweite Zeile mit $i$:
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{#0066CC}{1} & 1-2i &\textcolor{#CC6600}{-5i} &| & 0\\
0 & 0&\textcolor{#0066CC}{1} &| & -2\\
0 & 0 & 0 &| &0
\end{pmatrix}
~
\begin{matrix}
|5i(II)+(I)\\
\phantom{}\\
\phantom{}
\end{matrix}\]
Anschließend addieren wir das $5i$-fache der zweiten Zeile zu der ersten Zeile:
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{#0066CC}{1} & 1-2i&0 &| & -10i\\
0 & 0&\textcolor{#0066CC}{1} &| & -2\\
0 & 0 & 0 &| & 0
\end{pmatrix} \]
Damit ist die reduzierte Stufenform erreicht.%\\
Als Gleichungssystem ist dies
\[
\begin{mtable}[\cellaligns{crcrcrl}]
(I)&\qquad x_1 &+&(1-2i)x_2 &\phantom{-} & & = & -10i & \\
(II)& & & & & x_3 & = & -2 & \\
\end{mtable} \]
und man erhält die Lösungsmenge
\[ \mathbb{L}
= \left\{ \begin{pmatrix} -10i-(1-2i)t \\ t \\ -2 \end{pmatrix} \, \big| \, t\in \C \right\}
= \left\{ \begin{pmatrix} -10i \\ 0 \\ -2 \end{pmatrix}+ t\cdot \begin{pmatrix} -1+2i\\ 1\\ 0 \end{pmatrix} \, \big| \, t\in \C \right\}. \]}
\lang{en}{
For the complex-valued linear system
\[ \begin{mtable}[\cellaligns{crcrcrcrl}]
(I)&\qquad ix_1 &+& (2+i)x_2 &+ &5x_3& = & 0 & \phantom{\qquad|\,\, -2\cdot \text{(II)}}\\
(II)& -x_1 &+ &(-1+2i)x_2 & + & 4ix_3 & = & 2i& \\
(III)& -3ix_1 & - & 6-3ix_2 & - &12x_3 &= & -6&
\end{mtable} \]
the augmented matrix is given by:
\[ \begin{pmatrix}
i & 2+i & 5 & | & 0\\
-1 & 2i-1 & 4i &| & 2i\\
-3i & -6-3i & -12 &| & -6
\end{pmatrix}
~
\begin{matrix}
\phantom{}\\
|(-i)(I)+(II)\\
|3(I)+(III)
\end{matrix}\]
The first column contains non-zero coefficients, even in the first row, which is why no rows need to be exchanged.
The first row ist multiplied with $-i$ and then added to the second row.
Likewise, the triple of the first row is added to the third.
\[
\rightsquigarrow~~\begin{pmatrix}
i & 2+i & 5 &| & 0\\
0 & 0 & -i &| & 2i\\
0 & 0 & 3 &| & -6
\end{pmatrix}\]
The first cycle is done and we continue with the submatrix consisting of the second and the third row, but keep noting down the first row:
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{gray}{i} & \textcolor{gray}{2+i} & \textcolor{gray}{5} & {|} & \textcolor{gray}{0}\\
0 & 0 & -i &| & 2i\\
0 & 0 & 3 &| & -6
\end{pmatrix}
~
\begin{matrix}
\phantom{}\\
\phantom{}\\
|(-3i)(II)+(III)
\end{matrix}\]
Considering only the submatrix, the first and the second column contain only zeros, but there are non-zero entries in the third column.
Therefore, nothing needs to be exchanged.
The second row is multiplied with $-3i$ and is then added to the third row
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{gray}{i} & \textcolor{gray}{2+i} & \textcolor{gray}{5} & {|} & \textcolor{gray}{0}\\
0 & 0 & -i &| & 2i\\
0 & 0 & 0 &| & 0
\end{pmatrix}, \]
which is the row echelon form.
The leading elements are colored blue in the following:
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{#0066CC}{i} & {2+i} & {5} &{|} & {0}\\
0 & 0 & \textcolor{#0066CC}{-i}&| & 2i\\
0 & 0 & 0 &| & 0
\end{pmatrix}
~
\begin{matrix}
|(-i)(I)\\
|i(II)\\
\phantom{}
\end{matrix}\]
To get only ones as leading elements, the first row is multiplied with $-i$ and the second row with $i$:
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{#0066CC}{1} & 1-2i &\textcolor{#CC6600}{-5i} &| & 0\\
0 & 0&\textcolor{#0066CC}{1} &| & -2\\
0 & 0 & 0 &| &0
\end{pmatrix}
~
\begin{matrix}
|5i(II)+(I)\\
\phantom{}\\
\phantom{}
\end{matrix}\]
Afterwards we add $5i$-times the second row to the first:
\[ \rightsquigarrow~~
\begin{pmatrix}
\textcolor{#0066CC}{1} & 1-2i&0 &| & -10i\\
0 & 0&\textcolor{#0066CC}{1} &| & -2\\
0 & 0 & 0 &| & 0
\end{pmatrix} \]
Now the linear system is in reduced row echelon form.%\\
Written as a system of linear equations we have
\[
\begin{mtable}[\cellaligns{crcrcrl}]
(I)&\qquad x_1 &+&(1-2i)x_2 &\phantom{-} & & = & -10i & \\
(II)& & & & & x_3 & = & -2 & \\
\end{mtable} \]
and the solution set is given by
\[ \mathbb{L}
= \left\{ \begin{pmatrix} -10i-(1-2i)t \\ t \\ -2 \end{pmatrix} \, \big| \, t\in \C \right\}
= \left\{ \begin{pmatrix} -10i \\ 0 \\ -2 \end{pmatrix}+ t\cdot \begin{pmatrix} -1+2i\\ 1\\ 0 \end{pmatrix} \, \big| \, t\in \C \right\}. \]}
\end{tabs*}
\end{example}
\begin{remark}
\lang{de}{
Ist allgemein eine Matrix $A$ gegeben (die nicht von einem LGS induziert sein muss),
reden wir dennoch von Zeilenumformungen und reduzierter Stufenform der Matrix $A$.
Diese werden entsprechend dem obigen Gauß-Verfahren gebildet, wobei keine rechte Seite vorhanden ist.}
\lang{en}{
The terms "row operations" and "reduced row echelon form" may also be used for a general matrix $A$, that does not necesseraly
need to be given by a system of linear equations.
For that, the above Gaussian elimination can be applied, even if no right side exists. }
\end{remark}
\lang{de}{
Eine Matrix $A$ (bzw. ein LGS) kann durch unterschiedliche Umformungen eine andere Stufenform annehmen.
Im Gegensatz dazu existiert genau eine dazugehörige reduzierte Stufenform.}
\lang{en}{
A matrix $A$ (or a linear system) may have different row echelon forms depending on the transformations applied.
In contrast to that, there exists exactly on corresponding reduced row echelon form.}
\label{rule:red-stufenform-eind}
\begin{theorem}
\begin{enumerate}
\item \lang{de}{Die reduzierte Stufenform einer Matrix $A$ hängt nicht von den getätigten
Zwischenschritten ab. Das heißt, wenn man im Gauß-Verfahren andere Schritte
durchführt - zum Beispiel am Anfang noch Zeilen vertauscht, um einen anderen von Null
verschiedenen Eintrag an erster Position zu erhalten -, ist die reduzierte Stufenform mit Einsen als Stufenelementen
am Ende wieder dieselbe.}
\lang{en}{The reduced row echelon form of a matrix $A$ does not depend on the intermediate steps taken.
This means, that if we perform different steps in the Gaussian elimination - e.g. exchanging rows to start with a different non-zero entry -,
the reduced row echelon form with only ones as leading elements is the same in the end.}
\item \lang{de}{Sind $A$ und $B$ zwei Matrizen, die durch Zeilenumformungen auseinander
hervorgegangen sind, so sind ihre reduzierten Stufenformen dieselben.}
\lang{en}{If $A$ and $B$ are two matrices that have been created from each other by row transformations,
then their reduced row echelon forms are the same.}
\end{enumerate}
\end{theorem}
\begin{block}[explanation]
\begin{showhide}
\begin{enumerate}
\item \lang{de}{Durch die Zeilenumformungen ändert sich die Lösungsmenge des entsprechenden
homogenen linearen Gleichungssystems $Ax=0$ nicht.\\
Aus der reduzierten Stufenform lässt sich die Lösungsmenge in Parameterform direkt ablesen (s. \lref{rule:loesung-parametrisiert}{unten}).
Diese Darstellung hängt von den
als Parametern gewählten Variablen ab (siehe \ref{rule:loesung-parametrisiert}), welche aber bei dem angewendeten Verfahren
stets die möglichst letzten sind.\\
Die reduzierte Stufenform ist also immer dieselbe, egal welche elementaren Umformungen dafür gemacht wurden.}
\lang{en}{
The row operations do not change the solution set of the corresponding homogeneous linear system $Ax=0$.\\
From the reduced row echelon form, the solution set can be read directly in parameter form (see \lref{rule:loesung-parametrisiert}{below}).
The representation depends on the chosen parameters for the variables (see \ref{rule:loesung-parametrisiert}), which, however,
are always the last possible in the procedure used.\\
So, the reduced row echelon form is always the same, no matter which elementary operations were used.}
\item \lang{de}{Eine Matrix $A$ lässt sich immer in reduzierter Stufenform angeben und somit lässt sich auch jede Matrix $B$, die durch elementare Umformungen von $A$ erzeugt wurde, in dieser darstellen.
Da die reduzierte Stufenform von $A$ eindeutig ist, entspricht sie auch der von $B$.}
\lang{en}{
A matrix $A$ can always be presented in reduced row echelon form. Therefore, every matrix $B$, created from $A$ by using elementary operations,
can be displayed in reduced row echelon form too. Because the reduced row echelon form of $A$ is unique, it also corresponds to that of $B$.}\\
\end{enumerate}
\end{showhide}
\end{block}
\section{\lang{de}{Lineare Gleichungssysteme mit mehreren rechten Seiten} \lang{en}{Linear systems with several right sides}}\label{sec:mehrere-rechte-seiten}
\lang{de}{In der Praxis möchte man oft mehrere lineare Gleichungssysteme lösen, wobei die
linke Seite ($Ax$) durch das konkrete Problem stets dieselbe ist und sich lediglich die
rechte Seite ($b$) ändert.
Mit dem Gauß-Verfahren kann man diese LGS in einer Rechnung
lösen. Man muss in der erweiterten Koeffizientenmatrix lediglich alle rechten Seiten nebeneinander aufführen.}
\lang{en}{In practise we often want to solve several linear system, in which the left side ($Ax$) is always the same because of
the given problem and only the righ side ($b$) changes.
With the Gaussian elimination these linear systems can be solved with only one calculation. For this, all the right sides need to be listed
in the augmented matrix.}
\begin{example}
\begin{tabs*}
\tab{\lang{de}{1. Beispiel} \lang{en}{2. Example}}\ref{ex:gauss}
\lang{de}{
Zu lösen sind die linearen Gleichungssysteme}
\begin{displaymath}
\begin{mtable}[\cellaligns{ccrcrcrcr}]
(I)&\quad-&x&+&2y&+&3z&=&5\\
(II)&\quad&x&-&y&+&z&=&6\\
(III)&\quad&2x&-&3y&-&4z&=&-5
\end{mtable}\qquad \text{und} \qquad
\begin{mtable}[\cellaligns{ccrcrcrcr}]
(I)&\quad-&x&+&2y&+&3z&=&2\\
(II)&\quad&x&-&y&+&z&=&-1\\
(III)&\quad&2x&-&3y&-&4z&=&3
\end{mtable}
\end{displaymath}
und bei beiden ist die Koeffizientenmatrix
\[ A= \begin{pmatrix}
-1 & 2 & 3 \\ 1 & -1 & 1 \\ 2 & -3 & -4 \end{pmatrix}. \]
Die Spaltenvektoren zur rechten Seite sind
\[ b=\begin{pmatrix} 5 \\ 6 \\ -5\end{pmatrix} \quad \text{bzw.} \quad
c= \begin{pmatrix} 2 \\ -1 \\ 3\end{pmatrix}. \]
Um beide LGS gleichzeitig zu lösen (und damit Rechenaufwand zu sparen),
schreibt man eine erweiterte Koeffizientenmatrix, bei der beide Spaltenvektoren auf der rechten Seite stehen:
\[ (A \ \mid \ b\ c)= \begin{pmatrix}
-1 & 2 & 3 & | & 5 & 2 \\ 1 & -1 & 1& | & 6 & -1 \\ 2 & -3 & -4& | & -5 & 3 \end{pmatrix}. \]
Anschließend wendet man auf diese Matrix das oben beschriebene Gauß-Verfahren an
und kann danach beide LGS in reduzierter Stufenform ablesen:
\begin{eqnarray*}
&& \begin{pmatrix} -1 & 2 & 3 & | & 5 & 2 \\ 1 & -1 & 1& | & 6 & -1 \\ 2 & -3 & -4& | & -5 & 3 \end{pmatrix}
\begin{matrix} \text{|} \cdot (-1) \\ \phantom{1}\\ \phantom{1} \end{matrix} \rightsquigarrow
\begin{pmatrix} 1 & -2 & -3 & | & -5 & -2 \\ 1 & -1 & 1& | & 6 & -1 \\ 2 & -3 & -4& | & -5 & 3 \end{pmatrix}
\begin{matrix} \phantom{1} \\ \text{|} - 1\cdot (I)\\ \text{|} -2\cdot (I) \end{matrix} \\ &&\\
& \rightsquigarrow & \begin{pmatrix} 1 & -2 & -3 & | & -5 & -2 \\ 0 & 1 & 4& | & 11 & 1 \\ 0 & 1 & 2& | & 5 & 7 \end{pmatrix}
\begin{matrix} \phantom{1} \\ \phantom{1}\\ \text{|} -1\cdot (II) \end{matrix} \rightsquigarrow
\begin{pmatrix} 1 & -2 & -3 & | & -5 & -2 \\ 0 & 1 & 4& | & 11 & 1 \\ 0 & 0 & -2& | & -6 & 6 \end{pmatrix}
\begin{matrix} \phantom{1} \\ \phantom{1}\\ \text{|} \cdot (-1/2) \end{matrix} \\ &&\\
& \rightsquigarrow & \begin{pmatrix} 1 & -2 & -3 & | & -5 & -2 \\ 0 & 1 & 4& | & 11 & 1 \\ 0 & 0 & 1& | & 3 & -3 \end{pmatrix}
\begin{matrix}\text{|} +3\cdot (III) \\ \text{|} -4\cdot (III) \\\phantom{1} \end{matrix} \rightsquigarrow
\begin{pmatrix} 1 & -2 & 0 & | & 4 & -11 \\ 0 & 1 & 0& | & -1 & 13 \\ 0 & 0 & 1& | & 3 & -3 \end{pmatrix}
\begin{matrix}\text{|} +2\cdot (II) \\ \phantom{1} \\ \phantom{1} \end{matrix} \\ &&\\
& \rightsquigarrow & \begin{pmatrix} 1 & 0 & 0 & | & 2 & 15 \\ 0 & 1 & 0& | & -1 & 13 \\ 0 & 0 & 1& | & 3 & -3 \end{pmatrix}
\end{eqnarray*}
Die Lösungsmenge für das erste LGS lautet damit
\[ \mathbb{L}=\{ \left(\begin{smallmatrix}
2 \\ -1\\ 3 \end{smallmatrix}\right) \},\]
und die Lösungsmenge für das zweite LGS ist
\[ \mathbb{L}=\{ \left(\begin{smallmatrix}
15 \\ 13\\ -3 \end{smallmatrix}\right) \}.\]
%}
\lang{en}{
The following linear systems need to be solved
\begin{displaymath}
\begin{mtable}[\cellaligns{ccrcrcrcr}]
(I)&\quad-&x&+&2y&+&3z&=&5\\
(II)&\quad&x&-&y&+&z&=&6\\
(III)&\quad&2x&-&3y&-&4z&=&-5
\end{mtable}\qquad \text{und} \qquad
\begin{mtable}[\cellaligns{ccrcrcrcr}]
(I)&\quad-&x&+&2y&+&3z&=&2\\
(II)&\quad&x&-&y&+&z&=&-1\\
(III)&\quad&2x&-&3y&-&4z&=&3
\end{mtable}.
\end{displaymath}
Both have the coefficient matrix
\[ A= \begin{pmatrix}
-1 & 2 & 3 \\ 1 & -1 & 1 \\ 2 & -3 & -4 \end{pmatrix}. \]
The column vectors of the right side are
\[ b=\begin{pmatrix} 5 \\ 6 \\ -5\end{pmatrix} \quad \text{bzw.} \quad
c= \begin{pmatrix} 2 \\ -1 \\ 3\end{pmatrix}. \]
To solve both linear systems at a time (and save calculation effort),
we write a augmented matrix with both column vectors on the right side:
\[ (A \ \mid \ b\ c)= \begin{pmatrix}
-1 & 2 & 3 & | & 5 & 2 \\ 1 & -1 & 1& | & 6 & -1 \\ 2 & -3 & -4& | & -5 & 3 \end{pmatrix}. \]
Afterwards we apply the Gaussian elimination from above. In the end it is possible to read both linear systems in
reduced row echelon form:
\begin{eqnarray*}
&& \begin{pmatrix} -1 & 2 & 3 & | & 5 & 2 \\ 1 & -1 & 1& | & 6 & -1 \\ 2 & -3 & -4& | & -5 & 3 \end{pmatrix}
\begin{matrix} \text{|} \cdot (-1) \\ \phantom{1}\\ \phantom{1} \end{matrix} \rightsquigarrow
\begin{pmatrix} 1 & -2 & -3 & | & -5 & -2 \\ 1 & -1 & 1& | & 6 & -1 \\ 2 & -3 & -4& | & -5 & 3 \end{pmatrix}
\begin{matrix} \phantom{1} \\ \text{|} - 1\cdot (I)\\ \text{|} -2\cdot (I) \end{matrix} \\ &&\\
& \rightsquigarrow & \begin{pmatrix} 1 & -2 & -3 & | & -5 & -2 \\ 0 & 1 & 4& | & 11 & 1 \\ 0 & 1 & 2& | & 5 & 7 \end{pmatrix}
\begin{matrix} \phantom{1} \\ \phantom{1}\\ \text{|} -1\cdot (II) \end{matrix} \rightsquigarrow
\begin{pmatrix} 1 & -2 & -3 & | & -5 & -2 \\ 0 & 1 & 4& | & 11 & 1 \\ 0 & 0 & -2& | & -6 & 6 \end{pmatrix}
\begin{matrix} \phantom{1} \\ \phantom{1}\\ \text{|} \cdot (-1/2) \end{matrix} \\ &&\\
& \rightsquigarrow & \begin{pmatrix} 1 & -2 & -3 & | & -5 & -2 \\ 0 & 1 & 4& | & 11 & 1 \\ 0 & 0 & 1& | & 3 & -3 \end{pmatrix}
\begin{matrix}\text{|} +3\cdot (III) \\ \text{|} -4\cdot (III) \\\phantom{1} \end{matrix} \rightsquigarrow
\begin{pmatrix} 1 & -2 & 0 & | & 4 & -11 \\ 0 & 1 & 0& | & -1 & 13 \\ 0 & 0 & 1& | & 3 & -3 \end{pmatrix}
\begin{matrix}\text{|} +2\cdot (II) \\ \phantom{1} \\ \phantom{1} \end{matrix} \\ &&\\
& \rightsquigarrow & \begin{pmatrix} 1 & 0 & 0 & | & 2 & 15 \\ 0 & 1 & 0& | & -1 & 13 \\ 0 & 0 & 1& | & 3 & -3 \end{pmatrix}
\end{eqnarray*}
The solution set of the first linear system ist
\[ \mathbb{L}=\{ \left(\begin{smallmatrix}
2 \\ -1\\ 3 \end{smallmatrix}\right) \},\]
and the solution set of the second linear system is
\[ \mathbb{L}=\{ \left(\begin{smallmatrix}
15 \\ 13\\ -3 \end{smallmatrix}\right) \}.\]}
\tab{\lang{de}{2. Beispiel} \lang{en}{2. Example}}
\lang{de}{
Zu lösen sind die linearen Gleichungssysteme
\begin{displaymath}
\begin{mtable}[\cellaligns{ccrcrcrcr}]
(I)&\qquad ix_1 &+& (2+i)x_2 &+ &5x_3& = & 0 \\
(II)& -x_1 &+ &(-1+2i)x_2 & + & 4ix_3 & = & 2i \\
(III)& -3ix_1 & + & (-6-3i)x_2 & - &12x_3 &= & -6
\end{mtable}\qquad \text{und} \qquad
\begin{mtable}[\cellaligns{ccrcrcrcr}]
(I)&\qquad ix_1 &+& (2+i)x_2 &+ &5x_3& = & 1\\
(II)& -x_1 &+ &(-1+2i)x_2 & + & 4ix_3 & = & i \\
(III)& -3ix_1 & + & (-6-3i)x_2 & - &12x_3 &= & -3
\end{mtable}
\end{displaymath}
und bei beiden ist die Koeffizientenmatrix
\[ \begin{pmatrix}
i & 2+i & 5 \\
-1 & 2i-1 & 4i \\
-3i & -6-3i & -12
\end{pmatrix}. \]
Die Spaltenvektoren zur rechten Seite sind
\[ b=\begin{pmatrix} 0\\ 2i \\ -6\end{pmatrix} \quad \text{bzw.} \quad
c= \begin{pmatrix} 1 \\ i \\ -3\end{pmatrix}. \]
Um beide LGS gleichzeitig zu lösen (und damit Rechenaufwand zu sparen),
schreibt man eine erweiterte Koeffizientenmatrix, bei der beide Spaltenvektoren auf der rechten Seite stehen:
\[ (A \ \mid \ b\ c)=\begin{pmatrix}
i & 2+i & 5 & | & 0 &1\\
-1 & 2i-1 & 4i &| & 2i&i\\
-3i & -6-3i & -12 &| & -6&-3
\end{pmatrix}. \]
Anschließend wendet man auf diese Matrix das oben beschriebene Gauß-Verfahren an
und kann danach beide LGS in reduzierter Stufenform ablesen:
\begin{eqnarray*}
&& \begin{pmatrix}
i & 2+i & 5 & | & 0 &1\\
-1 & 2i-1 & 4i &| & 2i&i\\
-3i & -6-3i & -12 &| & -6&-3
\end{pmatrix}
\begin{matrix} \phantom{1} \\ \text{|} -i \cdot (I) \\ \text{|} +3 \cdot (I) \end{matrix} \rightsquigarrow
\begin{pmatrix}
i & 2+i & 5 &| & 0 & 1\\
0 & 0 & -i &| & 2i & 0\\
0 & 0 & 3 &| & -6 & 0
\end{pmatrix}
\begin{matrix} \phantom{1} \\\phantom{1} \\ \text{|} -3i \cdot (II) \end{matrix} \\ &&\\
& \rightsquigarrow &
\begin{pmatrix}
i & 2+i & 5 &| & 0 & 1\\
0 & 0 & -i &| & 2i & 0\\
0 & 0 & 0 &| & 0 & 0
\end{pmatrix}
\begin{matrix} \text{|} \cdot (-i) \\ \text{|} \cdot i\\ \phantom{1} \end{matrix} \rightsquigarrow
\begin{pmatrix}
1 & 1-2i &{-5i} &| & 0 & -i\\
0 & 0&{1} &| & -2 & 0\\
0 & 0 & 0 &| & 0 & 0
\end{pmatrix}
\begin{matrix} \text{|} +5i \cdot (II) \\ \phantom{1} \\ \phantom{1} \end{matrix} \\ &&\\& \rightsquigarrow &
\begin{pmatrix}
1 & 1-2i&0 &| & -10i& -i\\
0 & 0 &1 &| & -2 & 0\\
0 & 0 &0 &| & 0 & 0
\end{pmatrix}
\end{eqnarray*}
Die Lösungsmenge des ersten LGS lautet damit
\[ \mathbb{L}=\left\{ \begin{pmatrix} -10i-(1-2i)t \\ t \\ -2 \end{pmatrix} \, \big| \, t\in \C \right\}\]
und die Lösungsmenge des zweiten LGS ist
\[ \mathbb{L}=\left\{ \begin{pmatrix} -i-(1-2i)t \\ t \\ 0 \end{pmatrix} \, \big| \, t\in \C \right\}.\]}
\lang{en}{
The following linear systems need to be solved
\begin{displaymath}
\begin{mtable}[\cellaligns{ccrcrcrcr}]
(I)&\qquad ix_1 &+& (2+i)x_2 &+ &5x_3& = & 0 \\
(II)& -x_1 &+ &(-1+2i)x_2 & + & 4ix_3 & = & 2i \\
(III)& -3ix_1 & + & (-6-3i)x_2 & - &12x_3 &= & -6
\end{mtable}\qquad \text{und} \qquad
\begin{mtable}[\cellaligns{ccrcrcrcr}]
(I)&\qquad ix_1 &+& (2+i)x_2 &+ &5x_3& = & 1\\
(II)& -x_1 &+ &(-1+2i)x_2 & + & 4ix_3 & = & i \\
(III)& -3ix_1 & + & (-6-3i)x_2 & - &12x_3 &= & -3
\end{mtable}.
\end{displaymath}
For both the coefficient matrix is
\[ \begin{pmatrix}
i & 2+i & 5 \\
-1 & 2i-1 & 4i \\
-3i & -6-3i & -12
\end{pmatrix}. \]
The column vectors on the right side are
\[ b=\begin{pmatrix} 0\\ 2i \\ -6\end{pmatrix} \quad \text{bzw.} \quad
c= \begin{pmatrix} 1 \\ i \\ -3\end{pmatrix}. \]
To solve both linear systems at a time (and save calculation effort),
we write a augmented matrix with both column vectors on the right side:
\[ (A \ \mid \ b\ c)=\begin{pmatrix}
i & 2+i & 5 & | & 0 &1\\
-1 & 2i-1 & 4i &| & 2i&i\\
-3i & -6-3i & -12 &| & -6&-3
\end{pmatrix}. \]
Afterwards we apply the Gaussian elimination on the matrix. Then it is possible to
read both linear systems in reduced row echelon form:
\begin{eqnarray*}
&& \begin{pmatrix}
i & 2+i & 5 & | & 0 &1\\
-1 & 2i-1 & 4i &| & 2i&i\\
-3i & -6-3i & -12 &| & -6&-3
\end{pmatrix}
\begin{matrix} \phantom{1} \\ \text{|} -i \cdot (I) \\ \text{|} +3 \cdot (I) \end{matrix} \rightsquigarrow
\begin{pmatrix}
i & 2+i & 5 &| & 0 & 1\\
0 & 0 & -i &| & 2i & 0\\
0 & 0 & 3 &| & -6 & 0
\end{pmatrix}
\begin{matrix} \phantom{1} \\\phantom{1} \\ \text{|} -3i \cdot (II) \end{matrix} \\ &&\\
& \rightsquigarrow &
\begin{pmatrix}
i & 2+i & 5 &| & 0 & 1\\
0 & 0 & -i &| & 2i & 0\\
0 & 0 & 0 &| & 0 & 0
\end{pmatrix}
\begin{matrix} \text{|} \cdot (-i) \\ \text{|} \cdot i\\ \phantom{1} \end{matrix} \rightsquigarrow
\begin{pmatrix}
1 & 1-2i &{-5i} &| & 0 & -i\\
0 & 0&{1} &| & -2 & 0\\
0 & 0 & 0 &| & 0 & 0
\end{pmatrix}
\begin{matrix} \text{|} +5i \cdot (II) \\ \phantom{1} \\ \phantom{1} \end{matrix} \\ &&\\& \rightsquigarrow &
\begin{pmatrix}
1 & 1-2i&0 &| & -10i& -i\\
0 & 0 &1 &| & -2 & 0\\
0 & 0 &0 &| & 0 & 0
\end{pmatrix}
\end{eqnarray*}
The solution set of the first linear system is
\[ \mathbb{L}=\left\{ \begin{pmatrix} -10i-(1-2i)t \\ t \\ -2 \end{pmatrix} \, \big| \, t\in \C \right\}\]
The solution set of the second linear system is
\[ \mathbb{L}=\left\{ \begin{pmatrix} -i-(1-2i)t \\ t \\ 0 \end{pmatrix} \, \big| \, t\in \C \right\}.\]}
\end{tabs*}
\end{example}
\end{content}
|
// Define pins
// LCD module connections
sbit LCD_RS at RB4_bit;
sbit LCD_EN at RB5_bit;
sbit LCD_D7 at RB3_bit;
sbit LCD_D6 at RB2_bit;
sbit LCD_D5 at RB1_bit;
sbit LCD_D4 at RB0_bit;
// Pin direction
sbit LCD_RS_Direction at TRISB4_bit;
sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_D7_Direction at TRISB3_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D4_Direction at TRISB0_bit;
// Define constants
#define BAUD_RATE 9600 // UART baud rate for communication with ESP32
// Function prototypes
void initUART();
void initPWM();
void startWatering();
void stopWatering();
void printToLCD(char *message);
void StartSignal();
unsigned short CheckResponse();
unsigned short ReadByte();
void ReadDHT11();
// globals
bit wateringState; // Variable to track watering state
char command;
char message[] = "00.0";
unsigned short TOUT = 0, CheckSum, i;
unsigned int T_Byte1, T_Byte2, RH_Byte1, RH_Byte2;
int moist, light;
char buff[45];
sbit DHT at RB6_bit;
sbit DataDir at TRISB6_bit;
//STRING REQUIRED FOR UARTTTT "temp:40 moist:90 humid:80 light:889"
void main()
{
ADCON0 = 0x01; // Enable ADC
TRISC2_bit = 0; // Set RC2 as output (Water pump)
TRISB1_bit = 1; // Set RB1 as input (DHT11)
// Set up LCD
TRISB &= ~0xF0; // Set RB4-RB7 as outputs for LCD data lines
Lcd_Init();
Lcd_Cmd(_LCD_CLEAR);
Lcd_Cmd(_LCD_CURSOR_OFF);
initUART();
initPWM();
// InitADC();
ADC_Init();
wateringState = 0;
INTCON.GIE = 1; // Enable global interrupt
INTCON.PEIE = 1; // Enable peripheral interrupt
// Configure Timer2 module
PIE1.TMR2IE = 1; // Enable Timer2 interrupt
T2CON = 0; // Prescaler 1:1, and Timer2 is off initially
PIR1.TMR2IF = 0; // Clear TMR INT Flag bit
TMR2 = 0;
while (1)
{
// Check for incoming commands from ESP32
INTCON.GIE = 0;
ReadDHT11();
INTCON.GIE = 1;
printToLCD("Reading sensors...");
moist = ADC_Get_Sample(2);
// buff[16] = moist / 10 + 48;
// buff[17] = moist % 10 + 48;
light = ADC_Get_Sample(3);
// buff[36] = light / 10 + 48;
// buff[37] = light % 10 + 48;
//LDR to LUX
light = light * 0.48875855327;
for (i = 0; i < 5; i++)
{
message[i] = 0;
}
printToLCD("Moisture:");
IntToStr(moist, message);
Lcd_Out(1, 11, message);
Lcd_Out(1, 16, "%");
uart1_write_text(" ");
uart1_write_text("moist:");
delay_ms(20);
uart1_write_text(message);
delay_ms(20);
for (i = 0; i < 5; i++)
{
message[i] = 0;
}
// delay_ms(1000);
Lcd_Out(2, 1, "Light:");
IntToStr(light, message);
Lcd_Out(2, 11, message);
Lcd_Out(2, 16, "%");
uart1_write_text(" ");
uart1_write_text("light:");
delay_ms(20);
uart1_write_text(message);
delay_ms(20);
UART1_Write_Text("\r\n");
delay_ms(200);
//Clear "message"
for (i = 0; i < 5; i++)
{
message[i] = 0;
}
if (UART1_Data_Ready())
{
command = UART1_Read(); // Read a single character and wait for carriage return
if (command == '1')
{
startWatering();
wateringState = 1;
printToLCD("Watering...");
}
else if (command == '2')
{
stopWatering();
wateringState = 0;
printToLCD("Watering stopped");
}
}
// printToLCD("Uart msg");
// //printToLCD(buff);
// // sprinti(buff, "temp:%s moist:%d humid:%s light:%d ", tempstr , moist, humidstr, light);
// printToLCD("sprintf done");
// delay_ms(200);
// uart1_write_text(buff);
// printToLCD("Uart msg sent");
// delay_ms(200);
// UART1_Write_Text("\r\n");
// printToLCD("rn msg sent");
// delay_ms(200);
delay_ms(200);
}
}
void initUART()
{
// Configure UART settings
UART1_Init(BAUD_RATE);
}
void initPWM()
{
// Configure PWM module
PWM1_Init(5000); // Set PWM frequency to 5 kHz
PWM1_Start();
PWM1_Set_Duty(0); // Set initial duty cycle to 0%
}
void startWatering()
{
// Start watering by setting PWM duty cycle
PWM1_Set_Duty(192); // Set duty cycle to 75%
}
void stopWatering()
{
// Stop watering by setting PWM duty cycle to 0%
PWM1_Set_Duty(0);
}
void printToLCD(char *message)
{
// Print message to LCD
Lcd_Cmd(_LCD_CLEAR);
Lcd_Out(1, 1, message);
}
void StartSignal()
{
DataDir = 0; // Data port is output
DHT = 0;
Delay_ms(25);
DHT = 1;
Delay_us(30);
DataDir = 1; // Data port is input
}
unsigned short CheckResponse()
{
TOUT = 0;
TMR2 = 0;
T2CON.TMR2ON = 1; // start timer
while (!DHT && !TOUT)
;
if (TOUT)
return 0;
else
{
TMR2 = 0;
while (DHT && !TOUT)
;
if (TOUT)
return 0;
else
{
T2CON.TMR2ON = 0;
return 1;
}
}
}
unsigned short ReadByte()
{
unsigned short num = 0, t;
DataDir = 1;
for (i = 0; i < 8; i++)
{
while (!DHT)
;
Delay_us(40);
if (DHT)
num |= 1 << (7 - i);
while (DHT)
;
}
return num;
}
void ReadDHT11()
{
unsigned short check;
PIE1.TMR2IE = 1; // Enable Timer2 interrupt
StartSignal();
check = CheckResponse();
RH_Byte1 = ReadByte();
RH_Byte2 = ReadByte();
T_Byte1 = ReadByte();
T_Byte2 = ReadByte();
CheckSum = ReadByte();
// Check for error in Data reception
lcd_cmd(_lcd_clear);
lcd_out(1, 1, "Read");
delay_ms(1000);
if (CheckSum == ((RH_Byte1 + RH_Byte2 + T_Byte1 + T_Byte2) & 0xFF))
{
Lcd_Out(1, 1, "HUMIDITY:");
message[0] = RH_Byte1 / 10 + 48;
message[1] = RH_Byte1 % 10 + 48;
// buff[26] = RH_Byte1 / 10 + 48;
// buff[27] = RH_Byte1 % 10 + 48;
Lcd_Out(1, 11, message);
Lcd_Out(1, 16, "%");
UART1_Write_Text("humid:");
delay_ms(20);
UART1_Write_Text(message);
delay_ms(20);
// uart1_write('H');
//uart1_write_text(message);
//UART1_Write_Text("\r\n");
delay_ms(100);
Lcd_Out(2, 1, "TEMP:");
message[0] = T_Byte1 / 10 + 48;
message[1] = T_Byte1 % 10 + 48;
// buff[6] = T_Byte1 / 10 + 48;
// buff[7] = T_Byte1 % 10 + 48;
Lcd_Out(2, 11, message);
Lcd_Chr_CP(223);
Lcd_Out(2, 16, "C");
uart1_write_text(" ");
UART1_Write_Text("temp:");
delay_ms(20);
UART1_Write_Text(message);
delay_ms(20);
// uart1_write('T');
//uart1_write_text(message);
//UART1_Write_Text("\r\n");
Delay_ms(200);
}
lcd_cmd(_lcd_clear);
lcd_out(1, 1, "finish");
delay_ms(100);
PIE1.TMR2IE = 0; // disable Timer2 interrupt
}
|
package View;
import DAO.ProdutoDAO;
import View.TelaPrincipal;
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author luciana
*/
class TelaCadastroProduto extends JFrame {
JLabel labelCodigoProduto, labelDescricao, labelPreco, labelUnidade, labelQuantidadeInicial, labelDataCadastro, labelQuantidadeAtual, label3, label4;
JButton btGravar, btAlterar, btExcluir, btNovo, btLocalizar, btCancelar, btVoltarMenuPrincipal, btSair;
JButton btPrimeiro, btAnterior, btProximo, btUltimo, btCons;
JPanel painel, painelBotoes, painelREG;
JFrame janela;
static JTextField textFieldCodigoProduto, textFieldDescricao, textFieldPreco, textFieldUnidade, textFieldQuantidadeInicial, textFieldDataCadastro, textFieldQuantidadeAtual;
private ProdutoDAO produtos;
private ResultSet objetoResultSet;
private TelaConsultaProduto consultaProdutos;
public TelaCadastroProduto() {
inicializacomponentes();
definirEventos();
}
public void inicializacomponentes() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout()); //define layout da janela
painel = new JPanel();
painel.setLayout(new BoxLayout(painel, BoxLayout.PAGE_AXIS)); //define layout do painel
this.add(painel, BorderLayout.NORTH);
painelBotoes = new JPanel(new FlowLayout()); //define layout do painelBotoes
this.add(painelBotoes, BorderLayout.CENTER);
painelREG = new JPanel(new FlowLayout()); //define layout do painelREG
this.add(painelREG, BorderLayout.SOUTH);
setTitle("Cadastro de Produtos");
setSize(750, 450);
setLocationRelativeTo(null);
labelCodigoProduto = new JLabel("Código do Produto: ");
textFieldCodigoProduto = new JTextField(4);
labelDescricao = new JLabel("Descrição: ");
textFieldDescricao = new JTextField(80);
labelPreco = new JLabel("Preço:");
textFieldPreco = new JTextField(80);
labelUnidade = new JLabel("Unidade:");
textFieldUnidade = new JTextField(80);
labelQuantidadeInicial = new JLabel("Quantidade Inicial:");
textFieldQuantidadeInicial = new JTextField(80);
labelDataCadastro = new JLabel("Data de Cadastro:");
textFieldDataCadastro = new JTextField(80);
labelQuantidadeAtual = new JLabel("Quantidade Atual:");
textFieldQuantidadeAtual = new JTextField(80);
label3 = new JLabel("Movimentação de Registros");
btGravar = new JButton("Gravar");
btAlterar = new JButton("Alterar");
btExcluir = new JButton("Excluir");
btLocalizar = new JButton("Localizar");
btNovo = new JButton("Novo");
btCancelar = new JButton("Cancelar");
btCons = new JButton("Consultar");
btVoltarMenuPrincipal = new JButton("Menu Principal");
btSair = new JButton("Sair");
btPrimeiro = new JButton("<<");
btPrimeiro.setToolTipText("Primeiro");
btAnterior = new JButton("<");
btAnterior.setToolTipText("Anterior");
btProximo = new JButton(">");
btProximo.setToolTipText("Próximo");
btUltimo = new JButton(">>");
btUltimo.setToolTipText("Ultimo");
painel.add(labelCodigoProduto);
painel.add(textFieldCodigoProduto);
painel.add(labelDescricao);
painel.add(textFieldDescricao);
painel.add(labelPreco);
painel.add(textFieldPreco);
painel.add(labelUnidade);
painel.add(textFieldUnidade);
painel.add(labelQuantidadeInicial);
painel.add(textFieldQuantidadeInicial);
painel.add(labelDataCadastro);
painel.add(textFieldDataCadastro);
painel.add(labelQuantidadeAtual);
painel.add(textFieldQuantidadeAtual);
painelBotoes.add(btNovo);
painelBotoes.add(btLocalizar);
painelBotoes.add(btGravar);
painelBotoes.add(btAlterar);
painelBotoes.add(btExcluir);
painelBotoes.add(btCancelar);
painelBotoes.add(btCons);
painelBotoes.add(btVoltarMenuPrincipal);
painelBotoes.add(btSair);
painelREG.add(label3);
painelREG.add(btPrimeiro);
painelREG.add(btAnterior);
painelREG.add(btProximo);
painelREG.add(btUltimo);
setResizable(true);
setBotoes(true, true, false, false, false, false);
produtos = new ProdutoDAO();
if (!produtos.objetoConexaoBD.getConnection()) {
JOptionPane.showMessageDialog(null, "Falha na conexão!");
System.exit(0);
}
tabelaProdutos();
//tfRA.setEnabled(false);
//tfNome.setEnabled(false);
//carregaDados();
}
public void setBotoes(boolean bNovo, boolean bLocalizar, boolean bGravar,
boolean bAlterar, boolean bExcluir, boolean bCancelar) {
btNovo.setEnabled(bNovo);
btLocalizar.setEnabled(bLocalizar);
btGravar.setEnabled(bGravar);
btAlterar.setEnabled(bAlterar);
btExcluir.setEnabled(bExcluir);
btCancelar.setEnabled(bCancelar);
}
public void definirEventos() {
btSair.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
produtos.objetoConexaoBD.close();
System.exit(0);
}
});
btVoltarMenuPrincipal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
produtos.objetoConexaoBD.close();
//estanciar a tela produto
TelaPrincipal objetofrmPrincipalVIEW = new TelaPrincipal();
//exibir o objeto tela principal
objetofrmPrincipalVIEW.setVisible(true);
//fechar a tela
dispose();
}
});
btProximo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
objetoResultSet.next();
carregaDados();
} catch (SQLException erro) {
}
}
});
btAnterior.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
objetoResultSet.previous();
carregaDados();
} catch (SQLException erro) {
}
}
});
btPrimeiro.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
objetoResultSet.first();
carregaDados();
} catch (SQLException erro) {
}
}
});
btUltimo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
objetoResultSet.last();
carregaDados();
} catch (SQLException erro) {
}
}
});
btNovo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textFieldCodigoProduto.setEnabled(false);
//tfNome.setEnabled(true);
limparcampos();
setBotoes(false, false, true, false, false, true);
textFieldDescricao.requestFocus();
}
});
btCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textFieldCodigoProduto.setEnabled(true);
//tfRA.setEnabled(false);
//tfNome.setEnabled(false);
limparcampos();
tabelaProdutos();
}
});
btGravar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (textFieldDescricao.getText().equals("")) {
JOptionPane.showMessageDialog(null, "O nome não pode ser vazio!");
textFieldDescricao.requestFocus();
return;
}
produtos.produto.setDescricao(textFieldDescricao.getText());
produtos.produto.setPreco(Double.parseDouble(textFieldPreco.getText()));
produtos.produto.setUnidade(textFieldUnidade.getText());
produtos.produto.setQuantidadeInicial(Double.parseDouble(textFieldQuantidadeInicial.getText()));
produtos.produto.setDataCadastro(textFieldDataCadastro.getText());
produtos.produto.setQuantidadeAtual(Double.parseDouble(textFieldQuantidadeAtual.getText()));
JOptionPane.showMessageDialog(null, produtos.atualizar(ProdutoDAO.INCLUSAO));
textFieldCodigoProduto.setEnabled(true);
limparcampos();
tabelaProdutos();
}
});
btAlterar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
produtos.produto.setDescricao(textFieldDescricao.getText());
produtos.produto.setPreco(Double.parseDouble(textFieldPreco.getText()));
produtos.produto.setUnidade(textFieldUnidade.getText());
produtos.produto.setQuantidadeInicial(Double.parseDouble(textFieldQuantidadeInicial.getText()));
produtos.produto.setDataCadastro(textFieldDataCadastro.getText());
produtos.produto.setQuantidadeAtual(Double.parseDouble(textFieldQuantidadeAtual.getText()));
JOptionPane.showMessageDialog(null, produtos.atualizar(ProdutoDAO.ALTERACAO));
limparcampos();
tabelaProdutos();
}
});
btExcluir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
produtos.produto.setCodigoProduto(Integer.parseInt(textFieldCodigoProduto.getText()));
produtos.localizar();
int n = JOptionPane.showConfirmDialog(null, produtos.produto.getDescricao(),
"Excluir o produto?", JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, produtos.atualizar(ProdutoDAO.EXCLUSAO));
limparcampos();
tabelaProdutos();
}
}
});
btLocalizar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
atualizarCampos();
tabelaProdutos();
}
});
btCons.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame janela = new TelaConsultaProduto();
janela.setVisible(true);
}
});
}
public void limparcampos() {
//textFieldCodigoProduto.setText("");
textFieldDescricao.setText("");
textFieldPreco.setText("");
textFieldUnidade.setText("");
textFieldQuantidadeInicial.setText("");
textFieldDataCadastro.setText("");
textFieldQuantidadeAtual.setText("");
setBotoes(true, true, false, false, false, false);
}
public void atualizarCampos() {
produtos.produto.setCodigoProduto(Integer.parseInt(textFieldCodigoProduto.getText()));
if (produtos.localizar()) {
textFieldCodigoProduto.setText(Integer.toString(produtos.produto.getCodigoProduto()));
textFieldDescricao.setText(produtos.produto.getDescricao());
textFieldPreco.setText(Double.toString(produtos.produto.getPreco()));
textFieldUnidade.setText(produtos.produto.getUnidade());
textFieldQuantidadeInicial.setText(Double.toString(produtos.produto.getQuantidadeInicial()));
textFieldDataCadastro.setText(produtos.produto.getDataCadastro());
textFieldQuantidadeAtual.setText(Double.toString(produtos.produto.getQuantidadeAtual()));
setBotoes(true, true, false, true, true, true);
} else {
JOptionPane.showMessageDialog(null, "Produto não econtrado!");
limparcampos();
}
}
public void tabelaProdutos() {
try {
String sql = "Select * from produtos";
PreparedStatement statement = produtos.objetoConexaoBD.objetoConnection.prepareStatement(sql);
objetoResultSet = statement.executeQuery();
} catch (SQLException erro) {
JOptionPane.showMessageDialog(null, "Problemas na conexão!\n" + erro.toString());
}
}
public void carregaDados() {
try {
//String vazio = " ";
if (objetoResultSet.isAfterLast()) {
objetoResultSet.last();
}
if (objetoResultSet.isBeforeFirst()) {
objetoResultSet.first();
}
textFieldCodigoProduto.setText(objetoResultSet.getString("codprod"));
textFieldDescricao.setText(objetoResultSet.getString("descricao"));
textFieldPreco.setText(objetoResultSet.getString("preco"));
textFieldUnidade.setText(objetoResultSet.getString("unidade"));
textFieldQuantidadeInicial.setText(objetoResultSet.getString("qtde_inicial"));
textFieldDataCadastro.setText(objetoResultSet.getString("data_cad"));
textFieldQuantidadeAtual.setText(objetoResultSet.getString("qtde_atual"));
} catch (SQLException erro) {
JOptionPane.showMessageDialog(null, "Problemas na conexão!\n" + erro.toString());
}
}
}
|
/**
* @file 7-getBudgetObject.js
* @author TheWatcher01
* @date 06-05-2024
* @description This file contains a function that creates a budget object from given parameters.
*/
/**
* @function getBudgetObject
* @description Constructs a budget object from given income, GDP, and GDP per capita values.
* @param {string} income - The income value.
* @param {string} gdp - The GDP value.
* @param {string} capita - The GDP per capita value.
* @returns {Object} A budget object containing the income, GDP, and GDP per capita.
*/
export default function getBudgetObject(income, gdp, capita) {
const budget = {
income,
gdp,
capita,
};
return budget;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.