text
stringlengths 184
4.48M
|
---|
import * as React from "react";
import * as Styled from "./NavbarStyles";
import * as types from "./NavbarTypes";
import { isAuth } from '../../redux/reducers/userReducer';
import { useSelector } from 'react-redux';
import NavbarUserData from './NavbarUserData';
const routes: types.RouteTypes = {
HOME: "/posts",
REGISTER: "/register",
LOGIN: "/login"
};
const Navbar = () => {
const isUserAuth = useSelector(isAuth);
return (
<Styled.Navbar>
<Styled.NavbarLink to={routes.HOME}>
Posts
</Styled.NavbarLink>
<Styled.LinksGroup>
{isUserAuth
? <NavbarUserData />
: (
<React.Fragment>
<Styled.NavbarLink
to={routes.LOGIN}
data-testid="loginPage"
>
Login
</Styled.NavbarLink>
<Styled.NavbarLink
to={routes.REGISTER}
data-testid="registerPage"
>
Register
</Styled.NavbarLink>
</React.Fragment>
)}
</Styled.LinksGroup>
</Styled.Navbar>
);
};
export default Navbar; |
package com.example.duolingo.service.impl;
import com.example.duolingo.controller.payload.request.LoginDto;
import com.example.duolingo.controller.payload.request.RegisterDto;
import com.example.duolingo.domain.entities.User;
import com.example.duolingo.mapper.RegisterDtoToUser;
import com.example.duolingo.repository.UserRepository;
import com.example.duolingo.utils.JwtUtils;
import java.util.HashSet;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.mapstruct.factory.Mappers;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
@Service
@Slf4j
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final JwtUtils jwtUtils;
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
private RegisterDtoToUser registerMapper = Mappers.getMapper(RegisterDtoToUser.class);
public String processLogin(LoginDto loginUser) {
Optional<User> foundUser = userRepository.findByUsername(loginUser.username());
User userData = foundUser.get();
if (!passwordEncoder.matches(loginUser.password(), userData.getPass())) {
log.debug("The password doesn't match for user {}", loginUser.username());
return null;
}
return jwtUtils.generateJwtToken(userData);
}
public void register(RegisterDto registerDto) {
User user = registerMapper.registerDtoToUser(registerDto);
user.setPass(passwordEncoder.encode(registerDto.pass()));
userRepository.save(user);
}
public Optional<User> getCurrentUser() {
val principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username;
if (principal instanceof UserDetails) {
username = ((UserDetails) principal).getUsername();
} else {
username = principal.toString();
}
return userRepository.findByUsername(username);
}
public UserDetails loadJwtUser(String username) {
val user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
val grantedAuthorities = new HashSet<SimpleGrantedAuthority>();
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPass(), grantedAuthorities);
}
public UserDetailsService userDetailsService() {
return new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String username) {
return loadJwtUser(username);
}
};
}
} |
const express = require('express')
const path = require('path')
const http = require('http')
const Filter = require('bad-words')
const socketio = require('socket.io')
const moment = require('moment')
const{generateMessage, generateLocationMessage} = require('./utils/messages')
const{addUser, removeUser, getUser, getUsersInRoom} = require('./utils/users')
const app = express()
const server = http.createServer(app)
const io = socketio(server)
const port = process.env.PORT || 3000
const publicDirectoryPath = path.join(__dirname, '../public')
app.use(express.static(publicDirectoryPath))
// let count = 0;
//server(emit) -> client(receive) - countUpdated
//client(emit) -> server(receive) - increment
io.on('connection', (socket) => {
console.log('New websocket connection')
socket.on('join', ({username, room}, callback) => {
const{error, user} = addUser({id: socket.id, username, room})
if(error){
return callback(error)
}
socket.join(user.room)
socket.emit('message', generateMessage('Admin', 'Welcome!'))
socket.broadcast.to(user.room).emit('message', generateMessage('Admin', `${user.username} has joined!`))
io.to(user.room).emit('roomData', {
room: user.room,
users: getUsersInRoom(user.room)
})
callback()
})
socket.on('sendMessage', (message, callback) => {
const user = getUser(socket.id)
// io.emit('message', message)
const filter = new Filter()
if(filter.isProfane(message)){
return callback('Profanity is not allowed')
}
io.to(user.room).emit('message', generateMessage(user.username, message))
callback('Delivered!')
})
socket.on('sendLocation', (coords, callback) => {
const user = getUser(socket.id)
io.to(user.room).emit('locationMessage', generateLocationMessage(user.username,`https://google.com/maps?q=${coords.latitude},${coords.longitude}`))
callback()
})
socket.on('disconnect', () => {
const user = removeUser(socket.id)
if(user){
io.to(user.room).emit('message', generateMessage('Admin', `${user.username} has left`))
io.to(user.room).emit('roomData', {
room: user.room,
users: getUsersInRoom(user.room)
})
}
})
// socket.emit('countUpdated', count)
// socket.on('increment', () => {
// count++
// // socket.emit('countUpdated', count)
// io.emit('countUpdated', count)
// })
})
server.listen(port, () => {
console.log(`Server is up on the ${port}`)
}) |
//
// TutorDetail.swift
// Simple TableView App Swift UI
//
// Created by Jeffrey Almonte on 6/3/20.
// Copyright © 2020 Jeffrey Almonte. All rights reserved.
//
import SwiftUI
struct TutorDetail: View {
var name: String
var headline: String
var bio: String
var body: some View {
VStack {
VStack {
Image(name)
.clipShape(Circle())
.overlay(Circle().stroke(Color.orange, lineWidth: 4))
.shadow(radius: 10)
Text(name)
.font(.title)
}
Text("Founder of AppCoda")
.font(.subheadline)
Divider()
Text(bio)
.font(.headline)
.multilineTextAlignment(.center)
.lineLimit(50)
}.padding().navigationBarTitle(Text(name), displayMode: .inline)
}
}
struct TutorDetail_Previews: PreviewProvider {
static var previews: some View {
TutorDetail(name: "Simon Ng", headline: "Founder of AppCoda", bio: "Founder of AppCoda. Author of multiple iOS programming books including Beginning iOS 12 Programming with Swift and Intermediate iOS 12 Programming with Swift. iOS Developer and Blogger.")
}
} |
//
// LessonListViewModel.swift
// Nanuri
//
// Created by Park Gyurim on 2022/01/30.
//
import Foundation
import Combine
import Alamofire
final class LessonListViewModel : ObservableObject {
@Published var LessonList : [Lesson] = []
@Published var selectedLesson : Lesson = Lesson(
lessonId: 0,
creator: "",
lessonName: "Title",
category: "Category",
location: "Location",
limitedNumber: 5,
content: "Content",
createDate: "",
status: true,
images: []
)
@Published var isFetchDone : Bool = false
@Published var isSearching : Bool = false
@Published var searchingText : String = ""
@Published var selectedClassId = 0
@Published var detailViewShow : Bool = false
@Published var isSortBtnClicked : Bool = false
@Published var sort_OnlyAvailable : Bool = false
private var subscription = Set<AnyCancellable>()
private let url = "http://ec2-3-39-19-215.ap-northeast-2.compute.amazonaws.com:8080/lesson"
func fetchLessons() {
AF.request(url,
method: .get
).responseJSON { [weak self] response in
guard let statusCode = response.response?.statusCode else { return }
if statusCode == 200 { self?.isFetchDone = true }
//print(statusCode)
//print(response)
}.publishDecodable(type : Lessons.self)
.compactMap { $0.value }
.map { $0.body }
.sink { completion in
switch completion {
case let .failure(error) :
print(error.localizedDescription)
case .finished :
print("Get Lesson Finished")
}
} receiveValue: { [weak self] recievedValue in
//print(recievedValue)
self?.LessonList = recievedValue.reversed()
//print(self?.LessonList)
}.store(in: &subscription)
}
} |
package org.smartregister.fhir.structuremaptool
import ca.uhn.fhir.context.FhirContext
import ca.uhn.fhir.context.FhirVersionEnum
import org.apache.poi.ss.usermodel.Row
import org.hl7.fhir.r4.hapi.ctx.HapiWorkerContext
import org.hl7.fhir.r4.model.Enumeration
import org.hl7.fhir.r4.model.Questionnaire
import org.hl7.fhir.r4.model.Questionnaire.QuestionnaireItemComponent
import org.hl7.fhir.r4.model.QuestionnaireResponse
import org.hl7.fhir.r4.model.Resource
import org.hl7.fhir.r4.model.Type
import org.hl7.fhir.r4.utils.FHIRPathEngine
import java.lang.reflect.Field
import java.lang.reflect.ParameterizedType
// Get the hl7 resources
val contextR4 = FhirContext.forR4()
val fhirResources = contextR4.resourceTypes
fun getQuestionsPath(questionnaire: Questionnaire): HashMap<String, String> {
val questionsMap = hashMapOf<String, String>()
questionnaire.item.forEach { itemComponent ->
getQuestionNames("", itemComponent, questionsMap)
}
return questionsMap
}
fun getQuestionNames(parentName: String, item: QuestionnaireItemComponent, questionsMap: HashMap<String, String>) {
val currParentName = if (parentName.isEmpty()) "" else parentName
questionsMap.put(item.linkId, currParentName)
item.item.forEach { itemComponent ->
getQuestionNames(currParentName + ".where(linkId = '${item.linkId}').item", itemComponent, questionsMap)
}
}
class Group(
entry: Map.Entry<String, MutableList<Instruction>>,
val stringBuilder: StringBuilder,
val questionsPath: HashMap<String, String>
) {
var lineCounter = 0
var groupName = entry.key
val instructions = entry.value
private fun generateReference(resourceName: String, resourceIndex: String): String {
// Generate the reference based on the resourceName and resourceIndex
val sb = StringBuilder()
sb.append("create('Reference') as reference then {")
sb.appendNewLine()
sb.append("src-> reference.reference = evaluate(bundle, \$this.entry.where(resourceType = '$resourceName/$resourceIndex'))")
sb.append(""" "rule_d";""".trimMargin())
sb.appendNewLine()
sb.append("}")
return sb.toString()
}
fun generateGroup(questionnaireResponse: QuestionnaireResponse) {
if(fhirResources.contains(groupName.dropLast(1))){
val resourceName = instructions[0].resource
// add target of reference to function if reference is not null
val structureMapFunctionHead = "group Extract$groupName(source src : QuestionniareResponse, target bundle: Bundle) {"
stringBuilder.appendNewLine()
stringBuilder.append(structureMapFunctionHead)
.appendNewLine()
stringBuilder.append("src -> bundle.entry as entry, entry.resource = create('$resourceName') as entity1 then {")
.appendNewLine()
val mainNest = Nest()
mainNest.fullPath = ""
mainNest.name = ""
mainNest.resourceName = resourceName
instructions.forEachIndexed { index, instruction ->
mainNest.add(instruction)
}
mainNest.buildStructureMap(0, questionnaireResponse)
stringBuilder.append("} ")
addRuleNo()
stringBuilder.appendNewLine()
stringBuilder.append("}")
stringBuilder.appendNewLine()
stringBuilder.appendNewLine()
} else{
println("$groupName is not a valid hl7 resource name")
}
}
fun addRuleNo() {
stringBuilder.append(""" "${groupName}_${lineCounter++}"; """)
}
fun Instruction.getPropertyPath(): String {
return questionsPath.getOrDefault(responseFieldId, "")
}
fun Instruction.getAnswerExpression(questionnaireResponse: QuestionnaireResponse): String {
//1. If the answer is static/literal, just return it here
// TODO: We should infer the resource element and add the correct conversion or code to assign this correctly
if (constantValue != null) {
return when {
fieldPath == "id" -> "create('id') as id, id.value = '$constantValue'"
fieldPath == "rank" -> {
val constValue = constantValue!!.replace(".0", "")
"create('positiveInt') as rank, rank.value = '$constValue'"
}
else -> "'$constantValue'"
}
}
// 2. If the answer is from the QuestionnaireResponse, get the ID of the item in the "Questionnaire Response Field Id" and
// get its value using FHIR Path expressions
if (responseFieldId != null) {
// TODO: Fix the 1st param inside the evaluate expression
var expression = "${"$"}this.item${getPropertyPath()}.where(linkId = '$responseFieldId').answer.value"
// TODO: Fix these to use infer
if (fieldPath == "id" || fieldPath == "rank") {
expression = "create('${if (fieldPath == "id") "id" else "positiveInt"}') as $fieldPath, $fieldPath.value = evaluate(src, $expression)"
} else {
// TODO: Infer the resource property type and answer to perform other conversions
// TODO: Extend this to cover other corner cases
if (expression.isCoding(questionnaireResponse) && fieldPath.isEnumeration(this)) {
expression = expression.replace("answer.value", "answer.value.code")
} else if (inferType(fullPropertyPath()) == "CodeableConcept") {
return "''"
}
expression = "evaluate(src, $expression)"
}
return expression
}
// 3. If it's a FHIR Path/StructureMap function, add the contents directly from here to the StructureMap
if (fhirPathStructureMapFunctions != null && fhirPathStructureMapFunctions!!.isNotEmpty()) {
// TODO: Fix the 2nd param inside the evaluate expression --> Not sure what this is but check this
return fhirPathStructureMapFunctions!!
}
// 4. If the answer is a conversion, (Assume this means it's being converted to a reference)
if (conversion != null && conversion!!.isNotBlank() && conversion!!.isNotEmpty()) {
println("current resource to reference is $conversion")
val resourceName = conversion!!.replace("$", "")
var resourceIndex = conversion!!.replace("$$resourceName", "")
if (resourceIndex.isNotEmpty()) {
resourceIndex = "[$resourceIndex]"
}
val reference = generateReference(resourceName = resourceName, resourceIndex = resourceIndex)
return reference
}
/*
5. You can use $Resource eg $Patient to reference another resource being extracted here,
but how do we actually get its instance so that we can use it???? - This should be handled elsewhere
*/
return "''"
}
inner class Nest {
var instruction: Instruction? = null
// We can change this to a linked list
val nests = ArrayList<Nest>()
lateinit var name: String
lateinit var fullPath: String
lateinit var resourceName: String
fun add(instruction: Instruction) {
/*if (instruction.fieldPath.startsWith(fullPath)) {
}*/
val remainingPath = instruction.fieldPath.replace(fullPath, "")
remainingPath.run {
if (contains(".")) {
val parts = split(".")
val partName = parts[0].ifEmpty {
parts[1]
}
// Search for the correct property to put this nested property
nests.forEach {
if (partName.startsWith(it.name)) {
val nextInstruction = Instruction().apply {
copyFrom(instruction)
var newFieldPath = ""
parts.forEachIndexed { index, s ->
if (index != 0) {
newFieldPath += s
}
if (index > 0 && index < parts.size - 1) {
newFieldPath += "."
}
}
fieldPath = newFieldPath
}
it.add(nextInstruction)
return@run
}
}
// If no match is found, let's create a new one
val newNest = Nest().apply {
name = partName
fullPath = if (this@Nest.fullPath.isNotEmpty()) {
"${this@Nest.fullPath}.$partName"
} else {
partName
}
resourceName = inferType("${this@Nest.resourceName}.$fullPath") ?: ""
if ((parts[0].isEmpty() && parts.size > 2) || (parts[0].isNotEmpty() && parts.size > 1)) {
val nextInstruction = Instruction().apply {
copyFrom(instruction)
var newFieldPath = ""
parts.forEachIndexed { index, s ->
if (index != 0) {
newFieldPath += s
}
}
fieldPath = newFieldPath
}
add(nextInstruction)
} else {
this@apply.instruction = instruction
}
}
nests.add(newNest)
} else {
this@Nest.nests.add(Nest().apply {
name = remainingPath
fullPath = instruction.fieldPath
this@apply.instruction = instruction
resourceName = inferType("${this@Nest.resourceName}.$fullPath") ?: ""
})
}
}
}
fun buildStructureMap(currLevel: Int, questionnaireResponse: QuestionnaireResponse) {
if (instruction != null) {
val answerExpression = instruction?.getAnswerExpression(questionnaireResponse)
if (answerExpression != null) {
if (answerExpression.isNotEmpty() && answerExpression.isNotBlank() && answerExpression != "''") {
val propertyType = inferType(instruction!!.fullPropertyPath())
val answerType = answerExpression.getAnswerType(questionnaireResponse)
if (propertyType != "Type" && answerType != propertyType && propertyType?.canHandleConversion(
answerType ?: ""
)?.not() == true && answerExpression.startsWith("evaluate")
) {
println("Failed type matching --> ${instruction!!.fullPropertyPath()} of type $answerType != $propertyType")
stringBuilder.append("src -> entity$currLevel.${instruction!!.fieldPath} = ")
stringBuilder.append("create('${propertyType.getFhirType()}') as randomVal, randomVal.value = ")
stringBuilder.append(answerExpression)
addRuleNo()
stringBuilder.appendNewLine()
return
}
stringBuilder.append("src -> entity$currLevel.${instruction!!.fieldPath} = ")
stringBuilder.append(answerExpression)
addRuleNo()
stringBuilder.appendNewLine()
}
}
} else if (nests.size > 0) {
//val resourceType = inferType("entity$currLevel.$name", instruction)
if (!name.equals("")) {
val resourceType = resourceName
stringBuilder.append("src -> entity$currLevel.$name = create('$resourceType') as entity${currLevel + 1} then {")
stringBuilder.appendNewLine()
} else {
//stringBuilder.append("src -> entity$currLevel.$name = create('$resourceType') as entity${currLevel + 1} then {")
}
nests.forEach {
it.buildStructureMap(currLevel + 1, questionnaireResponse)
}
//nest!!.buildStructureMap(currLevel + 1)
if (!name.equals("")) {
stringBuilder.append("}")
addRuleNo()
} else {
//addRuleNo()
}
stringBuilder.appendNewLine()
} else {
throw Exception("nest & instruction are null inside Nest object")
}
}
}
}
fun generateStructureMapLine(
structureMapBody: StringBuilder,
row: Row,
resource: Resource,
extractionResources: HashMap<String, Resource>
) {
row.forEachIndexed { index, cell ->
val cellValue = cell.stringCellValue
val fieldPath = row.getCell(4).stringCellValue
val targetDataType = determineFhirDataType(cellValue)
structureMapBody.append("src -> entity.${fieldPath}=")
when (targetDataType) {
"string" -> {
structureMapBody.append("create('string').value ='$cellValue'")
}
"integer" -> {
structureMapBody.append("create('integer').value = $cellValue")
}
"boolean" -> {
val booleanValue =
if (cellValue.equals("true", ignoreCase = true)) "true" else "false"
structureMapBody.append("create('boolean').value = $booleanValue")
}
else -> {
structureMapBody.append("create('unsupportedDataType').value = '$cellValue'")
}
}
structureMapBody.appendNewLine()
}
}
fun determineFhirDataType(cellValue: String): String {
val cleanedValue = cellValue.trim().toLowerCase()
when {
cleanedValue == "true" || cleanedValue == "false" -> return "boolean"
cleanedValue.matches(Regex("-?\\d+")) -> return "boolean"
cleanedValue.matches(Regex("-?\\d*\\.\\d+")) -> return "decimal"
cleanedValue.matches(Regex("\\d{4}-\\d{2}-\\d{2}")) -> return "date"
cleanedValue.matches(Regex("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}")) -> return "dateTime"
else -> {
return "string"
}
}
}
fun StringBuilder.appendNewLine(): StringBuilder {
append(System.lineSeparator())
return this
}
private val Field.isList: Boolean
get() = isParameterized && type == List::class.java
private val Field.isParameterized: Boolean
get() = genericType is ParameterizedType
/** The non-parameterized type of this field (e.g. `String` for a field of type `List<String>`). */
private val Field.nonParameterizedType: Class<*>
get() =
if (isParameterized) (genericType as ParameterizedType).actualTypeArguments[0] as Class<*>
else type
private fun Class<*>.getFieldOrNull(name: String): Field? {
return try {
getDeclaredField(name)
} catch (ex: NoSuchFieldException) {
superclass?.getFieldOrNull(name)
}
}
private fun String.isCoding(questionnaireResponse: QuestionnaireResponse): Boolean {
val answerType = getType(questionnaireResponse)
return if (answerType != null) {
answerType == "org.hl7.fhir.r4.model.Coding"
} else {
false
}
}
private fun String.getType(questionnaireResponse: QuestionnaireResponse): String? {
val answer = fhirPathEngine.evaluate(questionnaireResponse, this)
return answer.firstOrNull()?.javaClass?.name
}
internal val fhirPathEngine: FHIRPathEngine =
with(FhirContext.forCached(FhirVersionEnum.R4)) {
FHIRPathEngine(HapiWorkerContext(this, this.validationSupport)).apply {
hostServices = FHIRPathEngineHostServices
}
}
private fun String.isEnumeration(instruction: Instruction): Boolean {
return inferType(instruction.fullPropertyPath())?.contains("Enumeration") ?: false
}
fun String.getAnswerType(questionnaireResponse: QuestionnaireResponse): String? {
return if (isEvaluateExpression()) {
val fhirPath = substring(indexOf(",") + 1, length - 1)
fhirPath.getType(questionnaireResponse)
?.replace("org.hl7.fhir.r4.model.", "")
} else {
// TODO: WE can run the actual line against StructureMapUtilities.runTransform to get the actual one that is generated and confirm if we need more conversions
"StringType";
}
}
// TODO: Confirm and fix this
fun String.isEvaluateExpression(): Boolean = startsWith("evaluate(")
/**
* Infer's the type and return the short class name eg `HumanName` for org.fhir.hl7.r4.model.Patient
* when given the path `Patient.name`
*/
fun inferType(propertyPath: String): String? {
// TODO: Handle possible errors
// TODO: Handle inferring nested types
val parts = propertyPath.split(".")
val parentResourceClassName = parts[0]
lateinit var parentClass: Class<*>
if (fhirResources.contains(parentResourceClassName)) {
parentClass = Class.forName("org.hl7.fhir.r4.model.$parentResourceClassName")
return inferType(parentClass, parts, 1)
} else {
return null
}
}
fun inferType(parentClass: Class<*>?, parts: List<String>, index: Int): String? {
val resourcePropertyName = parts[index]
val propertyField = parentClass?.getFieldOrNull(resourcePropertyName)
val propertyType = if (propertyField?.isList == true)
propertyField.nonParameterizedType
// TODO: Check if this is required
else if (propertyField?.type == Enumeration::class.java)
// TODO: Check if this works
propertyField.nonParameterizedType
else
propertyField?.type
return if (parts.size > index + 1) {
return inferType(propertyType, parts, index + 1)
} else
propertyType?.name
?.replace("org.hl7.fhir.r4.model.", "")
}
fun String.isMultipleTypes(): Boolean = this == "Type"
// TODO: Finish this. Use the annotation @Chid.type
fun String.getPossibleTypes(): List<Type> {
return listOf()
}
fun String.canHandleConversion(sourceType: String): Boolean {
val propertyClass = Class.forName("org.hl7.fhir.r4.model.$this")
val targetType2 =
if (sourceType == "StringType") String::class.java else Class.forName("org.hl7.fhir.r4.model.$sourceType")
val possibleConversions = listOf(
"BooleanType" to "StringType",
"DateType" to "StringType",
"DecimalType" to "IntegerType",
"AdministrativeGender" to "CodeType"
)
possibleConversions.forEach {
if (this.contains(it.first) && sourceType == it.second) {
return true
}
}
try {
propertyClass.getDeclaredMethod("fromCode", targetType2)
} catch (ex: NoSuchMethodException) {
return false
}
return true
}
fun String.getParentResource(): String? {
return substring(0, lastIndexOf('.'))
}
fun String.getResourceProperty(): String? {
return substring(lastIndexOf('.') + 1)
}
fun String.getFhirType(): String = replace("Type", "")
.lowercase() |
let numeroSecreto = gerarNumeroAleatorio();
let tentativas = 1;
function exibirTextoNaTela(tag, texto) {
let campo = document.querySelector(tag);
campo.innerHTML = texto;
};
function mensagemInicial() {
exibirTextoNaTela('h1', 'Jogo do Número Secreto');
exibirTextoNaTela('p', 'Escolha um número entre 1 e 100');
};
mensagemInicial();
function verificarChute() {
let chute = document.querySelector('input').value;
if (chute > 100 || chute < 1) {
exibirTextoNaTela('p', 'Erro! Digite um número entre 1 e 100!');
} else if (chute > numeroSecreto && chute <= 100) {
exibirTextoNaTela('p', 'O número secreto está abaixo deste número!');
} else if (chute < numeroSecreto && chute <= 100) {
exibirTextoNaTela('p', 'O número secreto está acima deste número!');
} else {
exibirTextoNaTela('h1', 'Acertou!');
let palavraTentativas = tentativas > 1 ? 'tentativas' : 'tentativa';
let mensagemTentativas = `Você descobriu o número secreto em ${tentativas} ${palavraTentativas}!`;
exibirTextoNaTela('p', mensagemTentativas);
document.getElementById('reiniciar').removeAttribute('disabled');
};
tentativas++;
limparCampo();
};
function gerarNumeroAleatorio() {
return parseInt(Math.random() * 10 + 1);
};
function limparCampo() {
chute = document.querySelector('input');
chute.value = '';
};
function novoJogo() {
numeroSecreto = gerarNumeroAleatorio();
tentativas = 1
limparCampo();
mensagemInicial();
document.getElementById('reiniciar').setAttribute('disable', true);
}; |
using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
namespace VRUIP
{
public class TextController : A_ColorController
{
// Settings.
[SerializeField] [Tooltip("If enabled, text will be empty on start and will be waiting for the function call to start typing.")]
private bool enableTyping = false;
[SerializeField] private bool typingOnAwake = false;
[SerializeField] private bool pauseLongerOnPeriod = false;
[SerializeField] private float delayBetweenLetters = 0.04f;
// Events.
[SerializeField] private UnityEvent onTypingFinished = new();
// Components.
[SerializeField] private TextMeshProUGUI text;
private string _currentText = "";
private bool _isTyping;
private bool _typingFinished;
private string _fullText;
private Coroutine _typingCoroutine;
public string Text
{
get => text.text;
set => text.text = value;
}
protected override void Start()
{
base.Start();
if (enableTyping)
{
_fullText = text.text;
text.text = "";
}
if (typingOnAwake)
{
StartTyping();
}
}
/// <summary>
/// Start typing this text.
/// </summary>
public void StartTyping()
{
// Already typed this text.
if (_typingFinished) return;
_typingCoroutine = StartCoroutine(TypeText());
}
private IEnumerator TypeText()
{
if (_isTyping) yield break;
_isTyping = true;
for (int i = 0; i < _fullText.Length; i++)
{
var currentChar = _fullText[i];
_currentText += currentChar;
// Add cursor.
text.text = _currentText + "|";
// If period and waiting longer enabled, wait longer.
if (pauseLongerOnPeriod && currentChar == '.') yield return new WaitForSeconds(delayBetweenLetters * 6);
yield return new WaitForSeconds(delayBetweenLetters);
}
// Remove cursor.
text.text = _currentText;
_isTyping = false;
_typingFinished = true;
onTypingFinished?.Invoke();
}
private void OnDisable()
{
if (_typingCoroutine == null) return;
StopCoroutine(_typingCoroutine);
onTypingFinished?.Invoke();
text.text = _fullText;
_isTyping = false;
_typingFinished = true;
}
protected override void SetColors(ColorTheme theme)
{
text.color = theme.secondaryColor;
}
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ver Reservas</title>
<!-- Incluye los estilos de Tailwind CSS utilizando una CDN -->
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body>
<div class="container mx-auto p-4">
<h1 class="text-3xl font-bold mb-4">Reservas</h1>
<table class="table-auto border-collapse border border-gray-400">
<thead>
<tr>
<th class="px-4 py-2 bg-gray-200 border border-gray-400">Fecha</th>
<th class="px-4 py-2 bg-gray-200 border border-gray-400">Hora</th>
<th class="px-4 py-2 bg-gray-200 border border-gray-400">Personas</th>
<th class="px-4 py-2 bg-gray-200 border border-gray-400">Nombre Cliente</th>
<th class="px-4 py-2 bg-gray-200 border border-gray-400">Acciones</th>
</tr>
</thead>
<tbody>
{% for reserva in reservas %}
<tr>
<td class="px-4 py-2 border border-gray-400">{{ reserva.fecha }}</td>
<td class="px-4 py-2 border border-gray-400">{{ reserva.hora }}</td>
<td class="px-4 py-2 border border-gray-400">{{ reserva.personas }}</td>
<td class="px-4 py-2 border border-gray-400">{{ reserva.nombre_cliente }}</td>
<td class="px-4 py-2 border border-gray-400">
<a href="/modificar_reserva/{{ reserva.id }}" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-1 px-2 rounded">Modificar</a>
<a href="/cancelar_reserva/{{ reserva.id }}" class="bg-red-500 hover:bg-red-700 text-white font-bold py-1 px-2 rounded">Cancelar</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<!-- Formulario para agregar una reserva manualmente -->
<h2 class="text-2xl font-bold mt-8 mb-4">Agregar Reserva</h2>
<form action="/agregar_reserva" method="post" class="border border-gray-400 p-4 rounded">
<div class="mb-4">
<label for="fecha" class="block text-sm font-bold mb-2">Fecha:</label>
<input type="date" id="fecha" name="fecha" required class="w-full border border-gray-300 p-2 rounded">
</div>
<div class="mb-4">
<label for="hora" class="block text-sm font-bold mb-2">Hora:</label>
<input type="time" id="hora" name="hora" required class="w-full border border-gray-300 p-2 rounded">
</div>
<div class="mb-4">
<label for="personas" class="block text-sm font-bold mb-2">Número de Personas:</label>
<input type="number" id="personas" name="personas" min="1" required class="w-full border border-gray-300 p-2 rounded">
</div>
<div class="mb-4">
<label for="nombre" class="block text-sm font-bold mb-2">Nombre del Cliente:</label>
<input type="text" id="nombre" name="nombre" required class="w-full border border-gray-300 p-2 rounded">
</div>
<button type="submit" class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">Agregar Reserva</button>
</form>
</div>
</body>
</html> |
import { motion } from "framer-motion";
import { useEffect, useState } from "react";
import { kataSemangat } from "../data/constant/PositiveWord";
export default function PositiveWordComponent() {
const [currentIndex, setCurrentIndex] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
setCurrentIndex((prevIndex) => (prevIndex + 1) % kataSemangat.length);
}, 5000); // Change interval (in milliseconds) to adjust speed
return () => clearInterval(intervalId);
}, [kataSemangat.length]); // Dependency array ensures effect runs only once
const currentText = kataSemangat[currentIndex];
return (
<div className="running-text md:flex gap-3 items-center hidden">
<div>
<img src={currentText.flag} width={22}></img>
</div>
<motion.span
key={currentText.text} // Key based on current text for reactivity
animate={{ x: 0, y: 0, opacity: 1 }} // Initial position animation
transition={{ duration: 1 }} // Adjust animation speed
initial={{ y: "10px", opacity: 0 }} // Start text off-screen
whileInView={{ x: 0 }} // Animate to position on scroll
viewport={{ once: false }} // Animate on every scroll into view
>
{currentText.text}
</motion.span>
</div>
);
} |
import { Card, Col, Row } from "antd";
import { useContext } from "react";
import FavoritesContext from "../../context/favoritesCotext";
import { CiHeart } from "react-icons/ci";
import { Link } from "react-router-dom";
const { Meta } = Card;
const FavoritesPage = () => {
const { favs, setFavs } = useContext(FavoritesContext);
return (
<div id="favorites">
<div className="container">
<div className="favorites">
<Row gutter={16}>
{favs.length > 0 &&
favs.map((w) => {
return (
<Col
className="gutter-row"
span={8}
key={w._id}
xs={24}
md={12}
lg={8}
>
<Card
style={{ position: "relative" }}
hoverable
cover={<img alt="example" src={w.imageUrl} />}
>
<Meta
title={<Link to={`/products/${w._id}`}>{w.title}</Link>}
description={`$ ${w.price}`}
/>
<CiHeart
style={{
position: "absolute",
right: 5,
top: 5,
fontSize: "1.5rem",
}}
onClick={() => {
setFavs([...favs.filter((q) => q._id !== w._id)]);
localStorage.setItem(
"favs",
JSON.stringify([
...favs.filter((q) => q._id !== w._id),
])
);
}}
/>
</Card>
</Col>
);
})}
</Row>
</div>
</div>
</div>
);
};
export default FavoritesPage; |
import React, { FC, ChangeEvent } from "react";
interface TextAreaProps {
id: string;
label: string;
value: string;
onChange: (event: ChangeEvent<HTMLTextAreaElement>) => void;
placeholder?: string;
rows?: number;
cols?: number;
required?: boolean;
}
const TextArea: FC<TextAreaProps> = ({
id,
label,
value,
onChange,
placeholder = "",
rows = 3,
cols = 30,
required,
}) => {
return (
<div className="textarea-group">
<label htmlFor={id} className="sr-only">
{label}
</label>
<textarea
id={id}
value={value}
onChange={onChange}
placeholder={placeholder}
rows={rows}
cols={cols}
aria-label={label}
style={{
width: "100%",
borderRadius: 2,
border: "2px solid #000",
margin: "8px 0",
boxSizing: "border-box",
padding: "8px 16px",
fontSize: 16,
}}
required={required}
/>
</div>
);
};
export default TextArea; |
Me:
Generate a data model, incorporating what data needs to be stored and how it needs to be linked as Django file.
At a high level here are all the entities that you have:
Users (of type either instructor or students)
Courses (instructors teach these and students take these)
Lectures (particular days for each course)
QR Codes (uploads that are associated with lectures and students)
ChatGPT:
To model the entities described (Users, Courses, Lectures, and QR Codes) and their relationships in Django,
we'll create a set of models that define the data structure and the relationships between these entities.
Below is an example of how you can set up these models in Django:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Custom User model to differentiate between instructors and students
class User(AbstractUser):
USER_TYPE_CHOICES = (
('instructor', 'Instructor'),
('student', 'Student'),
)
user_type = models.CharField(max_length=20, choices=USER_TYPE_CHOICES)
def __str__(self):
return self.username
# Course model to represent courses taught by instructors
class Course(models.Model):
name = models.CharField(max_length=100)
instructor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='courses_taught')
def __str__(self):
return self.name
# Lecture model to represent lectures scheduled for each course
class Lecture(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='lectures')
date = models.DateField()
def __str__(self):
return f'{self.course.name} - Lecture on {self.date}'
# QRCode model to represent uploaded QR codes associated with lectures and students
class QRCode(models.Model):
lecture = models.ForeignKey(Lecture, on_delete=models.CASCADE, related_name='qr_codes')
student = models.ForeignKey(User, on_delete=models.CASCADE, related_name='qr_codes_scanned')
qr_image = models.ImageField(upload_to='qrcodes/')
def __str__(self):
return f'QR Code for {self.lecture} - Scanned by {self.student.username}'
In this Django model setup:
User Model:
Inherits from AbstractUser to provide basic user functionalities.
Includes a custom field user_type to differentiate between instructors and students.
The user_type field is a choice field with options for 'instructor' or 'student'.
Course Model:
Represents a course taught by an instructor.
Contains a foreign key instructor linking to the User model (instructor).
Lecture Model:
Represents a lecture scheduled for a specific course on a particular date.
Contains a foreign key course linking to the Course model.
QRCode Model:
Represents a QR code uploaded and associated with a specific lecture and student.
Contains foreign keys lecture and student linking to the Lecture and User models respectively.
Includes an qr_image field to upload the QR code image.
Usage and Querying Examples:
1. Creating a new Course:
instructor = User.objects.get(username='instructor1')
course = Course.objects.create(name='Introduction to Django', instructor=instructor)
2. Adding a Lecture to a Course:
course = Course.objects.get(name='Introduction to Django')
lecture = Lecture.objects.create(course=course, date='2024-04-10')
3. Uploading a QR Code for a Lecture:
lecture = Lecture.objects.get(course__name='Introduction to Django', date='2024-04-10')
student = User.objects.get(username='student1')
qr_code = QRCode.objects.create(lecture=lecture, student=student, qr_image='path_to_image.png')
4. Querying QR Codes Scanned by a Student:
student = User.objects.get(username='student1')
qr_codes_scanned = QRCode.objects.filter(student=student)
This Django model setup allows you to manage users (instructors and students), courses, lectures, and QR codes efficiently and
query relationships between these entities as needed. Adjust the model fields and relationships based on your specific
requirements and application logic.
Me:
We think that this data model seems a lot more simple and streamlined compared to our unique data model.
However, we think that ChatGPT lacks the information from the helper functions that we incorporated
within out unique data model which is more informative overall. We think at its core, ChatGPT's data
model is a lot more simpler and easier to implement at a higher level compared to ours, but it is less
informative from a documentation standpoint. |
/* eslint-disable no-unused-expressions */
/* eslint-disable camelcase */
/* eslint-disable react-hooks/rules-of-hooks */
import { useState } from 'react';
import { useQueryClient } from 'react-query';
import {
Container,
ContentContainer,
FooterContainer
} from './styles';
import ActionHeader from '../../components/ActionHeader';
import ModalDevice, { DeviceFormData } from '../../components/Modal/Device/ModalCreateDevice';
import ModalConnectDevice from '../../components/Modal/Device/ModalConnectDevice ';
import ModalDeviceUpdate from '../../components/Modal/Device/ModalUpdateDevice';
import { useApi } from '../../services/hooks/useApi';
import { HTTPMethod, Recurse } from '../../services/api';
import { useToast } from '../../hook/toast';
import Appointment from '../../components/Appointment/Device';
import { findAllDevices } from '../../services/hooks/useDeviceFetch';
interface IFindAllDevicesResponse {
id: string;
code: string;
model: string;
variant: string;
status: string;
created_at: string;
updated_at: string;
}
export default function Devices ():JSX.Element {
const [modalVisible, setModalVisible] = useState(false)
const [modalEditVisible, setModalEditVisible] = useState(false)
const [modalConnectVisible, setModalConnectVisible] = useState(false)
const [editedValues, setEditedValues] = useState<Omit< IFindAllDevicesResponse, "created_at" | "updated_at">>({
code: '',
id: '',
model: '',
status: '',
variant: ''
})
const { addToast } = useToast();
const queryClient = useQueryClient()
const {fullData} = findAllDevices<IFindAllDevicesResponse>()
function showConnectModal(deviceData: Omit< IFindAllDevicesResponse, "created_at" | "updated_at">) {
setEditedValues(deviceData)
setModalConnectVisible(true)
}
function showEditModal(deviceData: Omit< IFindAllDevicesResponse, "created_at" | "updated_at">) {
setEditedValues(deviceData)
setModalEditVisible(true)
}
async function updateDevice(deviceData:Omit< IFindAllDevicesResponse, "created_at" | "updated_at">) {
const response = await useApi(deviceData, HTTPMethod.patch, Recurse.updateDevice)
if (response.status === 200 ) {
setModalEditVisible(false)
addToast({
type: 'success',
title: 'Device editado com sucesso',
description: `Cadastro ${response.statusText}`
})
queryClient.resetQueries('deviceslist')
}else {
addToast({
type: 'error',
title: 'Erro ao Cadastrar',
description: ` ${response.data.message}`
})
}
}
async function handleConnectDevice(deviceData:Omit< IFindAllDevicesResponse, "created_at" | "updated_at">) {
const response = await useApi(deviceData, HTTPMethod.patch, Recurse.updateDevice)
if (response.status === 200 ) {
setModalEditVisible(false)
addToast({
type: 'success',
title: 'Device editado com sucesso',
description: `Cadastro ${response.statusText}`
})
queryClient.resetQueries('deviceslist')
}else {
addToast({
type: 'error',
title: 'Erro ao Cadastrar',
description: ` ${response.data.message}`
})
}
}
async function removeDevice(id:string) {
const response = await useApi(id, HTTPMethod.delete, Recurse.removeDevice)
if (response.status === 204 ) {
addToast({
type: 'success',
title: 'Device Excluido com sucesso',
description: `Exclusão ${response.statusText}`
})
queryClient.resetQueries('deviceslist')
}else {
addToast({
type: 'error',
title: 'Erro ao Excluir',
description: ` ${response.data.message}`
})
}
}
async function createDevice(data: DeviceFormData): Promise<any> {
setModalVisible(false)
const response = await useApi(data, HTTPMethod.post, Recurse.createDevice)
if (response.status === 200 ) {
addToast({
type: 'success',
title: 'Device cadastrado com sucesso',
description: `Cadastro ${response.statusText}`
})
queryClient.resetQueries('deviceslist')
}else {
addToast({
type: 'error',
title: 'Erro ao Cadastrar',
description: ` ${response.data.message}`
})
}
}
return (
<Container>
<ActionHeader
buttonFilter
buttonRegister
registerbuttonClick={() => setModalVisible(true)}
/>
<ContentContainer>
{fullData.map( device => (
<Appointment
key={device.id}
values={device}
clickExclude={(id: string) => removeDevice(id)}
clickUpdate={
(deviceData: Omit< IFindAllDevicesResponse, "created_at" | "updated_at">) =>
showEditModal(deviceData)
}
clickConnect={
(deviceData: Omit< IFindAllDevicesResponse, "created_at" | "updated_at">) =>
showConnectModal(deviceData)
}
/>
))}
</ContentContainer>
<FooterContainer />
<ModalDevice
isOpen={modalVisible}
setIsOpen={() => setModalVisible(false)}
handleAddDevice={(data) => createDevice(data)}
/>
<ModalDeviceUpdate
isOpen={modalEditVisible}
setIsOpen={() => setModalEditVisible(false)}
values={editedValues}
handleUpdateDevice={(device) => updateDevice(device)}
/>
<ModalConnectDevice
isOpen={modalConnectVisible}
setIsOpen={() => setModalConnectVisible(false)}
values={editedValues}
handleConnectDevice={(device) => handleConnectDevice(device)}
/>
</Container>
);
}; |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
using Theatre.Data.Models.Enums;
namespace Theatre.Data.Models
{
public class Play
{
public Play()
{
this.Casts = new List<Cast>();
this.Tickets = new List<Ticket>();
}
[Key]
public int Id { get; set; }
[Required]
[StringLength(50, MinimumLength =4)]
public string Title { get; set; }
[Required]
[Column(TypeName="time")]
public TimeSpan Duration { get; set; }
[Required]
[Range(typeof(float),"0.00","10.00")]
public float Rating { get; set; }
[Required]
public Genre Genre { get; set; }
[Required]
[MaxLength(700)]
public string Description { get; set; }
[Required]
[StringLength(30, MinimumLength =4)]
public string Screenwriter { get; set; }
public ICollection<Cast> Casts { get; set; }
public ICollection<Ticket> Tickets { get; set; }
}
}
// • Id – integer, Primary Key
// • Title – text with length [4, 50] (required)
// • Duration – TimeSpan in format
// { hours: minutes: seconds}, with a minimum length of 1 hour. (required)
// • Rating – float in the range[0.00….10.00] (required)
// • Genre – enumeration of type Genre, with possible values (Drama, Comedy, Romance, Musical) (required)
// • Description – text with length up to 700 characters (required)
// • Screenwriter – text with length [4, 30] (required)
// • Casts – a collection of type Cast
// • Tickets – a collection of type Ticket |
<?php
//Início: Classe usuário
class Usuario {
private $idusuario;
private $deslogin;
private $dessenha;
private $dtcadastro;
//Get's and Set's idUsuario
public function getIdusuario(){return $this->idusuario;}
public function setIdusuario($value){$this->idusuario = $value;}
//Get's and Set's desLogin
public function getDeslogin(){return $this->deslogin;}
public function setDeslogin($value){$this->deslogin = $value;}
//Get's and Set's desSenha
public function getDessenha(){return $this->dessenha;}
public function setDessenha($value){$this->dessenha = $value;}
//Get's and Set's dtCadastro
public function getDtcadastro(){return $this->dtcadastro;}
public function setDtcadastro($value){$this->dtcadastro = $value;}
//Inicio: Método select por id
public function loadById($id){
$sql = new Sql();
$result = $sql->select("SELECT * FROM tb_usuarios WHERE idUsuario = :ID", array(
":ID"=>$id
));
if (isset($result[0])) {
$this->setData($result[0]);
}
}
//Término: Método select por id
//Inicio: Método select por usuário
public static function search($login){
$sql = new Sql();
return $sql->select("SELECT * FROM tb_usuarios WHERE deslogin LIKE :SEARCH ORDER BY deslogin",
array(
':SEARCH'=>"%".$login."%"
));
}
//Término: Método select por usuário
//Início: Método validação de Login
public function login($login, $password){
$sql = new Sql();
$result = $sql->select("SELECT * FROM tb_usuarios WHERE deslogin = :LOGIN AND dessenha = :PASSWORD", array(
":LOGIN"=>$login,
":PASSWORD"=>$password
));
if (isset($result[0])) {
$this->setData($result[0]);
} else {
throw new Exception("Login e/ou senha invalidos.");
}
}
//Término: Método validação de Login
//Já foi utilizado várias vezes o results então foi criado um método
public function setData($data){
$this->setIdusuario($data['idusuario']);
$this->setDeslogin($data['deslogin']);
$this->setDessenha($data['dessenha']);
$this->setDtcadastro(new DateTime($data['dtcadastro']));
}
//Início: Método para inserir dados no banco
public function insert(){
$sql = new Sql();
//Será criado uma procedure
$results = $sql->select("CALL sp_usuarios_insert(:LOGIN, :SENHA)", array(
':LOGIN'=>$this->getDeslogin(),
':SENHA'=>$this->getDessenha()
));
if (count($results) > 0) {
$this->setData($results[0]);
}
}
//Término: Método para inserir dados no banco
//Início: Método para selecionar todos usuários da tabela
public static function getList(){
//Método static porque não utilizo o $this que faz ref a variaveis
$sql = new Sql();
return $sql->select("SELECT * FROM tb_usuarios ORDER BY deslogin");
}
//Término: Método para selecionar todos usuários da tabela
//Início: Método update
public function update($login, $password){
$this->setDeslogin($login);
$this->setDessenha($password);
$sql = new Sql();
$sql->query("UPDATE tb_usuarios SET deslogin = :LOGIN, dessenha = :PASSWORD WHERE idusuario = :ID", array(
':LOGIN'=>$this->getDeslogin(),
':PASSWORD'=>$this->getDessenha(),
':ID'=>$this->getIdusuario()
));
}
//Término: Método update
//Início: Método delete
public function delete (){
$sql = new Sql();
$sql->query("DELETE FROM tb_usuarios WHERE idUsuario = :ID", array(
':ID'=>$this->getIdusuario()
));
$this->setIdusuario(0);
$this->setDeslogin("");
$this->setDessenha("");
$this->setDtcadastro(new DateTime());
}
//Término: Método delete
//Início: Método construtor
public function __construct($login="", $password=""){
$this->setDeslogin($login);
$this->setDessenha($password);
}
//Término: Método construtor
//Início: Método toString
public function __toString(){
return json_encode(array(
"idusuario"=>$this->getIdusuario(),
"deslogin"=>$this->getDeslogin(),
"dessenha"=>$this->getDessenha(),
"dtcadastro"=>$this->getDtcadastro()->format("d/m/Y H:i:s")
));
}
//Término: Método toString
}
//Término: Classe usuário
?> |
#pragma warning(disable : 4996)
#pragma once
#define _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING
#define _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS
#include <thread>
#include <condition_variable>
#include <iterator>
#include <functional>
#include <vector>
#include <queue>
#include <mutex>
#include <future>
#include <algorithm>
#include <optional>
// we define Our Parallel Pattern namespace -> OPP
namespace OPP
{
extern unsigned nbThreads;
/**
* This class implements a thread-barrier.
* The constructor needs the number of used threads.
* When a thread calls the "arrive_and_wait()" method,
* it will sleep until the number of sleeping threads
* equals the number of used threads. Then, they will
* be wake up ...
* The barrier may be used once, twice, and so on.
*/
class Barrier
{
std::mutex mutex;
std::condition_variable cv;
const uint32_t nbThreadsInBarrier;
uint32_t nbExpectedThreads;
public:
Barrier(const uint32_t nb)
: nbThreadsInBarrier(nb), nbExpectedThreads(nb)
{}
~Barrier() = default;
Barrier(const Barrier&) = delete;
Barrier& operator=(const Barrier&) = delete;
void arrive_and_wait() {
std::unique_lock<std::mutex> lock(mutex);
-- nbExpectedThreads;
if( nbExpectedThreads > 0 )
cv.wait(lock);
else {
nbExpectedThreads = nbThreadsInBarrier; // reset
cv.notify_all();
}
lock.unlock(); }
};
/**
* This class implements a thread semaphore.
*
* Actually, counting and binary semaphore are available in C++ ... from version 20!
*
* The constructor is also the initialiser of the counting value.
*/
template<typename T=uint32_t>
class Semaphore
{
std::mutex mutex;
std::condition_variable cv;
T value;
public:
// creates (and initializes) a new Semaphore
Semaphore(const T init=T(0))
: value(init)
{}
~Semaphore() = default;
Semaphore(const Semaphore&) = delete;
Semaphore& operator=(const Semaphore&) = delete;
// Acquires the semaphore (P)
void acquire(const T how=T(1))
{
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [=] { return value >= std::max(T(1),how) ;});
value -= std::max(T(1),how);
}
// Releases the semaphore (V)
void release(const T how=T(1))
{
const std::lock_guard<std::mutex> lock(mutex);
T n = std::max(T(1),how);
value += n; // warning, here an overflow may occur ...
while(n--)
cv.notify_one();
}
};
class ThreadPool
{
// need some polymorphism to be able to return a correct std::shared_future ...
struct Job
{
virtual ~Job() = default;
virtual void run() = 0;
};
// the use class to store real tasks
template <typename R>
struct AnyJob : public Job
{
std::packaged_task<R()> task;
AnyJob(std::packaged_task<R()> func) : task(std::move(func)) {}
void run()
{
task();
}
};
// queue of jobs
class jobs_queue
{
using ulock = std::unique_lock<std::mutex>;
using glock = std::lock_guard<std::mutex>;
public:
void push(std::shared_ptr<Job> job)
{
glock l(mutex);
queue.emplace(std::move(job));
condition_variable.notify_one();
}
std::optional<std::shared_ptr<Job>> pop()
{
ulock l(mutex);
condition_variable.wait(l, [this]{ return abort || !queue.empty(); } );
if (abort)
return std::nullopt;
auto job = queue.front();
queue.pop();
return job;
}
void terminate()
{
glock l(mutex);
abort = true;
condition_variable.notify_all();
}
~jobs_queue()
{
terminate();
}
private:
std::mutex mutex;
std::queue<std::shared_ptr<Job>> queue;
std::condition_variable condition_variable;
bool abort = false;
}; // class job_queues
const uint32_t maxThreads = uint32_t(std::thread::hardware_concurrency());
// list of workers (threads)
std::vector<std::thread> workers;
// our threads' pool contains a list of jobs to run
jobs_queue jobs;
// add workers, setting the function they will run
void add_workers(const uint32_t n = 1)
{
for(uint32_t i=0; i<n; ++i)
{
// creates one thread with infinite loop
std::thread thread(
[=] {
while (true)
{
// get one job (blocking function)
auto optional_job = jobs.pop();
// check if exit is requested
if (!optional_job)
break; // exit requested
// get the job from the optional value
std::shared_ptr<Job> job = (*optional_job);
// and run the job !
job->run();
}
}
);
// put the thread into the vector of workers
workers.emplace_back( std::move(thread) );
}
}
public:
// push a R() function, i.e. function returning R and taking no arguments
// NB : void() functions are allowed ;-)
template <typename _Fct>
auto push_task( _Fct&& f )
{
// gets the returning type
using R = typename std::invoke_result<_Fct>::type; // Warning: since C++17
// make a task from the function, allowing to get at "future"
std::packaged_task<R()> task(std::move(f));
// gets the future
std::shared_future<R> future = task.get_future();
// push the task into the jobs queue
jobs.push( std::make_shared<AnyJob<R>>( std::move(task) ) );
// returns the future
return future;
}
// returns the real number of threads ...
auto getRealThreadNumber()
{
return workers.size();
}
// constructor
ThreadPool(uint32_t nbThreads)
{
add_workers(std::min(nbThreads, maxThreads));
}
ThreadPool() = delete;
ThreadPool(const ThreadPool&) = delete;
ThreadPool &operator=(const ThreadPool&) = delete;
// do some cleaning ... stop the threads!
~ThreadPool()
{
jobs.terminate();
std::for_each(workers.begin(), workers.end(), [] (std::thread &th) { th.join();});
}
};
ThreadPool& getDefaultThreadPool();
// counting iterator ... T should be an integer (char/short/int/long/long long, signed or unsigned)
template<
typename T=long,
typename Tdiff=long long>
class CountingIterator : public std::iterator<std::random_access_iterator_tag, T>
{
T position;
public:
using pointer = typename std::iterator<std::random_access_iterator_tag,T>::pointer;
using reference = typename std::iterator<std::random_access_iterator_tag,T>::reference;
CountingIterator(const T position=T(0))
: position(position)
{}
CountingIterator(const CountingIterator& cit) = default;
~CountingIterator() = default;
CountingIterator& operator=(const CountingIterator&) = default;
CountingIterator& operator++() {
++position;
return *this;
}
CountingIterator operator++(int) const {
return CountingIterator(position++);
}
CountingIterator& operator--() {
--position;
return *this;
}
CountingIterator operator--(int) const {
return CountingIterator(position--);
}
bool operator==(const CountingIterator& cit) const {
return position == cit.position;
}
bool operator!=(const CountingIterator& cit) const {
return position != cit.position ;
}
T operator*() const {
return position;
}
T& operator*() {
return position;
}
CountingIterator operator+(const Tdiff& dt) const {
return CountingIterator(T(position+dt));
}
CountingIterator& operator+=(const Tdiff& dt) {
position += dt;
return *this;
}
CountingIterator operator-(const Tdiff& dt) const {
return CountingIterator(T(position-dt));
}
CountingIterator& operator-=(const Tdiff& dt) {
position -= dt;
return *this;
}
T operator[](const Tdiff& n) const {
return position+n;
}
bool operator<(const CountingIterator& cit) const {
return position < cit.position;
}
bool operator>(const CountingIterator& cit) const {
return position > cit.position;
}
bool operator<=(const CountingIterator& cit) const {
return position <= cit.position;
}
bool operator>=(const CountingIterator& cit) const {
return position >= cit.position;
}
Tdiff operator+(const CountingIterator& cit) const {
return position + cit.position;
}
Tdiff operator-(const CountingIterator& cit) const {
return position - cit.position;
}
};
template<typename T>
CountingIterator<T> make_counting_iterator(T position) {
return CountingIterator(position);
}
template<
typename Iterator,
typename Functor,
typename Tsrc,
typename Tdst,
typename Tdiff=long long
>
class TransformIterator : public std::iterator<std::random_access_iterator_tag, Tdst, Tdiff,void,void>
{
Functor transform;
Iterator iterator;
public:
TransformIterator(const Iterator& iterator, const Functor& transform)
: transform(transform), iterator(iterator)
{}
TransformIterator(Iterator&& iterator, Functor&& transform)
: transform(transform), iterator(iterator)
{}
TransformIterator(const TransformIterator&) = default;
~TransformIterator() = default;
TransformIterator& operator=(const TransformIterator&) = default;
TransformIterator& operator++() {
++iterator;
return *this;
}
TransformIterator operator++(int) const {
auto copy = TransformIterator(iterator, transform);
++iterator;
return copy;
}
TransformIterator& operator--() {
--iterator;
return *this;
}
TransformIterator operator--(int) const {
auto copy = TransformIterator(iterator, transform);
--iterator;
return copy;
}
bool operator==(const TransformIterator& cit) const {
return iterator == cit.iterator && transform == cit.transform;
}
bool operator!=(const TransformIterator& cit) const {
return ! ( *this == cit );
}
Tdst operator*() const {
return std::invoke(transform, *iterator);
}
TransformIterator operator+(const Tdiff& dt) const {
return TransformIterator(iterator+dt, transform);
}
TransformIterator& operator+=(const Tdiff& dt) {
iterator += dt;
return *this;
}
TransformIterator operator-(const Tdiff& dt) const {
return TransformIterator(iterator-dt, transform);
}
TransformIterator& operator-=(const Tdiff& dt) {
iterator -= dt;
return *this;
}
Tdst operator[](const Tdiff& n) const {
return std::invoke(transform, iterator[n]);
}
bool operator<(const TransformIterator& cit) const {
return iterator < cit.iterator;
}
bool operator>(const TransformIterator& cit) const {
return iterator > cit.iterator;
}
bool operator<=(const TransformIterator& cit) const {
return iterator <= cit.iterator;
}
bool operator>=(const TransformIterator& cit) const {
return iterator >= cit.iterator;
}
Tdiff operator+(const TransformIterator& cit) const {
return iterator + cit.iterator;
}
Tdiff operator-(const TransformIterator& cit) const {
return iterator - cit.iterator;
}
};
template<
typename Iterator,
typename Tsrc,
typename Tdst,
typename Tdiff=long long>
inline
auto make_transform_iterator(Iterator iterator, std::function<Tdst(Tsrc)> functor)
{
//using Tsrc = typename Iterator::value_type;
//using Tdst = typename functor::result_type; // n�cessite une std::function<Tdst(Tsrc)> ....
return TransformIterator<Iterator,std::function<Tdst(Tsrc)>,Tsrc,Tdst,Tdiff>(iterator, functor);
}
} |
'use client'
import { Repository, RepositoryArray } from '@/app/interfaces/Interfaces';
import React, { ReactNode, useEffect, useState, createContext, useContext } from 'react';
export const dataContext = createContext<RepositoryArray| undefined>(undefined);
export const DataContextProvider = ({ children } : {children: ReactNode}) => {
const [repo, setRepo] = useState<Repository[]>([]);
useEffect(() => {
const username = 'Danilo-Couto';
const apiUrl = `https://api.github.com/users/${username}/repos`;
const accessToken = process.env.NEXT_PUBLIC_GITHUB_ACCESS_TOKEN;
if (!accessToken) {
throw new Error('GitHub access token not provided in environment variables.');
}
const fetchRepos = async (url: RequestInfo | URL) => {
try {
const response = await fetch(url, {
headers: {
Authorization: `token ${accessToken}`,
},
});
const data = await response.json();
const filteredRepo = data.filter((r: { fork: boolean; stargazers_count : number}) => !r.fork && r.stargazers_count > 0 );
const linkHeader = response.headers.get('Link');
if (linkHeader) {
const linksArray = linkHeader.split(', ');
const nextPageUrl = linksArray.find(link => link.includes('rel="next"'));
if (nextPageUrl) {
const nextUrl = nextPageUrl.match(/<([^>]*)>/);
if (nextUrl) {
const nextPage = nextUrl[1];
fetchRepos(nextPage);
}
}
}
setRepo(prevRepo => {
const uniqueData = filteredRepo.filter((newData: { id: string; }) => prevRepo.every(prevData => newData.id !== prevData.id));
return [...prevRepo, ...uniqueData];
});
} catch (error) {
throw new Error(`API request failed with status ${error}`);
}
};
// Initial fetch
fetchRepos(apiUrl);
}, []);
return (
<dataContext.Provider value={{ repo }}>
{children}
</dataContext.Provider>
);
};
export const useDataContext = () => useContext(dataContext); |
---
import SearchWidget from './SearchWidget.astro';
import Search from './SearchWidget.astro';
---
<nav id="navbar">
<div
class="max-w-screen-xl flex flex-wrap items-center justify-between mx-auto p-4">
<a href="/" class="flex items-center">
<img
src="https://res.cloudinary.com/dgakih33l/image/upload/v1688440085/assmattoury/hero_ubeakr.png"
class="h-14 mr-5"
alt="Nounours"
/>
<span
class="self-center text-2xl font-semibold whitespace-nowrap dark:text-white"
>Accueil</span
>
</a>
<button
data-collapse-toggle="navbar-dropdown"
type="button"
class="inline-flex items-center p-2 ml-3 text-sm text-pink-500 rounded-lg md:hidden hover:bg-pink-100 focus:outline-none focus:ring-2 ring-pink-200"
aria-controls="navbar-dropdown"
aria-expanded="false">
<svg
class="w-10 h-10 text-white bg-blue-800 rounded-2xl p-1"
aria-hidden="true"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
><path
fill-rule="evenodd"
d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 15a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z"
clip-rule="evenodd"></path></svg
>
</button>
<div
class="hidden w-full md:block md:w-auto font-bold text-xl"
id="navbar-dropdown">
<ul
class="flex flex-col font-medium p-4 md:p-0 mt-4 border rounded-lg md:flex-row md:space-x-8 md:mt-0 md:border-0">
<details>
<summary
role="button"
class="hover:text-blue-700 md:p-0 md:w-auto cursor-pointer"
>Présentation</summary
>
<ul class="list-disc px-7 text-sm">
<li>
<a
href="/about"
class="hover:text-blue-700 md:p-0 md:w-auto cursor-pointer text-base"
>A propos</a
>
</li>
<li>
<a
href="/activity"
class="hover:text-blue-700 md:p-0 md:w-auto cursor-pointer text-base"
>Activités</a
>
</li>
<li>
<a
href="/days"
class="hover:text-blue-700 md:p-0 md:w-auto cursor-pointer text-base"
>Journées Type</a
>
</li>
</ul>
</details>
<details>
<summary
role="button"
class="hover:text-blue-700 md:p-0 md:w-auto cursor-pointer rounded-xl"
>Ressources</summary
>
<ul class="list-disc px-7 text-sm">
<li>
<a
href="/start"
class="block hover:text-blue-700 rounded-lg text-base"
>Avant tout</a
>
</li>
<li>
<a
href="/caf"
class="block hover:text-blue-700 rounded-lg text-base">CAF</a
>
</li>
<li>
<a
href="/pajemploi"
class="block hover:text-blue-700 rounded-lg text-base"
>Pajemploi+</a
>
</li>
<li>
<a
href="/nounou"
class="block hover:text-blue-700 rounded-lg text-base"
>Top-Assmat</a
>
</li>
</ul>
</details>
<details>
<summary
role="button"
class="hover:text-blue-700 md:p-0 md:w-auto cursor-pointer"
>Coût</summary
>
<ul class="list-disc px-7 text-sm">
<li>
<a
href="/price"
class="block hover:text-blue-700 rounded-lg text-base"
>Taux horaires</a
>
</li>
<li>
<a
href="/rates"
class="block hover:text-blue-700 rounded-lg text-base">Repas</a
>
</li>
<li>
<a
href="/indemnity"
class="block hover:text-blue-700 rounded-lg text-base"
>Indemnités d'entretien</a
>
</li>
<li>
<a
href="/calculate"
class="block hover:text-blue-700 rounded-lg text-base"
>Evaluez vos dépenses</a
>
</li>
</ul>
</details>
<li>
<a
href="/faq"
class="hover:text-blue-700 md:p-0 md:w-auto cursor-pointer">FAQ</a
>
</li>
<li>
<a
href="/contact"
class="hover:text-blue-700 md:p-0 md:w-auto cursor-pointer"
>Contact</a
>
</li>
</ul>
</div>
</div>
</nav>
<script>
// Get the navbar element
const navbar = document.getElementById('navbar');
// Initialize the previous scroll position
let prevScrollpos = window.scrollY;
// Add an event listener to the window object to detect when the user scrolls
window.addEventListener('scroll', () => {
// Get the current scroll position
const currentScrollPos = window.scrollY;
// Determine the direction of the scroll
const isScrollingDown = currentScrollPos > prevScrollpos;
// Animate the navbar based on the direction of the scroll
if (isScrollingDown) {
navbar.style.transform = 'translateY(-100%)';
} else {
navbar.style.transform = 'translateY(0)';
}
// Update the previous scroll position
prevScrollpos = currentScrollPos;
});
</script> |
/**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: BUSL-1.1
*/
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import sinon from 'sinon';
module('Unit | Service | console', function (hooks) {
setupTest(hooks);
hooks.beforeEach(function () {});
hooks.afterEach(function () {});
const testCases = [
{
method: 'read',
args: ['/sys/health', {}],
expectedURL: 'sys/health',
expectedVerb: 'GET',
expectedOptions: { data: undefined, wrapTTL: undefined },
},
{
method: 'read',
args: ['/secrets/foo/bar', {}, { wrapTTL: '30m' }],
expectedURL: 'secrets/foo/bar',
expectedVerb: 'GET',
expectedOptions: { data: undefined, wrapTTL: '30m' },
},
{
method: 'write',
args: ['aws/roles/my-other-role', { arn: 'arn=arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess' }],
expectedURL: 'aws/roles/my-other-role',
expectedVerb: 'POST',
expectedOptions: {
data: { arn: 'arn=arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess' },
wrapTTL: undefined,
},
},
{
method: 'list',
args: ['secret/mounts', {}],
expectedURL: 'secret/mounts/',
expectedVerb: 'GET',
expectedOptions: { data: { list: true }, wrapTTL: undefined },
},
{
method: 'list',
args: ['secret/mounts', {}, { wrapTTL: '1h' }],
expectedURL: 'secret/mounts/',
expectedVerb: 'GET',
expectedOptions: { data: { list: true }, wrapTTL: '1h' },
},
{
method: 'delete',
args: ['secret/secrets/kv'],
expectedURL: 'secret/secrets/kv',
expectedVerb: 'DELETE',
expectedOptions: { data: undefined, wrapTTL: undefined },
},
];
test('it reads, writes, lists, deletes', function (assert) {
assert.expect(18);
const ajax = sinon.stub();
const uiConsole = this.owner.factoryFor('service:console').create({
adapter() {
return {
buildURL(url) {
return url;
},
ajax,
};
},
});
testCases.forEach((testCase) => {
uiConsole[testCase.method](...testCase.args);
const [url, verb, options] = ajax.lastCall.args;
assert.strictEqual(url, testCase.expectedURL, `${testCase.method}: uses trimmed passed url`);
assert.strictEqual(verb, testCase.expectedVerb, `${testCase.method}: uses the correct verb`);
assert.deepEqual(options, testCase.expectedOptions, `${testCase.method}: uses the correct options`);
});
});
const kvTestCases = [
{
method: 'kvGet',
args: ['kv/foo'],
expectedURL: 'kv/data/foo',
expectedVerb: 'GET',
expectedOptions: { data: undefined, wrapTTL: undefined },
},
{
method: 'kvGet',
args: ['kv/foo', {}, { metadata: true }],
expectedURL: 'kv/metadata/foo',
expectedVerb: 'GET',
expectedOptions: { data: undefined, wrapTTL: undefined },
},
{
method: 'kvGet',
args: ['kv/foo', {}, { wrapTTL: '10m' }],
expectedURL: 'kv/data/foo',
expectedVerb: 'GET',
expectedOptions: { data: undefined, wrapTTL: '10m' },
},
{
method: 'kvGet',
args: ['kv/foo', {}, { metadata: true, wrapTTL: '10m' }],
expectedURL: 'kv/metadata/foo',
expectedVerb: 'GET',
expectedOptions: { data: undefined, wrapTTL: '10m' },
},
];
test('it reads kv secret and metadata', function (assert) {
assert.expect(12);
const ajax = sinon.stub();
const uiConsole = this.owner.factoryFor('service:console').create({
adapter() {
return {
buildURL(url) {
return url;
},
ajax,
};
},
});
kvTestCases.forEach((testCase) => {
uiConsole[testCase.method](...testCase.args);
const [url, verb, options] = ajax.lastCall.args;
assert.strictEqual(url, testCase.expectedURL, `${testCase.method}: uses correct url`);
assert.strictEqual(verb, testCase.expectedVerb, `${testCase.method}: uses the correct verb`);
assert.deepEqual(options, testCase.expectedOptions, `${testCase.method}: uses the correct options`);
});
});
}); |
---
id: 660f47afe4c98536715d5fa4
title: Step 91
challengeType: 1
dashedName: step-91
---
# --description--
<dfn>严格不等式</dfn>运算符 `!==` 允许你检查两个值是否不相等,或者是否不具有相同的类型。 语法类似于相等运算符:`value !== 4`。
更新 `while` 循环条件以检查 `done` 是否不等于 `count`。
# --hints--
你的 `while` 循环应检查 `done` 和 `count` 是否不相等。
```js
assert.match(__helpers.removeJSComments(code), /while\s*\(\s*(?:done\s*!==\s*count|count\s*!==\s*done)/);
```
# --seed--
## --seed-contents--
```js
const character = "#";
const count = 8;
const rows = [];
function padRow(rowNumber, rowCount) {
return " ".repeat(rowCount - rowNumber) + character.repeat(2 * rowNumber - 1) + " ".repeat(rowCount - rowNumber);
}
// TODO: use a different type of loop
/*for (let i = 1; i <= count; i++) {
rows.push(padRow(i, count));
}*/
let continueLoop = false;
let done = 0;
--fcc-editable-region--
while (continueLoop) {
done++;
rows.push(padRow(done, count));
if (done === count) {
continueLoop = false;
}
}
--fcc-editable-region--
let result = ""
for (const row of rows) {
result = result + "\n" + row;
}
console.log(result);
``` |
package Javaders.Javaders.day25varargsinheritance;
import com.sun.security.jgss.GSSUtil;
public class Vehicle {
/* 1) Javada Object Class tum java classlarinin ortak parentidir
2) Javada Object Class haric tum classlarin parent i vardir.
3) Javada Parent tan child a olan iliskilere HAS A Relation Ship denir
Javada child dan parent a olan iliskilere IS A Relation Ship denir
4) Javada her classin bir tane default constructoru vardir.
Bu default constructor classin icinde gorunmez cunku
default constructor Object Classin icindedir
5) Child class'tan bir object olusturdugumuzda Canstructorlar en
ustteki parent class dan baslatilarak alta dogru calistirilir
6)Child Class'daki constructordan parent classdaki constructor a
gidebilmek icin super() kullanilir
7)Parent classda birden fazla constructor varsa istenilen constructor super()
ifadesinin icine yazilan parametreler yardimi ile secilebilir
8)Ayni class icindeki constructorlari secmek icin this() kullanilir
Ayni classta birden fazla constructor varsa istenilen constructor this()
parantezinin icine yazilan parametreler yardimi ile secilebilir
9)super() ifadesinin yazmak isteger baglidir. Siz yazmasanizda java sanki super()
varmis gibi davranir. Ama kodunuzu daha okunur kilmak icin yazmaniz tavsiye edilir
10) super() ve this() ifadeleri constructor icinde her zaman ilk satirda olmalidir
11)Bir constructor icinde super() ve this() ifadeleri sadece bir kere kullanilabilir
bakiniz 10. madde
12) Inheritance variable'lari ve method'lari cagirmak icin this veya super kullanilir.
this ==> kendi class'indan
super ==> parent class'indan veya nethod cagirmayi saglar.
* */
public Vehicle (){
this(5);
System.out.println("Vehicle 1");
}
public Vehicle (int price){
System.out.println("Vehicle int parametreli");
}
}//class |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strlcat.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aghergho <aghergho@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/31 21:22:28 by aghergho #+# #+# */
/* Updated: 2023/11/12 18:15:38 by aghergho ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
size_t ft_strlcat(char *dest, const char *src, size_t size)
{
size_t len_dest;
size_t len_src;
size_t j;
len_dest = ft_strlen(dest);
len_src = ft_strlen(src);
j = 0;
if (size == 0)
return (len_src);
if (size <= len_dest)
return (len_src + size);
while (src[j] && (len_dest + j) < (size - 1))
{
dest[len_dest + j] = src[j];
j++;
}
dest[len_dest + j] = '\0';
return (len_src + len_dest);
}
int main(void)
{
char dst[100];
char src[100];
strcpy(src, "abde");
strcpy(dst, "gher");
ft_strlcat(dst, src, 100);
printf("%s\n", dst);
return (0);
} |
# Examples for UAT Testing
User Acceptance Testing (UAT) focuses on validating that the system meets the business requirements and is ready for use by end-users.
## UAT Test Cases:
1. ### User Authentication:
Objective: Ensure users can successfully log in.
<br>Test Steps:
- Navigate to the login page.
- Enter valid credentials (username and password).
- Verify successful login and access to the streaming platform.
2. ### Streaming Video Playback:
Objective: Confirm that users can watch streaming MLB videos.
<br>Test Steps:
- Navigate to the MLB streaming page.
- Select a live or recorded video.
- Verify that the video starts playing without interruptions.
Check for video quality and responsiveness.
3. ### Interactive Features:
Objective: Ensure interactive features (e.g., comments, reactions) work as expected.
<br>Test Steps:
- Access a live-streaming event.
- Interact with features like comments or reactions.
- Verify that user interactions are displayed in real-time.
4. ### Content Search and Navigation:
Objective: Confirm that users can easily find and navigate to desired content.
<br>Test Steps:
- Use the search functionality to find specific teams, players, or events.
- Verify that search results are accurate and relevant.
- Navigate to different sections of the platform and ensure smooth transitions.
5. ### User Preferences and Settings:
Objective: Validate that users can customize their preferences and settings.
<br>Test Steps:
- Access the user profile or settings page.
- Modify preferences such as language, notification settings, or video quality.
- Confirm that changes are saved and reflected in the user experience.
6. ### Account Management:
Objective: Ensure users can manage their accounts effectively.
<br>Test Steps:
- Update account information (e.g., email, password).
- Verify that account changes are applied.
- Test the password recovery/reset process.
7. ### Cross-Browser Compatibility:
Objective: Confirm that the streaming platform works across different browsers.
<br>Test Steps:
- Access the platform using different browsers (Chrome, Firefox, Safari).
- Verify that all features and functionalities work consistently.
8. ### Mobile Responsiveness:
Objective: Validate the responsiveness of the platform on mobile devices.
<br>Test Steps:
- Access the platform using various mobile devices (phones, tablets).
- Confirm that the layout adjusts appropriately, and all features are accessible.
9. ### Error Handling:
Objective: Test how the system handles errors and edge cases.
<br>Test Steps:
- Submit invalid login credentials and verify the error message.
- Attempt to access unavailable content and check error handling.
10. ### Performance Testing:
Objective: Assess the platform's performance under varying conditions.
<br>Test Steps:
- Simulate concurrent users accessing the platform.
- Measure and monitor response times during peak usage.
- Verify that the system remains responsive and stable.
UAT Execution Guidelines:
- Collaboration with Stakeholders:
Note: Involve key stakeholders in the UAT process to gather feedback and ensure alignment with business goals.
### Test Data Preparation:
### Best Practices:
- [x] Use real-world data whenever possible to simulate actual user scenarios.
Documentation:
- [x] Document test cases, expected results, and any deviations observed during testing.
Feedback Collection:
- [x] Encourage end-users to provide feedback on their overall experience and any issues encountered.
Regression Testing:
- [x] Execute regression tests to ensure that new features or changes do not impact existing functionality.
Usability Testing:
- [x] Assess the overall usability and intuitiveness of the platform from an end-user perspective.
Accessibility Testing:
- [x] Verify that the application complies with accessibility standards to accommodate users with diverse needs.
Performance Monitoring:
- [x] Monitor system performance during UAT to identify potential bottlenecks or areas for optimization.
Scalability Testing:
If applicable, simulate an increase in user load to validate the platform's scalability.
Test Environment:
- [x] Ensure that the UAT environment closely mirrors the production environment. |
"use client";
import Button from "@/app/components/Button";
import Input from "@/app/components/input/Input";
import Modal from "@/app/components/Modal";
import Select from "@/app/components/input/Select";
import { User } from "@prisma/client";
import axios from "axios";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { FieldValues, SubmitHandler, useForm } from "react-hook-form";
import { toast } from "react-hot-toast";
interface GroupChatModalProps {
users: User[];
isOpen?: boolean;
onClose: () => void;
}
const GroupChatModal: React.FC<GroupChatModalProps> = ({
users = [],
isOpen,
onClose,
}) => {
const router = useRouter();
const [isLoading, setIsLoading] = useState(false);
const {
register,
handleSubmit,
setValue,
watch,
formState: { errors },
} = useForm<FieldValues>({
defaultValues: {
name: "",
members: [],
},
});
const members = watch("members");
const onSubmit: SubmitHandler<FieldValues> = (data) => {
setIsLoading(true);
axios
.post("/api/conversations", {
...data,
isGroup: true,
})
.then(() => {
router.refresh();
onClose();
})
.catch(() => toast.error("뭔가 잘못되었어요!"))
.finally(() => setIsLoading(false));
};
return (
<Modal isOpen={isOpen} onClose={onClose}>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="space-y-12">
<div className="border-b border-gray-900/10 pb-12">
<h2
className="
text-base
font-semibold
leading-7
text-gray-900
"
>
그룹채팅 만들기
</h2>
<p>2명이상의 친구를 선택하고 그룹채팅을 만드세요</p>
<div className="mt-10 flex flex-col gap-y-8">
<Input
register={register}
label="이름"
id="name"
disabled={isLoading}
required
errors={errors}
/>
<Select
disabled={isLoading}
label="Members"
options={users.map((user) => ({
value: user.id,
label: user.name,
}))}
onChange={(value) =>
setValue("members", value, {
shouldValidate: true,
})
}
value={members}
/>
</div>
</div>
</div>
<div className="mt-6 flex items-center justify-end gap-x-6">
<Button
disabled={isLoading}
onClick={onClose}
type="button"
secondary
>
취소
</Button>
<Button disabled={isLoading} type="submit">
만들기
</Button>
</div>
</form>
</Modal>
);
};
export default GroupChatModal; |
using JokesApp.DataLayer;
using JokesApp.Shared.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace JokesApp.ServerSide
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<JokesDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<JokesDbContext>();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<DataSeeder>();
services.AddScoped<IJokesService, JokesService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataSeeder dataSeeder)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
dataSeeder.Seed();
}
}
} |
#pragma once
#include "Observable.h"
#include "Point.h"
#include "Target.h"
using net::draconia::util::Observable;
namespace net
{
namespace draconia
{
namespace games
{
namespace bane
{
namespace model
{
class Character : public Observable, public Target
{
int miAgility, miConstitution, miDexterity, miIntelligence, miStrength;
unsigned muiHitPoints, muiMagicPoints, muiMaxHitPoints, muiMaxMagicPoints;
public:
Character();
Character(const int iAgility, const int iConstitution, const int iDexterity, const int iIntelligence, const int iStrength);
Character(const Character &refCopy);
~Character();
int getAgility() const;
int getConstitution() const;
unsigned getCurrentHitPoints() const;
unsigned getCurrentMagicPoints() const;
unsigned getDefense() const;
int getDexterity() const;
int getIntelligence() const;
unsigned getMagic() const;
unsigned getMaxHitPoints() const;
unsigned getMaxMagicPoints() const;
unsigned getSpellResistance() const;
int getStrength() const;
void setAgility(const int iAgility);
void setConstitution(const int iConstitution);
void setCurrentHitPoints(const unsigned uiHitPoints);
void setCurrentMagicPoints(const unsigned uiMagicPoints);
void setDexterity(const int iDexterity);
void setIntelligence(const int iIntelligence);
void setMaxHitPoints(const unsigned uiHitPoints);
void setMaxMagicPoints(const unsigned uiMagicPoints);
void setStrength(const int iStrength);
Character &operator=(const Character &refCopy);
bool operator==(const Character &refOther) const;
bool operator!=(const Character &refOther) const;
};
}
}
}
}
} |
import React from 'react';
import '../style/SignUp.css';
import {useNavigate} from "react-router-dom";
import logo from "../icons/MovieTube-logo.png";
import { auth } from'../utils/firebase-config';
import { useForm, SubmitHandler } from "react-hook-form";
import { createUserWithEmailAndPassword } from 'firebase/auth';
type Inputs = {
email: string,
password: string,
passwordConf: string
}
function SignUpPage() {
const { register, handleSubmit } = useForm<Inputs>();
const onSignUp: SubmitHandler<Inputs> = async (formData)=> {
try {
if(formData.password === formData.passwordConf) {
createUserWithEmailAndPassword(auth, formData.email, formData.password).then().catch((error) => {alert(error.message)});
console.log('passwords matches');
console.log(`Account creation attempt email: ${formData.email} password: ${formData.password} and password: ${formData.passwordConf}`);
}
} catch (error) {
console.error('Error creating user!');
}
}
const navigate = useNavigate()
return(
<div className='signUp-container'>
<div>
<img className='signUp-logo-icon' src={logo} alt='logo'/>
<button className='signUp-button' onClick={() => {
navigate('/')
}}>Login
</button>
<div className='signUp-gradient'/>
</div>
<div className='signUp-content'>
<h1>Sign Up</h1>
<div className='signUp-form'>
<form onSubmit={handleSubmit(onSignUp)}>
<input {...register('email')} type='email' placeholder='Email'/>
<input {...register('password')} type='password' placeholder='Password'/>
<input {...register('passwordConf')} type='password' placeholder='Confirm password'/>
<button type='submit' className='signUp-submit-button'>Create Account</button>
<h5>Already have an account?
<span className='signUp-bold' onClick={() => {
navigate('/signin')
}}>Sing In!</span>
</h5>
</form>
</div>
</div>
</div>
);
}
export default SignUpPage; |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/DOMRequestHelper.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
"@mozilla.org/childprocessmessagemanager;1", "nsISyncMessageSender");
XPCOMUtils.defineLazyServiceGetter(this, "tm",
"@mozilla.org/thread-manager;1", "nsIThreadManager");
/*
* A WeakMap to map input method iframe window to
* it's active status, kbID, and ipcHelper.
*/
let WindowMap = {
// WeakMap of <window, object> pairs.
_map: null,
/*
* Set the object associated to the window and return it.
*/
_getObjForWin: function(win) {
if (!this._map) {
this._map = new WeakMap();
}
if (this._map.has(win)) {
return this._map.get(win);
} else {
let obj = {
active: false,
kbID: undefined,
ipcHelper: null
};
this._map.set(win, obj);
return obj;
}
},
/*
* Check if the given window is active.
*/
isActive: function(win) {
if (!this._map || !win) {
return false;
}
return this._getObjForWin(win).active;
},
/*
* Set the active status of the given window.
*/
setActive: function(win, isActive) {
if (!win) {
return;
}
let obj = this._getObjForWin(win);
obj.active = isActive;
},
/*
* Get the keyboard ID (assigned by Keyboard.jsm) of the given window.
*/
getKbID: function(win) {
if (!this._map || !win) {
return undefined;
}
let obj = this._getObjForWin(win);
return obj.kbID;
},
/*
* Set the keyboard ID (assigned by Keyboard.jsm) of the given window.
*/
setKbID: function(win, kbID) {
if (!win) {
return;
}
let obj = this._getObjForWin(win);
obj.kbID = kbID;
},
/*
* Get InputContextDOMRequestIpcHelper instance attached to this window.
*/
getInputContextIpcHelper: function(win) {
if (!win) {
return;
}
let obj = this._getObjForWin(win);
if (!obj.ipcHelper) {
obj.ipcHelper = new InputContextDOMRequestIpcHelper(win);
}
return obj.ipcHelper;
},
/*
* Unset InputContextDOMRequestIpcHelper instance.
*/
unsetInputContextIpcHelper: function(win) {
if (!win) {
return;
}
let obj = this._getObjForWin(win);
if (!obj.ipcHelper) {
return;
}
obj.ipcHelper = null;
}
};
let cpmmSendAsyncMessageWithKbID = function (self, msg, data) {
data.kbID = WindowMap.getKbID(self._window);
cpmm.sendAsyncMessage(msg, data);
};
/**
* InputMethodManager
*/
function MozInputMethodManager(win) {
this._window = win;
}
MozInputMethodManager.prototype = {
_supportsSwitching: false,
_window: null,
classID: Components.ID("{7e9d7280-ef86-11e2-b778-0800200c9a66}"),
QueryInterface: XPCOMUtils.generateQI([]),
showAll: function() {
if (!WindowMap.isActive(this._window)) {
return;
}
cpmmSendAsyncMessageWithKbID(this, 'Keyboard:ShowInputMethodPicker', {});
},
next: function() {
if (!WindowMap.isActive(this._window)) {
return;
}
cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SwitchToNextInputMethod', {});
},
supportsSwitching: function() {
if (!WindowMap.isActive(this._window)) {
return false;
}
return this._supportsSwitching;
},
hide: function() {
if (!WindowMap.isActive(this._window)) {
return;
}
cpmmSendAsyncMessageWithKbID(this, 'Keyboard:RemoveFocus', {});
}
};
/**
* InputMethod
*/
function MozInputMethod() { }
MozInputMethod.prototype = {
__proto__: DOMRequestIpcHelper.prototype,
_inputcontext: null,
_wrappedInputContext: null,
_layouts: {},
_window: null,
_isSystem: false,
_isKeyboard: true,
classID: Components.ID("{4607330d-e7d2-40a4-9eb8-43967eae0142}"),
QueryInterface: XPCOMUtils.generateQI([
Ci.nsIDOMGlobalPropertyInitializer,
Ci.nsIObserver,
Ci.nsISupportsWeakReference
]),
init: function mozInputMethodInit(win) {
this._window = win;
this._mgmt = new MozInputMethodManager(win);
this.innerWindowID = win.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils)
.currentInnerWindowID;
Services.obs.addObserver(this, "inner-window-destroyed", false);
let principal = win.document.nodePrincipal;
let perm = Services.perms.testExactPermissionFromPrincipal(principal,
"input-manage");
if (perm === Ci.nsIPermissionManager.ALLOW_ACTION) {
this._isSystem = true;
}
perm = Services.perms.testExactPermissionFromPrincipal(principal, "input");
if (perm !== Ci.nsIPermissionManager.ALLOW_ACTION) {
this._isKeyboard = false;
return;
}
cpmm.addWeakMessageListener('Keyboard:FocusChange', this);
cpmm.addWeakMessageListener('Keyboard:SelectionChange', this);
cpmm.addWeakMessageListener('Keyboard:GetContext:Result:OK', this);
cpmm.addWeakMessageListener('Keyboard:LayoutsChange', this);
cpmm.addWeakMessageListener('InputRegistry:Result:OK', this);
cpmm.addWeakMessageListener('InputRegistry:Result:Error', this);
},
uninit: function mozInputMethodUninit() {
this._window = null;
this._mgmt = null;
Services.obs.removeObserver(this, "inner-window-destroyed");
if (!this._isKeyboard) {
return;
}
cpmm.removeWeakMessageListener('Keyboard:FocusChange', this);
cpmm.removeWeakMessageListener('Keyboard:SelectionChange', this);
cpmm.removeWeakMessageListener('Keyboard:GetContext:Result:OK', this);
cpmm.removeWeakMessageListener('Keyboard:LayoutsChange', this);
cpmm.removeWeakMessageListener('InputRegistry:Result:OK', this);
cpmm.removeWeakMessageListener('InputRegistry:Result:Error', this);
this.setActive(false);
},
receiveMessage: function mozInputMethodReceiveMsg(msg) {
if (!msg.name.startsWith('InputRegistry') &&
!WindowMap.isActive(this._window)) {
return;
}
let data = msg.data;
let resolver = ('requestId' in data) ?
this.takePromiseResolver(data.requestId) : null;
switch(msg.name) {
case 'Keyboard:FocusChange':
if (data.type !== 'blur') {
// XXX Bug 904339 could receive 'text' event twice
this.setInputContext(data);
}
else {
this.setInputContext(null);
}
break;
case 'Keyboard:SelectionChange':
if (this.inputcontext) {
this._inputcontext.updateSelectionContext(data, false);
}
break;
case 'Keyboard:GetContext:Result:OK':
this.setInputContext(data);
break;
case 'Keyboard:LayoutsChange':
this._layouts = data;
break;
case 'InputRegistry:Result:OK':
resolver.resolve();
break;
case 'InputRegistry:Result:Error':
resolver.reject(data.error);
break;
}
},
observe: function mozInputMethodObserve(subject, topic, data) {
let wId = subject.QueryInterface(Ci.nsISupportsPRUint64).data;
if (wId == this.innerWindowID)
this.uninit();
},
get mgmt() {
return this._mgmt;
},
get inputcontext() {
if (!WindowMap.isActive(this._window)) {
return null;
}
return this._wrappedInputContext;
},
set oninputcontextchange(handler) {
this.__DOM_IMPL__.setEventHandler("oninputcontextchange", handler);
},
get oninputcontextchange() {
return this.__DOM_IMPL__.getEventHandler("oninputcontextchange");
},
setInputContext: function mozKeyboardContextChange(data) {
if (this._inputcontext) {
this._inputcontext.destroy();
this._inputcontext = null;
this._wrappedInputContext = null;
this._mgmt._supportsSwitching = false;
}
if (data) {
this._mgmt._supportsSwitching = this._layouts[data.type] ?
this._layouts[data.type] > 1 :
false;
this._inputcontext = new MozInputContext(data);
this._inputcontext.init(this._window);
// inputcontext will be exposed as a WebIDL object. Create its
// content-side object explicitly to avoid Bug 1001325.
this._wrappedInputContext =
this._window.MozInputContext._create(this._window, this._inputcontext);
}
let event = new this._window.Event("inputcontextchange",
Cu.cloneInto({}, this._window));
this.__DOM_IMPL__.dispatchEvent(event);
},
setActive: function mozInputMethodSetActive(isActive) {
if (WindowMap.isActive(this._window) === isActive) {
return;
}
WindowMap.setActive(this._window, isActive);
if (isActive) {
// Activate current input method.
// If there is already an active context, then this will trigger
// a GetContext:Result:OK event, and we can initialize ourselves.
// Otherwise silently ignored.
// get keyboard ID from Keyboard.jsm,
// or if we already have it, get it from our map
// Note: if we need to get it from Keyboard.jsm,
// we have to use a synchronous message
var kbID = WindowMap.getKbID(this._window);
if (kbID) {
cpmmSendAsyncMessageWithKbID(this, 'Keyboard:Register', {});
} else {
let res = cpmm.sendSyncMessage('Keyboard:Register', {});
WindowMap.setKbID(this._window, res[0]);
}
cpmmSendAsyncMessageWithKbID(this, 'Keyboard:GetContext', {});
} else {
// Deactive current input method.
cpmmSendAsyncMessageWithKbID(this, 'Keyboard:Unregister', {});
if (this._inputcontext) {
this.setInputContext(null);
}
}
},
addInput: function(inputId, inputManifest) {
return this.createPromiseWithId(function(resolverId) {
let appId = this._window.document.nodePrincipal.appId;
cpmm.sendAsyncMessage('InputRegistry:Add', {
requestId: resolverId,
inputId: inputId,
inputManifest: inputManifest,
appId: appId
});
}.bind(this));
},
removeInput: function(inputId) {
return this.createPromiseWithId(function(resolverId) {
let appId = this._window.document.nodePrincipal.appId;
cpmm.sendAsyncMessage('InputRegistry:Remove', {
requestId: resolverId,
inputId: inputId,
appId: appId
});
}.bind(this));
},
setValue: function(value) {
this._ensureIsSystem();
cpmm.sendAsyncMessage('System:SetValue', {
'value': value
});
},
setSelectedOption: function(index) {
this._ensureIsSystem();
cpmm.sendAsyncMessage('System:SetSelectedOption', {
'index': index
});
},
setSelectedOptions: function(indexes) {
this._ensureIsSystem();
cpmm.sendAsyncMessage('System:SetSelectedOptions', {
'indexes': indexes
});
},
removeFocus: function() {
this._ensureIsSystem();
cpmm.sendAsyncMessage('System:RemoveFocus', {});
},
_ensureIsSystem: function() {
if (!this._isSystem) {
throw new this._window.Error("Should have 'input-manage' permssion.");
}
}
};
/**
* InputContextDOMRequestIpcHelper
*/
function InputContextDOMRequestIpcHelper(win) {
this.initDOMRequestHelper(win,
["Keyboard:GetText:Result:OK",
"Keyboard:GetText:Result:Error",
"Keyboard:SetSelectionRange:Result:OK",
"Keyboard:ReplaceSurroundingText:Result:OK",
"Keyboard:SendKey:Result:OK",
"Keyboard:SendKey:Result:Error",
"Keyboard:SetComposition:Result:OK",
"Keyboard:EndComposition:Result:OK",
"Keyboard:SequenceError"]);
}
InputContextDOMRequestIpcHelper.prototype = {
__proto__: DOMRequestIpcHelper.prototype,
_inputContext: null,
attachInputContext: function(inputCtx) {
if (this._inputContext) {
throw new Error("InputContextDOMRequestIpcHelper: detach the context first.");
}
this._inputContext = inputCtx;
},
// Unset ourselves when the window is destroyed.
uninit: function() {
WindowMap.unsetInputContextIpcHelper(this._window);
},
detachInputContext: function() {
// All requests that are still pending need to be invalidated
// because the context is no longer valid.
this.forEachPromiseResolver(k => {
this.takePromiseResolver(k).reject("InputContext got destroyed");
});
this._inputContext = null;
},
receiveMessage: function(msg) {
if (!this._inputContext) {
dump('InputContextDOMRequestIpcHelper received message without context attached.\n');
return;
}
this._inputContext.receiveMessage(msg);
}
};
/**
* InputContext
*/
function MozInputContext(ctx) {
this._context = {
inputtype: ctx.type,
inputmode: ctx.inputmode,
lang: ctx.lang,
type: ["textarea", "contenteditable"].indexOf(ctx.type) > -1 ?
ctx.type :
"text",
selectionStart: ctx.selectionStart,
selectionEnd: ctx.selectionEnd,
textBeforeCursor: ctx.textBeforeCursor,
textAfterCursor: ctx.textAfterCursor
};
this._contextId = ctx.contextId;
}
MozInputContext.prototype = {
_window: null,
_context: null,
_contextId: -1,
_ipcHelper: null,
classID: Components.ID("{1e38633d-d08b-4867-9944-afa5c648adb6}"),
QueryInterface: XPCOMUtils.generateQI([
Ci.nsIObserver,
Ci.nsISupportsWeakReference
]),
init: function ic_init(win) {
this._window = win;
this._ipcHelper = WindowMap.getInputContextIpcHelper(win);
this._ipcHelper.attachInputContext(this);
},
destroy: function ic_destroy() {
// A consuming application might still hold a cached version of
// this object. After destroying all methods will throw because we
// cannot create new promises anymore, but we still hold
// (outdated) information in the context. So let's clear that out.
for (var k in this._context) {
if (this._context.hasOwnProperty(k)) {
this._context[k] = null;
}
}
this._ipcHelper.detachInputContext();
this._ipcHelper = null;
this._window = null;
},
receiveMessage: function ic_receiveMessage(msg) {
if (!msg || !msg.json) {
dump('InputContext received message without data\n');
return;
}
let json = msg.json;
let resolver = this._ipcHelper.takePromiseResolver(json.requestId);
if (!resolver) {
dump('InputContext received invalid requestId.\n');
return;
}
// Update context first before resolving promise to avoid race condition
if (json.selectioninfo) {
this.updateSelectionContext(json.selectioninfo, true);
}
switch (msg.name) {
case "Keyboard:SendKey:Result:OK":
resolver.resolve(true);
break;
case "Keyboard:SendKey:Result:Error":
resolver.reject(json.error);
break;
case "Keyboard:GetText:Result:OK":
resolver.resolve(json.text);
break;
case "Keyboard:GetText:Result:Error":
resolver.reject(json.error);
break;
case "Keyboard:SetSelectionRange:Result:OK":
case "Keyboard:ReplaceSurroundingText:Result:OK":
resolver.resolve(
Cu.cloneInto(json.selectioninfo, this._window));
break;
case "Keyboard:SequenceError":
// Occurs when a new element got focus, but the inputContext was
// not invalidated yet...
resolver.reject("InputContext has expired");
break;
case "Keyboard:SetComposition:Result:OK": // Fall through.
case "Keyboard:EndComposition:Result:OK":
resolver.resolve(true);
break;
default:
dump("Could not find a handler for " + msg.name);
resolver.reject();
break;
}
},
updateSelectionContext: function ic_updateSelectionContext(ctx, ownAction) {
if (!this._context) {
return;
}
let selectionDirty = this._context.selectionStart !== ctx.selectionStart ||
this._context.selectionEnd !== ctx.selectionEnd;
let surroundDirty = this._context.textBeforeCursor !== ctx.textBeforeCursor ||
this._context.textAfterCursor !== ctx.textAfterCursor;
this._context.selectionStart = ctx.selectionStart;
this._context.selectionEnd = ctx.selectionEnd;
this._context.textBeforeCursor = ctx.textBeforeCursor;
this._context.textAfterCursor = ctx.textAfterCursor;
if (selectionDirty) {
this._fireEvent("selectionchange", {
selectionStart: ctx.selectionStart,
selectionEnd: ctx.selectionEnd,
ownAction: ownAction
});
}
if (surroundDirty) {
this._fireEvent("surroundingtextchange", {
beforeString: ctx.textBeforeCursor,
afterString: ctx.textAfterCursor,
ownAction: ownAction
});
}
},
_fireEvent: function ic_fireEvent(eventName, aDetail) {
let detail = {
detail: aDetail
};
let event = new this._window.CustomEvent(eventName,
Cu.cloneInto(detail, this._window));
this.__DOM_IMPL__.dispatchEvent(event);
},
// tag name of the input field
get type() {
return this._context.type;
},
// type of the input field
get inputType() {
return this._context.inputtype;
},
get inputMode() {
return this._context.inputmode;
},
get lang() {
return this._context.lang;
},
getText: function ic_getText(offset, length) {
let self = this;
return this._sendPromise(function(resolverId) {
cpmmSendAsyncMessageWithKbID(self, 'Keyboard:GetText', {
contextId: self._contextId,
requestId: resolverId,
offset: offset,
length: length
});
});
},
get selectionStart() {
return this._context.selectionStart;
},
get selectionEnd() {
return this._context.selectionEnd;
},
get textBeforeCursor() {
return this._context.textBeforeCursor;
},
get textAfterCursor() {
return this._context.textAfterCursor;
},
setSelectionRange: function ic_setSelectionRange(start, length) {
let self = this;
return this._sendPromise(function(resolverId) {
cpmmSendAsyncMessageWithKbID(self, 'Keyboard:SetSelectionRange', {
contextId: self._contextId,
requestId: resolverId,
selectionStart: start,
selectionEnd: start + length
});
});
},
get onsurroundingtextchange() {
return this.__DOM_IMPL__.getEventHandler("onsurroundingtextchange");
},
set onsurroundingtextchange(handler) {
this.__DOM_IMPL__.setEventHandler("onsurroundingtextchange", handler);
},
get onselectionchange() {
return this.__DOM_IMPL__.getEventHandler("onselectionchange");
},
set onselectionchange(handler) {
this.__DOM_IMPL__.setEventHandler("onselectionchange", handler);
},
replaceSurroundingText: function ic_replaceSurrText(text, offset, length) {
let self = this;
return this._sendPromise(function(resolverId) {
cpmmSendAsyncMessageWithKbID(self, 'Keyboard:ReplaceSurroundingText', {
contextId: self._contextId,
requestId: resolverId,
text: text,
offset: offset || 0,
length: length || 0
});
});
},
deleteSurroundingText: function ic_deleteSurrText(offset, length) {
return this.replaceSurroundingText(null, offset, length);
},
sendKey: function ic_sendKey(dictOrKeyCode, charCode, modifiers, repeat) {
if (typeof dictOrKeyCode === 'number') {
// XXX: modifiers are ignored in this API method.
return this._sendPromise((resolverId) => {
cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SendKey', {
contextId: this._contextId,
requestId: resolverId,
method: 'sendKey',
keyCode: dictOrKeyCode,
charCode: charCode,
repeat: repeat
});
});
} else if (typeof dictOrKeyCode === 'object') {
return this._sendPromise((resolverId) => {
cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SendKey', {
contextId: this._contextId,
requestId: resolverId,
method: 'sendKey',
keyboardEventDict: this._getkeyboardEventDict(dictOrKeyCode)
});
});
} else {
// XXX: Should not reach here; implies WebIDL binding error.
throw new TypeError('Unknown argument passed.');
}
},
keydown: function ic_keydown(dict) {
return this._sendPromise((resolverId) => {
cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SendKey', {
contextId: this._contextId,
requestId: resolverId,
method: 'keydown',
keyboardEventDict: this._getkeyboardEventDict(dict)
});
});
},
keyup: function ic_keyup(dict) {
return this._sendPromise((resolverId) => {
cpmmSendAsyncMessageWithKbID(this, 'Keyboard:SendKey', {
contextId: this._contextId,
requestId: resolverId,
method: 'keyup',
keyboardEventDict: this._getkeyboardEventDict(dict)
});
});
},
setComposition: function ic_setComposition(text, cursor, clauses, dict) {
let self = this;
return this._sendPromise((resolverId) => {
cpmmSendAsyncMessageWithKbID(self, 'Keyboard:SetComposition', {
contextId: self._contextId,
requestId: resolverId,
text: text,
cursor: (typeof cursor !== 'undefined') ? cursor : text.length,
clauses: clauses || null,
keyboardEventDict: this._getkeyboardEventDict(dict)
});
});
},
endComposition: function ic_endComposition(text, dict) {
let self = this;
return this._sendPromise((resolverId) => {
cpmmSendAsyncMessageWithKbID(self, 'Keyboard:EndComposition', {
contextId: self._contextId,
requestId: resolverId,
text: text || '',
keyboardEventDict: this._getkeyboardEventDict(dict)
});
});
},
_sendPromise: function(callback) {
let self = this;
return this._ipcHelper.createPromiseWithId(function(aResolverId) {
if (!WindowMap.isActive(self._window)) {
self._ipcHelper.removePromiseResolver(aResolverId);
reject('Input method is not active.');
return;
}
callback(aResolverId);
});
},
// Take a MozInputMethodKeyboardEventDict dict, creates a keyboardEventDict
// object that can be sent to forms.js
_getkeyboardEventDict: function(dict) {
if (typeof dict !== 'object' || !dict.key) {
return;
}
var keyboardEventDict = {
key: dict.key,
code: dict.code,
repeat: dict.repeat,
flags: 0
};
if (dict.printable) {
keyboardEventDict.flags |=
Ci.nsITextInputProcessor.KEY_FORCE_PRINTABLE_KEY;
}
if (/^[a-zA-Z0-9]$/.test(dict.key)) {
// keyCode must follow the key value in this range;
// disregard the keyCode from content.
keyboardEventDict.keyCode = dict.key.toUpperCase().charCodeAt(0);
} else if (typeof dict.keyCode === 'number') {
// Allow keyCode to be specified for other key values.
keyboardEventDict.keyCode = dict.keyCode;
// Allow keyCode to be explicitly set to zero.
if (dict.keyCode === 0) {
keyboardEventDict.flags |=
Ci.nsITextInputProcessor.KEY_KEEP_KEYCODE_ZERO;
}
}
return keyboardEventDict;
}
};
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([MozInputMethod]); |
$(function () {
// Prepare demo data
var data = [
{
"hc-key": "us-ky-01",
"value": 0
},
{
"hc-key": "us-ky-03",
"value": 1
},
{
"hc-key": "us-ky-05",
"value": 2
},
{
"hc-key": "us-ky-06",
"value": 3
},
{
"hc-key": "us-ky-02",
"value": 4
},
{
"hc-key": "us-ky-04",
"value": 5
}
];
// Initiate the chart
$('#container').highcharts('Map', {
title : {
text : 'Highmaps basic demo'
},
subtitle : {
text : 'Source map: <a href="http://code.highcharts.com/mapdata/countries/us/custom/us-ky-congress-113.js">Kentucky congressional districts</a>'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
colorAxis: {
min: 0
},
series : [{
data : data,
mapData: Highcharts.maps['countries/us/custom/us-ky-congress-113'],
joinBy: 'hc-key',
name: 'Random data',
states: {
hover: {
color: '#BADA55'
}
},
dataLabels: {
enabled: true,
format: '{point.name}'
}
}]
});
}); |
import Stack from "@mui/material/Stack";
import TextField from "@mui/material/TextField";
import Styles from "./AddressModal.module.css";
import MenuItem from "@mui/material/MenuItem";
import Radio from "@mui/material/Radio";
import RadioGroup from "@mui/material/RadioGroup";
import FormControlLabel from "@mui/material/FormControlLabel";
import FormControl from "@mui/material/FormControl";
import FormLabel from "@mui/material/FormLabel";
import AddressLabel from "./AddressLabel";
import HomeIcon from "@mui/icons-material/Home";
import BusinessCenterIcon from "@mui/icons-material/BusinessCenter";
import AddCircleOutlineRoundedIcon from "@mui/icons-material/AddCircleOutlineRounded";
import PrimaryButton from "../../../shared/Buttons/PrimaryButton";
import * as React from "react";
const Provinces = [
{
value: "KPK",
label: "KPK",
},
{
value: "Sindh",
label: "Sindh",
},
];
const Cities = [
{
value: "karachi",
label: "karachi",
},
{
value: "Hyderabad",
label: "Hyderabad",
},
];
const Areas = [
{
value: "area 1",
label: "area 1",
},
{
value: "area 2",
label: "area 2",
},
];
const AddressModal = () => {
const [Province, setProvince] = React.useState("");
const [City, setCity] = React.useState("");
const [Area, setArea] = React.useState("");
const handleProvinceChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setProvince(event.target.value);
};
const handleCityChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setCity(event.target.value);
};
const handleAreaChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setArea(event.target.value);
};
return (
<div>
<Stack className={Styles.modalDescription}>
<TextField
label="Complete Address"
id="Complete Address"
margin="normal"
/>
<Stack
direction={{ xs: "column", md: "row" }}
alignItems="center"
justifyContent="space-between"
spacing={{ xs: 1, md: 2 }}
>
<TextField
fullWidth
id="outlined-select-Province"
select
label="Province"
value={Province}
onChange={handleProvinceChange}
margin="normal"
>
{Provinces.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</TextField>
<TextField
fullWidth
id="outlined-select-Cities"
select
label="Cities"
value={City}
onChange={handleCityChange}
margin="normal"
>
{Cities.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</TextField>
</Stack>
<Stack
direction={{ xs: "column", md: "row" }}
alignItems="center"
justifyContent="space-between"
spacing={{ xs: 1, md: 2 }}
>
<TextField
fullWidth
id="outlined-select-Area"
select
label="Area"
value={Area}
onChange={handleAreaChange}
margin="normal"
>
{Areas.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</TextField>
<TextField label="Contact" id="Contact" margin="normal" fullWidth />
</Stack>
<FormControl component="fieldset">
<FormLabel component="legend" className={Styles.LabelHeading}>
Add a Label
</FormLabel>
<RadioGroup
aria-label="add a label"
defaultValue="Home"
name="radio-buttons-group"
row
className={Styles.AddressLabelGroup}
>
<FormControlLabel
value="Home"
control={<Radio />}
label={<AddressLabel icon={<HomeIcon />} labelName="Home" />}
/>
<FormControlLabel
value="Office"
control={<Radio />}
label={
<AddressLabel
icon={<BusinessCenterIcon />}
labelName="Office"
/>
}
/>
<FormControlLabel
value="Others"
control={<Radio />}
label={
<AddressLabel
icon={<AddCircleOutlineRoundedIcon />}
labelName="Others"
/>
}
/>
</RadioGroup>
</FormControl>
<div className="mx-2 mt-2">
<PrimaryButton buttonText="Add Address" customStyleClasses="" />
</div>
</Stack>
</div>
);
};
export default AddressModal; |
<?php
namespace Bytes\DiscordCommandsBundle\Commands;
use Bytes\DiscordClientBundle\Slash\SlashCommandInterface;
use Bytes\DiscordResponseBundle\Enums\ApplicationCommandOptionType as ACOT;
use Bytes\DiscordResponseBundle\Enums\Permissions;
use Bytes\DiscordResponseBundle\Objects\Application\Command\ChatInputCommand;
use Bytes\DiscordResponseBundle\Objects\Slash\ApplicationCommand;
use Bytes\DiscordResponseBundle\Objects\Slash\ApplicationCommandOption as Option;
use Bytes\DiscordResponseBundle\Objects\Slash\ApplicationCommandOptionChoice;
/**
*
*/
class Ff7r implements SlashCommandInterface
{
/**
* @return ApplicationCommand
*/
public static function createCommand(): ApplicationCommand
{
return ChatInputCommand::createChatCommand(static::getDefaultIndexName(), 'How long will it be until Final Fantasy VII Remake releases?', [
Option::create(ACOT::STRING, 'version', 'Which part of the remake?', false, [
ApplicationCommandOptionChoice::create('Part 1'),
ApplicationCommandOptionChoice::create('Part 1 Intergrade'),
ApplicationCommandOptionChoice::create('Part 2')
])
]);
}
/**
* Return the command name
* @return string
*/
public static function getDefaultIndexName(): string
{
return 'ff7r';
}
/**
* @return bool False will prevent the permissions command from displaying the @everyone role.
*/
public static function allowEveryoneRole(): bool
{
return true;
}
/**
* Returns an array of Discord Permission enums that will be used by the add command to build a list of roles to get
* access to run the command. Any role that has any permission in this list will get access.
* @return Permissions[]
*/
public static function getPermissionsForRoles(): array
{
return [];
}
} |
#include "procgen/PlanetGenerator.h"
// Generates all the resources necessary to render the planet
// - vertex attributes
// - later on materials ??
void PlanetGenerator::generatePlanetData(
std::vector<VertexAttributes> &vertexData,
std::vector<uint32_t> &indices,
GUISettings settings) {
// settings of the planet
unsigned int resolution = settings.resolution;
ElevationGenerator elevationGenerator(
settings.radius,
settings.frequency,
settings.octaves);
// define the 6 faces normals
auto top = glm::vec3(0.0f, 1.0f, 0.0f);
auto down = glm::vec3(0.0f, -1.0f, 0.0f);
auto left = glm::vec3(-1.0f, 0.0f, 0.0f);
auto right = glm::vec3(1.0f, 0.0f, 0.0f);
auto front = glm::vec3(0.0f, 0.0f, 1.0f);
auto back = glm::vec3(0.0f, 0.0f, -1.0f);
std::vector<glm::vec3> faces{top, down, left, right, front, back};
// make sure the vectors are empty
vertexData.resize(0);
indices.resize(0);
// generate each face
auto start = chrono::steady_clock::now();
for (uint8_t i = 0; i < faces.size(); i++) {
glm::vec3 face = faces[i];
FaceGenerator faceGenerator(face, resolution, elevationGenerator);
faceGenerator.generateFaceData(vertexData, indices);
}
// compute the normals
// TODO: could be inproved by computing normals on the edges of the faces
for (uint32_t i = 0; i < indices.size(); i += 3) {
auto &v1 = vertexData[indices[i]];
auto &v2 = vertexData[indices[i + 1]];
auto &v3 = vertexData[indices[i + 2]];
auto edge1 = v2.position - v1.position;
auto edge2 = v3.position - v1.position;
// DON'T normalize here, we want to keep each magnitude data information
auto face_normal = glm::cross(edge1, edge2);
v1.normal += face_normal;
v2.normal += face_normal;
v3.normal += face_normal;
}
// final normalization needed
for (uint32_t i = 0; i < vertexData.size(); i++) {
vertexData[i].normal = glm::normalize(vertexData[i].normal);
}
auto end = chrono::steady_clock::now();
cout << "Time to generate planet data: "
<< chrono::duration_cast<chrono::milliseconds>(end - start).count()
<< " ms" << endl;
} |
import { Field, InputType, PartialType } from '@nestjs/graphql';
import { StatusShop } from '../entities/shop.entity';
import { CreateShopInput } from './create-shop.input';
@InputType({ description: 'Datos para actualizar la tienda' })
export class UpdateShopInput extends PartialType(CreateShopInput) {
@Field(() => StatusShop, {
description: 'Estado de la tienda',
nullable: true,
})
status: StatusShop;
@Field(() => String, {
description: 'Identificador de la empresa para la tienda',
nullable: true,
})
companyId?: string;
} |
import Git, { TreeEntry } from 'nodegit';
import indexFiles from '../utils/indexFiles';
// import validateRepo from '../utils/validateRepo';
import { Arguments } from 'yargs';
import { cacheData } from '../utils/config';
import { isLoggedIn } from '../utils/authToken';
import { getGitRepo, getBranchFromRef } from '../utils/git';
interface Args {
path?: string;
branch?: string;
}
export const indexBranchUtil = async (repo: Git.Repository, branchRef: string): Promise<void> => {
const commit = await repo.getBranchCommit(branchRef);
const branchName = getBranchFromRef(branchRef);
const tree = await commit.getTree();
const walker = tree.walk();
return new Promise(async (resolve, reject) => {
const files: Buffer[] = [];
const paths: string[] = [];
let finished = false;
const callback = async (): Promise<void> => {
try {
await indexFiles(paths, files, branchName);
resolve();
} catch (err) {
reject(err as Error);
}
};
walker.on('entry', async (entry: TreeEntry) => {
const filePath = entry.path();
paths.push(`/${filePath}`);
const file = await entry.getBlob();
if (file.isBinary()) {
console.warn(`file ${filePath} is binary`);
files.push(file.rawcontent().toBuffer(file.rawsize()));
} else {
files.push(file.content());
}
if (finished && paths.length === files.length) {
await callback();
}
});
walker.on('error', (err: Error) => {
throw err;
});
walker.on('end', () => {
finished = true;
});
walker.start();
});
};
export default async (args: Arguments<Args>): Promise<void> => {
if (cacheData.repositoryOwner.length === 0 || cacheData.repository.length === 0) {
throw new Error('owner and repository need to be set with <set-repo>');
}
if (!isLoggedIn(cacheData.authToken)) {
throw new Error('user must be logged in to index a branch');
}
if (!args.path) {
args.path = '.';
}
const repo = await getGitRepo(args.path);
// await validateRepo(repo);
const branchRef = args.branch ?
(await repo.getBranch(args.branch)).name()
: (await repo.getCurrentBranch()).name();
await indexBranchUtil(repo, branchRef);
console.log('done indexing the branch');
}; |
package com.wt.algorithm.leetCode;
import java.util.*;
import java.util.stream.Collectors;
public class LeetCode {
/**
* 有多少小于当前数字的数字
*
* @param nums
* @return
*/
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] numsCount = new int[nums.length];
for (int i = 0; i < numsCount.length; i++) {
int count = 0;
int target = nums[i];
for (int j = 0; j < nums.length; j++) {
if (nums[j] < target) {
count++;
}
}
numsCount[i] = count;
}
return numsCount;
}
public boolean validMountainArray(int[] arr) {
if (arr.length < 3) {
return false;
}
int left = 0;
int right = arr.length - 1;
while (left < arr.length - 1 && arr[left] < arr[left + 1]) {
left++;
}
while (right > 0 && arr[right] < arr[right - 1]) {
right--;
}
if (left == right && left != 0 && right != arr.length - 1) {
return true;
}
return false;
}
/**
* 独一无二的出现次数
*
* @param arr
* @return
*/
public boolean uniqueOccurrences(int[] arr) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : arr) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
Set<Integer> set = new HashSet<>();
for (Integer value : map.values()) {
set.add(value);
}
return set.size() == map.size();
}
/**
* 全排列
*
* @param nums
* @return
*/
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backTrack(nums, new int[nums.length], new ArrayList<>(), result);
return result;
}
private void backTrack(int[] nums, int[] used, List<Integer> path, List<List<Integer>> result) {
if (path.size() == nums.length) {
result.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i] == 1) {
continue;
}
path.add(nums[i]);
used[i] = 1;
backTrack(nums, used, path, result);
used[i] = 0;
path.remove(path.size() - 1);
}
}
/**
* N皇后
*
* @param n
* @return
*/
public List<List<String>> solveNQueens(int n) {
List<List<String>> result = new ArrayList<>();
char[][] chessBoard = new char[n][n];
for (char[] c : chessBoard) {
Arrays.fill(c, '.');
}
backTrack(n, 0, chessBoard, result);
return result;
}
private void backTrack(int n, int row, char[][] chessBoard, List<List<String>> result) {
if (row == n) {
result.add(Arrays.stream(chessBoard).map(String::valueOf).collect(Collectors.toList()));
return;
}
for (int col = 0; col < n; col++) {
if (isValid(row, col, n, chessBoard)) {
chessBoard[row][col] = 'Q';
backTrack(n, row + 1, chessBoard, result);
chessBoard[row][col] = '.';
}
}
}
private boolean isValid(int row, int col, int n, char[][] chessBoard) {
for (int i = 0; i < row; i++) {
if (chessBoard[i][col] == 'Q') {
return false;
}
}
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (chessBoard[i][j] == 'Q') {
return false;
}
}
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
if (chessBoard[i][j] == 'Q') {
return false;
}
}
return true;
}
/**
* 子集
*
* @param nums
* @return
*/
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backTrack(nums, 0, new ArrayList(), result);
return result;
}
private void backTrack(int[] nums, int index, List<Integer> path, List<List<Integer>> result) {
result.add(new ArrayList<>(path));
for (int i = index; i < nums.length; i++) {
path.add(nums[i]);
backTrack(nums, i + 1, path, result);
path.remove(path.size() - 1);
}
}
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
backTrack(n, k, 1, new ArrayList(), result);
return result;
}
private void backTrack(int n, int k, int index, List<Integer> path, List<List<Integer>> result) {
if (path.size() == k) {
result.add(new ArrayList<>(path));
return;
}
for (int i = index; i <= n; i++) {
path.add(i);
backTrack(n, k, i + 1, path, result);
path.remove(path.size() - 1);
}
}
/**
* 子集II
*
* @param nums
* @return
*/
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
backTracking(nums, 0, new ArrayList<>(), result);
return result;
}
private void backTracking(int[] nums, int index, List<Integer> path, List<List<Integer>> result) {
result.add(new ArrayList<>(path));
System.out.println(path.stream().map(Object::toString).collect(Collectors.joining(",")));
for (int i = index; i < nums.length; i++) {
if (i > index && nums[i] == nums[i - 1]) {
continue;
}
path.add(nums[i]);
backTracking(nums, i + 1, path, result);
path.remove(path.size() - 1);
}
}
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(candidates);
backtrack(candidates, target, 0, 0, new ArrayList<>(), result);
return result;
}
private void backtrack(int[] candidates, int target, int index, int sum, List<Integer> path, List<List<Integer>> result) {
if (sum > target) {
return;
}
if (sum == target) {
result.add(new ArrayList<>(path));
return;
}
for (int i = index; i < candidates.length; i++) {
if (i > index && candidates[i] == candidates[i - 1]) {
continue;
}
path.add(candidates[i]);
backtrack(candidates, target, i + 1, sum + candidates[i], path, result);
path.remove(path.size() - 1);
}
}
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
backtrack(nums, new int[nums.length], new ArrayList<>(), result);
return result;
}
private void backtrack(int[] nums, int[] used, List<Integer> path, List<List<Integer>> result) {
if (path.size() == nums.length) {
result.add(new ArrayList<>(path));
}
for (int i = 0; i < nums.length; i++) {
if (used[i] == 1) {
continue;
}
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == 0) {
continue;
}
path.add(nums[i]);
used[i] = 1;
backtrack(nums, used, path, result);
used[i] = 0;
path.remove(path.size() - 1);
}
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
backTrackCSM(candidates, target, 0, 0, new ArrayList<>(), result);
return result;
}
private void backTrackCSM(int[] candidates, int target, int index, int sum, List<Integer> path, List<List<Integer>> result) {
if (sum > target) {
return;
}
if (sum == target) {
result.add(new ArrayList<>(path));
return;
}
for (int i = index; i < candidates.length; i++) {
path.add(candidates[i]);
backTrackCSM(candidates, target, i, sum + candidates[i], path, result);
path.remove(path.size() - 1);
}
}
public static void main(String[] args) {
LeetCode code = new LeetCode();
int[] nums = {1, 2, 2};
// code.smallerNumbersThanCurrent(nums);
// code.validMountainArray(nums);
List<List<Integer>> list = code.permuteUnique(nums);
System.out.println(list);
}
} |
package com.cz.enrol.configure;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.cz.enrol.exception.UnLoginException;
import com.cz.enrol.utils.BusLogUtil;
import com.cz.enrol.utils.RedisUtil;
/**
* @author liuzhongshuai
*/
public class LoginInterceptorForStudent extends HandlerInterceptorAdapter {
@Value("${server.token-key}")
private String loginToken;
private BusLogUtil logger = new BusLogUtil(LoginInterceptorForStudent.class);
// @Autowired
//private StringRedisTemplate stringRedisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String uri = request.getRequestURI();
//前台用户请求
if (uri.indexOf("management") <= -1) {
//前台用户请求
String tokenValue = request.getHeader(loginToken);
logger.error("token", tokenValue);
if (StringUtils.isEmpty(tokenValue)) {
//用户未登录
throw new UnLoginException("用户未登录!", 1002);
}
//token 有值,去redis 验证
if (!RedisUtil.hasKey(tokenValue)) {
//用户登录超时,请重新登录
throw new UnLoginException("用户登录会话超时,请重新登录!", 1002);
}
//初始化超时 时长
RedisUtil.expire(tokenValue, 3600);
return true;
}
return true;
}
} |
import React from "react";
import Header from "../components/landing_page/Header";
import BlocDemo from "../components/landing_page/BlocDemo";
import Features from "../components/landing_page/Features";
import VidoSec from "../components/landing_page/VideoSec";
import Bottom from "../components/landing_page/Bottom";
const featuresData = [
{
icon: "/icons/icon4.png",
title: "One Stop Solution",
desc: "With an internal knowledge base chatbot your entire company can find up-to-date information in one place.",
},
{
icon: "/icons/icon1.png",
title: "Faster Employee Training an onboarding",
desc: "Bloc can fast track new employee training and allow new starters to become more effective more quickly. Now everything they want to know, related to the product, the tech or the policies is just a question away.",
},
{
icon: "/icons/icon2.png",
title: "Optimised Inventory Management",
desc: "Optimize inventory management by providing real-time access to inventory data. Teams can inquire about stock availability. Managers can find information quicker, reduce the risk of stockouts.",
},
];
function startupPage() {
return (
<main className="flex flex-col items-center w-full justify-center gap-[90px] py-8">
<Header
initial={"Founders & Managers"}
Heading={
<span>
Supercharge Your{" "}
<span className="text-primary">Startup’s Knowledge</span> Management!
</span>
}
Subheading={
"Revolutionize your employee experience with Bloc. Empower your team with instant access to information through chat, transforming the way knowledge flows."
}
/>
<BlocDemo
Heading={
<span>
Revolutionize Internal <span className="text-primary">Team Communication</span>
</span>
}
Subheading={
<span>
Not just knowledge-sharing, improve{" "}
<span className="text-white">
cross team collaboration Bloc will improve the visibility of what other teams{" "}
</span>{" "}
are doing, leading to better understanding, greater collaboration and new perspectives.
</span>
}
BotName={"StartUp Bot"}
/>
<Features featuresData={featuresData} />
<VidoSec />
<Bottom />
</main>
);
}
export default startupPage; |
# Information Disclosure 🕵️
Information Disclousure, ou traduzindo diretamente para o português Divulgação e Informação, é uma vulnerabilidade encontrada predominantemente em aplicações WEB e consiste no vazamento de informações confidenciais do sistema.
Os danos causados por esta vulnerabilidade são diversos , já que a uma enorme possibilidade de dados vazados, ou seja, pode afetar os dois lados de uma instituição, seu sistema interno e os dados de clientes.
Sobre danos a clientes, vale destacar o vazamento em texto livre de banco de dados anexados a página e mal protegidos, listas de emails, senhas, informações de contato e credencias de login.
Quanto a infraestrutura do sistema, é importante ressaltar que os principais vazamentos estão relacionados com a disponibilização de chaves API e credenciais de sistemas de banco de dados e serviços na nuvem. Além disso, o vazamento do código fonte completo de uma funcionalidade pode conceder informação privilegiada para invasores e para concorrentes diretos da empresa.

Para exemplificar esta vulnerabilidade irei utilizar o laboratório disponibilizado pela PortSwigger “**Information disclosure on debug page**”:
Inicialmente é importante compreender que a identificação desta categoria de vulnerabilidades é identificada principalmente na fase de reconhecimento e análise de um sistema. Por isso o desenvolvimento do laboratório será utilizando uma busca no código fonte da página.
Buscando o termo “.php” no código fonte da página foi possível identificar um hiperlink comentado, o qual tem um caminho para página de debug do PHP.

Inserindo este diretório no fim do endereço da página foi possível acessar o conteúdo da página de Debug e buscando pelo termo “KEY” no código fonte é encontrado código para conclusão do laboratório.

É possível notar que apesar de se tratar apenas de um laboratório de CTF, a busca por termos “key”, “api”, “psswd”, por exemplo, pode levar a informações no código fonte da página. Neste caso foi “esquecido” por algum responsável pelo código fonte da páina uma chave secreta em texto limpo.
 |
<script setup lang="ts">
import CardProduct from "@/components/CardProduct.vue";
import { onMounted, ref, watch } from "vue";
interface Product {
_id: string;
title: string;
description: string;
picture: string;
category: string;
}
const allProducts = ref<Product[]>([]);
const filteredProducts = ref<Product[]>([]);
const category = ref("Todos");
const search = ref("");
const loadingProducts = ref(true);
const fetchProducts = async () => {
try {
const response = await fetch(`${import.meta.env.VITE_BACK_URL}/product`);
if (!response.ok) {
throw new Error("Error al obtener los productos");
}
allProducts.value = await response.json();
loadingProducts.value = false;
} catch (error) {
console.error(error);
}
};
watch(category, (newValue, oldValue) => {
filteredProducts.value = allProducts.value.filter((product) => {
return newValue === "Todos" || product.category === newValue;
});
});
watch(search, (newValue, oldValue) => {
filteredProducts.value = allProducts.value.filter((product) => {
const searchTerm = newValue.toLowerCase();
return (
product.title.toLowerCase().includes(searchTerm) ||
product.description.toLowerCase().includes(searchTerm)
);
});
});
onMounted(async () => {
await fetchProducts();
filteredProducts.value = allProducts.value;
});
</script>
<template>
<main
class="bg-color-1 flex justify-center min-h-screen text-xl font-bold text-color5"
>
<div class="container">
<p class="text-center text-3xl">Productos</p>
<div class="sm:flex-row flex gap-4 flex-col">
<v-select
v-model="category"
label="Categoria"
:items="[
'Todos',
'Adornos',
'Bufandas',
'Gorros',
'Guantes',
'Individuales',
'Mantas',
'Medias',
]"
></v-select>
<v-text-field
v-model="search"
label="Buscar por titulo o descripcion"
></v-text-field>
</div>
<div class="flex gap-4 justify-center flex-wrap py-4">
<p v-if="loadingProducts" data-aos="fade-left" data-aos-duration="2000">
Cargando productos...
</p>
<CardProduct
data-aos="fade-left"
data-aos-anchor="#example-anchor"
data-aos-offset="500"
data-aos-duration="500"
v-for="prod in filteredProducts"
:prod="prod"
:key="prod?._id"
/>
</div>
</div>
</main>
</template> |
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:UShealthcare/apps/common/bottom_button_view.dart';
import 'package:UShealthcare/apps/view/address/add_address_page/add_address_page.dart';
import 'package:UShealthcare/apps/view/my_order/order_successful_page.dart';
import 'package:UShealthcare/helper/NavigatorHelper.dart';
import 'package:UShealthcare/helper/WidgetHelper.dart';
import 'package:UShealthcare/localization/AppLocalizations.dart';
import 'loader/my_address_page_loader.dart';
import 'tile/AddressListTile.dart';
class MyAddressPage extends StatefulWidget {
const MyAddressPage({Key? key}) : super(key: key);
@override
State<MyAddressPage> createState() => _MyAddressPageState();
}
class _MyAddressPageState extends State<MyAddressPage> {
bool myaddress = true;
void initState() {
super.initState();
if(myaddress){
Timer(Duration(seconds: 2), () {
setState(() {
myaddress = false;
});
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
appBar: WidgetHelper.getHeader(
context,
buildTranslate(context, "myAddress"),
showFilterIcon: true,
showNotificationIcon: false,
centerTitle: true,
shownotificationIcon: false,
showIcon: true,
showBackIcon: true,
showaddIcon: true,
onAddIconClick: (){
NavigatorHelper.add(AddAddressPage());
},
onAddressClick: (){
// NavigatorHelper.remove();
}
),
body: Container(
child: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
if(myaddress)
ListView.builder(
itemCount: 2,
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return MyAddressPageLoader();
},
),
if(!myaddress)...[
ListView.builder(
itemCount: 2,
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return AddressListTile(
index:index,
Callback: (int select){
select = 1;
}, select: 1);
},
),
],
WidgetHelper.getFieldSeparator(),
],),
),
),
),
bottomNavigationBar: BottomButtonView(
ButtonTitle: 'next',
deSelect: false,
callback: (){
NavigatorHelper.add(OrderSuccessfulPage());
},),
);
}
} |
{% extends "layout.html" %}
{% block content %}
<div class="content-section col-xs-12 col-sm-12 col-md-9 col-lg-6 col-xl-4 container-fluid padding">
<form action="" method="POST" novalidate>
{{ form.hidden_tag()}}
<fieldset class="form.group">
<legend class="border-bottom mb-4">Werde Teil unseres Dorfes</legend>
<div class="form-group">
{{ form.firstname.label(class="form-control-label") }}<br>
{% if form.firstname.errors %}
{{ form.firstname(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.firstname.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.firstname(class="form-control form-control-lg") }}
{% endif %}
</div>
<div class="form-group">
{{ form.lastname.label(class="form-control-label") }}<br>
{% if form.lastname.errors %}
{{ form.lastname(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.lastname.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.lastname(class="form-control form-control-lg") }}
{% endif %}
</div>
<div class="form-group">
{{ form.email.label(class="form-control-label") }}<br>
{% if form.email.errors %}
{{ form.email(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.email.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.email(class="form-control form-control-lg") }}
{% endif %}
</div>
<div class="form-group">
{{ form.password.label(class="form-control-label") }}<br>
{% if form.password.errors %}
{{ form.password(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.password.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.password(class="form-control form-control-lg") }}
{% endif %}
</div>
<div class="form-group">
{{ form.confirm_password.label(class="form-control-label") }}<br>
{% if form.confirm_password.errors %}
{{ form.confirm_password(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.confirm_password.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.confirm_password(class="form-control form-control-lg") }}
{% endif %}
</div>
</fieldset>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Bereits einen Account? <a class="ml-2" href="{{ url_for('login') }}">Login</a>
</small>
</div>
</div>
{% endblock content %} |
<?php
/**
* The header for our theme
*
* This is the template that displays all of the <head> section and everything up until <div id="content">
*
* @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
*
* @package Blogeasy
*/
?>
<!doctype html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="page" class="site">
<div id="box-container" class="container">
<header id="masthead" class="site-header text-center">
<div class="site-branding">
<?php
the_custom_logo();
if ( is_front_page() && is_home() ) :
?>
<h1 class="site-title h1"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
<?php
else :
?>
<h2 class="site-title h1"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h2>
<?php
endif;
$blogeasy_description = get_bloginfo( 'description', 'display' );
if ( $blogeasy_description || is_customize_preview() ) :
?>
<p class="site-description"><?php echo $blogeasy_description; /* WPCS: xss ok. */ ?></p>
<?php endif; ?>
</div><!-- .site-branding -->
</header><!-- #masthead -->
<div class="row main-nav-bg">
<div class="col-md-12">
<nav id="site-navigation" class="main-navigation">
<?php
wp_nav_menu( array(
'theme_location' => 'menu-1',
'menu_id' => 'primary-menu',
) );
?>
</nav><!-- #site-navigation -->
</div>
</div>
<div id="content" class="site-content"> |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box1{
height:200px;
background-color: #ccc;
position: relative;
padding:5px;
}
.box2{
width: 100px;
height: 100px;
background-color:pink ;
position: absolute;
left: 0;
}
button{
margin:10px;
}
</style>
</head>
<body>
<button>移动200</button>
<button>移动400</button>
<div class="box1">
<div class="box2"></div>
</div>
<script>
var btnArr = document.getElementsByTagName('button');
var box2 = document.getElementsByClassName('box2')[0];
var timer = null;
btnArr[0].onclick = function () {
animate(200);
}
btnArr[1].onclick = function () {
animate(400);
}
function animate(target) {
// bug1:点击多次以后不断加速
// 解决办法:执行定时器前先清除定时器
// clearInterval(timer);
// bug2:无法返回,原因就是步长不能为恒定值(传递的值比当前值小则为负值,传递的值比当前值小则为负值)
var speed = (target-box2.offsetLeft)>0?10:-10 ;
timer= setInterval(function () {
if(box2.offsetLeft === target){
clearInterval(timer);
}
// bug3:二次点击在目标位置仍然会移动.解决方法:用if else语句,先判断是否到达了目标值
else {
box2.style.left = box2.offsetLeft + speed +"px";
}
},30)
}
//老师解决方法:
// var val = target-box2.offsetLeft;
//if(Math.abs(val)<=Math.abs(speed)){
// box2.style.left = target + "px";
// clearInterval(timer);
//}
</script>
</body>
</html> |
// SCSS variables are information about icon's compiled state, stored under its original file name
//
// .icon-home {
// width: $icon-home-width;
// }
//
// The large array-like variables contain all information about a single icon
// $icon-home: x y offset_x offset_y width height total_width total_height image_path;
//
// At the bottom of this section, we provide information about the spritesheet itself
// $spritesheet: width height image $spritesheet-sprites;
$image10: (141px, 173px, -141px, -173px, 46px, 46px, 312px, 219px, '/dist/images/avatar/sprites.png', 'image10', );
$image11: (86px, 87px, -86px, -87px, 122px, 46px, 312px, 219px, '/dist/images/avatar/sprites.png', 'image11', );
$image12: (218px, 48px, -218px, -48px, 88px, 46px, 312px, 219px, '/dist/images/avatar/sprites.png', 'image12', );
$image13: (76px, 173px, -76px, -173px, 63px, 46px, 312px, 219px, '/dist/images/avatar/sprites.png', 'image13', );
$image14: (189px, 173px, -189px, -173px, 40px, 46px, 312px, 219px, '/dist/images/avatar/sprites.png', 'image14', );
$image15: (218px, 96px, -218px, -96px, 80px, 46px, 312px, 219px, '/dist/images/avatar/sprites.png', 'image15', );
$image8: (0px, 173px, 0px, -173px, 74px, 46px, 312px, 219px, '/dist/images/avatar/sprites.png', 'image8', );
$image9: (218px, 0px, -218px, 0px, 94px, 46px, 312px, 219px, '/dist/images/avatar/sprites.png', 'image9', );
$logo: (0px, 0px, 0px, 0px, 216px, 85px, 312px, 219px, '/dist/images/avatar/sprites.png', 'logo', );
$topgame: (0px, 87px, 0px, -87px, 84px, 84px, 312px, 219px, '/dist/images/avatar/sprites.png', 'topgame', );
$spritesheet-sprites: ($image10, $image11, $image12, $image13, $image14, $image15, $image8, $image9, $logo, $topgame, );
$spritesheet: (312px, 219px, '/dist/images/avatar/sprites.png', $spritesheet-sprites, );
// The provided mixins are intended to be used with the array-like variables
//
// .icon-home {
// @include sprite-width($icon-home);
// }
//
// .icon-email {
// @include sprite($icon-email);
// }
//
// Example usage in HTML:
//
// `display: block` sprite:
// <div class="icon-home"></div>
//
// To change `display` (e.g. `display: inline-block;`), we suggest using a common CSS class:
//
// // CSS
// .icon {
// display: inline-block;
// }
//
// // HTML
// <i class="icon icon-home"></i>
@mixin sprite-width($sprite) {
width: nth($sprite, 5);
}
@mixin sprite-height($sprite) {
height: nth($sprite, 6);
}
@mixin sprite-position($sprite) {
$sprite-offset-x: nth($sprite, 3);
$sprite-offset-y: nth($sprite, 4);
background-position: $sprite-offset-x $sprite-offset-y;
}
@mixin sprite-image($sprite) {
$sprite-image: nth($sprite, 9);
background-image: url(#{$sprite-image});
}
@mixin sprite($sprite) {
@include sprite-image($sprite);
@include sprite-position($sprite);
@include sprite-width($sprite);
@include sprite-height($sprite);
}
// The `sprites` mixin generates identical output to the CSS template
// but can be overridden inside of SCSS
//
// @include sprites($spritesheet-sprites);
@mixin sprites($sprites) {
@each $sprite in $sprites {
$sprite-name: nth($sprite, 10);
.#{$sprite-name} {
@include sprite($sprite);
}
}
} |
package com.byd.dct.iddm.common.swagger.config;
import com.byd.dct.iddm.common.swagger.annotation.EnableIddmDoc;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import java.util.Optional;
/**
* openapi 配置类
*
* @author lengleng
* @date 2023/1/1
*/
public class OpenAPIDefinitionImportSelector implements ImportBeanDefinitionRegistrar {
/**
* 注册Bean定义方法
* @param metadata 注解元数据
* @param registry Bean定义注册器
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
Optional.ofNullable(metadata.getAnnotationAttributes(EnableIddmDoc.class.getName(), true))
.map(attrs -> attrs.get("value"))
.ifPresent(value -> {
createBeanDefinition(registry, "openAPIMetadataRegister", OpenAPIMetadataRegister.class, value);
createBeanDefinition(registry, "openAPIDefinition", OpenAPIDefinition.class, value);
});
}
/**
* 创建Bean定义
* @param registry Bean定义注册器
* @param beanName Bean名称
* @param beanClass Bean类
* @param value Bean属性值
*/
private void createBeanDefinition(BeanDefinitionRegistry registry, String beanName, Class<?> beanClass,
Object value) {
BeanDefinitionBuilder beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(beanClass);
beanDefinition.addPropertyValue("path", value);
registry.registerBeanDefinition(beanName, beanDefinition.getBeanDefinition());
}
} |
import { AnimatePresence, motion } from "framer-motion";
import { FC, useState } from "react";
import { FaRocket } from "react-icons/fa";
import AppTemplate, { Splitter } from "../../components/AppTemplate";
import { IPageElement } from "../../components/Pages";
import { post } from "../../lib/post";
import { useCore } from "../../providers/CoreProvider";
const LoginPage: FC<IPageElement> = ({ setPage }) => {
const { locales } = useCore();
const [error, setError] = useState<string | null>(null);
const login = (e: any) => {
e.preventDefault();
post("setup:login", {
email: e.target.email.value + "@" + locales?.emailProvider,
password: e.target.password.value,
}).then((data: any) => {
if (!data.status) {
setError(locales?.loginIncorrect);
return;
}
setPage("colormode");
});
};
return (
<AppTemplate className="px-8 pt-10 pb-5 flex items-center flex-col justify-between">
<div className="w-full h-full flex items-center flex-col justify-center">
<div className="flex justify-center mb-3 items-center flex-col gap-2">
<FaRocket className="text-5xl mb-2" />
<h1 className="text-2xl px-6 font-normal text-center">
{locales?.login}
</h1>
</div>
<form id="createAccount" onSubmit={login} className="mb-2 w-full">
<div className="grid w-full gap-1">
<label>{locales?.email}</label>
<div className="flex gap-2 items-center justify-center">
<input className="input" name="email" required />
<div className="input max-w-[50%] text-sm h-full flex items-center !w-fit">
<p className="text-ellipsis overflow-hidden">
@{locales?.emailProvider}
</p>
</div>
</div>
<label>{locales?.password}</label>
<input
className="input"
name="password"
type={"password"}
required
/>
</div>
</form>
<div className="p-3 text-red-500">{error}</div>
</div>
<div className="grid w-full gap-3">
<button
type="submit"
form="createAccount"
className="btn-2 bg-blue-500 text-lg !rounded-xl flex items-center justify-center brightness-100 disabled:brightness-75 disabled:cursor-default"
>
{locales?.login}
</button>
<button
onClick={() => setPage("account")}
className="dark:text-gray-400 text-black font-medium"
>
{locales?.goBack}
</button>
</div>
</AppTemplate>
);
};
export default LoginPage; |
<?php declare(strict_types=1);
/*
* This file is part of sebastian/type.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Type;
use function strtolower;
final class SimpleType extends Type
{
/**
* @var string
*/
private $name;
/**
* @var bool
*/
private $allowsNull;
/**
* @var mixed
*/
private $value;
public function __construct(string $name, bool $nullable, $value = null)
{
$this->name = $this->normalize($name);
$this->allowsNull = $nullable;
$this->value = $value;
}
public function isAssignable(Type $other): bool
{
if ($this->allowsNull && $other instanceof NullType) {
return true;
}
if ($this->name === 'bool' && $other->name() === 'true') {
return true;
}
if ($this->name === 'bool' && $other->name() === 'false') {
return true;
}
if ($other instanceof self) {
return $this->name === $other->name;
}
return false;
}
public function name(): string
{
return $this->name;
}
public function allowsNull(): bool
{
return $this->allowsNull;
}
public function value()
{
return $this->value;
}
/**
* @psalm-assert-if-true SimpleType $this
*/
public function isSimple(): bool
{
return true;
}
private function normalize(string $name): string
{
$name = strtolower($name);
switch ($name) {
case 'boolean':
return 'bool';
case 'real':
case 'double':
return 'float';
case 'integer':
return 'int';
case '[]':
return 'array';
default:
return $name;
}
}
} |
import { FC, ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from 'react-query'
import { Provider } from 'react-redux'
import { Layout } from '../components/layout/Layout'
import { ReduxToast } from './ReduxToast'
import { store } from '../store/store'
import { HeadProvider } from './HeaderProvider/HeadProvider'
import { AuthProvider } from './AuthProvider/AuthProvider'
import { TypeComponentAuthFields } from '../shared/types/auth.types'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
},
},
})
export const MainProvider: FC<TypeComponentAuthFields> = ({
children,
Component,
}) => {
return (
<HeadProvider>
<Provider store={store}>
<QueryClientProvider client={queryClient}>
<ReduxToast />
<AuthProvider Component={Component}>
<Layout>{children}</Layout>
</AuthProvider>
</QueryClientProvider>
</Provider>
</HeadProvider>
)
} |
import React from 'react'
import { formatDistanceToNow } from 'date-fns'
import PropTypes from 'prop-types'
import {NewTaskForm} from '../NewTaskForm'
export default class Task extends React.Component {
static defaultProps = {
label: 'Your text',
date: new Date(),
onDestroyed: () => {},
onToggleDone: () => {},
done: false,
edit: false,
onEdit: () => {},
editForm: () => {},
}
static propTypes = {
label: PropTypes.string,
date: PropTypes.instanceOf(Date),
onDestroyed: PropTypes.func,
onToggleDone: PropTypes.func,
done: PropTypes.bool,
edit: PropTypes.bool,
onEdit: PropTypes.func,
editForm: PropTypes.func,
}
render() {
const {
label,
date,
onDestroyed,
onToggleDone,
done,
// checked,
edit,
onEdit,
editForm,
} = this.props
const daysBetween = formatDistanceToNow(date)
const classNames = () => {
if (edit) {
return 'editing'
}
if (done) {
return 'completed'
}
return ''
}
return (
<li className={classNames()}>
<div className="view">
<input // label
className="toggle"
type="checkbox"
checked={done}
onChange={onToggleDone}
/>
<label>
<span
className="description"
onClick={onToggleDone}
onKeyDown={onToggleDone}
role="button"
tabIndex={0}
>
{label}
</span>
<span className="created">created {daysBetween} ago</span>
</label>
<button
title="edit"
type="button"
className="icon icon-edit"
onClick={onEdit}
onKeyDown={onEdit}
>
{' '}
</button>
<button
title="destroy"
type="button"
className="icon icon-destroy"
onClick={onDestroyed}
>
{' '}
</button>
</div>
{edit && <NewTaskForm editForm={editForm} label={label} />}
</li>
)
}
} |
# <img width=28 style="margin-bottom: -2px" src="https://github.githubassets.com/favicons/favicon.png"> GitHub Widescreen 🖥️ [](https://twitter.com/intent/tweet?text=Hide%20the%20annoying%20sidebars%20from%20new%20GitHub%20UI%20with%20this%20userscript%21&url=https://github.com/adamlui/github-widescreen&hashtags=greasemonkey,github,javascript)
[](../LICENSE.md)
### Auto-hides obtrusive side panels from GitHub.
<a href="https://greasyfork.org/scripts/473439-github-widescreen"><img height=42 src="https://github.com/adamlui/userscripts/raw/master/media/images/buttons/install-button.svg"></a><a href="#-installation"><img height=42 title="How to install" src="https://github.com/adamlui/userscripts/raw/master/media/images/buttons/help-button.svg"></a>
<br>
[Discuss](https://github.com/adamlui/github-widescreen/discussions) /
[Review](https://greasyfork.org/scripts/473439-github-widescreen/feedback#post-discussion) /
[Contact author](https://github.com/adamlui)
## ⚡ Installation
1. Install Tampermonkey ([Chrome](https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo), [Firefox](https://addons.mozilla.org/firefox/addon/tampermonkey/), [Edge](https://microsoftedge.microsoft.com/addons/detail/tampermonkey/iikmkjmpaadaobahmlepeloendndfphd), [Opera](https://addons.opera.com/extensions/details/tampermonkey-beta/)) or Violentmonkey ([Chrome](https://chrome.google.com/webstore/detail/violent-monkey/jinjaccalgkegednnccohejagnlnfdag), [Firefox](https://addons.mozilla.org/firefox/addon/violentmonkey/), [Edge](https://microsoftedge.microsoft.com/addons/detail/violentmonkey/eeagobfjdenkkddmbclomhiblgggliao))
2. Install [GitHub Widescreen](https://greasyfork.org/scripts/473439-github-widescreen) (will load in userscript manager installed above)
3. Visit [github.com](https://github.com) as normal, and side panels (like the symbols navigator) will auto-hide on first load!
## 🪶 Author links
[")](https://elonsucks.org/@adam)
[](https://x.com/intent/user?screen_name=adamllui)
[](https://adamlui.com)
[](https://www.youtube.com/AdamLuiTube?sub_confirmation=1)
[](https://linkedin.com/in/adamlui)
[](https://github.com/adamlui)
<br><br>
## 📜 Related scripts
### <img width=17 style="margin: 0 2px -1px" src="https://github.githubassets.com/favicons/favicon.png"> [GitHub Star History ⭐](https://github.com/adamlui/github-star-history) <a href="https://github.com/awesome-scripts/awesome-userscripts#github"><img src="https://awesome.re/mentioned-badge.svg" style="margin:0 0 -2px 5px"></a>
Adds star history chart to sidebar of GitHub repos.<br>
[Install](https://greasyfork.org/scripts/473377) /
[Readme](https://github.com/adamlui/github-star-history#readme) /
[Discuss](https://github.com/adamlui/github-star-history/discussions)
### <img width=17 style="margin: 0 3px -1px" src="https://raw.githubusercontent.com/adamlui/chatgpt-widescreen/main/media/images/icons/widescreen-robot-emoji/icon32.png"> [ChatGPT Widescreen Mode](https://chatgptwidescreen.com/github) <img src="https://raw.githubusercontent.com/adamlui/chatgpt-widescreen/main/media/images/badges/product-hunt/product-of-the-week-2-larger-centered-rounded-light.svg" style="width: auto; height: 24px; margin:0 0 -4px 5px;" width="auto" height="24" />
Adds Widescren + Fullscreen modes to ChatGPT for enhanced viewing + reduced scrolling.
<br>[Install](https://github.com/adamlui/chatgpt-widescreen#installation) /
[Readme](https://github.com/adamlui/chatgpt-widescreen#readme) /
[Discuss](https://chatgptwidescreen.com/discuss)
<img height=6px width="100%" src="https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/aqua.png">
<a href="https://github.com/adamlui/userscripts">**More userscripts**</a> /
<a href="#-github-widescreen--">Back to top ↑</a> |
"""
Base adapter test class that can be reused across all adapters
"""
from typing import cast
import textwrap
from select import select
from sqlglot import select
from sqlglot.expressions import Identifier, Select, alias_
from featurebyte import AggFunc
from featurebyte.enum import DBVarType
from featurebyte.query_graph.sql.adapter import BaseAdapter
from featurebyte.query_graph.sql.common import get_qualified_column_identifier, quoted_identifier
from featurebyte.query_graph.sql.groupby_helper import (
GroupbyColumn,
GroupbyKey,
get_aggregation_expression,
get_vector_agg_column_snowflake,
)
class BaseAdapterTest:
"""
Base adapter test class that can be reused across all adapters
"""
adapter: BaseAdapter
@classmethod
def get_group_by_expected_result(cls) -> str:
"""
Returns expected result of group by query
"""
return textwrap.dedent(
"""
SELECT
a,
b,
REQ."serving_name" AS "serving_name",
REQ."serving_name_2" AS "serving_name_2",
entity_column,
"entity_column_2",
SUM("parent") AS "sum_result",
AVG("parent_avg") AS "avg_result"
GROUP BY
REQ."serving_name",
REQ."serving_name_2"
"""
).strip()
def test_group_by(self):
"""
Test group_by method
"""
adapter = self.adapter
select_expr: Select = cast(Select, select("a", "b"))
groupby_keys = [
GroupbyKey(
expr=get_qualified_column_identifier("serving_name", "REQ"),
name="serving_name",
),
GroupbyKey(
expr=get_qualified_column_identifier("serving_name_2", "REQ"),
name="serving_name_2",
),
]
select_keys = [k.get_alias() for k in groupby_keys]
select_keys.append(Identifier(this="entity_column"))
select_keys.append(quoted_identifier("entity_column_2"))
keys = [k.expr for k in groupby_keys]
agg_exprs = [
alias_(
get_aggregation_expression(AggFunc.SUM, "parent", None),
alias="sum_result",
quoted=True,
),
alias_(
get_aggregation_expression(AggFunc.AVG, "parent_avg", None),
alias="avg_result",
quoted=True,
),
]
vector_aggregate_exprs = [
get_vector_agg_column_snowflake(
select(),
AggFunc.SUM,
groupby_keys,
GroupbyColumn(
AggFunc.SUM,
parent_expr=(get_qualified_column_identifier("parent", "TABLE")),
parent_dtype=DBVarType.ARRAY,
result_name="result",
parent_cols=[(get_qualified_column_identifier("parent", "TABLE"))],
),
0,
False,
),
get_vector_agg_column_snowflake(
select(),
AggFunc.SUM,
groupby_keys,
GroupbyColumn(
AggFunc.SUM,
parent_expr=(get_qualified_column_identifier("parent2", "TABLE")),
parent_dtype=DBVarType.ARRAY,
result_name="result2",
parent_cols=[(get_qualified_column_identifier("parent2", "TABLE"))],
),
1,
False,
),
get_vector_agg_column_snowflake(
select(),
AggFunc.SUM,
groupby_keys,
GroupbyColumn(
AggFunc.SUM,
parent_expr=(get_qualified_column_identifier("parent3", "TABLE")),
parent_dtype=DBVarType.ARRAY,
result_name="result3",
parent_cols=[(get_qualified_column_identifier("parent3", "TABLE"))],
),
2,
False,
),
]
group_by_expr = adapter.group_by(
select_expr, select_keys, agg_exprs, keys, vector_aggregate_exprs
)
expected = self.get_group_by_expected_result()
assert group_by_expr.sql(pretty=True) == expected
@classmethod
def get_expected_haversine_sql(cls) -> str:
"""
Get expected haversine SQL string
"""
return textwrap.dedent(
"""
2 * ASIN(
SQRT(
POWER(SIN((
RADIANS(TABLE."lat1") - RADIANS(TABLE."lat2")
) / 2), 2) + COS(RADIANS(TABLE."lat1")) * COS(RADIANS(TABLE."lat2")) * POWER(SIN((
RADIANS(TABLE."lon1") - RADIANS(TABLE."lon2")
) / 2), 2)
)
) * 6371
"""
).strip()
def test_haversine(self):
adapter = self.adapter
lat_node_1_expr = get_qualified_column_identifier("lat1", "TABLE")
lon_node_1_expr = get_qualified_column_identifier("lon1", "TABLE")
lat_node_2_expr = get_qualified_column_identifier("lat2", "TABLE")
lon_node_2_expr = get_qualified_column_identifier("lon2", "TABLE")
expr = adapter.haversine(lat_node_1_expr, lon_node_1_expr, lat_node_2_expr, lon_node_2_expr)
assert expr.sql(pretty=True) == self.get_expected_haversine_sql() |
STIA1113
Quiz 1
1. In the Java programming language, all source code is first written in plain text files ending with the ______ extension.
a..javac
b..java
c..class
d..txt
Answer: ____b__
2. The Java compiler generates
a.machine code
b.source code
c.byte code
d.HTML
Answer: __c____
3. JVM stands for
a.Java Variable Machine
b.Java Variable Method
c.Java Virtual Method
d.Java Virtual Machine
Answer: __d____
4. Write a Java program to print the sum of two numbers.
Answer:
class SumProgram
{
public static void main(String[] args)
{
int x=10;
int y=5;
int sum;
sum = x+y;
System.out.println(sum);
}
}
5. Write the signature of the main method.
Answer: ___public static void main(String[] args)___
6. These characters mark the beginning of a single-line comment.
a.//
b./*
c.*/
d./**
Answer: ___a___
7. Which of the following are not valid assignment statements?
a.sum = 9;
b.72 = cost;
c.price = 129;
d.ans = 'y';
Answer: ___b___
8. Which of the following are valid Java identifiers?
a.myFirstProgram
b.1stProgram
c.Program1
d.David'sFirstProgram
e.First Program
f.FIRST_PROGRAM
Answer: __a,c,f____
9. This is a named storage location in the computer's memory.
a.class
b.keyword
c.variable
d.operator
Answer: ___c___
10.This keyword is used to declare a named constant.
a.constant
b.namedConstant
c.final
d.concrete
Answer: ___c___
11. Which of the following is not primitive data type?
a.String
b.double
c.boolean
d.int
Answer: ___a___
12. Write Java statements that accomplish the following.
i.Declare int variables a and b.
ii.Initialize an int variable x to 10 and a char variable ch to 'y'.
iii.Declare and initialize a double variable payRate to 12.50.
iv.Declare a boolean variable ans and set the value of ans to true.
Answer: I. int a, b;
II. int x = 10;
char ch = ‘y’;
III. double payRate = 12.50;
IV. Boolean ans = true;
13. Write the output of the following expressions.
i.System.out.println(13 / 4);
ii.System.out.println(2 + 12 / 4);
iii.System.out.println(21 % 5);
iv.System.out.println(3 - 5 % 7);
v.System.out.println(17.0 / 4);
vi.System.out.println(8 - 5 * 2.0);
vii.System.out.println(14 + 5 % 2 - 3);
viii.System.out.println(15.0 + 3 / 2);
Answer: I. 3
II. 5
III. 1
IV. -2
V. 4.25
VI. -2.0
VII. 12
VIII. 16.0
14. What is the value of each variable after the last statement executes?
int a, b, c;
double x, y;
a = 17;
b = 15;
a = a + b / 4;
c = a % 3 + 4;
x = 17 / 3 + 6.5;
y = a / 4.0 + 15 % 4 - 3.5;
Answer: a=20
b=15
c=6
x=11.5
y=4.5
15. Suppose x, y, and sum are int variables and z is a double variable. What value is assigned to sum variable after statement executes? Suppose x = 3, y = 5, and z = 14.1.
sum = x + y + (int) z;
Answer: ___22___
16. Write equivalent statements using combined assignment for the following, if possible.
i.x = 2 * x;
ii.x = x + y - 2;
iii.sum = sum + num;
iv.y = y / (x + 5);
Answer: i. x *= 2;
ii. x += y - 2;
iii. sum += num;
iv. y /= (x+5)
17. Change the SampleProgram.java program so that it displays Programming is fun! instead of Hello World!.
class SampleProgram
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
Answer:
class SampleProgram
{
public static void main(String[] args)
{
System.out.println("Programming is fun!");
}
}
18. The FixProgram.java has some errors. Fix the errors so that the program successfully compiles and runs.
class FixProgram
{
public static void main(String[] args)
{
System.out.println('Hello World!')
}
}
Answer:
class FixProgram
{
public static void main(String[] args)
{
System.out.println(“Hello World!”);
}
} |
const mongoose = require("mongoose");
const validator = require("validator");
// const validator = require("mongoose-validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const crypto = require("crypto");
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "The name is required, Please check again"],
maxLength: [30, "The name cant be more than 30 characters"],
minLength: [4, "The name cant be less than 4 characters"],
},
email: {
type: String,
required: [true, "The email is required, Please Enter your Email"],
unique: true,
validate: [validator.isEmail, "Please Enter a valid Email"],
},
password: {
type: String,
required: [true, "The password is required"],
maxLength: [15, "The password should be les than 15 charachters"],
minLength: [6, "The password should be more than 6"],
select: false,
},
avatar: {
public_id: {
type: String,
required: true,
},
url: {
type: String,
required: true,
},
},
role: {
type: String,
default: "user",
},
createdAt: {
type: Date,
default: Date.now,
},
resetPasswordToken: String,
resetPasswordExpire: Date,
});
userSchema.pre("save", async function (next) {
if (!this.isModified("password")) {
next();
}
this.password = await bcrypt.hash(this.password, 10);
});
//validate the name and the the email before changing
userSchema.pre("findByIdAndUpdate", function (next) {
this.options.runValidators = true;
next();
});
//JWT Token
userSchema.methods.getJWTToken = function () {
return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRE,
});
};
//compare Password
userSchema.methods.comparePassword = async function (password) {
return await bcrypt.compare(password, this.password);
};
//Generating Password reset Token
userSchema.methods.getResetPasswordToken = function () {
//Generating Token
const resetToken = crypto.randomBytes(20).toString("hex");
//Hashing and added it to userSchema
this.resetPasswordToken = crypto
.createHash("sha256")
.update(resetToken)
.digest("hex");
this.resetPasswordExpire = Date.now() + 15 * 60 * 1000;
return resetToken;
};
module.exports = mongoose.model("User", userSchema); |
import { useAuth } from "../../hooks/auth"
// o Context específico que se pretende utilizar
import { useState } from "react"
// pra criar estados que armazenam infos. (no caso, o "email" e "password" digitados nos inputs)
import { FiLogIn, FiMail, FiLock } from "react-icons/fi"
import { Link } from "react-router-dom"
import { Container, Form, Background } from "./styles"
import { Input } from "../../components/Input"
import { Button } from "../../components/Button"
export function SignIn() {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
/* useState --- Hook que trabalha com estados
const [email, setEmail] --- 1º value: variável/nome do Estado, que armazena o value momentâneo do Estado
2º value: a function que vai atualizar/acessar o Estado, quando quiser mudar o Estado
useState('') --- a function que permite a criação do Estado; entre (...) se informa o valor inicial do Estado
ex: nesse caso, o valor incial é uma String vazia ('') */
const { signIn } = useAuth()
function handleSignIn() {
signIn({ email, password })
}
// handleSignIn() --- function criada pra quando apertar o button "Entrar"
return(
<Container>
<Form>
<h1>Rocket Notes</h1>
<p>Aplicação para salvar e gerenciar seus links úteis.</p>
<h2>Faça seu login</h2>
<Input
placeholder="E-mail"
type="text"
icon={FiMail}
onChange={ event => setEmail(event.target.value)}
/>
<Input
placeholder="Senha"
type="password"
icon={FiLock}
onChange={ event => setPassword(event.target.value)}
/>
<Button title="Entrar" onClick={handleSignIn} />
<Link to="/register">
Criar conta
</Link>
</Form>
<Background />
</Container>
)
}
/* Link --- Component importado de "react-router-dom" que cria a navegação entre as págs.
to="/route" --- o endereçao da rota */ |
<!DOCTYPE html>
<html lang="en">
<head>
<title>HappyBio</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="styles.css">
<script defer src="https://unpkg.com/scrollreveal/dist/scrollreveal.min.js"></script>
<script defer src="javascript.js"></script>
</head>
<body>
<div class="container-fluid">
<!--Navbar-->
<div id="navbar">
<nav class="navbar navbar-expand-md bg-light navbar-light">
<a class="navbar-brand" href="#"><img alt="The company logo, a banana, an apple and a carrot" src="images/apple.png">HappyBio</a>
<button class="navbar-toggler" data-toggle="collapse" data-target="#navbarlinks">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarlinks">
<ul class="navbar-nav">
<li class="nav-item"><a class="nav-link" href="#trailer">Trailer</a></li>
<li class="nav-item"><a class="nav-link" href="#features">Features</a></li>
<li class="nav-item"><a class="nav-link" href="#products">Products</a></li>
<li class="nav-item"><a class="nav-link" href="#testimonials">Testimonials</a></li>
<li class="nav-item"><a class="nav-link" href="#contact">Contact us</a></li>
</ul>
</div>
</nav>
</div>
<!--Intro-->
<div id="intro">
<div class="row">
<div class="col-md">
<img class="img-fluid d-block mx-auto" src="images/apple.png" alt="The company logo, a banana, an apple and a carrot"></div>
<div class="col-md">
<h2>Welcome to the tastiest market on the web!</h2>
<h4>Our online shop is only one click away</h4>
<form action="#">
<button>Visit our shop</button>
</form>
</div>
</div>
</div>
<!--Trailer-->
<div id="trailer">
<h2>Fresh and Happy</h2>
<h5>Watch our newest trailer</h5>
<form action="#">
<button>Watch the video</button>
</form>
</div>
<!--Features-->
<div id="features">
<div id="features-row" class="row">
<div class="col-md">
<div class="card">
<div class="card-header">A rainbow of flavors</div>
<div class="card-body">HappyBio is proud of its big catalogue. You can choose any fruit and vegetable you want, be it bananas from Costa Rica or tomatoes from Italy.</div>
</div>
</div>
<div class="col-md">
<div class="card">
<div class="card-header">Questions? Ask us!</div>
<div class="card-body">At HappyBio, no question is left unasnswered. We want to make sure that every customer knows anything they want about our products. We promise to be transparent and accesible.</div>
</div>
</div>
<div class="col-md">
<div class="card">
<div class="card-header">Freshly roasted coffee</div>
<div class="card-body">You deserve the quality. We import only from sustainable plantations. Our roasting experts prepare the best blends for you.</div>
</div>
</div>
</div>
</div>
<!--Products-->
<div id="products">
<h2>Our bestsellers</h2>
<h5>Our customers always ask for their favorite fruits and vegetables</h5>
<div class="row">
<div class="card col-sm-3">
<img alt="An avocado" src="images/products/avocado.png">
<div class="card-img-overlay" id="avocado-overlay">
<div class="card-body">
<h4>Avocadoes</h4>from <a href="https://goo.gl/maps/2U1Yu9ZTbHs">Peru</a></div>
</div>
</div>
<div class="card col-sm-3">
<img alt="A bottle of olive oil" src="images/products/olive-oil.png">
<div class="card-img-overlay" id="oliveoil-overlay">
<div class="card-body">
<h4>Olive Oil</h4>from <a href="https://goo.gl/maps/cH57zXYa3ZP2">Ayvalık</a></div>
</div>
</div>
<div class="card col-sm-3">
<img alt="Some cherries" src="images/products/cherries.png">
<div class="card-img-overlay" id="cherry-overlay">
<div class="card-body">
<h4>Cherries</h4>from <a href="https://goo.gl/maps/uewaWTGyMd52">Chile</a></div>
</div>
</div>
<div class="card col-sm-3">
<img alt="Some grapes" src="images/products/grapes-1.png">
<div class="card-img-overlay" id="grape-overlay">
<div class="card-body">
<h4>Grapes</h4>from <a href="https://goo.gl/maps/hGCwgpDJjCS2">Italy</a></div>
</div>
</div>
</div>
</div>
<!--Testimonials-->
<div id="testimonials">
<h2>We <3 HappyBio</h2>
<h5>Reviews from our customers</h5>
<div class="row">
<div class="testimonial col-md-6"><img alt="Customer profile picture" src="images/customers/kaycee.png" class="testimonial-img">
<div class="testimonial-text">"Fast delivery, fresh food!"
<div class="testimonial-name">Kaycee Elwes</div>
</div>
</div>
<div class="testimonial col-md-6"><img alt="Customer profile picture" src="images/customers/reg.png" class="testimonial-img">
<div class="testimonial-text">"The cheapest bio in the town"
<div class="testimonial-name">Reg Short</div>
</div>
</div>
</div>
<div class="row">
<div class="testimonial col-md-6"><img alt="Customer profile picture" src="images/customers/harmon.png" class="testimonial-img">
<div class="testimonial-text">"Everything is so delicious!"
<div class="testimonial-name">Harmon Triggs</div>
</div>
</div>
<div class="testimonial col-md-6"><img alt="Customer profile picture" src="images/customers/donna.png" class="testimonial-img">
<div class="testimonial-text">"Before I discovered HappyBio, I didn't know how to cook. Now I eat fresh and healthy home-cooked meals!"
<div class="testimonial-name">Donna Verity</div>
</div>
</div>
</div>
</div>
<!--Partners-->
<div id="partners">
<h2>Our partners</h2>
<div class="row">
<div class="col-sm-4"><img alt="The Android logo" src="images/partners/android.png"></div>
<div class="col-sm-4"><img alt="The Apple logo" src="images/partners/apple.png"></div>
<div class="col-sm-4"><img alt="The Chrome logo" src="images/partners/chrome.png"></div>
</div>
</div>
<!--Contact-->
<div id="contact">
<h2>Contact us</h2>
<h5>Send us an e-mail, or subscribe to our newsletter to hear from us! To place a special order, click the button below and get a private offer.</h5>
<form action="#">
<button>request offer</button>
</form>
<ul class="contact-links">
<li><a href="#">Homepage</a></li>
<li><a href="#">happy@happybio.com</a></li>
<li><a href="#">+123 456 789</a></li>
<li><a href="#">12 Happy st. Smiletown</a></li>
<li><a href="#">Online Shop</a></li>
</ul>
<form action="#" class="form-group">
<input class="email form-control" placeholder="E-mail" type="text">
<button class="subbutton">Subscribe</button>
</form>
<div class="declaration">Icons made by <a href="http://www.freepik.com" title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0"
target="_blank">CC 3.0 BY</a></div>
</div>
</div>
<!--jquery-->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js">
</script>
</body>
</html> |
1. Create a project ASP.NET platform Windows, target Web
{ASP.NET Core Web Application => Web Application (Model-View-Controller)}
Authentification : change : Individual User Accounts
2. Make a changes in Views/Home/Index.cshtml as you want
3. Add a class in Models folder e.g. Joke.cs
add properties ( prop + 2 x Tab key )
add constructor ( ctor + 2 x Tab key )
4. Pick Contoller folder and run command Add / Controller
> MVC COntroller using Entity Framework
> Specify Joke model as a model + specify ApplicationDBContext
...
wait for a while to code generation
------
check the Data folder for Migrations, created Controller and Model classes, run project and go to localhost:.../{Jokes} you should see the database error
5. Install from NuGet Package Management.
> Microsoft.AspNet.Identity.EntityFramework
> EntityFramework
>
Go to Package Management Console (used for install new dependecies) and run command
{ Tools / NuGet Package Manager / Package Manager Console }
PM
PM> add-migration "initialsetup"
{ xxxx_migration_name.cs will be created inside Migrations folder
to delete migration use PM> Remove-Migration
}
PM> update-database
Entity Framework will initialize ApplicationDBContext to create tables automatically
2 possible ways to deal with database:
- ADO.NET (Access Data Object) using manually created queries (but more complex and transparent)
- Entity Framework (Microsoft's ORM - Object Relationship Model ) using automatically created queries as methods of model class (faster but for simpler queries)
Run Application and insert a couple of records and check with database
6. Improving UI
- Opem file Views / Shared / _Layout.cshtml and add nav-link to Jokes page:
E.G. <li><a asp-area="" asp-controller="Jokes" asp-action="Index">Jokes</a></li>
- Add a link to new page and call new Method in Controller e.g. "ShowSearchForm"
- Add a new Method in Controller e.g. "ShowSearchForm"
// GET: Jokes/ShowSearchForm
public async Task<IActionResult> ShowSearchForm()
{
return View();
}
Right Click on the method > Add > View > Empty >
Template: "Create" (Model Class : Joke) + Create as Partial View
Modify created view to support search functionality (as in example) + set form action new in the controller (e.g. ShowSearchResults)
1. Remove Database with connections & backup
2. Remove old migration file Data/Migrations/...
3. Run commands from Package Management Console:
PM> EntityFrameworkCore\add-migration "initialsetup"
PM> EntityFrameworkCore\update-database |
import { window } from "vscode";
import { TokenCredential } from "@azure/identity";
import {
AzureResource,
Subscription,
CosmosAccount,
CosmosDatabase,
CosmosContainer,
AzureResourceProvider
} from "../provider/azure-resource-tree-provider";
const SUBSCRIPTION_CHECK_MESSAGE: string = "Please type the subscription label to confirm clearing the subscription"
const ACCOUNT_CHECK_MESSAGE: string = "Please type the account label to confirm clearing the account"
const DATABASE_CHECK_MESSAGE: string = "Please type the database label to confirm clearing the database"
const CONTAINER_CHECK_MESSAGE: string = "Are you sure you want to clear the container"
const YES: string = "Yes"
const NO: string = "No"
export class CosmosClientAdapter {
constructor(
private readonly _azureResourceProvider: AzureResourceProvider
) {}
public async clearSelection(
selection: AzureResource): Promise<void>
{
switch (selection.constructor) {
case Subscription:
const subscription = selection as Subscription;
await CosmosClientAdapter.promptCheck(
`${SUBSCRIPTION_CHECK_MESSAGE} ${subscription.label}`,
subscription.label,
async () => await this.clearSubscription(subscription)
);
break;
case CosmosAccount:
const account = selection as CosmosAccount;
await CosmosClientAdapter.promptCheck(
`${ACCOUNT_CHECK_MESSAGE} ${account.label}`,
account.label,
async () => await this.clearAccount(account)
);
break;
case CosmosDatabase:
const database = selection as CosmosDatabase;
await CosmosClientAdapter.promptCheck(
`${DATABASE_CHECK_MESSAGE} ${database.label}`,
database.label,
async () => await this.clearDatabase(database)
);
break;
case CosmosContainer:
const container = selection as CosmosContainer;
await CosmosClientAdapter.promptAccept(
`${CONTAINER_CHECK_MESSAGE} ${container.label}?`,
async () => await this.clearContainer(container)
);
break;
default:
break;
}
}
private async clearSubscription(
subscription: Subscription): Promise<void>
{
var accounts = this._azureResourceProvider.getRelatedCosmosAccounts(
subscription.subscriptionId);
if (accounts) {
accounts.forEach(account => {
this.clearAccount(account);
});
}
}
private async clearAccount(
account: CosmosAccount): Promise<void>
{
var databases = this._azureResourceProvider.getRelatedCosmosDatabases(
account.accountId);
if (databases) {
databases.forEach(database => {
this.clearDatabase(database);
});
}
}
private async clearDatabase(
database: CosmosDatabase): Promise<void>
{
var containers = this._azureResourceProvider.getRelatedCosmosContainers(
database.databaseId);
if (containers) {
containers.forEach(container => {
this.clearContainer(container);
});
}
}
private async clearContainer(
container: CosmosContainer) : Promise<void>
{
var items = await container.container.items.readAll().fetchAll();
items.resources.forEach(async item => {
if (item.id) { await container.container.item(item.id).delete(); }
});
}
private static async promptAccept(
promptMessage: string,
action: () => Promise<void>): Promise<void>
{
await window
.showInformationMessage(promptMessage, YES, NO)
.then(async answer => {
if (answer === YES) { await action(); }
});
}
private static async promptCheck(
prompt: string,
check: string,
action: () => Promise<void>): Promise<void>
{
await window
.showInputBox({
prompt: prompt,
placeHolder: check
})
.then(async text => {
if (text === check) { await action(); }
});
}
} |
import { json } from '@sveltejs/kit';
import { parse } from 'node-html-parser';
export async function GET({ params }) {
const api = `https://github.com/users/${params.user}/contributions?from=${params.year}-12-01&to=${params.year}-12-31`;
const res = await fetch(api);
if (!res.ok) {
throw new Error(`Failed to fetch data: ${res.status} ${res.statusText}`);
}
const html = await res.text();
const dom = parse(html);
const rows = dom.querySelectorAll('tbody > tr');
const contributions = [];
for (const row of rows) {
const days = row.querySelectorAll('td:not(.ContributionCalendar-label)');
const currentRow = [];
for (const day of days) {
const data = day.textContent.trim().split(' ');
if (data.length > 1) {
const dataLevel = day.getAttribute('data-level');
const level = dataLevel !== undefined ? +dataLevel : 0;
const contribution = {
count: data[0] === 'No' ? 0 : +data[0],
name: data[3].replace(',', ''),
month: data[4],
day: +data[5].replace(',', ''),
year: data[6],
level: level
};
currentRow.push(contribution);
} else {
currentRow.push();
}
}
contributions.push(currentRow);
}
return json(contributions);
} |
import React, { useState } from 'react';
import { StyleSheet, Text, View, Image, FlatList, TextInput, ScrollView, Dimensions, TouchableOpacity } from 'react-native';
import { FontAwesome, Feather } from '@expo/vector-icons'; // Importe os ícones desejados
const data = [
{
id: '1',
username: 'Filipe Deschamps',
userImage: require('./assets/user1.png'),
postImage: require('./assets/Bun.jpeg'),
text: 'Vercel adiciona suporte ao gerenciador de módulos do Bun: projetos que contenham um arquivo “bun.lockb” rodarão por padrão o comando “bun install”. Assim como o yarn e pnpm, o Bun foca em acelerar o processo de instalação e economizar espaço em disco. A mudança afeta apenas a fase de build, não a de runtime. As informações são do changelog da Vercel.',
},
{
id: '2',
username: 'DevMedia',
userImage: require('./assets/devmedia.png'),
postImage: require('./assets/post2.png'),
text: 'Texto da segunda postagem. Outro texto longo que será truncado com reticências quando for muito longo.',
},
// Adicione mais objetos de postagem aqui conforme necessário.
{
id: '3',
username: 'Usuário 3',
userImage: require('./assets/post.png'),
postImage: require('./assets/post.png'),
text: 'Texto da terceira postagem. Mais um exemplo de texto longo que será truncado.',
},
{
id: '4',
username: 'Usuário 4',
userImage: require('./assets/post.png'),
postImage: require('./assets/post.png'),
text: 'Texto da quarta postagem. Exemplo de texto longo que será truncado com reticências.',
},
{
id: '5',
username: 'Filipe Deschamps',
userImage: require('./assets/user1.png'),
postImage: require('./assets/post5.png'),
text: 'Popular engine de jogos Unity anuncia nova estrutura de preço, gerando confusão e alvoroço entre desenvolvedores: a partir de 2024, será cobrada uma taxa extra de até 20 centavos de dólar por cada instalação de jogos que usam a engine. Isso gerou uma enorme preocupação sobre como serão tratados jogos pirateados, demos ou quando o jogo for instalado em vários dispositivos pelo jogador ao longo do tempo. A mudança seria particularmente prejudicial para desenvolvedores de jogos independentes. As informações são do site The Verge.',
},
];
export default function App() {
const [expanded, setExpanded] = useState(false);
const toggleExpand = () => {
setExpanded(!expanded);
};
const renderItem = ({ item }) => (
<View style={styles.post}>
<Image source={item.userImage} style={styles.userImage} />
<Text style={styles.username}>{item.username}</Text>
<Text style={styles.postText} numberOfLines={expanded ? undefined : 2}>
{item.text}
</Text>
{item.text.length > 100 && (
<TouchableOpacity onPress={toggleExpand}>
<Text style={styles.expandText}>
{expanded ? 'Veja menos' : 'Veja mais'}
</Text>
</TouchableOpacity>
)}
<Image source={item.postImage} style={styles.postImage} />
<View style={styles.iconContainer}>
<View style={styles.iconTextContainer}>
<FontAwesome name="thumbs-up" size={24} color="#333" />
<Text style={styles.iconText}>Gostei</Text>
</View>
<View style={styles.iconTextContainer}>
<FontAwesome name="comment" size={24} color="#333" />
<Text style={styles.iconText}>Comentar</Text>
</View>
<View style={styles.iconTextContainer}>
<FontAwesome name="share" size={24} color="#333" />
<Text style={styles.iconText}>Compartilhar</Text>
</View>
<View style={styles.iconTextContainer}>
<Feather name="send" size={24} color="#333" />
<Text style={styles.iconText}>Enviar</Text>
</View>
</View>
</View>
);
const windowHeight = Dimensions.get('window').height;
const postsHeight = windowHeight * 0.7;
return (
<View style={styles.container}>
<View style={styles.header}>
<Image
source={require('./assets/post.png')}
style={styles.userImageHeader}
/>
<View style={styles.searchContainer}>
<Feather name="search" size={20} color="#333" style={styles.searchIcon} />
<TextInput
style={styles.input}
placeholder="Pesquisar"
placeholderTextColor="#333"
/>
</View>
<Feather name="message-circle" size={20} color="#333" />
</View>
<ScrollView style={{ height: postsHeight }}>
{data.map((item) => renderItem({ item }))}
</ScrollView>
{/* Menu horizontal fixo na parte inferior da tela */}
<View style={styles.bottomMenu}>
<Feather name="home" size={24} color="#333" />
<Feather name="users" size={24} color="#333" />
<Feather name="edit" size={24} color="#333" />
<Feather name="bell" size={24} color="#333" />
<Feather name="briefcase" size={24} color="#333" />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
header: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
padding: 10,
},
userImageHeader: {
width: 40,
height: 40,
borderRadius: 20,
},
post: {
padding: 16,
borderBottomWidth: 1,
borderBottomColor: '#ddd',
},
userImage: {
width: 30,
height: 30,
borderRadius: 15,
marginRight: 10,
},
username: {
fontWeight: 'bold',
fontSize: 16,
},
postText: {
fontSize: 14,
marginTop: 8,
},
postImage: {
width: '100%',
height: 400,
marginTop: 8,
resizeMode: 'cover',
borderRadius: 8,
},
iconContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 8,
},
iconTextContainer: {
alignItems: 'center',
},
iconText: {
fontSize: 14,
marginTop: 4,
},
searchContainer: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#f2f2f2',
borderRadius: 10,
paddingHorizontal: 10,
paddingVertical: 4,
marginLeft: 10,
},
searchIcon: {
marginRight: 5,
},
input: {
flex: 1,
fontSize: 16,
color: '#333',
},
// Estilos para o menu horizontal fixo
bottomMenu: {
flexDirection: 'row',
justifyContent: 'space-around',
paddingVertical: 10,
borderTopWidth: 1,
borderTopColor: '#ddd',
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
backgroundColor: '#fff',
},
expandText: {
color: 'blue',
marginTop: 5,
},
}); |
import 'dart:convert';
DetailAproval detailAprovalFromJson(String str) =>
DetailAproval.fromJson(json.decode(str));
String detailAprovalToJson(DetailAproval data) => json.encode(data.toJson());
class DetailAproval {
DetailAproval({
this.data,
this.pesan,
this.status,
});
Data? data;
String? pesan;
bool? status;
factory DetailAproval.fromJson(Map<String, dynamic> json) => DetailAproval(
data: Data.fromJson(json["data"]),
pesan: json["pesan"],
status: json["status"],
);
Map<String, dynamic> toJson() => {
"data": data!.toJson(),
"pesan": pesan,
"status": status,
};
}
class Data {
Data({
this.id,
this.transaksi,
this.namapeminjam,
this.tglpinjam,
this.tglkembali,
this.barang,
this.nip,
this.noWa,
this.dipinjam,
});
String? id;
String? transaksi;
String? namapeminjam;
DateTime? tglpinjam;
DateTime? tglkembali;
List<Barang>? barang;
String? nip;
String? noWa;
String? dipinjam;
factory Data.fromJson(Map<String, dynamic> json) => Data(
id: json["id"],
transaksi: json["transaksi"],
namapeminjam: json["namapeminjam"],
tglpinjam: DateTime.parse(json["tglpinjam"]),
tglkembali: DateTime.parse(json["tglkembali"]),
barang:
List<Barang>.from(json["barang"].map((x) => Barang.fromJson(x))),
nip: json["nip"],
noWa: json["no_wa"],
dipinjam: json["dipinjam"],
);
Map<String, dynamic> toJson() => {
"id": id,
"transaksi": transaksi,
"namapeminjam": namapeminjam,
"tglpinjam":
"${tglpinjam!.year.toString().padLeft(4, '0')}-${tglpinjam!.month.toString().padLeft(2, '0')}-${tglpinjam!.day.toString().padLeft(2, '0')}",
"tglkembali":
"${tglkembali!.year.toString().padLeft(4, '0')}-${tglkembali!.month.toString().padLeft(2, '0')}-${tglkembali!.day.toString().padLeft(2, '0')}",
"barang": List<dynamic>.from(barang!.map((x) => x.toJson())),
"nip": nip,
"no_wa": noWa,
"dipinjam": dipinjam,
};
}
class Barang {
Barang({
this.nama,
this.kategori,
this.inventaris,
this.statusbarang,
});
String? nama;
String? kategori;
String? inventaris;
String? statusbarang;
factory Barang.fromJson(Map<String, dynamic> json) => Barang(
nama: json["nama"],
kategori: json["kategori"],
inventaris: json["inventaris"],
statusbarang: json["statusbarang"],
);
Map<String, dynamic> toJson() => {
"nama": nama,
"kategori": kategori,
"inventaris": inventaris,
"statusbarang": statusbarang,
};
} |
<?php
namespace MDMasudSikdar\Geezsms\Tests;
use GuzzleHttp\Client;
use MDMasudSikdar\Geezsms\GeezSmsClient;
use PHPUnit\Framework\MockObject\Exception;
use PHPUnit\Framework\TestCase;
class GeezSmsClientTest extends TestCase
{
private GeezSmsClient $smsClient;
/**
* Set up the GeezSmsClient instance for testing.
*/
protected function setUp(): void
{
$this->smsClient = new GeezSmsClient('api_token_here');
}
/**
* Test the constructor with a valid token.
*/
public function testConstructorWithValidToken(): void
{
$this->assertInstanceOf(GeezSmsClient::class, $this->smsClient);
}
/**
* Test the constructor with a missing token.
*/
public function testConstructorWithMissingToken(): void
{
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage("Token is required.");
new GeezSmsClient('');
}
/**
* Test the setHttpClient method.
* @throws Exception
*/
public function testSetHttpClient(): void
{
$httpClient = $this->createMock(Client::class);
$result = $this->smsClient->setHttpClient($httpClient);
$this->assertInstanceOf(GeezSmsClient::class, $result);
}
} |
#
# (C) Tenable Network Security, Inc.
#
# The descriptive text and package checks in this plugin were
# extracted from Mandriva Linux Security Advisory MDVSA-2015:133.
# The text itself is copyright (C) Mandriva S.A.
#
include("compat.inc");
if (description)
{
script_id(82386);
script_version("$Revision: 1.1 $");
script_cvs_date("$Date: 2015/03/30 13:59:01 $");
script_cve_id("CVE-2014-1829", "CVE-2014-1830", "CVE-2015-2296");
script_xref(name:"MDVSA", value:"2015:133");
script_name(english:"Mandriva Linux Security Advisory : python-requests (MDVSA-2015:133)");
script_summary(english:"Checks rpm output for the updated packages");
script_set_attribute(
attribute:"synopsis",
value:
"The remote Mandriva Linux host is missing one or more security
updates."
);
script_set_attribute(
attribute:"description",
value:
"Updated python-requests packages fix security vulnerabilities :
Python-requests was found to have a vulnerability, where the attacker
can retrieve the passwords from ~/.netrc file through redirect
requests, if the user has their passwords stored in the ~/.netrc file
(CVE-2014-1829).
It was discovered that the python-requests Proxy-Authorization header
was never re-evaluated when a redirect occurs. The Proxy-Authorization
header was sent to any new proxy or non-proxy destination as
redirected (CVE-2014-1830).
In python-requests before 2.6.0, a cookie without a host value set
would use the hostname for the redirected URL exposing requests users
to session fixation attacks and potentially cookie stealing
(CVE-2015-2296)."
);
script_set_attribute(
attribute:"see_also",
value:"http://advisories.mageia.org/MGASA-2014-0409.html"
);
script_set_attribute(
attribute:"see_also",
value:"http://advisories.mageia.org/MGASA-2015-0120.html"
);
script_set_attribute(
attribute:"solution",
value:
"Update the affected python-requests and / or python3-requests
packages."
);
script_set_cvss_base_vector("CVSS2#AV:N/AC:M/Au:N/C:P/I:P/A:P");
script_set_attribute(attribute:"plugin_type", value:"local");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:mandriva:linux:python-requests");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:mandriva:linux:python3-requests");
script_set_attribute(attribute:"cpe", value:"cpe:/o:mandriva:business_server:2");
script_set_attribute(attribute:"patch_publication_date", value:"2015/03/29");
script_set_attribute(attribute:"plugin_publication_date", value:"2015/03/30");
script_end_attributes();
script_category(ACT_GATHER_INFO);
script_copyright(english:"This script is Copyright (C) 2015 Tenable Network Security, Inc.");
script_family(english:"Mandriva Local Security Checks");
script_dependencies("ssh_get_info.nasl");
script_require_keys("Host/local_checks_enabled", "Host/cpu", "Host/Mandrake/release", "Host/Mandrake/rpm-list");
exit(0);
}
include("audit.inc");
include("global_settings.inc");
include("rpm.inc");
if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED);
if (!get_kb_item("Host/Mandrake/release")) audit(AUDIT_OS_NOT, "Mandriva / Mandake Linux");
if (!get_kb_item("Host/Mandrake/rpm-list")) audit(AUDIT_PACKAGE_LIST_MISSING);
cpu = get_kb_item("Host/cpu");
if (isnull(cpu)) audit(AUDIT_UNKNOWN_ARCH);
if (cpu !~ "^(amd64|i[3-6]86|x86_64)$") audit(AUDIT_LOCAL_CHECKS_NOT_IMPLEMENTED, "Mandriva / Mandrake Linux", cpu);
flag = 0;
if (rpm_check(release:"MDK-MBS2", reference:"python-requests-2.3.0-1.1.mbs2")) flag++;
if (rpm_check(release:"MDK-MBS2", reference:"python3-requests-2.3.0-1.1.mbs2")) flag++;
if (flag)
{
if (report_verbosity > 0) security_warning(port:0, extra:rpm_report_get());
else security_warning(0);
exit(0);
}
else audit(AUDIT_HOST_NOT, "affected"); |
JIRA.VersionModel = JIRA.RestfulTable.EntryModel.extend({
// rest resources
RELATED_ISSUES_PATH: "/relatedIssueCounts",
UNRESOLVED_ISSUES_PATH: "/unresolvedIssueCount",
addExpand: function (changed) {
changed.expand = "operations";
},
/**
* Destroys the model on the server. We need to override the default method as it does not support sending of
* query paramaters.
*
* @override
* @param options
* ... {function} success - Server success callback
* ... {function} error - Server error callback
* ... {object} data
* ... ... {String} moveFixIssuesTo - The version to set fixVersion to on issues where the deleted version is the
* fix version, If null then the fixVersion is removed.
* ... ... {String} moveAffectedIssuesTo The version to set affectedVersion to on issues where the deleted version
* is the affected version, If null then the affectedVersion is removed.
*
* @return JIRA.VersionModel
*/
destroy: function (options) {
var instance = this,
url = this.url(),
data = jQuery.param(options.data);
if (data !== "") {
// we need to add to the url as the data param does not work for jQuery DELETE requests
url = url + "?" + data;
}
JIRA.SmartAjax.makeRequest({
url: url,
type: "DELETE",
dataType: "json",
complete: function (xhr, status, smartAjaxResponse) {
var smartAjaxResponseData = smartAjaxResponse.data;
if (typeof smartAjaxResponse.data === "string") {
smartAjaxResponseData = JSON.parse(smartAjaxResponse.data);
}
var isValidationError = !(xhr.status === 400 && smartAjaxResponseData && smartAjaxResponseData.errors);
if (smartAjaxResponse.successful) {
instance.collection.remove(instance);
if (options.success) {
options.success.call(instance, smartAjaxResponseData);
}
} else if(isValidationError) {
instance._serverErrorHandler(smartAjaxResponse);
if (options.error) {
options.error.call(instance, smartAjaxResponseData);
}
}
if (options.complete) {
options.complete.call(instance, xhr.status, smartAjaxResponseData);
}
}
});
return this;
},
/**
* Gets count for issues with either affects version or fix version containing this version
*
* @param options
* ... {function} success - Server success callback
* ... {function} error - Server error callback
* @return JIRA.VersionModel
*/
getRelatedIssueCount: function (options) {
var instance = this;
options = options || {};
JIRA.SmartAjax.makeRequest({
url: this.url() + this.RELATED_ISSUES_PATH,
complete: function (xhr, status, smartAjaxResponse) {
if (smartAjaxResponse.successful) {
options.success.call(instance, smartAjaxResponse.data);
} else {
instance._serverErrorHandler(smartAjaxResponse)
}
}
});
return this;
},
/**
* Gets JSON representation of available versions to migrate issues of this version into.
*
* @return {Array}
*/
getSwapVersionsJSON: function () {
var instance = this,
availableSwapVersions = [];
this.collection.sort().each(function (model) {
if (!model.get("archived") && model !== instance) {
availableSwapVersions.push(model.toJSON());
}
});
return availableSwapVersions.reverse();
},
/**
* Gets JSON representation of available versions to migrate issues of this version into.
*
* @return {Array}
*/
getMoveVersionsJSON: function () {
var instance = this,
availableMoveVersions = [];
this.collection.sort().each(function (model, i) {
var json = model.toJSON();
if (instance.collection.at(i+1) === instance) {
json.nextScheduled = true;
}
if (!model.get("released") && model !== instance) {
availableMoveVersions.push(json);
}
});
return availableMoveVersions;
},
/**
* Gets count for unresolved issues in this version
*
* @param options
* ... {function} success - Server success callback
* ... {function} error - Server error callback
* @return JIRA.VersionModel
*/
getUnresolvedIssueCount: function (options) {
var instance = this;
options = options || {};
JIRA.SmartAjax.makeRequest({
url: this.url() + this.UNRESOLVED_ISSUES_PATH,
complete: function (xhr, status, smartAjaxResponse) {
if (smartAjaxResponse.successful) {
options.success.call(instance, smartAjaxResponse.data);
} else {
instance._serverErrorHandler(smartAjaxResponse)
}
}
});
return this;
}
}); |
import { v4 } from "uuid";
import { OrmType } from "../db/orm";
import { generateMnemonic } from "bip39";
import { Room } from "~/common/types";
import { cardRepo } from "./card-repo";
export const roomRepo = (orm: OrmType) => {
const format = (room: any) => {
if (!room) { return null; }
const cards = JSON.parse(room.cards);
const shownCards = cardRepo(orm).getRoomShownCards({
room_id: room.room_id
});
room.cards = cards.map((card: any, idx: number) => ({
...card,
face: shownCards.includes(idx) ? 'up' : 'down'
}));
return room as Room;
};
const getByName = ({ name }: { name: string }) => {
const [room = null] = orm.query<any>({ from: "rooms", where: { name } })
return format(room);
};
const getById = ({ room_id }: { room_id: string }) => {
const [room = null] = orm.query<any>({ from: "rooms", where: { room_id } })
return format(room);
};
const create = ({ user_id }: { user_id: string }) => {
const name = generateMnemonic()
.split(' ').slice(0, 3).join('-');
const cards = generateCards();
orm.insert({
into: "rooms",
data: {
user_id,
room_id: v4(),
name,
cards: JSON.stringify(cards),
status: 'lobby'
},
});
return getByName({ name });
};
const updateStatus = ({ room_id, status }: {
room_id: string,
status: 'lobby' | 'red-won' | 'blue-won'
}) => {
const [room] = orm.update<any>({
table: 'rooms',
where: { room_id },
set: { status }
});
return room && { ...room, cards: JSON.parse(room.cards) } as Room;
};
const getShownCards = ({ room_id }: { room_id: string }) => {
const cards = orm.query<{ card_idx: number }>({
from: 'shown_cards s join clues c using(clue_id)',
where: { 'c.room_id': room_id },
select: 's.card_idx'
});
return cards.map(({ card_idx }) => card_idx);
};
const reset = ({ room_id }: { room_id: string }) => {
const cards = generateCards();
const room = orm.update({
table: "rooms",
where: { room_id },
set: {
cards: JSON.stringify(cards),
status: 'lobby'
},
});
orm.update({
table: 'user_roles',
where: { room_id },
set: { role: 'none' }
});
orm.remove({
from: 'clues',
where: { room_id }
});
return room;
};
return {
create,
reset,
getByName,
getById,
updateStatus,
getShownCards,
};
};
const shuffleArray = <T>(array: T[]) => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
};
const generateCards = () => {
const colors = [
"black",
"blue", "blue", "blue", "blue", "blue", "blue", "blue",
"neutral", "neutral", "neutral", "neutral",
"red", "red", "red", "red", "red", "red", "red",
Math.random() > 0.5 ? "red" : "blue",
];
shuffleArray(colors);
const cards: { image: string, color: string }[] = [];
while (cards.length < colors.length) {
const i = cards.length;
const idx = Math.floor(Math.random() * (279 - 0 + 1)) + 0;
const image = `card-${idx}.svg`;
if (cards.find(c => c.image === image)) { continue; }
cards.push({ image, color: colors[i] });
}
return cards;
}; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="./vue.js"></script>
<title>Vue.js</title>
</head>
<body>
<!--
1) Você possui o nome e sobrenome do usuário em data,
crie uma propriedade computed que retorne o nome completo
-->
<div id="app">
{{fullName}}
</div>
<script>
const vm = new Vue({
el: "#app",
data: {
nome: "Bruno",
sobrenome: "Ramires"
},
computed: {
fullName(){
return this.nome + " " + this.sobrenome;
}
}
});
</script>
</body>
</html> |
import WpApiClient, { DefaultEndpoint } from 'wordpress-api-client'
import {
FeaturedMedia,
ModelPostType,
PageSlugsByTemplate,
ProductPostType,
RepPostType,
SeriesPostType,
StatePostType,
WordPressImage,
WordPressMenu
} from './types'
const HEADER_DESKTOP_MENU_PATH = 'wp-api-menus/v2/menus/7'
const FOOTER_PAGES_MENU_PATH = 'wp-api-menus/v2/menus/8'
const FOOTER_EXPLORE_MENU_PATH = 'wp-api-menus/v2/menus/9'
const HEADER_MOBILE_MENU_PATH = 'wp-api-menus/v2/menus/63'
const MODELS_POST_TYPE_PATH = 'wp/v2/models'
const PRODUCTS_POST_TYPE_PATH = 'wp/v2/products'
const REPS_POST_TYPE_PATH = 'wp/v2/reps'
const SERIES_POST_TYPE_PATH = 'wp/v2/series'
const STATES_POST_TYPE_PATH = 'wp/v2/states'
const PAGE_SLUGS_PATH = 'puroflux/v1/page-slugs'
class WpClient extends WpApiClient {
constructor() {
super(`${process.env.NEXT_PUBLIC_SOURCE_URL}`, {
auth: {
type: 'basic',
username: `${process.env.NEXT_PUBLIC_WP_USERNAME}`,
password: `${process.env.NEXT_PUBLIC_WP_PASSWORD}`
}
})
}
headerDesktopMenu = this.createEndpointCustomGet<WordPressMenu>(
HEADER_DESKTOP_MENU_PATH
)
headerMobileMenu = this.createEndpointCustomGet<WordPressMenu>(
HEADER_MOBILE_MENU_PATH
)
footerExploreMenu = this.createEndpointCustomGet<WordPressMenu>(
FOOTER_EXPLORE_MENU_PATH
)
footerPagesMenu = this.createEndpointCustomGet<WordPressMenu>(
FOOTER_PAGES_MENU_PATH
)
pageSlugsByTemplate = this.createEndpointCustomGet<PageSlugsByTemplate>(PAGE_SLUGS_PATH)
public model(): DefaultEndpoint<ModelPostType> {
return this.addPostType<ModelPostType>(MODELS_POST_TYPE_PATH)
}
public product<P = ProductPostType>(): DefaultEndpoint<P> {
const queryParams = new URLSearchParams({
order: 'desc',
orderBy: 'id'
})
return {
...this.defaultEndpoints(PRODUCTS_POST_TYPE_PATH, queryParams)
}
}
public rep(): DefaultEndpoint<RepPostType> {
return this.addPostType<RepPostType>(REPS_POST_TYPE_PATH)
}
public series(): DefaultEndpoint<SeriesPostType> {
return this.addPostType<SeriesPostType>(SERIES_POST_TYPE_PATH)
}
public state(): DefaultEndpoint<StatePostType> {
return this.addPostType<StatePostType>(STATES_POST_TYPE_PATH)
}
}
export const wpClient = new WpClient()
export const queryBySlug = (slug: string) => new URLSearchParams({ slug })
export const formatPhoneNumber = (
phoneNumber: string,
formatType: 'back' | 'front' = 'back'
): string => {
// Replace any non-number with an empty string and trim
const numbersOnly = phoneNumber.replace(/\D/g, '').trim()
// Group string of numbers into telephone parts
const grouped = numbersOnly.match(/^(\d{3})(\d{3})(\d{4})$/)
if (!grouped) return phoneNumber
let formatted
switch (formatType) {
case 'front':
formatted = `(${grouped[1]}) ${grouped[2]}-${grouped[3]}`
break
case 'back':
default:
formatted = `${grouped[1]}-${grouped[2]}-${grouped[3]}`
break
}
return formatted
}
export const formatURL = (url: string): string => {
// Determine if the URL contains /wp-content/
const filePath = 'wp-content/uploads'
const baseURL = process.env.NEXT_PUBLIC_BASE_URL
const httpLink = `http://${baseURL}`
const httpsLink = `https://${baseURL}`
let formattedURL = url
if (url.match(filePath)) return url
if (url.match(httpLink)) formattedURL = url.replace(httpLink, '')
if (url.match(httpsLink)) formattedURL = url.replace(httpsLink, '')
return formattedURL
}
export function getImageData(imageData: WordPressImage | FeaturedMedia | null) {
let imgAlt = ''
let imgSrc = ''
let imgHeight = 0
let imgWidth = 0
if (imageData) {
if (typeof imageData.title === 'string') {
imgAlt = imageData.title
} else if (typeof imageData.title === 'object') {
imgAlt = imageData.title.rendered
}
if (!imgAlt) {
if ('alt' in imageData) {
imgAlt = imageData.alt
} else if ('alt_text' in imageData) {
imgAlt = imageData.alt_text
}
}
if ('media_details' in imageData) {
const mediaDetailsHierarchy = 'full' || 'medium'
imgSrc =
imageData.media_details.sizes[mediaDetailsHierarchy]?.source_url || ''
imgHeight =
imageData.media_details.sizes[mediaDetailsHierarchy]?.height ||
imageData.media_details.height
imgWidth =
imageData.media_details.sizes[mediaDetailsHierarchy]?.width ||
imageData.media_details.width
} else if ('sizes' in imageData) {
const sizesHierarchy = 'large' || 'medium_large'
const heightHierarchy = 'large-height' || 'medium_large-height'
const widthHierarchy = 'large-width' || 'medium_large-width'
imgSrc = imageData.sizes[sizesHierarchy] || ''
imgHeight = imageData.sizes[heightHierarchy] || 0
imgWidth = imageData.sizes[widthHierarchy] || 0
}
if (!imgSrc) imgSrc = imageData.source_url
}
return {
imgAlt,
imgSrc,
imgHeight,
imgWidth
}
} |
.output "clock.go"
.ignorecase = 0
package clockgsl
import (
"time"
"fmt"
"math"
)
type supplier interface {
FractionOfDayPassed() float64
}
func floatingModulo(fractionOfDayPassed float64, resetFraction float64) float64 {
division := math.Floor(fractionOfDayPassed / resetFraction )
return (fractionOfDayPassed - (division * resetFraction))
}
.for clock
func get$(name:neat)(fractionOfDayPassed float64) string {
. if count(outputfield) > 0
resetFraction := 1.0 * $(resetfraction ? 1.0)
resetFractionOfDayPassed := floatingModulo(fractionOfDayPassed, resetFraction)
. endif
. printvars = ""
. for field
. printvars = printvars + ", $(name)"
$(name) := time.Now().$(name)()
. endfor
. for digit
. printvars = printvars + ", $(name)"
$(name)collection := []string{\
. for element
"$(element)",\
. endfor
}
$(name)idx := int(math.Mod(math.Floor((fractionOfDayPassed) / (1.0 * $(dayfraction))),float64(len($(name)collection))))
$(name) := $(name)collection[$(name)idx]
. endfor
. for outputfield
$(name) := get$(type:neat)OutputElement(resetFractionOfDayPassed, 1.0 * $(dayfraction))
. printvars = printvars + ", $(name)"
. endfor
return fmt.Sprintf("$(printf)" $(printvars))
}
.endfor
.for outputtypes
.for type
func get$(name:neat)OutputElement(fractionOfDayPassed float64, dayFraction float64) string {
collection := []string{\
. for element
"$(element)",\
. endfor
}
idx := int(math.Mod(math.Floor((fractionOfDayPassed) / dayFraction),float64(len(collection))))
return collection[idx]
}
.endfor
.endfor
.for timezones
.for.timezone
func $(name)Supplier() supplier {
. if "$(isSystemDefault?"false")" = "true"
return thesupplier { time.Now() }
. else
location := time.FixedZone("$(name)", $(offset) * 60 * 60)
return thesupplier{ time.Now().In(location) }
. endif
}
.endfor
.endfor
type thesupplier struct {
clock time.Time
}
func (self thesupplier) FractionOfDayPassed() float64 {
nanoSecondsPerDay := float64(24 * 60 * 60 * 1000 * 1000 * 1000)
round := self.clock.Round(time.Nanosecond)
midnight := round.Add(-time.Duration(round.Hour()) * time.Hour).Add(-time.Duration(round.Minute()) * time.Minute).Add(-time.Duration(round.Second()) * time.Second).Add(-time.Duration(round.Nanosecond()) * time.Nanosecond)
return float64(self.clock.Sub(midnight).Nanoseconds()) / nanoSecondsPerDay
}
func GetAllAsString() string {
out := ""
.for clock
out = out + fmt.Sprintln(get$(name:neat)($(timezone)Supplier().FractionOfDayPassed()))
.endfor
return out
}
func GetAllAsJSON() string {
return fmt.Sprintf(
`{\
.for clock
"$(name)":"%s",\
.endfor
"tail": "true"}`,
.for clock
get$(name:neat)($(timezone)Supplier().FractionOfDayPassed()),
.endfor
)
}
.output "clock_test.go"
package clockgsl
import (
"strings"
"strconv"
"testing"
"fmt"
)
func timeToDayFraction(timestamp string) (float64, error) {
timesplit := strings.Split(timestamp, ":")
if len(timesplit) != 3 {
return 0.0, fmt.Errorf("Time needs to be in format HH:MM:SS but was %s", timestamp)
}
hours, err := strconv.Atoi(timesplit[0])
if err != nil {
return 0.0, fmt.Errorf("Time needs to be in format HH:MM:SS but was %s", timestamp)
}
mins, err := strconv.Atoi(timesplit[1])
if err != nil {
return 0.0, fmt.Errorf("Time needs to be in format HH:MM:SS but was %s", timestamp)
}
secs, err := strconv.Atoi(timesplit[2])
if err != nil {
return 0.0, fmt.Errorf("Time needs to be in format HH:MM:SS but was %s", timestamp)
}
secondsSinceMidnight := float64(hours * 60 * 60 + mins * 60 + secs)
return secondsSinceMidnight / float64(1.0 * 24 * 60 * 60), nil
}
.for clock
func Test$(name:neat)(t *testing.T) {
testdata := []struct {
in string
out string
}{
.for tests
.for test
{ "$(attime)", "$(expect)" },
.endfor
.endfor
}
for _, tt := range testdata {
fraction, err := timeToDayFraction(tt.in)
if err != nil {
t.Errorf("Error: %s", err)
}
s := get$(name:neat)(fraction)
if s != tt.out {
t.Errorf("%q => %q, want %q (fraction: %q)", tt.in, s, tt.out, fraction)
}
}
}
.endfor |
import { Injectable } from '@angular/core';
import {
HttpClient,
HttpErrorResponse,
} from '@angular/common/http';
import { BehaviorSubject, Observable, map, catchError, throwError } from 'rxjs';
import { PathRest } from '../enviroments/path-rest';
import { endpoint } from '../enviroments/endpoints';
import { JwtHelperService } from '@auth0/angular-jwt';
import { UserResponse } from '../../models/userResponse';
import { UserCredentials } from '../../models/userCredentials';
import { Router } from '@angular/router';
const helper = new JwtHelperService();
@Injectable({
providedIn: 'root',
})
export class AuthService {
private readonly TOKEN_KEY = 'token'; // Clave para guardar el token en el almacenamiento local
private readonly USER_KEY = 'user';
private authStatusSubject = new BehaviorSubject<boolean>(this.isSessionActive());
authStatus$ = this.authStatusSubject.asObservable();
constructor(private router: Router, private http: HttpClient) {}
private updateAuthStatus(isAuthenticated: boolean): void {
this.authStatusSubject.next(isAuthenticated);
}
login(authData: UserCredentials): Observable<boolean | void> {
return this.http.post<UserResponse>(`${PathRest.GET_LOGIN}`, authData).pipe(
map((response: UserResponse) => {
if (response.success) {
this.saveToken(response.token);
localStorage.setItem(this.USER_KEY, response.user._id);
this.updateAuthStatus(true);
}
return response.success;
}),
catchError((error: HttpErrorResponse) => {
return throwError(() => error);
})
);
}
logout(): void {
localStorage.removeItem(this.TOKEN_KEY);
this.updateAuthStatus(false);
this.router.navigate([endpoint.LOGIN]);
}
private saveToken(tokenValue: string): void {
localStorage.setItem(this.TOKEN_KEY, tokenValue);
}
public isSessionActive(): boolean {
const token = this.getToken();
if (token && !helper.isTokenExpired(token)) {
return true;
}
return false;
}
getToken(): string | null {
return localStorage.getItem(this.TOKEN_KEY);
}
getUserId(): string | null {
return localStorage.getItem(this.USER_KEY);
}
} |
import FontAwesome from "@expo/vector-icons/FontAwesome"
import Ionicons from "@expo/vector-icons/Ionicons"
import { Link, Tabs } from "expo-router"
import { Pressable, useColorScheme } from "react-native"
import Colors from "../../constants/Colors"
import { Strings } from "../../constants/Strings"
/**
* You can explore the built-in icon families and icons on the web at https://icons.expo.fyi/
*/
function TabBarIcon(props: {
name: React.ComponentProps<typeof Ionicons>["name"]
color: string
}) {
return <Ionicons size={28} style={{ marginBottom: -3 }} {...props} />
}
export default function TabLayout() {
const colorScheme = useColorScheme()
return (
<Tabs
screenOptions={{
tabBarActiveTintColor: Colors[colorScheme ?? "light"].tint,
}}
>
<Tabs.Screen
name="index"
options={{
title: Strings.news,
tabBarIcon: ({ color }) => (
<TabBarIcon name="flash-outline" color={color} />
),
headerRight: () => (
<Link href="/modal" asChild>
<Pressable>
{({ pressed }) => (
<FontAwesome
name="info-circle"
size={25}
color={Colors[colorScheme ?? "light"].text}
style={{ marginRight: 15, opacity: pressed ? 0.5 : 1 }}
/>
)}
</Pressable>
</Link>
),
}}
/>
<Tabs.Screen
name="smallGroups"
options={{
title: Strings.smallGroups,
tabBarIcon: ({ color }) => (
<TabBarIcon name="cafe-outline" color={color} />
),
}}
/>
<Tabs.Screen
name="calendar"
options={{
title: Strings.calendar,
tabBarIcon: ({ color }) => (
<TabBarIcon name="calendar-outline" color={color} />
),
}}
/>
<Tabs.Screen
name="more"
options={{
title: Strings.more,
tabBarIcon: ({ color }) => (
<TabBarIcon name="keypad-outline" color={color} />
),
}}
/>
</Tabs>
)
} |
// import replaceTemplate from "./modules/replaceTemplate";
const fs = require('fs')
const http = require('http')
const url = require('url')
const slugify = require('slugify')
const replaceTemplate = require('./modules/replaceTemplate')
// Files
// // Blocking, synchronous
//
// const textIn = fs.readFileSync('./txt/input.txt', 'utf-8')
//
// const textOut = `Some important message ${textIn}, \nCreated ${Date.now()}`
//
// fs.writeFileSync('./txt/output.txt', textOut, 'utf-8')
//
// // Non-blocking, asynchronous
//
// fs.readFile('./txt/start.txt', 'utf-8', (err, data1) => {
// fs.readFile(`./txt/${data1}.txt`, 'utf-8', (err, data2) => {
// // console.log(data2)
// fs.readFile(`./txt/${data2}.txt`, 'utf-8', (err, data3) => {
// // console.log(data3)
// fs.writeFile('./txt/final.txt', `${data2} \n${data3}`, (err => {
// console.log(`${data2} \n ${data3}`)
// console.log('Your file has been written')
// }))
// })
// })
// })
//
// console.log("will read file")
//Server
const tempOverview = fs.readFileSync(`${__dirname}/templates/template-overview.html`, "utf-8")
const tempProduct = fs.readFileSync(`${__dirname}/templates/template-product.html`, "utf-8")
const tempCard = fs.readFileSync(`${__dirname}/templates/template-card.html`, "utf-8")
const data = fs.readFileSync(`${__dirname}/dev-data/data.json`, 'utf-8')
const dataObj = JSON.parse(data)
const slugs = dataObj.map(el => slugify(el.productName, { lower: true }))
console.log(slugify('Fresh avocados', { lowercase: true }))
const server = http.createServer((req, res) => {
const { query, pathname } = url.parse(req.url, true)
//Overview page
if (pathname === "/" || pathname === "/overview"){
res.writeHead(200, {'Content-type': 'text/html'})
const cardsHTML = dataObj.map(el => replaceTemplate(tempCard, el)).join('')
const output = tempOverview.replace(`{%PRODUCT_CARDS%}`, cardsHTML)
// res.end(tempOverview)
res.end(output)
//Product page
} else if (pathname === "/product") {
const product = dataObj[query.id]
const output = replaceTemplate(tempProduct, product)
res.writeHead(200, {'Content-type': 'text/html'})
res.end(output)
//API page
} else if (pathname === "/api"){
res.writeHead(200, {'Content-type': 'application/json'})
res.end(data)
} else {
res.writeHead(404, {
'Content-type': 'text/html',
'my-own-header': 'hello world'
})
res.end("<h1>Page not found</h1>")
}
})
server.listen(8000, '127.0.0.1', () => {
console.log('listening to requests on port 8000')
}) |
/**
* Copyright 2008 The University of North Carolina at Chapel Hill
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.unc.lib.fedora.repairsiblings;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.apache.http.HttpStatus;
import org.fcrepo.client.FcrepoClient;
import org.fcrepo.client.FcrepoOperationFailedException;
import org.fcrepo.client.FcrepoResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import picocli.CommandLine;
/**
* @author bbpennel
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy({
@ContextConfiguration("/spring-test/test-fedora-container.xml"),
})
public class RepairIT {
private String serverAddress = "http://localhost:48085";
private FcrepoClient fcrepoClient;
final PrintStream originalOut = System.out;
final ByteArrayOutputStream out = new ByteArrayOutputStream();
@Before
public void setUp() throws Exception {
fcrepoClient = FcrepoClient.client().build();
System.setOut(new PrintStream(out));
out.reset();
}
@Test
public void locateAndRepair() throws Exception {
final String baseId = UUID.randomUUID().toString();
URI baseUri = URI.create(serverAddress + "/" + baseId);
try (FcrepoResponse resp = fcrepoClient.put(baseUri).perform()) {
assertEquals(HttpStatus.SC_CREATED, resp.getStatusCode());
}
generateSiblingNodes(baseId);
CommandLine command = new CommandLine(new RepairCLI());
// Locate all the problems generated
String[] args = new String[] { "locate",
"-b", baseUri.toString() };
int result = command.execute(args);
assertEquals("Incorrect exit status", 0, result);
List<String> output = Arrays.asList(out.toString().trim().split("\n"));
assertTrue(output.size() > 0);
out.reset();
Path locateResults = Files.createTempFile("locate", ".txt");
Files.write(locateResults, output, UTF_8);
System.setOut(originalOut);
// Repair the problems
String[] args2 = new String[] { "repair", locateResults.toString(),
"-b", baseUri.toString() };
int result2 = command.execute(args2);
assertEquals("Incorrect exit status", 0, result2);
System.setOut(new PrintStream(out));
out.reset();
String[] args3 = new String[] { "locate",
"-b", baseUri.toString() };
int result3 = command.execute(args3);
assertEquals("Incorrect exit status", 0, result3);
System.setOut(originalOut);
assertTrue(out.toString().trim().isEmpty());
}
@Test
public void dryRun() throws Exception {
final String baseId = UUID.randomUUID().toString();
URI baseUri = URI.create(serverAddress + "/" + baseId);
try (FcrepoResponse resp = fcrepoClient.put(baseUri).perform()) {
assertEquals(HttpStatus.SC_CREATED, resp.getStatusCode());
}
generateSiblingNodes(baseId);
CommandLine command = new CommandLine(new RepairCLI());
// Locate all the problems generated
String[] args = new String[] { "locate",
"-b", baseUri.toString() };
int result = command.execute(args);
assertEquals("Incorrect exit status", 0, result);
List<String> output = Arrays.asList(out.toString().trim().split("\n"));
assertTrue(output.size() > 0);
out.reset();
Path locateResults = Files.createTempFile("locate", ".txt");
Files.write(locateResults, output, UTF_8);
System.setOut(originalOut);
// Repair the problems
String[] args2 = new String[] { "repair", locateResults.toString(),
"-b", baseUri.toString(),
"-n" };
int result2 = command.execute(args2);
assertEquals("Incorrect exit status", 0, result2);
System.setOut(new PrintStream(out));
out.reset();
String[] args3 = new String[] { "locate",
"-b", baseUri.toString() };
int result3 = command.execute(args3);
assertEquals("Incorrect exit status", 0, result3);
System.setOut(originalOut);
List<String> output2 = Arrays.asList(out.toString().trim().split("\n"));
assertEquals(output.size(), output2.size());
assertTrue(output.containsAll(output2));
}
private void generateSiblingNodes(String baseId) throws Exception {
List<String> txIds = new ArrayList<>();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; i++) {
final String txLocation;
URI startTxUri = URI.create(serverAddress + "/fcr:tx");
try (FcrepoResponse resp = fcrepoClient.post(startTxUri).perform()) {
assertEquals(HttpStatus.SC_CREATED, resp.getStatusCode());
txLocation = resp.getLocation().toString();
txIds.add(txLocation);
}
final String objId = baseId + "/path" + i % 3 + "/to" + i % 2 + "/obj" + i;
URI objUri = URI.create(txLocation + "/" + objId);
try (FcrepoResponse resp = fcrepoClient.put(objUri).perform()) {
assertEquals(HttpStatus.SC_CREATED, resp.getStatusCode());
}
}
for (final String txLocation : txIds) {
Runnable commitThread = new Runnable() {
@Override
public void run() {
URI commitUri = URI.create(txLocation + "/fcr:tx/fcr:commit");
try (FcrepoResponse resp = fcrepoClient.post(commitUri).perform()) {
assertEquals(HttpStatus.SC_NO_CONTENT, resp.getStatusCode());
} catch (IOException | FcrepoOperationFailedException e) {
throw new RuntimeException(e);
}
}
};
Thread thread = new Thread(commitThread);
threads.add(thread);
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
}
} |
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="jakarta.tags.core" prefix="c"%>
<%@ taglib prefix="fmt" uri="jakarta.tags.fmt"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<%@ taglib uri="jakarta.tags.functions" prefix="fn"%>
<jsp:include page="../../../template/successErrors.jsp" />
<div class="modal fade" id="editAnalysisModel" tabindex="-1" role="dialog" data-aria-labelledby="editAnalysis" data-aria-hidden="true" data-backdrop="static">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" data-aria-hidden="true">×</button>
<h4 class="modal-title">
<spring:message code="label.title.properties" />
</h4>
</div>
<div class="modal-body">
<form name="analysis" action="Analysis/Save?${_csrf.parameterName}=${_csrf.token}" class="form-horizontal" id="analysis_form">
<fieldset>
<legend style="font-size: 15px">
<spring:message code="label.property.analysis" />
</legend>
<input type="hidden" name="id" value="${analysis.id}" id="analysis_id">
<c:if test="${not analysis.profile}">
<div class="form-group">
<label for="type" class="col-sm-3 control-label" data-helper-content='<spring:message code="help.analysis.info.type"/>'> <spring:message code="label.analysis.type"
text="Type" /></label>
<div class="col-sm-9" align="center">
<div class="btn-group" data-toggle="buttons">
<c:forEach items="${types}" var="type" varStatus="status">
<c:set var="typeValue" value="${fn:toLowerCase(type)}" />
<label class="btn btn-default ${analysis.type == type? 'active':''}" ><spring:message code="label.analysis.type.${typeValue}" text="${typeValue}" />
<input type="radio" name="type" value="${type}" ${analysis.type == type? 'checked':''}>
</label>
</c:forEach>
</div>
</div>
</div>
</c:if>
<div class="form-group">
<label for="identifier" class="col-sm-3 control-label" data-helper-content='<spring:message code="help.analysis.info.identifier" />'> <spring:message
code="label.analysis.identifier" text="Identifier" />
</label>
<div class="col-sm-9">
<input name="identifier" id="analysis_identifier" class="form-control" type="text" value="${analysis.identifier}" readonly />
</div>
</div>
<c:if test="${not analysis.profile}">
<div class="form-group">
<label for="customer" class="col-sm-3 control-label" data-helper-content='<spring:message code="help.analysis.info.customer" />'> <spring:message
code="label.customer.organisation" text="Customer" />
</label>
<div class="col-sm-9" id="customercontainer">
<select name="customer" class="form-control">
<c:forEach items="${customers}" var="customer">
<option value="${customer.id}" ${customer.equals(analysis.customer)?"selected='selected'":""}>${customer.organisation}</option>
</c:forEach>
</select>
</div>
</div>
</c:if>
<div class="form-group">
<label for="label" class="col-sm-3 control-label" data-helper-content='<spring:message code="help.analysis.info.label" />'> <spring:message
code="label.analysis.label" text="Name" />
</label>
<div class="col-sm-9">
<input name="label" class="form-control resize_vectical_only" required="required" value='<spring:message text="${analysis.label}" />'>
</div>
</div>
</fieldset>
<fieldset>
<legend style="font-size: 15px">
<spring:message code="label.property.version" />
</legend>
<div class="form-group">
<label for="creationDate" class="col-sm-3 control-label" data-helper-content='<spring:message code="help.analysis.info.creation_date" />'> <spring:message
code="label.analysis.creation_date" text="Creation date" />
</label>
<div class="col-sm-9">
<input name="creationDate" id="analysis_creationDate" class="form-control" type="text" value="${analysis.creationDate}" readonly />
</div>
</div>
<c:if test="${not analysis.profile}">
<div class="form-group">
<label for="version" class="col-sm-3 control-label" data-helper-content='<spring:message code="help.analysis.info.version" />'> <spring:message
code="label.analysis.version" text="Version" />
</label>
<div class="col-sm-9">
<input name="version" id="analysis_version" class="form-control" type="text" value="${analysis.version}" readonly />
</div>
</div>
</c:if>
<c:if test="${not(analysis.profile || empty analysis.basedOnAnalysis)}">
<div class="form-group">
<label for="basedOnAnalysis" class="col-sm-3 control-label" data-helper-content='<spring:message code="help.analysis.info.parent" />'> <spring:message
code="label.analysis.based_on_analysis" text="Based on analysis version" />
</label>
<div class="col-sm-9">
<input name="basedOnAnalysis" id="analysis_basedOnAnalysis" class="form-control" type="text" value="${analysis.basedOnAnalysis.version}" readonly />
</div>
</div>
</c:if>
<div class="form-group">
<label for="owner" class="col-sm-3 control-label" data-helper-content='<spring:message code="help.analysis.info.author" />'> <spring:message
code="label.analysis.owner" text="Owner" />
</label>
<div class="col-sm-9">
<input name="owner" id="analysis_owner" class="form-control" type="text" value="${analysis.owner.firstName} ${analysis.owner.lastName}" readonly />
</div>
</div>
<div class="form-group">
<label for="language" class="col-sm-3 control-label" data-helper-content='<spring:message code="help.analysis.info.language" />'> <spring:message
code="label.analysis.language" text="Language" />
</label>
<div class="col-sm-9" id="languagecontainer">
<select name="language" class="form-control">
<c:forEach items="${languages}" var="language">
<option value="${language.id}" ${language.equals(analysis.language)?"selected='selected'":""}>${language.name}</option>
</c:forEach>
</select>
</div>
</div>
<c:if test="${not analysis.profile}">
<div class="form-group">
<label for="uncertainty" class="col-sm-3 control-label" data-helper-content='<spring:message code="help.analysis.info.uncertainty" />'> <spring:message
code="label.analysis.uncertainty" text="Uncertainty" />
</label>
<div class="col-sm-9" align="center">
<c:choose>
<c:when test="${ analysis.type=='QUALITATIVE'}">
<input type="checkbox" name="uncertainty" class="checkbox" disabled="disabled">
</c:when>
<c:otherwise>
<input type="checkbox" name="uncertainty" class="checkbox" ${analysis.uncertainty?"checked='checked'":''}>
</c:otherwise>
</c:choose>
</div>
</div>
</c:if>
</fieldset>
</form>
</div>
<div class="modal-footer">
<button name='save' type="button" class="btn btn-primary">
<spring:message code="label.action.save" text="Save" />
</button>
<button type="button" class="btn btn-default" data-dismiss="modal" name="cancel">
<spring:message code="label.action.cancel" text="Cancel" />
</button>
</div>
</div>
</div>
</div> |
import {createAction, props} from '@ngrx/store';
import {Product} from './product.model';
import {HttpErrorResponse} from "@angular/common/http";
import {Update} from "@ngrx/entity";
export const loadProducts = createAction(
'[Product/API] Load Products',
);
export const loadProductsSuccess = createAction(
'[Product/API] Load Product Success',
props<{ data: Product[] }>()
);
export const loadProductFailure = createAction(
'[Product/API] Load Product Failure',
props<{ error: HttpErrorResponse }>()
);
export const addProduct = createAction(
'[Product/API] Add Product',
props<{ product: Product }>()
);
export const updateProduct = createAction(
'[Product/API] Update Product',
props<{ product: Update<Product> }>()
);
export const deleteProduct = createAction(
'[Product/API] Delete Product',
props<{ code: string }>()
); |
import './style.scss';
import { useMemo } from 'react';
import { useLocation } from 'react-router';
import { useI18nContext } from '../../../../i18n/i18n-react';
import SvgDefguadNavLogoCollapsed from '../../../../shared/components/svg/DefguadNavLogoCollapsed';
import SvgIconNavHamburger from '../../../../shared/components/svg/IconNavHamburger';
import { useNavigationStore } from '../../hooks/useNavigationStore';
import { NavigationItems } from '../../types';
import { MobileNavModal } from './MobileNavModal/MobileNavModal';
type Props = {
onLogout: () => void;
navItems: NavigationItems;
};
export const NavigationMobile = ({ navItems, onLogout }: Props) => {
const { LL } = useI18nContext();
const { pathname } = useLocation();
const setStore = useNavigationStore((state) => state.setState);
const titleMap = useMemo(
() => [
{
path: '/admin/settings',
title: LL.navigation.mobileTitles.settings(),
},
{
path: '/admin/users',
title: LL.navigation.mobileTitles.users(),
},
{
path: '/admin/user',
title: LL.navigation.mobileTitles.user(),
},
{
path: '/admin/me',
title: LL.navigation.mobileTitles.user(),
},
{
path: '/admin/provisioners',
title: LL.navigation.mobileTitles.provisioners(),
},
{
path: '/admin/webhooks',
title: LL.navigation.mobileTitles.webhooks(),
},
{
path: '/admin/wizard',
title: LL.navigation.mobileTitles.wizard(),
},
{
path: '/admin/network',
title: LL.navigation.mobileTitles.networkSettings(),
},
{
path: '/admin/overview',
title: LL.navigation.mobileTitles.overview(),
},
{
path: '/admin/enrollment',
title: LL.navigation.mobileTitles.enrollment(),
},
{
path: '/admin/openid',
title: LL.navigation.mobileTitles.openId(),
},
],
[LL.navigation.mobileTitles],
);
const getPageTitle = useMemo(() => {
for (const item of titleMap) {
if (pathname.includes(item.path)) {
return item.title;
}
}
return '';
}, [pathname, titleMap]);
return (
<>
<nav className="nav-mobile">
<SvgDefguadNavLogoCollapsed />
<p className="page-title">{getPageTitle}</p>
<button className="hamburger" onClick={() => setStore({ isOpen: true })}>
<SvgIconNavHamburger />
</button>
</nav>
<MobileNavModal navItems={navItems} onLogout={onLogout} />
</>
);
}; |
<link rel='stylesheet' href='../style.css'>
<script src='../script.js'></script>
<h1>NAME</h1>
<p>pam-auth-update - manage PAM configuration using packaged
profiles</p>
<h1>SYNOPSIS</h1>
<p><strong>pam-auth-update</strong> [<strong>--package</strong>
[<strong>--remove</strong> <em>profile</em> [<em>profile...</em>]]]
[<strong>--force</strong>] [<strong>--enable</strong> <em>profile</em>
[<em>profile...</em>]] [<strong>--disable</strong> <em>profile</em>
[<em>profile...</em>]]</p>
<h1>DESCRIPTION</h1>
<p><em>pam-auth-update</em> is a utility that permits configuring the
central authentication policy for the system using pre-defined profiles
as supplied by PAM module packages. Profiles shipped in the
<em>/usr/share/pam-configs/</em> directory specify the modules, with
options, to enable; the preferred ordering with respect to other
profiles; and whether a profile should be enabled by default. Packages
providing PAM modules register their profiles at install time by calling
<strong>pam-auth-update --package</strong>. Selection of profiles is
done using the standard debconf interface. The profile selection
question will be asked at `medium' priority when packages are added or
removed, so no user interaction is required by default. Users may invoke
<strong>pam-auth-update</strong> directly to change their authentication
configuration.</p>
<p>The script makes every effort to respect local changes to
<em>/etc/pam.d/common-*</em>. Local modifications to the list of module
options will be preserved, and additions of modules within the managed
portion of the stack will cause <strong>pam-auth-update</strong> to
treat the config files as locally modified and not make further changes
to the config files unless given the <strong>--force</strong>
option.</p>
<p>If the user specifies that <strong>pam-auth-update</strong> should
override local configuration changes, the locally-modified files will be
saved in <em>/etc/pam.d/</em> with a suffix of <em>.pam-old</em>.</p>
<h1>OPTIONS</h1>
<dl>
<dt><strong>--package</strong></dt>
<dd>
<p>Indicate that the caller is a package maintainer script; lowers the
priority of debconf questions to `medium' so that the user is not
prompted by default.</p>
</dd>
<dt><strong>--disable <em>profile</em>
[<em>profile</em>...]</strong></dt>
<dd>
<p>Disable the specified profiles in system configuration. This can be
used from system administration scripts to disable profiles.</p>
</dd>
<dt><strong>--enable <em>profile</em>
[<em>profile</em>...]</strong></dt>
<dd>
<p>Enable the specified profiles in system configuration. This is used
to enable profiles that are not on by default.</p>
</dd>
<dt><strong>--remove <em>profile</em>
[<em>profile</em>...]</strong></dt>
<dd>
<p>Remove the specified profiles from the system configuration.
<strong>pam-auth-update --remove</strong> should be used to remove
profiles from the configuration before the modules they reference are
removed from disk, to ensure that PAM is in a consistent and usable
state at all times during package upgrades or removals.</p>
</dd>
<dt><strong>--force</strong></dt>
<dd>
<p>Overwrite the current PAM configuration, without prompting. This
option <strong>must not</strong> be used by package maintainer scripts;
it is intended for use by administrators only.</p>
</dd>
</dl>
<h1>FILES</h1>
<p><em>/etc/pam.d/common-*</em></p>
<blockquote>
<p>Global configuration of PAM, affecting all installed services.</p>
</blockquote>
<p><em>/usr/share/pam-configs/</em></p>
<blockquote>
<p>Package-supplied authentication profiles.</p>
</blockquote>
<h1>AUTHOR</h1>
<p>Steve Langasek <steve.langasek@canonical.com></p>
<h1>COPYRIGHT</h1>
<p>Copyright (C) 2008 Canonical Ltd.</p>
<h1>SEE ALSO</h1>
<p>PAM(7), pam.d(5), debconf(7)</p> |
//
// VocabularyBoxTableViewCell.swift
// Cool Eng
//
// Created by Ivan Chernetskiy on 05.06.2020.
// Copyright © 2020 Ivan Chernetskiy. All rights reserved.
//
import UIKit
import AVFoundation
class VocabularyBoxTableViewCell: UITableViewCell {
@IBOutlet weak var originalWord: UILabel!
@IBOutlet weak var translatedWord: UILabel!
@IBOutlet weak var speachButton: UIButton!
@IBOutlet weak var selectionIndicator: UIImageView!
private var wordText = ""
var isSelectedCell: Bool = false {
didSet {
if isSelectedCell {
selectionIndicator.image = UIImage(named: "radiobutton")
} else {
selectionIndicator.image = UIImage(named: "rbempty")
}
}
}
func setup(_ word: Word) {
originalWord.text = word.original
var translation = word.translation
if translation.contains(",") {
let words = translation.components(separatedBy: ",")
translation = "\(words[0]), \(words[1])"
}
translatedWord.text = translation
wordText = word.original
}
@IBAction func speachButtonAction() {
let speechSynthesizer = AVSpeechSynthesizer()
let speechUtterance: AVSpeechUtterance = AVSpeechUtterance(string: wordText)
speechUtterance.rate = AVSpeechUtteranceMaximumSpeechRate / 2.0
speechUtterance.voice = AVSpeechSynthesisVoice(language: "en-US")
speechSynthesizer.speak(speechUtterance)
}
} |
Quick introduction to web development.
Separation of Concerns: separate styling (CSS) from rendering (HTML) and logic (javaScript) into at least three separate files.
Progressive Enhancement: The latest and greatest is delivered to those who have the latest technologies installed and can view it, but a simpler version will work for those not on the bleeding edge.
# Visual Studio Code
Command Pallet: Shift+Ctrl+P (opens the top command list) or View > Command Palette
Explorer: Ctrl+Shift+E (opens the folder view)
## Welcome Page
Command Pallet > Help: Welcome
* New File...
* Open File...
* Open Folder...
* Clone Git Repository...
* Connect to...
**Recent List**
**Walkthroughs**
* Get Started with VS Code
* Learn the Fundamentals
* Boost your Productivity
* ...
## Extensions
The cubes with one floating off into space icon opens extensions.
**open in browser**: opens the page in the default browser. (Compare **Live Server** and the **Live Preview** extensions.)
## HTML
`html:5` will populate a basic HTML5 page template to get you started. |
import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { CommonService } from "src/service/commonservice";
import { SocialSharing } from "@ionic-native/social-sharing/ngx";
import { Clipboard } from "@ionic-native/clipboard/ngx";
import {
AlertController,
ActionSheetController,
Platform,
NavController,
} from "@ionic/angular";
import { ModalController, ToastController } from "@ionic/angular";
declare var cordova: any;
@Component({
selector: "app-user-profile",
templateUrl: "./user-profile.page.html",
styleUrls: ["./user-profile.page.scss"],
})
export class UserProfilePage implements OnInit {
servicedata: any = "";
user_id: any = "";
userdata: any = "";
profiledata: any = "";
first_name: any = "";
last_name: any = "";
image: any = "";
lastImage: string = null;
baseUrl: any = "";
referral_code: any = "";
constructor(
private router: Router,
private common: CommonService,
public alertController: AlertController,
public toastController: ToastController,
public modalCtrl: ModalController,
private actionSheetController: ActionSheetController,
public platform: Platform,
private socialSharing: SocialSharing,
private clipboard: Clipboard,
private navController: NavController
) {}
ngOnInit() {}
ionViewWillEnter() {
this.baseUrl = this.common.serviceurl;
this.userdata = JSON.parse(localStorage.getItem("user"));
this.user_id = this.userdata.user_id;
this.getUserProfile();
}
toEditProfile() {
this.navController.navigateRoot(['/edit-profile']);
// this.router.navigateByUrl("/edit-profile");
}
toContactUs() {
this.router.navigateByUrl("/user-contact-us");
}
toBackBtn() {
this.router.navigateByUrl("/user-contact-us");
}
toAboutUs() {
this.router.navigateByUrl("/user-aboutus");
}
logout() {
this.logoutAlertConfirm();
}
getUserProfile() {
this.servicedata = {
user_id: this.user_id,
};
this.common.serverdatapost("user/getUserById", this.servicedata).subscribe(
(res) => {
var data;
data = res;
this.profiledata = data.response;
console.log(this.profiledata);
if (this.profiledata.first_name)
this.first_name = this.profiledata.first_name;
if (this.profiledata.last_name)
this.last_name = this.profiledata.last_name;
if (this.profiledata.image) this.image = this.profiledata.image;
this.referral_code = data.response.referral_code;
},
(err) => {
console.log(err);
}
);
}
async logoutAlertConfirm() {
const alert = await this.alertController.create({
cssClass: "my-custom-class",
header: "Logging out?",
message: "Are you sure you want to log out?",
buttons: [
{
text: "Cancel",
role: "cancel",
cssClass: "secondary",
handler: (blah) => {
console.log("Confirm Cancel: false");
},
},
{
text: "Yes, logout",
handler: () => {
localStorage.clear();
this.router.navigateByUrl("/login-main");
},
},
],
});
await alert.present();
}
//Social Share Plugin
share() {
var msg =
"Join me on SHOOT, the best app for photography, videography, gifts and arts." +
" Enter my code " +
this.referral_code +
" to get discount on your first shoot! " +
"https://play.google.com/store/apps/details?id=com.appshoot.www";
// "Checkout Shoot App, I found it best for photography. Download : " +
// "https://play.google.com/store/apps/details?id=com.shootapp.www" +
// " Use my referral code - " +
// this.ref_code;
console.log(msg);
this.socialSharing.share(msg, null, null, null);
}
// Copy Referral Code to Clipboard
copyCode() {
this.clipboard.copy(this.referral_code);
this.common.toastalert("copied!");
console.log(this.referral_code);
}
pasteText() {
this.clipboard.paste().then(
(resolve: string) => {
this.referral_code = resolve;
// console.log(resolve);
},
(reject: string) => {
console.error("Error: " + reject);
}
);
this.clipboard.clear();
}
} |
'use client';
import UpdateButton from '@/components/UpdateButton';
import { Flex, Heading } from '@radix-ui/themes';
import { useParams, useRouter } from 'next/navigation';
import AnecdotalNotes from '@/components/AnecdotalNotes';
import { useStudent } from '@/hooks/useStudent';
const StudentPage = () => {
const { id } = useParams<{ id: string }>();
const router = useRouter();
const { student, loading } = useStudent(id);
if (loading || !student) return null;
return (
<div>
<Flex direction={'column'} mt={'4'} gap={'4'}>
<Flex justify="between" align="center">
<div onClick={router.back}>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={3}
stroke="currentColor"
className="w-6 h-6"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M15.75 19.5L8.25 12l7.5-7.5"
/>
</svg>
</div>
<Heading className="capitalize text-center">
{student.name} {student.lastName} Notes
</Heading>
<UpdateButton fields={student.fields} studentId={id} />
</Flex>
<AnecdotalNotes fields={student.fields} />
</Flex>
</div>
);
};
export default StudentPage; |
#ifndef NETWORK_H
#define NETWORK_H
#include <string>
#include "utils.h"
namespace tk { namespace dnn {
/**
Data representation between layers
n = batch size
c = channels
h = height (lines)
w = width (rows)
l = length (3rd dimension)
*/
struct dataDim_t {
int n, c, h, w, l;
dataDim_t() : n(1), c(1), h(1), w(1), l(1) {};
dataDim_t(int _n, int _c, int _h, int _w, int _l = 1) :
n(_n), c(_c), h(_h), w(_w), l(_l) {};
void print() {
std::cout<<"Data dim: "<<n<<" "<<c<<" "<<h<<" "<<w<<" "<<l<<"\n";
}
int tot() {
return n*c*h*w*l;
}
};
class Layer;
const int MAX_LAYERS = 512;
class Network {
public:
Network(dataDim_t input_dim);
virtual ~Network();
void releaseLayers();
/**
Do inference for every added layer
*/
dnnType* infer(dataDim_t &dim, dnnType* data);
bool addLayer(Layer *l);
void print();
const char *getNetworkRTName(const char *network_name);
cudnnDataType_t dataType;
cudnnTensorFormat_t tensorFormat;
cudnnHandle_t cudnnHandle;
cublasHandle_t cublasHandle;
Layer* layers[MAX_LAYERS]; //contains layers of the net
int num_layers; //current number of layers
dataDim_t input_dim;
dataDim_t getOutputDim();
bool fp16, dla, int8;
int maxBatchSize;
bool dontLoadWeights;
std::string fileImgList;
std::string fileLabelList;
std::string networkName;
std::string networkNameRT;
};
}}
#endif //NETWORK_H |
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href=".\style.css">
<script src=".\d3.v3.js"></script>
</head>
<body>
<div id="scatterPlot" >
</div>
<script type="text/javascript">
async function timed() {
while (true) {
// Scaterplot.
var w = 250;
var h = 200;
var padding = 15;
var svgMain = d3.select("div")
.append("svg")
.attr("width", w)
.attr("height", h);
// Perhaps time elapsed since creation vs total left in inventory?
//Dynamic, random dataset
var dataset = [];
var numDataPoints = 6;
var xRange = Math.random() * 100;
var yRange = Math.random() * 100;
for (var i = 0; i < numDataPoints; i++) {
var newNumber1 = Math.round(Math.random() * xRange);
var newNumber2 = Math.round(Math.random() * yRange);
dataset.push([newNumber1, newNumber2]);
}
var xScale = d3.scale.linear()
.domain([0, d3.max(dataset, function (d) { return d[0] / .75; })])
.range([padding, w - padding]);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function (d) { return d[1]; })])
.range([h - padding, padding]);
var rScale = d3.scale.linear()
.domain([0, d3.max(dataset, function (d) { return d[1]; })])
.range([1, 6]);
svgMain.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.on('mouseover', function () {
console.log(this.childNodes);
})
.attr("cx", function (d) {
return xScale(d[0]);
})
.attr("cy", function (d) {
return yScale(d[1]);
})
.attr("r", function (d) {
return rScale(d[1]);
});
svgMain.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function (d) {
return "[" + d[0] + "]";
})
.attr("class", "textPlots")
.style("font-family", "sans-serif")
.style("font-size", "11px")
.style("fill", "#808080")
.attr("id", function (d) {
return d[0] + "_" + d[1];
})
.attr("x", function (d) {
return xScale(d[0] + 8);
})
.attr("y", function (d) {
return yScale(d[1]);
});
// X-Axis.
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
// Create.
svgMain.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
// Y-Axis.
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(5);
// Create.
svgMain.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
await sleep(3000);
d3.select("svg").remove();
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
timed();
</script>
</body>
</html> |
import React, { useState, useContext } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { AuthContext } from "../context/auth-context";
const Item = () => {
const [tag, setTag] = useState("");
const [description, setDescription] = useState("");
const [lastSeenLocation, setLastSeenLocation] = useState("");
const [dateTime, setDateTime] = useState("");
const [image, setImage] = useState(null);
const [type, setType] = useState("lost");
const auth = useContext(AuthContext);
const params = useParams();
const navigate = useNavigate();
const updateHandler = async (e) => {
e.preventDefault();
try {
const response = await fetch(
`${process.env.REACT_APP_BASE_URL}item/${params.id}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${auth.token}`,
},
body: JSON.stringify({
tag,
location: lastSeenLocation,
description,
datetime: dateTime,
type,
}),
}
);
if (response.ok) {
console.log("updated successfully");
navigate(-1);
} else {
const responseData = await response.json();
alert(`Error: ${responseData.message}`);
}
} catch (error) {
console.error("Error updating item:", error);
}
};
return (
<div className="m-auto p-4 grid md:grid-cols-2 items-center justify-items-center h-[calc(100vh-74px)]">
<div className="lg:w-1/2 p-4 hidden lg:block text-center">
<h2 className="text-4xl font-bold mb-4 text-sky ">
Welcome to Lostings
</h2>
<p className="text-lg text-navy mb-4">
Update the details of the item to improve the chances of it being
found or returned. Please provide as much accurate information as
possible, including a clear description, the location where it was
last seen, the date and time, and a relevant image. By updating these
details, you can help us in our mission to reunite lost items with
their owners or finders. Thank you for your assistance in making the
lost and found process more effective and efficient.
</p>
</div>
<div className=" bg-white flex items-center justify-center">
<div className="text-navy rounded p-8 shadow-xl w-full max-w-lg">
<h2 className="text-2xl font-semibold mb-4 text-center">
Update Item
</h2>
<form onSubmit={updateHandler}>
<label className="font-semibold">Type</label>
<select
value={type}
onChange={(e) => setType(e.target.value)}
className="w-full h-9 rounded-lg my-2 p-2 border font-medium mb-4 outline-none text-gray-700 bg-green-50"
>
<option value="lost">Lost</option>
<option value="found">Found</option>
</select>
<label className="font-semibold">Tag</label>
<input
type="text"
value={tag}
onChange={(e) => setTag(e.target.value)}
className="w-full h-9 rounded-lg my-2 p-2 border font-medium mb-4 outline-none text-gray-700 bg-green-50"
/>
<label className="font-semibold">Description</label>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
className="w-full rounded-lg my-2 p-2 border font-medium mb-4 outline-none text-gray-700 bg-green-50"
/>
<label className="font-semibold">Last Seen Location</label>
<input
type="text"
value={lastSeenLocation}
onChange={(e) => setLastSeenLocation(e.target.value)}
className="w-full h-9 rounded-lg my-2 p-2 border font-medium mb-4 outline-none text-gray-700 bg-green-50"
/>
<label className="font-semibold">Date and Time</label>
<input
type="datetime-local"
value={dateTime}
onChange={(e) => setDateTime(e.target.value)}
className="w-full h-9 rounded-lg my-2 p-2 border font-medium mb-4 outline-none text-gray-700 bg-green-50"
/>
<label className="font-semibold">Image</label>
<input
type="file"
accept="image/*"
onChange={(e) => setImage(e.target.files[0])}
className="w-full h-9 rounded-lg my-2 p-2 border text-sm font-medium mb-4 outline-none text-gray-700 bg-green-50"
/>
<button
type="submit"
className="w-full font-medium bg-sky hover:bg-navy text-white p-2 my-4 rounded-lg"
>
Update Item
</button>
</form>
</div>
</div>
</div>
);
};
export default Item; |
## RabbitMQ基本知识
### RabbitMQ几个基本名词:
- 消息:有效载荷(payload)+标签(label)
- 有效载荷:就是想要传输的数据
- 标签:可以用来表述这条消息(一个交换器的名称和可选的主题标记)【不会传输给消费者】
- 消费者:消息队列中消费消息
- 生产者:消息队列中生成消息
- 代理:代理服务器(即MQ) 起到一个路由作用
- 交换器:【消息投递到队列前,通过绑定在交换器上确定的规则(路由键)后将他们投递到对应的队列中】
- 队列:消息最终到达的地方,并且给消费者接收的地方
- 绑定:规则(路由键)绑定到交换机上
- 虚拟主机(vhost):一个消息队列可以创建多个虚拟主机(虚拟主机之间相互独立,类似于很多小的MQ 各自有各自的 交换器,路由键和队列)
### RabbitMQ是怎么工作的:
应用程序和RabbitMQ建立一个TCP连接,在连接建立并且已经通过认证的情况下,应用程序便会创建一个AMQP信道【每个信道都有一个独立的ID 由AMQP库记录】(信道和建立在”真实的“的TCP连接中的虚拟连接)。每个AMQP指令(发送消息,订阅队列或接收消息)都是通过信道发送出去的。
- **为什么每次是创建信道而不是创建一个TCP连接:**如果是建立TCP连接,那么应用程序每个线程都需要建立连接,性能消耗便会十分大
- **队列中有多个消费者的情况下,队列中的消息是怎么发送给消费者的:**队列收到的消息将以循环的方式发送给消费者
- **交换器的几种类型:**direct【空白字符串交换器,路由键匹配】,fanout【扇区-例子买东西会扣钱和加积分,扣钱和加积分两个队列便可以同时绑定到一个fanout交换器上】,topic【订阅】,headers
- **持久化消息**
- **发送方确认模式**
- **死信队列:** 未看
😂暂时就这些-2019/6/13😂 |
"""
Search index (main) view.
URLs include:
/
"""
import threading
import heapq
import search
import requests
import flask
@search.app.route('/', methods=['GET'])
def get_results():
"""Docstring for app route."""
# print("entered get results")
# parse parameters
query = flask.request.args.get("q")
weight = flask.request.args.get("w", default=0.5)
# print(query)
# print(weight)
context = {
"search_results": [],
"num_results": 0,
"query": query,
"weight": weight
}
if query is None:
print("query is none here")
return flask.render_template("search.html", **context), 200
# print("32")
# connect to index servers, create rest api request
rest_api_urls = search.app.config['SEARCH_INDEX_SEGMENT_API_URLS']
threads = []
search_results = []
for url in rest_api_urls:
# print("Connect to url")
thread = threading.Thread(target=get_index,
args=(query, weight, url, search_results))
threads.append(thread)
thread.start()
# Join all threads together
for thread in threads:
thread.join()
connection = search.model.get_db()
for searcher in heapq.merge(*search_results, key=lambda x:
x["score"], reverse=True):
# Use doc_id to look up relevant info in database
# Connect to database
cur = connection.execute(
"SELECT * FROM Documents WHERE docid = ?",
(searcher["docid"], )
)
document = cur.fetchone()
if len(context["search_results"]) < 10:
context["search_results"].append({
"doc_url": document["url"],
"doc_title": document["title"],
"doc_summary": document["summary"]
})
# Use threads to concurrently hit servers
# parse rest api request
# Consider using the heapq.merge() function to combine the
# results of several Index servers
# context = {
# "search_results": search_results,
# "num_results": len(search_results)
# }
# print("it here gere")
context["num_results"] = len(context["search_results"])
return flask.render_template("search.html", **context)
def get_index(query, weight, url, search_results):
"""Capture index and append to search."""
# Pass in parameters to index API
params = {'q': query, 'w': weight}
# Get information from API, r is response
response = requests.get(url, params=params, timeout=100)
# print(response)
# doc_id = response["hits"]["doc_id"]
# score = response["hits"]["score"]
if response:
search_results.append(response.json()["hits"]) |
import React, { useState } from "react";
import { View, Text, TouchableOpacity, Image, StyleSheet, ImageBackground } from "react-native";
const questions = [
{
id: 1,
name: "octopus",
image: require("../assets/images/quizimages/octopus.png"),
options: ["o", "b", "d"],
correctOption: "o",
},
{
id: 2,
name: "Igloo",
image: require("../assets/images/quizimages/igloo.png"),
options: ["p", "m", "i"],
correctOption: "i",
},
{
id: 3,
name: "King",
image: require("../assets/images/quizimages/king.png"),
options: ["k", "h", "q"],
correctOption: "k",
},
{
id: 4,
name: "Umbrella",
image: require("../assets/images/quizimages/umbrella.png"),
options: ["a", "u", "b"],
correctOption: "u",
},
{
id: 5,
name: "Socks",
image: require("../assets/images/quizimages/socks.png"),
options: ["s", "k", "o"],
correctOption: "s",
},
{
id: 6,
name: "Fox",
image: require("../assets/images/quizimages/fox.png"),
options: ["x", "o", "f"],
correctOption: "f",
},
];
const QuizScreen = ({ image, options, onSelect }) => {
const [selectedOption, setSelectedOption] = useState(null);
return (
<View style={styles.subContainer}>
<View style={styles.imageContainer}>
<Image
style={styles.image}
source={image}
/>
</View>
<View style={styles.optionsContainer}>
{options.map((option) => (
<TouchableOpacity
key={option}
onPress={() => {
setSelectedOption(option);
onSelect(option);
}}
style={{
backgroundColor: selectedOption === option ? "#6cdfef" : "#f878b5",
padding: 6,
borderRadius: 16,
flexDirection: "column",
width: "28%",
aspectRatio:1/1,
alignItems: "center",
justifyContent: "center"
}}
>
<Text style={styles.optionButtonText}>{option}</Text>
</TouchableOpacity>
))}
</View>
</View>
);
};
const QuizApp = () => {
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
const [selectedOptions, setSelectedOptions] = useState([]);
const [showScore, setShowScore] = useState(false);
const [selectedOpt, setSelectedOpt] = useState(null);
const [selectedAnswer, setSelectedAnswer] = useState(null);
const [showResult, setShowResult] = useState(false);
const handleSelect = (option) => {
setSelectedAnswer(option);
const newSelectedOptions = [...selectedOptions];
newSelectedOptions[currentQuestionIndex] = option;
setSelectedOptions(newSelectedOptions);
setSelectedOpt(newSelectedOptions);
setShowResult(true);
};
const handleRestartButtonClick = () => {
setCurrentQuestionIndex(0);
// setScore(0);
setShowScore(false);
setSelectedAnswer(null);
setSelectedOpt(null);
setShowResult(false);
};
const handleNextQuestion = () => {
if (currentQuestionIndex === questions.length - 1) {
setShowScore(true);
}
// else {
// setCurrentQuestionIndex(currentQuestionIndex + 1);
// }
// setSelectedOpt(null);
else if (selectedAnswer === questions[currentQuestionIndex].correctOption) {
setCurrentQuestionIndex(currentQuestionIndex + 1);
setSelectedAnswer(null);
setShowResult(false);
}
// setCurrentQuestion(currentQuestion + 1);
setSelectedOpt(null);
};
const score = selectedOptions.filter(
(option, index) => option === questions[index].correctOption
).length;
return (
<View style={styles.container}>
<ImageBackground source={require('../assets/images/blob3.png')} resizeMode="contain" style={styles.bgimage}>
{showScore ? (
<View style={styles.scoreContainer}>
{/* <Text style={styles.scoreText}>
Your Score: {score}/{questions.length}
</Text>
{score === questions.length ? (
<Text style={{ fontSize: 48 }}>😎</Text>
) : score >= questions.length / 2 ? (
<Text style={{ fontSize: 48 }}>🙂</Text>
) : (
<Text style={{ fontSize: 48 }}>😞</Text>
)} */}
<Text style={{ fontSize: 60 }}>🎉</Text>
<Text style={styles.scoreText}>Well Done!</Text>
<TouchableOpacity
style={styles.restartButton}
onPress={handleRestartButtonClick}
>
<Text style={styles.restartButtonText}>Play again</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.backButton}
onPress={handleRestartButtonClick}
>
<Text style={styles.restartButtonText}>Back to Games</Text>
</TouchableOpacity>
</View>
) : (
<QuizScreen
image={questions[currentQuestionIndex].image}
options={questions[currentQuestionIndex].options}
onSelect={handleSelect}
/>
)}
<View style={styles.subContainer}>
<View style={styles.answerBlock}>
{!showScore && showResult && (
<Text style={styles.handleAnswer}>
{selectedAnswer === questions[currentQuestionIndex].correctOption
? 'Correct ✅'
: 'Try again ❌'}
</Text>
)}
</View>
{!showScore && (
// <TouchableOpacity
// style={[
// styles.nextButton,
// selectedOpt === null && styles.disabledButton,
// ]}
// onPress={handleNextQuestion}
// disabled={selectedOpt === null}
// >
// <Text style={[styles.nextButtonText, selectedOpt === null && styles.disabledButton]}>Next</Text>
// </TouchableOpacity>
<TouchableOpacity
style={[
styles.nextButton,
selectedAnswer === questions[currentQuestionIndex].correctOption
? styles.nextButtonEnabled
: styles.disabledButton,
]}
onPress={handleNextQuestion}
disabled={!selectedAnswer}
>
<Text style={[styles.nextButtonText, selectedAnswer !== questions[currentQuestionIndex].correctOption && styles.disabledButton]}>Next</Text>
</TouchableOpacity>
)}
</View>
</ImageBackground>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "column",
// flexWrap: "wrap",
backgroundColor: "#1f354b",
alignItems: "center",
justifyContent: "center",
},
subContainer: {
width: 350,
justifyContent: 'center',
alignItems: 'center'
},
bgimage: {
flex: 1,
justifyContent: 'center',
alignItems: "center",
},
imageContainer: {
// flex: 1,
alignItems: "center",
justifyContent: "center",
borderRadius: 16,
height: 200,
width: 200,
backgroundColor: "#0671d5"
},
image: {
// width: 300,
// height: 300,
resizeMode: "contain",
padding: 1,
alignItems: "center",
justifyContent: "center",
display: "flex",
width: "85%"
},
scoreContainer: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
scoreText: {
fontSize: 24,
color: "#fff",
fontWeight: "bold",
marginBottom: 16,
marginTop: 12
},
optionsContainer: {
// flex: 1,
display: "flex",
gap: 10,
flexDirection: "row",
width: 200,
alignItems: "center",
justifyContent: "center",
marginTop: 30
},
optionButtonText: {
color: "#000",
fontSize: 22,
fontWeight: "bold",
textAlign: "center",
},
answerBlock: {
height: 55
},
handleAnswer : {
color: "#ffffff",
padding: 16,
fontSize: 14
},
nextButton: {
backgroundColor: "#fff",
borderRadius: 16,
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 30,
paddingRight: 30,
},
nextButtonText: {
fontWeight: "bold",
fontSize: 16
},
disabledButton: {
backgroundColor: "#fff",
color: "lightgray"
},
restartButton: {
backgroundColor: "#f878b5",
padding: 12,
borderRadius: 8,
width: 160,
marginTop: 18
},
backButton: {
backgroundColor: "#6cdfef",
padding: 12,
borderRadius: 8,
width: 160,
marginTop: 18
},
restartButtonText: {
color: "#000",
fontSize: 16,
fontWeight: "bold",
textAlign: "center"
},
});
export default QuizApp; |
package com.ohgiraffers.section03.overriding;
public class SubClass extends SuperClass{
/*설명 0. 부모 메소드와 이름, 반환형, 매개변수, 접근 제어자 모두 동일한 경우에 오버라이딩 성립*/
// @Override
// public void method(int num) {}
/*설명 1. 메소드 이름 변경(에러 발생)*/
// @Override
// public void method1(int num) {}
/*설명 2. 메소드 리턴 타입 변경(에러 발생)*/
// @Override
// public String method(int num) {return null;}
/*설명 3. 메소드의 매개변수 변경(에러 발생)*/
// @Override
// public void method(int num, int num2) {}
/*설명 4. 부모 메소드 반환형 자식 타입으로만 반환형 변경 가능*/
public String method2(int num) {return null;}
/*설명 5. private 메소드는 오버라이딩 불가*/
// @Override
// private void privateMethod() {}
/*설명 6. final 메소드는 오버라이딩 불가*/
// @Override
// public final void finalMethod() {}
/*설명 7. 부모 타입과 같은 접근 제어자이거나 더 넓은 범위의 접근 제어자로 오버라이딩 가능*/
// @Override
// public void protectedMethod() {}
}
//public - protected - (default) - private
//protected: 자식 클래스는 다른 패키지에 위치한 경우에도 접근 가능 |
import {Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {CrudService} from '../../crud.service';
import {MatSnackBar} from '@angular/material';
import {AuthService} from '../../auth.service';
import {Subscription} from 'rxjs';
@Component({
selector: 'app-basket-order-item',
templateUrl: './basket-order-item.component.html',
styleUrls: ['./basket-order-item.component.scss']
})
export class BasketOrderItemComponent implements OnInit, OnDestroy {
@Input() data;
@Output() removeBasket = new EventEmitter();
public removeObj = {
index: null,
obj: null
};
public discount = 0;
public companyDiscount = 0;
public language;
public chooseAll = false;
public showConfirm = false;
public removeItemShow = false;
public items = [];
public translate = {
by: {
ru: 'Купить',
ua: 'Купити'
},
total: {
ru: 'Всего к оплате:',
ua: 'Всього до оплати'
}
};
// tslint:disable-next-line:variable-name
private _subscription: Subscription[] = [];
constructor(
private crud: CrudService,
private auth: AuthService,
private snackBar: MatSnackBar
) { }
ngOnDestroy() {
this._subscription.forEach((item) => {
item.unsubscribe();
});
}
ngOnInit() {
this._subscription.push(this.auth.onLanguage.subscribe((l: any) => {
if (l) {
this.language = l;
}
}));
this.mainChack();
this.crud.get(`product?query={"basketOwner":"${this.data._id}"}&populate={"path":"orderOwner","select":"img name price count discount loyaltyAvailable"}`).then((v: any) => {
if (v && v.length > 0) {
this.data.product = v;
this.data.product.forEach((item) => {
this.items.push({isChoise: item.verify, _id: item._id});
});
}
});
this._subscription.push(this.auth.onConfirmOrder.subscribe(v => {
if (!v) {return; }
this.showConfirm = true;
}));
this.crud.get(`my-discount/${this.data.companyOwner.createdBy}`).then((v: any) => {
if (v.success && v.discount) {
this.discount = v.discount;
} else {
this.discount = 0;
}
});
this.auth.onMe.subscribe((v: any) => {
this.crud.get(`discount?query={"$and": [{"client":"${v._id}"},{"provider":"${this.data.companyOwner.createdBy}"}]}`).then((d: any[]) => {
this.companyDiscount = (d && d.length !== 0) ? d[0].discount : 0;
});
});
}
closeConfirm(e) {
this.showConfirm = e.value;
this.removeBasket.emit(true);
}
closeRemoveItem(e) {
this.removeItemShow = e;
}
mainChack() {
this.chooseAll = !this.chooseAll;
if (this.chooseAll) {
this.items.forEach((item, index) => {
this.items[index].isChoise = true;
this.crud.post(`product`, {verify: true}, item._id).then((v: any) => {
if (v) {
this.refreshBasket();
}
});
});
} else {
this.items.forEach((item, index) => {
this.items[index].isChoise = false;
this.crud.post(`product`, {verify: false}, item._id).then((v: any) => {
if (v) {
this.refreshBasket();
}
});
});
}
}
otherChack(it) {
this.items[it].isChoise = !this.items[it].isChoise;
this.crud.post(`product`, {verify: this.items[it].isChoise}, this.data.product[it]._id).then((v: any) => {
if (v) {
this.refreshBasket();
}
});
let isAll = true;
this.items.forEach((item, index) => {
if (!this.items[index].isChoise) {
isAll = false;
}
});
this.chooseAll = isAll;
}
minus(i) {
let count = this.data.product[i].count;
count--;
if (count < 1) {
this.crud.delete(`product`, this.data.product[i]._id).then((v: any) => {
if (v) {
this.data.product.splice(i, 1);
this.removeBasket.emit(this.data._id);
}
});
} else {
this.data.product[i].count--;
this.crud.post(`product`, {count: this.data.product[i].count}, this.data.product[i]._id).then((v: any) => {
if (v) {
this.refreshBasket();
}
});
}
}
plus(i) {
this.data.product[i].count++;
this.crud.post(`product`, {count: this.data.product[i].count}, this.data.product[i]._id).then((v: any) => {
if (v) {
this.refreshBasket();
}
});
}
refreshBasket() {
this.crud.get(`basket?query={"_id":"${this.data._id}"}&select="totalPrice"`).then((v: any) => {
this.data.totalPrice = v[0].totalPrice;
});
}
removeProduct(i) {
this.removeItemShow = true;
this.removeObj = {
index: i,
obj: this.data.product[i]
};
}
successRemove(e) {
this.data.product.splice(e, 1);
if (this.data.product.length === 0) {
this.removeBasket.emit(true);
} else {
this.refreshBasket();
}
}
openConfirmComponent() {
if (this.data.totalPrice === 0) {
this.openSnackBar('Выберете товар поставщика', 'Ok');
return;
}
this.showConfirm = true;
}
openSnackBar(message: string, action: string) {
this.snackBar.open(message, action, {
duration: 2000,
});
}
} |
import { createSlice } from "@reduxjs/toolkit";
import type { PayloadAction } from "@reduxjs/toolkit";
import { menuBaguettes } from "./products";
interface Baguette {
name: string;
description: string;
ingredients: string[];
cost: number;
img: string;
stock: number;
isTopSell: boolean;
id: number;
}
interface ProductState {
baggetes: Baguette[];
cart: {
id: number;
quantity: number;
}[];
}
// Define the initial state using that type
const initialState: ProductState = {
baggetes: menuBaguettes,
cart: [],
};
export const productSlice = createSlice({
name: "product",
initialState,
reducers: {
addToCart: (state, action: PayloadAction<number>) => {
const index = state.cart.findIndex(
(product) => product.id === action.payload
);
if (index !== -1) {
state.cart[index].quantity += 1;
} else {
state.cart.push({ id: action.payload, quantity: 1 });
}
},
removeFromCart: (state, action: PayloadAction<number>) => {
const index = state.cart.findIndex(
(product) => product.id === action.payload
);
if (index !== -1) {
state.cart[index].quantity -= 1;
if (state.cart[index].quantity === 0) {
state.cart.splice(index, 1);
}
}
},
addProduct: (
state,
action: PayloadAction<{
name: string;
description: string;
ingredients: string[];
cost: number;
img: string;
}>
) => {
state.baggetes.push({
...action.payload,
stock: 10,
isTopSell: false,
id: state.baggetes.length + 1,
});
},
},
});
export const { addToCart, removeFromCart,addProduct } = productSlice.actions;
export default productSlice.reducer; |
/*
* SPDX-FileCopyrightText: 2019 Anna Medonosova <anna.medonosova@gmail.com>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef KISMIRRORAXISCONFIG_H
#define KISMIRRORAXISCONFIG_H
#include <QScopedPointer>
#include "kritaui_export.h"
#include <boost/operators.hpp>
class QDomElement;
class QDomDocument;
/**
* @brief The KisMirrorAxisConfig class stores configuration for the KisMirrorAxis
* canvas decoration. Contents are saved to/loaded from KRA documents.
*/
class KRITAUI_EXPORT KisMirrorAxisConfig : public QObject, boost::equality_comparable<KisMirrorAxisConfig>
{
Q_OBJECT
public:
KisMirrorAxisConfig();
~KisMirrorAxisConfig();
KisMirrorAxisConfig(const KisMirrorAxisConfig &rhs);
KisMirrorAxisConfig& operator=(const KisMirrorAxisConfig& rhs);
bool operator==(const KisMirrorAxisConfig& rhs) const;
bool mirrorHorizontal() const;
void setMirrorHorizontal(bool state);
bool mirrorVertical() const;
void setMirrorVertical(bool state);
bool lockHorizontal() const;
void setLockHorizontal(bool state);
bool lockVertical() const;
void setLockVertical(bool state);
bool hideVerticalDecoration() const;
void setHideVerticalDecoration(bool state);
bool hideHorizontalDecoration() const;
void setHideHorizontalDecoration(bool state);
float handleSize() const;
void setHandleSize(float size);
float horizontalHandlePosition() const;
void setHorizontalHandlePosition(float position);
float verticalHandlePosition() const;
void setVerticalHandlePosition(float position);
QPointF axisPosition() const;
void setAxisPosition(QPointF position);
/**
* @brief saveToXml() function for KisKraSaver
* @param doc
* @param tag
* @return
*/
QDomElement saveToXml(QDomDocument& doc, const QString &tag) const;
/**
* @brief loadFromXml() function for KisKraLoader
* @param parent element
* @return
*/
bool loadFromXml(const QDomElement &parent);
/**
* @brief Check whether the config object was changed, or is the class default.
* @return true, if the object is default; false, if the config was changed
*/
bool isDefault() const;
private:
class Private;
const QScopedPointer<Private> d;
};
#endif // KISMIRRORAXISCONFIG_H |
<?php
/**
* The template for displaying product category thumbnails within loops
*
* This template can be overridden by copying it to yourtheme/woocommerce/content-product-cat.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* @see https://woo.com/document/template-structure/
* @package WooCommerce\Templates
* @version 4.7.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
?>
<?php $term = $category; ?>
<div class="col-lg-4">
<div class="advert-item">
<a href="<?php echo get_term_link( $term->term_id )?>">
<?php
$term_thumbnail_id = get_term_meta( $term->term_id, 'thumbnail_id', true ); // Get the ID of the term thumbnail
$term_thumbnail = wp_get_attachment_image( $term_thumbnail_id, 'full' ); // Get the HTML markup for the term thumbnail
?>
<?php if( $term_thumbnail ): ?>
<?php echo $term_thumbnail; ?>
<?php else: ?>
<img src="<?php echo TYPEROCKET_DIR_URL; ?>/resources/assets/img/placeholder.webp" class="thumbnail">
<?php endif; ?>
<div class="advert-item-title">
<h4><?php echo $term->name; ?></h4>
</div>
</a>
</div>
</div>
<!-- <li <?php // wc_product_cat_class( '', $category ); ?>>
<?php
/**
* The woocommerce_before_subcategory hook.
*
* @hooked woocommerce_template_loop_category_link_open - 10
*/
// do_action( 'woocommerce_before_subcategory', $category );
/**
* The woocommerce_before_subcategory_title hook.
*
* @hooked woocommerce_subcategory_thumbnail - 10
*/
// do_action( 'woocommerce_before_subcategory_title', $category );
/**
* The woocommerce_shop_loop_subcategory_title hook.
*
* @hooked woocommerce_template_loop_category_title - 10
*/
// do_action( 'woocommerce_shop_loop_subcategory_title', $category );
/**
* The woocommerce_after_subcategory_title hook.
*/
// do_action( 'woocommerce_after_subcategory_title', $category );
/**
* The woocommerce_after_subcategory hook.
*
* @hooked woocommerce_template_loop_category_link_close - 10
*/
// do_action( 'woocommerce_after_subcategory', $category );
?>
</li> --> |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>La Hot Fast Food</title>
<!-- Link for the icon -->
<link rel="icon" href="images/egusi 2.png">
<!-- Google Fonts API -->
<style>
@import url('https://fonts.googleapis.com/css2?family=Asap+Condensed&family=Jost&family=Kanit&family=Noto+Sans+Display:wght@600&family=PT+Sans+Narrow&family=Slabo+27px&family=Ubuntu:wght@500&display=swap');
</style>
<!-- for second font "dancing Script" -->
<style>
@import url('https://fonts.googleapis.com/css2?family=Asap+Condensed&family=Dancing+Script&family=Jost&family=Kanit&family=Noto+Sans+Display:wght@600&family=PT+Sans+Narrow&family=Slabo+27px&family=Ubuntu:wght@500&display=swap');
</style>
<!-- BootStrap Link CSS-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<!-- customised CSS -->
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<!-- Main Container -->
<div class="container-main">
<!-- for menu section -->
<div class="menu" onclick="closeOrderBox()">
<h2 class="logo">La-Hot</h2>
<!-- code for navbarIcon -->
<div class="navButtons">
<i class="fa-solid fa-xmark " id="closeNavs"></i>
<i class="fa-solid fa-burger" id="openNavs"></i>
</div>
<!-- for nav-links PRIMARY specifically designed to show only on the mobile screens -->
<div class="nav-links">
<ul>
<li><a href="#home" class="Active-Link nav-1">Home</a></li>
<li><a href="#menu" class="nav-2">Menu</a></li>
<li><a href="#about" class="nav-3">About</a></li>
<li><a href="#bookTable" class="nav-4">Book Table</a></li>
<li><a href="accoutnlogin.html"><i class="fa-solid fa-user-plus" id="registerAccount"></i></a></li>
</ul>
</div>
<!-- For Nav-Links SECONDARY specifically designed to show on the desktop or Large Screens only-->
<div class="nav-linksSecondary">
<ul>
<li><a href="#home" class="Active-Link nav-1">Home</a></li>
<li><a href="#menu" class="nav-2">Menu</a></li>
<li><a href="#about" class="nav-3">About</a></li>
<li><a href="#bookTable" class="nav-4">Book Table</a></li>
<li><a href="accoutnlogin.html" target="_blank"><i class="fa-solid fa-user-plus" id="registerAccount"></i></a>
<!-- <p class="userNameContainer" style="position: relative; left: -15px; top: 5px;"></p> -->
</li>
</ul>
</div>
<!-- For Nav-Links Secondary -->
</div>
<!-- Home Section -->
<section id="home">
<div class="imageContainerBg">
<img src="images/bg2.png" alt="" class="backgroundImg">
</div>
<!-- For the Order Online Container -->
<div class="makeOrder">
<div class="innerContentsForm">
<h2 class="head">La-hot Order Form <br> Free and fast</h2>
<form action="" id="order" autocomplete="on">
<!-- for name container -->
<div class="orderName">
<label for="name-food" class="labels">Name:</label> <br>
<input type="text" autocomplete="family-name" placeholder="First" id="name-food" required>
<input type="text" autocomplete="name" placeholder="Last" id="name-food" required>
</div>
<!-- For Purchaser's Email Container -->
<div class="purchaseEmail">
<label for="purchaser-email" class="labels">Purchaser's Email</label> <br>
<input type="email" autocomplete="email" placeholder="Your Email" id="purchaser-email" required>
</div>
<!-- For delievery phone container -->
<div class="phoneOrder">
<label for="delievery-phone" class="labels">Your Phone:</label> <br>
<input type="tel" autocomplete="tel" id="delievery-phone" placeholder="+234 XXX XXX XX" required>
</div>
<!-- for delivery address container -->
<div class="delievryAddress">
<label for="delievery-address" class="labels">Delivery Address:</label> <br>
<input type="text" autocomplete="address-line1" id="delievery-address" placeholder="Street Address" required> <br>
<input type="text" autocomplete="address-line2" id="delievery-address" placeholder="Street Address Line 2">
</div>
<div class="cityAddress">
<input type="text" autocomplete="street-address" id="city-order" placeholder="City" required>
<input type="text" autocomplete="state" id="city-order" placeholder="Region/State">
</div>
<div class="postalcode">
<input type="text" autocomplete="postal-code" id="zip-code" placeholder="Postal/Zip Code">
<input list="Country-order" placeholder="Country" id="zip-code" required />
<datalist id="Country-order">
<option value="Nigeria "></option>
<option value="USA "></option>
<option value="Canada "></option>
<option value="Switzerland"></option>
<option value="Denmark"></option>
<option value="UK"></option>
<option value="Other"></option>
</datalist>
</div>
<!-- For the foods in ordering -->
<div class="foodNamestoOrder">
<div class="food-1Order">
<input type="checkbox" name="" id="">
<img src="images/okro soup main.png" alt="" class="okro-order-food">
<div class="orderTexts">
<p>Okro Soup</p>
<p><i class="fa-solid fa-naira-sign">2, 500</i></p>
<p>
<label for="QuantityOf-Foods">Quantity</label> <br>
<input type="number">
</p>
</div>
</div>
<!-- Food order 2 -->
<div class="food-2Order">
<input type="checkbox" name="" id="">
<img src="images/egusi 2.png" alt="" class="okro-order-food">
<div class="orderTexts">
<p>Egusi Soup</p>
<p><i class="fa-solid fa-naira-sign">3, 500</i></p>
<p>
<label for="QuantityOf-Foods">Quantity</label> <br>
<input type="number">
</p>
</div>
</div>
<!-- Food order 3 -->
<div class="food-3Order">
<input type="checkbox" name="" id="">
<img src="images/egg sauce 3.png" alt="" class="okro-order-food">
<div class="orderTexts">
<p>Egg Sauce</p>
<p><i class="fa-solid fa-naira-sign">5, 000</i></p>
<p>
<label for="QuantityOf-Foods">Quantity</label> <br>
<input type="number">
</p>
</div>
</div>
<!-- Food order 4 -->
<div class="food-4Order">
<input type="checkbox" name="" id="">
<img src="images/fried rice 2.png" alt="" class="okro-order-food">
<div class="orderTexts">
<p>Fried Rice</p>
<p><i class="fa-solid fa-naira-sign">2, 500</i></p>
<p>
<label for="QuantityOf-Foods">Quantity</label> <br>
<input type="number">
</p>
</div>
</div>
</div>
<div class="sub">
<button type="submit" class="submit">Make Order</button>
</div>
</form>
</div>
</div>
<!-- carousel -->
<div class="carouselContainer">
<div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-indicators">
<button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active"
aria-current="true" aria-label="Slide 1" id="carouselButtonHome"></button>
<button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"
id="carouselButtonHome"></button>
<button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="2" aria-label="Slide 3"
id="carouselButtonHome"></button>
</div>
<div class="carousel-inner">
<div class="carousel-item active">
<h2>La Hot <br> Fast Food Restaurant</h2>
<p>
WELCOME.... Explore the beauty and serene arena of our reataurant.. <br> We offer the best sales and
affordable foods in Nigeria.
This is a place to call your home. <br> As a Nigerian based reaturant, we are happy to let you taste the
sweet aroma of our food.
</p>
<button class="orderBtn" >
Order Online
</button>
</div>
<div class="carousel-item">
<h2>La Hot <br> Fast Food Restaurant</h2>
<p>
WELCOME.... Explore the beauty and serene arena of our reataurant.. <br> We offer the best sales and
affordable foods in Nigeria.
This is a place to call your home. <br> As a Nigerian based reaturant, we are happy to let you taste the
sweet aroma of our food.
</p>
<button class="orderBtn" >
Order Online
</button>
</div>
<div class="carousel-item">
<h2>La Hot <br> Fast Food Restaurant</h2>
<p>
WELCOME.... Explore the beauty and serene arena of our reataurant.. <br> We offer the best sales and
affordable foods in Nigeria.
This is a place to call your home. <br> As a Nigerian based reaturant, we are happy to let you taste the
sweet aroma of our food.
</p>
<button class="orderBtn" >
Order Online
</button>
</div>
</div>
</div>
</div>
</section>
<!-- Our Menu Section -->
<section id="menu" onclick="closeOrderBox()">
<h2 class="titleHeadre">Our Menu</h2>
<div class="foodsContent">
<button id="forAllFoods">All</button>
<button id="EgusiBtn">Egusi Soup</button>
<button id="OkroBtn">Okro Soup</button>
<button id="AmalaBtn">Amala & Ewedu Meal</button>
<button id="MeatPieBtn">Meat Pie</button>
<button id="FRiedRiceBtn">Fried Rice</button>
<button id="EggSauceBtn">Egg Sauce</button>
</div>
<div class="foodNames">
<!-- for all the foods container -->
<!-- This container contains all the availabel foods -->
<div class="AllFoods">
<div class="cardsforFood">
<div class="foodcard1">
<div class="cardup">
<img src="images/fried rice 2.png" alt="">
</div>
<div class="cardDown">
<h3>Delicious Fried Rice</h3>
<p>Dont miss the blessed taste of our Fried Rice <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">2, 500</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- food 2 -->
<div class="foodcard2">
<div class="cardup">
<img src="images/okro soup 4.png" alt="">
</div>
<div class="cardDown">
<h3>Delicious Okro Soup</h3>
<p>Dont miss the blessed taste of our Okro<br> A food you are not going to compare with another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">4, 700</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- food 3 -->
<div class="foodcard3">
<div class="cardup">
<img src="images/egusi 1.png" alt="">
</div>
<div class="cardDown">
<h3>Delicious Egusi Soup</h3>
<p>Dont miss the blessed taste of our Egusi Soup <br> A food you are not going to compare with another
</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">3, 500</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- food 4 -->
<div class="foodcard4">
<div class="cardup">
<img src="images/egusi 2.png" alt="">
</div>
<div class="cardDown">
<h3>Delicious Egusi Soup</h3>
<p>Dont miss the blessed taste of our Egusi Soup <br> A food you are not going to compare with another
</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">3, 500</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- food 5 -->
<div class="foodcard5">
<div class="cardup">
<img src="images/egg sauce 1.png" alt="">
</div>
<div class="cardDown">
<h3>Delicious Egg Sauce</h3>
<p>Dont miss the blessed taste of our Egg Sauce <br> A food you are not going to compare with another
</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">5, 000</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- food 6 -->
<div class="foodcard7">
<div class="cardup">
<img src="images/egg sauce 3.png" alt="">
</div>
<div class="cardDown">
<h3>Delicious Egg Sauce</h3>
<p>Dont miss the blessed taste of our Egg Sauce <br> A food you are not going to compare with another
</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">5, 000</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- food 7 -->
<div class="foodcard7">
<div class="cardup">
<img src="images/meat pie 1.png" alt="">
</div>
<div class="cardDown">
<h3>Delicious Meat Pie</h3>
<p>Dont miss the blessed taste of our Meat Pie <br> A food you are not going to compare with another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">1, 950</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- food 8 -->
<div class="foodcard8">
<div class="cardup">
<img src="images/dry meats bg.png" alt="">
</div>
<div class="cardDown">
<h3>Delicious Dry Meat</h3>
<p>Dont miss the blessed taste of our Dry Meat <br> A food you are not going to compare with another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">2, 400</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- food card 9 -->
<div class="foodcard9">
<div class="cardup">
<img src="images/bg1.png" alt="">
</div>
<div class="cardDown">
<h3>Delicious Chicken Jollof Rice</h3>
<p>Dont miss the blessed taste of our Chicken Jollof Rice <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">7, 000</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- food card 10 -->
<div class="foodcard10">
<div class="cardup">
<img src="images/bg2.png" alt="">
</div>
<div class="cardDown">
<h3>Delicious Macaroni Pasta</h3>
<p>Dont miss the blessed taste of our Macaroni Pasta <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">9, 700</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- food card 11 -->
<div class="foodcard11">
<div class="cardup">
<img src="images/okro soup 2.png" alt="">
</div>
<div class="cardDown">
<h3>Delicious Okro Soup</h3>
<p>Dont miss the blessed taste of our Chicken Okro Soup <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">4, 700</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- food card 12 -->
<div class="foodcard12">
<div class="cardup">
<img src="images/amala and ewedu 2.png" alt="">
</div>
<div class="cardDown">
<h3>Delicious Amala & Ewedu Soup</h3>
<p>Dont miss the blessed taste of our Amala & Ewedu Soup <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">2, 700</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
</div>
</div>
<!-- container for Egusi Soup -->
<div class="EgusiSoupSection">
<div class="Egusi1">
<div class="cardupEgusi">
<img src="images//egusi 3.png" alt="">
</div>
<div class="cardDownEgusi">
<h3>Delicious Naija Egusi Soup</h3>
<p>Dont miss the blessed taste of our Egusi Soup <br> A food you are not going to compare with another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">3, 500</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- For the second soup -->
<div class="Egusi2">
<div class="cardupEgusi">
<img src="images/egusi 1.png" alt="">
</div>
<div class="cardDownEgusi">
<h3>Delicious Naija Egusi Soup</h3>
<p>Dont miss the blessed taste of our Egusi Soup <br> A food you are not going to compare with another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">3, 500</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- for thr third Egusi -->
<div class="Egusi3">
<div class="cardupEgusi">
<img src="images/egusi 2.png" alt="">
</div>
<div class="cardDownEgusi">
<h3>Delicious Naija Egusi Soup</h3>
<p>Dont miss the blessed taste of our Egusi Soup <br> A food you are not going to compare with another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">3, 500</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
</div>
<!-- Container for Okro Soup -->
<div class="okroSoupSection">
<div class="Okro1">
<div class="cardupOkro">
<img src="images/okro soup 5.png" alt="">
</div>
<div class="cardDownOkro">
<h3>Delicious Naija Okro Soup</h3>
<p>Dont miss the blessed taste of our Okro Soup <br> A food you are not going to compare with another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">4, 700</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- for the second okro soup -->
<div class="Okro2">
<div class="cardupOkro">
<img src="images/okro soup 2.png" alt="">
</div>
<div class="cardDownOkro">
<h3>Delicious Naija Okro Soup</h3>
<p>Dont miss the blessed taste of our Okro Soup <br> A food you are not going to compare with another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">4, 700</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- for the third okro soup -->
<div class="Okro3">
<div class="cardupOkro">
<img src="images/okro soup 1.png" alt="">
</div>
<div class="cardDownOkro">
<h3>Delicious Naija Okro Soup</h3>
<p>Dont miss the blessed taste of our Okro Soup <br> A food you are not going to compare with another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">4, 700</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- for the 4th Okro Soup -->
<div class="Okro4">
<div class="cardupOkro">
<img src="images/okro soup main.png" alt="">
</div>
<div class="cardDownOkro">
<h3>Delicious Naija Okro Soup</h3>
<p>Dont miss the blessed taste of our Okro Soup <br> A food you are not going to compare with another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">4, 700</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
</div>
<!-- Container for Amala & Ewedu Food Section -->
<div class="AmalaFoodsSection">
<div class="Amala1">
<div class="cardupAmala">
<img src="images/amala and ewedu 2.png" alt="">
</div>
<div class="cardDownAmala">
<h3>Delicious Naija Amala & Ewedu Meal</h3>
<p>Dont miss the blessed taste of our Amala & Ewedu Meal <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">2, 700</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- For the 2nd Amala & Ewedu Food -->
<div class="Amala2">
<div class="cardupAmala">
<img src="images/amala and ewedu 1.png" alt="">
</div>
<div class="cardDownAmala">
<h3>Delicious Naija Amala & Ewedu Meal</h3>
<p>Dont miss the blessed taste of our Amala & Ewedu Meal <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">2, 700</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
</div>
<!-- Container for Meat Pie Section -->
<div class="MeatPieFoods">
<div class="MeatPie1">
<div class="cardupMeatPie">
<img src="images//meat pie 3.png" alt="">
</div>
<div class="cardDowMeatPie">
<h3>Delicious Naija Meat Pie</h3>
<p>Dont miss the blessed taste of our Meat Pie <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">1, 950</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- for the second Meat Pie -->
<div class="MeatPie2">
<div class="cardupMeatPie">
<img src="images//meat pie 1.png" alt="">
</div>
<div class="cardDowMeatPie">
<h3>Delicious Naija Meat Pie</h3>
<p>Dont miss the blessed taste of our Meat Pie <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">1, 950</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- for the 3rd Meat Pie -->
<div class="MeatPie3">
<div class="cardupMeatPie">
<img src="images//meat pie 2.png" alt="">
</div>
<div class="cardDowMeatPie">
<h3>Delicious Naija Meat Pie</h3>
<p>Dont miss the blessed taste of our Meat Pie <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">1, 950</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
</div>
<!-- Container for Fried Rice Section -->
<div class="friedRiceSection">
<div class="FriedRice1">
<div class="cardupFriedRice">
<img src="images/fried rice 1.png" alt="">
</div>
<div class="cardDowFriedRice">
<h3>Delicious Naija Fried Rice</h3>
<p>Dont miss the blessed taste of our Fried Rice <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign" id="price1">2500</i>
<i class="fa-solid fa-cart-plus" id="calculateRice1"></i>
</div>
</div>
</div>
<!-- for the 2nd fried rice food -->
<div class="FriedRice2">
<div class="cardupFriedRice">
<img src="images/fried rice 2.png" alt="">
</div>
<div class="cardDowFriedRice">
<h3>Delicious Naija Fried Rice</h3>
<p>Dont miss the blessed taste of our Fried Rice <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign" id="price2">2500</i>
<i class="fa-solid fa-cart-plus" id="calculateRice2"></i>
</div>
</div>
</div>
<!-- for the 3rd fried rice food -->
<div class="FriedRice3">
<div class="cardupFriedRice">
<img src="images/fried rice 3.png" alt="">
</div>
<div class="cardDowFriedRice">
<h3>Delicious Naija Fried Rice</h3>
<p>Dont miss the blessed taste of our Fried Rice <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign" id="price3">2500</i>
<i class="fa-solid fa-cart-plus" id="calculateRice3"></i>
</div>
</div>
</div>
</div>
<!-- Container for Egg sauce -->
<div class="eggSauceContainer">
<div class="EggSauce1">
<div class="cardupEggSauce">
<img src="images/sauce bg egg.png" alt="">
</div>
<div class="cardDowEggSauce">
<h3>Delicious Naija Egg Sauce</h3>
<p>Dont miss the blessed taste of our Egg Sauce <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">5, 000</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- for the 2nd egg sauce food -->
<div class="EggSauce2">
<div class="cardupEggSauce">
<img src="images/egg sauce 1.png" alt="">
</div>
<div class="cardDowEggSauce">
<h3>Delicious Naija Egg Sauce</h3>
<p>Dont miss the blessed taste of our Egg Sauce <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">5, 000</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- for the 3rd Egg Suace -->
<div class="EggSauce3">
<div class="cardupEggSauce">
<img src="images/egg sauce 3.png" alt="">
</div>
<div class="cardDowEggSauce">
<h3>Delicious Naija Egg Sauce</h3>
<p>Dont miss the blessed taste of our Egg Sauce <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">5, 000</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- for the 4th Egg Sauce -->
<div class="EggSauce4">
<div class="cardupEggSauce">
<img src="images/egg sauce 4.png" alt="">
</div>
<div class="cardDowEggSauce">
<h3>Delicious Naija Egg Sauce</h3>
<p>Dont miss the blessed taste of our Egg Sauce <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">5, 000</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
<!-- for the 5th Egg Sauce -->
<div class="EggSauce5">
<div class="cardupEggSauce">
<img src="images/egg sauce 5.png" alt="">
</div>
<div class="cardDowEggSauce">
<h3>Delicious Naija Egg Sauce</h3>
<p>Dont miss the blessed taste of our Egg Sauce <br> A food you are not going to compare with
another</p>
<div class="inner">
<i class="fa-solid fa-naira-sign">5, 000</i>
<i class="fa-solid fa-cart-plus"></i>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- About Section -->
<section id="about">
<!-- for the about us Container -->
<div class="aboutContainerr">
<!-- container for the image on the about -->
<div class="aboutImg">
<img src="images/sauce bg egg.png" alt="">
</div>
<!-- container for the About us Text -->
<div class="aboutText">
<h2 class="aboutHeader">We Are La-Hot</h2>
<p class="aboutInfoText">
"Welcome to La-Hot Restaurant <strong>'Nigerian best Restaurant'</strong> where culinary excellence meets a
warm and inviting atmosphere.
Discover a symphony of flavors, crafted with passion and precision, in a warm and inviting ambiance. From
delectable appetizers to
mouthwatering entrees and decadent desserts, our menu celebrates culinary excellence. Join us for a
memorable dining experience,
where every bite tells a story. Explore our menu, reserve your table, and savor the moment at La-Hot
Restaurant.
Whether you're seeking a romantic dinner, a lively family gathering, or a memorable celebration, our
restaurant promises to delight your
senses and create lasting memories.
Our story began with a dream to provide a place where friends and family could gather over exceptional food
and drinks. We've carefully
curated a menu that blends traditional and
contemporary flavors, resulting in a dining experience that transcends the ordinary.
Join us for a gastronomic journey that combines impeccable service with a passion for exceptional food."
</p>
</div>
</div>
</section>
<!-- Book A Table Section -->
<section id="bookTable" onclick="closeOrderBox()">
<!-- bookingHeader -->
<h2 class="bookingHeader">Reserve A Table Now</h2>
<div class="formBookingTable">
<form action="" method="post" autocomplete="on">
<!-- for name input field -->
<div class="nameFied">
<label for="YourName"></label>
<input type="text" id="YourName" placeholder="Your Name" autocomplete="name" autocapitalize="name"
required>
</div>
<!-- for phone number input field -->
<div class="numberFied">
<label for="YourNumber"></label>
<input type="tel" id="YourNumber" placeholder="Phone Number" autocomplete="tel" maxlength="15" required>
</div>
<!-- for email input field -->
<div class="emailFied">
<label for="YourEmail"></label>
<input type="text" id="YourEmail" placeholder="Your Email" autocomplete="email" required>
</div>
<!-- For booking the number of persons fieled -->
<div class="tableNumberFieled">
<input list="book-now" placeholder="How Many People?" required />
<datalist id="book-now">
<option value="1"></option>
<option value="3"></option>
<option value="4"></option>
<option value="7"></option>
<option value="8"></option>
<option value="10"></option>
</datalist>
</div>
<!-- for the date of booking -->
<div class="bookingdateFieled">
<label for="dateOfBooking"></label>
<input type="datetime-local" id="dateOfBooking" required>
</div>
<!-- Booking Button -->
<button type="submit" id="BookingBtn">
Book Now
</button>
</form>
</div>
</section>
<!-- What Our Customer's say Section -->
<section id="customers">
<h2 class="customerHeader">See What Our Customer's Are Saying</h2>
<div class="customerContainer">
<!-- For the carousel cintainer -->
<div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-indicators">
<button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active"
aria-current="true" aria-label="Slide 1" id="hideCarousel"></button>
<button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"
id="hideCarousel"></button>
<button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="2" aria-label="Slide 3"
id="hideCarousel"></button>
</div>
<div class="carousel-inner">
<!-- for the first carousel item -->
<div class="carousel-item active">
<div class="customerCommentsContainer">
<p class="customerMsg">
"An evening at La-Hot is a sensory symphony of flavors, elegance, and hospitality. From the moment you
step through the door, you're
transported to a world of culinary delight. The menu is a culinary masterpiece,
a carefully orchestrated fusion of innovation and tradition. <br>
<i class="fa-solid fa-star fa-beat"></i><i class="fa-solid fa-star fa-beat"></i>
<i class="fa-solid fa-star fa-beat"></i><i class="fa-solid fa-star fa-beat"></i>
<i class="fa-solid fa-star fa-beat"></i>
<aside>
<strong>Miracle Chibuike</strong> <br> <i class="fa-solid fa-location-dot fa-beat-fade"></i> Owerri,
Nigeria
</aside>
</p>
</div>
<i class="fa-solid fa-caret-up"></i>
<img src="images/miracles image.jpg" alt="..." id="customerImg1">
</div>
<!-- for the 2nd carousel Item -->
<div class="carousel-item">
<div class="customerCommentsContainer2">
<p class="customerMsg">
"An evening at La-Hot is a sensory symphony of flavors, elegance, and hospitality. From the moment you
step through the door, you're
transported to a world of culinary delight. The menu is a culinary masterpiece,
a carefully orchestrated fusion of innovation and tradition. <br>
<i class="fa-solid fa-star fa-beat"></i><i class="fa-solid fa-star fa-beat"></i>
<i class="fa-solid fa-star fa-beat"></i><i class="fa-solid fa-star fa-beat"></i>
<i class="fa-solid fa-star fa-beat"></i>
<aside>
<strong>Miracle Chibuike</strong> <br> <i class="fa-solid fa-location-dot fa-beat-fade"></i> Owerri,
Nigeria
</aside>
</p>
</div>
<i class="fa-solid fa-caret-up"></i>
<img src="images/mira2.jpg" alt="..." id="customerImg2">
</div>
<!-- for the 3rd carousel item -->
<div class="carousel-item">
<div class="customerCommentsContainer3">
<p class="customerMsg">
"An evening at La-Hot is a sensory symphony of flavors, elegance, and hospitality. From the moment you
step through the door, you're
transported to a world of culinary delight. The menu is a culinary masterpiece,
a carefully orchestrated fusion of innovation and tradition. <br>
<i class="fa-solid fa-star fa-beat"></i><i class="fa-solid fa-star fa-beat"></i>
<i class="fa-solid fa-star fa-beat"></i><i class="fa-solid fa-star fa-beat"></i>
<i class="fa-solid fa-star fa-beat"></i>
<aside>
<strong>Miracle Chibuike</strong> <br> <i class="fa-solid fa-location-dot fa-beat-fade"></i> Owerri,
Nigeria
</aside>
</p>
</div>
<i class="fa-solid fa-caret-up"></i>
<img src="images/miracles image.jpg" alt="..." id="customerImg3">
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators"
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="#carouselExampleIndicators"
data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
</div>
</section>
<!-- Footer Section -->
<section id="Footer">
<!-- This Div is going to be divided in 3 sections -->
<!-- for the parent Footer-Outer container -->
<div class="parentFooter">
<!-- Container For Contact Us -->
<div class="contactUsContainer">
<h2 class="contactHeader">Let's Get In Touch</h2>
<!-- for location -->
<p>
<i class="fa-solid fa-location-dot"></i>
Owerri, Imo State Nigeria
</p>
<!-- for phone contact -->
<p>
<i class="fa-solid fa-phone-volume fa-shake"></i>
<a href="tel:+2349056255572">Call +234 905-625-5572</a>
</p>
<!-- for email contact -->
<p>
<i class="fa-solid fa-envelope"></i>
<a href="mailto:lahotfastfoodng@gmail.com">lahotfastfood@gmail.com</a>
</p>
</div>
<!-- Container For Retaurant Info -->
<div class="laHotContainer">
<h2 class="lahotHeadre">La-Hot</h2>
<p class="lahotText">
"In the heart of Owerri, Imo, a culinary journey was born. <br> La-Hot, established in 2002, has a rich
history
of delighting palates <br> and creating cherished memories. <br> What began as a humble endeavor by
<strong>Onyia Miracle Chibuike</strong> <br> soon evolved into
a gastronomic destination renowned <br> for its commitment to quality and innovation."
</p>
</div>
<!-- Container for Opening Hours -->
<div class="openingHoursContainer">
<h2 class="hoursHeadre">Opening Hours</h2>
<p><strong>Monday to Friday</strong>
<aside>
8:00 Am - 8:30 Pm
</aside>
</p>
<p>
<strong>Sundays </strong>
<aside>
2:00 Pm - 7:30 Pm
</aside>
</p>
</div>
</div>
<!-- For the Social Media Icons -->
<div class="socilaMediaContacts">
<!-- LiinkedIn icon-->
<a href="http://www.linkedin.com/in/onyia-miracle-b582b4237/"><i class="fa-brands fa-linkedin-in"></i></a>
<!-- for facebook icon-->
<i class="fa-brands fa-facebook-f"></i>
<!-- for Instagram icon-->
<i class="fa-brands fa-instagram"></i>
<!-- for pinterest icon -->
<i class="fa-brands fa-pinterest-p"></i>
<!-- for twitter icon -->
<i class="fa-brands fa-x-twitter"></i>
</div>
<!-- For the Last Message Down -->
<div class="Rights">
<p> © 2023 All Rights Reserved By <a href="http://github.com/MiracleChibuike" target="_blank"> Miracle-Tech
Coding Projects</a> </p>
<p>© Distributed By <a href="http://github.com/MiracleChibuike">Miracle Chibuike</a></p>
<!-- Adding Google Translate Page -->
<!-- Adding a google translate API -->
<p>You can translate the content of this page below</p>
<div id="google_translate_element"></div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({ pageLanguage: 'en' }, 'google_translate_element');
}
</script>
<script type="text/javascript"
src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
</div>
</section>
</div>
<!-- Bootstrap Link Js -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"
integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"
integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF"
crossorigin="anonymous"></script>
<!-- font-awsome Script -->
<script src="https://kit.fontawesome.com/9b5c4c6b23.js" crossorigin="anonymous"></script>
<!-- custom JS -->
<script src="js/index.js"></script>
</body>
</html> |
package com.example.FileWizard.controller;
import com.example.FileWizard.model.User;
import com.example.FileWizard.model.UserFile;
import com.example.FileWizard.service.FileService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@RestController
@RequestMapping("/api")
public class FileController {
private final FileService fileService;
public FileController(FileService fileService) {
this.fileService = fileService;
}
@GetMapping("/all-files")
public ResponseEntity<List<UserFile>> getAll() {
return ResponseEntity.ok(fileService.getAll());
//endpoint: http://localhost:8080/api/all-files
//Desc: Returns all files
}
@GetMapping("/my-files")
public ResponseEntity<?> getMyFolders(@AuthenticationPrincipal UserDetails userDetails) {
System.out.println("Finding files for: " + userDetails.getUsername());
return ResponseEntity.ok(fileService.getMyFiles(userDetails.getUsername()));
//endpoint: http://localhost:8080/api/my-files
//Desc: Returns all (authenticated users) files
//Require: Token
}
@PostMapping("/upload")
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("folder") String folder, @AuthenticationPrincipal UserDetails userDetails) {
try {
return ResponseEntity.ok(fileService.uploadFile(file, folder, (User) userDetails));
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error creating file: " + e.getMessage());
}
// endpoint: http://localhost:8080/api/upload
/* MultipartFile / form-data:
{
"file" (file): testfile.file
"folder" (text/string): "testfolder"
}
*/
//Require: Token
}
@GetMapping("/download/{fileId}")
public ResponseEntity<?> downloadFile(@PathVariable Long fileId, @AuthenticationPrincipal UserDetails userDetails) {
try {
return fileService.downloadFile(fileId, (User) userDetails);
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error creating file: " + e.getMessage());
}
// endpoint: http://localhost:8080/api/download/{id}
//Require: Token
}
@DeleteMapping("/delete/{fileId}")
public ResponseEntity<?> deleteFile(@PathVariable Long fileId, @AuthenticationPrincipal UserDetails userDetails) {
try {
return fileService.deleteFile(fileId, (User) userDetails);
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error creating file: " + e.getMessage());
}
// endpoint: http://localhost:8080/api/delete/{id}
//Require: Token
}
} |
use actix_identity::Identity;
use actix_web::{web, Responder, Result};
use chrono::{DateTime, Days, Utc};
use lettre::message::header::ContentType;
use log::error;
use surrealdb::sql::Thing;
use super::response::Response;
use crate::{
mail::{
mailing::{build_mail, send_mail}, utils::{load_template, Mailer}
}, models::{
links_model::{Link, LinkType}, model::{ConnectionData, CRUD}, user_model::User
}
};
pub async fn change_email_get(
id: Option<Identity>, db: ConnectionData, mailer: web::Data<Mailer>,
) -> Result<impl Responder> {
if id.is_none() {
return Ok(web::Json(Response::new_error(403, "Not logged in".into())));
}
let id = id.unwrap();
let id = match id.id() {
Ok(a) => a,
Err(e) => {
error!("Error trying to get id.id()\n{e}");
return Ok(Response::new_error(500, "Internal Server Error".into()).into());
}
};
let user = match User::get_from_id(db.clone(), Thing::from(id.split_once(':').unwrap())).await {
Ok(a) => match a {
Some(a) => a,
None => {
error!("User not found?");
return Ok(Response::new_error(500, "Internal Server Error".into()).into());
}
},
Err(e) => {
error!("Error getting user from id\n{e}");
return Ok(Response::new_error(500, "Internal Server Error".into()).into());
}
};
let mail = user.email.clone();
let expiry: DateTime<Utc> = Utc::now().checked_add_days(Days::new(2)).unwrap();
let link = match Link::create_from_user(db, user, expiry, LinkType::EmailChange).await {
Ok(a) => a.construct_link(),
Err(e) => {
error!("Error creating link\n{e}");
return Ok(Response::new_error(500, "Internal Server Error".into()).into());
}
};
let template = match load_template("email_change.html").await {
Ok(a) => a.replace("${{CHANGE_URL}}", &link),
Err(e) => {
error!("Error loading template\n{e}");
return Ok(Response::new_error(500, "Internal Server Error".into()).into());
}
};
let message = match build_mail(&mail, "E-Mail Änderung", ContentType::TEXT_HTML, template) {
Ok(a) => a,
Err(e) => {
error!("Error building message\n{e}");
return Ok(Response::new_error(500, "Internal Server Error".into()).into());
}
};
if let Err(e) = send_mail(mailer, message).await {
error!("Error sending mail\n{e}");
return Ok(Response::new_error(500, "Internal Server Error".into()).into());
};
Ok(web::Json(Response::new_success("Sent E-Mail, check your inbox".to_string())))
} |
from queue import PriorityQueue
class Problem:
"""Transportation problem.
Args:
sources (int): Number of sources.
destinations (int): Number of destinations.
costs (list[list[int]]): Costs of transportation from source to destination.
supply (list[int]): Supply of each source.
demand (list[int]): Demand of each destination.
"""
_sources: int
"""Number of sources."""
_destinations: int
"""Number of destinations."""
costs: dict[tuple[int, int], int]
"""Costs of transportation from source to destination."""
supply: tuple[int, ...]
"""Supply of each source."""
demand: tuple[int, ...]
"""Demand of each destination."""
def __init__(
self,
sources: int,
destinations: int,
costs: list[list[int]],
supply: list[int],
demand: list[int],
):
assert sources > 0 and destinations > 0
self._sources = sources
self._destinations = destinations
assert len(costs) == sources
assert all(len(costs[i]) == destinations for i in range(sources))
self.costs = {}
for i in range(sources):
for j in range(destinations):
assert costs[i][j] >= 0
self.costs[i, j] = costs[i][j]
assert len(supply) == sources
assert len(demand) == destinations
assert sum(supply) == sum(demand)
self.supply = tuple(supply)
self.demand = tuple(demand)
def __repr__(self) -> str:
"""Serialize the problem to string.
Returns:
str: Serialized problem.
"""
return f"Problem(sources={self._sources}, destinations={self._destinations}, costs={self.costs}, supply={self.supply}, demand={self.demand})"
@property
def sources(self) -> int:
"""Number of sources."""
return self._sources
@property
def destinations(self) -> int:
"""Number of destinations."""
return self._destinations
def format_transportation_table(self):
table_str = "Initial Transportation Table:\n\n"
table_str += (
"\t"
+ "\t".join(f"Dest{j+1}" for j in range(self._destinations))
+ "\tSupply\n"
)
for i in range(self._sources):
row = "\t".join(str(self.costs[i, j]) for j in range(self._destinations))
table_str += f"Src{i+1}\t{row}\t{self.supply[i]}\n"
table_str += "Demand\t" + "\t".join(str(d) for d in self.demand) + "\n\n"
return table_str
class Approximation:
"""Transportation approximation.
Args:
problem (Problem): Transportation problem.
"""
_problem: Problem
"""Transportation problem reference."""
plan: dict[tuple[int, int], int]
"""Transportation plan."""
supply: list[int]
"""Supply of each source."""
demand: list[int]
"""Demand of each destination."""
def __init__(self, problem: Problem):
self._problem = problem
self.plan = {}
self.supply = list(problem.supply)
self.demand = list(problem.demand)
def __repr__(self) -> str:
"""Serialize the approximation to string.
Returns:
str: Serialized approximation.
"""
return f"Approximation(problem={self._problem}, plan={self.plan}, supply={self.supply}, demand={self.demand})"
@property
def problem(self) -> Problem:
"""Transportation problem."""
return self._problem
@property
def sources(self) -> int:
"""Number of sources."""
return self._problem.sources
@property
def destinations(self) -> int:
"""Number of destinations."""
return self._problem.destinations
@property
def costs(self) -> dict[tuple[int, int], int]:
"""Costs of transportation from source to destination."""
return self._problem.costs
def format_result_table(self, method_name):
table_str = f"Result Transportation Table:\n\n"
table_str += (
"\t"
+ "\t".join(f"Dest{j+1}" for j in range(self._problem.destinations))
+ "\tSupply\n"
)
for i in range(self._problem.sources):
row = "\t".join(
str(self.plan.get((i, j), 0)) for j in range(self._problem.destinations)
)
table_str += f"Src{i+1}\t{row}\t{self._problem.supply[i]}\n"
table_str += "\n"
return table_str
def north_west_corner(problem: Problem) -> Approximation:
"""North-West corner method.
Args:
problem (Problem): Transportation problem.
Returns:
Approximation: Transportation approximation.
"""
approximation = Approximation(problem)
i = 0
j = 0
while i < approximation.sources and j < approximation.destinations:
approximation.plan[i, j] = min(approximation.supply[i], approximation.demand[j])
approximation.supply[i] -= approximation.plan[i, j]
approximation.demand[j] -= approximation.plan[i, j]
if approximation.supply[i] == 0:
i += 1
else:
j += 1
return approximation
def penalty(approximation):
"""Calculate the penalty for each row and column.
Args:
approximation (Approximation): Transportation approximation.
Returns:
tuple[list[int | None], list[int | None]]: Penalty for each row and column.
"""
row_penalty = [0] * approximation.sources
for i in range(approximation.sources):
if approximation.supply[i] == 0:
continue
row = [
approximation.costs[i, j]
for j in range(approximation.destinations)
if (i, j) not in approximation.plan
]
if len(row) >= 2:
sorted_row = sorted(row)
row_penalty[i] = sorted_row[1] - sorted_row[0]
col_penalty = [0] * approximation.destinations
for j in range(approximation.destinations):
if approximation.demand[j] == 0:
continue
col = [
approximation.costs[i, j]
for i in range(approximation.sources)
if (i, j) not in approximation.plan
]
if len(col) >= 2:
sorted_col = sorted(col)
col_penalty[j] = sorted_col[1] - sorted_col[0]
return row_penalty, col_penalty
def vogel(problem: Problem) -> Approximation:
"""Vogel's approximation method.
Args:
problem (Problem): Transportation problem.
Returns:
Approximation: Transportation approximation.
"""
approximation = Approximation(problem)
while max(approximation.supply) != 0 and max(approximation.demand) != 0:
row_penalty, col_penalty = penalty(approximation)
# print(row_penalty, col_penalty)
max_row_penalty = max(row_penalty)
max_col_penalty = max(col_penalty)
if max_row_penalty >= max_col_penalty:
i = row_penalty.index(max_row_penalty)
min_cost = min(
(
(approximation.costs[i, j], (i, j))
for j in range(approximation.destinations)
if (i, j) not in approximation.plan
),
key=lambda x: x[0],
)
j = min_cost[1][1]
else:
j = col_penalty.index(max_col_penalty)
min_cost = min(
(
(approximation.costs[i, j], (i, j))
for i in range(approximation.sources)
if (i, j) not in approximation.plan
),
key=lambda x: x[0],
)
i = min_cost[1][0]
approximation.plan[i, j] = min(approximation.supply[i], approximation.demand[j])
approximation.supply[i] -= approximation.plan[i, j]
approximation.demand[j] -= approximation.plan[i, j]
return approximation
def russell(problem: Problem) -> Approximation:
"""Russell's approximation method.
Args:
problem (Problem): Transportation problem.
Returns:
Approximation: Transportation approximation.
"""
approximation = Approximation(problem)
row_max = [0] * approximation.sources
col_max = [0] * approximation.destinations
for i in range(approximation.sources):
for j in range(approximation.destinations):
if approximation.costs[i, j] > row_max[i]:
row_max[i] = approximation.costs[i, j]
if approximation.costs[i, j] > col_max[j]:
col_max[j] = approximation.costs[i, j]
queue = PriorityQueue()
for i in range(approximation.sources):
for j in range(approximation.destinations):
queue.put((approximation.costs[i, j] - row_max[i] - col_max[j], (i, j)))
while not queue.empty():
_, (i, j) = queue.get()
approximation.plan[i, j] = min(approximation.supply[i], approximation.demand[j])
approximation.supply[i] -= approximation.plan[i, j]
approximation.demand[j] -= approximation.plan[i, j]
return approximation
def calculate_total_cost(plan, costs):
total_cost = 0
for (i, j), transported_quantity in plan.items():
total_cost += transported_quantity * costs[i, j]
return total_cost |
my_set = set()
my_other_set = {}
print(type(my_set))
print(type(my_other_set))
my_other_set = {"Lua", "Cuello", 23}
print(type(my_other_set))
my_other_set.add("Luana")
print(my_other_set)
print("Luana" in my_other_set)
print("Luani" in my_other_set)
my_other_set.clear()
print(len(my_other_set))
my_set = {"Lua", "Cuello", 23}
my_list = list(my_set)
print(my_list)
print(my_list[0])
"""
los sets son un tipo de dato como las listas y tuplas, nos sirven para almacenar datos, y al igual que estas tiene funciones propias de python para interactuar con los sets.
como sabemos python es un lenguaje de alto nivel, y no es de tipado fuerte, por lo que como podemos ver podemos definir una variable de un tipo y al ponerle datos se torne a otro tipo como en el caso de my_other_set.
Los sets no son de estructura ordenada, por lo que no podemos acceder a sus elementos por medio de un indice, es como si metieramos cosas dentro de una bolsa. Los sets tampoco admiten duplicados.
Para comprobar si un elemento forma parte de un set lo podemos hacer con print y con la funcion in preguntamos si dicho elemento se encuentra en el set, y nos lo dira con un booleano, para acceder a sus elementos, como no podemos hacerlo por su indice, lo hacemos colocando el dato directamente.
Con la funcion de Clear() podemos vaciar el set dejandolo vacio.
Si quisieramos hacer determinadas funcionalidades con los sets y por su comportamiento no pudieramos lo podriamos convertir en una lista y por ejemplo, ahi podriamos obtener una estructura ordenada y acceder a los elementos por su indice. Y asi con los demas tipo de variable que sirve para almacenar datos.
""" |
Basic Input Output System (BIOS)
- older version
- only supports 32-bit processors and motherboards
- program that a CPU uses to start the computer system after being turned on
- method for configuring the motherboard using a text-based interface
- stored as firmware on the motherboard
- Power-on self-test
- test an initialize the:
- processor
- video card
- disk drives
- adapters
- hardware configuration
- boot order setup
- stored in read-only memory (ROM)
- type of chip embedded in the motherboard and can be upgraded through flashing
- settings are stored saved in the CMOS (Complementary Metal-Oxide Semiconductor)
- battery powered memory chip
- non-volatile memory
- store BIOS settings
- built into motherboard
- as long as the battery has power, the settings will be maintained
- only supports Master Boot Record (MBR)
- storage device partition table
Unified Extensible Firmware Interface (UEFI)
- supports 64-bit processors
- provides a GUI
- stored as firmware on the motherboard
- supports larger HDDs and SSDs
- (9.4 zettabytes ~ 9.4 * 10^21 bytes)
- supports the new GUID Partition Table (GPT) format
- faster boot-up
- uses a larger ROM size
Boot Options
------------
boot process:
1. Power-On Self-Test (POST)
- diagnostic testing sequence to check the computer's basic input/output system
- check's computer's:
- keyboard
- RAM
- disk drives
- storage devices
- and other hardware
- if everything is detected and operating properly, the computer can begin to boot up
- if hardware is not detected or not operating properly, the BIOS will issue an error message
- since the post runs before the video card is activated, it may not be possible to display everything to the screen. So, variable beeps are used to tell what's wrong
2. BIOS reads settings from the CMOS and the BIOS will look for an operating system from the configured boot devices
- the BIOS has a low-level OS which allows it to take input and give output to the basic components including the:
- keyboard
- disk drives
- video display
- turns control over to operating system
For safety, corporate environments will have booting from an optical drive or USB drive disabled, because if someone has physical access to your machine, they could boot into a different OS and access your system without needing to know your particular OS's login credentials.
To upgrade the BIOS and UEFI, you perform flashing.
- performed during upgrades, security fixes, or feature improvements
BIOS/UEFI Security
------------------
- Supervisor/Administrator/Setup Password
- used to protect access to the BIOS or UEFI configuration program and prevents access from unauthorized users
- does not prevent booting to the OS
- User/System Password
- used to lock access to the computer
- Storage/Hard Drive Password
- password that locks access to a hard drive connected to the system and requires the end user's password
- Secure Boot
- enabled in the UEFI interface and settings and is not supported by BIOS
- performs three checks
- has to be enabled inside UEFI
- OS has to support it
- setting up permissions for the USB ports on the motherboard
- most modern systems can be configured to enable or disable the USB ports on the motherboard
TPM and HSM
-----------
Hardware Root of Trust (RoT) is the foundation of all secure operations of a computing system.
- cryptographic module embedded in a computer system that endorses trusted execution and attests to boot settings and metrics
- used to scan the boot metrics in the OS files to verify signatures and then use them to sign the report
- contains keys used for cryptographic functions
- enables the secure boot process
- it is inherently trusted and so it must be secure by design
- TPM is a hardware RoT
Trusted Platform Module (TPM)
- most common hardware RoT
- specification for hardware-based storage of digital certificates, keys, hashed passwords, and other user and platform identification information
- hardcoded with unique and unchageable key that's called the endorsement key (EK)
- ensures the system have not been tampered with:
- firmware
- boot loader
- OS kernel
Hardware Security Module (HSM)
- appliance for generating and storing cryptographic keys that is less susceptible to tampering and insider threats
BIOS/UEFI Cooling Options
-------------------------
BIOS and UEFI have the ability to configure fans.
Configuring the BIOS
--------------------
Configuring the UEFI
-------------------- |
#ifndef __THREAD_THREAD_H
#define __THREAD_THREAD_H
#include "stdint.h"
#include "kernel/list.h"
#include "memory.h"
#include "kernel/bitmap.h"
#define TASK_NAME_LEN 16
#define MAX_FILES_OPEN_PER_PROC 8
/* 用来指定在线程中运行的函数类型 */
typedef void thread_func(void*);
typedef int16_t pid_t;
/* 进程或线程的状态, 区别在于是否拥有页表 */
enum task_status {
TASK_RUNNING,
TASK_READY,
TASK_BLOCKED,
TASK_WAITING,
TASK_HANGING,
TASK_DIED
};
/* 中断栈 intr_stack
此结构用于中断发生时保护程序(线程或进程)的上下文环境:
进程或线程被外部中断或软中断打断时,会按照此结构压入上下文
寄存器, intr_exit 中的出栈操作是此结构的逆操作
此栈在线程自己的内核栈中位置固定,所在页的最顶端
*/
struct intr_stack {
uint32_t vec_no; // kernel.S 宏 VECTOR 中 push %1 压入的中断号
uint32_t edi;
uint32_t esi;
uint32_t ebp;
uint32_t esp_dummy; // 虽然 pushad 把 esp 也压入,但 esp 是不断变化的,所以会被 popad 忽略
uint32_t ebx;
uint32_t edx;
uint32_t ecx;
uint32_t eax;
uint32_t gs;
uint32_t fs;
uint32_t es;
uint32_t ds;
// 以下由 cpu 从低特权级进入高特权级时压入
uint32_t err_code; // err_code 会被压入在 eip 之后
void (*eip) (void);
uint32_t cs;
uint32_t eflags;
void* esp;
uint32_t ss;
};
/* 线程栈 thread_stack
线程自己的栈,用于存储线程中待执行的函数
此结构在线程自己的内核栈中位置不固定,
仅用在 switch_to 时保存线程环境。
实际位置取决于实际运行情况。
*/
struct thread_stack {
uint32_t ebp;
uint32_t ebx;
uint32_t edi;
uint32_t esi;
/* 线程第一次执行时, eip 指向待调用的函数 kernel_thread
其他时候, eip 是指向 switch_to 的返回地址 */
void (*eip) (thread_func* func, void* func_arg);
/* 以下仅供第一次被调度上 cpu 时使用 */
void (*unused_retaddr); // 占位
thread_func* function; // 由 kernel_thread 所调用的函数名
void* func_arg; // 由 kernel_thread 所调用的函数所需的参数
};
/* 进程或线程的 pcb ,程序控制块 */
struct task_struct {
uint32_t* self_kstack; // 各内核线程都用自己的内核栈
pid_t pid;
enum task_status status;
char name[TASK_NAME_LEN];
uint8_t priority; // 线程优先级
uint8_t ticks; // 每次在处理器上执行的时间嘀嗒数
// 每次时钟中断都会将当前任务的 ticks 减 1 ,当减到 0 时就被换下处理器。
uint32_t elapsed_ticks; // 此任务自上 cpu 运行后至今占用了多少 cpu 嘀嗒数
int32_t fd_table[MAX_FILES_OPEN_PER_PROC]; // 文件描述符数组
struct list_elem general_tag; // 用于线程在一般的队列中的结点
struct list_elem all_list_tag; // 用于线程队列 thread_all_list 中的结点
uint32_t* pgdir; // 进程自己页表的虚拟地址(往寄存器 cr3 中加载页目录地址时,会将pgdir转换成物理地址)
struct virtual_addr userprog_vaddr; // 用户进程的虚拟地址池
struct mem_block_desc u_block_desc[DESC_CNT]; // 用户进程内存块描述符
uint32_t cwd_inode_nr; // 进程所在的工作目录的 inode 编号
int16_t parent_pid; // 父进程id
int8_t exit_status; // 进程结束时自己调用 exit 传入的参数
uint32_t stack_magic; // 栈的边界标记,用于检测栈的溢出
};
extern struct list thread_ready_list;
extern struct list thread_all_list;
void thread_create(struct task_struct* pthread, thread_func function, void* func_arg);
void init_thread(struct task_struct* pthread, char* name, int prio);
struct task_struct* thread_start(char* name, int prio, thread_func function, void* func_arg);
struct task_struct* running_thread(void);
void schedule(void);
void thread_init(void);
void thread_block(enum task_status stat);
void thread_unblock(struct task_struct* pthread);
void thread_yield(void);
pid_t fork_pid(void);
void sys_ps(void);
#endif |
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, only: [:new, :edit, :destroy]
def index
@items = Item.order(created_at: :desc)
end
def new
@item = Item.new
end
def create
@item = Item.new(item_params)
if @item.save
redirect_to root_path
else
render :new
end
end
def show
end
def edit
if @item.user_id != current_user.id || @item.sold_out?
redirect_to root_path
return
end
return if @item.present?
redirect_to root_path
end
def update
if @item.update(item_params)
redirect_to item_path(@item)
else
render action: :edit
end
end
def destroy
if @item.user_id == current_user.id
@item.destroy
end
redirect_to root_path
end
private
def item_params
params.require(:item).permit(:product_name, :description, :genre_id, :item_condition_id, :shipping_fee_payer_id, :shipping_area_id,
:shipping_day_id, :price, :image).merge(user_id: current_user.id,sold_out: 1)
end
def set_item
@item = Item.find(params[:id])
end
end |
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from places.models import PlaceName
def serialize_post(location):
redirect_url = reverse('get_details_json', args=[location.pk])
return {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [location.longitude, location.latitude]
},
"properties": {
"title": location.title,
"detailsUrl": redirect_url
}
}
def index(request):
locations = PlaceName.objects.all()
context = {
'places_posts': {"type": "FeatureCollection",
"features": [
serialize_post(location) for location in locations
]}
}
return render(request, 'places/index.html', context)
def get_details_json(request, pk):
location = get_object_or_404(PlaceName, pk=pk)
location_information = {
"title": location.title,
"imgs": [
pic.picture.url for pic in location.pictures.all().order_by('sequence_number')
],
"description_short": location.short_description,
"description_long": location.long_description,
"coordinates": {
"lng": location.longitude,
"lat": location.latitude
}
}
return JsonResponse(location_information, safe=False, json_dumps_params={'ensure_ascii': False, 'indent': 4}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.