text stringlengths 184 4.48M |
|---|
---
description: "Bagaimana Menyiapkan Soto ayam + tulang, Sempurna"
title: "Bagaimana Menyiapkan Soto ayam + tulang, Sempurna"
slug: 1355-bagaimana-menyiapkan-soto-ayam-tulang-sempurna
date: 2020-09-11T10:40:43.323Z
image: https://img-global.cpcdn.com/recipes/3da694ec3e2537e2/751x532cq70/soto-ayam-tulang-foto-resep-utama.jpg
thumbnail: https://img-global.cpcdn.com/recipes/3da694ec3e2537e2/751x532cq70/soto-ayam-tulang-foto-resep-utama.jpg
cover: https://img-global.cpcdn.com/recipes/3da694ec3e2537e2/751x532cq70/soto-ayam-tulang-foto-resep-utama.jpg
author: Elmer Washington
ratingvalue: 4.3
reviewcount: 14
recipeingredient:
- " dada ayam"
- " tulang ayam"
- " jeruk nipis"
- " bahan merebus ayam "
- "3 siung bawang putih cincang"
- "1 sdm garam"
- "1 sdt lada"
- " bahan bumbu "
- "7 buah kemiri"
- "6 siung bawang merah"
- "7 siung bawang putih"
- "2 ruas jari kunyit"
- "1 ruas jari jahe"
- " daun jeruk"
- " daun salam"
- " lengkoas geprek"
- " sereh"
- " garam"
- " penyedap"
- " gula"
- " bahan pelengkap "
- "4 bungkus soun"
- " tauge"
- " kol"
- " daun bawang seledri"
- " jeruk nipis"
- " kerupuk"
- " sambal"
- " bahan sambal "
- "6 buah cabe merah"
- "15 buah cabe rawit merah"
- "5 buah bawang putih"
- " garam"
recipeinstructions:
- "Cuci ayam dan tulang, beri perasan jeruk nipis diamkan 15 menit cuci kembali.... kemudian rebus ayam dan tulang kemudian tambahkan bawang putih cincang garam dan lada.. setelah matang angkat daging ayam nya saja kemudia goreng.. air kaldu jangan dibuang"
- "Iris kol kemudian rebus bersama dengan tauge (sebentar saja hanya utk buat layu sedikit) setelah itu rebus bihun"
- "Haluskan bumbu bawang putih bawang merah kunyit kemiri dan jahe.. daun jeruk salam sereh dan lengkoas hanya digeprek.. tumis sampai matang dan harum setelah matang tuang ke air kaldu tambahkan garam gula penyedap dan lada.. koreksi rasa"
- "Cara membuat sambal :"
- "Rebus cabai dan bawang dengan setengah gelas air biarkan matang uleg sampai halus tambahkan sedikit garam"
- "Hidangkan semuanya dalam 1 mangkok.. pakai nasi hangat lebih mantap"
categories:
- Resep
tags:
- soto
- ayam
-
katakunci: soto ayam
nutrition: 100 calories
recipecuisine: Indonesian
preptime: "PT27M"
cooktime: "PT37M"
recipeyield: "1"
recipecategory: Dessert
---

<b><i>soto ayam + tulang</i></b>, Memasak merupakan sebuah kegiatan yang menyenangkan dilakukan oleh banyak kelompok. tidaklah hanya para perempuan, sebagian cowok juga cukup banyak yang senang dengan kegemaran ini. walau hanya untuk sekedar kebersamaan dengan rekan atau memang sudah menjadi kesukaan dalam dirinya. tidak asing lagi dalam dunia restoran sekarang sedikit banyak ditemukan cowok dengan keahlian memasak yang sempurna, dan banyak sekali juga kita melihat di berbagai kedai dan restoran yang mempunyai chef pria sebagai koki andalan nya.
Oke, kita awali ke perihal resep makanan <i>soto ayam + tulang</i>. di tengah tengah kegiatan kita, mungkin akan terasa membahagiakan apabila sejenak anda menyempatkan sedikit waktu untuk memasak soto ayam + tulang ini. dengan keberhasilan kita dalam mengolah olahan tersebut, bisa menjadikan diri kita bangga oleh hasil menu kalian sendiri. dan lagi disini melalui situs ini kita akan mendapatkan saran saran untuk membuat hidangan <u>soto ayam + tulang</u> tersebut menjadi hidangan yang yummy dan menggugah selera, oleh karena itu simpan alamat situs ini di hp anda sebagai salah satu referensi kalian dalam membuat masakan baru yang endes.
Soto Ayam - Soto ayam adalah salah satu masakan berkuah khas Indonesia yang cukup populer dan sangat diminati oleh masyarakat. Lihat juga resep Soto Ayam Super Kilat enak lainnya. Ada Soto Lamongan, Soto Betawi, Soto Bogor, Soto Jawa Timur Kalau tidak ada daging sapi, soto ayam nggak kalah lezatnya.
Sekarang langsung saja kita awali untuk menyediakan bahan baku yang dibutuhkan dalam mengolah masakan <u><i>soto ayam + tulang</i></u> ini. seenggaknya harus ada <b>33</b> bahan bahan yang dibutuhkan untuk masakan ini. agar nantinya dapat tercapai rasa yang yummy dan menggugah selera. dan juga siapkan waktu kita sesaat, sebab kalian akan mengolahnya paling tidak dengan <b>6</b> langkah. saya harap berbagai hal yang dibutuhkan sudah anda sediakan disini, Baiklah mari kita proses dengan mengamati dulu bahan perlengkapan dibawah ini.
<!--inarticleads1-->
##### Bahan-bahan dan bumbu yang diperlukan untuk menyiapkan Soto ayam + tulang:
1. Ambil dada ayam
1. Sediakan tulang ayam
1. Ambil jeruk nipis
1. Gunakan bahan merebus ayam :
1. Siapkan 3 siung bawang putih cincang
1. Sediakan 1 sdm garam
1. Ambil 1 sdt lada
1. Gunakan bahan bumbu :
1. Gunakan 7 buah kemiri
1. Gunakan 6 siung bawang merah
1. Gunakan 7 siung bawang putih
1. Sediakan 2 ruas jari kunyit
1. Sediakan 1 ruas jari jahe
1. Sediakan daun jeruk
1. Siapkan daun salam
1. Ambil lengkoas geprek
1. Sediakan sereh
1. Siapkan garam
1. Siapkan penyedap
1. Sediakan gula
1. Sediakan bahan pelengkap :
1. Siapkan 4 bungkus soun
1. Siapkan tauge
1. Siapkan kol
1. Sediakan daun bawang seledri
1. Sediakan jeruk nipis
1. Siapkan kerupuk
1. Gunakan sambal
1. Ambil bahan sambal :
1. Sediakan 6 buah cabe merah
1. Gunakan 15 buah cabe rawit merah
1. Gunakan 5 buah bawang putih
1. Ambil garam
Resep Soto Ayam Kampung, Satu yang Selalu Mengundang Selera. Simpan ke bagian favorit Tersimpan di bagian favorit. Soto ayam yang satu ini, sudah populer di berbagai penjuru Indonesia. Berasal dari satu kota di Kali ini Endeus mencoba membuat resep soto ayam lamongan yang simpel dan bisa kamu coba sendiri.
<!--inarticleads2-->
##### Cara membuat Soto ayam + tulang:
1. Cuci ayam dan tulang, beri perasan jeruk nipis diamkan 15 menit cuci kembali.... kemudian rebus ayam dan tulang kemudian tambahkan bawang putih cincang garam dan lada.. setelah matang angkat daging ayam nya saja kemudia goreng.. air kaldu jangan dibuang
1. Iris kol kemudian rebus bersama dengan tauge (sebentar saja hanya utk buat layu sedikit) setelah itu rebus bihun
1. Haluskan bumbu bawang putih bawang merah kunyit kemiri dan jahe.. daun jeruk salam sereh dan lengkoas hanya digeprek.. tumis sampai matang dan harum setelah matang tuang ke air kaldu tambahkan garam gula penyedap dan lada.. koreksi rasa
1. Cara membuat sambal :
1. Rebus cabai dan bawang dengan setengah gelas air biarkan matang uleg sampai halus tambahkan sedikit garam
1. Hidangkan semuanya dalam 1 mangkok.. pakai nasi hangat lebih mantap
Cara memasak soto ayam lamongan hampir mirip dengan resep soto ayam pada umumnya. Yang membedakan antara soto ayam biasa dengan soto ayam lamongan adalah tambahan serbuk krupuk. Resep soto ayam dan cara membuatnya dengan mudah, kamu bisa lakukan sendiri di rumah dan rasanya lezat asal kamu ikuti langkahnya dengan baik Soto ayam di Indonesia punya banyak jenis. Khasiat.co.id - Soto ayam merupakan salah satu makanan berkuah dengan kaldu yang gurih, suwiran ayam, potongan telur rebus,serta gumpalan soun memang sungguh nikmat di santap kapan saja. Penjual soto ayam memang sudah menjamur.
Demikianlah sedikit ulasan masakan perihal resep resep <u>soto ayam + tulang</u> yang lezat. kita ingin kalian bisa memahami dengan penjabaran diatas, dan anda dapat membuat ulang di masa datang untuk di sajikan dalam bermacam kegiatan family atau kolega kalian. kalian bisa menambahkan bumbu bumbu yang ada diatas sesuai dengan keinginan anda, sehingga menu <b>soto ayam + tulang</b> ini dapat menjadi lebih yummy dan menggugah selera lagi. demikian penjabaran singkat ini, sampai berjumpa kembali di lain hal. kami harap hari kamu menyenangkan. |
package com.nikpanfilov.superfit.main.data.storage
import android.content.Context
import android.content.SharedPreferences
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
import com.nikpanfilov.network.token.data.storage.SharedPrefsDataStorage
class SignOutDataStorageImpl(private val context: Context) : SignOutDataStorage {
companion object {
const val SHARED_PREFERENCES_FILENAME = "myPrefs"
const val NAME = "name"
const val ACCESS_TOKEN = "access_token"
const val REFRESH_TOKEN = "refresh_token"
}
private val encryptedSharedPreferences = EncryptedSharedPreferences.create(
SHARED_PREFERENCES_FILENAME,
MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
private val sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILENAME, Context.MODE_PRIVATE)
override fun signOut() {
deleteName()
deleteTokens()
}
private fun deleteName() {
val e: SharedPreferences.Editor = encryptedSharedPreferences.edit()
e.putString(NAME, null)
e.apply()
}
private fun deleteTokens() {
val e: SharedPreferences.Editor = sharedPreferences.edit()
e.putString(SharedPrefsDataStorage.ACCESS_TOKEN, null)
e.putString(SharedPrefsDataStorage.REFRESH_TOKEN, null)
e.apply()
}
} |
# 2597. The Number of Beautiful Subsets 🟡
You are given an array `nums` of positive integers and a positive integer `k`.
A subset of `nums` is beautiful if it does not contain two integers with an absolute difference equal to `k`.
Return the number of non-empty beautiful subsets of the array `nums`.
A subset of `nums` is an array that can be obtained by deleting some (possibly none) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
### Commentary
- It's slow but it works. I'll probably come back to see how the faster solutions work
```cpp
class Solution {
public:
void dive(std::vector<int>& nums, int& k, int start, std::unordered_map<int, int>& found, int& count)
{
if(start >= nums.size())
{
count++;
return;
}
if(!found[nums.at(start) - k] && !found[nums.at(start) + k]) // dont need found[nums.at(start) + k] if input array is sorted in beautifulSUbsets
{
found[nums.at(start)]++;
dive(nums, k, start + 1, found, count);
found[nums.at(start)]--;
}
dive(nums, k, start + 1, found, count);
return;
}
int beautifulSubsets(vector<int>& nums, int k) {
// use a map bs a set will potentially remove duplicates
// ex [2,2,4] will remove 2 from the set after 1 recursion, leaving the second 2 in without checking
std::unordered_map<int, int> found{};
//std::sort(nums.begin(), nums.end());
int count{ 0 };
dive(nums, k, 0, found, count);
return count - 1;
}
};
``` |
<template>
<nav class="">
<div class="row gx-0">
<div class="col-md-6">
<h1
:key="index"
v-for="(name, index) in customTestName[0]"
class="test-name"
>
{{ name }}
</h1>
</div>
<div class="col-md-6 text-center">
<div class="quiz-info">
<span @click="goHome" type="button" class="home btn"
>Return Home</span
>
<span class="questions-left">
{{ currentQuestion + 1 }} / {{ questions.length }}</span
>
</div>
</div>
</div>
</nav>
<div>
<div
v-if="showScore"
class="scoreboard text-center elevation-4 col-md-4 mx-auto"
>
<div><h3>Test Completed!</h3></div>
<div class="text-muted">You scored:</div>
<div class="percentage mt-3">
<p class="score">{{ percentage }}%</p>
</div>
<div class="home-btn">
<button @click="goHome" class="btn text-danger">Return Home</button>
</div>
</div>
<div v-else class="row gx-0">
<form id="form" action="" @submit.prevent="submit(answer)">
<div class="test-card rounded col-md-8 mx-auto elevation-5">
<div class="question-name">
<span> {{ currentQuestion + 1 }}. </span>
<span>
{{ questions[currentQuestion].questionText }}
</span>
</div>
<div class="d-flex"></div>
<div
class="d-flex justify-content-between questions"
:key="index"
v-for="(option, index) in questions[currentQuestion].answerOptions"
>
<label v-bind:value="option.answerText">
{{ option.letter }}. {{ option.answerText }}
</label>
<input
v-bind:id="option.answerText"
:value="option.isCorrect"
type="radio"
v-model="answer"
name="testing"
/>
</div>
</div>
<div v-if="showError" class="col-md-8 mx-auto">
<div class="rounded-pill error text-center mt-4">
<p class="text-white">Please select an answer</p>
</div>
</div>
<div class="col-md-8 mx-auto text-end mt-5 mb-5">
<button title="Submit" class="btn bg-danger submit-btn">
submit
</button>
</div>
</form>
</div>
</div>
</template>
<script>
import { AppState } from "../AppState";
import { computed, onMounted, ref } from "@vue/runtime-core";
import { useRouter } from "vue-router";
import Pop from "../utils/Pop";
export default {
data() {
const route = useRouter();
return {
answer: {},
currentQuestion: 0,
showScore: false,
showError: false,
score: 0,
percentage: "",
questions: computed(() => AppState.customTest),
testName: computed(() => AppState.testNames),
goHome() {
route.push({ name: "Home" });
},
customTestName: computed(() => AppState.customTestName),
};
},
methods: {
submit(answer) {
console.log(answer);
let nextQuestion = this.currentQuestion + 1;
if (answer != "true" && answer != "") {
Pop.toast("Please Select an Answer");
this.showError = true;
return;
}
if (answer == "true") {
this.score = this.score + 1;
console.log("correct!");
console.log(answer);
}
if (nextQuestion < this.questions.length) {
this.answer = {};
this.currentQuestion = nextQuestion;
this.showError = false;
console.log(this.currentQuestion);
} else {
let totalQuestions = AppState.customTest.length;
let newScore = (this.score / totalQuestions) * 100;
this.percentage = newScore.toFixed(0);
this.showScore = true;
}
},
},
};
</script>
<style scoped>
.home-btn {
color: red;
font-weight: bolder;
padding-top: 1.5rem;
}
.score {
margin-top: 4rem;
font-size: 40px;
}
.error {
background-color: rgb(75, 75, 75);
padding: 0.5rem;
}
.percentage {
display: inline-block;
width: 200px;
height: 200px;
background-color: black;
border-radius: 50%;
text-align: center;
color: white;
}
.scoreboard {
margin-top: 4rem;
background-color: white;
padding: 3rem;
}
.submit-btn {
background-color: red;
padding-left: 2rem;
padding-right: 2rem;
}
.question-name {
padding-bottom: 1rem;
border-bottom: 2px solid red;
color: red;
font-size: 20px;
font-weight: bolder;
}
.questions {
padding-top: 2rem;
padding-bottom: 2rem;
}
.test-card {
margin-top: 4rem;
background-color: white;
padding: 3rem;
padding-right: 4rem;
padding-left: 4rem;
}
.test-name {
padding: 1.2rem;
text-align: center;
color: white;
}
.questions-left {
padding: 0.7rem;
padding-right: 2rem;
padding-left: 2rem;
border-radius: 16px;
color: white;
background-color: black;
}
.home {
margin-right: 6rem;
font-size: 18px;
}
nav {
background: rgba(232, 27, 27, 0.953);
height: 10vh;
}
.quiz-info {
padding-top: 1.8rem;
color: white;
}
@media (max-width: 786px) {
.quiz-info {
padding-top: 0;
}
nav {
height: 14vh;
}
.test-name {
padding: 0.7rem;
}
}
</style> |
import styled, { css } from "styled-components";
interface DesktopProps {
$dropdown: boolean;
}
export const StyledNavDesktop = styled.nav<DesktopProps>`
${({ theme, $dropdown }) => css`
padding: 1.6rem 2.4rem;
display: flex;
justify-content: space-between;
align-items: center;
.navbar-desktop-item-1 {
flex: 1 1 auto;
display: flex;
align-items: center;
justify-content: flex-start;
}
.navbar-desktop-item-2 {
flex: 1 1 auto;
display: flex;
align-items: center;
justify-content: flex-end;
gap: 2.4rem;
}
.menu-desktop {
display: flex;
justify-content: flex-start;
align-items: center;
.menu-item {
margin-left: ${theme.spacing.gap_1};
position: relative;
}
}
.nav-link-desktop {
display: inline-block;
padding: 1.2rem 1.6rem;
position: relative;
&::after {
content: "";
position: absolute;
top: 42%;
right: -0.3rem;
width: 0.7rem;
height: 0.7rem;
border-radius: 0.1rem;
border-bottom: 0.2rem solid ${theme.colors.blue_main.primary_normal};
border-right: 0.2rem solid ${theme.colors.blue_main.primary_normal};
transform: rotate(45deg);
transition: 0.2s linear;
}
&:hover {
&::after {
top: 45%;
}
}
}
.dropdown-menu {
background: ${theme.colors.white_auxiliary.white_light};
padding: 1.6rem 2.4rem;
border-radius: 1.6rem;
box-shadow: 0px 51px 80px rgba(27, 108, 231, 0.08),
0px 15px 24px rgba(27, 108, 231, 0.05),
0px 6px 10px rgba(27, 108, 231, 0.04),
0px 2.3px 3.6px rgba(27, 108, 231, 0.02);
position: absolute;
top: 4.6rem;
left: 2.4rem;
display: flex;
justify-content: flex-start;
flex-direction: column;
align-items: center;
transition: .5s ease;
opacity: 0;
pointer-events: none;
&.active-dropdown {
pointer-events: all;
opacity: 1;
}
.dropdown-item {
min-width: 100%;
white-space: nowrap;
}
}
.nav-link-dropdown {
display: inline-block;
width: 100%;
padding: 0.8rem 1.6rem;
position: relative;
&::after {
content: "";
position: absolute;
top: 90%;
left: 0;
width: 0%;
height: 0.2rem;
background-color: ${theme.colors.blue_main.secondary_normal};
transition: 0.5s ease;
}
&:hover {
&::after {
width: 100%;
}
}
}
`}
`; |
import type { CartEndpoint } from '.'
import type { RawVariantSpec } from '../../../types/product'
import { formatCart } from '../../utils/cart'
import { serialize } from 'cookie'
const addItem: CartEndpoint['handlers']['addItem'] = async ({
req,
body: { cartId, item },
config: { restBuyerFetch, cartCookie, tokenCookie },
}) => {
// Get token
let token = req.cookies.get(tokenCookie)?.value
let headers: any = {}
// Create an order if it doesn't exist
if (!cartId) {
const { ID, meta } = await restBuyerFetch(
'POST',
`/orders/Outgoing`,
{},
{ token }
)
cartId = ID
headers = {
'set-cookie': [
serialize(cartCookie, cartId!, {
maxAge: 60 * 60 * 24 * 30,
expires: new Date(Date.now() + 60 * 60 * 24 * 30 * 1000),
secure: process.env.NODE_ENV === 'production',
path: '/',
sameSite: 'lax',
}),
],
}
if (meta?.token) {
headers['set-cookie'].push(
serialize(tokenCookie, meta.token?.access_token, {
maxAge: meta.token.expires_in,
expires: new Date(Date.now() + meta.token.expires_in * 1000),
secure: process.env.NODE_ENV === 'production',
path: '/',
sameSite: 'lax',
})
)
}
}
let specs: RawVariantSpec[] = []
// If a variant is present, fetch its specs
if (item.variantId !== 'undefined') {
const { Specs } = await restBuyerFetch(
'GET',
`/me/products/${item.productId}/variants/${item.variantId}`,
null,
{ token }
)
specs = Specs
}
// Add the item to the order
await restBuyerFetch(
'POST',
`/orders/Outgoing/${cartId}/lineitems`,
{
ProductID: item.productId,
Quantity: item.quantity,
Specs: specs,
},
{ token }
)
// Get cart & line items
const [cart, { Items }] = await Promise.all([
restBuyerFetch('GET', `/orders/Outgoing/${cartId}`, null, { token }),
restBuyerFetch('GET', `/orders/Outgoing/${cartId}/lineitems`, null, {
token,
}),
])
// Format cart
const formattedCart = formatCart(cart, Items)
// Return cart and headers
return { data: formattedCart, headers }
}
export default addItem |
/*
* Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
*
* 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.
*/
#pragma once
#include <memory>
namespace clara::viz
{
class MessageReceiver;
/**
* Renderer.
* Receives messages from the interfaces, renders images and pass them to the video message
* receiver.
*/
class Renderer
{
public:
/**
* Construct
*
* @param video_msg_receiver [in] video message receiver
* @param cuda_device_ordinal [in] Cuda device to render on
* @param mhd_file_name [in] Name of MHD file to load
*/
explicit Renderer(const std::shared_ptr<MessageReceiver> &video_msg_receiver, uint32_t cuda_device_ordinal,
const std::string &mhd_file_name);
Renderer() = delete;
/**
* Destruct.
*/
~Renderer();
/**
* Run the renderer.
*/
void Run();
/**
* Shutdown the renderer, wait for all running tasks to finish.
*/
void Shutdown();
/**
* @returns the message receiver of the renderer
*/
std::shared_ptr<MessageReceiver> GetReceiver() const;
private:
struct Impl;
std::shared_ptr<Impl> impl_;
};
} // namespace clara::viz |
//
// GeneralInputPage.swift
// Tourify
//
// Created by 顾悦平 on 11/7/23.
//
import Foundation
import UIKit
class GeneralInputPage: UIViewController,UITextFieldDelegate{
let currentDate = Date()
@IBOutlet weak var startDate: UIDatePicker!
@IBOutlet weak var endDate: UIDatePicker!
@IBOutlet weak var departure: UITextField!
@IBOutlet weak var destination: UITextField!
@IBOutlet weak var numTravelers: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
startDate.minimumDate = currentDate
endDate.minimumDate = currentDate
departure.delegate = self
destination.delegate = self
numTravelers.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Get the current text in the text field
guard let currentText = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) else {
print("now")
return true
}
guard !currentText.isEmpty else {
return true
}
// Call the checkPlaceInput function based on the text field
if textField == departure {
if checkPlaceInput(input: currentText){
print("Valid Place of Departure.")
}
else{
departure.text = ""
let title = "Invalid Departure Place Input."
let message = "Please enter a valid city of departure."
let alert = generateAlert(t: title, msg: message)
self.present(alert, animated: true, completion: nil)
}
}
else if textField == destination {
if checkPlaceInput(input: currentText){
print("Valid Destination.")
}
else{
destination.text = ""
let title = "Invalid Destination Input."
let message = "Please enter a valid city of destination."
let alert = generateAlert(t: title, msg: message)
self.present(alert, animated: true, completion: nil)
}
}
else if textField == numTravelers{
let num: Int? = Int(currentText)
if let num = num{
if num > 0{
print("Valid number of travelers.")
}
else if num == 0{
let title = "Invalid Input."
let message = "Please enter a valid number of travelers."
let alert = generateAlert(t: title, msg: message)
self.present(alert, animated: true, completion: nil)
}
}
else{
let title = "Invalid Input."
let message = "Please enter a number."
let alert = generateAlert(t: title, msg: message)
self.present(alert, animated: true, completion: nil)
}
}
return true
}
func checkPlaceInput(input: String)->Bool{
// need to refine the regex pattern, now it allows continuous input of whitespaces, hyphens, and periods, and the combination of the three.
let pattern = "^[a-zA-Z]{1}[a-zA-Z\\s\\-\\.]*[^\\.s]?$"
let regex = try? NSRegularExpression(pattern: pattern)
let range = NSRange(location: 0, length: input.utf16.count)
return regex?.firstMatch(in: input, options: [], range: range) != nil
}
@IBAction func goToFlight(_ sender: Any) {
//check all inputs are filled(handle at this final confirm step)
if startDate == nil || endDate == nil || departure == nil || destination == nil || numTravelers == nil || departure.text == "" || destination.text == "" || numTravelers.text == ""{
let title = "Incomplete information."
let message = "All fields are required to be filled."
let alert = generateAlert(t: title, msg: message)
self.present(alert, animated: true, completion: nil)
}
else if endDate.date <= startDate.date{
let title = "Invalid Date Inputs."
let message = "Start date should be no later than end date."
let alert = generateAlert(t: title, msg: message)
self.present(alert, animated: true, completion: nil)
}
else if departure.text == destination.text{
let title = "Invalid Place Inputs."
let message = "Place of Departure and Destination should not be the same."
let alert = generateAlert(t: title, msg: message)
self.present(alert, animated: true, completion: nil)
}
else {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let parseStart = dateFormatter.string(from: startDate.date)
let parseEnd = dateFormatter.string(from: endDate.date)
let dep = departure.text?.trimmingCharacters(in: .whitespaces)
let des = destination.text?.trimmingCharacters(in: .whitespaces)
info = GeneralPlan(startDate_: parseStart, endDate_: parseEnd, departure_: dep, destination_: des, numTravelers_: Int(numTravelers.text!))
//check trimming of leading and trailing whitespaces
print(info?.departure_.count ?? 0)
print(info?.departure_ ?? "")
print(info?.destination_ ?? "")
print(info?.startDate_ ?? "")
print(info?.endDate_ ?? "")
print(info?.numTravelers_ ?? 0)
//once the information from this step is all extracted, a new trip is initiated with a name. Remaining attributes will be added later
showTripNameInput()
}
}
@IBAction func discard(_ sender: Any) {
startDate.date = currentDate
endDate.date = currentDate
departure.text = ""
destination.text = ""
numTravelers.text = ""
}
func showTripNameInput() {
let alertController = UIAlertController(title: "Name Your New Trip", message: nil, preferredStyle: .alert)
alertController.addTextField {
textField in
textField.placeholder = "Trip Name"
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) {_ in
print("User clicked Cancel")
print(trips)
// If the user clicks 'cancel' then reset the info.
info = nil
}
let createTripAction = UIAlertAction(title: "Create Trip", style: .default) {_ in
if let tripName = alertController.textFields?.first?.text{
if tripName.isEmpty{
let title = "Failed to create your trip."
let message = "Please provide a name for your trip."
let alert = generateAlert(t: title, msg: message)
self.present(alert, animated: true, completion: nil)
return
}
else{
//inputting a name initiates a new trip, and append this trip to the trip list
let newTrip = Trip(name: tripName)
trips.append(newTrip)
print("New trip created:")
print("Name: \(String(describing: newTrip.name))")
print(trips)
}
} else {
print("Invalid trip name entered.")
}
}
alertController.addAction(cancelAction)
alertController.addAction(createTripAction)
present(alertController, animated: true, completion: nil)
}
} |
import React from 'react';
import { Button, ButtonProps } from '@chakra-ui/react';
import useAnimatedRouter from '@/components/useAnimatedRouter';
interface AnimatedButtonProps extends Omit<ButtonProps, 'onClick'> {
destination: string;
}
// Use React.forwardRef to forward refs to the underlying Button component
const AnimatedButton = React.forwardRef<HTMLButtonElement, AnimatedButtonProps>(
({ destination, children, ...rest }, ref) => {
const router = useAnimatedRouter(); // Using the custom hook
const handleClick = () => {
router.animatedRoute(destination); // Navigate using the custom animated route method
};
// Pass the ref along with other props to the Button component
return (
<Button ref={ref} onClick={handleClick} {...rest}>
{children}
</Button>
);
},
);
AnimatedButton.displayName = 'AnimatedButton';
export default AnimatedButton; |
import React, { useContext } from "react";
// import components
import House from "../components/House";
// import contex
import { HouseContext } from "../components/HouseContext";
// import links
import { Link } from "react-router-dom";
// import icons
import { ImSpinner2 } from "react-icons/im";
const HouseList = () => {
const { houses, loading } = useContext(HouseContext);
// if loading is true
if (loading) {
return (
<ImSpinner2 className="mx-auto animate-spin text-violet-700 text-4xl mt-[200px]" />
);
}
if (houses.length < 1) {
return (
<div className="text-3xl text-center text-gray-400 mt-48">
Sorry , nothing found
</div>
);
}
return (
<section className="mb-20">
<div className="mx-auto container">
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4 lg:gap-14">
{houses.map((house, index) => {
return (
<Link to={`/property/${house.id}`} key={index}>
<House house={house} />
</Link>
);
})}
</div>
</div>
</section>
);
};
export default HouseList; |
# Setting Up Ansible for Linux via WSL 2 on Ubuntu
*********************************************************
*********************************************************
*********************************************************
# Step 1: Update and Install Dependencies
Update package information:
Run **sudo apt update**.
Upgrade packages (optional but recommended):
Run **sudo apt upgrade**.
Install Git:
Run **sudo apt install git**.
Install net-tools (for ifconfig):
Run **sudo apt install net-tools**.
Install Ansible:
Run **sudo apt install ansible**.
# Step 2: Prepare SSH for Remote Connections
Create a directory for Ansible (replace **<directory_name>** with your preferred name):
Run **mkdir <directory_name>**.
Check your IP address:
Run **ifconfig**.
Connect to another device remotely via SSH:
Run **ssh <username>@<remote_ip>**.
List SSH connections:
Run **ls -la ~/.ssh**.
View the content of a file:
Run cat **<filename.filetype>**.
# Step 3: Prepare SSH Key for Automation
Create an SSH key using ed25519 (provide a name and passphrase when prompted):
Run **ssh-keygen -t ed25519 -C " "name"**".
Copy the SSH key to another machine for passwordless authentication:
Run **ssh-copy-id -i ~/.ssh/id_ed25519.pub <username>@<remote_ip>**.
# Step 4: Manage Ansible Inventory and Ping Servers
Create a repository on GitHub and clone it locally for file management.
Create an inventory file and store the IPs of every server:
Run touch inventory.
To view the SSH key's public part:
Run **cat ~/.ssh/id_ed25519.pub**.
Check the ping of every server using Ansible:
Run **ansible all --key-file ~/.ssh/id_ed25519 -i inventory -m ping**.
# Step 5: Manage SSH Agent (Optional)
Add the SSH agent:
Run **eval $(ssh-agent).**
Add your SSH key to the agent (if not added automatically):
Run **ssh-add** |
classdef IntegratorSE < DynamicalSystem
% Integrator system on SE(n), n = 2 or 3.
%
% x: [n + n^2, 1] vector.
% u: [3, 1] vector if n == 2 or [6, 1] vector if n == 3.
% \dot{x} = u \in T_x SE(n).
properties (Access = private)
dim
end
methods
function obj = IntegratorSE(n, x0, Au, bu)
assert(n == 2 || n == 3);
nx = n + n*n;
if n == 2
nu = 3;
else
nu = 6;
end
if isempty(x0)
R0 = eye(n);
x0 = [zeros(n, 1); R0(:)];
end
if isempty(Au) || isempty(bu)
Au = [eye(nu); -eye(nu)];
bu = [ones(nu, 1); ones(nu, 1)];
end
obj@DynamicalSystem(nx, nu, Au, bu);
obj.dim = n;
obj.x = x0;
end
function [f, g] = dyn(obj, x)
f = zeros(obj.nx, 1);
if obj.dim == 2
ctheta = x(3);
stheta = x(4);
g = [eye(2), zeros(2, 1);
zeros(4, 2), [-stheta; ctheta; -ctheta; -stheta]];
else
R = reshape(x(4:end), 3, 3);
kR = kron(eye(3), R);
gw = [kR(:,6)-kR(:,8), kR(:,7)-kR(:,3), kR(:,2)-kR(:,4)];
g = [eye(3), zeros(3,9); zeros(9,3), gw];
end
end
function [x_new] = step(obj, dt, u)
p = obj.x(1:obj.dim);
R = reshape(obj.x(1+obj.dim:end), obj.dim, obj.dim);
v = u(1:obj.dim);
w = u(1+obj.dim:end);
if obj.dim == 2
w_hat = [0, -w; w, 0];
else
w_hat = [0, -w(3), w(2); w(3), 0, -w(1); -w(2), w(1), 0];
end
p_new = p + dt * v;
R_new = R * expm(dt * w_hat);
x_new = [p_new; R_new(:)];
end
end
end |
<?php
namespace Sabre\VObject;
/**
* UUID Utility.
*
* This class has static methods to generate and validate UUID's.
* UUIDs are used a decent amount within various *DAV standards, so it made
* sense to include it.
*
* @copyright Copyright (C) fruux GmbH (https://fruux.com/)
* @author Evert Pot (http://evertpot.com/)
* @license http://sabre.io/license/ Modified BSD License
*/
class UUIDUtil {
/**
* Returns a pseudo-random v4 UUID.
*
* This function is based on a comment by Andrew Moore on php.net
*
* @see http://www.php.net/manual/en/function.uniqid.php#94959
*
* @return string
*/
static function getUUID() {
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
// 16 bits for "time_mid"
mt_rand(0, 0xffff),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,
// 48 bits for "node"
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
/**
* Checks if a string is a valid UUID.
*
* @param string $uuid
*
* @return bool
*/
static function validateUUID($uuid) {
return preg_match(
'/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i',
$uuid
) !== 0;
}
} |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2016 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.teller.pixeldungeonofteller.items.scrolls;
import com.teller.pixeldungeonofteller.Assets;
import com.teller.pixeldungeonofteller.actors.buffs.Invisibility;
import com.teller.pixeldungeonofteller.items.Item;
import com.teller.pixeldungeonofteller.messages.Messages;
import com.teller.pixeldungeonofteller.scenes.GameScene;
import com.teller.pixeldungeonofteller.windows.WndBag;
import com.teller.pixeldungeonofteller.windows.WndOptions;
import com.watabou.noosa.audio.Sample;
public abstract class InventoryScroll extends Scroll {
protected static boolean identifiedByUse = false;
protected static WndBag.Listener itemSelector = new WndBag.Listener() {
@Override
public void onSelect(Item item) {
if (item != null) {
((InventoryScroll) curItem).onItemSelected(item);
((InventoryScroll) curItem).readAnimation();
Sample.INSTANCE.play(Assets.SND_READ);
Invisibility.dispel();
} else if (identifiedByUse && !((Scroll) curItem).ownedByBook) {
((InventoryScroll) curItem).confirmCancelation();
} else if (!((Scroll) curItem).ownedByBook) {
curItem.collect(curUser.belongings.backpack);
}
}
};
protected String inventoryTitle = Messages.get(this, "inv_title");
protected WndBag.Mode mode = WndBag.Mode.ALL;
@Override
protected void doRead() {
if (!isKnown()) {
setKnown();
identifiedByUse = true;
} else {
identifiedByUse = false;
}
GameScene.selectItem(itemSelector, mode, inventoryTitle);
}
private void confirmCancelation() {
GameScene.show(new WndOptions(name(), Messages.get(this, "warning"),
Messages.get(this, "yes"), Messages.get(this, "no")) {
@Override
protected void onSelect(int index) {
switch (index) {
case 0:
curUser.spendAndNext(TIME_TO_READ);
identifiedByUse = false;
break;
case 1:
GameScene.selectItem(itemSelector, mode, inventoryTitle);
break;
}
}
public void onBackPressed() {
}
});
}
protected abstract void onItemSelected(Item item);
} |
import { atom, atomFamily } from 'recoil'
import { ProposalDraft } from '@dao-dao/types'
import { ProposalCreatedCardProps } from '@dao-dao/types/proposal'
import { localStorageEffectJSON } from '../effects'
// Store proposal ID list endings for proposal pagination for the given
// coreAddress. Map list index to its ending for each proposal module address.
export const proposalStartBeforesAtom = atomFamily<
Record<number, Record<string, number | undefined> | undefined>,
string
>({
key: 'proposalStartBefores',
// Start first list (index 0) at the beginning.
// It uses the previous list's ending as its starting point, so
// set index -1 to undefined so startBefore is initially undefined.
default: { [-1]: undefined },
})
// Count of proposal lists that have been loaded for the given coreAddress. Each
// 'load more' action increments this.
export const proposalListCountAtom = atomFamily<number, string>({
key: 'proposalListCount',
default: 1,
})
// Store proposal drafts per DAO.
export const proposalDraftsAtom = atomFamily<ProposalDraft[], string>({
key: 'proposalDrafts',
default: [],
effects: [localStorageEffectJSON],
})
// Store latest proposal form state per DAO.
export const latestProposalSaveAtom = atomFamily<any, string>({
key: 'latestProposalSave',
default: {},
effects: [localStorageEffectJSON],
})
// When set, shows proposal created modal with these props for the ProposalCard
// shown.
export const proposalCreatedCardPropsAtom = atom<
ProposalCreatedCardProps | undefined
>({
key: 'proposalCreatedCardProps',
default: undefined,
})
// When set, shows gov proposal created modal with these props for the
// ProposalCard shown.
export const govProposalCreatedCardPropsAtom = atom<
ProposalCreatedCardProps | undefined
>({
key: 'govProposalCreatedCardProps',
default: undefined,
}) |
import Foundation
import SwiftUI
import UIDelight
import DesignSystem
import CoreLocalization
public struct PinCodeView: View {
let length: Int
let attempt: Int
@Binding
var errorMessage: String
let cancelAction: () -> Void
@Binding
var pinCode: String {
didSet {
if pinCode.count > length {
pinCode = oldValue
}
}
}
let hideCancel: Bool
public init(pinCode: Binding<String>, errorMessage: Binding<String> = .constant(""), length: Int = 4, attempt: Int, hideCancel: Bool = false, cancelAction: @escaping () -> Void) {
self._pinCode = pinCode
self._errorMessage = errorMessage
self.length = length
self.attempt = attempt
self.cancelAction = cancelAction
self.hideCancel = hideCancel
}
public var body: some View {
VStack(alignment: .center, spacing: 22) {
VStack(spacing: 16) {
HStack(spacing: 29) {
ForEach(1..<5) { value in
Circle()
.stroke(Color.ds.border.neutral.standard.idle, lineWidth: 1)
.frame(width: 12, height: 12)
.background(
Circle()
.fill(Color.ds.text.neutral.standard)
.hidden(self.pinCode.count < value)
)
}
}
.shakeAnimation(forNumberOfAttempts: attempt)
Text(errorMessage)
.foregroundColor(.ds.text.danger.quiet)
.font(.body)
.multilineTextAlignment(.center)
}
VStack(alignment: .trailing, spacing: 16) {
HStack(spacing: 16) {
ForEach(1..<4) { value in
PinButton(action: {self.didClickCode(value)}, title: String(value)).font(.title)
.keyboardShortcut(.init(value), modifiers: [])
}
}
HStack(spacing: 16) {
ForEach(4..<7) { value in
PinButton(action: {self.didClickCode(value)}, title: String(value)).font(.title)
.keyboardShortcut(.init(value), modifiers: [])
}
}
HStack(spacing: 16) {
ForEach(7..<10) { value in
PinButton(action: {self.didClickCode(value)}, title: String(value)).font(.title)
.keyboardShortcut(.init(value), modifiers: [])
}
}
HStack(spacing: 16) {
PinButton(action: {}, title: "").hidden()
PinButton(action: {self.didClickCode(0)}, title: "0").font(.title)
.keyboardShortcut(.init(0), modifiers: [])
if pinCode.count == 0 {
if hideCancel {
cancelButton
.hidden()
} else {
cancelButton
}
} else {
deleteButton
}
}
}
}
.padding(.all, 16)
}
var cancelButton: some View {
PinButton(action: cancelAction,
title: L10n.Core.cancel,
fillColor: .clear,
highlightColor: .clear)
.keyboardShortcut(KeyEquivalent.escape, modifiers: [])
.font(.caption)
.foregroundColor(.ds.text.neutral.standard)
}
var deleteButton: some View {
PinButton(action: {
if !self.pinCode.isEmpty {
_ = self.pinCode.removeLast()
}
}, title: L10n.Core.kwDelete, fillColor: .clear, highlightColor: .clear).font(.caption)
.foregroundColor(.ds.text.neutral.standard)
.keyboardShortcut(KeyEquivalent.return, modifiers: [])
}
func didClickCode(_ code: Int) {
self.pinCode += String(code)
}
}
struct PinCodeView_Previews: PreviewProvider {
static var previews: some View {
MultiContextPreview {
Group {
PinCodeView(pinCode: .constant(""), attempt: 1, cancelAction: {}).padding(.horizontal, 20).loginAppearance()
PinCodeView(pinCode: .constant("1"), attempt: 0, cancelAction: {}).loginAppearance()
.frame(width: 260, height: 318)
PinCodeView(pinCode: .constant("12"), attempt: 2, cancelAction: {}).frame(width: 200, height: 300).loginAppearance()
PinCodeView(pinCode: .constant("123"), attempt: 2, cancelAction: {}).frame(width: 300, height: 400).loginAppearance()
PinCodeView(pinCode: .constant("1234"), attempt: 2, cancelAction: {}).loginAppearance()
PinCodeView(pinCode: .constant("123456789"), attempt: 2, cancelAction: {}).loginAppearance()
}
}.previewLayout(.sizeThatFits)
}
}
private extension KeyEquivalent {
init(_ intValue: Int) {
let char = Character("\(intValue)")
self.init(unicodeScalarLiteral: char)
}
} |
List<List<Integer>> lists = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if (candidates == null || candidates.length == 0 || target < 0) {
return lists;
}
List<Integer> list = new ArrayList<>();
process(0, candidates, target, list);
return lists;
}
private void process(int start, int[] candidates, int target, List<Integer> list) {
//递归的终止条件
if (target < 0) {
return;
}
if (target == 0) {
lists.add(new ArrayList<>(list));
} else {
for (int i = start; i < candidates.length; i++) {
list.add(candidates[i]);
//因为每个数字都可以使用无数次,所以递归还可以从当前元素开始
//加入传参列表不传入start,那么就会出现组合的情况,举例如下
/*
target = 5
for i in range(1, 11):
for j in range(1, 11):
for z in range(1, 11):
if i + j + z == target:
print(i, j, z)
输出:
1 1 3
1 2 2
1 3 1
2 1 2
2 2 1
3 1 1
target = 5
for i in range(1, 11):
for j in range(i, 11): # change and [i,10]
for z in range(j, 11):
if i + j + z == target:
print(i, j, z)
输出:
1 1 3
1 2 2
**/
process(i, candidates, target - candidates[i], list);
list.remove(list.size() - 1);
}
}
} |
import React from 'react'
import { useLoaderData, Form, redirect, useActionData, useNavigation, NavLink, useSearchParams } from 'react-router-dom';
import { styled } from 'styled-components'
import { useNavigate } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux';
import { logIn } from '../features/slice/loginSlice';
const LoginPageStyled = styled.div`
width: 100vw;
height: 80vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
div {
width: 50%;
max-width: 500px;
padding: 1.3em;
text-align: center;
background: rgba(255, 255, 255, 0.2);
border-radius: 16px;
box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
backdrop-filter: blur(17.3px);
-webkit-backdrop-filter: blur(17.3px);
border: 1px solid rgba(255, 255, 255, 0.3);
h2 {
color: red;
font-weight: 500;
}
form {
h5 {
margin-top: .4em;
a {
color: ${({theme}) => theme.colors.pop};
}
}
button {
padding: .6em;
margin: 1.2em 0;
border-radius: 5px;
font-weight: 600;
&:hover {
color: white;
background-color: red;
}
}
section {
display:flex;
flex-direction: column;
align-items: center;
margin-top: 1.5em;
input {
padding: .8em;
border-radius: 5px;
margin-top: .3em;
width: 80%;
max-width: 300px;
text-align: center;
}
}
}
}
`
export const loginLoader = ({request}) => {
const url = new URL(request.url).searchParams;
return (url.get('message'))
}
export default function Login() {
const [formData, setFormData] = React.useState({email: '', password: ''});
const [error, setError] = React.useState('');
const navigate = useNavigate();
const dispatch = useDispatch();
const registeredUsers = useSelector(state => state.logIn.users);
const message = useLoaderData();
const handleChange = (e) => {
const {name, value} = e.target;
setFormData(p => {
return {...p, [name] : value};
})
}
const handleSubmit = (e) => {
e.preventDefault();
const email = formData.email;
const password = formData.password;
const currentUser = registeredUsers.find(item => item.email === email);
if(currentUser) {
const name = currentUser.name;
if(currentUser.password === password) {
dispatch(logIn())
return navigate(`/project/products/?name=${name}`, {replace: true});
}
else{
setError('Incorrect Password')
}
} else {
setError('User does not exist')
}
}
return (
<LoginPageStyled>
<div>
<h1>Login</h1>
{message && <h4 style={{color: 'red'}}>{message}</h4>}
<form onSubmit={handleSubmit}>
<section>
<label>Email</label>
<input
required
type='email'
name='email'
placeholder='Enter your email'
value={formData.email}
onChange={handleChange}
/>
</section>
<section>
<label>Password</label>
<input
required
type='password'
name='password'
placeholder='Enter your password'
value={formData.password}
onChange={handleChange}
/>
</section>
<h5>Haven't signed in? <NavLink to='/register'>Register</NavLink></h5>
<button >Log in</button>
{error && <h3>{error}</h3>}
</form>
</div>
</LoginPageStyled>
)
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using Microsoft.VisualBasic;
using System.Text.RegularExpressions;
using System.Collections;
using System.Data.SqlClient;
namespace OnlineBookstore
{
// Class users interact with -- buying and looking for books
public partial class HomepageForm : Form
{
// The total count of books in the database
private int _maxbook = 0;
// The total of the books a user is purchasing
private decimal price;
// The user ID
private int _userID;
// Constructor that initializes user ID
public HomepageForm(int userID)
{
InitializeComponent();
this.Load += new System.EventHandler(this.HomepageForm_Load);
_userID = userID;
}
// On load up of the homepage, disables certain buttons that need conditions to be met for them to enable -- loads all books into listbox
private void HomepageForm_Load(object sender, EventArgs e)
{
uxBuy.Enabled = false;
uxRemove.Enabled = false;
LoadBooks();
_maxbook = uxBookList.Items.Count;
uxDisplaying.Text = _maxbook + " of " + _maxbook;
}
// Loads all the books that aren't removed into the list box
private void LoadBooks()
{
string connectionString = ConfigurationManager.ConnectionStrings["OnlineBookstoreDb"].ConnectionString;
string query = "SELECT ISBN, Title, Price FROM Books WHERE IsRemoved = 0";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable books = new DataTable();
adapter.Fill(books);
uxBookList.DisplayMember = "Title";
uxBookList.ValueMember = "ISBN";
uxBookList.DataSource = books;
}
}
// Event handler for pressing the search/filter button -- has different cases for each filter option
private void uxSearchButton_Click(object sender, EventArgs e)
{
string searchterm = uxSearchBox.Text.Trim();
uxBookList.DataSource = null;
if (string.IsNullOrWhiteSpace(searchterm))
{
if (uxFilter.SelectedItem?.ToString() == "Genre")
{
string selectedGenre = uxGenreComboBox.Text;
ExecuteQueryFiltered("GenreName", selectedGenre);
}
else
{
LoadBooks();
}
}
else
{
if (uxFilter.SelectedItem?.ToString() == "Genre")
{
string selectedGenre = uxGenreComboBox.Text;
ExecuteQueryFiltered("GenreName", selectedGenre);
}
else
{
switch (uxFilter.SelectedItem?.ToString())
{
case "Title":
ExecuteQueryFiltered("Title", searchterm);
break;
case "Author":
ExecuteQueryFiltered("AuthorName", searchterm);
break;
case "ISBN":
ExecuteQueryFiltered("ISBN", searchterm);
break;
case "Price":
ExecuteQueryFiltered("Price", searchterm);
break;
case "Publisher":
ExecuteQueryFiltered("Publisher", searchterm);
break;
default:
MessageBox.Show("Invalid filter selection.");
break;
}
}
}
uxSearchBox.Text = "";
uxDisplaying.Text = uxBookList.Items.Count + " of " + _maxbook;
}
// Formats how books are displayed depending on which filter option is chosen
private void FormatBookDisplay(object sender, ListControlConvertEventArgs e)
{
DataRowView row = e.ListItem as DataRowView;
if (row != null)
{
string title = row["Title"].ToString();
string author = row["AuthorName"].ToString();
string isbn = row["ISBN"].ToString();
string price = String.Format("{0:C}", row["Price"]);
string publisher = row["Publisher"].ToString();
string genre = row.Row.Table.Columns.Contains("GenreName") ? row["GenreName"].ToString() : "";
switch (uxFilter.SelectedItem.ToString())
{
case "Title":
e.Value = $"{title} by {author}";
break;
case "Author":
e.Value = $"Author: {author} - {title}";
break;
case "ISBN":
e.Value = $"{isbn} - {title}";
break;
case "Genre":
e.Value = $"Genre: {genre} - {title} by {author}";
break;
case "Price":
e.Value = $"{price} - {title} by {author}";
break;
case "Publisher":
e.Value = $"Publisher: {publisher} - {title} by {author}";
break;
}
}
}
// Performs SQL queries for the filters -- needed special Publisher, AuthorName, and GenreName cases
private void ExecuteQueryFiltered(string fieldName, string filter)
{
string connectionString = ConfigurationManager.ConnectionStrings["OnlineBookstoreDb"].ConnectionString;
DataTable books = new DataTable();
string query = "";
switch (fieldName)
{
case "Title":
case "ISBN":
case "Price":
case "Publisher":
query = $@"SELECT ISBN, Title, Authors.AuthorName, Price, Publisher
FROM Books
INNER JOIN Authors ON Books.AuthorID = Authors.AuthorID
WHERE {fieldName} LIKE @Filter AND IsRemoved = 0
ORDER BY {(fieldName == "Price" ? "Title" : fieldName)}";
break;
case "AuthorName":
query = $@"SELECT ISBN, Title, Authors.AuthorName, Price, Publisher
FROM Books
INNER JOIN Authors ON Books.AuthorID = Authors.AuthorID
WHERE Authors.AuthorName LIKE @Filter AND Books.IsRemoved = 0
ORDER BY Title";
break;
case "GenreName":
query = $@"SELECT ISBN, Title, Authors.AuthorName, Genres.GenreName, Price, Publisher
FROM Books
INNER JOIN Authors ON Books.AuthorID = Authors.AuthorID
INNER JOIN Genres ON Books.GenreID = Genres.GenreID
WHERE Genres.GenreName LIKE @Filter AND Books.IsRemoved = 0
ORDER BY Title";
break;
}
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Filter", $"%{filter}%");
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(books);
uxBookList.DisplayMember = "Title";
uxBookList.ValueMember = "ISBN";
uxBookList.DataSource = books;
uxBookList.Format += new ListControlConvertEventHandler(FormatBookDisplay);
}
}
// Event handler for clicking the buy button -- loads the buy form to checkout
private void uxBuy_Click(object sender, EventArgs e)
{
List<string> selectedBooks = new List<string>();
foreach (var item in uxBuyList.Items)
{
selectedBooks.Add(item.ToString());
}
BuyForm buyForm = new BuyForm(selectedBooks, _userID);
buyForm.Show();
}
// Event handler for clicking the add button -- adds books to cart
private void uxAdd_Click(object sender, EventArgs e)
{
if (uxBookList.SelectedItem != null)
{
DataRowView selectedBook = uxBookList.SelectedItem as DataRowView;
if (selectedBook != null)
{
string title = selectedBook["Title"].ToString();
decimal price = Convert.ToDecimal(selectedBook["Price"]);
string displayText = $"{title} - ${price:F2}";
uxBuyList.Items.Add(displayText);
updatePrice(price);
uxBuy.Enabled = uxBuyList.Items.Count > 0;
}
}
}
// Updates the total price of the books the user has selected
private void updatePrice(decimal prices)
{
price += prices;
uxPrice.Text = "Total: $" + price.ToString();
}
// Event handler to remove books from cart
private void uxRemove_Click(object sender, EventArgs e)
{
if (uxBuyList.SelectedIndex != -1)
{
string item2 = uxBuyList.Items[uxBuyList.SelectedIndex].ToString();
int index = item2.IndexOf('$') + 1;
string substring = item2.Substring(index);
price -= decimal.Parse(substring);
uxPrice.Text = "Total: $" + price.ToString();
uxBuyList.Items.RemoveAt(uxBuyList.SelectedIndex);
uxBuy.Enabled = uxBuyList.Items.Count > 0;
}
if (uxBuyList.Items.Count <= 0)
{
uxRemove.Enabled = false;
}
}
// Event handler that enables the buy and remove buttons once something is in user's cart
private void uxBuyList_SelectedIndexChanged(object sender, EventArgs e)
{
if (uxBuyList.Items.Count >= 1)
{
uxRemove.Enabled = true;
uxBuy.Enabled = true;
}
}
// Event handler for detecting if the genre search filter was selected
private void uxFilter_SelectedIndexChanged(object sender, EventArgs e)
{
// Check if filtering by genre. If so, display genre ComboBox
uxGenreComboBox.Visible = uxFilter.SelectedItem?.ToString() == "Genre";
if (uxGenreComboBox.Visible)
{
LoadGenres();
}
}
// Load a new combobox with all the genres if it was chosen to filter by
private void LoadGenres()
{
string connectionString = ConfigurationManager.ConnectionStrings["OnlineBookstoreDb"].ConnectionString;
string query = "SELECT GenreID, GenreName FROM Genres ORDER BY GenreName";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable genres = new DataTable();
adapter.Fill(genres);
uxGenreComboBox.DisplayMember = "GenreName";
uxGenreComboBox.ValueMember = "GenreID";
uxGenreComboBox.DataSource = genres;
}
}
// Back button to the signup page
private void uxBackButton_Click(object sender, EventArgs e)
{
SignUpForm signUpForm = new SignUpForm();
signUpForm.Show();
this.Hide();
}
}
} |
import React, { Component } from 'react';
import { Layout } from 'antd';
import styles from './index.less';
import BaseLayout from '@/components/BaseLayout';
import BaseMenu from '@/components/BaseMenu';
import ProfileSettingPage from './profile';
import router from 'umi/router';
import _ from 'lodash';
const { Sider, Content } = Layout;
/**
* 个人设置
*/
export default class SettingPage extends Component {
constructor(props) {
super(props);
this.state = { selectedKeys: ['1'], title: '基础设置' };
}
componentDidMount = () => {
const { selectedKeys } = this.state;
this._pushToPage(selectedKeys[0]);
};
_menuSider = [
{ id: '1', name: '基础设置', url: '/account/setting/profile' },
{ id: '2', name: '安全设置', url: '/account/setting/security' },
];
// 菜单选择
_onMenuSelect = ({ item, key, selectedKeys }) => {
const element = _.find(this._menuSider, item => item.id === key);
this.setState({ selectedKeys, title: element.name });
router.push(element.url);
};
// push to new page
_pushToPage = key => {
const element = _.find(this._menuSider, item => item.id === key);
router.push(element.url);
};
render() {
const { children } = this.props;
const { selectedKeys, title } = this.state;
return (
<div>
<BaseLayout title="个人设置">
<Sider className={styles.sider} width={220}>
<BaseMenu
style={{ minHeight: '100%' }}
theme="light"
loading={false}
link={false}
selectedKeys={selectedKeys}
menuData={this._menuSider}
onSelect={this._onMenuSelect}
/>
</Sider>
<Content className={styles.rightContent}>
{/* 二级页面标题 */}
<div className={styles.title}>{title}</div>
{children}
</Content>
</BaseLayout>
</div>
);
}
} |
export default class Airport {
constructor(name, code) {
this.name = name;
this.code = code;
}
get name() {
// eslint-disable-next-line
return this._name;
}
set name(value) {
// eslint-disable-next-line
if (typeof value !== 'string') {
throw new TypeError('Name must be a string');
}
// eslint-disable-next-line
this._name = value;
}
get code() {
// eslint-disable-next-line
return this._code;
}
set code(value) {
if (typeof value !== 'string') {
throw new TypeError('Code must be a string');
}
// eslint-disable-next-line
this._code = value;
}
get [Symbol.toStringTag]() {
// eslint-disable-next-line
return this._code;
}
} |
import { observer } from "mobx-react-lite";
import { ChangeEventHandler, useCallback, useState } from "react";
import { ToDo, toDoStore } from "./store/global-store";
import { Button, TextField, Toolbar, Typography, Switch } from "@mui/material";
import { ListOfTodos } from "./components/list-of-todos/list-of-todos";
export const App = observer(() => {
const [todo, setToDo] = useState<string>("");
const registerNameOfToDo = useCallback<ChangeEventHandler<HTMLInputElement>>(
(event) => setToDo(event.target.value),
[]
);
const addToDo = useCallback(() => {
toDoStore.add(todo);
setToDo("");
}, [todo]);
const removeToDo = useCallback(
(elIdx: number) => () => {
toDoStore.remove(elIdx);
},
[]
);
const defineIsDone = useCallback(
(toDoTask: ToDo) => () => toDoStore.defineIsDone(toDoTask),
[]
);
const setFiltered = useCallback((event, checked) => {
toDoStore.filter(checked);
}, []);
const arrToDisplay: Array<ToDo> = !toDoStore.isFiltered
? toDoStore.arrOfToDo
: toDoStore.arrOfToDo.filter((todo: ToDo) => todo.isDone);
return (
<div className="App">
<Toolbar
sx={{
display: "flex",
justifyContent: "space-between",
alignItems: "center"
}}
>
<Typography variant="h4" component="div">
ToDoList
</Typography>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center"
}}
>
<Switch value={toDoStore.isFiltered} onChange={setFiltered} />
<Typography variant="h6" component="div">
filter by isDone
</Typography>
</div>
</Toolbar>
<ListOfTodos
listToDos={arrToDisplay}
defineIsDone={defineIsDone}
removeToDo={removeToDo}
/>
<TextField
variant="filled"
sx={{ maxHeight: "30px !important", width: "90%" }}
value={todo}
onChange={registerNameOfToDo}
/>
<Button
onClick={addToDo}
variant={"contained"}
sx={{ height: "55px !important", width: "10%" }}
>
add
</Button>
</div>
);
}); |
import { all, call, takeLatest, put } from "typed-redux-saga/macro";
import { USER_ACTIONS_TYPE } from "./user.types";
import {
AdditionalInfo,
createAuthUserWithEmailAndPassword,
createUserDocumentFromAuth,
getCurrentUser,
signInAuthUserWithEmailAndPassword,
signInWithGooglePopup,
signOutUser,
} from "../../utils/firebase/firebase.utils";
import {
EmailSighInStart,
SignUpSuccess,
SignUpUStart,
userActions,
} from "./user.actions";
import { User } from "firebase/auth";
function* getSnapshotFromUserAuth(
userAuth: User,
additionalDetails?: AdditionalInfo
) {
try {
const userSnapshot = yield* call(
createUserDocumentFromAuth,
userAuth,
additionalDetails
);
if (userSnapshot) {
yield put(
userActions.signInSuccess({
id: userSnapshot.id,
...userSnapshot.data(),
})
);
}
} catch (e) {
yield put(userActions.signInFailed(e as Error));
}
}
export function* isUserAuthenticated() {
try {
const userAuth = yield* call(getCurrentUser);
if (!userAuth) return;
yield* call(getSnapshotFromUserAuth, userAuth);
} catch (e) {
yield* put(userActions.signInFailed(e as Error));
}
}
export function* signInWithGoogle() {
try {
const { user } = yield call(signInWithGooglePopup);
yield* call(getSnapshotFromUserAuth, user);
} catch (e) {
yield put(userActions.signInFailed(e as Error));
}
}
export function* sighInWithEmail(action: EmailSighInStart) {
const {
payload: { email, password },
} = action;
try {
const { user } = yield call(
signInAuthUserWithEmailAndPassword,
email,
password
);
yield* call(getSnapshotFromUserAuth, user);
} catch (e) {
yield* put(userActions.signInFailed(e as Error));
}
}
export function* signUp(action: SignUpUStart) {
const {
payload: { email, password, displayName },
} = action;
try {
const { user } = yield call(
createAuthUserWithEmailAndPassword,
email,
password
);
yield* put(userActions.signUpSuccess(user, { displayName }));
} catch (e) {
yield* put(userActions.signUpFailed(e as Error));
}
}
export function* signInAfterSingUp(action: SignUpSuccess) {
const { user, additionalDetails } = action.payload;
try {
yield* call(getSnapshotFromUserAuth, user, additionalDetails);
} catch (e) {
yield* put(userActions.signUpFailed(e as Error));
}
}
export function* sighOut() {
try {
yield* call(signOutUser);
yield* put(userActions.signOutSuccess());
} catch (e) {
yield* put(userActions.signOutFailed(e as Error));
}
}
export function* watchUserAction() {
yield takeLatest(USER_ACTIONS_TYPE.CHECK_USER_SESSION, isUserAuthenticated);
yield takeLatest(USER_ACTIONS_TYPE.GOOGLE_SIGN_IN_START, signInWithGoogle);
yield takeLatest(USER_ACTIONS_TYPE.EMAIL_SIGN_IN_START, sighInWithEmail);
yield takeLatest(USER_ACTIONS_TYPE.SIGN_UP_START, signUp);
yield takeLatest(USER_ACTIONS_TYPE.SIGN_UP_SUCCESS, signInAfterSingUp);
yield takeLatest(USER_ACTIONS_TYPE.SIGN_OUT_START, sighOut);
}
export function* userSagas() {
yield all([call(watchUserAction)]);
} |
#include <CL/sycl.hpp>
#include <iomanip>
#include <vector>
#include "dpc_common.hpp"
#include "Complex.hpp"
using namespace sycl;
using namespace std;
// Number of complex numbers passing to the DPC++ code
static const int num_elements = 10000;
// in_vect1 and in_vect2 are the vectors with num_elements complex nubers and
// are inputs to the parallel function
void DpcppParallel(queue &q, std::vector<Complex2> &in_vect1,
std::vector<Complex2> &in_vect2,
std::vector<Complex2> &out_vect)
{
auto R = range(in_vect1.size());
buffer bufin_vect1(in_vect1);
buffer bufin_vect2(in_vect2);
buffer bufout_vect(out_vect);
std::cout << "Target Device: ";
// TODO: Get info from the device print here
q.submit([&](auto &h)
{
// Accessors set as read mode
// How we should access bufin_vect1 and 2: read_only, write_only, read_write...
accessor V1(bufin_vect1, h, //TODO: Add here your decision);
accessor V2(bufin_vect2, h, //TODO: Add here your decision);
// How we should access bufout_vect: read_only, write_only, read_write...
accessor V3(bufout_vect, h, //TODO: Add here your decision);
h.parallel_for(R, [=](auto i)
{
V3[i] = V1[i].complex_mul(V2[i]);
});
});
// TODO add code to wait the work
}
void DpcppScalar(std::vector<Complex2> &in_vect1,
std::vector<Complex2> &in_vect2,
std::vector<Complex2> &out_vect)
{
for (int i = 0; i < in_vect1.size(); i++)
{
out_vect[i] = in_vect1[i].complex_mul(in_vect2[i]);
}
}
// Compare the results of the two output vectors from parallel and scalar. They
// should be equal
int Compare(std::vector<Complex2> &v1, std::vector<Complex2> &v2)
{
int ret_code = 1;
if (v1.size() != v2.size())
{
ret_code = -1;
}
for (int i = 0; i < v1.size(); i++)
{
if (v1[i] != v2[i])
{
ret_code = -1;
break;
}
}
return ret_code;
}
int main()
{
// Declare your Input and Output vectors of the Complex2 class
vector<Complex2> input_vect1;
vector<Complex2> input_vect2;
vector<Complex2> out_vect_parallel;
vector<Complex2> out_vect_scalar;
for (int i = 0; i < num_elements; i++)
{
input_vect1.push_back(Complex2(i + 2, i + 4));
input_vect2.push_back(Complex2(i + 4, i + 6));
out_vect_parallel.push_back(Complex2(0, 0));
out_vect_scalar.push_back(Complex2(0, 0));
}
// Initialize your Input and Output Vectors. Inputs are initialized as below.
// Outputs are initialized with 0
cpu_selector selector;
queue q(selector, dpc_common::exception_handler);
// Call the DpcppParallel with the required inputs and outputs
DpcppParallel(q, input_vect1, input_vect2, out_vect_parallel);
std::cout << "****************************************Multiplying Complex numbers "
"in Parallel********************************************************"
<< std::endl;
// Print the outputs of the Parallel function
int indices[]{0, 1, 2, 3, 4, (num_elements - 1)};
constexpr size_t indices_size = sizeof(indices) / sizeof(int);
for (int i = 0; i < indices_size; i++)
{
int j = indices[i];
if (i == indices_size - 1)
std::cout << "...\n";
std::cout << "[" << j << "] " << input_vect1[j] << " * " << input_vect2[j]
<< " = " << out_vect_parallel[j] << "\n";
}
// Call the DpcppScalar function with the required input and outputs
DpcppScalar(input_vect1, input_vect2, out_vect_scalar);
// Compare the outputs from the parallel and the scalar functions. They should
// be equal
int ret_code = Compare(out_vect_parallel, out_vect_scalar);
if (ret_code == 1)
{
std::cout << "Complex multiplication successfully run on the device"
<< "\n";
}
else
std::cout
<< "*********************************************Verification Failed. Results are "
"not matched**************************"
<< "\n";
return 0;
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngularAsm</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<!-- icon -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- tailwind -->
<link rel="stylesheet" href="styles.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght@200;400&display=swap" rel="stylesheet">
<!-- font family -->
<style>
@import url('https://fonts.googleapis.com/css?family=Karla:400,700&display=swap');
.font-family-karla {
font-family: karla;
}
.bg-sidebar {
background: #3d68ff;
}
.cta-btn {
color: #3d68ff;
}
.upgrade-btn {
background: #1947ee;
}
.upgrade-btn:hover {
background: #0038fd;
}
.active-nav-link {
background: #1947ee;
}
.nav-item:hover {
background: #1947ee;
}
.account-link:hover {
background: #3d68ff;
}
.nunito {
font-family: 'Nunito', sans-serif;
}
.background {
background-image: url('https://media.ex-cdn.com/EXP/media.vntravellive.com/files/news/2020/04/29/tang-tan-suat-gt-vt-tai-cac-thanh-pho-041453.jpg');
width: 100%
}
.backgroundMain {
background-image: url('https://media.timeout.com/images/105168794/image.jpg');
}
.backgroundFooter {
background-image: url('https://upload.wikimedia.org/wikipedia/commons/1/16/Appearance_of_sky_for_weather_forecast%2C_Dhaka%2C_Bangladesh.JPG');
}
.backgroundPlaceManager {
background-image: url('https://media.ex-cdn.com/EXP/media.vntravellive.com/files/news/2020/06/18/nhung-cung-duong-sat-dep-nhat-vn-140855.jpg');
width: 100%
}
.backgroundSuccess {
background-image: url('https://thumb.ex-cdn.com/EXP/media.vntravellive.com/resize/900x599/files/editor2/2020/06/18/img_5816-1356.jpg');
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
</style>
</head>
<body class="nunito">
<app-root></app-root>
</body>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js" defer></script>
<!-- Font Awesome -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js" integrity="sha256-KzZiKy0DWYsnwMF+X1DvQngQ2/FxF7MF3Ff72XcpuPs=" crossorigin="anonymous"></script> -->
<!-- ChartJS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"
integrity="sha256-R4pqcOYV8lt7snxMQO/HSbVCFRPMdrhAFMH+vr9giYI=" crossorigin="anonymous"></script>
<script>
var chartOne = document.getElementById('chartOne');
var myChart = new Chart(chartOne, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
var chartTwo = document.getElementById('chartTwo');
var myLineChart = new Chart(chartTwo, {
type: 'line',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
</html> |
import React from 'react'
import { Line} from 'react-chartjs-2'
import data from '../Beras/data.json'
import { Table } from 'react-bootstrap'
function InflasiJogja(){
const styles={marginLeft:"20%"}
return(
<div id="features">
<div className='container'>
<div className='col-md-10 col-md-offset-1 section-title'>
<h2>Peramalan Tingkat Inflasi Provinsi Yogyakarta</h2>
<p>Plot Peramalan Tingkat Inflasi Provinsi Yogyakarta Periode Januari 2021 - Desember 2022</p>
</div>
<div style={styles} className="col-lg-8 col-lg-8">
<Line
data={{
labels: ['Jan 2021','Feb 2021', 'Mar 2021', 'Apr 2021', 'Mei 2021', 'Jun 2021 ', 'Jul 2021', 'Agu 2021', 'Sep 2021', 'Okt 2021', 'Nov 2021', 'Des 2021','Jan 2022','Feb 2022', 'Mar 2022', 'Apr 2022', 'Mei 2022', 'Jun 2022 ', 'Jul 2022', 'Agu 2022', 'Sep 2022', 'Okt 2022', 'Nov 2022', 'Des 2022'],
datasets: [
{
label: 'Data Ramalan Tingkat Inflasi',
data: [0.3304187,
0.1013424,
0.1114660,
0.0324912,
0.2604206,
0.1048357,
-0.0734631,
-0.0431127,
-0.0579001,
0.0722242,
0.1599586,
0.4156502,
0.2470128,
0.1872462,
0.0369961,
-0.1509110,
0.1864436,
0.0382072,
-0.1314633,
-0.0965630,
-0.0713717,
0.0209726,
0.0909146,
0.3910742,
],
borderColor: 'red',
borderWidth: 1,
},
],
}}
height={400}
width={600}
options={{
maintainAspectRatio: false,
scales: {
y: {
display: true,
title: {
display: true,
text: 'Tingkat Inflasi(%)',
font: {
size: 20,
style: 'normal',
lineHeight: 1.2
},
padding: {top: 30, left: 0, right: 0, bottom: 0}
}
},
x: {
display: true,
title: {
display: true,
text: 'Tahun 2021-2022',
font: {
size: 20,
style: 'normal',
lineHeight: 1.2
},
padding: {top: 30, left: 0, right: 0, bottom: 0}
}
}
},
legend: {
labels: {
fontSize: 25,
},
},
}}
/>
</div>
<div className='col-lg-8 col-lg-8' style={styles}>
<h3>Berikut tabel hasil peramalan tingkat inflasi di provinsi Yogyakarta</h3>
<Table striped bordered hover size="sm">
<thead>
<tr>
<th>Provinsi</th>
<th>Bulan</th>
<th>Tingkat Inflasi(%)</th>
</tr>
</thead>
<tbody>
{data.Jogja.map((item, i)=>(
<tr key={i}>
<td>{item.Provinsi}</td>
<td>{item.Tahun}</td>
<td>{item.Inflasi}</td>
</tr>
))}
</tbody>
</Table>
</div>
</div>
</div>
)
}
export default InflasiJogja |
<?php
/**
* @file
* Functions to support theming in the university_theme theme.
*/
use Drupal\block\Entity\Block;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Render\Markup;
use Drupal\Core\Template\Attribute;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
use Drupal\media_entity\Entity\Media;
use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;
use Drupal\taxonomy\Entity\Term;
use Drupal\views\Views;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
/**
* Implements hook_preprocess_HOOK() for html.html.twig.
*/
function university_theme_preprocess_html(array &$variables) {
if (\Drupal::service('path.matcher')->isFrontPage()) {
$variables['attributes']['class'][] = 'template-front-page';
}
elseif (!empty($variables['node_type'])) {
$variables['attributes']['class'][] = 'template-' . $variables['node_type'];
}
// Add class to user page.
if (isset($variables['root_path'])) {
if ($variables['root_path'] == 'user') {
$variables['attributes']['class'][] = 'template-employee';
}
elseif ($variables['root_path'] == 'studies' || $variables['root_path'] == 'employees') {
$variables['attributes']['class'][] = 'template-study-list';
}
elseif ($variables['root_path'] == 'search') {
$variables['attributes']['class'][] = 'template-search';
}
}
}
/**
* Implements hook_page_attachments_alter().
*/
function university_theme_page_attachments_alter(array &$page) {
// Tell IE to use latest rendering engine (not to use compatibility mode).
/*$ie_edge = [
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => [
'http-equiv' => 'X-UA-Compatible',
'content' => 'IE=edge',
],
];
$page['#attached']['html_head'][] = [$ie_edge, 'ie_edge'];*/
}
/**
* Implements hook_preprocess_page() for page.html.twig.
*/
function university_theme_preprocess_page(array &$variables) {
}
/**
* Implements hook_theme_suggestions_page_alter().
*/
function university_theme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
}
/**
* Implements hook_preprocess_HOOK().
*/
function university_theme_preprocess_region(array &$variables) {
}
/**
* Implements hook_theme_suggestions_region_alter().
*/
function university_theme_theme_suggestions_region_alter(array &$suggestions, array $variables) {
$nowrap_regions = [
'bottom',
'breadcrumb',
'content',
'featured_top',
'footer',
'header',
'highlighted',
'primary_menu',
'secondary_menu',
'sidebar_first',
'sidebar_second',
];
if (in_array($variables['elements']['#region'], $nowrap_regions)) {
$suggestions[] = 'region__nowrap';
}
}
/**
* Implements hook_theme_suggestions_container_alter().
*/
function university_theme_theme_suggestions_container_alter(array &$suggestions, array $variables) {
if (isset($variables['element']['#view'])) {
$suggestions[] = 'container__' . $variables['element']['#view']->id();
}
}
/**
* Implements hook_theme_suggestions_node_alter().
*/
function university_theme_theme_suggestions_node_alter(array &$suggestions, array $variables) {
}
/**
* Implements hook_theme_suggestions_user_alter().
*/
function university_theme_theme_suggestions_user_alter(array &$suggestions, array $variables) {
$suggestions[] = 'user__' . $variables['elements']['#view_mode'];
}
/**
* Implements hook_preprocess_HOOK() for Block document templates.
*/
function university_theme_preprocess_block(array &$variables) {
static $pos = 1;
if ($block = Block::load($variables['elements']['#id'])) {
$region = $block->getRegion();
if ($region == 'footer') {
$variables['content']['#attributes']['class'][] = 'list-icons';
$variables['title_attributes']['class'][] = 'nav-title';
if ($pos % 3 != 0) {
$variables['title_attributes']['class'][] = 'collapsable';
}
$pos++;
}
}
}
/**
* Implements hook_theme_suggestions_block_alter().
*/
function university_theme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
$block = Block::load($variables['elements']['#id']);
if ($block) {
$suggestions[] = 'block__' . $block->getRegion();
}
}
/**
* Implements hook_theme_suggestions_paragraph_alter().
*/
function university_theme_theme_suggestions_paragraph_alter(array &$suggestions, array $variables) {
$bundle = $variables['elements']['#paragraph']->bundle();
$parent = $variables['elements']['#paragraph']->getParentEntity();
if (!$parent) {
$ref_parent = $variables['elements']['#paragraph']->_referringItem->getParent();
if ($ref_parent && $ref_parent_parent = $ref_parent->getParent()) {
$parent = $ref_parent_parent->getValue();
}
}
if ($parent instanceof Node || $parent instanceof Paragraph) {
$parent_bundle = $parent->bundle();
}
// Fallback parent bundle.
if (empty($parent_bundle)) {
$parent_bundle = 'paragraph';
}
$nowrap_paragraphs = [
'gallery',
'html',
'media',
'text',
'twitter',
];
$suggestions[] = 'paragraph__' . $bundle . '__' . $parent_bundle;
if (in_array($bundle, $nowrap_paragraphs)) {
if ($parent_bundle == 'page') {
if ($bundle == 'media') {
$suggestions[] = 'paragraph__fullwidth__media';
}
else {
$suggestions[] = 'paragraph__fullwidth';
}
}
else {
$suggestions[] = 'paragraph__nowrap';
}
}
}
/**
* Implements hook_theme_suggestions_field_alter().
*/
function university_theme_theme_suggestions_field_alter(array &$suggestions, array $variables) {
$nowrap_fields = [
'field_author',
'field_block',
'field_department',
'field_hero_media',
'field_paragraphs',
'field_media',
'field_url',
'field_links',
'field_items',
'field_study_admission_reqs',
'field_study_application_code',
'field_study_application_date',
'field_study_contact',
'field_study_credits',
'field_study_duration',
'field_study_education_type',
'field_study_internationalization',
'field_study_intro',
'field_study_start_semester',
'field_study_teaching_methods',
'field_study_text',
'field_study_work_further_studies',
'field_subtitle',
];
if (in_array($variables['element']['#field_name'], $nowrap_fields)) {
$suggestions[] = 'field__nowrap';
}
}
/**
* Implements hook_theme_suggestions_field_alter().
*/
function university_theme_theme_suggestions_fieldset_alter(array &$suggestions, array $variables) {
}
/**
* Implements hook_preprocess_node().
*/
function university_theme_preprocess_node(array &$variables) {
// Get node author real name.
$author = $variables['node']->getOwner();
if ($author->id() == 0) {
$variables['author_name'] = t('Guest author');
}
else {
$fields = $author->getFields();
$first_name = $fields['field_first_name']->getString();
$last_name = $fields['field_last_name']->getString();
if ($first_name || $last_name) {
$author_name = $first_name . ' ' . $last_name;
if ($author->isActive()) {
$variables['author_name'] = Link::createFromRoute($author_name, 'entity.user.canonical', ['user' => $author->id()]);
}
else {
$variables['author_name'] = ['#plain_text' => $author_name];
}
}
}
// Get copyright and/or authors from featured media.
if (!empty($variables['elements']['field_hero_media'][0]['#media'])) {
$copyright = [];
$hero_media = $variables['elements']['field_hero_media'][0]['#media'];
if ($hero_media->bundle() == 'gallery') {
$media_images = $hero_media->get('field_media_images');
$media_ids = array_column($media_images->getValue(), 'target_id');
$images = Media::loadMultiple($media_ids);
foreach ($images as $image) {
if ($txt = $image->get('field_copyright')->getString()) {
$copyright[] = $txt;
}
}
}
elseif ($txt = $hero_media->get('field_copyright')->getString()) {
$copyright[] = $txt;
}
if (!empty($copyright)) {
$variables['photo_author_name'] = implode(', ', $copyright);
}
}
// Dates.
$created_time = $variables['node']->getCreatedTime();
$date_formatter = \Drupal::service('date.formatter');
$variables['created_time'] = $date_formatter->format($created_time, 'custom', 'd. F Y');
$variables['created_datetime'] = $date_formatter->format($created_time, 'html_datetime');
$updated_time = $variables['node']->get('changed')->value;
if ($updated_time && $updated_time != $created_time) {
$variables['updated_time'] = \Drupal::service('date.formatter')
->format($updated_time, 'custom', 'd.F Y');
$variables['updated_datetime'] = \Drupal::service('date.formatter')
->format($updated_time, 'html_datetime');
}
// Event.
if ($variables['node']->bundle() == 'event') {
// Dates.
if (!empty($variables['content']['field_date_from']['#items'])) {
$from_timestamp = strtotime($variables['content']['field_date_from'][0]['#attributes']['datetime']);
$from_day = $date_formatter->format($from_timestamp, 'custom', 'j');
$from_month = $date_formatter->format($from_timestamp, 'custom', 'M');
$from_hour = $date_formatter->format($from_timestamp, 'custom', 'H.i');
$variables['event']['datetime'] = $date_formatter->format($from_timestamp, 'html_datetime');
$variables['event']['day'] = $from_day;
$variables['event']['month'] = $from_month;
$variables['event']['hour'] = $from_hour;
if (!empty($variables['content']['field_date_to']['#items'])) {
$to_timestamp = strtotime($variables['content']['field_date_to'][0]['#attributes']['datetime']);
$to_day = $date_formatter->format($to_timestamp, 'custom', 'j');
$to_month = $date_formatter->format($to_timestamp, 'custom', 'M');
$to_hour = $date_formatter->format($to_timestamp, 'custom', 'H.i');
if ($from_day != $to_day) {
$variables['event']['day'] .= '-' . $to_day;
}
if ($from_hour != $to_hour) {
$variables['event']['hour'] .= ' - ' . $to_hour;
}
if ($from_month != $to_month) {
$variables['event']['month'] .= '/' . $to_month;
}
}
}
// Location.
if (!empty($variables['content']['field_location']['#items'])) {
$variables['content']['location'] = $variables['content']['field_location']['#items']->getString();
if (!empty($variables['content']['field_location_url']['#items'])) {
$url = $variables['content']['field_location_url'][0]['#url'];
$link_options = [
'attributes' => [
'class' => [
'location',
'icon-map-marker',
],
'target' => ['_blank'],
],
];
$url->setOptions($link_options);
$variables['content']['location_url'] = Link::fromTextAndUrl($variables['content']['location'], $url);
}
}
// CTA.
if (!empty($variables['content']['field_link']['#items'])) {
$link = $variables['content']['field_link']['#items']->get(0)
->getValue();
$variables['event']['cta']['label'] = empty($link['title']) ? t('Sign up!') : $link['title'];
$variables['event']['cta']['url'] = $variables['content']['field_link'][0]['#url'];
}
}
elseif ($variables['node']->bundle() == 'study') {
if ($variables['view_mode'] == 'full') {
// _university_theme_add_study_information($variables);
// _university_theme_add_study_plan($variables);
// _university_theme_add_study_insights($variables);
// _university_theme_add_study_cta($variables);
}
else {
// TODO: other view modes needs processing?
}
}
}
/**
* Add study information nodes to study program content type.
*
* @param array $variables
*/
function _university_theme_add_study_information(array &$variables) {
if (!empty($variables['elements']['field_study_program']['#items'])) {
$study_program = $variables['elements']['field_study_program']['#items']->getString();
$result = \Drupal::entityQuery('node')
->condition('status', 1)
->condition('type', 'study_information')
->condition('field_study_program.entity.tid', $study_program)
->sort('created', 'DESC')
->range(0, 1)
->execute();
if ($result) {
$node = Node::load(reset($result));
$node_view = \Drupal::entityTypeManager()
->getViewBuilder('node')
->view($node, 'full');
$variables['study_information'] = $node_view['#node']->getFields();
}
}
}
/**
* Add study plan to study program content type.
*
* @param array $variables
*/
function _university_theme_add_study_plan(array &$variables) {
// Get study plan from EmWeb.
$program = '';
$elements = $variables['elements'];
$emweb_installation = 'https://ny.emweb.no';
if (!empty($elements['field_study_program']['#items'])) {
$program = $elements['field_study_program'][0]['#title'];
}
$client = new Client(['base_uri' => $emweb_installation]);
try {
$query = ['filter[studyProgram.shortName]' => $program];
$response = $client->request('GET', '/[INSTALLATION_PATH]/nn/api/v1.0/pd', [
'query' => $query,
]);
} catch (RequestException $e) {
}
if (isset($response) && $response->getStatusCode() == 200) {
$response_body = json_decode($response->getBody(), TRUE);
if (!empty($response_body['data'])) {
$plans = [];
foreach ($response_body['data'] as $plan) {
if ($plan['attributes']['gateflow_done'] == TRUE
&& !empty($plan['attributes']['year'])
) {
$plans[$plan['attributes']['year']['label']] = $plan;
}
}
if (!empty($plans)) {
sort($plans);
$plan_id = end($plans)['id'];
$plan_res = $client->request('GET', '/[INSTALLATION_PATH]/nn/rendered/' . $plan_id);
if ($plan_res->getStatusCode() == 200) {
$path = \Drupal::service('path.current')
->getPath();
$study_plan = json_decode($plan_res->getBody());
$study_plan = str_replace('="studieplan', '="' . $path, $study_plan);
$variables['study_plan'] = ['#markup' => $study_plan];
}
}
}
}
}
/**
* Add study insights to study program content type.
*
* @param array $variables
*/
function _university_theme_add_study_insights(array &$variables) {
$view = Views::getView('related_content');
if ($insights = $view->render('insights')) {
$variables['study_insights'] = $insights;
}
}
/**
* Add study CTA button or text to study program content type.
*
* @param array $variables
*/
function _university_theme_add_study_cta(array &$variables) {
if (!empty($variables['elements']['field_study_admission_type']['#items'])) {
$study_cta = [];
$tid = $variables['elements']['field_study_admission_type']['#items']->getString();
$admission_type = Term::load($tid);
if ($admission_type->hasField('field_study_cta')) {
$study_cta = $admission_type->get('field_study_cta');
}
if (!empty($study_cta[0])) {
$text = !empty($study_cta[0]->title) ? $study_cta[0]->title : t('Search for a study place!');
if ($study_cta[0]->uri == '#') {
$variables['study_cta'] = Markup::create('<span class="btn">' . $text . '</span>');
}
else {
$options = [
'attributes' => [
'target' => '_blank',
'rel' => 'nofollow',
'class' => ['btn'],
],
];
$url = Url::fromUri($study_cta[0]->uri, $options);
$variables['study_cta'] = Link::fromTextAndUrl($text, $url);
}
}
elseif ($admission_type->getName() == 'Stengt for søking') {
$text = t('Closed for application');
$variables['study_cta'] = Markup::create('<span class="btn">' . $text . '</span>');
}
}
}
/**
* Implements hook_theme_suggestions_views_view_alter().
*/
function university_theme_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
$suggestions[] = 'views_view__' . $variables['view']->id();
}
/**
* Implements hook_theme_suggestions_views_view_unformatted_alter().
*/
function university_theme_theme_suggestions_views_view_unformatted_alter(array &$suggestions, array $variables) {
if ($variables['view']->id() == 'related_content') {
$suggestions[] = 'views_view__nowrap';
}
}
/**
* Implements hook_preprocess_form().
*/
function university_theme_preprocess_form(array &$variables) {
if ($variables['element']['#id'] == 'views-exposed-form-study-page') {
$variables['attributes']['class'][] = 'filter-study';
$variables['attributes']['class'][] = 'grid-three';
}
elseif ($variables['element']['#id'] == 'views-exposed-form-search-api-sok') {
}
}
/**
* Implements hook_form_alter().
*
* @param $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
* @param $form_id
*/
function university_theme_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form['#id'] == 'views-exposed-form-search-api-sok') {
$form['keys']['#placeholder'] = t('Search on university');
$form['keys']['#prefix'] = '<div class="input-button-group input-underline">';
$form['actions']['#suffix'] = '</div>';
$form['actions']['submit']['#value'] = '';
$form['actions']['submit']['#attributes']['class'] = [
'btn-search',
'input-btn-search',
];
}
elseif ($form['#id'] == 'views-exposed-form-employees-page') {
$form['name']['#prefix'] = '<div class="input-button-group">';
$form['name']['#suffix'] = '</div>';
}
}
/**
* Prepares variables for form element templates.
*
* @param array $variables
*/
function university_theme_preprocess_form_element(&$variables) {
if ($variables['type'] == 'checkbox') {
$variables['attributes']['class'][] = 'checkbox-group';
}
}
/**
* Implements hook_preprocess_select().
*/
function university_theme_preprocess_select(array &$variables) {
//$variables['attributes']['class'][] = 'select-chosen';
}
/**
* Implements hook_preprocess_field().
*/
function university_theme_preprocess_field(array &$variables) {
if ($variables['field_name'] == 'field_tags') {
foreach ($variables['items'] as $key => $item) {
$variables['items'][$key]['content']['#attributes']['class'] = 'tag-link';
}
}
elseif ($variables['field_name'] == 'field_column_items') {
foreach ($variables['items'] as $key => $item) {
if ($item['content']['#paragraph']->bundle() == 'text') {
$variables['items'][$key]['content']['#attributes']['class'] = 'copy';
}
}
}
}
/**
* Implements hook_preprocess_paragraph().
*/
function university_theme_preprocess_paragraph(array &$variables) {
$bundle = $variables['paragraph']->bundle();
$content = &$variables['content'];
if ($bundle == 'link') {
$parent = $variables['paragraph']->getParentEntity();
if ($parent && $parent->bundle() == 'links') {
$parent_fields = $parent->getFields();
if (!empty($parent_fields['field_links_variant'])) {
$variables['links_variant'] = $parent_fields['field_links_variant']->getString();
}
else {
$variables['links_variant'] = 'regular';
}
$variables['attributes']['class'][] = 'grid-item';
}
elseif (!empty($content['field_links_variant']['#items'])) {
$variables['links_variant'] = $content['field_links_variant']['#items']->getString();
switch ($variables['links_variant']) {
case 'button':
$variables['attributes']['class'][] = 'widget-btn-link';
break;
case 'box':
$variables['attributes']['class'][] = 'widget-box-link';
break;
default:
$variables['attributes']['class'][] = 'widget-link';
break;
}
}
else {
$variables['links_variant'] = 'regular';
$variables['attributes']['class'][] = 'widget-link';
}
}
elseif ($bundle == 'links') {
if (!empty($content['field_links_variant']['#items'])) {
switch ($content['field_links_variant']['#items']->getString()) {
case 'button':
$variables['attributes']['class'][] = 'widget-btn-link';
break;
case 'box':
$variables['attributes']['class'][] = 'widget-box-link';
break;
default:
$variables['attributes']['class'][] = 'widget-link';
break;
}
hide($content['field_links_variant']);
}
else {
$variables['attributes']['class'][] = 'widget-link';
}
}
elseif ($bundle == 'banner') {
if (!empty($content['field_banner_variant']['#items'])) {
$variant = $content['field_banner_variant']['#items']->getString();
}
if (empty($variant)) {
$variant = 'banner_media';
}
if (!empty($content['field_banner_height']['#items'])) {
$variables['attributes']['class'][] = $content['field_banner_height']['#items']->getString();
}
if (!empty($content['field_banner_overlay']['#items'])) {
$overlay = (int) $content['field_banner_overlay']['#items']->getString();
if ($overlay === 1) {
$variables['attributes']['class'][] = 'overlay';
}
}
if (!empty($content['field_media']['#items'])) {
$media_fields = $content['field_media'][0]['#media']->getFields();
$fid = $media_fields['field_image']->getValue()[0]['target_id'];
$image_style = ImageStyle::load($variant);
if ($image_style && ($file = File::load($fid))) {
$image_uri = $image_style->buildUrl($file->getFileUri());
$variables['banner_image'] = Url::fromUri(file_create_url($image_uri));
}
}
switch ($variant) {
case 'banner_media_wide':
$variables['attributes']['class'][] = 'full-width';
break;
default:
$variables['attributes']['class'][] = 'row-space-medium';
break;
}
}
elseif ($bundle == 'dynamic_list') {
// $variables['content']['view'] = _university_theme_get_dynamic_list($content);
if (!empty($content['field_content_type']['#items'])) {
$variables['attributes']['class'][] = $content['field_content_type']['#items']->getString();
}
}
// Add paragraph attributes.
if (!empty($content['field_row_width']['#items'])) {
$variables['attributes']['class'][] = 'row-' . $content['field_row_width']['#items']->getString();
hide($content['field_row_width']);
}
if (!empty($content['field_row_columns']['#items'])) {
$type = ($bundle == 'list' || $bundle == 'dynamic_list') ? 'carousel' : 'grid';
$variables['attributes']['class'][] = $type . '-' . $content['field_row_columns']['#items']->getString();
hide($content['field_row_columns']);
}
if (!empty($content['field_row_space']['#items'])) {
$variables['attributes']['class'][] = 'row-' . $content['field_row_space']['#items']->getString();
hide($content['field_row_space']);
}
if (!empty($content['field_row_bg']['#items'])) {
$variables['attributes']['class'][] = 'bg-' . $content['field_row_bg']['#items']->getString();
hide($content['field_row_bg']);
}
}
/**
* Implements hook_preprocess_details().
*/
function university_theme_preprocess_details(array &$variables) {
/*$variables['attributes']['class'][] = 'details';
$variables['summary_attributes']['class'] = 'summary';*/
}
/**
* Implements hook_theme_suggestions_details_alter().
*/
function university_theme_theme_suggestions_details_alter(array &$suggestions, array $variables) {
}
/**
* Implements hook_preprocess_menu_local_task().
*/
function university_theme_preprocess_menu_local_task(array &$variables) {
//$variables['element']['#link']['url']->setOption('attributes', ['class'=>'rounded']);
}
/**
* Implements hook_preprocess_menu().
*/
function university_theme_preprocess_menu(array &$variables) {
if (
$variables['menu_name'] == 'main'
|| $variables['menu_name'] == 'main-english'
|| $variables['menu_name'] == 'top'
|| $variables['menu_name'] == 'top-english') {
foreach ($variables['items'] as $key => $item) {
$variables['items'][$key]['attributes']->addClass('nav-item');
}
if ($variables['menu_name'] == 'main' || $variables['menu_name'] == 'main-english') {
$variables['attributes']['class'][] = 'nav-primary';
}
elseif ($variables['menu_name'] == 'top' || $variables['menu_name'] == 'top-english') {
$variables['attributes']['class'][] = 'nav-secondary';
}
}
elseif ($variables['menu_name'] == 'social-links') {
$variables['attributes']['class'][] = 'social-links';
foreach ($variables['items'] as $key => $item) {
$variables['items'][$key]['attributes']->addClass('social-link');
$attributes = $item['url']->getOption('attributes');
if (!empty($attributes['class'])) {
$variables['items'][$key]['attributes']->addClass($attributes['class']);
}
}
}
elseif ($variables['menu_name'] == 'admission-information' || $variables['menu_name'] == 'professional-information') {
$variables['attributes']['class'][] = 'list-icons';
}
// Add translation links.
if ($variables['menu_name'] == 'top' || $variables['menu_name'] == 'top-english') {
_university_theme_add_language_links($variables);
}
}
/**
* Add language switcher links
*
* @param array $variables
*/
function _university_theme_add_language_links(array &$variables) {
$route_name = \Drupal::service('path.matcher')
->isFrontPage() ? '<front>' : '<current>';
$switch_links = \Drupal::languageManager()
->getLanguageSwitchLinks('language_interface', Url::fromRoute($route_name));
if (!empty($switch_links->links)) {
$langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
foreach ($switch_links->links as $lang => $link) {
if ($lang != $langcode) {
$url = $link['url'];
$url->setOption('language', $link['language']);
$attributes = new Attribute(['class' => ['nav-item']]);
$variables['items'][$lang] = [
'url' => $url,
'title' => $link['title'],
'attributes' => $attributes,
];
}
}
}
}
/**
* Implements hook_preprocess_breadcrumb().
*/
function university_theme_preprocess_breadcrumb(&$variables) {
if ($variables['breadcrumb'] && !\Drupal::service('path.matcher')
->isFrontPage()) {
// Add current page title to breadcrumb.
$request = \Drupal::request();
$route_match = \Drupal::routeMatch();
$route_name = $route_match->getRouteName();
$node_url = NULL;
if ($route_name == 'entity.user.canonical') {
$params = $route_match->getParameters();
if ($params->has('user')) {
$user_account = $params->get('user');
if ($department = $user_account->get('field_department')) {
$term_view = $department->view();
if (isset($term_view[0]['#options']['entity'])) {
$term_id = $term_view[0]['#options']['entity']->id();
$department = '/employees?department[' . $term_id . ']=' . $term_id;
$department_url = Url::fromUserInput($department);
$variables['breadcrumb'][] = Link::fromTextAndUrl($term_view[0]['#title'], $department_url);
}
}
$user_fields = [];
if ($first_name = $user_account->get('field_first_name')) {
$user_fields[] = $first_name->getString();
}
if ($last_name = $user_account->get('field_last_name')) {
$user_fields[] = $last_name->getString();
}
if (!empty($user_fields)) {
$title = implode(' ', $user_fields);
}
else {
$title = $user_account->get('name')->getString();
}
}
}
elseif ($route_name == 'entity.node.canonical') {
$node = $route_match->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
$node_url = $node->toUrl()->toString();
}
}
// Remove 'Node' and 'Front' link.
// todo: provide proper breadcrumb through custom module.
foreach ($variables['breadcrumb'] as $key => $crumb) {
if (is_array($crumb)
&& isset($crumb['text'])
&& ($crumb['text'] == 'Node' || $crumb['text'] == 'Front')) {
unset($variables['breadcrumb'][$key]);
}
}
if (empty($title)) {
$title = \Drupal::service('title_resolver')
->getTitle($request, $route_match->getRouteObject());
}
$variables['breadcrumb'][] = ['text' => $title];
// Handle cache. Invalidate by url.
$variables['#cache']['contexts'][] = 'url';
}
else {
$variables['breadcrumb'] = '';
}
}
/**
* Implements hook_preprocess_media().
*/
function university_theme_preprocess_media(&$variables) {
if (!empty($variables['elements']['field_copyright'][0])
|| !empty($variables['elements']['field_description'][0])
) {
$variables['caption'] = TRUE;
$variables['attributes']['class'][] = 'caption-overlay';
}
else {
$variables['caption'] = FALSE;
}
if ($variables['elements']['#view_mode'] == 'embed') {
// TODO: create a formatter or move this to custom module.
if (isset($variables['content']['field_file'][0])) {
$file_uri = $variables['content']['field_file'][0]['#file']->getFileUri();
$file_url = file_create_url($file_uri);
$variables['content']['name'][0]['#url'] = Url::fromUri($file_url);
unset($variables['content']['field_file']);
}
}
}
/**
* Implements hook_preprocess_slick().
*/
function university_theme_preprocess_slick(&$variables) {
$variables['attributes']['class'][] = 'slick-slider';
}
/**
* Implements hook_preprocess_user().
*/
function university_theme_preprocess_user(array &$variables) {
$elements = $variables['elements'];
$user = $elements['#user'];
// Email is a protected property on the template. So let's add a template var.
$variables['email'] = $user->getEmail();
}
/**
* Implements hook_preprocess_views_view__VIEWNAME().
*
* @param $variables
*/
function university_theme_preprocess_views_view__study(&$variables) {
// TODO: figure out why we even have to set this! :\
$variables['title'] = $variables['view']->getTitle();
_university_theme_exposed_input_permalink($variables);
}
/**
* Implements hook_preprocess_views_view__VIEWNAME().
*
* @param $variables
*/
function university_theme_preprocess_views_view__employees(&$variables) {
// TODO: figure out why we even have to set this! :\
$variables['title'] = $variables['view']->getTitle();
_university_theme_exposed_input_permalink($variables);
}
/**
* Helper function to build a permalink for a exposed views form.
*
* @param $variables
*/
function _university_theme_exposed_input_permalink(&$variables) {
if (\Drupal::currentUser()->hasPermission('link to any page')) {
$params = [];
$exposed_input = $variables['view']->getExposedInput();
if (!empty($exposed_input)) {
if (isset($exposed_input['ajax_page_state'])) {
unset($exposed_input['ajax_page_state']);
}
foreach ($exposed_input as $param => $input) {
if ($param == 'name' || $param == '_wrapper_format') {
continue;
}
foreach ($input as $key => $value) {
if (!empty($value)) {
$params[] = $param . '[' . $key . ']=' . $value;
}
}
}
}
if (!empty($params)) {
$view_url = $variables['view']->getUrl()->toString();
$params = implode('&', $params);
$variables['permalink'] = $view_url . '?' . $params;
}
}
}
/**
* Helper to retrieve Dynamic List view render.
*/
function _university_theme_get_dynamic_list($content) {
static $tag = 1;
// Number of items.
$quantity = 3;
if (!empty($content['field_quantity']['#items'])) {
$quantity = (int) $content['field_quantity']['#items']->getString();
}
// Content type.
$type = 'article';
if (!empty($content['field_content_type']['#items'])) {
$type = $content['field_content_type']['#items']->getString();
}
// Build view.
$view = Views::getView('dynamic_list');
$view->setItemsPerPage($quantity);
$display = &$view->storage->getDisplay('default');
$filters = &$display['display_options']['filters'];
$sorts = &$display['display_options']['sorts'];
// Type.
$filters['type']['value'] = [$type => $type];
// Filters
if ($type !== 'event') {
unset($filters['field_date_from_value']);
}
// Category.
if (!empty($content['field_taxonomy']['#items'])) {
$filters['tid']['value'] = (int) $content['field_taxonomy']['#items']->getString();
}
else {
unset($filters['tid']);
}
// Sorting
if ($type === 'event') {
unset($sorts['created']);
}
else {
unset($sorts['field_date_from_value']);
}
$node = \Drupal::routeMatch()->getParameter('node');
if ($node) {
// TODO: remove logic after drupal.org/node/2730631 is in core.
if (is_string($node)) {
$nid = (int) $node;
}
else {
$nid = $node->id();
}
$cache_tag = 'dynamic_list:' . $nid . ':' . $tag; // TODO: Add valid tag.
$view->storage->addCacheTags([$cache_tag]);
$tag++;
}
return $view->buildRenderable();
}
/**
* Implements hook_preprocess().
*/
function university_theme_preprocess_block_shariff(&$variables) {
// Get settings.
$settings = _shariff_get_settings($variables['blocksettings']);
// Sort services.
if (!empty($settings['services'])) {
asort($settings['services']);
}
// Build data attributes and escape settings.
$data = [];
foreach ($settings as $key => $setting) {
if (!empty($setting)) {
switch ($key) {
case 'services':
$value = '["' . implode('","', $setting) . '"]';
break;
case 'referrer_track':
$value = urlencode(Html::escape($setting));
break;
case 'backend_url':
case 'url':
case 'mail_url':
case 'media_url':
$value = Html::escape(UrlHelper::stripDangerousProtocols($setting));
break;
case 'twitter_via':
case 'mail_subject':
case 'mail_body':
case 'flattr_user':
case 'flattr_category':
default:
$value = Html::escape($setting);
break;
case 'shariff_theme':
$value = Html::escape($setting);
$key = 'theme';
break;
case 'lang':
$value = $setting;
break;
}
// Shariff requires data-attributes with dashes instead of underscores.
$data['data-' . str_replace('_', '-', $key)] = $value;
}
}
// See https://www.drupal.org/node/1727592.
$variables['data_attributes'] = new Attribute($data);
// Load shariff library.
$variant = isset($settings['css']) ? $settings['css'] : 'complete';
$variables['#attached'] = [
'library' => [
'shariff/shariff-' . $variant,
],
];
}
/**
* Prepares variables for facets summary item list templates.
*
* @param $variables
*/
function university_theme_preprocess_facets_summary_item_list(&$variables) {
$items = &$variables['items'];
// Hide and move reset link to the bottom.
if (!empty($items[0]['value']['#type'])
&& $items[0]['value']['#type'] == 'link') {
$reset_link = $items[0];
unset($items[0]);
if (count($items) > 1) {
$items[] = $reset_link;
}
}
} |
---
title: How to Reset your Oppo A59 5G Lock Screen Password
date: 2024-05-19T14:17:28.865Z
updated: 2024-05-20T14:17:28.865Z
tags:
- unlock
- remove screen lock
categories:
- android
description: This article describes How to Reset your Oppo A59 5G Lock Screen Password
excerpt: This article describes How to Reset your Oppo A59 5G Lock Screen Password
keywords: Oppo A59 5G oem unlock missing,Oppo A59 5G lock screen pattern,remove screen lock pin on android,Oppo A59 5G fingerprint not working,how to change lock screen password,android device password reset,android password reset,unlock,how to use oem unlocking
thumbnail: https://www.lifewire.com/thmb/koSaGJ5iVSnQrrvXh53lyy1rSZM=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/podcasts-safeforkids-5b2f3dd4eb97de0036d9f87b.jpg
---
## How to Reset your Oppo A59 5G Lock Screen Password
Android phones have the option of locking the screen using a PIN, pattern, or password. This is meant to keep the phone secure and prevent any unwanted intrusion. PINs and patterns are somewhat easy to remember, but it is common to forget the Android lock screen password. The phone gets locked if someone consecutively enters the wrong password multiple times. Then it is a common question to ask, "How to reset your Android password?"
The device becomes inaccessible and requires an Android password reset. But there is no easy way to do that. Either one needs their Gmail account or has to forget about getting back the Android data. Today we will deliver how to reset Android passwords and teach 6 useful ways. They can be used to reset the Android password and use the phone again. But if someone has to perform a factory restore, they need to depend on backups to get back the data. Now let's begin with the first way and learn how to reset your Android phone password.
<iframe width="560" height="315" src="https://www.youtube.com/embed/yjlTG2d0gSY" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="allowfullscreen"></iframe>
safe & secure
## Solution 1: Dr.Fone - Screen Unlock (Android): A Direct Way to Unlock the Phone
Using [Dr.Fone - Screen Unlock (Android)](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) is a direct way to Android reset the password and unlock the phone. There is no tension of data loss, and this [phone unlocking software](https://drfone.wondershare.com/sim-unlock/android-unlock-software.html) works for different lock systems. It can reset the Android password, pattern, PIN, and fingerprint lock in under 5 minutes. It is straightforward to operate and does not require any technical knowledge.
Wondershare offers you 100% security as it only authorizes you access. It is simple and user-friendly and keeps all the data on the Android device ( Samsung and LG only) intact.

### [Dr.Fone - Screen Unlock (Android)](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/)
Get into Locked Android Phones Within Minutes
- 4 screen lock types are available: pattern, PIN, password & fingerprints.
- Easily remove the lock screen; No need to root your device.
- Unlock 20,000+ models of Android phones & tablets.
- Provide specific removal solutions to promise good success rate
**4,008,669** people have downloaded it
### How to reset an Android phone password with Dr.Fone - Screen Unlock (Android)
**Step 1: Select "Screen Unlock"**
Open the program. After that, select and click on "Screen Unlock" on the right side of the window. With this option, you can Android reset your password and remove the lock screen of PIN, password, pattern, and fingerprints.

Now get the Android phone connected to the PC and select the Oppo A59 5G device model in the list to proceed.

**Step 2: Activate download mode**
You have to put your device into download mode. For that, follow the instructions given by Wondershare:
- 1\. Switch off the Android device
- 2\. Tap and keep holding the volume decrease button along with the power and home button simultaneously
- 3\. Now tap the volume increase button to initiate download mode

**Step 3: Download the recovery package**
After the download mode has been entered, the program will begin to download the recovery package automatically. You have to hold your horses until it is complete.

**Step 4: Remove the Android password without data loss**
Soon the recovery package finishes downloading. Then the program begins to remove the lock screen. After the process is over, you can access all your data on your Android device and reset your Android password.

These simple steps will ensure that you can secure your Android lock screen easily, without any worries. You do not have to worry about data loss, and you will reset your Android phone. Even if you have forgotten your Android password and are thinking about starting your Android phone again, these simple tips will help.
## Solution 2: How to reset Android Phone Password with Smart Lock?
Setting up Smart Lock on your Android device adds a convenient and straightforward method for unlocking your screen. Smart Lock provides different alternatives to bypass the lock screen based on specific situations.
These alternatives encompass trusted locations, connected devices, or facial recognition. For devices operating on Android 14, it's now referred to as Extend Unlock. Here's a guide on utilizing Smart Lock to unlock your Android device:
**Step 1.** Set a pattern, PIN, or password for your screen lock if you haven't already. Open the Settings on your Android device and tap on "Security & Privacy." Here, tap "More Security & Privacy" and select "Trust agents."

**Step 2.** Within "Trust agents," toggle on "Extend Unlock" and then return to the previous screen. Select "Extend Unlock" and input your pattern, PIN, or password to confirm. Next, pick your desired Smart Lock type and follow the on-screen prompts to activate.

## Solution 3: How to Unlock Samsung Phone with SmartThings?
Unlocking an Android phone using SmartThings is an option available for Samsung devices. SmartThings offers remote control and management of Samsung devices. It also includes the ability to unlock your phone under specific conditions. Here's a general guide on how to use SmartThings to unlock your Samsung phone:
**Step 1.** Access the SmartThings website, where you should click on the “Sign In” button. Now log in using your Samsung Account, and you'll be directed to a new screen displaying a map pinpointing your phone's location.

**Step 2.** Select the "Unlock" button located in the top right corner of the menu. Then, proceed by clicking "Unlock," and entering your Samsung password. Finally, confirm by clicking Unlock once more. This action will reset all your lock settings, comprising biometric security, PIN, password, and swipe pattern.

## Solution 4: How to Reset Android Password using Google?
To reset the Android password using Google, it is necessary to remember the Google password and ID. Google account must also be activated on the phone. Also, this method only works on devices running Android 4.4 or below. Follow the steps below for the Android password reset.
**Step 1: Access Google login**
Enter the wrong password 5 times till the Android device gives you a "Forgot password?" prompt. Click on the tab and choose "Enter Google Account details."

**Step 2: Enter credentials and do an Android reset password**
Now enter the Google ID and password and log in. You will be able to Android reset your password and get access to your phone.

## Solution 5: How to Reset Android Password using Android Device Manager?
Familiar with Android Device Manager? Well, it has been renamed now as Find My Device. This service provided by Google helps you find, lock, or wipe your Android device. Plus, if you have enabled Find My Device, it might prove very helpful to assist you in unlocking your device. Check out these easy-to-follow steps for unlocking your Android device. For this, you need to use Find My Device, the upgraded Android Device Manager:
**Instructions.** On a computer or another device, go to the “[Google Find My Device](https://www.google.com/android/find/)” website. Here, sign in using your Google account linked to the locked Android device. Once you've logged in, the website will present a map revealing the most recent location of your device. Next, navigate to the left side and select "Erase Device." Follow the prompts on the screen to finalize the process.

## Solution 6: How to reset Android Phone Password using Factory Reset?
This method can be used when no other means of Android password reset works. This will erase all your data, so it is better to have backups created before. Now perform the steps to Android reset the password.
**Step 1: Initiate factory restore.**
Turn your Android device off. Press and hold the power button + home button + volume up button. This will bring up the recovery mode to initiate factory restoration.

**Step 2: Factory restore**
Now use the volume +/- button to navigate to the "Wipe Data / Factory Reset" option and press the power button to select it. Wait till the process complete.

**Step 3: Reboot and reset the password.**
From the available options, choose "Reboot System Now." After the Android device powers on, you will be able to do the Android password reset.
## Bonus Part: Useful Tips to Prevent Future Lockouts on Android
Here are some helpful tips to prevent future lockouts on your Android device and ensure better password management.
- **1\. Use Password Managers**: Consider using reputable password manager apps that securely store and manage your passwords. These apps often have features to generate strong, unique passwords for different accounts and help you remember them.
- **2\. Set up Biometric Authentication**: In case your device supports it, use biometric authentication methods for a better experience. These can be fingerprints or facial recognition. These methods can be more convenient than remembering passwords and offer added security.
- **3\. Create Memorable Passwords**: If you opt against using a password manager, craft robust yet easily remembered passwords. To improve your security, try to use a sequence of lowercase and uppercase letters, numbers, and symbols. Plus, avoid easily guessable details like birthdays or common phrases to make your password strong.
- **4\. Enable Two-Factor Authentication (2FA)**: Enable two-factor authentication whenever possible for your accounts. Likewise, this provides an added layer of security by requiring a secondary verification method. It could be a text message code or authentication app in addition to your password.
- **5\. Regularly Back Up Your Data**: Make it a habit to consistently [back up your device data](https://tools.techidaily.com/wondershare/drfone/android-backup-and-restore/). To prevent potential data loss from forgotten passwords or unexpected issues, take precautions. Safeguard your crucial data by creating backups, whether in the cloud or on an external storage device.
## Conclusion
This article guided all the possible ways available in 2024 to reset your Android lock screen password, such as using the Smart Lock, Google Find My, Samsung SmartThings, and Wondershare Dr.Fone - Screen Unlock (Android). The most recommended method out of these methods is Dr.Fone because it can handle all Android brands without restrictions.
On the other hand, other methods have their limitations. For example, SmartThings can only work for Samsung smartphones. Moreover, Wondershare Dr.Fone - Screen Unlock (Android) is compatible with Android 14 and can unlock the screen within 2 minutes.
## How to Unlock Oppo A59 5G Phone without Google Account?
Uh oh – you’ve forgotten your Android Unlock code, and you can’t get it online to unlock using Google. Nothing could be more frustrating than gazing at your phone, knowing that it is essentially a paperweight at this point. Unless you can get it unlocked, your phone is useless, and all of your important photos, text messages, and content are all locked out of your reach. While right now, nothing can do without a Google account. But you can try to reset your Google account first.
## Part 1: How to Bypass Lock Screen on Android device with Google Account (Android Device Manager)
Even if you have a Google account, if your phone isn’t connected to the internet, you cannot access it to unlock your phone. If this sounds familiar, you can always try this method.
1\. First, navigate to the Android Device Manager page. You will need to sign in with the Google account that you use to set up your phone.
Android Device Manager link: <http://www.google.com/android/devicemanager>

2\. Once you have logged in, you will automatically be redirected to the Android Device Manager page. If this is your first time, click the “Accept” button.

3\. A list of all of the Oppo A59 5G devices registered to this Android account will pop up. Select the Oppo A59 5G device in question from this list.

4\. The Android Device Manager will then locate your device. Make sure it is turned on!

5\. After it has been located, you will have a few options for what to do next. If you do not know your phone's location, you can call it from this screen, but if you know where it is, click the ‘Enable Lock & Erase’ option.

6\. A notification will pop up on your device; confirm it.

7\. At this point, you will be asked to create a new lock screen password. Once you have chosen one, press “Lock.”

8\. Now, simply enter the new passcode on your device, and voila! It will open, and you can get back to your daily routine.
## Part 2: How to Reset Your Google Account on your Android Phone
If you have forgotten your Google Account password, it is still possible to unlock your account and access the information within. Here is how you can unlock your Google account on your Android phone.
1\. On your browser, go to the Google home page and try to sign in. You will fail, but that is good! It will lead you to the next step.

2\. Since you cannot sign in on the sign-in page, you can now select the ‘Help’ link.

3\. Choose the “forgot password” option. You will be prompted to enter your email address to proceed.

4\. Two options will then appear: the first is your phone number, and the other asks you for your backup email.

5\. Enter either one of these options, and you will receive a verification code via email, SMS, or a telephone call from an operator. If you have chosen to enter your backup email, at this point, you will receive detailed instructions on how to access the ‘reset password’ page.

6\. Once you have been redirected to the ‘reset password’ page, you can input your new login information.

7\. Finally, you can unlock your Google account on your Android! Confirm this by clicking the “Change Password” button. Success!

## Part 3. How to Remove Locked Screen on Android using Dr.Fone
It supports removing screen lock from mainstream models, such as Samsung, LG, Lenovo, Xiaomi, etc. For some older version Samsung models, you can remove the lock without data loss. It will erase data after unlocking for other models.
### [Dr.Fone - Android Lock Screen Removal](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/)
Remove Android Screen Lock In One Click
- Pattern, PIN, password, fingerprints & face screen lock can all be unlocked.
- Bypass Android FRP lock without a PIN or Google account.
- No tech knowledge asked. Everybody can handle it.
- It will complete the unlocking process in minutes.
**3,981,454** people have downloaded it
### How to use Dr.Fone to unlock
**Step 1:** Install Dr.Fone toolkit and select Screen Unlock > Android > Unlock Android Screen.

Now connect your Android phone connected with the PC, and select the Oppo A59 5G device brand from the list.

**Step 2:** Follow the on-screen instructions to put your Android device into the specific mode. Once the download is complete, Dr.Fone will start the unlocking process.

**Step 3:** After the process is complete, your Android device should be unlocked, and you can access it without the screen lock.

## Conclusion
We know that losing or forgetting your Android lock code can be a real pain, and so these solutions are sure to put the smile back on your face and get you using your phone again as usual. As you can see, the [Dr.Fone - Screen Unlock (Android)](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) is a simple and reliable way to unlock your Android phone, but you can always try the Google option if you assess that it better suits your needs. No matter which solution you choose, your locked Android phone will be up and running again in no time at all.
## How To Enable USB Debugging on a Locked Oppo A59 5G Phone
Unlocking your Android’s potential goes beyond its surface features. Understanding USB debugging is key to troubleshooting and maximizing your device’s capabilities. In simple terms, USB debugging allows deeper access to your phone’s functionalities, aiding in software development and data recovery.
However, enabling USB debugging becomes crucial yet challenging when your phone is locked. This article delves into this necessity, explaining **how to enable USB debugging on locked phones**, especially for Android users. Unravel the mystery behind this essential feature, empowering yourself to navigate through locked phone scenarios effortlessly.

## Part I. Challenges in Enabling USB Debugging on a Locked Android Phone
USB debugging is a nifty tool that lets you peek behind the scenes of your Android phone’s software. It’s like having a secret key that unlocks deeper access to your device, enabling tasks like software tweaking, app testing, and even data recovery.

### Challenges in Enabling USB Debugging on a Locked Phone
Outlined below are some of the barriers, scenarios, and limitations, shedding light on the challenges that make USB debugging seemingly impossible.
- **Locked-out access.**When your phone is locked, gaining access to the settings becomes a roadblock to enabling USB debugging.
- **Limited functionality.**The phone’s locked state restricts the usual methods of accessing developer settings and USB debugging options.
- **Security measures.**For security reasons, most devices limit access to sensitive settings when the phone is locked, making it tricky to enable USB debugging.
### Scenarios Requiring USB Debugging on a Locked Phone
Unlocking your phone’s potential becomes crucial in moments of crisis. Explore below some of the scenarios where enabling USB debugging on a locked Android device becomes your beacon of hope:
- **Data recovery.**Imagine accidentally locking yourself out of your phone with important data inside. Enabling USB debugging could be your ticket to retrieve that precious information.
- **Software troubleshooting.**Sometimes, a locked phone might need software fixes or troubleshooting that requires USB debugging to access certain tools.
- **Device testing.**For developers or tech-savvy users, testing new apps or debugging software issues often demands enabling USB debugging, even when the phone is locked.
## Part II. How To Enable USB Debugging on Locked Phones
This section outlines the traditional method of enabling USB debugging on an Android phone. Stay tuned and check out the steps below:
- **Step 1:** Unlock your device**.** If needed, enter your phone’s passcode or pattern to gain access to the **Settings**.
- **Step 2:** Go to **Settings**, scroll down to **About Phone**, and tap on **Build number** seven or eight times to unlock the **Developer Options**.

**Step 3:** Once unlocked, return to **Setting**s, find **Developer Options** (usually at the bottom), and enter the menu. Enable USB Debugging by tapping **OK** once the **Allow USB Debugging?** message appears.

However, what if your phone remains locked, making these steps impossible? Such a case calls for an alternative solution. Fortunately, there is one tool that is fully reliable when it comes to unlocking locked mobile devices. [<u>Dr.Fone - Screen Unlock (Android)</u>](https://tools.techidaily.com/wondershare/drfone/drfone-toolkit/) can help bypass these challenges and enable USB debugging on a locked Android phone effortlessly. So, buckle up as the next section unravels the secrets to unlock your device’s potential!
## Part III. Seamlessly Unlock Your Android With a Professional Resolution
Enabling USB debugging on a locked phone can feel like navigating a maze with no clear exit. Sometimes, despite your best efforts, the traditional method fails to grant access. Fret not! There’s a smoother path that unlocks your phone and eases the USB debugging hurdle.

### Why Unlocking First Makes Sense
Attempting to **enable USB debugging on locked phones** can hit roadblocks. That’s why unlocking your device first becomes a game-changer. Dr.Fone – Screen Unlock (Android) is the hero of this story, simplifying the process and ensuring a hassle-free experience.
### Key Features and Benefits
Check out the amazing key features and benefits of Dr.Fone – Screen Unlock that fits Android devices:
- **Data safety and reliability.**Your data’s security remains paramount. With Dr.Fone – Screen Unlock, your device’s integrity and precious data stay safeguarded throughout the unlocking process.
- Dr.Fone - Screen Unlock is compatible with a wide range of Android devices, irrespective of brand or model, ensuring accessibility for various users.
- It’s not just about unlocking a locked screen; Dr.Fone offers multiple unlock modes tailored to different scenarios, whether a forgotten password, PIN, pattern, or fingerprint issue.
- **High success rate.**With a high success rate in unlocking locked screens, Dr.Fone - Screen Unlock provides a reliable solution, even for complex lock scenarios.
- **No data loss.**Users can rejoice in the fact that the unlocking process doesn’t compromise data integrity. Your photos, messages, and apps remain untouched and secure.
- **Ease of use.**The software is designed for simplicity, making the unlocking process accessible to users with varying levels of technical expertise.
_**Tips:** Forget your device password and can't get access to it? No worries as [Dr.Fone](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) is here to help you. Download it and start a seamless unlock experience!_
### Guide To Unlock Your Oppo A59 5G With Dr.Fone – Screen Unlock (Android)
Below are the steps on how you can unlock your Android device using Dr.Fone:
- **Step 1:** Get the most recent version of Wondershare Dr.Fone and connect your Android device to your computer via a USB cord. After connecting, access the unlock screen tool by going to the **Toolbox** and then selecting **Screen Unlock**.
- **Step 2:** Once prompted, choose **Android** to unlock your Android screen lock. On the following screen, you’ll see two options; choose **Unlock Android Screen**.

- **Step 3:** After that, you’ll be taken to a new screen where you can choose the brand of your mobile device.

- **Step 4:** Once done, click the **Remove without Data Loss** button from the two options presented on the screen.

- **Step 5:** Unlocking the Android screen requires choosing the **Brand**, **Device Name**, and **Device Model** next. Enable the option that says **I agree with the warning, and I am ready to proceed** by clicking the corresponding checkbox. To proceed with unlocking the screen, click **Next**.

- **Step 6:** Type **000000** when asked to confirm the process. After entering the code, click **Confirm** to run the program.

- **Step 7:** Once you’ve recognized your Android device’s model, Dr. Fone will walk you through entering **Download Mode**. Following the on-screen prompts will take you directly to the next screen. It then depicts the progress of the screen unlocking procedure, in which the platform’s required drivers and configuration files are downloaded.

- **Step 8:** A new screen will appear, indicating the process has been completed. Click **Done** if your device’s screen unlock issue has been successfully fixed. If not, click the **Try Again** button.
Dr.Fone – Screen Unlock (Android) acts as your trusty guide, leading you through the maze of locked screens and inaccessible settings. It unlocks your phone first and enables USB debugging without the frustrating barriers.
**Learn More About Android Unlock:**
[<u>Samsung Unlock Codes to Unlock Samsung Phones [2024 Updated]</u>](https://drfone.wondershare.com/unlock/samsung-unlock-codes.html)
[<u>Unlocking Your Realme Phone Made Easy: No Data Loss!</u>](https://drfone.wondershare.com/unlock/how-to-unlock-realme-phone-without-losing-data.html)
[<u>The Best Android Unlock Software of 2024</u>](https://drfone.wondershare.com/sim-unlock/android-unlock-software.html)
## Conclusion
In face of locked screens, USB debugging is a beacon of access and troubleshooting for your Android device. Remember, enabling USB debugging on a locked phone is crucial, opening doors to unforeseen solutions. However, what if you want to **enable USB debugging on locked phones,** but the process gets messy?
Then, it’s time to consider Dr.Fone - Screen Unlock (Android). It effortlessly paves the way to **enable USB debugging on locked phones.** By ensuring your device’s security and accessibility, even in locked states, Dr.Fone empowers you to navigate through obstacles, safeguarding your data while unlocking endless possibilities.
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="8358498916"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<span class="atpl-alsoreadstyle">Also read:</span>
<div><ul>
<li><a href="https://android-unlock.techidaily.com/best-ways-on-how-to-unlockbypassswiperemove-lava-blaze-curve-5g-fingerprint-lock-by-drfone-android/"><u>Best Ways on How to Unlock/Bypass/Swipe/Remove Lava Blaze Curve 5G Fingerprint Lock</u></a></li>
<li><a href="https://android-unlock.techidaily.com/unlock-your-oppo-a38s-potential-the-top-20-lock-screen-apps-you-need-to-try-by-drfone-android/"><u>Unlock Your Oppo A38s Potential The Top 20 Lock Screen Apps You Need to Try</u></a></li>
<li><a href="https://android-unlock.techidaily.com/mastering-lock-screen-settings-how-to-enable-and-disable-on-vivo-x100-by-drfone-android/"><u>Mastering Lock Screen Settings How to Enable and Disable on Vivo X100</u></a></li>
<li><a href="https://android-unlock.techidaily.com/in-2024-how-to-bypass-android-lock-screen-using-emergency-call-on-samsung-galaxy-a34-5g-by-drfone-android/"><u>In 2024, How to Bypass Android Lock Screen Using Emergency Call On Samsung Galaxy A34 5G?</u></a></li>
<li><a href="https://android-unlock.techidaily.com/10-easy-to-use-frp-bypass-tools-for-unlocking-google-accounts-on-samsung-galaxy-f15-5g-by-drfone-android/"><u>10 Easy-to-Use FRP Bypass Tools for Unlocking Google Accounts On Samsung Galaxy F15 5G</u></a></li>
<li><a href="https://android-unlock.techidaily.com/the-ultimate-guide-to-oppo-find-x7-pattern-lock-screen-everything-you-need-to-know-by-drfone-android/"><u>The Ultimate Guide to Oppo Find X7 Pattern Lock Screen Everything You Need to Know</u></a></li>
<li><a href="https://android-unlock.techidaily.com/in-2024-how-to-unlock-vivo-x90s-phone-without-pin-by-drfone-android/"><u>In 2024, How to Unlock Vivo X90S Phone without PIN</u></a></li>
<li><a href="https://android-unlock.techidaily.com/remove-the-lock-screen-fingerprint-of-your-samsung-galaxy-z-fold-5-by-drfone-android/"><u>Remove the Lock Screen Fingerprint Of Your Samsung Galaxy Z Fold 5</u></a></li>
<li><a href="https://android-unlock.techidaily.com/top-4-sim-location-trackers-to-easily-find-your-lost-oppo-find-x7-device-by-drfone-android/"><u>Top 4 SIM Location Trackers To Easily Find Your Lost Oppo Find X7 Device</u></a></li>
<li><a href="https://android-unlock.techidaily.com/in-2024-unlock-your-vivo-y27s-phone-with-ease-the-3-best-lock-screen-removal-tools-by-drfone-android/"><u>In 2024, Unlock Your Vivo Y27s Phone with Ease The 3 Best Lock Screen Removal Tools</u></a></li>
<li><a href="https://android-unlock.techidaily.com/in-2024-complete-review-and-guide-to-techeligible-frp-bypass-and-more-for-vivo-v27-pro-by-drfone-android/"><u>In 2024, Complete Review & Guide to Techeligible FRP Bypass and More For Vivo V27 Pro</u></a></li>
<li><a href="https://android-unlock.techidaily.com/best-ways-on-how-to-unlockbypassswiperemove-vivo-y55s-5g-2023-fingerprint-lock-by-drfone-android/"><u>Best Ways on How to Unlock/Bypass/Swipe/Remove Vivo Y55s 5G (2023) Fingerprint Lock</u></a></li>
<li><a href="https://android-unlock.techidaily.com/in-2024-how-to-unlock-vivo-x-fold-2-phone-with-broken-screen-by-drfone-android/"><u>In 2024, How to Unlock Vivo X Fold 2 Phone with Broken Screen</u></a></li>
<li><a href="https://android-unlock.techidaily.com/how-to-reset-a-locked-oppo-a38-phone-by-drfone-android/"><u>How to Reset a Locked Oppo A38 Phone</u></a></li>
<li><a href="https://android-unlock.techidaily.com/how-to-unlock-samsung-galaxy-a14-4g-pin-codepattern-lockpassword-by-drfone-android/"><u>How to Unlock Samsung Galaxy A14 4G PIN Code/Pattern Lock/Password</u></a></li>
<li><a href="https://android-unlock.techidaily.com/how-to-unlock-samsung-galaxy-m14-5g-phone-with-broken-screen-by-drfone-android/"><u>How to Unlock Samsung Galaxy M14 5G Phone with Broken Screen</u></a></li>
<li><a href="https://android-unlock.techidaily.com/in-2024-the-ultimate-guide-to-vivo-y78-5g-pattern-lock-screen-everything-you-need-to-know-by-drfone-android/"><u>In 2024, The Ultimate Guide to Vivo Y78 5G Pattern Lock Screen Everything You Need to Know</u></a></li>
<li><a href="https://android-unlock.techidaily.com/complete-review-and-guide-to-techeligible-frp-bypass-and-more-for-lava-yuva-2-pro-by-drfone-android/"><u>Complete Review & Guide to Techeligible FRP Bypass and More For Lava Yuva 2 Pro</u></a></li>
<li><a href="https://android-unlock.techidaily.com/in-2024-rootjunky-apk-to-bypass-google-frp-lock-for-samsung-galaxy-a14-5g-by-drfone-android/"><u>In 2024, Rootjunky APK To Bypass Google FRP Lock For Samsung Galaxy A14 5G</u></a></li>
<li><a href="https://android-unlock.techidaily.com/everything-you-need-to-know-about-lock-screen-settings-on-your-motorola-moto-g13-by-drfone-android/"><u>Everything You Need to Know about Lock Screen Settings on your Motorola Moto G13</u></a></li>
<li><a href="https://android-unlock.techidaily.com/universal-unlock-pattern-for-vivo-y78-5g-by-drfone-android/"><u>Universal Unlock Pattern for Vivo Y78 5G</u></a></li>
<li><a href="https://android-unlock.techidaily.com/how-to-track-imei-number-of-oppo-f25-pro-5g-through-google-earth-by-drfone-android/"><u>How To Track IMEI Number Of Oppo F25 Pro 5G Through Google Earth?</u></a></li>
<li><a href="https://android-unlock.techidaily.com/in-2024-how-to-fix-oem-unlock-missing-on-samsung-galaxy-f15-5g-by-drfone-android/"><u>In 2024, How To Fix OEM Unlock Missing on Samsung Galaxy F15 5G?</u></a></li>
<li><a href="https://android-unlock.techidaily.com/6-proven-ways-to-unlock-samsung-galaxy-a34-5g-phone-when-you-forget-the-password-by-drfone-android/"><u>6 Proven Ways to Unlock Samsung Galaxy A34 5G Phone When You Forget the Password</u></a></li>
<li><a href="https://android-unlock.techidaily.com/how-to-unlock-a-network-locked-samsung-galaxy-z-flip-5-phone-by-drfone-android/"><u>How to Unlock a Network Locked Samsung Galaxy Z Flip 5 Phone?</u></a></li>
<li><a href="https://android-unlock.techidaily.com/how-to-reset-a-samsung-galaxy-a54-5g-phone-that-is-locked-by-drfone-android/"><u>How to Reset a Samsung Galaxy A54 5G Phone that is Locked?</u></a></li>
<li><a href="https://android-unlock.techidaily.com/how-to-unlock-vivo-y77t-phone-pattern-lock-without-factory-reset-by-drfone-android/"><u>How to Unlock Vivo Y77t Phone Pattern Lock without Factory Reset</u></a></li>
<li><a href="https://android-unlock.techidaily.com/how-to-unlock-oppo-a2-phone-without-pin-by-drfone-android/"><u>How to Unlock Oppo A2 Phone without PIN</u></a></li>
<li><a href="https://android-unlock.techidaily.com/in-2024-how-to-unlock-vivo-s17-pro-phone-without-pin-by-drfone-android/"><u>In 2024, How to Unlock Vivo S17 Pro Phone without PIN</u></a></li>
<li><a href="https://android-unlock.techidaily.com/a-perfect-guide-to-remove-or-disable-google-smart-lock-on-samsung-galaxy-m14-5g-by-drfone-android/"><u>A Perfect Guide To Remove or Disable Google Smart Lock On Samsung Galaxy M14 5G</u></a></li>
<li><a href="https://android-unlock.techidaily.com/how-to-bypass-android-lock-screen-using-emergency-call-on-samsung-galaxy-f14-5g-by-drfone-android/"><u>How to Bypass Android Lock Screen Using Emergency Call On Samsung Galaxy F14 5G?</u></a></li>
<li><a href="https://android-unlock.techidaily.com/in-2024-how-to-fix-oem-unlock-missing-on-vivo-by-drfone-android/"><u>In 2024, How To Fix OEM Unlock Missing on Vivo?</u></a></li>
<li><a href="https://android-unlock.techidaily.com/in-2024-how-to-use-google-assistant-on-your-lock-screen-of-oppo-a18-phone-by-drfone-android/"><u>In 2024, How to Use Google Assistant on Your Lock Screen Of Oppo A18 Phone</u></a></li>
<li><a href="https://android-unlock.techidaily.com/in-2024-how-to-reset-gmail-password-on-vivo-y100-devices-by-drfone-android/"><u>In 2024, How to Reset Gmail Password on Vivo Y100 Devices</u></a></li>
<li><a href="https://android-unlock.techidaily.com/in-2024-how-to-unlock-vivo-y78-5g-bootloader-easily-by-drfone-android/"><u>In 2024, How to Unlock Vivo Y78 5G Bootloader Easily</u></a></li>
<li><a href="https://easy-unlock-android.techidaily.com/in-2024-how-to-change-realme-gt-5-lock-screen-clock-in-seconds-by-drfone-android/"><u>In 2024, How To Change Realme GT 5 Lock Screen Clock in Seconds</u></a></li>
<li><a href="https://howto.techidaily.com/fixes-for-apps-keep-crashing-on-infinix-hot-30-5g-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Fixes for Apps Keep Crashing on Infinix Hot 30 5G | Dr.fone</u></a></li>
<li><a href="https://ai-video-apps.techidaily.com/in-2024-replace-imovie-with-these-10plus-powerful-windows-video-editors/"><u>In 2024, Replace iMovie with These 10+ Powerful Windows Video Editors</u></a></li>
<li><a href="https://review-topics.techidaily.com/in-2024-fixing-foneazy-mockgo-not-working-on-apple-iphone-12-pro-max-drfone-by-drfone-virtual-ios/"><u>In 2024, Fixing Foneazy MockGo Not Working On Apple iPhone 12 Pro Max | Dr.fone</u></a></li>
<li><a href="https://location-social.techidaily.com/in-2024-how-to-changeadd-location-filters-on-snapchat-for-your-lava-yuva-2-pro-drfone-by-drfone-virtual-android/"><u>In 2024, How to Change/Add Location Filters on Snapchat For your Lava Yuva 2 Pro | Dr.fone</u></a></li>
<li><a href="https://ai-editing-video.techidaily.com/this-article-introduces-how-sheila-become-a-youtuber-and-how-she-started-video-editing-for-2024/"><u>This Article Introduces How Sheila Become a Youtuber and How She Started Video Editing for 2024</u></a></li>
<li><a href="https://android-location-track.techidaily.com/in-2024-how-to-turn-off-google-location-to-stop-tracking-you-on-realme-12-pro-5g-drfone-by-drfone-virtual-android/"><u>In 2024, How to Turn Off Google Location to Stop Tracking You on Realme 12 Pro 5G | Dr.fone</u></a></li>
<li><a href="https://iphone-unlock.techidaily.com/in-2024-can-you-unlock-apple-iphone-11-pro-after-forgetting-the-passcode-drfone-by-drfone-ios/"><u>In 2024, Can You Unlock Apple iPhone 11 Pro After Forgetting the Passcode? | Dr.fone</u></a></li>
<li><a href="https://android-pokemon-go.techidaily.com/in-2024-what-pokemon-evolve-with-a-dawn-stone-for-oneplus-ace-2-drfone-by-drfone-virtual-android/"><u>In 2024, What Pokémon Evolve with A Dawn Stone For OnePlus Ace 2? | Dr.fone</u></a></li>
<li><a href="https://fake-location.techidaily.com/apply-these-techniques-to-improve-how-to-detect-fake-gps-location-on-htc-u23-pro-drfone-by-drfone-virtual-android/"><u>Apply These Techniques to Improve How to Detect Fake GPS Location On HTC U23 Pro | Dr.fone</u></a></li>
<li><a href="https://location-social.techidaily.com/in-2024-edit-and-send-fake-location-on-telegram-for-your-lava-agni-2-5g-in-3-ways-drfone-by-drfone-virtual-android/"><u>In 2024, Edit and Send Fake Location on Telegram For your Lava Agni 2 5G in 3 Ways | Dr.fone</u></a></li>
<li><a href="https://ios-pokemon-go.techidaily.com/what-is-the-best-pokemon-for-pokemon-pvp-ranking-on-apple-iphone-x-drfone-by-drfone-virtual-ios/"><u>What is the best Pokemon for pokemon pvp ranking On Apple iPhone X? | Dr.fone</u></a></li>
<li><a href="https://apple-account.techidaily.com/guide-on-how-to-remove-apple-id-from-apple-iphone-12-mini-by-drfone-ios/"><u>Guide on How To Remove Apple ID From Apple iPhone 12 mini</u></a></li>
<li><a href="https://ai-video-editing.techidaily.com/split-a-video-in-the-lightworks-step-by-step/"><u>Split a Video in the Lightworks Step by Step</u></a></li>
<li><a href="https://ai-editing-video.techidaily.com/2024-approved-how-to-export-video-in-filmora/"><u>2024 Approved How To Export Video in Filmora</u></a></li>
<li><a href="https://android-transfer.techidaily.com/how-to-transfer-photos-from-tecno-phantom-v-fold-to-samsung-galaxy-s21-ultra-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>How to Transfer Photos From Tecno Phantom V Fold to Samsung Galaxy S21 Ultra | Dr.fone</u></a></li>
<li><a href="https://ios-unlock.techidaily.com/everything-you-need-to-know-about-unlocked-apple-iphone-se-2020-by-drfone-ios/"><u>Everything You Need To Know About Unlocked Apple iPhone SE (2020)</u></a></li>
<li><a href="https://techidaily.com/simple-ways-to-get-recent-calls-back-from-infinix-gt-10-pro-by-fonelab-android-recover-call-logs/"><u>Simple ways to get recent calls back from Infinix GT 10 Pro</u></a></li>
</ul></div> |
@extends('layout.master')
@section('content')
<form action="{{ route('kategorigallery.update', $kategorigallery->id) }}" method="POST" enctype="multipart/form-data">
@csrf
@method('PUT')
@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="content-wrapper bg-white">
<div class="row">
<div class="col-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Form Kategori Gallery</h4>
<p class="card-description">
Isi Form Kategori Gallery
</p>
<form class="forms-sample">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Gambar</strong>
<input type="hidden" name="oldImage" value="{{ $kategorigallery->gambar }}">
@if ($kategorigallery->gambar)
<img src="{{ asset('storage/' . $kategorigallery->gambar) }}" class="img-preview img-fluid mb-3 col-sm-5 d-block">
@else
<img class="img-preview img-fluid mb-3">
@endif
<img class="img-preview img-fluid mb-3 col-sm-5">
<div class="input-group mb-3">
<input type="file" class="form-control" @error('image') is-invalid @enderror name="gambar" id="image" onchange="previewImage()" value="{{ asset('storage/' . $kategorigallery->gambar) }}">
@error('image')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputName1">Kategori</label>
<input type="text" class="form-control" id="exampleInputName1" placeholder="Kategori" name="kategori" value="{{ $kategorigallery->kategori}}">
</div>
<button type="submit" class="btn btn-primary me-2">Submit</button>
<a class="btn btn-light" href="{{ route('kategorigallery.index') }}">Cancel</a>
</form>
</div>
</div>
</div>
</form>
<!-- content-wrapper ends -->
<!-- partial:../../partials/_footer.html -->
<footer class="footer">
<div class="d-sm-flex justify-content-center justify-content-sm-between">
<span class="text-muted text-center text-sm-left d-block d-sm-inline-block">Halaman ini bersifat rahasia dan hanya boleh diakses oleh pihak yang berwajib</span>
<span class="float-none float-sm-right d-block mt-1 mt-sm-0 text-center">Copyright © 2022.</span>
</div>
</footer>
<!-- partial -->
</div>
<!-- main-panel ends -->
</div>
<!-- page-body-wrapper ends -->
</div>
@endsection |
// 获取链接和模态框元素
const openLoginModalLink = document.getElementById('openLoginModalLink');
const loginModal = document.getElementById('loginModal');
const closeLoginModalButton = document.getElementById('closeLoginModalButton');
// 打开登录模态框
openLoginModalLink.addEventListener('click', (e) => {
e.preventDefault(); // 阻止链接的默认行为
loginModal.style.display = 'block';
});
// 关闭登录模态框
closeLoginModalButton.addEventListener('click', () => {
loginModal.style.display = 'none';
});
// 点击模态框外部区域也可以关闭模态框
window.addEventListener('click', (e) => {
if (e.target === loginModal) {
loginModal.style.display = 'none';
}
});
document.addEventListener('DOMContentLoaded', function() {
const categoryBtns = document.querySelectorAll('.category-btn');
const categoryItems = document.querySelectorAll('.category-item');
const orderList = document.getElementById('orderList');
const totalPrice = document.getElementById('totalPrice');
// 初始化订单和总价
let order = [];
let total = 0;
// 为每个项目按钮添加点击事件监听器
categoryBtns.forEach(categoryBtn => {
categoryBtn.addEventListener('click', () => {
const category = categoryBtn.getAttribute('data-category');
// 隐藏所有项目的品项
categoryItems.forEach(item => {
item.style.display = 'none';
});
// 显示当前项目的品项
const currentCategory = document.querySelector(`.category-item.${category}`);
currentCategory.style.display = 'block';
});
});
// 为“全部”按钮添加点击事件监听器
const allBtn = document.querySelector('.category-btn[data-category="All"]');
allBtn.addEventListener('click', () => {
// 显示所有项目的品项
categoryItems.forEach(item => {
item.style.display = 'block';
});
});
// 为每个品项按钮添加点击事件监听器
const items = document.querySelectorAll('.item');
items.forEach(item => {
item.addEventListener('click', () => {
const itemName = item.getAttribute('data-name');
const itemPrice = parseFloat(item.getAttribute('data-price'));
// 将品项添加到订单列表
order.push({ name: itemName, price: itemPrice });
const listItem = document.createElement('li');
listItem.innerHTML = `${itemName}: $${itemPrice.toFixed(2)}`;
orderList.appendChild(listItem);
// 更新总价
total += itemPrice;
totalPrice.textContent = total.toFixed(2);
});
});
}); |
package com.wimoor.admin.controller;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wimoor.admin.pojo.dto.SysUserRoleDTO;
import com.wimoor.admin.pojo.dto.UserDTO;
import com.wimoor.admin.pojo.dto.UserInsertDTO;
import com.wimoor.admin.pojo.dto.UserRegisterInfoDTO;
import com.wimoor.admin.pojo.entity.SysUser;
import com.wimoor.admin.pojo.entity.SysUserBind;
import com.wimoor.admin.pojo.entity.SysUserRole;
import com.wimoor.admin.pojo.vo.UserVO;
import com.wimoor.admin.service.ISysMenuService;
import com.wimoor.admin.service.ISysUserBindService;
import com.wimoor.admin.service.ISysUserRoleService;
import com.wimoor.admin.service.ISysUserService;
import com.wimoor.common.mvc.BizException;
import com.wimoor.common.mvc.FileUpload;
import com.wimoor.common.mybatisplus.MysqlGenerator;
import com.wimoor.common.result.Result;
import com.wimoor.common.result.ResultCode;
import com.wimoor.common.user.UserInfo;
import com.wimoor.common.user.UserInfoContext;
import com.wimoor.sys.sms.util.AliyunSmsUtils;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Api(tags = "用户接口")
@RestController
@RequestMapping("/api/v1/users")
@Slf4j
@RequiredArgsConstructor
public class UserController {
private final ISysMenuService menuService;
private final ISysUserService iSysUserService;
private final ISysUserRoleService iSysUserRoleService;
private final FileUpload fileUpload;
private final AliyunSmsUtils aliyunSmsUtils;
private final StringRedisTemplate stringRedisTemplate;
private final ISysUserBindService iSysUserBindService;
@ApiOperation(value = "删除用户")
@ApiImplicitParam(name = "ids", value = "id集合", required = true, paramType = "query", dataType = "String")
@DeleteMapping("/{ids}")
public Result<String> delete(@PathVariable String ids) {
List<SysUser> list = iSysUserService.listByIds(Arrays.asList(ids.split(",")).stream().collect(Collectors.toList()));
for(SysUser item:list) {
item.setLogicDelete(true);
item.setPasswordkey(item.getAccount());
item.setAccount(item.getId());
iSysUserService.updateById(item);
}
return Result.judge(true);
}
@ApiOperation(value = "删除用户")
@ApiImplicitParam(name = "ids", value = "id集合", required = true, paramType = "query", dataType = "String")
@GetMapping("detail")
public Result<String> detail() {
UserInfo userInfo = UserInfoContext.get();
iSysUserService.detail(userInfo);
return Result.judge(true);
}
@PostMapping(value="/saveImage",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Transactional
public Result<Boolean> saveImageAction(@RequestParam(value="file",required=false)MultipartFile file){
UserInfo userinfo = UserInfoContext.get();
iSysUserService.saveImage(file,userinfo);
return Result.success(true);
}
@ApiOperation(value = "停用用户")
@ApiImplicitParam(name = "ids", value = "id集合", required = true, paramType = "query", dataType = "String")
@PostMapping("/diable/{ids}")
public Result<String> disable(@PathVariable String ids) {
List<SysUser> list = iSysUserService.listByIds(Arrays.asList(ids.split(",")).stream().collect(Collectors.toList()));
for(SysUser item:list) {
item.setDisable(true);
iSysUserService.updateById(item);
}
return Result.judge(true);
}
@ApiOperation(value = "启用用户")
@ApiImplicitParam(name = "ids", value = "id集合", required = true, paramType = "query", dataType = "String")
@PostMapping("/enable/{ids}")
public Result<String> enable(@PathVariable String ids) {
Calendar c=Calendar.getInstance();
c.add(Calendar.YEAR, 10);
List<SysUser> list = iSysUserService.listByIds(Arrays.asList(ids.split(",")).stream().collect(Collectors.toList()));
for(SysUser item:list) {
item.setDisable(false);
item.setLosingeffect(c.getTime());
iSysUserService.updateById(item);
}
return Result.judge(true);
}
@GetMapping("/createpojo")
public Result<String> createPojoAction(String table,String pkg) {
MysqlGenerator.autoGenerator(table, pkg);
return Result.success("true");
}
@GetMapping("/limitData")
public Result<String> limitDataAction(String type) {
UserInfo userInfo = UserInfoContext.get();
if(userInfo.isLimit(type)) {
return Result.success("true");
}else {
return Result.success("false");
}
}
/**
* 提供用于用户登录认证信息
*/
@ApiOperation(value = "根据登录用户ID获取用户名称等信息")
@GetMapping("/roles/{userid}")
public Result<List<SysUserRoleDTO>> getUserRoleById(@PathVariable String userid) {
if(userid!=null) {
List<SysUserRole> list = iSysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
.eq(SysUserRole::getUserId,new BigInteger(userid)));
List<SysUserRoleDTO> result=new LinkedList<SysUserRoleDTO>();
if(list!=null) {
list.stream().forEach(userrole->{
SysUserRoleDTO item=new SysUserRoleDTO();
BeanUtil.copyProperties(userrole, item);
result.add(item);
});
}
return Result.success(result);
}else {
return Result.failed(ResultCode.USER_NOT_EXIST);
}
}
@ApiOperation(value = "列表分页")
@ApiImplicitParams({
@ApiImplicitParam(name = "page", value = "页码", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "limit", value = "每页数量", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "name", value = "用户名", paramType = "query", dataType = "String"),
})
@PostMapping("/list")
public Result<IPage<UserVO>> list(@RequestBody UserDTO dto) {
UserInfo userInfo = UserInfoContext.get();
dto.setShopid(userInfo.getCompanyid());
if(StrUtil.isEmpty(dto.getName())) {
dto.setName(null);
}else {
dto.setName("%"+dto.getName().trim()+"%");
}
if(StrUtil.isEmpty(dto.getRoleid())) {
dto.setRoleid(null);
}
if(StrUtil.isEmpty(dto.getAccount())) {
dto.setAccount(null);
}else {
dto.setAccount("%"+dto.getAccount().trim()+"%");
}
IPage<UserVO> result = iSysUserService.listQuery(dto.getPage(),dto);
return Result.success(result);
}
/**
* 提供用于用户登录认证信息
*/
@ApiOperation(value = "根据用户账号(电话或邮箱)获取用户信息")
@ApiImplicitParam(name = "account", value = "用户账号", required = true, paramType = "path", dataType = "String")
@GetMapping("/sysrole/account/{account}")
public Result<UserInfo> getUserByUsername(@PathVariable String account) {
byte[] bytes = account.getBytes();
Base64.Decoder decoder = Base64.getDecoder();
String decodeValue = new String( decoder.decode(bytes));
SysUser user = iSysUserService.getUserAllByAccount(decodeValue);
if(user!=null) {
if(user.getDisable()) {
return Result.failed(ResultCode.USER_ACCOUNT_LOCKED);
}
if(user.getLogicDelete()) {
return Result.failed(ResultCode.USER_NOT_EXIST);
}
if(user.getLosingeffect().before(new Date())) {
return Result.failed(ResultCode.USER_ACCOUNT_INVALID);
}
user.setPassword("***");
user.setSalt("***");
log.debug(account+"获取所有信息---时间:"+new Date());
UserInfo info=iSysUserService.convertToUserInfo(user);
return Result.success(info);
}else {
return Result.failed(ResultCode.USER_NOT_EXIST);
}
}
/**
* 提供用于用户登录认证信息
*/
@ApiOperation(value = "根据微信openid与账号密码登陆并同时绑定获取用户信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "account", value = "登陆账号", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "password", value = "登陆密码", paramType = "query", dataType = "String")
})
@GetMapping("/sysrole/verifyAccount")
public Result<UserInfo> verifyAccountAction(String account,String password) {
SysUser user = null;
try {
user = iSysUserService.verifyAccount(account,password);
}catch(Exception e) {
return Result.failed(e.getMessage());
}
if(user!=null) {
user.setPassword("***");
user.setSalt("***");
log.debug(account+"获取所有信息---时间:"+new Date());
UserInfo info=iSysUserService.convertToUserInfo(user);
return Result.success(info);
}else {
return Result.failed(ResultCode.USER_NOT_EXIST);
}
}
@ApiOperation(value = "根据用户ID获取用户信息")
@ApiImplicitParam(name = "ID", value = "用户ID", required = true, paramType = "path", dataType = "String")
@GetMapping("/sysrole/userid/{userid}")
public Result<UserInfo> getUserByUserId(@PathVariable String userid) {
SysUser user = iSysUserService.getUserAllById(userid);
if(user!=null) {
user.setPassword("***");
user.setSalt("***");
UserInfo info=iSysUserService.convertToUserInfo(user);
return Result.success(info);
}else {
return Result.failed(ResultCode.USER_NOT_EXIST);
}
}
/**
* 提供用于用户登录认证信息
*/
@ApiOperation(value = "根据登录用户ID获取用户名称等信息")
@GetMapping("/sysrole/info/{userid}")
@Cacheable(value = "userinfo")
public Result<Map<String,Object>> getUserInfoByUserId(@PathVariable String userid) {
if(userid!=null) {
Map<String, Object> info = iSysUserService.getUserInfoById(userid) ;
return Result.success(info);
}else {
return Result.failed(ResultCode.USER_NOT_EXIST);
}
}
/**
* 提供用于用户登录认证信息
*/
@ApiOperation(value = "根据登录用户ID获取用户名称等信息")
@GetMapping("/info")
public Result<Map<String,Object>> getUserInfoById() {
UserInfo userInfo = UserInfoContext.get();
if(userInfo!=null) {
Map<String, Object> info = iSysUserService.getUserInfoById(userInfo.getId());
info.put("company", iSysUserService.getCompanyName(userInfo.getCompanyid()));
if(info.get("image")!=null) {
String image=info.get("image").toString();
image=fileUpload.getPictureImage(image);
info.put("image", image);
}
SysUser user = iSysUserService.getUserAllById(userInfo.getId());
if(user!=null) {
user.setPassword("***");
user.setSalt("***");
}
info.put("user", user);
info.put("usertype", userInfo.getUsertype());
return Result.success(info);
}else {
return Result.failed(ResultCode.USER_NOT_EXIST);
}
}
/**
* 提供用于用户登录认证信息
*/
@ApiOperation(value = "根据微信openid与账号密码登陆并同时绑定获取用户信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "openid", value = "微信openid", paramType = "query", dataType = "String")
})
@GetMapping("/sysrole/findbyopenid/{openid}/{appType}")
public Result<List<UserInfo>> findUserByOpenid(@PathVariable String openid,@PathVariable String appType) {
List<SysUser> userList =null;
if(appType.equals("website")){
if(StrUtil.isBlankOrUndefined(openid)) {
UserInfo userInfo = UserInfoContext.get();
userList = iSysUserService.findBindList(userInfo);
}else {
List<SysUserBind> bindUserList = iSysUserBindService.getBindList(openid);
List<SysUser> result=new ArrayList<SysUser>();
for(SysUserBind item:bindUserList) {
SysUser user = iSysUserService.getUserAllById(item.getUserid().toString());
user.setPassword("***");
user.setSalt("***");
result.add(user);
}
userList=result;
}
}else {
userList = iSysUserService.findAppUserByOpenid(openid,appType);
}
List<UserInfo> result=new LinkedList<UserInfo>();
if(userList!=null) {
for(SysUser user:userList) {
user.setPassword("***");
user.setSalt("***");
UserInfo info=iSysUserService.convertToUserInfo(user);
result.add(info);
}
return Result.success(result);
}else {
return Result.failed(ResultCode.USERNAME_OR_PASSWORD_ERROR);
}
}
/**
* 提供用于用户登录认证信息
*/
@GetMapping("/findbindlist")
public Result<List<UserInfo>> findbindlist() {
UserInfo userInfo = UserInfoContext.get();
List<SysUser> userList = iSysUserService.findBindList(userInfo);
List<UserInfo> result=new LinkedList<UserInfo>();
if(userList!=null) {
for(SysUser user:userList) {
user.setPassword("***");
user.setSalt("***");
UserInfo info=iSysUserService.convertToUserInfo(user);
result.add(info);
}
return Result.success(result);
}else {
return Result.failed(ResultCode.USERNAME_OR_PASSWORD_ERROR);
}
}
@GetMapping("/getbindId")
public Result<?> getbindId(String account) {
UserInfo userInfo = UserInfoContext.get();
String key=account;
if(key.length()>16) {
key=key.substring(0, 16);
}else {
while(key.length()<16) {
key=key+"0";
}
}
String bindid = iSysUserBindService.getBindId(userInfo.getId());
String iv=userInfo.getSession();
if(iv.length()>16) {
iv=iv.substring(0, 16);
}else {
while(iv.length()<16) {
iv=iv+"0";
}
}
cn.hutool.crypto.symmetric.AES aes = new cn.hutool.crypto.symmetric.AES(Mode.CBC, Padding.ISO10126Padding, key.getBytes(), iv.getBytes());
bindid = aes.encryptBase64(bindid, CharsetUtil.CHARSET_UTF_8);
try {
bindid= java.net.URLEncoder.encode(bindid,"utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Result.success(bindid);
}
/**
* 提供用于用户登录认证信息
*/
@ApiOperation(value = "根据微信openid与账号密码登陆并同时绑定获取用户信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "openid", value = "微信openid", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "account", value = "登陆账号", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "password", value = "登陆密码", paramType = "query", dataType = "String")
})
@GetMapping("/sysrole/openidbind")
public Result<UserInfo> bindUserByOpenid(String openid,String appType,String account,String password) {
try {
if(appType.equals("website")){
UserInfo userInfo = UserInfoContext.get();
openid=iSysUserBindService.getBindId(userInfo.getId());
}
SysUser user = iSysUserService.bindOpenId(openid,appType,account,password);
user.setPassword("***");
user.setSalt("***");
log.debug(account+"获取所有信息---时间:"+new Date());
UserInfo info=iSysUserService.convertToUserInfo(user);
return Result.success(info);
}catch(BizException e) {
return Result.failed(ResultCode.USERNAME_OR_PASSWORD_ERROR,e.getMessage());
}
}
@ApiOperation(value = "登录用户注销该用户的账户信息")
@GetMapping("/unbindAccount")
public Object unbindAccountAction(HttpServletRequest request) {
UserInfo userInfo = UserInfoContext.get();
Map<String,Object> map=new HashMap<String, Object>();
int res=iSysUserService.unbindAccount(userInfo);
if(res>0) {
map.put("isOk", true);
map.put("msg", "注销成功!");
}else {
map.put("isOk", false);
map.put("msg", "注销失败,请联系管理员!");
}
return Result.success(map);
}
@ApiOperation(value = "当前微信账号解除和wimoor的绑定")
@GetMapping("/unbindWechat")
public Object unbindWechatAction(HttpServletRequest request) {
//UserInfo userInfo = UserInfoContext.get();
String appType=request.getParameter("appType");
String account=request.getParameter("account");
String openid=request.getParameter("openid");
Map<String,Object> map=new HashMap<String, Object>();
List<SysUser> userlist = iSysUserService.findAppUserByOpenid(openid,appType);
SysUser user = userlist.stream().filter(muser->muser.getAccount().equals(account)).findFirst().get();
UserInfo info=iSysUserService.convertToUserInfo(user);
int res=iSysUserService.unbindWechat(info,appType);
if(res>0) {
map.put("isOk", true);
map.put("msg", "解绑成功!");
}else {
map.put("isOk", false);
map.put("msg", "操作失败,或者您当前暂无绑定!");
}
return Result.success(map);
}
@ApiOperation(value = "新增用户")
@PostMapping
@Transactional
public Result<?> add(@RequestBody UserInsertDTO userDTO) {
UserInfo operatorUserInfo = UserInfoContext.get();
boolean result = iSysUserService.saveUser(userDTO,operatorUserInfo);
return Result.judge(result);
}
@ApiOperation(value = "修改用户")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path", dataType = "Long")
@PutMapping(value = "/{id}")
@Transactional
@CacheEvict(value = { "userall","userinfo"}, allEntries = true)
public Result<?> update(
@PathVariable BigInteger id,
@RequestBody UserInsertDTO userDTO) {
UserInfo operatorUserInfo = UserInfoContext.get();
boolean result = iSysUserService.updateUser(userDTO,operatorUserInfo);
if(result) {
UserInfo myinfo=new UserInfo();
myinfo.setId(userDTO.getId());
menuService.cleanCacheByUser(myinfo);
}
return Result.judge(result);
}
@ApiOperation(value = "修改自己用户名称")
@PostMapping(value = "/updateSelf")
@Transactional
@CacheEvict(value = { "userall","userinfo"}, allEntries = true)
public Result<?> updateSelfAction(@RequestBody UserInsertDTO userDTO) {
UserInfo operatorUserInfo = UserInfoContext.get();
boolean result = iSysUserService.updateUserSelf(userDTO,operatorUserInfo);
return Result.judge(result);
}
@ApiOperation(value = "修改自己密码")
@PostMapping("/updatePasswordSelf")
@CacheEvict(value = { "userall","userinfo"}, allEntries = true)
public Result<?> updatePasswordSelfAction(@RequestBody UserRegisterInfoDTO dto) {
UserInfo info = UserInfoContext.get();
iSysUserService.changePasswordSelf(info,dto);
return Result.success(true);
}
@ApiOperation(value = "修改自己密码")
@PostMapping("/updatePasswordForget")
@CacheEvict(value = { "userall","userinfo"}, allEntries = true)
public Result<?> updatePasswordForgetAction(@RequestBody UserRegisterInfoDTO dto) {
String code = stringRedisTemplate.opsForValue().get(dto.getKey());
if(StrUtil.isNotBlank(code)&&StrUtil.isNotBlank(dto.getCode())&&code.equals(dto.getCode())) {
iSysUserService.changePassword(dto);
}else {
throw new BizException("验证码失效或输入不正确");
}
stringRedisTemplate.delete(dto.getKey());
return Result.success(true);
}
@ApiOperation(value = "修改自己账户")
@PostMapping("/updateAccountSelf")
@CacheEvict(value = { "userall","userinfo"}, allEntries = true)
public Result<?> updateAccountSelfAction(@RequestBody UserRegisterInfoDTO dto) {
String code = stringRedisTemplate.opsForValue().get(dto.getKey());
if(StrUtil.isNotBlank(code)&&StrUtil.isNotBlank(dto.getCode())&&code.equals(dto.getCode())) {
UserInfo info = UserInfoContext.get();
iSysUserService.changeAccountSelf(info,dto);
}else {
throw new BizException("验证码失效或输入不正确");
}
stringRedisTemplate.delete(dto.getKey());
return Result.success(true);
}
@ApiOperation(value = "修改自己账户")
@PostMapping("/updateEmailSelf")
@CacheEvict(value = { "userall","userinfo"}, allEntries = true)
public Result<?> updateEmailSelfAction(@RequestBody UserRegisterInfoDTO dto) {
String code = stringRedisTemplate.opsForValue().get(dto.getKey());
if(StrUtil.isNotBlank(code)&&StrUtil.isNotBlank(dto.getCode())&&code.equals(dto.getCode())) {
UserInfo info = UserInfoContext.get();
iSysUserService.changeEmailSelf(info,dto);
}else {
throw new BizException("验证码失效或输入不正确");
}
stringRedisTemplate.delete(dto.getKey());
return Result.success(true);
}
@ApiOperation(value = "修改自己密码")
@PostMapping("/verifyPassword")
@CacheEvict(value = { "userall","userinfo"}, allEntries = true)
public Result<?> verifyPasswordSelfAction(@RequestBody UserRegisterInfoDTO dto) {
iSysUserService.verifyAccount(dto.getAccount(), dto.getOldpassword());
return Result.success(true);
}
@ApiOperation(value = "迁移")
@PostMapping("/mergeAccount")
@CacheEvict(value = { "userall","userinfo"}, allEntries = true)
@Transactional
public Result<?> mergeAccountAction(@RequestBody UserRegisterInfoDTO dto) {
UserInfo fromuser = UserInfoContext.get();
SysUser touser = iSysUserService.verifyAccount(dto.getAccount(), dto.getPassword());
iSysUserService.mergeData(fromuser,touser);
return Result.success(true);
}
@GetMapping("/getSmsCode")
public Result<String> getAliyunSmsCodeAction(String mobile,String ftype ) {
AliyunSmsUtils.setNewcode();
String code = Integer.toString(AliyunSmsUtils.getNewcode());//4位数验证码
SendSmsResponse response=null;
try {
response = aliyunSmsUtils.sendVerifySms(mobile, code,ftype);
} catch (ClientException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null&&response.getCode().toUpperCase().equals("OK")) {
String key= UUID.fastUUID().toString();
stringRedisTemplate.opsForValue().set(key, code, Duration.ofMinutes(10));
return Result.success(key);
}else{
throw new BizException("短信发送失败,请联系管理员");
}
}
@GetMapping("/getEmailCode")
public Result<String> getEmailCodeAction(String email,String ftype ) {
AliyunSmsUtils.setNewcode();
String code = Integer.toString(AliyunSmsUtils.getNewcode());//4位数验证码
iSysUserService.sendEmail(email,code, ftype);
String key= UUID.fastUUID().toString();
stringRedisTemplate.opsForValue().set(key, code, Duration.ofMinutes(10));
return Result.success(key);
}
@PostMapping("/register")
public Result<UserInfo> register(@RequestBody UserRegisterInfoDTO dto) {
if(StrUtil.isEmpty(dto.getAccount())) {
throw new BizException("手机号不能为空");
}
if(StrUtil.isEmpty(dto.getPassword())) {
throw new BizException("密码不能为空");
}
if(StrUtil.isEmpty(dto.getCode())) {
throw new BizException("验证码不能为空");
}
if(StrUtil.isEmpty(dto.getKey())) {
throw new BizException("未获取验证码或验证码已失效,请重新获取验证码");
}
String code = stringRedisTemplate.opsForValue().get(dto.getKey());
if(StrUtil.isNotBlank(code)&&StrUtil.isNotBlank(dto.getCode())&&code.equals(dto.getCode())) {
SysUser user = iSysUserService.saveRegister(dto);
user.setPassword("***");
user.setSalt("***");
UserInfo info=iSysUserService.convertToUserInfo(user);
stringRedisTemplate.delete(dto.getKey());
return Result.success(info);
}else {
throw new BizException("验证码失效或输入不正确");
}
}
@PostMapping("/updatePassword")
@CacheEvict(value = { "userall","userinfo"}, allEntries = true)
public Result<UserInfo> updatePassword(@RequestBody UserRegisterInfoDTO dto) {
SysUser user = iSysUserService.changePassword(dto);
user.setPassword("***");
user.setSalt("***");
UserInfo info=iSysUserService.convertToUserInfo(user);
return Result.success(info);
}
@ApiOperation(value = "获取所有用户")
@GetMapping("/findOwnerAll")
public Result<List<Map<String, Object>>> findOwnerAllAction() {
UserInfo userInfo = UserInfoContext.get();
List<Map<String, Object>> list = iSysUserService.findOwnerAll(userInfo.getCompanyid(),null);
return Result.success(list);
}
} |
import styles from './ResultsTable.module.css';
const formatter = new Intl.NumberFormat('ko-KR', {
style: 'currency',
currency: 'KRW',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
export default function ResultsTable({ data, initialInvestment }) {
return (
<table className={styles.result}>
<thead>
<tr>
<th>Year</th>
<th>Total Savings</th>
<th>Interest (Year)</th>
<th>Total Interest</th>
<th>Invested Capital</th>
</tr>
</thead>
<tbody>
{data.map(
({ year, savingsEndOfYear, yearlyContribution, yearlyInterest }) => (
<tr key={year}>
<td>{year}</td>
<td>{formatter.format(savingsEndOfYear)}</td>
<td>{formatter.format(yearlyInterest)}</td>
<td>
{formatter.format(savingsEndOfYear -
initialInvestment -
yearlyContribution * year)}
</td>
<td>{formatter.format(initialInvestment + yearlyContribution * year)}</td>
</tr>
)
)}
</tbody>
</table>
);
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>blogDetail</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Serif+Display&family=Lato:wght@300;400;700;900&display=swap"
rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=DM+Serif+Display&family=Jost&family=Lato:wght@300;400;700;900&display=swap"
rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="header center">
<nav class="header__left">
<a class="header__logo" href="main.html">
<img src="img/header_logo.svg" width="34" height="34" alt="logo">
<span class="header__left__text">Interno</span>
</a>
</nav>
<nav class="header__right">
<a class="header__right__link" href="#">Home</a>
<a class="header__right__link" href="#">Project</a>
<a class="header__right__link" href="blog.html">Blog</a>
</nav>
</header>
<main id="app">
<section class="blogDetails__top__content"></section>
<section class="blogDetails__mid__content center">
<div class="blogDetails__mid__content__right">
<h1 class="blogDetails__mid__content__right__header">Let’s Get Solution for Building Construction Work
</h1>
<img class="blogDetails__mid__content__right__img" src="img/blogDetaisImg1.png" alt="photo">
<div class="blogDetails__mid__content__right__datelinks">
<p class="blogDetails__mid__content__right__datelinks__date">26 December,2022</p>
<ul class="blogDetails__mid__content__right__datelinks__links">
<li><a href="#">Interior</a></li>
<li><a href="main.html">Home</a></li>
<li><a href="#">Decore</a></li>
</ul>
</div>
<!-- <p class="blogDetails__mid__content__right__text">Lorem ipsum dolor sit amet, adipiscing Aliquam eu sem
vitae turpmaximus.posuere in.Contrary to popular belief.There are many variations of passages of
Lorem Ipsum available, but the majority have suffered alteration in some form, by injecthumour, or
randomised words which don't look even slightly believable. Embarrassing hidden in the middle of
text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary.
</p> -->
<!-- <div class="blogDetails__mid__content__right__quotes">
<h1 class="blogDetails__mid__content__right__quotes__header">“</h1>
<p class="blogDetails__mid__content__right__quotes__text">The details are not the details. They make
the design.</p>
</div> -->
<component :is="changeTabs"></component>
</div>
<div class="blogDetails__mid__content__left">
<h3 class="blogDetails__mid__content__left__header">Tags</h3>
<div class="blogDetails__mid__content__left__buttons">
<button class="blogDetails__mid__content__left__button" @click="currentTab=nameButton"
v-for="nameButton in nameButtons" :key="nameButton.id">{{nameButton}}</button>
</div>
</section>
</main>
<footer class="footer__bottom center">
<div class="Interno">
<h2 class="footer__bottom__header"><img src="img/header_logo.svg" alt="logo">Interno</h2>
<p class="footer__bottom__text">It is a long established fact that a reader will be distractedv
lookings.</p>
</div>
<div class="pages">
<h2 class="pages__contacts__header">Pages</h2>
<a class="pages__contacts__text" href="#">Home</a>
<a class="pages__contacts__text" href="">Project</a>
<a class="pages__contacts__text" href="blog.html">Blog</a>
</div>
<div class="contacts">
<h2 class="pages__contacts__header">Contacts</h2>
<p class="pages__contacts__text">55 East Birchwood Ave. Brooklyn, New York 11201 contact@interno.com (123)
456 - 7890</p>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="components.js"></script>
<script>
new Vue({
el: "#app",
data: {
nameButtons: ['Kitchen', 'Bedroom', 'Building', 'Architecture', 'Kitchen-Planning', 'Bedroom'],
currentTab: 'none'
},
methods: {
},
computed: {
changeTabs() {
return `change-${this.currentTab}`
}
},
});
</script>
</body>
</html> |
import abc
import functools
import psycopg2
from psycopg2 import OperationalError
from psycopg2.extras import DictCursor
from psycopg2.extensions import parse_dsn
from loguru import logger
from product_inventory.config.envs import DB_URI
from product_inventory.exceptions import ErrorDetails
from product_inventory.exceptions.database import RequiredFieldsException
def fields_obrigatorios(fields):
"""
For any database operation (DDL or DML) guaruatees that the required fields
for such operations are passed, otherwise, throws exception.
:param fields: field(s) necessário(s) para a transação.
:raises RequiredFieldsException: If any of the required fields are not passed.
"""
def decorator_required_fields(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
for field in fields:
if self.dict().get(field) is None:
raise RequiredFieldsException(
status=403,
error="Forbidden",
message="required field not passed",
error_details=[
ErrorDetails(
message=f"{self.__class__.__name__}: {field} not passed"
).to_dict()
],
)
return func(self, *args, **kwargs)
return wrapper
return decorator_required_fields
class DataBase:
"""
Each database table is represented as a class, with columns as attributes and
class methods as transactions (DML or DDL). Database operation results are
dictionaries with keys corresponding to table columns, using the DictCursor
cursor factory. Classes inheriting from DataBase must implement the dict method
to instantiate table objects and map attributes to table columns. This object-oriented
approach eliminates the need for other classes to implement common database
table transactions such as insert, find_one, and find_all.
"""
def __connect(self):
"""
Establishes a database connection using connection data sourced from
environment variables exported in the product_inventory/config/envs.py file.
:raises OperationalError: Could not establish a connection.
"""
while True:
try:
self.__connection = psycopg2.connect(**parse_dsn(DB_URI))
if self.__connection:
self.__cursor = self.__connection.cursor(cursor_factory=DictCursor)
break
except OperationalError as op_error:
logger.bind(**{"error": op_error}).error(
"Database connection error occurred."
)
continue
def __disconect(self):
"""
Closes the database connection.
"""
self.__cursor.close()
self.__connection.close()
def insert(self):
"""
Inserts data into the database. Classes inheriting from DataBase should
be instantiated with the query_string and dict methods to map object values
in the database transaction.
.. code-block:: python
self.__cursor.execute('''
INSERT INTO some_table (an_int, a_date, another_date, a_string)
VALUES (%(int)s, %(date)s, %(date)s, %(str)s);
''',
{'int': 10, 'str': "O'Reilly", 'date': datetime.date(2005, 11, 18)})
The connection opens and closes promptly, preventing unnecessary open connections.
:return: The number of affected rows: 1 on success, None on failure.
:rtype: int or None
"""
self.__connect()
self.__cursor.execute(self.query_string, self.dict())
self.__connection.commit()
result = self.__cursor.rowcount
self.__disconect()
return result
def find_one(self):
"""
Retrieves the next database row impacted by the query in query_string.
If no record exists, it returns None. The connection is promptly opened
and closed to prevent unnecessary openings.
:return: Query result.
:rtype: dict
"""
self.__connect()
self.__cursor.execute(self.query_string, self.dict())
result = self.__cursor.fetchone()
self.__disconect()
return result
def find_all(self, total=False):
"""
Retrieves all database rows impacted by the query in query_string. Returns
an empty list if no records exist. The connection opens and closes promptly,
preventing unnecessary openings.
:param bool total: Retrieve the total number of search records.
:return: Query result.
:rtype: list
"""
self.__connect()
self.__cursor.execute(self.query_string, self.dict())
result = self.__cursor.fetchall()
self.__disconect()
if total:
return result, self.__cursor.rowcount
return result
@abc.abstractclassmethod
def dict(self):
raise NotImplementedError |
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class RoomResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'summary' => $this->summary,
'price_per_night' => $this->price_per_night,
'guest_number' => $this->guest_number,
'location' => $this->location,
'language' => $this->langauges->name,
'room_type_id' => $this->types->name,
'services' => $this->services->pluck('name'),
'images' =>ImageResource::collection($this->images) ,
];
}
} |
## Introduction
>[!definition]
>A language $A$ is **decidable**, or equivalently **recursive** if there exists a halting Turing machine $M$ such that $L(M)=A$. That is, there is a TM $M$ that given an input $w$, if $w$ is in $A$ halts in the accepting state and otherwise halts in the rejecting state.
Decidable problems are "solvable."
>[!lemma]
>Regular languages are decidable.
You can see this by continually moving right until the end. Then, when we hit $\_$, we accept/reject based on whether the state is in $F$.
>**Example.** $\mathrm{PRIMES}=\{0^p\mid p\text{ is a prime number}\}$
>
>>[!solution]+
>>$$\begin{align}
\hline
&\textbf{High-level Algorithm}\\
\hline
&\text{\bf if } p = 0 \lor p = 1 \textbf{ then } \text{accept} \\
&\text{\bf else } \\
&\quad i\leftarrow 2 \\
&\quad \textbf{while }i<p: \\
&\quad\quad\text{\textbf{if} $p$ is a multiple of $i$ \textbf{then} stop and accept}\\
&\quad\quad i\leftarrow i+1 \\
&\quad \text{accept} \\
\hline
\end{align}$$
>>From a high level, we look at the remaining $0$s, increasing the number of $1$s by one each time, to check if the number is divisible by any number.
>>
>>1. Check if input is $\varepsilon$ or $0$. If so, accept.
>>2. If not, add $\#$ at the beginning and replace the first two $0$s with $1$s.
>>3. Check if remaining number of $0$s is divisible by 2. If so, stop and reject, else change first $0$ to $1$.
>>4. Check if remaining number of $0$s is divisible by 3. If so, stop and reject, else change next $0$ to $1$, and so on.
>>
>>To check if the number of $0$'s is divisible by the number of $1$s, repeatedly subtract the number of $1$s from the number of $0$s. For each $1$ find a corresponding $0$ and change it to $\mathrm y$. If no $0$ is found, answer is NO, otherwise YES.
>>
>>See slides for step-by-step.
>>
## Closure
### Closure Under Intersection
Given two decidable languages $A_1$ and $A_2$, there exist halting TMs $M_1$ and $M_2$ such that $L(M_1)=A_1$ and $L(M_2)=A_2$.
Consider the following TM $M$, given input $w$:
$$\begin{align}
\hline
&\text{Execute $M_1$ on $w$}\\
&\text{{\bf if} $M_1$ accepts {\bf then}}\\
&\quad\text{Execute $M_2$ on $w$} \\
&\quad\text{{\bf if} $M_2$ accepts {\bf then} ACCEPT {\bf else} REJECT}\\
&\text{{\bf else} REJECT}\\
\hline
\end{align}$$
$M$ is a halting TM, and $L(M)=A_1\cap A_2$.
### Closure Under Union
Given two decidable languages $A_1$ and $A_2$, there exist halting TMs $M_1$ and $M_2$ such that $L(M_1)=A_1$ and $L(M_2)=A_2$.
Consider the following TM $M$, given input $w$:
$$\begin{align}
\hline
&\text{Execute $M_1$ on $w$}\\
&\text{{\bf if} $M_1$ accepts {\bf then} ACCEPT}\\
&\text{{\bf else}}\\
&\quad\text{Execute $M_2$ on $w$} \\
&\quad\text{{\bf if} $M_2$ accepts {\bf then} ACCEPT {\bf else} REJECT}\\
\hline
\end{align}$$
$M$ is a halting TM, and $L(M)=A_1\cup A_2$.
### Closure Under Complement
Decidable languages are closed under complementation. We can do this by just switching $q_a$ and $q_r$. |
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap/dist/js/bootstrap.bundle';
import './App.css';
import LoadingBar from 'react-top-loading-bar'
import React, { Component } from 'react'
import Navbar from './Components/Navbar';
import News from './Components/News';
import {
BrowserRouter as Router,
Routes,
Route
}from "react-router-dom";
import Home from './Components/Home';
export default class App extends Component {
pageSize = 15;
state = {
progress : 0
}
setProgress=(progress)=>{
this.setState({progress:progress})
}
render() {
return (
<div>
<Router>
<Navbar/>
<LoadingBar
height={3}
color='#f11946'
progress={this.state.progress}
// onLoaderFinished={() => setProgress(0)}
/>
<Routes>
{/* <Route exact path="/signup" element={<Signup/>}/>
<Route exact path="/login" element={<Login/>}/> */}
<Route exact path="/" element={<Home/>}/>
<Route exact path="/general" element={<News setProgress={this.setProgress} key="general" pageSize={15} country='in' category='general'/>}/>
<Route exact path="/business" element={<News setProgress={this.setProgress} key="business" pageSize={15} country='in' category='business'/>}/>
<Route exact path="/entertainment" element={<News setProgress={this.setProgress} key="entertainment" pageSize={15} country='in' category='entertainment'/>}/>
<Route exact path="/health" element={<News setProgress={this.setProgress} key="health" pageSize={15} country='in' category='health'/>}/>
<Route exact path="/science" element={<News setProgress={this.setProgress} key="science" pageSize={15} country='in' category='science'/>}/>
<Route exact path="/sports" element={<News setProgress={this.setProgress} key="sports" pageSize={15} country='in' category='sports'/>}/>
<Route exact path="/technology" element={<News setProgress={this.setProgress} key="technology" pageSize={15} country='in' category='technology'/>}/>
</Routes>
</Router>
</div>
)
}
} |
import React, { useState } from 'react';
import { snake2NameCase } from '../../utils/common';
const Table = ({ data, id = true, headers = [], headerNames = [], actions = [], className }) => {
if (!data || !data.length) {
return <h3>Nothing to show</h3>;
}
const [filteredData, setFilteredData] = useState(data);
if (headers.length) {
data = data.map((item) => {
let tempItem = { ...item };
Object.keys(tempItem).forEach((key) => {
if (!headers.includes(key)) {
delete tempItem[key];
}
});
return tempItem;
});
}
let header = Object.keys(data[0]);
if (headerNames.length) {
if (headers.length) {
if (headers.length !== headerNames.length) {
throw new Error('Headers and Header Names length must be same');
}
} else {
if (header.length !== headerNames.length) {
throw new Error('Headers and Header Names length must be same');
} else {
header = headerNames;
}
}
}
if (!id) {
header = header.filter((item) => item.toLowerCase().replace('_', '') !== 'id');
}
return !data.length ? (
<h3>Nothing to show</h3>
) : (
<div className="card">
<table className={className}>
<thead>
<tr>
{header.map((key, index) => (
<td key={index}>{snake2NameCase(key)}</td>
))}
{actions.length > 0 && <td colSpan={actions.length}>Actions</td>}
</tr>
</thead>
<tbody>
{filteredData.map((item) => {
let tempItem = { ...item };
!id && delete tempItem.id
return (<tr key={item.id}>
{Object.values(tempItem).map((value, index) => (
<td key={index}>{value.toString()}</td>
))}
{actions.length > 0 && <td>
{actions.map((action, index) => {
return <button key={index} onClick={() => action.handler(item.id)}>{action.name}</button>
})}
</td>}
</tr>)
})}
</tbody>
</table>
</div>
);
};
export default Table; |
# Karma Core
Karma Core is a React Provider Component that is intended to provide each micro-frontend application its core functionality such Context, Session Management, GraphQL Connection, and Responsive Layouts. To do so, the application is wrapped in a [Provider Component](https://reactjs.org/docs/context.html#contextprovider). This [Provider Component](https://reactjs.org/docs/context.html#contextprovider) is a [Organization Scoped Private Node Package](https://docs.npmjs.com/about-private-packages) stored within NPM. This means, in order to install the package locally, you must have an NPM account associated with the Karma Organization.
- Do you have access? [Click here to check](https://www.npmjs.com/package/@hatech/karma-core)
- If you see a 404 page then you do NOT have access
- If you see the Readme page then you DO have access
- How do you get access?
- [Create a NPM account](https://docs.npmjs.com/creating-a-new-npm-user-account) if you do NOT already have one
- Contact Kevin Li/Praneeth to add your user to the Karma Organization
- Login to your npm account locally by running `npm login`
- How can I learn more about the [Karma Provider](https://www.npmjs.com/package/@hatech/karma-core) and its functionality
- Once you are granted access to the [Karma Provider](https://www.npmjs.com/package/@hatech/karma-core) NPM Package you can view the Readme associated with the package for more details
## Example Usage
```
import Karma from "@hatech/karma-core";
import React from "react";
const App: React.FC = () => {
return <Karma>Content</Karma>;
};
export default App;
```
## How To Use Context
Along with providing your application a responsive layout the Karma Provider also provides context data to your application via the [React Context API](https://reactjs.org/docs/context.html#contextprovider). The context provider value is an object consisting of two properties `state` and `dispatch`. If you're familiar with Redux then you understand the concept of state and the dispatching of an action. If not, no worries, below is an example usage of the context.
### Things to know before usage
- State is simply data temporarily stored in a React Component or in React Context. In this case we are referring to React Context. Data stored in React Context can be retrieved by any component within the Context Provider.
- Dispatch is a function which invokes a reducer and causes a change in state. Therefore, to change the `state` of context you must `dispatch` an action.
### Drawer Context Example
The Karma Provider applies a layout to the micro-frontend which includes a slideout menu drawer on tablet and mobile devices. The following example shows the use of both the `state` and `dispatch` properties of the context provider. Please remember the slideout menu is for tablet and mobile devices so for this to work you must view the application within a viewport less than 900px.
```
import { DrawerContext } from "@hatech/karma-core/context/drawer";
import Button from "@material-ui/core/Button";
import React from "react";
const Example: React.FC = () => {
const { state, dispatch } = React.useContext(DrawerContext);
const text = state === "main" ? "Close Drawer" : "Open Drawer";
const handleClick = () => {
dispatch({ type: "TOGGLE_DRAWER", payload: "main" });
};
return (
<Button onClick={handleClick} variant="contained">
{text}
</Button>
);
};
export default Example;
```
### Alerts Context Example
The Karma Provider allows you to quickly send a popup alert to the user via the `AlertsContext`. Below is an example of using the `dispatch` property of the context provider.
```
import { AlertsContext } from "@hatech/karma-core/context/alerts";
import Button from "@material-ui/core/Button";
import React from "react";
const Example: React.FC = () => {
const { dispatch } = React.useContext(AlertsContext);
const handleClick = () => {
const dialog = { title: "Super Alert", body: "I'm an alert" };
dispatch({ type: "ADD_ALERT", payload: dialog });
};
return (
<Button onClick={handleClick} variant="contained">
Add Alert
</Button>
);
};
export default Example;
```
### User Context Example
The Karma Provider allows you to retrieve data about the current logged in user from anywhere within the application. Below is an example of using the `state` property of the context provider.
```
import { UserContext } from "@hatech/karma-core/context/user";
import React from "react";
const Example: React.FC = () => {
const { state } = React.useContext(UserContext);
const text = state ? `Hello ${state.identity["cognito:username"]}` : "User is not logged in";
return <div>{text}</div>;
};
export default Example;
```
# hatech-core |
// RecipeDetailsRouter.swift
import UIKit
import SafariServices
enum RecipeDetailsDestination {
case recipeWebPage(_ url: URL)
case shareRecipe(_ url: URL)
}
final class RecipeDetailsRouter: BaseRouter, RecipeDetailsRouterProtocol {
static func createModule(recipe: RecipeModel) -> UIViewController {
let view = RecipeDetailsViewController.instance()
let interactor = RecipeDetailsInteractor()
let router = RecipeDetailsRouter()
let presenter = RecipeDetailsPresenter(recipe: recipe, view: view, interactor: interactor, router: router)
interactor.presenter = presenter
router.viewController = view
view.presenter = presenter
view.title = ScreenTitles.recipeDetails.title
return view
}
func navigate(to destination: RecipeDetailsDestination) {
switch destination {
case .recipeWebPage(let url):
openRecipeWebPage(with: url)
case .shareRecipe(let url):
shareRecipe(url)
}
}
private func openRecipeWebPage(with url: URL) {
let config = SFSafariViewController.Configuration()
config.entersReaderIfAvailable = true
let vc = SFSafariViewController(url: url, configuration: config)
viewController?.present(vc, animated: true)
}
private func shareRecipe(_ url: URL) {
let activityController = UIActivityViewController(activityItems: [url], applicationActivities: nil)
viewController?.present(activityController, animated: true)
}
} |
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: Screen(),
);
}
}
class Screen extends StatefulWidget {
const Screen({super.key});
@override
State<Screen> createState() => _ScreenState();
}
class _ScreenState extends State<Screen> {
String result = " ";
final controll1 = TextEditingController();
final controll2 = TextEditingController();
void Calcultion(){
double Num1 = controll1.text.trim().isEmpty ? 0.0 : double.parse(controll1.text.trim().toString());
double Num2 = controll2.text.trim().isEmpty ? 0.0 : double.parse(controll2.text.trim().toString());
setState(() {
switch(Selectedgroup){
case 0 :
result = (Num1 + Num2).toString();
break;
case 1 :
result = (Num1 - Num2).toString();
break;
case 2 :
result = (Num1 * Num2).toString();
break;
case 3 :
result = (Num1 ~/ Num2).toString();
break;
}
});
}
int ? Selectedgroup ;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Material App Bar'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
controller: controll1,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: " Enter Number 1"
),
),
TextField(
controller: controll2,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: " Enter Number 1"
),
),
RadioListTile(value: 0,
groupValue: Selectedgroup ,
onChanged:(value) {
setState(() {
Selectedgroup = value;
});
},title: Text("+"),),
RadioListTile(value: 1,
groupValue: Selectedgroup ,
onChanged:(value) {
setState(() {
Selectedgroup = value;
});
},title: Text("-"),),
RadioListTile(value: 2,
groupValue: Selectedgroup ,
onChanged:(value) {
setState(() {
Selectedgroup = value;
});
},title: Text("*"),),
RadioListTile(value: 3,
groupValue: Selectedgroup ,
onChanged:(value) {
setState(() {
Selectedgroup = value;
});
},title: Text("/"),),
ElevatedButton(onPressed: () {
Calcultion();
},
child: Text("RESULT")),
Text("${result}"),
],
),
),
);
}
} |
import express, { Express, NextFunction, Request, Response } from "express";
import bodyParser from "body-parser";
import cors from "cors";
import helmet from "helmet";
import serverless from "serverless-http";
import rateLimit from "express-rate-limit";
import morgan from "morgan";
import requestIp from "request-ip";
import { CLIENT } from "./lib/constants";
import lockerApi from "./services/locker";
import meetingApi from "./services/meeting";
// Rate limiting configuration
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs
message: "Too many requests from this IP, please try again later.",
keyGenerator: (req, res) => {
return req.clientIp || "default ip"; // IP address from requestIp.mw(), as opposed to req.ip
},
});
const app: Express = express();
app.set("trust proxy", false);
app.use(requestIp.mw());
app.use(cors({ origin: CLIENT, credentials: true }));
app.use(helmet());
app.use(bodyParser.json());
app.use((req: Request, res: Response, next: NextFunction) => {
res.setHeader("Content-Type", "application/json");
next();
});
app.use(limiter);
app.use(morgan("combined"));
app.use(`/.netlify/functions/api/locker`, lockerApi); //for locker project
app.use(`/.netlify/functions/api/meeting`, meetingApi); //for meeting booking project
export const handler = serverless(app); |
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import json
import re
import os
import pandas as pd
def get_content(url):
user_agent = UserAgent().random.strip()
headers = {'User-Agent': user_agent}
response = requests.get(url, headers=headers)
if response.status_code == 200:
html_content = response.text
soup = BeautifulSoup(html_content, 'html.parser')
return soup
else:
return -1
def delete_param(url):
match = re.match(r'([^?]*)\?', url)
if match:
return match.group(1)
else:
return url
def get_categories():
soup = get_content("https://kaminvdom.ru/")
data = []
links = soup.find_all(class_='nsmenu-parent-title')
for link in links:
data.append(link.attrs['href'])
with open("categories.json", 'w') as json_file:
json.dump(data, json_file)
def get_cards(url):
soup = get_content(f"{url}?limit=1000")
data = []
cards = soup.find_all(class_='product-list')
for card in cards:
link = card.find(class_='caption').find('a').attrs['href']
link = delete_param(link)
data.append(link)
category = url.replace("https://kaminvdom.ru/", "")
with open(f"cards/{category}.json", 'w') as json_file:
json.dump(data, json_file)
def get_params(url):
soup = get_content(url)
name = soup.find('h1').text
categories_res = ""
categories = soup.find(class_="breadcrumb").find_all("span")
for categ in categories:
if categ.text == "":
continue
if name in categ.text:
continue
if categories_res != "":
categories_res += "/"
categories_res += categ.text
images_res = []
images = soup.find(class_='thumbnails').find_all('img')
for image in images:
image = image.attrs['src']
image = image.replace('cache/', '')
image = image[:image.rfind('-')] + image[image.rfind('.'):]
images_res.append(image)
images_res = ', '.join(images_res)
ul = soup.find(class_="deshevle").find_next_sibling(class_="list-unstyled")
brend = ul.find('img')
if brend != None:
brend = brend.attrs['title']
else:
brend = ""
lists = ul.find_all('li')
for li in lists:
if 'Модель' in li.text:
model = li.text.replace("Модель: ", "")
prices = soup.find_all(class_='priceprod')
if len(prices) > 1:
old_price = prices[0].text.replace(" руб", "")
new_price = prices[1].text.replace(" руб", "")
else:
old_price = ""
new_price = prices[0].text.replace(" руб", "")
description = soup.find(id='tab-description').decode_contents()
input_elements = soup.find(id='product').select("input[type='radio']")
values = [input_element.next.strip() for input_element in input_elements]
count = soup.find(id='product').find('input', {'name': 'quantity'}).attrs['value']
rows = soup.find(id='tab-specification')
spec_dict = {}
if rows != None:
rows = rows.select("tbody tr")
else:
rows = []
for row in rows:
col = row.find_all("td")
name_spec = col[0].text
value_spec = col[1].text
spec_dict[name_spec] = value_spec
if os.path.exists('result1.csv'):
df = pd.read_csv('result1.csv', encoding='utf-8', sep=';')
else:
df = pd.DataFrame()
if len(values) == 0:
new_row = {
'Категория' : categories_res,
'Товар' : name,
'Цена' : new_price,
'Адрес' : '',
'Видим' : count,
'Хит' : '',
'Бренд' : brend,
'Вариант' : '',
'Старая цена' : old_price,
'Артикул' : '',
'Склад' : '',
'Модель' : model,
'Заголовок страницы' : '',
'Ключевые слова' : '',
'Описание страницы' : '',
'Аннотация' : '',
'Описание' : description,
'Изображения' : images_res
}
new_row.update(spec_dict)
df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
else:
for value in values:
new_row = {
'Категория' : categories_res,
'Товар' : name,
'Цена' : new_price,
'Адрес' : '',
'Видим' : count,
'Хит' : '',
'Бренд' : brend,
'Вариант' : value,
'Старая цена' : old_price,
'Артикул' : '',
'Склад' : '',
'Модель' : model,
'Заголовок страницы' : '',
'Ключевые слова' : '',
'Описание страницы' : '',
'Аннотация' : '',
'Описание' : description,
'Изображения' : images_res
}
new_row.update(spec_dict)
df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
df.to_csv('result1.csv', index=False, encoding='utf-8', sep=';')
def parse_all():
file_names = os.listdir('cards')
errors = {}
for file_name in file_names:
print(f"Парсим {file_name}")
with open(f'cards/{file_name}', 'r') as json_file:
urls = json.load(json_file)
for url in urls:
try:
get_params(url)
except Exception as e:
print(url)
print(str(e))
errors[url] = str(e)
with open(f"errors.json", 'w') as json_file:
json.dump(errors, json_file)
def main():
#get_categories()
#with open("categories.json", 'r') as json_file:
# categories = json.load(json_file)
#for categ in categories:
# get_cards(categ)
parse_all()
if __name__ == "__main__":
main() |
import BaseCommand from "@structures/BaseCommand";
import BaseClient from "@structures/BaseClient";
import { SlashCommandBuilder, EmbedBuilder } from "discord.js";
export default class UnmuteCommand extends BaseCommand {
public constructor(client: BaseClient) {
super(client, {
name: "unmute",
description: "Entmutet ein Mitglied",
memberPermissions: ["KickMembers"],
cooldown: 1000,
dirname: __dirname,
slashCommand: {
addCommand: true,
data: new SlashCommandBuilder().addUserOption((option: any) =>
option
.setName("mitglied")
.setDescription("Wähle ein Mitglied")
.setRequired(true)
)
}
});
}
private interaction: any;
public async dispatch(interaction: any, data: any): Promise<void> {
this.interaction = interaction;
await this.unmute(interaction.options.getUser("mitglied"), data);
}
private async unmute(user: any, data: any): Promise<void> {
const member: any = await this.interaction.guild.resolveMember(user.id);
if (!member) {
const invalidOptionsEmbed: EmbedBuilder = this.client.createEmbed(
"Du musst ein Mitglied angeben.",
"error",
"error"
);
return this.interaction.followUp({ embeds: [invalidOptionsEmbed] });
}
const memberData: any = await this.client.findOrCreateMember(
user.id,
this.interaction.guild.id
);
if (!memberData.muted.state) {
const isNotMutedEmbed: EmbedBuilder = this.client.createEmbed(
"{0} ist nicht gemutet.",
"error",
"error",
user.username
);
return this.interaction.followUp({ embeds: [isNotMutedEmbed] });
}
member.roles
.remove(
data.guild.settings.muterole,
"Vorzeitiger Unmute durch " + this.interaction.user.username
)
.catch((): void => {});
memberData.muted = {
state: false,
reason: null,
moderator: {
name: null,
id: null
},
duration: null,
mutedAt: null,
mutedUntil: null
};
memberData.markModified("muted");
await memberData.save();
this.client.databaseCache.mutedUsers.delete(user.id + this.interaction.guild.id);
const logText: string =
"### " +
this.client.emotes.timeout +
" " +
user.username +
" wurde entmutet\n\n" +
this.client.emotes.user +
" Moderator: " +
this.interaction.user.username;
const logEmbed: EmbedBuilder = this.client.createEmbed(logText, null, "normal");
logEmbed.setThumbnail(user.displayAvatarURL());
await this.interaction.guild.logAction(logEmbed, "moderation");
const successEmbed: EmbedBuilder = this.client.createEmbed(
"{0} wurde entmutet.",
"success",
"success",
user.username
);
return this.interaction.followUp({ embeds: [successEmbed] });
}
} |
package com.koleff.stockserver.stocks.utils.jsonUtil.base;
import com.google.gson.Gson;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
public abstract class JsonUtil<T> {
@Value("${koleff.versionAnnotation}") //Configuring version annotation for Json loading / exporting
private String versionAnnotation;
private final static Logger logger = LogManager.getLogger(JsonUtil.class);
private final String resourcePath = "src/main/resources/json/%s/%s/%s";
@Qualifier("gson")
private final Gson gson;
@Autowired
public JsonUtil(Gson gson) {
this.gson = gson;
}
/**
* Used to parse JSON to class T
*
* @return parametrized type T initialized in different child classes
*/
protected abstract Type getType();
/**
* Used to get json parent directory
* Example: json/v2/eod/eodAAPLV2.json
*/
protected abstract String getDirectory();
/**
* Load JSON from file
*
* @param jsonPath path to JSON file with data
* @return json data
*/
public String loadJson(String jsonPath) {
logger.info("Loading JSON...");
String filePath = String.format(resourcePath, versionAnnotation, getDirectory(), jsonPath);
logger.info(String.format("JSON file path: %s", filePath));
File jsonFile = new File(filePath);
String json = null;
try {
JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(
new FileReader(jsonFile)
);
json = data.toJSONString();
} catch (IOException | ParseException e) {
logger.error(String.format("Failed to parse JSON. File exists -> %s\n", jsonFile.exists()));
}
logger.info(String.format("JSON successfully loaded!\n JSON: %s", json));
return json;
}
/**
* Map JSON to custom object
* - SerializedName() only works for serialization.
* - For deserialization @JsonAlias from jackson library is supported by Spring.
*
* @param json data in JSON format
* @return json mapped to custom object T
*/
public T convertJson(String json) {
logger.info("Converting JSON...");
T entity = gson.fromJson(json, getType());
logger.info(String.format("JSON was parsed to: %s", entity.toString()));
return entity;
}
/**
* Saves data to JSON
* Used for IntraDay and EndOfDay entities
*
* @param response data
* @param requestName remote api request name used for configuring JSON file name
* @param versionAnnotation which JSON file to use (V2 is with configured ids)
* @param stockTag stock tag
*/
public void exportToJson(T response, String requestName, String versionAnnotation, String stockTag) {
String jsonPath;
//Create file path based on request
switch (requestName) {
case "intraday":
jsonPath = String.format("intraday%s%s.json", stockTag, versionAnnotation);
break;
case "eod":
jsonPath = String.format("eod%s%s.json", stockTag, versionAnnotation);
break;
default:
return;
}
logger.info(String.format("Json name: %s", jsonPath));
export(response, jsonPath);
}
/**
* Saves data to JSON
* Used for Stock and StockExchange entities
* - V2 suffix means configured JSON files
*
* @param response data
* @param requestName remote api request name used for configuring JSON file name
* @param versionAnnotation which JSON file to use (V2 is with configured ids)
*/
public void exportToJson(T response, String requestName, String versionAnnotation) {
String jsonPath;
//Create file path based on request
switch (requestName) {
case "exchanges":
jsonPath = String.format("exchanges%s.json", versionAnnotation);
break;
case "tickers":
jsonPath = String.format("tickers%s.json", versionAnnotation);
break;
default:
return;
}
logger.info(String.format("Json name: %s", jsonPath));
export(response, jsonPath);
}
/**
* Saves data to JSON. Writes to file
*
* <p> When using Jackson library for JSON converting:
* <p> - serialize data with JsonProperty() instead of SerializedName()
* <p> - use ObjectMapper() for converting instead of Gson
* <p> - Gson is not compatible with Jackson.
*
* @param response data
* @param jsonPath file path
*/
private void export(T response, String jsonPath) {
logger.info("Exporting data to JSON...");
String filePath = String.format(resourcePath, versionAnnotation, getDirectory(), jsonPath);
logger.info(String.format("JSON file path: %s", filePath));
//Convert response to JSON
String json;
logger.info(String.format("Data before converting to JSON: %s", response));
json = gson.toJson(response);
//Write JSON in file
File jsonFile = new File(filePath);
try {
FileWriter file = new FileWriter(jsonFile);
file.write(json);
file.close();
} catch (IOException e) {
logger.error("JSON could not be exported to file.");
return;
}
logger.info(String.format("JSON file successfully created! JSON file content: %s\n", json));
}
} |
import { Fragment, useState } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { NavLink, useSearchParams } from 'react-router-dom';
import classNames from 'classnames/bind';
import { useForgotPasswordMutation } from '../../../app/api';
import {ReactComponent as IconArrowLeft} from '../../../assets/img/Icon_arrow_left.svg';
import { FormFooter } from '../../../components/form-blocks/form-footer';
import { FormStatusBlock } from '../../../components/form-blocks/form-status-block';
import { Input } from '../../../components/form-blocks/input-password';
import { PATHS } from '../../../constants/path-routing';
import { RestorePassword } from './restore-password';
import styleDefault from '../auth-forms-default.module.css';
import style from './forgot-password.module.css';
export type FormForgotPasswordType = {
email: string
}
export const ForgotPasswordPage = () => {
const classesDefault = classNames.bind(styleDefault);
const [forgot, {isSuccess, error}] = useForgotPasswordMutation();
const { register, formState: { errors, isValid, dirtyFields }, handleSubmit } = useForm<FormForgotPasswordType>({mode: 'all'});
const classes = classNames.bind(style);
const onSubmit: SubmitHandler<FormForgotPasswordType> = data => {
forgot(data);
};
const [ searchValue ] = useSearchParams();
const codeRestore = searchValue.get('code') || '';
const [isRestorePassword] = useState(searchValue.get('code') ? true : false);
const {onChange: onChangeSecondInput, onBlur: onBlurSecondInput, name: nameSecondInput, ref: refSecondInput} = register(
'email', {
validate: {
checkLength: (value: string) => value?.length > 0 || 'Поле не может быть пустым',
validateEmail: (value) => value.match(/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/) !== null || 'Введите корректный e-mail'
}}
);
return (
<div className={style.form_container}>
{!isSuccess && !isRestorePassword &&
<Fragment>
<div className={style.form_header}>
<NavLink to={PATHS.auth} className={style.form_header_link}><IconArrowLeft /><span>вход в личный кабинет</span></NavLink>
</div>
<div className={style.form_wrapper}>
<p className={styleDefault.title}>Восстановление пароля</p>
<form
onSubmit={handleSubmit(onSubmit)}
className={style.form}
data-test-id='send-email-form'
>
<Input
name={nameSecondInput}
innerRef={refSecondInput}
onBlur={onBlurSecondInput}
onChange={onChangeSecondInput}
defaultHint='На это email будет отправлено письмо с инструкциями по восстановлению пароля'
defaultHintError='Введите корректный e-mail'
dirtyFields={dirtyFields}
errors={errors}
placeholder='E-mail'
showCheckMark={false}
showDefaultHint={true}
onChangeMode={false}
checkOnDirtyEyesIcon={false}
inputType='text'
showEyesIcon={false}
/>
{error &&
<span
data-test-id='hint'
className={classes('message_error_response'
)}
>
{error && 'error'}
</span>
}
<button
type="submit"
className={classesDefault(
'btn__submit_form',
{'btn__submit_form_disabled': !isValid }
)}
disabled={!isValid}
>восстановить</button>
</form>
<FormFooter
link={PATHS.registration}
linkMessage='РЕГИСТРАЦИЯ'
questionMessage='Нет учётной записи?'
/>
</div>
</Fragment>
}
{isSuccess &&
<div className={style.status_block}>
<FormStatusBlock
text='Перейдите в вашу почту, чтобы воспользоваться подсказками по восстановлению пароля'
title='Письмо выслано'
/>
</div>
}
{isRestorePassword &&
<RestorePassword code={codeRestore}/>
}
</div>
)
} |
package com.saeyan.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import util.DBManager;
import com.saeyan.dto.BoardVO;
public class BoardDAO {
private BoardDAO() {
}
private static BoardDAO instance = new BoardDAO();
public static BoardDAO getInstance() {
return instance;
}
public List<BoardVO> selectAllBoards() {
String sql = "select * from board order by num desc";
List<BoardVO> list = new ArrayList<BoardVO>();//글목록
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DBManager.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql); //글행집합
while (rs.next()) {
// VO클래스 = 테이블
// 테이블당 최소 1개의 VO 필요
// 테이블당 최소 1개의 DAO 필요
// VO객체 = 행
BoardVO bVo = new BoardVO();//글(VO)
bVo.setNum(rs.getInt("num"));
bVo.setName(rs.getString("name"));
bVo.setEmail(rs.getString("email"));
bVo.setPass(rs.getString("pass"));
bVo.setTitle(rs.getString("title"));
bVo.setContent(rs.getString("content"));
bVo.setReadcount(rs.getInt("readcount"));
bVo.setWritedate(rs.getTimestamp("writedate"));
list.add(bVo);//글목록에 글(VO) 추가
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBManager.close(conn, stmt, rs);
}
return list;
}
public void insertBoard(BoardVO bVo) {
String sql = "insert into board("
+ "num, name, email, pass, title, content) "
+ "values(board_seq.nextval, ?, ?, ?, ?, ?)";
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DBManager.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, bVo.getName());
pstmt.setString(2, bVo.getEmail());
pstmt.setString(3, bVo.getPass());
pstmt.setString(4, bVo.getTitle());
pstmt.setString(5, bVo.getContent());
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBManager.close(conn, pstmt);
}
}
public void updateReadCount(String num) {
String sql = "update board set readcount=readcount+1 where num=?";
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DBManager.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, num);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBManager.close(conn, pstmt);
}
}
// num으로 게시글 조회
public BoardVO selectOneBoardByNum(String num) {
String sql = "select * from board where num = ?";
BoardVO bVo = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DBManager.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, num);
rs = pstmt.executeQuery();
if (rs.next()) {
bVo = new BoardVO();
bVo.setNum(rs.getInt("num"));
bVo.setName(rs.getString("name"));
bVo.setPass(rs.getString("pass"));
bVo.setEmail(rs.getString("email"));
bVo.setTitle(rs.getString("title"));
bVo.setContent(rs.getString("content"));
bVo.setWritedate(rs.getTimestamp("writedate"));
bVo.setReadcount(rs.getInt("readcount"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBManager.close(conn, pstmt, rs);
}
return bVo;
}
public void updateBoard(BoardVO bVo) {
String sql = "update board set name=?, email=?, pass=?, "
+ "title=?, content=? where num=?";
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DBManager.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, bVo.getName());
pstmt.setString(2, bVo.getEmail());
pstmt.setString(3, bVo.getPass());
pstmt.setString(4, bVo.getTitle());
pstmt.setString(5, bVo.getContent());
pstmt.setInt(6, bVo.getNum());
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBManager.close(conn, pstmt);
}
}
public BoardVO checkPassWord(String pass, String num) {
String sql = "select * from board where pass=? and num=?";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
BoardVO bVo = null;
try {
conn = DBManager.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, pass);
pstmt.setString(2, num);
rs = pstmt.executeQuery();
if (rs.next()) {
bVo = new BoardVO();
bVo.setNum(rs.getInt("num"));
bVo.setName(rs.getString("name"));
bVo.setEmail(rs.getString("email"));
bVo.setPass(rs.getString("pass"));
bVo.setTitle(rs.getString("title"));
bVo.setContent(rs.getString("content"));
bVo.setReadcount(rs.getInt("readcount"));
bVo.setWritedate(rs.getTimestamp("writedate"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return bVo;
}
public void deleteBoard(String num) {
String sql = "delete board where num=?";
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DBManager.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, num);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
} |
package tech.ada.pagamento.controller;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import tech.ada.pagamento.exception.GetMoneyException;
import tech.ada.pagamento.exception.UserNotFoundException;
@RestControllerAdvice
public class PagamentoExceptionHandler {
public PagamentoExceptionHandler() {
}
@ExceptionHandler({RuntimeException.class})
public ProblemDetail exceptionHandler(RuntimeException exception) {
ProblemDetail problemDetails = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(503), exception.getMessage());
problemDetails.setTitle("RunTime Exception - Object Not Found");
return problemDetails;
}
@ExceptionHandler({GetMoneyException.class})
public ProblemDetail handleInsuficientFoundsException(GetMoneyException e) {
ProblemDetail problemDetails = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(400), e.getMessage());
problemDetails.setTitle("RunTime Exception - Insuficient founds");
return problemDetails;
}
@ExceptionHandler({UserNotFoundException.class})
public ProblemDetail handleUserNotFoundException(UserNotFoundException e) {
ProblemDetail problemDetails = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(404), e.getMessage());
problemDetails.setTitle("RunTime Exception - User Not Found");
return problemDetails;
}
} |
import { useContext, useEffect, useState } from 'react';
import {
Collapse,
IconButton,
TableCell,
TableRow,
Tooltip,
} from '@mui/material';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import { Link, useLocation } from 'react-router-dom';
import LinkIcon from '@mui/icons-material/Link';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { useSnackbar } from 'notistack';
import TimestampDateDisplay from '../TimestampDateDisplay';
import TokenAmountDisplay from '../TokenAmountDisplay';
import Chart from '../Chart';
import { formatTokenAmount, toCompactString } from '../../utils';
import { INearProps, NearContext } from '../../services/near';
import { TMetadata } from '../../services/tokenApi';
import { TLockup } from '../../services/api';
import TerminateLockup from '../TerminateLockup';
import TerminateWithDaoButton from '../TerminateWithDaoButton';
import ScheduleTable from '../ScheduleTable';
import { chartData } from '../../services/chartHelpers';
import { calcBalancesRaw } from '../../services/scheduleHelpers';
import { enqueueCustomSnackbar } from '../Snackbars/Snackbar';
import success from '../Snackbars/SuccessPartials';
export default function Row({
opened, adminControls, row, token,
}: { opened: boolean, adminControls: boolean, row: TLockup, token: TMetadata }) {
const location = useLocation();
const currentContractName = location.pathname.split('/')[1];
const [open, setOpen] = useState<boolean>(false);
const { enqueueSnackbar } = useSnackbar();
const {
near,
}: {
near: INearProps | null
} = useContext(NearContext);
const [now, _setNow] = useState<number>(Math.floor(new Date().getTime() / 1000));
const [hasBeenOpen, setHasBeenOpen] = useState<boolean>(false);
useEffect(() => {
setOpen(opened);
setHasBeenOpen(opened);
}, [opened]);
if (!near) return null;
const { isAdmin } = near.currentUser;
const vestingSchedule = row?.termination_config?.vesting_schedule?.Schedule;
const selectedAccountPage = window.location.href.split('/').pop() === row.account_id;
const selectedLockupId = window.location.href.split('/').pop() === row.id.toString();
const balancesRaw = calcBalancesRaw(row, now);
const claimedAmount = `${formatTokenAmount(balancesRaw.claimed, token.decimals)}`;
const availbleAmount = `${formatTokenAmount(balancesRaw.unclaimed, token.decimals)}`;
const vestedAmount = `${formatTokenAmount(balancesRaw.vested, token.decimals)}`;
const unvestedAmount = `${formatTokenAmount(balancesRaw.unvested, token.decimals)}`;
let payerMessage;
if (!row.termination_config?.beneficiary_id) {
payerMessage = 'This lockup cannot be terminated';
} else {
payerMessage = `Unvested amount will return to ${row.termination_config?.beneficiary_id}`;
}
const terminatorId = row?.termination_config?.beneficiary_id;
const terminateButton = (terminator: string) => {
if (!adminControls) {
return null;
}
return (
<>
<div>
{isAdmin && (
<TerminateLockup
token={token}
adminControls={adminControls}
lockupIndex={row.id}
config={row.termination_config}
buttonText={terminator ? 'Terminate' : 'No termination config'}
lockup={row}
/>
)}
</div>
<div>
<TerminateWithDaoButton
accountId={row.account_id}
token={token}
adminControls={adminControls}
lockupIndex={row.id}
config={row.termination_config}
buttonText={terminator ? 'Terminate with Dao' : 'No termination config'}
lockup={row}
/>
</div>
</>
);
};
return (
<>
<TableRow className={open ? 'expanded exp-row' : 'exp-row'}>
<TableCell>
<IconButton
aria-label="expand row"
size="small"
onClick={() => { setOpen(!open); setHasBeenOpen(true); }}
>
{open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
</IconButton>
</TableCell>
<TableCell align="left">
{!selectedLockupId
? <Link to={`/${currentContractName}${adminControls ? '/admin' : ''}/lockups/${row.account_id}/${row.id}`}>{row.id}</Link>
: row.id}
{!selectedLockupId && (
<CopyToClipboard
text={`${window.location.origin}/#/${currentContractName}/lockups/${row.account_id}/${row.id}`}
onCopy={() => enqueueCustomSnackbar(enqueueSnackbar, null, success.header('Copied'), { autoHideDuration: 1000 })}
>
<IconButton aria-label="copy link">
<LinkIcon />
</IconButton>
</CopyToClipboard>
)}
</TableCell>
<TableCell align="left">
{!selectedAccountPage
? <Link to={`/${currentContractName}${adminControls ? '/admin' : ''}/lockups/${row.account_id}`}>{toCompactString(row.account_id)}</Link>
: toCompactString(row.account_id)}
{!selectedAccountPage
&& (
<CopyToClipboard
text={`${window.location.origin}/#/${currentContractName}/lockups/${row.account_id}`}
onCopy={() => enqueueCustomSnackbar(enqueueSnackbar, null, success.header('Copied'), { autoHideDuration: 1000 })}
>
<IconButton aria-label="copy link">
<LinkIcon />
</IconButton>
</CopyToClipboard>
)}
</TableCell>
<TableCell align="right">
<TimestampDateDisplay unixSeconds={row.schedule[0].timestamp} />
</TableCell>
<TableCell align="right">
<TimestampDateDisplay unixSeconds={row.schedule[row.schedule.length - 1].timestamp} />
</TableCell>
<TableCell align="center">
{vestingSchedule ? 'Yes' : 'No'}
</TableCell>
<TableCell align="right">
<TokenAmountDisplay amount={row.total_balance} token={token} />
</TableCell>
<TableCell align="center">
<Tooltip
title={(
<div className="progress-bar__tooltip">
<span className="nowrap">
<i className="claimed"> </i>
<b>{claimedAmount}</b>
{' '}
Claimed
</span>
<span className="nowrap">
<i className="available"> </i>
<b>{availbleAmount}</b>
{' '}
Available
</span>
<span className="nowrap">
<i className="vested"> </i>
<b>{vestedAmount}</b>
{' '}
Vested
</span>
<span className="nowrap">
<i className="unvested"> </i>
<b>{unvestedAmount}</b>
{' '}
Unvested
</span>
</div>
)}
placement="top"
arrow
>
<div className="progress-bar-outer">
<div className="progress-bar">
<div style={{ width: `${balancesRaw.total === '0' ? '100' : (parseFloat(balancesRaw.claimed) / parseFloat(balancesRaw.total)) * 100}%` }} className="claimed">
</div>
<div style={{ width: `${balancesRaw.total === '0' ? '0' : (parseFloat(balancesRaw.unclaimed) / parseFloat(row.total_balance)) * 100}%` }} className="available">
</div>
<div style={{ width: `${balancesRaw.total === '0' ? '0' : (parseFloat(balancesRaw.vested) / parseFloat(row.total_balance)) * 100}%` }} className="vested">
</div>
<div style={{ width: `${balancesRaw.total === '0' ? '0' : (parseFloat(balancesRaw.unvested) / parseFloat(row.total_balance)) * 100}%` }} className="unvested">
</div>
</div>
</div>
</Tooltip>
</TableCell>
</TableRow>
<TableRow className="expanded">
<TableCell style={{ padding: 0 }} colSpan={8}>
<Collapse in={open} timeout="auto" unmountOnExit>
{ hasBeenOpen && (
<div className="lockup-row">
<ScheduleTable schedule={row.schedule} title="Lockup schedule" token={token} />
{vestingSchedule && (
<ScheduleTable schedule={vestingSchedule} title="Vesting schedule" token={token} />
)}
<div className="lockup-row-column chart">
<div style={{ height: 320 }}>
<Chart data={chartData([row], token.decimals)} />
</div>
{adminControls && (
<div className="terminate">
<span className="fine-print">{payerMessage}</span>
{terminatorId && terminateButton(terminatorId)}
</div>
)}
</div>
</div>
)}
</Collapse>
</TableCell>
</TableRow>
</>
);
} |
package redis
import (
"context"
"github.com/26huitailang/yogo/framework/provider/config"
"github.com/26huitailang/yogo/framework/provider/log"
tests "github.com/26huitailang/yogo/test"
. "github.com/smartystreets/goconvey/convey"
"testing"
"time"
)
func TestYogoService_Load(t *testing.T) {
container := tests.InitBaseContainer()
container.Bind(&config.YogoConfigProvider{})
container.Bind(&log.YogoLogServiceProvider{})
Convey("test get client", t, func() {
yogoRedis, err := NewYogoRedis(container)
So(err, ShouldBeNil)
service, ok := yogoRedis.(*YogoRedis)
So(ok, ShouldBeTrue)
client, err := service.GetClient(WithConfigPath("redis.write"))
So(err, ShouldBeNil)
So(client, ShouldNotBeNil)
ctx := context.Background()
err = client.Set(ctx, "foo", "bar", 1*time.Hour).Err()
So(err, ShouldBeNil)
val, err := client.Get(ctx, "foo").Result()
So(err, ShouldBeNil)
So(val, ShouldEqual, "bar")
err = client.Del(ctx, "foo").Err()
So(err, ShouldBeNil)
})
} |
<?php
include_once('../db.php');
$data = [
['state' => 'Punjab', 'city' => 'Bathinda'],
['state' => 'Punjab', 'city' => 'Jaito'],
['state' => 'Hariyana', 'city' => 'Gurgaon'],
['state' => 'Hariyana', 'city' => 'Ambala'],
['state' => 'Rajasthan', 'city' => 'Jaipur'],
];
// Create a states table
$query = "CREATE TABLE IF NOT EXISTS states (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL
)";
if ($conn->query($query) === TRUE) {
// Create a cities table with a foreign key
$query = "CREATE TABLE IF NOT EXISTS cities (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
state_id INT NOT NULL,
FOREIGN KEY (state_id) REFERENCES states(id)
)";
if ($conn->query($query) === TRUE) {
foreach ($data as $item) {
$state = $conn->real_escape_string($item['state']);
$city = $conn->real_escape_string($item['city']);
// Check if the state exists in the states table
$state_query = "SELECT id FROM states WHERE name = '$state'";
$state_result = $conn->query($state_query);
if ($state_result && $state_result->num_rows > 0) {
$state_row = $state_result->fetch_assoc();
$state_id = $state_row['id'];
} else {
// If the state does not exist, insert it
$conn->query("INSERT INTO states (name) VALUES ('$state')");
$state_id = $conn->insert_id;
}
// Insert the city into the cities table
$conn->query("INSERT INTO cities (name, state_id) VALUES ('$city', $state_id)");
}
echo "Cities and states tables created and populated successfully.";
} else {
echo "Error creating cities table: " . $conn->error;
}
} else {
echo "Error creating states table: " . $conn->error;
}
$query =
"CREATE TABLE IF NOT EXISTS course_info (
id INT AUTO_INCREMENT PRIMARY KEY,
course_name VARCHAR(255) NOT NULL,
duration VARCHAR(50) NOT NULL,
fee DECIMAL(10, 2) NOT NULL
)";
if ($conn->query($query) === TRUE) {
echo "Course Info table created successfully.";
} else {
echo "Error creating Course Info table: " . $conn->error;
}
$insertQueries = [
"INSERT INTO course_info (course_name, duration, fee) VALUES ('BCA', '3 years', 5000.00)",
"INSERT INTO course_info (course_name, duration, fee) VALUES ('MCA', '2 years', 6000.00)",
"INSERT INTO course_info (course_name, duration, fee) VALUES ('Btech', '4 years', 7000.00)",
];
foreach ($insertQueries as $query) {
if ($conn->query($query) !== TRUE) {
echo "Error inserting data: " . $conn->error;
exit();
}
}
// Create the admissions table
$query =
"CREATE TABLE IF NOT EXISTS admissions (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
mobile VARCHAR(15) NOT NULL,
email VARCHAR(255) NOT NULL,
father_name VARCHAR(255) NOT NULL,
mother_name VARCHAR(255) NOT NULL,
address TEXT NOT NULL,
state_id INT NOT NULL,
city_id INT NOT NULL,
dob DATE NOT NULL,
age INT NOT NULL,
gender ENUM('male', 'female') NOT NULL,
course_id INT NOT NULL,
FOREIGN KEY (state_id) REFERENCES states(id),
FOREIGN KEY (city_id) REFERENCES cities(id),
FOREIGN KEY (course_id) REFERENCES course_info(id)
)";
if ($conn->query($query) === TRUE) {
echo "Admissions table created successfully.";
} else {
echo "Error creating admissions table: " . $conn->error;
}
echo "Data inserted into the Course Info table successfully.";
$conn->close(); |
<div class="main" #main>
<div class="container">
<div class="pt-5 pb-3">
<div class="d-flex justify-content-end">
<form #search="ngForm" (ngSubmit)="searchHandler(search)" class="d-flex justify-content-end">
<input class="form-control me-2" type="search" name="query" placeholder="Search" aria-label="Search"
[(ngModel)]="query" required>
<button class="btn btn-outline-success" type="submit" [disabled]="search.invalid">
Search
</button>
</form>
</div>
</div>
<section class="add">
<div class="card border-0 my-3 bg-dark shadow-lg" *ngFor="let house of houses">
<!-- <div class="image">
<figure>
<picture>
<img src="https://images.unsplash.com/photo-1499424258882-3fc11ba2e15e" alt=""
class="card-img-top">
</picture>
<figcaption>
{{ house.title }}
</figcaption>
</figure>
</div> -->
<!-- <div class="about">
<div class="heading">
<span class="currency">BDT</span>
<span class="price"> {{ house.price |number}}</span>
</div>
<div class="details">
<div class="address">
<a [routerLink]="['/house', house.id]">{{ house.address }}</a>
</div>
<div class="type">{{ house.type }}</div>
<div class="description">
{{ house.description }}
</div>
<div class="feature">
<div class="bed">
<span> {{ house.beds }} </span>
<i class="fas fa-bed"></i>
</div>
<div class="bath">
<span> {{ house.baths }} </span>
<i class="fas fa-bath"></i>
</div>
<div class="area">
<i class="fas fa-th-large"></i>
<span> {{ house.area |number}} sqft</span>
</div>
</div>
</div>
<div class="contact">
<button class="btn call">
<i class="fas fa-phone-alt"></i>
<span> Call </span>
</button>
<button class="btn email">
<i class="fas fa-envelope"></i>
<span> Email </span>
</button>
</div>
</div> -->
<div class="card-body">
<h5 class="card-title text-white">{{ house.title }}</h5>
<h6 class="card-subtitle text-white-50">{{ house.address }}</h6>
<div class="d-flex text-white-50 my-3">
<div class="pe-2">
<span> {{ house.beds }} </span>
<i class="fas fa-bed"></i>
</div>
<div class="px-2">
<span> {{ house.baths }} </span>
<i class="fas fa-bath"></i>
</div>
<div class="ps-2">
<i class="fas fa-th-large"></i>
<span> {{ house.area |number}} sqft</span>
</div>
</div>
<p class="card-text text-muted">{{ house.description }}</p>
<a class="btn btn-primary" [routerLink]="['/house', house.id]">View Details</a>
</div>
</div>
</section>
<ul class="pagination justify-content-end mb-0 pb-3">
<li class="page-item" *ngIf="previous" [ngClass]="{'disabled': !previous}">
<button [disabled]="!previous" (click)="listHouse(previous); main.scrollTop = 0" class="page-link">
Previous
</button>
</li>
<li class="page-item" *ngIf="next" [ngClass]="{'disabled': !next}">
<button [disabled]="!next" (click)="listHouse(next); main.scrollTop = 0" class="page-link">Next</button>
</li>
</ul>
</div>
</div> |
import 'package:equeuebiz/constants/appcolor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:equeuebiz/enum/company_enum.dart';
import 'package:equeuebiz/enum/user_type.dart';
import 'package:equeuebiz/providers/auth_prov.dart';
import 'package:equeuebiz/screens/transaction.dart';
import 'package:equeuebiz/translations/locale_keys.g.dart';
import 'package:equeuebiz/widgets/appbar.dart';
import 'package:equeuebiz/widgets/custom_widgets.dart';
import 'package:flutter/material.dart';
class Profile extends StatefulWidget {
String? acn;
String? acnum;
String? bname;
String? descr;
String? earned;
String? id;
String? ifsc;
String? moneyearned;
String? name;
String? profileurl;
String? type;
var usertype;
Profile(
{this.acn,
this.usertype,
this.acnum,
this.bname,
this.descr,
this.earned,
this.id,
this.ifsc,
this.moneyearned,
this.name,
this.profileurl,
this.type});
@override
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
String? acn;
String? acnum;
String? bname;
String? descr;
String? earned;
String? id;
String? ifsc;
String? moneyearned;
String? name;
String? profileurl;
String? type;
AuthProv? a;
@override
void initState() {
setState(() {
acn = widget.acn;
acnum = widget.acnum;
bname = widget.bname;
descr = widget.descr;
earned = widget.earned;
id = widget.id;
ifsc = widget.ifsc;
name = widget.name;
profileurl = widget.profileurl;
type = widget.type;
});
super.initState();
}
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: Scaffold(
appBar: whiteAppBar(context, LocaleKeys.Profile.tr()) as PreferredSizeWidget?,
body: Container(
alignment: Alignment.topCenter,
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 1200),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(
height: 15,
),
widget.usertype == UserEnum.Company
? _photo('https://www.nobatdeh.com/uploads/$profileurl')
: _photo(
'https://www.nobatdeh.com/uploads/biz-logos/$profileurl'),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
margin: EdgeInsets.all(20),
child: Center(
child: earned == null
? Text('\$ 0.00')
: Text('\$ $earned'),
),
),
Container(
child: ElevatedButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (ctx) => TransactionDets(
id: id,
)));
},
child: Text('Transactions'),
),
)
],
),
IgnorePointer(
child: _textField(LocaleKeys.Name.tr(), name)),
type == 'booking'
? _textField(LocaleKeys.Acc_Name.tr(), acn)
: SizedBox(),
type == 'booking'
? _textField(LocaleKeys.Acc_No.tr(), acnum)
: SizedBox(),
type == 'booking'
? _textField(LocaleKeys.Bank_Name.tr(), bname)
: SizedBox(),
_textField(LocaleKeys.Description.tr(), descr),
type == 'booking'
? _textField(LocaleKeys.Ifsc.tr(), ifsc)
: SizedBox(),
IgnorePointer(
child: _textField(LocaleKeys.Type.tr(), type)),
// addCancel()
],
),
),
)),
),
);
}
Widget _photo(String p) {
return CircleAvatar(
radius: 60,
backgroundImage: NetworkImage(p),
);
}
Widget _textField(String hintText, String? val) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
decoration: BoxDecoration(
color: Colors.grey[300], borderRadius: BorderRadius.circular(4)),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0),
child: TextFormField(
onChanged: (v) {
setState(() {
acn = v;
});
},
initialValue: val,
decoration: InputDecoration(
hintText: hintText,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
disabledBorder: InputBorder.none,
),
),
);
}
Widget addCancel() {
return Container(
margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
height: 50,
child: Row(
children: [
Expanded(child: CustomWidgets().filledButton(LocaleKeys.Save.tr())),
SizedBox(
width: 25,
),
Expanded(child: CustomWidgets().hollowButton(LocaleKeys.CANCEL.tr()))
],
),
);
}
} |
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>HomePage </title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
</head>
<body>
<div th:insert="Blocks/header :: header"></div>
<header class="bg-dark py-5">
<div class="container px-4 px-lg-5 my-5">
<div class="text-center text-white">
<h1 class="display-4 fw-bolder">Your Clothing Store</h1>
<p class="lead fw-normal text-white-50 mb-0">Welcome <3</p>
</div>
</div>
</header>
<section class="py-5">
<div class="container px-4 px-lg-5 mt-5">
<div class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center">
<div th:each="clothing : ${clothing}" class="col mb-5">
<div class="card h-100">
<!-- Product image-->
<img th:src="${clothing.Img}" class="card-img-top" alt="...">
<!-- Product details-->
<div class="card-body p-4">
<div class="text-left">
<!-- Product name-->
<h5 th:text="${clothing.ClothingName}" class="fw-bolder"/>
<!-- Product price-->
<h4 th:text="${clothing.ClothingPrice}+ ' p.'"/>
</div>
</div>
<!-- Product actions-->
<div class="card-footer p-4 pt-0 border-top-0 bg-transparent">
<div class="text">
<!-- <a class="btn btn-outline-dark mt-auto, me-1" th:href="'/product/'+${clothing.ClothingID}">Подробнее</a>-->
<a class="btn btn-outline-success mt-center " th:href="@{'/shoppingCart/addProduct/{ClothingID}'(ClothingID=${clothing.ClothingID})}">
Добавить в корзину
</a>
<!-- <a th:href="${'/shoppingCart/addProduct/' + clothing.getId()}"
class="btn btn-outline-dark mt-auto"
sec:authorize="isAuthenticated()">
В корзину</a>-->
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<footer class="py-5 bg-dark">
<div class="container"><p class="m-0 text-center text-white">Copyright © Your Clothing Store 2022</p></div>
</footer>
</body>
</html> |
import os
import re
import importlib.util
from pathlib import Path
import shutil
from arcgis.gis import GIS, Group
from arcgis.env import active_gis
from dotenv import find_dotenv, load_dotenv
# see if arcpy available to accommodate non-windows environments
if importlib.util.find_spec('arcpy') is not None:
import arcpy
has_arcpy = True
else:
has_arcpy = False
def _not_none_and_len(string: str) -> bool:
"""helper to figure out if not none and string is populated"""
is_str = isinstance(string, str)
has_len = False if re.match(r'\S{5,}', '') is None else True
status = True if has_len and is_str else False
return status
def add_group(gis: GIS = None, group_name: str = None) -> Group:
"""
Add a group to the GIS for the project for saving resources.
Args:
gis: Optional
arcgis.gis.GIS object instance.
group_name: Optional
Group to be added to the cloud GIS for storing project resources. Default
is to load from the .env file. If a group name is not provided, and one is
not located in the .env file, an exception will be raised.
Returns: Group
"""
# load the .env into the namespace
load_dotenv(find_dotenv())
# try to figure out what GIS to use
if gis is None and isinstance(active_gis, GIS):
gis = active_gis
if gis is None and not isinstance(active_gis, GIS):
url = os.getenv('ESRI_GIS_URL')
usr = os.getenv('ESRI_GIS_USERNAME')
pswd = os.getenv('ESRI_GIS_PASSWORD')
# if no group name provided
if group_name is None:
# load the group name
group_name = os.getenv('ESRI_GIS_GROUP')
err_msg = 'A group name must either be defined in the .env file or explicitly provided.'
assert isinstance(group_name, str), err_msg
assert len(group_name), err_msg
# create an instance of the content manager
cmgr = gis.groups
# make sure the group does not already exist
assert len([grp for grp in cmgr.search() if
grp.title.lower() == group_name.lower()]) is 0, f'A group named "{group_name}" already exists. ' \
'Please select another group name.'
# create the group
grp = cmgr.create(group_name)
# ensure the group was successfully created
assert isinstance(grp, Group), 'Failed to create the group in the Cloud GIS.'
return grp
def create_local_data_resources(data_pth: Path = None) -> Path:
"""create all the data resources for the available environment"""
# default to the expected project structure
if data_pth is None:
data_pth = Path(__file__).parent.parent.parent / 'data'
# cover if a string is inadvertently passed in as the path
data_pth = Path(data_pth) if isinstance(data_pth, str) else data_pth
# iterate the data subdirectories
for data_name in ['interim', 'raw', 'processed', 'external']:
# ensure the data subdirectory exists
dir_pth = data_pth / data_name
if not dir_pth.exists():
dir_pth.mkdir(parents=True)
# if working in an arcpy environment
if has_arcpy:
# remove the file geodatabase if it exists and recreate it to make sure compatible with version of Pro
fgdb_pth = dir_pth / f'{data_name}.gdb'
if fgdb_pth.exists():
shutil.rmtree(fgdb_pth)
arcpy.management.CreateFileGDB(str(dir_pth), f'{data_name}.gdb')
# do the same thing for a mobile geodatabase, a sqlite database
gdb_pth = dir_pth / f'{data_name}.geodatabase'
if gdb_pth.exists():
gdb_pth.unlink()
arcpy.management.CreateMobileGDB(str(dir_pth), f'{data_name}.geodatabase')
return data_pth
class Paths:
"""Object to easily reference data resources"""
def __init__(self):
self.dir_prj = Path(__file__).parent.parent.parent
self.dir_data = self.dir_prj / 'data'
self.dir_raw = self.dir_data / 'raw'
self.dir_ext = self.dir_data / 'external'
self.dir_int = self.dir_data / 'interim'
self.dir_out = self.dir_data / 'processed'
self.gdb_raw = self.dir_raw / 'raw.gdb'
self.gdb_ext = self.dir_ext / 'external.gdb'
self.gdb_int = self.dir_int / 'interim.gdb'
self.gdb_out = self.dir_out / 'processed.gdb'
self.dir_models = self.dir_prj / 'models'
self.dir_reports = self.dir_prj / 'reports'
self.dir_fig = self.dir_reports / 'figures'
@staticmethod
def _create_resource(pth: Path) -> Path:
"""Internal function to create resources."""
# see if we're working with a file geodatabase
is_gdb = (pth.suffix == '.gdb' or pth.suffix == '.geodatabase')
# if a geodatabase, the path dir is one level up
pth_dir = pth.parent if is_gdb else pth
# ensure the file directory exists including parents as necessary
if not pth_dir.exists():
pth_dir.mkdir(parents=True)
# now if a geodatabase, create it
if is_gdb:
# flag if-exists so only run function once
gdb_exists = arcpy.Exists(str(pth))
# if a file geodatabase, create it
if pth.suffix == '.gdb' and not gdb_exists:
arcpy.management.CreateFileGDB(pth_dir, pth.stem)
# if a mobile geodatabase, create it
if pth.suffix == '.geodatabase' and not gdb_exists:
arcpy.management.CreateMobileGDB(pth_dir, pth.stem)
return pth
def create_resources(self):
"""Create data storage resources if they do not already exist."""
# get the data resources from the object properties
pth_lst = [p for p in dir(self) if isinstance(p, Path)]
# iterate the paths and create any necessary resources
for pth in pth_lst:
self._create_resource(pth)
return |
<template>
<div class="side-drawer-container"
:class="{ 'side-drawer-container-closed': closed, 'side-drawer-container-open': !closed }"
>
<div class="side-drawer"
:class="{'side-drawer-closed': closed}"
@touchstart="touchStart"
@touchmove="touchMove"
>
<div class="side-drawer-heading" @click="toggleDrawer">
<user-card-content :user="currentUser" :switcher="false" :hideBio="true" v-if="currentUser">
</user-card-content>
</div>
<ul>
<li v-if="currentUser" @click="toggleDrawer">
<router-link :to="{ name: 'new-status', params: { username: currentUser.screen_name } }">
{{ $t("post_status.new_status") }}
</router-link>
</li>
<li v-else @click="toggleDrawer">
<router-link :to="{ name: 'login' }">
{{ $t("login.login") }}
</router-link>
</li>
<li v-if="currentUser" @click="toggleDrawer">
<router-link :to="{ name: 'notifications', params: { username: currentUser.screen_name } }">
{{ $t("notifications.notifications") }} {{ unseenNotificationsCount > 0 ? `(${unseenNotificationsCount})` : '' }}
</router-link>
</li>
<li v-if="currentUser" @click="toggleDrawer">
<router-link :to="{ name: 'dms', params: { username: currentUser.screen_name } }">
{{ $t("nav.dms") }}
</router-link>
</li>
</ul>
<ul>
<li v-if="currentUser" @click="toggleDrawer">
<router-link :to="{ name: 'friends' }">
{{ $t("nav.timeline") }}
</router-link>
</li>
<li v-if="currentUser && currentUser.locked" @click="toggleDrawer">
<router-link to='/friend-requests'>
{{ $t("nav.friend_requests") }}
</router-link>
</li>
<li @click="toggleDrawer">
<router-link to='/main/public'>
{{ $t("nav.public_tl") }}
</router-link>
</li>
<li @click="toggleDrawer">
<router-link to='/main/all'>
{{ $t("nav.twkn") }}
</router-link>
</li>
<li v-if="currentUser && chat" @click="toggleDrawer">
<router-link :to="{ name: 'chat' }">
{{ $t("nav.chat") }}
</router-link>
</li>
</ul>
<ul>
<li @click="toggleDrawer">
<router-link :to="{ name: 'user-search' }">
{{ $t("nav.user_search") }}
</router-link>
</li>
<li v-if="currentUser && suggestionsEnabled" @click="toggleDrawer">
<router-link :to="{ name: 'who-to-follow' }">
{{ $t("nav.who_to_follow") }}
</router-link>
</li>
<li @click="toggleDrawer">
<router-link :to="{ name: 'settings' }">
{{ $t("settings.settings") }}
</router-link>
</li>
<li @click="toggleDrawer">
<router-link :to="{ name: 'about'}">
{{ $t("nav.about") }}
</router-link>
</li>
<li v-if="currentUser" @click="toggleDrawer">
<a @click="doLogout" href="#">
{{ $t("login.logout") }}
</a>
</li>
</ul>
</div>
<div class="side-drawer-click-outside"
@click.stop.prevent="toggleDrawer"
:class="{'side-drawer-click-outside-closed': closed}"
></div>
</div>
</template>
<script src="./side_drawer.js" ></script>
<style lang="scss">
@import '../../_variables.scss';
.side-drawer-container {
position: fixed;
z-index: 1000;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: stretch;
}
.side-drawer-container-open {
transition-delay: 0.0s;
transition-property: left;
}
.side-drawer-container-closed {
left: -100%;
transition-delay: 0.5s;
transition-property: left;
}
.side-drawer-click-outside {
flex: 1 1 100%;
}
.side-drawer {
overflow-x: hidden;
transition: 0.35s;
transition-timing-function: cubic-bezier(0, 1, 0.5, 1);
margin: 0 0 0 -100px;
padding: 0 0 1em 100px;
width: 80%;
max-width: 20em;
flex: 0 0 80%;
box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.6);
box-shadow: var(--panelShadow);
background-color: $fallback--bg;
background-color: var(--bg, $fallback--bg);
}
.side-drawer-click-outside-closed {
flex: 0 0 0;
}
.side-drawer-closed {
transform: translate(-100%);
}
.side-drawer-heading {
background: transparent;
flex-direction: column;
align-items: stretch;
display: flex;
min-height: 7em;
padding: 0;
margin: 0;
.profile-panel-background {
border-radius: 0;
.panel-heading {
background: transparent;
flex-direction: column;
align-items: stretch;
}
}
}
.side-drawer ul {
list-style: none;
margin: 0;
padding: 0;
border-bottom: 1px solid;
border-color: $fallback--border;
border-color: var(--border, $fallback--border);
margin: 0.2em 0;
}
.side-drawer ul:last-child {
border: 0;
}
.side-drawer li {
padding: 0;
a {
display: block;
padding: 0.5em 0.85em;
&:hover {
background-color: $fallback--lightBg;
background-color: var(--lightBg, $fallback--lightBg);
}
}
}
</style> |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Scheduling Page</title>
<link rel="stylesheet" href="../css/globals.css"/>
<link rel="stylesheet" href="../css/styleguide.css"/>
<link rel="stylesheet" href="../css/style.css"/>
<!-- JQuery Import-->
<script class="jsbin" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<div class="WF-utility-app">
<header>
<div class="WF-title-bar">
<div class="scheduling-input">myScheduling</div>
<img class="logo" src="../img/QuickLULogo.png"/>
</div>
</header>
<table class="input-table">
<tr>
<td>
<div>
<table>
<tr>
<td>
<!-- Program Select Form-->
<div class="form">
<div class="div-wrapper">
<div class="WF-input-field">
<div class="label">Program</div>
<select class="form-select text-input" id="program_select">
<option value="1">Example Program 1</option>
<option value="2">Example Program 2</option>
<option value="3">Example Program 3</option>
<option value="3">Example Program 4</option>
<option value="3">Example Program 5</option>
<option value="3">Example Program 6</option>
</select>
</div>
</div>
<div class="div-wrapper">
<div class="drop-down-base">
<div class="label">Year Level</div>
<select class="form-select text-input" id="year_select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="3">Four</option>
<option value="3">Other</option>
</select>
</div>
</div>
</div>
</td>
</tr>
<tr>
<td>
<!-- Schedule Upload Input-->
<div class="file-upload">
<div class="image-upload-wrap">
<input class="file-upload-input" type='file' onchange="readURL(this);"
accept="image/*"/>
<div class="drag-text">
<h3>Drag and drop a schedule or upload</h3>
</div>
</div>
<div class="file-upload-content">
<img class="file-upload-image" src="#" alt="your image"/>
<div class="image-title-wrap">
<button type="button" onclick="removeUpload()" class="remove-image">Remove
<span class="image-title">Uploaded Image</span></button>
</div>
</div>
</div>
<button class="file-upload-btn" type="button"
onclick="$('.file-upload-input').trigger( 'click' )">Upload Schedule
</button>
</td>
</tr>
</table>
</div>
</td>
<td class="selected-course-table-container">
<!-- Selected Class List -->
<div class="label" style="font-size: 24px; padding: 10px 0px 10px;">
<span style="text-align: left">Selected Courses</span>
<span style="float: right" id="selected_course_count">0/7</span>
</div>
<table class="table course-list-table">
<thead>
<tr>
<th scope="col">
Course Code
</th>
<th scope="col">
Name
</th>
<th scope="col">
Type
</th>
</tr>
</thead>
<tbody id="selected_course_tbody">
<!-- Empty Table Placeholder -->
<tr>
<td>
No Courses Selected!
</td>
<td>
N/A
</td>
<td>
Elective
</td>
</tr>
</tbody>
</table>
</td>
<td colspan="1" class="course-result-container">
<div class="course-search-input">
<div class="label">Required Courses</div>
<input type="text" class="text-input" id="core-course-list-input"
oninput="updateCourseList('core-course-list')">
</div>
<div class="core-course-option" id="core-course-list">
<div class="course-result">
<div class="text-wrapper-2">Select a Program.<input type="checkbox" hidden="hidden"></div>
</div>
</div>
</td>
<td colspan="1" class="course-result-container">
<div class="course-search-input">
<div class="label">Elective Courses</div>
<input type="text" class="text-input" id="elective-course-list-input"
oninput="updateCourseList('elective-course-list')">
</div>
<div class="core-course-option" id="elective-course-list">
<!-- <div class="course-result">-->
<!-- <div class="text-wrapper-2">Select a Program</div>-->
<!-- </div>-->
</div>
</td>
</tr>
</table>
</div>
</body>
<!--Fuse JS For Fuzzy Searching-->
<script src="https://cdn.jsdelivr.net/npm/fuse.js/dist/fuse.js"></script>
<script>
//IMPORTED FOR FILE UPLOAD -- NOT MINE
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.image-upload-wrap').hide();
$('.file-upload-image').attr('src', e.target.result);
$('.file-upload-content').show();
$('.image-title').html(input.files[0].name);
};
reader.readAsDataURL(input.files[0]);
} else {
removeUpload();
}
}
function removeUpload() {
$('.file-upload-input').replaceWith($('.file-upload-input').clone());
$('.file-upload-content').hide();
$('.image-upload-wrap').show();
}
$('.image-upload-wrap').bind('dragover', function () {
$('.image-upload-wrap').addClass('image-dropping');
});
$('.image-upload-wrap').bind('dragleave', function () {
$('.image-upload-wrap').removeClass('image-dropping');
});
//Fuse.js Fuzzy search options.
let options = {
// isCaseSensitive: false,
includeScore: true, //debug purposes
shouldSort: false,
threshold: 0.2, // tweak to be less tolerant
keys: [
"CourseCode",
"Title",
"SubjectCode"
]
};
let masterCourseList;
//Will be populated with all possible core courses for selected program/year
let programCourseList = []
//Will be populated with all possible electives for the selected program
let electiveList = [];
let selectedCourses = [];
init();
function init() {
loadJSON(function (response) {
// Parse JSON string into object
masterCourseList = JSON.parse(response).Courses;
//temp debug code to populate both lists too test searching functionality
programCourseList = masterCourseList;
electiveList = masterCourseList;
console.log(masterCourseList);
});
}
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'lu_courses.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
function fuzzyCourseSearch(courseArray, keyword) {
//if keyword is empty return null
if (keyword.trim() == '')
return null;
let result_array = [];
let fuse = new Fuse(courseArray, options);
fuse.search(keyword).forEach(x => result_array.push(x.item));
return result_array;
}
function updateCourseList(id) {
//get search term and filtered course list based on what search bar called the method
let keyword = document.getElementById(id + '-input').value;
let resultArray = id == "core-course-list" ? fuzzyCourseSearch(programCourseList, keyword) : fuzzyCourseSearch(electiveList, keyword);
let parentElement = document.getElementById(id);
parentElement.innerHTML = "";
if (resultArray == null)
return;
for (result of resultArray)
parentElement.appendChild(createCourseResultElement(result));
}
//given a course object return a course div element with id = to course Id
function createCourseResultElement(course) {
let courseDiv = document.createElement("div");
courseDiv.id = course.Id;
courseDiv.onclick = function () {
selectCourse(course)
};
courseDiv.classList.add("course-result")
courseDiv.innerHTML = '<input type="checkbox" id="course_select_' + course.Id + '" hidden="hidden"><div class="text-wrapper-2">' + course.CourseCode + ': ' + course.Title + '</div>';
return courseDiv;
}
//callback for course result onClick
function selectCourse(course) {
console.log(course);
var index = selectedCourses.indexOf(course);
if (index != -1) {
selectedCourses.splice(index, 1);
} else
selectedCourses.push(course);
if (selectedCourses.length > 7) {
alert("Maximum Number Of Courses Reached. (7/7)");
//remove the course we added
selectedCourses.pop();
return;
}
updateSelectedCourseTable();
}
function updateSelectedCourseTable() {
var table = document.getElementById("selected_course_tbody");
//clear table.
table.innerHTML = "";
document.getElementById("selected_course_count").textContent = selectedCourses.length + "/7";
for (course of selectedCourses) {
table.innerHTML += "<tr><td>" + course.CourseCode + '</td><td>' + course.Title + '</td><td>' + 'TODO' + '</td></tr>';
}
}
</script>
</html> |
'''Importação para poder limpar a tela'''
import os
restaurantes = [{'nome': 'Praça', 'categoria': 'Japonesa', 'ativo': False},
{'nome': 'Pizza Suprema', 'categoria': 'Pizza', 'ativo': True},
{'nome': 'Cantina', 'categoria': 'Italizano', 'ativo': False}]
def exibir_nome_do_programa():
'''
Apresenta o nome estilizado do programa na tela inicial
'''
print('''
░██████╗░█████╗░██████╗░░█████╗░██████╗░ ███████╗██╗░░██╗██████╗░██████╗░███████╗░██████╗░██████╗
██╔════╝██╔══██╗██╔══██╗██╔══██╗██╔══██╗ ██╔════╝╚██╗██╔╝██╔══██╗██╔══██╗██╔════╝██╔════╝██╔════╝
╚█████╗░███████║██████╦╝██║░░██║██████╔╝ █████╗░░░╚███╔╝░██████╔╝██████╔╝█████╗░░╚█████╗░╚█████╗░
░╚═══██╗██╔══██║██╔══██╗██║░░██║██╔══██╗ ██╔══╝░░░██╔██╗░██╔═══╝░██╔══██╗██╔══╝░░░╚═══██╗░╚═══██╗
██████╔╝██║░░██║██████╦╝╚█████╔╝██║░░██║ ███████╗██╔╝╚██╗██║░░░░░██║░░██║███████╗██████╔╝██████╔╝
╚═════╝░╚═╝░░╚═╝╚═════╝░░╚════╝░╚═╝░░╚═╝ ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░╚═╝╚══════╝╚═════╝░╚═════╝░
''') # Fsymbols.com
def exibir_opcoes():
'''
Mostrar todas as opções que poderá ser selecionado no menu inicial
'''
print('1. Cadastrar Restaurante')
print('2. Listar Restaurante')
print('3. Alterar Estado do Restaurante')
print('4. Sair')
def finalizar_app():
'''
Mostra a mensagem de finalização do programa
'''
exibir_subtitulo('Finalizando o app')
def voltar_ao_menu_principal():
'''
Solicita uma tecla para retornar ao menu inicial e redireciona para o mesmo
Output:
Retorna ao menu principal
'''
input('\nDigite uma tecla para voltar ao menu principal')
main()
def opcao_invalida(mensagem):
'''
Mostra na tela uma mensagem de erro de acordo com a chamada dessa função
Output:
Retorna ao menu principal
'''
print(mensagem)
voltar_ao_menu_principal()
def exibir_subtitulo(subtitulo):
'''Essa Função tem a resposabilidade de mostrar os subtítulos do programa.
Params:
subtitulo (str): texto que deverá ser mostrado na tela
'''
os.system('cls') # No Windows
linha = '*' * (len(subtitulo) + 4)
print(f'\033[1;034m{linha}\033[0;037m')
print(f' \033[1;032m{subtitulo}\033[0;037m ')
print(f'\033[1;034m{linha}\033[0;037m')
print()
def cadastrar_novo_resteurante():
'''
Cadastra um novo restaurante na lista de restaurantes.
Inputs:
nome_do_restaurante (str): O nome do restaurantte que será adicionado.
categoria (str): A categoria do restaurante que será adicionado.
Output:
Adiciona o novo restaurante na lista de restaurantes.
'''
try:
exibir_subtitulo('Cadastro de novos resteurantes')
nome_do_restaurante = input('Digite o nome do restaurante que deseja cadastrar: ')
# Alt-z para visualizar tudo
if not nome_do_restaurante:
raise ValueError('Nome do restaurante não foi inserido')
categoria = input(f'Digite a categoria do restaurante {nome_do_restaurante}: ')
if not categoria:
raise ValueError('Categoria não foi inserida')
dados_do_restaurante = {'nome': nome_do_restaurante, 'categoria': categoria, 'ativo': False}
restaurantes.append(dados_do_restaurante)
print(f'O restaurante {nome_do_restaurante} foi adicionado com sucesso!')
voltar_ao_menu_principal()
except Exception as ve:
opcao_invalida(ve)
def listar_restaurantes():
'''
Mosta na tela todos os restaurantes cadastrados.
Output:
Exibe a lista de restaurantes na tela
'''
exibir_subtitulo('Listando restaurantes')
print(f'{'Nome do restaurante'.ljust(22)} | {'Categoria'.ljust(20)} | Status ')
for restaurante in restaurantes:
nome = restaurante['nome']
categoria = restaurante['categoria']
ativo = 'ativado' if restaurante['ativo'] else 'desativado'
print(f'- {nome.ljust(20)} | {categoria.ljust(20)} | {ativo}')
voltar_ao_menu_principal()
def alternar_estado_restaurante():
'''
Altera o estado de um restaurante cadastrado.
Inputs:
nome_retaurante (str): nome do restaurante que terá seu estado alterado
Output:
Alteração do estado do restaurante selecionado'''
exibir_subtitulo('Alterando estado do restaurante')
nome_restaurante = input('Digite o nome do restaurante que deseja alterar o estado: ')
restaurante_encontrado = False
for restaurante in restaurantes:
if nome_restaurante == restaurante['nome']:
restaurante_encontrado = True
restaurante['ativo'] = not restaurante['ativo']
status = 'ativado' if restaurante['ativo'] else 'dessativado'
mensagem = f'O restaurante {nome_restaurante} foi {status} com sucesso'
print(mensagem)
if not restaurante_encontrado:
print(f'O restaurante {nome_restaurante} não foi encontrado')
voltar_ao_menu_principal()
def escolher_opcao():
'''
Requere que uma opção seja escolhida entre as opções da tela.
Inputs:
opcao_escolhida (int): Opção que será selecionada.
Output:
Executa a operação escolhida.
'''
try:
opcao_escolhida = int(input('Escolha uma opção: '))
match opcao_escolhida:
case 1: cadastrar_novo_resteurante()
case 2: listar_restaurantes()
case 3: alternar_estado_restaurante()
case 4: finalizar_app()
case _:opcao_invalida("Opcao inválida!\n")
except Exception:
opcao_invalida("Opcao inválida! \n")
def main():
'''
Inicia o fluxo do programa principal
'''
os.system('cls')
exibir_nome_do_programa()
exibir_opcoes()
escolher_opcao()
if __name__ == '__main__':
main() |
import Doctor from "../models/Doctor.js";
import Patient from "../models/Patient.js"
import { createError } from "../utils/error.js";
import bcrypt from "bcryptjs"
import jwt from "jsonwebtoken";
export const patientRegister = async (req, res, next) => {
try {
console.log("1");
const salt = bcrypt.genSaltSync(10)
const hash = bcrypt.hashSync(req.body.password, salt)
console.log("2");
const newPatient = new Patient({
...req.body,
password: hash,
})
console.log("3");
await newPatient.save()
console.log("4");
res.status(201).json(newPatient);
} catch (err) {
next(err)
}
}
export const patientLogin = async (req, res, next) => {
try {
const patient = await Patient.findOne({ username: req.body.username });
if (!patient) return next(createError(404, "Patient not found!"));
const isPasswordCorrect = await bcrypt.compare(
req.body.password,
patient.password
);
if (!isPasswordCorrect) return next(createError(400, "Wrong password or username!"));
const token = jwt.sign({ id: patient._id, username: patient.username }, process.env.JWT)
res.cookie("access_token", token, {
httpOnly: true
}).status(200).json(patient)
} catch (err) {
next(err)
}
}
export const doctorRegister = async (req, res, next) => {
console.log(req.body)
try {
const salt = bcrypt.genSaltSync(10)
const hash = bcrypt.hashSync(req.body.password, salt)
console.log("in try block");
const newDoctor = new Doctor({
...req.body,
password: hash,
})
console.log(newDoctor);
await newDoctor.save()
res.status(201).json({message:newDoctor});
} catch (err) {
next(err)
}
}
export const doctorLogin = async (req, res, next) => {
try {
const doctor = await Doctor.findOne({ username: req.body.username });
if (!doctor) return next(createError(404, "Patient not found!"));
const isPasswordCorrect = await bcrypt.compare(
req.body.password,
doctor.password
);
if (!isPasswordCorrect) return next(createError(400, "Wrong password or username!"));
const token = jwt.sign({ id: doctor._id, username: doctor.username }, process.env.JWT)
res.cookie("access_token", token, {
httpOnly: true
}).status(200).json(doctor._doc)
} catch (err) {
next(err)
}
} |
// ignore_for_file: use_build_context_synchronously
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:room_rental/blocs/cubits/user_data/user_data_cubit.dart';
import 'package:room_rental/service/storage/storage_service.dart';
import 'package:room_rental/utils/constants/assets_path.dart';
import 'package:room_rental/utils/constants/branding_colors.dart';
import 'package:room_rental/utils/constants/routes.dart';
import 'package:room_rental/utils/constants/styles.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class SettingsPage extends StatefulWidget {
const SettingsPage({super.key});
@override
State<SettingsPage> createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
String? fullName;
String? email;
String? profilePic;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
AppLocalizations.of(context)!.settings,
style: ConstantStyles.bodyTitleStyle(context),
),
leading: const Icon(
Icons.settings,
color: BrandingColors.primaryColor,
),
),
body: ListView(
padding: const EdgeInsets.only(top: 0, bottom: 10, left: 10, right: 10),
children: [
// UserData
userData(),
const SizedBox(height: 20),
// Lists
ListTile(
tileColor: BrandingColors.cardBackgroundColor,
title: Text(
AppLocalizations.of(context)!.personalDetails,
),
leading: const Icon(
Icons.person,
color: BrandingColors.primaryColor,
),
trailing: const Icon(
Icons.arrow_forward_ios_sharp,
color: Colors.black,
size: 15,
weight: 20,
grade: 20,
fill: 1,
),
onTap: () =>
Navigator.pushNamed(context, Routes.personalDetailsPage),
),
ListTile(
tileColor: BrandingColors.cardBackgroundColor,
title: Text(
AppLocalizations.of(context)!.contractDetails,
),
leading: const Icon(
Icons.home_work_rounded,
color: BrandingColors.primaryColor,
),
trailing: const Icon(
Icons.arrow_forward_ios_sharp,
color: Colors.black,
size: 15,
weight: 20,
grade: 20,
fill: 1,
),
onTap: () =>
Navigator.pushNamed(context, Routes.contractDetailsPage),
),
ListTile(
tileColor: BrandingColors.cardBackgroundColor,
title: Text(
AppLocalizations.of(context)!.notifications,
),
leading: const Icon(
Icons.notifications,
color: BrandingColors.primaryColor,
),
trailing: const Icon(
Icons.arrow_forward_ios_sharp,
color: Colors.black,
size: 15,
weight: 20,
grade: 20,
fill: 1,
),
onTap: () => Navigator.pushNamed(context, Routes.notificationsPage),
),
ListTile(
tileColor: BrandingColors.cardBackgroundColor,
title: Text(
AppLocalizations.of(context)!.languages,
),
leading: const Icon(
Icons.language,
color: BrandingColors.primaryColor,
),
trailing: const Icon(
Icons.arrow_forward_ios_sharp,
color: Colors.black,
size: 15,
weight: 20,
grade: 20,
fill: 1,
),
onTap: () => Navigator.pushNamed(context, Routes.languagesPage),
),
ListTile(
tileColor: BrandingColors.cardBackgroundColor,
title: Text(
AppLocalizations.of(context)!.privacyandSecurity,
),
leading: const Icon(
Icons.security_outlined,
color: BrandingColors.primaryColor,
),
trailing: const Icon(
Icons.arrow_forward_ios_sharp,
color: Colors.black,
size: 15,
weight: 20,
grade: 20,
fill: 1,
),
// trailing:
),
ListTile(
tileColor: BrandingColors.cardBackgroundColor,
title: Text(
AppLocalizations.of(context)!.helpandSupport,
),
leading: const Icon(
Icons.help_outlined,
color: BrandingColors.primaryColor,
),
trailing: const Icon(
Icons.arrow_forward_ios_sharp,
color: Colors.black,
size: 15,
weight: 20,
grade: 20,
fill: 1,
),
),
ListTile(
tileColor: BrandingColors.cardBackgroundColor,
title: const Text(
"Logout",
),
leading: const Icon(
Icons.logout_outlined,
color: BrandingColors.primaryColor,
),
trailing: const Icon(
Icons.arrow_forward_ios_sharp,
color: Colors.black,
size: 15,
weight: 20,
grade: 20,
fill: 1,
),
onTap: () async {
await Storage.logout();
Navigator.pushNamedAndRemoveUntil(
context,
Routes.signIn,
(route) => false,
);
},
),
],
),
);
}
Widget userData() {
return BlocProvider(
create: (context) => UserDataCubit()..getUserData(),
child: BlocBuilder<UserDataCubit, UserDataState>(
builder: (context, state) {
if (state is UserData) {
return Column(
children: [
Center(
child: CircleAvatar(
radius: MediaQuery.of(context).size.height * 0.06,
backgroundImage: (state.profilePic != null &&
state.profilePic!.isNotEmpty)
? NetworkImage(
state.profilePic!,
)
: const AssetImage(
AssetsPath.lanlord,
) as ImageProvider<Object>?,
),
),
Center(
child: Text(
state.fullName!,
style: Theme.of(context).textTheme.bodyLarge!.copyWith(
color: Colors.black,
fontWeight: FontWeight.w600,
),
),
),
Center(
child: Text(state.email!),
),
],
);
} else {
return const Center(child: CircularProgressIndicator());
}
},
),
);
}
} |
import { useEffect, useState } from "react";
import { useLocation, useParams } from "react-router-dom";
import { getStationDetails } from "../services/station-service.tsx";
interface DetailStation {
id: number;
station_name: string;
station_address: string;
journeys_started: number;
journeys_ended: number;
journeys_started_avg_distance: number;
journeys_started_avg_duration: number;
}
const StationDetailsPage = () => {
const [station, setStation] = useState<DetailStation | null>(null);
const { id } = useParams<Record<string, string | undefined>>();
const location = useLocation();
useEffect(() => {
if (location.state && location.state.station) {
setStation(location.state.station);
} else {
getStationDetails(id).then((station) => {
setStation(station);
});
}
}, [id, location]);
if (!station) {
return false;
}
return (
<div
aria-label="station-details"
className="station-details"
>
<p className="mb-1 font-semibold text-4xl">{station.station_name}</p>
<p className="mb-8 text-3xl">{station.station_address}</p>
<p className="mb-1 text-2xl font-semibold decoration-slate-600">
Journeys
</p>
<p className="text-xl">Started from station {station.journeys_started}</p>
<p className="mb-4 text-xl">Ended to station {station.journeys_ended}</p>
<p className="mb-1 text-2xl font-semibold decoration-slate-600">
Started journeys
</p>
<p className="text-xl">
Average distance {station.journeys_started_avg_distance} meters
</p>
<p className="text-xl">
Average duration{" "}
{Math.floor(station.journeys_started_avg_duration / 60)} minutes{" "}
{station.journeys_started_avg_duration % 60} seconds
</p>
</div>
);
};
export default StationDetailsPage; |
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { clearAllSeats } from "../../store/order";
import List from "../../models/List";
import TrainDesc from "./TrainDesc"
import SeatType from "./SeatType";
import VagonOverview from "./VagonOverview";
import { arrayOf, bool, object } from "prop-types";
export default function SeatPanel({ back, seats, route }) {
const navigate = useNavigate();
const dispatch = useDispatch();
const seatsByCategory = {
to: useSelector(state => state.root.order.seats),
back: useSelector(state => state.root.order.seatsBack),
};
let seatsByDirection;
if (back) seatsByDirection = seatsByCategory.back;
else seatsByDirection = seatsByCategory.to;
const [open, setOpen] = useState(false);
const [category, setCategory] = useState('');
const vagonTypes = [{
name: 'Сидячий',
className: 'fourth',
status: route.have_fourth_class,
}, {
name: 'Плацкарт',
className: 'third',
status: route.have_third_class,
}, {
name: 'Купе',
className: 'second',
status: route.have_second_class,
}, {
name: 'Люкс',
className: 'first',
status: route.have_first_class,
}];
const showSeats = (value) => {
if (open) {
setOpen(false);
setCategory('');
return;
}
setOpen(true);
setCategory(value);
}
const moveBack = (e) => {
e.preventDefault();
dispatch(clearAllSeats());
navigate(-1);
}
return (
<div className="panel__wrapper seat" id={back ? "back" : "to"}>
<div className={`seats__panel`}>
<div className="seats__panel__header flex">
<button className="sign bold">{back ? <>🠘</> : <>🠚</>}</button>
<button
className="button__transp compact narrow__black"
onClick={moveBack}>
Выбрать другой поезд
</button>
</div>
<TrainDesc route={route}/>
<div className="seat__types age">
<h3>Количество билетов</h3>
<List className="type__list flex">
{seatsByDirection.map((item) => <SeatType
key={item.name}
item={item}
showSeats={showSeats}
className={item.codename}
category={category}/>)}
</List>
</div>
</div>
{open && <VagonOverview vagonTypes={vagonTypes} seats={seats} back={back} category={category}/>}
</div>
)
}
SeatPanel.propTypes = {
back: bool,
seats: arrayOf(object),
route: object,
} |
const propertyRouter = require("express").Router();
const Property = require("../models/property");
const User = require("../models/user");
const jwt = require("jsonwebtoken");
const multer = require("multer");
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./attachments");
},
filename: (req, file, cb) => {
cb(null, file.originalname);
},
});
// Create multer upload middleware
const upload = multer({ storage });
propertyRouter.get("/", async (request, response) => {
const properties = await Property.find({ isSold: false }).populate("owner", {
username: 1,
fullname: 1,
});
response.json(properties);
});
propertyRouter.get("/:id", async (request, response) => {
const property = await Property.findById(request.params.id).populate(
"owner",
{ username: 1, fullname: 1 },
);
if (property) {
response.json(property);
} else {
response.status(404).end();
}
});
propertyRouter.get("/owner/:id", async (request, response) => {
console.log(request.params.id);
const properties = await Property.find({ owner: request.params.id }).populate(
"owner",
{ username: 1, fullname: 1 },
);
console.log(properties);
if (properties) {
response.json(properties);
} else {
response.status(404).end();
}
});
propertyRouter.get("/buyer/:id", async (request, response) => {
const properties = await Property.find({ buyer: request.params.id }).populate(
"owner",
{ username: 1, fullname: 1 },
);
if (properties) {
response.json(properties);
} else {
response.status(404).end();
}
});
propertyRouter.get("/search/:query", async (request, response) => {
const properties = await Property.find({
title: { $regex: request.params.query, $options: "i" },
}).populate("owner", { username: 1, fullname: 1 });
if (properties) {
response.json(properties);
} else {
response.status(404).end();
}
});
propertyRouter.get("/search/:query/:location", async (request, response) => {
console.log(request.params.query, request.params.location);
const { query, location } = request.params;
let queryCondition = {
title: { $regex: query, $options: "i" }
};
if (location) {
queryCondition.location = { $regex: location, $options: "i" };
}
const properties = await Property.find(queryCondition).populate("owner", {
username: 1,
fullname: 1
});
if (properties) {
response.json(properties);
} else {
response.status(404).end();
}
});
//list a new property
propertyRouter.post(
"/",
upload.array("attachments"),
async (request, response) => {
try {
const { title, description, price, location, history, tax } =
request.body;
const decodedToken = jwt.verify(request.token, process.env.SECRET);
if (!request.token || !decodedToken.id) {
return response.status(401).json({ error: "token missing or invalid" });
}
const user = await User.findById(decodedToken.id);
if (!user) {
return response.status(401).json({ error: "user not found" });
} else if (user.role !== "seller") {
return response.status(401).json({ error: "user not authorized" });
}
const attachments = request.files.map((file) =>
file.path.replace(/\\/g, "/"),
);
const property = new Property({
title,
description,
price,
photos: attachments,
location,
history,
tax,
owner: user._id,
buyer: null,
isSold: false,
});
console.log(property);
const savedProperty = await property.save();
user.propertiesOwned = user.propertiesOwned.concat(savedProperty._id);
console.log(user);
await user.save();
response.json(savedProperty);
} catch (error) {
console.log(error);
response.status(404).end();
}
},
);
//delete a property
propertyRouter.delete("/:id", async (request, response) => {
try {
const property = await Property.findById(request.params.id);
const decodedToken = jwt.verify(request.token, process.env.SECRET);
if (!request.token || !decodedToken.id) {
return response.status(401).json({ error: "token missing or invalid" });
}
const user = await User.findById(decodedToken.id);
console.log(user);
if (!user) {
return response.status(401).json({ error: "user not found" });
} else if (property && property.owner.toString() === user._id.toString() || user.role === "admin") {
const property=await Property.findByIdAndRemove(request.params.id);
response.send(property).status(204).end();
} else {
response.status(404).end();
}
} catch (error) {
response.status(404).end();
}
});
propertyRouter.put("/:id", async (request, response) => {
try {
const { title, description, price, photos, location, history, tax } =
request.body;
const decodedToken = jwt.verify(request.token, process.env.SECRET);
if (!request.token || !decodedToken.id) {
return response.status(401).json({ error: "token missing or invalid" });
}
const user = await User.findById(decodedToken.id);
if (!user) {
return response.status(401).json({ error: "user not found" });
} else if (user.role !== "seller" && user.role !== "admin") {
return response.status(401).json({ error: "user not authorized" });
}
const updateFields = {};
if (title) updateFields.title = title;
if (description) updateFields.description = description;
if (price) updateFields.price = price;
if (photos) updateFields.photos = photos;
if (location) updateFields.location = location;
if (history) updateFields.history = history;
if (tax) updateFields.tax = tax;
updateFields.buyer = null;
updateFields.isSold = false;
const property = await Property.findByIdAndUpdate(
request.params.id,
updateFields,
{ new: true }
);
response.json(property);
} catch (error) {
response.status(404).end();
}
});
propertyRouter.put("/buy/:id", async (request, response) => {
try {
const decodedToken = jwt.verify(request.token, process.env.SECRET);
if (!request.token || !decodedToken.id) {
return response.status(401).json({ error: "token missing or invalid" });
}
const user = await User.findById(decodedToken.id);
console.log(user);
if (!user) {
return response.status(401).json({ error: "user not found" });
} else if (user.role !== "customer") {
return response.status(401).json({ error: "user not authorized" });
}
const property = await Property.findByIdAndUpdate(
request.params.id,
{
buyer: user._id,
isSold: true,
},
{ new: true },
);
await property.save();
console.log(property);
response.json(property);
} catch (error) {
response.status(404).end();
}
});
propertyRouter.put("/cancel/:id", async (request, response) => {
try {
const decodedToken = jwt.verify(request.token, process.env.SECRET);
if (!request.token || !decodedToken.id) {
return response.status(401).json({ error: "token missing or invalid" });
}
const user = await User.findById(decodedToken.id);
if (!user) {
return response.status(401).json({ error: "user not found" });
} else if (user.role !== "buyer") {
return response.status(401).json({ error: "user not authorized" });
}
const property = await Property.findByIdAndUpdate(
request.params.id,
{
buyer: null,
isSold: false,
},
{ new: true },
);
response.json(property);
} catch (error) {
response.status(404).end();
}
});
// approve a property
propertyRouter.put("/:id/approve", async (request, response) => {
try {
console.log(request.token)
console.log(request.params.id)
const decodedToken = jwt.verify(request.token, process.env.SECRET);
if (!request.token || !decodedToken.id) {
return response.status(401).json({ error: "token missing or invalid" });
}
const user = await User.findById(decodedToken.id);
if (!user) {
return response.status(401).json({ error: "user not found" });
} else if (user.role !== "admin") {
return response.status(401).json({ error: "user not authorized" });
}
const propertyId = request.params.id;
const property = await Property.findById(propertyId);
if (!property) {
return response.status(404).json({ error: "Property not found." });
}
property.isApproved = true;
property.verificationComments = "Property approved by admin";
const savedProperty = await property.save();
response.json(savedProperty);
} catch (error) {
response.status(500).json({ error: "Failed to approve property." });
}
});
// verify a property
propertyRouter.put("/:id/verify", async (request, response) => {
try {
const verificationComments = request.body.verificationComments;
const decodedToken = jwt.verify(request.token, process.env.SECRET);
if (!request.token || !decodedToken.id) {
return response.status(401).json({ error: "token missing or invalid" });
}
const user = await User.findById(decodedToken.id);
if (!user) {
return response.status(401).json({ error: "user not found" });
} else if (user.role !== "admin") {
return response.status(401).json({ error: "user not authorized" });
}
const propertyId = request.params.id;
const property = await Property.findById(propertyId);
if (!property) {
return response.status(404).json({ error: "Property not found." });
}
property.isVerified = true;
property.verificationComments = verificationComments;
const savedProperty = await property.save();
response.json(savedProperty);
} catch (error) {
response.status(500).json({ error: "Failed to verify property." });
}
});
propertyRouter.get("/approved", async (request, response) => {
try {
const approvedProperties = await Property.find({ isApproved: true });
response.json(approvedProperties);
} catch (error) {
response
.status(500)
.json({ error: "Failed to retrieve approved properties." });
}
});
propertyRouter.get("/verified", async (request, response) => {
try {
const verifiedProperties = await Property.find({ isVerified: true });
response.json(verifiedProperties);
} catch (error) {
response
.status(500)
.json({ error: "Failed to retrieve verified properties." });
}
});
module.exports = propertyRouter; |
package myapi.a02systemdemo;
public class SystemDemo1 {
public static void main(String[] args) {
/*
public static void exit(int status) 终止当前运行的 Java 虚拟机
public static long currentTimeMillis() 返回当前系统的时间毫秒值形式
public static void arraycopy(数据源数组,起始索引,目的地数组,起始索引,拷贝个数) 数组拷贝
*/
//方法的形参:
//状态码:
//0: 表示当前虚拟机是正常停止
//非0: 表示当前虚拟机异常停止
//System.exit(e);
//System.out.printIn("看看我执行了吗?“);
//以拼图小游戏为例:
//当我们需要把整个程序就结束的时候,就可以调用这个方法。
//long l = System.currentTimeMillis();
//System.out.println(l);//1698316631884 1698316647758
//拷贝数组
int[] arr1 = {1,2,3,4,5,6,7,8,9,10};
int[] arr2 = new int[10];
//把arr1数组中的数据拷贝到arr2中
//参数一:数据源,要拷贝的数据从哪个数组而来
//参数二:从数据源数组中的第几个索引开始拷贝
//参数三:目的地,我要把数据拷贝到哪个数组中
//参数四:目的地数组的索引
//参数五:拷贝的个数
//System.arraycopy(arr1,0,arr2,0,10);
//练习1:
//arr2: 0 0 0 0 1 2 3 0 0 0
//System.arraycopy(arr1,0,arr2,4,3);
//练习2:
//arr2: 0 0 7 8 9 10 0 0 0 0
System.arraycopy(arr1,6,arr2,2,4);
//遍历数组验证
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i] + " ");
}
}
} |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strmapi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lnicoter <lnicoter@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/01/25 03:12:57 by lnicoter #+# #+# */
/* Updated: 2023/01/25 03:25:30 by lnicoter ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strmapi(char const *s, char (*f)(unsigned int, char))
{
int i;
char *str;
i = 0;
str = (char *)s;
if (!s || !f)
return (NULL);
str = (char *) malloc ((ft_strlen(s) + 1) * sizeof(char));
if (!str)
return (NULL);
while (s[i] != '\0')
{
str[i] = f(i, s[i]);
i++;
}
str[i] = '\0';
return (str);
} |
package services
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/louislaugier/twitter-id-username/internal/scraper"
)
func getFollowers(s *scraper.Scraper, userID string, cursor string) ([]string, string, error) {
url := fmt.Sprintf("https://api.twitter.com/1.1/followers/ids.json?user_id=%s&cursor=%s&count=5", userID, cursor)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, "", err
}
resp, err := s.RequestAPI(req, nil)
if err != nil {
if strings.Contains(err.Error(), "Too Many Requests") {
time.Sleep(time.Minute * 5)
return getFollowers(s, userID, cursor)
}
return nil, "", err
}
var result map[string]interface{}
if err := json.Unmarshal(resp, &result); err != nil {
return nil, "", err
}
var followers []string
if ids, ok := result["ids"].([]interface{}); ok {
for _, id := range ids {
if idFloat, ok := id.(float64); ok {
idStr := strconv.FormatFloat(idFloat, 'f', 0, 64)
followers = append(followers, idStr)
}
}
}
nextCursor := ""
if nextCursorStr, ok := result["next_cursor_str"].(string); ok {
nextCursor = nextCursorStr
}
return followers, nextCursor, nil
}
func getFollowing(s *scraper.Scraper, userID string, cursor string) ([]string, string, error) {
url := fmt.Sprintf("https://api.twitter.com/1.1/friends/ids.json?user_id=%s&cursor=%s&count=5", userID, cursor)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, "", err
}
resp, err := s.RequestAPI(req, nil)
if err != nil {
if strings.Contains(err.Error(), "Too Many Requests") {
time.Sleep(time.Minute * 5)
return getFollowing(s, userID, cursor)
}
return nil, "", err
}
var result map[string]interface{}
if err := json.Unmarshal(resp, &result); err != nil {
return nil, "", err
}
var following []string
if ids, ok := result["ids"].([]interface{}); ok {
for _, id := range ids {
if idFloat, ok := id.(float64); ok {
idStr := strconv.FormatFloat(idFloat, 'f', 0, 64)
following = append(following, idStr)
}
}
}
nextCursor := ""
if nextCursorStr, ok := result["next_cursor_str"].(string); ok {
nextCursor = nextCursorStr
}
return following, nextCursor, nil
}
func isFollowingOrPending(s *scraper.Scraper, userID string) (bool, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("https://api.twitter.com/1.1/friendships/show.json?target_id=%s", userID), nil)
if err != nil {
return false, err
}
resp, err := s.RequestAPI(req, nil)
if err != nil {
if strings.Contains(err.Error(), "Too Many Requests") {
time.Sleep(time.Minute * 5)
return isFollowingOrPending(s, userID)
}
return false, err
}
var result map[string]interface{}
if err := json.Unmarshal(resp, &result); err != nil {
return false, err
}
if relationship, ok := result["relationship"].(map[string]interface{}); ok {
if source, ok := relationship["source"].(map[string]interface{}); ok {
if following, _ := source["following"].(bool); following {
return true, nil
}
if followRequestSent, _ := source["following_requested"].(bool); followRequestSent {
return true, nil
}
}
}
return false, nil
}
func isFollower(s *scraper.Scraper, sourceID, targetID string) (bool, error) {
url := fmt.Sprintf("https://api.twitter.com/1.1/friendships/show.json?source_id=%s&target_id=%s", sourceID, targetID)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return false, err
}
resp, err := s.RequestAPI(req, nil)
if err != nil {
if strings.Contains(err.Error(), "Too Many Requests") {
time.Sleep(time.Minute * 5)
return isFollower(s, sourceID, targetID)
}
return false, err
}
var result map[string]interface{}
if err := json.Unmarshal(resp, &result); err != nil {
return false, err
}
relationship, ok := result["relationship"].(map[string]interface{})
if !ok {
return false, fmt.Errorf("Unable to get relationship information")
}
following, ok := relationship["target"].(map[string]interface{})["followed_by"].(bool)
if !ok {
return false, fmt.Errorf("Unable to determine follow status")
}
return following, nil
}
func GetUserID(s *scraper.Scraper, username string) (string, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("https://api.twitter.com/1.1/users/show.json?screen_name=%s", username), nil)
if err != nil {
return "", err
}
resp, err := s.RequestAPI(req, nil)
if err != nil {
return "", err
}
var result map[string]interface{}
if err := json.Unmarshal(resp, &result); err != nil {
return "", err
}
if id, ok := result["id_str"].(string); ok {
return id, nil
}
return "", fmt.Errorf("Failed to parse response")
}
func GetUsername(s *scraper.Scraper, userID string) (string, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("https://api.twitter.com/1.1/users/show.json?user_id=%s", userID), nil)
if err != nil {
return "", err
}
resp, err := s.RequestAPI(req, nil)
if err != nil {
return "", err
}
var result map[string]interface{}
if err := json.Unmarshal(resp, &result); err != nil {
return "", err
}
if username, ok := result["screen_name"].(string); ok {
return username, nil
}
return "", fmt.Errorf("Failed to parse response")
}
// Get user IDs from "Connect" tab on Twitter webapp sidebar
func getConnectTabUserIDs(s *scraper.Scraper) ([]string, error) {
type userResults struct {
Result struct {
ID string `json:"id"`
RestID string `json:"rest_id"`
} `json:"result"`
}
type item struct {
ItemContent struct {
ItemType string `json:"itemType"`
UserResults userResults `json:"user_results"`
} `json:"itemContent"`
}
type rsp struct {
Data struct {
ConnectTabTimeline struct {
Timeline struct {
Instructions []struct {
Type string `json:"type"`
Entries []struct {
EntryID string `json:"entryId"`
Content struct {
EntryType string `json:"entryType"`
Items []struct {
EntryID string `json:"entryId"`
Item item `json:"item"`
} `json:"items"`
} `json:"content"`
} `json:"entries"`
} `json:"instructions"`
} `json:"timeline"`
} `json:"connect_tab_timeline"`
} `json:"data"`
}
req, err := http.NewRequest("GET", "https://twitter.com/i/api/graphql/kfbHAW8uW0F3PboJu827wg/ConnectTabTimeline?variables=%7B%22count%22%3A20%2C%22context%22%3A%22%7B%7D%22%7D&features=%7B%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Afalse%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_media_download_video_enabled%22%3Afalse%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D", nil)
if err != nil {
return nil, err
}
resp, err := s.RequestAPI(req, nil)
if err != nil {
return nil, err
}
response := rsp{}
if err := json.Unmarshal(resp, &response); err != nil {
return nil, err
}
userIDs := []string{}
for _, instruction := range response.Data.ConnectTabTimeline.Timeline.Instructions {
if instruction.Type == "TimelineAddEntries" {
for _, entry := range instruction.Entries {
for _, item := range entry.Content.Items {
if item.Item.ItemContent.ItemType == "TimelineUser" {
restID := item.Item.ItemContent.UserResults.Result.RestID
userIDs = append(userIDs, restID)
}
}
}
}
}
return userIDs, nil
} |
package com.highwayac.com.domain;
import jakarta.validation.constraints.*;
import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
/**
* A Novel.
*/
@Table("novel")
@SuppressWarnings("common-java:DuplicatedBlocks")
public class Novel implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column("id")
private Long id;
@NotNull(message = "must not be null")
@Column("noveltext")
private String noveltext;
@NotNull(message = "must not be null")
@Column("novelname")
private String novelname;
@Column("noveltype")
private String noveltype;
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return this.id;
}
public Novel id(Long id) {
this.setId(id);
return this;
}
public void setId(Long id) {
this.id = id;
}
public String getNoveltext() {
return this.noveltext;
}
public Novel noveltext(String noveltext) {
this.setNoveltext(noveltext);
return this;
}
public void setNoveltext(String noveltext) {
this.noveltext = noveltext;
}
public String getNovelname() {
return this.novelname;
}
public Novel novelname(String novelname) {
this.setNovelname(novelname);
return this;
}
public void setNovelname(String novelname) {
this.novelname = novelname;
}
public String getNoveltype() {
return this.noveltype;
}
public Novel noveltype(String noveltype) {
this.setNoveltype(noveltype);
return this;
}
public void setNoveltype(String noveltype) {
this.noveltype = noveltype;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Novel)) {
return false;
}
return getId() != null && getId().equals(((Novel) o).getId());
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "Novel{" +
"id=" + getId() +
", noveltext='" + getNoveltext() + "'" +
", novelname='" + getNovelname() + "'" +
", noveltype='" + getNoveltype() + "'" +
"}";
}
} |
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:meals_app/features/filters/widgets/filters_check_item.dart';
import 'package:meals_app/features/tab_bar/widgets/main_drawer.dart';
import 'package:meals_app/providers/filter_provider.dart';
class FiltersScreen extends ConsumerWidget {
const FiltersScreen({super.key});
void onFilterCheck(WidgetRef ref, Filter filter, bool isChecked) {
ref.read(filterProvider.notifier).setFilter(filter, isChecked);
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final filters = ref.watch(filterProvider);
return Scaffold(
appBar: AppBar(
title: const Text('Your Filters'),
),
drawer: const MainDrawer(currentPage: DrawerRoutes.filters),
body: Column(children: [
FilterCheckItem(
title: "Gluten-free",
subtitle: "Only include gluten-free meals",
value: filters[Filter.glutenFree]!,
onChanged: (isChecked) {
onFilterCheck(ref, Filter.glutenFree, isChecked);
},
),
FilterCheckItem(
title: "Lactose-free",
subtitle: "Only include lactose-free meals",
value: filters[Filter.lactoseFree]!,
onChanged: (isChecked) {
onFilterCheck(ref, Filter.lactoseFree, isChecked);
},
),
FilterCheckItem(
title: "Vegetarian",
subtitle: "Only include vegetarian meals",
value: filters[Filter.vegetarian]!,
onChanged: (isChecked) {
onFilterCheck(ref, Filter.vegetarian, isChecked);
},
),
FilterCheckItem(
title: "Vegan",
subtitle: "Only include vegan meals",
value: filters[Filter.vegan]!,
onChanged: (isChecked) {
onFilterCheck(ref, Filter.vegan, isChecked);
},
),
]),
);
}
} |
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="shortcut icon"
href="../src/images/icon.ico"
type="image/x-icon"
/>
<title>Mesto Russia</title>
</head>
<body>
<div class="page">
<header class="header">
<img src="./images/logo.svg" class="header__logo" alt="Логотип" />
</header>
<main class="content">
<section class="profile">
<div class="profile-info">
<div class="profile-info__image-container">
<button
type="button"
class="profile-info__avatar-customizaton"
></button>
<img
src="../src/images/avatar.jpg"
alt="Аватар"
class="profile-info__image"
/>
</div>
<div class="profile-info__container">
<div class="profile-info__name-box">
<h1 class="profile-info__name">Жак-Ив Кусто</h1>
<button
type="button"
class="profile-info__customization"
></button>
</div>
<p class="profile-info__job">Исследователь океана</p>
</div>
</div>
<button type="button" class="profile__button"></button>
</section>
<section class="elements">
<ul class="cards"></ul>
</section>
</main>
<footer class="footer">
<p class="footer__credit">© 2020 Mesto Russia</p>
</footer>
<div class="popup" id="popupInfo">
<div class="popup__container">
<h2 class="popup__heading">Редактировать профиль</h2>
<form
class="popup__form"
name="popupFormInfo"
id="popupFormInfo"
novalidate
>
<fieldset class="popup__set">
<label class="popup__field">
<input
minlength="2"
maxlength="40"
type="text"
class="popup__input popup__input_data_name"
name="name"
placeholder="Имя"
required
id="name-input"
/>
<span class="popup__error" id="name-input-error"></span>
</label>
<label class="popup__field">
<input
minlength="2"
maxlength="200"
type="text"
class="popup__input popup__input_data_info"
name="info"
placeholder="О себе"
required
id="data-input"
/>
<span class="popup__error" id="data-input-error"></span>
</label>
<button type="submit" class="popup__button" id="infoSubmit">
Сохранить
</button>
</fieldset>
</form>
<button
class="popup__close"
type="button"
id="popupInfoClose"
></button>
</div>
</div>
<div class="popup" id="popupCard">
<div class="popup__container">
<h2 class="popup__heading">Новое место</h2>
<form
class="popup__form"
name="popupFormCard"
id="popupFormCard"
novalidate
>
<fieldset class="popup__set">
<label class="popup__field">
<input
minlength="2"
maxlength="30"
type="text"
class="popup__input popup__input_data_name"
name="name"
placeholder="Название"
required
id="place-input"
/>
<span class="popup__error" id="place-input-error"></span>
</label>
<label class="popup__field">
<input
minlength="2"
type="url"
class="popup__input popup__input_data_info"
name="link"
placeholder="Ссылка на картинку"
required
id="url-input"
/>
<span class="popup__error" id="url-input-error"></span>
</label>
<button type="submit" class="popup__button">Создать</button>
</fieldset>
</form>
<button
class="popup__close"
type="button"
id="popupCardClose"
></button>
</div>
</div>
<div class="popup" id="popupImg">
<div class="popup__img-container">
<img src="#" class="popup__image" />
<button
class="popup__close"
type="button"
id="popupImgClose"
></button>
<h3 class="popup__img-subline"></h3>
</div>
</div>
<div class="popup" id="popupAvatar">
<div class="popup__container">
<h2 class="popup__heading">Обновить аватар</h2>
<form
class="popup__form"
name="popupFormAvatar"
id="popupFormAvatar"
novalidate
>
<fieldset class="popup__set">
<label class="popup__field">
<input
minlength="2"
type="url"
class="popup__input popup__input_data_info"
name="link"
placeholder="Ссылка на картинку"
required
id="url-input"
/>
<span class="popup__error" id="url-input-error"></span>
</label>
<button type="submit" class="popup__button">Сохранить</button>
</fieldset>
</form>
<button
class="popup__close"
type="button"
id="popupAvatarClose"
></button>
</div>
</div>
<div class="popup" id="popupConfirm">
<div class="popup__container">
<h2 class="popup__heading popup__heading_type_confirm">
Вы уверены?
</h2>
<form
class="popup__form"
name="popupFormConfirm"
id="popupFormConfirm"
novalidate
>
<button type="submit" class="popup__button">Да</button>
</form>
<button
class="popup__close"
type="button"
id="popupConfirmClose"
></button>
</div>
</div>
<div class="popup popup_opened" id="popupLoading">
<div class="popup__img-container popup__img-container_loader">
<img src="../src/images/loading_1.svg" class="popup__image" />
</div>
</div>
</div>
<template class="card-template">
<li class="card">
<img src="#" alt="#" class="card__image" />
<button type="button" class="card__delete-button"></button>
<div class="card__box">
<h2 class="card__title"></h2>
<div class="card__like-box">
<button type="button" class="card__like"></button>
<p class="card__like-counter">0</p>
</div>
</div>
</li>
</template>
</body>
</html> |
<!--
File: index.html
Author: Nathan Hunter
Date: April 23, 2022
Purpose:
Creates a 3D animated scene using the Three.js library
Consists of at least 6 different shapes, minimum resolution 640x480,
multiple lighting effects, and controls to alter/toggle variosu components
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<title>Project 3: Three.js Scene</title>
<style>
body {
margin: 0;
}
canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<script type="importmap">
{
"imports": {
"three": "./libs/three.module.js"
}
}
</script>
<!--
<script src="./three.js"></script>
<script src="./FBXLoader.js"></script>
-->
<script src="./libs/dat.gui.js"></script>
<script type="module">
import * as THREE from 'three';
//import { GUI } from './dat.gui.js';
import { OrbitControls } from './libs/OrbitControls.js';
import { FBXLoader } from './libs/FBXLoader.js';
var scene, camera, renderer, orbit, cube, sphere, viewWidth, viewHeight;
var loader = new THREE.TextureLoader();
var animationOn = true, animationSpeed = 1.0, rotateCube = true;
const clock = new THREE.Clock();
const modelLoader = new FBXLoader();
var theta = 0, models = new Array();
init();
animate();
function init() {
// ***************************** MATERIALS ***************************** //
const panelMat = new THREE.MeshPhysicalMaterial({
map: loader.load('res/panel_albedo.png'),
normalMap: loader.load('res/panel_normal.png'),
metalnessMap: loader.load('res/panel_metallic.png'),
roughnessMap: loader.load('res/panel_roughness.png'),
aoMap: loader.load('res/panel_ao.png'),
});
const steelMat = new THREE.MeshPhysicalMaterial({
map: loadTex('res/steel_albedo.png', 6, 6),
normalMap: loadTex('res/steel_normal.png', 6, 6),
metalnessMap: loadTex('res/steel_metallic.png', 6, 6),
roughnessMap: loadTex('res/steel_roughness.png', 6, 6),
aoMap: loadTex('res/steel_ao.png', 6, 6),
});
const metalMat = new THREE.MeshPhysicalMaterial({
map: loadTex('res/metal_albedo.png', 6, 6),
normalMap: loadTex('res/metal_normal.png', 6, 6),
metalnessMap: loadTex('res/metal_metallic.png', 6, 6),
roughnessMap: loadTex('res/metal_roughness.png', 6, 6),
aoMap: loadTex('res/metal_ao.png', 6, 6),
});
// ***************************** GRAPHICS SETUP ***************************** //
// Scene with shadow catcher
scene = new THREE.Scene();
const floor = new THREE.Mesh(new THREE.PlaneGeometry(40, 40), steelMat);
floor.position.y = -0.04;
floor.rotateX(-Math.PI * 0.5);
floor.receiveShadow = true;
steelMat.side = THREE.DoubleSide;
scene.add(floor);
// Renderer
viewWidth = Math.max(window.innerWidth, 640);
viewHeight = Math.max(window.innerHeight, 480);
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(viewWidth, viewHeight);
renderer.setClearColor('#222222');
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(renderer.domElement);
// Camera
camera = new THREE.PerspectiveCamera(60, viewWidth / viewHeight, 0.1, 1000);
camera.position.set(0, 14, 30);
orbit = new OrbitControls(camera, renderer.domElement);
orbit.target.set(0, 2, 0);
orbit.update();
// ****************************** LIGHTING ****************************** //
// Ambient light
const ambLight = new THREE.AmbientLight(0xffffff, 0.2);
scene.add(ambLight);
// Directional light - casts shadows
const dirLight = new THREE.DirectionalLight(0xffffff, 1, 100);
dirLight.position.set(-5, 14, -5);
dirLight.lookAt(5, 0, -5);
dirLight.radius = 20;
dirLight.castShadow = true;
dirLight.shadow.mapSize.width = 2048;
dirLight.shadow.mapSize.height = 2048;
var lSize = 40;
dirLight.shadow.camera.left = -lSize;
dirLight.shadow.camera.right = lSize;
dirLight.shadow.camera.top = lSize;
dirLight.shadow.camera.bottom = -lSize;
dirLight.shadow.camera.near = 0.1;
dirLight.shadow.camera.far = 1000;
scene.add(dirLight);
// Point light
const pointLight = new THREE.PointLight(0x33ccff, 0.5);
pointLight.position.set(0, 20, 0);
scene.add(pointLight);
// ****************************** SCENE OBJECTS ****************************** //
// Cube
cube = new THREE.Mesh(new THREE.BoxGeometry(8, 8, 8), panelMat);
cube.position.set(0, 4, -13);
cube.castShadow = true;
scene.add(cube);
sphere = new THREE.Mesh(new THREE.SphereGeometry(3, 32, 16), metalMat);
sphere.position.set(0, 4, -13);
sphere.castShadow = true;
scene.add(sphere);
loadModel('dance_00.fbx', -12, 0, 2, 0.05);
loadModel('dance_01.fbx', 0, 0, -3, 0.05);
loadModel('dance_02.fbx', 10, 0, 2, 0.05);
loadModel('dance_03.fbx', 0, 0, 15, 0.05);
// *********************************** GUI *********************************** //
const controls = {
type: 'three',
toggleDirLight: true,
colorDirLight: 0xffffff,
toggleAmbLight: true,
colorAmbLight: 0xffffff,
togglePointLight: true,
colorPointLight: 0x33ccff,
toggleAnimation: true,
speedAnimation: animationSpeed,
toggleBall: true,
toggleCube: true,
toggleCubeRot: true,
};
const gui = new dat.GUI();
// Ambient light controls
const folderAmbLight = gui.addFolder('Ambient Light');
folderAmbLight.add(controls, 'toggleAmbLight')
.name('On').listen()
.onChange(function () {
ambLight.visible = !ambLight.visible;
});
folderAmbLight.addColor(controls, 'colorAmbLight')
.name('Color')
.onChange(function () {
ambLight.color.set(controls.colorAmbLight);
});
folderAmbLight.open();
// Directional light controls
const folderDirLight = gui.addFolder('Directional Light');
folderDirLight.add(controls, 'toggleDirLight')
.name('On').listen()
.onChange(function () {
dirLight.visible = !dirLight.visible;
});
folderDirLight.add(dirLight.position, 'x', -10, 10).listen();
folderDirLight.add(dirLight.position, 'y', 14, 30).listen();
folderDirLight.add(dirLight.position, 'z', -10, 10).listen();
folderDirLight.addColor(controls, 'colorDirLight')
.name('Color')
.onChange(function () {
dirLight.color.set(controls.colorDirLight);
});
folderDirLight.open();
// Point light controls
const folderPointLight = gui.addFolder('Point Light');
folderPointLight.add(controls, 'togglePointLight')
.name('On').listen()
.onChange(function () {
pointLight.visible = !pointLight.visible;
});
folderPointLight.add(pointLight.position, 'x', -10, 10).listen();
folderPointLight.add(pointLight.position, 'y', 0, 10).listen();
folderPointLight.add(pointLight.position, 'z', -10, 10).listen();
folderPointLight.addColor(controls, 'colorPointLight')
.name('Color')
.onChange(function () {
pointLight.color.set(controls.colorPointLight);
});
folderPointLight.open();
// Animation controls
const folderAnimation = gui.addFolder('Animation');
folderAnimation.add(controls, 'toggleAnimation')
.name('On').listen()
.onChange(function () {
animationOn = !animationOn;
});
folderAnimation.add(controls, 'toggleBall')
.name('Ball').listen()
.onChange(function () {
sphere.visible = !sphere.visible;
});
folderAnimation.add(controls, 'toggleCube')
.name('Cube').listen()
.onChange(function () {
cube.visible = !cube.visible;
});
folderAnimation.add(controls, 'toggleCubeRot')
.name('Cube Rotation').listen()
.onChange(function () {
rotateCube = !rotateCube;
});
folderAnimation.add(controls, 'speedAnimation').min(0.1).max(2.0).step(0.01)
.name('Speed').listen()
.onChange(function () {
animationSpeed = controls.speedAnimation;
});
folderAnimation.open();
// ************************* FINALIZE AND ANIMATE ************************** //
window.addEventListener('resize', () => {
viewWidth = Math.max(window.innerWidth, 640);
viewHeight = Math.max(window.innerHeight, 480);
renderer.setSize(viewWidth, viewHeight);
camera.aspect = viewWidth / viewHeight;
camera.updateProjectionMatrix();
});
}
function loadTex(fileName, u, v) {
let tex = loader.load(fileName);
tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
tex.repeat.set(u, v);
return tex;
}
function loadModel(fileName, x, y, z, scale) {
let mix;
modelLoader.load('./res/'+fileName, function (model) {
mix = new THREE.AnimationMixer(model);
models.push(mix);
var action = mix.clipAction(model.animations[0]);
action.play();
model.traverse(function (child) {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
model.position.set(x, y, z);
model.scale.multiplyScalar(scale);
scene.add(model);
});
}
function animate() {
requestAnimationFrame(animate);
if (animationOn) {
const delta = clock.getDelta() * animationSpeed;
theta += delta;
var xPos = 10 * Math.sin(theta);
cube.position.x = xPos;
if (rotateCube) cube.rotateY(delta * 2);
var pos = (Math.sin(theta * 8) + 1) * 0.5; // Normalize 0 - 1
var yPos = 11 + 5 * Math.sin((pos * Math.PI) * 0.5); // ease-out sine
sphere.position.set(xPos, yPos, -13);
for (var i = 0; i < models.length; i++) {
if (models[i]) models[i].update(delta);
}
}
renderer.render(scene, camera);
}
</script>
</body>
</html> |
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/Dialog';
import { useState } from 'react';
import { Button } from '../../components/ui/Button';
import { useMutation } from '@tanstack/react-query';
import useAxiosPrivate from '@/hooks/useAxiosPrivate';
import toast from 'react-hot-toast';
import { AxiosError } from 'axios';
interface CreateAppProps {
children: React.ReactNode;
title: string
onClose: (refreshParent:boolean) => void;
isOpen: boolean
};
function CreateAppPopup({ children, title, onClose, isOpen }: CreateAppProps) {
const [appName, setAppName] = useState('');
const [appDomain, setAppDomain] = useState('');
const [appDesc, setAppDesc] = useState('');
const axiosPrivate = useAxiosPrivate();
const { mutate, isPending } = useMutation({
mutationFn: () =>
axiosPrivate({
url: '/apps',
method: 'post',
data: {
appName: appName,
appDesc: appDesc,
appDomain: appDomain
},
}),
onSuccess: (response: any) => {
const resposeData: any = response?.data;
console.log(resposeData);
setAppName('');
setAppDesc('');
setAppDomain('');
toast.success(resposeData.message);
onClose(true);
},
onError: (error: AxiosError) => {
console.error("failed::", error);
const resposeData: any = error.response?.data;
toast.error(resposeData.message)
}
});
return (
<>
<Dialog onOpenChange={open => {
if (!open) onClose(false);
}} open={isOpen}>
<DialogTrigger>{children}</DialogTrigger>
<DialogContent className="gap-0">
<DialogHeader className="space-y-3">
<DialogTitle>{title}</DialogTitle>
</DialogHeader>
<div className="max-w-md mx-auto bg-white p-8 rounded">
<form
className="flex flex-grow flex-col"
onSubmit={e => {
e.preventDefault();
mutate();
}}
>
<div className="mb-4">
<label htmlFor="appName" className="block text-gray-600 text-sm font-medium mb-2">Name</label>
<input
type="text"
id="appName"
name="appName"
className="w-full px-4 py-2 border rounded-md focus:outline-none focus:border-blue-500"
value={appName}
onChange={(e) => setAppName(e.target.value)}
/>
</div>
<div className="mb-4">
<label htmlFor="appDomain" className="block text-gray-600 text-sm font-medium mb-2">Domain</label>
<input
type="text"
id="appDomain"
name="appDomain"
className="w-full px-4 py-2 border rounded-md focus:outline-none focus:border-blue-500"
value={appDomain}
onChange={(e) => setAppDomain(e.target.value)}
/>
</div>
<div className="mb-6">
<label htmlFor="message" className="block text-gray-600 text-sm font-medium mb-2">Description</label>
<textarea
id="appDesc"
name="appDesc"
rows={4}
cols={50}
value={appDesc}
className="w-full px-4 py-2 border rounded-md focus:outline-none focus:border-blue-500"
onChange={(e) => setAppDesc(e.target.value)}
>
</textarea>
</div>
<Button
disabled={false}
isLoading={isPending}
className="gap-2.5"
>
<span>Save</span>
</Button>
</form>
</div>
</DialogContent>
</Dialog>
</>
)
};
export default CreateAppPopup; |
{% extends "base.html" %}
{% block content %}
<h1>Регистрация</h1>
<form action="" method="post" enctype="multipart/form-data" class="login_form">
{{ form.hidden_tag() }}
<div class="form-group">
<label for="picture">Аватарка</label>
<input type="file" class="form-control-file" id="picture" name="file" accept="image/*">
</div>
<p>
{{ form.name.label }}<br>
{{ form.name(class="form-control") }}<br>
{% for error in form.name.errors %}
<p class="alert alert-danger" role="alert">
{{ error }}
</p>
{% endfor %}
</p>
<p>
{{ form.login.label }}<br>
{{ form.login(class="form-control") }}<br>
{% for error in form.login.errors %}
<p class="alert alert-danger" role="alert">
{{ error }}
</p>
{% endfor %}
</p>
<p>
{{ form.about.label }}<br>
{{ form.about(class="form-control") }}<br>
{% for error in form.about.errors %}
<p class="alert alert-danger" role="alert">
{{ error }}
</p>
{% endfor %}
</p>
<p>
{{ form.email.label }}<br>
{{ form.email(class="form-control", type="email") }}<br>
{% for error in form.email.errors %}
<p class="alert alert-danger" role="alert">
{{ error }}
</p>
{% endfor %}
</p>
<p>
{{ form.password.label }}<br>
{{ form.password(class="form-control", type="password") }}<br>
{% for error in form.password.errors %}
<p class="alert alert-danger" role="alert">
{{ error }}
</p>
{% endfor %}
</p>
<p>
{{ form.password_again.label }}<br>
{{ form.password_again(class="form-control", type="password") }}<br>
{% for error in form.password_again.errors %}
<p class="alert alert-danger" role="alert">
{{ error }}
</p>
{% endfor %}
</p>
<p>{{ form.submit(type="submit", class="btn btn-outline-success") }}</p>
{{message}}
</form>
{% endblock %} |
import { Text, TouchableOpacity } from "react-native";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import { faSquare, faSquareCheck } from "@fortawesome/free-regular-svg-icons";
type CheckProps = {
label: string;
checked: boolean | false;
onToggle: () => void;
style?: {};
};
export default function Check({ label, checked, onToggle, style }: CheckProps) {
const handleToggle = () => {
onToggle();
};
return (
<TouchableOpacity
onPress={handleToggle}
style={[
{
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "flex-start",
},
style,
]}
>
<FontAwesomeIcon
icon={checked ? faSquareCheck : faSquare}
size={32}
style={{ color: "orange", marginRight: 8 }}
/>
<Text style={{ fontSize: 24 }}>{label}</Text>
</TouchableOpacity>
);
} |
import 'dart:io';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/material.dart';
import 'package:haelo_flutter/constants.dart';
import 'package:haelo_flutter/core/utils/functions.dart';
import 'package:haelo_flutter/core/utils/ui_helper.dart';
import 'package:haelo_flutter/features/causeslist/presentation/widget/error_dialog.dart';
import 'package:haelo_flutter/features/court_date_report/presentation/screen/court_date_report_screen.dart';
import 'package:haelo_flutter/features/drawer_content/presentation/screens/draw_aboutus.dart';
import 'package:haelo_flutter/features/drawer_content/presentation/screens/draw_commentshistory.dart';
import 'package:haelo_flutter/features/drawer_content/presentation/screens/draw_faq.dart';
import 'package:haelo_flutter/features/drawer_content/presentation/screens/draw_hiddencauselist.dart';
import 'package:haelo_flutter/features/drawer_content/presentation/screens/draw_listinghistory.dart';
import 'package:haelo_flutter/features/drawer_content/presentation/screens/draw_orderhistory.dart';
import 'package:haelo_flutter/features/drawer_content/presentation/screens/draw_settings.dart';
import 'package:haelo_flutter/features/home_page/presentation/widgets/custometext.dart';
import 'package:haelo_flutter/features/in_app_purchase/presentation/screen/my_subscription.dart';
import 'package:haelo_flutter/features/in_app_purchase/presentation/screen/plans.dart';
import 'package:haelo_flutter/features/in_app_purchase/presentation/screen/promo_codes.dart';
import 'package:haelo_flutter/features/order_comment_history/presentation/screen/orderCommentHistory.dart';
import 'package:haelo_flutter/features/order_comment_history/presentation/screen/order_cmt_history_test.dart';
import 'package:haelo_flutter/features/order_comment_history/presentation/screen/order_cmt_history_test2.dart';
import 'package:haelo_flutter/features/ticker_data/presentation/ticker_data_screen.dart';
import 'package:haelo_flutter/features/userboard/presentation/screens/login.dart';
import 'package:haelo_flutter/features/userboard/presentation/widgets/html_content.dart';
import 'package:haelo_flutter/widgets/go_prime.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../../widgets/error_widget.dart';
import '../../../drawer_content/presentation/screens/coupans_list.dart';
import '../../../drawer_content/presentation/screens/draw_myteam.dart';
import '../../../drawer_content/presentation/screens/draw_paperhistory.dart';
import '../../../drawer_content/presentation/screens/draw_profile.dart';
import 'package:haelo_flutter/locators.dart' as di;
import 'package:google_sign_in/google_sign_in.dart' as google_sign_in;
import '../../../in_app_purchase/presentation/screen/inapp_purchase.dart';
import '../../../in_app_purchase/presentation/screen/ios_plans.dart';
import '../../../mass_addition_of_case/presentation/mass_addition_of_cases.dart';
import '../../../pending_order_report/presentation/screen/pendingOrderReport.dart';
class AppDrawer extends StatefulWidget {
const AppDrawer({Key? key}) : super(key: key);
@override
State<AppDrawer> createState() => _AppDrawerState();
}
class _AppDrawerState extends State<AppDrawer> {
late SharedPreferences pref;
@override
void initState() {
super.initState();
print("hello from drawer");
pref = di.locator();
}
void showPrimePopup(BuildContext context) {
FocusScope.of(context).requestFocus(FocusNode());
showDialog(
context: context,
builder: (ctx) => SafeArea(
child: GoPrime(),
));
}
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return SafeArea(
child: Drawer(
width: size.width * 0.8,
child: SingleChildScrollView(
child: Column(children: [
Container(
alignment: Alignment.centerLeft,
height: 45,
// width: size.width * 1,
padding: EdgeInsets.only(left: 15),
decoration: BoxDecoration(
color: AppColor.primary,
border: Border(
bottom: BorderSide(color: Colors.orange, width: 2.5),
)),
child: Text("HAeLO",
style: mpHeadLine18(
textColor: Colors.white,
fontWeight: FontWeight.w500,
)),
),
InkWell(
onTap: () {
if (Platform.isIOS) {
Navigator.pop(context);
goToPage(context, IOSPlans());
} else {
Navigator.pop(context);
goToPage(context, Plans());
}
// goToPage(context, InApp());
},
child: NeoText(
text: "Go Prime",
iconss: Icon(
Icons.workspace_premium_outlined,
color: AppColor.primary,
)),
),
InkWell(
onTap: () {
Navigator.pop(context);
goToPage(context, PromoCodes());
},
child: NeoText(
text: "Purchase coupons",
iconss: Icon(
Icons.workspace_premium_outlined,
color: AppColor.primary,
)),
),
InkWell(
onTap: () {
Navigator.pop(context);
goToPage(context, CouponList());
},
child: NeoText(
text: "My coupons",
iconss: Icon(
Icons.workspace_premium_outlined,
color: AppColor.primary,
)),
),
InkWell(
onTap: () {
if (isPrime(pref) &&
(planName(pref) == Constants.goldPlan ||
planName(pref) == Constants.platinumPlan ||
planName(pref) == Constants.silverPlan)) {
Navigator.pop(context);
goToPage(context, MySubscription());
} else {
// showPrimePopup(context);
Navigator.pop(context);
goToPage(context, MySubscription());
}
},
child: NeoText(
text: "My Subscription",
iconss: Icon(
Icons.subscriptions_outlined,
color: AppColor.primary,
)),
),
InkWell(
onTap: () {
Navigator.pop(context);
Navigator.push(context,
MaterialPageRoute(builder: (context) => ProfileDraw()));
},
child: NeoText(
text: "Profile",
// size: 20,
// fontWeight: FontWeight.bold,
// color: Colors.black,
// wordSpacing: 1,
iconss: Icon(
Icons.person,
color: AppColor.primary,
)),
),
pref.getString(Constants.USER_TYPE) == "2"
? SizedBox()
: InkWell(
onTap: () {
if (isPrime(pref) &&
(planName(pref) == Constants.goldPlan ||
planName(pref) == Constants.platinumPlan ||
planName(pref) == Constants.silverPlan)) {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const MyTeam()));
} else {
showPrimePopup(context);
}
},
child: NeoText(
text: "My Team",
iconss: Icon(Icons.people, color: AppColor.primary))),
InkWell(
onTap: () {
if (isPrime(pref) &&
(planName(pref) == Constants.goldPlan ||
planName(pref) == Constants.platinumPlan)) {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CourtDateReportScreen()));
} else {
showPrimePopup(context);
}
},
child: NeoText(
text: "Court Date Report",
iconss: Icon(Icons.data_exploration_outlined,
color: AppColor.primary))),
Column(
mainAxisSize: MainAxisSize.min,
children: [
InkWell(
onTap: () {
if (isPrime(pref) &&
(planName(pref) == Constants.goldPlan ||
planName(pref) == Constants.silverPlan) ||
planName(pref) == Constants.platinumPlan) {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HiddenCauselist()));
} else {
showPrimePopup(context);
}
},
child: NeoText(
text: "My Hidden Cause List",
iconss: Icon(Icons.featured_play_list_outlined,
color: AppColor.primary))),
InkWell(
onTap: () {
if (isPrime(pref)) {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
const TickerDataTableScreen()));
} else {
showPrimePopup(context);
}
},
child: NeoText(
text: "Ticker Data",
iconss: Icon(Icons.table_chart_outlined,
color: AppColor.primary))),
InkWell(
onTap: () {
if (isPrime(pref)) {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
const MassAdditionOfCase()));
} else {
showPrimePopup(context);
}
},
child: NeoText(
text: "Mass addition of cases",
iconss: Icon(Icons.table_chart_outlined,
color: AppColor.primary))),
InkWell(
onTap: () {
if (isPrime(pref)) {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PendingCmtHistory()));
} else {
showPrimePopup(context);
}
},
child: NeoText(
text: "Pending Order Report",
iconss: Icon(Icons.table_chart_outlined,
color: AppColor.primary))),
InkWell(
onTap: () {
if (isPrime(pref) &&
(planName(pref) == Constants.goldPlan ||
planName(pref) == Constants.platinumPlan)) {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => OrderCmtHistory4(
isFromCmt: true,
)));
} else {
showPrimePopup(context);
}
},
child: NeoText(
text: "Order-Comment History",
iconss: Icon(Icons.featured_play_list_outlined,
color: AppColor.primary))),
InkWell(
onTap: () {
if (isPrime(pref) &&
(planName(pref) == Constants.goldPlan ||
planName(pref) == Constants.platinumPlan)) {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => OrderHistory()));
} else {
showPrimePopup(context);
}
},
child: NeoText(
text: "Order Judgement/History",
iconss:
Icon(Icons.lock_clock, color: AppColor.primary))),
InkWell(
onTap: () {
if (isPrime(pref) &&
(planName(pref) == Constants.goldPlan ||
planName(pref) == Constants.platinumPlan)) {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CommentHistory()));
} else {
showPrimePopup(context);
}
},
child: NeoText(
text: "Comments history",
iconss:
Icon(Icons.lock_clock, color: AppColor.primary))),
InkWell(
onTap: () {
if (isPrime(pref) &&
(planName(pref) == Constants.goldPlan ||
planName(pref) == Constants.platinumPlan)) {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ListingHistory()));
} else {
showPrimePopup(context);
}
},
child: NeoText(
text: "Date of Listing History",
iconss:
Icon(Icons.lock_clock, color: AppColor.primary))),
InkWell(
onTap: () {
if (isPrime(pref) &&
(planName(pref) == Constants.goldPlan ||
planName(pref) == Constants.platinumPlan)) {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PaperDetailHistory()));
} else {
showPrimePopup(context);
}
},
child: NeoText(
text: "Paper Details history",
iconss: Icon(Icons.lock, color: AppColor.primary))),
InkWell(
onTap: () {
if (isPrime(pref) &&
(planName(pref) == Constants.goldPlan ||
planName(pref) == Constants.platinumPlan)) {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SettingsDraw()));
} else {
showPrimePopup(context);
}
},
child: NeoText(
text: "Settings",
iconss: Icon(Icons.settings_applications_sharp,
color: AppColor.primary))),
],
),
InkWell(
onTap: () {
Navigator.pop(context);
Navigator.push(context,
MaterialPageRoute(builder: (context) => AboutUs()));
},
child: NeoText(
text: "About Us",
iconss: Icon(Icons.account_circle_rounded,
color: AppColor.primary))),
InkWell(
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyWebView(
"https://haeloapp.in/privacy-policy",
"Privacy Policy",
)));
},
child: NeoText(
text: "Privacy Policy",
iconss: Icon(Icons.shield, color: AppColor.primary))),
InkWell(
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyWebView(
"https://haeloapp.in/terms-and-conditions",
"Terms & Conditions",
)));
},
child: NeoText(
text: "Terms & Conditions",
iconss: Icon(Icons.shield, color: AppColor.primary))),
InkWell(
onTap: () {
Navigator.pop(context);
Navigator.push(
context, MaterialPageRoute(builder: (context) => FAQ()));
},
child: NeoText(
text: "FAQs",
iconss:
Icon(Icons.question_mark, color: AppColor.primary))),
InkWell(
onTap: () {
_showLogoutDialog();
// Navigator.push(context, MaterialPageRoute(builder: (context) => Login()));
},
child: NeoText(
text: "Logout",
iconss: Icon(Icons.lock_open, color: AppColor.primary))),
Center(
child: InkWell(
onTap: () {
//FirebaseCrashlytics.instance.crash();
},
child: Text(
"V (${pref.getString(Constants.app_version)})",
style: mpHeadLine16(fontWeight: FontWeight.w700),
),
),
),
SizedBox(
height: 27,
)
]),
),
),
);
}
void _showLogoutDialog() {
Widget cancelButton = TextButton(
child: const Text(
"Cancel",
style: TextStyle(color: AppColor.primary),
),
onPressed: () {
Navigator.of(context).pop();
},
);
Widget continueButton = TextButton(
child: const Text("Logout", style: TextStyle(color: AppColor.primary)),
onPressed: () async {
Navigator.of(context).pop();
await pref.clear();
final googleSignIn = google_sign_in.GoogleSignIn.standard();
if (await googleSignIn.isSignedIn()) {
googleSignIn.signOut();
}
showDialog(
context: context,
barrierDismissible: false,
builder: (ctx) => AppMsgPopup(
"Logout Successfully",
isCloseIcon: false,
isError: false,
btnCallback: () {
Navigator.of(context).pop();
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => Login()),
(route) => false);
},
));
},
);
var actoins = <Widget>[];
actoins.add(cancelButton);
actoins.add(continueButton);
AlertDialogShow().showAlertDialog(
context: context,
actions: actoins,
titleMsg: "Logout",
contentStr: "Are you sure you want to logout?");
}
} |
import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { Box, SxProps, Typography } from '@mui/material';
import debounce from 'lodash.debounce';
import IconButton from '../IconButton/IconButton';
import { ArrowLeftIcon, ArrowRightIcon } from '../icons';
import { carouselStyles } from './carousel-styles';
type CarouselProps = {
heading?: string;
actionElement?: JSX.Element;
items: JSX.Element[];
itemsToShow?: number;
smallGutter?: boolean;
hideArrows?: boolean;
sx?: SxProps;
};
const DEFAULT_ITEMS_TO_SHOW = 5;
const Carousel = forwardRef((props: CarouselProps, ref) => {
const carouselContentRef = useRef<HTMLDivElement>(null);
const [activeSlideIndex, setActiveSlideIndex] = useState(0);
const [sliderOffset, setSliderOffset] = useState(0);
const { heading, actionElement, items, itemsToShow, smallGutter, hideArrows, sx } = props;
const currentItemsToShow = itemsToShow || DEFAULT_ITEMS_TO_SHOW;
const totalSlides = Math.ceil(items.length / currentItemsToShow);
const slideItemPercentWidth = 100 / currentItemsToShow;
const onSlideChange = useCallback(
(index: number, currentTotalSlides: number) => {
if (carouselContentRef.current) {
const slideFirstItem = carouselContentRef.current.children[0];
if (slideFirstItem) {
const slideItemPixelWidth = slideFirstItem.getBoundingClientRect().width;
let currentSliderOffset = index * currentItemsToShow * slideItemPixelWidth;
if (index === currentTotalSlides - 1 && slideItemPercentWidth < 100) {
const totalItems = items.length;
const totalItemsToFillSlide = currentItemsToShow * (index + 1);
const itemsMissFillLastSlide = totalItemsToFillSlide - totalItems;
currentSliderOffset -= itemsMissFillLastSlide * slideItemPixelWidth;
}
setActiveSlideIndex(index);
setSliderOffset(currentSliderOffset);
}
}
},
[currentItemsToShow, items.length, slideItemPercentWidth]
);
const onArrowClick = useCallback(
(direction: 'back' | 'forward') => {
const currentIndex = direction === 'back' ? activeSlideIndex - 1 : activeSlideIndex + 1;
if (currentIndex < totalSlides && currentIndex >= 0) {
onSlideChange(currentIndex, totalSlides);
}
},
[onSlideChange, activeSlideIndex, totalSlides]
);
const onResizeSlider = debounce(() => {
if (totalSlides > 1) onSlideChange(activeSlideIndex, totalSlides);
}, 300);
useEffect(() => {
window.addEventListener('resize', onResizeSlider);
return () => {
window.removeEventListener('resize', onResizeSlider);
};
});
useImperativeHandle(ref, () => ({
slideChange: (index: number) => {
onSlideChange(index, totalSlides);
},
carouselContentRef,
}));
const headingMemo = useMemo(
() => (
<Box display="flex" alignItems="center">
<Typography variant="h2" mr={4}>
{heading}
</Typography>
{actionElement}
</Box>
),
[heading, actionElement]
);
const carouselItemsMemo = useMemo(
() =>
items.map((item, index) => {
return (
<Box
key={`item-${1 * index}`}
sx={{
...carouselStyles.carouselItem,
width: `${slideItemPercentWidth}%`,
...{ ...(smallGutter && carouselStyles.carouselItemSmallGutter) },
}}
>
{item}
</Box>
);
}),
[items, slideItemPercentWidth, smallGutter]
);
const backArrowMemo = useMemo(
() => (
<IconButton
mr={!heading && !hideArrows ? 4 : 2}
variant="circular"
btnSize="large"
icon={<ArrowLeftIcon />}
colorVariant="grey"
disabled={activeSlideIndex === 0}
onClick={() => {
onArrowClick('back');
}}
/>
),
[activeSlideIndex, onArrowClick, heading, hideArrows]
);
const forwardArrowMemo = useMemo(
() => (
<IconButton
ml={!heading && !hideArrows ? 4 : 0}
variant="circular"
btnSize="large"
icon={<ArrowRightIcon />}
colorVariant="grey"
disabled={activeSlideIndex === totalSlides - 1}
onClick={() => {
onArrowClick('forward');
}}
/>
),
[activeSlideIndex, totalSlides, onArrowClick, heading, hideArrows]
);
return (
<Box
sx={{
...carouselStyles.carouselContainer,
...{ ...(!heading && !hideArrows && carouselStyles.carouselContainerWithArrows) },
...sx,
}}
>
{heading && (
<Box display="flex" justifyContent="space-between" alignItems="center" mb={6}>
{headingMemo}
{totalSlides > 1 && (
<Box>
{backArrowMemo}
{forwardArrowMemo}
</Box>
)}
</Box>
)}
{!heading && !hideArrows && backArrowMemo}
<Box sx={carouselStyles.carouselSlidesWrapper}>
<Box
ref={carouselContentRef}
sx={{
...carouselStyles.carouselContent,
transform: `translateX(-${sliderOffset}px)`,
}}
>
{carouselItemsMemo}
</Box>
</Box>
{!heading && !hideArrows && forwardArrowMemo}
</Box>
);
});
export default Carousel; |
import { Controller, Get, Post, Put, Delete, Param, Body, NotFoundException, UseGuards, Request } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { CarsService } from './cars.service';
import { Car } from './car.entity';
import { CarDto } from './dto/car.dto';
@Controller('cars')
export class CarsController {
constructor(private readonly carsService: CarsService) { }
@Get()
async findAll(): Promise<Car[]> {
return await this.carsService.findAll();
}
@Get(':id')
async findOne(@Param('id') id: number): Promise<Car> {
const car = await this.carsService.findOne(id);
if (!car) {
throw new NotFoundException('This Car doesn\'t exist');
}
return car;
}
@UseGuards(AuthGuard('jwt'))
@Post()
async create(@Body() car: CarDto, @Request() req: any): Promise<Car> {
console.log(req.user.id)
return await this.carsService.create(car, req.user.id);
}
@UseGuards(AuthGuard('jwt'))
@Put(':id')
async update(@Param('id') id: number, @Body() car: CarDto, @Request() req: any): Promise<Car> {
const { numberOfAffectedRows, updatedCar } = await this.carsService.update(id, car, req.user.id);
if (numberOfAffectedRows === 0) {
throw new NotFoundException('This Car doesn\'t exist');
}
return updatedCar;
}
@UseGuards(AuthGuard('jwt'))
@Delete(':id')
async delete(@Param('id') id: number, @Request() req: any): Promise<string> {
const deleted = await this.carsService.delete(id, req.user.id);
if (deleted === 0) {
throw new NotFoundException('This Car doesn\'t exist');
}
return 'Successfully deleted';
}
} |
import React, { useState, useEffect } from 'react';
import { useHistory, useParams } from 'react-router-dom';
import TripPlanService from '../../services/trip-plan.service';
import DestinationService from '../../services/destination.service';
const AddTrip = () => {
const history = useHistory();
const { id } = useParams();
const [trip, setTrip] = useState({
destination: '',
startDate: '',
endDate: '',
activities: [''],
accommodations: {
hotel: '',
checkInDate: '',
checkOutDate: '',
},
});
const [destinationDetails, setDestinationDetails] = useState({});
const [destinationOptions, setDestinationOptions] = useState([]);
useEffect(() => {
const fetchDestinations = async () => {
try {
const destinations = await DestinationService.getAllDestinations();
setDestinationOptions(destinations);
} catch (error) {
console.error(error);
}
};
fetchDestinations();
}, []);
useEffect(() => {
if (id && id.length > 3) {
const fetchTripDetails = async () => {
try {
const data = await TripPlanService.getTripPlan(id);
setTrip(data);
fetchDestinationDetails(data.destination);
} catch (error) {
console.error(error);
}
};
fetchTripDetails();
}
}, [id]);
const fetchDestinationDetails = async (destinationId) => {
try {
const details = await DestinationService.getDestination(destinationId);
setDestinationDetails(details);
} catch (error) {
console.error(error);
}
};
const handleChange = (e) => {
const { name, value } = e.target;
setTrip((prevTrip) => ({
...prevTrip,
[name]: value,
}));
};
const handleDestinationChange = (e) => {
const selectedDestinationId = e.target.value;
setTrip((prevTrip) => ({
...prevTrip,
destination: selectedDestinationId,
}));
};
const handleActivitiesChange = (e, index) => {
const { value } = e.target;
const updatedActivities = [...trip.activities];
updatedActivities[index] = value;
setTrip((prevTrip) => ({
...prevTrip,
activities: updatedActivities,
}));
};
const handleAddActivityField = () => {
setTrip((prevTrip) => ({
...prevTrip,
activities: [...prevTrip.activities, ''],
}));
};
const handleAccommodationsChange = (e) => {
const { name, value } = e.target;
setTrip((prevTrip) => ({
...prevTrip,
accommodations: {
...prevTrip.accommodations,
[name]: value,
},
}));
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
if (id && id.length > 3) {
await TripPlanService.updateTripPlan(id, trip);
} else {
await TripPlanService.createTripPlan(trip);
}
goToRoute();
} catch (error) {
console.error(error);
}
};
const goToRoute = () => {
history.push('/trips/all');
};
return (
<div>
<h1>{id && id.length > 3 ? 'Edit Trip' : 'Add Trip'}</h1>
<form onSubmit={handleSubmit}>
<div>
<label>Destination:</label>
<select name="destination" value={trip.destination} onChange={handleDestinationChange}>
<option value="">Select a destination</option>
{destinationOptions.map((destination) => (
<option key={destination._id} value={destination._id}>
{destination.name}
</option>
))}
</select>
</div>
<div>
<label>Start Date:</label>
<input type="date" name="startDate" value={trip.startDate.slice(0, 10)} onChange={handleChange} />
</div>
<div>
<label>End Date:</label>
<input type="date" name="endDate" value={trip.endDate.slice(0, 10)} onChange={handleChange} />
</div>
<div>
<label>Activities:</label>
{trip.activities.map((activity, index) => (
<div key={index}>
<input
type="text"
name="activity"
value={activity}
onChange={(e) => handleActivitiesChange(e, index)}
/>
</div>
))}
<button type="button" onClick={handleAddActivityField}>
+ Add Activity
</button>
</div>
<div>
<label>Accommodations:</label>
<input
type="text"
name="hotel"
placeholder="Hotel Name"
value={trip.accommodations.hotel}
onChange={handleAccommodationsChange}
/>
<input
type="date"
name="checkInDate"
placeholder="Check-in Date"
value={trip.accommodations.checkInDate.slice(0, 10)}
onChange={handleAccommodationsChange}
/>
<input
type="date"
name="checkOutDate"
placeholder="Check-out Date"
value={trip.accommodations.checkOutDate.slice(0, 10)}
onChange={handleAccommodationsChange}
/>
</div>
<button type="submit">{(id && id.length > 3) ? 'Update Trip' : 'Create Trip'}</button>
</form>
</div>
);
}
export default AddTrip; |
package structure.linkedlist;
import common.ListNode;
/**
* 92. 反转链表 II
*
* @author Real
* @since 2023/4/5 20:43
*/
public class ReverseLinkedListScope {
public static void main(String[] args) {
ReverseLinkedListScope test = new ReverseLinkedListScope();
int[] array = {1, 2, 3, 4, 5};
ListNode head = ListNode.initList(array);
ListNode.printList(test.reverseBetween(head, 1, 5));
}
/**
* 翻转范围内的链表
*
* @param head 头结点
* @param left 左
* @param right 右
* @return {@link ListNode}
*/
public ListNode reverseBetween(ListNode head, int left, int right) {
// 因为头节点有可能发生变化,使用虚拟头节点可以避免复杂的分类讨论
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode pre = dummyNode;
// 第 1 步:从虚拟头节点走 left - 1 步,来到 left 节点的前一个节点
// 建议写在 for 循环里,语义清晰
for (int i = 0; i < left - 1; i++) {
pre = pre.next;
}
// 第 2 步:从 pre 再走 right - left + 1 步,来到 right 节点
ListNode rightNode = pre;
for (int i = 0; i < right - left + 1; i++) {
rightNode = rightNode.next;
}
// 第 3 步:切断出一个子链表(截取链表)
ListNode leftNode = pre.next;
ListNode curr = rightNode.next;
// 注意:切断链接
pre.next = null;
rightNode.next = null;
// 第 4 步:同第 206 题,反转链表的子区间
reverseLinkedList(leftNode);
// 第 5 步:接回到原来的链表中
pre.next = rightNode;
leftNode.next = curr;
return dummyNode.next;
}
private void reverseLinkedList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
}
public ListNode reverseBetweenSecond(ListNode head, int left, int right) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
for (int i = 0; i < left - 1; i++) {
pre = pre.next;
}
// 头插法,将后面的节点不断移动到pre的下一个节点完成翻转
ListNode cur = pre.next;
for (int i = 0; i < right - left; i++) {
ListNode next = cur.next;
cur.next = next.next;
next.next = pre.next;
pre.next = next;
}
return dummy.next;
}
} |
import React from 'react';
import Question from './Question';
import QuestionCount from './QuestionCount';
import AnswerOption from './AnswerOption';
import './Quiz.css'
import PropTypes from 'prop-types';
const Quiz = (props) => {
function renderAnswerOptions(key) {
return (
<p>
<AnswerOption
key={key.content}
answerContent={key.content}
answerType={key.type}
answer={props.answer}
questionId={props.questionId}
onAnswerSelected={props.onAnswerSelected}
/>
</p>
);
}
return (
<section className="quiz">
<QuestionCount
counter={props.questionId}
total={props.questionTotal}
/>
<h2 className="question">What key signature is this?</h2>
<div className="questionContainer">
<Question question={props.question} alt={props.alt}/>
<ul className="answerOptions">
{props.answerOptions.map(renderAnswerOptions)}
</ul>
</div>
</section>
);
}
export default Quiz;
Quiz.propTypes = {
alt: PropTypes.string.isRequired,
answer: PropTypes.string.isRequired,
answerOptions: PropTypes.array.isRequired,
question: PropTypes.string.isRequired,
questionId: PropTypes.number.isRequired,
questionTotal: PropTypes.number.isRequired,
onAnswerSelected: PropTypes.func.isRequired
}; |
#Boa:Frame:PlotFrame
import wx
import sys
import os
sys.path.append(os.getenv("PAPARAZZI_HOME") + "/sw/lib/python")
from settings_tool import IvySettingsInterface
def create(parent, ac_ids):
return SettingsFrame(parent, ac_ids)
SLIDER_ID_OFFSET = 250000
BUTTON_ID_OFFSET = 2 * 250000
SLIDER_FACTOR = 100
# Wraps TextCtrl to provide added functionality
class TextCtrlSetting(wx.TextCtrl):
update_callback = None
def __init__(self, parent, setting):
self.setting = setting
wx.TextCtrl.__init__(self, parent=parent, name=setting.shortname, id=setting.index)
self.Bind(wx.EVT_TEXT, self.onEvtText, self)
def RegisterUpdateCallback(self, cb):
self.update_callback = cb
def onEvtText(self, event):
index = int(self.GetId())
try:
value = float(self.GetValue())
self.update_callback(index, value)
except:
return
# helper function to toggle edit box boldness (bold = user-set, normal=downlink-received)
def setBold(self, bold):
font = self.GetFont()
if (bold):
font.SetWeight(wx.FONTWEIGHT_BOLD)
else:
font.SetWeight(wx.FONTWEIGHT_NORMAL)
self.SetFont(font)
def SetSettingValue(self, value):
if (self.setting.step < 1):
self.SetValue("%.2f" % float(value))
else:
self.SetValue("%i" % int(float(value)))
# Wraps slider
class SettingCtrl(wx.Slider):
update_callback = None
def __init__(self, parent, setting):
self.setting = setting
max_v = int(setting.max_value) * SLIDER_FACTOR
min_v = int(setting.min_value) * SLIDER_FACTOR
if (min_v >= max_v):
max_v = max_v + 1
wx.Slider.__init__(self, parent=parent, minValue=min_v, maxValue=max_v, style=wx.SL_HORIZONTAL | wx.SL_AUTOTICKS, size=(200, 30), id=setting.index + SLIDER_ID_OFFSET)
self.SetLineSize(setting.step * SLIDER_FACTOR)
self.Bind(wx.EVT_MOUSEWHEEL, self.sliderWheel, self)
self.Bind(wx.EVT_SLIDER, self.OnEvtSlider, self)
def RegisterUpdateCallback(self, cb):
self.update_callback = cb
def OnEvtSlider(self, event):
slider = event.GetEventObject()
self.update_callback(slider.GetSettingIndex(), slider.GetSettingValue())
# Called on mouse wheel events (default handler seems backwards?)
def sliderWheel(self, event):
slider = event.GetEventObject()
if (event.GetWheelRotation() > 0):
slider.SetValue(slider.GetValue() + slider.GetLineSize())
else:
slider.SetValue(slider.GetValue() - slider.GetLineSize())
self.update_callback(slider.GetSettingIndex(), slider.GetSettingValue())
def GetSettingIndex(self):
index = int(self.GetId())
if index >= SLIDER_ID_OFFSET:
index = index - SLIDER_ID_OFFSET
return index
def SetSettingValue(self, value):
self.SetValue(int(float(value)) * SLIDER_FACTOR)
def GetSettingValue(self):
if (self.setting.step < 1):
return float(self.GetValue()) / SLIDER_FACTOR
else:
return int(self.GetValue()) / SLIDER_FACTOR
class SettingsFrame(wx.Frame):
edits = []
sliders = []
def __init__(self, parent, ac_ids):
self.settings = IvySettingsInterface(ac_ids)
title = "Settings %s (%s)" % (ac_ids, self.settings.GetACName())
wx.Frame.__init__(self, name=u'SettingsFrame', parent=parent, title=title, size=(480, 320))
self.book = wx.Notebook(self)
self.updates = []
self.Bind( wx.EVT_CLOSE, self.OnClose)
for setting_group in self.settings.groups:
page = wx.Panel(self.book)
vert_box = wx.BoxSizer(orient=wx.VERTICAL)
for setting in setting_group.member_list:
horz_box = wx.BoxSizer(orient=wx.HORIZONTAL)
text = wx.StaticText(page, label=setting.shortname, size=(100,30))
# Edit
edit = TextCtrlSetting(page, setting)
edit.RegisterUpdateCallback(self.editUpdate)
self.edits.append(edit)
# Slider
slider = SettingCtrl(page, setting)
slider.RegisterUpdateCallback(self.updateEditFromSlider)
self.sliders.append(slider)
# Button
button = wx.Button(page, id=setting.index + BUTTON_ID_OFFSET, label="Apply")
self.Bind(wx.EVT_BUTTON, self.onButton)
horz_box.AddWindow(text)
horz_box.AddWindow(edit)
horz_box.AddWindow(slider)
horz_box.AddWindow(button)
vert_box.AddWindow(horz_box)
page.SetSizer(vert_box)
self.book.AddPage(page, setting_group.name)
self.settings.RegisterCallback(self.onUpdate)
# Copy slider value into associated edit box
def updateEditFromSlider(self, index, value):
self.edits[index].ChangeValue(str(value))
self.edits[index].setBold(True)
# Called on edit box update
def editUpdate(self, index, value):
self.sliders[index].SetSettingValue(value)
self.edits[index].setBold(True)
# Called on button push
def onButton(self, event):
button = event.GetEventObject()
index = int(button.GetId())
if index >= BUTTON_ID_OFFSET:
index = index - BUTTON_ID_OFFSET
self.settings.lookup[index].value = self.sliders[index].GetSettingValue()
self.settings.SendSetting(index)
# Called for remote settings updates
def onUpdate(self, index, value, fromRemote):
# Schedule the call for later via wx (run after events)
# to prevent crashy crashy
wx.CallAfter(self.update_value, index, value, fromRemote)
# Called to update GUI with new values
def update_value(self, index, value, fromRemote):
editCtrl = self.edits[index]
if fromRemote and editCtrl.FindFocus() == editCtrl:
# don't process remote updates if the control is focused
return
editCtrl.SetSettingValue(value)
editCtrl.setBold(not fromRemote)
self.sliders[index].SetSettingValue(value)
def OnClose(self, event):
# need to forward close to canvas so that ivy is shut down, otherwise ivy hangs the shutdown
self.settings.OnClose()
self.Destroy() |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pokemon Cards</title>
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;500;700&display=swap" rel="stylesheet">
<script defer src="main.js"></script>
</head>
<body>
<div class="background-wrapper">
<nav>
<div class="logo"><a href="#">PokemonCards</a></div>
<div class="hamburger-menu">
<i class="fa-solid fa-bars-staggered" id="menu-open"></i>
<i class="fa-solid fa-xmark" id="menu-close"></i>
</div>
<div class="nav-links">
<ul>
<li><a class="active" href="#">Home</a></li>
<li><a href="./productpagina.html">Products</a></li>
<li><a href="">Contact us</a></li>
<li><a href="./loginpagina.html">Login</a></li>
<li><a href=""><i class="fa-solid fa-cart-shopping"><span id="counter">1</span></i></a></li>
</ul>
</div>
</nav>
<script>
const menuClose = document.getElementById("menu-close")
const menuOpen = document.getElementById("menu-open")
const navLinks = document.querySelector(".nav-links")
menuOpen.addEventListener('click',()=>{
navLinks.classList.toggle('open')
menuOpen.classList.toggle('iconWeg')
menuClose.classList.toggle('show')
})
menuClose.addEventListener('click', () => {
navLinks.classList.toggle('open')
menuClose.classList.toggle('show')
menuOpen.classList.toggle('iconWeg')
})
</script>
<main>
<div class="main-container">
<div class="title">
<h1>Unleash Your Inner Trainer with Every Card!</h1>
<p>Discover a world of adventure, strategy, and nostalgia as you embark on your Pokémon journey with our premium selection of cards. <span>Catch 'em all, one card at a time!</span></p>
<button class="button-primary" role="button"><a href="./productpagina.html">Buy Now !</a></button>
</div>
<div class="main-img">
<img class="first-img" src="/assets/en_US-HGSS4-094-gengar.webp" alt="">
<img class="second-img" src="/assets/gengar-lv.x-arceus-ar-97.webp" alt="">
</div>
</div>
</main>
</div>
<div class="showcase-wrapper">
<article class="showcase-product">
<div class="showcase-container">
<div class="showcase-text">
<h2 class="showcase-title">Limited-Time Flash Sale: Grab Your Deal Now!</h2>
<p>We unveil some of the most captivating and powerful Pokémon cards from the vast world of Pokémon TCG (Trading Card Game). These cards are not just collectibles; they are a testament to the rich lore, stunning artwork, and strategic depth that make Pokémon TCG an enduring and beloved game for trainers of all ages.</p>
<a href="./productpagina.html"><button class="showcase-button">Uncover More</button></a>
</div>
<div class="showcase-img">
<img src="./assets/en_US-Promo_BW-BW45-mewtwo_ex.webp" alt="">
</div>
</div>
</article>
</div>
<div class="review">
<h2>Recent Customer Reviews.</h2>
<div class="review-card">
<div class="review-rating">
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<span class="review-number">5.0</span>
</div>
<h3 class="review-summary">Top-Notch Pokémon Card Retailer</h3>
<p class="review-message">"This company is a Pokémon card collector's dream come true. Their extensive selection and quality service make them my go-to for all things Pokémon."</p>
<div class="review-location">
<i class="fa-solid fa-location-dot"></i>
<p class="review-location">New York City, USA | August 8, 2023</p>
</div>
</div>
<div class="review-card">
<div class="review-rating">
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<span class="review-number">5.0</span>
</div>
<h3 class="review-summary">Exceptional Customer Care</h3>
<p class="review-message">"I had a small issue with my order, but the company's customer support team went above and beyond to resolve it quickly. Great service!"</p>
<div class="review-location">
<i class="fa-solid fa-location-dot"></i>
<p class="review-location">London, UK | September 5, 2023</p>
</div>
</div>
<div class="review-card">
<div class="review-rating">
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star-half"></i>
<span class="review-number">4.5</span>
</div>
<h3 class="review-summary">Rare Finds Galore!</h3>
<p class="review-message">"I can't believe the rare Pokémon cards I've stumbled upon from this company. It's like a treasure trove for collectors, and their prices are fair."</p>
<div class="review-location">
<i class="fa-solid fa-location-dot"></i>
<p class="review-location">Tokyo, Japan | June 17, 2022</p>
</div>
</div>
<div class="review-card">
<div class="review-rating">
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<span class="review-number">4.0</span>
</div>
<h3 class="review-summary">Pokémon Card Paradise</h3>
<p class="review-message">"Every time I visit their store, I feel like a kid in a candy shop. They have cards from all generations, and it's a must-visit for any Pokémon enthusiast."</p>
<div class="review-location">
<i class="fa-solid fa-location-dot"></i>
<p class="review-location">Djoppenbiek, Belgium | September 28, 2022</p>
</div>
</div>
<div class="review-card">
<div class="review-rating">
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<i class="fa-solid fa-star"></i>
<span class="review-number">5.0</span>
</div>
<h3 class="review-summary">Reliable and Trustworthy</h3>
<p class="review-message">"I've been buying Pokémon cards from this company for years, and they've never let me down. Authentic cards and speedy delivery every time."</p>
<div class="review-location">
<i class="fa-solid fa-location-dot"></i>
<p class="review-location">Sydney, Australia | April 12, 2023</p>
</div>
</div>
</div>
<footer class="footer">
<div class="footer-socials">
<h4>PokemonCards inc.</h4>
<div class="socials">
<a href=""><i class="fa-brands fa-square-x-twitter"></i></a>
<a href=""><i class="fa-brands fa-square-instagram"></i></a>
<a href=""><i class="fa-brands fa-square-snapchat"></i></a>
<a href=""><i class="fa-brands fa-square-facebook"></i></a>
<a href=""><i class="fa-brands fa-linkedin"></i></a>
</div>
<p>PokemonCards 2023. All Rights Reserved.</p>
</div>
<div class="footer-links">
<ul class="list-column">
<li class="list-title">Company.</li>
<li class="list-link"><a href="">Advertise</a></li>
<li class="list-link"><a href="">World Data</a></li>
<li class="list-link"><a href="">Blog</a></li>
</ul>
<ul class="list-column">
<li class="list-title">Help center.</li>
<li class="list-link"><a href="">FAQ</a></li>
<li class="list-link"><a href="">Careers</a></li>
<li class="list-link"><a href="">Contact us</a></li>
</ul>
<ul class="list-column">
<li class="list-title">Legal.</li>
<li class="list-link"><a href="">Privacy Policy</a></li>
<li class="list-link"><a href="">Terms & Conditions</a></li>
</ul>
</div>
</footer>
</body>
</html> |
<?php
namespace App\Http\Controllers\Student;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class StudentLoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::STUDENT_HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest:student')->except('logout');
}
public function showLoginForm(){
return view('student.login');
}
// public function login(Request $request)
// {
// $this->validate($request,[
// 'email'=>['required','string','email'],
// 'password'=>['required','string','min:4']
// ]);
// if(Auth::guard('teacher')->attempt(
// ['email'=>$request->email,
// 'password'=>$request->password],
// $request->remember)){
// redirect()->route('teacher.home');
// }
// return redirect()->back()->withInput($request->except('password'));
// }
public function logout(Request $request)
{
Auth::guard('student')->logout();
return redirect()->route('/');
}
} |
;; (define (for-each proc items)
;; (define (for-iter i item)
;; (if (null? item)
;; true
;; (for-iter (proc (car item)) (cdr item))))
;; (for-iter '() items))
(define (for-each proc items)
(if (not (null? items))
(proc (car items)))
(if (null? items)
true
(for-each proc (cdr items))))
;; (define (for-each proc items)
;; (let ((items-cdr (cdr items)))
;; (proc (car items))
;; (if (not (null? items-cdr))
;; (for-each proc items-cdr)
;; true))) |
# _api_parser.py
# Internal parsing function for the Scrutiny server API messages
#
# - License : MIT - See LICENSE file.
# - Project : Scrutiny Debugger (github.com/scrutinydebugger/scrutiny-python)
#
# Copyright (c) 2021-2023 Scrutiny Debugger
import scrutiny.sdk
import scrutiny.sdk.datalogging
sdk = scrutiny.sdk # Workaround for vscode linter an submodule on alias
from scrutiny.core.basic_types import *
from scrutiny.core.firmware_description import MetadataType as FirmwareMetadataDict
from scrutiny.server.api.API import API
from scrutiny.server.api import typing as api_typing
from dataclasses import dataclass
from datetime import datetime
from base64 import b64decode
import binascii
import time
from typing import List, Dict, Optional, Any, cast, Literal, Type, Union, TypeVar, Iterable, get_args
@dataclass(frozen=True)
class WatchableConfiguration:
watchable_type: sdk.WatchableType
datatype: EmbeddedDataType
server_id: str
@dataclass(frozen=True)
class WatchableUpdate:
server_id: str
value: Union[bool, int, float]
@dataclass(frozen=True)
class WriteCompletion:
request_token: str
watchable: str
success: bool
timestamp: datetime
batch_index: int
@dataclass(frozen=True)
class WriteConfirmation:
request_token: str
count: int
@dataclass(frozen=True)
class MemoryReadCompletion:
request_token: str
success: bool
data: Optional[bytes]
error: str
timestamp: float
@dataclass(frozen=True)
class MemoryWriteCompletion:
request_token: str
success: bool
error: str
timestamp: float
@dataclass(frozen=True)
class DataloggingCompletion:
request_token: str
reference_id: Optional[str]
success: bool
detail_msg: str
T = TypeVar('T', str, int, float, bool)
def _check_response_dict(cmd: str, d: Any, name: str, types: Union[Type, Iterable[Type]], previous_parts: str = '') -> None:
if isinstance(types, type):
types = tuple([types])
else:
types = tuple(types)
parts = name.split('.')
key = parts[0]
if not key:
return
if previous_parts:
part_name = f"{previous_parts}.{key}"
else:
part_name = key
next_parts = parts[1:]
if key not in d:
raise sdk.exceptions.BadResponseError(f'Missing field {part_name} in message "{cmd}"')
if len(next_parts) > 0:
if not isinstance(d, dict):
raise sdk.exceptions.BadResponseError(f'Field {part_name} is expected to be a dictionary in message "{cmd}"')
_check_response_dict(cmd, d[key], '.'.join(next_parts), types, part_name)
else:
if not isinstance(d[key], types):
gotten_type = d[key].__class__.__name__
typename = "(%s)" % ', '.join([t.__name__ for t in types])
raise sdk.exceptions.BadResponseError(
f'Field {part_name} is expected to be of type "{typename}" but found "{gotten_type}" in message "{cmd}"')
def _fetch_dict_val(d: Any, path: str, wanted_type: Type[T], default: Optional[T], allow_none=True) -> Optional[T]:
if d is None:
return default
assert isinstance(d, dict)
parts = path.split('.')
key = parts[0]
next_parts = parts[1:]
if not key:
raise RuntimeError('Empty path to fetch from dict')
if key not in d:
return default
if len(next_parts) == 0:
if d[key] is None:
if allow_none:
return None
raise sdk.exceptions.BadResponseError(f'Field {key} cannot be None')
return wanted_type(d[key])
else:
return _fetch_dict_val(d[key], '.'.join(next_parts), wanted_type=wanted_type, default=default)
def _fetch_dict_val_no_none(d: Any, path: str, wanted_type: Type[T], default: T) -> T:
return cast(T, _fetch_dict_val(d, path, wanted_type, default, allow_none=False))
def _read_sfd_metadata_from_incomplete_dict(obj: Optional[FirmwareMetadataDict]) -> Optional[sdk.SFDMetadata]:
if obj is None:
return None
try:
timestamp = _fetch_dict_val(obj, 'generation_info.time', int, None)
except (TypeError, ValueError):
timestamp = None
return sdk.SFDMetadata(
author=_fetch_dict_val(obj, 'author', str, None),
project_name=_fetch_dict_val(obj, 'project_name', str, None),
version=_fetch_dict_val(obj, 'version', str, None),
generation_info=sdk.SFDGenerationInfo(
python_version=_fetch_dict_val(obj, 'generation_info.python_version', str, None),
scrutiny_version=_fetch_dict_val(obj, 'generation_info.scrutiny_version', str, None),
system_type=_fetch_dict_val(obj, 'generation_info.system_type', str, None),
timestamp=datetime.fromtimestamp(timestamp) if timestamp is not None else None
)
)
def parse_get_watchable_single_element(response: api_typing.S2C.GetWatchableList, requested_path: str) -> WatchableConfiguration:
"""Parse a response to get_watchable_list and assume the request was for a single watchable"""
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.GET_WATCHABLE_LIST_RESPONSE
_check_response_dict(cmd, response, 'qty.alias', int)
_check_response_dict(cmd, response, 'qty.rpv', int)
_check_response_dict(cmd, response, 'qty.var', int)
_check_response_dict(cmd, response, 'done', bool)
total = response['qty']['alias'] + response['qty']['rpv'] + response['qty']['var']
if total == 0:
raise sdk.exceptions.NameNotFoundError(f'No watchable element matches the path {requested_path} on the server')
if total > 1:
raise sdk.exceptions.BadResponseError(f"More than one item were returned by the server that matched the path {requested_path}")
if response['done'] != True:
raise sdk.exceptions.BadResponseError(f"done field should be True")
_check_response_dict(cmd, response, 'content.alias', list)
_check_response_dict(cmd, response, 'content.rpv', list)
_check_response_dict(cmd, response, 'content.var', list)
watchable_type: sdk.WatchableType = sdk.WatchableType.NA
content: Any = None
WatchableTypeKey = Literal['rpv', 'alias', 'var']
typekey: WatchableTypeKey
if response['qty']['alias'] == 1:
watchable_type = sdk.WatchableType.Alias
typekey = 'alias'
elif response['qty']['rpv']:
watchable_type = sdk.WatchableType.RuntimePublishedValue
content = response['content']['rpv']
typekey = 'rpv'
elif response['qty']['var']:
watchable_type = sdk.WatchableType.Variable
typekey = 'var'
else:
raise sdk.exceptions.BadResponseError('Unknown watchable type')
key: WatchableTypeKey
for key in get_args(WatchableTypeKey):
expected_count = 1 if key == typekey else 0
if len(response['content'][key]) != expected_count:
raise sdk.exceptions.BadResponseError("Incoherent element quantity in API response.")
content = cast(dict, response['content'][typekey][0])
keyprefix = f'content.{typekey}[0]'
_check_response_dict(cmd, content, 'id', str, keyprefix)
_check_response_dict(cmd, content, 'display_path', str, keyprefix)
_check_response_dict(cmd, content, 'datatype', str, keyprefix)
if content['datatype'] not in API.APISTR_2_DATATYPE:
raise sdk.exceptions.BadResponseError(f"Unknown datatype {content['datatype']}")
datatype = EmbeddedDataType(API.APISTR_2_DATATYPE[content['datatype']])
if requested_path != content['display_path']:
raise sdk.exceptions.BadResponseError(
f"The display path of the element returned by the server does not matched the requested path. Got {content['display_path']} but expected {requested_path}")
if not isinstance(content['id'], str):
raise sdk.exceptions.BadResponseError(f"Invalid server id received for watchable {requested_path}")
return WatchableConfiguration(
watchable_type=watchable_type,
datatype=datatype,
server_id=content['id']
)
def parse_subscribe_watchable_response(response: api_typing.S2C.SubscribeWatchable) -> Dict[str, WatchableConfiguration]:
"""Parse a response to get_watchable_list and assume the request was for a single watchable"""
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.SUBSCRIBE_WATCHABLE_RESPONSE
outdict: Dict[str, WatchableConfiguration] = {}
_check_response_dict(cmd, response, 'subscribed', dict)
for k, v in response['subscribed'].items():
if not isinstance(k, str):
raise sdk.exceptions.BadResponseError('Gotten a subscription dict with invalid key')
_check_response_dict(cmd, v, 'datatype', str)
_check_response_dict(cmd, v, 'type', str)
_check_response_dict(cmd, v, 'id', str)
if v['datatype'] not in API.APISTR_2_DATATYPE:
raise sdk.exceptions.BadResponseError(f"Unknown datatype {v['datatype']}")
datatype = EmbeddedDataType(API.APISTR_2_DATATYPE[v['datatype']])
if v['type'] == 'alias':
watchable_type = sdk.WatchableType.Alias
elif v['type'] == 'var':
watchable_type = sdk.WatchableType.Variable
elif v['type'] == 'rpv':
watchable_type = sdk.WatchableType.RuntimePublishedValue
else:
raise sdk.exceptions.BadResponseError(f"Unsupported watchable type {v['type']}")
outdict[k] = WatchableConfiguration(
watchable_type=watchable_type,
datatype=datatype,
server_id=v['id']
)
return outdict
def parse_inform_server_status(response: api_typing.S2C.InformServerStatus) -> sdk.ServerInfo:
"""Parse the inform_server_status message"""
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.INFORM_SERVER_STATUS
NoneType: Type = type(None)
_check_response_dict(cmd, response, 'device_status', str)
_check_response_dict(cmd, response, 'device_session_id', (str, NoneType))
def _device_status_from_api(api_val: api_typing.DeviceCommStatus) -> sdk.DeviceCommState:
if api_val == API.DeviceCommStatus.UNKNOWN:
return sdk.DeviceCommState.NA
if api_val == API.DeviceCommStatus.DISCONNECTED:
return sdk.DeviceCommState.Disconnected
if api_val == API.DeviceCommStatus.CONNECTING:
return sdk.DeviceCommState.Connecting
if api_val == API.DeviceCommStatus.CONNECTED:
return sdk.DeviceCommState.Connecting # This is not a mistake Connected->Connecting, for sdk simplicity
if api_val == API.DeviceCommStatus.CONNECTED_READY:
return sdk.DeviceCommState.ConnectedReady
raise sdk.exceptions.BadResponseError('Unsupported device communication status "{api_val}"')
_check_response_dict(cmd, response, 'device_info', (dict, NoneType))
device_info: Optional[sdk.DeviceInfo] = None
if isinstance(response['device_info'], dict):
_check_response_dict(cmd, response, 'device_info.device_id', str)
_check_response_dict(cmd, response, 'device_info.display_name', str)
_check_response_dict(cmd, response, 'device_info.max_tx_data_size', int)
_check_response_dict(cmd, response, 'device_info.max_rx_data_size', int)
_check_response_dict(cmd, response, 'device_info.max_bitrate_bps', (int, type(None)))
_check_response_dict(cmd, response, 'device_info.rx_timeout_us', int)
_check_response_dict(cmd, response, 'device_info.heartbeat_timeout_us', int)
_check_response_dict(cmd, response, 'device_info.address_size_bits', int)
_check_response_dict(cmd, response, 'device_info.protocol_major', int)
_check_response_dict(cmd, response, 'device_info.protocol_minor', int)
_check_response_dict(cmd, response, 'device_info.supported_feature_map.memory_write', bool)
_check_response_dict(cmd, response, 'device_info.supported_feature_map.datalogging', bool)
_check_response_dict(cmd, response, 'device_info.supported_feature_map.user_command', bool)
_check_response_dict(cmd, response, 'device_info.supported_feature_map._64bits', bool)
_check_response_dict(cmd, response, 'device_info.forbidden_memory_regions', list)
_check_response_dict(cmd, response, 'device_info.readonly_memory_regions', list)
forbidden_regions: List[sdk.MemoryRegion] = []
for region in response['device_info']['forbidden_memory_regions']:
_check_response_dict(cmd, region, 'start', int)
_check_response_dict(cmd, region, 'end', int)
if region['end'] <= region['start']:
raise sdk.exceptions.BadResponseError(f'Received a forbidden memory region with incoherent start and end in message "{cmd}"')
size = region['end'] - region['start'] + 1
if size <= 0:
raise sdk.exceptions.BadResponseError(f'Got a forbidden memory region with an invalid size "{cmd}"')
forbidden_regions.append(sdk.MemoryRegion(
start=region['start'],
size=size
))
readonly_regions: List[sdk.MemoryRegion] = []
for region in response['device_info']['readonly_memory_regions']:
_check_response_dict(cmd, region, 'start', int)
_check_response_dict(cmd, region, 'end', int)
if region['end'] <= region['start']:
raise sdk.exceptions.BadResponseError(f'Received a readonly memory region with incoherent start and end in message "{cmd}"')
size = region['end'] - region['start'] + 1
if size <= 0:
raise sdk.exceptions.BadResponseError(f'Got a readonly memory region with an invalid size "{cmd}"')
readonly_regions.append(sdk.MemoryRegion(
start=region['start'],
size=size
))
if response['device_info']['address_size_bits'] not in get_args(sdk.AddressSize):
raise sdk.exceptions.BadResponseError(f"Unexpected address size {response['device_info']['address_size_bits']}")
device_info = sdk.DeviceInfo(
device_id=response['device_info']['device_id'],
display_name=response['device_info']['display_name'],
max_tx_data_size=response['device_info']['max_tx_data_size'],
max_rx_data_size=response['device_info']['max_rx_data_size'],
max_bitrate_bps=response['device_info']['max_bitrate_bps'],
rx_timeout_us=response['device_info']['rx_timeout_us'],
heartbeat_timeout=float(response['device_info']['heartbeat_timeout_us']) * 1e-6,
address_size_bits=cast(sdk.AddressSize, response['device_info']['address_size_bits']),
protocol_major=response['device_info']['protocol_major'],
protocol_minor=response['device_info']['protocol_minor'],
supported_features=sdk.SupportedFeatureMap(
memory_write=response['device_info']['supported_feature_map']['memory_write'],
datalogging=response['device_info']['supported_feature_map']['datalogging'],
user_command=response['device_info']['supported_feature_map']['user_command'],
sixtyfour_bits=response['device_info']['supported_feature_map']['_64bits'],
),
forbidden_memory_regions=forbidden_regions,
readonly_memory_regions=readonly_regions
)
sfd: Optional[sdk.SFDInfo] = None
if response['loaded_sfd'] is not None:
_check_response_dict(cmd, response, 'loaded_sfd.firmware_id', str)
_check_response_dict(cmd, response, 'loaded_sfd.metadata', dict)
sfd = sdk.SFDInfo(
firmware_id=response['loaded_sfd']['firmware_id'],
metadata=_read_sfd_metadata_from_incomplete_dict(response['loaded_sfd']['metadata'])
)
_check_response_dict(cmd, response, 'device_datalogging_status.datalogger_state', str)
_check_response_dict(cmd, response, 'device_datalogging_status.completion_ratio', [NoneType, float])
def _datalogging_status(api_val: api_typing.DataloggerState) -> sdk.DataloggerState:
if api_val == API.DataloggingStatus.UNAVAILABLE:
return sdk.DataloggerState.NA
elif api_val == API.DataloggingStatus.STANDBY:
return sdk.DataloggerState.Standby
elif api_val == API.DataloggingStatus.WAITING_FOR_TRIGGER:
return sdk.DataloggerState.WaitForTrigger
elif api_val == API.DataloggingStatus.ACQUIRING:
return sdk.DataloggerState.Acquiring
elif api_val == API.DataloggingStatus.DATA_READY:
return sdk.DataloggerState.DataReady
elif api_val == API.DataloggingStatus.ERROR:
return sdk.DataloggerState.Error
raise sdk.exceptions.BadResponseError('Unsupported datalogger state "{api_val}"')
datalogging = sdk.DataloggingInfo(
completion_ratio=response['device_datalogging_status']['completion_ratio'],
state=_datalogging_status(response['device_datalogging_status']['datalogger_state'])
)
def _link_type(api_val: api_typing.LinkType) -> sdk.DeviceLinkType:
if api_val == 'none':
return sdk.DeviceLinkType.NA
if api_val == 'serial':
return sdk.DeviceLinkType.Serial
if api_val == 'dummy':
return sdk.DeviceLinkType._Dummy
if api_val == 'thread_safe_dummy':
return sdk.DeviceLinkType._DummyThreadSafe
if api_val == 'udp':
return sdk.DeviceLinkType.UDP
raise sdk.exceptions.BadResponseError('Unsupported device link type "{api_val}"')
link_type = _link_type(response['device_comm_link']['link_type'])
link_config: Optional[sdk.SupportedLinkConfig]
if link_type == sdk.DeviceLinkType.NA:
link_config = None
elif link_type == sdk.DeviceLinkType.UDP:
udp_config = cast(api_typing.UdpLinkConfig, response['device_comm_link']['link_config'])
_check_response_dict(cmd, response, 'device_comm_link.link_config.host', str)
_check_response_dict(cmd, response, 'device_comm_link.link_config.port', int)
link_config = sdk.UDPLinkConfig(
host=udp_config['host'],
port=udp_config['port'],
)
elif link_type == sdk.DeviceLinkType.Serial:
serial_config = cast(api_typing.SerialLinkConfig, response['device_comm_link']['link_config'])
_check_response_dict(cmd, response, 'device_comm_link.link_config.portname', str)
_check_response_dict(cmd, response, 'device_comm_link.link_config.baudrate', int)
_check_response_dict(cmd, response, 'device_comm_link.link_config.stopbits', str)
_check_response_dict(cmd, response, 'device_comm_link.link_config.databits', int)
_check_response_dict(cmd, response, 'device_comm_link.link_config.parity', str)
api_stopbits = serial_config['stopbits']
if api_stopbits not in ('1', '1.5', '2'):
raise sdk.exceptions.BadResponseError(f'Unsupported stop bit value "{api_stopbits}" in message {cmd}')
api_parity = serial_config['parity']
if api_parity not in ('none', 'even', 'odd', 'mark', 'space'):
raise sdk.exceptions.BadResponseError(f'Unsupported parity value "{api_parity}" in message {cmd}')
api_databits = serial_config['databits']
if api_databits not in (5, 6, 7, 8):
raise sdk.exceptions.BadResponseError(f'Unsupported number of databits value "{api_databits}" in message {cmd}')
link_config = sdk.SerialLinkConfig(
port=serial_config['portname'],
baudrate=serial_config['baudrate'],
stopbits=cast(sdk.SerialStopBits, api_stopbits),
parity=cast(sdk.SerialParity, api_parity),
databits=cast(sdk.SerialDataBits, api_databits)
)
else:
raise RuntimeError('Unsupported device link type "{link_type}"')
_check_response_dict(cmd, response, 'device_comm_link.link_type', str)
device_link = sdk.DeviceLinkInfo(
type=link_type,
config=link_config
)
return sdk.ServerInfo(
device_comm_state=_device_status_from_api(response['device_status']),
device_session_id=response['device_session_id'],
datalogging=datalogging,
device=device_info,
sfd=sfd,
device_link=device_link
)
def parse_watchable_update(response: api_typing.S2C.WatchableUpdate) -> List[WatchableUpdate]:
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.WATCHABLE_UPDATE
outlist: List[WatchableUpdate] = []
_check_response_dict(cmd, response, 'updates', list)
for element in response['updates']:
_check_response_dict(cmd, element, 'id', str)
_check_response_dict(cmd, element, 'value', [float, int, bool])
outlist.append(WatchableUpdate(
server_id=element['id'],
value=element['value'],
))
return outlist
def parse_write_value_response(response: api_typing.S2C.WriteValue) -> WriteConfirmation:
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.WRITE_WATCHABLE_RESPONSE
_check_response_dict(cmd, response, 'request_token', str)
_check_response_dict(cmd, response, 'count', int)
return WriteConfirmation(
request_token=response['request_token'],
count=response['count']
)
def parse_write_completion(response: api_typing.S2C.WriteCompletion) -> WriteCompletion:
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.INFORM_WRITE_COMPLETION
_check_response_dict(cmd, response, 'watchable', str)
_check_response_dict(cmd, response, 'success', bool)
_check_response_dict(cmd, response, 'request_token', str)
_check_response_dict(cmd, response, 'timestamp', float)
_check_response_dict(cmd, response, 'batch_index', int)
return WriteCompletion(
request_token=response['request_token'],
watchable=response['watchable'],
success=response['success'],
timestamp=datetime.fromtimestamp(response['timestamp']),
batch_index=response['batch_index']
)
def parse_get_installed_sfds_response(response: api_typing.S2C.GetInstalledSFD) -> Dict[str, sdk.SFDInfo]:
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.GET_INSTALLED_SFD_RESPONSE
output: Dict[str, sdk.SFDInfo] = {}
_check_response_dict(cmd, response, 'sfd_list', dict)
for firmware_id, sfd_content in response['sfd_list'].items():
timestamp = _fetch_dict_val(sfd_content, 'generation_info.time', int, None)
metadata = sdk.SFDMetadata(
author=_fetch_dict_val(sfd_content, 'author', str, None),
project_name=_fetch_dict_val(sfd_content, 'project_name', str, None),
version=_fetch_dict_val(sfd_content, 'version', str, None),
generation_info=sdk.SFDGenerationInfo(
python_version=_fetch_dict_val(sfd_content, 'generation_info.python_version', str, None),
scrutiny_version=_fetch_dict_val(sfd_content, 'generation_info.scrutiny_version', str, None),
system_type=_fetch_dict_val(sfd_content, 'generation_info.system_type', str, None),
timestamp=datetime.fromtimestamp(timestamp) if timestamp is not None else None
)
)
output[firmware_id] = sdk.SFDInfo(
firmware_id=firmware_id,
metadata=metadata
)
return output
def parse_memory_read_completion(response: api_typing.S2C.ReadMemoryComplete) -> MemoryReadCompletion:
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.INFORM_MEMORY_READ_COMPLETE
_check_response_dict(cmd, response, 'request_token', str)
_check_response_dict(cmd, response, 'success', bool)
success = _fetch_dict_val_no_none(response, 'success', bool, False)
data_bin: Optional[bytes] = None
if success:
data = _fetch_dict_val_no_none(response, 'data', str, "")
try:
data_bin = b64decode(data, validate=True)
except binascii.Error as e:
raise sdk.exceptions.BadResponseError(f"Server returned a invalid base64 data block. {e}")
detail_msg = _fetch_dict_val(response, 'detail_msg', str, "")
return MemoryReadCompletion(
request_token=_fetch_dict_val_no_none(response, 'request_token', str, ""),
success=success,
data=data_bin,
error=detail_msg if detail_msg is not None else "",
timestamp=time.time()
)
def parse_memory_write_completion(response: api_typing.S2C.WriteMemoryComplete) -> MemoryWriteCompletion:
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.INFORM_MEMORY_WRITE_COMPLETE
_check_response_dict(cmd, response, 'request_token', str)
_check_response_dict(cmd, response, 'success', bool)
detail_msg = _fetch_dict_val(response, 'detail_msg', str, "")
return MemoryWriteCompletion(
request_token=_fetch_dict_val_no_none(response, 'request_token', str, ""),
success=_fetch_dict_val_no_none(response, 'success', bool, False),
error=detail_msg if detail_msg is not None else "",
timestamp=time.time()
)
def parse_get_datalogging_capabilities_response(response: api_typing.S2C.GetDataloggingCapabilities) -> Optional[sdk.datalogging.DataloggingCapabilities]:
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.GET_DATALOGGING_CAPABILITIES_RESPONSE
_check_response_dict(cmd, response, 'available', bool)
_check_response_dict(cmd, response, 'capabilities', (dict, type(None)))
if response['capabilities'] is None or not response['available']:
return None
_check_response_dict(cmd, response, 'capabilities.buffer_size', int)
_check_response_dict(cmd, response, 'capabilities.encoding', str)
_check_response_dict(cmd, response, 'capabilities.max_nb_signal', int)
_check_response_dict(cmd, response, 'capabilities.sampling_rates', list)
api_to_sdk_encoding_map: Dict[api_typing.DataloggingEncoding, sdk.datalogging.DataloggingEncoding] = {
'raw': sdk.datalogging.DataloggingEncoding.RAW,
}
encoding = response['capabilities']['encoding']
if encoding not in api_to_sdk_encoding_map:
raise sdk.exceptions.BadResponseError(f'Datalogging encoding is not supported: "{encoding}"')
sampling_rates: List[sdk.datalogging.SamplingRate] = []
for rate_entry in response['capabilities']['sampling_rates']:
_check_response_dict(cmd, rate_entry, 'identifier', int)
_check_response_dict(cmd, rate_entry, 'name', str)
_check_response_dict(cmd, rate_entry, 'type', str)
rate: sdk.datalogging.SamplingRate
if rate_entry['type'] == 'fixed_freq':
_check_response_dict(cmd, rate_entry, 'frequency', (float, int))
assert rate_entry['frequency'] is not None
rate = sdk.datalogging.FixedFreqSamplingRate(
identifier=rate_entry['identifier'],
name=rate_entry['name'],
frequency=float(rate_entry['frequency']),
)
elif rate_entry['type'] == 'variable_freq':
rate = sdk.datalogging.VariableFreqSamplingRate(
identifier=rate_entry['identifier'],
name=rate_entry['name'],
)
else:
raise sdk.exceptions.BadResponseError(f'Unsupported sampling rate type: {rate_entry["type"]}')
sampling_rates.append(rate)
return sdk.datalogging.DataloggingCapabilities(
buffer_size=response['capabilities']['buffer_size'],
encoding=api_to_sdk_encoding_map[encoding],
max_nb_signal=response['capabilities']['max_nb_signal'],
sampling_rates=sampling_rates
)
def parse_read_datalogging_acquisition_content_response(response: api_typing.S2C.ReadDataloggingAcquisitionContent) -> sdk.datalogging.DataloggingAcquisition:
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.READ_DATALOGGING_ACQUISITION_CONTENT_RESPONSE
_check_response_dict(cmd, response, 'reference_id', str)
_check_response_dict(cmd, response, 'firmware_id', str)
_check_response_dict(cmd, response, 'firmware_name', (str, type(None)))
_check_response_dict(cmd, response, 'timestamp', float)
_check_response_dict(cmd, response, 'name', str)
_check_response_dict(cmd, response, 'trigger_index', (int, type(None)))
_check_response_dict(cmd, response, 'yaxes', list)
_check_response_dict(cmd, response, 'signals', list)
_check_response_dict(cmd, response, 'xdata.name', str)
_check_response_dict(cmd, response, 'xdata.data', list)
_check_response_dict(cmd, response, 'xdata.logged_element', str)
acquisition = sdk.datalogging.DataloggingAcquisition(
firmware_id=response['firmware_id'],
reference_id=response['reference_id'],
acq_time=datetime.fromtimestamp(response['timestamp']),
name=response['name'],
firmware_name=response['firmware_name']
)
axis_map: Dict[int, sdk.datalogging.AxisDefinition] = {}
for yaxis in response['yaxes']:
_check_response_dict(cmd, yaxis, 'id', int)
_check_response_dict(cmd, yaxis, 'name', str)
axis_map[yaxis['id']] = sdk.datalogging.AxisDefinition(axis_id=yaxis['id'], name=yaxis['name'])
xaxis_data: Optional[List[float]] = None
try:
xaxis_data = [float(x) for x in response['xdata']['data']]
except Exception:
raise sdk.exceptions.BadResponseError('X-Axis data is not all numerical')
assert xaxis_data is not None
for sig in response['signals']:
_check_response_dict(cmd, sig, 'axis_id', int)
_check_response_dict(cmd, sig, 'logged_element', str)
_check_response_dict(cmd, sig, 'name', str)
_check_response_dict(cmd, sig, 'data', list)
yaxis_data: Optional[List[float]] = None
try:
yaxis_data = [float(x) for x in sig['data']]
except Exception:
raise sdk.exceptions.BadResponseError(f'Dataseries {sig["name"]} data is not all numerical')
assert yaxis_data is not None
if sig['axis_id'] not in axis_map:
raise sdk.exceptions.BadResponseError(f'Dataseries {sig["name"]} refer to a non-existent Y-Axis')
ds = sdk.datalogging.DataSeries(
data=yaxis_data,
name=sig['name'],
logged_element=sig['logged_element']
)
acquisition.add_data(ds, axis=axis_map[sig['axis_id']])
xdata = sdk.datalogging.DataSeries(
data=response['xdata']['data'],
name=response['xdata']['name'],
logged_element=response['xdata']['logged_element']
)
acquisition.set_xdata(xdata)
try:
acquisition.set_trigger_index(response['trigger_index'])
except Exception:
raise sdk.exceptions.BadResponseError(f'Given Trigger index is not valid. {response["trigger_index"]}')
return acquisition
def parse_request_datalogging_acquisition_response(response: api_typing.S2C.RequestDataloggingAcquisition) -> str:
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.REQUEST_DATALOGGING_ACQUISITION_RESPONSE
_check_response_dict(cmd, response, 'request_token', str)
return response['request_token']
def parse_datalogging_acquisition_complete(response: api_typing.S2C.InformDataloggingAcquisitionComplete) -> DataloggingCompletion:
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.INFORM_DATALOGGING_ACQUISITION_COMPLETE
_check_response_dict(cmd, response, 'request_token', str)
_check_response_dict(cmd, response, 'reference_id', (str, type(None)))
_check_response_dict(cmd, response, 'success', bool)
_check_response_dict(cmd, response, 'detail_msg', str)
if response['success']:
if response['reference_id'] is None:
raise sdk.exceptions.BadResponseError("Missing reference ID for a successful acquisition")
return DataloggingCompletion(
request_token=response['request_token'],
reference_id=response['reference_id'],
detail_msg=response['detail_msg'],
success=response['success'],
)
def parse_list_datalogging_acquisitions_response(response: api_typing.S2C.ListDataloggingAcquisition) -> List[sdk.datalogging.DataloggingStorageEntry]:
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.LIST_DATALOGGING_ACQUISITION_RESPONSE
_check_response_dict(cmd, response, 'acquisitions', list)
dataout: List[sdk.datalogging.DataloggingStorageEntry] = []
for acq in response['acquisitions']:
_check_response_dict(cmd, acq, 'firmware_id', str)
_check_response_dict(cmd, acq, 'name', str)
_check_response_dict(cmd, acq, 'timestamp', float)
_check_response_dict(cmd, acq, 'reference_id', str)
_check_response_dict(cmd, acq, 'firmware_metadata', (dict, type(None)))
entry = sdk.datalogging.DataloggingStorageEntry(
firmware_id=acq['firmware_id'],
name=acq['name'] if acq['name'] is not None else '',
timestamp=datetime.fromtimestamp(acq['timestamp']),
reference_id=acq['reference_id'],
firmware_metadata=_read_sfd_metadata_from_incomplete_dict(acq['firmware_metadata'])
)
dataout.append(entry)
return dataout
def parse_user_command_response(response: api_typing.S2C.UserCommand) -> sdk.UserCommandResponse:
assert isinstance(response, dict)
assert 'cmd' in response
cmd = response['cmd']
assert cmd == API.Command.Api2Client.USER_COMMAND_RESPONSE
_check_response_dict(cmd, response, 'subfunction', int)
_check_response_dict(cmd, response, 'data', str)
if response['subfunction'] < 0 or response['subfunction'] > 0xFF:
raise sdk.exceptions.BadResponseError(f'Invalid subfunction {response["subfunction"]}')
try:
data = b64decode(response['data'], validate=True)
except binascii.Error as e:
raise sdk.exceptions.BadResponseError(f"Server returned a invalid base64 data block. {e}")
return sdk.UserCommandResponse(
subfunction=response['subfunction'],
data=data
) |
#pragma once
#include <cstring>
#include <iostream>
#include <fstream>
#include <cassert>
#include "Gb_types.h"
#define CARTRIDGE_MAX_SIZE 1024 * 1024 * 2
#define SIMPLE_BANKING_MODE 0x0
#define RAM_BANKING_MODE 0x1
class Gb_cartridge{
public:
// offsets in the cartridge header.
enum header{
HARDWARE_TYPE = 0x0147,
ROM_SIZE = 0x0148,
RAM_SIZE = 0x0149
};
enum hardware_type{
MBC1 = 0x1,
MBC1_RAM = 0x2,
MBC1_RAM_BATTERY = 0x3,
MBC2 = 0x5,
MBC2_BATTERY = 0x6
};
Gb_cartridge(const char * filename);
operator bool() const;
hardware_type hw_type() const;
int ram_size() const; // number of ram banks
int rom_size() const; // number of rom banks
/* reads from rom bank0 if addr <= 0x3fff or from the currently selected
* rom bank mapped to the 0x4000 - 0x7fff range.*/
BYTE read_rom(WORD addr);
/* reads from external ram in cartridge of min size 8kb max size 32kb,
* depending on the currently selected ram bank mapped to the 0xa000 - 0xbfff
* range, to perform this operation RAM must be enabled first.*/
BYTE read_ram(WORD addr);
/* writes to external ram in cartridge of min size 8kb max size 32kb,
* depending on the currently selected ram bank mapped to the 0xa000 - 0xbfff
* range, to perfom this operation RAM must be enabled first.*/
void write(WORD addr, BYTE value);
/* Intercepts any writes to the range 0x0000-0x7fff (READ ONLY) and intercepts
* the values according to the mbc type present on the cartridge.*/
void mbc_intercept(WORD addr, BYTE value);
void mbc1(unsigned short addr, unsigned char value);
private:
BYTE m_memory[CARTRIDGE_MAX_SIZE];
BYTE m_ram[0x8000]; // max ram, 32kb max
void load_rom(const char * filename);
bool m_mbc1 = false;
bool m_mbc2 = false;
bool m_ram_enabled = false;
int m_rom_banking_mode = 0;
int m_rombank_num = 1;
int m_rambank_num = 0;
}; |
package com.github.stanislavbukaevsky.patientrecordsystem.serialization.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.stanislavbukaevsky.patientrecordsystem.dto.FindByCardsResponseDto;
import com.github.stanislavbukaevsky.patientrecordsystem.dto.FindByDoctorsAndCardsResponseDto;
import com.github.stanislavbukaevsky.patientrecordsystem.dto.FindByTicketsResponseDto;
import com.github.stanislavbukaevsky.patientrecordsystem.exception.CardNotFoundException;
import com.github.stanislavbukaevsky.patientrecordsystem.serialization.FindSerialization;
import com.github.stanislavbukaevsky.patientrecordsystem.service.FindService;
import com.github.stanislavbukaevsky.patientrecordsystem.service.impl.FindByForeignKeyService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/**
* Класс для сериализации в JSON формат для поиска по внешнему ключу.
* Реализует интерфейс {@link FindSerialization}. Параметры: <br>
* {@link HttpServletRequest} - запрос пользователя <br>
* {@link HttpServletResponse} - ответ пользователю <br>
*/
public class FindByForeignKeySerialization implements FindSerialization<HttpServletRequest, HttpServletResponse> {
private final static FindByForeignKeySerialization INSTANCE = new FindByForeignKeySerialization();
private final FindService findService = FindByForeignKeyService.getInstance();
private final ObjectMapper objectMapper = new ObjectMapper();
private FindByForeignKeySerialization() {
}
public static FindByForeignKeySerialization getInstance() {
return INSTANCE;
}
/**
* Этот метод преобразует в JSON для получения всех запросов для поиска по внешнему ключу
*
* @param request запрос пользователя
* @param response ответ пользователю
* @throws IOException исключение ввода/вывода
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String answer = "";
try {
String uri = request.getRequestURI();
String[] findId = uri.split("/");
Long id = Long.parseLong(findId[3]);
if (uri.equals("/find/cards-patient/" + id)) {
List<FindByCardsResponseDto> cardsResponse = findService.findCardsByPatientId(id);
response.setStatus(HttpServletResponse.SC_OK);
answer = objectMapper.writeValueAsString(cardsResponse);
} else if (uri.equals("/find/tickets-doctor/" + id)) {
List<FindByTicketsResponseDto> ticketsResponse = findService.findTicketsByDoctorId(id);
response.setStatus(HttpServletResponse.SC_OK);
answer = objectMapper.writeValueAsString(ticketsResponse);
} else if (uri.equals("/find/tickets-patient/" + id)) {
List<FindByTicketsResponseDto> ticketsResponse = findService.findTicketsByPatientId(id);
response.setStatus(HttpServletResponse.SC_OK);
answer = objectMapper.writeValueAsString(ticketsResponse);
} else if (uri.equals("/find/doctors-and-cards-doctor/" + id)) {
List<FindByDoctorsAndCardsResponseDto> doctorsAndCardsResponse = findService.findDoctorsAndCardsByDoctorId(id);
response.setStatus(HttpServletResponse.SC_OK);
answer = objectMapper.writeValueAsString(doctorsAndCardsResponse);
} else if (uri.equals("/find/doctors-and-cards-card/" + id)) {
List<FindByDoctorsAndCardsResponseDto> doctorsAndCardsResponse = findService.findDoctorsAndCardsByCardId(id);
response.setStatus(HttpServletResponse.SC_OK);
answer = objectMapper.writeValueAsString(doctorsAndCardsResponse);
}
} catch (CardNotFoundException c) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
answer = c.getMessage();
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
answer = e.getMessage();
}
PrintWriter printWriter = response.getWriter();
printWriter.write(answer);
printWriter.flush();
}
} |
import 'package:flutter/material.dart';
import 'package:flutter_pokedex/constants/constant.dart';
import 'package:flutter_pokedex/model/pokemon_model.dart';
import 'package:flutter_pokedex/widgets/pokemon_img_and_ball.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
class PokemonListItem extends StatelessWidget {
final PokemonModel pokemon;
PokemonListItem({required this.pokemon});
@override
Widget build(BuildContext context) {
return Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.w)),
elevation: 3,
shadowColor: Colors.white,
color: Colors.red.shade200,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
pokemon.name ?? "N/A",
style: Constants.pokemonNameStyle(),
),
Chip(label: Text(pokemon.type![0])),
Expanded(child: PokemonImgAndBall(pokemon: pokemon))
],
),
);
}
} |
#ifndef GUN_MANAGER_MODULE_H
#define GUN_MANAGER_MODULE_H
#include <DebugUtil.h>
#include <vuVec3.h>
class IFiringMode;
///
/// @class GunManager
///
/// @brief
///
class GunManager
{
public:
enum FireType
{
UNSET,
SINGLE_SHOT,
BURST,
AUTO,
UNDEFINED
};
static inline void Initialize(void)
{
ASSERT(! s_pkInstance)
s_pkInstance = new GunManager();
}
static inline GunManager* GetInstance(void)
{
ASSERT(s_pkInstance)
return s_pkInstance;
}
static inline void Shutdown(void)
{
delete s_pkInstance;
}
void Configure(void);
void Fire(void);
void Update(double dDeltaTime);
void Reset(void);
void Start(void);
void GetMouseHeadingPitch(double* dHeading, double* dPitch, vuVec3<double>* pvdDirVec);
void GetHeadingPitchFromMouseCoordinates(double* dHeading, double* dPitch, float fMX, float fMY,
vuVec3<double>* pvdDirVec);
void PlayGunfireSound(void);
void GetMousePixelCoordinates(float* fMX, float* fMY);
void SetLagAdjustmentPoint(void);
void UpdateLagAdjustmentPoint(void);
void TriggerReleased(void);
inline const vuVec3<double>& GetLagAdjustmentPoint(void) const { return m_vdMotionPlatformAdjustmentPoint; }
const inline FireType& GetFireType(void) const { return m_kFireType; }
const inline void SetFireType(const FireType& kFireType) { m_kFireType = kFireType; }
private:
GunManager(void);
~GunManager(void);
static GunManager* s_pkInstance;
FireType m_kFireType;
IFiringMode* m_pkFiringMode;
vuVec3<double> m_vdMotionPlatformAdjustmentPoint;
};
#endif |
import { Component, OnInit, Input, Inject, Output, EventEmitter } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { TaskService, TaskItem, ImportanceList, StatusList } from '../service/task.service';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { Location } from '@angular/common';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatDialogConfig } from '@angular/material/dialog';
import { Comment, CommentService } from '../service/comment.service';
@Component({
selector: 'app-task-update',
templateUrl: './task-update.component.html',
})
/** task-update component*/
export class TaskUpdateComponent implements OnInit {
@Input() task: TaskItem;
public updateForm: FormGroup;
private errorMessagesTask = [];
public importanceList = [
{ value: 0, name: "low" },
{ value: 1, name: "medium" },
{ value: 2, name: "high" }];
public statusList = [
{ value: 0, name: "open" },
{ value: 1, name: "in progress" },
{ value: 2, name: "closed" }];
public errorMessages = <any>[];
constructor(private service: TaskService,
private route: ActivatedRoute,
private location: Location,
public dialog: MatDialog) {
}
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.service.getTask(+params['id']))
.subscribe(task => {
this.task = task;
this.initializeFormControls();
});
}
initializeFormControls(): void {
this.updateForm = new FormGroup({
id: new FormControl(this.task.id, Validators.required),
title: new FormControl(this.task.title, Validators.required),
description: new FormControl(this.task.description, Validators.required),
dateAdded: new FormControl(this.task.dateAdded),
dateDeadline: new FormControl(this.task.dateDeadline),
importance: new FormControl((this.task.importance)),
status: new FormControl(this.task.status),
dateClosure: new FormControl(this.task.dateClosure),
})
}
goBack() {
this.location.back();
}
onFormSubmit() {
console.log(this.updateForm.value);
this.service.update(this.updateForm.value)
.subscribe(
() => console.log('Task update complete'),
err => {
this.errorMessages = err;
console.log(err);
});
}
openDialog(id: number): void {
const dialogConfig = new MatDialogConfig();
dialogConfig.disableClose = true;
dialogConfig.autoFocus = true;
dialogConfig.data = {
dialogTaskId: id
};
const dialogRef = this.dialog.open(AddcommentComponent, dialogConfig
);
dialogRef.afterClosed().subscribe(result => {
});
const dialogSubmitSubscription =
dialogRef.componentInstance.submitClicked.subscribe(result => {
dialogSubmitSubscription.unsubscribe();
});
}
}
interface DialogData {
dialogTaskId: number;
dialogText: string;
dialogImportant: boolean;
}
@Component({
selector: 'addComment',
templateUrl: 'addComment.html',
})
export class AddcommentComponent implements OnInit {
dialogTaskId: number;
dialogText: string;
dialogImportant: boolean;
@Output() submitClicked = new EventEmitter<any>();
private errorMessagesComment = [];
constructor(
private service: CommentService,
public dialogRef: MatDialogRef<AddcommentComponent>,
@Inject(MAT_DIALOG_DATA) public data: DialogData) { }
ngOnInit() {
this.dialogTaskId = this.data.dialogTaskId;
console.log(this.dialogTaskId);
}
onNoClick(): void {
this.dialogRef.close();
}
saveComment(text, important) {
const id = 0;
const taskid = this.data.dialogTaskId;
this.service.saveComment({
id, text, important, taskid
}).subscribe(
() => console.log("completed"),
(err) => {
console.log("save not possible");
this.errorMessagesComment = err;
console.log(this.errorMessagesComment);
});
}
} |
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsArray, IsDefined, IsEthereumAddress, IsInt, IsOptional, IsString } from "class-validator";
export namespace GetTransactionListDTO {
export type Transaction = {
hash: string;
incoming: boolean;
senderAddress: string;
recipients: {
address: string;
amount: string;
}[];
amount: string;
actualAmount: string;
fee: string;
timestamp: number;
confirmed: boolean;
};
export class GetTransactionListRequest {
@IsDefined({
message: 'Address is required'
})
@IsString({
message: 'Address must be a string'
})
@IsEthereumAddress({
message: 'Address must be a valid ethereum address'
})
@ApiProperty()
address!: string;
@IsOptional({
message: 'Contract is optional'
})
@IsString({
message: 'Contract must be a string'
})
@IsEthereumAddress({
message: 'Contract must be a valid ethereum address'
})
@ApiPropertyOptional()
contract?: string;
@IsOptional({
message: 'Page is required'
})
@Type(() => Number)
@IsInt({
message: 'Page must be an int'
})
@ApiPropertyOptional()
page?: number;
@IsOptional({
message: 'Limit is required'
})
@Type(() => Number)
@IsInt({
message: 'Limit must be an int'
})
@ApiPropertyOptional()
limit?: number;
fill(address: string, page: number, limit: number, contract?: string) {
this.address = address;
this.page = page;
this.limit = limit;
this.contract = contract;
}
};
export class GetTransactionListResponse {
@IsDefined({
message: 'Inputs is required'
})
@IsArray({
message: 'Inputs must be an array'
})
@ApiProperty()
transactions!: Transaction[];
fill(transactions: Transaction[]) {
this.transactions = transactions;
}
};
}; |
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Link, useNavigate } from "react-router-dom";
import { login } from "./store/Slices/authSlice";
const Login = () => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const dispatch = useDispatch();
const navigate = useNavigate();
useEffect(() => {
if (localStorage.getItem("isAuth")) {
navigate("/profile");
}
}, [navigate]);
const handleSubmit = (e) => {
e.preventDefault();
if (username !== "" && password !== "") {
fetch("http://localhost:8000/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
})
.then((response) => response.json())
.then((data) => {
if (data.token) {
// Assuming the server responds with a token upon successful authentication
localStorage.setItem("isAuth", true);
localStorage.setItem("token", data.token);
localStorage.setItem("user", JSON.stringify({ username }));
dispatch(login(username)); // Adjust based on your Redux action
navigate("/profile");
} else {
alert("Login failed. Please check your username and password.");
}
})
.catch((error) => {
console.error("Login error:", error);
alert("An error occurred. Please try again later.");
});
}
};
return (
<div className="col-md-12">
<div className="card card-container">
<img
src="//ssl.gstatic.com/accounts/ui/avatar_2x.png"
alt="profile-img"
className="profile-img-card"
/>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="username">Username</label>
<input
type="text"
className="form-control"
name="username"
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
name="password"
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="form-group">
<button className="btn btn-block">
<span>Login</span>
</button>
</div>
<div className="mt-3">
<p>
Don't have an account? <Link to="/register">Sign Up</Link>
</p>
</div>
</form>
</div>
</div>
);
};
export default Login; |
import { useState } from "react";
import Button, { BUTTON_TYPE_CLASSES } from "../button/button.component";
import FormInput from "../form-input/form-input.component";
import {
signInAuthUserWithEmailAndPassword,
signInWithGooglePopup,
// createUserDocumentFromAuth,
} from "../../utils/firebase/firebase.utils";
import { ButtonsContainer, SignUpContainer } from "./sign-in-form.styles";
const defaultFormValues = {
email: "",
password: "",
};
const SignInForm = () => {
const [formValues, setFormValues] = useState(defaultFormValues);
const { email, password } = formValues;
const logGoogleUser = async () => {
await signInWithGooglePopup();
};
const handleSubmit = async (event) => {
event.preventDefault();
try {
await signInAuthUserWithEmailAndPassword(email, password);
} catch (error) {}
};
const handleChange = (event) => {
const { name, value } = event.target;
setFormValues({ ...formValues, [name]: value });
};
return (
<SignUpContainer>
<h2>Have an account?</h2>
<span>Sign in with your email and password</span>
<form onSubmit={handleSubmit}>
<FormInput
label="Email"
type="text"
required
onChange={handleChange}
name="email"
value={email}
/>
<FormInput
label="Password"
type="password"
required
onChange={handleChange}
name="password"
value={password}
/>
<ButtonsContainer>
<Button type="submit">SIGN IN</Button>
<Button
type="button"
buttonType={BUTTON_TYPE_CLASSES.google}
onClick={logGoogleUser}
>
GOOGLE SIGN IN
</Button>
</ButtonsContainer>
</form>
</SignUpContainer>
);
};
export default SignInForm; |
import React from 'react';
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import useScrollTrigger from '@mui/material/useScrollTrigger';
const Navbar = () => {
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const handleMenuClick = (event: React.MouseEvent<HTMLButtonElement>) => {
setAnchorEl(event.currentTarget);
};
const handleMenuClose = () => {
setAnchorEl(null);
};
const getFirstName = () => {
const firstName =JSON.parse(localStorage.getItem('userInfo')!).firstName;
return firstName ? firstName : '';
};
const handleLogout = () => {
localStorage.removeItem('userInfo');
window.location.href = '/SignIn';
};
const trigger = useScrollTrigger();
return (
<AppBar position="sticky" elevation={trigger ? 4 : 0}>
<Toolbar>
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
NewsApp
</Typography>
<div>
<Button
color="inherit"
startIcon={<AccountCircleIcon />}
onClick={handleMenuClick}
>
{getFirstName()}
</Button>
<Menu
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={handleMenuClose}
>
<MenuItem onClick={handleLogout}>Logout</MenuItem>
</Menu>
</div>
</Toolbar>
</AppBar>
);
};
export default Navbar; |
import getConfig from "next/config";
const { publicRuntimeConfig } = getConfig();
import { useState, useMemo, useEffect } from "react";
import {
STD_COLS,
STD_FILTERS,
ALT_COLS,
ALT_FILTERS,
MINT_PASS_COLS,
GROUP_COLORS,
} from "components/constants";
import {
PageLayout,
PageTitle,
CustomTable,
Tabs,
ServerError,
Loading,
} from "components";
const getCellProps = (cell, withColors, rowIndex) => {
if (withColors && GROUP_COLORS.hasOwnProperty(cell.column?.parent?.Header)) {
const color = GROUP_COLORS[cell.column?.parent?.Header].row;
return {
className: rowIndex % 2 === 0 ? color.even : color.odd,
};
}
return {
className: rowIndex % 2 === 0 ? "bg-slate-50" : "bg-slate-200",
};
};
const getHeaderCellProps = (column, withColors) => {
const propName = column.depth === 0 ? column.Header : column?.parent?.Header;
if (withColors && GROUP_COLORS.hasOwnProperty(propName)) {
const color = GROUP_COLORS[propName].header;
return {
className: `${
column.depth === 0 ? color.main : color.sub
} text-white font-normal`,
};
}
return {
className: `${
column?.depth === 0 ? "bg-slate-900" : "bg-slate-700"
} text-white font-normal`,
};
};
export default function Home() {
const [stats, setStats] = useState();
const [error, setError] = useState(false);
const [withColors, setWithColors] = useState(true);
const filterTypes = useMemo(
() => ({
exactFilter: (rows, id, filterValue) => {
const field = id[0];
return rows.filter((r) => String(r.original[field]) === filterValue);
},
startWithFilter: (rows, id, filterValue) => {
const field = id[0];
return rows.filter((r) =>
r.original[field].toLowerCase().startsWith(filterValue.toLowerCase())
);
},
}),
[]
);
useEffect(() => {
fetch(`${publicRuntimeConfig.serverUrl}/stats?separateFoil=1`)
.then((res) => res.json())
.then((data) => setStats(data))
.catch(() => setError(true));
}, []);
const tabs = [
{
name: "Standard cards",
content: (
<CustomTable
data={stats?.std_cards}
columns={STD_COLS}
filters={STD_FILTERS}
filterTypes={filterTypes}
getCellProps={getCellProps}
getHeaderCellProps={getHeaderCellProps}
withColors={withColors}
setWithColors={setWithColors}
/>
),
},
{
name: "Alternative cards",
content: (
<CustomTable
data={stats?.alt_cards}
columns={ALT_COLS}
filters={ALT_FILTERS}
filterTypes={filterTypes}
getCellProps={getCellProps}
getHeaderCellProps={getHeaderCellProps}
withColors={withColors}
setWithColors={setWithColors}
/>
),
},
{
name: "Mint passes",
content: (
<CustomTable
data={stats?.mint_passes || []}
columns={MINT_PASS_COLS}
getCellProps={getCellProps}
getHeaderCellProps={getHeaderCellProps}
/>
),
},
];
return (
<>
{error ? (
<ServerError />
) : !stats ? (
<Loading />
) : (
<PageLayout lastUpdate={stats.last_update}>
<PageTitle>Cards collection</PageTitle>
{stats.std_cards.length > 0 || stats.alt_cards.length > 0 ? (
<Tabs tabs={tabs} />
) : (
<ServerError />
)}
</PageLayout>
)}
</>
);
} |
| Задание 44 |
| --- |
| В ячейке ниже представлен код генерирующий DataFrame, которая состоит всего из 1 столбца. Ваша задача перевести его в one hot вид. Сможете ли вы это сделать без get_dummies?
import random
lst = ['robot'] * 10
lst += ['human'] * 10
random.shuffle(lst)
data = pd.DataFrame({'whoAmI'lst})
data.head() |
Решение :
import random
lst = ['robot'] * 10
lst += ['human'] * 10
random.shuffle(lst)
data = pd.DataFrame({'whoAmI':lst})
data.head()
categories = data['whoAmI'].unique()
one_hot_data = pd.DataFrame(columns=categories)
for i, row in data.iterrows():
category = row['whoAmI']
one_hot_row = [1 if cat == category else 0 for cat in categories]
one_hot_data.loc[i] = one_hot_row
one_hot_data.head()
https://colab.research.google.com/drive/1k9Rrsssf3mxZzAbk3ngQpcElGaLirdW6?hl=ru#scrollTo=s8uygX2kXfd1 |
#include "ds/str.h"
#include <stdio.h>
#include <string.h>
#include "utils/mem.h"
double str_charp_hash(const char *str) {
double hash = 5381;
int c = 0; // store the current char
int count = 0;
for (c = *str; (count < MAX_STR_LEN) && (*str != 0); str++, count++) {
hash = ((hash * 32) + hash) + c;
}
return hash;
}
Str *str_create_from_charp(char *str) {
Str *new_str = malloc_with_check(sizeof(Str));
strncpy(new_str->str, str, MAX_STR_LEN - 1);
new_str->str[MAX_STR_LEN - 1] = '\0';
new_str->hash = str_charp_hash(new_str->str);
return new_str;
}
void str_print(Str *str) {
if (str == NULL) return;
printf("Str(str: '%s', hash: %lf)\n", str->str, str->hash);
}
void str_free(Str *str) {
if (str == NULL) return;
free(str);
}
StrList *str_list_create() {
StrList *new_str_list = malloc_with_check(sizeof(StrList));
new_str_list->str = NULL;
new_str_list->next = NULL;
return new_str_list;
}
void str_list_print(StrList *str_list) {
StrList *temp = str_list;
while (temp != NULL) {
if (temp->str != NULL) {
str_print(temp->str);
}
temp = temp->next;
}
}
StrList *str_list_add(StrList *str_list, Str *str, size_t *pos) {
if (str_list == NULL) return NULL;
size_t npos = 0;
StrList *temp = str_list;
if (temp->str == NULL) {
if (pos != NULL) *pos = npos;
temp->str = str;
return str_list;
}
StrList *new_node = str_list_create();
new_node->str = str;
npos++;
while (temp->next != NULL) {
npos++;
temp = temp->next;
}
if (pos != NULL) *pos = npos;
temp->next = new_node;
return str_list;
}
Str *str_list_get(StrList *str_list, double hash) {
if (str_list == NULL) return NULL;
StrList *temp = str_list;
while (temp != NULL) {
if (temp->str->hash == hash) {
return temp->str;
}
}
return NULL;
}
void str_list_free(StrList *str_list) {
if (str_list == NULL) return;
StrList *temp;
while (str_list != NULL) {
temp = str_list;
str_list = str_list->next;
free(temp);
}
}
void str_list_free_all(StrList *str_list) {
if (str_list == NULL) return;
StrList *temp;
while (str_list != NULL) {
temp = str_list;
str_list = str_list->next;
if (temp->str != NULL) {
str_free(temp->str);
}
free(temp);
}
} |
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:med_sal/controller/profile/profile_controller.dart';
import 'package:med_sal/core/constant/app_colors.dart';
import 'package:med_sal/core/constant/app_images.dart';
import 'package:med_sal/view/widgets/profile/custom_text.dart';
class ProfilePage extends StatelessWidget {
const ProfilePage({super.key});
@override
Widget build(BuildContext context) {
ProfileController profileController = Get.put(ProfileController());
double width = MediaQuery.sizeOf(context).width;
double height = MediaQuery.sizeOf(context).height;
return Scaffold(
body: ListView(
children: [
Stack(
children: [
//********************** Green Container Area *************************/
Container(
height: height * 0.5,
width: width,
decoration: const BoxDecoration(
color: AppColors.buttonGreen,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(45),
bottomRight: Radius.circular(45),
),
),
child: const Column(
children: [
SizedBox(height: 30),
//********************** Text *************************/
Text('My Profile'),
SizedBox(height: 30),
//********************** Circle Image *************************/
SizedBox(
width: 220,
height: 220,
child: CircleAvatar(
backgroundImage: AssetImage(AppImages.profile)))
],
),
),
//********************** Setting Button *************************/
Positioned(
top: 35,
left: 20,
child: InkWell(
onTap: () {
profileController.goToSetting();
},
child: const Icon(Icons.settings_outlined)))
],
),
//********************** Bottom Area *************************/
//* */
//********************** Email Area *************************/
const Padding(
padding: EdgeInsets.all(20),
child: Column(
children: [
CustomTextProfile(
icon: Icons.mail_outline,
textIcon: 'Email',
text: 'yourname @mail.com',
),
SizedBox(height: 20),
Divider(),
//********************** Phone Area *************************/
SizedBox(height: 20),
CustomTextProfile(
icon: Icons.phone_outlined,
textIcon: 'Phone',
text: '08954752516',
),
SizedBox(height: 20),
Divider(),
//********************** Date Area *************************/
SizedBox(height: 20),
CustomTextProfile(
icon: Icons.date_range_outlined,
textIcon: 'Date of joining',
text: '25 / 10 / 2023',
),
],
),
),
const SizedBox(height: 50),
],
),
);
}
} |
package com.dongkuksystems.dbox.services.dept;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.documentum.fc.client.IDfPersistentObject;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfId;
import com.documentum.fc.common.DfTime;
import com.dongkuksystems.dbox.constants.EntCode;
import com.dongkuksystems.dbox.constants.NotiItem;
import com.dongkuksystems.dbox.daos.table.etc.gwaddjob.GwAddJobDao;
import com.dongkuksystems.dbox.daos.table.etc.gwdept.GwDeptDao;
import com.dongkuksystems.dbox.daos.table.etc.gwuser.GwUserDao;
import com.dongkuksystems.dbox.daos.type.manager.deptMgr.DeptMgrDao;
import com.dongkuksystems.dbox.errors.NotFoundException;
import com.dongkuksystems.dbox.models.common.UserSession;
import com.dongkuksystems.dbox.models.dto.table.gwdept.GwDeptChildrenDto;
import com.dongkuksystems.dbox.models.dto.table.gwdept.GwDeptFilterDto;
import com.dongkuksystems.dbox.models.dto.table.gwdept.GwDeptListManagerDto;
import com.dongkuksystems.dbox.models.dto.table.gwdept.GwDeptPathDto;
import com.dongkuksystems.dbox.models.dto.table.gwdept.GwDeptTreeDto;
import com.dongkuksystems.dbox.models.table.etc.GwDept;
import com.dongkuksystems.dbox.models.table.etc.VDept;
import com.dongkuksystems.dbox.models.type.manager.deptMgr.DeptMgrs;
import com.dongkuksystems.dbox.services.AbstractCommonService;
import com.dongkuksystems.dbox.services.notification.NotificationService;
@Service
public class GwDeptServiceImpl extends AbstractCommonService implements GwDeptService {
private final GwDeptDao gwDeptDao;
private final GwUserDao gwUserDao;
private final GwAddJobDao gwAddJobDao;
private final DeptMgrDao deptMgrDao;
private final NotificationService notificationService;
public GwDeptServiceImpl(GwDeptDao gwDeptDao, GwUserDao gwUserDao, GwAddJobDao gwAddJobDao, DeptMgrDao deptMgrDao,
NotificationService notificationService) {
this.gwDeptDao = gwDeptDao;
this.gwUserDao = gwUserDao;
this.gwAddJobDao = gwAddJobDao;
this.deptMgrDao = deptMgrDao;
this.notificationService = notificationService;
}
@Override
@Cacheable(value = "selectDepts", key = "#comOrgId.concat('-').concat(#mobileYn)")
public List<VDept> selectDepts(String comOrgId, String mobileYn) {
if (EntCode.DKG.name().equals(comOrgId)) {
return gwDeptDao.selectAll();
}
List<VDept> rst = null;
if ("Y".equals(mobileYn)) {
final List<String> excludes = Arrays.asList("DKS", "CHR", "VHR", "UNC", "FEI", "ITG");
rst = gwDeptDao.selectAll().stream().filter(v -> comOrgId.equals(v.getComOrgId()) && !excludes.contains(v.getOrgId())).collect(Collectors.toList());
} else {
rst = gwDeptDao.selectAll().stream().filter(v -> comOrgId.equals(v.getComOrgId())).collect(Collectors.toList());
}
// .sorted((t1, t2) -> t1.getUnitFullId().compareToIgnoreCase(t2.getUnitFullId())).collect(Collectors.toList());
return rst;
}
@Override
@Cacheable(value = "selectDepts", key = "#comOrgId")
public List<GwDept> selectDeptsInGwDept(String comOrgId) {
if (EntCode.DKG.name().equals(comOrgId)) {
return gwDeptDao.selectDeptsInGwDept();
}
List<GwDept> rst = gwDeptDao.selectDeptsInGwDept().stream().filter(v -> comOrgId.equals(v.getComOrgId())).collect(Collectors.toList());
return rst;
}
@Override
@Cacheable(value = "selectDeptByOrgId", key = "#orgId")
public VDept selectDeptByOrgId(String orgId) throws Exception {
VDept rst = gwDeptDao.selectOneByOrgId(orgId).orElseThrow(() -> new NotFoundException("There is no such dept"));
if (rst.getComOrgId() != null) {
rst.setComOrgNm(EntCode.findOrgNmByOrgId(rst.getComOrgId()));
}
return rst;
}
@Override
@Cacheable(value = "selectGwDeptByOrgId", key = "#orgId")
public GwDept selectGwDeptByOrgId(String orgId) throws Exception {
GwDept rst = gwDeptDao.selectGwOneByOrgId(orgId).orElseThrow(() -> new NotFoundException("There is no such dept"));
if (rst.getComOrgId() != null) {
rst.setComOrgNm(EntCode.findOrgNmByOrgId(rst.getComOrgId()));
}
return rst;
}
@Override
@Cacheable(value = "selectDeptCodeByCabinetcode", key = "#cabinetcode")
public String selectDeptCodeByCabinetcode(String cabinetCode) throws Exception {
return gwDeptDao.selectOrgIdByCabinetcode(cabinetCode);
}
@Override
public GwDeptChildrenDto selectDeptChildren(String orgId, boolean userYn, boolean addJobYn) throws Exception {
return GwDeptChildrenDto.builder().deptList(gwDeptDao.selectListByUpOrgId(orgId, "A", ""))
.deptUsers(userYn ? gwUserDao.selectListByOrgId(orgId, "A", "") : null)
.addJob(addJobYn ? gwAddJobDao.selectListByAjId(orgId) : null).build();
}
@Override
@Cacheable(value = "selectDeptPath", key = "#orgId")
public GwDeptPathDto selectDeptPath(String orgId) throws Exception {
return gwDeptDao.selectDeptPath(orgId);
}
@Override
@Cacheable(value = "selectDeptTree", key = "#dto.hashCode()")
public GwDeptTreeDto selectDeptTree(GwDeptFilterDto dto) throws Exception {
List<VDept> depts = this.selectDepts(EntCode.DKG.name(), "N");
EntCode ent = EntCode.getEnt(dto.getDeptId());
String deptCode = ent != null ? ent.name() : dto.getDeptId();
GwDeptTreeDto tree = GwDeptTreeDto.builder()
.dept(this.selectDeptByOrgId(deptCode))
.deptUsers(dto.isUserYn()?gwUserDao.selectListByOrgId(deptCode, dto.getUserStatus(), "") : null)
.addJob(dto.isAddJobYn()?gwAddJobDao.selectDetailedListByAjId(deptCode) : null)
.children(this.makeTree(dto, deptCode, depts)).build();
return tree;
}
private List<GwDeptTreeDto> makeTree(GwDeptFilterDto dto, String upOrgId, List<VDept> depts) {
List<GwDeptTreeDto> list = new ArrayList<>();
for (VDept val : depts) {
if (upOrgId.equals(val.getUpOrgId())) {
if (val.getComOrgId() != null) {
val.setComOrgNm(EntCode.findOrgNmByOrgId(val.getComOrgId()));
}
GwDeptTreeDto tmp = GwDeptTreeDto.builder().dept(val)
.deptUsers(dto.isUserYn() ? gwUserDao.selectListByOrgId(val.getOrgId(), dto.getUserStatus(), "") : null)
.addJob(dto.isAddJobYn() ? gwAddJobDao.selectDetailedListByAjId(val.getOrgId()) : null)
.children(this.makeTree(dto, val.getOrgId(),
depts.stream().filter(t -> !upOrgId.equals(t.getUpOrgId())).collect(Collectors.toList())))
.build();
list.add(tmp);
}
}
return list;
}
@Override
@Cacheable(value = "selectDeptChildrenByOrgId", key = "#orgId")
public List<VDept> selectDeptChildrenByOrgId(String orgId) throws Exception {
return gwDeptDao.selectDeptChildrenByOrgId(orgId);
}
@Override
@Cacheable(value = "selectComCodeByCabinetCode", key = "#cabinetcode")
public String selectComCodeByCabinetCode(String cabinetcode) throws Exception {
return gwDeptDao.selectComCodeByCabinetCode(cabinetcode);
}
@Override
@Cacheable(value = "selectUserListOfPart", key = "#gwOrgId") // jjg,2021.10.19 Part사용자들 조회용
public List<String> selectUserListOfPart(String gwOrgId) throws Exception {
return gwDeptDao.selectUserListOfPart(gwOrgId);
}
@Override
public List<GwDeptListManagerDto> selectDeptMemberList(String deptId) {
return gwDeptDao.selectDeptMemberList(deptId);
}
// TODO 트랜잭션 처리 어떻게?
@Override
public void postDeptManager(String deptId, UserSession userSession, List<GwDeptListManagerDto> members) throws Exception {
List<GwDeptListManagerDto> managers = gwDeptDao.selectDeptManagerList(deptId);
IDfSession idfSession = this.getIdfSession(userSession);
IDfPersistentObject idf_PObj = null;
idfSession.beginTrans();
try {
if (idfSession == null || !idfSession.isConnected()) {
throw new Exception("DCTM Session 가져오기 실패");
}
for (GwDeptListManagerDto member : members) {
boolean isChecked = isTypeManager(member.getUMgrType());
boolean isManager = isManager(managers, member.getUserId());
boolean canSaveManager = isChecked && !isManager;
if(canSaveManager) {
saveManager(deptId, userSession.getUser().getUserId(), member, idfSession);
idf_PObj = (IDfPersistentObject) idfSession.newObject("edms_noti");
idf_PObj.setString("u_msg_type", "DM");
idf_PObj.setString("u_sender_id", userSession.getDUserId());
idf_PObj.setString("u_receiver_id", member.getUserId());
idf_PObj.setString("u_msg", "부서문서관리자로 지정되었습니다.");
idf_PObj.setString("u_performer_id", userSession.getDUserId());
idf_PObj.setString("u_obj_id", member.getRObjectId());
idf_PObj.setString("u_sent_date", new DfTime().toString());
idf_PObj.setString("u_action_yn", "N");
idf_PObj.setString("u_action_need_yn", "N");
idf_PObj.save();
} else if (!isChecked && isManager) {
destroyManagerIfPossible(idfSession, member.getRObjectId());
idf_PObj = (IDfPersistentObject) idfSession.newObject("edms_noti");
idf_PObj.setString("u_msg_type", "DM");
idf_PObj.setString("u_sender_id", userSession.getDUserId());
idf_PObj.setString("u_receiver_id", member.getUserId());
idf_PObj.setString("u_msg", "부서문서관리자에서 해제 되었습니다.");
idf_PObj.setString("u_performer_id", userSession.getDUserId());
idf_PObj.setString("u_obj_id", member.getRObjectId());
idf_PObj.setString("u_sent_date", new DfTime().toString());
idf_PObj.setString("u_action_yn", "N");
idf_PObj.setString("u_action_need_yn", "N");
idf_PObj.save();
}
}
idfSession.commitTrans();
} catch (Exception e) {
throw e;
} finally {
if (idfSession != null) {
if (idfSession.isTransactionActive()) {
idfSession.abortTrans();
}
if (idfSession.isConnected()) {
sessionRelease(userSession.getUser().getUserId(), idfSession);
}
}
}
}
@Override
@Cacheable(value = "selectOrgIdByCabinetcode", key = "#cabinetcode")
public String selectOrgIdByCabinetcode(String cabinetcode) throws Exception {
return gwDeptDao.selectOrgIdByCabinetcode(cabinetcode);
}
@Override
public List<GwDept> selectDeptMng(String managerPerId) {
return gwDeptDao.selectDeptMng(managerPerId);
}
private void destroyManagerIfPossible(IDfSession idfSession, String rObjectId) throws DfException {
if(StringUtils.isNotEmpty(rObjectId)) {
idfSession.getObject(new DfId(rObjectId)).destroy();
}
}
private void saveManager(String deptId, String sessionUserId, GwDeptListManagerDto member, IDfSession idfSession) throws DfException {
// TODO 건건이 처리 말고 배치로
IDfPersistentObject idf_PObj = idfSession.newObject("edms_dept_mgr");
idf_PObj.setString("u_com_code", member.getComOrgId());
idf_PObj.setString("u_dept_code", deptId);
idf_PObj.setString("u_user_id", member.getUserId());
idf_PObj.setString("u_mgr_type", "M");
idf_PObj.setString("u_assign_user", sessionUserId);
idf_PObj.setString("u_assign_date", (new DfTime()).toString());
idf_PObj.setString("u_assign_user_type", "D");
idf_PObj.save();
}
private boolean isTypeManager(String mgrType) {
return "M".equals(mgrType);
}
private boolean isManager(List<GwDeptListManagerDto> managers, String memberId) {
GwDeptListManagerDto manager = managers
.stream()
.filter(item -> item.getUserId().equals(memberId) && isTypeManager(item.getUMgrType()))
.findAny().orElse(null);
return manager != null;
}
private void sendNotification(String deptId) throws Exception {
List<DeptMgrs> newManagerList = deptMgrDao.selectByDeptCode(deptId);
List<String> newManagerDept = newManagerList.stream().map(DeptMgrs::getUDeptCode).collect(Collectors.toList());
List<String> newManagerId = newManagerList.stream().map(DeptMgrs::getUUserId).collect(Collectors.toList());
notificationService.sendNotification(Stream.concat(newManagerDept.stream(), newManagerId.stream()).collect(Collectors.toList()), NotiItem.SH, "Dbox", "푸시를 확인해주세요");
}
} |
/*
* Copyright (C) 2023 Inria
*
* Inria: Institut National de Recherche en Informatique et en Automatique
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* A copy of the license is provided in the file "LICENSE" distributed
* with this file. You may also obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import fs from 'node:fs/promises';
import crypt from 'crypto';
import iv from './initial-vals.js';
import { ipfsAddObj, ipfsCommit } from "./utilities.js"
export async function createAgent(profileName: string) {
// now just using default parameters
const { privateKey, publicKey } = crypt.generateKeyPairSync('ed25519', {
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
// create a profile and add it to the profiles file
const fingerPrint = crypt.createHash('sha256').update(publicKey).digest('hex');
const newProfile: agentProfile = {
"name": profileName,
"public-key": publicKey,
"private-key": privateKey,
"fingerprint": fingerPrint
};
await iv.agentProfiles.write(profileName, newProfile);
console.log("Agent profile " + profileName + " created successfully!");
}
export async function createTool(toolProfileName: string,
inputType: "file" | "cid" | "json",
input: string) {
let toolCid = undefined;
if (inputType === "file") {
// [HACK] assumes file is data, not text
// could have { encoding: "utf-8" }
const content = await fs.readFile(input);
toolCid = await ipfsAddObj({
"format": "tool",
"content": content
});
}
else if (inputType === "json") {
const data = await fs.readFile(input, { encoding: "utf-8" });
const content = JSON.parse(data);
toolCid = await ipfsAddObj({
"format": "tool",
"content": content
});
}
else if (inputType === "cid")
toolCid = input; // assuming the cid refers to a "format" = "tool" object --> check later
else
throw new Error(`createTool: invalid inputType ${ inputType }`);
const toolProfile = {
"name": toolProfileName,
"tool": toolCid
}
await ipfsCommit();
await iv.toolProfiles.write(toolProfileName, toolProfile);
console.log("Tool profile " + toolProfileName + " created successfully!")
}
// check that cid refers to "format"="language" type --> later
export async function createLanguage(languageName: string,
inputType: "file" | "cid" | "json",
input: string) {
let languageCid = "";
if (inputType === "file") {
const content = await fs.readFile(input);
languageCid = await ipfsAddObj({
"format": "language",
"content": content
});
}
else if (inputType === "json") {
const data = await fs.readFile(input, { encoding: "utf-8" });
const content = JSON.parse(data)
languageCid = await ipfsAddObj({
"format": "language",
"content": content
});
}
else if (inputType === "cid")
languageCid = input; // assuming the cid refers to a "format" = "language" object --> check later
else
throw new Error(`createLanguage: invalid inputType ${ inputType }`);
const language = {
"name": languageName,
"language": languageCid
};
await ipfsCommit();
await iv.languages.write(languageName, language);
console.log("Language record " + languageName + " created successfully!");
}
export async function setweb3token(token: string) {
await iv.config.write("my-web3.storage-api-token", token);
}
export async function setgateway(gateway: string) {
await iv.config.write("my-gateway", gateway);
}
/*let trustagent = (agent: string) => {
let allowlistFile = fs.readFileSync(allowlistpath)
let allowList = JSON.parse(allowlistFile)
allowList.push(agent)
allowList = Array.from(new Set(allowList)) // agent listed only once
try {
fs.writeFileSync(allowlistpath, JSON.stringify(allowList))
}
catch (err) {
console.log(err)
}
}*/
export async function listconfig() {
console.log("//", iv.config.fileName);
console.log(await iv.config.readAll());
console.log("//", iv.keyStore.fileName);
console.log(await iv.keyStore.readAll());
console.log("//", iv.agentProfiles.fileName);
console.log(await iv.agentProfiles.readAll());
console.log("//", iv.toolProfiles.fileName);
console.log(await iv.toolProfiles.readAll());
console.log("//", iv.languages.fileName);
console.log(await iv.languages.readAll());
console.log("//", iv.allowList.fileName);
console.log(await iv.allowList.readAll());
}
// export default {
// createAgent,
// createTool, createLanguage,
// setweb3token, setgateway,
// listconfig,
// }; |
import { ComputedRef } from 'vue';
import { balancerSubgraphService } from '@/services/balancer/subgraph/balancer-subgraph.service';
import { PoolDecorator } from '@/services/pool/decorators/pool.decorator';
import {
GraphQLArgs,
PoolRepository as SDKPoolRepository,
} from '@balancer-labs/sdk';
import { balancerAPIService } from '@/services/balancer/api/balancer-api.service';
import { Pool } from '@/services/pool/types';
import { TokenInfoMap } from '@/types/TokenList';
import { isBalancerApiDefined } from '@/lib/utils/balancer/api';
import {
getPoolsFallbackRepository,
PoolsFallBackFactoryConstructor,
} from '@/dependencies/PoolsFallbackRepository';
export default class PoolRepository {
repository: PoolsFallBackFactoryConstructor;
queryArgs: GraphQLArgs;
constructor(private tokens: ComputedRef<TokenInfoMap>) {
const PoolsFallbackRepository = getPoolsFallbackRepository();
this.repository = new PoolsFallbackRepository(this.buildRepositories(), {
timeout: 30 * 1000,
});
this.queryArgs = {};
}
public async fetch(queryArgs: GraphQLArgs): Promise<Pool> {
this.queryArgs = queryArgs;
const [pool] = await this.repository.fetch();
return pool as Pool;
}
private initializeDecoratedAPIRepository() {
return {
fetch: async (): Promise<Pool[]> => {
const pool = await balancerAPIService.pool.get(this.queryArgs);
if (!pool) throw new Error('Cannot find pool via Balancer API');
return [pool];
},
get skip(): number {
return 0;
},
};
}
private initializeDecoratedSubgraphRepository() {
return {
fetch: async (): Promise<Pool[]> => {
const pools = await balancerSubgraphService.pools.get(this.queryArgs);
const poolDecorator = new PoolDecorator(pools);
const decoratedPools = await poolDecorator.decorate(
this.tokens.value,
true
);
return decoratedPools;
},
get skip(): number {
return 0;
},
};
}
private buildRepositories() {
const repositories: SDKPoolRepository[] = [];
if (isBalancerApiDefined) {
const balancerApiRepository = this.initializeDecoratedAPIRepository();
repositories.push(balancerApiRepository);
}
const subgraphRepository = this.initializeDecoratedSubgraphRepository();
repositories.push(subgraphRepository);
return repositories;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.