text
stringlengths 184
4.48M
|
---|
package Q17_07_Baby_Names
import scala.collection.mutable
class NameSet(name: String, freq: Int) {
private val names = mutable.Set(name)
private var frequency = freq
private val rootName = name
def getNames: Set[String] = names.toSet
def getRootName: String = rootName
def copyNamesWithFrequency(more: Set[String], freq: Int): Unit = {
names ++= more
frequency += freq
}
def getFrequency: Int = frequency
def size: Int = names.size
}
|
# frozen_string_literal: true
# Migration responsible for creating a table with activities
class CreateActivities < ActiveRecord::Migration[6.1]
def self.up
create_table :activities do |t|
t.belongs_to :trackable, polymorphic: true
t.belongs_to :owner, polymorphic: true
t.string :key
t.jsonb :parameters
t.belongs_to :recipient, polymorphic: true
t.datetime :deleted_at
t.timestamps
end
add_index :activities, %i[trackable_id trackable_type]
add_index :activities, %i[owner_id owner_type]
add_index :activities, %i[recipient_id recipient_type]
end
# Drop table
def self.down
drop_table :activities
end
end
|
/**
*
*/
public class Morse {
// NUM_CHARS field stores no of characters allowed
public int NUM_CHARS = 40;
// original stores the original String
private String original;
// mcode stores the String converted to morseCode
private String mcode;
// regular char[] array stores values for characters
private char[] regular = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
// morse String[] array stores value for regular array's corresponding
// morse values
private String[] morse = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---",
"...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----" };
/**
* Constructor Morse takes String as an argument
* converts it into an array called array of Strings by splitiing the spaces
* between words
* outer for loop converts every element of this array
* into an another char Array named input1 and then
* every element for that char Array is converted
* into morse code using the method
* toMorse() by looping through each element
* using inner for loop and morse code is added into an empty
* String s which was initialised as ""
* and then s is assigned to field mcode
*
* @param input
*/
public Morse(String input) {
String s = "";
String[] array = input.split(" ");
for (int j = 0; j < array.length; j++) {
char[] input1 = array[j].toCharArray();
if (input1.length <= this.NUM_CHARS) {
for (int i = 0; i < input1.length; i++) {
s += toMorse(input1[i]) + "\n";
}
s += "\n";
} else {
System.out.println("Input length must be upto 40 characters.");
}
}
mcode = s;
}
/**
* toMorse takes in characters
* and returns the corresponding MorseCode
*
* @param h is a character
* @return output as morse code for the character entered
*/
public String toMorse(char h) {
char d = Character.toUpperCase(h);
boolean found = false;
int i = 0;
int index = 0;
String output = " ";
while (!found && i < regular.length) {
if (d == regular[i]) {
found = true;
index = i;
}
i++;
}
output = morse[index];
return output;
}
/**
* getMorseCode returns mcode
*
* @return mcode as String
*/
public String getMorseCode() {
return mcode;
}
/**
* getOriginal returns the original
* String entered by the user
*
* @return original
*/
public String getOriginal() {
return original;
}
/**
* toString() returns mcode
* whenever an object of Morse class is printed out
*/
public String toString() {
return mcode;
}
}
|
import React, {useState, useEffect, useRef} from "react";
import { View, TextInput, KeyboardAvoidingView, Platform } from "react-native";
import Checkbox from '../Checkbox';
interface ToDoItemProps {
todo: {
id: string,
content: string,
isCompleted: boolean,
},
onSubmit: () => void,
}
const ToDoItem = ({todo, onSubmit}: ToDoItemProps) => {
const [isChecked, setIsChecked] = useState(false);
const [content, setContent] = useState('');
const input = useRef(null)
useEffect (() => {
if(!todo) {return}
setIsChecked(todo.isCompleted)
setContent(todo.content)
},[todo])
useEffect (() => {
if(input.current){
setTimeout(() => {
input?.current?.focus()
}, 0)
}
},[input])
const onKeyPress = ({nativeEvent}) => {
if(nativeEvent.key === 'Backspace' && content === '' ) {
console.warn('Delete item')
}
}
return (
<View style={{ flexDirection: "row", alignItems: "center", marginVertical: 3 }}>
{/* Checkbox */}
<Checkbox
isChecked={isChecked}
onPress={() => {
setIsChecked(!isChecked);
}}
/>
{/* Text Input */}
<TextInput
ref={input}
value={content}
blurOnSubmit={true}
onSubmitEditing={onSubmit}
onKeyPress={onKeyPress}
onChangeText={setContent}
multiline={true}
style={{
flex: 1,
fontSize: 18,
color: "black",
marginLeft: 12,
}}
/>
</View>
);
};
export default ToDoItem;
|
import { getAuth, onAuthStateChanged, signOut } from "firebase/auth";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Link, useNavigate } from "react-router-dom";
import { addUser, clearUser } from "../../../redux/authReducer";
import AddData from "../Components/AddData";
import ReadData from "../Components/ReadData";
import Parallax from "../../Parallax/Parallax";
const HomePage = () => {
const { email, id, token } = useSelector((data) => data.auth);
const auth = getAuth();
const navigate = useNavigate();
const dispatch = useDispatch();
useEffect(() => {
onAuthStateChanged(auth, (user) => {
if (user) {
dispatch(
addUser({
email: user.email,
id: user.uid,
token: user.refreshToken,
})
);
} else {
dispatch(clearUser());
navigate("/sign-in");
}
});
});
return (
<div>
<button onClick={() => signOut(auth)}>Exit</button>
<Link to={"payment"}>
<button>Payment</button>
</Link>
<p>Hello {email}</p>
<AddData />
<Parallax />
<ReadData />
</div>
);
};
export default HomePage;
|
import React from 'react'
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'
function Create() {
const [user,setUser]=useState({
name:"",
email:"",
mobile:"",
address:""
})
const navigate=useNavigate()
const readInput=(event)=>{
console.log(`input=`,event.target.value)
setUser({...user,[event.target.name]:event.target.value})
}
const submithandler=async (e)=>{
e.preventDefault()
let userData=localStorage.getItem('users') ? JSON.parse(localStorage.getItem("users")):[]
const extemail=userData.find(item=>item.email === user.email )
const extmobile=userData.find(item=>item.mobile === user.mobile )
if(extemail){
toast.warning(`${user.email} email already exists`)
}else if(extmobile){
toast.warning(`${user.mobile} number is already present`)
} else{
let newuser={
id:Math.floor(Math.random()*100000),
...user
}
userData.push(newuser)
localStorage.setItem("users",JSON.stringify(userData))
toast.success("New user added successfully")
navigate(`/`)
}
}
return (
<div>
<div className="container">
<div className="row">
<div className="col-md-12 text-center">
<h3 className="display-3 text-primary">Create User</h3>
</div>
</div>
<div className="row">
<div className="col-md-6 col-lg-6 col-sm-12 offset-lg-3">
<div className="card">
<div className="card-body">
<form onSubmit={submithandler}>
<div className="form-group mt-2">
<label htmlFor="name">NAME</label>
<input type="text" name="name" value={user.name} onChange={readInput} id="name" className='form-control' required/>
</div>
<div className='form-group mt-2'>
<label htmlFor="email">EMAIL</label>
<input type="email" name="email" id="email" value={user.email} onChange={readInput} className="form-control" required />
</div>
<div className="form-group mt-2">
<label htmlFor="mobile">MOBILE</label>
<input type="number" name="mobile" id="mobile" value={user.mobile} onChange={readInput} className='form-control' />
</div>
<div className="form-group mt-2">
<label htmlFor="address">Address</label>
<textarea name="address" id="address" cols="30" value={user.address} onChange={readInput} rows="6" className='form-control' required></textarea>
</div>
<div className="form-group mt-2">
<input type="submit" value="Add new user" className='btn btn-primary'/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
export default Create
|
var budgetController = (function(){
var Expense = function(id, description, value){
this.id = id;
this.description = description;
this.value = value;
this.percentage = -1;
};
Expense.prototype.calcPercentage = function(totalIncome){
if(totalIncome > 0){
this.percentage = Math.round((this.value/totalIncome) * 100);
}else{
this.percentage = -1;
}
};
Expense.prototype.getPercentage = function(){
return this.percentage;
};
var Income = function(id, description, value){
this.id = id;
this.description = description;
this.value = value;
};
var calculateTotal = function(type){
var sum = 0;
data.allItems[type].forEach(function(item){
sum+=item.value;
});
data.totals[type] = sum;
};
var data = {
allItems : {
exp: [],
inc: []
},
totals: {
exp: 0,
inc: 0
},
budget:0,
percentage:-1
};
return {
addItem: function(type, des, val){
var newItem, ID;
if(data.allItems[type].length > 0){
ID = data.allItems[type][data.allItems[type].length-1].id + 1;
}else{
ID = 0;
}
if(type === 'exp'){
newItem = new Expense(ID, des, val);
}else if(type === 'inc'){
newItem = new Income(ID, des, val);
}
data.allItems[type].push(newItem);
return newItem;
},
deleteItem: function(type, id){
var ids,index;
ids = data.allItems[type].map(function(item){
return item.id;
});
index = ids.indexOf(id);
if(index !== -1){
data.allItems[type].splice(index,1);
}
},
calculateBudget: function(){
calculateTotal('inc');
calculateTotal('exp');
data.budget = data.totals.inc - data.totals.exp;
if(data.totals.inc > 0){
data.percentage = Math.round((data.totals.exp / data.totals.inc) * 100);
}else{
data.percentage = -1;
}
},
getBudget: function(){
return{
budget: data.budget,
totalIncome: data.totals.inc,
totalExpenses: data.totals.exp,
percentage: data.percentage
};
},
testing: function(){
console.log(data);
},
calculatePercentages: function(){
data.allItems.exp.forEach(function(item){
item.calcPercentage(data.totals.inc);
});
},
getPercentages: function(){
var allPerc = data.allItems.exp.map(function(item){
return item.getPercentage();
});
return allPerc;
}
};
})();
var UIController = (function(){
var DOMStrings = {
inputType: '.add__type',
inputDescription: '.add__description',
inputValue: '.add__value',
inputBtn: '.add__btn',
incomeContainer: '.income__list',
expenseContainer: '.expenses__list',
budgetLabel: '.budget__value',
incomeLabel: '.budget__income--value',
expenseLabel: '.budget__expenses--value',
percentageLabel: '.budget__expenses--percentage',
continer: '.container',
expensePercentageLabel: '.item__percentage',
dateLabel: '.budget__title--month'
};
return {
getInput: function(){
return {
type: document.querySelector(DOMStrings.inputType).value,
description: document.querySelector(DOMStrings.inputDescription).value,
value: parseFloat(document.querySelector(DOMStrings.inputValue).value)
};
},
getDOMstrings: function(){
return DOMStrings;
},
addListItem: function(obj,type){
var html, newHtml, element;
if(type === 'inc'){
element = DOMStrings.incomeContainer;
html = '<div class="item clearfix" id="inc-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
}else if(type === 'exp'){
element = DOMStrings.expenseContainer;
html = '<div class="item clearfix" id="exp-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__percentage">21%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
}
newHtml = html.replace('%id%', obj.id);
newHtml = newHtml.replace('%description%', obj.description);
newHtml = newHtml.replace('%value%', obj.value);
document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);
},
deleteListItem: function(selectorID){
var el;
el = document.getElementById(selectorID);
el.parentNode.removeChild(el);
},
displayBudget: function(obj){
document.querySelector(DOMStrings.budgetLabel).textContent = obj.budget;
document.querySelector(DOMStrings.incomeLabel).textContent = obj.totalIncome;
document.querySelector(DOMStrings.expenseLabel).textContent = obj.totalExpenses;
if(obj.percentage > 0){
document.querySelector(DOMStrings.percentageLabel).textContent = obj.percentage + "%";
}else{
document.querySelector(DOMStrings.percentageLabel).textContent = "---";
}
},
displayPercentage: function(percentages){
var fields = document.querySelectorAll(DOMStrings.expensePercentageLabel);
var nodeListForEach = function(list, callback){
for(var i=0; i<list.length; i++)
callback(list[i], i);
};
nodeListForEach(fields, function(item, index){
if(percentages[index] > 0){
item.textContent = percentages[index] + '%';
}else{
item.textContent = '---';
}
});
},
displayMonth: function(){
var now, month, months, year;
now = new Date();
year = now.getFullYear();
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
month = now.getMonth();
document.querySelector(DOMStrings.dateLabel).textContent = months[month] + ' ' + year;
},
clearFields: function(){
var fields, fieldsArr;
fields = document.querySelectorAll(DOMStrings.inputDescription + ', ' + DOMStrings.inputValue);
fieldsArr = Array.prototype.slice.call(fields);
fieldsArr.forEach(function(field){
field.value = "";
});
fieldsArr[0].focus();
}
};
})();
var controller = (function(budgetCtrl, UICtrl){
var setupEventListeners = function(){
//setting event listeners for adding items
var DOM = UICtrl.getDOMstrings();
document.querySelector(DOM.inputBtn).addEventListener('click', ctrlAddItem);
document.addEventListener('keypress', function(event){
if(event.keyCode === 13 || event.which === 13){
ctrlAddItem();
}
});
//setting up an event listener for deleting an item
document.querySelector(DOM.continer).addEventListener('click', ctrlDeleteItem);
};
var budgetUpdate = function(){
//1.Calculate The Budget
budgetCtrl.calculateBudget();
//2.Return the budget
var budget = budgetCtrl.getBudget();
//3.Display the budget on the ui
UICtrl.displayBudget(budget);
};
//updating percentages and adding it to the UI
var updatePercentages = function(){
//1.Calculate Percentages
budgetCtrl.calculatePercentages();
//2.read percentages from the budget controller
var percentages = budgetCtrl.getPercentages();
//3.update the percentages on the ui
UICtrl.displayPercentage(percentages);
};
//deleting an item
var ctrlDeleteItem = function(event){
var itemID, splitID, ID, type;
itemID = event.target.parentNode.parentNode.parentNode.parentNode.id;
if(itemID){
splitID = itemID.split('-');
type = splitID[0];
ID = parseInt(splitID[1]);
//1.Delete item from the data
budgetCtrl.deleteItem(type,ID);
//2.Delete item from the interface
UICtrl.deleteListItem(itemID);
//3.Calculate the updated budget and display
budgetUpdate();
}
};
//adding an item
var ctrlAddItem = function(){
var input, newItem;
//1.Get the input data from UI
input = UICtrl.getInput();
if(input.description !== "" && input.value !== 0 && !isNaN(input.value)){
//2.Add the item to budgetController
newItem = budgetCtrl.addItem(input.type, input.description, input.value);
//3.Display the items on the UI
UICtrl.addListItem(newItem, input.type);
//4.Remove items from the input box
UICtrl.clearFields();
//5.Update Budget
budgetUpdate();
//6.Update Percentages
updatePercentages();
}
};
return{
init: function(){
console.log('Application has started');
UICtrl.displayMonth();
UICtrl.displayBudget({
budget:0,
totalIncome:0,
totalExpenses:0,
percentage:-1
});
setupEventListeners();
}
};
})(budgetController,UIController);
controller.init();
|
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie-edge">
<title>Nota de Venta</title>
<link rel="stylesheet" href="{{ public_path('css/pdf.css') }}">
<style>
@font-face {
font-family: "Roboto";
src: url('{{ storage_path('fonts/Roboto-Light.ttf') }}') format('truetype');
font-weight: 100;
font-style: normal;
}
@font-face {
font-family: "Roboto";
src: url('{{ storage_path('fonts/Roboto-Regular.ttf') }}') format('truetype');
font-weight: 400;
font-style: normal;
}
@font-face {
font-family: "Roboto";
src: url('{{ storage_path('fonts/Roboto-Bold.ttf') }}') format('truetype');
font-weight: 700;
font-style: normal;
}
</style>
</head>
<body>
<div id="header">
<img class="imgHeader" src="{{ public_path('img/logo.png') }}" alt="" width="200px">
<div class="infoHeader">
<h1 class="normal">NOTA DE VENTA </h1>
<h2 class="normal">Nº: {{ $venta->id }}</h2>
<div class="normal"><span class="bold">Fecha: </span>{{ \Carbon\Carbon::parse($venta->created_at)->format('d/m/Y') }}</div>
</div>
</div>
<table class="section">
<tr>
<div class="section">
<div class="section-content">
<div class="section-header normal">Datos del Cliente:</div>
<div class="normal"><span class="bold">Señor (es): </span>{{ $venta->cliente->razon_social }}</div>
<div class="normal"><span class="bold">NIT/C.I: </span>{{ $venta->cliente->nit }}</div>
{{-- telefono --}}
<div class="normal"><span class="bold">Teléfono: </span>{{ $venta->cliente->telefono }}</div>
<div class="normal"><span class="bold">Dirección: </span>{{ $venta->cliente->direccion }}</div>
</div>
</div>
<td width="120"></td>
<td class="section-content">
<div class="section-header normal">Datos de la Empresa:</div>
<div class="normal"><span class="bold">Dirección: </span>Calle Murillo Nº897, esq Sagarnaga</div>
<div class="normal"><span class="bold">Email: </span>[email protected]</div>
<div class="normal"><span class="bold">Celular: </span>76202463 - 74005262</div>
<div class="normal"><span class="bold">NIT: </span>4801118019</div>
</td>
</tr>
</table>
<div class="container">
<table class="items-table">
<tr>
<th>ID</th>
<th>Cantidad</th>
<th>Descripción</th>
<th>U. Medida</th>
<th>Precio</th>
<th>Subtotal</th>
</tr>
@foreach ($data as $item)
<tr>
<td align="center">{{ $item->id }}</td>
<td align="center">{{ number_format($item->cantidad,0) }}</td>
<td>{{ $item->descripcion }}</td>
<td>{{ $item->medida }}</td>
<td align="right">{{ $item->precio }}</td>
<td align="right">{{ number_format($item->precio * $item->cantidad, 2) }}</td>
</tr>
@endforeach
<!-- Agrega una fila para el total justo debajo de la tabla de detalles -->
<tr>
<td colspan="5" align="right"><strong>Total:</strong></td>
<td align="right">{{ number_format($data->sum('total'), 2) }}</td>
</tr>
</table>
</div>
{{-- <div id="footer">
<p class="textFooter">Ofibol.com</p>
</div> --}}
<script type="text/php">
if ( isset($pdf) ) {
$pdf->page_script('
$font = $fontMetrics->get_font("Arial, Helvetica, sans-serif", "normal");
$pdf->text(500, 810, "Página $PAGE_NUM de $PAGE_COUNT", $font, 10);
');
}
</script>
</body>
</html>
|
import React from "react";
import { Link } from "react-router-dom";
import { ReactComponent as Logo } from "../../assets/original.svg";
import {auth} from "../../firebase/firebase.utils";
import {connect} from "react-redux";
import {createStructuredSelector} from "reselect";
import {selectCartHidden} from "../../redux/cart/cart.selectors";
import {selectCurrentUser} from "../../redux/user/user.selectors";
import CartIcon from "../cart-icon/cart-icon.component";
import CardDropdown from "../card-dropdown/card-dropdown.component";
import "./header.style.scss";
const Header = ({currentUser, hidden}) => (
<div className="header">
<Link to="/" className="logo-container">
<Logo className="logo" />
</Link>
<div className="options">
<Link className="option" to="/shop">
SHOP
</Link>
<Link className="option" to="/contact">
CONTACT
</Link>
{
currentUser? <div className="option" onClick={()=>auth.signOut()}> SIGN OUT</div> : <Link className="option" to="/signin"> SIGN IN</Link>
}
<CartIcon/>
</div>
{hidden ? null: <CardDropdown/>}
</div>
);
const mapStateToProps =createStructuredSelector({
currentUser: selectCurrentUser,
hidden: selectCartHidden
})
export default connect(mapStateToProps)(Header);
|
import argparse
import os
from Averagemeter import AverageMeter
import torch
from torch.utils.data import DataLoader
import FID
import cometml
import json
import Pix2pixModel
import warnings
warnings.filterwarnings('ignore')
import CMPfacade3channel, CMPfacade12channel
import Averagemeter
import numpy as np
import random
import CMP3c, CMP12c
def save_json(file, param_save_path, mode):
with open(param_save_path, mode) as outfile:
json.dump(file, outfile, indent=4)
class Opts():
def __init__(self, args):
self.epochs = 200
self.save_data_interval = 10
self.save_image_interval = 10
self.log_interval = 20
self.sample_interval = 10
self.batch_size = 32
self.load_size = 286
self.crop_size = 256
self.cpu = True
self.dataroot = 'CMPFacadeDatasets/facades'
self.output_dir = 'myPix2pixOutput'
self.log_dir = './logs'
self.phase = 'base'
self.lambda_L1 = 100
self.epochs_lr_decay = 0
self.epochs_lr_decay_start = -1
self.path_to_generator = None
self.path_to_discriminator = None
self.device_name = "cuda:0"
self.device = torch.device(self.device_name)
self.input_channel = args.channels
self.train_sheets = args.sheets
def to_dict(self):
parameters = {
'epochs': self.epochs,
'save_data_interval': self.save_data_interval,
'save_image_interval': self.save_image_interval,
'log_interval': self.log_interval,
'sample_interval': self.sample_interval,
'batch_size': self.batch_size,
'load_size': self.load_size,
'crop_size': self.crop_size,
'cpu': self.cpu,
'dataroot': self.dataroot,
'output_dir': self.output_dir,
'log_dir': self.log_dir,
'phase': self.phase,
'lambda_L1': self.lambda_L1,
'epochs_lr_decay': self.epochs_lr_decay,
'epochs_lr_decay_start': self.epochs_lr_decay_start,
'path_to_generator': self.path_to_generator,
'path_to_discriminator': self.path_to_discriminator,
'device_name': self.device_name,
}
return parameters
# 重複なし
def rand_int(a, b, train_sheets):
ns = []
str_ns = []
while len(ns) < train_sheets:
n = random.randint(a, b)
if not n in ns:
ns.append(n)
for i in range(len(ns)):
n = ns[i]
str_n = str(n)
zfill_n = str_n.zfill(4)
str_ns.append(zfill_n)
return str_ns
def make_loader(args, opt):
#2以上606以下の乱数
#1は確定でバリデーション用とした
train_file_number = rand_int(2, 606, opt.train_sheets)
if args.channels == 3:
opt.output_dir = '3C_CMP286(trainRatio:' + str(opt.train_sheets) + '/606)'
dataset = CMPfacade3channel.AlignedDataset3CMP(opt, train_file_number)
val_dataset = CMPfacade3channel.valAlignedDataset3CMP(opt, train_file_number)
# ランダムクロップ
# dataset = CMP3c.AlignedDataset3CMP(opt, train_file_number, 'train')
# val_dataset = CMP3c.AlignedDataset3CMP(opt, train_file_number, 'val')
else:
opt.output_dir = '12C_CMP286(trainRatio:' + str(opt.train_sheets) + '/606)'
dataset = CMPfacade12channel.AlignedDataset12CMP(opt, train_file_number)
val_dataset = CMPfacade12channel.valAlignedDataset12CMP(opt, train_file_number)
# ランダムクロップ
# dataset = CMP12c.AlignedDataset12CMP(opt, train_file_number, 'train')
# val_dataset = CMP12c.AlignedDataset12CMP(opt, train_file_number, 'val')
dataloader = DataLoader(dataset, batch_size=opt.batch_size,
shuffle=True , drop_last = True)
val_loader = DataLoader(val_dataset, batch_size=opt.batch_size, shuffle=False)
return dataloader, val_loader
def main():
parser = argparse.ArgumentParser(description='myPx2pix')
parser.add_argument('-c', '--channels', type=int,
choices=[3, 12],
help='number of channels.')
parser.add_argument('-s', '--sheets', type=int,
choices=[300, 350, 400, 450, 500],
help='number of train sheets.')
args = parser.parse_args()
opt = Opts(args)
dataloader, val_loader = make_loader(args, opt)
model = Pix2pixModel.Pix2Pix(opt)
if not os.path.exists(opt.output_dir):
os.makedirs(opt.output_dir)
param_save_path = os.path.join(opt.output_dir, 'param.json')
save_json(opt.to_dict(), param_save_path, 'w')
experiment = cometml.comet()
val_lossG = Averagemeter.AverageMeter()
val_lossD = Averagemeter.AverageMeter()
"""## 学習の開始"""
for epoch in range(1, opt.epochs + 1):
model.netG.train()
model.netD.train()
for batch_num, data in enumerate(dataloader):
batches_done = (epoch - 1) * len(dataloader) + batch_num
model.train(data)
print(batch_num)
if batch_num % opt.log_interval == 0:
print("===> Epoch[{}]({}/{}): Loss_D: {:.4f} Loss_G: {:.4f}".format(
epoch, batch_num, len(dataloader), model.lossD, model.lossG_GAN))
cometml.gLossComet(experiment, model.lossG_GAN, batches_done)
cometml.dLossComet(experiment, model.lossD, batches_done)
if epoch % 100 == 0:
model.save_image('train', epoch)
act1 = []
act2 = []
for batch_num, data in enumerate(val_loader):
model.eval(data)
if batch_num == 0:
print("===> Validation:Epoch[{}]({}/{})".format(
epoch, batch_num, len(val_loader)))
val_lossG.update(model.lossG_GAN, data['A'].to(torch.device("cuda:0")).shape[0])
val_lossD.update(model.lossD, data['A'].to(torch.device("cuda:0")).shape[0])
if epoch % 5 == 0 or epoch == 1 or epoch == 2 or epoch == 3 :
#バリデーション用のすべてのデータを用いる
label = data['A'].to(torch.device("cuda:0"))
real = data['B'].to(torch.device("cuda:0"))
fake = model.netG(label)
act_real, act_fake = FID.calculate_fretchet(real, fake)
act1.extend(act_real)
act2.extend(act_fake)
if epoch % 5 == 0 or epoch == 1 or epoch == 2 or epoch == 3 :
act1 = np.array(act1)
act2 = np.array(act2)
fretchet_dist = FID.calculate_frechet_distance(act1, act2)
print("FIDscore:" + str(fretchet_dist))
cometml.FIDComet(experiment, fretchet_dist, epoch)
print("Loss_D: {:.4f} Loss_G: {:.4f}".format(
val_lossD.avg, val_lossG.avg))
cometml.valGLossComet(experiment, model.lossG_GAN, epoch)
cometml.valDLossComet(experiment, model.lossD_real, epoch)
if epoch % 10 == 0:
model.save_model('val', epoch)
model.save_image('val', epoch)
model.update_learning_rate()
val_lossD.reset()
val_lossG.reset()
if __name__ == '__main__':
main()
|
SELECT '010-1234-1234' AS ORIGIN -- REPLACE 문하열 치환
,REPLACE('010-1234-4567','-',' ') AS RE1 -- 첫번째'-'는 삭제할 요소, 두번쨰 ' ' 는 대체할 요소
,REPLACE('010-1234-4567','-') AS RE2 -- 두번째 ' ' 없으면 그냥 공백없이 출력
FROM DUAL;
SELECT 'ORACLE'
,LPAD('ORACLE',10,'#') AS LPAD1
,RPAD('ORACLE',10,'#') AS RPAD1
,LPAD('ORACLE',10) AS LPAD2
,RPAD('ORACLE',10) AS RPAD2
FROM DUAL;
SELECT '011230-3122332' AS ORI
,RPAD(SUBSTR('011230-3122332',1,7),14,'*') AS BLOCK
,CONCAT(SUBSTR('011230-3122332',1,7),'*******') AS CON
,'SDFASDF'||'SDFASDF'||'ASDFASDF'||'ASDFASDF' AS EN
FROM DUAL;
SELECT '['||TRIM(' ^ ORA CLE ^ ')||']' AS TRIM
,'['||TRIM(LEADING FROM' ORA CLE ')||']' AS TLEAD
,'['||TRIM(TRAILING FROM' ORA CLE ')||']' AS TTRAIL
,'['||TRIM(BOTH FROM' ORA CLE ')||']' AS BOTH
FROM DUAL;
/*
NUMBER FUNCTION
*/
--ROUND 반올림
SELECT ROUND(1234.5678) AS R
,ROUND(1234.4567,2) AS R1
,ROUND(1234.4567,-2) AS R2
FROM DUAL;
-- TRUNC 그냥 짜름.
SELECT TRUNC(1234.5345) AS R
,TRUNC(1234.5678,0) AS R1
FROM DUAL;
SELECT CEIL(3.14) --올림
,FLOOR (3.14) -- 버림
,CEIL(-3.14)
,FLOOR(-3.14)
FROM DUAL;
--MOD 나머지 연산
SELECT MOD(15,6),MOD(10,2),MOD(11,2) FROM DUAL;
/*
DATE FUNCTION
*/
SELECT SYSDATE AS NOW
,SYSDATE-1 AS YESTERDAY
,SYSDATE+1 AS TOMORROW
,(SELECT HIREDATE FROM EMP WHERE EMPNO=7934)
-(SELECT HIREDATE FROM EMP WHERE EMPNO=7902) AS DIFF
FROM DUAL;
SELECT SYSDATE
,ADD_MONTHS(SYSDATE,3)
FROM DUAL;
SELECT EMPNO, ENAME, HIREDATE, ADD_MONTHS(HIREDATE, 120) AS WORK10YEAR
FROM EMP;
--Q1 회사에서 32년 이상 일한사람 찾기
SELECT EMPNO, ENAME, HIREDATE
FROM EMP
WHERE ADD_MONTHS(HIREDATE,384)<SYSDATE;
----
SELECT EMPNO, ENAME, HIREDATE, SYSDATE
,MONTHS_BETWEEN(HIREDATE,SYSDATE) AS MONTHS1
,MONTHS_BETWEEN(SYSDATE,HIREDATE) AS MONTHS2
,TRUNC(MONTHS_BETWEEN(SYSDATE,HIREDATE)) AS MONTHS3
FROM EMP;
SELECT SYSDATE, NEXT_DAY(SYSDATE, '월요일'),LAST_DAY(SYSDATE)
FROM DUAL;
SELECT SYSDATE,
ROUND(SYSDATE,'YYYY')AS FORMAT_YYYY,
ROUND(SYSDATE,'DDD')AS FORMAT_DDD,
ROUND(SYSDATE,'HH')AS FORMAT_HH,
ROUND(SYSDATE,'MM')AS FORMAT_MM,
TRUNC(SYSDATE,'MM')AS FORMAT_MM2
FROM DUAL;
/*
TYPE CONVERSION
*/
DESC EMP;
SELECT EMPNO, ENAME, EMPNO+'500' -- + 숫자치환
--,EMPNO+'ABCD
,ENAME||'SDKJF' -- || 문자치환
,ENAME||500
FROM EMP;
SELECT TO_CHAR(SYSDATE,'YYYYMM/DD HH24:MI:SS') AS NOW
FROM DUAL;
SELECT SYSDATE,
TO_CHAR(SYSDATE, 'MM') AS MM,
TO_CHAR(SYSDATE, 'MON','NLS_DATE_LANGUAGE=KOREAN') AS MON_KOR,
TO_CHAR(SYSDATE, 'MON','NLS_DATE_LANGUAGE=ENGLISH') AS MON_ENG,
TO_CHAR(SYSDATE, 'MONTH','NLS_DATE_LANGUAGE=KOREAN') AS MON_KOR,
TO_CHAR(SYSDATE, 'MONTH','NLS_DATE_LANGUAGE=ENGLISH') AS MON_ENG,
TO_CHAR(SYSDATE, 'DAY') AS DAY,
TO_CHAR(SYSDATE, 'DAY','NLS_DATE_LANGUAGE=ENGLISH') AS DAY_ENG
FROM DUAL;
/*
숫자 표기 양식 9 숫자 한자리 0 빈자리에 채움 L 지역 단위
*/
SELECT SAL,
TO_CHAR(SAL, '$999,999') AS SAL_$,
TO_CHAR(SAL, 'L999,999') AS SAL_L,
TO_CHAR(SAL, '999,999.00') AS SAL_1,
TO_CHAR(SAL, '000,999,999.00') AS SAL_2,
TO_CHAR(SAL, '000999,999.99') AS SAL_3,
TO_CHAR(SAL, '999,999,00') AS SAL_4
FROM EMP;
SELECT TO_NUMBER('1,300','999,999')-TO_NUMBER('1,500','999,999')
FROM DUAL;
SELECT TO_DATE('2018-07-14','YYYY-MM-DD') AS TODATE
,TO_DATE('2018^07^14','YYYY-MM-DD') AS TODATE2
FROM DUAL;
SELECT *
FROM EMP
WHERE HIREDATE >TO_DATE('06/01/1981','MM/DD/YYYY');
/*
NULL FUNCTION
NVL, NVL2, COALESCE
*/
SELECT EMPNO, ENAME, SAL, COMM, SAL+COMM AS PAY
,NVL(COMM,0)
,SAL+NVL(COMM,0)
,NVL2(COMM,'O','X')
,NVL2(COMM,SAL*12+COMM,SAL*12) AS ANNSAL
FROM EMP;
/*
CONDITION FUNCTION
*/
SELECT EMPNO, ENAME, JOB, SAL, COMM
,CASE
WHEN JOB='MANAGER' THEN SAL*1.1
WHEN JOB='SALESMAN' THEN SAL*1.05
WHEN JOB='ANALIST' THEN SAL
ELSE SAL *1.03
END AS UPSAL
,CASE
WHEN COMM IS NULL THEN '해당없음'
WHEN COMM=0 THEN '수당없음'
WHEN COMM>0 THEN '수당: '||COMM
END AS COMM_TEXT
FROM EMP;
SELECT EMPNO, ENAME, JOB, SAL, COMM
,DECODE(JOB,
'MANAGER', SAL*1.1,
'SALESMAN', SAL*1.05,
'ANALYST',SAL,
SAL*1.03) AS UPSAL
FROM EMP;
-- Q1 EMP 테이블에서 사번, 사번앞 두자리 뒤에는 *로 마스킹
-- 이름, 이름 첫자리 뒤로는 *로 마스킹
SELECT EMPNO, ENAME
,RPAD(SUBSTR(EMPNO,1,2),4,'*') AS 사번
,RPAD(SUBSTR(ENAME,1,1),LENGTH(ENAME),'*') AS 이름
FROM EMP
-- 이름길이가 5인 애들만 할때는 따로 조건을 달아준당.
WHERE LENGTH(ENAME)=5;
-- Q2 EMP 테이블에서 사번, 사원명, 월급, 일당(월 근무일수는 20.5일로 계산 소수점 2자리), 시급(하루 근무시간은 8시간으로 계산)
SELECT EMPNO, ENAME, SAL
,TRUNC(SAL /20.5,2) AS DAY_PAY
,ROUND(SAL/20.5/8,1) AS TIME_PAY
FROM EMP;
-- Q3 EMP 테이블에서 사번, 사원명, 입사일(연도(4자리)/월/일로 표시)
-- ,입사일로부터 세달 뒤 다음 월요일의 날자(연도(4자리)-월-일로 표시
-- ,수당(COMM이 없는 사람은 N/A로 표시)
SELECT EMPNO, ENAME
,TO_CHAR(HIREDATE,'YYYY/MM/DD') AS 입사일
,TO_CHAR(NEXT_DAY(ADD_MONTHS(HIREDATE, 3),'월요일'),'YYYY/MM/DD') AS 세달뒤월요일
,NVL2(COMM,TO_CHAR(COMM),'N/A') AS 수당
FROM EMP;
-- Q4 EMP 테이블에서 사번, 사원명, 관리자 사번(없으면 ' '으로 표시)
-- , 대체 관리자(관리자 사번의 첫 두자리 값이 없으면 '0000' '75'이면 '5555', '76'이면'6666','77'이면 '7777'
-- , '78'이면 '8888'로 표시)
SELECT EMPNO, ENAME, NVL2(MGR,TO_CHAR(MGR),' ') AS 관리자사번
,CASE
WHEN MGR IS NULL THEN '0000'
WHEN SUBSTR(MGR,1,2)=75 THEN '5555'
WHEN SUBSTR(MGR,1,2)=76 THEN '6666'
WHEN SUBSTR(MGR,1,2)=77 THEN '7777'
WHEN SUBSTR(MGR,1,2)=78 THEN '8888'
ELSE TO_CHAR(MGR)
END AS 대체관리자
,DECODE(SUBSTR(MGR,1,2),NULL, '0000'
,'75','5555'
,'76','6666'
,'77','7777'
,'78','8888'
,TO_CHAR(MGR)
) AS 대체관리자
FROM EMP;
|
/*
Class
- Abstract Classes And Members مجرد
--- We Cannot Create An Instance Of An Abstract Class
*/
abstract class Food {
constructor(public title: string) {}
abstract getCookingTime(): void;
}
class Pizza extends Food {
constructor(title: string, public price: number) {
super(title);
}
getCookingTime(): void {
console.log(
`Cooking time for ${this.title} is 2hours, price is ${this.price}`
);
}
}
class Burger extends Food {
constructor(title: string, public price: number) {
super(title);
}
getCookingTime(): void {
console.log(
`Cooking time for ${this.title} is 1hours, price is ${this.price}`
);
}
}
const pizzaOrder1 = new Pizza("margrita", 150);
pizzaOrder1.getCookingTime();
const BurgerOrder1 = new Burger("Cheezy Smashed", 90);
BurgerOrder1.getCookingTime();
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_COMMAND_LENGTH 100
#define MAX_ARGUMENTS 10
/**
* void display_prompt:Displays the shell prompt (> ) on the standard output.
* void split_command_arguments(char *command, char **arguments):Splits the command into individual arguments.
* void free_command_arguments(char **arguments):Frees the memory allocated for the arguments array.
* int is_exit_command(char *command):Checks if the given command is the exit command
* int main():he main loop of the simple shell.
* Returns: 0 upon successful execution
*/
void display_prompt();
void split_command_arguments(char *command, char **arguments);
void free_command_arguments(char **arguments);
int is_exit_command(char *command);
int main()
{
char command[MAX_COMMAND_LENGTH];
char *arguments[MAX_ARGUMENTS];
while (1)
{
display_prompt();
fgets(command, sizeof(command), stdin);
command[strcspn(command, "\n")] = '\0';
split_command_arguments(command, arguments);
if (arguments[0] != NULL)
{
if (is_exit_command(arguments[0]))
{
break;
}
else
{
// Handle other commands
}
}
// Free the allocated memory for arguments
free_command_arguments(arguments);
}
return 0;
}
void display_prompt()
{
printf("> ");
fflush(stdout);
}
void split_command_arguments(char *command, char **arguments)
{
int arg_index = 0;
char *token = command;
while (*token != '\0' && arg_index < MAX_ARGUMENTS - 1)
{
while (*token == ' ' || *token == '\t')
{
token++;
}
arguments[arg_index] = NULL;
}
void free_command_arguments(char **arguments)
{
for (int i = 0; arguments[i] != NULL; i++)
{
free(arguments[i]);
}
}
int is_exit_command(char *command)
{
return strcmp(command, "exit") == 0;
}
|
package com.mastercard.paymenttransfersystem.domain.account.controller.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
/**
* The DTO sent by the client to process a transfer request
*/
@Data
@AllArgsConstructor
public class TransferRequestDTO {
@NotNull(message = "recipientAccountId is required")
private Long recipientAccountId;
@NotNull(message = "amount is required")
private BigDecimal amount;
@NotBlank(message = "currency is required")
private String currency;
}
|
#!/usr/bin/python3
"""Defines the HBnB console."""
import cmd
from models.base_model import BaseModel
from models import storage
from shlex import split
from models.user import User
def parse(arg):
return [i.strip(",") for i in split(arg)]
class HBNBCommand(cmd.Cmd):
"""Defines the HolbertonBnB command interpreter.
Attributes:
prompt (str): The command prompt.
"""
prompt = "(hbnb) "
prompt = "(hbnb) "
__classes = {
"BaseModel",
"User",
"State",
"City",
"Place",
"Amenity",
"Review"
}
def do_quit(self, arg):
"""Quit command to e:wqxit the program."""
return True
def do_EOF(self, arg):
"""EOF signal to exit the prgram."""
print("")
return True
def emptyline(self):
"""Do nothing upon receiving an empty line."""
pass
def do_create(self, arg):
"""Usage: create <class>
Create a new class instance and print its id.
"""
argtemp = parse(arg)
if len(argtemp) == 0:
print("** class name missing **")
elif argtemp[0] not in HBNBCommand.__classes:
print("** class doesn't exist **")
else:
print(eval(argtemp[0])().id)
storage.save()
def do_show(self, arg):
"""Usage: show <class> <id> or <class>.show(<id>)
Display the string representation of a class instance of a given id.
"""
argtemp = parse(arg)
objdict = storage.all()
if len(argtemp) == 0:
print("** class name missing **")
elif argtemp[0] not in HBNBCommand.__classes:
print("{}".format(argtemp[0]))
print("** class doesn't exist **")
elif len(argtemp) == 1:
print("** instance id missing **")
elif "{}.{}".format(argtemp[0], argtemp[1]) not in objdict:
print("** no instance found **")
else:
print(objdict["{}.{}".format(argtemp[0], argtemp[1])])
def do_destroy(self, arg):
"""Usage: destroy <class> <id> or <class>.destroy(<id>)
Delete a class instance of a given id."""
objdict = storage.all()
argtemp = parse(arg)
if len(argtemp) == 0:
print("** class name missing **")
elif argtemp[0] not in HBNBCommand.__classes:
print("** class doesn't exist **")
elif len(argtemp) == 1:
print("** instance id missing **")
elif "{}.{}".format(argtemp[0], argtemp[1]) not in objdict.keys():
print("** no instance found **")
else:
del objdict["{}.{}".format(argtemp[0], argtemp[1])]
storage.save()
def do_all(self, arg):
"""Usage: all or all <class> or <class>.all()
Display string representations of all instances of a given class.
If no class is specified, displays all instantiated objects."""
argtemp = parse(arg)
if len(argtemp) > 0 and argtemp[0] not in HBNBCommand.__classes:
print("** class doesn't exist **")
else:
objl = []
for obj in storage.all().values():
if len(argtemp) > 0 and argtemp[0] == obj.__class__.__name__:
objl.append(obj.__str__())
elif len(argtemp) == 0:
objl.append(obj.__str__())
print(objl)
def do_update(self, arg):
"""Usage: update <class> <id> <attribute_name> <attribute_value> or
<class>.update(<id>, <attribute_name>, <attribute_value>) or
<class>.update(<id>, <dictionary>)
Update a class instance of a given id by adding or updating
a given attribute key/value pair or dictionary."""
objdict = storage.all()
argtemp = parse(arg)
if len(argtemp) == 0:
print("** class name missing **")
return False
if argtemp[0] != "BaseModel":
print("** class doesn't exist **")
return False
if len(argtemp) == 1:
print("** instance id missing **")
return False
if "{}.{}".format(argtemp[0], argtemp[1]) not in objdict.keys():
print("** no instance found **")
return False
if len(argtemp) == 2:
print("** attribute name missing **")
return False
if len(argtemp) == 3:
try:
type(eval(argtemp[2])) != dict
except NameError:
print("** value missing **")
return False
if len(argtemp) == 4:
obj = objdict["{}.{}".format(argtemp[0], argtemp[1])]
if argtemp[2] in obj.__class__.__dict__.keys():
valtype = type(obj.__class__.__dict__[argtemp[2]])
obj.__dict__[argtemp[2]] = valtype(argtemp[3])
else:
obj.__dict__[argtemp[2]] = argtemp[3]
elif type(eval(argtemp[2])) == dict:
obj = objdict["{}.{}".format(argtemp[0], argtemp[1])]
for k, v in eval(argtemp[2]).items():
if (k in obj.__class__.__dict__.keys() and
type(obj.__class__.__dict__[k]) in {str, int, float}):
valtype = type(obj.__class__.__dict__[k])
obj.__dict__[k] = valtype(v)
else:
obj.__dict__[k] = v
storage.save()
if __name__ == "__main__":
HBNBCommand().cmdloop()
|
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import AddIcon from '@mui/icons-material/Add';
import AddCardIcon from '@mui/icons-material/AddCard';
import { Link } from 'react-router-dom';
import {
Card,
CardContent,
Container,
Grid,
Typography,
IconButton,
Dialog,
TextField,
Button,
DialogContent,
DialogTitle,
DialogActions,
} from '@mui/material';
import { Edit, Delete } from '@mui/icons-material';
const Template = () => {
const [companies, setCompanies] = useState([]);
const [selectedCompany, setSelectedCompany] = useState(null);
const [openDialog, setOpenDialog] = useState(false);
const [editCompany, setEditCompany] = useState({
_id: '',
image: '',
});
const [loading, setLoading] = useState(false);
useEffect(() => {
fetchCompanies();
}, []);
const fetchCompanies = async () => {
try {
const response = await axios.get('http://localhost:8080/api/templatelist');
setCompanies(response.data);
} catch (error) {
console.error(error);
}
};
const handleEditClick = (company) => {
setSelectedCompany(company);
setOpenDialog(true);
setEditCompany(company);
};
const handleEditDialogClose = () => {
setOpenDialog(false);
setSelectedCompany(null);
setEditCompany({
_id: '',
image: '',
});
};
const handleEditInputChange = (e) => {
const { name, value } = e.target;
setEditCompany((prevCompany) => ({
...prevCompany,
[name]: value,
}));
};
const handleUpdateClick = async () => {
try {
setLoading(true);
const formData = new FormData();
formData.append('image', editCompany.image);
await axios.put(`http://localhost:8080/api/updatetemplate/${editCompany._id}`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
setCompanies((prevCompanies) =>
prevCompanies.map((company) => (company._id === editCompany._id ? editCompany : company))
);
handleEditDialogClose();
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
};
const handleImageInputChange = (e) => {
setEditCompany((prevCompany) => ({
...prevCompany,
image: e.target.files[0],
}));
};
return (
<div style={{ padding: '100px' }}>
<Container maxWidth="md">
<Grid container spacing={2}>
{companies.map((company) => (
<Grid item xs={12} sm={6} md={4} key={company._id}>
<Card variant="outlined" style={{ marginBottom: '10px' }}>
<CardContent>
<img
src={company.image}
alt="Company"
style={{ width: '100%', height: 'auto', objectFit: 'cover' }}
/>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<IconButton onClick={() => handleEditClick(company)}>
<Edit />
</IconButton>
</div>
</CardContent>
</Card>
</Grid>
))}
</Grid>
</Container>
{/* Edit Dialog */}
<Dialog open={openDialog} onClose={handleEditDialogClose}>
<DialogTitle>Edit Company</DialogTitle>
<DialogContent>
<input type="file" accept="image/*" onChange={handleImageInputChange} />
</DialogContent>
<DialogActions>
<Button onClick={handleEditDialogClose}>Cancel</Button>
<Button onClick={handleUpdateClick} disabled={loading}>
Save
</Button>
</DialogActions>
</Dialog>
</div>
);
};
export default Template;
|
<template>
<Window
:isShow="windowConfig.isShow"
:buttons="windowConfig.buttons"
@close="closeWindow"
>
<el-form
:model="blogFormData"
:rules="blogFormDataRules"
ref="blogFormDataRef"
class="editor-form"
>
<el-form-item prop="title">
<el-input
v-model="blogFormData.title"
placeholder="请输入博客标题"
class="title-input"
>
</el-input>
</el-form-item>
<el-form-item v-if="blogFormData.editorType === 1" prop="content">
<HtmlEditor
v-model="blogFormData.content"
:height="htmlEditorHeight"
:style="{ width: '100%' }"
>
</HtmlEditor>
</el-form-item>
<el-form-item v-else prop="markdownContent">
<MarkdownEditor
v-model="blogFormData.markdownContent"
:height="markdownEditorHeight"
@htmlContent="setHtmlContent"
class="blog-editor-markdown"
>
</MarkdownEditor>
</el-form-item>
</el-form>
<Dialog
:isShow="dialogConfig.isShow"
:title="dialogConfig.title"
@close="dialogConfig.isShow = false"
:buttons="dialogConfig.buttons"
:closeCallback="dialogConfig.closeCallback"
>
<el-form
:model="blogFormData"
:rules="blogFormDataRules"
ref="settingsFormRef"
label-width="80px"
class="blog-setting-form"
>
<el-form-item label="博客分类" prop="categoryId">
<el-select
clearable
placeholder="请选择博客分类"
v-model="blogFormData.categoryId"
>
<el-option
v-for="item in categoryList"
:key="item.id"
:label="item.categoryName"
:value="item.id"
>
</el-option>
</el-select>
</el-form-item>
<el-form-item label="封面" prop="cover">
<CoverUpload v-model="blogFormData.cover"></CoverUpload>
</el-form-item>
<el-form-item label="博客类型" prop="sourceType">
<el-radio-group v-model="blogFormData.sourceType">
<el-radio :label="0">原创</el-radio>
<el-radio :label="1">转载</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item
label="原文地址"
prop="reprintUri"
v-if="blogFormData.sourceType === 1"
>
<el-input
placeholder="请输入原文地址"
v-model="blogFormData.reprintUri"
>
</el-input>
</el-form-item>
<el-form-item label="评论" prop="allowComment">
<div class="allow-comment">
<el-radio-group v-model="blogFormData.allowComment">
<el-radio :label="1">允许</el-radio>
<el-radio :label="0">不允许</el-radio>
</el-radio-group>
<span class="info"
>请先在评论设置里设置好相应参数,评论才会生效</span
>
</div>
</el-form-item>
<el-form-item label="博客摘要" prop="summary">
<el-input
type="textarea"
maxlength="255"
v-model="blogFormData.summary"
placeholder="请简短描述博客的内容"
:autosize="{ minRows: 4, maxRows: 4 }"
>
</el-input>
</el-form-item>
<el-form-item label="博客标签" prop="tag">
<div class="tag-input-panel">
<span class="info" v-if="blogFormData.tag.length === 0">
添加标签更容易被搜索引擎收录
</span>
<div class="tag-list">
<el-tag
v-for="(item, index) in blogFormData.tag"
:key="index"
:closable="true"
@close="deleteTag(index)"
class="tag-item"
size="small"
>
{{ item }}
</el-tag>
<span
class="iconfont icon-add-bold"
v-show="!isShowTagInput"
@click="showAddTagHandler"
>
</span>
<el-input
class="tag-input"
ref="tagInputRef"
v-show="isShowTagInput"
@blur="insertTag2Form"
@keyup.enter="insertTag2Form"
v-model="tagInputValue"
>
</el-input>
</div>
</div>
</el-form-item>
</el-form>
</Dialog>
</Window>
</template>
<script setup>
import { toInteger } from 'lodash'
import {
getCurrentInstance,
nextTick,
onMounted,
onUnmounted,
reactive,
ref
} from 'vue'
import { useStore, mapState } from 'vuex'
const store = useStore()
const emit = defineEmits(['callback'])
const { proxy } = getCurrentInstance()
const props = defineProps({
isShow: {
type: Boolean,
default: false
}
})
// 需要用到的接口
const api = {
// 博客的正删改查接口,使用 RESTFUL 区分
blogEdit: '/blog',
// 自动保存接口
autoSave: '/blog/autoSave'
}
// 编辑器的高度
const markdownEditorHeight = ref()
const htmlEditorHeight = ref()
// 博客表单数据
const blogFormData = ref({ tag: [] })
// reactive({ tag: [] })
const blogFormDataRef = ref(null)
const settingsFormRef = ref(null)
// 自定义验证博客内容的规则
const checkBlogContent = (rule, value, callback) => {
const regConteng = /^<p><br><\/p>$/
if (regConteng.test(value)) return callback(new Error('请输入博客正文'))
callback()
}
const blogFormDataRules = {
title: [{ required: true, message: '请输入博客标题' }],
content: [{ validator: checkBlogContent, trigger: 'blur' }],
markdownContent: [{ required: true, message: '请输入博客正文' }],
categoryId: [{ required: true, message: '请选择博客分类' }],
sourceType: [{ required: true, message: '请选择博客类型' }],
reprintUri: [{ required: true, message: '请输入博客转载地址' }],
allowComment: [{ required: true, message: '请选择是否允许评论' }]
}
// 分类列表
const categoryList = ref([])
// 标签输入内容
const tagList = ref([])
// 是否显示新增标签的flag
const isShowTagInput = ref(false)
// tag 输入框的值
const tagInputValue = ref()
// 标签输入框的引用
const tagInputRef = ref(null)
// 新增或者修改博客弹出框的配置数据
const windowConfig = reactive({
isShow: false,
buttons: [
{
// 唯一标识符,用于绑定循环的 key 值
btnId: '1',
// 按钮类型
type: 'danger',
text: '确定',
// 按钮的点击事件
click: (e) => {
proxy.$func.unFocus(e)
blogFormDataRef.value.validate((valid) => {
if (valid) {
cleanTimerInteval()
// 清除掉自动保存的分类信息
blogFormData.value.categoryId =
blogFormData.value.categoryId === 1
? null
: blogFormData.value.categoryId
// 显示出弹框
dialogConfig.isShow = true
}
})
}
}
]
})
// 点击确定按钮时弹出框的配置项
const dialogConfig = reactive({
isShow: false,
title: '博客设置',
buttons: [
{
type: 'danger',
text: '确定',
click: (e) => {
proxy.$func.unFocus(e)
submitBlog()
}
}
],
closeCallback: () => {
if (windowConfig.isShow === true) {
startTimerInteval()
}
}
})
// 自动保存的定时器
let timer = ref(null)
// 开启定时器,一分钟自动保存一次
const startTimerInteval = () => {
if (timer.value === null) {
timer.value = setInterval(() => {
autoSave()
}, 20000)
}
}
// 清除定时器的方法
const cleanTimerInteval = () => {
if (timer.value !== null) {
clearInterval(timer.value)
timer.value = null
}
}
// 组件挂载完成的钩子
onMounted(async () => {
getEditorHeight()
window.addEventListener('resize', getEditorHeight)
// 获取分类数据
const result = await proxy.$request({
url: '/category',
method: 'GET'
})
categoryList.value = result.data.filter((cate) => cate.id !== 1)
})
// 组件卸载的钩子
onUnmounted(() => {
cleanTimerInteval()
})
// 动态获取window的高度
const getEditorHeight = () => {
markdownEditorHeight.value = window.innerHeight - 270
htmlEditorHeight.value = window.innerHeight - 355
}
// 隐藏新增或者修改的弹出框
const closeWindow = () => {
// 关闭window
windowConfig.isShow = false
// 清空数据
blogFormDataRef.value.resetFields()
if (settingsFormRef.value) {
settingsFormRef.value.resetFields()
}
// 关闭自动保存的定时器
cleanTimerInteval()
// 退出之后刷新一下列表
emit('callback')
}
// 当处于markdown编辑器时填充html内容
const setHtmlContent = (htmlContent) => {
blogFormData.value.content = htmlContent
}
// 删除标签方法实现
const deleteTag = (index) => {
blogFormData.value.tag.splice(index, 1)
}
// 显示新增标签的逻辑
const showAddTagHandler = () => {
// 1. 显示出输入框
isShowTagInput.value = true
// 2. 让输入框获取焦点
nextTick(() => {
tagInputRef.value.focus()
})
}
// 插入tag 到表单中
const insertTag2Form = () => {
// 1. 隐藏输入框
isShowTagInput.value = false
// 2. 空值不用加
if (!tagInputValue.value) return
// 3. 重复值不加
if (blogFormData.value.tag.indexOf(tagInputValue.value) !== -1) {
tagInputValue.value = undefined
return
}
// 4. 将输入框中的值插入到 form 中
blogFormData.value.tag.push(tagInputValue.value)
tagInputValue.value = undefined
}
// 初始化方法
const init = (type, data) => {
windowConfig.isShow = true
nextTick(() => {
// 开启自动保存的定时器
startTimerInteval()
blogFormDataRef.value.resetFields()
blogFormData.value = { tag: [] }
if (type === 'add') {
// 获取用户信息
blogFormData.value.editorType = store.state.userInfo.editorType
} else {
getBlogDetail(data)
}
})
}
// 对外暴露初始化方法到
defineExpose({ init })
// 获取博客详情
const getBlogDetail = (data) => {
const formData = { ...data, tag: data.tag ? data.tag.split('|') : [] }
blogFormData.value = formData
}
// 自动保存
const autoSave = async () => {
const emptHtmlReg = /^<p><br><\/p>$/
if (
proxy.$func.isEmpty(blogFormData.value.content) ||
proxy.$func.isEmpty(blogFormData.value.title) ||
emptHtmlReg.test(blogFormData.value.content)
) {
return
}
const result = await proxy.$request({
url: api.autoSave,
method: 'POST',
showLoading: false,
params: { ...blogFormData.value, tag: blogFormData.value.tag.join('|') }
})
if (!result) return
if (result.data[0].tag) {
result.data[0].tag = result.data[0].tag.split('|')
} else {
result.data[0].tag = []
}
Object.assign(blogFormData.value, result.data[0])
}
// 提交博客数据到后台
const submitBlog = () => {
settingsFormRef.value.validate(async (valid) => {
if (!valid) return
const params = { ...blogFormData.value }
params.tag = params.tag.join('|')
// 发送请求,新增博客
const result = await proxy.$request({
url: api.blogEdit,
method: 'POST',
params
})
if (!result) return
proxy.$message.success(result.message)
dialogConfig.isShow = false
settingsFormRef.value.resetFields()
closeWindow()
emit('callback')
})
}
</script>
<style lang="less" scoped>
.editor-form {
:deep(.el-form-item) {
margin-bottom: 15px;
}
.title-input {
border-bottom: 1px solid #ddd;
margin-bottom: 9px;
:deep(.el-input__wrapper) {
box-shadow: none;
input {
font-size: 18px;
}
}
}
}
.blog-setting-form {
.allow-comment {
display: flex;
.info {
margin-left: 10px;
color: #b0b0b0;
font-size: 13px;
}
}
.tag-input-panel {
display: flex;
align-items: center;
.info {
font-size: 13px;
color: #b0b0b0;
margin-right: 10px;
}
.tag-list {
float: left;
.tag-item {
margin-right: 10px;
}
.icon-add-bold {
cursor: pointer;
color: red;
}
.tag-input {
width: 100px;
}
}
}
}
</style>
|
#include <bits/stdc++.h>
using namespace std;
// Define an Edge structure
struct Edge {
string destination;
int distance;
};
// Define a Graph class
class Graph {
private:
map<string, vector<Edge>> adjList;
public:
// Constructor that adds all edges
Graph() {
// Add edges to the graph
addEdge("City Center", "Park", 6);
addEdge("City Center", "Hotel Plaza", 15);
addEdge("City Center", "Central Market", 9);
addEdge("City Center", "Cafe Harmony", 3);
addEdge("Park", "Hotel Plaza", 18);
addEdge("Park", "Shopping Mall Deluxe", 12);
addEdge("Hotel Plaza", "Cricket Stadium", 24);
addEdge("Hotel Plaza", "Art Gallery Haven", 30);
addEdge("Hotel Plaza", "Sky Lounge", 9);
addEdge("Central Market", "Shopping Mall Deluxe", 6);
addEdge("Central Market", "Cafe Harmony", 12);
addEdge("Central Market", "Art Gallery Haven", 21);
addEdge("Central Market", "Bookworm's Cafe", 18);
addEdge("Cafe Harmony", "Restaurant Elegance", 9);
addEdge("Cafe Harmony", "Tech Hub Plaza", 24);
addEdge("Shopping Mall Deluxe", "Restaurant Elegance", 15);
addEdge("Shopping Mall Deluxe", "Tech Hub Plaza", 9);
addEdge("Shopping Mall Deluxe", "Cinema Paradiso", 21);
addEdge("Cricket Stadium", "Restaurant Elegance", 18);
addEdge("Cricket Stadium", "Fitness Junction", 12);
addEdge("Restaurant Elegance", "Cinema Paradiso", 6);
addEdge("Art Gallery Haven", "Hotel Plaza", 30);
addEdge("Tech Hub Plaza", "Bookworm's Cafe", 12);
addEdge("Green Oasis Park", "City Center", 12);
addEdge("Green Oasis Park", "Restaurant Elegance", 21);
addEdge("Green Oasis Park", "Fitness Junction", 15);
addEdge("Fitness Junction", "Cricket Stadium", 12);
addEdge("Fitness Junction", "Sky Lounge", 18);
addEdge("Sky Lounge", "Hotel Plaza", 9);
addEdge("Sky Lounge", "Tech Hub Plaza", 6);
addEdge("Sky Lounge", "Beachfront Resort", 24);
addEdge("Cinema Paradiso", "Shopping Mall Deluxe", 21);
addEdge("Cinema Paradiso", "Beachfront Resort", 30);
addEdge("Bookworm's Cafe", "Central Market", 18);
addEdge("Bookworm's Cafe", "Tech Hub Plaza", 12);
addEdge("Beachfront Resort", "Sky Lounge", 24);
addEdge("Beachfront Resort", "Cinema Paradiso", 30);
}
// Add edge to the graph
void addEdge(const string& source, const string& destination, int distance) {
adjList[source].push_back(Edge{destination, distance});
// Since it's bidirectional
adjList[destination].push_back(Edge{source, distance});
}
// Method to print all location points
void printLocations() {
cout << "Locations:" << endl;
for (const auto& pair : adjList) {
cout << "- " << pair.first << endl;
}
}
// Dijkstra's algorithm to find the shortest path
map<string, pair<int, string>> dijkstra(const string& source) {
map<string, pair<int, string>> distances;
set<pair<int, string>> queue;
// Initialize distances to infinity and set predecessors to empty
for (auto& vertex : adjList) {
distances[vertex.first] = {numeric_limits<int>::max(), ""};
}
// Set the distance for the source
distances[source].first = 0;
queue.insert({0, source});
while (!queue.empty()) {
auto front = *queue.begin();
queue.erase(queue.begin());
int distance = front.first;
string current = front.second;
// Visit all neighbors
for (auto& edge : adjList[current]) {
int newDist = distance + edge.distance;
if (newDist < distances[edge.destination].first) {
queue.erase({distances[edge.destination].first, edge.destination});
distances[edge.destination] = {newDist, current};
queue.insert({newDist, edge.destination});
}
}
}
return distances;
}
// Method to print the shortest path
int printShortestPath(const string& source, const string& destination) {
auto distances = dijkstra(source);
vector<string> path;
string current = destination;
int totalDistance = 0; // Initialize total distance
while (current != source) {
path.push_back(current);
totalDistance += distances[current].first; // Accumulate distance
current = distances[current].second;
}
path.push_back(source);
reverse(path.begin(), path.end());
cout << "Shortest path from " << source << " to " << destination << ":" << endl;
for (size_t i = 0; i < path.size(); ++i) {
cout << path[i];
if (i < path.size() - 1) {
cout << " -> ";
}
}
cout << endl;
// cout << "Total distance: " << totalDistance << " km" << endl; // Print total distance
return totalDistance; // Return total distance
}
};
// int main() {
// Graph g; // Graph is now initialized with all edges
// g.printLocations(); // Print all locations
// string source, destination;
// cout << "Enter source location: ";
// // cin >> source;
// getline(cin, source);
// cout << "Enter destination location: ";
// // cin >> destination;
// getline(cin, destination);
// int distance = g.printShortestPath(source, destination); // Print the shortest path and total distance
// cout<<distance<<" Km"<<endl;
// return 0;
// }
|
import { MakeCreateGymsService } from "@/services/factories/make-create-gym-service"
import { FastifyReply, FastifyRequest } from "fastify"
import { z } from "zod"
export async function gymCreate(req: FastifyRequest, res: FastifyReply){
const createGymBodySchema = z.object({
title: z.string(),
description: z.string().nullable(),
phone: z.string().nullable(),
latitude: z.coerce.number().refine(value => {
return Math.abs(value) <= 90
}),
longitude: z.coerce.number().refine(value => {
return Math.abs(value) <= 180
})
})
const {title, description, phone, latitude, longitude} = createGymBodySchema.parse(req.body)
const createGymService = MakeCreateGymsService()
await createGymService.execute({
title,
description,
phone,
latitude,
longitude,
})
return res.status(201).send()
}
|
# GShell - little shell / logger for embedded systems
## Overview
Basic uart shell for embedded systems. While it has been initially developed for the AVR microcontrollers, it can be used with pretty much any controller or on computers as long as you provide the nessesary `printChar` function.

## Features
- Should run on most microcontrollers with no changes
- Configureable via define-macros
- Supports basic VT100 Coloring
- Nicely printed shell logging
- Ease of use to add additional commands
- Supports both static command lists or dynamically added commands
- Handles Quotation-Marks to pass larger arguments to the commands
## Usage
In order to use the library, simply initialise `gs_init` with a function pointer to a printCharacter-function. Optionally you can also pass over a millisecond-timestamp/tick function, in order to add timelogging capabilities on the logging functions.
From there, simply call `gshell_processShell` (in your `main` function) with the received character from the UART or USB-CDC driver. Any called command can return a value, which is passed back to `gshell_processShell`, which returns it back to the programmer, allowing basic information exchange between executed commands and the main function.
A lot of work has been put into documentation of the header and c file, please take a look in the header file to get a detailed information about each function, required arguments and possible return values. Alternatively, take a look at the included main.c file, which should give a good insight of the shell's capabilities.
|
import { Avatar, Icon } from "@mui/material";
import { useRouter } from "next/router";
import { useAuthState } from "react-firebase-hooks/auth";
import styled from "styled-components";
import { auth, db } from "../firebase";
import { AttachFile, MoreVert, InsertEmoticon } from "@mui/icons-material";
import { useCollection } from "react-firebase-hooks/firestore";
import Message from "./message";
import firebase from "firebase/compat/app";
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import { useRef, useState } from "react";
import getRecipientEmail from "../utils/getRecipientEmail";
import TimeAgo from "timeago-react";
function ChatScreen({ chat, messages }) {
const [user] = useAuthState(auth);
const [input, setInput] = useState('');
const router = useRouter();
const endOfMessagesRef = useRef(null);
const [messagesSnapshot] = useCollection(db.collection('chats').doc(router.query.id).collection('messages').orderBy('timestamp', 'asc'));
const recipientEmail = getRecipientEmail(chat.users, user);
const [recipientSnapshot] = useCollection(db.collection('users').where("email", "==", recipientEmail));
const recipient = recipientSnapshot?.docs?.[0]?.data();
const showMessages = () => {
if (messagesSnapshot) {
return messagesSnapshot.docs.map(message => (
<Message
key={message.id}
user={message.data().user}
message={{
...message.data(),
timestamp: message.data().timestamp?.toDate().getTime(),
}}
/>
))
}
// else {
// return JSON.parse(messages).map(message => (
// <Message key={message.id} user={message.user} message={message} />
// ))
// }
}
const scrollToBottom = () => {
endOfMessagesRef.current.scrollIntoView({
behavior: "smooth",
block: "start"
});
}
const sendMessage = (e) => {
e.preventDefault();
db.collection('users').doc(user.uid).set({
lastSeen: firebase.firestore.FieldValue.serverTimestamp(),
}, { merge: true });
db.collection('chats').doc(router.query.id).collection('messages').add({
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
message: input,
user: user.email,
photoURL: user.photoURL,
});
setInput('');
scrollToBottom();
}
return (
<Container>
<Header>
{recipient ? (<Avatar src={recipient?.photoURL} />) : (<Avatar>{recipientEmail[0]}</Avatar>)}
<HeaderInformation>
<h3>{recipientEmail}</h3>
{recipientEmail ? (<p>Last seen: {' '}{recipient?.lastSeen?.toDate() ? (<TimeAgo datetime={recipient?.lastSeen?.toDate()} />) : "Unavailable"}</p>):(<p>Loading..</p>)}
</HeaderInformation>
<HeaderIcons>
<IconButton>
<AttachFile />
</IconButton>
<IconButton>
<MoreVert />
</IconButton>
</HeaderIcons>
</Header>
<MessageContainer>
{showMessages()}
<EndOfMessage ref={endOfMessagesRef}/>
</MessageContainer>
<InputContainer>
<InsertEmoticon />
<Input value={input} onChange={e => setInput(e.target.value)} />
<button hidden disabled={!input} type="submit" onClick={sendMessage}>Send Message</button>
</InputContainer>
</Container>
)
}
export default ChatScreen;
const Container = styled.div``;
const Input = styled.input`
flex: 1;
outline: 0;
border: none;
border-radius: 10px;
background-color: whitesmoke;
padding: 20px;
margin-left: 15px;
margin-right: 15px;
`;
const InputContainer = styled.form`
display: flex;
align-items: center;
padding: 10px;
position: sticky;
bottom: 0;
background-color: white;
z-index: 100;
`;
const Header = styled.div`
position: sticky;
background-color: white;
z-index: 100;
top: 0;
display: flex;
padding: 11px;
height: 80px;
align-items: center;
border-bottom: 1px solid whitesmoke;
`;
const HeaderInformation = styled.div`
margin-left: 15px;
flex: 1;
> h3 {
margin-bottom: 3px;
}
> p {
font-size: 14px;
color: gray;
}
`;
const HeaderIcons = styled.div``;
const IconButton = styled.div``;
const EndOfMessage = styled.div`
margin-bottom: 50px;
`;
const MessageContainer = styled.div`
padding: 30px;
background-color: #e5ded8;
min-height: 90vh;
`;
|
import React from 'react';
import { useNavigate } from 'react-router-dom';
import moduleStyle from "./index.module.css"
import LayoutBox from "../../components/LayoutBox/"
import IconCom from './components/iconCom/';
import HeaderTitle from './components/HeaderTitle/';
import { Layout, Menu } from 'antd';
const { Sider, Content, Header } = Layout;
export default function Home() {
const navigate = useNavigate();
const items = [
{ label: '数据看板', key: 'dataPanel' }, // 菜单项务必填写 key
{ label: '会员管理', key: 'memberManage' }, // 菜单项务必填写 key
{ label: '菜单项二', key: 'item-2' },
{
label: '子菜单',
key: 'submenu',
children: [{ label: '子菜单项', key: 'submenu-item-1' }],
}
]
const menuClickHandle = ({ key, keyPath, domEvent }) => {
navigate("/" + key)
}
return (
<>
<Layout>
<Sider className={moduleStyle.sider_box}>
<IconCom></IconCom>
<Menu
onClick={menuClickHandle}
mode="inline"
items={items} />
</Sider>
<Layout>
<Header style={{background: "#666af9", display: 'flex', alignItems: "center",justifyContent: 'flex-end'}}>
<HeaderTitle></HeaderTitle>
</Header>
<Content>
<LayoutBox></LayoutBox>
</Content>
</Layout>
</Layout>
</>
)
}
|
/* eslint-disable no-plusplus */
import { message } from "antd";
import { v4 as uuid } from 'uuid';
import type { RcFile } from "antd/es/upload/interface";
import moment from "moment";
import { LOCALE, VALUE_TOKEN } from "./constant";
export default class Utils {
static charCodeA = 65;
static convertToStringFormat(num?: number | null): string {
if (num === null || num === undefined) return "-";
const mergeNum = num?.toString().split(".").join("");
return mergeNum.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
static convertToIntFormat(str?: string): number {
if (str === null || str === undefined) return 0;
return parseInt(str.toString().split(".").join(""), 10);
}
static cutText(length: number, string?: string): string {
if (!string) return "-";
return string?.length > length ? `${string.slice(0, length)}...` : string;
}
static imageSafety(image: string | undefined | null): string {
return image ?? "/images/placeholder.png";
}
static currencyFormatter = (selectedCurrOpt: any) => (value: any) => {
return new Intl.NumberFormat(LOCALE, {
style: "currency",
currency: selectedCurrOpt.split("::")[1],
}).format(value);
};
static currencyParser = (value: any) => {
let newValue = value;
try {
// for when the input gets clears
if (typeof value === "string" && !value.length) {
newValue = "0.0";
}
// detecting and parsing between comma and dot
const group = new Intl.NumberFormat(LOCALE).format(1111).replace(/1/g, "");
const decimal = new Intl.NumberFormat(LOCALE).format(1.1).replace(/1/g, "");
let reversedVal = newValue.replace(new RegExp(`\\${group}`, "g"), "");
reversedVal = reversedVal.replace(new RegExp(`\\${decimal}`, "g"), ".");
// => 1232.21 €
// removing everything except the digits and dot
reversedVal = reversedVal.replace(/[^0-9.]/g, "");
// => 1232.21
// appending digits properly
const digitsAfterDecimalCount = (reversedVal.split(".")[1] || []).length;
const needsDigitsAppended = digitsAfterDecimalCount > 2;
if (needsDigitsAppended) {
reversedVal *= 10 ** (digitsAfterDecimalCount - 2);
}
return Number.isNaN(reversedVal) ? 0 : reversedVal;
} catch (error) {
console.error(error);
return 0;
}
};
static getBase64 = (data: RcFile | File, callback: (url: string) => void) => {
const reader = new FileReader();
reader.addEventListener("load", () => callback(reader.result as string));
reader.readAsDataURL(data);
};
static beforeUpload = (file: RcFile) => {
const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
if (!isJpgOrPng) {
message.error("Format gambar hanya boleh jpg/jpeg/png");
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error("Ukuran gambar tidak boleh lebih dari 2MB!");
}
return isJpgOrPng && isLt2M;
};
static parseTreeObjectToArray<T>(obj: any): T[] {
if (!obj) return [];
const parse = Object.keys(obj).map((key) => ({
...obj[key],
id: key,
})) as T[];
return parse as T[];
}
static onPaste = (e: any): Promise<any> | null => {
if (!(e.clipboardData && e.clipboardData.items)) return null;
return new Promise((resolve, reject) => {
for (let i = 0, len = e.clipboardData.items.length; i < len; i++) {
const item = e.clipboardData.items[i];
if (item.kind === 'string') {
item.getAsString((str: any) => resolve({ type: 'text', value: str }));
} else if (item.kind === 'file') {
const pasteFile = item.getAsFile();
resolve({ type: 'file', value: pasteFile });
} else {
reject(new Error('Not allow to paste this type!'));
}
}
});
}
static removeDashes(str: string) {
return str.split('-').join('');
}
static createChatId({ postfix, uids }: { uids: string[], postfix: string }) {
return this.removeDashes(uids.sort().join('') + postfix);
}
static stripHtml = (html: string) => {
const tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
static isDifferentDate = ({ prevTime, time }: { prevTime: any, time: any }) => {
return moment(prevTime || moment.now()).isSame(time, 'date');
}
static generateFileName({ file }: { file: File }) {
const extension = file.name.split('.')[file.name.split('.').length - 1].toLowerCase();
return `${uuid()}.${extension}`;
}
static convertToToken(total: number) {
return Math.round(total / VALUE_TOKEN);
}
}
|
const test = require("node:test");
const { deepEqual } = require("node:assert");
const { tokenize } = require("../");
test("tokenizing letters", () => {
const words = tokenize("a b c");
deepEqual(
["a", "b", "c"],
words.map((w) => w.lexeme),
);
});
test("tokenizing words", () => {
const words = tokenize("one two three");
deepEqual(
["one", "two", "three"],
words.map((w) => w.lexeme),
);
});
test("tokenizing sentences with punctuation", () => {
const words = tokenize(`
Lorem ipsum, dolor sit amet.
Lorem ipsum, dolor sit amet.
`);
deepEqual(
[
"Lorem",
"ipsum",
"dolor",
"sit",
"amet",
"Lorem",
"ipsum",
"dolor",
"sit",
"amet",
],
words.map((w) => w.lexeme),
);
});
|
package com.ecommerce.productservice;
import com.ecommerce.productservice.dto.ProductRequest;
import com.ecommerce.productservice.model.Product;
import com.ecommerce.productservice.repository.ProductRepository;
import com.ecommerce.productservice.service.ProductService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.testcontainers.containers.MongoDBContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.math.BigDecimal;
import java.util.List;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
@Testcontainers
class ProductServiceApplicationTests {
// To be able to make a request from the test, we use mockMvc which will provide a mock servlet environment to call controller endpoints
@Autowired
private MockMvc mockMvc;
//converts JSON to pojo and vice-versa
@Autowired
private ObjectMapper objectMapper;
@Autowired
private ProductRepository prodRepo;
@Autowired
private ProductService prodService;
//This container method will only take objects of type string
@Container
static MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:4.4.2");
//the replica uri will be added dynamically to the spring contest while running the test
@DynamicPropertySource
static void setProperties(DynamicPropertyRegistry dynamicPropertyRegistry){
dynamicPropertyRegistry.add("spring.data.mongodb.uri", mongoDBContainer::getReplicaSetUrl);
}
@Test
void testCreateProduct() throws Exception {
ProductRequest prodRequest = getProductRequest();
String productRequest = objectMapper.writeValueAsString(prodRequest);
mockMvc.perform(MockMvcRequestBuilders.post("/ecommerce/api/product/add")
.contentType(MediaType.APPLICATION_JSON)
.content(productRequest))
.andExpect(status().isCreated());
Assertions.assertEquals(1, prodRepo.findAll().size());
}
private ProductRequest getProductRequest(){
return ProductRequest.builder()
.name("Iphone 13")
.description("Iphone 13")
.price(BigDecimal.valueOf(1200))
.build();
}
@Test
void getProduct(){
addProduct();
List<Product> productList = prodRepo.findAll();
for(Product product: productList){
Assertions.assertEquals("Iphone 13", product.getName());
}
}
void addProduct(){
ProductRequest productRequest = ProductRequest.builder()
.name("Iphone 13")
.description("Iphone 13")
.price(BigDecimal.valueOf(1200))
.build();
prodService.createProduct(productRequest);
}
}
|
package composicaoEnumDadosCliente;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Pedido {
private Date momentoPedido;
private StatusPedido status;
private Cliente cliente;
private List<ItemPedido> itens = new ArrayList<ItemPedido>();
private static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
//construtores:
public Pedido() {
}
public Pedido(Date momentoPedido, StatusPedido status, Cliente cliente) {
this.momentoPedido = momentoPedido;
this.status = status;
this.cliente = cliente;
}
//Geters e Seters:
public Date getMomentoPedido() {
return momentoPedido;
}
public void setMomentoPedido(Date momentoPedido) {
this.momentoPedido = momentoPedido;
}
public StatusPedido getStatus() {
return status;
}
public void setStatus(StatusPedido status) {
this.status = status;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public void adicionarItens(ItemPedido item) {
itens.add(item);
}
public void removerItens(ItemPedido item) {
itens.remove(item);
}
public double total() {
double soma = 0;
for (ItemPedido ip : itens) {
soma = soma + ip.subTotal();
}
return soma;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Momento do pedido: ");
sb.append(sdf.format(momentoPedido) + "\n");
sb.append("Status do pedido: ");
sb.append(status + "\n");
sb.append("Cliente: ");
sb.append(cliente + "\n");
sb.append("Itens do pedido:\n");
for (ItemPedido item : itens) {
sb.append(item + "\n");
}
sb.append("Preço total: $");
sb.append(String.format("%.2f", total()));
return sb.toString();
}
}
|
package com.wemax.mtech.Adapter.home
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.wemax.mtech.Model.groups.PostModel
import com.wemax.mtech.R
import com.wemax.mtech.activity.home.PlaceDetailsActivity
class HomeFragmentPlacesAdapter(val context: Context, val booking: List<PostModel>) :
RecyclerView.Adapter<HomeFragmentPlacesAdapter.myViewHolder>() {
inner class myViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
// var profile_image = itemView.findViewById<ShapeableImageView>(R.id.image)
var profile_image = itemView.findViewById<ImageView>(R.id.image)
var providerName = itemView.findViewById<TextView>(R.id.postTitle)
var providerRating = itemView.findViewById<TextView>(R.id.rating)
var parentProductDetail = itemView.findViewById<CardView>(R.id.parentProductDetail)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): myViewHolder {
val inflater: LayoutInflater = LayoutInflater.from(parent.context)
val view: View = inflater.inflate(R.layout.item_home_fragment_services2, parent, false)
return myViewHolder(view)
}
override fun onBindViewHolder(holder: myViewHolder, position: Int) {
val obj = booking.get(position)
holder.profile_image.setImageResource(obj.postImage)
holder.providerName.text = obj.postTitle
holder.providerRating.text = obj.postRating
holder.parentProductDetail.setOnClickListener {
context.startActivity(Intent(context, PlaceDetailsActivity::class.java))
}
}
override fun getItemCount(): Int {
return booking.size
}
}
|
################################################
# INCLUDE SECTION. LOAD LIBRARIES, CODE
##########
setwd("S:/grups/MODELING/Lung_AECC_Gerard/3_ModelAECC_Gerard/ModelLC/Git_LC")
# Simulation basics
source("constantDefinition.R")
source("lcSimulCpp.R")
source("lcInterventionsUtils.R")
# Data load and manip
source("loadTPMatrixFromFile.R")
# Parallel support
library(foreach)
library(doParallel)
library(doRNG)
library(itertools)
# Utils
source("scriptUtils.R")
# Output support
library(Matrix)
source("yajirobai.R")
################################################
# INIT SECTION
##########
t0 <- Sys.time()
tstamp <- format(t0, "%Y%m%d_%H%M%S")
logfilename <- paste0("results/logs/exec_", tstamp, ".log")
#zz <- file(logfilename, open="wt")
#sink(zz)
#sink(zz, type="message")
cat(sprintf("Logfile \"%s\" initialized\n", logfilename))
if (exists("sim.name")) {
cat(paste0("Simulation name:\t", sim.name, "\n"))
}
## Reproducible results
seed <- sample.int(.Machine$integer.max,1)
#seed <- 1433461694
set.seed(seed)
cat(sprintf("Using seed: %10d\n\n", seed))
## CLUSTER SETUP
n.cores <- kNcores
cat( "***********************************\n")
cat(sprintf("*** RUNNING ON A %d-core CLUSTER ***\n", n.cores))
cat( "***********************************\n")
cat("\n")
cat("Initializing cluster...\n")
cl <- makeCluster(n.cores)
clusterExport(cl, c('lc.simulate.cpp', 'lc_simulate_cpp',
'kStartAge', 'kEndAge', 'kPeriods', 'kHealthy',
'kDefaultGroupLength',
'kOptionsDefaultIncidence',
'GetAllInterventionsParameters',
'kInterventionsDefaultParameters',
'age.weights'))
registerDoParallel(cl)
cat("Cluster initialized\n\n")
## [END] cluster setup
## DATA LOAD
transition.matrix.filename <- "Remarkable TP matrices/tp_dan20.xls"
#transition.matrix.filename <- "Remarkable TP matrices/tp_euron0.xls"
cat("Loading matrix from file:")
cat(transition.matrix.filename)
cat("\n")
tpm <- LoadTPMatrixFromFile(transition.matrix.filename)
cat("Matriu carregada\n")
## [END] data load
################################################
# PARAMETERS SETUP
##########
N = 100000
Nsim=1
# show.band <- TRUE
show.band <- FALSE
show.overall <- TRUE
# show.overall <- FALSE
source("karin_parameters_prova.R")
#si no inicialitzem aixo es queixa
cost=vector()
qaly=vector()
costni=vector()
qalyni=vector()
counter=0
for(par1 in params){
counter=counter+1
interventions_p=par1$interventions_p
costs_p=par1$costs_p
#options_p=par1$options_p
#no entenc que passa amb els parametres
cat( "\n***************************\n")
cat( "*** RUNNING PARAMETERS: ***\n")
cat( "***************************\n")
cat("\n")
cat(sprintf("N=%d\n", N))
cat("\n*** Intervention parameters:\n")
print(interventions_p)
cat("\n*** Cost parameters:\n")
print(costs_p)
cat("\n*** Options parameters:\n")
print(options_p)
##cal???
## Random seed
#seed <- sample.int(.Machine$integer.max,1)
# cat("WARNING. Using preset seed.\n")
# seed <- 1966531022
#set.seed(seed)
#cat(sprintf("Using seed: %10d\n", seed))
################################################
# SIMULATION
##########
cat( "\n***************************\n")
cat( "*** STARTING SIMULATION ***\n")
cat( "***************************\n")
sim <- lc.simulate.cpp.multiple(tpm$tpm, tpm$tp.limits,
interventions_p = interventions_p,
costs_p = costs_p,
options_p = options_p,
# initial.healthy.population = N)
initial.healthy.population = N,
N.sim = Nsim)
cat( "\n**************************\n")
cat( "*** SIMULATION RESULTS ***\n")
cat( "**************************\n")
#print(sim["nh"]) # TODO make it friendlier
#descomentar linia dabaix per mes informacio
#print(sim[names(sim)[2:9]]) # (TODO) Warning: if "costs" entry is removed, this has to be modified
print(sim["costs_person"]) # TODO make it friendlier
print(sim["costs_person_year"]) # TODO make it friendlier
print(sim["qaly"])
cost[counter]=sim$'costs_person'[3,1]
qaly[counter]=sim$'qaly'
cat( "\n**********************************\n")
cat( "*** NO INTERVENTION SIMULATION ***\n")
cat( "**********************************\n")
#no intervention parameters
interventions_p=list(diag_screen=c(0,0.604,0.604,0.604,0,0,0),
diag_spont= c(5e-8,1e-5,1e-4,1e-3,0,0,0),
# no quitting nor screening
screening_start_age=55, screening_end_age=55, screening_periodicity=12, screening_coverage=0.1869, screening_quitters_years=15, survival_after_scr_dx=.3714,
quitting_interventions = list(list()), quitting_effect_type = 'logistic', quitting_ref_years = 15, quitting_rr_after_ref_years = .2, # reducció 80% als 15 anys
p_smoker=0,
rr_smoker=1
)
costs_p <- list(
screening=list(i=0),
quitting.int=list(i=0), # dummy
postdx_treatment=list(i=14160.4),
#usual.care=list(md=c(0, 1,5,10,0.2,0,0)),
utilities=c(1,.705,.655,.530,0,0,0),
discount.factor=0.03
)
options_p <- list(
smoker_inc_type = "current"
)
# [END] parameters
cat(sprintf("N=%d\n", N))
cat("\n*** Intervention parameters:\n")
print(interventions_p)
cat("\n*** Cost parameters:\n")
print(costs_p)
cat("\n*** Options parameters:\n")
print(options_p)
####SIMULATION
sim <- lc.simulate.cpp.multiple(tpm$tpm, tpm$tp.limits,
interventions_p = interventions_p,
costs_p = costs_p,
options_p = options_p,
# initial.healthy.population = N)
initial.healthy.population = N,
N.sim = Nsim)
##end simulation
print(sim["costs_person"]) # TODO make it friendlier
print(sim["costs_person_year"]) # TODO make it friendlier
print(sim["qaly"])
costni[counter]=sim$'costs_person'[3,1]
qalyni[counter]=sim$'qaly'
print(counter)
print(qaly)
print(qalyni)
print(cost)
print(costni)
icer=(cost-costni)/(qaly-qalyni)
print(icer)
cat("\n")
}
cat("qaly no int\n")
cat(paste0(mean(qalyni)))
cat("\n cost no int\n")
cat(paste0(mean(costni)))
cat("\n qaly int\n")
cat(paste0(mean(qaly)))
cat("\n cost int\n")
cat(paste0(mean(cost)))
plot(qaly-qalyni,cost-costni,col="blue",cex=.4, pch=3)
abline(1,25000,col=2)
################################################
# CLEANING UP
##########
cat( "\n*******************\n")
cat( "*** CLEANING UP ***\n")
cat( "*******************\n")
cat("Stopping cluster\n")
stopCluster(cl)
registerDoSEQ()
cat("Done\n")
t1 <- Sys.time()
cat(sprintf("\nExecution time: %10.2f secs\n\n", as.numeric(difftime(t1,t0,units="secs"))))
#cat("Stopping log\n")
#sink()
#sink(type="message")
|
<template>
<div
class="drag"
:style="'top:'+top+'px;left:'+left+'px;width:'+width+'px;height:'+height+'px;z-index:'+zIndex+';'"
:class="`${(active || isActive) ? 'active' : 'inactive'} ${contentClass ? contentClass: ''}`"
@mousedown="bodyDown($event)"
@touchstart="bodyDown($event)"
@touchend="up($event)"
>
<slot />
</div>
</template>
<script>
export default {
name: 'Drag',
props: {
isActive: {
type: Boolean, default: false
},
preventActiveBehavior: {
type: Boolean, default: false
},
isDraggable: {
type: Boolean, default: true
},
parentLimitation: {
type: Boolean, default: false
},
parentW: {
type: Number,
default: 0,
validator: function(val) {
return val >= 0
}
},
parentH: {
type: Number,
default: 0,
validator: function(val) {
return val >= 0
}
},
w: {
type: Number,
default: 100,
validator: function(val) {
return val > 0
}
},
h: {
type: Number,
default: 100,
validator: function(val) {
return val > 0
}
},
x: {
type: Number,
default: 0,
validator: function(val) {
return typeof val === 'number'
}
},
y: {
type: Number,
default: 0,
validator: function(val) {
return typeof val === 'number'
}
},
z: {
type: [String, Number],
default: 'auto',
validator: function(val) {
const valid = (typeof val === 'string') ? val === 'auto' : val >= 0
return valid
}
},
dragHandle: {
type: String,
default: null
},
dragCancel: {
type: String,
default: null
},
contentClass: {
type: String,
required: false,
default: ''
}
},
data: function() {
return {
active: this.isActive,
rawWidth: this.w,
rawHeight: this.h,
rawLeft: this.x,
rawTop: this.y,
rawRight: null,
rawBottom: null,
zIndex: this.z,
parentWidth: null,
parentHeight: null,
left: this.x,
top: this.y,
right: null,
bottom: null
}
},
computed: {
width() {
return this.parentWidth - this.left - this.right
},
height() {
return this.parentHeight - this.top - this.bottom
},
rect() {
return {
left: Math.round(this.left),
top: Math.round(this.top),
width: Math.round(this.width),
height: Math.round(this.height)
}
}
},
watch: {
rawLeft(newLeft) {
const limits = this.limits
if (limits.minLeft !== null && newLeft < limits.minLeft) {
newLeft = limits.minLeft
} else if (limits.maxLeft !== null && limits.maxLeft < newLeft) {
newLeft = limits.maxLeft
}
this.left = newLeft
},
rawRight(newRight) {
const limits = this.limits
if (limits.minRight !== null && newRight < limits.minRight) {
newRight = limits.minRight
} else if (limits.maxRight !== null && limits.maxRight < newRight) {
newRight = limits.maxRight
}
this.right = newRight
},
rawTop(newTop) {
const limits = this.limits
if (limits.minTop !== null && newTop < limits.minTop) {
newTop = limits.minTop
} else if (limits.maxTop !== null && limits.maxTop < newTop) {
newTop = limits.maxTop
}
this.top = newTop
},
rawBottom(newBottom) {
const limits = this.limits
if (limits.minBottom !== null && newBottom < limits.minBottom) {
newBottom = limits.minBottom
} else if (limits.maxBottom !== null && limits.maxBottom < newBottom) {
newBottom = limits.maxBottom
}
this.bottom = newBottom
},
active(isActive) {
if (isActive) {
this.$emit('activated')
} else {
this.$emit('deactivated')
}
},
isActive(val) {
this.active = val
},
z(val) {
if (val >= 0 || val === 'auto') {
this.zIndex = val
}
},
x() {
if (this.bodyDrag) {
return
}
if (this.parentLimitation) {
this.limits = this.calcDragLimitation()
}
const delta = this.x - this.left
this.rawLeft = this.x
this.rawRight = this.right - delta
},
y() {
if (this.bodyDrag) {
return
}
if (this.parentLimitation) {
this.limits = this.calcDragLimitation()
}
const delta = this.y - this.top
this.rawTop = this.y
this.rawBottom = this.bottom - delta
},
parentW(val) {
this.right = val - this.width - this.left
this.parentWidth = val
},
parentH(val) {
this.bottom = val - this.height - this.top
this.parentHeight = val
}
},
created: function() {
this.bodyDrag = false
this.stickStartPos = { mouseX: 0, mouseY: 0, top: 0, bottom: 0, left: 0, right: 0 }
this.limits = {
minLeft: null,
maxLeft: null,
minRight: null,
maxRight: null,
minTop: null,
maxTop: null,
minBottom: null,
maxBottom: null
}
},
mounted: function() {
this.parentElement = this.$el.parentNode
this.parentWidth = this.parentW ? this.parentW : this.parentElement.clientWidth
this.parentHeight = this.parentH ? this.parentH : this.parentElement.clientHeight
this.rawRight = this.parentWidth - this.rawWidth - this.rawLeft
this.rawBottom = this.parentHeight - this.rawHeight - this.rawTop
document.documentElement.addEventListener('mousemove', this.move)
document.documentElement.addEventListener('mouseup', this.up)
document.documentElement.addEventListener('mouseleave', this.up)
document.documentElement.addEventListener('mousedown', this.deselect)
document.documentElement.addEventListener('touchmove', this.move, true)
document.documentElement.addEventListener('touchend', this.up, true)
document.documentElement.addEventListener('touchcancel', this.up, true)
// document.documentElement.addEventListener('touchstart', this.up, true)
if (this.dragHandle) {
const dragHandles = Array.prototype.slice.call(this.$el.querySelectorAll(this.dragHandle))
for (const i in dragHandles) {
dragHandles[i].setAttribute('data-drag-handle', this._uid)
}
}
if (this.dragCancel) {
const cancelHandles = Array.prototype.slice.call(this.$el.querySelectorAll(this.dragCancel))
for (const i in cancelHandles) {
cancelHandles[i].setAttribute('data-drag-cancel', this._uid)
}
}
},
beforeDestroy: function() {
document.documentElement.removeEventListener('mousemove', this.move)
document.documentElement.removeEventListener('mouseup', this.up)
document.documentElement.removeEventListener('mouseleave', this.up)
document.documentElement.removeEventListener('mousedown', this.deselect)
document.documentElement.removeEventListener('touchmove', this.move, true)
document.documentElement.removeEventListener('touchend', this.up, true)
document.documentElement.removeEventListener('touchcancel', this.up, true)
// document.documentElement.removeEventListener('touchstart', this.up, true)
},
methods: {
deselect() {
if (this.preventActiveBehavior) {
return
}
this.active = false
},
move(ev) {
if (!this.bodyDrag) {
return
}
ev.stopPropagation()
this.bodyMove(ev)
},
up(ev) {
if (this.bodyDrag) {
this.bodyUp(ev)
}
},
bodyDown: function(ev) {
const target = ev.target || ev.srcElement
if (!this.preventActiveBehavior) {
this.active = true
}
if (ev.button && ev.button !== 0) {
return
}
if (!this.active) {
return
}
if (this.dragHandle && target.getAttribute('data-drag-handle') !== this._uid.toString()) {
return
}
if (this.dragCancel && target.getAttribute('data-drag-cancel') === this._uid.toString()) {
return
}
this.$emit('clicked', ev)
ev.stopPropagation()
ev.preventDefault()
if (this.isDraggable) {
this.bodyDrag = true
}
this.stickStartPos.mouseX = typeof ev.pageX !== 'undefined' ? ev.pageX : ev.touches[0].pageX
this.stickStartPos.mouseY = typeof ev.pageY !== 'undefined' ? ev.pageY : ev.touches[0].pageY
this.stickStartPos.left = this.left
this.stickStartPos.right = this.right
this.stickStartPos.top = this.top
this.stickStartPos.bottom = this.bottom
if (this.parentLimitation) {
this.limits = this.calcDragLimitation()
}
},
calcDragLimitation() {
const parentWidth = this.parentWidth
const parentHeight = this.parentHeight
return {
minLeft: 0,
maxLeft: parentWidth - this.width,
minRight: 0,
maxRight: parentWidth - this.width,
minTop: 0,
maxTop: parentHeight - this.height,
minBottom: 0,
maxBottom: parentHeight - this.height
}
},
bodyMove(ev) {
const stickStartPos = this.stickStartPos
const pageX = typeof ev.pageX !== 'undefined' ? ev.pageX : ev.touches[0].pageX
const pageY = typeof ev.pageY !== 'undefined' ? ev.pageY : ev.touches[0].pageY
const offsetX = stickStartPos.mouseX - pageX
const offsetY = stickStartPos.mouseY - pageY
this.rawTop = stickStartPos.top - offsetY
this.rawBottom = stickStartPos.bottom + offsetY
this.rawLeft = stickStartPos.left - offsetX
this.rawRight = stickStartPos.right + offsetX
this.$emit('dragging', this.rect)
},
bodyUp() {
this.bodyDrag = false
this.$emit('dragging', this.rect)
this.$emit('dragstop', this.rect)
this.stickStartPos = { mouseX: 0, mouseY: 0, top: 0, bottom: 0, left: 0, right: 0 }
this.limits = {
minLeft: null,
maxLeft: null,
minRight: null,
maxRight: null,
minTop: null,
maxTop: null,
minBottom: null,
maxBottom: null
}
},
calcResizeLimitation() {
const width = this.width
const height = this.height
const bottom = this.bottom
const top = this.top
const left = this.left
const right = this.right
const parentLim = this.parentLimitation ? 0 : null
const limits = {
minLeft: parentLim,
maxLeft: left + (width),
minRight: parentLim,
maxRight: right + (width),
minTop: parentLim,
maxTop: top + (height),
minBottom: parentLim,
maxBottom: bottom + (height)
}
return limits
}
}
}
</script>
<style scoped>
.drag {
position: absolute;
box-sizing: border-box;
}
</style>
|
# DS_Invidudual_Project_Avery
## Introduction
Many people believe that their judgement of the best pizza is the best. However, one man’s opinion seemingly reigns the truth over the internet. His name is Dave Portnoy. Dave travels all over the United States trying out new pizza. He has over 1000 reviews and a YouTube channel with millions of subscribers. A good review from him could make a failing small business make it into a local hotspot.
Over time, as Dave’s following grew, he created an app called the One Bite app where the community can place their opinions and ratings on other pizza and try and get Dave to give his official score.
Question 1
One question to be answered is one of the oldest questions of all time. What town has the greatest pizza? Could it be the Chicago deep dish style pizza, or maybe the Detroit style rectangular pizza. And then the biggest rivalry, New York (Specifically Brookyln) VS New Haven. These two cities have been fighting for the title for many years. We will see what Dave thinks the best is.
After this we will make a linear regression model to see if the location plays a factor in Dave’s scoring.
Question 2
Let’s also create a map that displays all the Pizza Restaurants he has reviews with their pinpoints being color coded based off the score. This map is useful to someone in a new area looking for the best pizza place quickly and easily based off their own location.
Question 3
We will also look at the distribution of Dave’s and the community scoring. Let’s see if Dave and the community tend to favor rating more popular and better tasting pizza.
Question 4
In this project we are going to create a predictive model to see if we can predict what Dave will score on a restaurant based off various factors such as location, price, current community score, and amount of community reviews. These are factoring that Dave has acknowledged could change his opinion stating that “Vacation Dave gives better reviews than New York”. Meaning that when Dave is traveling to Saratoga Springs or Miami, he often gives better scores. When a pizza is more expensive, he often raises his expectations which could result in lower or higher scores as well.
## Selection of Data
Model and processing training were done using a Jupyter Notebook available [here](https://github.com/averymatwit/DS_Invidudual_Project_Avery/blob/main/codes/PizzaScoreAnalysis.ipynb)
The data I selected is directly from the app so it is from a very credible source, you could even describe it as a primary source. The data is old and not up to date with some of his current reviews but there are still over 400 in this set.
To create a more accurate model, for any community score that was null, I estimated the score based off the scores in the location and Dave’s score. Dave has claimed the community scores do often line up with his so this seemed like a fair method. I also wanted to make sure that local biases were factored into the estimated score which is why I included the average score in the location.
I created a new feature called Is_New_York to determine if Dave is reviewing the pizza in New York City (meaning he is at work) or if he is traveling. Dave has claimed this plays a factor in his scoring because of his mood while traveling.
Data file is available [here](https://github.com/averymatwit/DS_Invidudual_Project_Avery/blob/main/data/pizza_data.csv)
Data preview:

## Methods
The methods that were used was a Random Forest Regressor, this was used to train the model. This tool was preferred over others because of its compatibility with Boolean values, numerical values, and categorical values.
We also used a LinearRegression model to look at the impact longitude and latitude had on Dave’s scores.
Matplotlib and Seaborn were used to create a bar chart to display which city truly has the best pizza. Plotly express was used to create a map that shows the best pizza places in a location.
A new feature was engineered as well which was a Boolean that said if Dave was in New York or not.
The dataset was obtained through a Github user who had a similar curiosity as I did. He downloaded the data from the app and published the set.
Google Colab was used as an online IDE because of its accessability
## Results
Question 1 results
We found that the city with the best pizza is New Haven with Brooklyn in second place. Dave has controversially claimed New Haven does have the best tasting pizza with some of his favorites being Frank Pepe’s and Sally’s Pizzeria and it appears that our analysis proves his claims to be true.

Looking at the Linear Regression model we can see that the longitude and latitude play a very small, almost negligible role in Dave’s scores. The latitude and longitude show some degree of correlation, but the relationships are weak. These factors may be because of differences in pizza styles but the longitude and latitude are not as influential as other factors like community score and price level.


Question 2 results
The map successfully shows all the locations of the pizza restaurants Dave has rated. The color also accurately displays the score that was given. This color display is useful to users because the app doesn’t have a feature like this.

Question 3 results
The score distribution graphs display that the community and Dave both favors reviewing good pizza places. The community scores higher rankings and the peak is around 7 to 8. This shows that pizza places that have reviews are more popular in the community. Dave’s scores have a similar pattern, his concentration is in the 6 to 8 range. This distribution graph also shows that Dave scores a little harder than the community, especially with the lower scores where Dave has a lot more in the 0-3 range than the community.

Question 4 results
Looking at the Linear Regression model we can see that the longitude and latitude play a very small, almost negligible role in Dave’s scores. The latitude and longitude show some degree of correlation, but the relationships are weak. These factors may be because of differences in pizza styles but the longitude and latitude are not as influential as other factors like community score and price level.
When looking at the plot and the model it does appear that the community and Dave do often agree on pizza scoring. Our model had a Mean Error of 3.35 which is slightly on the higher side but not too far off. Looking at the factors, the community score has the greatest pull with an importance of 92.5% and the price category had an importance of 4% and the factor of the place being in New York or not had an importance of 2%.


## Discussion
These results can help prove the accuracy of Dave's scoring and whether or not his own claims about pizza align with his reviews. These results are important because of how big of a following Dave has on social media. His pizza reviews have great influence of millions of consumers so it is important that he gives accurate reviews and claims.
This study shows that several of Dave Portnoy's claims have been found true. His statement that New Haven has the best pizza shows in his scoring. This also shows a notable alignment between his reviews and his community review. There are correlations with another project called "The Portnoy Project" which analyzed all of Dave's reviews up to 2020. This dataset was less extensive, but its conclusions are in sync with my findings.
Future research could involve using a more up to date data set up to 2023. Additionally, implementing Yelp reviews to find correlations in addition to Dave's review, and the community review, revealing potential correlations and trends. More future research could be investigating the impact that Dave has on small buisness. Seeing the before and after of a small buisness's income could help Dave make claims on how important he is to the pizza community.
# Summary
The project deploys a Linear Regression Model and a Random Forest Model to estimate Dave's pizza review. With the Linear Regression Model we had a MSE of about 2.2 and with the Forst Model we had a MSE of 3.5.
The map will assist users to be able to quickly scan for the best pizza place in a location.
We also revealed that many of Dave's claims he makes during his videos are backed by his scores, such as New Haven being the best pizza and that the higher the price, the tougher he grades.
## References
[1] [The Portnoy Project](https://www.libertybrewtours.com/project-portnoy/)
[2] [Adventures in Barstool’s Pizza Data)](https://towardsdatascience.com/adventures-in-barstools-pizza-data-9b8ae6bb6cd1)
|
import config from './config.js'
/**
* @param {number} n
* @param {number[][]} edges
* @param {string} labels
* @return {number[]}
*/
const countSubTrees = function (n, edges, labels) {
const adj = [],
result = Array(n).fill(1)
for (const [p, c] of edges) {
if (!adj[p]) {
adj[p] = []
}
if (!adj[c]) {
adj[c] = []
}
adj[p].push(c)
adj[c].push(p)
}
const dfs = (node = 0, parent = -1) => {
const count = {}
for (const n of adj[node] || []) {
if (n !== parent) {
const _count = dfs(n, node)
for (const key in _count) {
count[key] = (count[key] || 0) + _count[key]
}
}
}
count[labels[node]] = (count[labels[node]] || 0) + 1
result[node] = count[labels[node]]
return count
}
dfs()
return result
}
// noinspection JSUnusedGlobalSymbols
export function run() {
for (const c of config) {
// noinspection JSCheckFunctionSignatures
console.log(
'Input:',
...c.input,
', Output:',
countSubTrees(...c.input),
', Expected:',
c.output
)
}
}
|
#include "main.h"
/**
* _strncpy - copies most of an inputted number
* @dest: buffer
* @src: source string
* @n: maximum number of bytes copied
* Return: a pointer to resulting string
*/
char *_strncpy(char *dest, char *src, int n)
{
int index = 0, src_len = 0;
while (src[index++])
src_len++;
for (index = 0; src[index] && index < n; index++)
dest[index] = src[index];
for (index = src_len; index < n; index++)
dest[index] = '\0';
return (dest);
}
|
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- GOOGLE FONTS -->
<!-- Key Ctrl + p >google fonts: insert <link>-->
<link href="https://fonts.googleapis.com/css?family=Roboto:regular,500,700" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css">
<!-- CSS STYLE -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
<!-- TITLE -->
<title>Beauty</title>
</head>
<body>
<!-- Header -->
<header class="header">
<div class="header__top-line">
<nav class="header__top-nav">
<ul class="header__top-list">
<li class="header__top-item">
<a href="#" class="header__top-link">Доставка</a>
</li>
<li class="header__top-item">
<a href="#" class="header__top-link">Оплата</a>
</li>
<li class="header__top-item">
<a href="#" class="header__top-link">Отзывы</a>
</li>
<li class="header__top-item">
<a href="#" class="header__top-link">Вопрос - ответ</a>
</li>
<li class="header__top-item">
<a href="#" class="header__top-link">Контакты</a>
</li>
</ul>
</nav>
</div>
<div class="container header__container">
<div class="header__second-line">
<a href="#" class="header__logo">
<img src="img/logo.svg" alt="Beauty logo" class="header__logo-img">
<span class="header__logo-text">Beauty</span>
</a>
<div class="header__phone-number">8 (812) 123-45-67</div>
<a href="#" class="header__second-line-btn btn">Обратный звонок</a>
<div class="header__menu">
<i class="fa-solid fa-bars"></i>
</div>
</div>
</div>
<div class="header__bottom-line">
<nav class="header__bottom-nav">
<ul class="header__bottom-list">
<li class="header__bottom-item">
<a href="#" class="header__bottom-link">Парикмахерская</a>
</li>
<li class="header__bottom-item">
<a href="#" class="header__bottom-link">Барбершоп</a>
</li>
<li class="header__bottom-item">
<a href="#" class="header__bottom-link">Маникюр</a>
</li>
<li class="header__bottom-item">
<a href="#" class="header__bottom-link">Педикюр</a>
</li>
<li class="header__bottom-item">
<a href="#" class="header__bottom-link">Массаж</a>
</li>
<li class="header__bottom-item">
<a href="#" class="header__bottom-link">Мебель</a>
</li>
</ul>
</nav>
</div>
</header>
<!-- Main -->
<main class="main">
<!-- Sections -->
<div class="sale">
<div class="container sale__container">
<div class="sale__heading">Супер кресло</div>
<p class="sale__text">Текст акции всегда отражает суть, а не просто <br>
болтовню, поэтому внимательнее</p>
<a href="#" class="sale__btn btn">Подробнее</a>
</div>
</div>
<section class="goods">
<div class="container goods__container">
<h1 class="goods__heading">Специальные предложения</h1>
<div class="goods__row">
<div class="goods__column">
<img src="img/kreslo.png" alt="kreslo img" class="goods__img">
<p class="goods__text">Парикмахерское кресло «Норм» гидравлическое</p>
<h3 class="goods__price">9 900 ₽</h3>
<a href="#" class="goods__btn btn">Купить</a>
</div>
<div class="goods__column">
<img src="img/kreslo.png" alt="kreslo img" class="goods__img">
<p class="goods__text">Парикмахерское кресло «Норм» гидравлическое</p>
<h3 class="goods__price">9 900 ₽</h3>
<a href="#" class="goods__btn btn">Купить</a>
</div>
<div class="goods__column">
<img src="img/kreslo.png" alt="kreslo img" class="goods__img">
<p class="goods__text">Парикмахерское кресло «Норм» гидравлическое</p>
<h3 class="goods__price">9 900 ₽</h3>
<a href="#" class="goods__btn btn">Купить</a>
</div>
<div class="goods__column">
<img src="img/kreslo.png" alt="kreslo img" class="goods__img">
<p class="goods__text">Парикмахерское кресло «Норм» гидравлическое</p>
<h3 class="goods__price">9 900 ₽</h3>
<a href="#" class="goods__btn btn">Купить</a>
</div>
</div>
</div>
</section>
<section class="subscribe-shop">
<div class="container subscribe-shop__container">
<div class="subscribe-shop__row">
<div class="subscribe-shop__column">
<div class="subscribe-shop__item">
<h2 class="subscribe-shop__heading">Получайте бонусы и подарки</h2>
<p class="subscribe-shop__text">Каждый месяц разыгрываем <br>
10 000 рублей для наших клиентов</p>
<input type="email" class="subscribe-shop__input" placeholder="Введите e-mail">
</div>
<div class="subscribe-shop__item">
<img class="subscribe-shop__item-img" src="img/envelope.png" alt="envelope img">
</div>
</div>
<div class="subscribe-shop__column">
<div class="subscribe-shop__item">
<h2 class="subscribe-shop__heading">Заходите к нам</h2>
<p class="subscribe-shop__text">Более 300 магазинов <br>
по всей России</p>
<a href="#" class="subscribe-shop__btn btn">Карта магазинов</a>
</div>
</div>
</div>
</div>
</section>
</main>
<!-- Footer -->
<footer class="footer">
<div class="container footer__container">
<div class="footer__line">
<div class="footer__socials">
<a href="" class="footer__socials-link"><i class="fa-brands fa-youtube"></i></a>
<a href="" class="footer__socials-link"><i class="fa-brands fa-vk"></i></a>
<a href="" class="footer__socials-link"><i class="fa-brands fa-facebook-f"></i></a>
<a href="" class="footer__socials-link"><i class="fa-brands fa-instagram"></i></a>
</div>
<div class="footer__address">198555, Невский пр. 140, офис 140</div>
<div class="footer__phone-number">8 (812) 123-45-67</div>
<a href="#" class="header__second-line-btn btn">Обратный звонок</a>
</div>
</div>
<div class="footer__copyright">
<div class="container container__copyright">
<p class="footer__text">
Лучший магазин (с) 2019 Все права защищены. Интернет-магазин оборудования для салонов красоты
</p>
<p class="footer__text">Политика конфиденциальности</p>
</div>
</div>
</footer>
<!-- JAVASCRIPT -->
<script src="js/script.js"></script>
</body>
</html>
|
import * as moment from 'moment';
export interface IDatabaseFriend {
last_name: string;
first_name: string;
date_of_birth: string;
email: string;
}
export class Friend {
private constructor(
readonly lastName: string,
readonly firstName: string,
readonly dOb: string,
readonly email: string
) {}
static createFromDatabaseValues(databaseFriend: IDatabaseFriend): Friend {
return new Friend(
databaseFriend.last_name,
databaseFriend.first_name,
databaseFriend.date_of_birth,
databaseFriend.email
);
}
isBirthday(): Boolean {
const parsedBirthday = moment(this.dOb, 'YYYY/MM/DD');
if (!parsedBirthday.isValid()) {
const errorMsg = `Invalid birthday ${this.dOb}`;
console.error(errorMsg);
throw new Error(errorMsg);
}
const currentDate = moment();
if (currentDate.dayOfYear() === parsedBirthday.dayOfYear()) {
return true;
}
const birthdayMonth = parsedBirthday.format('MM');
// If the month is february and the birthday is on the 29th, greet on the 28th.
if (birthdayMonth === '02' && parsedBirthday.date() === 29) {
return currentDate.date() === 28;
}
return false;
}
}
|
import 'package:connectivity_bloc/src/cubit/fetch_cats_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class CatApp extends StatefulWidget {
const CatApp({super.key});
@override
State<CatApp> createState() => _CatAppState();
}
class _CatAppState extends State<CatApp> {
late final ScrollController scrollController;
void _scrollListener() async {
final isBottom = scrollController.position.maxScrollExtent == scrollController.offset &&
scrollController.position.pixels == scrollController.position.maxScrollExtent;
if (isBottom) {
await context.read<FetchCatsCubit>().fetchCats();
}
}
@override
void initState() {
scrollController = ScrollController()..addListener(_scrollListener);
context.read<FetchCatsCubit>().fetchCats();
super.initState();
}
@override
void dispose() {
scrollController
..removeListener(_scrollListener)
..dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocListener<FetchCatsCubit, FetchCatsState>(
listener: (context, state) {
if (state is FetchCatsNoInternet) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No internet connection')),
);
}
},
child: Scaffold(
appBar: AppBar(title: const Text('Cat App')),
body: ListView(
shrinkWrap: true,
physics: const BouncingScrollPhysics(),
controller: scrollController,
children: [
GridView.builder(
shrinkWrap: true,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
),
physics: const NeverScrollableScrollPhysics(),
itemCount: context.watch<FetchCatsCubit>().catList.length,
itemBuilder: (context, index) {
final item = context.watch<FetchCatsCubit>().catList[index];
return Padding(
padding: const EdgeInsets.all(8.0),
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.grey),
image: DecorationImage(
image: NetworkImage(item.url ?? ''),
fit: BoxFit.cover,
),
),
),
);
},
),
const SizedBox(
height: 100,
child: Center(child: CircularProgressIndicator.adaptive()),
),
],
),
),
);
}
}
|
pragma solidity >= 0.4.22 < 0.6.0; //version to use in solidity or else being confused
contract ICO {
//introducing the maximum number of tokens available for sealed
uint public max_tokens = 1000000; //give investor confident (no unlimited inflation allowed)
// conversion rate
uint public usd_to_mytoken = 1000; //i.e. 0.1 cent USD per token
uint public total_tokens_sold = 0;
//mapping - This is similar to pointing two variables. Address pointing to uint type variable equity_usd.
// You can also consider mapping as sort of associative arrays. equity_usd is the total value of investment in USD
// Mapping ~ dictionary
// We need to map the user address with his equity. To do it we will use mapping keyword followed by parenthesis, address with type
// And it will be followed by variables like equity_USD or equity_tokens etc. Mapping is similar to pointing one address on some other variable.
mapping(address => uint) equity_usd;
mapping(address => uint) equity_tokens;
// This function tells the equity of investor in terms of tokens purchased
// Method to update
// check balance in terms of token or USD
function equity_in_tokens(address investor) view public returns (uint) {
return equity_tokens[investor]; // equity_tokens is resolved with mapping defined above against the investor address.
}
// This funtion tells the equity of investor in US dollars
// This function returns approximate (ceiling) value because data type is uint.
function equity_in_usd(address investor) view public returns (uint) {
return equity_usd[investor]; // equity_usd is resloved with mapping defined above.
}
// Purchase of tokens, accessor or getter methods for Equity in Tokens and US Dollar
function buy_tokens(address investor, uint usd_invested) public {
// Check the condition: if tokens are available enough
// require() --> check if condition is fulfilled
// if not fulfilled, message: 'XXX'
require(usd_invested * usd_to_mytoken + total_tokens_sold <= max_tokens, 'Token supply is not enough. Please try some less amount.');
// else execute the code below
uint tokens_bought = usd_invested * usd_to_mytoken;
// update mapped data structure for equity_tokens and equity_usd
equity_tokens[investor] += tokens_bought;
equity_usd[investor] = equity_tokens[investor] / usd_to_mytoken;
// update the amount of total sold tokens
total_tokens_sold += tokens_bought;
}
function sell_tokens(address investor, uint tokens_sold) public {
// Check if investor has enough tokens that he is trying to sell, require() provide a msg for invalid cases
require(tokens_sold <= equity_tokens[investor], 'You do not have enough token to sell. Please try some less amount.');
// update variables
equity_tokens[investor] -= tokens_sold;
equity_usd[investor] = equity_tokens[investor] / usd_to_mytoken;
total_tokens_sold -= tokens_sold;
}
}
|
<script>
$(function() {
// First component to display
components.getComponent('requests');
});
/* ----------------------------------------------------------------------
>>> LOADER
---------------------------------------------------------------------- */
var loader = (function() {
// DOM caching
const $loader = $('#loader');
function start() {
$loader.show();
}
function finish(){
$loader.hide();
}
return {
start: start,
finish: finish
}
})();
/* ----------------------------------------------------------------------
>>> COMPONENTS MODULE
---------------------------------------------------------------------- */
var components = (function() {
// DOM caching
const $mainContainer = $('#main-container');
const $window = $(window);
// Get component by string or data-component of event
function getComponent(e) {
let name;
if(typeof e === 'string'){
name = e;
}else if(e.type === "click"){
name = e.currentTarget.dataset.component;
}else{
return;
}
loader.start();
render_(name);
}
function render_(name) {
google.script.run.withSuccessHandler(_onSuccess)
.withFailureHandler(_onFailure)
.service('components', 'getComponent', name);
}
// Sets HTML content
// $.html() extracts the tags, updates the DOM and evaluates the code embedded in the script tag.
function _onSuccess(component) {
$mainContainer.empty().html(component.html);
loader.finish();
scrollTop_();
}
function _onFailure(response) {
errors.handleError(response);
loader.finish();
scrollTop_();
}
function scrollTop_() {
$window.scrollTop(0);
}
// Public pointers
return {
getComponent: getComponent
}
})();
/* ----------------------------------------------------------------------
>>> ERROR MODULE
---------------------------------------------------------------------- */
var errors = (function(){
function handleError(err){
alert(err);
}
return {
handleError: handleError
}
})();
</script>
|
require 'rails_helper'
require 'support/database_cleaner'
require 'support/devise'
RSpec.describe 'User sign out', type: :feature do
let(:user) { create(:user, email: '[email protected]') }
before do
sign_in user
end
scenario 'User sing out' do
visit '/'
click_link 'Sign out'
expect(page).to have_content('Signed out successfully.')
expect(page).to have_content('Sign in')
expect(page).to have_content('Sign up')
expect(page).not_to have_content('Sign out')
end
end
|
//importing libraries
import React from "react";
//importing stylesheets
import classes from './Overview.module.css';
//importing hooks
import { useContext } from "react";
//importing context
import AppData from "../../store/app-data";
//import UI components
import Card from "../UI/Card";
import Panel from "../UI/Panel";
const Overview = (props) => {
console.log("rendering overview component");
const appData = useContext(AppData);
let selectedThemeClass ="";
if(appData.selectedTheme==="dark"){
selectedThemeClass="dark-mode-theme";
}else if(appData.selectedTheme==="light"){
selectedThemeClass="light-mode-theme"
}else if(appData.selectedTheme==="violet"){
selectedThemeClass="violet-mode-theme"
}
return (
<Card>
<div className={classes["overview-container"]}>
<Panel heading="Income" text={`${appData.currencySymbol} ${appData.expenseData.income}`} className={`${classes[selectedThemeClass]} ${classes["income-panel"]}`}></Panel>
<Panel heading="Expenses" text={`${appData.currencySymbol} ${appData.expenseData.expense}`} className={`${classes[selectedThemeClass]} ${classes["expense-panel"]}`}></Panel>
</div>
</Card>
);
};
export default Overview;
|
<!--
An [amp-script](/content/amp-dev/documentation/components/reference/amp-script.md) hello world example.
-->
<!-- -->
<!doctype html>
<html ⚡>
<head>
<meta charset="utf-8">
<title>amp-script</title>
<link rel="canonical" href="self.html" />
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
<script async src="https://cdn.ampproject.org/v0.js"></script>
<!--
## Setup
First, you need to import the `amp-script` extension.
-->
<script async custom-element="amp-script" src="https://cdn.ampproject.org/v0/amp-script-0.1.js"></script>
<style amp-custom>
.amp-script-sample {
padding: 8px;
}
.amp-script-sample button {
background-color: #005AF0;
font-size: 16px;
font-weight: 700;
color: white;
border: none;
padding: 8px;
margin: 8px 0;
}
.amp-script-sample button[disabled] {
background-color: #f3f3f3;
color: #ccc;
}
</style>
<!--
For inline scripts you need to generate a CSP header. Read more about this in the [component documentation](/content/amp-dev/documentation/components/reference/amp-script-v0.1.md).
-->
<meta name="amp-script-src" content="sha384-X8xW7VFd-a-kgeKjsR4wgFSUlffP7x8zpVmqC6lm2DPadWUnwfdCBJ2KbwQn6ADE sha384-nNFaDRiLzgQEgiC5kP28pgiJVfNLVuw-nP3VBV-e2s3fOh0grENnhllLfygAuU_M sha384-u7NPnrcs7p4vsbGLhlYHsId_iDJbcOWxmBd9bhVuPoA_gM_he4vyK6GsuvFvr2ym">
</head>
<body>
<!--
## Basic usage
An amp-script element can load a JavaScript file from a URL. This is usually the best way to integrate a script as the browser needs to download the script only once.
-->
<amp-script layout="container" src="<% hosts.platform %>/documentation/examples/components/amp-script/hello-world.js" class="amp-script-sample" >
<button id="hello">Click!</button>
</amp-script>
<!--
This is the script in [hello-world.js](hello-world.js):
```js
const button = document.getElementById('hello');
button.addEventListener('click', () => {
const h1 = document.createElement('h1');
h1.textContent = 'Hello World!';
document.body.appendChild(h1);
});```
## Inline Scripts
You can also declare scripts inline and reference them by `id`.
-->
<amp-script layout="container" script="hello-world" class="amp-script-sample">
<button id="hello2">Click!</button>
</amp-script>
<!--
This is the inlined script. Note that the type needs to be `type=text/plain` and the `target=amp-script`.
-->
<script id="hello-world" type="text/plain" target="amp-script">
const button = document.getElementById('hello2');
button.addEventListener('click', () => {
const h1 = document.createElement('h1');
h1.textContent = 'Hello World 2!';
document.body.appendChild(h1);
});
</script>
<!-- Note: `document.body` refers to the `amp-script` tag and not the actual `body` tag. `document.body.appendChild(...)` actually adds an element inside the `amp-script` element. -->
<!--
## Using the fetch API
`amp-script` supports using the fetch API. To be able to update the page on load, we need to use the `fixed-height` layout instead of the `container` layout (and the height needs to be less than `300px`).
-->
<amp-script layout="fixed-height" height="32" script="time-script" class="amp-script-sample">
<div>The time is: <span id="time"></span></div>
</amp-script>
<!-- As `amp-script` code is executed inside a web worker, fetch only works with absolute URLs. -->
<script id="time-script" type="text/plain" target="amp-script">
const fetchCurrentTime = async () => {
const response = await fetch('<% hosts.platform %>/documentation/examples/api/time');
const data = await response.json();
const div = document.getElementById('time');
div.textContent = data.time;
}
fetchCurrentTime();
</script>
<!--
## Custom form validation
You can also use `amp-script` to implement custom form validation. Here we set the
`disabled` state of a button based on the input value.
-->
<amp-script layout="container" script="form-validation-script" class="amp-script-sample" sandbox="allow-forms">
<input id="validated-input" placeholder="Only upper case letters allowed...">
<button id="validated-input-submit" disabled>Submit</button>
</amp-script>
<!-- The script adds events listeners to the input elements and sets the `disabled` state based on a custom regex. -->
<script id="form-validation-script" type="text/plain" target="amp-script">
const submitButton = document.getElementById('validated-input-submit');
const validatedInput = document.getElementById('validated-input');
validatedInput.addEventListener('input', () => {
const isValid = /^[A-Z]+$/.test(validatedInput.value);
if (isValid) {
submitButton.removeAttribute('disabled');
} else {
submitButton.setAttribute('disabled', '');
}
});
</script>
<!--
## Detecting Android vs iOS in AMP
`amp-script` is great to implement functionality not offered by AMP out-of-the-box. Here is a sample that checks if the current device is using Android or iOS.
-->
<amp-script layout="container" script="user-agent-script" class="amp-script-sample">
<div>Your user-agent is: <span id="user-agent">other</span></div>
</amp-script>
<!-- The script implementation retrieves the mobile operating system from the user agent string. -->
<script id="user-agent-script" type="text/plain" target="amp-script">
function getMobileOperatingSystem() {
const userAgent = navigator.userAgent;
if (/android/i.test(userAgent)) {
return "Android";
}
// iOS detection from: http://stackoverflow.com/a/9039885/177710
if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
return "iOS";
}
return "other";
}
const span = document.getElementById('user-agent');
span.textContent = getMobileOperatingSystem();
const pre = document.createElement('pre');
pre.textContent = navigator.userAgent;
span.appendChild(pre);
</script>
</body>
</html>
|
:root {
--PrimaryColor: hsl(199, 100%, 33%);
--SecondaryColor: hsl(187, 85%, 43%);
--gradientColor: linear-gradient(
to right,
hsl(187, 85%, 43%),
hsl(199, 100%, 33%)
);
--whiteColor: hsl(0, 0%, 100%);
--blackColor: hsl(201, 33%, 16%);
--textColor: hsl(240, 4%, 36%);
--whiteColorDeam: hsl(0, 0%, 93%);
--greyText: rgb(190, 190, 190);
--inputColor: rgb(239, 239, 239);
--bodyColor: rgb(240, 240, 246);
--cardBG: rgb(225, 225, 235);
}
.footer {
width: 100%;
position: relative;
padding: 2rem 0;
display: flex;
justify-content: center;
align-items: center;
margin: auto;
.videoDiv {
position: absolute;
width: 100%;
height: 100%;
video {
height: 100%;
object-fit: cover;
}
&::after {
content: "";
position: absolute;
background: rgba(34, 82, 97, 0.307);
top: 0;
bottom: 0;
left: 0;
right: 0;
mix-blend-mode: multiply;
}
}
.secContainer {
width: 100%;
height: max-content;
display: flex;
flex-direction: column;
text-align: center;
justify-content: center;
padding: 2rem initial;
margin: auto;
row-gap: 2rem;
z-index: 100;
.contactDiv {
justify-content: space-between;
flex-direction: column;
gap: 1rem;
.text {
small {
font-size: 18px;
color: var(--whiteColor);
font-weight: 400;
}
h2 {
font-size: 1.8rem;
color: var(--whiteColor);
font-weight: 600;
}
}
.inputDiv {
width: 100%;
flex-direction: column;
gap: 1rem;
input {
width: 100%;
padding: 0.5rem 0.6rem;
border-radius: 3rem;
border: 1px solid var(--whiteColor);
outline: none;
background: transparent;
color: var(--whiteColor);
&::placeholder {
opacity: 0.9;
color: var(--whiteColor);
}
}
.btn {
color: var(--whiteColor);
font-weight: 500;
font-size: 18px;
width: 100%;
justify-content: center;
gap: 1rem;
.icon {
font-size: 19px;
}
}
}
}
.footerCard {
background: var(--bodyColor);
position: relative;
width: 100%;
padding: 1rem 1rem 4rem;
gap: 2rem;
border-radius: 1rem;
justify-content: center;
flex-direction: column;
align-items: flex-start;
overflow: hidden;
.footerIntro {
flex-basis: 50%;
flex-direction: column;
justify-content: center;
align-items: flex-start;
row-gap: 0.5rem;
.logoDiv {
.logo {
color: var(--blackColor);
font-weight: 600;
font-size: 1.2rem;
}
.icon {
color: var(--PrimaryColor);
font-size: 25px;
margin-right: 9px;
}
}
.footerPara {
font-size: 15px;
color: var(--textColor);
}
.footerSocial {
column-gap: 0.5rem;
.icon {
color: var(--blackColor);
font-size: 24px;
&:hover {
color: var(--PrimaryColor);
}
}
}
}
.footerLink {
grid-template-columns: repeat(2, 1fr);
flex-basis: 50%;
width: 100%;
gap: 1rem;
justify-content: space-between;
.linkGrp {
.footerTitle {
display: block;
font-weight: 600;
color: var(--blackColor);
margin-bottom: 0.5rem;
}
.footerList {
color: var(--textColor);
font-size: 15px;
transition: 0.3s ease-in-out;
// cursor: pointer;
.icon {
font-size: 15px;
color: var(--greyText);
}
&:hover {
color: var(--PrimaryColor);
transform: translateX(7px);
.icon {
color: var (--SecondaryColor);
}
}
}
}
}
}
}
}
//media queries
@media screen and (min-width: 500px) {
.footer {
.secContainer {
.footerCard {
.footerLink {
grid-template-columns: repeat(3, 1fr);
padding-bottom: 1rem;
}
.contactDiv {
justify-content: space-between;
flex-direction: row;
small {
font-size: 14px;
color: var(--textColor);
}
}
}
}
}
}
@media screen and (min-width: 660px) {
.footer {
.secContainer {
.contactDiv {
flex-direction: row;
justify-content: space-between;
.inputDiv {
width: max-content;
flex-direction: row;
justify-content: flex-start;
input {
width: 60%;
}
.btn {
width: max-content;
}
}
}
}
}
}
@media screen and (min-width: 840px) {
.footer {
padding: 5rem 0;
.secContainer {
.footerCard{
flex-direction: row;
.footerLink{
grid-template-columns: repeat(3,1fr);
}
}
}
}
}
@media screen and (min-width: 1024px) {
.footer {
.secContainer{
.footerCard{
padding: 3rem 1rem;
.footerIntro{
.footerPara{
font-size: 15px;
color: var(--textColor);
}
.footerSocial{
column-gap: .5rem;
.icon{
color: var(--textColor);
font-size: 25px;
&:hover{
color: var(--PrimaryColor);
}
}
}
}
.footerLink {
.linkGrp{
.footerList{
font-size: 16px;
padding: 5px 0;
}
}
}
}
}
}
}
|
import {JSX, useMemo, useState} from "react";
import { Form, Mentions } from "antd";
import { useAppSelector } from "../../store/store.ts";
import {IComment} from "../../types/types.ts";
interface IMention {
formItemName: string;
rows?: number;
placeholder?: string;
commentToEdit?: IComment
}
export const CustomMention = (props: IMention): JSX.Element => {
const [commentBody, setCommentBody] = useState<string>("");
const { placeholder = "Add a comment…", rows = 4, formItemName } = props;
const { users } = useAppSelector((state) => state.commentsData);
const options = useMemo(() => {
return users.map((user) => ({
value: user.username,
label: user.username,
}));
}, [users]);
return (
<Form.Item name={formItemName} style={{ width: "100%", marginBottom: 0 }} rules={[
{
required: true,
message: '',
},
]}>
<Mentions
rows={rows}
placeholder={placeholder}
options={options}
value={commentBody}
onChange={setCommentBody}
/>
</Form.Item>
);
};
|
import Badge from "@/components/badge";
import { PostModel } from "@/model/post.model";
import { API_ENDPOINTS, fetchData } from "@/service/api/api.service";
import { getRelativeTime } from "@/utils/time.utils";
import Image from "next/image";
import { FunctionComponent } from "react";
import PostsPage from "../components/posts_list";
interface CategoryPageProps {
category_name: string;
}
const CategoryPage: FunctionComponent<CategoryPageProps> = async (props) => {
const category_name = props.category_name;
const _posts: PostModel[] = await fetchData(
API_ENDPOINTS.POSTS_BY_CATEGORY,
{
category_name: category_name,
}
);
const firstPost: PostModel = await fetchData(
API_ENDPOINTS.POST_OUTSTANDING_CATEGORY,
{
category_name: category_name,
}
);
const isLessThanTwoPost = _posts.length < 2;
const posts = isLessThanTwoPost ? _posts : _posts.filter((post) => post.id != firstPost?.id)
const isCategoryNotValid = posts == null;
return (
<>
<div>
<div className="flex justify-center items-center">
<p className="my-10 text-xl font-semibold leading-10">
{isCategoryNotValid ? "" : category_name.toUpperCase()}
</p>
</div>
{isCategoryNotValid || posts.length < 1 || isLessThanTwoPost ? (
<></>
) : (
<div className="mb-10 flex relative">
<div
className="text-white rounded-[12px] w-full h-[400px] bg-slate-300 bg-cover bg-center bg-no-repeat"
style={{
backgroundImage: `url('${firstPost.thumbImageUrl}')`,
}}
>
<div className="absolute inset-0 bg-black opacity-50 rounded-[12px]"></div>
<div className="mx-6 sm:mt-3 md:mt-48 absolute sm:top-1/2 md:top-1/4 lg:top-1/4 top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-full">
<div className="flex">
{firstPost.categories.map((category) => (
<>
<div className="mr-1">
<Badge
key={category.id}
value={category.name}
/>
</div>
</>
))}
</div>
<p className="mt-1 text-2xl font-semibold leading-10 ">
{firstPost.title}
</p>
<div className="flex mt-1 items-center">
<div className="flex items-center">
<Image
className="avatar-sm mr-2"
alt=""
src="/avatar.jpg"
width={256}
height={256}
/>
<p>{firstPost.author.displayName}</p>
</div>
<div className="ms-10">
<p>{getRelativeTime(firstPost.createdDate)}</p>
</div>
</div>
</div>
</div>
</div>
)}
<div>
<PostsPage posts={posts} />
</div>
</div>
</>
);
};
export default CategoryPage;
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\ItemModel;
use App\Models\InstitutionModel;
use App\Models\RoomModel;
use App\Models\CategoryModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use App\Exports\ItemExport;
use Carbon\Carbon;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Validator;
class ItemController extends Controller
{
public function item_admin()
{
$items = ItemModel::orderBy('item_id', 'desc')->get();
$title = "Item";
foreach ($items as $item) {
$institution = DB::table('ms_institution')->select('institution_name')->where('institution_id', $item->institution_id)->first();
$room = DB::table('ms_room')->select('room_name')->where('room_id', $item->room_id)->first();
$category = DB::table('ms_category')->select('category_name')->where('category_id', $item->category_id)->first();
$item->institution_name = $institution ? $institution->institution_name : null;
$item->room_name = $room ? $room->room_name : null;
$item->category_name = $category ? $category->category_name : null;
}
$data = [
'items' => $items,
'title' => $title,
];
return view('admin.item.index', compact('data'));
}
public function item_user()
{
$items = ItemModel::orderBy('item_id', 'desc')->get();
$title = "Item";
foreach ($items as $item) {
$institution = DB::table('ms_institution')->select('institution_name')->where('institution_id', $item->institution_id)->first();
$room = DB::table('ms_room')->select('room_name')->where('room_id', $item->room_id)->first();
$category = DB::table('ms_category')->select('category_name')->where('category_id', $item->category_id)->first();
$item->institution_name = $institution ? $institution->institution_name : null;
$item->room_name = $room ? $room->room_name : null;
$item->category_name = $category ? $category->category_name : null;
}
$data = [
'items' => $items,
'title' => $title,
];
return view('user.item.index', compact('data'));
}
public function item_show_admin($id)
{
$item = ItemModel::with('institution')
->with('room')
->with('category')
->where('item_id', '=', $id)
->first();
$title = "Item Details";
$data = [
'item' => $item,
'title' => $title,
];
// dd($data);
return view('admin.item.show', compact('data'));
}
public function item_show_user($id)
{
$item = ItemModel::with('institution')
->with('room')
->with('category')
->where('item_id', '=', $id)
->first();
$title = "Item Details";
$data = [
'item' => $item,
'title' => $title,
];
// dd($data);
return view('user.item.show', compact('data'));
}
public function item_room_admin($id)
{
$title = DB::table('ms_room')->where('room_id', '=', $id)->get();
$items = DB::table('ms_item')
->where('room_id', $id)
->orderBy('item_id', 'desc')
->get();
$total_item = count($items);
$total_price = $items->sum('item_price');
$total_price_formated = "Rp " . number_format($total_price, 0, ',', '.');
foreach ($items as $item) {
$institution = DB::table('ms_institution')->select('institution_name')->where('institution_id', $item->institution_id)->first();
$room = DB::table('ms_room')->select('room_name')->where('room_id', $item->room_id)->first();
$category = DB::table('ms_category')->select('category_name')->where('category_id', $item->category_id)->first();
$item->institution_name = $institution ? $institution->institution_name : null;
$item->room_name = $room ? $room->room_name : null;
$item->category_name = $category ? $category->category_name : null;
}
$data = [
'title' => $title,
'items' => $items,
'total_item' => $total_item,
'total_price' => $total_price_formated
];
return view('admin.item.room.index', compact('data'));
}
public function item_room_user($id)
{
$title = DB::table('ms_room')->where('room_id', '=', $id)->get();
$items = DB::table('ms_item')
->where('room_id', $id)
->orderBy('item_id', 'desc')
->get();
$total_item = count($items);
$total_price = $items->sum('item_price');
$total_price_formated = "Rp " . number_format($total_price, 0, ',', '.');
foreach ($items as $item) {
$institution = DB::table('ms_institution')->select('institution_name')->where('institution_id', $item->institution_id)->first();
$room = DB::table('ms_room')->select('room_name')->where('room_id', $item->room_id)->first();
$category = DB::table('ms_category')->select('category_name')->where('category_id', $item->category_id)->first();
$item->institution_name = $institution ? $institution->institution_name : null;
$item->room_name = $room ? $room->room_name : null;
$item->category_name = $category ? $category->category_name : null;
}
$data = [
'title' => $title,
'items' => $items,
'total_item' => $total_item,
'total_price' => $total_price_formated
];
return view('user.item.room.index', compact('data'));
}
public function item_room_edit($id)
{
$item = DB::table('ms_item')->where('item_id', '=', $id)->first();
$institution = InstitutionModel::all();
$room = RoomModel::all();
$category = CategoryModel::all();
$data =
[
'item' => $item,
'institution' => $institution,
'room' => $room,
'category' => $category
];
return view('admin.item.room.edit', compact('data'));
}
public function item_room_update(Request $request, $item_id)
{
$item = ItemModel::find($item_id);
if (!$item) {
Session::flash('error', 'Item not found.');
return redirect()->route('admin.item');
}
Session::flash('txtItemName', $request->txtItemName);
Session::flash('txtItemBrand', $request->txtItemBrand);
Session::flash('txtItemType', $request->txtItemType);
Session::flash('txtItemName', $request->txtItemName);
Session::flash('txtItemPrice', $request->txtItemPrice);
Session::flash('txtSerialNumber', $request->txtSerialNumber);
Session::flash('notes', $request->notes);
Session::flash('room_id', $request->room_id);
$request->validate([
'txtItemName' => 'required',
'txtItemPrice' => 'required',
], [
'txtItemName.required' => 'Item Name Required.',
'txtItemPrice.required' => 'Item Price Required.',
]);
$data = [
'item_name' => $request->input('txtItemName'),
'item_brand' => $request->input('txtItemBrand'),
'item_type' => $request->input('txtItemType'),
'item_price' => $request->input('txtItemPrice'),
'serial_number' => $request->input('txtSerialNumber'),
'notes' => $request->input('txtNotes'),
];
$room_id = $request->input('room_id');
$item->update($data);
Session::flash('success', 'Data successfully updated.');
return redirect()->route('admin.item.room', $room_id);
}
public function item_room_show_admin($id)
{
$item = ItemModel::with('institution')
->with('room')
->with('category')
->where('item_id', '=', $id)
->first();
$title = "Item Details";
$data = [
'item' => $item,
'title' => $title,
];
// dd($data);
return view('admin.item.room.show', compact('data'));
}
public function item_room_show_user($id)
{
$item = ItemModel::with('institution')
->with('room')
->with('category')
->where('item_id', '=', $id)
->first();
$title = "Item Details";
$data = [
'item' => $item,
'title' => $title,
];
// dd($data);
return view('user.item.room.show', compact('data'));
}
public function item_room_destroy($item_id, $room_id)
{
ItemModel::find($item_id)->delete();
Session::flash('success', 'Data successfully deleted.');
return redirect()->route('admin.item.room', $room_id);
}
public function item_create()
{
$institution = InstitutionModel::all();
$room = RoomModel::all();
$category = CategoryModel::all();
$title = "ITEM";
$data = [
'institutions' => $institution,
'room' => $room,
'category' => $category,
'title' => $title
];
return view('admin.item.add', compact('data'));
}
public function item_store(Request $request)
{
$ItemModel = new ItemModel();
Session::flash('txtItemName', $request->txtItemName);
Session::flash('txtItemPrice', $request->txtItemPrice);
Session::flash('txtItemBrand', $request->txtItemBrand);
Session::flash('txtItemType', $request->txtItemType);
Session::flash('txtItemQty', $request->txtItemQty);
Session::flash('selInstitution', $request->selInstitution);
Session::flash('txtSerialNumber', $request->txtSerialNumber);
$institution = DB::table('ms_institution')->where('institution_id', '=', $request->selInstitution)->first();
if ($institution) {
Session::flash('txtInstitution', $institution->institution_name);
}
Session::flash('selRoom', $request->selRoom);
$room = DB::table('ms_room')->where('room_id', '=', $request->selRoom)->first();
if ($room) {
Session::flash('txtRoom', $room->room_name);
}
Session::flash('selCategory', $request->selCategory);
$category = DB::table('ms_category')->where('category_id', '=', $request->selCategory)->first();
if ($category) {
Session::flash('txtCategory', $category->category_name);
}
Session::flash('txtPurchaseDate', $request->txtPurchaseDate);
Session::flash('txtItemNotes', $request->txtItemNotes);
$request->validate([
'txtItemName' => 'required',
'txtItemPrice' => 'required',
'selInstitution' => 'integer|required',
'selRoom' => 'integer|required',
'selCategory' => 'integer|required',
// 'txtPurchaseDate' => 'required',
], [
'txtItemName.required' => 'Item Name Required.',
'txtItemPrice.required' => 'Item Price Required.',
'selInstitution.integer' => 'Please Choose Item Institution.',
'selInstitution.required' => 'Please Choose Item Institution.',
'selRoom.integer' => 'Please Choose the Item Room.',
'selRoom.required' => 'Please Choose the Item Room.',
'selCategory.integer' => 'Please Choose the Item Category.',
'selCategory.required' => 'Please Choose the Item Category.',
// 'txtPurchaseDate.required' => 'Please fill the Purchase Date.',
]);
$itemQty = $request->input('txtItemQty');
$itemName = $request->input('txtItemName');
$itemBrand = $request->input('txtItemBrand');
$itemType = $request->input('txtItemType');
$serialNumber = $request->input('txtSerialNumber');
$notes = $request->input('txtNotes');
$itemPrice = intval(str_replace(',', '', $request->input('txtItemPrice')));
$institution_id = intval($request->input('selInstitution'));
$category_id = intval($request->input('selCategory'));
$institution = InstitutionModel::find($request->input('selInstitution'));
if (!empty($institution->institution_code)) {
$institutionCode = $institution->institution_code;
}
$room = RoomModel::find($request->input('selRoom'));
if (!empty($room->room_code)) {
$roomCode = $room->room_code;
}
$purchase_date = $request->input('txtPurchaseDate');
$room_id = intval($request->input('selRoom'));
$lastItem = ItemModel::where('room_id', $room_id)
->orderBy('item_id', 'desc')
->first();
$sequenceNumber = $lastItem ? intval(substr($lastItem->item_code, -3)) + 1 : 1;
for ($i = 0; $i < $itemQty; $i++) {
if (!empty($purchase_date)) {
$purchase_date = $request->input('txtPurchaseDate');
} else {
$purchase_date = false;
}
$code = $this->itemCode($institutionCode, $roomCode, $purchase_date, $room_id, $sequenceNumber);
if ($purchase_date === false) {
$purchase_date = null;
}
$data = [
'item_name' => $itemName,
'item_brand' => $itemBrand,
'item_type' => $itemType,
'item_price' => $itemPrice,
'item_qty' => $itemQty,
'item_code' => $code,
'institution_id' => $institution_id,
'room_id' => $room_id,
'category_id' => $category_id,
'serial_number' => $serialNumber,
'purchase_date' => $purchase_date,
'notes' => $notes,
];
// dd($data);
$insert = ItemModel::create($data);
// dd($insert);
$sequenceNumber++;
}
Session::flash('success', 'Data successfully Inserted.');
return redirect()->route('admin.item');
}
public function item_edit($id)
{
$item = DB::table('ms_item')->where('item_id', '=', $id)->first();
$institution = InstitutionModel::all();
$room = RoomModel::all();
$category = CategoryModel::all();
$data = [$item, $institution, $room, $category];
return view('admin.item.edit', compact('data'));
}
public function item_update(Request $request, $id)
{
$item = ItemModel::find($id);
if (!$item) {
Session::flash('error', 'Item not found.');
return redirect()->route('admin.item');
}
Session::flash('txtItemName', $request->txtItemName);
Session::flash('txtItemBrand', $request->txtItemBrand);
Session::flash('txtItemType', $request->txtItemType);
Session::flash('txtItemName', $request->txtItemName);
Session::flash('txtItemPrice', $request->txtItemPrice);
Session::flash('txtSerialNumber', $request->txtSerialNumber);
Session::flash('notes', $request->notes);
$request->validate([
'txtItemName' => 'required',
'txtItemPrice' => 'required',
], [
'txtItemName.required' => 'Item Name Required.',
'txtItemPrice.required' => 'Item Price Required.',
]);
$data = [
'item_name' => $request->input('txtItemName'),
'item_brand' => $request->input('txtItemBrand'),
'item_type' => $request->input('txtItemType'),
'item_price' => $request->input('txtItemPrice'),
'serial_number' => $request->input('txtSerialNumber'),
'notes' => $request->input('txtNotes'),
];
$item->update($data);
Session::flash('success', 'Data successfully updated.');
return redirect()->route('admin.item');
}
public function item_export()
{
$columns = [
'ms_item.*',
'ms_institution.institution_name',
'ms_room.room_name',
'ms_category.category_name',
];
$data = ItemModel::select($columns)
->join('ms_institution', 'ms_institution.institution_id', '=', 'ms_item.institution_id')
->join('ms_room', 'ms_room.room_id', '=', 'ms_item.room_id')
->join('ms_category', 'ms_category.category_id', '=', 'ms_item.category_id')
->get();
return Excel::download(new ItemExport($data), 'All_item |' . Carbon::now()->timestamp . '.xlsx');
}
public function item_room_export($room_id)
{
$roomName = RoomModel::where('room_id', $room_id)->value('room_name');
$data = ItemModel::select([
'ms_item.*',
'ms_institution.institution_name AS institution_name',
'ms_room.room_name AS room_name',
'ms_category.category_name AS category_name',
])
->join('ms_institution', 'ms_institution.institution_id', '=', 'ms_item.institution_id')
->join('ms_room', 'ms_room.room_id', '=', 'ms_item.room_id')
->join('ms_category', 'ms_category.category_id', '=', 'ms_item.category_id')
->where('ms_item.room_id', '=', $room_id)
->get();
return Excel::download(new ItemExport($data), 'Item |' . $roomName . '|' . Carbon::now()->timestamp . '.xlsx');
}
public function item_destroy($id)
{
ItemModel::find($id)->delete();
Session::flash('success', 'Data successfully deleted.');
return redirect()->route('admin.item');
}
}
|
//
// CustomButton.swift
// SwiftDemos
//
// Created by minjing.lin on 2021/11/30.
//
import UIKit
class CustomButton: UIButton {
//MARK: -定义button相对label的位置
enum RGButtonImagePosition {
case top //图片在上,文字在下,垂直居中对齐
case bottom //图片在下,文字在上,垂直居中对齐
case left //图片在左,文字在右,水平居中对齐
case right //图片在右,文字在左,水平居中对齐
}
var positionStyle = RGButtonImagePosition.top
var positionSpacing : CGFloat = 0
/// - Description 设置Button图片的位置
/// - Parameters:
/// - style: 图片位置
/// - spacing: 按钮图片与文字之间的间隔
func imagePosition(style: RGButtonImagePosition, spacing: CGFloat) {
//得到imageView和titleLabel的宽高
positionStyle = style
positionSpacing = spacing
}
func layoutWith(style: RGButtonImagePosition, spacing: CGFloat) {
let imageWidth = self.imageView?.frame.size.width
let imageHeight = self.imageView?.frame.size.height
var labelWidth: CGFloat! = 0.0
var labelHeight: CGFloat! = 0.0
labelWidth = self.titleLabel?.intrinsicContentSize.width
labelHeight = self.titleLabel?.intrinsicContentSize.height
//初始化imageEdgeInsets和labelEdgeInsets
var imageEdgeInsets = UIEdgeInsets.zero
var labelEdgeInsets = UIEdgeInsets.zero
//根据style和space得到imageEdgeInsets和labelEdgeInsets的值
switch style {
case .top:
//上 左 下 右
imageEdgeInsets = UIEdgeInsets(top: -labelHeight-spacing/2, left: 0, bottom: 0, right: -labelWidth)
labelEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth!, bottom: -imageHeight!-spacing/2, right: 0)
break;
case .left:
imageEdgeInsets = UIEdgeInsets(top: 0, left: -spacing/2, bottom: 0, right: spacing)
labelEdgeInsets = UIEdgeInsets(top: 0, left: spacing/2, bottom: 0, right: -spacing/2)
break;
case .bottom:
imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -labelHeight!-spacing/2, right: -labelWidth)
labelEdgeInsets = UIEdgeInsets(top: -imageHeight!-spacing/2, left: -imageWidth!, bottom: 0, right: 0)
break;
case .right:
imageEdgeInsets = UIEdgeInsets(top: 0, left: labelWidth+spacing/2, bottom: 0, right: -labelWidth-spacing/2)
labelEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth!-spacing/2, bottom: 0, right: imageWidth!+spacing/2)
break;
}
self.titleEdgeInsets = labelEdgeInsets
self.imageEdgeInsets = imageEdgeInsets
}
override func layoutSubviews() {
super.layoutSubviews()
self.layoutWith(style: positionStyle, spacing: positionSpacing)
}
}
|
import Foundation
import YandexMobileAdsInstream
import AVFoundation
class AdPlayerErrorConverter {
func convert(_ reason: InstreamAdPlayerErrorReason) -> InstreamAdPlayerError {
.init(reason: reason)
}
func convert(_ error: Error?) -> InstreamAdPlayerError {
guard let error = error as NSError? else {
return .init(reason: .unknown)
}
let reason: InstreamAdPlayerErrorReason
switch error.domain {
case AVFoundationErrorDomain where error.code == AVError.serverIncorrectlyConfigured.rawValue:
reason = .invalidFile
case NSURLErrorDomain where error.code == NSURLErrorFileDoesNotExist,
NSURLErrorDomain where error.code == NSURLErrorNoPermissionsToReadFile:
reason = .fileNotFound
case NSURLErrorDomain where error.code == NSURLErrorTimedOut:
reason = .timedOut
case NSURLErrorDomain where error.code == NSURLErrorNotConnectedToInternet:
reason = .netwrokUnavailable
case AVFoundationErrorDomain where error.code == AVError.fileFormatNotRecognized.rawValue:
reason = .unsupportedFileFormat
case AVFoundationErrorDomain where error.code == AVError.unknown.rawValue:
reason = reasonForUnknownAVError(error)
default:
reason = .unknown
}
return .init(reason: reason, underlyingError: error)
}
private final func reasonForUnknownAVError(_ error: NSError) -> InstreamAdPlayerErrorReason {
guard let underlyingError = error.underlyingError, underlyingError.isAVFormatError else {
return .fileNotFound
}
return .unsupportedCodec
}
}
private extension InstreamAdPlayerError {
convenience init(reason: InstreamAdPlayerErrorReason) {
self.init(reason: reason, underlyingError: EmptyError())
}
private struct EmptyError: Error {}
}
private extension Error {
var underlyingError: Error? {
let nsError = self as NSError
guard #available(iOS 14.5, *) else {
return nsError.userInfo[NSUnderlyingErrorKey] as? Error
}
return nsError.underlyingErrors.first
}
}
private let kAVErrorFourCharCode = "AVErrorFourCharCode"
private let AVErrorFourCharCodeFormat = "\'fmt?\'"
private extension Error {
var isAVFormatError: Bool {
let nsError = self as NSError
guard let errorFourCharCode = nsError.userInfo[kAVErrorFourCharCode] as? String else {
return false
}
return nsError.domain == NSOSStatusErrorDomain && errorFourCharCode == AVErrorFourCharCodeFormat
}
}
|
// import { NgModule } from "@angular/core";
// import { CoreModule } from "./admin/core/core.module";
// import { SharedModule } from "./admin/shared/shared.module";
// import { BrowserModule } from "@angular/platform-browser";
// import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
// import { AppRoutingModule } from "./app-routing.module";
// import { AppComponent } from "./app.component";
// import { HeaderComponent } from "./admin/layout/header/header.component";
// import { PageLoaderComponent } from "./admin/layout/page-loader/page-loader.component";
// import { SidebarComponent } from "./admin/layout/sidebar/sidebar.component";
// import { RightSidebarComponent } from "./admin/layout/right-sidebar/right-sidebar.component";
// import { AuthLayoutComponent } from "./admin/layout/app-layout/auth-layout/auth-layout.component";
// import { MainLayoutComponent } from "./admin/layout/app-layout/main-layout/main-layout.component";
// import { fakeBackendProvider } from "./admin/core/interceptor/fake-backend";
// import { ErrorInterceptor } from "./admin/core/interceptor/error.interceptor";
// import { JwtInterceptor } from "./admin/core/interceptor/jwt.interceptor";
// import { LocationStrategy, HashLocationStrategy } from "@angular/common";
// import { FormsModule } from '@angular/forms';
// import {
// PerfectScrollbarModule,
// PERFECT_SCROLLBAR_CONFIG,
// PerfectScrollbarConfigInterface,
// } from "ngx-perfect-scrollbar";
// import { TranslateModule, TranslateLoader } from "@ngx-translate/core";
// import { TranslateHttpLoader } from "@ngx-translate/http-loader";
// import { ClickOutsideModule } from "ng-click-outside";
// import {
// HttpClientModule,
// HTTP_INTERCEPTORS,
// HttpClient,
// } from "@angular/common/http";
// import { LoadingBarRouterModule } from "@ngx-loading-bar/router";
// import { environment } from "src/environments/environment.prod";
// import { AuthComponent } from './admin/layout/auth/auth.component';
// const DEFAULT_PERFECT_SCROLLBAR_CONFIG: PerfectScrollbarConfigInterface = {
// suppressScrollX: true,
// wheelPropagation: false,
// };
// if (environment.production) {
// // // disable all console output in production mode
// // console.log = function() {};
// // console.warn = function() {};
// // console.error = function() {};
// }
// export function createTranslateLoader(http: HttpClient): any {
// return new TranslateHttpLoader(http, "assets/i18n/", ".json");
// }
// @NgModule({
// declarations: [
// AppComponent,
// HeaderComponent,
// PageLoaderComponent,
// SidebarComponent,
// RightSidebarComponent,
// AuthLayoutComponent,
// MainLayoutComponent,
// AuthComponent,
// ],
// imports: [
// BrowserModule,
// BrowserAnimationsModule,
// AppRoutingModule,
// HttpClientModule,
// FormsModule,
// PerfectScrollbarModule,
// ClickOutsideModule,
// TranslateModule.forRoot({
// loader: {
// provide: TranslateLoader,
// useFactory: createTranslateLoader,
// deps: [HttpClient],
// },
// }),
// LoadingBarRouterModule,
// // core & shared
// CoreModule,
// SharedModule,
// ],
// providers: [
// { provide: LocationStrategy, useClass: HashLocationStrategy },
// {
// provide: PERFECT_SCROLLBAR_CONFIG,
// useValue: DEFAULT_PERFECT_SCROLLBAR_CONFIG,
// },
// { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
// { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
// fakeBackendProvider,
// //AutoLogoutService
// ],
// bootstrap: [AppComponent],
// })
// export class AppModule { }
|
import { MenuItem } from '@material-ui/core'
import AppBar from '@material-ui/core/AppBar'
import Button from '@material-ui/core/Button'
import Dialog from '@material-ui/core/Dialog'
import DialogActions from '@material-ui/core/DialogActions'
import DialogContent from '@material-ui/core/DialogContent'
import DialogTitle from '@material-ui/core/DialogTitle'
import IconButton from '@material-ui/core/IconButton'
import Slide from '@material-ui/core/Slide'
import { createStyles, makeStyles, Theme } from '@material-ui/core/styles'
import TextField from '@material-ui/core/TextField'
import Toolbar from '@material-ui/core/Toolbar'
import { TransitionProps } from '@material-ui/core/transitions'
import Typography from '@material-ui/core/Typography'
import CloseIcon from '@material-ui/icons/Close'
import * as React from 'react'
import useMedia from 'use-media'
import { getMyItems, postItems } from '../../../apis/item'
import { MyItemsContext } from '../../../contexts/itemsContexts'
import { ItemType } from '../types'
import { ItemsWrapper } from './itemsWrapper'
const { useContext, useEffect, useState } = React
const useStyles = makeStyles((theme: Theme) =>
createStyles({
appBar: {
position: 'relative',
},
title: {
marginLeft: theme.spacing(2),
flex: 1,
},
}),
)
const Transition = React.forwardRef(function Transition(
props: TransitionProps & { children?: React.ReactElement },
ref: React.Ref<unknown>,
) {
return <Slide direction="up" ref={ref} {...props} />
})
export const UserMenu: React.FC = () => {
const classes = useStyles()
const isWide = useMedia({ minWidth: '750px' })
const { myItemsState, setMyItems } = useContext(MyItemsContext)
const [open, setOpen] = useState(false)
const [itemTitle, setItemTitle] = useState('')
const [itemYear, setItemYear] = useState('')
const [itemYearType, setItemYearType] = useState('')
const [itemGoroText, setItemGoroText] = useState('')
const [itemDescription, setItemDescription] = useState('')
const handleOpenForm = () => {
setOpen(true)
}
const handleClose = () => {
setOpen(false)
}
const handleItemTitle = (event: React.ChangeEvent<HTMLInputElement>) => {
setItemTitle(event.target.value)
}
const handleItemYearType = (event: React.ChangeEvent<HTMLInputElement>) => {
setItemYearType(event.target.value)
}
const handleItemYear = (event: React.ChangeEvent<HTMLInputElement>) => {
setItemYear(event.target.value)
}
const handleItemGoroText = (event: React.ChangeEvent<HTMLInputElement>) => {
setItemGoroText(event.target.value)
}
const handleItemDescription = (
event: React.ChangeEvent<HTMLInputElement>,
) => {
setItemDescription(event.target.value)
}
const handleClearState = () => {
setItemTitle('')
setItemYear('')
setItemYearType('')
setItemGoroText('')
setItemDescription('')
}
const handleMyItems = () => {
const randomId = Math.random().toString(36).slice(-8)
const newItem: ItemType = {
id: randomId,
user_id: '',
title: itemTitle,
year: itemYear,
year_for_sort: 0,
year_type: itemYearType,
goro_text: itemGoroText,
description: itemDescription,
}
const newMyItems: ItemType[] =
myItemsState.length === 0 ? [...myItemsState, newItem] : [newItem]
setMyItems(newMyItems)
}
const handleAddItem = () => {
postItems(
itemTitle,
itemYear,
itemYearType,
itemGoroText,
itemDescription,
).then(() => {
handleMyItems()
handleClearState()
setOpen(false)
})
}
useEffect(() => {
getMyItems().then((data: React.SetStateAction<ItemType[]>) => {
setMyItems(data)
})
}, [setMyItems])
return (
<>
<Button variant="outlined" color="primary" onClick={handleOpenForm}>
語呂合わせ作成
</Button>
{isWide ? (
<Dialog
open={open}
onClose={handleClose}
aria-labelledby="form-dialog-title"
>
<DialogTitle id="form-dialog-title">語呂合わせ新規作成</DialogTitle>
<DialogContent>
<TextField
autoFocus
value={itemTitle}
margin="dense"
id="title-text-field"
label="できごと"
type="text"
fullWidth
onChange={handleItemTitle}
/>
<TextField
value={itemYear}
margin="dense"
id="year-text-field"
label="年"
type="text"
fullWidth
onChange={handleItemYear}
/>
<TextField
id="year-type-select"
margin="dense"
select
label="年代タイプ"
fullWidth
onChange={handleItemYearType}
>
<MenuItem selected value="紀元後">
紀元後
</MenuItem>
<MenuItem value="紀元前">紀元前</MenuItem>
<MenuItem value="年前">年前</MenuItem>
<MenuItem value="万年前">万年前</MenuItem>
<MenuItem value="億年前">億年前</MenuItem>
</TextField>
<TextField
value={itemGoroText}
margin="dense"
id="goro-text-field"
label="語呂"
type="text"
fullWidth
onChange={handleItemGoroText}
/>
<TextField
id="description-text-field"
label="説明"
margin="dense"
fullWidth
multiline
rows={4}
variant="outlined"
onChange={handleItemDescription}
/>
</DialogContent>
<DialogActions>
<Button
onClick={handleClose}
color="primary"
style={{ position: 'absolute', left: '20px' }}
>
キャンセル
</Button>
<Button
color="primary"
variant="contained"
onClick={() => handleAddItem()}
>
作成
</Button>
</DialogActions>
</Dialog>
) : (
<Dialog
fullScreen
open={open}
onClose={handleClose}
TransitionComponent={Transition}
>
<AppBar className={classes.appBar}>
<Toolbar>
<IconButton
edge="start"
color="inherit"
onClick={handleClose}
aria-label="close"
>
<CloseIcon />
</IconButton>
<Typography variant="h6" className={classes.title}>
新規語呂作成
</Typography>
<Button autoFocus color="inherit" onClick={() => handleAddItem()}>
作成
</Button>
</Toolbar>
</AppBar>
<DialogContent>
<TextField
autoFocus
value={itemTitle}
margin="dense"
id="title-text-field"
label="できごと"
type="text"
fullWidth
onChange={handleItemTitle}
/>
<TextField
value={itemYear}
margin="dense"
id="year-text-field"
label="年"
type="text"
fullWidth
onChange={handleItemYear}
/>
<TextField
id="year-type-select"
margin="dense"
select
label="年代タイプ"
fullWidth
onChange={handleItemYearType}
>
<MenuItem selected value="紀元後">
紀元後
</MenuItem>
<MenuItem value="紀元前">紀元前</MenuItem>
<MenuItem value="年前">年前</MenuItem>
<MenuItem value="万年前">万年前</MenuItem>
<MenuItem value="億年前">億年前</MenuItem>
</TextField>
<TextField
value={itemGoroText}
margin="dense"
id="goro-text-field"
label="語呂"
type="text"
fullWidth
onChange={handleItemGoroText}
/>
<TextField
id="description-text-field"
label="説明"
margin="dense"
fullWidth
multiline
rows={4}
variant="outlined"
onChange={handleItemDescription}
/>
</DialogContent>
</Dialog>
)}
<h3>アイテムリスト</h3>
{Object.keys(myItemsState).length != 0 ? (
<span>
{myItemsState.map((myItem, index) => (
<ItemsWrapper key={index} item={myItem} />
))}
</span>
) : (
<span></span>
)}
</>
)
}
|
import { supabase } from "@/utils/supabase/admin";
import { makeServerClient } from "@/utils/supabase/server";
import { NextRequest, NextResponse } from "next/server";
interface TokenData {
access_token: string;
token_type: string;
expires_in: number;
refresh_token: string;
scope: string;
}
export async function POST(req: NextRequest) {
const authSupabase = makeServerClient();
const {
data: { user },
} = await authSupabase.auth.getUser();
if (!user) return NextResponse.redirect(new URL("/auth/login", req.url));
const { data: tokenData } = await supabase.from("token").select().eq("user_id", user.id).single();
const client_id = process.env.NEXT_PUBLIC_SPOTIFY_CLIENT_ID!;
const client_secret = process.env.SPOTIFY_CLIENT_SECRET!;
const params = new URLSearchParams();
params.set("grant_type", "refresh_token");
params.set("refresh_token", tokenData!.refresh_token);
const data: TokenData = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
Authorization: "Basic " + Buffer.from(client_id + ":" + client_secret).toString("base64"),
},
body: params.toString(),
}).then((res) => res.json());
const currentTime = new Date();
const futureTime = new Date(currentTime.getTime() + (data.expires_in - 300) * 1000);
const futureTimeString = futureTime.toISOString();
const returnData = {
access_token: data.access_token,
refresh_token: data.refresh_token,
expire_at: futureTimeString,
};
await supabase.from("token").update(returnData).eq("id", tokenData!.id);
return NextResponse.json(returnData);
}
|
import { StyleSheet, Text, View } from 'react-native';
import { useEffect, useState } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { Provider } from 'react-native-paper';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { theme } from './core/theme'
import { StartScreen, LoginScreen, RegisterScreen, ResetPasswordScreen, DashboardScreen, WelcomeScreen } from './components/screens'
import { GlobalContext } from './context/GlobalContext';
const Stack = createNativeStackNavigator();
export default function App() {
const [globalState, setGlobalState] = useState({ userInfo: null, foodData: [], DailyNotes: [] })
return (
<GlobalContext.Provider value={{ globalState, setGlobalState }}>
<Provider theme={theme}>
<NavigationContainer>
<Stack.Navigator
initialRouteName="WelcomeScreen"
screenOptions={{
headerShown: false,
}}
>
<Stack.Screen name="WelcomeScreen" component={WelcomeScreen} />
<Stack.Screen name="StartScreen" component={StartScreen} />
<Stack.Screen name="LoginScreen" component={LoginScreen} />
<Stack.Screen name="RegisterScreen" component={RegisterScreen} />
<Stack.Screen name="Dashboard" component={DashboardScreen} />
<Stack.Screen name="ResetPasswordScreen" component={ResetPasswordScreen}
/>
</Stack.Navigator>
</NavigationContainer>
</Provider>
</GlobalContext.Provider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
justifyContent: 'center',
},
});
|
# [Thinkful - String Drills: Poem Formatter](https://www.codewars.com/kata/585af8f645376cda59000200)
## Description
You have a collection of lovely poems. Unfortunately, they aren't formatted very well. They're all on one line, like this:
```
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated.
```
What you want is to present each sentence on a new line, so that it looks like this:
```
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
```
Write a function, format_poem() that takes a string like the one line example as an argument and returns a new string that is formatted across multiple lines with each new sentence starting on a new line when you print it out.
Try to solve this challenge with the str.split() and the str.join() string methods.
Every sentence will end with a period, and every new sentence will have one space before the previous period. Be careful about trailing whitespace in your solution.
## My Solution
**JavaScript**
```js
const formatPoem = (poem) => poem.split(/\. /g).join('.\n');
```
### User Solution
**JavaScript**
```js
const formatPoem = (s) => {
return s.replace(/\. /g, '.\n');
};
```
|
//亂數生成dbid
function generateUniqueDbId() {
const min = 10000; // 最小值,5位數的最小值
const max = 99999; // 最大值,5位數的最大值
let num;
do {
num = Math.floor(Math.random() * (max - min + 1) + min);
} while (generatedNumbers.has(num));
generatedNumbers.add(num);
return num;
}
//Three Mesh方式
function addGeometryV1(modelBuilder, dbId) {
const boxGeometry = new THREE.BufferGeometry().fromGeometry(
new THREE.BoxGeometry(10, 10, 10)
);
const boxMaterial = new THREE.MeshPhongMaterial({
color: new THREE.Color(1, 0, 0),
});
const Mesh = new THREE.Mesh(boxGeometry, boxMaterial);
const x = parseFloat(document.getElementById("x").value);
const y = parseFloat(document.getElementById("y").value);
const z = parseFloat(document.getElementById("z").value);
var position = new THREE.Vector3(x, y, z);
Mesh.matrix = new THREE.Matrix4().compose(
position,
new THREE.Quaternion(0, 0, 0, 1),
new THREE.Vector3(1, 1, 1)
);
Mesh.dbId = dbId;
modelBuilder.addMesh(Mesh);
Mesh.position.set(x, y, z);
Mesh.updateMatrix();
modelBuilder.updateMesh(Mesh);
return Mesh;
}
//Three Mesh方式
function addGeometryV2(modelBuilder, dbId,x,y,z) {
console.log("到addGeo了");
const boxGeometry = new THREE.BufferGeometry().fromGeometry(
new THREE.BoxGeometry(10, 10, 10)
);
const boxMaterial = new THREE.MeshPhongMaterial({
color: new THREE.Color(1, 0, 0),
});
const Mesh = new THREE.Mesh(boxGeometry, boxMaterial);
var position = new THREE.Vector3(x, y, z);
Mesh.matrix = new THREE.Matrix4().compose(
position,
new THREE.Quaternion(0, 0, 0, 1),
new THREE.Vector3(1, 1, 1)
);
Mesh.dbId = dbId;
modelBuilder.addMesh(Mesh);
Mesh.position.set(x, y, z);
Mesh.updateMatrix();
modelBuilder.updateMesh(Mesh);
return Mesh;
}
//根據api生成模式
function addGeometryWithPosition(modelBuilder, dbId, x, y, z) {
// 創建方塊幾何體
const boxGeometry = new THREE.BufferGeometry().fromGeometry(
new THREE.BoxGeometry(10, 10, 10)
);
// 創建物體材料
const boxMaterial = new THREE.MeshPhongMaterial({
color: new THREE.Color(1, 0, 0),
});
// 使用幾何體和材料創建網格物體
const Mesh = new THREE.Mesh(boxGeometry, boxMaterial);
// 設定物體位置
const position = new THREE.Vector3(x, y, z);
// 更新物體的變換矩陣
Mesh.matrix = new THREE.Matrix4().compose(
position,
new THREE.Quaternion(0, 0, 0, 1),
new THREE.Vector3(1, 1, 1)
);
// 設定dbId到模型上
Mesh.dbId = dbId;
// 向模型生成器添加此網格
modelBuilder.addMesh(Mesh);
// 再次設定位置並更新變換矩陣
Mesh.position.set(x, y, z);
Mesh.updateMatrix();
// 更新模型生成器中的網格
modelBuilder.updateMesh(Mesh);
// 返回生成的網格
return Mesh;
}
//模型載入
async function LoadSceneBuilder() {
//載入外掛
sceneBuilder = await viewer.loadExtension("Autodesk.Viewing.SceneBuilder");
modelBuilder = await sceneBuilder.addNewModel({
conserveMemory: false,
modelNameOverride: "test",
});
//生成dbid
const dbid = generateUniqueDbId();
//生成模型
const mesh = addGeometryV1(modelBuilder, dbid);
//保存進額外模型字典
MeshDictionary[dbid] = mesh;
externalIdDictionary[dbid] = targetExternalId;
deviceIdDictionary[dbid] = mesh.uuid;
//當聚合模型被選擇切換
viewer.addEventListener(
Autodesk.Viewing.AGGREGATE_SELECTION_CHANGED_EVENT,
async function (ev) {
//取得選擇資訊
const selection = await viewer.getAggregateSelection();
console.log(selection);
//取得dbid
var dbId = selection[0].selection[0];
document.getElementById("dbid-input").value = dbId;
//把externalId放進external字典,key是dbId,value是externalId
externalIdDictionary[dbId] = targetExternalId;
//檢查選擇的模型是額外添加的還是原本就有
selectedMesh = MeshDictionary[dbId];
console.log(selectedMesh);
//當選擇的是額外添加模型
if (selectedMesh != null) {
// console.log(selectedMesh);
//載入數值即可
document.getElementById("x").value = selectedMesh.position.x.toFixed(2);
document.getElementById("y").value = selectedMesh.position.y.toFixed(2);
document.getElementById("z").value = selectedMesh.position.z.toFixed(2);
//聚合模型額外添加模型更換位置
document.getElementById("x").addEventListener("input", updatePosition);
document.getElementById("y").addEventListener("input", updatePosition);
document.getElementById("z").addEventListener("input", updatePosition);
} else {
//當選擇的是聚合模型的預設模型
//取得fragId
const fragId = await new Promise((resolve) => {
viewer.model
.getData()
.instanceTree.enumNodeFragments(dbId, function (fragId) {
resolve(fragId);
});
});
// console.log(fragId)
//取得片段代理
const fragProxy = viewer.impl.getFragmentProxy(viewer.model, fragId);
fragProxy.updateAnimTransform(); //更新動畫變換
const worldMatrix = new THREE.Matrix4();
fragProxy.getWorldMatrix(worldMatrix); //取得世界變換矩陣
//從變換矩陣取得世界位置
const worldPosition = new THREE.Vector3();
worldPosition.setFromMatrixPosition(worldMatrix);
//設定面板數值
document.getElementById("x").value = worldPosition.x.toFixed(2);
document.getElementById("y").value = worldPosition.y.toFixed(2);
document.getElementById("z").value = worldPosition.z.toFixed(2);
//數值改動添加updatePosition2
document
.getElementById("x")
.addEventListener("input", updatePosition2(dbId));
document
.getElementById("y")
.addEventListener("input", updatePosition2(dbId));
document
.getElementById("z")
.addEventListener("input", updatePosition2(dbId));
}
function updatePosition() {
if (selectedMesh) {
// 從面板讀取相對坐標
const targetX = parseFloat(document.getElementById("x").value);
const targetY = parseFloat(document.getElementById("y").value);
const targetZ = parseFloat(document.getElementById("z").value);
// 將新的本地坐標設置到模型
selectedMesh.position.set(targetX, targetY, targetZ);
// 標記矩陣需要更新
selectedMesh.matrixAutoUpdate = true;
selectedMesh.updateMatrix();
// 如果有額外的更新,應用它們
modelBuilder.updateMesh(selectedMesh);
}
}
function updatePosition2(dbId) {
if (modelPositions[dbId]) {
// 如果已經移動過,使用字典中的位置
const { x, y, z } = modelPositions[dbId];
document.getElementById("x").value = x;
document.getElementById("y").value = y;
document.getElementById("z").value = z;
} else if (dbId != null) {
// 如果尚未移動,計算位置並存儲在字典中
viewer.model
.getData()
.instanceTree.enumNodeFragments(dbId, function (fragId) {
const fragProxy = viewer.impl.getFragmentProxy(
viewer.model,
fragId
);
console.log(fragProxy);
fragProxy.getAnimTransform();
const worldMatrix = new THREE.Matrix4();
fragProxy.getWorldMatrix(worldMatrix);
const worldPosition = new THREE.Vector3();
worldPosition.setFromMatrixPosition(worldMatrix);
// 將位置存儲在字典中
modelPositions[dbId] = {
x: worldPosition.x.toFixed(2),
y: worldPosition.y.toFixed(2),
z: worldPosition.z.toFixed(2),
};
document.getElementById("x").value = worldPosition.x.toFixed(2);
document.getElementById("y").value = worldPosition.y.toFixed(2);
document.getElementById("z").value = worldPosition.z.toFixed(2);
});
}
}
}
);
}
//模型載入2
async function LoadSceneBuilder2(modelDataList) {
//載入modelDataList,其中包括externalID,dbId,tag,xyz
for (let modelData of modelDataList) {
console.log('看看運作次數');
const { deviceId, dbId, tag, position,extendedId } = modelData;
//載入外掛
if(sceneBuilder == null){
sceneBuilder = await viewer.loadExtension("Autodesk.Viewing.SceneBuilder");
modelBuilder = await sceneBuilder.addNewModel({
conserveMemory: false,
modelNameOverride: "test",
});
}
// 檢查是否dbId, deviceId, 或 position 有空值或未定義
if (!dbId || !deviceId || !position) {
console.warn("Incomplete model data detected, skipping:", modelData);
continue; // 跳過這次迴圈,繼續處理下一個modelData
}
const [x, y, z] = position.split(",").map(Number);
// 確保 x, y, z 都是有效的數字
if ([x, y, z].some((val) => isNaN(val))) {
console.warn("Invalid position data detected, skipping:", position);
continue; // 跳過這次迴圈,繼續處理下一個modelData
}
// 建立模型使用addGeometryWithPosition (assuming it returns the mesh)
const mesh = addGeometryWithPosition(modelBuilder, dbId, x, y, z);
mesh.position.set(x, y, z);
mesh.updateMatrix();
// Update dictionaries:
externalIdDictionary[dbId] = extendedId;
deviceIdDictionary[dbId] = deviceId;
MeshDictionary[dbId] = mesh;
viewer.addEventListener(
Autodesk.Viewing.AGGREGATE_SELECTION_CHANGED_EVENT,
async function (ev) {
//取得選擇資訊
const selection = await viewer.getAggregateSelection();
console.log(selection);
//取得dbid
var dbId = selection[0].selection[0];
document.getElementById("dbid-input").value = dbId;
//把externalId放進external字典,key是dbId,value是externalId
externalIdDictionary[dbId] = targetExternalId;
//檢查選擇的模型是額外添加的還是原本就有
selectedMesh = MeshDictionary[dbId];
//當選擇的是額外添加模型
if (selectedMesh != null) {
// console.log(selectedMesh);
//載入數值即可
document.getElementById("x").value =
selectedMesh.position.x.toFixed(2);
document.getElementById("y").value =
selectedMesh.position.y.toFixed(2);
document.getElementById("z").value =
selectedMesh.position.z.toFixed(2);
//聚合模型額外添加模型更換位置
document
.getElementById("x")
.addEventListener("input", updatePosition);
document
.getElementById("y")
.addEventListener("input", updatePosition);
document
.getElementById("z")
.addEventListener("input", updatePosition);
} else {
//當選擇的是聚合模型的預設模型
//取得fragId
const fragId = await new Promise((resolve) => {
viewer.model
.getData()
.instanceTree.enumNodeFragments(dbId, function (fragId) {
resolve(fragId);
});
});
// console.log(fragId)
//取得片段代理
const fragProxy = viewer.impl.getFragmentProxy(viewer.model, fragId);
fragProxy.updateAnimTransform(); //更新動畫變換
const worldMatrix = new THREE.Matrix4();
fragProxy.getWorldMatrix(worldMatrix); //取得世界變換矩陣
//從變換矩陣取得世界位置
const worldPosition = new THREE.Vector3();
worldPosition.setFromMatrixPosition(worldMatrix);
//設定面板數值
document.getElementById("x").value = worldPosition.x.toFixed(2);
document.getElementById("y").value = worldPosition.y.toFixed(2);
document.getElementById("z").value = worldPosition.z.toFixed(2);
//數值改動添加updatePosition2
document
.getElementById("x")
.addEventListener("input", updatePosition2(dbId));
document
.getElementById("y")
.addEventListener("input", updatePosition2(dbId));
document
.getElementById("z")
.addEventListener("input", updatePosition2(dbId));
}
function updatePosition() {
if (selectedMesh) {
// 從面板讀取相對坐標
const targetX = parseFloat(document.getElementById("x").value);
const targetY = parseFloat(document.getElementById("y").value);
const targetZ = parseFloat(document.getElementById("z").value);
// 將新的本地坐標設置到模型
selectedMesh.position.set(targetX, targetY, targetZ);
// 標記矩陣需要更新
selectedMesh.matrixAutoUpdate = true;
selectedMesh.updateMatrix();
// 如果有額外的更新,應用它們
modelBuilder.updateMesh(selectedMesh);
}
}
function updatePosition2(dbId) {
if (modelPositions[dbId]) {
// 如果已經移動過,使用字典中的位置
const { x, y, z } = modelPositions[dbId];
document.getElementById("x").value = x;
document.getElementById("y").value = y;
document.getElementById("z").value = z;
} else if (dbId != null) {
// 如果尚未移動,計算位置並存儲在字典中
viewer.model
.getData()
.instanceTree.enumNodeFragments(dbId, function (fragId) {
const fragProxy = viewer.impl.getFragmentProxy(
viewer.model,
fragId
);
console.log(fragProxy);
fragProxy.getAnimTransform();
const worldMatrix = new THREE.Matrix4();
fragProxy.getWorldMatrix(worldMatrix);
const worldPosition = new THREE.Vector3();
worldPosition.setFromMatrixPosition(worldMatrix);
// 將位置存儲在字典中
modelPositions[dbId] = {
x: worldPosition.x.toFixed(2),
y: worldPosition.y.toFixed(2),
z: worldPosition.z.toFixed(2),
};
document.getElementById("x").value = worldPosition.x.toFixed(2);
document.getElementById("y").value = worldPosition.y.toFixed(2);
document.getElementById("z").value = worldPosition.z.toFixed(2);
});
}
}
}
);
}
}
//模型載入
async function LoadSceneBuilder3(dbid,x,y,z,exId) {
console.log("最新生成")
//載入外掛
sceneBuilder = await viewer.loadExtension("Autodesk.Viewing.SceneBuilder");
modelBuilder = await sceneBuilder.addNewModel({
conserveMemory: false,
modelNameOverride: "test",
});
//生成模型
const mesh = addGeometryV2(modelBuilder, dbid,x,y,z);
//保存進額外模型字典
MeshDictionary[dbid] = mesh;
externalIdDictionary[dbid] = exId;
//當聚合模型被選擇切換
viewer.addEventListener(
Autodesk.Viewing.AGGREGATE_SELECTION_CHANGED_EVENT,
async function (ev) {
//取得選擇資訊
const selection = await viewer.getAggregateSelection();
console.log(selection);
//取得dbid
var dbId = selection[0].selection[0];
document.getElementById("dbid-input").value = dbId;
//把externalId放進external字典,key是dbId,value是externalId
console.log(externalIdDictionary[dbid])
console.log(dbId)
console.log(tagDictionary[dbid])
console.log(MeshDictionary[dbid].position);
console.log(deviceIdDictionary[dbid]);
//檢查選擇的模型是額外添加的還是原本就有
selectedMesh = MeshDictionary[dbId];
console.log(tagDictionary)
var tag = tagDictionary[dbId]
document.getElementById("markup-content-input").value = tag
console.log(selectedMesh);
//當選擇的是額外添加模型
if (selectedMesh != null) {
// console.log(selectedMesh);
//載入數值即可
document.getElementById("x").value = selectedMesh.position.x.toFixed(2);
document.getElementById("y").value = selectedMesh.position.y.toFixed(2);
document.getElementById("z").value = selectedMesh.position.z.toFixed(2);
//聚合模型額外添加模型更換位置
document.getElementById("x").addEventListener("input", updatePosition);
document.getElementById("y").addEventListener("input", updatePosition);
document.getElementById("z").addEventListener("input", updatePosition);
} else {
//當選擇的是聚合模型的預設模型
//取得fragId
const fragId = await new Promise((resolve) => {
viewer.model
.getData()
.instanceTree.enumNodeFragments(dbId, function (fragId) {
resolve(fragId);
});
});
// console.log(fragId)
//取得片段代理
const fragProxy = viewer.impl.getFragmentProxy(viewer.model, fragId);
fragProxy.updateAnimTransform(); //更新動畫變換
const worldMatrix = new THREE.Matrix4();
fragProxy.getWorldMatrix(worldMatrix); //取得世界變換矩陣
//從變換矩陣取得世界位置
const worldPosition = new THREE.Vector3();
worldPosition.setFromMatrixPosition(worldMatrix);
//設定面板數值
document.getElementById("x").value = worldPosition.x.toFixed(2);
document.getElementById("y").value = worldPosition.y.toFixed(2);
document.getElementById("z").value = worldPosition.z.toFixed(2);
//數值改動添加updatePosition2
document
.getElementById("x")
.addEventListener("input", updatePosition2(dbId));
document
.getElementById("y")
.addEventListener("input", updatePosition2(dbId));
document
.getElementById("z")
.addEventListener("input", updatePosition2(dbId));
}
function updatePosition() {
if (selectedMesh) {
// 從面板讀取相對坐標
const targetX = parseFloat(document.getElementById("x").value);
const targetY = parseFloat(document.getElementById("y").value);
const targetZ = parseFloat(document.getElementById("z").value);
// 將新的本地坐標設置到模型
selectedMesh.position.set(targetX, targetY, targetZ);
// 標記矩陣需要更新
selectedMesh.matrixAutoUpdate = true;
selectedMesh.updateMatrix();
// 如果有額外的更新,應用它們
modelBuilder.updateMesh(selectedMesh);
}
}
function updatePosition2(dbId) {
if (modelPositions[dbId]) {
// 如果已經移動過,使用字典中的位置
const { x, y, z } = modelPositions[dbId];
document.getElementById("x").value = x;
document.getElementById("y").value = y;
document.getElementById("z").value = z;
} else if (dbId != null) {
// 如果尚未移動,計算位置並存儲在字典中
viewer.model
.getData()
.instanceTree.enumNodeFragments(dbId, function (fragId) {
const fragProxy = viewer.impl.getFragmentProxy(
viewer.model,
fragId
);
console.log(fragProxy);
fragProxy.getAnimTransform();
const worldMatrix = new THREE.Matrix4();
fragProxy.getWorldMatrix(worldMatrix);
const worldPosition = new THREE.Vector3();
worldPosition.setFromMatrixPosition(worldMatrix);
// 將位置存儲在字典中
modelPositions[dbId] = {
x: worldPosition.x.toFixed(2),
y: worldPosition.y.toFixed(2),
z: worldPosition.z.toFixed(2),
};
document.getElementById("x").value = worldPosition.x.toFixed(2);
document.getElementById("y").value = worldPosition.y.toFixed(2);
document.getElementById("z").value = worldPosition.z.toFixed(2);
});
}
}
}
);
}
|
<script setup>
import { ref } from "vue";
import { useGetImageUrl } from "../composables/getImageUrl";
import servicesData from "@/assets/services.json";
import { useHead } from "@vueuse/head";
const pageTitle = ref("Szolgáltatásaink");
const pageDescription = ref(
"Fedezd fel a legjobb orvosi és esztétikai lézerkezeléseket szolgáltatásaink között, tapasztalt szakembereink és korszerű technológiáink segítségével."
);
useHead({
title: pageTitle.value,
meta: [
{
name: "description",
content: pageDescription.value,
},
{
property: "og:title",
content: pageTitle.value,
},
{
property: "og:description",
content: pageDescription.value,
},
{
property: "og:url",
content: "https://elysia.hu/szolgaltatasaink",
},
],
});
</script>
<template>
<section class="mb-0">
<div class="flex flex-col space-y-10 mx-auto">
<AppHeader>
<template #subtitle> elysia laser clinic </template>
<template #title> Szolgáltatásaink </template>
</AppHeader>
</div>
<div class="max-w-screen-xl site-padding space-y-10 mx-auto py-16">
<!-- <p class="max-w-lg text-center mx-auto">{{ pageDescription }}</p> -->
<ul
class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-y-8 lg:gap-y-12 sm:gap-x-6 px-2 items-start"
name="list"
>
<li
v-for="service in servicesData"
:key="service.id"
class="list-item transform transition duration-300 ease-in-out hover:-translate-y-1"
>
<AppLink
class="flex flex-col items-center gap-4"
:to="{
name: 'services.category',
params: { category: service.slug },
}"
>
<img
class="h-24 sm:h-32 w-full object-contain"
:src="useGetImageUrl(service.image)"
:alt="service.name + 'szimbólum'"
height="100"
width="100"
/>
<p class="font-semibold text-center text-xs sm:text-base">
{{ service.name }}
</p>
</AppLink>
</li>
<li
class="list-item transform transition duration-300 ease-in-out hover:-translate-y-1"
>
<AppLink
class="flex flex-col items-center gap-4"
:to="{
name: 'service.pulmonology',
}"
>
<img
class="h-24 sm:h-32 w-full object-contain"
:src="useGetImageUrl('tudogyogyaszati-szakrendeles.webp')"
alt="tüdőgyógyászati vizsgálatok szimbólum"
/>
<p class="font-semibold text-center text-xs sm:text-base">
Tüdőgyógyászat
</p>
</AppLink>
</li>
<li
class="list-item transform transition duration-300 ease-in-out hover:-translate-y-1"
>
<AppLink
class="flex flex-col items-center gap-4"
:to="{
name: 'service.neurosurgery',
}"
>
<img
class="h-24 sm:h-32 w-full object-contain"
:src="useGetImageUrl('idegsebeszeti-vizsgalatok.webp')"
alt="idegsebészeti vizsgálatok szimbólum"
height="100"
width="100"
/>
<p class="font-semibold text-center text-xs sm:text-base">
Idegsebészet
</p>
</AppLink>
</li>
<li
class="list-item transform transition duration-300 ease-in-out hover:-translate-y-1"
>
<AppLink
class="flex flex-col items-center gap-4"
:to="{
name: 'service.somnology',
}"
>
<img
class="h-24 sm:h-32 w-full object-contain"
:src="useGetImageUrl('szomnologia.webp')"
alt="szomnológia szimbólum"
height="100"
width="100"
/>
<p class="font-semibold text-center text-xs sm:text-base">
Szomnológia
</p>
</AppLink>
</li>
<li
class="list-item transform transition duration-300 ease-in-out hover:-translate-y-1"
>
<AppLink
class="flex flex-col items-center gap-4"
:to="{
name: 'service.allergology',
}"
>
<img
class="h-24 sm:h-32 w-full object-contain"
:src="useGetImageUrl('allergologia.webp')"
alt="allergológia szimbólum"
height="100"
width="100"
/>
<p class="font-semibold text-center text-xs sm:text-base">
Allergológia
</p>
</AppLink>
</li>
</ul>
</div>
</section>
</template>
|
package com.example.fleeapp.presentation.navigation.bottom_navigation
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.example.fleeapp.presentation.Screen
import com.example.fleeapp.presentation.base_ui.theme.flee_main.FleeMainTheme
@Composable
fun BottomNavigationBar(navController: NavHostController) {
val items = listOf(
Screen.HomepageFeedScreen,
Screen.ListenMusicScreen,
Screen.MusicPlayerScreen,
Screen.ManagePlaylistsScreen
)
var selectedItemIndex by rememberSaveable {
mutableStateOf(0)
}
fun navigateTo(index: Int, screen: Screen) {
selectedItemIndex = index
navController.navigate(screen.route)
}
NavigationBar(
containerColor = FleeMainTheme.colors.backgroundSecondary,
) {
items.forEachIndexed { index, screen ->
NavigationBarItem(
selected = selectedItemIndex == index,
onClick = { navigateTo(index = index, screen = screen) },
icon = {
Icon(
imageVector = if (index == selectedItemIndex)
screen.selectedIcon
else screen.unselectedIcon,
contentDescription = screen.title,
)
},
label = {
Text(
text = screen.title,
style = FleeMainTheme.typography.small
)
},
colors = NavigationBarItemDefaults.colors(
selectedIconColor = FleeMainTheme.colors.navItemSelectedIcon,
selectedTextColor = FleeMainTheme.colors.navItemSelectedBackground,
unselectedIconColor = FleeMainTheme.colors.navItemUnselectedIcon,
unselectedTextColor = FleeMainTheme.colors.textSecondary,
indicatorColor = FleeMainTheme.colors.navItemSelectedBackground,
),
)
}
}
}
|
/* Proyecto Aviones
* Salvador Rodriguez Paredes
* A01704562
* 12/30/2021
*/
/*
* Clase Aeropuerto contiene los métodos genéricos para el manejo de aeropuerto
* y tiene 3 clases hijas que son especializaciones de aeropuerto:
* Dinamarca, China y Texas
*
*/
#ifndef PROYECTOPOO_AEROPUERTO_H
#define PROYECTOPOO_AEROPUERTO_H
#include <string>
#include <utility>
using namespace std;
//Declaración de la clase aeropuerto que es abstracta
class Aeropuerto {
private:
//Declaro variables de instancia
string nombreAeropuerto;
string pais;
int numeroVuelos;
public:
//Se declaran los métodos que tiene el objeto asi como su constructor
//Constructor default
Aeropuerto() : nombreAeropuerto(""), pais(""), numeroVuelos(0) {};
//Constructor que recibe parámetros para llenar las variables
Aeropuerto(string nomAe, string pai, int numVu) : nombreAeropuerto(nomAe), pais(pai), numeroVuelos(numVu) {};
//Getters de las variables nombre aeropuerto, pais y numero de vuelo
string get_nombreAeropuerto();
string get_pais();
int get_numeroVuelos();
//Setters de las variables nombre aeropuerto, pais y numero de vuelo
void set_nombreAeropuerto(string);
void set_pais(string);
void set_numeroVuelos(int);
};
//Método que regresa el valor de nombre aeropuerto
string Aeropuerto::get_nombreAeropuerto() {
return nombreAeropuerto;
}
//Método que regresa el valor de pais
string Aeropuerto::get_pais() {
return pais;
}
//Método que regresa el valor de número de vuelos
int Aeropuerto::get_numeroVuelos() {
return numeroVuelos;
}
//Método que asigna un valor a nombre aeropuerto
void Aeropuerto::set_nombreAeropuerto(string nomAe) {
nombreAeropuerto = nomAe;
}
//Método que asigna un valor a numero vuelos
void Aeropuerto::set_numeroVuelos(int numVu) {
numeroVuelos = numVu;
}
//Método que asigna un valor a pais
void Aeropuerto::set_pais(string pai) {
pais = pai;
}
//Declaración de la clase Dinamarca que hereda de Aeropuerto
class Dinamarca : public Aeropuerto {
public:
//Métodos y constructores del objeto
//Constructor default
Dinamarca (string nomAe, string pai, int numVu) : Aeropuerto(nomAe, pai, numVu) {};
//Constructor que recibe parámetros para llenar las variables
Dinamarca():Aeropuerto("","",0){};
float coronaDanesa_peso(float);
};
//Método que hace la conversion de la variable precio a pesos mexicanos, haciendo una multiplicación por 3.27
float Dinamarca ::coronaDanesa_peso(float coro_dan) {
float peso = coro_dan * 3.27;
return peso;
}
//Declaración de la clase China que hereda de Aeropuerto
class China : public Aeropuerto {
public:
//Métodos y constructores del objeto
//Constructor default
China(string nomAe, string pai, int numVu) : Aeropuerto(nomAe, pai, numVu) {};
//Constructor que recibe parámetros para llenar las variables
China():Aeropuerto("","",0){};
float yuanChino_peso(float);
};
//Método que hace la conversion de la variable precio a pesos mexicanos, haciendo una multiplicación por 3.40
float China::yuanChino_peso(float yuan_chino) {
float peso = yuan_chino * 3.40;
return peso;
}
//Declaración de la clase Texas que hereda de Aeropuerto
class Texas : public Aeropuerto{
public:
//Métodos y constructores del objeto
//Constructor default
Texas(string nomAe, string pai,int numVu): Aeropuerto(nomAe,pai,numVu){};
//Constructor que recibe parámetros para llenar las variables
Texas():Aeropuerto("","",0){};
double dolarEua_peso(float);
};
//Método que hace la conversion de la variable precio a pesos mexicanos, haciendo una multiplicación por 21.72
double Texas::dolarEua_peso(float dolar) {
float peso = dolar * 21.72;
return peso;
}
#endif
|
import React from "react";
import { SimplePopover } from "./SimplePopover";
import AppBar from "@material-ui/core/AppBar/AppBar";
import Grid from "@material-ui/core/Grid/Grid";
import Toolbar from "@material-ui/core/Toolbar/Toolbar";
import { createStyles, makeStyles, Theme } from "@material-ui/core/styles";
import { IUser } from "../store/modules/user/types";
import { AvatarProfileMenu } from "./AvatarProfileMenu";
import { HelpButton } from "./HelpButton";
import { SearchCompanyButton } from "./SearchCompanyButton";
import { HistoryIconButton } from "./HistoryIconButton";
import { AvatarWithBadge } from "./AvatarWithBadge";
interface ICompanyHeaderProps {
user: IUser;
}
const useStyles = makeStyles((theme: Theme) =>
createStyles({
appBar: {
height: 38,
backgroundColor: theme.palette.primary.dark,
},
toolbar: {
minHeight: 0,
},
grid: {
height: 38,
},
iconButton: {
color: "rgb(210,210,210)",
padding: "0",
},
avatar: {
width: theme.spacing(4),
height: theme.spacing(4),
},
})
);
export const CompanyHeader: React.FC<ICompanyHeaderProps> = ({ user }) => {
const classes = useStyles();
return (
<AppBar className={classes.appBar} position="static">
<Toolbar
classes={{
regular: classes.toolbar,
}}
>
<Grid container alignItems="center">
<Grid
classes={{
root: classes.grid,
}}
container
item
alignItems="center"
justify="flex-end"
xs={9}
>
<HistoryIconButton user={user} />
<SearchCompanyButton user={user} />
<HelpButton />
</Grid>
<Grid container item justify="flex-end" xs={3}>
<SimplePopover
opener={
<AvatarWithBadge user={user} className={classes.avatar} />
}
anchorOriginBlockVertical="bottom"
anchorOriginBlockHorizontal="center"
anchorPopupBlockVertical="top"
anchorPopupBlockHorizontal="center"
>
<AvatarProfileMenu me={user} />
</SimplePopover>
</Grid>
</Grid>
</Toolbar>
</AppBar>
);
};
export default CompanyHeader;
|
//
// AreaTableViewCell.swift
// Esim
//
// Created by Viacheslav on 13.03.2023.
//
import UIKit
class PackagesTableViewCell: UITableViewCell {
private typealias C = Constants
private enum Constants {
static let title = "Hello"
static let titleButtonStart = "US$"
static let titleButton = " - BUY NOW"
static let margin: CGFloat = 20
static let marginVertical: CGFloat = 30
static let height: CGFloat = 28
static let width: CGFloat = 37
static let imageHeight: CGFloat = 88
static let imageWidth: CGFloat = 140
static let aspectRatio: CGFloat = 1.16
}
// MARK: - Properties
fileprivate let labelData: UILabel = {
let label = UILabel()
label.textAlignment = .right
label.textColor = Color.esGrey
label.font = .italicSystemFont(ofSize: 17)
return label
}()
fileprivate let labelValidity: UILabel = {
let label = UILabel()
label.textAlignment = .right
label.textColor = Color.esGrey
label.font = .italicSystemFont(ofSize: 17)
return label
}()
fileprivate let labelTitle: UILabel = {
let label = UILabel()
label.textAlignment = .left
label.textColor = Color.esGrey
label.font = .boldSystemFont(ofSize: 19)
return label
}()
fileprivate let labelSubtitle: UILabel = {
let label = UILabel()
label.textAlignment = .left
label.textColor = Color.esGrey
label.font = .italicSystemFont(ofSize: 13)
return label
}()
fileprivate let button: UIButton = {
let button = UIButton()
button.setTitleColor(Color.esGrey, for: .normal)
button.titleLabel?.font = .boldSystemFont(ofSize: 11)
return button
}()
private var image: UIImageView = {
let image = UIImageView()
image.contentMode = .scaleAspectFill
image.backgroundColor = .clear
image.layer.cornerRadius = 12
return image
}()
fileprivate var card: UIImageView = {
let image = UIImageView()
image.image = Icon.esim?.withRenderingMode(.alwaysTemplate)
image.contentMode = .scaleAspectFill
return image
}()
private var bgView: UIView = {
let view = UIView()
view.layer.cornerRadius = 7
view.clipsToBounds = true
return view
}()
private var gradientLayer: CAGradientLayer?
private var colorsGradient: [UIColor] = []
// MARK: - Init
override func layoutSubviews() {
super.layoutSubviews()
guard gradientLayer == nil else {
gradientLayer?.frame.size = frame.size
return
}
gradientLayer = CAGradientLayer()
gradientLayer?.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
gradientLayer?.locations = [0, 1]
gradientLayer?.startPoint = CGPoint(x: 0, y: 0)
gradientLayer?.endPoint = CGPoint(x: 1, y: 0)
gradientLayer?.colors = colorsGradient.map(\.cgColor)
bgView.layer.addSublayer(gradientLayer!)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
separatorInset = UIEdgeInsets(top: 0, left: UIScreen.main.bounds.width, bottom: 0, right: 0)
configureLayout()
backgroundColor = .clear
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
static var reuseIdentifier: String { String(describing: self) }
// MARK: - Public methods
func configure(package: Package) {
let color: UIColor = package.operator?.style == .light ? .systemBackground : Color.esGrey
labelData.text = package.data
labelValidity.text = package.validity
labelTitle.text = package.operator?.title
labelSubtitle.text = package.operator?.countries.first?.title
button.setTitle(Constants.titleButtonStart + String(package.price ?? 0) + Constants.titleButton, for: .normal)
image.image = UIImage(data: package.operator?.imageData ?? Data())
colorsGradient = [UIColor(hex: package.operator?.gradient_start ?? String()) ?? .clear,
UIColor(hex: package.operator?.gradient_end ?? String()) ?? .clear]
card.tintColor = color
[labelTitle, labelSubtitle, labelData, labelValidity].forEach { $0.textColor = color }
button.setTitleColor(color, for: .normal)
}
// MARK: - Private methods
private func configureLayout() {
[bgView, card, labelData, labelValidity, labelTitle, labelSubtitle, image, button]
.forEach(contentView.addSubview)
card.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
card.topAnchor .constraint(equalTo: contentView.topAnchor, constant: C.margin),
card.leadingAnchor .constraint(equalTo: contentView.leadingAnchor, constant: C.margin),
card.trailingAnchor .constraint(equalTo: contentView.trailingAnchor, constant: -C.margin),
card.widthAnchor .constraint(equalTo: card.heightAnchor, multiplier: C.aspectRatio)
])
bgView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
bgView.topAnchor .constraint(equalTo: contentView.topAnchor, constant: C.margin),
bgView.leadingAnchor .constraint(equalTo: contentView.leadingAnchor, constant: C.margin),
bgView.trailingAnchor .constraint(equalTo: contentView.trailingAnchor, constant: -C.margin),
bgView.bottomAnchor .constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -C.margin),
bgView.widthAnchor .constraint(equalTo: bgView.heightAnchor, multiplier: C.aspectRatio)
])
labelData.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
labelData.centerYAnchor .constraint(equalTo: card.centerYAnchor, constant: -C.marginVertical),
labelData.trailingAnchor .constraint(equalTo: card.trailingAnchor, constant: -C.margin)
])
labelValidity.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
labelValidity.topAnchor .constraint(equalTo: labelData.bottomAnchor, constant: C.margin * 2),
labelValidity.trailingAnchor .constraint(equalTo: labelData.trailingAnchor)
])
labelTitle.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
labelTitle.topAnchor .constraint(equalTo: card.topAnchor, constant: C.margin),
labelTitle.leadingAnchor .constraint(equalTo: card.leadingAnchor, constant: C.margin)
])
labelSubtitle.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
labelSubtitle.topAnchor .constraint(equalTo: labelTitle.bottomAnchor, constant: 5),
labelSubtitle.leadingAnchor .constraint(equalTo: labelTitle.leadingAnchor)
])
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.centerXAnchor .constraint(equalTo: card.centerXAnchor),
button.bottomAnchor .constraint(equalTo: card.bottomAnchor, constant: -C.marginVertical)
])
image.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
image.topAnchor .constraint(equalTo: contentView.topAnchor),
image.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -C.margin),
image.heightAnchor .constraint(equalToConstant: C.imageHeight),
image.widthAnchor .constraint(equalToConstant: C.imageWidth)
])
}
}
|
# frozen_string_literal: true
module Filters
module EventFilterScopes
extend FilterScopeable
filter_scope :start_from, ->(start_date) { where('start >= ?', start_date) }
filter_scope :start_to, ->(start_date) { where('start <= ?', start_date) }
filter_scope :finish_from, ->(finish_date) { where('finish >= ?', finish_date) }
filter_scope :finish_to, ->(finish_date) { where('finish <= ?', finish_date) }
filter_scope :event_type, ->(id) { where(event_type_id: id) }
filter_scope :customer, ->(id) { where(customer_id: id) }
end
class EventFilterProxy < FilterProxy
def self.query_scope
Event
end
def self.filter_scopes_module
Filters::EventFilterScopes
end
end
end
|
import "./Questionare.css";
import axios from "axios";
import React, { useState } from "react";
export const Questionare1 = () => {
const [data, setData] = useState({
fullName: "",
email: "",
dateOfBirth: "",
phoneNumber: "",
occupation: "",
address: "",
medicalHistory: "",
chronicConditions: "",
allergies: "",
medications: "",
familyHistory: "",
lifestyleFactors: "",
recentChanges: "",
preferredCommunication: "",
healthcarePreferences: "",
culturalConsiderations: "",
currentIllness: "",
status: "",
});
function submit(e) {
e.preventDefault();
console.log(data.dateOfBirth);
axios
.post(url, {
fullName: data.fullName,
email: data.email,
dateOfBirth: data.dateOfBirth,
occupation: data.occupation,
address: data.address,
phoneNumber: data.phoneNumber,
medicalHistory: data.medicalHistory,
chronicConditions: data.chronicConditions,
allergies: data.allergies,
medications: data.medications,
familyHistory: data.familyHistory,
lifestyleFactors: data.lifestyleFactors,
recentChanges: data.recentChanges,
preferredCommunication: data.preferredCommunication,
healthcarePreferences: data.healthcarePreferences,
culturalConsiderations: data.culturalConsiderations,
currentIllness: data.currentIllness,
status: "not assigned",
})
.then((res) => {
console.log(res.data.error ? res.data.error : res.data);
// feed.textContent = successMsg
})
.catch((err) => {
console.log(err);
// feed.textContent = "*" + err.response.data.error
});
}
function handle(e) {
const newdata = { ...data };
newdata[e.target.id] = e.target.value;
setData(newdata);
}
const url = "http://localhost:3001/api/patients/patientForm";
return (
<>
<nav className="navbar">
<div className="logo">
<img
id="artemis-logo"
src={require("../static/images/logo.png")}
alt="Artemis Logo"
/>
</div>
<div className="personLogo">
<img
id="person-logo"
src={require("../static/images/personLogo.png")}
alt="Person Logo"
/>
</div>
</nav>
<div className="box">
<div className="top2">
<div className="top-left">
<h1>Diagnostic Quiz</h1>{" "}
</div>
{/* <div className="top-right"><h1>1/3</h1> </div> */}
</div>
<form onSubmit={submit}>
<div className="flex">
<label htmlFor="FullName">Full Name</label>
<input
type="text"
value={data.fullName}
id="fullName"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="Number">Phone Number</label>
<input
type="phone-number"
value={data.phoneNumber}
id="phoneNumber"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="Occupation">Occupation</label>
<input
type="text"
value={data.occupation}
id="occupation"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="Email">Email</label>
<input
type="text"
value={data.email}
id="email"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="DateofBirth">Date of Birth</label>
<input
type="date"
value={data.dateOfBirth}
id="dateOfBirth"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="Address">Address</label>
<input
type="text-area"
value={data.address}
id="address"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="MedicalHistory"> Medical History</label>
<input
type="text"
value={data.medicalHistory}
id="medicalHistory"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="ChronicConditions">Chronic Conditions</label>
<input
type="text"
value={data.chronicConditions}
id="chronicConditions"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="Allergies">Allergies</label>
<input
type="text"
value={data.allergies}
id="allergies"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="Medications">Medications</label>
<input
type="text"
value={data.medications}
id="medications"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="FamHistory">Family History</label>
<input
type="text"
value={data.familyHistory}
id="familyHistory"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="LifestyleFactors">Lifestyle Factors</label>
<input
type="text"
value={data.lifestyleFactors}
id="lifestyleFactors"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="Recent Changes">Recent Changes</label>
<input
type="text"
value={data.recentChanges}
id="recentChanges"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="Communication">
Preferred form of Communication
</label>
<input
type="text"
value={data.preferredCommunication}
id="preferredCommunication"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="Preferences">Healthcare Preferences</label>
<input
type="text"
value={data.healthcarePreferences}
id="healthcarePreferences"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="Considerations">
Religious/Cultural Considerations
</label>
<input
type="text"
value={data.culturalConsiderations}
id="culturalConsiderations"
onChange={(e) => handle(e)}
/>
</div>
<div className="flex">
<label htmlFor="CurrIllness">Current Illness</label>
<select value={data.currentIllness} name="currentIllness" id="currentIllness" onChange={(e) => handle(e)}>
<option value="Dermatology">Dermatology</option>
<option value="Cardiology">Cardiology</option>
<option value="Orthopedic">Orthopedic</option>
<option value="Psychiatric">Psychiatric</option>
<option value="Ophthalmology">Ophthalmology</option>
<option value="Neurology">Neurology</option>
</select>
</div>
<div className="bottomBox">
<button type="submit">Submit</button>
</div>
</form>
</div>
</>
);
};
|
import 'package:firebase_crud_app/Auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class ForgotPasswordScreen extends StatefulWidget {
@override
State<ForgotPasswordScreen> createState() => _ForgotPasswordScreenState();
}
class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> {
String email = '';
bool showLoading = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox(
height: double.infinity,
width: double.infinity,
child: Center(
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(21),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Reset Password',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 21),
),
SizedBox(
height: 11,
),
Text(
'Enter the email so we can send reset password option to it.',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black54, fontSize: 13),
),
SizedBox(
height: 41,
),
emailField(),
SizedBox(
height: 11,
),
sendVerificationEmailButton(context)
],
),
),
),
)),
);
}
Widget emailField() {
return TextField(
onChanged: (value) {
setState(() {
email = value;
});
},
cursorColor: Colors.purple.shade400,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.purple.shade400)),
hintText: 'Enter email...',
hintStyle: TextStyle(color: Colors.grey.shade400, fontSize: 14)),
);
}
Widget sendVerificationEmailButton(context) {
return Padding(
padding: EdgeInsets.only(top: 21, bottom: 21),
child: MaterialButton(
onPressed: email.isEmpty
? null
: () async {
showLoading = true;
AuthClass().sendVerificationEmail(email).then((value) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Email sent'),
backgroundColor: Colors.purple,
));
});
},
padding: EdgeInsets.symmetric(vertical: 13),
minWidth: double.infinity,
color: Colors.purple.shade300,
disabledColor: Colors.grey.shade300,
textColor: Colors.white,
child: showLoading
? SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
color: Colors.white,
),
)
: Text('Send Verification Email')),
);
}
}
|
package com.lc.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lc.reggie.common.R;
import com.lc.reggie.entity.User;
import com.lc.reggie.service.UserService;
import com.lc.reggie.utils.SMSUtils;
import com.lc.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 发送手机短信验证码
* @return
*/
@PostMapping("/sendMsg")
public R<String> sendMsg(@RequestBody User user, HttpSession session){
//获取手机号
String phone = user.getPhone();
if (StringUtils.isNotEmpty(phone)) {
//生成随机的4位验证码
String code = ValidateCodeUtils.generateValidateCode4String(4);
log.info("code:{}",code);
//调用阿里云的断行服务API完成发送短信
// SMSUtils.sendMessage("天天外卖","",phone,code);
//需要将生成的验证码保存到session
session.setAttribute(phone,code);
return R.success("短信发送成功");
}
return R.error("短信发送失败");
}
/**
* 移动端用户登录
* @param map
* @param session
* @return
*/
@PostMapping("/login")
public R<User> login(@RequestBody Map map, HttpSession session){
//获取手机号
String phone = map.get("phone").toString();
//获取验证码
String code = map.get("code").toString();
//从session中获取后台生成的验证码
Object codeInSession = session.getAttribute(phone);
//后台生成的验证码与前台发送的验证码进行比对
if (codeInSession!=null &&codeInSession.equals(code)){
//判断用户是否存在,不存在则帮其创建一个账户
User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, phone));
if (user==null){
//自动注册
user = new User();
user.setPhone(phone);
user.setStatus(1);
userService.save(user);
}
session.setAttribute("userId",user.getId());
return R.success(user);
}
return R.error("登录失败");
}
}
|
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package instanceprofile
import (
"context"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/iam/iamiface"
"github.com/mitchellh/hashstructure/v2"
"github.com/patrickmn/go-cache"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
corev1beta1 "sigs.k8s.io/karpenter/pkg/apis/v1beta1"
"github.com/aws/karpenter-provider-aws/pkg/apis/v1beta1"
awserrors "github.com/aws/karpenter-provider-aws/pkg/errors"
"github.com/aws/karpenter-provider-aws/pkg/operator/options"
)
type Provider struct {
region string
iamapi iamiface.IAMAPI
cache *cache.Cache
}
func NewProvider(region string, iamapi iamiface.IAMAPI, cache *cache.Cache) *Provider {
return &Provider{
region: region,
iamapi: iamapi,
cache: cache,
}
}
func (p *Provider) Create(ctx context.Context, nodeClass *v1beta1.EC2NodeClass) (string, error) {
tags := lo.Assign(nodeClass.Spec.Tags, map[string]string{
fmt.Sprintf("kubernetes.io/cluster/%s", options.FromContext(ctx).ClusterName): "owned",
corev1beta1.ManagedByAnnotationKey: options.FromContext(ctx).ClusterName,
v1beta1.LabelNodeClass: nodeClass.Name,
v1.LabelTopologyRegion: p.region,
})
profileName := GetProfileName(ctx, p.region, nodeClass)
// An instance profile exists for this NodeClass
if _, ok := p.cache.Get(string(nodeClass.UID)); ok {
return profileName, nil
}
// Validate if the instance profile exists and has the correct role assigned to it
var instanceProfile *iam.InstanceProfile
out, err := p.iamapi.GetInstanceProfileWithContext(ctx, &iam.GetInstanceProfileInput{InstanceProfileName: aws.String(profileName)})
if err != nil {
if !awserrors.IsNotFound(err) {
return "", fmt.Errorf("getting instance profile %q, %w", profileName, err)
}
o, err := p.iamapi.CreateInstanceProfileWithContext(ctx, &iam.CreateInstanceProfileInput{
InstanceProfileName: aws.String(profileName),
Tags: lo.MapToSlice(tags, func(k, v string) *iam.Tag { return &iam.Tag{Key: aws.String(k), Value: aws.String(v)} }),
})
if err != nil {
return "", fmt.Errorf("creating instance profile %q, %w", profileName, err)
}
instanceProfile = o.InstanceProfile
} else {
instanceProfile = out.InstanceProfile
}
// Instance profiles can only have a single role assigned to them so this profile either has 1 or 0 roles
// https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html
if len(instanceProfile.Roles) == 1 {
if aws.StringValue(instanceProfile.Roles[0].RoleName) == nodeClass.Spec.Role {
return profileName, nil
}
if _, err = p.iamapi.RemoveRoleFromInstanceProfileWithContext(ctx, &iam.RemoveRoleFromInstanceProfileInput{
InstanceProfileName: aws.String(profileName),
RoleName: instanceProfile.Roles[0].RoleName,
}); err != nil {
return "", fmt.Errorf("removing role %q for instance profile %q, %w", aws.StringValue(instanceProfile.Roles[0].RoleName), profileName, err)
}
}
if _, err = p.iamapi.AddRoleToInstanceProfileWithContext(ctx, &iam.AddRoleToInstanceProfileInput{
InstanceProfileName: aws.String(profileName),
RoleName: aws.String(nodeClass.Spec.Role),
}); err != nil {
return "", fmt.Errorf("adding role %q to instance profile %q, %w", nodeClass.Spec.Role, profileName, err)
}
p.cache.SetDefault(string(nodeClass.UID), nil)
return profileName, nil
}
func (p *Provider) Delete(ctx context.Context, nodeClass *v1beta1.EC2NodeClass) error {
profileName := GetProfileName(ctx, p.region, nodeClass)
out, err := p.iamapi.GetInstanceProfileWithContext(ctx, &iam.GetInstanceProfileInput{
InstanceProfileName: aws.String(profileName),
})
if err != nil {
return awserrors.IgnoreNotFound(fmt.Errorf("getting instance profile %q, %w", profileName, err))
}
// Instance profiles can only have a single role assigned to them so this profile either has 1 or 0 roles
// https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html
if len(out.InstanceProfile.Roles) == 1 {
if _, err = p.iamapi.RemoveRoleFromInstanceProfileWithContext(ctx, &iam.RemoveRoleFromInstanceProfileInput{
InstanceProfileName: aws.String(profileName),
RoleName: out.InstanceProfile.Roles[0].RoleName,
}); err != nil {
return fmt.Errorf("removing role %q from instance profile %q, %w", aws.StringValue(out.InstanceProfile.Roles[0].RoleName), profileName, err)
}
}
if _, err = p.iamapi.DeleteInstanceProfileWithContext(ctx, &iam.DeleteInstanceProfileInput{
InstanceProfileName: aws.String(profileName),
}); err != nil {
return awserrors.IgnoreNotFound(fmt.Errorf("deleting instance profile %q, %w", profileName, err))
}
return nil
}
// GetProfileName gets the string for the profile name based on the cluster name and the NodeClass UUID.
// The length of this string can never exceed the maximum instance profile name limit of 128 characters.
func GetProfileName(ctx context.Context, region string, nodeClass *v1beta1.EC2NodeClass) string {
return fmt.Sprintf("%s_%d", options.FromContext(ctx).ClusterName, lo.Must(hashstructure.Hash(fmt.Sprintf("%s%s", region, nodeClass.Name), hashstructure.FormatV2, nil)))
}
|
#include <stdio.h>
#include <stdlib.h>
#define safeFree(p) saferFree((void**)&(p))
//free function does not check the pointer passed
//to see whether it is NULL and does not set the pointer to NULL before it returns.
//So below function does exactly the same
void saferFree(void **pp)
{
if (pp != NULL && *pp != NULL)
{
free(*pp);//remove the value
*pp = NULL;
}
}
//If I use a single pointer then changes done on p won't be reflecting, as void *p is a local variable in freer.
//that's why we have to use double pointer so that address of passed pointer becomes a value passed by reference.
//to see this effect this file, check_this_pointer_case.c.
//So to still work with single pointer we have to pass the changes done in p by returning.
//approach 1 is better as we do not need to
void *freer(void *p)
{
if(p != NULL)
{
free(p);
p = NULL;
}
return p;
}
/*
//totally wrong code for intended purpose.
void freer(void *p)
{
if(p != NULL && &p != NULL)
{
free(p);
p = NULL;
}
}
*/
int main()
{
int *pi;
pi = (int*) malloc(sizeof(int));
*pi = 5;
printf("Before: %p\n",pi);
//safeFree(pi);//saferFree((void **)&p);
pi = freer(pi);//no need to cast
printf("After: %p\n",pi);
//safeFree(pi);
pi = freer(pi);
return (EXIT_SUCCESS);
}
|
<% content_for :title, "Guided - Nearest landmark" %>
<!-- Banner -->
<div class="landmarkshow-banner" style="background-image: linear-gradient(-225deg, rgba(0,101,168,0.1) 0%, rgba(0,36,61,0.1) 50%), url(<%= @nearest_landmark.image %>);">
<div class="landmarkbanner-content">
<p>
Your nearest landmark
</p>
<h1>
<%= @nearest_landmark.name %>
</h1>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-xs-12 col-lg-6 landmarkshow-content">
<p>
<%= @nearest_landmark.description %>
</p>
</div>
<!-- Display Stories attached to current nearest location -->
<div class="col-xs-12">
<%= render 'stories/story_list', stories: @stories %>
</div>
<!-- Add a new story -->
<div class="col-xs-12 new-nearest-story-button">
<% if current_user != nil %>
<%= link_to new_story_path(landmark: @nearest_landmark.id), class: "link-success" do %>
<i class="fa fa-plus"></i> Add a story
<% end %>
<% else %>
<%= link_to new_user_session_path, class: "link-success" do %>
<i class="fa fa-plus"></i> Add a story
<% end %>
<% end %>
</div>
</div>
<!-- Show 4 nearest landmarks + map -->
<div class="row">
<div class="col-xs-12">
<h2>Other landmarks near you</h2>
<%= render 'landmark_list', landmarks: @landmarks.drop(1) %>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<%= render 'shared/map', markers: @markers %>
</div>
</div>
</div>
<!--################## Experimentation zone ##############################################-->
<div class="container">
<h1>Nearby Google Places</h1>
<div class="row">
<% @places.each do |place| %> <!-- Start -->
<div class="col-xs-12 col-md-6">
<% if place.photos[0] != nil %> <!-- Start -->
<div class="card landmark-card" style="background-image: linear-gradient(rgba(0,0,0,0.3), rgba(0,0,0,0.2)), url( <%= place.photos[0].fetch_url(400) %>);">
<% else %>
<div class="card landmark-card" style="background-image: linear-gradient(rgba(0,0,0,0.3), rgba(0,0,0,0.2)), url(http://21642-presscdn.pagely.netdna-cdn.com/wp-content/themes/nucleare-pro/images/no-image-box.png;">
<% end %> <!-- end -->
<div class="card-description">
<h2>
<%= place.name %>(<%=place.vicinity%>)
</h2>
<p>
<%= place.types %>
</p>
</div>
</div>
<div class="landmark-follow-star">
<img src="<%= place.icon %>" alt="">
</div>
</div>
<% end %> <!-- end -->
</div>
<!-- Input for places search-->
<br>
<input name="location" id="location" value="search" />
<script>
const locationInput = document.getElementById("location");
console.log(locationInput.value);
locationInput.addEventListener("click", (event) => {
// console.log(event)
console.log(locationInput.value)
});
</script>
<!-- Not going to work because input is javascript -->
<% @client.predictions_by_input('locationInput.value') %>
</div>
</div>
|
package pl.niewadzj.moneyExchange.config.jwt;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;
import java.util.function.Function;
@Service
public class JwtService {
private static final String SECRET = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
private static final long EXPIRATION_TIME = 1000L * 60L * 10L;
private static final long REFRESH_TIME = 1000L * 60L * 60L;
public String extractEmail(String token) {
return extractClaim(token, Claims::getSubject);
}
private <T> T extractClaim(String token, Function<Claims, T> resolver) {
Claims claims = extractAllClaims(token);
return resolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return Jwts
.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(token)
.getPayload();
}
public String generateRefreshToken(UserDetails user) {
return generateToken(Map.of("role", user.getAuthorities()), user, REFRESH_TIME);
}
public String generateToken(UserDetails user) {
return generateToken(Map.of("role", user.getAuthorities()), user, EXPIRATION_TIME);
}
public String generateToken(Map<String, Object> extraClaims, UserDetails user, long expiration) {
final Date now = new Date(System.currentTimeMillis());
final Date expirationDate = new Date(System.currentTimeMillis() + expiration);
return Jwts
.builder()
.claims(extraClaims)
.subject(user.getUsername())
.issuedAt(now)
.expiration(expirationDate)
.signWith(getSigningKey())
.compact();
}
public boolean isTokenValid(String token, UserDetails user) {
final String tokenEmail = extractEmail(token);
return tokenEmail.equals(user.getUsername()) && !isTokenExpired(token);
}
private boolean isTokenExpired(String token) {
return extractExpirationDate(token).before(new Date());
}
private Date extractExpirationDate(String token) {
return extractClaim(token, Claims::getExpiration);
}
private SecretKey getSigningKey() {
byte[] keyBytes = Decoders.BASE64.decode(SECRET);
return Keys.hmacShaKeyFor(keyBytes);
}
}
|
//
// ViewController.swift
// NewsTimeProject
//
// Created by Defne Çetiner on 11.05.2023.
//
import UIKit
import NewsAPI
final class NewsListViewController: UIViewController, LoadingShowable {
@IBOutlet private weak var tableView: UITableView!
private let service: NewsServiceProtocol = NewsService()
private var news: [News] = []
private var media: [Multimedia] = []
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchNews()
}
override func viewDidLoad() {
tableView.register(.init(nibName: "NewsTimeTableViewCell", bundle: nil),forCellReuseIdentifier: "news")
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
}
private func fetchNews() {
self.showLoading()
service.fetchNews { [weak self] response in
guard let self else { return }
self.hideLoading()
switch response {
case .success(let news):
self.news = news
self.tableView.reloadData()
case .failure(let error):
let alertController = UIAlertController(title: "Hata", message: error.localizedDescription, preferredStyle: .alert)
let okAction = UIAlertAction(title: "Tamam", style: .default, handler: nil)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}
extension NewsListViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
news.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "news", for: indexPath) as! NewsTimeTableViewCell
let news = self.news[indexPath.row]
cell.configure(news: news)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedNews = news[indexPath.row]
let newsTimeDetailsVC = storyboard?.instantiateViewController(withIdentifier: "news") as! NewsDetailViewController
newsTimeDetailsVC.selectedNews = selectedNews
self.navigationController?.pushViewController(newsTimeDetailsVC, animated: true)
}
}
|
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import nltk
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
import string
from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer
from sklearn.model_selection import train_test_split
nltk.download('punkt')
def preprocess_data(file_path='spam.csv'):
df = pd.read_csv(file_path, encoding='ISO-8859-1')
df.drop(columns=['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4'], inplace=True)
df.rename(columns={'v1': 'target', 'v2': 'text'}, inplace=True)
encoder = LabelEncoder()
df['target'] = encoder.fit_transform(df['target'])
df = df.drop_duplicates(keep='first')
df['num_characters'] = df['text'].apply(len)
df['num_words'] = df['text'].apply(lambda x: len(nltk.word_tokenize(x)))
df['num_sentences'] = df['text'].apply(lambda x: len(nltk.sent_tokenize(x)))
df['transformed_text'] = df['text'].apply(transform_text)
spam_corpus = [word for msg in df[df['target'] == 1]['transformed_text'].tolist() for word in msg.split()]
ham_corpus = [word for msg in df[df['target'] == 0]['transformed_text'].tolist() for word in msg.split()]
vectorizer = None
if vectorizer is None:
vectorizer = TfidfVectorizer(max_features=3000)
X = vectorizer.fit_transform(df['transformed_text']).toarray()
else:
X = vectorizer.transform(df['transformed_text']).toarray()
y = df['target'].values
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.3, random_state=42)
X_valid, X_test, y_valid, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)
return X_train, X_valid, X_test, y_train, y_valid, y_test, vectorizer
def transform_text(text):
text = text.lower()
text = nltk.word_tokenize(text)
y = [i for i in text if i.isalnum()]
y = [i for i in y if i not in stopwords.words('english') and i not in string.punctuation]
ps = PorterStemmer()
y = [ps.stem(i) for i in y]
return " ".join(y)
if __name__ == "__main__":
X_train, X_valid, X_test, y_train, y_valid, y_test,vectorizer = preprocess_data()
print("Shape of X_train:", X_train.shape)
print("Shape of X_valid:", X_valid.shape)
print("Shape of X_test:", X_test.shape)
print("Shape of y_train:", y_train.shape)
print("Shape of y_valid:", y_valid.shape)
print("Shape of y_test:", y_test.shape)
|
//------------------------------------------------
//--- 010 Editor v9.0.1 Binary Template
//
// File: Util.bt
// Authors: TKGP
// Version:
// Purpose: Utility types and functions for SoulsTemplates
// Category:
// File Mask:
// ID Bytes:
// History:
//------------------------------------------------
#ifndef _SOULSTEMPLATES_UTIL
#define _SOULSTEMPLATES_UTIL
void Align(int align) {
if (FTell() % align > 0) {
FSkip(align - (FTell() % align));
}
}
void AlignRelative(int base, int align) {
local int offset = (FTell() - base) % align;
if (offset) {
FSkip(align - offset);
}
}
int IsBool(int value) {
return value == 0 || value == 1;
}
ubyte ReverseBits(ubyte value) {
return
((value & 0b00000001) << 7) |
((value & 0b00000010) << 5) |
((value & 0b00000100) << 3) |
((value & 0b00001000) << 1) |
((value & 0b00010000) >> 1) |
((value & 0b00100000) >> 3) |
((value & 0b01000000) >> 5) |
((value & 0b10000000) >> 7);
}
typedef struct {
float x;
float y;
} Vector2 <read=ReadVector2>;
string ReadVector2(Vector2& vec) {
string str;
SPrintf(str, "<%7.2f, %7.2f>", vec.x, vec.y);
return str;
}
string ReadVector2Fmt(Vector2& vec, int width, int precision) {
string fmt;
SPrintf(fmt, "<%%%d.%df, %%%d.%df>",
width, precision, width, precision);
string str;
return SPrintf(str, fmt, vec.x, vec.y);
}
typedef struct {
float x;
float y;
float z;
} Vector3 <read=ReadVector3>;
string ReadVector3(Vector3& vec) {
string str;
SPrintf(str, "<%7.2f, %7.2f, %7.2f>", vec.x, vec.y, vec.z);
return str;
}
string ReadVector3Fmt(Vector3& vec, int width, int precision) {
string fmt;
SPrintf(fmt, "<%%%d.%df, %%%d.%df, %%%d.%df>",
width, precision, width, precision, width, precision);
string str;
return SPrintf(str, fmt, vec.x, vec.y, vec.z);
}
typedef struct {
float x;
float y;
float z;
float w;
} Vector4 <read=ReadVector4>;
string ReadVector4(Vector4& vec) {
string str;
SPrintf(str, "<%7.2f, %7.2f, %7.2f, %7.2f>", vec.x, vec.y, vec.z, vec.w);
return str;
}
string ReadVector4Fmt(Vector4& vec, int width, int precision) {
string fmt;
SPrintf(fmt, "<%%%d.%df, %%%d.%df, %%%d.%df, %%%d.%df>",
width, precision, width, precision, width, precision, width, precision);
string str;
return SPrintf(str, fmt, vec.x, vec.y, vec.z, vec.w);
}
typedef struct (int longOffset, int unicode) {
if (longOffset)
quad offset <format=hex>;
else
uint offset <format=hex>;
local quad pos <hidden=true> = FTell();
FSeek(offset);
if (unicode)
wstring str;
else
string str;
FSeek(pos);
} OffsetString <read=ReadOffsetString>;
wstring ReadOffsetString(OffsetString& os) {
return os.str;
}
typedef struct {
string str;
} WrappedString <read=ReadWrappedString>;
string ReadWrappedString(WrappedString& ws) {
return ws.str;
}
typedef struct {
wstring str;
} WrappedWString <read=ReadWrappedWString>;
wstring ReadWrappedWString(WrappedWString& wws) {
return wws.str;
}
typedef struct {
if (VARINT_LONG)
quad val;
else
int val;
} Varint <read=ReadVarint>;
string ReadVarint(Varint& v) {
string s;
SPrintf(s, "%Xh | %d", v.val, v.val);
return s;
}
#endif
|
import getFireBaseImage from "@/lib/getFireBaseImage";
import { useEffect, useState } from "react";
import Image from "next/image";
export default function PostImage({ postName, height, width }) {
const [imageURL, setImageURL] = useState("");
const [imageName, setImageName] = useState("");
useEffect(() => {
setImageName(`${postName}`);
}, [postName]);
useEffect(() => {
async function fetchImage() {
if (imageName) {
const url = await getFireBaseImage(imageName, "blogs");
setImageURL(url);
}
}
if (imageName) {
fetchImage();
}
}, [imageName]);
return (
<Image
className="rounded-3xl"
src={imageURL}
height={height}
width={width}
/>
);
}
|
<template>
<div class="mod-config">
<el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
<el-form-item>
<el-input v-model="dataForm.key" placeholder="Parameter Name" clearable></el-input>
</el-form-item>
<el-form-item>
<el-button @click="getDataList()">Query</el-button>
<el-button v-if="isAuth('commodity:skuinfo:save')" type="primary" @click="addOrUpdateHandle()">Add</el-button>
<el-button v-if="isAuth('commodity:skuinfo:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">Batch Deletion</el-button>
</el-form-item>
</el-form>
<el-table
:data="dataList"
border
v-loading="dataListLoading"
@selection-change="selectionChangeHandle"
style="width: 100%;">
<el-table-column
type="selection"
header-align="center"
align="center"
width="50">
</el-table-column>
<el-table-column
prop="skuId"
header-align="center"
align="center"
label="skuId">
</el-table-column>
<el-table-column
prop="spuId"
header-align="center"
align="center"
label="spu Id">
</el-table-column>
<el-table-column
prop="skuName"
header-align="center"
align="center"
label="sku name">
</el-table-column>
<el-table-column
prop="skuDesc"
header-align="center"
align="center"
label="sku description">
</el-table-column>
<el-table-column
prop="catalogId"
header-align="center"
align="center"
label="category id">
</el-table-column>
<el-table-column
prop="brandId"
header-align="center"
align="center"
label="brand id">
</el-table-column>
<el-table-column
prop="skuDefaultImg"
header-align="center"
align="center"
label="default image">
</el-table-column>
<el-table-column
prop="skuTitle"
header-align="center"
align="center"
label="sku title">
</el-table-column>
<el-table-column
prop="skuSubtitle"
header-align="center"
align="center"
label="sku sub title">
</el-table-column>
<el-table-column
prop="price"
header-align="center"
align="center"
label="price">
</el-table-column>
<el-table-column
prop="saleCount"
header-align="center"
align="center"
label="sales volume">
</el-table-column>
<el-table-column
fixed="right"
header-align="center"
align="center"
width="150"
label="操作">
<template slot-scope="scope">
<el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.skuId)">Update</el-button>
<el-button type="text" size="small" @click="deleteHandle(scope.row.skuId)">Delete</el-button>
</template>
</el-table-column>
</el-table>
<el-pagination
@size-change="sizeChangeHandle"
@current-change="currentChangeHandle"
:current-page="pageIndex"
:page-sizes="[10, 20, 50, 100]"
:page-size="pageSize"
:total="totalPage"
layout="total, sizes, prev, pager, next, jumper">
</el-pagination>
<!-- pop-up window, add / update -->
<add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
</div>
</template>
<script>
import AddOrUpdate from './skuinfo-add-or-update'
export default {
data () {
return {
dataForm: {
key: ''
},
dataList: [],
pageIndex: 1,
pageSize: 10,
totalPage: 0,
dataListLoading: false,
dataListSelections: [],
addOrUpdateVisible: false
}
},
components: {
AddOrUpdate
},
activated () {
this.getDataList()
},
methods: {
// get data list
getDataList () {
this.dataListLoading = true
this.$http({
url: this.$http.adornUrl('/commodity/skuinfo/list'),
method: 'get',
params: this.$http.adornParams({
'page': this.pageIndex,
'limit': this.pageSize,
'key': this.dataForm.key
})
}).then(({data}) => {
if (data && data.code === 0) {
this.dataList = data.page.list
this.totalPage = data.page.totalCount
} else {
this.dataList = []
this.totalPage = 0
}
this.dataListLoading = false
})
},
// amount per page
sizeChangeHandle (val) {
this.pageSize = val
this.pageIndex = 1
this.getDataList()
},
// current page
currentChangeHandle (val) {
this.pageIndex = val
this.getDataList()
},
// multiple selection
selectionChangeHandle (val) {
this.dataListSelections = val
},
// add / update
addOrUpdateHandle (id) {
this.addOrUpdateVisible = true
this.$nextTick(() => {
this.$refs.addOrUpdate.init(id)
})
},
// delete
deleteHandle (id) {
var ids = id ? [id] : this.dataListSelections.map(item => {
return item.skuId
})
this.$confirm(`Do you want to [${id ? 'delete' : 'batch delete'}] [id=${ids.join(',')}]?`, 'warning', {
confirmButtonText: 'Sure',
cancelButtonText: 'Cancel',
type: 'warning'
}).then(() => {
this.$http({
url: this.$http.adornUrl('/commodity/skuinfo/delete'),
method: 'post',
data: this.$http.adornData(ids, false)
}).then(({data}) => {
if (data && data.code === 0) {
this.$message({
message: 'Completed',
type: 'success',
duration: 1500,
onClose: () => {
this.getDataList()
}
})
} else {
this.$message.error(data.msg)
}
})
})
}
}
}
</script>
|
import pybroker as pb
import pandas as pd
import traceback
from auto.indicator_talib import calculate_indicator
from pybroker import Strategy
from sqlalchemy import text
from auto.strategy_content import buy_with_indicator,buy_low
from auto.strategy_chart import create_strategy_charts
from auto.parameter import database
def execute_backtest():
print("开始回测")
datasource = pd.DataFrame()
backtest_symbol = pb.param(name='backtest_symbol')
backtest_start_date = pb.param(name='backtest_start_date')
backtest_end_date = pb.param(name='backtest_end_date')
initial_cash_value = int(pb.param(name='initial_cash'))
print('backtest_symbol:', backtest_symbol)
print('backtest_start_date:', backtest_start_date)
print('backtest_end_date:', backtest_end_date)
print('initial_cash_value:', initial_cash_value)
engine = database();
conn = engine.connect()
sql = f"SELECT * FROM basic_data_stock_code_akshare WHERE Symbol IN ({backtest_symbol})"
df = pd.read_sql(text(sql), conn)
#初始资金
my_config = pb.StrategyConfig(initial_cash=initial_cash_value)
# 处理查询结果
for index,row in df.iterrows():
try:
symbolCode = row['Symbol']
stockName = row['StockName']
pageName = symbolCode + " " + stockName
sql = f"SELECT * FROM basic_stock_history_day_hfq_akshare WHERE symbol='{symbolCode}' AND date BETWEEN '{backtest_start_date}' AND '{backtest_end_date}' ORDER BY date"
print(sql)
df = pd.read_sql(text(sql), conn)
#计算指标
data_with_indicator = calculate_indicator(df)
data_with_indicator['date'] = pd.to_datetime(data_with_indicator['date'])
# print(data_with_indicator.shape[0])
datasource = pd.concat([datasource, data_with_indicator])
# print(datasource.shape[0])
except Exception as error:
print(symbolCode, stockName, "回测异常", traceback.print_exc(), " : ", error)
else:
print(symbolCode, stockName,'回测完成')
# print(data_with_indicator)
#在pybroker中注册指标名称
'''MACD指标'''
pb.register_columns('macd')
pb.register_columns('macdsignal')
pb.register_columns('macdhist')
'''MFI指标'''
pb.register_columns('MFI')
'''CCI指标'''
pb.register_columns('CCI')
'''ROC指标'''
pb.register_columns('ROC')
'''RSI指标'''
pb.register_columns('RSI')
'''OBV指标'''
pb.register_columns('OBV')
'''ATR指标'''
pb.register_columns('ATR')
print(datasource)
#创建策略
strategy = Strategy(datasource, start_date=backtest_start_date, end_date=backtest_end_date, config=my_config)
# for index,row in df.iterrows():
# print(row['Symbol'])
# 设置股票对应的策略
strategy.add_execution(buy_low, symbols=['000012','000333','000623','000756','000951'])
#strategy.add_execution(buy_with_indicator, symbols=['000012','000333','000623','000756','000951'])
# 执行回测,并打印出回测结果的度量值(四舍五入到小数点后四位)
result = strategy.backtest()
print(result.metrics_df.round(2))
return_order_metrics = result.metrics_df.round(2)
trade_count=0
initial_market_value=0
for index,row in return_order_metrics.iterrows():
name = row['name']
value = row['value']
if(name=='trade_count'): trade_count=value
elif (name=='initial_market_value'): initial_market_value=value
elif (name=='end_market_value'): end_market_value=value
elif (name=='total_pnl'): total_pnl=value
elif (name=='unrealized_pnl'): unrealized_pnl=value
elif (name=='total_return_pct'): total_return_pct=value
elif (name=='total_profit'): total_profit=value
elif (name=='total_loss'): total_loss=value
elif (name=='total_fees'): total_fees=value
elif (name=='max_drawdown'): max_drawdown=value
elif (name=='max_drawdown_pct'): max_drawdown_pct=value
elif (name=='win_rate'): win_rate=value
elif (name=='loss_rate'): loss_rate=value
elif (name=='winning_trades'): winning_trades=value
elif (name=='losing_trades'): losing_trades=value
elif (name=='avg_pnl'): avg_pnl=value
elif (name=='avg_return_pct'): avg_return_pct=value
elif (name=='avg_trade_bars'): avg_trade_bars=value
elif (name=='avg_profit'): avg_profit=value
elif (name=='avg_profit_pct'): avg_profit_pct=value
elif (name=='avg_winning_trade_bars'): avg_winning_trade_bars=value
elif (name=='avg_loss'): avg_loss=value
elif (name=='avg_loss_pct'): avg_loss_pct=value
elif (name=='avg_losing_trade_bars'): avg_losing_trade_bars=value
elif (name=='largest_win'): largest_win=value
elif (name=='largest_win_pct'): largest_win_pct=value
elif (name=='largest_win_bars'): largest_win_bars=value
elif (name=='largest_loss'): largest_loss=value
elif (name=='largest_loss_pct'): largest_loss_pct=value
elif (name=='largest_loss_bars'): largest_loss_bars=value
elif (name=='max_wins'): max_wins=value
elif (name=='max_losses'): max_losses=value
elif (name=='sharpe'): sharpe=value
elif (name=='sortino'): sortino=value
elif (name=='profit_factor'): profit_factor=value
elif (name=='ulcer_index'): ulcer_index=value
elif (name=='upi'): upi=value
elif (name=='equity_r2'): equity_r2=value
elif (name=='std_error'): std_error=value
insertsql = text("INSERT INTO return_metrics (trade_count, initial_market_value, end_market_value, total_pnl, unrealized_pnl, total_return_pct, total_profit, total_loss, total_fees, max_drawdown, max_drawdown_pct, win_rate, loss_rate, winning_trades, losing_trades, avg_pnl, avg_return_pct, avg_trade_bars, avg_profit, avg_profit_pct, avg_winning_trade_bars, avg_loss, avg_loss_pct, avg_losing_trade_bars, largest_win, largest_win_pct, largest_win_bars, largest_loss, largest_loss_pct, largest_loss_bars, max_wins, max_losses, sharpe, sortino, profit_factor, ulcer_index, upi, equity_r2, std_error) VALUES ("
+ " " + str(trade_count)
+ ", " + str(initial_market_value)
+ ", " + str(end_market_value)
+ ", " + str(total_pnl)
+ ", " + str(unrealized_pnl)
+ ", " + str(total_return_pct)
+ ", " + str(total_profit)
+ ", " + str(total_loss)
+ ", " + str(total_fees)
+ ", " + str(max_drawdown)
+ ", " + str(max_drawdown_pct)
+ ", " + str(win_rate)
+ ", " + str(loss_rate)
+ ", " + str(winning_trades)
+ ", " + str(losing_trades)
+ ", " + str(avg_pnl)
+ ", " + str(avg_return_pct)
+ ", " + str(avg_trade_bars)
+ ", " + str(avg_profit)
+ ", " + str(avg_profit_pct)
+ ", " + str(avg_winning_trade_bars)
+ ", " + str(avg_loss)
+ ", " + str(avg_loss_pct)
+ ", " + str(avg_losing_trade_bars)
+ ", " + str(largest_win)
+ ", " + str(largest_win_pct)
+ ", " + str(largest_win_bars)
+ ", " + str(largest_loss)
+ ", " + str(largest_loss_pct)
+ ", " + str(largest_loss_bars)
+ ", " + str(max_wins)
+ ", " + str(max_losses)
+ ", " + str(sharpe)
+ ", " + str(sortino)
+ ", " + str(profit_factor)
+ ", " + str(ulcer_index)
+ ", " + str(upi)
+ ", " + str(equity_r2)
+ ", " + str(std_error) + ")")
conn.execute(insertsql)
conn.commit()
# 显示所有列
pd.set_option('display.max_columns',None)
# 显示所有行
pd.set_option('display.max_rows',None)
return_order_df = result.orders
return_order_df.to_sql(name="return_order", con=conn, index=True ,if_exists='append')
conn.commit()
print(return_order_df)
return_positions_df = result.positions
return_positions_df.to_sql(name="return_positions", con=conn, index=True ,if_exists='append')
conn.commit()
print(return_positions_df)
return_portfolio_df = result.portfolio
return_portfolio_df.to_sql(name="return_portfolio", con=conn, index=True ,if_exists='append')
conn.commit()
print(return_portfolio_df)
return_trades_df = result.trades
return_trades_df.to_sql(name="return_trades", con=conn, index=True ,if_exists='append')
conn.commit()
print(return_trades_df)
#创建图表
create_strategy_charts(data_with_indicator,result)
|
import { defineStore } from 'pinia'
import {useDruxtMenu} from "../composables/useDruxtMenu";
const DruxtMenuStore = defineStore({
id: 'druxt-menu-store',
state: () => ({
entities: {},
}),
/**
* Actions.
*/
actions: {
/**
* Get menu by name.
*
* - Fetches the menu items from the JSON:API endpoint.
* - Commits the menu items to the Vuex state object.
*
* @name get
* @action get=entities
* @param {object} app - The Nuxt app context.
* @param {string|object} context - The Menu name or context object.
*
* @example @lang js
* await this.$store.dispatch('druxtMenu/get', { name: 'main' })
*/
async get ( context ) {
const { name, settings, prefix } = typeof context === 'object'
? context
: { name: context }
const { entities } = (await useDruxtMenu().get(name, settings, prefix)) || {}
this.addEntities(entities, prefix)
},
/**
* @name addEntities
* @mutator {object} addEntities=entities Adds specified Drupal JSON:API Menu Items data to the Vuex state object.
* @param {State} state - The Vuex State object.
* @param {object} entities - The Drupal JSON:API Menu Item entities.
*
* @example @lang js
*/
addEntities ( entities, prefix = null) {
if (!this.entities[prefix]) this.entities[prefix] = {};
const x = this.entities;
for (const index in entities) {
const entity = entities[index]
this.entities[prefix][entity.id] = entity;
}
},
/**
* @name getEntitiesByFilter
* @mutator {object} getEntitiesByFilter=entities Adds specified Drupal JSON:API Menu Items data to the Vuex state object.
* @param {State} state - The Vuex State object.
* @param {object} entities - The Drupal JSON:API Menu Item entities.
*
* @example @lang js
*/
getEntitiesByFilter ( filter, prefix = null ) {
const keys = Object.keys((this.entities || {})[prefix]).filter(key => filter(key, this.entities, prefix))
if (!keys.length) return {}
return Object.assign(
...keys.map(key => ({ [key]: this.entities[prefix][key] }))
)
}
}
});
export { DruxtMenuStore }
|
#include <iostream>
using namespace std;
// In this problem the list is given with the values and it is sorted in such a way that all the evens comes
// before the odd . Consequently, the even values would be on the LHS and odd values would be on RHS.
class Node
{
public:
int data;
Node *next;
Node()
{
data = 0;
next = nullptr;
}
Node(int data)
{
this->data = data;
this->next = nullptr;
}
};
class SinglyLinkedList
{
public:
Node *head; // Note, only using head for pointing , not using its data
SinglyLinkedList()
{
head = new Node();
}
void insert_tail(int value){
if(NodeExist(value)){
cout<<" A node with a value "<<value<<" already exist !"<<endl;
}
else
{
Node* n = head;
while(n->next != nullptr) n=n->next;
n->next = new Node(value);
}
}
bool NodeExist(int value){
Node* n = head->next;
while(n != nullptr && n->data != value) n=n->next;
if(n != nullptr && n->data == value) return true;
else return false;
}
void traverse(){
Node* n = head->next;
while(n != nullptr) {
cout<<n->data<<" ";
n=n->next;
}
}
};
int main()
{
SinglyLinkedList list;
cout<<"How many elements do you want in list : ";
int n;
cin>>n;
cout<<"\nNote repeated elements cannot be inserted ! \n\n";
for(int i=0;i<n;i++)
{
cout<<"Enter the value you want to insert : ";
int temp;
cin>>temp;
list.insert_tail(temp);
}
cout<<"The list is : ";
list.traverse();
cout<<endl;
return 0;
}
|
import matplotlib.pyplot as plt
import numpy as np
# A scatter plot in Python is a type of plot used to represent the relationship between two variables.
# Each point in the scatter plot represents a pair of values from the data, allowing you to visualize trends,
# correlations, or patterns in the dataset.
# Generate random data for the scatter plot
x = np.random.rand(50)
# Linear relationship with some noise
y = 2 * x + 1 + 0.1 * np.random.randn(50)
# Create the scatter plot
plt.scatter(x, y)
# Add titles and axis labels
plt.title('Scatter Plot')
# Label for the x-axis
plt.xlabel('X-axis')
# Label for the y-axis
plt.ylabel('Y-axis')
# Display the plot
plt.show()
|
package org.graphs;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class GraphAdjList {
private int N; // number of nodes
private int M; // number of edges
private ArrayList<Integer>[] adjencyList; // adjacency list representation of the graph
public GraphAdjList(String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
N = 0;
M = 0;
while ((line = br.readLine()) != null) {
String[] tokens = line.trim().split("\\s+");
int u = Integer.parseInt(tokens[0]);
int v = Integer.parseInt(tokens[1]);
N = Math.max(N, Math.max(u, v));
M++;
}
br.close();
adjencyList = new ArrayList[N + 1];
for (int i = 1; i <= N; i++) {
adjencyList[i] = new ArrayList<Integer>();
}
br = new BufferedReader(new FileReader(filename));
while ((line = br.readLine()) != null) {
String[] tokens = line.trim().split("\\s+");
int u = Integer.parseInt(tokens[0]);
int v = Integer.parseInt(tokens[1]);
if (u != 0 && v != 0) {
adjencyList[u].add(v);
adjencyList[v].add(u);
}
}
br.close();
}
public void addEdge(int u, int v) {
if (u != 0 && v != 0) {
adjencyList[u].add(v);
adjencyList[v].add(u);
M++;
}
}
public int getN() {
return N;
}
public int getM() {
return M;
}
public ArrayList<Integer>[] getAdjencyList() {
return adjencyList;
}
public void Neighbors(int v) {
System.out.print("Edge's Neighbors " + v + " : ");
for (int neighbor : adjencyList[v]) {
System.out.print(neighbor + " ");
}
System.out.println();
}
public int Degree(int v) {
return adjencyList[v].size();
}
public void structuralProperties() {
int minimumDegree = Integer.MAX_VALUE;
int maximumDegree = Integer.MIN_VALUE;
int sumDegree = 0;
int isolatedNodes = 0;
boolean hasLoops = false;
for (int v = 1; v <= N; v++) {
int degree = Degree(v);
if (degree == 0) {
isolatedNodes++;
}
if (degree > maximumDegree) {
maximumDegree = degree;
}
if (degree < minimumDegree) {
minimumDegree = degree;
}
if (adjencyList[v].contains(v)) {
hasLoops = true;
}
sumDegree += degree;
}
double averageDegree = sumDegree / (double) N;
double edgeDensity = 2 * M / (double) (N * (N - 1));// Compute edge-density
System.out.println("Average degree: " + averageDegree);
System.out.println("Minimum degree: " + minimumDegree);
System.out.println("Maximum degree: " + maximumDegree);
System.out.println("Edge density: " + edgeDensity);
if (edgeDensity >= 0.5) {
System.out.println("This graph is dense");
} else {
System.out.println("This graph is sparse");
}
System.out.println("Number of isolated nodes: " + isolatedNodes);
System.out.println("Has loops: " + hasLoops);
}
public static void printAllNeighbors(GraphAdjList graph, ArrayList<Integer>[] adjList) {
for (int i = 1; i <= graph.getN(); i++) {
System.out.print(i + ": ");
for (int j = 0; j < adjList[i].size(); j++) {
System.out.print(adjList[i].get(j) + " ");
}
System.out.println();
}
}
}
|
namespace Seedwork;
/// <summary>
/// Entity interface.
/// </summary>
public interface IEntity
{
/// <summary>
/// Collection of domain events.
/// </summary>
IReadOnlyCollection<IDomainEvent> DomainEvents { get; }
/// <summary>
/// Removes all domain events.
/// </summary>
void ClearDomainEvents();
/// <summary>
/// Moves all domain events from <paramref name="entity"/> to current.
/// </summary>
/// <param name="entity">Entity.</param>
void MoveDomainEventsFrom(IEntity entity);
}
/// <summary>
/// Entity base class.
/// </summary>
public abstract class Entity : IEntity
{
/// <summary>
/// Collection of domain events.
/// </summary>
private List<IDomainEvent>? _domainEvents;
/// <summary>
/// Collection of domain events.
/// </summary>
public IReadOnlyCollection<IDomainEvent> DomainEvents
{
get
{
if (_domainEvents is not null)
{
return _domainEvents.AsReadOnly();
}
return Array.Empty<IDomainEvent>();
}
}
/// <summary>
/// Adds domain event to collection.
/// </summary>
/// <param name="domainEvent">Domain event to add.</param>
/// <exception cref="ArgumentNullException">
/// Throws, when <paramref name="domainEvent"/> was null.
/// </exception>
protected virtual void AddDomainEvent(IDomainEvent domainEvent)
{
ArgumentNullException.ThrowIfNull(domainEvent);
_domainEvents ??= [];
_domainEvents.Add(domainEvent);
}
/// <summary>
/// Replace domain event in collection.
/// </summary>
/// <param name="domainEvent">Domain event to add.</param>
/// <exception cref="ArgumentNullException">
/// Throws, when <paramref name="domainEvent"/> was null.
/// </exception>
protected virtual void ReplaceDomainEvent(IDomainEvent domainEvent)
{
ArgumentNullException.ThrowIfNull(domainEvent);
_domainEvents ??= [];
_domainEvents.RemoveAll(x => x.GetType() == domainEvent.GetType());
_domainEvents.Add(domainEvent);
}
/// <summary>
/// Removes all domain events.
/// </summary>
public void ClearDomainEvents()
{
_domainEvents?.Clear();
}
/// <summary>
/// Moves all domain events from <paramref name="entity"/> to current.
/// </summary>
/// <param name="entity">Entity.</param>
public void MoveDomainEventsFrom(IEntity entity)
{
ArgumentNullException.ThrowIfNull(entity);
_domainEvents ??= [];
_domainEvents.AddRange(entity.DomainEvents);
entity.ClearDomainEvents();
}
}
|
import React, { createContext, FC, useContext } from 'react';
import { PrimaryProfile } from '@/controllers/graphql/generated';
interface ProfileState {
profileType: PrimaryProfile;
setProfileType: (value: PrimaryProfile) => void;
}
const initialState: ProfileState = {
profileType: PrimaryProfile.NotDefined,
setProfileType: () => { /* EMPTY */ },
};
const ProfileContext = createContext<ProfileState>(initialState);
interface Props {
data: ProfileState;
}
export const ProfileProvider: FC<Props> = (props) => {
const { data, children } = props;
return (
<ProfileContext.Provider value={data}>
{children}
</ProfileContext.Provider>
);
};
export const useProfileContext = () => useContext(ProfileContext);
|
using Zambon.OrderManagement.Core.BusinessEntities.Security;
using Zambon.OrderManagement.WebApi.Helpers.Exceptions;
using Zambon.OrderManagement.WebApi.Models;
namespace Zambon.OrderManagement.WebApi.Services.Security.Interfaces
{
/// <summary>
/// Service for authentication of the <see cref="Users"/>.
/// </summary>
public interface IAuthenticationService
{
/// <summary>
/// Refresh the JWT token using a valid Refresh Token.
/// </summary>
/// <param name="model">The <see cref="RefreshTokenModel"/> instance to refresh the token.</param>
/// <returns>An instance of <see cref="AuthenticationResponseModel"/> representing the acess token and properties from the <see cref="Users"/> instance.</returns>
/// <exception cref="ArgumentNullException">If the <see cref="RefreshTokenModel" /> is null.</exception>
/// <exception cref="RefreshTokenNotFoundException">If missing the username or refresh token, the user or refresh token are invalid, or password does not match.</exception>
/// <exception cref="InvalidRefreshTokenException">If the refresh token is revoked or expired.</exception>
Task<AuthenticationResponseModel> RefreshTokenAsync(RefreshTokenModel model);
/// <summary>
/// Validate the user credentials to grant access to the API.
/// </summary>
/// <param name="model">The <see cref="RefreshTokenModel"/> instance to sign in the user.</param>
/// <returns>An instance of <see cref="AuthenticationResponseModel"/> representing the acess token and properties from the <see cref="Users"/> instance.</returns>
/// <exception cref="ArgumentNullException">If the <see cref="SignInModel" /> is null.</exception>
/// <exception cref="InvalidAuthenticationException">If missing the username or password, the user is invalid, or password does not match.</exception>
Task<AuthenticationResponseModel> SignInAsync(SignInModel model);
}
}
|
import React, { lazy } from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ROUTES } from "../../utils/constants/routes";
import AuthBaseLayout from "./AuthBaseLayout/AuthBaseLayout";
const PrivateRouter: React.FC = () => {
const privateRoutes = [
{
path: ROUTES.ADMIN_DASHBOARD,
element: lazy(() => import("../pages/Home/Home")),
},
{
path: ROUTES.ADMIN_ABOUT,
element: lazy(() => import("../pages/About/About")),
},
{
path: "*",
element: lazy(() => import("../pages/NotFound/NotFound")),
},
];
return (
<BrowserRouter>
<Routes>
<Route element={<AuthBaseLayout />}>
{privateRoutes.map((route, index) => (
<Route
path={route.path}
element={
<React.Suspense fallback={<>...</>}>
{<route.element />}
</React.Suspense>
}
key={index}
></Route>
))}
</Route>
</Routes>
</BrowserRouter>
);
};
export default PrivateRouter;
|
import axios from 'axios';
export const GET_ALL_DOGS = 'GET_ALL_DOGS';
export const GET_DOG_DETAIL = 'GET_DOG_DETAIL';
export const CREATE_DOG = 'CREATE_DOG';
export const GET_TEMPERAMENTS = 'GET_TEMPERAMENTS';
export const SEARCH_DOG='SEARCH_DOG';
export const CLEAR= 'CLEAR';
export const FILTER_DB_API='FILTER_DB_API';
export const FILTER_TEMPERAMENTS='FILTER_TEMPERAMENTS';
export const ORDER='ORDER';
export function getAllDogs(){
return async function(dispatch){
try {
let dogs = await axios.get('/dog/')
return dispatch({type: GET_ALL_DOGS, payload: dogs.data})
} catch (error) {
console.log(error)
}
}
}
export function search(name){
return async function (dispatch){
try {
let dog = await axios.get(`/dog?name=${name}`)
return dispatch({type: SEARCH_DOG, payload: dog.data})
} catch (error) {
alert('Dog not found');
}
}
}
export function getTemperaments(){
return async function (dispatch){
try{
let temp= await axios.get('/temperament/')
return dispatch({type: GET_TEMPERAMENTS, payload: temp.data})
}catch(error){
console.log(error)}
}
}
export function createDog(payload){
return async function (dispatch){
try {
let res = await axios.post('/dog/', payload)
return dispatch({type: CREATE_DOG, payload: res.data})
} catch (error) {
console.log(error);
}
}
}
export function DogDetail(id){
return async function (dispatch){
try {
let res = await axios.get(`/dog/${id}`)
return dispatch({type: GET_DOG_DETAIL, payload: res.data})
} catch (error) {
console.log(error);
}
}
}
export function FilterDbApi(filtrado){
return {type: FILTER_DB_API, payload: filtrado}
}
export function FilterTemperaments(temperamento){
return {type: FILTER_TEMPERAMENTS, payload: temperamento}
}
export function Order(ordenamiento){
return {type: ORDER, payload: ordenamiento}
}
export const clear = () => {
return { type: CLEAR}
}
|
<!-- TIME TAKEN : 15 MINUTES -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>Complex Form</h2>
<form>
<fieldset>
<legend>Personal Information</legend>
<label for="name">Name</label>
<input type="text" id="name" name="name">
<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="[email protected]">
<label for="phone">Phone</label>
<input type="tel" id="phone" name="phone">
<label for="dob">Date Of Birth</label>
<input type="date" name="dob" id="dob">
<label for="gender">Gender</label>
<input type="radio" name="radio" id="male">
<label for="male">Male</label>
<input type="radio" name="radio" id="female">
<label for="female">Female</label>
<label for="country">Country</label>
<select name="country" id="country">
<option value="United States">United States</option>
<option value="India" selected >India</option>
<option value="China">China</option>
<option value="Japan">Japan</option>
</select>
</fieldset>
<fieldset>
<label for="address">Address Street </label>
<input type="text" name="address" id="address">
<label for="city">City </label>
<input type="text" name="city" id="city">
<label for="state">State</label>
<input type="text" name="state" id="state">
<label for="zip">Zip code </label>
<input type="text" name="zip" id="zip">
</fieldset>
<fieldset>
<legend>
Other Information
</legend>
<label for="comments">Comments</label>
<textarea name="comments" id="comments" cols="30" rows="10"></textarea>
<label for="agree">I agree to The Terms of service</label>
<input type="checkbox" id="agree" name="agree ">
</fieldset>
<button>submit</button>
</form>
</body>
</html>
|
/// <reference path="../index.d.ts" />
declare class version {
// 主版本号(如 **2**.1.0 里的 **2**)
major: number
// 次版本号(如 2.**1**.0 里的 **1**)
minor: number
// 修订版本号(如 2.1.**0** 里的 **0**)
revision: number
// 当前版本是否为测试版
isBeta: boolean
}
declare namespace ll {
// LiteLoaderBDS使用的语言。(例如zh_Hans、en和ru_RU)
const language: string
// 主版本号(如 2.1.0 里的 2)
const major: number
// 次版本号(如 2.1.0 里的 1)
const minor: number
// 修订版本号(如 2.1.0 里的 0)
const revision: number
// 版本状态 (0为Dev, 1为Beta, 2为Release)
const status: number
// LiteLoaderBDS Script Engine版本
const scriptEngineVersion: string
// 是否处于Wine环境下
const isWine: boolean
// 是否处于debug模式
const isDebugMode: boolean
// 当前版本是否为测试版
const isBeta: boolean
// 当前版本是否为开发版
const isDev: boolean
// 当前版本是否为发布版本
const isRelease: boolean
/**
* 获取LiteLoader加载器版本
* @returns version 加载器版本对象
*/
function version(): version
/**
* 获取LiteLoader加载器版本字符串
* @returns string 加载器版本
*/
function versionString(): string
/**
* 检查LiteLoader加载器版本
* @returns boolean 检查结果
*/
function requireVersion(
major: number,
minor?: number,
revision?: number
): boolean
/**
* 列出所有已加载的插件
* @returns Array<string> 列出所有已加载的插件
*/
function listPlugins(): Array<string>
/**
* 导出函数
* @param func 要导出的函数
* @param namespace 函数的命名空间名,只是方便用于区分不同插件导出的API
* @param name 函数的导出名称。其他插件根据导出名称来调用这个函数
* @returns boolean 是否成功导出
*/
function exports(
func: (...arg) => any,
namespace: string,
name: string
): boolean
/**
* 导入函数
* @param namespace 要导入的函数使用的命名空间名称
* @param name 要导入的函数使用的导出名称
* @returns Function 导入的函数
*/
function imports(namespace: string, name: string): (...arg) => any
/**
* 导出函数(注意:由于TypeScript的保留字,请删除`_`使用ll._export=>ll.export)
* @description 已弃用,应使用{@link ll.exports}
* @see {@link ll.exports}
*/
function _export(
func: (...arg) => any,
namespace: string,
name: string
): boolean
/**
* 导入函数(注意:由于TypeScript的保留字,请删除`_`使用ll._export=>ll.export)
* @description 已弃用,应使用{@link ll.imports}
* @see {@link ll.exports}
*/
function _import(namespace: string, name: string): (...arg) => any
/**
* 判断远程函数是否已导出
* @param namespace 函数使用的命名空间名称
* @param name 函数使用的导出名称
* @returns boolean 函数是否已导出
*/
function hasExported(namespace: string, name: string): boolean
/**
* 设置插件依赖库
* @param path 依赖库文件名(如`addplugin.js`)
* @param remotePath (可选参数)查找并装载依赖库的路径,说明见文档
* @returns boolean 是否加载依赖库成功
*/
function require(path: string, remotePath?: string): boolean
/**
* 将字符串作为脚本代码执行
* @param str 要作为脚本代码执行的字符串
* @returns any 执行结果
*/
function eval(str: string): any
}
|
import React from 'react';
// import { pathToRegexp }from "path-to-regexp";
import { useRouter } from 'next/router';
import Link from 'next/link'
import { Breadcrumb } from 'antd';
function Breadcrumbs({ location }){
const router = useRouter()
const pathname = router.pathname;
const pathSnippets = pathname.substring(1).split('/');
const extraBreadcrumbItems = [];
pathSnippets.forEach((name, index) => {
const url = `/${pathSnippets.slice(0, index + 1).join('/')}`;
extraBreadcrumbItems.push(<Breadcrumb.Item key={url} style={{fontSize: "14px"}}>
<Link href={url} >
<a>{name}</a>
</Link>
</Breadcrumb.Item>);
});
const BreadcrumbItems = [(
<Breadcrumb.Item key="/" style={{fontSize: "14px"}}>
<Link href="/" >
<a>Home</a>
</Link>
</Breadcrumb.Item>
)].concat(extraBreadcrumbItems);
return <Breadcrumb>
{BreadcrumbItems}
</Breadcrumb>
}
export default Breadcrumbs;
|
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type coord struct {
row int
col int
}
func main() {
in := bufio.NewReader(os.Stdin)
out := bufio.NewWriter(os.Stdout)
defer out.Flush()
Run(in, out)
}
func Run(in *bufio.Reader, out *bufio.Writer) {
var n int
fmt.Fscanln(in, &n)
for i := 0; i < n; i++ {
a := coord{}
b := coord{}
var rows, cols int
fmt.Fscanln(in, &rows, &cols)
matrix := make([][]string, rows)
for i := range matrix {
matrix[i] = make([]string, cols)
}
var line string
for row := 0; row < rows; row++ {
fmt.Fscanln(in, &line)
for col := 0; col < cols; col++ {
matrix[row][col] = string(line[col])
if matrix[row][col] == "A" {
a.row = row
a.col = col
}
if matrix[row][col] == "B" {
b.row = row
b.col = col
}
}
}
if a.row == 0 && a.col == 0 {
goDownRight(matrix, b, "b")
} else if a.row == len(matrix)-1 && a.col == len(matrix[0])-1 {
goUpLeft(matrix, b, "b")
} else if b.row == 0 && b.col == 0 {
goDownRight(matrix, a, "a")
} else if b.row == len(matrix)-1 && b.col == len(matrix[0])-1 {
goUpLeft(matrix, a, "a")
} else if a.row == b.row {
if a.col < b.col {
goUpLeft(matrix, a, "a")
goDownRight(matrix, b, "b")
} else {
goUpLeft(matrix, b, "b")
goDownRight(matrix, a, "a")
}
} else if a.row <= b.row {
goUpLeft(matrix, a, "a")
goDownRight(matrix, b, "b")
} else {
goUpLeft(matrix, b, "b")
goDownRight(matrix, a, "a")
}
// for i := range matrix {
// fmt.Println(matrix[i])
// }
// fmt.Println()
fmt.Fprint(out, matrixToStr(matrix))
}
}
func goUpLeft(matrix [][]string, pos coord, mark string) {
if pos.row > 0 {
if matrix[pos.row-1][pos.col] == "#" {
pos.col--
matrix[pos.row][pos.col] = mark
}
}
pos = goUp(matrix, pos, mark)
pos = goLeft(matrix, pos, mark)
}
func goUp(matrix [][]string, pos coord, mark string) coord {
for i := pos.row - 1; i >= 0; i-- {
pos.row = i
matrix[pos.row][pos.col] = mark
}
return pos
}
func goLeft(matrix [][]string, pos coord, mark string) coord {
for i := pos.col - 1; i >= 0; i-- {
pos.col = i
matrix[pos.row][pos.col] = mark
}
return pos
}
func goDownRight(matrix [][]string, pos coord, mark string) {
if pos.row < len(matrix)-2 {
if matrix[pos.row+1][pos.col] == "#" {
pos.col++
matrix[pos.row][pos.col] = mark
}
}
pos = goDown(matrix, pos, mark)
pos = goRight(matrix, pos, mark)
}
func goDown(matrix [][]string, pos coord, mark string) coord {
for i := pos.row + 1; i < len(matrix); i++ {
pos.row = i
matrix[pos.row][pos.col] = mark
}
return pos
}
func goRight(matrix [][]string, pos coord, mark string) coord {
for i := pos.col + 1; i < len(matrix[0]); i++ {
pos.col = i
matrix[pos.row][pos.col] = mark
}
return pos
}
func matrixToStr(m [][]string) string {
sb := strings.Builder{}
for _, row := range m {
sb.WriteString(strings.Join(row, ""))
sb.WriteString("\n")
}
return sb.String()
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h4>图像标签的使用:</h4>
<img src="img.jpg" />
<h4>alt 替换文本 图像显示不出来的时候用文字替换:</h4>
<img src="img1.jpg" alt="我是pink老师" />
<h4>title 提示文本 鼠标放到图像上提示的文字:</h4>
<img src="img.jpg" alt="我是pink老师" title="我是pink老师~" />
<h4>width 给图像设定宽度:</h4>
<img src="img.jpg" alt="我是pink老师" title="我是pink老师~" width="500" />
<h4>height 给图像设定高度:</h4>
<img src="img.jpg" alt="我是pink老师" title="我是pink老师~" height="100" />
<h4>border 给图像设定边框:</h4>
<img
src="img.jpg"
alt="我是pink老师"
title="我是pink老师~"
width="500"
border="15"
/>
</body>
</html>
|
import {
CheckboxProps,
FormControlLabel,
Checkbox as MuiCheckBox,
} from '@material-ui/core'
import React from 'react'
type Props = CheckboxProps & {
name: string
label: string
value: boolean
color?: string
onChange: (e: React.ChangeEvent<HTMLInputElement>, checked?: boolean) => void
}
export function CheckBox({
name,
label,
value,
color,
onChange,
}: Props): React.ReactElement {
return (
<FormControlLabel
control={
<MuiCheckBox
name={name}
checked={value}
color={color || 'primary'}
onChange={onChange}
/>
}
label={label}
/>
)
}
|
import NodeCache from "node-cache";
import fetch from "node-fetch";
import sizeOf from "image-size";
import fs from 'fs';
const remoteImageCache = new NodeCache();
type TImage = Buffer | string;
type TGetImageSizeParam = TImage;
interface IGetImageSizeReturn {
height: number;
width: number;
type?: string;
};
interface IGetImageSize {
(file: TGetImageSizeParam): IGetImageSizeReturn;
};
interface ILoadRemoteImage {
(srcUrl: string): Promise<Buffer>;
};
interface ILoadImageImg extends IGetImageSizeReturn {
src: string;
};
interface ILoadImageReturn {
img: ILoadImageImg;
file: TImage;
};
interface ILoadImage {
(imagePath: TImage): Promise<ILoadImageReturn | undefined>;
};
const getImageSize: IGetImageSize = (file) => {
const { width, height, type } = sizeOf(file);
return {
width,
height,
type
};
};
const loadRemoteImage: ILoadRemoteImage = async (srcUrl) => {
const cachedImage = remoteImageCache.get(srcUrl); //Keep remote image cache
if(typeof cachedImage === "undefined") {
const response = await fetch(srcUrl);
const buffer = await response.buffer(); //Get image
remoteImageCache.set(srcUrl, buffer); //Cache
return buffer;
}
if(!Buffer.isBuffer(cachedImage)) throw Error(`Cached value for ${srcUrl} is invalid.`);
return cachedImage;
};
const loadImage: ILoadImage = async (imagePath) => {
if(Buffer.isBuffer(imagePath)) { //Buffer
const imageSize = getImageSize(imagePath);
return { //Return buffer image
file: imagePath,
img: {
src: null,
...imageSize,
}
};
}
if(!imagePath.startsWith('http')) { //Local file
if(!fs.existsSync(imagePath)) return undefined;
const imageSize = getImageSize(imagePath);
return { //Return local image
file: imagePath,
img: {
src: imagePath,
...imageSize,
}
};
}
//Remote image url
const buffer = await loadRemoteImage(imagePath);
const imageSize = getImageSize(buffer);
return { //Return remote image
file: buffer,
img: {
src: imagePath,
...imageSize
}
};
};
export default loadImage;
|
@extends('layouts.app')
@section('content')
<div class="container-fluid text-center pt-5" style="background: rgb(96, 233, 243,.5);height:1000px">
<div class="row">
<div class="col-md-6 offset-3">
@if ($editservice != null)
<form action="{{ route('editservice', $editservice['id']) }}" method="post">
@else
<form action="{{ route('service') }}" method="post">
@endif
@csrf
<div class="form-group">
<h1>Add service</h1>
@if ($editservice != null)
<input type="hidden" value="{{ $editservice['id'] }}" name="id">
<input type="text" value="{{ $editservice['name'] }}" name="service" class="mt-2 form-control"
placeholder="Enter sesson ex. 2000-2001">
@else
<input type="text" name="service" class="mt-2 form-control"
placeholder="Add service ex. খাবার প্রস্তুতি">
@endif
</div>
<button type="submit" class="mt-3 btn btn-outline-primary">Submit</button>
</form>
</div>
</div>
<div class="row mt-5">
<div class="col-md-6 offset-3">
<h1>All services</h1>
<table class="table table-striped table-dark">
<thead>
<tr>
<th scope="col">No</th>
<th scope="col">Name</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
@php
$i = 1;
@endphp
@foreach ($services as $service)
<tr>
<td>{{ $i }}</td>
<td>{{ $service['name'] }}</td>
<td><a href="{{ route('editservice', $service['id']) }}"
class="btn btn-outline-success">Edit</a></td>
<td>
<form method="post" action="{{ route('destroyservice', $service['id']) }}"
onsubmit="return confirm('Sure?')">
@csrf
@method('DELETE')
<input type="submit" value="Delete" class="btn btn-outline-danger" />
</form>
</td>
</tr>
@php
$i++;
@endphp
@endforeach
</tbody>
</table>
</div>
</div>
</div>
@endsection
|
package com.ppi.api.testcases;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.ppi.api.endpoints.Constants;
import com.ppi.api.endpoints.Routes;
import com.ppi.pages.ExtentReportPage;
import com.ppi.utilities.GenericMethods;
public class PrepareExtentReport extends BaseTest {
public static Logger log = LogManager.getLogger(PrepareExtentReport.class.getName());
public ExtentReportPage erPage;
@BeforeMethod
public void beforeMethodPrepareExtentReport() {
log.info("beforeMethodPrepareExtentReport");
String fileName = GenericMethods.getExtentReportLatestFileName();
driver.get(Routes.extentReportsPath+fileName);
}
@Test
public void prepareExtentReport() {
System.out.println("prepareExtentReport Function");
erPage = new ExtentReportPage(driver);
String apiName = null;
String startTime;
String endTime;
String testsPasses;
String testsFailed;
/*
* System.out.println("erPage.getApiNames().size()"+erPage.getApiNames().size())
* ; for(int i=0; i<erPage.getApiNames().size();i++) {
* System.out.println(erPage.getApiNames().get(i).getText()); }
*/
if(erPage.getApiNames().size()>0)
apiName = erPage.getApiNames().get(erPage.getApiNames().size()-1).getText().replace("test", "");
/*
* System.out.println("erPage.getApiNamesFailed().size()"+erPage.
* getApiNamesFailed().size()); for(int i=0;
* i<erPage.getApiNamesFailed().size();i++) {
* System.out.println(erPage.getApiNamesFailed().get(i).getText()); }
*/
if(apiName == null || apiName.contentEquals("") ) {
if(erPage.getApiNamesFailed().size()>0)
apiName = erPage.getApiNamesFailed().get(erPage.getApiNamesFailed().size()-1).getText().replace("test", "");
}
erPage.getBarChat().click();
GenericMethods.waitExplicitely(2);
startTime = erPage.getStartTime().getText();
endTime = erPage.getEndTime().getText();
testsPasses = erPage.getTestsPassed().getText();
testsFailed = erPage.getTestsFailed().getText();
System.out.println("ApiName::"+ apiName);
System.out.println("StartTime::"+ startTime);
System.out.println("EndTime::"+ endTime);
System.out.println("Tests Passed::"+ testsPasses);
System.out.println("Tests Failed::"+ testsFailed);
//Date ApiName StartDateTime EndDateTime TestsPassed TestsFailed
int rowCount = GenericMethods.getRowCount(Constants.extentReportSummaryFile,
Constants.extentReportSummaryFileSheetName);
rowCount++;
GenericMethods.writingToExcel(Constants.extentReportSummaryFile, Constants.extentReportSummaryFileSheetName,
"Date", rowCount, GenericMethods.getCurrentDateTime("dd-MM-yyyy"));
GenericMethods.writingToExcel(Constants.extentReportSummaryFile, Constants.extentReportSummaryFileSheetName,
"ApiName", rowCount, apiName);
GenericMethods.writingToExcel(Constants.extentReportSummaryFile, Constants.extentReportSummaryFileSheetName,
"StartDateTime", rowCount, startTime);
GenericMethods.writingToExcel(Constants.extentReportSummaryFile, Constants.extentReportSummaryFileSheetName,
"EndDateTime", rowCount, endTime);
GenericMethods.writingToExcel(Constants.extentReportSummaryFile, Constants.extentReportSummaryFileSheetName,
"TestsPassed", rowCount, testsPasses);
GenericMethods.writingToExcel(Constants.extentReportSummaryFile, Constants.extentReportSummaryFileSheetName,
"TestsFailed", rowCount, testsFailed);
Assert.assertTrue(true);
}
@AfterMethod
public void afterMethodPrepareExtentReport() {
log.info("afterMethodPrepareExtentReport");
System.out.println("afterMethodPrepareExtentReport");
}
}
|
package Programmers;
/*
어떤 문자열을 둘로 나누고 , 두 부분 문자열의 순서를 바꾸는 것을 문자열을 회전시킨다고한다.
예를 들어 "helloworld" 라는 문자열을 Hello, World 두 부분을 나누어 회전시키면 worldhello가 된다
S1 과 S2 두 가지 문자열이 주어졌을때, S2가 S1 을 회전시켜 나온 결과인지 판단해 맞으면 1아니면 0을 반환해라
*/
public class Programmers11530 {
public int solution(String S1, String S2) {
// 길이가 다르다면 끝
if (S1.length() != S2.length()) {
return 0;
}
// S2에 S1을 회저시킨 문자열이있는지 확인해본다
// helloworldhelloworld 라면, 중간에 worldhello가 나와 포함되어있는것을 확인할 수 있다.
String concatenated = S1 + S1; // S1을 두 번 연결
// 연결된 문자열이 S2를 포함면 회전성공
if (concatenated.contains(S2)) {
return 1;
} else {
return 0;
}
}
}
|
import React, { useEffect } from 'react';
type UseClickOutsideType = {
ref: React.RefObject<HTMLDivElement>;
outsideClickFunc: () => void;
additionalCondition?: boolean;
};
export function useClickOutside({
ref,
outsideClickFunc,
additionalCondition,
}: UseClickOutsideType) {
useEffect(() => {
function handleClickOutside(event: any) {
if (
ref.current &&
!ref.current.contains(event.target) &&
additionalCondition
) {
outsideClickFunc();
}
}
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [ref, additionalCondition]);
}
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const common_1 = require("@nestjs/common");
const jsonwebtoken_1 = require("jsonwebtoken");
const configuration_service_1 = require("../configuration/configuration.service");
const configuration_enum_1 = require("../configuration/configuration.enum");
const user_service_1 = require("../../user/user.service");
let AuthService = class AuthService {
constructor(_userService, _configurationService) {
this._userService = _userService;
this._configurationService = _configurationService;
this.jwtOptions = { expiresIn: '2h' };
this.jwtKey = this._configurationService.get(configuration_enum_1.Configuration.JWT_KEY);
}
signPayload(payload) {
return __awaiter(this, void 0, void 0, function* () {
return jsonwebtoken_1.sign(payload, this.jwtKey, this.jwtOptions);
});
}
validatePayload(payload) {
return __awaiter(this, void 0, void 0, function* () {
return this._userService.findOne({ email: payload.email.toLocaleLowerCase() });
});
}
};
AuthService = __decorate([
common_1.Injectable(),
__param(0, common_1.Inject(common_1.forwardRef(() => user_service_1.UserService))),
__metadata("design:paramtypes", [user_service_1.UserService,
configuration_service_1.ConfigurationService])
], AuthService);
exports.AuthService = AuthService;
//# sourceMappingURL=auth.service.js.map
|
package requests
import (
"github.com/sebastiankennedy/go-web-skeleton/app/models/user"
"github.com/thedevsaddam/govalidator"
)
// ValidateRegistrationForm 验证表单,返回 errs 长度等于零即通过
func ValidateRegistrationForm(data user.User) map[string][]string {
// 1. 定制认证规则
rules := govalidator.MapData{
"email": []string{"required", "min:4", "max:30", "email", "not_exists:users,email"},
"username": []string{"required", "alpha_num", "between:3,20", "not_exists:users,username"},
"password": []string{"required", "min:6"},
"password_confirmation": []string{"required"},
}
// 2. 定制错误消息
messages := govalidator.MapData{
"email": []string{
"required:Email 为必填项",
"min:Email 长度需大于 4",
"max:Email 长度需小于 30",
"email:Email 格式不正确,请提供有效的邮箱地址",
},
"username": []string{
"required:用户名为必填项",
"alpha_num:格式错误,只允许数字和英文",
"between:用户名长度需在 3~20 之间",
},
"password": []string{
"required:密码为必填项",
"min:长度需大于 6",
},
"password_confirmation": []string{
"required:确认密码框为必填项",
},
}
// 3. 配置初始化
opts := govalidator.Options{
Data: &data,
Rules: rules,
TagIdentifier: "valid", // 模型中的 Struct 标签标识符
Messages: messages,
}
// 4. 开始验证
errs := govalidator.New(opts).ValidateStruct()
// 5. 因 govalidator 不支持 password_confirmation 验证,我们自己写一个
if data.Password != data.PasswordConfirmation {
errs["password_confirmation"] = append(errs["password_confirmation"], "两次输入密码不匹配!")
}
return errs
}
|
import React from "react";
import PropTypes from "prop-types";
import { Box, IconButton, TextField } from "@mui/material";
import { Controller } from "react-hook-form";
import { RemoveCircleOutline, AddCircleOutline } from "@mui/icons-material";
import { useDispatch } from "react-redux";
import { removeFromCart, setQuantity } from "../../../features/Cart/cartSlice";
const QuantityField = (props) => {
const { form, name, label, disabled, onChange, product, id } = props;
// const handleChange = () => {
// console.log(form.getValues(name));
// };
const dispatch = useDispatch();
const handleChangeQuantity = (quantity) => {
if (onChange) return;
if (quantity <= 0) {
const action = removeFromCart({
id: product.id,
product,
quantity: quantity,
});
dispatch(action);
} else {
const action = setQuantity({
id: id,
product,
quantity: quantity,
});
dispatch(action);
}
};
if (form)
return (
<Controller
name={name}
control={form.control}
fullWidth
render={({
field: { onChange, onBlur, value, name },
fieldState: { invalid, error, isDirty, disabled },
}) => (
<Box className='flex max-w-xs'>
<IconButton
onClick={() => {
form.setValue(name, Number.parseInt(value) - 1);
}}>
<RemoveCircleOutline />
</IconButton>
<TextField
InputProps={{ inputProps: { min: 0, max: 10 }, readOnly: true }}
type='number'
error={invalid}
isDirty={isDirty}
helperText={error?.message}
onBlur={onBlur}
name={name}
value={value}
onChange={handleChangeQuantity(value)}
label={label}
size='small'
/>
<IconButton
onClick={() => form.setValue(name, Number.parseInt(value) + 1)}>
<AddCircleOutline />
</IconButton>
</Box>
)}
label={label}
disabled={disabled}
/>
);
};
QuantityField.propTypes = {
form: PropTypes.object.isRequired,
name: PropTypes.string.isRequired,
label: PropTypes.string,
disabled: PropTypes.bool,
};
export default QuantityField;
|
<template>
<div class="categorybar">
<div class="leftbtn" @click="slideClick">
<div class="sort">{{ headTitle }}</div>
<div class="icon"></div>
</div>
<div class="centerbar">
<div class="hot">热门标签:</div>
<div
class="sortbtn"
v-for="(item, index) in sortTitle"
:key="index"
@click="btnClick(item.name)"
:class="{ btnActive: headTitle === item.name }"
>
{{ item.name }}
</div>
</div>
<div
class="rightbtn"
:class="{ allActive: headTitle === '全部' }"
@click="allClick"
>
全部
</div>
<slot name="slidebar">
<SlideBar ref="slideBar">
<div slot="categories" class="contextbox">
<SlideItem :subs="subs[0]" @subClick="subClick" :headTitle="headTitle"
><div class="title" slot="title"> 语种</div></SlideItem
>
<SlideItem :subs="subs[1]" @subClick="subClick" :headTitle="headTitle"
><div class="title" slot="title"> 风格</div></SlideItem
>
<SlideItem :subs="subs[2]" @subClick="subClick" :headTitle="headTitle"
><div class="title" slot="title"> 场景</div></SlideItem
>
<SlideItem :subs="subs[3]" @subClick="subClick" :headTitle="headTitle"
><div class="title" slot="title"> 情感</div></SlideItem
>
<SlideItem :subs="subs[4]" @subClick="subClick" :headTitle="headTitle"
><div class="title" slot="title"> 主题</div></SlideItem
>
</div>
</SlideBar>
</slot>
</div>
</template>
<script>
import SlideBar from "./SlideBar.vue";
import SlideItem from "./SlideItem.vue";
export default {
data() {
return {
headTitle: "全部",
subs: [],
};
},
components: {
SlideBar,
SlideItem,
},
computed: {
isAll() {
return this.headTitle === "全部" ? true : false;
},
},
props: {
sortTitle: {
type: Array,
default() {
return [];
},
},
allType: {
type: Object,
default() {
return {};
},
},
},
watch: {
allType() {
if (Object.keys(this.allType) !== 0) {
for (const type in this.allType.categories) {
let arr = [];
for (const sub of this.allType.sub) {
if (sub.category == type) {
arr.push(sub.name);
}
}
this.subs.push(arr);
}
}
},
},
methods: {
btnClick(name) {
this.headTitle = name;
this.$emit("btnClick", name);
},
allClick() {
this.headTitle = "全部";
this.$emit("allClick", "全部");
},
slideClick() {
this.$refs.slideBar.isSlide = !this.$refs.slideBar.isSlide;
},
subClick(type) {
this.headTitle = type;
this.$emit("subClick", type);
},
},
};
</script>
<style lang="less" scoped>
.categorybar {
position: relative;
display: flex;
text-align: center;
height: 40px;
line-height: 40px;
box-shadow: 0px 5px 40px -1px rgba(2, 10, 18, 0.1);
border-radius: 8px;
color: #4a4a4a;
margin-bottom: 20px;
.leftbtn {
cursor: pointer;
text-align: left;
display: flex;
color: #fff;
background-color: #fa2800;
border-radius: 8px;
.sort {
padding-left: 20px;
flex-shrink: 0;
}
.icon {
font-family: "icomoon";
font-size: 18px;
padding-right: 15px;
}
}
.centerbar {
display: flex;
flex: 88%;
padding-left: 15px;
background-color: #fff;
.hot {
margin-right: 15px;
}
.sortbtn {
margin-right: 15px;
cursor: pointer;
}
.sortbtn:hover {
color: #fa2800;
}
}
.rightbtn {
border-radius: 4px;
background-color: #f7f7f7;
line-height: 30px;
color: #4a4a4a;
margin: 5px 20px;
cursor: pointer;
font-size: 12px;
flex: 4%;
}
}
.allActive {
color: #fff !important;
background-color: #fa2800 !important;
}
.btnActive {
color: #fa2800;
}
</style>
|
import { Td, Text, Tr } from "@chakra-ui/react";
import React from "react";
import useFormatNumber from "../utils/useFormatNumber";
import { useLocation } from "react-router-dom";
import { RetailProduct } from "../types";
type Props = {
p: RetailProduct;
action: (param: any) => void;
};
export default function RetailProductListItem({ p, action }: Props) {
const fn = useFormatNumber;
const location = useLocation();
const path = location.pathname.split("/");
const endpoint = path[path.length - 1];
return (
<Tr
className="listItem"
_hover={{ bg: "var(--divider)" }}
cursor={"pointer"}
onClick={() => {
if (endpoint === "retail-product-search") {
action({
id: p.id,
code: p.code,
name: p.name,
price: parseInt(p.price),
qty: 1,
totalPrice: parseInt(p.price),
stock: parseInt(p.stock),
category: p.category,
});
window.history.back();
} else {
action(p.id);
}
}}
>
<Td className="before" py={2} px={"18px"} pl={6}>
<Text noOfLines={1} maxW={"200px"}>
{p.code}
</Text>
</Td>
<Td py={2} px={"18px"}>
<Text noOfLines={1} maxW={"300px"}>
{p.name}
</Text>
</Td>
<Td textAlign={"center"} py={2} px={"18px"}>
{p.category}
</Td>
<Td isNumeric py={2} px={"18px"}>
{fn(parseInt(p.stock))}
</Td>
<Td isNumeric py={2} px={"18px"} pr={6}>
{fn(parseInt(p.price))}
</Td>
</Tr>
);
}
|
<template>
<Tabbar :value="activeTabBar" :border="false">
<TabbarItem v-for="tabBarItem of tabBarDataSource" :key="tabBarItem.key" :name="tabBarItem.key"
:to="tabBarItem.key">
<span v-html="tabBarItem.title"></span>
<template #icon>
<div>
<img v-show="activeTabBar === tabBarItem.key" :src="tabBarItem.activeIcon" alt="">
<img v-show="activeTabBar !== tabBarItem.key" :src="tabBarItem.icon" alt="">
</div>
</template>
</TabbarItem>
</Tabbar>
</template>
<script>
import { Tabbar, TabbarItem } from 'vant'
export default {
components: {
Tabbar,
TabbarItem
},
data() {
return {
tabBarDataSource: Object.freeze([
{
key: '/city-meta/home',
title: '首页',
icon: '/static/images/tab-bar/home.png',
activeIcon: '/static/images/tab-bar/home-active.png'
},
{
key: '/city-meta/collection',
title: '藏品',
icon: '/static/images/tab-bar/collection.png',
activeIcon: '/static/images/tab-bar/collection-active.png'
},
{
key: '/city-meta/my-center',
title: '我的',
icon: '/static/images/tab-bar/my-center.png',
activeIcon: '/static/images/tab-bar/my-center-active.png'
}
])
}
},
computed: {
activeTabBar() {
return this.$route.path
}
}
}
</script>
<style scoped>
.van-tabbar--fixed{
z-index: 10000;
}
</style>
|
# 문제
# 용사는 마왕이 숨겨놓은 공주님을 구하기 위해 (N, M) 크기의 성 입구 (1,1)으로 들어왔다. 마왕은 용사가 공주를 찾지 못하도록 성의 여러 군데 마법 벽을 세워놓았다. 용사는 현재의 가지고 있는 무기로는 마법 벽을 통과할 수 없으며, 마법 벽을 피해 (N, M) 위치에 있는 공주님을 구출해야만 한다.
#
# 마왕은 용사를 괴롭히기 위해 공주에게 저주를 걸었다. 저주에 걸린 공주는 T시간 이내로 용사를 만나지 못한다면 영원히 돌로 변하게 된다. 공주님을 구출하고 프러포즈 하고 싶은 용사는 반드시 T시간 내에 공주님이 있는 곳에 도달해야 한다. 용사는 한 칸을 이동하는 데 한 시간이 걸린다. 공주님이 있는 곳에 정확히 T시간만에 도달한 경우에도 구출할 수 있다. 용사는 상하좌우로 이동할 수 있다.
#
#
#
# 성에는 이전 용사가 사용하던 전설의 명검 "그람"이 숨겨져 있다. 용사가 그람을 구하면 마법의 벽이 있는 칸일지라도, 단숨에 벽을 부수고 그 공간으로 갈 수 있다. "그람"은 성의 어딘가에 반드시 한 개 존재하고, 용사는 그람이 있는 곳에 도착하면 바로 사용할 수 있다. 그람이 부술 수 있는 벽의 개수는 제한이 없다.
#
# 우리 모두 용사가 공주님을 안전하게 구출 할 수 있는지, 있다면 얼마나 빨리 구할 수 있는지 알아보자.
#
# 입력
# 첫 번째 줄에는 성의 크기인 N, M 그리고 공주에게 걸린 저주의 제한 시간인 정수 T가 주어진다. 첫 줄의 세 개의 수는 띄어쓰기로 구분된다. (3 ≤ N, M ≤ 100, 1 ≤ T ≤ 10000)
#
# 두 번째 줄부터 N+1번째 줄까지 성의 구조를 나타내는 M개의 수가 띄어쓰기로 구분되어 주어진다. 0은 빈 공간, 1은 마법의 벽, 2는 그람이 놓여있는 공간을 의미한다. (1,1)과 (N,M)은 0이다.
#
# 출력
# 용사가 제한 시간 T시간 이내에 공주에게 도달할 수 있다면, 공주에게 도달할 수 있는 최단 시간을 출력한다.
#
# 만약 용사가 공주를 T시간 이내에 구출할 수 없다면, "Fail"을 출력한다.
from collections import deque
n, m, t = map(int, input().split())
grid = [list(map(int, input().split())) for _ in range(n)]
dy, dx = [0, 1, 0, -1], [1, 0, -1, 0]
def bfs():
q = deque()
q.append((0, 0, 0, False))
visited = [[1e9 for _ in range(m)] for _ in range(n)]
visited[0][0] = 0
result = 1e9
while q:
y, x, time, flag = q.popleft()
if (y, x) == (n-1, m-1):
result = min(result, time)
continue
if flag:
result = min(result, time+abs(n-1-y)+abs(m-1-x))
continue
for i in range(4):
ny, nx = y+dy[i], x+dx[i]
if 0 <= ny < n and 0 <= nx < m and visited[ny][nx] > time+1:
if flag:
visited[ny][nx] = time+1
q.append((ny, nx, time+1, flag))
else:
if grid[ny][nx] != 1:
if grid[ny][nx] == 2:
flag = True
visited[ny][nx] = time+1
q.append((ny, nx, time+1, flag))
if result == 1e9:
return -1
return result
answer = bfs()
if 0 <= answer <= t:
print(answer)
else:
print("Fail")
|
const express = require('express');
const bodyParser = require('body-parser');
// ========= Import in the randomNumber module
const randomNumber = require('./randomNumber');
const app = express();
const PORT = 5000;
// This must be added before GET & POST routes.
app.use(bodyParser.urlencoded({ extended: true }));
// Serve up static files (HTML, CSS, Client JS)
app.use(express.static('server/public'));
//Declare global variables
let guessArray = [];
let whoWins = {
xai: false,
connor: false,
xaiHigher: false,
connorHigher: false,
guessCount: 0,
};
let minNumber = 0;
let maxNumber = 0;
// let myNumber = randomNumber(1, 25).toString();
let myNumber = 0;
// GET & POST Routes go here
app.listen(PORT, () => {
console.log('Server is running on port', PORT);
});
app.post('/randomNumber', (req, res) => {
minNumber = req.body.minNumber;
maxNumber = req.body.maxNumber;
myNumber = randomNumber(minNumber, maxNumber).toString();
// // console.log('Sending Random Number:', myNumber);
// res.send(myNumber);
res.sendStatus(201);
});
app.get('/number', (req, res) => {
console.log('myNumber', myNumber);
console.log('generated random number', myNumber);
res.send(myNumber);
});
app.get('/restart', (req, res) => {
myNumber = randomNumber(1, 25).toString();
console.log('Sending New Random Number:', myNumber);
whoWins.xai = false;
whoWins.connor = false;
whoWins.xaiHigher = false;
whoWins.connorHigher = false;
whoWins.guessCount = 0;
guessArray = [];
console.log('whoWins objet after restart', whoWins);
res.send(myNumber);
});
app.post('/number', (req, res) => {
console.log('Inside of guess POST request', req.body);
let guess = req.body;
guessArray.push(guess);
console.log('guessArray in here:', guessArray);
whoWins.guessCount = guessArray.length;
console.log('guessCount....', whoWins.guessCount);
res.sendStatus(201);
});
app.get('/result', (req, res) => {
let confirm = 'confirmed!';
let currentGuess = guessArray[guessArray.length - 1];
console.log('current guess.....', currentGuess);
myNumber = Number(myNumber);
currentGuess.xai = Number(currentGuess.xai);
currentGuess.connor = Number(currentGuess.connor);
console.log('myNumber', myNumber);
console.log('currentGuess.xai', currentGuess.xai);
console.log('currentGuess.connor', currentGuess.connor);
if (currentGuess.xai === myNumber) {
whoWins.xai = true;
}
if (currentGuess.connor === myNumber) {
whoWins.connor = true;
}
if (currentGuess.xai > myNumber) {
whoWins.xaiHigher = true;
whoWins.xai = false;
}
if (currentGuess.connor > myNumber) {
whoWins.connorHigher = true;
whoWins.connor = false;
}
if (currentGuess.xai < myNumber) {
whoWins.xaiHigher = false;
whoWins.xai = false;
}
if (currentGuess.connor < myNumber) {
whoWins.connorHigher = false;
whoWins.connor = false;
}
console.log('whoWins', whoWins);
res.send(whoWins);
// if(currentGuess.xai === myNumber && currentGuess.connor === myNumber){
// console.log('Connor Guess', currentGuess.connor, 'Xai Guess', currentGuess.xai, 'Real Number', myNumber);
// whoWins.xai = true;
// whoWins.connor = true;
// whoWins.xaiHigher = false;
// whoWins.connorHigher = false;
// console.log('Xai & Connor win', myNumber, currentGuess.xai, currentGuess.connor, whoWins);
// res.send(whoWins);
// }
// else if(currentGuess.connor === myNumber && currentGuess.xai !== myNumber){
// console.log('Connor Guess', currentGuess.connor, 'Xai Guess', currentGuess.xai, 'Real Number', myNumber);
// whoWins.connor = true;
// whoWins.xai = false;
// whoWins.connorHigher = false;
// if (currentGuess.xai > myNumber) {
// whoWins.xaiHigher = true;
// }
// if (currentGuess.xai < myNumber) {
// whoWins.xaiHigher = false;
// }
// console.log('Connor wins', myNumber, currentGuess.connor, currentGuess.xai, whoWins);
// res.send(whoWins)
// }
// else if(currentGuess.xai === myNumber && currentGuess.connor !== myNumber){
// console.log('Connor Guess', currentGuess.connor, 'Xai Guess', currentGuess.xai, 'Real Number', myNumber);
// whoWins.xai = true;
// whoWins.connor = false;
// whoWins.xaiHigher = false;
// if (currentGuess.connor > myNumber) {
// whoWins.connorHigher = true;
// }
// if (currentGuess.connor < myNumber) {
// whoWins.connorHigher = false;
// }
// console.log('Xai wins', myNumber, currentGuess.connor, currentGuess.xai, whoWins);
// res.send(whoWins);
// }
// else {
// console.log('Connor Guess', currentGuess.connor, 'Xai Guess', currentGuess.xai, 'Real Number', myNumber);
// console.log('connor and xai lost');
// whoWins.xai = false;
// whoWins.connor = false;
// if (currentGuess.xai > myNumber) {
// whoWins.xaiHigher = true;
// }
// if (currentGuess.xai < myNumber) {
// whoWins.xaiHigher = false;
// }
// if (currentGuess.connor > myNumber) {
// whoWins.connorHigher = true;
// }
// if (currentGuess.connor < myNumber ) {
// whoWins.connorHigher = false;
// }
// console.log('Nobody wins', whoWins);
// res.send(whoWins);
// }
});
// function randomNumber(min, max) {
// return Math.floor(Math.random() * (1 + max - min) + min);
// }
|
package kataChallenge;
class TranslateRoman {
public static int romanToInt(String s) {
int res = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
char chAfter;
char chBefore;
if (i != (s.length() - 1))
chAfter = s.charAt(i+1);
else
chAfter = ' ';
if (i != 0)
chBefore = s.charAt(i-1);
else
chBefore = ' ';
switch (ch) {
case ('I') -> {
if (chAfter == 'V')
res += 4;
else if (chAfter == 'X')
res += 9;
else
res++;
}
case ('V') -> {
if (chBefore == 'I') {
} else
res += 5;
}
case ('X') -> {
if (chBefore == 'I') {
} else if (chAfter == 'L')
res += 40;
else if (chAfter == 'C')
res += 90;
else
res += 10;
}
case ('L') -> {
if (chBefore == 'X') {
} else
res += 50;
}
case ('C') -> {
if (chBefore == 'X') {
} else if (chAfter == 'D')
res += 400;
else if (chAfter == 'M')
res += 900;
else
res += 100;
}
case ('D') -> {
if (chBefore == 'C') {
} else
res += 500;
}
case ('M') -> {
if (chBefore == 'C') {
} else
res += 1000;
}
}
}
return res;
}
public static String intToRoman(int s) {
int[] values = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
String[] romanLetters = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
StringBuilder roman = new StringBuilder();
for(int i=0;i<values.length;i++)
{
while(s >= values[i])
{
s = s - values[i];
roman.append(romanLetters[i]);
}
}
return roman.toString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.