text
stringlengths 184
4.48M
|
---|
using NauticalCatchChallenge.Core.Contracts;
using NauticalCatchChallenge.Models;
using NauticalCatchChallenge.Models.Contracts;
using NauticalCatchChallenge.Repositories;
using NauticalCatchChallenge.Utilities.Messages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
namespace NauticalCatchChallenge.Core
{
public class Controller : IController
{
private readonly DiverRepository divers;
private readonly FishRepository fishes;
public Controller()
{
divers = new DiverRepository();
fishes = new FishRepository();
}
public string ChaseFish(string diverName, string fishName, bool isLucky)
{
IDiver diver = divers.GetModel(diverName);
if (diver == null)
{
return string.Format(OutputMessages.DiverNotFound, divers.GetType().Name, diverName);
}
IFish fish = fishes.GetModel(fishName);
if (fish == null)
{
return string.Format(OutputMessages.FishNotAllowed, fishName);
}
if (diver.HasHealthIssues)
{
return string.Format(OutputMessages.DiverHealthCheck, diverName);
}
if (diver.OxygenLevel < fish.TimeToCatch)
{
diver.Miss(fish.TimeToCatch);
if (diver.OxygenLevel <= 0)
{
diver.UpdateHealthStatus();
}
return string.Format(OutputMessages.DiverMisses, diverName, fishName);
}
else if (diver.OxygenLevel == fish.TimeToCatch)
{
if (isLucky)
{
diver.Hit(fish);
diver.UpdateHealthStatus();
return string.Format(OutputMessages.DiverHitsFish, diverName, fish.Points, fishName);
}
else
{
diver.Miss(fish.TimeToCatch);
if (diver.OxygenLevel <= 0)
{
diver.UpdateHealthStatus();
}
return string.Format(OutputMessages.DiverMisses, diverName, fishName);
}
}
else
{
diver.Hit(fish);
return string.Format(OutputMessages.DiverHitsFish, diverName, fish.Points, fishName);
}
}
public string CompetitionStatistics()
{
var arrangedDivers = divers.Models
.Where(d => !d.HasHealthIssues)
.OrderByDescending(d => d.CompetitionPoints)
.ThenByDescending(d => d.Catch.Count)
.ThenBy(d => d.Name);
StringBuilder sb = new StringBuilder();
sb.AppendLine("**Nautical-Catch-Challenge**");
foreach (var diver in arrangedDivers)
{
sb.AppendLine(diver.ToString());
}
return sb.ToString().TrimEnd();
}
public string DiveIntoCompetition(string diverType, string diverName)
{
IDiver diver = divers.GetModel(diverName);
if (diver != null)
{
return string.Format(OutputMessages.DiverNameDuplication, diverName, divers.GetType().Name);
}
else
{
if (diverType == nameof(FreeDiver))
{
diver = new FreeDiver(diverName);
}
else if (diverType == nameof(ScubaDiver))
{
diver = new ScubaDiver(diverName);
}
else
{
return string.Format(OutputMessages.DiverTypeNotPresented, diverType);
}
divers.AddModel(diver);
return string.Format(OutputMessages.DiverRegistered, diverName, divers.GetType().Name);
}
}
public string DiverCatchReport(string diverName)
{
IDiver diver = divers.GetModel(diverName);
if (diver == null)
{
return string.Format(OutputMessages.DiverNotFound, divers.GetType().Name, diverName);
}
StringBuilder sb = new StringBuilder();
sb.AppendLine(diver.ToString());
sb.AppendLine("Catch Report:");
foreach (var fish in diver.Catch)
{
IFish currentFish = fishes.GetModel(fish);
sb.AppendLine(currentFish.ToString());
}
return sb.ToString().TrimEnd();
}
public string HealthRecovery()
{
int count = 0;
foreach (var diver in divers.Models)
{
if (diver.HasHealthIssues)
{
diver.UpdateHealthStatus();
diver.RenewOxy();
count++;
}
}
return string.Format(OutputMessages.DiversRecovered, count);
}
public string SwimIntoCompetition(string fishType, string fishName, double points)
{
IFish fish = fishes.GetModel(fishName);
if (fish != null)
{
return string.Format(OutputMessages.FishNameDuplication, fishName, fishes.GetType().Name);
}
else
{
if (fishType == nameof(ReefFish))
{
fish = new ReefFish(fishName, points);
}
else if (fishType == nameof(PredatoryFish))
{
fish = new PredatoryFish(fishName, points);
}
else if (fishType == nameof(DeepSeaFish))
{
fish = new DeepSeaFish(fishName, points);
}
else
{
return string.Format(OutputMessages.FishTypeNotPresented, fishType);
}
fishes.AddModel(fish);
return string.Format(OutputMessages.FishCreated, fishName);
}
}
}
}
|
import * as React from "react";
import { TrEditorCell } from "../TrEditorCell";
import { Dev } from "../models/Dev";
import { EditableTrProps } from "./props";
import { EditableTrState } from "./state";
export class EditableTr extends React.Component<EditableTrProps, EditableTrState> {
constructor(props: EditableTrProps) {
super(props);
this.handleDevNameChange = this.handleDevNameChange.bind(this);
this.view = this.view.bind(this);
this.edit = this.edit.bind(this);
this.delete = this.delete.bind(this);
this.state = {
dev: props.dev
}
}
handleDevNameChange(event) {
const newDev: Dev = {
id: this.state.dev.id,
firstName: event.target.value,
lastName: this.props.dev.lastName
}
this.setState({ dev: newDev });
}
view() {
this.props.view(this.props.dev.id);
}
edit() {
this.props.edit(this.state.dev);
}
delete() {
this.props.delete(this.props.dev.id);
}
render() {
return <tr>
<td>{this.props.dev.id}</td>
<td>
<input
type="text"
value={this.state.dev.firstName}
onChange={this.handleDevNameChange}
/>
</td>
<TrEditorCell
view={this.view}
edit={this.edit}
delete={this.delete}
/>
</tr>
}
}
|
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
require('dotenv').config();
let Schema = mongoose.Schema;
let userSchema = new Schema({
userName: {
type: String,
unique: true,
},
password: String,
email: String,
loginHistory: [{
dateTime: Date,
userAgent: String
}]
});
let User;
function initialize() {
return new Promise(function (resolve, reject) {
let db = mongoose.createConnection(process.env.MONGODB);
db.on('error', (err)=>{
reject(err); // reject the promise with the provided error
});
db.once('open', ()=>{
User = db.model("users", userSchema);
resolve();
});
});
}
function registerUser(userData) {
return new Promise((resolve, reject) => {
if (userData.password !== userData.password2) {
return reject("Passwords do not match");
}
// Hash the password
bcrypt.hash(userData.password, 10)
.then(hash => {
// Replace userData.password with the hashed password
userData.password = hash;
// Create a new User instance with the updated userData
let newUser = new User(userData);
// Save the user to the database
newUser.save()
.then(() => {
resolve();
})
.catch(err => {
if (err.code === 11000) {
reject("User Name already taken");
} else {
reject(`There was an error creating the user: ${err}`);
}
});
})
.catch(err => {
// If there's an error during password hashing, reject with a specific message
reject("There was an error encrypting the password");
});
});
}
function checkUser(userData) {
return new Promise((resolve, reject) => {
// Find user by userName
User.find({ userName: userData.userName })
.then(users => {
// Check if the user was found
if (users.length === 0) {
return reject(`Unable to find user: ${userData.userName}`);
}
// Get the first user found (there should only be one)
let user = users[0];
// Compare the entered password with the hashed password from the database
bcrypt.compare(userData.password, user.password)
.then(result => {
if (!result) {
return reject(`Incorrect Password for user: ${userData.userName}`);
}
// If passwords match, update login history
if (user.loginHistory.length === 8) {
user.loginHistory.pop();
}
user.loginHistory.unshift({
dateTime: (new Date()).toString(),
userAgent: userData.userAgent
});
// Update user login history in the database
User.updateOne({ userName: user.userName }, { $set: { loginHistory: user.loginHistory } })
.then(() => {
resolve(user);
})
.catch(err => {
reject(`There was an error verifying the user: ${err}`);
});
})
.catch(err => {
// Handle error during password comparison
reject(`There was an error verifying the user: ${err}`);
});
})
.catch(() => {
// Handle error during user search
reject(`Unable to find user: ${userData.userName}`);
});
});
}
module.exports = { initialize, checkUser, registerUser }
|
//38a1108d19f54a1fab115779487fbbcea3ae1843
//c_to_f
//multiply by 1.8 and add 32
let c_to_f = (temp: float) : float => {
((temp *. 1.8) +. 32.);
};
//split tip
//inside of a switch statement you use when
//make a case for if the number is negative
//price is the amount the meal cost and n is the number of ways it needs to be split
let split_tip = ((price: float), (n: int)) : option(float) => {
switch (price, n){
|(price, n) when (price > 0.) && (n > 1) => Some((price +. (price *. 0.2))/. float_of_int(n));
|_ => None;
};
};
//triangle area
let triangle_area = ((s1: float), (s2: float), (s3: float)) : option(float) => {
let s = (s1 +. s2 +. s3)/.2.;
let area = sqrt(s*.(s-.s1)*.(s-.s2)*.(s-.s3));
switch(s1, s2, s3){
|(s1, s2, s3) when (s1 +. s2 > s3) && (s1 +. s3 > s2) && (s3 +. s2 > s1) => Some(area);
|_ => None;
};
};
//repeat
let rec repeat = ((f: 'a => 'a), (arg: 'a), (n: int)) : 'a => {
//let arg = int_of_string(read_line());
//let f = arg + (arg + 1);
switch(n){
|0 => arg;
|_ => repeat(f, f(arg), n-1);
}
};
//list length
let rec list_length = (l: list('a)) : int => {
switch(l){
|[] => 0;
|[_hd, ...tl] => 1 + list_length(tl);
}
};
|
# Simple inheritance - Relations between classes
# Association - uses, Aggregation - has
# Composition - Owns, Inheritance - Is a
#
# Inheritance vs Composition
#
# Main class (Person)
# -> super class, base class, parent class
# Child classes (Client)
# -> sub class, child class, derived class
class Person:
cpf = '1234'
def __init__(self, name, surname):
self.name = name
self.surname = surname
def speak_class_name(self):
print('Class PERSON')
print(self.name, self.surname, self.__class__.__name__)
class Person(Person):
def speak_class_name(self):
print("YEAH, I didn't even leave the CLIENT class")
print(self.name, self.surname, self.__class__.__name__)
class Student(Person):
cpf = 'student cpf'
...
c1 = Person('Luiz', 'Otávio')
c1.speak_class_name()
a1 = Student('Maria', 'Helena')
a1.speak_class_name()
print(a1.cpf)
# help(Client)
|
package edu.uga.cs.shoppingapp.Dialogs;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import edu.uga.cs.shoppingapp.Item.Item;
import edu.uga.cs.shoppingapp.R;
// This is a DialogFragment to handle edits to a item.
// The edits are: updates and deletions of existing items.
public class EditItemDialogFragment extends DialogFragment {
// indicate the type of an edit
public static final int SAVE = 1; // update an existing item
public static final int DELETE = 2; // delete an existing item
public static final int ADD = 3; // add an existing item to cart
private EditText itemView;
private Button btn;
int position; // the position of the edited item on the list of items
String item;
String key;
String userEmail;
String buyer;
private boolean textChanged = false;
FragmentManager frag;
// A callback listener interface to finish up the editing of a item
// ReviewItemActivity implements this listener interface, as it will
// need to update the list of JobLeads and also update the RecyclerAdapter to reflect the
// changes.
public interface EditItemDialogListener {
void updateItem(int position, Item item, int action);
}
public static EditItemDialogFragment newInstance(int position, String key, String item, String userEmail, String buyer) {
EditItemDialogFragment dialog = new EditItemDialogFragment();
// Supply item values as an argument.
Bundle args = new Bundle();
args.putString( "key", key );
args.putInt( "position", position );
args.putString("item", item);
args.putString("userEmail", userEmail);
// args.putString("buyer", buyer);
dialog.setArguments(args);
return dialog;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState ) {
key = getArguments().getString( "key" );
position = getArguments().getInt( "position" );
item = getArguments().getString( "item" );
userEmail = getArguments().getString("userEmail");
// buyer = getArguments().getString("buyer");
frag = getParentFragmentManager();
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate( R.layout.edit_item_dialog, getActivity().findViewById( R.id.root ) );
itemView = layout.findViewById(R.id.ItemText);
btn = layout.findViewById(R.id.button4);
// Pre-fill the edit texts with the current values for this item.
// The user will be able to modify them.
itemView.setText( item );
AlertDialog.Builder builder = new AlertDialog.Builder( getActivity(), R.style.AlertDialogStyle );
builder.setView(layout);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String item = itemView.getText().toString();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
buyer = user.getEmail();
Item dbItem = new Item(item, 0.0, userEmail, null);
dbItem.setKey( key );
// get the Activity's listener to add the new item
EditItemDialogListener listener = (EditItemDialogFragment.EditItemDialogListener) getParentFragment();
listener.updateItem( position, dbItem, ADD);
// close the dialog
dismiss();
}
});
// Set the title of the AlertDialog
builder.setTitle( "Edit Item" );
// The Cancel button handler
builder.setNegativeButton( android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
// close the dialog
dialog.dismiss();
}
});
builder.setPositiveButton("SAVE", new SaveButtonClickListener() );
// The Delete button handler
builder.setNeutralButton( "DELETE", new DeleteButtonClickListener() );
// Create the AlertDialog and show it
return builder.create();
}
private class SaveButtonClickListener implements DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface dialog, int which) {
String item = itemView.getText().toString();
Item dbItem = new Item(item, 0.0, userEmail, null);
dbItem.setKey( key );
// get the Activity's listener to add the new item
EditItemDialogListener listener = (EditItemDialogFragment.EditItemDialogListener) getParentFragment();
listener.updateItem(position, dbItem, SAVE);
// close the dialog
dismiss();
}
}
private class DeleteButtonClickListener implements DialogInterface.OnClickListener {
@Override
public void onClick( DialogInterface dialog, int which ) {
Item delItem = new Item(item, 0.0, userEmail, null);
delItem.setKey( key );
Log.d("Edit Item", String.valueOf(frag));
// get the Activity's listener to add the new item
EditItemDialogFragment.EditItemDialogListener listener = (EditItemDialogFragment.EditItemDialogListener) getParentFragment(); // add the new job lead
listener.updateItem( position, delItem, DELETE );
// close the dialog
dismiss();
}
}
}
|
%% OpenFOAM Wall Shear Stress Calculations
clear;
%% Initializing File Names
% Replace with your own file path for this data.
% Square Data
file_name1 = "C:\Users\Benjamin Tan\Desktop\Courses\COE347\OpenFOAM\square_data\Data1_RE10";
file_name2 = "C:\Users\Benjamin Tan\Desktop\Courses\COE347\OpenFOAM\square_data\Data2_RE100";
file_name3 = "C:\Users\Benjamin Tan\Desktop\Courses\COE347\OpenFOAM\square_data\Data3_RE250";
file_name4 = "C:\Users\Benjamin Tan\Desktop\Courses\COE347\OpenFOAM\square_data\Data4_RE500";
% Shallow Data
file_name5 = "C:\Users\Benjamin Tan\Desktop\Courses\COE347\OpenFOAM\shallow_data\shallowRe10_data";
file_name6 = "C:\Users\Benjamin Tan\Desktop\Courses\COE347\OpenFOAM\shallow_data\shallowRe50_data";
file_name7 = "C:\Users\Benjamin Tan\Desktop\Courses\COE347\OpenFOAM\shallow_data\shallowRe100_data";
file_name8 = "C:\Users\Benjamin Tan\Desktop\Courses\COE347\OpenFOAM\shallow_data\shallowRe250_data";
file_name9 = "C:\Users\Benjamin Tan\Desktop\Courses\COE347\OpenFOAM\shallow_data\shallowRe500_data";
% Tall Data
file_name10 = "C:\Users\Benjamin Tan\Desktop\Courses\COE347\OpenFOAM\tall_data\tallRe10_data";
file_name11 = "C:\Users\Benjamin Tan\Desktop\Courses\COE347\OpenFOAM\tall_data\tallRe50_data";
file_name12 = "C:\Users\Benjamin Tan\Desktop\Courses\COE347\OpenFOAM\tall_data\tallRe100_data";
file_name13 = "C:\Users\Benjamin Tan\Desktop\Courses\COE347\OpenFOAM\tall_data\tallRe250_data";
file_name14 = "C:\Users\Benjamin Tan\Desktop\Courses\COE347\OpenFOAM\tall_data\tallRe500_data";
%% Function Calls
% Square
[u_x1, u_y1, ~, dp_y1, F1, ~] = GridXY(file_name1, 81, 0.1, 0.1);
[u_x2, u_y2, ~, dp_y2, F2, ~] = GridXY(file_name2, 81, 0.1, 0.1);
[u_x3, u_y3, ~, dp_y3, F3, ~] = GridXY(file_name3, 81, 0.1, 0.1);
[u_x4, u_y4, ~, dp_y4, F4, ~] = GridXY(file_name4, 100, 0.1, 0.1);
% [x_x, p_x, dp_x, dUx] = DifferentiateGridX(u_x);
% [x_y, p_y, dp_y, dUy] = DifferentiateGridY(u_x);
% Shallow
[u_x5, u_y5, ~, dp_y5, F5, ~] = GridXY(file_name5, 81, 0.2, 0.1);
[u_x6, u_y6, ~, dp_y6, F6, ~] = GridXY(file_name6, 81, 0.2, 0.1);
[u_x7, u_y7, ~, dp_y7, F7, ~] = GridXY(file_name7, 81, 0.2, 0.1);
[u_x8, u_y8, ~, dp_y8, F8, ~] = GridXY(file_name8, 81, 0.2, 0.1);
[u_x9, u_y9, ~, dp_y9, F9, ~] = GridXY(file_name9, 81, 0.2, 0.1);
% Tall
[u_x10, u_y10, ~, dp_y10, F10, ~] = GridXY(file_name10, 81, 0.1, 0.2);
[u_x11, u_y11, ~, dp_y11, F11, ~] = GridXY(file_name11, 81, 0.1, 0.2);
[u_x12, u_y12, ~, dp_y12, F12, ~] = GridXY(file_name12, 81, 0.1, 0.2);
[u_x13, u_y13, ~, dp_y13, F13, ~] = GridXY(file_name13, 81, 0.1, 0.2);
[u_x14, u_y14, ~, dp_y14, F14, ~] = GridXY(file_name14, 81, 0.1, 0.2);
%% Generates figures.
% Define x and y values.
x81 = linspace(0, 0.1, 81);
y81 = linspace(0, 0.1, 81);
x81s = linspace(0, 0.2, 81);
y81s = linspace(0, 0.1, 81);
x100 = linspace(0, 0.1, 100);
y100 = linspace(0, 0.1, 100);
x81t = linspace(0, 0.1, 81);
y81t = linspace(0, 0.2, 81);
%% Square
% % Contour Plots of Velocity
% figure;
% contour(x100, y100, u_x4);
% title('Plot of u');
% xlabel('x-distance (m)');
% ylabel('y-distace (m)');
%
% figure;
% contour(x100, y100, u_y4);
% title('Plot of v');
% xlabel('x-distance (m)');
% ylabel('y-distance (m)');
% Shear Force Graphs
figure;
plot(x81, dp_y1);
hold on;
plot(x81, dp_y2);
hold on;
plot(x81, dp_y3);
hold on;
plot(x100, dp_y4);
hold on;
title('Plot of Shear Stress on Boundary');
xlabel('x-distance (m)');
ylabel('Tal (a.u.)');
hold off;
legend('Re = 10','Re = 100', 'Re = 250', 'Re = 500');
% Non-Dimensional Force Graphs
F = [F1, F2, F3, F4];
Re = [10, 100, 250, 500];
figure;
for i = 1:size(Re, 2)
scatter(Re(i), F(i));
hold on;
end
plot(Re, F);
title('Plot of Non-Dimensional Force Over Reynolds Number');
legend('Re = 10', 'Re = 100', 'Re = 250', 'Re = 500');
xlabel('Reynolds Number');
ylabel('Intensity (a.u.)');
%% Shallow
F = [F5, F6, F7, F8, F9];
Re = [10, 50, 100, 250, 500];
% Shear Stress Graphs
figure;
plot(x81s, dp_y5);
hold on;
plot(x81s, dp_y6);
hold on;
plot(x81s, dp_y7);
hold on;
plot(x81s, dp_y8);
hold on;
plot(x81s, dp_y9);
hold on;
title('Plot of Shear Stress on Boundary (Shallow 0.2 x 0.1 m)');
xlabel('x-distance (m)');
ylabel('Tal (a.u.)');
hold off;
legend('Re = 10', 'Re = 50', 'Re = 100', 'Re = 250', 'Re = 500');
% Non-Dimensional Force Graphs
figure;
for i = 1:size(Re, 2)
scatter(Re(i), F(i));
hold on;
end
plot(Re, F);
title('Plot of Non-Dimensional Force Over Reynolds Number (Shallow 0.2 x 0.1 m)');
legend('Re = 10', 'Re = 50', 'Re = 100', 'Re = 250', 'Re = 500');
xlabel('Reynolds Number');
ylabel('Intensity (a.u.)');
%% Tall
F = [F10, F11, F12, F13, F14];
Re = [10, 50, 100, 250, 500];
figure;
plot(x81, dp_y10);
hold on;
plot(x81, dp_y11);
hold on;
plot(x81, dp_y12);
hold on;
plot(x81, dp_y13);
hold on;
plot(x81, dp_y14);
hold on;
title('Plot of Shear Stress on Boundary (Tall 0.1 x 0.2 m)');
xlabel('x-distance (m)');
ylabel('Tal (a.u.)');
hold off;
legend('Re = 10', 'Re = 50', 'Re = 100', 'Re = 250', 'Re = 500');
% Non-Dimensional Force Graphs
figure;
for i = 1:size(Re, 2)
scatter(Re(i), F(i));
hold on;
end
plot(Re, F);
title('Plot of Non-Dimensional Force Over Reynolds Number (Tall 0.1 x 0.2 m)');
legend('Re = 10', 'Re = 50', 'Re = 100', 'Re = 250', 'Re = 500');
xlabel('Reynolds Number');
ylabel('Intensity (a.u.)');
% Contour Plots of Velocity
figure;
contour(x81, y81, u_y1);
title('Plot of uy for Square Re = 10');
xlabel('x-distance (m)');
ylabel('y-distace (m)');
figure;
contour(x81s, y81s, u_y5);
title('Plot of uy for Shallow Re = 10');
xlabel('x-distance (m)');
ylabel('y-distace (m)');
figure;
contour(x81t, y81t, u_y10);
title('Plot of uy for Tall Re = 10');
xlabel('x-distance (m)');
ylabel('y-distace (m)');
% % Plotting the polynomial generated by the DifferentiateGridX function.
% for i = 1:21
% figure;
% plot(x_x, polyval(p_x(:,i), x_x));
% strTitle = ["Polynomial for", 0.05 * (i-1)];
% title(strTitle);
% end
%
% % Plotting the polynomial generated by the DifferentiateGridX function.
% for i = 1:21
% figure;
% plot(x_y, polyval(p_y(:,i), x_y));
% strTitle = ["Polynomial for", 0.05 * (i-1), " m"];
% title(strTitle);
% end
%% Functions
% Tabulates the values of U_x and U_y into a matrix containing the
% component of velocity for each mesh row in a corresponding row.
% Calls DifferentiateGridY for returning the polynomial fit and derivative
% of the polynomial fit.
function [u_xf, u_yf, p_x_yf, duf_y, F, Tf] = GridXY(file_name, meshsize, L, H)
T = readtable(file_name);
T = table2array(T);
u_x = zeros(meshsize, meshsize);
u_y = zeros(meshsize, meshsize);
du_y = zeros(meshsize, meshsize);
for j = 1:meshsize
for i = 1:meshsize
u_x(j, i) = T((meshsize*(j-1))+i,1);
u_y(j, i) = T((meshsize*(j-1))+i,2);
end
end
% Generate polynomial for u_x going down the y-direction.
[y, p_x_yf, dp_x_y, ~] = DifferentiateGridY(u_x, H);
% Evaluate the derivative of the polynomial for u_x going down the
% y-direction.
for i = 1:meshsize
du_y(:, i) = polyval(dp_x_y(:,i), H);
end
% Integrate the mesh of the derivative using trapezoidal method.
x_mesh = linspace(0, L, meshsize);
F = trapz(x_mesh, du_y(meshsize,:));
% Returns output.
u_xf = u_x;
u_yf = u_y;
duf_y = du_y(meshsize,:);
Tf = T;
end
% Creates a polynomial fit of a matrix of values going through its rows.
function [xf, pf, dpf, dUf] = DifferentiateGridX(U)
% Initialize variables.
[m, n] = size(U);
p = zeros(m, n);
dU = zeros(m, n);
dp = zeros(m-1, n);
x = linspace(0, 0.1, n);
% Create polynomial equations.
for i = 1:m
p(:,i) = polyfit(x, U(i,:), m-1);
dp(:,i) = polyder(p(:,i));
end
% Returns output
xf = x;
pf = p;
dpf = dp;
dUf = 1;
end
% Creates a polynomial fit of a matrix of values going down its columns.
% Finds
function [yf, pf, dpf, dUf] = DifferentiateGridY(U, H)
% Initialize variables.
[m, n] = size(U);
p = zeros(6, n);
dU = zeros(m, n);
dp = zeros(5, n);
y = linspace(0, H, m);
% Create polynomial equations.
for j = 1:n
p(:,j) = polyfit(y, U(:,j), 5);
dp(:,j) = polyder(p(:,j));
end
% Returns output.
yf = y;
pf = p;
dpf = dp;
dUf = 1;
end
|
/* Copyright (C) 2016 Andrew Shakinovsky
*/
#ifndef COMMONCOMPONENTS_H_
#define COMMONCOMPONENTS_H_
#include "../JuceLibraryCode/JuceHeader.h"
#include "EditorState.h"
#include "Constants.h"
enum SeqMouseAxis {
unknown,
vertical,
horizontal
};
Component helper - Allows a class to listen for a value change
Implement cptValueChange and optionally cptValueChanging
class CptNotify {
public:
/* receive notification when item has changed value.
cptId - is the ID of the component
value - The new value. For different components this means:
ToggleCpt - the id associated with the item selected. If this is a single item
toggle, then it will be the ID if it's on, and 0 if it's off
NumberCpt - the value of the number
*/
virtual void cptValueChange(int cptId, int value) = 0;
// toggle cpt calls this when an item is clicked while modifier key is held
// (in this case index doesn't change)
// mod - the modifier flags
virtual void cptItemClickWithModifier(int /*cptId*/, int /*idx*/, juce::ModifierKeys /*mod*/) {}
/* called if the value is busy changing (cptValueChanged will be called when it's done)
applies to NumberCpt
*/
virtual void cptValueChanging(int /*cptId*/, int /*value*/) {}
virtual ~CptNotify(){}
};
This is a set of toggle buttons where one button is active at a time.
Can also be used when there is a single item that is either on or off.
class ToggleCpt : public Component {
int mId;
bool mAlwaysNotify;
CptNotify *mNotify;
struct Item {
int id;
String text;
bool selected;
};
void recalcGrid();
int mItemsPerRow; // max columns as set by setMaxItemsPerRow
int mNumRows; // number of rows in the toggle (calculated)
int mNumItemsOnEachRow; // number of items on each row (possibly excluding the last row) (calculated)
int mNumItemsOnLastRow; // number of items on the last row (calculated)
protected:
SeqGlob *mGlob;
Array<Item> mItems;
virtual void paintText(Graphics &g, Rectangle<float> r, const String &txt);
public:
ToggleCpt(SeqGlob *glob, int id, CptNotify *notify, String name = "toggle");
// a value of 0 means unlimited (ie one row which is default)
void setMaxItemsPerRow(int max);
/* Add an item to the toggle collection. id can be used to reference it */
void addItem(int id, String text, bool selected=false);
// clear all items
void clearItems();
int getNumItems() { return mItems.size(); }
/* Set the current item. does not trigger valueChange unless 3nd param is set.
val parameter - only applicable if single item and determines whether to toggle on or off
*/
void setCurrentItem(int id, bool val, bool triggerNotify);
// return true if the item specified is current
bool isCurrent(int id);
// by default notify will not be called if an item was clicked but it's the same item that
// was already clicked. this turns that off (by setting to false)
void setAlwaysNotify(bool val);
virtual void paint(Graphics &g) override;
void mouseDown(const MouseEvent &event) override;
};
class ToggleCptWithLabel : public ToggleCpt {
juce::HashMap<int, String> mLabels;
public:
void setLabel(int id, const String &txt);
void clearLabels();
void clearLabel(int id);
bool hasLabel(int id) { return mLabels.contains(id); }
void paint(Graphics &g) override;
void paintText(Graphics &g, Rectangle<float> r, const String &txt) override;
ToggleCptWithLabel(SeqGlob *glob, int id, CptNotify *notify, String name = "toggleLabel");
};
Button Component - for single button with text that can be clicked
notify will receive the ID and a value of 0 when it's clicked
class ButtonCpt : public Component {
int mId;
SeqGlob *mGlob;
String mText;
CptNotify *mNotify;
juce::Colour mOverrideColor;
void mouseDown(const MouseEvent &event) override;
public:
ButtonCpt(SeqGlob *glob, int id, CptNotify *notify, String name = "button");
void paint(Graphics &g) override;
void setText(String txt);
// call with no parameters to not override
void overrideColor(juce::Colour c =Colour());
inline int getId() { return mId; }
};
Number component - drag up and down, or left and right to change value
double click to reset
class NumberCpt : public Component {
SeqGlob *mGlob;
int mId; // ID used to determine which number control
int mValue; // current value
int mDefaultValue;// default value (double click)
int mInterval; // interval jump
int mLowBound; // lower bound
int mHighBound; // upper bound
String mSuffix; // appended onto text
CptNotify *mNotify;
bool mInteracting;// busy dragging
int mDragValue; // value while dragging
int mIntSense; // internal sensitivity (factor of how many items)
SeqMouseAxis mAxis; // which axis we are dragging on
bool mEnabled; // if enabled for dragging
juce::HashMap<int, String> mReplacements;
void mouseDrag(const MouseEvent &event) override;
void mouseDown(const MouseEvent &event) override;
void mouseUp(const MouseEvent &event) override;
void mouseDoubleClick(const MouseEvent &event) override;
void paint(Graphics &g) override;
/* This is the text box that comes up when the user double clicks
on the item.
*/
class InlineEditor : public TextEditor, public TextEditor::Listener {
/** Called when the user presses the return key. Accept the edit */
void textEditorReturnKeyPressed(TextEditor&) override;
/** Called when the user presses the escape key. Abort the edit */
void textEditorEscapeKeyPressed(TextEditor&) override;
/** Called when the text editor loses focus. Accept the edit */
void textEditorFocusLost(TextEditor&) override;
// mouse listener added to get mouse click outside this component
// which does the same as make it lose focus (saves the contents)
void mouseDown(const MouseEvent& event) override;
void mouseDoubleClick(const MouseEvent&) override {
// do nothing. we want to throw away the double click on this text box
// otherwise it ends up causing an extra double click which might select
// one word (if there is a space) instead of keeping the full selection
}
Component *mTop;
NumberCpt *mParent;
public:
~InlineEditor();
InlineEditor(NumberCpt *parent);
};
InlineEditor *mTextEdit;
public:
class CustomText {
public:
// given the value, return the custom text in repl
// id is the id as passed into the ctor
// return false if you don't want to change that value
virtual bool getNumberCptCustomText(int id, int value, String &repl) = 0;
virtual ~CustomText(){}
};
NumberCpt(SeqGlob *glob, int id, CptNotify *notify, String name = "number");
// set range, etc
void setSpec(int lo, int hi, int interval, int defaultVal, String suffix);
// set a string replacement for values that equal a certain value
void setStringRep(int val, String repl);
void setCustomText(CustomText *replacer);
// get current value
int getValue();
// set current value optionally sending notification.
void setValue(int val, bool notify);
// try to set the value (if it's compatible and can be parsed)
// will try to interpret textual entry too if it matches string replacements
// (as set with setStringRep) or custom Text (as set with setCustomText)
void trySetValue(const String &val, bool notify);
// enable or disable
void enable(bool);
// get effective text that is displayed
// if stripped is set it does not add a suffix if any
String getTextualValue(bool stripped=false);
private:
CustomText *mTextReplacer;
};
Modal Dialog Popup
// This is the actual box that contains everything (as opposed to SeqEditDialog which takes up the whole
// client area and is semi-opaque)
/*
Generic Dialog helper.
To use this, you need to override it, and add an instance of the overriden class to the
main component. When you want the dialog to show, call openDialog.
*/
class SeqModalDialog : public Component,
public Button::Listener,
public ComboBox::Listener,
public CptNotify // for our own controls
{
CptNotify *mParent;
int mId; // for parent notify
int mWidth; // width and height of the inner panel
int mHeight;
void buttonClicked(Button *) override;
void comboBoxChanged(ComboBox *) override;
void mouseDown(const MouseEvent & event) override;
void paint(Graphics &) override;
void cptValueChange(int cptId, int value) override;
void resized() override;
class InnerPanel : public Component
{
SeqGlob *mGlob;
SeqModalDialog *mParent;
void paint(Graphics &) override;
void resized() override;
public:
InnerPanel(SeqGlob *glob, SeqModalDialog *par);
};
// contains all the controls for the dialog
InnerPanel mPanel;
//void fixColors(Component *cpt);
protected:
// a dirty hack
void forceResize();
// use this to access the Glob
SeqGlob *mGlob;
// this calls the cptnotify interface that was passed in passing the cptid and this value
void notifyParent(int val);
public:
// parent will be notified if user clicks ok on dialog (usually needing repaint)
SeqModalDialog(SeqGlob *glob, int id, CptNotify *parent, int width, int height);
// helpers for adding controls to inner panel.
// will new them and return them. id is used to pass into the
// notify function which you need to override
// if parent is specified, it's added to that component instead of the inner panel
// if cptId is specified, it's the value that's passed to notify as the cptId
ToggleButton *addToggle(const String &txt, int grp, Component *parent=nullptr, int cptId=0);
ComboBox *addCombo(const String &txt, Component *parent = nullptr, int cptId = 0);
Label *addStdLabel(const String &txt, Component *parent = nullptr);
TextButton *addStdButton(const String &txt, Component *parent = nullptr, int cptId = 0);
TextEditor *addStdTextEditor(Component *parent = nullptr, int cptId = 0);
// generic for other stuff. do it yourself. does not make visible
// cptId is used for the component's id (which is set)
void addToInner(int cptId, Component &cpt, int zOrd=-1);
void removeFromInner(Component *cpt);
// call this if you want the dialog to show
void openDialog();
// call this if you want the dialog to go away
void closeDialog(bool OK);
// override to provide action that happens when dialog ends
// you do not need to close and hide it, it will be done
virtual void endDialog(bool hitOk)=0;
// will be called when one of your components has user interaction
// value is only valid in some cases
virtual void notify(int cptId, int value)=0;
// override to do your sizing
virtual void resizedInner(Component *inner) = 0;
virtual ~SeqModalDialog() {};
// called if color scheme changes, goes thru child components to fix them
// to reflect the new color scheme
virtual void fixButtonColors();
};
#endif
|
<!DOCTYPE html>
<html>
<head>
<!-- include our dependency on angular -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<meta charset="utf-8">
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
<title>User Avatar Template</title>
</head>
<body>
<!--
1. ng-app='app' tells angular that everything within this div should function within
the scope of a declared angular module with the name of app.
2. ng-controller='mainCtrl' tells angular that the scope of this div should be handled
by a controller by the name of 'mainCtrl'. In a bigger application you will likely have
multiple controllers within one ng-app
-->
<div ng-app='app' ng-controller='mainCtrl'> <!-- [1],[2] -->
<h1>Create new user</h1>
<form name='userForm' ng-submit='addNew(userForm)'> <!-- [1], [2] -->
<input placeholder='Name' ng-model='userForm.name'/> <!-- [3] -->
<input placeholder='Image Url' ng-model='userForm.url'/>
<!--
setting button to type submit will trigger the ng-submit of the
form that button is a child of.
-->
<button type='submit'>Add New</button>
</form>
<ul class="User-list">
<li ng-repeat="user in users | orderBy:'name'">
<avatar user='user'/>
</li>
</ul>
</div>
</body>
</html>
|
<?php
/**
* Security controller.
*/
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
/**
* Class SecurityController.
*
* @Route("/")
*/
class SecurityController extends AbstractController
{
/**
* Homepage.
*
* @return \Symfony\Component\HttpFoundation\Response HTTP response
*
* @Route("/", name="home")
*/
public function homepage(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser()) {
return $this->redirectToRoute('book_index');
} else {
return $this->redirectToRoute('app_login');
}
}
/**
* Login.
*
* @return \Symfony\Component\HttpFoundation\Response HTTP response
*
* @Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser()) {
return $this->redirectToRoute('book_index');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
/**
* Logout.
*
* @Route("/logout", name="app_logout")
*/
public function logout()
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
}
|
import axios from 'axios';
import {
loginFailed,
loginStart,
loginSuccess,
logOutFailed,
logOutStart,
logOutSuccess,
registerFailed,
registerStart,
registerSuccess,
} from './authSlice';
export const loginUser = async (user, dispatch, navigate, toast) => {
dispatch(loginStart());
try {
const res = await axios.post('https://firealerthub.onrender.com/auth/login', user, {
withCredentials: true,
});
dispatch(loginSuccess(res.data));
toast.success('Đăng nhập thành công');
navigate('/');
} catch (err) {
toast.warn('Đăng nhập thất bại');
dispatch(loginFailed(err.response.data.message));
}
};
export const registerUser = async (user, dispatch, navigate, toast) => {
dispatch(registerStart());
try {
await axios.post('https://firealerthub.onrender.com/auth/register', user);
dispatch(registerSuccess());
toast.success('Đăng ký thành công!');
navigate('/login');
return true;
} catch (err) {
toast.warn('Đăng ký thất bại!');
dispatch(registerFailed());
return false;
}
};
export const logOut = async (dispatch, id, router, accessToken, axiosJWT) => {
dispatch(logOutStart());
try {
await axiosJWT.post('https://firealerthub.onrender.com/auth/logout', id, {
withCredentials: true,
headers: { token: `Bearer ${accessToken}` },
});
dispatch(logOutSuccess());
router.push('/');
} catch (err) {
dispatch(logOutFailed());
}
};
|
package ast.instructions.controls;
import static ast.instructions.ExecutionResult.SUCCESS;
import ast.instructions.AbstractInstruction;
import ast.instructions.ExecutionResult;
import ast.instructions.expressions.AbstractExpression;
import environment.JWASMStack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The condition of an 'if' instruction is considered <code>false</code> if it is zero. Any other
* value is considered as <code>true</code>.
*
* The {@link this#nextInstruction} of an 'if' should be set on creation to the instruction after
* the whole block. When {@link this#execute()} is called the next instruction is set to either the
* first instruction of the 'then' or 'else' branch depending on the evaluation of the
* {@link this#conditionExpression}. If the chosen branch is empty the next instruction is not
* changed.
*/
public class IfThenElse extends AbstractInstruction {
private static final Logger LOG = LoggerFactory.getLogger(IfThenElse.class);
private AbstractExpression<? extends Number> conditionExpression;
private AbstractInstruction thenInstruction;
private AbstractInstruction elseInstruction;
public IfThenElse(int lineNumber,
AbstractExpression<Integer> conditionExpression,
AbstractInstruction thenInstruction,
AbstractInstruction elseInstruction) {
super(lineNumber);
this.conditionExpression = conditionExpression;
this.thenInstruction = thenInstruction;
this.elseInstruction = elseInstruction;
}
public IfThenElse(
AbstractExpression<Integer> conditionExpression,
AbstractInstruction thenInstruction,
AbstractInstruction elseInstruction) {
super();
this.conditionExpression = conditionExpression;
this.thenInstruction = thenInstruction;
this.elseInstruction = elseInstruction;
}
public AbstractExpression<? extends Number> getConditionExpression() {
return conditionExpression;
}
public void setConditionExpression(
AbstractExpression<? extends Number> conditionExpression) {
this.conditionExpression = conditionExpression;
}
public AbstractInstruction getThenInstruction() {
return thenInstruction;
}
public void setThenInstruction(
AbstractInstruction thenInstruction) {
this.thenInstruction = thenInstruction;
}
public AbstractInstruction getElseInstruction() {
return elseInstruction;
}
public void setElseInstruction(
AbstractInstruction elseInstruction) {
this.elseInstruction = elseInstruction;
}
@Override
public ExecutionResult execute() {
LOG.trace("({})\tEvaluating 'if' condition", lineNumber);
Number conditionResult = conditionExpression.evaluate();
if (conditionResult.equals(0)) {
LOG.trace("({})\tExecuting 'then' branch - condition result was: {}", lineNumber,
conditionResult);
determineNextInstructionAsBranchOrStepOver(thenInstruction);
} else {
LOG.trace("({})\tExecuting 'else' branch - condition result was: {}", lineNumber);
determineNextInstructionAsBranchOrStepOver(elseInstruction);
}
return SUCCESS;
}
private void determineNextInstructionAsBranchOrStepOver(AbstractInstruction branchInstruction) {
if (branchInstruction != null) {
setNextInstruction(branchInstruction);
} else {
LOG.trace("({})\tBranch is empty, stepping over 'if' instruction", lineNumber);
}
}
@Override
public void setStack(JWASMStack stack) {
super.setStack(stack);
conditionExpression.setStack(stack);
if (thenInstruction != null) {
thenInstruction.setStack(stack);
}
if (elseInstruction != null) {
elseInstruction.setStack(stack);
}
}
}
|
import React, { useState } from "react";
import Swal from "sweetalert2";
export default function Chasier({ kafes, fails, loads, storeLaba }) {
const [pesan, setPesan] = useState([]);
const [harga, setHarga] = useState(0);
const [riwayat, setRiwayat] = useState([]);
const [laba, setLaba] = useState(0);
const handlePesan = (id) => {
const getPesanan = kafes.filter((kafe) => kafe._id === id);
const pesanan = {
qty: 1,
menu: getPesanan[0].menu,
harga: getPesanan[0].harga,
};
setPesan((prevPesan) => [...prevPesan, pesanan]);
setHarga((prevHarga) => prevHarga + pesanan.harga);
};
const handleTambah = (id) => {
setHarga((prevHarga) => prevHarga + pesan[id].harga);
pesan[id].qty = pesan[id].qty + 1;
setPesan(pesan);
};
const handleKurang = (id) => {
setHarga((prevHarga) => prevHarga - pesan[id].harga);
pesan[id].qty = pesan[id].qty - 1;
setPesan(pesan);
};
const handleBayar = () => {
if (harga === 0) {
Swal.fire("Mau bayar apa?", "Pesanannya masih kosong loh", "question");
} else {
let jam = new Date().getHours();
let menit = new Date().getMinutes();
let bulan = new Date().toLocaleString(navigator.language, {
month: "long",
});
let tanggal = new Date().getDate();
let tahun = new Date().getFullYear();
let hari = new Date().toLocaleString(navigator.language, {
weekday: "long",
});
if (jam < 10) {
jam = "0" + jam;
}
if (menit < 10) {
menit = "0" + menit;
}
const newRiwayat = {
tanggal: `${hari}, ${tanggal} ${bulan} ${tahun}`,
jam: `${jam} : ${menit}`,
harga: harga,
};
setRiwayat((prevRiwayat) => [...prevRiwayat, newRiwayat]);
setHarga(0);
setPesan([]);
setLaba((prevLaba) => prevLaba + harga);
Swal.fire({
icon: "success",
title: "Terimakasih :D",
text: "Semoga harimu menyenangkan",
});
}
};
const handleSetor = () => {
if (laba === 0) {
Swal.fire("Mau setor apa?", "Labanya masih kosong loh", "question");
} else {
let bulan = new Date().toLocaleString(navigator.language, {
month: "long",
});
let tanggal = new Date().getDate();
let tahun = new Date().getFullYear();
const setoran = {
tanggal: `${tanggal} ${bulan} ${tahun}`,
pendapatan: laba,
};
storeLaba(setoran);
setPesan([]);
setRiwayat([]);
setLaba(0);
setHarga(0);
}
};
return (
<div className="chasier">
<div className="kiri">
{loads && (
<div className="loading">
<h2>Loading...</h2>
</div>
)}
{fails && (
<div className="fail">
<h2>{fails}</h2>
</div>
)}
<h2 className="judul">Minuman</h2>
{kafes &&
kafes
.filter((kafe) => kafe.kategori === "minuman")
.map((menus, index) => (
<div
className="menu"
key={index}
onClick={() => handlePesan(menus._id)}
>
<h2>{menus.menu}</h2>
<h5>Rp.{menus.harga}</h5>
</div>
))}
<h2 className="judul">Cemilan</h2>
{kafes &&
kafes
.filter((kafe) => kafe.kategori === "cemilan")
.map((menus, index) => (
<div
className="menu"
key={index}
onClick={() => handlePesan(menus._id)}
>
<h2>{menus.menu}</h2>
<h5>Rp.{menus.harga}</h5>
</div>
))}
<h2 className="judul">Makanan</h2>
{kafes &&
kafes
.filter((kafe) => kafe.kategori === "makanan")
.map((menus, index) => (
<div
className="menu"
key={index}
onClick={() => handlePesan(menus._id)}
>
<h2>{menus.menu}</h2>
<h5>Rp.{menus.harga}</h5>
</div>
))}
</div>
<div className="kanan">
<h3 className="judulpesan">Pesanan</h3>
<table>
<thead>
<tr>
<th>Pesanan</th>
<th>Qty</th>
<th>Aksi</th>
<th>Harga</th>
</tr>
</thead>
<tbody>
{pesan &&
pesan
.filter((pesanans) => pesanans.qty > 0)
.map((pesanan, index) => (
<tr className="pesanan" key={index}>
<td>{pesanan.menu}</td>
<td>
<h5>{pesanan.qty}</h5>
</td>
<td>
<button
className="kurang"
onClick={() => handleKurang(index)}
>
- 1
</button>
<button
className="tambah"
onClick={() => handleTambah(index)}
>
+ 1
</button>
</td>
<td>{pesanan.qty * pesanan.harga}</td>
</tr>
))}
</tbody>
</table>
<div className="harga">
<h3>Total Bayar : Rp.{harga}</h3>
<button onClick={() => handleBayar()}>Bayar Sekarang</button>
</div>
<h3 className="judulpesan">History</h3>
{riwayat &&
riwayat.map((riwayats, index) => (
<div className="riwayat" key={index}>
<h5>{riwayats.tanggal}</h5>
<h5>{riwayats.jam}</h5>
<h5>{riwayats.harga}</h5>
</div>
))}
<div className="setor">
<button onClick={() => handleSetor()}>Setor Total : {laba}</button>
</div>
</div>
</div>
);
}
|
package com.callback.base.worker.async.wrap;
import com.callback.base.service.backpressure.constants.BackPressureEnums;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
import org.springframework.stereotype.Component;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author JerryLong
* @version V1.0
* @Title: CallBackAsyncWrapper
* @Description: 异步包装
* @date 2022/5/26 5:52 PM
*/
@Component
public class CallBackAsyncWrapper {
/**
* 快线程池
*/
private static ExecutorService fastExecutorService = ExecutorServiceMetrics.monitor(
Metrics.globalRegistry,
new ThreadPoolExecutor(20, 100, 30, TimeUnit.SECONDS, new SynchronousQueue<>(), (r) -> new Thread(r, "回调服务处理线程池-快"), new ThreadPoolExecutor.CallerRunsPolicy())
, "callback_fastExecutorService"
);
/**
* 慢线程池
*/
private static ExecutorService slowExecutorService = ExecutorServiceMetrics.monitor(
Metrics.globalRegistry,
new ThreadPoolExecutor(5, 10, 30, TimeUnit.SECONDS, new SynchronousQueue<>(), (r) -> new Thread(r, "回调服务处理线程池-慢"), new ThreadPoolExecutor.CallerRunsPolicy())
, "callback_slowExecutorService"
);
/**
* 对任务进行异步包装
*
* @param backPressureEnums
* @param runnable
*/
public void wrap(BackPressureEnums backPressureEnums, Runnable runnable) {
switch (backPressureEnums) {
case SLOW:
slowExecutorService.execute(runnable);
return;
case FAST:
default:
fastExecutorService.execute(runnable);
return;
}
}
}
|
package com.example.duan.fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import com.example.duan.R;
import com.example.duan.activity.SearchViewActivity;
import com.example.duan.adapter.ViewPager2FragmentAdapter;
import com.example.duan.dao.NguoiDungDao;
import com.example.duan.model.NguoiDung;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
public class Home_Fragment extends Fragment {
public Home_Fragment(){
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_home,container,false);
TabLayout tabLayout=view.findViewById(R.id.TabLayout);
ViewPager2 viewPager2=view.findViewById(R.id.ViewPager);
ImageView ic_searchView=view.findViewById(R.id.ic_searchView);
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("dataUser", Context.MODE_PRIVATE);
int manguoidung=sharedPreferences.getInt("manguoidung",-1);
NguoiDungDao nguoiDungDao=new NguoiDungDao(getContext());
NguoiDung nguoiDung=nguoiDungDao.getNguoiDungByID(manguoidung);
if(nguoiDung!=null){
TextView txt_ten=view.findViewById(R.id.txt_ten);
txt_ten.setText(nguoiDung.getHoten());
}
ic_searchView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), SearchViewActivity.class));
}
});
Fragment[] fragments={new Tab_Home1_Fragment(),new Tab_Category1_Fragment()};
ViewPager2FragmentAdapter viewPager2FragmentAdapter=new ViewPager2FragmentAdapter(requireActivity(), fragments);
viewPager2.setAdapter(viewPager2FragmentAdapter);
new TabLayoutMediator(tabLayout, viewPager2,
(tab, position) -> {
switch (position) {
case 0:
tab.setText("Home");
break;
case 1:
tab.setText("Category");
break;
}
}
).attach();
return view;
}
}
|
import Updateable from "../../DataTypes/Interfaces/Updateable";
import ParticleSystem from "./ParticleSystem";
export default class ParticleSystemManager implements Updateable {
private static instance: ParticleSystemManager = null;
protected particleSystems: Array<ParticleSystem>;
private constructor(){
this.particleSystems = new Array();
}
static getInstance(): ParticleSystemManager {
if(ParticleSystemManager.instance === null){
ParticleSystemManager.instance = new ParticleSystemManager();
}
return ParticleSystemManager.instance;
}
registerParticleSystem(system: ParticleSystem){
this.particleSystems.push(system);
}
deregisterParticleSystem(system: ParticleSystem){
let index = this.particleSystems.indexOf(system);
this.particleSystems.splice(index, 1);
}
clearParticleSystems(){
this.particleSystems = new Array();
}
update(deltaT: number): void {
for(let particleSystem of this.particleSystems){
particleSystem.update(deltaT);
}
}
}
|
// This is the main script
// load this script into Arduino UNO to control the OC box
// To test the proper functionality of the OC box write INPUT COMMANDS on the serial monitor
//
// INPUT COMMANDS:
// 4 Reward
// 3 Dot Stim Both [ Double dots - No wrong response ]
// 1 Dot Stim Left [One dot on the left]
// 2 Dot Stim Right [One dot on the right]
// 5 LCD - BOTH no stimuli are shown but both buttons trigger a reward
// 6 LCD - LEFT no stimuli are shown but left button triggers a reward
// 7 LCD - RIGHT no stimuli are shown but right button triggers a reward
// 13 Dot Stim Both [Extinction] -stub [No reward]
// 11 Dot Stim Left [Extinction] -stub [One dot on the left - No reward]
// 12 Dot Stim Right [Extinction] -stub [One dot on the right - No reward]
// 21 Dot Stim Left [reverse criterion] -stub [One dot on the left - reward on the other side]
// 22 Dot Stim Right [reverse criterion] -stub [One dot on the right - reward on the other side]
// 50 Recharge [recharge syringe pump]
// 51 Refill [push continuously the syringe pump]
// 0 Stop
//------ EDIT THE PARAMETERS BELOW TO CUSTOMIZE YOUR EXPERIMENT ------
// BUTTONS CAPACITIVE THRESHOLDs (set this value using skinnerCapacitiveTest.ino)
int thrsx=200;
int thrdx=200;
// PERMANENCE OF STIMULUS AFTER THE RESPONSE [milliseconds]
int stimPermanenceRight = 2500;
int stimPermanenceWrong = 1000;
//------ END OF EDITABLE CODE ------
unsigned long startTime;
unsigned long reactionTime;
int cdx;
int csx;
int resetPin=12;
void setup() {
ledInit();
Serial.begin(9600); // Initializzation of Serial communication
}
void loop() {
delay(2);
if (Serial.available()){ // check for Serial input
int cmd = Serial.parseInt();
// If a serial message is available, it is parsed in an integer and the following if,
// elseif statements guide the arduino behavior accordingly
if(cmd==4){ // REWARD
correct();
Serial.println("reward");
reward();
clearScreen();
}else if (cmd ==1){ // Dot Stim Left
clearScreen();
drawLeft();
startTime=millis();
while (true){
cdx = checkDx();
csx = checkSx();
if (csx >= thrsx | cdx >= thrdx){
reactionTime = millis() - startTime;
if (csx >= thrsx){
correct();
Serial.print("yes : ");
Serial.println(reactionTime,DEC);
reward();
delay(stimPermanenceRight);
}else if(cdx >= thrdx){
wrong();
Serial.print("no : ");
Serial.println(reactionTime,DEC);
delay(stimPermanenceWrong);
}
break;
}else if(Serial.available()){
Serial.println("skipped");
break;
}
}
clearScreen();
}else if (cmd == 6){ // LCD Stim Left
startTime=millis();
while (true){
cdx = checkDx();
csx = checkSx();
if (csx >= thrsx | cdx >= thrdx){
reactionTime = millis() - startTime;
if (csx >= thrsx){
correct();
Serial.print("yes : ");
Serial.println(reactionTime,DEC);
reward();
}else if(cdx >= thrdx){
wrong();
Serial.print("no : ");
Serial.println(reactionTime,DEC);
}
break;
}else if(Serial.available()){
Serial.println("skipped");
break;
}
}
clearScreen();
} else if (cmd ==11){ // Dot Stim Left [Extinction]
clearScreen();
drawLeft();
startTime=millis();
while (true){
cdx = checkDx();
csx = checkSx();
if (csx >= thrsx | cdx >= thrdx){
reactionTime = millis() - startTime;
if (csx >= thrsx){
correct();
Serial.print("yes : ");
Serial.println(reactionTime,DEC);
//reward();
delay(stimPermanenceRight);
}else if(cdx >= thrdx){
wrong();
Serial.print("no : ");
Serial.println(reactionTime,DEC);
delay(stimPermanenceWrong);
}
break;
}else if(Serial.available()){
Serial.println("skipped");
break;
}
}
clearScreen();
}else if (cmd ==21){ // Dot Stim Left [Reversed criterion]
clearScreen();
drawLeft();
startTime=millis();
while (true){
cdx = checkDx();
csx = checkSx();
if (csx >= thrsx | cdx >= thrdx){
reactionTime = millis() - startTime;
if (csx >= thrsx){
wrong();
Serial.print("no : ");
Serial.println(reactionTime,DEC);
delay(stimPermanenceWrong);
}else if(cdx >= thrdx){
correct();
Serial.print("yes : ");
Serial.println(reactionTime,DEC);
reward();
delay(stimPermanenceRight);
}
break;
}else if(Serial.available()){
Serial.println("skipped");
break;
}
}
clearScreen();
} else if(cmd==2){ // Dot Stim Right
clearScreen();
drawRight();
startTime=millis();
while (true){
cdx = checkDx();
csx = checkSx();
if (csx >= thrsx | cdx >= thrdx){
reactionTime = millis() - startTime;
if (csx >= thrsx){
wrong();
Serial.print("no : ");
Serial.println(reactionTime,DEC);
delay(stimPermanenceWrong);
}else if(cdx >= thrdx){
correct();
Serial.print("yes : ");
Serial.println(reactionTime,DEC);
reward();
delay(stimPermanenceRight);
}
break;
}else if(Serial.available()){
Serial.println("skipped");
break;
}
}
clearScreen();
} else if(cmd==7){ // LCD Stim Right
startTime=millis();
while (true){
cdx = checkDx();
csx = checkSx();
if (csx >= thrsx | cdx >= thrdx){
reactionTime = millis() - startTime;
if (csx >= thrsx){
wrong();
Serial.print("no : ");
Serial.println(reactionTime,DEC);
}else if(cdx >= thrdx){
correct();
Serial.print("yes : ");
Serial.println(reactionTime,DEC);
reward();
}
break;
}else if(Serial.available()){
Serial.println("skipped");
break;
}
}
clearScreen();
}else if(cmd==12){ // Dot Stim Right [Extinction]
clearScreen();
drawRight();
startTime=millis();
while (true){
cdx = checkDx();
csx = checkSx();
if (csx >= thrsx | cdx >= thrdx){
reactionTime = millis() - startTime;
if (csx >= thrsx){
wrong();
Serial.print("no : ");
Serial.println(reactionTime,DEC);
delay(stimPermanenceWrong);
}else if(cdx >= thrdx){
correct();
Serial.print("yes : ");
Serial.println(reactionTime,DEC);
delay(stimPermanenceRight);
}
break;
}else if(Serial.available()){
Serial.println("skipped");
break;
}
}
clearScreen();
}else if(cmd==22){ // Dot Stim Right [Reversed criterion]
clearScreen();
drawRight();
startTime=millis();
while (true){
cdx = checkDx();
csx = checkSx();
if (csx >= thrsx | cdx >= thrdx){
reactionTime = millis() - startTime;
if (csx >= thrsx){
correct();
Serial.print("yes : ");
Serial.println(reactionTime,DEC);
reward();
delay(stimPermanenceRight);
}else if(cdx >= thrdx){
wrong();
Serial.print("no : ");
Serial.println(reactionTime,DEC);
delay(stimPermanenceWrong);
}
break;
}else if(Serial.available()){
Serial.println("skipped");
break;
}
}
clearScreen();
}else if(cmd==3){ // Dot Stim Both
clearScreen();
drawRight();
drawLeft();
startTime=millis();
while (true){
cdx = checkDx();
csx = checkSx();
if (csx >= thrsx | cdx >= thrdx){
reactionTime = millis() - startTime;
if (csx >= thrsx){
correct();
Serial.print("both_SX : ");
Serial.println(reactionTime,DEC);
reward();
delay(stimPermanenceRight);
}else if(cdx >= thrdx){
correct();
Serial.print("both_DX : ");
Serial.println(reactionTime,DEC);
reward();
delay(stimPermanenceRight);
}
break;
}else if(Serial.available()){
Serial.println("skipped");
break;
}
}
clearScreen();
}else if(cmd==5){ // LCD Stim Both
startTime=millis();
while (true){
cdx = checkDx();
csx = checkSx();
if (csx >= thrsx | cdx >= thrdx){
reactionTime = millis() - startTime;
if (csx >= thrsx){
correct();
Serial.print("both_SX : ");
Serial.println(reactionTime,DEC);
reward();
}else if(cdx >= thrdx){
correct();
Serial.print("both_DX : ");
Serial.println(reactionTime,DEC);
reward();
delay(stimPermanenceRight);
}
break;
}else if(Serial.available()){
Serial.println("skipped");
break;
}
}
clearScreen();
}else if(cmd==13){ // Dot Stim Both [extinction]
clearScreen();
drawRight();
drawLeft();
startTime=millis();
while (true){
cdx = checkDx();
csx = checkSx();
if (csx >= thrsx | cdx >= thrdx){
reactionTime = millis() - startTime;
if (csx >= thrsx){
correct();
Serial.print("both_SX : ");
Serial.println(reactionTime,DEC);
delay(stimPermanenceRight);
}else if(cdx >= thrdx){
correct();
Serial.print("both_DX : ");
Serial.println(reactionTime,DEC);
delay(stimPermanenceRight);
}
break;
}else if(Serial.available()){
Serial.println("skipped");
break;
}
}
clearScreen();
}else if(cmd==50){ // Recharge the reward tube
Serial.println("recharging...");
int count = 0;
while (true){
if(Serial.available()){
Serial.println("stop");
break;
}else{
recharge();
if(count%5){
warning();
}
count++;
}
}
}else if(cmd==51){ // Refill the reward tube
Serial.println("refilling...");
int count = 0;
while (true){
if(Serial.available()){
Serial.println("stop");
break;
}else{
fill();
if(count%5){
warning();
}
count++;
}
}
}else{
Serial.println("other");
clearScreen();
}
}
}
|
import subprocess
import platform
def ping_ip(ip_address):
"""
Pings a given IP address once and returns whether the ping was successful.
Args:
ip_address (str): The IP address to ping.
Returns:
bool: True if the ping succeeds, False otherwise.
"""
try:
if platform.system().lower() == "windows":
parameters = ['-n', '1', '-w', '1000']
else:
parameters = ['-c', '1', '-W', '1']
response = subprocess.run(
['ping'] + parameters + [ip_address],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
return response.returncode == 0
except Exception as e:
print(f"Error pinging: {e}")
return False
|
<template>
<ModalComponent
:isOpen="isModalOpened"
@modal-close="closeModal"
name="modal"
/>
<div class="grid-container">
<GridItem
v-if="artworks.length > 0"
class="grid-item"
v-for="artwork in artworks"
@click="() => openModal(artwork.id)"
:key="artwork.id"
:image-url="artwork.webImage.url"
:title="artwork.title"
/>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { useStore } from "@/stores/store";
import ModalComponent from "../modal/modal.vue";
import GridItem from "@/components/grid-item/grid-item.vue";
const store = useStore();
const { setCurrentArtwork } = store;
const { artworks } = toRefs(store);
const isModalOpened = ref(false);
const openModal = (id: string) => {
isModalOpened.value = true;
setCurrentArtwork(id);
};
const closeModal = () => {
isModalOpened.value = false;
};
</script>
<style scoped>
.grid-container {
display: flex;
flex-wrap: wrap;
flex: 1;
margin: 1.25rem 0;
min-width: 9.375rem;
}
.grid-item {
flex: 1 0 25%;
box-sizing: border-box;
}
@media screen and (max-width: 768px) {
.grid-item {
flex: 1 0 33.33%;
}
}
@media screen and (max-width: 480px) {
.grid-item {
flex: 1 0 50%;
}
}
</style>
|
## AWS EC2 - Security Groups
### Requirements
For this exercise you'll need:
1. EC2 instance with web application
2. Security group inbound rules that allow HTTP traffic
### Objectives
1. List the security groups you have in your account, in the region you are using
2. Remove the HTTP inbound traffic rule
3. Can you still access the application? What do you see/get?
4. Add back the rule
5. Can you access the application now?
### Solution
#### Console
1. Go to EC2 service - > Click on "Security Groups" under "Network & Security"
You should see at least one security group. One of them is called "default"
2. Click on the security group with HTTP rules and click on "Edit inbound rules".
Remove the HTTP related rules and click on "Save rules"
3. No. There is a time out because we removed the rule allowing HTTP traffic.
4. Click on the security group -> edit inbound rules and add the following rule:
* Type: HTTP
* Port range: 80
* Source: Anywhere -> 0.0.0.0/0
5. yes
#### CLI
1. `aws ec2 describe-security-groups` -> by default, there is one security group called "default", in a new account
2. Remove the rule:
```
aws ec2 revoke-security-group-ingress \
--group-name someHTTPSecurityGroup
--protocol tcp \
--port 80 \
--cidr 0.0.0.0/0
```
3. No. There is a time out because we removed the rule allowing HTTP traffic.
4. Add the rule we remove:
```
aws ec2 authorize-security-group-ingress \
--group-name someHTTPSecurityGroup
--protocol tcp \
--port 80 \
--cidr 0.0.0.0/0
```
5. yes
|
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { toast } from 'react-hot-toast';
import { faHeart as solidHeart } from '@fortawesome/free-solid-svg-icons';
import { faHeart as regularHeart } from '@fortawesome/free-regular-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Link } from 'react-router-dom';
import './Dish.css';
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import { useSelector, useDispatch } from 'react-redux';
import { wishlistActions } from '../../../store/wishlistSlice';
function Dish({ product }) {
const [dish, setDish] = useState(product);
const [quantity, setQuantity] = useState(1);
const [isMobile, setIsMobile] = useState(window.innerWidth < 768);
const restaurantId = useSelector(state => state.restaurant.restaurantId);
const tableNb = useSelector(state => state.restaurant.tableNb);
const isAuthenticated = useSelector(state => state.auth.isAuthenticated);
const userId = useSelector(state => state.auth.userId);
const dispatch = useDispatch();
useEffect(() => {
function handleResize() {
setIsMobile(window.innerWidth < 768);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
const handleFavoriteClick = async () => {
if (!isAuthenticated) {
toast.error("Please log in to update your wishlist.");
return;
}
try {
const response = await axios.post(
`${process.env.REACT_APP_BACKEND_URL}/product/users/${userId}/wishlist/${dish._id}`,
{ isFavorited: !dish.isFavorited },
{ withCredentials: true }
);
if (response.status === 200) {
const updatedIsFavorited = !dish.isFavorited;
setDish(prevDish => ({ ...prevDish, isFavorited: updatedIsFavorited }));
dispatch(wishlistActions.toggleWishlist({ ...dish, isFavorited: updatedIsFavorited }));
toast.success(updatedIsFavorited ? "Added to wishlist!" : "Removed from wishlist!");
} else {
throw new Error('Failed to update wishlist');
}
} catch (error) {
console.error('Error updating wishlist:', error);
toast.error("Error updating wishlist.");
}
};
const addToCart = async () => {
if (!dish) {
toast.error('Dish details not available');
return;
}
const userId = localStorage.getItem("userId");
const userPass = userId || "000000000000000000000000";
const storedRestaurantId = localStorage.getItem('restaurantId');
if (!storedRestaurantId) {
console.error('Restaurant ID is missing');
toast.error('Restaurant ID is missing');
return;
}
console.log('Adding product to cart:', dish); // Log the product being added to the cart
try {
const response = await axios.post(
`${process.env.REACT_APP_BACKEND_URL}/cart/addtocartweb/${userPass}`,
{
productFK: dish._id,
quantity: 1,
restaurantFK: storedRestaurantId,
},
{ withCredentials: true }
);
if (response.status === 200) {
toast.success("Product added to cart!");
} else {
throw new Error('Failed to add product to cart');
}
} catch (error) {
console.error('Error adding product to cart:', error);
toast.error(error.message || "An error occurred while adding product to cart");
}
};
return (
<div className="containers my-5">
{dish && (
<div className="cards">
<div className="card-headers bg-transparent">
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<FontAwesomeIcon
icon={dish.isFavorited ? solidHeart : regularHeart}
onClick={handleFavoriteClick}
style={{ color: dish.isFavorited ? 'red' : 'gray', cursor: 'pointer' }}
/>
<span>Today's Offer</span>
{dish.promotion > 0 && (
<span className="text-danger">{dish.promotion}%</span>
)}
</div>
</div>
<div className="card-bodys">
<img src={dish.photo} alt={dish.name} className="img-fluid" />
<h5>{dish.name.toUpperCase()}</h5>
<p>${dish.price}</p>
<p>Description: {dish.description}</p>
<div className="btn-group">
<button style={{ color: 'white', background: 'salmon' }} onClick={addToCart}>Add to cart</button>
<Link to={`/dish-details/${dish._id}`} className="btn btn-link" style={{ color: 'salmon' }}>Details</Link>
</div>
</div>
</div>
)}
</div>
);
}
export default Dish;
|
/*
; Title: Exercise 6.2 Output Properties
; Author: Kimberly Pierce
; Date: August 2020
; Modified By: Kimberly Pierce
; Description: Exercise 6.2 Output Properties
*/
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BookListComponent } from './book-list/book-list.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
import { WishlistComponent } from './wishlist/wishlist.component';
const routes: Routes = [
{ path: ' ', component: BookListComponent },
{path: 'book-list', component: BookListComponent},
{path: 'about' , component: AboutComponent},
{path: 'contact', component: ContactComponent},
{path: 'wishlist', component: WishlistComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
@extends('layouts.mainLayout')
@section('content')
<div class="flex flex-col p-10">
<div class="flex justify-between">
<div>
<h1 class="text-3xl font-semibold">Expenses</h1>
<p class="mt-2 text-gray-400 font-medium">Total expense amount on all properties - ₹ {{$sum}}</p>
</div>
<div class="flex items-center gap-4">
<a href="{{route('createExpenses')}}"><button class="bg-purple-800 text-white rounded-md pr-4 pl-4 pt-2 pb-2">+ New Expense</button></a>
</div>
</div>
<div class="bg-white rounded-sm border border-gray-300 mt-8">
<div >
<form id='filter' class="flex text-sm px-3 py-2 gap-5" action="{{route('filterExpense')}}" method="post">
@csrf
<div class="mt-2 mb-6">
<select name="propertyName" class="rounded-sm p-2 border mt-2 border-gray-300 w-full">
<option class="text-gray-300 p-2" value="" selected>Select a Property</option>
@if ($property->count()>0)
@foreach ($property as $prop)
@if ($values!==null)
<option class="text-gray-700" {{$values->propertyName===$prop->title?'selected':''}} value="{{$prop->title}}">{{$prop->title}}</option>
@else
<option class="text-gray-700" value="{{$prop->title}}">{{$prop->title}}</option>
@endif
@endforeach
@else
<h1>There are no properties added yet.</h1>
@endif
</select>
</div>
<div class="mt-2 mb-6">
<input id="fromDate" class="rounded-sm p-2 border mt-2 border-gray-300 w-full" type="date" name="fromDate" value="{{$values!==null? $values->fromDate: ''}}" placeholder="From Date">
</div>
<div class="mt-2 mb-6">
<input id="toDate" class="rounded-sm p-2 border mt-2 border-gray-300 w-full" type="date" name="toDate" value="{{$values!==null? $values->toDate: ''}}" placeholder="To Date">
</div>
<div class="mt-2 mb-6">
<button class="rounded-md font-semibold py-3 px-6 text-white border mt-2 bg-purple-500 hover:bg-purple-800" type="submit" name="submit">✓ Apply</button>
</div>
<div class="mt-2 mb-6">
<div class="rounded-md font-semibold py-3 px-6 border mt-2 border-gray-500 text-gray-800 hover:bg-gray-800 hover:text-white" type="submit" name="submit"><i class="fa-solid fa-download"></i> Export</div>
</div>
</form>
</div>
<div id="results" class="flex justify-center items-center p-4 border-t border-gray-300">
@if ($data === null)
@elseif ($data->isEmpty() )
<h1>No Records Found.</h1>
@else
<table class="w-full h-full table-auto border-collapse border border-gray-300">
<thead>
<tr class="grid grid-cols-[1fr,3fr,3fr,3fr,3fr,2fr,3fr,2fr]">
<th class="border border-gray-300 text-slate-500">#</th>
<th class="border border-gray-300 text-slate-500">Property Name</th>
<th class="border border-gray-300 text-slate-500">Tenant Name</th>
<th class="border border-gray-300 text-slate-500">Expense Type</th>
<th class="border border-gray-300 text-slate-500">Date</th>
<th class="border border-gray-300 text-slate-500">Amount</th>
<th class="border border-gray-300 text-slate-500">Paid By</th>
<th class="border border-gray-300">
</th>
</tr>
</thead>
<tbody>
@foreach ($data as $item)
<tr class="grid grid-cols-[1fr,3fr,3fr,3fr,3fr,2fr,3fr,2fr] group hover:bg-gray-100">
<td class="border border-gray-300 flex justify-center text-slate-500 font-semibold">{{$loop->iteration}}</td>
<td class="border border-gray-300 flex justify-center text-slate-500 font-semibold">{{$item->propertyName}}</td>
<td class="border border-gray-300 flex justify-center text-slate-500 font-semibold">{{$item->tenantName}}</td>
<td class="border border-gray-300 flex justify-center text-slate-500 font-semibold">{{$item->expenseType}}</td>
<td class="border border-gray-300 flex justify-center text-slate-500 font-semibold">{{$item->date}}</td>
<td class="border border-gray-300 flex justify-center text-slate-500 font-semibold">{{$item->amount}}</td>
<td class="border border-gray-300 flex justify-center font-semibold text-orange-400">{{$item->paidBy}}</td>
<td class="border border-gray-300 flex justify-center">
<div id="three_dots" class="basis-1/12 flex items-center justify-end pr-10">
<button id="dropdownMenuIconButton" data-dropdown-toggle="{{$item->id}}" class="group-hover:bg-gray-100 inline-flex justify-center items-center p-2 text-sm font-medium text-center w-10 h-10 text-gray-900 bg-white rounded-full focus:outline-none" type="button">
<i class="fa-solid fa-ellipsis"></i>
</button>
<!-- Dropdown menu -->
<div id="{{$item->id}}" class="z-10 hidden bg-white divide-y divide-gray-100 rounded-lg shadow w-44" >
<ul class="py-2 text-sm text-gray-500" aria-labelledby="dropdownMenuIconButton">
<li>
<a href="{{route('expenseDetails',$item->id)}}" class="block py-2 hover:bg-gray-100 dark:hover:bg-gray-500 dark:hover:text-white text-sm">
<i class="fa-solid fa-eye px-3"></i> View
</a>
</li>
<li>
<a href="{{route('editExpenses',$item->id)}}" class="block py-2 hover:bg-gray-100 dark:hover:bg-gray-500 dark:hover:text-white text-sm">
<i class="fa-solid fa-user-pen px-3"></i> Edit
</a>
</li>
</ul>
</div>
</div>
</td>
</tr>
@endforeach
<tr class="grid grid-cols-[10fr,3fr,2fr,3fr,2fr]">
<td class="border border-gray-300 flex justify-center"></td>
<td class="border border-gray-300 flex justify-center font-bold text-slate-500">Total</td>
<td class="border border-gray-300 flex justify-center font-bold text-slate-500">{{$data->sum('amount')}}</td>
<td class="border border-gray-300 flex justify-center"></td>
<td class="border border-gray-300 flex justify-center"></td>
</tr>
</tbody>
</table>
@endif
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.2.1/flowbite.min.js"></script>
@endsection
|
#include <ros/ros.h>
#include <Eigen/Eigen>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <livz/livz.hpp>
Eigen::Vector3d sin3D(double t){
return Eigen::Vector3d(t, std::sin(t), t);
}
bool moveBallUpdater(double duration){
// duration表示自创建任务开始,经过的秒数
Livz::drawOneSphere("sphere", sin3D(duration), 0.7, LCOLOR::YELLOW, -1.0, "map",1);
if(duration > 10.0){
Livz::clearAll("sphere");
return true; //这将结束任务,自动删除此updater
}
return false;
}
bool waveUpdater(double duration){
//控制帧率为10
static int last_ms = -100;
int ms = duration*1000;
if(ms - last_ms < 100) {
return false;
}
last_ms = ms;
static int id = 1;
// 结合animate功能,实现水波扩散效果
Eigen::Vector3d current_pos(0.4*duration*duration - 20, 0.3*duration*duration - 10, 0);
LAnimateParam ani_param("circle", 3.0);
Livz::createAnimate(ani_param, Livz::draw2DCircle,
LPARAMS(current_pos, 0.05 , LCOLOR::RED, 0.1, 0.8,"map",id, 20 ),
LPARAMS(current_pos, 15.0 , LCOLOR::YELLOW, 0.3, 0.0,"map",id, 50 ) ); //随着圆变大,采样密度也逐渐增大
Livz::draw2DCircle("circle", current_pos, 0.05 , LCOLOR::RED, 0.1, 1.0,"map",id+100000, 20);
id++;
if(duration > 10.0){
return true; //这将结束任务,自动删除此updater
}
return false;
}
bool threeBody(double duration)
{
static double last_duration = 0.0;
static Eigen::Vector3d pos1(-10, 0, 0), pos2(10, 0, 0), pos3(0, 5, 10);
static Eigen::Vector3d vel1(0, 1, 0), vel2(0, -1, 0), vel3(1, 0, 0);
const double M1 = 1.0;
const double M2 = 2.0;
const double M3 = 3.0;
const double G = 6.67430e1; // 赛博万有引力常数
// 时间步长
double dt = duration - last_duration;
// 计算距离
Eigen::Vector3d r12 = pos1 - pos2;
Eigen::Vector3d r13 = pos1 - pos3;
Eigen::Vector3d r23 = pos2 - pos3;
// 计算引力
Eigen::Vector3d F12 = -G * M1 * M2 * r12 / pow(r12.norm(), 3);
Eigen::Vector3d F13 = -G * M1 * M3 * r13 / pow(r13.norm(), 3);
Eigen::Vector3d F23 = -G * M2 * M3 * r23 / pow(r23.norm(), 3);
// 计算加速度
Eigen::Vector3d a1 = (F12 + F13) / M1;
Eigen::Vector3d a2 = (-F12 + F23) / M2;
Eigen::Vector3d a3 = (-F13 - F23) / M3;
// 更新速度
vel1 += a1 * dt;
vel2 += a2 * dt;
vel3 += a3 * dt;
// 更新位置
pos1 += vel1 * dt;
pos2 += vel2 * dt;
pos3 += vel3 * dt;
last_duration = duration;
Livz::drawOneSphere("sphere", pos1, 1, LCOLOR::GREEN, 0.8, "map", 1);
Livz::drawOneSphere("sphere", pos2, 1.4, LCOLOR::YELLOW, 0.8, "map", 2);
Livz::drawOneSphere("sphere", pos3, 1.7, LCOLOR::BLUE, 0.8, "map", 3);
Livz::drawOneArrow("arrow", pos1 , pos1 + a1 ,Eigen::Vector3d(0.1, 0.3,0.3), LCOLOR::GREEN, 0.6, "map", 1);
Livz::drawOneArrow("arrow", pos2 , pos2 + a2 ,Eigen::Vector3d(0.1, 0.3,0.3), LCOLOR::YELLOW, 0.6, "map", 2);
Livz::drawOneArrow("arrow", pos3 , pos3 + a3 ,Eigen::Vector3d(0.1, 0.3,0.3), LCOLOR::BLUE, 0.6, "map", 3);
if(duration < 60){return false;}
return true;
}
void demoUpdater()
{
// 绘制参数化曲线
Livz::drawParametricCurve("parametric_curve", sin3D, Eigen::Vector2d(0, 10), LCOLOR::GREEN);
// 通过updater实现小球沿曲线运动
Livz::addUpdater("task1", moveBallUpdater);
Livz::Delay( 10000 );
Livz::clearAll("parametric_curve");
// 结合updater和animate功能,实现水波扩散效果
Livz::addUpdater("task2", waveUpdater);
Livz::Delay( 15000 );
Livz::clearAll("circle");
// 三体运动1分钟
Livz::addUpdater("task3", threeBody);
}
|
import os
import numpy as np
import pandas as pd
import torch
from torch import cuda
from torch.utils.data import Dataset, DataLoader
from transformers import T5Tokenizer, T5ForConditionalGeneration
from rich.table import Column, Table
from rich import box
from rich.console import Console
console = Console(record=True)
def display_df(df):
"""display dataframe in ASCII format"""
console = Console()
table = Table(
Column("source_text", justify="center"),
Column("target_text", justify="center"),
title="Sample Data",
pad_edge=False,
box=box.ASCII,
)
for i, row in enumerate(df.values.tolist()):
table.add_row(row[0], row[1])
console.print(table)
training_logger = Table(
Column("Epoch", justify="center"),
Column("Steps", justify="center"),
Column("Loss", justify="center"),
title="Training Status",
pad_edge=False,
box=box.ASCII,
)
device = 'cuda' if cuda.is_available() else 'cpu'
class DataSet(Dataset):
def __init__(
self, dataframe, tokenizer, source_len, target_len, source_text, target_text
):
self.tokenizer = tokenizer
self.data = dataframe
self.source_len = source_len
self.summ_len = target_len
self.target_text = self.data[target_text]
self.source_text = self.data[source_text]
def __len__(self):
"""returns the length of dataframe"""
return len(self.target_text)
def __getitem__(self, index):
"""return the input ids, attention masks and target ids"""
source_text = str(self.source_text[index])
target_text = str(self.target_text[index])
source_text = " ".join(source_text.split())
target_text = " ".join(target_text.split())
source = self.tokenizer.batch_encode_plus(
[source_text],
max_length=self.source_len,
pad_to_max_length=True,
truncation=True,
padding="max_length",
return_tensors="pt",
)
target = self.tokenizer.batch_encode_plus(
[target_text],
max_length=self.summ_len,
pad_to_max_length=True,
truncation=True,
padding="max_length",
return_tensors="pt",
)
source_ids = source["input_ids"].squeeze()
source_mask = source["attention_mask"].squeeze()
target_ids = target["input_ids"].squeeze()
return {
"source_ids": source_ids.to(dtype=torch.long),
"source_mask": source_mask.to(dtype=torch.long),
"target_ids": target_ids.to(dtype=torch.long),
"target_ids_y": target_ids.to(dtype=torch.long),
}
def inference(epoch, tokenizer, model, device, loader):
"""
Function to evaluate model for predictions
"""
model.eval()
predictions = []
actuals = []
with torch.no_grad():
for _, data in enumerate(loader, 0):
y = data['target_ids'].to(device, dtype = torch.long)
ids = data['source_ids'].to(device, dtype = torch.long)
mask = data['source_mask'].to(device, dtype = torch.long)
generated_ids = model.generate(
input_ids = ids,
attention_mask = mask,
max_length=512,
num_beams=2,
repetition_penalty=10.0,
length_penalty=0.01,
early_stopping=True
)
preds = [tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=True) for g in generated_ids]
target = [tokenizer.decode(t, skip_special_tokens=True, clean_up_tokenization_spaces=True)for t in y]
if _%100==0:
console.print(f'Completed {_}')
lm_labels = y[:, 1:].clone().detach()
lm_labels[y[:, 1:] == tokenizer.pad_token_id] = -100
outputs = model(generated_ids, labels=lm_labels)
neg_log_likelihood = outputs[0]
ppl = torch.exp(neg_log_likelihood)
console.print(f'Perplexity {ppl}')
predictions.extend(preds)
actuals.extend(target)
return predictions, actuals
def T5Trainer(dataframe, source_text, target_text, model_params, output_dir="../outputs/t5_0608"):
torch.manual_seed(model_params["SEED"])
np.random.seed(model_params["SEED"])
torch.backends.cudnn.deterministic = True
console.log(f"""[Model]: Loading {model_params["MODEL"]}...\n""")
tokenizer = T5Tokenizer.from_pretrained(model_params["MODEL"])
tokenizer.add_tokens(['<section>'])
model = T5ForConditionalGeneration.from_pretrained(model_params["MODEL"])
model = model.to(device)
console.log(f"[Data]: Reading data...\n")
dataframe = dataframe[[source_text, target_text]]
# Defining the train size. So 90% of the data will be used for training and the rest for validation.
train_size = 0.9
train_dataset = dataframe.sample(frac=train_size, random_state=model_params["SEED"])
test_dataset = dataframe.drop(train_dataset.index).reset_index(drop=True)
display_df(test_dataset.head(2))
console.print(f"TEST Dataset: {test_dataset.shape}\n")
test_set = DataSet(
test_dataset,
tokenizer,
model_params["MAX_SOURCE_TEXT_LENGTH"],
model_params["MAX_TARGET_TEXT_LENGTH"],
source_text,
target_text,
)
titles = test_set.source_text
test_params = {
"batch_size": model_params["TEST_BATCH_SIZE"],
"shuffle": False,
"num_workers": 0,
}
test_loader = DataLoader(test_set, **test_params)
console.log(f"[Initiating Testing ON TEST SET]...\n")
for epoch in range(model_params["TEST_EPOCHS"]):
predictions, actuals = inference(epoch, tokenizer, model, device, test_loader)
final_df = pd.DataFrame({"Titles":titles, "Generated Text": predictions, "Actual Text": actuals})
final_df.to_csv(os.path.join(output_dir, "predictions0116.csv"))
console.save_text(os.path.join(output_dir, "logs.txt"))
console.log(f"[Testing Completed.]\n")
console.print(
f"""[Model] Model saved @ {os.path.join(output_dir, "model_files")}\n"""
)
console.print(
f"""[Validation] Generation on Validation data saved @ {os.path.join(output_dir,'predictions0116.csv')}\n"""
)
console.print(f"""[Logs] Logs saved @ {os.path.join(output_dir,'logs.txt')}\n""")
if __name__ == "__main__":
model_params = {
"MODEL": "../outputs/wikihow/model_files",
"TEST_BATCH_SIZE": 16,
"TEST_EPOCHS": 1,
"LEARNING_RATE": 1e-4,
"MAX_SOURCE_TEXT_LENGTH": 64,
"MAX_TARGET_TEXT_LENGTH": 512,
"SEED": 42,
}
path = "../data/wikihow/wikiwithPredictedSection.csv"
df = pd.read_csv(path)
df["title"] = "ask_question: " + df["title"]
df["method"] = "answer: "+df["method"]
T5Trainer(
dataframe=df,
source_text="title",
target_text="method",
model_params=model_params,
output_dir="../outputs/wikihow",
)
|
#ifndef TIMER_HEAP_HPP
#define TIMER_HEAP_HPP
#include <algorithm>
#include <functional>
#include <iostream>
#include <memory>
#include <vector>
using TimeoutCallback = std::function<void()>;
class Timer {
public:
Timer(int fd, int delay, const TimeoutCallback& cb)
{
this->fd = fd;
expire = time(nullptr) + delay;
timeoutCallback = cb;
}
~Timer() = default;
auto operator>(const Timer& other) const -> bool
{
return expire > other.expire;
}
[[nodiscard]] auto getExpire() const -> time_t
{
return expire;
}
void setExpire(time_t expire)
{
this->expire = expire;
}
void setTimeoutCallback(const TimeoutCallback& cb)
{
timeoutCallback = cb;
}
[[nodiscard]] auto getTimeoutCallback() const -> TimeoutCallback
{
return timeoutCallback;
}
[[nodiscard]] auto getFd() const -> int
{
return fd;
}
private:
int fd; //定时器对应的文件描述符
time_t expire; //任务的超时,单位为秒
TimeoutCallback timeoutCallback; //超时回调函数
};
class TimerHeap {
public:
TimerHeap() = default;
~TimerHeap() = default;
void addTimer(int fd, int delay, const TimeoutCallback& cb)
{
m_timerQueue.emplace_back(fd, delay, cb);
std::push_heap(
m_timerQueue.begin(), m_timerQueue.end(),
[](const auto& lhs, const auto& rhs) { return lhs > rhs; });
}
auto popTimer() -> Timer
{
auto timer = std::move(m_timerQueue.front());
std::pop_heap(
m_timerQueue.begin(), m_timerQueue.end(),
[](const auto& lhs, const auto& rhs) { return lhs > rhs; });
m_timerQueue.pop_back();
return timer;
}
void tick()
{
if (m_timerQueue.empty()) {
return;
}
while (!m_timerQueue.empty()) {
const Timer top = m_timerQueue.front();
if (top.getExpire() > time(nullptr)) {
break;
}
top.getTimeoutCallback()();
std::pop_heap(
m_timerQueue.begin(), m_timerQueue.end(),
[](const auto& lhs, const auto& rhs) { return lhs > rhs; });
m_timerQueue.pop_back();
}
}
auto getNextTick() -> size_t
{
return m_timerQueue.empty() ?
0 :
m_timerQueue.front().getExpire() - time(NULL);
}
void extentTimerExpire(int fd, int delay)
{
for (auto& timer : m_timerQueue) {
if (timer.getFd() == fd) {
timer.setExpire(time(nullptr) + delay);
std::make_heap(
m_timerQueue.begin(), m_timerQueue.end(),
[](const auto& lhs, const auto& rhs) { return lhs > rhs; });
break;
}
}
}
void print()
{
for (auto& timer : m_timerQueue) {
std::cout << timer.getFd() << " " << timer.getExpire() << std::endl;
}
}
private:
std::vector<Timer> m_timerQueue;
};
#endif
|
import React from "react";
import { useSelector } from "react-redux";
import { selectColor } from "../store/reducers";
const Card = ({ header, subheader, bodies, second_body, sub_body, second_sub_body }) => {
const color = useSelector(selectColor);
return (
<div
className={`w-5/6 md:w-2/3 lg:w-2/5 mt-4 border-2 border-${color}-300 dark:border-${color}-800 rounded-lg bg-${color}-50 dark:bg-${color}-300 p-3 shadow-2xl`}>
<div
className={`bg-${color}-200 shadow-lg rounded-lg mt-2 text-center text-${color}-800 dark:text-${color}-900 p-3 dark:bg-${color}-400`}>
<div className="text-2xl font-light md:text-4xl">{header}</div>
{subheader && <div className="text-lg italic font-light md:text-2xl md:text-xl">{subheader}</div>}
</div>
{bodies &&
bodies.map((body, index) => (
<div
key={`card-body-paragraph-${index}`}
className={`font-light text-base md:text-xl p-2 mt-2 text-${color}-800 dark:text-${color}-900`}>
{body}
</div>
))}
{sub_body && <div className={`font-bold text-sm md:text-lg p-2 text-${color}-800 dark:text-${color}-900`}>{sub_body}</div>}
{second_body && (
<div className={`font-light text-base md:text-xl p-2 mt-2 text-${color}-800 dark:text-${color}-900`}>{second_body}</div>
)}
{second_sub_body && (
<div className={`font-bold text-sm md:text-lg p-2 text-${color}-800 dark:text-${color}-900`}>{second_sub_body}</div>
)}
</div>
);
};
export default Card;
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'catelogue_id',
'name',
'slug',
'sku',
'img_thumbnail',
'price_regular',
'price_sale',
'description',
'content',
'material',
'user_manual',
'views',
'is_active',
'is_hot_deal',
'is_good_deal',
'is_new',
'is_show_home'
];
protected $casts = [
'is_active' => 'boolean',
'is_hot_deal' => 'boolean',
'is_good_deal' => 'boolean',
'is_new' => 'boolean',
'is_show_home' => 'boolean',
];
public function catelogue(){
return $this->belongsTo(Catelogue::class);
}
public function tags(){
return $this->belongsToMany(Tag::class);
}
public function galleries(){
return $this->hasMany(ProductGallery::class);
}
public function variant (){
return $this->hasMany(ProductVariant::class);
}
}
|
import React from 'react';
import styled from 'styled-components';
import {
MdAddCircleOutline,
MdPanoramaFishEye,
MdCheckCircle,
MdDelete,
MdOutlineEdit,
MdCheck,
} from 'react-icons/md';
import Skeleton from '@mui/material/Skeleton';
import Modal from '../../components/modal';
import { HTTP_URL } from '../../const';
const Container = styled.div`
width: 100%;
`;
// 상단 컨트롤 패널
const Control = styled.div`
width: 100%;
height: 50px;
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding: 0 10px;
`;
// 리스트 테이블 컨테이너
const Table = styled.div`
position: relative;
width: 100%;
height: 100%;
`;
// 테이블 헤더
const Header = styled.div`
width: 100%;
height: 40px;
text-align: center;
display: flex;
justify-content: space-around;
align-items: center;
font-size: 14px;
color: #777;
border-bottom: 1px solid #f2f2f2;
`;
// 상품 개별 아이템 컨테이너
const ItemStyle = styled.div`
width: 100%;
height: 60px;
background: #fff;
font-size: 14px;
font-weight: 400;
display: flex;
justify-content: space-around;
align-items: center;
text-align: center;
cursor: pointer;
&:hover {
background: #f2f2f2;
}
`;
// 상품 정보 컴포넌트
const Item = ({
number,
name,
price,
image,
description,
size,
checkedList,
setCheckedList,
}) => {
return (
<ItemStyle
onClick={() => {
// 만약 isCheck가 true이면 클릭이 된 상태에서 다시 체크해제하는 것이므로 상태배열에서 제거해야함
if (checkedList.filter((item) => item === name).length === 1) {
setCheckedList([...checkedList].filter((item) => item !== name));
} else {
setCheckedList([...checkedList, name]);
}
}}
>
<div style={{ width: '30px' }}>
{checkedList.filter((item) => item === name).length === 1 ? (
<MdCheckCircle size={15} color="#41B97F" />
) : (
<MdPanoramaFishEye size={15} color="#bcbcbc" />
)}
</div>
<div style={{ width: '30px' }}>{number}</div>
<div style={{ width: '150px' }}>{name}</div>
<div style={{ width: '100px' }}>{price}</div>
<div style={{ width: '150px' }}>{image}</div>
<div style={{ width: '200px' }}>{description}</div>
<div style={{ width: '100px' }}>{size}</div>
</ItemStyle>
);
};
// 상품 관리 전체 페이지 컴포넌트
const Admin1 = () => {
const [data, setData] = React.useState();
const [isDataLoading, setDataLoading] = React.useState(true);
const [checkedList, setCheckedList] = React.useState([]);
const [isModalOpen, setModalOpen] = React.useState(false);
const [isModifying, setModifying] = React.useState(false);
function GetItemData() {
fetch('https://3.36.96.63/fetchtest/fetchAll', {
method: 'GET',
})
.then((res) => res.json())
.then((json) => {
setData(json);
});
}
function RemoveItems() {
fetch(`${HTTP_URL}/fetchtest/deleteArray`, {
method: 'DELETE',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify({
deleteList: [...checkedList],
}),
}).then((res) => GetItemData());
}
// 서버에서 데이터 받아오기
React.useLayoutEffect(() => {
fetch(`${HTTP_URL}/fetchtest/fetchAll`, {
method: 'GET',
})
.then((res) => res.json())
.then((json) => {
console.log(json);
setData(json);
setDataLoading(false);
});
return () => {
setData();
setDataLoading(false);
};
}, []);
return (
<Container>
<Control>
<div
style={{ visibility: `${checkedList.length ? 'visible' : 'hidden'}` }}
>
<MdOutlineEdit
onClick={() => {
setModalOpen(true);
setModifying(true);
}}
style={{
display: `${checkedList.length === 1 ? 'inline-block' : 'none'}`,
cursor: 'pointer',
}}
size={20}
color="#686868"
/>
<MdDelete
onClick={() => {
// removeItem(checkedList, setCheckedList, data, setData)
RemoveItems();
}}
style={{ marginLeft: '10px', cursor: 'pointer' }}
size={20}
color="#686868"
/>
</div>
<div>
<MdAddCircleOutline
onClick={() => setModalOpen(true)}
style={{ cursor: 'pointer' }}
size={20}
color="#686868"
/>
</div>
</Control>
<Table>
<Header>
<div style={{ width: '30px' }}>
<MdCheck
style={{ cursor: 'pointer' }}
onClick={() => {
if (checkedList.length === data.length) {
setCheckedList([]);
} else {
setCheckedList([...data.map((item) => item.name)]);
}
}}
size={15}
color="#bcbcbc"
/>
</div>
<div style={{ width: '30px' }}>번호</div>
<div style={{ width: '150px' }}>상품명</div>
<div style={{ width: '100px' }}>가격</div>
<div style={{ width: '150px' }}>상품이미지</div>
<div style={{ width: '200px' }}>상세설명</div>
<div style={{ width: '100px' }}>사이즈</div>
</Header>
{!isDataLoading ? (
data.map((item, index) => {
return (
<Item
key={index}
number={index + 1}
name={item.name}
price={item.price}
image={item.image}
description={item.description}
size={item.size}
checkedList={checkedList}
setCheckedList={setCheckedList}
/>
);
})
) : (
<div>
<Skeleton
animation="wave"
variant="rectangular"
width="100%"
height={50}
style={{ marginBottom: '10px', borderRadius: '5px' }}
/>
<Skeleton
animation="wave"
variant="rectangular"
width="100%"
height={50}
style={{ marginBottom: '10px', borderRadius: '5px' }}
/>
<Skeleton
animation="wave"
variant="rectangular"
width="100%"
height={50}
style={{ borderRadius: '5px' }}
/>
</div>
)}
</Table>
{isModalOpen ? (
<Modal
givenData={
isModifying
? data.filter((item) => item.name === checkedList[0])
: undefined
}
setModifying={setModifying}
setModalOpen={setModalOpen}
GetItemData={GetItemData}
/>
) : undefined}
</Container>
);
};
export default Admin1;
|
package co.techlax.quoteapp.ui.theme.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import co.techlax.quoteapp.ui.theme.models.Quote
@Composable
fun QuoteListScreen(data: Array<Quote>, onClick: (quote: Quote) -> Unit) {
Box(
modifier = Modifier
.fillMaxSize()
.background(
Color.Black.copy(0.8f),
),
) {
Column {
Text(
text = "Quote App",
textAlign = TextAlign.Center,
modifier = Modifier
.padding(8.dp, 13.dp)
.fillMaxWidth(1f),
style = MaterialTheme.typography.headlineMedium,
fontFamily = FontFamily.Monospace,
color = Color.White, // White text color
)
QuoteList(data = data, onClick)
}
}
}
|
{% load static %}
<nav class="bg-white shadow" x-data="{ isOpen: false }">
<div
class="container px-6 py-4 mx-auto lg:flex lg:justify-between lg:items-center"
>
<div class="lg:flex lg:items-center">
<div class="flex items-center justify-between">
<div>
<a
class="text-2xl font-bold text-gray-800 transition-colors duration-200 transform lg:text-3xl hover:text-gray-700"
href="#"
>Brand</a
>
</div>
<!-- Mobile menu button -->
<div class="flex lg:hidden">
<button
type="button"
@click="isOpen = !isOpen"
class="text-gray-500 hover:text-gray-600 focus:outline-none focus:text-gray-600"
aria-label="toggle menu"
>
<svg viewBox="0 0 24 24" class="w-6 h-6 fill-current">
<path
fill-rule="evenodd"
d="M4 5h16a1 1 0 0 1 0 2H4a1 1 0 1 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2z"
></path>
</svg>
</button>
</div>
</div>
<div
:class="isOpen ? '' : 'hidden'"
class="flex flex-col text-gray-600 capitalize lg:flex lg:px-16 lg:-mx-4 lg:flex-row lg:items-center"
>
<a
href="#proceso"
class="mt-2 transition-colors duration-200 transform lg:mt-0 lg:mx-4 hover:text-gray-900"
>Proceso</a
>
<a
href="#diferenciador"
class="mt-2 transition-colors duration-200 transform lg:mt-0 lg:mx-4 hover:text-gray-900"
>Diferenciador</a
>
<a
href="#beneficios"
class="mt-2 transition-colors duration-200 transform lg:mt-0 lg:mx-4 hover:text-gray-900"
>Beneficios</a
>
</div>
</div>
<div
:class="isOpen ? 'show' : 'hidden'"
x-transition
class="flex justify-center mt-6 lg:flex lg:mt-0 lg:-mx-2"
>
<!-- Authenticated -->
{% if request.user.is_authenticated %}
<a
class="block w-1/2 px-3 py-2 mx-1 text-sm font-medium leading-5 text-center text-white transition-colors duration-200 transform bg-cyan-500 rounded-md hover:bg-cyan-600 md:mx-2 md:w-auto"
href="{% url 'home' %}"
>Ir a Inicio</a
>
{% else %}
<a
class="block w-1/2 px-3 py-2 mx-1 text-sm font-medium leading-5 text-center text-white transition-colors duration-200 transform bg-gray-500 rounded-md hover:bg-cyan-600 md:mx-2 md:w-auto"
href="{% url 'login' %}"
>Entrar</a
>
<a
class="block w-1/2 px-3 py-2 mx-1 text-sm font-medium leading-5 text-center text-white transition-colors duration-200 transform bg-cyan-500 rounded-md hover:bg-cyan-600 md:mx-0 md:w-auto"
href="{% url 'signup' %}"
>Crear Cuenta</a
>
{% endif %}
</div>
</div>
</nav>
|
import styled, { keyframes } from "styled-components";
import { colors } from "../../utils/colorPallete";
interface SquareContainerProps {
isClickable: boolean;
isWinningSquare: boolean;
value: string | null;
boardSize: number;
}
export const SquareContainer = styled.button<SquareContainerProps>`
background: ${colors.background};
font-size: 1.5vh;
max-height: calc(40vh / ${({ boardSize }) => boardSize});
/* overflow: hidden; */
font-weight: bold;
aspect-ratio: 1;
display: flex;
justify-content: center;
align-items: center;
border: 1px hidden white;
box-sizing: border-box;
width: 100%;
> div {
opacity: 1;
width: 90%;
margin: 0;
animation: ${({ isWinningSquare }) =>
isWinningSquare ? winningAnimation : null}
1.5s ease-in-out 0.4s forwards;
}
`;
const winningAnimation = keyframes`
0% {
transform: scale(1);
}
25% {
transform: scale(.5) rotate(-35deg) ;
}
75% {
transform: scale(1.1) rotate(720deg);
}
100% {
opacity: 1;
transform: scale(1) rotate(720deg);
}
`;
|
import { Suspense, useState } from "react";
import { Outlet } from "react-router-dom";
import Spinner from "../components/common/Spinner";
import Sidebar from "../components/navbarSideBar/Sidebar";
import Header from "../components/navbarSideBar/Header";
import Footer from "../components/common/Footer";
const DefaultLayout = () => {
const [sidebarOpen, setSidebarOpen] = useState(false);
return (
<>
<div className="dark:bg-boxdark-2 dark:text-bodydark">
<div className="flex h-screen overflow-hidden">
<Sidebar sidebarOpen={sidebarOpen} setSidebarOpen={setSidebarOpen} />
<div className="relative flex flex-1 flex-col overflow-y-auto overflow-x-hidden">
<Header sidebarOpen={sidebarOpen} setSidebarOpen={setSidebarOpen} />
<main>
<div className="mx-auto max-w-screen-2xl p-4 md:p-6 2xl:p-10">
<Suspense fallback={<Spinner />}>
<Outlet />
</Suspense>
{/* Stay Connected */}
<Footer />
</div>
</main>
</div>
</div>
</div>
</>
);
};
export default DefaultLayout;
|
const request = require("supertest");
const { app } = require("../../../setup/app");
const stateController = require("../../../../src/api/v1/state/controllers");
const stateServices = require("../../../../src/lib/state");
const { stateTestUrl, stateTestData } = require("../../../testSeed/state");
// Mock service methods
jest.mock("../../../../src/lib/state", () => ({
create: jest.fn(),
}));
// Set up route
app.post(stateTestUrl, stateController.create);
describe("State Controller", () => {
it("should create a new state", async () => {
// Mock the create method from your service to return a sample state
stateServices.create.mockResolvedValue(stateTestData);
const response = await request(app).post(stateTestUrl).send(stateTestData);
expect(response.statusCode).toBe(201);
expect(response.body.code).toBe(201);
expect(response.body.message).toBe("State Created Successfully");
expect(response.body.data).toEqual(stateTestData);
});
});
|
import 'dart:async';
import 'dart:ui';
import 'package:easy_localization/easy_localization.dart';
import 'package:firedart/firedart.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:watch_me/pages/home_page.dart';
import 'package:watch_me/pages/login_pages/sign_up.dart';
import 'package:watch_me/screens/loading_widget.dart';
class SignInPage extends StatefulWidget {
static const String id = "wv937547534h8n";
const SignInPage({Key? key}) : super(key: key);
@override
State<SignInPage> createState() => _SignInPageState();
}
class _SignInPageState extends State<SignInPage> {
var emailcontrol = TextEditingController();
var passwordcontrol = TextEditingController();
bool hidetext = true;
int index = 0;
List<String> images = [
"assets/images/img_1.png",
"assets/images/img.png",
"assets/images/img_3.png",
"assets/images/img_2.png",
];
void slideshow() {
Timer.periodic(const Duration(seconds: 3), (timer) {
if (index < images.length - 1) {
setState(() {
index++;
});
} else {
setState(() {
index = 0;
});
}
});
}
@override
void initState() {
// TODO: implement initState
super.initState();
slideshow();
}
final auth = FirebaseAuth.instance;
Future signIn() async {
showDialog(
context: context,
builder: (BuildContext context) {
return Container(
height: double.infinity,
width: double.infinity,
color: Colors.white24,
child: Center(
child: Loading.loading(),
),
);
});
final prefs = await SharedPreferences.getInstance();
String email = emailcontrol.text.trim();
String password = passwordcontrol.text.trim();
try {
await auth.signIn(email, password).then((value) {
prefs.setString("password", password);
prefs.setString("email", email);
prefs.setBool("logged", true);
setState(() {
prefs.setBool("logged", true);
});
Navigator.pop(context);
Navigator.pushReplacementNamed(context, HomePage.id);
});
} catch (e) {
// ignore: use_build_context_synchronously
Navigator.pop(context);
// ignore: use_build_context_synchronously
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
backgroundColor: Colors.red,
content: Text('Error! Check your password or email and try again'),
),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height * 1,
width: MediaQuery.of(context).size.width * 1,
decoration: BoxDecoration(
color: Colors.grey,
image: DecorationImage(
image: AssetImage(images[index]),
fit: BoxFit.cover,
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(
left: 16,
right: 16,
),
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: BackdropFilter(
filter: ImageFilter.blur(
sigmaX: 15,
sigmaY: 15,
),
child:Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(
left: 16, top: 12,
),
child: Text(
"signin".tr(),
style: const TextStyle(
color: Colors.white,
fontSize: 35,
fontWeight: FontWeight.bold,
),
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.01,
),
// glassmorphizm UI
Container(
margin: EdgeInsets.only(
left: MediaQuery.of(context).size.width * 0.02,
right: MediaQuery.of(context).size.width * 0.02,
),
height: MediaQuery.of(context).size.height * 0.36,
child: SizedBox(
width: double.infinity,
height: MediaQuery.of(context).size.height * 0.7,
child: Column(
children: [
SizedBox(
height: MediaQuery.of(context).size.height * 0.027,
),
// email
Container(
padding: const EdgeInsets.only(left: 14, right: 14),
height: MediaQuery.of(context).size.height * 0.068,
width: MediaQuery.of(context).size.width * 0.83,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(
7,
),
),
child: TextField(
showCursor: true,
cursorColor: Colors.red,
textAlign: TextAlign.start,
controller: emailcontrol,
//obscureText: false, textni yashirish
style: const TextStyle(
fontSize: 17,
),
textInputAction: TextInputAction.done,
decoration: InputDecoration(
hintText: "Email".tr(),
border: InputBorder.none,
hintStyle: TextStyle(
fontSize: 17,
color: Colors.grey[700],
),
),
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.022,
),
// password
Container(
padding: const EdgeInsets.only(left: 14, right: 14),
height: MediaQuery.of(context).size.height * 0.068,
width: MediaQuery.of(context).size.width * 0.83,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(7)),
child: TextField(
showCursor: true,
cursorColor: Colors.red,
textAlign: TextAlign.start,
controller: passwordcontrol,
obscureText: hidetext,
//textni yashirish
style: const TextStyle(
fontSize: 17,
),
textInputAction: TextInputAction.done,
decoration: InputDecoration(
suffixIcon: IconButton(
onPressed: () {
setState(() {
hidetext = !hidetext;
});
},
icon: hidetext
? const Icon(
Icons.visibility_off,
color: Colors.grey,
)
: const Icon(
Icons.visibility,
color: Colors.grey,
)),
hintText: "Password".tr(),
border: InputBorder.none,
hintStyle: TextStyle(
fontSize: 17,
color: Colors.grey[700],
),
),
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.022,
),
//continue
Container(
height: MediaQuery.of(context).size.height * 0.068,
width: MediaQuery.of(context).size.width * 0.83,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(
7,
),
),
child: TextButton(
onPressed: () {
signIn();
},
child: Text(
"Continue".tr(),
style: const TextStyle(
fontSize: 18,
color: Colors.white,
),
),
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.022,
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.03,
width: MediaQuery.of(context).size.width * 0.83,
// color: Colors.lightBlue,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"no_account".tr(),
style:const TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.w600,
),
),
const SizedBox(
width: 7,
),
GestureDetector(
onTap: () {
Navigator.pushReplacementNamed(
context,
SignUpPage.id,
);
},
child: Text(
"signup".tr(),
style: const TextStyle(
fontSize: 15,
color: Colors.red,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
],
),
),
//width: MediaQuery.of(context).size.width,
),
],
)
),
),
),
],
),
),
),
);
}
}
|
package io.github.jhipster.application.web.rest;
import io.github.jhipster.application.JhipsterSampleApplicationApp;
import io.github.jhipster.application.domain.ListNominalWallThickness;
import io.github.jhipster.application.domain.BendHist;
import io.github.jhipster.application.domain.BuckleArrestorHist;
import io.github.jhipster.application.domain.PipeHist;
import io.github.jhipster.application.domain.TeeHist;
import io.github.jhipster.application.domain.ValveHist;
import io.github.jhipster.application.repository.ListNominalWallThicknessRepository;
import io.github.jhipster.application.service.ListNominalWallThicknessService;
import io.github.jhipster.application.service.dto.ListNominalWallThicknessDTO;
import io.github.jhipster.application.service.mapper.ListNominalWallThicknessMapper;
import io.github.jhipster.application.web.rest.errors.ExceptionTranslator;
import io.github.jhipster.application.service.dto.ListNominalWallThicknessCriteria;
import io.github.jhipster.application.service.ListNominalWallThicknessQueryService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import static io.github.jhipster.application.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {@Link ListNominalWallThicknessResource} REST controller.
*/
@SpringBootTest(classes = JhipsterSampleApplicationApp.class)
public class ListNominalWallThicknessResourceIT {
private static final String DEFAULT_CODE = "AAAAAAAAAA";
private static final String UPDATED_CODE = "BBBBBBBBBB";
private static final String DEFAULT_NAME = "AAAAAAAAAA";
private static final String UPDATED_NAME = "BBBBBBBBBB";
private static final String DEFAULT_FULL_NAME = "AAAAAAAAAA";
private static final String UPDATED_FULL_NAME = "BBBBBBBBBB";
private static final Integer DEFAULT_IS_CURRENT_FLAG = 1;
private static final Integer UPDATED_IS_CURRENT_FLAG = 2;
private static final String DEFAULT_DESCRIPTION = "AAAAAAAAAA";
private static final String UPDATED_DESCRIPTION = "BBBBBBBBBB";
private static final Instant DEFAULT_DATE_CREATE = Instant.ofEpochMilli(0L);
private static final Instant UPDATED_DATE_CREATE = Instant.now().truncatedTo(ChronoUnit.MILLIS);
private static final Instant DEFAULT_DATE_EDIT = Instant.ofEpochMilli(0L);
private static final Instant UPDATED_DATE_EDIT = Instant.now().truncatedTo(ChronoUnit.MILLIS);
private static final String DEFAULT_CREATOR = "AAAAAAAAAA";
private static final String UPDATED_CREATOR = "BBBBBBBBBB";
private static final String DEFAULT_EDITOR = "AAAAAAAAAA";
private static final String UPDATED_EDITOR = "BBBBBBBBBB";
@Autowired
private ListNominalWallThicknessRepository listNominalWallThicknessRepository;
@Autowired
private ListNominalWallThicknessMapper listNominalWallThicknessMapper;
@Autowired
private ListNominalWallThicknessService listNominalWallThicknessService;
@Autowired
private ListNominalWallThicknessQueryService listNominalWallThicknessQueryService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private Validator validator;
private MockMvc restListNominalWallThicknessMockMvc;
private ListNominalWallThickness listNominalWallThickness;
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
final ListNominalWallThicknessResource listNominalWallThicknessResource = new ListNominalWallThicknessResource(listNominalWallThicknessService, listNominalWallThicknessQueryService);
this.restListNominalWallThicknessMockMvc = MockMvcBuilders.standaloneSetup(listNominalWallThicknessResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static ListNominalWallThickness createEntity(EntityManager em) {
ListNominalWallThickness listNominalWallThickness = new ListNominalWallThickness()
.code(DEFAULT_CODE)
.name(DEFAULT_NAME)
.fullName(DEFAULT_FULL_NAME)
.isCurrentFlag(DEFAULT_IS_CURRENT_FLAG)
.description(DEFAULT_DESCRIPTION)
.dateCreate(DEFAULT_DATE_CREATE)
.dateEdit(DEFAULT_DATE_EDIT)
.creator(DEFAULT_CREATOR)
.editor(DEFAULT_EDITOR);
return listNominalWallThickness;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static ListNominalWallThickness createUpdatedEntity(EntityManager em) {
ListNominalWallThickness listNominalWallThickness = new ListNominalWallThickness()
.code(UPDATED_CODE)
.name(UPDATED_NAME)
.fullName(UPDATED_FULL_NAME)
.isCurrentFlag(UPDATED_IS_CURRENT_FLAG)
.description(UPDATED_DESCRIPTION)
.dateCreate(UPDATED_DATE_CREATE)
.dateEdit(UPDATED_DATE_EDIT)
.creator(UPDATED_CREATOR)
.editor(UPDATED_EDITOR);
return listNominalWallThickness;
}
@BeforeEach
public void initTest() {
listNominalWallThickness = createEntity(em);
}
@Test
@Transactional
public void createListNominalWallThickness() throws Exception {
int databaseSizeBeforeCreate = listNominalWallThicknessRepository.findAll().size();
// Create the ListNominalWallThickness
ListNominalWallThicknessDTO listNominalWallThicknessDTO = listNominalWallThicknessMapper.toDto(listNominalWallThickness);
restListNominalWallThicknessMockMvc.perform(post("/api/list-nominal-wall-thicknesses")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(listNominalWallThicknessDTO)))
.andExpect(status().isCreated());
// Validate the ListNominalWallThickness in the database
List<ListNominalWallThickness> listNominalWallThicknessList = listNominalWallThicknessRepository.findAll();
assertThat(listNominalWallThicknessList).hasSize(databaseSizeBeforeCreate + 1);
ListNominalWallThickness testListNominalWallThickness = listNominalWallThicknessList.get(listNominalWallThicknessList.size() - 1);
assertThat(testListNominalWallThickness.getCode()).isEqualTo(DEFAULT_CODE);
assertThat(testListNominalWallThickness.getName()).isEqualTo(DEFAULT_NAME);
assertThat(testListNominalWallThickness.getFullName()).isEqualTo(DEFAULT_FULL_NAME);
assertThat(testListNominalWallThickness.getIsCurrentFlag()).isEqualTo(DEFAULT_IS_CURRENT_FLAG);
assertThat(testListNominalWallThickness.getDescription()).isEqualTo(DEFAULT_DESCRIPTION);
assertThat(testListNominalWallThickness.getDateCreate()).isEqualTo(DEFAULT_DATE_CREATE);
assertThat(testListNominalWallThickness.getDateEdit()).isEqualTo(DEFAULT_DATE_EDIT);
assertThat(testListNominalWallThickness.getCreator()).isEqualTo(DEFAULT_CREATOR);
assertThat(testListNominalWallThickness.getEditor()).isEqualTo(DEFAULT_EDITOR);
}
@Test
@Transactional
public void createListNominalWallThicknessWithExistingId() throws Exception {
int databaseSizeBeforeCreate = listNominalWallThicknessRepository.findAll().size();
// Create the ListNominalWallThickness with an existing ID
listNominalWallThickness.setId(1L);
ListNominalWallThicknessDTO listNominalWallThicknessDTO = listNominalWallThicknessMapper.toDto(listNominalWallThickness);
// An entity with an existing ID cannot be created, so this API call must fail
restListNominalWallThicknessMockMvc.perform(post("/api/list-nominal-wall-thicknesses")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(listNominalWallThicknessDTO)))
.andExpect(status().isBadRequest());
// Validate the ListNominalWallThickness in the database
List<ListNominalWallThickness> listNominalWallThicknessList = listNominalWallThicknessRepository.findAll();
assertThat(listNominalWallThicknessList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void checkCodeIsRequired() throws Exception {
int databaseSizeBeforeTest = listNominalWallThicknessRepository.findAll().size();
// set the field null
listNominalWallThickness.setCode(null);
// Create the ListNominalWallThickness, which fails.
ListNominalWallThicknessDTO listNominalWallThicknessDTO = listNominalWallThicknessMapper.toDto(listNominalWallThickness);
restListNominalWallThicknessMockMvc.perform(post("/api/list-nominal-wall-thicknesses")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(listNominalWallThicknessDTO)))
.andExpect(status().isBadRequest());
List<ListNominalWallThickness> listNominalWallThicknessList = listNominalWallThicknessRepository.findAll();
assertThat(listNominalWallThicknessList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkNameIsRequired() throws Exception {
int databaseSizeBeforeTest = listNominalWallThicknessRepository.findAll().size();
// set the field null
listNominalWallThickness.setName(null);
// Create the ListNominalWallThickness, which fails.
ListNominalWallThicknessDTO listNominalWallThicknessDTO = listNominalWallThicknessMapper.toDto(listNominalWallThickness);
restListNominalWallThicknessMockMvc.perform(post("/api/list-nominal-wall-thicknesses")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(listNominalWallThicknessDTO)))
.andExpect(status().isBadRequest());
List<ListNominalWallThickness> listNominalWallThicknessList = listNominalWallThicknessRepository.findAll();
assertThat(listNominalWallThicknessList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkFullNameIsRequired() throws Exception {
int databaseSizeBeforeTest = listNominalWallThicknessRepository.findAll().size();
// set the field null
listNominalWallThickness.setFullName(null);
// Create the ListNominalWallThickness, which fails.
ListNominalWallThicknessDTO listNominalWallThicknessDTO = listNominalWallThicknessMapper.toDto(listNominalWallThickness);
restListNominalWallThicknessMockMvc.perform(post("/api/list-nominal-wall-thicknesses")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(listNominalWallThicknessDTO)))
.andExpect(status().isBadRequest());
List<ListNominalWallThickness> listNominalWallThicknessList = listNominalWallThicknessRepository.findAll();
assertThat(listNominalWallThicknessList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkIsCurrentFlagIsRequired() throws Exception {
int databaseSizeBeforeTest = listNominalWallThicknessRepository.findAll().size();
// set the field null
listNominalWallThickness.setIsCurrentFlag(null);
// Create the ListNominalWallThickness, which fails.
ListNominalWallThicknessDTO listNominalWallThicknessDTO = listNominalWallThicknessMapper.toDto(listNominalWallThickness);
restListNominalWallThicknessMockMvc.perform(post("/api/list-nominal-wall-thicknesses")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(listNominalWallThicknessDTO)))
.andExpect(status().isBadRequest());
List<ListNominalWallThickness> listNominalWallThicknessList = listNominalWallThicknessRepository.findAll();
assertThat(listNominalWallThicknessList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllListNominalWallThicknesses() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList
restListNominalWallThicknessMockMvc.perform(get("/api/list-nominal-wall-thicknesses?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(listNominalWallThickness.getId().intValue())))
.andExpect(jsonPath("$.[*].code").value(hasItem(DEFAULT_CODE.toString())))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString())))
.andExpect(jsonPath("$.[*].fullName").value(hasItem(DEFAULT_FULL_NAME.toString())))
.andExpect(jsonPath("$.[*].isCurrentFlag").value(hasItem(DEFAULT_IS_CURRENT_FLAG)))
.andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION.toString())))
.andExpect(jsonPath("$.[*].dateCreate").value(hasItem(DEFAULT_DATE_CREATE.toString())))
.andExpect(jsonPath("$.[*].dateEdit").value(hasItem(DEFAULT_DATE_EDIT.toString())))
.andExpect(jsonPath("$.[*].creator").value(hasItem(DEFAULT_CREATOR.toString())))
.andExpect(jsonPath("$.[*].editor").value(hasItem(DEFAULT_EDITOR.toString())));
}
@Test
@Transactional
public void getListNominalWallThickness() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get the listNominalWallThickness
restListNominalWallThicknessMockMvc.perform(get("/api/list-nominal-wall-thicknesses/{id}", listNominalWallThickness.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(listNominalWallThickness.getId().intValue()))
.andExpect(jsonPath("$.code").value(DEFAULT_CODE.toString()))
.andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString()))
.andExpect(jsonPath("$.fullName").value(DEFAULT_FULL_NAME.toString()))
.andExpect(jsonPath("$.isCurrentFlag").value(DEFAULT_IS_CURRENT_FLAG))
.andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString()))
.andExpect(jsonPath("$.dateCreate").value(DEFAULT_DATE_CREATE.toString()))
.andExpect(jsonPath("$.dateEdit").value(DEFAULT_DATE_EDIT.toString()))
.andExpect(jsonPath("$.creator").value(DEFAULT_CREATOR.toString()))
.andExpect(jsonPath("$.editor").value(DEFAULT_EDITOR.toString()));
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByCodeIsEqualToSomething() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where code equals to DEFAULT_CODE
defaultListNominalWallThicknessShouldBeFound("code.equals=" + DEFAULT_CODE);
// Get all the listNominalWallThicknessList where code equals to UPDATED_CODE
defaultListNominalWallThicknessShouldNotBeFound("code.equals=" + UPDATED_CODE);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByCodeIsInShouldWork() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where code in DEFAULT_CODE or UPDATED_CODE
defaultListNominalWallThicknessShouldBeFound("code.in=" + DEFAULT_CODE + "," + UPDATED_CODE);
// Get all the listNominalWallThicknessList where code equals to UPDATED_CODE
defaultListNominalWallThicknessShouldNotBeFound("code.in=" + UPDATED_CODE);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByCodeIsNullOrNotNull() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where code is not null
defaultListNominalWallThicknessShouldBeFound("code.specified=true");
// Get all the listNominalWallThicknessList where code is null
defaultListNominalWallThicknessShouldNotBeFound("code.specified=false");
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByNameIsEqualToSomething() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where name equals to DEFAULT_NAME
defaultListNominalWallThicknessShouldBeFound("name.equals=" + DEFAULT_NAME);
// Get all the listNominalWallThicknessList where name equals to UPDATED_NAME
defaultListNominalWallThicknessShouldNotBeFound("name.equals=" + UPDATED_NAME);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByNameIsInShouldWork() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where name in DEFAULT_NAME or UPDATED_NAME
defaultListNominalWallThicknessShouldBeFound("name.in=" + DEFAULT_NAME + "," + UPDATED_NAME);
// Get all the listNominalWallThicknessList where name equals to UPDATED_NAME
defaultListNominalWallThicknessShouldNotBeFound("name.in=" + UPDATED_NAME);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByNameIsNullOrNotNull() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where name is not null
defaultListNominalWallThicknessShouldBeFound("name.specified=true");
// Get all the listNominalWallThicknessList where name is null
defaultListNominalWallThicknessShouldNotBeFound("name.specified=false");
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByFullNameIsEqualToSomething() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where fullName equals to DEFAULT_FULL_NAME
defaultListNominalWallThicknessShouldBeFound("fullName.equals=" + DEFAULT_FULL_NAME);
// Get all the listNominalWallThicknessList where fullName equals to UPDATED_FULL_NAME
defaultListNominalWallThicknessShouldNotBeFound("fullName.equals=" + UPDATED_FULL_NAME);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByFullNameIsInShouldWork() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where fullName in DEFAULT_FULL_NAME or UPDATED_FULL_NAME
defaultListNominalWallThicknessShouldBeFound("fullName.in=" + DEFAULT_FULL_NAME + "," + UPDATED_FULL_NAME);
// Get all the listNominalWallThicknessList where fullName equals to UPDATED_FULL_NAME
defaultListNominalWallThicknessShouldNotBeFound("fullName.in=" + UPDATED_FULL_NAME);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByFullNameIsNullOrNotNull() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where fullName is not null
defaultListNominalWallThicknessShouldBeFound("fullName.specified=true");
// Get all the listNominalWallThicknessList where fullName is null
defaultListNominalWallThicknessShouldNotBeFound("fullName.specified=false");
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByIsCurrentFlagIsEqualToSomething() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where isCurrentFlag equals to DEFAULT_IS_CURRENT_FLAG
defaultListNominalWallThicknessShouldBeFound("isCurrentFlag.equals=" + DEFAULT_IS_CURRENT_FLAG);
// Get all the listNominalWallThicknessList where isCurrentFlag equals to UPDATED_IS_CURRENT_FLAG
defaultListNominalWallThicknessShouldNotBeFound("isCurrentFlag.equals=" + UPDATED_IS_CURRENT_FLAG);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByIsCurrentFlagIsInShouldWork() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where isCurrentFlag in DEFAULT_IS_CURRENT_FLAG or UPDATED_IS_CURRENT_FLAG
defaultListNominalWallThicknessShouldBeFound("isCurrentFlag.in=" + DEFAULT_IS_CURRENT_FLAG + "," + UPDATED_IS_CURRENT_FLAG);
// Get all the listNominalWallThicknessList where isCurrentFlag equals to UPDATED_IS_CURRENT_FLAG
defaultListNominalWallThicknessShouldNotBeFound("isCurrentFlag.in=" + UPDATED_IS_CURRENT_FLAG);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByIsCurrentFlagIsNullOrNotNull() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where isCurrentFlag is not null
defaultListNominalWallThicknessShouldBeFound("isCurrentFlag.specified=true");
// Get all the listNominalWallThicknessList where isCurrentFlag is null
defaultListNominalWallThicknessShouldNotBeFound("isCurrentFlag.specified=false");
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByIsCurrentFlagIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where isCurrentFlag greater than or equals to DEFAULT_IS_CURRENT_FLAG
defaultListNominalWallThicknessShouldBeFound("isCurrentFlag.greaterOrEqualThan=" + DEFAULT_IS_CURRENT_FLAG);
// Get all the listNominalWallThicknessList where isCurrentFlag greater than or equals to UPDATED_IS_CURRENT_FLAG
defaultListNominalWallThicknessShouldNotBeFound("isCurrentFlag.greaterOrEqualThan=" + UPDATED_IS_CURRENT_FLAG);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByIsCurrentFlagIsLessThanSomething() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where isCurrentFlag less than or equals to DEFAULT_IS_CURRENT_FLAG
defaultListNominalWallThicknessShouldNotBeFound("isCurrentFlag.lessThan=" + DEFAULT_IS_CURRENT_FLAG);
// Get all the listNominalWallThicknessList where isCurrentFlag less than or equals to UPDATED_IS_CURRENT_FLAG
defaultListNominalWallThicknessShouldBeFound("isCurrentFlag.lessThan=" + UPDATED_IS_CURRENT_FLAG);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByDescriptionIsEqualToSomething() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where description equals to DEFAULT_DESCRIPTION
defaultListNominalWallThicknessShouldBeFound("description.equals=" + DEFAULT_DESCRIPTION);
// Get all the listNominalWallThicknessList where description equals to UPDATED_DESCRIPTION
defaultListNominalWallThicknessShouldNotBeFound("description.equals=" + UPDATED_DESCRIPTION);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByDescriptionIsInShouldWork() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where description in DEFAULT_DESCRIPTION or UPDATED_DESCRIPTION
defaultListNominalWallThicknessShouldBeFound("description.in=" + DEFAULT_DESCRIPTION + "," + UPDATED_DESCRIPTION);
// Get all the listNominalWallThicknessList where description equals to UPDATED_DESCRIPTION
defaultListNominalWallThicknessShouldNotBeFound("description.in=" + UPDATED_DESCRIPTION);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByDescriptionIsNullOrNotNull() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where description is not null
defaultListNominalWallThicknessShouldBeFound("description.specified=true");
// Get all the listNominalWallThicknessList where description is null
defaultListNominalWallThicknessShouldNotBeFound("description.specified=false");
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByDateCreateIsEqualToSomething() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where dateCreate equals to DEFAULT_DATE_CREATE
defaultListNominalWallThicknessShouldBeFound("dateCreate.equals=" + DEFAULT_DATE_CREATE);
// Get all the listNominalWallThicknessList where dateCreate equals to UPDATED_DATE_CREATE
defaultListNominalWallThicknessShouldNotBeFound("dateCreate.equals=" + UPDATED_DATE_CREATE);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByDateCreateIsInShouldWork() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where dateCreate in DEFAULT_DATE_CREATE or UPDATED_DATE_CREATE
defaultListNominalWallThicknessShouldBeFound("dateCreate.in=" + DEFAULT_DATE_CREATE + "," + UPDATED_DATE_CREATE);
// Get all the listNominalWallThicknessList where dateCreate equals to UPDATED_DATE_CREATE
defaultListNominalWallThicknessShouldNotBeFound("dateCreate.in=" + UPDATED_DATE_CREATE);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByDateCreateIsNullOrNotNull() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where dateCreate is not null
defaultListNominalWallThicknessShouldBeFound("dateCreate.specified=true");
// Get all the listNominalWallThicknessList where dateCreate is null
defaultListNominalWallThicknessShouldNotBeFound("dateCreate.specified=false");
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByDateEditIsEqualToSomething() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where dateEdit equals to DEFAULT_DATE_EDIT
defaultListNominalWallThicknessShouldBeFound("dateEdit.equals=" + DEFAULT_DATE_EDIT);
// Get all the listNominalWallThicknessList where dateEdit equals to UPDATED_DATE_EDIT
defaultListNominalWallThicknessShouldNotBeFound("dateEdit.equals=" + UPDATED_DATE_EDIT);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByDateEditIsInShouldWork() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where dateEdit in DEFAULT_DATE_EDIT or UPDATED_DATE_EDIT
defaultListNominalWallThicknessShouldBeFound("dateEdit.in=" + DEFAULT_DATE_EDIT + "," + UPDATED_DATE_EDIT);
// Get all the listNominalWallThicknessList where dateEdit equals to UPDATED_DATE_EDIT
defaultListNominalWallThicknessShouldNotBeFound("dateEdit.in=" + UPDATED_DATE_EDIT);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByDateEditIsNullOrNotNull() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where dateEdit is not null
defaultListNominalWallThicknessShouldBeFound("dateEdit.specified=true");
// Get all the listNominalWallThicknessList where dateEdit is null
defaultListNominalWallThicknessShouldNotBeFound("dateEdit.specified=false");
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByCreatorIsEqualToSomething() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where creator equals to DEFAULT_CREATOR
defaultListNominalWallThicknessShouldBeFound("creator.equals=" + DEFAULT_CREATOR);
// Get all the listNominalWallThicknessList where creator equals to UPDATED_CREATOR
defaultListNominalWallThicknessShouldNotBeFound("creator.equals=" + UPDATED_CREATOR);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByCreatorIsInShouldWork() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where creator in DEFAULT_CREATOR or UPDATED_CREATOR
defaultListNominalWallThicknessShouldBeFound("creator.in=" + DEFAULT_CREATOR + "," + UPDATED_CREATOR);
// Get all the listNominalWallThicknessList where creator equals to UPDATED_CREATOR
defaultListNominalWallThicknessShouldNotBeFound("creator.in=" + UPDATED_CREATOR);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByCreatorIsNullOrNotNull() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where creator is not null
defaultListNominalWallThicknessShouldBeFound("creator.specified=true");
// Get all the listNominalWallThicknessList where creator is null
defaultListNominalWallThicknessShouldNotBeFound("creator.specified=false");
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByEditorIsEqualToSomething() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where editor equals to DEFAULT_EDITOR
defaultListNominalWallThicknessShouldBeFound("editor.equals=" + DEFAULT_EDITOR);
// Get all the listNominalWallThicknessList where editor equals to UPDATED_EDITOR
defaultListNominalWallThicknessShouldNotBeFound("editor.equals=" + UPDATED_EDITOR);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByEditorIsInShouldWork() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where editor in DEFAULT_EDITOR or UPDATED_EDITOR
defaultListNominalWallThicknessShouldBeFound("editor.in=" + DEFAULT_EDITOR + "," + UPDATED_EDITOR);
// Get all the listNominalWallThicknessList where editor equals to UPDATED_EDITOR
defaultListNominalWallThicknessShouldNotBeFound("editor.in=" + UPDATED_EDITOR);
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByEditorIsNullOrNotNull() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
// Get all the listNominalWallThicknessList where editor is not null
defaultListNominalWallThicknessShouldBeFound("editor.specified=true");
// Get all the listNominalWallThicknessList where editor is null
defaultListNominalWallThicknessShouldNotBeFound("editor.specified=false");
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByBendHistIsEqualToSomething() throws Exception {
// Initialize the database
BendHist bendHist = BendHistResourceIT.createEntity(em);
em.persist(bendHist);
em.flush();
listNominalWallThickness.addBendHist(bendHist);
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
Long bendHistId = bendHist.getId();
// Get all the listNominalWallThicknessList where bendHist equals to bendHistId
defaultListNominalWallThicknessShouldBeFound("bendHistId.equals=" + bendHistId);
// Get all the listNominalWallThicknessList where bendHist equals to bendHistId + 1
defaultListNominalWallThicknessShouldNotBeFound("bendHistId.equals=" + (bendHistId + 1));
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByBuckleArrestorHistIsEqualToSomething() throws Exception {
// Initialize the database
BuckleArrestorHist buckleArrestorHist = BuckleArrestorHistResourceIT.createEntity(em);
em.persist(buckleArrestorHist);
em.flush();
listNominalWallThickness.addBuckleArrestorHist(buckleArrestorHist);
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
Long buckleArrestorHistId = buckleArrestorHist.getId();
// Get all the listNominalWallThicknessList where buckleArrestorHist equals to buckleArrestorHistId
defaultListNominalWallThicknessShouldBeFound("buckleArrestorHistId.equals=" + buckleArrestorHistId);
// Get all the listNominalWallThicknessList where buckleArrestorHist equals to buckleArrestorHistId + 1
defaultListNominalWallThicknessShouldNotBeFound("buckleArrestorHistId.equals=" + (buckleArrestorHistId + 1));
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByPipeHistIsEqualToSomething() throws Exception {
// Initialize the database
PipeHist pipeHist = PipeHistResourceIT.createEntity(em);
em.persist(pipeHist);
em.flush();
listNominalWallThickness.addPipeHist(pipeHist);
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
Long pipeHistId = pipeHist.getId();
// Get all the listNominalWallThicknessList where pipeHist equals to pipeHistId
defaultListNominalWallThicknessShouldBeFound("pipeHistId.equals=" + pipeHistId);
// Get all the listNominalWallThicknessList where pipeHist equals to pipeHistId + 1
defaultListNominalWallThicknessShouldNotBeFound("pipeHistId.equals=" + (pipeHistId + 1));
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByTeeHistIsEqualToSomething() throws Exception {
// Initialize the database
TeeHist teeHist = TeeHistResourceIT.createEntity(em);
em.persist(teeHist);
em.flush();
listNominalWallThickness.addTeeHist(teeHist);
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
Long teeHistId = teeHist.getId();
// Get all the listNominalWallThicknessList where teeHist equals to teeHistId
defaultListNominalWallThicknessShouldBeFound("teeHistId.equals=" + teeHistId);
// Get all the listNominalWallThicknessList where teeHist equals to teeHistId + 1
defaultListNominalWallThicknessShouldNotBeFound("teeHistId.equals=" + (teeHistId + 1));
}
@Test
@Transactional
public void getAllListNominalWallThicknessesByValveHistIsEqualToSomething() throws Exception {
// Initialize the database
ValveHist valveHist = ValveHistResourceIT.createEntity(em);
em.persist(valveHist);
em.flush();
listNominalWallThickness.addValveHist(valveHist);
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
Long valveHistId = valveHist.getId();
// Get all the listNominalWallThicknessList where valveHist equals to valveHistId
defaultListNominalWallThicknessShouldBeFound("valveHistId.equals=" + valveHistId);
// Get all the listNominalWallThicknessList where valveHist equals to valveHistId + 1
defaultListNominalWallThicknessShouldNotBeFound("valveHistId.equals=" + (valveHistId + 1));
}
/**
* Executes the search, and checks that the default entity is returned.
*/
private void defaultListNominalWallThicknessShouldBeFound(String filter) throws Exception {
restListNominalWallThicknessMockMvc.perform(get("/api/list-nominal-wall-thicknesses?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(listNominalWallThickness.getId().intValue())))
.andExpect(jsonPath("$.[*].code").value(hasItem(DEFAULT_CODE)))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
.andExpect(jsonPath("$.[*].fullName").value(hasItem(DEFAULT_FULL_NAME)))
.andExpect(jsonPath("$.[*].isCurrentFlag").value(hasItem(DEFAULT_IS_CURRENT_FLAG)))
.andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION)))
.andExpect(jsonPath("$.[*].dateCreate").value(hasItem(DEFAULT_DATE_CREATE.toString())))
.andExpect(jsonPath("$.[*].dateEdit").value(hasItem(DEFAULT_DATE_EDIT.toString())))
.andExpect(jsonPath("$.[*].creator").value(hasItem(DEFAULT_CREATOR)))
.andExpect(jsonPath("$.[*].editor").value(hasItem(DEFAULT_EDITOR)));
// Check, that the count call also returns 1
restListNominalWallThicknessMockMvc.perform(get("/api/list-nominal-wall-thicknesses/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
* Executes the search, and checks that the default entity is not returned.
*/
private void defaultListNominalWallThicknessShouldNotBeFound(String filter) throws Exception {
restListNominalWallThicknessMockMvc.perform(get("/api/list-nominal-wall-thicknesses?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
// Check, that the count call also returns 0
restListNominalWallThicknessMockMvc.perform(get("/api/list-nominal-wall-thicknesses/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("0"));
}
@Test
@Transactional
public void getNonExistingListNominalWallThickness() throws Exception {
// Get the listNominalWallThickness
restListNominalWallThicknessMockMvc.perform(get("/api/list-nominal-wall-thicknesses/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateListNominalWallThickness() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
int databaseSizeBeforeUpdate = listNominalWallThicknessRepository.findAll().size();
// Update the listNominalWallThickness
ListNominalWallThickness updatedListNominalWallThickness = listNominalWallThicknessRepository.findById(listNominalWallThickness.getId()).get();
// Disconnect from session so that the updates on updatedListNominalWallThickness are not directly saved in db
em.detach(updatedListNominalWallThickness);
updatedListNominalWallThickness
.code(UPDATED_CODE)
.name(UPDATED_NAME)
.fullName(UPDATED_FULL_NAME)
.isCurrentFlag(UPDATED_IS_CURRENT_FLAG)
.description(UPDATED_DESCRIPTION)
.dateCreate(UPDATED_DATE_CREATE)
.dateEdit(UPDATED_DATE_EDIT)
.creator(UPDATED_CREATOR)
.editor(UPDATED_EDITOR);
ListNominalWallThicknessDTO listNominalWallThicknessDTO = listNominalWallThicknessMapper.toDto(updatedListNominalWallThickness);
restListNominalWallThicknessMockMvc.perform(put("/api/list-nominal-wall-thicknesses")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(listNominalWallThicknessDTO)))
.andExpect(status().isOk());
// Validate the ListNominalWallThickness in the database
List<ListNominalWallThickness> listNominalWallThicknessList = listNominalWallThicknessRepository.findAll();
assertThat(listNominalWallThicknessList).hasSize(databaseSizeBeforeUpdate);
ListNominalWallThickness testListNominalWallThickness = listNominalWallThicknessList.get(listNominalWallThicknessList.size() - 1);
assertThat(testListNominalWallThickness.getCode()).isEqualTo(UPDATED_CODE);
assertThat(testListNominalWallThickness.getName()).isEqualTo(UPDATED_NAME);
assertThat(testListNominalWallThickness.getFullName()).isEqualTo(UPDATED_FULL_NAME);
assertThat(testListNominalWallThickness.getIsCurrentFlag()).isEqualTo(UPDATED_IS_CURRENT_FLAG);
assertThat(testListNominalWallThickness.getDescription()).isEqualTo(UPDATED_DESCRIPTION);
assertThat(testListNominalWallThickness.getDateCreate()).isEqualTo(UPDATED_DATE_CREATE);
assertThat(testListNominalWallThickness.getDateEdit()).isEqualTo(UPDATED_DATE_EDIT);
assertThat(testListNominalWallThickness.getCreator()).isEqualTo(UPDATED_CREATOR);
assertThat(testListNominalWallThickness.getEditor()).isEqualTo(UPDATED_EDITOR);
}
@Test
@Transactional
public void updateNonExistingListNominalWallThickness() throws Exception {
int databaseSizeBeforeUpdate = listNominalWallThicknessRepository.findAll().size();
// Create the ListNominalWallThickness
ListNominalWallThicknessDTO listNominalWallThicknessDTO = listNominalWallThicknessMapper.toDto(listNominalWallThickness);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restListNominalWallThicknessMockMvc.perform(put("/api/list-nominal-wall-thicknesses")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(listNominalWallThicknessDTO)))
.andExpect(status().isBadRequest());
// Validate the ListNominalWallThickness in the database
List<ListNominalWallThickness> listNominalWallThicknessList = listNominalWallThicknessRepository.findAll();
assertThat(listNominalWallThicknessList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteListNominalWallThickness() throws Exception {
// Initialize the database
listNominalWallThicknessRepository.saveAndFlush(listNominalWallThickness);
int databaseSizeBeforeDelete = listNominalWallThicknessRepository.findAll().size();
// Delete the listNominalWallThickness
restListNominalWallThicknessMockMvc.perform(delete("/api/list-nominal-wall-thicknesses/{id}", listNominalWallThickness.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isNoContent());
// Validate the database is empty
List<ListNominalWallThickness> listNominalWallThicknessList = listNominalWallThicknessRepository.findAll();
assertThat(listNominalWallThicknessList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(ListNominalWallThickness.class);
ListNominalWallThickness listNominalWallThickness1 = new ListNominalWallThickness();
listNominalWallThickness1.setId(1L);
ListNominalWallThickness listNominalWallThickness2 = new ListNominalWallThickness();
listNominalWallThickness2.setId(listNominalWallThickness1.getId());
assertThat(listNominalWallThickness1).isEqualTo(listNominalWallThickness2);
listNominalWallThickness2.setId(2L);
assertThat(listNominalWallThickness1).isNotEqualTo(listNominalWallThickness2);
listNominalWallThickness1.setId(null);
assertThat(listNominalWallThickness1).isNotEqualTo(listNominalWallThickness2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(ListNominalWallThicknessDTO.class);
ListNominalWallThicknessDTO listNominalWallThicknessDTO1 = new ListNominalWallThicknessDTO();
listNominalWallThicknessDTO1.setId(1L);
ListNominalWallThicknessDTO listNominalWallThicknessDTO2 = new ListNominalWallThicknessDTO();
assertThat(listNominalWallThicknessDTO1).isNotEqualTo(listNominalWallThicknessDTO2);
listNominalWallThicknessDTO2.setId(listNominalWallThicknessDTO1.getId());
assertThat(listNominalWallThicknessDTO1).isEqualTo(listNominalWallThicknessDTO2);
listNominalWallThicknessDTO2.setId(2L);
assertThat(listNominalWallThicknessDTO1).isNotEqualTo(listNominalWallThicknessDTO2);
listNominalWallThicknessDTO1.setId(null);
assertThat(listNominalWallThicknessDTO1).isNotEqualTo(listNominalWallThicknessDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(listNominalWallThicknessMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(listNominalWallThicknessMapper.fromId(null)).isNull();
}
}
|
import { Fragment } from "react";
import EventContent from "../../components/event-detail/EventContent";
import EventLogistics from "../../components/event-detail/EventLogistics";
import EventSummary from "../../components/event-detail/EventSummary";
import { getEventById, getFeaturedEvents } from "../../helpers/api-util";
import Head from "next/head"
import Comments from "../../components/input/Comments";
function EventDetailPage(props) {
const event = props.selectedEvent;
if (!event) {
return <div className="center">
<p>Loading...</p>
</div>
}
return (
<Fragment>
<Head>
<title>{ event.title }</title>
<meta
name="description"
content={ event.description }
/>
</Head>
<EventSummary title={ event.title }/>
<EventLogistics date={ event.date } address={ event.location } image={event.image} imageAlt={ event.title }/>
<EventContent>
<p>{ event.description }</p>
</EventContent>
<Comments eventId={event.id}/>
</Fragment>
)
}
export async function getStaticProps(context) {
const eventId = context.params.eventId;
const event = await getEventById(eventId);
return {
props: {
selectedEvent: event,
},
revalidate: 30
}
}
export async function getStaticPaths () {
const events = await getFeaturedEvents();
const paths = events.map(event => ({ params: { eventId: event.id } }));
return {
paths: paths,
fallback: 'blocking'
}
}
export default EventDetailPage
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using UserApi.Jwt;
using UserApi.Model;
namespace UserApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly UserContextDb _context;
private readonly IJwtAuth auth;
public UsersController(UserContextDb context,IJwtAuth _auth)
{
_context = context;
auth = _auth;
}
// GET: api/Users
[HttpGet]
public async Task<ActionResult<IEnumerable<Users>>> GetUsers()
{
return await _context.Users.ToListAsync();
}
// [Route("Validate")]
[HttpPost]
public ActionResult PostUsers(Users user)
{
Users u = (from x in _context.Users where (x.Username == user.Username && x.Password == user.Password) select x ).FirstOrDefault() ;
if (u != null)
{
string token = auth.Authentication(u.Username, u.Password);
return new JsonResult(token);
}
else if (u == null)
{
return NotFound();
}
return BadRequest();
}
// GET: api/Users/5
[HttpGet("{id}")]
public async Task<ActionResult<Users>> GetUsers(int id)
{
var users = await _context.Users.FindAsync(id);
if (users == null)
{
return NotFound();
}
return users;
}
// PUT: api/Users/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutUsers(int id, Users users)
{
if (id != users.Id)
{
return BadRequest();
}
_context.Entry(users).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UsersExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Users
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
// [HttpPost]
/* public async Task<ActionResult<Users>> PostUsers(Users users)
{
_context.Users.Add(users);
await _context.SaveChangesAsync();
return CreatedAtAction("GetUsers", new { id = users.Id }, users);
} */
// DELETE: api/Users/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteUsers(int id)
{
var users = await _context.Users.FindAsync(id);
if (users == null)
{
return NotFound();
}
_context.Users.Remove(users);
await _context.SaveChangesAsync();
return NoContent();
}
private bool UsersExists(int id)
{
return _context.Users.Any(e => e.Id == id);
}
}
}
|
import axios from 'axios';
(async () => {
const delay = (seconds: number, message: string) => {
return new Promise((resolve) => {
setTimeout(() => resolve(message), seconds * 1000);
});
};
const getProduts = () =>
axios.get('https://api.escuelajs.co/api/v1/products?offset=1&limit=1');
const getProdutsAsync = async () => {
const response = await axios.get(
'https://api.escuelajs.co/api/v1/products?offset=1&limit=1',
);
return response.data;
};
console.log('Waiting for delay() to finish...');
console.log(await delay(2, 'delay() has finished after 2 seconds'));
console.log('Products: ' + JSON.stringify((await getProduts()).data));
console.log('Products (async): ' + JSON.stringify(await getProdutsAsync()));
})();
|
import 'dart:ui';
import 'package:flutter/material.dart';
class AppWidget extends StatelessWidget {
const AppWidget({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Smart App',
theme: ThemeData(primarySwatch: Colors.blue),
home: HomeWidget(),
);
}
}
class HomeWidget extends StatelessWidget {
HomeWidget({super.key});
final controller = RichTextFieldController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextField(
controller: controller,
maxLines: 5,
onChanged: (value) {
// final val = TextSelection.collapsed(offset: controller.text.length);
// controller.selection = val;
},
),
),
);
}
}
class RichTextFieldController extends TextEditingController {
late final Pattern pattern;
final enterSymbol = String.fromCharCode(0x23CE);
String pureText = '';
final Map<String, TextStyle> map = {
r'\d': const TextStyle(backgroundColor: Colors.blue),
r'\u23ce\n\u23ce': const TextStyle(backgroundColor: Colors.yellow),
r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])':
const TextStyle(backgroundColor: Colors.red),
};
RichTextFieldController() {
pattern = RegExp(map.keys.map((key) => key).join('|'), multiLine: true);
}
@override
set value(TextEditingValue newValue) {
String replaceLastNewLine(String input) {
if (input.length < value.text.length) {
final lastIndexOfNewLine = value.text.lastIndexOf(RegExp('$enterSymbol\n$enterSymbol'));
if (lastIndexOfNewLine == -1) {
return input;
}
if (lastIndexOfNewLine == value.text.length - 3) {
return value.text.replaceRange(value.text.length - 3, value.text.length, '');
}
return input;
}
final lastNewLineIndex = input.lastIndexOf(RegExp('\n'));
if (lastNewLineIndex == -1 || input.isEmpty) {
return input;
}
final leng = input.length;
final isNewSymbol = lastNewLineIndex == input.length - 1;
if (isNewSymbol) {
return input.replaceFirst(RegExp('\n'), '$enterSymbol\n$enterSymbol', input.length - 1);
}
return input;
}
final newText = replaceLastNewLine(newValue.text);
super.value = newValue.copyWith(
text: newText,
// selection: TextSelection.collapsed(offset: newText.length),
composing: TextRange.empty,
);
}
@override
set text(String newText) {
value = value.copyWith(
text: newText,
selection: TextSelection.collapsed(offset: newText.length),
composing: TextRange.empty,
);
}
@override
TextSpan buildTextSpan({
required context,
TextStyle? style,
required bool withComposing,
}) {
final List<InlineSpan> children = [];
text.splitMapJoin(
pattern,
onMatch: (Match match) {
String? formattedText;
String? textPattern;
final patterns = map.keys.toList();
for (final element in patterns.indexed) {
if (RegExp(patterns[element.$1]).hasMatch(match[0]!)) {
formattedText = match[0];
textPattern = patterns[element.$1];
break;
}
}
children.add(TextSpan(
text: formattedText,
style: style!.merge(map[textPattern!]),
));
return "";
},
onNonMatch: (String text) {
children.add(TextSpan(text: text, style: style));
return "";
},
);
return TextSpan(
style: style,
children: children
..forEach(
(element) => element.toPlainText(),
));
}
}
|
import { useState } from "react";
import Step1 from "./components/views/Step1";
import Step2 from "./components/views/Step2";
import Step3 from "./components/views/Step3";
import "./app.scss";
function App() {
const [currentView, setCurrentView] = useState("step1");
const [fetchedFigures, setFetchedFigures] = useState([]);
const [selectedFigure, setSelectedFigure] = useState(null);
const [partsDetails, setPartsDetails] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [orderSubmitted, setOrderSubmitted] = useState(false);
return (
<div className="container">
{currentView === "step1" && isLoading !== true && (
<Step1
setCurrentView={setCurrentView}
setFetchedFigures={setFetchedFigures}
setIsLoading={setIsLoading}
/>
)}
{currentView === "step2" && isLoading !== true && (
<Step2
fetchedFigures={fetchedFigures}
selectedFigure={selectedFigure}
setSelectedFigure={setSelectedFigure}
setCurrentView={setCurrentView}
setPartsDetails={setPartsDetails}
setIsLoading={setIsLoading}
/>
)}
{currentView === "step3" && isLoading !== true && (
<Step3
selectedFigure={selectedFigure}
fetchedFigures={fetchedFigures}
partsDetails={partsDetails}
setCurrentView={setCurrentView}
setIsLoading={setIsLoading}
setOrderSubmitted={setOrderSubmitted}
/>
)}
{isLoading && orderSubmitted !== true && <span className="loader"></span>}
{orderSubmitted && (
<span>Order successfully submitted! Thank you :)</span>
)}
</div>
);
}
export default App;
|
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine.SceneManagement;
using UnityEngine;
public class GarbageMiniGameManager : MonoBehaviour
{
public int score;
// Reference to the TextMeshProUGUI components
public TextMeshProUGUI scoreText;
public TextMeshProUGUI timerText;
public TextMeshProUGUI finalScoreText;
public string additiveSceneName;
public GarbageSpawner garbageSpawner;
// Timer and game state
public float remainingTime = 15f; // 15 seconds
private bool gameEnded = false;
private GameManager gameManager;
// Multiplier for calculating happiness change
public int happinessMultiplier = 1;
// Start is called before the first frame update
void Start()
{
score = 0; // Initialize the score to 0
UpdateScoreText(); // Update the score text
finalScoreText.gameObject.SetActive(false); // Hide the final score text
gameManager = FindObjectOfType<GameManager>();
}
void Update()
{
if (!gameEnded)
{
// Update the timer
remainingTime -= Time.deltaTime;
UpdateTimerText();
UpdateScoreText();
// Check if the timer has reached zero
if (remainingTime <= 0f)
{
EndGame();
}
}
else
{
// Check for any key event or click event to unload the current additive scene
if (Input.anyKeyDown || Input.GetMouseButtonDown(0))
{
UnloadCurrentScene();
}
}
}
// Public method to get the current score
public int GetScore()
{
return score;
}
// Public method to increment the score
public void IncrementScore(int amount)
{
// Debug when called
score += amount;
}
private void UpdateScoreText()
{
if (scoreText != null)
{
scoreText.text = $"Garbage collected: {score}";
}
}
// Update the score text to display the current score
private void UpdateTimerText()
{
if (timerText != null)
{
int remainingSeconds = Mathf.Max(0, Mathf.FloorToInt(remainingTime));
timerText.text = $"Time remaining: {remainingSeconds}s";
}
}
// End the game and display the final score message
private void EndGame()
{
gameEnded = true;
finalScoreText.gameObject.SetActive(true);
finalScoreText.text = $"You picked up {score} pieces of trash! Good job!";
// Stop spawning squares and destroy all spawned squares
if (garbageSpawner != null)
{
garbageSpawner.ToggleSpawning(false);
garbageSpawner.DestroyAllSquares();
}
// Calculate happiness change based on score and multiplier
int happinessChange = score * happinessMultiplier;
// Update happiness in the GameManager
if (gameManager != null)
{
gameManager.UpdateHappiness(happinessChange);
}
}
// Unload the current additive scene and return to the main scene
private void UnloadCurrentScene()
{
if (!string.IsNullOrEmpty(additiveSceneName))
{
// Unload the current additive scene
SceneManager.UnloadSceneAsync(additiveSceneName);
additiveSceneName = null;
// Call the ReactivatePlayerAndUI function from the GameManager script
if (gameManager != null)
{
gameManager.ReactivatePlayerAndUI();
}
}
}
void OnDestroy()
{
garbageSpawner.DestroyAllSquares();
}
}
|
//
// ViewController.swift
// StoreSearch
//
// Created by Benjamin Jaramillo on 03/02/24.
//
import UIKit
class SearchViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var segmentedControl: UISegmentedControl!
var searchResults = [SearchResult]()
var hasSearched = false
var isLoading = false
var dataTask: URLSessionDataTask?
// Definición de la estructura TableView
struct TableView {
// Anidamiento de la estructura CellIdentifiers
struct CellIdentifiers {
// Definición de identificadores de celda estáticos para SearchResultCell y NothingFoundCell
static let searchResultCell = "SearchResultCell" // Identificador de celda para los resultados de búsqueda
static let nothingFoundCell = "NothingFoundCell" // Identificador de celda para mostrar cuando no se encuentran resultados
static let loadingCell = "LoadingCell"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Llama al método de la superclase para realizar cualquier configuración adicional.
super.viewDidLoad()
// Ajusta el contenido del tableView para que tenga un margen superior de 91 puntos.
tableView.contentInset = UIEdgeInsets(top: 91, left: 0, bottom: 0, right: 0)
// Crea un UINib para la celda de resultados de búsqueda usando el identificador especificado.
var cellNib = UINib(nibName: TableView.CellIdentifiers.searchResultCell, bundle: nil)
// Registra el UINib en el tableView para que pueda usarlo al crear celdas con ese identificador.
tableView.register(cellNib, forCellReuseIdentifier: TableView.CellIdentifiers.searchResultCell)
// Crea un UINib para la celda que se muestra cuando no se encuentran resultados.
cellNib = UINib(nibName: TableView.CellIdentifiers.nothingFoundCell, bundle: nil)
// Registra el UINib en el tableView para que pueda usarlo al crear celdas con ese identificador.
tableView.register(cellNib, forCellReuseIdentifier: TableView.CellIdentifiers.nothingFoundCell)
// Hace que la barra de búsqueda se convierta en el primer respondedor, mostrando el teclado al cargar la vista.
searchBar.becomeFirstResponder()
// Crea un UINib para la celda de carga usando el identificador especificado.
cellNib = UINib(nibName: TableView.CellIdentifiers.loadingCell, bundle: nil)
// Registra el UINib en el tableView para que pueda usarlo al crear celdas con ese identificador.
tableView.register(cellNib, forCellReuseIdentifier: TableView.CellIdentifiers.loadingCell)
}
@IBAction func segmentChanged(_ sender: UISegmentedControl) {
print("Segment changed: \(sender.selectedSegmentIndex)")
}
}
extension SearchViewController: UISearchBarDelegate {
// Método delegado llamado cuando se presiona el botón de búsqueda en la barra de búsqueda.
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
performSearch()
}
// Método que realiza la búsqueda.
func performSearch() {
// Verifica si el texto del searchBar no está vacío.
if !searchBar.text!.isEmpty {
// Desactiva el teclado.
searchBar.resignFirstResponder()
// Cancela cualquier tarea de datos en curso.
dataTask?.cancel()
// Indica que la aplicación está cargando.
isLoading = true
// Recarga la tabla para mostrar la celda de carga.
tableView.reloadData()
// Marca que se ha realizado una búsqueda.
hasSearched = true
// Limpia los resultados de búsqueda anteriores.
searchResults = []
// Crea la URL para la búsqueda en iTunes con el texto de búsqueda y la categoría seleccionada.
let url = iTunesURL(searchText: searchBar.text!, category: segmentedControl.selectedSegmentIndex)
// Crea una sesión compartida de URL.
let session = URLSession.shared
// Crea una tarea de datos para la URL.
dataTask = session.dataTask(with: url) { data, response, error in
// Verifica si hubo un error y si el error es de cancelación (-999).
if let error = error as NSError?, error.code == -999 {
return // La búsqueda fue cancelada.
} else if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
// Verifica si la respuesta HTTP es válida (código 200).
if let data = data {
// Parsea los datos recibidos.
self.searchResults = self.parse(data: data)
// Ordena los resultados de búsqueda.
self.searchResults.sort(by: <)
// Actualiza la interfaz en el hilo principal.
DispatchQueue.main.async {
self.isLoading = false
self.tableView.reloadData()
}
return
}
} else {
print("Failure! \(response!)")
}
// En caso de error, actualiza la interfaz en el hilo principal.
DispatchQueue.main.async {
self.hasSearched = false
self.isLoading = false
self.tableView.reloadData()
self.showNetworkError()
}
}
// Inicia la tarea de datos.
dataTask?.resume()
}
}
}
// Devuelve la posición de la barra en la interfaz de usuario
func position(for bar: UIBarPositioning) -> UIBarPosition {
// Devuelve la posición de la barra como "topAttached" para adjuntarla en la parte superior
return .topAttached
}
// MARK: - Table View Delegate
extension SearchViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int
) -> Int {
// Si está cargando, devuelve 1 para mostrar la celda de carga.
if isLoading {
return 1
// Si no se ha realizado una búsqueda, devuelve 0 para no mostrar filas.
} else if !hasSearched {
return 0
// Si se ha buscado pero no hay resultados, devuelve 1 para mostrar la celda de "Nada encontrado".
} else if searchResults.count == 0 {
return 1
// Si hay resultados de búsqueda, devuelve el número de resultados.
} else {
return searchResults.count
}
}
// Método del delegado de UITableView para proporcionar una celda para una fila dada.
func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
// Verifica si está cargando.
if isLoading {
// Obtiene una celda reutilizable con el identificador "loadingCell".
let cell = tableView.dequeueReusableCell(
withIdentifier: TableView.CellIdentifiers.loadingCell,
for: indexPath)
// Encuentra el spinner (UIActivityIndicatorView) en la celda utilizando su etiqueta.
let spinner = cell.viewWithTag(100) as! UIActivityIndicatorView
// Inicia la animación del spinner.
spinner.startAnimating()
// Devuelve la celda de carga.
return cell
// Verifica si no hay resultados de búsqueda.
} else if searchResults.count == 0 {
// Obtiene una celda reutilizable con el identificador "nothingFoundCell".
return tableView.dequeueReusableCell(
withIdentifier: TableView.CellIdentifiers.nothingFoundCell,
for: indexPath)
// Si hay resultados de búsqueda.
} else {
// Obtiene una celda reutilizable con el identificador "searchResultCell".
let cell = tableView.dequeueReusableCell(
withIdentifier: TableView.CellIdentifiers.searchResultCell,
for: indexPath) as! SearchResultCell
// Obtiene el resultado de búsqueda correspondiente a la fila actual.
let searchResult = searchResults[indexPath.row]
// Establece el nombre del resultado en la etiqueta de nombre de la celda.
cell.configure(for: searchResult)
return cell
}
}
// Función que se ejecuta cuando se selecciona una fila de la tabla
func tableView(
_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath
) {
// Deselecciona la fila para eliminar el resaltado
tableView.deselectRow(at: indexPath, animated: true)
performSegue(withIdentifier: "ShowDetail", sender: indexPath)
}
// Función que determina si una fila específica de la tabla puede ser seleccionada
func tableView(
_ tableView: UITableView,
willSelectRowAt indexPath: IndexPath
) -> IndexPath? {
// Si no hay resultados de búsqueda, no se permite la selección
if searchResults.count == 0 || isLoading{
return nil
} else {
// Si hay resultados de búsqueda, permite la selección de la fila
return indexPath
}
}
func iTunesURL(searchText: String, category: Int) -> URL {
// Declara una variable `kind` para almacenar el tipo de búsqueda
let kind: String
// Asigna el tipo de búsqueda basado en la categoría seleccionada
switch category {
case 1:
kind = "musicTrack"
case 2:
kind = "software"
case 3:
kind = "ebook"
default:
kind = ""
}
// Codifica el texto de búsqueda para que sea seguro para incluir en una URL
let encodedText = searchText.addingPercentEncoding(
withAllowedCharacters: CharacterSet.urlQueryAllowed)!
// Construye la cadena de la URL utilizando el texto codificado y el tipo de búsqueda
let urlString = "https://itunes.apple.com/search?" +
"term=\(encodedText)&limit=200&entity=\(kind)"
// Crea una URL a partir de la cadena de URL
let url = URL(string: urlString)
// Devuelve la URL
return url!
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Comprueba si el identificador del segue es "ShowDetail".
if segue.identifier == "ShowDetail" {
// Obtiene el view controller de destino y lo convierte en un `DetailViewController`.
let detailViewController = segue.destination as! DetailViewController
// Obtiene el índice de la celda seleccionada (enviada como el sender) y lo convierte en `IndexPath`.
let indexPath = sender as! IndexPath
// Obtiene el resultado de la búsqueda correspondiente al índice de la celda seleccionada.
let searchResult = searchResults[indexPath.row]
// Asigna el resultado de la búsqueda al `searchResult` del `DetailViewController`.
detailViewController.searchResult = searchResult
}
}
// Método para analizar los datos JSON obtenidos de la solicitud y devolver un array de SearchResult
func parse(data: Data) -> [SearchResult] {
do {
// Crea una instancia de JSONDecoder para decodificar los datos JSON
let decoder = JSONDecoder()
// Decodifica los datos JSON en un objeto de tipo ResultArray utilizando el JSONDecoder
let result = try decoder.decode(ResultArray.self, from: data)
// Devuelve la matriz de resultados obtenidos del objeto ResultArray
return result.results
} catch {
// Si se produce un error al decodificar los datos JSON, imprime el error y devuelve un array vacío
print("JSON Error: \(error)")
return []
}
}
// Método para mostrar un mensaje de error de red al usuario
func showNetworkError() {
// Crea una instancia de UIAlertController para mostrar el mensaje de error
let alert = UIAlertController(
title: "Whoops...",
message: "There was an error accessing the iTunes Store." +
" Please try again.",
preferredStyle: .alert)
// Agrega un botón de acción "OK" al UIAlertController
let action = UIAlertAction(
title: "OK", style: .default, handler: nil)
alert.addAction(action)
// Presenta el UIAlertController para mostrar el mensaje de error al usuario
present(alert, animated: true, completion: nil)
}
}
|
package com.wein_business.data.model.ticket
import com.google.gson.annotations.SerializedName
import com.wein_business.data.model.LookupModel
data class TicketSearchModel(
@SerializedName("title")
var title: String,
@SerializedName("imageMaster")
var imageMaster: String,
@SerializedName("startDate")
var startDate: String,
@SerializedName("endDate")
var endDate: String,
@SerializedName("startTime")
var startTime: String,
@SerializedName("endTime")
var endTime: String,
@SerializedName("statusClass")
var statusClass: LookupModel,
@SerializedName("priceClasses")
var priceClasses: ArrayList<TicketSearchPriceModel>
)
|
package wapi
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/rauldotgit/pricemage/utils"
)
type GameItem struct {
ID int32 `json:"id"`
Name string `json:"name"`
Quality interface{} `json:"quality"`
Media struct {
Key struct {
Href string `json:"href"`
} `json:"key"`
} `json:"media"`
}
type ItemClass struct {
Name string
}
type ItemClassIndex struct {
ItemClasses []struct {
Name string `json:"name"`
ID int `json:"id"`
} `json:"item_classes"`
}
// map of all items indexed by id
type LocalItemIndex struct {
Items map[int32]GameItem
Size int32
}
func (L *LocalItemIndex) Initialize() {
L.Items = make(map[int32]GameItem)
}
func (L *LocalItemIndex) Add(newItem GameItem) {
_, ok := L.Items[newItem.ID]
if !ok {
log.Println("Local index added:", newItem.Name)
L.Items[newItem.ID] = newItem
}
}
func GetItemInfo(itemID int32, region string, locale string, client *http.Client, authToken *string) (GameItem, error) {
url := fmt.Sprintf("https://%s.api.blizzard.com/data/wow/item/%d?namespace=%s&locale=%s", region, itemID, "static-"+region, locale)
resJSON, err := utils.Fetch(url, "GET", nil, client, authToken)
if err != nil {
return GameItem{}, fmt.Errorf("error in GetItemInfo: %w", err)
}
var item GameItem
umErr := json.Unmarshal(resJSON, &item)
if umErr != nil {
return GameItem{}, fmt.Errorf("error in GetItemInfo: %w", umErr)
}
return item, nil
}
func GetItemClassIndex(region string, locale string, client *http.Client, authToken *string) (ItemClassIndex, error) {
url := fmt.Sprintf("https://%s.api.blizzard.com/data/wow/item-class/index?namespace=%s&locale=%s", region, "static-"+region, locale)
resJSON, err := utils.Fetch(url, "GET", nil, client, authToken)
if err != nil {
return ItemClassIndex{}, fmt.Errorf("error in GetItemClassIndex: %w", err)
}
var itemClassIndex ItemClassIndex
umErr := json.Unmarshal(resJSON, &itemClassIndex)
if umErr != nil {
return ItemClassIndex{}, fmt.Errorf("error in GetItemClassIndex: %w", umErr)
}
return itemClassIndex, nil
}
func GetItemClass(itemClassID int, region string, locale string, client *http.Client, authToken *string) (ItemClass, error) {
url := fmt.Sprintf("https://%s.api.blizzard.com/data/wow/item-class/%d?namespace=%s&locale=%s", region, itemClassID, "static-"+region, locale)
resJSON, err := utils.Fetch(url, "GET", nil, client, authToken)
if err != nil {
return ItemClass{}, fmt.Errorf("error in GetItemClass: %w", err)
}
log.Println(string(resJSON))
// var itemClassIndex ItemClassIndex
// umErr := json.Unmarshal(resJSON, &itemClassIndex)
// if umErr != nil {
// return ItemClass{}, fmt.Errorf("error in GetItemClassIndex: %w", umErr)
// }
return ItemClass{}, nil
}
// time consuming, fetches all available auctions, retrieves the item info and
func BuildLocalItemIndex(realmID int, region string, locale string, itemIndex *LocalItemIndex, client *http.Client, authToken *string) error {
rawAuctions, err := GetRawAuctions(realmID, region, locale, client, authToken)
if err != nil {
return fmt.Errorf("error in BuildLocalItemIndex: %w", err)
}
localIndex := *itemIndex
log.Println("Starting full local item index build.")
for _, rawAuc := range rawAuctions {
gameItem, err := GetItemInfo(rawAuc.Item.ID, region, locale, client, authToken)
if err != nil {
errMsg := fmt.Errorf("non-fatal error in BuildLocalItemIndex: %w", err)
log.Println(errMsg)
continue
}
localIndex.Add(gameItem)
}
log.Println("Full local item index build complete.")
return nil
}
// less time consuming, fetches only gameItem info of items not yet in the index taken from new auctions
func UpdateLocalItemIndex(realmID int, region string, locale string, itemIndex *LocalItemIndex, client *http.Client, authToken *string) error {
rawAuctions, err := GetRawAuctions(realmID, region, locale, client, authToken)
if err != nil {
return fmt.Errorf("error in BuildLocalItemIndex: %w", err)
}
localIndex := *itemIndex
log.Println("Starting local item index refresh.")
for _, rawAuc := range rawAuctions {
_, ok := localIndex.Items[rawAuc.Item.ID]
if !ok {
gameItem, err := GetItemInfo(rawAuc.Item.ID, region, locale, client, authToken)
if err != nil {
errMsg := fmt.Errorf("non-fatal error in BuildLocalItemIndex: %w", err)
log.Println(errMsg)
continue
}
localIndex.Add(gameItem)
}
}
log.Println("Local item index refresh complete.")
return nil
}
|
<template>
<div class="article">
<h2 class="article__header">{{ article.title }}</h2>
<p class="article__text">
{{ article.shortText }}
</p>
<button class="button button__white" @click.prevent="goToArticleHandler">
Button
</button>
</div>
</template>
<script>
import { computed } from '@vue/runtime-core';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
export default {
name: 'AppArticle',
props: ['id'],
setup(props) {
const router = useRouter();
const store = useStore();
const goToArticleHandler = () => {
router.push(`/main/${props.id}`);
};
return {
goToArticleHandler,
article: computed(() => store.getters['articles/articleById'](props.id)),
};
},
};
</script>
<style></style>
|
import { Button, createStyles, Grid, TextField, Theme, Typography, withStyles, WithStyles } from '@material-ui/core';
import * as React from 'react';
import { IAuthProps } from '../../common/IAuthProps';
import { Endpoints } from '../../configuration/Endpoints';
const styles = (theme: Theme) =>
createStyles({
button: {
justify: 'center',
margin: theme.spacing.unit * 2,
},
textField: {
marginLeft: theme.spacing.unit,
marginRight: theme.spacing.unit,
},
});
interface IPasswordHandlerProps extends WithStyles<typeof styles>, IAuthProps {
closeDialog: () => void,
}
interface IPasswordHandlerState {
confirmPassword: string,
newPassword: string,
oldPassword: string,
passwordHasError: boolean,
}
const PasswordHandler = withStyles(styles)(
class extends React.Component<IPasswordHandlerProps, IPasswordHandlerState> {
constructor(props: IPasswordHandlerProps) {
super(props);
this.state = {
confirmPassword: "",
newPassword: "",
oldPassword: "",
passwordHasError: false,
}
}
public render() {
const { classes } = this.props;
return(
<Grid container={true} justify="center">
<Grid item={true} lg={11} md={11} sm={11} xs={11} >
<Typography variant="subtitle1">
Change Password
</Typography>
</Grid>
<Grid item={true} lg={11} md={11} sm={11} xs={11} >
<TextField
required={true}
className={classes.textField}
id="oldPassword"
label="Old Password"
type="password"
fullWidth={true}
value={this.state.oldPassword}
onChange={this.handleOldPasswordFieldChange}
/>
</Grid>
<Grid item={true} lg={11} md={11} sm={11} xs={11} >
<TextField
required={true}
className={classes.textField}
id="newPassword"
label="New Password"
type="password"
fullWidth={true}
value={this.state.newPassword}
onChange={this.handlePasswordFieldChange}
error={this.state.passwordHasError}
inputProps={{
maxLength: 50
}}
/>
</Grid>
<Grid item={true} lg={11} md={11} sm={11} xs={11} >
<TextField
required={true}
className={classes.textField}
id="confirmPassword"
label="Confirm Password"
type="password"
fullWidth={true}
value={this.state.confirmPassword}
onChange={this.handleConfirmPasswordChange}
error={this.state.passwordHasError}
inputProps={{
maxLength: 50
}}
/>
</Grid>
<Grid item={true} lg={11} md={11} sm={11} xs={11} >
<Button
variant="contained"
color="default"
className={classes.button}
onClick={this.handleUpdatePassword}
>
Update Password
</Button>
</Grid>
</Grid>
);
}
private handlePasswordFieldChange =
(event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
if (this.state.confirmPassword !== "") {
if (event.target.value === this.state.confirmPassword) {
this.setState({
passwordHasError: false,
})
}
else {
this.setState({
passwordHasError: true,
})
}
}
this.setState({
newPassword: event.target.value,
})
}
private handleConfirmPasswordChange =
(event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
if (event.target.value === this.state.newPassword) {
this.setState({
passwordHasError: false,
});
}
else {
this.setState({
passwordHasError: true,
})
}
this.setState({
confirmPassword: event.target.value,
})
}
private handleOldPasswordFieldChange =
(event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
this.setState({
oldPassword: event.target.value,
});
}
private handleUpdatePassword = () => {
if (this.state.passwordHasError) {
this.props.toast("Invalid Password");
}
else {
fetch(
Endpoints.Server + Endpoints.User + "/password",
{
body: JSON.stringify({
"newPassword": this.state.newPassword,
"oldPassword": this.state.oldPassword,
}),
headers: {
'Access-Control-Allow-Origin': '*',
'Authorization': this.props.token,
'content-type': 'application/json',
},
method: 'POST',
mode: 'cors',
referrer: 'no-referrer',
})
.then(response => response.json())
.then(response => {
if (response.status === 400) {
this.props.toast(response.message);
}
else {
this.props.toast("Password Changed");
this.props.closeDialog();
}
});
}
}
}
);
export default PasswordHandler;
|
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import Footer from './footer';
function ModificarProductoForm() {
const [productId, setProductId] = useState('');
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [price, setPrice] = useState('');
const [image, setImage] = useState(null);
const [message, setMessage] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('name', name);
formData.append('description', description);
formData.append('price', price);
if (image) {
formData.append('image', image);
}
const token = localStorage.getItem('authToken');
console.log('Token almacenado:', token);
try {
const response = await axios.put(`http://localhost:8080/api/v1/productos/update/${productId}`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${token}`,
},
withCredentials: true,
});
console.log('Respuesta del servidor:', response);
if (response.status === 200) {
setMessage('Producto actualizado exitosamente');
} else {
setMessage('Error al actualizar el producto');
}
} catch (error) {
setMessage('Error al actualizar el producto');
console.error('Error al actualizar el producto:', error);
}
};
const handleImageChange = (e) => {
setImage(e.target.files[0]);
};
return (
<div>
<header>
<img src="/impacto.jpg" alt="Logo" className="logo" />
<h1 className="impacto">Impacto visual</h1>
<img src="/impacto.jpg" alt="Logo" className="logo" />
</header>
<nav className="menu">
<ul className='menu-lista'>
<li><Link className="menu-link" to="/Admin">Dashboard</Link></li>
<li><Link className="menu-link" to="/NewProduct">Nuevo Producto</Link></li>
<li><Link className="menu-link" to="/Modificar">Modificar Producto</Link></li>
</ul>
</nav>
<h1>Modificar Producto</h1>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="productId">ID del Producto:</label>
<input
type="text"
id="productId"
value={productId}
onChange={(e) => setProductId(e.target.value)}
required
/>
</div>
<div>
<label htmlFor="name">Nombre:</label>
<input
type="text"
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
</div>
<div>
<label htmlFor="description">Descripción:</label>
<textarea
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
required
/>
</div>
<div>
<label htmlFor="price">Precio:</label>
<input
type="number"
id="price"
value={price}
onChange={(e) => setPrice(e.target.value)}
required
/>
</div>
<div>
<label htmlFor="image">Imagen:</label>
<input
type="file"
id="image"
onChange={handleImageChange}
/>
</div>
<button type="submit">Actualizar Producto</button>
</form>
{message && <p>{message}</p>}
<Footer />
</div>
);
}
export default ModificarProductoForm;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mon Site Web</title>
<style>
/* CSS du code que tu m'as fourni */
/* Reset des marges et paddings et utilisation de flexbox pour centrer le contenu */
body, html {
margin: 0;
padding: 0;
height: 100%;
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
}
/* Vidéo de fond */
#background-video {
position: fixed;
top: 50%;
left: 50%;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
transform: translate(-50%, -50%) rotate(-90deg);
z-index: -1;
}
/* Contenu principal */
.content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
z-index: 1;
}
/* Boîte d'informations */
.info-box {
background-color: rgba(40, 40, 40, 0.2); /* Couleur légèrement plus foncée et presque totalement transparente */
padding: 20px;
border-radius: 10px; /* Bords arrondis */
}
.info {
font-size: 24px; /* Taille du texte */
color: white;
text-shadow: 0 0 10px rgba(255, 255, 255, 0.8); /* Effet de brillance */
margin: 10px 0; /* Marge entre les lignes */
}
/* Informations sur la musique */
.music-info {
position: absolute;
right: 20px; /* Marge à droite */
top: 50%;
transform: translateY(-50%);
text-align: center;
}
.music-box {
background-color: rgba(40, 40, 40, 0.2); /* Couleur légèrement plus foncée et presque totalement transparente */
padding: 20px;
border-radius: 10px; /* Bords arrondis */
}
.music-title {
font-size: 18px;
color: white;
margin-bottom: 10px;
}
.music-box img {
max-width: 200px; /* Taille maximale de l'image */
border-radius: 10px; /* Bords arrondis */
}
/* Bouton Play Music */
#playButton {
position: fixed;
left: 50px; /* Ajuste la position à gauche */
bottom: 20px; /* Ajuste la position verticalement */
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
z-index: 1;
}
#playButton:hover {
background-color: #45a049;
}
/* CSS pour la pluie rose */
#rain {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 9998; /* Juste en dessous des autres éléments */
}
.raindrop {
position: absolute;
top: -15px; /* Commence en haut de la fenêtre */
width: 2px;
height: 15px;
background: rgba(255, 0, 234, 0.8); /* Rose */
animation: fall linear infinite;
}
@keyframes fall {
to {
transform: translateY(100vh);
}
}
</style>
</head>
<body>
<video id="background-video" loop muted autoplay>
<source src="gt3rs.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<div class="content">
<div class="info-box">
<p class="info">👀 𝕵𝖚𝖑𝖎𝖊𝖓</p>
<p class="info">🎁 𝟗𝟏𝟓𝟔𝟔𝟑𝟏𝟔𝟒𝖟𝟖𝟎𝟕𝟒𝟓𝟎𝟔𝟒𝟓</p>
<p class="info">👑 𝕱𝖗𝖆𝖓𝖈̧𝖆𝖎𝖘 𝖊𝖙 𝖋𝖎𝖊𝖗 𝖉𝖊 𝖑'𝖊̂𝖙𝖗𝖊 ! 👑</p>
</div>
</div>
<div class="music-info">
<div class="music-box">
<p class="music-title">🎵𝕸𝖚𝖘𝖎𝖀𝖊: 𝕶𝖊𝖗𝖈𝖍𝖆𝖐 𝖘𝖆𝖎𝖘𝖔𝖓 2 !</p>
<img src="kerchak.jpg" alt="Kerchak">
</div>
</div>
<!-- Bouton Play Music -->
<button id="playButton">Play Music !</button>
<!-- Pluie rose -->
<div id="rain"></div>
<script>
// Fonction pour générer des gouttes de pluie roses
function createRain() {
const rainContainer = document.getElementById('rain');
const numDrops = 100; // Nombre de gouttes de pluie
for (let i = 0; i < numDrops; i++) {
const drop = document.createElement('div');
drop.className = 'raindrop';
drop.style.left = `${Math.random() * 100}vw`;
drop.style.animationDuration = `${Math.random() * 2 + 1}s`;
rainContainer.appendChild(drop);
}
}
createRain(); // Appeler la fonction pour créer la pluie
// Récupération de la référence vers la balise audio et le bouton
var audio = new Audio("Kerchak.mp3");
var playButton = document.getElementById("playButton");
// Ajout d'un gestionnaire d'événement clic sur le bouton
playButton.addEventListener("click", function() {
// Vérifie si la musique est en pause, si oui, la joue,
if (audio.paused) {
audio.play();
playButton.textContent = "Pause Music";
} else {
audio.pause();
playButton.textContent = "Play Music !";
}
});
</script>
<footer style="position: absolute; bottom: 10px; width: 100%; text-align: center; color: white;">
© Pistol.lol 2024 by Julien © DM OPEN
</footer>
</body>
</html>
|
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import FriendListItem from './components/profileBar';
import Heading from './components/heading';
import { useState } from 'react';
import Profile from './components/profile';
import * as FileSystem from 'expo-file-system';
import { Audio } from 'expo-av';
const userData = require('./tempDB.json');
export default function App() {
const [page, setPage] = useState(true);
const [recording, setRecording] = useState(null);
const [transcription, setTranscription] = useState('');
const [isSilent, setIsSilent] = useState(false);
//console.log(getLatestLine())
console.log("test")
useEffect(() => {
startRecording();
});
useEffect(() => {
if (isSilent && recording) {
stopRecordingAndSendData();
}
}, [isSilent]);
const startRecording = async () => {
const recordingInstance = new Audio.Recording();
try {
await recordingInstance.prepareToRecordAsync(Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY);
await recordingInstance.startAsync();
// Start a function to monitor the amplitude (to detect silence)
monitorAmplitude(recordingInstance);
setRecording(recordingInstance);
} catch (error) {
// Handle error
}
};
const monitorAmplitude = async (recordingInstance) => {
const intervalId = setInterval(async () => {
try {
const status = await recordingInstance.getStatusAsync();
if (status.isRecording && status.isMeteringEnabled) {
if (status.metering.averagePower < -30) { // Adjust this threshold as necessary
setIsSilent(true);
} else {
setIsSilent(false);
}
}
} catch (error) {
// Handle error
}
}, 10000); // Adjust interval as necessary
return () => clearInterval(intervalId); // Cleanup the interval on component unmount
};
const stopRecordingAndSendData = async () => {
try {
await recording.stopAndUnloadAsync();
const audioData = (await recording.getURI()); // Read the file into a format suitable for sending via HTTP
// Now send audioData to your server for transcription
const response = await fetch('http://localhost:3000/transcribe', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ audioData }),
});
const result = await response.json();
setTranscription(result.text); // Assuming your server sends back a JSON object with a "text" property
// Reset the recording instance and silence detection
setRecording(null);
setIsSilent(false);
} catch (error) {
// Handle error
}
};
return (
<View>
<Heading/>
{page ?
<View>
{Object.keys(userData["users"]).map(user => (
<FriendListItem
key={user}
name={user}
location={userData["users"][user]["location"]}
setPage = {setPage}/>
))}
</View>
: <View>
<Profile/>
<Text>Person1 was encountered at the park</Text>
<Text>{"<More details about person1>"}</Text>
</View>
}
</View>
);
}
const getLatestLine = async () => {
try {
const fileUri = `${FileSystem.documentDirectory}services/transcribedSpeech.txt`;
ensureDirExists(`${FileSystem.documentDirectory}services/`);
const fileContent = await FileSystem.readAsStringAsync(fileUri);
const lines = fileContent.split('\n');
const lastLine = lines[lines.length - 1];
return lastLine.substring(indexOf(':')+2);
} catch (error) {
console.error('Error reading file:', error);
return 'Error reading file';
}
}
async function ensureDirExists(dir) {
const dirInfo = await FileSystem.getInfoAsync(dir);
console.log(dirInfo);
if (!dirInfo.exists) {
console.log("directory doesn't exist, creating...");
await FileSystem.makeDirectoryAsync(dir, { intermediates: true });
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
|
/*
* Copyright (C) 2008-2014 Hellground <http://hellground.net/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef HELLGROUND_MAPUPDATER_H
#define HELLGROUND_MAPUPDATER_H
#include <ace/Thread_Mutex.h>
#include <ace/Condition_Thread_Mutex.h>
#include "DelayExecutor.h"
#include "Common.h"
#include "Map.h"
struct MapUpdateInfo
{
public:
MapUpdateInfo();
MapUpdateInfo(uint32 id, uint32 instanceId, uint32 startTime) : _id(id), _instanceId(instanceId), _startUpdateTime(startTime) {}
uint32 GetId() const { return _id; }
uint32 GetInstanceId() const { return _instanceId; }
uint32 GetUpdateTime() const { return _startUpdateTime; }
private:
uint32 _id;
uint32 _instanceId;
uint32 _startUpdateTime;
};
typedef std::map<ACE_thread_t const, MapUpdateInfo> ThreadMapMap;
class MapUpdater
{
public:
MapUpdater();
virtual ~MapUpdater();
friend class MapUpdateRequest;
/// schedule update on a map, the update will start
/// as soon as possible,
/// it may even start before the call returns
int schedule_update(Map& map, ACE_UINT32 diff);
/// Wait until all pending updates finish
int wait();
/// Start the worker threads
int activate(size_t num_threads);
/// Stop the worker threads
int deactivate(void);
bool activated();
void update_finished();
void register_thread(ACE_thread_t const threadId, uint32 mapId, uint32 instanceId);
void unregister_thread(ACE_thread_t const threadId);
void FreezeDetect();
MapUpdateInfo const* GetMapUpdateInfo(ACE_thread_t const threadId);
private:
ThreadMapMap m_threads;
uint32 freezeDetectTime;
DelayExecutor m_executor;
ACE_Condition_Thread_Mutex m_condition;
ACE_Thread_Mutex m_mutex;
size_t pending_requests;
};
#endif //_MAP_UPDATER_H_INCLUDED
|
<?php
// This file is part of AAMS Monitor
// Copyright (C) 2013 Gabriele Antonini
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/**
* Class AamsEvent
*
* A "bean-like" class representing an Event object
*
* @category AAMS Monitor
* @copyright Copyright (C) 2013 Gabriele Antonini (gabriele.antonini@gmail.com)
* @license GNU General Public License
*/
class AamsEvent
{
/** @var $aams_event_id string */
private $aams_event_id;
/** @var $aams_program_id string */
private $aams_program_id;
/** @var $name string */
private $name;
/** @var $href string */
private $href;
/** @var $dateTime string */
private $dateTime;
/** @var $hash string */
private $hash;
/** @var $mode int */
private $mode; // 0 = QUOTA_FISSA | 1 = LIVE
/** @var $category string */
private $category;
/** @var $subCategory string */
private $subCategory;
/**
* @param string $aams_event_id
*/
public function setAamsEventId($aams_event_id)
{
$this->aams_event_id = $aams_event_id;
}
/**
* @return string
*/
public function getAamsEventId()
{
return $this->aams_event_id;
}
/**
* @param string $aams_program_id
*/
public function setAamsProgramId($aams_program_id)
{
$this->aams_program_id = $aams_program_id;
}
/**
* @return string
*/
public function getAamsProgramId()
{
return $this->aams_program_id;
}
/**
* @param string $category
*/
public function setCategory($category)
{
$this->category = $category;
}
/**
* @return string
*/
public function getCategory()
{
return $this->category;
}
/**
* @param string $dateTime
*/
public function setDateTime($dateTime)
{
$this->dateTime = $dateTime;
}
/**
* @return string
*/
public function getDateTime()
{
return $this->dateTime;
}
/**
* @param string $hash
*/
public function setHash($hash)
{
$this->hash = $hash;
}
/**
* @return string
*/
public function getHash()
{
return $this->hash;
}
/**
* @param string $href
*/
public function setHref($href)
{
$this->href = $href;
}
/**
* @return string
*/
public function getHref()
{
return $this->href;
}
/**
* @param int $mode
*/
public function setMode($mode)
{
$this->mode = $mode;
}
/**
* @return int
*/
public function getMode()
{
return $this->mode;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $subCategory
*/
public function setSubCategory($subCategory)
{
$this->subCategory = $subCategory;
}
/**
* @return string
*/
public function getSubCategory()
{
return $this->subCategory;
}
/**
* __toString() override method outputting a string representation of the object
*
* @return string The string representation of the object
*/
public function __toString()
{
$str = "Event Name: " . $this->name . "\r\n" .
"Event Href: " . $this->href . "\r\n" .
"Event DateTime: " . $this->dateTime . "\r\n" .
"Mode (live:1 | quota fissa:0): " . $this->mode . "\r\n" .
"Category: " . $this->category . "\r\n" .
"SubCategory: " . $this->subCategory . "\r\n" .
"Program Id: " . $this->aams_program_id . "\r\n" .
"Event Id: " . $this->aams_event_id. "\r\n" .
"Event Page Hash: " . $this->hash. "\r\n" .
"\r\n";
return $str;
}
}
|
import React, { useRef, useState } from 'react';
import dropdown from "../../assets/icons/chevron-down.svg";
import funnel from "../../assets/icons/filter-funnel-02.svg";
import filterlines from "../../assets/icons/filter-lines.svg";
import upload from "../../assets/icons/share-02.svg";
import add from "../../assets/icons/user-plus-01.svg";
import BasicButton from '../DashboardButtons/BasicButton';
import DashDropdown from '../DashboardButtons/Dropdown';
import AddAgentModal from '../Modal/AddLecturer';
import CustomModal from "../Modal/UploadModal";
import './lecturer.css';
import AgentsTableData from './table';
const AgentsTable = () => {
const [isOpen, setIsOpen] = useState(false);
const openModal = () => {
setIsOpen(true);
};
const closeModal = () => {
setIsOpen(false);
};
const [modalOpen, setModalOpen] = useState(false);
const [rows, setRows] = useState([
{
firstname: "Home",
lastname: "website",
idType: "Ghana Card",
email: "penilive@hotpen.org",
},
]);
const [rowToEdit, setRowToEdit] = useState(null);
const fileInputRef = useRef(null);
const [typeError, setTypeError] = useState(null);
const handleFile = (e) => {
const fileTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/csv'];
const selectedFile = e.target.files && e.target.files[0];
if (selectedFile) {
if (selectedFile && fileTypes.includes(selectedFile.type)) {
setTypeError(null);
const reader = new FileReader();
reader.readAsText(selectedFile);
reader.onload = (e) => {
const csvText = e.target.result;
const lines = csvText?.split('\n');
if (lines) {
const headers = lines[0].split(',');
const data = [];
for (let i = 1; i < lines.length; i++) {
const values = lines[i].split(',');
if (values.length === headers.length) {
const entry = {
firstname: values[0],
lastname: values[1],
email: values[2],
};
data.push(entry);
}
}
setRows(data);
closeModal();
}
};
} else {
setTypeError('Please select only excel file types');
}
} else {
console.log('Please select your file');
}
};
const handleUploadButtonClick = () => {
fileInputRef.current?.click();
setModalOpen(false);
}
const handleDeleteRow = (targetIndex) => {
setRows((prevRows) => prevRows.filter((_, idx) => idx !== targetIndex));
};
const handleEditRow = (idx) => {
setRowToEdit(idx);
setModalOpen(true);
};
const handleSubmit = (newRow) => {
if (rowToEdit === null) {
setRows([...rows, newRow]);
} else {
setRows(
rows.map((currRow, idx) => {
if (idx !== rowToEdit) return currRow;
return newRow;
})
);
}
};
const defaultValue = rowToEdit !== null ? rows[rowToEdit] : undefined;
const sortOptions = ['Ascending', 'Descending', 'Recently added'];
const filterOptions = ['Agents', 'Farmers', 'Recently added'];
return (
<div className="adminArea">
<div className="adminTopbar">
<div className="buttonArea">
<h2 className="headText">
All Agents
</h2>
</div>
<div className="dashdropdown">
<DashDropdown name={'Sort by'}
icon1={<img src={filterlines} alt='filter' />}
icon2={<img src={dropdown} alt='dropdown' />}
options={sortOptions}
/>
<DashDropdown name={'Filter by'}
icon1={<img src={funnel} alt='filter' />}
icon2={<img src={dropdown} alt='dropdown' />}
options={filterOptions}
/>
<label className='uploadButton' onClick={openModal}>
<img className='smallIcon' src={upload} alt="upload" />
Bulk Upload
</label>
<CustomModal isOpen={isOpen} onRequestClose={closeModal}>
{typeError && (
<div className="alert alert-danger" role="alert">{typeError}</div>
)}
<form className="" >
<input
ref={fileInputRef}
type="file"
className=""
style={{ display: 'none' }}
required
onChange={handleFile}
/>
<label
htmlFor="fileInput"
className="uploadText"
onClick={handleUploadButtonClick}
>
<span className='click'>Click to Upload </span>{" "} or drag and drop <br />
</label>
<span className='csvOnly'>CSV Files only</span>
</form>
</CustomModal>
<BasicButton onClick={() => setModalOpen(true)} name={'Add Agent'} icon1={<img className="smallIcon" src={add} alt='add' />} className={'dd-button1'} />
</div>
</div>
<div className="tableArea">
<AgentsTableData rows={rows} deleteRow={handleDeleteRow} editRow={handleEditRow} />
{modalOpen && (
<AddAgentModal
closeModal={() => {
setModalOpen(false);
setRowToEdit(null);
}}
onSubmit={handleSubmit}
defaultValue={defaultValue}
/>
)}
</div>
</div>
);
};
export default AgentsTable;
|
//
// ViewController.swift
// ForgetItNot
//
// Created by 박정현 on 30/07/2019.
// Copyright © 2019 박정현. All rights reserved.
//
import UIKit
import SwipeCellKit
class FinTableViewController: UITableViewController {
let date = DateManager()
var db = Database.getInstance()
var categories = Settings.defaults.categories {
didSet {
Settings.defaults.categories = categories
}
}
//MARK: - tableView 관련 함수
override func viewDidLoad() {
super.viewDidLoad()
initializeData()
tableView.separatorStyle = .none
Settings.settings.getTheme()
detectDayChange()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return db.sizeOfTodo()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FinCell") as! FinTableViewCell
guard let selected = db.getTodo(from: indexPath.row) else {fatalError("Invalid index in finToday")}
var color = Settings.cellColors()[0]
if let repetition = selected.repetition.value {
color = Settings.cellColors()[repetition]
}
cell.categoryLabel.text = selected.category
cell.rangeLabel.text = selected.range
cell.categoryLabel.textColor = Settings.adjustTint(color)
cell.rangeLabel.textColor = Settings.adjustTint(color)
cell.backgroundColor = color
cell.delegate = self
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showFinData", sender: self)
}
//MARK: - 앱 실행 관련 함수
func initializeData() {
db = Database.getInstance()
if date.loadLastDate() == nil {
initFirstTime()
}
date.updateLastDate()
}
func initFirstTime() {
debugPrint("This is first time to run app.")
Settings.settings.changeTheme(to: 0)
Settings.setNotification(false)
insert(FinData(category: NSLocalizedString("Swipe the cell", comment: ""), range: "<-------------------------------"))
tableView.reloadData()
}
//MARK: - 화면 전환 관련 함수
override func viewWillAppear(_ animated: Bool) {
Settings.settings.delegate = self // 자식 뷰에서 나올 때 SettingDelegate 재적용
Settings.setUI()
}
//MARK: - Navigation Bar 관련 함수
func setNavBar() {
guard let navigationBar = navigationController?.navigationBar else {fatalError()}
let bar = Settings.background()
let tint = Settings.tint()
let navigationBarAppearance = UINavigationBarAppearance()
navigationBar.barTintColor = bar
navigationBar.tintColor = tint
navigationBarAppearance.configureWithOpaqueBackground()
navigationBarAppearance.titleTextAttributes = [.foregroundColor:tint]
navigationBarAppearance.largeTitleTextAttributes = [.foregroundColor:tint]
navigationBarAppearance.backgroundColor = bar
navigationBar.standardAppearance = navigationBarAppearance
navigationBar.scrollEdgeAppearance = navigationBarAppearance
}
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "addNewFinData", sender: self)
}
@IBAction func settingButtonPressed(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "changeSettings", sender: self)
}
//MARK: - Segue 관련 함수
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "addNewFinData":
prepare(to: segue.destination as! AddFinViewController)
case "showFinData":
prepare(to: segue.destination as! FinInfoViewController)
case "changeSettings":
prepare(to: segue.destination as! SettingTableViewController)
default:
debugPrint("Cannot find matching identifier.")
}
}
func prepare(to destination: AddFinViewController) {
destination.delegate = self
destination.categories = categories
}
func prepare(to destination: FinInfoViewController) {
guard let indexPath = tableView.indexPathForSelectedRow else {fatalError()}
if let selectedFin = db.getTodo(from: indexPath.row) {
destination.currentFin = selectedFin
destination.selectedRow = indexPath.row
destination.delegate = self
}
}
func prepare(to destination: SettingTableViewController) {
destination.categories = categories
destination.delegate = self
}
func clear(_ data: FinData) {
db.clear(data)
}
//MARK: - 날짜 관련 함수
func detectDayChange() {
let notificationArray = [UIApplication.significantTimeChangeNotification, UIApplication.didBecomeActiveNotification]
for notification in notificationArray {
NotificationCenter.default.addObserver(forName: notification, object: nil, queue: nil) {_ in
Settings.today = Date()
self.initializeData()
self.tableView.reloadData()
}
}
}
}
//MARK: - SwipeTableView 라이브러리
extension FinTableViewController: SwipeTableViewCellDelegate {
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
if orientation == .right {
let clearAction = SwipeAction(style: .destructive, title: NSLocalizedString("Clear", comment: "")) { action, indexPath in
guard let cleared = self.db.getTodo(from: indexPath.row) else {fatalError()}
self.clear(cleared)
}
setSwipeAction(clearAction, img: "done-icon")
return [clearAction]
}
return nil
}
func setSwipeAction (_ action: SwipeAction, img imgName: String) {
action.image = UIImage(named: imgName)!.withRenderingMode(.alwaysTemplate)
action.backgroundColor = Settings.background()
action.textColor = Settings.tint()
}
func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions {
var options = SwipeOptions()
options.expansionStyle = .destructive
return options
}
}
//MARK:- FinDelegate 관련 함수
extension FinTableViewController: FinDelegate {
func insert(_ data: FinData) {
db.insert(data)
tableView.reloadData()
}
func getCategories(_ list: [String]) {
categories = list
}
func isAlreadyExist(_ data: FinData) -> Bool {
return db.isThere(data)
}
func delete(_ data: FinData) {
db.delete(fin: data)
tableView.reloadData()
}
func deleteAll() {
db.deleteAll()// Realm 저장소 초기화
categories = [] // 이름 목록 삭제(Userdefaults에도 자동 적용)
initializeData()
}
}
//MARK: - SettingDelegate 관련 함수
extension FinTableViewController: SettingDelegate {
func adjustColor() {
setNavBar()
tableView.backgroundColor = Settings.background()
tableView.reloadData()
}
}
protocol FinDelegate {
func insert(_ data: FinData)
func getCategories(_ list: [String])
func delete(_ data: FinData)
func deleteAll()
func isAlreadyExist(_ data: FinData) -> Bool
}
|
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Document, Page, Text, View, StyleSheet, PDFDownloadLink } from '@react-pdf/renderer';
import '../styles/MostReservedVehiclesReport.css';
const MostReservedVehiclesReport = () => {
const [mostReservedVehicles, setMostReservedVehicles] = useState([]);
useEffect(() => {
const fetchMostReservedVehicles = async () => {
try {
const response = await axios.get('http://localhost:3000/reportes/vehiculos-mas-reservados');
setMostReservedVehicles(response.data);
} catch (error) {
console.error('Error fetching most reserved vehicles', error);
}
};
fetchMostReservedVehicles();
}, []);
const MyDocument = () => (
<Document>
<Page style={styles.page}>
<View style={styles.section}>
<Text style={styles.title}>Vehículos más reservados</Text>
<View style={styles.vehicleList}>
{mostReservedVehicles.map((vehicle, index) => (
<Text key={index} style={styles.vehicleItem}>
{vehicle._id} - {vehicle.count} reservas
</Text>
))}
</View>
</View>
</Page>
</Document>
);
const styles = StyleSheet.create({
page: {
flexDirection: 'row',
backgroundColor: '#E4E4E4',
},
section: {
margin: 10,
padding: 10,
flexGrow: 1,
},
title: {
fontSize: 24,
marginBottom: 10,
},
vehicleList: {
fontSize: 16,
},
vehicleItem: {
marginBottom: 5,
},
});
return (
<div className="report-container">
<h2 className="report-title">Vehículos más reservados</h2>
<ul className="vehicle-list">
{mostReservedVehicles.map((vehicle, index) => (
<li key={index} className="vehicle-item">
<span className="vehicle-name">{vehicle._id}</span> - <span className="reservations-count">{vehicle.count} reservas</span>
</li>
))}
</ul>
<PDFDownloadLink document={<MyDocument />} fileName="most_reserved_vehicles_report.pdf">
{({ blob, url, loading, error }) =>
loading ? 'Cargando documento...' : 'Descargar PDF'
}
</PDFDownloadLink>
</div>
);
};
export default MostReservedVehiclesReport;
|
package com.lcx.controller.advice;
import com.lcx.util.NiuKeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Create by LCX on 8/5/2022 11:08 AM
*/
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {
private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
@ExceptionHandler({Exception.class})
public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
logger.error("服务器发生异常:" + e.getMessage());
for (StackTraceElement element : e.getStackTrace()) {
logger.error(element.toString());
}
String xRequestedWith = request.getHeader("X-Requested-With");
if ("XMLHttpRequest".equals(xRequestedWith)) {
// application/plain --》 默认为普通格式的数据,
// 当发送json格式的数据给页面时,需要人为的转换成json格式的数据来显示,即$.parseJSON()
response.setContentType("application/plain;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.write(NiuKeUtil.getJSONString(1, "服务器异常!"));
} else {
response.sendRedirect(request.getContextPath() + "/error");
}
}
}
|
package com.syh.algorithm.leetcode.hard;
import com.syh.algorithm.leetcode.ListNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
* k 是一个正整数,它的值小于或等于链表的长度。
* 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
* 示例 1:
* 输入:head = [1,2,3,4,5], k = 2
* 输出:[2,1,4,3,5]
* 示例 2:
* 输入:head = [1,2,3,4,5], k = 3
* 输出:[3,2,1,4,5]
* 示例 3:
* 输入:head = [1,2,3,4,5], k = 1
* 输出:[1,2,3,4,5]
* 示例 4:
* 输入:head = [1], k = 1
* 输出:[1]
*/
public class ReverseKGroup {
public static void main(String[] args) {
ListNode node = ListNode.buildNode(Arrays.asList(1, 2, 3, 4, 5));
System.out.println(new ReverseKGroup().reverseKGroup(node, 2));
}
/**
* 时间复杂度为 O(n*K) 最好的情况为 O(n) 最差的情况未 O(n^2)
* 空间复杂度为 O(1) 除了几个必须的节点指针外,我们并没有占用其他空间
*/
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0);
dummy.next = head;
// 双指针记录需要反转的头尾
ListNode pre = dummy;
ListNode end = dummy;
while (end.next != null) {
for (int i = 0; i < k && end != null; i++) end = end.next;
if (end == null) break;
ListNode start = pre.next;
ListNode next = end.next;
end.next = null;
pre.next = reverse(start);
start.next = next;
pre = start;
end = pre;
}
return dummy.next;
}
public ListNode reverse(ListNode head) {
ListNode pre = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\CommonService;
use App\Models\CoaDetailAccount;
use App\Services\PermissionService;
use Illuminate\Support\Facades\Auth;
use App\Services\ChartOfAccountService;
use App\Services\CoaDetailAccountService;
use Illuminate\Database\Eloquent\RelationNotFoundException;
class CoaDetailAccountController extends Controller
{
private $chartOfAccountService;
private $permissionService;
private $commonService;
private $coaDetailAccountService;
public function __construct(CoaDetailAccountService $coaDetailAccountService, ChartOfAccountService $chartOfAccountService, PermissionService $permissionService, CommonService $commonService)
{
$this->chartOfAccountService = $chartOfAccountService;
$this->permissionService = $permissionService;
$this->commonService = $commonService;
$this->coaDetailAccountService = $coaDetailAccountService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$detailAccounts = $this->coaDetailAccountService->getListOfDetailAccounts($request->search);
$permission = $this->permissionService->getUserPermission(Auth::user()->id, '24');
$pageTitle = 'List of Detail accounts';
return view('chart-of-accounts.detail-account.index', compact('detailAccounts', 'permission', 'pageTitle'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$pageTitle = 'Create Detail Account';
$title = 'Detail Account';
$mainHeads = $this->chartOfAccountService->getMainHeads();
$controlHeads = $this->chartOfAccountService->getControlHeads();
$subHeads = $this->chartOfAccountService->getSubHeads();
$subSubHeads = $this->chartOfAccountService->getSubSubHeads();
$permission = $this->permissionService->getUserPermission(Auth::user()->id, '24');
return view('chart-of-accounts.detail-account.create', compact('permission', 'controlHeads', 'pageTitle', 'title', 'mainHeads', 'subHeads', 'subSubHeads'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
try {
$this->coaDetailAccountService->storeAccountData($request);
$message = !empty(request('id')) ? config('constants.update') : config('constants.add');
session()->flash('message', $message);
return redirect('detail-account/list');
} catch (\Throwable $exception) {
return back()->withError($exception->getMessage())->withInput();
} catch (RelationNotFoundException $exception) {
return back()->withError($exception->getMessage())->withInput();
}
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$pageTitle = 'Update Detail Account';
$detailAccount = CoaDetailAccount::find($id);
if (!$detailAccount) {
return abort(404);
}
$mainHeads = $this->chartOfAccountService->getMainHeads();
$controlHeads = $this->chartOfAccountService->getControlHeadsForMainHead($detailAccount->main_head);
$subHeads = $this->chartOfAccountService->getSubHeadsForControlHead($detailAccount->control_head);
$subSubHeads = $this->chartOfAccountService->getSubSubHeadsBySubHead($detailAccount->sub_head);
$permission = $this->permissionService->getUserPermission(Auth::user()->id, '13');
return view('chart-of-accounts.detail-account.create', compact('detailAccount', 'subSubHeads', 'subHeads', 'controlHeads', 'mainHeads', 'permission', 'pageTitle'));
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
/**
* Remove the specified resource from storage.
*
* @param \App\Models\coa_sub_head $coa_control_head
* @return \Illuminate\Http\Response
*/
public function destroy()
{
return $this->commonService->deleteResource(CoaDetailAccount::class);
}
/**
* Get maximum account code
*
* @param $mainHead
* @return \Illuminate\Http\Response
*/
public function getMaxDetailAccountCode($subSubHead)
{
$detailAccountCode = $this->coaDetailAccountService->generateDetailAccountCode($subSubHead);
return response()->json(['status' => 'success', 'account_code' => $detailAccountCode]);
}
public function getSubSubHeadAccountsBySubHead($subHead)
{
$subSubAccounts = $this->coaDetailAccountService->getSubSubHeadsBySubHead($subHead);
if ($subSubAccounts) {
return response()->json(['status' => 'success', 'data' => $subSubAccounts ? $subSubAccounts : []]);
}
}
}
|
import { render, screen } from '../../../test-utils/testing-library-utils';
import Options from '../Options';
import OrderEntry from '../OrderEntry';
import userEvent from '@testing-library/user-event';
// we test an isolated component so in order to get context here in tests we need to wrap it with context
// you can wrap it in redux provider, router etc
// render(<Options optionType="scoops" />, { wrapper: OrderDetailsProvider });
test('update scoop subtotal when scoops change', async () => {
const user = userEvent.setup();
render(<Options optionType="scoops" />);
// make sure total starts out at $0.00
const scoopsSubtotal = screen.getByText('Scoops total: $', { exact: false });
expect(scoopsSubtotal).toHaveTextContent('0.00');
// update vanilla scoops to 1, and check subtotal
const vanillaInput = await screen.findByRole('spinbutton', { name: 'Vanilla' });
await user.clear(vanillaInput);
await user.type(vanillaInput, '1');
expect(scoopsSubtotal).toHaveTextContent('2.00');
// update chocolate scoops to 2 and check subtotal
const chocolateInput = await screen.findByRole('spinbutton', { name: 'Chocolate' });
await user.clear(chocolateInput);
await user.type(chocolateInput, '2');
expect(scoopsSubtotal).toHaveTextContent('6.00');
});
test('update toppings subtotal when toppings change', async () => {
const user = userEvent.setup();
render(<Options optionType="toppings" />);
const toppingsSubtotal = screen.getByText('Toppings total: $', { exact: false });
expect(toppingsSubtotal).toHaveTextContent('0.00');
const cherriesCheckbox = await screen.findByRole('checkbox', { name: 'Cherries' });
await user.click(cherriesCheckbox);
expect(toppingsSubtotal).toHaveTextContent('1.50');
expect(cherriesCheckbox).toBeChecked();
const hotFudgeCheckbox = await screen.findByRole('checkbox', { name: 'Hot fudge' });
await user.click(hotFudgeCheckbox);
expect(toppingsSubtotal).toHaveTextContent('3.00');
await user.click(hotFudgeCheckbox);
expect(hotFudgeCheckbox).not.toBeChecked();
expect(toppingsSubtotal).toHaveTextContent('1.50');
});
describe('grand total', () => {
test('grand total starts at $0.00', () => {
render(<OrderEntry />);
const grandTotal = screen.getByRole('heading', { name: /Grand total: \$/i });
expect(grandTotal).toHaveTextContent('0.00');
});
test('grand total updates properly if scoop is added first', async () => {
const user = userEvent.setup();
render(<OrderEntry />);
const grandTotal = screen.getByRole('heading', { name: /Grand total: \$/i });
const vanillaInput = await screen.findByRole('spinbutton', { name: 'Vanilla' });
await user.clear(vanillaInput);
await user.type(vanillaInput, '2');
expect(grandTotal).toHaveTextContent('4.00');
const cherriesCheckbox = await screen.findByRole('checkbox', { name: 'Cherries' });
await user.click(cherriesCheckbox);
expect(grandTotal).toHaveTextContent('5.50');
});
test('grand total updates properly if topping is added first', async () => {
const user = userEvent.setup();
render(<OrderEntry />);
const grandTotal = screen.getByRole('heading', { name: /Grand total: \$/i });
const cherriesCheckbox = await screen.findByRole('checkbox', { name: 'Cherries' });
await user.click(cherriesCheckbox);
expect(grandTotal).toHaveTextContent('1.50');
const vanillaInput = await screen.findByRole('spinbutton', { name: 'Vanilla' });
await user.clear(vanillaInput);
await user.type(vanillaInput, '1');
expect(grandTotal).toHaveTextContent('3.50');
});
test('grand total updates properly if item is removed', async () => {
const user = userEvent.setup();
render(<OrderEntry />);
const grandTotal = screen.getByRole('heading', { name: /Grand total: \$/i });
const cherriesCheckbox = await screen.findByRole('checkbox', { name: 'Cherries' });
await user.click(cherriesCheckbox);
const vanillaInput = await screen.findByRole('spinbutton', { name: 'Vanilla' });
await user.clear(vanillaInput);
await user.type(vanillaInput, '2');
await user.clear(vanillaInput);
await user.type(vanillaInput, '1');
expect(grandTotal).toHaveTextContent('3.50');
await user.click(cherriesCheckbox);
expect(grandTotal).toHaveTextContent('2.00');
});
});
|
using CompraInteractiva.Properties;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace CompraInteractiva
{
public partial class Tienda : Form
{
private static Dictionary<string, Image> imagenes;
private String equipo;
private List<String> equiposElegidos = new List<String>();
private String periferico;
private int precioPeriferico;
private String metodoPago;
private List<String> productos = new List<string>();
private int total = 0;
public Tienda()
{
InitializeComponent();
InicializarControles();
InicilizarImagenes();
}
private void InicilizarImagenes()
{
//Creamos un clave valor con el nombre y la foto
imagenes = new Dictionary<string, Image>
{
{ radioPc.Name, Resources.pc },
{ radioMacintosh.Name, Resources.macintosh },
{ radioPortatil.Name, Resources.portatil },
{ checkContestador.Name, Resources.contestador },
{ checkCalculadora.Name, Resources.calculadora },
{ checkFotoCopiadora.Name, Resources.fotocopiadora },
{ listBoxPerifericos.Items[0].ToString(), Resources.discoDuro },
{ listBoxPerifericos.Items[1].ToString(), Resources.impresora },
{ listBoxPerifericos.Items[2].ToString(), Resources.antena },
{ cmboBoxMetodoPago.Items[0].ToString(), Resources.tarjeta },
{ cmboBoxMetodoPago.Items[1].ToString(), Resources.paypal },
{ cmboBoxMetodoPago.Items[2].ToString(), Resources.bizum }
};
}
private void InicializarControles()
{
//Iniciamos los valores de los perifericos
listBoxPerifericos.Items.Add("Disco duro adicional (75$)");
listBoxPerifericos.Items.Add("Impresora (90$)");
listBoxPerifericos.Items.Add("Antena (50$)");
//Iniciamos los valores de los metodos de pago
cmboBoxMetodoPago.Items.Add("Tarjeta");
cmboBoxMetodoPago.Items.Add("PayPal");
cmboBoxMetodoPago.Items.Add("Bizum");
}
//Cargamos las imagenes de el equipo al dar click
private void radioPc_CheckedChanged(object sender, EventArgs e)
{
if (radioPc.Checked)
{
pictureEquipo.Image = imagenes[radioPc.Name];
total += 700;
equipo = radioPc.Text;
}
else
{
total -= 700;
}
}
private void radioMacintosh_CheckedChanged(object sender, EventArgs e)
{
if (radioMacintosh.Checked)
{
pictureEquipo.Image = imagenes[radioMacintosh.Name];
total += 1000;
equipo = radioMacintosh.Text;
}
else
{
total -= 1000;
}
}
private void radioPortatil_CheckedChanged(object sender, EventArgs e)
{
if (radioPortatil.Checked)
{
pictureEquipo.Image = imagenes[radioPortatil.Name];
total += 500;
equipo = radioPortatil.Text;
}
else
{
total -= 500;
}
}
//Cargamos imagenes de los equipos de oficina
private void checkContestador_CheckedChanged(object sender, EventArgs e)
{
if (checkContestador.Checked)
{
pictureContestador.Image = imagenes[checkContestador.Name];
equiposElegidos.Add(checkContestador.Text);
total += 50;
}
else
{
pictureContestador.Image = null;
equiposElegidos.Remove(checkContestador.Text);
total -= 50;
}
}
private void checkCalculadora_CheckedChanged(object sender, EventArgs e)
{
if (checkCalculadora.Checked)
{
pictureCalculadora.Image = imagenes[checkCalculadora.Name];
equiposElegidos.Add(checkCalculadora.Text);
total += 20;
}
else
{
pictureCalculadora.Image = null;
equiposElegidos.Remove(checkCalculadora.Text);
total -= 20;
}
}
private void checkFotoCopiadora_CheckedChanged(object sender, EventArgs e)
{
if (checkFotoCopiadora.Checked)
{
pictureFotoCopiadora.Image = imagenes[checkFotoCopiadora.Name];
equiposElegidos.Add(checkFotoCopiadora.Text);
total += 100;
}
else
{
pictureFotoCopiadora.Image = null;
equiposElegidos.Remove(checkFotoCopiadora.Text);
total -= 100;
}
}
//Cargamos imagenes de perifericos
private void listBoxPerifericos_SelectedIndexChanged(object sender, EventArgs e)
{
switch (listBoxPerifericos.SelectedIndex)
{
case 0:
picturePeriferico.Image = imagenes[listBoxPerifericos.Items[0].ToString()];
precioPeriferico = 75;
periferico = listBoxPerifericos.Items[0].ToString();
break;
case 1:
picturePeriferico.Image = imagenes[listBoxPerifericos.Items[1].ToString()];
periferico = listBoxPerifericos.Items[1].ToString();
precioPeriferico = 90;
break;
case 2:
picturePeriferico.Image = imagenes[listBoxPerifericos.Items[2].ToString()];
periferico = listBoxPerifericos.Items[2].ToString();
precioPeriferico = 50;
break;
}
}
//Cargamos imagenes de metodo de pago
private void cmboBoxMetodoPago_SelectedIndexChanged(object sender, EventArgs e)
{
switch (cmboBoxMetodoPago.SelectedIndex)
{
case 0:
picturePago.Image = imagenes[cmboBoxMetodoPago.Items[0].ToString()];
metodoPago = cmboBoxMetodoPago.Items[0].ToString();
break;
case 1:
picturePago.Image = imagenes[cmboBoxMetodoPago.Items[1].ToString()];
metodoPago = cmboBoxMetodoPago.Items[1].ToString();
break;
case 2:
picturePago.Image = imagenes[cmboBoxMetodoPago.Items[2].ToString()];
metodoPago = cmboBoxMetodoPago.Items[2].ToString();
break;
}
}
//Boton de salir
private void btSalir_Click(object sender, EventArgs e)
{
Application.Exit();
}
//Presupuestos
private void btnPresupuesto_Click(object sender, EventArgs e)
{
if (cmboBoxMetodoPago.SelectedIndex == -1)
{
errorProvider.SetError(cmboBoxMetodoPago, "Seleccione un metodo de pago");
}
else
{
recontarProductos();
mostrarPresupuesto(productos);
errorProvider.SetError(cmboBoxMetodoPago, "");
}
}
private void recontarProductos()
{
productos.Clear();
//Agregamos todo lo seleccionado
productos.Add(equipo);
foreach (var product in equiposElegidos)
{
productos.Add(product);
}
productos.Add(periferico);
}
private void mostrarPresupuesto(List<String> productos)
{
Presupuesto presupuesto = new Presupuesto(productos, metodoPago, (total + precioPeriferico));
presupuesto.Show();
}
}
}
|
/* Copyright (c) 2022 StoneAtom, Inc. All rights reserved.
Use is subject to license terms
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA
*/
#ifndef STONEDB_CORE_HASH_TABLE_H_
#define STONEDB_CORE_HASH_TABLE_H_
#pragma once
#include <memory>
#include <vector>
#include "base/util/spinlock.h"
#include "core/bin_tools.h"
#include "mm/traceable_object.h"
namespace stonedb {
namespace core {
class HashTable : public mm::TraceableObject {
public:
struct CreateParams {
std::vector<int> keys_length;
std::vector<int> tuples_length;
int64_t max_table_size = 0;
bool easy_roughable = false;
};
class Finder;
HashTable(const std::vector<int> &keys_length, const std::vector<int> &tuples_length);
explicit HashTable(const CreateParams &create_params);
HashTable(HashTable &&table) = default;
~HashTable();
void Initialize(int64_t max_table_size, bool easy_roughable);
size_t GetKeyBufferWidth() const { return key_buf_width_; }
int64_t GetCount() const { return rows_count_; }
int64_t AddKeyValue(const std::string &key_buffer, bool *too_many_conflicts = nullptr);
void SetTupleValue(int col, int64_t row, int64_t value);
int64_t GetTupleValue(int col, int64_t row);
private:
// Overridden from mm::TraceableObject:
mm::TO_TYPE TraceableType() const override { return mm::TO_TYPE::TO_TEMPORARY; }
std::vector<int> column_size_;
bool for_count_only_ = false;
std::vector<int> column_offset_;
size_t key_buf_width_ = 0; // in bytes
size_t total_width_ = 0; // in bytes
int multi_offset_ = 0;
int64_t rows_count_ = 0;
int64_t rows_limit_ = 0; // a capacity of one memory buffer
int64_t rows_of_occupied_ = 0;
unsigned char *buffer_ = nullptr;
// Rows locks, max is 10000, if fill the hash table, lock N %
// rows_lock_.size().
std::vector<base::util::spinlock> rows_lock_;
};
class HashTable::Finder {
public:
Finder(HashTable *hash_table, std::string *key_buffer);
~Finder() = default;
int64_t GetMatchedRows() const { return matched_rows_; }
// If null rows, return common::NULL_VALUE_64.
int64_t GetNextRow();
private:
void LocateMatchedPosition();
HashTable *hash_table_ = nullptr;
std::string *key_buffer_ = nullptr;
int64_t matched_rows_ = 0;
int64_t current_row_ = 0; // row value to be returned by the next GetNextRow() function
int64_t to_be_returned_ = 0; // the number of rows left for GetNextRow()
int64_t current_iterate_step_ = 0;
};
} // namespace core
} // namespace stonedb
#endif // STONEDB_CORE_HASH_TABLE_H_
|
"""Buffer List Mixin."""
# Copyright (C) 2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import torch
from torch import nn
class BufferListMixin(nn.Module):
"""Buffer List Mixin.
This mixin is used to allow registering a list of tensors as buffers in a pytorch module.
Example:
>>> class MyModule(BufferListMixin, nn.Module):
... def __init__(self):
... super().__init__()
... tensor_list = [torch.ones(3) * i for i in range(3)]
... self.register_buffer_list("my_buffer_list", tensor_list)
>>> module = MyModule()
>>> # The buffer list can be accessed as a regular attribute
>>> module.my_buffer_list
[
tensor([0., 0., 0.]),
tensor([1., 1., 1.]),
tensor([2., 2., 2.])
]
>>> # We can update the buffer list at any time
>>> new_tensor_list = [torch.ones(3) * i + 10 for i in range(3)]
>>> module.register_buffer_list("my_buffer_list", new_tensor_list)
>>> module.my_buffer_list
[
tensor([10., 10., 10.]),
tensor([11., 11., 11.]),
tensor([12., 12., 12.])
]
>>> # Move to GPU. Since the tensors are registered as buffers, device placement is handled automatically
>>> module.cuda()
>>> module.my_buffer_list
[
tensor([10., 10., 10.], device='cuda:0'),
tensor([11., 11., 11.], device='cuda:0'),
tensor([12., 12., 12.], device='cuda:0')
]
"""
def register_buffer_list(self, name: str, values: list[torch.Tensor], persistent: bool = True, **kwargs) -> None:
"""Register a list of tensors as buffers in a pytorch module.
Each tensor is registered as a buffer with the name `_name_i` where `i` is the index of the tensor in the list.
To update and retrieve the list of tensors, we dynamically assign a descriptor attribute to the class.
Args:
name (str): Name of the buffer list.
values (list[torch.Tensor]): List of tensors to register as buffers.
persistent (bool, optional): Whether the buffers should be saved as part of the module state_dict.
Defaults to True.
**kwargs: Additional keyword arguments to pass to `torch.nn.Module.register_buffer`.
"""
for i, value in enumerate(values):
self.register_buffer(f"_{name}_{i}", value, persistent=persistent, **kwargs)
setattr(BufferListMixin, name, BufferListDescriptor(name, len(values)))
class BufferListDescriptor:
"""Buffer List Descriptor.
This descriptor is used to allow registering a list of tensors as buffers in a pytorch module.
Args:
name (str): Name of the buffer list.
length (int): Length of the buffer list.
"""
def __init__(self, name: str, length: int) -> None:
self.name = name
self.length = length
def __get__(self, instance: object, object_type: type | None = None) -> list[torch.Tensor]:
"""Get the list of tensors.
Each element of the buffer list is stored as a buffer with the name `name_i` where `i` is the index of the
element in the list. We use list comprehension to retrieve the list of tensors.
Args:
instance (object): Instance of the class.
object_type (Any, optional): Type of the class. Defaults to None.
Returns:
list[torch.Tensor]: Contents of the buffer list.
"""
del object_type
return [getattr(instance, f"_{self.name}_{i}") for i in range(self.length)]
def __set__(self, instance: object, values: list[torch.Tensor]) -> None:
"""Set the list of tensors.
Assigns a new list of tensors to the buffer list by updating the individual buffer attributes.
Args:
instance (object): Instance of the class.
values (list[torch.Tensor]): List of tensors to set.
"""
for i, value in enumerate(values):
setattr(instance, f"_{self.name}_{i}", value)
|
import type {
IDataObject,
IExecuteFunctions,
INodeExecutionData,
INodeProperties,
} from 'n8n-workflow';
import type { QueryRunner, QueryValues, QueryWithValues } from '../../helpers/interfaces';
import { AUTO_MAP, DATA_MODE } from '../../helpers/interfaces';
import { escapeSqlIdentifier, replaceEmptyStringsByNulls } from '../../helpers/utils';
import { optionsCollection } from '../common.descriptions';
import { updateDisplayOptions } from '@utils/utilities';
const properties: INodeProperties[] = [
{
displayName: 'Data Mode',
name: 'dataMode',
type: 'options',
options: [
{
name: 'Auto-Map Input Data to Columns',
value: DATA_MODE.AUTO_MAP,
description: 'Use when node input properties names exactly match the table column names',
},
{
name: 'Map Each Column Below',
value: DATA_MODE.MANUAL,
description: 'Set the value for each destination column manually',
},
],
default: AUTO_MAP,
description:
'Whether to map node input properties and the table data automatically or manually',
},
{
displayName: `
In this mode, make sure incoming data fields are named the same as the columns in your table. If needed, use an 'Edit Fields' node before this node to change the field names.
`,
name: 'notice',
type: 'notice',
default: '',
displayOptions: {
show: {
dataMode: [DATA_MODE.AUTO_MAP],
},
},
},
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-wrong-for-dynamic-options
displayName: 'Column to Match On',
name: 'columnToMatchOn',
type: 'options',
required: true,
// eslint-disable-next-line n8n-nodes-base/node-param-description-wrong-for-dynamic-options
description:
'The column to compare when finding the rows to update. Choose from the list, or specify an ID using an <a href="https://docs.n8n.io/code-examples/expressions/" target="_blank">expression</a>.',
typeOptions: {
loadOptionsMethod: 'getColumns',
loadOptionsDependsOn: ['schema.value', 'table.value'],
},
default: '',
hint: "Used to find the correct row to update. Doesn't get changed. Has to be unique.",
},
{
displayName: 'Value of Column to Match On',
name: 'valueToMatchOn',
type: 'string',
default: '',
description:
'Rows with a value in the specified "Column to Match On" that corresponds to the value in this field will be updated. New rows will be created for non-matching items.',
displayOptions: {
show: {
dataMode: [DATA_MODE.MANUAL],
},
},
},
{
displayName: 'Values to Send',
name: 'valuesToSend',
placeholder: 'Add Value',
type: 'fixedCollection',
typeOptions: {
multipleValueButtonText: 'Add Value',
multipleValues: true,
},
displayOptions: {
show: {
dataMode: [DATA_MODE.MANUAL],
},
},
default: {},
options: [
{
displayName: 'Values',
name: 'values',
values: [
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-wrong-for-dynamic-options
displayName: 'Column',
name: 'column',
type: 'options',
// eslint-disable-next-line n8n-nodes-base/node-param-description-wrong-for-dynamic-options
description:
'Choose from the list, or specify an ID using an <a href="https://docs.n8n.io/code-examples/expressions/" target="_blank">expression</a>',
typeOptions: {
loadOptionsMethod: 'getColumnsWithoutColumnToMatchOn',
loadOptionsDependsOn: ['schema.value', 'table.value'],
},
default: [],
},
{
displayName: 'Value',
name: 'value',
type: 'string',
default: '',
},
],
},
],
},
optionsCollection,
];
const displayOptions = {
show: {
resource: ['database'],
operation: ['upsert'],
},
hide: {
table: [''],
},
};
export const description = updateDisplayOptions(displayOptions, properties);
export async function execute(
this: IExecuteFunctions,
inputItems: INodeExecutionData[],
runQueries: QueryRunner,
nodeOptions: IDataObject,
): Promise<INodeExecutionData[]> {
let returnData: INodeExecutionData[] = [];
const items = replaceEmptyStringsByNulls(inputItems, nodeOptions.replaceEmptyStrings as boolean);
const queries: QueryWithValues[] = [];
for (let i = 0; i < items.length; i++) {
const table = this.getNodeParameter('table', i, undefined, {
extractValue: true,
}) as string;
const columnToMatchOn = this.getNodeParameter('columnToMatchOn', i) as string;
const dataMode = this.getNodeParameter('dataMode', i) as string;
let item: IDataObject = {};
if (dataMode === DATA_MODE.AUTO_MAP) {
item = items[i].json;
}
if (dataMode === DATA_MODE.MANUAL) {
const valuesToSend = (this.getNodeParameter('valuesToSend', i, []) as IDataObject)
.values as IDataObject[];
item = valuesToSend.reduce((acc, { column, value }) => {
acc[column as string] = value;
return acc;
}, {} as IDataObject);
item[columnToMatchOn] = this.getNodeParameter('valueToMatchOn', i) as string;
}
const onConflict = 'ON DUPLICATE KEY UPDATE';
const columns = Object.keys(item);
const escapedColumns = columns.map(escapeSqlIdentifier).join(', ');
const placeholder = `${columns.map(() => '?').join(',')}`;
const insertQuery = `INSERT INTO ${escapeSqlIdentifier(
table,
)}(${escapedColumns}) VALUES(${placeholder})`;
const values = Object.values(item) as QueryValues;
const updateColumns = Object.keys(item).filter((column) => column !== columnToMatchOn);
const updates: string[] = [];
for (const column of updateColumns) {
updates.push(`${escapeSqlIdentifier(column)} = ?`);
values.push(item[column] as string);
}
const query = `${insertQuery} ${onConflict} ${updates.join(', ')}`;
queries.push({ query, values });
}
returnData = await runQueries(queries);
return returnData;
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles/main.css">
<title>Homework_12</title>
</head>
<body>
<header>
<nav class="header-nav">
<a class="logo" href="index.html" target="_self"><img src="images/logo.svg" alt="HowTo"></a>
<div class="menu-search">
<ul class="menu">
<li><a href="#">პროექტის შესახებ</a></li>
<li><a href="#">მოთხოვნები</a></li>
<li><a href="#">EXPLORE</a></li>
<li><a href="#">შესვლა</a></li>
</ul>
<a href="index.html"><button class="burger"><img src="images/burger.png"></button></a>
<div class="responsive-menu">
<ul >
<li><a href="#">პროექტის შესახებ</a></li>
<li><a href="#">მოთხოვნები</a></li>
<li><a href="#">EXPLORE</a></li>
<li><a href="#">შესვლა</a></li>
</ul>
</div>
<div class="search-div">
<input type="search" name="search" id="search" class="search-input">
<button class="search-icon"><img src="images/search.svg" alt="Search"></button>
</div>
</div>
</nav>
</header>
<div class="container">
<div class="slider">
<img class="slides" src="images/recent2.jpg" alt="Slide Image">
<img class="slides" src="images/slide2.jpg" alt="Slide Image">
<img class="slides" src="images/slide3.jpg" alt="Slide Image">
<button class="slide-button-left" onclick="plusDivs(-1)">❮</button>
<button class="slide-button-right" onclick="plusDivs(1)">❯</button>
</div>
<script>
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("slides");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block"
}
</script>
<div class="popular">
<h2 class="div-title" >პოპულარული სტატიები</h2>
<div class="articles">
<article class="article-popular">
<img src="images/recent1.jpg" alt="Image">
<h3 class="article-title">სტატიის სათაური</h3>
<p class="article-text">ამ სტატიასაც სჭირდება აღწერა, ამიტომ ეს ველი დაეთმობა ამ სტატიის მოკლე აღწერას</p>
<a class="more" href="#">more</a>
</article>
<article class="article-popular">
<img src="images/recent2.jpg" alt="Image">
<h3 class="article-title">სტატიის სათაური</h3>
<p class="article-text">ამ სტატიასაც სჭირდება აღწერა, ამიტომ ეს ველი დაეთმობა ამ სტატიის მოკლე აღწერას</p>
<a class="more" href="#">more</a>
</article>
<article class="article-popular">
<img src="images/recent3.jpg" alt="Image">
<h3 class="article-title">სტატიის სათაური</h3>
<p class="article-text">ამ სტატიასაც სჭირდება აღწერა, ამიტომ ეს ველი დაეთმობა ამ სტატიის მოკლე აღწერას</p>
<a class="more" href="#">more</a>
</article>
</div>
<a class="load-more" href="#">Load more</a>
</div>
<div class="recent">
<h2 class="div-title">ბოლოს დამატებული</h2>
<div class="articles">
<article class="article-recent">
<img src="images/popular1.jpg" alt="Image">
<h3 class="article-title">სტატიის სათაური</h3>
<p class="article-text">ამ სტატიასაც სჭირდება აღწერა, ამიტომ ეს ველი დაეთმობა ამ სტატიის მოკლე აღწერას</p>
<a class="more" href="#">more</a>
</article>
<article class="article-recent">
<img src="images/popular2.jpg" alt="Image">
<h3 class="article-title">სტატიის სათაური</h3>
<p class="article-text">ამ სტატიასაც სჭირდება აღწერა, ამიტომ ეს ველი დაეთმობა ამ სტატიის მოკლე აღწერას</p>
<a class="more" href="#">more</a>
</article>
<article class="article-recent">
<img src="images/popular3.jpg" alt="Image">
<h3 class="article-title">სტატიის სათაური</h3>
<p class="article-text">ამ სტატიასაც სჭირდება აღწერა, ამიტომ ეს ველი დაეთმობა ამ სტატიის მოკლე აღწერას</p>
<a class="more" href="#">more</a>
</article>
</div>
</div>
</div>
<footer>
<nav class="footer-nav">
<a class="footer-logo" href="index.html" target="_self"><img src="images/logo.svg" alt="HowTo"></a>
<address class="contact">
<div class="virtual-contact">
<h4 class="contact-title">კონტაქტი</h4>
<a href="tel:+995 0322 38 08 02">+995 0322 38 08 02</a>
<a href="mailto:info@lucapolare.com.svg">info@lucapolare.com.svg</a>
</div>
<div class="physical-contact">
<h4 class="contact-title">მისამართი</h4>
<p>მერაბ ალექსიძის ქუჩა 10. თბილისი</p>
</div>
</address>
<ul class="social-icons">
<li>
<a href="https://www.facebook.com/"><img src="images/fb.svg" alt="Facebook"></a>
</li>
<li>
<a href="https://www.instagram.com/"><img src="images/instagram.svg" alt="Facebook"></a>
</li>
</ul>
</nav>
</footer>
</body>
</html>
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleLevelContract {
enum LevelType {
Level1,
Level2,
Level3,
Level4
}
enum StepType {
CallChief,
TriggerAlarm,
ExtinguishFire,
Escape
}
struct Level {
LevelType levelType;
uint256 mark;
uint256 time;
}
struct Player {
Level[] levels;
address pk;
mapping(LevelType => uint256) currentStepIndex; // Track current step index for each level
mapping(LevelType => uint256[]) marks; // Auxiliar structure to track marks for each level
}
mapping(LevelType => StepType[]) levelSteps;
mapping(address => Player) public players;
// Function to set steps for a specific level
function setLevelSteps(LevelType levelType, StepType[] memory steps) public {
levelSteps[levelType] = steps;
}
function isLevelCompleted(LevelType levelType) public view returns (bool) {
for (uint256 i = 0; i < players[msg.sender].levels.length; i++) {
if (players[msg.sender].levels[i].levelType == levelType) {
return true;
}
}
return false;
}
// Function to generate a random score (for demonstration purposes)
function getRandomScore() private view returns (uint256) {
uint256 randomNumber = uint256(
keccak256(
abi.encodePacked(block.timestamp, block.difficulty, msg.sender)
)
) % 101; // Generate a random number between 0 and 100
return randomNumber;
}
function performStep(LevelType levelType, StepType currentStep) public {
bool stepFound;
uint256 currentIndex;
uint256 randomMark;
require(!isLevelCompleted(levelType), "Level already completed");
Player storage player = players[msg.sender];
// Get the current step index for the level
currentIndex = player.currentStepIndex[levelType];
// Check if the performed step matches the required step
if (levelSteps[levelType][currentIndex] == currentStep) {
stepFound = true;
// Increment current step index for the level
player.currentStepIndex[levelType]++;
// Random mark (development)
randomMark = getRandomScore();
player.marks[levelType].push(randomMark);
}
require(stepFound, "Incorrect step performed");
// If all steps are completed
if (currentIndex == levelSteps[levelType].length - 1) {
uint256 totalMarks = 0;
for (uint256 i = 0; i < player.marks[levelType].length; i++) {
totalMarks += player.marks[levelType][i];
}
uint256 averageMark = totalMarks / player.marks[levelType].length;
player.levels.push(Level(levelType, averageMark, block.timestamp));
// Reset current step index and marks for the completed level
//delete player.marks[levelType];
//player.currentStepIndex[levelType] = 0;
}
}
}
|
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
raise IndexError("Stack is empty")
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
raise IndexError("Stack is empty")
def size(self):
return len(self.items)
def print(self):
print("Stack:", self.items)
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.print()
print(stack.size())
print(stack.pop())
print(stack.peek())
print(stack.is_empty())
|
/*
* Copyright (c) 2022-2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import router from '@ohos.router';
import prompt from '@ohos.prompt'
import { ServiceModel } from '../model/ServiceModel'
import { TitleBar } from '../component/TitleBar'
import { OperateView } from '../component/OperateView'
import rpc from "@ohos.rpc"
import reminderAgent from '@ohos.reminderAgent';
import notification from '@ohos.notification';
import Logger from '../model/Logger'
const TAG = "Index"
async function routePage() {
let options = {
url: 'pages/Selects'
}
try {
await router.push(options)
} catch (err) {
Logger.error(`${TAG} fail callback,code: ${err.code},msh: ${err.msg}`)
}
}
@Entry
@Component
struct Index {
private btnResources: Array<Resource> = [$r('app.string.connect_service'), $r('app.string.disconnect_service'), $r('app.string.set_alarm'), $r('app.string.set_calendar'), $r('app.string.start_game')]
private serviceModel = new ServiceModel()
private isStart: boolean = false;
@State beforeSortString: string = ''
@State afterSortString: string = ''
async sortString() {
Logger.info(`${TAG} sortString begin`)
let mRemote = this.serviceModel.getRemoteObject()
if (mRemote === null) {
prompt.showToast({
message: 'please connect service'
})
}
if (this.beforeSortString.length === 0) {
prompt.showToast({
message: 'please input a string'
})
}
let messageOption: rpc.MessageOption = new rpc.MessageOption()
let data: rpc.MessageParcel = rpc.MessageParcel.create()
let reply: rpc.MessageParcel = rpc.MessageParcel.create()
data.writeString(this.beforeSortString)
await mRemote.sendRequest(1, data, reply, messageOption)
let msg = reply.readString()
this.afterSortString = msg
}
// 闹钟实例对象,用于设置提醒的时间
async setGameRenmindAlarm() {
Logger.info(`${TAG} setGameRenmindAlarm begin`)
// publish reminder
let reminder: reminderAgent.ReminderRequestAlarm = {
reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM,
// 指明提醒的目标时刻
hour: 7,
// 指明提醒的目标分钟
minute: 24,
// 指明每周哪几天需要重复提醒。范围为周一到周末,对应数字为1到7
daysOfWeek: [1, 2, 3, 4, 5, 6, 7],
// 用于设置弹出的提醒通知信息上显示的按钮类型和标题
actionButton: [
{
title: "snooze",
type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE,
}
],
// wantAgent用于点击提醒通知后跳转的目标ability信息
wantAgent: {
pkgName: "ohos.samples.flybird",
abilityName: "EntryAbility"
},
// maxScreenWantAgent用于全屏显示提醒到达时自动拉起的目标ability信息,该接口预留
maxScreenWantAgent: {
pkgName: "ohos.samples.flybird",
abilityName: "EntryAbility"
},
// 指明响铃时长
ringDuration: 10,
// 指明延迟提醒次数
snoozeTimes: 2,
// 执行延迟提醒间隔
timeInterval: 5 * 60,
// 指明延迟提醒时需要显示的内容
snoozeContent: "later",
// 指明提醒标题
title: "game alarm",
// 指明提醒内容
content: "remember play game",
// 指明提醒过期后需要显示的内容
expiredContent: "expiredContent",
// 指明提醒使用的通知的id号,相同id号的提醒会覆盖
notificationId: 200,
}
reminderAgent.publishReminder(reminder);
}
async callback(err, data) {
if (err) {
Logger.error(TAG,`setGameRenmindAlarm failed Cause: ${err}`);
} else {
Logger.info(TAG ,'setGameRenmindAlarm succeeded');
}
}
// 日历实例对象,用于设置提醒的时间
async setGameRenmindCalendar() {
Logger.info(`${TAG} setGameRenmindCalendar begin`)
let calendar: {
reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR,
// 指明提醒的目标时间
dateTime: {
year: 2022,
month: 4,
day: 14,
hour: 7,
minute: 50,
second: 30
},
// 指明重复提醒的月份
repeatMonths: [1],
// 指明重复提醒的日期
repeatDays: [1],
wantAgent: {
pkgName: "ohos.samples.flybird",
abilityName: "EntryAbility"
},
maxScreenWantAgent: {
pkgName: "ohos.samples.flybird",
abilityName: "EntryAbility"
},
ringDuration: 5,
snoozeTimes: 2,
timeInterval: 5,
title: "game calendar",
content: "game calender",
expiredContent: "this reminder has expired",
snoozeContent: "remind later",
notificationId: 100,
slotType: notification.SlotType.SOCIAL_COMMUNICATION
}
reminderAgent.publishReminder(calendar);
}
async disconenctService() {
Logger.info(`${TAG} disconenctService begin`)
let mRemote = this.serviceModel.getRemoteObject()
if (mRemote === null) {
prompt.showToast({
message: 'please connect service'
})
}
let option: rpc.MessageOption = new rpc.MessageOption()
let data: rpc.MessageParcel = rpc.MessageParcel.create()
let reply: rpc.MessageParcel = rpc.MessageParcel.create()
data.writeString('disconnect_service')
await mRemote.sendRequest(1, data, reply, option)
let msg = reply.readString()
this.afterSortString = msg
}
async startGame() {
let mRemote = this.serviceModel.getRemoteObject()
if (mRemote === null) {
prompt.showToast({
message: 'please connect service'
})
} else {
if (!this.isStart) {
this.startGameEx()
this.isStart = true
}
routePage()
}
}
async startGameEx() {
Logger.info(`${TAG} startGame begin`)
let mRemote = this.serviceModel.getRemoteObject()
if (mRemote === null) {
prompt.showToast({
message: 'please connect service'
})
}
let option: rpc.MessageOption = new rpc.MessageOption()
let data: rpc.MessageParcel = rpc.MessageParcel.create()
let reply: rpc.MessageParcel = rpc.MessageParcel.create()
data.writeString("start_game")
await mRemote.sendRequest(1, data, reply, option)
let msg = reply.readString()
this.afterSortString = msg
}
build() {
Column() {
TitleBar()
Scroll() {
Column() {
OperateView({ before: $beforeSortString, after: $afterSortString })
ForEach(this.btnResources, (item, index) => {
Button() {
Text(item)
.fontColor(Color.White)
.fontSize(20)
}
.type(ButtonType.Capsule)
.backgroundColor('#0D9FFB')
.width('94%')
.height(50)
.margin(10)
.onClick(() => {
Logger.info(`${TAG} button clicked,index=${index}`)
switch (index) {
case 0:
this.serviceModel.connectService()
break
case 1:
this.disconenctService();
this.serviceModel.disconnectService()
break
case 2:
this.setGameRenmindAlarm();
break
case 3:
this.setGameRenmindCalendar();
break
case 4:
this.startGame()
break
default:
break
}
})
}, item => JSON.stringify(item))
}
}
.layoutWeight(1)
}
.width('100%')
.height('100%')
}
}
|
import { Effect, flow, pipe } from 'effect';
import { getEnabledTypes } from '../config/get-enabled-types';
import type { ErrorHandlers } from '../error-handlers/default-error-handlers';
import type { Ctx } from '../get-context';
import { canAddToGroup } from '../guards/can-add-to-group';
import type { Io } from '../io';
import { sortByName } from '../lib/sort-by-name';
import type { SemverGroup } from '../semver-group';
import { createSemverGroups } from '../semver-group/create-semver-groups';
import type { VersionGroup } from '../version-group';
import { createVersionGroups } from '../version-group/create-version-groups';
import type { Instance } from './instance';
interface Instances {
all: Instance[];
semverGroups: SemverGroup.Any[];
versionGroups: VersionGroup.Any[];
}
export function getInstances(
ctx: Ctx,
io: Io,
errorHandlers: ErrorHandlers,
): Effect.Effect<never, never, Instances> {
const exitOnError = Effect.flatMap(() => Effect.failSync(() => io.process.exit(1)));
return pipe(
Effect.Do,
Effect.bind('enabledTypes', () => getEnabledTypes(ctx.config)),
Effect.bind('semverGroups', () => createSemverGroups(ctx)),
Effect.bind('versionGroups', () => createVersionGroups(ctx)),
Effect.bind('instances', (acc) =>
pipe(
ctx.packageJsonFiles,
Effect.forEach((file) => file.getInstances(acc.enabledTypes)),
Effect.map((instancesByFile) => instancesByFile.flat()),
),
),
Effect.tap(({ instances, semverGroups, versionGroups }) =>
Effect.sync(() => {
for (const instance of instances) {
// assign each instance to its semver group, first match wins
assignToSemverGroup: for (const group of semverGroups) {
if (canAddToGroup(ctx.packageJsonFilesByName, group, instance)) {
instance.semverGroup = group;
group.instances.push(instance);
break assignToSemverGroup;
}
}
// assign each instance to its version group, first match wins
assignToVersionGroup: for (const group of versionGroups) {
if (canAddToGroup(ctx.packageJsonFilesByName, group, instance)) {
instance.versionGroup = group;
group.instances.push(instance);
break assignToVersionGroup;
}
}
}
}),
),
Effect.map(({ instances, semverGroups, versionGroups }) => ({
all: instances,
semverGroups: getSortedAndFiltered(semverGroups),
versionGroups: getSortedAndFiltered(versionGroups),
})),
Effect.catchTags({
DeprecatedTypesError: flow(errorHandlers.DeprecatedTypesError, exitOnError),
InvalidCustomTypeError: flow(errorHandlers.InvalidCustomTypeError, exitOnError),
RenamedWorkspaceTypeError: flow(errorHandlers.RenamedWorkspaceTypeError, exitOnError),
SemverGroupConfigError: flow(errorHandlers.SemverGroupConfigError, exitOnError),
VersionGroupConfigError: flow(errorHandlers.VersionGroupConfigError, exitOnError),
}),
);
function getSortedAndFiltered<T extends SemverGroup.Any | VersionGroup.Any>(groups: T[]) {
return groups.filter((group) => group.instances.sort(sortByName).length > 0);
}
}
|
<template>
<fs-page>
<fs-crud ref="crudRef" v-bind="crudBinding">
<template #actionbar-right>
<a-alert class="ml-1" type="info" message=" ← 在表单的各个位置都可以插入自定义内容" />
</template>
<template #form-header-left>
<a-tag color="red">form-header-left插槽</a-tag>
</template>
<template #form-header-right>
<a-tag color="red">form-header-right插槽</a-tag>
</template>
<template #form-header-action-left>
<a-tag color="red">form-header-action-left插槽</a-tag>
</template>
<template #form-header-action-right>
<a-tag color="red">form-header-action-right插槽</a-tag>
</template>
<template #form-body-top>
<a-alert type="warning" message="form-body-top 插槽" />
</template>
<template #form-body-bottom>
<a-alert type="warning" message="form-body-bottom 插槽" />
</template>
<template #form-footer-left>
<a-button type="danger">form-footer-left 插槽</a-button>
</template>
<template #form-footer-right>
<a-button type="danger">form-footer-right 插槽</a-button>
</template>
</fs-crud>
</fs-page>
</template>
<script lang="ts">
import { defineComponent, onMounted } from "vue";
import createCrudOptions from "./crud";
import { useFs } from "@fast-crud/fast-crud";
export default defineComponent({
name: "SlotsForm",
setup() {
const { crudBinding, crudRef, crudExpose } = useFs({ createCrudOptions });
// 页面打开后获取列表数据
onMounted(() => {
crudExpose.doRefresh();
});
return {
crudBinding,
crudRef
};
}
});
</script>
|
import { useForm } from "react-hook-form";
import { Link } from "react-router-dom";
import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2 } from "lucide-react";
import * as z from "zod";
import { Button } from "../../components/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "../../components/ui/form";
import { Input } from "../../components/ui/input";
import { AuthSuccessResponse, useRegister } from "../api";
const FormSchema = z.object({
email: z.string().email("Invalid email"),
password: z
.string()
.min(4, "Password must be at least 4 characters")
.regex(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{4,}$/,
"Password must contain an upper case letter, a lower case letter, a number, and a special character",
),
});
type RegisterFormProps = {
onRegister: (resp: AuthSuccessResponse) => void;
};
export default function RegisterForm(props: RegisterFormProps) {
const { onRegister } = props;
const registerMutation = useRegister({
onSuccess: onRegister,
onError: (error) => {
console.error(error);
},
});
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: {
email: "",
password: "",
},
});
function onSubmit(data: z.infer<typeof FormSchema>) {
registerMutation.mutate(data);
}
return (
<section className="flex flex-col items-center gap-4">
<Form {...form}>
<form
className="flex flex-col items-center"
onSubmit={form.handleSubmit(onSubmit)}
>
<h1 className="text-3xl font-sans font-bold">Create an account</h1>
<div className="flex flex-col items-center gap-5 mt-8 w-[360px]">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem className="w-full">
<FormLabel>Email</FormLabel>
<FormControl>
<Input
required
type="email"
placeholder="john@gmail.com"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem className="w-full">
<FormLabel>Password</FormLabel>
<FormControl>
<Input
required
type="password"
placeholder="********"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button
disabled={registerMutation.isPending}
type="submit"
className="w-full mt-2 animate-in slide-in-from-bottom-2"
>
{registerMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
{registerMutation.isPending ? "Please wait..." : "Register"}
</Button>
</div>
</form>
</Form>
<span className="text-sm text-zinc-500">
Already have an account?{" "}
<Link to="/auth/login" className="text-primary hover:underline">
Login
</Link>
</span>
</section>
);
}
|
const crypto = require("crypto");
const { promisify } = require("util");
const jwt = require("jsonwebtoken");
const User = require("./../models/userModel");
const catchAsync = require("./../utils/catchAsync");
const AppError = require("./../utils/appError");
const sendEmail = require("./../utils/email");
const signToken = (id) => {
return jwt.sign({ id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN,
});
};
const createSendToken = (user, statusCode, res) => {
const token = signToken(user._id);
const cookieOptions = {
expires: new Date(
Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000
),
httpOnly: true,
};
if (process.env.NODE_ENV === "production") cookieOptions.secure = true;
res.cookie("jwt", token, cookieOptions);
// Remove password from output
user.password = undefined;
res.status(statusCode).json({
status: "success",
token,
data: {
user,
},
});
};
exports.signup = catchAsync(async (req, res, next) => {
const newUser = await User.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password,
passwordConfirm: req.body.passwordConfirm,
});
// console.log(newUser);
res.status(201).json({
status: "success",
data: {
newUser,
},
});
});
exports.login = catchAsync(async (req, res, next) => {
const { email, password } = req.body;
// 1) Check if email and password exist
if (!email || !password) {
return next(new AppError("Please provide email and password!", 400));
}
// 2) Check if user exists && password is correct
const user = await User.findOne({ email }).select("+password");
if (!user || !(await user.correctPassword(password, user.password))) {
return next(new AppError("Incorrect email or password", 401));
}
// 3) If everything ok, send token to client
createSendToken(user, 200, res);
});
exports.forgotPassword = catchAsync(async (req, res, next) => {
// 1) Get user based on POSTed email
const user = await User.findOne({ email: req.body.email });
if (!user) {
return next(new AppError("There is no user with email address.", 404));
}
// 2) Generate the random reset token
const resetToken = user.createPasswordResetToken();
await user.save({ validateBeforeSave: false });
// 3) Send it to user's email
const resetURL = `${req.protocol}://${req.get(
"host"
)}/users/resetPassword/${resetToken}`;
const message = `Forgot your password? Please link on the link below to reset your password.\n https://url-shortenerapp.netlify.app/reset/${resetToken}.\nIf you didn't forget your password, please ignore this email!`;
try {
await sendEmail({
email: user.email,
subject: "Your password reset token (valid for 10 min)",
message,
});
res.status(200).json({
status: "success",
message: "Token sent to email!",
});
} catch (err) {
user.passwordResetToken = undefined;
user.passwordResetExpires = undefined;
await user.save({ validateBeforeSave: false });
return next(
new AppError("There was an error sending the email. Try again later!"),
500
);
}
});
exports.resetPassword = catchAsync(async (req, res, next) => {
// 1) Get user based on the token
const hashedToken = crypto
.createHash("sha256")
.update(req.params.token)
.digest("hex");
console.log(hashedToken);
const user = await User.findOne({
passwordResetToken: hashedToken,
passwordResetExpires: { $gt: Date.now() },
});
// 2) If token has not expired, and there is user, set the new password
if (!user) {
return next(new AppError("Token is invalid or has expired", 400));
}
user.password = req.body.password;
user.passwordConfirm = req.body.passwordConfirm;
user.passwordResetToken = undefined;
user.passwordResetExpires = undefined;
await user.save();
// 3) Update changedPasswordAt property for the user
// 4) Log the user in, send JWT
createSendToken(user, 200, res);
});
exports.protect = catchAsync(async (req, res, next) => {
// 1) Getting token and check of it's there
// let token;
// if (
// req.headers.authorization &&
// req.headers.authorization.startsWith("Bearer")
// ) {
// token = req.headers.authorization.split(" ")[1];
// }
let token = req.params.id;
if (!token) {
return next(
new AppError("You are not logged in! Please log in to get access.", 401)
);
}
// 2) Verification token
const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
// 3) Check if user still exists
const currentUser = await User.findById(decoded.id);
if (!currentUser) {
return next(
new AppError(
"The user belonging to this token does no longer exist.",
401
)
);
}
// 4) Check if user changed password after the token was issued
if (currentUser.changedPasswordAfter(decoded.iat)) {
return next(
new AppError("User recently changed password! Please log in again.", 401)
);
}
// GRANT ACCESS TO PROTECTED ROUTE
req.user = currentUser;
const id = req.user._id.toString();
// FOR USER UPDATION
if (req.body.name) {
const updatedUser = await User.findByIdAndUpdate(id, req.body, {
new: true,
runValidators: true,
});
res.status(200).json({
status: "success",
data: {
user: updatedUser,
},
});
}
next();
});
exports.updatePassword = catchAsync(async (req, res, next) => {
// 1) Get user from collection
const user = await User.findById(req.user.id).select("+password");
// 2) Check if POSTed current password is correct
if (!(await user.correctPassword(req.body.passwordCurrent, user.password))) {
return next(new AppError("Your current password is wrong.", 401));
}
// 3) If so, update password
user.password = req.body.password;
user.passwordConfirm = req.body.passwordConfirm;
await user.save();
// User.findByIdAndUpdate will NOT work as intended!
// 4) Log user in, send JWT
createSendToken(user, 200, res);
});
exports.activateAccount = catchAsync(async (req, res, next) => {
// 1) Get user from collection
const updatedUser = await User.findByIdAndUpdate(
req.params.id,
{ $set: { isActive: true } },
{
new: true,
runValidators: true,
}
);
res.status(200).json({
status: "success",
message: "User has been activated",
});
});
exports.activateEmail = catchAsync(async (req, res, next) => {
// 1) Get user from collection
console.log(req.body);
const userId = req.params.id;
const activateURL = `https://url-shortenerapp.netlify.app/authenticate/${userId}`;
const message = `Please activate your account by clicking on the link below.\n ${activateURL}`;
await sendEmail({
email: req.body.email,
subject: "Your password reset token (valid for 10 min)",
message,
});
res.status(200).json({
status: "success",
message: "Email has been sent!",
});
});
|
import React, { Component } from 'react';
import styles from './textBox.css';
// SubComponent
import StyleControls from './StyleControls';
import constants from './constants';
const {
BLOCK_TYPES,
LIST_TYPES,
HEADER_TYPES,
TEXT_ALIGN_TYPES,
INLINE_STYLES
} = constants;
// Libs
import {
convertToRaw,
CompositeDecorator,
ContentState,
Editor,
EditorState,
RichUtils,
Entity,
} from 'draft-js';
// DraftJS Plugins
import { stateFromHTML } from 'draft-js-import-html';
import { stateToHTML } from 'draft-js-export-html';
// Components
import Button from '../../components/Button';
import ButtonGroup from '../../components/ButtonGroup';
import Dialog from '../../components/Dialog';
class TextBox extends Component {
constructor(props) {
super(props);
this.onToggle = (e) => {
e.preventDefault();
this.props.onToggle(this.props.style);
};
const decorator = new CompositeDecorator([
{
strategy: findLinkEntities,
component: Link,
},
]);
const body = props.bodyKey ? props.body[props.bodyKey] : props.body;
this.state = {
showURLInput: false,
urlValue: '',
textAlign: props.textAlign || 'left',
editorState: EditorState.createWithContent(stateFromHTML(body), decorator)
};
this.focus = () => this.refs.editor.focus();
};
render() {
const { editorState, showURLInput } = this.state;
const urlInput = showURLInput
? (
<Dialog
className="urlInputContainer"
onClose={ () => this.setState({ showURLInput: false }) }
onAction={ this._confirmLink }
heading='Insert link'
>
<label className="formField">
<span>Link:</span>
<input
ref="url"
onChange={ this._onURLChange }
className="urlInput"
type="text"
value={ this.state.urlValue }
onKeyDown={ this._onLinkInputKeyDown }
/>
</label>
</Dialog>
)
: null;
return (
<div className="textBox">
<div className="textBox-toolbar">
<StyleControls
editorState={ editorState }
onToggle={ this._toggleBlockType }
blockTypes={ HEADER_TYPES }
/>
<StyleControls
editorState={ editorState }
onToggle={ this._toggleBlockType }
blockTypes={ LIST_TYPES }
/>
<StyleControls
editorState={ editorState }
onToggle={ this._toggleInlineStyle }
blockTypes={ INLINE_STYLES }
/>
<StyleControls
editorState={ editorState }
onToggle={ this._toggleBlockType }
blockTypes={ BLOCK_TYPES }
/>
<StyleControls
editorState={ editorState }
onToggle={ this._changeBlockStyle }
blockTypes={ TEXT_ALIGN_TYPES }
/>
<Button
center
onClick={ this._promptForLink }
classes='transparent'
icon='link'
/>
<Button
center
onClick={ this._removeLink }
classes='transparent'
icon='chain-broken'
/>
{ urlInput }
</div>
<Editor
spellCheck
textAlignment={ this.state.textAlign }
contentEditable
suppressContentEditableWarning
editorState={ editorState }
handleKeyCommand={ this._handleKeyCommand }
onChange={ this._onChange }
ref="editor"
/>
</div>
);
};
_onChange = (editorState) => {
this.setState({ editorState });
const updatedIntro = this._outputHtml();
if (this.props.bodyKey) return this.props.updateSlide(this.props.bodyKey, updatedIntro);
return this.props.updateSlide('body', updatedIntro, this.props.slideNum);
};
_toggleBlockType = (blockType) => {
this._onChange(
RichUtils.toggleBlockType(
this.state.editorState,
blockType
)
);
};
_toggleInlineStyle = (inlineStyle) => {
this._onChange(
RichUtils.toggleInlineStyle(
this.state.editorState,
inlineStyle
)
);
};
_changeBlockStyle = (block) => {
this.setState({
textAlign: block
});
if (this.props.bodyKey) return this.props.updateSlide('textAlign', block);
return this.props.updateSlide('textAlign', block, this.props.slideNum);
};
_promptForLink = (e) => {
e.preventDefault();
const { editorState } = this.state;
const selection = editorState.getSelection();
if (!selection.isCollapsed()) {
this.setState({
showURLInput: true,
urlValue: '',
});
}
};
_confirmLink = (e) => {
e.preventDefault();
const { editorState, urlValue } = this.state;
const url = urlValue.indexOf('//') > -1
? urlValue
: '//' + urlValue;
const entityKey = Entity.create('LINK', 'MUTABLE', { url });
this.setState({
editorState: RichUtils.toggleLink(
editorState,
editorState.getSelection(),
entityKey
),
showURLInput: false,
urlValue: '',
}, this.refs.editor.focus());
};
_onLinkInputKeyDown = (e) => e.which === 13 ? this._confirmLink(e) : '';
_removeLink = (e) => {
e.preventDefault();
const { editorState } = this.state;
const selection = editorState.getSelection();
if (!selection.isCollapsed()) {
this.setState({
editorState: RichUtils.toggleLink(editorState, selection, null),
}, this.refs.editor.focus());
}
};
_outputHtml = () => stateToHTML(this.state.editorState.getCurrentContent()).toString();
_handleKeyCommand = (command) => {
const { editorState } = this.state;
const newState = RichUtils.handleKeyCommand(editorState, command);
if (newState) {
this._onChange(newState);
return true;
}
return false;
};
_onURLChange = (e) => this.setState({ urlValue: e.target.value });
};
function findLinkEntities(contentBlock, cb) {
contentBlock.findEntityRanges(
(character) => {
const entityKey = character.getEntity();
return (
entityKey !== null &&
Entity.get(entityKey).getType() === 'LINK'
);
},
cb
);
}
const Link = (props) => {
const {url} = Entity.get(props.entityKey).getData();
return (
<a href={url} target="_blank">
{ props.children }
</a>
);
};
export default TextBox;
|
"use client";
import BreadCrumb from "@/components/ui/BreadCrumb";
import React from "react";
import { useSession } from "next-auth/react";
import Form from "@/components/ui/Form";
import FormInput from "@/components/ui/FormInput";
import { useAddCategoryMutation } from "@/redux/features/categories/categoriesApi";
import toast from "react-hot-toast";
import Button from "@/components/ui/Button";
import { Metadata } from "next/types";
const AddCategory = () => {
const { data: session } = useSession();
const role = (session as any)?.role;
const items = [
{
name: "Dashboard",
slug: `/dashboard`,
},
{
name: "Categories",
slug: `/dashboard/categories`,
},
];
const [addCategory] = useAddCategoryMutation();
const handleSubmit = async (values: any) => {
try {
await addCategory(values).unwrap();
toast.success("Category Added Successfully");
} catch (error) {
toast.error("Something went wrong");
}
};
return (
<section className="p-5">
<BreadCrumb items={items} />
<h1 className="my-5 text-2xl font-semibold">Add New Category</h1>
<Form submitHandler={handleSubmit}>
<FormInput
name="name"
required={true}
label="Category Name"
placeholder="Enter Your Category Name"
className="text-white"
/>
<Button type="submit" className="max-w-[200px]">
Add Category
</Button>
</Form>
</section>
);
};
export default AddCategory;
|
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
from tkinter import ttk, messagebox
import sympy as sp
def RungeKutta(f, a, b, h, y0):
n = int((b - a) / h)
t = np.linspace(a, b, n + 1)
y = np.zeros((n + 1, len(y0)))
y[0] = y0
for i in range(n):
k1 = h * np.array(f(t[i], y[i])).astype(float)
k2 = h * np.array(f(t[i] + h / 2, y[i] + k1 / 2)).astype(float)
k3 = h * np.array(f(t[i] + h / 2, y[i] + k2 / 2)).astype(float)
k4 = h * np.array(f(t[i] + h, y[i] + k3)).astype(float)
y[i + 1] = y[i] + (k1 + 2 * k2 + 2 * k3 + k4) / 6
return t, y
def Euler(f, a, b, h, y0):
n = int((b - a) / h)
t = np.linspace(a, b, n + 1)
y = np.zeros((n + 1, len(y0)))
y[0] = y0
for i in range(n):
y[i + 1] = y[i] + h * np.array(f(t[i], y[i])).astype(float)
return t, y
class DifferentialEquationsApp:
def __init__(self, root):
self.root = root
self.root.title("Ecuaciones Diferenciales")
self.root.geometry("1000x600")
control_frame = ttk.LabelFrame(self.root, text="Datos de Entrada")
control_frame.pack(padx=10, pady=10, fill="both", expand=True)
self.graph_frame = ttk.LabelFrame(self.root, text="Gráfica")
self.graph_frame.pack(padx=10, pady=10, fill="both", expand=True)
ttk.Label(control_frame, text="Función f(t, y):").grid(row=0, column=0, padx=5, pady=5, sticky="e")
self.f_entry1 = ttk.Entry(control_frame, width=50)
self.f_entry1.grid(row=0, column=1, padx=5, pady=5)
ttk.Label(control_frame, text="Función g(t, y):").grid(row=1, column=0, padx=5, pady=5, sticky="e")
self.f_entry2 = ttk.Entry(control_frame, width=50)
self.f_entry2.grid(row=1, column=1, padx=5, pady=5)
ttk.Label(control_frame, text="Función h(t, y):").grid(row=2, column=0, padx=5, pady=5, sticky="e")
self.f_entry3 = ttk.Entry(control_frame, width=50)
self.f_entry3.grid(row=2, column=1, padx=5, pady=5)
ttk.Label(control_frame, text="Valor inicial t (a):").grid(row=3, column=0, padx=5, pady=5, sticky="e")
self.t0_entry = ttk.Entry(control_frame)
self.t0_entry.grid(row=3, column=1, padx=5, pady=5)
ttk.Label(control_frame, text="Valor final t (b):").grid(row=4, column=0, padx=5, pady=5, sticky="e")
self.tf_entry = ttk.Entry(control_frame)
self.tf_entry.grid(row=4, column=1, padx=5, pady=5)
ttk.Label(control_frame, text="Tamaño de paso h:").grid(row=5, column=0, padx=5, pady=5, sticky="e")
self.h_entry = ttk.Entry(control_frame)
self.h_entry.grid(row=5, column=1, padx=5, pady=5)
ttk.Label(control_frame, text="Valores iniciales y0 (separados por comas):").grid(row=6, column=0, padx=5, pady=5, sticky="e")
self.y0_entry = ttk.Entry(control_frame)
self.y0_entry.grid(row=6, column=1, padx=5, pady=5)
self.runge_kutta_button = ttk.Button(control_frame, text="Runge Kutta", command=self.run_runge_kutta)
self.runge_kutta_button.grid(row=7, column=0, padx=5, pady=10, sticky="ew")
self.euler_button = ttk.Button(control_frame, text="Euler", command=self.run_euler)
self.euler_button.grid(row=7, column=1, padx=5, pady=10, sticky="ew")
self.instrucciones_button = ttk.Button(control_frame, text="Instrucciones", command=self.mostrar_instrucciones)
self.instrucciones_button.grid(row=7, column=2, padx=5, pady=10, sticky="ew")
self.result_text = tk.Text(self.graph_frame, height=10, width=60)
self.result_text.pack(side=tk.LEFT, fill="both", expand=True)
self.fig, self.ax = plt.subplots()
self.canvas = FigureCanvasTkAgg(self.fig, master=self.graph_frame)
self.canvas.get_tk_widget().pack(side=tk.RIGHT, fill="both", expand=True)
def plot_solution(self, t_vals, y_vals, method_names):
self.ax.clear()
if t_vals and y_vals:
for i, method in enumerate(method_names):
self.ax.plot(t_vals[i], y_vals[i], label=f"Función {method}")
self.ax.set_xlabel('t')
self.ax.set_ylabel('y')
self.ax.set_title('Solución de Ecuaciones Diferenciales')
self.ax.legend()
self.canvas.draw()
else:
messagebox.showwarning("Advertencia", "No hay datos para graficar.")
def parse_function(self, f_str):
try:
t, y = sp.symbols('t y')
locals_dict = {"sp": sp}
f_expr = sp.sympify(f_str, locals=locals_dict)
return sp.lambdify((t, y), f_expr, 'numpy')
except Exception as e:
messagebox.showerror("Error", f"Error en la función: {e}")
return None
def run_runge_kutta(self):
f_str1 = self.f_entry1.get().strip()
f_str2 = self.f_entry2.get().strip()
f_str3 = self.f_entry3.get().strip()
try:
t0 = float(self.t0_entry.get())
tf = float(self.tf_entry.get())
h = float(self.h_entry.get())
y0 = list(map(float, self.y0_entry.get().split(',')))
except ValueError as e:
messagebox.showerror("Error", f"Error en los valores numéricos: {e}")
return
functions = []
method_names = []
initial_values = []
if f_str1:
f_lambda1 = self.parse_function(f_str1)
if f_lambda1:
functions.append(f_lambda1)
method_names.append("f1")
initial_values.append(y0[0])
if f_str2:
f_lambda2 = self.parse_function(f_str2)
if f_lambda2:
functions.append(f_lambda2)
method_names.append("f2")
initial_values.append(y0[1])
if f_str3:
f_lambda3 = self.parse_function(f_str3)
if f_lambda3:
functions.append(f_lambda3)
method_names.append("f3")
initial_values.append(y0[2])
if not functions:
messagebox.showerror("Error", "No se proporcionaron funciones válidas.")
return
t_vals, y_vals = [], []
for func, y0_val in zip(functions, initial_values):
t_val, y_val = RungeKutta(func, t0, tf, h, [y0_val])
t_vals.append(t_val)
y_vals.append(y_val)
self.result_text.delete(1.0, tk.END)
self.result_text.insert(tk.END, f"t: {t_vals}\n\ny: {y_vals}\n")
self.plot_solution(t_vals, y_vals, method_names)
def run_euler(self):
f_str1 = self.f_entry1.get().strip()
f_str2 = self.f_entry2.get().strip()
f_str3 = self.f_entry3.get().strip()
try:
t0 = float(self.t0_entry.get())
tf = float(self.tf_entry.get())
h = float(self.h_entry.get())
y0 = list(map(float, self.y0_entry.get().split(',')))
except ValueError as e:
messagebox.showerror("Error", f"Error en los valores numéricos: {e}")
return
functions = []
method_names = []
initial_values = []
if f_str1:
f_lambda1 = self.parse_function(f_str1)
if f_lambda1:
functions.append(f_lambda1)
method_names.append("f1")
initial_values.append(y0[0])
if f_str2:
f_lambda2 = self.parse_function(f_str2)
if f_lambda2:
functions.append(f_lambda2)
method_names.append("f2")
initial_values.append(y0[1])
if f_str3:
f_lambda3 = self.parse_function(f_str3)
if f_lambda3:
functions.append(f_lambda3)
method_names.append("f3")
initial_values.append(y0[2])
if not functions:
messagebox.showerror("Error", "No se proporcionaron funciones válidas.")
return
t_vals, y_vals = [], []
for func, y0_val in zip(functions, initial_values):
t_val, y_val = Euler(func, t0, tf, h, [y0_val])
t_vals.append(t_val)
y_vals.append(y_val)
self.result_text.delete(1.0, tk.END)
self.result_text.insert(tk.END, f"t: {t_vals}\n\ny: {y_vals}\n")
self.plot_solution(t_vals, y_vals, method_names)
def mostrar_instrucciones(self):
instrucciones = """
Instrucciones de Uso:
1. Función f(t, y) - obligatorio:
- Ingrese la función f(t, y) en este campo. Por ejemplo:
- t + y
- t**2 + y
- y * sp.exp(t)
- Utilice 'sp.' antes de funciones especiales de sympy, por ejemplo:
- sp.exp(y)
- sp.sin(t)
2. Función g(t, y) - opcional:
- Ingrese la función g(t, y) en este campo siguiendo las mismas reglas que para f(t, y).
3. Función h(t, y) - opcional:
- Ingrese la función h(t, y) en este campo siguiendo las mismas reglas que para f(t, y).
4. Valor inicial t (a) - obligatorio:
- Ingrese el valor inicial t en este campo. Debe ser un número real.
5. Valor final t (b) - obligatorio:
- Ingrese el valor final t en este campo. Debe ser un número real mayor que el valor inicial t.
6. Tamaño de paso h - obligatorio:
- Ingrese el tamaño de paso h en este campo. Debe ser un número real positivo.
7. Valores iniciales y0 (separados por comas) - obligatorio:
- Ingrese los valores iniciales y0 separados por comas. Cada valor se asignará a la función correspondiente en el orden en que se ingresaron.
8. Botones:
- Runge Kutta: Ejecuta el método de Runge Kutta con las funciones y parámetros ingresados.
- Euler: Ejecuta el método de Euler con las funciones y parámetros ingresados.
- Instrucciones: Muestra esta ventana de instrucciones.
Nota: Asegúrese de ingresar funciones válidas y valores numéricos correctos antes de ejecutar los métodos.
"""
messagebox.showinfo("Instrucciones de Uso", instrucciones)
|
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<!-- <div class="card-header">{{ __('Admin Login') }}</div> -->
<div class="card-body">
<form method="POST" action="{{ route('admin.login.submit') }}">
{{ csrf_field() }}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group row">
<label for="email" class="col-md-2 col-form-label text-md-right">Email</label>
<div class="col-md-4">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required autofocus>
@if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>Email invalido</strong>
</span>
@endif
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-2 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-4">
<input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
@if ($errors->has('password'))
<span class="invalid-feedback" role="alert">
<strong>Contraseña invalida</strong>
</span>
@endif
</div>
</div>
<!-- <div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
Recordarme
</label>
</div>
</div>
</div> -->
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
<!-- @if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
@endif -->
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
|
// OpenTibia - an opensource roleplaying game
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "otpch.h"
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include "spawn.h"
#include "tools.h"
#include "player.h"
#include "npc.h"
#include "configmanager.h"
#include "game.h"
extern ConfigManager g_config;
extern Monsters g_monsters;
extern Game g_game;
#define MINSPAWN_INTERVAL 1000
#define DEFAULTSPAWN_INTERVAL 60000
Spawns::Spawns()
{
filename = "";
loaded = started = false;
}
Spawns::~Spawns()
{
if(started)
clear();
}
bool Spawns::loadFromXml(const std::string& _filename)
{
if(isLoaded())
return true;
filename = _filename;
xmlDocPtr doc = xmlParseFile(filename.c_str());
if(!doc)
{
std::cout << "[Warning - Spawns::loadFromXml] Cannot open spawns file." << std::endl;
std::cout << getLastXMLError() << std::endl;
return false;
}
xmlNodePtr spawnNode, root = xmlDocGetRootElement(doc);
if(xmlStrcmp(root->name,(const xmlChar*)"spawns"))
{
std::cout << "[Error - Spawns::loadFromXml] Malformed spawns file." << std::endl;
xmlFreeDoc(doc);
return false;
}
spawnNode = root->children;
while(spawnNode)
{
parseSpawnNode(spawnNode, false);
spawnNode = spawnNode->next;
}
xmlFreeDoc(doc);
loaded = true;
return true;
}
bool Spawns::parseSpawnNode(xmlNodePtr p, bool checkDuplicate)
{
if(xmlStrcmp(p->name, (const xmlChar*)"spawn"))
return false;
int32_t intValue;
std::string strValue;
Position centerPos;
if(!readXMLString(p, "centerpos", strValue))
{
if(!readXMLInteger(p, "centerx", intValue))
return false;
centerPos.x = intValue;
if(!readXMLInteger(p, "centery", intValue))
return false;
centerPos.y = intValue;
if(!readXMLInteger(p, "centerz", intValue))
return false;
centerPos.z = intValue;
}
else
{
IntegerVec posVec = vectorAtoi(explodeString(",", strValue));
if(posVec.size() < 3)
return false;
centerPos = Position(posVec[0], posVec[1], posVec[2]);
}
if(!readXMLInteger(p, "radius", intValue))
return false;
int32_t radius = intValue;
Spawn* spawn = new Spawn(centerPos, radius);
if(checkDuplicate)
{
for(SpawnList::iterator it = spawnList.begin(); it != spawnList.end(); ++it)
{
if((*it)->getPosition() == centerPos)
delete *it;
}
}
spawnList.push_back(spawn);
xmlNodePtr tmpNode = p->children;
while(tmpNode)
{
if(!xmlStrcmp(tmpNode->name, (const xmlChar*)"monster"))
{
std::string name;
if(!readXMLString(tmpNode, "name", strValue))
{
tmpNode = tmpNode->next;
continue;
}
name = strValue;
int32_t interval = MINSPAWN_INTERVAL / 1000;
if(readXMLInteger(tmpNode, "spawntime", intValue) || readXMLInteger(tmpNode, "interval", intValue))
{
if(intValue <= interval)
{
std::cout << "[Warning - Spawns::loadFromXml] " << name << " " << centerPos << " spawntime cannot";
std::cout << " be less than " << interval << " seconds." << std::endl;
tmpNode = tmpNode->next;
continue;
}
interval = intValue;
}
interval *= 1000;
Position placePos = centerPos;
if(readXMLInteger(tmpNode, "x", intValue))
placePos.x += intValue;
if(readXMLInteger(tmpNode, "y", intValue))
placePos.y += intValue;
if(readXMLInteger(tmpNode, "z", intValue))
placePos.z /*+*/= intValue;
Direction direction = NORTH;
if(readXMLInteger(tmpNode, "direction", intValue) && direction >= EAST && direction <= WEST)
direction = (Direction)intValue;
spawn->addMonster(name, placePos, direction, interval);
}
else if(!xmlStrcmp(tmpNode->name, (const xmlChar*)"npc"))
{
std::string name;
if(!readXMLString(tmpNode, "name", strValue))
{
tmpNode = tmpNode->next;
continue;
}
name = strValue;
Position placePos = centerPos;
if(readXMLInteger(tmpNode, "x", intValue))
placePos.x += intValue;
if(readXMLInteger(tmpNode, "y", intValue))
placePos.y += intValue;
if(readXMLInteger(tmpNode, "z", intValue))
placePos.z /*+*/= intValue;
Direction direction = NORTH;
if(readXMLInteger(tmpNode, "direction", intValue)){
direction = (Direction)intValue;
}
Npc* npc = Npc::createNpc(name);
if(!npc)
{
tmpNode = tmpNode->next;
continue;
}
npc->setMasterPosition(placePos, radius);
npc->setDirection(npc->direction);
npcList.push_back(npc);
}
tmpNode = tmpNode->next;
}
return true;
}
void Spawns::startup()
{
if(!isLoaded() || isStarted())
return;
for(NpcList::iterator it = npcList.begin(); it != npcList.end(); ++it)
g_game.placeCreature((*it), (*it)->getMasterPosition(), false, true);
npcList.clear();
for(SpawnList::iterator it = spawnList.begin(); it != spawnList.end(); ++it)
(*it)->startup();
started = true;
}
void Spawns::clear()
{
started = false;
for(SpawnList::iterator it = spawnList.begin(); it != spawnList.end(); ++it)
delete (*it);
spawnList.clear();
loaded = false;
filename = "";
}
bool Spawns::isInZone(const Position& centerPos, int32_t radius, const Position& pos)
{
if(radius == -1)
return true;
return ((pos.x >= centerPos.x - radius) && (pos.x <= centerPos.x + radius) &&
(pos.y >= centerPos.y - radius) && (pos.y <= centerPos.y + radius));
}
void Spawn::startEvent()
{
if(checkSpawnEvent == 0)
checkSpawnEvent = Scheduler::getInstance().addEvent(createSchedulerTask(getInterval(), boost::bind(&Spawn::checkSpawn, this)));
}
Spawn::Spawn(const Position& _pos, int32_t _radius)
{
centerPos = _pos;
radius = _radius;
interval = DEFAULTSPAWN_INTERVAL;
checkSpawnEvent = 0;
}
Spawn::~Spawn()
{
stopEvent();
Monster* monster = NULL;
for(SpawnedMap::iterator it = spawnedMap.begin(); it != spawnedMap.end(); ++it)
{
if(!(monster = it->second))
continue;
monster->setSpawn(NULL);
if(!monster->isRemoved())
g_game.freeThing(monster);
}
spawnedMap.clear();
spawnMap.clear();
}
bool Spawn::findPlayer(const Position& pos)
{
SpectatorVec list;
g_game.getSpectators(list, pos);
Player* tmpPlayer = NULL;
for(SpectatorVec::iterator it = list.begin(); it != list.end(); ++it)
{
if((tmpPlayer = (*it)->getPlayer()) && !tmpPlayer->hasFlag(PlayerFlag_IgnoredByMonsters))
return true;
}
return false;
}
bool Spawn::spawnMonster(uint32_t spawnId, MonsterType* mType, const Position& pos, Direction dir, bool startup /*= false*/)
{
if(mType->realName != "")
mType->name = mType->realName;
Monster* monster = Monster::createMonster(mType->name);
if(!monster)
return false;
if(startup)
{
//No need to send out events to the surrounding since there is no one out there to listen!
if(!g_game.internalPlaceCreature(monster, pos, false, true))
{
delete monster;
return false;
}
else
{
monster->onCreatureAppear(monster);
}
}
else
{
if(!g_game.placeCreature(monster, pos, false, true))
{
delete monster;
return false;
}
}
monster->setSpawn(this);
monster->addRef();
monster->setMasterPosition(pos, radius);
monster->setDirection(dir);
spawnedMap.insert(SpawnedPair(spawnId, monster));
spawnMap[spawnId].lastSpawn = OTSYS_TIME();
return true;
}
void Spawn::startup()
{
for(SpawnMap::iterator it = spawnMap.begin(); it != spawnMap.end(); ++it)
{
spawnBlock_t& sb = it->second;
spawnMonster(it->first, sb.mType, sb.pos, sb.direction, true);
}
}
void Spawn::checkSpawn()
{
#ifdef __DEBUG_SPAWN__
std::cout << "[Notice] Spawn::checkSpawn " << this << std::endl;
#endif
checkSpawnEvent = 0;
Monster* monster;
uint32_t spawnId;
for(SpawnedMap::iterator it = spawnedMap.begin(); it != spawnedMap.end();)
{
spawnId = it->first;
monster = it->second;
if(monster->isRemoved())
{
if(spawnId != 0)
spawnMap[spawnId].lastSpawn = OTSYS_TIME();
monster->unRef();
spawnedMap.erase(it++);
}
else if(!isInSpawnZone(monster->getPosition()) && spawnId != 0)
{
spawnedMap.insert(SpawnedPair(0, monster));
spawnedMap.erase(it++);
}
else
++it;
}
uint32_t spawnCount = 0;
for(SpawnMap::iterator it = spawnMap.begin(); it != spawnMap.end(); ++it)
{
spawnId = it->first;
spawnBlock_t& sb = it->second;
if(spawnedMap.count(spawnId) == 0)
{
if(OTSYS_TIME() >= sb.lastSpawn + sb.interval)
{
if(findPlayer(sb.pos))
{
sb.lastSpawn = OTSYS_TIME();
continue;
}
spawnMonster(spawnId, sb.mType, sb.pos, sb.direction);
++spawnCount;
if(spawnCount >= (uint32_t)g_config.getNumber(ConfigManager::RATE_SPAWN))
break;
}
}
}
if(spawnedMap.size() < spawnMap.size())
checkSpawnEvent = Scheduler::getInstance().addEvent(createSchedulerTask(getInterval(), boost::bind(&Spawn::checkSpawn, this)));
#ifdef __DEBUG_SPAWN__
else
std::cout << "[Notice] Spawn::checkSpawn stopped " << this << std::endl;
#endif
}
bool Spawn::addMonster(const std::string& _name, const Position& _pos, Direction _dir, uint32_t _interval)
{
if(!g_game.getTile(_pos))
{
std::cout << "[Spawn::addMonster] NULL tile at spawn position (" << _pos << ")" << std::endl;
return false;
}
MonsterType* mType = g_monsters.getMonsterType(_name);
if(!mType)
{
std::cout << "[Spawn::addMonster] Cannot find \"" << _name << "\"" << std::endl;
return false;
}
if(_interval < interval)
interval = _interval;
spawnBlock_t sb;
sb.mType = mType;
sb.pos = _pos;
sb.direction = _dir;
sb.interval = _interval;
sb.lastSpawn = 0;
uint32_t spawnId = (int32_t)spawnMap.size() + 1;
spawnMap[spawnId] = sb;
return true;
}
void Spawn::removeMonster(Monster* monster)
{
for(SpawnedMap::iterator it = spawnedMap.begin(); it != spawnedMap.end(); ++it)
{
if(it->second == monster)
{
monster->unRef();
spawnedMap.erase(it);
break;
}
}
}
void Spawn::stopEvent()
{
if(checkSpawnEvent != 0)
{
Scheduler::getInstance().stopEvent(checkSpawnEvent);
checkSpawnEvent = 0;
}
}
|
----------------------------------------------TRIGGERS----------------------------------------------
-Triggers are the plsql block , which are executed before or after specific event or instead of specific event
-triggers are executed automatically by the database server
-Triggers are defined on tables,views,schemas,databases
-Triggers are fired when one of the below situation occurs
theses are database triggers:
*When DML(INSERT,UPDATE,DELETE) occurs
*When DDL(CREATE,ALTER,DROP) occurs
*When some database operations occurs(like logon,startup,servererror....)
other one is application triggers
these triggers are related with some application like oracle forms....
What are triggers and triggers types:
-why do we use triggers
-security,auditing,data integrity,table logging,event logging,derived data
Note: 1.we use trigger to get to know the wrong usage of statements
2.provide security before updating any table
-three types of triggers
1.DML triggers
2.Compound triggers
3.Non-DML triggers
DML TRIGGER:
----------
DML TRIGGERS are PL/SQL Blocks running when the specified event occurs
-we use DML triggers for duplications,log table maintenance,security etc.
The syntax for creating a trigger is −
CREATE [OR REPLACE ] TRIGGER trigger_name
timimg=BEFORE | AFTER | INSTEAD OF
event=INSERT [OR] | UPDATE [OR] | DELETE | UPDATE OF col_list
ON object_name
[REFERENCING OLD AS old NEW AS new]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with the trigger_name.
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF col_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various DML statements, such as INSERT, UPDATE, and DELETE.
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger.
WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is valid only for row-level triggers.
Specifying the timing of triggers:
---------------------------------
There are three options two specify the timing
1.Before:
-we can allow or reject the specified action
-we can specify default values for the columns
-we can validate the complex business rules
2.After:
-make some after checks
-Duplicate tables or add log records
3.Instead of:
note: there can be multiple triggers with same timing points on table or view.
Statement and row level triggers:
--------------------------------
1.BEFORE STATEMENT:
-This is the statement level trigger, this trigger will fire right before the execution of DML statement
2.BEFORE ROW
-This is the row level trigger , this trigger will fire, right before the execeution of each row
3.AFTER ROW
-This is the row level trigger , this trigger will fire, right after the execeution of each row
4.AFTER STATEMENT
-This is the statement level trigger, this trigger will fire right after the execution of DML statement
use of :old and :new reference in triggers:
note: which is only applicable for the row level trigger
Conditional Predicates:
-----------------------
Conditional predicates are used to use single trigger for the different events using
-IF
-INSERTING,UPDATING AND DELETING COMMANDS
UPDATE OF EVENT:
---------------------
we can not use the UPDATE command , when we using update of
- it is used to update the table for specific columns(it is useful for the business point of view)
use of WHEN CLAUSE in triggers:
------------------------------
it reduces the execution statement in body and it leads to increase the performance
NOTE:
ORA-04077: WHEN clause cannot be used with table level triggers
syntax to disable trigger:
alter trigger trigger_name disable;
Instead of Triggers:
-------------------
-simple views are used only with the views
-Instead of triggers used to apply some DML statements on un updatable views
some important things about INSTEAD OF TRIGGERS:
-Instead of triggers are used only with views
-Generally used with complex views
-if your view has a check option, it wont be enforced when we use the instead of triggers
-BEFORE OR AFTER timings are not valid for instead of triggers
exploring and managing triggers:
-------------------------------
there are two data dictionary views for the triggers:
----------------------------------------------------
1.user_objects;
2.user_triggers;
to check all triggers information:
----------------
select * from user_triggers;
select * from dba_triggers;
alter trigger trigger_name enale|disable;
disable or enable all triggers in a table:
-----------------------------------------
alter table table_name [enable|disable] all triggers;
alter trigger trigger_name compile;
drop trigger trigger_name;
COMPOUND TRIGGERS:
-----------------
-Compound triggers is a single trigger that allows us to specify actions for each DML trigger types.
-So, they can share the variables,types etc amoung each other
-Why we use compound triggers:
----------------------------
-Taking actions for various timing points by sharing the common data
-Making inserts to some other tables faster then the bulk inserts
-Avoiding mutating table error
-Compound triggers restrictions:
-------------------------------
-Compound trigger must be a DML trigger defined on the table or view
-Compound trigger body must be a Compound trigger block
-Compound trigger body can not have a initialization block
- :old and :new can not be used in the declaration or before or after statements
-The firing order of compound is not guaranteed if we dont use the FOLLOWS CLAUSE
SYNTAX:
------
CREATE [OR REPLACE] TRIGGER trigger_name
FOR INSERT |UPDATE|DELETE|UPDATE OF column_list
ON object_name
[REFERENCING OLD as old NEW as new]
[WHEN (condition)]
COMPOUND TRIGGER
[variables,types etc]
BEFORE STATEMENT IS
pl/sql block
[EXCEPTION]
END BEFORE STATEMENT;
BEFORE EACH ROW IS
pl/sql block
[EXCEPTION]
END BEFORE STATEMENT;
AFTER EACH ROW IS
pl/sql block
[EXCEPTION]
END BEFORE STATEMENT;
AFTER STATEMENT IS
pl/sql block
[EXCEPTION]
END BEFORE STATEMENT;
END;
MUTATING TABLE ERRORS:
---------------------
Trigger Restriction on Mutating Tables:
-A Mutating table is :
*a table that being modified
*a table that mieght be updated with DELETE CASCADE
-Row Level Trigger can not query or modify a mutating table.
-This restriction prevents inconsistent data changes
-VIEWS being modified by the INSTEAD OF TRIGGERS are not considered as mutating
We can handle the mutating table error with couple of ways:
-store related data in the another table
-store related data in the package
-use of COMPOUND TRIGGERS
------------------------------SPECIFYING THE TIMING OF TRIGGERS------------------------------
---------------------------------------------------------------------------------------------
----------------- The create code of the first trigger
create or replace trigger first_trigger
before insert or update on employees_copy
begin
dbms_output.put_line('An insert or update occurred in employees_copy table!.');
end;
----------------- sql commands to or not to run the trigger
update employees_copy set salary = salary + 100;
delete from employees_copy;
2>>>>>
---------------------------------------------------------------------------------------------
-------------------------------STATEMENT & ROW LEVEL TRIGGERS--------------------------------
---------------------------------------------------------------------------------------------
----------------- before statement level trigger example
create or replace trigger before_statement_emp_cpy
before insert or update on employees_copy
begin
dbms_output.put_line('Before Statement Trigger is Fired!.');
end;
----------------- after statement level trigger example
create or replace trigger after_statement_emp_cpy
after insert or update on employees_copy
begin
dbms_output.put_line('After Statement Trigger is Fired!.');
end;
----------------- before row level trigger example
create or replace trigger before_row_emp_cpy
before insert or update on employees_copy
for each row
begin
dbms_output.put_line('Before Row Trigger is Fired!.');
end;
----------------- after row level trigger example
create or replace trigger after_row_emp_cpy
after insert or update on employees_copy
for each row
begin
dbms_output.put_line('After Row Trigger is Fired!.');
end;
----------------- sql queries used in this lecture
update employees_copy set salary = salary + 100 where employee_id = 100;
update employees_copy set salary = salary + 100 where employee_id = 99;
update employees_copy set salary = salary + 100
where department_id = 30;
3>>>>
---------------------------------------------------------------------------------------------
-------------------------------:NEW & :OLD QUALIFIERS IN TRIGGERS----------------------------
---------------------------------------------------------------------------------------------
create or replace trigger before_row_emp_cpy
before insert or update or delete on employees_copy
referencing old as O new as N
for each row
begin
dbms_output.put_line('Before Row Trigger is Fired!.');
dbms_output.put_line('The Salary of Employee '||:o.employee_id
||' -> Before:'|| :o.salary||' After:'||:n.salary);
4>>>>>>
---------------------------------------------------------------------------------------------
--------------------------------USING CONDITIONAL PREDICATES --------------------------------
---------------------------------------------------------------------------------------------
create or replace trigger before_row_emp_cpy
before insert or update or delete on employees_copy
referencing old as O new as N
for each row
begin
dbms_output.put_line('Before Row Trigger is Fired!.');
dbms_output.put_line('The Salary of Employee '||:o.employee_id
||' -> Before:'|| :o.salary||' After:'||:n.salary);
if inserting then
dbms_output.put_line('An INSERT occurred on employees_copy table');
elsif deleting then
dbms_output.put_line('A DELETE occurred on employees_copy table');
elsif updating ('salary') then
dbms_output.put_line('A DELETE occurred on the salary column');
elsif updating then
dbms_output.put_line('An UPDATE occurred on employees_copy table');
end if;
end;
5>>>>>>>>>>
------------------------------------------------------------------------------------------
----------------------------raise_application_error---------------------------------------
create or replace trigger before_row_emp_trigger
before insert or update or delete on employees_copy
for each row
begin
dbms_output.put_line('before row level trigger is fired!!');
dbms_output.put_line('before row level trigger is fired employees !!'||:old.employee_id||'==>before:'||:old.salary||'==>After:'||:new.salary);
if INSERTING THEN
dbms_output.put_line('before row level INSERTING EVENT trigger is fired!!');
elsif UPDATING('salary') THEN
if :new.salary>50000 then
raise_application_error('-20001','salary should not be higher then the 50000');
end if;
dbms_output.put_line('before row level UPDATING EVENT and specific column trigger is fired!!');
elsif UPDATING THEN
dbms_output.put_line('before row level UPDATING EVENT trigger is fired!!');
elsif DELETING THEN
dbms_output.put_line('before row level DELETING EVENT trigger is fired!!');
end if;
end;
------------------------------------------
create or replace trigger prevent_high_salary
before insert or update of salary on employees_copy
for each row
when (new.salary > 50000)
begin
raise_application_error(-20006,'A salary cannot be higher than 50000!.');
end;
6>>>
---------------------------------------------------------------------------------------------
--------------------------------USING UPDATE OF EVENT IN TRIGGERS----------------------------
---------------------------------------------------------------------------------------------
create or replace trigger prevent_updates_of_constant_columns
before update of hire_date,salary on employees_copy
for each row
begin
raise_application_error(-20005,'You cannot modify the hire_date and salary columns');
end;
7>>>
--------------------------------------------------------------------------------------------
----------------------------------USING WHEN CLAUSE ON TRIGGERS------------------------------
---------------------------------------------------------------------------------------------
create or replace trigger prevent_high_salary
before insert or update of salary on employees_copy
for each row
when (new.salary > 50000)
begin
raise_application_error(-20006,'A salary cannot be higher than 50000!.');
end;
8>>>
---------------------------------------------------------------------------------------------
-----------------------------------USING INSTEAD OF TRIGGERS---------------------------------
---------------------------------------------------------------------------------------------
----------------- creating a complex view -----------------
CREATE OR REPLACE VIEW VW_EMP_DETAILS AS
SELECT UPPER(DEPARTMENT_NAME) DNAME, MIN(SALARY) MIN_SAL, MAX(SALARY) MAX_SAL
FROM EMPLOYEES_COPY JOIN DEPARTMENTS_COPY
USING (DEPARTMENT_ID)
GROUP BY DEPARTMENT_NAME;
----------------- updating the complex view -----------------
UPDATE VW_EMP_DETAILS SET DNAME = 'EXEC DEPT' WHERE
UPPER(DNAME) = 'EXECUTIVE';
----------------- Instead of trigger -----------------
CREATE OR REPLACE TRIGGER EMP_DETAILS_VW_DML
INSTEAD OF INSERT OR UPDATE OR DELETE ON VW_EMP_DETAILS
FOR EACH ROW
DECLARE
V_DEPT_ID PLS_INTEGER;
BEGIN
IF INSERTING THEN
SELECT MAX(DEPARTMENT_ID) + 10 INTO V_DEPT_ID FROM DEPARTMENTS_COPY;
INSERT INTO DEPARTMENTS_COPY VALUES (V_DEPT_ID, :NEW.DNAME,NULL,NULL);
ELSIF DELETING THEN
DELETE FROM DEPARTMENTS_COPY WHERE UPPER(DEPARTMENT_NAME) = UPPER(:OLD.DNAME);
ELSIF UPDATING('DNAME') THEN
UPDATE DEPARTMENTS_COPY SET DEPARTMENT_NAME = :NEW.DNAME
WHERE UPPER(DEPARTMENT_NAME) = UPPER(:OLD.DNAME);
ELSE
RAISE_APPLICATION_ERROR(-20007,'You cannot update any data other than department name!.');
END IF;
END;
results check:
select * from departments_copy;
select * from VW_EMP_DETAILS;
update vw_emp_details set dname='exec dept' where UPPER(DNAME)='EXECUTIVE';
delete from VW_EMP_DETAILS where dname='EXEC DEPT';
insert into VW_EMP_DETAILS values ('KExecution',null,null);
update vw_emp_details set min_sal=300 where dname='SALES';
/*You cannot update any data other than department name*/
9>>>>
---------------------------------------------------------------------------------------------
-----------------------------------CREATING DISABLED TRIGGERS--------------------------------
---------------------------------------------------------------------------------------------
create or replace trigger prevent_high_salary
before insert or update of salary on employees_copy
for each row
disable
when (new.salary > 50000)
begin
raise_application_error(-20006,'A salary cannot be higher than 50000!.');
end;
---------------------------------general examples------------------------------
create table employees_copy as select * from hr.employees;
select * from departments_copy;
desc departments_copy;
create table departments_copy as select * from hr.departments;
/*most of the time sequences are used to assign primary key value, here we show how that happened*/
create sequence seq_dept_copy start with 280 increment by 10;
create or replace trigger before_insert_dept_copy
before insert or update on departments_copy
for each row
begin
--select seq_dept_copy.nextval into :new.department_id from dual;
:new.department_id:=seq_dept_copy.nextval;
dbms_output.put_line('we r going to insert the departments_copy table');
end;
insert into departments_copy(department_name,manager_id,location_id) values('oracle',11,22);
insert into departments_copy(department_name,manager_id,location_id) values('HCM',130,220);
insert into departments_copy(department_name,manager_id,location_id) values('ERP',140,230);
insert into departments_copy(department_name,manager_id,location_id) values('sim',150,250);
10>>>>
---------------------------------------------------------------------------------------------
-------------------------------------COMPOUND TRIGGERS---------------------------------------
---------------------------------------------------------------------------------------------
----------------- The first simple compound trigger
create or replace trigger trg_comp_emps
for insert or update or delete on employees_copy
compound trigger
v_dml_type varchar2(10);
before statement is
begin
if inserting then
v_dml_type := 'INSERT';
elsif updating then
v_dml_type := 'UPDATE';
elsif deleting then
v_dml_type := 'DELETE';
end if;
dbms_output.put_line('Before statement section is executed with the '||v_dml_type ||' event!.');
end before statement;
before each row is
t number;
begin
dbms_output.put_line('Before row section is executed with the '||v_dml_type ||' event!.');
end before each row;
after each row is
begin
dbms_output.put_line('After row section is executed with the '||v_dml_type ||' event!.');
end after each row;
after statement is
begin
dbms_output.put_line('After statement section is executed with the '||v_dml_type ||' event!.');
end after statement;
end;
result:
checking dml statement:
update employees_copy set salary=salary+100 where employee_id=101;
1 row(s) updated.
the before statement trigger fired!UPDATEevent!
the before each row trigger fired!UPDATEevent!
the after each row trigger fired!UPDATEevent!
the after statement trigger fired!UPDATEevent!
-----------------
CREATE OR REPLACE TRIGGER TRG_COMP_EMPS
FOR INSERT OR UPDATE OR DELETE ON EMPLOYEES_COPY
COMPOUND TRIGGER
TYPE T_AVG_DEPT_SALARIES IS TABLE OF EMPLOYEES_COPY.SALARY%TYPE INDEX BY PLS_INTEGER;
AVG_DEPT_SALARIES T_AVG_DEPT_SALARIES;
/*here, we got the avg sal of the each department into the asociative array, so it makes checks much faster*/
BEFORE STATEMENT IS
BEGIN
FOR AVG_SAL IN (SELECT AVG(SALARY) SALARY , NVL(DEPARTMENT_ID,999) DEPARTMENT_ID
FROM EMPLOYEES_COPY GROUP BY DEPARTMENT_ID) LOOP
AVG_DEPT_SALARIES(AVG_SAL.DEPARTMENT_ID) := AVG_SAL.SALARY;
END LOOP;
END BEFORE STATEMENT;
AFTER EACH ROW IS
V_INTERVAL NUMBER := 15;
BEGIN
IF :NEW.SALARY > AVG_DEPT_SALARIES(:NEW.DEPARTMENT_ID) + AVG_DEPT_SALARIES(:NEW.DEPARTMENT_ID)*V_INTERVAL/100 THEN
RAISE_APPLICATION_ERROR(-20005,'A raise cannot be '|| V_INTERVAL|| ' percent higher than
its department''s average!');
END IF;
END AFTER EACH ROW;
AFTER STATEMENT IS
BEGIN
DBMS_OUTPUT.PUT_LINE('All the changes are done successfully!');
END AFTER STATEMENT;
END;
Note:Use of associate array with trigger:
-if our update statement will update 100 rows,when we want to know the avg sal of the specific dept in each update,
we have to query from the database 100 times, so this will decrease the performance
-Instead we got the avg sal into our memory, while doing update, we can get the data from the memory much faster then , getting from the database;
-its easy to get the avg salary by indexed based using department_id from associative array
11<<<<<<
---------------------------------------------------------------------------------------------
------------------------------------ MUTATING TABLE ERRORS ----------------------------------
---------------------------------------------------------------------------------------------
NOTE:
1.DML statements are valid only before and after statement, but if same dml event fires , we fall into the recursive levels, so we have to use the dml statements which should not repeated
2.in row level trigger
if we created trigger from the same table and modified the same table with dml command, in this case we will get mutating error
-we handle this using compound trigger, but has some restrcitions
1.we can not make change or query inside the row level section trigger
2.if u run the dml command inside the before or after statement,if that trigger runs again, at that time also we will get mutating error
----------------- A mutating table error example
create or replace trigger trg_mutating_emps
before insert or update on employees_copy
for each row
declare
v_interval number := 15;
v_avg_salary number;
begin
select avg(salary) into v_avg_salary from employees_copy where department_id = :new.department_id;
if :new.salary > v_avg_salary*v_interval/100 then
RAISE_APPLICATION_ERROR(-20005, 'A raise cannot be '|| v_interval|| ' percent higher than its department''s average');
end if;
end;
----------------- Getting mutating table error within a compound trigger
create or replace trigger trg_comp_emps
for insert or update or delete on employees_copy
compound trigger
type t_avg_dept_salaries is table of employees_copy.salary%type index by pls_integer;
avg_dept_salaries t_avg_dept_salaries;
before statement is
begin
for avg_sal in (select avg(salary) salary,nvl(department_id,999) department_id from employees_copy group by department_id) loop
avg_dept_salaries(avg_sal.department_id) := avg_sal.salary;
end loop;
end before statement;
after each row is
v_interval number := 15;
begin
update employees_copy set commission_pct = commission_pct;
if :new.salary > avg_dept_salaries(:new.department_id)*v_interval/100 then
RAISE_APPLICATION_ERROR(-20005, 'A raise cannot be '|| v_interval|| ' percent higher than its department''s average');
end if;
end after each row;
after statement is
begin
dbms_output.put_line('All the updates are done successfully!.');
end after statement;
end;
------------------------
create or replace trigger trg_comp_emps
for insert or update on employees_copy
compound trigger
type t_avg_dept_salaries is table of employees_copy.salary%type index by pls_integer;
avg_dept_salaries t_avg_dept_salaries;
before statement is
begin
delete from employees_copy where employee_id=105;
for avg_sal in (select avg(salary) salary,nvl(department_id,999) department_id from employees_copy group by department_id) loop
avg_dept_salaries(avg_sal.department_id) := avg_sal.salary;
end loop;
end before statement;
after each row is
v_interval number := 15;
begin
if :new.salary > avg_dept_salaries(:new.department_id)*v_interval/100 then
RAISE_APPLICATION_ERROR(-20005, 'A raise cannot be '|| v_interval|| ' percent higher than its department''s average');
end if;
end after each row;
after statement is
begin
delete from employees_copy where employee_id=104;
dbms_output.put_line('All the updates are done successfully!.');
end after statement;
end;
--------------------------
----------------- An example of getting maximum level of recursive SQL levels
create or replace trigger trg_comp_emps
for insert or update or delete on employees_copy
compound trigger
type t_avg_dept_salaries is table of employees_copy.salary%type index by pls_integer;
avg_dept_salaries t_avg_dept_salaries;
before statement is
begin
update employees_copy set commission_pct = commission_pct where employee_id = 100;
for avg_sal in (select avg(salary) salary,nvl(department_id,999) department_id from employees_copy group by department_id) loop
avg_dept_salaries(avg_sal.department_id) := avg_sal.salary;
end loop;
end before statement;
after each row is
v_interval number := 15;
begin
if :new.salary > avg_dept_salaries(:new.department_id)*v_interval/100 then
RAISE_APPLICATION_ERROR(-20005, 'A raise cannot be '|| v_interval|| ' percent higher than its department''s average');
end if;
end after each row;
after statement is
begin
update employees_copy set commission_pct = commission_pct where employee_id = 100;
dbms_output.put_line('All the updates are done successfully!.');
end after statement;
end;
NOTES:
Mutating errors:
---------------
Mutating error occurs , whenever the trigger tries to query or modify the same table which is cuased trigger to fire,
this error occurs due to confict between the new and old states of table.
two ways to avoid this mutating error:
1.Use of statement level trigger instead of row level trigger :
bcs it executes for one complete statement , there wont be a confict between new and old states of table
-Disadvantage of use of statement level trigger is
-we cant get to use old and new values for each rows
-One way to avoid mutating table errors is to use statement-level triggers instead of row-level triggers.
Statement-level triggers fire once for each DML statement, not for each affected row,
so they do not cause conflicts with the table state.
2.With USE OF COMPOUND TRIGGERS:
-Compound triggers are special triggers which combine the logic of multiple trigger into one,
-Compound triggers contains four section
1.BEFORE Statement
2.BEFORE EACH ROW
3.AFTER EACH Row
4.AFTER STATEMENT
-By using compound triggers, you can separate the actions that need to access the triggering table from the actions
that need to query or modify other tables, and avoid the mutating table error.
TRIGGERS (PLURALSIGHT)::
----------------------
DML Triggers::
------------
- DML Trigger is the most commonly used trigger by the developer.
-They fire when DML operation occurs.
DML Trigger key points:
------------------
1.A trigger may fire once for statement or once for each affected rows.
2.A trigger may fire before or after statement or row.
3.A trigger may fire for updates ,deletes and inserts or any specified combination.
BEFORE TRIGGER : Executes before certain operations
ex: before insert
AFETR TRIGGER : Executes after ceratin operations
ex: after insert
STATEMENT LEVEL TRIGGER:
Executes once per SQL statement
ROW LEVEL TRIGGER:
Executes once per affected row
NEW PSEUDO RECORD:A data structure that holds the new value of an affected rows.
OLD PSEUDO RECORD:A data structure that contains the old value of an affected rows.
WHEN clause :Determine wether the trigger code should execute
TRANSACTION PARTICIPATION::
---------------------------
-If trigger terminates with the unhandled exception,the statement that invoked it is automatically rolled back
-Transaction that occure inside trigger are automatically part of the calling DML.
-We can not issue a commit or rollback from DML trigger
mutating error:
Mutating error:
-----------
quereing some table , that table already changing/caused to triggered
create or replace trigger emp_mutating_trigger
before delete on emp_copy6
for each row
declare
v_f_name varchar2(300);
begin
select first_name into v_f_name from emp_copy6 where employee_id=100;
dbms_output.put_line('trigger fired before the each row affected!!');
end;
delete from emp_copy6;
mutating error solution:
1.creating global variable and use statement level trigger to get rid of the mutating error in row level trigger
create table emp_log_data(id number,expression varchar2(265));
create table emp as select * from hr.employees;
select * from emp where first_name='Steven';
select * from emp_log_data;
CREATE OR REPLACE PACKAGE global_var
AS
l_steven_salary varchar2(200);
END global_var;
/
create or replace trigger emp_statement_level_trigger
before update of salary on emp
begin
select salary into global_var.l_steven_salary from emp where first_name='Steven' and last_name='King';
dbms_output.put_line('statement level trigger fired!!!');
end;
update department set department_name='kingdom_bug' where department_id=10;
create or replace trigger emp_row_level_trigger
before update of salary on emp
for each row
begin
if (:new.salary <global_var.l_steven_salary and :old.first_name<>'Steven' and :old.last_name<>'King') or (:old.first_name='Steven' and :old.last_name='King') then
insert into emp_log_data values(:new.employee_id,'salary updated successfully:'||' old salary:'||:old.salary||' new salary:'||:new.salary);
else
:new.salary:=:old.salary;
insert into emp_log_data values(:new.employee_id,'salary not updated: Salary can not be more then '||global_var.l_steven_salary);
end if;
dbms_output.put_line('row level trigger fired!!!');
end;
update emp set salary=1000 where employee_id=109;
drop package global_var;
drop trigger emp_statement_level_trigger;
drop trigger emp_row_level_trigger;
2.Using Compound trigger:
create or replace trigger mutating_solu_comp_trigger
for update on emp COMPOUND TRIGGER
l_steven_salary number;
BEFORE STATEMENT IS
BEGIN
select salary into l_steven_salary from emp where first_name='Steven' and last_name='King';
dbms_output.put_line('statement level trigger fired!!!');
END BEFORE STATEMENT;
BEFORE EACH ROW IS
BEGIN
if (:new.salary <l_steven_salary and :old.first_name<>'Steven' and :old.last_name<>'King') or (:old.first_name='Steven' and :old.last_name='King') then
insert into emp_log_data values(:new.employee_id,'salary updated successfully:'||' old salary:'||:old.salary||' new salary:'||:new.salary);
else
:new.salary:=:old.salary;
insert into emp_log_data values(:new.employee_id,'salary not updated: Salary can not be more then '||l_steven_salary);
end if;
dbms_output.put_line('row level trigger fired!!!');
END BEFORE EACH ROW;
end mutating_solu_comp_trigger;
--------------
update emp set salary=25000 where employee_id=110;
select * from emp_log_data;
begin
select1
if salary
selct2
end
|
/**
* MIT License
*
* Copyright (c) 2019-2022 TriumphTeam and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.triumphteam.docsly.elements
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/** Any serializable that can be linked to a specific location of a language. */
@Serializable
public sealed interface DocElement : WithName {
/** The URL location of the serializable. */
public val location: String
/** The virtual path of the serializable within the codebase. */
public val path: Path
/** Create a list of possible search references for the doc element. */
public fun createReferences(): List<String>
}
/** A [DocElement] that also contains language details. */
@Serializable
public sealed interface DocElementWithLanguage : DocElement, WithLanguage
/** Contains information about the [DocElement]'s path. */
@Serializable
public data class Path(
public val packagePath: String?,
public val classPath: List<String>?,
)
@Serializable
@SerialName("PACKAGE")
public data class SerializablePackage(
override val location: String,
override val path: Path,
override val name: String,
override val annotations: List<SerializableAnnotation>,
override val documentation: DescriptionDocumentation?,
override val extraDocumentation: List<Documentation>,
) : DocElement, WithDocumentation, WithExtraDocs, WithAnnotations {
override fun createReferences(): List<String> {
return listOf(name)
}
}
/** Possible documentation languages. */
@Serializable
public enum class Language {
KOTLIN, JAVA;
}
/** Possible visibilities for a serializable [WithVisibility]. */
@Serializable
public enum class Visibility {
PRIVATE, PROTECTED, PUBLIC, // Common
INTERNAL, // KT only
PACKAGE; // Java only
public companion object {
private val MAPPED_VALUES = entries.associateBy { it.name.lowercase() }
/** If the type is empty it'll be Java's [PACKAGE], else we take it from the mapped values. */
public fun fromString(name: String): Visibility? = if (name.isEmpty()) PACKAGE else MAPPED_VALUES[name]
}
}
/** Shout out to non-sealed for being the odd one out and needing [displayName], thanks Java. */
@Serializable
public enum class Modifier(public val order: Int, public val displayName: String? = null) {
// COMMON
OPEN(0), FINAL(0), ABSTRACT(0), SEALED(0),
// KOTLIN ONLY
REIFIED(0), CROSSINLINE(0), NOINLINE(0),
CONST(0),
EXTERNAL(1),
OVERRIDE(2),
LATEINIT(3),
TAILREC(4),
VARARG(5),
SUSPEND(6),
INNER(7),
FUN(8), ENUM(8), ANNOTATION(8),
COMPANION(9),
INLINE(10), VALUE(10),
INFIX(11),
DATA(13), OPERATOR(12),
// JAVA ONLY
STATIC(0), NATIVE(0), SYNCHRONIZED(0), STRICTFP(0),
TRANSIENT(0), VOLATILE(0), TRANSITIVE(0), RECORD(0),
NONSEALED(0, "non-sealed"), DEFAULT(0)
;
public companion object {
private val MAPPED_VALUES = entries.associateBy { it.displayName ?: it.name.lowercase() }
public fun fromString(name: String): Modifier? = MAPPED_VALUES[name]
}
}
|
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'ConfirmationScreen.dart';
class AnswersScreen extends StatefulWidget {
final int questionId; // Field to store the question ID
final String quizName; // Field to store the quiz name
final int totalMarks; // Field to store the total marks
final int quizId; // Field to store the quiz ID
AnswersScreen({
required this.questionId,
required this.quizName,
required this.totalMarks,
required this.quizId,
}); // Constructor to accept these fields
@override
_AnswersScreenState createState() => _AnswersScreenState();
}
class _AnswersScreenState extends State<AnswersScreen> {
final TextEditingController _optionAController = TextEditingController();
final TextEditingController _optionBController = TextEditingController();
final TextEditingController _optionCController = TextEditingController();
final TextEditingController _optionDController = TextEditingController();
int? _selectedOptionIndex;
int _getCorrectOptionIndex() {
return _selectedOptionIndex ?? -1; // Default to -1 if no option is selected
}
Future<void> _saveAnswer() async {
// Prepare the data to send in the POST request
Map<String, dynamic> postData = {
'question': {
'questionId': widget.questionId,
},
'optionA': _optionAController.text,
'optionB': _optionBController.text,
'optionC': _optionCController.text,
'optionD': _optionDController.text,
'correctOptionIndex': _getCorrectOptionIndex(),
'quizName': widget.quizName, // Include quizName in the post data
'totalMarks': widget.totalMarks, // Include totalMarks in the post data
'quizId': widget.quizId, // Include quizId in the post data
};
// Send the HTTP POST request
try {
final response = await http.post(
Uri.parse('http://192.168.220.102:8080/answer/save'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(postData),
);
if (response.statusCode == 201) {
print('Answer saved successfully.');
// Handle success as needed, such as showing a success message or navigating to another screen
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => ConfirmationScreen(
quizName: widget.quizName,
totalMarks: widget.totalMarks,
quizId: widget.quizId,
),
),
);
} else {
print('Failed to save answer: ${response.statusCode}');
// Handle error, such as showing an error message to the user
}
} catch (e) {
print('Error saving answer: $e');
// Handle error, such as showing an error message to the user
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Answers Screen'),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: _optionAController,
decoration: InputDecoration(labelText: 'Option A'),
),
TextField(
controller: _optionBController,
decoration: InputDecoration(labelText: 'Option B'),
),
TextField(
controller: _optionCController,
decoration: InputDecoration(labelText: 'Option C'),
),
TextField(
controller: _optionDController,
decoration: InputDecoration(labelText: 'Option D'),
),
SizedBox(height: 16),
Text('Choose Correct Answer:'),
RadioListTile<int>(
title: Text('Option A'),
value: 0,
groupValue: _selectedOptionIndex,
onChanged: (int? value) {
setState(() {
_selectedOptionIndex = value;
});
},
),
RadioListTile<int>(
title: Text('Option B'),
value: 1,
groupValue: _selectedOptionIndex,
onChanged: (int? value) {
setState(() {
_selectedOptionIndex = value;
});
},
),
RadioListTile<int>(
title: Text('Option C'),
value: 2,
groupValue: _selectedOptionIndex,
onChanged: (int? value) {
setState(() {
_selectedOptionIndex = value;
});
},
),
RadioListTile<int>(
title: Text('Option D'),
value: 3,
groupValue: _selectedOptionIndex,
onChanged: (int? value) {
setState(() {
_selectedOptionIndex = value;
});
},
),
ElevatedButton(
onPressed: _saveAnswer,
child: Text('Save Answer'),
),
],
),
),
);
}
}
|
#include "Character.hpp"
Character::Character() : _name("Default"), _count(0), _floorCount(0)
{
std::cout << this->_name << " Character default constructor called" << std::endl;
for (size_t i = 0; i < MATMAX; i++)
_inventory[i] = NULL;
}
Character::Character(std::string const& name) : _name(name), _count(0), _floorCount(0)
{
std::cout << this->_name << " Character constructor called" << std::endl;
for (size_t i = 0; i < MATMAX; i++)
_inventory[i] = NULL;
}
Character::Character(const Character& other) : _name(other._name), _count(other._count), _floorCount(other._floorCount)
{
std::cout << this->_name << " Character copy constructor called." << std::endl;
std::cout << " Copying inventory..." << std::endl;
for (size_t i = 0; i < MATMAX; i++)
{
this->_inventory[i] = NULL;
if (other._inventory[i])
this->_inventory[i] = other._inventory[i]->clone();
}
std::cout << " Copying floor..." << std::endl;
for (size_t i = 0; i < _floorCount; i++)
this->_floor[i] = other._floor[i]->clone();
}
Character& Character::operator= (const Character& other)
{
std::cout << "Copy assigning " << other.getName() << " to " << this->_name << std::endl;
if (this != &other)
{
ICharacter::operator=(other);
this->_name = other.getName();
std::cout << " Deleting inventory..." << std::endl;
for (size_t i = 0; i < MATMAX; i++)
{
if (this->_inventory[i])
delete (this->_inventory[i]);
this->_inventory[i] = NULL;
}
std::cout << " Deleting floor..." << std::endl;
for (size_t i = 0; i < this->_floorCount; i++)
delete (this->_floor[i]);
std::cout << " Copying new inventory..." << std::endl;
this->_count = other._count;
for (size_t i = 0; i < MATMAX; i++)
{
if (other._inventory[i])
this->_inventory[i] = other._inventory[i]->clone();
}
std::cout << " Copying new floor..." << std::endl;
this->_floorCount = other._floorCount;
for (size_t i = 0; i < this->_floorCount; i++)
this->_floor[i] = other._floor[i]->clone();
}
return (*this);
}
Character::~Character()
{
std::cout << this->_name << " Character destructor called" << std::endl;
std::cout << " Deleting inventory..." << std::endl;
for (size_t i = 0; i < MATMAX; i++)
{
if (this->_inventory[i])
delete (this->_inventory[i]);
}
std::cout << " Deleting floor..." << std::endl;
for (size_t i = 0; i < this->_floorCount; i++)
delete (this->_floor[i]);
}
std::string const& Character::getName() const
{
return (this->_name);
}
void Character::equip(AMateria* m)
{
std::cout << this->_name << " attempting to equip " << m->getType() << std::endl;
if (!m || this->_count == MATMAX)
{
std::cout << " " << this->_name << " cannot equip this materia" << std::endl;
return;
}
for (size_t i = 0; i < MATMAX; i++)
{
if (this->_inventory[i] == NULL)
{
this->_inventory[i] = m->clone();
this->_count++;
std::cout << " " << this->_name << " successfully equipped " << this->_inventory[i]->getType() << "!" << std::endl;
std::cout << " " << this->_count << " materia currently equipped." << std::endl;
break;
}
}
}
void Character::unequip(int idx)
{
if (idx < 0 || idx >= MATMAX || !(this->_inventory[idx]))
{
std::cout << this->_name << " cannot unequip that Materia!" << std::endl;
return;
}
if (this->_floorCount >= FLOORMAX)
{
std::cout << "The floor is full, cannot unequip" << std::endl;
return;
}
this->_floor[this->_floorCount] = this->_inventory[idx];
this->_inventory[idx] = NULL;
std::cout << this->_name << " successfully unequipped " << this->_floor[this->_floorCount]->getType() << "!" << std::endl;
this->_floorCount++;
std::cout << " Floor now contains " << this->_floorCount << " materia." << std::endl;
this->_count--;
std::cout << " " << this->_count << " materia currently equipped." << std::endl;
}
void Character::use(int idx, ICharacter& target)
{
if (idx < 0 || idx >= MATMAX || !(this->_inventory[idx]))
{
std::cout << this->_name << " cannot use that Materia!" << std::endl;
return;
}
std::cout << this->_name;
this->_inventory[idx]->use(target);
}
|
import 'remixicon/fonts/remixicon.css';
import '@utrecht/component-library-css';
import '@utrecht/design-tokens/dist/root.css';
import {
Heading5,
Paragraph,
Button,
Heading4,
Heading6,
} from '@utrecht/component-library-react';
import { ProgressBar } from '@openstad-headless/ui/src';
import { SessionStorage } from '@openstad-headless/lib/session-storage';
import { loadWidget } from '@openstad-headless/lib/load-widget';
import { getResourceId } from '@openstad-headless/lib/get-resource-id';
import { hasRole } from '@openstad-headless/lib';
import DataStore from '@openstad-headless/data-store/src';
import React, { useState, useEffect } from 'react';
import './likes.css';
import type { BaseProps, ProjectSettingProps } from '@openstad-headless/types';
export type LikeWidgetProps = BaseProps &
LikeProps &
ProjectSettingProps & {
resourceId?: string;
resourceIdRelativePath?: string;
};
export type LikeProps = {
title?: string;
variant?: 'small' | 'medium' | 'large';
yesLabel?: string;
noLabel?: string;
hideCounters?: boolean;
showProgressBar?: boolean;
progressBarDescription?: string;
};
function Likes({
title = '',
variant = 'large',
hideCounters,
yesLabel = 'Voor',
noLabel = 'Tegen',
showProgressBar = true,
...props
}: LikeWidgetProps) {
let resourceId = String(getResourceId({
resourceId: parseInt(props.resourceId || ''),
url: document.location.href,
targetUrl: props.resourceIdRelativePath,
})); // todo: make it a number throughout the code
const necessaryVotes = props.resources?.minimumYesVotes || 50;
// Pass explicitely because datastore is not ts, we will not get a hint if the props have changed
const datastore: any = new DataStore({
projectId: props.projectId,
api: props.api,
});
const session = new SessionStorage({ projectId: props.projectId });
const { data: currentUser } = datastore.useCurrentUser(props);
const { data: resource } = datastore.useResource({
projectId: props.projectId,
resourceId,
});
const [isBusy, setIsBusy] = useState(false);
const supportedLikeTypes: Array<{
type: 'yes' | 'no';
label: string;
icon: string;
}> = [
{ type: 'yes', label: yesLabel, icon: 'ri-thumb-up-line' },
{ type: 'no', label: noLabel, icon: 'ri-thumb-down-line' },
];
useEffect(() => {
let pending = session.get('osc-resource-vote-pending');
if (pending && pending[resource.id]) {
if (currentUser && currentUser.role) {
doVote(null, pending[resource.id]);
session.remove('osc-resource-vote-pending');
}
}
}, [resource, currentUser]);
async function doVote(
e: React.MouseEvent<HTMLElement, MouseEvent> | null,
value: string
) {
if (e) e.stopPropagation();
if (isBusy) return;
setIsBusy(true);
if (!props.votes.isActive) {
return;
}
if (!hasRole(currentUser, props.votes.requiredUserRole)) {
let loginUrl = props.login?.url || '';
if (props.votes.requiredUserRole == 'anonymous') {
loginUrl = props.login?.anonymous?.url || '';
}
if (!loginUrl) {
console.log('Config error: no login url defined');
return;
}
// login
session.set('osc-resource-vote-pending', { [resource.id]: value });
return (document.location.href = loginUrl);
}
let change: { [key: string]: any } = {};
if (resource.userVote) change[resource.userVote.opinion] = -1;
await resource.submitLike({
opinion: value,
});
setIsBusy(false);
}
return (
<div className="osc">
<div className={`like-widget-container ${variant}`}>
{title ? (
<Heading4 className="like-widget-title">{title}</Heading4>
) : null}
<div className={`like-option-container`}>
{supportedLikeTypes.map((likeVariant, index) => (
<Button
appearance="primary-action-button"
key={`${likeVariant.type}-${index}`}
onClick={(e) => doVote(e, likeVariant.type)}
className={`like-option ${
resource?.userVote?.opinion === likeVariant.type
? 'selected'
: ''
} ${hideCounters ? 'osc-no-counter' : ''}`}>
<section className="like-kind">
<i className={likeVariant.icon}></i>
{variant === 'small' ? null : likeVariant.label}
</section>
{!hideCounters ? (
<section className="like-counter">
{resource[likeVariant.type] && resource[likeVariant.type] < 10
? resource[likeVariant.type].toString().padStart(2, '0')
: resource[likeVariant.type] ||
(0).toString().padStart(2, '0')}
</section>
) : null}
</Button>
))}
</div>
{props?.resources?.minimumYesVotes && showProgressBar ? (
<div className="progressbar-container">
<ProgressBar progress={(resource.yes / necessaryVotes) * 100} />
<Paragraph className="progressbar-counter">
{resource.yes || 0} /{necessaryVotes}
</Paragraph>
</div>
) : null}
<div>
{props?.resources?.minimumYesVotes &&
showProgressBar &&
props.progressBarDescription && (
<Heading6 style={{ textAlign: 'start' }}>
{props.progressBarDescription}
</Heading6>
)}
</div>
</div>
</div>
);
}
Likes.loadWidget = loadWidget;
export { Likes };
|
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<header th:fragment="headerFragment" id="header" class="p-3 mb-3 border-bottom w-100" style="top: 0;">
<div class="container">
<div class="d-flex flex-wrap align-items-center justify-content-center justify-content-lg-start">
<ul class="nav col-12 col-lg-auto me-lg-auto mb-2 justify-content-center mb-md-0">
<li>
<a href="/" class="nav-link px-5 link-secondary">
<h3>Hoozy's CS</h3>
</a>
</li>
<li class="dropdown">
<a href="/know" class="nav-link px-4 link-secondary">
<h3>지식</h3>
</a>
</li>
<li class="dropdown">
<a href="/prob/short" class="nav-link px-4 link-secondary">
<h3>문제(단답형)</h3>
</a>
</li>
<li class="dropdown">
<a href="/prob/long" class="nav-link px-4 link-secondary">
<h3>문제(주관식)</h3>
</a>
</li>
<li class="dropdown">
<a href="/chat/rooms" class="nav-link px-4 link-secondary">
<h3>오픈 채팅</h3>
</a>
</li>
</ul>
<!-- 로그인 되었을 때 -->
<a th:if="${session.loginUser != null}" href="/logout" type="button" class="btn btn-primary">
로그아웃
</a>
<!--로그인 안되었을 때-->
<!-- Button trigger modal -->
<button th:if="${session.loginUser == null}" type="button" class="btn btn-primary" data-bs-toggle="modal"
data-bs-target="#loginModal">
로그인
</button>
<!-- Modal -->
<div class="modal fade" id="loginModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content col-md-10 mx-auto col-lg-5">
<div>
<button type="button" style="float: right; margin-right: 10px; margin-top: 10px;"
class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="mx-auto py-3">
<h3>로그인</h3>
</div>
<!-- th:object : form 내의 DTO(VO) 매핑, th:field : input 내의 id, name, value="" 자동 생성 -->
<form class="p-4 p-md-5 border rounded-3 bg-light" method="POST" th:action="@{/login}"
th:object="${user}">
<div class="form-floating mb-3">
<input type="email" class="form-control" id="email1" th:field="*{email}"
placeholder="email@example.com" required autofocus>
<label for="email">이메일(text@example.com)</label>
</div>
<div class="checkbox mb-3">
<label>
<input type="checkbox" id="emailStore" name="emailStore">
아이디 저장
</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="pwd1" th:field="*{pwd}"
placeholder="password" minlength="6" maxlength="12" required>
<label for="pwd">비밀번호(6자리 이상, 12자리 이하)</label>
</div>
<input type="submit" class="w-100 btn btn-lg btn-primary mt-4" value="로그인">
<hr class="my-4">
<div><small class="text-muted">아직 회원이 아니시라면, </small>
<a href="#" class="btn btn-primary" data-bs-toggle="modal" data-bs-dismiss="modal"
data-bs-target="#registerModal">회원가입</a>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="registerModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content col-md-10 mx-auto col-lg-5">
<div>
<button type="button" style="float: right; margin-right: 10px; margin-top: 10px;"
class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="mx-auto py-3">
<h3>회원가입</h3>
</div>
<form class="p-4 p-md-5 border rounded-3 bg-light" method="POST" th:action="@{/register}"
th:object="${user}">
<div class="form-floating mb-3">
<input type="name" class="form-control" th:id="nick" th:name="nick" placeholder="nick"
minlength="4" required autofocus>
<label for="nick">닉네임(중복 불가, 4자리 이상)</label>
<div id="nickNotice" class="invalid-feedback">
닉네임이 중복됩니다.
</div>
</div>
<div class="form-floating mb-3">
<input type="email" class="form-control" id="email2" th:field="*{email}"
placeholder="email@example.com" required>
<label for="email">이메일(중복 불가, text@example.com)</label>
<div id="emailNotice" class="invalid-feedback">
이메일이 중복됩니다.
</div>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="pwd2" th:field="*{pwd}"
placeholder="password" minlength="6" maxlength="12" aria-describedby="pwdNotice"
required>
<label for="pwd">비밀번호(6자리 이상, 12자리 이하)</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" placeholder="password" id="pwd_confirm"
minlength="6" maxlength="12" aria-describedby="pwdNotice" required>
<label for="pwd_confirm">비밀번호 확인</label>
<div id="pwdNotice" class="feedback" style="height: 20px;">
비밀번호를 입력해주세요.
</div>
</div>
<button type="submit" onclick="return check()"
class="w-100 btn btn-lg btn-primary mt-4">회원가입</button>
<hr class="my-4">
<div><small class="text-muted">이미 회원이시라면, </small>
<a href="#" class="btn btn-primary" data-bs-toggle="modal" data-bs-dismiss="modal"
data-bs-target="#loginModal">로그인</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script th:inline="javascript">
var cookie = $.cookie('email');
if (cookie != 'undefined') { // 쿠키에 이메일이 있으면
$('#emailStore').prop('checked', true); // 체크박스 체크
$('#email1').val($.cookie('email'));
} else {
console.log(cookie)
$('#emailStore').prop('checked', false); // 체크박스 체크 해제
$('#email1').val('');
}
$('#pwd_confirm').keyup(function () {
var pwd = $('#pwd2').val();
var pwd_confirm = $('#pwd_confirm').val();
if (pwd == pwd_confirm) {
$('#pwd_confirm').removeClass('is-invalid');
$('#pwd_confirm').addClass('is-valid');
$('#pwdNotice').html('비밀번호가 일치합니다.');
} else {
$('#pwd_confirm').removeClass('is-valid');
$('#pwd_confirm').addClass('is-invalid');
$('#pwdNotice').html('비밀번호가 일치하지 않습니다.');
}
});
$('#nick').keyup(function () {
var nick = $('#nick').val();
$.ajax({
type: 'get',
url: '/check/nick',
data: {
nick: nick,
},
contentType: "application/json;charset=UTF-8",
success: function (data) {
console.log(data);
// 중복
if (data == '1') {
$('#nick').addClass('is-invalid');
} else {
$('#nick').removeClass('is-invalid');
}
},
error: function (e) {
console.log(e);
}
});
});
$('#email2').keyup(function () {
var email = $('#email2').val();
$.ajax({
type: 'get',
url: '/check/email',
data: {
email: email,
},
contentType: "application/json;charset=UTF-8",
success: function (data) {
console.log(data);
// 중복
if (data == '1') {
$('#email2').addClass('is-invalid');
} else {
$('#email2').removeClass('is-invalid');
}
},
error: function (e) {
console.log(e);
}
});
});
function check() {
if ($('#nick').hasClass('is-invalid') || $('#email2').hasClass('is-invalid') || $('#pwd_confirm').hasClass('is-invalid')) {
return false;
} else {
return true;
}
};
</script>
</header>
</html>
|
$Id: README.txt,v 1.3 2005/10/14 08:53:57 webgeer Exp $
Description
-----------
The GMap filter module uses filters to allow the insertion of a Google map
into a node. It includes a page to create the macro and a filter to insert
a map based on the macro.
Installation
------------
1) copy the gmap directory into the modules directory
2) edit the theme files to ensure that the html file has the following at
the top of each page (the first one is recommended by Google, the
second is required for the lines to work in IE:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
3) Get a GMap API Key at http://www.google.com/apis/maps/signup.html
4) enable the 'gmap module' in drupal
5) edit admin/settings/gmap to include the key you received from google and
change any other default setting.
6) configure an 'input format' so that the gmap filter is activated. If
this will be on a 'html filtered' format, ensure that the weighting is
such that the HTML filter comes before the gmap filter.
Instructions
------------
A gmap macro can be created on the gmapmacro page and the text can then be
copied and pasted into any node where the gmap filter is enabled.
Default settings will be the initial settings and will be used for any
parameter not inserted into the macro.
A gmap can also be inserted into any page or template by using either the
macro text and the function gmap_from_text($macro); or using the
function gmap_from_var($gmapvar); where $gmapvar is an associative array.
After you insert the macro into a node, you can edit it using raw values
that you get from elsewhere to create a set of points or lines on the map.
It should be noted that when editing the macro you are not limited to 3
points on the map. An unlimited number of points may be added separated
by the '+' symbol. This could be used, for example, to plot a series of
points that you get from a GPS.
Demo
----
To see the macro creation tool go to:
http://vancouver.cyclehome.org/gmapmacro
To see an example a node with the macro inserted go to:
http://vancouver.cyclehome.org/
It should be noted that because of the way the gmap api works much of the
development can only be done on-line and therefore, I am not able to test
the module on my home server. As a result the version on this webpage
is likely to be a little more developed than the one in the drupal CVS.
These pages may also occasionally have errors on them.
Bugs & quirks
-------------
- When you preview a node, if the map is shown in the short version, it
will not be shown on the long version of the node, this is because only
one copy of a mapid can be shown on the same page.
To do
-----
- create interface to geocoding for address or postal code to Long, Lat
conversion. Preferably on the client side of the javascript gmapmacro
page.
- Change so number of markers is not limited. (currently maximum of 3).
- Create an API that will allow the use of the macro creation tool in any
module.
- Create setting to suppress the option of changing some of the settings in
the macro creation page. This could be used so that all maps generated
are the same size, or the same magnification.
- Add more settings (for example fixed/draggable map)
Credit
------
Written by:
James Blake
http://www.webgeer.com/James
History
-------
2005-10-15 Quite a few fixes. (some reported in the project and some just
noted myself)
-Map controls are properly initialized in the gmapmacro page (can be
removed or changed)
-33949-Prevent errors from occurring if the Google Map key still blank
(not yet set)
-34036-Hybrid and Satellite maps now show in nodes
-33951-Long,Lat order and terminology corrected (note old Macros will
still work)
-33730-Alignment problem fixed. Now uses css.
-A few other little bugs
2005-10-10 Fix a number of little things and improve the macro interface
2005-10-09 Initial Release (probably too early)
|
defmodule Aa.Invitations.Invitation do
use Ecto.Schema
import Ecto.Changeset
schema "invitations" do
field :status, :string, default: "pending"
belongs_to :user, Aa.Accounts.User
field :invitation_token, :string
field :valid_until, :naive_datetime
belongs_to :trip, Aa.Trips.Trip
belongs_to :created_by_user, Aa.Accounts.User
timestamps(type: :utc_datetime)
end
@doc false
def changeset(invitation, attrs) do
invitation
|> cast(attrs, [
:user_id,
:invitation_token,
:status,
:valid_until,
:trip_id,
:created_by_user_id
])
|> validate_required([:user_id, :trip_id, :created_by_user_id])
|> validate_inclusion(:status, ["pending", "accepted", "declined"])
|> set_valid_until()
|> generate_token()
|> foreign_key_constraint(:user_id)
|> foreign_key_constraint(:created_by_user_id)
|> foreign_key_constraint(:trip_id)
end
defp generate_token(changeset) do
if changeset.valid?,
do:
put_change(changeset, :invitation_token, :crypto.strong_rand_bytes(64) |> Base.encode64()),
else: changeset
end
defp set_valid_until(changeset) do
if changeset.valid? do
put_change(
changeset,
:valid_until,
NaiveDateTime.add(NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second), 1, :day)
)
else
changeset
end
end
end
|
import React from "react";
import { useQuery, gql } from "@apollo/client";
const FILMS_QUERY = gql`
{
launchesPast(limit: 10) {
id
launch_date_local
launch_site {
site_name_long
}
mission_name
links {
article_link
video_link
}
rocket {
rocket_name
}
ships {
name
image
}
}
}
`;
interface SpaceXObject {
id: number;
launch_site: {
site_name_long: string;
};
launch_date_local: Date;
mission_name: string;
links: {
article_link: string;
video_link: string;
};
rocket: {
rocket_name: string;
};
ships: [
{
name: string;
image: string | undefined;
}
];
}
const Missions = () => {
const { data, loading, error } = useQuery(FILMS_QUERY);
if (loading) return <>Loading...</>;
if (error) return <pre>{error.message}</pre>;
return (
<div>
List of missions done by SpaceX
<br />
<br />
<div className="row">
{data.launchesPast.map((launch: SpaceXObject) => {
return (
<div className="column" key={launch.id}>
<div className="card">
<img
src={
launch.ships.length > 0
? launch.ships[0].image
: "https://annahemi.files.wordpress.com/2015/11/1274237_300x300.jpg"
}
className="imageWidth"
alt="Avatar"
/>
<div className="container">
<h4>
<b>{launch.mission_name}</b>
</h4>
<p>Date: {launch.launch_date_local}</p>
<p>Rocket used: {launch.rocket.rocket_name}</p>
<p>
<a href={launch.links.video_link}>Video link</a>
</p>
</div>
</div>
</div>
);
})}
</div>
</div>
);
};
export default Missions;
|
<template lang="pug">
.curso-main-container.pb-3.tema3
BannerInterno
.container.tarjeta.tarjeta--blanca.p-4.p-md-5.mb-5
.titulo-principal.color-acento-botones
.titulo-principal__numero
span 3
h1 Sistemas de gestión de la energía (SGEn)
.row.justify-content-center.align-items-center.mb-4(data-aos="fade-left")
.col-md-7.col-12(data-aos="fade-down")
p Como respuesta a las necesidades de los países y las organizaciones frente a los paradigmas del modelo energético a través de los años se ha trabajado en el desarrollo de los #[strong sistemas de gestión de la energía (SGEn)] como la herramienta principal que permite integrar y sistematizar todos los procesos que involucran los usos y consumos de la energía necesarios para el cumplimiento de la misión, la visión y los objetivos de las empresas y de las organizaciones, incluyendo la sostenibilidad ambiental de las operaciones.
p Los sistemas de gestión de la energía (SGEn) están basados en el modelo del ciclo PHVA (planear-hacer-verificar-actuar), utilizando la experiencia obtenida con otros sistemas de gestión como, por ejemplo, el sistema de gestión de la calidad. Inicialmente los SGEn se implementaron en las empresas alrededor del mundo con el objetivo principal de ejecutar y documentar los proyectos de eficiencia energética y ahorro de energía, que permitan reducir los costos e incrementar su competitividad; sin embargo, a través de los años se ha demostrado el éxito de esta metodología no solo para este fin, sino para gestionar todos los procesos de las organizaciones relacionados con la energía como, por ejemplo, las políticas de la organización, la responsabilidad de la alta dirección, los procedimientos de compra de energéticos y equipos que usan energía, las comunicaciones, el desarrollo de competencias en los empleados, la mejora continua, por mencionar algunos.
.col-md-5.col-12(data-aos="fade-up")
img.mb-0.position-relative(src="@/assets/curso/temas/tema3/tema3-01.png")
.row.justify-content-center.align-items-center.mb-4(data-aos="fade-left")
.col-md-5.col-12(data-aos="fade-up")
img.mb-0.position-relative(src="@/assets/curso/temas/tema3/tema3-02.png")
.col-md-7.col-12(data-aos="fade-down")
p En resumen, un #[strong sistema de gestión de la energía (SGEn)] es una metodología establecida que permite a las empresas u organizaciones de cualquier tamaño o actividad sistematizar de manera continua las acciones orientadas a la eficiencia energética, el uso racional de la energía en las operaciones, las buenas prácticas de mantenimiento, la optimización de los costos energéticos, la confiabilidad en el suministro y la disminución de los impactos ambientales por el uso y el consumo de la energía.
p La metodología más utilizada y reconocida mundialmente para los sistemas de gestión de la energía se denomina ISO 50001 Sistemas de gestión de la energía requisitos con orientación para su uso (actualmente versión 2018), elaborada por la Organización Internacional de Normalización (ISO). La primera versión de esta norma fue publicada en el año 2011. La norma ISO 50001 compila toda la experiencia internacional de las mejores prácticas para la implementación, la operación, el mantenimiento y la mejora continua de los SGEn.
p.mb-5(data-aos="fade-down") En Colombia también se da la gestión de la energía desde los sistemas así:
.tarjeta.tarjeta--azul.p-4.mb-5(data-aos="fade-down")
SlyderA(tipo="b")
.row.justify-content-center.align-items-center
.col-md-6.col-12.mb-4.mb-md-0
p.mb-0 Desde que el Gobierno Nacional promulgó la Ley 697 de 2001 donde se declara “…el uso racional y eficiente de la energía (URE) como un asunto de interés social, público y de conveniencia nacional, fundamental para asegurar el abastecimiento energético pleno y oportuno, la competitividad de la economía colombiana, la protección al consumidor y la promoción del uso de energías no convencionales de manera sostenible con el medioambiente y los recursos naturales”, se realizaron programas piloto para la implementación y la capacitación de los sistemas de gestión de la energía en las industrias, en especial durante los años 2010 a 2014.
.col-md-6.col-lg-5.col-12
figure
img(src='@/assets/curso/temas/tema3/tema3-03.png', alt='')
.row.justify-content-center.align-items-center
.col-md-6.col-12.mb-4.mb-md-0
p.mb-0 Sin embargo, es en el año 2014 cuando el Gobierno Nacional promulga la Ley 1715 de 2014 donde se especifica la necesidad para la elaboración de planes de gestión eficiente de la energía en las administraciones públicas y el fomento de la investigación en el ámbito de la gestión eficiente de la energía a nivel nacional.
.col-md-6.col-lg-5.col-12
figure
img(src='@/assets/curso/temas/tema3/tema3-04.png', alt='')
.row.justify-content-center.align-items-center
.col-md-7.col-12.mb-4.mb-md-0
p.mb-2 Posteriormente, con la publicación por parte del Ministerio de Minas y Energía del Plan de acción indicativo de eficiencia energética 2017-2022 (PAI PROURE) se consolida el uso de los sistemas de gestión de la energía como herramienta para lograr las metas indicativas en materia energética para el país.
h4.mb-0 Sabías que
p.mb-2 Además de ser una herramienta para mejorar el desempeño energético de las organizaciones, la implementación de los SGEn permite la creación de empleos verdes (denominados así porque contribuyen a la sostenibilidad ambiental del planeta) y un mercado competitivo para el desarrollo de servicios energéticos y ambientales.
h4.mb-0 Recuerda
p Lo anterior va de la mano con la Política de crecimiento verde establecida por el Departamento Nacional de Planeación en el CONPES 3934 de 2018.
.col-md-5.col-12
figure
img(src='@/assets/curso/temas/tema3/tema3-05.png', alt='')
.row.justify-content-center.align-items-center
.col-md-6.col-12.mb-4.mb-md-0
p.mb-0 Finalmente, con la Ley 2099 de 2021 el Gobierno Nacional establece el desarrollo de la gestión eficiente de la energía como medio para el desarrollo económico sostenible, la reducción de emisiones de gases de efecto invernadero (GEI) y la seguridad del abastecimiento energético.
.col-md-6.col-lg-5.col-12
figure
img(src='@/assets/curso/temas/tema3/tema3-06.png', alt='')
p.mb-5(data-aos="fade-down") Teniendo en cuenta todo lo que se ha informado, algunos programas implementados en Colombia para la promoción y el fortalecimiento de la gestión eficiente de la energía son:
.tarjeta.tarjeta--azul.p-4.mb-5(data-aos="fade-down")
SlyderA(tipo="b")
.row.justify-content-center.align-items-center
.col-md-6.col-12.mb-4.mb-md-0
h4 Programa EEI Colombia
p.mb-0 Es un proyecto realizado por el Fondo Mundial para el Medioambiente (GEF por sus siglas en inglés), la Organización de las Naciones Unidas para el Desarrollo Industrial (ONUDI) y la Unidad de Planeación Minero-Energética (UPME).
.col-md-6.col-lg-5.col-12
figure
img(src='@/assets/curso/temas/tema3/tema3-07.png', alt='')
.row.justify-content-center.align-items-center
.col-md-6.col-12.mb-4.mb-md-0
h4 De acuerdo con el Ministerio de Minas y Energía, ONUDI, GEF (2019), los objetivos principales del programa son:
ul.lista-ul.mb-0
li.mb-0
i.fas.fa-angle-right
| Impulsar el mercado de servicios y productos de eficiencia energética en la industria colombiana, a través del fortalecimiento de reglamentos y normas técnicas.
li.mb-0
i.fas.fa-angle-right
| La creación de capacidades para la implementación de sistemas de gestión de la energía.
li.mb-0
i.fas.fa-angle-right
| Implementación de estrategias para la optimización de procesos y eficiencia energética.
li.mb-0
i.fas.fa-angle-right
| El diseño de esquemas financieros para permitir la sostenibilidad de la implementación de medidas en el mediano y largo plazo.
.col-md-6.col-lg-5.col-12
figure
img(src='@/assets/curso/temas/tema3/tema3-08.png', alt='')
.row.justify-content-center.align-items-center
.col-md-7.col-12.mb-4.mb-md-0
h4 Colombia productiva
p Colombia productiva es un patrimonio autónomo creado por el Ministerio de Comercio, Industria y Turismo en el año 2008, con el objetivo principal de promover la productividad y competitividad en la industria y dar cumplimiento a la Política de Desarrollo Productivo establecida en el CONPES 3866 de 2016 y la Política Nacional de Competitividad y Productividad establecida en el CONPES 3527 de 2008.
p En el aspecto de productividad, el programa Colombia productiva ha desarrollado el proyecto denominado Fábricas de productividad, el cual tiene como uno de los ejes de acción la eficiencia energética como el factor que más impacta de manera positiva a las empresas con los siguientes beneficios:
ul.lista-ul.mb-0
li.mb-0
i.fas.fa-angle-right
| Ahorros económicos para los empresarios.
li.mb-0
i.fas.fa-angle-right
| Aumento de la competitividad y productividad.
li.mb-0
i.fas.fa-angle-right
| Reducción de emisiones de gases de efecto invernadero y gases contaminantes.
li.mb-0
i.fas.fa-angle-right
| Promoción de mercado ambiental y acceso a nuevos mercados.
.col-md-5.col-12
figure
img(src='@/assets/curso/temas/tema3/tema3-09.png', alt='')
</template>
<script>
export default {
name: 'Tema3',
data: () => ({
// variables de vue
}),
mounted() {
this.$nextTick(() => {
this.$aosRefresh()
})
},
updated() {
this.$aosRefresh()
},
}
</script>
<style lang="sass"></style>
|
nginx.org website
This repository hosts the content and static site generator for [nginx.org](https://nginx.org/).
The website is primarily authored in XML and converted to static HTML content through
[Extensible Stylesheet Language Transformations](https://en.wikipedia.org/wiki/XSLT) (XSLT).
Static site generation
----------------------
The [.xslt files](xslt/) in this repo are automatically generated and should not be edited directly.
XML transformation is defined by [.xsls files](xsls/) and performed by [XSLScript](tools/xslscript.pl)
as part of the site generation process.
The XML content is then combined with the corresponding XSLT file(s) that generates HTML in the
**libxslt** directory.
```mermaid
flowchart
direction LR
subgraph make
.xsls -->|XSLScript| .xslt
subgraph xsltproc
.xslt --> .html
.xml ---> .html
end
end
```
Site generation is performed with [make(1)](GNUmakefile) with several targets, notably:
* The default target creates the static HTML (this is usually enough for local development).
* `images` target creates thumbnail icons from [sources](sources/) for the [books page](xml/en/books.xml).
* `gzip` target creates compressed versions of the HTML and text content which is used by the production website.
Docker image
------------
Use the [Dockerfile](Dockerfile) to create a self-container Docker image that approximates the production website.
```shell
docker build --no-cache -t nginx.org:my_build .
```
The docker image exposes port 8080 as per the convention for container hosting services.
Local development with Docker
-----------------------------
Use [Docker Compose](docker-compose.yaml) to enable local development with a text editor (no
other tools required). Site generation is performed within the Docker container whenever a change
is made to the local files in the [banner](banner/), [xml](xml/), and [xsls](xsls/) directories.
Start the development container:
```
docker compose up --build --watch
```
Test the site by visiting [localhost:8001](http://localhost:8001/).
> **Note:** To keep the site generation time to a minimum, only the core HTML content is produced.
> Use the main [Dockerfile](Dockerfile) for a complete build.
Local development with toolchain
--------------------------------
### Prerequisities
The static site generator uses a UNIX/Linux toolchain that includes:
* `make`
* `perl`
* `xsltproc`
* `xmllint` - typically found in the **libxml2** or **libxml2-utils** packages
* `jpegtopnm`, `pamscale` and `pnmtojpeg` - typically found in the **netpbm** package; only required for the `images` make(1) target
* `rsync` - only required for the `gzip` make(1) target
**macOS** ships with all of the above with the exception of the **netpbm** tools.
This can be installed with [Homebrew](https://formulae.brew.sh/formula/netpbm) if required.
Some **Linux** distros may also require the `perl-dev` or `perl-utils` package.
**Windows** *TODO*
### Building the site content
With the prerequisites installed, run `make` from the top-level directory. This will create the
**libxslt** directory with HTML content therein.
### Running the website locally
Adapt the [docker-nginx.conf](docker-nginx.conf) file to suit your local `nginx` installation.
Authoring content
-----------------
### How pages are constructed
*TODO*
### Making changes
Existing pages are edited by modifying the content in the [xml directory](xml/). After making changes,
run `make` from the top-level directory to regenerate the HTML.
### Creating new pages
New pages should be created in the most appropriate location within a language directory,
typically [xml/en](xml/en/). The [GNUmakefile](xml/en/GNUmakefile) must then be updated to
reference the new page before it is included in the site generation process.
After determining the most appropriate location for the page, choose the most appropriate Document
Type Definition ([DTD](dtd/)) for your content. This will determine the page layout and the XML tags
that are available for markup. The most likely candidates are:
* [article.dtd](dtd/article.dtd) - for general content
* [module.dtd](dtd/module.dtd) - for nginx reference documentation
Note that DTD files may include other DTDs, e.g. **article.dtd** [includes](dtd/article.dtd#L18)
[**content.dtd**](dtd/content.dtd).
### Style guide
Pay attention to existing files before making significant edits.
The basic rules for XML content are:
* Lines are typically no longer than 70 characters, with an absolute maximum of 80 characters.
`<programlisting>` and `<example>` tags are excluded from this requirement.
* Each new sentence begins on a new line.
* A single empty line appears between `<para>` tags and other tags of equal significance.
* Two empty lines appear between `<section>` tags.
* Do not link to your content from the menu unless you are creating an all-new type of content.
* Apply a version bump to the changed file: increment the number by 1 in the `rev=""` line.
* The commit log criteria:
* the log line is no longer than 67 characters,
* the style is similar to existing log entries (see https://hg.nginx.org/nginx.org),
* the end of a log entry is indicated by a full stop.
Example: `Improved GNUMakefile explanation.`
* Review feedback is implemented into the same patch, do not include a separate patch with the review in the PR. The PRs are added as "Rebase and merge" option.
|
/* eslint-disable spaced-comment */
/**
* ScandiPWA - Progressive Web App for Magento
*
* Copyright © Scandiweb, Inc. All rights reserved.
* See LICENSE for license details.
*
* @license OSL-3.0 (Open Software License ("OSL") v. 3.0)
* @package scandipwa/scandipwa
* @link https://github.com/scandipwa/scandipwa
*/
import { createRef, PureComponent, Suspense } from 'react';
import { FieldType } from 'Component/Field/Field.config';
import ProductPrice from 'Component/ProductPrice';
import TextPlaceholder from 'Component/TextPlaceholder';
import { TextPlaceHolderLength } from 'Component/TextPlaceholder/TextPlaceholder.config';
import { CategoryPageLayout } from 'Route/CategoryPage/CategoryPage.config';
import { ReactElement } from 'Type/Common.type';
import { filterConfigurableOptions } from 'Util/Product';
import { IndexedBundleItem, IndexedConfigurableOption } from 'Util/Product/Product.type';
import { lowPriorityLazy } from 'Util/Request/LowPriorityRender';
import { ValidationInputTypeNumber } from 'Util/Validator/Config';
import { ProductType } from './Product.config';
import { ProductComponentProps } from './Product.type';
export const ProductReviewRating = lowPriorityLazy(
() => import(/* webpackMode: "lazy", webpackChunkName: "product-misc" */ 'Component/ProductReviewRating'),
);
export const ProductConfigurableAttributes = lowPriorityLazy(
() => import(/* webpackMode: "lazy", webpackChunkName: "product-misc" */ 'Component/ProductConfigurableAttributes/ProductConfigurableAttributes.container'),
);
export const AddToCart = lowPriorityLazy(
() => import(/* webpackMode: "lazy", webpackChunkName: "product-misc" */ 'Component/AddToCart'),
);
export const FieldContainer = lowPriorityLazy(
() => import(/* webpackMode: "lazy", webpackChunkName: "product-misc" */ 'Component/Field'),
);
export const ProductCustomizableOptions = lowPriorityLazy(
() => import(/* webpackMode: "lazy", webpackChunkName: "product-misc" */ 'Component/ProductCustomizableOptions'),
);
export const ProductBundleOptions = lowPriorityLazy(
() => import(/* webpackMode: "lazy", webpackChunkName: "product-misc" */ 'Component/ProductBundleOptions'),
);
export const GroupedProductList = lowPriorityLazy(
() => import(/* webpackMode: "lazy", webpackChunkName: "product-misc" */ 'Component/GroupedProductList'),
);
export const ProductCompareButton = lowPriorityLazy(
() => import(/* webpackMode: "lazy", webpackChunkName: "product-misc" */ 'Component/ProductCompareButton'),
);
export const ProductDownloadableLinks = lowPriorityLazy(
() => import(/* webpackMode: "lazy", webpackChunkName: "product-misc" */ 'Component/ProductDownloadableLinks'),
);
export const ProductDownloadableSamples = lowPriorityLazy(
() => import(/* webpackMode: "lazy", webpackChunkName: "product-misc" */ 'Component/ProductDownloadableSamples'),
);
export const ProductWishlistButton = lowPriorityLazy(
() => import(/* webpackMode: "lazy", webpackChunkName: "product-misc" */ 'Component/ProductWishlistButton'),
);
/**
* Product
* @class Product
* @namespace Component/Product/Component
*/
export class ProductComponent<P extends ProductComponentProps = ProductComponentProps> extends PureComponent<P> {
static defaultProps: Partial<ProductComponentProps> = {
configFormRef: createRef<HTMLFormElement>(),
};
className = this.constructor.name.slice(0, -1) || 'Product';
//#region PLACEHOLDERS
renderTextPlaceholder(): ReactElement {
return <TextPlaceholder />;
}
renderBlockPlaceholder(): ReactElement {
return (
<div
block={ this.className }
mods={ { isLoading: true, isPlaceholder: true } }
/>
);
}
//#endregion
//#region PRODUCT OPTIONS
renderBundleOptions(): ReactElement {
const {
product: {
items = [],
} = {},
updateSelectedValues,
} = this.props;
return (
<Suspense fallback={ null }>
<ProductBundleOptions
options={ items as IndexedBundleItem[] }
updateSelectedValues={ updateSelectedValues }
/>
</Suspense>
);
}
renderCustomizableOptions(): ReactElement {
const {
product: {
options,
},
updateSelectedValues,
} = this.props;
return (
<Suspense fallback={ null }>
<ProductCustomizableOptions
options={ options }
updateSelectedValues={ updateSelectedValues }
/>
</Suspense>
);
}
renderDownloadableLinks(): ReactElement {
const {
setDownloadableLinks,
product: {
type_id,
downloadable_product_links: links,
links_title,
links_purchased_separately,
},
} = this.props;
if (type_id !== ProductType.DOWNLOADABLE || (Array.isArray(links) && !links.length)) {
return null;
}
const isRequired = links_purchased_separately === 1;
return (
<Suspense fallback={ null }>
<ProductDownloadableLinks
links={ links }
setLinkedDownloadables={ setDownloadableLinks }
title={ links_title }
isRequired={ isRequired }
/>
</Suspense>
);
}
renderDownloadableSamples(): ReactElement {
const {
product: {
type_id,
samples_title = '',
downloadable_product_samples: samples,
},
} = this.props;
if (type_id !== ProductType.DOWNLOADABLE || !samples || (Array.isArray(samples) && !samples.length)) {
return null;
}
return (
<Suspense fallback={ null }>
<ProductDownloadableSamples
title={ samples_title }
samples={ samples }
/>
</Suspense>
);
}
getConfigurableAttributes(): Record<string, IndexedConfigurableOption> {
const {
product: { configurable_options: configurableOptions = {}, variants = [] },
} = this.props;
return filterConfigurableOptions(configurableOptions, variants);
}
renderConfigurableOptions(): ReactElement {
const {
setActiveProduct,
parameters,
product: { type_id: type, variants = [] },
inStock,
addToCartTriggeredWithError,
updateAddToCartTriggeredWithError,
} = this.props;
if (type !== ProductType.CONFIGURABLE) {
return null;
}
return (
<div
block="ProductActions"
elem="AttributesWrapper"
>
<Suspense fallback={ null }>
<ProductConfigurableAttributes
// eslint-disable-next-line no-magic-numbers
numberOfPlaceholders={ [2, 4] }
updateAddToCartTriggeredWithError={ updateAddToCartTriggeredWithError }
addToCartTriggeredWithError={ addToCartTriggeredWithError }
mix={ { block: this.className, elem: 'Attributes' } }
parameters={ parameters }
variants={ variants }
updateConfigurableVariant={ setActiveProduct }
configurable_options={ this.getConfigurableAttributes() }
isContentExpanded
inStock={ inStock }
showProductAttributeAsLink={ false }
/>
</Suspense>
</div>
);
}
renderGroupedOptions(): ReactElement {
const {
product,
product: {
type_id: typeId,
},
setQuantity,
quantity,
} = this.props;
if (typeId !== ProductType.GROUPED) {
return null;
}
return (
<div
block={ this.className }
elem="GroupedItems"
>
<Suspense fallback={ null }>
<GroupedProductList
product={ product }
quantity={ quantity }
setQuantity={ setQuantity }
/>
</Suspense>
</div>
);
}
renderCustomAndBundleOptions(): ReactElement {
const { product: { type_id }, configFormRef } = this.props;
return (
<form ref={ configFormRef }>
{ type_id === ProductType.BUNDLE && this.renderBundleOptions() }
{ this.renderCustomizableOptions() }
</form>
);
}
//#endregion
//#region BUTTONS
renderAddToCartButton(layout = CategoryPageLayout.GRID): ReactElement {
const {
addToCart,
inStock,
quantity,
getActiveProduct,
updateSelectedValues,
} = this.props;
return (
<Suspense fallback={ null }>
<AddToCart
mix={ { block: this.className, elem: 'AddToCart' } }
addToCart={ addToCart }
isDisabled={ !inStock }
isIconEnabled={ false }
layout={ layout }
updateSelectedValues={ updateSelectedValues }
quantity={ quantity }
product={ getActiveProduct() }
/>
</Suspense>
);
}
renderWishlistButton(): ReactElement {
const { magentoProduct, isWishlistEnabled } = this.props;
if (magentoProduct.length === 0 || !isWishlistEnabled) {
return null;
}
return (
<Suspense fallback={ null }>
<ProductWishlistButton
magentoProduct={ magentoProduct }
mix={ {
block: this.className,
elem: 'WishListButton',
} }
/>
</Suspense>
);
}
renderCompareButton(): ReactElement {
const { product: { id } } = this.props;
if (!id) {
return null;
}
return (
<Suspense fallback={ null }>
<ProductCompareButton
productId={ id }
mix={ {
block: this.className,
elem: 'ProductCompareButton',
mods: { isGrey: true },
} }
/>
</Suspense>
);
}
renderQuantityChanger(): ReactElement {
const {
quantity,
minQuantity,
maxQuantity,
setQuantity,
inStock,
product: { type_id },
} = this.props;
if (type_id === ProductType.GROUPED) {
return null;
}
return (
<Suspense fallback={ null }>
<FieldContainer
type={ FieldType.NUMBER_WITH_CONTROLS }
attr={ {
id: 'item_qty',
name: 'item_qty',
defaultValue: quantity as number,
max: maxQuantity,
min: minQuantity,
} }
validationRule={ {
inputType: ValidationInputTypeNumber.NUMERIC,
isRequired: true,
range: {
min: minQuantity,
max: maxQuantity,
},
} }
isDisabled={ !inStock }
mix={ { block: this.className, elem: 'Qty' } }
events={ { onChange: setQuantity } }
validateOn={ ['onChange'] }
/>
</Suspense>
);
}
//#endregion
//#region FIELDS
renderRatingSummary(): ReactElement {
const {
product: {
review_summary: {
rating_summary,
review_count,
} = {},
},
} = this.props;
if (!rating_summary) {
return null;
}
return (
<Suspense fallback={ null }>
<ProductReviewRating
summary={ rating_summary || 0 }
count={ review_count }
/>
</Suspense>
);
}
renderBrand(withMeta = false): ReactElement {
const {
product: {
attributes: { brand: { attribute_value: brand = '' } = {} } = {},
},
} = this.props;
if (!brand) {
return null;
}
return (
<>
{ withMeta && <meta itemProp="brand" content={ brand } /> }
<h4 block={ this.className } elem="Brand" itemProp="brand">
<TextPlaceholder content={ brand } />
</h4>
</>
);
}
renderPrice(isPreview = false, isSchemaRequired = false): ReactElement {
const { getActiveProduct, productPrice } = this.props;
const product = getActiveProduct();
const {
type_id: type,
price_tiers: priceTiers,
} = product;
if (!productPrice) {
return null;
}
return (
<div
block={ this.className }
elem="PriceWrapper"
>
<ProductPrice
price={ productPrice }
priceType={ type as ProductType }
tierPrices={ priceTiers }
isPreview={ isPreview }
isSchemaRequired={ isSchemaRequired }
mix={ { block: this.className, elem: 'Price' } }
/>
</div>
);
}
renderStock(): ReactElement {
const { inStock } = this.props;
const stockStatusLabel = inStock ? __('In stock') : __('Out of stock');
return <span block={ this.className } elem="Stock">{ stockStatusLabel }</span>;
}
renderSku(): ReactElement {
const { getActiveProduct } = this.props;
const { sku } = getActiveProduct();
return <span block={ this.className } elem="Sku" itemProp="sku">{ __('SKU: %s', sku) }</span>;
}
/**
* Renders name if { dynamic } is set to true, then will output
* name to active product AKA configurable products selected variant
*
* @param header If header outputs as H1
* @param dynamic Name type (false - shows parent product only)
* @returns {ReactElement}
*/
renderName(header = true, dynamic = false): ReactElement {
const { product: { name }, productName } = this.props;
const nameToRender = dynamic ? productName : name;
if (!header) {
return (
<p block={ this.className } elem="Name">
<TextPlaceholder content={ nameToRender } length={ TextPlaceHolderLength.MEDIUM } />
</p>
);
}
return (
<h1 block={ this.className } elem="Title" itemProp="name">
<TextPlaceholder content={ nameToRender } length={ TextPlaceHolderLength.MEDIUM } />
</h1>
);
}
//#endregion
render(): ReactElement {
return null;
}
}
export default ProductComponent;
|
import {
FetchHttpClient,
HttpClient,
HttpSparqlRepository,
RemoteDataSource,
} from '@exec-graph/graph/data-source-remote';
import { DataSet, DataSource } from '@exec-graph/graph/types';
import { Component } from 'react';
import { detailQuery, wikidataQuery } from './detail-view-queries';
import { DetailView as WrappedDetailView } from '@exec-graph/explorer/detail-view';
import LoadingBar, {
LoadingStatus,
Step,
} from '@exec-graph/ui-react/loading-bar';
/**
* URL of the WikiData Sparql Endpoint for automatic queries
*/
const WIKIDATA_SPARQL_ENDPOINT = 'https://query.wikidata.org/sparql';
/**
* This attribute defines the field in which the WikiData Property is defined
*
* Note: In theory this field could point to an arbitrary
* source, not only wikidata. However, at the current time
* all ExecGraph entities only refer to wikidata so we kept
* the code simple.
*/
const WIKIDATA_JOIN_ATTRIBUTE = 'http://schema.org/sameAs';
/**
* Type definition of mandatory and optional properties of the {@link DetailView} component
*/
export interface DetailViewProps {
selectedObject: string;
data?: DataSet;
mainDataSource?: DataSource;
/**
* Invoked if a user used the detail view to travers the graph
*/
onSelect: (selectedObject: string) => void;
}
/**
* Type definition of internal state of the {@link TableView} component
*/
interface DetailViewState {
detailsStatus: LoadingStatus;
wikidataStatus: LoadingStatus;
data?: DataSet;
}
/**
* Loads the right data and displays it in the
* wrapped DetailView component
*
* In particular it deals with loading all details
* and the addition of wikidata contents
*
* @category React Component
*/
export class DetailView extends Component<DetailViewProps, DetailViewState> {
private wikidataDataSource: DataSource;
constructor(props: DetailViewProps) {
super(props);
this.state = {
data: this.props.data,
detailsStatus: LoadingStatus.NOT_STARTED,
wikidataStatus: LoadingStatus.NOT_STARTED,
};
this.wikidataDataSource = this.initRemoteSource(WIKIDATA_SPARQL_ENDPOINT);
}
/**
* React event hook called upon mounting the component to the page tree
*/
public override componentDidMount(): void {
this.loadDetails();
}
/**
* React event hook called upon change of passed properties
*/
public override componentDidUpdate(
prevProps: Readonly<DetailViewProps>
): void {
if (this.props.selectedObject !== prevProps.selectedObject) {
this.setState(
{
data: this.props.data,
detailsStatus: LoadingStatus.NOT_STARTED,
wikidataStatus: LoadingStatus.NOT_STARTED,
},
() => this.loadDetails()
);
}
}
/**
* Provides a {@link DataSource} instance for the passed endpoint
*
* @param endpoint url of the sparql endpoint
* @returns the {@link DataSource} instance
*/
private initRemoteSource(endpoint: string): DataSource {
const httpClient: HttpClient = new FetchHttpClient();
return new RemoteDataSource(new HttpSparqlRepository(endpoint, httpClient));
}
/**
* Loads the data from the different sources
*/
private loadDetails(): void {
const selected = this.props.selectedObject;
if (selected == null) {
return;
}
this.setState({
detailsStatus: LoadingStatus.PENDING,
});
this.props.mainDataSource
?.getForSparql(detailQuery(selected))
.then((ds: DataSet) => {
this.setState(
{
detailsStatus: LoadingStatus.LOADED,
data: ds,
},
() => this.resolveWikiDataFor(selected, ds)
);
})
.catch(() => this.setState({ detailsStatus: LoadingStatus.ERROR }));
}
/**
* Checks if the selected object is linked to a WikiData object and makes a request to the WikiData endpoint if so. The returned data is added to the loaded graph.
*
* @param selected the uri of the object to load details for
* @param graph a graph which contains details for the selected object
*/
private resolveWikiDataFor(selected: string, { graph }: DataSet): void {
if (
!graph?.hasNode(selected) ||
!graph?.getNodeAttribute(selected, WIKIDATA_JOIN_ATTRIBUTE)
) {
// no join information is available to base a wikidata query on
this.setStatusOfWikiDataRequest(LoadingStatus.SKIPPED);
return;
}
this.setStatusOfWikiDataRequest(LoadingStatus.PENDING);
const sameAs = graph?.getNodeAttribute(selected, WIKIDATA_JOIN_ATTRIBUTE);
this.wikidataDataSource
.addInformation(graph, wikidataQuery(selected, sameAs))
.then((ds) =>
this.setState({
wikidataStatus: LoadingStatus.LOADED,
data: ds,
})
)
.catch(() => this.setStatusOfWikiDataRequest(LoadingStatus.ERROR));
}
/**
* Updates the progress of the wikidata request
*
* @param wikidataStatus the new status
*/
private setStatusOfWikiDataRequest(wikidataStatus: LoadingStatus): void {
this.setState({
wikidataStatus,
});
}
/**
* Show the actual detail view with an additional loading bar
* @returns page section for the details
*/
public override render(): JSX.Element {
return (
<div className="bg-white pt-4">
<LoadingBar steps={this.currentProgress()}></LoadingBar>
<div className="max-w-7xl mx-auto px-4 py-6 sm:px-0">
{this.state.data ? (
<WrappedDetailView
data={this.state.data}
selectedObject={this.props.selectedObject}
onSelect={this.props.onSelect}
></WrappedDetailView>
) : (
<div className="px-4 py-5 sm:p-6">
<p>Loading details of</p>
<h3 className="font-bold">{this.props.selectedObject}</h3>
</div>
)}
</div>
</div>
);
}
/**
* Converts the loading progress from the state to a list supported by the progress bar component.
*
* @returns list of steps to be passed to the progress bar component
*/
private currentProgress(): Step[] {
return [
{
name: 'Graph Data',
width: 'w-1/6',
status: LoadingStatus.LOADED,
},
{
name: 'All Details',
width: 'w-3/6',
status: this.state.detailsStatus,
},
{
name: 'WikiData.org',
width: 'w-2/6',
status: this.state.wikidataStatus,
},
];
}
}
export default DetailView;
|
load 'affine_root_system.rb'
load 'utility.rb'
require 'set'
=begin
Let's explore the world of affine root systems! (・∀・)
=end
type = 'B'
l = 4
# Generate the affine root system R of type B_4^{(1)}
rsys = Affine_root_system.new(type, l)
# Print all the positive roots in the finite root subsystem of type B_4 spanned by a_1, ..., a_l,
# where a_i is the i-th simple root. We follow the assignment of indices as in Kac's textbook.
puts 'List of positive roots in the finite root system of type B_4'
rsys.print_roots(rsys.associated_roots(rsys.w0))
puts
# The roots which are congruent to simple roots modulo the action of the Weyl group
# is called 'real'. The roots which are not real is called 'imaginary'.
# Print the null root, D := a_0 + a_1 + 2*a_2 + 2*a_3 + 2*a_4.
# It is known that every imaginary root in R is of the form m*D (m: nonzero integer)
puts 'The null root:'
print 'D = '
for i in 0..l do
if rsys.delta[i] > 0 then
if rsys.delta[i] > 1 then
print rsys.delta[i].to_s + '*'
end
print 'a_' + i.to_s
end
if i < l then
print ' + '
else
puts
end
end
puts
# Then, every real root in the root system R is of the form m*D + a,
# where m is an integer and a is a root in the finite root system of type B_4
# The null root is fixed by all the simple reflections
puts 'The action of simple reflection on the null root D'
for i in 0..l do
b = rsys.action([i], rsys.delta)
puts 's_' + i.to_s + '(D) = ' + rsys.root2str(b)
end
puts
wstr = "02431231402123"
puts 'w := ' + wstr + ' (size: ' + wstr.size.to_s + ')'
w = str2w(wstr)
puts 'The action of w:'
rsys.action_underlying(w)
puts
# The length of an element w of the Weyl group is
# the shortest length k of expression of the form w = s_{i_1} s_{i_2} ... s_{i_k}.
# It coincide with the number of positive roots which are sent to negative roots by w.
# If w(alpha) = m*D + beta (beta: positive),
# then w reverse the sign of positive roots n*D + alpha to negative for n = 0, 1, ..., -m-1 (thus -m roots)
# and n*D - alpha for n = 1, 2, ..., m (thus m roots)
# and thus w reverse in total |m| roots.
# In the same way,
# if w(alpha) = m*D - beta (beta: positive),
# then w reverse the sign of positive roots n*D + alpha to negative for n = 0, 1, ..., -m (thus -m+1 roots)
# and n*D - alpha for n = 1, 2, ..., m-1 (thus m-1 roots)
# and thus w reverse in total |m-1| roots.
# Please rest easy, you can compute the length of w as following:
puts 'The length of w = ' + rsys.length(w).to_s
# You can get reduced expression:
wred = rsys.reduce(w)
puts 'w = ' + wred.join + ' (reduced)'
puts
# When w = s_{i_1} s_{i_2} ... s_{i_k} is reduced, the set of positive roots
# \Phi(w) := w\Delta_- \cap \Delta_+ = {s_{i_1} s_{i_2} ... s_{i_{m-1}} (\alpha_m) | m = 1, 2, ..., k}
# is important set in the theory of convex orders.
# By the way, by definition, \Phi(w^{-1}) = w^{-1}\Delta_- \cap \Delta_+
# coincide with the set of positive roots which is reversed by w.
puts 'The positive roots reversed by w:'
rsys.print_roots(rsys.associated_roots(wred.reverse))
# Note: w^{-1} = w.reverse since the order of simple reflection s_i is 2.
|
<article class="container character">
<ng-container *ngIf="canUpdate">
<div class="character__edit-container">
<a [routerLink]="updateUrl">
<app-button
[icon]="'pencil'"
[type]="'SECONDARY'"
></app-button>
</a>
</div>
</ng-container>
<!-- Heading -->
<div class="row">
<h1 class="col-12 character__heading">
<ng-container *ngIf="character.title">
{{ character.title }} -
</ng-container>
{{ character.name }}
<ng-container *ngIf="!character.alive">
(†)
</ng-container>
</h1>
<div class="col-12 character__subheading">
<!-- Organization -->
<h5>
<ng-container *ngIf="character.gender !=='Other'">
{{ character.gender }}
</ng-container>
{{ character.race }}
{{ playerClasses }}
</h5>
<ng-container *ngIf="organizations.length > 0">
<ng-container *ngFor="let entry of organizations; let i = index">
<h5 class="col-12">
{{ entry.organization.role }} of
<a [routerLink]="entry.link">
<strong>{{ entry.organization.name }}</strong>
</a>
</h5>
</ng-container>
</ng-container>
<!-- Current Location -->
<ng-container *ngIf="character.current_location_details">
<div class="col-12">
Last known location:
<a [routerLink]="locationUrl">
<strong> {{ character.current_location_details.name }} </strong>
</a>
</div>
</ng-container>
</div>
</div>
<div class="character__images">
<!-- Image Gallery -->
<app-image-carousel-card
[images]="character.images ?? []"
[serverUrl]="serverUrl"
[serverModel]="imageServerModel"
[canUpdate]="canUpdate"
[canCreate]="canCreate"
[canDelete]="canDelete"
(createImage)="createImage.emit($event)"
(deleteImage)="deleteImage.emit($event)"
(updateImage)="updateImage.emit($event)"
></app-image-carousel-card>
</div>
<!-- Quote -->
<div class="character__quote">
<app-quote-field
[quote]="characterQuote"
[character]="character"
[campaignCharacters]="campaignCharacters"
[serverModel]="quoteServerModel"
[canUpdate]="canUpdate"
[canCreate]="canCreate"
[canDelete]="canDelete"
(refreshQuote)="refreshQuote.emit($event)"
(quoteUpdate)="quoteUpdate.emit($event)"
(quoteCreate)="quoteCreate.emit($event)"
(quoteDelete)="quoteDelete.emit($event)"
(connectionCreate)="quoteConnectionCreate.emit($event)"
(connectionDelete)="quoteConnectionDelete.emit($event)"
></app-quote-field>
</div>
<div class="character__description">
<h4> Description </h4>
<app-html-text
[text]="character.description"
></app-html-text>
</div>
<div class="character__items">
<app-list
[heading]="'Items of Note'"
[entries]="characterItems"
[enableCreate]="canCreate"
[emptyListText]="character.name + ' has no significant items.'"
(create)="routeToItem()"
></app-list>
</div>
<div class="row">
<h4 class="col mb-0">
<app-info-circle-tooltip
[text]="(character.encounters?.length ?? 0) + ' Encounters'"
[tooltip]="'List of all encounters with ' + character.name + '. Starts with the most recent encounter and ends with the latest.'"
></app-info-circle-tooltip>
</h4>
<app-encounter-accordion
[encounters]="character.encounters ?? []"
[campaignCharacters]="campaignCharacters"
[serverModel]="encounterServerModel"
[canUpdate]="canUpdate"
[canCreate]="canCreate"
[canDelete]="canDelete"
(connectionCreate)="encounterConnectionCreate.emit($event)"
(connectionDelete)="encounterConnectionDelete.emit($event)"
(encounterDelete)="encounterDelete.emit($event)"
(encounterUpdate)="encounterUpdate.emit($event)"
></app-encounter-accordion>
</div>
<app-article-footer
[buttonLink]="overviewUrl"
[buttonLabel]="'Back to Characters'"
[showDelete]="canDelete"
[deleteMessage]="'Delete ' + character.name + '?'"
(delete)="characterDelete.emit(character)"
></app-article-footer>
</article>
|
import { Inject, Injectable, Logger } from '@nestjs/common';
import { ImageInfoService } from '@haus/api-common/image-info/services/image-info/image-info.service';
import { ModelInfoService } from '@haus/api-common/model-info/services/model-info/model-info.service';
import { ShopItemRepo } from '@haus/db-common/shop-item/repo/shop-item.repo';
import { ImageInfoRespDto, ModelInfoRespDto, PaginatedRequestDto, ShopItemDto } from "@printhaus/common";
import { Mapper } from '@automapper/core';
import { ShopItem } from '@haus/db-common/shop-item/model/shop.item';
import { UserRatingService } from '../user-rating/user-rating.service';
import { InjectMapper } from '@automapper/nestjs';
import { Types } from 'mongoose';
import { PrintMaterialService } from '../../../printing/services/print-material/print-material.service';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
@Injectable()
export class ShopItemService {
private SHOP_ITEM_TTL_MS = 1000 * 60 * 60;
private MODEL_INFO_URL_TTL_MS = 1000 * 60 * 60;
private MODEL_INFO_CACHE_TTL_MS = 1000 * 60 * 59;
private logger = new Logger(ShopItemService.name);
constructor(
private readonly shopItemRepo: ShopItemRepo,
private readonly imageInfoService: ImageInfoService,
private readonly modelInfoService: ModelInfoService,
private readonly ratingService: UserRatingService,
private readonly materialService: PrintMaterialService,
@InjectMapper() private readonly mapper: Mapper,
@Inject(CACHE_MANAGER) private cacheManager: Cache
) {}
public async getShopItemList(pagination: PaginatedRequestDto): Promise<ShopItemDto[]> {
const cacheKey = `shopItems-${JSON.stringify(pagination)}`;
const cachedData = await this.cacheManager.get<ShopItemDto[]>(cacheKey);
if (cachedData) {
return cachedData;
}
const shopItems = await this.shopItemRepo.findAll(pagination);
let shopItemDtoList: ShopItemDto[] = [];
for (let shopItem of shopItems) {
const mainPhoto: ImageInfoRespDto = await this.imageInfoService.getImageInfo(
new Types.ObjectId(shopItem.mainPhoto.id)
);
const galleryPhotos: ImageInfoRespDto[] = await Promise.all(
shopItem.galleryPhotos.map((photo) => {
return this.imageInfoService.getImageInfo(new Types.ObjectId(photo.id));
})
);
const ratingResult = await this.ratingService.getRating(new Types.ObjectId(shopItem.id));
const materialDto = await this.materialService.getMaterial(new Types.ObjectId(shopItem.material.id));
const shopItemDto = this.mapper.map(shopItem, ShopItem, ShopItemDto);
shopItemDto.mainPhoto = mainPhoto;
shopItemDto.galleryPhotos = galleryPhotos;
shopItemDto.reviewValue = ratingResult.averageRating;
shopItemDto.reviewCount = ratingResult.count;
shopItemDto.material = materialDto;
shopItemDtoList.push(shopItemDto);
}
this.cacheManager.set(cacheKey, shopItemDtoList, this.SHOP_ITEM_TTL_MS).catch((err) => this.logger.error(err));
return shopItemDtoList;
}
public async getShopItemCount(): Promise<number> {
return this.shopItemRepo.count();
}
public async getShopItemModelUrl(id: string | Types.ObjectId): Promise<ModelInfoRespDto> {
const cacheKey = `shopItemModelUrl-${id}`;
const cachedData = await this.cacheManager.get<ModelInfoRespDto>(cacheKey);
if (cachedData) {
return cachedData;
}
const modelInfoDto = await this.modelInfoService.getModelSignedUrl(
await this.shopItemRepo.getModelInfoId(id),
this.MODEL_INFO_URL_TTL_MS / 1000
);
this.cacheManager.set(cacheKey, modelInfoDto, this.MODEL_INFO_CACHE_TTL_MS).catch((err) => this.logger.error(err));
return modelInfoDto;
}
}
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<title>cyc-editor-window</title>
<script src="../node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
<script src="../node_modules/wct-browser-legacy/browser.js"></script>
<script type="module" src="../dist/cyc-editor-window/cyc-editor-window.js"></script>
</head>
<body>
<test-fixture id="default">
<template>
<cyc-editor-window></cyc-editor-window>
</template>
</test-fixture>
<script>
suite('<cyc-editor-window>', () => {
let el;
setup(async() => {
el = fixture('default');
await el.updateComplete;
});
// Integration tests
// checks that own properties are properly bound to other components
suite('Components configuration', () => {
test('setting themeName sets themeName to <cyc-editor-titlebar>', async() => {
const $titlebar = el.shadowRoot.querySelector('.title-bar');
el.themeName = 'any';
await el.updateComplete;
assert.equal($titlebar.themeName, el.themeName);
});
test('setting projectFiles sets files to <cyc-editor-sidebar>', () => {
const $sidebar = el.shadowRoot.querySelector('.sidebar');
assert.deepEqual($sidebar.files, el.projectFiles);
});
test('<cyc-editor-content> fileType is set as the type of the selected item in projectFiles', () => {
const $content = el.shadowRoot.querySelector('.editor');
const selectedFile = el.projectFiles.filter((file) => file.selected)[0];
assert.equal($content.fileType, selectedFile.type);
});
});
});
</script>
</body>
</html>
|
import { Component } from '@angular/core';
import { ApiService } from '../../service/api.service';
import { DatePipe } from '@angular/common';
@Component({
selector: 'app-listarjugadores',
templateUrl: './listarjugadores.component.html',
styleUrls: ['./listarjugadores.component.css']
})
export class ListarjugadoresComponent {
rendimiento: any[] = [];
jugadores: any[] = [];
mostrarPopupFlag: boolean = false;
constructor(private api: ApiService, private datePipe: DatePipe) {}
ngOnInit(): void {
this.listarjugadores();
}
// Función para mostrar el popup
mostrarPopup(JugadorID: number) {
this.mostrarPopupFlag = true;
this.api.getRendimiento(JugadorID).subscribe(
data => {
this.rendimiento = this.transformarArrayRendimiento(data);
},
error => {
console.error('Error al obtener la lista de rendimiento.', error);
}
);
}
// Función para cerrar el popup
cerrarPopup() {
this.mostrarPopupFlag = false;
}
listarjugadores() {
this.api.getJugadores().subscribe(
data => {
this.jugadores = this.transformarArray(data);
},
error => {
console.error('Error al obtener la lista de jugadores.', error);
}
);
}
transformarArray(array: any[]): any[] {
return array.map(jugador => {
return {
JugadorID: jugador[0],
NombreJugador: jugador[1],
EquipoID: jugador[2]
};
});
}
transformarArrayRendimiento(array: any[]): any[] {
return array.map(rendimiento => {
return {
FechaRendimiento: this.formatFecha(rendimiento[0]),
JugadorID: rendimiento[1],
RendimientoID: rendimiento[2]
};
});
}
private formatFecha(fecha: any): string {
if (!fecha) {
return ''; // O cualquier valor predeterminado que desees si fecha es undefined
}
// Formatear la fecha directamente en TypeScript
const dateObj = new Date(fecha);
const year = dateObj.getFullYear();
const month = (dateObj.getMonth() + 1).toString().padStart(2, '0');
const day = dateObj.getDate().toString().padStart(2, '0');
return `${year}-${month}-${day}`;
}
}
|
"use client";
import React from "react";
import { motion } from "framer-motion";
import Image from "next/image";
import Link from "next/link";
import { TypeAnimation } from "react-type-animation";
export default function IntroSection() {
return (
<section className="lg:py-16">
<div className="grid grid-cols-1 sm:grid-cols-12">
<motion.div
initial={{ opacity: 0, scale: 0.5 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 1 }}
className="col-span-8 place-self-center text-center sm:text-left justify-self-start"
>
<h1 className="mb-4 text-4xl sm:text-5xl lg:text-8xl lg:leading-normal font-extrabold">
<span className="text-transparent bg-clip-text bg-gradient-to-r from-indigo-800 from-40% to-blue-400">
Hello, I'm
</span>
<br></br>
<TypeAnimation
sequence={[
"Minh Khanh Dao",
1000,
"FE Developer",
1000,
"ReactJS Developer",
1000,
]}
wrapper="span"
speed={50}
repeat={Infinity}
/>
</h1>
<p className="text-[#ADB7BE] text-base sm:text-lg mb-6 lg:text-xl">
Welcome to my portfolio, the one is using plenty of technologies such as:
React, NextJS 14, Tailwind CSS, Shadcn UI, Vercel, Framer Motion.
</p>
<Link
href="https://drive.google.com/file/d/1us41ysHM7M2Z2k6HLMh0YQXc_eWhLtcA/view?usp=drive_link"
className="px-1 inline-block py-1 w-full sm:w-fit rounded-full text-white mt-3 hover:bg-blue-100"
target="_blank"
download
>
<span className="block bg-gradient-to-r from-indigo-800 from-40% to-blue-400 rounded-full px-5 py-2">
Download CV
</span>
</Link>
</motion.div>
<motion.div
initial={{ opacity: 0, scale: 0.5 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.5 }}
className="col-span-4 place-self-center mt-4 lg:mt-0"
>
<Image
src="/images/avatar.png"
alt="avatar image"
className="rounded-full w-[200px] lg:w-[300px] lg:h-[400px]"
width={0}
height={0}
sizes="100vw"
priority
/>
</motion.div>
</div>
</section>
);
}
|
/*
* @Author: Daniel Maurelle
* @Email: daniel.maurelle@gmail.com
* Youtube: https://youtube.com/playlist?list=PLDqCEJxpkYKCzZSwAz-2PpzcwMDY11NGp&si=HRSvwoUxsEBtFsfI
* @Date: 12-18-2023 18:20:55
* @Description: 1-Sample code basic banking system.
*
* MIT License
*
* Copyright 2023 Daniel Maurelle
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdio.h>
int varMyvar = 10;
int main() {
int accountBalance = 1000; // Initial balance in the account
int *balancePtr = &accountBalance; // Pointer to the account balance
int transactionAmount; // Amount for deposit or withdrawal
int transactionType; // 1 for deposit, 2 for withdrawal
printf("Welcome to the Simple Banking System\n");
printf("Initial Account Balance: $%d\n", accountBalance);
// Ask the user for the transaction type
printf("Choose transaction type (1 for Deposit, 2 for Withdrawal): ");
scanf("%d", &transactionType);
// Ask for the amount
printf("Enter the amount: $");
scanf("%d", &transactionAmount);
if (transactionType == 1) { // Deposit
printf("Depositing $%d to account...\n", transactionAmount);
*balancePtr += transactionAmount;
printf("Account Balance after deposit: $%d\n", accountBalance);
} else if (transactionType == 2) { // Withdrawal
printf("Withdrawing $%d from account...\n", transactionAmount);
if (*balancePtr >= transactionAmount) {
*balancePtr -= transactionAmount;
printf("Account Balance after withdrawal: $%d\n", accountBalance);
} else {
printf("Insufficient funds for withdrawal. Current Balance: $%d\n", accountBalance);
}
} else { // Invalid transaction type
printf("Invalid transaction type selected.\n");
}
return 0;
}
|
import { OpenAI as OpenAIApi } from "openai";
import { Container } from "@sapphire/pieces";
import { ChatInputCommandInteraction, Message } from "discord.js";
import * as process from "process";
const { OPENAI_API_KEY } = process.env;
export default class OpenAI extends OpenAIApi {
private readonly container: Container;
constructor(container: Container) {
super({
apiKey: OPENAI_API_KEY
});
this.container = container;
}
async createChat(prompt: string, userId: string, username: string) {
let systemMessage = "Your name is Kuramisa. You are Stealth's pet fox. Your owner is Stealth. No one can be your owner but Stealth.";
if (userId === "401269337924829186") systemMessage +=
" You are talking to your owner. You do not have to greet him or anything similar. But it is up to you";
else systemMessage += " You are not talking to your owner.";
if (prompt.length === 0) systemMessage += `Greet ${username} and ask if the user needs assistance`;
const completion = await this.chat.completions.create({
messages: [
{
role: "system",
content: systemMessage
},
{
role: "user",
content: prompt
}
],
model: "gpt-3.5-turbo"
});
return completion.choices[0].message?.content;
}
async createImage(prompt: string) {
const completion = await this.images.generate({
prompt
});
return completion.data[0].url;
}
throwError(
error: any,
prompt: string,
interaction?: ChatInputCommandInteraction | null,
message?: Message | null
) {
const { logger } = this.container;
try {
if (error.response) {
logger.error(`Prompt: ${prompt}}`, error.response);
if (interaction) {
if (interaction.guild)
logger.error(`in ${interaction.guild.name}`);
if (interaction.replied) {
interaction.editReply(
error.response.data.error.message
);
} else {
interaction.reply(error.response.data.error.message);
}
}
if (message) {
if (message.guild) logger.error(`in ${message.guild.name}`);
message.reply(error.response.data.error.message);
}
} else {
logger.error(`Prompt: ${prompt}`, error.message);
if (interaction) {
if (interaction.guild)
logger.error(`in ${interaction.guild.name}`);
if (interaction.replied) {
interaction.editReply(error.message);
} else {
interaction.reply(error.message);
}
}
if (message) {
if (message.guild) logger.error(`in ${message.guild.name}`);
message.reply(error.message);
}
}
} catch (error) {
logger.error(error);
}
}
}
|
const socket = io();
const myFace = document.getElementById("myFace");
const muteBtn = document.getElementById("audio");
const cameraBtn = document.getElementById("camera");
const camerasSelect = document.getElementById("cameras");
const call = document.getElementById("call");
let myStream;
let muted = false;
let cameraOff = false;
let roomName;
let myPeerConnection;
let myDataChannel = "";
let messageText;
async function getCameras() {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
const cameras = devices.filter((device) => device.kind === "videoinput");
const currentCamera = myStream.getAudioTracks()[0];
cameras.forEach((camera) => {
const option = document.createElement("option");
option.value = camera.deviceId;
option.innerText = camera.label;
if (currentCamera.label === camera.label) {
option.selected = true;
}
camerasSelect.appendChild(option);
});
} catch (e) {
console.log(e);
}
}
async function getMedia(deviceId) {
const initialConstrains = {
audio: true,
video: { facingMode: "user" },
};
const cameraConstrains = {
audio: true,
video: { deviceId: { exact: deviceId } },
};
try {
myStream = await navigator.mediaDevices.getUserMedia(
deviceId ? cameraConstrains : initialConstrains
);
myFace.srcObject = myStream;
if (!deviceId) {
await getCameras();
}
} catch (e) {
console.log(e);
}
}
function handleMuteClick() {
myStream
.getAudioTracks()
.forEach((track) => (track.enabled = !track.enabled));
if (!muted) {
muteBtn.classList.remove("btnColor");
muted = true;
} else {
muteBtn.classList.add("btnColor");
muted = false;
}
}
function handleCameraClick() {
myStream
.getVideoTracks()
.forEach((track) => (track.enabled = !track.enabled));
if (cameraOff) {
cameraBtn.classList.add("btnColor");
cameraOff = false;
} else {
cameraBtn.classList.remove("btnColor");
cameraOff = true;
}
}
async function handleCameraChange() {
await getMedia(camerasSelect.value);
if (myPeerConnection) {
const videoTrack = myStream.getVideoTracks()[0];
const videoSender = myPeerConnection
.getSenders()
.find((sender) => sender.track.kind === "video");
videoSender.replaceTrack(videoTrack);
}
}
muteBtn.addEventListener("click", handleMuteClick);
cameraBtn.addEventListener("click", handleCameraClick);
camerasSelect.addEventListener("input", handleCameraChange);
// Welcome Form (join a room)
const welcome = document.getElementById("welcome");
const welcomeForm = welcome.querySelector("form");
async function initcall() {
welcome.classList.add("hidden");
call.classList.remove("hidden");
await getMedia();
makeConnection();
}
async function handleWelcomeSubmit(event) {
event.preventDefault();
const input = welcomeForm.querySelector("input");
await initcall();
socket.emit("join_room", input.value);
roomName = input.value;
input.value = "";
}
// Send Message code
const message = document.getElementById("message");
const messageForm = message.querySelector("form");
const messageList = message.querySelector("ul");
function sendPeersMessage(msg) {
const li = document.createElement("li");
const div = document.createElement("div");
const span = document.createElement("span");
div.className = "divMsg";
span.className = "spanMsg";
const ul = message.querySelector("ul");
if (msg.data.length > 31) {
div.innerText = `Peer: ${msg.data}`;
li.appendChild(div);
} else {
span.innerText = `Peer: ${msg.data}`;
li.appendChild(span);
}
ul.appendChild(li);
if (messageList.scrollHeight >= message.clientHeight - 70) {
messageList.scrollTop = messageList.scrollHeight;
}
}
function sendMyMessage(msg) {
const li = document.createElement("li");
const div = document.createElement("div");
const span = document.createElement("span");
div.className = "divMsg";
span.className = "spanMsg";
const ul = message.querySelector("ul");
if (msg.length > 31) {
div.innerText = `You: ${msg}`;
li.appendChild(div);
} else {
span.innerText = `You: ${msg}`;
li.appendChild(span);
}
ul.appendChild(li);
if (messageList.scrollHeight >= message.clientHeight - 70) {
messageList.scrollTop = messageList.scrollHeight;
}
}
function handleMessageSubmit(event) {
event.preventDefault();
const input = message.querySelector("input");
messageText = input.value;
sendMyMessage(messageText);
if (myDataChannel !== "") {
myDataChannel.send(messageText);
}
input.value = "";
if (messageList.scrollHeight >= message.clientHeight - 70) {
messageList.scrollTop = messageList.scrollHeight;
}
}
welcomeForm.addEventListener("submit", handleWelcomeSubmit);
messageForm.addEventListener("submit", handleMessageSubmit);
// Socket Code
socket.on("welcome", async () => {
myDataChannel = myPeerConnection.createDataChannel("chat");
myDataChannel.addEventListener("message", sendPeersMessage);
console.log("made data channel");
const offer = await myPeerConnection.createOffer();
myPeerConnection.setLocalDescription(offer);
socket.emit("offer", offer, roomName);
});
socket.on("offer", async (offer) => {
myPeerConnection.addEventListener("datachannel", (event) => {
myDataChannel = event.channel;
myDataChannel.addEventListener("message", sendPeersMessage);
});
myPeerConnection.setRemoteDescription(offer);
const answer = await myPeerConnection.createAnswer();
myPeerConnection.setLocalDescription(answer);
socket.emit("answer", answer, roomName);
});
socket.on("answer", (answer) => {
myPeerConnection.setRemoteDescription(answer);
});
socket.on("ice", (ice) => {
console.log("received candidate");
myPeerConnection.addIceCandidate(ice);
});
// RTC Code
function makeConnection() {
myPeerConnection = new RTCPeerConnection({
iceServers: [
{
urls: [
"stun:stun.l.google.com:19302",
"stun:stun1.l.google.com:19302",
"stun:stun2.l.google.com:19302",
"stun:stun3.l.google.com:19302",
"stun:stun4.l.google.com:19302",
],
},
],
});
myPeerConnection.addEventListener("icecandidate", handleIce);
myPeerConnection.addEventListener("addstream", handleAddStream);
myPeerConnection.addEventListener("track", handleTrack);
myStream
.getTracks()
.forEach((track) => myPeerConnection.addTrack(track, myStream));
}
function handleIce(data) {
console.log("send candidate");
socket.emit("ice", data.candidate, roomName);
}
function handleAddStream(data) {
const peersFace = document.getElementById("peersFace");
peersFace.srcObject = data.stream;
}
// for Safari
function handleTrack(data) {
const peersFace = document.getElementById("peersFace");
peersFace.srcObject = data.streams[0];
}
socket.on("disconnection", () => {
const peersFace = document.getElementById("peersFace");
myDataChannel = "";
peersFace.srcObject = null;
});
|
//Arquivo de tratativa de erro
//Descobre se é fastfy ou express e continuar a aplicação
import { Catch, HttpException, ExceptionFilter, ArgumentsHost, HttpStatus } from "@nestjs/common";
import { AbstractHttpAdapter, HttpAdapterHost } from "@nestjs/core";
@Catch(HttpException)
export class ExceptionFilterHttp implements ExceptionFilter {
private httpAdapter: AbstractHttpAdapter;
constructor(adapterHost: HttpAdapterHost){
this.httpAdapter = adapterHost.httpAdapter;
}
catch(exception: Error, host: ArgumentsHost) {
const context = host.switchToHttp();
const request = context.getRequest();
const response = context.getResponse();
const { status, body } = exception instanceof HttpException ?
{
status: exception.getStatus(),
body: exception.getResponse()
}
:
{
status: HttpStatus.INTERNAL_SERVER_ERROR,
body: {
statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
timestamp: new Date().toISOString(),
message: exception.message,
path: request.path
}
};
this.httpAdapter.reply(response, body, status);
}
}
|
package org.patterns.generative;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
class SingletonWorker implements Runnable {
private final int threadNumber;
public SingletonWorker(int threadNumber) {
this.threadNumber = threadNumber;
}
@Override
public void run() {
Singleton singleton = Singleton.getInstance();
singleton.greetOurselves(threadNumber);
}
}
class SingletonExampleTest {
@Test
void testGetInstance() throws InterruptedException {
ArrayList<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new SingletonWorker(i));
threads.add(thread);
}
threads.forEach(Thread::run);
for (Thread thread: threads) {
thread.join();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.