text
stringlengths 184
4.48M
|
---|
import { CompensationGroup } from "./CompensationGroup";
import { PayoutPreferrences } from "./PayoutPreferrences";
import { Role } from "./enums/Role";
import { Timestamp, DocumentData } from "firebase/firestore";
export class User {
uid: string;
profilePictureSrc: string | null;
firstName: string;
lastName: string;
email: string;
roles: Role[];
phone: string | null;
registeredAt: Date;
compensationGroupId: string | null;
payoutPreferrences?: PayoutPreferrences;
pastCompGroupIds: Set<string>;
constructor({
uid,
profilePictureSrc = null,
firstName,
lastName,
email,
phone = null,
roles = [Role.salesperson],
registeredAt,
compensationGroupId = null,
payoutPreferrences,
pastCompGroupIds,
}: {
uid: string;
profilePictureSrc?: string | null;
firstName: string;
lastName: string;
email: string;
phone?: string | null;
roles: Role[];
registeredAt: Date;
compensationGroupId?: string | null;
payoutPreferrences?: PayoutPreferrences;
pastCompGroupIds?: Set<string>;
}) {
this.uid = uid;
this.profilePictureSrc = profilePictureSrc;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.roles = roles;
this.phone = phone;
this.compensationGroupId = compensationGroupId;
this.payoutPreferrences = payoutPreferrences;
this.registeredAt = registeredAt;
this.pastCompGroupIds = pastCompGroupIds ?? new Set<string>();
}
public static create({
uid,
profilePictureSrc,
firstName,
lastName,
email,
compensationGroupId,
}: {
uid: string;
profilePictureSrc?: string;
firstName: string;
lastName: string;
email: string;
compensationGroupId?: string;
}): User {
return new User({
uid,
profilePictureSrc,
firstName,
lastName,
email,
roles: [Role.salesperson],
registeredAt: new Date(),
compensationGroupId,
});
}
public isAdmin = () => this.roles.includes(Role.admin);
public isSalesperson = () => this.roles.includes(Role.salesperson);
public getFullName = () => `${this.firstName} ${this.lastName}`;
public updateCompGroup = (compGroup: CompensationGroup | null) => {
if (compGroup != null) {
this.pastCompGroupIds.add(compGroup.id);
}
this.compensationGroupId = compGroup?.id ?? null;
};
public toFirestoreDoc = (): DocumentData => {
return {
uid: this.uid,
profilePictureSrc: this.profilePictureSrc,
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
roles: this.roles,
phone: this.phone,
registeredAt: this.registeredAt
? Timestamp.fromDate(this.registeredAt)
: null,
compensationGroupId: this.compensationGroupId,
payoutPreferrences: this.payoutPreferrences?.toFirestoreDoc() ?? null,
pastCompGroupIds: Array.from(this.pastCompGroupIds),
};
};
public static fromFirestoreDoc = (doc: DocumentData): User => {
return new User({
uid: doc.uid,
profilePictureSrc: doc.profilePictureSrc,
firstName: doc.firstName,
lastName: doc.lastName,
email: doc.email,
roles: doc.roles,
phone: doc.phone,
registeredAt: doc.registeredAt ? doc.registeredAt.toDate() : new Date(),
compensationGroupId: doc.compensationGroupId,
payoutPreferrences: doc.payoutPreferrences
? PayoutPreferrences.fromFirestoreDoc(doc.payoutPreferrences)
: undefined,
pastCompGroupIds: new Set(doc.pastCompGroupIds ?? []),
});
};
} |
= Conversational Agent
:order: 4
:type: challenge
:optional: true
During this course, you have learned about the fundamentals of LLMs, how to interact with them using langchain, and how Neo4j can support the LLM in answering questions.
In this optional challenge you will apply this new knowledge and skills to a new problem.
You will create a conversational agent using Langchain that can answer questions about a topic you are interested in.
The agent should:
* Use a prompt that sets the scene for the LLM
* Be given additional context that is relevant to the scenario
* Have conversational memory and be able to answer a string of questions
* Be given a few-shot example to support it in answering a specific type of question
I recommend that you approach this challenge in the following order:
. Choose a topic that you are interested in
. Create a prompt and create a chain that uses the prompt
. Create an agent and add conversational memory
. Add additional context to the agent
. Add a few-shot example to the agent
== Next Steps
You can learn more about creating chat bots using Neo4j in the next GraphAcademy course - link:https://graphacademy.neo4j.com/courses/llm-chatbot-python/[Build a Neo4j-backed Chatbot using Python^].
read::Continue[]
[.summary]
== Summary
In this optional challenge, you used the knowledge and skills you have learned during this course to create a conversational agent.
Congratulations on completing this course. I hope you have enjoyed it and learned a lot. |
# Axios 取消请求
## 步骤
1. 发请求时携带取消令牌
2. 在需要取消时(如路由离开时 beforeRouteLeave)调用方法取消所有携带取消令牌的请求
## 用法
```js
const source = axios.CancelToken.source()
axios.get('/api/a', {
// 取消令牌
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('请求已取消', thrown.message)
}
})
axios.get('/api/b', {
// 取消令牌
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('请求已取消', thrown.message)
}
})
// 取消请求
source.cancel()
``` |
package monitor
import (
pb "avatar/services/gateway/protos/pos"
"context"
)
type CreateMonitorInput struct {
Maker string `json:"maker" binding:"required"`
SerialNumber string `json:"serialNumber" binding:"required"`
MonitorStatus string `json:"monitorStatus"`
ResolutionWidth int64 `json:"resolutionWidth" binding:"required"`
ResolutionHeight int64 `json:"resolutionHeight" binding:"required"`
HorizontalRotation bool `json:"horizontalRotation"`
PosId int64 `json:"posId" binding:"required"`
}
type CreateMonitorOutput struct {
Id int64 `json:"id"`
Maker string `json:"maker"`
SerialNumber string `json:"serialNumber"`
MonitorStatus string `json:"monitorStatus"`
ResolutionWidth int64 `json:"resolutionWidth"`
ResolutionHeight int64 `json:"resolutionHeight"`
HorizontalRotation bool `json:"horizontalRotation"`
PosId int64 `json:"posId"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt,omitempty"`
}
func CreateMonitor(input *CreateMonitorInput, posClient pb.POSClient) (*CreateMonitorOutput, error) {
data := &pb.CreateMonitorRequest{
Maker: input.Maker,
SerialNumber: input.SerialNumber,
MonitorStatus: input.MonitorStatus,
ResolutionWidth: input.ResolutionWidth,
ResolutionHeight: input.ResolutionHeight,
HorizontalRotation: input.HorizontalRotation,
PosId: input.PosId,
}
response, err := posClient.CreateMonitor(context.Background(), data)
if err != nil {
return nil, err
}
output := &CreateMonitorOutput{
Id: response.Id,
Maker: response.Maker,
SerialNumber: response.SerialNumber,
MonitorStatus: response.MonitorStatus,
ResolutionWidth: response.ResolutionWidth,
ResolutionHeight: response.ResolutionHeight,
HorizontalRotation: response.HorizontalRotation,
PosId: response.PosId,
CreatedAt: response.CreatedAt,
}
return output, nil
} |
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import EditarTurno from './EditarTurno';
import './Turnos.css';
function Turnos() {
const [turnos, setTurnos] = useState([]);
const [cliente, setCliente] = useState('');
const [apellido, setApellido] = useState('');
const [celular, setCelular] = useState('');
const [mensaje, setMensaje] = useState('');
const [fecha, setFecha] = useState('');
const [hora, setHora] = useState('');
const [servicio, setServicio] = useState('');
const [editando, setEditando] = useState(false);
const [turnoToEdit, setTurnoToEdit] = useState(null);
useEffect(() => {
fetchTurnos();
}, []);
const fetchTurnos = () => {
axios.get('http://localhost:3001/turnos')
.then(response => {
setTurnos(response.data);
})
.catch(error => {
console.error("Error al recuperar los turnos", error);
});
};
const agregarTurno = () => {
axios.post('http://localhost:3001/turnos', {
cliente,
apellido,
celular,
mensaje,
fecha,
hora,
servicio
})
.then(() => {
fetchTurnos();
setCliente('');
setApellido('');
setCelular('');
setMensaje('');
setFecha('');
setHora('');
setServicio('');
})
.catch(error => {
console.error("Error al agregar el turno:", error);
});
};
const editar = (turno) => {
setTurnoToEdit(turno);
setEditando(true);
};
const eliminarTurno = (id) => {
axios.delete(`http://localhost:3001/turnos/${id}`)
.then(() => {
fetchTurnos();
})
.catch(error => {
console.error("Error al eliminar el turno:", error);
});
};
return (
<div className="Turnos-container">
{editando ? (
<EditarTurno turno={turnoToEdit} onFinish={() => {
setEditando(false);
fetchTurnos();
}} />
) : (
<>
<div className="Turnos-formContainer">
<h2>Agendar Turno</h2>
<input className="Turnos-input" placeholder="Nombre" value={cliente} onChange={e => setCliente(e.target.value)} />
<input className="Turnos-input" placeholder="Apellido" value={apellido} onChange={e => setApellido(e.target.value)} />
<input className="Turnos-input" placeholder="Celular" value={celular} onChange={e => setCelular(e.target.value)} />
<textarea className="Turnos-textarea" placeholder="Mensaje (Opcional)" value={mensaje} onChange={e => setMensaje(e.target.value)} />
<input className="Turnos-input" type="date" value={fecha} onChange={e => setFecha(e.target.value)} />
<input className="Turnos-input" type="time" value={hora} onChange={e => setHora(e.target.value)} />
<input className="Turnos-input" placeholder="Servicio" value={servicio} onChange={e => setServicio(e.target.value)} />
<button className="Turnos-addButton" onClick={agregarTurno}>Agendar Turno</button>
</div>
<div className="Turnos-list">
<h2>Turnos Agendados</h2>
{turnos.map(turno => (
<div key={turno.id} className="Turnos-listItem">
{turno.cliente} {turno.apellido} - {turno.celular} - {turno.mensaje ? `${turno.mensaje} - ` : ""} {turno.fecha} - {turno.hora} - {turno.servicio}
</div>
))}
</div>
</>
)}
<Footer />
</div>
);
}
function Footer() {
return (
<div className="Turnos-footer">
<p>© 2023 La Escabioneta. Todos los derechos reservados.</p>
</div>
);
}
export default Turnos; |
/*
* Caturix, a command processing library
* Copyright (C) Intake team and contributors
* Copyright (C) Caturix team and contributors
*
* This program 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.
*
* 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fablesfantasyrp.caturix.argument
/**
* Argument exceptions occur when there is a problem with user-provided
* arguments, whether it be because of incorrect arguments, missing arguments,
* or excess arguments.
*
* @see ArgumentParseException
*
* @see MissingArgumentException
*
* @see UnusedArgumentException
*/
open class ArgumentException : Exception {
protected constructor() : super()
protected constructor(message: String?) : super(message)
protected constructor(message: String?, cause: Throwable?) : super(message, cause)
protected constructor(cause: Throwable?) : super(cause)
} |
<div class="modal fade" id="modal-schedule-appointment">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Schedule Appointments</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" (click)="onClose()">
<span aria-hidden="true">×</span>
</button>
</div>
<form [formGroup]="vitalForm">
<div class="modal-body">
<div class="form-group">
<label for="location">Location</label>
<select required
[ngClass]="(location.invalid && (location.dirty || location.touched)) ? 'form-control is-invalid' : (location.valid)? 'form-control is-valid':'form-control'"
formControlName="location" id="location">
<option value="">Select One</option>
<option value="Lagos">Lagos</option>
<option value="Abuja">Abuja</option>
<option value="Rivers">Rivers</option>
<option value="Outside Nigeria">Outside Nigeria</option>
</select>
<div *ngIf="location.invalid && (location.dirty || location.touched)" class="invalid-feedback">
<div *ngIf="location.errors.required">Select an Location</div>
</div>
</div>
<div class="form-group">
<label for="procedure">Procedure</label>
<select required
[ngClass]="(procedure.invalid && (procedure.dirty || procedure.touched)) ? 'form-control is-invalid' : (procedure.valid)? 'form-control is-valid':'form-control'"
formControlName="procedure" id="procedure">
<option value="">Select One</option>
<option value="Boady Confidence">Boady Confidence</option>
<option value="Facials">Facials</option>
<option value="Breast">Breast</option>
<option value="Skin">Skin</option>
</select>
<div *ngIf="procedure.invalid && (procedure.dirty || procedure.touched)"
class="invalid-feedback">
<div *ngIf="procedure.errors.required">Select an Procedure</div>
</div>
</div>
<div class="form-group">
<label for="next_appointment">Appointment Date</label>
<input type="datetime-local" required
[ngClass]="(next_appointment.invalid && (next_appointment.dirty || next_appointment.touched)) ? 'form-control is-invalid' : (next_appointment.valid)? 'form-control is-valid':'form-control'"
formControlName="next_appointment" id="next_appointment" placeholder="Appointment Date"
min="{{date | date:'yyyy-MM-ddTHH:mm'}}">
<div *ngIf="next_appointment.invalid && (next_appointment.dirty || next_appointment.touched)"
class="invalid-feedback">
<div *ngIf="next_appointment.errors.required">appointment date is required</div>
</div>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea
[ngClass]="(message.invalid && (message.dirty || message.touched)) ? 'form-control is-invalid' : (message.valid)? 'form-control is-valid':'form-control'"
formControlName="message" id="message" placeholder="Description"></textarea>
<div *ngIf="message.invalid && (message.dirty || message.touched)" class="invalid-feedback">
<div *ngIf="message.errors.maxLength">Message is required</div>
</div>
</div>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-warning" data-dismiss="modal" (click)="onClose()">Close</button>
<button type="submit" [disabled]="!vitalForm.valid || vitalForm.pending || processing" (click)="onCreate()" class="btn btn-success">Book Appointment</button>
</div>
</form>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal --> |
#include "duckdb/execution/operator/aggregate/physical_perfecthash_aggregate.hpp"
#include "duckdb/execution/perfect_aggregate_hashtable.hpp"
#include "duckdb/planner/expression/bound_aggregate_expression.hpp"
#include "duckdb/planner/expression/bound_reference_expression.hpp"
#include "duckdb/storage/buffer_manager.hpp"
#include "duckdb/storage/statistics/numeric_statistics.hpp"
namespace duckdb {
PhysicalPerfectHashAggregate::PhysicalPerfectHashAggregate(ClientContext &context, vector<LogicalType> types_p,
vector<unique_ptr<Expression>> aggregates_p,
vector<unique_ptr<Expression>> groups_p,
vector<unique_ptr<BaseStatistics>> group_stats,
vector<idx_t> required_bits_p, idx_t estimated_cardinality)
: PhysicalOperator(PhysicalOperatorType::PERFECT_HASH_GROUP_BY, std::move(types_p), estimated_cardinality),
groups(std::move(groups_p)), aggregates(std::move(aggregates_p)), required_bits(std::move(required_bits_p)) {
D_ASSERT(groups.size() == group_stats.size());
group_minima.reserve(group_stats.size());
for (auto &stats : group_stats) {
D_ASSERT(stats);
auto &nstats = (NumericStatistics &)*stats;
D_ASSERT(!nstats.min.IsNull());
group_minima.push_back(std::move(nstats.min));
}
for (auto &expr : groups) {
group_types.push_back(expr->return_type);
}
vector<BoundAggregateExpression *> bindings;
vector<LogicalType> payload_types_filters;
for (auto &expr : aggregates) {
D_ASSERT(expr->expression_class == ExpressionClass::BOUND_AGGREGATE);
D_ASSERT(expr->IsAggregate());
auto &aggr = (BoundAggregateExpression &)*expr;
bindings.push_back(&aggr);
D_ASSERT(!aggr.IsDistinct());
D_ASSERT(aggr.function.combine);
for (auto &child : aggr.children) {
payload_types.push_back(child->return_type);
}
if (aggr.filter) {
payload_types_filters.push_back(aggr.filter->return_type);
}
}
for (const auto &pay_filters : payload_types_filters) {
payload_types.push_back(pay_filters);
}
aggregate_objects = AggregateObject::CreateAggregateObjects(bindings);
// filter_indexes must be pre-built, not lazily instantiated in parallel...
idx_t aggregate_input_idx = 0;
for (auto &aggregate : aggregates) {
auto &aggr = (BoundAggregateExpression &)*aggregate;
aggregate_input_idx += aggr.children.size();
}
for (auto &aggregate : aggregates) {
auto &aggr = (BoundAggregateExpression &)*aggregate;
if (aggr.filter) {
auto &bound_ref_expr = (BoundReferenceExpression &)*aggr.filter;
auto it = filter_indexes.find(aggr.filter.get());
if (it == filter_indexes.end()) {
filter_indexes[aggr.filter.get()] = bound_ref_expr.index;
bound_ref_expr.index = aggregate_input_idx++;
} else {
++aggregate_input_idx;
}
}
}
}
unique_ptr<PerfectAggregateHashTable> PhysicalPerfectHashAggregate::CreateHT(Allocator &allocator,
ClientContext &context) const {
return make_unique<PerfectAggregateHashTable>(context, allocator, group_types, payload_types, aggregate_objects,
group_minima, required_bits);
}
//===--------------------------------------------------------------------===//
// Sink
//===--------------------------------------------------------------------===//
class PerfectHashAggregateGlobalState : public GlobalSinkState {
public:
PerfectHashAggregateGlobalState(const PhysicalPerfectHashAggregate &op, ClientContext &context)
: ht(op.CreateHT(Allocator::Get(context), context)) {
}
//! The lock for updating the global aggregate state
mutex lock;
//! The global aggregate hash table
unique_ptr<PerfectAggregateHashTable> ht;
};
class PerfectHashAggregateLocalState : public LocalSinkState {
public:
PerfectHashAggregateLocalState(const PhysicalPerfectHashAggregate &op, ExecutionContext &context)
: ht(op.CreateHT(Allocator::Get(context.client), context.client)) {
group_chunk.InitializeEmpty(op.group_types);
if (!op.payload_types.empty()) {
aggregate_input_chunk.InitializeEmpty(op.payload_types);
}
}
//! The local aggregate hash table
unique_ptr<PerfectAggregateHashTable> ht;
DataChunk group_chunk;
DataChunk aggregate_input_chunk;
};
unique_ptr<GlobalSinkState> PhysicalPerfectHashAggregate::GetGlobalSinkState(ClientContext &context) const {
return make_unique<PerfectHashAggregateGlobalState>(*this, context);
}
unique_ptr<LocalSinkState> PhysicalPerfectHashAggregate::GetLocalSinkState(ExecutionContext &context) const {
return make_unique<PerfectHashAggregateLocalState>(*this, context);
}
SinkResultType PhysicalPerfectHashAggregate::Sink(ExecutionContext &context, GlobalSinkState &state,
LocalSinkState &lstate_p, DataChunk &input) const {
auto &lstate = (PerfectHashAggregateLocalState &)lstate_p;
DataChunk &group_chunk = lstate.group_chunk;
DataChunk &aggregate_input_chunk = lstate.aggregate_input_chunk;
for (idx_t group_idx = 0; group_idx < groups.size(); group_idx++) {
auto &group = groups[group_idx];
D_ASSERT(group->type == ExpressionType::BOUND_REF);
auto &bound_ref_expr = (BoundReferenceExpression &)*group;
group_chunk.data[group_idx].Reference(input.data[bound_ref_expr.index]);
}
idx_t aggregate_input_idx = 0;
for (auto &aggregate : aggregates) {
auto &aggr = (BoundAggregateExpression &)*aggregate;
for (auto &child_expr : aggr.children) {
D_ASSERT(child_expr->type == ExpressionType::BOUND_REF);
auto &bound_ref_expr = (BoundReferenceExpression &)*child_expr;
aggregate_input_chunk.data[aggregate_input_idx++].Reference(input.data[bound_ref_expr.index]);
}
}
for (auto &aggregate : aggregates) {
auto &aggr = (BoundAggregateExpression &)*aggregate;
if (aggr.filter) {
auto it = filter_indexes.find(aggr.filter.get());
D_ASSERT(it != filter_indexes.end());
aggregate_input_chunk.data[aggregate_input_idx++].Reference(input.data[it->second]);
}
}
group_chunk.SetCardinality(input.size());
aggregate_input_chunk.SetCardinality(input.size());
group_chunk.Verify();
aggregate_input_chunk.Verify();
D_ASSERT(aggregate_input_chunk.ColumnCount() == 0 || group_chunk.size() == aggregate_input_chunk.size());
lstate.ht->AddChunk(group_chunk, aggregate_input_chunk);
return SinkResultType::NEED_MORE_INPUT;
}
//===--------------------------------------------------------------------===//
// Combine
//===--------------------------------------------------------------------===//
void PhysicalPerfectHashAggregate::Combine(ExecutionContext &context, GlobalSinkState &gstate_p,
LocalSinkState &lstate_p) const {
auto &lstate = (PerfectHashAggregateLocalState &)lstate_p;
auto &gstate = (PerfectHashAggregateGlobalState &)gstate_p;
lock_guard<mutex> l(gstate.lock);
gstate.ht->Combine(*lstate.ht);
}
//===--------------------------------------------------------------------===//
// Source
//===--------------------------------------------------------------------===//
class PerfectHashAggregateState : public GlobalSourceState {
public:
PerfectHashAggregateState() : ht_scan_position(0) {
}
//! The current position to scan the HT for output tuples
idx_t ht_scan_position;
};
unique_ptr<GlobalSourceState> PhysicalPerfectHashAggregate::GetGlobalSourceState(ClientContext &context) const {
return make_unique<PerfectHashAggregateState>();
}
void PhysicalPerfectHashAggregate::GetData(ExecutionContext &context, DataChunk &chunk, GlobalSourceState &gstate_p,
LocalSourceState &lstate) const {
auto &state = (PerfectHashAggregateState &)gstate_p;
auto &gstate = (PerfectHashAggregateGlobalState &)*sink_state;
gstate.ht->Scan(state.ht_scan_position, chunk);
}
string PhysicalPerfectHashAggregate::ParamsToString() const {
string result;
for (idx_t i = 0; i < groups.size(); i++) {
if (i > 0) {
result += "\n";
}
result += groups[i]->GetName();
}
for (idx_t i = 0; i < aggregates.size(); i++) {
if (i > 0 || !groups.empty()) {
result += "\n";
}
result += aggregates[i]->GetName();
auto &aggregate = (BoundAggregateExpression &)*aggregates[i];
if (aggregate.filter) {
result += " Filter: " + aggregate.filter->GetName();
}
}
return result;
}
} // namespace duckdb |
/**
* WordPress dependencies
*/
import { useEffect } from "@wordpress/element";
import {
WRAPPER_BG,
WRAPPER_MARGIN,
WRAPPER_PADDING,
WRAPPER_BORDER_SHADOW,
ICON_SIZE,
BORDER,
BORDER_WIDTH,
} from "./constants";
const {
softMinifyCssStrings,
generateTypographyStyles,
generateResponsiveRangeStyles,
generateDimensionsControlStyles,
generateBorderShadowStyles,
generateBackgroundControlStyles,
} = window.EBControls;
export default function Style(props) {
const { attributes, setAttributes } = props;
const {
resOption,
blockMeta,
blockId,
iconAlign,
iconPadding,
iconPrimaryColor,
iconPrimaryHoverColor,
iconSecondaryColor,
iconSecondaryHoverColor,
} = attributes;
const {
dimensionStylesDesktop: wrapperMarginDesktop,
dimensionStylesTab: wrapperMarginTab,
dimensionStylesMobile: wrapperMarginMobile,
} = generateDimensionsControlStyles({
controlName: WRAPPER_MARGIN,
styleFor: "margin",
attributes,
});
const {
dimensionStylesDesktop: wrapperPaddingDesktop,
dimensionStylesTab: wrapperPaddingTab,
dimensionStylesMobile: wrapperPaddingMobile,
} = generateDimensionsControlStyles({
controlName: WRAPPER_PADDING,
styleFor: "padding",
attributes,
});
const {
backgroundStylesDesktop: wrapperBackgroundStylesDesktop,
hoverBackgroundStylesDesktop: wrapperHoverBackgroundStylesDesktop,
backgroundStylesTab: wrapperBackgroundStylesTab,
hoverBackgroundStylesTab: wrapperHoverBackgroundStylesTab,
backgroundStylesMobile: wrapperBackgroundStylesMobile,
hoverBackgroundStylesMobile: wrapperHoverBackgroundStylesMobile,
overlayStylesDesktop: wrapperOverlayStylesDesktop,
hoverOverlayStylesDesktop: wrapperHoverOverlayStylesDesktop,
overlayStylesTab: wrapperOverlayStylesTab,
hoverOverlayStylesTab: wrapperHoverOverlayStylesTab,
overlayStylesMobile: wrapperOverlayStylesMobile,
hoverOverlayStylesMobile: wrapperHoverOverlayStylesMobile,
bgTransitionStyle: wrapperBgTransitionStyle,
ovlTransitionStyle: wrapperOvlTransitionStyle,
} = generateBackgroundControlStyles({
attributes,
controlName: WRAPPER_BG,
});
const {
styesDesktop: wrapperBDShadowDesktop,
styesTab: wrapperBDShadowTab,
styesMobile: wrapperBDShadowMobile,
stylesHoverDesktop: wrapperBDShadowHoverDesktop,
stylesHoverTab: wrapperBDShadowHoverTab,
stylesHoverMobile: wrapperBDShadowHoverMobile,
transitionStyle: wrapperBDShadowTransition,
} = generateBorderShadowStyles({
controlName: WRAPPER_BORDER_SHADOW,
attributes,
});
// icon size
const {
rangeStylesDesktop: iconSizeDesktop,
rangeStylesTab: iconSizeTab,
rangeStylesMobile: iconSizeMobile,
} = generateResponsiveRangeStyles({
controlName: ICON_SIZE,
property: "font-size",
attributes,
});
const {
dimensionStylesDesktop: iconBorderDesktop,
dimensionStylesTab: iconBorderTab,
dimensionStylesMobile: iconBorderMobile,
} = generateDimensionsControlStyles({
controlName: BORDER,
styleFor: "border-radius",
attributes,
});
const {
dimensionStylesDesktop: iconBorderWidthDesktop,
dimensionStylesTab: iconBorderWidthTab,
dimensionStylesMobile: iconBorderWidthMobile,
} = generateDimensionsControlStyles({
controlName: BORDER_WIDTH,
styleFor: "border",
attributes,
});
// all desktop styls start
// Desktop Wrapper
const desktopWrapper = `
.${blockId}.eb-icon-wrapper {
text-align: ${iconAlign};
${wrapperMarginDesktop}
${wrapperPaddingDesktop}
${wrapperBDShadowDesktop}
${wrapperBackgroundStylesDesktop}
transition:${wrapperBgTransitionStyle}, ${wrapperBDShadowTransition};
}
.${blockId}.eb-icon-wrapper:hover {
${wrapperBDShadowHoverDesktop}
}
`;
const desktopIcon = `
.${blockId}.eb-icon-wrapper.eb-icon-view-framed .eb-icon-container,
.${blockId}.eb-icon-wrapper.eb-icon-view-default .eb-icon-container {
${iconPrimaryColor ? `color: ${iconPrimaryColor};` : ""}
}
.${blockId}.eb-icon-wrapper.eb-icon-view-framed .eb-icon-container {
${
iconSecondaryColor
? `background-color: ${iconSecondaryColor};`
: ""
}
${iconPrimaryColor ? `border-color: ${iconPrimaryColor};` : ""}
}
.${blockId}.eb-icon-wrapper.eb-icon-view-framed .eb-icon-container:hover {
${iconPrimaryHoverColor ? `color: ${iconPrimaryHoverColor};` : ""}
${
iconPrimaryHoverColor
? `border-color: ${iconPrimaryHoverColor};`
: ""
}
${
iconSecondaryHoverColor
? `background-color: ${iconSecondaryHoverColor};`
: ""
}
}
.${blockId}.eb-icon-wrapper.eb-icon-view-stacked .eb-icon-container {
${iconPrimaryColor ? `background-color: ${iconPrimaryColor};` : ""}
${iconSecondaryColor ? `color: ${iconSecondaryColor};` : ""}
}
.${blockId}.eb-icon-wrapper.eb-icon-view-stacked .eb-icon-container:hover {
${
iconPrimaryHoverColor
? `background-color: ${iconPrimaryHoverColor};`
: ""
}
${
iconSecondaryHoverColor
? `color: ${iconSecondaryHoverColor};`
: ""
}
}
.${blockId}.eb-icon-wrapper .eb-icon-container {
${iconSizeDesktop}
${iconPadding ? `padding: ${iconPadding}px;` : ""}
${iconBorderDesktop}
${iconBorderWidthDesktop}
}
`;
// ALL TAB Styles
// tab Wrapper
const tabWrapper = `
.${blockId}.eb-icon-wrapper{
${wrapperMarginTab}
${wrapperPaddingTab}
${wrapperBDShadowTab}
${wrapperBackgroundStylesTab}
}
.${blockId}.eb-icon-wrapper:hover {
${wrapperBDShadowHoverTab}
}
`;
const tabIcon = `
.${blockId}.eb-icon-wrapper .eb-icon-container {
${iconSizeTab}
${iconBorderTab}
${iconBorderWidthTab}
}
`;
// ALL MOBILE Styles
// mobile Wrapper
const mobileWrapper = `
.eb-parent-${blockId} {
line-height: 0;
}
.${blockId}.eb-icon-wrapper {
${wrapperMarginMobile}
${wrapperPaddingMobile}
${wrapperBDShadowMobile}
${wrapperBackgroundStylesMobile}
}
.${blockId}.eb-icon-wrapper:hover {
${wrapperBDShadowHoverMobile}
}
`;
const mobileIcon = `
.${blockId}.eb-icon-wrapper .eb-icon-container {
${iconSizeMobile}
${iconBorderMobile}
${iconBorderWidthMobile}
}
`;
// all css styles for large screen width (desktop/laptop) in strings ⬇
// all desktop
const desktopAllStyles = softMinifyCssStrings(`
${desktopWrapper}
${desktopIcon}
`);
// all css styles for Tab in strings ⬇
const tabAllStyles = softMinifyCssStrings(`
${tabWrapper}
${tabIcon}
`);
// all css styles for Mobile in strings ⬇
const mobileAllStyles = softMinifyCssStrings(`
${mobileWrapper}
${mobileIcon}
`);
// Set All Style in "blockMeta" Attribute
useEffect(() => {
const styleObject = {
desktop: desktopAllStyles,
tab: tabAllStyles,
mobile: mobileAllStyles,
};
if (JSON.stringify(blockMeta) != JSON.stringify(styleObject)) {
setAttributes({ blockMeta: styleObject });
}
}, [attributes]);
return (
<style>
{`
${desktopAllStyles}
/* mimmikcssStart */
${resOption === "Tablet" ? tabAllStyles : " "}
${resOption === "Mobile" ? tabAllStyles + mobileAllStyles : " "}
/* mimmikcssEnd */
@media all and (max-width: 1024px) {
/* tabcssStart */
${softMinifyCssStrings(tabAllStyles)}
/* tabcssEnd */
}
@media all and (max-width: 767px) {
/* mobcssStart */
${softMinifyCssStrings(mobileAllStyles)}
/* mobcssEnd */
}
`}
</style>
);
} |
import React, { useState, useEffect, useMemo } from 'react';
import { Button, Container, Row, Col, Form, Modal, Spinner } from 'react-bootstrap';
import { FiSearch } from 'react-icons/fi';
import { MdOutlineAddHome } from "react-icons/md";
import { FaEdit ,FaTrash } from "react-icons/fa";
import { SlOptions } from "react-icons/sl";
import UnidadForm from '../Form';
import LoadingSkeleton from '../../LoadingSkeleton';
import { agregarUnidad, editarUnidad, eliminarUnidad } from '../../../Context/Unidad';
import { obtenerEdificioPorCodigo, unidadesPorEdificio } from '../../../Context/Edificios';
import { useTable, useGlobalFilter, useSortBy } from 'react-table';
import './UnidadesPage.css';
import { MdEdit } from "react-icons/md";
import AccionesUnidadModal from '../MasOpciones';
function GlobalFilter({ globalFilter, setGlobalFilter }) {
return (
<Form className="d-flex align-items-center mb-3">
<FiSearch style={{ marginRight: '5px', marginTop: '0.3rem' }} />
<Form.Control
type="text"
value={globalFilter || ''}
onChange={e => setGlobalFilter(e.target.value || undefined)}
placeholder="Buscar por piso o número..."
style={{ flex: 1 }}
/>
</Form>
);
}
const UnidadesPage = () => {
const [unidades, setUnidades] = useState([]);
const [edificios, setEdificios] = useState([]);
const [edificioSeleccionado, setEdificioSeleccionado] = useState([]);
const [unidadSeleccionado, setUnidadSeleccionado] = useState({ edificio: { codigo: '', nombre: '' }, piso: '', numero: '', identificador: null });
const [mostrarModal, setMostrarModal] = useState(false);
const [loading, setLoading] = useState(true);
const [showModal, setShowModal] = useState(false);
const [mostrarModalCarga, setMostrarModalCarga] = useState(false);
useEffect(() => {
const fetchEdificios = async () => {
try {
const edificiosData = await obtenerEdificioPorCodigo();
setEdificios(edificiosData.data);
if (edificiosData.length > 0) {
setEdificioSeleccionado(edificiosData.data[0]);
console.log('edificioSeleccionado', edificioSeleccionado);
fetchUnidades(edificiosData.data[0][0]);
}
} catch (error) {
console.error('Error fetching edificios:', error);
}
};
fetchEdificios();
}, []);
const fetchUnidades = async (edificioId) => {
setLoading(true);
try {
const unidadesData = await unidadesPorEdificio(edificioId);
if (unidadesData.status === 200) {
setUnidades(unidadesData.data);
console.log('unidades', unidadesData.data);
}
else if (unidadesData.status === 403) {
setUnidades([]);
}
else {
setUnidades([]);
}
} catch (error) {
console.error('Error fetching unidades:', error);
}
finally {
setLoading(false);
}
};
const handleEdificioChange = (event) => {
const selectedEdificioId = event.target.value;
setEdificioSeleccionado(edificios.find((edificio) => edificio[0] == selectedEdificioId));
fetchUnidades(selectedEdificioId);
};
const handleGuardarUnidad = async (nuevaUnidad) => {
setMostrarModalCarga(true);
try {
if (nuevaUnidad.identificador) {
const unidad = {
identificador: nuevaUnidad.identificador,
codigo: nuevaUnidad.edificio,
piso: nuevaUnidad.piso,
numero: nuevaUnidad.numero
}
console.log('unidad-----------', unidad);
await editarUnidad(unidad);
} else {
const unidadCrear = {
codigo: nuevaUnidad.edificio,
piso: nuevaUnidad.piso,
numero: nuevaUnidad.numero
}
await agregarUnidad(unidadCrear);
}
fetchUnidades(edificioSeleccionado[0]);
setMostrarModal(false);
} catch (error) {
console.error('Error saving unidad:', error);
}
finally {
setMostrarModalCarga(false);
}
};
const handleEliminarUnidad = async (codigo) => {
setMostrarModalCarga(true);
try {
await eliminarUnidad(codigo);
fetchUnidades(edificioSeleccionado[0]);
} catch (error) {
console.error('Error deleting unidad:', error);
}
finally {
setMostrarModalCarga(false);
}
};
const handleAgregarUnidad = () => {
setUnidadSeleccionado({ edificio: { codigo: edificioSeleccionado[0], nombre: edificioSeleccionado[2] }, piso: '', numero: '', identificador: null });
console.log('unidadSeleccionado', unidadSeleccionado);
setMostrarModal(true);
};
const handleEditarUnidad = (unidad) => {
setMostrarModal(true);
const unidadEditar = unidad;
setUnidadSeleccionado({ edificio: unidadEditar.edificio, piso: unidadEditar.piso, numero: unidadEditar.numero, identificador: unidadEditar.id });
};
const handleCerrarModal = () => {
setUnidadSeleccionado(null);
setMostrarModal(false);
};
const handleOpciones = (unidad) => {
setUnidadSeleccionado(unidad);
abrirModal(true);
};
const abrirModal = (unidad) => {
setUnidadSeleccionado(unidad);
setShowModal(true);
};
const columns = useMemo(() => [
{ Header: 'Edificio', accessor: 'edificio.nombre' },
{ Header: 'Piso', accessor: 'piso' },
{ Header: 'Número', accessor: 'numero' },
{
Header: 'Acciones',
accessor: 'acciones',
Cell: ({ row }) => (
<>
<Button variant="outline-secundary" onClick={() => handleOpciones(row.original)} className="ml-2">
<SlOptions />
</Button>
<Button variant="outline-primary" onClick={() => handleEditarUnidad(row.original)} className="ml-2">
<FaEdit />
</Button>
<Button variant="outline-danger" onClick={() => handleEliminarUnidad(row.original.id)} className="ml-2">
<FaTrash />
</Button>
</>
)
}
], []);
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
state,
setGlobalFilter,
} = useTable(
{ columns, data: unidades },
useGlobalFilter,
useSortBy
);
return (
<Container className="mt-20">
<Row className="mt-3 align-items-center">
<Col>
<Form.Group controlId="formEdificioSelect">
<Form.Label>Selecciona un Edificio</Form.Label>
<Form.Control as="select" value={edificioSeleccionado[0]} onChange={handleEdificioChange} className="mb-3">
<option value="" disabled>Selecciona un edificio</option>
{edificios.map((edificio) => (
<option key={edificio[0]} value={edificio[0]}>
{edificio[2]}
</option>
))}
</Form.Control>
</Form.Group>
</Col>
<Col className="d-flex justify-content-end">
<Button variant="primary" onClick={() => handleAgregarUnidad()}>
<MdOutlineAddHome />
</Button>
</Col>
</Row>
<Row>
<Col>
<GlobalFilter
globalFilter={state.globalFilter}
setGlobalFilter={setGlobalFilter}
/>
</Col>
</Row>
<Row>
{loading ? (
<LoadingSkeleton />
) : (
<table {...getTableProps()} className="table">
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps(column.getSortByToggleProps())}>
{column.render('Header')}
<span>
{column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''}
</span>
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map(row => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
})}
</tr>
);
})}
</tbody>
</table>
)}
</Row>
{mostrarModal && (
<UnidadForm
onSave={handleGuardarUnidad}
unidadSeleccionado={unidadSeleccionado}
onClose={() => setMostrarModal(false)}
/>
)}
{showModal && ( <AccionesUnidadModal
show={showModal}
onHide={() => setShowModal(false)}
unidad={unidadSeleccionado}
dialogClassName="modal-90w"
/> )}
<Modal show={mostrarModalCarga} centered>
<Modal.Body>
<div className="text-center">
<Spinner animation="border" role="status">
<span className="sr-only">Cargando...</span>
</Spinner>
<p>Procesando...</p>
</div>
</Modal.Body>
</Modal>
</Container>
);
};
export default UnidadesPage; |
#---------------- Question 1 ----------------
# Find the missing number in an integer array of 1 to 100?
# This list has a msising number
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
def findMissing(list, n): # Where n is the total number
sum1 = sum(list) # sum1 = 4977
sum2 = n*(n + 1)/2 # sum2 = 100*(100 + 1)/2 = 5050
print(sum2-sum1) # 5050 - 4977
findMissing(mylist, 100)
#---------------- Question 2 ----------------
# Two Sum
# Write a program to find all pairs of integers whose sum is equal to a given number.
# The pairs have to be distinct, for example, not 2 and 2. And not 3, 3.
myList = [2, 6, 3, 9, 11]
target = 9
def findPairs(list, sum):
for i in range(len(list)):
for j in range(i+1,len(list)):
if (list[i]+list[j]) == sum:
print(list[i],list[j])
findPairs(list=myList, sum=target) # Returns 6 3
#---------------- Question 3 ----------------
# How to check if an array contains a number in Python
# Arrays don't have a built in search, and so this is a method to search
import numpy as np
myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
def findNumber(array, number): # This method is a linear search
for i in range(len(array)):
if array[i] == number:
print(f"The number is at index: {i}")
findNumber(myArray, 12)
#---------------- Question 4 ----------------
# Find the maximum product of two integers in an array where all integers are positive
import numpy as np
myArray = np.array([1, 20, 30, 44, 5, 56, 7, 8, 9, 10])
def findMaxProduct(array):
maxProduct = 0
for i in range(len(array)):
for j in range(i+1,len(array)):
if array[i]*array[j] > maxProduct:
maxProduct = array[i]*array[j]
pairs = str(array[i])+ "," + str(array[j])
print(pairs)
print(maxProduct)
findMaxProduct(myArray)
#---------------- Question 5 ----------------
# Implment an algorithm to determine if a list has all unique characters, using python list.
# Method 1
myList = [1, 20, 30, 44, 5, 56, 57, 8, 19, 10, 31, 12, 13, 14, 35, 16, 27, 58, 19, 21]
def isUnique(list):
a=[]
for i in list:
if i in a:
print(i)
return False
else:
a.append(i)
return True
print(isUnique(myList))
# Method 2
myList = [1, 20, 30, 44, 5, 56, 57, 8, 19, 10, 31, 12, 13, 14, 35, 16, 27, 58, 19, 21]
def isUnique(list):
for i in range(len(list)):
for j in range(i + 1, len(list)):
if list[i] == list[j]:
return print(f"The list is not unique, the number {list[i]} is not unique")
print("The list is unique")
isUnique(myList)
#---------------- Question 6 ----------------
# Given two strings, write a method to see if one is a permutation of another
# If two lists are permentations, they have the same elements but in different orders
def permutation(list1, list2):
if list1.sort() == list2.sort():
return print("The lists are permutations of each other")
else:
return print("The lists are not permutations of each other")
permutation([1, 2, 3], [3, 1, 2])
permutation(['b', 'a'], ['a', 'b'])
#---------------- Question 6 ----------------
# Given an image represented by an NxN matrix write a method to rotate the image by 90 degrees
def rotate_matrix(matrix):
'''rotates a matrix 90 degrees clockwise'''
n = len(matrix) # number of rows
for layer in range(n // 2):
# The floor operator '//', means discard the remainder of division
# n // 2 gives the number of layers of a matrix
# For example:
# 1*1 array = 1 // 2 = 0.5 --> 1 layer
# 2*2 array = 2 // 2 = 1.0 --> 1 layer
# 3*3 array = 3 // 2 = 1.5 --> 2 layer
# 4*4 array = 4 // 2 = 2.0 --> 2 layer
# 5*5 array = 5 // 2 = 2.5 --> 3 layer
# Each layer is an outer surface of the middle array number?
first = layer
last = n - layer - 1
for i in range(first, last):
# Temporarily save the top into a variable
top = matrix[layer][i]
# left -> top
matrix[layer][i] = matrix[-i - 1][layer]
# bottom -> left
matrix[-i - 1][layer] = matrix[-layer - 1][-i - 1]
# right -> bottom
matrix[-layer - 1][-i - 1] = matrix[i][- layer - 1]
# top -> right
matrix[i][- layer - 1] = top
return matrix
matrix1 = [[1,2], [3,4]]
import numpy as np
matrix2 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(matrix1)
print(rotate_matrix(matrix1))
print(matrix2)
print(rotate_matrix(matrix2)) |
import BannerPhone from '@assets/images/help-page-banner-image.png'
import AccountSectionHeader from 'components/forms/segments/AccountSectionHeader/AccountSectionHeader'
import Accordion from 'components/forms/simple-components/Accordion'
import Banner from 'components/forms/simple-components/Banner'
import { useTranslation } from 'next-i18next'
const HelpSection = () => {
const { t } = useTranslation('account')
const bannerContent = `<span className='text-p2'>${t(
'account_section_help.banner_content',
)}</span>`
return (
<div className="flex flex-col">
<AccountSectionHeader title={t('account_section_help.navigation')} />
<div className="mx-auto w-full max-w-screen-lg py-6 lg:py-16">
<h2 className="text-h2 flex justify-start px-4 lg:px-0">
{t('account_section_help.faq.title')}
</h2>
<div className="flex flex-col gap-2 px-4 md:gap-3 lg:px-0">
<h4 className="text-h4 mt-6 flex justify-start">
{t('account_section_help.faq.general_category')}
</h4>
<Accordion
title={t('account_section_help.faq.1.question')}
size="md"
content={t('account_section_help.faq.1.answer')}
/>
<Accordion
title={t('account_section_help.faq.2.question')}
size="md"
content={t('account_section_help.faq.2.answer')}
/>
<Accordion
title={t('account_section_help.faq.3.question')}
size="md"
content={t('account_section_help.faq.3.answer')}
/>
<Accordion
title={t('account_section_help.faq.4.question')}
size="md"
content={t('account_section_help.faq.4.answer')}
/>
<Accordion
title={t('account_section_help.faq.5.question')}
size="md"
content={t('account_section_help.faq.5.answer')}
/>
<Accordion
title={t('account_section_help.faq.6.question')}
size="md"
content={t('account_section_help.faq.6.answer')}
/>
<Accordion
title={t('account_section_help.faq.7.question')}
size="md"
content={t('account_section_help.faq.7.answer')}
/>
<Accordion
title={t('account_section_help.faq.28.question')}
size="md"
content={t('account_section_help.faq.28.answer')}
/>
<Accordion
title={t('account_section_help.faq.8.question')}
size="md"
content={t('account_section_help.faq.8.answer')}
/>
<Accordion
title={t('account_section_help.faq.9.question')}
size="md"
content={t('account_section_help.faq.9.answer')}
/>
<Accordion
title={t('account_section_help.faq.10.question')}
size="md"
content={t('account_section_help.faq.10.answer')}
/>
<Accordion
title={t('account_section_help.faq.11.question')}
size="md"
content={t('account_section_help.faq.11.answer')}
/>
<Accordion
title={t('account_section_help.faq.12.question')}
size="md"
content={t('account_section_help.faq.12.answer')}
/>
<h4 className="text-h4 mt-6 flex justify-start lg:mt-12">
{t('account_section_help.faq.taxes_category')}
</h4>
<Accordion
title={t('account_section_help.faq.13.question')}
size="md"
content={t('account_section_help.faq.13.answer')}
/>
<Accordion
title={t('account_section_help.faq.14.question')}
size="md"
content={t('account_section_help.faq.14.answer')}
/>
<Accordion
title={t('account_section_help.faq.15.question')}
size="md"
content={t('account_section_help.faq.15.answer')}
/>
<Accordion
title={t('account_section_help.faq.16.question')}
size="md"
content={t('account_section_help.faq.16.answer')}
/>
<Accordion
title={t('account_section_help.faq.17.question')}
size="md"
content={t('account_section_help.faq.17.answer')}
/>
<Accordion
title={t('account_section_help.faq.18.question')}
size="md"
content={t('account_section_help.faq.18.answer')}
/>
<Accordion
title={t('account_section_help.faq.19.question')}
size="md"
content={t('account_section_help.faq.19.answer')}
/>
<Accordion
title={t('account_section_help.faq.20.question')}
size="md"
content={t('account_section_help.faq.20.answer')}
/>
<Accordion
title={t('account_section_help.faq.21.question')}
size="md"
content={t('account_section_help.faq.21.answer')}
/>
<Accordion
title={t('account_section_help.faq.22.question')}
size="md"
content={t('account_section_help.faq.22.answer')}
/>
<Accordion
title={t('account_section_help.faq.23.question')}
size="md"
content={t('account_section_help.faq.23.answer')}
/>
<Accordion
title={t('account_section_help.faq.24.question')}
size="md"
content={t('account_section_help.faq.24.answer')}
/>
<Accordion
title={t('account_section_help.faq.25.question')}
size="md"
content={t('account_section_help.faq.25.answer')}
/>
<Accordion
title={t('account_section_help.faq.26.question')}
size="md"
content={t('account_section_help.faq.26.answer')}
/>
<Accordion
title={t('account_section_help.faq.27.question')}
size="md"
content={t('account_section_help.faq.27.answer')}
/>
</div>
</div>
<div className="bg-gray-50 py-0 lg:py-16">
<Banner
title="Nenašli ste odpoveď na vašu otázku?"
content={bannerContent}
buttonText={t('account_section_help.banner_button_text')}
href="mailto:info@bratislava.sk"
image={BannerPhone}
/>
</div>
</div>
)
}
export default HelpSection |
package net.minecraft.client.resources.data;
import java.lang.reflect.*;
import com.google.common.collect.*;
import net.minecraft.util.*;
import org.apache.commons.lang3.*;
import java.util.*;
import com.google.gson.*;
public class AnimationMetadataSectionSerializer extends BaseMetadataSectionSerializer implements JsonSerializer
{
public AnimationMetadataSection deserialize(final JsonElement p_deserialize_1_, final Type p_deserialize_2_, final JsonDeserializationContext p_deserialize_3_) {
final ArrayList var4 = Lists.newArrayList();
final JsonObject var5 = JsonUtils.getElementAsJsonObject(p_deserialize_1_, "metadata section");
final int var6 = JsonUtils.getJsonObjectIntegerFieldValueOrDefault(var5, "frametime", 1);
if (var6 != 1) {
Validate.inclusiveBetween(1L, 2147483647L, (long)var6, "Invalid default frame time");
}
if (var5.has("frames")) {
try {
final JsonArray var7 = JsonUtils.getJsonObjectJsonArrayField(var5, "frames");
for (int var8 = 0; var8 < var7.size(); ++var8) {
final JsonElement var9 = var7.get(var8);
final AnimationFrame var10 = this.parseAnimationFrame(var8, var9);
if (var10 != null) {
var4.add(var10);
}
}
}
catch (ClassCastException var11) {
throw new JsonParseException("Invalid animation->frames: expected array, was " + var5.get("frames"), (Throwable)var11);
}
}
final int var12 = JsonUtils.getJsonObjectIntegerFieldValueOrDefault(var5, "width", -1);
int var8 = JsonUtils.getJsonObjectIntegerFieldValueOrDefault(var5, "height", -1);
if (var12 != -1) {
Validate.inclusiveBetween(1L, 2147483647L, (long)var12, "Invalid width");
}
if (var8 != -1) {
Validate.inclusiveBetween(1L, 2147483647L, (long)var8, "Invalid height");
}
final boolean var13 = JsonUtils.getJsonObjectBooleanFieldValueOrDefault(var5, "interpolate", false);
return new AnimationMetadataSection(var4, var12, var8, var6, var13);
}
private AnimationFrame parseAnimationFrame(final int p_110492_1_, final JsonElement p_110492_2_) {
if (p_110492_2_.isJsonPrimitive()) {
return new AnimationFrame(JsonUtils.getJsonElementIntegerValue(p_110492_2_, "frames[" + p_110492_1_ + "]"));
}
if (p_110492_2_.isJsonObject()) {
final JsonObject var3 = JsonUtils.getElementAsJsonObject(p_110492_2_, "frames[" + p_110492_1_ + "]");
final int var4 = JsonUtils.getJsonObjectIntegerFieldValueOrDefault(var3, "time", -1);
if (var3.has("time")) {
Validate.inclusiveBetween(1L, 2147483647L, (long)var4, "Invalid frame time");
}
final int var5 = JsonUtils.getJsonObjectIntegerFieldValue(var3, "index");
Validate.inclusiveBetween(0L, 2147483647L, (long)var5, "Invalid frame index");
return new AnimationFrame(var5, var4);
}
return null;
}
public JsonElement serialize(final AnimationMetadataSection p_serialize_1_, final Type p_serialize_2_, final JsonSerializationContext p_serialize_3_) {
final JsonObject var4 = new JsonObject();
var4.addProperty("frametime", (Number)p_serialize_1_.getFrameTime());
if (p_serialize_1_.getFrameWidth() != -1) {
var4.addProperty("width", (Number)p_serialize_1_.getFrameWidth());
}
if (p_serialize_1_.getFrameHeight() != -1) {
var4.addProperty("height", (Number)p_serialize_1_.getFrameHeight());
}
if (p_serialize_1_.getFrameCount() > 0) {
final JsonArray var5 = new JsonArray();
for (int var6 = 0; var6 < p_serialize_1_.getFrameCount(); ++var6) {
if (p_serialize_1_.frameHasTime(var6)) {
final JsonObject var7 = new JsonObject();
var7.addProperty("index", (Number)p_serialize_1_.getFrameIndex(var6));
var7.addProperty("time", (Number)p_serialize_1_.getFrameTimeSingle(var6));
var5.add((JsonElement)var7);
}
else {
var5.add((JsonElement)new JsonPrimitive((Number)p_serialize_1_.getFrameIndex(var6)));
}
}
var4.add("frames", (JsonElement)var5);
}
return (JsonElement)var4;
}
public String getSectionName() {
return "animation";
}
public JsonElement serialize(final Object p_serialize_1_, final Type p_serialize_2_, final JsonSerializationContext p_serialize_3_) {
return this.serialize((AnimationMetadataSection)p_serialize_1_, p_serialize_2_, p_serialize_3_);
}
} |
import React, { FC, useState } from "react";
import "./ItemCard.css";
import Carousel from "react-bootstrap/Carousel";
export interface ItemCardProps {
productImages: string[];
batchNumber: string;
productName: string;
productQuantity: string;
productPrice: string;
}
const ItemCard: FC<ItemCardProps> = ({
productImages,
batchNumber,
productName,
productQuantity,
productPrice,
}) => {
const [index, setIndex] = useState(0);
const handleSelect = (selectedIndex) => {
setIndex(selectedIndex);
};
return (
<div className="item-card">
<div className="image">
<Carousel
activeIndex={index}
onSelect={handleSelect}
controls={false}
indicators={false}
>
{productImages.map((image, imageIndex) => (
<Carousel.Item key={imageIndex}>
<img
className="d-block w-100"
src={image}
alt={`Image ${imageIndex + 1}`}
/>
</Carousel.Item>
))}
</Carousel>
</div>
<div className="descrilition">
<li>Batch No: {batchNumber}</li>
<li>Product Name: {productName}</li>
<li>Quantity: {productQuantity}</li>
<li>Price: {productPrice}</li>
</div>
</div>
);
};
export default ItemCard; |
import { DatabaseService } from '@database/database.service'
import { GameBuilder } from '@packages/testing'
import { sql } from 'kysely'
import { container } from 'tsyringe'
import { InsertGamePriceRepository } from './insertGamePrice.repository'
describe('InsertGamePriceRepository', () => {
let repository: InsertGamePriceRepository
let db: DatabaseService
beforeEach(async () => {
db = container.resolve(DatabaseService)
repository = new InsertGamePriceRepository(db)
await db.connect()
})
afterEach(async () => {
await sql`DELETE FROM game`.execute(db.getClient())
await sql`DELETE FROM game_price`.execute(db.getClient())
await db.disconnect()
})
it('should insert a new game price', async () => {
const game = new GameBuilder().build()
await db.getClient().insertInto('game').values(game).execute()
const price = await repository.insert(game.id, {
steam_price: 120.5,
nuuvem_price: 110.99,
green_man_gaming_price: 115.10
})
expect(price.steam_price).toBe('120.50')
expect(price.nuuvem_price).toBe('110.99')
})
}) |
<?php
/**
* @file
* Placeholder module file.
*/
/**
* Implements hook_element_info_alter().
*/
function placeholder_element_info_alter(&$types) {
foreach (array_keys($types) as $type) {
switch ($type) {
case 'textfield':
case 'textarea':
case 'password':
$types[$type]['#process'][] = 'placeholder_process_placeholder';
break;
}
}
}
/**
* Element process callback. Adds support for the HTML5 placeholder attribute.
*
* @param array $element
* The render array element.
*
* @return
* The processed element.
*/
function placeholder_process_placeholder($element) {
if (isset($element['#placeholder']) || isset($element['#attributes']['placeholder'])) {
// Set the placeholder attribute, if we need to.
if (!isset($element['#attributes']['placeholder'])) {
$element['#attributes']['placeholder'] = $element['#placeholder'];
}
// Add the library, if it's available.
if (($library = libraries_detect('placeholder')) && !empty($library['installed'])) {
// Attach the library files.
$element['#attached']['libraries_load'][] = array('placeholder');
}
}
return $element;
}
/**
* Implements hook_libraries_info().
*/
function placeholder_libraries_info() {
$libraries = array();
$libraries['placeholder'] = array(
'title' => 'jQuery-Placeholder',
'vendor url' => 'https://github.com/mathiasbynens/jquery-placeholder',
'version' => '1.0',
'files' => array(
'js' => array(
'jquery.placeholder.js',
),
),
'integration files' => array(
'placeholder' => array(
'js' => array('placeholder.js' => array()),
),
),
'post-load integration files' => TRUE,
);
return $libraries;
} |
syntax = "proto3";
package user;
import "google/protobuf/timestamp.proto";
option go_package = "./pkg/pb/userauth";
service User {
rpc UserSignUp(UserSignUpRequest) returns (UserSignUpResponse) {};
rpc UserLogin(UserLoginRequest) returns (UserLoginResponse) {};
rpc UserEditDetails(UserEditDetailsRequest) returns (UserEditDetailsResponse) {};
rpc UserOtpGeneration(UserOtpRequest) returns (UserOtpRequestResponse){};
rpc UserOtpVerification(UserOtpVerificationRequest) returns (UserOtpVerificationResponse){};
rpc GetUsers(GetUsersRequest) returns (GetUsersResponse){};
rpc UpdateUserStatus(UpdateUserStatusRequest) returns (UpdateUserStatusResponse){};
rpc AddUserInterest(AddUserInterestRequest) returns (AddUserInterestResponse) {};
rpc EditUserInterest(EditUserInterestRequest) returns (EditUserInterestResponse) {};
rpc DeleteUserInterest(DeleteUserInterestRequest) returns (DeleteUserInterestResponse) {};
rpc GetUserInterests(GetUserInterestsRequest) returns (GetUserInterestsResponse) {}; // New RPC for interests
rpc AddUserPreference(AddUserPreferenceRequest) returns (AddUserPreferenceResponse) {}; // New RPC for preferences
rpc EditUserPreference(EditUserPreferenceRequest) returns (EditUserPreferenceResponse) {}; // New RPC for preferences
rpc DeleteUserPreference(DeleteUserPreferenceRequest) returns (DeleteUserPreferenceResponse) {}; // New RPC for preferences
rpc GetUserPreferences(GetUserPreferencesRequest) returns (GetUserPreferencesResponse) {}; // New RPC for preferences
rpc FollowUser(FollowUserRequest)returns(FollowUserResponce){};
rpc BlockUser(BlockUserRequest)returns(BlockUserResponce){};
rpc SendMessage(SendMessageRequest) returns (SendMessageResponce);
// New RPC method to read messages in a room
rpc ReadMessages(ReadMessagesRequest) returns (ReadMessagesResponse);
rpc GetConnections(GetConnectionsRequest) returns (GetConnectionsResponse) {};
rpc UpdateProfilePhoto (UpdateProfilePhotoRequest) returns (UpdateUserResponse);
rpc AddProfilePhoto(AddProfilePhotoRequest) returns (AddProfilePhotoResponse) {}
rpc DeleteProfilePhotoByID(DeleteProfilePhotoRequest) returns (DeleteProfilePhotoResponse) {}
}
message AddProfilePhotoRequest {
int64 userid = 1;
repeated bytes image_data = 2; // Image data in bytes
}
message AddProfilePhotoResponse {
int64 status = 1;
string image_url = 2; // URL of the uploaded photo
}
message DeleteProfilePhotoRequest {
int64 userid = 1;
string image_id = 2; // ID of the photo to be deleted
}
message DeleteProfilePhotoResponse {
int64 status = 1;
}
message UpdateProfilePhotoRequest {
int64 userid = 1;
repeated bytes image_data = 2; // List of image data in bytes
}
message UpdateUserResponse {
int64 status=1;
int64 userid = 2;
repeated string image_url = 3;
}
message GetConnectionsResponse {
int64 status = 1;
repeated UserDetails UserDetails = 2;
}
message GetConnectionsRequest {
uint64 user_id = 1;
}
message ReadMessagesResponse {
repeated Message messages = 1;
}
message ReadMessagesRequest {
uint32 senter_id = 1;
uint32 receiver_id =2;
}
message SendMessageRequest {
uint32 senter_id = 1;
uint32 receiver_id = 2;
string content = 3;
repeated Media media = 4;
}
message Message {
uint32 message_id = 1;
uint32 receiver_id_id = 2;
uint32 sender_id = 3;
string content = 4;
google.protobuf.Timestamp timestamp = 5;
repeated Media media = 6; // Added media field
}
// New message for receiving a message in a room
message SendMessageResponce {
uint32 message_id = 1;
uint32 senter_id = 2;
uint32 receiver_id = 3;
string content = 4;
google.protobuf.Timestamp timestamp = 5;
repeated Media media = 6; // Added media field
}
message Media {
string filename = 2;
// Add other fields as needed, such as media type, size, etc.
}
message BlockUserRequest{
int64 userid=1;
int64 senderid=2;
}
message BlockUserResponce{
int64 status=1;
}
message FollowUserRequest{
int64 userid=1;
int64 senderid=2;
}
message FollowUserResponce{
int64 status=1;
}
message UpdateUserStatusRequest{
int64 userid=1;
}
message UpdateUserStatusResponse{
int64 status=1;
}
message GetUsersRequest {
// You can leave this message empty
}
message Users {
uint32 id = 1;
string firstname = 2;
string lastname = 3;
string email = 4;
string password = 5;
string phone = 6;
bool blocked = 7;
string username = 8;
int32 gender_id = 9;
int32 age = 10;
}
message GetUsersResponse {
int64 status=1;
repeated Users users = 2;
}
message UserOtpRequest{
string email=1;
}
message UserOtpRequestResponse{
int64 status=1;
string email=2;
int64 otp=3;
}
message UserOtpVerificationRequest{
string email=1;
int64 otp=2;
}
message UserOtpVerificationResponse{
int64 status=1;
UserDetails userDetails=2;
}
message UserSignUpRequest {
string firstname = 1;
string lastname = 2;
string username = 3;
string email = 4;
string password = 5;
string phone = 6;
int32 genderid = 7;
int32 age = 8;
}
message UserEditDetailsRequest {
string firstname = 1;
string lastname = 2;
string username = 3;
string email = 4;
string password = 5;
string phone = 6;
int32 genderid = 7;
int32 age = 8;
}
message UserEditDetailsResponse {
int64 status=1;
UserDetails userDetails=2;
}
message UserDetails {
uint64 id=1;
string firstname=2;
string lastname=3;
string email=4;
string phone=5;
}
message UserSignUpResponse {
int64 status=1;
UserDetails userDetails=2;
string AccessToken=3;
string RefreshToken =4;
}
message UserLoginRequest{
string email=1;
string password=2;
}
message UserLoginResponse{
int64 status=1;
UserDetails userDetails=2;
string AccessToken=3;
string RefreshToken =4;
}
message AddUserInterestRequest {
uint64 user_id = 1;
uint64 interest_id= 2;
}
message AddUserInterestResponse {
int64 status = 1;
}
message EditUserInterestRequest {
uint64 user_id = 1;
uint64 interest_id = 2;
string new_interest_name = 3;
}
message EditUserInterestResponse {
int64 status = 1;
}
message DeleteUserInterestRequest {
uint64 user_id = 1;
uint64 interest_id = 2;
}
message DeleteUserInterestResponse {
int64 status = 1;
}
// New messages for managing user preferences
message AddUserPreferenceRequest {
uint64 user_id = 1;
uint64 preference_id = 2;
}
message AddUserPreferenceResponse {
int64 status = 1;
}
message EditUserPreferenceRequest {
uint64 user_id = 1;
uint64 preference_id = 2;
string new_preference_name = 3;
}
message EditUserPreferenceResponse {
int64 status = 1;
}
message DeleteUserPreferenceRequest {
uint64 user_id = 1;
uint64 preference_id = 2;
}
message DeleteUserPreferenceResponse {
int64 status = 1;
}
message GetUserInterestsRequest {
uint64 user_id = 1;
}
message GetUserInterestsResponse {
int64 status = 1;
repeated string interests = 2;
}
message GetUserPreferencesRequest {
uint64 user_id = 1;
}
message GetUserPreferencesResponse {
int64 status = 1;
repeated string preferences = 2;
} |
<script setup lang="ts">
import { RouterView, useRouter } from 'vue-router'
import TheHeader from './components/inc/TheHeader.vue';
import TheFooter from './components/inc/TheFooter.vue';
import { computed, onMounted, provide, ref } from 'vue';
import type { IUser } from './lib/interface';
import useUser from './lib/hook/useUser';
import useAuthen from './lib/hook/useAuthen';
const router = useRouter()
const isFindCars = computed(() => router.currentRoute.value.name === 'FindCars')
const user = ref<IUser>()
const isAuthen = ref(false)
const updateUser = (value?:IUser)=>{
user.value = value
}
const updateAuthen = (value:boolean)=>{
isAuthen.value = value
}
provide('user', {
user,updateUser,isAuthen,updateAuthen
})
onMounted(()=>{updateUser(useUser()),updateAuthen(useAuthen())})
</script>
<template>
<TheHeader/>
<main>
<RouterView :key="$route.fullPath"/>
</main>
<TheFooter v-if="!isFindCars"/>
</template> |
package com.rc.springsecurity.security;
import com.rc.springsecurity.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${spring.h2.console.path}")
private String h2ConsolePath;
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Autowired
private JwtTokenFilter jwtTokenFilter;
@Autowired
private AuthEntryPoint unauthorizedHandler;
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/test/**").permitAll()
.antMatchers(h2ConsolePath + "/**").permitAll()
.anyRequest().authenticated();
// fix H2 database console: Refused to display ' in a frame because it set 'X-Frame-Options' to 'deny'
http.headers().frameOptions().sameOrigin();
http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
} |
/**
* @ngdoc service
* @name gcms.components.data.service:business.profile
*
* @description
* Represents an business profile data service.
*
*```js
* function myCtrl($scope, ValidatedProfile){
* $scope.identityRequests = [];
* ValidatedProfile.query().$promise.then(function(result){
* $scope.ValidatedProfile = result;
* });
* }
*```
*/
(function() {
'use strict';
angular
.module('gcms.components.data')
.factory('ValidatedProfile', ValidatedProfile);
ValidatedProfile.$inject = ['$resource','localeMapper', 'ENVIRONMENT'];
/**
* @ngdoc method
* @name business.profile
* @methodOf gcms.components.data.service:business.profile
* @description Constructor for the business profile data service
* @param {object} $resource A factory which creates a resource object
that lets you interact with RESTful server-side data sources
* @param {object} ENVIRONMENT The configuration object which supplies a
consistent service uri to use across the application
* @returns {object} The business profile data service
*/
function ValidatedProfile($resource,localeMapper, ENVIRONMENT) {
return $resource(
ENVIRONMENT.SERVICE_URI + ':locale/identityProfiles/:id/:regionId' + ENVIRONMENT.SERVICE_EXT,
{
id: '@id',
regionId: '@regionId',
locale: function(){ return localeMapper.getCurrentISOCode();}
},
{
get: { method:'GET', isArray:true },
query: { method:'GET',isArray:true }
}
);
}
})(); |
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kim.impl.identity.affiliation
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
import org.kuali.rice.kim.api.identity.affiliation.EntityAffiliationType
import org.kuali.rice.kim.framework.identity.affiliation.EntityAffiliationTypeEbo
import org.kuali.rice.krad.bo.PersistableBusinessObjectBase
@Entity
@Table(name="KRIM_AFLTN_TYP_T")
public class EntityAffiliationTypeBo extends PersistableBusinessObjectBase implements EntityAffiliationTypeEbo {
@Id
@Column(name="EMP_TYP_CD")
String code;
@Column(name="NM")
String name;
@org.hibernate.annotations.Type(type="yes_no")
@Column(name="ACTV_IND")
boolean active;
@Column(name="DISPLAY_SORT_CD")
String sortCode;
@org.hibernate.annotations.Type(type="yes_no")
@Column(name="EMP_AFLTN_TYP_IND")
boolean employmentAffiliationType;
/**
* Converts a mutable EntityAffiliationTypeBo to an immutable EntityAffiliationType representation.
* @param bo
* @return an immutable EntityAffiliationType
*/
static EntityAffiliationType to(EntityAffiliationTypeBo bo) {
if (bo == null) { return null }
return EntityAffiliationType.Builder.create(bo).build()
}
/**
* Creates a EntityAffiliationType business object from an immutable representation of a EntityAffiliationType.
* @param an immutable EntityAffiliationType
* @return a EntityAffiliationTypeBo
*/
static EntityAffiliationTypeBo from(EntityAffiliationType immutable) {
if (immutable == null) {return null}
EntityAffiliationTypeBo bo = new EntityAffiliationTypeBo()
bo.code = immutable.code
bo.name = immutable.name
bo.sortCode = immutable.sortCode
bo.employmentAffiliationType = immutable.employmentAffiliationType
bo.active = immutable.active
bo.versionNumber = immutable.versionNumber
bo.objectId = immutable.objectId
return bo;
}
} |
import React, { memo, useState, useEffect } from 'react';
import { Box, Container, Grid, Typography } from '@mui/material';
import { useFormik } from 'formik';
import { useTranslation } from 'react-i18next';
import { useNavigate, useParams } from 'react-router-dom';
import Input from '../../components/UIComponents/Input/Input';
import { Button } from '../../components/UIComponents/Button/Button.component';
import ToastMessage from '../../components/UIComponents/ToastMessage/ToastMessage.component';
import ProductManagementModel from '../../models/ProductManagementModel';
import { AddProductValidationSchema } from './validation';
import Select from '../../components/UIComponents/Select/SingleSelect';
import './AddProduct.scss';
import { HorizontalBarVersionState, useShowConfirmationDialogBoxStore, useStore } from '../../store';
import { useAddProductManagement, useGetProductColors, useGetProductTypes, useGetProductData, useEditProductManagement } from './queries';
import { LoadingIcon } from '../../assets/icons';
import { isCurrentAppCountryUSA, getProductIcon } from '../../utils/helperFunctions';
interface IFormStatus {
message: string
type: string
}
export interface AddProductProps {
version: string
}
const initialValues = new ProductManagementModel();
const AddProduct: React.FC<AddProductProps> = memo(() => {
const { t } = useTranslation();
const navigate = useNavigate();
const { productId }: any = useParams();
const { data: productTypesList, isLoading: isLoadingTypes, } = useGetProductTypes('us');
const { data: productColorsList, isLoading: isLoadingColors } = useGetProductColors('us');
const showDialogBox = useShowConfirmationDialogBoxStore((state) => state.showDialogBox);
const isFormValidated = useShowConfirmationDialogBoxStore((state) => state.setFormFieldValue);
const [productGroupCd, setProductGroupCd] = useState("");
const productStatusList = [
{ label: 'Enabled', value: 'Y', },
{ label: 'Disabled', value: 'N' },
];
const [formStatus, setFormStatus] = useState<IFormStatus>({
message: '',
type: '',
});
const setVersion = useStore((state: HorizontalBarVersionState) => state.setVersion);
setVersion("Breadcrumbs-Single");
// Add section starts
const onSuccessAddProduct = () => {
isFormValidated(false);
formik.resetForm({ values: formik.values });
setFormStatus({ message: t("formStatusProps.success.message"), type: 'Success' });
};
const onErrorAddProduct = (err: any) => {
const { data } = err.response;
setFormStatus({ message: data?.error?.details[0] || t("formStatusProps.error.message"), type: 'Error' });
};
const { mutate: addNewProduct, isSuccess: isSuccessAddProduct, isError: isErrorAddProduct, isLoading: isLoadingAddProduct } = useAddProductManagement(onSuccessAddProduct, onErrorAddProduct);
const createProductData = (form: ProductManagementModel) => {
try {
addNewProduct(form);
} catch {
setFormStatus({ message: t("formStatusProps.error.message"), type: 'Error' });
}
};
// Add section ends
// Edit section starts
const [isEditMode, setEditMode] = useState(false);
const populateDataInAllFields = (responseData: any) => {
formik.resetForm({
values: { ...responseData }
});
};
const onGetProductSuccess = (response: any) => {
try {
if (response?.data) {
const finalData = {
countryCode: 'us',
productName: response.data.productNm,
productType: {
value: response.data.productGroup.productGroupCd,
label: response.data.productGroup.productGroupNm
},
productColor: {
value: response.data.productIcon.productIconCd,
label: response.data.productIcon.productIconNm,
icon: getProductIcon(response.data.productIcon.productIconNm)
},
productStatus: productStatusList.filter((pObj) => pObj.value === response.data.activeInactiveInd)[0],
productPricing: response.data.manualPricing || 0
};
populateDataInAllFields(finalData);
setProductGroupCd(response.data.productCd);
setEditMode(true);
}
} catch {
setFormStatus({ message: t("formStatusProps.error.message"), type: 'Error' });
}
};
const onGetProductError = (err: any) => {
try {
const { data } = err.response;
setFormStatus({ message: data?.error?.message || t("formStatusProps.error.message"), type: 'Error' });
formik.setSubmitting(false);
} catch (error: any) {
setFormStatus({ message: error?.message || t("formStatusProps.error.message"), type: 'Error' });
}
};
useGetProductData(productId, onGetProductSuccess, onGetProductError);
const onEditProductSuccess = () => {
isFormValidated(false);
setFormStatus({ message: t("formStatusProps.updated.message"), type: 'Success' });
formik.resetForm({ values: formik.values });
};
const onEditProductError = (err: any) => {
try {
const { data } = err.response;
setFormStatus({ message: data?.error?.message || t("formStatusProps.error.message"), type: 'Error' });
formik.setSubmitting(false);
} catch (error: any) {
setFormStatus({ message: error?.message || t("formStatusProps.error.message"), type: 'Error' });
}
};
const { mutate: editProduct, isSuccess: isSuccessEditProduct, isError: isErrorEditProduct, isLoading: isLoadingEditProduct } = useEditProductManagement(
productId,
productGroupCd,
onEditProductSuccess,
onEditProductError
);
const updateProductData = (form: ProductManagementModel) => {
try {
editProduct(form);
} catch {
setFormStatus({ message: t("formStatusProps.error.message"), type: 'Error' });
}
};
// Edit section ends
const formik = useFormik({
initialValues,
validationSchema: AddProductValidationSchema,
onSubmit: (values) => {
if (isEditMode) {
updateProductData(values);
} else {
createProductData(values);
}
},
enableReinitialize: true,
});
useEffect(() => {
if (!formik.isValid || formik.dirty) {
isFormValidated(true);
} else {
isFormValidated(false);
}
}, [formik.isValid, formik.dirty]);
const onClickCancel = () => {
if (!formik.isValid || formik.dirty) {
showDialogBox(true);
} else {
navigate('/productManagement');
}
};
const disableButton = () => {
if (formik.dirty) {
return !formik.isValid || formik.isSubmitting;
} else {
return true;
}
};
return (
<Box display="flex" className="global_main_wrapper">
<Grid item md={7} xs={7}>
<Container maxWidth="lg" className="page-container">
<form onSubmit={formik.handleSubmit} id="form">
<Typography color="var(--Darkgray)" variant="h3" gutterBottom className="fw-bold" mb={1} pt={3}>
{t("productManagement.form.title")} *
</Typography>
<Grid container mt={1}>
<Grid item xs={12} md={12} pr={2.5} pb={2.5}>
<Grid item xs={12} md={6}>
<Input
id='productName'
label={t("productManagement.form.productName")}
type='text'
helperText={(formik.touched.productName && formik.errors.productName) ? formik.errors.productName : undefined}
error={(formik.touched.productName && formik.errors.productName) ? true : false}
description=''
placeholder='Enter Product Name'
{...formik.getFieldProps('productName')}
required
/>
</Grid>
</Grid>
<Grid item xs={12} md={12} pr={2.5} pb={2.5}>
<Grid item xs={12} md={6}>
<Select
id='productType'
name='productType'
label={t("productManagement.form.productType")}
placeholder='Choose'
value={formik.values.productType}
items={productTypesList}
helperText={(formik.touched.productType && formik.errors.productType) ? formik.errors.productType.value : undefined}
error={(formik.touched.productType && formik.errors.productType) ? true : false}
onChange={formik.setFieldValue}
onBlur={() => { formik.setFieldTouched("productType"); formik.validateField("productType"); }}
required
isLoading={isLoadingTypes}
noOptionsMessage={() => "No data Found"}
/>
</Grid>
</Grid>
<Grid item xs={12} md={12} pr={2.5} pb={2.5}>
<Grid item xs={12} md={6}>
<Select
id='productColor'
dropdownType='productcolor'
name='productColor'
label={t("productManagement.form.productColor")}
placeholder='Choose'
value={formik.values.productColor}
items={productColorsList}
helperText={(formik.touched.productColor && formik.errors.productColor) ? formik.errors.productColor.value : undefined}
error={(formik.touched.productColor && formik.errors.productColor) ? true : false}
onChange={formik.setFieldValue}
onBlur={() => { formik.setFieldTouched("productColor"); formik.validateField("productColor"); }}
required
isLoading={isLoadingColors}
noOptionsMessage={() => "No data Found"}
/>
</Grid>
</Grid>
<Grid item xs={12} md={12} pr={2.5} pb={2.5}>
<Grid item xs={12} md={6}>
<Select
id='productStatus'
name='productStatus'
label={t("productManagement.form.productStatus")}
placeholder='Choose'
value={formik.values.productStatus}
items={productStatusList}
helperText={(formik.touched.productStatus && formik.errors.productStatus) ? formik.errors.productStatus.value : undefined}
error={(formik.touched.productStatus && formik.errors.productStatus) ? true : false}
onChange={formik.setFieldValue}
onBlur={() => { formik.setFieldTouched("productStatus"); formik.validateField("productStatus"); }}
required
/>
</Grid>
</Grid>
<Grid item xs={12} md={12} pr={2.5} pb={2.5}>
<Grid item xs={12} md={6}>
<Input
id='productPricing'
label={t("productManagement.form.productPricing")}
type='text'
helperText={(formik.touched.productPricing && formik.errors.productPricing) ? formik.errors.productPricing : undefined}
error={(formik.touched.productPricing && formik.errors.productPricing) ? true : false}
description=''
disabled={isCurrentAppCountryUSA()}
{...formik.getFieldProps('productPricing')}
/>
</Grid>
</Grid>
<Grid item xs={12} md={12} pr={2.5} mt={4} mb={4}>
<Grid item xs={12} md={6}>
<Box className="form-action-section">
<Button
id="cancelBtn"
types="cancel"
aria-label={t("buttons.cancel")}
className="mr-4"
onClick={onClickCancel}
data-test="cancel"
>
{t("buttons.cancel")}
</Button>
<Button
id="saveBtn"
type="submit"
types="save"
aria-label={t("buttons.save")}
className="ml-4"
data-test="save"
disabled={disableButton()}
>
{t("buttons.save")} {(isLoadingAddProduct || isLoadingEditProduct) && <LoadingIcon data-testid="loading-spinner" className='loading_save_icon' />}
</Button>
</Box>
<ToastMessage
isOpen={
isErrorAddProduct || isSuccessAddProduct ||
isErrorEditProduct || isSuccessEditProduct
}
messageType={formStatus.type}
onClose={() => { return ''; }}
message={formStatus.message} />
</Grid>
</Grid>
</Grid>
</form>
</Container>
</Grid>
</Box>
);
});
export default AddProduct; |
// SPDX-License-Identifier:UNLICENSED
pragma solidity ^0.8.7;
contract ex_enum{
enum steps {command, sending, delivered}
struct product {
uint _SKU;
ex_enum.steps _step;
}
mapping(address => product) CommandStatus;
function command(address client, uint SKU) public{
product memory p = product(SKU, steps.command); // **
CommandStatus[client] = p;
}
function sending(address client) public{
CommandStatus[client]._step = steps.sending;
}
function received(address client) public{
CommandStatus[client]._step = steps.delivered;
}
function getSKU(address client) public view returns(uint){
return CommandStatus[client]._SKU;
}
function getStep(address client) public view returns(steps){
return CommandStatus[client]._step;
}
} |
import { useState } from "react";
import Button from "@material-ui/core/Button";
import FormControl from "@material-ui/core/FormControl";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Paper from "@material-ui/core/Paper";
import Radio from "@material-ui/core/Radio";
import RadioGroup from "@material-ui/core/RadioGroup";
import styled from "styled-components";
import TextField from "@material-ui/core/TextField";
import Typography from "@material-ui/core/Typography";
//advance todo
import Box from "@mui/material/Box";
import Tab from "@mui/material/Tab";
import TabContext from "@mui/lab/TabContext";
import TabList from "@mui/lab/TabList";
import TabPanel from "@mui/lab/TabPanel";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import { useStyles } from "../hooks";
import axios from "../api";
import { useScoreCard } from "../hooks/useScoreCard";
const Wrapper = styled.section`
display: flex;
flex-direction: column;
`;
const Row = styled.div`
display: flex;
align-items: center;
justify-content: center;
width: 100%;
padding: 1em;
`;
const StyledFormControl = styled(FormControl)`
min-width: 120px;
`;
const ContentPaper = styled(Paper)`
height: 300px;
padding: 2em;
overflow: auto;
`;
const Body = () => {
const classes = useStyles();
const {
messages,
addCardMessage,
addRegularMessage,
addErrorMessage,
changeView,
} = useScoreCard();
const [name, setName] = useState("");
const [subject, setSubject] = useState("");
const [score, setScore] = useState(0);
const [info, setInfo] = useState([]);
const [queryType, setQueryType] = useState("name");
const [queryString, setQueryString] = useState("");
const [value, setValue] = useState("add");
const handleChange = (func) => (event) => {
//console.log(event.target.value);
func(event.target.value);
};
const handleAdd = async () => {
const {
data: { message, card },
} = await axios.post("/card", {
name,
subject,
score,
});
if (!card) addErrorMessage(message);
else addCardMessage(message);
getInfo("name", name);
};
const handleQuery = async () => {
const {
data: { messages, message },
} = await axios.get("/cards", {
params: {
type: queryType,
queryString,
},
});
if (!messages) addErrorMessage(message);
else addRegularMessage("query", ...messages);
getInfo(queryType, queryString);
};
const getInfo = async (filter, content) => {
const {
data: { tmpInfo },
} = await axios.get("/cards/info", {
params: { filter, content },
});
setInfo(tmpInfo);
};
const advTable = () => {
if (info.length === 0) return;
else {
return (
<TableContainer component={Paper}>
<Table sx={{ width: "100%" }} aria-label="info table">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell align="right">Subject</TableCell>
<TableCell align="right">Score</TableCell>
</TableRow>
</TableHead>
<TableBody>
{info.map((dt, index) => (
<TableRow
key={index}
sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
>
<TableCell component="th" scope="row">
{dt.name}
</TableCell>
<TableCell align="right">{dt.subject}</TableCell>
<TableCell align="right">{dt.score}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
}
};
return (
<Wrapper>
<Box sx={{ width: "100%" }}>
<TabContext value={value}>
<Box sx={{ borderBottom: 1, borderColor: "divider" }}>
<TabList aria-label="tab API">
<Tab
label="ADD"
value="add"
onClick={() => {
setValue("add");
changeView("ADD");
setInfo([]);
}}
></Tab>
<Tab
label="QUERY"
value="query"
onClick={() => {
setValue("query");
changeView("QUERY");
setInfo([]);
}}
></Tab>
</TabList>
</Box>
<TabPanel value="add">
<Row>
{/* Could use a form & a library for handling form data here such as Formik, but I don't really see the point... */}
<TextField
className={classes.input}
placeholder="Name"
value={name}
onChange={handleChange(setName)}
/>
<TextField
className={classes.input}
placeholder="Subject"
style={{ width: 240 }}
value={subject}
onChange={handleChange(setSubject)}
/>
<TextField
className={classes.input}
placeholder="Score"
value={score}
onChange={handleChange(setScore)}
type="number"
/>
<Button
className={classes.button}
variant="contained"
color="primary"
disabled={!name || !subject}
onClick={handleAdd}
>
Add
</Button>
</Row>
</TabPanel>
<TabPanel value="query">
<Row>
<StyledFormControl>
<FormControl component="fieldset">
<RadioGroup
row
value={queryType}
onChange={handleChange(setQueryType)}
>
<FormControlLabel
value="name"
control={<Radio color="primary" />}
label="Name"
/>
<FormControlLabel
value="subject"
control={<Radio color="primary" />}
label="Subject"
/>
</RadioGroup>
</FormControl>
</StyledFormControl>
<TextField
placeholder="Query string..."
value={queryString}
onChange={handleChange(setQueryString)}
style={{ flex: 1 }}
/>
<Button
className={classes.button}
variant="contained"
color="primary"
disabled={!queryString}
onClick={handleQuery}
>
Query
</Button>
</Row>
</TabPanel>
</TabContext>
</Box>
<ContentPaper variant="outlined">
{advTable()}
{messages.map((m, i) => (
<Typography variant="body2" key={m + i} style={{ color: m.color }}>
{m.message}
</Typography>
))}
</ContentPaper>
</Wrapper>
);
};
export default Body; |
* Install - McStas and the (optional) Webserver *
* --------------------------------------------- *
* Debian 7.1 iso 64bit (DL+install) *
* use ifconfig to find ip address *
System Setup
------------
1) Check out the McCode SVN repos:
mkdir <whatever_build_dir_structure_you_want>
cd <whatever_build_dir_structure_you_want>
svn co https://svn.mccode.org/svn/McCode/trunk
2) Build all dependencies in this list:
sudo apt-get (build-dep) install cmake
texlive-* (all except the langs and docs, you just need lang-danish)
latex2html
latexmk
gcc
flex
bison
libc6-dev
xbase-clients
build-essential
emacs
subversion
nginx-full
python-dev
libopenmpi-dev (if you need MPI. (Yes, you need it.))
python-pip (the python package manager)
and:
sudo pip install python-django==1.7
*** I am here on my vm ***
3) Enable non-free repos:
sudo apt-add-repository 'deb http://ftp.debian.org/debian/ wheezy main contrib non-free'
cd /etc/apt/sources.list.d
sudo wget http://packages.mccode.org/debian/mccode.list
change your shell to bash:
dpkg-reconfigure dash (and tell it 'No')
now look at all the goodies you have directed your machine to find:
sudo apt-get update ; apt-get upgrade
4) In the trunk dir there are a bunch of scripts which build .debs or .rpms for your particular
OS. Run the correct one.
cd /trunk/dist
dpkg -i <whichever_you_wish_to_install> (I would just install them all)
If this fails for some reason run:
sudo apt-get -f install
The -f flag tells the unmet dependencies to be forced to install. Then run:
dpkg -i <whichever_you_wish_to_install>
again. This should install McStas, you can install McXtrace in exactly the same way using the correct
build_... script.
Setting up Django Webserver
---------------------------
5) Create the server dir and copy the server files into it, you are playing in the root dir now so you have to
sudo everything or run as root, change the permissions at the end if you don't like running round your
system as su:
sudo mkdir /srv/mcstas-django
sudo cp -rp /root/trunk/tools/Python/www/www-django/mcwww/ /srv/mcstas-django
6) Move to your shiny new working directory (the one you just made). Run:
sudo bin/get-dependencies.sh
7) Make a <Group_Dir> in sim/ and populate sim/<Group_Dir> with at least one instr -
sudo cp /usr/local/lib/mcstas-2.0/examples/<choose_one_or_more>.instr sim/<Group_Dir>
sidenote_1: You will need to login to <IP ADDRESS>:<PORT>/admin (after creating your users) and put users
in groups so they can run simulations. Groups correspond to <Group_Dir> names.
sidenote_2: Ensure your keyboard is set to a locale that the python scripts are happy with:
export LC_ALL="en_US.UTF-8"
8) ### THERE SHOULD BE FLAGS FOR THE VARIOUS MODES OF INSTALLATION ###
REMEMBER THE NEW LDAP PASSWORD, IT IS REQUESTED AGAIN!
Run:
./bin/init-db.sh
set up the LDAP authentication DB, the sqlite simulation DBs, and, the file uploading DB (upon completion).
you will be prompted for some information to set up the LDAP DB, this is important to keep hold of.
9) Follow the prompts, you should set up a superuser to start with, step (10)a) shows how to create new users:
Username (leave blank to use 'root'):
E-mail address:
Password:
Password (again):
Superuser created successfully.
10) Run the following commands (put the runworker in the background with '&' or open a new terminal):
a) ./manage.py createuser <USERNAME> <PASSWORD>
c) sudo ./manage.py runworker &
d) sudo ./manage.py runserver <IP ADDRESS>:<PORT> (80 is a good listening port)
sidenote_3: When you have compiled the instruments (step (10)b) ) you should copy the .html files into the <GROUP>
folder. This keeps everything tidy, although the server will find them in any of the referenced subfolders
from where you run step (10)c & d).
Adding a Simulation to the DB
-----------------------------
- If you wisdh to create a new group of simulations follow step (7) and then (10)b). Remember to put your
user in groups that you wish them to be able to select simulations from.
- Otherwise put your .instr file(s) in an existing group and perform step (10)b).
- Upon reopening the configuration page the new simulations should be available to the users in the correct
groups. |
import {createContext, useContext, useReducer, useEffect} from 'react';
import AppReducer from "./AppReducer"
const initialState = {
transactions: []
}
export const Context = createContext();
export const useGlobalState = () => {
const context= useContext(Context)
return context
}
export const GlobalProvider = ({children}) => {
const [state, dispatch] = useReducer(AppReducer, initialState,
() => {
const localData = localStorage.getItem('transactions')
return localData ? JSON.parse(localData) : initialState
}
);
useEffect(() => {
localStorage.setItem('transactions', JSON.stringify(state))
}, [state])
const addTransaction = (transaction) =>
dispatch({
type: 'ADD_TRANSACTION',
payload: transaction
});
const deleteTransaction = (id) =>
dispatch({
type: 'DELETE_TRANSACTION',
payload: id
})
return (
<Context.Provider
value={{
transactions: state.transactions,
addTransaction,
deleteTransaction
}}>
{children}
</Context.Provider>
)
} |
Snort++ differs from Snort in the following ways:
* command line and conf file syntax made more uniform
* removed unused and deprecated features
* remove as many barriers to successful run as possible
(e.g.: no upper bounds on memcaps)
* assume the simplest mode of operation
(e.g.: never assume input from or output to some hardcoded filename)
* all Snort config options are grouped into Snort++ modules
=== Build Options
* configure --with-lib{pcap,pcre}-* -> --with-{pcap,pcre}-*
* control socket, cs_dir, and users were deleted
* POLICY_BY_ID_ONLY code was deleted
* hardened --enable-inline-init-failopen / INLINE_FAILOPEN
=== Command Line
* --pause loads config and waits for resume before processing packets
* --require-rule-sid is hardened
* --shell enables interactive Lua shell
* -T is assumed if no input given
* added --help-config prefix to dump all matching settings
* added --script-path
* added -K text; -K text/pcap is old dump/log mode
* added -z <#> and --max-packet-threads <#>
* delete --enable-mpls-multicast, --enable-mpls-overlapping-ip,
--max-mpls-labelchain-len, --mpls-payload-type
* deleted --pid-path and --no-interface-pidfile
* deleting command line options which will be available with --lua or some such including:
-I, -h, -F, -p, --disable-inline-init-failopen
* hardened -n < 0
* removed --search-method
* replaced "unknown args are bpf" with --bpf
* replaced --dynamic-*-lib[-dir] with --plugin-path (with : separators)
* removed -b, -N, -Z and, --perfmon-file options
=== Conf File
* Snort++ has a default unicode.map
* Snort++ will not enforce an upper bound on memcaps and the like within 64 bits
* Snort++ will supply a default *_global config if not specified
(Snort would fatal; e.g. http_inspect_server w/o http_inspect_global)
* address list syntax changes: [[ and ]] must be [ [ and ] ] to avoid Lua string
parsing errors (unless in quoted string)
* because the Lua conf is live code, we lose file:line locations in app error messages
(syntax errors from Lua have file:line)
* changed search-method names for consistency
* delete config include_vlan_in_alerts (not used in code)
* delete config so_rule_memcap (not used in code)
* deleted --disable-attribute-table-reload-thread
* deleted config decode_*_{alerts,drops} (use rules only)
* deleted config dump-dynamic-rules-path
* deleted config ipv6_frag (not actually used)
* deleted config threshold and ips rule threshold (-> event_filter)
* eliminated ac-split; must use ac-full-q split-any-any
* frag3 -> defrag, arpspoof -> arp_spoof, sfportscan -> port_scan,
perfmonitor -> perf_monitor, bo -> back_orifice
* limits like "1234K" are now "limit = 1234, units = 'K'"
* lua field names are (lower) case sensitive; snort.conf largely wasn't
* module filenames are not configurable: always <log-dir>/<module-name><suffix>
(suffix is determined by module)
* no positional parameters; all name = value
* perf_monitor configuration was simplified
* portscan.detect_ack_scans deleted (exact same as include_midstream)
* removed various run modes - now just one
* frag3 default policy is Linux not bsd
* lowmem* search methods are now in snort_examples
* deleted unused http_inspect stateful mode
* deleted stateless inspection from ftp and telnet
* deleted http and ftp alert options (now strictly rule based)
* preprocessor disabled settings deleted since no longer relevant
* sessions are always created; snort config stateful checks eliminated
* stream5_tcp: prune_log_max deleted; to be replaced with histogram
* stream5_tcp: max_active_responses, min_response_seconds moved to
active.max_responses, min_interval
=== Rules
* all rules must have a sid
* deleted activate / dynamic rules
* deleted metadata engine shared
* deleted metadata: rule-flushing (with PDU flushing rule flushing can cause
missed attacks, the opposite of its intent)
* deleted unused rule_state.action
* fastpattern_offset, fast_pattern_length
* no ; separated content suboptions
* offset, depth, distance, and within must use a space separator not colon
(e.g. offset:5; becomes offset 5;)
* rule option sequence: <stub> soid <hidden>
* sid == 0 not allowed
* soid is now a non-metadata option
* content suboptions http_* are now full options and should be place before content
* the following pcre options have been deleted: use sticky buffers instead
B, U, P, H, M, C, I, D, K, S, Y
* deleted uricontent ips rule option.
uricontent:"foo" --> http_uri; content:"foo"
* deleted urilen raw and norm; must use http_raw_uri and http_uri instead
* deleted unused http_encode option
* urilen replaced with generic bufferlen which applies to current sticky
buffer
* added optional selector to http_header, e.g. http_header:User-Agent;
* multiline rules w/o \n
* #begin ... #end comments
=== Output
* alert_fast includes packet data by default
* all text mode outputs default to stdout
* changed default logging mode to -K none
* deleted layer2resets and flexresp2_*
* deleted log_ascii
* general output guideline: don't print zero counts
* Snort++ queues decoder and inspector events to the main event queue before ips policy
is selected; since some events may not be enabled, the queue needs to be sized larger
than with Snort which used an intermediate queue for decoder events.
* deleted the intermediate http and ftp_telnet event queues
* alert_unified2 and log_unified2 have been deleted
=== HTTP Profiles
This section describes the changes to the Http Inspect config option "profile".
Snort 2.X allows users to select pre-defined HTTP server profiles using the
config option "profile". The user can choose one of five predefined profiles.
When defined, this option will set defaults for other config options within
Http Inspect.
With Snort++, the user has the flexibility of defining and fine tuning custom
profiles along with the five predefined profiles.
Snort 2.X conf
preprocessor http_inspect_server: server default \
profile apache ports { 80 3128 } max_headers 200
Snort 3.0 conf
http_inspect = { profile = http_profile_apache }
http_inspect.profile.max_headers = 200
binder =
{
{
when = { proto = 'tcp', ports = '80 3128', },
use = { type = 'http_inspect' },
},
}
NOTE: The "profile" option now that points to a table "http_profile_apache"
which is defined in "snort_defaults.lua" (as follows).
http_profile_apache =
{
profile_type = 'apache',
server_flow_depth = 300,
client_flow_depth = 300,
post_depth = -1,
chunk_length = 500000,
ascii = true,
multi_slash = true,
directory = true,
webroot = true,
utf_8 = true,
apache_whitespace = true,
non_strict = true,
normalize_utf = true,
normalize_javascript = false,
max_header_length = 0,
max_headers = 0,
max_spaces = 200,
max_javascript_whitespaces = 200,
whitespace_chars ='0x9 0xb 0xc 0xd'
}
NOTE: The config option "max_headers" is set to 0 in the profile, but
overwritten by "http_inspect.profile.max_headers = 200".
Conversion
Snort2lua can convert the existing snort.conf with the "profile" option to
Snort3.0 compatible "profile". Please refer to the Snort2Lua post for more
details.
Examples
"profile all" ==> "profile = http_profile_default"
"profile apache" ==> "profile = http_profile_apache"
"profile iis" ==> "profile = http_profile_iis"
"profile iis_40" ==> "profile = http_profile_iis_40"
"profile iis_50" ==> "profile = http_profile_iis_50"
Defining custom profiles
The complete set of Http Inspect config options that a custom profile can
configure can be found by running the following command:
snort --help-config http_inspect | grep http_inspect.profile
The new Http Inspect (new_http_inspect) implementation of config options is
still under development. |
<u>QuickSort</u>
Quicksort is an extremely fast sorting algorithm that is particularly efficient for average scenarios.
While in worst-case scenarios (that is, inversely sorted arrays), it performs similarly to Insertion Sort and Selection Sort, it is much faster for average scenarios - which are what occur most of the time.
Quicksort relies on a concept called partitioning.
The Quicksort algorithm is a combination of partitions and recursion. It works as follows:
1. Partition the array. The pivot is now in its proper place.
2. Treat the subarrays to the left and right of the pivot as their own arrays, and recursively repeat Steps 1 and 2. That means we'll partition each subarray and end up with even smaller sub-subarrays to the left and right of each subarray’s pivot. We then partition those subsubarrays, and so on and so forth.
3. When we have a subarray that has zero or one elements, that is our base case and we do nothing.
Quicksort is O(nlogN) time. In a worst-case scenario, Quicksort has an efficiency of O(N^2).
MergeSort is another recursive algorithm that has O(nlogN) time. |
type Admin = {
name: string;
priviledges: string[];
};
type NormalStaff = {
name: string;
startDate: Date;
};
// intersection type
type ElevatedEmployee = Admin & NormalStaff;
const E1: ElevatedEmployee = {
name: "Elon",
priviledges: ["Handle CI/CD"],
startDate: new Date(),
}; |
from: https://www.pdflabs.com/docs/pdftk-cli-examples/
PDFtk Server Examples
These examples show you how to perform common PDF tasks from the command-line using pdftk.
1. Collate scanned pages
pdftk A=even.pdf B=odd.pdf shuffle A B output collated.pdf
or if odd.pdf is in reverse order:
pdftk A=even.pdf B=odd.pdf shuffle A Bend-1 output collated.pdf
2. Decrypt a PDF
pdftk secured.pdf input_pw foopass output unsecured.pdf
3. Encrypt a PDF using 128-bit strength (the default), withhold all permissions (the default)
pdftk 1.pdf output 1.128.pdf owner_pw foopass
Same as above, except password baz must also be used to open output PDF
pdftk 1.pdf output 1.128.pdf owner_pw foo user_pw baz
Same as above, except printing is allowed (once the PDF is open)
pdftk 1.pdf output 1.128.pdf owner_pw foo user_pw baz allow printing
Join in1.pdf and in2.pdf into a new PDF, out1.pdf
pdftk in1.pdf in2.pdf cat output out1.pdf
or (using handles):
pdftk A=in1.pdf B=in2.pdf cat A B output out1.pdf
or (using wildcards):
pdftk *.pdf cat output combined.pdf
Remove page 13 from in1.pdf to create out1.pdf
pdftk in.pdf cat 1-12 14-end output out1.pdf
or:
pdftk A=in1.pdf cat A1-12 A14-end output out1.pdf
Apply 40-bit encryption to output, revoking all permissions (the default). Set the owner PW to foopass.
pdftk 1.pdf 2.pdf cat output 3.pdf encrypt_40bit owner_pw foopass
Join two files, one of which requires the password foopass. The output is not encrypted.
pdftk A=secured.pdf 2.pdf input_pw A=foopass cat output 3.pdf
Uncompress PDF page streams for editing the PDF in a text editor (e.g., vim, emacs)
pdftk doc.pdf output doc.unc.pdf uncompress
Repair a PDF’s corrupted XREF table and stream lengths, if possible
pdftk broken.pdf output fixed.pdf
Burst a single PDF document into pages and dump its data to doc_data.txt
pdftk in.pdf burst
Burst a single PDF document into encrypted pages. Allow low-quality printing
pdftk in.pdf burst owner_pw foopass allow DegradedPrinting
Write a report on PDF document metadata and bookmarks to report.txt
pdftk in.pdf dump_data output report.txt
Rotate the first PDF page to 90 degrees clockwise
pdftk in.pdf cat 1east 2-end output out.pdf
Rotate an entire PDF document to 180 degrees
pdftk in.pdf cat 1-endsouth output out.pdf |
import {useState} from 'react'
import { useDispatch, useSelector } from 'react-redux';
import {Link, NavLink} from 'react-router-dom'
import { toast } from 'react-toastify';
import { logoutUser } from '../../../redux/userSlice';
// import css and components
import './navbar.css'
import Bubbles from '../../utility/bubbles/bubbles';
// menu
const menu = [
{mainMenu: 'home'},
{mainMenu: 'about'},
{mainMenu: 'contact'},
{mainMenu: 'auction'},
{mainMenu: 'products', subMenu: ['painting', 'photography', 'sculpture', 'drawing', 'digital art']},
];
const Navbar = ({user, isAuthenticated}) => {
const dispatch = useDispatch();
const {isLoading} = useSelector(state => state.user);
const [sidebar, setSidebar] = useState(false);
const [profileSpeedDial, setProfileSpeedDial] = useState(false);
let activeStyle = {
fontWeight: "bolder",
};
const handleLogout = () => {
dispatch(logoutUser());
toast.success("Logged out successfully!");
};
return (
<>
<nav className='navbar'>
<div className="navLogo">
<Link to='/'>VA</Link>
</div>
<ul className={!sidebar ? "navMenu" : "navMenu active" }>
{
menu.map((mm, index) => {
return(
<li key={index}>
<NavLink exact="true" to={mm.mainMenu === 'home' ? '/' : mm.mainMenu} style={({ isActive }) => isActive ? activeStyle : undefined }>
<span>{mm.mainMenu}</span>
{mm.subMenu && <i className="fa-solid fa-chevron-down"></i>}
</NavLink>
{
mm.subMenu &&
<ul className='subMenu'>
{
mm.subMenu.map((sm, index) => {
return(
<li key={index}>
<NavLink exact="true" to={sm ==='digital art' ? mm.mainMenu+'/digital' : mm.mainMenu+'/'+sm}>{sm}</NavLink>
</li>
)
})
}
</ul>
}
</li>
)
})
}
</ul>
<div className='navIcons'>
<div className='searchIcon'>
<input type="text" placeholder="Search" autoComplete="off" required/>
<i className="fa-solid fa-magnifying-glass"></i>
</div>
<div className="profileIcon" onClick={() => setProfileSpeedDial(!profileSpeedDial)}>
{profileSpeedDial ? <i className="fa-solid fa-xmark"></i> : <i className="fa-regular fa-user"></i>}
<div className={profileSpeedDial ? "active" : ""}>
{isAuthenticated && <Link to='/profile'>{user?.name || "Account"}</Link>}
{isAuthenticated && user?.role === "admin" && <Link to='/admin'>Admin Panel</Link>}
{!isAuthenticated && <Link to='/login'>Login</Link>}
{!isAuthenticated && <Link to='/register'>Register</Link>}
{isAuthenticated && <button onClick={handleLogout}>{isLoading ? <Bubbles /> : "Log Out"}</button>}
</div>
</div>
<div className="cartIcon">
<i className="fa-solid fa-cart-shopping"></i>
<span className="nav-total-quantity">8</span>
</div>
<div className="barsIcon" onClick={() => setSidebar(!sidebar)}>
{!sidebar ? <i className="fa-solid fa-bars"></i> : <i className="fa-solid fa-xmark"></i>}
</div>
</div>
</nav>
</>
)
}
export default Navbar |
import * as React from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import WebhookSubscription from "~/models/WebhookSubscription";
import WebhookSubscriptionForm from "./WebhookSubscriptionForm";
type Props = {
onSubmit: () => void;
webhookSubscription: WebhookSubscription;
};
interface FormData {
name: string;
url: string;
events: string[];
}
function WebhookSubscriptionEdit({ onSubmit, webhookSubscription }: Props) {
const { t } = useTranslation();
const handleSubmit = React.useCallback(
async (data: FormData) => {
try {
const events = Array.isArray(data.events) ? data.events : [data.events];
const toSend = {
...data,
events,
};
await webhookSubscription.save(toSend);
toast.success(t("Webhook updated"));
onSubmit();
} catch (err) {
toast.error(err.message);
}
},
[t, onSubmit, webhookSubscription]
);
return (
<WebhookSubscriptionForm
handleSubmit={handleSubmit}
webhookSubscription={webhookSubscription}
/>
);
}
export default WebhookSubscriptionEdit; |
class UsersController < ApplicationController
def index
users = User.all
render json: users
end
def show
user = User.find(params[:id])
render json: user
end
def showme
user = User.find_by(id: session[:user_id])
if user
render json: user
else
render json: { error: "Not authorized" }, status: :unauthorized
end
end
def create
user = User.create(params_user)
if user.valid?
render json: user, status: :created
else
render json: { errors: user.errors.full_messages }, status: :unprocessable_entity
end
end
def update
user = User.find(params[:id])
user.update(params_user)
render json: user
end
#Delete
def destroy
user = User.find(params[:id])
user.destroy!
head :no_content
end
private
def params_user
params.permit(:username, :email, :avatar, :bio, :contact, :password, :password_confirmation)
end
end |
package launch;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.WebResourceSet;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.EmptyResourceSet;
import org.apache.catalina.webresources.StandardRoot;
import org.apache.tomcat.util.descriptor.web.ErrorPage;
import java.io.File;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
Tomcat tomcat = new Tomcat();
Path tempPath = Files.createTempDirectory("tomcat-base-dir");
tomcat.setBaseDir(tempPath.toString());
tomcat.setPort(8080);
File webContentFolder = new File("src/main/webapp/");
StandardContext ctx = (StandardContext) tomcat.addWebapp("", webContentFolder.getAbsolutePath());
ctx.setParentClassLoader(Main.class.getClassLoader());
ErrorPage errorPage404 = new ErrorPage();
errorPage404.setErrorCode(404);
errorPage404.setLocation("/index.jsp");
ctx.addErrorPage(errorPage404);
File additionWebInfClassesFolder = new File("target/classes");
WebResourceRoot resources = new StandardRoot(ctx);
WebResourceSet resourceSet;
if (additionWebInfClassesFolder.exists()) {
resourceSet = new DirResourceSet(resources, "/WEB-INF/classes",
additionWebInfClassesFolder.getAbsolutePath(), "/");
} else {
resourceSet = new EmptyResourceSet(resources);
}
resources.addPreResources(resourceSet);
ctx.setResources(resources);
tomcat.start();
tomcat.getServer().await();
}
} |
package util
import (
"crypto/rand"
"fmt"
"math"
"math/big"
)
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
func RandomString(tkLength int32) string {
s := make([]rune, tkLength)
length := big.NewInt(int64(len(letters)))
for i := range s {
number, _ := rand.Int(rand.Reader, length)
s[i] = letters[number.Int64()]
}
return string(s)
}
func ParseUIntFromMap(data map[string]interface{}, key string) (uint, error) {
value, ok := data[key]
if !ok {
return 0, fmt.Errorf("key '%s' not found in map", key)
}
var intValue int
switch v := value.(type) {
case int:
intValue = v
case float64:
// Check if float value is within integer range and convert
if math.Trunc(v) == v {
intValue = int(v)
} else {
return 0, fmt.Errorf("value for key '%s' is a float and cannot be represented as an integer", key)
}
default:
return 0, fmt.Errorf("value for key '%s' is not an integer or float", key)
}
return uint(intValue), nil
} |
// Modul implementujacy kolejke FIFO
#include <stdlib.h>
#include "memory.h"
#include "queue.h"
// Funkcja tworzaca nowa kolejke.
Queue *queue_init() {
Queue *queue = safe_malloc(sizeof(Queue));
// Poczatkowo kolejka jest pusta.
queue->size = 0;
queue->first_element = NULL;
queue->last_element = NULL;
return queue;
}
// Funkcja sprawdzajaca, czy kolejka "queue" jest pusta.
bool queue_is_empty(Queue *queue) {
return queue->size == 0;
}
// Funkcja dodajacy nowy element "value" na koniec kolejki "queue".
void queue_insert(Queue *queue, size_t value) {
struct Node *new_element_node = safe_malloc(sizeof(struct Node));
new_element_node->value = value;
new_element_node->next_element = NULL;
// Jezeli kolejka jest pusta, to dodawany element bedzie jednoczesnie
// na jej poczatku i koncu.
if (queue->first_element == NULL) {
queue->first_element = new_element_node;
queue->last_element = new_element_node;
queue->size ++;
return;
}
// Zmiana wskaznika do ostatniego elementu kolejki.
queue->last_element->next_element = new_element_node;
queue->last_element = new_element_node;
queue->size ++;
}
// Funkcja zwracajaca wartosc pierwszego elementu w kolejce "queue".
size_t queue_front(Queue *queue) {
return queue->first_element->value;
}
// Funkcja usuwajaca pierwszy element z kolejki "queue".
void queue_pop(Queue *queue) {
struct Node *popped_element = queue->first_element;
queue->first_element = queue->first_element->next_element;
// Podczas wywolywania tej funkcji, tracimy wskaznik do usunietego elementu,
// wiec trzeba ja od razu zwolnic, by zapobiec wyciekom.
free(popped_element);
queue->size --;
}
// Funkjca zwalniajaca pamiec zaalkoowana przez kolejke "queue".
void queue_free(Queue *queue) {
// Usuwanie elementow zwalnia zaalokowana dla nich pamiec, wiec w ponizszy
// mozna zwolnic pamiec zaalokowana dla wszystkich elementow w kolejce.
while (!queue_is_empty(queue)) {
queue_pop(queue);
}
free(queue);
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
html:-moz-full-screen{
background: red;
}
html:-webkit-full-screen{
background: red;
}
html:fullscreen{
background: red;
}
</style>
<body>
<input type="button" id="btnFullScreen" value="页面全屏显示" onclick="toggleFullScreen();">
<div style="width: 100%;" id="fullscreenState">非全屏显示</div>
</body>
<script>
var docElm = document.documentElement;
var fullscreenState = document.getElementById("fullcreenState");
var btnFullScreen = document.getElementById("btnFullScreen");
fullscreenState.style.height=docElm.clientHeight+"px";
document.addEventListener("fullcreenchange",function () {
fullscreenState.innerHTML = (document.fullscreen)?"全屏显示":"非全屏显示";
btnFullScreen.value = (document.fulllscreen)?"页面非全屏显示":"页面全屏显示";
},false);
document.addEventListener("mozfullcreenchange",function () {
fullscreenState.innerHTML = (document.mozFullScreen)?"全屏显示":"非全屏显示";
btnFullScreen.value = (document.mozFulllScreen)?"页面非全屏显示":"页面全屏显示";
},false);
document.addEventListener("webkitfullcreenchange",function () {
fullscreenState.innerHTML = (document.webkitIsFullScreen)?"全屏显示":"非全屏显示";
btnFullScreen.value = (document.webkitIsFullScreen)?"页面非全屏显示":"页面全屏显示";
},false);
function toggleFullScreen(){
if (btnFullScreen.value=="页面全屏显示"){
if(docElm.requestFullscreen){
docElm.requestFullscreen();
}else if(docElm.mozRequestFullScreen){
docElm.mozRequestFullScreen();
}else if (docElm.webkitRequestFullScreen){
docElm.webkitRequestFullScreen();
}
}else{
if (document.exitFullscreen){
document.exitFullscreen();
}else if(document.mozCancelFullScreen){
document.mozCancelFullScreen();
}else if(document.webkitCancelFullScreen){
document.webkitCancelFullScreen();
}
}
}
</script>
</html> |
import asyncio
import types
import typing
from eyepop.jobs import Job
class SyncJob:
def __init__(self, job: Job, event_loop):
self.job = job
self.event_loop = event_loop
def predict(self) -> dict:
prediction = self.event_loop.run_until_complete(self.job.predict())
return prediction
def cancel(self):
self.event_loop.run_until_complete(self.job.cancel())
class SyncEndpoint:
def __init__(self, enpoint: "Endpoint"):
self._on_ready = None
self.endpoint = enpoint
self.event_loop = asyncio.new_event_loop()
def __del__(self):
self.event_loop.close()
def __enter__(self) -> "SyncEndpoint":
self.connect()
return self
def __exit__(
self,
exc_type: typing.Optional[typing.Type[BaseException]],
exc_val: typing.Optional[BaseException],
exc_tb: typing.Optional[types.TracebackType],
) -> None:
self.disconnect()
def upload(self, file_path: str, params: dict | None = None, on_ready: typing.Callable[[Job], None] | None = None) -> SyncJob:
if on_ready is not None:
raise TypeError(
"'on_ready' callback not supported for sync endpoints. "
"Use 'EyePopSdk.connect(is_async=True)` to create an async endpoint with callback support")
job = self.event_loop.run_until_complete(self.endpoint.upload(file_path, params, None))
return SyncJob(job, self.event_loop)
def upload_stream(self, stream: typing.BinaryIO, mime_type: str, params: dict | None = None, on_ready: typing.Callable[[Job], None] | None = None) -> SyncJob:
if on_ready is not None:
raise TypeError(
"'on_ready' callback not supported for sync endpoints. "
"Use 'EyePopSdk.connect(is_async=True)` to create an async endpoint with callback support")
job = self.event_loop.run_until_complete(self.endpoint.upload_stream(stream, mime_type, params, None))
return SyncJob(job, self.event_loop)
def load_from(self, location: str, params: dict | None = None, on_ready: typing.Callable[[Job], None] | None = None) -> SyncJob:
if on_ready is not None:
raise TypeError(
"'on_ready' callback not supported for sync endpoints. "
"Use 'EyePopSdk.connect(is_async=True)` to create an async endpoint with callback support")
job = self.event_loop.run_until_complete(self.endpoint.load_from(location, params, None))
return SyncJob(job, self.event_loop)
def connect(self):
self.event_loop.run_until_complete(self.endpoint.connect())
def disconnect(self):
self.event_loop.run_until_complete(self.endpoint.disconnect())
def session(self) -> dict:
return self.event_loop.run_until_complete(self.endpoint.session())
def get_pop_comp(self) -> dict:
return self.event_loop.run_until_complete(self.endpoint.get_pop_comp())
def set_pop_comp(self, popComp: str) -> dict:
return self.event_loop.run_until_complete(self.endpoint.set_pop_comp(popComp))
def get_post_transform(self) -> dict:
return self.event_loop.run_until_complete(self.endpoint.get_post_transform())
def set_post_transform(self, transform: str) -> dict:
return self.event_loop.run_until_complete(self.endpoint.set_post_transform(transform))
'''
Start Block
Below methods are not meant for the end user to use directly. They are used by the SDK internally.
'''
def list_models(self) -> dict:
return self.event_loop.run_until_complete(self.endpoint.list_models())
def get_manifest(self) -> dict:
return self.event_loop.run_until_complete(self.endpoint.get_manifest())
def set_manifest(self, manifest:dict) -> None:
return self.event_loop.run_until_complete(self.endpoint.set_manifest(manifest))
def load_model(self, model:dict, override:bool = False) -> dict:
return self.event_loop.run_until_complete(self.endpoint.load_model(model, override))
def unload_model(self, model_id: str) -> None:
return self.event_loop.run_until_complete(self.endpoint.unload_model(model_id))
'''
End Block
''' |
package vohohungthinh.lab3.Validator.annotation;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import vohohungthinh.lab3.Validator.ValidUsernameValidator;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({TYPE, FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = ValidUsernameValidator.class)
@Documented
public @interface ValidUsername {
String message() default "Username already exists";
Class<?> [] groups() default {};
Class <? extends Payload> [] payload() default {};
} |
import {
View,
Text,
RefreshControl,
ScrollView,
StatusBar,
Box,
Button,
Input,
InputField,
Modal,
ModalBackdrop,
ModalCloseButton,
ModalContent,
ModalHeader,
} from '@gluestack-ui/themed';
import { useAppTheme, useAppToast, useAuth, useFirebase, useImageUpload } from '../../../../hooks';
import { useEffect, useState } from 'react';
import { Journal as JournalType, JournalObject } from '../../../../types';
import { IconButton } from '../../../../components';
import { router } from 'expo-router';
import { ArrowLeft, Plus } from 'lucide-react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';
const cardColors = {
own: '#32285c',
other: '#1e3375',
};
export default function Journal() {
const { colorMode } = useAppTheme();
const { showToast } = useAppToast();
const { user } = useAuth();
const [journal, setJournal] = useState<JournalObject | null>(null);
const { uploadImage, askPermission } = useImageUpload();
const [isUploading, setIsUploading] = useState(false);
const { getJournal, listenToJournalChanges, createEntryInJournal } = useFirebase();
const [refreshing, setRefreshing] = useState(false);
const [loading, setLoading] = useState(true);
const [modalOpen, setModalOpen] = useState(false);
const [modalValues, setModalValues] = useState<JournalType>({
author: user.displayName || '',
authorId: user.uid || '',
title: '',
description: '',
createdAt: '',
updatedAt: '',
});
const loadData = async () => {
if (user.roomId) {
const data = await getJournal(user.roomId);
setJournal(data);
setLoading(false);
}
};
useEffect(() => {
if (user.roomId) {
loadData();
listenToJournalChanges((data) => {
setJournal(data.journal);
}, user.roomId);
}
}, []);
const handleOpenModal = () => {
setModalOpen(true);
};
const handleCloseModal = () => {
setModalOpen(false);
};
const handleSave = async () => {
if (!user.roomId) return;
if (modalValues.title && modalValues.description) {
const data = {
...modalValues,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
await createEntryInJournal(user.roomId, data);
showToast({ description: 'Entry created', status: 'success', title: 'Success' });
setModalOpen(false);
}
};
const getTextPreview = (text: string) => {
if (text.length > 100) {
return text.slice(0, 100) + '...';
}
return text;
};
const goToEntry = (entryId: string) => {
router.push(`/(tabs)/Home/Journal/${entryId}`);
};
return (
<View
style={{
backgroundColor: colorMode === 'dark' ? '#121212' : '#F5F5F5',
padding: 20,
paddingBottom: 20,
flex: 1,
}}>
<Box
style={{
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingBottom: 20,
}}>
<IconButton icon={ArrowLeft} onPress={router.back} />
<Box
style={{
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
gap: 10,
}}>
<Text
style={{
fontSize: 24,
lineHeight: 32,
fontWeight: 'bold',
}}>
Journal
</Text>
<IconButton icon={Plus} onPress={handleOpenModal} />
</Box>
</Box>
<ScrollView
$dark-backgroundColor="#121212"
contentContainerStyle={{
justifyContent: 'flex-start',
alignItems: 'center',
paddingBottom: 60,
gap: 10,
}}
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={loadData} />}>
{journal &&
Object.keys(journal).map((key) => {
const entry = journal[key];
return (
<TouchableOpacity
key={key}
style={{
minWidth: '100%',
backgroundColor: user?.uid === entry.authorId ? cardColors.own : cardColors.other,
padding: 20,
borderRadius: 10,
flexDirection: 'column',
justifyContent: 'flex-start',
gap: 10,
}}
onPress={() => goToEntry(key)}>
<Box
style={{
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
gap: 10,
}}>
<Text
style={{
fontSize: 18,
fontWeight: 'bold',
}}>
{entry.title}
</Text>
</Box>
<Text
style={{
fontSize: 14,
}}>
{getTextPreview(entry.description)}
</Text>
<Box
style={{
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
gap: 10,
}}>
<Text
style={{
fontSize: 12,
}}>
{new Date(entry.createdAt).toLocaleString()}
</Text>
<Text
style={{
fontSize: 12,
}}>
{entry.author}
</Text>
</Box>
</TouchableOpacity>
);
})}
<StatusBar backgroundColor={colorMode === 'dark' ? '#000000' : '#F5F5F5'} />
</ScrollView>
<Modal isOpen={modalOpen}>
<ModalBackdrop onPress={handleCloseModal} />
<ModalContent>
<ModalCloseButton onPress={handleCloseModal} />
<ModalHeader>
<Text>New note</Text>
</ModalHeader>
<Box
style={{
padding: 20,
gap: 20,
}}>
<Input>
<InputField
value={modalValues.title}
onChangeText={(value) => setModalValues({ ...modalValues, title: value })}
placeholder="Title"
/>
</Input>
<Input
style={{
height: 200,
flexDirection: 'column',
justifyContent: 'flex-start',
alignContent: 'flex-start',
}}>
<InputField
value={modalValues.description}
onChangeText={(value) => setModalValues({ ...modalValues, description: value })}
placeholder="Note"
multiline
numberOfLines={8}
style={{
height: 200,
textAlignVertical: 'top',
}}
/>
</Input>
<Button
onPress={handleSave}
style={{
backgroundColor: '#005e78',
padding: 10,
borderRadius: 10,
}}>
<Text
style={{
color: '#ffffff',
textAlign: 'center',
}}>
Save
</Text>
</Button>
</Box>
</ModalContent>
</Modal>
</View>
);
} |
import React, { useState, useEffect } from 'react';
import { SafeAreaView, StatusBar, Text, View, Image, TouchableOpacity, PermissionsAndroid } from 'react-native';
import firestore from '@react-native-firebase/firestore';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';
import Input from '../../../components/Input'
import InputDate from '../../../components/InputDate'
import { Styles } from './styles';
const Update = ({ route, navigation }) => {
const { selected } = route.params
const [image, setImage] = useState(selected.image)
const [code, setCode] = useState(`${selected.code}`)
const [name, setName] = useState(`${selected.name}`)
const [birthdate, setBirthdate] = useState(new Date(selected.birthdate.toDate()))
const [isLoading, setIsLoading] = useState(false)
const callCamera = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: "App Camera Permission",
message: "App needs access to your camera ",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
var options = {
skipBackup: true,
includeBase64: true,
maxHeight: 500,
mediaType: 'photo',
path: 'images',
}
launchCamera(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker')
return
}
if (response.error) {
console.log('ImagePicker Error: ', response.error)
return
}
if (response.customButton) {
console.log('User tapped custom button: ', response.customButton)
alert(response.customButton)
return
}
setImage(response.assets[0].base64)
}).catch((error) => alert(error))
} else {
console.log("Camera permission denied");
}
} catch (err) {
console.warn(err);
}
}
const callGalery = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
{
title: "App Camera Permission",
message: "App needs access to your camera ",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
var options = {
skipBackup: true,
includeBase64: true,
maxHeight: 500,
maxWidth: 500,
mediaType: 'photo',
path: 'images',
}
launchImageLibrary(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker')
return
}
if (response.error) {
console.log('ImagePicker Error: ', response.error)
return
}
if (response.customButton) {
console.log('User tapped custom button: ', response.customButton)
alert(response.customButton)
return
}
setImage(response.assets[0].base64)
}).catch((error) => alert(error))
} else {
console.log("Camera permission denied");
}
} catch (err) {
console.warn(err);
}
}
const updateUser = () => {
setIsLoading(true)
firestore()
.collection('user')
.doc(selected.id)
.update({
code: code,
name: name,
birthdate: birthdate,
image: image
})
.then(() => {
setIsLoading(false)
navigation.reset({
index: 0,
routes: [{ name: "UserList" }]
})
})
.catch((error) => console.log(error))
}
const deleteUser = () => {
setIsLoading(true)
firestore()
.collection('user')
.doc(selected.id)
.delete()
.then(() => {
setIsLoading(false)
navigation.reset({
index: 0,
routes: [{ name: "UserList" }]
})
})
.catch((error) => console.log(error))
}
const popNavigation = () => {
navigation.pop()
}
return (
<SafeAreaView style={Styles.container} >
<StatusBar backgroundColor="#fff" />
<View style={Styles.header} >
<TouchableOpacity onPress={popNavigation} >
<Icon name='chevron-left' color='#555' size={30} />
</TouchableOpacity>
<Text style={Styles.title} >Edit</Text>
<TouchableOpacity onPress={() => !isLoading && deleteUser()} >
<Text style={Styles.delete} >delete</Text>
</TouchableOpacity>
</View>
{
image ?
<View style={Styles.input} >
<Image style={Styles.avatarBg} source={{ uri: `data:image/jpg;base64,${image}` }} />
</View>
:
<View style={Styles.input} >
<View style={Styles.avatarBg} >
<Icon style={Styles.avatar} name='account' color='#022280' size={80} />
</View>
</View>
}
<View style={Styles.input} >
<View style={{ width: 200, flexDirection: 'row', justifyContent: 'space-around' }} >
<TouchableOpacity style={Styles.imageOption} onPress={callCamera} >
<Icon style={{ alignSelf: 'center' }} name='camera' color='#fff' size={20} />
</TouchableOpacity>
<TouchableOpacity style={Styles.imageOption} onPress={callGalery} >
<Icon style={{ alignSelf: 'center' }} name='image-plus' color='#fff' size={20} />
</TouchableOpacity>
<TouchableOpacity style={Styles.imageOption} onPress={() => setImage(null)} >
<Icon style={{ alignSelf: 'center' }} name='image-off' color='#fff' size={20} />
</TouchableOpacity>
</View>
</View>
<View style={Styles.input} >
<Input
placeholder={'User code'}
label={'User code'}
keyboard='numeric'
state={code}
setState={setCode}
editable={!isLoading}
/>
</View>
<View style={Styles.input} >
<Input
placeholder={'User name'}
label={'User name'}
keyboard='default'
state={name}
setState={setName}
editable={!isLoading}
/>
</View>
<View style={Styles.input} >
<InputDate
state={birthdate}
setState={setBirthdate}
label={'Birthdate'}
editable={!isLoading}
/>
</View>
<View style={Styles.input} >
<TouchableOpacity style={Styles.button} onPress={updateUser} >
<Icon style={Styles.avatar} name='content-save' color='#fff' size={20} />
<Text style={Styles.btext} >Save</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
export default Update; |
//
// CurrentUserProfileView.swift
// ThreadsClone
//
// Created by Isidro Chávez on 2024-05-24.
//
import SwiftUI
struct CurrentUserProfileView: View {
@StateObject var viewModel = CurrentUserProfileViewModel()
@State private var showEditProfile = false
private var currentUser: User? {
return viewModel.currentUser
}
var body: some View {
NavigationStack{
ScrollView{
//bio and stats
VStack (spacing: 20){
ProfileHeaderView(user: currentUser)
Button {
showEditProfile.toggle()
} label: {
Text("Edit Profile")
.font(.subheadline)
.fontWeight(.semibold)
.foregroundStyle(.black)
.frame(width: 352, height: 32)
.background(.white)
.clipShape(RoundedRectangle(cornerRadius: 8))
.overlay{
RoundedRectangle(cornerRadius: 8)
.stroke(Color(.systemGray4), lineWidth: 1)
}
}
//user content list view
if let user = currentUser {
UserContentListView(user: user)
}
}
}
.sheet(isPresented: $showEditProfile, content: {
if let user = currentUser {
EditProfileView(user: user)
}
})
.toolbar {
ToolbarItem(placement: .topBarTrailing){
Button {
AuthService.shared.signOut()
} label: {
Image(systemName: "line.3.horizontal")
}
.tint(.black)
}
}
.scrollIndicators(.never)
.padding(.horizontal)
}
}
}
#Preview {
CurrentUserProfileView()
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="content">
<router-link to="/home">home</router-link>
<router-link to="/news">news</router-link>
<router-view></router-view>
</div>
<template id="homePage">
<div class="">
<h2>this is home page</h2>
</div>
</template>
<template id="newsPage">
<div class="">
<h3>this is news page</h3>
</div>
</template>
<script src="../js/vue.js" charset="utf-8"></script>
<script src="../js/vue-router.min.js" charset="utf-8"></script>
<script type="text/javascript">
//init router component
var Home = {
template:'#homePage'
}
var News = {
template:'#newsPage'
}
var route = [
{path:'/home',component:Home},
{path:'/news',component:News}
]
var router = new VueRouter({
routes:route
})
var app = new Vue({
router,
el:'.content'
})
</script>
</body>
</html> |
import {
Facebook,
Instagram,
Linkedin,
Mail,
MapPin,
MessageCircle,
MessageSquare,
Phone,
Twitter,
} from "lucide-react";
import Link from "next/link";
import React from "react";
import { info } from "@/constants/info";
function TopBar() {
return (
<div className="shadow-inner bg-primary-fill-light-muted dark:bg-primary-fill-dark-muted shadow-zinc-800">
<div className="top-bar container flex flex-row justify-between content-center py-1">
<div className="left-top flex flex-row gap-4 text-secondary-light dark:text-secondary-dark">
<div className="address">
<Link
href={info.map}
className="flex flex-row justify-center"
target="_blank"
>
<MapPin className="w-4 h-4 mt-1 mr-2" />
<p className="text-sm text-bold">{info.address}</p>
</Link>
</div>
<div className="email">
<Link
href={`mailto:${info.email}`}
className="flex flex-row justify-center"
>
<Mail className="w-4 h-4 mt-1 mr-2" />
<p className="text-sm text-bold ">{info.email}</p>
</Link>
</div>
<div className="phone">
<Link
href={`tel:${info.phone.replace(" ", "")}`}
className="flex flex-row justify-center"
>
<Phone className="w-4 h-4 mt-1 mr-2" />
<p className="text-sm text-bold">{info.phone}</p>
</Link>
</div>
</div>
<div className="right-top flex flex-row gap-4 text-secondary-light">
{info.facebook && (
<Link href={info.facebook} target="_blank">
<Facebook className="h-4 w-4 cursor-pointer hover:bg-blue-600 hover:rounded hover:bg-opacity-80 hover:text-blue-800" />
</Link>
)}
{info.instagram && (
<Link href={info.instagram} target="_blank">
<Instagram className="h-4 w-4 cursor-pointer hover:bg-pink-600 hover:rounded hover:bg-opacity-80 hover:text-pink-800" />
</Link>
)}
{info.linkedin && (
<Link href={info.linkedin} target="_blank">
<Linkedin className="h-4 w-4 cursor-pointer hover:bg-violet-600 hover:rounded hover:bg-opacity-80 hover:text-violet-800" />
</Link>
)}
{info.twitter && (
<Link href={info.twitter} target="_blank">
<Twitter className="h-4 w-4 cursor-pointer hover:bg-blue-400 hover:rounded hover:bg-opacity-80 hover:text-blue-800" />
</Link>
)}
{info.viber && (
<Link href={info.viber} target="_blank">
<MessageSquare className="h-4 w-4 cursor-pointer hover:bg-purple-400 hover:rounded hover:bg-opacity-80 hover:text-purple-800" />
</Link>
)}
{info.whatsapp && (
<Link href={info.whatsapp} target="_blank">
<MessageCircle className="h-4 w-4 cursor-pointer hover:bg-green-400 hover:rounded hover:bg-opacity-80 hover:text-green-800" />
</Link>
)}
</div>
</div>
</div>
);
}
export default TopBar; |
import React, { useEffect, useState } from "react";
import Form from "./Form";
import Items from "./Items";
const App = () => {
const API_URL = "http://localhost:3004/comments/";
const [items, setItems] = useState([]);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const [isUpdate, setIsUpdate] = useState(false);
const getId = items.map((id) => id.id);
const [newItem, setNewItem] = useState({
id: getId.at(-1) + 1,
name: "",
body: "",
});
const fetchApi = async () => {
setLoading(true);
try {
const res = await fetch(`${API_URL}/?_sort=id&_order=desc`);
if (!res.ok) throw Error("Error : at fetchApi");
const data = await res.json();
setItems(data);
setLoading(false);
} catch (error) {
console.log(error);
setError(error.message);
setLoading(false);
}
};
useEffect(() => {
fetchApi();
}, []);
const putDataToApi = async () => {
const { id, name, body } = newItem;
try {
const res = await fetch(`${API_URL}${id}`, {
method: "PUT",
// body: JSON.stringify({
// ...id,
// ...name,
// ...body,
// }),
header: {
"Content-Type": "application/json",
},
});
const newData = await res.json();
setItems([...items, { ...newData }]);
fetchApi();
console.log(newData);
console.log(id, name, body);
} catch (error) {
console.log(error.message);
}
};
const onEditItem = (data) => {
setIsUpdate(true);
setNewItem(data);
// console.log(isUpdate);
// console.log(data);
};
const onDeleteItem = async (id) => {
try {
const fetchItem = await fetch(`${API_URL}${id}`, {
method: "DELETE",
});
if (!fetchItem.ok) throw Error(`Error : cannot fetching the data`);
fetchApi();
} catch (error) {
console.log(error);
setError(error.message);
}
};
return (
<section className="bg-[#0F172A] text-white">
<div className="flex justify-center py-4 px-8">
{error && <p>{error}</p>}
</div>
<Form
items={items}
setItems={setItems}
API_URL={API_URL}
fetchApi={fetchApi}
newItem={newItem}
setNewItem={setNewItem}
isUpdate={isUpdate}
putDataToApi={putDataToApi}
setIsUpdate={setIsUpdate}
/>
<div className="flex justify-center ">
{loading && <p>Loading ...</p>}
</div>
{items.length > 0 ? (
<Items items={items} deleteItem={onDeleteItem} editItem={onEditItem} />
) : (
<div className="flex justify-center ">
<p className="mt-8">Item not found</p>
</div>
)}
</section>
);
};
export default App; |
from django.shortcuts import render
from django.shortcuts import redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.core import serializers
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.shortcuts import get_object_or_404
from home.forms import PostsForm
from .models import Posts
import datetime
import json
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
def show_homepage(request):
data_posts = Posts.objects.all()
context = {
'list_posts': data_posts,
'is_authenticated': request.user.is_authenticated,
}
return render(request, "home.html", context)
@login_required(login_url='/home/login/')
def logged_in(request):
data_posts = Posts.objects.all()
context = {
'list_posts': data_posts,
'username': request.COOKIES['username'],
'last_login': request.COOKIES['last_login'],
'is_authenticated': request.user.is_authenticated,
}
return render(request, "home.html", context)
@login_required(login_url='/home/login/')
def profile(request):
data_posts = Posts.objects.filter(user=request.user)
context = {
'list_posts': data_posts,
'username': request.COOKIES['username'],
'last_login': request.COOKIES['last_login'],
'is_authenticated': request.user.is_authenticated,
}
return render(request, "profile.html", context)
def register(request):
form = UserCreationForm()
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Akun berhasil dibuat!')
return redirect('home:login')
context = {'form': form}
return render(request, 'register.html', context)
def login_user(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
if user is not None:
login(request, user)
response = HttpResponseRedirect(
reverse("home:logged_in"))
response.set_cookie('last_login', str(datetime.datetime.now()))
response.set_cookie('username', username)
return response
else:
messages.info(request, 'Username atau Password salah!')
context = {}
return render(request, 'login.html', context)
def logout_user(request):
logout(request)
response = HttpResponseRedirect(reverse('home:show_homepage'))
response.delete_cookie('last_login')
return response
@login_required(login_url='/home/login/')
def delete_posts(request, posts_id):
if request.method == "POST":
posts = get_object_or_404(Posts, pk=posts_id)
posts.delete()
return redirect(reverse('home:show_homepage'))
def show_json(request):
posts = Posts.objects.all()
data = serializers.serialize('json', posts)
return HttpResponse(data, content_type='application/json')
@login_required(login_url='/home/login/')
def add_new_posts(request):
if request.method == "POST":
data = json.loads(request.POST['data'])
new_posts = Posts(content=data["content"], user=request.user)
new_posts.save()
return HttpResponse(serializers.serialize("json", [new_posts]), content_type="application/json")
return HttpResponse()
@login_required(login_url='/home/login/')
@csrf_exempt
def delete_new_posts(request, id):
if request.method == "POST":
posts = get_object_or_404(Posts, pk=id, user=request.user)
posts.delete()
return HttpResponse()
@login_required(login_url='/home/login/')
@csrf_exempt
def edit_new_posts(request, id):
queryset = Posts().objects.get(id=id)
form = EditPosts(instance=queryset)
if request.method == 'POST':
form = EditPosts(request.POST, instance=queryset)
if form.is_valid():
form.save()
return redirect('home:logged_in')
context = {
'form':form
}
return render(request, 'edit.html', context) |
# Brain Tumor Detection in Medical Images Using Object Detection Models
## Overview
Object Detection (OD) or object recognition in images is a profound aspect of Computer Vision. It refers to the ability of computer systems and software to locate objects in an image and identify each object, which can be used in various fields such as security, healthcare, etc., with many functions such as face detection, smart cars, license plate recognition, anomaly detection, foreign object detection, etc.
This project, **“Experimenting with Object Detection Models for Brain Tumor Detection in Medical Images”**, focuses on experimenting with Object Detection models like R-CNN, Fast R-CNN/ Faster R-CNN, and YOLOv7 to address the problem of detecting brain tumors in medical images.
## Input
- Image data from MRI or CT scanners containing information on the presence, location, and characteristics of brain tumors.
- The object to be detected: brain tumor in the images.
## Output
- Bounding box around the brain tumor in the image.
- Information about the location and characteristics of the tumor.
## Objective
- Experiment with Object Detection models: R-CNN, Fast R-CNN, Faster R-CNN, and YOLOv7.
- Automatically identify brain tumors in images to support early diagnosis and treatment planning.
## Data Requirements
- MRI or CT image data with labeled (bounding box) brain tumors.
- Data must be diverse in terms of the size, location, and characteristics of the tumors.
## Model Requirements
- The model must be capable of detecting tumors not only in easy cases but also in difficult cases such as small tumors, closely located tumors, occluded tumors, etc.
- The model needs to achieve high accuracy and fast processing speed.
## Input Requirements
- MRI or CT images containing brain tumors.
## Output Requirements
- Marked region containing the tumor and information about the tumor.
## Data
**“Brain Tumor Object Detection Datasets”** is an image and label training dataset for detecting brain tumors. The set includes training image sets and labels/bounding box coordinates for brain cancer detection in MRI images.
**Source:**
- Derived from the RSNA-MICCAI Brain Tumor competition data.
**Collection Method:**
- JPG datasets were exported at their original size, manually labeled using makesense.ai, and split by plane (Axial, Coronal, and Sagittal).
- Positive/Negative MGMT status and bounding box were labeled to classify tumor type.
**License Information:** CC0: Public Domain.
**Data Information:**
- Training set: 878 image files.
- Test set: 223 image files.
** Coronal_t1wce_2_class:**
- Training set: 319 images + 318 labels
- Test set: 78 images + 78 labels
** Axial_t1wce_2_class:**
- Training set: 310 images + 296 labels
- Test set: 75 images + 75 labels
** Sagittal_t1wce_2_class:**
- Training set: 264 images + 264 labels
- Test set: 70 images + 70 labels
### Dataset Link:
- The dataset can be accessed on Kaggle: [Brain Tumor Object Detection Datasets](https://www.kaggle.com/datasets/davidbroberts/brain-tumor-object-detection-datasets)
## Getting Started
### Prerequisites
- Python 3.x
- TensorFlow or PyTorch
- OpenCV
- Other dependencies
## Contributing
Contributions are welcome! Please open an issue or submit a pull request.
## Acknowledgments
- Thank you to all contributors and the open-source community.
- Special thanks to the developers of the R-CNN, Fast R-CNN, Faster R-CNN, and YOLOv7 models. |
import path from 'path';
import type { UploadedFile } from 'express-fileupload';
import { v4 } from 'uuid';
import { userService, verificationService } from '../services';
export class UserController {
async registration(req: Ex.Request, res: Ex.Response<{ user: UserDto }>, next: Ex.NextFunction) {
try {
const { email, name, password } = req.body;
const userData = await userService.registration({ email, name, password });
res.cookie('refreshToken', userData.refreshToken, {
maxAge: 1000 * 60 * 60 * 24 * 30, // 30 days
httpOnly: true,
});
return res.json(userData);
} catch (e) {
next(e);
}
}
async login(
req: Ex.Request,
res: Ex.Response<{ user: UserDto; refreshToken: Token['refreshToken'] }>,
next: Ex.NextFunction,
) {
try {
const { email, password } = req.body;
const userData = await userService.login({ email, password });
res.cookie('refreshToken', userData.refreshToken, {
maxAge: 1000 * 60 * 60 * 24 * 30, // 30 days
httpOnly: true,
});
return res.json(userData);
} catch (e) {
next(e);
}
}
async verify(
req: Ex.Request<{ id: User['id'] }>,
res: Ex.Response<{ user: UserDto; refreshToken: Token['refreshToken'] }>,
next: Ex.NextFunction,
) {
try {
const userId = Number(req.params.id);
const { verificationCode } = req.body;
const userData = await verificationService.verify(userId, verificationCode);
res.cookie('refreshToken', userData.refreshToken, {
maxAge: 1000 * 60 * 60 * 24 * 30, // 30 days
httpOnly: true,
});
return res.json(userData);
} catch (e) {
next(e);
}
}
async logout(req: Ex.Request, res: Ex.Response, next: Ex.NextFunction) {
try {
const { refreshToken } = req.cookies;
await userService.logout({ refreshToken });
res.clearCookie('refreshToken');
return res.status(204).json({});
} catch (e) {
next(e);
}
}
async refresh(
req: Ex.Request,
res: Ex.Response<{ user: UserDto; refreshToken: Token['refreshToken'] }>,
next: Ex.NextFunction,
) {
try {
const { refreshToken } = req.cookies;
const userData = await userService.refresh({ refreshToken });
res.cookie('refreshToken', userData.refreshToken, {
maxAge: 1000 * 60 * 60 * 24 * 30, // 30 days
httpOnly: true,
});
return res.json(userData);
} catch (e) {
next(e);
}
}
async update(req: Ex.Request, res: Ex.Response<{ user: UserDto }>, next: Ex.NextFunction) {
try {
const user = req.user!;
const updateFields = req.body;
const image = req.files?.image;
let avatar: string | null = null;
if (image) {
avatar = v4() + '.jpg';
(image as UploadedFile).mv(path.resolve(__dirname, '..', 'images', avatar));
}
const userData = await userService.update({
id: user.id,
...updateFields,
...(avatar && { avatar }),
});
return res.json({ user: userData });
} catch (e) {
next(e);
}
}
} |
package com.demo.bbq.repository.product;
import com.demo.bbq.config.properties.ServiceConfigurationProperties;
import com.demo.bbq.repository.product.wrapper.request.ProductSaveRequestWrapper;
import com.demo.bbq.repository.product.wrapper.request.ProductUpdateRequestWrapper;
import com.demo.bbq.repository.product.wrapper.response.ProductResponseWrapper;
import com.demo.bbq.commons.errors.dto.ErrorDTO;
import com.demo.bbq.commons.restclient.resttemplate.CustomRestTemplate;
import com.demo.bbq.commons.restclient.resttemplate.dto.ExchangeRequestDTO;
import java.util.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.*;
import org.springframework.stereotype.Repository;
@Repository
@RequiredArgsConstructor
public class ProductRepository {
private static final String SERVICE_NAME = "product-v1";
private final CustomRestTemplate restTemplate;
private final ServiceConfigurationProperties properties;
public ProductResponseWrapper findByCode(HttpServletRequest servletRequest, String code) {
return restTemplate.exchange(
ExchangeRequestDTO.<Void, ProductResponseWrapper>builder()
.url(getEndpoint().concat("/products/{code}"))
.httpMethod(HttpMethod.GET)
.uriVariables(Collections.singletonMap("code", code))
.responseClass(ProductResponseWrapper.class)
.errorWrapperClass(ErrorDTO.class)
.httpServletRequest(servletRequest)
.build(), SERVICE_NAME);
}
public List<ProductResponseWrapper> findByScope(HttpServletRequest servletRequest, String scope) {
return Arrays.asList(restTemplate.exchange(
ExchangeRequestDTO.<Void, ProductResponseWrapper[]>builder()
.url(getEndpoint().concat("/products?scope={scope}"))
.httpMethod(HttpMethod.GET)
.uriVariables(Collections.singletonMap("scope", scope))
.responseClass(ProductResponseWrapper[].class)
.errorWrapperClass(ErrorDTO.class)
.httpServletRequest(servletRequest)
.build(), SERVICE_NAME));
}
public void save(HttpServletRequest servletRequest, ProductSaveRequestWrapper productRequest) {
restTemplate.exchange(
ExchangeRequestDTO.<ProductSaveRequestWrapper, Void>builder()
.url(getEndpoint().concat("/products"))
.httpMethod(HttpMethod.POST)
.requestBody(productRequest)
.responseClass(Void.class)
.errorWrapperClass(ErrorDTO.class)
.httpServletRequest(servletRequest)
.build(), SERVICE_NAME);
}
public void update(HttpServletRequest servletRequest, String code, ProductUpdateRequestWrapper productRequest) {
restTemplate.exchange(
ExchangeRequestDTO.<ProductUpdateRequestWrapper, Void>builder()
.url(getEndpoint().concat("/products/{code}"))
.httpMethod(HttpMethod.PUT)
.uriVariables(Collections.singletonMap("code", code))
.requestBody(productRequest)
.responseClass(Void.class)
.errorWrapperClass(ErrorDTO.class)
.httpServletRequest(servletRequest)
.build(), SERVICE_NAME);
}
public void delete(HttpServletRequest servletRequest, String code) {
restTemplate.exchange(
ExchangeRequestDTO.<Void, Void>builder()
.url(getEndpoint().concat("/products/{code}"))
.httpMethod(HttpMethod.DELETE)
.uriVariables(Collections.singletonMap("code", code))
.responseClass(Void.class)
.errorWrapperClass(ErrorDTO.class)
.httpServletRequest(servletRequest)
.build(), SERVICE_NAME);
}
private String getEndpoint() {
return properties.getRestClients().get(SERVICE_NAME).getRequest().getEndpoint();
}
} |
import React, { useEffect, useState } from "react";
import { Col, Container, Row, Spinner } from "react-bootstrap";
import Product from "./products";
const ProductStore = () => {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch("https://dummyjson.com/products")
.then((res) => res.json())
.then((data) => {
setProducts(data.products);
setLoading(false);
});
}, []);
return (
<Container className="mt-4">
<h2 className="my-5">Produt Store</h2>
{loading && (
<div className="text-center">
<Spinner variant="warning" />
</div>
)}
<Row xs={1} sm={2} md={3} lg={4} className="g-3">
{products.map((item) => (
<Col key={item.id}>
<Product {...item} />
</Col>
))}
</Row>
</Container>
);
};
export default ProductStore; |
import { useState, useEffect } from 'react'
import { useQuery, useMutation } from '@apollo/client'
import { GET_USER_INFO } from '../../../utils/graphql/queries';
import Auth from '../../../utils/auth'
import { UPDATE_INFO, UPDATE_INTERESTS } from '../../../utils/graphql/mutations';
import { useNavigate, useParams } from 'react-router-dom';
function ViewProfile() {
const navigate = useNavigate();
const { userId } = useParams();
const { loading, error, data } = useQuery(GET_USER_INFO, {
variables: {
userId: userId, //ID FROM PARAMS
}
});
useEffect(() => {
if (!data) return;
console.log(data);
}, [data]);
return (
// <></>
<>
<main className='flex-center-h'>
{data ? (
<div id='main-container'>
<h1>{data.userById.username}</h1>
<h2>About</h2>
<table>
<thead></thead>
<tbody>
<tr>
<td>Name</td>
<td className='user-data'>{data.userById.info.name}</td>
<td>Phone</td>
<td className='user-data'>{data.userById.info.phone}</td>
</tr>
<tr>
<td>City</td>
<td className='user-data'>{data.userById.info.city}</td>
<td>Country</td>
<td className='user-data'>{data.userById.info.country}</td>
</tr>
</tbody>
</table >
<h2>Interests</h2>
{data.userById.interests.length
?
data.userById.interests.map((interest, i) =>
(<ul
key={i}
className='interest'>
<span>{interest}</span>
</ul>)
)
: 'This person has no interests.'
}
</div >
) : 'Loading...'}
</main>
</>
)
}
export default ViewProfile; |
class Classify extends tf.layers.Layer {
constructor() {
super({});
}
computeOutputShape(inputShape) { return inputShape; }
build() {}
call(input) {
return tf.tidy(() => {
return tf.concat([
tf.sigmoid(input[0].slice([0, 0, 0, 0], [-1, -1, -1, 1])),
tf.relu(input[0].slice([0, 0, 0, 1], [-1, -1, -1, -1]))
], 3);
});
}
getConfig() { return super.getConfig(); }
static get className() { return "Classify"; }
}
class Skip extends tf.layers.Layer {
constructor() {
super({});
}
computeOutputShape(inputShape) { return [null, inputShape[1][1], inputShape[1][2], inputShape[0][3] + inputShape[1][3]]; }
build() {}
call(input) {
return tf.tidy(() => {
return tf.concat([
input[1],
input[0].slice([0, 0, 0, 0], input[1].shape)
], 3);
});
}
getConfig() { return super.getConfig(); }
static get className() { return "Skip"; }
}
tf.serialization.registerClass(Classify);
tf.serialization.registerClass(Skip);
function loss(t, p) {
return tf.tidy(() => {
const [batchSize, height, width, channel] = p.shape;
// cross-entropy loss on all binary classification; mean squared error on position predictions of true text
const binaryLabels = t.slice([0, 0, 0, 0], [-1, -1, -1, 1]);
const binaryPredictions = p.slice([0, 0, 0, 0], [-1, -1, -1, 1]);
const crossEntropy = tf.metrics.binaryCrossentropy(binaryLabels, binaryPredictions);
const posLabels = t.slice([0, 0, 0, 1]);
const posPredictions = p.slice([0, 0, 0, 1]);
// const newPos = posPredictions.where(binaryLabels.cast("bool"), posLabels);
const newPos = posPredictions.mul(binaryLabels);
// console.log(posPredictions.shape, binaryLabels.shape, posLabels.shape, newPos.shape);
// const posError = tf.losses.meanSquaredError(posPredictions.mul(binaryLabels), posLabels.mul(binaryLabels));
const posError = tf.losses.meanSquaredError(newPos, posLabels);
return crossEntropy.mean().add(posError);
// return posError;
});
}
function createModel() {
// model = tf.sequential();
// model.add(tf.layers.conv2d({
// inputShape: [null, null, 1],
// filters: 16,
// kernelSize: 7,
// activation: "relu",
// padding: "same"
// }));
// model.add(tf.layers.conv2d({
// filters: 16,
// kernelSize: 3,
// activation: "relu",
// padding: "same"
// }));
// model.add(tf.layers.conv2d({
// filters: 5,
// kernelSize: 1,
// padding: "same"
// }));
// model.add(new Classify());
const inputs = tf.input({ shape: [null, null, 1]});
const architecture = [8, 16];
let layer = inputs;
const layers = [];
for(let i = 0; i < architecture.length; i += 1) {
layer = tf.layers.conv2d({
filters: architecture[i],
kernelSize: 3,
activation: "relu",
padding: "same"
}).apply(layer);
layer = tf.layers.dropout({ rate: 0.1 }).apply(layer);
layer = tf.layers.conv2d({
filters: architecture[i],
kernelSize: 3,
activation: "relu",
padding: "same"
}).apply(layer);
layers.push(layer);
layer = tf.layers.batchNormalization().apply(layer);
layer = tf.layers.reLU().apply(layer);
layer = tf.layers.maxPooling2d({ poolSize: 2 }).apply(layer);
}
layer = tf.layers.conv2d({
filters: 32,
kernelSize: 3,
activation: "relu",
padding: "same"
}).apply(layer);
layer = tf.layers.batchNormalization().apply(layer);
layer = tf.layers.reLU().apply(layer);
layer = tf.layers.dropout({ rate: 0.1 }).apply(layer);
layer = tf.layers.conv2d({
filters: 32,
kernelSize: 3,
activation: "relu",
padding: "same"
}).apply(layer);
for(let i = architecture.length - 1; i >= 0; i -= 1) {
layer = tf.layers.conv2dTranspose({
filters: architecture[i],
kernelSize: 2,
strides: 2,
padding: "same"
}).apply(layer);
layer = new Skip().apply([layers[i], layer]);
// layer = tf.layers.concatenate().apply([layer, layers[i]]);
layer = tf.layers.batchNormalization().apply(layer);
layer = tf.layers.reLU().apply(layer);
}
layer = tf.layers.conv2d({
filters: 5,
kernelSize: 1,
padding: "same"
}).apply(layer);
const outputs = new Classify().apply(layer);
model = tf.model({ inputs, outputs });
return model;
}
var model = createModel();
function makeIteratorMaker(batchSize) {
let batchNum = 0;
return function() {
return {
next: () => {
return tf.tidy(() => {
const xs = [], ys = [];
for(let i = 0; i < batchSize; i += 1) {
[x, y] = sample();
xs.push(x);
ys.push(y);
}
console.log("batch generated");
[testImage, testMask] = sample();
test();
return { value: { xs: tf.stack(xs), ys: tf.stack(ys) }, done: false };
});
}
};
};
}
var num = 0;
function train(batchesPerEpoch = +document.getElementById("batches").value, epochs = +document.getElementById("epochs").value, batchSize = +document.getElementById("batchSize").value) {
console.log("preparing data");
const dataset = tf.data.generator(makeIteratorMaker(batchSize));
console.log("train start");
const optimizer = tf.train.adam();
console.log("initalizing");
model.compile({
optimizer,
loss,
metrics: ["accuracy"]
});
console.log("compiled");
model.fitDataset(dataset, { batchesPerEpoch, epochs }).then(info => {
console.log("accuracy", info.history.acc);
optimizer.dispose();
const newNum = tf.memory().numTensors;
console.log(`${num} + ${newNum - num} = ${newNum}`);
num = newNum;
});
// return model.fit(images, masks, {
// epochs,
// batchSize,
// callbacks: {
// onBatchEnd: (batch, logs) => console.log("accuracy", logs.acc)
// }
// }).then(info => {
}
async function save() {
await model.save("downloads://text");
console.log("saved");
}
async function load() {
console.log("loading");
const newModel = await tf.loadLayersModel(tf.io.browserFiles([
document.getElementById("json").files[0],
document.getElementById("weights").files[0]
]));
for(let i = 0; i < newModel.layers.length; i += 1) {
// for(let i = 0; i < 26; i += 1) {
model.layers[i].setWeights(newModel.layers[i].getWeights());
}
newModel.dispose();
console.log("loaded");
}
// document.addEventListener("DOMContentLoaded", async function () {
// // Load and preprocess the MNIST dataset
// const dataset = await tf.data.mnist();
// const trainData = dataset.trainImages.reshape([-1, 28, 28, 1]);
// const testData = dataset.testImages.reshape([-1, 28, 28, 1]);
// const trainLabels = tf.oneHot(dataset.trainLabels, 10);
// const testLabels = tf.oneHot(dataset.testLabels, 10);
// // Build the fully convolutional neural network (FCNN) model
// const model = tf.sequential();
// model.add(tf.layers.conv2d({
// inputShape: [28, 28, 1],
// filters: 32,
// kernelSize: 3,
// activation: 'relu'
// }));
// model.add(tf.layers.maxPooling2d({ poolSize: 2, strides: 2 }));
// model.add(tf.layers.flatten());
// model.add(tf.layers.dense({ units: 128, activation: 'relu' }));
// model.add(tf.layers.dense({ units: 10, activation: 'softmax' }));
// // Compile the model
// model.compile({
// optimizer: 'adam',
// loss: 'categoricalCrossentropy',
// metrics: ['accuracy']
// });
// // Train the model
// await model.fit(trainData, trainLabels, {
// epochs: 5,
// batchSize: 64,
// validationData: [testData, testLabels]
// });
// // Evaluate the model
// const evalResult = await model.evaluate(testData, testLabels);
// console.log('Evaluation Result:', evalResult);
// // Perform inference on a sample image
// const inferenceResult = model.predict(testData.slice([0, 0, 0, 0], [1, 28, 28, 1]));
// const predictedClass = inferenceResult.argMax(1).dataSync()[0];
// console.log('Predicted Class:', predictedClass);
// }); |
package com.kosa.shop.domain.entity;
import com.kosa.shop.constant.Role;
import com.kosa.shop.dto.MemberFormDto;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.persistence.*;
@Entity
@Table(name = "members") // 테이블 이름을 복수형으로(책과 다름)
@Getter
@Setter
@ToString
public class Member extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@Column(unique = true)
private String email;
private String password;
private String address;
@Enumerated(EnumType.STRING)
private Role role;
public static @NotNull Member createMember(@NotNull MemberFormDto memberFormDto,
@NotNull PasswordEncoder passwordEncoder) {
var member = new Member();
member.setName(memberFormDto.getName());
member.setEmail(memberFormDto.getEmail());
member.setAddress(member.getAddress());
var password = passwordEncoder.encode(memberFormDto.getPassword());
member.setPassword(password);
member.setRole(Role.ADMIN);
return member;
}
} |
package domain.car;
import java.util.List;
import domain.assembly_line.TaskType;
/**
* TruckModel is a subclass of Model that represents models of trucks.
*
* @author Thomas Vochten
*
*/
public class TruckModel extends Model {
/**
* Initialise a TruckModel with the specified name, option categories,
* default expected amount of minutes on a work post, expected amount
* of minutes on the body post and expected amount of minutes on the
* certification post
*
* @param modelName
* The name of the new TruckModel.
* @param optionCategories
* The option categories of the new TruckModel.
* @param minsPerWorkPost
* The default amount of minutes trucks of this TruckModel are expected to
* spend on a work post.
* @param minsOnBodyPost
* The amount of minutes trucks of this TruckModel are expected to
* spend on the body post.
* @param minsOnCertificationPost
* The amount of minutes trucks of this TruckModel are expected to
* spend on the certification post.
*/
public TruckModel(String modelName, List<OptionCategory> optionCategories,
int minsPerWorkPost, int minsOnBodyPost, int minsOnCertificationPost) {
super(modelName, optionCategories, minsPerWorkPost);
this.minsOnBodyPost = minsOnBodyPost;
this.minsOnCertificationPost = minsOnCertificationPost;
}
/** The amount of minutes trucks of this TruckModel are expected
* to spend on the body post. */
private final int minsOnBodyPost;
/** Get the amount of minutes trucks of this TruckModel are expected to
* spend on the body post. */
private int getMinsOnBodyPost() {
return this.minsOnBodyPost;
}
/** The amount of minutes trucks of this TruckModel are expected
* to spend on the certification post. */
private final int minsOnCertificationPost;
/** Get the amount of minutes trucks of this TruckModel are expected to
* spend on the certification post. */
private int getMinsOnCertificationPost() {
return this.minsOnCertificationPost;
}
@Override
public int getMinsOnWorkPostOfType(TaskType workPostType) {
switch(workPostType) {
case BODY:
return this.getMinsOnBodyPost();
case CERTIFICATION:
return this.getMinsOnCertificationPost();
default:
return super.getMinsPerWorkPost();
}
}
} |
package com.example.passwordmanager.validator;
import com.example.passwordmanager.exception.ExceptionMessages;
import com.example.passwordmanager.exception.RegisterException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.regex.Pattern;
@Component
@Slf4j
@RequiredArgsConstructor
public class EmailValidator {
private static final String RFC_EMAIL_REGEX = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$";
private static final String TOP_LEVEL_DOMAIN_EMAIL_REGEX = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
private static final String DOTS_EMAIL_REGEX = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+(?:\\.[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+)*@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$";
private static final String OWASP_EMAIL_REGEX = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
private static final List<String> regexes = List.of(
RFC_EMAIL_REGEX, TOP_LEVEL_DOMAIN_EMAIL_REGEX, DOTS_EMAIL_REGEX, OWASP_EMAIL_REGEX);
public void validate(String email) throws RegisterException {
if (regexes.stream().anyMatch(regex -> !Pattern.compile(regex).matcher(email).matches())) {
log.info("Invalid registration with email: " + email);
throw new RegisterException(ExceptionMessages.getEmailInvalidMsg(email));
}
}
} |
<div class="wrapper">
<%= render "shared/header" %>
<div class="side-bar">
<%= render "shared/side_bar" %>
</div>
<div class="main">
<h2>Sign up</h2>
<%= form_with model: @user, url: user_registration_path, id: 'new_user', class: 'new_user', local: true do |f| %>
<%= render "devise/shared/error_messages", resource: resource %>
<div class="field">
<%= f.label :nickname %> <em>(6 characters maximum)</em><br />
<%= f.text_field :nickname, autofocus: true, maxlength: "6" %>
</div>
<div class="field">
<%= f.label :game_name %><br />
<%= f.text_field :game_name, autofocus: true %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email %>
</div>
<div class="field">
<%= f.label :password %>
<% if @minimum_password_length %>
<em>(<%= @minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "off" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "off" %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
</div>
<%= render "shared/footer" %>
</div> |
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPC_SRC_CORE_LIB_EVENT_ENGINE_THREAD_POOL_H
#define GRPC_SRC_CORE_LIB_EVENT_ENGINE_THREAD_POOL_H
#include <grpc/support/port_platform.h>
#include <stdint.h>
#include <atomic>
#include <memory>
#include <queue>
#include "y_absl/base/thread_annotations.h"
#include "y_absl/functional/any_invocable.h"
#include <grpc/event_engine/event_engine.h>
#include <grpc/support/cpu.h>
#include "src/core/lib/event_engine/executor/executor.h"
#include "src/core/lib/event_engine/forkable.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/sync.h"
namespace grpc_event_engine {
namespace experimental {
class ThreadPool final : public Forkable, public Executor {
public:
ThreadPool();
// Asserts Quiesce was called.
~ThreadPool() override;
void Quiesce();
// Run must not be called after Quiesce completes
void Run(y_absl::AnyInvocable<void()> callback) override;
void Run(EventEngine::Closure* closure) override;
// Forkable
// Ensures that the thread pool is empty before forking.
void PrepareFork() override;
void PostforkParent() override;
void PostforkChild() override;
// Returns true if the current thread is a thread pool thread.
static bool IsThreadPoolThread();
// Set the maximum numbers of treads for threadpool
static size_t SetThreadsLimit(size_t count);
private:
class Queue {
public:
explicit Queue(unsigned reserve_threads)
: reserve_threads_(reserve_threads) {}
bool Step();
// Add a callback to the queue.
// Return true if we should also spin up a new thread.
bool Add(y_absl::AnyInvocable<void()> callback);
void SetShutdown(bool is_shutdown);
void SetForking(bool is_forking);
bool IsBacklogged();
void SleepIfRunning();
private:
const unsigned reserve_threads_;
grpc_core::Mutex queue_mu_;
grpc_core::CondVar cv_;
std::queue<y_absl::AnyInvocable<void()>> callbacks_
Y_ABSL_GUARDED_BY(queue_mu_);
unsigned threads_waiting_ Y_ABSL_GUARDED_BY(queue_mu_) = 0;
// Track shutdown and fork bits separately.
// It's possible for a ThreadPool to initiate shut down while fork handlers
// are running, and similarly possible for a fork event to occur during
// shutdown.
bool shutdown_ Y_ABSL_GUARDED_BY(queue_mu_) = false;
bool forking_ Y_ABSL_GUARDED_BY(queue_mu_) = false;
};
class ThreadCount {
public:
void Add();
void Remove();
void BlockUntilThreadCount(int threads, const char* why);
private:
grpc_core::Mutex thread_count_mu_;
grpc_core::CondVar cv_;
int threads_ Y_ABSL_GUARDED_BY(thread_count_mu_) = 0;
};
struct State {
explicit State(int reserve_threads) : queue(reserve_threads) {}
Queue queue;
ThreadCount thread_count;
// After pool creation we use this to rate limit creation of threads to one
// at a time.
std::atomic<bool> currently_starting_one_thread{false};
std::atomic<uint64_t> last_started_thread{0};
};
using StatePtr = std::shared_ptr<State>;
enum class StartThreadReason {
kInitialPool,
kNoWaitersWhenScheduling,
kNoWaitersWhenFinishedStarting,
};
static void ThreadFunc(StatePtr state);
// Start a new thread; throttled indicates whether the State::starting_thread
// variable is being used to throttle this threads creation against others or
// not: at thread pool startup we start several threads concurrently, but
// after that we only start one at a time.
static void StartThread(StatePtr state, StartThreadReason reason);
void Postfork();
unsigned GetMaxSystemThread();
const unsigned reserve_threads_ = GetMaxSystemThread();
const StatePtr state_ = std::make_shared<State>(reserve_threads_);
std::atomic<bool> quiesced_{false};
};
} // namespace experimental
} // namespace grpc_event_engine
#endif // GRPC_SRC_CORE_LIB_EVENT_ENGINE_THREAD_POOL_H |
import {
AnyAction,
createAsyncThunk,
createSlice,
PayloadAction,
} from "@reduxjs/toolkit";
import { AuthWot } from "api/actions/auth_wot";
import { Wot } from "api/actions/wot";
import { RootState } from "app/store";
import { logOutUser } from "helpers/user";
import { ClanResponseInterface } from "interfaces/response/ClanResponseInterface";
import { ClansListResponseInterface } from "interfaces/response/ClansListResponseInterface";
import { ExpectedResponseInterface } from "interfaces/response/ExpectedResponseInterface";
import { LoggedUserResponseInterface } from "interfaces/response/LoggedUserResponseInterface";
import { MapGeneratorResponseInterface } from "interfaces/response/MapGeneratorResponseInterface";
import { MapsListResponseInterface } from "interfaces/response/MapsListResponseInterface";
import { MoeResponseInterface } from "interfaces/response/MoeResponseInterface";
import { PlayerResponseInterface } from "interfaces/response/PlayerResponseInterface";
import { PlayersListResponseInterface } from "interfaces/response/PlayersListResponseInterface";
import { PlayerTanksResponseInterface } from "interfaces/response/PlayerTanksResponseInterface";
import { TankResponseInterface } from "interfaces/response/TankResponseInterface";
import { TanksResponseInterface } from "interfaces/response/TanksResponseInterface";
type SliceState = {
loading: false | true;
error: false | true;
not_found: false | true;
crash: false | true;
unauthorized: false | true;
maps_list: MapsListResponseInterface | null;
map_generator: MapGeneratorResponseInterface | null;
search_clan: ClanResponseInterface | null;
get_user: LoggedUserResponseInterface | null;
search_player: PlayerResponseInterface | null;
clans_list: ClansListResponseInterface | null;
search_players: PlayersListResponseInterface | null;
exp_wn8_list: ExpectedResponseInterface | null;
moe_list: MoeResponseInterface | null;
search_tank: TankResponseInterface | null;
tanks: TanksResponseInterface | null;
user_tanks: PlayerTanksResponseInterface | null;
players_list: [];
user_tanks_achievements: [];
games: [];
game: {};
};
const initialState: SliceState = {
loading: false,
error: false,
not_found: false,
crash: false,
unauthorized: false,
maps_list: null,
map_generator: null,
search_clan: null,
get_user: null,
search_player: null,
clans_list: null,
search_players: null,
exp_wn8_list: null,
moe_list: null,
search_tank: null,
tanks: null,
user_tanks: null,
players_list: [],
user_tanks_achievements: [],
user_tanks: {},
maps_guess: [],
games: [],
game: {},
};
const ignoring = [
"wot/get_user/fulfilled",
"wot/get_user/pending",
"wot/get_user/rejected",
"wot/map_guess/pending",
"wot/map_guess/fulfilled",
];
const ignoring404 = ["wot/map_guess/rejected"];
function isPendingAction(action: AnyAction) {
if (ignoring.includes(action?.type)) return false;
return action.type.endsWith("pending");
}
function isUnauthorizedAction(action: AnyAction) {
return action.type.endsWith("rejected") && action?.payload?.status === 401;
}
function isRejectedErrorAction(action: AnyAction) {
if (ignoring.includes(action?.type)) return false;
return (
action.type.endsWith("rejected") &&
![404, 500].includes(action?.payload?.status)
);
}
function isRejectedNotFoundAction(action: AnyAction) {
if (ignoring404.includes(action?.type)) return false;
return action.type.endsWith("rejected") && action?.payload?.status === 404;
}
function isCrashedAction(action: AnyAction) {
if (ignoring.includes(action?.type)) return false;
return action.type.endsWith("rejected") && action?.payload?.status === 500;
}
function isFulfilledAction(action: AnyAction) {
if (ignoring.includes(action?.type)) return false;
return action.type.endsWith("fulfilled");
}
export const handleRejectValues = (name: string, action: any) =>
createAsyncThunk(
name,
async (data: object | undefined, { rejectWithValue }) => {
try {
return await action(data);
} catch (error) {
const response = error.response;
return rejectWithValue({
status: response.status,
statusText: response.statusText,
});
}
}
);
export const searchPlayer = handleRejectValues(
"wot/search_player",
Wot.search_player
);
export const searchPlayerById = handleRejectValues(
"wot/search_player_by_id",
Wot.search_player_by_id
);
export const loadMaps = handleRejectValues("wot/load_maps", Wot.load_maps);
export const loadMapGenerator = handleRejectValues(
"wot/map_generator",
Wot.map_generator
);
export const searchClan = handleRejectValues(
"wot/search_clan",
Wot.search_clan
);
export const searchTank = handleRejectValues(
"wot/search_tank",
Wot.search_tank
);
export const userTanksAchievements = handleRejectValues(
"wot/user_tanks_achievements",
Wot.user_tanks_achievements
);
export const clansList = handleRejectValues("wot/clans_list", Wot.clans);
export const expWn8List = handleRejectValues("wot/wn8", Wot.exp_wn8);
export const moeList = handleRejectValues("wot/moe", Wot.moe);
export const guessList = handleRejectValues("wot/map_guess", Wot.map_guess);
export const loadTanks = handleRejectValues("wot/tanks", Wot.tanks);
export const getUser = handleRejectValues("wot/get_user", AuthWot.get_user);
export const fetchUserTanks = handleRejectValues(
"wot/user_tanks",
AuthWot.user_tanks
);
export const wotSlice = createSlice({
name: "wot",
initialState,
reducers: {
setError: (state, action) => {
state.error = action.payload;
},
clearSearchPlayer: (state: RootState) => {
state.search_player = null;
},
clearSearchPlayers: (state: RootState) => {
state.search_players = null;
},
clearPlayerTanks: (state: RootState) => {
state.user_tanks = {};
},
setGameParam: (state, action) => {
state.game = Object.assign({}, state.game, action.payload);
},
},
extraReducers: (builder) => {
builder
.addCase(
getUser.fulfilled,
(state, action: PayloadAction<LoggedUserResponseInterface>) => {
state.get_user = action.payload;
}
)
/********************************************************
*/
.addCase(loadMaps.pending, (state: RootState) => {
state.maps_list = null;
})
.addCase(
loadMaps.fulfilled,
(state, action: PayloadAction<MapsListResponseInterface>) => {
state.maps_list = action.payload;
}
)
.addCase(guessList.fulfilled, (state, action) => {
state.maps_guess = action.payload;
})
.addCase(loadMapGenerator.pending, (state: RootState) => {
state.map_generator = null;
})
.addCase(
loadMapGenerator.fulfilled,
(state, action: PayloadAction<MapGeneratorResponseInterface>) => {
state.map_generator = action.payload;
}
)
.addCase(searchTank.pending, (state: RootState) => {
state.search_tank = {};
})
.addCase(
searchTank.fulfilled,
(state, action: PayloadAction<TankResponseInterface>) => {
state.search_tank = action.payload;
}
)
.addCase(fetchUserTanks.pending, (state: RootState) => {
state.user_tanks = {};
})
.addCase(
fetchUserTanks.fulfilled,
(state, action: PayloadAction<PlayerTanksResponseInterface>) => {
state.user_tanks = action.payload;
}
)
.addCase(loadTanks.pending, (stateRootState) => {
state.tanks = [];
})
.addCase(
loadTanks.fulfilled,
(state, action: PayloadAction<TanksResponseInterface>) => {
state.tanks = action.payload;
}
)
.addCase(searchPlayer.pending, (state: RootState) => {
state.search_players = null;
})
.addCase(
searchPlayer.fulfilled,
(state, action: PayloadAction<PlayersListResponseInterface>) => {
state.search_players = action.payload;
}
)
.addCase(expWn8List.pending, (state: RootState) => {
state.exp_wn8_list = [];
})
.addCase(
expWn8List.fulfilled,
(state, action: PayloadAction<ExpectedResponseInterface>) => {
state.exp_wn8_list = action.payload;
}
)
.addCase(moeList.pending, (state: RootState) => {
state.moe_list = [];
})
.addCase(
moeList.fulfilled,
(state, action: PayloadAction<MoeResponseInterface>) => {
state.moe_list = action.payload;
}
)
.addCase(searchPlayerById.pending, (state: RootState) => {
state.search_player = null;
})
.addCase(
searchPlayerById.fulfilled,
(state, action: PayloadAction<PlayerResponseInterface>) => {
state.search_player = action.payload;
}
)
.addCase(searchClan.pending, (state: RootState) => {
state.search_clan = null;
})
.addCase(
searchClan.fulfilled,
(state, action: PayloadAction<ClanResponseInterface>) => {
state.search_clan = action.payload;
}
)
.addCase(userTanksAchievements.pending, (state: RootState) => {
state.user_tanks_achievements = [];
})
.addCase(userTanksAchievements.fulfilled, (state, action) => {
state.user_tanks_achievements = action.payload;
})
.addCase(
clansList.fulfilled,
(state, action: PayloadAction<ClansListResponseInterface>) => {
state.clans_list = action.payload;
}
)
.addMatcher(isRejectedErrorAction, (state: RootState) => {
state.error = true;
state.loading = false;
state.not_found = false;
state.crash = false;
state.unauthorized = false;
})
.addMatcher(isPendingAction, (state: RootState) => {
state.loading = true;
state.not_found = false;
state.error = false;
state.crash = false;
state.unauthorized = false;
})
.addMatcher(isFulfilledAction, (state: RootState) => {
state.loading = false;
state.not_found = false;
state.error = false;
state.crash = false;
state.unauthorized = false;
})
.addMatcher(isUnauthorizedAction, (state: RootState) => {
state.loading = false;
state.not_found = false;
state.error = false;
state.crash = false;
state.unauthorized = true;
logOutUser();
})
.addMatcher(isRejectedNotFoundAction, (state: RootState) => {
state.loading = false;
state.not_found = true;
state.error = false;
state.crash = false;
state.unauthorized = false;
})
.addMatcher(isCrashedAction, (state: RootState) => {
state.loading = false;
state.not_found = false;
state.error = false;
state.crash = true;
state.unauthorized = false;
});
},
});
export const {
setError,
clearSearchPlayer,
clearSearchPlayers,
clearPlayerTanks,
setGameParam,
} = wotSlice.actions;
export const selectLoadMaps = (state: RootState) => state.wot.maps_list;
export const selectMapGenerator = (state: RootState) => state.wot.map_generator;
export const selectSearchPlayer = (state: RootState) => state.wot.search_player;
export const selectSearchPlayers = (state: RootState) =>
state.wot.search_players;
export const selectSearchClan = (state: RootState) => state.wot.search_clan;
export const selectSearchTank = (state: RootState) => state.wot.search_tank;
export const selectUserTanks = (state: RootState) => state.wot.user_tanks;
export const selectUserTanksAchievements = (state: RootState) =>
state.wot.user_tanks_achievements;
export const selectClansList = (state: RootState) => state.wot.clans_list;
export const selectTanks = (state: RootState) => state.wot.tanks;
export const selectUser = (state: RootState) => state.wot.get_user;
export const selectLoadMaps = (state: RootState) => state.wot.maps_list;
export const selectMapGenerator = (state: RootState) => state.wot.map_generator;
export const selectExpWn8List = (state: RootState) => state.wot.exp_wn8_list;
export const selectMoeList = (state: RootState) => state.wot.moe_list;
export const selectMapGuess = (state: RootState) => state.wot.maps_guess;
export const selectGameItem = (state: RootState) => state.wot.game || {};
export const selectLoading = (state: RootState) => state.wot.loading;
export const selectError = (state: RootState) => state.wot.error;
export const selectNotFound = (state: RootState) => state.wot.not_found;
export const selectCrash = (state: RootState) => state.wot.crash;
export const selectUnauthorized = (state: RootState) => state.wot.unauthorized;
export default wotSlice.reducer; |
import React, { useState } from "react";
import { View, StyleSheet, Text, TouchableOpacity, Button } from "react-native";
import { TextInput } from "../components";
import DropDownPicker from 'react-native-dropdown-picker';
import { Formik } from 'formik';
import { db } from "../config/firebase";
import { collection, addDoc } from "firebase/firestore";
import { Footer } from '../components/Footer';
import { Header } from '../components/Header';
import { Colors } from "../config";
export const AddItemScreen = ({ navigation }) => {
const [open1, setOpen1] = useState(false);
const [type, setType] = useState('');
const [types, initializeTypes] = useState([
{label: 'Chair', value: 'chair'},
{label: 'Couch', value: 'couch'},
{label: 'Table', value: 'table'},
{label: 'Desk', value: 'desk'},
{label: 'Coffee Table', value: 'coffee_table'},
{label: 'Lamp', value: 'lamp'},
]);
const [open2, setOpen2] = useState(false);
const [material, setMaterial] = useState('');
const [materials, initMaterials] = useState([
{label: 'Wood', value: 'wood'},
{label: 'Plastic', value: 'plastic'},
{label: 'Metal', value: 'metal'},
{label: 'Glass', value: 'glass'},
]);
const [open4, setOpen4] = useState(false);
const [color, setColor] = useState('');
const [colors, initColors] = useState([
{label: 'Red', value: 'red'},
{label: 'Orange', value: 'orange'},
{label: 'Yellow', value: 'yellow'},
{label: 'Green', value: 'green'},
{label: 'Blue', value: 'blue'},
{label: 'Violet', value: 'violet'},
{label: 'Black', value: 'black'},
{label: 'White', value: 'white'}
]);
const handleAddItem = async (values) => {
const { type, material, custom, length, width, height, color } = values;
// console.log(`type: ${type}, material: ${material}, custom: ${custom}, length: ${length}, width: ${width}, height: ${height}, color: ${color}`);
try {
const docRef = await addDoc(collection(db, "furniture"), {
type: type,
material: material,
custom_field: custom,
length: length,
width: width,
height: height,
color: color
});
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}
};
return (
<View style={styles.container}>
<Header />
<Formik
initialValues={{ type: '', material1: '', custom: '', length: '', width: '', height: ''}}
onSubmit={values => handleAddItem(values)}
>
{({ handleChange, handleBlur, handleSubmit, setFieldValue, values, touched, errors }) => (
<>
<View style={styles.dropdownRow}>
<DropDownPicker
open={open1}
value={type}
items={types}
setOpen={setOpen1}
setValue={setType}
setItems={initializeTypes}
onChangeValue={item => setFieldValue('type', item)}
placeholder="Type"
style={{width: '95%'}}
maxHeight={150}
zIndex={3000}
zIndexInverse={1000}
/>
<DropDownPicker
open={open2}
value={material}
items={materials}
setOpen={setOpen2}
setValue={setMaterial}
setItems={initMaterials}
onChangeValue={item => setFieldValue('material', item)}
placeholder="Material"
style={{width: '95%'}}
maxHeight={150}
zIndex={2500}
zIndexInverse={2500}
/>
</View>
{ (open1 || open2) ? (
<View style={{paddingTop:140}}>
<View style={styles.textRow}>
<TextInput
placeholder="Length"
value={values.length}
onChangeText={item => setFieldValue('length', item)}
width={'49%'}
/>
<TextInput
placeholder="Width"
value={values.width}
onChangeText={item => setFieldValue('width', item)}
width={'49%'}
/>
</View>
<View style={styles.textRow}>
<TextInput
placeholder="Height"
value={values.height}
onChangeText={item => setFieldValue('height', item)}
width={'49%'}
/>
<TextInput
placeholder="Custom Field"
value={values.custom}
onChangeText={item => setFieldValue('custom', item)}
width={'49%'}
/>
</View>
<DropDownPicker
open={open4}
value={color}
items={colors}
setOpen={setOpen4}
setValue={setColor}
setItems={initColors}
onChangeValue={item => setFieldValue('color', item)}
placeholder="Color"
style={{width: '95%'}}
maxHeight={150}
/>
<Button title="Submit" onPress={handleSubmit} />
</View>
) : (
<>
<View style={styles.textRow}>
<TextInput
placeholder="Length"
value={values.length}
onChangeText={item => setFieldValue('length', item)}
width={'49%'}
/>
<TextInput
placeholder="Width"
value={values.width}
onChangeText={item => setFieldValue('width', item)}
width={'49%'}
/>
</View>
<View style={styles.textRow}>
<TextInput
placeholder="Height"
value={values.height}
onChangeText={item => setFieldValue('height', item)}
width={'49%'}
/>
<TextInput
placeholder="Custom Field"
value={values.custom}
onChangeText={item => setFieldValue('custom', item)}
width={'49%'}
/>
</View>
<DropDownPicker
open={open4}
value={color}
items={colors}
setOpen={setOpen4}
setValue={setColor}
setItems={initColors}
onChangeValue={item => setFieldValue('color', item)}
placeholder="Color"
maxHeight={150}
zIndex={1000}
zIndexInverse={3000}
/>
<Button title="Submit" onPress={handleSubmit} />
</>
)
}
</>
)}
</Formik>
<Footer />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
paddingVertical: 72,
backgroundColor: Colors.white,
paddingHorizontal: 12,
},
dropdownRow: {
flexDirection: 'row',
width:'51%',
justifyContent: 'space-between',
marginBottom:16
},
textRow: {
flexDirection: 'row',
width:'100%',
justifyContent: 'space-between',
}
}); |
//
// AudioViewController.swift
// TersarZoe
//
// Created by Manjunath Ramesh on 22/11/20.
//
import UIKit
import SVProgressHUD
class AudioViewController: BaseViewController {
@IBOutlet weak var collectionView: UICollectionView!
var audioCategoryArray:[MainSubCategory] = []
var selectedSubCatID = 0
var selectedPageTitle = ""
override func viewDidLoad() {
super.viewDidLoad()
configureNavBar()
collectionView.register(UINib(nibName: "AudioCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "AudioCell")
collectionView.backgroundColor = ColorConstants.appBgColor
if hasNetworkConnection() {
fetchAudioCategories()
} else {
super.showNoInternetConnectionAlert()
}
}
private func configureNavBar() {
navigationController?.navigationBar.barTintColor = ColorConstants.navBarColor
navigationItem.title = "MP3 Teaching"
let button = UIButton(type: .custom)
button.setImage(UIImage (named: "More"), for: .normal)
button.frame = CGRect(x: 0.0, y: 0.0, width: 35.0, height: 35.0)
button.addTarget(self, action: #selector(moreBtnTapped), for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: button)
//navigationItem.rightBarButtonItem = barButtonItem
let searchButton = UIButton(type: .custom)
searchButton.setImage(UIImage (named: "Search"), for: .normal)
searchButton.frame = CGRect(x: 0.0, y: 0.0, width: 35.0, height: 35.0)
searchButton.addTarget(self, action: #selector(searchBtnTapped), for: .touchUpInside)
let searchbarButtonItem = UIBarButtonItem(customView: searchButton)
navigationItem.rightBarButtonItems = [barButtonItem, searchbarButtonItem]
}
private func fetchAudioCategories() {
SVProgressHUD.showInfo(withStatus: "Fetching...")
NetworkManager.shared.getSubCategoriesFor(categoryID: AppConstants.audioCategoryID) {[weak self] (status, audioCategories) in
SVProgressHUD.dismiss()
if status && !audioCategories.isEmpty {
print("Number of audio Category: \(audioCategories.count)")
DispatchQueue.main.async {
CoreDataManger.shared.saveMainSubCategories(subCategories: audioCategories)
self?.audioCategoryArray = CoreDataManger.shared.fetchMainSubCategories()
self?.collectionView.reloadData()
}
}
}
}
@objc
func moreBtnTapped() {
self.performSegue(withIdentifier: "AudioSettings", sender: self)
}
@objc
func searchBtnTapped() {
self.performSegue(withIdentifier: "ShowAudioSearch", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowAudio" {
if let nextViewController = segue.destination as? CommonCollectionViewController {
nextViewController.contentType = .audio
nextViewController.subCategoryId = selectedSubCatID
nextViewController.pageTitle = selectedPageTitle
}
} else if segue.identifier == "ShowAudioSearch" {
if let nextViewController = segue.destination as? SearchViewController {
nextViewController.categoryName = "Audio"
nextViewController.contentType = .audio
nextViewController.subCategoryList = audioCategoryArray
}
}
}
}
extension AudioViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return audioCategoryArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AudioCell", for: indexPath) as! AudioCollectionViewCell
cell.populateCell(sc: audioCategoryArray[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedSubCatID = audioCategoryArray[indexPath.row].id
selectedPageTitle = audioCategoryArray[indexPath.row].name
performSegue(withIdentifier: "ShowAudio", sender: nil)
}
}
extension AudioViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let flowayout = collectionViewLayout as? UICollectionViewFlowLayout
let space: CGFloat = (flowayout?.minimumInteritemSpacing ?? 0.0) + (flowayout?.sectionInset.left ?? 0.0) + (flowayout?.sectionInset.right ?? 0.0)
let size:CGFloat = (collectionView.frame.size.width - space) / 2.0
return CGSize(width: size, height: size)
}
} |
package com.nexters.dailyphrase.member.implement.factory;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.nexters.dailyphrase.common.enums.SocialType;
import com.nexters.dailyphrase.member.implement.SocialLoginService;
import com.nexters.dailyphrase.member.implement.strategy.SocialLoginStrategy;
@Component
public class SocialLoginServiceFactory {
private final Map<SocialType, SocialLoginService> contextMap;
@Autowired
public SocialLoginServiceFactory(List<SocialLoginStrategy> strategies) {
contextMap = new EnumMap<>(SocialType.class);
for (SocialLoginStrategy strategy : strategies) {
SocialType socialType = strategy.getSocialType();
contextMap.put(socialType, new SocialLoginService(strategy));
}
}
public SocialLoginService getServiceBySocialType(SocialType socialType) {
return contextMap.get(socialType);
}
} |
import os
import sys
import mmengine
import torch
import torch.nn as nn
from mmengine.device import get_device
from opencompass.registry import MM_MODELS
def load_package():
"""Load required packages from llama_adapter_v2_multimodal7b."""
current_file_path = os.path.abspath(__file__)
current_folder_path = os.path.dirname(current_file_path)
sys.path.append(os.path.join(current_folder_path, 'mPLUG-Owl')) # noqa
from mplug_owl.modeling_mplug_owl import MplugOwlForConditionalGeneration
from mplug_owl.processing_mplug_owl import (MplugOwlImageProcessor,
MplugOwlProcessor)
from mplug_owl.tokenization_mplug_owl import MplugOwlTokenizer
sys.path.pop(-1)
return MplugOwlForConditionalGeneration, MplugOwlImageProcessor, MplugOwlProcessor, MplugOwlTokenizer # noqa
MplugOwlForConditionalGeneration, MplugOwlImageProcessor, MplugOwlProcessor, MplugOwlTokenizer = load_package( # noqa
) # noqa
@MM_MODELS.register_module('mplug_owl_7b')
class MplugOwl(nn.Module):
def __init__(self,
prompt_constructor: dict,
post_processor: dict,
model_path='MAGAer13/mplug-owl-llama-7b',
mode: str = 'generation'):
super().__init__()
pretrained_ckpt = model_path
# import pdb;pdb.set_trace()
print(pretrained_ckpt)
self.model = MplugOwlForConditionalGeneration.from_pretrained(
pretrained_ckpt,
torch_dtype=torch.bfloat16,
).cuda()
self.image_processor = MplugOwlImageProcessor.from_pretrained(
pretrained_ckpt)
self.tokenizer = MplugOwlTokenizer.from_pretrained(pretrained_ckpt)
self.processor = MplugOwlProcessor(self.image_processor,
self.tokenizer)
self.generate_kwargs = {
'do_sample': False,
'top_k': 5,
'max_length': 20,
'num_beams': 3,
}
self.prompt_constructor = mmengine.registry.build_from_cfg(
prompt_constructor, MM_MODELS)
if post_processor is not None:
self.post_processor = mmengine.registry.build_from_cfg(
post_processor, MM_MODELS)
self.mode = mode
def forward(self, batch):
if self.mode == 'generation':
return self.generate(batch)
def generate(self, batch):
images = [image.unsqueeze(0) for image in batch['inputs']]
data_samples = [data_sample for data_sample in batch['data_samples']]
images = torch.cat(images, dim=0).to(get_device())
inputs = {'image': images, 'data_samples': data_samples}
inputs = self.prompt_constructor(inputs)
image = inputs['image']
prompt = inputs['prompt'][0]
data_samples = inputs['data_samples']
data_sample = data_samples[0]
owl_template = """The following is a conversation
between a curious human and AI assistant.
The assistant gives helpful, detailed, and
polite answers to the user's questions.
Human: <image>
Human: {text_input}
AI: """
prompt = owl_template.format(text_input=prompt)
inputs = self.processor(text=[prompt], return_tensors='pt')
inputs['pixel_values'] = image
# inputs['pixel_values'] = torch.zeros_like(samples['image'])
inputs = {
k: v.bfloat16() if v.dtype == torch.float else v
for k, v in inputs.items()
}
inputs = {k: v.to(self.model.device) for k, v in inputs.items()}
with torch.no_grad():
res = self.model.generate(**inputs, **self.generate_kwargs)
output_text = self.tokenizer.decode(res.tolist()[0],
skip_special_tokens=True)
output_text = self.post_processor(output_text)
data_sample.pred_answer = output_text
return data_sample |
import { Injectable } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { IPublisher, NewPublisher } from '../publisher.model';
/**
* A partial Type with required key is used as form input.
*/
type PartialWithRequiredKeyOf<T extends { id: unknown }> = Partial<Omit<T, 'id'>> & { id: T['id'] };
/**
* Type for createFormGroup and resetForm argument.
* It accepts IPublisher for edit and NewPublisherFormGroupInput for create.
*/
type PublisherFormGroupInput = IPublisher | PartialWithRequiredKeyOf<NewPublisher>;
type PublisherFormDefaults = Pick<NewPublisher, 'id'>;
type PublisherFormGroupContent = {
id: FormControl<IPublisher['id'] | NewPublisher['id']>;
name: FormControl<IPublisher['name']>;
};
export type PublisherFormGroup = FormGroup<PublisherFormGroupContent>;
@Injectable({ providedIn: 'root' })
export class PublisherFormService {
createPublisherFormGroup(publisher: PublisherFormGroupInput = { id: null }): PublisherFormGroup {
const publisherRawValue = {
...this.getFormDefaults(),
...publisher,
};
return new FormGroup<PublisherFormGroupContent>({
id: new FormControl(
{ value: publisherRawValue.id, disabled: true },
{
nonNullable: true,
validators: [Validators.required],
}
),
name: new FormControl(publisherRawValue.name, {
validators: [Validators.required, Validators.maxLength(100)],
}),
});
}
getPublisher(form: PublisherFormGroup): IPublisher | NewPublisher {
return form.getRawValue() as IPublisher | NewPublisher;
}
resetForm(form: PublisherFormGroup, publisher: PublisherFormGroupInput): void {
const publisherRawValue = { ...this.getFormDefaults(), ...publisher };
form.reset(
{
...publisherRawValue,
id: { value: publisherRawValue.id, disabled: true },
} as any /* cast to workaround https://github.com/angular/angular/issues/46458 */
);
}
private getFormDefaults(): PublisherFormDefaults {
return {
id: null,
};
}
} |
package com.entity.vo;
import com.entity.YishengChatEntity;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
/**
* 用户咨询
* 手机端接口返回实体辅助类
* (主要作用去除一些不必要的字段)
*/
@TableName("yisheng_chat")
public class YishengChatVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableField(value = "id")
private Integer id;
/**
* 提问人
*/
@TableField(value = "yonghu_id")
private Integer yonghuId;
/**
* 回答人
*/
@TableField(value = "yisheng_id")
private Integer yishengId;
/**
* 问题
*/
@TableField(value = "yisheng_chat_issue_text")
private String yishengChatIssueText;
/**
* 问题时间
*/
@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
@DateTimeFormat
@TableField(value = "issue_time")
private Date issueTime;
/**
* 回复
*/
@TableField(value = "yisheng_chat_reply_text")
private String yishengChatReplyText;
/**
* 回复时间
*/
@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
@DateTimeFormat
@TableField(value = "reply_time")
private Date replyTime;
/**
* 状态
*/
@TableField(value = "zhuangtai_types")
private Integer zhuangtaiTypes;
/**
* 数据类型
*/
@TableField(value = "yisheng_chat_types")
private Integer yishengChatTypes;
/**
* 提问时间
*/
@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
@DateTimeFormat
@TableField(value = "insert_time")
private Date insertTime;
/**
* 创建时间
*/
@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
@DateTimeFormat
@TableField(value = "create_time")
private Date createTime;
/**
* 设置:主键
*/
public Integer getId() {
return id;
}
/**
* 获取:主键
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 设置:提问人
*/
public Integer getYonghuId() {
return yonghuId;
}
/**
* 获取:提问人
*/
public void setYonghuId(Integer yonghuId) {
this.yonghuId = yonghuId;
}
/**
* 设置:回答人
*/
public Integer getYishengId() {
return yishengId;
}
/**
* 获取:回答人
*/
public void setYishengId(Integer yishengId) {
this.yishengId = yishengId;
}
/**
* 设置:问题
*/
public String getYishengChatIssueText() {
return yishengChatIssueText;
}
/**
* 获取:问题
*/
public void setYishengChatIssueText(String yishengChatIssueText) {
this.yishengChatIssueText = yishengChatIssueText;
}
/**
* 设置:问题时间
*/
public Date getIssueTime() {
return issueTime;
}
/**
* 获取:问题时间
*/
public void setIssueTime(Date issueTime) {
this.issueTime = issueTime;
}
/**
* 设置:回复
*/
public String getYishengChatReplyText() {
return yishengChatReplyText;
}
/**
* 获取:回复
*/
public void setYishengChatReplyText(String yishengChatReplyText) {
this.yishengChatReplyText = yishengChatReplyText;
}
/**
* 设置:回复时间
*/
public Date getReplyTime() {
return replyTime;
}
/**
* 获取:回复时间
*/
public void setReplyTime(Date replyTime) {
this.replyTime = replyTime;
}
/**
* 设置:状态
*/
public Integer getZhuangtaiTypes() {
return zhuangtaiTypes;
}
/**
* 获取:状态
*/
public void setZhuangtaiTypes(Integer zhuangtaiTypes) {
this.zhuangtaiTypes = zhuangtaiTypes;
}
/**
* 设置:数据类型
*/
public Integer getYishengChatTypes() {
return yishengChatTypes;
}
/**
* 获取:数据类型
*/
public void setYishengChatTypes(Integer yishengChatTypes) {
this.yishengChatTypes = yishengChatTypes;
}
/**
* 设置:提问时间
*/
public Date getInsertTime() {
return insertTime;
}
/**
* 获取:提问时间
*/
public void setInsertTime(Date insertTime) {
this.insertTime = insertTime;
}
/**
* 设置:创建时间
*/
public Date getCreateTime() {
return createTime;
}
/**
* 获取:创建时间
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
} |
<?php
namespace App\Http\Livewire\Petugas;
use App\Models\Motor as ModelsMotor;
use App\Models\Kategori;
use App\Models\Penerbit;
use App\Models\Rak;
use Livewire\Component;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
class Motor extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
use WithFileUploads;
public $create, $edit, $delete, $show;
public $kategori, $rak, $penerbit;
public $kategori_id, $rak_id, $penerbit_id, $baris;
public $judul, $stok, $produktor, $sampul, $motor_id, $search;
protected $rules = [
'judul' => 'required',
'produktor' => 'required',
'stok' => 'required|numeric|min:1',
'sampul' => 'required|image|max:1024',
'kategori_id' => 'required|numeric|min:1',
'rak_id' => 'required|numeric|min:1',
'penerbit_id' => 'required|numeric|min:1',
];
protected $validationAttributes = [
'kategori_id' => 'kategori',
'rak_id' => 'rak',
'penerbit_id' => 'penerbit',
];
public function pilihKategori()
{
$this->rak = Rak::where('kategori_id', $this->kategori_id)->get();
}
public function create()
{
$this->format();
$this->create = true;
$this->kategori = Kategori::all();
$this->penerbit = Penerbit::all();
}
public function store()
{
$this->validate();
$this->sampul = $this->sampul->store('motor', 'public');
ModelsMotor::create([
'sampul' => $this->sampul,
'judul' => $this->judul,
'produktor' => $this->produktor,
'stok' => $this->stok,
'kategori_id' => $this->kategori_id,
'rak_id' => $this->rak_id,
'penerbit_id' => $this->penerbit_id,
'slug' => Str::slug($this->judul)
]);
session()->flash('sukses', 'Data berhasil ditambahkan.');
$this->format();
}
public function show(ModelsMotor $motor)
{
$this->format();
$this->show = true;
$this->judul = $motor->judul;
$this->sampul = $motor->sampul;
$this->produktor = $motor->produktor;
$this->stok = $motor->stok;
$this->kategori = $motor->kategori->nama;
$this->penerbit = $motor->penerbit->nama;
$this->rak = $motor->rak->rak;
$this->baris = $motor->rak->baris;
}
public function edit(ModelsMotor $motor)
{
$this->format();
$this->edit = true;
$this->motor_id = $motor->id;
$this->judul = $motor->judul;
$this->produktor = $motor->produktor;
$this->stok = $motor->stok;
$this->kategori_id = $motor->kategori_id;
$this->rak_id = $motor->rak_id;
$this->penerbit_id = $motor->penerbit_id;
$this->kategori = Kategori::all();
$this->rak = Rak::where('kategori_id', $motor->kategori_id)->get();
$this->penerbit = Penerbit::all();
}
public function update(ModelsMotor $motor)
{
$validasi = [
'judul' => 'required',
'produktor' => 'required',
'stok' => 'required|numeric|min:1',
'kategori_id' => 'required|numeric|min:1',
'rak_id' => 'required|numeric|min:1',
'penerbit_id' => 'required|numeric|min:1',
];
if ($this->sampul) {
$validasi['sampul'] = 'required|image|max:1024';
}
$this->validate($validasi);
if ($this->sampul) {
Storage::disk('public')->delete($motor->sampul);
$this->sampul = $this->sampul->store('motor', 'public');
} else {
$this->sampul = $motor->sampul;
}
$motor->update([
'sampul' => $this->sampul,
'judul' => $this->judul,
'produktor' => $this->produktor,
'stok' => $this->stok,
'kategori_id' => $this->kategori_id,
'rak_id' => $this->rak_id,
'penerbit_id' => $this->penerbit_id,
'slug' => Str::slug($this->judul)
]);
session()->flash('sukses', 'Data berhasil diubah.');
$this->format();
}
public function delete(ModelsMotor $motor)
{
$this->format();
$this->delete = true;
$this->motor_id = $motor->id;
}
public function destroy(ModelsMotor $motor)
{
Storage::disk('public')->delete($motor->sampul);
$motor->delete();
session()->flash('sukses', 'Data berhasil dihapus.');
$this->format();
}
public function updatingSearch()
{
$this->resetPage();
}
public function render()
{
if ($this->search) {
$motor = ModelsMotor::latest()->where('judul', 'like', '%'. $this->search .'%')->paginate(5);
} else {
$motor = ModelsMotor::latest()->paginate(5);
}
return view('livewire.petugas.motor', compact('motor'));
}
public function format()
{
unset($this->create);
unset($this->delete);
unset($this->edit);
unset($this->show);
unset($this->motor_id);
unset($this->judul);
unset($this->sampul);
unset($this->stok);
unset($this->produktor);
unset($this->kategori);
unset($this->penerbit);
unset($this->rak);
unset($this->rak_id);
unset($this->penerbit_id);
unset($this->kategori_id);
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Estado, Mercado y Cultura han convertido a nuestros autores en líderes involuntarios de inofensivas endogamias. En TOKONOMA.lit no queremos seguidores, queremos críticos. Nos proponemos estimularlos y/o inventarlos.">
<meta name="keywords" content="escritura, lectura, poesía, crítica, ensayo, literatura, reseñas, talleres, revista">
<title>Home- TOKONOMA.lit</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<!--MI HOJA DE CSS -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
/>
<link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
<link rel="stylesheet" href="./CSS/Styles.css">
</head>
<body>
<!-- HEADER: section Logo & Menú -->
<header>
<nav class="navbar navbar-expand-lg bg-header-color">
<div class="container">
<a class="navbar-brand animate__animated animate__jackInTheBox" href="index.html"><img src="./images/titulo-sitio.png" alt="imagen que muestra el logo, que es una máquina de escribir, y título del sitio"></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse navbar-align" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" aria-current="page" href="index.html">Inicio</a>
</li>
<li class="nav-item">
<a class="nav-link" href="./page/manifiesto.html">Manifiesto</a>
</li>
<li class="nav-item">
<a class="nav-link" href="./page/revista.html">Revista</a>
<li class="nav-item">
<li class="nav-item">
<a class="nav-link" href="./page/talleres.html">Talleres</a>
<li class="nav-item">
<li class="nav-item">
<a class="nav-link" href="./page/eventos.html">Eventos</a>
<li class="nav-item">
<li class="nav-item">
<a class="nav-link" href="./page/contacto.html">Contacto</a>
<li class="nav-item">
</ul>
</div>
</div>
</nav>
</header>
<!-- FIN DE HEADER: section Logo & Menú -->
<!-- HOME, sección 1 -->
<main class="container container-general">
<section id="presentacion" class="container seccion-presentacion ">
<img class="imagen-presentacion container" src="./images/logo-completo.png" alt="logo de Tokonoma.lit, que es una máquina de escribir, junto al siguiente slogan: poesía, crítica y ensayo">
<div class="contenedor-texto-presentacion">
<p class="parrafo-citas"><em>La literatura, como todo ámbito comercial necesitaría una inyección de prejuicios, supersticiones, preferencias caprichosas, hostilidades arbitrarias. Porque sin prejuicios, casi no se puede pensar. Y sin enemigos, no se puede pensar. Y los enemigos pret-a porter que oferta el menú de los medios -y de la prensa cultural hecha de medios- son tan compartidos que sacan las ganas de pensar.</em></p>
<p class="parrafo-normal"><strong>TOKONOMA.lit</strong> toma estas palabras de Rodolfo Enrique Fogwill al pie de la letra. Se propone ser un espacio vincular, un intersticio, un <em>espacio entre espacios</em> del que surja (lo volvemos a citar): «mano de obra intelectual capacitada para obrar por instinto. Dotada de un sistema de prejuicios eficaz. Gente dispuesta a moverse colectivamente sola. Como verdaderos samurais, pero sin tanta aparatosidad y griteríos. Maradonas, pero con menos predisposición a engordar y sin Coppolas».</p>
</div>
<br>
</section>
<!-- HOME, sección 2 -->
<h1>VALORES</h1>
<div class="container text-justify">
<div class="row align-items-top">
<div class="col col-md-12 col-xl-4">
<div class="section-valores">
<div class="contenedor-imagen-seccion-valores">
<img class="imagenes_seccion_valores" data-aos="flip-left" data-aos-duration="1250" src="./images/objetivos.png" alt="imagen ilustrativa sobre los objetivos del sitio, utilizando el icono de una vacuna, dado que se hace alusión a un virus">
</div>
<p class="subtitulos">Objetivos</p>
<p class="parrafo-normal">Inyectar vitalidad a un campo literario adormecido por la conformidad, el algoritmo y la pereza intelectual. Discutir ideas, obras y modos de leer. Debatir las lecturas vigentes de obras, discursos y, por qué no, <em>la selva espesa de lo real</em>.</p>
</div>
</div>
<div class="col col-md-12 col-xl-4">
<div class="section-valores">
<div class="contenedor-imagen-seccion-valores">
<img class="imagenes_seccion_valores" data-aos="flip-left" data-aos-duration="1250" src="./images/mision.png" alt="imagen ilustrativa de la misión del sitio, en la que se ve una mano ofreciendo un libro">
</div>
<p class="subtitulos">Misión</p>
<p class="parrafo-normal">Generar un espacio dinámico que, a modo de laboratorio, sirva para formar pensamiento crítico orientado a la literatura y la cultura argentinas. Reivindicarlas como experiencias totales que, si dejaron de serlo, se debe a la atrofia de sus hacedores.</p>
</div>
</div>
<div class="col col-md-12 col-xl-4">
<div class="section-valores">
<div class="contenedor-imagen-seccion-valores">
<img class="imagenes_seccion_valores" data-aos="flip-left" data-aos-duration="1250" src="./images/vision.png" alt="imagen ilustrativa de la visión del sitio, en la que se ve un documento de texto con un gran ojo superpuesto encima">
</div>
<p class="subtitulos">Visión</p>
<p class="parrafo-normal">En un tiempo en que la IA amenaza con adueñarse de la industria del entretenimiento, es vital defender el estatuto del arte como experiencia humana. Fomentar la contemplación y la crítica (es decir: la lectura) es, hoy, una cuestión de supervivencia.</p>
</div>
</div>
</div>
</div>
<br>
<!-- HOME, sección 3 -->
<div class="container text-center">
<h2 class="h2-index">STAFF</h2>
<div class="row align-items-top">
<div class="col col-md-12 col-xl-6">
<div class="section-valores">
<div class="contenedor-section-staff">
<div class="contendor-imagen-section-staff"><img class="imagenes_seccion_staff" data-aos="fade-right" data-aos-duration="1250" src="./images/juan.jpg" alt="imagen de Juan Rochi, mirando a la cámara"></div>
<p class="subtitulos">Juan Rochi</p>
<p class="parrafo-normal">Licenciado en Filosofía por la UBA con un especial interés en la poesía argentina de los 90 (o en Martín Gambarotta). Defensor de la crítica auerbachiana y enraizado en los principios poéticos de Ezra Pound.</p>
</div>
</div>
</div>
<div class="col col-md-12 col-xl-6">
<div class="section-valores">
<div class="contenedor-section-staff">
<div class="contendor-imagen-section-staff"><img class="imagenes_seccion_staff" data-aos="fade-left" data-aos-duration="1250" src="./images/leandro.jpg" alt="imagen de Leandro Diego, mirando a cámara"></div>
<p class="subtitulos">Leandro Diego</p>
<p class="parrafo-normal">Periodista cultural y autor del poemario narrativo Monoimi (<em>AñosLuz</em>, 2020). Abomina de los edificios de ideas y defiende el pensamiento como una serie de premisas que no tienen por qué concluir nada.</p>
</div>
</div>
</div>
</div>
</div>
<br>
<!-- HOME, sección 4 -->
<section class="container container-carousel">
<h3 class="h3-index">NOVEDADES</h3>
<div id="carouselExampleCaptions" class="carousel slide">
<div class="carousel-indicators">
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button>
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3"></button>
</div>
<div class="carousel-inner">
<div class="carousel-item active">
<img src="./images/carousel-img-1.jpg" class="d-block w-100" alt="portada del libro Sangria, de martín Gambarotta">
<div class="carousel-caption d-none d-md-block">
<h4 class="h4-index">Sangría, de Martín Gambarotta</h4>
<p class="subtitulo-carrousel">Reseña de Carlos Maslatón.</p>
</div>
</div>
<div class="carousel-item">
<img src="./images/carousel-img-2.jpg" class="d-block w-100" alt="imagen de una mano escribiendo sobre el agua">
<div class="carousel-caption d-none d-md-block">
<h4 class="h4-index">Elogio de la pérdida</h4>
<p class="subtitulo-carrousel">Ensayo de Clorindo Testa</p>
</div>
</div>
<div class="carousel-item">
<img src="./images/carousel-img-3.jpg" class="d-block w-100" alt="portada de El ruido de una época, de Ariana Harwicz">
<div class="carousel-caption d-none d-md-block">
<h4 class="h4-index">El ruido de una época, de Ariana Harwicz</h4>
<p class="subtitulo-carrousel">Reseña de Richard Coleman</p>
</div>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
<br>
</div>
</section>
</main>
<!-- FOOTER -->
<footer>
<section class="footer row container">
<div class="footer-redes col-12 col-lg-6" id="RRSS">
<div class="contenedor-facebook"><div class="icono-facebook"><img src="./images/facebook.png" alt="logo de Facebook"></div>
<div><a href="https://facebook.com/tokonoma.lit">Facebook</a></div></div>
<div class="contenedor-instagram"><div class="icono-instagram"><img src="./images/logotipo-de-instagram.png" alt="logo de Instagram"></div>
<div><a href="https://instagram.com/tokonoma.lit">Instagram</a></div>
</div></div>
<div class="footer-contacto col-12 col-lg-6" id="MAIL & TEL">
<div class="contenedor-whatsapp"><div class="icono-whatsapp"><img src="./images/whatsapp.png" alt="logo de WhatsApp"></div>
<div class="link-whatsapp"><a href="https://wa.me/5491167521022">551167521022</a></div></div>
<div class="contenedor-mail"><div class="icono-mail"><img src="./images/correo-electronico.png" alt="logo de correo electrónico"></div>
<div class="link-mail"><a href="mailto:talleres.leandrodiego@gmail.com">info@tokonoma.com.ar</a></div>
</div></div>
</section>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
<script>
AOS.init();
</script>
</body>
</html> |
import solutions.*;
import java.util.*;
public class Main {
private static final Scanner scan = new Scanner(System.in);
private static final ArrayList<SolutionInterface> solutions = new ArrayList<>(
Arrays.asList(
new SolutionTask1(),
new SolutionTask2(),
new SolutionTask3(),
new SolutionTask4(),
new SolutionTask5(),
new SolutionTask6(),
new SolutionTask7(),
new SolutionTask8(),
new SolutionTask9(),
new SolutionTask10()
)
);
private static void printHello(){
System.out.println("""
Hello!
This is an application made to test the solutions to assignment 1.
""");
}
/*
* This is just a linear search through the list of solutions.
*
* Time complexity: O(solutions.length())
*
* @param taskNumber number of the task required to be found.
*
* @return SolutionInterface a solution with corresponding task number.
*/
private static SolutionInterface getSolution(int taskNumber) throws Exception {
for (SolutionInterface solution : solutions)
if (solution.getTaskNumber() == taskNumber)
return solution;
throw new Exception("No task with number " + taskNumber + " found.");
}
/*
* This method reads certain number of line from console, and returns them as a single String object.
*
* Time complexity: O(numberOfLines)
*
* @param numberOfLines numbers of line that needs to be read from the console.
*
* @return String object containing concatenation of read lines.
*/
private static String readArguments(int numberOfLines){
System.out.println("Enter input (" + numberOfLines + " lines):");
StringBuilder total = new StringBuilder();
for(int i = 0; i < numberOfLines + 1; i++){
total.append(' ').append(scan.nextLine());
}
return total.toString();
}
private static int askTaskNumber(){
System.out.print("""
Please enter number of a task that you wish to test:""");
return scan.nextInt();
}
/*
* executeSolution
*
* Executes the solution with corresponding task number.
*
* @param taskNumber number of the task for which solution is expected to be executed.
*/
private static void executeSolution(int taskNumber){
SolutionInterface solution;
try {
solution = getSolution(taskNumber);
} catch (Exception e) {
System.out.println(e.getMessage());
return;
}
System.out.println(solution.getParametersDescription());
String arguments = readArguments(solution.getNumberOfInputLines());
// Save time before execution.
long time1 = System.currentTimeMillis();
String response = solution.execute(arguments);
// Save time after execution
long time2 = System.currentTimeMillis();
System.out.println("Output:");
System.out.println(response);
// Ascertain time spend by execution of the solution
System.out.println("Execution time: " + (time2 - time1) + " ms.");
}
private static boolean askContinue(){
System.out.println("Do you wish to continue testing solutions? y/n");
String ans = scan.nextLine();
return Objects.equals(ans, "y");
}
private static void runApplication(){
printHello();
do {
executeSolution(askTaskNumber());
}while(askContinue());
}
public static void main(String[] args) {
runApplication();
}
} |
package br.com.fiap.InovaTechDuo.controller;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import static org.springframework.http.HttpStatus.NO_CONTENT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import br.com.fiap.InovaTechDuo.model.Exames;
import br.com.fiap.InovaTechDuo.repository.ExamesRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
@RestController
@RequestMapping("explorar/exames")
@Tag(name = "exames")
public class ExamesController {
@Autowired
ExamesRepository repository;
// public ExamesController(ExamesService service) {
// this.service = service;
// }
@GetMapping
@Operation(
summary = "Listar todos os exames cadastrados",
description = "Retorna uma page com todos os exames em formato de objeto"
)
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Registro cadastrado com sucesso!"),
@ApiResponse(responseCode = "400", description = "Não foi possível adicionar a categoria. Verifique o corpo da requisição", useReturnTypeSchema = false),
@ApiResponse(responseCode = "401", description = "Acesso não permitido. É necessário autentificação.")
})
public Page<Exames> index(
@RequestParam(required = false) Integer mes,
@PageableDefault(sort = "data", direction = Direction.ASC) Pageable pageable) {
if (mes != null) {
return repository.findByMes(mes, pageable);
}
return repository.findAll(pageable);
}
@GetMapping("ultima")
@Operation(
summary = "Listar o ultimo registro na categoria",
description = "Retorna um array com o ultimo registro cadastrado"
)
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Os dados do ultimo registro foram retornados com sucesso!"),
@ApiResponse(responseCode = "401", description = "Acesso não permitido. É necessário autentificação.")
})
public Exames getUltimoExames() {
var pageable = PageRequest.of(0, 1, Direction.DESC, "data");
return repository.findAll(pageable).getContent().get(0);
}
@GetMapping("{id}")
@Operation(
summary = "Listar o resgistro com o parametro id",
description = "Retornar os detalhes do registro com o id informado como parâmetro de path."
)
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Dados do registro retornado com sucesso!"),
@ApiResponse(responseCode = "404", description = "Não existe dados do registro com o id informado."),
@ApiResponse(responseCode = "401", description = "Acesso não permitido. É necessário autentificação.")
})
public ResponseEntity<Exames> getById(@PathVariable Long id) {
return repository
.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@DeleteMapping("{id}")
@Operation(
summary = "Deletar o resgistro com o parametro id",
description = "Apaga os dados do registro com o id especificado no parâmetro de path."
)
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Dados do registro foram apagados com sucesso!"),
@ApiResponse(responseCode = "404", description = "Não existe dados do registro com o id informado."),
@ApiResponse(responseCode = "401", description = "Acesso não permitido. É necessário autentificação.")
})
@ResponseStatus(NO_CONTENT)
public void destroy(@PathVariable Long id) {
verificarSeRegistroExiste(id);
repository.deleteById(id);
}
@PutMapping("{id}")
@Operation(
summary = "Alterar o resgistro com o parametro id",
description = "Altera os dados do registro especificado pelo id, utilizando as informações enviadas no corpo da requisição"
)
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Registro cadastrado com sucesso!"),
@ApiResponse(responseCode = "400", description = "Dados enviados são inválidos. Verifique o corpo da requisição.", useReturnTypeSchema = false),
@ApiResponse(responseCode = "401", description = "Acesso não permitido. É necessário autentificação.")
})
public Exames update(@PathVariable Long id, @RequestBody Exames exames) {
verificarSeRegistroExiste(id);
exames.setId(id);
return repository.save(exames);
}
private void verificarSeRegistroExiste(Long id) {
repository
.findById(id)
.orElseThrow(() -> new ResponseStatusException(
NOT_FOUND,
"Não existe registro com o id informado"));
}
@PostMapping()
@ResponseStatus(CREATED)
@Operation(
summary = "Cadastrar exame ou consulta",
description = "Cria um novo registro com os dados enviados no corpo da requisição."
)
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Registro cadastrado com sucesso!"),
@ApiResponse(responseCode = "400", description = "Dados enviados são inválidos. Verifique o corpo da requisição.", useReturnTypeSchema = false),
@ApiResponse(responseCode = "401", description = "Acesso não permitido. É necessário autentificação.")
})
public Exames create(@RequestBody @Valid Exames exame) {
return repository.save(exame);
}
} |
import Head from "next/head";
import tw from "twin.macro";
type Props = {};
import { AiOutlineArrowRight } from "react-icons/ai";
import { RxDividerVertical } from "react-icons/rx";
import { useContext } from "react";
import { AppContext } from "../utils/AppContext";
import { AppContextType } from "../types/dataTypes";
import CartItem from "../components/cart/CartItem";
import Link from "next/link";
import Stripe from "stripe";
import getStripe from "../utils/get-stripe";
const Container = tw.div`min-h-[calc(100vh-5.74rem)] flex flex-col justify-between`;
const CartItemsWrapper = tw.div`flex-1 p-5`;
const CheckOutWrapper = tw.div`border-t-[2px] flex border-biege-4 p-5 sticky bottom-0 bg-biege-2`;
const EmptyCartWrapper = tw.div`h-full text-3xl text-center`;
const HomeRedirectAnchor = tw(
Link
)`mt-5 flex items-center justify-center text-lg gap-x-3 bg-biege-2 p-3 border-[2px] border-biege-4 transition-all hover:bg-biege-3/50 hover:-translate-y-1 hover:shadow-biege-4 hover:shadow-[6px_6px_0_-2px]`;
const Title = tw.h1`text-3xl text-center font-bold px-5 py-2`;
const CheckoutButton = tw.button`w-full max-w-[500px] mx-auto flex items-center justify-center text-lg gap-x-3 bg-biege-2 p-3 border-[2px] border-biege-4 transition-all hover:bg-biege-3/50 hover:-translate-y-1 hover:shadow-biege-4 hover:shadow-[6px_6px_0_-2px]`;
const Cart = (props: Props) => {
const { cartItems, totalPrice } = useContext(AppContext) as AppContextType;
const handleStripeCheckout = async () => {
const stripe = await getStripe();
const checkoutSession: Stripe.Checkout.Session = await fetch(
"/api/stripe-checkout",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ items: cartItems }),
}
).then((res) => res.json());
const result = await stripe?.redirectToCheckout({
sessionId: checkoutSession.id,
});
};
return (
<>
<Head>
<title>Cart - tonoyShop</title>
</Head>
<Container>
<Title>Your Cart</Title>
<CartItemsWrapper>
{cartItems.length > 0 ? (
cartItems.map((item) => (
<CartItem key={item._id} item={item} />
))
) : (
<EmptyCartWrapper>
<span>Your cart is empty :(</span>
<HomeRedirectAnchor href="/">
Continue shopping
<AiOutlineArrowRight />
</HomeRedirectAnchor>
</EmptyCartWrapper>
)}
</CartItemsWrapper>
{cartItems.length > 0 && (
<CheckOutWrapper>
<CheckoutButton onClick={handleStripeCheckout}>
<span>Total: ₹{totalPrice}</span>
<RxDividerVertical />
Check Out
<AiOutlineArrowRight />
</CheckoutButton>
</CheckOutWrapper>
)}
</Container>
</>
);
};
export default Cart; |
import React from "react";
import { useParams, useHistory, Link } from "react-router-dom";
import { SingleCharacterProps, IdProps } from "../../types/CharacterType";
import * as S from "./styles";
import { Loading } from "../../pages/CharacterPage/styles";
function SingleCharacter({
character,
likedList,
likeBtnHandleClick,
loading,
unLikeBtnHandleClick,
}: SingleCharacterProps) {
const { id } = useParams<IdProps>();
const history = useHistory();
const singleCharacter = character?.find(
(char: any) => char.id.toString() === id
);
const isLiked = likedList.some((id: any) => id === singleCharacter?.id);
const { image, name, status, episode, origin, location } =
singleCharacter || {};
function handleClick() {
if (!history) {
return <div>No Character</div>;
} else {
history.push("/");
}
}
return (
<>
{loading === false ? (
<S.Wrapper>
<S.ReturnButton onClick={handleClick}>
<i className="fas fa-long-arrow-alt-left fa-3x"></i>
</S.ReturnButton>
{singleCharacter && (
<S.Section>
<S.StyledButton
isLiked={!isLiked}
onClick={
!isLiked
? () => likeBtnHandleClick(singleCharacter.id)
: () => unLikeBtnHandleClick(singleCharacter.id)
}
>
<i className="fas fa-heart fa-2x"></i>
</S.StyledButton>
<S.ProfilePicture src={image} alt={name} />
<S.Status alive={status === "Alive"}>
{singleCharacter.status}
</S.Status>
<S.Name>{name}</S.Name>
<span>In {episode?.length} episode</span>
<S.Location>
<span>
<S.LocationTitle>Origin</S.LocationTitle> {origin?.name}
</span>
<span>
<S.LocationTitle>Lives</S.LocationTitle>
{location?.name}
</span>
</S.Location>
</S.Section>
)}
<div>
<h1>Played Episodes:</h1>
<S.EpisodeSection>
{episode &&
episode.map((e: any) => (
<S.EpisodeList key={e.episode}>
<Link to={`/episodeitem/${e.episode}`}>
<div>{e.episode}</div>
</Link>
</S.EpisodeList>
))}
</S.EpisodeSection>
</div>
</S.Wrapper>
) : (
<Loading>
<i className="fas fa-spinner fa-5x"></i>
</Loading>
)}
</>
);
}
export default SingleCharacter; |
import argparse
import datetime
import os
import requests
from bs4 import BeautifulSoup
from dateutil.parser import parse as parse_date
HOST = 'http://www.lunarbaboon.com'
HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,'
'application/signed-exchange;v=b3;q=0.9',
'Accept-Encoding': 'gzip, deflate',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/106.0.0.0 Safari/537.36',
}
COOKIES = {
'Cookie': 'JSESSIONID=4671D41BC6A297E8F70576727EA7D0F9.v5-web010; '
'ss_cid=f051e213-4199-4184-b464-9b958402c8b3; ss_cpvisit=1663317626270; '
'ss_cid=f051e213-4199-4184-b464-9b958402c8b3; ss_cpvisit=1666782210676'
}
DEFAULT_PATH = 'comics_folder/lunarbaboon'
START_TIME = datetime.datetime.now()
DEFAULT_DATE = (START_TIME - datetime.timedelta(days=30)).strftime("%Y-%m-%d")
def get_html(comics_folder, date_limit: datetime, url=HOST):
""""Get html of page for parsing"""
sess = requests.Session()
while True:
res = sess.get(url, headers=HEADERS, cookies=COOKIES)
res.raise_for_status()
soup = BeautifulSoup(res.text, 'lxml')
comics_dict = get_content(soup)
for comic_date, comic_url in comics_dict.items():
if date_limit and comic_date < date_limit:
print('Done. Got date limit')
return
save_comic(comic_url, comics_folder, comic_date)
try:
url = get_next_page(soup)
except IndexError:
print('Done!')
return
def get_content(soup) -> dict:
"""Return dict: k - date, v - url"""
global comic_images_elem
comic_urls = []
comic_dates = []
if soup.select('.body>p>span>span>img'):
comic_images_elem = soup.select('.body>p>span>span>img')
elif soup.select('.body>p>span>img'):
comic_images_elem = soup.select('.body>p>span>img')
comic_dates_elem = soup.select('.posted-on')
for image in comic_images_elem:
image_link = image.get('src')
if image_link.startswith('http://'):
comic_url = image_link
else:
comic_url = HOST + image_link
comic_urls.append(comic_url)
for date in comic_dates_elem:
comic_date = date.getText()
comic_date = parse_date(comic_date)
comic_dates.append(comic_date)
find_elems = dict(zip(comic_dates, comic_urls))
return find_elems
def get_next_page(soup):
"""Get a URL for next page"""
url = HOST + soup.select('.paginationControlNextPageSuffix>a')[0].get('href')
return url
def save_comic(comic_url, comics_folder, comic_date):
"""Get URL of image and save file in base folder"""
comic_link = comic_url.split('?')[0]
sess = requests.Session()
res = sess.get(comic_link, headers=HEADERS, cookies=COOKIES)
res.raise_for_status()
file_name = comic_date.strftime("%Y-%m-%d") + '__' + os.path.basename(comic_url).split('?')[0]
image_path = os.path.join(comics_folder, file_name)
# checking file availability
if not os.path.isfile(image_path):
print('Download image... %s' % comic_url.split('?')[0])
image_file = open(image_path, 'wb')
for chunk in res.iter_content(100_000):
image_file.write(chunk)
image_file.close()
return True
else:
print(f'Date: {comic_date.strftime("%Y-%m-%d")} -- No new comics!')
return False
def main(comics_folder, date_limit):
"""Start the main process"""
print('Lunarbaboon start')
print(f'Comics folder is {comics_folder}')
os.makedirs(comics_folder, exist_ok=True)
try:
# this a last page
# url = 'http://www.lunarbaboon.com/comics/?currentPage=195'
get_html(comics_folder, date_limit)
except KeyboardInterrupt:
print('Forced <Lunarbaboon> program termination!')
return
def valid_date(s):
"""Datetime validator"""
try:
return datetime.datetime.strptime(s, '%Y-%m-%d')
except ValueError:
msg = "not a valid date: {0!r}".format(s)
raise argparse.ArgumentTypeError(msg)
def parse_params():
"""Choice output comics folder"""
parser = argparse.ArgumentParser(prog='loader', description='loader comics shit')
parser.add_argument('--outdir', type=str, default=None, help='Output absolut path')
parser.add_argument('--date_limit', type=valid_date,
default=None, help="The Date - format YYYY-MM-DD")
args = parser.parse_args()
if args.outdir is None:
args.outdir = DEFAULT_PATH
elif not os.path.isabs(args.outdir):
raise ValueError('Path is not absolute')
if args.date_limit is None:
args.date_limit = parse_date(DEFAULT_DATE)
return args
if __name__ == '__main__':
params = parse_params()
main(comics_folder=params.outdir, date_limit=params.date_limit) |
import React, { useState } from "react";
import MyPicture from "../assets/oge2.jpg";
import S from "../styles/index.module.scss";
import {
experiences,
myProfile,
links,
frameworks,
languages,
tools,
others,
myContacts,
myProjects,
} from "../constant";
export const Home = () => {
const [active, setActive] = useState("Overview");
const year = new Date().getFullYear();
return (
<div className={S.Home}>
<div className={S.navbar}>
<div className={S.logo_wrap}>
<p className={S.logo}>OP</p>
<p className={S.my_name}>Ogechi</p>
</div>
<div className={S.desktop_nav}>
<div className={S.links_container}>
{links.map((link) => (
<p
key={link}
className={`${active === link ? S.active_link : S.link}`}
onClick={() => setActive(link)}
>
<span>#</span>
{link}
</p>
))}
</div>
</div>
</div>
<div className={S.home_content}>
<div className={S.about_container}>
<div className={S.about_content}>
<div className={S.image_container}>
<div className={S.image_wrap}>
<img src={MyPicture} alt="my picture" />
</div>
<div>
<p className={S.name}>Onyejekwe Ogechukwu</p>
<p className={S.role}>Frontend Developer</p>
</div>
</div>
<p className={S.about_me}>
I am an enthusiastic frontend developer with proven experience in
crafting modern web applications. I'm goal driven,
industrious and love human interaction. Problem solving is one
thing I love doing. I am interested in freelance opportunities. Contact me and you will be happy you did.
</p>
</div>
</div>
<div className={S.mobile_navs}>
<div className={S.links_container}>
{links.map((link) => (
<p
key={link}
className={`${active === link ? S.active_link : S.link}`}
onClick={() => setActive(link)}
>
<span>#</span>
{link}
</p>
))}
</div>
</div>
<div className={S.main_content}>
{/* about me */}
{active === "Overview" && (
<div>
<div>
<p className={S.subHeading}>My Profile:</p>
{myProfile.map((profile) => (
<div className={S.paragraph_wrap} key={profile.subtitle}>
<p className={`${S.sub_title} ${S.max_width}`}>
{profile.subtitle}
</p>
<p className={S.paragraph}>{profile.text}</p>
</div>
))}
</div>
<div className={S.content_wrap}>
<p className={S.subHeading}>Work Experience:</p>
<div className={S.experience_container}>
{experiences.map((experience, i) => (
<div className={S.company_card} key={i}>
<p className={S.title}>{experience.company}</p>
<p className={`${S.small_text} ${S.italic}`}>
{experience.city}
</p>
<p className={S.sub_title}>{experience.role}</p>
<p className={S.small_text}>{experience.duration}</p>
</div>
))}
</div>
</div>
</div>
)}
{/* skilll */}
{active === "Skills" && (
<div>
<div className={S.skill_content}>
<p className={S.subHeading}>FramwWork:</p>
<div className={S.flexbox}>
{frameworks.map((framework) => (
<p key={framework} className={S.skill_wrap}>
{framework}
</p>
))}
</div>
</div>
<div className={S.skill_content}>
<p className={S.subHeading}>Languages:</p>
<div className={S.flexbox}>
{languages.map((language) => (
<p key={language} className={S.skill_wrap}>
{language}
</p>
))}
</div>
</div>
<div className={S.skill_content}>
<p className={S.subHeading}>Tools:</p>
<div className={S.flexbox}>
{tools.map((tool) => (
<p key={tool} className={S.skill_wrap}>
{tool}
</p>
))}
</div>
</div>
<div className={S.skill_content}>
<p className={S.subHeading}>Others:</p>
<div className={S.flexbox}>
{others.map((tool) => (
<p key={tool} className={S.skill_wrap}>
{tool}
</p>
))}
</div>
</div>
</div>
)}
{/* projects */}
{active === "Projects" && (
<div className={S.project_container}>
{myProjects.map((project) => (
<div className={S.project_card}>
<div className={S.project_card_image}>
<img
src={project.image}
alt=""
className={S.project_image}
/>
</div>
<div className={S.project_tool}>
{project.tools.map((tool) => (
<p>{tool}</p>
))}
</div>
<div className={S.about_project}>
<p className={S.project_header}>{project.title}</p>
<p>{project.aboutProject}</p>
<a href={project.link} target="_blank">
view
</a>
</div>
</div>
))}
</div>
)}
{/* contact */}
{active === "Contacts" && (
<div>
<div>
<p className={S.subHeading}>Contact Me:</p>
{myContacts.map((profile) => (
<div className={S.paragraph_wrap} key={profile.subtitle}>
<p className={`${S.sub_title} ${S.max_width}`}>
{profile.subtitle}
</p>
<a
target="_blank"
href={profile.url}
className={S.paragraph}
>
{profile.text}
</a>
</div>
))}
</div>
</div>
)}
</div>
</div>
<div className={S.footer}>
<p>© {year} By onyejekwe ogechukwu</p>
</div>
</div>
);
}; |
import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Book } from './book';
import { BookFormComponent } from './book-form.component';
import { BookTableComponent } from './book-table.component';
import { BookService } from './book.service';
@Component({
selector: 'app-book-list',
standalone: true,
imports: [BookTableComponent, BookFormComponent, CommonModule],
template: `
<ng-container *ngIf="$books | async as books">
<app-book-table [books]="books" (edit)="onEdit($event)" />
</ng-container>
<ng-container *ngIf="book">
<app-book-form (submit)="onAdd($event)" (cancel)="onCancel()" [book]="book" />
</ng-container>
`,
})
export class BookListComponent implements OnInit {
$books: Observable<Array<Book>> | undefined;
book: Book | undefined;
constructor(private bookService: BookService) {}
ngOnInit() {
this.$books = this.bookService.getBooks();
this.book = new Book();
}
onAdd(book: Book) {
this.bookService.saveBook(book);
this.book = new Book();
}
onEdit(book: Book) {
this.book = Object.assign(new Book(), book);
}
onCancel() {
this.book = new Book();
}
} |
public class QueueBO {
private static final QueueBO instance = new QueueBO();
private QueueBO(){}
public static QueueBO getInstance() {
return instance;
}
public enum QueueStatus {
CREATED,
SUCCESS,
ERROR
}
private static map<String, IProcessingQueue> mapToExecute;
static {
mapToExecute = new map<String, IProcessingQueue>();
mapToExecute.put(QueueEventNames.ACCOUNT_SALESFORCE_TO_SAP.name(), new AccountIntegrationBO());
mapToExecute.put(QueueEventNames.OPPORTUNITY_SALESFORCE_TO_SAP.name(), new OpportunityVtaIntegrationS4BO());
mapToExecute.put(QueueEventNames.OPPORTUNITY_REJ_SALESFORCE_TO_SAP.name() , new OpportunityVtaIntegrationBO());
mapToExecute.put(QueueEventNames.OPPORTUNITY_UPDATE_SALESFORCE_TO_SAP.name() , new ModificaPedidoIntegrationS4BO());
}
public String createQueue( String eventName, String payLoad, Boolean ignoredByTrigger ) {
Queue__c queue = new Queue__c();
queue.EventName__c = eventName;
queue.Payload__c = payLoad;
queue.Status__c = QueueStatus.CREATED.name();
queue.IgnoredByTrigger__c = ignoredByTrigger;
insert queue;
return queue.Id;
}
public Queue__c sObjectQueue( String recordId, String eventName, String payLoad, Boolean ignoredByTrigger ) {
Queue__c queue = new Queue__c();
queue.RecordId__c = recordId;
queue.EventName__c = eventName;
queue.Payload__c = payLoad;
queue.Status__c = QueueStatus.CREATED.name();
queue.IgnoredByTrigger__c = ignoredByTrigger;
if(eventName.contains('OPP'))
queue.Opportunity__c = recordId;
if(eventName.contains('ACC'))
queue.Account__c = recordId;
return queue;
}
public void updateQueue( String queueId, String dmlExceptionStackTrace, String msg) {
Queue__c queue = new Queue__c();
queue.Id = queueId;
queue.Status__c = dmlExceptionStackTrace.equals('') ? QueueStatus.SUCCESS.name() : QueueStatus.ERROR.name();
queue.ExceptionStackTrace__c = dmlExceptionStackTrace;
if(msg.length() > 250)
queue.Messages__c = msg.substring(0,250);
else
queue.Messages__c = msg;
update queue;
}
public void updateQueue( String queueId, String dmlExceptionStackTrace) {
Queue__c queue = new Queue__c();
queue.Id = queueId;
queue.Status__c = dmlExceptionStackTrace.equals('') ? QueueStatus.SUCCESS.name() : QueueStatus.ERROR.name();
queue.ExceptionStackTrace__c = dmlExceptionStackTrace;
update queue;
}
public void updateQueueConfirm( String queueId, String xmlResult) {
Queue__c queue = new Queue__c();
queue.Id = queueId;
queue.Status__c = xmlResult.contains( '"Type_x":"E"' ) ? QueueStatus.ERROR.name() : QueueStatus.SUCCESS.name();
queue.Response__c = xmlResult;
update queue;
}
public void updateQueueConfirm( String queueId, String xmlResult, String msg) {
Queue__c queue = new Queue__c();
queue.Id = queueId;
queue.Status__c = xmlResult.contains( '"Type_x":"E"' ) ? QueueStatus.ERROR.name() : QueueStatus.SUCCESS.name();
queue.Response__c = xmlResult;
if(msg.length() > 250)
queue.Messages__c = msg.substring(0,250);
else
queue.Messages__c = msg;
update queue;
}
public void insertQueueConfirmForTest(String xmlResult) {
Queue__c queue = new Queue__c();
queue.Status__c = xmlResult.contains( '"Type_x":"E"' ) ? QueueStatus.ERROR.name() : QueueStatus.SUCCESS.name();
queue.Response__c = xmlResult.abbreviate(131000);
queue.IgnoredByTrigger__c = true;
insert queue;
}
public void executeProcessingQueue( List<Queue__c> queueToProcessing ) {
for( Queue__c queue : queueToProcessing ) {
if(Test.isRunningTest() ) return;
if(queue.IgnoredByTrigger__c ) return;
//OpportunityVtaIntegrationS4BO.executeQueue( queue.Id, queue.RecordId__c, queue.EventName__c, queue.Payload__c, 200);
mapToExecute.get(queue.EventName__c).executeQueue(queue.Id, queue.RecordId__c, queue.EventName__c, queue.Payload__c, 200);
//Change to S4 VtaIntegration for testing
}
}
} |
// Used by home page, a thumbnail for previewing professionals
import ProfileIcon from "components/ProfileIcon"
import React from "react"
import { useNavigate } from "react-router-dom"
import { ProfessionalUser } from "types/professional.types"
type TTalentPreview = {
talent: ProfessionalUser
}
const TalentPreview: React.FC<TTalentPreview> = ({ talent }) => {
const navigate = useNavigate()
return (
<div
className="p-4 hover:bg-sky-300/10 cursor-pointer group"
onClick={() => navigate(`/home/talents/details/${talent.userId}`)}
>
<div className="flex items-center gap-2">
<ProfileIcon verified={talent.verified} srcUrl={talent.profilePhoto} />
<h1 className="text-lg font-semibold truncate group-hover:text-sky-300 group-hover:underline">
{talent.firstName} {talent.lastName}
</h1>
</div>
<div className="p-2">
<p className="line-clamp-6">{talent.description}</p>
</div>
</div>
)
}
export default TalentPreview |
import React, { useEffect, useState } from 'react'
import { Div } from '@vkontakte/vkui'
import { Posts } from '../services/posts'
import { PostsItem } from './PostsItem'
export const PostsList = () => {
const [posts, setPosts] = useState([])
const [isLoading, setIsLoading] = useState(false)
const [isError, setIsError] = useState(false)
useEffect(() => {
setIsLoading(true)
setIsError(false)
Posts.get()
.then((response) => setPosts(response.data))
.catch(() => setIsError(true))
.finally(() => setIsLoading(false))
}, [])
if (isLoading) return 'Loading'
if (isError) return 'Fetch error'
if (!posts?.length) return 'No posts'
return (
<Div>
{posts.map((post) => <PostsItem key={post.id} title={post.title} desc={post.body} /> )}
</Div>
)
} |
import { useState } from "react";
import { useSignIn } from "../hooks/useSignIn";
import { doc, updateDoc } from "firebase/firestore";
import { db } from "../firebase";
import { useAuthContext } from "../hooks/useAuthContext";
import { useNavigate } from "react-router-dom";
// styles
export function Login() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const { isLoading, login, isError } = useSignIn(email, password);
const { login: authLogin } = useAuthContext();
const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
console.log(email, password);
const user = await login();
const docRef = doc(db, "users", user.uid);
await updateDoc(docRef, { online: true });
console.log("success logging in");
authLogin(user);
navigate("/");
};
return (
<form onSubmit={handleSubmit} className="auth-form">
<h2>login</h2>
<label>
<span>email:</span>
<input
required
type="email"
onChange={(e) => setEmail(e.target.value)}
value={email}
/>
</label>
<label>
<span>password:</span>
<input
required
type="password"
onChange={(e) => setPassword(e.target.value)}
value={password}
/>
</label>
<button className="btn">Log in</button>
{isError}
</form>
);
} |
<!--
Nextcloud - Inventory
@author Raimund Schlüßler
@copyright 2020 Raimund Schlüßler <raimund.schluessler@mailbox.org>
@author Julius Härtl
@copyright 2020 Julius Härtl <jus@bitgrid.net>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
License as published by the Free Software Foundation; either
version 3 of the License, or 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 AFFERO GENERAL PUBLIC LICENSE for more details.
You should have received a copy of the GNU Affero General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
-->
<template>
<div class="attachments"
:class="{ 'attachments--empty': !attachments.length }"
@dragover.prevent="!isDraggingOver && (isDraggingOver = true)"
@dragleave.prevent="isDraggingOver && (isDraggingOver = false)"
@drop.prevent="handleDropFiles">
<div class="attachments__wrapper">
<ul>
<li class="attachments__header">
<div class="label">
{{ attachments.length ? t('inventory', 'Attachments') : t('inventory', 'No files attached.') }}
</div>
<NcActions :boundaries-element="boundaries">
<NcActionButton :close-after-click="true"
@click="upload">
<template #icon>
<Upload :size="20" />
</template>
{{ t('inventory', 'Upload attachment') }}
</NcActionButton>
<NcActionButton :close-after-click="true"
@click="select">
<template #icon>
<Folder :size="20" />
</template>
{{ t('inventory', 'Select attachment') }}
</NcActionButton>
</NcActions>
</li>
<li v-for="attachment in attachments" :key="attachment.id" class="attachment">
<a class="fileicon" :style="attachmentMimetype(attachment)" :href="attachment.url" />
<div class="details">
<a :href="attachmentUrl(attachment)">
<div class="filename">
<span class="basename">{{ attachment.extendedData.info.filename }}</span>
<span class="extension">{{ '.' + attachment.extendedData.info.extension }}</span>
</div>
<span class="filesize">{{ bytes(attachment.extendedData.filesize) }}</span>
<span class="filedate">{{ relativeDate(attachment.lastModified) }}</span>
<span class="filedate">{{ t('inventory', 'by {username}', { username: attachment.createdBy }) }}</span>
</a>
</div>
<NcActions :boundaries-element="boundaries">
<NcActionLink :href="fileLink(attachment)"
target="_blank"
:close-after-click="true">
<template #icon>
<OpenInNew :size="20" />
</template>
{{ t('inventory', 'Show in files') }}
</NcActionLink>
<NcActionButton v-if="canUnlink(attachment)"
:close-after-click="true"
@click="unlinkAttachment(attachment)">
<template #icon>
<Close :size="20" />
</template>
{{ t('inventory', 'Unlink attachment') }}
</NcActionButton>
<NcActionButton :close-after-click="true"
@click="deleteAttachment(attachment)">
<template #icon>
<Delete :size="20" />
</template>
{{ t('inventory', 'Delete attachment') }}
</NcActionButton>
</NcActions>
</li>
<li v-if="loadingAttachments" class="attachment attachment--placeholder">
<NcLoadingIcon />
<span class="message">{{ t('inventory', 'Load attachments from server.') }}</span>
</li>
</ul>
</div>
<input ref="localAttachments"
type="file"
style="display: none;"
@change="handleUploadFile">
<transition name="fade" mode="out-in">
<div v-show="isDraggingOver"
class="dragover">
<div class="drop-hint">
<div class="drop-hint__icon icon-upload" />
<h2 class="drop-hint__text">
{{ t('inventory', 'Drop your files to upload') }}
</h2>
</div>
</div>
</transition>
<NcModal v-if="modalShow"
class="modal-attachments"
:name="t('inventory', 'File already exists')"
@close="modalShow=false">
<div class="modal__content">
<h2>{{ t('inventory', 'File already exists') }}</h2>
<p>
{{ t('inventory', 'A file with the name {filename} already exists.', {filename: file.name}) }}
</p>
<p>
{{ t('inventory', 'Do you want to overwrite it?') }}
</p>
<div class="button-wrapper">
<NcButton @click="overrideAttachment">
{{ t('inventory', 'Overwrite file') }}
</NcButton>
<NcButton type="primary" @click="modalShow=false">
{{ t('inventory', 'Keep existing file') }}
</NcButton>
</div>
</div>
</NcModal>
</div>
</template>
<script>
import { showError, getFilePickerBuilder } from '@nextcloud/dialogs'
import { formatFileSize } from '@nextcloud/files'
import { translate as t } from '@nextcloud/l10n'
import moment from '@nextcloud/moment'
import { generateUrl } from '@nextcloud/router'
import {
NcActions,
NcActionButton,
NcActionLink,
NcButton,
NcModal,
NcLoadingIcon,
} from '@nextcloud/vue'
import Close from 'vue-material-design-icons/Close.vue'
import Delete from 'vue-material-design-icons/Delete.vue'
import Folder from 'vue-material-design-icons/Folder.vue'
import OpenInNew from 'vue-material-design-icons/OpenInNew.vue'
import Upload from 'vue-material-design-icons/Upload.vue'
export default {
components: {
NcActions,
NcActionButton,
NcActionLink,
NcButton,
NcModal,
NcLoadingIcon,
Close,
Delete,
Folder,
OpenInNew,
Upload,
},
props: {
attachments: {
type: Array,
default: () => [],
},
itemId: {
type: String,
required: true,
},
instanceId: {
type: String,
default: null,
},
loadingAttachments: {
type: Boolean,
default: false,
},
},
data() {
return {
modalShow: false,
file: '',
overwriteAttachment: null,
isDraggingOver: false,
maxUploadSize: 16e7,
// Hack to fix https://github.com/nextcloud/nextcloud-vue/issues/1384
boundaries: document.querySelector('#content-vue'),
}
},
methods: {
t,
/**
* Whether an attachment can be unlinked or only deleted.
* Files that have been linked start with a '/' which indicates the path is absolute
*
* @param {object} attachment The attachment to check
* @return {boolean}
*/
canUnlink(attachment) {
return attachment.basename.startsWith('/')
},
bytes(bytes) {
if (isNaN(parseFloat(bytes, 10)) || !isFinite(bytes)) {
return '-'
}
const precision = 2
const units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB']
const number = Math.floor(Math.log(bytes) / Math.log(1024))
return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision) + ' ' + units[number]
},
relativeDate(timestamp) {
return moment.unix(timestamp).fromNow()
},
async unlinkAttachment(attachment) {
try {
await this.$store.dispatch('unlinkAttachment', {
itemId: this.itemId,
attachmentId: attachment.id,
instanceId: this.instanceId,
})
} catch (err) {
showError(err.response.data.message)
}
},
async deleteAttachment(attachment) {
try {
await this.$store.dispatch('deleteAttachment', {
itemId: this.itemId,
attachmentId: attachment.id,
instanceId: this.instanceId,
})
} catch (err) {
showError(err.response.data.message)
}
},
upload() {
this.$refs.localAttachments.click()
},
async select() {
const attachment = await getFilePickerBuilder(t('inventory', 'Select a file to link as attachment')).build().pick()
try {
await this.$store.dispatch('linkAttachment', {
itemId: this.itemId,
attachment,
instanceId: this.instanceId,
})
} catch (err) {
showError(err.response.data.message)
}
},
handleDropFiles(event) {
this.isDraggingOver = false
this.onLocalAttachmentSelected(event.dataTransfer.files[0])
event.dataTransfer.value = ''
},
handleUploadFile(event) {
this.onLocalAttachmentSelected(event.target.files[0])
event.target.value = ''
},
async onLocalAttachmentSelected(file) {
if (this.maxUploadSize > 0 && file.size > this.maxUploadSize) {
showError(
t('inventory', 'Failed to upload {name}', { name: file.name }) + ' - '
+ t('inventory', 'Maximum file size of {size} exceeded', { size: formatFileSize(this.maxUploadSize) })
)
event.target.value = ''
return
}
const bodyFormData = new FormData()
bodyFormData.append('itemId', this.itemId)
if (this.instanceId) {
bodyFormData.append('instanceId', this.instanceId)
}
bodyFormData.append('file', file)
try {
await this.$store.dispatch('createAttachment', {
itemId: this.itemId,
formData: bodyFormData,
instanceId: this.instanceId,
})
} catch (err) {
if (err.response.data.status === 409) {
this.file = file
this.overwriteAttachment = err.response.data.data
this.modalShow = true
} else {
showError(err.response.data.message)
}
}
},
overrideAttachment() {
const bodyFormData = new FormData()
bodyFormData.append('itemId', this.itemId)
bodyFormData.append('file', this.file)
this.$store.dispatch('updateAttachment', {
itemId: this.itemId,
attachmentId: this.overwriteAttachment.id,
formData: bodyFormData,
instanceId: this.instanceId,
})
this.modalShow = false
},
attachmentMimetype(attachment) {
const url = OC.MimeType.getIconUrl(attachment.extendedData.mimetype)
return {
'background-image': `url("${url}")`,
}
},
attachmentUrl(attachment) {
if (attachment.instanceid) {
return generateUrl(`/apps/inventory/item/${attachment.itemid}/instance/${attachment.instanceid}/attachment/${attachment.id}/display`)
} else {
return generateUrl(`/apps/inventory/item/${attachment.itemid}/attachment/${attachment.id}/display`)
}
},
fileLink(attachment) {
return generateUrl(attachment.link)
},
},
}
</script>
<style lang="scss" scoped>
.attachments {
display: flex;
align-items: center;
flex-wrap: wrap;
&--empty {
flex-wrap: nowrap;
}
&__wrapper {
display: inline-block;
flex: 1 1 auto;
>ul {
display: grid;
grid-gap: 5px;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
grid-auto-flow: dense;
.attachments__header {
display: flex;
grid-column: 1 / -1;
.label {
line-height: 44px;
}
.action-item {
margin-left: auto;
}
}
li.attachment {
display: flex;
padding: 3px 0;
align-items: center;
&--placeholder {
.icon {
height: 38px;
width: 38px;
}
.message {
padding-left: 10px;
}
}
&.deleted {
opacity: .5;
}
.fileicon {
display: inline-block;
min-width: 32px;
width: 32px;
height: 32px;
background-size: contain;
margin-bottom: auto;
}
.details {
flex-grow: 1;
flex-shrink: 1;
min-width: 0;
flex-basis: 50%;
line-height: 110%;
padding: 2px;
}
.filename {
width: 70%;
display: flex;
white-space: nowrap;
.basename {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
padding-bottom: 2px;
}
.extension {
opacity: .7;
}
}
.filesize,
.filedate {
font-size: 90%;
color: var(--color-text-lighter);
padding-right: 2px;
}
}
}
}
.dragover {
width: 100%;
.drop-hint__text {
text-align: center;
}
}
}
.modal-attachments {
.modal__content {
min-width: 250px;
text-align: center;
margin: 20px;
.button-wrapper {
display: flex;
justify-content: center;
padding-top: 40px;
.button-vue {
margin: 0 20px;
}
}
}
}
</style> |
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
This file is part of Eruption.
Eruption 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.
Eruption 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 Eruption. If not, see <http://www.gnu.org/licenses/>.
Copyright (c) 2019-2022, The Eruption Development Team
*/
use bitvec::prelude::*;
use evdev_rs::enums::EV_KEY;
use hidapi::{HidApi, HidDevice};
use log::*;
use parking_lot::{Mutex, RwLock};
use std::time::Duration;
// use std::sync::atomic::Ordering;
use std::collections::HashMap;
use std::sync::Arc;
use std::{any::Any, thread};
use crate::constants::{self, DEVICE_SETTLE_MILLIS};
use super::{
Capability, DeviceCapabilities, DeviceInfoTrait, DeviceStatus, DeviceTrait, HwDeviceError,
MouseDevice, MouseDeviceTrait, MouseHidEvent, RGBA,
};
pub type Result<T> = super::Result<T>;
// pub const NUM_BUTTONS: usize = 9;
// canvas to LED index mapping
pub const LED_0: usize = constants::CANVAS_SIZE - 36;
pub const LED_1: usize = constants::CANVAS_SIZE - 1;
/// Binds the driver to a device
pub fn bind_hiddev(
hidapi: &HidApi,
usb_vid: u16,
usb_pid: u16,
serial: &str,
) -> super::Result<MouseDevice> {
let ctrl_dev;
let led_dev;
if usb_pid == 0x2c8e {
// wireless mode
ctrl_dev = hidapi.device_list().find(|&device| {
device.vendor_id() == usb_vid
&& device.product_id() == usb_pid
&& device.serial_number().unwrap_or("") == serial
&& device.interface_number() == 1
});
led_dev = hidapi.device_list().find(|&device| {
device.vendor_id() == usb_vid
&& device.product_id() == usb_pid
&& device.serial_number().unwrap_or("") == serial
&& device.interface_number() == 2
});
} else {
// cable mode
ctrl_dev = hidapi.device_list().find(|&device| {
device.vendor_id() == usb_vid
&& device.product_id() == usb_pid
&& device.serial_number().unwrap_or("") == serial
&& device.interface_number() == 2
});
led_dev = hidapi.device_list().find(|&device| {
device.vendor_id() == usb_vid
&& device.product_id() == usb_pid
&& device.serial_number().unwrap_or("") == serial
&& device.interface_number() == 1
});
}
if ctrl_dev.is_none() || led_dev.is_none() {
Err(HwDeviceError::EnumerationError {}.into())
} else {
Ok(Arc::new(RwLock::new(Box::new(RoccatKoneProAir::bind(
ctrl_dev.unwrap(),
led_dev.unwrap(),
)))))
}
}
/// ROCCAT Kone Pro Air info struct (sent as HID report)
#[derive(Debug, Copy, Clone)]
#[repr(C, packed)]
pub struct DeviceInfo {
pub report_id: u8,
pub size: u8,
pub firmware_version: u8,
pub reserved1: u8,
pub reserved2: u8,
pub reserved3: u8,
}
#[derive(Clone)]
/// Device specific code for the ROCCAT Kone Pro Air mouse
pub struct RoccatKoneProAir {
pub is_initialized: bool,
pub is_bound: bool,
pub ctrl_hiddev_info: Option<hidapi::DeviceInfo>,
pub led_hiddev_info: Option<hidapi::DeviceInfo>,
pub is_opened: bool,
pub ctrl_hiddev: Arc<Mutex<Option<hidapi::HidDevice>>>,
pub led_hiddev: Arc<Mutex<Option<hidapi::HidDevice>>>,
pub button_states: Arc<Mutex<BitVec>>,
pub has_failed: bool,
// device specific configuration options
pub brightness: i32,
// device status
pub device_status: DeviceStatus,
}
impl RoccatKoneProAir {
/// Binds the driver to the supplied HID device
pub fn bind(ctrl_dev: &hidapi::DeviceInfo, led_dev: &hidapi::DeviceInfo) -> Self {
info!("Bound driver: ROCCAT Kone Pro Air");
Self {
is_initialized: false,
is_bound: true,
ctrl_hiddev_info: Some(ctrl_dev.clone()),
led_hiddev_info: Some(led_dev.clone()),
is_opened: false,
ctrl_hiddev: Arc::new(Mutex::new(None)),
led_hiddev: Arc::new(Mutex::new(None)),
button_states: Arc::new(Mutex::new(bitvec![0; constants::MAX_MOUSE_BUTTONS])),
has_failed: false,
brightness: 100,
device_status: DeviceStatus(HashMap::new()),
}
}
// pub(self) fn query_ctrl_report(&mut self, id: u8) -> Result<()> {
// trace!("Querying control device feature report");
// if !self.is_bound {
// Err(HwDeviceError::DeviceNotBound {}.into())
// } else if !self.is_opened {
// Err(HwDeviceError::DeviceNotOpened {}.into())
// } else {
// match id {
// 0x0f => {
// let mut buf: [u8; 256] = [0; 256];
// buf[0] = id;
// let ctrl_dev = self.ctrl_hiddev.as_ref().lock();
// let ctrl_dev = ctrl_dev.as_ref().unwrap();
// match ctrl_dev.get_feature_report(&mut buf) {
// Ok(_result) => {
// hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
// Ok(())
// }
// Err(_) => Err(HwDeviceError::InvalidResult {}.into()),
// }
// }
// _ => Err(HwDeviceError::InvalidStatusCode {}.into()),
// }
// }
// }
fn send_ctrl_report(&mut self, id: u8) -> Result<()> {
trace!("Sending control device feature report");
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else if !self.is_opened {
Err(HwDeviceError::DeviceNotOpened {}.into())
} else {
// using led_hiddev is intentional here
let led_dev = self.led_hiddev.as_ref().lock();
let led_dev = led_dev.as_ref().unwrap();
match id {
0x90 => {
let buf: [u8; 65] = [
0x00, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
];
match led_dev.write(&buf) {
Ok(_result) => {
hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
}
Err(_) => return Err(HwDeviceError::InvalidResult {}.into()),
}
Ok(())
}
_ => Err(HwDeviceError::InvalidStatusCode {}.into()),
}
}
}
fn wait_for_ctrl_dev(&self) -> Result<()> {
trace!("Waiting for control device to respond...");
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else if !self.is_opened {
Err(HwDeviceError::DeviceNotOpened {}.into())
} else {
let mut buf: [u8; 1] = [0; 1];
let ctrl_dev = self.led_hiddev.as_ref().lock();
let ctrl_dev = ctrl_dev.as_ref().unwrap();
match ctrl_dev.read_timeout(&mut buf, 15) {
Ok(_result) => {
hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
// if buf[1] == 0x01 {
return Ok(());
// }
}
Err(_) => { /* do nothing */ }
}
thread::sleep(Duration::from_millis(DEVICE_SETTLE_MILLIS));
Ok(())
}
}
// fn write_feature_report(&self, buffer: &[u8]) -> Result<()> {
// if !self.is_bound {
// Err(HwDeviceError::DeviceNotBound {}.into())
// } else {
// let ctrl_dev = self.ctrl_hiddev.as_ref().lock();
// let ctrl_dev = ctrl_dev.as_ref().unwrap();
// match ctrl_dev.send_feature_report(buffer) {
// Ok(_result) => {
// hexdump::hexdump_iter(buffer).for_each(|s| trace!(" {}", s));
// Ok(())
// }
// Err(_) => Err(HwDeviceError::InvalidResult {}.into()),
// }
// }
// }
// fn read_feature_report(&self, id: u8, size: usize) -> Result<Vec<u8>> {
// if !self.is_bound {
// Err(HwDeviceError::DeviceNotBound {}.into())
// } else {
// // we have to use the led_hiddev here, this is intentional
// let ctrl_dev = self.ctrl_hiddev.as_ref().lock();
// let ctrl_dev = ctrl_dev.as_ref().unwrap();
// loop {
// let mut buf = Vec::new();
// buf.resize(size, 0);
// buf[0] = id;
// match ctrl_dev.read_timeout(buf.as_mut_slice(), 10) {
// Ok(_result) => {
// if buf[0] == 0x01 || buf[0..2] == [0x07, 0x14] {
// continue;
// } else {
// hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
// break Ok(buf);
// }
// }
// Err(_) => break Err(HwDeviceError::InvalidResult {}.into()),
// }
// }
// }
// }
fn update_device_status(&mut self) -> Result<()> {
fn read_results(led_dev: &HidDevice) -> Result<super::DeviceStatus> {
let mut table = HashMap::new();
let mut cntr = 0;
'POLL_LOOP: loop {
// query results
let mut buf = Vec::new();
buf.resize(64, 0);
match led_dev.read_timeout(&mut buf, 10) {
Ok(_result) => {
hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
}
Err(_) => {
error!("Could not read results from previous status query");
// return Err(HwDeviceError::InvalidResult {}.into());
}
}
match buf[0] {
0x00 => break 'POLL_LOOP,
0x90 => {
match buf[1] {
0x0a => {
let battery_status = buf[10];
let battery_level_percent = battery_status.clamp(0, 100);
table.insert(
"battery-level-percent".to_string(),
format!("{:.0}", battery_level_percent),
);
table.insert(
"battery-level-raw".to_string(),
format!("{}", battery_status),
);
}
0x70 => {
let signal = buf[4];
let transceiver_enabled = signal != 236;
// radio
table.insert(
"transceiver-enabled".to_string(),
format!("{}", transceiver_enabled),
);
if transceiver_enabled {
// signal strength
table.insert(
"signal-strength-percent".to_string(),
format!("{:.0}", (128.0 - signal as f32).clamp(0.0, 100.0)),
);
table.insert(
"signal-strength-raw".to_string(),
format!("{}", signal),
);
} else {
// signal strength when radio is off
table.insert(
"signal-strength-percent".to_string(),
format!("{:.0}", 0.0),
);
table.insert(
"signal-strength-raw".to_string(),
format!("{}", 0),
);
}
}
_ => { /* do nothing */ }
}
break 'POLL_LOOP;
}
_ => { /* do nothing */ }
}
if cntr > 3 {
break 'POLL_LOOP;
}
cntr += 1;
thread::sleep(Duration::from_millis(10));
}
Ok(DeviceStatus(table))
}
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else if !self.is_opened {
Err(HwDeviceError::DeviceNotOpened {}.into())
} else if !self.is_initialized {
Err(HwDeviceError::DeviceNotInitialized {}.into())
} else {
let led_dev = self.led_hiddev.as_ref().lock();
let led_dev = led_dev.as_ref().unwrap();
// TODO: Further investigate the meaning of the fields
let buf: [u8; 65] = [
0x00, 0x90, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];
match led_dev.write(&buf) {
Ok(_result) => {
hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
}
Err(_) => {
error!("Could not write to the device");
// return Err(HwDeviceError::InvalidResult {}.into());
}
}
let result = read_results(led_dev)?;
let buf: [u8; 65] = [
0x00, 0x90, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];
match led_dev.write(&buf) {
Ok(_result) => {
hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
}
Err(_) => {
error!("Could not write to the device");
// return Err(HwDeviceError::InvalidResult {}.into());
}
}
let result1 = read_results(led_dev)?;
self.device_status = DeviceStatus(
result
.0
.into_iter()
.chain(result1.0)
// .chain(result2.0)
.collect(),
);
Ok(())
}
}
}
impl DeviceInfoTrait for RoccatKoneProAir {
fn get_device_capabilities(&self) -> DeviceCapabilities {
DeviceCapabilities::from([Capability::Mouse, Capability::RgbLighting])
}
fn get_device_info(&self) -> Result<super::DeviceInfo> {
trace!("Querying the device for information...");
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else if !self.is_opened {
Err(HwDeviceError::DeviceNotOpened {}.into())
} else {
/* let mut buf = [0; size_of::<DeviceInfo>()];
buf[0] = 0x09; // Query device info (HID report 0x09)
let ctrl_dev = self.ctrl_hiddev.as_ref().lock();
let ctrl_dev = ctrl_dev.as_ref().unwrap();
match ctrl_dev.get_feature_report(&mut buf) {
Ok(_result) => {
hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
let tmp: DeviceInfo =
unsafe { std::ptr::read_unaligned(buf.as_ptr() as *const _) };
let result = super::DeviceInfo::new(tmp.firmware_version as i32);
Ok(result)
}
Err(_) => Err(HwDeviceError::InvalidResult {}.into()),
} */
let result = super::DeviceInfo::new(0_i32);
Ok(result)
}
}
fn get_firmware_revision(&self) -> String {
// if let Ok(device_info) = self.get_device_info() {
// format!(
// "{}.{:02}",
// device_info.firmware_version / 100,
// device_info.firmware_version % 100
// )
// } else {
"<unknown>".to_string()
// }
}
}
impl DeviceTrait for RoccatKoneProAir {
fn get_usb_path(&self) -> String {
self.ctrl_hiddev_info
.clone()
.unwrap()
.path()
.to_str()
.unwrap()
.to_string()
}
fn get_usb_vid(&self) -> u16 {
self.ctrl_hiddev_info.as_ref().unwrap().vendor_id()
}
fn get_usb_pid(&self) -> u16 {
self.ctrl_hiddev_info.as_ref().unwrap().product_id()
}
fn get_serial(&self) -> Option<&str> {
self.ctrl_hiddev_info.as_ref().unwrap().serial_number()
}
fn get_support_script_file(&self) -> String {
"mice/roccat_kone_pro_air".to_string()
}
fn open(&mut self, api: &hidapi::HidApi) -> Result<()> {
trace!("Opening HID devices now...");
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else {
trace!("Opening control device...");
match self.ctrl_hiddev_info.as_ref().unwrap().open_device(api) {
Ok(dev) => *self.ctrl_hiddev.lock() = Some(dev),
Err(_) => return Err(HwDeviceError::DeviceOpenError {}.into()),
};
trace!("Opening LED device...");
match self.led_hiddev_info.as_ref().unwrap().open_device(api) {
Ok(dev) => *self.led_hiddev.lock() = Some(dev),
Err(_) => return Err(HwDeviceError::DeviceOpenError {}.into()),
};
self.is_opened = true;
Ok(())
}
}
fn close_all(&mut self) -> Result<()> {
trace!("Closing HID devices now...");
// close keyboard device
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else if !self.is_opened {
Err(HwDeviceError::DeviceNotOpened {}.into())
} else {
trace!("Closing control device...");
*self.ctrl_hiddev.lock() = None;
trace!("Closing LED device...");
*self.led_hiddev.lock() = None;
self.is_opened = false;
Ok(())
}
}
fn send_init_sequence(&mut self) -> Result<()> {
trace!("Sending device init sequence...");
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else if !self.is_opened {
Err(HwDeviceError::DeviceNotOpened {}.into())
} else {
// match self.get_device_info() {
// Ok(device_info) => {
// if device_info.firmware_version < 110 {
// warn!(
// "Outdated firmware version: {}, should be: >= 1.10",
// format!(
// "{}.{:02}",
// device_info.firmware_version / 100,
// device_info.firmware_version % 100
// )
// );
// }
// }
// Err(e) => {
// error!("Could not get firmware version: {}", e);
// }
// }
self.send_ctrl_report(0x90)
.unwrap_or_else(|e| error!("Step 1: {}", e));
self.wait_for_ctrl_dev()
.unwrap_or_else(|e| error!("Wait 1: {}", e));
self.is_initialized = true;
Ok(())
}
}
fn is_initialized(&self) -> Result<bool> {
Ok(self.is_initialized)
}
fn has_failed(&self) -> Result<bool> {
Ok(self.has_failed)
}
fn fail(&mut self) -> Result<()> {
self.has_failed = true;
Ok(())
}
fn write_data_raw(&self, buf: &[u8]) -> Result<()> {
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else if !self.is_opened {
Err(HwDeviceError::DeviceNotOpened {}.into())
} else if !self.is_initialized {
Err(HwDeviceError::DeviceNotInitialized {}.into())
} else {
let ctrl_dev = self.ctrl_hiddev.as_ref().lock();
let ctrl_dev = ctrl_dev.as_ref().unwrap();
match ctrl_dev.write(buf) {
Ok(_result) => {
hexdump::hexdump_iter(buf).for_each(|s| trace!(" {}", s));
Ok(())
}
Err(_) => Err(HwDeviceError::InvalidResult {}.into()),
}
}
}
fn read_data_raw(&self, size: usize) -> Result<Vec<u8>> {
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else if !self.is_opened {
Err(HwDeviceError::DeviceNotOpened {}.into())
} else if !self.is_initialized {
Err(HwDeviceError::DeviceNotInitialized {}.into())
} else {
let ctrl_dev = self.ctrl_hiddev.as_ref().lock();
let ctrl_dev = ctrl_dev.as_ref().unwrap();
let mut buf = Vec::new();
buf.resize(size, 0);
match ctrl_dev.read(buf.as_mut_slice()) {
Ok(_result) => {
hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
Ok(buf)
}
Err(_) => Err(HwDeviceError::InvalidResult {}.into()),
}
}
}
fn device_status(&self) -> Result<super::DeviceStatus> {
Ok(self.device_status.clone())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn as_device(&self) -> &dyn DeviceTrait {
self
}
fn as_device_mut(&mut self) -> &mut dyn DeviceTrait {
self
}
fn as_mouse_device(&self) -> Option<&dyn MouseDeviceTrait> {
Some(self as &dyn MouseDeviceTrait)
}
fn as_mouse_device_mut(&mut self) -> Option<&mut dyn MouseDeviceTrait> {
Some(self as &mut dyn MouseDeviceTrait)
}
}
impl MouseDeviceTrait for RoccatKoneProAir {
fn get_profile(&self) -> Result<i32> {
trace!("Querying device profile config");
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else if !self.is_opened {
Err(HwDeviceError::DeviceNotOpened {}.into())
} else {
// let ctrl_dev = self.ctrl_hiddev.as_ref().lock();
// let ctrl_dev = ctrl_dev.as_ref().unwrap();
// let mut buf: [u8; 64] = [0x00 as u8; 64];
// buf[0] = 0x06;
// match ctrl_dev.get_feature_report(&mut buf) {
// Ok(_result) => {
// hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
// Ok(())
// }
// Err(_) => Err(HwDeviceError::InvalidResult {}),
// }?;
// Ok(buf[6] as i32)
Err(HwDeviceError::OpNotSupported {}.into())
}
}
fn set_profile(&mut self, _profile: i32) -> Result<()> {
trace!("Setting device profile config");
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else if !self.is_opened {
Err(HwDeviceError::DeviceNotOpened {}.into())
} else {
// let ctrl_dev = self.ctrl_hiddev.as_ref().lock();
// let ctrl_dev = ctrl_dev.as_ref().unwrap();
// let mut buf: [u8; 64] = [0x00 as u8; 64];
// buf[0] = 0x06;
// match ctrl_dev.get_feature_report(&mut buf) {
// Ok(_result) => {
// hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
// Ok(())
// }
// Err(_) => Err(HwDeviceError::InvalidResult {}),
// }?;
// buf[6] = profile as u8;
// match ctrl_dev.send_feature_report(&buf) {
// Ok(_result) => {
// hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
// Ok(())
// }
// Err(_) => Err(HwDeviceError::InvalidResult {}),
// }?;
// Ok(())
Err(HwDeviceError::OpNotSupported {}.into())
}
}
fn get_dpi(&self) -> Result<i32> {
trace!("Querying device DPI config");
Err(HwDeviceError::OpNotSupported {}.into())
}
fn set_dpi(&mut self, _dpi: i32) -> Result<()> {
trace!("Setting device DPI config");
Err(HwDeviceError::OpNotSupported {}.into())
}
fn get_rate(&self) -> Result<i32> {
trace!("Querying device poll rate config");
Err(HwDeviceError::OpNotSupported {}.into())
}
fn set_rate(&mut self, _rate: i32) -> Result<()> {
trace!("Setting device poll rate config");
Err(HwDeviceError::OpNotSupported {}.into())
}
fn get_dcu_config(&self) -> Result<i32> {
trace!("Querying device DCU config");
Err(HwDeviceError::OpNotSupported {}.into())
}
fn set_dcu_config(&mut self, _dcu: i32) -> Result<()> {
trace!("Setting device DCU config");
Err(HwDeviceError::OpNotSupported {}.into())
}
fn get_angle_snapping(&self) -> Result<bool> {
trace!("Querying device angle-snapping config");
Err(HwDeviceError::OpNotSupported {}.into())
}
fn set_angle_snapping(&mut self, _angle_snapping: bool) -> Result<()> {
trace!("Setting device angle-snapping config");
Err(HwDeviceError::OpNotSupported {}.into())
}
fn get_debounce(&self) -> Result<bool> {
trace!("Querying device debounce config");
Err(HwDeviceError::OpNotSupported {}.into())
}
fn set_debounce(&mut self, _debounce: bool) -> Result<()> {
trace!("Setting device debounce config");
Err(HwDeviceError::OpNotSupported {}.into())
}
fn set_local_brightness(&mut self, brightness: i32) -> Result<()> {
trace!("Setting device specific brightness");
self.brightness = brightness;
Ok(())
}
fn get_local_brightness(&self) -> Result<i32> {
trace!("Querying device specific brightness");
Ok(self.brightness)
}
#[inline]
fn get_next_event(&self) -> Result<MouseHidEvent> {
self.get_next_event_timeout(-1)
}
fn get_next_event_timeout(&self, millis: i32) -> Result<MouseHidEvent> {
trace!("Querying control device for next event");
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else if !self.is_opened {
Err(HwDeviceError::DeviceNotOpened {}.into())
} else if !self.is_initialized {
Err(HwDeviceError::DeviceNotInitialized {}.into())
} else {
let ctrl_dev = self.ctrl_hiddev.as_ref().lock();
let ctrl_dev = ctrl_dev.as_ref().unwrap();
let mut buf = [0; 8];
match ctrl_dev.read_timeout(&mut buf, millis) {
Ok(size) => {
hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
let event = match buf[0..6] {
// Button reports (DPI)
[0x07, 0x04, 0x17, 0x01, level, _] => MouseHidEvent::DpiChange(level),
// Button reports
[button_mask, 0x00, button_mask2, 0x00, _] if size > 0 => {
let mut result = vec![];
let button_mask = button_mask.view_bits::<Lsb0>();
let button_mask2 = button_mask2.view_bits::<Lsb0>();
let mut button_states = self.button_states.lock();
// notify button press events for the buttons 0..7
for (index, down) in button_mask.iter().enumerate() {
if *down && !*button_states.get(index).unwrap() {
result.push(MouseHidEvent::ButtonDown(index as u8));
button_states.set(index, *down);
break;
}
}
// notify button press events for the buttons 8..15
for (index, down) in button_mask2.iter().enumerate() {
let index = index + 8; // offset by 8
if *down && !*button_states.get(index).unwrap() {
result.push(MouseHidEvent::ButtonDown(index as u8));
button_states.set(index, *down);
break;
}
}
// notify button release events for the buttons 0..7
for (index, down) in button_mask.iter().enumerate() {
if !*down && *button_states.get(index).unwrap() {
result.push(MouseHidEvent::ButtonUp(index as u8));
button_states.set(index, *down);
break;
}
}
// notify button release events for the buttons 8..15
for (index, down) in button_mask2.iter().enumerate() {
let index = index + 8; // offset by 8
if !*down && *button_states.get(index).unwrap() {
result.push(MouseHidEvent::ButtonUp(index as u8));
button_states.set(index, *down);
break;
}
}
if result.len() > 1 {
error!(
"We missed a HID event, mouse button states will be inconsistent"
);
}
if result.is_empty() {
MouseHidEvent::Unknown
} else {
debug!("{:?}", result[0]);
result[0]
}
}
_ => MouseHidEvent::Unknown,
};
Ok(event)
}
Err(_) => Err(HwDeviceError::InvalidResult {}.into()),
}
}
}
fn ev_key_to_button_index(&self, code: EV_KEY) -> Result<u8> {
match code {
EV_KEY::KEY_RESERVED => Ok(0),
EV_KEY::BTN_LEFT => Ok(1),
EV_KEY::BTN_MIDDLE => Ok(2),
EV_KEY::BTN_RIGHT => Ok(3),
EV_KEY::BTN_0 => Ok(4),
EV_KEY::BTN_1 => Ok(5),
EV_KEY::BTN_2 => Ok(6),
EV_KEY::BTN_3 => Ok(7),
EV_KEY::BTN_4 => Ok(8),
EV_KEY::BTN_5 => Ok(9),
EV_KEY::BTN_6 => Ok(10),
EV_KEY::BTN_7 => Ok(11),
EV_KEY::BTN_8 => Ok(12),
EV_KEY::BTN_9 => Ok(13),
EV_KEY::BTN_EXTRA => Ok(14),
EV_KEY::BTN_SIDE => Ok(15),
EV_KEY::BTN_FORWARD => Ok(16),
EV_KEY::BTN_BACK => Ok(17),
EV_KEY::BTN_TASK => Ok(18),
EV_KEY::KEY_0 => Ok(19),
EV_KEY::KEY_1 => Ok(20),
EV_KEY::KEY_2 => Ok(21),
EV_KEY::KEY_3 => Ok(22),
EV_KEY::KEY_4 => Ok(23),
EV_KEY::KEY_5 => Ok(24),
EV_KEY::KEY_6 => Ok(25),
EV_KEY::KEY_7 => Ok(26),
EV_KEY::KEY_8 => Ok(27),
EV_KEY::KEY_9 => Ok(28),
EV_KEY::KEY_MINUS => Ok(29),
EV_KEY::KEY_EQUAL => Ok(30),
_ => Err(HwDeviceError::MappingError {}.into()),
}
}
fn button_index_to_ev_key(&self, index: u32) -> Result<EV_KEY> {
match index {
0 => Ok(EV_KEY::KEY_RESERVED),
1 => Ok(EV_KEY::BTN_LEFT),
2 => Ok(EV_KEY::BTN_MIDDLE),
3 => Ok(EV_KEY::BTN_RIGHT),
4 => Ok(EV_KEY::BTN_0),
5 => Ok(EV_KEY::BTN_1),
6 => Ok(EV_KEY::BTN_2),
7 => Ok(EV_KEY::BTN_3),
8 => Ok(EV_KEY::BTN_4),
9 => Ok(EV_KEY::BTN_5),
10 => Ok(EV_KEY::BTN_6),
11 => Ok(EV_KEY::BTN_7),
12 => Ok(EV_KEY::BTN_8),
13 => Ok(EV_KEY::BTN_9),
14 => Ok(EV_KEY::BTN_EXTRA),
15 => Ok(EV_KEY::BTN_SIDE),
16 => Ok(EV_KEY::BTN_FORWARD),
17 => Ok(EV_KEY::BTN_BACK),
18 => Ok(EV_KEY::BTN_TASK),
19 => Ok(EV_KEY::KEY_0),
20 => Ok(EV_KEY::KEY_1),
21 => Ok(EV_KEY::KEY_2),
22 => Ok(EV_KEY::KEY_3),
23 => Ok(EV_KEY::KEY_4),
24 => Ok(EV_KEY::KEY_5),
25 => Ok(EV_KEY::KEY_6),
26 => Ok(EV_KEY::KEY_7),
27 => Ok(EV_KEY::KEY_8),
28 => Ok(EV_KEY::KEY_9),
29 => Ok(EV_KEY::KEY_MINUS),
30 => Ok(EV_KEY::KEY_EQUAL),
_ => Err(HwDeviceError::MappingError {}.into()),
}
}
fn send_led_map(&mut self, led_map: &[RGBA]) -> Result<()> {
trace!("Setting LEDs from supplied map...");
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else if !self.is_opened {
Err(HwDeviceError::DeviceNotOpened {}.into())
} else if !self.is_initialized {
Err(HwDeviceError::DeviceNotInitialized {}.into())
} else {
{
let led_dev = self.led_hiddev.as_ref().lock();
let led_dev = led_dev.as_ref().unwrap();
let buf: [u8; 65] = [
0x00,
0x10,
0x10,
0x0b,
0x00,
0x09,
0x64,
0x64,
0x64,
0x06,
(led_map[LED_0].r as f32 * (self.brightness as f32 / 100.0)).floor() as u8,
(led_map[LED_0].g as f32 * (self.brightness as f32 / 100.0)).floor() as u8,
(led_map[LED_0].b as f32 * (self.brightness as f32 / 100.0)).floor() as u8,
(led_map[LED_1].r as f32 * (self.brightness as f32 / 100.0)).floor() as u8,
(led_map[LED_1].g as f32 * (self.brightness as f32 / 100.0)).floor() as u8,
(led_map[LED_1].b as f32 * (self.brightness as f32 / 100.0)).floor() as u8,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
];
match led_dev.write(&buf) {
Ok(_result) => {
hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
let mut poll_cntr = 0;
'POLL_LOOP: loop {
let mut buf: [u8; 32] = [0x00; 32];
match led_dev.read_timeout(&mut buf, 10) {
Ok(_result) => {
hexdump::hexdump_iter(&buf).for_each(|s| trace!(" {}", s));
match buf[1] {
0x10 => break 'POLL_LOOP,
0x00 => break 'POLL_LOOP,
_ => { /* do nothing */ }
}
}
Err(e) => error!("Error in poll loop: {}", e),
}
if poll_cntr >= 5 {
break 'POLL_LOOP;
}
poll_cntr += 1;
thread::sleep(Duration::from_millis(10));
}
}
Err(_) => {
// the device has failed; maybe it has been disconnected?
self.is_initialized = false;
self.is_opened = false;
self.has_failed = true;
return Err(HwDeviceError::InvalidResult {}.into());
}
}
}
self.update_device_status()?;
Ok(())
}
}
fn set_led_init_pattern(&mut self) -> Result<()> {
trace!("Setting LED init pattern...");
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else if !self.is_opened {
Err(HwDeviceError::DeviceNotOpened {}.into())
} else if !self.is_initialized {
Err(HwDeviceError::DeviceNotInitialized {}.into())
} else {
let led_map: [RGBA; constants::CANVAS_SIZE] = [RGBA {
r: 0x00,
g: 0x00,
b: 0x00,
a: 0x00,
}; constants::CANVAS_SIZE];
self.send_led_map(&led_map)?;
Ok(())
}
}
fn set_led_off_pattern(&mut self) -> Result<()> {
trace!("Setting LED off pattern...");
if !self.is_bound {
Err(HwDeviceError::DeviceNotBound {}.into())
} else if !self.is_opened {
Err(HwDeviceError::DeviceNotOpened {}.into())
} else if !self.is_initialized {
Err(HwDeviceError::DeviceNotInitialized {}.into())
} else {
let led_map: [RGBA; constants::CANVAS_SIZE] = [RGBA {
r: 0x00,
g: 0x00,
b: 0x00,
a: 0x00,
}; constants::CANVAS_SIZE];
self.send_led_map(&led_map)?;
Ok(())
}
}
fn has_secondary_device(&self) -> bool {
false
}
} |
import { SemanticClass } from "../../lib/parser";
import { db } from "../state";
import { vscode } from "../vscode";
export class SemanticTokensProvider implements vscode.DocumentSemanticTokensProvider {
legend: vscode.SemanticTokensLegend;
keywordToken: number;
commentToken: number;
variableToken: number;
propetyToken: number;
enumMemberToken: number;
enumToken: number;
classToken: number;
structToken: number;
typeToken: number;
operatorToken: number;
stringToken: number;
numberToken: number;
functionToken: number;
macroToken: number;
labelToken: number;
modifierDeclarationToken: number;
readonlyToken: number;
types: string[];
modifiers: string[];
constructor() {
// https://code.visualstudio.com/api/language-extensions/semantic-highlight-guide
this.types = [
'namespace',
'class',
'enum',
'interface',
'struct',
'typeParameter',
'type',
'parameter',
'variable',
'property',
'enumMember',
'decorator',
'event',
'function',
'method',
'macro',
'label',
'comment',
'string',
'keyword',
'number',
'regexp',
'operator', // For tokens that represent an operator.
];
this.modifiers = [
'declaration',
'definition',
'readonly',
'static',
'deprecated',
'abstract',
'async',
'modification',
'documentation',
'defaultLibrary', // For symbols that are part of the standard library.
];
this.keywordToken = this.types.indexOf('keyword');
this.commentToken = this.types.indexOf('comment');
this.variableToken = this.types.indexOf('variable');
this.propetyToken = this.types.indexOf('property');
this.enumMemberToken = this.types.indexOf('enumMember');
this.enumToken = this.types.indexOf('enum');
this.classToken = this.types.indexOf('class');
this.structToken = this.types.indexOf('struct');
this.typeToken = this.types.indexOf('type');
this.operatorToken = this.types.indexOf('operator');
this.stringToken = this.types.indexOf('string');
this.numberToken = this.types.indexOf('number');
this.functionToken = this.types.indexOf('method');
this.macroToken = this.types.indexOf('macro');
this.labelToken = this.types.indexOf('label');
this.modifierDeclarationToken = this.modifiers.indexOf('declaration');
this.readonlyToken = this.modifiers.indexOf('readonly');
this.legend = new vscode.SemanticTokensLegend(this.types, this.modifiers);
}
provideDocumentSemanticTokens(document: vscode.TextDocument, ctoken: vscode.CancellationToken) {
const ast = db.updateDocumentAndGetAst(document, ctoken);
const tokensBuilder = new vscode.SemanticTokensBuilder(this.legend);
// on line 1, characters 1-5 are a class declaration
for (const token of ast.tokens) {
let type: number | undefined = undefined;
let modifier: number | undefined = undefined;
switch (token.type) {
case SemanticClass.Comment:
type = this.commentToken;
break;
case SemanticClass.ModifierKeyword:
case SemanticClass.Keyword:
type = this.keywordToken;
break;
case SemanticClass.StructMember:
case SemanticClass.StructMemberDeclaration:
type = this.propetyToken;
modifier = this.modifierDeclarationToken;
break;
case SemanticClass.ClassVariable:
type = this.propetyToken;
break;
case SemanticClass.EnumMember:
type = this.enumMemberToken;
break;
case SemanticClass.EnumDeclaration:
type = this.enumToken;
modifier = this.modifierDeclarationToken;
break;
case SemanticClass.StructDeclaration:
type = this.structToken;
modifier = this.modifierDeclarationToken;
break;
case SemanticClass.ClassDeclaration:
type = this.classToken;
modifier = this.modifierDeclarationToken;
break;
case SemanticClass.ClassReference:
type = this.classToken;
break;
case SemanticClass.TypeReference:
type = this.typeToken;
break;
case SemanticClass.Operator:
case SemanticClass.AssignmentOperator:
type = this.operatorToken;
break;
case SemanticClass.ClassConstant:
type = this.propetyToken;
modifier = this.readonlyToken;
break;
case SemanticClass.ObjectReferenceName:
type = this.stringToken;
break;
case SemanticClass.LiteralName:
type = this.stringToken;
break;
case SemanticClass.LiteralString:
// skip, tmGrammer has better highlight for escapes
// type = TOKEN_TYPE_STRING;
break;
case SemanticClass.LiteralNumber:
type = this.numberToken;
break;
case SemanticClass.FunctionDeclaration:
modifier = this.modifierDeclarationToken;
case SemanticClass.FunctionReference:
type = this.functionToken;
break;
case SemanticClass.LocalVariable:
type = this.variableToken;
break;
case SemanticClass.VariableReference:
type = this.variableToken;
break;
case SemanticClass.ExecInstruction:
// skip this until tmGrammar has proper syntax
// type = TOKEN_TYPE_MACRO;
break;
case SemanticClass.LanguageConstant:
// skip for now, tmGrammar identifies this type of constant
// type = TOKEN_TYPE_KEYWORD;
break;
case SemanticClass.StatementLabel:
type = this.labelToken;
break;
}
if (type !== undefined) {
tokensBuilder.push(
token.line, token.position, token.text.length, type, modifier
);
}
}
return tokensBuilder.build();
}
} |
import React from "react";
//packages
import { LoaderFunction, useLoaderData } from "react-router-dom";
import InfiniteScroll from "react-infinite-scroller";
import { isAxiosError } from "axios";
import uniqBy from "lodash/uniqBy";
// axios
import axiosInstance from "../../apis/axiosInstance";
// types
import {
GifListResponseDTO,
GifResponseType,
} from "../../dto/gif-response.dto";
// UI components
import { GifList } from "../../components";
// hooks
import useGifApi from "../../apis/hooks/useGifApi";
import FakeGifList from "../../components/lists/fake-gif-list/fake-gif-list";
const TrendingPage: React.FC = () => {
const { data } = useLoaderData() as GifListResponseDTO;
const [gifList, setGifList] = React.useState<GifResponseType[]>(data);
const [count, setCount] = React.useState<number>(50);
const { getTrendingGifs } = useGifApi();
const handleFetchMore = async (page: number) => {
try {
const { data } = await getTrendingGifs(
`api_key=${import.meta.env.VITE_GIPHY_API_KEY}&&offset=${page * 50}`
);
//** duplicated results existed in the trending api */
//** filter them by their ids */
const gifUniq = uniqBy([...gifList, ...data.data], "id");
setGifList(gifUniq);
setCount(data.pagination.total_count);
} catch (error) {
if (isAxiosError(error)) {
//todo display error here*/
}
} finally {
// setIsLoading(false);
}
};
return (
<div className="trending-page">
<InfiniteScroll
pageStart={0}
loadMore={handleFetchMore}
hasMore={gifList.length <= count || true}
loader={<FakeGifList />}
>
<GifList list={gifList} />
</InfiniteScroll>
</div>
);
};
// ** don't need to handle the error here /
//** it will be handled in react router's error page */
export const TrendingPageLoader: LoaderFunction = async () => {
const result = await axiosInstance.get<GifListResponseDTO>(
`trending?api_key=${import.meta.env.VITE_GIPHY_API_KEY}`
);
return result.data;
};
export default TrendingPage; |
<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { noteListApi, noteDeleteApi, noteInfoApi, noteTopicsApi } from "@/api/note"
import { noteListRequest } from "@/api/note/types"
import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { Note } from "@/api/note/types"
import router from "@/router"
import { OptionIface } from "types/api"
defineOptions({
name: "NoteList"
})
const loading = ref<boolean>(false)
const previewDialog = ref({
visible: false,
title: "",
content: ""
})
const topicOptions = ref<OptionIface[]>([])
noteTopicsApi().then((resp) => {
resp.data.forEach((v) => {
topicOptions.value.push({ value: v, label: v })
})
})
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const handleDelete = (row: Note) => {
ElMessageBox.confirm(`< ${row.title} >`, "删除笔记", {
confirmButtonText: "删除",
cancelButtonText: "取消",
type: "warning"
}).then(() => {
noteDeleteApi(row.id).then(() => {
ElMessage.success("删除成功")
handleRefresh()
})
})
}
const currentUpdateId = ref<number>(0)
const handleSave = (row: Note | null) => {
if (row != null) {
currentUpdateId.value = row.id
}
router.push({
path: "/note/editor",
query: { id: currentUpdateId.value }
})
}
const tableData = ref<Note[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
keyword: "",
topic: "",
timeRange: ""
})
// 刷新列表
const handleRefresh = () => {
loading.value = true
const params: noteListRequest = {
pager: {
index: paginationData.currentPage,
size: paginationData.pageSize,
count: paginationData.total,
disable: false
},
keyword: searchData.keyword,
topic: searchData.topic
}
if (searchData.timeRange.length === 2) {
params.updateTimeRange = {
left: (searchData.timeRange[0] as unknown as Date).getTime() / 1000,
right: (searchData.timeRange[1] as unknown as Date).getTime() / 1000 + 86400
}
}
noteListApi(params)
.then((resp) => {
paginationData.total = resp.data.pager.count
tableData.value = resp.data.list
})
.catch(() => {
tableData.value = []
})
.finally(() => {
loading.value = false
})
}
// 搜索
const handleSearch = () => {
if (paginationData.currentPage === 1) {
handleRefresh()
}
paginationData.currentPage = 1
}
// 重置搜索条件
const resetSearch = () => {
searchFormRef.value?.resetFields()
if (paginationData.currentPage === 1) {
handleRefresh()
}
paginationData.currentPage = 1
}
// 预览
const contentPreview = (row: Note) => {
noteInfoApi(row.id)
.then((resp) => {
previewDialog.value.visible = true
previewDialog.value.title = resp.data.title
previewDialog.value.content = resp.data.content
})
.finally(() => {
loading.value = false
})
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], handleRefresh, { immediate: true })
</script>
<template>
<div class="app-container">
<el-card v-loading="loading" shadow="never" class="search-wrapper">
<el-form ref="searchFormRef" :inline="true" :model="searchData">
<el-form-item prop="keyword" label="关键词">
<el-input v-model="searchData.keyword" placeholder="关键词" />
</el-form-item>
<el-form-item prop="topic" label="主题">
<el-select v-model="searchData.topic" filterable placeholder="选择主题">
<el-option
v-for="item in topicOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</el-form-item>
<el-form-item prop="timeRange" label="时间">
<el-date-picker
v-model="searchData.timeRange"
type="daterange"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
<el-button :icon="Refresh" @click="resetSearch">重置</el-button>
</el-form-item>
</el-form>
</el-card>
<el-card v-loading="loading" shadow="never">
<div class="toolbar-wrapper">
<div>
<el-button type="primary" :icon="CirclePlus" @click="handleSave(null)">新增笔记</el-button>
</div>
<div>
<el-tooltip content="刷新表格">
<el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
</el-tooltip>
</div>
</div>
<div class="table-wrapper">
<el-table :data="tableData">
<el-table-column width="50" align="center" />
<el-table-column prop="id" label="ID" width="50" align="center" />
<el-table-column prop="title" label="标题" align="center" />
<el-table-column label="主题" align="center">
<template #default="scope">
<el-tag>{{ scope.row.topic }}</el-tag>
</template>
</el-table-column>
<el-table-column prop="createTime" label="创建时间" align="center" />
<el-table-column prop="updateTime" label="更新时间" align="center" />
<el-table-column fixed="right" label="操作" width="200" align="center">
<template #default="scope">
<el-button type="primary" text bg size="small" @click="contentPreview(scope.row)"
>预览</el-button
>
<el-button type="primary" text bg size="small" @click="handleSave(scope.row)"
>修改</el-button
>
<el-button type="danger" text bg size="small" @click="handleDelete(scope.row)"
>删除</el-button
>
</template>
</el-table-column>
</el-table>
</div>
<el-dialog v-model="previewDialog.visible" :title="previewDialog.title" width="40%">
<v-md-preview :text="previewDialog.content" />
<template #footer>
<span class="dialog-footer">
<el-button type="primary" @click="previewDialog.visible = false"> 关闭 </el-button>
</span>
</template>
</el-dialog>
<div class="pager-wrapper">
<el-pagination
background
:layout="paginationData.layout"
:page-sizes="paginationData.pageSizes"
:total="paginationData.total"
:page-size="paginationData.pageSize"
:currentPage="paginationData.currentPage"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
/>
</div>
</el-card>
</div>
</template>
<style lang="scss" scoped>
.search-wrapper {
margin-bottom: 20px;
:deep(.el-card__body) {
padding-bottom: 2px;
}
}
.toolbar-wrapper {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
}
.table-wrapper {
margin-bottom: 20px;
}
.pager-wrapper {
display: flex;
justify-content: flex-end;
}
</style> |
import { DocumentType } from "@typegoose/typegoose";
import { CommandInteraction, Message } from "discord.js";
import AdminCommands from ".";
import Global, { ModulePrices } from "../../models/global";
import User from "../../models/user";
import embeds from "../../util/embed";
import { confirmator } from "../../util/questions";
import _ from "lodash";
import { SlashCommandBuilder } from "@discordjs/builders";
export default class ModulePriceCommand extends AdminCommands {
slashCommand = new SlashCommandBuilder()
.setName("prices")
.setDescription("Change the prices of the modules.")
.addStringOption(sub =>
sub.setName("module name").setDescription("The module name.").setRequired(true))
.addNumberOption(sub =>
sub.setName("amount").setDescription("The new price of the module.").setRequired(true));
async run(
interaction: CommandInteraction,
_userData: DocumentType<User>,
globalData: DocumentType<Global>
) {
const modules: string[] = _.sortedUniq(
this.client.commands
.map((x) => x.groupName)
.filter((x) => !x.toLowerCase().includes("admin"))
);
const moduleName = interaction.options.getString("module name").toLowerCase();
if (!modules?.includes(moduleName))
return interaction.reply({
embeds: [
embeds.error(
`Please choose from the following modules: ${modules.join(", ")}`
)
]
});
const price = interaction.options.getNumber("amount");
if (!price)
return interaction.reply({
embeds: [
embeds.error(`Please provide the new price of the module.`)
]
});
const confirm = await confirmator(
interaction,
`Are you sure you would like to change the price of the module **${moduleName}** to **$${price}**?`
);
if (confirm) {
globalData.modulePrices[moduleName as keyof ModulePrices] = price;
await globalData.save();
return interaction.reply({
embeds: [
embeds.normal(
`Module Price Edited`,
`The price of the module **${moduleName}** has been set to **$${price}**!`
)
]
});
}
}
} |
IP-WATCHER(1) User Contributed Perl Documentation IP-WATCHER(1)
NNAAMMEE
ip-watcher - watch the status of an IP address and notify the user of
it's status.
SSYYNNOOPPSSIISS
ip-watcher <options> <ip-address> <email-address>
See below for more information on the various switches available.
UUSSAAGGEE
# Typical usage -- watch 127.0.0.1 and notify jbraum@music.org
$ ip-watcher 127.0.0.1 jbraum@music.org
DDEESSCCRRIIPPTTIIOONN
This script will watch the status of an IP address and notify the user
when it has gone up or down. ip-watcher can be configured to notify the
user when the IP address to monitor has been down or up for N number of
checks. Additionally, this script is designed to be run as a daemon. As
such, it will automatically fork into the background and monitor things
from there.
ip-watcher is also designed to log messages to the daemon syslog facil-
ity, thus freeing up your terminal from the messages it would otherwise
spew all over.
To shutdown ip-watcher from the daemonized state, simply send a kill
signal of SIGINT, SIGQUIT, SIGABRT, or SIGTERM. Please refrain from
using SIGKILL, as this is usually reserved for emergency system func-
tions, or shutdown needs and will not notify the user when it is being
shut down.
OOPPTTIIOONNSS
--help
Show a quick bit of usage help.
--mail-from=<email-address>
Set the email address for the From: headers for all notifications.
If this is not specified on the command line, it defaults to
"ip-watcher".
--sleep-secs=<num>
Set the amount of time to sleep between ping checks. The default
when this is not specified is 5 seconds. NOTE: don't set this to 0
or you'll be very sorry. :)
--email-delay=<num>
Set the number of consecutive times that a ping must succeed or
fail before the user is notified of the state change. This is use-
ful as it helps to prevent "flapping" of notifications when a
server is going a bit nutty. Note that setting this value too high
can cause ip-watcher to not detect a true failure, and setting it
too low can annoy the heck out of the owner of the email address.
Defaults to a reasonable 5.
--daemonize
--no-daemonize
Toggle whether ip-watcher should fork into the background. The
default is to go ahead and daemonize. Note that specifying
--no-daemonize on the command line will result in all log messages
going to the terminal, as logging all that cruft to syslog while
running in the foreground is mostly pointless.
--syslogging
--no-syslogging
Toggle whether or not ip-watcher should log it's output to the sys-
log or to stdout instead. This allows you to have ip-watcher run-
ning as a daemon and yet still output log messages to your terminal
if you need to debug something. Mostly useful to developers only.
Defaults to syslogging, unless --no-daemonize is specified, which
implies --no-syslogging.
--ping=<filename>
The fully qualified pathname to the ping utility. If this is not
specified, ip-watcher will attempt to guess at where ping is by
scanning the PATH environment variable. Note that this program must
be executable by the user ip-watcher runs as, and must accept the
-c command line parameter (count).
CCOOPPYYRRIIGGHHTT
Copyright(C) 2006, June R. Tate-Gans <june@theonelab.com>
LLIICCEENNSSEE
This file is a part of ip-watcher.
ip-watcher 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.
ip-watcher is distributed in the hope that it will be useful, but WITH-
OUT ANY WARRANTY; without even the immplied 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 ip-watcher; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
BBUUGGSS
+o While running the ping command, ip-watcher will be placed into a
sleeping state and not respond to signals. Possibly fixable through
a refactoring of the _p_i_n_g_C_h_e_c_k_(_) subroutine to not use _s_y_s_t_e_m_(_)
calls.
+o Relies upon the ping binary to do the heavy lifting work of the
whole script. This is not portable, and should be really integrated
into the heart of the script itself either through a CPAN module,
or by being written directly into it.
+o The _f_i_n_d_P_i_n_g_(_) routine is not portable across non-POSIX architec-
tures.
+o None of the signal handling routines are portable across non-POSIX
architectures.
SSEEEE AALLSSOO
_p_i_n_g(8)
perl v5.8.6 2006-01-28 IP-WATCHER(1) |
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TaskController;
use App\Http\Controllers\CalendarController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/AddSchedule', [TaskController::class, 'create']);
Route::resource('tasks', 'App\Http\Controllers\TaskController');
Route::get('/dashboard', [TaskController::class, 'index']);
Route::post('/dashboard/store', [TaskController::class, 'store']);
Route::get('/edit-{id}', [TaskController::class, 'edit']);
Route::put('/dashboard/{id}', [TaskController::class, 'update']);
Route::delete('/dashboard/{id}', [TaskController::class, 'delete']);
Route::get('/dashboard/{id}', [TaskController::class, 'show']);
Route::get('/calendar', [CalendarController::class, 'index']);
Route::get('/events', [CalendarController::class, 'events']); |
class StopThread implements Runnable {
private boolean flag = true;
public synchronized void run() {
while(flag) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "-Exception~!");
/**
* 这时候再去设置flag标志位
*/
flag = false;
}
System.out.println(Thread.currentThread().getName() + "-run");
}
}
public void changeFlag() {
flag = false;
}
}
public class StopThreadDemo {
public static void main(String[] args) {
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.start();
int num = 0;
while(true) {
if(num ++ == 60) {
// st.changeFlag();
/**
* interrupt:当线程调用该方法的时候, 会强制从他的wait或者是sleep状态中恢复,但是会报
* InterruptedException异常。
* 当没有指定的方式让冻结的线程恢复到运行状态时,
* 这是需要对冻结的进行清除。
* 强制让线程恢复到运行中来。这样就可以让线程结束。
* sleep,wait,join都可以被中断
*/
t1.interrupt();
t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName() + "..." + num);
}
System.out.println("main over");
}
} |
import { useContext, useRef, useState } from 'react'
import { AuthContext } from '../../context/authContext'
import './login.scss'
import { Link, useNavigate } from 'react-router-dom'
const Login = () => {
const [state, setState] = useState({
error: "",
status: ""
})
const { login, currentUser } = useContext(AuthContext)
const username = useRef(null)
const password = useRef(null)
const navigate = useNavigate()
const handleLogin = async (e) => {
e.preventDefault()
setState({ status: "pending", error: "" })
try {
const response = await login({ username: username.current.value, password: password.current.value })
setState({ status: "fullfilled", error: "" })
navigate("/")
} catch (err) {
setState({ status: "fullfilled", error: err.message })
}
}
return (
<div className='login'>
<div className="card">
<div className="left">
<h1>Hello World!</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ullam optio corrupti quisquam cupiditate voluptatum esse minima eum aliquam laboriosam quod suscipit, repudiandae nisi architecto officiis iste explicabo porro nihil velit.</p>
<span>Don't you have an account?</span>
<Link to='/register'>
<button>Register</button>
</Link>
</div>
<div className="right">
<h1>Login</h1>
<form>
<input ref={username} type="text" placeholder='Username' />
<input ref={password} type="password" placeholder='Password' />
{state.error && <span style={{ color: "red" }}>{state.error}</span>}
<button onClick={handleLogin} disabled={state.status === "pending" ? true : false}>{state.status === "pending" ? "Loading..." : "Login"}</button>
</form>
</div>
</div>
</div>
)
}
export default Login |
import React, { useState } from "react";
import {
Paper,
Input,
Button,
FormControl,
InputLabel,
CircularProgress,
Modal,
IconButton,
} from "@mui/material";
import { Candidate } from "../../types/candidate";
import { Formik } from "formik";
import axios, { AxiosError, AxiosResponse } from "axios";
import { Role } from "../../types/roles";
import { Meeting } from "../../types/meetings";
import { InterviewForm } from "../../helpers/validation";
import { Notifier } from "../notifier";
import { Close } from "@mui/icons-material";
interface ScheduleProps {
candidate: Candidate;
role: Role;
close: () => void;
}
export const ScheduleInterview: React.FC<ScheduleProps> = ({
candidate,
role,
close
}) => {
const [loading, setLoading] = useState<boolean>();
const [meetingInfo, setMeetingInfo] = useState<Meeting>();
const [status, setStatus] = useState<{ [key: string]: any }>({
open: false,
});
//* closes the notifier and clears notification state
const clearStatus = () => setStatus({ open: false });
return (
<div>
<Modal
className="flex justify-center"
open={status?.open ? true : false}
onClose={clearStatus}
>
<Notifier
topic={status?.topic ?? ""}
content={status?.content ?? ""}
close={clearStatus}
/>
</Modal>
<Paper className="w-[700px] bg-slate-100 p-4 mt-4 h-[550px] flex flex-col">
<div className="flex flex-row justify-between">
<p className="text-green-700 text-xl font-semibold">
Schedule Interview
</p>
<IconButton onClick={close}>
<Close />
</IconButton>
</div>
<div className="mt-10">
<form>
<Formik
validationSchema={InterviewForm}
initialValues={{
topic: "",
date: "",
time: "",
}}
onSubmit={(value, { validateForm }) => {
validateForm(value);
var body = {
date: value.date,
time: value.time,
topic: value.topic,
participantId: candidate.id,
firstName: candidate.firstName,
lastName: candidate.lastName,
email: candidate.email,
jobTitle: role.name,
jobId: role.id,
};
setLoading(true);
console.log(body)
//* creates a new online meeting
axios
.post(process.env.NEXT_PUBLIC_CREATE_MEETING as string, body)
.then((res: AxiosResponse) => {
//* if operation is successful
if (res.data.code == 200) {
setMeetingInfo(res.data.data);
setLoading(false);
} else if (res.data.code == 401) {
setLoading(false)
setStatus({
open: true,
topic: "Unsuccessful",
content: res.data.message,
});
}
})
.catch((err: AxiosError) => {
setStatus({
open: true,
topic: "Unsuccessful",
content: err.message,
});
setLoading(false);
});
}}
>
{({ handleChange, handleSubmit, values, errors }) => (
<div className="grid justify-center">
<div className="flex flex-row gap-7">
<FormControl>
<div className="text-[12px] mb-1">Day</div>
<Input
value={values.date}
onChange={handleChange("date")}
className="text-black bg-white rounded-md h-[40px] w-[250px] px-2"
type="date"
/>
<div className="text-red-600 text-[10px] ml-4">
{errors.date as any}
</div>
</FormControl>
<FormControl>
<div className="text-[12px] mb-1">Time</div>
<Input
value={values.time}
onChange={handleChange("time")}
className="text-black bg-white rounded-md h-[40px] w-[250px] px-2"
type="time"
/>
<div className="text-red-600 text-[10px] ml-4">
{errors.time as any}
</div>
</FormControl>
</div>
<div className="flex flex-row gap-7 mt-8">
<FormControl>
<InputLabel>Candidate</InputLabel>
<Input
value={candidate.email}
readOnly
className="text-black bg-white rounded-md h-[40px] w-[250px] px-2"
type="text"
/>
</FormControl>
<FormControl>
<InputLabel>Topic</InputLabel>
<Input
value={"Invitation for an Interactive Session"}
onChange={handleChange("topic")}
className="text-black bg-white rounded-md h-[40px] w-[250px] px-2"
type="text"
readOnly
/>
<div className="text-red-600 text-[10px] ml-4">
{errors.topic as any}
</div>
</FormControl>
</div>
<Button
onClick={() => handleSubmit()}
className="bg-green-700 h-[50px] text-white mt-[30px]"
>
{loading ? (
<CircularProgress thickness={5} className="text-white" />
) : (
<p>Schedule</p>
)}
</Button>
</div>
)}
</Formik>
</form>
<div className="mt-[20px] px-6">
<div className="flex flex-row bg-white rounded-md p-0.5 px-2 mt-2 gap-2">
<p>MeetingId:</p>
<p className="text-green-700 font-semibold">
{meetingInfo?.meetingId}
</p>
</div>
<div className="flex flex-row bg-white rounded-md p-0.5 px-2 mt-2 gap-2">
<p>Password:</p>
<p className="text-green-700 font-semibold">
{meetingInfo?.password}
</p>
</div>
<div className="flex flex-row bg-white rounded-md p-0.5 px-2 mt-2 gap-2">
<p>Meeting Link:</p>
<p className="text-green-700 font-semibold">
{meetingInfo?.link}
</p>
</div>
<div className="flex flex-row bg-white rounded-md p-0.5 px-2 mt-2 gap-2">
<p>Date:</p>
{meetingInfo?.date && (
<div>
<p className="text-green-700 font-semibold">
{meetingInfo?.date?.split(" ")?.[0]}
</p>
</div>
)}
</div>
<div className="flex flex-row bg-white rounded-md p-0.5 px-2 mt-2 gap-2">
<p>Time:</p>
{meetingInfo?.date && (
<div>
<p className="text-green-700 font-semibold">
{meetingInfo?.date?.split(" ")?.[1]}
</p>
</div>
)}
</div>
</div>
</div>
</Paper>
</div>
);
}; |
#include <Wire.h>
#include <esp_now.h>
#include <WiFi.h>
#include "base64.hpp"
// Pin analog untuk LM35
const int lm35Pin = A0;
esp_now_peer_info_t peerInfo;
// Alamat MAC ESP-NOW penerima
uint8_t receiverMacAddress[] = { 0xc8, 0xf0, 0x9e, 0x4f, 0xe1, 0xb4};
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
if (status == ESP_NOW_SEND_SUCCESS) {
Serial.println("Delivery Success");
Serial.println("Masuk ke deep sleep...");
delay(100);
// Masuk ke deep sleep
esp_deep_sleep_start();
} else {
Serial.println("Delivery Fail");
}
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
esp_now_register_send_cb(OnDataSent);
// register peer
peerInfo.channel = 0;
peerInfo.encrypt = false;
// register first peer
memcpy(peerInfo.peer_addr, receiverMacAddress, 6);
if (esp_now_add_peer(&peerInfo) != ESP_OK) {
Serial.println("Failed to add peer");
return;
}
esp_sleep_enable_timer_wakeup(10e6);
}
void loop() {
// Baca nilai analog dari LM35
int lm35Value = analogRead(lm35Pin);
// Konversi nilai analog menjadi suhu dalam derajat Celsius
float temperature = (lm35Value * 3.3 / 4095) * 100;
Serial.println("");
Serial.println("Temperature: ");
Serial.print(temperature);
Serial.println("°C");
// Encode data menggunakan base64
unsigned char encodedData[20];
int encodedLength = encode_base64((unsigned char *)&temperature, sizeof(temperature), encodedData);
// Kirim data melalui ESP-NOW
if (esp_now_send(receiverMacAddress, encodedData, encodedLength) != ESP_OK) {
Serial.println("Failed to send data");
} else {
Serial.print("Sent encoded data: ");
Serial.println((char *)encodedData);
}
delay(1000);
} |
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import soccerteam.Player;
import soccerteam.Position;
import soccerteam.Team;
import soccerteam.TeamImpl;
/**
* Tests for Team.
*/
public class TeamTest {
private Team team9;
private Team team16;
private Team team21;
private Player player1;
private Player player2;
private Player player3;
private Player player4;
private Player player5;
private Player player6;
private Player player7;
private Player player8;
private Player player9;
private Player player10;
private Player player11;
private Player player12;
private Player player13;
private Player player14;
private Player player15;
private Player player16;
private Player player17;
private Player player18;
private Player player19;
private Player player20;
private Player player21;
/**
* Setting up some objects of Team and Player.
*/
@Before
public void setUp() {
team9 = new TeamImpl();
team16 = new TeamImpl();
team21 = new TeamImpl();
player1 = new Player("Ethan", "Smith", LocalDate.of(2013, 12,
1), Position.FORWARD, 3);
player2 = new Player("Olivia", "Rodriguez", LocalDate.of(2014, 2,
14), Position.DEFENDER, 2);
player3 = new Player("Mason", "Johnson", LocalDate.of(2015, 9,
5), Position.MIDFIELDER, 4);
player4 = new Player("Sophia", "Brown", LocalDate.of(2014, 6,
30), Position.GOALIE, 1);
player5 = new Player("Liam", "Perez", LocalDate.of(2013, 11,
9), Position.FORWARD, 5);
player6 = new Player("Emma", "Hernandez", LocalDate.of(2015, 4,
2), Position.DEFENDER, 3);
player7 = new Player("Noah", "Davis", LocalDate.of(2013, 7,
15), Position.MIDFIELDER, 2);
player8 = new Player("Ava", "Martinez", LocalDate.of(2014, 9,
28), Position.GOALIE, 4);
player9 = new Player("William", "Wilson", LocalDate.of(2015, 2,
25), Position.FORWARD, 1);
player10 = new Player("Isabella", "Taylor", LocalDate.of(2013, 12,
10), Position.DEFENDER, 5);
player11 = new Player("James", "Thomas", LocalDate.of(2014, 10,
21), Position.MIDFIELDER, 3);
player12 = new Player("Mia", "Anderson", LocalDate.of(2015, 3,
19), Position.GOALIE, 2);
player13 = new Player("Benjamin", "Martin", LocalDate.of(2013, 5,
7), Position.FORWARD, 4);
player14 = new Player("Charlotte", "Garcia", LocalDate.of(2014, 1,
18), Position.DEFENDER, 1);
player15 = new Player("Samuel", "Rodriguez", LocalDate.of(2015, 8,
22), Position.MIDFIELDER, 5);
player16 = new Player("Abigail", "Perez", LocalDate.of(2013, 6,
13), Position.GOALIE, 3);
player17 = new Player("Daniel", "Hernandez", LocalDate.of(2014,
12, 9), Position.FORWARD, 2);
player18 = new Player("Emily", "Davis", LocalDate.of(2015, 5,
3), Position.DEFENDER, 4);
player19 = new Player("Michael", "Wilson", LocalDate.of(2014, 11,
26), Position.MIDFIELDER, 1);
player20 = new Player("Harper", "Taylor", LocalDate.of(2013, 3,
8), Position.GOALIE, 5);
player21 = new Player("Jacob", "Thomas", LocalDate.of(2014, 7,
4), Position.FORWARD, 3);
}
/**
* Helper method to add 9 players to team9.
*/
public void team9Helper() {
team9.addPlayer(player1);
team9.addPlayer(player2);
team9.addPlayer(player3);
team9.addPlayer(player4);
team9.addPlayer(player5);
team9.addPlayer(player6);
team9.addPlayer(player7);
team9.addPlayer(player8);
team9.addPlayer(player9);
}
/**
* Helper method to add 16 players to team16.
*/
public void team16Helper() {
team16.addPlayer(player1);
team16.addPlayer(player2);
team16.addPlayer(player3);
team16.addPlayer(player4);
team16.addPlayer(player5);
team16.addPlayer(player6);
team16.addPlayer(player7);
team16.addPlayer(player8);
team16.addPlayer(player9);
team16.addPlayer(player10);
team16.addPlayer(player11);
team16.addPlayer(player12);
team16.addPlayer(player13);
team16.addPlayer(player14);
team16.addPlayer(player15);
team16.addPlayer(player16);
}
/**
* Helper method to add 21 players to team21.
*/
public void team21Helper() {
team21.addPlayer(player1);
team21.addPlayer(player2);
team21.addPlayer(player3);
team21.addPlayer(player4);
team21.addPlayer(player5);
team21.addPlayer(player6);
team21.addPlayer(player7);
team21.addPlayer(player8);
team21.addPlayer(player9);
team21.addPlayer(player10);
team21.addPlayer(player11);
team21.addPlayer(player12);
team21.addPlayer(player13);
team21.addPlayer(player14);
team21.addPlayer(player15);
team21.addPlayer(player16);
team21.addPlayer(player17);
team21.addPlayer(player18);
team21.addPlayer(player19);
team21.addPlayer(player20);
team21.addPlayer(player21);
}
/**
* Test for addPlayer method.
*/
@Test
public void testAddPlayer() {
team9Helper();
team16Helper();
team21Helper();
assertEquals(9, team9.getTeam().size());
assertEquals(16, team16.getTeam().size());
assertEquals(21, team21.getTeam().size());
}
@Test
public void testRemovePlayer() {
team9Helper();
team16Helper();
team9.removePlayer("Ethan", "Smith");
team16.removePlayer("Mason", "Johnson");
assertEquals(8, team9.getTeam().size());
assertEquals(15, team16.getTeam().size());
}
/**
* Test for createTeam method with invalid number of players (less than 10).
*/
@Test (expected = IllegalArgumentException.class)
public void testInvalidCreateTeam() {
// team9 has 9 players
team9Helper();
team9.createTeam();
}
/**
* Test for createTeam method with valid number of players.
*/
@Test
public void testCreateTeam() {
// test for add 10 players
team9Helper();
team9.addPlayer(player10);
team9.createTeam();
assertEquals(10, team9.getTeam().size());
// test for add players' number between 10 and 20
team16Helper();
team16.createTeam();
assertEquals(16, team16.getTeam().size());
// test for add more than 20 players
team21Helper();
team21.createTeam();
assertEquals(20, team21.getTeam().size());
}
/**
* Test for getTeam method.
*/
@Test
public void getTeam() {
List<Player> copyTeam16 = new ArrayList<>();
copyTeam16.add(player1);
copyTeam16.add(player2);
copyTeam16.add(player3);
copyTeam16.add(player4);
copyTeam16.add(player5);
copyTeam16.add(player6);
copyTeam16.add(player7);
copyTeam16.add(player8);
copyTeam16.add(player9);
copyTeam16.add(player10);
copyTeam16.add(player11);
copyTeam16.add(player12);
copyTeam16.add(player13);
copyTeam16.add(player14);
copyTeam16.add(player15);
copyTeam16.add(player16);
team16Helper();
assertEquals(copyTeam16, team16.getTeam());
}
/**
* Test for getStartingLineUp method.
*/
@Test
public void getStartingLineUp() {
List<Player> copyStartingLineUp21 = new ArrayList<>();
copyStartingLineUp21.add(player20);
copyStartingLineUp21.add(player8);
copyStartingLineUp21.add(player10);
copyStartingLineUp21.add(player3);
copyStartingLineUp21.add(player13);
copyStartingLineUp21.add(player15);
copyStartingLineUp21.add(player5);
team21Helper();
team21.createTeam();
assertEquals(copyStartingLineUp21, team21.getStartingLineUp());
}
/**
* Test for getTeamSize method.
*/
@Test
public void testGetTeamSize() {
team21Helper();
team21.createTeam();
assertEquals(20, team21.getTeamSize());
}
/**
* Test for getTeamInfo method.
* Since jersey number will change every time we create a team, we delete the jersey number
* in the expected string and actual string, and see if other information matches.
* Also, check if the team is sorted by last name.
*/
@Test
public void testGetTeamInfo() {
team21Helper();
team21.createTeam();
String expected = "U10 Soccer Team\n"
+ "Team Size: 20\n"
+ "------------------------\n"
+ "First Name Last Name \n"
+ "Mia Anderson \n"
+ "Sophia Brown \n"
+ "Emily Davis \n"
+ "Noah Davis \n"
+ "Charlotte Garcia \n"
+ "Emma Hernandez \n"
+ "Daniel Hernandez \n"
+ "Mason Johnson \n"
+ "Benjamin Martin \n"
+ "Ava Martinez \n"
+ "Liam Perez \n"
+ "Abigail Perez \n"
+ "Samuel Rodriguez \n"
+ "Olivia Rodriguez \n"
+ "Ethan Smith \n"
+ "Isabella Taylor \n"
+ "Harper Taylor \n"
+ "James Thomas \n"
+ "Jacob Thomas \n"
+ "William Wilson \n";
String actual = team21.teamInfo();
String[] lines = actual.split("\n");
StringBuilder sb = new StringBuilder();
String format = "%1$-15s %2$-15s\n";
String headers = String.format(format, "First Name", "Last Name");
int length = lines.length;
String[] newArray = Arrays.copyOfRange(lines, 4, length);
sb.append("U10 Soccer Team\n"
+ "Team Size: 20\n"
+ "------------------------\n").append(headers);
// delete jersey number
for (String item : newArray) {
String[] columns = item.split("\\s+");
sb.append(String.format(format, columns[0], columns[1]));
}
String modifiedString = sb.toString();
assertEquals(expected, modifiedString);
}
/**
* Test for getStartingLineUpInfo method. Since jersey number will change every time we create
* a team, we delete the jersey number in the expected string and actual string, and see if
* other information matches.
* Also, check if the team is sorted first by position then by last name.
*/
@Test
public void testGetStartingLineup() {
team21Helper();
team21.createTeam();
String expected = "Starting Line Up\n"
+ "------------------------\n"
+ "First Name Last Name Position \n"
+ "Harper Taylor Goalie \n"
+ "Ava Martinez Defender \n"
+ "Isabella Taylor Defender \n"
+ "Mason Johnson Midfielder \n"
+ "Benjamin Martin Midfielder \n"
+ "Samuel Rodriguez Midfielder \n"
+ "Liam Perez Forward \n";
String actual = team21.startingLineUpInfo();
String[] lines = actual.split("\n");
StringBuilder sb = new StringBuilder();
String format = "%1$-15s %2$-15s %3$-15s\n";
String headers = String.format(format, "First Name", "Last Name", "Position");
int length = lines.length;
String[] newArray = Arrays.copyOfRange(lines, 3, length);
sb.append("Starting Line Up\n"
+ "------------------------\n").append(headers);
// delete jersey number
for (String item : newArray) {
String[] columns = item.split("\\s+");
sb.append(String.format(format, columns[0], columns[1], columns[3]));
}
String modifiedString = sb.toString();
assertEquals(expected, modifiedString);
}
} |
import { Injectable, OnModuleInit } from "@nestjs/common";
import { SSHConfig } from "../interfaces/ssh-config.interface";
import { app } from 'electron';
import { resolve } from "path";
import * as mkdirp from 'mkdirp';
import { readFileSync, writeFileSync } from "fs";
import { HostHelper } from "../helpers";
import { IConfig } from "../interfaces/config.interface";
import { ILogger } from "update-electron-app";
import { InjectLogger } from "@nestcloud/logger";
@Injectable()
export class StoreService implements OnModuleInit {
private readonly homePath = app.getPath('home');
private readonly appPath = resolve(this.homePath, 'dolphin');
private readonly hostsFilename = 'hosts.data';
private readonly configFilename = 'data.data';
private readonly logFilename = 'dolphin.log';
private hosts: SSHConfig[] = [];
private config: IConfig = { proxyPort: 1080 };
constructor(
@InjectLogger() private readonly logger: ILogger,
private readonly hostHelper: HostHelper,
) {
}
onModuleInit(): any {
mkdirp(this.appPath);
try {
const data = readFileSync(resolve(this.appPath, this.hostsFilename)).toString();
this.hosts = JSON.parse(data) || [] as SSHConfig[];
} catch (e) {
this.logger.error(`read data file error: ${e.message}`);
}
try {
const configData = readFileSync(resolve(this.appPath, this.configFilename)).toString();
this.config = JSON.parse(configData) || { proxyPort: 1080 } as IConfig;
} catch (e) {
this.logger.error(`read config file error: ${e.message}`);
}
}
getConfig(): IConfig {
return this.config;
}
readLog() {
const logs = readFileSync(resolve(this.appPath, this.logFilename)).toString();
return logs.split('\n');
}
updateConfig(config: IConfig) {
this.config = config;
writeFileSync(
resolve(this.appPath, this.configFilename),
JSON.stringify(config)
);
}
getHosts() {
return this.hosts;
}
getHostByIndex(index: number) {
return this.hosts[index];
}
getHost(hostname: string) {
return this.hosts.find(host => host.name === hostname);
}
addHost(config: SSHConfig): boolean {
if (this.hostHelper.isExists(this.hosts, config.name)) {
return false;
}
this.hosts.push(config);
this.syncToFile();
return true;
}
editHost(index: number, config: SSHConfig): boolean {
const hosts = Object.create(this.hosts);
hosts.splice(index, 1);
if (this.hostHelper.isExists(hosts, config.name)) {
return false;
}
this.hosts.splice(index, 1, config);
this.syncToFile();
return true;
}
deleteHost(hostname: string) {
this.hosts = this.hosts.filter(host => host.name !== hostname);
this.syncToFile();
}
private syncToFile() {
writeFileSync(
resolve(this.appPath, this.hostsFilename),
JSON.stringify([...this.hosts])
);
}
} |
import React, { lazy, Suspense, useEffect, useState } from "react";
import ReactDOM from "react-dom/client";
import Header from "./components/Header";
import Body from "./components/Body";
import About from "./components/About";
import Contact from "./components/Contact";
import { createBrowserRouter, Outlet, RouterProvider } from 'react-router-dom';
import Error from "./components/Error";
import RestaurantMenu from "./components/RestaurantMenu";
import UserContext from "./utils/UserContext";
// import Grocery from "./components/Grocery";
const Grocery = lazy(() => import("./components/Grocery") );
// const About = lazy(() => import("./components/About") );
const AppLayout = () => {
const [userName, setUserName] = useState('');
// authentication
useEffect(() => {
const data = {
name: "Prajakta"
};
setUserName(data.name);
}, []);
return (
// This wraps whole app
// <UserContext.Provider value={ { loggedInUser: userName } }>
// <div className="app">
// <Header />
// <Outlet />
// </div>
// </UserContext.Provider>
// This wraps only header, rest(About, RestaurantCard) will have default value, it avoids Outlet
// <div className="app">
// <UserContext.Provider value={ { loggedInUser: userName } }>
// <Header />
// </UserContext.Provider>
// <Outlet />
// </div>
// Try to wrap 'Elon Musk' for header
// Shows Default value
<UserContext.Provider value={ { loggedInUser: userName, setUserName } }>
{/* Shows Prajakta */}
<div className="app">
<UserContext.Provider value={ { loggedInUser: 'Elon Musk' } }>
{/* Shows Elon Musk */}
<Header />
</UserContext.Provider>
<Outlet />
</div>
</UserContext.Provider>
)
}
const appRouter = createBrowserRouter([
{
path: "/",
element: <AppLayout />,
children: [
{
path: "/",
element: <Body />
},
{
path: "/about",
element: <About />
},
{
path: "/contact",
element: <Contact />
},
{
path: "/grocery",
element: (
<Suspense fallback={<h1>Loading ... </h1>}>
<Grocery />
</Suspense>
),
},
{
path: "/restaurants/:resId",
element: <RestaurantMenu />
}
],
errorElement: <Error />
}
]);
const root = ReactDOM.createRoot(document.getElementById("root"));
// root.render(<AppLayout />); // render the component
root.render(<RouterProvider router={appRouter}/>); // render the component |
---
layout: protreptik
show: true
title: Protreptik
image: /images/protreptik/Protreptik.jpeg
header: 'PROTREPTIK'
description: >-
Vi har i CCC altid været optaget af Protreptikken, dvs. den filosofiske samtalekunst, der formår at få os mennesker til at komme i kontakt med det væsentlige i os selv og i det gældende fællesskab. Det gælder for alle i CCC, at vi er trænet godt op i den protreptiske dialogform, fordi vi mener, at den er ligeså vigtig som alle de psykologiske coaching-metoder, som vi behersker.
published: true
order: '5'
image-position: top
---
## Fordi ordene, vi siger, betyder noget
Hvad angår Protreptikken, er den som samtaledisciplin at finde helt tilbage i antikkens filosofi, hvor specielt Platon og Aristoteles har forholdt sig til den og bygget videre herpå. Men Protreptikken har også historisk set udviklet sig op gennem Kristendommens æra og specielt langt ind i den psykologiserende Katolicisme, hvor syndsforladelse og sjæleransagelse bliver dominerende kendetegn.
I forhold til den moderne Protreptik har vi kunnet finde mange inspirationer. Lige fra den tyske oplysningsfilosofi (ved fx Immanuel Kant), indover Romantikken (1800-tallet med specielt Søren Kierkegaard) og frem til 1900-tallets filosofi med fx Martin Heidegger, Michael Foucault og Gilles Deleuze. Imidlertid er Aristoteles og den dialogfilosofiske disciplin (med Martin Buber, Gabriel Marcel og Emmanuel Levinas), dem, der bærer fanen højest, og dermed danner det etiske og sprogfilosofiske grundlag for vores indgang til og respekt for den protreptiske samtalekunst.
### Protreptik på semester 3 på vores 2-årige Masteruddannelse i Business Coaching
Det tog os nogle år at indse, at Proteptikken fortjente et helt semester for sig selv på vores masteruddannelse. Således begyndte de første hold (tilbage til omkring 2004 og frem til omtrent 2008) med både at have psykologisk coaching, protreptik og filosofi allerede på 1. semester. Vi indså hen ad vejen, at det var for voldsomt og samtidig gjorde protreptikken til skamme. Derfor besluttede vi os for, henover 2009, at skabe plads til, at de 10 dage som semester 3 varer, kun skal handle om protreptik. Og det er stadig det længste og mest intensive sammenhængende forløb, der findes i Danmark (og formentlig også i verden) omkring Protreptik. Se mere om semester 3, som også kan tages som et selvstændigt uddannelsesforløb, [her](https://www.copenhagencoaching.dk/academy/ledelseskursesP%C3%A5Lesbos/).
Og vores semester 4 på MBC udfolder endvidere mere moderne, filosofiske inspirationer til denne samtalekunst (jvf. ovenstående navne). Se mere om semester 4 [her](/pdfs/master-of-business-coaching.pdf).
Det gælder for begge semestre, at man kan tage dem uden at have været igennem semester 1 og semester 2.
### Individuel certificering i protreptik
Dette forløb har vi haft god succes med i mange år, dels fordi det er så fleksibelt og intenst, og dels fordi en del mennesker har behov for at dyrke en proces uden at skulle følge et hold med faste programmer, etc. Dette forløb danner således en ramme og grund for dine behov, fx ved at aftale tider som passer dig, steder som passer dig og emner som passer dig. Og ikke mindst giver dig muligheder for, som leder og menneske, både at lære protreptikken at kende som redskab, metode og eksistentiel livsindstilling, og samtidig komme tættere på de emner, som betyder noget for dig i din ledelse og i dit liv. Dette forløb afslutter med en praktisk eksamination med efterfølgende refleksion. Se mere [her](https://www.copenhagencoaching.dk/academy/certificeringIProtreptik/).
### Masterclass i protreptik
Vi har i mange år holdt vores årlige masterclass i protreptik, både udenfor CCC-huset på kursussteder, langs strand og skov, og i CCC-huset, i vores fine undervisningslokaler. Uanset hvor det foregår, er fokus at blive bedre til protreptikken, styrke sine greb, mødes med erfarne protreptikere, ligesindede, og samtidig få bygget noget ny teori på, nye principper, input, og ikke mindst, træning og øvelser. Vi sætter altid den fælles bundgrænse, hvad angår færdigheder og kompetencer, højt. Læs mere om den næstkommende Masterclass i Protreptik [her](https://www.copenhagencoaching.dk/academy/masterclassIProtreptik/).
### Protreptiske foredrag, workshops og seminarer
Vi har igennem de sidste 10 år været vidt omkring og lavet mindre forløb i og om protreptik, lige fra coaching-konferencer rundt om i verden til interne seminarer og workshops i danske organisationer, kommuner, private virksomheder samt foreninger, ledergrupper, bestyrelser, m.m. Vores erfaring er stadig, at deltagerne finder protreptikken spændende, givtig og gavnlig. Nogle oplever den også vanskelig, og igen andre finder det svært bare at sige ordet: “Protreptik”. Det gælder også i sådanne sammenhænge, at vi holder af at bruge tiden, vi har sammen med jer, på en blanding af input om teori, principper, greb og metoder og træning og små øvelser, så vi sammen kan gøre os nogle erfaringer om, hvad og hvordan det virker.
### Protreptik i praksis
I 2015 lykkedes det Mette Mejlhede og Kim Gørtz at få skrevet og udgivet: “Protreptik i praksis”.
Den bliver brugt flittigt, både ift ovenstående forløb, og bredt ud i det danske erhvervsliv kan vi også se og høre, at folk nyder gavn af dens meget praktiske vinkel på, hvordan man fører en protreptik. Og mon ikke de er på vej til at udgive en follow-up, der rummer “findings”, erfaringer, metoder og teori-konstruktioner indenfor de seneste 5 år…?
Husk, det handler om at få væsentlige samtaler til at lykkes…
<img src="/images/protreptik/PRotreptikipraksis.jpg" class="object-fit">
### Protreptik for viderekomne
I denne dialogiske arbejdsbog lærer du at filosofere og at invitere til at filosofere. Bogen sigter efter livsklykken og arbejder med begrebslogiske, eksistentielle og seis-miske samtaleformer.
I bogen gennemgås Protepticus (af den unge Aristoteles) med henblik på at inddrage kognitions-filosofiske, eksistensfilosofiske og differensfilosofiske dialogformer.
Igennem bogen inviteres læseren til selv at arbejde med den protreptiske disciplin og kunstart via en lang række øvelser...
<div class="row">
<div class="col-12 col-sm-6 mb-4">
<img src="/images/boger/protreptik-for-viderekommende.jpeg" class="object-fit">
</div>
<div class="col-12 col-sm-6">
<img src="/images/boger/protreptik-for-viderekommende-2.jpeg" class="object-fit">
</div>
</div> |
/* Copyright (C) 2022 GSI Helmholtzzentrum fuer Schwerionenforschung, Darmstadt
SPDX-License-Identifier: GPL-3.0-only
Authors: Sergey Gorbunov, Sergei Zharko [committer] */
/// \file L1SearchWindow.h
/// \brief Provides parameterisation for hits searching window in the CA tracking (header)
/// \date 08.11.2022
/// \author S.Zharko <s.zharko@gsi.de>
#ifndef L1SearchWindow_h
#define L1SearchWindow_h 1
#include <boost/serialization/array.hpp>
#include <boost/serialization/string.hpp>
#include <array>
#include <string>
/// TODO: SZh 8.11.2022: add selection of parameterisation
/// \brief Class L1SearchWindow defines a parameterisation of hits search window for CA tracking algorithm
/// TODO: SZh 8.11.2022: add description
class L1SearchWindow {
public:
/// Constructor
/// \param stationID Global index of active station
/// \param trackGrID Track group ID
L1SearchWindow(int stationID, int trackGrID);
/// Default constructor
L1SearchWindow() = default;
/// Destructor
~L1SearchWindow() = default;
/// Copy constructor
L1SearchWindow(const L1SearchWindow& other) = default;
/// Copy assignment operator
L1SearchWindow& operator=(const L1SearchWindow& other) = default;
/// Move constructor
L1SearchWindow(L1SearchWindow&& other) noexcept = default;
/// Move assignment operator
L1SearchWindow& operator=(L1SearchWindow&& other) = default;
/// Parameterisation function for dx_max(x0)
float DxMaxVsX0(float /*x*/) const { return fvParams[kDxMaxVsX0 /*+ 0*/]; }
/// Parameterisation function for dx_min(x0)
float DxMinVsX0(float /*x*/) const { return fvParams[kDxMinVsX0 /*+ 0*/]; }
/// Parameterisation function for dx_max(y0)
float DxMaxVsY0(float /*x*/) const { return fvParams[kDxMaxVsY0 /*+ 0*/]; }
/// Parameterisation function for dx_min(y0)
float DxMinVsY0(float /*x*/) const { return fvParams[kDxMinVsY0 /*+ 0*/]; }
/// Parameterisation function for dy_max(x0)
float DyMaxVsX0(float /*x*/) const { return fvParams[kDyMaxVsX0 /*+ 0*/]; }
/// Parameterisation function for dy_min(x0)
float DyMinVsX0(float /*x*/) const { return fvParams[kDyMinVsX0 /*+ 0*/]; }
/// Parameterisation function for dy_max(y0)
float DyMaxVsY0(float /*y*/) const { return fvParams[kDyMaxVsY0 /*+ 0*/]; }
/// Parameterisation function for dy_min(y0)
float DyMinVsY0(float /*y*/) const { return fvParams[kDyMinVsY0 /*+ 0*/]; }
/// Gets station id
int GetStationID() const { return fStationID; }
/// Gets track group id
int GetTrackGroupID() const { return fTrackGroupID; }
/// Sets tag
/// A tag can be used for insurance, if this search window corresponds to a desired track finder iteration
void SetTag(const char* name) { fsTag = name; }
/// TODO: SZh 08.11.2022: Implement variadic template function
/// TODO: SZh 08.11.2022: Try to reduce number of functions
/// Sets parameters for dx_max(x0)
/// \param id Parameter index
/// \param val Parameter value
void SetParamDxMaxVsX0(int id, float val);
/// Sets parameters for dx_min(x0)
/// \param id Parameter index
/// \param val Parameter value
void SetParamDxMinVsX0(int id, float val);
/// Sets parameters for dx_max(y0)
/// \param id Parameter index
/// \param val Parameter value
void SetParamDxMaxVsY0(int id, float val);
/// Sets parameters for dx_min(y0)
/// \param id Parameter index
/// \param val Parameter value
void SetParamDxMinVsY0(int id, float val);
/// Sets parameters for dy_max(x0)
/// \param id Parameter index
/// \param val Parameter value
void SetParamDyMaxVsX0(int id, float val);
/// Sets parameters for dy_min(x0)
/// \param id Parameter index
/// \param val Parameter value
void SetParamDyMinVsX0(int id, float val);
/// Sets parameters for dy_max(y0)
/// \param id Parameter index
/// \param val Parameter value
void SetParamDyMaxVsY0(int id, float val);
/// Sets parameters for dy_min(y0)
/// \param id Parameter index
/// \param val Parameter value
void SetParamDyMinVsY0(int id, float val);
/// String representation of the contents
std::string ToString() const;
private:
static constexpr unsigned char kNpars = 1; ///< Max number of parameters for one dependency
static constexpr unsigned char kNdeps = 8; ///< Number of the dependencies
/// Enumeration for dependencies stored
enum EDependency
{
kDxMaxVsX0,
kDxMinVsX0,
kDxMaxVsY0,
kDxMinVsY0,
kDyMaxVsX0,
kDyMinVsX0,
kDyMaxVsY0,
kDyMinVsY0
};
/// Search window parameter array containing parameters from
/// - dx_max vs x0 - indexes [0 .. kNpars - 1]
/// - dx_min vs x0 - indexes [kNpars .. (2 * kNpars - 1)]
/// - dx_max vs y0 - indexes [2 * kNpars .. (3 * kNpars - 1)]
/// - dx_min vs y0 - indexes [3 * kNpars .. (4 * kNpars - 1)]
/// - dy_max vs y0 - indexes [4 * kNpars .. (5 * kNpars - 1)]
/// - dy_min vs y0 - indexes [5 * kNpars .. (6 * kNpars - 1)]
/// - dy_max vs y0 - indexes [6 * kNpars .. (7 * kNpars - 1)]
/// - dy_min vs y0 - indexes [7 * kNpars .. (8 * kNpars - 1)]
std::array<float, kNdeps* kNpars> fvParams = {0};
int fStationID = -1; ///< Global index of active tracking station
int fTrackGroupID = -1; ///< Index of tracks group
std::string fsTag = ""; ///< Tag, containing information on the tracks group (TODO: can be omitted?)
/// Serialization function
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int)
{
ar& fvParams;
ar& fStationID;
ar& fTrackGroupID;
ar& fsTag;
}
};
#endif // L1SearchWindow_h |
import { randomBytes } from "node:crypto";
import mongoose from "mongoose";
const { ObjectId } = mongoose.Types;
import encryptPassword from "../../../../../helpers/encryptPassword.js";
import decryptPassword from "../../../../../helpers/decryptPassword.js";
import { CustomError } from "../../../../common/middlewares/error.middleware.js";
import STATUS_CODE from "../../../../../constants/statusCode.js";
import User from "../models/user.model.js";
import Token from "../models/token.model.js";
import Session from "../models/session.model.js";
import config from "../../../../../config/config.js";
import {
generateAccessToken,
generateRefreshToken,
} from "../../../../../helpers/token.js";
import USER_ROLE from "../../../../../constants/userRole.js";
class UserService {
createUser = async (userInfo) => {
// 1. extract all info
const { userName, email, password } = userInfo;
// 2. check if user already exist with email id or userName
const prevUser = await User.findOne({ $or: [{ email }, { userName }] });
// console.log("Prev User", prevUser);
if (prevUser) {
throw new CustomError("User already exist", STATUS_CODE.CONFLICT);
}
// 2. hash the password
const hashedPassword = await encryptPassword(password);
// 3. create user object
const user = new User({ userName, email, password: hashedPassword });
user.role = USER_ROLE.DOCTOR;
// 4. save user
await user.save();
// console.log("new User", user);
// 5. return user
user.password = undefined; // remove password filed while returning
return user;
};
loginUser = async (userInfo) => {
const { email, password } = userInfo;
// 1. check if user exist
const user = await User.findOne({ email });
if (!user) {
throw new CustomError("Invalid Credentials", STATUS_CODE.NOT_FOUND);
}
// 2. match the password
const hashedPass = user.password;
const isPassMatch = await decryptPassword(password, hashedPass);
if (!isPassMatch) {
throw new CustomError("Invalid Credentials", STATUS_CODE.NOT_FOUND);
}
// generate access and refresh token and return it
const payload = {
userId: user._id.toString(),
email,
};
// console.log(payload);
const accessToken = generateAccessToken(payload);
const refreshToken = generateRefreshToken(payload);
return { accessToken, refreshToken, userId: user._id.toString() };
};
updateUser = async (userId, userInfo) => {
const { userName, email } = userInfo;
const prevUser = await User.findOne({
$or: [{ email }, { userName }],
_id: { $ne: new ObjectId(userId) }, // Exclude the current user by their ID
});
// console.log("Prev User", prevUser);
if (prevUser) {
throw new CustomError("User already exist", STATUS_CODE.CONFLICT);
}
// update user
const updatedUser = await User.findOneAndUpdate(
{ _id: new ObjectId(userId) },
{ $set: userInfo },
{ new: true }
);
// delete password while returning
updatedUser.password = undefined;
// return updated user
return updatedUser;
};
requestPasswordReset = async (email) => {
const user = await User.findOne({ email });
// if (!user) throw new Error('Email does not exist');
if (!user) {
throw new CustomError("Email does not exist", STATUS_CODE.NOT_FOUND);
}
// if token is already there first delete token
let token = await Token.findOne({ userId: user._id });
if (token) await Token.deleteOne();
const resetStr = randomBytes(32).toString("hex");
// hashing string
// this operation same type of password hashing
const hash = await encryptPassword(resetStr);
token = new Token({
userId: user._id,
token: hash,
});
await token.save();
console.log("Reset password token", token);
// client url will be useful when we use react
const { clientUrl } = config;
const resetPasswordLink = `${clientUrl}/password-reset?token=${resetStr}&id=${user._id}`;
console.log(resetPasswordLink);
// send email with link
return resetPasswordLink;
};
isResetPasswordTokenValid = async (token, userId) => {
// check if token exist into DB
const passwordResetToken = await Token.findOne({
userId: new ObjectId(userId),
});
if (!passwordResetToken) {
throw new CustomError(
"Invalid or expired password reset token",
STATUS_CODE.NOT_FOUND
);
}
// compare token with DB token
const isValid = await decryptPassword(token, passwordResetToken.token);
if (!isValid) {
throw new CustomError(
"Invalid or token does'nt match",
STATUS_CODE.NOT_FOUND
);
}
return isValid;
};
resetPassword = async (resetInfo) => {
const { token, userId, password } = resetInfo;
// check if token exist into DB
const passwordResetToken = await Token.findOne({
userId: new ObjectId(userId),
});
if (!passwordResetToken) {
throw new CustomError(
"Invalid or expired password reset token",
STATUS_CODE.NOT_FOUND
);
}
// compare token with DB token
const isValid = await decryptPassword(token, passwordResetToken.token);
if (!isValid) {
throw new CustomError(
"Invalid or token does'nt match",
STATUS_CODE.NOT_FOUND
);
}
// encrypt the password
const hashedPass = await encryptPassword(password);
await User.updateOne(
{ _id: new ObjectId(userId) },
{ $set: { password: hashedPass } },
{ new: true }
);
return true;
};
deleteUser = async (email, password) => {
// find user in DB with email id
const user = await User.findOne({ email });
const isPasswordValid = await decryptPassword(password, user.password);
// match the password
if (!(user && isPasswordValid)) {
throw new CustomError(
"Token or password is not valid",
STATUS_CODE.BAD_REQUEST
);
}
// if found correct delete that user
const response = await user.deleteOne();
// console.log("Deleted User Info", response)
// find session with user id
const query = { "session.userId": response._id.toString() };
// if found then delete user session
const allSessions = await Session.deleteMany(query);
// console.log("Deleted Sessions Info",allSessions);
response.password = undefined;
return response;
};
}
const userService = new UserService();
export default userService; |
using DG.Tweening;
using System;
using System.Collections;
using UnityEngine;
public class MoonController : MonoBehaviour
{
[Header("Options")]
public bool canMoveHorizontal = false;
[Header("Orbit")]
public Transform orbitTarget;
public float orbitRadius = 1f;
public float orbitSpeed = 2f;
[Header("Charge")]
public float maxCharge = 3f;
public float chargeRate = 1f;
public float chargeTime = .25f;
public float downTime = .25f;
public float recoveryTime = .5f;
[Range(0f, 1f)]
public float speedDuringCharge = .5f;
public AnimationCurve chargeDownCurve, chargeUpCurve;
public GameObject chargeBar;
[Header("References")]
public GameObject moonHitParticleSystem, floorHitParticleSystem;
[HideInInspector]
public float startingOrbitRadius = 1f;
public float currentAngle = 0f;
[SerializeField]
private bool isAttacking, isChargingAttack, canAttack = true;
private Collider2D col;
[SerializeField, Range(0f, 3f)]
private float currentCharge = 0f;
public MoonHealth moonHealth;
private GameObject chargeBarLvl1, chargeBarLvl2, chargeBarLvl3;
private void Awake()
{
moonHealth = GetComponent<MoonHealth>();
if (orbitTarget == null)
{
Debug.LogError("Target object not assigned.");
enabled = false;
return;
}
col = GetComponent<Collider2D>();
currentAngle = Mathf.PI / 2;
chargeBarLvl1 = chargeBar.transform.GetChild(0).gameObject;
chargeBarLvl2 = chargeBar.transform.GetChild(1).gameObject;
chargeBarLvl3 = chargeBar.transform.GetChild(2).gameObject;
DisableChargeBar();
}
private void Start()
{
transform.position = (Vector2)orbitTarget.position + Vector2.up * (orbitRadius + GetMoonRadius());
startingOrbitRadius = orbitRadius;
}
void Update()
{
Attack();
}
void FixedUpdate()
{
Movement();
Rotation();
}
private void Attack()
{
if (Input.GetButtonDown("Jump") && !isChargingAttack && !isAttacking)
{
isChargingAttack = true;
chargeBar.SetActive(true);
}
if (isChargingAttack && Input.GetButton("Jump"))
{
currentCharge += chargeRate * Time.deltaTime;
currentCharge = Mathf.Clamp(currentCharge, 0, maxCharge);
if (currentCharge >= 1) chargeBarLvl1.SetActive(true);
if (currentCharge >= 2) chargeBarLvl2.SetActive(true);
if (currentCharge >= 3) chargeBarLvl3.SetActive(true);
}
if (canAttack && isChargingAttack && Input.GetButtonUp("Jump"))
{
DisableChargeBar();
StartCoroutine(AttackCoroutine(currentCharge));
}
}
private void DisableChargeBar()
{
chargeBarLvl1.SetActive(false);
chargeBarLvl2.SetActive(false);
chargeBarLvl3.SetActive(false);
chargeBar.SetActive(false);
}
private void Movement()
{
//float inputValue = !(isAttacking || isChargingAttack) ? (Input.GetAxis("Horizontal") * -1f) : 0);
//float inputValue = !isAttacking ? (!isChargingAttack ? (Input.GetAxis("Horizontal") * -1f) : (Input.GetAxis("Horizontal") * (-1f * speedDuringCharge))) : 0f; //Biba la lejivilidad del kodygo
float inputValue = 0f;
if (!isAttacking && canMoveHorizontal)
if (!isChargingAttack)
inputValue = Input.GetAxis("Horizontal") * -1f;
else
inputValue = Input.GetAxis("Horizontal") * (-1f * speedDuringCharge);
currentAngle += inputValue * orbitSpeed * Time.deltaTime; //By using GetAxis we already have acceleration
float newX = (orbitTarget.position.x + orbitRadius + GetMoonRadius()) * Mathf.Cos(currentAngle);
float newY = (orbitTarget.position.y + orbitRadius + GetMoonRadius()) * Mathf.Sin(currentAngle);
Debug.DrawLine(orbitTarget.position, new Vector2(newX, newY), Color.green, Time.deltaTime);
transform.position = new Vector2(newX, newY);
}
public float GetMoonRadius()
{
return col.bounds.extents.y;
}
private void Rotation()
{
transform.up = (transform.position - orbitTarget.position).normalized;
}
private void OnDrawGizmosSelected()
{
if (col == null) col = GetComponent<Collider2D>();
if (col == null || orbitTarget == null) return;
Gizmos.DrawLine(orbitTarget.position, orbitTarget.position + Vector3.up * (orbitRadius + GetMoonRadius()));
Gizmos.DrawWireSphere(orbitTarget.position, (orbitTarget.position + Vector3.up * (orbitRadius + GetMoonRadius())).y);
Gizmos.DrawWireSphere(orbitTarget.position + Vector3.up * (orbitRadius + GetMoonRadius()), GetMoonRadius());
}
public IEnumerator AttackCoroutine(float attackCharge)
{
canAttack = false;
isChargingAttack = false;
isAttacking = true;
float elapsed = 0f;
float lowerLimit = orbitTarget.GetComponent<Collider2D>().bounds.extents.y;
//-- Go down --
while (elapsed < chargeTime)
{
elapsed = Mathf.Clamp(elapsed + Time.deltaTime, 0, chargeTime);
orbitRadius = Mathf.Lerp(startingOrbitRadius, lowerLimit, chargeDownCurve.Evaluate(elapsed / chargeTime));
yield return null;
}
//-------------
isAttacking = false;
Camera.main.DOShakePosition(0.5f, 0.5f, 30);
if (floorHitParticleSystem != null)
Instantiate(floorHitParticleSystem, transform.position - Vector3.up * col.bounds.extents.y, Quaternion.identity);
AudioManager.self.PlayAdditively(SoundId.StoneCrush);
yield return new WaitForSecondsRealtime(downTime);
//-- Go up --
while (elapsed > 0)
{
orbitRadius = Mathf.Lerp(startingOrbitRadius, lowerLimit, chargeUpCurve.Evaluate(elapsed / recoveryTime));
elapsed = Mathf.Clamp(elapsed - Time.deltaTime, 0, recoveryTime);
yield return null;
}
//-------------
canAttack = true;
currentCharge = 0f;
yield return null;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (isAttacking)
{
if (collision.TryGetComponent(out EnemyBase enemy))
if (!enemy.TryKill(Mathf.FloorToInt(currentCharge)) && !(enemy is CityEnemy))
moonHealth.TakeDamage(1);
}
else if (canAttack)
{
if (collision.TryGetComponent(out EnemyBase enemy) && !(enemy is CityEnemy))
moonHealth.TakeDamage(1);
}
AudioManager.self.PlayAdditively(SoundId.Hit);
//Instantiate(moonHitParticleSystem, collision.ClosestPoint(transform.position), Quaternion.identity);
}
} |
const config = require('./utils/config')
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const cors = require('cors')
const chaptersRouter = require('./controllers/chapters')
const partsRouter = require('./controllers/parts')
const middleware = require('./utils/middleware')
const mongoose = require('mongoose')
console.log('connecting to', config.MONGODB_URI)
mongoose.connect(config.MONGODB_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useFindAndModify: false
})
.then(() => {
console.log('connected to MongoDB app.js')
})
.catch((error) => {
console.log('error connection to MongoDB:', error.message)
})
app.use(cors())
app.use(express.static('build'))
app.use(bodyParser.json())
app.use(middleware.requestLogger)
app.use('/api/chapters', chaptersRouter)
app.use('/api/parts', partsRouter)
app.use(middleware.unknownEndpoint)
app.use(middleware.errorHandler)
module.exports = app |
import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import NavbarCustom from './components/Header/Header';
import AdminDashboard from './pages/AdminDashboard';
import CreateBook from './pages/CreateBooks';
import ShowBook from './pages/ShowBook';
import EditBook from './pages/EditBook';
import DeleteBook from './pages/DeleteBook';
const App = () => {
return (
<>
<NavbarCustom />
<Routes>
<Route path='/' element={<Home />} />
<Route path='/admin' element={<AdminDashboard />} />
<Route path='/admin/books/create' element={<CreateBook />} />
<Route path='/admin/books/details/:id' element={<ShowBook />} />
<Route path='/admin/books/edit/:id' element={<EditBook />} />
<Route path='/admin/books/delete/:id' element={<DeleteBook />} />
</Routes>
</>
);
};
export default App; |
// Demonstrates various String properties and methods
string value = "Hello, Nathan.";
// Get the total number of chars in the string
int length = value.Length;
Console.WriteLine($"The length of the string: {length}");
// Access a single char
char firstChar = value[0];
Console.WriteLine($"The first character: {firstChar}");
char lastChar = value[length - 1];
Console.WriteLine($"The last character: {lastChar}");
// Upper and Lower
Console.WriteLine($"The string UPPER: {value.ToUpper()}");
Console.WriteLine($"The string lower: {value.ToLower()}");
// Get a substring
string hello = value.Substring(0, 5);
Console.WriteLine($"Hello: {hello}");
// Search for a char or a substring
int commaPosition = value.IndexOf(',');
Console.WriteLine($"The comma is at pos: {commaPosition}");
int namePostion = value.IndexOf("Nathan");
Console.WriteLine($"The name is at pos: {namePostion}");
// Does a string contain another string
bool containsName = value.Contains("Nathan");
bool containsZ = value.Contains('z');
Console.WriteLine($"Contains name: {containsName}");
Console.WriteLine($"Contains z: {containsZ}");
// TASK: using the methods and properties above, create a variable
// that contains your name from the original string value
int firstLetterPos = value.IndexOf(' ') + 1;
int periodPos = value.IndexOf('.');
int nameLength = periodPos - firstLetterPos;
Console.WriteLine($"The name is: {value.Substring(firstLetterPos, nameLength)}"); |
import unittest
import time
from linkedin_scraper import ScraperController
from linkedin_scraper.scrapers.base import BaseScraperWorker
from linkedin_scraper.config import (
LINKEDIN_SCRAPER_GOOGLE_CONCURRENCY,
LINKEDIN_SCRAPER_LINKEDIN_CONCURRENCY,
)
class TestBaseScraperController(unittest.TestCase):
def setUp(self):
self.scrape_controller = ScraperController(show_progress=False)
self.scrape_controller.initialize()
def tearDown(self):
self.scrape_controller.stop()
self.scrape_controller = None
def test_scraper_controller_process_check(self):
"""This test checks for the process handling, making sure there are no zombie processes left"""
google_workers = []
linkedin_workers = []
time.sleep(2)
worker: BaseScraperWorker
for worker in self.scrape_controller.get_workers():
self.assertIsInstance(worker, BaseScraperWorker)
if worker.get_worker_type() == "GoogleScrapeWorker":
google_workers.append(worker)
elif worker.get_worker_type() == "LinkedinScrapeWorker":
linkedin_workers.append(worker)
# Make sure we have the correct number of worker instances of each type
self.assertEqual(len(google_workers), LINKEDIN_SCRAPER_GOOGLE_CONCURRENCY)
self.assertEqual(len(linkedin_workers), LINKEDIN_SCRAPER_LINKEDIN_CONCURRENCY)
# Stop the process
self.scrape_controller.stop()
time.sleep(2)
# There shouldn't be any process anymore
self.assertEqual(len(self.scrape_controller.get_workers()), 0) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.