text
stringlengths 184
4.48M
|
---|
import { useEffect, useState } from "react";
function useKeylistener(
key: { mainKey: string; extraKey?: string } | string,
eventHandler: (e: KeyboardEvent) => void
): void {
const [firstKeyPressed, setFirstKeyPressed] = useState(false);
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (typeof key === "string") {
if (key === e.code) eventHandler(e);
return;
}
if (e.code === key.mainKey && !key.extraKey) {
eventHandler(e);
return;
}
if (e.code === key.extraKey && firstKeyPressed) {
e.preventDefault();
eventHandler(e);
setFirstKeyPressed(false);
} else if (e.code === key.mainKey) {
setFirstKeyPressed(true);
} else {
setFirstKeyPressed(false);
}
};
document.addEventListener("keyup", handler);
return () => document.removeEventListener("keyup", handler);
}, [key, eventHandler, firstKeyPressed]);
}
export default useKeylistener;
type ModifierListener = {
modifierKey: string;
eventHandler: (e: KeyboardEvent) => void;
};
type ModifierKeymap = {
mainKey: string;
mainEventHandler: (e: KeyboardEvent) => void;
modifierListeners: ModifierListener[];
};
export const useWithModifiersKeylistener = (keymaps: ModifierKeymap) => {
const [modifierKey, setModifierKey] = useState<ModifierListener | null>(null);
useEffect(() => {
const handler = (e: KeyboardEvent) => {
const modifier = keymaps.modifierListeners.find(
(m) => m.modifierKey === e.code
);
setModifierKey(modifier ?? null);
if (e.code === keymaps.mainKey && !modifierKey) {
keymaps.mainEventHandler(e);
console.log("Hurray");
return;
} else if (e.code === keymaps.mainKey && modifierKey) {
modifierKey?.eventHandler(e);
}
};
document.addEventListener("keyup", handler);
return () => document.removeEventListener("keyup", handler);
}, [modifierKey, keymaps]);
};
|
import { NotificationService } from './../../services/notification.service';
import { DataService } from './../../services/data.service';
import { NgFor } from '@angular/common';
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Heroi } from '../../Models/Herois';
import { Superpoderes } from '../../Models/Superpoderes';
@Component({
selector: 'app-editar-heroi',
standalone: true,
imports: [FormsModule, NgFor],
templateUrl: './editar-heroi.component.html',
styleUrl: './editar-heroi.component.scss'
})
export class EditarHeroiComponent {
heroi: Heroi;
dataAniversarioFormatado: string = "";
listaSuperpoderes: Superpoderes[] = [];
dataService: DataService<Heroi>;
notificationService: NotificationService;
constructor(dataService: DataService<Heroi>, notificationService: NotificationService) {
this.heroi = new Heroi(0, "", "", new Date(), 0, 0, []);
this.dataService = dataService;
this.notificationService = notificationService;
document.addEventListener("EditarHeroi", (e: any) => {
this.carregaHeroi(e.detail as number);
this.carregaSuperpoderes();
this.AbrirLista();
});
}
AbrirLista() {
const editor = document.querySelector("app-editar-heroi") as HTMLDivElement;
editor.style.display = "block";
}
cancelarEdicao() {
const editor = document.querySelector("app-editar-heroi") as HTMLDivElement;
editor.style.display = "none";
}
salvarAlteracoes() {
this.heroi.dataNascimento = new Date(this.dataAniversarioFormatado);
const button = document.getElementById("btnSalvar");
if (!this.ValidaHeroi(this.heroi)) {
return;
}
button?.setAttribute("disabled", "true");
this.dataService.put("herois", this.heroi.id, this.heroi).subscribe({
next: (data) => {
this.notificationService.showToastr("Heroi alterado com sucesso!");
this.cancelarEdicao();
document.dispatchEvent(new CustomEvent("UpdateEventList"));
button?.removeAttribute("disabled");
},
error: (error) => {
if (error.status == 400) {
this.notificationService.showToastr(error.error);
}
else this.notificationService.showToastr("Erro ao alterar heroi!");
button?.removeAttribute("disabled");
}
});
}
SelecionaPoder(id: number) {
const label = document.querySelector("#label--" + id) as HTMLLabelElement;
const checkbox = document.querySelector("#checkbox--" + id) as HTMLInputElement;
if(checkbox.checked){
label.classList.add("heroi__checkbox__label--active");
if(this.heroi.listaSuperpoderes)
this.heroi.listaSuperpoderes.push(this.listaSuperpoderes.find((poder) => poder.id == id) as Superpoderes);
}
else{
label.classList.remove("heroi__checkbox__label--active");
if(this.heroi.listaSuperpoderes)
this.heroi.listaSuperpoderes = this.heroi.listaSuperpoderes.filter((poder) => poder.id != id);
}
}
private ValidaHeroi(heroi: Heroi): boolean {
if (heroi.nome == "") {
this.notificationService.showToastr("Nome é obrigatório!");
return false;
}
if (heroi.nomeHeroi == "") {
this.notificationService.showToastr("Nome do heroi é obrigatório!");
return false;
}
if (heroi.dataNascimento == undefined) {
this.notificationService.showToastr("Data de nascimento é obrigatório!");
return false;
}
if (!heroi.dataNascimento) {
this.notificationService.showToastr("Data Iválida!");
return false;
}
return true;
}
private carregaHeroi(id: number) {
this.dataService.get("herois/" + id).subscribe({
next: (data) => {
this.heroi = data as any as Heroi;
const dia = new Date(this.heroi.dataNascimento);
this.dataAniversarioFormatado = dia.getFullYear().toString().padStart(4, "0") + "-" + (dia.getMonth() + 1).toString().padStart(2, "0") + "-" + dia.getDate().toString().padStart(2, "0");
this.PintaPoderesHeroi();
},
error: () => {
this.notificationService.showToastr("Erro ao buscar heroi!");
}
});
}
private carregaSuperpoderes() {
this.dataService.get("superpoderes").subscribe({
next: (data) => {
this.listaSuperpoderes = data as any as Superpoderes[];
},
error: () => {
this.notificationService.showToastr("Erro ao buscar superpoderes!");
}
});
}
private PintaPoderesHeroi() {
if(this.heroi.listaSuperpoderes)
this.heroi.listaSuperpoderes.forEach((poder) => {
const label = document.querySelector("#label--" + poder.id) as HTMLLabelElement;
const checkbox = document.querySelector("#checkbox--" + poder.id) as HTMLInputElement;
label.classList.add("heroi__checkbox__label--active");
checkbox.checked = true;
});
}
}
|
@charset "UTF-8";
//@mixin loadify($direction: "loadify", $duration: 1s, $delay: 0) {
// opacity: 0;
// visibility: hidden;
// backface-visibility: hidden;
// animation-fill-mode: forwards;
// animation-delay: $delay;
// animation-duration: $duration;
// @if $duration == "up" {
// animation-name: loadify-up;
// }
// @else if $duration == "down" {
// animation-name: loadify-down;
// }
// @else if $duration == "left" {
// animation-name: loadify-left;
// }
// @else if $duration == "right" {
// animation-name: loadify-right;
// }
// @else {
// animation-name: loadify;
// }
//}
@mixin loadify($params...) {
@if not & {
@if length($params) == 0 or (length($params) == 1 and nth($params, 1) == "init") {
@keyframes loadify {
to {
opacity: 1;
visibility: visible;
backface-visibility: visible;
}
}
%loadify {
opacity: 0;
visibility: hidden;
backface-visibility: hidden;
animation-name: loadify;
animation-fill-mode: forwards;
}
} @else if (length($params) == 1 and nth($params, 1) != "init") or (length($params) == 1 and type-of(nth($params, 1)) != "string") {
@error "#{nth($params, 1)} is not a valid argument. Please pass `init` as an argument to initialize the effect or do not pass any argument at //all.";
} @else if length($params) > 1 {
@error "Only one argument is allowed when you call this mixin at the root of your stylesheet! Please pass `init` as an argument to initialize //the effect or do not pass any argument at all.";
}
} @else if & {
@extend %loadify;
@if length($params) == 0 {
animation-delay: 0.2s;
animation-duration: 0.5s;
} @else if length($params) == 1 {
animation-delay: #{__isTime(nth($params, 1))};
animation-duration: 0.5s;
} @else if length($params) == 2 {
animation-delay: #{__isTime(nth($params, 1))};
animation-duration: #{__isTime(nth($params, 2))};
} @else if length($params) > 2 {
@error "You cannot pass more than two arguments.";
}
}
}
|
import torch
import torch.nn as nn
import torch.optim as optim
from data.processed.data_preprocessing import load_and_process_data
from data.processed.model import SimpleLSTM
# Load data
train_loader, X_test, y_test = load_and_process_data('AAPL_stock_data_with_indicators.csv', 5)
# Initialize model, loss function, and optimizer
model = SimpleLSTM(input_size=5, hidden_layer_size=100, output_size=1)
loss_function = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# Training loop
epochs = 10
for epoch in range(epochs):
for seq, labels in train_loader:
optimizer.zero_grad()
model.hidden_cell = (torch.zeros(1, 1, model.hidden_layer_size),
torch.zeros(1, 1, model.hidden_layer_size))
y_pred = model(seq)
single_loss = loss_function(y_pred, labels)
single_loss.backward()
optimizer.step()
print(f'Epoch {epoch} loss: {single_loss.item()}')
# Add evaluation code here if needed
|
// implements bubble-sort algorithm
export function bubbleSort(array) {
const moves = []
let noSwaps
for (let i = array.length; i > 0; i--) {
noSwaps = true
for (let j = 0; j < i - 1; j++) {
moves.push({ indeces: [j, j + 1], type: 'comp' })
if (array[j] > array[j + 1]) {
moves.push({ indeces: [j, j + 1], type: 'swap' })
;[array[j], array[j + 1]] = [array[j + 1], array[j]]
noSwaps = false
}
}
if (noSwaps) break
}
return moves
}
// implements selection-sort algorithm
export function selectionSort(array) {
let moves = []
for (let i = 0; i < array.length; i++) {
let lowest = i
for (let j = i + 1; j < array.length; j++) {
moves.push({ indeces: [i, lowest], j, type: 'comp' })
if (array[lowest] > array[j]) {
lowest = j
}
}
if (i !== lowest) {
moves.push({ indeces: [i, lowest], type: 'swap' })
;[array[i], array[lowest]] = [array[lowest], array[i]]
}
}
return moves
}
// implements insertion-sort algorithms
export function insertionSort(array) {
let moves = []
let currentVal
for (let i = 1; i < array.length; i++) {
currentVal = array[i]
let j = i - 1
moves.push({ indeces: [j, i], type: 'comp' })
while (j >= 0 && array[j] > currentVal) {
moves.push({ indeces: [j, j + 1], type: 'comp' })
moves.push({ indeces: [j + 1, j], type: 'swap' })
;[array[j + 1], array[j]] = [array[j], array[j + 1]]
j--
}
}
return moves
}
// implements merge-sort algorithms
export function mergeSort(array, moves_m = []) {
if (array.length <= 0) return array
let auxiliaryArray = [...array]
mergeSortHelper(array, 0, array.length - 1, auxiliaryArray, moves_m)
return moves_m
}
function mergeSortHelper(mainArray, startIdx, endIdx, auxiliaryArray, moves_m) {
if (startIdx === endIdx) return
let middleIdx = startIdx + Math.floor((endIdx - startIdx) / 2)
mergeSortHelper(auxiliaryArray, startIdx, middleIdx, mainArray, moves_m)
mergeSortHelper(auxiliaryArray, middleIdx + 1, endIdx, mainArray, moves_m)
merge(mainArray, startIdx, middleIdx, endIdx, auxiliaryArray, moves_m)
}
// merge-sort helper function - sorts array in place given start/end indeces using auxilliary array
function merge(mainArray, startIdx, middleIdx, endIdx, auxiliaryArray, moves_m) {
let replace = []
let k = startIdx
let i = startIdx
let j = middleIdx + 1
while (i <= middleIdx && j <= endIdx) {
moves_m.push({ indeces: [i, j], type: 'comp' })
if (auxiliaryArray[i] <= auxiliaryArray[j]) {
mainArray[k] = auxiliaryArray[i]
replace.push({ indeces: [k], newVal: auxiliaryArray[i], type: 'replace' })
i++
} else {
mainArray[k] = auxiliaryArray[j]
replace.push({ indeces: [k], newVal: auxiliaryArray[j], type: 'replace' })
j++
}
k++
}
while (i <= middleIdx) {
mainArray[k] = auxiliaryArray[i]
replace.push({ indeces: [k], newVal: auxiliaryArray[i], type: 'replace' })
i++
k++
}
while (j <= endIdx) {
mainArray[k] = auxiliaryArray[j]
replace.push({ indeces: [k], newVal: auxiliaryArray[j], type: 'replace' })
j++
k++
}
moves_m.push(...replace)
}
// quick-sort helper function - places first array item in correct (sorted) place and returns the index
function pivot(arr, start = 0, end = arr.length - 1, moves_q) {
let swapIdx = start
for (let i = start + 1; i <= end; i++) {
moves_q.push({ indeces: [start, i, swapIdx], start, swapIdx, type: 'comp' })
if (arr[i] < arr[start]) {
swapIdx++
;[arr[swapIdx], arr[i]] = [arr[i], arr[swapIdx]]
moves_q.push({ indeces: [swapIdx, i], start, swapIdx, type: 'swap', finalSwap: false })
}
}
;[arr[start], arr[swapIdx]] = [arr[swapIdx], arr[start]]
moves_q.push({ indeces: [swapIdx, start], start, swapIdx, type: 'swap', finalSwap: true })
return swapIdx
}
// implements quick-sort algorithm
export function quickSort(arr, left = 0, right = arr.length - 1, moves_q = []) {
if (left >= right) return
let pivotIdx = pivot(arr, left, right, moves_q)
quickSort(arr, left, pivotIdx - 1, moves_q)
quickSort(arr, pivotIdx + 1, right, moves_q)
return moves_q
}
|
#include <boost/test/unit_test.hpp>
#include <sstream>
#include <tryte.h>
using namespace Ternary;
BOOST_AUTO_TEST_SUITE(Types_Tryte)
BOOST_AUTO_TEST_CASE(constructor)
{
Tryte t;
Tryte t2(1);
BOOST_CHECK(t2.trits[0].data == 0b01);
Tryte t3(2);
BOOST_CHECK_EQUAL(t3.toString(), "1T");
Tryte t4(-1);
BOOST_CHECK_EQUAL(t4.trits[0].data, 0b10);
BOOST_CHECK_EQUAL(t4.toString(), "T");
Tryte t5(27);
BOOST_CHECK_EQUAL(t5.toString(), "1000");
t = 5;
BOOST_CHECK_EQUAL(t.toString(), "1TT");
t = -5;
BOOST_CHECK_EQUAL(t.toString(), "T11");
t = Tryte::FromString("T11");
BOOST_CHECK_EQUAL(t.toString(), "T11");
}
BOOST_AUTO_TEST_CASE(tryte_to_string)
{
std::ostringstream os;
Tryte t1(1);
os << t1;
BOOST_CHECK_EQUAL(os.str(), "1");
os.str(std::string());
Tryte t2(-1);
os << t2;
BOOST_CHECK_EQUAL(os.str(), "T");
os.str(std::string());
Tryte t3(200);
t3.trits[2].data = 0b11;
BOOST_CHECK_THROW(os << t3, TException);
}
BOOST_AUTO_TEST_CASE(tryte_neg)
{
Tryte t1(1), t2(-1), t3(2), t4(-2);
try {
BOOST_CHECK_EQUAL(-t1, t2);
BOOST_CHECK_EQUAL(-t2, t1);
BOOST_CHECK_EQUAL(-t3, t4);
BOOST_CHECK_EQUAL(-t4, t3);
}
catch (TException& e) {
std::cout << e.what() << std::endl;
}
}
BOOST_AUTO_TEST_CASE(tryte_comparison)
{
Tryte t1(1), t2(-1), t3(2), t4(-2), t5(3), t6(-3);
BOOST_CHECK(t1 == t1);
BOOST_CHECK(t2 == t2);
BOOST_CHECK(t3 == t3);
BOOST_CHECK(t4 == t4);
BOOST_CHECK(t5 == t5);
BOOST_CHECK(t6 == t6);
BOOST_CHECK(t1 != t2);
BOOST_CHECK(t1 != t3);
BOOST_CHECK(t1 != t4);
BOOST_CHECK(t1 != t5);
BOOST_CHECK(t1 != t6);
BOOST_CHECK(t2 != t3);
BOOST_CHECK(t2 != t4);
BOOST_CHECK(t2 != t5);
BOOST_CHECK(t2 != t6);
BOOST_CHECK(t3 != t4);
BOOST_CHECK(t3 != t5);
BOOST_CHECK(t3 != t6);
BOOST_CHECK(t4 != t5);
BOOST_CHECK(t4 != t6);
BOOST_CHECK(t5 != t6);
BOOST_CHECK(t1 > t2);
BOOST_CHECK(t1 < t3);
BOOST_CHECK(t1 > t4);
BOOST_CHECK(t1 < t5);
BOOST_CHECK(t1 > t6);
BOOST_CHECK(t2 < t3);
BOOST_CHECK(t2 > t4);
BOOST_CHECK(t2 < t5);
BOOST_CHECK(t2 > t6);
BOOST_CHECK(t3 > t4);
BOOST_CHECK(t3 < t5);
BOOST_CHECK(t3 > t6);
BOOST_CHECK(t4 < t5);
BOOST_CHECK(t4 > t6);
BOOST_CHECK(t5 > t6);
}
BOOST_AUTO_TEST_CASE(tryte_and_or)
{
Tryte t1(1), t2(-1), t3(2), t4(-2), t5(3), t6(-3);
BOOST_CHECK_EQUAL(t1 & t2, Tryte::FromString("T"));
BOOST_CHECK_EQUAL(t1 & t3, Tryte::FromString("T"));
BOOST_CHECK_EQUAL(t1 & t4, Tryte::FromString("T1"));
BOOST_CHECK_EQUAL(t1 | t5, Tryte::FromString("11"));
BOOST_CHECK_EQUAL(t1 | t6, Tryte::FromString("1"));
}
BOOST_AUTO_TEST_CASE(tryte_add)
{
Tryte t1(1), t2(-1), t3(2), t4(-2), t5(3), t6(-3);
BOOST_CHECK_EQUAL(t1 + t2, Tryte::FromString("0"));
BOOST_CHECK_EQUAL(t1 + t3, Tryte::FromString("10"));
BOOST_CHECK_EQUAL(t1 + t4, Tryte::FromString("T"));
BOOST_CHECK_EQUAL(t1 + t5, Tryte::FromString("11"));
BOOST_CHECK_EQUAL(t1 + t6, Tryte::FromString("T1"));
}
BOOST_AUTO_TEST_SUITE_END()
|
/**
* @file
* Protected interface for computing semantic policy difference.
*
* @author Jeremy A. Mowery [email protected]
* @author Jason Tang [email protected]
*
* Copyright (C) 2006-2007 Tresys Technology, LLC
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef POLDIFF_POLDIFF_INTERNAL_H
#define POLDIFF_POLDIFF_INTERNAL_H
#ifdef __cplusplus
extern "C"
{
#endif
#include <poldiff/poldiff.h>
#include <apol/bst.h>
typedef enum
{
AVRULE_OFFSET_ALLOW = 0, AVRULE_OFFSET_AUDITALLOW,
AVRULE_OFFSET_DONTAUDIT, AVRULE_OFFSET_NEVERALLOW,
AVRULE_OFFSET_MAX
} avrule_offset_e;
typedef enum
{
TERULE_OFFSET_CHANGE = 0, TERULE_OFFSET_MEMBER,
TERULE_OFFSET_TRANS,
TERULE_OFFSET_MAX
} terule_offset_e;
#include "attrib_internal.h"
#include "avrule_internal.h"
#include "bool_internal.h"
#include "cat_internal.h"
#include "class_internal.h"
#include "level_internal.h"
#include "range_internal.h"
#include "range_trans_internal.h"
#include "rbac_internal.h"
#include "role_internal.h"
#include "terule_internal.h"
#include "user_internal.h"
#include "type_internal.h"
#include "type_map_internal.h"
/* forward declarations */
struct poldiff_attrib_summary;
struct poldiff_avrule_summary;
struct poldiff_bool_summary;
struct poldiff_cat_summary;
struct poldiff_class_summary;
struct poldiff_common_summary;
struct poldiff_level_summary;
struct poldiff_range_trans_summary;
struct poldiff_role_summary;
struct poldiff_role_allow_summary;
struct poldiff_role_trans_summary;
struct poldiff_terule_summary;
struct poldiff_type_summary;
struct poldiff_user_summary;
/* and so forth for ocon_summary structs */
struct poldiff
{
/** the "original" policy */
apol_policy_t *orig_pol;
/** the "modified" policy */
apol_policy_t *mod_pol;
/** pointer to original's qpol policy within orig_pol */
qpol_policy_t *orig_qpol;
/** pointer to modified's qpol policy within mod_pol */
qpol_policy_t *mod_qpol;
/** non-zero if rules' line numbers are accurate */
int line_numbers_enabled;
/** BST of duplicated strings, used when making pseudo-rules */
apol_bst_t *class_bst;
/** BST of duplicated strings, used when making pseudo-rules */
apol_bst_t *perm_bst;
/** BST of duplicated strings, used when making pseudo-rules */
apol_bst_t *bool_bst;
poldiff_handle_fn_t fn;
void *handle_arg;
/** set of POLDIF_DIFF_* bits for diffs run */
uint32_t diff_status;
struct poldiff_attrib_summary *attrib_diffs;
struct poldiff_avrule_summary *avrule_diffs[AVRULE_OFFSET_MAX];
struct poldiff_bool_summary *bool_diffs;
struct poldiff_cat_summary *cat_diffs;
struct poldiff_class_summary *class_diffs;
struct poldiff_common_summary *common_diffs;
struct poldiff_level_summary *level_diffs;
struct poldiff_range_trans_summary *range_trans_diffs;
struct poldiff_role_summary *role_diffs;
struct poldiff_role_allow_summary *role_allow_diffs;
struct poldiff_role_trans_summary *role_trans_diffs;
struct poldiff_terule_summary *terule_diffs[TERULE_OFFSET_MAX];
struct poldiff_type_summary *type_diffs;
struct poldiff_user_summary *user_diffs;
/* and so forth if we want ocon_diffs */
type_map_t *type_map;
/** most recently used flags to open the two policies */
int policy_opts;
/** set if type mapping was changed since last run */
int remapped;
};
/**
* Callback function signature for getting a vector of all unique
* items of a given kind in a policy. The vector must be sorted
* prior to returning from this function.
*
* @param diff Policy diff error handler.
* @param policy The policy from which to get the items.
* @return a newly allocated vector of all unique items of the
* appropriate kind on success, or NULL on error; if the call fails,
* errno will be set.
*/
typedef apol_vector_t *(*poldiff_get_items_fn_t) (poldiff_t * diff, const apol_policy_t * policy);
/**
* Callback function signature for quickly comparing two items to
* determine if they are semantically the same item. This operation
* should quickly determine if the two are obviously different or
* not.
*
* @param x The item from the original policy.
* @param y The item from the modified policy.
* @param diff The policy difference structure associated with both
* items.
*
* @return Expected return value from this function is < 0, 0, or > 0
* if item x is respectively less than, equal to, or greater than item y.
* This must be able to return a defined stable ordering for all items
* not semantically equivalent.
*/
typedef int (*poldiff_item_comp_fn_t) (const void *x, const void *y, const poldiff_t * diff);
/**
* Callback function signature for creating, initializing and inserting
* a new semantic difference entry for an item.
* @param diff The policy difference structure to which to add the entry.
* @param form The form of the difference, one of POLDIFF_FORM_ADDED or
* POLDIFF_FORM_REMOVED.
* @param item Item for which the entry is being created.
* @return Expected return value from this function is 0 on success and
* < 0 on error; if the call fails, it is expected to set errno and to
* leave the policy difference structure unchanged.
*/
typedef int (*poldiff_new_diff_fn_t) (poldiff_t * diff, poldiff_form_e form, const void *item);
/**
* Callback function signature for computing the semantic difference of
* two items for which the compare callback returns 0. This function should
* calculate the difference of any properties of the items and if a difference
* is found to allocate, initialize, and insert an new semantic difference
* entry for that item.
* @param diff The policy difference structure associated with both items and
* to which to add an entry if needed.
* @param x The item from the original policy.
* @param y The item from the modified policy.
* @return Expected return value from this function is 0 on success and
* < 0 on error; if the call fails, it is expected to set errno and to
* leave the policy difference structure unchanged.
*/
typedef int (*poldiff_deep_diff_fn_t) (poldiff_t * diff, const void *x, const void *y);
/**
* Callback function signature for resetting the diff results for an
* item. called when mapping of the symbols used by the diff change.
* @param diff The policy difference structure containing the diffs
* to reset.
* @return 0 on success and < 0 on error; if the call fails,
* it is expected to set errno.
*/
typedef int (*poldiff_reset_fn_t) (poldiff_t * diff);
/******************** error handling code below ********************/
#define POLDIFF_MSG_ERR 1
#define POLDIFF_MSG_WARN 2
#define POLDIFF_MSG_INFO 3
/**
* Write a message to the callback stored within a poldiff error
* handler. If the msg_callback field is empty then suppress the
* message.
*
* @param p Error reporting handler. If NULL then write message to
* stderr.
* @param level Severity of message, one of POLDIFF_MSG_ERR,
* POLDIFF_MSG_WARN, or POLDIFF_MSG_INFO.
* @param fmt Format string to print, using syntax of printf(3).
*/
__attribute__ ((format(printf, 3, 4))) extern void poldiff_handle_msg(const poldiff_t * p, int level, const char *fmt, ...);
#undef ERR
#undef WARN
#undef INFO
#define ERR(handle, format, ...) poldiff_handle_msg(handle, POLDIFF_MSG_ERR, format, __VA_ARGS__)
#define WARN(handle, format, ...) poldiff_handle_msg(handle, POLDIFF_MSG_WARN, format, __VA_ARGS__)
#define INFO(handle, format, ...) poldiff_handle_msg(handle, POLDIFF_MSG_INFO, format, __VA_ARGS__)
/**
* Build the BST for classes, permissions, and booleans if the
* policies have changed. This effectively provides a partial mapping
* of rules from one policy to the other.
*
* @param diff Policy difference structure containing policies to diff.
*
* @return 0 on success, < 0 on error.
*/
int poldiff_build_bsts(poldiff_t * diff);
#ifdef __cplusplus
}
#endif
#endif /* POLDIFF_POLDIFF_INTERNAL_H */
|
import { NextRequest, NextResponse, userAgentFromString } from "next/server";
import connect from "@/dbConfig/dbConfig";
import users from '@/models/userModel'
import bcryptjs from 'bcryptjs'
import { error } from "console";
import jwt from 'jsonwebtoken'
connect()
export async function POST(req: NextRequest) {
try {
const { email, password } = await req.json();
const user = await users.findOne({ email });
if (!user) {
return NextResponse.json(
{
message: "User Did not exists, please signup"
},
{
status: 400
}
)
}
const validPassword = await bcryptjs.compare(password, user.password);
if (!validPassword) {
return NextResponse.json(
{
error: "Invalid Password"
},
{
status: 400
}
)
}
const tokenData = {
id: user._id,
name: user.name,
email: user.email
}
const token = await jwt.sign(tokenData, process.env.JWT_SECRET!, { expiresIn: '6d' })
const response = NextResponse.json({
message: "Login Successful",
success : true,
userName : user.name
})
response.cookies.set('token', token, {
httpOnly : true,
});
return response;
} catch (error: any) {
console.error(error.message);
return NextResponse.json({ error: error.message }, { status: 500 })
}
}
|
import random
class MarkovChainTextGenerator:
def __init__(self, order=1):
self.order = order
self.model = {}
def train(self, text):
words = text.split()
for i in range(len(words) - self.order):
gram = tuple(words[i:i + self.order])
next_word = words[i + self.order]
if gram in self.model:
self.model[gram].append(next_word)
else:
self.model[gram] = [next_word]
def generate_text(self, length=50):
current = random.choice(list(self.model.keys()))
text = list(current)
for _ in range(length - self.order):
if current in self.model:
next_word = random.choice(self.model[current])
text.append(next_word)
current = tuple(text[-self.order:])
else:
break
return ' '.join(text)
# Example usage:
if __name__ == "__main__":
source_text = "This is a sample text for Markov chain text generation. It demonstrates how Markov chains can be used to generate new text."
generator = MarkovChainTextGenerator(order=2)
generator.train(source_text)
for i in range(10):
generated_text = generator.generate_text(length=20)
n = i+1
print(f"Text {n} : {generated_text}")
|
use anyhow::{Context, Result};
use futures::{Sink, Stream, StreamExt, TryStreamExt};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use px_round_based::Msg;
use futures::channel::mpsc;
use libc::{c_char, c_int};
use std::ffi::CString;
pub async fn join_computation<M>(
index: u16,
incoming_receiver: Box<mpsc::Receiver<String>>,
callback: unsafe extern "C" fn(*const c_char, c_int),
) -> Result<(
impl Stream<Item = Result<Msg<M>>>,
impl Sink<Msg<M>, Error = anyhow::Error>,
)>
where
M: Serialize + DeserializeOwned,
{
let client = SmClient::new(callback).context("construct SmClient")?;
// Construct channel of incoming messages
let incoming = client
.subscribe(incoming_receiver)
.await
.context("subscribe")?
.and_then(|msg| async move {
serde_json::from_str::<Msg<M>>(&msg).context("deserialize message")
});
// Ignore incoming messages addressed to someone else
let incoming = incoming.try_filter(move |msg| {
futures::future::ready(
msg.sender != index && (msg.receiver.is_none() || msg.receiver == Some(index)),
)
});
// Construct channel of outgoing messages
let outgoing = futures::sink::unfold(client, |client, message: Msg<M>| async move {
let serialized = serde_json::to_string(&message).context("serialize message")?;
client
.broadcast(&serialized)
.await
.context("broadcast message")?;
Ok::<_, anyhow::Error>(client)
});
Ok((incoming, outgoing))
}
pub struct SmClient {
callback: unsafe extern "C" fn(*const c_char, c_int),
}
impl SmClient {
pub fn new(
callback: unsafe extern "C" fn(*const c_char, c_int),
) -> Result<Self> {
Ok(Self {
callback: callback,
})
}
pub async fn broadcast(&self, message: &str) -> Result<()> {
let outgoing_message = generate_outgoing_message("broadcast", message);
let msg = CString::new(outgoing_message).unwrap();
unsafe { (self.callback)(msg.as_ptr(), msg.as_bytes().len() as c_int) };
Ok(())
}
pub async fn subscribe(&self, incoming_receiver: Box<mpsc::Receiver<String>>) -> Result<impl Stream<Item = Result<String>>> {
Ok(incoming_receiver.filter_map(|msg| async {
Some(Ok(msg))
}))
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct OutgoingMessage<'a, 'b> {
pub data_type: &'a str,
pub data: &'b str,
}
pub fn generate_outgoing_message<'a, 'b>(data_type: &'a str, data: &'b str) -> String {
let outgoing_message = OutgoingMessage { data_type, data };
return serde_json::to_string(&outgoing_message).unwrap();
}
|
//
// WebServices+Login.swift
// Lumi
//
// Created by Rishabh Sharma on 27/04/22.
//
import Foundation
import KeychainAccess
extension WebServices {
// MARK: = Login API
static func loginAPICall(parameters: JSONDictionary,response: @escaping ((Result<(JSON),Error>) -> Void)) {
commonPostWithRawJSONAPI(parameters: parameters, endPoint: .phoneNumberPost, loader: true) { (result) in
switch result {
case .success(let json):
response(.success(json))
case .failure(let error):
response(.failure(error))
}
}
}
// MARK: - Api for update number
static func updatePhoneCall(parameters: JSONDictionary,response: @escaping ((Result<(JSON),Error>) -> Void)) {
commonPatchWithRawJSONAPI(parameters: parameters, endPoint: .updatePhonePatch, loader: true) { (result) in
switch result {
case .success(let json):
response(.success(json))
case .failure(let error):
response(.failure(error))
}
}
}
// MARK: - API for otp
static func otpAPICall(parameters: JSONDictionary,response: @escaping ((Result<(JSON),Error>) -> Void)) {
commonPostWithRawJSONAPI(parameters: parameters, endPoint: .otpPost, loader: true) { (result) in
switch result {
case .success(let json):
let token = json["token"].stringValue
// Storing in keychain
// Change token1 to token to get it from login page
let loginType = json["message"].stringValue
UserDefaults.standard.set(loginType, forKey: UserDefaultVar.loginType.rawValue)
keychain[KeychainVar.token.rawValue] = token
debugPrint(keychain[KeychainVar.token.rawValue] as Any)
// Storing in userDefault
// UserDefaults.standard.set(token, forKey: "token")
// print(UserDefaults.standard.object(forKey: "token") as Any)
response(.success(json))
case .failure(let error):
response(.failure(error))
}
}
}
// MARK: - Api for user profile
static func profileCall(parameters: JSONDictionary,response: @escaping ((Result<(JSON),Error>) -> Void)) {
commonPatchWithRawJSONAPI(parameters: parameters, endPoint: .profilePost, loader: true) { (result) in
switch result {
case .success(let json):
let token = json["token"].stringValue
// Storing in keychain
keychain[KeychainVar.token.rawValue] = token
response(.success(json))
case .failure(let error):
response(.failure(error))
}
}
}
}
|
/**
* PJAX 刷新。
* 对于 PJAX,最困难的问题在于不同脚本的刷新,页面切换之后,尽管大部分 PJAX 插件会提供自动执行脚本的功能。
* 但此功能实际上需要各个网站定制化,因此需要将脚本分类,在 PJAX 的角度上大致能将脚本分为三类
* 1、例如看板娘等全局页面都会存在的脚本,仅仅需要加载一次。
* 2、例如网站访问量、AD 等每个页面都存在,并且 pjax 刷新的时候都需要重新加载的脚本。
* 3、例如评论组件等仅在部分页面存在,不使用不加载的脚本。
*
* 对于上述脚本,每一类需要有每一类的处理方式。
* 1、第一类脚本,通常需要将其放在非 PJAX 刷新区域之外,之后便不需要进行任何处理。只需保证在 PJAX 加载
* 刷新区时,不重复加载即可。
* 2、第二类脚本,例如 AD,如果用户从首页切换到某个目录,此时由于 PJAX 的原因,AD 并不会在第二个页面加载,
* 此时的做法可以是重新调用目标 JS 的初始化,但此类脚本通常不包含初始化方法且种类繁多,处理极其麻烦。因此
* 比较好的处理方式是重新加载此脚本的 script。如使用 replaceChild 重新替换脚本。
* 3、第三类脚本,例如评论组件加载,当用户从首页进入到某个文章,评论组件并不会重新在此文章页面渲染,而且,
* 通常文章会控制是否使用评论。此类脚本与第二类很相似,但不同点在于,此类组件可选并且只加载一次【全体】,
* 而每个需要此插件的页面则只需重新执行初始化方法即可。因而此种方式也更为麻烦,因为不同的脚本具有不同的初始化
* 方式。计划通过 Zero 的刷新事件来同步更新所有内联代码块的刷新功能。
*
* 脱离 Jquery,使用 https://github.com/MoOx/pjax
*/
import Pjax from "pjax";
import { sakura } from "../main";
import NProgress from "nprogress";
import { Util } from "../utils/util";
NProgress.configure({ trickle: false });
const pjax = new Pjax({
elements: "a[data-pjax]",
selectors: ["head title", ".wrapper", ".pjax"],
switches: {
".wrapper": Pjax.switches.innerHTML,
},
analytics: false,
cacheBust: false,
debug: import.meta.env.MODE === "development" ? true : false,
});
// @ts-ignore
// 修复由于 pjax 导致的 Request Context 无法被拦截获取信息的问题。
pjax.doRequest = function (
location,
options: Pjax.IOptions,
callback: (requestText: string | null, request: XMLHttpRequest, href: string, options?: Pjax.IOptions) => void
) {
options = options || {};
var queryString;
var requestOptions = options.requestOptions || {};
var requestMethod = (requestOptions.requestMethod || "GET").toUpperCase();
var requestParams = requestOptions.requestParams || null;
var formData = requestOptions.formData || null;
var requestPayload = null;
var request = new XMLHttpRequest();
var timeout = options.timeout || 0;
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status === 200) {
callback(request.responseText, request, location, options);
} else if (request.status !== 0) {
callback(null, request, location, options);
}
}
};
request.onerror = function (e) {
console.log(e);
callback(null, request, location, options);
};
request.ontimeout = function () {
callback(null, request, location, options);
};
if (requestParams && requestParams.length) {
queryString = requestParams
.map(function (param: { name: string; value: string }) {
return param.name + "=" + param.value;
})
.join("&");
switch (requestMethod) {
case "GET":
location = location.split("?")[0];
location += "?" + queryString;
break;
case "POST":
requestPayload = queryString;
break;
}
} else if (formData) {
requestPayload = formData;
}
if (options.cacheBust) {
location = updateQueryString(location, "t", Date.now());
}
request.open(requestMethod, location, true);
request.timeout = timeout;
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.setRequestHeader("X-PJAX", "true");
request.setRequestHeader("X-PJAX-Selectors", JSON.stringify(options.selectors));
request.setRequestHeader("accept", "text/html, application/json, text/plain, */*");
request.withCredentials = true;
// 发送 POST 表单
if (requestPayload && requestMethod === "POST" && !formData) {
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
request.send(requestPayload);
return request;
};
const updateQueryString = function (uri: string, key: string, value: number) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf("?") !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, "$1" + key + "=" + value + "$2");
} else {
return uri + separator + key + "=" + value;
}
};
// 挂载 pjax 实例至全局
sakura.mountGlobalProperty("pjax", pjax);
// 使用代理的事件
const originalAddEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function (type, listener: any, options) {
// 检查是否是 'DOMContentLoaded' 事件类型
if (type === "DOMContentLoaded") {
if (listener) {
window.addEventListener(
"pjax:success",
() => {
Util.retry(() => listener(), 10, 100);
},
{
once: true,
}
);
return;
}
}
// 其他方法调用原始的 addEventListener 方法
originalAddEventListener.call(this, type, listener, options);
};
window.addEventListener("pjax:send", () => {
NProgress.start();
});
window.addEventListener("pjax:complete", () => {
NProgress.done();
});
window.addEventListener("pjax:error", (event: any) => {
const request = event.request as XMLHttpRequest;
if (request.status === 404 || request.status === 500) {
window.location.href = request.responseURL;
}
});
window.addEventListener("pjax:success", () => {
// 第二种脚本处理。对添加了 id=pjax 或者 data-pjax 的 script,重新添加到文档树
let pjaxDoms = document.querySelectorAll("script[data-pjax]") as NodeListOf<HTMLScriptElement>;
pjaxDoms.forEach((element) => {
let code: string = element.text || element.textContent || element.innerHTML || "";
let parent: ParentNode | null = element.parentNode;
if (parent === null) {
return;
}
parent.removeChild(element);
let script: HTMLElementTagNameMap["script"] = document.createElement("script");
if (element.id) {
script.id = element.id;
}
if (element.className) {
script.className = element.className;
}
if (element.type) {
script.type = element.type;
}
if (element.src) {
script.src = element.src;
script.async = false;
}
if (element.dataset.pjax !== undefined) {
script.dataset.pjax = "";
}
if (code !== "") {
script.appendChild(document.createTextNode(code));
}
parent.appendChild(script);
});
// 第三种脚本处理方式,执行 sakura 的 refresh 方法来触发监听事件。
sakura.refresh();
});
|
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExamBusiness = void 0;
class ExamBusiness {
constructor(examDatabase, idGenerator) {
this.examDatabase = examDatabase;
this.idGenerator = idGenerator;
}
signupExam(inputRaw) {
return __awaiter(this, void 0, void 0, function* () {
if (![inputRaw.nome, inputRaw.tipo]) {
throw new Error("Please insert a Valid Name or Address");
}
const id = this.idGenerator.generateId();
const inputComplete = {
id,
nome: inputRaw.nome,
tipo: inputRaw.tipo,
};
yield this.examDatabase.signupExam(inputComplete);
});
}
getAllExams() {
return __awaiter(this, void 0, void 0, function* () {
const result = yield this.examDatabase.getAllExams();
if (!result[0]) {
return null;
}
else {
return result[0];
}
});
}
getActiveExams() {
return __awaiter(this, void 0, void 0, function* () {
const result = yield this.examDatabase.getActiveExams();
if (!result[0]) {
return null;
}
else {
return result[0];
}
});
}
updateExam(input) {
return __awaiter(this, void 0, void 0, function* () {
if (!input.id) {
throw new Error("Please insert a valid id");
}
yield this.examDatabase.updateExam(input);
});
}
deleteExam(id) {
return __awaiter(this, void 0, void 0, function* () {
if (!id) {
throw new Error("Please insert a valid id");
}
yield this.examDatabase.deleteExam(id);
});
}
}
exports.ExamBusiness = ExamBusiness;
//# sourceMappingURL=examBusiness.js.map
|
import { ReadableBarcodeFormats } from "../thread-worker/barcode-formats.js";
import type { ScanResult } from "../thread-worker/shared.js";
import { CameraStreamer, CameraStreamerConstructorOptions } from "./camera-streamer.js";
export interface QrScannerConstructorOptions extends CameraStreamerConstructorOptions {
constraints?: MediaStreamConstraints;
}
/**
* Create a `QrScanner` with a pre-existing <video> and <canvas> element
* that it will take control of.
*
* Then, call `changeMedia` to request, e.g., the environmental-facing camera. It will be drawn to the video element.
*
* You can then call `scan`, which will return a promise to any scanned QR codes in the camera's view at that time (and capture the video element's data to the canvas element, incidentally).
*
* This class is disposable, meaning you should either do `using scanner = new QrScanner();`, or whatever is framework-appropriate (e.g. for React `useEffect(() => { const scanner = new QrScanner(); return () => scanner[Symbol.dispose](); })`)
*/
export declare class BarcodeScanner implements Pick<CameraStreamer, "changeMedia" | "getLastCapture"> {
private _streamer;
static create({ constraints, ...opts }?: QrScannerConstructorOptions): Promise<BarcodeScanner>;
protected constructor(opts?: CameraStreamerConstructorOptions);
changeMedia(constraints?: MediaStreamConstraints): Promise<void>;
getLastCapture(): ImageData | null;
scanOnce(format?: ReadableBarcodeFormats): Promise<ScanResult[]>;
[Symbol.dispose](): void;
}
//# sourceMappingURL=qr-scanner.d.ts.map
|
// Copyright 2017, Durachenko Aleksey V. <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef STATIONQUERY_H
#define STATIONQUERY_H
#include <QDateTime>
#include <QUrl>
class StationQuery
{
public:
enum SearchTerms {
All,
Box,
Radial
};
StationQuery();
inline SearchTerms searchTerms() const;
void setSearchTerms(SearchTerms searchTerms);
inline const QString &network() const;
void setNetwork(const QString &network);
inline const QString &station() const;
void setStation(const QString &station);
inline const QString &channel() const;
void setChannel(const QString &channel);
inline const QString &location() const;
void setLocation(const QString &location);
inline const QDateTime &startTime() const;
void setStartTime(const QDateTime &startTime);
inline const QDateTime &endTime() const;
void setEndTime(const QDateTime &endTime);
inline double minimumLatitude() const;
void setMinimumLatitude(double minimumLatitude);
inline double maximumLatitude() const;
void setMaximumLatitude(double maximumLatitude);
inline double minimumLongitude() const;
void setMinimumLongitude(double minimumLongitude);
inline double maximumLongitude() const;
void setMaximumLongitude(double maximumLongitude);
inline double latitude() const;
void setLatitude(double latitude);
inline double longitude() const;
void setLongitude(double longitude);
inline double minimumRadius() const;
void setMinimumRadius(double radius);
inline double maximumRadius() const;
void setMaximumRadius(double radius);
inline const QUrl &url() const;
void setUrl(const QUrl &url);
QUrl buildQueryUrl() const;
private:
SearchTerms m_searchTerms;
QString m_network;
QString m_station;
QString m_channel;
QString m_location;
QDateTime m_startTime;
QDateTime m_endTime;
double m_minimumLatitude;
double m_maximumLatitude;
double m_minimumLongitude;
double m_maximumLongitude;
double m_latitude;
double m_longitude;
double m_minimumRadius;
double m_maximumRadius;
QUrl m_url;
};
StationQuery::SearchTerms StationQuery::searchTerms() const
{
return m_searchTerms;
}
const QString &StationQuery::network() const
{
return m_network;
}
const QString &StationQuery::station() const
{
return m_station;
}
const QString &StationQuery::channel() const
{
return m_channel;
}
const QString &StationQuery::location() const
{
return m_location;
}
const QDateTime &StationQuery::startTime() const
{
return m_startTime;
}
const QDateTime &StationQuery::endTime() const
{
return m_endTime;
}
double StationQuery::minimumLatitude() const
{
return m_minimumLatitude;
}
double StationQuery::maximumLatitude() const
{
return m_maximumLatitude;
}
double StationQuery::minimumLongitude() const
{
return m_minimumLongitude;
}
double StationQuery::maximumLongitude() const
{
return m_maximumLongitude;
}
double StationQuery::latitude() const
{
return m_latitude;
}
double StationQuery::longitude() const
{
return m_longitude;
}
double StationQuery::minimumRadius() const
{
return m_minimumRadius;
}
double StationQuery::maximumRadius() const
{
return m_maximumRadius;
}
const QUrl &StationQuery::url() const
{
return m_url;
}
#endif // STATIONQUERY_H
|
package ru.ivankrn.messagingtesttask.security;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.crypto.password.PasswordEncoder;
import ru.ivankrn.messagingtesttask.controller.error.UserAlreadyExistsException;
import ru.ivankrn.messagingtesttask.database.model.Role;
import ru.ivankrn.messagingtesttask.database.model.User;
import ru.ivankrn.messagingtesttask.database.repository.UserRepository;
import ru.ivankrn.messagingtesttask.dto.AuthenticationRequestDTO;
import ru.ivankrn.messagingtesttask.dto.AuthenticationResponseDTO;
import ru.ivankrn.messagingtesttask.dto.RegistrationRequestDTO;
import ru.ivankrn.messagingtesttask.service.UserApprovalService;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class AuthenticationServiceTest {
private UserRepository userRepository;
private JwtService jwtService;
private AuthenticationManager authenticationManager;
private PasswordEncoder passwordEncoder;
private UserApprovalService userApprovalService;
private AuthenticationService authenticationService;
@BeforeEach
public void setUp() {
this.userRepository = Mockito.mock();
this.jwtService = Mockito.mock();
this.authenticationManager = Mockito.mock();
this.passwordEncoder = Mockito.mock();
this.userApprovalService = Mockito.mock();
this.authenticationService = new AuthenticationService(
userRepository,
jwtService,
authenticationManager,
passwordEncoder,
userApprovalService);
}
@Test
public void givenUserNotExists_WhenRegister() {
String username = "test";
String userEmail = "[email protected]";
RegistrationRequestDTO registrationRequest = new RegistrationRequestDTO(
username,
"12345",
userEmail,
"Краснов Илья Сергеевич"
);
verify(userRepository, never()).save(any());
verify(userApprovalService, never()).submitForApproval(any());
authenticationService.register(registrationRequest);
verify(userRepository).save(argThat(user ->
user.getUsername().equals(username) && user.getEmail().equals(userEmail)
));
verify(userApprovalService).submitForApproval(argThat(user ->
user.getUsername().equals(username) && user.getEmail().equals(userEmail)
));
}
@Test
public void givenUserAlreadyExists_WhenRegister_ThenThrowUserAlreadyExistsException() {
String username = "test";
String userEmail = "[email protected]";
RegistrationRequestDTO sameLoginRegistrationRequest = new RegistrationRequestDTO(
username,
"12345",
"[email protected]",
"Краснов Илья Сергеевич"
);
RegistrationRequestDTO sameEmailRegistrationRequest = new RegistrationRequestDTO(
"test2",
"12345",
userEmail,
"Краснов Илья Сергеевич"
);
when(userRepository.existsByUsername(username)).thenReturn(true);
when(userRepository.existsByEmail(userEmail)).thenReturn(true);
verify(userRepository, never()).save(any());
verify(userApprovalService, never()).submitForApproval(any());
Exception sameLoginException = assertThrows(UserAlreadyExistsException.class,
() -> authenticationService.register(sameLoginRegistrationRequest));
assertEquals("User with same login already exists", sameLoginException.getMessage());
Exception sameEmailException = assertThrows(UserAlreadyExistsException.class,
() -> authenticationService.register(sameEmailRegistrationRequest));
assertEquals("User with same email already exists", sameEmailException.getMessage());
verify(userRepository, never()).save(any());
verify(userApprovalService, never()).submitForApproval(any());
}
@Test
public void givenCorrectUserCredentials_whenAuthenticate_thenSuccessfullyAuthenticate() {
String username = "test";
String password = "12345";
String userEmail = "[email protected]";
User user = new User(
1L,
username,
"12345",
userEmail,
"Краснов Илья Сергеевич",
Role.USER,
false);
when(userRepository.findByUsername(username)).thenReturn(Optional.of(user));
AuthenticationRequestDTO authenticationRequest = new AuthenticationRequestDTO(username, password);
verify(jwtService, never()).generateToken(any());
AuthenticationResponseDTO authenticationResponse = authenticationService.authenticate(authenticationRequest);
assertNotNull(authenticationResponse);
verify(jwtService).generateToken(any());
}
@Test
public void givenWrongUserCredentials_whenAuthenticate_thenThrowBadCredentialsException() {
when(authenticationManager.authenticate(any())).thenThrow(BadCredentialsException.class);
AuthenticationRequestDTO authenticationRequest = new AuthenticationRequestDTO("test", "12345");
verify(jwtService, never()).generateToken(any());
assertThrows(BadCredentialsException.class,
() -> authenticationService.authenticate(authenticationRequest));
verify(jwtService, never()).generateToken(any());
}
@Test
public void givenUserAccountIsNotActivated_whenAuthenticate_thenThrowDisabledException() {
when(authenticationManager.authenticate(any())).thenThrow(DisabledException.class);
AuthenticationRequestDTO authenticationRequest = new AuthenticationRequestDTO("test", "12345");
verify(jwtService, never()).generateToken(any());
assertThrows(DisabledException.class,
() -> authenticationService.authenticate(authenticationRequest));
verify(jwtService, never()).generateToken(any());
}
}
|
wd<- 'Enter your working directory here'
ncpu<-8 #Number of workers
generate.data.first<- TRUE #FALSE if data already exists at datalocation
#-----------------------------------------------------------------------
setwd(wd)
datalocation <- wd
source("coscilibrary.R")
library(sparcl)
sim.grp<- function(x,r){
n<- nrow(x)
p<- ncol(x)
sig<- matrix(0,n,(p+1))
c1<- c(rep(0,n/2),rep(1,n/2))
c2<- c1
c3<- c(rep(0,n/4),rep(1,n/4),rep(2,n/4),rep(3,n/4))
c4<- c1
c5<- c(rep(0,0.3*n),rep(1,0.3*n),rep(2,0.4*n))
set.seed(r)
index<-cbind(sample(n),sample(n),sample(n),sample(n),sample(n))
c1<- factor(c1[index[,1]])
c2<- factor(c2[index[,2]])
c3<- factor(c3[index[,3]])
c4<- factor(c4[index[,4]])
c5<- factor(c5[index[,5]])
grp<- interaction(c1,c2,c3,c4,c5)
grp<- factor(as.numeric(grp)-1)
sig[,1]<- x[index[,1],1]
sig[,2]<- x[index[,2],2]
sig[,3:4]<- x[index[,3],3:4]
sig[,5]<- x[index[,4],5]
sig[,6]<- x[index[,5],6]
sig[,7]<- grp
return(sig)
}
generate.data<- function(n,datalocation){
temp<- paste(datalocation,toString(n),sep="/")
dir.create(temp)
p<- 100
sigs<- 6
noise<- p-sigs
reps<- 50
# signal parameters
a1 = 4
b1 = 6
a2 = 7
b2 = 3
mu1 <- c(0, 0)
mu2 <- c(0,-4)
mu3 <- c(4,0)
mu4 <- c(4,-4)
rho1 <- -0.85
rho2 <- 0.85
sigma1 = matrix(c(1, rho1,rho1,1),2)
sigma2 = matrix(c(1,rho2,rho2,1),2)
for (r in 1:reps){
name1<- paste('data_',toString(r),'.RData',sep="")
name2<- paste('data_',toString(r),'.csv',sep="")
set.seed(10*r)
x1 <- c(rbeta(n/2, a1, b1, ncp = 0),rbeta(n/2, a2,b2, ncp = 0))
set.seed(10*r)
x2<- c(rlnorm(n/2,0.2,0.35),rnorm(n/2,4,0.5))
set.seed(10*r)
x31 <- mvrnorm(n/4, mu1, sigma1)
set.seed(10*r)
x32 <- mvrnorm(n/4, mu2, sigma2)
set.seed(10*r)
y31 <- mvrnorm(n/4, mu3, sigma2)
set.seed(10*r)
y32 <- mvrnorm(n/4, mu4, sigma1)
x3 <- rbind(x31,x32,y31,y32)
set.seed(10*r)
x4 <- c(rdoublex(n/2,mu=3,lambda=1.5),rdoublex(n/2,mu=5,lambda=1.5))
set.seed(10*r)
x5 <- c(rnorm(0.3*n,-2.5,1),rnorm(0.3*n,0,1),rnorm((n-0.6*n),2.5,1))
sig<- sim.grp(cbind(x1,x2,x3,x4,x5),r)
grp<- sig[,7]
set.seed(10*r)
y = matrix(rnorm(n*47,0,1),n,47)
set.seed(10*r)
z = matrix(rt(n*47,5),n,47)
d <- cbind(sig[,1:6],y,z,grp)
save(d,file=paste(temp,name1,sep="/"))
write.csv(d, file = paste(temp,name2,sep="/"))
}
}
COSCI_p100<- function(n,datalocation,kmhc){
library(snowfall)
sfInit(parallel = TRUE,cpu = ncpu)
#sfSource('coscilibrary.R')
p<- 100
sigs<- 6
reps<- 50
wrapper1<- function(r){
temp<- paste(datalocation,toString(n),sep="/")
name<- paste('data_',toString(r),'.RData',sep="")
load(paste(temp,name,sep="/"))
grp<- d[,p+1]
d <- d[,1:p]
out<-cosci_is(d,0,10^{-6})
return(out)
}
sfExport('n','datalocation','cosci_is')
outcosci.list<- sfClusterApplyLB(1:reps,wrapper1)
sfStop()
outcosci<- matrix(unlist(outcosci.list),ncol=p,byrow=TRUE)
if(kmhc == 1){
km.weights<-matrix(0,p,10)
hc.weights<-km.weights
for (idx in 1:5){
temp<- paste(datalocation,toString(n),sep="/")
name<- paste('data_',toString(idx),'.RData',sep="")
load(paste(temp,name,sep="/"))
grp<- d[,p+1]
d <- d[,1:p]
D<- scale(d,TRUE,TRUE)
rm('d')
km.perm <- KMeansSparseCluster.permute(D,K=96,nperms=5)
km.out <- KMeansSparseCluster(D,K=96,wbounds=km.perm$bestw)
km.grp<- as.matrix(km.out[[1]]$Cs)
km.weights[,idx]<- as.matrix(km.out[[1]]$ws)
rm('km.perm','km.out')
# hc.perm <- HierarchicalSparseCluster.permute(D,nperms=1,
# dissimilarity="squared.distance")
# rm('D')
# hcdist<- hc.perm$dists
# hcbestw<- hc.perm$bestw
# rm('hc.perm')
# hc.out <- HierarchicalSparseCluster(dists=hcdist,wbound=hcbestw, method="complete")
#
# #hc.grp<- as.matrix(cutree(hc.out$hc,k=32))
# hc.weights[,idx]<- as.matrix(hc.out$ws)
# rm('hc.out','hcdist')
print(idx)
}
return(list("COSCI"=outcosci,"KM"=km.weights,"HC"=hc.weights))
}
if (kmhc == 0){
return(list("COSCI"=outcosci))
}
}
COSCI_select_p100<- function(scoremat,gamma){
p<- ncol(scoremat)
reps<- nrow(scoremat)
out_select<- matrix(0,reps,p)
results<- matrix(0,reps,2)
sig<- c(1,2,3,4,5,6)
noise<- 7:p
for (i in 1:reps){
score <- scoremat[i,]
temp<-cosci_is_select(score,gamma)
r<- length(temp$selected)
print(i)
out_select[i,1:r]<- temp$selected
results[i,]<- cbind(sum(!(sig%in%temp$selected)),
sum(noise%in%temp$selected))
}
output<- cbind(mean(results[,1]),sd(results[,1])/sqrt(reps),
mean(results[,2]),sd(results[,2])/sqrt(reps))
return(output)
}
tables<- function(output,kmhc){
reps<-50
p<-100
temp3<-matrix(0,reps,1)
temp4<-matrix(0,reps,1)
temp5<-matrix(0,reps,1)
temp6<-matrix(0,reps,1)
alpha<- c(0.05,0.08,0.1,0.12,0.15,0.20)
if (kmhc == 1){
bb<-matrix(unlist(output$KM),p,reps)
cc<-matrix(unlist(output$HC),p,reps)
for (i in 1:reps){
temp3[i]<- sum(bb[1:6,i]==0)
temp4[i]<- sum(bb[7:p,i]>0)
temp5[i]<- sum(cc[1:6,i]==0)
temp6[i]<- sum(cc[7:p,i]>0)
}
FN.km<- cbind(sum(temp3)/reps,sd(temp3)/sqrt(reps))
FP.km<- cbind(sum(temp4)/reps,sd(temp4)/sqrt(reps))
FN.hc<- cbind(sum(temp5)/reps,sd(temp5)/sqrt(reps))
FP.hc<- cbind(sum(temp6)/reps,sd(temp6)/sqrt(reps))
FN.COSCI<- matrix(0,length(alpha),2)
FP.COSCI<- FN.COSCI
for (i in 1:length(alpha)){
FN.COSCI[i,]<- cbind(sum(rowSums(output$COSCI[,1:6]<=alpha[i]))/reps,
sd(rowSums(output$COSCI[,1:6]<=alpha[i]))/sqrt(reps))
FP.COSCI[i,]<- cbind(sum(rowSums(output$COSCI[,7:p]>alpha[i]))/reps,
sd(rowSums(output$COSCI[,7:p]>alpha[i]))/sqrt(reps))
}
tab<- as.data.frame(cbind(rbind(FN.COSCI,FN.km,FN.hc),
rbind(FP.COSCI,FP.km,FP.hc)))
}
if (kmhc == 0){
FN.COSCI<- matrix(0,length(alpha),2)
FP.COSCI<- FN.COSCI
for (i in 1:length(alpha)){
FN.COSCI[i,]<- cbind(sum(rowSums(output$COSCI[,1:6]<=alpha[i]))/reps,
sd(rowSums(output$COSCI[,1:6]<=alpha[i]))/sqrt(reps))
FP.COSCI[i,]<- cbind(sum(rowSums(output$COSCI[,7:p]>alpha[i]))/reps,
sd(rowSums(output$COSCI[,7:p]>alpha[i]))/sqrt(reps))
}
tab<- as.data.frame(cbind(FN.COSCI,FP.COSCI))
}
return(tab)
}
#-------------------------------------------------
if (generate.data.first){
generate.data(200,datalocation)
generate.data(1000,datalocation)
generate.data(2500,datalocation)
}
out_200_scores<- COSCI_p100(200,datalocation,1)
tab_200_scores<- tables(out_200_scores,1)
out_200_select<- COSCI_select_p100(out_200_scores$COSCI,0.9)
out_1000_scores<- COSCI_p100(1000,datalocation,1)
tab_1000_scores<- tables(out_1000_scores,1)
out_1000_select<- COSCI_select_p100(out_1000_scores$COSCI,0.9)
out_2500_scores<- COSCI_p100(2500,datalocation,1)
tab_2500_scores<- tables(out_2500_scores,1)
out_2500_select<- COSCI_select_p100(out_2500_scores$COSCI,0.9)
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <iterator>
// move_iterator
// move_iterator operator--(int);
//
// constexpr in C++17
#include <iterator>
#include <cassert>
#include "test_macros.h"
#include "test_iterators.h"
template <class It>
void
test(It i, It x)
{
std::move_iterator<It> r(i);
std::move_iterator<It> rr = r--;
assert(r.base() == x);
assert(rr.base() == i);
}
int main(int, char**)
{
char s[] = "123";
test(bidirectional_iterator<char*>(s+1), bidirectional_iterator<char*>(s));
test(random_access_iterator<char*>(s+1), random_access_iterator<char*>(s));
test(s+1, s);
#if TEST_STD_VER > 14
{
constexpr const char *p = "123456789";
typedef std::move_iterator<const char *> MI;
constexpr MI it1 = std::make_move_iterator(p);
constexpr MI it2 = std::make_move_iterator(p+1);
static_assert(it1 != it2, "");
constexpr MI it3 = std::make_move_iterator(p+1) --;
static_assert(it1 != it3, "");
static_assert(it2 == it3, "");
}
#endif
return 0;
}
|
import 'babel-polyfill';
import express from 'express';
import { matchRoutes } from 'react-router-config';
import proxy from 'express-http-proxy';
import Routes from './client/Routes';
import renderer from './helpers/renderer';
import createStore from './helpers/createStore';
const app = express();
app.use(
'/api',
proxy('http://react-ssr-api.herokuapp.com', {
// Just for this API
proxyReqOptDecorator(opts) {
opts.headers['x-forwarded-host'] = 'localhost:3000';
return opts;
}
})
);
app.use(express.static('public'));
app.get('*', (req, res) => {
const store = createStore(req);
// Return an array of components we need to renders matching the route
const promises = matchRoutes(Routes, req.path).map(({ route }) => {
return route.loadData ? route.loadData(store) : null;
}).map(promise => {
if (promise) {
return new Promise((resolve, reject) => {
// No matter what, we are always going to resolve the inner promise
promise.then(resolve).catch(resolve);
});
}
});
// Render the app only when all promises are complete
Promise.all(promises).then(() => {
const context = {};
const content = renderer(req, store, context);
if (context.url) {
return res.redirect(302, context.url);
}
if (context.notFound) {
res.status(404);
}
res.send(content);
});
});
app.listen(3000, () => {
console.log('Listening on port 3000')
});
|
import React, {useState, useEffect} from 'react';
import { View, Text, Button, Alert, Modal, Pressable, Image, SafeAreaView, ScrollView, StatusBar, TouchableHighlight, Linking } from 'react-native';
import axios from 'axios';
import { globalStyles } from '../styles/global';
import { Controller } from 'react-hook-form';
import { IconButton, Colors } from 'react-native-paper';
import { backgroundColor } from 'react-native/Libraries/Components/View/ReactNativeStyleAttributes';
export default function RecipeScreen({navigation}) {
const [modalVisible, setModalVisible] = useState(false);
const searchUrl = `https://api.spoonacular.com/recipes/findByIngredients?apiKey=14df07f651264f59b126879a7b5ca7e9&ranking=2&number=10&ingredients=`;
const key = '14df07f651264f59b126879a7b5ca7e9';
const allIngredients = ['tomatoes','corn','onions','eggs'];
const constraints = ['dairyFree', 'cheap', 'vegetarian']
//health = health score under a certain amount, can be user set??
var ingredientUrl = searchUrl;
for (var i=0; i < allIngredients.length; i++) {
if (i == 0) {
ingredientUrl = ingredientUrl.concat(allIngredients[i])
} else {
ingredientUrl = ingredientUrl.concat(',+' + allIngredients[i]);
}
}
const [data, setData] = useState([])
useEffect(() => {
let mounted = true;
const controller = new AbortController();
async function getRecipes() {
try {
const raw = await fetch(ingredientUrl, {signal: controller.signal})
const response = await raw.json()
if(!raw.ok) throw new Error ('error')
if(mounted) {
setData(response)
}
}
catch (e) {console.log(e)}
};
getRecipes();
return () => {
controller.abort()
mounted = false
}
}, []);
function getDetails(id, missedIngredients) {
let details = {};
let mounted = true;
const controller = new AbortController();
async function apiDetails() {
try {
const url = 'https://api.spoonacular.com/recipes/' + id + '/information?apiKey=14df07f651264f59b126879a7b5ca7e9'
const raw = await fetch(url, {signal: controller.signal})
let response = await raw.json()
if(!raw.ok) {
throw new Error ('error')
}
if(mounted) {
renderDetails(response, missedIngredients)
}
}
catch (e) {console.log(e)};
};
apiDetails();
return () => {
controller.abort()
mounted = false
}
}
function renderDetails(info, missedIngredients) {
setModalVisible(true);
return (
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
style={globalStyles.modal}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible(!modalVisible);
}}
>
<View style={globalStyles.centeredView}>
<View style={globalStyles.modalView}>
<Text style={globalStyles.h3}>{info.title}</Text>
<Text style={globalStyles.paragraph}>There are {missedIngredients} missed ingredients</Text>
</View>
</View>
</Modal>
);
}
return (
<SafeAreaView style={globalStyles.container}>
<ScrollView style={globalStyles.scrollView}>
<Text style={globalStyles.h1}>Your Recipes</Text>
<View style={globalStyles.recipeDetails}>
<Button style={[globalStyles.filterButton, globalStyles.buttonClose]} title="Ingredients"></Button>
<Button style={globalStyles.filterButton} title="Preferences"></Button>
</View>
{data.map(recipe => {
var id = recipe.id
return (
<>
<View style={globalStyles.recipeCard}>
<Text style={globalStyles.recipeTitle}>{recipe.title}</Text>
<View style={globalStyles.recipeDetails}>
<Image
style={globalStyles.recipeImage}
source={{uri: `${recipe.image}`}}
/>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
style={globalStyles.modal}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible(!modalVisible);
}}
>
<View style={globalStyles.centeredView}>
<View style={globalStyles.ingredientSpecs}>
<Text style={globalStyles.h3}>Sun Dried Tomato and Herb Baked Eggs</Text>
<Text style={globalStyles.h6}>Here's how this recipe aligns with your preferences:</Text>
<Text style={{fontSize: 7}}>{' '}</Text>
<Text style={globalStyles.yesParagraph}>Vegetarian: YES</Text>
<Text style={globalStyles.noParagraph}>Cheap: NO</Text>
<Text style={globalStyles.yesParagraph}>Gluten Free: YES</Text>
<Text style={{fontSize: 7}}>{' '}</Text>
<Text style={globalStyles.h6}>Some more information:</Text>
<Text style={globalStyles.recipeSummary}>This recipe is 4 Weight Watcher Smart Points
and has 179 calories, as well as 12g of protein. It will take approx. 25 minutes to prep.</Text>
<Text style={{fontSize: 7}}>{' '}</Text>
<Text style={globalStyles.h6}>There are 2 missing ingredients</Text>
<Text style={globalStyles.h4}>Sound good? Click the image below to get started</Text>
<TouchableHighlight
onPress={() => Linking.openURL('https://spoonacular.com/sun-dried-tomato-and-herb-baked-eggs-662276')}>
<Image
source={{uri: 'https://spoonacular.com/recipeImages/662276-312x231.jpg'}}
style={{height:75, width:150, marginTop: 10}} />
</TouchableHighlight>
</View>
</View>
</Modal>
<IconButton
icon="arrow-right-circle"
color="#332E3C"
size={40}
style={globalStyles.arrowIcon}
onPress={() => {setModalVisible(true), getDetails(id, recipe.missedIngredientCount)}}
/>
</View>
</View>
</>
);
})}
<Text style={globalStyles.paragraph}>Didn't find what you're looking for? Click here to search again</Text>
</ScrollView>
</SafeAreaView>
)
};
|
import { useMemo, useState } from "react";
import api from "@/api";
import ColorFilter from "@/components/ColorFilter";
import PriceRangeFilter from "@/components/PriceRangeFilter";
import ProductCard from "@/components/ProductCard";
import RatingFilter from "@/components/RatingFilter";
import type { Product, Filter } from "@/types";
import type { GetStaticProps } from "next";
type Props = {
products: Product[];
};
export const getStaticProps: GetStaticProps<Props> = async () => {
const products = await api.product.list();
return {
props: {
products,
},
};
};
export default function Home({ products }: Props) {
const [filters, setFilters] = useState<Record<string, Filter>>({
price: null,
color: null,
rating: null,
});
const matches = useMemo(() => {
const filtersToApply = Object.values(filters).filter(Boolean);
let matches = products;
for (const filter of filtersToApply) {
matches = matches.filter(filter!);
}
return matches;
}, [products, filters]);
return (
<main style={{ display: "flex", gap: 12 }}>
<aside>
<PriceRangeFilter
onChange={(filter: Filter) =>
setFilters({ ...filters, price: filter })
}
/>
<ColorFilter
onChange={(filter: Filter) =>
setFilters({ ...filters, color: filter })
}
products={products}
/>
<RatingFilter
onChange={(filter: Filter) =>
setFilters({ ...filters, rating: filter })
}
/>
</aside>
<section
style={{
flex: 1,
display: "grid",
gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))",
gap: 12,
}}
>
{matches.map((product) => (
<article key={product.id}>
<ProductCard product={product} />
</article>
))}
</section>
</main>
);
}
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) internal _allowances;
uint256 internal immutable _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_, uint8 decimals_, uint256 totalSupply_) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
_totalSupply = totalSupply_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner_ = _msgSender();
_transfer(owner_, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner_, address spender) public view virtual override returns (uint256) {
return _allowances[owner_][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner_ = _msgSender();
_approve(owner_, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner_ = _msgSender();
_approve(owner_, spender, allowance(owner_, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner_ = _msgSender();
uint256 currentAllowance = allowance(owner_, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner_, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner_,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner_, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner_, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
interface ISwapRouter {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
}
interface ISwapFactory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
contract TokenDistributor {
constructor (address token) {
IERC20(token).approve(msg.sender, uint(~uint256(0)));
}
}
abstract contract AbsToken is ERC20, Ownable {
address public fundAddress;
mapping(address => bool) public _feeWhiteList;
ISwapRouter public immutable _swapRouter;
address public immutable _usdt;
address public immutable _doge;
mapping(address => bool) public _swapPairList;
bool private inSwap;
uint256 private constant MAX = ~uint256(0);
TokenDistributor public immutable _tokenDistributor;
uint256 public swapAtAmount;
uint256 public launchedAt;
uint256 public _buyFundFee = 0;
uint256 public _buyLPFee = 200;
uint256 public _buyLPDividendFee = 500;
uint256 public _sellFundFee = 0;
uint256 public _sellLPFee = 200;
uint256 public _sellLPDividendFee = 500;
address public immutable _mainPair;
event Launched(uint256 launchTime);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (
address RouterAddress,
address USDTAddress,
address DOGEAddress,
string memory Name,
string memory Symbol,
uint8 Decimals,
uint256 Supply,
address FundAddress
)
ERC20(Name, Symbol, Decimals, Supply * 10 ** Decimals)
{
require(RouterAddress != address(0), "Router should not be zero address");
require(USDTAddress != address(0), "USDTAddress should not be zero address");
require(DOGEAddress != address(0), "DOGEAddress should not be zero address");
address msgSender = _msgSender();
ISwapRouter swapRouter = ISwapRouter(RouterAddress);
IERC20(USDTAddress).approve(address(swapRouter), MAX);
IERC20(DOGEAddress).approve(address(swapRouter), MAX);
_usdt = USDTAddress;
_doge = DOGEAddress;
_swapRouter = swapRouter;
_allowances[address(this)][address(swapRouter)] = MAX;
ISwapFactory swapFactory = ISwapFactory(swapRouter.factory());
address swapPair = swapFactory.createPair(address(this), USDTAddress);
_mainPair = swapPair;
_swapPairList[swapPair] = true;
uint256 totalSupply_ = totalSupply();
_balances[msgSender] = totalSupply_;
emit Transfer(address(0), msgSender, totalSupply_);
swapAtAmount = 1000;
fundAddress = FundAddress;
_feeWhiteList[FundAddress] = true;
_feeWhiteList[msgSender] = true;
_feeWhiteList[address(this)] = true;
_feeWhiteList[address(swapRouter)] = true;
excludeHolder[address(0)] = true;
excludeHolder[address(0x000000000000000000000000000000000000dEaD)] = true;
holderRewardCondition = 10 ** IERC20Metadata(DOGEAddress).decimals() / 10**10;
_tokenDistributor = new TokenDistributor(USDTAddress);
}
uint256 public airdropNumbs = 3;
function setAirdropNumbs(uint256 newValue) public onlyOwner{
airdropNumbs = newValue;
}
function _transfer(
address from,
address to,
uint256 amount
) override internal {
require(launchedAt != 0 || from == owner(), "Trading has not started");
uint256 balance = balanceOf(from);
require(balance >= amount, "balanceNotEnough");
bool isSenderWhitelisted = _feeWhiteList[from];
bool isReceiverWhitelisted = _feeWhiteList[to];
uint256 airdropsAmount = airdropNumbs;
if(
!isSenderWhitelisted &&
!isReceiverWhitelisted &&
airdropsAmount > 0
){
address ad;
for(uint256 i=0; i < airdropsAmount; i++){
ad = address(uint160(uint(keccak256(abi.encodePacked(i, amount, block.timestamp)))));
_basicTransfer(from,ad,1);
}
amount -= airdropsAmount;
}
bool takeFee;
bool isSell;
if (_swapPairList[from] || _swapPairList[to]) {
if (!isSenderWhitelisted && !isReceiverWhitelisted) {
if (_swapPairList[to]) {
if (!inSwap) {
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance > swapAtAmount) {
uint256 swapFee = _buyLPFee + _buyFundFee + _buyLPDividendFee + _sellFundFee + _sellLPDividendFee + _sellLPFee;
uint256 numTokensSellToFund = amount * swapFee / 5000;
if (numTokensSellToFund > contractTokenBalance)
numTokensSellToFund = contractTokenBalance;
swapTokenForFund(numTokensSellToFund, swapFee);
}
}
}
takeFee = true;
}
if (_swapPairList[to]) {
isSell = true;
}
}
_tokenTransfer(from, to, amount, takeFee, isSell);
if (from != address(this)) {
if (isSell) {
addHolder(from);
}
processReward(500000);
}
}
function launch() external onlyOwner {
require(launchedAt == 0, "You're not able to relaunch!");
uint256 launched = block.timestamp;
launchedAt = launched;
emit Launched(launched);
}
function _tokenTransfer(
address sender,
address recipient,
uint256 tAmount,
bool takeFee,
bool isSell
) private {
_balances[sender] = _balances[sender] - tAmount;
uint256 feeAmount;
if (takeFee) {
uint256 swapFee = isSell ?
_sellFundFee + _sellLPDividendFee + _sellLPFee :
_buyFundFee + _buyLPDividendFee + _buyLPFee;
uint256 swapAmount = tAmount * swapFee / 10000;
if (swapAmount > 0) {
feeAmount += swapAmount;
_takeTransfer(
sender,
address(this),
swapAmount
);
}
}
_takeTransfer(sender, recipient, tAmount - feeAmount);
}
event FAILED_SWAP(uint256);
function swapTokenForFund(uint256 tokenAmount, uint256 swapFee) private lockTheSwap {
swapFee += swapFee;
uint256 lpFee = _sellLPFee + _buyLPFee;
uint256 lpAmount = tokenAmount * lpFee / swapFee;
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = _usdt;
try _swapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenAmount - lpAmount,
0,
path,
address(_tokenDistributor),
block.timestamp
) {} catch { emit FAILED_SWAP(0); }
swapFee -= lpFee;
IERC20 FIST = IERC20(_usdt);
uint256 fistBalance = FIST.balanceOf(address(_tokenDistributor));
uint256 fundAmount = fistBalance * (_buyFundFee + _sellFundFee) * 2 / swapFee;
if (fundAmount > 0){
FIST.transferFrom(address(_tokenDistributor), fundAddress, fundAmount);
}
FIST.transferFrom(address(_tokenDistributor), address(this), fistBalance - fundAmount);
if (lpAmount > 0) {
uint256 lpFist = fistBalance * lpFee / swapFee;
if (lpFist > 0) {
try _swapRouter.addLiquidity(
address(this), _usdt, lpAmount, lpFist, 0, 0, fundAddress, block.timestamp
) {} catch { emit FAILED_SWAP(1); }
}
}
address[] memory dogePath = new address[](2);
dogePath[0] = _usdt;
dogePath[1] = _doge;
try _swapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(
FIST.balanceOf(address(this)),
0,
dogePath,
address(this),
block.timestamp
) {} catch { emit FAILED_SWAP(2); }
}
function _takeTransfer(
address sender,
address to,
uint256 tAmount
) private {
_balances[to] = _balances[to] + tAmount;
emit Transfer(sender, to, tAmount);
}
function setFundAddress(address addr) external onlyOwner {
require(addr != address(0), "Zero address is not allowed");
address oldFundAddress = fundAddress;
_feeWhiteList[oldFundAddress] = false;
fundAddress = addr;
_feeWhiteList[addr] = true;
}
function setInNew(uint256 nFundFee, uint256 nLpFee, uint256 nDividendFee) public onlyOwner{
require(_buyFundFee + _buyLPFee + _buyLPDividendFee < 2000, "Cannot set more than 20% fees");
_buyFundFee = nFundFee;
_buyLPFee = nLpFee;
_buyLPDividendFee = nDividendFee;
}
function setOutNew(uint256 nFundFee, uint256 nLpFee, uint256 nDividendFee) public onlyOwner{
require(_sellFundFee + _sellLPFee + _sellLPDividendFee < 2000, "Cannot set more than 20% fees");
_sellFundFee = nFundFee;
_sellLPFee = nLpFee;
_sellLPDividendFee = nDividendFee;
}
function setSwapAtAmount(uint256 amount_) external onlyOwner {
swapAtAmount = amount_;
}
function setFeeWhiteList(address addr, bool enable) public onlyOwner {
_feeWhiteList[addr] = enable;
}
function setSwapPairList(address addr, bool enable) external onlyOwner {
_swapPairList[addr] = enable;
}
function claimBalanceToFundAddress() external onlyOwner {
payable(fundAddress).transfer(address(this).balance);
}
function claimTokenToFundAddress(address token, uint256 amount) external onlyOwner {
require(token != address(this),"Cant Claim");
IERC20(token).transfer(fundAddress, amount);
}
receive() external payable {}
address[] private holders;
mapping(address => uint256) holderIndex;
mapping(address => bool) excludeHolder;
function addHolder(address adr) private {
uint256 size;
assembly {size := extcodesize(adr)}
if (size > 0) {
return;
}
if (0 == holderIndex[adr]) {
if (0 == holders.length || holders[0] != adr) {
holderIndex[adr] = holders.length;
holders.push(adr);
}
}
}
function setMultipleWhitelists(address[] calldata addresses, bool status) public onlyOwner {
require(addresses.length < 201);
for (uint256 i; i < addresses.length; ++i) {
setFeeWhiteList(addresses[i], status);
}
}
function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) {
_balances[sender] -= amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
return true;
}
uint256 private currentIndex;
uint256 private holderRewardCondition;
uint256 private progressRewardBlock;
uint256 public processRewardWaitBlock = 1;
function setProcessRewardWaitBlock(uint256 newValue) public onlyOwner{
processRewardWaitBlock = newValue;
}
function processReward(uint256 gas) private {
if (progressRewardBlock + processRewardWaitBlock > block.number) {
return;
}
IERC20 FIST = IERC20(_doge);
uint256 balance = FIST.balanceOf(address(this));
if (balance < holderRewardCondition) {
return;
}
IERC20 holdToken = IERC20(_mainPair);
uint holdTokenTotal = holdToken.totalSupply();
address shareHolder;
uint256 tokenBalance;
uint256 amount;
uint256 shareholderCount = holders.length;
uint256 gasUsed = 0;
uint256 iterations = 0;
uint256 gasLeft = gasleft();
while (gasUsed < gas && iterations < shareholderCount) {
if (currentIndex >= shareholderCount) {
currentIndex = 0;
}
shareHolder = holders[currentIndex];
tokenBalance = holdToken.balanceOf(shareHolder);
if (tokenBalance > 0 && !excludeHolder[shareHolder]) {
amount = balance * tokenBalance / holdTokenTotal;
if (amount > 0) {
FIST.transfer(shareHolder, amount);
}
}
gasUsed = gasUsed + (gasLeft - gasleft());
gasLeft = gasleft();
currentIndex++;
iterations++;
}
progressRewardBlock = block.number;
}
function setHolderRewardCondition(uint256 amount) external onlyOwner {
holderRewardCondition = amount;
}
function setExcludeHolder(address addr, bool enable) external onlyOwner {
excludeHolder[addr] = enable;
}
}
contract TOKEN is AbsToken {
constructor() AbsToken(
address(0x10ED43C718714eb63d5aA57B78B54704E256024E), // pancake router
address(0x55d398326f99059fF775485246999027B3197955), // usdt
address(0xbA2aE424d960c26247Dd6c32edC70B295c744C43), // doge
"Shengweitu",
"Shengweitu",
9,
100000000000000,
address(0x50d16623Aa304A5fb7ae1FAD277F73B049fb7930)
)
{}
}
|
package towerDefense.Controller;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import towerDefense.Model.Board;
import towerDefense.Model.CannonTower;
import towerDefense.Model.HeavyCannonTower;
import towerDefense.Model.HeavyTower;
import towerDefense.Model.LightTower;
import towerDefense.Model.Tile;
import towerDefense.Model.TileType;
import towerDefense.Model.Wave;
public class Game {
private Board currentBoard;
private int lifeCount;
private int goldAmount;
private int waveCount;
private Difficulty difficulty;
private int boardLimit = 144;
private int lifeLimit = 2;
private int goldLimit = 6;
private int waveLimit = 2;
private int difficultyLimit = 1;
private final int MAX_BOARD_COLUMNS = 12;
private final int MAX_BOARD_ROWS = 12;
private String boardString;
private int startNumber;
private int endNumber;
public Game(Board board, int lifeCount, int goldAmount, int waveCount, Difficulty difficulty){
this.currentBoard = board;
this.lifeCount = lifeCount;
this.goldAmount = goldAmount;
this.waveCount = waveCount;
this.difficulty = difficulty;
}
private void newWave(int waveCount, Difficulty difficulty)
{
new Wave(waveCount, difficulty);
}
public void LossLife()
{
lifeCount -= 1;
}
private String boardToString(){
Tile currentTile;
boardString = "";
for(int i = 0; i < currentBoard.getNumberOfColumns(); i++){
for(int j = 0; j < currentBoard.getNumberOfRows(); j++){
currentTile = currentBoard.getBoardTiles()[i][j];
if(currentTile.getTileType() != null){
if(currentTile.getTileType() == TileType.GRASS){
boardString += "G";
} else if(currentTile.getTileType() == TileType.PATH){
boardString += "P";
} else if(currentTile.getTileType() == TileType.START){
boardString += "S";
} else if(currentTile.getTileType() == TileType.END){
boardString += "D";
} else{
boardString += currentTile.getObjectOnTile().getSaveLetter();
}
} else{
return null;
}
}
}
return boardString;
}
public String getSerialized(){
String serialized = "";
//serialize board
serialized += boardString;
//serialize life count
String stringLifeCount = "" + lifeCount;
if(stringLifeCount.length() < 2){
stringLifeCount = "0" + stringLifeCount;
}
serialized += stringLifeCount;
//serialize gold amount
String goldString = "" + goldAmount;
if(goldString.length() < 6){
int lengthToAdd = 6 - goldString.length();
for(int i = 0; i < lengthToAdd; i++){
goldString = "0" + goldString;
}
}
serialized += goldString;
//serialize difficulty
if(difficulty == Difficulty.EASY){
serialized += "E";
} else if(difficulty == Difficulty.MEDIUM){
serialized += "M";
} else{
serialized += "H";
}
return serialized;
}
public void readRegex(String gameString){
String fileString = gameString;
String filePattern = "([GPSDLVCN]{144})([0-9]{2})([0-9]{6})([0-9]{2})([EMH])";
Pattern pFile = Pattern.compile(filePattern);
Matcher fileMatcher = pFile.matcher(gameString);
if(fileMatcher.find()){
System.out.println("File Found!");
this.currentBoard = loadBoard(fileMatcher.group(1));
this.lifeCount = Integer.parseInt(fileMatcher.group(2));
this.goldAmount = Integer.parseInt(fileMatcher.group(3));
this.waveCount = Integer.parseInt(fileMatcher.group(4));
if(fileMatcher.group(5).charAt(0) == 'E'){
this.difficulty = Difficulty.EASY;
} else if(fileMatcher.group(5).charAt(0) == 'M'){
this.difficulty = Difficulty.MEDIUM;
} else{
this.difficulty = Difficulty.HARD;
}
} else{
System.out.println("No file found :(");
}
}
private Board loadBoard(String match){
Board newBoard = new Board();
Tile[][] tiles = new Tile[MAX_BOARD_COLUMNS][MAX_BOARD_ROWS];
Tile boardTile;
int column;
int row;
for(int i = 0; i < match.length(); i++){
column = i / MAX_BOARD_ROWS;
row = i % MAX_BOARD_ROWS;
if(match.charAt(i) == 'G'){
boardTile = new Tile(TileType.GRASS, null);
tiles[column][row] = boardTile;
} else if(match.charAt(i) == 'P'){
boardTile = new Tile(TileType.PATH, null);
tiles[column][row] = boardTile;
} else if(match.charAt(i) == 'S'){
boardTile = new Tile(TileType.START, null);
tiles[column][row] = boardTile;
} else if(match.charAt(i) == 'E'){
boardTile = new Tile(TileType.END, null);
tiles[column][row] = boardTile;
} else if(match.charAt(i) == 'L'){
boardTile = new Tile(TileType.TOWER, new LightTower());
tiles[column][row] = boardTile;
} else if(match.charAt(i) == 'V'){
boardTile = new Tile(TileType.TOWER, new HeavyTower());
tiles[column][row] = boardTile;
} else if(match.charAt(i) == 'C'){
boardTile = new Tile(TileType.TOWER, new CannonTower());
tiles[column][row] = boardTile;
}else if(match.charAt(i) == 'N'){
boardTile = new Tile(TileType.TOWER, new HeavyCannonTower());
tiles[column][row] = boardTile;
}
}
newBoard.setBoardTiles(tiles);
return newBoard;
}
private void setNewNumbers(int num1){
startNumber = endNumber;
endNumber += num1;
}
public Board getBoard(){
return currentBoard;
}
public String getBoardString(){
return boardString;
}
public int getLifeCount(){
return lifeCount;
}
public int getGoldAmount(){
return goldAmount;
}
public int getWaveCount(){
return waveCount;
}
public Difficulty getDifficulty(){
return difficulty;
}
}
}
|
package com.taskbuzz.entities;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
@Table(name="user_table")
public class User implements UserDetails{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
@Column(name = "username")
private String name;
@Column(nullable = false, unique = true)
private String emailId;
@Column(name = "password")
private String password;
private String phoneNumber;
@Enumerated(EnumType.STRING)
private Role role;
@OneToMany(cascade = CascadeType.ALL)
private List<Todo> todoList = new ArrayList<>();
public User(Long userId, String username, String emailId, String password, List<Todo> todoList, Role role,String phoneNumber) {
super();
this.userId = userId;
this.name = username;
this.emailId = emailId;
this.password = password;
this.todoList = todoList;
this.role = role;
this.phoneNumber = phoneNumber;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public List<Todo> getTodoList() {
return todoList;
}
public void setTodoList(List<Todo> todoList) {
this.todoList = todoList;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of(new SimpleGrantedAuthority(role.name()));
}
@Override
public String getUsername() {
// TODO Auto-generated method stub
return this.emailId;
}
@Override
public boolean isAccountNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isCredentialsNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
}
|
/**
* Reservation service not working as intended
*/
package com.dacdigitals.librarymanagementsystem.service;
import com.dacdigitals.librarymanagementsystem.dto.ReservationDTO;
import com.dacdigitals.librarymanagementsystem.entity.*;
import com.dacdigitals.librarymanagementsystem.entity.constant.TYPE;
import com.dacdigitals.librarymanagementsystem.exceptionHandler.BookNotAvailable;
import com.dacdigitals.librarymanagementsystem.exceptionHandler.ReservationNotFound;
import com.dacdigitals.librarymanagementsystem.repository.IBookAvailabilityRepository;
import com.dacdigitals.librarymanagementsystem.repository.IBookRepository;
import com.dacdigitals.librarymanagementsystem.repository.IReservationRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class ReservationService implements IReservationService {
private final IPersonService ipersonService;
private final IBookService iBookService;
private final IReservationRepository iReservationRepository;
private final IBookRepository iBookRepository;
private final ITransactionService iTransactionService;
private final IBookAvailabilityRepository bookAvailabilityRepository;
@Override
public Reservation makeReservation(ReservationDTO reservation) {
Person user = ipersonService.getPerson(reservation.getUserId());
Book book = iBookService.getBookById(reservation.getBookId());
Transaction borrowedBook;
if (user != null && book != null) {
Optional<Transaction> transaction =
iTransactionService.getAllTransaction().stream().filter(trxn -> trxn.getBookId() == book.getId() && trxn.getType() == TYPE.BORROW).distinct().findFirst();
if (transaction.isPresent()) {
borrowedBook = transaction.get();
//book shouldn't be available and not reserved
if (!book.getAvailable() && !getReservationByBookId(book.getId()).isReserved()) {
LocalDateTime reserveDate = LocalDateTime.now();
LocalDateTime expiryDate =
borrowedBook.getDueDate().plusHours(1);
Reservation reserved = Reservation.builder()
.id(0)
.userId(user.getId())
.bookId(book.getId())
.isReserved(true)
.reserveDate(reserveDate)
.expiryDate(expiryDate)
.build();
BookAvailability setBookAvailability =
BookAvailability.builder()
.id(0L)
.userId(reserved.getUserId())
.bookId(reserved.getBookId())
.bookReserveId(reserved.getId())
.isReserved(reserved.isReserved())
.setTime(reserveDate)
.updatedAt(reserveDate)
.build();
bookAvailabilityRepository.save(setBookAvailability);
return iReservationRepository.save(reserved);
} else {
throw new BookNotAvailable("Book not available! Check " + "back by " + borrowedBook.getDueDate());
}
}
}
return null;
}
@Override
public Reservation getReservationByUserId(Long userId) {
Reservation reservation = iReservationRepository.findByUserId(userId);
if (reservation != null) {
return reservation;
} else {
throw new ReservationNotFound("No reservation with user id " + userId + " was " + "found!");
}
}
@Override
public List<Reservation> getAllReservation() {
return iReservationRepository.findAll();
}
@Override
public Reservation getReservationByRservId(Long reservationId) {
Optional<Reservation> reservations =
iReservationRepository.findById(reservationId);
if (reservations.isPresent()) {
return reservations.get();
} else {
throw new ReservationNotFound("No reservation with id " + reservationId + " was " + "found!");
}
}
@Override
public Reservation getReservationByBookId(Long bookId) {
Reservation reservation =
iReservationRepository.findByBookId(bookId);
if (reservation != null) {
return reservation;
} else {
throw new ReservationNotFound("No reservation with book id " + bookId + " was " + "found! You can proceed to borrow the book.");
}
}
@Override
public String cancelReservation(Long id) {
Reservation reservation = getReservationByRservId(id);
if (reservation != null) {
Optional<BookAvailability> bookAvailability =
bookAvailabilityRepository.findById(reservation.getId());
if (bookAvailability.isPresent() && bookAvailability.get().isReserved()) {
Book book = iBookService.getBookById(reservation.getBookId());
book.setAvailable(true);
book.setUpdatedAt(LocalDateTime.now());
iBookRepository.save(book);
reservation.setReserved(false);
reservation.setExpiryDate(LocalDateTime.now());
BookAvailability setBookAvailability =
BookAvailability.builder()
.id(bookAvailability.get().getId())
.userId(bookAvailability.get().getUserId())
.bookId(bookAvailability.get().getBookId())
.bookReserveId(reservation.getId())
.isReserved(false)
.setTime(bookAvailability.get().getSetTime())
.updatedAt(LocalDateTime.now())
.build();
bookAvailabilityRepository.save(setBookAvailability);
iReservationRepository.save(reservation);
return "Reservation cancelled successfully!";
} else {
throw new BookNotAvailable("Book either not present or book " +
"isn't reserved!");
}
}
return null;
}
@Override
public String deleteReservation(Long id) {
Optional<Reservation> reservation = iReservationRepository.findById(id);
if (reservation.isPresent()) {
Book book = iBookService.getBookById(reservation.get().getBookId());
book.setAvailable(true);
book.setUpdatedAt(LocalDateTime.now());
iBookRepository.save(book);
iReservationRepository.delete(reservation.get());
return "Reservation deleted successfully!";
} else {
throw new ReservationNotFound("No reservation with id " + id + " was " + "found!");
}
}
}
|
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
class Solution {
public String[] solution(int n, int[] arr1, int[] arr2) {
String[] answer = new String[n];
// 01001(2) = 9(10)
// arr1, arr2의 배열 사이즈 처리
String[] binary1 = new String[n];
String[] binary2 = new String[n];
double result = Math.pow(2, n); // 16
// arr1을 String 형태의 이진수로 변환
for(int i = 0; i < n; i++) {
binary1[i] = Integer.toBinaryString(arr1[i]);
binary2[i] = Integer.toBinaryString(arr2[i]);
// 2진수가 n-1자리일 때 0으로 채우기
// binary1[i] 의 length로 조건문 바꾸기
int len1 = binary1[i].length();
if(len1 < n) {
for(int j = 0; j < n - len1; j++) {
binary1[i] = "0" + binary1[i];
}
}
// binary2[i] 의 length로 조건문 바꾸기
int len2 = binary2[i].length();
if(len2 < n) {
for(int j = 0; j < n - len2; j++) {
binary2[i] = "0" + binary2[i];
}
}
}
// arr1, arr2를 오버레이함.
// 공백 || 벽 = 벽
// 공백 && 공백 = 공백
// test
// logic
// answer에 담기
for(int i = 0; i < n; i++) {
answer[i] = ""; // 초기화를 해주지 않으면 null인 상태에서 +연산이 된다.
for(int j = 0; j < n; j++) {
int tmp = (binary1[i].charAt(j) - '0') + (binary2[i].charAt(j) - '0');
// tmp가 1 이상이면 #, 0이면 공백
if(tmp == 0) {
answer[i] = answer[i] + " ";
} else {
answer[i] = answer[i] + "#";
}
}
}
return answer;
}
}
|
import * as amplitude from "@amplitude/analytics-browser";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Outlet, useLocation, useOutletContext } from "react-router-dom";
import Content from "../Content";
import LanguageSelector from "../LanguageSelector";
import Menu from "../Menu";
import { LayoutContainer, Title } from "./Layout.styles";
const Layout = ({}) => {
const { pathname } = useLocation();
const {
t,
i18n: { language },
} = useTranslation();
const title = {
"/accomodations": t("pages.accomodations.path"),
"/schedule": t("pages.schedule.path"),
"/rsvp": t("pages.rsvp.path"),
}[pathname];
useEffect(() => {
amplitude.track("Page View", { pathname, language });
}, [pathname]);
return (
<LayoutContainer>
{/* Menu */}
<Menu />
{/* Content */}
<Content>
<>
<Title sx={{ textAlign: pathname === "/schedule" ? "center" : "" }}>
{title}
</Title>
<Outlet />
</>
</Content>
{/* Lanugage Selector */}
<LanguageSelector />
</LayoutContainer>
);
};
export function useSetTitle() {
return useOutletContext();
}
export default Layout;
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
// Actions
import { echo } from './actions/echo'
import { fetchProductsAll } from './actions/api'
import { change_view } from './actions/gui'
import {
serverMessage,
serverProducts,
mainView
} from './reducers'
import { Container, Row, Col } from 'reactstrap'
import NavBar from './components/NavBar'
import Orders from './components/Orders'
import Products from './components/Products'
import Stocks from './components/Stocks'
class App extends Component {
componentDidMount() {
this.props.fetchMessage('BATATAS!')
this.props.fetchProductsAll()
}
navBarClick(btn_clicked) {
this.props.changeView(btn_clicked);
}
render() {
const elems = this.props.serverProductsAll.map(
(elem) => <li key={elem.id}> {elem.name}:{elem.code} </li>
)
const body = () => {
if (this.props.serverProductsAll.length) {
return <div> M: <b>{this.props.message}</b> {elems} </div>;
} else {
return <div>Loading...</div>;
}
}
const view = () => {
switch (this.props.currentview) {
case 1:
return <Orders />;
case 2:
return <Products />;
case 3:
return <Stocks />;
default:
return <Orders />;
}
}
return (
<Container >
<Row>
<Col>
<NavBar
onClick={(i) => this.navBarClick(i)}
active={this.props.currentview} />
</Col>
</Row>
<br />
<Row>
<Col>
<p />
{view()}
<p />
</Col>
</Row>
<Row>
<Col>CURRENT VIEW: {this.props.currentview} {body()}</Col>
</Row>
</Container>
);
}
}
export default connect(
state => ({
message: serverMessage(state),
serverProductsAll: serverProducts(state),
currentview: mainView(state)
}),
{
fetchMessage: echo,
fetchProductsAll: fetchProductsAll,
changeView: change_view
}
)(App)
|
import React, { useState, useEffect } from 'react';
import './App.css';
import {DateFooter} from "./components/DateFooter";
import {TimeFooter} from "./components/TimeFooter";
function App() {
const [dateState, setDateState] = useState(new Date());
useEffect(() => {
setInterval(() => setDateState(new Date()), 1000);
}, []);
return (
<div className="App">
<header className="App-header">
<p className="current-conditions">Your current conditions!</p>
</header>
<footer className="App-footer">
<DateFooter date={dateState} />
<TimeFooter date={dateState} />
</footer>
</div>
);
}
export default App;
|
import Component from "@ember/component";
import EmberObject from "@ember/object";
import {alias} from "@ember/object/computed";
import {inject as service} from "@ember/service";
import {buildValidations, validator} from "ember-cp-validations";
import {task} from "ember-concurrency";
import {getOwner} from "@ember/application";
import {buildRecipientValidations} from "./create-fulfillments-modal/recipient-validations";
const ValidationContainer = EmberObject.extend(
buildRecipientValidations("contact."),
{
isValid: alias("validations.isValid"),
contact: null,
}
);
const Validations = buildValidations({
contactIds: [validator("presence", true), validator("length", {min: 1})],
lineItems: [validator("presence", true), validator("length", {min: 1})],
});
export default Component.extend({
ajax: service(),
store: service(),
shop: null,
isRecipientsInvalid: true,
isPermittable: true,
init() {
this._super(...arguments);
this.set(
"formModel",
EmberObject.extend(Validations).create(
getOwner(this).ownerInjection(), // http://offirgolan.github.io/ember-cp-validations/docs/modules/Basic%20Usage.html
{
lineItems: [],
contactIds: this.contactIds,
}
)
);
if (this.contactIds && this.contactIds.length) {
this.vaildateRecipients();
}
this.checkPermittable();
},
async checkPermittable() {
const integration = await this.store.findRecord("integration", "Shopify");
if (!integration.permittedFeatures.includes("fulfillments")) {
this.set("integration", integration);
this.set("isPermittable", false);
}
},
async vaildateRecipients() {
const contactIds = this.get("formModel.contactIds") || [];
if (!contactIds.length) {
this.set("isRecipientsInvalid", true);
return true;
}
const contacts = await contactIds.map((id) =>
this.store.findRecord("contact", id)
);
for (const contact of contacts) {
const validation = ValidationContainer.create(
getOwner(this).ownerInjection(), // http://offirgolan.github.io/ember-cp-validations/docs/modules/Basic%20Usage.html
{contact: contact}
);
if (!validation.get("isValid")) {
this.set("isRecipientsInvalid", true);
return true;
}
}
this.set("isRecipientsInvalid", false);
return false;
},
createFulfillments: task(function* (params) {
const {contactIds, lineItems} = params;
const recipients = [];
for (let i = 0; i < contactIds.length; i++) {
const contact = yield this.store.findRecord("contact", contactIds[i]);
recipients.push({
contact_id: contactIds[i],
first_name: contact.get("firstName"),
last_name: contact.get("lastName"),
email: contact.get("email"),
street: contact.get("street"),
street2: contact.get("street2"),
city: contact.get("city"),
province: contact.get("province"),
postal_code: contact.get("postalCode"),
country: contact.get("country"),
});
}
const line_items = lineItems.filter(li => li.title).map((li) =>
li.getProperties(
"title",
"description",
"product_variant_id",
"quantity",
"unit_price",
"image_url",
"meta",
"description",
"variant_title"
)
);
const {shopId: sub_id} = this.shop
// Create fulfillment
return yield this.ajax.request("/api/ember/fulfillments", {
method: "POST",
contentType: "application/json",
data: {
sub_id,
line_items,
recipients,
},
});
}),
afterSave() {
// Override
},
actions: {
onLineItemsChange(lineItems) {
this.set("formModel.lineItems", lineItems);
},
onRecipientsChange(contactIds) {
this.set("formModel.contactIds", contactIds);
this.vaildateRecipients();
},
},
});
|
# Copyright (C) 2019 Greenbone Networks GmbH
# Text descriptions are largely excerpted from the referenced
# advisory, and are Copyright (C) the respective author(s)
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
if(description)
{
script_oid("1.3.6.1.4.1.25623.1.0.704386");
script_version("2019-07-04T09:25:28+0000");
script_cve_id("CVE-2018-16890", "CVE-2019-3822", "CVE-2019-3823");
script_name("Debian Security Advisory DSA 4386-1 (curl - security update)");
script_tag(name:"last_modification", value:"2019-07-04 09:25:28 +0000 (Thu, 04 Jul 2019)");
script_tag(name:"creation_date", value:"2019-02-06 00:00:00 +0100 (Wed, 06 Feb 2019)");
script_tag(name:"cvss_base", value:"7.5");
script_tag(name:"cvss_base_vector", value:"AV:N/AC:L/Au:N/C:P/I:P/A:P");
script_tag(name:"solution_type", value:"VendorFix");
script_tag(name:"qod_type", value:"package");
script_xref(name:"URL", value:"https://www.debian.org/security/2019/dsa-4386.html");
script_category(ACT_GATHER_INFO);
script_copyright("Copyright (C) 2019 Greenbone Networks GmbH");
script_family("Debian Local Security Checks");
script_dependencies("gather-package-list.nasl");
script_mandatory_keys("ssh/login/debian_linux", "ssh/login/packages", re:"ssh/login/release=DEB9");
script_tag(name:"affected", value:"curl on Debian Linux");
script_tag(name:"solution", value:"For the stable distribution (stretch), these problems have been fixed in
version 7.52.1-5+deb9u9.
We recommend that you upgrade your curl packages.");
script_xref(name:"URL", value:"https://security-tracker.debian.org/tracker/curl");
script_tag(name:"summary", value:"Multiple vulnerabilities were discovered in cURL, an URL transfer library.
CVE-2018-16890
Wenxiang Qian of Tencent Blade Team discovered that the function
handling incoming NTLM type-2 messages does not validate incoming
data correctly and is subject to an integer overflow vulnerability,
which could lead to an out-of-bounds buffer read.
CVE-2019-3822
Wenxiang Qian of Tencent Blade Team discovered that the function
creating an outgoing NTLM type-3 header is subject to an integer
overflow vulnerability, which could lead to an out-of-bounds write.
CVE-2019-3823
Brian Carpenter of Geeknik Labs discovered that the code handling
the end-of-response for SMTP is subject to an out-of-bounds heap
read.");
script_tag(name:"vuldetect", value:"This check tests the installed software version using the apt package manager.");
exit(0);
}
include("revisions-lib.inc");
include("pkg-lib-deb.inc");
res = "";
report = "";
if(!isnull(res = isdpkgvuln(pkg:"curl", ver:"7.52.1-5+deb9u9", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"libcurl3", ver:"7.52.1-5+deb9u9", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"libcurl3-dbg", ver:"7.52.1-5+deb9u9", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"libcurl3-gnutls", ver:"7.52.1-5+deb9u9", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"libcurl3-nss", ver:"7.52.1-5+deb9u9", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"libcurl4-doc", ver:"7.52.1-5+deb9u9", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"libcurl4-gnutls-dev", ver:"7.52.1-5+deb9u9", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"libcurl4-nss-dev", ver:"7.52.1-5+deb9u9", rls:"DEB9"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"libcurl4-openssl-dev", ver:"7.52.1-5+deb9u9", rls:"DEB9"))) {
report += res;
}
if(report != "") {
security_message(data:report);
} else if (__pkg_match) {
exit(99);
}
|
import { getLogger, EventEmitter } from '@signalwire/core'
import type { DevicePermissionName } from './index'
import {
getUserMedia,
enumerateDevices,
enumerateDevicesByKind,
checkPermissions,
checkCameraPermissions,
checkMicrophonePermissions,
checkSpeakerPermissions,
_getMediaDeviceKindByName,
stopStream,
supportsMediaOutput,
getMediaDevicesApi,
} from './index'
const _constraintsByKind = (
kind?: DevicePermissionName | 'all'
): MediaStreamConstraints => {
return {
audio:
!kind || kind === 'all' || kind === 'microphone' || kind === 'speaker',
video: !kind || kind === 'all' || kind === 'camera',
}
}
/**
* After prompting the user for permission, returns an array of media input and
* output devices available on this machine. If `kind` is not null, only the
* devices of the specified kind are returned. Possible values of the `kind`
* parameters are `"camera"`, `"microphone"`, and `"speaker"`, which
* respectively correspond to functions
* {@link getCameraDevicesWithPermissions},
* {@link getMicrophoneDevicesWithPermissions}, and
* {@link getSpeakerDevicesWithPermissions}.
*
* @param kind filter for this device category
* @param fullList By default, only devices for which
* we have been granted permissions are returned. To obtain a list of devices regardless of
* the permissions, pass `fullList=true`. Note however that some values such as
* `name` and `deviceId` could be omitted.
*
* @example
* ```typescript
* await SignalWire.WebRTC.getDevicesWithPermissions("camera")
* // [
* // {
* // "deviceId": "Rug5Bk...4TMhY=",
* // "kind": "videoinput",
* // "label": "HD FaceTime Camera",
* // "groupId": "Su/dzw...ccfnY="
* // }
* // ]
* ```
* @deprecated Use {@link getDevices} for better cross browser compatibility.
*/
export const getDevicesWithPermissions = async (
kind?: DevicePermissionName,
fullList: boolean = false
): Promise<MediaDeviceInfo[]> => getDevices(kind, fullList)
/**
* After prompting the user for permission, returns an array of camera devices.
*
* @example
* ```typescript
* await SignalWire.WebRTC.getCameraDevicesWithPermissions()
* // [
* // {
* // "deviceId": "Rug5Bk...4TMhY=",
* // "kind": "videoinput",
* // "label": "HD FaceTime Camera",
* // "groupId": "Su/dzw...ccfnY="
* // }
* // ]
* ```
* @deprecated Use {@link getCameraDevices} for better cross browser compatibility.
*/
export const getCameraDevicesWithPermissions = () =>
getDevicesWithPermissions('camera')
/**
* After prompting the user for permission, returns an array of microphone devices.
*
* @example
* ```typescript
* await SignalWire.WebRTC.getMicrophoneDevicesWithPermissions()
* // [
* // {
* // "deviceId": "ADciLf...NYgF8=",
* // "kind": "audioinput",
* // "label": "Internal Microphone",
* // "groupId": "rgZgKM...NW1hU="
* // }
* // ]
* ```
* @deprecated Use {@link getMicrophoneDevices} for better cross browser compatibility.
*/
export const getMicrophoneDevicesWithPermissions = () =>
getDevicesWithPermissions('microphone')
/**
* After prompting the user for permission, returns an array of speaker devices.
*
* @example
* ```typescript
* await SignalWire.WebRTC.getSpeakerDevicesWithPermissions()
* // [
* // {
* // "deviceId": "ADciLf...NYgF8=",
* // "kind": "audiooutput",
* // "label": "External Speaker",
* // "groupId": "rgZgKM...NW1hU="
* // }
* // ]
* ```
* @deprecated Use {@link getSpeakerDevices} for better cross browser compatibility.
*/
export const getSpeakerDevicesWithPermissions = () =>
getDevicesWithPermissions('speaker')
const _filterDevices = (
devices: MediaDeviceInfo[],
options: { excludeDefault?: boolean; targets?: MediaDeviceKind[] } = {}
) => {
const found: string[] = []
return devices.filter(({ deviceId, kind, groupId }) => {
if (!deviceId || (options.targets && !options.targets?.includes(kind))) {
return false
}
if (!groupId) {
return true
}
const key = `${kind}-${groupId}`
const checkDefault = options?.excludeDefault ? deviceId !== 'default' : true
if (!found.includes(key) && checkDefault) {
found.push(key)
return true
}
return false
})
}
/**
* Enumerates the media input and output devices available on this machine. If
* `name` is provided, only the devices of the specified kind are returned.
* Possible values of the `name` parameters are `"camera"`, `"microphone"`, and
* `"speaker"`, which respectively correspond to functions
* {@link getCameraDevices}, {@link getMicrophoneDevices}, and
* {@link getSpeakerDevices}.
*
* @param name filter for this device category
* @param fullList Default to false. Set to true to retrieve the raw list as returned by
* the browser, which might include multiple, duplicate deviceIds for the same group.
*
* @example
* ```typescript
* await SignalWire.WebRTC.getDevices("camera", true)
* // [
* // {
* // "deviceId": "3c4f97...",
* // "kind": "videoinput",
* // "label": "HD Camera",
* // "groupId": "828fec..."
* // }
* // ]
* ```
*/
export const getDevices = async (
name?: DevicePermissionName,
fullList: boolean = false
): Promise<MediaDeviceInfo[]> => {
const hasPerms = await checkPermissions(name)
let stream: MediaStream | undefined = undefined
if (hasPerms === false) {
const constraints = _constraintsByKind(name)
stream = await getUserMedia(constraints)
}
const devices = await enumerateDevicesByKind(_getMediaDeviceKindByName(name))
/**
* Firefox requires an active stream at the time of `enumerateDevices`
* so we need to stop it after `WebRTC.enumerateDevicesByKind`
*/
if (stream) {
stopStream(stream)
}
if (fullList === true) {
return devices
}
return _filterDevices(devices)
}
/**
* Returns an array of camera devices that can be accessed on this device (for which we have permissions).
*
* @example
* ```typescript
* await SignalWire.WebRTC.getCameraDevices()
* // [
* // {
* // "deviceId": "Rug5Bk...4TMhY=",
* // "kind": "videoinput",
* // "label": "HD FaceTime Camera",
* // "groupId": "Su/dzw...ccfnY="
* // }
* // ]
* ```
*/
export const getCameraDevices = () => getDevices('camera')
/**
* Returns an array of microphone devices that can be accessed on this device (for which we have permissions).
*
* @example
* ```typescript
* await SignalWire.WebRTC.getMicrophoneDevices()
* // [
* // {
* // "deviceId": "ADciLf...NYgF8=",
* // "kind": "audioinput",
* // "label": "Internal Microphone",
* // "groupId": "rgZgKM...NW1hU="
* // }
* // ]
* ```
*/
export const getMicrophoneDevices = () => getDevices('microphone')
/**
* Returns an array of speaker devices that can be accessed on this device (for which we have permissions).
*
* @example
* ```typescript
* await SignalWire.WebRTC.getSpeakerDevices()
* // [
* // {
* // "deviceId": "ADciLf...NYgF8=",
* // "kind": "audiooutput",
* // "label": "External Speaker",
* // "groupId": "rgZgKM...NW1hU="
* // }
* // ]
* ```
*/
export const getSpeakerDevices = () => getDevices('speaker')
/**
* Assure a deviceId exists in the current device list from the browser.
* It checks for deviceId or label - in case the UA changed the deviceId randomly
*/
export const assureDeviceId = async (
id: string,
label: string,
name: DevicePermissionName
): Promise<string | null> => {
const devices = await getDevices(name, true)
for (let i = 0; i < devices.length; i++) {
const { deviceId, label: deviceLabel } = devices[i]
if (id === deviceId || label === deviceLabel) {
return deviceId
}
}
return null
}
/**
* Helper methods to assure a deviceId without asking the user the "kind"
*/
export const assureVideoDevice = (id: string, label: string) =>
assureDeviceId(id, label, 'camera')
export const assureAudioInDevice = (id: string, label: string) =>
assureDeviceId(id, label, 'microphone')
export const assureAudioOutDevice = (id: string, label: string) =>
assureDeviceId(id, label, 'speaker')
const _deviceInfoToMap = (devices: MediaDeviceInfo[]) => {
const map = new Map<string, MediaDeviceInfo>()
devices.forEach((deviceInfo) => {
if (deviceInfo.deviceId) {
map.set(deviceInfo.deviceId, deviceInfo)
}
})
return map
}
const _getDeviceListDiff = (
oldDevices: MediaDeviceInfo[],
newDevices: MediaDeviceInfo[]
) => {
const current = _deviceInfoToMap(oldDevices)
const removals = _deviceInfoToMap(oldDevices)
const updates: MediaDeviceInfo[] = []
getLogger().debug('[_getDeviceListDiff] <- oldDevices', oldDevices)
getLogger().debug('[_getDeviceListDiff] -> newDevices', newDevices)
const additions = newDevices.filter((newDevice) => {
const id = newDevice.deviceId
const oldDevice = current.get(id)
if (oldDevice) {
removals.delete(id)
if (newDevice.label !== oldDevice.label) {
updates.push(newDevice)
}
}
return oldDevice === undefined
})
return {
updated: updates.map((value) => {
return {
type: 'updated' as const,
payload: value,
}
}),
// Removed devices
removed: Array.from(removals, ([_, value]) => value).map((value) => {
return {
type: 'removed' as const,
payload: value,
}
}),
added: additions.map((value) => {
return {
type: 'added' as const,
payload: value,
}
}),
}
}
const TARGET_PERMISSIONS_MAP: Record<
DevicePermissionName,
() => Promise<boolean | null>
> = {
// FIXME: Replace this object with just checkPermissions(<target>)
camera: checkCameraPermissions,
microphone: checkMicrophonePermissions,
speaker: checkSpeakerPermissions,
}
const DEFAULT_TARGETS: DevicePermissionName[] = [
'camera',
'microphone',
'speaker',
]
const ALLOWED_TARGETS_MSG = `Allowed targets are: '${DEFAULT_TARGETS.join(
"', '"
)}'`
type TargetPermission = Record<
'supported' | 'unsupported',
[Partial<DevicePermissionName>, boolean][]
>
const CHECK_SUPPORT_MAP: Partial<Record<DevicePermissionName, () => boolean>> =
{
speaker: supportsMediaOutput,
}
const checkTargetPermissions = async (options: {
targets: DevicePermissionName[]
}): Promise<TargetPermission> => {
const targets = options.targets
const permissions = await Promise.all(
targets.map((target) => TARGET_PERMISSIONS_MAP[target]())
)
return permissions.reduce(
(reducer, permission, index) => {
const target = targets[index] as DevicePermissionName
/**
* If we don't specify a check for the target we'll assume
* there's no need to check for support
*/
const platformSupportStatus =
target in CHECK_SUPPORT_MAP ? CHECK_SUPPORT_MAP[target]?.() : true
const supportStatus: keyof TargetPermission = platformSupportStatus
? 'supported'
: 'unsupported'
reducer[supportStatus].push([target, !!permission])
return reducer
},
{ supported: [], unsupported: [] } as TargetPermission
)
}
const validateTargets = async (options: {
targets?: DevicePermissionName[]
}): Promise<DevicePermissionName[]> => {
const targets = (options.targets ?? DEFAULT_TARGETS).filter((target) => {
if (!DEFAULT_TARGETS.includes(target)) {
getLogger().warn(
`We'll ignore the "${target}" target as it is not allowed. ${ALLOWED_TARGETS_MSG}.`
)
return false
}
return true
})
if (!targets.length) {
throw new Error(
`At least one "target" is required for createDeviceWatcher(). ${ALLOWED_TARGETS_MSG}.`
)
}
const permissions = await checkTargetPermissions({ targets })
if (
permissions.unsupported.length > 0 &&
targets.length === permissions.unsupported.length
) {
throw new Error(
`The platform doesn't support "${targets.join(
', '
)}" as target/s, which means it's not possible to watch for changes on those devices.`
)
} else if (permissions.supported.every(([_, status]) => !status)) {
throw new Error(
'You must ask the user for permissions before being able to listen for device changes. Try calling getUserMedia() before calling `createDeviceWatcher()`.'
)
}
let needPermissionsTarget: DevicePermissionName[] = []
const filteredTargets: DevicePermissionName[] = permissions.supported.reduce(
(reducer, [target, status]) => {
if (!status) {
needPermissionsTarget.push(target)
} else {
reducer.push(target)
}
return reducer
},
[] as DevicePermissionName[]
)
/**
* If the length of these two arrays is different it means whether
* we have unsupported devices or that the user hasn't granted the
* permissions for certain targets
*/
if (filteredTargets.length !== targets.length) {
const unsupportedTargets =
permissions.unsupported.length > 0
? `The platform doesn't support "${permissions.unsupported
.map(([t]) => t)
.join(
', '
)}" as target/s, which means it's not possible to watch for changes on those devices. `
: ''
const needPermissions =
needPermissionsTarget.length > 0
? `The user hasn't granted permissions for the following targets: ${needPermissionsTarget.join(
', '
)}. `
: ''
getLogger().warn(
`${unsupportedTargets}${needPermissions}We'll be watching for the following targets instead: "${filteredTargets.join(
', '
)}"`
)
}
getLogger().debug(`Watching these targets: "${filteredTargets.join(', ')}"`)
return filteredTargets
}
interface CreateDeviceWatcherOptions {
targets?: DevicePermissionName[]
}
// prettier-ignore
type DeviceWatcherEventNames =
| 'added'
| 'changed'
| 'removed'
| 'updated'
type DeviceWatcherChangePayload<T extends DeviceWatcherEventNames> = {
type: T
payload: MediaDeviceInfo
}
type DeviceWatcherChange<T extends DeviceWatcherEventNames> = {
changes: DeviceWatcherChangePayload<T>[]
devices: MediaDeviceInfo[]
}
interface DeviceWatcherEvents {
added: (params: DeviceWatcherChange<'added'>) => void
removed: (params: DeviceWatcherChange<'removed'>) => void
updated: (params: DeviceWatcherChange<'updated'>) => void
changed: (params: {
changes: {
added: DeviceWatcherChangePayload<'added'>[]
removed: DeviceWatcherChangePayload<'removed'>[]
updated: DeviceWatcherChangePayload<'updated'>[]
}
devices: MediaDeviceInfo[]
}) => void
}
// FIXME: Move createDeviceWatcher and all related helpers/derived methods to its own module
/**
* Asynchronously returns an event emitter that notifies changes in the devices.
* The possible events are:
*
* - "added": a device has been added
* - "removed": a device has been removed
* - "updated": a device has been updated
* - "changed": any of the previous events occurred
*
* In all cases, your event handler gets as parameter an object `e` with the
* following keys:
*
* - `e.changes`: the changed devices. For "added", "removed", and "updated"
* event handlers, you only get the object associated to the respective event
* (i.e., only a list of added devices, removed devices, or updated devices).
* For "changed" event handlers, you get all three lists.
* - `e.devices`: the new list of devices
*
* For device-specific helpers, see {@link createCameraDeviceWatcher},
* {@link createMicrophoneDeviceWatcher}, and {@link createSpeakerDeviceWatcher}.
*
* @param options if null, the event emitter is associated to all devices for
* which we have permission. Otherwise, you can pass an object
* `{targets: string}`, where the value for key targets is a list of categories.
* Allowed categories are `"camera"`, `"microphone"`, and `"speaker"`.
*
* @example
* Creating an event listener on the "changed" event and printing the received parameter after both connecting and disconnecting external headphones:
* ```typescript
* await SignalWire.WebRTC.getUserMedia({audio: true, video: false})
* h = await SignalWire.WebRTC.createDeviceWatcher()
* h.on('changed', (c) => console.log(c))
* ```
*
* @example
* Getting notified just for changes about audio input and output devices, ignoring the camera:
* ```typescript
* h = await SignalWire.WebRTC.createDeviceWatcher({targets: ['microphone', 'speaker']})
* h.on('changed', (c) => console.log(c))
* ```
*/
export const createDeviceWatcher = async (
options: CreateDeviceWatcherOptions = {}
) => {
const targets = await validateTargets({ targets: options.targets })
const emitter = new EventEmitter<DeviceWatcherEvents>()
const currentDevices = await enumerateDevices()
const kinds = targets?.reduce((reducer, name) => {
const kind = _getMediaDeviceKindByName(name)
if (kind) {
reducer.push(kind)
}
return reducer
}, [] as MediaDeviceKind[])
let knownDevices = _filterDevices(currentDevices, {
excludeDefault: true,
targets: kinds,
})
const deviceChangeHandler = async () => {
const currentDevices = await enumerateDevices()
const oldDevices = knownDevices
const newDevices = _filterDevices(currentDevices, {
excludeDefault: true,
targets: kinds,
})
knownDevices = newDevices
const changes = _getDeviceListDiff(oldDevices, newDevices)
const hasAddedDevices = changes.added.length > 0
const hasRemovedDevices = changes.removed.length > 0
const hasUpdatedDevices = changes.updated.length > 0
if (hasAddedDevices || hasRemovedDevices || hasUpdatedDevices) {
emitter.emit('changed', { changes: changes, devices: newDevices })
}
if (hasAddedDevices) {
emitter.emit('added', {
changes: changes.added,
devices: newDevices,
})
}
if (hasRemovedDevices) {
emitter.emit('removed', {
changes: changes.removed,
devices: newDevices,
})
}
if (hasUpdatedDevices) {
emitter.emit('updated', {
changes: changes.updated,
devices: newDevices,
})
}
}
getMediaDevicesApi().addEventListener('devicechange', deviceChangeHandler)
return emitter
}
/**
* Asynchronously returns an event emitter that notifies changes in all
* microphone devices. This is equivalent to calling
* `createDeviceWatcher({ targets: ['microphone'] })`, so refer to
* {@link createDeviceWatcher} for additional information about the returned
* event emitter.
*/
export const createMicrophoneDeviceWatcher = () =>
createDeviceWatcher({ targets: ['microphone'] })
/**
* Asynchronously returns an event emitter that notifies changes in all speaker
* devices. This is equivalent to calling
* `createDeviceWatcher({ targets: ['speaker'] })`, so refer to
* {@link createDeviceWatcher} for additional information about the returned
* event emitter.
*/
export const createSpeakerDeviceWatcher = () =>
createDeviceWatcher({ targets: ['speaker'] })
/**
* Asynchronously returns an event emitter that notifies changes in all camera
* devices. This is equivalent to calling
* `createDeviceWatcher({ targets: ['camera'] })`, so refer to
* {@link createDeviceWatcher} for additional information about the returned
* event emitter.
*/
export const createCameraDeviceWatcher = () =>
createDeviceWatcher({ targets: ['camera'] })
const isMediaStream = (options: any): options is MediaStream => {
return typeof options?.getTracks === 'function'
}
// FIXME: Move getMicrophoneAnalyzerMediaStream and all related helpers/derived methods to its own module
const getMicrophoneAnalyzerMediaStream = async (
options: string | MediaTrackConstraints | MediaStream
) => {
if (isMediaStream(options)) {
return options
}
let constraints: MediaStreamConstraints
if (typeof options === 'string') {
constraints = {
audio: {
deviceId: options,
},
}
} else {
constraints = {
audio: options,
}
}
return getUserMedia(constraints)
}
const createAnalyzer = (audioContext: AudioContext) => {
const analyser = audioContext.createAnalyser()
analyser.fftSize = 64
analyser.minDecibels = -90
analyser.maxDecibels = -10
analyser.smoothingTimeConstant = 0.85
return analyser
}
const MAX_VOLUME = 100
interface MicrophoneAnalyzerEvents {
volumeChanged: (volume: number) => void
destroyed: (reason: null | 'error' | 'disconnected') => void
}
interface MicrophoneAnalyzer extends EventEmitter<MicrophoneAnalyzerEvents> {
destroy(): void
}
/**
* Initializes a microphone analyzer. You can use a MicrophoneAnalyzer to track
* the input audio volume.
*
* To stop the analyzer, plase call the `destroy()` method on the object
* returned by this method.
*
* The returned object emits the following events:
*
* - `volumeChanged`: instantaneous volume from 0 to 100
* - `destroyed`: the object has been destroyed. You get a parameter
* describing the reason, which can be `null` (if you called `destroy()`),
* `"error"` (in case of errors), or `"disconnected"` (if the device was
* disconnected).
*
* @example
*
* ```js
* const micAnalyzer = await createMicrophoneAnalyzer('device-id')
*
* micAnalyzer.on('volumeChanged', (vol) => {
* console.log("Volume: ", vol)
* })
* micAnalyzer.on('destroyed', (reason) => {
* console.log('Microphone analyzer destroyed', reason)
* })
*
* micAnalyzer.destroy()
* ```
*
* @param options either the id of the device to analize, or
* [MediaStreamConstraints](https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints),
* or a
* [MediaStream](https://developer.mozilla.org/en-US/docs/Web/API/MediaStream).
*
* @returns Asynchronously returns a MicrophoneAnalyzer.
*/
export const createMicrophoneAnalyzer = async (
options: string | MediaTrackConstraints | MediaStream
): Promise<MicrophoneAnalyzer> => {
const stream = await getMicrophoneAnalyzerMediaStream(options)
if (!stream) {
throw new Error('Failed to get the audio stream')
}
const emitter = new EventEmitter<MicrophoneAnalyzerEvents>()
const audioContext = new (window.AudioContext ||
(window as any).webkitAudioContext)()
const analyser = createAnalyzer(audioContext)
let rafId: number | undefined
let volume: number | undefined
try {
audioContext.createMediaStreamSource(stream).connect(analyser)
} catch (error) {
throw new Error('No audio track found')
}
/**
* If the device gets disconnected, we'll notify the user of
* the change.
*/
stream.getAudioTracks().forEach((track) => {
track.addEventListener('ended', () => {
emitter.emit('destroyed', 'disconnected')
})
})
const startMetering = () => {
try {
const dataArray = new Uint8Array(analyser.frequencyBinCount)
analyser.getByteFrequencyData(dataArray)
/**
* dataArray contains the values of the volume
* gathered within a single requestAnimationFrame With
* reduce and divide by 20 we translate the array
* values into a 0-100 scale to draw the green bars
* for the voice/volume energy.
*/
const latestVol =
dataArray.reduce((final, value) => final + value, 0) / 20
if (volume !== latestVol) {
volume = latestVol
emitter.emit('volumeChanged', Math.min(volume, MAX_VOLUME))
}
rafId = requestAnimationFrame(startMetering)
} catch (e) {
emitter.emit('destroyed', 'error')
}
}
rafId = requestAnimationFrame(startMetering)
const destroy = () => {
if (rafId) {
cancelAnimationFrame(rafId)
}
if (audioContext.state !== 'closed') {
audioContext.close().catch((error) => {
getLogger().error('Error closing the AudioContext', error)
})
}
/**
* If the user provided a MediaStream, we don't need to
* close it.
*/
if (!isMediaStream(options)) {
stream.getTracks().forEach((track) => track.stop())
}
emitter.emit('destroyed', null)
emitter.removeAllListeners()
}
return new Proxy<MicrophoneAnalyzer>(
// @ts-expect-error
emitter,
{
get(target, prop: keyof MicrophoneAnalyzer, receiver: any) {
if (prop === 'destroy') {
return destroy
}
return Reflect.get(target, prop, receiver)
},
}
)
}
/**
* Returns the speaker based on the given id.
* @param id string
* @returns MediaDevices | undefined
*/
export const getSpeakerById = async (
id: string
): Promise<MediaDeviceInfo | undefined> => {
const speakers = await getSpeakerDevices()
return speakers.find(
(audio) =>
audio.deviceId === id ||
(audio.deviceId === 'default' && id === '') ||
(audio.deviceId === '' && id === 'default')
)
}
|
package com.example.beneficiaries.ui.beneficiarieslist.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.beneficiaries.R
import com.example.beneficiaries.domain.model.Beneficiary
class BeneficiaryAdapter(private val beneficiariesList: List<Beneficiary>): RecyclerView.Adapter<BeneficiaryAdapter.BeneficiaryViewHolder>(){
private var itemClickedListener: ClickListener? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BeneficiaryViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.beneficiary_view_holder, parent, false)
return BeneficiaryViewHolder(view)
}
override fun getItemCount(): Int {
return beneficiariesList.size
}
override fun onBindViewHolder(holder: BeneficiaryViewHolder, position: Int) {
holder.firstNameTextView.text = beneficiariesList[position].firstName
holder.lastNameTextView.text = beneficiariesList[position].lastName
holder.beneTypeNameTextView.text = beneficiariesList[position].beneType
holder.designationTextView.text = if (beneficiariesList[position].designationCode == "P") "Primary" else "Contingent"
}
fun setOnItemClickListener(itemClickedListener: ClickListener) {
this.itemClickedListener = itemClickedListener
}
fun getSSN(position: Int): String? {
return beneficiariesList[position].socialSecurityNumber
}
inner class BeneficiaryViewHolder(itemView: View): RecyclerView.ViewHolder(itemView), View.OnClickListener {
var firstNameTextView: TextView
var lastNameTextView: TextView
var beneTypeNameTextView: TextView
var designationTextView: TextView
init {
firstNameTextView = itemView.findViewById(R.id.beneficiary_first_name_tv)
lastNameTextView = itemView.findViewById(R.id.beneficiary_last_name_tv)
beneTypeNameTextView = itemView.findViewById(R.id.beneficiary_type_tv)
designationTextView = itemView.findViewById(R.id.designation_tv)
if (itemClickedListener != null) {
itemView.setOnClickListener(this)
}
}
override fun onClick(v: View?) {
if (v != null) {
itemClickedListener?.onItemClicked(v, adapterPosition)
}
}
}
interface ClickListener {
fun onItemClicked(v: View, position: Int)
}
}
|
package com.hotent.nodetimeandcount.controller.nodetimeandcount;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.hotent.core.annotion.Action;
import org.springframework.web.servlet.ModelAndView;
import com.hotent.core.util.UniqueIdUtil;
import com.hotent.core.web.util.RequestUtil;
import com.hotent.core.web.controller.BaseController;
import com.hotent.core.util.BeanUtils;
import com.hotent.core.web.query.QueryFilter;
import com.hotent.nodetimeandcount.model.nodetimeandcount.Nodetimeandcount;
import com.hotent.nodetimeandcount.service.nodetimeandcount.NodetimeandcountService;
import com.hotent.core.web.ResultMessage;
/**
* 对象功能:节点发生时间与发生量表 控制器类
*/
@Controller
@RequestMapping("/nodetimeandcount/nodetimeandcount/nodetimeandcount/")
public class NodetimeandcountController extends BaseController
{
@Resource
private NodetimeandcountService nodetimeandcountService;
/**
* 添加或更新节点发生时间与发生量表。
* @param request
* @param response
* @param nodetimeandcount 添加或更新的实体
* @return
* @throws Exception
*/
@RequestMapping("save")
@Action(description="添加或更新节点发生时间与发生量表")
public void save(HttpServletRequest request, HttpServletResponse response,Nodetimeandcount nodetimeandcount) throws Exception
{
String resultMsg=null;
try{
if(nodetimeandcount.getId()==null){
Long id=UniqueIdUtil.genId();
nodetimeandcount.setId(id);
nodetimeandcountService.add(nodetimeandcount);
resultMsg=getText("添加","节点发生时间与发生量表");
}else{
nodetimeandcountService.update(nodetimeandcount);
resultMsg=getText("更新","节点发生时间与发生量表");
}
writeResultMessage(response.getWriter(),resultMsg,ResultMessage.Success);
}catch(Exception e){
writeResultMessage(response.getWriter(),resultMsg+","+e.getMessage(),ResultMessage.Fail);
}
}
/**
* 取得节点发生时间与发生量表分页列表
* @param request
* @param response
* @param page
* @return
* @throws Exception
*/
@RequestMapping("list")
@Action(description="查看节点发生时间与发生量表分页列表")
public ModelAndView list(HttpServletRequest request,HttpServletResponse response) throws Exception
{
List<Nodetimeandcount> list=nodetimeandcountService.getAll(new QueryFilter(request,"nodetimeandcountItem"));
ModelAndView mv=this.getAutoView().addObject("nodetimeandcountList",list);
return mv;
}
/**
* 删除节点发生时间与发生量表
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("del")
@Action(description="删除节点发生时间与发生量表")
public void del(HttpServletRequest request, HttpServletResponse response) throws Exception
{
String preUrl= RequestUtil.getPrePage(request);
ResultMessage message=null;
try{
Long[] lAryId=RequestUtil.getLongAryByStr(request,"id");
nodetimeandcountService.delByIds(lAryId);
message=new ResultMessage(ResultMessage.Success, "删除节点发生时间与发生量表成功!");
}catch(Exception ex){
message=new ResultMessage(ResultMessage.Fail, "删除失败" + ex.getMessage());
}
addMessage(message, request);
response.sendRedirect(preUrl);
}
/**
* 编辑节点发生时间与发生量表
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("edit")
@Action(description="编辑节点发生时间与发生量表")
public ModelAndView edit(HttpServletRequest request) throws Exception
{
Long id=RequestUtil.getLong(request,"id");
String returnUrl=RequestUtil.getPrePage(request);
Nodetimeandcount nodetimeandcount=nodetimeandcountService.getById(id);
return getAutoView().addObject("nodetimeandcount",nodetimeandcount)
.addObject("returnUrl",returnUrl);
}
/**
* 取得节点发生时间与发生量表明细
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping("get")
@Action(description="查看节点发生时间与发生量表明细")
public ModelAndView get(HttpServletRequest request, HttpServletResponse response) throws Exception
{
Long id=RequestUtil.getLong(request,"id");
Nodetimeandcount nodetimeandcount=nodetimeandcountService.getById(id);
return getAutoView().addObject("nodetimeandcount", nodetimeandcount);
}
}
|
import React from "react";
import "./App.css";
import { Tabs, Tab, AppBar } from "@material-ui/core";
import { Route, BrowserRouter, Switch, Link } from "react-router-dom";
import addProducts from "./components/addproducts";
import removeProducts from "./components/removeproducts";
import listProducts from "./components/listproducts";
export default function App() {
const routes = ["/addproducts", "/removeproducts", "/listproducts"];
return (
<div className="App">
<BrowserRouter>
<Route
path="/"
render={(history) => (
<AppBar>
<Tabs
value={
history.location.pathname !== "/"
? history.location.pathname
: false
}
>
{console.log(history.location.pathname)}
<Tab
value={routes[0]}
label="Add Products"
component={Link}
to={routes[0]}
/>
<Tab
value={routes[1]}
label="Remove Products"
component={Link}
to={routes[1]}
/>
<Tab
value={routes[1]}
label="Link Products"
component={Link}
to={routes[1]}
/>
</Tabs>
</AppBar>
)}
/>
<Switch>
<Route path="/addproducts" component={addProducts} />
<Route path="/removeproducts" component={removeProducts} />
<Route path="/listproducts" component={listProducts} />
</Switch>
</BrowserRouter>
</div>
);
}
|
import React, { useContext, useState } from "react";
import { useMutation } from "@apollo/client";
import { Button, Form } from "semantic-ui-react";
import { REGISTER_USER_MUTATION } from "../util/graphql";
import { useForm } from "../util/hooks";
import { AuthContext } from "../context/auth";
const Register = ({ history }) => {
const [errors, setErrors] = useState({});
const context = useContext(AuthContext);
const { onChange, onSubmit, values } = useForm(registerUser, {
username: "",
email: "",
password: "",
confirmPassword: "",
});
const [addUser, { loading }] = useMutation(REGISTER_USER_MUTATION, {
update(_, { data: { register: userData } }) {
context.login(userData);
history.push("/");
},
onError(err) {
console.log("Errors: ", err?.graphQLErrors[0]?.extensions);
setErrors(err.graphQLErrors[0].extensions.errors);
// setErrors(err?.graphQLErrors[0]?.extensions?.exception?.errors);
},
variables: values,
});
function registerUser() {
addUser();
}
return (
<div className="form-container">
<Form onSubmit={onSubmit} noValidate className={loading ? "loading" : ""}>
<h1>Register</h1>
<Form.Input
label="Username"
placeholder="Username.."
name="username"
type="text"
value={values.username}
error={
errors && errors.username
? Object.keys(errors).length > 0 && {
content: errors["username"],
}
: false
}
onChange={onChange}
/>
<Form.Input
label="Email"
placeholder="Email.."
name="email"
type="email"
value={values.email}
onChange={onChange}
error={
errors && errors.email
? Object.keys(errors).length > 0 && {
content: errors["email"],
}
: false
}
// error={errors["email"] ? true : false}
/>
<Form.Input
label="Password"
placeholder="Password.."
name="password"
type="password"
value={values.password}
onChange={onChange}
error={
errors && errors.password
? Object.keys(errors).length > 0 && {
content: errors["password"],
}
: false
}
/>
<Form.Input
label="Confirm Password"
placeholder="Confirm Password.."
name="confirmPassword"
type="password"
value={values.confirmPassword}
onChange={onChange}
error={
errors && errors.confirmPassword
? Object.keys(errors).length > 0 && {
content: errors["confirmPassword"],
}
: false
}
/>
<Button type="submit" primary>
Register
</Button>
</Form>
{Object.keys(errors).length > 0 ? (
<div className="ui error message">
<ul className="list">
{Object.values(errors).map((value) => (
<li key={value}>{value}</li>
))}
</ul>
</div>
) : (
""
)}
</div>
);
};
export default Register;
|
/* Responsive Mixins */
// Source: https://css-tricks.com/snippets/css/fluid-typography/
@mixin fluid-type($min-vw, $max-vw, $min-font-size, $max-font-size, $set-base-font: true) {
$u1: unit($min-vw);
$u2: unit($max-vw);
$u3: unit($min-font-size);
$u4: unit($max-font-size);
@if $u1 == $u2 and $u1 == $u3 and $u1 == $u4 {
& {
@if ($set-base-font) {
font-size: $min-font-size;
}
@media screen and (min-width: $min-vw) {
font-size: calc(#{$min-font-size} + #{stripUnit($max-font-size - $min-font-size)} * ((100vw - #{$min-vw}) / #{stripUnit($max-vw - $min-vw)}));
}
@media screen and (min-width: $max-vw) {
font-size: $max-font-size;
}
}
}
}
// Source: https://css-tricks.com/snippets/css/fluid-typography/
@mixin fluid-type-important($min-vw, $max-vw, $min-font-size, $max-font-size, $set-base-font: true) {
$u1: unit($min-vw);
$u2: unit($max-vw);
$u3: unit($min-font-size);
$u4: unit($max-font-size);
@if $u1 == $u2 and $u1 == $u3 and $u1 == $u4 {
& {
@if ($set-base-font) {
font-size: $min-font-size !important;
}
@media screen and (min-width: $min-vw) {
font-size: calc(#{$min-font-size} + #{stripUnit($max-font-size - $min-font-size)} * ((100vw - #{$min-vw}) / #{stripUnit($max-vw - $min-vw)})) !important;
}
@media screen and (min-width: $max-vw) {
font-size: $max-font-size !important;
}
}
}
}
// Based on fluid-type: Source: https://css-tricks.com/snippets/css/fluid-typography/
@mixin fluid-transition($min-vw, $max-vw, $min-size, $max-size, $css-property, $set-base-font: true) {
$u1: unit($min-vw);
$u2: unit($max-vw);
$u3: unit($min-size);
$u4: unit($max-size);
@if $u1 == $u2 and $u1 == $u3 and $u1 == $u4 {
& {
@if ($set-base-font) {
#{$css-property}: $min-size;
}
@media screen and (min-width: $min-vw) {
#{$css-property}: calc(#{$min-size} + #{stripUnit($max-size - $min-size)} * ((100vw - #{$min-vw}) / #{stripUnit($max-vw - $min-vw)}));
}
@media screen and (min-width: $max-vw) {
#{$css-property}: $max-size;
}
}
}
}
// Based on fluid-type: Source: https://css-tricks.com/snippets/css/fluid-typography/
@mixin fluid-transition-important($min-vw, $max-vw, $min-size, $max-size, $css-property, $set-base-font: true) {
$u1: unit($min-vw);
$u2: unit($max-vw);
$u3: unit($min-size);
$u4: unit($max-size);
@if $u1 == $u2 and $u1 == $u3 and $u1 == $u4 {
& {
@if ($set-base-font) {
#{$css-property}: $min-size !important;
}
@media screen and (min-width: $min-vw) {
#{$css-property}: calc(#{$min-size} + #{stripUnit($max-size - $min-size)} * ((100vw - #{$min-vw}) / #{stripUnit($max-vw - $min-vw)})) !important;
}
@media screen and (min-width: $max-vw) {
#{$css-property}: $max-size !important;
}
}
}
}
// Source: http://www.developerdrive.com/2018/05/10-best-sass-mixins-for-web-developers/
@mixin aspect-ratio($width, $height) {
position: relative;
&:before {
display: block;
content: "";
width: 100%;
padding-top: ($height / $width) * 100%;
}
> .inner-box {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
}
// Source: https://engageinteractive.co.uk/blog/top-10-scss-mixins
@mixin responsive-ratio($x,$y, $pseudo: false) {
$padding: unquote( ( $y / $x ) * 100 + '%' );
@if $pseudo {
&:before {
@include pseudo($pos: relative);
width: 100%;
padding-top: $padding;
}
} @else {
padding-top: $padding;
}
}
/* Positioning */
// Source: http://www.developerdrive.com/2018/05/10-best-sass-mixins-for-web-developers/
@mixin abs-position ($top: auto, $right: auto, $bottom: auto, $left: auto) {
position: absolute;
top: $top;
right: $right;
bottom: $bottom;
left: $left;
}
@mixin rel-position ($top: auto, $right: auto, $bottom: auto, $left: auto) {
position: relative;
top: $top;
right: $right;
bottom: $bottom;
left: $left;
}
// Source: https://medium.com/@justinbrazeau/10-useful-sass-mixins-for-automation-833cdee9d69b
// Define vertical, horizontal, or both position
@mixin abs-center($position) {
position: absolute;
@if $position == 'vertical' {
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
@else if $position == 'horizontal' {
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translate(-50%);
}
@else if $position == 'both' {
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
}
// Source: https://medium.com/@justinbrazeau/10-useful-sass-mixins-for-automation-833cdee9d69b
// Clearfix mixin (use @extend %clearfix instead of @include clearfix)
// Example:
// .container-with-floated-children {
// @extend %clearfix;
// }
%clearfix {
*zoom: 1;
&:before, &:after {
content: " ";
display: table;
}
&:after {
clear: both;
}
}
// Hide visually and from screenreaders, but maintain layout
@mixin invisible {
visibility: hidden;
}
/* Margin/Padding Mixins */
// Source: https://github.com/engageinteractive/core/blob/master/src/scss/utility/_mixins.scss
@mixin content-margins($selector: '> *', $last-child: false) {
@if not $selector {
$selector: '&';
}
#{unquote($selector)} {
&:first-child { margin-top: 0; }
@if $last-child {
&:last-child { margin-bottom: 0; }
}
}
}
// Source: https://engageinteractive.co.uk/blog/top-10-scss-mixins
@mixin push--auto {
margin: {
left: auto;
right: auto;
}
}
/* Styling */
// Source: http://www.developerdrive.com/2018/05/10-best-sass-mixins-for-web-developers/
@mixin text-shorten {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
// Source: https://medium.com/@justinbrazeau/10-useful-sass-mixins-for-automation-833cdee9d69b
@mixin background-gradient($start-color, $end-color, $orientation) {
background: $start-color;
@if $orientation == 'vertical' {
background: -webkit-linear-gradient(top, $start-color, $end-color);
background: linear-gradient(to bottom, $start-color, $end-color);
} @else if $orientation == 'horizontal' {
background: -webkit-linear-gradient(left, $start-color, $end-color);
background: linear-gradient(to right, $start-color, $end-color);
} @else {
background: -webkit-radial-gradient(center, ellipse cover, $start-color, $end-color);
background: radial-gradient(ellipse at center, $start-color, $end-color);
}
}
/* Animation */
// Source: https://medium.com/@justinbrazeau/10-useful-sass-mixins-for-automation-833cdee9d69b
//Animation mixin setup
@mixin keyframes($animation-name) {
@-webkit-keyframes #{$animation-name} {
@content;
}
@-moz-keyframes #{$animation-name} {
@content;
}
@-ms-keyframes #{$animation-name} {
@content;
}
@-o-keyframes #{$animation-name} {
@content;
}
@keyframes #{$animation-name} {
@content;
}
}
@mixin animation($str) {
-webkit-animation: #{$str};
-moz-animation: #{$str};
-ms-animation: #{$str};
-o-animation: #{$str};
animation: #{$str};
}
/* Screen Reader Mixins */
/* Source: https://github.com/engageinteractive/core/blob/master/src/scss/utility/_mixins.scss */
// Hide only visually, but have it available for screenreaders
@mixin vh($focusable: false) {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
@if $focusable {
@include vh-focusable;
}
}
@mixin vh-reset {
clip: auto;
height: auto;
margin: 0;
overflow: visible;
position: static;
width: auto;
}
// Allow the element to be focusable when navigated to via the keyboard
@mixin vh-focusable {
&:active,
&:focus {
clip: auto;
height: auto;
margin: 0;
overflow: visible;
position: static;
width: auto;
}
}
/* Utility Mixins */
// Source: https://coderwall.com/p/4hd9bw/easy-embedding-of-web-fonts-using-a-sass-mixin
@mixin fontFace($family, $src, $style: normal, $weight: normal) {
@font-face {
font-family: $family;
src: url('#{$src}.eot'); // IE9 compat
src: url('#{$src}.eot?#iefix') format('embedded-opentype'), // IE8 and below
url('#{$src}.woff2') format('woff2'), // standards
url('#{$src}.woff') format('woff'), // standards
url('#{$src}.ttf') format('truetype'), // Safari, Android, iOS
url('#{$src}.svg##{$family}') format('svg'); // legacy iOS
font-style: $style;
font-weight: $weight;
}
}
// Source: http://www.developerdrive.com/2018/05/10-best-sass-mixins-for-web-developers/
@mixin retina-image($image, $width, $height) {
@media (min--moz-device-pixel-ratio: 1.3),
(-o-min-device-pixel-ratio: 2.6/2),
(-webkit-min-device-pixel-ratio: 1.3),
(min-device-pixel-ratio: 1.3),
(min-resolution: 1.3dppx) {
background-image: url($image);
background-size: $width $height;
}
}
// Source: http://www.developerdrive.com/2018/05/10-best-sass-mixins-for-web-developers/
@mixin css3-prefix($prop, $value) {
-webkit-#{$prop}: #{$value};
-moz-#{$prop}: #{$value};
-ms-#{$prop}: #{$value};
-o-#{$prop}: #{$value};
#{$prop}: #{$value};
}
// Source: https://engageinteractive.co.uk/blog/top-10-scss-mixins
@mixin input-placeholder {
&.placeholder { @content; }
&:-moz-placeholder { @content; }
&::-moz-placeholder { @content; }
&:-ms-input-placeholder { @content; }
&::-webkit-input-placeholder { @content; }
}
// Source: https://engageinteractive.co.uk/blog/top-10-scss-mixins
@mixin truncate($truncation-boundary) {
max-width: $truncation-boundary;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
// Max's Mixins
@mixin generate-overlay($background, $position: relative) {
position: #{$position};
&:before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: $background;
}
}
// Same as above, but has to be applied to &:before. Keep around for legacy code.
@mixin generateOverlay($background) {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: $background;
}
@mixin responsive-padding {
padding-left: $desktop-edge-gap;
padding-right: $desktop-edge-gap;
@include tablet-v {
padding-left: $tablet-edge-gap;
padding-right: $tablet-edge-gap;
}
@include iphone-v {
padding-left: $mobile-edge-gap;
padding-right: $mobile-edge-gap;
}
}
@mixin margin-auto {
margin-left: auto;
margin-right: auto;
}
@mixin comp-max-width {
max-width: calc(#{$content-max-width} + (#{$desktop-edge-gap * 2}));
@include margin-auto;
@include responsive-padding;
}
@mixin group-spacing($property, $spacing-left, $spacing-right: $spacing-left) {
#{$property}-left: #{$spacing-left};
#{$property}-right: #{$spacing-right};
&:first-child {
#{$property}-left: 0;
}
&:last-child {
#{$property}-right: 0;
}
}
@mixin no-first-last($property, $value) {
#{$property}: #{$value};
&:first-child {
#{$property}: 0;
}
&:last-child {
#{$property}: 0;
}
}
|
package ru.practicum.shareit.user.service;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import ru.practicum.shareit.user.UserService;
import ru.practicum.shareit.user.UserServiceImpl;
import ru.practicum.shareit.user.dto.UserDto;
import ru.practicum.shareit.user.exception.UserNotFoundException;
import ru.practicum.shareit.user.model.User;
import ru.practicum.shareit.user.storage.UserRepository;
import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@ExtendWith(MockitoExtension.class)
public class UserServiceTest {
@Mock
UserRepository repository;
private User user1;
@BeforeEach
public void createUsers() {
user1 = User.builder().id(1L).name("name1").email("[email protected]").build();
}
@Test
public void testFindById() throws UserNotFoundException {
UserService service = new UserServiceImpl(repository);
Mockito.when(repository.findById(1L))
.thenReturn(Optional.of(user1));
User actual = service.findById(1);
assertThat(actual, Matchers.hasProperty("id", equalTo(1L)));
assertThat(actual, Matchers.hasProperty("name", equalTo("name1")));
assertThat(actual, Matchers.hasProperty("email", equalTo("[email protected]")));
}
@Test
public void testFindByIdShouldThrowUserNotFoundException() {
UserService service = new UserServiceImpl(repository);
Mockito.when(repository.findById(Mockito.anyLong()))
.thenReturn(Optional.ofNullable(null));
final UserNotFoundException exception = Assertions.assertThrows(
UserNotFoundException.class,
() -> service.findById(1L)
);
Assertions.assertEquals("MASSAGE: a user with id { 1 } does not exist; ERROR CODE: null",
exception.getErrorMessage());
}
@Test
public void testSave() {
UserService service = new UserServiceImpl(repository);
Mockito.when(repository.save(Mockito.any(User.class)))
.thenReturn(user1);
User actual = service.save(user1);
assertThat(actual, Matchers.hasProperty("id", equalTo(1L)));
assertThat(actual, Matchers.hasProperty("name", equalTo("name1")));
assertThat(actual, Matchers.hasProperty("email", equalTo("[email protected]")));
}
@Test
public void testSaveWhenArgumentNullShouldThrowIllegalArgumentException() throws IllegalArgumentException {
UserService service = new UserServiceImpl(repository);
Mockito.when(repository.save(null))
.thenThrow(new IllegalArgumentException("Illegal argument"));
final IllegalArgumentException exception = Assertions.assertThrows(
IllegalArgumentException.class,
() -> service.save(null)
);
Assertions.assertEquals("Illegal argument", exception.getMessage());
}
@Test
public void testUpdateWhenNameAndEmailNotNull() throws UserNotFoundException {
UserService service = new UserServiceImpl(repository);
UserDto userDto = UserDto.builder().id(1).name("newName").email("[email protected]").build();
User updatedUser = User.builder().id(1).name("newName").email("[email protected]").build();
Mockito.when(repository.save(updatedUser))
.thenReturn(updatedUser);
Mockito.when(repository.findById(1L))
.thenReturn(Optional.of(user1));
User actual = service.update(userDto);
assertThat(actual, Matchers.hasProperty("id", equalTo(1L)));
assertThat(actual, Matchers.hasProperty("name", equalTo("newName")));
assertThat(actual, Matchers.hasProperty("email", equalTo("[email protected]")));
}
@Test
public void testUpdateWhenNameNullAndEmailNotNull() throws UserNotFoundException {
UserService service = new UserServiceImpl(repository);
UserDto userDto = UserDto.builder().id(1).name(null).email("[email protected]").build();
User updatedUser = User.builder().id(1).name("name").email("[email protected]").build();
Mockito.when(repository.save(updatedUser))
.thenReturn(updatedUser);
Mockito.when(repository.findById(1L))
.thenReturn(Optional.of(user1));
User actual = service.update(userDto);
assertThat(actual, Matchers.hasProperty("id", equalTo(1L)));
assertThat(actual, Matchers.hasProperty("name", equalTo("name")));
assertThat(actual, Matchers.hasProperty("email", equalTo("[email protected]")));
}
@Test
public void testUpdateWhenNameNotNullAndEmailNull() throws UserNotFoundException {
UserService service = new UserServiceImpl(repository);
UserDto userDto = UserDto.builder().id(1).name("newName").email(null).build();
User updatedUser = User.builder().id(1).name("newName").email("[email protected]").build();
Mockito.when(repository.save(updatedUser))
.thenReturn(updatedUser);
Mockito.when(repository.findById(1L))
.thenReturn(Optional.of(user1));
User actual = service.update(userDto);
assertThat(actual, Matchers.hasProperty("id", equalTo(1L)));
assertThat(actual, Matchers.hasProperty("name", equalTo("newName")));
assertThat(actual, Matchers.hasProperty("email", equalTo("[email protected]")));
}
@Test
public void testUpdateWhenUserDoesNotExistShouldThrowUserNotFoundException() {
UserService service = new UserServiceImpl(repository);
UserDto userDto = UserDto.builder().id(1).name("newName").email("[email protected]").build();
Mockito.when(repository.findById(1L))
.thenReturn(Optional.ofNullable(null));
final UserNotFoundException exception = Assertions.assertThrows(
UserNotFoundException.class,
() -> service.update(userDto)
);
Assertions.assertEquals("MASSAGE: a user with id { 1 } does not exist; ERROR CODE: null",
exception.getErrorMessage());
}
@Test
public void testDeleteById1() throws UserNotFoundException {
UserService service = new UserServiceImpl(repository);
Mockito.when(repository.existsById(Mockito.anyLong()))
.thenReturn(true);
service.deleteById(1L);
Mockito.verify(repository, Mockito.times(1))
.deleteById(1L);
}
@Test
public void testDeleteByIdShouldThrowUserNotFoundException() {
UserService service = new UserServiceImpl(repository);
Mockito.when(repository.existsById(Mockito.anyLong()))
.thenReturn(false);
final UserNotFoundException exception = Assertions.assertThrows(
UserNotFoundException.class,
() -> service.deleteById(1L)
);
Assertions.assertEquals("MASSAGE: a user with id { 1 } does not exist; ERROR CODE: null",
exception.getErrorMessage());
}
}
|
from transformers import (AutoTokenizer, AutoConfig, LlamaForCausalLM, DataCollatorForLanguageModeling, Trainer, TrainingArguments)
from datasets import load_dataset
from huggingface_hub import login
import wandb
from utils_bitnet import *
### Login
# Wandb is for logging and is optional.
hf_token = "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"
wb_token = "725c6c7925bafb00921bf2a9e6f65bbdf1b1c6cb"
wandb.login(key=wb_token)
login(token=hf_token)
### Load and tokenize training data. Uncomment these lines to load and tokenize yourself.
# data_source = "Skylion007/openwebtext"
# data = load_dataset(data_source)
# subset = load_dataset(data_source, split="train[:15%]")
# context_length = 256
# tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
# def tokenize(element):
# outputs = tokenizer(
# element["text"],
# truncation=False,
# max_length=context_length,
# return_overflowing_tokens=True,
# return_length=True,
# )
# # Combine all tokens
# combined = []
# for tokenized_doc in outputs['input_ids']:
# combined += tokenized_doc + [tokenizer.eos_token_id]
# # Chunk
# input_batch = []
# for i in range(0, len(combined) - context_length, context_length):
# input_batch.append(combined[i:i+context_length])
# return {"input_ids": input_batch}
# tokenized_data = subset.map(
# tokenize, batched=True, remove_columns=data["train"].column_names,
# )
### End Load and tokenize training data
### Load pretokenized data (15% of openwebtext tokenized for ctx len of 256, ~1.5B tokens)
# You can subset this even further if you want a smaller dataset.
context_length = 256
tokenizer = AutoTokenizer.from_pretrained("NousResearch/Llama-2-7b-hf")
tokenized_data = load_dataset("xz56/openwebtext-tokenized-small")
total_tokens = tokenized_data['train'].num_rows * context_length
print(f"Training on {total_tokens:_} tokens")
### Adjust llama config to make the model tiny
config = AutoConfig.from_pretrained(
"NousResearch/Llama-2-7b-hf",
vocab_size=len(tokenizer),
n_ctx=context_length,
bos_token_id=tokenizer.bos_token_id,
eos_token_id=tokenizer.eos_token_id,
)
dim = 768
n_heads = 6
n_layers = 6
intermediate_size = 1536
config.hidden_size = dim
config.max_position_embeddings = dim
config.num_attention_heads = n_heads
config.num_hidden_layers = n_layers
config.num_key_value_heads = n_heads
config.intermediate_size = intermediate_size
### Create the llama model with our custom config. Convert it to bitnet.
# See utils.py for BitLinear and convert_to_bitnet function details.
model = LlamaForCausalLM(config)
convert_to_bitnet(model, copy_weights=False)
### Print number of parameters.
model_size = sum(t.numel() for t in model.parameters())
print(f"Model size: {model_size/1000**2:.1f}M parameters")
### Set up DataCollator for creating batches
tokenizer.pad_token = tokenizer.eos_token
data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)
### Set up training arguments and begin training. Adjust these to your needs.
# Adjust the batch size until you can train on your device. Then increase accumulation steps to satisfy the following:
# tokens per batch = per_device_train_batch_size * gradient_accumulation_steps * 256
# Adjust this until tokens per batch is at least ~100k.
output_path = "./out_bitnet"
args = TrainingArguments(
output_dir=output_path,
per_device_train_batch_size=64,
per_device_eval_batch_size=64,
evaluation_strategy="steps",
eval_steps=0.05,
logging_steps=100,
gradient_accumulation_steps=8,
num_train_epochs=1,
weight_decay=0.01,
warmup_steps=0.1,
lr_scheduler_type="cosine",
learning_rate=1.5e-3,
save_steps=0.25,
fp16=True,
report_to="wandb",
run_name="tinyllama-bitnet"
)
trainer = Trainer(
model=model,
tokenizer=tokenizer,
args=args,
data_collator=data_collator,
train_dataset=tokenized_data["train"],
eval_dataset=tokenized_data["test"],
)
trainer.train()
trainer.save_model(f"{output_path}/final_model")
|
// ignore_for_file: unnecessary_cast, prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:jupiter_academy/core/widgets/my_list_tile.dart';
import '../../../../core/api/api_service.dart';
import '../../../../core/utils/constants.dart';
import '../../../../core/utils/styles.dart';
import '../../../../core/widgets/errorwidget.dart';
import '../../../../core/widgets/loadingwidget.dart';
import '../../../../core/widgets/build_appbar_method.dart';
import '../../logic/models/student_model.dart';
class StudentsScrennBuilder extends StatefulWidget {
final String batchId;
const StudentsScrennBuilder({super.key, required this.batchId});
@override
State<StudentsScrennBuilder> createState() => _StudentsScrennBuilderState();
}
class _StudentsScrennBuilderState extends State<StudentsScrennBuilder> {
late Future<List<StudentModel>> _studentsFuture;
@override
void initState() {
super.initState();
_studentsFuture =
APiService().getStudentsByBatchId(widget.batchId);
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _studentsFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const MyLoadingWidget();
} else if (snapshot.hasError) {
print(snapshot.error.toString());
return const MyErrorWidget();
} else if (!snapshot.hasData ||
(snapshot.data as List<StudentModel>).isEmpty) {
return Scaffold(
appBar: buildAppBar(),
body: const Center(
child: Text('There are no students in this batch'),
),
);
} else {
return StudentsScreen(
studentsList: snapshot.data! as List<StudentModel>,
);
}
},
);
}
}
class StudentsScreen extends StatelessWidget {
final List<StudentModel> studentsList;
const StudentsScreen({super.key, required this.studentsList});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: buildAppBar(),
body: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text('Total students in this batch: ${studentsList.length}', style: Styles.style25,),
),
ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: MySquareTile(
child: Column(
children: [
ListTile(
title: Text(
'name: ${studentsList[index].name}',
style: Styles.style22,
),
),
ListTile(
title: Text(
'jupiterCoins: ${studentsList[index].jupiterCoins}',
style: Styles.style22,
),
),
ListTile(
title: Text(
'phone: ${studentsList[index].phone}',
style: Styles.style22,
),
),
ListTile(
title: Text(
'whatsApp: ${studentsList[index].whatsApp}',
style: Styles.style22,
),
),
],
),
),
);
},
itemCount: studentsList.length,
),
],
),
),
);
}
}
|
package i.socket_programming
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
fun main() {
try {
val externalIp = getExternalIPAddress()
println("Your External IP Address is: $externalIp")
} catch (e: IOException) {
e.printStackTrace()
}
}
@Throws(IOException::class)
private fun getExternalIPAddress(): String {
val url = URL("http://checkip.amazonaws.com/")
val connection = url.openConnection() as HttpURLConnection
return try {
BufferedReader(InputStreamReader(connection.inputStream)).use {
it.readLine()
}
} finally {
connection.disconnect()
}
}
|
const axios = require('axios')
const express = require('express');
const http = require('http');
const path = require('path')
const app = express();
app.use(express.static(path.join(__dirname, "../public")));
var router = express.Router()
app.use('/', router)
app.use(express.json())
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, "../public") + '/index.html');
});
app.post('/createTicket', async (req, res) => {
console.log(req.body);
console.log("test click");
var options = {
url: 'https://dev122250.service-now.com/api/now/table/incident',
method: 'POST',
headers: { "Accept": "application/json", "Content-Type": "application/json", "Authorization": ("Basic " + new Buffer("admin:8D-FiiP5-lZm").toString('base64')) },
json: true,
data: { 'short_description': "Ticket from MIT", 'description': 'Creating incident through Request', 'assignment_group': '', 'urgency': '2', 'impact': '2', "severity": "2" }
};
const response = await axios(options)
console.log(response);
let loc = response.headers.location
//console.log(loc);
let locArr = loc.split("/")
let id = locArr[locArr.length - 1]
console.log("ID in server:",id);
res.send({
"id": id
});
})
app.post("/getTicketInfo", async (req, res) => {
let ticketID = req.body.id
const response = await fetch(`https://dev122250.service-now.com/api/now/table/incident?sysparm_display_value=all&sys_id=${ticketID}`,
{ headers: { "Accept": "application/json", "Content-Type": "application/json", "Authorization": ("Basic " + new Buffer("admin:8D-FiiP5-lZm").toString('base64')) } }
)
let txt = await response.text()
let jsnDT = JSON.parse(txt);
console.log("json",jsnDT);
console.log("Comments: ",jsnDT.result[0]["comments"]["display_value"]);
let arr= jsnDT.result[0]["comments"]["display_value"].split("\n")
console.log("split message:",arr);
let message_arr=[]
let temp=[]
arr.forEach(item => {
if(item==""){
if(temp[0]!= undefined){
message_arr.push({date:temp[0].split(" - ")[0].split(" ")[0],time:temp[0].split(" - ")[0].split(" ")[1],author:temp[0].split(" - ")[1].split(" (")[0],message:temp.slice(1,temp.length),msg_type:temp[0].split(" - ")[1].split(" (")[1].replace(")","")})
temp=[]
}
}else{
temp.push(item)
}
});
console.log("message arr:",message_arr);
// res.send({
// "messages": id
// });
})
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
console.log('message: ', msg);
io.emit('chat message', msg);
});
});
server.listen(3000, () => {
console.log('Listening on *: 3000');
});
|
import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"
const Image = () => {
const data = useStaticQuery(graphql`
query {
allFile(
filter: {extension: {regex: "/(jpg)|(png)|(jpeg)/"}, name: {nin: ["background", "background2"]}}
) {
nodes {
base
childImageSharp {
fluid {
...GatsbyImageSharpFluid
}
}
}
}
}
`)
return (
<div className="image-container">
<h1>View our Destinations</h1>
<div className= "image-grid">
{data.allFile.edges.map((image, key)=> (
<Img key={key}
className="image-item"
fluid={image.node.childImageSharp.fluid}
alt={image.node.base.split('.')[0]}
/>
)
)}
</div>
</div>
)
}
export default Image
|
Content-Type: text/x-zim-wiki
Wiki-Format: zim 0.4
Creation-Date: 2016-12-03T15:47:15+01:00
====== scp ======
Created lørdag 03 december 2016
**# scp will allow you to transfer to, or download from, a remote SSH server.**
**# It works in contrast with Unix **//cp//** command **
**# So you specify where the file you want copied, to where you want the file copied to**
**# To specify the hosts filesystem **//[user] //**@ **//[host] //**: **///path/to/folder//
== Basic Examples ==
**# Copy a single file to a remote server**
$ scp //path/to/file <username>//@//<server-adress>//:///path/to/folder//
**# To copy a single file from the remote server to your home folder (ex)**
$ scp //<username>//@//<server-adress>//:///path/to/file /path/to/folder//
== Basic folder and files handling ==
**# In below examples, we'll use **//[host]//** instead of the **//<username>//@//<server-adress>//:///path/to/folder //**string**
**# You can specify multiple files in a space seperated list**
$ //file1 file2 file3 /path/to/file4 [host]//
**# Specific (all) file types**
**# Use the typical regex * (star) sorting. F.ex. all **//.txt //**files.**
$ [host]:/path/to/*.txt //path/to/folder///
**# Recursive **
**# Use **//-r//** (recursive) to download/upload all the folder content, ex.**
$ scp -r ~/path/to/folder [host]
|
import React, { useMemo, useState, useEffect, useRef } from 'react'
import { IoSearchOutline } from 'react-icons/io5'
import { useHistory } from 'react-router-dom'
import { PulseLoader, ClipLoader } from 'react-spinners';
import { useInView } from 'react-intersection-observer';
import { searchUsers, getMoreFoundUsers, getOneUser } from '../../Redux/ApiCalls'
import { LazyLoadImage } from 'react-lazy-load-image-component'
const SearchContent = () => {
const history = useHistory();
const { ref, inView } = useInView();
const myRef = useRef()
const [text, setText] = useState('')
const [query, setQuery] = useState('')
const [loading, setLoading] = useState(false)
const [searchLoad, setSearchLoad] = useState(false)
const [pageNum, setPageNum] = useState(2)
const [data, setData] = useState(null)
const [totalCount, setTotalCount] = useState(null)
useMemo(() => {
if (text && text.length > 0) {
setSearchLoad(true)
} else {
setSearchLoad(false)
setData(null)
}
}, [text])
useEffect(() => {
const timeout = setTimeout(() => setQuery(text), 200)
return () => clearTimeout(timeout)
}, [text])
useEffect(() => {
let isMounted = true;
if (query && query.length > 0) {
searchUsers(text, setSearchLoad)
.then(res => {
if (isMounted) {
setData(res.data?.items)
setTotalCount(res.data?.total_count)
setSearchLoad(false)
// mapData(res?.data?.items)
console.log(res.data || {})
res.data?.items.length > 0 && myRef.current.scrollTo(0, 0)
}
})
}
return () => { isMounted = false }
}, [query])
useEffect(() => {
if (inView) {
if (!loading && data.length < totalCount) {
setLoading(true)
getMoreFoundUsers(query, pageNum, setLoading)
.then(res => {
const current = res.data?.items
setLoading(false)
setPageNum(p => p + 1)
if (current && current.length > 0) {
setData([...data, ...current])
}
})
}
} else {
setLoading(false)
}
}, [inView])
const handleChanges = (e) => {
setText(e.target.value)
}
// const mapData = (url) => {
// const name = ''
// const followers = ''
// getOneUser(url, setSearchLoad)
// .then(res => {
// setSearchLoad(false)
// name = res.data.name
// followers = res.data.followers
// console.log(res.data.name)
// })
// return {
// name,
// followers
// }
// }
return (
<div className="search-content">
<div className={`${text && 'active'} search-btn`}>
<input type="text" onChange={handleChanges} placeholder="Search user..." />
<div className="icon-wrapper">
{
!searchLoad ?
<IoSearchOutline className="search-icon" /> :
<ClipLoader size={20} color={'#0086ff'} />
}
</div>
</div>
{data && <>
{
data.length > 0 ? <div className="found-users-wrapper">
<ul ref={myRef} className="found-users">
{
data.map((item, index) => (
<li onClick={() => history.push(`/user-repo/${item.login}`)} ref={data.length - 1 === index ? ref : null} key={index}>
<div className="user-content">
<div className="user-img">
<LazyLoadImage src={item.avatar_url} effect={'blur'} w="100%" height="100%" />
</div>
<div className="right">
<div className="user-login">
<label>Login:</label>
<span>{item.login}</span>
</div>
<div className="user-name">
<label>Name:</label>
<span>Abbosjon Nosirov</span>
</div>
</div>
</div>
<div className="user-followers">
<label>Followers:</label>
<span>23</span>
</div>
</li>
))
}
{loading && <div className="loading-wrapper">
<PulseLoader
color={'#0086ff'}
size={8}
margin={3}
speedMultiplier={0.8}
/>
</div>}
</ul>
</div> :
<p className="not-found">User not found!</p>
}
</>
}
</div>
)
}
export default SearchContent
|
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import IUser from 'src/models/IUser';
@Injectable({
providedIn: 'root'
})
export class UserService {
user: BehaviorSubject<IUser> = new BehaviorSubject<IUser>({ name: "" });
constructor() {
this.loadUserFromLocalStorage();
}
setUser(user: IUser) {
window.localStorage.setItem("user", JSON.stringify(user));
this.user.next(user);
}
private loadUserFromLocalStorage() {
const localStorageUserData = window.localStorage.getItem("user");
if (localStorageUserData) {
try {
const localUser = JSON.parse(localStorageUserData);
if (localUser) {
this.user.next({
name: localUser.name?.toString() || "",
});
}
} catch { }
}
}
}
|
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
import { ObjectId } from 'bson';
import { CreateReviewDto } from 'src/review/dto/create-review.dto';
const productId = new ObjectId().toHexString();
const fakeId = new ObjectId().toHexString();
const wrongId = 'wrongId';
const testUser = {
email: '[email protected]',
password: '118649qwe',
};
const testReview: CreateReviewDto = {
productId: productId,
name: 'Test review',
title: 'Test title',
description: 'Test description',
rating: 5,
};
describe('ReviewController (e2e)', () => {
let app: INestApplication;
let createdId: string;
let token: string;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
app.useGlobalPipes(new ValidationPipe());
await app.init();
const res = await request(app.getHttpServer())
.post('/auth/login')
.send(testUser);
token = res.body.access_token;
});
it('/review/create (POST) - success', async () => {
return request(app.getHttpServer())
.post('/review/create')
.send(testReview)
.expect(201)
.then((res) => {
createdId = res.body.id;
expect(createdId).toBeDefined();
expect(res.body).toEqual(expect.objectContaining(testReview));
});
});
it('/review/create (POST) - fail', async () => {
return request(app.getHttpServer())
.post('/review/create')
.send({
...testReview,
rating: 6,
})
.expect(400, {
statusCode: 400,
message: ['rating must not be greater than 5'],
error: 'Bad Request',
});
});
it('/review/byProduct/:productId (GET)', async () => {
return request(app.getHttpServer())
.get(`/review/byProduct/${productId}`)
.expect(200)
.then((res) => {
expect(res.body.length).toBe(1);
expect(res.body[0]).toEqual(
expect.objectContaining(testReview),
);
});
});
it('/review/byProduct/:productId (GET) - fakeId', async () => {
return request(app.getHttpServer())
.get(`/review/byProduct/${fakeId}`)
.expect(200)
.then((res) => {
expect(res.body.length).toBe(0);
});
});
it('/review/byProduct/:productId (GET) - wrongId', async () => {
return request(app.getHttpServer())
.get(`/review/byProduct/${wrongId}`)
.expect(400, {
statusCode: 400,
message: ['productId must be a mongodb id'],
error: 'Bad Request',
});
});
it('/review/:id (DELETE) - fakeId', async () => {
return request(app.getHttpServer())
.delete(`/review/${fakeId}`)
.set('Authorization', `Bearer ${token}`)
.expect(404, {
statusCode: 404,
message: 'Review not found',
error: 'Not Found',
});
});
it('/review/:id (DELETE)', async () => {
return request(app.getHttpServer())
.delete(`/review/${createdId}`)
.set('Authorization', `Bearer ${token}`)
.expect(200);
});
});
|
package com.example.bootlegekool.controller;
import com.example.bootlegekool.models.Student;
import com.example.bootlegekool.service.StudentService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1/ekool/student")
@AllArgsConstructor
public class StudentController {
@Autowired
private final StudentService studentService;
//Get a list of all students
@GetMapping(path = "/")
public List<Student> getAllStudents() {
return studentService.getAllStudents();
}
//Adding new students
@PostMapping(path = "/addStudent")
public void addStudent(@RequestBody Student student) {
studentService.addStudent(student);
}
@PutMapping(path = "/updateStudent")
public Student updateStudent(@RequestBody Student student) {
return studentService.updateStudent(student);
}
//Delete student
@DeleteMapping(path = "/deleteStudent/{studentId}")
public void deleteStudent(@PathVariable("studentId") Long studentId) {
studentService.deleteStudent(studentId);
}
}
|
#lang simply-scheme
; We specified that a set would be represented as a list with no duplicates. Now suppose we allow duplicates.
; For instance, the set {1, 2, 3} could be represented as the list (2 3 2 1 3 2 2). Design procedures element-of-
; set?, adjoin-set, union-set, and intersection-set that operate on this representation. How does the efficiency
; of each compare with the corresponding procedure for the non-duplicate representation? Are there applications for which
; you would use this representation in preference to the nonduplicate one?
(define (element-of-set? x set)
(cond ((null? set)
#f)
((equal? x (car set)) #t)
(else (element-of-set? x (cdr set)))))
(define (adjoin-set x set)
(cons x set))
(define (union-set set1 set2)
(if (equal? set2 '())
set1
(union-set (cons (car set2) set1) (cdr set2))))
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((element-of-set? (car set1) set2)
(if (element-of-set? (car set1) (cdr set1))
(intersection-set (cdr set1) set2)
(cons (car set1) (intersection-set (cdr set1) set2))))
(else (intersection-set (cdr set1) set2))))
(define set2 (list 1 2 3))
(define set1 (list 1 2 3 2 3 1))
(define set3 (list 3 4 5))
;(element-of-set? 1 set1)
;(element-of-set? 3 set1)
;(element-of-set? 7 set1)
;(adjoin-set 2 set2)
;(union-set set2 set3)
(intersection-set set2 set1)
(intersection-set set1 set2)
(intersection-set set1 set3)
(intersection-set set3 set1)
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "FirstPersonCharacterTemplate.h"
#include "PatrolPath.h"
#include "Boss.generated.h"
UCLASS()
class MYPROJECT3_API ABoss : public ACharacter
{
GENERATED_BODY()
public:
// Sets default values for this character's properties
ABoss();
UPROPERTY(EditAnywhere, Category = "AI")
class UBehaviorTree* BehaviorTree;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Stats")
float ArmourModifier = 1.f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Stats")
float Health = 300.f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Stats")
float MaxHealth = 300.f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Stats")
float DamageGiven = 45.f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Stats")
float RecoveryTime = 1.f;
UPROPERTY(EditDefaultsOnly, Category = "Spawning")
TSubclassOf<ABoss> ActorToSpawn;
/** Attack Sound */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay)
class USoundBase* AttackSound1;
/** Take Damage Sound */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay)
class USoundBase* TakeDamageSound1;
/** Body */
UPROPERTY(VisibleDefaultsOnly, Category = Mesh)
class USkeletalMeshComponent* Body;
/** Battle Cry Animation */
UPROPERTY(VisibleDefaultsOnly, Category = Mesh)
UAnimSequence* BattleCryAnim;
/** Walking Animation */
UPROPERTY(VisibleDefaultsOnly, Category = Mesh)
UAnimSequence* WalkAnim;
/** Atack Animation */
UPROPERTY(VisibleDefaultsOnly, Category = Mesh)
UAnimSequence* AttackAnim;
class UObject* BloodEffect;
/** True if the AI can hit, flase otherwise*/
bool bCanHit;
/** Handles the dalay between hits*/
FTimerHandle HitDelayTimerHandle;
/** Restets the AI's ability to hit*/
void ResetHit();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
void RayCast();
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
UFUNCTION()
void SpawnObject(FVector Loc, FRotator Rot);
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
void Damage(float damage);
void Die();
//The delegate function for handling a hit event
UFUNCTION()
void OnHit(AActor* SelfActor, AActor* OtherActor, FVector NormalImpulse, const FHitResult& Hit);
APatrolPath* GetPatrolPath();
AFirstPersonCharacterTemplate* CharacterTemplate;
float GetHealth() const;
float GetMaxHealth() const;
void SetHealth(float const newHealth);
void SetCanSeePlayer();
bool CanSeePlayer;
void SpawnInSecondRoom();
class ARiseDoor* CurrentDoor;
private:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "AI", meta = (AllowPrivateAccess = "true"))
APatrolPath* patrol_path;
class UWidgetComponent* WidgetComponent;
FTimerHandle HealthBarHandle;
int tickCounter;
FVector location;
FRotator rotation;
int NumberOfEnemies;
int Count;
TArray<AActor*> DeadActors;
};
|
import { Injectable } from '@angular/core';
import { CaptchaSettingModel } from '@wvs-play-win-workspace/shared/types';
@Injectable()
export class CaptchaService {
private readonly possibleCharacters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
private _settings: any = {};
private readonly defaults: CaptchaSettingModel = new CaptchaSettingModel();
constructor() {
this.defaults = {
text: null,
randomText: true,
randomColours: true,
width: 300,
height: 150,
colour1: null,
colour2: null,
font: 'bold 48px "Comic Sans MS", cursive, sans-serif',
};
}
static getCanvas() {
const canvas = <HTMLCanvasElement>document.getElementById('game');
return canvas.getContext('2d');
}
static _generateRandomColour() {
const a = Math.random() * 254;
const b = Math.floor(a / 8) * 8;
return 'rgb(' + b + ',' + b + ',' + b + ')';
}
static convertCanvasToImage(canvas) {
const image = new Image();
image.src = canvas.toDataURL('image/png');
return image.src;
}
public generate(string) {
const context = CaptchaService.getCanvas();
this._settings = this.defaults;
this._settings.text = string;
// if there's no text, set the flag to randomly generate some
if (string === null || string === '' || string === undefined) {
this._settings.randomText = true;
} else {
this._settings.text = string;
}
if (this._settings.randomColours) {
this._settings.colour1 = CaptchaService._generateRandomColour();
this._settings.colour2 = CaptchaService._generateRandomColour();
}
context.fillStyle = '#fff';
context.fillRect(0, 0, this._settings.width, this._settings.height);
const gradient1 = context.createLinearGradient(
0,
0,
this._settings.width,
0
);
gradient1.addColorStop(0, this._settings.colour1);
gradient1.addColorStop(1, this._settings.colour2);
context.font = this._settings.font;
context.fillStyle = gradient1;
const textWidth = context.measureText(this._settings.text).width;
context.fillText(
this._settings.text,
this._settings.width / 2 - textWidth / 2,
this._settings.height / 2
);
context.setTransform(1, 0, 0, 1, 0, 0);
const numRandomCurves = 3;
for (let i = 0; i < numRandomCurves; i++) {
this._drawRandomCurve();
}
return context;
}
public generateRandomText() {
let string = '';
const length = 5;
for (let i = 0; i < length; i++) {
string += this.possibleCharacters.charAt(
Math.floor(Math.random() * this.possibleCharacters.length)
);
}
return string;
}
private _drawRandomCurve() {
const ctx = CaptchaService.getCanvas();
const gradient1 = ctx.createLinearGradient(0, 0, this._settings.width, 0);
gradient1.addColorStop(
0,
Math.random() < 0.5 ? this._settings.colour1 : this._settings.colour2
);
gradient1.addColorStop(
1,
Math.random() < 0.5 ? this._settings.colour1 : this._settings.colour2
);
ctx.lineWidth = Math.floor(Math.random() * 4 + 2);
ctx.strokeStyle = gradient1;
ctx.beginPath();
ctx.moveTo(
Math.floor(Math.random() * this._settings.width),
Math.floor(Math.random() * this._settings.height)
);
ctx.bezierCurveTo(
Math.floor(Math.random() * this._settings.width),
Math.floor(Math.random() * this._settings.height),
Math.floor(Math.random() * this._settings.width),
Math.floor(Math.random() * this._settings.height),
Math.floor(Math.random() * this._settings.width),
Math.floor(Math.random() * this._settings.height)
);
ctx.stroke();
}
}
|
-- Licensed under: AGPLv3 --
-- GNU AFFERO GENERAL PUBLIC LICENSE --
-- Version 3, 19 November 2007 --
-- Loads the user when called, only ever needs to get called once
function LoadUser(identifier, source, new, licenseNotRequired)
local Source = source
db.retrieveUser(identifier, function(user, isJson)
if isJson then
user = json.decode(user)
end
if user.license or licenseNotRequired then
-- Creates the player class for OOP imitation and then sets a var to say which idType was used (This isn't relevant anymore)
Users[source] = CreatePlayer(source, user.permission_level, user.money, user.bank, user.identifier, user.license, user.group, user.roles or "")
Users[Source].setSessionVar('idType', 'identifier')
-- Tells other resources that a player has loaded
TriggerEvent('es:playerLoaded', Source, Users[Source])
log('User (' .. identifier .. ') loaded')
-- Sets a decorator on the client if enabled, allows some cool stuff on the client see: https://runtime.fivem.net/doc/natives/#_0xA06C969B02A97298
if(settings.defaultSettings.enableRankDecorators ~= "false")then
TriggerClientEvent('es:setPlayerDecorator', Source, 'rank', Users[Source]:getPermissions())
end
-- Sets the money "icon" on the client. This is UTF8
TriggerClientEvent('es:setMoneyIcon', Source,settings.defaultSettings.moneyIcon)
-- Sends the command suggestions to the client, this creates a neat autocomplete
for k,v in pairs(commandSuggestions) do
TriggerClientEvent('chat:addSuggestion', Source, settings.defaultSettings.commandDelimeter .. k, v.help, v.params)
end
-- If a player connected that was never on the server before then this will be triggered for other resources
if new then
TriggerEvent('es:newPlayerLoaded', Source, Users[Source])
end
else
-- Irrelevant
local license
for k,v in ipairs(GetPlayerIdentifiers(Source))do
if string.sub(v, 1, string.len("license:")) == "license:" then
license = v
break
end
end
if license then
db.updateUser(user.identifier, {license = license}, function()
LoadUser(user.identifier, Source, false)
end)
else
LoadUser(user.identifier, Source, false, true)
end
end
end)
end
-- Exported function, same as es:getPlayerFromId
function getPlayerFromId(id)
return Users[id]
end
-- Returns all EssentialMode user objects
AddEventHandler('es:getPlayers', function(cb)
cb(Users)
end)
-- This gets called whenever a user spawns for the first time in the server, it basically loads the player
function registerUser(identifier, source)
local Source = source
db.doesUserExist(identifier, function(exists)
if exists then
LoadUser(identifier, Source, false)
else
local license
for k,v in ipairs(GetPlayerIdentifiers(Source))do
if string.sub(v, 1, string.len("license:")) == "license:" then
license = v
break
end
end
db.createUser(identifier, license, function()
LoadUser(identifier, Source, true)
end)
end
end)
end
-- Allow other resources to set raw data on a player instead of using helper functions, these aren't really used often.
AddEventHandler("es:setPlayerData", function(user, k, v, cb)
if(Users[user])then
if(Users[user].get(k))then
if(k ~= "money") then
Users[user].set(k, v)
db.updateUser(Users[user].get('identifier'), {[k] = v}, function(d)
if d == true then
cb("Player data edited", true)
else
cb(d, false)
end
end)
end
if(k == "group")then
Users[user].set(k, v)
end
else
cb("Column does not exist!", false)
end
else
cb("User could not be found!", false)
end
end)
-- Same as above just easier was we know the ID already now.
AddEventHandler("es:setPlayerDataId", function(user, k, v, cb)
db.updateUser(user, {[k] = v}, function(d)
cb("Player data edited.", true)
end)
end)
-- Returns the user if all checks completed, if the first if check fails then you're in a bit of trouble
AddEventHandler("es:getPlayerFromId", function(user, cb)
if(Users)then
if(Users[user])then
cb(Users[user])
else
cb(nil)
end
else
cb(nil)
end
end)
-- Same as above but uses the DB to get a user instead of memory.
AddEventHandler("es:getPlayerFromIdentifier", function(identifier, cb)
db.retrieveUser(identifier, function(user)
cb(user)
end)
end)
-- Function to save player money to the database every 60 seconds.
local function savePlayerMoney()
SetTimeout(60000, function()
Citizen.CreateThread(function()
for k,v in pairs(Users)do
if Users[k] ~= nil then
db.updateUser(v.get('identifier'), {money = v.getMoney(), bank = v.getBank()}, function()end)
end
end
savePlayerMoney()
end)
end)
end
savePlayerMoney()
|
import { useState, useEffect } from 'react';
export interface VehicleData {
Location: string;
Timestamp: Date;
NumberPlate: string;
}
const useStationsInfo = () => {
const [vehicleDatas, setVehicleDatas] = useState<VehicleData[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchVehicleDatas = async () => {
try {
const response = await fetch('http://localhost:3000/vehicleDatas'); // Replace with your backend endpoint URL
if (!response.ok) {
throw new Error('Failed to fetch data');
}
const data = await response.json();
setVehicleDatas(data);
setLoading(false);
} catch (err: any) {
setError(err.message);
setLoading(false);
}
};
fetchVehicleDatas();
}, []);
return { vehicleDatas, loading, error };
};
export default useStationsInfo;
|
/**
* The component for moving list in the track.
*
* @author Naotoshi Fujita
* @copyright Naotoshi Fujita. All rights reserved.
*/
import { applyStyle, getRect } from '../../utils/dom';
import { between } from "../../utils/utils";
import { LOOP, FADE } from '../../constants/types';
import { RTL, TTB } from '../../constants/directions';
import { MOVING } from "../../constants/states";
const { abs } = Math;
/**
* The component for moving list in the track.
*
* @param {Splide} Splide - A Splide instance.
* @param {Object} Components - An object containing components.
*
* @return {Object} - The component object.
*/
export default ( Splide, Components ) => {
/**
* Hold the Layout component.
*
* @type {Object}
*/
let Layout;
/**
* Hold the Layout component.
*
* @type {Object}
*/
let Elements;
/**
* Store the list element.
*
* @type {Element}
*/
let list;
/**
* Whether the current direction is vertical or not.
*
* @type {boolean}
*/
const isVertical = Splide.options.direction === TTB;
/**
* Whether the slider type is FADE or not.
*
* @type {boolean}
*/
const isFade = Splide.is( FADE );
/**
* This will be true while transitioning from the last index to the first one.
*
* @type {boolean}
*/
let isLoopPending = false;
/**
* Sign for the direction. Only RTL mode uses the positive sign.
*
* @type {number}
*/
const sign = Splide.options.direction === RTL ? 1 : -1;
/**
* Track component object.
*
* @type {Object}
*/
const Track = {
/**
* Make public the sign defined locally.
*
* @type {number}
*/
sign,
/**
* Called when the component is mounted.
*/
mount() {
Elements = Components.Elements;
Layout = Components.Layout;
list = Elements.list;
},
/**
* Called after the component is mounted.
* The resize event must be registered after the Layout's one is done.
*/
mounted() {
if ( ! isFade ) {
this.jump( 0 );
Splide.on( 'mounted resize updated', () => { this.jump( Splide.index ) } );
}
},
/**
* Go to the given destination index.
* After arriving there, the track is jump to the new index without animation, mainly for loop mode.
*
* @param {number} destIndex - A destination index.
* This can be negative or greater than slides length for reaching clones.
* @param {number} newIndex - An actual new index. They are always same in Slide and Rewind mode.
* @param {boolean} silently - If true, suppress emitting events.
*/
go( destIndex, newIndex, silently ) {
const newPosition = getTrimmedPosition( destIndex );
const prevIndex = Splide.index;
// Prevent any actions while transitioning from the last index to the first one for jump.
if ( Splide.State.is( MOVING ) && isLoopPending ) {
return;
}
isLoopPending = destIndex !== newIndex;
if ( ! silently ) {
Splide.emit( 'move', newIndex, prevIndex, destIndex );
}
if ( Math.abs( newPosition - this.position ) >= 1 || isFade ) {
Components.Transition.start( destIndex, newIndex, prevIndex, this.toCoord( newPosition ), () => {
onTransitionEnd( destIndex, newIndex, prevIndex, silently );
} );
} else {
if ( destIndex !== prevIndex && Splide.options.trimSpace === 'move' ) {
Components.Controller.go( destIndex + destIndex - prevIndex, silently );
} else {
onTransitionEnd( destIndex, newIndex, prevIndex, silently );
}
}
},
/**
* Move the track to the specified index.
*
* @param {number} index - A destination index where the track jumps.
*/
jump( index ) {
this.translate( getTrimmedPosition( index ) );
},
/**
* Set the list position by CSS translate property.
*
* @param {number} position - A new position value.
*/
translate( position ) {
applyStyle( list, { transform: `translate${ isVertical ? 'Y' : 'X' }(${ position }px)` } );
},
/**
* Cancel the transition and set the list position.
* Also, loop the slider if necessary.
*/
cancel() {
if ( Splide.is( LOOP ) ) {
this.shift();
} else {
// Ensure the current position.
this.translate( this.position );
}
applyStyle( list, { transition: '' } );
},
/**
* Shift the slider if it exceeds borders on the edge.
*/
shift() {
let position = abs( this.position );
const left = abs( this.toPosition( 0 ) );
const right = abs( this.toPosition( Splide.length ) );
const innerSize = right - left;
if ( position < left ) {
position += innerSize;
} else if ( position > right ) {
position -= innerSize;
}
this.translate( sign * position );
},
/**
* Trim redundant spaces on the left or right edge if necessary.
*
* @param {number} position - Position value to be trimmed.
*
* @return {number} - Trimmed position.
*/
trim( position ) {
if ( ! Splide.options.trimSpace || Splide.is( LOOP ) ) {
return position;
}
const edge = sign * ( Layout.totalSize() - Layout.size - Layout.gap );
return between( position, edge, 0 );
},
/**
* Calculate the closest slide index from the given position.
*
* @param {number} position - A position converted to an slide index.
*
* @return {number} - The closest slide index.
*/
toIndex( position ) {
let index = 0;
let minDistance = Infinity;
Elements.getSlides( true ).forEach( Slide => {
const slideIndex = Slide.index;
const distance = abs( this.toPosition( slideIndex ) - position );
if ( distance < minDistance ) {
minDistance = distance;
index = slideIndex;
}
} );
return index;
},
/**
* Return coordinates object by the given position.
*
* @param {number} position - A position value.
*
* @return {Object} - A coordinates object.
*/
toCoord( position ) {
return {
x: isVertical ? 0 : position,
y: isVertical ? position : 0,
};
},
/**
* Calculate the track position by a slide index.
*
* @param {number} index - Slide index.
*
* @return {Object} - Calculated position.
*/
toPosition( index ) {
const position = Layout.totalSize( index ) - Layout.slideSize( index ) - Layout.gap;
return sign * ( position + this.offset( index ) );
},
/**
* Return the current offset value, considering direction.
*
* @return {number} - Offset amount.
*/
offset( index ) {
const { focus } = Splide.options;
const slideSize = Layout.slideSize( index );
if ( focus === 'center' ) {
return -( Layout.size - slideSize ) / 2;
}
return -( parseInt( focus ) || 0 ) * ( slideSize + Layout.gap );
},
/**
* Return the current position.
* This returns the correct position even while transitioning by CSS.
*
* @return {number} - Current position.
*/
get position() {
const prop = isVertical ? 'top' : 'left';
return getRect( list )[ prop ] - getRect( Elements.track )[ prop ] - Layout.padding[ prop ];
},
};
/**
* Called whenever slides arrive at a destination.
*
* @param {number} destIndex - A destination index.
* @param {number} newIndex - A new index.
* @param {number} prevIndex - A previous index.
* @param {boolean} silently - If true, suppress emitting events.
*/
function onTransitionEnd( destIndex, newIndex, prevIndex, silently ) {
applyStyle( list, { transition: '' } );
isLoopPending = false;
if ( ! isFade ) {
Track.jump( newIndex );
}
if ( ! silently ) {
Splide.emit( 'moved', newIndex, prevIndex, destIndex );
}
}
/**
* Convert index to the trimmed position.
*
* @return {number} - Trimmed position.
*/
function getTrimmedPosition( index ) {
return Track.trim( Track.toPosition( index ) );
}
return Track;
}
|
<!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>Form Test</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<div class="container">
<div class="flex-wrapper">
<form action="" name="contact-form" id="contact-form">
<a id="select-language" href="#">Español</a>
<h2 id="contact-title">Contact Information</h2>
<div class="flex-row">
<select name="salutation" id="salutation" required>
<option disabled selected value></option>
<option value="Dr.">Dr.</option>
<option value="Miss">Miss</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Ms.">Ms.</option>
<option value="Mx.">Mx.</option>
</select>
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" placeholder="First Name" required>
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" placeholder="Last Name" required>
</div>
<div class="flex-row pt-10">
<label for="address">Address</label>
<input type="text" name="address" id="address" placeholder="Address" class="w-100" required>
</div>
<div class="flex-row pt-10">
<label for="city">City</label>
<input type="text" name="city" id="city" placeholder="City" class="w-100" required>
<label for="state">State</label>
<input type="text" name="state" id="state" placeholder="State" size="4" required>
<label for="zip">Zip</label>
<input type="text" name="zip" id="zip" placeholder="Zip" size="10" required>
</div>
<div class="flex-row pb-20 pt-10">
<label for="phone">Phone Number</label>
<input type="text" name="phone" id="phone" placeholder="(000)000-0000" size="10" required>
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder="[email protected]" class="w-100" required>
</div>
<h2 id="questions-title">Questions</h2>
<label for="who" class="pb-5 strong">Who?</label>
<input type="text" name="who" id="who" placeholder="Let us know who..." required>
<label for="what" class="pt-20 pb-5 strong">What?</label>
<textarea type="text" name="what" id="what" maxlength="2000" rows="4" cols="50" placeholder="Let us know what..." required></textarea>
<div id="char-limit">*2000 Character Limit</div>
<div class="flex-row">
<div class="flex-col flex-col-70">
<span id="where-text" class="pt-20 pb-5 strong">Where?</span>
<div class="flex-row">
<label for="where_city">City</label>
<input type="text" name="where_city" id="where_city" placeholder="City" class="w-100" required>
<label for="where_state">State</label>
<input type="text" name="where_state" id="where_state" placeholder="State" size="4" required>
</div>
</div>
<div class="flex-col flex-col-30">
<label for="when" class="pt-20 pb-5 strong">When?</label>
<input type="text" name="when" id="when" size="8" required>
</div>
</div>
<div class="flex-row pt-20">
<div class="flex-col flex-col-50">
<div class="flex-row fj-left">
<span id="witness-text" class="pb-5 strong">Do you have a witness?</span>
<label class="toggleSwitch" for="witness" onclick="">
<input type="hidden" value="no" name="witness">
<input type="checkbox" name="witness" id="witness" value="yes"/>
<span>
<span class="text-no">No</span>
<span class="text-yes">Yes</span>
</span>
<a></a>
</label>
</div>
<div id="witness-details" class="flex-col" style="display: none;">
<label for="witness_firstname">Witnesses First Name</label>
<input type="text" name="witness_firstname" id="witness_firstname" placeholder="First Name" required>
<label for="witness_lastname">Witness Last Name</label>
<input type="text" name="witness_lastname" id="witness_lastname" placeholder="Last Name" required>
<label for="witness_phone">Witness Phone Number</label>
<input type="text" name="witness_phone" id="witness_phone" placeholder="(000)000-0000" size="10" required>
</div>
</div>
<div class="flex-col flex-col-50">
<div class="flex-row fj-left">
<span id="attorney-text" class="pb-5 strong">Do you have an attorney?</span>
<label class="toggleSwitch" for="attorney" onclick="">
<input type="hidden" value="no" name="attorney">
<input type="checkbox" name="attorney" id="attorney" value="yes"/>
<span>
<span class="text-no">No</span>
<span class="text-yes">Yes</span>
</span>
<a></a>
</label>
</div>
<div id="attorney-details" class="flex-col" style="display: none;">
<label for="attorney_name">Attorney Name</label>
<input type="text" name="attorney_name" id="attorney_name" placeholder="Attorney Name" required>
<label for="attorney_practicename">Attorney Practice Name</label>
<input type="text" name="attorney_practicename" id="attorney_practicename" placeholder="Practice Name" required>
<label for="attorney_website">Attorney Website</label>
<input type="text" name="attorney_website" id="attorney_website" placeholder="https://www.example.com" required>
</div>
</div>
</div>
<div class="error pt-10"><span></span></div>
<button id="submitBtn" type="submit">Submit</button>
</form>
</div>
</div>
<div id="form-data-output" style="display: none;"><button type="reset" value="Reset" onClick="window.location.reload()">RESET</button></div>
</body>
<footer>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js" integrity="sha256-eTyxS0rkjpLEo16uXTS0uVCS4815lc40K2iVpWDvdSY=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
<script src="./scripts.js"></script>
</footer>
</html>
|
import { Component, inject, OnInit } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { CartService } from '../../services/cart.service';
import { IContactForm } from '../../models/contact';
@Component({
selector: 'ng-contact-form',
standalone: true,
imports: [
MatCardModule,
MatInputModule,
ReactiveFormsModule,
MatButtonModule,
MatIconModule,
],
templateUrl: './contact-form.component.html',
styles: `
mat-card {
padding: 1rem;
}
mat-card-content {
padding: 1rem 0;
}
.contact-form {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
justify-content: center;
gap: 1rem;
}
.btn-text {
display: inline-block;
margin-left: 0.5rem;
vertical-align: baseline;
}
mat-card-actions {
justify-content: space-between;
}
`,
})
export class ContactFormComponent implements OnInit {
#fb = inject(FormBuilder);
#cart = inject(CartService);
contactForm = this.createForm();
ngOnInit(): void {
if (this.#cart.userData) {
this.contactForm.patchValue(this.#cart.userData);
}
if (this.#cart.contactConfirmed()) {
this.contactForm.disable();
}
this.contactForm.statusChanges.subscribe((status) => {
this.#cart.contactConfirmed.set(status === 'VALID');
});
}
saveInfo(disableForm: boolean = false) {
const formValue = this.contactForm.value;
this.#cart.userData = formValue;
if (disableForm) {
this.contactForm.disable();
this.#cart.contactConfirmed.set(true);
}
}
private createForm() {
return this.#fb.nonNullable.group<IContactForm>({
name: this.#fb.nonNullable.control<string>('', [
Validators.required,
Validators.minLength(2),
]),
surname: this.#fb.nonNullable.control<string>('', [
Validators.required,
Validators.minLength(2),
]),
address: this.#fb.nonNullable.control<string>('', [
Validators.required,
Validators.minLength(3),
]),
city: this.#fb.nonNullable.control<string>('', [
Validators.required,
Validators.minLength(3),
]),
country: this.#fb.nonNullable.control<string>('', [
Validators.required,
Validators.minLength(2),
Validators.maxLength(3),
]),
zip: this.#fb.nonNullable.control<string>('', [
Validators.required,
Validators.pattern(/\d{4}/),
]),
telephone: this.#fb.nonNullable.control<string>('', [
Validators.required,
Validators.pattern(/\d{8}/),
]),
});
}
}
|
//CAB301 - Assignment 2
//Tool ADT specification
using System;
using System.Text;
//Invariants: Name=!null and Number >=1
public interface ITool
{
// get the name of this tool
string Name // get the name of this tool
{
get;
}
//get the number of this tool currently available in the tool library
int Number
{
get;
}
//check if a person is in the borrower list of this tool (is holding this tool)
//Pre-condition: nil
//Post-condition: return true if the person is in the borrower list; return false otherwise. The information about this tool remains unchanged.
bool IsInBorrowerList(string personName);
//add a person to the borrower list
//Pre-condition: the borrower is not in the borrower list and Number > 0
//Post-condition: the borrower is added to the borrower list and New Number = Old Number - 1
bool AddBorrower(string personName);
//remove a borrower from the borrower list
//Pre-condition: the borrower is in the borrower list
//Post-condition: the borrower is removed from the borrower list and and new Number = old Number + 1
bool RemoveBorrower(string personName);
//Compare this tool's name to another tool's name
//Pre-condition: anotherTool =! null
//Post-condition: return -1, if this tool's name is less than another tool's name by alphabetical order
// return 0, if this tool's name equals to another tool's name by alphabetical order
// return +1, if this tool's name is greater than another tool's name by alphabetical order
int CompareTo(ITool? anotherTool);
//Return a string containing the name and the number of this tool currently in the tool library
//Pre-condition: nil
//Post-condition: A string containing the name and number of this tool is returned
string ToString();
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('contents', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->text('note')->nullable();
$table->string('type')->nullable();
$table->string('link')->nullable();
$table->longText('image')->nullable();
$table->longText('featured_image')->nullable();
$table->enum('status',['Draft','Published'])->default('Draft');
$table->longText('body')->nullable();
$table->longText('sideinfo')->nullable();
$table->string('title')->nullable();
$table->string('meta_key')->nullable();
$table->longText('meta_value')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('contents');
}
};
|
package hawkge.main.register;
import hawkge.Model;
import hawkge.event.Callable;
import hawkge.event.EventQueue;
import hawkge.main.ClearModelInterface;
import hawkge.main.IpModelInterface;
import hawkge.main.NameModelInterface;
import hawkge.network.IPAddress;
import hawkge.storage.User;
import hawkge.storage.registration.Registrator;
import hawkge.storage.registration.events.CloseRegistratorEvent;
import hawkge.storage.registration.events.RegisterUserEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
* @create on Apr 27, 2012
* @author jorisvi
*/
public class RegisterModel extends Model implements NameModelInterface, ClearModelInterface, IpModelInterface {
private String name;
private String password;
private String passwordConfirm;
private String description;
private String ip;
private JFrame registerFrame;
private JFrame login;
/**
*
* @param registerFrame a JFrame object
* @param queue an EventQueue object
* @param login a JFrame object
*/
public RegisterModel(JFrame registerFrame, JFrame login) {
super();
name = new String();
password = new String();
passwordConfirm = new String();
ip = new String();
description = new String();
this.registerFrame = registerFrame;
this.login = login;
}
/**
* Returns the a String of the discription.
* @return a string of the discription
*/
public String getDescription() {
return description;
}
/**
* Set the description.
* @param description a String object
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Returns the a String of the name.
* @return a string of the name
*/
public String getName() {
return name;
}
/**
* Set the name.
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* Returns the a String of the password.
* @return a string of the password
*/
public String getPassword() {
return password;
}
/**
* Set the password.
* @param password a String object
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Returns the a String of the confirm password.
* @return a string of the confirm password
*/
public String getPasswordConfirm() {
return passwordConfirm;
}
/**
* Set the confirm of the password.
* @param passwordConfirm
*/
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
/**
* Set the ip.
* @param ip
*/
public void setIp(String ip) {
this.ip = ip;
}
/**
* Returns the a String of the ip
* @return a string of the ip
*/
public String getIp() {
return ip;
}
/**
* Activated when the registerbutton is pressed,
* control checks of the fields.
*/
public void register() {
if (name.length() == 0) {
JOptionPane.showMessageDialog(registerFrame, "Fill in a username",
"NameField empty", JOptionPane.ERROR_MESSAGE);
} else if (password.length() == 0 || passwordConfirm.length() == 0) {
JOptionPane.showMessageDialog(registerFrame, "Fill in a password",
"PasswordField empty", JOptionPane.ERROR_MESSAGE);
} else if (ip.length() == 0) {
JOptionPane.showMessageDialog(registerFrame, "Fill a correct ip in",
"IPField empty", JOptionPane.ERROR_MESSAGE);
} else if (password.equals(passwordConfirm)) {
System.out.println(ip);
EventQueue.queue(new RegisterUserEvent(name, password, new IPAddress(ip), description, new Callable<User>() {
public void call(User user) {
EventQueue.queue(new CloseRegistratorEvent());
confirm(user);
}
}));
System.out.println("send register event"); // TODO Remove
} else {
JOptionPane.showMessageDialog(registerFrame, "Password doesn't match",
"Password fault", JOptionPane.ERROR_MESSAGE);
password = "";
passwordConfirm = "";
fireStateChanged();
}
}
/**
* Clears allFields of the registerpanel.
*/
public void clearAllFields() {
name = "";
password = "";
passwordConfirm = "";
ip = "";
description = "";
fireStateChanged();
}
/**
* Called by an callable object to confirm if the user was registrate
* @param user a User object
*/
private void confirm(User user) {
if (user != null) {
JOptionPane.showMessageDialog(registerFrame, "Registration complete",
"Registration passed", JOptionPane.INFORMATION_MESSAGE);
closeWindow();
} else {
JOptionPane.showMessageDialog(registerFrame, "Username already exists",
"Username wrong", JOptionPane.ERROR_MESSAGE);
name = "";
fireStateChanged();
}
}
public void closeWindow() {
registerFrame.dispose();
new Registrator();
login.setVisible(true);
}
}
|
#ifndef _REQUESTANDRESPONSE_
#define _REQUESTANDRESPONSE_
#include <string>
#include <vector>
#include <map>
#include <boost/noncopyable.hpp>
namespace base{
class Request : boost::noncopyable{
public:
enum Equal{
FALSE,
ALMOST,
EQUAL
};
Request(std::string &req);
int method_equal(std::string &&val);
int url_equal(std::string &&val);
int version_equal(std::string &&val);
int connection_equal(std::string &&val);
std::string get_body();
std::string get_cookie();
private:
int equal(std::string &&key, std::string &&val);
void parse(std::string &msg);
void parse_line(std::string &msg);
void parse_header(std::string &msg);
void parse_cookie();
void parse_body(std::string &msg);
std::string get_line(std::string &msg);
std::map<std::string, std::string> headers_;
std::map<std::string, std::string> cookies_;
};
class Response : boost::noncopyable{
public:
struct file_info{
file_info() : file_name("./src/html/"),
file_size(0){
;
}
std::string file_name;
off_t file_size;
};
enum SendFlag{
NONE,
BODY,
FILE
};
Response();
std::string message();
void set_status_code(int code);
void set_keep_alive();
void set_content_type(std::string &&type);
void set_body(std::string &body);
void set_file(std::string &&file_name);
void set_cookie_username(std::string &val);
void set_cookie_password(std::string &val);
bool is_send_file();
file_info file();
private:
void set_header(std::string &&key, std::string &&val);
void set_cookie(std::string &&key, std::string &&val);
int status_code_;
std::string body_;
std::map<std::string, std::string> headers_;
std::map<std::string, std::string> cookies_;
static const std::map<int , std::string> http_status_;
file_info file_info_;
int send_flag_;
};
}
#endif
|
import AddIcon from '@mui/icons-material/Add';
import RemoveIcon from '@mui/icons-material/Remove';
import { makeStyles } from '@mui/styles';
import { Box } from '@mui/system';
import PropTypes from 'prop-types';
import React from 'react';
import { useDispatch } from 'react-redux';
import { STATIC_HOST, THUMBNAIL_PLACEHOLDER } from '../../../constants/common';
import { removeFromCart, setQuantity } from '../../Cart/cartSlice';
CartItem.propTypes = {
item: PropTypes.object,
};
const useStyles = makeStyles(theme => ({
root: {
padding: '20px',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between'
},
img: {
width: '80px',
height: '80px',
borderRadius: '5px'
},
left: {
display: 'flex' ,
alignItems: 'stretch',
flexFlow: 'row nowrap'
},
name: {
display: 'inline-block',
fontSize: '16px',
fontWeight: '400',
margin: '8px 0 0 25px'
},
originalPrice: {
display: 'inline-block',
color: '#8f8f97',
textDecorationLine: 'line-through',
fontSize: '12px',
marginLeft: '5px'
},
right: {
display: 'flex',
flexFlow: 'row nowrap',
alignItems: 'center',
},
quantity: {
display: 'flex',
flexFlow: 'row nowrap',
alignItems: 'center',
padding: '3px',
},
borderSpan: {
display: 'inline-block',
padding: '3px'
},
boxCircle: {
display: 'flex',
alignItems: 'center',
flexFlow: 'row nowrap',
border: '1px solid #cfcfcf',
borderRadius: '3px',
cursor: 'pointer',
margin: '0 60px'
},
textCircle: {
display: 'inline-block',
padding: '0 10px',
margin: '0 5px',
borderLeft: '1px solid #cfcfcf',
borderRight: '1px solid #cfcfcf',
cursor: 'context-menu'
},
handlePrice: {
display: 'inline-block',
color: '#fb4c53',
fontSize: '14px',
fontWeight: 500
},
garbage: {
cursor: 'pointer',
marginLeft: '50px'
}
}))
function CartItem({item}) {
const urlGarbage = 'https://frontend.tikicdn.com/_desktop-next/static/img/icons/trash.svg'
const classes = useStyles();
const dispatch = useDispatch();
const thumbnailUrl = item.product.thumbnail ?
`${STATIC_HOST}${item.product.thumbnail?.url}` : THUMBNAIL_PLACEHOLDER;
const handleDecrease = () => {
let quantity = item.quantity;
if(quantity > 1) {
--quantity;
}
const action = setQuantity({
id: item.id,
quantity: quantity,
})
dispatch(action);
}
const handleIncrease = () => {
let quantity = item.quantity;
++quantity;
const action = setQuantity({
id: item.id,
quantity: quantity,
})
dispatch(action);
}
const handleGarbageClick = () => {
const idRemove = item.id;
const action = removeFromCart({id: idRemove})
dispatch(action);
}
const handlePrice = (price , quantity) => {
return price * quantity;
}
return (
<Box className={classes.root} mt={7}>
<Box className={classes.left}>
<img className={classes.img} src={thumbnailUrl} alt={item.product.name} />
<span className={classes.name}>{item.product.name}</span>
</Box>
<Box className={classes.right}>
{item.product.promotionPercent > 0
?
<div>
<span style={{fontWeight: 500}}>{new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(item.product.salePrice)}</span>
<span className={classes.originalPrice}>{new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(item.product.originalPrice)}</span>
</div>
: <span style={{fontWeight: 500 }}>{new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(item.product.originalPrice)}</span>
}
<div className={classes.boxCircle}>
<RemoveIcon onClick={handleDecrease}/>
<span className={classes.textCircle}>{item.quantity}</span>
<AddIcon onClick={handleIncrease}/>
</div>
<span className={classes.handlePrice}>{new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(handlePrice(item.product.salePrice, item.quantity))}</span>
<div className={classes.garbage} onClick={handleGarbageClick}>
<img src={urlGarbage} alt="garbage-img" />
</div>
{console.log(item)}
</Box>
</Box>
);
}
export default CartItem;
|
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
export default function NftCollectionSelectorDropdown(props: {
items: string[];
selected: string;
onItemClicked: (item: string) => void;
className?: string;
}) {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
className={cn("min-w-56 hover:bg-transparent", props.className)}
variant="outline"
>
Chat Room: {props.selected}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56">
<DropdownMenuGroup>
{props.items.map((item) => (
<DropdownMenuItem
key={item}
onClick={() => props.onItemClicked(item)}
>
{item}
</DropdownMenuItem>
))}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
);
}
|
"use client";
import { ref, getDownloadURL } from "firebase/storage";
import { storage } from "@/lib/firebase";
import Link from "next/link";
import Image from "next/image";
import { FormatDateTime, ReduceString } from "@/lib/functional";
import { useEffect, useState } from "react";
import { MediaDataType, ChannelDataType } from "@/types/type";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
export default function VideoItem({
videoData,
}: {
videoData: MediaDataType;
}) {
const [img, setImg] = useState<string>();
const videoImageStorageRef = ref(
storage,
`/video/thumbnails/${videoData.link}`
);
useEffect(() => {
getDownloadURL(videoImageStorageRef).then((url) => setImg(url));
}, ['']);
// const {img, channelAvatar} = Promise.all([fetchImg])
return (
<Link
href={`/watch/${videoData.link}`}
className="max-[640px]:max-w-[78vw] w-full"
>
<div className="flex gap-3 w-full items-center">
<div className="relative flex-0 w-[40%] pt-[25%] h-fit rounded-md bg-transparent">
{img ? (
<Image
alt=""
className="rounded-md bg-transparent"
fill
src={img}
priority={true}
sizes="16/9"
/>
) : (
<></>
)}
</div>
<div className="flex w-full flex-1 flex-col">
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
<p className="text-lg font-bold w-full text-start overflow-hidden">
{ReduceString({
string: videoData.title,
maxLength: 30,
})}
</p>
</TooltipTrigger>
<TooltipContent>
<p>{videoData.title}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
<div>
<p className="text-sm">{videoData.view} lượt xem</p>
<p className="text-sm">
{FormatDateTime(videoData.createdTime)}
</p>
</div>
</div>
</div>
</Link>
);
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900" rel="stylesheet" />
<!-- <link rel="stylesheet" href="css/icon-font.css" /> -->
<link rel="stylesheet" href="css/style.css" />
<link rel="shortcut icon" type="image/png" href="img/favicon.png" />
<title>Natours | Exciting tours for adventurous people</title>
</head>
<body>
<div class="navigation">
<input type="checkbox" class="navigation__checkbox" id="navi-toggle">
<label for="navi-toggle" class="navigation__button">
<span class="navigation__icon"> </span>
</label>
<div class="navigation__background"> </div>
<nav class="navigation__nav">
<ul class="navigation__list">
<li class="navigation__item"><a href="#" class="navigation__link"><span>01</span>Natours</a></li>
<li class="navigation__item"><a href="#" class="navigation__link"><span>02</span>Your benefits</a></li>
<li class="navigation__item"><a href="#" class="navigation__link"><span>03</span>Popular tours</a></li>
<li class="navigation__item"><a href="#" class="navigation__link"><span>04</span>Stories</a></li>
<li class="navigation__item"><a href="#" class="navigation__link"><span>05</span>Book now</a></li>
</ul>
</nav>
</div>
<header class="header">
<div class="header__logo-box">
<img src="img/logo-white.png" alt="Logo" class="header__logo">
</div>
<div class="header__text-box">
<h1 class="heading-primary">
<span class="heading-primary--main">Outdoors</span>
<span class="heading-primary--sub">is where life happens</span>
</h1>
<a href="#" class="btn btn--white btn--animated">Discover our tours</a>
</div>
</header>
<main>
<section class="section-about">
<div class="u-center-text u-margin-bottom-big">
<h2 class="heading-secondary">
Exciting tours for adventurous people
</h2>
</div>
<div class="row">
<div class="col-1-of-2">
<h3 class="heading-tertiary u-margin-bottom-small">
You're goign to fall in love with nature
</h3>
<p class="paragraph">Lorem ipsum dolor sit amet consectetur adipisicing elit. Asperiores sunt
doloribus illum eveniet tempore. Voluptatibus, cum eius sapiente inventore dolorum animi eum ab
ratione enim, accusamus asperiores nam aperiam voluptatem.</p>
<h3 class="heading-tertiary u-margin-bottom-small">
Live adventures like you never have before
</h3>
<p class="paragraph">Lorem ipsum dolor sit amet consectetur adipisicing elit. Asperiores sunt
doloribus illum eveniet tempore.</p>
<a href="#" class="btn-text">Learn more →</a>
</div>
<div class="col-1-of-2">
<div class="composition">
<img srcset="img/nat-1.jpg 300w, img/nat-1-large.jpg 1000w"
sizes="(max-width: 56.25em) 20vw, (max-width: 37.5em) 30vw, 300px" alt="Photo 1"
class="composition__photo composition__photo--p1" src="img/nat-1-large.jpg">
<img srcset="img/nat-2.jpg 300w, img/nat-2-large.jpg 1000w"
sizes="(max-width: 56.25em) 20vw, (max-width: 37.5em) 30vw, 300px" alt="Photo 2"
class="composition__photo composition__photo--p2" src="img/nat-2-large.jpg">
<img srcset="img/nat-3.jpg 300w, img/nat-3-large.jpg 1000w"
sizes="(max-width: 56.25em) 20vw, (max-width: 37.5em) 30vw, 300px" alt="Photo 3"
class="composition__photo composition__photo--p3" src="img/nat-3-large.jpg">
<!--
<img src="img/nat-1-large.jpg" alt="Photo 1" class="composition__photo composition__photo--p1">
<img src="img/nat-2-large.jpg" alt="Photo 2" class="composition__photo composition__photo--p2">
<img src="img/nat-3-large.jpg" alt="Photo 3" class="composition__photo composition__photo--p3">
-->
</div>
</div>
</div>
</section>
<section class="section-features">
<div class="row">
<div class="col-1-of-4">
<div class="feature-box">
<i class="icon-basic-world feature-box__icon"></i>
<h3 class="heading-tertiary">Explore the world</h3>
<p class="feature-box__text">
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</p>
</div>
</div>
<div class="col-1-of-4">
<div class="feature-box">
<i class="icon-basic-compass feature-box__icon"></i>
<h3 class="heading-tertiary">Meet nature</h3>
<p class="feature-box__text">
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</p>
</div>
</div>
<div class="col-1-of-4">
<div class="feature-box">
<i class="icon-basic-map feature-box__icon"></i>
<h3 class="heading-tertiary">Find your way</h3>
<p class="feature-box__text">
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</p>
</div>
</div>
<div class="col-1-of-4">
<div class="feature-box">
<i class="icon-basic-heart feature-box__icon"></i>
<h3 class="heading-tertiary">Live a healthier life</h3>
<p class="feature-box__text">
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</p>
</div>
</div>
</div>
</section>
<section class="section-tours" id="section-tours">
<div class="u-center-text u-margin-bottom-big">
<h2 class="heading-secondary">
Most popular tours
</h2>
</div>
<div class="row">
<div class="col-1-of-3">
<div class="card">
<div class="card__side card__side--front">
<div class="card__picture card__picture--1">
</div>
<h4 class="card__heading">
<span class="card__heading-span card__heading-span--1">
The sea explorer
</span>
</h4>
<div class="card__details" id="bookmark">
<ul>
<li>3 day tours</li>
<li>Up to 30 people</li>
<li>2 tour guides</li>
<li>Sleep in cozy hotels</li>
<li>Difficulty: easy</li>
</ul>
</div>
</div>
<div class="card__side card__side--back card__side--back-1">
<div class="card__cta">
<div class="card__price-box">
<p class="card__price-only">
Only
</p>
<p class="card__price-value">
$297
</p>
<a href="#popup" class="btn btn--white">Book now!</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-1-of-3">
<div class="card">
<div class="card__side card__side--front">
<div class="card__picture card__picture--2">
</div>
<h4 class="card__heading">
<span class="card__heading-span card__heading-span--2">
The Forest Hiker
</span>
</h4>
<div class="card__details" id="bookmark">
<ul>
<li>7 day tours</li>
<li>Up to 40 people</li>
<li>6 tour guides</li>
<li>Sleep in provided tents</li>
<li>Difficulty: medium</li>
</ul>
</div>
</div>
<div class="card__side card__side--back card__side--back-2">
<div class="card__cta">
<div class="card__price-box">
<p class="card__price-only">
Only
</p>
<p class="card__price-value">
$497
</p>
<a href="#popup" class="btn btn--white">Book now!</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-1-of-3">
<div class="card">
<div class="card__side card__side--front">
<div class="card__picture card__picture--3">
</div>
<h4 class="card__heading">
<span class="card__heading-span card__heading-span--3">
The Snow Adventurer
</span>
</h4>
<div class="card__details" id="bookmark">
<ul>
<li>5 day tours</li>
<li>Up to 15 people</li>
<li>3 tour guides</li>
<li>Sleep in provided tents</li>
<li>Difficulty: hard</li>
</ul>
</div>
</div>
<div class="card__side card__side--back card__side--back-3">
<div class="card__cta">
<div class="card__price-box">
<p class="card__price-only">
Only
</p>
<p class="card__price-value">
$897
</p>
<a href="#popup" class="btn btn--white">Book now!</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="u-center-text u-margin-top-huge">
<a href="#" class="btn btn--green">Discover all tours</a>
</div>
</section>
<section class="section-stories">
<div class="bg-video">
<video class="bg-video__content" autoplay muted loop>
<!-- videos from coverr.co -->
<source src="img/video.mp4" type="video/mp4">
<source src="img/video.webm" type="video/webm">
Your browser is not supported!
</video>
</div>
<div class="u-center-text u-margin-bottom-big">
<h2 class="heading-secondary">
We make people genuinely happy
</h2>
</div>
<div class="row">
<div class="story">
<figure class="story__shape">
<img src="img/nat-8.jpg" class="story__img" alt="Person on a tour">
<figcaption class="story__caption">
Mary Smith
</figcaption>
</figure>
<div class="story__text">
<h3 class="heading-tertiary u-margin-bottom-small">
I had the best week ever with my family.
</h3>
<p>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ab, beatae reprehenderit? Modi
doloremque rem repellat fuga.
Quasi mollitia totam iusto, harum tempora dignissimos. Atque reprehenderit quasi nesciunt
sint quisquam assumenda, harum tempora dignissimos.
</p>
</div>
</div>
</div>
<div class="row">
<div class="story">
<figure class="story__shape">
<img src="img/nat-9.jpg" class="story__img" alt="Person on a tour">
<figcaption class="story__caption">
Jack Wilson
</figcaption>
</figure>
<div class="story__text">
<h3 class="heading-tertiary u-margin-bottom-small">
Wow! My life is completely different now.
</h3>
<p>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ab, beatae reprehenderit? Modi
doloremque rem repellat fuga.
Quasi mollitia totam iusto, harum tempora dignissimos. Atque reprehenderit quasi nesciunt
sint quisquam assumenda, harum tempora dignissimos.
</p>
</div>
</div>
</div>
<div class="u-center-text u-margin-top-huge">
<a href="#" class="btn-text">Discover all tours →</a>
</div>
</section>
<section class="section-book">
<div class="row">
<div class="book">
<div class="book__form">
<form action="#" class="form">
<div class="u-margin-bottom-medium">
<h3 class="heading-secondary">
Start booking now!
</h3>
</div>
<div class="form__group">
<input id="name" type="text" class="form__input" placeholder="Full name" required>
<label for="name" class="form__label">Full name</label>
</div>
<div class="form__group">
<input id="email" type="email" class="form__input" placeholder="Email address" required>
<label for="email" class="form__label">Email address</label>
</div>
<div class="form__group u-margin-bottom-medium">
<div class="form__radio-group">
<!-- html radio button that belong to the same group need to have the same name. Only then just one can be selected. -->
<input type="radio" class="form__radio-input" id="small" name="size">
<label for="small" class="form__radio-label">
<span class="form__radio-button"></span>
Small tour group
</label>
</div>
<div class="form__radio-group">
<input type="radio" class="form__radio-input" id="large" name="size">
<label for="large" class="form__radio-label">
<span class="form__radio-button"></span>
Large tour group
</label>
</div>
</div>
<div class="form__group">
<button class="btn btn--green">Next step →</button>
</div>
</form>
</div>
</div>
</div>
</section>
</main>
<footer class="footer">
<div class="footer__logo-box">
<picture class="footer_logo">
<source srcset="img/logo-green-small-1x.png 1x, img/logo-green-small-2x.png 2x"
media="(max-width: 37.5em)">
<img srcset="img/logo-green-1x.png 1x, img/logo-green-2x.png 2x" alt="Full logo"
src="img/logo-green-2x.png">
</picture>
</div>
<div class="row">
<div class="col-1-of-2">
<div class="footer__navigation">
<ul class="footer__list">
<li class="footer__item"><a href="" class="footer__link">Company</a></li>
<li class="footer__item"><a href="" class="footer__link">Contact us</a></li>
<li class="footer__item"><a href="" class="footer__link">Careers</a></li>
<li class="footer__item"><a href="" class="footer__link">Privacy Policy</a></li>
<li class="footer__item"><a href="" class="footer__link">Terms</a></li>
</ul>
</div>
</div>
<div class="col-1-of-2">
<p class="footer__copyright">
Built by <a href="#" class="footer__link">Jonas Schmedtmann</a> for his online course <a href="#"
class="footer__link">Advanced CSS and SASS</a>. Copyright © by Jonas Schmedtmann. You are
100% allowed to use this webpage for both personal and commercial use, but NOT to claim it as your
own design. A credit to the original author, Jonas Schmedtmann, is of course highly appreciated!
</p>
</div>
</div>
</footer>
<div class="popup" id="popup">
<div class="popup__content">
<div class="popup__left">
<img src="img/nat-8.jpg" alt="Tour photo" class="popup__img">
<img src="img/nat-9.jpg" alt="Tour photo" class="popup__img">
</div>
<div class="popup__right">
<a href="#section-tours" class="popup__close">×</a>
<h2 class="heading-secondary u-margin-bottom-small">Start booking now</h2>
<h3 class="heading-tertiary u-margin-bottom-small">Important – Please read these terms before
booking.</h3>
<p class="popup__text">
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Ipsam illo incidunt assumenda amet tempora
necessitatibus odio eum, explicabo iusto. Consectetur veniam ab aliquam nemo eius odit nulla fugiat
totam ipsum? Lorem ipsum dolor sit, amet consectetur adipisicing elit. Laborum aliquam quisquam
ullam quaerat ex? Facere amet expedita in repellat? Sunt, amet. Ea incidunt aspernatur ut nihil
exercitationem? Impedit, cupiditate ab.
</p>
<a href="#" class="btn btn--green">Book now</a>
</div>
</div>
</div>
</body>
</html>
|
import 'package:dhak_dhol/data/model/genres_model.dart';
import 'package:dhak_dhol/provider/genre_provider.dart';
import 'package:dhak_dhol/utils/app_const.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../search/search_music_content.dart';
class GenreScreen extends StatefulWidget {
const GenreScreen({Key? key, this.genreTitle}) : super(key: key);
final Genres? genreTitle;
@override
State<GenreScreen> createState() => _GenreScreenState();
}
class _GenreScreenState extends State<GenreScreen> {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (BuildContext context) =>
GenreProvider(widget.genreTitle?.id ?? ''),
child: Consumer<GenreProvider>(
builder: (BuildContext context, provider, _) {
return Scaffold(
backgroundColor: AppColor.deepBlue,
appBar: AppBar(
backgroundColor: AppColor.deepBlue,
title: Text(widget.genreTitle?.name ?? ''),
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
provider.medias.isEmpty
? Center(
child: Padding(
padding: const EdgeInsets.only(top: 16.0),
child: CircularProgressIndicator(
color: Colors.white,
),
),
)
: Expanded(
child: ListView.builder(
scrollDirection: Axis.vertical,
itemCount: provider.medias.length,
itemBuilder: (context, index) {
return SearchMusicContent(
selectMusic: provider.medias.elementAt(index),
mediaList: provider.medias,
index: index,
);
},
),
),
],
),
),
);
},
),
);
}
}
|
@(qualityModel : model.QualityModel)
@import model._
@printAttributes(aspect : QualityAspect) = {
@for(attr <- qualityModel.getAttributes) {
qa = new QualityAttribute("@attr.getName().replaceAll(" ", "")", "@attr.getName()", [
@for(m <- attr.getMetrics()) {
new Metric("@m.getIdentifier()", "@m.getName()", false),
}
]);
vm.qualityAttributes.push(qa);
}
@for(asp <- aspect.getAspects()) {
@printAttributes(asp)
}
}
@main(Messages("ossmeter.index.title")) {
<section>
<div class="container box">
<div class="row">
<div class="col-md-3">
<h1>Compare</h1>
</div>
<div class="col-md-6">
<div class="row">
<div class="col-md-12 center">
<h2 style="margin:5px">Discover, <span style="color:#ff9400">Compare</span>, Adopt, Monitor</h2>
</div>
</div>
<!-- <div class="row" data-bind="foreach: projects">
<div class="col-md-4">
<div class="input-group" data-bind="css: css()">
<input type="text" class="form-control txt-search" id="project0" placeholder="Search..." data-bind="value: name">
<div class="input-group-addon" data-bind="click: $parent.removeProject">
<span class="glyphicon glyphicon-remove"></span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 center">
<button class="btn btn-default" data-bind="click: addProject, enable: projects().length < 3"><span class="glyphicon glyphicon-plus"></span> Add Project</button>
</div>
</div> -->
</div>
</div>
</div>
</section>
<section>
<div class="container box">
<div class="row">
<div class="col-md-4">
<div class="input-group">
<input type="text" class="form-control txt_search" id="project0" placeholder="Search...">
<div class="input-group-addon">
<span class="glyphicon glyphicon-remove"></span>
</div>
</div>
</div>
<div class="col-md-4">
<div class="input-group">
<input type="text" class="form-control txt_search" id="project1" placeholder="Search...">
<div class="input-group-addon">
<span class="glyphicon glyphicon-remove"></span>
</div>
</div>
</div>
<div class="col-md-4">
<div class="input-group">
<input type="text" class="form-control txt_search" id="project2" placeholder="Search...">
<div class="input-group-addon">
<span class="glyphicon glyphicon-remove"></span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button id="btn_compare" class="btn btn-primary form-control">Compare</button>
</div>
</div>
</div>
</section>
<script type="text/javascript">
$(function () {
projects = [];
$(".txt_search").autocomplete({
source: function(request, response) {
console.log("making request")
console.log(request)
jsRoutes.controllers.Application.autocomplete(request.term, true).ajax()
.success(function(result) {
console.log("success: " + result);
response($.map(result, function(item) {
return {
label: item.name,
value: item.id
}
}));
}).error(function(result) {
console.log("fail: " + result);
});
},
minLength: 2,
select : function(event, ui) {
//FIXME: Should use Play's routing
projects.push(ui.item);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
})
});
</script>
<section data-bind="visible: validProjects().length > 0">
<div class="container box">
<div class="row">
<div class="col-md-6" data-bind="visible: selectedMetrics().length > 0">
<strong>Legend</strong> <span data-bind="html: drawMainLegend()"></span>
</div>
<div class="col-md-6" data-bind="visible: selectedMetrics().length > 0">
<!-- <strong>Toolbox</strong> <a href="#">EVENTS</a> -->
</div>
</div>
<div class="row">
<!-- ko foreach: selectedMetrics -->
<div class="col-md-6">
<span data-bind="text:name"></span><span data-bind="attr:{id: 'legend-'+id}"></span>
<div class="box" data-bind="compPlot: { metric: $data, projects: $parent.projects}, attr : {id: 'plot-' + id}">
No data
</div>
</div>
<!-- /ko -->
</div>
</div>
</section>
<!-- ko foreach: qualityAttributes -->
<section data-bind="visible: $parent.validProjects().length > 0">
<div class="container box">
<div class="row" data-toggle="collapse" aria-expanded="true" data-bind="attr : { 'aria-controls' : 'div-attr-' + id, 'data-target' : '#div-attr-' + id }">
<h2 class="marginless" data-bind="text:name"></h2>
</div>
<div class="row collapse" data-bind="attr :{id : 'div-attr-' + id }">
<table class="table">
<thead>
<th>toolkit</th>
<th>metric</th>
<!-- ko foreach: $parent.validProjects() -->
<th data-bind="text: name"></th>
<!-- /ko -->
</thead>
<tbody data-bind="foreach: metrics">
<tr>
<td>
<div class="checkbox">
<input type="checkbox" value="id" data-bind="checked: selected">
</div>
</td>
<td data-bind="text: name"></td>
<!-- ko foreach: $root.validProjects() -->
<td>
<span data-bind="sparkplot: { project: $data, metric: $parent }"></span>
</td>
<!-- /ko -->
</tr>
</tbody>
</table>
</div>
</div>
</section>
<!-- /ko -->
<script type="text/javascript" src="@routes.Assets.at("js/metvis.0.1.0.js")"></script>
<script type="text/javascript" src="@routes.Assets.at("js/d3.v3.min.js")"></script>
<script type="text/javascript">
function addVisToChart(vis, chart) {
chart.draw();
chart.addVis(vis);
}
function drawMainLegend() {
// var l = $(this);
// l.empty();
var lgd = '<ul class="list-inline">';
var chart = new metvis.Chart("","");
for (var s in vm.validProjects()) {
lgd = lgd + '<li><div class="legend-box" style="background-color:' + chart.colors(s) + '"></div>' + vm.validProjects()[s].name() + '</li>';
}
lgd = lgd + "</ul>";
return lgd;
l.append(lgd);
}
$(function(){
$("#btn_compare").click(function() {
// Collect projects
if (projects.length >= 2) {
for(var p in projects) {
vm.projects.push(new Project(projects[p].value, projects[p].label, true));
}
// var p = new Project("modeling-graphiti", "Graphiti", true);
// var p2 = new Project("modeling-mmt-atl", "ATL", true);
// var p3 = new Project("modeling-acceleo", "Acceleo", true);
// vm.projects.push(p);
// vm.projects.push(p2);
// vm.projects.push(p3);
}
});
chartmap = {}
ko.bindingHandlers.compPlot = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// destroy any references to the chart when disposed
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
var metricid = valueAccessor().metric.id;
if (chartmap[metricid]) {
delete chartmap[metricid];
}
});
},
update: function(element, valueAccessor, allBindingsAccessor) {
var vacc = valueAccessor();
var metric = vacc.metric;
var projects = vacc.projects();
// This is really bad coding, but I'm tired. Can easily be generalised.
$.getJSON(getApi() + "/projects/p/" + projects[0].id() + "/m/" + metric.id, function(vis) {
vis.projectName = projects[0].name();
projects[0].metricmap[metric.id] = vis;
var chart = new metvis.Chart(jq("plot-" + metric.id), vis);
chart.height = 200;
chart.draw();
chartmap[metric.id] = chart;
if (projects[1]) {
if (projects[1].metricmap[metric.id]) {
chartmap[metric.id].addVis(projects[1].metricmap[metric.id]);
return;
}
(function(proj) {
$.getJSON(getApi() + "/projects/p/" + proj.id() + "/m/" + metric.id, function(vis) {
vis.projectName = proj.name();
chartmap[metric.id].addVis(vis);
proj.metricmap[metric.id] = vis;
// drawLegend(chartmap[metric.id], "#legend-"+metric.id)
if (projects[2]) {
if (projects[2].metricmap[metric.id]) {
chartmap[metric.id].addVis(projects[2].metricmap[metric.id]);
return;
}
(function(proj2) {
$.getJSON(getApi() + "/projects/p/" + proj2.id() + "/m/" + metric.id, function(vis) {
vis.projectName = proj2.name();
chartmap[metric.id].addVis(vis);
proj2.metricmap[metric.id] = vis;
// drawLegend(chartmap[metric.id], "#legend-"+metric.id)
});
})(projects[2]);
}
});
})(projects[1]);
}
});
}
}
ko.bindingHandlers.sparkplot = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
$(element).html("No data");
},
update: function(element, valueAccessor, allBindingsAccessor) {
// Extract info
var vacc = valueAccessor();
var project = vacc.project;
var metric = vacc.metric;
// TODO keep the sparks in memory (in the view model)
// then check the VM before invoking the API
// Grab all sparks in single query on "Compare" push
$.getJSON(getApi() + "/projects/p/" + project.id() +"/s/" + metric.id, function (data) {
$(element).html('<img src="' + getApi() + data.spark+'" class="spark" /> ' + abbreviateNumber(data.last));
});
}
};
var Project = function(id, name, valid) {
this.id = ko.observable(id);
this.name = ko.observable(name);
this.valid = ko.observable(valid);
this.metricmap = ko.observable();
this.css = function() {
return this.valid() ? "has-success" : "";
}
}
var QualityAttribute = function(id, name, metrics) {
this.id = id;
this.name = name;
this.metrics = metrics;
}
var Metric = function(id, name, selected) {
this.id = id;
this.name = name;
this.selected = ko.observable(selected);
}
var ComparisonModel = function() {
"use strict";
var self = this;
self.qualityAttributes = ko.observableArray();
self.projects = ko.observableArray();
self.validProjects = ko.computed(function() {
var val = [];
ko.utils.arrayForEach(self.projects(), function(p) {
if (p.valid()) {
val.push(p);
}
});
return val;
});
self.selectedMetrics = ko.computed(function() {
var sel = [];
ko.utils.arrayForEach(self.qualityAttributes(), function(attr){
ko.utils.arrayForEach(attr.metrics, function(m){
if (m.selected()) {
sel.push(m);
}
});
});
return sel;
});
self.removeProject = function(project) {
self.projects.remove(project);
}.bind(self);
self.addProject = function() {
self.projects.push(new Project("", "", false));
}.bind(self);
}
vm = new ComparisonModel();
@printAttributes(qualityModel)
ko.applyBindings(vm);
// Load projects from cookies
// var comp = JSON.parse($.cookie("cccc"));
// if (comp) {
// for (c in comp) {
// // Bind
// var p = new Project(comp[c].id, comp[c].name, true);
// vm.projects.push(p);
// // And populate the text boxes
// $("#project"+c).val(comp[c].name);
// }
// }
});
</script>
<script type="text/javascript" src="@routes.Assets.at("js/knockout-2.3.0.js")"></script>
}
|
<?php
/**
* Calculate a bid amount depends if can or not reveal absentee bid\asking bid
* SAM-5229: Outrageous bid alert reveals hidden high absentee bid
*
* @copyright 2019 Bidpath, Inc.
* @author Maxim Lyubetskiy
* @package com.swb.sam2
* @version SVN: $Id$
* @since 18 Jul, 2019
*
* Bidpath, Inc., 269 Mt. Hermon Road #102, Scotts Valley, CA 95066, USA
* Phone: ++1 (415) 543 5825, <[email protected]>
*/
namespace Sam\Bidding\ExcessiveBid;
use Sam\Core\Entity\Model\Auction\Status\AuctionStatusPureChecker;
use Sam\Core\Service\CustomizableClass;
/**
* Class ExcessiveBidHelper
*/
class AssumedAskingBidLiveCalculator extends CustomizableClass
{
/**
* Class instantiation method
* @return static
*/
public static function new(): static
{
return parent::_new(self::class);
}
/**
* Detect amount of asking bid, that can be revealed to user
* it should be - in that order -
* 0. actual asking, if is allowed to know its value
* a. my current max absentee bid, (I may not have an absentee bid on the lot)
* b. if there is none, the starting bid, (there may not be a starting bid on the lot,
* that’s possible on live and hybrid auctions)
* c. if there is none, the first increment (there will always be an increment defined on the account,
* auction or lot level)
* b and c calculated in $auctionLotCache->StartingBidNormalized
*
* @param float $askingBid
* @param float|null $maxBid - null means absent maxBid
* @param float $startingBid
* @param bool $isNotifyAbsenteeBidders
* @param string $absenteeBidDisplay
* @return float
*/
public function calc(
float $askingBid,
?float $maxBid,
float $startingBid,
bool $isNotifyAbsenteeBidders,
string $absenteeBidDisplay
): float {
$amount = $askingBid;
if (!$this->isActualAskingBidVisible($isNotifyAbsenteeBidders, $absenteeBidDisplay)) {
$amount = $this->detectUserKnownAskingBid($startingBid, $maxBid);
//in case amount == null\0, then we return askingBid as it contains first increment
$amount = $amount ?: $askingBid;
}
return $amount;
}
/**
* Checks, if actual asking bid value can be revealed to user
* @param bool $isNotifyAbsenteeBidders
* @param string $absenteeBidDisplay
* @return bool
*/
protected function isActualAskingBidVisible(bool $isNotifyAbsenteeBidders, string $absenteeBidDisplay): bool
{
$canReveal = !AuctionStatusPureChecker::new()->isAbsenteeBidsDisplaySetAsDoNotDisplay($absenteeBidDisplay)
|| $isNotifyAbsenteeBidders;
return $canReveal;
}
/**
* Detect amount, when we don't want to reveal actual asking bid
* @param float $startingBidNormalized
* @param float|null $maxBid - null means absent maxBid
* @return float
*/
protected function detectUserKnownAskingBid(float $startingBidNormalized, ?float $maxBid): float
{
$amount = $maxBid ?: $startingBidNormalized;
return $amount;
}
}
|
package labes.facomp.ufpa.br.meuegresso.controller.tipobolsa;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.validation.Valid;
import labes.facomp.ufpa.br.meuegresso.dto.tipobolsa.TipoBolsaDTO;
import labes.facomp.ufpa.br.meuegresso.enumeration.ResponseType;
import labes.facomp.ufpa.br.meuegresso.exceptions.InvalidRequestException;
import labes.facomp.ufpa.br.meuegresso.exceptions.UnauthorizedRequestException;
import labes.facomp.ufpa.br.meuegresso.model.TipoBolsaModel;
import labes.facomp.ufpa.br.meuegresso.service.auth.JwtService;
import labes.facomp.ufpa.br.meuegresso.service.tipobolsa.TipoBolsaService;
import lombok.RequiredArgsConstructor;
/**
* Responsável por fornecer end-points para tipo bolsa.
*
* @author Bruno Eiki
* @since 21/04/2023
* @version 1.0
*/
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/tipoBolsa")
public class TipoBolsaController {
private final TipoBolsaService tipoBolsaService;
private final ModelMapper mapper;
private final JwtService jwtService;
/**
* Endpoint responsavel por buscar todas bolsas do banco.
*
* @return {@link List<TipoBolsaDTO>} Retorna uma lista com todos os tipos de
* bolsa.
* @author Bruno Eiki
* @since 21/04/2023
*/
@GetMapping
@ResponseStatus(code = HttpStatus.OK)
@Operation(security = { @SecurityRequirement(name = "Bearer") })
public List<TipoBolsaDTO> buscarTipoBolsas() {
return mapper.map(tipoBolsaService.findAll(), new TypeToken<List<TipoBolsaDTO>>() {
}.getType());
}
/**
* Endpoint responsavel por adicionar um tipo de bolsa no banco.
*
* @param tipoBolsaDTO Estrutura de dados contendo as informações necessárias
* para
* adicionar um tipo de bolsa.
* @return {@link String} Mensagem de confirmacao.
* @author Bruno Eiki
* @since 21/04/2023
*/
@PostMapping
@ResponseStatus(code = HttpStatus.CREATED)
@Operation(security = { @SecurityRequirement(name = "Bearer") })
public String cadastrarTipoBolsa(
@RequestBody @Valid TipoBolsaDTO tipoBolsaDTO) {
TipoBolsaModel tipoBolsaModel = mapper.map(tipoBolsaDTO, TipoBolsaModel.class);
tipoBolsaService.save(tipoBolsaModel);
return ResponseType.SUCCESS_SAVE.getMessage();
}
/**
* Endpoint responsavel por atualizar um tipo de bolsa no banco.
*
* @param tipoBolsaDTO Estrutura de dados contendo as informações necessárias
* para
* atualizar um tipo bolsa.
* @return {@link String} Mensagem de confirmacao.
* @author Bruno Eiki
* @since 21/04/2023
*/
@PutMapping
@ResponseStatus(code = HttpStatus.CREATED)
@Operation(security = { @SecurityRequirement(name = "Bearer") })
public String atualizarTipoBolsa(@RequestBody @Valid TipoBolsaDTO tipoBolsaDTO, JwtAuthenticationToken token)
throws InvalidRequestException, UnauthorizedRequestException {
if (tipoBolsaService.existsByIdAndCreatedBy(tipoBolsaDTO.getId(), jwtService.getIdUsuario(token))) {
TipoBolsaModel tipoBolsaModel = mapper.map(tipoBolsaDTO, TipoBolsaModel.class);
tipoBolsaService.update(tipoBolsaModel);
return ResponseType.SUCCESS_UPDATE.getMessage();
}
throw new UnauthorizedRequestException();
}
/**
* Endpoint responsavel por deletar um tipo de bolsa no banco.
*
* @param tipoBolsaDTO Estrutura de dados contendo as informações necessárias
* para deletar um tipo de bolsa.
* @return {@link String} Mensagem de confirmacao.
* @author Bruno Eiki
* @since 21/04/2023
*/
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasRole('ADMIN')")
//@ResponseStatus(code = HttpStatus.OK)
@Operation(security = { @SecurityRequirement(name = "Bearer") })
public String deleteById(@PathVariable Integer id) {
if(tipoBolsaService.deleteById(id)){
return ResponseType.SUCCESS_DELETE.getMessage();
}
return ResponseType.FAIL_DELETE.getMessage();
}
}
|
O F E L I
Object Finite Element Library
Copyright (C) 1998 - 2023 Rachid Touzani
This file is part of OFELI.
OFELI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OFELI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with OFELI. If not, see <http://www.gnu.org/licenses/>.
Implementation of class SkMatrix
#ifndef __SKMATRIX_IMPL_H
#define __SKMATRIX_IMPL_H
#include "linear_algebra/SkMatrix.h"
#include "linear_algebra/Vect_impl.h"
#include "linear_algebra/Matrix_impl.h"
namespace OFELI {
#ifndef DOXYGEN_SHOULD_SKIP_THIS
class Mesh;
template<class T_>
SkMatrix<T_>::SkMatrix()
{
_dof = 0;
_is_diagonal = false;
}
template<class T_>
SkMatrix<T_>::SkMatrix(size_t size,
int is_diagonal)
{
_dof = 0;
_zero = 0;
_is_diagonal = is_diagonal;
_dof_type = NODE_DOF;
_nb_rows = _nb_cols = _size = size;
_ch.resize(size);
_diag.resize(_size);
_ch[0] = 0;
for (size_t i=1; i<_size; i++)
_ch[i] = _ch[i-1] + i + 1;
if (_is_diagonal) {
for (size_t i=1; i<_size; i++)
_ch[i] = _ch[i-1] + 1;
}
_length = _ch[_size-1] + 1;
_a.resize(_length);
_aU.resize(_length);
}
template<class T_>
SkMatrix<T_>::SkMatrix(Mesh& mesh,
size_t dof,
int is_diagonal)
{
_is_diagonal = is_diagonal;
setMesh(mesh,dof);
}
template<class T_>
SkMatrix<T_>::SkMatrix(const Vect<size_t> &ColHt) : _dof(0)
{
_is_diagonal = false;
_zero = 0;
_size = ColHt.size();
_ch.resize(_size,0);
for (size_t i=1; i<_size; i++)
_ch[i] = _ch[i-1] + ColHt[i];
_length = _ch[_size-1] + 1;
_a.resize(_length);
_aU.resize(_length);
_diag.resize(_size);
}
template<class T_>
SkMatrix<T_>::SkMatrix(const SkMatrix<T_>& m)
{
_is_diagonal = m._is_diagonal;
_size = m._size;
_length = m._length;
_ch.resize(_size);
_ch = m._ch;
_diag.resize(_size);
_diag = m._diag;
_a.resize(_length);
_aU.resize(_length);
_a = m._a;
_aU = m._aU;
_dof = m._dof;
_zero = static_cast<T_>(0);
}
template<class T_>
SkMatrix<T_>::~SkMatrix()
{ }
template<class T_>
void SkMatrix<T_>::setMesh(Mesh& mesh,
size_t dof)
{
_dof_type = mesh.getDOFSupport();
Matrix<T_>::init_set_mesh(mesh,dof);
if (_dof_type==NODE_DOF) {
if (dof)
_length = NodeSkyline(mesh,_ch,dof);
else
_length = NodeSkyline(mesh,_ch);
}
else if (_dof_type==SIDE_DOF) {
if (dof)
_length = SideSkyline(mesh,_ch,dof);
else
_length = SideSkyline(mesh,_ch);
}
else if (_dof_type==ELEMENT_DOF) {
if (dof)
_length = ElementSkyline(mesh,_ch,dof);
else
_length = ElementSkyline(mesh,_ch);
}
else
;
_diag.resize(_size);
_a.resize(_length);
_aU.resize(_length);
_ch[0] = 0;
for (size_t i=1; i<_size; i++)
_ch[i] += _ch[i-1];
_zero = T_(0);
}
template<class T_>
void SkMatrix<T_>::setGraph(const Vect<RC>& I,
int opt)
{ }
template<class T_>
void SkMatrix<T_>::setMesh(size_t dof,
Mesh& mesh,
int code)
{
// This is just to avoid warning on unused variable
dof = 0;
if (mesh.getDim()==0) { }
code = 0;
_theMesh = &mesh;
}
template<class T_>
void SkMatrix<T_>::setMesh(size_t dof,
size_t nb_eq,
Mesh& mesh)
{
// This is just to avoid warning on unused variable
dof = 0;
nb_eq = 0;
if (mesh.getDim()==0) { }
_theMesh = &mesh;
}
template<class T_>
void SkMatrix<T_>::setSkyline(Mesh& mesh)
{
_zero = 0;
int set_sides = mesh.SidesAreDOF();
_size = mesh.getNbEq();
_theMesh = &mesh;
if (_dof)
_size = mesh.getNbNodes();
if (set_sides) {
if (_dof) {
_size = mesh.getNbSides();
_length = SideSkyline(mesh,_ch,_dof);
}
_length = SideSkyline(mesh,_ch);
}
else {
if (_dof) {
_size = mesh.getNbNodes();
_length = SideSkyline(mesh,_ch,_dof);
}
_length = SideSkyline(mesh,_ch);
}
_diag.resize(_size);
_ch[0] = 0;
for (size_t i=1; i<_size; i++)
_ch[i] += _ch[i-1];
_a.resize(_length);
_aU.resize(_length);
}
template<class T_>
void SkMatrix<T_>::setDiag()
{
for (size_t i=0; i<_size; i++)
_diag[i] = _aU[_ch[i]];
}
template<class T_>
void SkMatrix<T_>::setDOF(size_t i)
{
_dof = i;
}
template<class T_>
void SkMatrix<T_>::set(size_t i,
size_t j,
const T_& val)
{
int k=0, l=0;
if (i>1)
k = int(j-i+_ch[i-1]-_ch[i-2]-1);
if (j>1)
l = int(i-j+_ch[j-1]-_ch[j-2]-1);
if (k>=0 && i>j)
_a[_ch[i-1]+j-i] = val;
else if (l>=0 && i<=j)
_aU[_ch[j-1]+i-j] = val;
else
throw OFELIException("In SkMatrix::Set(i,j,x): Index pair: ("+to_string(i)+"," +
to_string(j)+") not " + "compatible with skyline symmeric storage.");
}
template<class T_>
void SkMatrix<T_>::SSet(size_t i,
size_t j,
const T_& val)
{
int k=0, l=0;
if (i>1)
k = j-i+_ch[i-1]-_ch[i-2]-1;
if (j>1)
l = i-j+_ch[j-1]-_ch[j-2]-1;
if (k>=0 && i>j)
_a[_ch[i-1]+j-i] = val;
else if (l>=0 && i<=j)
_aU[_ch[j-1]+i-j] = val;
}
template<class T_>
void SkMatrix<T_>::Axpy(T_ a,
const SkMatrix<T_>& m)
{
_a += a * m._a;
_aU += a * m._aU;
}
template<class T_>
void SkMatrix<T_>::Axpy(T_ a,
const Matrix<T_>* m)
{
for (size_t i=0; i<_length; i++) {
_a[i] += a * m->_a[i];
_aU[i] += a * m->_aU[i];
}
}
template<class T_>
void SkMatrix<T_>::MultAdd(const Vect<T_>& x,
Vect<T_>& y) const
{
for (size_t i=0; i<_size; i++)
for (size_t j=0; j<_size; j++)
y[i] += operator()(i+1,j+1)*x[j];
}
template<class T_>
void SkMatrix<T_>::TMultAdd(const Vect<T_>& x,
Vect<T_>& y) const
{
cerr << "TMultAdd is not implemented for class SkMatrix" << endl;
}
template<class T_>
void SkMatrix<T_>::MultAdd(T_ a,
const Vect<T_>& x,
Vect<T_>& y) const
{
for (size_t i=0; i<_size; i++)
for (size_t j=0; j<_size; j++)
y[i] += a * operator()(i+1,j+1)*x[j];
}
template<class T_>
void SkMatrix<T_>::Mult(const Vect<T_>& x,
Vect<T_>& y) const
{
y = static_cast<T_>(0);
MultAdd(x,y);
}
template<class T_>
void SkMatrix<T_>::TMult(const Vect<T_>& x,
Vect<T_>& y) const
{
y = static_cast<T_>(0);
TMultAdd(x,y);
}
template<class T_>
void SkMatrix<T_>::add(size_t i,
size_t j,
const T_& val)
{
if (i>j)
_a[_ch[i-1]+j-i] += val;
else if (i<=j)
_aU[_ch[j-1]+i-j] += val;
}
template<class T_>
size_t SkMatrix<T_>::getColHeight(size_t i) const
{
if (i==1)
return 1;
else
return _ch[i-1]-_ch[i-2];
}
template<class T_>
T_ SkMatrix<T_>::operator()(size_t i,
size_t j) const
{
int k=0, l=0;
if (i>1)
k = int(j-i+_ch[i-1]-_ch[i-2]-1);
if (j>1)
l = int(i-j+_ch[j-1]-_ch[j-2]-1);
if (k>=0 && i>j)
return _a[_ch[i-1]+j-i];
else if (l>=0 && i<=j)
return _aU[_ch[j-1]+i-j];
else
return _zero;
}
template<class T_>
T_& SkMatrix<T_>::operator()(size_t i,
size_t j)
{
int k=0, l=0;
if (i>1)
k = int(j-i+_ch[i-1]-_ch[i-2]-1);
if (j>1)
l = int(i-j+_ch[j-1]-_ch[j-2]-1);
if (k>=0 && i>j)
return _a[_ch[i-1]+j-i];
else if (l>=0 && i<=j)
return _aU[_ch[j-1]+i-j];
else
throw OFELIException("In SkMatrix::Operator(): Index pair (" + to_string(i) + "," +
to_string(j) + ") not compatible with skyline structure");
return _temp;
}
template<class T_>
void SkMatrix<T_>::add(size_t i,
const T_& val)
{
_a[i-1] += val;
}
template<class T_>
void SkMatrix<T_>::DiagPrescribe(Mesh& mesh,
Vect<T_>& b,
const Vect<T_>& u,
int flag)
{
real_t p=0;
for (size_t l=0; l<_size; l++)
p = std::max(p,_aU[_ch[l]]);
node_loop(&mesh) {
for (size_t i=1; i<=The_node.getNbDOF(); ++i) {
if (The_node.getCode(i)>0) {
size_t ii = The_node.getDOF(i)-1;
for (size_t j=ii+1+_ch[ii-1]-_ch[ii]; j<=ii; j++) {
b[ii] = p*u[ii];
_a[_ch[ii]+j-ii] = _aU[_ch[ii]+j-ii] = 0;
}
_diag[ii] = _aU[_ch[ii]] = p;
}
}
}
}
template<class T_>
void SkMatrix<T_>::DiagPrescribe(Vect<T_>& b,
const Vect<T_>& u,
int flag)
{
real_t p=0;
for (size_t l=0; l<_size; l++)
p = std::max(p,_aU[_ch[l]]);
MESH_ND {
for (size_t i=1; i<=The_node.getNbDOF(); ++i) {
if (The_node.getCode(i)>0) {
size_t ii = The_node.getDOF(i)-1;
for (size_t j=ii+1+_ch[ii-1]-_ch[ii]; j<=ii; j++) {
b[ii] = p*u[ii];
_a[_ch[ii]+j-ii] = _aU[_ch[ii]+j-ii] = 0;
}
_diag[ii] = _aU[_ch[ii]] = p;
}
}
}
}
template<class T_>
SkMatrix<T_>& SkMatrix<T_>::operator=(const SkMatrix<T_>& m)
{
_a = m._a;
_aU = m._aU;
return *this;
}
template<class T_>
SkMatrix<T_>& SkMatrix<T_>::operator=(const T_& x)
{
for (size_t i=0; i<_length; i++)
_a[i] = _aU[i] = 0;
for (size_t i=0; i<_nb_rows; i++) {
_diag[i] = x;
set(i+1,i+1,x);
}
return *this;
}
template<class T_>
SkMatrix<T_>& SkMatrix<T_>::operator+=(const SkMatrix<T_>& m)
{
_a += m._a;
_aU += m._aU;
return *this;
}
template<class T_>
SkMatrix<T_>& SkMatrix<T_>::operator+=(const T_& x)
{
_a += x;
_aU += x;
return *this;
}
template<class T_>
SkMatrix<T_>& SkMatrix<T_>::operator*=(const T_& x)
{
_a *= x;
_aU *= x;
return *this;
}
template<class T_>
int SkMatrix<T_>::Factor()
{
return setLU();
}
template<class T_>
int SkMatrix<T_>::setLU()
{
if (_is_diagonal)
return 0;
size_t k, di, dij, i=0;
if (Abs(_aU[_ch[0]]) < OFELI_EPSMCH)
throw OFELIException("In SkMatrix::Factor(): First pivot is null.");
for (i=1; i<_size; i++) {
size_t dj = 0;
for (size_t j=di=i+1+_ch[i-1]-_ch[i]; j<i; j++) {
if (j>0)
dj = j+1+_ch[j-1]-_ch[j];
dij = std::max(di,dj);
for (k=0; k<j-dij; k++)
_a[_ch[i]+j-i] -= _a[_ch[i]+dij+k-i]*_aU[_ch[j]+dij+k-j];
_a[_ch[i]+j-i] /= _aU[_ch[j]];
for (k=0; k<j-dij; k++)
_aU[_ch[i]+j-i] -= _a[_ch[j]+dij+k-j]*_aU[_ch[i]+dij+k-i];
}
for (k=0; k<i-di; k++)
_aU[_ch[i]] -= _a[_ch[i]+k+di-i]*_aU[_ch[i]+k+di-i];
if (Abs(_aU[_ch[i]]) < OFELI_EPSMCH)
throw OFELIException("In SkMatrix::Factor(): " + to_string(i+1) + "-th pivot is null.");
}
return 0;
}
template<class T_>
int SkMatrix<T_>::solve(Vect<T_>& b,
bool fact)
{
int ret = 0;
if (_is_diagonal) {
for (size_t i=0; i<_size; i++) {
if (Abs(_aU[i]) < OFELI_EPSMCH)
throw OFELIException("In SkMatrix::solve(b): " + to_string(i+1) + "-th diagonal is null.");
b[i] /= _aU[i];
}
return ret;
}
size_t di;
if (fact)
ret = setLU();
size_t i, j;
for (i=1; i<_size; i++) {
di = i+1+_ch[i-1]-_ch[i];
T_ s = 0;
for (j=0; j<i-di; j++)
s += _a[_ch[i]+di+j-i] * b[di+j];
b[i] -= s;
}
for (int k=int(_size-1); k>0; k--) {
if (Abs(_aU[_ch[k]]) < OFELI_EPSMCH)
throw OFELIException("In SkMatrix::solve(b): " + to_string(k+1) + "-th pivot is null.");
b[k] /= _aU[_ch[k]];
di = k+1+_ch[k-1]-_ch[k];
for (j=0; j<k-di; j++)
b[j+di] -= b[k] * _aU[_ch[k]+di+j-k];
}
b[0] /= _aU[_ch[0]];
return ret;
}
template<class T_>
int SkMatrix<T_>::solve(const Vect<T_>& b,
Vect<T_>& x,
bool fact)
{
x = b;
return solve(x,fact);
}
template<class T_>
int SkMatrix<T_>::solveLU(const Vect<T_>& b,
Vect<T_>& x)
{
int ret = setLU();
x = b;
if (_is_diagonal) {
for (size_t i=0; i<_size; i++)
x[i] /= _aU[i];
return 0;
}
size_t di, i, j;
for (i=1; i<_size; i++) {
di = i+1+_ch[i-1]-_ch[i];
T_ s = 0;
for (j=0; j<i-di; j++)
s += _a[_ch[i]+di+j-i] * x[di+j];
x[i] -= s;
}
for (int k=int(_size-1); k>0; k--) {
if (Abs(_aU[_ch[k]]) < OFELI_EPSMCH)
throw OFELIException("In SkMatrix::solveLU(b,x): " + to_string(k+1) + "-th pivot is null.");
x[k] /= _aU[_ch[k]];
di = k+1+_ch[k-1]-_ch[k];
for (j=0; j<k-di; j++)
x[j+di] -= b[k] * _aU[_ch[k]+di+j-k];
}
x[0] /= _aU[_ch[0]];
return ret;
}
template<class T_>
T_* SkMatrix<T_>::get() const
{
return _a;
}
template<class T_>
T_ SkMatrix<T_>::get(size_t i,
size_t j) const
{
if (i>j)
return _a[_ch[i-1]+j-i];
else
return _aU[_ch[j-1]+i-j];
}
// ASSOCIATED FUNCTIONS //
template<class T_>
Vect<T_> operator*(const SkMatrix<T_>& A,
const Vect<T_>& b)
{
Vect<T_> v(b.size());
A.Mult(b,v);
}
template<class T_>
ostream& operator<<(ostream& s,
const SkMatrix<T_>& A)
{
s.setf(ios::right|ios::scientific);
s << endl;
for (size_t i=1; i<=A.getNbRows(); i++) {
s << "\nRow " << setw(6) << i << endl;
for (size_t j=1; j<=A.getNbColumns(); j++)
s << " " << setprecision(8) << std::setfill(' ') << setw(18) << A(i,j);
s << endl;
}
return s;
}
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
} /* namespace OFELI */
#endif
|
import React, { useState, createContext } from 'react'
import { changeCssVariable } from '../../services/changeCssVariable'
export const THEME_DARK = 'dark';
export const THEME_LIGHT = 'light';
export const ThemeContext = createContext()
const ThemeProvider = ({ children, ...props }) => {
const [theme, setTheme] = useState('dark')
const change = name => {
setTheme(name)
changeCssVariable(name)
}
return (
<ThemeContext.Provider
value={{
theme,
change
}}
{...props}
>
{children}
</ThemeContext.Provider>
)
}
export default ThemeProvider
|
<script lang="ts">
import { errorMessagesOf, type VResult } from "@/lib/validation";
import type { Patient, Kouhi } from "myclinic-model";
import KouhiForm from "./KouhiForm.svelte";
import type { Hoken } from "../hoken";
import api from "@/lib/api";
import { batchFromHoken } from "../fetch-hoken-list";
import Refer from "./refer/Refer.svelte";
export let patient: Patient;
export let init: Kouhi | null;
export let onEnter: (data: Kouhi) => Promise<string[]>;
export let onClose: () => void;
let validate: () => VResult<Kouhi>;
let errors: string[] = [];
let showRefer = false;
async function doEnter() {
const vs = validate();
if( vs.isValid ){
errors = [];
const errs = await onEnter(vs.value);
if( errs.length === 0 ){
onClose();
} else {
errors = errs;
}
} else {
errors = errorMessagesOf(vs.errors);
}
}
function doClose() {
onClose();
}
async function initRefer(): Promise<Hoken[]> {
let [shahokokuhoList, koukikoureiList, roujinList, kouhiList] =
await api.listAllHoken(patient.patientId);
const hs: Hoken[] = await batchFromHoken(
shahokokuhoList,
koukikoureiList,
roujinList,
kouhiList
);
return hs;
}
async function doReferAnother() {
if (!showRefer) {
showRefer = true;
} else {
showRefer = false;
}
}
</script>
<div>
<div class="form-wrapper">
{#if showRefer}
<Refer init={initRefer} />
{/if}
<div>
{#if errors.length > 0}
<div class="error">
{#each errors as e}
<div>{e}</div>
{/each}
</div>
{/if}
<KouhiForm {patient} {init} bind:validate />
</div>
</div>
<div class="commands">
<a href="javascript:void(0)" on:click={doReferAnother}>別保険参照</a>
<button on:click={doEnter}>入力</button>
<button on:click={doClose}>キャンセル</button>
</div>
</div>
<style>
.form-wrapper {
display: flex;
gap: 10px;
}
.error {
margin: 10px 0;
color: red;
}
.commands {
display: flex;
justify-content: right;
align-items: center;
margin-top: 10px;
}
.commands * + * {
margin-left: 4px;
}
</style>
|
<template>
<b-container>
<b-row align-h="center" class="mt-4">
<h2>
Login
</h2>
</b-row>
<b-row align-h="center" class="mt-4">
<b-col cols="5" class="mt-4">
<b-row>
<label for="email">Email address:</label>
</b-row>
<b-row>
<b-form-input
id="email"
placeholder="Enter email"
v-model="email"
:state="emailValid"
>
</b-form-input>
</b-row>
<b-row align-h="start">
<b-form-invalid-feedback :state="emailValid">
Please enter a valid email
</b-form-invalid-feedback>
</b-row>
<b-row class="mt-4">
<label for="password">Password: </label>
</b-row>
<b-row>
<b-form-input type="password" id="text-password" placeholder="Enter password"
v-model="password" :state="passwordValid"
>
</b-form-input>
</b-row>
<b-form-invalid-feedback :state="passwordValid">
Please enter a password
</b-form-invalid-feedback>
<b-row>
</b-row>
<b-row align-h="center" class="mt-4" >
<b-button :disabled="!(emailValid && passwordValid)" squared size="lg"
@click="login">
LOGIN
</b-button>
</b-row>
</b-col>
</b-row>
</b-container>
</template>
<script>
import axios from 'axios'
import { api } from '../../api.js'
import { setJwt,getRole } from '../../helpers/jwt.js'
export default {
name: 'Login',
computed:{
emailValid(){
const regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return regex.test(this.email)
},
passwordValid(){
return this.password.length > 0
}
},
data() {
return {
email:'',
password:''
}
},
methods:{
reroute(){
let role = getRole()
if(role === "ROLE_PHARMACIST"){
this.$router.push('/pharmacist/')
}
else if(role === "ROLE_DERMATOLOGIST"){
this.$router.push('/dermatologist/')
}
else if(role === "ROLE_PATIENT") {
this.$router.push('/client')
}
else if(role === "ROLE_SUPPLIER") {
this.$router.push("/supplier");
}
else if (role === "ROLE_SYS_ADMIN") {
this.$router.push("/sys");
}
},
clearInput(){
this.email = ''
this.password = ''
},
login(){
let credentials = {
email: this.email,
password: this.password
}
axios.post(api.auth.login,credentials).then(res => {
setJwt(res.headers['authorization'])
this.reroute()
})
.catch(err => {
if (err.response.status === 401) {
this.$toast.error("User does not exist or is not activated.")
this.clearInput()
}
else if (err.response.status === 500) {
this.$toast.error("Server error occurred.");
}
else {
this.$toast.error("An error occurred");
}
})
}
}
}
</script>
<style>
</style>
|
import { useState } from 'react';
import BandProfileAPI from '../../apis/BandProfileAPI';
import { Link } from 'react-router-dom';
import NoBandImage from '../../assets/default/band_no_img.svg';
function BandMakingForm() {
const [bandName, setBandName] = useState<string>('');
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
//e.preventDefault();
//폼은 제출시 자동 새로고침된다
console.log(bandName, '밴드로 제출됨');
BandProfileAPI.createBand(bandName)
.then((res) => {
if (res.status === 200) {
setBandName('');
}
})
.catch((err) => {
console.log(err);
});
};
return (
<form onSubmit={handleSubmit} className='flex flex-col'>
<label className='text-lg'>만들 밴드 이름</label>
<input
value={bandName}
onChange={(e) => {
setBandName(e.target.value);
}}
className='input input-bordered mt-3'
/>
<button type='submit' className='btn btn-primary btn-sm h-10 mt-3'>
만들기
</button>
</form>
);
}
function EmptyBandProfile() {
const [bandMaking, setBandMaking] = useState<boolean>(false);
return (
<section>
<h1 className='text-bold text-2xl font-bold'>밴드 정보</h1>
<div className='grid grid-flow-row justify-center'>
<img src={NoBandImage} alt='밴드 없음' className='w-full' />
아직 밴드에 가입하지 않으셨습니다!
<Link to='/recruit/user' className='w-full'>
<button className='btn btn-sm bg-base-100 hover:bg-base-200 h-8 my-2 w-full'>
밴드 구하러 가기
</button>
</Link>
<button
onClick={() => {
setBandMaking((prev) => !prev);
}}
className='btn btn-sm bg-base-100 hover:bg-base-200 h-8 '
>
새 밴드 만들기
</button>
{bandMaking ? <BandMakingForm /> : null}
</div>
</section>
);
}
export default EmptyBandProfile;
|
using LCPCollection.Server.Context;
using LCPCollection.Server.Filters;
using LCPCollection.Server.Interfaces;
using LCPCollection.Server.RewriterRules;
using LCPCollection.Server.Services;
using LCPCollection.Server.Hubs;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Extensions.FileProviders;
using Microsoft.OpenApi.Models;
using System.Reflection;
using System.Text.Json.Serialization;
using Serilog;
using Microsoft.EntityFrameworkCore;
using LCPCollection.Server.Interfaces.Auth;
using LCPCollection.Server.Services.Auth;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
//using Newtonsoft.Json.Converters;
var builder = WebApplication.CreateBuilder(args);
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.CreateLogger();
builder.Logging.ClearProviders();
builder.Logging.AddSerilog(logger);
if (builder.Configuration["DBMode"]!.Contains("SQLite", StringComparison.InvariantCultureIgnoreCase))
{
builder.Services.AddDbContext<DBContext, DBContextSQLite>();
}
else if (builder.Configuration["DBMode"]!.Contains("PostgreSQL", StringComparison.InvariantCultureIgnoreCase))
{
builder.Services.AddDbContext<DBContext, DBContextPostgreSQL>();
}
else if (builder.Configuration["DBMode"]!.Contains("MySQL", StringComparison.InvariantCultureIgnoreCase))
{
builder.Services.AddDbContext<DBContext, DBContextMySQL>();
}
else
{
builder.Services.AddDbContext<DBContext>();
}
builder.Services.AddScoped<IAnimes, AnimesService>();
builder.Services.AddScoped<IBooks, BooksService>();
builder.Services.AddScoped<IGames, GamesService>();
builder.Services.AddScoped<IMovies, MoviesService>();
builder.Services.AddScoped<ITVSeries, TVSeriesService>();
builder.Services.AddScoped<IFilesList, FilesListService>();
builder.Services.AddScoped<ISoftwares, SoftwaresService>();
builder.Services.AddScoped<IWebsites, WebsitesService>();
builder.Services.AddScoped<ITokenService, TokenService>();
builder.Services.AddScoped<IUsers, UsersService>();
builder.Services.AddAuthentication(opt => {
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = Convert.ToBoolean(builder.Configuration["JWTConfig:ValidateAudience"]),
ValidateAudience = Convert.ToBoolean(builder.Configuration["JWTConfig:ValidateAudience"]),
ValidateLifetime = Convert.ToBoolean(builder.Configuration["JWTConfig:ValidateLifetime"]),
ValidateIssuerSigningKey = Convert.ToBoolean(builder.Configuration["JWTConfig:ValidateIssuerSigningKey"]),
ValidIssuer = builder.Configuration["JWTConfig:ValidIssuer"],
ValidAudience = builder.Configuration["JWTConfig:ValidAudience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWTConfig:IssuerSigningKey"]!))
};
});
//builder.Services.AddControllersWithViews().AddNewtonsoftJson(opts => opts.SerializerSettings.Converters.Add(new StringEnumConverter()));
builder.Services.AddControllersWithViews().AddJsonOptions(options => {
options.JsonSerializerOptions.WriteIndented = true;
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
builder.Services.AddRouting(options =>
{
options.LowercaseUrls = true;
});
builder.Services.AddRazorPages();
builder.Services.AddMvc();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "LCPCollection API",
Description = "LCPCollection API",
TermsOfService = new Uri("https://example.com/terms"),
Contact = new OpenApiContact
{
Name = "Contact",
Url = new Uri("https://example.com/contact")
},
License = new OpenApiLicense
{
Name = "License",
Url = new Uri("https://example.com/license")
}
});
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
In = ParameterLocation.Header,
Scheme = "bearer",
Description = "Please insert JWT token into field"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
// using System.Reflection;
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
options.SchemaFilter<EnumSchemaFilter>();
options.ParameterFilter<ParameterFilter>();
options.UseInlineDefinitionsForEnums();
});
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsAllowAll", builder =>
{
builder.AllowAnyMethod()
.AllowAnyOrigin()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true);
});
});
builder.Services.AddSignalR();
builder.Services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[] { "application/octet-stream" });
});
var app = builder.Build();
var isMigServiceScopeEnabled = false;
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
if(isMigServiceScopeEnabled)
{
using (var serviceScope = app.Services.CreateScope())
{
var dbContext = serviceScope.ServiceProvider.GetRequiredService<DBContext>();
await dbContext.Database.MigrateAsync();
// or dbContext.Database.EnsureCreatedAsync();
}
}
app.UseSwagger(options =>
{
options.SerializeAsV2 = false;
});
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
options.EnablePersistAuthorization();
});
app.UseWebAssemblyDebugging();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
app.UseResponseCompression();
}
app.UseRewriter(new RewriteOptions().Add(new RedirectLowerCaseRule()));
app.UseCors("CorsAllowAll");
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "Uploads")),
RequestPath = "/Uploads"
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
app.MapHub<ChatHub>("/chathub");
app.MapHub<DataSendHub>("/datasendhub");
app.MapFallbackToFile("index.html");
app.Run();
|
function writeFortranParameters(caseName,mesh,flowParameters,time,numMethods,logAll,p_row,p_col)
% This function writes the parameters.F90 file, which contains basic parameters that will be used in the simulation
outFile = fopen([caseName '/bin/parameters.F90'],'w');
fprintf(outFile,' integer :: nx = %d\n',mesh.nx);
fprintf(outFile,' integer :: ny = %d\n',mesh.ny);
fprintf(outFile,' integer :: nz = %d\n\n',mesh.nz);
fprintf(outFile,' real*8 :: Re = %.20fd0\n',flowParameters.Re);
fprintf(outFile,' real*8 :: Ma = %.20fd0\n',flowParameters.Ma);
fprintf(outFile,' real*8 :: Pr = %.20fd0\n',flowParameters.Pr);
fprintf(outFile,' real*8 :: T0 = %.20fd0\n',flowParameters.T0);
fprintf(outFile,' real*8 :: gamma = %.20fd0\n\n',flowParameters.gamma);
fprintf(outFile,' real*8 :: dtmax = %.20fd0\n',time.dt);
fprintf(outFile,' real*8 :: maxCFL = %.20fd0\n',time.maxCFL);
if logAll == 0
logAll = 2147483647;
end
fprintf(outFile,' integer :: logAll = %d\n', logAll);
fprintf(outFile,' integer :: nSave = %d\n', time.nStep);
if ~isfield(mesh,'trackedNorm') || ~mesh.trackedNorm
fprintf(outFile,' real*8 :: trackedNorm = 0.d0\n');
else
fprintf(outFile,' real*8 :: trackedNorm = %.20fd0\n',1/((flowParameters.gamma^2-flowParameters.gamma)*flowParameters.Ma^2));
end
switch time.control
case 'dt'
fprintf(outFile,' integer :: timeControl = 1\n');
fprintf(outFile,' integer :: qTimesInt = %d\n',time.qtimes);
fprintf(outFile,' real*8 :: qTimesReal\n\n');
fprintf(outFile,' integer :: tmaxInt = %d\n',time.tmax);
fprintf(outFile,' real*8 :: tmaxReal\n\n');
case 'cfl'
fprintf(outFile,' integer :: timeControl = 2\n');
fprintf(outFile,' integer :: qTimesInt\n');
fprintf(outFile,' real*8 :: qtimesReal = %.20fd0\n\n',time.qtimes);
fprintf(outFile,' integer :: tmaxInt\n');
fprintf(outFile,' real*8 :: tmaxReal = %.20fd0\n\n',time.tmax);
otherwise
error('Unrecognized type of time control. Use either dt or cfl')
end
switch numMethods.timeStepping
case 'RK4'
fprintf(outFile,' integer :: timeStepping = 1\n');
case 'Euler'
fprintf(outFile,' integer :: timeStepping = 2\n');
case 'SSPRK3'
fprintf(outFile,' integer :: timeStepping = 3\n');
otherwise
error('Unrecognized time stepping method')
end
if isfield(numMethods,'SFD')
fprintf(outFile,' integer :: SFD = %d\n',numMethods.SFD.type);
fprintf(outFile,' real*8 :: SFD_Delta = %.20fd0\n',numMethods.SFD.Delta);
fprintf(outFile,' real*8 :: SFD_X_val = %.20fd0\n',numMethods.SFD.X);
fprintf(outFile,' integer :: resumeMeanFlow = %d\n\n',numMethods.SFD.resume);
else
fprintf(outFile,' integer :: SFD = 0\n');
fprintf(outFile,' real*8 :: SFD_Delta = %.20fd0\n',0);
fprintf(outFile,' real*8 :: SFD_X_val = %.20fd0\n',0);
fprintf(outFile,' integer :: resumeMeanFlow = 0\n\n');
end
if ~isfield(numMethods,'spatialFilterTime') || numMethods.spatialFilterTime <= 0
fprintf(outFile,' real*8 :: FilterCharTime = %.20fd0\n',-1);
else
fprintf(outFile,' real*8 :: FilterCharTime = %.20fd0\n',numMethods.spatialFilterTime);
end
if mesh.nz == 1
dxmin = [1/min(diff(mesh.X)), 1/min(diff(mesh.Y)), 0];
else
dxmin = [1/min(diff(mesh.X)), 1/min(diff(mesh.Y)), 1/min(diff(mesh.Z))];
end
if isfield(time,'CFLignoreZ') && time.CFLignoreZ
dxmin(3) = 0;
end
fprintf(outFile,' real*8,dimension(3) :: dxmin = (/%.20fd0,%.20fd0,%.20fd0/)\n\n', dxmin(1), dxmin(2), dxmin(3));
fprintf(outFile,' integer :: p_row = %d\n',p_row);
fprintf(outFile,' integer :: p_col = %d\n',p_col);
fclose(outFile);
end
|
<div class="grid grid-cols-1 md:grid-cols-2 h-screen overflow-hidden">
<div class="general-auth h-full">
<div class="absolute right-[20%] bottom-[15%] z-20 text-white">
<div class="text-2xl font-bold">I-Recruiter</div>
<div>© {{date.getFullYear()}}.</div>
</div>
</div>
<div class="overflow-auto">
<div class="flex items-center justify-between sticky left-0 right-0 top-0 bg-white shadow p-4">
<div class="cursor-pointer text-slate-400 hover:text-slate-600"><span><</span> Home</div>
<div class="" *ngIf="login">
Don't have an account? <span class="cursor-pointer text-blue-400 hover:text-blue-600" (click)="toggleToRegister()">Register</span>
</div>
<div class="" *ngIf="register">
Already have an account? <span class="cursor-pointer text-blue-400 hover:text-blue-600" (click)="toggleToLogin()">Login</span>
</div>
</div>
<div class="p-10 h-full flex items-center justify-center">
<div *ngIf="login">
<div class="font-bold text-2xl">IRecruiter {{status}} Login</div>
<div class="text-slate-400 text-lg mt-3">Please fill in your login details.</div>
<form action="" class="mt-3" [formGroup]="loginForm">
<div>
<div class="font-bold text-lg">Email <span class="text-red-400 font-normal">*</span></div>
<div class="mt-2"><input type="email" class="outline-none border border-black rounded p-4 min-w-[400px] w-[60%]" [ngClass]="{'border-red-400': loginForm.get('email')?.dirty && loginForm.get('email')?.invalid}" placeholder="Enter your Email" formControlName="email"> <span class="fa fa-eye-slash"></span></div>
<div *ngIf="loginForm.get('email')?.touched && loginForm.get('email')?.invalid">
<small class="text-red-400" *ngIf="loginForm.get('email')?.errors?.['required']">Email cannot be empty.</small>
<small class="text-red-400" *ngIf="loginForm.get('email')?.errors?.['email']">Invalid Email Format.</small>
</div>
</div>
<div class="mt-3">
<div class="font-bold text-lg">Password <span class="text-red-400 font-normal">*</span></div>
<div class="mt-2"><input type="password" class="outline-none border border-black rounded p-4 min-w-[400px] w-[60%]" [ngClass]="{'border-red-400': loginForm.get('password')?.dirty && loginForm.get('password')?.invalid}" placeholder="Enter your Password" formControlName="password"></div>
<div *ngIf="loginForm.get('password')?.touched && loginForm.get('password')?.invalid">
<small class="text-red-400" *ngIf="loginForm.get('password')?.errors?.['required']">Password cannot be empty.</small>
</div>
</div>
<div class="mt-5"><button [disabled]="loginForm?.invalid" class="outline-none bg-blue-400 hover:bg-blue-700 text-white rounded p-4 min-w-[400px] w-[60%]" [class.bg-blue-600]="loginForm?.valid">Login</button></div>
</form>
</div>
<div *ngIf="register">
<div class="font-bold text-2xl">IRecruiter {{status}} Registration</div>
<div class="text-slate-400 text-lg mt-3">Please fill in your details to register.</div>
<form action="" class="mt-3" [formGroup]="registrationForm">
<div>
<div class="font-bold text-lg">Full Name <span class="text-red-400 font-normal">*</span></div>
<div class="mt-2"><input type="text" class="outline-none border border-black rounded p-4 min-w-[400px] w-[60%]" [ngClass]="{'border-red-400': registrationForm.get('fullName')?.dirty && registrationForm.get('fullName')?.invalid}" formControlName="fullName"></div>
<div *ngIf="registrationForm.get('fullName')?.touched && registrationForm.get('fullName')?.invalid">
<small class="text-red-400" *ngIf="registrationForm.get('fullName')?.errors?.['required']">Full Name cannot be empty.</small>
<small class="text-red-400" *ngIf="registrationForm.get('fullName')?.errors?.['minLength']">Minimum length is 5.</small>
</div>
</div>
<div class="mt-3">
<div class="font-bold text-lg">Email <span class="text-red-400 font-normal">*</span></div>
<div class="mt-2"><input type="email" class="outline-none border border-black rounded p-4 min-w-[400px] w-[60%]" [ngClass]="{'border-red-400': registrationForm.get('email')?.dirty && registrationForm.get('email')?.invalid}" formControlName="email"></div>
<div *ngIf="registrationForm.get('email')?.touched && registrationForm.get('email')?.invalid">
<small class="text-red-400" *ngIf="registrationForm.get('email')?.errors?.['required']">Email cannot be empty.</small>
<small class="text-red-400" *ngIf="registrationForm.get('email')?.errors?.['email']">Invalid Email Format.</small>
</div>
</div>
<div class="mt-3">
<div class="font-bold text-lg">Password <span class="text-red-400 font-normal">*</span></div>
<div class="mt-2"><input type="password" class="outline-none border border-black rounded p-4 min-w-[400px] w-[60%]" [ngClass]="{'border-red-400': registrationForm.get('password')?.dirty && registrationForm.get('password')?.invalid}" formControlName="password"></div>
<div *ngIf="registrationForm.get('password')?.touched && registrationForm.get('password')?.invalid">
<small class="text-red-400" *ngIf="registrationForm.get('password')?.errors?.['required']">Password cannot be empty.</small>
<small class="text-red-400" *ngIf="registrationForm.get('password')?.errors?.['pattern']">Weak Password.</small>
</div>
</div>
<div class="mt-3">
<div class="font-bold text-lg">Confirm Password <span class="text-red-400 font-normal">*</span></div>
<div class="mt-2"><input type="password" class="outline-none border border-black rounded p-4 min-w-[400px] w-[60%]" [ngClass]="{'border-red-400': registrationForm?.errors?.['mismatch'] && registrationForm.get('confirmPassword')?.dirty}" formControlName="confirmPassword"></div>
<small class="text-red-400 block" *ngIf="registrationForm.get('confirmPassword')?.errors?.['required'] && registrationForm.get('confirmPassword')?.dirty">Confirm Password cannot be empty.</small>
<small class="text-red-400 block" *ngIf="registrationForm?.errors?.['mismatch'] && registrationForm.get('confirmPassword')?.dirty">Password Mismatch.</small>
</div>
<div class="mt-5"><input type="button" value="Register" class="outline-none bg-blue-600 hover:bg-blue-700 text-white cursor-pointer rounded p-4 min-w-[400px] w-[60%]"></div>
</form>
</div>
</div>
</div>
</div>
|
const async = require("async");
const util = require("./util.");
const socket = require('../../routes/socket.js');
const request = require('request');
const fs = require('fs');
const csv = require('csv-parser')
var csvCrawler = {
indexSource: function (config, callback) {
var data = [];
var headers = [];
var bulkStr = "";
var t0 = new Date();
async.series([
// read csv
function (callbackseries) {
csvCrawler.readCsv(config.connector, 50000, function (err, result) {
if (err)
return callbackseries(err);
data = result.data;
headers = result.headers;
return callbackseries();
})
}
,
//prepare payload
function (callbackseries) {
var totalLines = 0;
async.eachSeries(data, function (dataFetch, callbackEach) {
totalLines += dataFetch.length
dataFetch.forEach(function (line, indexedLine) {
var lineContent = "";
var record = {}
headers.forEach(function (header) {
var key = header;
var value = line[header];
if (!value)
return;
if (value == "0000-00-00")
return;
lineContent += "[#" + key + "] " + value + " [/#]"
record[key] = value;
})
record[config.schema.contentField] = lineContent;
var incrementRecordId = util.getStringHash(lineContent);
record.incrementRecordId = incrementRecordId;
var id = "R" + incrementRecordId;
if (config.incrementRecordIds.indexOf(incrementRecordId) < 0) {
bulkStr += JSON.stringify({index: {_index: config.general.indexName, _type: config.general.indexName, _id: id}}) + "\r\n"
bulkStr += JSON.stringify(record) + "\r\n";
}
})
var options = {
method: 'POST',
body: bulkStr,
encoding: null,
timeout: 1000 * 3600 * 24 * 3, //3 days //Set your timeout value in milliseconds or 0 for unlimited
headers: {
'content-type': 'application/json'
},
url: config.indexation.elasticUrl + "_bulk?refresh=wait_for"
};
request(options, function (error, response, body) {
if (error) {
return callbackEach(error)
}
const elasticRestProxy = require('../elasticRestProxy..js')
elasticRestProxy.checkBulkQueryResponse(body, function (err, result) {
if (err)
return callbackEach(err);
var message = "indexed " + totalLines + " records ";
socket.message(message);
setTimeout(function() {
elasticRestProxy.refreshIndex(config, function (err, result) {
if (err)
return callbackEach(err);
return callbackEach()
});
},5000)
})
})
}, function (err) {
if (err)
return callbackseries(err);
return callbackseries()
})
}
], function (err) {
if (err)
return callback(err);
var duration = new Date().getTime() - t0;
var message = "*** indexation done : " + data.length + " records in " + duration + " msec.";
socket.message(message)
callback(null, "done");
})
}
, generateDefaultMappingFields: function (connector, callback) {
csvCrawler.readCsv(connector, 1000000, function (err, result) {
if (err)
return callback(err);
var fields = {}
result.headers.forEach(function (header) {
if (header != "")
if (!fields[header]) {
result.data.forEach(function (line) {
if (util.isFloat(line[header]))
fields[header] = {type: "float"};
else if (util.isInt(line[header]))
fields[header] = {type: "integer"};
else
fields[header] = {type: "text"};
})
}
})
return callback(null, fields);
})
},
readCsv: function (connector, lines, callback) {
util.getCsvFileSeparator(connector.filePath, function (separator) {
var headers = [];
var jsonData = [];
var jsonDataFetch = [];
var startId = 100000
fs.createReadStream(connector.filePath)
.pipe(csv(
{
separator: separator,
mapHeaders: ({header, index}) =>
util.normalizeHeader(headers, header)
,
})
.on('header', function (header) {
headers.push(header);
})
.on('data', function (data) {
jsonDataFetch.push(data)
if (lines && jsonDataFetch.length >= lines) {
jsonData.push(jsonDataFetch);
jsonDataFetch = [];
}
})
.on('end', function () {
jsonData.push(jsonDataFetch);
return callback(null, {headers: headers, data: jsonData})
})
);
})
}
}
module.exports = csvCrawler;
|
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables, sort_child_properties_last
import 'package:sportshoses/authScreens/login_tab_page.dart';
import 'package:sportshoses/model/item.dart';
import 'package:sportshoses/pages/checkout.dart';
import 'package:sportshoses/pages/details_screen.dart';
import 'package:sportshoses/provider/cart.dart';
import 'package:sportshoses/shared/appbar.dart';
import 'package:sportshoses/shared/colors.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Home extends StatelessWidget {
//const Home({Key? key}) : super(key: key);
List<Item> items = [];
void _getInitialInfo() {
items = Item.getItems();
}
@override
Widget build(BuildContext context) {
_getInitialInfo();
final carttt = Provider.of<Cart>(context);
return Scaffold(
body: Padding(
padding: const EdgeInsets.only(top: 22),
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 2 / 2,
crossAxisSpacing: 10,
mainAxisSpacing: 20),
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Details(product: items[index]),
),
);
},
child: GridTile(
child: Padding(
padding: const EdgeInsets.all(14.0),
child: Stack(children: [
Positioned(
top: -3,
bottom: -9,
right: 0,
left: 0,
child: ClipRRect(
borderRadius: BorderRadius.circular(55),
child: Padding(
padding: const EdgeInsets.only(bottom: 20),
child: Image.asset(items[index].imgPath),
),),
),
]),
),
header: IconButton(
color: Color.fromARGB(255, 62, 94, 70),
onPressed: () {
carttt.add(items[index]);
},
icon: Icon(Icons.add)),
footer: GridTileBar(
subtitle:
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(items[index].name ,style: TextStyle(color:appbarGreen ),),
Text( "\$"+ items[index].price.toString() ,style: TextStyle(color:appbarGreen ),),
],
),
),
),
);
}),
),
drawer: Drawer(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
children: [
UserAccountsDrawerHeader(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/img/test.jpg"),
fit: BoxFit.cover),
),
currentAccountPicture: CircleAvatar(
radius: 55,
backgroundImage: AssetImage("assets/img/a.png")),
accountEmail: Text("project.com"),
accountName: Text("project",
style: TextStyle(
color: Color.fromARGB(255, 255, 255, 255),
)),
),
ListTile(
title: Text("Home"),
leading: Icon(Icons.home),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Home(),
),
);
}),
ListTile(
title: Text("My products"),
leading: Icon(Icons.add_shopping_cart),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CheckOut(),
),
);
}),
ListTile(
title: Text("Logout"),
leading: Icon(Icons.exit_to_app),
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => LoginTabPage()),);
}),
],
),
Container(
margin: EdgeInsets.only(bottom: 12),
child: Text("Developed by Group,leave it to God ©2023",
style: TextStyle(fontSize: 14)),
)
],
),
),
appBar: PreferredSize(
preferredSize: Size.fromHeight(55),
child: AppBar(
actions: [
ProductsAndPrice()
],
backgroundColor: appbarGreen,
title: Text("Home"),
)));
}
//AppBar appBar()=>
//Drawer drawer()=>
}
// leading: IconButton(
//
// color: Color.fromARGB(255, 62, 94, 70),
// onPressed: () {
// carttt.add(items[index]);
// },
// icon: Icon(Icons.add)),
// ListTile(
// title: Text("About"),
// leading: Icon(Icons.help_center),
// onTap: () {}),
|
"use strict";
// spec/routes/orders.ts
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const supertest_1 = __importDefault(require("supertest"));
const server_1 = require("../../src/server");
describe("Order Routes", () => {
let authToken; // JWT token for authentication (obtained during login)
let orderId;
let userId;
beforeAll(async () => {
const newUser = await (0, supertest_1.default)(server_1.app).post("/users").send({
firstName: "x",
lastName: "x",
username: "testuser",
password: "testpassword",
});
userId = newUser.body.userId;
authToken = newUser.body.token;
const newProduct = await (0, supertest_1.default)(server_1.app)
.post("/products")
.set("Authorization", `Bearer ${authToken}`)
.send({ name: "iphone 15", price: 1000, category: "phone" }); // Replace with valid credentials
const newOrder = await (0, supertest_1.default)(server_1.app)
.post("/orders")
.send({
productIds: [newProduct.body.productId],
quantities: [1],
userId: newUser.body.userId,
status: "active",
})
.set("Authorization", `Bearer ${authToken}`);
orderId = newOrder.body.orderId;
});
describe("GET /orders/current/:userId", () => {
it("should return a list of orders by user", async () => {
const response = await (0, supertest_1.default)(server_1.app)
.get(`/orders/current/${userId}`)
.set("Authorization", `Bearer ${authToken}`);
expect(response.status).toBe(200);
expect(response.body).toBeInstanceOf(Object);
});
it("should require authentication", async () => {
const response = await (0, supertest_1.default)(server_1.app).get("/orders/current/" + userId);
expect(response.status).toBe(401);
});
});
});
|
//
// ContentView.swift
// Moonshot
//
// Created by Roman Zherebko on 03.06.2022.
//
import SwiftUI
struct ContentView: View {
@State private var showingGrid = true
let missions: [Mission] = Bundle.main.decode("missions.json")
let astronauts: [String: Astronaut] = Bundle.main.decode("astronauts.json")
var body: some View {
NavigationView {
ScrollView {
if showingGrid {
GridLayout(missions: missions, astronauts: astronauts)
} else {
ListLayout(missions: missions, astronauts: astronauts)
}
}
.navigationTitle("Moonshot")
.background(.darkBackground)
.preferredColorScheme(.dark)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
showingGrid.toggle()
} label: {
Image(systemName: showingGrid ? "list.bullet" : "square.grid.2x2")
.foregroundColor(.primary)
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
/*
* Invite is a named function that will replace /invite commands
* @param {Object} message - The message object
*/
import { Meteor } from 'meteor/meteor';
import { TAPi18n } from 'meteor/rocketchat:tap-i18n';
import type { ISubscription, SlashCommand } from '@rocket.chat/core-typings';
import { Rooms, Subscriptions, Users } from '../../models/server';
import { slashCommands } from '../../utils/lib/slashCommand';
import { settings } from '../../settings/server';
import { api } from '../../../server/sdk/api';
function inviteAll<T extends string>(type: T): SlashCommand<T>['callback'] {
return function inviteAll(command: T, params: string, item): void {
if (!/invite\-all-(to|from)/.test(command)) {
return;
}
let channel = params.trim();
if (channel === '') {
return;
}
channel = channel.replace('#', '');
if (!channel) {
return;
}
const userId = Meteor.userId();
if (!userId) {
return;
}
const user = Users.findOneById(userId);
const lng = user?.language || settings.get('Language') || 'en';
const baseChannel = type === 'to' ? Rooms.findOneById(item.rid) : Rooms.findOneByName(channel);
const targetChannel = type === 'from' ? Rooms.findOneById(item.rid) : Rooms.findOneByName(channel);
if (!baseChannel) {
api.broadcast('notify.ephemeralMessage', userId, item.rid, {
msg: TAPi18n.__('Channel_doesnt_exist', {
postProcess: 'sprintf',
sprintf: [channel],
lng,
}),
});
return;
}
const cursor = Subscriptions.findByRoomIdWhenUsernameExists(baseChannel._id, {
fields: { 'u.username': 1 },
});
try {
const APIsettings = settings.get('API_User_Limit');
if (!APIsettings) {
return;
}
if (cursor.count() > APIsettings) {
throw new Meteor.Error('error-user-limit-exceeded', 'User Limit Exceeded', {
method: 'addAllToRoom',
});
}
const users = cursor.fetch().map((s: ISubscription) => s.u.username);
if (!targetChannel && ['c', 'p'].indexOf(baseChannel.t) > -1) {
Meteor.call(baseChannel.t === 'c' ? 'createChannel' : 'createPrivateGroup', channel, users);
api.broadcast('notify.ephemeralMessage', userId, item.rid, {
msg: TAPi18n.__('Channel_created', {
postProcess: 'sprintf',
sprintf: [channel],
lng,
}),
});
} else {
Meteor.call('addUsersToRoom', {
rid: targetChannel._id,
users,
});
}
api.broadcast('notify.ephemeralMessage', userId, item.rid, {
msg: TAPi18n.__('Users_added', { lng }),
});
return;
} catch (e: any) {
const msg = e.error === 'cant-invite-for-direct-room' ? 'Cannot_invite_users_to_direct_rooms' : e.error;
api.broadcast('notify.ephemeralMessage', userId, item.rid, {
msg: TAPi18n.__(msg, { lng }),
});
}
};
}
slashCommands.add({
command: 'invite-all-to',
callback: inviteAll('to'),
options: {
description: 'Invite_user_to_join_channel_all_to',
params: '#room',
permission: ['add-user-to-joined-room', 'add-user-to-any-c-room', 'add-user-to-any-p-room'],
},
});
slashCommands.add({
command: 'invite-all-from',
callback: inviteAll('from'),
options: {
description: 'Invite_user_to_join_channel_all_from',
params: '#room',
permission: 'add-user-to-joined-room',
},
});
module.exports = inviteAll;
|
<!DOCTYPE html>
<html lang="en" xmlns:th="http://thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Book</title>
</head>
<body>
<p th:text="${book.getBookName()}">VALUE</p>
<p th:text="${book.getBookAuthor()}">VALUE</p>
<p th:text="${book.getYearOfPublication()}">VALUE</p>
<br/>
<div th:if="${owner}">
<span>Person that has this book: </span> <span th:text="${owner.getPersonName()}">Person Name</span>
<form th:method="PATCH" th:action="@{/books/{bookId}/release(bookId=${book.getBookId()})}">
<input type="submit" value="Release the book">
</form>
</div>
<br/>
<hr/>
<div th:if="${people}">
<span>This book is free. Who do you want to assign in to?</span>
<form th:method="PATCH" th:action="@{/books/{id}/assign(id=${book.getBookId()})}">
<label for="person">Choose the person</label>
<select th:object="${person}" th:field="*{personId}" id="person">
<option th:each="person : ${people}" th:value="${person.getPersonId()}" th:text="${person.getPersonName()}">
</option>
</select>
<input type="submit" value="Assign the book"/>
</form>
</div>
<form th:method="GET" th:action="@{/books/{bookId}/edit(bookId=${book.getBookId()})}">
<input type="submit" value="Edit"/>
</form>
<form th:method="DELETE" th:action="@{/books/{bookId}(bookId=${book.getBookId()})}">
<input type="submit" value="Delete"/>
</form>
</body>
</html>
|
import * as React from 'react';
import { styled, alpha } from '@mui/material/styles';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import InputBase from '@mui/material/InputBase';
import Badge from '@mui/material/Badge';
import AccountCircle from '@mui/icons-material/AccountCircle';
import MailIcon from '@mui/icons-material/Mail';
import NotificationsIcon from '@mui/icons-material/Notifications';
import MoreIcon from '@mui/icons-material/MoreVert';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Grid from '@mui/material/Grid';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import MobileStepper from '@mui/material/MobileStepper';
import Paper from '@mui/material/Paper';
import Button from '@mui/material/Button';
import KeyboardArrowLeft from '@mui/icons-material/KeyboardArrowLeft';
import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight';
import { useTheme } from '@mui/material/styles';
import SwipeableViews from 'react-swipeable-views';
import { autoPlay } from 'react-swipeable-views-utils';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import demoData from '../../assets/demoFiles/demo.json'
const theme = createTheme();
const AutoPlaySwipeableViews = autoPlay(SwipeableViews);
const images = [
{
label: 'Image 1',
imgPath:
"https://a0.muscache.com/im/pictures/miso/Hosting-7602468/original/775720cd-cee0-44a3-aec1-6e135195ef57.jpeg?im_w=960",
},
{
label: 'Image 2',
imgPath:
"https://a0.muscache.com/im/pictures/miso/Hosting-7602468/original/06d9c082-9475-466e-bc7f-735618c32659.jpeg?im_w=480",
},
{
label: 'Image 3',
imgPath:
"https://a0.muscache.com/im/pictures/380b3d77-1a9e-423b-8f64-8189f124dccf.jpg?im_w=480",
}
];
const StyledInputBase = styled(InputBase)(({ theme }) => ({
color: 'inherit',
'& .MuiInputBase-input': {
padding: theme.spacing(1, 1, 1, 0),
// vertical padding + font size from searchIcon
paddingLeft: `calc(1em + ${theme.spacing(4)})`,
transition: theme.transitions.create('width'),
width: '100%',
[theme.breakpoints.up('md')]: {
width: '20ch',
},
},
}));
interface TabPanelProps {
children?: React.ReactNode;
dir?: string;
index: number;
value: number;
}
function TabPanel(props: TabPanelProps) {
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Box sx={{ p: 3 }}>
<Typography>{children}</Typography>
</Box>
)}
</div>
);
}
function a11yProps(index: number) {
return {
id: `simple-tab-${index}`,
'aria-controls': `simple-tabpanel-${index}`,
};
}
export default function NewRental() {
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
};
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const [mobileMoreAnchorEl, setMobileMoreAnchorEl] =
React.useState<null | HTMLElement>(null);
const isMenuOpen = Boolean(anchorEl);
const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);
const handleProfileMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget);
};
const handleMobileMenuClose = () => {
setMobileMoreAnchorEl(null);
};
const handleMenuClose = () => {
setAnchorEl(null);
handleMobileMenuClose();
};
const handleMobileMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
setMobileMoreAnchorEl(event.currentTarget);
};
const [value, setValue] = React.useState(0);
const handleChange = (event: React.SyntheticEvent, newValue: number) => {
setValue(newValue);
};
const handleChangeIndex = (index: number) => {
setValue(index);
};
const theme = useTheme();
const [activeStep, setActiveStep] = React.useState(0);
const maxSteps = images.length;
const handleNext = () => {
setActiveStep((prevActiveStep) => prevActiveStep + 1);
};
const handleBack = () => {
setActiveStep((prevActiveStep) => prevActiveStep - 1);
};
const handleStepChange = (step: number) => {
setActiveStep(step);
};
return (
<ThemeProvider theme={theme}>
<AppBar position="relative" color='transparent'>
<Toolbar>
<Typography
variant="h6"
noWrap
component="div"
sx={{ display: { xs: 'none', sm: 'block' } }}
>
vSeC Rentals
</Typography>
<Box sx={{ flexGrow: 1 }} />
<Box sx={{ display: { xs: 'none', md: 'flex' } }}>
<IconButton size="large" aria-label="show 4 new mails" color="inherit">
<Badge badgeContent={4} color="error">
<MailIcon />
</Badge>
</IconButton>
<IconButton
size="large"
aria-label="show 17 new notifications"
color="inherit"
>
<Badge badgeContent={17} color="error">
<NotificationsIcon />
</Badge>
</IconButton>
<IconButton
size="large"
edge="end"
aria-label="account of current user"
aria-haspopup="true"
onClick={handleProfileMenuOpen}
color="inherit"
>
<AccountCircle />
</IconButton>
</Box>
<Box sx={{ display: { xs: 'flex', md: 'none' } }}>
<IconButton
size="large"
aria-label="show more"
aria-haspopup="true"
onClick={handleMobileMenuOpen}
color="inherit"
>
<MoreIcon />
</IconButton>
</Box>
</Toolbar>
</AppBar>
<main>
<Grid container spacing={1}>
<Grid xs={6}>
<Box sx={{
maxWidth: 700,
flexGrow: 1,
padding: "40px 65px 10px 20px",
}}
justifyContent="center"
alignItems="center"
>
<Paper
square
elevation={0}
sx={{
display: 'flex',
alignItems: 'center',
height: 50,
pl: 2,
bgcolor: 'background.default',
}}
>
<Typography>{images[activeStep].label}</Typography>
</Paper>
<AutoPlaySwipeableViews
axis={theme.direction === 'rtl' ? 'x-reverse' : 'x'}
index={activeStep}
onChangeIndex={handleStepChange}
enableMouseEvents
>
{images.map((step, index) => (
<div key={step.label}>
{Math.abs(activeStep - index) <= 2 ? (
<Box
component="img"
sx={{
height: 455,
display: 'block',
maxWidth: 700,
overflow: 'hidden',
width: '100%',
}}
src={step.imgPath}
alt={step.label}
/>
) : null}
</div>
))}
</AutoPlaySwipeableViews>
<MobileStepper
steps={maxSteps}
position="static"
activeStep={activeStep}
nextButton={
<Button
size="small"
onClick={handleNext}
disabled={activeStep === maxSteps - 1}
>
Next
{theme.direction === 'rtl' ? (
<KeyboardArrowLeft />
) : (
<KeyboardArrowRight />
)}
</Button>
}
backButton={
<Button size="small" onClick={handleBack} disabled={activeStep === 0}>
{theme.direction === 'rtl' ? (
<KeyboardArrowRight />
) : (
<KeyboardArrowLeft />
)}
Back
</Button>
}
/>
</Box>
</Grid>
<Grid xs={3}>
<Box sx={{
bgcolor: 'background.paper',
width: 475,
margin: "40px 65px 10px 0px"
}}>
<AppBar position="static">
<Tabs
value={value}
onChange={handleChange}
indicatorColor="secondary"
textColor="inherit"
variant="fullWidth"
aria-label="full width tabs example"
>
<Tab label="Overview" {...a11yProps(0)} />
<Tab label="Available Dates" {...a11yProps(1)} />
<Tab label="Reviews" {...a11yProps(2)} />
<Tab label="Your Host" {...a11yProps(3)} />
</Tabs>
</AppBar>
<SwipeableViews
axis={theme.direction === 'rtl' ? 'x-reverse' : 'x'}
index={value}
onChangeIndex={handleChangeIndex}
>
<TabPanel value={value} index={0} dir={theme.direction}>
<Card sx={{
width: 300,
}}>
<CardContent>
<Typography sx={{ fontSize: 14 }} color="text.secondary" gutterBottom>
</Typography>
</CardContent>
</Card>
</TabPanel>
<TabPanel value={value} index={1} dir={theme.direction}>
Item Two
</TabPanel>
<TabPanel value={value} index={2} dir={theme.direction}>
Item Three
</TabPanel>
<TabPanel value={value} index={3} dir={theme.direction}>
Item Four
</TabPanel>
</SwipeableViews>
</Box>
</Grid>
<Grid xs={1}>
<Card sx={{
width: 200,
margin: "30px 30px 30px 150px",
height: "100%"
}}>
<CardContent>
<Typography sx={{ fontSize: 14 }} color="text.secondary" gutterBottom>
Total
</Typography>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
href="/Payment"
>
Go to Payment
</Button>
</CardContent>
</Card>
</Grid>
</Grid>
</main>
</ThemeProvider>
);
}
|
/**
* Copyright (c) 2008-2011 Sonatype, Inc.
* All rights reserved. Includes the third-party code listed at http://www.sonatype.com/products/nexus/attributions.
*
* This program is free software: you can redistribute it and/or modify it only under the terms of the GNU Affero General
* Public License Version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License Version 3
* for more details.
*
* You should have received a copy of the GNU Affero General Public License Version 3 along with this program. If not, see
* http://www.gnu.org/licenses.
*
* Sonatype Nexus (TM) Open Source Version is available from Sonatype, Inc. Sonatype and Sonatype Nexus are trademarks of
* Sonatype, Inc. Apache Maven is a trademark of the Apache Foundation. M2Eclipse is a trademark of the Eclipse Foundation.
* All other trademarks are the property of their respective owners.
*/
package org.sonatype.nexus.integrationtests.proxy.nexus2922;
import static org.sonatype.nexus.integrationtests.ITGroups.PROXY;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.maven.index.artifact.Gav;
import org.sonatype.nexus.integrationtests.AbstractNexusProxyIntegrationTest;
import org.sonatype.nexus.integrationtests.TestContainer;
import org.sonatype.nexus.rest.model.GlobalConfigurationResource;
import org.sonatype.nexus.test.utils.GavUtil;
import org.sonatype.nexus.test.utils.SettingsMessageUtil;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class Nexus2922CacheRemoteArtifactsIT
extends AbstractNexusProxyIntegrationTest
{
private static Gav GAV1;
private static Gav GAV2;
@Override
protected void runOnce()
throws Exception
{
TestContainer.getInstance().getTestContext().useAdminForRequests();
GlobalConfigurationResource settings = SettingsMessageUtil.getCurrentSettings();
settings.setSecurityAnonymousAccessEnabled( false );
SettingsMessageUtil.save( settings );
}
@BeforeClass(alwaysRun = true)
public void enableSecurity(){
TestContainer.getInstance().getTestContext().setSecureTest( true );
}
public Nexus2922CacheRemoteArtifactsIT()
{
super( "release-proxy-repo-1" );
GAV1 = GavUtil.newGav( "nexus2922", "artifact", "1.0.0" );
GAV2 = GavUtil.newGav( "nexus2922", "artifact", "2.0.0" );
}
protected void clearCredentials()
{
TestContainer.getInstance().getTestContext().setUsername("");
TestContainer.getInstance().getTestContext().setPassword("");
}
@Test(groups = PROXY)
public void downloadNoPriv()
throws IOException
{
String msg = null;
clearCredentials();
try
{
this.downloadArtifactFromRepository( REPO_RELEASE_PROXY_REPO1, GAV1, "target/downloads" );
Assert.fail( "Should fail to download artifact" );
}
catch ( FileNotFoundException e )
{
// ok!
msg = e.getMessage();
}
File file = new File( nexusWorkDir, "storage/release-proxy-repo-1/nexus2922/artifact/1.0.0/artifact-1.0.0.jar" );
Assert.assertFalse( file.exists(), file.toString() );
Assert.assertTrue( msg.contains( "401" ), msg );
}
@Test(groups = PROXY)
public void downloadNoPrivFromProxy()
throws IOException
{
String msg = null;
clearCredentials();
try
{
this.downloadArtifactFromRepository( REPO_TEST_HARNESS_REPO, GAV1, "target/downloads" );
Assert.fail( "Should fail to download artifact" );
}
catch ( FileNotFoundException e )
{
// ok!
msg = e.getMessage();
}
File file =
new File( nexusWorkDir, "storage/nexus-test-harness-repo/nexus2922/artifact/1.0.0/artifact-1.0.0.jar" );
Assert.assertFalse( file.exists(), file.toString() );
Assert.assertTrue( msg.contains( "401" ), msg );
}
@Test(groups = PROXY)
public void downloadAdmin()
throws Exception
{
TestContainer.getInstance().getTestContext().useAdminForRequests();
this.downloadArtifactFromRepository( REPO_RELEASE_PROXY_REPO1, GAV2, "target/downloads" );
File file = new File( nexusWorkDir, "storage/release-proxy-repo-1/nexus2922/artifact/2.0.0/artifact-2.0.0.jar" );
Assert.assertTrue( file.exists(), file.toString() );
}
}
|
package com.mahesh.interviewprogram;
import java.util.*;
import java.util.stream.Collectors;
public class StreamDemo {
public static void main(String[] args) {
{
List<Integer> integerList = Arrays.asList(-7, -1, 0, 2, -4, -3, -3, 1, 2);
Map<Boolean, List<Integer>> listMap = integerList.stream().distinct().collect(Collectors.partitioningBy(number -> number > 0));
System.out.println(listMap);
List<Employee> listEmp = new ArrayList();
listEmp.add(new Employee(1, "Mahesh", "Gurgaon"));
listEmp.add(new Employee(1, "Ramesh", "Delhi"));
listEmp.add(new Employee(1, "Suresh", "Gurgaon"));
listEmp.add(new Employee(1, "Prince", "Delhi"));
Map<String, List<Employee>> listEmpMap = listEmp.stream().collect(Collectors.groupingBy(Employee::getAddress));
System.out.println(listEmpMap);
listEmp.sort(Comparator.comparing(Employee::getName).thenComparing(Comparator.comparing(Employee::getId)));
}
}
}
class Employee {
private int Id;
private String name;
private String address;
private List<String> test;
public Employee(int id, String name, String address) {
Id = id;
this.name = name;
this.address = address;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<String> getTest() {
return test;
}
public void setTest(List<String> test) {
this.test = test;
}
@Override
public String toString() {
return "Employee{" +
"Id=" + Id +
", name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
|
MAXIMA AND MINIMA
In mathematical analysis, the maxima and minima (the respective plurals of maximum and minimum) of a function, known collectively as extrema (the plural of extremum), are the largest and smallest value of the function, either within a given range (the local or relative extrema) or on the entire domain of a function (the global or absolute extrema). Pierre de Fermat was one of the first mathematicians to propose a general technique, adequality, for finding the maxima and minima of functions.
As defined in set theory, the maximum and minimum of a set are the greatest and least elements in the set, respectively. Unbounded infinite sets, such as the set of real numbers, have no minimum or maximum.
DEFINITION
Section::::Definition.
A real-valued function f defined on a domain X has a global (or absolute) maximum point at x if f(x) ≥ f(x) for all x in X. Similarly, the function has a global (or absolute) minimum point at x if f(x) ≤ f(x) for all x in X. The value of the function at a maximum point is called the maximum value of the function and the value of the function at a minimum point is called the minimum value of the function.
If the domain X is a metric space then f is said to have a local (or relative) maximum point at the point x if there exists some ε > 0 such that f(x) ≥ f(x) for all x in X within distance ε of x. Similarly, the function has a local minimum point at x if f(x) ≤ f(x) for all x in X within distance ε of x. A similar definition can be used when X is a topological space, since the definition just given can be rephrased in terms of neighbourhoods.
In both the global and local cases, the concept of a strict extremum can be defined. For example, x is a strict global maximum point if, for all x in X with x ≠ x, we have f(x) > f(x), and x is a strict local maximum point if there exists some ε > 0 such that, for all x in X within distance ε of x with x ≠ x, we have f(x) > f(x). Note that a point is a strict global maximum point if and only if it is the unique global maximum point, and similarly for minimum points.
A continuous real-valued function with a compact domain always has a maximum point and a minimum point. An important example is a function whose domain is a closed (and bounded) interval of real numbers (see the graph above).
FINDING FUNCTIONAL MAXIMA AND MINIMA
Section::::Finding functional maxima and minima.
Finding global maxima and minima is the goal of mathematical optimization. If a function is continuous on a closed interval, then by the extreme value theorem global maxima and minima exist. Furthermore, a global maximum (or minimum) either must be a local maximum (or minimum) in the interior of the domain, or must lie on the boundary of the domain. So a method of finding a global maximum (or minimum) is to look at all the local maxima (or minima) in the interior, and also look at the maxima (or minima) of the points on the boundary, and take the largest (or smallest) one.
Local extrema of differentiable functions can be found by Fermat's theorem, which states that they must occur at critical points. One can distinguish whether a critical point is a local maximum or local minimum by using the first derivative test, second derivative test, or higher-order derivative test, given sufficient differentiability.
For any function that is defined piecewise, one finds a maximum (or minimum) by finding the maximum (or minimum) of each piece separately, and then seeing which one is largest (or smallest).
EXAMPLES
* The function x has a unique global minimum at x = 0.
* The function x has no global minima or maxima. Although the first derivative (3x) is 0 at x = 0, this is an inflection point.
* The function formula_1 has a unique global maximum at x = e. (See figure at right)
* The function x has a unique global maximum over the positive real numbers at x = 1/e.
* The function x/3 − x has first derivative x − 1 and second derivative 2x. Setting the first derivative to 0 and solving for x gives stationary points at −1 and +1. From the sign of the second derivative we can see that −1 is a local maximum and +1 is a local minimum. Note that this function has no global maximum or minimum.
* The function x has a global minimum at x = 0 that cannot be found by taking derivatives, because the derivative does not exist at x = 0.
* The function cos(x) has infinitely many global maxima at 0, ±2, ±4, ..., and infinitely many global minima at ±π, ±3π, ….
* The function 2 cos(x) − x has infinitely many local maxima and minima, but no global maximum or minimum.
* The function cos(3x)/x with 0.1 ≤ x ≤ 1.1 has a global maximum at x = 0.1 (a boundary), a global minimum near x = 0.3, a local maximum near x = 0.6, and a local minimum near x = 1.0. (See figure at top of page.)
* The function x + 3x − 2x + 1 defined over the closed interval (segment) [−4,2] has a local and maximum at x = −1−/3, a local minimum at x = −1+/3, a global maximum at x = 2 and a global minimum at x = −4.
FUNCTIONS OF MORE THAN ONE VARIABLE
Section::::Functions of more than one variable.
For functions of more than one variable, similar conditions apply. For example, in the (enlargeable) figure at the right, the necessary conditions for a local maximum are similar to those of a function with only one variable. The first partial derivatives as to z (the variable to be maximized) are zero at the maximum (the glowing dot on top in the figure). The second partial derivatives are negative. These are only necessary, not sufficient, conditions for a local maximum because of the possibility of a saddle point. For use of these conditions to solve for a maximum, the function z must also be differentiable throughout. The second partial derivative test can help classify the point as a relative maximum or relative minimum.
In contrast, there are substantial differences between functions of one variable and functions of more than one variable in the identification of global extrema. For example, if a bounded differentiable function f defined on a closed interval in the real line has a single critical point, which is a local minimum, then it is also a global minimum (use the intermediate value theorem and Rolle's theorem to prove this by reductio ad absurdum). In two and more dimensions, this argument fails, as the function
shows. Its only critical point is at (0,0), which is a local minimum with ƒ(0,0) = 0. However, it cannot be a global one, because ƒ(2,3) = −5.
MAXIMA OR MINIMA OF A FUNCTIONAL
Section::::Maxima or minima of a functional.
If the domain of a function for which an extremum is to be found consists itself of functions, i.e. if an extremum is to be found of a functional, the extremum is found using the calculus of variations.
IN RELATION TO SETS
Section::::In relation to sets.
Maxima and minima can also be defined for sets. In general, if an ordered set S has a greatest element m, m is a maximal element. Furthermore, if S is a subset of an ordered set T and m is the greatest element of S with respect to order induced by T, m is a least upper bound of S in T. The similar result holds for least element, minimal element and greatest lower bound. The maximum and minimum function for sets are used in databases, and can be computed rapidly, since the maximum (or minimum) of a set can be computed from the maxima of a partition; formally, they are self-decomposable aggregation functions.
In the case of a general partial order, the least element (smaller than all other) should not be confused with a minimal element (nothing is smaller). Likewise, a greatest element of a partially ordered set (poset) is an upper bound of the set which is contained within the set, whereas a maximal element m of a poset A is an element of A such that if m ≤ b (for any b in A) then m = b. Any least element or greatest element of a poset is unique, but a poset can have several minimal or maximal elements. If a poset has more than one maximal element, then these elements will not be mutually comparable.
In a totally ordered set, or chain, all elements are mutually comparable, so such a set can have at most one minimal element and at most one maximal element. Then, due to mutual comparability, the minimal element will also be the least element and the maximal element will also be the greatest element. Thus in a totally ordered set we can simply use the terms minimum and maximum. If a chain is finite then it will always have a maximum and a minimum. If a chain is infinite then it need not have a maximum or a minimum. For example, the set of natural numbers has no maximum, though it has a minimum. If an infinite chain S is bounded, then the closure Cl(S) of the set occasionally has a minimum and a maximum, in such case they are called the greatest lower bound and the least upper bound of the set S, respectively.
SEE ALSO
* Derivative test
* Infimum and supremum
* Limit superior and limit inferior
* Mechanical equilibrium
* Sample maximum and minimum
* Saddle point
REFERENCES
EXTERNAL LINKS
* Maxima and Minima From MathWorld—A Wolfram Web Resource.
* Thomas Simpson's work on Maxima and Minima at Convergence
* Application of Maxima and Minima with sub pages of solved problems
|
# python-async-sqs-consumer
Python client for consuming messages asynchronously from AWS Simple Queue Service (SQS).
This provides a `SQSConsumer class` witch is able to consume multiple fifo queues from SQS.
It uses `Asyncio` library in order to process the messages asynchronously with a predefined concurrency.
It also is able to perform retries and give up messages, sending them to a failure queue.
Example:
```python
from sqs_consumer import SQSConsumer
consumer = SQSConsumer(concurrency=10)
@consumer.consume(
queue_name="MyQueue.fifo",
failure_queue="MyFailureQueue.fifo",
attempts=10
)
async def handle_message(message):
print(message)
# This is a blocking call.
# To stop the consumer call `consumer.stop()` in some point of the program.
consumer.start()
```
|
<link href="https://raw.github.com/clownfart/Markdown-CSS/master/markdown.css" rel="stylesheet"></link>
# The config file
[Back to index](index.md.html)
----
Each TShock installation automatically generates a configuration file which can edit basic settings when the server starts.
The file "config.json" is located in the *tshock* folder, in the same directory as TerrariaServer.exe.
Being a JSON file, it is extremely critical that you edit the file in a standard text editor. Use [Notepad++](http://notepad-plus-plus.org/) to edit your file, or another text editor used for programming. Before restarting TShock, check the syntax of your file using [JSONLint](http://jsonlint.com/), and verify that it contains no errors.
An example configuration file is below.
{
"InvasionMultiplier": 1,
"DefaultMaximumSpawns": 0,
"DefaultSpawnRate": 600,
"ServerPort": 7777,
"EnableWhitelist": false,
"InfiniteInvasion": false,
"PvPMode": "normal",
"SpawnProtection": true,
"SpawnProtectionRadius": 5,
"MaxSlots": 8,
"RangeChecks": true,
"DisableBuild": false,
"SuperAdminChatRGB": [
255.0,
0.0,
0.0
],
"SuperAdminChatPrefix": "(Admin) ",
"SuperAdminChatSuffix": "",
"BackupInterval": 0,
"BackupKeepFor": 60,
"RememberLeavePos": false,
"HardcoreOnly": false,
"MediumcoreOnly": false,
"KickOnMediumcoreDeath": false,
"BanOnMediumcoreDeath": false,
"AutoSave": true,
"MaximumLoginAttempts": 3,
"RconPassword": "",
"RconPort": 7777,
"ServerName": "",
"MasterServer": "127.0.0.1",
"StorageType": "sqlite",
"MySqlHost": "localhost:3306",
"MySqlDbName": "",
"MySqlUsername": "",
"MySqlPassword": "",
"MediumcoreBanReason": "Death results in a ban",
"MediumcoreKickReason": "Death results in a kick",
"EnableDNSHostResolution": false,
"EnableIPBans": true,
"EnableBanOnUsernames": false,
"DefaultRegistrationGroupName": "default",
"DefaultGuestGroupName": "guest",
"DisableSpewLogs": true,
"HashAlgorithm": "sha512",
"BufferPackets": true,
"ServerFullReason": "Server is full",
"ServerFullNoReservedReason": "Server is full. No reserved slots open.",
"SaveWorldOnCrash": true,
"EnableGeoIP": false,
"EnableTokenEndpointAuthentication": false,
"ServerNickname": "TShock Server",
"RestApiEnabled": false,
"RestApiPort": 7878,
"DisableTombstones": true,
"DisplayIPToAdmins": false,
"EnableInsecureTileFixes": true,
"KickProxyUsers": true,
"DisableHardmode": false,
"DisableDungeonGuardian": false,
"ServerSideInventory": false,
"ServerSideInventorySave": 15,
"LogonDiscardThreshold": 250,
"DisablePlayerCountReporting": false,
"DisableClownBombs": false,
"DisableSnowBalls": false,
"ChatFormat": "{1}{2}{3}: {4}",
"ForceTime": "normal",
"TileKillThreshold": 60,
"TilePlaceThreshold": 20,
"TileLiquidThreshold": 15,
"ProjectileThreshold": 50,
"ProjIgnoreShrapnel": true,
"RequireLogin": true,
"DisableInvisPvP": false,
"MaxRangeForDisabled": 10,
"ServerPassword": "",
"RegionProtectChests": false,
"DisableLoginBeforeJoin": false,
"AllowRegisterAnyUsername": false,
"AllowLoginAnyUsername": true,
"MaxDamage": 175,
"MaxProjDamage": 175,
"IgnoreProjUpdate": false,
"IgnoreProjKill": false,
"IgnoreNoClip": false,
"AllowIce": true
}
In this file, if you wanted to change the maximum players to 64, you would edit that the file so that the line referring to max players looked like so:
"MaxSlots": 64,
The following is the official documentation for the configuration file:
## AllowCorruptionCreep
**Type:** Boolean
**Description:** Allows corrutption to spread when a world is hardmode.
**Default:** "True"
## AllowHallowCreep
**Type:** Boolean
**Description:** Allows hallow to spread when a world is hardmode.
**Default:** "True"
## AllowIce
**Type:** Boolean
**Description:** Allow Ice placement even when user does not have canbuild
**Default:** "False"
## AllowLoginAnyUsername
**Type:** Boolean
**Description:** Allows users to login with any username with /login
**Default:** "True"
## AllowRegisterAnyUsername
**Type:** Boolean
**Description:** Allows users to register any username with /register
**Default:** "False"
## AutoSave
**Type:** Boolean
**Description:** Enable/Disable Terrarias built in auto save
**Default:** "True"
## BackupInterval
**Type:** Int32
**Description:** Backup frequency in minutes. So, a value of 60 = 60 minutes. Backups are stored in the \tshock\backups folder.
**Default:** "0"
## BackupKeepFor
**Type:** Int32
**Description:** How long backups are kept in minutes. 2880 = 2 days.
**Default:** "60"
## BanOnMediumcoreDeath
**Type:** Boolean
**Description:** Bans a Hardcore player on death.
**Default:** "False"
## BufferPackets
**Type:** Boolean
**Description:** Buffers up the packets and sends them out at the end of each frame
**Default:** "True"
## ChatFormat
**Type:** String
**Description:** Change ingame chat format, {0} = Group Name, {1} = Group Prefix, {2} = Player Name, {3} = Group Suffix, {4} = Chat Message
**Default:** "{1}{2}{3}: {4}"
## DefaultGuestGroupName
**Type:** String
**Description:** Selects the default group name to place non registered users under
**Default:** "guest"
## DefaultMaximumSpawns
**Type:** Int32
**Description:** The default maximum mobs that will spawn per wave. Higher means more mobs in that wave.
**Default:** "5"
## DefaultRegistrationGroupName
**Type:** String
**Description:** Selects the default group name to place new registrants under
**Default:** "default"
## DefaultSpawnRate
**Type:** Int32
**Description:** The delay between waves. Shorter values lead to less mobs.
**Default:** "600"
## DisableBuild
**Type:** Boolean
**Description:** Disables any building; placing of blocks
**Default:** "False"
## DisableClownBombs
**Type:** Boolean
**Description:** Disables clown bomb projectiles from spawning
**Default:** "False"
## DisableDungeonGuardian
**Type:** Boolean
**Description:** Disables Dungeon Guardian from being spawned by player packets, this will instead force a respawn
**Default:** "False"
## DisableHardmode
**Type:** Boolean
**Description:** Disables hardmode, can't never be activated. Overrides /starthardmode
**Default:** "False"
## DisableInvisPvP
**Type:** Boolean
**Description:** Disables Invisibility potions from being used in PvP (Note, they can use them on the client, but the effect isn't sent to the rest of the server)
**Default:** "False"
## DisableLoginBeforeJoin
**Type:** Boolean
**Description:** Disable users from being able to login with account password when joining
**Default:** "False"
## DisablePiggybanksOnSSI
**Type:** Boolean
**Description:** Prevent banks on SSI
**Default:** "False"
## DisablePlayerCountReporting
**Type:** Boolean
**Description:** Disables reporting of playercount to the stat system.
**Default:** "False"
## DisableSnowBalls
**Type:** Boolean
**Description:** Disables snow ball projectiles from spawning
**Default:** "False"
## DisableSpewLogs
**Type:** Boolean
**Description:** Force-Disable printing logs to players with the log permission
**Default:** "True"
## DisableTombstones
**Type:** Boolean
**Description:** Disable tombstones for all players.
**Default:** "True"
## DisplayIPToAdmins
**Type:** Boolean
**Description:** Displays a player's IP on join to everyone who has the log permission
**Default:** "False"
## EnableBanOnUsernames
**Type:** Boolean
**Description:** Enables kicking of banned users by matching their Character Name
**Default:** "False"
## EnableDNSHostResolution
**Type:** Boolean
**Description:** Enables DNS resolution of incoming connections with GetGroupForIPExpensive.
**Default:** "False"
## EnableGeoIP
**Type:** Boolean
**Description:** This will announce a player's location on join
**Default:** "False"
## EnableInsecureTileFixes
**Type:** Boolean
**Description:** Some tiles are 'fixed' by not letting TShock handle them. Disabling this may break certain asthetic tiles.
**Default:** "True"
## EnableIPBans
**Type:** Boolean
**Description:** Enables kicking of banned users by matching their IP Address
**Default:** "True"
## EnableTokenEndpointAuthentication
**Type:** Boolean
**Description:** This will turn on a token requirement for the /status API endpoint.
**Default:** "False"
## EnableWhitelist
**Type:** Boolean
**Description:** Enable or disable the whitelist based on IP addresses in whitelist.txt
**Default:** "False"
## ForceTime
**Type:** String
**Description:** Force the world time to be normal, day, or night
**Default:** "normal"
## HardcoreOnly
**Type:** Boolean
**Description:** Hardcore players ONLY. This means softcore players cannot join.
**Default:** "False"
## HashAlgorithm
**Type:** String
**Description:** Valid types are "sha512", "sha256", "md5", append with "-xp" for the xp supported algorithms
**Default:** "sha512"
## IgnoreNoClip
**Type:** Boolean
**Description:** Ignores all no clip checks for players
**Default:** "False"
## IgnoreProjKill
**Type:** Boolean
**Description:** Ignores checking to see if player 'can' kill a projectile
**Default:** "False"
## IgnoreProjUpdate
**Type:** Boolean
**Description:** Ignores checking to see if player 'can' update a projectile
**Default:** "False"
## InfiniteInvasion
**Type:** Boolean
**Description:** Enable the ability for invaison size to never decrease. Make sure to run /invade, and note that this adds 2 million+ goblins to the spawn que for the map.
**Default:** "False"
## InvasionMultiplier
**Type:** Int32
**Description:** The equation for calculating invasion size is 100 + (multiplier * (number of active players with greater than 200 health))
**Default:** "1"
## KickOnMediumcoreDeath
**Type:** Boolean
**Description:** Kicks a Hardcore player on death.
**Default:** "False"
## KickProxyUsers
**Type:** Boolean
**Description:** Kicks users using a proxy as identified with the GeoIP database
**Default:** "True"
## LogonDiscardThreshold
**Type:** Int32
**Description:** Time, in milliseconds, to disallow discarding items after logging in when ServerSideInventory is ON
**Default:** "250"
## MasterServer
**Type:** String
**Description:** Not implemented
**Default:** "127.0.0.1"
## MaxDamage
**Type:** Int32
**Description:** The maximum damage a player/npc can inflict
**Default:** "175"
## MaximumLoginAttempts
**Type:** Int32
**Description:** Number of failed login attempts before kicking the player.
**Default:** "3"
## MaxProjDamage
**Type:** Int32
**Description:** The maximum damage a projectile can inflict
**Default:** "175"
## MaxRangeForDisabled
**Type:** Int32
**Description:** The maximum distance players disabled for various reasons can move from
**Default:** "10"
## MaxSlots
**Type:** Int32
**Description:** Max slots for the server. If you want people to be kicked with "Server is full" set this to how many players you want max and then set Terraria max players to 2 higher.
**Default:** "8"
## MediumcoreBanReason
**Type:** String
**Description:** Bans a Mediumcore player on death.
**Default:** "Death results in a ban"
## MediumcoreKickReason
**Type:** String
**Description:** Kicks a Mediumcore player on death.
**Default:** "Death results in a kick"
## MediumcoreOnly
**Type:** Boolean
**Description:** Mediumcore players ONLY. This means softcore players cannot join.
**Default:** "False"
## MySqlDbName
**Type:** String
**Description:** Database name to connect to
**Default:** ""
## MySqlHost
**Type:** String
**Description:** The MySQL Hostname and port to direct connections to
**Default:** "localhost:3306"
## MySqlPassword
**Type:** String
**Description:** Database password to connect with
**Default:** ""
## MySqlUsername
**Type:** String
**Description:** Database username to connect with
**Default:** ""
## PreventBannedItemSpawn
**Type:** Boolean
**Description:** Prevent banned items from being /i or /give
**Default:** "False"
## ProjectileThreshold
**Type:** Int32
**Description:** Disable a player if they exceed this number of projectile new within 1 second.
**Default:** "50"
## ProjIgnoreShrapnel
**Type:** Boolean
**Description:** Ignore shrapnel from crystal bullets for Projectile Threshold.
**Default:** "True"
## PvPMode
**Type:** String
**Description:** Set the server pvp mode. Vaild types are, "normal", "always", "disabled"
**Default:** "normal"
## RangeChecks
**Type:** Boolean
**Description:** Global protection agent for any block distance based anti-grief check.
**Default:** "True"
## RconPassword
**Type:** String
**Description:** Not implemented
**Default:** ""
## RconPort
**Type:** Int32
**Description:** Not implemented
**Default:** "7777"
## RegionProtectChests
**Type:** Boolean
**Description:** Protect chests with region and build permissions
**Default:** "False"
## RememberLeavePos
**Type:** Boolean
**Description:** Remembers where a player left off. It works by remembering the IP, NOT the character.
eg. When you try to disconnect, and reconnect to be automatically placed at spawn, you'll be at your last location. Note: Won't save after server restarts.
**Default:** "False"
## RequireLogin
**Type:** Boolean
**Description:** Require all players to register or login before being allowed to play.
**Default:** "False"
## RestApiEnabled
**Type:** Boolean
**Description:** Enable/Disable the rest api.
**Default:** "False"
## RestApiPort
**Type:** Int32
**Description:** This is the port which the rest api will listen on.
**Default:** "7878"
## SaveWorldOnCrash
**Type:** Boolean
**Description:** This will save the world if Terraria crashes from an unhandled exception.
**Default:** "True"
## ServerFullNoReservedReason
**Type:** String
**Description:** String that is used when kicking people when the server is full with no reserved slots.
**Default:** "Server is full. No reserved slots open."
## ServerFullReason
**Type:** String
**Description:** String that is used when kicking people when the server is full.
**Default:** "Server is full"
## ServerName
**Type:** String
**Description:** Used when replying to a rest /status request.
**Default:** ""
## ServerNickname
**Type:** String
**Description:** This is used when the API endpoint /status is queried.
**Default:** "TShock Server"
## ServerPassword
**Type:** String
**Description:** Server password required to join server
**Default:** ""
## ServerPort
**Type:** Int32
**Description:** The port the server runs on.
**Default:** "7777"
## ServerSideInventory
**Type:** Boolean
**Description:** Enable Server Side Inventory checks, EXPERIMENTAL
**Default:** "False"
## ServerSideInventorySave
**Type:** Int32
**Description:** How often SSI should save, in minutes
**Default:** "15"
## SpawnProtection
**Type:** Boolean
**Description:** Prevents tiles from being placed within SpawnProtectionRadius of the default spawn.
**Default:** "True"
## SpawnProtectionRadius
**Type:** Int32
**Description:** Radius from spawn tile for SpawnProtection.
**Default:** "10"
## StatueSpawn200
**Type:** Int32
**Description:** How many things a statue can spawn within 200 pixels(?) before it stops spawning. Default = 3
**Default:** "3"
## StatueSpawn600
**Type:** Int32
**Description:** How many things a statue can spawn within 600 pixels(?) before it stops spawning. Default = 6
**Default:** "6"
## StatueSpawnWorld
**Type:** Int32
**Description:** How many things a statue spawns can exist in the world before it stops spawning. Default = 10
**Default:** "10"
## StorageType
**Type:** String
**Description:** Valid types are "sqlite" and "mysql"
**Default:** "sqlite"
## SuperAdminChatPrefix
**Type:** String
**Description:** Super admin group chat prefix
**Default:** "(Admin) "
## SuperAdminChatRGB
**Type:** Single[]
**Description:** #.#.#. = Red/Blue/Green - RGB Colors for the Admin Chat Color. Max value: 255
**Default:** "System.Single[]"
## SuperAdminChatSuffix
**Type:** String
**Description:** Super admin group chat suffix
**Default:** ""
## TileKillThreshold
**Type:** Int32
**Description:** Disable/Revert a player if they exceed this number of tile kills within 1 second.
**Default:** "60"
## TileLiquidThreshold
**Type:** Int32
**Description:** Disable a player if they exceed this number of liquid sets within 1 second.
**Default:** "15"
## TilePlaceThreshold
**Type:** Int32
**Description:** Disable/Revert a player if they exceed this number of tile places within 1 second.
**Default:** "20"
## WhitelistKickReason
**Type:** String
**Description:** String that is used when a user is kicked due to not being on the whitelist.
**Default:** "You are not on the whitelist."
|
<?
// no direct access
defined('_JEXEC') or die('Restricted access');
/**
* This is a file to add template specific chrome to pagination rendering.
*
* pagination_list_footer
* Input variable $list is an array with offsets:
* $list[limit] : int
* $list[limitstart] : int
* $list[total] : int
* $list[limitfield] : string
* $list[pagescounter] : string
* $list[pageslinks] : string
*
* pagination_list_render
* Input variable $list is an array with offsets:
* $list[all]
* [data] : string
* [active] : boolean
* $list[start]
* [data] : string
* [active] : boolean
* $list[previous]
* [data] : string
* [active] : boolean
* $list[next]
* [data] : string
* [active] : boolean
* $list[end]
* [data] : string
* [active] : boolean
* $list[pages]
* [{PAGE}][data] : string
* [{PAGE}][active] : boolean
*
* pagination_item_active
* Input variable $item is an object with fields:
* $item->base : integer
* $item->link : string
* $item->text : string
*
* pagination_item_inactive
* Input variable $item is an object with fields:
* $item->base : integer
* $item->link : string
* $item->text : string
*
* This gives template designers ultimate control over how pagination is rendered.
*
* NOTE: If you override pagination_item_active OR pagination_item_inactive you MUST override them both
*/
function pagination_list_footer($list)
{
// Initialize variables
$lang = & JFactory::getLanguage();
$html = "<div class=\"list-footer\">\n";
$html .= "\n<div class=\"limit\">" . JText::_('Display Num') . $list['limitfield'] . "</div>";
$html .= $list['pageslinks'];
$html .= "\n<div class=\"counter\">" . $list['pagescounter'] . "</div>";
$html .= "\n<input type=\"hidden\" name=\"limitstart\" value=\"" . $list['limitstart'] . "\" />";
$html .= "\n</div>";
return $html;
}
function pagination_list_render($list)
{
/*
<span>
<ul id="navigator">
<li><a href="#"><span class="nav">�</span></a></li>
<li><a href="#"><span class="nav">1</span></a></li>
<li><a href="#"><span class="nav">2</span></a></li>
<li class="active"><a href="#"><span class="nav">3</span></a></li>
<li><a href="#"><span class="nav">4</span></a></li>
<li><a href="#"><span class="nav">5</span></a></li>
<li><a href="#"><span class="nav">�</span></a></li>
<li><span>...</span class="nav"></li>
<li><a href="#"><span class="nav">�</span></a></li>
</ul>
</span>
*/
// Initialize variables
$lang = & JFactory::getLanguage();
$html = '<div class="links"><div class="pagination">';
$html .= "<ul class=\"pagination-list\">\n<li class=\"tab\">" . "\n" . $list['start']['data'] . "</li>";
$html .= "\n<li class=\"tab\">" . "\n" . $list['previous']['data'] . "</li>";
foreach ($list['pages'] as $page)
{
if ($page['data']['active'])
{
//$html .= '<strong>';
}
$html .= "\n<li class=\"page-block\">" . $page['data'] . "</li>";
if ($page['data']['active'])
{
// $html .= '</strong>';
}
}
$html .= "\n<li class=\"tab\">" . "\n" . $list['next']['data'] . "</li>";
$html .= "\n<li class=\"tab\">" . "\n" . $list['end']['data'] . "</li><ul>";
// $html .= '«';
$html .= '</div></div>';
return $html;
}
function pagination_item_active(&$item)
{
return "<span><a href=\"" . $item->link . "\" title=\"" . $item->text . "\">" . $item->text . "</a></span>";
}
function pagination_item_inactive(&$item)
{
return "<span class=\"active\">" . $item->text . "</span>";
}
?>
|
import { expect } from "@playwright/test"
import { LoginPage } from "../page-objects/login-page"
import { MainPage } from "../page-objects/main-page"
import { settings } from "../utils/settings"
import { test } from "../utils/extensions"
import { createAuthorizedWebContext } from "../utils/functions"
/*test.beforeAll(async ({ browser }) => {
settings.authorizedContext = await createAuthorizedWebContext(
settings.activeUser.email,
settings.activeUser.password,
browser
)
})*/
test.describe(`WEB Tests`, () => {
test.describe.configure({ mode: `default` })
test(`@web Login To Espresa`, async ({ loginPage, mainPage }) => {
await loginPage.loginToEspresa(
settings.activeUser.email,
settings.activeUser.password
)
let userGreetingText = await mainPage.isUserLoggedIn(
settings.activeUser.firstName,
settings.activeUser.lastName
)
console.log(userGreetingText)
})
test(`@web Negative Login To Espresa`, async ({
page,
loginPage,
invalidUser,
}) => {
await loginPage.goToEspresa()
await loginPage.enterEmail(invalidUser.email)
await page.waitForTimeout(1 * 1000)
let loginErrorText = await loginPage.loginError.textContent()
expect(loginErrorText, `Error text is incorrect`).toContain(
`Please enter a valid email address.`
)
console.log(loginErrorText)
})
test(`@web Get First Event`, async ({ loginPage, mainPage }) => {
await loginPage.loginToEspresa(
settings.activeUser.email,
settings.activeUser.password
)
await mainPage.isUserLoggedIn(
settings.activeUser.firstName,
settings.activeUser.lastName
)
let firstIventInfo = await mainPage.cardsInfo.first().textContent()
console.log(`First event: ${firstIventInfo}`)
})
})
test.describe(`Mix Of WEB And API Tests`, () => {
test.describe.configure({ mode: `parallel` })
test(`@web Get First Event Mix`, async ({ authorizedMainPage }) => {
await authorizedMainPage.goToDashboard()
await authorizedMainPage.isUserLoggedIn(
settings.activeUser.firstName,
settings.activeUser.lastName
)
let firstIventInfo = await authorizedMainPage.cardsInfo
.first()
.textContent()
console.log(`First event: ${firstIventInfo}`)
})
test(`@web Fake Coins Mix`, async ({ authorizedContext }) => {
const page = await authorizedContext.newPage()
const mainPage = new MainPage(page)
await page.route(
`${settings.baseURL}api/company/employee/points/`,
async (route) => {
const response = await page.request.fetch(route.request())
const newBody = {
available_points: 777,
}
route.fulfill({
response: response,
body: JSON.stringify(newBody),
})
}
)
await mainPage.goToDashboard()
await expect(
await mainPage.cardsInfo.first(),
`First card isn't visible`
).toBeVisible()
await page.screenshot({ path: `screenshots/fakeCoins.png` })
let coinsCount = await mainPage.userCoins.textContent()
expect(coinsCount, `Coins count is incorrect`).toEqual(`777.00 LX Coins`)
console.log(`Fake ${coinsCount} are available to the user`)
})
})
|
require "application_system_test_case"
class SegmentConnectionsTest < ApplicationSystemTestCase
setup do
@segment_connection = segment_connections(:one)
end
test "visiting the index" do
visit segment_connections_url
assert_selector "h1", text: "Segment connections"
end
test "should create segment connection" do
visit segment_connections_url
click_on "New segment connection"
click_on "Create Segment connection"
assert_text "Segment connection was successfully created"
click_on "Back"
end
test "should update Segment connection" do
visit segment_connection_url(@segment_connection)
click_on "Edit this segment connection", match: :first
click_on "Update Segment connection"
assert_text "Segment connection was successfully updated"
click_on "Back"
end
test "should destroy Segment connection" do
visit segment_connection_url(@segment_connection)
click_on "Destroy this segment connection", match: :first
assert_text "Segment connection was successfully destroyed"
end
end
|
#' Compute the count statistics of a network and given node labels
#'
#' @param adj adjacency matrix
#' @param Z vector with node labels
#' @param K Number of blocks of the associated stochastic block model. If NULL
#' (by default), the number of empty blocks present in the node label vector Z is used.
#' Otherwise, a stochastic block model with K blocks is consider implying the presence
#' of empty blocks.
#' @param directed directed network (TRUE by default) or undirected (FALSE).
#'
#' @return list with the number of nodes per block ($S), the number of edges
#' for all pairs of blocks ($A) and the maximal number of edges
#' for all pairs of blocks ($R)
#' @noRd
getCounts <- function(adj, Z, K=NULL, directed=TRUE){
n_m <- nrow(adj)
labNames <- as.numeric(names(table(Z)))
if (is.null(K)) {
s_k <- as.numeric(table(Z))
K <- J <- length(s_k)
s <- NULL
# relabel Z:
if (max(Z)>K){
for (k in 1:K){
Z[Z==labNames[k]] <- k
}
}
}else{
s_k <- rep(0, K)
s <- as.numeric(table(Z))
J <- length(labNames)
for (j in 1:J){
s_k[labNames[j]] <- s[j]
}
}
Zmask <- matrix(0, K, n_m)
Zmask[matrix(c(Z, 1:n_m), ncol=2)] <- 1
a_kl <- Zmask %*% adj %*% t(Zmask)
if (K>1){
r_kl <- s_k %*% t(s_k) - diag(s_k)
}else{
r_kl <- s_k * (s_k-1)
}
return(list(S=s_k, A=a_kl, R=r_kl))
}
#' Compute the count statistics for all networks in a collection and given node labels
#'
#' @param listAdj list of adjacency matrices
#' @param listZ list of node labels
#' @param K Number of blocks of the associated stochastic block model. If NULL
#' (by default), the number of empty blocks present in the node label vector Z is used.
#' Otherwise, a stochastic block model with K blocks is consider implying the presence
#' of empty blocks.
#' @param directed directed network (TRUE by default) or undirected (FALSE).
#'
#' @return list of lists: with the number of nodes per block ($S), the number of edges
#' for all pairs of blocks ($A), the maximal number of edges
#' for all pairs of blocks ($R) and the node labels ($Z)
#' @noRd
getListCounts <- function(listAdj, listZ, K=NULL, directed=TRUE){
M <- length(listAdj)
listCountsPerGraph <- lapply(1:M,
function(m) getCounts(listAdj[[m]], listZ[[m]], K)
)
listCountsPerStat <- list(S=NULL, A=NULL, R=NULL)
listCountsPerStat$S <- lapply(listCountsPerGraph, function(el) el$S)
listCountsPerStat$A <- lapply(listCountsPerGraph, function(el) el$A)
listCountsPerStat$R <- lapply(listCountsPerGraph, function(el) el$R)
listCountsPerStat$Z <- listZ
return(listCountsPerStat)
}
#' Extract count statistics for a given set of networks
#'
#' @param countStat list of count statistics of a collection of networks
#' @param ind vector of network indices to be extracted
#'
#' @return list of count statistics of the desired networks
#' @noRd
extractCountStat <- function(countStat, ind){
return(list(Z=countStat$Z[ind], S=countStat$S[ind],
R=countStat$R[ind], A=countStat$A[ind]))
}
#' Update entries of the list of count statistics of the collection of networks
#'
#' @param countStat list of count statistics of a collection of networks
#' @param ind vector of network indices to be updated
#' @param newCountStat list of new count statistics
#'
#' @return updated list of count statistics of the collection
#' @noRd
updateCountStat <- function(countStat, ind, newCountStat){
countStat$Z[ind] <- newCountStat$Z
countStat$S[ind] <- newCountStat$S
countStat$A[ind] <- newCountStat$A
countStat$R[ind] <- newCountStat$R
return(countStat)
}
#' Merge two lists of count statistics
#'
#' @param countStat1 list of count statistics
#' @param countStat2 list of count statistics
#'
#' @return merged list of count statistics
#' @noRd
mergeCountStat <- function(countStat1, countStat2){
return(list(Z=c(countStat1$Z, countStat2$Z),
S=c(countStat1$S, countStat2$S),
R=c(countStat1$R, countStat2$R),
A=c(countStat1$A, countStat2$A)))
}
#' Create list of count statistics from arrays of count statistics
#'
#' @param Z list of node labels
#' @param S matrix of count statistics
#' @param A array of count statistics
#' @param R array of count statistics
#'
#' @return list of count statistics
#' @noRd
buildCountStat <- function(Z, S, A, R){
countStat <- list(Z=Z)
M <- ncol(S)
countStat$S <- lapply(1:M, function(m) S[ , m])
countStat$A <- lapply(1:M, function(m) A[ , , m])
countStat$R <- lapply(1:M, function(m) R[ , , m])
return(countStat)
}
#' Update list of count statistics when permuting block labels
#'
#' @param countStat list of count statistics
#' @param permut permutation of block labels
#'
#' @return updated list of count statistics
#' @noRd
permutCountStat <- function(countStat, permut){
countStat$Z <- permutListZ(countStat$Z, permut)
countStat$S <- permutListOfVectors(countStat$S, permut)
countStat$R <- permutListOfMatrices(countStat$R, permut)
countStat$A <- permutListOfMatrices(countStat$A, permut)
return(countStat)
}
#' Permute labels of a vector of node labels
#'
#' @param Z vector of node labels
#' @param permut permutation of block labels
#'
#' @return vector of permuted node labels
#' @noRd
permutLabels <- function(Z, permut){
Znew <- Z
K <- length(permut)
for(k in 1:K)
Znew[Z==permut[k]] <- k
return(Znew)
}
#' Permute labels of a list of vectors of node labels
#'
#' @param Z vector of node labels
#' @param permut permutation of block labels
#'
#' @return updated list of vectors of node labels
#' @noRd
permutListZ <- function(Z, permut){
Z <- lapply(Z, function(z) permutLabels(z, permut))
return(Z)
}
#' Permute rows and columns of a list of matrices
#'
#' @param A list of square matrices of same size
#' @param permut permutation of rows and columns of matrices
#'
#' @return permuted list of matrices
#' @noRd
permutListOfMatrices <- function(A, permut){
A <- lapply(A, function(mat) permutMatrice(mat, permut))
return(A)
}
#' Permute rows and columns of a matrix
#'
#' @param A square matrix
#' @param permut permutation of rows and columns of A
#'
#' @return permuted matrix
#' @noRd
permutMatrice <- function(A, permut){
K <- length(permut)
ind <- matrix(c(rep(permut, K), rep(permut, each=K)), ncol=2)
A <- matrix(A[ind], K, K)
return(A)
}
#' Permute entries of a list of vectors of same size
#'
#' @param A list of vectors of same size
#' @param permut permutation of vector entries
#'
#' @return list of permuted vectors
#' @noRd
permutListOfVectors <- function(A, permut){
A <- lapply(A, function(vec) vec[permut])
return(A)
}
|
import React, { useEffect, useState } from "react";
/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";
import { postShareArticle } from "../../api/share";
import { postAskArticle } from "../../api/ask";
import DivideLine from "../common/DivideLine";
import InputBox from "../common/InputBox";
import ProductCalendar from "./ProductCalendar";
import MiddleWideButton from "../button/MiddleWideButton";
import ProductCategory from "./ProductCategory";
import ProductImageSelect from "./ProductImageSelect";
import ProductRegistType from "./ProductRegistType";
import { useNavigate, useLocation } from "react-router-dom";
import Map from "./../common/Map";
import { getUserDetail } from "../../api/user";
const { kakao } = window;
const ProductRegist = () => {
const loginUserId = window.localStorage.getItem("id");
const navigate = useNavigate();
const loc = useLocation();
const [registType, setRegistType] = useState("");
const [sendType, setSendType] = useState("");
const [title, setTitle] = useState("");
const [category, setCategory] = useState("");
const [content, setContent] = useState("");
const [startDay, setStartDay] = useState("");
const [endDay, setEndDay] = useState("");
const [location, setLocation] = useState("마우스 우클릭으로 장소를 선택해주시면 돼요");
const [hopeAreaLat, setHopeAreaLat] = useState("");
const [hopeAreaLng, setHopeAreaLng] = useState("");
const [imageList, setImageList] = useState([]);
const [myPoint, setMyPoint] = useState(0);
// 소셜 로그인 시 닉네임 변경
function checkSocialNickName() {
const nickName = window.localStorage.getItem("nickName");
if (nickName.slice(0, 1) === "#") {
alert("닉네임 변경을 진행해주세요.");
navigate("/socialnickname", { state: { url: "/product/regist" } });
}
}
function receiveRegistType(registType) {
setRegistType(registType);
}
function onChangeTitle(value) {
if (title.length > 30) {
alert("제목은 최대 30자 등록 가능해요 😥");
} else setTitle(value);
}
function receiveCategory(category) {
setCategory(category);
}
function receiveImageList(imageList) {
setImageList(imageList);
}
function receiveStartDate(startDate) {
const utcStartDate = new Date(Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate()));
const startDateResult = JSON.stringify(utcStartDate);
setStartDay(startDateResult.substring(1, 11));
setEndDay(""); // 시작일만 설정했을 경우의 이슈를 막기 위해 시작일이 바뀔 때마다 종료일 리셋
}
function receiveEndDate(endDate) {
const utcEndDate = new Date(Date.UTC(endDate.getFullYear(), endDate.getMonth(), endDate.getDate()));
const endDateResult = JSON.stringify(utcEndDate);
setEndDay(endDateResult.substring(1, 11));
}
function receiveLocation(location, lat, lng, zoomLevel, isMarker) {
if (isMarker) {
setHopeAreaLat(lat);
setHopeAreaLng(lng);
searchDetailAddrFromCoords(lat, lng, function (result, status) {
if (status === kakao.maps.services.Status.OK) {
setLocation(result[0].address.address_name);
}
});
}
}
function searchDetailAddrFromCoords(lat, lng, callback) {
const geocoder = new kakao.maps.services.Geocoder();
geocoder.coord2Address(lng, lat, callback);
}
function onClickRegistButton() {
// 유효성 검사
if (registType === "선택해주세요.") {
alert("공유할 지 요청할 지 선택해주셔야해요.");
return;
}
if (registType === "물품 요청 등록" && myPoint < 30) {
alert("공유를 요청하기에 포인트가 부족해요. 다른 사람에게 물건을 공유해주고 포인트를 얻어봐요 😀");
return;
}
if (
category === "카테고리" ||
!category ||
!content ||
!endDay ||
!hopeAreaLat ||
!hopeAreaLng ||
!startDay ||
!title
) {
alert("필수 항목을 모두 채워주셔야해요.");
return;
}
if (content.length > 300) {
alert("물품에 대한 설명은 최대 300자 입력 가능해요.");
return;
}
setContent(content.replaceAll("<br>", "\r\n")); // 개행 처리
const formData = new FormData();
imageList.forEach((image) => {
formData.append("image", image);
});
if (!imageList.length) {
alert("사진을 첨부해주시겠어요? 빌리지는 사진첨부가 필수에요");
return;
}
formData.append(
"board",
new Blob(
[
JSON.stringify({
category: category,
content: content,
endDay: endDay,
hopeAreaLat: hopeAreaLat,
hopeAreaLng: hopeAreaLng,
startDay: startDay,
title: title,
userId: loginUserId,
address: location,
}),
],
{ type: "application/json" }
)
);
// API 요청
if (registType === "물품 공유 등록") {
postShareArticle(formData)
.then((res) => {
res = res[0];
navigate(`/product/detail/share/${res.id}`);
})
.catch((error) => {
console.log(error);
});
} else if (registType === "물품 요청 등록") {
postAskArticle(formData)
.then((res) => {
res = res[0];
navigate(`/product/detail/ask/${res.id}`);
})
.catch((error) => {
console.log(error);
});
}
}
useEffect(() => {
checkSocialNickName();
if (loc.state) {
if (loc.state.type == 2) {
setRegistType("물품 공유 등록");
setSendType("물품 공유 등록");
} else {
setRegistType("물품 요청 등록");
setSendType("물품 요청 등록");
}
}
if (loginUserId) {
getUserDetail(loginUserId)
.then((res) => {
setMyPoint(res.point);
})
.catch((error) => console.log(error));
}
}, []);
return (
<div css={wrapper}>
<ProductRegistType sendRegistType={receiveRegistType} sendType={sendType} />
<DivideLine />
<div css={titleWrapper}>
<h3>
제목 <b>*</b>
</h3>
<InputBox useMainList={false} placeholder="제목을 입력해주세요." onChangeValue={onChangeTitle} />
</div>
<div css={categoryWrapper}>
<h3>
카테고리 <b>*</b>
</h3>
<ProductCategory path={""} isMain={true} sendCategory={receiveCategory} />
</div>
<div css={contentWrapper}>
<h3>
설명 <b>*</b>
<small>(최대 300자)</small>
</h3>
<textarea
placeholder="물품에 대한 상세한 설명을 해주면 좋아요."
onChange={(e) => setContent(e.target.value)}
id="textarea"
></textarea>
</div>
<div css={imageWrapper}>
<h3>
물품 사진 <b>*</b>
<small>(최대 8개)</small>
</h3>
<small>물품에 대한 사진을 보여주면, 찾는 사람이 정확하게 볼 수 있어요.</small>
<ProductImageSelect sendImageList={receiveImageList} />
</div>
<div css={hopeDateWrapper}>
<h3>
희망 공유 기간 <b>*</b>
</h3>
<small>희망 공유기간을 적어주세요. 기간은 대화를 통해 수정할 수 있어요.</small>
<ProductCalendar sendStartDate={receiveStartDate} sendEndDate={receiveEndDate} />
</div>
<div css={hopeAreaWrapper}>
<div css={hopeAreaHeaderWrapper}>
<h3>
희망 공유 장소 <b>*</b>
</h3>
<span>{location}</span>
</div>
<Map readOnly={false} sendLocation={receiveLocation} path={"regist"} />
</div>
<div css={registButtonWrapper}>
<div>
<MiddleWideButton text="등록하기" onclick={onClickRegistButton} />
</div>
</div>
</div>
);
};
const wrapper = css`
padding: 90px 200px;
display: flex;
flex-direction: column;
`;
const titleWrapper = css`
display: flex;
flex-direction: column;
width: 100%;
margin-top: 60px;
& > h3 {
margin-bottom: 15px;
& b {
color: red;
}
}
`;
const categoryWrapper = css`
display: flex;
flex-direction: column;
width: 100%;
margin-top: 60px;
& > h3 {
margin-bottom: 15px;
& b {
color: red;
}
}
`;
const contentWrapper = css`
display: flex;
flex-direction: column;
width: 100%;
margin-top: 60px;
& > h3 {
margin-bottom: 15px;
& b {
color: red;
}
}
& > textarea {
max-width: 100%;
height: 176px;
background: #ffffff;
border: 1px solid #e1e2e3;
border-radius: 5px;
outline: none;
resize: none;
font-size: 18px;
padding: 20px;
}
`;
const imageWrapper = css`
display: flex;
flex-direction: column;
width: 100%;
margin-top: 60px;
& > h3 {
margin-bottom: 15px;
& b {
color: red;
}
}
& > small {
color: #847a7a;
}
`;
const hopeDateWrapper = css`
display: flex;
flex-direction: column;
width: 100%;
margin-top: 60px;
& > h3 {
margin-bottom: 15px;
& b {
color: red;
}
}
& > small {
color: #847a7a;
margin-bottom: 15px;
}
`;
const hopeAreaWrapper = css`
display: flex;
flex-direction: column;
width: 100%;
margin-top: 60px;
& > div:nth-of-type(2) {
width: 100%;
height: 479px;
}
`;
const hopeAreaHeaderWrapper = css`
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
& > h3 b {
color: red;
}
& > span {
color: #8a8a8a;
}
`;
const registButtonWrapper = css`
width: 100%;
margin-top: 90px;
display: flex;
justify-content: center;
& > div {
width: 165px;
}
`;
export default ProductRegist;
|
.\"
.\" Copyright (c) Mark J. Kilgard, 1996.
.\"
.TH glutExtensionSupported 3GLUT "3.7" "GLUT" "GLUT"
.SH NAME
glutExtensionSupported - helps to easily determine whether a
given OpenGL extension is supported.
.SH SYNTAX
.nf
#include <GLUT/glut.h>
.LP
int glutExtensionSupported(char *extension);
.fi
.SH ARGUMENTS
.IP \fIextension\fP 1i
Name of OpenGL extension.
.SH DESCRIPTION
glutExtensionSupported helps to easily determine whether a
given OpenGL extension is supported or not. The extension
parameter names the extension to query. The supported extensions can
also be determined with glGetString(GL_EXTENSIONS), but
glutExtensionSupported does the correct parsing of the returned
string.
glutExtensionSupported returns non-zero if the extension is
supported, zero if not supported.
There must be a valid current window to call
glutExtensionSupported.
glutExtensionSupported only returns information about OpenGL
extensions only. This means window system dependent extensions (for
example, GLX extensions) are not reported by
glutExtensionSupported.
.SH EXAMPLE
Here is an example of using glutExtensionSupported:
.nf
.LP
if (!glutExtensionSupported("GL_EXT_texture")) {
fprintf(stderr, "Missing the texture extension!\\n");
exit(1);
}
.fi
Notice that the name argument includes both the GL prefix and the
extension family prefix (EXT).
.SH SEE ALSO
glutGet, glGetString
.SH AUTHOR
Mark J. Kilgard ([email protected])
|
package com.nguyentronghao.realtime_restapi_blogapp.model.dto.user;
import com.nguyentronghao.realtime_restapi_blogapp.model.entity.User;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* DTO for {@link User}
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Schema(
description = "User authentication model information"
)
public class AuthRequestDto {
@Schema(description = "User's username or email")
@NotBlank
private String usernameOrEmail;
@Schema(description = "User's password")
@NotBlank
private String password;
}
|
import { IUseCase } from './protocols/use-case'
import { ICheckInsRepository } from '@/repositories/protocols/check-ins.repository'
type GetUserMetricsUseCaseRequest = {
userId: string
}
type GetUserMetricsUseCaseResponse = {
checkInsCount: number
}
export class GetUserMetricsUseCase
implements
IUseCase<GetUserMetricsUseCaseRequest, GetUserMetricsUseCaseResponse>
{
constructor(private checkInRepository: ICheckInsRepository) {}
async run({
userId,
}: GetUserMetricsUseCaseRequest): Promise<GetUserMetricsUseCaseResponse> {
const checkInsCount = await this.checkInRepository.countByUserId(userId)
return { checkInsCount }
}
}
|
import React from "react";
import { NavLink } from "react-router-dom";
const Navbar = () => {
return (
<nav className="navbar navbar-expand-lg text-dark bg-warning shadow">
<div className="container">
<NavLink className="navbar-brand" to="/">
{/* Your brand/logo here */}
Product Review and Rating Platform
</NavLink>
<button
className="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0 text-dark">
<li className="nav-item">
<NavLink className="nav-link" activeClassName="active" exact to="/">
Home
</NavLink>
</li>
<li className="nav-item">
<NavLink className="nav-link" activeClassName="active" to="/about">
About
</NavLink>
</li>
<li className="nav-item">
<NavLink className="nav-link" activeClassName="active" to="/services">
Services
</NavLink>
</li>
<li className="nav-item">
<NavLink className="nav-link" activeClassName="active" to="/contact">
Contact
</NavLink>
</li>
</ul>
<NavLink className="btn btn-outline-dark ms-auto px-4 rounded-pill" to="/login">
<i className="fa fa-sign-in me-2"></i>Login
</NavLink>
<NavLink className="btn btn-outline-dark ms-2 px-4 rounded-pill" to="/register">
<i className="fa fa-user-plus me-2"></i>Register
</NavLink>
<NavLink className="btn btn-outline-dark ms-2 px-4 rounded-pill" to="/dashboard">
<i className="fa fa-sign-plus me-2"></i>Logout
</NavLink>
</div>
</div>
</nav>
);
};
export default Navbar;
|
-- Source: https://whc.unesco.org/en/list/
--
-- Comment drop database out later
--
DROP DATABASE IF EXISTS medicare;
--
-- Create database
--
CREATE DATABASE IF NOT EXISTS medicare;
USE medicare;
--
--
-- Drop tables
-- turn off FK checks temporarily to eliminate drop order issues
--
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS drg, provider_drg, provider, referral_region, address, city_state, t_medicare, t_medicare_1, f_medicare;
SET FOREIGN_KEY_CHECKS=1;
--
-- STATE
--
CREATE TABLE IF NOT EXISTS city_state
(
city_state_id INTEGER NOT NULL AUTO_INCREMENT UNIQUE,
city_state_name VARCHAR (100) NOT NULL,
state_name VARCHAR(100) NOT NULL,
city_name VARCHAR(100) NOT NULL,
PRIMARY KEY (city_state_id)
)
ENGINE=InnoDB
CHARACTER SET utf8mb4
COLLATE utf8mb4_0900_ai_ci;
--
-- ADDRESS
--
CREATE TABLE IF NOT EXISTS address
(
address_id INTEGER NOT NULL AUTO_INCREMENT UNIQUE,
street VARCHAR(100) NOT NULL UNIQUE,
zip VARCHAR(5) NOT NULL UNIQUE,
city_state_id INTEGER NOT NULL,
PRIMARY KEY (address_id),
FOREIGN KEY (city_state_id) REFERENCES city_state(city_state_id) ON DELETE RESTRICT
ON UPDATE CASCADE
)
ENGINE=InnoDB
CHARACTER SET utf8mb4
COLLATE utf8mb4_0900_ai_ci;
--
-- REFERRAL REGION
--
CREATE TABLE IF NOT EXISTS referral_region
(
referral_region_id INTEGER NOT NULL AUTO_INCREMENT UNIQUE,
referral_region_desc VARCHAR(100) NOT NULL UNIQUE,
PRIMARY KEY (referral_region_id)
)
ENGINE=InnoDB
CHARACTER SET utf8mb4
COLLATE utf8mb4_0900_ai_ci;
--
-- PROVIDER
--
CREATE TABLE IF NOT EXISTS provider
(
provider_id INTEGER NOT NULL AUTO_INCREMENT UNIQUE,
old_provider_id VARCHAR(100) NOT NULL,
provider_name VARCHAR(100) NOT NULL UNIQUE,
referral_region_id INTEGER NOT NULL UNIQUE,
address_id INTEGER NOT NULL,
PRIMARY KEY (provider_id),
FOREIGN KEY (referral_region_id) REFERENCES referral_region(referral_region_id) ON DELETE RESTRICT ON UPDATE CASCADE,
FOREIGN KEY (address_id) REFERENCES address(address_id) ON DELETE RESTRICT ON UPDATE CASCADE
)
ENGINE=InnoDB
CHARACTER SET utf8mb4
COLLATE utf8mb4_0900_ai_ci;
--
-- DRG
--
CREATE TABLE IF NOT EXISTS drg
(
drg_id INTEGER NOT NULL AUTO_INCREMENT UNIQUE,
drg_desc VARCHAR(100) NOT NULL UNIQUE,
PRIMARY KEY (drg_id)
)
ENGINE=InnoDB
CHARACTER SET utf8mb4
COLLATE utf8mb4_0900_ai_ci;
-- Temporary target table for medicare data import
--
-- PROVIDER_DRG (LINK TABLE)
--
CREATE TABLE IF NOT EXISTS provider_drg
(
provider_drg_id INTEGER NOT NULL AUTO_INCREMENT UNIQUE,
provider_id INTEGER NOT NULL,
drg_id INTEGER NOT NULL,
avg_med_payment NUMERIC ( 19,4 ),
avg_cov_charges NUMERIC ( 19,4 ),
avg_total_payment NUMERIC ( 19,4 ),
total_discharges NUMERIC ( 19,4 ),
PRIMARY KEY (provider_drg_id),
FOREIGN KEY (provider_id) REFERENCES provider(provider_id) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (drg_id) REFERENCES drg(drg_id) ON DELETE CASCADE ON UPDATE CASCADE
)
ENGINE=InnoDB
CHARACTER SET utf8mb4
COLLATE utf8mb4_0900_ai_ci;
-- CREATE TEMPORARY TABLE t_medicare
CREATE TABLE IF NOT EXISTS t_medicare_1
-- Change to root table, not temporary table. That way I can look at it and run queries on it.
-- Later change back.
(
id INTEGER NOT NULL AUTO_INCREMENT UNIQUE,
drg_desc VARCHAR(100),
old_provider_id VARCHAR(100) NOT NULL,
provider_name VARCHAR(100) NOT NULL,
street VARCHAR(100) NOT NULL,
city_name VARCHAR(100) NOT NULL,
state_name VARCHAR(100) NOT NULL,
zip CHAR(5) NOT NULL,
referral_region_desc VARCHAR(100),
avg_med_payment NUMERIC ( 19,4 ),
avg_cov_charges NUMERIC ( 19,4 ),
avg_total_payment NUMERIC ( 19,4 ),
total_discharges NUMERIC ( 19,4 ),
city_state_name VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
)
ENGINE=InnoDB
CHARACTER SET utf8mb4
COLLATE utf8mb4_0900_ai_ci;
-- Load data from external file.
-- Check for blank entries and set to NULL.
LOAD DATA LOCAL INFILE 'medicare_data_1212.csv' -- don't need long filepath
INTO TABLE t_medicare_1
CHARACTER SET utf8mb4
FIELDS TERMINATED BY '\,'
-- FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
-- LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(drg_desc, old_provider_id, provider_name, street, city_name, state_name, zip, referral_region_desc, total_discharges, avg_cov_charges, avg_total_payment, avg_med_payment, city_state_name)
SET drg_desc = IF(drg_desc = '', NULL, drg_desc),
old_provider_id = IF(old_provider_id = '', NULL, old_provider_id),
provider_name = IF(provider_name = '', NULL, provider_name),
street = IF(street = '', NULL, street),
city_name = IF(city_name = '', NULL, city_name),
state_name = IF(state_name = '', NULL, state_name),
zip = IF(zip = '', NULL, zip),
referral_region_desc = IF(referral_region_desc = '', NULL, referral_region_desc),
total_discharges = IF(total_discharges = '', NULL, total_discharges),
avg_cov_charges = IF(avg_cov_charges = '', NULL, avg_cov_charges),
avg_total_payment = IF(avg_total_payment = '', NULL, avg_total_payment),
avg_med_payment = IF(avg_med_payment = '', NULL, avg_med_payment),
city_state_name = IF(city_state_name = '', NULL, city_state_name);
CREATE TABLE IF NOT EXISTS f_medicare
-- Change to root table, not temporary table. That way I can look at it and run queries on it.
-- Later change back.
(
id INTEGER NOT NULL AUTO_INCREMENT UNIQUE,
drg_desc VARCHAR(100),
old_provider_id VARCHAR(100) NOT NULL,
provider_name VARCHAR(100) NOT NULL,
street VARCHAR(100) NOT NULL,
city_name VARCHAR(100) NOT NULL,
state_name VARCHAR(100) NOT NULL,
zip CHAR(5) NOT NULL,
referral_region_desc VARCHAR(100),
avg_med_payment NUMERIC ( 19,4 ),
avg_cov_charges NUMERIC ( 19,4 ),
avg_total_payment NUMERIC ( 19,4 ),
total_discharges NUMERIC ( 19,4 ),
city_state_name VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
)
ENGINE=InnoDB
CHARACTER SET utf8mb4
COLLATE utf8mb4_0900_ai_ci;
-- Insert country_area attributes only (N=249) from temp table (no regions).
INSERT IGNORE INTO f_medicare (drg_desc, old_provider_id, provider_name, street, city_name, state_name, zip, referral_region_desc, total_discharges, avg_cov_charges, avg_total_payment, avg_med_payment, city_state_name)
SELECT tm.drg_desc, tm.provider_name, tm.street, tm.city_state_name, tm.state_name, tm.city_name,
tm.zip, tm.referral_region_desc, tm.avg_med_payment, tm.avg_cov_charges,
tm.avg_total_payment, tm.total_discharges, tm.old_provider_id
FROM t_medicare_1 tm
LEFT JOIN drg dr
ON tm.drg_desc = dr.drg_desc
LEFT JOIN provider pr
ON tm.old_provider_id = pr.old_provider_id
LEFT JOIN referral_region rr
ON tm.referral_region_desc = rr.referral_region_desc
LEFT JOIN address ad
ON tm.street = ad.street
LEFT JOIN city_state cs
ON tm.city_state_name = cs.city_state_name
WHERE IFNULL(tm.drg_desc, 0) = IFNULL(dr.drg_desc, 0)
AND IFNULL(tm.old_provider_id, 0) = IFNULL(pr.old_provider_id, 0)
AND IFNULL(tm.referral_region_desc, 0) = IFNULL(rr.referral_region_desc, 0)
AND IFNULL(tm.street, 0) = IFNULL(ad.street, 0)
AND IFNULL(tm.city_state_name, 0) = IFNULL(cs.city_state_name, 0)
ORDER BY tm.drg_desc;
-- DROP TEMPORARY TABLE t_medicare_1 -- Comment back in later
|
import 'highlight.js/styles/atom-one-dark.css'
import { Document, PDFDownloadLink, Page } from '@react-pdf/renderer'
import {
BubbleMenu,
EditorContent,
FloatingMenu,
useEditor,
} from '@tiptap/react'
import {
RxChatBubble,
RxChevronDown,
RxCode,
RxFile,
RxFontBold,
RxFontItalic,
RxHeading,
RxListBullet,
RxStrikethrough,
} from 'react-icons/rx'
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight'
import StarterKit from '@tiptap/starter-kit'
import js from 'highlight.js/lib/languages/javascript'
import { lowlight } from 'lowlight'
import { useState } from 'react'
import ReactDOMServer from 'react-dom/server'
import { Html } from 'react-pdf-html'
import { BubbleButton } from './BubbleButton'
import { initialContent } from './initialContent'
lowlight.registerLanguage('js', js)
export default function Editor() {
const [contentText, setContentText] = useState('')
const today = new Date()
const editor = useEditor({
extensions: [
StarterKit,
CodeBlockLowlight.configure({
lowlight,
}),
],
onUpdate: ({ editor }) => {
setContentText(editor.getHTML())
localStorage.setItem('content', editor.getHTML())
},
content: localStorage.getItem('content') || initialContent,
editorProps: {
attributes: {
class: 'outline-none',
},
},
})
if (!editor) {
return null
}
const element = (contentText: string) => (
<html>
<body>{contentText}</body>
</html>
)
const html = ReactDOMServer.renderToStaticMarkup(element(contentText))
return (
<>
<PDFDownloadLink
document={
<Document>
<Page size="A4">
<Html>{html}</Html>
</Page>
</Document>
}
fileName={`documento-${today.getDate()}-${today.getMonth()}-${today.getFullYear()}.pdf`}
className="flex items-center justify-center w-full py-2 text-center text-white bg-red-500 hover:bg-red-400 gap-2 transition-colors duration-200 rounded-lg"
>
<RxFile className="w-6 h-6" /> Exportar PDF
</PDFDownloadLink>
<EditorContent
editor={editor}
className="max-w-[700px] mx-auto pt-16 prose prose-invert prose-violet"
/>
<BubbleMenu
editor={editor}
className="bg-zinc-700 border border-zinc-600 shadow-xl shadow-black/20 rounded-lg overflow-hidden flex divide-x divide-zinc-600"
>
<BubbleButton
icon={<RxChatBubble className="w-4 h-4" />}
// onClick={() => editor.chain().focus().toggleBold().run()}
text="Comentar"
/>
<BubbleButton
icon={<RxChevronDown className="w-4 h-4" />}
// onClick={() => editor.chain().focus().toggleBold().run()}
text="Text"
/>
<div className="flex items-center">
<BubbleButton
icon={<RxFontBold className="w-4 h-4" />}
onClick={() => editor.chain().focus().toggleBold().run()}
data-active={editor.isActive('bold')}
/>
<BubbleButton
icon={<RxFontItalic className="w-4 h-4" />}
onClick={() => editor.chain().focus().toggleItalic().run()}
data-active={editor.isActive('italic')}
/>
<BubbleButton
icon={<RxStrikethrough className="w-4 h-4" />}
onClick={() => editor.chain().focus().toggleStrike().run()}
data-active={editor.isActive('strike')}
/>
<BubbleButton
icon={<RxCode className="w-4 h-4" />}
onClick={() => editor.chain().focus().toggleCodeBlock().run()}
data-active={editor.isActive('codeBlock')}
/>
</div>
</BubbleMenu>
<FloatingMenu
editor={editor}
shouldShow={({ state }) => {
const { $from } = state.selection
const currentLineText = $from.nodeBefore?.textContent
return currentLineText === '/'
}}
className="bg-zinc-700 border border-zinc-600 shadow-xl shadow-black/20 rounded-lg overflow-hidden flex flex-col divide-x divide-zinc-600"
>
<BubbleButton
icon={<RxHeading className="w-4 h-4" />}
onClick={() =>
editor.chain().focus().toggleHeading({ level: 1 }).run()
}
data-active={editor.isActive('heading', { level: 1 })}
text="Título"
/>
<BubbleButton
icon={<RxListBullet className="w-4 h-4" />}
onClick={() => editor.chain().focus().toggleBulletList().run()}
data-active={editor.isActive('bulletList')}
text="Lista"
/>
</FloatingMenu>
</>
)
}
|
# 创造的基石
> 原文:<https://dev.to/decentraland/building-blocks-of-creation-2ba8>
这是一系列视频教程的第一部分,将教你使用分散 SDK 的基础知识。
我们很快就要迎来 9 月 16 日和我们的 [Game Jam](https://gamejam.decentraland.org/) 的开始——这是一个为期两周的活动,艺术家和开发者将使用分散的 SDK 创建交互式 3D 场景,并争夺超过 250,000 美元的 MANA 和土地奖金。
在发布之前,我们将推出两项关键计划:
第一个,我们将在接下来的帖子中介绍,是在世界各地多个城市举行的一系列线下讲座和训练营。第二个是 SDK 教程系列...
### 创造的积木
本系列教程涵盖了分散式 SDK 的基本机制。这包括:
* 如何安装 SDK
* 如何放置对象并制作动画
* 如何管理点击事件
* 如何实现 UI
* 如何使用新的“utils”库,它极大地增强了开发体验
到本系列结束时,你将具备完成你自己的由九个不同房间组成的逃生室游戏的知识(可以在 [this GitHub repo](https://github.com/decentraland-scenes/Escape-Room) 中找到),所以准备好享受乐趣吧!
即使你从未做过任何游戏开发,你也会发现这些视频内容丰富且易于理解。它们可以作为一个系列或独立的模块来理解:
### 你将学到什么
1. [介绍逃生室游戏和系列教程的目标。](https://www.youtube.com/watch?v=j7XbiTZ9GN0&feature=youtu.be)
2. 设置您的开发环境,创建一个分散的场景,并放置一个 3D 模型。
3. 给你的场景添加一个 3D 模型,并设置它的坐标。
4. [播放动画开门。](https://www.youtube.com/watch?v=QHgOIh04ukY)
5. 添加开门时播放的音效。
6. 将每个房间的代码移动到它自己的文件中。
### 出来像个建筑工。像强盗一样亲热
在我们的分散的 SDK 教程系列的结尾,你也将拥有你所需要的一切,以一个合格的 3D 场景来结束游戏,如果你提交它,可以让你获得 1000 法力,以及前 20 名获胜者的土地和 25,000 到 350,000 法力的奖金。
但是你必须参加才能赢得它,所以[注册](https://gamejam.decentraland.org/),向上滚动并开始观看。另外,请务必关注我们的分散式 SDK 教程系列。
元宇宙见!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.