text
stringlengths 184
4.48M
|
|---|
import React from 'react';
import { NavLink, Link } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { useMutation } from '@apollo/client';
import { CHANGE_THEME } from '../../graphql/mutations/userMutations';
import Styles from '../../styles/nav/nav__user-menu.module.css';
import { light, dark } from '../../functions/theme';
import { CgDarkMode } from 'react-icons/cg';
import {
IoPersonCircleOutline,
IoPersonAddOutline,
IoLogOut,
} from 'react-icons/io5';
const NavUserMenu = ({ setOpenMenu, theme, setTheme }) => {
const { currentUser, logout } = useAuth();
const [changeTheme] = useMutation(CHANGE_THEME);
const handleClick = (e) => {
e.preventDefault();
setOpenMenu(false);
};
const handleTheme = async (e) => {
e.preventDefault();
if (theme === 'light') {
dark();
setTheme('dark');
if (currentUser) {
await changeTheme();
}
} else if (theme === 'dark') {
light();
setTheme('light');
if (currentUser) {
await changeTheme();
}
}
};
return (
<div onClick={handleClick} className={Styles.container}>
<div className={Styles.inner}>
{currentUser ? (
<>
<NavLink
className={Styles.option}
to={`/profile/${currentUser.id}`}
>
<IoPersonCircleOutline className={Styles.icon} />
<div>
<p>Profile</p>
</div>
</NavLink>
<div onClick={handleTheme} className={Styles.option}>
<CgDarkMode className={Styles.icon} />
<p>Change Theme</p>
</div>
<div onClick={logout} className={Styles.option}>
<IoLogOut className={Styles.icon} />
<p>Logout</p>
</div>
</>
) : (
<>
<Link className={Styles.option} to="/sign-up">
<IoPersonAddOutline className={Styles.icon} />
<div>
<p>Sign Up</p>
</div>
</Link>
<div onClick={handleTheme} className={Styles.option}>
<CgDarkMode className={Styles.icon} />
<p>Change Theme</p>
</div>
</>
)}
</div>
</div>
);
};
export default NavUserMenu;
|
// Recursion practice. More detailed progress can be found in testing ground repo. mergeSort function completed 12/10/23 commit: 89bcaab
// ************************************************************************************************************************
// Fibonacci without recursion:
function fibs(number) {
const array = [0, 1];
if (number === 0) {
return [];
}
if (number === 1) {
return [0];
}
for (let i = 0; i < number - 2; i++) {
const secondLast = array[array.length - 2];
const last = array[array.length - 1];
const newNumber = secondLast + last;
array.push(newNumber);
}
return array;
}
console.log(fibs(4));
console.log(fibs(8));
console.log(fibs(5));
// ************************************************************************************************************************
// Fibonacci with recursion:
function fibsRec(number) {
if (number === 0) {
return [];
}
if (number === 1) {
return [0];
}
if (number === 2) {
return [0, 1];
}
const array = fibsRec(number - 1);
array.push(array[array.length - 1] + array[array.length - 2]);
return array;
}
console.log(fibsRec(2));
console.log(fibsRec(3));
console.log(fibsRec(8));
// For Recursion - we want to break the problem into smaller problems. In this case, we're breaking it down to: add one more number to the array. Or, take the array of the number lower than this, then add one number.
// If F represents a function to calculate the fibonacci number at index n, then:
// F(n) = f(n-1) + f(n-2)
// ************************************************************************************************************************
// mergeSort with recursion:
function mergeSort(array) {
if (array.length < 2) {
return array;
}
let halfLength = array.length / 2;
if (halfLength % 2 !== 1) {
halfLength += 0.5;
}
const halfArray1 = array.slice(0, halfLength);
const halfArray2 = array.slice(halfLength);
let sortedHalf1 = mergeSort(halfArray1);
let sortedHalf2 = mergeSort(halfArray2);
let storageArray = [];
for (let i = 0; i < array.length; i++) {
if (sortedHalf1[0] < sortedHalf2[0]) {
storageArray.push(sortedHalf1[0]);
sortedHalf1 = sortedHalf1.splice(1);
} else if (sortedHalf1[0] > sortedHalf2[0]) {
storageArray.push(sortedHalf2[0]);
sortedHalf2 = sortedHalf2.splice(1);
} else if (sortedHalf1[0] === sortedHalf2[0]){
storageArray.push(sortedHalf1[0]);
sortedHalf1 = sortedHalf1.splice(1);
} else if (sortedHalf1[0] === undefined) {
storageArray.push(sortedHalf2[0]);
sortedHalf2 = sortedHalf2.splice(1);
} else if (sortedHalf2[0] === undefined) {
storageArray.push(sortedHalf1[0]);
sortedHalf1 = sortedHalf1.splice(1);
}
}
return storageArray;
}
// console.log(mergeSort([1]));
// console.log(mergeSort([4, 2]));
// console.log(mergeSort([2, 1, 4, 3]));
// console.log(mergeSort([6, 3, 2, 4, 5, 1]));
console.log(mergeSort([6, 3, 2, 8, 7, 4, 5, 1]));
console.log(mergeSort([6, 3, 2, 8, 7, 4, 5, 1, 2, 5]));
console.log(mergeSort([6, 13, 62, 8, 47, 4, 5, 100, 54, 456, 78, 35, 44]));
// NOTES:
// After looking at other solutions I realize I could've used Math.floor to round down to the nearest integer when dividing the array by half length
|
const Joi = require("joi");
const bookATableSchema = Joi.object({
name: Joi.string().min(2).max(256).required(),
phone: Joi.string()
.regex(new RegExp(/0[0-9]{1,2}\-?\s?[0-9]{3}\s?[0-9]{4}/))
.required(),
date: Joi.string()
.regex(new RegExp(/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/))
.required(),
time: Joi.string()
.regex(new RegExp(/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/))
.required(),
numOfPeople: Joi.string().min(1).max(10).required(),
bizNumber: Joi.number().min(1000000).max(9999999).allow(""),
/* orderStatus: Joi.boolean().required(), */
});
const validateBookATableSchema = (userInput) =>
bookATableSchema.validateAsync(userInput);
module.exports = {
validateBookATableSchema,
};
|
#pragma once
#include <memory>
#include <string>
#include <vcsn/core/join.hh>
#include <vcsn/core/kind.hh>
#include <vcsn/core/rat/fwd.hh>
#include <vcsn/ctx/fwd.hh>
#include <vcsn/ctx/traits.hh>
#include <vcsn/misc/format.hh>
#include <vcsn/misc/stream.hh>
#include <vcsn/misc/symbol.hh>
namespace vcsn
{
template <typename LabelSet, typename WeightSet>
class context
{
public:
using labelset_t = LabelSet;
using weightset_t = WeightSet;
using labelset_ptr = std::shared_ptr<const labelset_t>;
using weightset_ptr = std::shared_ptr<const weightset_t>;
using kind_t = typename labelset_t::kind_t;
enum
{
is_lal = vcsn::is_lal<context>::value,
is_lan = vcsn::is_lan<context>::value,
is_lao = vcsn::is_lao<context>::value,
is_lar = vcsn::is_lar<context>::value,
is_lat = vcsn::is_lat<context>::value,
is_law = vcsn::is_law<context>::value,
};
/// Type of transition labels, and type of expression atoms.
using label_t = typename labelset_t::value_t;
/// Type of weights.
using weight_t = typename weightset_t::value_t;
context(const context& that)
: context(that.ls_, that.ws_)
{}
/// \param ls the labelset
/// \param ws the weightset
context(const labelset_ptr& ls, const weightset_ptr& ws)
: ls_{ls}
, ws_{ws}
{}
/// Build a context.
/// \param ls the labelset
/// \param ws the weightset
context(const labelset_t& ls = {}, const weightset_t& ws = {})
: context(std::make_shared<const labelset_t>(ls),
std::make_shared<const weightset_t>(ws))
{}
context& operator=(context&& that)
{
if (this != &that)
{
std::swap(ls_, that.ls_);
std::swap(ws_, that.ws_);
}
return *this;
}
/// The name of this context, built from its parameters.
/// E.g., "lal_char, b", "law_char, zmin".
static symbol sname()
{
static auto res = symbol{"context<"
+ labelset_t::sname()
+ ", "
+ weightset_t::sname()
+ '>'};
return res;
}
/// Build from the description in \a is.
static context make(std::istream& is)
{
eat(is, "context<");
auto ls = labelset_t::make(is);
eat(is, ',');
while (isspace(is.peek()))
is.ignore();
auto ws = weightset_t::make(is);
eat(is, '>');
return {ls, ws};
}
const labelset_ptr& labelset() const
{
return ls_;
}
const weightset_ptr& weightset() const
{
return ws_;
}
std::ostream&
print_set(std::ostream& o, format fmt = {}) const
{
labelset()->print_set(o, fmt);
switch (fmt.kind())
{
case format::latex:
o << "\\to";
break;
case format::sname:
o << ", ";
break;
case format::text:
o << " -> ";
break;
case format::utf8:
o << " → ";
break;
case format::raw:
assert(0);
break;
}
weightset()->print_set(o, fmt);
return o;
}
static constexpr bool
has_one()
{
return labelset_t::has_one();
}
private:
labelset_ptr ls_;
weightset_ptr ws_;
};
/// Shorthand to build a context.
template <typename LabelSet, typename WeightSet>
context<LabelSet, WeightSet>
make_context(const LabelSet& ls, const WeightSet& ws)
{
return {ls, ws};
}
template <typename LabelSet, typename WeightSet>
struct is_multitape<context<LabelSet, WeightSet>>
: is_multitape<LabelSet>
{};
template <typename LabelSet, typename WeightSet>
struct number_of_tapes<context<LabelSet, WeightSet>>
: number_of_tapes<LabelSet>
{};
/*----------.
| meet_t. |
`----------*/
template <typename... ValueSets>
using meet_t = decltype(meet(std::declval<ValueSets>()...));
/// The meet of a single valueset.
/// Useful for variadic operator on a single argument.
template <typename ValueSet>
auto
meet(const ValueSet& vs)
-> ValueSet
{
return vs;
}
template <typename ValueSet1, typename ValueSet2, typename ValueSet3,
typename... VSs>
auto
meet(const ValueSet1& vs1, const ValueSet2& vs2, const ValueSet3& vs3,
const VSs&... vs)
-> decltype(meet(meet(vs1, vs2), vs3, vs...))
{
return meet(meet(vs1, vs2), vs3, vs...);
}
/*-------------------------.
| join(context, context). |
`-------------------------*/
namespace detail
{
/// The join of two contexts.
template <typename LS1, typename WS1,
typename LS2, typename WS2>
struct join_impl<context<LS1, WS1>, context<LS2, WS2>>
{
using labelset_t = join_t<LS1, LS2>;
using weightset_t = join_t<WS1, WS2>;
using type = context<labelset_t, weightset_t>;
static type join(const context<LS1, WS1>& ctx1,
const context<LS2, WS2>& ctx2)
{
// Don't use braces, otherwise the context constructor that
// takes a list-initializer for the labelset thinks both
// values here are letters for the labelset.
return type(vcsn::join(*ctx1.labelset(), *ctx2.labelset()),
vcsn::join(*ctx1.weightset(), *ctx2.weightset()));
}
};
}
/*-------------------------.
| meet(context, context). |
`-------------------------*/
/// The meet of two contexts.
template <typename LhsLabelSet, typename LhsWeightSet,
typename RhsLabelSet, typename RhsWeightSet>
auto
meet(const context<LhsLabelSet, LhsWeightSet>& a,
const context<RhsLabelSet, RhsWeightSet>& b)
-> context<meet_t<LhsLabelSet, RhsLabelSet>,
join_t<LhsWeightSet, RhsWeightSet>>
{
auto ls = meet(*a.labelset(), *b.labelset());
auto ws = join(*a.weightset(), *b.weightset());
return {ls, ws};
}
}
|
---
permalink: api/reference_element_api_startbulkvolumeread.html
sidebar: sidebar
keywords: volume,read,session,start,starting,bulk,startbulkvolumeread
summary: Se puede utilizar el método StartBulkVolumeRead para iniciar una sesión de lectura de volumen masivo en un volumen especificado.
---
= StartBulkVolumeRead
:allow-uri-read:
:icons: font
:imagesdir: ../media/
[role="lead"]
Puede utilizar el `StartBulkVolumeRead` método para iniciar una sesión de lectura masiva de volúmenes en un volumen especificado.
Solo se pueden ejecutar simultáneamente dos procesos de volúmenes masivos en un volumen. Cuando se inicializa la sesión, se leen datos de un volumen de almacenamiento de SolidFire que se almacena en un origen de backup externo. Un servidor web que se ejecuta en un nodo de almacenamiento de Element, accede a los datos externos. La información de interacción del servidor para el acceso a datos externos es pasada por un script que se ejecuta en el sistema de almacenamiento.
Al inicio de una operación de lectura masiva de volúmenes, se realiza una copia de Snapshot del volumen y la copia de Snapshot se elimina cuando finaliza la lectura. También es posible leer una copia de Snapshot del volumen si se introduce el ID de la copia de Snapshot como un parámetro. Cuando se lee una snapshot anterior, el sistema no crea una snapshot nueva del volumen ni elimina la snapshot anterior cuando finaliza la lectura.
NOTE: Este proceso crea una nueva snapshot si no se proporciona el ID de una snapshot existente. Se pueden crear copias de Snapshot si la ocupación del clúster se encuentra en la etapa 2 o 3. Las copias de Snapshot no se crean cuando la ocupación del clúster se encuentra en la etapa 4 o 5.
== Parámetros
Este método tiene los siguientes parámetros de entrada:
|===
| Nombre | Descripción | Tipo | Valor predeterminado | Obligatorio
a|
formato
a|
El formato de los datos del volumen. Puede ser:
* `uncompressed`: Todos los bytes del volumen se devuelven sin compresión.
* `native`: Los datos Opaque se devuelven que son más pequeños y eficientes almacenados y escritos en una escritura masiva posterior.
a|
cadena
a|
Ninguno
a|
Sí
a|
ID de volumen
a|
El ID del volumen que se leerá.
a|
entero
a|
Ninguno
a|
Sí
a|
ID de copia Snapshot
a|
El ID de una snapshot creada previamente para lecturas de volúmenes masivos. Si no se introduce ningún ID, se realiza una snapshot de la imagen de volumen activo actual.
a|
entero
a|
Ninguno
a|
No
a|
guión
a|
El nombre de un script ejecutable. Si no se otorga ningún nombre de script, la clave y la URL son necesarias para acceder a los nodos de almacenamiento Element. La secuencia de comandos se ejecuta en el nodo primario, y la clave y la URL se devuelven al script para que se pueda contactar con el servidor web local.
a|
cadena
a|
Ninguno
a|
No
a|
ScriptParameters
a|
Parámetros JSON para pasar al script.
a|
Objeto JSON
a|
Ninguno
a|
No
a|
atributos
a|
Atributos JSON para el trabajo de volúmenes masivos.
a|
Objeto JSON
a|
Ninguno
a|
No
|===
== Valores devueltos
Este método tiene los siguientes valores devueltos:
|===
| Nombre | Descripción | Tipo
a|
Establish asyncHandle
a|
El ID del proceso asíncrono que se comprobará para que finalice.
a|
entero
a|
clave
a|
Clave opaca que identifica de forma exclusiva la sesión.
a|
cadena
a|
url
a|
URL para acceder al servidor web del nodo.
a|
cadena
|===
== Ejemplo de solicitud
Las solicitudes de este método son similares al ejemplo siguiente:
[listing]
----
{
"method": "StartBulkVolumeRead",
"params": {
"volumeID" : 5,
"format" : "native",
"snapshotID" : 2
},
"id": 1
}
----
== Ejemplo de respuesta
Este método devuelve una respuesta similar al siguiente ejemplo:
[listing]
----
{
"id" : 1,
"result" : {
"asyncHandle" : 1,
"key" : "11eed8f086539205beeaadd981aad130",
"url" : "https://127.0.0.1:44000/"
}
}
----
== Nuevo desde la versión
9.6
|
/*
Haz una aplicación que calcule el área de un cÃrculo(pi*R2). El radio se pedirá
por teclado (recuerda pasar de String a double con Double.parseDouble). Usa la
constante PI y el método pow de Math.
*/
package com.mycompany.ejercicio_5;
import java.util.Scanner;
public class Ejercicio_5 {
public static void main(String[] args) {
// Declaracion de variables
double pi = 3.1416;
double radio = 0;
double area = 0;
// Se importa la funcion Scanner para poder resivir informacion por tec
Scanner radio_circulo = new Scanner (System.in);
System.out.print("Ingrese el radio del circulo: ");
// La variable radio se le asigna la informacion que contiene el Scanner
// y se le pasa el metodo nextDouble() para que el string que le retorna
// el Scaner lo convierta en decimal
radio = radio_circulo.nextDouble();
// El valor que contiene la variable radio se le asigna la funcion Math
// con le metodo pow para elevar la misma variable al cuadrado
radio = Math.pow(radio,2);
// Se realiza la operacion para hallar el area de un circulo
area = pi * radio;
// Se imprime el resultado por consola
System.out.println("El area del cuadrado es: "+area);
}
}
|
# 2023-10-19 13:08
* 185 - Variables & Debug
-------------------------
# First we'll see how to define a vaieble in an Ansible playbook
*PLAYBOOK*
- hosts: websrvgrp
vars:
http_port: 80
sqluser: admin
*Inventory Based*
If you want to define some variable for all the hosts, we can create a file with paths. This will be your own custom variables (not the Ansible user, login key) that you can use in your playbook (like http port, SQL user ets.)
group_vars/all
group_vars/groupname
host_vars/hostname
You shouldn't save passwords in variables. There is a better way to save it.
*Roles in Ansible*
# Include variables from files in playbook
*Fact variables*
Ansible has also its own variables. The majoruty of its variables get generated from the setup module. You don't need to run setup module when you execute playbook. The first task that gets executed gathering facts.
That tast will run the setup mdule and generate the fact variables.
Some examples of *fact variables*:
- ansible_os_family OS name like Red Hat, Debian etc.
- ansible_processor_cores Number of CPU cores
- ansible_kernel Kernel Version
- ansible_devices Connected devices information
- ansible_default_ipv4 IP, MAC addr., gateway etc.
- ansible_architecture 64/32 bit etc.
...
We can use variables with conditions and decision making in playbooks (late we'll see that).
*Returns of tasks*
The other way is storing the output of a task or any module that we run. The output usually return in JSON format. We can store that output into a variable and then we can use it.
Let's see all above usecases one by one.
{'name':'Control Machine', 'publicIP':'3.81.224.245'}
{'name':'profile-db02', 'privateIP':'172.31.20.103'}
{'name':'profile-db03', 'privateIP':'172.31.25.103'}
{'name':'profile-web01', 'privateIP':'172.31.23.107'}
$ ssh -i "~/.aws/230724-ec2-t2micro.pem" ubuntu@3.81.224.245
ubuntu@ip-172-31-31-168:~$ cd vprofile/exercise6
ubuntu@ip-172-31-31-168:~/vprofile/exercise6$ ls -ltr
total 36
-r-------- 1 ubuntu ubuntu 387 Oct 18 09:42 vprofile-key.pem
-rw-rw-r-- 1 ubuntu ubuntu 54 Oct 18 10:14 index.html
-rw-rw-r-- 1 ubuntu ubuntu 261 Oct 18 17:10 inventory
-rw-rw-r-- 1 ubuntu ubuntu 789 Oct 18 17:12 web_db.yaml
-rw-rw-r-- 1 ubuntu ubuntu 191 Oct 19 08:38 ansible.cfg
-rw-rw-r-- 1 ubuntu ubuntu 624 Oct 19 09:39 dbex6.yaml
-rw-rw-r-- 1 ubuntu ubuntu 624 Oct 19 09:39 db2.yaml
-rw-rw-r-- 1 ubuntu ubuntu 362 Oct 19 09:44 db2rem.yaml
-rw-rw-r-- 1 ubuntu ubuntu 1147 Oct 19 10:00 db3.yaml
-------
ubuntu@ip-172-31-31-168:~/vprofile/exercise6$ vim dbex6.yaml
---
- name: Setup DBServer
hosts: dbsrvgrp
become: yes
vars:
dbname: "groups"
dbuser: "devops"
dbpass: "admin123"
tasks:
- debug:
var: dbname
- debug:
msg: "Value of dbuser is {{dbuser}}"
- name: Install Python MySQL dependency
yum:
name: MySQL-python
state: present
- name: Install MySQL server
yum:
name: mariadb-server
state: present
- name: Start & Enable mariadb service
service:
name: mariadb
state: started
enabled: yes
- name: Create a new database with name 'acc19'
mysql_db:
name: "{{dbname}}"
state: present
- name: Create database user with name 'admin'
mysql_user:
name: "{{dbuser}}"
password: "{{dbpass}}"
priv: '*.*:ALL'
state: present
-------
# Проверка синтаксиса
ubuntu@ip-172-31-31-168:~/vprofile/exercise6$ ansible-playbook dbex6.yaml --syntax-check -C
playbook: dbex6.yaml
# Сухой пуск
ubuntu@ip-172-31-31-168:~/vprofile/exercise6$ ansible-playbook dbex6.yaml -C
# Удаление старой СУБД
ubuntu@ip-172-31-31-168:~/vprofile/exercise6$ ansible-playbook db2rem.yaml
...
PLAY RECAP ***************************************************************
db02 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
db03 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
# Установка и конфигурация новой СУБД на те же инстансы
ubuntu@ip-172-31-31-168:~/vprofile/exercise6$ ansible-playbook dbex6.yaml
...
PLAY RECAP **************************************************************
db02 : ok=8 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
db03 : ok=8 changed=5 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
|
using DsDelivery.Core.Shared.Dto.Order;
using DsDelivery.FakeData.OrderData;
using DsDelivery.Manager.Interfaces;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NSubstitute;
using NSubstitute.ReturnsExtensions;
using Xunit;
namespace DsDelivery.WebApi.Controllers.Tests
{
public class OrderControllerTest
{
private readonly IOrderService manager;
private readonly ILogger<OrderController> logger;
private readonly OrderController controller;
private readonly OrderDTO orderDTO;
private readonly List<OrderDTO> listaOrderDTO;
private readonly CreateOrderDTO createOrderDTO;
public OrderControllerTest()
{
manager = Substitute.For<IOrderService>();
logger = Substitute.For<ILogger<OrderController>>();
controller = new OrderController(manager, logger);
orderDTO = new OrderFakerDtoRefactor().Generate();
listaOrderDTO = new OrderFakerDtoRefactor().Generate(10);
createOrderDTO = new CreateOrderFakerDto().Generate();
}
[Fact]
public async Task GetAllOrders_Ok()
{
var controle = new List<OrderDTO>();
listaOrderDTO.ForEach(p => controle.Add(p.CloneTipado()));
manager.GetAllAsync().Returns(listaOrderDTO);
var resultado = (ObjectResult)await controller.GetAll();
await manager.Received().GetAllAsync();
resultado.StatusCode.Should().Be(StatusCodes.Status200OK);
resultado.Value.Should().BeEquivalentTo(controle);
}
[Fact]
public async Task GetAllOrders_NotFound()
{
manager.GetAllAsync().Returns(new List<OrderDTO>());
var resultado = (StatusCodeResult)await controller.GetAll();
await manager.Received().GetAllAsync();
resultado.StatusCode.Should().Be(StatusCodes.Status404NotFound);
}
[Fact]
public async Task GetOrder_GetById_Ok()
{
manager.GetByIdAsync(Arg.Any<int>()).Returns(orderDTO.CloneTipado());
var resultado = (ObjectResult)await controller.GetOrderById(orderDTO.Id);
await manager.Received().GetByIdAsync(Arg.Any<int>());
resultado.Value.Should().BeEquivalentTo(orderDTO);
resultado.StatusCode.Should().Be(StatusCodes.Status200OK);
}
[Fact]
public async Task GetByIdOrder_NotFound()
{
manager.GetByIdAsync(Arg.Any<int>()).Returns(new OrderDTO());
var resultado = (StatusCodeResult)await controller.GetOrderById(1);
await manager.Received().GetByIdAsync(Arg.Any<int>());
resultado.StatusCode.Should().Be(StatusCodes.Status404NotFound);
}
[Fact]
public async Task PostOrder_Created()
{
manager.InsertAsync(Arg.Any<CreateOrderDTO>()).Returns(orderDTO.CloneTipado());
var resultado = (ObjectResult)await controller.CreateOrder(createOrderDTO);
await manager.Received().InsertAsync(Arg.Any<CreateOrderDTO>());
resultado.StatusCode.Should().Be(StatusCodes.Status201Created);
resultado.Value.Should().BeEquivalentTo(orderDTO);
}
[Fact]
public async Task SetDelivered_Ok()
{
manager.SetDeliveredAsync(orderDTO.Id).Returns(orderDTO.CloneTipado());
var resultado = await controller.SetDelivered(orderDTO.Id);
await manager.Received().SetDeliveredAsync(orderDTO.Id);
resultado.Result.Should().BeOfType<OkObjectResult>();
}
[Fact]
public async Task SetDelivered_NotFound()
{
manager.SetDeliveredAsync(orderDTO.Id).ReturnsNull();
var resultado = await controller.SetDelivered(orderDTO.Id);
resultado.Result.Should().BeOfType<NotFoundResult>();
}
}
}
|
const puppeteer = require("puppeteer");
const fs = require("fs");
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36');
await page.goto("https://www.bestprice.gr/cat/806/mobile-phones.html" );
await page.waitForTimeout(1000);
await page.screenshot({path:"best_price_page1.png",fullPage: true})
let isBtnDisabled = false;
fs.appendFileSync("results.csv",`Title,Price,Release date,\n`,(err) => {if (err) {console.log(err);}});
while(!isBtnDisabled){
let prevurl = page.url();
await Promise.all([
page.click("li.pagination-action.pagination-action-next > a"),
await page.waitForSelector("li.pagination-action.pagination-action-next", { visible: true }),
await page.waitForNavigation({
waitUntil: 'networkidle2',
}),
]);
if(prevurl != page.url()){
console.log(page.url());
const titles = await page.evaluate(() => {
return Array.from(document.querySelectorAll("div.p__main > div > h3")).map(x=>x.textContent)
});
const price = await page.evaluate(() => {
return Array.from(document.querySelectorAll("div.p__footer > div.p__price-merchants > a > div")).map(x=>x.textContent)
});
const release_date = await page.evaluate(() => {
return Array.from(document.querySelectorAll("div.p__main > div.p__meta > div")).map(x=>x.textContent)
});
for(const title in titles){
if(titles[title]==null){
titles[title]="-";
}
if(price[title]==null){
price[title]="-";
}
if(release_date[title]==null){
release_date[title]="-";
}else{
release_date[title]=release_date[title].slice(0,4);
}
fs.appendFileSync(
"results.csv",`${titles[title]},${price[title].replace(/,/g, ".")},${release_date[title]},\n`,
(err) => {
if (err) {
console.log(err);
}
}
);
}
}
}
await browser.close();
})();
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Farm;
class FarmController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$farms = Farm::all();
return response()->json([
'farms' => $farms
]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data = $request->all();
$farm = Farm::create($data);
return response()->json([
'farm' => $farm
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$farm = Farm::find($id);
return response()->json([
'farm' => $farm
]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$data = $request->all();
$farm = Farm::find($id);
$farm->update($data);
return response()->json([
'farm' => $farm
]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Farm::delete($id);
return response()->json([
'ok'
]);
}
}
|
package grpc
import (
"context"
"log"
"math"
"net"
"time"
"protos/payment"
commonsGrpc "github.com/eggybytes/events/go/commons/grpc"
"github.com/eggybytes/events/go/commons/serviceregistry"
"github.com/eggybytes/events/go/services/payment/logic"
"google.golang.org/grpc"
)
// Server provides a gRPC API to the payment service
type Server struct {
*logic.Logic
Grpc *grpc.Server
}
// New creates a new gRPC server instance with the provided Logic
func New(l *logic.Logic) *Server {
opts := []grpc.ServerOption{
grpc.MaxConcurrentStreams(math.MaxUint32),
}
return &Server{
Logic: l,
Grpc: grpc.NewServer(opts...),
}
}
// ServeOnConn creates a new gRPC server and binds it to the provided network connection listener
func (s *Server) ServeOnConn(l net.Listener) error {
log.Printf("[payment-api gRPC] starting on %s", l.Addr().String())
payment.RegisterPaymentServiceServer(s.Grpc, s)
err := s.Grpc.Serve(l)
if err != nil {
log.Println("[payment-api gRPC] exit error: ", err)
return err
}
return nil
}
// Serve creates a new gRPC server and makes it start listening for traffic on the
// default port
func (s *Server) Serve() error {
lis, err := net.Listen("tcp", commonsGrpc.ListenAddr(serviceregistry.PaymentServiceGrpcPort))
if err != nil {
return err
}
return s.ServeOnConn(lis)
}
// Run starts the Payment server
func (s *Server) Run() error {
return s.Serve()
}
// Stop gracefully shuts down the Payment server and drains connections
func (s *Server) Stop() error {
log.Println("[payment-api gRPC] shutting down server...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
done := make(chan struct{})
go func() {
s.Grpc.GracefulStop()
close(done)
}()
select {
case <-ctx.Done():
log.Println("[payment-api gRPC] context timeout expired, forcing shutdown")
case <-done:
}
log.Println("[payment-api gRPC] shutdown complete")
return nil
}
|
"use client";
import styled from "styled-components";
export const StyledBlogCard = styled.div`
border-radius: 0.5rem;
overflow: hidden;
box-shadow: rgba(0, 0, 0, 0.05) 0px 0px 0px 1px;
height: 100%;
`;
export const ThumbnailWrapper = styled.div`
aspect-ratio: 16 / 7;
& .image-container {
height: 100%;
position: relative;
width: 100%;
background-color: ${(props) => props.theme.colors.white};
cursor: pointer;
transition: all 200ms;
&:hover {
transform: scale(1.02);
}
}
`;
export const Flex = styled.div`
display: flex;
gap: 1rem;
align-items: center;
justify-content: space-between;
`;
export const Chip = styled.div`
color: ${(props) => props.theme.colors.primary};
border-radius: 1rem;
font-size: 1rem;
font-weight: ${(props) => props.theme.fontWeight.medium};
text-transform: uppercase;
`;
export const ContentWrapper = styled.div`
padding: 1rem;
`;
export const Title = styled.h3`
font-size: 1.2rem;
margin: 1rem 0;
color: ${(props) => props.theme.colors.dark};
@media (min-width: ${(props) => props.theme.breakpoints.md}px) {
font-size: 1.5rem;
}
`;
export const Description = styled.div`
font-size: 0.9rem;
margin-top: 1rem;
font-weight: ${(props) => props.theme.fontWeight.regular};
color: #22222280;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
line-height: 150%;
@media (min-width: ${(props) => props.theme.breakpoints.md}px) {
font-size: 1rem;
}
`;
export const DateTime = styled(Description)`
margin-top: 0;
`;
|
//
// ContentView.swift
// HotProspects
//
// Created by Kevin Ngo on 2020-02-20.
// Copyright © 2020 Kevin Ngo. All rights reserved.
//
import SwiftUI
import UserNotifications
import SamplePackage
struct ContentView: View {
var prospects = Prospects()
var body: some View {
TabView {
//show every person you've met
ProspectsView(filter: .none)
.tabItem {
Image(systemName: "person.3")
Text("Everyone")
}
//show people you have contacted
ProspectsView(filter: .contacted)
.tabItem {
Image(systemName: "checkmark.circle")
Text("Contacted")
}
//show people you haven't contacted
ProspectsView(filter: .uncontacted)
.tabItem {
Image(systemName: "questionmark.diamond")
Text("Uncontacted")
}
MeView()
.tabItem {
Image(systemName: "person.crop.square")
Text("Me")
}
}.environmentObject(prospects)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
package com.mockito.tescases;
import com.mockito.test.exception.EmailServiceException;
import com.mockito.test.exception.UserServiceException;
import com.mockito.test.model.User;
import com.mockito.test.repository.UserRepository;
import com.mockito.test.service.EmailNotificationService;
import com.mockito.test.service.UserServiceImpl;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class) //Extending Mockito
public class UserServiceTest {
@InjectMocks
UserServiceImpl userServiceImpl;
@Mock
UserRepository userRepository;
@Mock
EmailNotificationService emailNotificationService;
String firstName;
String lastName;
String email;
String password;
String repeatPassword;
@BeforeEach
void init() {
//userService = new UserServiceImpl(userRepository); //Manually creating UserService obj
firstName = "Lishakar";
lastName = "Kumar";
email = "test@test.com";
password = "12345678";
repeatPassword = "12345678";
}
@Test
public void createNewUser() throws UserServiceException {
//Arrange
when(userRepository.saveUser(any(User.class))).thenReturn(true); //Stubbing and return true
//Actual Parameter
User userObj = userServiceImpl.createUser(firstName,lastName,email,password,repeatPassword);
System.out.println(userObj.toString());
//Assert
Assertions.assertEquals(userObj.getFirstName(),firstName); //This will not execute because we returned true
//Verify the number of times mock method getting called
Mockito.verify(userRepository, times(1)).saveUser(any(User.class));// This is a one seperate testcase
}
@Test
public void testCreateUser_whenSaveUser_throwsException_ThenThrowsUserServiceException() throws UserServiceException {
when(userRepository.saveUser(any(User.class))).thenThrow(RuntimeException.class);
Assertions.assertThrows(UserServiceException.class, () -> {
userServiceImpl.createUser(firstName, lastName, email, password, repeatPassword);
});
}
@Test
public void tesCreateUser_whenEmailServiceTrownException_throwUserServiceException()
{
//Arrange
when(userRepository.saveUser(any(User.class))).thenReturn(true); //Stubbing and return true
//when(emailNotificationService.sendEmailToUser(any(User.class)))
//This below is for throwing Exception to void method
doThrow(EmailServiceException.class).when(emailNotificationService).sendEmailToUser(any(User.class));
//Do nothing when method is called
doNothing().when(emailNotificationService).sendEmailToUser(any(User.class));
//Act & Assert
Assertions.assertThrows(UserServiceException.class,()->{
userServiceImpl.createUser(firstName,lastName,email,password,repeatPassword);
},"Should have thrown UserServiceException instead");
//Verify how many times sendEmail method is getting called
verify(emailNotificationService,times(1)).sendEmailToUser(any(User.class));
}
@Test
public void testCallRealMethod() throws UserServiceException {
//Arrange
when(userRepository.saveUser(any(User.class))).thenReturn(true); //Stubbing and return true
//Calling the original method
doCallRealMethod().when(emailNotificationService).sendEmailToUser(any(User.class));
//Act
userServiceImpl.createUser(firstName,lastName,email,password,repeatPassword);
//Assert
verify(emailNotificationService,times(1)).sendEmailToUser(any(User.class));
}
}
|
import { Sequelize } from "sequelize-typescript";
import { TransactionModel } from "../repository/transaction.model";
import { TransactionRepository } from "../repository/transaction.repository";
import { ProcessPaymentUseCase } from "../usecase/process-payment/process-payment.usecase";
import { PaymentFacade } from "./payment.facade";
describe('PaymentFacade Test', () => {
let sequelize: Sequelize;
beforeEach(async () => {
sequelize = new Sequelize({
dialect: 'sqlite',
storage: ':memory:',
logging: false,
sync: { force: true },
});
sequelize.addModels([TransactionModel]);
await sequelize.sync();
});
afterEach(async () => {
await sequelize.close();
});
it('should create a transaction', async () => {
const transactionRepository = new TransactionRepository();
const processPaymentUseCase = new ProcessPaymentUseCase(transactionRepository);
const paymentFacade = new PaymentFacade({
processPaymentUseCase: processPaymentUseCase
});
const input = {
orderId: '1',
amount: 100
};
const result = await paymentFacade.process(input);
expect(result.transactionId).toBeDefined();
expect(result.orderId).toBe(input.orderId);
expect(result.amount).toBe(input.amount);
expect(result.status).toBe('approved');
});
});
|
package com.chris.searchservice.controller;
import com.chris.common.service.elasticsearch.ElasticProductInfoService;
import com.chris.data.dto.PaginationResult;
import com.chris.data.dto.ResponseData;
import com.chris.data.dto.product.res.ProductDetailDTO;
import com.chris.data.elasticsearch.ProductInfo;
import com.chris.data.entity.product.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.StringQuery;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/product")
public class ProductInfoController extends BaseController {
@Autowired
private ElasticProductInfoService productInfoService;
@GetMapping("/search")
public ResponseEntity<?> search(
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "page_size", defaultValue = "10") int pageSize,
@RequestParam(name = "sort", defaultValue = "") String sort,
@RequestParam(name = "keyword", defaultValue = "") String keyword,
@RequestParam(name = "rating", defaultValue = "0") int rating,
@RequestParam(name = "category_id", defaultValue = "0") long categoryId,
@RequestParam(name = "price", defaultValue = "0") String price,
@RequestParam(name = "seller_id", defaultValue = "0") long sellerId
) {
ResponseData<PaginationResult<ProductInfo>> response = new ResponseData<>();
// PageRequest pageRequest = pageRequest(sort, page, pageSize);
PageRequest pageRequest = PageRequest.of(page, pageSize);
PaginationResult<ProductInfo> result = productInfoService.searchByCustomer(keyword, rating, categoryId, price, pageRequest, sort);
response.initData(result);
return new ResponseEntity<>(response, HttpStatus.OK);
}
@GetMapping("/full-search")
public ResponseEntity<?> sellerSearch(
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "page_size", defaultValue = "10") int pageSize,
@RequestParam(name = "sort", defaultValue = "id") String sort,
@RequestParam(name = "keyword", defaultValue = "") String keyword,
@RequestParam(name = "category_id", defaultValue = "0") long categoryId,
@RequestParam(name = "price", defaultValue = "0") String price,
@RequestParam(name = "status", defaultValue = "ALL") String status
) {
ResponseData<PaginationResult<ProductInfo>> response = new ResponseData<>();
PageRequest pageRequest = pageRequest(sort, page, pageSize);
PaginationResult<ProductInfo> result = productInfoService.searchBySeller(keyword, status, categoryId, price, pageRequest);
response.initData(result);
return new ResponseEntity<>(response, HttpStatus.OK);
}
@GetMapping("/admin-search")
public ResponseEntity<?> adminSearch(
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "page_size", defaultValue = "10") int pageSize,
@RequestParam(name = "sort", defaultValue = "id") String sort,
@RequestParam(name = "keyword", defaultValue = "") String keyword,
@RequestParam(name = "category_id", defaultValue = "0") long categoryId,
@RequestParam(name = "price", defaultValue = "0") String price,
@RequestParam(name = "status", defaultValue = "ALL") String status
) {
ResponseData<PaginationResult<ProductInfo>> response = new ResponseData<>();
PageRequest pageRequest = pageRequest(sort, page, pageSize);
PaginationResult<ProductInfo> result = productInfoService.searchByAdmin(keyword, status, categoryId, price, pageRequest);
response.initData(result);
return new ResponseEntity<>(response, HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<?> findById(@PathVariable(name = "id") long id) {
ResponseData<ProductInfo> response = new ResponseData<>();
ProductInfo product = productInfoService.findById(id);
response.initData(product);
response.success();
return new ResponseEntity<>(response, HttpStatus.OK);
}
}
|
// Copyright 2022 "Holloway" Chew, Kean Ho <kean.ho.chew@zoralab.com>
// Copyright 2022 ZORALab Enterprise <tech@zoralab.com>
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
package hestiaSTRING
import (
"hestia/hestiaERROR"
"hestia/hestiaIO/hestiaINTERNAL/hestiaMATH"
"hestia/hestiaTESTING"
"testing"
)
func Test_SN_ParseUINT(t *testing.T) {
scenarios := test_cases_SN_ParseNUMBER()
for i, s := range scenarios {
s.ID = uint64(i)
s.Name = "hestiaSTRING/SN_ParseUINT API"
s.Description = `
test hestiaSTRING/SN_ParseUINT is able to process the given string under the
following conditions.
`
// prepare
subject := generate_UINT_string(s)
hestiaTESTING.Log(s,
hestiaTESTING.Format("Given Subject : '%s'", subject))
base := create_base(s)
hestiaTESTING.Log(s,
hestiaTESTING.Format("Given Base : %d", base))
sizes := create_sizes(s)
hestiaTESTING.Log(s,
hestiaTESTING.Format("Given Sizes : %d", sizes))
// test
var output uint64
panick := ""
err := hestiaERROR.OK
_panick := hestiaTESTING.Exec(func() any {
output, err = SN_ParseUINT(subject, base, sizes)
return ""
})
panick, _ = _panick.(string)
hestiaTESTING.Log(s,
hestiaTESTING.Format("Got Output : %v", output))
hestiaTESTING.Log(s,
hestiaTESTING.Format("Got Error : %v", err))
hestiaTESTING.Log(s,
hestiaTESTING.Format("Got Panick : '%v'", panick))
// assert
hestiaTESTING.Conclude(s, hestiaTESTING.VERDICT_PASS)
if !assert_SN_ParseUINT_panick(panick) {
hestiaTESTING.Conclude(s, hestiaTESTING.VERDICT_FAIL)
hestiaTESTING.Log(s, hestiaTESTING.Format("Failed by panick!"))
t.Fail()
}
if !assert_SN_ParseUINT_output(s, output) {
hestiaTESTING.Conclude(s, hestiaTESTING.VERDICT_FAIL)
hestiaTESTING.Log(s, hestiaTESTING.Format("Failed by output!"))
t.Fail()
}
if !assert_SN_ParseUINT_error(s, err) {
hestiaTESTING.Conclude(s, hestiaTESTING.VERDICT_FAIL)
hestiaTESTING.Log(s, hestiaTESTING.Format("Failed by error!"))
t.Fail()
}
// report
t.Logf("%v", hestiaTESTING.ToString(s))
}
}
func assert_SN_ParseUINT_panick(panick string) bool {
return panick == ""
}
func assert_SN_ParseUINT_error(s *hestiaTESTING.Scenario, err hestiaERROR.Error) bool {
switch {
case hestiaTESTING.HasCondition(s, cond_PARTIAL_NORMAL):
return err != hestiaERROR.OK
case hestiaTESTING.HasCondition(s, cond_RESIZE_65):
return err != hestiaERROR.OK
case hestiaTESTING.HasCondition(s, cond_NEGATIVE):
return err != hestiaERROR.OK
case hestiaTESTING.HasCondition(s, cond_VALUE_NUMBER):
switch {
case hestiaTESTING.HasCondition(s, cond_BROKEN):
return err != hestiaERROR.OK
default:
return err == hestiaERROR.OK
}
default:
return err == hestiaERROR.OK
}
}
func assert_SN_ParseUINT_output(s *hestiaTESTING.Scenario, out uint64) bool {
switch {
case hestiaTESTING.HasCondition(s, cond_PARTIAL_NORMAL):
return out == 0 // error raised
case hestiaTESTING.HasCondition(s, cond_NEGATIVE):
return out == 0 // error raised
case hestiaTESTING.HasCondition(s, cond_FLOAT_NAN):
return out == 0 // error raised
case hestiaTESTING.HasCondition(s, cond_FLOAT_INF_POSITIVE):
return out == 0 // error raised
case hestiaTESTING.HasCondition(s, cond_FLOAT_INF_NEGATIVE):
return out == 0 // error raised
case hestiaTESTING.HasCondition(s, cond_VALUE_NUMBER):
switch {
case hestiaTESTING.HasCondition(s, cond_BROKEN):
return out == 0 // error raised
default:
switch {
case hestiaTESTING.HasCondition(s, cond_RESIZE_0):
return out == 0
case hestiaTESTING.HasCondition(s, cond_RESIZE_2):
return out == 3
case hestiaTESTING.HasCondition(s, cond_RESIZE_5):
return out == 31
case hestiaTESTING.HasCondition(s, cond_RESIZE_8):
return out == 255
case hestiaTESTING.HasCondition(s, cond_RESIZE_10):
return out == 1023
case hestiaTESTING.HasCondition(s, cond_RESIZE_12):
return out == 4095
case hestiaTESTING.HasCondition(s, cond_RESIZE_16):
return out == 65535
case hestiaTESTING.HasCondition(s, cond_RESIZE_22):
return out == 4194303
case hestiaTESTING.HasCondition(s, cond_RESIZE_36):
return out == 68719476735
case hestiaTESTING.HasCondition(s, cond_RESIZE_65):
return out == 0 // error raised
default:
return out == hestiaMATH.MAX_UINT64
}
}
}
switch {
case hestiaTESTING.HasCondition(s, cond_BASE_2):
return out == 10
case hestiaTESTING.HasCondition(s, cond_BASE_5):
return out == 194
case hestiaTESTING.HasCondition(s, cond_BASE_8):
return out == 668
case hestiaTESTING.HasCondition(s, cond_BASE_10):
return out == 1234
case hestiaTESTING.HasCondition(s, cond_BASE_12):
return out == 2056
case hestiaTESTING.HasCondition(s, cond_BASE_16):
return out == 43981
case hestiaTESTING.HasCondition(s, cond_BASE_22):
return out == 11686
case hestiaTESTING.HasCondition(s, cond_BASE_36):
return out == 49360
default:
return out == 0 // unknown case - fail it
}
}
func generate_UINT_string(s *hestiaTESTING.Scenario) (subject string) {
if hestiaTESTING.HasCondition(s, cond_VALUE_NUMBER) {
return configure_uint64_minmax_string(s)
}
if hestiaTESTING.HasCondition(s, cond_NEGATIVE) {
subject = "-"
}
switch {
case hestiaTESTING.HasCondition(s, cond_ROUND_NORMAL):
switch {
case hestiaTESTING.HasCondition(s, cond_BASE_2):
subject += "1010"
case hestiaTESTING.HasCondition(s, cond_BASE_16):
subject += "ABCD"
default:
subject += "1234"
}
case hestiaTESTING.HasCondition(s, cond_ROUND_ZERO):
subject = "0"
default:
}
switch {
case hestiaTESTING.HasCondition(s, cond_PARTIAL_NORMAL):
subject += ".11001"
case hestiaTESTING.HasCondition(s, cond_PARTIAL_ZERO):
// do nothing - exactly what we want as decimaless
default:
subject += ".0"
}
return subject
}
func configure_uint64_minmax_string(s *hestiaTESTING.Scenario) (subject string) {
if hestiaTESTING.HasCondition(s, cond_NEGATIVE) {
subject = "-"
}
switch {
case hestiaTESTING.HasCondition(s, cond_BROKEN):
subject += string_uint64_max
default:
subject += string_uint64_max_broken
}
return subject
}
|
<?xml version="1.0" encoding="UTF-8" ?>
<!--********************************************************************
© 2016–2023 Jeremy Sylvestre
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A
copy of the license is included in the appendix entitled “GNU Free
Documentation License” that appears in the output document of this
PreTeXt source code. All trademarks™ are the registered® marks of their
respective owners.
*********************************************************************-->
<worksheet xml:id="worksheet-sys-diff-eq">
<title>Discovery guide</title>
<activity xml:id="activity-sys-diff-eq-one-var">
<task>
<p> Verify that <m>y(t) = 5 e^{-2t}</m> solves the differential equation <m>\dydt = -2 y(t)</m>. </p>
<p>
<em>Note:</em> Remember that <em>verifying</em> a function is a solution to a differential equation does not require you <em>solve</em> the differential equation <mdash />
you just need to verify that left-hand and right-hand sides evaluate to the same result when the proposed solution function is substituted.
</p>
<p> What is the initial value of the solution function? </p>
</task>
<task xml:id="activity-sys-diff-eq-one-var-pattern"><p>
Remind yourself of the pattern:
the general solution to <m>\dydt = k y</m> is <m>y(t) = <fillin characters="30" /></m>.
</p></task>
</activity>
<activity xml:id="activity-sys-diff-eq-two-vars-example">
<introduction><p>
Consider the following <term>coupled system of linear differential equations</term>:
<me>
\left\{\begin{array}{rcrcr}
\dxdt \amp = \amp 5 x(t) \amp - \amp 6 y(t) \text{,} \\
\dydt \amp = \amp 3 x(t) \amp - \amp 4 y(t) \text{.}
\end{array}\right.
</me>
</p></introduction>
<task>
<statement>
<p>
Suppose we create new functions
<me>
\left\{\begin{array}{rcrcr}
w(t) \amp = \amp - x(t) \amp + \amp y(t) \text{,} \\
z(t) \amp = \amp x(t) \amp - \amp 2 y(t) \text{,}
\end{array}\right.
</me>
out of the old.
Create a new system of differential equations in
<m>w(t), w'(t), z(t), z'(t)</m>.
</p><p>
What happened?
</p>
</statement>
<hint><p>
Differentiate the expression for <m>w(t)</m> to get a formula for <m>w'(t)</m> in terms of <m>x'(t)</m> and <m>y'(t)</m>.
Then substitute the expressions for <m>x'(t)</m> and <m>y'(t)</m> from the original differential equations into your expression for <m>w'(t)</m>.
Simplify, and then see if you can relate what you have back to the change-of-variable expressions for <m>w(t)</m> and <m>z(t)</m>.
Then repeat for <m>z(t)</m>.
</p></hint>
</task>
<task><p>
Now use the pattern from
<xref ref="activity-sys-diff-eq-one-var-pattern" />
to solve the simplified system in the new variables <m>w(t), z(t)</m>.
</p></task>
<task xml:id="activity-sys-diff-eq-two-vars-example-change-var-back">
<p>
If we want to convert these solutions for <m>w(t), z(t)</m> to solutions to for <m>x(t),y(t)</m>,
we'll need to reverse the change of variables.
That is, we'll need to solve the system
<me>
\left\{\begin{array}{rcrcr}
- x \amp + \amp y \amp = \amp w \text{,} \\
x \amp - \amp 2 y \amp = \amp z \text{,}
\end{array}\right.
</me>
for <m>x</m> and <m>y</m>.
</p><p>
Wait!
The pattern of the equations above looks familiar <ellipsis />
Perhaps we could use linear algebra to solve them.
(And maybe use matrix inversion to solve,
instead of row reducing.)
</p><p>
Once you've solved the reverse change of variables,
express the solutions for <m>x(t)</m> and <m>y(t)</m> as combinations of the solutions for <m>w(t)</m> and <m>z(t)</m>.
</p>
</task>
<task>
<p>
<xref ref="activity-sys-diff-eq-two-vars-example-change-var-back" text="type-local" />
demonstrated that the linear change-of-variable equations could be written in matrix form:
<me>
\begin{bmatrix} w \\ z \end{bmatrix}
= \begin{bmatrix}
<fillin characters="2" /> \amp <fillin characters="2" /> \\
<fillin characters="2" /> \amp <fillin characters="2" />
\end{bmatrix}
\begin{bmatrix} x \\ y \end{bmatrix}
</me>.
</p><p>
But the original system of differential equations involving <m>x(t),y(t)</m> also looks linear.
Can you write that differential system in terms of matrix multiplication as well?
One side of your matrix equation should involve a <m>2 \times 2</m> matrix times
<m>\left[\begin{smallmatrix} x \\ y \end{smallmatrix}\right]</m>.
Can you convert the other <q>differential</q> side of the matrix equation into an expression involving
<m>\left[\begin{smallmatrix} x \\ y \end{smallmatrix}\right]</m>?
</p><p>
Can you also turn your simplified system involving <m>w(t),w'(t),z'(t),z(t)</m> into a matrix equation?
What do you notice about coefficient matrix in this system?
</p>
</task>
<task><p>
So we have
<ul>
<li>
a coefficient matrix relating
<m>\ddt \left[\begin{smallmatrix} x \\ y \end{smallmatrix}\right] </m>
to
<m>\left[\begin{smallmatrix} x \\ y \end{smallmatrix}\right] </m>,
</li>
<li>
a coefficient matrix relating
<m>\ddt \left[\begin{smallmatrix} w \\ z \end{smallmatrix}\right] </m>
to
<m>\left[\begin{smallmatrix} w \\ z \end{smallmatrix}\right] </m>,
and
</li>
<li>
a coefficient matrix relating coordinate systems
<m>\left[\begin{smallmatrix} w \\ z \end{smallmatrix}\right] </m>
and
<m>\left[\begin{smallmatrix} x \\ y \end{smallmatrix}\right] </m>.
</li>
</ul>
What recent topic that we've been studying do you think relates these three coefficient matrices together?
</p></task>
</activity>
<activity><p>
Work out the pattern of <xref ref="activity-sys-diff-eq-two-vars-example" />.
Suppose matrices <m>A,B</m> are similar via transition matrix <m>P</m> in the similarity relation <m>\inv{P}AP = B</m>,
and that <m>y_1(t), y_2(t), \dotsc, y_n(t)</m> are functions that satisfy the differential matrix equation
<md><mrow>
\ddt \uvec{y}(t) \amp = A \uvec{y}(t) \text{,} \amp
\text{where } \uvec{y}(t) \amp = \begin{bmatrix} y_1(t) \\ y_2(t) \\ \vdots \\ y_n(t) \end{bmatrix} \text{.}
</mrow></md>
Substitute the similarity relation into the differential matrix equation and rearrange to get a new differential equation
<me> \ddt \uvec{w}(t) = B \uvec{w}(t) </me>,
where <m>\uvec{w}(t)</m> is some change of variables from <m>\uvec{y}(t)</m>.
Be explicit about how your change of variables relates <m>\uvec{y}(t)</m> and <m>\uvec{w}(t)</m>.
</p></activity>
<activity>
<introduction><p>
<xref ref="activity-sys-diff-eq-two-vars-example" />
demonstrated that if a differential matrix equation
<m> \ddt \uvec{y}(t) = A \uvec{y}(t) </m>
has a diagonalizable coefficient matrix <m>A</m>,
then a change of variables via a transition matrix <m>P</m> that diagonalizes <m>A</m> will <term>decouple</term> the underlying system of equations,
leaving simple proportional differential equations that are solved by exponential functions <m>w_j(t) = c_j e^{k_j t}</m>.
</p></introduction>
<task><p>
What do the constants <m>k_j</m> represent relative to the diagonal coefficient matrix <m>\inv{P} A P</m>?
What do they represent relative to the original coefficient matrix <m>A</m>?
</p></task>
<task><p>
Suppose you were given a collection of initial values
<me>
\left\{\begin{array}{rcr}
y_1(0) \amp = \amp a_1 \text{,} \\
y_2(0) \amp = \amp a_2 \text{,} \\
\amp \vdots \\
y_n(0) \amp = \amp a_n \text{.}
\end{array}\right.
</me>
We can collect these into an initial vector
<me> \uvec{y}(0) = \begin{bmatrix} a_1 \\ a_2 \\ \vdots \\ a_n \end{bmatrix} </me>.
How does this vector relate to the initial values for the <m>w_j(t)</m> solution functions?
</p></task>
</activity>
<activity xml:id="activity-sys-diff-eq-second-order">
<introduction>
<p>
The equation <me> y''(t) + 5 y'(t) + 4 y(t) = 0 </me>
is an example of a homogeneous, linear, second-order differential equation.
</p>
<p>
We will try to use vector/matrix methods to solve this equation.
The vector of unknown functions we will use is
<me> \mathbf{y}(t) = \begin{bmatrix} y(t) \\ y'(t) \end{bmatrix} </me>.
So, effectively we are setting <m>y_1(t) = y(t)</m> and <m>y_2(t) = y'(t)</m>.
</p>
</introduction>
<task xml:id="activity-sys-diff-eq-second-order-set-up">
<statement><p>
Let's set up our system of linear differential equations.
<md>
<mrow> y_1'(t) \amp = <fillin characters="3" /> y_1(t) + <fillin characters="3" /> y_2(t) </mrow>
<mrow> y_2'(t) \amp = <fillin characters="3" /> y_1(t) + <fillin characters="3" /> y_2(t) </mrow>
</md>
</p></statement>
<hint><p>
You can obtain the first equation by combining our definitions of <m>y_1(t)</m> and <m>y_2(t)</m>.
For the second equation, use the original differential equation and the fact that
<me> y_2'(t) = y_1''(t) </me>.
</p></hint>
</task>
<task xml:id="activity-sys-diff-eq-second-order-solve"><p>
Solve the system from <xref ref="activity-sys-diff-eq-second-order-set-up" text="type-local" />
by diagonalizing the coefficient matrix to decouple the system.
</p></task>
<task>
<p>
As part of <xref ref="activity-sys-diff-eq-second-order-solve" text="type-local" />,
you should have computed the characteristic polynomial of the coefficient matrix.
</p>
<p>
Compare this coefficient polynomial with the original second-order differential equation.
Do you notice anything special?
</p>
</task>
</activity>
</worksheet>
|
note
description : "Facilities for programming in Vision2. %
%Your Class should inherit from the class to use the facilities"
legal: "See notice at end of class."
status: "See notice at end of class."
author : "Arnaud PICHERY [ aranud@mail.dotcom.fr ]"
date : "$Date$"
revision : "$Revision$"
class
EB_VISION2_FACILITIES
inherit
EB_CONSTANTS
feature -- Basic operations
extend_no_expand (container: EV_BOX; widget: EV_WIDGET)
-- Add `widget' to `container' and make `widget' not expandable
do
container.extend (widget)
container.disable_item_expand (widget)
end
extend_with_size (container: EV_BOX; widget: EV_WIDGET; a_width, a_height: INTEGER)
-- Add `widget' to `container' and make `widget' not expandable
-- Set the minimum size of `widget' to (`a_width',`a_height')
do
widget.set_minimum_size (a_width, a_height)
container.extend (widget)
container.disable_item_expand (widget)
end
extend_button (container: EV_BOX; button: EV_BUTTON)
-- Add `widget' to `container' and make `widget' not expandable
-- Set the minimum size of `widget' to the default size for buttons
do
Layout_constants.set_default_width_for_button (button)
container.extend (button)
container.disable_item_expand (button)
end
adjust_sensitivity (a_widget: EV_WIDGET; a_sensitive: BOOLEAN)
-- Enable/disable sensitivity of given widget according to `a_sensitive'.
require
not_a_widget_destroyed: not a_widget.is_destroyed
do
if a_sensitive then
if not a_widget.is_sensitive then
a_widget.enable_sensitive
end
else
if a_widget.is_sensitive then
a_widget.disable_sensitive
end
end
end
feature -- Useful query
parent_window_from (w: EV_WIDGET): EV_WINDOW
-- Top parent Window containing `w'.
require
w_not_void: w /= Void
do
Result ?= w
if Result = Void and w.parent /= Void then
Result := parent_window_from (w.parent)
end
end
note
copyright: "Copyright (c) 1984-2010, Eiffel Software"
license: "GPL version 2 (see http://www.eiffel.com/licensing/gpl.txt)"
licensing_options: "http://www.eiffel.com/licensing"
copying: "[
This file is part of Eiffel Software's Eiffel Development Environment.
Eiffel Software's Eiffel Development Environment 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, version 2 of the License
(available at the URL listed under "license" above).
Eiffel Software's Eiffel Development Environment 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 Eiffel Software's Eiffel Development
Environment; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
]"
source: "[
Eiffel Software
5949 Hollister Ave., Goleta, CA 93117 USA
Telephone 805-685-1006, Fax 805-685-6869
Website http://www.eiffel.com
Customer support http://support.eiffel.com
]"
end -- class EB_VISION2_FACILITIES
|
"""
Principiile Testarii:
1. Testarea arata prezenta defectelor, nu absenta lor
- Faptul ca nu exista bug-uri, nu inseamna ca ele nu exista deloc
2. Testarea timpurie (Eearly testing)
- Cu cat testarea incepe mai repede, cu atat posibilitatea de aparitie a bug-urilor este mai mica.
3. Testarea exhaustiva nu este posibila
- Adica nu este posibil sa testam toata functionalitatea si toate combinatiile valide si nevalide de testare.
4. Testarea este dependenta de context
- Riscul asociat fiecarui tip de aplicatie este diferit, prin urmare nu este suficient sa utilizezi aceeasi metoda,
tehnica, tip de testare pentru a testa toate tipurile de aplicatii.
5. Gruparea Defectelor (Clustering)
- In timpul tetarii, se poate intampla ca majoritatea bug-urilor sa fie legate de un numar mic de module dezvoltate
de catre developeri
6. Paradoxul pesticidelor (Pesticide Paradox)
- Principiul paradoxului pesticidelor spune ca, daca acelasi set de cazuri de testare sunt executate din nou si
din nou pe parcursul perioadei de test, autnci aceste seturi de teste nu sunt suficient de capabile sa identifice noi
defecte.
Se refera mai ales la cazurile cand re-testam un bug.
7. Absenta erorii este o aberatie
- Daca software-ul este testat complet si daca nu se gasesc defecte inainte de lansare, atunci putem spune ca
softwareul este 99% fara defecte.
Testarea de API vine in intampinarea principiului 2 al testarii - introducerea testarii cat mia devreme salveaza timp.
Cand ar putea sa fie utila testarea API ?
- Pentru a detecta defectele din testare cat mai devreme
- Ofera posibilitatea automatizarii (investesti mai mult la inceput sa dezvolti tetele automate, higher time cost,
dar nu mai consumi ulterior resurse in rularea testelor, prin reducerea unei persoane care practic ruleaza testele
manual)
- Asigura adaptabilitatea testarii in functie de platforma. De exemplu cu acelasi API poti testa o aplicatie care
ruleaza atat pe Windows cat si pe Linux, Android, IOS
- Este time efficient, eficienta timpului investit pentru ca API-urile pot sa fie folosite in testare fara sa fie
o interfata grafica (GUI) dezvoltat complet
Termeni utilizati in testarea API:
- Interoperabilitate este procesul care faciliteaza ca mai multe aplicatii sa comunice intre ele desi sunt instalate
pe diferite platforme (Windows,Linux, Android, IOS)
- Autenficare si autorizare. Exemplu: Daca am o pagina personala de facebook, atunci poate sa fie considerat faptul ca
sunt si autorizat sa vad pozele personale.
- Endpoint. Este un termen foarte folosit si utilizat in orice request pe care il facem. Este URL-ul complet pe care
il apelam cand utilizam orice request.
- Idempotent/Indempotency este interactiunea client-server in care clientul indiferent de cate ori apeleaza
endpoint-ul serverul ii intoarce mereu acelasi raspuns.
Mecanisme de OAuth:
Este un standard de autorizare de tip open-standard si permite unui serviciu sa foloseasca alt serviciu fara sa mai
ceara detalii de autentificare (user si parola) ci doar pe baza unui token care este generat in momentul login-ului
apoi acel token este folosit pe tot parcursul interactiunii celor doua servicii
De ce este mai secure un token ?
- Nu trimiti un plain text user si parola -> mai putine contexte in care cineva neautorizat poate accesa serviciul
- Token are de regula un timp de expirare dupa care este necesara reautentificarea
- Dirverse tipuri de autorizare nu pot sa fie identificate prin token, administrator, moderator, user, etc.
- Token-ul este criptat cu un Key
Diferenta intre criptare si hashing:
A cripta inseamna a transformare un mesaj oarecare intr-un sir de caractere ce poate sa fie trimite in siguranta
mai departe. Pentru criptare se foloseste un key unic, daca ai keya unica pentru a cripta mesajul, il poti si decripta
cu aceeasi key. Rezulta ca este un proces reversibil
A hashui inseamna a transformare un mesaj oarecare intr-un sir de caractere, actiunea este ireversibila.
Exemplu, parola este salvata hasuit pe server iar cand cineva se autentifica atunci sistemul de autentificare
compara cele doua hash-uri
Pentru a definii body-ul corpul requestului de API avem doua tipuri de date. XML si JSON
Mic de studiu de caz:
JSON XML
JSON este un tip de data XML date un tip de data
JSON accepta: string, numere, boolean XML accepta doar stringuri
structura arborescente structura arborescenta
parcurgerea este mai lenta parcurgerea este mai rapida
Coduri de raspuns HTTP ( Status Codes HTTP )
- Status Codes sunt generate de catre Server ca raspuns al unui request dinspre client
- Compus din 3 cifre
- Impartite in 5 clase, prima cifra determina clasa din care fac parte:
1xx Informational - Rquestul a fost primit, continua procesarea
2xx Success - Requestul a fost receptionat cu success, inteles si acceptat ca format
3xx Redirect - Actiuni ulterioare trebuie procesate pentru a finaliza requestul cerut initial
4xx Eroare de client - Requestul contine o sintaxa gresita sau nu poate sa fie procesata
5xx Eroare de server - Serverul a esuat in procesa requestul primit
- ultimele doua cifre definesc semnificatia raspunsului. Cate un exemplu din fiecare categoria:
102 - Processing, Exemplu: Atunci cand trimit un alt request inainte si asteptam un raspuns, faptul ca intoarce
102 inseamna ca inca asteapta sa procese requestul initial. Practic, acest tip de mesaj informeaza
clientul ca request-ul lui NU a fost esuat, ci in continuare este procesat dar dureaza mai mult timp.
200 - OK - Raspunsul standard ca requestul a fost procesat. De regula intors dupa un request de tip GET
201 - Created - Request a fost procesat cu success, de regula intors dupa un POST
301 - Movdem Permanently - Atat acest request cat si cele viitoare sunt redirectionate catre alt endpoint.
401 - Unauthorized - Nu esti autorizat sa accesezi acel tip de endpoint.
404 - Not Found - Nu gaseste resursa specificata
503 - Service Unavailable - Serviciul nu este disponibil, poate aparea in urma unui crash al aplicatiei.
Modele principale de HTTP:
GET - Aceasta metoda este folosita pentru a prelua informatiile care sunt transmise de catre server folosind PUT sau POST.
Nu are un body, un corp, (JSON), Executia cu success a codului intoarce codul 200
POST - Aceasta metoda este folosita pentru a crea o inregistrare folosint un body (JSON). Execute cu success intoarce
codul 201
PUT - Aceasta metoda este folosita pentru update-ul unei inregistrari care este deja prezenta. Executia cu success
intoarce codul 200 sau 201.
PATCH - Aceasta metoda este folosita pentru a solicita modificarea doar anumitor parti din inregistrare, ca o
peticire. Executia cu success intoarce codul 200 sau 2-1.
DELETE - Aceasta metoda este folosita pentru a sterge inregistrarea. Executia cu success intaorce 200.
POSTMAN un HUI pentru trimiterea requesturilor si primirea raspunsurilor HTTP
"""
|
"""Utility used to transform swiss coordinate"""
# Source: https://www.swisstopo.admin.ch/en/transformation-calculation-services (see PDFs under "Documentation")
import math
class Topo(object):
'''
Topo class which is able to perform convertions between the
LV95 and WGS84 system.
'''
# Convert LV95(E,N) to WGS84
def LV95toWGS84(self, easting=None, northing=None):
# Convert the projection coordinates easting and northing in LV95
# into the civilian system (Bern = 0 / 0) and express in the unit [1000 km]
easting_p = (easting - 2600000) / 1000000
northing_p = (northing - 1200000) / 1000000
# calculate longitude lambda_wgs and latitude phi_wgs in the unit [10000"]
lambda_wgs_p = 2.6779094 + 4.728982 * easting_p \
+ 0.791484 * easting_p * northing_p \
+ 0.1306 * easting_p * pow(northing_p, 2) \
- 0.0436 * pow(easting_p, 3)
phi_wgs_p = 16.9023892 + 3.238272 * northing_p \
- 0.270978 * pow(easting_p, 2) \
- 0.002528 * pow(northing_p, 2) \
- 0.0447 * pow(easting_p, 2) * northing_p \
- 0.0140 * pow(northing_p, 3)
# convert longitude and latitude to the unit [°]
lambda_wgs = lambda_wgs_p * 100 / 36
phi_wgs = phi_wgs_p * 100 / 36
return [lambda_wgs, phi_wgs]
# Convert WGS84 to LV95 swiss projection coordinates
def WGS84toLV95(self, lat=None, long=None):
# Convert the ellipsoidal latitude and longitude into arcsecond ["]
wgs_phi = lat * 3600
wgs_lambda = long * 3600
# Calculate the auxilary values (difference of latitude and longitude relative to Bern in the unit [10000"])
phi_p = (wgs_phi - 169028.66) / 10000
lambda_p = (wgs_lambda - 26782.5) / 10000
# Calculate projection coordinates in LV95 (E, N)
east = 2600072.37 + 211455.93 * lambda_p \
- 10938.51 * lambda_p * phi_p \
- 0.36 * lambda_p * pow(phi_p, 2) \
- 44.54 * pow(lambda_p, 3)
north = 1200147.07 + 308807.95 * phi_p \
+ 3745.25 * pow(lambda_p, 2) \
+ 76.63 * pow(phi_p, 2) \
- 194.56 * pow(lambda_p, 2) * phi_p \
+ 119.79 * pow(phi_p, 3)
return [east, north]
# Convert decimal angle (° dec) to sexagesimal angle (dd.mmss,sss)
def DecToSexAngle(self, dec):
degrees = math.floor(dec)
minutes = (dec - degrees) * 60
whole_minutes = math.floor(minutes)
seconds = round((minutes - whole_minutes) * 60, 3)
return degrees + (whole_minutes / 100) + (seconds / 10000)
# Convert sexagesimal angle (dd.mmss,sss) to decimal angle (degrees)
def SexToDecAngle(self, dms):
degrees = math.floor(dms)
minutes = math.floor((dms - degrees) * 100)
seconds = round(((dms-degrees) * 10000) - (minutes *100), 3)
return degrees + (minutes / 60) + (seconds / 3600)
if __name__ == "__main__":
''' Example usage for the Topo class.'''
pass
|
using Vit.Framework.Input;
using Vit.Framework.Input.Events;
using Vit.Framework.Mathematics;
namespace Vit.Framework.TwoD.UI.Input.Events;
public abstract record PositionalUIEvent : UIEvent, IPositionalEvent {
public required Point2<float> EventPosition { get; init; }
}
public abstract record MovingPositionalUIEvent : PositionalUIEvent {
public required Point2<float> EventStartPosition { get; init; }
public required Point2<float> LastEventPosition { get; init; }
public Vector2<float> DeltaPosition => EventPosition - LastEventPosition;
}
/// <summary>
/// A cursor is now over this element. Needs to handle <see cref="HoveredEvent"/> to trigger.
/// </summary>
public record CursorEnteredEvent : PositionalUIEvent, INonPropagableEvent {
}
/// <summary>
/// A cursor is no longer over this element. Needs to handle <see cref="HoveredEvent"/> to trigger.
/// </summary>
public record CursorExitedEvent : PositionalUIEvent, INonPropagableEvent {
}
/// <summary>
/// A cursor moved while over this element.
/// </summary>
public record HoveredEvent : PositionalUIEvent {
}
/// <summary>
/// A cursor started holding down a button over this element. Needs to handle <see cref="HoveredEvent"/> to trigger.
/// </summary>
public record PressedEvent : PositionalUIEvent, ILoggableEvent, INonPropagableEvent {
public required CursorButton Button { get; init; }
}
/// <summary>
/// A cursor stopped holding down a button that was previously handled by <see cref="PressedEvent"/>.
/// </summary>
public record ReleasedEvent : PositionalUIEvent, ILoggableEvent, INonPropagableEvent {
public required CursorButton Button { get; init; }
}
/// <summary>
/// A cursor pressed and released a button over this element. Must have handled <see cref="PressedEvent"/> for this to trigger.
/// Handling <see cref="DragStartedEvent"/> will cause this event not to trigger.
/// </summary>
public record ClickedEvent : PositionalUIEvent, ILoggableEvent, INonPropagableEvent {
public required CursorButton Button { get; init; }
}
/// <summary>
/// A cursor pressed a button over this element and moved. Needs to either handle <see cref="PressedEvent"/> or fall through to trigger.
/// Handling this event will cause <see cref="ClickedEvent"/> not to trigger.
/// </summary>
public record DragStartedEvent : PositionalUIEvent, ILoggableEvent, IUpPropagableEvent {
public required CursorButton Button { get; init; }
}
/// <summary>
/// A cursor moved while dragging this element. Must have handled <see cref="DragStartedEvent"/> for this to trigger.
/// </summary>
public record DraggedEvent : MovingPositionalUIEvent, INonPropagableEvent {
public required CursorButton Button { get; init; }
}
/// <summary>
/// A cursor released a button while dragging this element. Must have handled <see cref="DragStartedEvent"/> for this to trigger.
/// </summary>
public record DragEndedEvent : MovingPositionalUIEvent, ILoggableEvent, INonPropagableEvent {
public required CursorButton Button { get; init; }
}
|
<template>
<BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" width="96%">
<BasicForm @register="registerForm" />
</BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form';
import { formSchema } from '../api/Idea.data';
import { saveOrUpdate } from '../api/Idea.api';
import dayjs from 'dayjs';
// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
//表单配置
const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
labelWidth: 150,
schemas: formSchema,
showActionButtonGroup: false,
autoFocusFirstItem: true,
autoSubmitOnEnter: true,
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
//重置表单
await resetFields();
setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
isUpdate.value = !!data?.isUpdate;
if (unref(isUpdate)) {
//表单赋值
await setFieldsValue({
...data.record,
});
} else {
//表单赋值
await setFieldsValue({
invalidTime: dayjs().add(364, 'days').format('YYYY-MM-DD HH:mm:ss'),
realInvalidTime: dayjs().add(364, 'days').format('YYYY-MM-DD HH:mm:ss'),
});
}
});
//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
//表单提交事件
async function handleSubmit(v) {
try {
let values = await validate();
setModalProps({ confirmLoading: true });
//提交表单
await saveOrUpdate(values, isUpdate.value);
//关闭弹窗
closeModal();
//刷新列表
emit('success', { isUpdate: isUpdate.value, values });
} finally {
setModalProps({ confirmLoading: false });
}
}
</script>
<style lang="less" scoped></style>
|
package ui
import (
"strings"
"github.com/SnareChops/nengine/bounds"
_input "github.com/SnareChops/nengine/input"
"github.com/SnareChops/nengine/types"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/inpututil"
)
type TextBox struct {
*bounds.Raw
input *_input.Input
keys []ebiten.Key
content string
cooldown int
repeating bool
focused bool
}
func (self *TextBox) Init(w, h int, input types.Input) *TextBox {
self.input = input.(*_input.Input)
self.Raw = new(bounds.Raw).Init(w, h)
return self
}
func (self *TextBox) SetContent(content string) {
self.content = content
}
func (self *TextBox) Content() string {
return self.content
}
func (self *TextBox) Focus() {
self.focused = true
}
func (self *TextBox) IsFocused() bool {
return self.focused
}
func (self *TextBox) Update(x, y, delta int) {
if self.input.IsInputCaptured() {
self.focused = false
return
}
if self.focused {
self.input.InputCapture()
// Detect click outside of textbox to lose focus
if !self.IsWithin(float64(x), float64(y)) && inpututil.IsMouseButtonJustPressed(ebiten.MouseButtonLeft) {
self.focused = false
self.input.InputUncapture()
return
}
// Handle backspace
self.cooldown -= delta
if ebiten.IsKeyPressed(ebiten.KeyBackspace) {
if self.cooldown <= 0 {
self.content = self.content[:len(self.content)-1]
self.repeating = true
if self.repeating {
self.cooldown = 100
} else {
self.cooldown = 500
}
}
return
} else {
self.cooldown = 0
self.repeating = false
}
// Handle keypresses
self.keys = inpututil.AppendJustPressedKeys(self.keys[:0])
for _, key := range self.keys {
if key == ebiten.KeySpace {
self.content += " "
continue
}
letter := ebiten.KeyName(key)
if ebiten.IsKeyPressed(ebiten.KeyShift) {
letter = keyToUpper(key, letter)
letter = strings.ToUpper(letter)
}
self.content += letter
}
} else {
// Detect click on textbox to set focus
if self.IsWithin(float64(x), float64(y)) && inpututil.IsMouseButtonJustPressed(ebiten.MouseButtonLeft) {
self.input.InputCapture()
self.focused = true
}
}
}
func keyToUpper(key ebiten.Key, letter string) string {
switch key {
case ebiten.KeyBackquote:
return "~"
case ebiten.KeyMinus:
return "_"
case ebiten.KeyEqual:
return "+"
case ebiten.KeyLeftBracket:
return "{"
case ebiten.KeyRightBracket:
return "}"
case ebiten.KeyBackslash:
return "|"
case ebiten.KeySemicolon:
return ":"
case ebiten.KeyApostrophe:
return "\""
case ebiten.KeyComma:
return "<"
case ebiten.KeyPeriod:
return ">"
case ebiten.KeySlash:
return "?"
case ebiten.Key1:
return "!"
case ebiten.Key2:
return "@"
case ebiten.Key3:
return "#"
case ebiten.Key4:
return "$"
case ebiten.Key5:
return "%"
case ebiten.Key6:
return "^"
case ebiten.Key7:
return "&"
case ebiten.Key8:
return "*"
case ebiten.Key9:
return "("
case ebiten.Key0:
return ")"
}
return strings.ToUpper(letter)
}
|
// strategy is an injectable class
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { UsersRepository } from './users.repository';
import { JwtPayload } from './types/jwt.payload.interface';
import { User } from './user.entity';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
// Get the user from the DB -> need depedency injection
constructor(
@InjectRepository(UsersRepository) private usersRepository: UsersRepository,
private configService: ConfigService,
) {
// Derived classes need to implment super() method
// The follow 2 options are required
// the secretkey used to verify the JWT
// and how it'll get the token
super({
secretOrKey: configService.get('JWT_SECRET_KEY'),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
});
}
// This method will be called by Passport and we can add our own logic here
async validate(payload: JwtPayload): Promise<User> {
const { username } = payload;
const user = await this.usersRepository.findOne({
where: {
username,
},
});
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
|
import express from "express";
import __dirname from "./util.js";
import mongoose from "mongoose";
import studentRouter from "./routes/students.router.js";
import courseRouter from "./routes/courses.router.js";
import viewRouter from "./routes/views.router.js";
import handlebars from "express-handlebars";
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.engine("handlebars", handlebars.engine());
app.set("views", __dirname + "/views");
app.set("view engine", "handlebars");
app.use(express.static(__dirname + "/public"));
app.use("/api/students", studentRouter);
app.use("/api/course", courseRouter);
app.use("/api/view", viewRouter);
const SERVER_PORT = 9090;
app.listen(9090, () => {
console.log("Servidor escuchando por el puerto: " + SERVER_PORT);
});
const connectMongoDB = async () => {
try {
await mongoose.connect(
"mongodb://localhost:27017/colegio?retryWrites=true&w=majority"
);
console.log("Conectado con exito a MongoDB usando Moongose.");
} catch (error) {
console.error("No se pudo conectar a la BD usando Moongose: " + error);
process.exit();
}
};
connectMongoDB();
|
import type { i18n } from "i18next";
export default function createLocaleRouteLoader(i18next: i18n) {
const locales = import.meta.glob<{ default: Record<string, any> }>(
"/src/modules/*/locales/index.ts",
{
eager: false,
}
);
const normalizedLocales = _mapKeys(locales, (_, key) => {
return _snakeCase(
key.replace(/\/src\/modules\/(.*?)\/locales\/index\.ts/g, "$1")
);
});
const loader: AppRouteLoaderFunction = async (_, route) => {
const moduleName = _snakeCase(route?.path?.split("/")[1]);
const moduleLocalesLoader =
moduleName in normalizedLocales
? normalizedLocales[moduleName]
: undefined;
if (moduleLocalesLoader) {
const { default: moduleLocales } = await moduleLocalesLoader();
for (const language in moduleLocales) {
if (Object.prototype.hasOwnProperty.call(moduleLocales, language)) {
const locale = moduleLocales[language];
i18next.addResourceBundle(language, moduleName, locale, true, false);
}
}
}
};
return loader;
}
|
<!doctype html>
<html lang="es" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Grupo Piñhero</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
<link rel="stylesheet" th:href="@{/css/estiloFormEntidad.css}">
</head>
<body>
<header th:replace="~{Fragments/header :: header}"></header>
<main>
<div class="container">
<div class="row mt-4">
<h1>Carga de Cuentas Contables</h1>
<form class="row g-3 needs-validation" th:action="@{/cuentas/__${action}__}" th:object="${cuenta}" method="post" autocomplete="off">
<input type="hidden" th:field="*{id}">
<div class="col-md-8">
<label for="descripcion" class="form-label">Descripcion: </label>
<input type="text" class="form-control" id="descripcion" th:field="*{descripcion}" placeholder="Ingese una descripcion" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4">
<label for="codigo" class="form-label">Codigo: </label>
<input type="number" class="form-control" id="codigo" th:field="*{codigo}">
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4">
<label for="ctaTotalizadora" class="form-label">Totalizadora: </label>
<select th:field="*{ctaTotalizadora}" id="ctaTotalizadora" class="form-select" aria-label="Seleccionar totalizadora" required>
<option selected value="">Seleccione Totalizadora</option>
<option th:each="xxx : ${listaTotalizadoras}" th:text="${xxx.descripcion}" th:value="${xxx.id}"></option>
</select>
</div>
<div class="col-md-4">
<label for="clasificacionCta" class="form-label">Clasificacion: </label>
<select th:field="*{clasificacionCta}" id="clasificacionCta" class="form-select" aria-label="Seleccionar clasificacion">
<option selected value="">Seleccione Clasificacion</option>
<option th:each="xxx : ${listaClasif}" th:text="${xxx.descripcion}" th:value="${xxx.id}"></option>
</select>
</div>
<div class="col-md-4">
<label for="moneda" class="form-label">Moneda: </label>
<select th:field="*{moneda}" id="moneda" class="form-select" aria-label="Seleccionar moneda" required>
<option selected value="">Seleccione Moneda</option>
<option th:each="xxx : ${listaMonedas}" th:text="${xxx.descripcion}" th:value="${xxx.id}"></option>
</select>
</div>
<div class="col-md-4">
<label for="impuestos" class="form-label">Impuestos: </label>
<select th:field="*{impuestos}" name="impuestos[]" size="4" multiple id="impuestos" class="form-select" aria-label="Seleccionar impuestos">
<option selected value="">No aplica</option>
<option th:each="xxx : ${listaImpuestos}" th:text="${xxx.descripcion}" th:value="${xxx.id}"></option>
</select>
</div>
<div class="col-12">
<button th:text="${action == 'create' ? 'Crear' : 'Actualizar'}" type="submit" class="btn btn-primary"></button>
</div>
</form>
</div>
</div>
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
<script th:src="@{/js/cambiarTema.js}"></script>
</body>
</html>
|
library(tidyverse)
mecha_table <- read.csv(file = 'MechaCar_mpg.csv', check.names = F, stringsAsFactors = F) #import Mecha csv
head(mecha_table)
lm(mpg ~ vehicle_length + vehicle_weight + spoiler_angle + ground_clearance + AWD, data=mecha_table) #mult linear regression model
summary(lm(mpg ~ vehicle_length + vehicle_weight + spoiler_angle + ground_clearance + AWD, data=mecha_table)) #generate stats
#Deliverable 2
mecha_table2 <- read.csv(file = 'Suspension_Coil.csv', check.names = F, stringsAsFactors = F) #import suspension coil csv
total_summary <- mecha_table2 %>% summarize(Mean=mean(PSI),Median=median(PSI),Variance=var(PSI), sd(PSI)) #create summary table with stats
lot_summary <- mecha_table2 %>% group_by(Manufacturing_Lot) %>% summarize(Mean=mean(PSI),Median=median(PSI),Variance=var(PSI), sd(PSI)) #create summary table by lot
#Deliverable 3
t.test((mecha_table2$PSI), mu=1500) #ttest for all lots
t.test(subset(mecha_table2, Manufacturing_Lot == "Lot1")$PSI, mu=1500)#ttest for each lot
t.test(subset(mecha_table2, Manufacturing_Lot == "Lot2")$PSI, mu=1500)
t.test(subset(mecha_table2, Manufacturing_Lot == "Lot3")$PSI, mu=1500)
|
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Plot, PlotStatus } from '@app/models/plot.model';
import { AppState } from '@app/store/app-state';
import { Store } from '@ngrx/store';
import { map, Observable, tap, filter, switchMap, combineLatest, Subject, takeUntil, withLatestFrom } from 'rxjs';
import * as fromPlot from '@app/store/plot';
import * as fromTransaction from '@app/store/transaction';
import * as fromUser from '@app/store/user';
import { Transaction, TransactionType } from '@app/models/transaction.model';
import { User } from '@app/models/user.model';
@Component({
selector: 'app-plot-details',
templateUrl: './plot-details.component.html',
styleUrls: ['./plot-details.component.scss']
})
export class PlotDetailsComponent implements OnInit, OnDestroy {
public user$: Observable<User>;
private plotId$: Observable<string>;
public plot$: Observable<Plot>;
public otherOwners$: Observable<User[]>;
public transactions$: Observable<Transaction[]>;
public isLoading$: Observable<boolean>;
private destroyed$ = new Subject<void>();
public transType = TransactionType;
constructor(private route: ActivatedRoute, private router: Router, private store$: Store<AppState>) {
this.plotId$ = this.route.paramMap.pipe(
map(x => x.get("id")),
tap(plotId => {
if (!plotId) {
console.log("Bad request. Missing PlotId");
this.router.navigate(['/', 'plots']);
}
}),
filter(plotId => plotId !== null),
map(plotId => plotId!)
);
this.plot$ = combineLatest([
this.plotId$,
this.store$.select(fromPlot.getPlotStatus)
]).pipe(
// Wait until plots finish loading before redirecting and calling it not found
filter(([plotId, status]) => status === fromPlot.PlotStatus.Loaded),
switchMap(([plotId, status]) => this.store$.select(fromPlot.getPlot(plotId))),
tap(plot => {
if (plot === null) {
console.log("Plot not found with id");
this.router.navigate(['/', 'plots']);
}
}),
filter(plot => plot !== null),
map(plot => plot!)
);
this.isLoading$ = combineLatest([
this.store$.select(fromPlot.arePlotsLoading),
this.store$.select(fromTransaction.getIsLoading)
]).pipe(
map(isLoading => isLoading.some(x => x))
);
this.transactions$ = this.store$.select(fromTransaction.selectAll);
this.user$ = this.store$.select(fromUser.getCurrentUser).pipe(
filter(user => user !== null),
map(user => user!)
);
this.otherOwners$ = this.plot$.pipe(
withLatestFrom(this.user$),
map(([plot, user]) =>
plot.homeowners.filter(owner =>
owner.id !== user.id
)
)
);
}
ngOnInit(): void {
this.plotId$.pipe(
takeUntil(this.destroyed$)
).subscribe(id => {
this.store$.dispatch(fromTransaction.loadTransactions({ plotId: id }));
});
}
ngOnDestroy(): void {
this.destroyed$.next();
}
}
|
import { ArtistDetails } from "@/components/artists/artist-details";
import { Container } from "@/components/container";
import { NoResults } from "@/components/no-results";
import { currentProfile } from "@/lib/current-profile";
import { db } from "@/lib/prismadb";
interface ArtistIdPageProps {
params: {
artistId: string;
};
searchParams: {
artistSongName: string;
artistBandName: string;
artistAlbumName: string;
};
}
const ArtistIdPage = async ({ params, searchParams }: ArtistIdPageProps) => {
const profile = await currentProfile();
const artist = await db.profile.findUnique({
where: {
id: params.artistId,
},
include: {
songs: {
where: {
title: {
contains: searchParams.artistSongName,
},
},
orderBy: {
createdAt: "desc",
},
include: {
profile: true,
},
},
},
});
const albums = await db.album.findMany({
where: {
profileId: artist?.id,
title: {
contains: searchParams.artistAlbumName,
},
},
});
const bands = await db.band.findMany({
where: {
name: {
contains: searchParams.artistBandName,
},
profileId: artist?.id,
},
});
const allFollowers = await db.following.findMany({
where: {
OR: [{ followeeId: artist?.id }, { followerId: artist?.id }],
},
});
const artistFollowers = allFollowers.filter(
(follower) => follower.followeeId === artist?.id
);
const artistFollowing = allFollowers.filter(
(follower) => follower.followerId === artist?.id
);
if (!artist) {
return (
<NoResults src="/not-found.png" title="No artist have been found." />
);
}
const isOwner = artist?.id === profile?.id;
const isFollowing = allFollowers.some(
(follower) =>
follower.followerId === profile?.id && follower.followeeId === artist?.id
);
return (
<Container>
<ArtistDetails
profile={artist}
isOwner={isOwner}
isFollowing={isFollowing}
followers={artistFollowers}
following={artistFollowing}
albums={albums}
bands={bands}
/>
</Container>
);
};
export default ArtistIdPage;
|
<!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">
<!-- font awesome cdn link -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
<!-- custom css file link -->
<link rel="stylesheet" href="css/style.css">
<head>
<body>
<!-- header section starts -->
<header>
<input type="checkbox" name="" id="toggler">
<label for="toggler" class="fas fa-bars"></label>
<a href="#" class="logo"> decorative flora's <span>.</span></a>
<nav class="navbar">
<a href="#home">home</a>
<a href="#about">about</a>
<a href="#products">products</a>
<a href="#review">review</a>
<a href="#contact">contact</a>
</nav>
<div class="icons">
<a href="#" class="fas fa-heart"></a>
<a href="#" class="fas fa-shopping-cart"></a>
<a href="#" class="fas fa-user"></a>
</div>
</header>
<!-- header section ends -->
<!-- home section starts -->
<section class="home" id="home">
<div class="content">
<h3>fresh flowers</h3>
<span> natural & beautiful flowers </span>
<p>You bring the love. We’ll bring the flowers.
We have the perfect floral arrangements to brighten someone’s day.
When words just won’t do…send a flower!</p>
<a href="#" class="btn">shop now</a>
</div>
</section>
<!-- home section ends -->
<!-- about section starts -->
<section class="about" id="about">
<h1 class="heading"> <span> about </span> us </h1>
<div class="row">
<div class="video-container">
<video src="images/about-vid.mp4" loop autoplay muted></video>
<h3>best decorative flower pot's sellers</h3>
</div>
<div class="content">
<h3>why choose us?</h3>
<p>Flowers pots for each and every occasion. Send flowers and sweet gifts with our reliable flower delivery service.Flowers/Plants can say it all.We’re not just making flower/plant arrangements</p>
<p>We’re creating memorable occasions.Always low and competitive prices.You’re in good hands with us.Your moment of joy on the right price.Celebrate all day long with us.
Feed your soul with flowers from (Decorative Flora's) because you deserve it.</p>
<a href="#" class="btn">learn more</a>
</div>
</div>
</section>
<!-- about section ends -->
<!-- icons section starts -->
<section class="icons-container">
<div class="icons">
<img src="images/icon-1.png" alt="">
<div class="info">
<h3>free delivery</h3>
<span>on all orders</span>
</div>
</div>
<div class="icons">
<img src="images/icon-2.png" alt="">
<div class="info">
<h3>10 days returns</h3>
<span>moneyback guarantee</span>
</div>
</div>
<div class="icons">
<img src="images/icon-3.png" alt="">
<div class="info">
<h3>offer & gifts</h3>
<span>on all orders</span>
</div>
</div>
<div class="icons">
<img src="images/icon-4.png" alt="">
<div class="info">
<h3>secure paymens</h3>
<span>protected by paypal</span>
</div>
</div>
</section>
<!-- icons section ends -->
<!-- prodcuts section starts -->
<section class="products" id="products">
<h1 class="heading"> latest <span>products</span> </h1>
<div class="box-container">
<div class="box">
<span class="discount">-10%</span>
<div class="image">
<img src="images/img-1.jpg" alt="">
<div class="icons">
<a href="#" class="fas fa-heart"></a>
<a href="#" class="cart-btn">add to cart</a>
<a href="#" class="fas fa-share"></a>
</div>
</div>
<div class="content">
<h3>welcome pot</h3>
<div class="price"> $14.99 <span>$15.99</span> </div>
</div>
</div>
<div class="box">
<span class="discount">-15%</span>
<div class="image">
<img src="images/img-2.jpeg" alt="">
<div class="icons">
<a href="#" class="fas fa-heart"></a>
<a href="#" class="cart-btn">add to cart</a>
<a href="#" class="fas fa-share"></a>
</div>
</div>
<div class="content">
<h3>landscape pot</h3>
<div class="price"> $14.99 <span>$16.99</span> </div>
</div>
</div>
<div class="box">
<span class="discount">-5%</span>
<div class="image">
<img src="images/img-3.jpg" alt="">
<div class="icons">
<a href="#" class="fas fa-heart"></a>
<a href="#" class="cart-btn">add to cart</a>
<a href="#" class="fas fa-share"></a>
</div>
</div>
<div class="content">
<h3>workship pot</h3>
<div class="price"> $12.99 <span>$15.99</span> </div>
</div>
</div>
<div class="box">
<span class="discount">-20%</span>
<div class="image">
<img src="images/img-4.jpg" alt="">
<div class="icons">
<a href="#" class="fas fa-heart"></a>
<a href="#" class="cart-btn">add to cart</a>
<a href="#" class="fas fa-share"></a>
</div>
</div>
<div class="content">
<h3>wall hanging pot</h3>
<div class="price"> $15.99 <span>$18.99</span> </div>
</div>
</div>
<div class="box">
<span class="discount">-17%</span>
<div class="image">
<img src="images/img-5.jpg" alt="">
<div class="icons">
<a href="#" class="fas fa-heart"></a>
<a href="#" class="cart-btn">add to cart</a>
<a href="#" class="fas fa-share"></a>
</div>
</div>
<div class="content">
<h3>bird pot</h3>
<div class="price"> $20.99 <span>$25.99</span> </div>
</div>
</div>
<div class="box">
<span class="discount">-3%</span>
<div class="image">
<img src="images/img-6.jpg" alt="">
<div class="icons">
<a href="#" class="fas fa-heart"></a>
<a href="#" class="cart-btn">add to cart</a>
<a href="#" class="fas fa-share"></a>
</div>
</div>
<div class="content">
<h3>animal pot</h3>
<div class="price"> $12.99 <span>$15.99</span> </div>
</div>
</div>
<div class="box">
<span class="discount">-18%</span>
<div class="image">
<img src="images/img-7.jpg" alt="">
<div class="icons">
<a href="#" class="fas fa-heart"></a>
<a href="#" class="cart-btn">add to cart</a>
<a href="#" class="fas fa-share"></a>
</div>
</div>
<div class="content">
<h3>fairy pot</h3>
<div class="price"> $18.99 <span>$20.99</span> </div>
</div>
</div>
<div class="box">
<span class="discount">-10%</span>
<div class="image">
<img src="images/img-8.jpg" alt="">
<div class="icons">
<a href="#" class="fas fa-heart"></a>
<a href="#" class="cart-btn">add to cart</a>
<a href="#" class="fas fa-share"></a>
</div>
</div>
<div class="content">
<h3>cute faces pot</h3>
<div class="price"> $12.99 <span>$15.99</span> </div>
</div>
</div>
<div class="box">
<span class="discount">-5%</span>
<div class="image">
<img src="images/img-9.jpg" alt="">
<div class="icons">
<a href="#" class="fas fa-heart"></a>
<a href="#" class="cart-btn">add to cart</a>
<a href="#" class="fas fa-share"></a>
</div>
</div>
<div class="content">
<h3>half moon pot</h3>
<div class="price"> $17.99 <span>$19.99</span> </div>
</div>
</div>
</div>
</section>
<!-- prodcuts section ends -->
<!-- review section starts -->
<section class="review" id="review">
<h1 class="heading"> customer's <span>review</span> </h1>
<div class="box-container">
<div class="box">
<div class="stars">
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
</div>
<p>Easy to carry, light in weight. i get good response when i gift these decorative pots to my relative</p>
<div class="user">
<img src="images/pic-1.png" alt="">
<div class="user-info">
<h3>mark john</h3>
<span>indian customer</span>
</div>
</div>
<span class="fas fa-quote-right"></span>
</div>
<div class="box">
<div class="stars">
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
</div>
<p>my house corners look goods. these pots are so cute and sometimes it give some messsage for keep clam and cool.</p>
<div class="user">
<img src="images/pic-2.png" alt="">
<div class="user-info">
<h3>christina</h3>
<span>france customer</span>
</div>
</div>
<span class="fas fa-quote-right"></span>
</div>
<div class="box">
<div class="stars">
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
</div>
<p>these wall hanging pots work as any attractive object in my room. these are light and easy to clean. i am happy that i get a good thing in a good price. </p>
<div class="user">
<img src="images/pic-3.png" alt="">
<div class="user-info">
<h3>neo</h3>
<span>france customer</span>
</div>
</div>
<span class="fas fa-quote-right"></span>
</div>
</div>
</section>
<!-- review section ends -->
<!-- contact section starts -->
<section class="contact" id="contact">
<h1 class="heading"> <span> contact </span> us </h1>
<div class="row">
<form action="">
<input type="text" placeholder="Name" class="box">
<input type="Email" placeholder="Email" class="box">
<input type="Number" placeholder="Number" class="box">
<textarea name="" class="box" placeholder="Message" id="" cols="30" rows="10"></textarea>
<input type="submit" value="send message" class="btn">
</form>
<div class="image">
<img src="images/contact-img.svg" alt="">
</div>
</div>
</section>
<!-- contact section ends -->
<!-- footer section starts -->
<section class="footer">
<div class="box-container">
<div class="box">
<h3>quick links</h3>
<a href="#">home</a>
<a href="#">about</a>
<a href="#">products</a>
<a href="#">review</a>
<a href="#">contact</a>
</div>
<div class="box">
<h3>extra links</h3>
<a href="#">my account</a>
<a href="#">my order</a>
<a href="#">my favorite</a>
</div>
<div class="box">
<h3>locations</h3>
<a href="#">india</a>
<a href="#">USA</a>
<a href="#">japan</a>
<a href="#">france</a>
</div>
<div class="box">
<h3>contact info</h3>
<a href="#">+91-8447407622</a>
<a href="#">kanishkachandolia179@gmail.com</a>
<a href="#">Delhi, India - 110005</a>
<img src="images/payment.png" alt="">
</div>
</div>
<div class="credit"> created by <span> Kanishka Chandolia </span> | all rights reserved </div>
</section>
<!-- footer section ends -->
|
<script setup>
import { ref, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import { useToast } from "vue-toastification";
const API_ROOT = import.meta.env.VITE_BASE_URL;
const showDeleteModal = ref(false);
const selectedDeletedTodo = ref(null);
const todos = ref([]);
const router = useRouter();
const deleteButton = ref(null);
let isSortedByStatus = false;
let originalTasks = [];
const filterStatus = ref([]);
const displayedFilterStatus = ref([]);
const toast = useToast();
const goToEdit = (id) => {
router.push({ path: `/task/${id}/edit` });
};
const goToView = (id) => {
router.push({ path: `/task/${id}` });
};
const gotoManageStatus = () => {
router.push({ path: "/task/status" });
};
const fetchTodos = async () => {
try {
const response = await fetch(`${API_ROOT}/v2/tasks`);
const data = await response.json();
todos.value = data.sort((a, b) => a.id - b.id);
originalTasks = [...todos.value];
} catch (error) {
console.error("Error:", error);
}
};
const truncateTitle = (title) => {
return title.length > 70 ? title.substring(0, 70) + "..." : title;
};
const deleteTodoById = async (id) => {
try {
const response = await fetch(`${API_ROOT}/v2/tasks/${id}`, {
method: "DELETE",
});
if (response.ok) {
toast.success("The task has been deleted");
} else if (response.status === 404) {
toast.error("An error has occurred, the task does not exist.");
setTimeout(() => {
location.reload();
}, 1500);
} else {
throw new Error(`HTTP error! status: ${response.status}`);
}
showDeleteModal.value = false;
selectedDeletedTodo.value = null;
await fetchTodos();
} catch (error) {
console.error("Error:", error);
}
};
const confirmDelete = async () => {
await deleteTodoById(selectedDeletedTodo.value.id);
showDeleteModal.value = false;
};
const openDeleteModal = (id) => {
const todoIndex = todos.value.findIndex((todo) => todo.id === id);
selectedDeletedTodo.value = {
...todos.value[todoIndex],
count: todoIndex + 1,
};
showDeleteModal.value = true;
nextTick(() => {
deleteButton.value.focus();
});
};
const gotoAdd = () => {
router.push({ path: "/task/add" });
};
// filter status
const filterTasksByStatus = (event) => {
const status = event.target.value.trim();
if (status && !filterStatus.value.includes(status)) {
filterStatus.value.push(status);
displayedFilterStatus.value = [...filterStatus.value];
todos.value = originalTasks.filter((task) =>
filterStatus.value.includes(task.status)
);
}
event.target.value = "";
};
const cancelFilter = (status) => {
filterStatus.value = filterStatus.value.filter((s) => s !== status);
displayedFilterStatus.value = [...filterStatus.value];
todos.value = filterStatus.value.length
? originalTasks.filter((task) => filterStatus.value.includes(task.status))
: [...originalTasks];
};
let sortDirection = 0;
// sort status
const sortTasksByStatus = () => {
if (sortDirection === 0) {
todos.value.sort((a, b) => a.status.localeCompare(b.status));
sortDirection = 1;
} else if (sortDirection === 1) {
todos.value.sort((a, b) => b.status.localeCompare(a.status));
sortDirection = -1;
} else {
todos.value = [...originalTasks];
sortDirection = 0;
}
};
onMounted(() => {
fetchTodos();
});
</script>
<template>
<div
class="w-full flex flex-col items-start h-screen bg-slate-400 overflow-auto"
>
<div class="flex justify-center w-full mb-7 relative">
<span
class="text-2xl md:text-4xl font-bold mb-3 text-white pt-4 shadow-lg"
>
ITBKK-Kradan Kanban
</span>
<span
class="absolute -bottom-1 left-0 w-full h-1 bg-gradient-to-r from-blue-500 to-green-600 rounded-full"
></span>
</div>
<div class="w-3/4 mx-auto flex flex-col items-start space-y-4">
<!-- filter search box -->
<div class="flex flex-wrap items-center justify-between w-[100%] space-x-*">
<input
@keyup.enter="filterTasksByStatus"
placeholder="Filter by status"
class="px-4 py-2 rounded w-[30%] border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 shadow-sm"
/>
<div
v-for="status in displayedFilterStatus"
:key="status"
class="flex items-center bg-blue-200 rounded-full px-3 py-1 text-sm font-semibold text-blue-700 m-1"
>
{{ status }}
<button
@click="cancelFilter(status)"
class="ml-2 text-xs bg-red-500 text-white rounded-full px-2 py-1 focus:outline-none"
>
x
</button>
</div>
<div
class="flex max-w-sm rounded-xl bg-gradient-to-tr from-pink-300 to-blue-300 p-0.5 shadow-lg"
:class="
isSortedByStatus
? 'bg-gradient-to-tr from-red-600 to-pink-200'
: 'bg-gradient-to-tr from-pink-300 to-blue-300'
"
>
<button
@click="sortTasksByStatus"
class="flex-1 font-bold text-lg bg-white px-4 py-2 rounded-xl"
:class="
sortDirection === 0
? 'text-gray-500'
: sortDirection === 1
? 'text-blue-600'
: 'text-red-600'
"
>
Sort By Status
</button>
</div>
</div>
<table
class="table-lg style bg-blue-700 text-lg w-full rounded-lg shadow-lg overflow-hidden"
>
<thead
class="text-white w-full bg-gradient-to-r from-pink-300 via-blue-200 to-purple-300"
>
<tr>
<th class="w-1/3 text-center text-gray-800 py-2">Title</th>
<th class="w-1/4 text-center text-gray-800 py-2">Assignees</th>
<th class="w-1/4 text-center text-gray-800 py-2">Status</th>
<th class="1/3 text-center py-2">
<button
@click="gotoAdd"
class="itbkk-button-add btn btn-outline btn-success bg-green-200 btn-md"
>
Add Task
</button>
</th>
<th>
<button
@click="gotoManageStatus"
class="itbkk-button-status btn btn-active btn-neutral btn-md hover:bg-blue-500 hover:text-white"
>
Manage Status
</button>
</th>
</tr>
</thead>
<!-- body -->
<tbody class="bg-white divide-y divide-gray-200">
<!-- if no task -->
<tr
v-if="todos.length === 0"
class="justify-center items-center min-h-screen hover"
>
<td
colspan="5"
class="px-6 py-4 whitespace-nowrap text-sm text-gray-800 h-20"
>
<h2 class="text-lg font-semibold text-gray-700">No tasks yet</h2>
</td>
</tr>
<tr
v-for="todo in todos"
:key="todo.id"
class="itbkk-item hover:bg-gray-100 transition duration-200 ease-in-out transform hover:-translate-y-1 hover:scale-80"
>
<td
class="itbkk-title px-6 py-4 whitespace-nowrap text-sm text-gray-800 cursor-pointer border-b border-gray-200"
@click="goToView(todo.id)"
>
<div
class="truncate text-lg font-semibold text-blue-600"
:title="todo.title"
>
{{ truncateTitle(todo.title) }}
</div>
</td>
<td
class="itbkk-assignees px-6 py-4 whitespace-nowrap text-sm text-black-500 italic text-gray-800 border-b border-gray-200 flex items-center justify-center"
>
<span class="text-md font-medium text-green-600">
{{ todo.assignees ? todo.assignees : "Unassigned" }}
</span>
</td>
<td
class="itbkk-status px-6 py-4 whitespace-nowrap text-sm text-gray-800 border-b border-gray-200"
>
<div
class="rounded-full text-center px-2 py-1"
:class="
todo.status === 'No Status'
? 'bg-gray-200 text-gray-800'
: 'bg-blue-200 text-blue-800'
"
>
{{ todo.status }}
</div>
</td>
<td
class="px-6 py-4 whitespace-nowrap text-sm font-medium text-center"
>
<button
@click="openDeleteModal(todo.id)"
class="itbkk-button-action bg-red-500 text-white hover:bg-red-700 px-3 py-1 rounded"
>
Delete
</button>
</td>
<td
class="px-6 py-4 whitespace-nowrap text-center text-sm font-medium"
>
<button
@click="goToEdit(todo.id)"
class="bg-indigo-500 text-white hover:bg-indigo-700 px-3 py-1 rounded"
>
Edit
</button>
</td>
</tr>
</tbody>
</table>
</div>
<!-- delete modal -->
<div
v-if="showDeleteModal"
class="fixed z-10 inset-0 overflow-y-auto flex items-center justify-center bg-slate-500 bg-opacity-25"
>
<div
class="bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:max-w-lg sm:w-full"
>
<div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<div class="flex flex-col items-center justify-center text-center">
<h3 class="text-lg leading-6 font-medium text-gray-900">
Do you want to delete the task number
{{ selectedDeletedTodo.count }}
</h3>
<h3
class="text-lg leading-6 font-medium text-gray-900 truncate-title"
>
{{ selectedDeletedTodo.title }}
</h3>
<h3 class="text-lg leading-6 font-medium text-gray-900">tasks?</h3>
</div>
</div>
<div
class="bg-gray-50 px-4 py-3 sm:px-6 flex justify-center sm:flex-row-reverse overflow-auto"
>
<button
@click="confirmDelete"
@keyup.enter="confirmDelete"
ref="deleteButton"
type="button"
class="itbkk-button-delete w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm"
>
Delete
</button>
<button
@click="showDeleteModal = false"
type="button"
class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:w-auto sm:text-sm"
>
Cancel
</button>
</div>
</div>
</div>
</div>
</template>
<style>
.status-no-status,
.status-to-do,
.status-doing,
.status-done {
border-style: solid;
border-width: 1px;
}
.status-no-status {
border-color: blue;
color: blue;
}
.status-to-do {
border-color: gray;
color: gray;
}
.status-doing {
border-color: orange;
color: orange;
}
.status-done {
border-color: green;
color: green;
}
.long-title {
word-wrap: break-word;
max-width: 90%;
}
.truncate-title {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 250px;
display: block;
}
</style>
|
import time # Importing the time module to measure execution time
from champion.source.models.Logistic_Regression import Logistic_Regression # Importing Logistic Regression model
from champion.source.models.Ensemble_Stacking import Ensemble_Stacking # Importing Ensemble Stacking model
from champion.source.models.Ensemble_Voting import Ensemble_Voting # Importing Ensemble Voting model
from champion.source.models.RandomForest import RandomForest # Importing Random Forest model
from champion.source.models.LongShortTM import LongShortTM # Importing Long Short-Term Memory (LSTM) model for sequential data
from champion.source.models.LightGBM import LightGBM # Importing LightGBM model
from champion.source.models.XGBoost import XGBoost # Importing XGBoost model
from champion.source.models.ANN import ANN # Importing Artificial Neural Network (ANN) model
if __name__ == "__main__":
# Measure the execution time for each model's SHAP value generation
# 1. Logistic Regression
start = time.time() # Start the timer
log_model = Logistic_Regression() # Instantiate the Logistic Regression model
log_model.generate_shap_value() # Generate SHAP values for the Logistic Regression model
log_train_time = time.time() - start # Calculate the execution time
# 3. Random-Forest
start = time.time() # Start the timer
rf_model = RandomForest() # Instantiate the Random Forest model
rf_model.generate_shap_value() # Generate SHAP values for the Random Forest model
rf_train_time = time.time() - start # Calculate the execution time
# 4. Boosting
start = time.time() # Start the timer
lightgbm_model = LightGBM() # Instantiate the LightGBM model
lightgbm_model.generate_shap_value() # Generate SHAP values for the LightGBM model
lightgbm_train_time = time.time() - start # Calculate the execution time
start = time.time() # Start the timer
xgboost_model = XGBoost() # Instantiate the XGBoost model
xgboost_model.generate_shap_value() # Generate SHAP values for the XGBoost model
xgboost_train_time = time.time() - start # Calculate the execution time
# 5. Neural Network - ANN
start = time.time() # Start the timer
ann_model = ANN() # Instantiate the ANN model
ann_model.generate_shap_value() # Generate SHAP values for the ANN model
ann_train_time = time.time() - start # Calculate the execution time
# 6. Neural Network - LSTM
start = time.time() # Start the timer
lstm_model = LongShortTM() # Instantiate the LSTM model
lstm_model.generate_shap_value() # Generate SHAP values for the LSTM model
lstm_train_time = time.time() - start # Calculate the execution time
# 7. Ensembly of Models
start = time.time() # Start the timer
ensemble_voting_model = Ensemble_Voting() # Instantiate the Ensemble Voting model
ensemble_voting_model.generate_shap_value() # Generate SHAP values for the Ensemble Voting model
voting_train_time = time.time() - start # Calculate the execution time
start = time.time() # Start the timer
ensemble_stacking_model = Ensemble_Stacking() # Instantiate the Ensemble Stacking model
ensemble_stacking_model.generate_shap_value() # Generate SHAP values for the Ensemble Stacking model
stacking_train_time = time.time() - start # Calculate the execution time
# Print the execution times for SHAP value generation for each model
print(f"""
The time taken (s) to generate SHAP Value for the following are noted below:
Logistic : {log_train_time:.2f}
Random Forest : {rf_train_time:.2f}
LightGBM : {lightgbm_train_time:.2f}
XGBoost : {xgboost_train_time:.2f}
ANN : {ann_train_time:.2f}
LSTM : {lstm_train_time:.2f}
Voting : {voting_train_time:.2f}
Stacking : {stacking_train_time:.2f}
""")
|
package com.tenic.possystem.utils;
import com.tenic.possystem.embeddables.Audit;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.security.core.context.SecurityContextHolder;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Objects;
/**
* @author Terrance Nyamfukudza
* 30/5/2024
*/
@Configurable
public class AppAuditEventListener {
private static final String DEFAULT_USER = "N/A";
private static Audit getAudit(Object obj) throws Exception {
Method getAudit = obj.getClass().getMethod("getAudit");
return (Audit) getAudit.invoke(obj);
}
private static String getLoggedUser() {
if (SecurityContextHolder.getContext().getAuthentication() == null) {
return DEFAULT_USER;
} else {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
}
@PrePersist
public void persist(Object obj) {
final String USER = getLoggedUser();
try {
Audit audit = getAudit(obj);
if (Objects.isNull(audit)) audit = new Audit();
audit.setCreatedBy(USER);
audit.setModifiedDate(LocalDateTime.now());
audit.setCreatedDate(LocalDateTime.now());
audit.setModifiedBy(USER);
Method setAudit = getSetAuditMethod(obj);
setAudit.invoke(obj, audit);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Method getSetAuditMethod(Object obj) throws Exception {
return obj.getClass().getMethod("setAudit", Audit.class);
}
@PreUpdate
void update(Object obj) {
try {
Audit audit = getAudit(obj);
if (Objects.isNull(audit)) {
audit = new Audit();
audit.setCreatedBy(getLoggedUser());
audit.setCreatedDate(LocalDateTime.now());
}
audit.setModifiedBy(getLoggedUser());
audit.setModifiedDate(LocalDateTime.now());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
#### Grazing x Insect Data - 2020 #
#### Code created by: Kathryn Bloodworth and Will Mann #
#Date started: 06/14/2021 # adapted and restarted 07/13/2022
#### Set working directory and load libraries ####
# Set Working Directory - Mac
setwd("~/Library/CloudStorage/Box-Box/Projects/Dissertation/Data/Insect_Data")
# Set Working Directory - PC
setwd("C:/Users/kjbloodw/Box/Projects/Dissertation/Data/Insect_Data")
#install.packages("scales")
library(scales)
library(vegan)
library(lmerTest)
#install.packages("devtools")
library(grid)
#install.packages("multcomp")
library(multcomp)
#Load Tidyverse#
library(tidyverse)
library(olsrr)
library(patchwork)
library(codyn)
library(pairwiseAdonis)
#install.packages("ggpattern")
library(ggpattern)
#Set ggplot2 theme to black and white
theme_set(theme_bw())
#Update ggplot2 theme - make box around the x-axis title size 30, vertically justify x-axis title to 0.35, Place a margin of 15 around the x-axis title. Make the x-axis title size 30. For y-axis title, make the box size 30, put the writing at a 90 degree angle, and vertically justify the title to 0.5. Add a margin of 15 and make the y-axis text size 25. Make the plot title size 30 and vertically justify it to 2. Do not add any grid lines. Do not add a legend title, and make the legend size 20
theme_update(panel.grid.major=element_blank(),
panel.grid.minor=element_blank())
#### Load in data ####
#make sure column names are consistent
#ID Data
ID_Data_20<-read.csv("2020_Sweep_Net_Dvac_Data_FK.csv",header=T) %>%
#make all collection methods the same across years
mutate(Collection_Method=ifelse(Collection_Method=="d-vac","dvac",ifelse(Collection_Method=="sweep_net","sweep",Collection_Method))) %>%
#rename sample column so that it's the same across years
rename(Sample_Number="Sample") %>%
dplyr::select(Collection_Method,Year,Block,Grazing_Treatment,Plot,Sample_Number,Order,Family,Genus,Species,Notes) %>%
filter(Collection_Method=="dvac")
ID_Data_21<-read.csv("2021_Sweep_Net_Dvac_Data_FK.csv",header=T) %>%
#make all collection methods the same across years
mutate(Collection_Method=ifelse(Collection_Method=="d-vac","dvac",ifelse(Collection_Method=="sweep_net","sweep",Collection_Method))) %>%
#rename sample column so that it's the same across years
rename(Sample_Number="Sample")%>%
dplyr::select(Collection_Method,Year,Block,Grazing_Treatment,Plot,Sample_Number,Order,Family,Genus,Species,Notes) %>%
#remove blanks from dataframe
filter(Collection_Method!="") %>%
#fix "LG " to "LG"
mutate(Grazing_Treatment=ifelse(Grazing_Treatment=="LG ","LG",Grazing_Treatment))%>%
filter(Collection_Method=="dvac")
ID_Data_22<-read.csv("2022_Sweep_Net_D-Vac_Data_FK.csv",header=T) %>%
#make all collection methods the same across years
mutate(Collection_Method=ifelse(Collection_Method=="Dvac","dvac",ifelse(Collection_Method=="Sweep_Net","sweep",Collection_Method))) %>%
#rename sample column so that it's the same across years
rename(Sample_Number="Sample")%>%
dplyr::select(Collection_Method,Year,Block,Grazing_Treatment,Plot,Sample_Number,Order,Family,Genus,Species,Notes)%>%
filter(Collection_Method=="dvac")
#Weight Data
Weight_Data_20<-read.csv("2020_Sweep_Net_D-Vac_Weight_Data_FK.csv",header=T) %>%
rename(Sample_Number=Sample_num) %>%
mutate(Collection_Method=ifelse(Collection_Method=="d-vac","dvac",ifelse(Collection_Method=="sweep_net","sweep",Collection_Method)))%>%
filter(Collection_Method=="dvac")
Weight_Data_21<-read.csv("2021_Sweep_Net_D-Vac_Weight_Data_FK.csv",header=T) %>%
mutate(Collection_Method=ifelse(Collection_Method=="d-vac","dvac",ifelse(Collection_Method=="sweep_net","sweep",Collection_Method)))%>%
filter(Collection_Method=="dvac")
Weight_Data_22<-read.csv("2022_Sweep_Net_D-Vac_Weight_Data_FK.csv",header=T) %>%
mutate(Collection_Method=ifelse(Collection_Method=="d-vac","dvac",ifelse(Collection_Method=="sweep_net","sweep",Collection_Method)))%>%
filter(Collection_Method=="dvac")
#Plant Species Comp Data
PlantComp<-read.csv("Plant_Species_Comp_2022.csv",header=T)
Functional_Groups<-read.csv("FunctionalGroups.csv")
#### Formatting and Cleaning ID Data ####
ID_20<-ID_Data_20 %>%
#Change block and grazing treatment to be consistent
mutate(Block=ifelse(Block=="B1",1,ifelse(Block=="B2",2,ifelse(Block=="B3",3,Block)))) %>%
#correct misspellings and inconsistencies in order data
mutate(Correct_Order=ifelse(Order=="orthoptera","Orthoptera",ifelse(Order=="hemiptera","Hemiptera",ifelse(Order=="coleoptera","Coleoptera",ifelse(Order=="hymenoptera","Hymenoptera",ifelse(Order=="diptera","Diptera",ifelse(Order=="araneae","Araneae",Order))))))) %>%
#correct misspellings and inconsistencies in order data
mutate(Correct_Family=ifelse(Family=="acrididae", "Acrididae",ifelse(Family=="cicadellidae", "Cicadellidae", ifelse(Family=="geocoridae", "Geocordidae", ifelse(Family=="carabidae", "Carabidae", ifelse(Family=="chrysomelidae","Chrysomelidae", ifelse(Family=="formicidae", "Formicidae", ifelse(Family=="halictidae", "Halictidae", ifelse(Family=="agromyzidae", "Agromyzidae", ifelse(Family=="lycosidae", "Lycosidae", ifelse(Family=="platygastridae", "Platygastridae", ifelse(Family=="tettigoniidae", "Tettigoniidae", ifelse(Family=="salticidae", "Salticidae", ifelse(Family=="thomisidae", "Thomisidae", ifelse(Family=="pentatomidae", "Pentatomidae", ifelse(Family=="lygaeidae", "Lygaeidae", ifelse(Family=="scutelleridae", "Scutelleridae", ifelse(Family=="gryllidae", "Gryllidae", ifelse(Family=="asilidae", "Asilidae", ifelse(Family=="chrysididae", "Chrysididae", ifelse(Family=="curculionidae", "Curculionidae", ifelse(Family=="latridiidae","Latridiidae", ifelse(Family=="muscidae", "Muscidae", ifelse(Family=="tenebrionidae", "Tenebrionidae",ifelse(Family=="Lygacidae","Lygaeidae",ifelse(Family=="Salticide","Salticidae", Family)))))))))))))))))))))))))) %>%
mutate(Correct_Genus=ifelse(Genus=="Melanoplus","Melanoplus",ifelse(Genus=="arphia","Arphia",ifelse(Genus=="melanoplus","Melanoplus",ifelse(Genus=="opeia","Opeia",ifelse(Genus=="nenconocephalus","Neoconocephalus",ifelse(Genus=="pachybrachis","Pachybrachis",ifelse(Genus=="ageneotettix ","Ageneotettix", ifelse(Genus=="phoetaliotes","Phoetaliotes",ifelse(Genus=="Ageneotettix ","Ageneotettix",ifelse(Genus=="amphiturnus","Amphiturnus",ifelse(Genus=="Ageneotettox","Ageneotettix",ifelse(Genus=="Agneotettix","Ageneotettix",ifelse(Genus=="ageneotettix","Ageneotettix",Genus)))))))))))))) %>%
mutate(Correct_Species=ifelse(Species=="differentalis","differentialis",ifelse(Species=="sanguinipes","sanguinipes",ifelse(Species=="packardi","packardii",ifelse(Species=="unknown","sp",ifelse(Species=="pachardii","packardii",ifelse(Species=="sanguinpes","sanguinipes",Species))))))) %>%
#remove unnecessary columns and reoder
dplyr::select(Collection_Method,Year,Block,Grazing_Treatment,Plot,Sample_Number,Correct_Order,Correct_Family,Correct_Genus,Correct_Species,Notes) %>%
#remove all body part entries
filter(Notes!="Body Parts" & Notes!="Body Parts/Legs" & Notes!="Body parts" & Notes!="too smooshed to tell, put into body parts jar") %>%
#make sample # numeric instead of character
mutate(Sample_Number=as.numeric(Sample_Number))
ID_21<-ID_Data_21 %>%
#Change block and grazing treatment to be consistent and match plot numbers
mutate(Block=ifelse(Block=="B1",1,ifelse(Block=="B2",2,ifelse(Block=="B3",3,Block)))) %>%
filter(!is.na(Year)) %>%
#fix block numbers
mutate(Block=ifelse(Plot<=15,1,ifelse(Plot==16,2,ifelse(Plot==17,2,ifelse(Plot==18,2,ifelse(Plot==19,2,ifelse(Plot==20,2,ifelse(Plot==21,2,ifelse(Plot==22,2,ifelse(Plot==23,2,ifelse(Plot==24,2,ifelse(Plot==25,2,ifelse(Plot==26,2,ifelse(Plot==27,2,ifelse(Plot==28,2,ifelse(Plot==29,2,ifelse(Plot==30,2,ifelse(Plot==31,3,ifelse(Plot==32,3,ifelse(Plot==33,3,ifelse(Plot==34,3,ifelse(Plot==35,3,ifelse(Plot==36,3,ifelse(Plot==37,3,ifelse(Plot==38,3,ifelse(Plot==39,3,ifelse(Plot==40,3,ifelse(Plot==41,3,ifelse(Plot==43,3,ifelse(Plot==43,3,ifelse(Plot==44,3,ifelse(Plot==45,3,Block))))))))))))))))))))))))))))))))%>%
#change grazing treatments to be consistent
mutate(Grazing_Treatment=ifelse(Grazing_Treatment=="LG ","LG",Grazing_Treatment)) %>%
#correct misspellings and inconsistencies in order data
mutate(Correct_Order=ifelse(Order=="Aranea ","Araneae",ifelse(Order=="Hemiptera ","Hemiptera",ifelse(Order=="Araneae ","Araneae",ifelse(Order=="Coleopetra","Coleoptera",ifelse(Order=="Coleoptera ","Coleoptera",ifelse(Order=="Hymenoptera ","Hymenoptera",ifelse(Order=="Hymeonptera","Hymenoptera",ifelse(Order=="Orthoptera ","Orthoptera",Order))))))))) %>%
#correct misspellings and inconsistencies in order data
mutate(Correct_Family=ifelse(Family=="Acridiae", "Acrididae",ifelse(Family=="Agramyzidae", "Agromyzidae", ifelse(Family=="Coleoptera ", "Coleoptera", ifelse(Family=="Currulianidae", "Curculionidae", ifelse(Family=="Ligidae","Lygaeidae", ifelse(Family=="Scuttelleridae", "Scutelleridae", ifelse(Family=="Scutelleridae ", "Scutelleridae", ifelse(Family=="staphylinidae", "Staphylinidae", ifelse(Family=="Thamisidae", "Thomisidae", ifelse(Family=="Thomsidae", "Thomisidae", ifelse(Family=="Formicide", "Formicidae", Family))))))))))))%>%
mutate(Correct_Genus=ifelse(Genus=="longipennis","Longipennis",ifelse(Genus=="Opcia","Opeia",ifelse(Genus=="melanoplus","Melanoplus",ifelse(Genus=="opeia","Opeia",ifelse(Genus=="Phoetaliotes ","Phoetaliotes",ifelse(Genus=="Erittix","Eritettix",Genus))))))) %>%
mutate(Correct_Species=ifelse(Species=="bru","bruneri",ifelse(Species=="Bruneri","bruneri",ifelse(Species=="Bruneri ","bruneri",ifelse(Species=="confuscus","confusus",ifelse(Species=="Confusus","confusus",ifelse(Species=="Curtipennis","curtipennis",ifelse(Species=="Deorum","deorum",ifelse(Species=="differntialis","differentialis",ifelse(Species=="Gladstoni","gladstoni",ifelse(Species=="Hebrascensis","nebrascensis",ifelse(Species=="Infantilis","infantilis",ifelse(Species=="Keeleri","keeleri",ifelse(Species=="Nebrascensis","nebrascensis",ifelse(Species=="Obscrua","obscura",ifelse(Species=="Obscura ","obscura",ifelse(Species=="Obscuria","obscura",ifelse(Species=="Pseudonietara","pseudonietana",ifelse(Species=="Pseudonietena","pseudonietana",ifelse(Species=="Sanguinipes","sanguinipes",ifelse(Species=="Simplex","simplex",ifelse(Species=="Angustipennis","angustipennis",Species)))))))))))))))))))))) %>%
#remove unnecessary columns and reoder
dplyr::select(Collection_Method,Year,Block,Grazing_Treatment,Plot,Sample_Number,Correct_Order,Correct_Family,Correct_Genus,Correct_Species,Notes) %>%
mutate(Sample_Number=as.numeric(Sample_Number))
ID_22<-ID_Data_22 %>%
#Change block and grazing treatment to be consistent and match plot numbers
mutate(Block=ifelse(Block=="B1",1,ifelse(Block=="B2",2,ifelse(Block=="B3",3,Block)))) %>%
#correct misspellings and inconsistencies in order data
mutate(Correct_Order=ifelse(Order=="araneae","Araneae",
ifelse(Order=="coleoptera","Coleoptera",
ifelse(Order=="diptera","Diptera",
ifelse(Order=="hemiptera","Hemiptera",
ifelse(Order=="hymenoptera","Hymenoptera",
ifelse(Order=="lepidoptera","Lepidoptera",
ifelse(Order=="neuroptera","Neuroptera",
ifelse(Order=="orthoptera","Orthoptera",
ifelse(Order=="thysanoptera","Thysanoptera",
ifelse(Order=="unknown","Unknown",Order))))))))))) %>%
#correct misspellings and inconsistencies in order data
mutate(Correct_Family=ifelse(Family=="aphididae", "Aphididae",ifelse(Family=="asilidae", "Asilidae",ifelse(Family=="Ceraphionidae","Ceraphronidae",ifelse(Family=="chloropidae","Chloropidae",ifelse(Family=="Chrionomidae","Chironomidae",ifelse(Family=="chrysididae","Chrysididae",ifelse(Family=="Cicadellidea","Cicadellidae",ifelse(Family=="coccinellidae","Coccinellidae",ifelse(Family=="Coccinelliadae","Coccinellidae",ifelse(Family=="culicidae","Culicidae",ifelse(Family=="curculionidae","Curculionidae",ifelse(Family=="Diapriidea","Diapriidae",ifelse(Family=="Euiophidae","Eulophidae",ifelse(Family=="eupelmidae","Eupelmidae",ifelse(Family=="ichneumonidae","Ichneumonidae",ifelse(Family=="latridiidae","Latridiidae",ifelse(Family=="lycosidae","Lycosidae",ifelse(Family=="muscidae","Muscidae",ifelse(Family=="myrmeleontidae","Myrmeleontidae",ifelse(Family=="nabidae","Nabidae",ifelse(Family=="pentatomidae","Pentatomidae",ifelse(Family=="perilampidae","Perilampidae",ifelse(Family=="platygastridae","Platygastridae",ifelse(Family=="scarabaeidae","Scarabaeidae",ifelse(Family=="Scarabacidae","Scarabaeidae",ifelse(Family=="sepsidae","Sepsidae",ifelse(Family=="tomisidae","Thomisidae",ifelse(Family=="Thripinae","Thripidae",ifelse(Family=="Thrips","Thripidae",ifelse(Family=="Tiombiculidae","Trombiculidae",ifelse(Family=="tingidae","Tingidae",ifelse(Family=="trichoceridae","Trichoceridae",ifelse(Family=="Trichoceridea","Trichoceridae",ifelse(Family=="unknown","Unknown",ifelse(Family=="",NA,ifelse(Family=="N/A",NA,ifelse(Family=="n/a",NA,Family)))))))))))))))))))))))))))))))))))))) %>%
mutate(Correct_Genus=ifelse(Genus=="ageneotettix","Ageneotettix",ifelse(Genus=="arphia","Arphia",ifelse(Genus=="melanoplus","Melanoplus",ifelse(Genus=="opeia","Opeia",ifelse(Genus=="dissosteira","Dissosteira",ifelse(Genus=="Dissosteria","Dissosteira" ,ifelse(Genus=="Eritcttix","Eritettix",ifelse(Genus=="eritettix","Eritettix",ifelse(Genus=="Erotettix","Eritettix",ifelse(Genus=="phoetaliotes","Phoetaliotes",ifelse(Genus=="unknown","Unknown",ifelse(Genus=="",NA,ifelse(Genus=="N/A",NA,ifelse(Genus=="n/a",NA,Genus))))))))))))))) %>%
mutate(Correct_Species=ifelse(Species=="os","obscura",ifelse(Species=="pseudomietana","pseudonietana",ifelse(Species=="unknown","Unknown",ifelse(Species=="",NA,ifelse(Species=="N/A",NA,ifelse(Species=="n/a",NA,Species))))))) %>%
#remove unnecessary columns and reoder
dplyr::select(Collection_Method,Year,Block,Grazing_Treatment,Plot,Sample_Number,Correct_Order,Correct_Family,Correct_Genus,Correct_Species,Notes) %>%
mutate(Sample_Number=as.numeric(Sample_Number))
#Merge together data frames
ID_Data_Official<-ID_20 %>%
rbind(ID_21) %>%
rbind(ID_22) %>%
mutate(Coll_Year_Bl_Trt=paste(Collection_Method,Year,Block,Grazing_Treatment,sep = "_")) %>%
mutate(Coll_Year_Bl_Trt_Pl=paste(Coll_Year_Bl_Trt,Plot,sep = "-"))
#### Abundance by Count ####
Abundance<-ID_Data_Official %>%
group_by(Collection_Method,Year,Block,Grazing_Treatment,Plot,Correct_Order) %>%
mutate(Abundance=length(Sample_Number)) %>%
ungroup()
Abundance_Plot<-ID_Data_Official %>%
group_by(Collection_Method,Year,Block,Grazing_Treatment,Plot) %>%
mutate(Plot_Abundance=length(Sample_Number)) %>%
ungroup() %>%
select(Collection_Method,Year,Block,Grazing_Treatment,Plot,Plot_Abundance) %>%
unique()
Abundance_Plot_Orthoptera<-Abundance %>%
filter(Correct_Order=="Orthoptera") %>%
select(Collection_Method,Year,Block,Grazing_Treatment,Plot,Abundance) %>%
unique()
#### Formatting and Cleaning Weight Data ####
Weight_20<-Weight_Data_20 %>%
#change blocks to be numeric
mutate(Block=ifelse(Block=="B1",1,ifelse(Block=="B2",2,ifelse(Block=="B3",3,Block)))) %>%
#Correct order spellings
mutate(Correct_Order=ifelse(Order=="Aranaea","Araneae",ifelse(Order=="Aranea","Araneae",ifelse(Order=="Hempitera","Hemiptera",ifelse(Order=="Cicadellidae","Hemiptera",ifelse(Order=="Lyaceidae","Hemiptera",ifelse(Order=="","Orthoptera",Order))))))) %>%
#fix NA issue related to body parts
mutate(Correct_Order=ifelse(Notes=="Body Parts","Body_Parts",ifelse(Notes=="Body parts","Body_Parts",ifelse(Notes=="unknown","unknown",Correct_Order)))) %>%
#remove unnecessary columns and reoder
dplyr::select(Collection_Method,Year,Block,Grazing_Treatment,Plot,Sample_Number,Correct_Order,Dry_Weight_g,Notes)
Weight_21<-Weight_Data_21 %>%
#change grazing treatments to be correct
mutate(Grazing_Treatment=ifelse(Grazing_Treatment=="LG ","LG",ifelse(Grazing_Treatment=="LH","LG",Grazing_Treatment))) %>%
#change blocks to be numeric
mutate(Block=ifelse(Block=="B1",1,ifelse(Block=="B2",2,ifelse(Block=="B3",3,Block)))) %>%
#Remove extra rows
filter(!is.na(Year)) %>%
#correct order spellings
mutate(Correct_Order=ifelse(Order=="aranea","Araneae",ifelse(Order=="body_parts","Body_Parts",ifelse(Order=="Body Parts","Body_Parts",ifelse(Order=="Body_Parts ","Body_Parts",ifelse(Order=="coleoptera","Coleoptera",ifelse(Order=="Coleoptera ","Coleoptera",ifelse(Order=="diptera","Diptera",ifelse(Order=="hemiptera","Hemiptera",ifelse(Order=="hymenoptera","Hymenoptera",ifelse(Order=="Orthoptera ","Orthoptera",ifelse(Order=="body parts","Body_Parts",ifelse(Order=="Cicadellidae","Hemiptera",Order))))))))))))) %>%
#remove unnecessary columns and reoder
dplyr::select(Collection_Method,Year,Block,Grazing_Treatment,Plot,Sample_Number,Correct_Order,Dry_Weight_g,Notes)
Weight_22<-Weight_Data_22 %>%
#change blocks to be numeric
mutate(Block=ifelse(Block=="B1",1,ifelse(Block=="B2",2,ifelse(Block=="B3",3,Block)))) %>%
mutate(Correct_Order=ifelse(Order=="Trombicvlidae","Trombiculidae",Order)) %>%
#remove unnecessary columns and reoder
dplyr::select(Collection_Method,Year,Block,Grazing_Treatment,Plot,Sample_Number,Correct_Order,Dry_Weight_g,Notes)
#Merge together data frames
Weight_Data_Official<-Weight_20 %>%
rbind(Weight_21) %>%
rbind(Weight_22) %>%
#wrong grazing treatment fixed
mutate(Grazing_Treatment=ifelse(Plot==35,"NG",Grazing_Treatment)) %>%
#wrong block numbers fixed
mutate(Block=ifelse(Plot=="40",3,Block)) %>%
#replace any weight that is <0.0001 with 0.00001 %>%
mutate(Dry_Weight_g=as.numeric(ifelse(Dry_Weight_g=="<0.0001","0.00001",Dry_Weight_g))) %>%
#Create a column that merges together treatment data and year
mutate(Coll_Year_Bl_Trt=paste(Collection_Method,Year,Block,Grazing_Treatment,sep = "_")) %>%
mutate(Coll_Year_Bl_Trt_Pl=paste(Coll_Year_Bl_Trt,Plot,sep = "-")) %>%
mutate(Coll_Year_Bl_Trt_Pl=ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2021_1_NG_33","dvac_2021_3_NG_33",Coll_Year_Bl_Trt_Pl)) %>%
#fix plot numbers to be correct numbers
mutate(Coll_Year_Bl_Trt_Pl=ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_NG-1","dvac_2020_1_NG-1",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_NG-2","dvac_2020_1_NG-2",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_NG-3","dvac_2020_1_NG-3",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_NG-4","dvac_2020_1_NG-4",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_NG-5","dvac_2020_1_NG-5",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_LG-1","dvac_2020_1_LG-6",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_LG-2","dvac_2020_1_LG-7",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_LG-3","dvac_2020_1_LG-8",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_LG-4","dvac_2020_1_LG-9",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_LG-5","dvac_2020_1_LG-10",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_HG-1","dvac_2020_1_HG-11",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_HG-2","dvac_2020_1_HG-12",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_HG-3","dvac_2020_1_HG-13",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_HG-4","dvac_2020_1_HG-14",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_1_HG-5","dvac_2020_1_HG-15",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_NG-1","dvac_2020_2_NG-16",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_NG-2","dvac_2020_2_NG-17",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_NG-3","dvac_2020_2_NG-18",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_NG-4","dvac_2020_2_NG-19",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_NG-5","dvac_2020_2_NG-20",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_LG-1","dvac_2020_2_LG-21",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_LG-2","dvac_2020_2_LG-22",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_LG-3","dvac_2020_2_LG-23",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_LG-4","dvac_2020_2_LG-24",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_LG-5","dvac_2020_2_LG-25",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_HG-1","dvac_2020_2_HG-26",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_HG-2","dvac_2020_2_HG-27",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_HG-3","dvac_2020_2_HG-28",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_HG-4","dvac_2020_2_HG-29",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_2_HG-5","dvac_2020_2_HG-30",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_NG-1","dvac_2020_3_NG-31",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_NG-2","dvac_2020_3_NG-32",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_NG-3","dvac_2020_3_NG-33",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_NG-4","dvac_2020_3_NG-34",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_NG-5","dvac_2020_3_NG-35",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_LG-1","dvac_2020_3_LG-36",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_LG-2","dvac_2020_3_LG-37",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_LG-3","dvac_2020_3_LG-38",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_LG-4","dvac_2020_3_LG-39",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_LG-5","dvac_2020_3_LG-40",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_HG-1","dvac_2020_3_HG-41",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_HG-2","dvac_2020_3_HG-42",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_HG-3","dvac_2020_3_HG-43",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_HG-4","dvac_2020_3_HG-44",
ifelse(Coll_Year_Bl_Trt_Pl=="dvac_2020_3_HG-5","dvac_2020_3_HG-45",
Coll_Year_Bl_Trt_Pl)))))))))))))))))))))))))))))))))))))))))))))) %>%
dplyr::select(Coll_Year_Bl_Trt_Pl,Sample_Number,Correct_Order,Dry_Weight_g,Notes) %>%
#RemovNAs from Dry weight
filter(!is.na(Dry_Weight_g)) %>%
separate(Coll_Year_Bl_Trt_Pl, c("Coll_Year_Bl_Trt","Plot"), "-")
#### Formatting and Cleaning Plant Species Data ####
#Create Long dataframe from wide dataframe and fix species issues
LongCov_SpComp<-gather(PlantComp,key="species","cover",12:70) %>%
dplyr::select(block,plot,grazing_treatment,added_total_excel,species,cover) %>%
filter(!species %in% c("dung","moss","rock","lichen","mushroom","litter","bare_ground","final_total","final_total_excel","Longpod.mustard..Erysimum.asperum..","Lygo.deomia","basal.rosette" )) %>%
na.omit(cover) %>%
filter(cover!=0)
#Calculate Relative Cover
Relative_Cover_PlantSp<-LongCov_SpComp%>%
#In the data sheet Relative_Cover, add a new column called "Relative_Cover", in which you divide "cover" by "Total_Cover"
mutate(Relative_Cover=(cover/added_total_excel)*100) %>%
dplyr::select(block,plot,grazing_treatment,species,Relative_Cover)
#make plot a factor not an integer
Relative_Cover_PlantSp$plot<-as.factor(Relative_Cover_PlantSp$plot)
Relative_Cover_PlantSp_Clean<-Relative_Cover_PlantSp%>%
#change species codes to full species names
mutate(Genus_Species=ifelse(species=="ALDE","Alyssum.desertorum",ifelse(species=="ANOC","Androsace.occidentalis",ifelse(species=="ANPA","Antennaria.parvifolia", ifelse(species=="ARDR","Artemisia.dracunculus",ifelse(species=="ARFR","Artemisia.frigida",ifelse(species=="ARPU","Aristida.purpurea",ifelse(species=="ASGR","Astragalus.gracilis",ifelse(species=="ASPU","Astragalus.purshii",ifelse(species=="BODA","Bouteloua.dactyloides",ifelse(species=="BOGR" ,"Bouteloua.gracilis",ifelse(species=="BRAR","Bromus.arvensis",ifelse(species=="BRTE","Bromus.tectorum",ifelse(species=="CADU","Carex.duriuscula",ifelse(species=="CAFI","Carex.filifolia",ifelse(species=="CHPR","Chenopodium.pratericola",ifelse(species=="COCA","Conyza.canadensis",ifelse(species=="DEPI","Descurainia.pinnata",ifelse(species=="HECO","Hesperostipa.comata",ifelse(species=="VUOC","Vulpia.octoflora",ifelse(species=="KOMA","Koeleria.macrantha",ifelse(species=="LOAR","Logfia.arvensis",ifelse(species=="LYJU","Lygodesmia.juncea",ifelse(species=="DRRE","Draba.reptans",ifelse(species=="HEHI","Hedeoma.hispida",ifelse(species=="LEDE","Lepidium.densiflorum",ifelse(species=="LIIN","Lithospermum.incisum",ifelse(species=="LIPU","Liatris.punctata",ifelse(species=="PEES","Pediomelum.esculentum", ifelse(species=="SPCR","Sporobolus.cryptandrus",ifelse(species=="POSE","Poa.secunda",ifelse(species=="SPCO","Sphaeralcea.coccinea",ifelse(species=="TRDU","Tragopogon.dubius",ifelse(species=="TAOF","Taraxacum.officinale",ifelse(species=="OESU","Oenotherea.suffrutescens", ifelse(species=="PASM","Pascopyrum.smithii",ifelse(species=="PLPA","Plantago.patagonica",ifelse(species== "OPPO","Opuntia.polyacantha",ifelse(species=="DECA","Dalea.candida",species))))))))))))))))))))))))))))))))))))))) %>%
dplyr::select(block,plot,grazing_treatment,Genus_Species,Relative_Cover) %>%
unique()
#Merge Relative Cover data and functional group data
RelCov_FunctionalGroups<-Relative_Cover_PlantSp_Clean %>%
full_join(Functional_Groups, relationship="many-to-many") %>%
filter(Relative_Cover!="NA")
#### Arthropod Abundance (Weight): Plot Level ####
#Summing all weights by order within dataset, grazing treatment, block, and plot so that we can look at differences in order across plots
Weight_Data_Summed<-aggregate(Dry_Weight_g~Coll_Year_Bl_Trt+Plot+Correct_Order, data=Weight_Data_Official, FUN=sum, na.rm=FALSE)
#Separating out Treatment_Plot into all distinctions again so that we can group based on different things
Weight_Data_Summed<-Weight_Data_Summed %>%
separate(Coll_Year_Bl_Trt, c("Collection_Method","Year","Block","Grazing_Treatment"), "_")
#create dataframe that just has dvac samples in it
Weight_Data_Summed_dvac<-Weight_Data_Summed %>%
filter(Collection_Method=="dvac") %>%
filter(Plot!="NA") %>%
#sum by plot
group_by(Year,Block,Grazing_Treatment,Plot) %>%
summarise(Plot_Weight=sum(Dry_Weight_g)) %>%
ungroup()
Weight_by_Grazing_dvac<-Weight_Data_Summed_dvac %>%
group_by(Year,Grazing_Treatment) %>%
summarise(Average_Weight=mean(Plot_Weight),Weight_SD=sd(Plot_Weight),Weight_n=length(Plot_Weight)) %>%
mutate(Weight_St_Error=Weight_SD/sqrt(Weight_n)) %>%
ungroup()%>%
mutate(Correct_Order="Plot")
### Order Abundance (Weight): Plot Level ###
Weight_by_Order_Dvac<-Weight_Data_Summed %>%
filter(Correct_Order!="Unknown_1") %>%
filter(Correct_Order!="Unknown") %>%
filter(Correct_Order!="unknown") %>%
filter(Correct_Order!="Snail") %>%
filter(Correct_Order!="Body_Parts") %>%
filter(Correct_Order!="Body Parts") %>%
filter(Plot!="NA") %>%
spread(key=Correct_Order,value=Dry_Weight_g, fill=0) %>%
gather(key="Correct_Order","Dry_Weight_g",6:15) %>%
group_by(Collection_Method,Year, Grazing_Treatment, Correct_Order) %>%
summarise(Average_Weight=mean(Dry_Weight_g),Weight_SD=sd(Dry_Weight_g),Weight_n=length(Dry_Weight_g)) %>%
mutate(Weight_St_Error=Weight_SD/sqrt(Weight_n)) %>%
ungroup() %>%
#make a new column with new name for calculation below
mutate(Orthoptera_Order_Weight=Average_Weight)
### Merge together Weight_by_Grazing_dvac and Weight_by_Order_Dvac to make dataframe for graph with total weight average across plots stacked with amount of that weight that is orthoptera
#Create a new dataframe for plot weight - grasshopper weight for graph below
Weight_Plot_Minus_Orthoptera <-Weight_by_Order_Dvac %>%
#only want grasshopper abundance
filter(Correct_Order=="Orthoptera") %>%
select(Year,Grazing_Treatment,Orthoptera_Order_Weight) %>%
left_join(Weight_by_Grazing_dvac) %>%
mutate(NonOrtho_Plot_Weight=Average_Weight-Orthoptera_Order_Weight) %>%
select(Year,Grazing_Treatment,Correct_Order,NonOrtho_Plot_Weight,Weight_SD,Weight_n,Weight_St_Error) %>%
rename(Average_Weight=NonOrtho_Plot_Weight)
Weight_Total_Order<-Weight_by_Order_Dvac %>%
select(Year,Grazing_Treatment,Correct_Order,Average_Weight,Weight_SD,Weight_n,Weight_St_Error) %>%
filter(Correct_Order=="Orthoptera") %>%
rbind(Weight_Plot_Minus_Orthoptera)
### Average Abundance (Count) plot level####
Abundance_Plot_Orthoptera_Avg<-Abundance_Plot_Orthoptera %>%
rename(OrthopteraAbundance=Abundance) %>%
#add a row for plot 43 which has no orthoptera
add_row(Collection_Method = "dvac", Year=2022, Block = "3", Grazing_Treatment="HG",Plot=43, OrthopteraAbundance=0) %>%
group_by(Year,Grazing_Treatment) %>%
summarise(Average_Plot_Abundance=mean(OrthopteraAbundance),Plot_Abundance_SD=sd(OrthopteraAbundance),Plot_Abundance_n=length(OrthopteraAbundance)) %>%
mutate(Plot_Abundance_St_Error=Plot_Abundance_SD/sqrt(Plot_Abundance_n)) %>%
ungroup() %>%
mutate(Correct_Order="Orthoptera")
Abundance_by_Grazing_Avg<-Abundance_Plot %>%
group_by(Year,Grazing_Treatment) %>%
summarise(Average_Plot_Abundance=mean(Plot_Abundance),Plot_Abundance_SD=sd(Plot_Abundance),Plot_Abundance_n=length(Plot_Abundance)) %>%
mutate(Plot_Abundance_St_Error=Plot_Abundance_SD/sqrt(Plot_Abundance_n)) %>%
ungroup() %>%
mutate(Correct_Order="Plot")
Abundance_Plot_Minus_Orthoptera <-Abundance_Plot_Orthoptera_Avg %>%
rename(AvgOrthopteraAbundance=Average_Plot_Abundance) %>%
select(Year,Grazing_Treatment,AvgOrthopteraAbundance) %>%
left_join(Abundance_by_Grazing_Avg) %>%
mutate(NonOrtho_Plot_Abundance=Average_Plot_Abundance-AvgOrthopteraAbundance) %>%
select(Year,Grazing_Treatment,Correct_Order,NonOrtho_Plot_Abundance,Plot_Abundance_SD,Plot_Abundance_n,Plot_Abundance_St_Error) %>%
rename(Average_Plot_Abundance=NonOrtho_Plot_Abundance)
Abundance_Total_Order<-Abundance_Plot_Orthoptera_Avg %>%
select(Year,Grazing_Treatment,Correct_Order,Average_Plot_Abundance,Plot_Abundance_SD,Plot_Abundance_n,Plot_Abundance_St_Error) %>%
rbind(Abundance_Plot_Minus_Orthoptera)
##reorder bar graphs##
Weight_by_Grazing_dvac$Grazing_Treatment <- factor(Weight_by_Grazing_dvac$Grazing_Treatment, levels = c("NG", "LG", "HG"))
Abundance_by_Grazing_Avg$Grazing_Treatment <- factor(Abundance_by_Grazing_Avg$Grazing_Treatment, levels = c("NG", "LG", "HG"))
#### Total Plot Weight Differences - Figures ####
# 2020 - Dvac
#Graph of Weights from Sweep Net by Grazing treatment- 2020
Dvac_2020_Plot<-ggplot(subset(Weight_by_Grazing_dvac,Year==2020),aes(x=Grazing_Treatment,y=Average_Weight,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Average_Weight-Weight_St_Error,ymax=Average_Weight+Weight_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Plot Weight (g)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=0.5)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=0.5, label="2020 Weight",size=20)
# 2021 - Dvac
#Graph of Weights from dvac by Grazing treatment- 2021
Dvac_2021_Plot<-ggplot(subset(Weight_by_Grazing_dvac,Year==2021),aes(x=Grazing_Treatment,y=Average_Weight,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Average_Weight-Weight_St_Error,ymax=Average_Weight+Weight_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Plot Weight (g)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(axis.title.y=element_blank(),legend.position = "none")+
#Make the y-axis extend to 50
expand_limits(y=0.2)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=0.2, label="2021 Weight",size=20)
# 2022 - Dvac
#Graph of Weights from dvac by Grazing treatment- 2021
Dvac_2022_Plot<-ggplot(subset(Weight_by_Grazing_dvac,Year==2022),aes(x=Grazing_Treatment,y=Average_Weight,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Average_Weight-Weight_St_Error,ymax=Average_Weight+Weight_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Plot Weight (g)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(axis.title.y=element_blank(),legend.position = "none")+
#Make the y-axis extend to 50
expand_limits(y=0.1)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=0.1, label="2022 Weight",size=20)
#### Create Average Plot Weight Figure ####
Dvac_2020_Plot+
Dvac_2021_Plot+
Dvac_2022_Plot+
plot_layout(ncol = 3,nrow = 1)
#Save at 4500x2000
#### Abundance by Count Figure ####
#Graph of Plot_Abundances from Dvac by Grazing treatment- 2020
Count_2020_Plot<-ggplot(subset(Abundance_by_Grazing_Avg,Year==2020),aes(x=Grazing_Treatment,y=Average_Plot_Abundance,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Average_Plot_Abundance-Plot_Abundance_St_Error,ymax=Average_Plot_Abundance+Plot_Abundance_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Plot Count")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=25)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=25, label="2020 Count",size=20)
# 2021 - Dvac
#Graph of Plot_Abundances from dvac by Grazing treatment- 2021
Count_2021_Plot<-ggplot(subset(Abundance_by_Grazing_Avg,Year==2021),aes(x=Grazing_Treatment,y=Average_Plot_Abundance,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Average_Plot_Abundance-Plot_Abundance_St_Error,ymax=Average_Plot_Abundance+Plot_Abundance_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Plot Count")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(axis.title.y=element_blank(),legend.position = "none")+
#Make the y-axis extend to 50
expand_limits(y=25)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=25, label="2021 Count",size=20)
# 2022 - Dvac
#Graph of Plot_Abundances from dvac by Grazing treatment- 2021
Count_2022_Plot<-ggplot(subset(Abundance_by_Grazing_Avg,Year==2022),aes(x=Grazing_Treatment,y=Average_Plot_Abundance,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Average_Plot_Abundance-Plot_Abundance_St_Error,ymax=Average_Plot_Abundance+Plot_Abundance_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Plot Count")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(axis.title.y=element_blank(),legend.position = "none")+
#Make the y-axis extend to 50
expand_limits(y=300)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=300, label="2022 Count",size=20)
#### Create Average Plot Weight Figure ####
Count_2020_Plot+
Count_2021_Plot+
Count_2022_Plot+
plot_layout(ncol = 3,nrow = 1)
#Save at 4500x2000
#### Normality: Plot Weights####
# Dvac 2020
dvac_2020_Weight <- lm(data = subset(Weight_Data_Summed_dvac, Year == 2020), sqrt(Plot_Weight) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2020_Weight)
ols_test_normality(dvac_2020_Weight) #normal
# dvac 2021
dvac_2021_Weight <- lm(data = subset(Weight_Data_Summed_dvac, Year == 2021), log(Plot_Weight) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2021_Weight)
ols_test_normality(dvac_2021_Weight) #normal
# dvac 2022
dvac_2022_Weight <- lm(data = subset(Weight_Data_Summed_dvac, Year == 2022), log(Plot_Weight) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2022_Weight)
ols_test_normality(dvac_2022_Weight) #normal
#### Glmm for Plot Weights by Grazing Treatment####
# 2020 Dvac
Plot_Weight_D_2020_Glmm <- lmer(sqrt(Plot_Weight) ~ Grazing_Treatment + (1 | Block) , data = subset(Weight_Data_Summed_dvac,Year==2020))
anova(Plot_Weight_D_2020_Glmm) #not significant
# 2021 Dvac
Plot_Weight_D_2021_Glmm <- lmer(log(Plot_Weight) ~ Grazing_Treatment + (1 | Block) , data = subset(Weight_Data_Summed_dvac,Year==2021))
anova(Plot_Weight_D_2021_Glmm) # p=0.003987
###post hoc test for lmer test ##
summary(glht(Plot_Weight_D_2021_Glmm, linfct = mcp(Grazing_Treatment = "Tukey")), test = adjusted(type = "BH")) #NG-LG (p=0.0.56774), #LG-HG (0.00857), NG-HG (0.00256)
# 2022 Dvac
Plot_Weight_D_2022_Glmm <- lmer(log(Plot_Weight) ~ Grazing_Treatment + (1 | Block) , data = subset(Weight_Data_Summed_dvac,Year==2022))
anova(Plot_Weight_D_2022_Glmm) #not significant
#### Normality: Plot Count####
# Dvac 2020
dvac_2020_count <- lm(data = subset(Abundance_Plot, Year == 2020), log(Plot_Abundance) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2020_count)
ols_test_normality(dvac_2020_count) #normal
# dvac 2021
dvac_2021_count <- lm(data = subset(Abundance_Plot, Year == 2021), log(Plot_Abundance) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2021_count)
ols_test_normality(dvac_2021_count) #normal
# dvac 2022
dvac_2022_count <- lm(data = subset(Abundance_Plot, Year == 2022), log(Plot_Abundance) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2022_count)
ols_test_normality(dvac_2022_count) #normal
#### Glmm for Plot Count by Grazing Treatment####
# 2020 Dvac
Count_2020_Glmm <- lmer(log(Plot_Abundance) ~ Grazing_Treatment + (1 | Block) , data = subset(Abundance_Plot,Year==2020))
anova(Count_2020_Glmm) #not significant
# 2021 Dvac
Count_2021_Glmm <- lmer(log(Plot_Abundance) ~ Grazing_Treatment + (1 | Block) , data = subset(Abundance_Plot,Year==2021))
anova(Count_2021_Glmm) #0.02996
###post hoc test for lmer test ##
summary(glht(Count_2021_Glmm, linfct = mcp(Grazing_Treatment = "Tukey")), test = adjusted(type = "BH")) #NG-LG (p=0.0.2455, #LG-HG (0.1655), NG-HG (0.0175)
# 2022 Dvac
Count_2022_Glmm <- lmer(log(Plot_Abundance) ~ Grazing_Treatment + (1 | Block) , data = subset(Abundance_Plot,Year==2022))
anova(Count_2022_Glmm) #0.0119
###post hoc test for lmer test ##
summary(glht(Count_2022_Glmm, linfct = mcp(Grazing_Treatment = "Tukey")), test = adjusted(type = "BH")) #NG-LG (p=0.06767, #LG-HG (0.00568), NG-HG (0.27006)
#### Graphs: Plot Weight with Grasshoppers Hatched ####
Weight_Plot_WGrasshoppers_2020<-ggplot(subset(Weight_Total_Order,Year==2020),aes(x=Grazing_Treatment,y=Average_Weight, pattern=Correct_Order,fill=Correct_Order, position = "stack"))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity",position = position_stack(reverse = TRUE),color="black")+
geom_col_pattern(aes(Grazing_Treatment,Average_Weight, pattern_fill = Correct_Order),pattern = c('stripe','stripe','stripe','none','none','none'),fill= 'grey20', colour = 'grey20',position = position_stack(reverse = TRUE),pattern_alpha = 0.6) +
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(data=subset(Weight_by_Grazing_dvac, Year==2020),aes(ymin=Average_Weight-Weight_St_Error,ymax=Average_Weight+Weight_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Plot Weight (g)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
#scale_fill_manual(values=c("grey30","grey10"), labels=c("Orthoptera Weight","Plot Weight"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=0.5)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=0.5, label="2020 Weight",size=20)
Weight_Plot_WGrasshoppers_2021<-ggplot(subset(Weight_Total_Order,Year==2021),aes(x=Grazing_Treatment,y=Average_Weight, pattern=Correct_Order,fill=Correct_Order, position = "stack"))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity",position = position_stack(reverse = TRUE),color="black")+
geom_col_pattern(aes(Grazing_Treatment,Average_Weight, pattern_fill = Correct_Order),pattern = c('stripe','stripe','stripe','none','none','none'),fill= 'grey20', colour = 'grey20',position = position_stack(reverse = TRUE),pattern_alpha = 0.6) +
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(data=subset(Weight_by_Grazing_dvac, Year==2021),aes(ymin=Average_Weight-Weight_St_Error,ymax=Average_Weight+Weight_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Plot Weight (g)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
#scale_fill_manual(values=c("grey30","grey10"), labels=c("Orthoptera Weight","Plot Weight"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=0.2)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=0.2, label="2021 Weight",size=20)
Weight_Plot_WGrasshoppers_2022<-ggplot(subset(Weight_Total_Order,Year==2022),aes(x=Grazing_Treatment,y=Average_Weight, pattern=Correct_Order,fill=Correct_Order, position = "stack"))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity",position = position_stack(reverse = TRUE),color="black")+
geom_col_pattern(aes(Grazing_Treatment,Average_Weight, pattern_fill = Correct_Order),pattern = c('stripe','stripe','stripe','none','none','none'),fill= 'grey20', colour = 'grey20',position = position_stack(reverse = TRUE),pattern_alpha = 0.6) +
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(data=subset(Weight_by_Grazing_dvac, Year==2022),aes(ymin=Average_Weight-Weight_St_Error,ymax=Average_Weight+Weight_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Plot Weight (g)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
#scale_fill_manual(values=c("grey30","grey10"), labels=c("Orthoptera Weight","Plot Weight"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=0.1)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=0.1, label="2022 Weight",size=20)
#### Create Average Plot Weight Figure ####
Weight_Plot_WGrasshoppers_2020+
Weight_Plot_WGrasshoppers_2021+
Weight_Plot_WGrasshoppers_2022+
plot_layout(ncol = 3,nrow = 1)
#Save at 4500x2000
#### Graphs: Plot Count with Grasshoppers Hatched ####
Count_WGrasshoppers_2020<-ggplot(subset(Abundance_Total_Order,Year==2020),aes(x=Grazing_Treatment,y=Average_Plot_Abundance, pattern=Correct_Order,fill=Correct_Order, position = "stack"))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity",position = position_stack(reverse = TRUE),color="black")+
geom_col_pattern(aes(Grazing_Treatment,Average_Plot_Abundance, pattern_fill = Correct_Order),pattern = c('stripe','stripe','stripe','none','none','none'),fill= 'grey20', colour = 'grey20',position = position_stack(reverse = TRUE),pattern_alpha = 0.6) +
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(data=subset(Abundance_by_Grazing_Avg, Year==2020),aes(ymin=Average_Plot_Abundance-Plot_Abundance_St_Error,ymax=Average_Plot_Abundance+Plot_Abundance_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Plot Weight (g)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
#scale_fill_manual(values=c("grey30","grey10"), labels=c("Orthoptera Weight","Plot Weight"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=25)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=25, label="2020 Count",size=20)
Count_WGrasshoppers_2021<-ggplot(subset(Abundance_Total_Order,Year==2021),aes(x=Grazing_Treatment,y=Average_Plot_Abundance, pattern=Correct_Order,fill=Correct_Order, position = "stack"))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity",position = position_stack(reverse = TRUE),color="black")+
geom_col_pattern(aes(Grazing_Treatment,Average_Plot_Abundance, pattern_fill = Correct_Order),pattern = c('stripe','stripe','stripe','none','none','none'),fill= 'grey20', colour = 'grey20',position = position_stack(reverse = TRUE),pattern_alpha = 0.6) +
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(data=subset(Abundance_by_Grazing_Avg, Year==2021),aes(ymin=Average_Plot_Abundance-Plot_Abundance_St_Error,ymax=Average_Plot_Abundance+Plot_Abundance_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Plot Weight (g)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
#scale_fill_manual(values=c("grey30","grey10"), labels=c("Orthoptera Weight","Plot Weight"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=20)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=20, label="2021 Count",size=20)
Count_WGrasshoppers_2022<-ggplot(subset(Abundance_Total_Order,Year==2022),aes(x=Grazing_Treatment,y=Average_Plot_Abundance, pattern=Correct_Order,fill=Correct_Order, position = "stack"))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity",position = position_stack(reverse = TRUE),color="black")+
geom_col_pattern(aes(Grazing_Treatment,Average_Plot_Abundance, pattern_fill = Correct_Order),pattern = c('stripe','stripe','stripe','none','none','none'),fill= 'grey20', colour = 'grey20',position = position_stack(reverse = TRUE),pattern_alpha = 0.6) +
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(data=subset(Abundance_by_Grazing_Avg, Year==2022),aes(ymin=Average_Plot_Abundance-Plot_Abundance_St_Error,ymax=Average_Plot_Abundance+Plot_Abundance_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Plot Weight (g)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
#scale_fill_manual(values=c("grey30","grey10"), labels=c("Orthoptera Weight","Plot Weight"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=250)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=250, label="2022 Count",size=20)
#### Create Average Plot Weight Figure ####
Count_WGrasshoppers_2020 +
Count_WGrasshoppers_2021 +
Count_WGrasshoppers_2022 +
plot_layout(ncol = 3,nrow = 1)
#Save at 4500x2000
#### Order Relative Weight ####
Relative_Weight<-Weight_Data_Summed %>%
filter(Plot!="NA") %>%
#add together all data of each orders across grazing treatments
group_by(Year,Grazing_Treatment,Correct_Order) %>%
mutate(Order_Weight=sum(Dry_Weight_g)) %>%
ungroup() %>%
#add together all data within each grazing treatment for total "plot" weight
group_by(Year,Grazing_Treatment) %>%
mutate(Total_Weight=sum(Dry_Weight_g)) %>%
ungroup() %>%
select(Year,Grazing_Treatment,Correct_Order,Order_Weight,Total_Weight) %>%
unique() %>%
filter(Correct_Order!="unknown"&Correct_Order!="Unknown"&Correct_Order!="Unknown_1"&Correct_Order!="Body_Parts"&Correct_Order!="Body Parts") %>%
mutate(RelativeWeight=Order_Weight/Total_Weight*100) %>%
group_by(Year,Grazing_Treatment,Correct_Order) %>%
summarise(Average_RelativeWeight=mean(RelativeWeight)) %>%
ungroup()
#### Order Relative Weight Plot ####
Order_2020<-ggplot(subset(Relative_Weight,Year==2020),aes(x=Grazing_Treatment,y=Average_RelativeWeight,fill=Correct_Order, position = "stack"))+
geom_bar(stat="identity")+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Relative Weight (g)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("#661100","#CC6677","#DDCC77","#2D7947", "#4B4084","#76948F"), labels=c("Araneae","Coleoptera","Diptera","Hemiptera","Hymenoptera","Orthoptera"), name = "Order")+
#scale_fill_manual(values=c("grey30","grey10"), labels=c("Orthoptera Weight","Plot Weight"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=100)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=100, label="2020",size=20)
Order_2021<-ggplot(subset(Relative_Weight,Year==2021),aes(x=Grazing_Treatment,y=Average_RelativeWeight,fill=Correct_Order, position = "stack"))+
geom_bar(stat="identity")+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Relative Weight (g)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("#661100","#CC6677","#DDCC77","#2D7947", "#4B4084","#76948F"), labels=c("Araneae","Coleoptera","Diptera","Hemiptera","Hymenoptera","Orthoptera"), name = "Order")+
#scale_fill_manual(values=c("grey30","grey10"), labels=c("Orthoptera Weight","Plot Weight"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=100)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=100, label="2021",size=20)
Order_2022<-ggplot(subset(Relative_Weight,Year==2022),aes(x=Grazing_Treatment,y=Average_RelativeWeight,fill=Correct_Order, position = "stack"))+
geom_bar(stat="identity")+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Relative Weight (g)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("#661100","#CC6677","#DDCC77","#2D7947", "#4B4084","#7E69A0","#6B99C7","#76948F","#7B4B4E","#BCB9EC"), labels=c("Araneae","Coleoptera","Diptera","Hemiptera","Hymenoptera","Lepidoptera","Neuroptera","Orthoptera","Thysanoptera","Trombiculidae"), name = "Order")+
#scale_fill_manual(values=c("grey30","grey10"), labels=c("Orthoptera Weight","Plot Weight"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=100)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=100, label="2022",size=20)
#### Create Relative Weight Figure ####
Order_2020 +
Order_2021+
Order_2022 +
plot_layout(ncol = 3,nrow = 1)
#save at 4500 x 2000
#### Order Relative Count ####
Relative_Count<-Abundance %>%
filter(Plot!="NA") %>%
select(Year,Block,Grazing_Treatment,Plot,Correct_Order,Abundance) %>%
unique() %>%
#add together all data of each orders across grazing treatments
group_by(Year,Grazing_Treatment,Correct_Order) %>%
mutate(Order_Abundance=sum(Abundance)) %>%
ungroup() %>%
#add together all data within each grazing treatment for total "plot"count
group_by(Year,Grazing_Treatment) %>%
mutate(Total_Abundance=sum(Abundance)) %>%
ungroup() %>%
select(Year,Grazing_Treatment,Correct_Order,Order_Abundance,Total_Abundance) %>%
unique() %>%
filter(Correct_Order!="unknown"&Correct_Order!="Unknown"&Correct_Order!="Unknown_1"&Correct_Order!="Body_Parts"&Correct_Order!="Body Parts") %>%
mutate(RelativeCount=Order_Abundance/Total_Abundance*100) %>%
group_by(Year,Grazing_Treatment,Correct_Order) %>%
summarise(Average_RelativeCount=mean(RelativeCount)) %>%
ungroup()
#### Order Relative Count Plot ####
Order_Count_2020<-ggplot(subset(Relative_Count,Year==2020),aes(x=Grazing_Treatment,y=Average_RelativeCount,fill=Correct_Order, position = "stack"))+
geom_bar(stat="identity")+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Relative Count")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("#661100","#CC6677","#DDCC77","#2D7947", "#4B4084","#76948F"), labels=c("Araneae","Coleoptera","Diptera","Hemiptera","Hymenoptera","Orthoptera"), name = "Order")+
#scale_fill_manual(values=c("grey30","grey10"), labels=c("Orthoptera Count","Plot Count"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=100)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=100, label="2020 Count",size=20)
Order_Count_2021<-ggplot(subset(Relative_Count,Year==2021),aes(x=Grazing_Treatment,y=Average_RelativeCount,fill=Correct_Order, position = "stack"))+
geom_bar(stat="identity")+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Relative Count (g)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("#661100","#CC6677","#DDCC77","#2D7947", "#4B4084","#76948F"), labels=c("Araneae","Coleoptera","Diptera","Hemiptera","Hymenoptera","Orthoptera"), name = "Order")+
#scale_fill_manual(values=c("grey30","grey10"), labels=c("Orthoptera Count","Plot Count"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=100)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=100, label="2021 Count",size=20)
Order_Count_2022<-ggplot(subset(Relative_Count,Year==2022),aes(x=Grazing_Treatment,y=Average_RelativeCount,fill=Correct_Order, position = "stack"))+
geom_bar(stat="identity")+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Relative Count (g)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("#661100","#CC6677","#DDCC77","#2D7947", "#4B4084","#7E69A0","#6B99C7","#76948F","#7B4B4E","#BCB9EC"), labels=c("Araneae","Coleoptera","Diptera","Hemiptera","Hymenoptera","Lepidoptera","Neuroptera","Orthoptera","Thysanoptera","Trombiculidae"), name = "Order")+
#scale_fill_manual(values=c("grey30","grey10"), labels=c("Orthoptera Count","Plot Count"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=100)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=100, label="2022 Count",size=20)
#### Create Relative Count Figure ####
Order_Count_2020 +
Order_Count_2021+
Order_Count_2022 +
plot_layout(ncol = 3,nrow = 1)
#save at 4500 x 2000
#### Total Plot Weight Differences by Order - Figures ####
#Colors:
#Aranea: #661100
#Coleoptera: #CC6677
#Diptera: #DDCC77
#Hemiptera:#2D7947
#Hymenoptera: #4B4084
#Orthoptera:#76948F
#Lepidoptera:#7E69A0
#Neuroptera:#6B99C7
#Thysanoptera:#7B4B4E
#Trombiculidae:#BCB9EC
#2020 - dvac
Dvac_2020_Order<-ggplot(subset(Weight_by_Order_Dvac,Year==2020),aes(x=Grazing_Treatment,y=Average_Weight, fill=Correct_Order, position="stack"))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Weight (g)")+
theme(legend.background=element_blank())+
scale_fill_manual(values=c("#661100","#CC6677","#DDCC77","#2D7947", "#4B4084","#7E69A0","#6B99C7","#76948F","#7B4B4E","#BCB9EC"), labels=c("Araneae","Coleoptera","Diptera","Hemiptera","Hymenoptera","Lepidoptera","Neuroptera","Orthoptera","Thysanoptera","Trombiculidae"), name = "Order")+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"), legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=0.3)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.position = "NONE")+
geom_text(x=1.1, y=0.3, label="2020 Dvac",size=20)
#2021 - Dvac
Dvac_2021_Order<-ggplot(subset(Weight_by_Order_Dvac,Year==2021),aes(x=Grazing_Treatment,y=Average_Weight, fill=Correct_Order, position="stack"))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Weight (g)")+
theme(legend.background=element_blank())+
scale_fill_manual(values=c("#661100","#CC6677","#DDCC77","#2D7947", "#4B4084","#7E69A0","#6B99C7","#76948F","#7B4B4E","#BCB9EC"), labels=c("Araneae","Coleoptera","Diptera","Hemiptera","Hymenoptera","Lepidoptera","Neuroptera","Orthoptera","Thysanoptera","Trombiculidae"), name = "Order")+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"), legend.position=c(0.18,0.715))+
#Make the y-axis extend to 50
expand_limits(y=0.1)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.position = "NONE",axis.title.y=element_blank())+
geom_text(x=1.1, y=0.1, label="2021 Dvac",size=20)
#2022 - Dvac
Dvac_2022_Order<-ggplot(subset(Weight_by_Order_Dvac,Year==2022),aes(x=Grazing_Treatment,y=Average_Weight, fill=Correct_Order, position="stack"))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Weight (g)")+
theme(legend.background=element_blank())+
scale_fill_manual(values=c("#661100","#CC6677","#DDCC77","#2D7947", "#4B4084","#7E69A0","#6B99C7","#76948F","#7B4B4E","#BCB9EC"), labels=c("Araneae","Coleoptera","Diptera","Hemiptera","Hymenoptera","Lepidoptera","Neuroptera","Orthoptera","Thysanoptera","Trombiculidae"), name = "Order")+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"), legend.position=c(0.18,0.715))+
#Make the y-axis extend to 50
expand_limits(y=0.08)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.position = "NONE",axis.title.y=element_blank())+
geom_text(x=1.1, y=0.08, label="2022 Dvac",size=20)
#### Create Average Plot Weight Figure ####
Dvac_2020_Order+
Dvac_2021_Order+
Dvac_2022_Order+
plot_layout(ncol = 3,nrow = 1)
#Save at 4500x3000
#### Changes in Orthoptera genra by grazing treatment ####
Weight_Orthoptera<-Weight_Data_Official %>%
filter(Correct_Order=="Orthoptera") %>%
separate(Coll_Year_Bl_Trt, c("Collection_Method","Year","Block","Grazing_Treatment"), "_") %>%
na.omit() %>%
dplyr::select(-Notes)
Weight_Orthoptera$Year=as.numeric(Weight_Orthoptera$Year)
Weight_Orthoptera$Block=as.character(Weight_Orthoptera$Block)
Weight_Orthoptera$Plot=as.numeric(Weight_Orthoptera$Plot)
ID_Orthoptera<-ID_Data_Official %>%
filter(Correct_Order=="Orthoptera") %>%
dplyr::select(-Notes)
Weight_Orthoptera_Official<-merge(Weight_Orthoptera, ID_Orthoptera, by=c("Collection_Method","Year","Block","Grazing_Treatment","Plot","Sample_Number","Correct_Order"),all=TRUE) %>%
filter(Sample_Number!="5a" & Sample_Number!="5b" & Sample_Number!="2a" & Sample_Number!="2b") %>% # need to be removed because of error
na.omit() %>% #all NAs need to be removed from 2020,2021,2022 (double checked all)
filter(Correct_Family=="Acrididae")
#make dataframe with sum of each genus of orthoptera summed by plot
Weight_Orthoptera_Summed_D <- Weight_Orthoptera_Official %>%
group_by(Collection_Method, Year, Block, Grazing_Treatment,Plot,Correct_Genus) %>%
summarise(Genus_Weight=sum(Dry_Weight_g)) %>%
ungroup()
#Sweepnet
#make table a graph looking at differences in genus weight by grazing treatment
Weight_Orthoptera_Avg_D<-Weight_Orthoptera_Summed_D %>%
group_by(Year,Grazing_Treatment,Correct_Genus) %>%
summarise(Average_Weight=mean(Genus_Weight),Weight_SD=sd(Genus_Weight),Weight_n=length(Genus_Weight)) %>%
#Make a new column called "Richness_St_Error" and divide "Richness_Std" by the square root of "Richness_n"
mutate(Weight_St_Error=Weight_SD/sqrt(Weight_n)) %>%
ungroup()
#### Orthoptera Genus Colors ####
#Ageneotettix "#661100"
#Amphiturnus "#CC6677"
#Arphia "#DDCC77"
#Chorthippus "#6699CC"
#Dissosteira #556F2E
#Eritettix #673F3F
#Melanoplus "#117733"
#Opeia "#332288"
#Phoetaliotes "#44AA99"
#Pseudopomala #7B66D9
#2020 - Dvac
Dvac_2020_Orthoptera<-ggplot(subset(Weight_Orthoptera_Avg_D,Year==2020),aes(x=Grazing_Treatment,y=Average_Weight, fill=Correct_Genus, position="stack"))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Weight (g)")+
theme(legend.background=element_blank())+
scale_fill_manual(values=c("#661100","#CC6677","#DDCC77","#673F3F", "#117733","#332288", "#44AA99","#7B66D9"), labels=c("Ageneotettix","Amphiturnus","Arphia","Eritettix", "Melanoplus","Opeia","Phoetaliotes"), name = "Genus")+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"), legend.position=c(0.18,0.715))+
#Make the y-axis extend to 50
expand_limits(y=0.5)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45),legend.position="none")+
geom_text(x=1.3, y=0.5, label="2020 Dvac",size=20)
#2021 - Dvac
Dvac_2021_Orthoptera<-ggplot(subset(Weight_Orthoptera_Avg_D,Year==2021),aes(x=Grazing_Treatment,y=Average_Weight, fill=Correct_Genus, position="stack"))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Weight (g)")+
theme(legend.background=element_blank())+
scale_fill_manual(values=c("#661100","#DDCC77","#556F2E","#673F3F","#117733","#332288", "#44AA99"), labels=c("Ageneotettix","Arphia","Dissosteira","Erittix", "Melanoplus","Opeia","Phoetaliotes"), name = "Genus")+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"), legend.position=c(0.18,0.715))+
#Make the y-axis extend to 50
expand_limits(y=0.1)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.position = "NONE",axis.title.y=element_blank())+
geom_text(x=1.3, y=0.1, label="2021 Dvac",size=20)
Dvac_2022_Orthoptera<-ggplot(subset(Weight_Orthoptera_Avg_D,Year==2022),aes(x=Grazing_Treatment,y=Average_Weight, fill=Correct_Genus, position="stack"))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge), and fill in the bars with the color grey.
geom_bar(stat="identity")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Average Weight (g)")+
theme(legend.background=element_blank())+
scale_fill_manual(values=c("#661100","#DDCC77","#556F2E","#673F3F","#117733","#332288", "#44AA99"), labels=c("Ageneotettix","Arphia","Dissosteira","Erittix", "Melanoplus","Opeia","Phoetaliotes"), name = "Genus")+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"), legend.position=c(0.18,0.715))+
#Make the y-axis extend to 50
expand_limits(y=0.08)+
scale_y_continuous(labels = label_number(accuracy = 0.01))+
theme(text = element_text(size = 55),legend.position = "NONE",axis.title.y=element_blank())+
geom_text(x=1.3, y=0.08, label="2022 Dvac",size=20)
#### Create Average Plot Weight Figure Orthoptera####
Dvac_2020_Orthoptera+
Dvac_2021_Orthoptera+
Dvac_2022_Orthoptera+
plot_layout(ncol = 3,nrow = 1)
#Save at 4500x3000
#### Normality: Plot Weights by Orthoptera ####
# Dvac 2020
dvac_2020_Weight_Orthoptera <- lm(data = subset(Weight_Orthoptera_Summed_D, Year == 2020), log(Genus_Weight) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2020_Weight_Orthoptera)
ols_test_normality(dvac_2020_Weight_Orthoptera) #normalish
# dvac 2021
dvac_2021_Weight_Orthoptera <- lm(data = subset(Weight_Orthoptera_Summed_D, Year == 2021), sqrt(Genus_Weight) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2021_Weight_Orthoptera)
ols_test_normality(dvac_2021_Weight_Orthoptera) #normalish
# dvac 2022
dvac_2022_Weight_Orthoptera <- lm(data = subset(Weight_Orthoptera_Summed_D, Year == 2022), log(Genus_Weight) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2022_Weight_Orthoptera)
ols_test_normality(dvac_2022_Weight_Orthoptera) #normal
#### Glmm for Plot Weights by Grazing Treatment Orthoptera####
# 2020 Dvac
Plot_Weight_D_2020_Glmm_Orthoptera <- lmer(log(Genus_Weight) ~ Grazing_Treatment + (1 | Block) , data = subset(Weight_Orthoptera_Summed_D,Year==2020))
anova(Plot_Weight_D_2020_Glmm_Orthoptera) #not significant
# 2021 Dvac
Plot_Weight_D_2021_Glmm_Orthoptera <- lmer(sqrt(Genus_Weight) ~ Grazing_Treatment + (1 | Block) , data = subset(Weight_Orthoptera_Summed_D,Year==2021))
anova(Plot_Weight_D_2021_Glmm_Orthoptera) # p=0.05
## post hoc test for lmer test ##
summary(glht(Plot_Weight_D_2021_Glmm_Orthoptera, linfct = mcp(Grazing_Treatment = "Tukey")), test = adjusted(type = "BH")) #NG-LG (p=0.2833), #LG-HG (0.2113, NG-HG (0.0391)
# 2022 Dvac
Plot_Weight_D_2022_Glmm_Orthoptera <- lmer(log(Genus_Weight) ~ Grazing_Treatment + (1 | Block) , data = subset(Weight_Orthoptera_Summed_D,Year==2022))
anova(Plot_Weight_D_2022_Glmm_Orthoptera) #not significant
#### Calculate Community Metrics: Weight Abundance ####
# uses codyn package and finds shannon's diversity
Weight_Data_Summed_2<-Weight_Data_Summed %>%
filter(Plot!="NA")
Diversity_Weight <- community_diversity(df = Weight_Data_Summed_2,
time.var = "Year",
replicate.var = c("Collection_Method","Plot","Block","Grazing_Treatment"),
abundance.var = "Dry_Weight_g")
#Sweep Net Community Structure
Structure_Weight <- community_structure(df = Weight_Data_Summed_2,
time.var = "Year",
replicate.var = c("Collection_Method","Plot","Block","Grazing_Treatment"),
abundance.var = "Dry_Weight_g",
metric = "Evar")
#Make a new data frame from "Extra_Species_Identity" to generate richness values for each research area
Order_Richness_Weight<-ID_Data_Official %>%
select(Collection_Method,Year,Block,Grazing_Treatment,Plot,Correct_Order) %>%
unique() %>%
#group data frame by Watershed and exclosure
group_by(Collection_Method,Year,Block,Grazing_Treatment,Plot) %>%
#Make a new column named "Richness" and add the unique number of rows in the column "taxa" according to the groupings
summarise(richness=length(Correct_Order)) %>%
#stop grouping by watershed and exclosure
ungroup()
Order_Richness_Weight$Year=as.character(Order_Richness_Weight$Year)
Order_Richness_Weight$Plot=as.character(Order_Richness_Weight$Plot)
#join the datasets
CommunityMetrics_Weight <- Diversity_Weight %>%
full_join(Structure_Weight) %>%
select(-richness) %>%
full_join(Order_Richness_Weight)
#make dataframe with averages
CommunityMetrics_Weight_Avg<-CommunityMetrics_Weight %>%
group_by(Year,Grazing_Treatment) %>%
summarize(Richness_Std=sd(richness),Richness_Mean=mean(richness),Richness_n=length(richness),
Shannon_Std=sd(Shannon),Shannon_Mean=mean(Shannon),Shannon_n=length(Shannon),
Evar_Std=sd(Evar,na.rm=T),Evar_Mean=mean(Evar,na.rm=T),Evar_n=length(Evar))%>%
mutate(Richness_St_Error=Richness_Std/sqrt(Richness_n),
Shannon_St_Error=Shannon_Std/sqrt(Shannon_n),
Evar_St_Error=Evar_Std/sqrt(Evar_n)) %>%
ungroup()
#### Calculate Community Metrics: Count Abundance ####
# uses codyn package and finds shannon's diversity
Diversity_Count <- community_diversity(df = Abundance,
time.var = "Year",
replicate.var = c("Collection_Method","Plot","Block","Grazing_Treatment"),
abundance.var = "Abundance")
#Sweep Net Community Structure
Structure_Count <- community_structure(df = Abundance,
time.var = "Year",
replicate.var = c("Collection_Method","Plot","Block","Grazing_Treatment"),
abundance.var = "Abundance",
metric = "Evar")
#Make a new data frame from "Extra_Species_Identity" to generate richness values for each research area
Order_Richness_Count<-ID_Data_Official %>%
select(Collection_Method,Year,Block,Grazing_Treatment,Plot,Correct_Order) %>%
unique() %>%
#group data frame by Watershed and exclosure
group_by(Collection_Method,Year,Block,Grazing_Treatment,Plot) %>%
#Make a new column named "Richness" and add the unique number of rows in the column "taxa" according to the groupings
summarise(richness=length(Correct_Order)) %>%
#stop grouping by watershed and exclosure
ungroup()
#join the datasets
CommunityMetrics_Count <- Diversity_Count %>%
full_join(Structure_Count) %>%
select(-richness) %>%
full_join(Order_Richness_Count)
#make dataframe with averages
CommunityMetrics_Count_Avg<-CommunityMetrics_Count %>%
group_by(Collection_Method,Year,Grazing_Treatment) %>%
summarize(Richness_Std=sd(richness),Richness_Mean=mean(richness),Richness_n=length(richness),
Shannon_Std=sd(Shannon),Shannon_Mean=mean(Shannon),Shannon_n=length(Shannon),
Evar_Std=sd(Evar),Evar_Mean=mean(Evar),Evar_n=length(Evar))%>%
mutate(Richness_St_Error=Richness_Std/sqrt(Richness_n),
Shannon_St_Error=Shannon_Std/sqrt(Shannon_n),
Evar_St_Error=Evar_Std/sqrt(Evar_n)) %>%
ungroup()
#### Plot Richness ####
# 2020 - Dvac
Richness_Count_2020<-ggplot(subset(CommunityMetrics_Count_Avg,Year==2020 & Collection_Method=="dvac"),aes(x=Grazing_Treatment,y=Richness_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Richness_Mean-Richness_St_Error,ymax=Richness_Mean+Richness_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Order Richness")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=10)+
scale_y_continuous(labels = label_number(accuracy = 1))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=10, label="2020 Count",size=20)
# 2021 - Dvac
#Graph of Weights from dvac by Grazing treatment- 2021
Richness_Count_2021<-ggplot(subset(CommunityMetrics_Count_Avg,Year==2021 & Collection_Method=="dvac"),aes(x=Grazing_Treatment,y=Richness_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Richness_Mean-Richness_St_Error,ymax=Richness_Mean+Richness_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Richness")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(axis.title.y=element_blank(),axis.text.y=element_blank(),legend.position = "none")+
#Make the y-axis extend to 50
expand_limits(y=10)+
scale_y_continuous(labels = label_number(accuracy = 1))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=10, label="2021 Count",size=20)
# 2022 - Dvac
Richness_Count_2022<-ggplot(subset(CommunityMetrics_Count_Avg,Year==2022 & Collection_Method=="dvac"),aes(x=Grazing_Treatment,y=Richness_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Richness_Mean-Richness_St_Error,ymax=Richness_Mean+Richness_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Richness")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(axis.title.y=element_blank(),legend.position = "none",axis.text.y=element_blank())+
#Make the y-axis extend to 50
expand_limits(y=10)+
scale_y_continuous(labels = label_number(accuracy = 1))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=10, label="2022 Count",size=20)
#### Create Order Richness Figure ####
Richness_Count_2020+
Richness_Count_2021+
Richness_Count_2022+
plot_layout(ncol = 3,nrow = 1)
#Save at 4000x2000
#### Normality: Order Richness ####
# Dvac 2020
dvac_2020_OrderRichness <- lm(data = subset(CommunityMetrics, Year == 2020 & Collection_Method=="dvac"),log(richness) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2020_OrderRichness)
ols_test_normality(dvac_2020_OrderRichness) #normalish
# dvac 2021
dvac_2021_OrderRichness <- lm(data = subset(CommunityMetrics, Year == 2021 & Collection_Method=="dvac"),(richness) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2021_OrderRichness)
ols_test_normality(dvac_2021_OrderRichness) #normalish
# dvac 2022
dvac_2022_OrderRichness <- lm(data = subset(CommunityMetrics, Year == 2022 & Collection_Method=="dvac"), (richness) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2022_OrderRichness)
ols_test_normality(dvac_2022_OrderRichness) #normal
#### Glmm for Richness by Grazing Treatment Orthoptera####
# 2020 Dvac
OrderRichness_D_2020_Glmm <- lmer(log(richness) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics,Year==2020 & Collection_Method=="dvac"))
anova(OrderRichness_D_2020_Glmm) #not significant
# 2021 Dvac
OrderRichness_D_2021_Glmm <- lmer((richness) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics,Year==2021 & Collection_Method=="dvac"))
anova(OrderRichness_D_2021_Glmm) #not significant
# 2022 Dvac
OrderRichness_D_2022_Glmm <- lmer((richness) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics,Year==2022 & Collection_Method=="dvac"))
anova(OrderRichness_D_2022_Glmm) #not significant
#### Plot Shannon: Weight ####
# 2020 - Weight
Shannon_2020_Weight<-ggplot(subset(CommunityMetrics_Weight_Avg,Year==2020),aes(x=Grazing_Treatment,y=Shannon_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Shannon_Mean-Shannon_St_Error,ymax=Shannon_Mean+Shannon_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Shannon"
ylab("Shannon's Diversity")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=1)+
scale_y_continuous(labels = label_number(accuracy = 0.1))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=1, label="2020 Weight",size=20)
# 2021 - Dvac
#Graph of Weights from dvac by Grazing treatment- 2021
Shannon_2021_Weight<-ggplot(subset(CommunityMetrics_Weight_Avg,Year==2021),aes(x=Grazing_Treatment,y=Shannon_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Shannon_Mean-Shannon_St_Error,ymax=Shannon_Mean+Shannon_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Shannon"
ylab("Shannon's Diversity")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(axis.title.y=element_blank(),axis.text.y=element_blank(),legend.position = "none")+
#Make the y-axis extend to 50
expand_limits(y=1)+
scale_y_continuous(labels = label_number(accuracy = 0.1))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=1, label="2021 Weight",size=20)
# 2022 - Dvac
Shannon_2022_Weight<-ggplot(subset(CommunityMetrics_Weight_Avg,Year==2022),aes(x=Grazing_Treatment,y=Shannon_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Shannon_Mean-Shannon_St_Error,ymax=Shannon_Mean+Shannon_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Shannon"
ylab("Shannon's Diversity")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(axis.title.y=element_blank(),legend.position = "none",axis.text.y=element_blank())+
#Make the y-axis extend to 50
expand_limits(y=1)+
scale_y_continuous(labels = label_number(accuracy = 0.1))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=1, label="2022 Weight",size=20)
#### Create Order Shannon Figure: Weight####
Shannon_2020_Weight+
Shannon_2021_Weight+
Shannon_2022_Weight+
plot_layout(ncol = 3,nrow = 1)
#Save at 4000x2000
#### Normality: Order Shannon: Weight ####
# Weight 2020
Weight_2020_OrderShannon <- lm(data = subset(CommunityMetrics_Weight, Year == 2020),(Shannon) ~ Grazing_Treatment)
ols_plot_resid_hist(Weight_2020_OrderShannon)
ols_test_normality(Weight_2020_OrderShannon) #normal
# Weight 2021
Weight_2021_OrderShannon <- lm(data = subset(CommunityMetrics_Weight, Year == 2021),(Shannon) ~ Grazing_Treatment)
ols_plot_resid_hist(Weight_2021_OrderShannon)
ols_test_normality(Weight_2021_OrderShannon) #normal
# Weight 2020
Weight_2022_OrderShannon <- lm(data = subset(CommunityMetrics_Weight, Year == 2022),(Shannon) ~ Grazing_Treatment)
ols_plot_resid_hist(Weight_2022_OrderShannon)
ols_test_normality(Weight_2022_OrderShannon) #normal
#### Glmm for Shannon's Diversity by Grazing Treatment: Weight####
# 2020 Weight
OrderShannon_2020_Glmm_Weight <- lmer((Shannon) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics_Weight,Year==2020))
anova(OrderShannon_2020_Glmm_Weight) #not significant
# 2021 Weight
OrderShannon_2021_Glmm_Weight <- lmer((Shannon) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics_Weight,Year==2021))
anova(OrderShannon_2021_Glmm_Weight) #0.005528
### post hoc test for lmer test ##
summary(glht(OrderShannon_2021_Glmm_Weight, linfct = mcp(Grazing_Treatment = "Tukey")), test = adjusted(type = "BH")) #NG-LG (p=0.09455), #LG-HG (0.09455), NG-HG (0.00178)
# 2022 Weight
OrderShannon_2022_Glmm_Weight <- lmer((Shannon) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics_Weight,Year==2022))
anova(OrderShannon_2022_Glmm_Weight) #not significant
#### Plot Shannon: Count ####
# 2020 - Dvac
Shannon_2020_Dvac<-ggplot(subset(CommunityMetrics_Avg,Year==2020 & Collection_Method=="dvac"),aes(x=Grazing_Treatment,y=Shannon_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Shannon_Mean-Shannon_St_Error,ymax=Shannon_Mean+Shannon_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Shannon"
ylab("Shannon's Diversity")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=6)+
scale_y_continuous(labels = label_number(accuracy = 1))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=6, label="2020 Count",size=20)
# 2021 - Dvac
#Graph of Weights from dvac by Grazing treatment- 2021
Shannon_2021_Dvac<-ggplot(subset(CommunityMetrics_Avg,Year==2021 & Collection_Method=="dvac"),aes(x=Grazing_Treatment,y=Shannon_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Shannon_Mean-Shannon_St_Error,ymax=Shannon_Mean+Shannon_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Shannon"
ylab("Shannon's Diversity")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(axis.title.y=element_blank(),axis.text.y=element_blank(),legend.position = "none")+
#Make the y-axis extend to 50
expand_limits(y=6)+
scale_y_continuous(labels = label_number(accuracy = 1))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=6, label="2021 Count",size=20)
# 2022 - Dvac
Shannon_2022_Dvac<-ggplot(subset(CommunityMetrics_Avg,Year==2022 & Collection_Method=="dvac"),aes(x=Grazing_Treatment,y=Shannon_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Shannon_Mean-Shannon_St_Error,ymax=Shannon_Mean+Shannon_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Shannon"
ylab("Shannon's Diversity")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(axis.title.y=element_blank(),legend.position = "none",axis.text.y=element_blank())+
#Make the y-axis extend to 50
expand_limits(y=6)+
scale_y_continuous(labels = label_number(accuracy = 1))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=6, label="2022 Count",size=20)
#### Create Order Shannon Figure: Count ####
Shannon_2020_Dvac+
Shannon_2021_Dvac+
Shannon_2022_Dvac+
plot_layout(ncol = 3,nrow = 1)
#Save at 4000x2000
#### Normality: Order Shannon: Count ####
# Dvac 2020
dvac_2020_OrderShannon <- lm(data = subset(CommunityMetrics, Year == 2020 & Collection_Method=="dvac"),(Shannon) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2020_OrderShannon)
ols_test_normality(dvac_2020_OrderShannon) #normalish
# dvac 2021
dvac_2021_OrderShannon <- lm(data = subset(CommunityMetrics, Year == 2021 & Collection_Method=="dvac"),(Shannon) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2021_OrderShannon)
ols_test_normality(dvac_2021_OrderShannon) #normalish
# dvac 2022
dvac_2022_OrderShannon <- lm(data = subset(CommunityMetrics, Year == 2022 & Collection_Method=="dvac"), (Shannon) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2022_OrderShannon)
ols_test_normality(dvac_2022_OrderShannon) #normal
#### Glmm for Shannon's Diversity by Grazing Treatment: Count####
# 2020 Dvac
OrderShannon_D_2020_Glmm <- lmer((Shannon) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics,Year==2020 & Collection_Method=="dvac"))
anova(OrderShannon_D_2020_Glmm) #not significant
# 2021 Dvac
OrderShannon_D_2021_Glmm <- lmer((Shannon) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics,Year==2021 & Collection_Method=="dvac"))
anova(OrderShannon_D_2021_Glmm) #0.03554
### post hoc test for lmer test ##
summary(glht(OrderShannon_D_2021_Glmm, linfct = mcp(Grazing_Treatment = "Tukey")), test = adjusted(type = "BH")) #NG-LG (p=2733), #LG-HG (1695), NG-HG (0.0221)
# 2022 Dvac
OrderShannon_D_2022_Glmm <- lmer((Shannon) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics,Year==2022 & Collection_Method=="dvac"))
anova(OrderShannon_D_2022_Glmm) #0.01073
## post hoc test for lmer test ##
summary(glht(OrderShannon_D_2022_Glmm, linfct = mcp(Grazing_Treatment = "Tukey")), test = adjusted(type = "BH")) #NG-LG (p=0.05361), #LG-HG (0.00524), NG-HG (.30277)
#### Plot Evar: Weight ####
# 2020 - Weight
Evar_2020_Weight<-ggplot(subset(CommunityMetrics_Weight_Avg,Year==2020),aes(x=Grazing_Treatment,y=Evar_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Evar_Mean-Evar_St_Error,ymax=Evar_Mean+Evar_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Evar"
ylab("Evenness")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=1)+
scale_y_continuous(labels = label_number(accuracy = .01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=1, label="2020 Weight",size=20)
# 2021 - Weight
#Graph of Weights from dvac by Grazing treatment- 2021
Evar_2021_Weight<-ggplot(subset(CommunityMetrics_Avg,Year==2021),aes(x=Grazing_Treatment,y=Evar_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Evar_Mean-Evar_St_Error,ymax=Evar_Mean+Evar_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Evar"
ylab("Evenness")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(axis.title.y=element_blank(),axis.text.y=element_blank(),legend.position = "none")+
#Make the y-axis extend to 50
expand_limits(y=1)+
scale_y_continuous(labels = label_number(accuracy = .01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=1, label="2021 Weight",size=20)
# 2022 - Weight
Evar_2022_Weight<-ggplot(subset(CommunityMetrics_Avg,Year==2022),aes(x=Grazing_Treatment,y=Evar_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Evar_Mean-Evar_St_Error,ymax=Evar_Mean+Evar_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Evar"
ylab("Evenness")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(axis.title.y=element_blank(),legend.position = "none",axis.text.y=element_blank())+
#Make the y-axis extend to 50
expand_limits(y=1)+
scale_y_continuous(labels = label_number(accuracy = .01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=1, label="2022 Weight",size=20)
#### Create Order Evar Figure: Weight ####
Evar_2020_Weight+
Evar_2021_Weight+
Evar_2022_Weight+
plot_layout(ncol = 3,nrow = 1)
#Save at 4000x2000
#### Normality: Order Evar: Weight ####
# Weight 2020
Weight_2020_OrderEvar <- lm(data = subset(CommunityMetrics_Weight, Year == 2020 & Collection_Method=="dvac"),1/(Evar) ~ Grazing_Treatment)
ols_plot_resid_hist(Weight_2020_OrderEvar)
ols_test_normality(Weight_2020_OrderEvar) #normalish
# Weight 2021
Weight_2021_OrderEvar <- lm(data = subset(CommunityMetrics_Weight, Year == 2021 & Collection_Method=="dvac"),log(Evar) ~ Grazing_Treatment)
ols_plot_resid_hist(Weight_2021_OrderEvar)
ols_test_normality(Weight_2021_OrderEvar) #normalish
# Weight 2022
Weight_2022_OrderEvar <- lm(data = subset(CommunityMetrics_Weight, Year == 2022 & Collection_Method=="dvac"),1/(Evar) ~ Grazing_Treatment)
ols_plot_resid_hist(Weight_2022_OrderEvar)
ols_test_normality(Weight_2022_OrderEvar) #normalish
#### Glmm for Evenness by Grazing Treatment: Weight ####
# 2020 Weight
OrderEvar_2020_Glmm_Weight <- lmer(1/(Evar) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics_Weight,Year==2020 ))
anova(OrderEvar_2020_Glmm_Weight) #not significant
# 2021 Weight
OrderEvar_2021_Glmm_Weight <- lmer((log(Evar)) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics_Weight,Year==2021 ))
anova(OrderEvar_2021_Glmm_Weight) #not significant
# 2020 Weight
OrderEvar_2021_Glmm_Weight <- lmer((1/Evar) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics_Weight,Year==2021 ))
anova(OrderEvar_2021_Glmm_Weight) #not significant
#### Plot Evar: Count ####
# 2020 - Count
Evar_2020_Count<-ggplot(subset(CommunityMetrics_Avg,Year==2020 & Collection_Method=="dvac"),aes(x=Grazing_Treatment,y=Evar_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Evar_Mean-Evar_St_Error,ymax=Evar_Mean+Evar_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Evar"
ylab("Evenness")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=1)+
scale_y_continuous(labels = label_number(accuracy = .01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=1, label="2020 Count",size=20)
# 2021 - Count
#Graph of Weights from dvac by Grazing treatment- 2021
Evar_2021_Count<-ggplot(subset(CommunityMetrics_Avg,Year==2021 & Collection_Method=="dvac"),aes(x=Grazing_Treatment,y=Evar_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Evar_Mean-Evar_St_Error,ymax=Evar_Mean+Evar_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Evar"
ylab("Evenness")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(axis.title.y=element_blank(),axis.text.y=element_blank(),legend.position = "none")+
#Make the y-axis extend to 50
expand_limits(y=1)+
scale_y_continuous(labels = label_number(accuracy = .01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=1, label="2021 Count",size=20)
# 2022 - Count
Evar_2022_Count<-ggplot(subset(CommunityMetrics_Avg,Year==2022 & Collection_Method=="dvac"),aes(x=Grazing_Treatment,y=Evar_Mean,fill=Grazing_Treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Evar_Mean-Evar_St_Error,ymax=Evar_Mean+Evar_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Evar"
ylab("Evenness")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(axis.title.y=element_blank(),legend.position = "none",axis.text.y=element_blank())+
#Make the y-axis extend to 50
expand_limits(y=1)+
scale_y_continuous(labels = label_number(accuracy = .01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))+
geom_text(x=0.85, y=1, label="2022 Count",size=20)
#### Create Order Evar Figure ####
Evar_2020_Count+
Evar_2021_Count+
Evar_2022_Count+
plot_layout(ncol = 3,nrow = 1)
#Save at 4000x2000
#### Normality: Order Evar: Count ####
# Dvac 2020
dvac_2020_OrderEvar <- lm(data = subset(CommunityMetrics, Year == 2020 & Collection_Method=="dvac"),(Evar) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2020_OrderEvar)
ols_test_normality(dvac_2020_OrderEvar) #normalish
# dvac 2021
dvac_2021_OrderEvar <- lm(data = subset(CommunityMetrics, Year == 2021 & Collection_Method=="dvac"),(Evar) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2021_OrderEvar)
ols_test_normality(dvac_2021_OrderEvar) #normalish
# dvac 2022
dvac_2022_OrderEvar <- lm(data = subset(CommunityMetrics, Year == 2022 & Collection_Method=="dvac"), 1/(Evar) ~ Grazing_Treatment)
ols_plot_resid_hist(dvac_2022_OrderEvar)
ols_test_normality(dvac_2022_OrderEvar) #normalish
#### Glmm for Evenness by Grazing Treatment ####
# 2020 Dvac
OrderEvar_D_2020_Glmm <- lmer((Evar) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics,Year==2020 & Collection_Method=="dvac"))
anova(OrderEvar_D_2020_Glmm) #not significant
# 2021 Dvac
OrderEvar_D_2021_Glmm <- lmer((Evar) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics,Year==2021 & Collection_Method=="dvac"))
anova(OrderEvar_D_2021_Glmm) #0.03418
# post hoc test for lmer test
summary(glht(OrderEvar_D_2021_Glmm, linfct = mcp(Grazing_Treatment = "Tukey")), test = adjusted(type = "BH")) #NG-LG (p=00.1897), #LG-HG (0.1897), NG-HG (0.0204)
# 2022 Dvac
OrderEvar_D_2022_Glmm <- lmer((1/Evar) ~ Grazing_Treatment + (1 | Block) , data = subset(CommunityMetrics,Year==2022 & Collection_Method=="dvac"))
anova(OrderEvar_D_2022_Glmm) #not significant
#### NMDS: By Order: Weight####
#### Bray Curtis: By Order: Weight ####
#Create wide relative cover dataframe
Abundance_Wide_Weight<-Weight_Data_Summed %>%
filter(!Correct_Order %in% c("Unknown","unknown", "Unknown_1","Body_Parts","Body Parts")) %>%
filter(Plot!="NA") %>%
spread(key=Correct_Order,value=Dry_Weight_g, fill=0) %>%
filter(Collection_Method=="dvac")
#### Make new data frame called BC_Data and run an NMDS
#dvac
BC_Data_Weight <- metaMDS(Abundance_Wide_Weight[,6:15])
#look at species signiciance driving NMDS
intrinsics <- envfit(BC_Data_Weight, Abundance_Wide_Weight, permutations = 999)
head(intrinsics)
#Make a data frame called sites with 1 column and same number of rows that is in Wide Order weight
sites <- 1:nrow(Abundance_Wide_Weight)
#Make a new data table called BC_Meta_Data and use data from Wide_Relative_Cover columns 1-3
BC_Meta_Data_Weight <- Abundance_Wide_Weight[,1:5] #%>%
#mutate(Trt_Year=paste(Grazing_Treatment,Year,sep="."))
#make a plot using the dataframe BC_Data and the column "points". Make Grazing Treatment a factor - make the different grazing treatments different colors
plot(BC_Data_Weight$points,col=as.factor(BC_Meta_Data_Weight$Year))
#Use the vegan ellipse function to make ellipses
veganCovEllipse<-function (cov, center = c(0, 0), scale = 1, npoints = 100)
{
theta <- (0:npoints) * 2 * pi/npoints
Circle <- cbind(cos(theta), sin(theta))
t(center + scale * t(Circle %*% chol(cov)))
}
#make elipses using the BC_Data. Group by grazing treatment and use standard deviation to draw eclipses
ordiellipse(BC_Data_Weight,groups = as.factor(BC_Meta_Data_Weight$Year),kind = "sd",display = "sites", label = T)
#Make a data frame called BC_NMDS and at a column using the first set of "points" in BC_Data and a column using the second set of points. Group them by watershed
BC_NMDS_Weight = data.frame(MDS1 = BC_Data_Weight$points[,1], MDS2 = BC_Data_Weight$points[,2],group=BC_Meta_Data_Weight$Year)
#Make data table called BC_NMDS_Graph and bind the BC_Meta_Data, and BC_NMDS data together
BC_NMDS_Graph_Weight <- cbind(BC_Meta_Data_Weight,BC_NMDS_Weight)
#Make a data table called BC_Ord_Ellipses using data from BC_Data and watershed information from BC_Meta_Data. Display sites and find the standard error at a confidence iinterval of 0.95. Place lables on the graph
BC_Ord_Ellipses_Weight<-ordiellipse(BC_Data_Weight, BC_Meta_Data_Weight$Year, display = "sites",
kind = "sd", conf = 0.95, label = T)
#Make a new empty data frame called BC_Ellipses
BC_Ellipses_Weight <- data.frame()
#Generate ellipses points - switched levels for unique - not sure if it's stil correct but it looks right
for(g in unique(BC_NMDS_Weight$group)){
BC_Ellipses_Weight <- rbind(BC_Ellipses_Weight, cbind(as.data.frame(with(BC_NMDS_Weight[BC_NMDS_Weight$group==g,], veganCovEllipse(BC_Ord_Ellipses_Weight[[g]]$cov,BC_Ord_Ellipses_Weight[[g]]$center,BC_Ord_Ellipses_Weight[[g]]$scale)))
,group=g))
}
#### NMDS Figures: By Order: Weight ####
#Plot the data from BC_NMDS_Graph, where x=MDS1 and y=MDS2, make an ellipse based on "group"
ggplot(data = BC_NMDS_Graph_Weight, aes(MDS1,MDS2, shape = group,color=group,linetype=group))+
#make a point graph where the points are size 5. Color them based on exlosure
geom_point(size=8, stroke = 2) +
#Use the data from BC_Ellipses to make ellipses that are size 1 with a solid line
geom_path(data = BC_Ellipses_Weight, aes(x=NMDS1, y=NMDS2), size=4)+
#make shape, color, and linetype in one combined legend instead of three legends
labs(color = "", linetype = "", shape = "")+
scale_color_manual(values=c("skyblue3","springgreen3","brown"),labels = c("2020","2021", "2022"),name="")+
scale_linetype_manual(values=c(1,2,3),labels = c("2020","2021", "2022"),name="")+
# make legend 2 columns
guides(shape=guide_legend(ncol=2),colour=guide_legend(ncol=2),linetype=guide_legend(ncol=2))+
#make the text size of the legend titles 28
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"))+
#Label the x-axis "NMDS1" and the y-axis "NMDS2"
xlab("NMDS1")+
ylab("NMDS2")+
theme(text = element_text(size = 55),legend.text=element_text(size=40))+
annotate(geom="text", x=-2, y=0.8, label="Weight",size=20)
#export at 2000 x 1800
####NMDS: Weight: 2021 by Grazing ####
BC_Meta_Data_Weight_Grazing <- Abundance_Wide_Weight[,1:5] %>%
mutate(Trt_Year=paste(Grazing_Treatment,Year,sep="."))
#make a plot using the dataframe BC_Data and the column "points". Make Grazing Treatment a factor - make the different grazing treatments different colors
plot(BC_Data_Weight$points,col=as.factor(BC_Meta_Data_Weight_Grazing$Trt_Year))
#make elipses using the BC_Data. Group by grazing treatment and use standard deviation to draw eclipses
ordiellipse(BC_Data_Weight,groups = as.factor(BC_Meta_Data_Weight_Grazing$Trt_Year),kind = "sd",display = "sites", label = T)
#Make a data frame called BC_NMDS and at a column using the first set of "points" in BC_Data and a column using the second set of points. Group them by watershed
BC_NMDS_Weight_Grazing = data.frame(MDS1 = BC_Data_Weight$points[,1], MDS2 = BC_Data_Weight$points[,2],group=BC_Meta_Data_Weight_Grazing$Trt_Year)
#Make data table called BC_NMDS_Graph and bind the BC_Meta_Data, and BC_NMDS data together
BC_NMDS_Graph_Weight_Grazing <- cbind(BC_Meta_Data_Weight_Grazing,BC_NMDS_Weight_Grazing)
#Make a data table called BC_Ord_Ellipses using data from BC_Data and watershed information from BC_Meta_Data. Display sites and find the standard error at a confidence iinterval of 0.95. Place lables on the graph
BC_Ord_Ellipses_Weight_Grazing<-ordiellipse(BC_Data_Weight, BC_Meta_Data_Weight_Grazing$Trt_Year, display = "sites",
kind = "sd", conf = 0.95, label = T)
#Make a new empty data frame called BC_Ellipses
BC_Ellipses_Weight_Grazing <- data.frame()
#Generate ellipses points - switched levels for unique - not sure if it's stil correct but it looks right
for(g in unique(BC_NMDS_Weight_Grazing$group)){
BC_Ellipses_Weight_Grazing <- rbind(BC_Ellipses_Weight_Grazing, cbind(as.data.frame(with(BC_NMDS_Weight_Grazing[BC_NMDS_Weight_Grazing$group==g,], veganCovEllipse(BC_Ord_Ellipses_Weight_Grazing[[g]]$cov,BC_Ord_Ellipses_Weight_Grazing[[g]]$center,BC_Ord_Ellipses_Weight_Grazing[[g]]$scale)))
,group=g))
}
#### NMDS Figures: By Order: Weight ####
#Plot the data from BC_NMDS_Graph, where x=MDS1 and y=MDS2, make an ellipse based on "group"
ggplot(data = subset(BC_NMDS_Graph_Weight_Grazing,group==c("HG.2021","LG.2021","NG.2021")), aes(MDS1,MDS2, shape = group,color=group,linetype=group))+
#make a point graph where the points are size 5. Color them based on exlosure
geom_point(size=8, stroke = 2) +
#Use the data from BC_Ellipses to make ellipses that are size 1 with a solid line
geom_path(data = subset(BC_Ellipses_Weight_Grazing,group==c("HG.2021","LG.2021","NG.2021")), aes(x=NMDS1, y=NMDS2), size=4)+
#make shape, color, and linetype in one combined legend instead of three legends
labs(color = "", linetype = "", shape = "")+
scale_color_manual(values=c("thistle2","thistle3","thistle4"), labels=c("Cattle Removal","Destock","High Impact Grazing"), breaks=c("NG.2021","LG.2021","HG.2021"))+
scale_shape_manual(values=c(15,16,17), labels=c("Cattle Removal","Destock","High Impact Grazing"), breaks=c("NG.2021","LG.2021","HG.2021"))+
scale_linetype_manual(values=c(1,2,3),labels=c("Cattle Removal","Destock","High Impact Grazing"), breaks=c("NG.2021","LG.2021","HG.2021"))+
# make legend 2 columns
guides(shape=guide_legend(ncol=2),colour=guide_legend(ncol=2),linetype=guide_legend(ncol=2))+
#make the text size of the legend titles 28
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"))+
#Label the x-axis "NMDS1" and the y-axis "NMDS2"
xlab("NMDS1")+
ylab("NMDS2")+
theme(text = element_text(size = 55),legend.text=element_text(size=40),legend.position="none")+
annotate(geom="text", x=-2, y=0.8, label="2021 Weight",size=20)
#export at 2000 x 1800
#### PERMANOVA: By Order: Weight ####
##PerMANOVA
#Make a new dataframe with the data from Wide_Relative_Cover all columns after 5
Species_Matrix_Weight <- Abundance_Wide_Weight[,6:ncol(Abundance_Wide_Weight)]
#Make a new dataframe with data from Wide_Relative_Cover columns 1-3
Environment_Matrix_Weight <- Abundance_Wide_Weight[,1:5] %>%
mutate(Gr_Yr=paste(Grazing_Treatment,Year,sep="."))
Environment_Matrix_Weight$Grazing_Treatment_Fact=as.factor(Environment_Matrix_Weight$Grazing_Treatment)
Environment_Matrix_Weight$Block_Fact=as.numeric(Environment_Matrix_Weight$Block)
Environment_Matrix_Weight$Plot_Fact=as.factor(Environment_Matrix_Weight$Plot)
Environment_Matrix_Weight$Year_Fact=as.factor(Environment_Matrix_Weight$Year)
#run a perMANOVA comparing across watershed and exclosure, how does the species composition differ. Permutation = 999 - run this 999 times and tell us what the preportion of times it was dissimilar
#Adding in the 'strata' function does not affect results - i can't figure out if I am doing in incorrectly or if they do not affect the results (seems unlikely though becuase everything is exactly the same)
PerMANOVA2_Weight <- adonis2(formula = Species_Matrix_Weight~Grazing_Treatment_Fact*Year_Fact + (1 | Block_Fact) , data=Environment_Matrix_Weight,permutations = 999, method = "bray")
#give a print out of the PermMANOVA
print(PerMANOVA2_Weight) #Grazing (0.01), Year (0.001), GxYear (0.003)
#pairwise test
Posthoc_Weight_Year<-pairwise.adonis(Species_Matrix_Weight,factors=Environment_Matrix_Weight$Year, p.adjust.m = "BH")
Posthoc_Weight_Year #2020-2021 (0.001), 2021-2022 (0.001), 2020-2022 (0.001)
Posthoc_Weight_Grazing_Year<-pairwise.adonis(Species_Matrix_Weight,factors=Environment_Matrix_Weight$Gr_Yr, p.adjust.m = "BH")
Posthoc_Weight_Grazing_Year #Significant: HG-NG (2021)
#### PERMDISP: By Order ####
Abundance_Wide_Weight_dispr<-Abundance_Wide_Weight %>%
mutate(Gr_Yr=paste(Grazing_Treatment,Year,sep="."))
#Dvac
#Make a new dataframe and calculate the dissimilarity of the Species_Matrix dataframe
BC_Distance_Matrix_Weight <- vegdist(Species_Matrix_Weight)
#Run a dissimilarity matrix (PermDisp) comparing grazing treatment
Dispersion_Results_Grazing_Weight <- betadisper(BC_Distance_Matrix_Weight,Abundance_Wide_Weight_dispr$Gr_Yr)
permutest(Dispersion_Results_Grazing_Weight,pairwise = T, permutations = 999)
#### NMDS: By Order: Count####
#### Bray Curtis: By Order: Count ####
#Create wide relative cover dataframe
#Change row 54 and 55 where we don't cant equate sample number to weight to be unique sample number so it can be used here
#2020 block 1 NG, plot 3
Abundance[54, "Sample_Number"] <- 10
Abundance[55, "Sample_Number"] <- 11
#2021 LG, plot 8
Abundance[944, "Sample_Number"] <- 2
Abundance[945, "Sample_Number"] <- 3
Abundance_Wide_Count<-Abundance %>%
dplyr::select(-c(Correct_Family,Correct_Genus, Correct_Species,Notes,Coll_Year_Bl_Trt,Coll_Year_Bl_Trt_Pl,Sample_Number)) %>%
unique() %>%
spread(key=Correct_Order,value=Abundance, fill=0) %>%
select(-c(Unknown,"<NA>")) %>%
filter(Collection_Method=="dvac")
Abundance_Wide_Count$Year=as.character(Abundance_Wide_Count$Year)
Abundance_Wide_Count$Plot=as.character(Abundance_Wide_Count$Plot)
#### Make new data frame called BC_Data and run an NMDS
#dvac
BC_Data_Count <- metaMDS(Abundance_Wide_Count[,6:15])
#look at species signiciance driving NMDS
intrinsics <- envfit(BC_Data_Count, Abundance_Wide_Count, permutations = 999)
head(intrinsics)
#Make a data frame called sites with 1 column and same number of rows that is in Wide Order Count
sites <- 1:nrow(Abundance_Wide_Count)
#Make a new data table called BC_Meta_Data and use data from Wide_Relative_Cover columns 1-3
BC_Meta_Data_Count <- Abundance_Wide_Count[,1:5]
#make a plot using the dataframe BC_Data and the column "points". Make Grazing Treatment a factor - make the different grazing treatments different colors
plot(BC_Data_Count$points,col=as.factor(BC_Meta_Data_Count$Year))
#make elipses using the BC_Data. Group by grazing treatment and use standard deviation to draw eclipses
ordiellipse(BC_Data_Count,groups = as.factor(BC_Meta_Data_Count$Year),kind = "sd",display = "sites", label = T)
#Make a data frame called BC_NMDS and at a column using the first set of "points" in BC_Data and a column using the second set of points. Group them by watershed
BC_NMDS_Count = data.frame(MDS1 = BC_Data_Count$points[,1], MDS2 = BC_Data_Count$points[,2],group=BC_Meta_Data_Count$Year)
#Make data table called BC_NMDS_Graph and bind the BC_Meta_Data, and BC_NMDS data together
BC_NMDS_Graph_Count <- cbind(BC_Meta_Data_Count,BC_NMDS_Count)
#Make a data table called BC_Ord_Ellipses using data from BC_Data and watershed information from BC_Meta_Data. Display sites and find the standard error at a confidence iinterval of 0.95. Place lables on the graph
BC_Ord_Ellipses_Count<-ordiellipse(BC_Data_Count, BC_Meta_Data_Count$Year, display = "sites",
kind = "sd", conf = 0.95, label = T)
#Make a new empty data frame called BC_Ellipses
BC_Ellipses_Count <- data.frame()
#Generate ellipses points - switched levels for unique - not sure if it's stil correct but it looks right
for(g in unique(BC_NMDS_Count$group)){
BC_Ellipses_Count <- rbind(BC_Ellipses_Count, cbind(as.data.frame(with(BC_NMDS_Count[BC_NMDS_Count$group==g,], veganCovEllipse(BC_Ord_Ellipses_Count[[g]]$cov,BC_Ord_Ellipses_Count[[g]]$center,BC_Ord_Ellipses_Count[[g]]$scale)))
,group=g))
}
#### NMDS Figures: By Order: Count ####
#Plot the data from BC_NMDS_Graph, where x=MDS1 and y=MDS2, make an ellipse based on "group"
ggplot(data = BC_NMDS_Graph_Count, aes(MDS1,MDS2, shape = group,color=group,linetype=group))+
#make a point graph where the points are size 5. Color them based on exlosure
geom_point(size=8, stroke = 2) +
#Use the data from BC_Ellipses to make ellipses that are size 1 with a solid line
geom_path(data = BC_Ellipses_Count, aes(x=NMDS1, y=NMDS2), size=4)+
#make shape, color, and linetype in one combined legend instead of three legends
labs(color = "", linetype = "", shape = "")+
scale_color_manual(values=c("skyblue3","springgreen3","brown"),labels = c("2020","2021", "2022"),name="")+
scale_linetype_manual(values=c(1,2,3),labels = c("2020","2021", "2022"),name="")+
# make legend 2 columns
guides(shape=guide_legend(ncol=2),colour=guide_legend(ncol=2),linetype=guide_legend(ncol=2))+
#make the text size of the legend titles 28
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"))+
#Label the x-axis "NMDS1" and the y-axis "NMDS2"
xlab("NMDS1")+
ylab("NMDS2")+
theme(text = element_text(size = 55),legend.text=element_text(size=40),legend.position="none")+
annotate(geom="text", x=-2, y=0.8, label="Count",size=20)
#export at 2000 x 1800
####NMDS: Count: 2021 by Grazing ####
BC_Meta_Data_Count_Grazing <- Abundance_Wide_Count[,1:5] %>%
mutate(Trt_Year=paste(Grazing_Treatment,Year,sep="."))
#make a plot using the dataframe BC_Data and the column "points". Make Grazing Treatment a factor - make the different grazing treatments different colors
plot(BC_Data_Count$points,col=as.factor(BC_Meta_Data_Count_Grazing$Trt_Year))
#make elipses using the BC_Data. Group by grazing treatment and use standard deviation to draw eclipses
ordiellipse(BC_Data_Count,groups = as.factor(BC_Meta_Data_Count_Grazing$Trt_Year),kind = "sd",display = "sites", label = T)
#Make a data frame called BC_NMDS and at a column using the first set of "points" in BC_Data and a column using the second set of points. Group them by watershed
BC_NMDS_Count_Grazing = data.frame(MDS1 = BC_Data_Count$points[,1], MDS2 = BC_Data_Count$points[,2],group=BC_Meta_Data_Count_Grazing$Trt_Year)
#Make data table called BC_NMDS_Graph and bind the BC_Meta_Data, and BC_NMDS data together
BC_NMDS_Graph_Count_Grazing <- cbind(BC_Meta_Data_Count_Grazing,BC_NMDS_Count_Grazing)
#Make a data table called BC_Ord_Ellipses using data from BC_Data and watershed information from BC_Meta_Data. Display sites and find the standard error at a confidence iinterval of 0.95. Place lables on the graph
BC_Ord_Ellipses_Count_Grazing<-ordiellipse(BC_Data_Count, BC_Meta_Data_Count_Grazing$Trt_Year, display = "sites",
kind = "sd", conf = 0.95, label = T)
#Make a new empty data frame called BC_Ellipses
BC_Ellipses_Count_Grazing <- data.frame()
#Generate ellipses points - switched levels for unique - not sure if it's stil correct but it looks right
for(g in unique(BC_NMDS_Count_Grazing$group)){
BC_Ellipses_Count_Grazing <- rbind(BC_Ellipses_Count_Grazing, cbind(as.data.frame(with(BC_NMDS_Count_Grazing[BC_NMDS_Count_Grazing$group==g,], veganCovEllipse(BC_Ord_Ellipses_Count_Grazing[[g]]$cov,BC_Ord_Ellipses_Count_Grazing[[g]]$center,BC_Ord_Ellipses_Count_Grazing[[g]]$scale)))
,group=g))
}
#### NMDS Figures: By Order: Count ####
#2021
#Plot the data from BC_NMDS_Graph, where x=MDS1 and y=MDS2, make an ellipse based on "group"
ggplot(data = subset(BC_NMDS_Graph_Count_Grazing,group==c("HG.2021","LG.2021","NG.2021")), aes(MDS1,MDS2, shape = group,color=group,linetype=group))+
#make a point graph where the points are size 5. Color them based on exlosure
geom_point(size=8, stroke = 2) +
#Use the data from BC_Ellipses to make ellipses that are size 1 with a solid line
geom_path(data = subset(BC_Ellipses_Count_Grazing,group==c("HG.2021","LG.2021","NG.2021")), aes(x=NMDS1, y=NMDS2), size=4)+
#make shape, color, and linetype in one combined legend instead of three legends
labs(color = "", linetype = "", shape = "")+
scale_color_manual(values=c("thistle2","thistle3","thistle4"), labels=c("Cattle Removal","Destock","High Impact Grazing"), breaks=c("NG.2021","LG.2021","HG.2021"))+
scale_shape_manual(values=c(15,16,17), labels=c("Cattle Removal","Destock","High Impact Grazing"), breaks=c("NG.2021","LG.2021","HG.2021"))+
scale_linetype_manual(values=c(1,2,3),labels=c("Cattle Removal","Destock","High Impact Grazing"), breaks=c("NG.2021","LG.2021","HG.2021"))+
# make legend 2 columns
guides(shape=guide_legend(ncol=2),colour=guide_legend(ncol=2),linetype=guide_legend(ncol=2))+
#make the text size of the legend titles 28
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"))+
#Label the x-axis "NMDS1" and the y-axis "NMDS2"
xlab("NMDS1")+
ylab("NMDS2")+
theme(text = element_text(size = 55),legend.text=element_text(size=40),legend.position="none")+
annotate(geom="text", x=-2, y=0.8, label="2021 Count",size=20)
#export at 2000 x 1800
#2022
#Plot the data from BC_NMDS_Graph, where x=MDS1 and y=MDS2, make an ellipse based on "group"
ggplot(data = subset(BC_NMDS_Graph_Count_Grazing,group==c("HG.2022","LG.2022","NG.2022")), aes(MDS1,MDS2, shape = group,color=group,linetype=group))+
#make a point graph where the points are size 5. Color them based on exlosure
geom_point(size=8, stroke = 2) +
#Use the data from BC_Ellipses to make ellipses that are size 1 with a solid line
geom_path(data = subset(BC_Ellipses_Count_Grazing,group==c("HG.2022","LG.2022","NG.2022")), aes(x=NMDS1, y=NMDS2), size=4)+
#make shape, color, and linetype in one combined legend instead of three legends
labs(color = "", linetype = "", shape = "")+
scale_color_manual(values=c("thistle2","thistle3","thistle4"), labels=c("Cattle Removal","Destock","High Impact Grazing"), breaks=c("HG.2022","LG.2022","NG.2022"))+
scale_shape_manual(values=c(15,16,17), labels=c("Cattle Removal","Destock","High Impact Grazing"), breaks=c("HG.2022","LG.2022","NG.2022"))+
scale_linetype_manual(values=c(1,2,3),labels=c("Cattle Removal","Destock","High Impact Grazing"), breaks=c("HG.2022","LG.2022","NG.2022"))+
# make legend 2 columns
guides(shape=guide_legend(ncol=2),colour=guide_legend(ncol=2),linetype=guide_legend(ncol=2))+
#make the text size of the legend titles 28
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"))+
#Label the x-axis "NMDS1" and the y-axis "NMDS2"
xlab("NMDS1")+
ylab("NMDS2")+
theme(text = element_text(size = 55),legend.text=element_text(size=40),legend.position="none")+
annotate(geom="text", x=-1, y=0.8, label="2022 Count",size=20)
#export at 2000 x 1800
#### PERMANOVA: By Order: Count ####
##PerMANOVA
#Make a new dataframe with the data from Wide_Relative_Cover all columns after 5
Species_Matrix_Count <- Abundance_Wide_Count[,6:ncol(Abundance_Wide_Count)]
#Make a new dataframe with data from Wide_Relative_Cover columns 1-3
Environment_Matrix_Count <- Abundance_Wide_Count[,1:5] %>%
mutate(Gr_Yr=paste(Grazing_Treatment,Year,sep="."))
Environment_Matrix_Count$Grazing_Treatment_Fact=as.factor(Environment_Matrix_Count$Grazing_Treatment)
Environment_Matrix_Count$Block_Fact=as.numeric(Environment_Matrix_Count$Block)
Environment_Matrix_Count$Plot_Fact=as.factor(Environment_Matrix_Count$Plot)
Environment_Matrix_Count$Year_Fact=as.factor(Environment_Matrix_Count$Year)
#run a perMANOVA comparing across watershed and exclosure, how does the species composition differ. Permutation = 999 - run this 999 times and tell us what the preportion of times it was dissimilar
#Adding in the 'strata' function does not affect results - i can't figure out if I am doing in incorrectly or if they do not affect the results (seems unlikely though becuase everything is exactly the same)
PerMANOVA2_Count <- adonis2(formula = Species_Matrix_Count~Grazing_Treatment_Fact*Year_Fact + (1 | Block_Fact) , data=Environment_Matrix_Count,permutations = 999, method = "bray")
#give a print out of the PermMANOVA
print(PerMANOVA2_Count) #Grazing (0.01), Year (0.001), GxYear (0.003)
#pairwise test
Posthoc_Count_Year<-pairwise.adonis(Species_Matrix_Count,factors=Environment_Matrix_Count$Year, p.adjust.m = "BH")
Posthoc_Count_Year #2020-2021 (0.001), 2021-2022 (0.001), 2020-2022 (0.001)
#pairwise test
Posthoc_Count_Grazing<-pairwise.adonis(Species_Matrix_Count,factors=Environment_Matrix_Count$Grazing_Treatment, p.adjust.m = "BH")
Posthoc_Count_Grazing #ns
Posthoc_Count_Grazing_Year<-pairwise.adonis(Species_Matrix_Count,factors=Environment_Matrix_Count$Gr_Yr, p.adjust.m = "BH")
Posthoc_Count_Grazing_Year #Significant: HG-NG (2021)
#### PERMDISP: By Order ####
Abundance_Wide_Count_dispr<-Abundance_Wide_Count %>%
mutate(Gr_Yr=paste(Grazing_Treatment,Year,sep="."))
#Dvac
#Make a new dataframe and calculate the dissimilarity of the Species_Matrix dataframe
BC_Distance_Matrix_Count <- vegdist(Species_Matrix_Count)
#Run a dissimilarity matrix (PermDisp) comparing grazing treatment
Dispersion_Results_Grazing_Count <- betadisper(BC_Distance_Matrix_Count,Abundance_Wide_Count_dispr$Gr_Yr)
permutest(Dispersion_Results_Grazing_Count,pairwise = T, permutations = 999)
#### NMDS: Orthoptera Genus ####
Abundance_OrthopteraGenus<-ID_Data_Official %>%
filter(Correct_Family=="Acrididae") %>%
group_by(Collection_Method,Year,Block,Grazing_Treatment,Plot,Correct_Genus) %>%
mutate(Abundance=length(Sample_Number)) %>%
ungroup()
#### Bray Curtis: Orthoptera Genus ####
#Create wide relative cover dataframe
Abundance_Wide_D__OrthopteraGenus<-Abundance_OrthopteraGenus %>%
dplyr::select(-c(Correct_Order,Correct_Family, Correct_Species,Notes,Coll_Year_Bl_Trt,Coll_Year_Bl_Trt_Pl,Sample_Number)) %>%
unique() %>%
spread(key=Correct_Genus,value=Abundance, fill=0) %>%
select(-c("<NA>"))%>%
filter(Collection_Method=="dvac") %>%
mutate(Treatment=paste(Year,Plot,sep=".")) %>%
#remove plot 29 because it had no grasshoppers
filter(Treatment!=2022.29) %>%
select(-Treatment)
#### Make new data frame called BC_Data and run an NMDS
#dvac
BC_Data_D__OrthopteraGenus <- metaMDS(Abundance_Wide_D__OrthopteraGenus[,6:13])
#look at species signiciance driving NMDS
intrinsics <- envfit(BC_Data_D__OrthopteraGenus, Abundance_Wide_D__OrthopteraGenus, permutations = 999)
head(intrinsics)
#Make a data frame called sites with 1 column and same number of rows that is in Wide Order weight
sites <- 1:nrow(Abundance_Wide_D__OrthopteraGenus)
#Make a new data table called BC_Meta_Data and use data from Wide_Relative_Cover columns 1-3
BC_Meta_Data_D__OrthopteraGenus <- Abundance_Wide_D__OrthopteraGenus[,1:5] %>%
mutate(Trt_Year=paste(Grazing_Treatment,Year,sep="."))
#make a plot using the dataframe BC_Data and the column "points". Make Grazing Treatment a factor - make the different grazing treatments different colors
plot(BC_Data_D__OrthopteraGenus$points,col=as.factor(BC_Meta_Data_D__OrthopteraGenus$Trt_Year))
#make elipses using the BC_Data. Group by grazing treatment and use standard deviation to draw eclipses
ordiellipse(BC_Data_D__OrthopteraGenus,groups = as.factor(BC_Meta_Data_D__OrthopteraGenus$Trt_Year),kind = "sd",display = "sites", label = T)
#Make a data frame called BC_NMDS and at a column using the first set of "points" in BC_Data and a column using the second set of points. Group them by watershed
BC_NMDS_D__OrthopteraGenus = data.frame(MDS1 = BC_Data_D__OrthopteraGenus$points[,1], MDS2 = BC_Data_D__OrthopteraGenus$points[,2],group=BC_Meta_Data_D__OrthopteraGenus$Trt_Year)
#Make data table called BC_NMDS_Graph and bind the BC_Meta_Data, and BC_NMDS data together
BC_NMDS_Graph_D__OrthopteraGenus <- cbind(BC_Meta_Data_D__OrthopteraGenus,BC_NMDS_D__OrthopteraGenus)
#Make a data table called BC_Ord_Ellipses using data from BC_Data and watershed information from BC_Meta_Data. Display sites and find the standard error at a confidence iinterval of 0.95. Place lables on the graph
BC_Ord_Ellipses_D__OrthopteraGenus<-ordiellipse(BC_Data_D__OrthopteraGenus, BC_Meta_Data_D__OrthopteraGenus$Trt_Year, display = "sites",
kind = "se", conf = 0.95, label = T)
#Make a new empty data frame called BC_Ellipses
BC_Ellipses_D__OrthopteraGenus <- data.frame()
#Generate ellipses points - switched levels for unique - not sure if it's stil correct but it looks right
for(g in unique(BC_NMDS_D__OrthopteraGenus$group)){
BC_Ellipses_D__OrthopteraGenus <- rbind(BC_Ellipses_D__OrthopteraGenus, cbind(as.data.frame(with(BC_NMDS_D__OrthopteraGenus[BC_NMDS_D__OrthopteraGenus$group==g,], veganCovEllipse(BC_Ord_Ellipses_D__OrthopteraGenus[[g]]$cov,BC_Ord_Ellipses_D__OrthopteraGenus[[g]]$center,BC_Ord_Ellipses_D__OrthopteraGenus[[g]]$scale)))
,group=g))
}
#### NMDS Figures: Orthoptera Genus ####
#Plot the data from BC_NMDS_Graph, where x=MDS1 and y=MDS2, make an ellipse based on "group"
NMDS_Dvac_OrthopteraGenus<-ggplot(data = BC_NMDS_Graph_D__OrthopteraGenus, aes(MDS1,MDS2, shape = group,color=group,linetype=group))+
#make a point graph where the points are size 5. Color them based on exlosure
geom_point(size=8, stroke = 2) +
#Use the data from BC_Ellipses to make ellipses that are size 1 with a solid line
geom_path(data = BC_Ellipses_D__OrthopteraGenus, aes(x=NMDS1, y=NMDS2), size=4)+
#make shape, color, and linetype in one combined legend instead of three legends
labs(color = "", linetype = "", shape = "")+
# make legend 2 columns
guides(shape=guide_legend(ncol=2),colour=guide_legend(ncol=2),linetype=guide_legend(ncol=2))+
#change order of legend
#Use different shapes
scale_shape_manual(values=c(15,16,17,22,21,24,21,15,17),labels = c("Heavy 2020","Destock 2020", "No Grazing 2020","Heavy 2021","Destock 2021", "No Grazing 2021","Heavy 2022","Destock 2022", "No Grazing 2022"), breaks = c("HG.2020","LG.2020","NG.2020","HG.2021","LG.2021","NG.2021","HG.2022","LG.2022","NG.2022"),name="")+
scale_color_manual(values=c("skyblue3","springgreen3","plum3","royalblue4","springgreen4","plum4","red","yellow","blue"),labels = c("Heavy 2020","Destock 2020", "No Grazing 2020","Heavy 2021","Destock 2021", "No Grazing 2021","Heavy 2022","Destock 2022", "No Grazing 2022"), breaks = c("HG.2020","LG.2020","NG.2020","HG.2021","LG.2021","NG.2021","HG.2022","LG.2022","NG.2022"),name="")+
scale_linetype_manual(values=c("solid","twodash","longdash","solid","twodash","longdash","solid","solid","solid"),labels = c("Heavy 2020","Destock 2020", "No Grazing 2020","Heavy 2021","Destock 2021", "No Grazing 2021","Heavy 2022","Destock 2022", "No Grazing 2022"), breaks = c("HG.2020","LG.2020","NG.2020","HG.2021","LG.2021","NG.2021","HG.2022","LG.2022","NG.2022"),name="")+
#make the text size of the legend titles 28
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Label the x-axis "NMDS1" and the y-axis "NMDS2"
xlab("NMDS1")+
ylab("NMDS2")+
theme(text = element_text(size = 55),legend.text=element_text(size=40))+
annotate(geom="text", x=-2, y=0.8, label="Dvac",size=20)
#### Create NMDS: Orthoptera Genus ####
NMDS_Sweep_OrthopteraGenus+
NMDS_Dvac_OrthopteraGenus+
plot_layout(ncol = 1,nrow = 2)
#Save at 4000x3000
#### PERMANOVA: Orthoptera Genus ####
##PerMANOVA
#Make a new dataframe with the data from Wide_Relative_Cover all columns after 5
Species_Matrix_D__OrthopteraGenus <- Abundance_Wide_D__OrthopteraGenus[,6:ncol(Abundance_Wide_D__OrthopteraGenus)]
#Make a new dataframe with data from Wide_Relative_Cover columns 1-3
Environment_Matrix_D__OrthopteraGenus <- Abundance_Wide_D__OrthopteraGenus[,1:5] %>%
mutate(Gr_Yr=paste(Grazing_Treatment,Year,sep="."))
Environment_Matrix_D__OrthopteraGenus$Grazing_Treatment_Fact=as.factor(Environment_Matrix_D__OrthopteraGenus$Grazing_Treatment)
Environment_Matrix_D__OrthopteraGenus$Block_Fact=as.numeric(Environment_Matrix_D__OrthopteraGenus$Block)
Environment_Matrix_D__OrthopteraGenus$Plot_Fact=as.factor(Environment_Matrix_D__OrthopteraGenus$Plot)
Environment_Matrix_D__OrthopteraGenus$Year_Fact=as.factor(Environment_Matrix_D__OrthopteraGenus$Year)
#run a perMANOVA comparing across watershed and exclosure, how does the species composition differ. Permutation = 999 - run this 999 times and tell us what the preportion of times it was dissimilar
#Adding in the 'strata' function does not affect results - i can't figure out if I am doing in incorrectly or if they do not affect the results (seems unlikely though becuase everything is exactly the same)
PerMANOVA2_D__OrthopteraGenus <- adonis2(formula = Species_Matrix_D__OrthopteraGenus~Grazing_Treatment_Fact*Year_Fact + (1 | Block_Fact) , data=Environment_Matrix_D__OrthopteraGenus,permutations = 999, method = "bray")
#give a print out of the PermMANOVA
print(PerMANOVA2_D__OrthopteraGenus) #Grazing (0.0187), Year (0.001), GxYear (NS)
#pairwise test
Posthoc_D__OrthopteraGenus_Year<-pairwise.adonis(Species_Matrix_D__OrthopteraGenus,factors=Environment_Matrix_D__OrthopteraGenus$Year, p.adjust.m = "BH")
Posthoc_D__OrthopteraGenus_Year #2020-2021 (0.001), 2021-2022 (0.001), 2020-2022 (0.001)
#pairwise test
Posthoc_D__OrthopteraGenus_Grazing_Year<-pairwise.adonis(Species_Matrix_D__OrthopteraGenus,factors=Environment_Matrix_D__OrthopteraGenus$Gr_Yr, p.adjust.m = "BH")
Posthoc_D__OrthopteraGenus_Grazing_Year #Significant: HG-NG (2021)
#### PERMDISP: Orthoptera Genus ####
Abundance_Wide_D__OrthopteraGenus_dispr<-Abundance_Wide_D__OrthopteraGenus %>%
mutate(Gr_Yr=paste(Grazing_Treatment,Year,sep="."))
#Dvac
#Make a new dataframe and calculate the dissimilarity of the Species_Matrix dataframe
BC_Distance_Matrix_D__OrthopteraGenus <- vegdist(Species_Matrix_D__OrthopteraGenus)
#Run a dissimilarity matrix (PermDisp) comparing grazing treatment
Dispersion_Results_Grazing_D__OrthopteraGenus <- betadisper(BC_Distance_Matrix_D__OrthopteraGenus,Abundance_Wide_D__OrthopteraGenus_dispr$Gr_Yr)
permutest(Dispersion_Results_Grazing_D__OrthopteraGenus,pairwise = T, permutations = 999)
#
#### Plant Species Analysis
#### Calculate Community Metrics ####
# uses codyn package and finds shannon's diversity
#FK Diversity
Diversity_PlantSp <- community_diversity(df = RelCov_FunctionalGroups,
replicate.var = "plot",
abundance.var = "Relative_Cover")
#FK Evenness
Structure_PlantSp <- community_structure(df = RelCov_FunctionalGroups,
replicate.var = "plot",
abundance.var = "Relative_Cover",
metric = "Evar")
#Make a new data frame from "Extra_Species_Identity" to generate richness values for each research area
Richness_PlantSp<-RelCov_FunctionalGroups %>%
#group data frame by Watershed and exclosure
group_by(grazing_treatment,plot,block) %>%
#Make a new column named "Richness" and add the unique number of rows in the column "taxa" according to the groupings
summarise(richness=length(Genus_Species)) %>%
#stop grouping by watershed and exclosure
ungroup()
#join the datasets
CommunityMetrics_PlantSp <- Diversity_PlantSp %>%
full_join(Structure_PlantSp) %>%
select(-richness) %>%
full_join(Richness_PlantSp)
#make dataframe with averages
CommunityMetrics_PlantSp_Avg<-CommunityMetrics_PlantSp %>%
group_by(grazing_treatment) %>%
summarize(Richness_Std=sd(richness),Richness_Mean=mean(richness),Richness_n=length(richness),
Shannon_Std=sd(Shannon),Shannon_Mean=mean(Shannon),Shannon_n=length(Shannon),
Evar_Std=sd(Evar,na.rm=T),Evar_Mean=mean(Evar,na.rm=T),Evar_n=length(Evar))%>%
mutate(Richness_St_Error=Richness_Std/sqrt(Richness_n),
Shannon_St_Error=Shannon_Std/sqrt(Shannon_n),
Evar_St_Error=Evar_Std/sqrt(Evar_n)) %>%
ungroup()
#### Plant Species Community Metrics Graphs ####
# 2022 - Dvac
Richness_PlantSp<-ggplot(CommunityMetrics_PlantSp_Avg,aes(x=grazing_treatment,y=Richness_Mean,fill=grazing_treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Richness_Mean-Richness_St_Error,ymax=Richness_Mean+Richness_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Richness"
ylab("Richness")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(legend.position = "none")+
#Make the y-axis extend to 50
expand_limits(y=20)+
scale_y_continuous(labels = label_number(accuracy = 1))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))
#geom_text(x=0.85, y=20, label="2022 Richness",size=20)
# 2022 - Dvac
Shannon_PlantSp<-ggplot(CommunityMetrics_PlantSp_Avg,aes(x=grazing_treatment,y=Shannon_Mean,fill=grazing_treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Shannon_Mean-Shannon_St_Error,ymax=Shannon_Mean+Shannon_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Shannon"
ylab("Shannon's Diversity")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(legend.position = "none")+
#Make the y-axis extend to 50
expand_limits(y=3)+
scale_y_continuous(labels = label_number(accuracy = 0.1))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))
#geom_text(x=0.85, y=3, label="2022 Shannon's",size=20)
# 2022 - Weight
Evar_PlantSp<-ggplot(CommunityMetrics_PlantSp_Avg,aes(x=grazing_treatment,y=Evar_Mean,fill=grazing_treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=Evar_Mean-Evar_St_Error,ymax=Evar_Mean+Evar_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Evar"
ylab("Evenness")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(legend.position = "none")+
#Make the y-axis extend to 50
expand_limits(y=0.6)+
scale_y_continuous(labels = label_number(accuracy = .01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))
#geom_text(x=0.85, y=1, label="2022 Weight",size=20)
#### Create Community Metrics Graph for Plant Species ####
Richness_PlantSp+
Shannon_PlantSp+
Evar_PlantSp+
plot_layout(ncol = 3,nrow = 1)
#### Plant Species Community Metrics: Normaility
#Richness
Richness_PlantSp_Norm <- lm(data = CommunityMetrics_PlantSp,(richness) ~ grazing_treatment)
ols_plot_resid_hist(Richness_PlantSp_Norm)
ols_test_normality(Richness_PlantSp_Norm) #normal
#Shannon
Shannon_PlantSp_Norm <- lm(data = CommunityMetrics_PlantSp,(Shannon) ~ grazing_treatment)
ols_plot_resid_hist(Shannon_PlantSp_Norm)
ols_test_normality(Shannon_PlantSp_Norm) #normal
#Evar
Evar_PlantSp_Norm <- lm(data = CommunityMetrics_PlantSp,(Evar) ~ grazing_treatment)
ols_plot_resid_hist(Evar_PlantSp_Norm)
ols_test_normality(Evar_PlantSp_Norm) #normal
#### Glmm for Plant species community metrics ####
# Richness
Richness_PlantSp_Glmm <- lmer((richness) ~ grazing_treatment + (1 | block) , data = CommunityMetrics_PlantSp)
anova(Richness_PlantSp_Glmm) #not significant
# Shannon
Shannon_PlantSp_Glmm <- lmer((Shannon) ~ grazing_treatment + (1 | block) , data = CommunityMetrics_PlantSp)
anova(Shannon_PlantSp_Glmm) #0.003476
# post hoc test for lmer test
summary(glht(Shannon_PlantSp_Glmm, linfct = mcp(grazing_treatment = "Tukey")), test = adjusted(type = "BH")) #NG-LG (p=0.16341), #LG-HG (8.98e-05), NG-HG (0.00815)
# Evar
Evar_PlantSp_Glmm <- lmer((Evar) ~ grazing_treatment + (1 | block) , data = CommunityMetrics_PlantSp)
anova(Evar_PlantSp_Glmm) #0.01525
# post hoc test for lmer test
summary(glht(Evar_PlantSp_Glmm, linfct = mcp(grazing_treatment = "Tukey")), test = adjusted(type = "BH")) #NG-LG (p=0.67105), #LG-HG (0.00606), NG-HG (0.01163)
#### NMDS for Plant Community
RelCov_FunctionalGroups_Wide<-RelCov_FunctionalGroups %>%
select(-c(Native_Introduced,Functional_Group,Annual_Perennial,Common.Name)) %>%
spread(key=Genus_Species,value=Relative_Cover, fill=0)
#### Make new data frame called BC_Data and run an NMDS
#dvac
BC_Data_PlantSp <- metaMDS(RelCov_FunctionalGroups_Wide[,4:41])
#look at species signiciance driving NMDS
intrinsics <- envfit(BC_Data_PlantSp, RelCov_FunctionalGroups_Wide, permutations = 999)
head(intrinsics)
#Make a data frame called sites with 1 column and same number of rows that is in Wide Order Count
sites <- 1:nrow(RelCov_FunctionalGroups_Wide)
#Make a new data table called BC_Meta_Data and use data from Wide_Relative_Cover columns 1-3
BC_Meta_Data_PlantSp <- RelCov_FunctionalGroups_Wide[,1:3]
#make a plot using the dataframe BC_Data and the column "points". Make Grazing Treatment a factor - make the different grazing treatments different colors
plot(BC_Data_PlantSp$points,col=as.factor(BC_Meta_Data_PlantSp$grazing_treatment))
#make elipses using the BC_Data. Group by grazing treatment and use standard deviation to draw eclipses
ordiellipse(BC_Data_PlantSp,groups = as.factor(BC_Meta_Data_PlantSp$grazing_treatment),kind = "sd",display = "sites", label = T)
#Make a data frame called BC_NMDS and at a column using the first set of "points" in BC_Data and a column using the second set of points. Group them by watershed
BC_NMDS_PlantSp = data.frame(MDS1 = BC_Data_PlantSp$points[,1], MDS2 = BC_Data_PlantSp$points[,2],group=BC_Meta_Data_PlantSp$grazing_treatment)
#Make data table called BC_NMDS_Graph and bind the BC_Meta_Data, and BC_NMDS data together
BC_NMDS_Graph_PlantSp <- cbind(BC_Meta_Data_PlantSp,BC_NMDS_PlantSp)
#Make a data table called BC_Ord_Ellipses using data from BC_Data and watershed information from BC_Meta_Data. Display sites and find the standard error at a confidence iinterval of 0.95. Place lables on the graph
BC_Ord_Ellipses_PlantSp<-ordiellipse(BC_Data_PlantSp, BC_Meta_Data_PlantSp$grazing_treatment, display = "sites",
kind = "sd", conf = 0.95, label = T)
#Make a new empty data frame called BC_Ellipses
BC_Ellipses_PlantSp <- data.frame()
#Generate ellipses points - switched levels for unique - not sure if it's stil correct but it looks right
for(g in unique(BC_NMDS_PlantSp$group)){
BC_Ellipses_PlantSp <- rbind(BC_Ellipses_PlantSp, cbind(as.data.frame(with(BC_NMDS_PlantSp[BC_NMDS_PlantSp$group==g,], veganCovEllipse(BC_Ord_Ellipses_PlantSp[[g]]$cov,BC_Ord_Ellipses_PlantSp[[g]]$center,BC_Ord_Ellipses_PlantSp[[g]]$scale)))
,group=g))
}
#### NMDS Figures: Plant Community ####
#Plot the data from BC_NMDS_Graph, where x=MDS1 and y=MDS2, make an ellipse based on "group"
ggplot(data = BC_NMDS_Graph_PlantSp, aes(MDS1,MDS2, shape = group,color=group,linetype=group))+
#make a point graph where the points are size 5. Color them based on exlosure
geom_point(size=8, stroke = 2) +
#Use the data from BC_Ellipses to make ellipses that are size 1 with a solid line
geom_path(data = BC_Ellipses_PlantSp, aes(x=NMDS1, y=NMDS2), size=4)+
#make shape, color, and linetype in one combined legend instead of three legends
labs(color = "", linetype = "", shape = "")+
scale_color_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"),limits=c("NG","LG","HG"))+
scale_linetype_manual(values=c(1,2,3),labels=c("High Impact Grazing","Cattle Removal","Destock"),limits=c("NG","LG","HG"))+
scale_shape_manual(values=c(15,16,17),labels=c("High Impact Grazing","Cattle Removal","Destock"),limits=c("NG","LG","HG"))+
# make legend 2 columns
guides(shape=guide_legend(ncol=1),colour=guide_legend(ncol=1),linetype=guide_legend(ncol=1))+
#make the text size of the legend titles 28
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"))+
#Label the x-axis "NMDS1" and the y-axis "NMDS2"
xlab("NMDS1")+
ylab("NMDS2")+
theme(text = element_text(size = 55),legend.text=element_text(size=40))
#annotate(geom="text", x=-2, y=0.8, label="Count",size=20)
#export at 2000 x 1800
#### PERMANOVA: Plant Community ####
##PerMANOVA
#Make a new dataframe with the data from Wide_Relative_Cover all columns after 5
Species_Matrix_PlantSp <- RelCov_FunctionalGroups_Wide[,4:ncol(RelCov_FunctionalGroups_Wide)]
#Make a new dataframe with data from Wide_Relative_Cover columns 1-3
Environment_Matrix_PlantSp <- RelCov_FunctionalGroups_Wide[,1:3]
Environment_Matrix_PlantSp$Grazing_Treatment_Fact=as.factor(Environment_Matrix_PlantSp$grazing_treatment)
Environment_Matrix_PlantSp$Block_Fact=as.numeric(Environment_Matrix_PlantSp$block)
Environment_Matrix_PlantSp$Plot_Fact=as.factor(Environment_Matrix_PlantSp$plot)
#run a perMANOVA comparing across watershed and exclosure, how does the species composition differ. Permutation = 999 - run this 999 times and tell us what the preportion of times it was dissimilar
#Adding in the 'strata' function does not affect results - i can't figure out if I am doing in incorrectly or if they do not affect the results (seems unlikely though becuase everything is exactly the same)
PerMANOVA2_PlantSp <- adonis2(formula = Species_Matrix_PlantSp~Grazing_Treatment_Fact + (1 | Block_Fact) , data=Environment_Matrix_PlantSp,permutations = 999, method = "bray")
#give a print out of the PermMANOVA
print(PerMANOVA2_PlantSp) #NS
#### PERMDISP: Plant Community ####
#Dvac
#Make a new dataframe and calculate the dissimilarity of the Species_Matrix dataframe
BC_Distance_Matrix_PlantSp <- vegdist(Species_Matrix_PlantSp)
#Run a dissimilarity matrix (PermDisp) comparing grazing treatment
Dispersion_Results_PlantSp <- betadisper(BC_Distance_Matrix_PlantSp,RelCov_FunctionalGroups_Wide$grazing_treatment)
permutest(Dispersion_Results_PlantSp,pairwise = T, permutations = 999) #NS
#### Relative Cover Figure
FG_RelCov_Avg<-RelCov_FunctionalGroups %>%
group_by(grazing_treatment) %>%
summarize(RelCov_Std=sd(Relative_Cover),RelCov_Mean=mean(Relative_Cover),RelCov_n=length(Relative_Cover))%>%
mutate(RelCov_St_Error=RelCov_Std/sqrt(RelCov_n)) %>%
ungroup()
#Rel Cov
ggplot(FG_RelCov_Avg,aes(x=grazing_treatment,y=RelCov_Mean,fill=grazing_treatment))+
#Make a bar graph where the height of the bars is equal to the data (stat=identity) and you preserve the vertical position while adjusting the horizontal(position_dodge)
geom_bar(stat="identity",position = "dodge")+
#Make an error bar that represents the standard error within the data and place the error bars at position 0.9 and make them 0.2 wide.
geom_errorbar(aes(ymin=RelCov_Mean-RelCov_St_Error,ymax=RelCov_Mean+RelCov_St_Error),position=position_dodge(),width=0.2)+
#Label the x-axis "Treatment"
xlab("Grazing Treatment")+
#Label the y-axis "Species Evar"
ylab("Relative Cover (%)")+
theme(legend.background=element_blank())+
scale_x_discrete(labels=c("HG"="High Impact Grazing","LG"="Destock","NG"="Cattle Removal"),limits=c("NG","LG","HG"))+
scale_fill_manual(values=c("thistle2","thistle3","thistle4"), labels=c("High Impact Grazing","Cattle Removal","Destock"))+
theme(legend.key = element_rect(size=3), legend.key.size = unit(1,"centimeters"),legend.position="NONE")+
#Make the y-axis extend to 50
expand_limits(y=1)+
scale_y_continuous(labels = label_number(accuracy = .01))+
theme(text = element_text(size = 55),legend.text=element_text(size=45))
#geom_text(x=0.85, y=1, label="2020 Count",size=20)
#### Relative Cover Normality ####
Normality_RelCov<- lm(data = FG_RelCov, log(Relative_Cover) ~ grazing_treatment)
ols_plot_resid_hist(Normality_RelCov)
ols_test_normality(Normality_RelCov) #not great but okay
#### Relative Cover Stats ####
RelCov_GLMM <- lmerTest::lmer(data = FG_RelCov, log(Relative_Cover) ~ grazing_treatment + (1|block))
anova(RelCov_GLMM, type = 3) #0.03647
# post hoc test for lmer test
summary(glht(RelCov_GLMM, linfct = mcp(grazing_treatment = "Tukey")), test = adjusted(type = "BH")) #NG-LG (p=0.5056), #LG-HG (0.1093), NG-HG (0.0351)
#### Relative Cover of Functional Group ####
FG_RelCov<-RelCov_FunctionalGroups %>%
mutate(Relative_Cover=Relative_Cover/100)
### Normality ####
#Forbs
Normality_Forb<- lm(data = subset(FG_RelCov, Functional_Group=="Forb"), 1/(Relative_Cover) ~ grazing_treatment)
ols_plot_resid_hist(Normality_Forb)
ols_test_normality(Normality_Forb) #not great but okay
#C4
Normality_C4<- lm(data = subset(FG_RelCov, Functional_Group=="C4"), log(Relative_Cover) ~ grazing_treatment)
ols_plot_resid_hist(Normality_C4)
ols_test_normality(Normality_C4) #normalish
#C3
Normality_C3<- lm(data = subset(FG_RelCov, Functional_Group=="C3"), log(Relative_Cover) ~ grazing_treatment)
ols_plot_resid_hist(Normality_C3)
ols_test_normality(Normality_C3) #normalish
#Brome
Normality_Brome<- lm(data = subset(FG_RelCov, Functional_Group=="Brome"), log(Relative_Cover) ~ grazing_treatment)
ols_plot_resid_hist(Normality_Brome)
ols_test_normality(Normality_Brome) #normalish
#Woody
Normality_Woody<- lm(data = subset(FG_RelCov, Functional_Group=="Woody"), log(Relative_Cover) ~ grazing_treatment)
ols_plot_resid_hist(Normality_Woody)
ols_test_normality(Normality_Woody) #normalish
#### Stats: Functional Groups ####
#Forbs
Forbs_GLMM <- lmerTest::lmer(data = subset(FG_RelCov, Functional_Group=="Forb"), 1/(Relative_Cover) ~ grazing_treatment + (1|block))
anova(Forbs_GLMM) #ns
#C4
C4_GLMM <- lmerTest::lmer(data = subset(FG_RelCov, Functional_Group=="C4"), log(Relative_Cover) ~ grazing_treatment + (1|block))
anova(C4_GLMM) #ns
#C3
C3_GLMM <- lmerTest::lmer(data = subset(FG_RelCov, Functional_Group=="C3"), log(Relative_Cover) ~ grazing_treatment + (1|block))
anova(C3_GLMM) #ns
#Brome
Brome_GLMM <- lmerTest::lmer(data = subset(FG_RelCov, Functional_Group=="Brome"), log(Relative_Cover) ~ grazing_treatment + (1|block))
anova(Brome_GLMM) #ns
#Woody
Woody_GLMM <- lmerTest::lmer(data = subset(FG_RelCov, Functional_Group=="Woody"), log(Relative_Cover) ~ grazing_treatment + (1|block))
anova(Woody_GLMM) #ns
#### Rank Abundance Curves: Plant Species ####
Rank_Abundance <- FG_RelCov %>%
mutate(Relative_Cover=Relative_Cover*100) %>%
group_by(grazing_treatment,Genus_Species,Native_Introduced,Annual_Perennial,Functional_Group) %>%
summarize(avg_cover=mean(Relative_Cover))%>%
ungroup()%>%
arrange(grazing_treatment, -avg_cover)%>%
group_by(grazing_treatment)%>%
mutate(rank=seq_along(grazing_treatment))%>%
ungroup()
ggplot(data=Rank_Abundance, aes(x=rank, y=avg_cover)) +
geom_line() +
geom_point(size=3) +
geom_point(aes(color=Native_Introduced,shape=Native_Introduced),size=3) +
xlab('') +
ylab('Relative Cover (%)') +
# scale_x_continuous(expand=c(0,0), limits=c(0.5,17), breaks=seq(0,17,5)) +
# scale_y_continuous(expand=c(0,0), limits=c(0,60), breaks=seq(0,60,10)) +
geom_text(aes(y=avg_cover+1.2, x=rank+0.1, label=Genus_Species), hjust='left', vjust='center', angle=90, size=4)+
expand_limits(y=100)+
theme(legend.position = "none")+
facet_grid(~grazing_treatment)
#save at 1500 x 1000
|
class Solution {
public int minDistance(String word1, String word2) {
int wordOneLength = word1.length();
int wordTwoLength = word2.length();
int[][] dp = new int[wordOneLength + 1][wordTwoLength + 1];
for (int i = 1; i <= wordOneLength; i++)
dp[i][0] = i;
for (int j = 1; j <= wordTwoLength; j++)
dp[0][j] = j;
for (int i = 1; i <= wordOneLength; i++) {
for (int j = 1; j <= wordTwoLength; j++) {
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
}
else {
dp[i][j] = Math.min(dp[i - 1][j - 1],
Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;
}
}
}
return dp[wordOneLength][wordTwoLength];
}
}
|
import { useEffect, useState } from 'react';
import {Link, useNavigate} from 'react-router-dom'
import ContactService from '../services/ContactService';
function AddContact() {
let navigate = useNavigate()
let [state,setState] = useState({
loading:false,
contact:{name:"",email:"",mobile:"",company:"",profession:"",groupid:""},
groups:[],
errorMesssage:""
})
let handleInput=(e)=>{
setState({...state,contact:{...state.contact,[e.target.name]:e.target.value}})
}
useEffect(()=>{
ContactService.getGroups().then((res)=>{
setState({...state,groups:res.data})
})
},[])
let submitForm=(e)=>{
e.preventDefault()
ContactService.createContact(state.contact).then((res)=>{
navigate("/")
})
}
let {loading,contact,groups,errorMesssage}= state
return (
<>
{/* <pre>{JSON.stringify(contact)}</pre> */}
<section className="add-contact p-3">
<div className="container">
<div className="row">
<div className="col">
<p className="h3 text-succes fw-bold">Create Contact</p>
<p className="fst-italic">
lorem ipsmun jnjnj sjhksjs i skk bsnnjs
</p>
</div>
<div className="row">
<div className="col-md-4">
<form onSubmit={submitForm}>
<input
type="text"
name="name" value={contact.name} onChange={handleInput} required
className="form-control my-2"
placeholder="Full Name"
/>
<input
type="email"
name="email" value={contact.email} onChange={handleInput} required
className="form-control my-2"
placeholder="Email Id"
/>
<input
type="number"
name="mobile" value={contact.mobile} onChange={handleInput} required
className="form-control my-2"
placeholder="Mobile Number"
/>
<input
type="text"
name="company" value={contact.company} onChange={handleInput} required
className="form-control my-2"
placeholder="Company"
/>
<input
type="text"
name="profession" value={contact.profession} onChange={handleInput} required
className="form-control my-2"
placeholder="Profession"
/>
<select className="form-control my-2 "
name="groupid" onChange={handleInput} required
>
<option disabled selected> Select Group </option>
{
groups.map((group)=>(
<option key={group.id} value={group.id} >{group.groupname}</option>
))
}
</select>
<div className='row'>
<div className='col-md-8'>
<input type="submit" className="btn btn-success w-100" value="Create"/>
</div>
<div className='col-md-4'>
<Link to="/contacts/list" className='btn btn-dark w-100'>Cancel</Link>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
</>
);
}
export default AddContact;
|
<!DOCTYPE html>
<html lang="uk">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="./styles.css/reset.css">
<link rel="stylesheet" href="./styles.css/styles.css">
</head>
<body>
<div class="page_wrapper">
<header class="header">
<div class="container">
<nav class="main_nav">
<ul class="nav_list">
<li class="nav_item">
<a href="#" class="nav_link active">Home</a>
</li>
<li class="nav_item">
<a href="#" class="nav_link">about me</a>
</li>
<li class="nav_item">
<a href="#" class="nav_link">skills</a>
</li>
<li class="nav_item">
<a href="#" class="nav_link">portfolio</a>
</li>
<li class="nav_item">
<a href="#" class="nav_link">contacts</a>
</li>
</ul>
</nav>
</div>
</header>
<section class="main_screen">
<div class="container">
<h1 class="site_name">Denis Novik</h1>
<div class="image_wrapper">
<img src="./img/main_screen.jpg" alt="" class="main_screen__image">
</div>
</div>
</section>
<section class="about">
<div class="container">
<h2 class="site_heading mb-50">about me</h2>
<div class="about_content">
<p>
Hi, I'm Denis – UX/UI designer from Minsk.<br>
I'm interested in design and everything connected with it.
</p>
<p>
I'm studying at courses "Web and mobile design
interfaces" in IT-Academy.
</p>
<p>
Ready to implement excellent projects<br>
with wonderful people.
</p>
</div>
</div>
</section>
<section class="skills">
<div class="container">
<h2 class="site_heading mb-20">skills</h2>
<p class="site_sub_heading">I work in such programs as</p>
<div class="skills_content">
<ul class="skills_list">
<li class="skill_item">
<img src="./img/Ps.svg" alt="photoshop" class="skill_img">
<p class="skill_item_name">
Adobe Photoshop
</p>
<ul class="rating">
<li class="rating_item active"></li>
<li class="rating_item active"></li>
<li class="rating_item"></li>
<li class="rating_item"></li>
<li class="rating_item"></li>
</ul>
</li>
<li class="skill_item">
<img src="./img/Ai.svg" alt="Illustrator" class="skill_img">
<p class="skill_item_name">
Adobe Illustrator
</p>
<ul class="rating">
<li class="rating_item active"></li>
<li class="rating_item active"></li>
<li class="rating_item active"></li>
<li class="rating_item"></li>
<li class="rating_item"></li>
</ul>
</li>
<li class="skill_item">
<img src="./img/Ae.svg" alt="After Effects" class="skill_img">
<p class="skill_item_name">
Adobe <br>After Effects
</p>
<ul class="rating">
<li class="rating_item active"></li>
<li class="rating_item active"></li>
<li class="rating_item active"></li>
<li class="rating_item active"></li>
<li class="rating_item"></li>
</ul>
</li>
<li class="skill_item">
<img src="./img/Figma.svg" alt="Figma" class="skill_img">
<p class="skill_item_name">
Figma
</p>
<ul class="rating">
<li class="rating_item active"></li>
<li class="rating_item active"></li>
<li class="rating_item active"></li>
<li class="rating_item active"></li>
<li class="rating_item active"></li>
</ul>
</li>
</ul>
</div>
</div>
</section>
<section class="portfolio">
<div class="container">
<h2 class="site_heading mb-50">portfolio</h2>
<ul class="portfolio_list">
<li class="portfolio_item">
<div class="image_wrapper">
<img src="./img/Fashion-Store.svg" alt="" class="fashion_store__image">
</div>
<a href="#" class="portfolio_link">
Online fashion store - Homepage
</a>
</li>
<li class="portfolio_item">
<div class="image_wrapper">
<img src="./img/reebok_web.svg" alt="" class="reebok_web__image">
</div>
<a href="#" class="portfolio_link">
Reebok Store - Concept
</a>
</li>
<li class="portfolio_item">
<div class="image_wrapper">
<img src="./img/braun-landing.svg" alt="" class="braun_landing__image">
</div>
<a href="#" class="portfolio_link">
Braun Landing Page - Concept
</a>
</li>
</ul>
</div>
</section>
<section class="contacts">
<div class="container">
<div class="contacts_heading">
<h2 class="site_heading mb-20">Contacts</h2>
<p class="site_sub_heading">
Want to know more or just chat? <br>You are welcome!
</p>
</div>
<div class="social_content">
<button type="button" class="social_button">Send message</button>
<ul class="social_list">
<li class="social_item">
<a href="#" class="social_link">
<img src="./img/linkedin.svg" alt="linkedin" class="social_image">
</a>
</li>
<li class="social_item">
<a href="#" class="social_link">
<img src="./img/instagram.svg" alt="instagram" class="social_image">
</a>
</li>
<li class="social_item">
<a href="#" class="social_link">
<img src="./img/behance.svg" alt="behance" class="social_image">
</a>
</li>
<li class="social_item">
<a href="#" class="social_link">
<img src="./img/dribbble.svg" alt="dribbble" class="social_image">
</a>
</li>
</ul>
</div>
<p class="site_sub_footer">
Like me on <br>
LinkedIn, Instagram, Behance,
<br>Dribble
</p>
</div>
</section>
</div>
</body>
</html>
|
import { Parser } from "./parser.mjs";
import { DatabaseError } from "./databaseError.mjs";
export class Database {
constructor() {
this.tables = {};
this.parser = new Parser();
}
createTable(parsedStatement) {
const tableName = parsedStatement[1];
const commandColumns = parsedStatement[2];
const columns = commandColumns.split(', ');
this.tables = {
[tableName]: {
columns: {},
data: []
}
};
for (const column of columns) {
const item = column.split(" ");
const col = item[0];
const tipo = item[1];
this.tables[tableName].columns[col] = tipo;
}
return this;
}
execute(statement) {
return new Promise((resolve, reject) => {
setTimeout(() => {
const result = this.parser.parse(statement);
if (result) {
resolve(this[result.command](result.parsedStatement));
}
reject(new DatabaseError(statement, `Syntax error: '${statement}'`));
}, 1000);
})
}
insert(parsedStatement) {
const tableName = parsedStatement[1];
const columns = parsedStatement[2].split(', ');
const values = parsedStatement[3].split(', ');
let row = {};
for (let i = 0; i < values.length; i++) {
const column = columns[i];
const value = values[i];
row[column] = value;
}
this.tables[tableName].data.push(row);
}
select(parsedStatement) {
const columns = parsedStatement[1].split(", ");
const tableName = parsedStatement[2];
let rows = this.tables[tableName].data;
const whereClause = parsedStatement[3] || null;
if (whereClause !== null) {
const whereCondition = whereClause.split(" ");
const [columnWhere, condition, valueWhere] = whereCondition;
rows = rows.filter(function (row) {
return (row[columnWhere] === valueWhere);
})
}
rows = rows.map(function (row) {
let selectedRows = {};
columns.forEach(function (column) {
selectedRows[column] = row[column];
})
return selectedRows;
});
console.log(rows);
}
delete(parsedStatement) {
let [, tableName, whereClause] = parsedStatement;
let rows = [];
if (whereClause) {
whereClause = whereClause.split(" ");
const [whereColumn, condition, whereValue] = whereClause;
rows = this.tables[tableName].data;
rows = rows.filter(function (row) {
return (row[whereColumn] !== whereValue);
})
}
this.tables[tableName].data = rows;
console.log(rows);
}
};
|
using AutoMapper;
using Business.Abstracts;
using Business.DTOs.Request.Exam;
using Business.DTOs.Response.Exam;
using Business.DTOs.Response.Question;
using Business.Rules.BusinessRules;
using Core.DataAccess.Paging;
using DataAccess.Abstracts;
using Entities.Concretes.CoursesFolder;
using Microsoft.EntityFrameworkCore;
namespace Business.Concretes
{
public class ExamManager : IExamService
{
private readonly IExamDal _examDal;
private readonly IMapper _mapper;
ExamBusinessRules _examBusinessRules;
public ExamManager(IExamDal examDal, IMapper mapper, ExamBusinessRules examBusinessRules)
{
_examDal = examDal;
_mapper = mapper;
_examBusinessRules = examBusinessRules;
}
public async Task<IPaginate<GetListExamResponse>> GetListAsync(PageRequest pageRequest)
{
var data = await _examDal.GetListAsync(index: pageRequest.PageIndex, size: pageRequest.PageSize);
var result = _mapper.Map<Paginate<GetListExamResponse>>(data);
return result;
}
public async Task<CreatedExamResponse> Add(CreateExamRequest createExamRequest)
{
// AutoMapper kullanarak DTO'dan Entity'e dönüşüm yapılıyor.
var exam = _mapper.Map<Exam>(createExamRequest);
// EF Core, Exam nesnesini ve ona bağlı tüm Question ve Option nesnelerini otomatik olarak ekler.
await _examDal.AddAsync(exam);
// Sonuç olarak oluşturulan Exam nesnesini DTO'ya dönüştürüyoruz.
var result = _mapper.Map<CreatedExamResponse>(exam);
return result;
}
public async Task<UpdatedExamResponse> Update(UpdateExamRequest updateExamRequest)
{
var examDal = await _examDal.GetAsync(e => e.Id == updateExamRequest.Id);
_mapper.Map(updateExamRequest, examDal);
await _examDal.UpdateAsync(examDal);
var result = _mapper.Map<UpdatedExamResponse>(examDal);
return result;
}
public async Task<DeletedExamResponse> Delete(DeleteExamRequest deleteExamRequest)
{
var examDal = await _examDal.GetAsync(e => e.Id == deleteExamRequest.Id);
var deletedExam = await _examDal.DeleteAsync(examDal);
var result = _mapper.Map<DeletedExamResponse>(deletedExam);
return result;
}
public async Task<CreatedExamResponse> GetById(int id)
{
var result = await _examDal.GetAsync(c => c.Id == id);
Exam mappedExam = _mapper.Map<Exam>(result);
CreatedExamResponse createdExamResponse = _mapper.Map<CreatedExamResponse>(mappedExam);
return createdExamResponse;
}
public async Task<List<GetListExamResponse>> GetExamsByCourseId(int courseId)
{
var examDals = await _examDal.GetListAsync(e => e.CourseId == courseId);
var result = _mapper.Map<List<GetListExamResponse>>(examDals);
return result;
}
public async Task<List<GetListQuestionResponse>> GetRandomQuestionsByExamId(int examId)
{
var exam = await _examDal.GetAsync(e => e.Id == examId, include: q => q.Include(e => e.Questions).ThenInclude(q => q.Options));
var questions = exam.Questions;
// Soruları GetListQuestionResponse listesine dönüştür
var result = _mapper.Map<List<GetListQuestionResponse>>(questions);
return result;
}
public async Task<StudentExamResultDto> SubmitExamResults(SubmitExamResultDto submitExamResultDto)
{
// Sınav sorularını al
var exam = await _examDal.GetAsync(e => e.Id == submitExamResultDto.ExamId, include: q => q.Include(e => e.Questions).ThenInclude(q => q.Options));
var questions = exam.Questions;
// Sınav sonuçlarını hesapla
var examResult = CalculateExamResult(submitExamResultDto.Answers, questions);
// StudentExamResult entity'sini oluştur
var studentExamResult = new StudentExamResult
{
StudentId = submitExamResultDto.StudentId,
ExamId = submitExamResultDto.ExamId,
CorrectAnswers = examResult.CorrectAnswers,
WrongAnswers = examResult.WrongAnswers,
Unanswered = examResult.Unanswered
};
// Sonuçları veritabanına kaydet
//await _studentExamResultDal.AddAsync(studentExamResult);
// Kaydedilen sonuçları DTO olarak dön
var result = _mapper.Map<StudentExamResultDto>(studentExamResult);
return result;
}
public ExamResultDto CalculateExamResult(List<UserAnswerDto> userAnswers, List<Question> questions)
{
var result = new ExamResultDto();
foreach (var question in questions)
{
var userAnswer = userAnswers.FirstOrDefault(ua => ua.QuestionId == question.Id);
// Kullanıcı bu soruya cevap vermemişse
if (userAnswer == null || userAnswer.SelectedOptionId == null)
{
result.Unanswered++;
continue;
}
// Kullanıcının verdiği cevap doğru mu?
var correctOption = question.Options.FirstOrDefault(o => o.IsCorrect);
if (correctOption != null && userAnswer.SelectedOptionId == correctOption.Id)
{
result.CorrectAnswers++;
}
else
{
result.WrongAnswers++;
}
}
return result;
}
}
}
|
const express = require("express");
const router = express.Router();
const User = require("../models/User");
const { body, validationResult } = require("express-validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const fetchuser = require("../middleware/fetchuser");
let JWT_SECRET = "Iamagoodboy";
// ROUTE 1: Create a user or Signup using: POST "/api/auth/createuser" No login required
router.post(
"/createuser",
[
body("name", "Please enter a valid name").isLength({ min: 3 }),
body("email", "Please enter a valid email").isEmail(),
body("password", "Password must be atleast 5 character").isLength({
min: 5,
}),
],
async (req, res) => {
let success = false;
// If there are errors, return bad request and errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({success, errors: errors.array() });
}
// Check weather the user with this email exists already
try {
let user = await User.findOne({ email: req.body.email });
if (user) {
return res
.status(400)
.json({success, error: "Sorry a user with this email already exists." });
}
// Hashing the password and added the salt to password
const salt = await bcrypt.genSalt(10);
const secPass = await bcrypt.hash(req.body.password, salt);
// Create a new user
user = await User.create({
name: req.body.name,
email: req.body.email,
password: secPass,
});
const data = {
user: {
id: user.id,
},
};
// Creating authentication token
const authToken = jwt.sign(data, JWT_SECRET);
// res.json({ Success: "User added successfuly!" });
success = true;
res.json({success, authToken });
} catch (error) {
console.log(error.message);
res.status(400).send("Some error occurred!");
}
}
);
// ROUTE 2: Authenticate a user or login using: POST "/api/auth/login" No login required
router.post(
"/login",
[
body("email", "Please enter a valid email").isEmail(),
body("password", "Password cannot be blank").exists(),
],
async (req, res) => {
// If there are errors, return bad request and errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
const user = await User.findOne({ email });
if (!user) {
success = false;
return res
.status(400)
.json({ success, error: "Please try to login with correct credentials." });
}
const comparePassword = await bcrypt.compare(password, user.password);
if (!comparePassword) {
success = false;
return res
.status(400)
.json({success, error: "Please try to login with correct credentials." });
}
const data = {
user: {
id: user.id,
},
};
// Creating authentication token
const authToken = jwt.sign(data, JWT_SECRET);
success = true;
res.json({ success, authToken });
} catch (error) {
console.log(error.message);
res.status(500).send("Internal Server Error!");
}
}
);
// ROUTE 3: Get loggedin user details using: POST "/api/auth/getuser" Login required
router.post("/getuser", fetchuser, async (req, res) => {
try {
userId = req.user.id;
const user = await User.findById(userId).select("-password");
res.send(user);
} catch (error) {
console.log(error.message);
res.status(500).send("Internal Server Error!");
}
});
module.exports = router;
|
import React from 'react'
import { LocalStorageStatic } from '@lottery/utils'
import { MaskBalanceTypes } from './types'
import { MaskBalanceContext } from './useMakeBalance'
export interface MaskBalanceProviderProps {
children: React.ReactNode
isMaskDefault?: boolean
storeKey?: string
}
export const MaskBalanceProvider: React.FC<MaskBalanceProviderProps> = ({ children, isMaskDefault = false, storeKey = '@maskBalance' }) => {
const [isMask, onSetMask] = React.useState<boolean>(isMaskDefault || false)
React.useEffect(() => {
const m = LocalStorageStatic.getItem<boolean>(storeKey)
if (m === null) {
LocalStorageStatic.setItem<boolean>(storeKey, isMaskDefault)
} else {
onSetMask(m)
}
}, [isMaskDefault, storeKey])
const onSetMaskBalance = React.useCallback(() => {
const ourMask = !isMask
onSetMask(ourMask)
LocalStorageStatic.setItem<boolean>(storeKey, ourMask)
}, [isMask, storeKey])
const value: MaskBalanceTypes.ContextState = {
isMask,
onSetMaskBalance
}
return <MaskBalanceContext.Provider value={value}>{children}</MaskBalanceContext.Provider>
}
|
#pragma once
#include <memory>
#include "Core/Io/LogManager.hpp"
#include "Core/Event/EventManager.hpp"
#include "Core/EntityManager.hpp"
#include "Core/ComponentManager.hpp"
#include "Core/SystemManager.hpp"
class Coordinator
{
public:
Coordinator(LogLevel logLevel)
: mLogManager(std::make_unique<LogManager>(logLevel)),
mEventManager(std::make_unique<EventManager>()),
mEntityManager(std::make_unique<EntityManager>()),
mComponentManager(std::make_unique<ComponentManager>()),
mSystemManager(std::make_unique<SystemManager>())
{ }
// EventManager Methods
void AddListener(EventId id, std::function<void(Event const&)> const& listener) const
{
mEventManager.get()->AddListener(id, listener);
}
void SendEvent(Event const& event) const
{
mEventManager.get()->SendEvent(event);
}
void SendEvent(const EventId id) const
{
mEventManager.get()->SendEvent(id);
}
// EntityManager Methods
Entity CreateEntity() const
{
return mEntityManager->CreateEntity();
}
void DestroyEntity(Entity entity) const
{
mEntityManager->DestroyEntity(entity);
mComponentManager->EntityDestroyed(entity);
mSystemManager->EntityDestroyed(entity);
}
// ComponentManager Methods
template<typename T>
void RegisterComponent() const
{
mComponentManager->RegisterComponent<T>();
}
template<typename T>
void AddComponent(Entity entity, T component) const
{
mComponentManager->AddComponent(entity, component);
auto signature = mEntityManager->GetSignature(entity);
signature.set(mComponentManager->GetComponentType<T>(), true);
mEntityManager->SetSignature(entity, signature);
mSystemManager->EntitySignatureChanged(entity, signature);
}
template<typename T>
void RemoveComponent(Entity entity) const
{
mComponentManager->RemoveComponent<T>(entity);
auto signature = mEntityManager->GetSignature(entity);
signature.set(mComponentManager->GetComponentType<T>(), false);
mEntityManager->SetSignature(entity, signature);
mSystemManager->EntitySignatureChanged(entity, signature);
}
template<typename T>
T& GetComponent(Entity entity) const
{
return mComponentManager->GetComponent<T>(entity);
}
template<typename T>
ComponentType GetComponentType() const
{
return mComponentManager->GetComponentType<T>();
}
// SystemManager Methods
template<typename T>
std::shared_ptr<T> RegisterSystem() const
{
return mSystemManager->RegisterSystem<T>();
}
template<typename T>
void SetSystemSignature(Signature signature) const
{
mSystemManager->SetSignature<T>(signature);
}
// LogManager Methods
template <typename... Args>
void LogDebug(Args&&... args) const
{
mLogManager->Debug(args...);
}
template <typename... Args>
void LogInfo(Args&&... args) const
{
mLogManager->Info(args...);
}
template <typename... Args>
void LogError(Args&&... args) const
{
mLogManager->Error(args...);
}
template<typename T, typename... Args>
void Assert(T condition, Args&&... args) const
{
mLogManager->Assert(condition, args...);
}
private:
const std::unique_ptr<LogManager> mLogManager;
const std::unique_ptr<EventManager> mEventManager;
const std::unique_ptr<EntityManager> mEntityManager;
const std::unique_ptr<ComponentManager> mComponentManager;
const std::unique_ptr<SystemManager> mSystemManager;
};
|
/* eslint-disable react/no-unescaped-entities */
import React, { useRef, useEffect } from 'react'
import { connect } from 'frontity'
import { Img, Content } from './styles'
import { Parallax, Background } from 'react-parallax'
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/dist/ScrollTrigger'
gsap.registerPlugin(ScrollTrigger)
const ImgParallax = ({ state, imgID, strength, content }) => {
const media = state.source.attachment[imgID]
const contentRef = useRef(null)
const containerImageRef = useRef(null)
useEffect(() => {
ScrollTrigger.matchMedia({
// desktop
'(min-width: 800px)': function () {
const tl = gsap.timeline({
scrollTrigger: {
trigger: contentRef.current,
start: 'top 60%',
end: 'bottom 30%'
}
})
tl.to(contentRef.current, {
opacity: 1,
y: 0,
duration: 0.5
})
},
// mobile
'(max-width: 799px)': function () {
const tl = gsap.timeline({
scrollTrigger: {
trigger: contentRef.current,
start: 'top 100%',
end: 'bottom 30%'
}
})
tl.to(contentRef.current, {
opacity: 1,
y: 0,
duration: 0.5
})
},
// all
all: function () {}
})
}, [])
return (
<>
<Parallax
id="parallaxImage"
strength={strength}
style={{ height: '100vh', zIndex: 7 }}
ref={containerImageRef}
>
<Background>
<Img src={media.source_url} alt='' />
<Content ref={contentRef} dangerouslySetInnerHTML={{ __html: content }}/>
</Background>
</Parallax>
</>
)
}
export default connect(ImgParallax)
|
import streamlit as st
import pandas as pd
import numpy as np
import pickle
import re
st.set_page_config(layout="wide")
# Load the model, encoder, and scaler
with open('model_reg.pkl', 'rb') as f:
model_reg = pickle.load(f)
with open('encoder_reg.pkl', 'rb') as f:
encoder = pickle.load(f)
with open('scaler_reg.pkl', 'rb') as f:
scaler = pickle.load(f)
with open('model_clf.pkl', 'rb') as f:
model_clf = pickle.load(f)
with open('encoder_clf.pkl', 'rb') as f:
encoder_clf = pickle.load(f)
# Load sample data for dropdown options
sample_data = pd.read_excel('Copper_Set.xlsx')
# Streamlit app
st.title('Industrial Copper Modeling Application')
# st.write("""
# <div style='text-align:center'>
# <h1 style='color:#009999;'>Industrial Copper Modeling Application</h1>
# </div>
# """, unsafe_allow_html=True)
tab1, tab2 = st.tabs(["PREDICT SELLING PRICE", "PREDICT STATUS"])
with tab1:
# Input form
with st.form('prediction_form'):
col1,col2,col3=st.columns([5,2,5])
with col1:
st.write("Please enter the following details:")
status = st.selectbox('Status', sample_data['status'].unique(),key=1)
item_type = st.selectbox('Item type', sample_data['item type'].unique(),key=2)
country = st.selectbox('Country', sample_data['country'].unique(),key=3)
application = st.selectbox('Application', sample_data['application'].unique(),key=4)
product_ref = st.selectbox('Product Reference', sample_data['product_ref'].unique(),key=5)
with col3:
quantity_tons = st.number_input('Quantity Tons', min_value=0.1, value=0.1)
thickness = st.number_input('Thickness', min_value=0.18, value=0.18)
width = st.number_input('Width', min_value=0.0, value=0.0)
customer = st.number_input('Customer ID', min_value=0, value=0)
delivery_duration=st.number_input("enter delivery duration.if no enter 0")
#material_ref=st.text_input('material reference if have')
submit_button = st.form_submit_button(label='Predict Selling Price')
flag=0
pattern="^(?:\d+|\d*\.\d+)$"
for i in [quantity_tons,thickness,customer,width]:
if re.match(pattern, str(i)):
pass
else:
flag=1
break
# Predict selling price
if submit_button and flag==1:
if len(i)==0:
st.write("Please enter a valid number.No spaces are allowed")
else:
st.write("You have entered an invalid value:",i)
if submit_button and flag == 0:
input_data = pd.DataFrame({
'customer': [int(customer)],
'country': [float(country)],
'status': [status],
'item_type': [item_type],
'application': [float(application)],
'width': [float(width)],
'product_ref': [int(product_ref)],
'delivery_duration': [int(delivery_duration)],
'thickness_log': [np.log(thickness)],
'quantity_tons_log': [np.log(quantity_tons)]
})
input_encoded = encoder.transform(input_data)
#input_data_encoded = pd.concat([input_data[['customer', 'country']],
#input_encoded,
#input_data[['application', 'width', 'product_ref',
# 'delivery_duration', 'thickness_log', 'quantity_tons_log']]], axis=1)
input_scaled = scaler.transform(input_encoded)
predicted_log_price = model_reg.predict(input_scaled)
predicted_price = np.exp(predicted_log_price)
st.success(f'Predicted Selling Price: {predicted_price[0]:.2f}')
with tab2:
with st.form('predict_status_form'):
col1,col2,col3=st.columns([5,1,5])
with col1:
st.write("Please enter the following details:")
item_type = st.selectbox('Item type', sample_data['item type'].unique(),key=22)
country = st.selectbox('Country', sample_data['country'].unique(),key=23)
application = st.selectbox('Application', sample_data['application'].unique(),key=24)
product_ref = st.selectbox('Product Reference', sample_data['product_ref'].unique(),key=25)
selling_price = st.number_input('selling price.Pleas enter value greater than zero')
with col3:
quantity_tons = st.number_input('Quantity Tons', min_value=0.1, value=0.1)
thickness = st.number_input('Thickness', min_value=0.18, value=0.18)
width = st.number_input('Width', min_value=0.0, value=0.0)
customer = st.number_input('Customer ID', min_value=0, value=0)
delivery_duration=st.number_input("enter delivery duration.if no enter 0")
submit_button = st.form_submit_button(label='Predict Status')
cflag=0
pattern="^(?:\d+|\d*\.\d+)$"
for k in [quantity_tons,thickness,customer,width]:
if re.match(pattern,str(k)):
pass
else:
cflag=1
break
# Predict selling price
if submit_button and cflag==1:
if len(i)==0:
st.write("Please enter a valid number.No spaces are allowed")
else:
st.write("You have entered an invalid value:",k)
if submit_button and flag == 0:
input_data1 = pd.DataFrame({
'customer': [int(customer)],
'country': [float(country)],
'item_type': [item_type],
'application': [float(application)],
'width': [float(width)],
'product_ref': [int(product_ref)],
'delivery_duration': [int(delivery_duration)],
'thickness_log': [np.log(thickness)],
'quantity_tons_log': [np.log(quantity_tons)],
'selling_price_log': [np.log(selling_price)]
})
# Replace this with the correct column name
input_encoded1 = encoder_clf.transform(input_data1)
#input_data_encoded1 = pd.concat([input_data1[uantity_tons_log','selling_price_log']]], axis=1)
#input_scaled = scaler.transform(input_data_encoded)
predicted_status = model_clf.predict(input_encoded1)
if predicted_status==1:
st.write('## :green[The status is WON]')
else:
st.write("## :red[The status is LOST]")
#st.write("App created by Your Name")
|
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>S80</title>
<script src="chart.min.js"></script>
<link rel="stylesheet" href="normalize.css">
<style type="text/css">
body
{
background-color: rgb(0, 0, 0);
color: #919191;
font-family: arial, helvetica, verdana, tahoma, sans-serif;
width:100vw;
}
h1 {
font-size: 12vw;
margin-top: 0rem;
margin-bottom: 0rem;
}
#results
{
width:90%;
letter-spacing:-.1em;
}
.grid-container {
display: grid;
grid-template-areas:
'header right right right'
'main main main main'
'main main main main'
'footer footer footer footer';
gap: .7rem;
background-color: #919191;
padding: 2.5vw;
}
.s80header {
grid-area: header;
}
.s80intro { grid-area: right; }
.s80chart {
grid-area: main;
padding:0;
position: relative;
margin: 0;
width:95vw;
}
.s80footer { grid-area: footer; }
.grid-container > div {
background-color: rgb(0, 0, 0);
text-align: center;
padding: 0;
font-size: 1rem;
}
</style>
</head>
<body>
<div class="grid-container">
<div class="s80header"><h1>S80</h1></div>
<div class="s80intro">This tool makes small HTTP requests from your browser similar to ICMP pings to measure connection latency.</div>
<div class="s80chart"><canvas id="mychart"></canvas></div>
<div class="s80footer">This software is released under the <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons BY-NC-SA</a> license.</div>
</div>
<div id="buttons"><button onmouseup="continuousstatic()">Start Test</button></div>
<div id="rtping"></div>
<div id="results"></div>
<ul id=""></ul>
<div id="afterresults1"></div>
<div id="afterresults2"></div>
<script type="text/javascript">
var counter1 = 0;
var animationRunning = false;
var total1 = 0;
var starttime = 0;
var string1 = "";
var minResponseTime = 50000;
var maxResponseTime = 0;
var results1;
var textX = 0;
var textY = 10;
var paused = false;
var resultList = [];
let resultListColors = [];
var s80worker = new Worker('s80worker.js');
s80worker.onmessage = aftercontinuousstatic;
var colormap = new Array (1501);
for(x=1;x<1500;x++)
{
colormap[x] = numberToColorHsl(Math.round((100-((Math.log(x)/6)*100)))+30);
}
let myChart = new Chart(document.getElementById("mychart"), {
type: 'scatter',
data: {
datasets: [{
label: 'response time ms',
data: resultList,
backgroundColor: resultListColors
// borderWidth: 0
}]
},
options: {
parsing: false,
animation:{
easing: 'easeOutElastic',
duration: 2000,
onComplete: function(animation) {
animationRunning = false;
}
},
responsive: true,
resizeDelay: 100,
elements: {
point: {
radius: 2,
borderwidth: 0
}
},
scales: {
x: {
type: 'linear',
min: 0,
//max: 7000,
grid: {
display: false
},
ticks:{
source: 'auto',
maxRotation: 0,
autoSkip: true
},
position: 'bottom'
},
y: {
grid:{
color: 'rgb(100,100,100)'
},
type:'logarithmic'
}
}
}
});
function colorof(num)
{
if(num>1499)
return colormap[1499];
return colormap[num];
}
/**
* http://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion
*/
function hslToRgb(h, s, l){
var r, g, b;
if(s == 0){
r = g = b = l; // achromatic
}else{
function hue2rgb(p, q, t){
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return [Math.floor(r * 255), Math.floor(g * 255), Math.floor(b * 255)];
}
// convert a number to a color using hsl
function numberToColorHsl(i) {
// as the function expects a value between 0 and 1, and red = 0� and green = 120�
// we convert the input to the appropriate hue value
var hue = i * (1.2 / 360);
// we convert hsl to rgb (saturation 100%, lightness 50%)
var rgb = hslToRgb(hue, 1, .5);
// we format to css value and return
return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
}
/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08 **
** Code licensed under Creative Commons Attribution-ShareAlike License **
** http://creativecommons.org/licenses/by-sa/2.0/ **/
function pausetest(){
buttondiv = document.getElementById("buttons");
buttondiv.innerHTML = '<button onmouseup="continuousstatic()">Start Test</button>';
paused = true;
}
function continuousstatic(){
paused = false;
buttondiv = document.getElementById("buttons");
buttondiv.innerHTML = '<button onmouseup="pausetest()">Pause</button>';
s80worker.postMessage(null);
setInterval(keepChartUpdated,100);
}
function keepChartUpdated(){
if(!paused && !animationRunning){
// animationRunning = true;
myChart.update();
}
}
function afterDataPointProcessing(){
s80worker.postMessage(null);
}
function aftercontinuousstatic(workerResponse){ // to rename to processDatapoint
let timesample = workerResponse.data;
var afterresults1 = document.getElementById("afterresults1");
var afterresults2 = document.getElementById("afterresults2");
var realtime1 = document.getElementById("rtping");
if(timesample < minResponseTime)
{
minResponseTime = timesample;
afterresults1.innerHTML = "<span style='color:" + colorof(minResponseTime) +"'>min:"+minResponseTime+"ms</span> <br><span style='color:" + colorof(maxResponseTime) +"'>"+"max:"+maxResponseTime+"ms</span>";
}
if(timesample > maxResponseTime)
{
maxResponseTime = timesample;
afterresults1.innerHTML = "<span style='color:" + colorof(minResponseTime) +"'>min:"+minResponseTime+"ms</span> <br><span style='color:" + colorof(maxResponseTime) +"'>"+"max:"+maxResponseTime+"ms</span>";
}
if(counter1 >= 1000 || paused == true)
{
return 1;
}
resultList.push({x:counter1, y:timesample,color:colorof(timesample)});
resultListColors[counter1] = colorof(timesample);
counter1 += 1;
total1 += timesample;
avgpingtime = Math.round(total1/counter1);
/* var temp = oXML.responseText;
temp += "";
if(temp == "1")
{
ctx.fillStyle = colorof(timesample);
ctx.fillText("!",textX,textY);
textX += 2;
if(textX > 596)
{
textY += 8;
textX = 0;
}
realtime1.innerHTML = "<span style='color:" + colorof(timesample) +"'>"+ timesample + "ms</span>";
afterresults2.innerHTML = "<span style='color:" + colorof(avgpingtime) +"'>avg: "+ avgpingtime + "ms</span>";
}
else
{
string1 += ". ";
realtime1.innerHTML = "timeout";
}
*/
afterDataPointProcessing();
}
continuousstatic();
</script>
</body></html>
|
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use App\Models\User;
use Faker\Core\Blood;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
// Call the manual seeder
// $this->call(CountriesSeeder::class);
$this->call(BloodGroupSeeder::class);
$this->call([
RoleSeeder::class,
]);
$admin = User::firstOrCreate(["email" => 'admin@email.com',], [
"first_name" => 'Admin',
// "last_name" => 'Doy',
"email" => 'admin@email.com',
"password" => Hash::make('admin'),
'is_active' => 1,
]);
$admin->assignRole('Admin'); #assigning role
$patient = User::firstOrCreate(
["email" => 'patient@email.com',],
[
"first_name" => 'Jhon',
"last_name" => 'Doy',
"religion" => 'Muslim',
'gender' => 'male',
"date_of_birth" => Carbon::createFromDate(1990, 5, 15),
"email" => 'patient@email.com',
'blood_group_id' => 5,
"password" => Hash::make('patient'),
'is_active' => 1,
],
);
$patient->assignRole('Patient'); #assigning role
$counselor = User::firstOrCreate(
["email" => 'counselor@email.com',],
[
// "first_name"=>'Counselor',
"email" => 'counselor@email.com',
"password" => Hash::make('counselor'),
'is_active' => 1,
],
);
$counselor->assignRole('Counselor'); #assigning role
$doctor = User::firstOrCreate(
["email" => 'doctor@email.com',],
[
// "first_name"=>'Doctor',
"email" => 'doctor@email.com',
"password" => Hash::make('doctor'),
'is_active' => 1,
],
);
$doctor->assignRole('Doctor'); #assigning role
// \App\Models\User::factory(10)->create();
// \App\Models\User::factory()->create([
// 'name' => 'Test User',
// 'email' => 'test@example.com',
// ]);
}
}
|
**The current status of this chapter is draft. I will finish it later when I have time**
Introduction
------------
In this chapter, we delve into the regulatory and ethical considerations associated with the application of artificial intelligence (AI) in supply chain management. As AI technologies play an increasingly significant role in optimizing logistics and inventory control, it is crucial to address the legal, regulatory, and ethical implications that arise from their implementation. We explore key areas of concern and discuss strategies for ensuring responsible and ethical use of AI in the supply chain.
Regulatory Frameworks
---------------------
### Compliance with Data Privacy Regulations
* Organizations must adhere to data privacy regulations, such as the General Data Protection Regulation (GDPR) in the European Union and similar laws in other jurisdictions.
* Implementing appropriate data protection measures, obtaining user consent, and ensuring secure storage and handling of personal and sensitive information are essential.
### Intellectual Property Rights and Licensing
* Organizations implementing AI systems need to ensure compliance with intellectual property laws, including patents, copyrights, and trade secrets.
* Adequate licensing agreements and permissions should be obtained when leveraging third-party AI algorithms, models, or datasets.
### Product Safety and Liability
* AI-enabled technologies used in supply chain management should meet applicable safety standards to mitigate risks to workers, consumers, and the environment.
* Organizations must be prepared to address liability concerns arising from AI-related failures, errors, or accidents.
Ethical Considerations
----------------------
### Fairness and Bias Mitigation
* AI algorithms used in supply chain management should be designed to avoid biases based on gender, race, ethnicity, or any protected characteristic.
* Ensuring fairness in decision-making processes, such as hiring, promotion, or resource allocation, is crucial to prevent discriminatory outcomes.
### Transparent and Explainable AI
* Organizations should strive to develop transparent AI systems that can provide explanations and justifications for their decisions.
* The ability to understand how AI algorithms arrive at specific recommendations or predictions helps build trust and facilitates accountability.
### Human-AI Collaboration
* Organizations need to define clear roles and responsibilities for humans and AI systems in the supply chain.
* Striking the right balance between human expertise and AI capabilities ensures effective collaboration, leverages human judgment, and avoids undue reliance on AI systems.
### Ethical Sourcing and Sustainability
* AI can be used to optimize supply chain operations, but organizations must prioritize ethical sourcing practices, environmental sustainability, and social responsibility.
* Ensuring that AI-driven decisions align with ethical principles and contribute to sustainable practices is essential.
Industry Standards and Guidelines
---------------------------------
### Adoption of Best Practices
* Organizations should stay informed about industry standards, guidelines, and best practices related to AI in supply chain management.
* Collaborating with industry associations, research institutions, and regulatory bodies can help shape responsible AI adoption across the supply chain.
### Independent Audits and Assessments
* Conducting regular audits and assessments of AI systems can identify issues, ensure compliance, and uncover opportunities for improvement.
* Third-party audits or certifications can provide added assurance and credibility in ethical AI implementation.
Conclusion
----------
The integration of AI technologies into supply chain management offers significant benefits in optimizing logistics and inventory control. However, it is crucial to navigate the regulatory landscape and address ethical considerations associated with AI implementation. Compliance with data privacy regulations, intellectual property rights, and product safety standards are essential. Emphasizing fairness, transparency, human-AI collaboration, and ethical sourcing practices fosters responsible and sustainable AI adoption. Keeping abreast of industry standards and conducting independent audits further ensures the responsible use of AI in the supply chain. By proactively addressing regulatory and ethical considerations, organizations can harness the full potential of AI while maintaining trust, accountability, and societal well-being.
|
import React, {useState } from "react";
import { connect } from "react-redux";
import { commentPost } from "../reduxParts/actions";
import "../stylesheets/CommentItem.css";
export const CommentItem = function (props: any){
// Allow for the ability to track keyboard input state.
const [inputValue, setInputValue] = useState ('');
return (
<div className="wrapper">
{ /* Input HTML Element for comment. */ }
<input style={ {width: "200px", height: "50px"} } className="form__input" type="text" id="name"
// preset value of input is ""
value={inputValue}
// As the user types set the input value to what is being
// capttured by the keyboard.
onChange={e => setInputValue(e.target.value)}
required
/>
{
// When the submit button is pressed
// call the "comment" mapping function below
// and pass the post id, and input value as parameters.
}
<button onClick ={ ()=> {
props.comment(props.id, inputValue); // mapDispatchToProps.comment ();
setInputValue(''); // User's comment string
}}>Submit Comment </button>
</div>
);
}
// This method allows us to pass information to the redux actions as parameters.
// For example, props.comment (1, "helloWorld") passes the post id 1, and the comment
// string "helloWorld" to the commentPost() method which handles updating the state of the
// CommentItem component and saving it, so that it actually persists.
function mapDispatchToProps (dispatch: any){
return {
comment: (post_id: number, comment: string) => dispatch (commentPost (post_id, comment))
}
}
// Connects CommentItem component to store
export default connect (null, mapDispatchToProps) (CommentItem);
|
package IFaceOnlineClass;
public class Circle extends Shape implements Comparable <Circle> {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double dia(){
return radius * 2;
}
public double circ(){
return Math.PI * dia();
}
public double area(){
return Math.PI * radius * radius;
}
public String toString(){
return String.format("\n\tCircle with radius %5.2f, dia %5.2f, cir %5.2f, area %5.2f",
radius, dia(), circ(), area());
}
@Override
public int compareTo(Circle o) {
if (getRadius() > o.getRadius())
return 1;
else if (getRadius() < o.getRadius())
return -1;
else
return 0;
}
public static Comparable findMax(Comparable cir1, Comparable cir2) {
if (cir1.compareTo(cir2) > 0)
return cir1;
else
return cir2;
}
}
|
import { NgTemplateOutlet } from '@angular/common';
import {
AfterViewInit,
Component,
Inject,
OnInit,
ViewChild,
inject,
} from '@angular/core';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { AccountsLayout } from '@accounts/interface-adapters/layouts/accounts/accounts.layout';
import { MatIcon } from '@angular/material/icon';
import { InputComponent } from '@common/interface-adapters/components/input/input.component';
import { ButtonOutlineIconComponent } from '@common/interface-adapters/components/button-outline-icon/button-outline-icon.component';
import { CheckboxComponent } from '@common/interface-adapters/components/checkbox/checkbox.component';
import { ErrorComponent } from '@common/interface-adapters/components/error/error.component';
import { IsFeatureEnabledUseCase } from '@common/application-business-rules/use-cases/is-feature-enabled/is-feature-enabled.use-case';
import { ButtonFlatComponent } from '@common/interface-adapters/components/button-flat/button-flat.component';
import { ButtonBasicComponent } from '@common/interface-adapters/components/button-basic/button-basic.component';
import { SignInWithEmailAndPasswordUseCase } from '@common/application-business-rules/use-cases/sign-in-with-email-and-password/sign-in-with-email-and-password.use-case';
import { SignInWithEmailAndPasswordMock } from '@common/interface-adapters/data-sources/sign-in-with-email-and-password-mock/sign-in-with-email-and-password.mock';
import { Observable, first, lastValueFrom, map } from 'rxjs';
import { EMAIl_TOKEN } from './tokens/email.token';
import { EMAIL_PARAMETER_CONSTANT } from './constants/email-parameter.constant';
import { SignInWithEmailAndPasswordDataSource } from '@common/application-business-rules/data-sources/sign-in/sign-in.data-source';
/**
* @todo show error if email is empty
*/
@Component({
selector: 'acc-challenge-pwd',
standalone: true,
imports: [
AccountsLayout,
ButtonBasicComponent,
ButtonFlatComponent,
ButtonOutlineIconComponent,
CheckboxComponent,
ErrorComponent,
InputComponent,
MatIcon,
NgTemplateOutlet,
RouterLink,
],
providers: [
{
provide: EMAIl_TOKEN,
useFactory: () => {
const route = inject(ActivatedRoute);
const email$ = route.queryParamMap.pipe(
first(),
map((queryParamMap) => {
const email = queryParamMap.get(EMAIL_PARAMETER_CONSTANT);
if (!email) {
return '';
}
return email;
}),
);
return email$;
},
},
SignInWithEmailAndPasswordUseCase,
{
provide: SignInWithEmailAndPasswordDataSource,
useClass: SignInWithEmailAndPasswordMock,
},
],
templateUrl: './challenge-pwd.page.html',
styleUrl: './challenge-pwd.page.scss',
})
export class ChallengePwdPage implements OnInit, AfterViewInit {
email: string = '';
errorMessage: string = '';
isLoading: boolean = false;
isOnNextEnabled: boolean = false;
isOnTryAnotherWayEnabled: boolean = false;
password: string = '';
showPassword: boolean = false;
@ViewChild('inputPassword') inputPassword!: InputComponent;
constructor(
@Inject(EMAIl_TOKEN) private email$: Observable<string>,
private isFeatureEnabled: IsFeatureEnabledUseCase,
private router: Router,
private signIn: SignInWithEmailAndPasswordUseCase,
) {}
ngOnInit(): void {
this.email$.pipe(first()).subscribe((email) => {
this.email = email;
if (!email) {
this.router.navigate(['/v3/signin/identifier'], {
queryParamsHandling: 'preserve',
replaceUrl: true,
});
return;
}
});
this.isFeatureEnabled
.execute('/v3/signin/challenge/pwd#onTryAnotherWay')
.then((response) => {
if (!response.ok) {
this.isOnTryAnotherWayEnabled = false;
return;
}
this.isOnTryAnotherWayEnabled = response.data.isEnabled;
});
this.isFeatureEnabled
.execute('/v3/signin/challenge/pwd#onNext')
.then((response) => {
if (!response.ok) {
this.isOnNextEnabled = false;
return;
}
this.isOnNextEnabled = response.data.isEnabled;
});
}
ngAfterViewInit(): void {
this.inputPassword.nativeElement.focus();
}
async onEmail() {
this.router.navigate(['/v3/signin/identifier'], {
queryParams: { email: undefined },
queryParamsHandling: 'merge',
});
}
async onNext() {
this.errorMessage = '';
if (!this.password) {
this.errorMessage = 'Enter a password';
this.password = '';
this.inputPassword.nativeElement.focus();
return;
}
this.isLoading = true;
const response = await lastValueFrom(
this.signIn.execute(this.email, this.password),
);
this.isLoading = false;
if (!response.ok) {
switch (response.errorCode) {
case 'email-not-found':
console.warn(
`${ChallengePwdPage.name} was not expected to be activated without email`,
);
this.errorMessage = 'Unexpected error';
this.password = '';
break;
case 'wrong-password':
this.errorMessage = 'Wrong Password. Try again';
this.password = '';
break;
default:
console.warn(
`${ChallengePwdPage.name} error code: ${response.errorCode}`,
);
this.errorMessage = 'Unexpected error';
this.password = '';
break;
}
this.inputPassword.nativeElement.focus();
return;
}
}
}
|
<?php
declare(strict_types=1);
namespace Rapkis\Controld\Resources;
use Illuminate\Http\Client\PendingRequest;
use Rapkis\Controld\Enums\DeviceStatus;
use Rapkis\Controld\Factories\DeviceFactory;
use Rapkis\Controld\Factories\DeviceTypeFactory;
use Rapkis\Controld\Responses\Device;
use Rapkis\Controld\Responses\DeviceTypes;
class Devices
{
public function __construct(
private readonly PendingRequest $client,
private readonly DeviceFactory $device,
private readonly DeviceTypeFactory $deviceType,
) {
}
public function list(): \Rapkis\Controld\Responses\Devices
{
$response = $this->client->get('devices')->json('body.devices');
$result = new \Rapkis\Controld\Responses\Devices();
foreach ($response as $device) {
$device = $this->device->make($device);
$result->put($device->pk, $device);
}
return $result;
}
public function create(
string $name,
string $profilePk,
string $icon,
string $profilePk2 = null,
int $stats = null,
bool $legacyIpv4Status = false,
bool $learnIp = false,
bool $restricted = false,
bool $bumpTls = false,
string $description = null,
int $ddnsStatus = null,
string $ddnsSubdomain = null,
int $ddnsExternalStatus = null,
string $ddnsExternalHost = null,
): Device {
$response = $this->client->post('devices', [
'name' => $name,
'profile_id' => $profilePk,
'profile_id2' => $profilePk2,
'icon' => $icon,
'stats' => $stats,
'legacy_ipv4_status' => (int) $legacyIpv4Status,
'learn_ip' => (int) $learnIp,
'restricted' => (int) $restricted,
'bump_tls' => (int) $bumpTls,
'desc' => $description,
'ddns_status' => $ddnsStatus,
'ddns_subdomain' => $ddnsSubdomain,
'ddns_ext_status' => $ddnsExternalStatus,
'ddns_ext_host' => $ddnsExternalHost,
])->json('body');
return $this->device->make($response);
}
public function types(): DeviceTypes
{
$response = $this->client->get('devices/types')->json('body.types');
$result = new DeviceTypes();
foreach ($response as $type => $deviceType) {
$deviceType['type'] = $type;
$deviceType = $this->deviceType->make($deviceType);
$result->put($deviceType->type, $deviceType);
}
return $result;
}
public function analyticsLevels(): array
{
return $this->client->get('devices/stat_levels')->json('body.stat_levels');
}
public function modify(
string $devicePk,
string $name = null,
string $profilePk = null,
string $icon = null,
string $profilePk2 = null,
int $stats = null,
bool $legacyIpv4Status = null,
bool $learnIp = null,
bool $restricted = null,
bool $bumpTls = null,
string $description = null,
int $ddnsStatus = null,
string $ddnsSubdomain = null,
int $ddnsExternalStatus = null,
string $ddnsExternalHost = null,
DeviceStatus $status = null,
string $ctrldCustomConfig = null,
): Device {
$response = $this->client->put("devices/{$devicePk}", [
'name' => $name,
'profile_id' => $profilePk,
'profile_id2' => $profilePk2,
'icon' => $icon,
'stats' => $stats,
'legacy_ipv4_status' => ! is_null($legacyIpv4Status) ? (int) $legacyIpv4Status : $legacyIpv4Status,
'learn_ip' => ! is_null($learnIp) ? (int) $learnIp : $learnIp,
'restricted' => ! is_null($restricted) ? (int) $restricted : $restricted,
'bump_tls' => ! is_null($bumpTls) ? (int) $bumpTls : $bumpTls,
'desc' => $description,
'ddns_status' => $ddnsStatus,
'ddns_subdomain' => $ddnsSubdomain,
'ddns_ext_status' => $ddnsExternalStatus,
'ddns_ext_host' => $ddnsExternalHost,
'status' => $status?->value,
'ctrld_custom_config' => $ctrldCustomConfig,
])->json('body');
return $this->device->make($response);
}
public function delete(string $devicePk): bool
{
$this->client->delete("devices/{$devicePk}");
return true;
}
}
|
<template>
<!-- <form @submit="onSubmit"> -->
<demo-block title="基本用法" padding>
<wan-radio-group
v-model="state.radio1"
@change="onChange('radio1', $event)"
>
<wan-radio name="1" custom-class="demo-radio">单选框 1</wan-radio>
<wan-radio name="2">单选框 2</wan-radio>
</wan-radio-group>
</demo-block>
<demo-block title="水平排列" padding>
<wan-radio-group
v-model="state.radio1"
direction="horizontal"
@change="onChange('radio1', $event)"
>
<wan-radio name="1">单选框 1</wan-radio>
<wan-radio name="2">单选框 2</wan-radio>
</wan-radio-group>
</demo-block>
<demo-block title="禁用状态" padding>
<wan-radio-group
v-model="state.radio2"
disabled
@change="onChange('radio2', $event)"
>
<wan-radio name="1" custom-class="demo-radio">单选框 1</wan-radio>
<wan-radio name="2">单选框 2</wan-radio>
</wan-radio-group>
</demo-block>
<demo-block title="自定义形状" padding>
<wan-radio-group
v-model="state.radioShape"
@change="onChange('radioShape', $event)"
>
<wan-radio name="1" shape="square" custom-class="demo-radio"
>单选框</wan-radio
>
<wan-radio name="2" shape="square">单选框</wan-radio>
</wan-radio-group>
</demo-block>
<demo-block title="自定义颜色" padding>
<wan-radio-group
v-model="state.radio3"
@change="onChange('radio3', $event)"
>
<wan-radio name="1" custom-class="demo-radio" checked-color="#07c160"
>单选框</wan-radio
>
<wan-radio name="2" checked-color="#07c160">单选框</wan-radio>
</wan-radio-group>
</demo-block>
<demo-block title="自定义大小" padding>
<wan-radio-group
v-model="state.radioSize"
@change="onChange('radioSize', $event)"
>
<wan-radio name="1" icon-size="24px" custom-class="demo-radio"
>单选框</wan-radio
>
<wan-radio name="2" icon-size="24px">单选框</wan-radio>
</wan-radio-group>
</demo-block>
<demo-block title="自定义图标" padding>
<wan-radio-group
v-model="state.radio4"
@change="onChange('radio4', $event)"
>
<wan-radio use-icon-slot name="1">
自定义图标
<template #icon>
<image
:src="state.radio4 === '1' ? state.icon.active : state.icon.normal"
class="icon"
mode="widthFix"
></image>
</template>
</wan-radio>
<wan-radio use-icon-slot name="2">
自定义图标
<template #icon>
<image
:src="state.radio4 === '2' ? state.icon.active : state.icon.normal"
class="icon"
mode="widthFix"
></image>
</template>
</wan-radio>
</wan-radio-group>
</demo-block>
<demo-block title="禁用文本点击" padding>
<wan-radio-group
v-model="state.radioLabel"
@change="onChange('radioLabel', $event)"
>
<wan-radio label-disabled name="1" custom-class="demo-radio"
>单选框 1</wan-radio
>
<wan-radio label-disabled name="2">单选框 2</wan-radio>
</wan-radio-group>
</demo-block>
<demo-block title="与 Cell 组件一起使用">
<wan-radio-group v-model="state.radio5">
<wan-cell-group>
<wan-cell title="单选框 1" clickable @click="onClick('1')">
<template #right-icon>
<wan-radio name="1"></wan-radio>
</template>
</wan-cell>
<wan-cell title="单选框 2" clickable @click="onClick('2')">
<template #right-icon>
<wan-radio name="2"></wan-radio>
</template>
</wan-cell>
</wan-cell-group>
</wan-radio-group>
</demo-block>
<!-- <button form-type="submit">提交</button>
</form> -->
</template>
<script setup lang="ts">
import { reactive } from 'vue';
const state = reactive({
radio1: '1',
radio2: '2',
radio3: '1',
radio4: '1',
radio5: '1',
radioSize: '1',
radioLabel: '1',
radioShape: '1',
icon: {
normal:
'https://img.yzcdn.cn/public_files/2017/10/13/c547715be149dd3faa817e4a948b40c4.png',
active:
'https://img.yzcdn.cn/public_files/2017/10/13/793c77793db8641c4c325b7f25bf130d.png'
}
});
function onChange(key, event) {
state[key] = event;
}
function onClick(name) {
state.radio5 = name;
}
function onSubmit(event) {
console.log(event);
}
</script>
<style>
.demo-radio {
margin-bottom: 10px;
}
.icon {
width: 20px;
}
</style>
|
import { calcTotalCount } from './../../utils/calcTotalCount';
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { calcTotalPrice } from '../../utils/calcTotalPrice';
import { getCartFromLS } from '../../utils/getCartFromLS';
import { RootState } from '../store';
export type CartItemsType = {
id: string;
name: string;
price: number;
imageUrl: string;
count: number;
color: string
}
interface cartSliceState {
totalPrice: number;
totalCount: number;
cartItems: CartItemsType[];
}
const {cartItems, totalPrice, totalCount} = getCartFromLS()
const initialState: cartSliceState = {
cartItems,
totalPrice,
totalCount,
}
export const cartSlice = createSlice({
name: 'cart',
initialState,
reducers: {
setAddItem: (state, action: PayloadAction<CartItemsType>) => {
const findItem = state.cartItems.find((obj) => obj.id === action.payload.id);
if (findItem) {
findItem.count++;
} else {
state.cartItems.push({
...action.payload,
count: 1,
});
}
state.totalPrice = calcTotalPrice(state.cartItems)
state.totalCount = calcTotalCount(state.cartItems)
},
setMinusItem: (state, action: PayloadAction<string>) => {
const findItem = state.cartItems.find((obj) => obj.id === action.payload);
if (findItem) {
findItem.count--;
}
state.totalPrice = calcTotalPrice(state.cartItems)
state.totalCount = calcTotalCount(state.cartItems)
},
setRemoveItem: (state, action: PayloadAction<string>) => {
state.cartItems = state.cartItems.filter((obj) => obj.id !== action.payload);
state.totalPrice = calcTotalPrice(state.cartItems)
state.totalCount = calcTotalCount(state.cartItems)
},
setClearItem: (state) => {
state.cartItems = [];
state.totalPrice = 0;
state.totalCount = 0;
},
},
});
export const selectCart = (state: RootState) => state.cart;
export const { setAddItem, setRemoveItem, setClearItem, setMinusItem } =
cartSlice.actions;
export default cartSlice.reducer;
|
const { verifyToken, verifyTokenAndAuthorization, verifyTokenAndAdmin } = require('./verifyToken');
const UserDetails = require('../models/UserDetails')
const router = require('express').Router();
//UPDATE USER
router.put("/:id", verifyTokenAndAuthorization, async (req,res) => {
if(req.body.password){
req.body.password = CryptoJS.AES.encrypt(
req.body.password,
process.env.PASS_SEC
).toString();
}
try{
const updatedUser = await UserDetails.findByIdAndUpdate(req.params.id, {
$set: req.body
},{new: true});
res.status(200).json(updatedUser);
} catch(err){
res.status(500).json(err)
}
})
//DELETE
router.delete("/:id", verifyTokenAndAuthorization, async (req,res) => {
try {
await UserDetails.findByIdAndDelete(req.params.id);
res.status(200).json("User has been deleted...");
} catch(error){ res.status(500).json(error)}
});
//GET USER BY ID
router.get("/find/:id", verifyTokenAndAdmin, async (req,res) => {
try {
const user = await UserDetails.findById(req.params.id);
const { password, ...others } = user._doc;
res.status(200).json(others);
} catch(error){ res.status(500).json(error)}
});
//GET ALL USERS
router.get("/", verifyTokenAndAdmin, async (req,res) => {
const query = req.query.new
try {
const users = query ? await UserDetails.find().sort({_id: -1}).limit(5) : await UserDetails.find();
res.status(200).json(users);
} catch(error){ res.status(500).json(error)}
});
//GET USER STATS
router.get("/stats", verifyTokenAndAdmin, async(req,res) => {
const date = new Date();
const lastYear = new Date(date.setFullYear(date.getFullYear() - 1));
try {
const data = await UserDetails.aggregate([
{ $match: {createdAt: { $gte: lastYear }}},
{ $project: { month: { $month: "$createdAt" },},},
{
$group: {
_id: "$month",
total: {$sum: 1}
}
}
]);
res.status(200).json(data);
} catch (error) {
res.status(500).json(error);
}
})
module.exports = router;
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePlanPersonalizadoTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('plan_personalizado', function (Blueprint $table) {
$table->id();
$table->string('nombre');
$table->string('descripcion');
$table->integer('objetivo');
$table->integer('horario');
$table->unsignedBigInteger('grupo_muscular_id');
$table->foreign('grupo_muscular_id')->references('id')->on('grupo_musculars')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('plan_personalizado');
}
}
|
/**
* @file include/kernel/clockevent.h
* @author Armin Luntzer (armin.luntzer@univie.ac.at)
*
* @ingroup time
*
* @copyright GPLv2
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.
*
*/
#ifndef _KERNEL_CLOCKEVENT_H_
#define _KERNEL_CLOCKEVENT_H_
#include <list.h>
#include <kernel/types.h>
#include <kernel/time.h>
/* clock event states */
enum clock_event_state {
CLOCK_EVT_STATE_UNUSED,
CLOCK_EVT_STATE_SHUTDOWN,
CLOCK_EVT_STATE_PERIODIC,
CLOCK_EVT_STATE_ONESHOT
};
/* feature set of a particular clock device */
#define CLOCK_EVT_FEAT_PERIODIC 0x000001
#define CLOCK_EVT_FEAT_ONESHOT 0x000002
#define CLOCK_EVT_FEAT_KTIME 0x000004
/**
* event_handler: callback function executed as the event occurs
*
* set_next_event: set next event function using a clock source delta
* set_next_ktime: set next event function using a direct ktime value
*
* max_delta_ns: maximum programmable delta value in nanoseconds
* min_delta_ns: minimum programmable delta value in nanoseconds
* mult: device ticks to nanoseconds multiplier
* state: timer operating state
* features: timer event features
* set_state: set state function
* rating: quality rating of the device, less is better (more
* resolution, e.g nanosecond-resolution)
* name: clock event name
* irq: IRQ number (-1 if device without IRL)
*/
struct clock_event_device {
void (*event_handler)(struct clock_event_device *);
int (*set_next_event)(unsigned long evt,
struct clock_event_device *);
int (*set_next_ktime)(struct timespec expires,
struct clock_event_device *);
uint32_t max_delta_ns;
uint32_t min_delta_ns;
uint32_t mult;
enum clock_event_state state;
unsigned int features;
void (*set_state)(enum clock_event_state state,
struct clock_event_device *);
void (*suspend)(struct clock_event_device *);
void (*resume)(struct clock_event_device *);
unsigned int rating;
const char *name;
int irq;
struct list_head node;
};
bool clockevents_timout_in_range(struct clock_event_device *dev,
unsigned long nanoseconds);
bool clockevents_feature_periodic(struct clock_event_device *dev);
bool clockevents_feature_oneshot(struct clock_event_device *dev);
void clockevents_set_state(struct clock_event_device *dev,
enum clock_event_state state);
void clockevents_set_handler(struct clock_event_device *dev,
void (*event_handler)(struct clock_event_device *));
void clockevents_register_device(struct clock_event_device *dev);
int clockevents_offer_device(void);
void clockevents_exchange_device(struct clock_event_device *old,
struct clock_event_device *new);
int clockevents_program_event(struct clock_event_device *dev,
struct timespec expires);
int clockevents_program_timeout_ns(struct clock_event_device *dev,
unsigned long nanoseconds);
#endif /* _KERNEL_CLOCKEVENT_H_ */
|
<?php
declare(strict_types=1);
namespace Akeneo\Category\back\tests\Unit\Application\Command\PurgeOrphanCategoryImageFiles;
use Akeneo\Category\Application\Command\PurgeOrphanCategoryImageFiles\PurgeOrphanCategoryImageFilesCommand;
use Akeneo\Category\Application\Command\PurgeOrphanCategoryImageFiles\PurgeOrphanCategoryImageFilesCommandHandler;
use Akeneo\Category\Domain\DTO\IteratorStatus;
use Akeneo\Category\Domain\ImageFile\DeleteCategoryImageFile;
use Akeneo\Category\Domain\ImageFile\GetOrphanCategoryImageFilePaths;
use Akeneo\Category\Domain\ImageFile\Storage;
use Akeneo\Tool\Component\FileStorage\FilesystemProvider;
use League\Flysystem\FilesystemOperator;
use PHPUnit\Framework\TestCase;
/**
* @copyright 2023 Akeneo SAS (https://www.akeneo.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
class PurgeOrphanCategoryImageFilesCommandHandlerTest extends TestCase
{
public function testItPurgesOrphanCategoryImageFiles(): void
{
$fileSystem = $this->createMock(FilesystemOperator::class);
$fileSystemProvider = $this->createMock(FilesystemProvider::class);
$fileSystemProvider
->method('getFilesystem')
->with(Storage::CATEGORY_STORAGE_ALIAS)
->willReturn($fileSystem);
$getOrphanCategoryImageFilePaths = $this->createMock(GetOrphanCategoryImageFilePaths::class);
$getOrphanCategoryImageFilePaths
->method('__invoke')
->willReturn(new \ArrayIterator([
IteratorStatus::inProgress(),
IteratorStatus::inProgress(),
IteratorStatus::done(['a_category/file1.jpg', 'a_category/file2.jpg']),
]));
$deleteCategoryImageFile = $this->createMock(DeleteCategoryImageFile::class);
$deleteCategoryImageFile
->method('__invoke')
->withConsecutive(
['a_category/file1.jpg'],
['a_category/file2.jpg'],
);
$handler = new PurgeOrphanCategoryImageFilesCommandHandler(
$fileSystemProvider,
$getOrphanCategoryImageFilePaths,
$deleteCategoryImageFile,
);
$purgeOrphanCategoryImageFilesCommand = $this->createMock(PurgeOrphanCategoryImageFilesCommand::class);
$results = iterator_to_array($handler($purgeOrphanCategoryImageFilesCommand));
$this->assertCount(5, $results);
$this->assertEquals([
IteratorStatus::inProgress(),
IteratorStatus::inProgress(),
IteratorStatus::inProgress(),
IteratorStatus::inProgress(),
IteratorStatus::done(),
], $results);
}
}
|
package elodiedaumaljava.learnspringframework02.examples.a7;
import java.util.Arrays;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import elodiedaumaljava.learnspringframework02.game.GameRunner;
public class XMLConfigContextLauncherApp {
public static void main(String[] args) {
try (var context = new ClassPathXmlApplicationContext("contextConfiguration.xml")) {
Arrays.stream(context.getBeanDefinitionNames()).forEach(System.out::println);
System.out.println(context.getBean("name"));
System.out.println(context.getBean("age"));
context.getBean(GameRunner.class).run();
} catch (BeansException e) {
e.printStackTrace();
}
;
}
}
|
import { useEffect, useState } from "react";
import axios from "axios";
export default function useFetch(url) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
let response = await axios.get(url)
setData(response.data)
console.log(response);
} catch (error){
console.log(error);
setError(error);
} finally {
setLoading(false);
}
}
fetchData()
}, [url])
return {data,error,loading }
}
|
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.permissions import IsAuthenticated
from django.http import JsonResponse
from rest_framework.authtoken.models import Token
from django.views.decorators.csrf import csrf_exempt
from . import batch
from . import paging
from . import redo_undo
from pprint import pprint
import json
history_params = ['id', 'undo', 'redo', 'page']
def get_user_from_token(request):
token_key = request.META.get('HTTP_AUTHORIZATION').replace("Token ", "")
user = Token.objects.get(key=token_key).user
return user
@api_view(["POST"])
@permission_classes([IsAuthenticated])
@csrf_exempt
def batch_tagger(request):
payload = json.loads(request.body.decode("utf-8"))
user = get_user_from_token(request=request)
data = {}
# Only authorized for user is admin
if not user.is_admin:
context = {"response_code": 401, "message": "Not authorized! " + user.username + " is not an admin.",
"success": "false"}
return JsonResponse(context, safe=False)
if payload:
data = batch.save_history(data=payload, username=user.username)
return JsonResponse({'data': data, 'username': user.username}, safe=False)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
@csrf_exempt
def history(request):
valid = False
user = get_user_from_token(request=request)
# Only authorized for user is admin
if not user.is_admin:
context = {"response_code": 401, "message": "Not authorized! " + user.username + " is not an admin.",
"success": "false"}
return JsonResponse(context, safe=False)
for param in history_params:
if request.GET.get(param):
valid = True
break
lookup_key = request.GET.get(param)
data = {}
if param == 'id':
data = batch.get_item(item_id=lookup_key)
elif param == 'page':
data = paging.get_page(page=lookup_key)
elif param == 'undo':
data = redo_undo.apply_selected_action_to_batch(item_id=lookup_key, action='undo', username=user.username)
elif param == 'redo':
data = redo_undo.apply_selected_action_to_batch(item_id=lookup_key, action='redo', username=user.username)
return JsonResponse({'history': True, 'param': param, 'data': data}, safe=False)
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BsSearch } from 'react-icons/bs';
import {
HeaderSearch,
FormSearch,
ButtonSearch,
LabelSearch,
InputSearch
} from './Searchbar.styled';
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
export class SearchBar extends Component {
state = {
searchQuery: '',
}
handleChange = e => {
this.setState({searchQuery:e.currentTarget.value.toLowerCase()})
}
handleSubmit = e => {
e.preventDefault();
if (this.state.searchQuery.trim() === '') {
toast.warn('Opps...Try again!');
return;
}
this.props.onSubmit(this.state.searchQuery);
this.setState({ searchQuery: '' });
}
render() {
const { searchQuery } = this.state;
const { handleSubmit, handleChange } = this;
return (
<HeaderSearch>
<FormSearch onSubmit={handleSubmit}>
<ButtonSearch type="submit">
<BsSearch/>
<LabelSearch>Search</LabelSearch>
</ButtonSearch>
<InputSearch
className="input"
type="text"
autoComplete="off"
autoFocus
placeholder="Search images and photos"
onChange={handleChange}
value={searchQuery}
/>
</FormSearch>
</HeaderSearch>
)
}
}
SearchBar.propTypes = {
handleSubmit: PropTypes.func,
handleChange: PropTypes.func,
}
|
################################################################################
### Author: Cornet Denis ###
### Date Created: 4 Novembre 2020 ###
### Last modified: 13 May 2024 ###
### Contributors: / ###
### Version: 0.9.1 ###
################################################################################
#
#
## Description:
# This script help the user to build a custom color chart.
# It is using available images on his computer to choose relevant colors
# for the chart. User can customize, the number of color patch present on
# the chart. A dedicated patch is always kept for pure white.
#
#
## Usage:
# The script requires the following packages: tidyverse, imager, crayon and colorscience.
# Run the script in RStudio or a similar R environment by sourcing this file.
# Example: source('./R/CreateCustomColorChart.R')
#
#
## Input:
# Path to some example of yam tuber flesh images : "./data/"
# Ensure to have images of the desired object on your drive from which to pick colors.
#
#
## Output:
# Outputs two csv files and two .png files :
# - ChartColorValues.csv: provide RGB, XYZ and CIE Lab color values for created custom chart
# - ColorDifferences.csv: provide color differences (dE2000) between each patch of the created color chart
# - TargetB5_RGB_Lab.png: Image of the created chart with color value label and patch number
# - TargetB5.png: Image of the created chart to be printed
# Output file path: "./out/CustomColorChart/"
#
#
## License:
# Distributed under the GNU General Public License v3.0. See CPOPTYING file for details.
#
#
## Additional Notes:
# This script logs its progress to the console and will report on incompatible chart size or
# potential issues with color picked from image (e.g. similar color based on dE2000 distance).
## Actual script code starts below
# Checking if library are available and (down)loading them ---------------------
packs <- c("tidyverse","imager", "crayon", "colorscience")
InstIfNec<-function (pack) {
if (!do.call(require,as.list(pack))) {
do.call(install.packages,as.list(pack)) }
do.call(require,as.list(pack)) }
lapply(packs, InstIfNec)
cat("\014")
# Initial ex
cat(green("\n\nDear user, first you'll be asked to choose the desired number of color of your custom chart. Right after you'll have to choose the number of rows and columns to fill the chart. Finally, you'll be prompt to choose images on your computer to collect color from. For each image, you'll have to choose 5 pixels corresponding to the desired color."))
output_dir <- "./out/CustomColorChart/"
if (!dir.exists(output_dir)) { dir.create(output_dir, recursive=T)}
# Define user parameters
NbOfColor<-readline(cat(blue("\nEnter the number of color in the desired chart: ")))
NbOfColor<-as.integer(NbOfColor)
NbOfRow<-readline(cat(blue("\nEnter the number of row in the desired chart: ")))
NbOfRow<-as.integer(NbOfRow)
NbOfCol<-readline(cat(blue("\nEnter the number of column in the desired chart: ")))
NbOfCol<-as.integer(NbOfCol)
if(NbOfRow*NbOfCol!=NbOfColor) stop("\n \nERROR:\nThe number of color do not match the number of cells in the chart. Please restart the script and ensure that:
Column number * Row number = Number of color")
cat(green(paste0("Within the ", NbOfColor, " colors you choosed, 1 will automatically be the white. So you'll only be asked to choose ", NbOfColor-1, " images to determine the remaining colors of your chart.")))
# Picking color from pics
df<-data.frame(ImageNb=NA, FileName=NA, R=NA, G=NA, B=NA, X=NA, Y=NA, Z=NA, L=NA,
a=NA, b=NA, Coul=NA)
for (i in 1:(NbOfColor-1)) {
cat(red(paste0("\nPicking color N°", i, "\n")))
cat(green("\nPlease choose an image on which you'll be asked to pick a specific color\n"))
FileName=file.choose()
image<-load.image(FileName)
image<-resize(image, 600, 400) # TODO: check if size is already <600
cat(green("\nPlease click on 5 pixels corresponding to the desired color\n"))
par(mar=c(0,0,0,0))
plot(image)
xy<-as.data.frame(lapply(locator(5), round, 0))
RGB<-cbind(diag(image[xy$x, xy$y,1,1]), diag(image[xy$x, xy$y,1,2]),
diag(image[xy$x, xy$y,1,3]))
df[i,]<-c(i, FileName, round(mean(RGB[,1])*255,0), round(mean(RGB[,2])*255,0),
round(mean(RGB[,3])*255,0), rep(NA, 7)) # to use with RGB loading
# df[i,]<-c(i, FileName, round(mean(RGB[,3])*255,0), round(mean(RGB[,2])*255,0),
# round(mean(RGB[,1])*255,0), rep(NA, 7)) # to use with BRG loading
}
# Add reference white
White<-c(NbOfColor, "Reference White", 255, 255, 255, rep(NA, 7))
df<-rbind(df, White)
df[, -c(1:2)] <- sapply(df[, -c(1:2)],as.numeric)
# Get color values in other usefull colorspaces
for (i in 1:nrow(df)) {
df[i, 6:8]<-RGB2XYZ(as.numeric(df[i, 3:5])/255)
df[i, 9:11]<-XYZ2Lab(as.numeric(df[i, 6:8]))
df[i, 12]<-rgb(df[i,3:5]/255)
}
df$Row<-rep(1:NbOfRow, NbOfCol)
df$Col<-rep(1:NbOfCol, each=NbOfRow)
df$PatchNb<-1:NbOfColor
df$TextColor<-ifelse((df$L/100) > 0.179, "black", "white")
# Save produced charts
png(height=9.8, width=6.9, res=300, filename="./out/CustomColorChart/TargetB5.png",
units="in", type="cairo",family="Garamond")
g<-ggplot(data=df, aes(Col, Row))+
geom_tile(color="black", linewidth=3, fill=df$Coul)+
theme_void()+
theme(legend.position="none", plot.background=element_rect(fill="black"))
print(g)
dev.off()
png(height=9.8, width=6.9, res=300, filename="./out/CustomColorChart/TargetB5_RGB_Lab.png",
units="in", type="cairo",family="Garamond")
g<-ggplot(df, aes(Col, Row))+
geom_tile(color="black", linewidth=3, fill=df$Coul)+
theme_void()+
geom_text(aes(x=Col, y=Row+0.3, label=PatchNb), color=df$TextColor, size=12)+
geom_text(aes(x=Col, y=Row+0.1, label=paste0("RGB (", R, ",", G, ",", B, ")")),
size=4, color=df$TextColor)+
geom_text(aes(x=Col, y=Row, label=paste0("XYZ (", round(X,2), ",",
round(Y, 2), ",", round(Z, 2), ")")),
size=4, color=df$TextColor)+
geom_text(aes(x=Col, y=Row-0.1, label=paste0("Lab (", round(L,0), ",",
round(a, 0), ",", round(b, 0), ")")),
size=4, color=df$TextColor)+
theme(legend.position="none", plot.background=element_rect(fill= "black"))
print(g)
dev.off()
# Calculation of color differences between selected patches
cb<-combn(df$PatchNb, 2)
dE<-data.frame(PatchNb1=NA, PatchNb2=NA, dE2000=NA)
for (i in 1:ncol(cb)) {
dE[i,]<-c(cb[,i], deltaE2000(t(df[cb[,i][1], c("R", "G", "B")])[,1],
t(df[cb[,i][2], c("R", "G", "B")])[,1]))
}
dE<-dE[order(dE$dE2000),]
if (min(dE$dE2000)<2) {
cat(red("\nWarning: if deltaE2000 value is less than 2, only experienced observer can notice the difference between 2 colors. It is the case for some colors you selected. Please refer to output file ColorDifferences.csv for further detail. You may want to change some of these colors with more contrasted ones."))
} else {
cat(green("\nWell done! You'll find all files (png and csv) in the ./out/CustomColorChart/ folder of this R project."))
}
# Saving data frames
write.csv2(df[,-c(15,16)], "./out/CustomColorChart/ChartColorValues.csv", row.names =F)
write.csv2(dE, "./out/CustomColorChart/ColorDifferences.csv", row.names =F)
|
# Algorithm
The way to convert a binary number to decimal is as follows:
| 1 | | 0 | | 1 | | 0 | | 1 |
| * | + | * | + | * | + | * | + | * |
|(2^4)| |(2^3)| |(2^2)| |(2^1)| |(2^0)|
The linked list starts from the value at the maximum place value. We can either find the total number of nodes in the linked list to calculate the power of two for the first binary digit, or we can reverse the binary list, start the exponent of 2 from 0 and make our way up.
Taking the latter approach, we first reverse the linked list. For the algorithm to reverse a linked list, refer problem #206.
public Node reverseList(Node head){
if ((head==null)||(head.next==null)) return head;
Node newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
Now within our getDecimalValue method, we first check if the value of head is null, we return the decimal equivalent to be zero.
if (head==null) return 0;
Next we call the reverseList method and store the reversed list in the revList variable.
Node revList = reverseList(head);
Next we initialize a temporary pointer ptr to point to the head of revList, a variable decNum to store the decimal value and a counter variable to keep track of the exponent for 2. The counter starts at 0.
Node ptr = revList;
int decNum = 0;
int counter = 0;
Next we use a loop with the condition ptr!=null
while(ptr!=null)
___
To calculate the decimal value, we multiple (2^counter) to the data at current ptr, then add it to the pre-existing value of decNum.
Math.pow returns a double value, so be sure to convert the result to int before adding it to decNum.
decNum = decNum + (int)(ptr.data*Math.pow(2,counter));
Next, we increment counter and the temporary pointer ptr.
counter++;
ptr=ptr.next;
___
Once out of the loop, we have the decimal equivalent stored in decNum. Return decNum.
return decNum;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Scopes</title>
<style type="text/css">
h2{
background-color: lightgreen;
text-align: center;
padding: 5px;
}
div{
background-color: seagreen;
text-align: center;
padding: 5px;
}
</style>
</head>
<body>
<h2>Js Scopes Example </h2>
<div>
<h1 id="display"></h1>
</div>
</body>
<script>
// functions recap
// Scopes introduction
// Block scoping for FOR loop
var output="";
for(var i=1;i<=10;i++)
{
}
output="The i value is:"+i;
console.log(output);
document.getElementById('display').innerHTML=output;
// Block scoping for if block
var name="bhavesh";
if(name == "bhavesh")
{
var dept="MCA"
}
output="The Department is:"+dept;
console.log(output);
document.getElementById('display').innerHTML=output;
// Function Scoping
function allocatedept()
{
var name1="bhavesh";
if(name1 === "bhavesh")
{
var dept="MCA"
}
}
allocatedept();
output="The Department is:"+dept;
console.log(output);
document.getElementById('display').innerHTML=output;
// coding exercises
// 1) output ?(30)
var top = 20;
function something() {
var inner = 30;
console.log(inner);
}
// 2) output ?(30)
var top = 20;
function something() {
var inner = 30;
console.log(inner);
}
something();
// 3) output ?(30)
var top = 20;
var inner = 50;
function something() {
var inner = 30;
console.log(inner);
}
something();
// 4) output ?(50)
var top = 20;
var inner = 50;
function something() {
var inner = 30;
}
something();
console.log(inner);
// 6) output ? (Hello john)
var name = "Naveen";
function greet(name) {
console.log("Hello " + name);
}
greet("John");
// IIFE example
// Immediately Invoked Function Expression
(function()
{
var a=10;
var b=20;
var sum=a+b;
output="The sum is:" +sum;
document.getElementById('display').innerHTML=output;
})();
// Read and Write Operations for variables
// Read and Write Operations for Functions
// Implications of Read and Write Operations
</script>
</html>
|
import React, { useState } from 'react'
import './style.css'
import { Link } from 'react-router-dom'
import { AiOutlineHome } from 'react-icons/ai'
import { BsCameraReels } from 'react-icons/bs'
import { MdOutlineSubscriptions } from 'react-icons/md'
import { AiOutlineHistory, AiOutlineFire, AiOutlineShopping } from 'react-icons/ai'
import { FiSettings } from 'react-icons/fi'
import { CiMusicNote1 } from 'react-icons/ci'
import { BiMoviePlay, BiNews, BiTrophy, BiHelpCircle } from 'react-icons/bi'
import { TbLivePhoto } from 'react-icons/tb'
import { SiYoutubegaming } from 'react-icons/si'
import { MdOutlineFeedback, MdOutlineWatchLater, MdOutlineQueueMusic, MdArrowDropDown } from 'react-icons/md'
export default function Sidebar() {
const [showMore, setShowMore] = useState(false)
return (
<div className='sidebar'>
<Link to='/' className='item'>
<AiOutlineHome className='icon' />
<span>Home</span>
</Link>
<Link to='/shorts' className='item'>
<BsCameraReels className='icon' />
<span>Shorts</span>
</Link>
<Link to='/subscriptions' className='item'>
<MdOutlineSubscriptions className='icon' />
<span>Subscriptions</span>
</Link>
<hr />
<Link to='/history' className='item'>
<AiOutlineHistory className='icon' />
<span>History</span>
</Link>
<Link to='/watchlater' className='item'>
<MdOutlineWatchLater className='icon' />
<span>Watch later</span>
</Link>
<Link to='/settings' className='item'>
<FiSettings className='icon' />
<span>Settings</span>
</Link>
<hr />
<span className='sidebar-menu-item'>Explore</span>
<Link to='/trending' className='item'>
<AiOutlineFire className='icon' />
<span>Trending</span>
</Link>
<Link to='/shopping' className='item'>
<AiOutlineShopping className='icon' />
<span>Shopping</span>
</Link>
<Link to='/music' className='item'>
<CiMusicNote1 className='icon' />
<span>Music</span>
</Link>
<span className='item' onClick={() => setShowMore((prev) => !prev)}>
<MdArrowDropDown className='icon' />
<span>{showMore ? "Show less" : "Show more"}</span>
</span>
{showMore &&
<>
<Link to='/music' className='item'>
<MdOutlineQueueMusic className='icon' />
<span>Hindi Songs</span>
</Link>
<Link to='/music' className='item'>
<MdOutlineQueueMusic className='icon' />
<span>Panjabi Songs</span>
</Link>
<Link to='/music' className='item'>
<MdOutlineQueueMusic className='icon' />
<span>Tamil Songs</span>
</Link>
</>
}
<hr />
<Link to='/movies' className='item'>
<BiMoviePlay className='icon' />
<span>Movies</span>
</Link>
<Link to='/live' className='item'>
<TbLivePhoto className='icon' />
<span>Live</span>
</Link>
<Link to='/gamming' className='item'>
<SiYoutubegaming className='icon' />
<span>Gamming</span>
</Link>
<Link to='/news' className='item'>
<BiNews className='icon' />
<span>News</span>
</Link>
<Link to='/sports' className='item'>
<BiTrophy className='icon' />
<span>Sports</span>
</Link>
<hr />
<Link to='/feedback' className='item'>
<MdOutlineFeedback className='icon' />
<span>Feedback</span>
</Link>
<Link to='/help' className='item'>
<BiHelpCircle className='icon' />
<span>Help</span>
</Link>
</div>
)
}
|
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import {MessageService} from 'primeng/api';
import {TreeNode} from 'primeng/api';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
providers: [MessageService],
})
export class AppComponent {
tree!: TreeNode[];
constructor(
public _http:HttpClient,
private messageService:MessageService,
){
this._http.get('/assets/employees.json').subscribe(
( data:any ) =>
{
const newdata : Array<any> = data.map((item:any)=>{
const {EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL,PHONE_NUMBER,HIRE_DATE,JOB_ID,SALARY,COMMISSION_PCT,MANAGER_ID,DEPARTMENT_ID} = item;
return {
id:EMPLOYEE_ID,
label:FIRST_NAME,
pid:MANAGER_ID,
commisionPCT:COMMISSION_PCT,
firstName:FIRST_NAME,
lastName:LAST_NAME,
email:EMAIL,
phone:PHONE_NUMBER,
dataOfJoining:HIRE_DATE,
jobId:JOB_ID,
salary:SALARY,
deptId:DEPARTMENT_ID,
styleClass: 'p-person',
expanded: true,
data:{
name:HIRE_DATE,
}
}
});
const root = newdata.find((item)=>{
return newdata.findIndex(inner=>inner.id === item.pid) === -1;
});
if(root){
root.children = [];
this.tree = [root];
this.tree[0]['children'] = newdata.filter(item=>item.pid === root.id);
console.log(this.tree);
this.tree[0].children.forEach((element:any)=>{
element['children'] = newdata.filter(item=>item.pid === element.id);
})
}
});
}
onNodeSelect(event: { node: { label: any; }; }) {
this.messageService.add({severity: 'success', summary: 'Node Selected', detail: event.node.label});
}
}
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './core/guards/auth-gaurd';
import { LoginGuard } from './core/guards/login.guard';
const routes: Routes = [
{
path: '',
pathMatch: 'full',
redirectTo: 'home'
},
{
path: 'home',
loadChildren: () => import('./feature_modules/feature.module').then(m => m.FeatureModule),
canActivate: [AuthGuard],
runGuardsAndResolvers: 'paramsOrQueryParamsChange'
},
{
path: 'auth',
loadChildren: () => import('./auth_modules/auth.module').then(m => m.AuthModule),
canActivate: [LoginGuard],
runGuardsAndResolvers: 'paramsOrQueryParamsChange',
},
{ path: '**', redirectTo: '/home', pathMatch: 'full' },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
import React, { useState, memo } from 'react';
import propsType from 'prop-types';
import { Collaspe } from '@central-tech/core-ui';
import styled from 'styled-components';
const WrapperStyled = styled.div`
position: relative;
${props => props.isHideBorder || 'border-bottom: 1px solid #B7B7B7;'}
${props => props.isToggle && 'padding-bottom: 16px;'}
`;
const ToggleSectionStyled = styled.div`
width: 100%;
padding: 15px 0;
font-size: 16px;
font-weight: bold;
color: #1a1b1a;
position: relative;
cursor: pointer;
${props => props.customStyle || ''}
`;
const ArrowStyled = styled.i`
border: solid #282828;
border-width: 0 1px 1px 0;
display: inline-block;
padding: 3px;
width: 8px;
height: 8px;
${props =>
props.direction === 'up'
? `
transform: rotate(-135deg);
-webkit-transform: rotate(-135deg);`
: `
transform: rotate(45deg);
-webkit-transform: rotate(45deg);
`}
`;
const SelectedResultStyled = styled.div`
font-size: 13px;
color: #817e7e;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
@media (max-width: 1024px) {
padding: 0 15px;
}
`;
const ClearBtnStyled = styled.button.attrs({ type: 'button' })`
color: #a9a9a9;
font-size: 12px;
position: absolute;
top: 16px;
right: 22px;
z-index: 1;
border: 0;
background: none;
`;
const TopStyled = styled.div`
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
@media (max-width: 1024px) {
padding: 0 15px;
}
`;
const CustomContentStyled = styled.div`
@media (max-width: 1024px) {
padding: 0 15px;
}
`;
const FilterTypeToggle = ({
type,
children,
isHideBorder,
titleList,
titleText,
disable,
onReset,
customStyle,
id,
btnClearId,
}) => {
const [isToggle, setToggle] = useState(false);
const titleListDecode =
titleList && titleList.length
? titleList.map(list => decodeURIComponent(list))
: [];
const titleTextDecode = titleText ? decodeURIComponent(titleText) : '';
return disable ? (
<WrapperStyled isHideBorder={isHideBorder}>
<ToggleSectionStyled disable={disable} customStyle={customStyle} id={id}>
<TopStyled>
{type}
{children}
</TopStyled>
{titleListDecode.length || titleTextDecode ? (
<SelectedResultStyled>
{titleTextDecode ? titleTextDecode : titleListDecode.join(', ')}
</SelectedResultStyled>
) : null}
</ToggleSectionStyled>
</WrapperStyled>
) : (
<WrapperStyled
isHideBorder={isHideBorder}
isToggle={isToggle}
customStyle={customStyle}
>
{isToggle && (
<ClearBtnStyled id={btnClearId} onClick={onReset}>
Clear
</ClearBtnStyled>
)}
<ToggleSectionStyled onClick={() => setToggle(!isToggle)} id={id}>
<TopStyled>
{type}
{isToggle ? (
<ArrowStyled direction="up" />
) : (
<ArrowStyled direction="down" />
)}
</TopStyled>
{(titleListDecode.length || titleTextDecode) && !isToggle ? (
<SelectedResultStyled>
{titleTextDecode ? titleTextDecode : titleListDecode.join(', ')}
</SelectedResultStyled>
) : null}
</ToggleSectionStyled>
<Collaspe visible={isToggle}>
<CustomContentStyled>{children}</CustomContentStyled>
</Collaspe>
</WrapperStyled>
);
};
FilterTypeToggle.PropsType = {
type: propsType.string.isRequired,
customStyle: propsType.string,
titleList: propsType.array,
titleText: propsType.string,
onReset: propsType.func,
id: propsType.string,
};
FilterTypeToggle.defaultProps = {
customStyle: '',
titleList: [],
titleText: '',
onReset: () => null,
id: '',
btnClearId: '',
};
export default memo(FilterTypeToggle);
|
/*You are given a binary array nums.
A subarray of an array is good if it contains exactly one element with the value 1.
Return an integer denoting the number of ways to split the array nums into good subarrays. As the number may be too large, return it modulo 109 + 7.
A subarray is a contiguous non-empty sequence of elements within an array.
*/
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
class Solution {
/* This is based on combinations.
Answer is Multiply all (numberOfZeros+1) between ones.
Algorithm:
1. If vector doesn't contain any 1s then return 0 else go to next step.
2. Start a loop to traverse the digits, go to next step
3. Pick new number and if number is 0, go to step - 4, else go to step 5.
4. If zeroPrefixExists == true, then ignore the current number, go to step 3 else go to step 4.1.
4.1. Increase zerosCount by 1 and go to step 3.
5. Since the digit is 1, noOfGoodArrays will be equal to noOfGoodArrays*(zerosCount+1).
6. If the traversal is complete then return the noOfGoodArrays.
*/
public:
int numberOfGoodSubarraySplits(vector<int>& nums) {
long zerosCount = 0, noOfGoodArrays=1;
bool zeroPrefixExists = true;
const int mod = 1e9+ 7;
if(find(nums.begin(), nums.end(), 1) == nums.end()) return 0;
for(int i: nums){
if(i==0){
if(zeroPrefixExists) continue;
zerosCount++;
}else{
// The below line is computationally expensive because of modulo operator.
// noOfGoodArrays = noOfGoodArrays == 0 ? (zerosCount+1)%mod : ((noOfGoodArrays%mod) * ((zerosCount+1)%mod))%mod;
noOfGoodArrays = noOfGoodArrays*(zerosCount+1);
// While loop is to avoid modulo operator as it is expensive
while(noOfGoodArrays >= mod){
noOfGoodArrays -= mod;
}
// noOfGoodArrays = ((noOfGoodArrays%mod) * ((zerosCount+1)%mod))%mod;
zerosCount = 0;
zeroPrefixExists = false;
}
}
return noOfGoodArrays;
}
};
class Solution1 {
/* This is based on combinations.
The number of combinations depend on number of zeros in between 2 ones.
Both suffix and prefix zeros doesn't alter the number of combinations
as they always go with 1 preceeding it for suffix zeros,
prefix zeros always go with 1 succeeding it.
So the algorithm starts with neglecting starting zeros.
If noOfGoodArray = 0 => we didn't yet encounter 1
Algorithm:
1. If vector doesn't contain any 1s then return 0 else go to next step.
2. Start traversing the digits, go to next step
3. If the number is 0, go to step - 4, else go to step
4. If noOfGoodArray is 0, then ignore the number and go to step 3 else go to step 5.
5. Increase zerosCount by 1 and go to step 3.
6. Since the digit is 1, noOfGoodArrays will be
Initialize two variable one to count number of zeros between ones, another one to store possible number of combinations
*/
public:
int numberOfGoodSubarraySplits(vector<int>& nums) {
long zerosCount = 0, noOfGoodArrays=0;
const int mod = 1e9+ 7;
if(find(nums.begin(), nums.end(), 1) == nums.end()) return 0;
for(int i: nums){
if(i==0){
if(noOfGoodArrays == 0) continue;
zerosCount++;
}else{
noOfGoodArrays = noOfGoodArrays == 0 ? (zerosCount+1)%mod : ((noOfGoodArrays%mod) * ((zerosCount+1)%mod))%mod;
zerosCount = 0;
}
}
return noOfGoodArrays;
}
};
int main(){
vector<int> vec1{0,1,1,0,0,1,0,0,1,1,0,1,0,1}; // 36
vector<int> vec2{0,0,0}; // 0
vector<int> vec3{0,1,0}; // 1
vector<int> vec4{0,1,0,0,1}; // 3
vector<int> vec5{0,1,1,1,0,0,1,1,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,0,1,1,0,0,1,0,0,0,0,0,0,0,1,1,1,1,0,0,1,1,1,1,1,1,0,0,1,1,1,0,1,0,1,0,1,1,0,0,0,0,0,1,0,0,1,0,0,1,1,1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0,0,0,0,1,0,1,0,0,0,1,0,0,1,1,0,1,1,1,1,1,0,1,1,0,0,1,1,1,0,0,1,0,0,1,1,0,1,0,1,1,1,0,0,1,0,0,0,1,0,0,1,0,0,1,1,1,1,0,0,0,0,0,1,0,1,0,0,1,0,1,0,1,0,1,1,1,0,0,0,1,0,1,1,1,1,1,0,1,0,1,0,0,0,0,1,0,0,0,1,1,1,0,1,1,0,1,1,1,0,1,1,0,1,1,0,0,0,1,0,1,1,0,0,1,1,1,0,1,1,1,0,1,0,1,1,0,0,1,1,1,0,0,1,1,1,1,0,0,1,0,0,1,0,1,0,1,1,1,0,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,0,1,1,1,0,0,1,0,1,0,1,0,1,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,1,0,0,0,1,0,1,0,1,1,1,1,0,0,0,1,0,0,1,0,0,0,1,0,1,1,1,0,1,1,0};
Solution sol;
cout << sol.numberOfGoodSubarraySplits(vec1) << endl;
cout << sol.numberOfGoodSubarraySplits(vec2) << endl;
cout << sol.numberOfGoodSubarraySplits(vec3) << endl;
cout << sol.numberOfGoodSubarraySplits(vec4) << endl;
cout << sol.numberOfGoodSubarraySplits(vec5) << endl;
}
|
import { useState } from 'react'
import { Router } from './Router'
import { BrowserRouter } from 'react-router-dom'
import { CyclesContextProvider } from './contexts/CyclesContext'
import { ThemeProvider } from 'styled-components'
import { GlobalStyle } from './styles/global'
import { lightTheme } from './styles/themes/light'
import { defaultTheme } from './styles/themes/default'
import { SwitchThemeButton } from './components/SwitchThemeButton'
import iconSun from './assets/icon-sun.svg'
import iconMoon from './assets/icon-moon.png'
export function App() {
const [isLightTheme, setIsLightTheme] = useState(false)
return (
<ThemeProvider theme={isLightTheme ? lightTheme : defaultTheme}>
<SwitchThemeButton>
<button onClick={() => setIsLightTheme(!isLightTheme)}>
{isLightTheme ? (
<img src={iconMoon} alt="ícone de sol cor preto" />
) : (
<img src={iconSun} alt="ícone de sol cor preto" />
)}
</button>
</SwitchThemeButton>
<BrowserRouter>
<CyclesContextProvider>
<Router />
</CyclesContextProvider>
</BrowserRouter>
<GlobalStyle />
</ThemeProvider>
)
}
|
package database
import (
"database/sql"
"github.com/devfullcycle/20-CleanArch/internal/entity"
)
type OrderRepository struct {
Db *sql.DB
}
func NewOrderRepository(db *sql.DB) *OrderRepository {
return &OrderRepository{Db: db}
}
func (r *OrderRepository) Save(order *entity.Order) error {
stmt, err := r.Db.Prepare("INSERT INTO orders (id, price, tax, final_price) VALUES (?, ?, ?, ?)")
if err != nil {
return err
}
_, err = stmt.Exec(order.ID, order.Price, order.Tax, order.FinalPrice)
if err != nil {
return err
}
return nil
}
func (r *OrderRepository) GetTotal() (int, error) {
var total int
err := r.Db.QueryRow("Select count(*) from orders").Scan(&total)
if err != nil {
return 0, err
}
return total, nil
}
func (r *OrderRepository) FindAll(page, limit int, sort string) ([]entity.Order, error) {
var orders []entity.Order
sql := "SELECT id, price, tax, final_price FROM orders"
if page <= 0 {
page = 1
}
pageAux := (page - 1)
if sort != "" {
sql += " ORDER BY " + sort
}
var args []interface{}
if limit > 0 && page > 0 {
args = append(args, limit, pageAux)
sql += " LIMIT ? OFFSET ?"
} else {
args = nil
}
stmt, err := r.Db.Prepare(sql)
if err != nil {
return nil, err
}
defer stmt.Close()
rows, err := stmt.Query(args...)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var order entity.Order
if err := rows.Scan(&order.ID, &order.Price, &order.Tax, &order.FinalPrice); err != nil {
return nil, err
}
orders = append(orders, order)
}
return orders, nil
}
|
import { BASE_URL } from "./constants";
const handleResponse = (res) => {
if (res.ok) {
return res.json();
} else {
return Promise.reject(`Произошла ошибка: ${res.status}`);
}
};
const register = (name, email, password) => {
return fetch(`${BASE_URL}/signup`, {
headers: {
"Content-Type": "application/json",
},
method: "POST",
body: JSON.stringify({ name, email, password }),
}).then(handleResponse);
};
const login = (email, password) => {
return fetch(`${BASE_URL}/signin`, {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify({ email, password }),
}).then(handleResponse);
};
const checkToken = (token) => {
return fetch(`${BASE_URL}/users/me`, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
method: "GET",
}).then(handleResponse);
};
const getUserInfo = () => {
return fetch(`${BASE_URL}/users/me`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("jwt")}`,
"Content-Type": "application/json",
},
method: "GET",
}).then(handleResponse);
};
const editUserInfo = (data) => {
return fetch(`${BASE_URL}/users/me`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("jwt")}`,
"Content-Type": "application/json",
},
method: "PATCH",
body: JSON.stringify({
name: data.name,
email: data.email,
}),
}).then((res) => handleResponse(res));
};
const getUsersMovies = () => {
return fetch(`${BASE_URL}/movies`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("jwt")}`,
"Content-Type": "application/json",
},
method: "GET",
}).then(handleResponse);
};
const saveMovie = (movies) => {
return fetch(`${BASE_URL}/movies`, {
method: "POST",
headers: {
Authorization: `Bearer ${localStorage.getItem("jwt")}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
country: movies.country,
director: movies.director,
duration: movies.duration,
year: movies.year,
description: movies.description,
image: "https://api.nomoreparties.co" + movies.image.url,
trailerLink: movies.trailerLink,
nameRU: movies.nameRU,
nameEN: movies.nameEN,
thumbnail:
"https://api.nomoreparties.co" + movies.image.formats.thumbnail.url,
movieId: movies.id,
}),
}).then((res) => handleResponse(res));
};
const deleteMovie = (movieId) => {
return fetch(`${BASE_URL}/movies/${movieId}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${localStorage.getItem("jwt")}`,
"Content-Type": "application/json",
},
}).then((res) => handleResponse(res));
};
export {
register,
login,
checkToken,
getUserInfo,
editUserInfo,
getUsersMovies,
saveMovie,
deleteMovie,
};
|
import { prismaClient } from "../../../database/prisma";
import { CreateBusiness } from "../dtos/ICreateBusinessDTO";
import { IBusinessRepository } from "./IBusinessRepository"
export class BusinessRepository implements IBusinessRepository {
constructor ( private prisma = prismaClient ) {}
async createBusiness({ name, website, cnpj, userId }: CreateBusiness): Promise<void> {
await this.prisma.business.create({
data: {
name: name,
website: website,
cnpj: cnpj,
userId: userId
}
})
}
async getAllBusiness(id: string): Promise<CreateBusiness[]> {
return await this.prisma.business.findMany({
where: {
userId: id
},
include: {
LocalBusiness: true
}
})
}
async findBusinessById(id: string): Promise<CreateBusiness> {
return await this.prisma.business.findUnique({ where: { id: id }})
}
async updateBusiness({ id, name, website, cnpj }: CreateBusiness): Promise<CreateBusiness> {
return await this.prisma.business.update({
data: {
name: name,
website: website,
cnpj: cnpj,
},
where: {
id: id
}
})
}
async deleteBusiness(id: string): Promise<void> {
await this.prisma.localBusiness.deleteMany({
where: { businessId: id }
})
await this.prisma.business.delete({
where: { id: id },
include: {
LocalBusiness: true
}
})
}
}
|
import { addContact } from 'redux/contactsSlice';
import css from './ContactForm.module.css';
import { useDispatch, useSelector } from 'react-redux';
import { nanoid } from '@reduxjs/toolkit';
import { getContacts } from 'redux/selectors';
export const ContactsForm = () => {
const dispatch = useDispatch();
const contacts = useSelector(getContacts);
const handleSubmit = e => {
e.preventDefault();
const form = e.target;
const newContact = {
id: nanoid(),
name: form.elements.name.value,
number: form.elements.number.value,
};
if (contacts.find(contact => contact.name === newContact.name)) {
alert('This contact already exist');
} else {
dispatch(addContact(newContact));
}
form.reset();
};
return (
<form className={css.form} onSubmit={handleSubmit}>
<label className={css.label} htmlFor="name">
Name
</label>
<input
id="name"
className={css.input}
type="text"
name="name"
pattern="^[a-zA-Zа-яА-Я]+(([' -][a-zA-Zа-яА-Я ])?[a-zA-Zа-яА-Я]*)*$"
title="Name may contain only letters, apostrophe, dash and spaces. For example Adrian, Jacob Mercer, Charles de Batz de Castelmore d'Artagnan"
required
autoComplete="off"
/>
<label className={css.label} htmlFor="number">
Number
</label>
<input
id="number"
className={css.input}
type="tel"
name="number"
pattern="\+?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}"
title="Phone number must be digits and can contain spaces, dashes, parentheses and can start with +"
required
autoComplete="off"
/>
<button className={css.addButton} type="submit">
Add
</button>
</form>
);
};
|
<template>
<div class="flex flex-row justify-center w-full h-full">
<button
class="rounded-l-3xl"
aria-label="Previous page"
:disabled="page === 1"
@click="prev()"
>
<IconMdiChevronLeft class="text-2xl" />
</button>
<div
class="flex dark:bg-slate-800 bg-white border-y-2 dark:border-slate-700 border-gray-200 dark:text-slate-300 text-gray-800 dark:shadow py-3 px-12"
>
<div class="w-max px-2 dark:text-slate-400 text-gray-600">{{ page }}</div>
<div class="">/</div>
<div class="w-max px-2">{{ pages }}</div>
</div>
<button
class="rounded-r-3xl"
aria-label="Next page"
:disabled="page >= pages"
@click="next()"
>
<IconMdiChevronRight class="text-2xl" />
</button>
</div>
</template>
<script setup lang="ts">
const props = defineProps({
count: {
type: Number,
default: 0,
},
perPage: {
type: Number,
default: 30,
},
page: {
type: Number,
default: 1,
},
})
const emit = defineEmits<{
(e: 'updatePage', page: string): void
}>()
const pages = computed<number>(() => Math.ceil(props.count / props.perPage))
function prev() {
if (props.page !== 1) {
let pageCopy = props.page
pageCopy--
emit('updatePage', String(pageCopy))
}
}
function next() {
if (props.page < pages.value) {
let pageCopy = props.page
pageCopy++
emit('updatePage', String(pageCopy))
}
}
</script>
<style scoped>
button {
@apply outline-none
dark:bg-slate-800 bg-white
border-2 border-transparent dark:border-slate-700 border-gray-200
dark:shadow
px-6
transition duration-150
dark:text-slate-300 text-gray-500
dark:hover:bg-slate-400/20
hover:bg-gray-100
active:border-teal-400
focus:border-teal-400
dark:active:border-teal-400
dark:focus:border-teal-400
dark:disabled:text-slate-600
dark:disabled:hover:bg-slate-800
dark:disabled:active:border-slate-700
disabled:text-gray-300
disabled:active:border-gray-200
disabled:hover:bg-white;
}
</style>
|
package com.example.android.justjava;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.NumberFormat;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
int quantity = 1;
int price = 5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void increment(View view) {
if(quantity >= 100) {
Toast.makeText(this, "Maximum cups ordered is 100", Toast.LENGTH_SHORT).show();
display(quantity);
return;
}
quantity = quantity + 1;
display(quantity);
}
public void decrement(View view) {
if(quantity <= 1){
Toast.makeText(this, "Must have Minimum of 1 cup", Toast.LENGTH_SHORT).show();
display(quantity);
return;
}
quantity = quantity - 1;
display(quantity);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
CheckBox whippedCreamCheckBox = findViewById(R.id.whipped_cream_checkbox);
boolean hasWhippedCream = whippedCreamCheckBox.isChecked();
CheckBox chocolateCheckBox = findViewById(R.id.chocolate_checkbox);
boolean hasChocolate = chocolateCheckBox.isChecked();
CheckBox vanillaCreamerCheckbox = findViewById(R.id.vanillaCreamer_checkbox);
boolean hasVaniallCreamer = vanillaCreamerCheckbox.isChecked();
EditText userNameField = (EditText) findViewById(R.id.user_name_field);
String userName = userNameField.getText().toString();
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_SUBJECT, "Just Java order for " + userName);
intent.putExtra(Intent.EXTRA_TEXT, createOrderSummary(hasWhippedCream, hasChocolate, hasVaniallCreamer, userName));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
/**
*
* @param addWhippedCream
* @param addChocolate
* @return
*/
private int calculatePrice(boolean addWhippedCream, boolean addChocolate){
if(addChocolate){
price += 2;
}
if(addWhippedCream){
price += 1;
}
return price * quantity;
}
/**
* * Creates a text summary of the order
* @param addWhippedCream whether or not the user wants whipped cream
* @param addChocolate yes or no to chocolate option
* @param userName
* @return order summary
*/
private String createOrderSummary(boolean addWhippedCream, boolean addChocolate, boolean addVaniallaCreamer, String userName){
String priceMessage = getString(R.string.order_summary_name, userName);
priceMessage += "\n"+ getString(R.string.order_summary_whipped_cream, addWhippedCream);
priceMessage += "\n" + getString(R.string.order_summary_chocolate, addChocolate);
priceMessage += "\n" + getString(R.string.order_summary_vanillaCreamer,addVaniallaCreamer );
priceMessage += "\n" + getString(R.string.order_summary_quantity, quantity);
priceMessage += "\nTotal: $" + calculatePrice(addWhippedCream, addChocolate) + "\nThank you!";
return priceMessage;
}
}
|
<?php
namespace App\Http\Livewire;
use App\Models\Post;
use Livewire\Component;
use Livewire\WithFileUploads;
class CreatePost extends Component
{ use WithFileUploads;
public $open=false;
public $title, $content; //$image;
protected $rules=[
'title' => 'required|max:100',
//'content' => 'requered|min:100'
'content' => 'required',
//'image' => 'required|image|max:2048'
];
public function render()
{
return view('livewire.create-post');
}
public function save(){
$this->validate();
//$image=$this->image->path_public('storage/posts');
Post::create([
'title' => $this->title,
'content' => $this->content
]);
$this->reset(['open', 'title', 'content']);
//$this->emit('render');
$this->emitTo('show-posts', 'render');
$this->emit('alert', 'Se creo el post');
}
public function updatingOpen(){
if($this->open==false){
$this->reset(['title', 'content']);
$this->emit('resetCKEditor');
}
}
}
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../bloc/chat/chat_bloc.dart';
import '../../screen/chat/widgets/message_box.dart';
import '../../utils/color_helpers.dart';
import '/screen/chat/widgets/message_list.dart';
class ChatScreen extends StatefulWidget {
const ChatScreen({super.key});
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final TextEditingController _messageController = TextEditingController();
@override
void initState() {
super.initState();
context.read<ChatBloc>().setupConnectionAndListen();
context.read<ChatBloc>().add(GetInitialMessageEvent());
}
@override
Widget build(BuildContext context) {
return BlocConsumer<ChatBloc, ChatState>(
listener: (context, state) {
if (state is ChatErrorState) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(state.message),
),
);
}
},
builder: (context, state) {
return Scaffold(
appBar: AppBar(
backgroundColor: ColorHelpers.primaryLight,
title: Text(
"Chat ID - ${context.read<ChatBloc>().currentChat}",
style: const TextStyle(color: Colors.white),
),
leading: InkWell(
onTap: () => {context.pop()},
child: const Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
// ignore: prefer_const_constructors
MessageList(),
MessageBox(
messageController: _messageController,
)
],
),
);
},
);
}
}
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
<title>Stockdata</title>
</head>
<body>
<div id="tabmenu" class="container">
<h1>ETF savings simulation</h1>
<ul class="nav nav-pills">
<li class="active"><a href="#home" data-toggle="pill" class="nav-link active">Data input</a></li>
<li><a href="#stockdata" data-toggle="pill" class="nav-link" id="stockdatalink">Stock data</a></li>
<li><a href="#savingspill" data-toggle="pill" class="nav-link">Depot value</a></li>
<li><a href="#win" data-toggle="pill" class="nav-link">Win/Loss</a></li>
<li><a href="#tax" data-toggle="pill" class="nav-link">Tax costs</a></li>
<li><a href="#allocation" data-toggle="pill" class="nav-link">Allocation</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">
<div class="row">
<h4>Stocks</h4>
</div>
<div class="row">
<div class="col-sm">
<div class="form-group">
<label for="symbolInput">Stock-Symbol</label>
<input type="text" class="form-control" id="symbolInput" value="XWD.TO">
<small class="form-text text-muted">Provide stock symbol to analyze.</small>
</div>
</div>
<div class="col-sm">
<div class="form-group">
<label for="initialAmount">Initial amount</label>
<input type="text" class="form-control" id="initialAmount" value="60">
<small class="form-text text-muted">Initial amount of stocks.</small>
</div>
</div>
<div class="col-sm">
<div class="form-group">
<label for="savings">Monthly savings</label>
<input type="text" class="form-control" id="savings" value="200.0">
<small class="form-text text-muted">Monthly saving rate in EUR.</small>
</div>
</div>
<div class="col-sm">
<div class="form-group">
<label class="control-label" for="symbolsBtn">Add stock symbol</label>
<input type="button" id="symbolsBtn" name="symbolsBtn" value="Add" class="form-control btn btn-primary btn-sm" />
<small class="form-text text-muted">Add stock symbol with amount and monthly saving to list.</small>
</div>
</div>
</div>
<div class="row">
<div class="col-sm">
<div class="form-group">
<hr>
<ul id="symbolsList" class="list-group"></ul>
</div>
</div>
</div>
<div class="row">
<h4>Cost data</h4>
</div>
<div class="row">
<div class="col-sm">
<div class="form-group">
<label for="transCost">Transaction costs</label>
<input type="text" class="form-control" id="transCost" value="0.015">
<small class="form-text text-muted">Monthly transaction cost in percent.</small>
</div>
</div>
<div class="col-sm">
<div class="form-group">
<label for="allowance">Allowance</label>
<input type="text" class="form-control" id="allowance" value="801">
<small class="form-text text-muted">Allowance to respect in costs.</small>
</div>
</div>
</div>
<div class="row">
<h4>Period</h4>
</div>
<div class="row">
<div class="col-sm">
<div class="form-group">
<label class="control-label" for="from">From</label>
<input class="form-control" id="from" value="2010-01" type="text"/>
<small class="form-text text-muted">Start date to analyze stock and depot.</small>
</div>
</div>
<div class="col-sm">
<div class="form-group">
<label class="control-label" for="to">To</label>
<input class="form-control" id="to" value="2018-01" type="text"/>
<small class="form-text text-muted">End date to analyze stock and depot.</small>
</div>
</div>
</div>
<div class="row">
<div class="col-sm">
<button type="submit" class="btn btn-primary" id="analyzeBtn">Analyze</button>
</div>
</div>
</div>
<div class="tab-pane" id="stockdata">
<div class="row">
<canvas id="stockChart" width="300" height="100"></canvas>
</div>
</div>
<div class="tab-pane" id="savingspill">
<div class="row">
<canvas id="depotValueChart" width="300" height="100"></canvas>
</div>
<div class="row">
<canvas id="spendingsChart" width="300" height="100"></canvas>
</div>
<div class="row">
<canvas id="amountsChart" width="300" height="100"></canvas>
</div>
</div>
<div class="tab-pane" id="win">
<div class="row">
<canvas id="winChart" width="300" height="100"></canvas>
</div>
</div>
<div class="tab-pane" id="tax">
<div class="row">
<canvas id="taxChart" width="300" height="100"></canvas>
</div>
<div class="row">
<canvas id="taxSellingChart" width="300" height="100"></canvas>
</div>
*Chart assumes that the stock is reinvesting
</div>
<div class="tab-pane" id="allocation">
<div class="row">
<canvas id="allocationChart" width="300" height="100"></canvas>
</div>
*Without rebalancing
</div>
</div>
</div>
<script>
var stack = [];
function md5(s){function L(k,d){return(k<<d)|(k>>>(32-d))}function K(G,k){var I,d,F,H,x;F=(G&2147483648);H=(k&2147483648);I=(G&1073741824);d=(k&1073741824);x=(G&1073741823)+(k&1073741823);if(I&d){return(x^2147483648^F^H)}if(I|d){if(x&1073741824){return(x^3221225472^F^H)}else{return(x^1073741824^F^H)}}else{return(x^F^H)}}function r(d,F,k){return(d&F)|((~d)&k)}function q(d,F,k){return(d&k)|(F&(~k))}function p(d,F,k){return(d^F^k)}function n(d,F,k){return(F^(d|(~k)))}function u(G,F,aa,Z,k,H,I){G=K(G,K(K(r(F,aa,Z),k),I));return K(L(G,H),F)}function f(G,F,aa,Z,k,H,I){G=K(G,K(K(q(F,aa,Z),k),I));return K(L(G,H),F)}function D(G,F,aa,Z,k,H,I){G=K(G,K(K(p(F,aa,Z),k),I));return K(L(G,H),F)}function t(G,F,aa,Z,k,H,I){G=K(G,K(K(n(F,aa,Z),k),I));return K(L(G,H),F)}function e(G){var Z;var F=G.length;var x=F+8;var k=(x-(x%64))/64;var I=(k+1)*16;var aa=Array(I-1);var d=0;var H=0;while(H<F){Z=(H-(H%4))/4;d=(H%4)*8;aa[Z]=(aa[Z]| (G.charCodeAt(H)<<d));H++}Z=(H-(H%4))/4;d=(H%4)*8;aa[Z]=aa[Z]|(128<<d);aa[I-2]=F<<3;aa[I-1]=F>>>29;return aa}function B(x){var k="",F="",G,d;for(d=0;d<=3;d++){G=(x>>>(d*8))&255;F="0"+G.toString(16);k=k+F.substr(F.length-2,2)}return k}function J(k){k=k.replace(/rn/g,"n");var d="";for(var F=0;F<k.length;F++){var x=k.charCodeAt(F);if(x<128){d+=String.fromCharCode(x)}else{if((x>127)&&(x<2048)){d+=String.fromCharCode((x>>6)|192);d+=String.fromCharCode((x&63)|128)}else{d+=String.fromCharCode((x>>12)|224);d+=String.fromCharCode(((x>>6)&63)|128);d+=String.fromCharCode((x&63)|128)}}}return d}var C=Array();var P,h,E,v,g,Y,X,W,V;var S=7,Q=12,N=17,M=22;var A=5,z=9,y=14,w=20;var o=4,m=11,l=16,j=23;var U=6,T=10,R=15,O=21;s=J(s);C=e(s);Y=1732584193;X=4023233417;W=2562383102;V=271733878;for(P=0;P<C.length;P+=16){h=Y;E=X;v=W;g=V;Y=u(Y,X,W,V,C[P+0],S,3614090360);V=u(V,Y,X,W,C[P+1],Q,3905402710);W=u(W,V,Y,X,C[P+2],N,606105819);X=u(X,W,V,Y,C[P+3],M,3250441966);Y=u(Y,X,W,V,C[P+4],S,4118548399);V=u(V,Y,X,W,C[P+5],Q,1200080426);W=u(W,V,Y,X,C[P+6],N,2821735955);X=u(X,W,V,Y,C[P+7],M,4249261313);Y=u(Y,X,W,V,C[P+8],S,1770035416);V=u(V,Y,X,W,C[P+9],Q,2336552879);W=u(W,V,Y,X,C[P+10],N,4294925233);X=u(X,W,V,Y,C[P+11],M,2304563134);Y=u(Y,X,W,V,C[P+12],S,1804603682);V=u(V,Y,X,W,C[P+13],Q,4254626195);W=u(W,V,Y,X,C[P+14],N,2792965006);X=u(X,W,V,Y,C[P+15],M,1236535329);Y=f(Y,X,W,V,C[P+1],A,4129170786);V=f(V,Y,X,W,C[P+6],z,3225465664);W=f(W,V,Y,X,C[P+11],y,643717713);X=f(X,W,V,Y,C[P+0],w,3921069994);Y=f(Y,X,W,V,C[P+5],A,3593408605);V=f(V,Y,X,W,C[P+10],z,38016083);W=f(W,V,Y,X,C[P+15],y,3634488961);X=f(X,W,V,Y,C[P+4],w,3889429448);Y=f(Y,X,W,V,C[P+9],A,568446438);V=f(V,Y,X,W,C[P+14],z,3275163606);W=f(W,V,Y,X,C[P+3],y,4107603335);X=f(X,W,V,Y,C[P+8],w,1163531501);Y=f(Y,X,W,V,C[P+13],A,2850285829);V=f(V,Y,X,W,C[P+2],z,4243563512);W=f(W,V,Y,X,C[P+7],y,1735328473);X=f(X,W,V,Y,C[P+12],w,2368359562);Y=D(Y,X,W,V,C[P+5],o,4294588738);V=D(V,Y,X,W,C[P+8],m,2272392833);W=D(W,V,Y,X,C[P+11],l,1839030562);X=D(X,W,V,Y,C[P+14],j,4259657740);Y=D(Y,X,W,V,C[P+1],o,2763975236);V=D(V,Y,X,W,C[P+4],m,1272893353);W=D(W,V,Y,X,C[P+7],l,4139469664);X=D(X,W,V,Y,C[P+10],j,3200236656);Y=D(Y,X,W,V,C[P+13],o,681279174);V=D(V,Y,X,W,C[P+0],m,3936430074);W=D(W,V,Y,X,C[P+3],l,3572445317);X=D(X,W,V,Y,C[P+6],j,76029189);Y=D(Y,X,W,V,C[P+9],o,3654602809);V=D(V,Y,X,W,C[P+12],m,3873151461);W=D(W,V,Y,X,C[P+15],l,530742520);X=D(X,W,V,Y,C[P+2],j,3299628645);Y=t(Y,X,W,V,C[P+0],U,4096336452);V=t(V,Y,X,W,C[P+7],T,1126891415);W=t(W,V,Y,X,C[P+14],R,2878612391);X=t(X,W,V,Y,C[P+5],O,4237533241);Y=t(Y,X,W,V,C[P+12],U,1700485571);V=t(V,Y,X,W,C[P+3],T,2399980690);W=t(W,V,Y,X,C[P+10],R,4293915773);X=t(X,W,V,Y,C[P+1],O,2240044497);Y=t(Y,X,W,V,C[P+8],U,1873313359);V=t(V,Y,X,W,C[P+15],T,4264355552);W=t(W,V,Y,X,C[P+6],R,2734768916);X=t(X,W,V,Y,C[P+13],O,1309151649);Y=t(Y,X,W,V,C[P+4],U,4149444226);V=t(V,Y,X,W,C[P+11],T,3174756917);W=t(W,V,Y,X,C[P+2],R,718787259);X=t(X,W,V,Y,C[P+9],O,3951481745);Y=K(Y,h);X=K(X,E);W=K(W,v);V=K(V,g)}var i=B(Y)+B(X)+B(W)+B(V);return i.toLowerCase()};
function createList(btnID, listID, valueFn) {
$('#' + btnID).click(function() {
var saving = valueFn();
appendToList(listID, saving);
return false;
});
}
function appendToList(listID, value) {
var id = md5(value);
var listElem = '<li class="list-group-item" id="'+id+'">' +
value +
' <input type="button" class="btn btn-sm" value="remove" onClick="$(\'#'+id+'\').remove();"/>'+
'</li>';
$('#' + listID).append(listElem);
}
$(document).ready(function(){
var from=$('#from');
var to=$('#to');
var oneTimeDate=$('#oneTimeDate');
var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body";
var options={
format: 'yyyy-mm',
container: container,
todayHighlight: true,
autoclose: true,
};
from.datepicker(options);
to.datepicker(options);
oneTimeDate.datepicker(options);
createList('symbolsBtn', 'symbolsList', function() {
return $('#symbolInput').val() + "**" + $('#initialAmount').val() + "**" + $('#savings').val();
});
appendToList('symbolsList', 'XWD.TO**66**200.0');
appendToList('symbolsList', 'XEM.TO**50**100.0');
})
$('#analyzeBtn').on('click', function(e) {
var allowance =$('#allowance').val();
var transCost =$('#transCost').val();
var from =$('#from').val();
var to =$('#to').val();
var oneTimeSavings = [];
var stocks = [];
$('#savingslist li').each(function(i) {
var entry = $(this).html().split('**');
oneTimeSavings.push({
date: entry[0],
amount: parseFloat(entry[1])
});
});
$('#symbolsList li').each(function(i) {
var entry = $(this).html().split('**');
stocks.push({
symbol: entry[0],
initialAmount: parseFloat(entry[1]),
monthlySavings: parseFloat(entry[2])
});
});
while (stack.length > 0) {
var chart = stack.pop();
chart.destroy();
}
var data = {
savings: stocks,
allowance: parseFloat(allowance),
transactionCostPercentage: parseFloat(transCost),
from: from,
to: to,
}
var jsonData = $.post({
type: 'POST',
url: 'getdata',
data: JSON.stringify(data),
dataType: 'json',
}).done(function (result) {
drawGraph("stockChart", result, "stocks", "Stock value");
drawGraph("depotValueChart", result, "depotValues", "Depot value");
drawGraph("spendingsChart", result, "spendings", "Spendings");
drawGraph("winChart", result, "winLoss", "Win/loss");
drawGraph("taxChart", result, "annualTaxes", "Annual tax costs");
drawGraph("taxSellingChart", result, "sellingTaxes", "Selling tax costs");
drawGraph("amountsChart", result, "amounts", "Amount", function(val) {
return new Intl.NumberFormat('en-US', { }).format(val);
});
drawGraph("allocationChart", result, "allocations","", function(val) {
return new Intl.NumberFormat('en-US', { style: 'percent'}).format(val);
});
});
$('#stockdatalink').trigger('click');
return false;
});
function createDataSet(dataset, index) {
var colors = ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850"];
return {
label: dataset.label,
data: dataset.data,
borderColor: colors[index],
fill: false
}
}
function drawGraph(graphID, result, key, label, formatFn) {
var labels = []
var data = []
if (formatFn === undefined) {
formatFn = function(val) {
return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'EUR' }).format(val);
}
}
Object.keys(result.analyzedData[key]).map((symbol) => {
var entry = result.analyzedData[key][symbol].data;
labels = entry.map(e => e.date);
data.push({
label: label + " " + symbol,
data: entry.map(e => e.value)
});
});
var styledData = data.map(createDataSet);
var ctx = document.getElementById(graphID).getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: styledData
},
options: {
tooltips: {
mode: 'index',
callbacks: {
label: function(tooltipItem, data) {
return formatFn(tooltipItem.yLabel.toString());
},
},
},
scales: {
xAxes: [{
type: 'time',
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
},
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'value'
},
ticks: {
callback: function(value, index, values) {
return formatFn(value);
}
}
}]
}
}
});
stack.push(chart);
}
</script>
</html>
|
// findFirstStringInBracket original code
func findFirstStringInBracket(str string) string {
if len(str) > 0 {
indexFirstBracketFound := strings.Index(str, "(")
if indexFirstBracketFound >= 0 {
runes := []rune(str)
wordsAfterFirstBracket := string(runes[indexFirstBracketFound:len(str)])
indexClosingBracketFound := strings.Index(wordsAfterFirstBracket, ")")
if indexClosingBracketFound >= 0 {
runes := []rune(wordsAfterFirstBracket)
return string(runes[1 : indexClosingBracketFound-1])
} else {
return ""
}
} else {
return ""
}
} else {
return ""
}
return ""
}
// findFirstStringInBracket2 , refactored and amended version of function findFirstStringInBracket
// example of input and output
// (asdf) -> asd
// (qwe -> ""
func findFirstStringInBracket2(wordInput string) string {
wordTemp, word := "", ""
firstBracketFound := false
for _, character := range wordInput {
if character == '(' {
firstBracketFound = true
continue
}
if character == ')' {
word = wordTemp
break
}
if firstBracketFound {
wordTemp += string(character)
}
}
if len(word) == 0 {
return ""
}
return word[:len(word)-1]
}
|
const mongoose = require('mongoose');
const Order = require('../models/order');
const Product = require('../models/product');
exports.order_get_all = (req, res, next) => {
Order.find()
.select('-__v')
.populate('product', 'name')
.exec()
.then(docs => {
res.status(200).json({
message: 'Orders were fetched',
count: docs.length,
oders: docs.map(doc => {
return {
product: doc.product,
quantity: doc.quantity,
_id: doc._id,
request: {
type: 'GET',
url: 'http://localhost:3000/orders/' + doc._id,
},
};
}),
});
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
};
exports.order_create_order = (req, res, next) => {
Product.findById(req.body.productId)
.then(product => {
if (!product)
return res.status(404).json({ message: 'Product not found!' });
const order = new Order({
_id: new mongoose.Types.ObjectId(),
quantity: req.body.quantity,
product: req.body.productId,
});
return order.save();
})
.then(result => {
console.log(result);
res.status(201).json({
message: 'Orders were created',
order: {
product: result.product,
quantity: result.quantity,
_id: result._id,
},
request: {
type: 'GET',
url: 'http://localhost:3000/orders/' + result._id,
},
});
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
};
exports.orders_get_order = (req, res, next) => {
Order.findById(req.params.orderId)
.populate('product')
.exec()
.then(order => {
if (!order) return res.status(404).json({ message: 'Order not found!' });
res.status(200).json({
message: 'Orders details',
order: order,
request: {
type: 'GET',
url: 'http://localhost:3000/orders/',
},
});
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
};
exports.order_delete_order = (req, res, next) => {
const id = req.params.orderId;
Order.deleteOne({ _id: id })
.exec()
.then(order => {
if (!order) return res.status(404).json({ message: 'Order not found!' });
res.status(200).json({
message: 'Order deleted',
request: {
type: 'POST',
url: 'http://localhost:3000/orders/' + id,
body: { productId: 'String', quantity: 'Number' },
},
});
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
};
|
/*
* Copyright 2021 The Quilt Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Events to track the lifecycle of Minecraft.
*
* <p>The events in this package track the lifecycle of a logical Minecraft server. A Minecraft server operates using a
* tick loop and events are executed as the tick loop runs.
*
* <p>The events in {@link org.quiltmc.qsl.lifecycle.api.event.ServerLifecycleEvents} are executed during server initialization
* or server shutdown.
*
* <p>The events in {@link org.quiltmc.qsl.lifecycle.api.event.ServerTickEvents} are executed as the tick loop is iterated.
*
* <p>The events in {@link org.quiltmc.qsl.lifecycle.api.event.ServerWorldLoadEvents} are executed as the worlds on a
* server are loaded or unloaded.
*
* @see org.quiltmc.qsl.lifecycle.api.event.ServerLifecycleEvents
* @see org.quiltmc.qsl.lifecycle.api.event.ServerTickEvents
* @see org.quiltmc.qsl.lifecycle.api.event.ServerWorldLoadEvents
*/
package org.quiltmc.qsl.lifecycle.api.event;
|
<template>
<div id="app">
<!--
<h1>Employees</h1>
<employee-form @add:employee="addEmployee" />
<employee-table v-bind:employees="employees" />
-->
<h1><spinner ref="spinner"></spinner>Homes</h1>
<button style="visibility:hidden" v-on:click="loadLatestRefresh()">test</button>
<h3>Latest refresh time:
<label>{{metadata.latest_refresh}}</label></h3>
<homes-table v-bind:homes="visible" v-on:refresh="refreshData()" v-on:reload="reloadData()" @update="updateData" @saveComment="saveComment" v-bind:all_refreshed="all_refreshed" />
</div>
</template>
<script>
import Vue from 'vue'
import Spinner from '@/components/Spinner.vue'
import EmployeeTable from '@/components/EmpoyeeTable.vue'
import HomesTable from '@/components/HomesTable.vue'
import EmployeeForm from '@/components/EmployeeForm.vue'
import gql from 'graphql-tag'
var ajax = require("vuejs-ajax")
Vue.use(ajax);
export default {
apollo: {
archived: {
query: gql`
query{
archived: homes(archived:1) {
id
}
visible: homes(archived:0) {
id
title
description
source
price
comments
dateCreated
dateFound
image
advUrl
type
}
}
`,
result(data){
this.visible = data.data.visible,
this.archived = data.data.archived
this.loadLatestRefresh();
this.$refs.spinner.hide();//After every reload, spinner must be hidden
}
}
},
name: 'App',
components: {
HomesTable,
Spinner
},
data() {
return {
all_refreshed: 0,
visible:[],
metadata: {"refresh":0, "latest_refresh":NaN}
}
},
created() {
this.loadLatestRefresh();
setInterval(function(){this.loadLatestRefresh();}, 1000*60*15);//call every 15 minutes
},
computed: {
noOfAllHomes: function(){
return this. visible && this. visible.length;
},
noOfAllHomesArchived: function(){
return this.archived && this.archived.length;
}
},
methods:{
addEmployee(employee) {
const lastId =
this.employees.length > 0
? this.employees[this.employees.length - 1].id
: 0;
const id = lastId + 1;
const newEmployee = { ...employee, id };
this.employees = [...this.employees, newEmployee];
},
refreshData(){
this.$refs.spinner.show();
this.$apollo.queries.archived.refetch();
},
saveComment(id, comment){
console.log(id,comment);
parent = this;
Vue.ajax({
url: process.env.URL_UPDATE + '/' + id,
method: "patch",
headers: {
'Access-Control-Allow-Origin': '*'
/*,'Content-Type': 'application/json'*/
},
data: { "comments": comment},
timeout: 600000,
}).then(
function(response) {
return response.data;
},
function(response) {
console.log('END ERROR');
console.log("Error", response.statusText)
});
},
updateData(id, selected_type){
parent = this;
Vue.ajax({
url: process.env.URL_UPDATE + '/' + id,
method: "patch",
headers: {
'Access-Control-Allow-Origin': '*'
/*,'Content-Type': 'application/json'*/
},
data: { "type": selected_type},
timeout: 600000,
}).then(
function(response) {
return response.data;
},
function(response) {
console.log('END ERROR');
console.log("Error", response.statusText)
});
},
reloadData(){
this.$refs.spinner.show();
this.loadData(this);
},
loadData(context) {
console.log('START OK', process.env.URL_REFRESH);
this.all_refreshed = NaN;
parent = this;
Vue.ajax({
url: process.env.URL_REFRESH,
//url: 'https://jsonplaceholder.typicode.com/todos',
method: "get",
headers: {
'Access-Control-Allow-Origin': '*'
},
timeout: 600000,
}).then(
function(response) {
context.all_refreshed = response.data['all_changed_items'];
parent.$apollo.queries.archived.refetch();
this.loadLatestRefresh(context);
return response.data;
},
function(response) {
console.log('END ERROR');
console.log("Error", response.statusText)
});
},
loadLatestRefresh(context) {
console.log("refresh called");
parent = this;
Vue.ajax({
url: process.env.URL_LATEST_REFRESH,
//url: 'https://jsonplaceholder.typicode.com/todos',
method: "get",
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
timeout: 600000,
}).then(
function(response) {
var metadata = response.data;
if (metadata != null){
var d = new Date(metadata.datetime.toString());
var datestring = d.getDate() + "." + (String(d.getMonth()+1)).padStart(2,"0") + "." + d.getFullYear() + " " +
String(d.getHours()).padStart(2, "0") + ":" + String(d.getMinutes()).padStart(2, "0");
var no_of_refreshed = metadata.changed_items;
console.log("XXXXXXXXXXXX" + datestring);
parent.metadata.latest_refresh = datestring;
parent.metadata.refresh = no_of_refreshed;
return response.data;
}
},
function(response) {
console.log('END ERROR');
console.log("Error", response.statusText)
});
}
},
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
|
package com.gyawaliamit.spring.html.generator.builder.body;
import com.gyawaliamit.spring.html.generator.builder.body.tags.*;
import com.gyawaliamit.spring.html.generator.builder.body.tags.table.TableBuilder;
import com.gyawaliamit.spring.html.generator.constants.HtmlConstants;
import com.gyawaliamit.spring.html.generator.enums.Heading;
import com.gyawaliamit.spring.html.generator.builder.head.HeadBuilder;
import com.gyawaliamit.spring.html.generator.handler.AttributesHandler;
import com.gyawaliamit.spring.html.generator.handler.Handler;
import com.gyawaliamit.spring.html.generator.handler.StyleHandler;
import java.util.*;
/**
* this is the builder class to create Body Elements
*/
public class BodyBuilder {
private Queue<BodyTags> bodyTags;
private StringBuilder content;
private Map<String, Handler> handlers;
public BodyBuilder(StringBuilder content, Queue<BodyTags> bodyTags, Map<String, Handler> styleHandler) {
this.bodyTags = bodyTags;
this.content = content;
this.handlers = styleHandler;
}
public static BodyBuilder builder() {
Map<String,Handler> handlers = new HashMap<>();
handlers.put(HtmlConstants.STYLE, new StyleHandler());
handlers.put(HtmlConstants.ATTRIBUTE, new AttributesHandler());
return new BodyBuilder(new StringBuilder(""), null,handlers);
}
public StringBuilder getContent() {
return content;
}
public BodyBuilder build() {
this.content.append("<body ");
this.handlers.forEach((key,handler) -> {
handler.handle(this.content);
});
this.content.append(">");
for(BodyTags bodyTag : bodyTags) {
content.append(bodyTag.getContent());
}
content.append("</body>");
return this;
}
public BodyBuilder div(DivBuilder divBuilder) {
if(this.bodyTags == null) {
this.bodyTags = new LinkedList<>();
}
this.bodyTags.add(divBuilder);
return this;
}
public BodyBuilder heading(HeadingBuilder headBuilder) {
if(this.bodyTags == null) {
this.bodyTags = new LinkedList<>();
}
this.bodyTags.add(headBuilder);
return this;
}
public BodyBuilder paragraph(ParagraphBuilder paragraphBuilder) {
if(this.bodyTags == null) {
this.bodyTags = new LinkedList<>();
}
this.bodyTags.add(paragraphBuilder);
return this;
}
public BodyBuilder ahref(AhrefBuilder ahrefBuilder) {
if(this.bodyTags == null) {
this.bodyTags = new LinkedList<>();
}
this.bodyTags.add(ahrefBuilder);
return this;
}
public BodyBuilder image(ImageBuilder imageBuilder) {
if(this.bodyTags == null) {
this.bodyTags = new LinkedList<>();
}
this.bodyTags.add(imageBuilder);
return this;
}
public BodyBuilder table(TableBuilder tableBuilder) {
if(this.bodyTags == null) {
this.bodyTags = new LinkedList<>();
}
this.bodyTags.add(tableBuilder);
return this;
}
public BodyBuilder style(String key, String value) {
Handler handler = this.handlers.get(HtmlConstants.STYLE);
handler.addItem(key,value);
return this;
}
public BodyBuilder attribute(String key, String value) {
Handler handler = this.handlers.get(HtmlConstants.ATTRIBUTE);
handler.addItem(key,value);
return this;
}
}
|
import React, { useEffect, useState, useCallback, useRef } from 'react';
import { ProviderConflux, ProviderEvents } from '@onekeyfe/onekey-conflux-provider';
import { exampleContract, cfxTypedData } from './contract';
import { DAppList } from '../dappList/DAppList';
import { dapps } from './dapps.config';
const cusdtAddress = 'cfxtest:acepe88unk7fvs18436178up33hb4zkuf62a9dk1gv';
const useProvider = () => {
const [provider, setProvider] = useState<ProviderConflux>();
useEffect(() => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const injectedProvider = window.conflux as ProviderConflux;
const confluxProvider = injectedProvider || new ProviderConflux({});
setProvider(confluxProvider);
}, []);
return provider;
};
function ConfluxExample() {
const [connected, setConnected] = useState(false);
const [chainId, setChainId] = useState('');
const [networkId, setNetworkId] = useState('');
const [accounts, setAccounts] = useState<string[]>([]);
const spender = useRef();
const transferFrom = useRef();
const transferTo = useRef();
const provider = useProvider();
const init = useCallback((provider: ProviderConflux) => {
if (provider.isConnected()) {
setConnected(true);
Promise.all([
provider.request<string[]>({ method: 'cfx_accounts' }),
provider.request<string>({ method: 'cfx_chainId' }),
])
.then(([accounts, chainId]) => {
setAccounts(accounts);
setChainId(chainId);
setNetworkId(parseInt(chainId, 16).toString(10));
})
.catch(console.error);
provider
.request<string[]>({
method: 'cfx_accounts',
})
.then((accounts) => setAccounts(accounts))
.catch(console.error);
}
}, []);
const handleConnectWallet = useCallback(async () => {
const accounts = await provider.request<string[]>({
method: 'cfx_requestAccounts',
});
setAccounts(accounts);
}, [provider]);
const handleSendNativeToken = useCallback(async () => {
const [connectedAddress] = await provider.request<string[]>({ method: 'cfx_accounts' });
const tx = {
from: connectedAddress,
value: '0xde0b6b3a7640000',
to: connectedAddress,
};
try {
const result = await provider.request<string>({
method: 'cfx_sendTransaction',
params: [tx],
});
console.log(`send native token success: ${result}`);
} catch (e) {
console.log(e);
}
}, [provider]);
const handleApproveToken = useCallback(async () => {
const [connectedAddress] = await provider.request<string[]>({ method: 'cfx_accounts' });
const tx = {
from: connectedAddress,
to: cusdtAddress,
// eslint-disable-next-line
data: exampleContract.approve(
(spender.current as HTMLInputElement).value,
100000000000000000000,
).data,
};
try {
const result = await provider.request<string>({
method: 'cfx_sendTransaction',
params: [tx],
});
console.log(`approve token success: ${result}`);
} catch (e) {
console.log(e);
}
}, [provider, spender]);
const handleTransferTokenFrom = useCallback(async () => {
const [connectedAddress] = await provider.request<string[]>({
method: 'cfx_accounts',
});
const tx = {
from: connectedAddress,
to: cusdtAddress,
// eslint-disable-next-line
data: exampleContract.transferFrom(
(transferFrom.current as HTMLInputElement).value,
(transferTo.current as HTMLInputElement).value,
10000000000000000000,
).data,
};
try {
const result = await provider.request<string>({
method: 'cfx_sendTransaction',
params: [tx],
});
console.log(`transfer from success: ${result}`);
} catch (e) {
console.log(e);
}
}, [provider, transferTo, transferFrom]);
const handlePersoanlSign = useCallback(async () => {
const [connectedAddress] = await provider.request<string[]>({
method: 'cfx_accounts',
});
try {
const result = await provider.request<string>({
method: 'personal_sign',
params: ['personal sign message example', connectedAddress],
});
console.log(`personal sign success: ${result}`);
} catch (e) {
console.log(e);
}
}, [provider]);
const handleSignTypedDataV4 = useCallback(async () => {
const [connectedAddress] = await provider.request<string[]>({
method: 'cfx_accounts',
});
try {
const result = await provider.request<string>({
method: 'cfx_signTypedData_v4',
params: [connectedAddress, JSON.stringify(cfxTypedData)],
});
console.log(`sing typed data v4 success: ${result}`);
} catch (e) {
console.log(e);
}
}, [provider]);
const handleDeployContract = useCallback(async () => {
const [connectedAddress] = await provider.request<string[]>({
method: 'cfx_accounts',
});
const tx = {
from: connectedAddress,
// eslint-disable-next-line
data: exampleContract.constructor('Example', 18, 'EP', 10000).data,
};
try {
const result = await provider.request<string>({
method: 'cfx_sendTransaction',
params: [tx],
});
console.log(`deploy contract success: ${result}`);
} catch (e) {
console.log(e);
}
}, [provider]);
const handleAddToken = useCallback(async () => {
try {
await provider.request({
method: 'wallet_watchAsset',
params: {
type: 'ERC20',
options: {
address: 'cfxtest:acepe88unk7fvs18436178up33hb4zkuf62a9dk1gv',
symbol: 'cUSDT',
decimals: 18,
image:
'https://scan-icons.oss-cn-hongkong.aliyuncs.com/testnet/cfxtest%3Aacepe88unk7fvs18436178up33hb4zkuf62a9dk1gv.png',
},
},
});
console.log('add token success');
} catch (e) {
console.log(e);
}
}, [provider]);
const handleAddNetwork = useCallback(async () => {
try {
await provider.request({
method: 'wallet_addConfluxChain',
params: [
{
chainId: '0x47',
chainName: 'EVM Conflux',
nativeCurrency: {
name: 'Conflux',
symbol: 'CFX',
decimals: 18,
},
rpcUrls: ['https://evmtestnet.confluxrpc.com'],
blockExplorerUrls: ['https://evmtestnet.confluxscan.io'],
},
],
});
console.log('add network success');
} catch (e) {
console.log(e);
}
}, [provider]);
const handleSwitchNetwork = useCallback(async () => {
try {
await provider.request<string>({
method: 'wallet_switchConfluxChain',
params: [{ chainId: '0x1' }],
});
console.log('switch network success');
} catch (e) {
console.log(e);
}
}, [provider]);
useEffect(() => {
if (!provider) return;
init(provider);
provider.on(ProviderEvents.CONNECT, (network) => {
console.log('connected');
setConnected(true);
setChainId(network.chainId);
setNetworkId(network.networkId);
provider
.request<string[]>({
method: 'cfx_accounts',
})
.then((accounts) => setAccounts(accounts))
.catch((e) => console.log(e));
});
provider.on(ProviderEvents.ACCOUNTS_CHANGED, (accounts) => {
setAccounts(accounts);
console.log('cfx accountsChanged', accounts);
});
provider.on(ProviderEvents.CHAIN_CHANGED, (chainId) => {
setChainId(chainId);
setNetworkId(parseInt(chainId, 16).toString(10));
console.log('cfx chainChanged', chainId);
});
provider.on(ProviderEvents.DISCONNECT, () => {
setAccounts([]);
setConnected(false);
});
}, [init, provider]);
return (
<div>
<DAppList dapps={dapps} />
{!provider && (
<a target="_blank" href={'https://www.onekey.so/download/'}>
Install OneKey Extension →
</a>
)}
{provider && (
<div>
<div>
<p>{connected ? 'Wallet is initialized' : 'Wallet is not initialized'}</p>
<p>chainId: {chainId}</p>
<p>networkId: {networkId}</p>
</div>
<div>
<button disabled={accounts.length > 0 || !connected} onClick={handleConnectWallet}>
{accounts.length ? 'connected' : 'connecte wallet'}
</button>
<p>{accounts}</p>
</div>
<div>
<button disabled={accounts.length === 0} onClick={handleSendNativeToken}>
send native token to my self
</button>
</div>
<div>
<input ref={spender} placeholder={'Sepnder Address'} />
<button disabled={accounts.length === 0} onClick={handleApproveToken}>
approve 100 cUDST limit
</button>
</div>
<div>
<input ref={transferFrom} placeholder={'from address'} />
<input ref={transferTo} placeholder={'to address'} />
<button disabled={accounts.length === 0} onClick={handleTransferTokenFrom}>
transfer from
</button>
</div>
<div>
<button disabled={accounts.length === 0} onClick={handlePersoanlSign}>
personal sign
</button>
</div>
<div>
<button disabled={accounts.length === 0} onClick={handleSignTypedDataV4}>
sign typed data v4
</button>
</div>
<div>
<button disabled={accounts.length === 0} onClick={handleDeployContract}>
deploy contract
</button>
</div>
<div>
<button disabled={accounts.length === 0} onClick={handleAddToken}>
add token
</button>
</div>
<div>
<button disabled={accounts.length === 0} onClick={handleAddNetwork}>
add network
</button>
</div>
<div>
<button disabled={accounts.length === 0} onClick={handleSwitchNetwork}>
switch network
</button>
</div>
</div>
)}
</div>
);
}
export default ConfluxExample;
|
import Navbar from "../subComponents/Navbar";
import { useEffect, useState, useRef } from "react";
import { useSelector } from "react-redux";
import AddProduct from "./AddProduct";
import ConfirmDialog from "../subComponents/ConfirmDialog";
import { FaMobile } from "react-icons/fa";
import { FaPencil } from "react-icons/fa6";
import { RiDeleteBin6Fill } from "react-icons/ri";
import { toast } from "react-toastify";
import { DeleteProduct, FetchProducts } from "../../services/productServices";
const Products = () => {
const token =
useSelector((state) => state?.auth?.token) ||
JSON.parse(localStorage.getItem("loginDetails")).token;
const [addForm, setAddForm] = useState(false);
const [editForm, setEditForm] = useState(false);
const [editFormData, setEditFormData] = useState({});
const [productList, setProductList] = useState([]);
const [showConfirm, setShowConfirm] = useState(false);
const [deleteId, setDeleteId] = useState(null);
//=======get all products==========
const getFetchedProducts = async()=>{
const data = await FetchProducts(token);
if (data?.success) {
setProductList(data?.allProducts);
}
};
const handleUpdate = async (product) => {
setEditForm(true);
setEditFormData(product);
};
const handleDelete = async (id) => {
setDeleteId(id);
setShowConfirm(true);
};
const onConfirm = async () => {
const data = await DeleteProduct(deleteId, token);
if (data?.success) {
setShowConfirm(false);
getFetchedProducts();
} else {
toast.error(data?.message);
}
};
const onCancel = () => {
setShowConfirm(false);
};
//fetching data in initial mounting
useEffect(() => {
getFetchedProducts();
}, []);
return (
<div className="relative">
<Navbar />
<div className="w-full max-w-[1000px] bg-gray-600 h-[60px] mx-auto my-10 flex items-center justify-around ">
<FaMobile className="text-5xl text-teal-500 " />
<h1 className="text-xl text-end text-gray-100 font-bold">Products</h1>
<button
className=" p-1 px-3 bg-teal-600 shadow-lg hover:shadow-teal-600/40 text-white font-semibold rounded-lg cursor-pointer"
onClick={() => setAddForm(true)}
>
Add Products
</button>
</div>
{/* add form only display on button click */}
{addForm && (
<AddProduct
handleClose={setAddForm}
title={"Add"}
getFetchedProducts={getFetchedProducts}
/>
)}
{/* Edit form pending */}
{editForm && (
<AddProduct
handleClose={setEditForm}
title={"Edit"}
getFetchedProducts={getFetchedProducts}
data={editFormData}
/>
)}
{/* Table to show all the available products */}
<div className="h-auto overflow-x-auto mx-auto my-10 w-auto sm:w-full max-w-[1000px]">
<table className="min-w-full divide-y shadow-lg bg-white border-collapse sm:w-full w-[100vw]">
<thead>
<tr>
<th scope="col" className="bg-blue-100 border text-left text-xs font-medium text-gray-500 uppercase tracking-wider px-8 py-4">image</th>
<th scope="col" className="bg-blue-100 border text-left text-xs font-medium text-gray-500 uppercase tracking-wider px-8 py-4">name</th>
<th scope="col" className="bg-blue-100 border text-left text-xs font-medium text-gray-500 uppercase tracking-wider px-8 py-4">brand</th>
<th scope="col" className="bg-blue-100 border text-left text-xs font-medium text-gray-500 uppercase tracking-wider px-8 py-4">price</th>
<th scope="col" className="bg-blue-100 border text-left text-xs font-medium text-gray-500 uppercase tracking-wider px-8 py-4">stock</th>
<th scope="col" className="bg-blue-100 border text-left text-xs font-medium text-gray-500 uppercase tracking-wider px-8 py-4">updated by</th>
<th scope="col" className="bg-blue-100 border text-left text-xs font-medium text-gray-500 uppercase tracking-wider px-8 py-4">
Actions
</th>
</tr>
</thead>
{productList.length === 0 ? (
<h1 className="font-medium text-l text-center mx-auto p-5">
No data to show
</h1>
) : (
<tbody className="bg-white divide-y divide-gray-200">
{productList.map((product, index) => {
return (
<tr
key={product._id}
className={`hover:bg-gray-300 focus:bg-gray-300 ${
index % 2 == 0 ? "bg-gray-200" : "bg-gray-50"
}`}
tabIndex="0"
>
<td className="border px-8 py-4 whitespace-nowrap">
<img
className="w-[100px] h-[100px]"
src={product.image}
alt="Product Img"
/>
</td>
<td className="border px-8 py-4 whitespace-nowrap">
{product.name}
</td>
<td className="border px-8 py-4 whitespace-nowrap">
{product.brand}
</td>
<td className="border px-8 py-4 whitespace-nowrap">
{product.price}
</td>
<td className="border px-8 py-4 whitespace-nowrap">
{product.stock}
</td>
<td className="border px-8 py-4 whitespace-nowrap">
{product.updatedBy}
</td>
<td className="border px-8 py-4 whitespace-nowrap">
<div className="flex justify-around">
<FaPencil
className="text-xl hover:text-green-900 text-green-700"
onClick={() => handleUpdate(product)}
/>
<RiDeleteBin6Fill
className="text-xl text-red-700 hover:text-red-900"
onClick={() => handleDelete(product._id)}
/>
</div>
</td>
</tr>
);
})}
</tbody>
)}
</table>
{/* Pagination */}
{/* <div className="mt-4">
<nav className="flex justify-end">
<ul className="pagination">
{Array.from({ length: totalPages }, (_, index) => (
<li key={index} className={index + 1 === currentPage ? 'page-item active' : 'page-item'}>
<button className="page-link" onClick={() => handlePageChange(index + 1)}>
{index + 1}
</button>
</li>
))}
</ul>
</nav>
</div> */}
</div>
{/* cofirm */}
{showConfirm && (
<ConfirmDialog
message={"Are you sure you want to delete this item?"}
onCancel={onCancel}
onConfirm={onConfirm}
/>
)}
</div>
)
}
export default Products
|
<html>
<head>
<meta charset="UTF-8">
<title>출력결과</title>
</head>
<body>
<script>
function solution(str) {
/**
// 배열로 만든다 -> 숫자형으로 변환했을 때 NaN이 아닌 것들만 모은다. -> string으로 만든다.-> 숫자로 만든다.
// number 형태일 때 앞에 있는 0은 자연스럽게 사라진다. parseInt나 Number를 이용하면 된다.
// https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
let answer = Number(str.split('').filter(v => !Number.isNaN(v / 1)).join(''));
/*/
let answer = 0;
for (let l of str) {
if (!isNaN(l)) {
// parseInt나 반복문을 사용하는 게 아닌
// 앞의 0들을 제거하는 방법
answer = answer * 10 + l / 1;
}
}
/**/
return answer;
}
let str = "g0en2T0s8eSoft";
console.log(solution(str));
</script>
</body>
</html>
|
class Traveler {
constructor (name) {
this.name = name
this.amountFood = 1
this.isHealthy = true
}
hunt () {
this.amountFood+= 2
}
eat () {
if (this.amountFood > 0) {
this.amountFood--
} else {
this.amountFood = 0
this.isHealthy = false
}
}
}
class Wagon {
constructor (capacity) {
this.capacity = capacity
this.passengers = new Array
}
getAvailableSeatCount () {
return this.capacity - this.passengers.length
}
join (hero) {
//se tiver espaço adicione
if (this.capacity - this.passengers.length > 0) {
this.passengers.push(hero)
}
}
shouldQuarantine () {
// se tiver um viajante doente return true
for (let i = 0; i < this.passengers.length; i++) {
if (this.passengers[i].isHealthy === false) {
return true
}
}
return false
}
totalFood () {
// retorna o total de comida de todos os ocupantes
let totFood = 0
for (let i = 0; i < this.passengers.length; i++) {
let quantFood = this.passengers[i].amountFood
totFood+=quantFood
}
return totFood
}
}
// Criar uma carroça que comporta 2 pessoas
let wagon = new Wagon(2);
// Criar três viajantes
let henrietta = new Traveler('Henrietta');
let juan = new Traveler('Juan');
let maude = new Traveler('Maude');
console.log(`${wagon.getAvailableSeatCount()} should be 2`);
wagon.join(henrietta);
console.log(`${wagon.getAvailableSeatCount()} should be 1`);
wagon.join(juan);
wagon.join(maude); // Não tem espaço para ela!
console.log(`${wagon.getAvailableSeatCount()} should be 0`);
henrietta.hunt(); // pega mais comida
juan.eat();
juan.eat(); // juan agora está com fome (doente)
console.log(`${wagon.shouldQuarantine()} should be true since juan is sick`);
console.log(`${wagon.totalFood()} should be 3`);
|
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/pagination";
import { Pagination, Autoplay } from "swiper";
import project1 from "../assets/projects/Language_Oasis.png"
import project2 from "../assets/projects/sports_toy.png"
import project3 from "../assets/projects/bengal_cusine.png"
export const Projects = () => {
return (
<section id="projects" className="py-10 text-white w-11/12 mx-auto mt-10">
<div className="text-center ">
<h3 className="text-4xl font-semibold">
My <span className="text-cyan-600">Projects</span>
</h3>
</div>
<br />
<div className="flex lg:w-10/12 gap-6 px-5 mx-auto items-center relative">
<div className="w-full">
<Swiper
slidesPerView={1}
spaceBetween={20}
breakpoints={{
768: {
slidesPerView: 1,
},
}}
loop={true}
autoplay={{
delay: 3000,
}}
pagination={{
clickable: true,
}}
modules={[Pagination, Autoplay]}
>
<SwiperSlide>
<div className="h-fit w-full p-4 bg-slate-700 rounded-xl lg:flex gap-10">
<img src={project1} alt="" className="rounded-lg w-[500px] h-96" />
<div>
<h3 className="text-4xl mb-4">Language Oasis</h3>
<div className="">
<h3 className="text-xl text-cyan-600 font-bold mb-4">Features:</h3>
<ul className="list-disc ml-4 ">
<li>User Login and Register System with Stripe payment gateway implementation</li>
<li>Popular Classes by number of enrollment, Popular Instructors and Select class for future payment.</li>
<li>Dashboard: User Selected Class, User Enrolled Class, User Payment History. Instructors Add New Class, Instructors
Added Classes. Admin Manage Classes, Admin Manage Users</li>
</ul>
<p className="my-4"><span className="text-cyan-600 font-bold">Tools:</span> React, Express.js, MongoDB, Tailwind, React Router, Firebase, Stripe Payment Gateway, Axios, TanStack Query</p>
<div className="flex gap-4">
<a
href="https://language-oasis.web.app/"
target="_blank"
rel="noreferrer"
className="text-cyan-600 bg-gray-800 px-2 py-1 inline-block"
>
Live Site
</a>
<a
href="https://github.com/mirza-mohibul-hasan/language-oasis-client"
target="_blank"
rel="noreferrer"
className="text-cyan-600 bg-gray-800 px-2 py-1 inline-block"
>
Client Repo
</a>
<a href="https://github.com/mirza-mohibul-hasan/language-oasis-server"
target="_blank"
rel="noreferrer"
className="text-cyan-600 bg-gray-800 px-2 py-1 inline-block"
>
Server Repo
</a>
</div>
</div>
</div>
</div>
</SwiperSlide>
<SwiperSlide>
<div className="h-fit w-full p-4 bg-slate-700 rounded-xl lg:flex gap-10">
<img src={project2} alt="" className="rounded-lg w-[500px] h-96" />
<div>
<h3 className="text-4xl mb-4">Sports Toy Zone</h3>
<div className="">
<h3 className="text-xl text-cyan-600 font-bold mb-4">Features:</h3>
<ul className="list-disc ml-4 ">
<li>Toy Gallery with Football, Cricket & Boxing categories, latest collection, and customer reviews.</li>
<li>User Registration, Login (Google or Email/Password).ular Instructors and Select class for future payment.</li>
<li>Toy management (Add, View, Update, Delete).All Toys listing, customer messaging, and user-specific toy tracking.</li>
</ul>
<p className="my-4"><span className="text-cyan-600 font-bold">Tools:</span> React, Express.js, MongoDB, Tailwind, React Router, Firebase</p>
<div className="flex gap-4">
<a
href="https://b7a11-toy-marketplace-4c6e4.web.app/"
target="_blank"
rel="noreferrer"
className="text-cyan-600 bg-gray-800 px-2 py-1 inline-block"
>
Live Site
</a>
<a
href="https://github.com/mirza-mohibul-hasan/sports-toy-zone-client-side"
target="_blank"
rel="noreferrer"
className="text-cyan-600 bg-gray-800 px-2 py-1 inline-block"
>
Client Repo
</a>
<a href="https://github.com/mirza-mohibul-hasan/-sports-toy-zone-server-side"
target="_blank"
rel="noreferrer"
className="text-cyan-600 bg-gray-800 px-2 py-1 inline-block"
>
Server Repo
</a>
</div>
</div>
</div>
</div>
</SwiperSlide>
<SwiperSlide>
<div className="h-fit w-full p-4 bg-slate-700 rounded-xl lg:flex gap-10">
<img src={project3} alt="" className="rounded-lg w-[500px] h-96" />
<div>
<h3 className="text-4xl mb-4">Bengal Cusine</h3>
<div className="">
<h3 className="text-xl text-cyan-600 font-bold mb-4">Features:</h3>
<ul className="list-disc ml-4 ">
<li>Online Recipe Tutorials with chef-specific recipes, user registration, and login options via Github and Google.</li>
<li>User Login using Email and Password for personalized experience, featuring a collection of recipes from various chefs.</li>
<li>TFavorite list functionality to save and access preferred recipes.</li>
</ul>
<p className="my-4"><span className="text-cyan-600 font-bold">Tools:</span>React, Express.js, Tailwind, React Router, Firebase</p>
<div className="flex gap-4">
<a
href="https://b7a10-chef-recipe-hunter-88f79.web.app/"
target="_blank"
rel="noreferrer"
className="text-cyan-600 bg-gray-800 px-2 py-1 inline-block"
>
Live Site
</a>
<a
href="https://github.com/mirza-mohibul-hasan/bengal-cuisine-client"
target="_blank"
rel="noreferrer"
className="text-cyan-600 bg-gray-800 px-2 py-1 inline-block"
>
Client Repo
</a>
<a href="https://github.com/mirza-mohibul-hasan/bengal-cuisine-server"
target="_blank"
rel="noreferrer"
className="text-cyan-600 bg-gray-800 px-2 py-1 inline-block"
>
Server Repo
</a>
</div>
</div>
</div>
</div>
</SwiperSlide>
</Swiper>
</div>
</div>
</section>
);
}
|
<template>
<card style="height: 100%" >
<!-- 主页面数据 -->
<!-- 查询框 -->
<Form ref="findForm" :model="searchData" :label-width="60" inline>
<FormItem label="编号:" prop="id">
<Input v-model="searchData.id" placeholder="请输入编号..." clearable style="width: 190px" />
</FormItem>
<FormItem label="产品名:" prop="name">
<Input v-model="searchData.name" placeholder="请输入产品名..." clearable style="width: 190px" />
</FormItem>
<FormItem label="类型:" prop="type">
<Select v-model="searchData.type" filterable clearable placeholder="请搜索选择产品类型..." style="width:190px">
<Option v-for="itemType in typeList" :value="itemType.id" :key="itemType.id" >{{ itemType.name }}</Option>
</Select>
</FormItem>
<FormItem label="标签:" prop="tags">
<Select v-model="searchDataTags" multiple style="width:190px">
<Option v-for="itemTag in tagList" :value="itemTag.id" :key="itemTag.id">{{ itemTag.name }}</Option>
</Select>
</FormItem>
<FormItem label="状态:" prop="status" >
<Select v-model="searchData.status" clearable style="width:190px">
<Option :value="1">可用</Option>
<Option :value="0">禁用</Option>
</Select>
</FormItem>
<FormItem label="品牌:" prop="brand">
<Input v-model="searchData.brand" placeholder="请输入品牌..." clearable style="width: 190px" />
</FormItem>
<FormItem label="产地:" prop="origin">
<Input v-model="searchData.origin" placeholder="请输入产地..." clearable style="width: 190px" />
</FormItem>
<FormItem>
<Button style="margin-left: 8px" type="primary" ghost @click="findForm">查询</Button>
<Button style="margin-left: 8px" type="warning" ghost @click="handleReset('findForm')">重置</Button>
</FormItem>
</Form>
<!-- 按钮框 -->
<div style="margin: 5px;">
<Button style="margin-right: 3px;" type="success" @click="insertMode = true" icon="md-add">添加</Button>
<Button style="margin-right: 3px;" type="info" @click="updateAction" icon="ios-create">修改</Button>
<Button style="margin-right: 3px;" type="error" @click="deleteAction" icon="ios-trash" >删除</Button>
<Button style="margin-right: 3px;" type="warning" :loading="exportLoading.excel" @click="exportAction" icon="md-download">导出Excel</Button>
<Button style="margin-right: 3px;" type="warning" :loading="exportLoading.csv" @click="getCSVModel" icon="md-download">导出CSV</Button>
<Button style="margin-right: 3px;" type="warning" :loading="exportLoading.template" @click="importTemplateAction" icon="md-download">下载Excel模板</Button>
<Button style="margin-right: 3px;" type="success" @click="getTagModel" icon="md-link">关联标签</Button>
<Button style="margin-right: 3px;" type="success" @click="getGauzeModel" icon="md-link">关联纱网</Button>
<Button style="margin-right: 3px;" type="success" @click="getPartModel" icon="md-link">关联配件</Button>
<Upload style="margin-top: 5px;" action="http://localhost:9090/api/product/import/product?updateSupport=true" :on-success="importSuccess" :on-error="importError">
<Button style="margin-right: 3px;" type="primary" icon="ios-cloud-upload-outline">上传Excel</Button>
</Upload>
</div>
<!-- 数据表格 -->
<Table @on-selection-change="setSelection" :loading="loading" :columns="tableColumns" :data="data" ref="table">
<template slot-scope="{ row, index }" slot="action">
<template v-if="data[index].hasInfo">
<Button type="primary" size="small" style="margin-right: 5px" @click="showParams(index)">View</Button>
<Button type="warning" size="small" style="margin-right: 5px" @click="modifyParams(index)">Update</Button>
</template>
<template v-else>
<Button type="success" size="small" style="margin-right: 5px" @click="addParams(index)">Add</Button>
</template>
</template>
<div style="margin: 10px;overflow: hidden" slot="footer">
<div style="float: right;">
<Page :total="total" :page-size="pageSize" show-total :current="pageIndex" @on-change="changePage" @on-page-size-change='changePageSize'></Page>
</div>
</div>
</Table>
<!-- 弹框 -->
<!-- 添加产品基本信息弹框 -->
<Drawer v-model="insertMode" width="550" :mask-closable="false" :styles="styles">
<div slot="header" style="font-size:14px;font-weight:bold;">
<span>添加新产品</span>
</div>
<Form ref="insertForm" :model="insertData" :rules="submitRules" :label-width="130">
<FormItem label="产品名:" prop="name">
<Input v-model="insertData.name" placeholder="请输入产品名..." clearable style="width: 310px" />
</FormItem>
<FormItem label="类型:" prop="type">
<Select v-model="insertData.type" filterable clearable placeholder="请搜索选择产品类型..." style="width:310px">
<Option v-for="itemType in typeList" :value="itemType.id" :key="itemType.id" >{{ itemType.name }}</Option>
</Select>
</FormItem>
<FormItem label="定价:" prop="price">
<Input v-model="insertData.price" placeholder="请输入定价..." clearable style="width: 310px" />
</FormItem>
<FormItem label="海报图(小):" prop="imagesSmall">
<upload-pic-input :default-images="insertData.imagesSmall" :default-type="imagesUploadIndex.insertProductSmall"
@on-change="handleUpload" width="200px" ref="upload"></upload-pic-input>
</FormItem>
<FormItem label="海报图(大):" prop="imagesDetail">
<upload-pic-input :default-images="insertData.imagesDetail" :default-type="imagesUploadIndex.insertProductDetail"
@on-change="handleUpload" width="200px" ref="upload"></upload-pic-input>
</FormItem>
<FormItem label="状态:" prop="status" >
<Select v-model="insertData.status" clearable style="width:310px">
<Option :value="1">可用</Option>
<Option :value="0">禁用</Option>
</Select>
</FormItem>
<FormItem label="产品简介:" prop="introduce">
<Input type="textarea" :rows="4" v-model="insertData.introduce" placeholder="请输入产品简介..." clearable style="width: 310px" />
</FormItem>
</Form>
<div class="demo-drawer-footer">
<Button style="margin-right: 8px" @click="insertMode = false">取消</Button>
<Button style="margin-right: 8px" type="warning" ghost @click="handleReset('insertForm')">重置</Button>
<Button type="primary" @click="handleSubmit('insertForm')">提交</Button>
</div>
</Drawer>
<!-- 添加产品参数弹框 -->
<Drawer v-model="insertParamsMode" width="550" :mask-closable="false" :styles="styles">
<div slot="header" style="font-size:14px;font-weight:bold;">
<span>添加 <span style="color: red">{{selectProductName}}</span> 产品的产品参数</span>
</div>
<Form ref="insertParamsForm" :model="insertParams" :rules="submitRules" :label-width="130">
<FormItem label="编号" prop="id">
<Input v-model="insertParams.pid" readonly="readonly" style="width:310px" />
</FormItem>
<FormItem label="品牌:" prop="brand">
<Input v-model="insertParams.brand" placeholder="请输入品牌..." clearable style="width: 310px" />
</FormItem>
<FormItem label="材质:" prop="profile">
<Input v-model="insertParams.profile" placeholder="请输入材质..." clearable style="width: 310px" />
</FormItem>
<FormItem label="尺寸:" prop="size">
<Input v-model="insertParams.size" placeholder="请输入尺寸..." clearable style="width: 310px" />
</FormItem>
<FormItem label="玻璃:" prop="glass">
<Input v-model="insertParams.glass" placeholder="请输入玻璃..." clearable style="width: 310px" />
</FormItem>
<FormItem label="颜色:" prop="color">
<Input v-model="insertParams.color" placeholder="请输入颜色..." clearable style="width: 310px" />
</FormItem>
<FormItem label="生产周期:" prop="cycle">
<Input v-model="insertParams.cycle" placeholder="请输入生产周期..." clearable style="width: 310px" />
</FormItem>
<FormItem label="产地:" prop="origin">
<Input v-model="insertParams.origin" placeholder="请输入产地..." clearable style="width: 310px" />
</FormItem>
<FormItem label="状态:" prop="status" >
<Select v-model="insertParams.status" clearable style="width:310px">
<Option :value="1">可用</Option>
<Option :value="0">禁用</Option>
</Select>
</FormItem>
<FormItem label="图片列表:" prop="brand">
<Button style="margin-right: 8px;width: 310px" :type="imageBtn.type" ghost @click="getImageMode">{{imageBtn.value}}</Button>
</FormItem>
</Form>
<div class="demo-drawer-footer">
<Button style="margin-right: 8px" @click="insertParamsMode = false">取消</Button>
<Button style="margin-right: 8px" type="warning" ghost @click="handleReset('insertParamsForm')">重置</Button>
<Button type="primary" @click="handleSubmit('insertParamsForm')">提交</Button>
</div>
</Drawer>
<!-- 修改产品参数弹框 -->
<Drawer v-model="modifyParamsMode" width="550" :mask-closable="false" :styles="styles">
<div slot="header" style="font-size:14px;font-weight:bold;">
<span>修改<span style="color: red">{{selectProductName}}</span>产品的产品参数</span>
</div>
<Form ref="updateParamsForm" :model="updateParams" :rules="submitRules" :label-width="130">
<FormItem label="编号" prop="id">
<Input v-model="updateParams.pid" readonly="readonly" style="width:310px" />
</FormItem>
<FormItem label="品牌:" prop="brand">
<Input v-model="updateParams.brand" placeholder="请输入品牌..." clearable style="width: 310px" />
</FormItem>
<FormItem label="材质:" prop="profile">
<Input v-model="updateParams.profile" placeholder="请输入材质..." clearable style="width: 310px" />
</FormItem>
<FormItem label="尺寸:" prop="size">
<Input v-model="updateParams.size" placeholder="请输入尺寸..." clearable style="width: 310px" />
</FormItem>
<FormItem label="玻璃:" prop="glass">
<Input v-model="updateParams.glass" placeholder="请输入玻璃..." clearable style="width: 310px" />
</FormItem>
<FormItem label="颜色:" prop="color">
<Input v-model="updateParams.color" placeholder="请输入颜色..." clearable style="width: 310px" />
</FormItem>
<FormItem label="生产周期:" prop="cycle">
<Input v-model="updateParams.cycle" placeholder="请输入生产周期..." clearable style="width: 310px" />
</FormItem>
<FormItem label="产地:" prop="origin">
<Input v-model="updateParams.origin" placeholder="请输入产地..." clearable style="width: 310px" />
</FormItem>
<FormItem label="状态:" prop="status" >
<Select v-model="updateParams.status" clearable style="width:310px">
<Option :value="1">可用</Option>
<Option :value="0">禁用</Option>
</Select>
</FormItem>
<FormItem label="图片列表:" prop="brand">
<Button style="margin-right: 8px;width: 310px" :type="imageBtn.type" ghost @click="getImageMode">{{imageBtn.value}}</Button>
</FormItem>
</Form>
<div class="demo-drawer-footer">
<Button style="margin-right: 8px" @click="modifyParamsMode = false">取消</Button>
<Button style="margin-right: 8px" type="warning" ghost @click="handleReset('updateParamsForm')">重置</Button>
<Button type="primary" @click="handleSubmit('updateParamsForm')">提交</Button>
</div>
</Drawer>
<!-- 预览产品参数弹框 -->
<Drawer v-model="showParamsMode" width="550" :styles="styles" :closable="false">
<div slot="header" style="font-size:14px;font-weight:bold;">
<span>具体参数</span>
</div>
<div class="demo-drawer-profile">
<Row style="margin-bottom: 12px;">
<Col span="11" offset="1">
编号: {{selectProductInfo.pid}}
</Col>
<Col span="12">
品牌: {{selectProductInfo.brand}}
</Col>
</Row>
<Row style="margin-bottom: 12px;">
<Col span="11" offset="1">
尺寸: {{selectProductInfo.size}}
</Col>
<Col span="12">
玻璃: {{selectProductInfo.glass}}
</Col>
</Row>
<Row style="margin-bottom: 12px;">
<Col span="11" offset="1">
颜色: {{selectProductInfo.color}}
</Col>
<Col span="12">
生产周期: {{selectProductInfo.cycle}}
</Col>
</Row>
<Row style="margin-bottom: 12px;">
<Col span="11" offset="1">
产地: {{selectProductInfo.origin}}
</Col>
</Row>
<Row style="flex-grow: 1">
<Col span="3" offset="1">
<span>图片列表: </span>
</Col>
<Col span="20" style="height:100%">
<div ref="viewScrollDiv" style="height:100%">
<Scroll :height="viewScrollHeight">
<div v-for="(item, index) in imagesCheckList" :key="index">
<Card dis-hover style="width:90%;margin: 0 auto 20px;" >
<img :src="item.url" alt="无效的图片链接" style="width: 100%;margin: 0 auto;display: block;">
</Card>
</div>
</Scroll>
</div>
</Col>
</Row>
</div>
</Drawer>
<!-- 修改产品基本信息弹框 -->
<Drawer v-model="modifyMode" width="550" :mask-closable="false" :styles="styles">
<div slot="header" style="font-size:14px;font-weight:bold;">
<span>修改产品信息</span>
</div>
<Form ref="modifyFrom" :model="updateData" :rules="submitRules" :label-width="130">
<FormItem label="编号:" prop="id">
<Input v-model="updateData.id" readonly="readonly" clearable style="width: 310px" />
</FormItem>
<FormItem label="产品名:" prop="name">
<Input v-model="updateData.name" placeholder="请输入产品名..." clearable style="width: 310px" />
</FormItem>
<FormItem label="类型:" prop="type">
<Select v-model="updateData.type" filterable clearable placeholder="请搜索选择产品类型..." style="width:310px">
<Option v-for="itemType in typeList" :value="itemType.id" :key="itemType.id" >{{ itemType.name }}</Option>
</Select>
</FormItem>
<FormItem label="定价:" prop="price">
<Input v-model="updateData.price" placeholder="请输入定价..." clearable style="width: 310px" />
</FormItem>
<FormItem label="海报图(小):" prop="imagesSmall">
<upload-pic-input :default-images="updateData.imagesSmall" :default-type="imagesUploadIndex.updateProductSmall"
@on-change="handleUpload" width="200px" ref="upload"></upload-pic-input>
</FormItem>
<FormItem label="海报图(大):" prop="imagesDetail">
<upload-pic-input :default-images="updateData.imagesDetail" :default-type="imagesUploadIndex.updateProductDetail"
@on-change="handleUpload" width="200px" ref="upload"></upload-pic-input>
</FormItem>
<FormItem label="状态:" prop="status" >
<Select v-model="updateData.status" clearable style="width:310px">
<Option :value="1">可用</Option>
<Option :value="0">禁用</Option>
</Select>
</FormItem>
<FormItem label="产品简介:" prop="introduce">
<Input type="textarea" :rows="4" v-model="updateData.introduce" placeholder="请输入产品简介..." clearable style="width: 310px" />
</FormItem>
</Form>
<div class="demo-drawer-footer">
<Button style="margin-right: 8px" @click="modifyMode = false">取消</Button>
<Button style="margin-right: 8px" type="warning" ghost @click="handleReset('modifyFrom')">重置</Button>
<Button type="primary" @click="handleSubmit('modifyFrom')">提交</Button>
</div>
</Drawer>
<!-- 选择图片列表的抽屉弹框 -->
<Drawer v-model="imagesMode" width="500" :mask-closable="false" :styles="styles">
<div slot="header" style="font-size:14px;font-weight:bold;">
<span>点击选择图片</span>
</div>
<div ref="scrollDiv" style="height:100%">
<Scroll :height="scrollHeight" v-if="!spinShow">
<div v-for="(item, index) in imagesList" :key="index" @click="selectImage(item.id)">
<Card dis-hover style="width:90%;margin: 0 auto 20px;" >
<img :src="item.url" alt="无效的图片链接" style="width: 100%;margin: 0 auto;display: block;">
<Spin size="large" fix v-if="item.spinShow">
<Icon type="md-checkmark-circle-outline" size=28 />
<div style="margin-top:5px;"><span style="font-style: italic;">已选</span></div>
</Spin>
</Card>
</div>
</Scroll>
<Spin fix v-if="spinShow">
<Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
<div>Loading</div>
</Spin>
</div>
<div class="demo-drawer-footer">
<Button style="margin-right: 8px" @click="imagesMode = false">取消</Button>
<Button type="primary" @click="submitImages">确定</Button>
</div>
</Drawer>
<!-- csv文件导出弹框 -->
<Modal v-model="model.csv" width="500">
<p slot="header" style="color:#2b85e4;text-align:center">
<Icon type="ios-information-circle"></Icon>
<span>导出CSV文件</span>
</p>
<Form ref="formInline" :model="fileProperty" :rules="submitRules" :label-width="130">
<FormItem label="文件名称:" prop="fileName">
<Poptip placement="top-start" trigger="focus">
<Input v-model="fileProperty.fileName" placeholder="请输入文件名..." clearable style="width: 310px" />
<div slot="content"><span>默认文件名:</span><span style="font-style: italic; color: rgb(194, 79, 74);">产品数据表 </span></div>
</Poptip>
</FormItem>
<FormItem label="数据大小:" prop="size">
<Poptip placement="top-start" trigger="focus">
<Input v-model="fileProperty.size" placeholder="请输入数据大小..." clearable style="width: 310px" />
<div slot="content"><span>总记录数:</span><span style="font-style: italic; color: rgb(194, 79, 74);">{{total}}</span></div>
</Poptip>
</FormItem>
<FormItem label="导出列:" prop="columns">
<CheckboxGroup v-model="checkedList.csv">
<Checkbox v-for="(item,index) in csvList" :label="index" :key="item.key">{{item.title}}</Checkbox>
</CheckboxGroup>
</FormItem>
</Form>
<div slot="footer">
<Button type="success" size="large" long :loading="model.csvLoading" @click="exportCSVFile">导出</Button>
</div>
</Modal>
<!-- 关联标签弹框 -->
<Modal v-model="model.tag" width="400">
<p slot="header" style="color:#2b85e4;text-align:center">
<Icon type="ios-information-circle"></Icon>
<span>选择标签</span>
</p>
<div style="text-align:center">
<CheckboxGroup v-model="checkedList.tag">
<Checkbox v-for="item in tagList" :label="item.id" :key="item.id">{{item.name}}</Checkbox>
</CheckboxGroup>
</div>
<div slot="footer">
<Button type="success" size="large" long :loading="model.tagLoading" @click="connectionTag">关联</Button>
</div>
</Modal>
<!-- 关联纱网弹框 -->
<Modal v-model="model.gauze" width="400">
<p slot="header" style="color:#2b85e4;text-align:center">
<Icon type="ios-information-circle"></Icon>
<span>选择关联的纱网</span>
</p>
<div style="text-align:center">
<CheckboxGroup v-model="checkedList.gauze">
<Checkbox v-for="item in gauzeList" :label="item.id" :key="item.id">{{item.name}}</Checkbox>
</CheckboxGroup>
</div>
<div slot="footer">
<Button type="success" size="large" long :loading="model.gauzeLoading" @click="connectionGauze">关联</Button>
</div>
</Modal>
<!-- 关联标配件弹框 -->
<Modal v-model="model.part" width="400">
<p slot="header" style="color:#2b85e4;text-align:center">
<Icon type="ios-information-circle"></Icon>
<span>选择关联的配件</span>
</p>
<div style="text-align:center">
<CheckboxGroup v-model="checkedList.part">
<Checkbox v-for="item in partList" :label="item.id" :key="item.id">{{item.name}}</Checkbox>
</CheckboxGroup>
</div>
<div slot="footer">
<Button type="success" size="large" long :loading="model.partLoading" @click="connectionPart">关联</Button>
</div>
</Modal>
</card>
</template>
<script>
import {
deleteProductRequest,
exportFile,
findDataActionRequest,
getProductInfoByPid,
getTagListRequest,
getTypeListRequest,
importTemplateFile,
insertParamsRequest,
insertProductRequest,
updateParamsRequest,
updateProductRequest,
connectionTagRequest,
connectionGauzeRequest,
connectionPartRequest,
getCheckedTagRequest,
getCheckedGauzeRequest,
getCheckedPartRequest,
getImagesListRequest
} from '../../api/product/productApi'
import { downloadFile } from '../../api/commonApi'
import uploadPicInput from '../components/upload-pic-input'
import config from '../../config/index'
import _ from 'lodash'
const { pageSize } = config
export default {
components: {
uploadPicInput
},
data () {
return {
typeList: [], // 类型集合
tagList: [], // 标签集合
gauzeList: [], // 纱网数据集合
partList: [], // 配件数据集合
csvList: [], // CSV数据集合
imagesList: [], // 产品图片列表
imagesCheckList: [], // 已选图片列表,后台数据
checkedList: {
tag: [],
gauze: [],
part: [],
csv: [],
image: []
}, // 选中的数据集合
ImageScrollHeight: '650', // 图片滚动框大小
viewScrollHeight: '500',
imageBtn: {
type: 'primary',
value: '选择图片'
},
fileProperty: {
fileName: '',
size: ''
}, // 导出CSV文件属性
checkedCache: {
tag: [],
gauze: [],
part: []
}, // 数据集合的缓存
spinShow: true, // 图片弹框加载显示
insertMode: false, // 添加产品数据弹框
modifyMode: false, // 修改产品数据弹框
insertParamsMode: false, // 添加产品参数数据弹框
modifyParamsMode: false, // 修改产品参数数据弹框
imagesMode: false, // 选择图片的弹框
showParamsMode: false, // 产品参数预览抽屉
loading: true, // 表格数据加载
exportLoading: {
excel: false,
template: false,
csv: false
}, // 导出按钮的加载
model: {
tag: false,
tagLoading: false,
gauze: false,
gauzeLoading: false,
part: false,
partLoading: false,
csv: false,
csvLoading: false
}, // 关联相关的操作弹框
selectProductName: '',
selectProductInfo: {
pid: '',
images: '',
profile: '',
glass: '',
color: '',
cycle: '',
size: '',
origin: '',
brand: ''
},
total: 0,
pageIndex: 1,
pageSize: pageSize,
imagesUploadIndex: {
insertProductSmall: '1',
insertProductDetail: '2',
updateProductSmall: '3',
updateProductDetail: '4'
},
searchDataTags: [],
searchData: {
id: '',
name: '',
type: '',
status: '',
origin: '',
brand: ''
},
insertData: {
name: '',
type: '',
price: '',
imagesSmall: '',
imagesDetail: '',
introduce: '',
status: 1
},
updateData: {
id: '',
name: '',
type: '',
price: '',
imagesSmall: '',
imagesDetail: '',
introduce: '',
status: ''
},
insertParams: {
pid: '',
images: '',
profile: '铝合金',
glass: '7厘',
color: '可定制',
cycle: '3周',
size: '可定制',
origin: '河北涿州',
status: 1,
brand: '德国美金'
},
updateParams: {
pid: '',
images: '',
profile: '',
glass: '',
color: '',
cycle: '',
size: '',
origin: '',
status: '',
brand: ''
},
data: [],
selection: [],
tableColumns: [
{
type: 'selection',
width: 60,
align: 'center'
},
{
title: '编号',
align: 'center',
key: 'id'
},
{
title: '产品名称',
align: 'center',
key: 'name'
},
{
title: '产品类型',
align: 'center',
key: 'type',
render: (h, params) => {
let re = ''
this.typeList.forEach(item => {
if (params.row.type === item.id) {
re = item.name
}
})
return h('div', re)
}
},
{
title: '产品简介',
align: 'center',
key: 'introduce',
tooltip: true
},
{
title: '产品状态',
align: 'center',
key: 'status',
render: (h, params) => {
let re = ''
if (params.row.status === 1) {
re = '可用'
} else if (params.row.status === 0) {
re = '禁用(已删除)'
}
return h('div', re)
}
},
{
title: '创建时间',
align: 'center',
key: 'createtime'
},
{
title: '修改时间',
align: 'center',
key: 'updatetime'
},
{
title: '参数详情',
slot: 'action',
fixed: 'right',
width: 200,
align: 'center'
}
],
submitRules: {
name: [
{ required: true, message: '标签名称不能为空', trigger: 'blur' }
]
},
pStyle: {
fontSize: '16px',
color: 'rgba(0,0,0,0.85)',
lineHeight: '24px',
display: 'block',
marginBottom: '16px',
marginLeft: '10px'
},
styles: {
height: 'calc(100% - 55px)',
overflow: 'auto',
paddingBottom: '53px',
position: 'static'
}
}
},
created () {
this.getTypeList()
this.getTagList()
this.findForm()
},
methods: {
/**
* 统一提交方法,表单验证
* @param name
*/
handleSubmit (name) {
this.$refs[name].validate((valid) => {
if (valid) {
this[name]({})
} else {
this.$Message.error('表单数据验证失败')
}
})
},
/**
* 统一重置方法
* @param name
*/
handleReset (name) {
if (name !== 'findForm') {
this.$refs[name].resetFields()
} else {
// TODO 清空有问题
this.searchDataTags = []
}
},
/**
* 设置表单选中的数据
*/
setSelection (selection) {
this.selection = selection
},
/**
* 上传之后,图片路径赋值方法
* @param image
* @param type
*/
handleUpload (image, type) {
if (type === '1') {
this.insertData.imagesSmall = image
} else if (type === '2') {
this.insertData.imagesDetail = image
} else if (type === '3') {
this.updateData.imagesSmall = image
} else if (type === '4') {
this.updateData.imagesDetail = image
}
},
/**
* 获取全部类型列表
*/
getTypeList () {
getTypeListRequest().then(({ data: { status, msg, data } }) => {
if (status) {
this.typeList = data
} else {
this.$Message.error(msg)
}
})
},
/**
* 获取全部标签
*/
getTagList () {
getTagListRequest().then(({ data: { status, msg, data } }) => {
if (status) {
this.tagList = data
} else {
this.$Message.error(msg)
}
})
},
/**
* 查找表单提交,初始表格数据
*/
findForm () {
this.selection.length = 0
let tags = ''
this.searchDataTags.forEach(item => {
tags = tags + ',' + item
})
let params = {
pageNum: this.pageIndex,
pageSize: this.pageSize,
tags: tags
}
findDataActionRequest({ ...params, ...this.searchData }).then(({ data: { data: trueData } }) => {
let { total, records, current, size } = trueData
records.forEach((item, index) => {
records[index].status = item.status ? 1 : 0
})
this.data = records
this.total = total
this.pageIndex = current
this.pageSize = size
this.loading = false
})
},
/**
* 产品表单提交
*/
insertForm () {
insertProductRequest(this.insertData).then(({ data: { msg, status } }) => {
if (status) {
this.$Message.success(msg)
this.findForm()
this.handleReset('insertForm')
this.insertMode = false
} else {
this.$Message.error(msg)
}
})
},
/**
* 更新产品按钮事件操作
*/
updateAction () {
if (this.selection.length !== 1) {
this.$Message.info('请选择一条数据')
return
}
_.keys(this.updateData).forEach(key => {
this.updateData[key] = this.selection[0][key]
})
this.modifyMode = true
},
/**
* 更新表单的提交处理
*/
modifyFrom () {
updateProductRequest(this.updateData).then(({ data: { msg, status } }) => {
if (status) {
this.$Message.success(msg)
this.findForm()
this.handleReset('modifyFrom')
this.modifyMode = false
} else {
this.$Message.error(msg)
}
})
},
/**
* 删除产品按钮事件操作,以及表单提交
*/
deleteAction () {
if (this.selection.length < 1) {
this.$Message.info('请选择要删除的数据')
return
}
if (!confirm('确定删除选中的数据?')) {
return
}
let ids = []
this.selection.forEach(val => ids.push(val['id']))
deleteProductRequest(ids).then(({ data: { status, msg } }) => {
if (status) {
this.findForm()
this.$Message.success(msg)
} else {
this.$Message.error(msg)
}
})
},
/**
* 设置页面大小操作
* @param pageSize
*/
changePageSize (pageSize) {
this.pageSize = pageSize
this.findForm()
},
/**
* 翻页操作
* @param pageNum
*/
changePage (pageNum) {
this.pageIndex = pageNum
this.findForm()
},
/**
* 查看参数详情操作
* @param index
*/
showParams (index) {
getProductInfoByPid(this.data[index].id).then(({ data: { data, status, msg } }) => {
if (status) {
if (data === null) {
this.$Message.error('该产品未找到详细参数!')
return
}
this.selectProductInfo = data.info
this.imagesCheckList = data.sysImages
this.showParamsMode = true
setTimeout(() => {
this.viewScrollHeight = this.$refs.viewScrollDiv.offsetHeight
}, 1000)
} else {
this.$Message.error('数据查找失败!请联系管理员!' + msg)
}
})
},
/**
* 添加产品参数操作
* @param index
*/
addParams (index) {
this.selectProductName = this.data[index].name
this.insertParams.pid = this.data[index].id
this.insertParamsMode = true
this.imageBtn.type = 'primary'
this.imageBtn.value = '选择图片'
},
/**
* 修改产品参数操作
* @param index
*/
modifyParams (index) {
this.selectProductName = this.data[index].name
this.updateParams.pid = this.data[index].id
getProductInfoByPid(this.data[index].id).then(({ data: { data, status, msg } }) => {
if (status) {
if (data === null) {
this.$Message.error('该产品未找到详细参数!')
return
}
_.keys(this.updateParams).forEach(key => {
if (key === 'status') {
this.updateParams[key] = data.info[key] ? 1 : 0
} else {
this.updateParams[key] = data.info[key]
}
})
this.imageBtn.type = 'warning'
this.imageBtn.value = '选择需要修改的图片'
} else {
this.$Message.error('数据查找失败!请联系管理员!' + msg)
}
})
this.modifyParamsMode = true
},
/**
* 提交添加产品参数请求
*/
insertParamsForm () {
if (this.imageBtn.type === 'primary' || this.imageBtn.type === 'error') {
this.imageBtn.type = 'error'
return
}
insertParamsRequest(this.insertParams).then(({ data: { msg, status } }) => {
if (status) {
this.$Message.success(msg)
this.findForm()
this.handleReset('insertParamsForm')
this.insertParamsMode = false
this.imageBtn.type = 'primary'
this.imageBtn.value = '选择图片'
this.checkedList.image = []
} else {
this.$Message.error(msg)
}
})
},
/**
* 提交修改产品参数请求
*/
updateParamsForm () {
updateParamsRequest(this.updateParams).then(({ data: { msg, status } }) => {
if (status) {
this.$Message.success(msg)
this.findForm()
this.handleReset('updateParamsForm')
this.modifyParamsMode = false
this.imageBtn.type = 'primary'
this.imageBtn.value = '选择图片'
this.checkedList.image = []
} else {
this.$Message.error(msg)
}
})
},
/**
* 导出Excel表格
*/
exportAction () {
this.exportLoading.excel = true
exportFile().then(({ data: { msg, status } }) => {
if (status) {
downloadFile(msg)
} else {
console.log(msg)
}
this.exportLoading.excel = false
})
},
/**
* 下载Excel数据模板
*/
importTemplateAction () {
this.exportLoading.template = true
importTemplateFile().then(({ data: { msg, status } }) => {
if (status) {
downloadFile(msg)
} else {
console.log(msg)
}
this.exportLoading.template = false
})
},
/**
* 导入数据成功
**/
importSuccess () {
this.$Message.success('数据导入成功')
this.findForm()
},
/**
* 导入数据失败
**/
importError () {
this.$Message.error('数据导入失败!请检查格式')
},
getCSVModel () {
this.model.csv = true
this.csvList = this.tableColumns.filter((col, index) => index > 0).filter((col, index) => index < 7)
},
/**
* 导出CSV文件
**/
exportCSVFile () {
this.model.csvLoading = true
if (this.checkedList.csv.length > 0) {
let columns = []
this.checkedList.csv.forEach(item => {
columns.push(this.tableColumns[item + 1])
})
let fileName = this.fileProperty.fileName === '' ? '产品数据表' : this.fileProperty.fileName
let params = {
pageNum: 1,
pageSize: this.fileProperty.size
}
findDataActionRequest({ ...params }).then(({ data: { data: trueData } }) => {
let { records } = trueData
records.forEach((item, index) => {
records[index].status = item.status ? 1 : 0
})
this.$refs.table.exportCsv({
filename: fileName,
columns: columns,
data: records
})
this.model.csvLoading = false
this.model.csv = false
})
} else {
this.$Message.success('请选择需要导出的数据列!!')
}
},
/**
* 弹出标签关联框
**/
getTagModel () {
if (this.selection.length !== 1) {
this.$Message.info('请选择一条数据')
return
}
getCheckedTagRequest(this.selection[0].id).then(({ data: { data, status, msg } }) => {
if (status) {
this.checkedList.tag = []
this.checkedCache.tag = []
if (data != null) {
data.forEach(item => this.checkedList.tag.push(item.id))
this.checkedCache.tag = this.checkedList.tag
}
} else {
this.$Message.error('系统出问题了!' + msg)
}
this.model.tag = true
})
},
/**
* 进行关联
**/
connectionTag () {
this.model.tagLoading = true
let result = this.tool(this.checkedCache.tag, this.checkedList.tag)
if (result.add.length === 0 && result.delete.length === 0) {
return
}
let params = {
productId: this.selection[0].id,
addList: result.add,
deleteList: result.delete
}
connectionTagRequest(params).then(({ data: { status, msg } }) => {
if (status) {
this.$Message.success(msg)
} else {
this.$Message.error(msg)
}
this.model.tagLoading = false
this.model.tag = false
})
},
/**
* 弹出纱网关联框
**/
getGauzeModel () {
if (this.selection.length !== 1) {
this.$Message.info('请选择一条数据')
return
}
getCheckedGauzeRequest(this.selection[0].id).then(({ data: { data, status, msg } }) => {
if (status) {
this.checkedList.gauze = []
this.checkedCache.gauze = []
this.gauzeList = data.gauzes
if (data.checked != null) {
data.checked.forEach(item => this.checkedList.gauze.push(item.id))
this.checkedCache.gauze = this.checkedList.gauze
}
} else {
this.$Message.error('系统出问题了!' + msg)
}
this.model.gauze = true
})
},
/**
* 进行关联
**/
connectionGauze () {
this.model.gauzeLoading = true
let result = this.tool(this.checkedCache.gauze, this.checkedList.gauze)
if (result.add.length === 0 && result.delete.length === 0) {
return
}
let params = {
productId: this.selection[0].id,
addList: result.add,
deleteList: result.delete
}
connectionGauzeRequest(params).then(({ data: { status, msg } }) => {
if (status) {
this.$Message.success(msg)
} else {
this.$Message.error(msg)
}
this.model.gauzeLoading = false
this.model.gauze = false
})
},
/**
* 弹出配件关联框
**/
getPartModel () {
if (this.selection.length !== 1) {
this.$Message.info('请选择一条数据')
return
}
getCheckedPartRequest(this.selection[0].id).then(({ data: { data, status, msg } }) => {
if (status) {
this.checkedList.part = []
this.checkedCache.part = []
this.partList = data.parts
if (data.checked != null) {
data.checked.forEach(item => this.checkedList.part.push(item.id))
this.checkedCache.part = this.checkedList.part
}
} else {
this.$Message.error('系统出问题了!' + msg)
}
this.model.part = true
})
},
/**
* 进行关联
**/
connectionPart () {
this.model.partLoading = true
let result = this.tool(this.checkedCache.part, this.checkedList.part)
if (result.add.length === 0 && result.delete.length === 0) {
return
}
let params = {
productId: this.selection[0].id,
addList: result.add,
deleteList: result.delete
}
connectionPartRequest(params).then(({ data: { status, msg } }) => {
if (status) {
this.$Message.success(msg)
} else {
this.$Message.error(msg)
}
this.model.partLoading = false
this.model.part = false
})
},
/**
* 根据新数组和旧数组找出删除和添加的集合
* @param oldList
* @param newList
* @returns {{add: Array, delete: Array}}
*/
tool (oldList, newList) {
let result = {
add: [],
delete: []
}
oldList.forEach(item => {
if (newList.indexOf(item) === -1) {
result.delete.push(item)
}
})
newList.forEach(item => {
if (oldList.indexOf(item) === -1) {
result.add.push(item)
}
})
return result
},
/**
* 打开图片抽屉
* */
getImageMode () {
this.imagesMode = true
setTimeout(() => {
this.spinShow = false
this.scrollHeight = this.$refs.scrollDiv.offsetHeight
}, 1000)
getImagesListRequest().then(({ data: { data, status, msg } }) => {
if (status) {
if (this.modifyParamsMode) {
let res = this.updateParams.images.split(',')
res.forEach(item => {
this.checkedList.image.push(item * 1)
})
}
if (this.checkedList.image.length > 0) {
data.forEach(item => {
item.spinShow = this.checkedList.image.indexOf(item.id) >= 0
})
} else {
data.forEach(item => {
item.spinShow = false
})
}
this.imagesList = data
} else {
this.$Message.error(msg)
}
})
},
/**
* 提交Image图片信息
*/
submitImages () {
let result = ''
this.checkedList.image.forEach((item, index) => {
if (index === this.checkedList.image.length - 1) {
result += item
} else {
result += item + ','
}
})
this.insertParams.images = result
this.updateParams.images = result
this.imagesMode = false
this.imageBtn.type = 'success'
this.imageBtn.value = '已成功选择图片'
},
/**
* 选择图片的操作
*/
selectImage (id) {
this.imagesList.forEach(item => {
if (item.id === id) {
item.spinShow = !item.spinShow
}
})
let index = this.checkedList.image.indexOf(id)
if (index >= 0) {
this.checkedList.image.splice(index, 1)
} else {
this.checkedList.image.push(id)
}
}
}
}
</script>
<style>
.demo-drawer-footer {
width: 100%;
position: absolute;
bottom: 0;
left: 0;
border-top: 1px solid #e8e8e8;
padding: 10px 16px;
text-align: right;
background: #fff;
}
.demo-spin-icon-load{
animation: ani-demo-spin 1s linear infinite;
}
.demo-drawer-profile{
font-size: 14px;
display:flex;
flex-direction: column;
height:100%;
}
</style>
|
package com.itwill.inheritance05;
import java.util.Random;
import java.util.Scanner;
class T {}
public class InheritanceMain05 {
public static void main(String[] args) {
// java.lang.Object 클래스: 자바의 최상위 클래스.
// 자바의 모든 클래스는 Object를 상속(확장)
// -> Object 클래스의 메서드를 하위 타입 객체에서 사용할 수 있음.
// -> Object 클래스의 메서드들을 하위 클래스에서 재정의(override)할 수 있음
// -> toString(), equals(), hashCode(), ...
T t = new T();
System.out.println(t.getClass()); // 클래스 타입을 리턴
int hash = t.hashCode(); // 해시코드를 리턴하는 메서드
System.out.println(hash + " = " + Integer.toHexString(hash));
System.out.println(t.toString()); // 문자열 타입..
System.out.println(t); // T 타입
// -> System.out.println(Object o) 메서드는 객체의 문자열 표현식을 콘솔에 출력한다.
// -> println() 메서드는 객체가 가지고 있는 toString()의 리턴값을 출력.. 그래서 사실 위의 코드 2줄은 서로 같다.
Random rand = new Random();
System.out.println(rand);
// -> Random 클래스는 toString 메서드를 재정의(override)하지 않았음
Scanner sc = new Scanner(System.in);
System.out.println(sc);
// -> Scanner class는 toString 메서드를 재정의(override)하고 있음
T t2 = new T();
System.out.println(t.equals(t2)); // 두 객체가 같은지를 리턴.
T t3 = t;
System.out.println(t.equals(t3));
// equals method가 재정의(override)된 예
String s1 = new String("java"); // 이렇게도 쓸 수 있음. 근데 이렇게 사용하지 않는게 좋음
String s2 = new String("java");
System.out.println(s1 == s2);
// -> 비교 연산자(==)는 참조변수에 저장된 객체의 참조값을 비교.
System.out.println(s1.equals(s2));
// -> String 클래스에서 equals 메서드는 문자열의 내용이 같으면
//(실제로 생성된 문자열 객체가 다르더라도) true를 리턴하도록 재정의(override)되어 있음.
// -> 두 문자열이 같은 지를 비교할 때는 반드시 equals method를 사용해야 함.
}
}
|
import React from 'react';
import Link from 'next/link';
import { useRecoilState } from 'recoil';
import { selectedProductState } from '@/app/recoil/recoil';
const ProductCard = ({ product }) => {
const [selectedProduct, setSelectedProduct] = useRecoilState(selectedProductState);
const handleClick = () => {
// Set the selected product to Recoil state when the card is clicked
setSelectedProduct(product);
console.log("Clicked");
console.log(selectedProduct);
localStorage.removeItem('single-product');
};
return (
<>
<Link href={`/product/${product.product_category[0].categories_id.slug}/${product.slug}`}>
<div onClick={handleClick}>
<img src={`http://localhost:8055/assets/${product.product_image.id}?width=380&height=400`} alt="Black machined steel pen with hexagonal grip and small white logo at top." className="h-full w-full object-cover object-center group-hover:opacity-75" />
</div>
<div className="px-6 py-4 bg-slate-200">
<h3 className="mt-4 font-semibold text-gray-900 text-lg">
{product.product_name}
<span className="text-xs mb-0 rounded-3xl px-2 py-1 inline-block ml-2">
{product.product_category[0].categories_id.category_name}
</span>
</h3>
<p className="mt-1 text-gray-900 text-lg font-medium">${product.price}</p>
</div>
</Link>
</>
);
};
export default ProductCard;
|
print(__doc__)
# Author: Phil Roth <mr.phil.roth@gmail.com>
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
plt.figure(figsize=(12, 12))
n_samples = 1500
random_state = 170
X, y = make_blobs(n_samples=n_samples, random_state=random_state)
# Incorrect number of clusters
y_pred = KMeans(n_clusters=10, random_state=random_state).fit_predict(X)
plt.subplot(221)
plt.scatter(X[:, 0], X[:, 1], c=y_pred)
plt.title("Incorrect Number of Blobs")
# Anisotropicly distributed data
transformation = [[ 0.60834549, -0.63667341], [-0.40887718, 0.85253229]]
X_aniso = np.dot(X, transformation)
y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X_aniso)
plt.subplot(222)
plt.scatter(X_aniso[:, 0], X_aniso[:, 1], c=y_pred)
plt.title("Anisotropicly Distributed Blobs")
# # Different variance
# X_varied, y_varied = make_blobs(n_samples=n_samples,
# cluster_std=[1.0, 2.5, 0.5],
# random_state=random_state)
# y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X_varied)
# plt.subplot(223)
# plt.scatter(X_varied[:, 0], X_varied[:, 1], c=y_pred)
# plt.title("Unequal Variance")
# Unevenly sized blobs
X_filtered = np.vstack((X[y == 0][:500], X[y == 1][:100], X[y == 2][:10]))
print(X_filtered.shape)
y_pred = KMeans(n_clusters=10, random_state=random_state).fit_predict(X_filtered)
# how to get centroids of clusters
#######################################################################
# I could do some downsampling of the MNIST data into
#
#######################################################################
kmeans = KMeans(n_clusters=20, random_state=random_state).fit(X_filtered)
centroids = kmeans.cluster_centers_
print(centroids)
plt.subplot(224)
plt.scatter(X_filtered[:, 0], X_filtered[:, 1], c=y_pred)
plt.title("Unevenly Sized Blobs")
plt.show()
|
import { addEdge, useReactFlow } from "reactflow";
import type { Connection, Node, Edge, OnConnectStartParams } from "reactflow";
import { toast } from "sonner";
import { Dispatch, SetStateAction, useCallback, useRef } from "react";
import { IndividualNode, NodeData } from "./types";
export function useAddNodeOnEdgeDrop(
setEdges: Dispatch<SetStateAction<Edge<any>[]>>,
setNodes: Dispatch<SetStateAction<Node<NodeData, string | undefined>[]>>
) {
const connectingNodeId = useRef<string | null>(null);
const { screenToFlowPosition } = useReactFlow();
const onConnect = useCallback(
(params: Edge | Connection) => {
// reset the start node on connections
connectingNodeId.current = null;
setEdges((eds) => addEdge(params, eds));
},
[setEdges]
);
const onConnectStart = useCallback(
(
_: React.MouseEvent | React.TouchEvent,
{ nodeId }: OnConnectStartParams
) => {
connectingNodeId.current = nodeId;
},
[]
);
const onConnectEnd = useCallback(
(event: MouseEvent | TouchEvent) => {
if (!connectingNodeId.current || !event.target) return;
// check if the event is a MouseEvent and the target is a pane
if (
!(event instanceof MouseEvent) ||
!(event.target instanceof HTMLDivElement)
)
return;
const targetIsPane = event.target.classList.contains("react-flow__pane");
if (targetIsPane) {
// we need to remove the wrapper bounds, in order to get the correct position
const id = crypto.randomUUID();
const newNode: IndividualNode = {
id,
type: "customNode",
position: screenToFlowPosition({
x: event.clientX,
y: event.clientY,
}),
data: {
name: "",
surname: "",
dateOfBirth: "",
placeOfBirth: "",
gender: "Male",
genderColor: {
Male: "#9ad3f6",
Female: "#f6bfba",
},
},
style: { borderRadius: "4px" },
};
setNodes((nds: Node<NodeData>[]) => nds.concat(newNode));
setEdges((eds) => {
// if we are not connecting a node, we don't need to create an edge
if (!connectingNodeId.current) return eds;
return eds.concat({
id,
source: connectingNodeId.current,
target: id,
});
});
}
},
[setNodes, setEdges, screenToFlowPosition]
);
return {
onConnect,
onConnectStart,
onConnectEnd,
};
}
export function useSaveAndRestore(
setNodes: Dispatch<SetStateAction<Node<NodeData, string | undefined>[]>>,
setEdges: Dispatch<SetStateAction<Edge<any>[]>>
) {
const { setViewport, toObject } = useReactFlow();
const onSave = useCallback(() => {
// creates a JSON-compatible representation of the flow
const flow = toObject();
localStorage.setItem("family-tree", JSON.stringify(flow));
toast.success("Your flow has been saved.");
}, [toObject]);
const onRestore = useCallback(() => {
const restoreFlow = async () => {
const data = localStorage.getItem("family-tree");
const flow = data ? JSON.parse(data) : null;
if (flow) {
const { x = 0, y = 0, zoom = 1 } = flow.viewport;
setNodes(flow.nodes || []);
setEdges(flow.edges || []);
setViewport({ x, y, zoom });
}
};
restoreFlow();
}, [setNodes, setEdges, setViewport]);
return {
onSave,
onRestore,
};
}
export function useAddNewNode(
newNode: Node<any, "customNode" | "customJunction">,
setNodes: Dispatch<SetStateAction<Node<NodeData, string | undefined>[]>>
) {
const onAdd = useCallback(() => {
setNodes((nds) => nds.concat(newNode));
}, [newNode, setNodes]);
return { onAdd };
}
|
import { useContext } from "react";
import CartContext from "../store/CartContaxt.jsx";
import Modal from "./UI/Modal.jsx";
import { currencyFormatter } from "../util/formatting.js";
import Button from "./UI/Button.jsx";
import UserProgressContext from "../store/UserProgressContext.jsx";
import CartItem from "./UI/CartItem.jsx";
export default function Cart(){
const cartCtx = useContext(CartContext);
const userProgressCtx = useContext(UserProgressContext);
const cartTotal =cartCtx.items.reduce((totalPrice,item)=>
totalPrice + item.quantity * item.price
,0);
function handleCloseCart(){
userProgressCtx.hideCart();
}
function handleGoToCheckout(){
userProgressCtx.showCheckout();
}
return(
<Modal className="cart"
onClose={userProgressCtx.progress === 'cart' ? handleCloseCart: null
// as soon as clicking on Go To check out the value is not 'cart' anymore it changes to 'checkout'
//and the model close without changing the value to ''
}
open={userProgressCtx.progress === 'cart'}>
<h2>Your Cart</h2>
<ul>
{cartCtx.items.map((item) => (
<CartItem key={item.id}
name={item.name}
quantity={item.quantity}
price={item.price}
onIncrease={()=>cartCtx.addItem(item)}
onDecrease={()=>cartCtx.removeItem(item.id)} />
))}
</ul>
<p className="cart-total">{currencyFormatter.format(cartTotal)}</p>
<p className="modal-actions">
<Button textOnly onClick={handleCloseCart}>Close</Button>
{cartCtx.items.length > 0 && (
<Button onClick={handleGoToCheckout}>Go To Checkout</Button>
)}
</p>
</Modal>
)
}
|
import Popup from './Popup.js'
export default class PopupWithForm extends Popup {
constructor(popupSelector, submitCallback ) {
super(popupSelector)
this._submitCallback = submitCallback
this._form = this._popup.querySelector('.popup__form')
this._inputList = this._form.querySelectorAll('.popup__input')
}
_getInputValues() {
this._inputValues = {}
this._inputList.forEach((input) => {
this._inputValues[input.name] = input.value
})
return this._inputValues
}
setInputValues(data) {
this._inputList.forEach((input) => {
input.value = data[input.name]
})
}
open() {
super.open()
}
close() {
super.close()
this._form.reset()
}
setEventListeners() {
super.setEventListeners()
this._form.addEventListener('submit', (evt) => {
evt.preventDefault()
this._submitCallback(this._getInputValues())
})
}
}
|
package br.com.phricardo.mockecomm.exceptions;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import java.time.LocalDateTime;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
@RequiredArgsConstructor
public class GlobalExceptionHandler {
private static final String CONTENT_TYPE = "Content-Type";
private static final String APPLICATION_JSON_CHARSET_UTF_8 = "application/json; charset=utf-8";
@ExceptionHandler(NotFoundException.class)
public HttpEntity<?> handleNotFoundException(final NotFoundException ex) {
final HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add(CONTENT_TYPE, APPLICATION_JSON_CHARSET_UTF_8);
return new ResponseEntity<>(createErrorPayload(ex), responseHeaders, NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public HttpEntity<?> handleGenericException(final Exception ex) {
log.debug("An internal server error occurred", ex);
final HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add(CONTENT_TYPE, APPLICATION_JSON_CHARSET_UTF_8);
return new ResponseEntity<>(createErrorPayload(ex), responseHeaders, INTERNAL_SERVER_ERROR);
}
private ErrorPayload createErrorPayload(final Exception ex) {
return new ErrorPayload(ex.getLocalizedMessage(), LocalDateTime.now());
}
}
|
import { createContext, ReactNode, useContext, useEffect } from "react";
import { NavigateFunction, useLocation, useNavigate } from "react-router-dom";
import { api } from "../services/api";
import { toast } from 'react-toastify';
import { useState } from "react";
import { iUserTechs, TechContext } from "./techContext";
import { iUserRegister } from "../pages/Register";
import { iUserLogin } from "../pages/Login";
import axios from "axios";
interface iUserContextProvider{
logarApi: (data: iUserLogin) => void,
setRegister: (data : iUserRegister ) => void,
loading: boolean,
user: iUser | null, //PODE SER MOTIVO DE ERRO!
OpenModal: boolean
setOpenModal: Function
setLoading: Function
setUser: Function
navigate: NavigateFunction
}
interface iUserContextProps{
children: ReactNode
}
export interface iUser{
id: string,
email:string,
name:string,
bio:string,
contact:string,
course_module: string,
techs: iUserTechs[]
}
interface iLoginAdd{
token: string,
user: iUser
}
export const UserContext = createContext({} as iUserContextProvider)
export function UserProvider({children} : iUserContextProps){
const navigate = useNavigate()
const [user,setUser] = useState<iUser | null>(null)
const [loading, setLoading] = useState(true)
const {setTechList} = useContext(TechContext)
const [OpenModal, setOpenModal] = useState(false)
const location = useLocation()
async function logarApi(data : iUserLogin){
try{
const response = await api.post<iLoginAdd>('/sessions', data)
const {user: userResponse, token} = response.data
setUser(userResponse)
setTechList(userResponse.techs)
localStorage.setItem('@Token', token)
toast.success('Usuario Logado com sucesso!', {
theme:'dark',
autoClose: 2500,
})
const toNavigate = location.state?.from?.pathname || 'dashboard'
navigate(toNavigate, {replace: true})
} catch (error){
if(axios.isAxiosError(error))
toast.error(`${error.message}`, {
theme:'dark',
autoClose: 1500,
})
}
setLoading(false)
}
function setRegister(data : iUserRegister ){
api.post('/users', {...data})
.then(response => {
toast.success('Cadastro Feito com sucesso!', {
theme: 'dark',
autoClose: 1500,
})
navigate('/')
})
.catch(error => {
if(axios.isAxiosError(error))
toast.error(`${error.message}`, {
theme:'dark',
autoClose: 1500,
})
})
}
useEffect(() => {
const token = localStorage.getItem('@Token')
function IsLogged(){
if(token){
navigate('/dashboard')
}
}
IsLogged()
}, [])
useEffect(() => {
async function loadUser(){
const token = localStorage.getItem('@Token')
if(token){
try{
api.defaults.headers.authorization = `Bearer ${token}`
const {data} = await api.get<iUser>('/profile')
setUser(data)
}catch(error){
if(axios.isAxiosError(error))
toast.error(`${error.message}`, {
theme:'dark',
autoClose: 1500,
})
navigate('/')
}
setLoading(false)
}
}
loadUser()
}, [])
return(
<UserContext.Provider value={{logarApi,setRegister,OpenModal,setOpenModal,user,loading,setLoading,setUser,navigate}}>
{children}
</UserContext.Provider>
)
}
export function useUserContext(){
const context = useContext(UserContext)
return context
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.