text
stringlengths
184
4.48M
// // SecondViewController.swift // UITableViewDemo // // Created by Саидов Тимур on 09.06.2022. // import UIKit class SecondViewController: UIViewController { private lazy var tableView: UITableView = { let tableView = UITableView(frame: .zero, style: .insetGrouped) /// При статическом отображении ячеек, параметр estimatedRowHeight не используется, а rowHeight задается нужной величиной. tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 44 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "DefaultCell") tableView.register(DynamicArticleTableViewCell.self, forCellReuseIdentifier: "DynamicCell") // tableView.register(StaticArticleTableViewCell.self, forCellReuseIdentifier: "StaticCell") tableView.dataSource = self tableView.delegate = self tableView.translatesAutoresizingMaskIntoConstraints = false return tableView }() private let articles: [Article] = Mock.shared.data override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .white self.view.addSubview(self.tableView) NSLayoutConstraint.activate([ self.tableView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor), self.tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), self.tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), self.tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor) ]) } } extension SecondViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { self.articles.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "DynamicCell", for: indexPath) as? DynamicArticleTableViewCell else { let cell = tableView.dequeueReusableCell(withIdentifier: "DefaultCell", for: indexPath) return cell } // guard let cell = tableView.dequeueReusableCell(withIdentifier: "StaticCell", for: indexPath) as? StaticArticleTableViewCell else { // let cell = tableView.dequeueReusableCell(withIdentifier: "DefaultCell", for: indexPath) // return cell // } let article = self.articles[indexPath.row] cell.setup(with: article) return cell } // func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // 200 // } }
// USER NAVIGATION (CSS) // // 1. Corrects the spacing added by .navUser-or // 2. Can't use top: 50% because its container `.header` changes its height to // 100% when mobile menu is expanded // 3. Make the triangle for store credit dropdown centered // 4. Needs to be 100% so its dropdown can take full width in mobile viewport // 5. Needs to be lower than logo zIndex, otherwise, logo is not clickable // 6. Make the triangle for currency dropdown right aligned // 7. Corrects mini cart positioned outside viewport. Since this resets right // position, nudge dropdown away from the side of viewport in mobile viewport. // 8. This corrects mini cart dropdown arrow alignment in mobile viewport by // setting the previous styles to medium breakpoint and adjusts for nudge in (7). // // ----------------------------------------------------------------------------- .navUser { margin-left: 5px; .dropdown-menu { background-color: stencilColor("navUser-dropdown-backgroundColor"); border: 1px solid stencilColor("navUser-dropdown-borderColor"); box-shadow: container("dropShadow"); position: absolute; &.is-open { &::before { @include css-triangle( $triangle-direction: "bottom", $triangle-size: 10px, $triangle-color: stencilColor("navUser-dropdown-borderColor") ); bottom: 100%; left: spacing("half"); position: absolute; } &::after { @include css-triangle( $triangle-direction: "bottom", $triangle-size: 8px, $triangle-color: stencilColor("navUser-dropdown-backgroundColor") ); bottom: 100%; left: spacing("half") + remCalc(2px); position: absolute; } } } } .navUser-section { align-items: center; display: flex; justify-content: center; list-style: none; margin: 0; padding: 0; } .navUser-action { align-items: center; color: stencilColor("color-textBase"); display: flex; justify-content: center; padding: ($container-padding / 2); transition: all 750ms ease; @include breakpoint("xsmall") { padding: ($container-padding / 1.8); } @include breakpoint("small") { padding: ($container-padding / 1.5); } @include breakpoint("large") { padding: ($container-padding / 1.2); } &:hover, &.is-open { color: stencilColor("color-primary"); svg { fill: stencilColor("color-primary"); stroke: stencilColor("color-primary"); } } &--quickSearch .material-icon { font-size: 30px; } &--account .material-icon { font-size: 34px; } &--cart .material-icon { font-size: 28px; } svg { fill: stencilColor("navUser-color"); stroke: stencilColor("navUser-color"); transition: all 0.15s ease; } } .navUser-item { display: none; @include breakpoint("xsmall") { display: block; } @include breakpoint("medium") { &.navUser-item--social { margin-top: rem-calc(5px); padding-right: rem-calc(5px); } &.navUser-item--divider { font-size: rem-calc(25px); margin-top: rem-calc(8px); padding-left: rem-calc(2px); } } } .navUser-item--quickSearch { display: block; } .navUser-item--cart { display: block; .navUser-action { color: stencilColor("color-textBase"); &:hover, &.is-open { color: stencilColor("color-primary"); } } .dropdown-menu { max-width: remCalc(320px); &.is-open { left: auto !important; // 7 right: remCalc(5px); // 7 top: auto !important; // 7 @include breakpoint("medium") { right: 0; // 7 } &::before, &::after { left: auto; } &::before { right: spacing("half") - remCalc(5px); // 8 @include breakpoint("medium") { right: spacing("half"); // 8 } } &::after { right: spacing("half") - remCalc(3px); // 8 @include breakpoint("medium") { right: spacing("half") + remCalc(2px); // 8 } } } } } .navUser-item-cartLabel { display: none; @include breakpoint("small") { display: inline; } } // Counter Pill // ----------------------------------------------------------------------------- // // 1. Hardcoded intentionally for precise pixels. // // ----------------------------------------------------------------------------- .countPill { background-color: $color-secondary; border-radius: 50%; color: color("whites", "bright"); font-size: fontSize("tiny"); font-weight: normal; height: 26px; // 1 line-height: 26px; // 1 margin-left: spacing("quarter"); text-align: center; width: 26px; // 1 } .countPill--alt { background-color: color("greys", "lighter"); color: color("greys", "darker"); }
import React, { useState } from "react"; import { useNavigate } from "react-router-dom"; import { Container, Form, Button } from "react-bootstrap"; import axios from "axios"; function Register() { const navigate = useNavigate(); const [formData, setFormData] = useState({ name: "", email: "", username: "", password: "", }); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value, }); }; const handleSubmit = async (e) => { e.preventDefault(); try { const response = await axios.post( "http://localhost:8000/api/auth/register", { name: formData.name, email: formData.email, username: formData.username, password: formData.password, }, { headers: { "Content-Type": "application/json", }, } ); console.log(response.data); if (response.status === 201) { navigate("/signin"); } else { console.error( "Registration failed:", response.data.msg || "Unknown error" ); } } catch (error) { console.error("Error:", error.message || "Unknown error"); } }; return ( <Container> <h2>Create a new account</h2> <Form onSubmit={handleSubmit}> <Form.Group controlId="formName"> <Form.Label>Name:</Form.Label> <Form.Control type="text" name="name" placeholder="First Name" value={formData.name} onChange={handleChange} required /> </Form.Group> <Form.Group controlId="formEmail"> <Form.Label>Email:</Form.Label> <Form.Control type="text" name="email" placeholder="Email" value={formData.email} onChange={handleChange} required /> </Form.Group> <Form.Group controlId="formUsername"> <Form.Label>Username:</Form.Label> <Form.Control type="text" name="username" placeholder="Username" value={formData.username} onChange={handleChange} required /> </Form.Group> <Form.Group controlId="formPassword"> <Form.Label>Password:</Form.Label> <Form.Control type="password" name="password" placeholder="Password" value={formData.password} onChange={handleChange} required /> </Form.Group> <Button variant="primary" type="submit"> Submit </Button> </Form> </Container> ); } export default Register;
import { CHR_BANK_SIZE, PRG_BANK_SIZE } from "./const"; import { None, Option, Some } from "./types/option"; import { Result, Ok, Err } from "./types/result"; enum Mirroring { Horizontal, Vertical, } export interface Cartridge { title: Option<string>; trainer: ArrayBuffer; prg_banks: ArrayBuffer[]; chr_banks: ArrayBuffer[]; mirroring: Mirroring; mapper: number; } interface ParseError { message: string; } export function parse(rom: ArrayBuffer): Result<Cartridge, ParseError> { const view = new Uint8Array(rom); if ( view[0] !== 0x4e || view[1] !== 0x45 || view[2] !== 0x53 || view[3] !== 0x1a ) { return new Err({ message: "Invalid header", }); } const trainerPresent = !!(view[6] & 0x06); const mirroring = view[6] & 0x01 ? Mirroring.Vertical : Mirroring.Horizontal; const mapper = (view[7] >> 4) | (view[6] & 0x0f); const n_prg_banks = view[4]; const n_chr_banks = view[5]; const prg_banks = []; const chr_banks = []; let ptr = trainerPresent ? 528 : 16; for (let i = 0; i < n_prg_banks; i++) { const bank = rom.slice(ptr, ptr + PRG_BANK_SIZE); prg_banks.push(bank); ptr += PRG_BANK_SIZE; } for (let i = 0; i < n_chr_banks; i++) { const bank = rom.slice(ptr, ptr + CHR_BANK_SIZE); chr_banks.push(bank); ptr += CHR_BANK_SIZE; } ptr += 8224; const title = ptr < rom.byteLength ? new Some(String.fromCharCode(...view.slice(ptr, ptr + 21))) : new None(); return new Ok({ title, trainer: trainerPresent ? rom.slice(16, 528) : new ArrayBuffer(0), prg_banks, chr_banks, mirroring, mapper, }); }
<template> <div class="row no-gutters"> <div class="card w-100"> <div class="cards_panel_header d-flex align-items-center"> Usuários <input class="form-control col-4 form-control-sm ml-auto" v-model="filter" placeholder="Buscar" @input="keyPushSearch($event, filter)" /> <select class="form-control col-2 form-control-sm ml-3" v-model="type" > <option :value="0">Selecione um Tipo</option> <option :value="1">Área de Risco</option> <option :value="2">Área de Negócios</option> </select> <toggle-buttom-shared-component class="mt-2 ml-2" v-model="activeOnly"/> </div> <div class="pr-2 pl-2 pt-2"> <table class="table table-sm table-hover"> <thead class="fixed_head"> <tr> <th v-for="(header, h) in headers" :key="`head-[${h}]`" :class="checkOrderBy(keyOrder,header.keyOrder)" @click="genericOrderBy(users, header.keyOrder, toggleOrder = !toggleOrder, keyOrder, header.auxParameter)" > <span class="text_sm"> {{ header.title }} <b-icon-caret-down-fill v-if="checkOrderBy(!toggleOrder)"></b-icon-caret-down-fill> <b-icon-caret-up-fill v-else></b-icon-caret-up-fill> </span> </th> <th class="text_sm">Ativo</th> <th style="width: 200px"></th> </tr> </thead> <tbody> <tr v-for="(user, u) in filterDataPagination(filterDataListBySearch(filterByType))" :key="`body-users-[${u}|${user.id}]`" slot="tableBody"> <td><span class="text_sm">{{ user.racf }}</span></td> <td><span class="text_sm">{{ user.mapa }}</span></td> <td><span class="text_sm">{{ user.tipo | typeFilter }}</span></td> <td><toggle-buttom-shared-component :size="true" class="mt-1" v-model="user.active"/></td> <td > <button class="btn btn-sm btn-primary btn_extra_sm"> Editar </button> <button class="btn btn-sm btn-danger btn_extra_sm ml-1"> Delete </button> </td> </tr> </tbody> </table> </div> <div class="d-flex justify-content-center"> <b-pagination v-if="totalRows>perPage" class="pagination pagination-sm" v-model="currentPage" :total-rows="totalRows" :per-page="perPage" aria-controls="warp-table-adjust" align="fill" ></b-pagination> </div> </div> </div> </template> <script> import { Users } from '@/response/users' import { PaginationMixin } from '@/mixins/paginationMixin' import ToggleButtomSharedComponent from '@/components/shared/toggle-buttom-shared' export default { name: 'users-list-component', mixins:[PaginationMixin], components: { ToggleButtomSharedComponent }, computed: { filterByType() { if(this.type === 0) { return this.users } return this.users.filter(x => { if(x.tipo === this.type) { return x } }) } }, mounted() { this.users = Users }, watch: { }, data:() => ({ users: [], type: 0, headers: [ { title: "RACF", keyOrder: "racf", auxParameter: "", }, { title: "Mapa", keyOrder: "mapa", auxParameter: "", }, { title: "Tipo", keyOrder: "tipo", auxParameter: "", }, ], filter: "", activeOnly: true, txtSearch: [], currentPage: 1, totalRows: 0, toggleOrder: false, keyOrder: { value: '' }, perPage: 8, timerSearch: () => {}, isLoadingSave: false }), methods: { }, filters: { typeFilter(val) { if(val == 1) { return "Área de Risco" } return "Área de Negócios" } } } </script> <style scoped> .table { border: #ccc solid 1px; } </style>
package dropbox.webCrawler.multiThread; import dropbox.webCrawler.Crawler; import dropbox.webCrawler.HttpClient; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * @author jacka * @version 1.0 on 6/7/2021 */ public final class MultiThreadSolutionI implements Crawler { private final HttpClient client; private static final int MAX_THREADS = Runtime.getRuntime().availableProcessors(); private final ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS); private final Queue<Future<List<String>>> pendingTasks = new ArrayDeque<>(); private final Set<String> visited = Collections.newSetFromMap(new ConcurrentHashMap<>()); public MultiThreadSolutionI(final HttpClient client) { this.client = client; } @Override public List<String> crawl(String url) { submit(url); try { while (!pendingTasks.isEmpty()) { final Iterator<Future<List<String>>> itr = pendingTasks.iterator(); while (itr.hasNext()) { final Future<List<String>> toRemove = itr.next(); if (toRemove.isDone()) { itr.remove(); final List<String> children = toRemove.get(); for (final String c : children) { submit(c); } } } } } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { // shutdown } return new ArrayList<>(visited); } private void submit(final String url) { if (visited.add(url)) { final CrawlTask task = new CrawlTask(client, url); pendingTasks.add(executor.submit(task)); } } private static final class CrawlTask implements Callable<List<String>> { private final HttpClient client; private final String url; private CrawlTask(final HttpClient client, final String url) { this.client = client; this.url = url; } @Override public List<String> call() throws Exception { return client.getChildUrls(url); } } }
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui.qs.pipeline.domain.autoaddable import com.android.systemui.dagger.SysUISingleton import com.android.systemui.qs.pipeline.domain.model.AutoAddSignal import com.android.systemui.qs.pipeline.shared.TileSpec import com.android.systemui.qs.tiles.CastTile import com.android.systemui.statusbar.policy.CastController import javax.inject.Inject import kotlinx.coroutines.channels.ProducerScope /** * [AutoAddable] for [CastTile.TILE_SPEC]. * * It will send a signal to add the tile when there's a casting device connected or connecting. */ @SysUISingleton class CastAutoAddable @Inject constructor( private val controller: CastController, ) : CallbackControllerAutoAddable<CastController.Callback, CastController>(controller) { override val spec: TileSpec get() = TileSpec.create(CastTile.TILE_SPEC) override fun ProducerScope<AutoAddSignal>.getCallback(): CastController.Callback { return CastController.Callback { val isCasting = controller.castDevices.any { it.state == CastController.CastDevice.STATE_CONNECTED || it.state == CastController.CastDevice.STATE_CONNECTING } if (isCasting) { sendAdd() } } } override val description = "CastAutoAddable ($autoAddTracking)" }
// // ContentView.swift // Flashzilla // // Created by Dominik Hofer on 28.09.22. // import SwiftUI extension View { func stacked(at position: Int, in total: Int) -> some View { let offset = Double(total - position) return self.offset(x: 0, y: offset * 10) } } struct ContentView: View { @Environment(\.accessibilityDifferentiateWithoutColor) var differentiateWithoutColor @Environment(\.accessibilityVoiceOverEnabled) var voiceOverEnabled @Environment(\.scenePhase) var scenePhase @State private var cards = [Card]() @State private var timeRemaining = 100 @State private var isActive = true @State private var showingEditScreen = false let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect() var body: some View { ZStack { Image("background") .resizable() .ignoresSafeArea() VStack { Text("Time: \(timeRemaining)") .font(.largeTitle) .foregroundColor(.white) .padding(.horizontal, 20) .padding(.vertical, 5) .background(.black.opacity(0.75)) .clipShape(Capsule()) ZStack { ForEach(cards) { card in if let index = cards.firstIndex(of: card) { CardView(card: card) { withAnimation { removeCard(at: index) } } wrongRemoval: { withAnimation { removeCard(at: index, addToEnd: true) } } .stacked(at: index, in: cards.count) .allowsHitTesting(index == cards.count - 1) .accessibilityHidden(index < cards.count - 1) } } } .allowsHitTesting(timeRemaining > 0) if cards.isEmpty { Group { Button("Start Again", action: resetCards) .padding() .background(.white) .foregroundColor(.black) .clipShape(Capsule()) } .padding(.top) } } VStack { HStack { Spacer() Button { showingEditScreen = true } label: { Image(systemName: "plus.circle") .padding() .background(.black.opacity(0.7)) .clipShape(Circle()) } } Spacer() } .foregroundColor(.white) .font(.largeTitle) .padding() if differentiateWithoutColor || voiceOverEnabled { VStack { Spacer() HStack { Button { withAnimation { removeCard(at: cards.count - 1, addToEnd: true) } } label: { Image(systemName: "xmark.circle") .padding() .background(.black.opacity(0.7)) .clipShape(Circle()) } .accessibilityLabel("Wrong") .accessibilityHint("Mark your answer as being incorrect.") Spacer() Button { withAnimation { removeCard(at: cards.count - 1) } } label: { Image(systemName: "checkmark.circle") .padding() .background(.black.opacity(0.7)) .clipShape(Circle()) } .accessibilityLabel("Correct") .accessibilityHint("Mark your answer as being correct.") } .foregroundColor(.white) .font(.largeTitle) .padding() } } } .onReceive(timer) { time in guard isActive else { return } if timeRemaining > 0 { timeRemaining -= 1 } } .onChange(of: scenePhase) { newValue in if newValue == .active { if cards.isEmpty == false { isActive = true } } else { isActive = false } } .sheet(isPresented: $showingEditScreen, onDismiss: resetCards, content: EditCards.init) .onAppear(perform: resetCards) } func removeCard(at index: Int, addToEnd: Bool = false) { guard index >= 0 else { return } let tempCard = cards[index] cards.remove(at: index) if addToEnd { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { cards.insert(tempCard, at: 0) } } if cards.isEmpty { isActive = false } } func resetCards() { timeRemaining = 100 isActive = true loadData() } func loadData() { if let data = UserDefaults.standard.data(forKey: "Cards") { if let decoded = try? JSONDecoder().decode([Card].self, from: data) { cards = decoded } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
float[] price; float minPrice, maxPrice; float x1, y1, x2, y2; int[] mm; PFont legendFont = createFont("SansSerif",20); void setup( ) { size(800,600, P3D); x1 = 50; y1= 50; x2= width -50; y2 = height - y1; smooth(); textFont(legendFont); String[] lines = loadStrings("aapl.txt"); price = new float[lines.length]; //println(price); mm = new int[lines.length]; for(int i = 0; i < lines.length; i++){ String[] pieces = split(lines[i],","); price[i]= float(pieces[5]); mm[i] = int(pieces[0]); } println("Data loaded: "+price.length+" entries."); minPrice = min(price); maxPrice = max(price); println("Min: "+minPrice); println("Max: "+maxPrice); } void draw( ) { background(0); rectMode(CORNERS); noStroke(); fill(255); rect(x1,y1,x2,y2); drawGraph(price,minPrice,maxPrice); //título fill(255); textSize(18); textAlign(LEFT); text("(AAPL) Apple Inc. 2016",x1,y1-10); textSize(10); textAlign(RIGHT,BOTTOM); text("Fuente: google finance (google.com/finance)", width-10, height-10); //banderas de los ejes drawXLabels(); drawYLabels(); } //función drawYLabels void drawYLabels( ) { fill(255); textSize(10); textAlign(RIGHT); stroke(255); for(float i = minPrice ; i < maxPrice; i+=2){ float y = map(i,minPrice,maxPrice,y2,y1) ; text(floor(i),x1-10,y); line(x1,y,x1-5,y); } textSize(18); text("$",x1-40,height/2); } //función drawXLabels void drawXLabels( ) { fill(255); textSize(10); textAlign(CENTER); int m = 0; for (int i=0; i<mm.length; i++) { if (mm[i] == m) continue; m = mm[i]; float x = map(i, 0, mm.length, x1, x2); text(m, x, y2+10); strokeWeight(0.3); line(x, y2, x, y1); } textSize(18); textAlign(CENTER, TOP); text("Mes", width/2, y2+10); } void drawGraph(float[]data , float yMin, float yMax ) { stroke(0); beginShape(); for(int i=0; i<data.length; i++){ float x = map(i,0,data.length-1, x1, x2); float y = map(data[i], yMin, yMax, y1,y2) ; vertex(x,y); } endShape(); }
import React, { useEffect, useReducer, useState } from "react"; import { StyleSheet, View } from "react-native"; import { Button, DataTable, IconButton } from "react-native-paper"; import HeaderBar from "../components/HeaderBar"; import { lampInfos } from "../apis/mock"; import LampAddModal from "../components/LampAddModal"; import axios from "axios"; import LampEditModal from "../components/LampEditModal"; import { useDeleteLampMutation, useGetLampsQuery } from "../apis/apis"; const Setting = ({ navigation }: any) => { const [page, setPage] = useState<number>(0); const [numberOfItemsPerPageList] = useState([2, 3, 4, 6]); const [itemsPerPage, onItemsPerPageChange] = useState( numberOfItemsPerPageList[3] ); const [visible, setVisible] = useState(false); const [editVisible, setEditVisible] = useState(false); const [items, setItems] = useState(lampInfos); const [selectedItem, setSelectedItem] = useState<any>(); const from = page * itemsPerPage; const to = Math.min((page + 1) * itemsPerPage, items.length); const { data: lamps } = useGetLampsQuery({ status: null }); const { mutate: deleteLamp } = useDeleteLampMutation(); useEffect(() => { setPage(0); }, [itemsPerPage]); useEffect(() => { if (!selectedItem) return; console.log(selectedItem); setEditVisible(true); }, [selectedItem]); useEffect(() => { if (!lamps) return; setItems(lamps); }, [lamps]); return ( <View style={styles.container}> <HeaderBar navigation={navigation} backScreen={"Main"} title={"가로등 관리"} /> <View style={{ marginTop: 20, display: "flex", flexDirection: "row", justifyContent: "flex-end", marginHorizontal: 15, }} > <Button style={{ width: 80 }} buttonColor="rgb(120, 69, 172)" textColor="white" mode="contained-tonal" onPress={() => { setVisible(true); }} > 추가 </Button> </View> <DataTable> <DataTable.Header> <DataTable.Title>No.</DataTable.Title> <DataTable.Title>가로등명</DataTable.Title> <DataTable.Title numeric>관리</DataTable.Title> </DataTable.Header> {items.slice(from, to).map((item, index) => { return ( <DataTable.Row key={item.lampName} onPress={() => { setSelectedItem(item); }} > <DataTable.Cell>{index + 1}</DataTable.Cell> <DataTable.Cell>{item.lampName}</DataTable.Cell> <DataTable.Cell numeric> <Button mode="contained-tonal" buttonColor="lightpink" onPress={() => { if (!item._id) return; deleteLamp(item._id); }} > 삭제 </Button> </DataTable.Cell> </DataTable.Row> ); })} <DataTable.Pagination page={page} numberOfPages={Math.ceil(items.length / itemsPerPage)} onPageChange={(page) => setPage(page)} label={`${from + 1}-${to} of ${items.length}`} numberOfItemsPerPageList={numberOfItemsPerPageList} numberOfItemsPerPage={itemsPerPage} onItemsPerPageChange={onItemsPerPageChange} showFastPaginationControls selectPageDropdownLabel={"Rows per page"} /> </DataTable> <LampAddModal visible={visible} setVisible={setVisible} /> <LampEditModal visible={editVisible} setVisible={setEditVisible} lampData={selectedItem} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#fff", }, }); export default Setting;
import axios from "axios"; import { config } from "dotenv"; config(); const CLIENT_ID = process.env.client_id; const CLIENT_SECRET = process.env.client_secret; const BASE_ENDPOINT = `https://api.spotify.com/v1/`; const AUTHORIZE_ENDPOINT = "https://accounts.spotify.com/api/token"; function getEndpoint(ext) { return `${BASE_ENDPOINT}${ext}`; } async function callEndpoint(endpoint, access_token) { let data = undefined; try { data = await axios.get(endpoint, { headers: { Authorization: `Bearer ${access_token}` } }); return data; } catch (e) { console.log(e); } } async function callTopEndpoint(endpoint, time_range, limit, access_token) { let data = undefined; const authOptions = { url: endpoint, headers: { Authorization: `Bearer ${access_token}`, }, params: { limit: limit, time_range: time_range }, }; try { data = await axios.get(authOptions.url, { headers: authOptions.headers, params: authOptions.params }); return data; } catch (e) { console.log(e); } } async function callRecsEndpoint(endpoint, opt_params, access_token) { let data = undefined; let { limit, seed_tracks, seed_artists, seed_genres } = opt_params; const authOptions = { url: endpoint, headers: { Authorization: `Bearer ${access_token}`, }, params: { limit: limit, seed_tracks: seed_tracks, // required seed_artists: seed_artists, // required seed_genres: seed_genres // required }, }; try { data = await axios.get(authOptions.url, { headers: authOptions.headers, params: authOptions.params }); return data; } catch (e) { console.log(e); } } async function callRecentEndpoint(endpoint, limit, access_token) { let data = undefined; const authOptions = { url: endpoint, headers: { Authorization: `Bearer ${access_token}`, }, params: { limit: limit, }, }; try { data = await axios.get(authOptions.url, { headers: authOptions.headers, params: authOptions.params }); return data; } catch (e) { console.log(e); } } export { getEndpoint, callEndpoint, callTopEndpoint, callRecsEndpoint, callRecentEndpoint }
import { INPUT } from './input.ts'; const TEST1: string = `[({(<(())[]>[[{[]{<()<>> [(()[<>])]({[<{<<[]>>( {([(<{}[<>[]}>{[]{[(<()> (((({<>}<{<{<>}{[]{[]{} [[<[([]))<([[{}[[()]]] [{[{({}]{}}([{[{{{}}([] {<[[]]>}<{[{[{[]{()[[[] [<(<(<(<{}))><([]([]() <{([([[(<>()){}]>(<<{{ <{([{{}}[<[[[<>{}]]]>[]]`; function doPart(input: string): string | number { const lines: string[] = input.split('\n').map(s => s); const openBrackets: Set<string> = new Set<string>(['[', '{', '<', '(']); const bracketMap: Map<string, string> = new Map([ [']', '['], ['}', '{'], ['>', '<'], [')', '('], ]); const pointsMap: Map<string, number> = new Map<string, number>([ [')', 3], [']', 57], ['}', 1197], ['>', 25137], ]); return lines.reduce((p,l) => { let points: number = 0; const stack: string[] = []; for (let i: number = 0; i < l.length; i++) { const v: string = l[i]; if (openBrackets.has(v)) { stack.push(v); } else { const onStack: string | undefined = stack.pop(); if (bracketMap.get(v) !== onStack) { points += pointsMap.get(v)!; break; } } } return p + points; }, 0); } function go(input: string, expected?: number | string): void { const result: number | string = doPart(input); console.log(`--> ${result} <--`); console.assert(!expected || result === expected, 'got: %s, expected: %s', result, expected); } void (() => { go(TEST1, 26397); go(INPUT); })();
<?xml version="1.0" encoding="utf-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" xml:lang="en" lang="en"> <head> <meta charset="utf-8"/> <title>Infra-red spectroscopy</title> <link rel="stylesheet" href="../styles/stylesheet.css" type="text/css"/> <script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> </head> <body> <a id="page_23" class="page" style="width:70%;">Page 23, Infra-red spectroscopy</a> <section epub:type="chapter" id="ch03"> <h1 class="main"><b>3</b><span class="space">&#160;</span> <b>Infra-red spectroscopy</b></h1> <p class="noindent">Infra-red (i.r.) radiation is the term used to describe electromagnetic radiation with frequencies and energies somewhat lower than those associated with visible light; it is emitted as a range of frequencies from a heated object (sometimes together with visible radiation). When a beam of i.r. is incident upon a collection of certain molecules, absorption of discrete frequencies by the molecules takes place, corresponding to the absorption of well-defined amounts of <i>energy</i> from the range of energies in the radiation. This is the basis of i.r. absorption spectroscopy.</p> <p class="indent">Two main applications of i.r. spectroscopy provide important structural information about molecules. The first is the study of simple molecules (diatomic and triatomic) in the gas phase; the exact amounts of energy absorbed from the i.r. radiation are related to increases in the rotational and vibrational energy of the molecules. It is possible to determine <i>bond lengths</i> and also <i>force constants</i> (a measure of the resistance to stretching).</p> <p class="indent">The second application of i.r. involves the recognition of the <i>structures</i> of more complicated molecules from their characteristic absorptions. As with mass spectrometry and n.m.r. spectroscopy (<a href="chapter5.xhtml">Chapter 5</a>), i.r. can be used to indicate the nature of the functional groups in a molecule, and, by comparison with spectra from known compounds, to aid identification of an unknown material.</p> <section epub:type="chapter" id="sec_3.1"> <h2 class="h2"><b>3.1</b><span class="space">&#160;</span><b>Pure rotation i.r. spectra of small molecules</b></h2> <p class="noindent">For gaseous diatomic molecules, an absorption of i.r. radiation is only possible if the molecule has a <b>dipole moment.</b> This occurs when the two atoms are chemically different (e.g. HF), such that an unequal sharing of electrons leads to an asymmetric distribution of electron density.</p> <p class="indent">The molecule is rotating, both about an axis along the bond and also about an axis through the centre of gravity and perpendicular to the bond (<a href="#fig_3.1">Fig. 3.1</a>). The latter motion gives rise to a fluctuating electric field which enables this type of molecule to interact with the fluctuating electric field of the incoming radiation and hence, by absorbing energy from the radiation, to increase its rotational energy. Molecules without dipoles rotate in similar fashion, but do not interact in this way with incident radiation.</p> <p class="indent"><a href="#fig_3.2">Fig. 3.2</a> shows the spectrum obtained when radiation with wavenumber &#x1FE1; in the 0&#x2013;300 cm<sup>&#x2013;1</sup> range is incident upon a gaseous sample of HF; there are several absorptions of energy, recognized by the downward peaks, at characteristic wavenumbers (i.e. at certain exact energies), and the separation between the lines is approximately constant (40.5 cm<sup>&#x2013;1</sup>). Similar spectra, but with different separations, are obtained for other heteronuclear diatomic molecules (for HCl, the spacing is 20.7 cm<sup>&#x2013;1</sup>).</p> <a id="page_24" class="page" style="width:70%;">Page 24, Infra-red spectroscopy</a> <aside class="abc" style="margin-left:0em;margin-top:-20em;" epub:type="sidebar"> <figure class="fig2" id="fig_3.1"> <img src="../images/f0023-01.jpg" alt="images"/> <figcaption> <p class="noindent2"><b>Fig. 3.1</b> Simple model for the rotational motion of a diatomic molecule</p> </figcaption> </figure> </aside> <figure class="fig1a" id="fig_3.2"> <img src="../images/f0024-01.jpg" alt="images"/> <figcaption> <p class="figurecaption2"><b>Fig. 3.2</b> Rotational i.r. absorption spectrum (in the range <i>&#x1FE1;</i> 0&#x2013;300 cm<sup>&#x2013;1</sup>) for gaseous hydrogen fluoride, HF</p> </figcaption> </figure> <p class="indent">The explanation for the appearance of the spectrum is as follows. For a molecule which consists of two masses <i>m</i><sub>1</sub> and <i>m</i><sub>2</sub> and a bond length <i>r</i><sub>0</sub>, the only allowed values for the rotational energy (E<sub>rot</sub>) are given by <a href="#eqn_3.1">eqn 3.1</a> where <i>h</i> is Planck&#x2019;s constant (6.626 &#x00D7; 10<sup>&#x2013;34</sup> J s), <i>I</i> is the <i>moment of inertia</i> for rotation about the axis indicated in <a href="#fig_3.1">Fig. 3.1</a> ( given by [<i>m</i><sub>1</sub><i>m</i><sub>2</sub>/(<i>m</i><sub>1</sub> <b>&#x002B;</b> <i>m</i><sub>2</sub>)]<i>r</i><sub>0</sub><sup>2</sup>). <i>J</i> is a <i>quantum number</i>, with the allowed values of 0,1,2,3... Only certain rotational energy levels (<i>E</i><sub>rot</sub>) for the molecule are allowed, because the quantum number is restricted to certain values: the energy levels are indicated in <a href="#fig_3.3">Fig. 3.3</a>. Each molecule at any moment must be in one of these energy levels, and since the energy separations between the levels are small, all the levels indicated will be fairly well populated (the distribution of molecules amongst energy levels is discussed later).</p> <aside class="abc" style="margin-left:0em;margin-top:-12em;" epub:type="sidebar"> <p class="noindent" id="eqn_3.1"> <math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <msub> <mtext>E</mtext> <mrow> <mtext>rot</mtext> </mrow> </msub> <mtext>&#x2009;</mtext><mo>=</mo><mtext>&#x2009;</mtext><mfrac> <mrow> <msup> <mi>h</mi> <mn>2</mn> </msup> <mtext>&#x2009;</mtext><mtext>J</mtext><mo stretchy='false'>(</mo><mi>J</mi><mo>+</mo><mn>1</mn><mo stretchy='false'>)</mo> </mrow> <mrow> <mn>8</mn><mtext>&#x2009;</mtext><msup> <mi>&#x03C0;</mi> <mn>2</mn> </msup> <mtext>&#x2009;</mtext><mi>l</mi> </mrow> </mfrac> </mrow> </math> </p> <p class="noindent2" style="text-align:right;margin-top:-1.5em;">(3.1)</p> </aside> <p class="indent">A molecule can increase its rotational energy by being promoted from one level to the next level (i.e. &#x0394;<i>J</i> &#x003D; 1) if <i>exactly</i> the correct amount of energy is incident upon it. Thus, those specific wavenumbers whose energies correspond to the changes of energy from <i>J</i> &#x003D; 0 to <i>J</i> &#x003D; 1 (by molecules in the <i>J</i> &#x003D; 0 level), or from <i>J</i> &#x003D; 1 to <i>J</i> &#x003D; 2 (by molecules in the <i>J</i> &#x003D; 1 level), etc., are absorbed from the incoming radiation.</p> <p class="indent">For an allowed transition, <i>J</i> &#x2192; <i>J</i>&#x2032; the energy change involved can be written:</p> <p class="indent" style="margin-bottom:1em;margin-top:1em;margin-left:8em;"><math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <mi>&#x0394;</mi><msub> <mi>E</mi> <mrow> <mtext>rot</mtext> </mrow> </msub> <mo>&#160;=</mo><mfrac> <mrow> <msup> <mi>h</mi> <mn>2</mn> </msup> </mrow> <mrow> <mn>8</mn><msup> <mi>&#x03C0;</mi> <mn>2</mn> </msup> <mi>I</mi> </mrow> </mfrac> <mtext>&#x2009;</mtext><mrow><mo>[</mo> <mrow> <msup> <mi>J</mi> <mo>&#x2032;</mo> </msup> <mtext>&#x2009;</mtext><mo stretchy='false'>(</mo><msup> <mi>J</mi> <mo>&#x2032;</mo> </msup> <mo>+</mo><mn>1</mn><mo stretchy='false'>)</mo><mo>&#x2212;</mo><mo stretchy='false'>(</mo><mi>J</mi><mo>+</mo><mn>1</mn><mo stretchy='false'>)</mo> </mrow> <mo>]</mo></mrow> </mrow> </math> </p> <p class="noindent">and therefore, since &#x0394;<i>J = </i> 1 (i.e. <i>J</i> &#x2032; &#x003D; <i>J</i> &#x002B; 1) then:</p> <p class="indent" id="eqn_3.2" style="margin-bottom:1em;margin-top:1em;margin-left:8em;"><math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <mi>&#x0394;</mi><msub> <mi>E</mi> <mrow> <mtext>rot</mtext> </mrow> </msub> <mtext>&#160;=&#160;2</mtext><msup> <mi>J</mi> <mo>&#x2032;</mo> </msup> <mtext>&#x2009;</mtext><mrow><mo>(</mo> <mrow> <mfrac> <mrow> <msup> <mi>h</mi> <mn>2</mn> </msup> </mrow> <mrow> <mn>8</mn><msup> <mi>&#x03C0;</mi> <mn>2</mn> </msup> <mi>I</mi> </mrow> </mfrac> </mrow> <mo>)</mo></mrow><mtext>&#x2009;</mtext><mtext>&#x0009;</mtext><mo stretchy='false'></mo><mn>&#160;</mn><mo stretchy='false'></mo> </mrow> </math> </p> <p class="indent" style="text-align:right;margin-top:-3em;">(3.2)</p> <a id="page_25" class="page" style="width:70%;">Page 25, Infra-red spectroscopy</a> <figure class="fig1a" id="fig_3.3"> <img src="../images/f0025-01.jpg" alt="images"/> <figcaption> <p class="figurecaption2"><b>Fig. 3.3</b> Lowest rotational energy levels for a diatomic molecule, showing the allowed transitions; <i>J</i> is the rotational quantum number</p> </figcaption> </figure> <p class="noindent">where <i>J</i> &#x2032; is the quantum number for the upper state. The energies of the transitions from the lowest levels are as follows:</p> <table style="width:40%;margin-bottom:0.9em;margin-top:0.9em;margin-left:8em;"> <tr><td><i>Transition</i></td><td><i>Energy change</i></td></tr> <tr><td style="padding-top:0.9em;">0 &#x2192; 1</td><td style="padding-top:0.5em;"><math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow><mo>(</mo> <mrow> <mfrac> <mrow> <msup> <mi>h</mi> <mn>2</mn> </msup> </mrow> <mrow> <mn>8</mn><msup> <mi>&#x03C0;</mi> <mn>2</mn> </msup> <mi>I</mi> </mrow> </mfrac> </mrow> <mo>)</mo></mrow><mo>&#x00D7;</mo><mn>2</mn> </math></td></tr> <tr><td style="padding-top:0.9em;">1 &#x2192; 2</td><td style="padding-top:0.5em;"><math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow><mo>(</mo> <mrow> <mfrac> <mrow> <msup> <mi>h</mi> <mn>2</mn> </msup> </mrow> <mrow> <mn>8</mn><msup> <mi>&#x03C0;</mi> <mn>2</mn> </msup> <mi>I</mi> </mrow> </mfrac> </mrow> <mo>)</mo></mrow><mo>&#x00D7;</mo><mn>4</mn> </math> </td></tr> <tr><td style="padding-top:0.9em;">2 &#x2192; 3</td><td style="padding-top:0.5em;"><math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow><mo>(</mo> <mrow> <mfrac> <mrow> <msup> <mi>h</mi> <mn>2</mn> </msup> </mrow> <mrow> <mn>8</mn><msup> <mi>&#x03C0;</mi> <mn>2</mn> </msup> <mi>I</mi> </mrow> </mfrac> </mrow> <mo>)</mo></mrow><mo>&#x00D7;</mo><mn>6</mn> </math> </td></tr> </table> <p class="indent">This means that transitions from successive energy levels to the levels above them are associated with energy changes (&#x0394;<i>&#x0395;</i>) which have steadily increasing values (an increment of 2<i>h</i><sup>2</sup>/8<i>&#x03C0;</i><sup>2</sup><i>I</i>). This is exactly what is observed in the spectrum: thus, for HF, molecules undergoing the 0 &#x2192; 1 transition absorb energy corresponding to a wavenumber of about 40 cm<sup>&#x2013;1</sup>; for molecules undergoing the 1 &#x2192; 2 transition &#x2206;&#x1FE1; is about 80 cm<sup>&#x2013;1</sup>; for the 2 &#x2192; 3 transition &#x2206;&#x1FE1; is about 120 cm<sup>&#x2013;1</sup>, and so on.</p> <section epub:type="chapter"> <h3 class="h3"><b>Calculation of the bond length of HF</b></h3> <p class="noindent">The difference (&#x2206;&#x1FE1;) between two successive rotational lines is 40.5 cm<sup>&#x2013;1</sup>, i.e. &#x0394;<i>&#x03BD;</i> &#x003D; 1.22 &#x00D7; 10<sup>12</sup> Hz. Since <i>E</i> &#x003D; <i>hv</i>, we can convert &#x0394;<i>v</i> to the appropriate energy difference (by multiplication by Planck&#x2019;s constant). The result must equal (2<i>h</i><sup>2</sup>/8<i>&#x03C0;</i><sup>2</sup><i>I</i>), as shown above. From this calculation <i>I</i> and <i>r</i><sub>0</sub> can be obtained.</p> <a id="page_26" class="page" style="width:70%;">Page 26, Infra-red spectroscopy</a> <p class="indent" style="margin-left:6em;margin-top:0em;"><math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <mi>&#x0394;</mi><mi>E</mi><mtext>&#x2009;</mtext><mo>=</mo><mtext>&#x2009;</mtext><mi>h</mi><mi>&#x0394;</mi><mi>v</mi><mtext>&#x2009;</mtext><mo>=</mo><mtext>&#x2009;</mtext><mfrac> <mrow> <mn>2</mn><msup> <mi>h</mi> <mn>2</mn> </msup> </mrow> <mrow> <mn>8</mn><msup> <mi>&#x03C0;</mi> <mn>2</mn> </msup> <mi>I</mi> </mrow> </mfrac> </mrow> </math> </p> <p class="indent" style="margin-left:6.8em;margin-top:0em;"><math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <mi>I</mi><mtext>&#x2009;</mtext><mo>=</mo><mtext>&#x2009;</mtext><mfrac> <mi>h</mi> <mrow> <mn>4</mn><msup> <mi>&#x03C0;</mi> <mn>2</mn> </msup> <mtext>&#x2009;</mtext><mi>&#x0394;</mi><mi>v</mi> </mrow> </mfrac> <mtext>&#x2009;</mtext><mo>=</mo><mtext>&#x2009;</mtext><mfrac> <mrow> <mn>6.626</mn><mtext>&#x2009;</mtext><mo>&#x00D7;</mo><mtext>&#x2009;</mtext><msup> <mrow> <mn>10</mn> </mrow> <mrow> <mo>&#x2212;</mo><mn>34</mn> </mrow> </msup> </mrow> <mrow> <mn>4</mn><msup> <mi>&#x03C0;</mi> <mn>2</mn> </msup> <mtext>&#x2009;</mtext><mo>&#x00D7;</mo><mtext>&#x2009;</mtext><mn>1.22</mn><mtext>&#x2009;</mtext><mo>&#x00D7;</mo><msup> <mrow> <mn>10</mn> </mrow> <mrow> <mn>12</mn> </mrow> </msup> </mrow> </mfrac> </mrow> </math> </p> <p class="indent" style="margin-left:7.7em;margin-top:0.5em;">= 1.376 &#215; 10<sup>&#8211;47</sup> kg m<sup>2</sup> (or J s<sup>2</sup>)</p> <p class="noindent">Now, since</p> <p class="indent" id="eqn_3.3" style="margin-left:8em;margin-bottom:1em;margin-top:1em;"><math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <mi>I</mi><mo>&#160;=&#160;</mo><mrow><mo>(</mo> <mrow> <mfrac> <mrow> <msub> <mi>m</mi> <mn>1</mn> </msub> <msub> <mi>m</mi> <mn>2</mn> </msub> </mrow> <mrow> <msub> <mi>m</mi> <mn>1</mn> </msub> <mo>+</mo><msub> <mi>m</mi> <mn>2</mn> </msub> </mrow> </mfrac> </mrow> <mo>)</mo></mrow><msubsup> <mi>r</mi> <mn>0</mn> <mn>2</mn> </msubsup> <mtext>&#x0009;&#160;</mtext> </mrow> </math> </p> <p class="indent" style="text-align:right;margin-top:-2.7em;">(3.3)</p> <p class="noindent" style="margin-top:0.9em;">where <i>m</i><sub>1</sub> is the mass of the hydrogen atom, and <i>m</i><sub>2</sub> is the mass of the fluorine atom, so that <i>m</i><sub>1</sub> = <math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <mfrac> <mn>1</mn> <mrow> <msup> <mrow> <mn>10</mn> </mrow> <mn>3</mn> </msup> <mo>&#x00D7;</mo><mi>L</mi> </mrow> </mfrac> <mtext>&#x2009;</mtext><mtext>Kg,</mtext><mtext>&#160;</mtext><mtext>&#x2009;</mtext><msub> <mi>m</mi> <mn>2</mn> </msub> <mtext>&#x2009;</mtext><mo>=</mo><mtext>&#x2009;</mtext><mfrac> <mrow> <mn>19</mn> </mrow> <mrow> <msup> <mrow> <mn>10</mn> </mrow> <mn>3</mn> </msup> <mo>&#x00D7;</mo><mi>L</mi> </mrow> </mfrac> <mtext>Kg,</mtext> </mrow> </math> where <i>L</i> is the Avogadro Constant (6.023 &#x00D7; 10<sup>23</sup> mol<sup>&#x2013;1</sup>), then,</p> <p class="indent" style="margin-left:6em;margin-bottom:0.9em;margin-top:0.9em;"><math xmlns="http://www.w3.org/1998/Math/MathML"> <mtable columnalign='left'> <mtr> <mtd> <msubsup> <mi>r</mi> <mn>0</mn> <mn>2</mn> </msubsup> <mtext>&#160;=&#160;1.376&#x00D7;</mtext><msup> <mn>10</mn> <mrow> <mo>&#x2212;</mo><mn>47</mn> </mrow> </msup> <mo>&#x00D7;</mo><mtext>&#x2009;</mtext><mfrac> <mrow> <mn>20</mn> </mrow> <mrow> <mn>19</mn> </mrow> </mfrac> <mo>&#x00D7;</mo><mn>6.023</mn><mo>&#x00D7;</mo><msup> <mn>10</mn> <mrow> <mn>26</mn> </mrow> </msup> <mtext>&#160;=&#160;0.872&#x00D7;</mtext><msup> <mn>10</mn> <mrow> <mo>&#x2212;</mo><mn>20</mn> </mrow> </msup> <msup> <mtext>m</mtext> <mn>2</mn> </msup> </mtd> </mtr> <mtr> <mtd> <msub> <mi>r</mi> <mn>0</mn> </msub> <mo>&#160;=&#160;</mo><msup> <mn>0.9310</mn> <mo>&#x2212;</mo> </msup> <msup> <mrow></mrow> <mrow> <mn>10</mn> </mrow> </msup> <mtext>&#x2009;</mtext><mtext>m</mtext><mo>&#160;=&#160;</mo><mn>0.093</mn><mtext>&#x2009;</mtext><mtext>nm</mtext> </mtd> </mtr> </mtable> </math> </p> <p class="noindent">In this way the bond lengths (<i>r</i><sub>0</sub>) of a variety of heteronuclear diatomic molecules can be measured (see <a href="#tab_3.1">Table 3.1</a>).</p> <aside class="abc" style="margin-left:0em;margin-top:-4em;" epub:type="sidebar"> <p class="tablecaption"><a id="tab_3.1"></a><b>Table 3.1</b> Bond lengths/nm for diatomic molecules determined from rotational spectra</p> <table style="border-collapse:collapse;width:90%;"> <tr><td style="border-top:1pt solid black;">HF</td> <td style="border-top:1pt solid black;">0.093</td></tr> <tr><td>HCl</td> <td>0.127</td></tr> <tr><td>HBr</td> <td>0.141</td></tr> <tr><td style="border-bottom:1pt solid black;">HI</td> <td style="border-bottom:1pt solid black;">0.160</td></tr> </table> </aside> <p class="indent">In practice, the experiments are most accurately carried out with what is known as a <b>microwave</b> (rather than a far infra-red) source of radiation (the essential theory and the range of wavelengths employed is the same in the two cases, although the experimental arrangements differ somewhat). Bond lengths can then be estimated to within about 0.0005 nm. It should also be noted here that the molecules are not rigid but are actually vibrating (see later) so that the bond length measured is an <i>average</i> value. At higher rotational energy levels the average bond length also shows centrifugal distortion, and the spacings change slightly.</p> <p class="indent">This interpretation of the rotational spectrum of a diatomic molecule can be tested by employing an isotopie substitution method. The bond length in a molecule is an <i>electronic</i> property and should not be affected by isotopie substitution, so that <sup>1</sup>HF and <sup>2</sup>HF (deuterium fluoride) should have the same bond length. The spacing in the rotational i.r. spectrum for <sup>2</sup>HF is found to be approximately half that for <sup>1</sup>HF, which is just as expected from <a href="#eqn_3.2">eqns 3.2</a> and <a href="#eqn_3.3">3.3</a> (you are encouraged to check this calculation).</p> </section> <section epub:type="chapter"> <h3 class="h3"><b>Triatomic molecules</b></h3> <p class="noindent">Complications arise when a linear triatomic molecule (e.g. HCN) is investigated. A spectrum can be observed, since the molecule has a dipole moment, and the discrete energy absorptions correspond to quantized changes in the energy of rotation about an axis through the centre of gravity, perpendicular <a id="page_27" class="page">Page 27, Infra-red spectroscopy</a>to the bonds. However, the spacing in the spectrum leads only to a single moment of inertia, and this value cannot be used to derive <i>both</i> bond lengths, (<i>r</i><sub>CH</sub> and <i>r</i><sub>CN</sub> for this example). The problem can be solved, however, with the help of isotopie substitution; the spacing of the energy levels, and hence the moment of inertia is measured for <sup>2</sup>HCN, as well as for <sup>1</sup>HC&#x039D;. As the bond lengths are unaltered by isotopie substitution, there is enough information (two moments of inertia, known masses) for both <i>r</i><sub>CH</sub> and <i>r</i><sub>CN</sub> to be determined.</p> <aside class="abc" style="margin-left:0em;margin-top:-9em;" epub:type="sidebar"> <figure class="fig2"> <img src="../images/f0027-02.jpg" alt="images"/> </figure> </aside> <p class="noindent">For more complicated molecules, an analysis to give bond lengths and angles may be possible if there is some degree of symmetry (as well as a dipole moment). For example, from a study of trichloromethane (chloroform, CHCl<sub>3</sub>) the moment of inertia about an axis perpendicular to the C&#x2013;H bond can be determined (rotation about an axis along this bond leads to no change in dipole moment). Then, via experiments on isotopically labelled derivatives, these details of the structure can be established.</p> </section> </section> <section epub:type="chapter" id="sec_3.2"> <h2 class="h2"><b>3.2</b><span class="space">&#160;</span><b>Vibration&#x2013;rotation i.r spectra of small molecules</b></h2> <p class="noindent">Many molecules show, in addition to the absorptions in the microwave (far i.r.) region of the spectrum, characteristic absorptions in a higher-energy part of the i.r. region. Most commercial spectrometers are designed to operate in this range, with gaseous liquid and solid samples. In addition to the measurement of bond lengths for certain molecules, considerable extra information can then be obtained.</p> <section epub:type="chapter"> <h3 class="h3"><b>Infra-red spectrometer</b></h3> <figure class="fig1a" id="fig_3.4"> <img src="../images/f0027-01.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.4</b> Essential features of an i.r. spectrometer</p> </figcaption> </figure> <p class="noindent"><a href="#fig_3.4">Fig. 3.4</a> illustrates the essential features of a typical instrument. The radiation is emitted from a heated filament as a continuous range of frequencies (and hence wavelengths and wavenumbers) in the i.r. region. This radiation is then passed through the sample, which is contained in a cell with a path length, for a gas, of several centimetres, or, for a liquid sample, of up to 10<sup>&#x2013;2</sup> cm. The resulting radiation, from which some of the radiation at certain frequencies will have been absorbed by molecules in the sample, is then passed through a system of slits and mirrors to emerge as a collimated beam. A prism or <a id="page_28" class="page">Page 28, Infra-red spectroscopy</a>grating disperses the beam into components at different wavelengths (just as a prism splits up a beam of visible white light into different colours) and, depending on the orientation of the prism, radiation of separate wavelengths reaches the detector thermocouple. The detector monitors the radiation transmitted at different wavelengths and converts the radiant energy into an electrical signal. An automatic scan of frequency or wavenumber, against energy either absorbed or transmitted, is easily achieved. The prism and sample holders have to be transparent to i.r. radiation and are prepared from suitable inorganic salts (NaCl, KBr, CaF<sub>2</sub>, for example).</p> </section> <section epub:type="chapter"> <h3 class="h3"><b>The spectrum from hydrogen chloride</b></h3> <p class="noindent"><a href="#fig_3.5">Fig. 3.5</a> shows the absorption spectrum of gaseous HC1 in the wavenumber region 2600&#x2013;3100 cm<sup>&#x2013;1</sup>. The most important features to note are the regular spacings of about 20 cm<sup>&#x2013;1</sup> between adjacent lines and the fact that the spectrum is centred at about 2890 cm<sup>&#x2013;1</sup>. Lines from the isotopically different species <sup>1</sup>H<sup>35</sup>Cl and <sup>1</sup>H<sup>37</sup>Cl are not seen separately in this spectrum (see <a href="#page_31">page 31</a>).</p> <figure class="fig1a" id="fig_3.5"> <img src="../images/f0028-01.jpg" alt="images" style="margin-left:-7em;"/> <figcaption> <p class="figurecaption2"><b>Fig. 3.5</b> Vibration rotation i.r. spectrum (&#x1FE1; 2600&#x2013;3100 cm<sup>&#x2013;1</sup>) of gaseous hydrogen chloride, HCl</p> </figcaption> </figure> </section> <section epub:type="chapter"> <h3 class="h3"><b>Analysis of the spectrum</b></h3> <p class="noindent">The behaviour of hydrogen chloride can be understood in terms of the molecule having <b>vibrational</b> energy (again, in well-defined amounts, or <b>quanta</b>) as well as rotational energy. For molecules with a dipole moment (e.g. HCl) this vibration allows interaction with the incident radiation, and hence energy can be absorbed: radiation of the appropriate energy (greater than that required for changes in the rotational energy) raises the molecule from its lowest <i>vibrational</i> energy state to the first excited vibrational state. The rotational energy can also change, which accounts for the many lines observed. This is now explained in more detail.</p> <p class="indent">The quantum theory predicts that only certain vibrational energies <i>E</i><sub>vib</sub> (<a href="#eqn_3.4">eqn 3.4</a>) are allowed, where <b>v</b> is a quantum number, with possible values 0, 1, 2 etc. and <i>v</i><sub>0</sub> is called the <b>fundamental frequency.</b></p> <aside class="abc" style="margin-left:0em;margin-top:-4.5em;" epub:type="sidebar"> <p class="noindent2" id="eqn_3.4"><math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <msub> <mi>E</mi> <mrow> <mtext>vib</mtext> </mrow> </msub> <mo>=</mo><mo stretchy='false'>(</mo><mtext>v+</mtext><mfrac> <mn>1</mn> <mn>2</mn> </mfrac> <mo stretchy='false'>)</mo><mi>h</mi><msub> <mi>&#x03BD;</mi> <mn>0</mn> </msub> <mtext>&#x0009;</mtext><mo stretchy='false'></mo><mn>&#160;</mn><mo stretchy='false'></mo> </mrow> </math> </p> <p class="indent" style="text-align:right;margin-top:-1.5em;margin-left:1.4em;">(3.4)</p> </aside> <p class="noindent"><a id="page_29" class="page">Page 29, Infra-red spectroscopy</a></p> <p class="indent">The lowest two energy levels, with <b>v</b> &#x003D; 0 and <b>v</b> &#x003D; 1, will have <math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <msub> <mi>E</mi> <mrow> <mn>v</mn><mn>i</mn><mn>b</mn> </mrow> </msub> <mtext>&#x2009;</mtext><mo>=</mo><mtext>&#x2009;</mtext><mfrac> <mn>1</mn> <mn>2</mn> </mfrac> <mtext>&#x2009;</mtext><mo stretchy='false'>(</mo><mi>h</mi><msub> <mi>v</mi> <mn>0</mn> </msub> <mo stretchy='false'>)</mo> </mrow> </math> and <math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <msub> <mi>E</mi> <mrow> <mn>v</mn><mn>i</mn><mn>b</mn> </mrow> </msub> <mtext>&#x2009;</mtext><mo>=</mo><mtext>&#x2009;</mtext><mfrac> <mn>3</mn> <mn>2</mn> </mfrac> <mtext>&#x2009;</mtext><mo stretchy='false'>(</mo><mi>h</mi><msub> <mi>v</mi> <mn>0</mn> </msub> <mo stretchy='false'>)</mo> </mrow> </math> respectively, so that the difference between them (i.e. the energy of the <i>v</i><sub>0</sub> &#x2192; <i>v</i><sub>1</sub> transition) is h<i>v</i><sub>0</sub>: the appropriate frequency associated with this energy change is the fundamental frequency (<i>v</i><sub>0</sub>)<i>.</i> It should also be noted that even in the ground vibrational state the molecule has vibrational energy, <math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <mtext>&#x2009;</mtext><mfrac> <mn>1</mn> <mn>2</mn> </mfrac> <mtext>&#x2009;</mtext><mo stretchy='false'>(</mo><mi>h</mi><msub> <mi>v</mi> <mn>0</mn> </msub> <mo stretchy='false'>)</mo> </mrow> </math> ; this is called the zero point energy.</p> <p class="indent">The molecule is rotating and vibrating simultaneously, and the <i>total</i> energy associated with these motions is the sum of the separate rotational and vibrational energies previously referred to (see <a href="#eqn_3.5">eqn 3.5</a>). This means that there are many possible energy levels: a molecule in a certain vibrational energy level can still have any one of the possible rotational energy levels referred to earlier.</p> <aside class="abc" style="margin-left:0em;margin-top:-6em;" epub:type="sidebar"> <p class="noindent2" id="eqn_3.5"><math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <msub> <mi>E</mi> <mrow> <mn>v</mn><mn>i</mn><mn>b</mn> </mrow> </msub> <mtext>&#x2009;</mtext><mo>+</mo><mtext>&#x2009;</mtext><msub> <mi>E</mi> <mrow> <mn>r</mn><mn>o</mn><mn>t</mn> </mrow> </msub> <mtext>&#x2009;</mtext><mo>=</mo><mtext>&#x2009;</mtext><mo stretchy='false'>(</mo><mi>v</mi><mtext>&#x2009;</mtext><mo>+</mo><mtext>&#x2009;</mtext><mfrac> <mn>1</mn> <mn>2</mn> </mfrac> <mo stretchy='false'>)</mo><mi>h</mi><msub> <mi>v</mi> <mn>0</mn> </msub> </mrow> </math> </p> <p class="noindent2" style="margin-left:14em;margin-top:-1.5em;">(3.5)</p> <p class="noindent2" style="margin-left:7em;margin-top:0.8em;"><math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <mo>+</mo><mtext>&#x2009;</mtext><mfrac> <mrow> <msup> <mi>h</mi> <mn>2</mn> </msup> <mtext>&#x2009;</mtext><mi>J</mi><mo stretchy='false'>(</mo><mi>J</mi><mo>+</mo><mn>1</mn><mo stretchy='false'>)</mo> </mrow> <mrow> <mn>8</mn><msup> <mi>&#x03C0;</mi> <mn>2</mn> </msup> <mi>l</mi> </mrow> </mfrac> </mrow> </math> </p> </aside> <p class="indent">Some of the allowed energy levels are illustrated in <a href="#fig_3.6">Fig. 3.6</a>: note that the vibrational energy levels are much more widely spaced than those for rotation (i.e <i>ca.</i> 3000 cm<sup>&#x2013;1</sup> compared with 20 cm<sup>&#x2013;1</sup> &#x2014; the vibrational energy separation in the figure is not to scale).</p> <figure class="fig1a" id="fig_3.6"> <img src="../images/f0029-01.jpg" alt="images"/> <figcaption> <p class="figurecaption2"><b>Fig. 3.6</b> Vibrational and rotational energy levels for a diatomic molecule: <b>v</b> is the vibrational quantum number and <i>J</i> is the rotational quantum number</p> </figcaption> </figure> <a id="page_30" class="page" style="width:70%;">Page 30, Infra-red spectroscopy</a> <p class="indent">When a molecule absorbs energy it can either change its <i>J</i> value (as discussed in <a href="chapter3.xhtml#sec_3.1">Section 3.1</a>) or it can change its vibrational <i>and</i> rotational levels. The particular transitions of the latter type which it is allowed to undergo are limited to those for which &#x0394;<b>&#x03BD;</b> &#x003D; &#x002B; 1 (e.g. from <b>v</b> &#x003D; 0 to <b>v</b> &#x003D; 1, <b>v</b> &#x003D; l to <b>v</b> &#x003D; 2) <i>and</i> &#x0394;<i>J</i> &#x003D; &#x00B1;1. For example, a molecule in the energy level <b>v</b> &#x003D; 0, <i>J</i> &#x003D; 1 can absorb energy to be promoted either to the level <b>v</b> &#x003D; 1, <i>J</i> &#x003D; 2, <i>or</i> to <b>v</b> &#x003D; 1<i>, J</i> &#x003D; 0. When all the possibilities are considered it is found that the spectrum should consist of two series of lines &#x2014; from a given <i>J</i> value in <b>v</b> &#x003D; 0 to (<i>J</i>&#x002B;1) in <b>v</b> &#x003D; 1, and from <i>J</i> in <b>v</b> &#x003D; 0 to (<i>J</i> &#x2013; 1) in <b>v</b> &#x003D; 1. The two series will have increasing energy (and hence increasing wavenumber) and decreasing energy (and wavenumber), respectively, as seen in <a href="#fig_3.6">Fig. 3.6</a> You are encouraged to identify which peaks are associated with individual transitions (0&#x2013;1, etc), to measure the relative &#x0394;<i>E</i> values for the transitions indicated, and to check that these account for the features of a typical spectrum (<a href="#fig_3.5">Fig. 3.5</a>).</p> <aside class="abc" style="margin-left:0em;margin-top:-15.5em;" epub:type="sidebar"> <p class="noindent3">The allowed changes in vibrational and rotational energy levels are governed by selection rules for &#x0394;&#x03BD; and &#x0394;J.</p> </aside> <p class="indent">The whole spectrum is centred about the transition (<b>v</b> &#x003D; 0) &#x2192; (<b>v</b> &#x003D; 1) which has no associated change in <i>J</i> (i.e. &#x0394;<i>J</i> &#x003D; 0). For the molecule HCl, this transition is forbidden, and does not take place, but the corresponding value of the energy change associated only with vibration (i.e. as if &#x0394;<i>J</i> &#x003D; 0) can be obtained from the middle of the spectrum.</p> <p class="indent">In the analysis, only transitions from <b>v</b> &#x003D; 0 to <b>v</b> &#x003D; 1 are indicated: this is a very reasonable approximation, since most of the molecules present will be in their lowest vibrational level rather than in higher levels (<b>v</b> &#x003D; 1, 2 etc.). In contrast, as indicated by the rotational spectrum (e.g. <a href="#fig_3.2">Fig. 3.2</a>), there are molecules in a wide range of rotational levels. This situation arises because the energy increment associated with the allowed increase of vibrational energy is much larger than that for an increase of rotational energy, so that molecules have only a small probability of being in an excited vibrational state.</p> <aside class="abc" style="margin-left:0em;margin-top:-6em;" epub:type="sidebar"> <p class="noindent3">The profile of the peak intensities in the two branches of the vibration&#x2013;rotation spectrum (<a href="#page_28">page 28</a>) reflects the Boltzmann distribution of molecules within different rotational energy levels (see <a href="chapter5.xhtml#page_56">page 56</a>).</p> </aside> <p class="indent">The analysis also explains why the individual absorptions in the rotation&#x2013;vibration spectrum are approximately equally spaced. This separation is identical to that obtained for the simple rotational spectrum, so that bond lengths can be obtained as described previously (<a href="#page_26">page 26</a>). It is helpful also to envisage this set of absorptions as centred at 2890 cm<sup>&#x2013;1</sup> (corresponding to the <b>v</b><sub>0</sub> &#x2192; <b>v</b><sub>1</sub> transition and to the fundamental frequency <i>v</i><sub>0</sub>)<i>.</i> For compounds in solution the rotational &#x2018;fine structure&#x2019; becomes blurred and a single broad peak centred on <i>v</i><sub>0</sub> is observed.</p> </section> <section epub:type="chapter"> <h3 class="h3"><b>Interpretation of the fundamental frequency,</b> <i>v</i><sub>0</sub></h3> <p class="noindent">The motion of the vibrating atoms of a diatomic molecule is closely analogous to the simple harmonic motion of two masses attached to each other by a spring (<a href="#fig_3.7">Fig. 3.7</a>). Both systems obey Hooke&#x2019;s law; that is, the restoring force when the masses are stretched or compressed away from the equilibrium position is proportional to the extent of displacement from that position. For the resultant simple harmonic motion of the spring it can be shown that the frequency of oscillation, <i>v,</i> is given by <a href="#eqn_3.6">equation 3.6</a>. where <i>&#x03BC;</i> is the <b>reduced mass</b>, <i>m</i><sub>1</sub><i>m</i><sub>2</sub><i>/</i>(<i>m</i><sub>1</sub> &#x002B; <i>m</i><sub>2</sub>), and <i>k</i> is the force constant of the spring (a measure of its resistance to stretching). Similarly, the behaviour of chemical bonds can be interpreted in terms of a fundamental frequency, <i>v</i><sub>0</sub><i>,</i> given by <a href="#eqn_3.6">equation (3.6)</a>, where <i>&#x03BC;</i> is the reduced mass of the two connected atoms, and, by analogy, <i>k</i> is the force constant of the bond. This concept is helpful in understanding vibrational spectra.</p> <aside class="abc" style="margin-left:0em;margin-top:-7em;" epub:type="sidebar"> <p class="noindent2" id="eqn_3.6"><math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <mi>&#x03BD;</mi><mo>=</mo><mfrac> <mn>1</mn> <mrow> <mn>2</mn><mi>&#x03C0;</mi> </mrow> </mfrac> <msqrt> <mrow> <mfrac> <mi>k</mi> <mi>&#x03BC;</mi> </mfrac> </mrow> </msqrt> <mtext>&#x0009;</mtext><mo stretchy='false'></mo><mn>&#160;</mn><mo stretchy='false'></mo> </mrow> </math> </p> <p class="indent" style="text-align:right;margin-top:-1.5em;">(3.6)</p> </aside> <a id="page_31" class="page" style="width:70%;">Page 31, Infra-red spectroscopy</a> <figure class="fig1a" id="fig_3.7"> <img src="../images/f0031-01.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.7</b> Simple model for the vibrational motion of a diatomic molecule</p> </figcaption> </figure> <p class="indent">For H<sup>35</sup>Cl, the absorption at wavenumber 2890 cm<sup>&#x2013;1</sup> in the vibrational spectrum is equivalent to a fundamental frequency, <i>v</i><sub>0</sub>, of 8.67 &#x00D7; 10<sup>13</sup> Hz. This leads to a value for the force constant <i>k,</i> of 4.8 &#x00D7; 10<sup>2</sup> N m<sup>&#x2013;1</sup> or kg s<sup>&#x2013;2</sup> (4.8 &#x00D7; 10<sup>5</sup> dynes cm<sup>&#x2013;1</sup>).</p> <p class="indent">The equations for rotational and vibrational energy levels indicate that the lines for H<sup>35</sup>Cl and H<sup>37</sup>Cl should be almost superimposed (as observed) because <i>&#x03BC;</i>, that is <i>m</i><sub>1</sub> <i>m</i><sub>2</sub><i>/</i>(<i>m</i><sub>1</sub> &#x002B; <i>m</i><sub>2</sub>), is very similar for the two molecules.</p> <p class="indent">However, the equations indicate that this similarity does not apply if we compare HCl and DCl. Thus the predicted spectrum from the latter (either chlorine isotope) will have quite different energies for its rotational and vibrational transitions when compared with the former. The force constant, an electronic property, is the same for HCl and DCl (with either chlorine isotope in each case) so that <i>v</i><sub>0</sub>(HCl) and <i>v</i><sub>0</sub>(DCl) should be related, as indicated by <a href="#eqn_3.6">eqn 3.6</a>, by a factor given by their different <math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <msqrt> <mi>&#x03BC;</mi> </msqrt> </mrow> </math> values: the experimental spectrum (<a href="#fig_3.8">Fig. 3.8</a>) confirms the expected ratio of <math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <msqrt> <mi>2</mi> </msqrt> </mrow> </math> for <i>v</i><sub>0</sub> (HCl): <i>v</i><sub>0</sub> (DCl), with <i>v</i><sub>0</sub> for DCl <i>ca.</i> 2090 cm<sup>&#x2013;1</sup> (remember that wavenumber is proportional to frequency). The spectrum also confirms the expected smaller rotational splitting for DCl; you may like to confirm that a factor of 2 (as observed) is predicted by the theory given here. Further, the separation of the spectrum from <sup>2</sup>HCl (<a href="#fig_3.8">Fig. 3.8</a>) into absorptions from <sup>2</sup>H<sup>35</sup>Cl and <sup>2</sup>H<sup>37</sup>Cl, with slightly different <i>v</i><sub>0</sub>, is also as expected from <a href="#eqn_3.6">eqn 3.6</a>: the relative intensities of the two sets of peaks are in the ratio 3:1, as expected. (Note the separation is smaller for <sup>1</sup>H<sup>35</sup>Cl and <sup>1</sup>H<sup>37</sup>Cl so that the separate absorbances cannot be resolved in <a href="#fig_3.5">Fig. 3.5</a>).</p> <p class="indent">The spectra of other heteronuclear diatomic molecules can also be analysed to give appropriate force constants. As might be expected, there is a correlation between force constants and bond enthalpies (energies) which is apparent, for example, in the values for the series of hydrogen halides (<a href="#tab_3.2">Table 3.2</a>): the trend in force constants also parallels the changes in bond length (see <a href="#tab_3.1">Table 3.1</a>, <a href="#page_26">page 26</a>). Similarly, the strong triple bond in carbon monoxide (bond enthalpy 1075 kJ mol<sup>&#x2013;1</sup>) has a correspondingly large force constant (18.4 &#x00D7; 10<sup>2</sup> N m<sup>&#x2013;1</sup>).</p> <aside class="abc" style="margin-left:0em;margin-top:-13em;" epub:type="sidebar"> <p class="tablecaption"><a id="tab_3.2"></a><b>Table 3.2</b></p> <table style="border-collapse:collapse;width:120%;"> <tr><td style="border-top:1pt solid black;"></td><td style="border-top:1pt solid black;padding-left:2em;">Force Constant/N m<sup>&#8211;1</sup></td><td style="border-top:1pt solid black;padding-left:2em;">Bond Enthalpy/kJ mol<sup>&#8211;1</sup></td></tr> <tr><td style="border-top:1pt solid black;">HF</td><td style="border-top:1pt solid black;padding-left:2em;">9.7 &#215; 10<sup>2</sup></td><td style="border-top:1pt solid black;padding-left:2em;">562</td></tr> <tr><td>HCL</td><td style="padding-left:2em;">4.8 &#215; 10<sup>2</sup></td><td style="padding-left:2em;">434</td></tr> <tr><td>HBr</td><td style="padding-left:2em;">4.1 &#215; 10<sup>2</sup></td><td style="padding-left:2em;">366</td></tr> <tr><td style="border-bottom:1pt solid black;">HI</td><td style="border-bottom:1pt solid black;padding-left:2em;">3.2 &#215; 10<sup>2</sup></td><td style="border-bottom:1pt solid black;padding-left:2em;">299</td></tr> </table> </aside> <a id="page_32" class="page" style="width:70%;">Page 32, Infra-red spectroscopy</a> <figure class="fig1a" id="fig_3.8"> <img src="../images/f0032-01.jpg" alt="images" style="margin-left:-6em;"/> <figcaption> <p class="figurecaption2"><b>Fig. 3.8</b> Vibration rotation i.r. spectrum &#x1FE1; 1900&#x2013;2300 cm<sup>&#x2013;1</sup>) of gaseous deuterium chloride, <sup>2</sup>HCl (DCl)</p> </figcaption> </figure> <p class="indent">Another branch of spectroscopy known as Raman Spectroscopy can be employed to calculate bond lengths and force constants for homonuclear diatomic molecules (e.g. H<sub>2</sub>, N<sub>2</sub>), though it will not be discussed further here.</p> </section> <section epub:type="chapter"> <h3 class="h3"><b>Triatomic molecules</b></h3> <p class="noindent">For molecules more complicated than the diatomic molecules considered so far, there are several possible ways in which the bonds can vibrate (these are called vibrational <b>modes</b>) and each vibration has an associated fundamental frequency. For example, the fundamental modes for the linear molecule CO<sub>2</sub> are illustrated in <a href="#fig_3.9">Fig. 3.9</a>. Of these, <i>v</i><sub>1</sub> (the <i>symmetric stretching</i> mode) does not involve a dipole moment change and is &#x2018;inactive&#x2019; in the infra-red region, there being no corresponding absorption of energy. However, absorptions are observed for <i>v</i><sub>2</sub> (667 cm<sup>&#x2013;1</sup>) and <i>v</i><sub>3</sub> (2349 cm<sup>&#x2013;1</sup>) because these modes of vibration involve dipole moment changes. These are called <i>bending</i> (<i>v</i><sub>2</sub>) and <i>asymmetric stretching</i> (<i>v</i><sub>3</sub>) modes, respectively, and the numerical values indicate (as might be expected) that less energy is involved in bending than in stretching.</p> <figure class="fig1a" id="fig_3.9"> <img src="../images/f0032-02.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.9</b> Vibrational modes for CO<sub>2</sub></p> </figcaption> </figure> <a id="page_33" class="page" style="width:70%;">Page 33, Infra-red spectroscopy</a> <p class="indent">For a non-linear triatomic molecule (e.g. H<sub>2</sub>O) the three vibrational modes are all infra-red active since each involves a dipole moment change. Since three absorptions are detected in the vibrational i.r. spectrum of SO<sub>2</sub>, it can be concluded that this molecule (like H<sub>2</sub>O) is not linear.</p> </section> </section> <section epub:type="chapter" id="sec_3.3"> <h2 class="h2"><b>3.3</b><span class="space">&#160;</span><b>I.r. spectroscopy of organic molecules</b></h2> <p class="noindent">The i.r. absorption spectrum gets very rapidly more complicated as we progress from diatomic molecules to tri-atomic, tetra-atomic, and larger molecules, because of the increase in the number of possible vibrations. Only in fairly simple cases can a full analysis be carried out, but nevertheless it is often possible to obtain useful information about the structure of complex molecules. The compound under investigation is examined, where possible, as a liquid sample. This can be done, for example, for a neat liquid by squeezing a few drops between two KBr discs ( transparent to i.r. radiation). Alternatively, the compound to be studied may be dissolved in a suitable solvent (e.g. CHCl<sub>3</sub>, CCl<sub>4</sub>); although peaks characteristic of the solvent&#x2019;s i.r. absorptions will be observed, these can easily be recognized and allowance made for them. (In a double-beam spectrometer, peaks from the pure solvent are recorded simultaneously and subtracted automatically.) A solid compound may be ground up to form a &#x2018;mull&#x2019; with paraffin oil before being placed between the KBr discs or ground with KBr and pressed into a disc.</p> <p class="indent">The spectra are plots of <b>transmittance</b> of energy at a given wavelength, rather than absorption of energy. Transmittance and absorption are related: a large transmittance implies little absorption, and vice versa.</p> <figure class="fig1a" id="fig_3.10"> <img src="../images/f0033-01.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.10</b> I.r. spectrum of propanone, (CH<sub>3</sub>)<sub>2</sub>CO (liquid film)</p> </figcaption> </figure> <p class="indent">Organic compounds show spectra in which many peaks are spread over the wide scan-range customarily employed (4000&#x2013;600 cm<sup>&#x2013;1</sup>). Each peak is associated with a particular vibration (or a combination of these) &#x2014; the rotational fine structure is smeared out for molecules in the liquid phase because rotation of the molecules is not free, as it is in a gas; each peak is really an &#x2018;envelope&#x2019; of all rotational lines. The complexity of the spectra (see, for example, the i.r. spectrum of propanone, <a href="#fig_3.10">Fig. 3.10</a>) reflects the large number of fundamental vibrations, which depends on the complexity of the molecule <a id="page_34" class="page">Page 34, Infra-red spectroscopy</a>(i.e. its number of bonds). Fortunately, to a certain extent certain absorptions can be associated with stretching or bending vibrations of particular bonds (or sometimes groups) in a molecule: for example, the absorptions at <i>ca.</i> 3000 and 1700 cm<sup>&#x2013;1</sup> in the spectrum of propanone are typical of the stretching modes of C&#x2013;H and C&#x003D;O groups, respectively, in organic compounds. In this way the spectra allow recognition of the types of functional group present in an organic molecule.</p> <p class="indent">Other absorptions are observed which are characteristic of the molecule as a whole, these depending on interactions between different groups. Further, there are complications which arise because absorptions can occur at overtones (harmonics) of other frequencies or at combinations (<i>&#x03BD;</i><sub>1</sub> &#x002B; <i>v</i><sub>2</sub>) and differences (<i>&#x03BD;</i><sub>1</sub> &#x2013; <i>v</i><sub>2</sub>) of other frequencies. These all add to the complexity but help provide the equivalent of an unambiguous fingerprint for any particular molecule.</p> <section epub:type="chapter"> <h3 class="h3"><b>Dependence of the i.r. spectrum on molecular structure</b></h3> <p class="noindent">Typical absorptions indicated diagrammatically in <a href="#fig_3.11">Fig. 3.11</a> can be of considerable assistance in the determination of an unknown compound&#x2019;s structure. The important features of the figure can be helpfully interpreted in terms of the dependence of a characteristic bond-stretching frequency (and hence wavenumber) on the <i>force constant</i> for that bond and on the <i>masses</i> of the atoms which are joined by the bond.</p> <p class="indent">For example, the lowering of the wavenumber (and hence energy) for stretching in the series <i>triple bond &#x003E; double bond &#x003E; single bond</i> [for C&#x2013;C and C&#x2013;N bonds and, if carbon monoxide is included (C&#x2261;O, <i>v</i><sub>0</sub> 2146 cm<sup>&#x2013;1</sup>), for C&#x2013;O bonds], is as expected from the appropriate bond enthalpies (bond strengths) and hence force constants (see <a href="#eqn_3.6">eqn 3.6</a>). Further, variations in the reduced mass (<i>&#x03BC;</i>) of the atoms forming the bond (see <a href="#eqn_3.6">eqn 3.6</a>) also have predictable effects, notably high wavenumber (and hence frequency) for C&#x2013;H, N&#x2013;H, and &#x039F;&#x2013;H stretches (these bonds all have low values of <i>&#x03BC;</i>)<i>.</i> Lastly, since bending involves less energy than stretching, absorptions for the former occur at lower wavenumbers than stretching modes involving the same bonds.</p> <p class="indent">Absorptions tend to be particularly prominent when a bond with large dipole moment is involved (e.g. C&#x2013;O).</p> <figure class="fig1a" id="fig_3.11"> <img src="../images/f0034-01.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.11</b> Typical areas for absorptions in the i.r. spectra of organic molecules</p> </figcaption> </figure> <a id="page_35" class="page" style="width:70%;">Page 35, Infra-red spectroscopy</a> <p class="indent">One of the particular attractions of i.r. spectroscopy is that a more detailed investigation of the positions of absorption of a bond (e.g. C&#x2013;H ) in a variety of different molecules shows that the exact wavenumber does depend to a small but significant extent on the environment of that bond in a molecule (cf. chemical shifts in n.m.r. spectra; <a href="chapter5.xhtml">Chapter 5</a>) and this can prove diagnostically extremely valuable. Some characteristic absorptions which illustrate the variation are listed in <a href="#tab_3.3">Table 3.3</a> and these are now discussed in more detail.</p> <p class="noindent">(i) C&#x2013;H <i>bonds.</i> For example, methyl (CH<sub>3</sub>) and methene (CH<sub>2</sub>) groups usually exhibit C&#x2013;H stretching modes in the range 2950&#x2013;2850 cm<sup>&#x2013;1</sup> (sometimes these appear with splittings owing to interaction between the different C&#x2013;H bonds) and also bending modes at around 1450 cm<sup>&#x2013;1</sup>. The absorptions for the C&#x2013;H stretch in propanone at just below 3000 cm<sup>&#x2013;1</sup> and the bending modes at <i>ca.</i> 1400 cm<sup>&#x2013;1</sup> are clearly visible in <a href="#fig_3.10">Fig. 3.10</a>.</p> <p class="indent">In contrast, an alkanal C&#x2013;H stretch usually appears between 2700 and 2900 cm<sup>&#x2013;1</sup>, and other C&#x2013;H stretching absorptions are as follows: alkynes (C&#x2261;CH), 3300 cm<sup>&#x2013;1</sup>; alkenes (C&#x003D;CH<sub>2</sub>), 3095&#x2013;3075 cm<sup>&#x2013;1</sup>; arenes 3040&#x2013;3010 cm<sup>&#x2013;1</sup>. Out-of-plane bending for arene and alkenic hydrogen atoms often gives characteristic absorption bands at 900&#x2013;650 and 990&#x2013;890 cm<sup>&#x2013;1</sup>, respectively.</p> <p class="tablecaption"><a id="tab_3.3"></a><b>Table 3.3</b> Characteristic infra-red absorptions for a variety of organic molecules&#x002A;</p> <figure class="fig"> <img src="../images/f0035-01.jpg" alt="images"/> </figure> <a id="page_36" class="page" style="width:70%;">Page 36, Infra-red spectroscopy</a> <p class="indent">The characteristic arene C&#x2013;H stretching vibrations (&#x003E;3000 cm<sup>&#x2013;1</sup>) and out-of-plane bending vibration (680 cm<sup>&#x2013;1</sup>) are apparent in the i.r. spectrum of benzene (<a href="#fig_3.12">Fig. 3.12</a>). Other prominent absorptions are from in-plane C&#x2013;C bending (1040 cm<sup>&#x2013;1</sup>) and C&#x2013;C stretching (1480 cm<sup>&#x2013;1</sup>). For more complicated benzene derivatives, it is sometimes possible to determine the ring substitution pattern from the modifications produced in the i.r. spectrum.</p> <figure class="fig1a" id="fig_3.12"> <img src="../images/f0036-01.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.12</b> I.r. spectrum of benzene, C<sub>6</sub>H<sub>6</sub> (liquid film)</p> </figcaption> </figure> <p class="noindent" id="sec_3.ii">(ii) O&#x2013;H, C&#x2013;O <i>bonds.</i> Hydroxyl groups (OH) generally give a strong peak (from the stretching vibration) in the 3650&#x2013;3590 cm<sup>&#x2013;1</sup> region; if the group is hydrogen-bonded there is usually a broadening and a shift towards lower wavenumbers. For example, <a href="#fig_3.13">Fig. 3.13</a> shows the i.r. spectrum of ethanol, showing clearly the C&#x2013;H and O&#x2013;H stretches (2900 and 3300 cm<sup>&#x2013;1</sup>, respectively) and absorption from aliphatic C&#x2013;H bending (1400 cm<sup>&#x2013;1</sup>) and C&#x2013;O stretching 1050 cm<sup>&#x2013;1</sup>, see also section (iv). From the shape and position of the O&#x2013;H peak it can be concluded that this group is involved in hydrogen-bonding.</p> <figure class="fig1a" id="fig_3.13"> <img src="../images/f0036-02.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.13</b> I.r. spectrum of ethanol, CH<sub>3</sub>CH<sub>2</sub>OH (liquid film)</p> </figcaption> </figure> <p class="noindent">(iii) N&#x2013;H <i>bonds.</i> Like O&#x2013;H bonds, N&#x2013;H bonds show a characteristic absorption at high wavenumber (3500&#x2013;3300 cm<sup>&#x2013;1</sup>). Hydrogen-bonding involving the N&#x2013;H hydrogen may again cause broadening and a shift towards lower wavenumbers.</p> <a id="page_37" class="page" style="width:70%;">Page 37, Infra-red spectroscopy</a> <p class="noindent">(iv) C&#x003D;0 <i>bonds.</i> Carbonyl-containing compounds show a very characteristic strong C&#x003D;O absorption in the range 1800&#x2013;1600 cm<sup>&#x2013;1</sup>, the exact value of which depends on the structure of the adjacent groups. For simple ketones and for aliphatic alkanals the appropriate value is 1725 cm<sup>&#x2013;1</sup> (see <a href="#fig_3.10">Fig. 3.10</a>) but the wavenumber tends to be slightly higher for simple alkanoyl chlorides, esters, and anhydrides, and slightly lower than this for amides. The characteristic wavenumbers are also generally a little lower if the carbonyl group (in ketones, esters etc.) is adjacent to an alkenic double bond (C&#x003D;C&#x2013;C&#x003D;O) or to a phenyl ring, or if it is involved in hydrogen-bonding (see also <a href="chapter4.xhtml">Chapters 4</a> and <a href="chapter5.xhtml">5</a>).</p> <p class="indent">Carbon&#x2013;oxygen single bonds (C&#x2013;O) in esters, alkanols, and ethers usually show a strong absorption in the range 1300&#x2013;1050 cm<sup>&#x2013;1</sup> [see <a href="#sec_3.ii">section (ii)</a>].</p> <p class="indent">Remember that the key absorptions mentioned here and in <a href="#tab_3.3">Table 3.3</a> are only some of the characteristic vibrations which may be encountered &#x2014; the spectra contain complicating features from other parts of the molecule.</p> </section> </section> <section epub:type="chapter" id="sec_3.4"> <h2 class="h2"><b>3.4</b><span class="space">&#160;</span><b>Examples of i.r.spectra</b></h2> <p class="noindent">The following examples illustrate the variation of i.r. spectra with molecular structure.</p> <section epub:type="chapter"> <h3 class="h3"><b>Hexane, CH<sub>3</sub>(CH<sub>2</sub>)<sub>4</sub>CH<sub>3</sub></b> (<a href="#fig_3.14">Fig. 3.14</a>)</h3> <p class="noindent">This spectrum reveals very clearly the characteristic aliphatic C&#x2013;H stretching modes (just below 3000 cm<sup>&#x2013;1</sup>) and bending modes (1500 cm<sup>&#x2013;1</sup>) with no indication of any functional groups.</p> <figure class="fig1a" id="fig_3.14"> <img src="../images/f0037-01.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.14</b> I.r. spectrum of hexane, C&#x0397;<sub>3</sub>(C&#x0397;<sub>2</sub>)<sub>4</sub>C&#x0397;<sub>3</sub> (liquid film)</p> </figcaption> </figure> </section> <section epub:type="chapter"> <h3 class="h3"><b>Pent-1-ene, CH<sub>3</sub>(CH<sub>2</sub>)<sub>2</sub>CH&#x003D;CH<sub>2</sub></b> (<a href="#fig_3.15">Fig. 3.15</a>)</h3> <p class="noindent">The peaks at 900 cm<sup>&#x2013;1</sup> and 3080 cm<sup>&#x2013;1</sup>, the alkenic C&#x2013;H out-of-plane bending and stretching modes, respectively, provide conclusive evidence for the presence of an alkene. Also present are alkyl C&#x2013;H modes (<i>ca.</i> 2900 and 1450 cm<sup>&#x2013;1</sup>) and the C&#x003D;C stretching vibration (1640 cm<sup>&#x2013;1</sup>).&#x00B7;Alkenes without a terminal double bond show slightly different absorptions below 1000 cm<sup>&#x2013;1</sup>: the details sometimes allow the substitution pattern of the alkene (<i>cis</i> or <i>trans</i>) to be established.</p> <a id="page_38" class="page" style="width:70%;">Page 38, Infra-red spectroscopy</a> <figure class="fig1a" id="fig_3.15"> <img src="../images/f0038-01.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.15</b> l.r.spectrum of pent-1-ene, CH<sub>3</sub>(CH<sub>2</sub>)<sub>2</sub>CH&#x003D;CH<sub>2</sub> (liquid film)</p> </figcaption> </figure> </section> <section epub:type="chapter"> <h3 class="h3"><b>Methylbenzene, C<sub>6</sub>H<sub>5</sub>CH<sub>3</sub></b> (<a href="#fig_3.16">Fig. 3.16</a>)</h3> <p class="noindent">In addition to the aromatic and aliphatic C&#x2013;H stretching modes (at 3050 and 2900 cm<sup>&#x2013;1</sup>, respectively) there are characteristic peaks from the aliphatic C&#x2013;H bending modes (<i>ca</i>. 1500 cm<sup>&#x2013;1</sup>) and from out-of-plane aromatic C&#x2013;H bending (<i>ca.</i> 700 cm<sup>&#x2013;1</sup>). The particular pattern around 700 cm<sup>&#x2013;1</sup> is typical of a mono-substituted benzene derivative.</p> <figure class="fig1a" id="fig_3.16"> <img src="../images/f0038-02.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.16</b> I.r. spectrum of methylbenzene, C<sub>6</sub>H<sub>5</sub>CH<sub>3</sub> (liquid film)</p> </figcaption> </figure> </section> <section epub:type="chapter"> <h3 class="h3"><b>Ethanoic acid (acetic acid), CH<sub>3</sub>CO<sub>2</sub>H</b> (<a href="#fig_3.17">Fig. 3.17</a>)</h3> <p class="noindent">This spectrum, from a thin film of the liquid, shows typical C&#x2013;H bending vibrations (<i>ca.</i> 1400 cm<sup>&#x2013;1</sup>) and the characteristic carbonyl absorption at 1720 cm<sup>&#x2013;1</sup>. The broad absorption at 3000 cm<sup>&#x2013;1</sup> typifies a hydrogen-bonded OH group.</p> </section> <section epub:type="chapter"> <h3 class="h3"><b>Ethyl ethanoate (ethyl acetate), CH<sub>3</sub>CO<sub>2</sub>C<sub>2</sub>H<sub>5</sub></b> (<a href="#fig_3.18">Fig. 3.18</a>)</h3> <p class="noindent">This shows clearly the typical carbonyl stretching absorption at 1740 cm<sup>&#x2013;1</sup>; note that this is at slightly higher wavenumber than that observed for ketones. The absorption at 1240 cm<sup>&#x2013;1</sup> is a C&#x2013;O stretch, particularly prominent for esters.<a id="page_39" class="page">Page 39, Infra-red spectroscopy</a></p> <figure class="fig1a" id="fig_3.17"> <img src="../images/f0039-01.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.17</b> I.r. spectrum of ethanoic acid, CH<sub>3</sub>CO<sub>2</sub>H (liquid film)</p> </figcaption> </figure> <figure class="fig1a" id="fig_3.18"> <img src="../images/f0039-02.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.18</b> I.r. spectrum of ethyl ethanoate, CH<sub>3</sub>CO<sub>2</sub>C<sub>2</sub>H<sub>5</sub> (liquid film)</p> </figcaption> </figure> </section> <section epub:type="chapter"> <h3 class="h3"><b>Diethylamine, (C<sub>2</sub>H<sub>5</sub>)<sub>2</sub>NH</b> (<a href="#fig_3.19">Fig. 3.19</a>)</h3> <p class="noindent">The broad peak at <i>ca.</i> 3300 cm<sup>&#x2013;1</sup> in this spectrum is indicative of an N&#x2013;H group; the broadening suggests that the hydrogen atom takes part in inter-molecular hydrogen-bonding with nitrogen atoms in other molecules. The strong absorption at 1140 cm<sup>&#x2013;1</sup> is from a C&#x2013;N stretching vibration (cf. C&#x2013;O stretch in alcohols, ethers, etc.).</p> <figure class="fig1a" id="fig_3.19"> <img src="../images/f0039-03.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.19</b> I.r. spectrum of diethylamine, (C<sub>2</sub>H<sub>5</sub>)<sub>2</sub>NH (liquid film)<a id="page_40" class="page">Page 40, Infra-red spectroscopy</a></p> </figcaption> </figure> </section> </section> <section epub:type="chapter" id="sec_3.5"> <h2 class="h2"><b>3.5</b><span class="space">&#160;</span><b>Problems</b></h2> <p class="noindenth1" id="prob_3.1">3.1<span class="space">&#160;</span>Calculate the fundamental stretching frequency and wavenumber for a C&#x2013;H bond, given that the atoms vibrate independently of other groups on the carbon atom and that the force constant is 4.8 &#x00D7; 10<sup>2</sup> N m<sup>&#x2013;1</sup>.</p> <p class="noindenth1" id="prob_3.2">3.2<span class="space">&#160;</span>Calculate the expected separation (in wavenumbers) between the rotational transitions in the far infra-red (or microwave) spectrum of carbon monoxide given that the bond length, <i>r</i><sub>CO</sub>, is 0.113 nm.</p> <p class="noindenth1" id="prob_3.3">3.3<span class="space">&#160;</span>Account for the observation that in the i.r. spectrum of deuteriated benzene (C<sub>6</sub><sup>2</sup>H<sub>6</sub>), the C&#x2013;D (C&#x2013;<sup>2</sup>H) symmetric stretching mode occurs at <i>ca.</i> 2280 cm<sup>&#x2013;1</sup> (in undeuteriated benzene the corresponding absorption is at 3050 cm<sup>&#x2013;1</sup>).</p> <p class="noindenth1" id="prob_3.4">3.4<span class="space">&#160;</span><a href="#fig_3.20">Fig. 3.20</a> is the i.r. spectrum of the compound whose mass spectrum has been given previously (<a href="chapter1.xhtml#prob_1.3">Problem 1.3</a>, <a href="chapter1.xhtml#page_16">page 16</a>) and whose n.m.r. spectrum is described on <a href="chapter5.xhtml#page_69">page 69</a>. Does the i.r. spectrum support your previous assignment&#x003F;</p> <figure class="fig1a" id="fig_3.20"> <img src="../images/f0040-01.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.20</b> I.r. spectrum of unknown compound: <a href="#prob_3.4">Problem 3.4</a></p> </figcaption> </figure> </section> <section epub:type="chapter" id="sec_3.6"> <h2 class="h2"><b>3.6</b><span class="space">&#160;</span><b>Conclusion</b></h2> <p class="noindent">The usefulness of i.r. spectroscopy lies not only in the detailed information which can be obtained for small molecules, but also, for example, in the rapid and fairly inexpensive technique it provides for deciding which functional groups are present in a molecule. It has some advantages over mass spectra (<a href="chapter1.xhtml">Chapter 1</a>) and n.m.r (discussed in <a href="chapter5.xhtml">Chapter 5</a>); thus, compared with the former it has the advantage that it can be easily applied to non-volatile samples. Compared with n.m.r. it possesses the ability to give information about all the atoms in a molecule (not just those nuclei with magnetic moments). In practice, all three techniques (with ultra-violet spectroscopy) can usually be used to complement each other in a complete diagnosis.</p> <p class="indent">The technique also finds increasing applications in a wider context. For example, <a href="#fig_3.21">Fig. 3.21</a> shows the i.r. spectrum obtained from a thin film of nylon-6.6 (this polymer is prepared by the <b>copolymerization</b> reaction of hexane-dioic acid and hexane-1,6-diamine). Infra-red absorptions from C&#x2013;H<a id="page_41" class="page">Page 41, Infra-red spectroscopy</a>stretching (2900 cm<sup>&#x2013;1</sup>), amide C&#x003D;O stretching (1600 cm<sup>&#x2013;1</sup>) and N&#x2013;H stretching (3300 cm<sup>&#x2013;1</sup>) help confirm the structure: note that the bonds around the amide function (the <b>peptide link</b> CO&#x2013;NH) are planar; out-of-plane N&#x2013;H bending accounts for the absorption at <i>ca.</i> 700 cm<sup>&#x2013;1</sup>.</p> <figure class="fig1a" id="fig_3.21"> <img src="../images/f0041-01.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.21</b> I.r. spectrum of nylon-6,6</p> </figcaption> </figure> <p class="indent">A thin film of perspex has strong absorptions at <i>ca.</i> 2950, 1730, 1450, and 1200 cm<sup>&#x2013;1</sup>. What type of polymer structure is consistent with these observations&#x003F;</p> <p class="indent">A quite different application is provided by a structural investigation of the metal-carbonyl compound Fe<sub>2</sub>(CO)<sub>9</sub>, (<a href="#fig_3.22">Fig. 3.22</a>), which has i.r. absorptions at 2020 and 1830 cm<sup>&#x2013;1</sup>. The former absorption is from terminal carbonyl groups (rather similar to carbon monoxide itself, which has <img src="../images/f0020-04.jpg" alt="images"/> 2146 cm<sup>&#x2013;1</sup>), whereas the latter is from the bridging carbonyl groups (cf. R<sub>2</sub>C&#x003D;O, <i>ca.</i> 1700 cm<sup>&#x2013;1</sup>).</p> <figure class="fig1a" id="fig_3.22"> <img src="../images/f0041-02.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.22</b> Structure of Fe<sub>2</sub>(CO)<sub>9</sub></p> </figcaption> </figure> <p class="indent">Finally, infra-red spectroscopy may also be employed for the rapid quantitative analysis of the components of a mixture. For example, <a href="#fig_3.23">Fig. 3.23</a> shows the i.r. spectrum of a sample taken from a car exhaust. Spectra (due to vibrational and rotational transitions) can be attributed to carbon monoxide,<a id="page_42" class="page">Page 42, Infra-red spectroscopy</a>carbon dioxide, water, unspent hydrocarbon fuel, and also methane (formed in the &#x2018;cracking&#x2019; of other hydrocarbons). The amount of any of these in the gaseous emission can be quantified and, for example, continuously monitored during performance tests. A commercial i.r. spectrometer is also available which gives rapid quantitative analysis of different components (e.g. lactose, proteins and fats) in milk samples.</p> <figure class="fig1a" id="fig_3.23"> <img src="../images/f0042-01.jpg" alt="images"/> <figcaption> <p class="figurecaption"><b>Fig. 3.23</b> I.r. spectrum of the mixture of gases in a car exhaust</p> </figcaption> </figure> <p class="indent">The more rapid acquisition of inra-red spectra can now be achieved using FTIR spectrometers which employ Fourier Transform procedures (see <a href="chapter5.xhtml#page_71">page 71</a>), an approach which also offers advantages in sensitivity.</p> </section> <section epub:type="chapter" id="sec_3.7"> <h3 class="h3"><b>Further Reading (<a href="chapter3.xhtml">Chapters 3</a> and <a href="chapter4.xhtml">4</a>)</b></h3> <p class="noindenth">1.<span class="space">&#160;</span>L. M. Harwood and T. D. W. Claridge, <i>Introduction to Organic Spectroscopy</i>, Oxford Chemistry Primers, Oxford University Press, 1997.</p> <p class="noindenth">2.<span class="space">&#160;</span>D. H. Williams and I. Fleming, <i>Spectroscopic Methods in Organic Chemistry</i>, 5<sup>th</sup> Edition McGraw Hill, 1995.</p> </section> </section> </body> </html>
package org.arquillian.example.basic.welcome; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * This test can be run using the arquillian-weld-ee-embedded profile. * * @author asohun * @version 06.03.2015 */ @RunWith(Arquillian.class) public class GreeterTest { /** * @return */ @Deployment public static JavaArchive createDeployment() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class); jar.addPackage(Greeter.class.getPackage()); jar.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); return jar; } /** * */ @Inject private Greeter greeter; /** * */ @Test public void should_create_greeting() { Assert.assertEquals("Hello, Earthling!", greeter.createGreeting("Earthling")); greeter.greet(System.out, "Earthling"); } }
import { useState } from 'react'; import axios from 'axios'; import { get } from 'lodash-es'; import { formatError } from '../../utils/formatters'; export default function usePostAnnotation() { const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [success, setSuccess] = useState(false); const postAnnotation = async ( assetId, iaClass, rect, viewpoint, theta = 0, ) => { try { setLoading(true); setError(null); const response = await axios({ url: `${__houston_url__}/api/v1/annotations/`, withCredentials: true, method: 'post', data: { viewpoint, asset_guid: assetId, ia_class: iaClass, bounds: { theta, rect, }, }, }); const successful = get(response, 'status') === 200; const newAnnotationGuid = get(response, ['data', 'guid']); if (successful) { setSuccess(true); setError(null); setLoading(false); return newAnnotationGuid; } const backendErrorMessage = get(response, 'passed_message'); const errorMessage = backendErrorMessage || formatError(response); setError(errorMessage); setSuccess(false); setLoading(false); return null; } catch (postError) { const backendErrorMessage = get(postError, [ 'response', 'data', 'passed_message', ]); const errorMessage = backendErrorMessage || formatError(postError); setError(errorMessage); setSuccess(false); setLoading(false); return null; } }; return { postAnnotation, loading, error, setError, success, setSuccess, }; }
// Copyright (c) 2023 Cisco and/or its affiliates. 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package response import ( "io" "strconv" "strings" "github.com/cisco-open/libnasp/components/kafka-protocol-go/pkg/pools" typesbytes "github.com/cisco-open/libnasp/components/kafka-protocol-go/pkg/protocol/types/bytes" "github.com/cisco-open/libnasp/components/kafka-protocol-go/pkg/protocol/messages/request" "github.com/cisco-open/libnasp/components/kafka-protocol-go/pkg/protocol" "github.com/cisco-open/libnasp/components/kafka-protocol-go/pkg/protocol/messages" "github.com/cisco-open/libnasp/components/kafka-protocol-go/pkg/protocol/messages/response" "emperror.dev/errors" ) type Response struct { data protocol.MessageData headerData response.Header } func (r *Response) HeaderData() *response.Header { return &r.headerData } func (r *Response) Data() protocol.MessageData { return r.data } func (r *Response) String() string { var s strings.Builder s.WriteString("{\"headerData\": ") s.WriteString(r.headerData.String()) s.WriteString(", \"data\": ") s.WriteString(r.data.String()) s.WriteRune('}') return s.String() } // Serialize serializes this Kafka response according to the given Kafka protocol version func (r *Response) Serialize(apiVersion int16) ([]byte, error) { apiKey := r.data.ApiKey() hdrVersion := headerVersion(apiKey, apiVersion) if hdrVersion == -1 { return nil, errors.New(strings.Join([]string{"unsupported api key", strconv.Itoa(int(apiKey))}, " ")) } if hdrVersion < response.HeaderLowestSupportedVersion() || hdrVersion > response.HeaderHighestSupportedVersion() { return nil, errors.New(strings.Join([]string{"unsupported response header version", strconv.Itoa(int(hdrVersion))}, " ")) } size, err := r.SizeInBytes(apiVersion) if err != nil { return nil, errors.WrapIf(err, "couldn't compute response size") } buf := make([]byte, 0, size) w := typesbytes.NewSliceWriter(buf) err = r.headerData.Write(&w, hdrVersion) if err != nil { return nil, errors.WrapIf(err, strings.Join([]string{"couldn't serialize response header for api key", strconv.Itoa(int(apiKey)), ", api version", strconv.Itoa(int(apiVersion)), ", header version", strconv.Itoa(int(hdrVersion))}, " ")) } err = r.data.Write(&w, apiVersion) if err != nil { return nil, errors.WrapIf(err, strings.Join([]string{"couldn't serialize response message for api key", strconv.Itoa(int(apiKey)), ", api version", strconv.Itoa(int(apiVersion))}, " ")) } return w.Bytes(), nil } // SizeInBytes returns the max size of this Kafka response in bytes when it's serialized func (r *Response) SizeInBytes(apiVersion int16) (int, error) { apiKey := r.data.ApiKey() hrdVersion := headerVersion(apiKey, apiVersion) if hrdVersion == -1 { return 0, errors.New(strings.Join([]string{"unsupported api key", strconv.Itoa(int(apiKey))}, " ")) } if hrdVersion < request.HeaderLowestSupportedVersion() || hrdVersion > request.HeaderHighestSupportedVersion() { return 0, errors.New(strings.Join([]string{"unsupported response header version", strconv.Itoa(int(hrdVersion))}, " ")) } hdrSize, err := r.headerData.SizeInBytes(hrdVersion) if err != nil { return 0, errors.WrapIf(err, "couldn't compute response header size") } dataSize, err := r.data.SizeInBytes(apiVersion) if err != nil { return 0, errors.WrapIf(err, "couldn't compute response data size") } return hdrSize + dataSize, nil } // Release releases the dynamically allocated fields of this object by returning then to object pools func (r *Response) Release() { if r == nil { return } r.headerData.Release() if r.data != nil { r.data.Release() } } // Parse deserializes this Kafka response func Parse(msg []byte, requestApiKey, requestApiVersion int16, requestCorrelationId int32) (Response, error) { hdrVersion := headerVersion(requestApiKey, requestApiVersion) if hdrVersion == -1 { return Response{}, errors.New(strings.Join([]string{"unsupported api key", strconv.Itoa(int(requestApiKey))}, " ")) } r := pools.GetBytesReader(msg) defer pools.ReleaseBytesReader(r) var hdr response.Header err := hdr.Read(r, hdrVersion) if err != nil { hdr.Release() return Response{}, errors.WrapIf(err, strings.Join([]string{"couldn't parse response header for api key", strconv.Itoa(int(requestApiKey)), ", api version", strconv.Itoa(int(requestApiVersion)), ", header version", strconv.Itoa(int(hdrVersion))}, " ")) } if hdr.CorrelationId() != requestCorrelationId { hdr.Release() return Response{}, errors.New(strings.Join([]string{"response correlation id", strconv.Itoa(int(hdr.CorrelationId())), "doesn't match request correlation id", strconv.Itoa(int(requestCorrelationId))}, " ")) } bufCurrentReadingPos := r.Size() - int64(r.Len()) // create typed request data struct resp, err := messages.NewResponse(requestApiKey) if err != nil { hdr.Release() return Response{}, errors.WrapIf(err, strings.Join([]string{"couldn't create new response object for api key", strconv.Itoa(int(requestApiKey)), ", api version", strconv.Itoa(int(requestApiVersion))}, " ")) } err = resp.Read(r, requestApiVersion) if err != nil { // ApiVersions needs special handling. If the broker doesn't support the api version specified in the ApiVersions // request than the broker will respond with an ApiVersions response version 0. Thus, if we can not parse // the ApiVersions response with request's api version than fall back to version 0 if requestApiVersion == 18 && requestApiVersion != 0 { if _, err = r.Seek(bufCurrentReadingPos, io.SeekStart); err != nil { hdr.Release() return Response{}, errors.WrapIf(err, "couldn't reset buffer position to retry parsing ApiVersions response with api version 0") } err = resp.Read(r, 0) } if err != nil { hdr.Release() return Response{}, errors.WrapIf(err, strings.Join([]string{"couldn't parse response message for api key", strconv.Itoa(int(requestApiKey)), ", api version", strconv.Itoa(int(requestApiVersion)), ", request correlation id", strconv.Itoa(int(requestCorrelationId))}, " ")) } } return Response{ headerData: hdr, data: resp, }, nil }
import com.codeborne.selenide.logevents.SelenideLogger; import io.qameta.allure.selenide.AllureSelenide; import org.junit.jupiter.api.Test; import static com.codeborne.selenide.Condition.text; import static com.codeborne.selenide.Selectors.byText; import static com.codeborne.selenide.Selenide.$; import static com.codeborne.selenide.Selenide.open; import static io.qameta.allure.Allure.step; public class SelenideSearchIssuesWithLambdaTest { SelenideSearchIssuesWithSteps selenideSearchIssuesWithSteps = new SelenideSearchIssuesWithSteps(); private static final String REPOSITORY = "/DimaKarpuk"; private static final String NameREPOSITORY = "/demoqa-tests-23"; private static final int ISSUE = 1; @Test void selenideSearchIssuesLambda(){ SelenideLogger.addListener("allure", new AllureSelenide()); step("Открываем главную страницу", () -> { open("https://github.com"); }); step("Ищем репозиторий " + REPOSITORY, () -> { $(".header-search-button").click(); $("#query-builder-test").setValue(REPOSITORY).pressEnter(); }); step("Кликаем по ссылке репозитория " + NameREPOSITORY, () -> { $(byText(NameREPOSITORY)).click(); }); step("Открываем таб issues", () -> { $("#issues-tab").click(); }); step("Проверяем наличие issues с номером " + ISSUE, () -> { $("[class = 'opened-by']").shouldHave(text("#" + ISSUE)); }); } @Test void selenideTestWithSteps(){ selenideSearchIssuesWithSteps.openMainPage(); selenideSearchIssuesWithSteps.searchRepository(REPOSITORY); selenideSearchIssuesWithSteps.clickOnRepositoryLink(NameREPOSITORY); selenideSearchIssuesWithSteps.openIssuesTab(); selenideSearchIssuesWithSteps.searchIssuesWithNumb(ISSUE); } }
<template> <div class="submit-form"> <div v-if="!submitted"> <h4>Add new Movie</h4> <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="title" required v-model="movie.title" name="title" /> </div> <div class="form-group"> <label for="actors">Actors</label> <input class="form-control" id="actors" required v-model="movie.actors" name="actors" /> </div> <div class="form-group"> <label for="productors">Productors</label> <input class="form-control" id="productors" required v-model="movie.productors" name="productors" /> </div> <div class="form-group"> <label for="validationTextarea">Description</label> <textarea class="form-control" name="description" id="description" v-model="movie.description" required></textarea> </div> <div class="form-group"> <label for="date">Date</label> <Datepicker v-model="movie.date" placeholder="Enter Date"></Datepicker> </div> <div class="form-group"> <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" role="switch" id="flexSwitchCheckChecked" name="published" v-model="movie.published" checked> <label class="form-check-label" for="flexSwitchCheckChecked">Published</label> </div> </div> <div class="form-group"> <label for="url">Url</label> <input class="form-control" id="url" required v-model="movie.url" name="url" /> </div> <button @click="saveMovie" class="btn btn-success">Submit</button> </div> <div v-else> <h4>You submitted successfully!</h4> <button class="btn btn-success" @click="newMovie">Add</button> </div> </div> </template> <script> import MovieDataService from "../services/MovieDataService"; import Datepicker from 'vue3-date-time-picker'; export default { name: "add-movie", components: { Datepicker }, data() { return { movie: { id: null, title: "", actors: "", productors:"", description: "", date: null, published: false, url: "" }, submitted: false, date: null }; }, methods: { saveMovie() { var data = { title: this.movie.title, actors: this.movie.actors, productors: this.movie.productors, description: this.movie.description, date: this.movie.date, published: this.movie.published, url: this.movie.url }; MovieDataService.create(data) .then(response => { this.movie.id = response.data.id; console.log(response.data); this.submitted = true; }) .catch(e => { console.log(e); }); }, newMovie() { this.submitted = false; this.movie = {}; } } }; </script> <style> .submit-form { max-width: 300px; margin: auto; } </style>
# TODO: copy your mypytable.py solution from PA2-PA7 here import copy import csv #from tabulate import tabulate # uncomment if you want to use the pretty_print() method # install tabulate with: pip install tabulate # required functions/methods are noted with TODOs # provided unit tests are in test_mypytable.py # do not modify this class name, required function/method headers, or the unit tests class MyPyTable: """Represents a 2D table of data with column names. Attributes: column_names(list of str): M column names data(list of list of obj): 2D data structure storing mixed type data. There are N rows by M columns. """ def __init__(self, column_names=None, data=None): """Initializer for MyPyTable. Args: column_names(list of str): initial M column names (None if empty) data(list of list of obj): initial table data in shape NxM (None if empty) """ if column_names is None: column_names = [] self.column_names = copy.deepcopy(column_names) if data is None: data = [] self.data = copy.deepcopy(data) # def pretty_print(self): # """Prints the table in a nicely formatted grid structure. # """ # print(tabulate(self.data, headers=self.column_names)) def get_shape(self): """Computes the dimension of the table (N x M). Returns: int: number of rows in the table (N) int: number of cols in the table (M) """ return len(self.data), len(self.column_names) def get_column(self, col_identifier, include_missing_values=True): col = [] col_index = self.column_names.index(col_identifier) for row in self.data: col.append(row[col_index]) """Extracts a column from the table data as a list. Args: col_identifier(str or int): string for a column name or int for a column index include_missing_values(bool): True if missing values ("NA") should be included in the column, False otherwise. Returns: list of obj: 1D list of values in the column Notes: Raise ValueError on invalid col_identifier """ return col def convert_to_numeric(self): """Try to convert each value in the table to a numeric type (float). Notes: Leave values as is that cannot be converted to numeric. """ for row in range(len(self.data)): for i in range(len(self.data[row])): try: self.data[row][i] = float(self.data[row][i]) #attempts to convert to float, pass if fails except ValueError: pass def drop_rows(self, row_indexes_to_drop): """Remove rows from the table data. Args: row_indexes_to_drop(list of int): list of row indexes to remove from the table data. """ row_indexes_to_drop.sort(reverse=True) #sorts indices for row in row_indexes_to_drop: self.data.pop(row) #removes rows with said indices def load_from_file(self, filename): """Load column names and data from a CSV file. Args: filename(str): relative path for the CSV file to open and load the contents of. Returns: MyPyTable: return self so the caller can write code like table = MyPyTable().load_from_file(fname) Notes: Use the csv module. First row of CSV file is assumed to be the header. Calls convert_to_numeric() after load """ inFile = open(filename, 'r') reader = csv.reader(inFile) header = [] table = [] #opens and reads file and then created header and data table num = 0 for value in reader: if num != 0: table.append(value) else: header = value num +=1 #differentiates between headers and data inFile.close() self.column_names = header self.data = table #puts header and data into table self.convert_to_numeric() #converts applicable valujes to numeric return self def save_to_file(self, filename): """Save column names and data to a CSV file. Args: filename(str): relative path for the CSV file to save the contents to. Notes: Use the csv module. """ outFile = open(filename, 'w') writer = csv.writer(outFile) writer.writerow(self.column_names) writer.writerows(self.data) #writes out headers and data to a csv file def find_duplicates(self, key_column_names): """Returns a list of indexes representing duplicate rows. Rows are identified uniquely based on key_column_names. Args: key_column_names(list of str): column names to use as row keys. Returns list of int: list of indexes of duplicate rows found Notes: Subsequent occurrence(s) of a row are considered the duplicate(s). The first instance of a row is not considered a duplicate. """ index_holder = [] table = [] for i in key_column_names: index_holder.append(self.column_names.index(i)) #creates list of column indices for row in self.data: table.append(tuple(row[i] for i in index_holder)) #checks for duplicates and then returns list of the indexes of the duplicates return [j for j, x in enumerate(table) if x in table[:j]] def remove_rows_with_missing_values(self): """Remove rows from the table data that contain a missing value ("NA"). """ self.data = [i for i in self.data if "NA" not in i] #checks if rows have missing values and then removes them if they do def replace_missing_values_with_column_average(self, col_name): """For columns with continuous data, fill missing values in a column by the column's original average. Args: col_name(str): name of column to fill with the original average (of the column). """ col = self.column_names.index(col_name) cleaned = [row[col] for row in self.data if row[col] != "NA"] #finds rows that dont have missing values average = sum(cleaned)/len(cleaned) #computes average for selected column self.data = [[row[i] if i != col or row[i] != "NA" else average for i in range(len(row))] for row in self.data] #applies average to rows with NA values def compute_summary_statistics(self, col_names): """Calculates summary stats for this MyPyTable and stores the stats in a new MyPyTable. min: minimum of the column max: maximum of the column mid: mid-value (AKA mid-range) of the column avg: mean of the column median: median of the column Args: col_names(list of str): names of the numeric columns to compute summary stats for. Returns: MyPyTable: stores the summary stats computed. The column names and their order is as follows: ["attribute", "min", "max", "mid", "avg", "median"] Notes: Missing values should in the columns to compute summary stats for should be ignored. Assumes col_names only contains the names of columns with numeric data. """ header = ["attribute", "min", "max", "mid", "avg", "median"] table = [] #assigns lists for col in col_names: stats = [] values = self.get_column(col, False) #gets seleected column and does not include missing values if not values == []: values.sort() stats.append(col) #adds attributes stats.append(min(values)) #finds max stats.append(max(values)) #finds min stats.append((max(values) + min(values)) / 2) #finds middle value stats.append(sum(values) / len(values)) # finds mean if len(values) % 2 == 0: stats.append((values[int((len(values) -1) / 2)] + values[int(((len(values) -1) / 2) + 1)]) / 2) #median for even number of values else: stats.append(values[int((len(values)-1)/2)]) #median for odd values #finds median table.append(stats) #appends values to table return MyPyTable(header, table) def perform_inner_join(self, other_table, key_column_names): """Return a new MyPyTable that is this MyPyTable inner joined with other_table based on key_column_names. Args: other_table(MyPyTable): the second table to join this table with. key_column_names(list of str): column names to use as row keys. Returns: MyPyTable: the inner joined table. """ table1 = [] table2 = [] values = [] header = copy.deepcopy(self.column_names) for i in other_table.column_names: try: key_column_names.index(i) except ValueError: header.append(i) #checks other table for specified columns to join on try: for name in key_column_names: table1.append(self.column_names.index(name)) table2.append(other_table.column_names.index(name)) #Appends column names to both tables except: pass else: for rows in self.data: for rows2 in other_table.data: equal = True #sets values as equal for j in range(len(key_column_names)): value1 = rows[table1[j]] value2 = rows2[table2[j]] if value1 != value2: equal = False #tests if values in 2 tables are equal, changes to false if false break if equal == True: row = copy.deepcopy(rows) for k in range(len(rows2)): try: table2.index(k) except ValueError: row.append(rows2[k]) #if true, appends values to new row after deep copy values.append(row) #appends rows to data return MyPyTable(header, data = values) def perform_full_outer_join(self, other_table, key_column_names): """Return a new MyPyTable that is this MyPyTable fully outer joined with other_table based on key_column_names. Args: other_table(MyPyTable): the second table to join this table with. key_column_names(list of str): column names to use as row keys. Returns: MyPyTable: the fully outer joined table. Notes: Pad the attributes with missing values with "NA". """ table1 = [] table2 = [] values = [] header = copy.deepcopy(self.column_names) for i in other_table.column_names: try: key_column_names.index(i) except ValueError: header.append(i) #checks other table for specified columns to join on try: for name in key_column_names: table1.append(self.column_names.index(name)) table2.append(other_table.column_names.index(name)) #Appends column names to both tables except: pass else: for rows in self.data: for rows2 in other_table.data: equal = True #sets values as equal for j in range(len(key_column_names)): value1 = rows[table1[j]] value2 = rows2[table2[j]] if value1 != value2: equal = False #tests if values in 2 tables are equal, changes to false if false break if equal == True: row = copy.deepcopy(rows) for k in range(len(rows2)): try: table2.index(k) except ValueError: row.append(rows2[k]) #if true, appends values to new row after deep copy values.append(row) #appends rows to data # I did not know what to do past the inner join return MyPyTable(header, data = values) #if __name__ == "__main__":
import connection from "../../connectionDb.cjs"; import { v4 as uuidv4 } from 'uuid' import { GetCurrentDateString, GetTwoGroupInicials, TransformDateToCorrectFormatString } from "../helpers/index.js"; import { GetFileUrl } from "../../s3.js"; const getContacts = async (sql, ContactData, userId) => { try { const resultOfGetUserContacts = await connection.query(sql, ContactData) const contactChatData = resultOfGetUserContacts.rows // aqui mapeamos los datos para devolver un objeto con la misma estructura de un objeto contacts, pero cambiando la propiedad contact_user_id por user y otorgandole los datos del usuario obtenido a la propiedad user // ******************NOTA******************* // aqui dejamos la logica del map, porque como el resultado que nos devuelve el query solo es un elemento, el map se ejecutara una sola vez, cumpliendo su funcion si tener que modificarlo const contactsListOfUser = await Promise.all( contactChatData.map(async (contact, index) => { try { // 1) const sql = 'SELECT user_id, socket_id, username, profile_picture FROM users WHERE user_id = $1' // 2) const sqlForGetParticipantStatus = 'SELECT * FROM chat_participants WHERE user_id = $1 AND chat_id = $2' // 3) const sqlForGetBlocksOfUser = 'SELECT * FROM blocks WHERE blocker_user_id = $1 AND blocked_user_id = $2 AND chat_id = $3' // 4) const sqlForGetBlocksOfContact = 'SELECT * FROM blocks WHERE blocker_user_id = $1 AND blocked_user_id = $2 AND chat_id = $3' // 5) const sqlToGetValueOfThisContactIsDeletedFromContact = 'SELECT this_contact_is_deleted FROM contacts WHERE user_id = $1 AND contact_user_id = $2 AND chat_id = $3' // 1) ************************** const contactDataForSql = [contact.contact_user_id] // aqui estamos extrayendo todos los datos del contacto const GetContactData = await connection.query(sql, contactDataForSql) // 2) *************************** // aqui estamos extrayendo el status de la tabla chat_participants del contacto const contactDataForGetStatus = [contact.contact_user_id, contact.chat_id] const GetParticipantStatus = await connection.query(sqlForGetParticipantStatus, contactDataForGetStatus) // 3) *************************** // aqui estamos obteniendo el ultimo block registrado del usuario, para otorgarle a la propiedad isBlocked falso si el status es inactive o true si es active const dataForGetBlocksOfUser = [userId, contact.contact_user_id, contact.chat_id] const resultOfGetUserBlocksList = await connection.query(sqlForGetBlocksOfUser, dataForGetBlocksOfUser) const userBlocksList = resultOfGetUserBlocksList.rows // 4) *************************** // aqui estamos Obteniendo el ultimo block que hizo el contacto a nuestro usuario y si es que este esta activbo const dataForGetBlocksOfContact = [contact.contact_user_id, userId, contact.chat_id] const resultOfGetContactBlocksList = await connection.query(sqlForGetBlocksOfContact, dataForGetBlocksOfContact) const ContactblocksList = resultOfGetContactBlocksList.rows // 5) *************************** // aqui obteniendo el valor this_contact_is_deleted del contacto del usuario sea true o false, esto para poder validar si el contacto lo elimino a este usuario como su contacto const dataForGetValueOfThisContactIsDeletedFromContact = [contact.contact_user_id, userId, contact.chat_id] const resultOfValueOfThisContactIsDeletedFromContact = await connection.query(sqlToGetValueOfThisContactIsDeletedFromContact, dataForGetValueOfThisContactIsDeletedFromContact) // ******************************* const resultOfGetContactData = GetContactData.rows[0] const resultOfGetParticipantStatus = GetParticipantStatus.rows[0] const wasUserDeletedByHisContactValue = resultOfValueOfThisContactIsDeletedFromContact.rows[0].this_contact_is_deleted // Aqui estamos generando una url prefirmada para la imagen de perfil de nuestro usuario let profilePictureUrl = '/' if (resultOfGetContactData.profile_picture) { profilePictureUrl = await GetFileUrl(resultOfGetContactData.profile_picture, 88000) console.log(profilePictureUrl) } // aqui estamos obteniendo las dos primera siglas del nombre del usuario para pobnerlo como icono en la vista en caso de que su foto de perfil no se visualize const contactIconValue = GetTwoGroupInicials(resultOfGetContactData.username) // *******aqui validamos si el contacto bloqueo al usuario, para que en la vista no se muestre la foto de usuario al contacto y mas informacion de importacion, si es que el contacto bloqueo a el usuario ********* let isUserBlockedForContact = false let isUserValidatedForContact = ContactblocksList.length > 0 ? true : false // aqui validamos si es que resultOfGetParticipantStatus.status exite, ya que el contacto podria haberse eliminido y el valor del status puede ser undefined let contactStatus = 'inactive' if (resultOfGetParticipantStatus) { contactStatus = resultOfGetParticipantStatus.status } if (ContactblocksList.length > 0) { isUserBlockedForContact = ContactblocksList[ContactblocksList.length - 1].status === 'active' ? true : false } const contactDataObtained = { ...resultOfGetContactData, socket_id: resultOfGetContactData.socket_id, profile_picture: profilePictureUrl, contact_icon: contactIconValue, status: contactStatus, contact_blocked_you: isUserBlockedForContact, contact_has_validated_you: isUserValidatedForContact, was_User_Deleted_By_His_Contact: wasUserDeletedByHisContactValue } // /* ********* Aqui validamos el ultimo bloquo que hizo el usuario a este contacto y si el bloqueo es active o inactive *********** */ // aqui validamos el ultimo bloqueo que hizo el usuario al contacto y si esta es activo, es decir que lo tiene bloqueado al contacto, para que se visualize de esta forma en la vista const isContactValidatedForUser = userBlocksList.length > 0 ? true : false const isContactBlockedForUser = isContactValidatedForUser && userBlocksList[userBlocksList.length - 1].status === 'active' ? true : false // aqui estamos transformando la fecha de creacion de los contactos a un formato string const creationDateOfContact = TransformDateToCorrectFormatString(contact.creation_date) return { user_id: userId, contact_id: contact.contact_id, contact_user: contactDataObtained, chat_id: contact.chat_id, is_blocked: isContactBlockedForUser, is_contact_validated: isContactValidatedForUser, creation_date: creationDateOfContact } } catch (error) { console.log(error) } }) ) return contactsListOfUser } catch (error) { throw { status: 500, message: error?.message || error }; } } const getContactList = async (sql, userData, userId) => { try { const resultOfGetUserContacts = await connection.query(sql, userData) // aqui estamos filtrando solo los contactos del usuario que en su campo this_contact_is_deleted en la tabla contacts de db enten en false, haciendo referencia que el usuario no elimino al contacto const contactsList = resultOfGetUserContacts.rows.filter((contact) => contact.this_contact_is_deleted === false) // console.log(contactsList) // aqui mapeamos los datos para devolver un objeto con la misma estructura de un objeto contacts, pero cambiando la propiedad contact_user_id por user y otorgandole los datos del usuario obtenido a la propiedad user const contactsListOfUser = await Promise.all( contactsList.map(async (contact, index) => { try { // 1) const sql = 'SELECT user_id, socket_id, username, profile_picture FROM users WHERE user_id = $1' // 2) const sqlForGetParticipantStatus = 'SELECT * FROM chat_participants WHERE user_id = $1 AND chat_id = $2' // 3) const sqlForGetBlocksOfUser = 'SELECT * FROM blocks WHERE blocker_user_id = $1 AND blocked_user_id = $2 AND chat_id = $3' // 4) const sqlForGetBlocksOfContact = 'SELECT * FROM blocks WHERE blocker_user_id = $1 AND blocked_user_id = $2 AND chat_id = $3' // 5) const sqlToGetValueOfThisContactIsDeletedFromContact = 'SELECT this_contact_is_deleted FROM contacts WHERE user_id = $1 AND contact_user_id = $2 AND chat_id = $3' // 1) ************************** const contactDataForSql = [contact.contact_user_id] // aqui estamos extrayendo todos los datos del contacto const GetContactData = await connection.query(sql, contactDataForSql) // 2) *************************** // aqui estamos extrayendo el status de la tabla chat_participants del contacto const contactDataForGetStatus = [contact.contact_user_id, contact.chat_id] const GetParticipantStatus = await connection.query(sqlForGetParticipantStatus, contactDataForGetStatus) // 3) *************************** // aqui estamos obteniendo el ultimo block registrado del usuario, para otorgarle a la propiedad isBlocked falso si el status es inactive o true si es active const dataForGetBlocksOfUser = [userId, contact.contact_user_id, contact.chat_id] const resultOfGetUserBlocksList = await connection.query(sqlForGetBlocksOfUser, dataForGetBlocksOfUser) const userBlocksList = resultOfGetUserBlocksList.rows // 4) *************************** // aqui estamos Obteniendo el ultimo block que hizo el contacto a nuestro usuario y si es que este esta activbo const dataForGetBlocksOfContact = [contact.contact_user_id, userId, contact.chat_id] const resultOfGetContactBlocksList = await connection.query(sqlForGetBlocksOfContact, dataForGetBlocksOfContact) const ContactblocksList = resultOfGetContactBlocksList.rows // 5) *************************** // aqui obteniendo el valor this_contact_is_deleted del contacto del usuario sea true o false, esto para poder validar si el contacto lo elimino a este usuario como su contacto const dataForGetValueOfThisContactIsDeletedFromContact = [contact.contact_user_id, userId, contact.chat_id] const resultOfValueOfThisContactIsDeletedFromContact = await connection.query(sqlToGetValueOfThisContactIsDeletedFromContact, dataForGetValueOfThisContactIsDeletedFromContact) // ******************************* const resultOfGetContactData = GetContactData.rows[0] const resultOfGetParticipantStatus = GetParticipantStatus.rows[0] const wasUserDeletedByHisContactValue = resultOfValueOfThisContactIsDeletedFromContact.rows[0].this_contact_is_deleted // Aqui estamos generando una url prefirmada para la imagen de perfil de nuestro usuario let profilePictureUrl = '/' if (resultOfGetContactData.profile_picture) { profilePictureUrl = await GetFileUrl(resultOfGetContactData.profile_picture, 88000) // console.log(profilePictureUrl) } // aqui estamos obteniendo las dos primera siglas del nombre del usuario para pobnerlo como icono en la vista en caso de que su foto de perfil no se visualize const contactIconValue = GetTwoGroupInicials(resultOfGetContactData.username) // ******aqui validamos si el contacto bloqueo al usuario, para que en la vista no se muestre la foto de usuario al contacto y mas informacion de importacion, si es que el contacto bloqueo a el usuario****** let isUserBlockedForContact = false let isUserValidatedForContact = ContactblocksList.length > 0 ? true : false // aqui validamos si es que resultOfGetParticipantStatus.status exite, ya que el contacto podria haberse eliminido y el valor del status puede ser undefined let contactStatus = 'inactive' if (resultOfGetParticipantStatus) { contactStatus = resultOfGetParticipantStatus.status } if (ContactblocksList.length > 0) { isUserBlockedForContact = ContactblocksList[ContactblocksList.length - 1].status === 'active' ? true : false } const contactDataObtained = { ...resultOfGetContactData, profile_picture: profilePictureUrl, contact_icon: contactIconValue, status: contactStatus, contact_blocked_you: isUserBlockedForContact, contact_has_validated_you: isUserValidatedForContact, was_User_Deleted_By_His_Contact: wasUserDeletedByHisContactValue } // /* ********* Aqui validamos el ultimo bloquo que hizo el usuario a este contacto y si el bloqueo es active o inactive *********** */ // aqui validamos el ultimo bloqueo que hizo el usuario al contacto y si esta es activo, es decir que lo tiene bloqueado al contacto, para que se visualize de esta forma en la vista const isContactValidatedForUser = userBlocksList.length > 0 ? true : false const isContactBlockedForUser = isContactValidatedForUser && userBlocksList[userBlocksList.length - 1].status === 'active' ? true : false // aqui estamos transformando la fecha de creacion de los contactos a un formato string const creationDateOfContact = TransformDateToCorrectFormatString(contact.creation_date) return { user_id: userId, contact_id: contact.contact_id, contact_user: contactDataObtained, chat_id: contact.chat_id, is_blocked: isContactBlockedForUser, is_contact_validated: isContactValidatedForUser, creation_date: creationDateOfContact } } catch (error) { console.log(error) } }) ) return contactsListOfUser } catch (error) { throw { status: 500, message: error?.message || error }; } } const saveContact = async (sqlForGetExistingContact, dataForSearchContact, sqlForRegisterUsersToChat, sqlForResgisterNewContact, sqlForCreateChat, sqlForResgisterNewBlockInactive, userId, contact_user_id) => { try { const resultToSearchContact = await connection.query(sqlForGetExistingContact, dataForSearchContact) const contactObtained = resultToSearchContact.rows[0] if (resultToSearchContact.rows.length === 1) { // 1) // ************ aqui registramos al usuario como participante del chat ya exitente ************* const userData = userId const unionDate = GetCurrentDateString() const dataForRegisterChat = [contactObtained.chat_id, userData, 'inactive', unionDate] const resultOfUserRegisterInChat = await connection.query(sqlForRegisterUsersToChat, dataForRegisterChat) if (resultOfUserRegisterInChat.rowCount === 0) { console.log('la propiedad rowCount indica que nos se registro los participantes del chat al chat con exito') throw { status: 500, message: `An error occurred, try again` } } // 2) // ************ aqui creamos un nuevo contacto y lo enlazamos con el chat ya exitente ************* const contact_id = uuidv4() const creation_date = GetCurrentDateString() const dataForRegisterContact = [contact_id, userId, contact_user_id, contactObtained.chat_id, creation_date] const resultOfContactsCreation = await connection.query(sqlForResgisterNewContact, dataForRegisterContact) if (resultOfContactsCreation.rowCount === 0) { console.log('la propiedad rowCount indica que el nuevo contacto no se creo con exito') throw { status: 500, message: `An error occurred, try again` } } // ***************************************** // ADVERTENCIA: Aqui ya no creamos ningun nuevo block inactive al usuario, por que cuando este se elimina de la tabla de contacts, su historial de blocks permenece intacto, y si este deja en block active al contacto que elimino cuando lo vuelva a agregar este seguira con el bloqueo activo hacia ese contacto, por lo que tendra que desbloquearlo manualmente si asi lo quiere el usuario // // 3) // // ************ aqui creamos un nuevo block inactive para el contacto recien creado ************* // // este es el id de bloqueo inactivo para el usuario que mando el mensaje // const block_id = uuidv4() // const blockStatus = 'inactive' // const blockDate = contactObtained.creation_date // const dataForRegisterBlock = [block_id, userId, contact_user_id, blockDate, contactObtained.chat_id, blockStatus] // const resultOfBlocksCreation = await connection.query(sqlForResgisterNewBlockInactive, dataForRegisterBlock) // if (resultOfBlocksCreation.rowCount === 0) { // console.log('la propiedad rowCount indica que el nuevo contacto no se creo con exito') // throw { status: 500, message: `An error occurred, try again` } // } // ********************************************** } else { // B)******************************************* // 1) // ************ Creacion de chat ************* const chat_id = uuidv4() const name = `name${userId, contact_user_id}` const chat_type = 'contact' const creationDate = GetCurrentDateString() const chatDataForRegister = [chat_id, name, chat_type, creationDate] const resultChatCreation = await connection.query(sqlForCreateChat, chatDataForRegister) if (resultChatCreation.rowCount === 0) { console.log('la propiedad rowCount indica que el chat no se creo con exito') throw { status: 500, message: `An error occurred, try again` } } // 2) // ******** creacion de participantes de chat *********** const listOfUsers = [{ id: userId }, { id: contact_user_id }] const unionDate = GetCurrentDateString() listOfUsers.forEach(async (participant) => { const adminDataForChatRegister = [chat_id, participant.id, 'inactive', unionDate] const resultOfUserRegisterInChat = await connection.query(sqlForRegisterUsersToChat, adminDataForChatRegister) if (resultOfUserRegisterInChat.rowCount === 0) { console.log('la propiedad rowCount indica que nos se registro los participantes del chat al chat con exito') throw { status: 500, message: `An error occurred, try again` } } }) // 3) // ************ Creacion de nuevo contacto ************* // este es el id de contacto para el usuario que mando el mensaje const contact_id_one = uuidv4() // este es el id de contacto para el usuario que recibio el mensaje const contact_id_two = uuidv4() const creation_date = GetCurrentDateString() const DataForRegisterContacts = [[contact_id_one, userId, contact_user_id, chat_id, creation_date], [contact_id_two, contact_user_id, userId, chat_id, creation_date]] DataForRegisterContacts.forEach(async (dataForCreateContact, index) => { const dataForQuery = DataForRegisterContacts[index] // console.log(dataForQuery) const resultOfContactsCreation = await connection.query(sqlForResgisterNewContact, dataForQuery) if (resultOfContactsCreation.rowCount === 0) { console.log('la propiedad rowCount indica que el nuevo contacto no se creo con exito') throw { status: 500, message: `An error occurred, try again` } } }) // 4) // ************ Creacion de registros de bloqueo inactivo para todos los participantes del chat de contacto ************* // este es el id de bloqueo inactivo para el usuario que mando el mensaje const block_id_one = uuidv4() const blockStatus = 'inactive' const blockDate = GetCurrentDateString() const DataForRegisterBlock = [block_id_one, userId, contact_user_id, blockDate, chat_id, blockStatus] const resultOfBlocksCreation = await connection.query(sqlForResgisterNewBlockInactive, DataForRegisterBlock) if (resultOfBlocksCreation.rowCount === 0) { console.log('la propiedad rowCount indica que el nuevo contacto no se creo con exito') throw { status: 500, message: `An error occurred, try again` } } } return } catch (error) { throw error } } const deleteContact = async (sqlForValidateAllContacts, dataToObtainAllContactInformation, sqlForDeleteContacts, sqlForDeleteChatParticipants, sqlForDeleteAllBlocksOfChat, sqlForDeleteAllChatHistoryDeletions, sqlForDeleteAllChatNotifications, sqlForDeleteAllChatsMessages, sqlForDeleteContactChat, sqlForUpdateContactInformation, sqlForResgisterChatDeletionMessages, userId, contactUserId, chatId) => { try { const resultOfGetAllContactsData = await connection.query(sqlForValidateAllContacts, dataToObtainAllContactInformation) // console.log('resultOfGetAllChatParticipants') // console.log(resultOfGetAllContactsData.rows) // aqui estamos extrayendo solo los objetos que tenga la propiedad this_contact_is_deleted en false, para ejecutar una de la dos condicionales que estan mas abajo const numberOfContactsNotDeletedInChat = resultOfGetAllContactsData.rows.filter((contact) => contact.this_contact_is_deleted === false) if (numberOfContactsNotDeletedInChat.length === 1) { // 2)******************************************* // *********** Aqui eliminamos el contacto del usuario ************ const dataForDeleteContact = [chatId] const resultOfDeleteContact = await connection.query(sqlForDeleteContacts, dataForDeleteContact) if (resultOfDeleteContact.rowCount === 0) { console.log('la propiedad rowCount indica que el contact del usuario no se elimino con exito DELETE /contacts') throw { status: 500, message: `An error occurred, try again` } } // 3)******************************************* // *********** Aqui eliminamos los participantes de chat ************ const dataForDeleteChatParticipants = [chatId] const resultOfDeleteChatParticipants = await connection.query(sqlForDeleteChatParticipants, dataForDeleteChatParticipants) if (resultOfDeleteChatParticipants.rowCount === 0) { console.log('la propiedad rowCount indica que el participante no se elimino con exito DELETE /groups') throw { status: 500, message: `An error occurred, try again` } } // 4)******************************************* // *********** Aqui eliminamos todos los Blocks del Usuario ************ const dataForDeleteAllBlocksOfChat = [chatId] const resultOfDeleteBlocks = await connection.query(sqlForDeleteAllBlocksOfChat, dataForDeleteAllBlocksOfChat) if (resultOfDeleteBlocks.rowCount === 0) { console.log('la propiedad rowCount indica que no se encontraron blocks del usuario para eliminarlos con exito DELETE /contacts') // throw { status: 500, message: `An error occurred, try again` } } // 5)******************************************* // *********** Aqui eliminamos todos registro de la tabla chat_history_deletions que estan relacionados con el chat de contacto ************ const dataForDeleteAllChatHistoryDeletions = [chatId] const resultOfDeleteAllChatHistoryDeletions = await connection.query(sqlForDeleteAllChatHistoryDeletions, dataForDeleteAllChatHistoryDeletions) if (resultOfDeleteAllChatHistoryDeletions.rowCount === 0) { console.log('la propiedad rowCount indica que no se encontraron los registros de eliminacion del historial de mensajes en la tabla chat_history_deletions para eliminarlos con exito DELETE /contacts') // throw { status: 500, message: `An error occurred, try again` } } // 6)******************************************* // *********** Aqui eliminamos todos las notificaciones del chat de contacto ************ const dataForDeleteAllChatsNotifications = [chatId] const resultOfDeleteAllChatsNotifications = await connection.query(sqlForDeleteAllChatNotifications, dataForDeleteAllChatsNotifications) if (resultOfDeleteAllChatsNotifications.rowCount === 0) { console.log('la propiedad rowCount indica que nose encontraron notificaciones para eliminar del contact chat con exito DELETE /contact') // throw { status: 500, message: `An error occurred, try again` } } // 7)******************************************* // *********** Aqui eliminamos todos los mensajes del chat de contacto ************ const dataForDeleteAllChatsMessages = [chatId] const resultOfDeleteAllChatsMessages = await connection.query(sqlForDeleteAllChatsMessages, dataForDeleteAllChatsMessages) if (resultOfDeleteAllChatsMessages.rowCount === 0) { console.log('la propiedad rowCount indica que no se encontraron mensajes que eleminar del contact chat con exito DELETE /grupo') // throw { status: 500, message: `An error occurred, try again` } } // 8)******************************************* // *********** Por ultimos aqui eliminamos permanentemente el chat de contacto ************ const dataForDeleteContactChat = [chatId] const resultOfDeleteContactChat = await connection.query(sqlForDeleteContactChat, dataForDeleteContactChat) if (resultOfDeleteContactChat.rowCount === 0) { console.log('la propiedad rowCount indica que el registro de chat no se elimino permaenente con exito DELETE /contacts') throw { status: 500, message: `An error occurred, try again` } } } else if (numberOfContactsNotDeletedInChat.length === 2) { // ****************************************** // B)******************************************* // 1)******************************************* // *********** Aqui eliminamos el contacto del usuario ************ // const dataForDeleteContact = [userId, contactUserId, chatId] // const resultOfDeleteContact = await connection.query(sqlForDeleteContact, dataForDeleteContact) // if (resultOfDeleteContact.rowCount === 0) { // console.log('la propiedad rowCount indica que el contact del usuario no se elimino con exito DELETE /contacts') // throw { status: 500, message: `An error occurred, try again` } // } // // 2)******************************************* // // *********** Aqui eliminamos los participantes de chat ************ // const dataForDeleteChatParticipants = [chatId, userId] // const resultOfDeleteChatParticipants = await connection.query(sqlForDeleteChatParticipants, dataForDeleteChatParticipants) // if (resultOfDeleteChatParticipants.rowCount === 0) { // console.log('la propiedad rowCount indica que el participante del chat no se elimino con exito DELETE /contact') // throw { status: 500, message: `An error occurred, try again` } // } // ******* ADVERTENCIA: Aqui ya no eliminamos los blocks del usuario, si no que esperamos a que el ultimo integrante del chat, elimine el chat de contacto, para que todos los blocks de ambos participantes sean eliminados permanentemente *************************** // 3)******************************************* // *********** Aqui eliminamos todos los Blocks del Usuario ************ // const resultOfDeleteBlocks = await connection.query(sqlForDeleteBlocksOfUser, dataForDeleteContact) // if (resultOfDeleteBlocks.rowCount === 0) { // console.log('la propiedad rowCount indica que los blocks del usuario no se eliminaron con exito DELETE /contact') // throw { status: 500, message: `An error occurred, try again` } // } // 4)******************************************* // *********** aqui actualizamos el valor de la columna this_contact_is_deleted de la tabla contacts del primer participante en eliminar a su contacto ************ const valueOfThisContactIsDeleted = true const dataForUpdateContactInformation = [valueOfThisContactIsDeleted, userId, chatId] const resultOfUpdateContactInformation = await connection.query(sqlForUpdateContactInformation, dataForUpdateContactInformation) if (resultOfUpdateContactInformation.rowCount === 0) { console.log('la propiedad rowCount indica que no se actualizo el valor del campo this_contact_is_deleted del contacto con exito DELETE /contact') throw { status: 500, message: `An error occurred, try again` } } // 5)******************************************* // *********** Aqui Registramos una eliminacion del historial del chat, para que si el otra conctacto le vuelve a escribir al usuario, este no tenga acceso a los mensajes antiguos ************ const deletionId = uuidv4() const deletionDate = GetCurrentDateString() const dataForCreateChatDeletionMessage = [deletionId, userId, chatId, deletionDate] const resultOfCreateChatDeletionMessages = await connection.query(sqlForResgisterChatDeletionMessages, dataForCreateChatDeletionMessage) if (resultOfCreateChatDeletionMessages.rowCount === 0) { console.log('la propiedad rowCount indica que no se registro la eliminacion del historial de mensajes con exito DELETE /contact') throw { status: 500, message: `An error occurred, try again` } } } return } catch (error) { throw error } } export default { getContacts, getContactList, saveContact, deleteContact }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Homepage</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=Inter:wght@400;500;600&amp;display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@500&amp;display=swap" rel="stylesheet"> <link rel="stylesheet" href="./css/main.css"> </head> <body> <header class="header"> <div class="container"> <div class="header-list"><a class="header-item" href="#">Things to do</a><a class="header-item" href="#">Travel Guide</a><a class="header-item" href="#">Tours</a> </div> </div> </header> <main> <section class="top-tours"> <div class="container"> <h2 class="heading">Top Bangkok Tours</h2> <div class="tour-list"> <div class="tour-item"> <div class="tour-top"><img class="tour-image" src="https://images.unsplash.com/photo-1523906834658-6e24ef2386f9?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=683&amp;q=80" alt="bali"/><span class="tour-price">From $40</span></div> <div class="tour-content"> <h3 class="tour-title">Thailands Ayutthaya Temples Cruise from Bangkok Thailands Ayutthaya Temples Cruise from Bangkok</h3> <div class="tour-rating"> <div class="tour-review"> <div class="tour-star"><img src="./images/star.png" alt="tour-rating"/></div> <div class="tour-review-count"><span>4.8 (20 reviews)</span></div> </div><span class="tour-duration">Duration: 9 hours</span> </div><a class="tour-button" href="https://evondev.com" target="_blank" rel="noopener noreferrer">Tours Price $55</a> </div> </div> <div class="tour-item"> <div class="tour-top"><img class="tour-image" src="https://images.unsplash.com/photo-1501785888041-af3ef285b470?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1470&amp;q=80" alt="bali"/><span class="tour-price">From $60</span></div> <div class="tour-content"> <h3 class="tour-title">FLoating Markets Day Trip from Bangkok</h3> <div class="tour-rating"> <div class="tour-review"> <div class="tour-star"><img src="./images/star.png" alt="tour-rating"/></div> <div class="tour-review-count"><span>4.5 (30 reviews)</span></div> </div><span class="tour-duration">Duration: 15 hours</span> </div><a class="tour-button" href="https://evondev.com" target="_blank" rel="noopener noreferrer">Tours Price $88</a> </div> </div> <div class="tour-item"> <div class="tour-top"><img class="tour-image" src="https://images.unsplash.com/photo-1530789253388-582c481c54b0?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1470&amp;q=80" alt="bali"/><span class="tour-price">From $60</span></div> <div class="tour-content"> <h3 class="tour-title">FLoating Markets Day Trip from Bangkok</h3> <div class="tour-rating"> <div class="tour-review"> <div class="tour-star"><img src="./images/star.png" alt="tour-rating"/></div> <div class="tour-review-count"><span>4.5 (30 reviews)</span></div> </div><span class="tour-duration">Duration: 15 hours</span> </div><a class="tour-button" href="https://evondev.com" target="_blank" rel="noopener noreferrer">Tours Price $88</a> </div> </div> </div> </div> </section> <section class="popular"> <div class="container"> <h2 class="heading">Popular things to do in Bangkok</h2> <div class="popular-list"> <div class="popular-item"> <div class="popular-image"><img class="popular-img" src="https://images.unsplash.com/photo-1568849676085-51415703900f?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=687&amp;q=80" alt=""/><span class="popular-label">Must see</span></div> <div class="popular-content"><span class="popular-time">Sep 28 10:00 AM - 1:00 PM</span> <h3 class="popular-title">The Grand Palace</h3> <div class="popular-review"><img src="./images/star.png" alt="star"/><span>4.8 (12 reviews)</span></div> </div> </div> <div class="popular-item"> <div class="popular-image"><img class="popular-img" src="https://images.unsplash.com/photo-1568849676085-51415703900f?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=687&amp;q=80" alt=""/><span class="popular-label">Must see</span></div> <div class="popular-content"><span class="popular-time">Sep 28 10:00 AM - 1:00 PM</span> <h3 class="popular-title">The Grand Palace</h3> <div class="popular-review"><img src="./images/star.png" alt="star"/><span>4.8 (12 reviews)</span></div> </div> </div> <div class="popular-item"> <div class="popular-image"><img class="popular-img" src="https://images.unsplash.com/photo-1568849676085-51415703900f?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=687&amp;q=80" alt=""/><span class="popular-label">Must see</span></div> <div class="popular-content"><span class="popular-time">Sep 28 10:00 AM - 1:00 PM</span> <h3 class="popular-title">The Grand Palace</h3> <div class="popular-review"><img src="./images/star.png" alt="star"/><span>4.8 (12 reviews)</span></div> </div> </div> <div class="popular-item"> <div class="popular-image"><img class="popular-img" src="https://images.unsplash.com/photo-1568849676085-51415703900f?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=687&amp;q=80" alt=""/><span class="popular-label">Must see</span></div> <div class="popular-content"><span class="popular-time">Sep 28 10:00 AM - 1:00 PM</span> <h3 class="popular-title">The Grand Palace</h3> <div class="popular-review"><img src="./images/star.png" alt="star"/><span>4.8 (12 reviews)</span></div> </div> </div> </div> </div> </section> <section class="gem"> <div class="container"> <h2 class="heading">Hidden gems in Bangkok</h2> <div class="gem-list"> <div class="gem-item"><img src="https://images.unsplash.com/photo-1530521954074-e64f6810b32d?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1470&amp;q=80" alt=""></div> <div class="gem-item"><img src="https://images.unsplash.com/photo-1476514525535-07fb3b4ae5f1?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1470&amp;q=80" alt=""></div> <div class="gem-item"><img src="https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1421&amp;q=80" alt=""></div> <div class="gem-item"><img src="https://images.unsplash.com/photo-1488085061387-422e29b40080?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1931&amp;q=80" alt=""></div> <div class="gem-item"><img src="https://images.unsplash.com/photo-1503220317375-aaad61436b1b?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1470&amp;q=80" alt=""></div> </div> </div> </section> <section class="diamond"> <div class="container"> <h2 class="heading">Hidden gems in Bangkok</h2> <div class="diamond-list"> <div class="diamond-item"> <div class="diamond-image"><img src="https://images.unsplash.com/photo-1530521954074-e64f6810b32d?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1470&amp;q=80" alt=""> <div class="diamond-content"> <h3 class="diamond-title">Bangkok</h3> </div> </div> </div> <div class="diamond-item"> <div class="diamond-image"><img src="https://images.unsplash.com/photo-1476514525535-07fb3b4ae5f1?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1470&amp;q=80" alt=""> <div class="diamond-content"> <h3 class="diamond-title">Bangkok</h3> </div> </div> </div> <div class="diamond-item"> <div class="diamond-image"><img src="https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1421&amp;q=80" alt=""> <div class="diamond-content"> <h3 class="diamond-title">Bangkok</h3> </div> </div> </div> <div class="diamond-item"> <div class="diamond-image"><img src="https://images.unsplash.com/photo-1488085061387-422e29b40080?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1931&amp;q=80" alt=""> <div class="diamond-content"> <h3 class="diamond-title">Bangkok</h3> </div> </div> </div> </div><a class="button diamond-all" href="#">Explore All</a> </div> </section> <section class="grid"> <div class="container"> <div class="grid-layout"> <div class="grid-item">1</div> <div class="grid-item">2</div> <div class="grid-item">3</div> <div class="grid-item">4</div> <div class="grid-item">5</div> <div class="grid-item">6</div> <div class="grid-item">7</div> </div> <div class="my-name"><span>Evondev</span></div> <button class="button-rounded">icon</button> <div class="bag-icon"> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M4.53715 10.4713C4.80212 8.48412 6.49726 7 8.50207 7H15.4979C17.5027 7 19.1979 8.48412 19.4628 10.4713L20.3962 17.4713C20.7159 19.8693 18.8504 22 16.4313 22H7.56873C5.14958 22 3.2841 19.8693 3.60382 17.4713L4.53715 10.4713Z" stroke="#7B88A8" stroke-width="1.5"></path> <path d="M16 9V6C16 3.79086 14.2091 2 12 2V2C9.79086 2 8 3.79086 8 6L8 9" stroke="#7B88A8" stroke-width="1.5" stroke-linecap="round"></path> </svg> </div> <button class="pointer"><span>Demo</span><span>Icon</span></button> <div class="column"> <h3 class="title">this is tile</h3>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Hic ad reprehenderit, unde quas modi rerum iure cumque esse in quasi obcaecati cum architecto consequuntur dolorum dolore qui maiores, veritatis impedit! Lorem ipsum dolor sit amet consectetur, adipisicing elit. Hic ad reprehenderit, unde quas modi rerum iure cumque esse in quasi obcaecati cum architecto consequuntur dolorum dolore qui maiores, veritatis impedit! Lorem ipsum dolor sit amet consectetur, adipisicing elit. Hic ad reprehenderit, unde quas modi rerum iure cumque esse in quasi obcaecati cum architecto consequuntur dolorum dolore qui maiores, veritatis impedit! Lorem ipsum dolor sit amet consectetur, adipisicing elit. Hic ad reprehenderit, unde quas modi rerum iure cumque esse in quasi obcaecati cum architecto consequuntur dolorum dolore qui maiores, veritatis impedit! </div> <div class="boxed"></div> <div class="text-indent">evondev</div> <div class="box-overflow">Lorem ipsum dolor sit amet consectetur adipisicing elit. Odio doloribus minima dolorem accusantium soluta sunt quia assumenda esse, magni iure modi sapiente adipisci voluptatem eligendi aut iste laboriosam beatae eius!Odio quaerat dicta est, voluptatem quas esse magni quasi aliquid at tempore ratione, praesentium inventore sint repellat assumenda blanditiis, vel doloribus itaque quo voluptates explicabo quae cum incidunt. Recusandae, iure.Obcaecati fugit repellendus non, doloribus sapiente aspernatur temporibus laborum tempore similique quam tempora omnis rerum animi necessitatibus officia aliquid modi eligendi id dolor illo hic earum reiciendis et. Laudantium, cumque!Libero numquam beatae, accusamus voluptatibus dolor ducimus. Sint est cum dicta error temporibus explicabo vero asperiores mollitia officiis exercitationem assumenda, autem, odit sunt suscipit ea fugiat deleniti, quidem ipsa optio!Similique reprehenderit veritatis laborum provident dolores sint non, ex modi amet nesciunt est molestias nulla nostrum, rerum officiis esse dolor culpa? Provident consectetur doloremque nobis itaque recusandae quibusdam eius iure?Modi et reprehenderit labore, nemo, autem veniam facilis ratione officiis non error molestiae. Voluptas ipsum velit pariatur ad nisi dolorum eaque? Incidunt ex dignissimos doloremque. Ea recusandae ad blanditiis repellat.Cum non minus nihil illo amet aperiam, iste inventore perspiciatis vel soluta id, libero, in laborum! Dignissimos officia, facilis eum quia odio molestias placeat ab! Ab soluta deserunt nobis incidunt.Animi assumenda dolorem dolores, quod officia expedita dolorum odit voluptatibus nisi error temporibus quaerat eveniet reiciendis laboriosam, necessitatibus doloribus voluptate quisquam omnis. Blanditiis, eos quas. Maiores possimus earum deserunt impedit?Dicta labore impedit sint harum aut obcaecati molestias perspiciatis reiciendis, animi rerum illo assumenda aliquam commodi ullam aliquid quod similique a excepturi dolorem qui quasi nobis laborum vitae. Alias, ab?Molestias quaerat at accusantium autem beatae doloribus velit odio provident eaque possimus, aliquid sequi nulla sed dignissimos quidem iusto atque, error recusandae rerum quod alias ea officia, ad quasi. Odio?</div> <div class="image-ratio-wrapper"><img class="image-ratio" src="https://images.unsplash.com/photo-1517336714731-489689fd1ca8?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1452&amp;q=80"></div> <div class="counter"> <h1>HTML and CSS</h1> <h2>HTML Tutorial</h2> <h2>CSS Tutorial</h2> <h2>Bootstrap Tutorial</h2> <hr> <h1>JavaScript</h1> <h2>JavaScript Tutorial</h2> <h2>jQuery Tutorial</h2> <h2>JSON Tutorial</h2> <hr> <h1>Server Side</h1> <h2>SQL Tutorial</h2> <h2>PHP Tutorial</h2> </div> <div class="item-image"><img src="https://images.unsplash.com/photo-1616588589676-62b3bd4ff6d2?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=2064&amp;q=80"></div> <div class="title-clamp">My name is Evondev</div> <div class="card-item-wrapper"> <div class="card-item"><img src="https://images.unsplash.com/photo-1517336714731-489689fd1ca8?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=1452&amp;q=80"> <div class="card-item-content">Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequuntur quis molestias illum cupiditate! Facere molestiae accusantium asperiores debitis officia quae sunt esse, iure praesentium odio ipsa nisi eveniet assumenda soluta.</div> </div> </div> </div> </section> </main> <footer class="footer"> <div class="container footer-container"> <div class="footer-top"> <div class="footer-columns"> <div class="footer-column"><a class="footer-logo" href="/"><img srcSet="./images/logo.png 2x" alt="Airtrav"></a> <p class="footer-desc">Similarly, a loan taken out to buy a car may be secured by the car. The duration of the loan.</p> <form class="subscribe" action="" autocomplete> <input class="subscribe-email" type="email" placeholder="Enter your email"> <button class="subscribe-button" type="submit"><img srcSet="./images/icon-arrow-right.png 2x" alt="icon-arrow-right"></button> </form> </div> <div class="footer-column"> <h4 class="footer-heading">Services</h4> <ul class="footer-links"> <li class="footer-item"><a class="footer-link" href="#">Trip Planner</a></li> <li class="footer-item"><a class="footer-link" href="#">Tour Planning</a></li> <li class="footer-item"><a class="footer-link" href="#">Tour Guide</a></li> <li class="footer-item"><a class="footer-link" href="#">Tour Package</a></li> <li class="footer-item"><a class="footer-link" href="#">Tour advice</a></li> </ul> </div> <div class="footer-column"> <h4 class="footer-heading">Services</h4> <ul class="footer-links"> <li class="footer-item"><a class="footer-link" href="#">Trip Planner</a></li> <li class="footer-item"><a class="footer-link" href="#">Tour Planning</a></li> <li class="footer-item"><a class="footer-link" href="#">Tour Guide</a></li> <li class="footer-item"><a class="footer-link" href="#">Tour Package</a></li> <li class="footer-item"><a class="footer-link" href="#">Tour advice</a></li> </ul> </div> <div class="footer-column"> <h4 class="footer-heading">Services</h4> <ul class="footer-links"> <li class="footer-item"><a class="footer-link" href="#">Trip Planner</a></li> <li class="footer-item"><a class="footer-link" href="#">Tour Planning</a></li> <li class="footer-item"><a class="footer-link" href="#">Tour Guide</a></li> <li class="footer-item"><a class="footer-link" href="#">Tour Package</a></li> <li class="footer-item"><a class="footer-link" href="#">Tour advice</a></li> </ul> </div> </div> </div> <div class="footer-bottom"> <p class="footer-copyright">Copyright© 2023 UIHUT LLC. All rights reserved</p> <div class="footer-sn-list"> <div class="footer-sn-item"><a class="footer-sn-link" href="#"><img src="./images/icon-fb.svg"></a></div> <div class="footer-sn-item"><a class="footer-sn-link" href="#"><img src="./images/icon-fb.svg"></a></div> <div class="footer-sn-item"><a class="footer-sn-link" href="#"><img src="./images/icon-fb.svg"></a></div> <div class="footer-sn-item"><a class="footer-sn-link" href="#"><img src="./images/icon-fb.svg"></a></div> </div> </div> </div> </footer> </body> </html>
class Vehicle{ constructor( color = 'blue', wheels = 4, horn = 'beep beep'){ this.color = color; this.wheels = wheels; this.horn = horn; } honkHorn(){ console.log(this.horn); } } // the subclass of vehicle class Bicycle extends Vehicle { constructor(color = 'blue', wheels = 2, horn = 'honk honk'){ super(color, wheels, horn); } displayWheels(){ console.log(this.wheels); } } const myVehicle = new Vehicle(); myVehicle.honkHorn(); const myBike = new Bicycle(); myBike.honkHorn(); myBike.displayWheels();
--- name: 'Jekyll 小书' description: '用极客的方式搭建个人网站' edition: version: '3.2.1.p1' author: '安道' pages: '134' revdate: '2016-08-04' price: '20.00' order: 4 date: '2021/08/30' # no use, but required by `blog` extension body_class: 'product-page product-jekyll-book' --- <% content_for :toc do %> <ul> <li> <h3>第 1 章 简介</h3> <p>了解 Jekyll 是什么,阅读本书需要什么预备知识,源码下载地址。</p> </li> <li> <h3>第 2 章 安装 Jekyll</h3> <p>在电脑中安装 Ruby 和 Jekyll,为使用 Jekyll 做好准备。</p> </li> <li> <h3>第 3 章 创建第一个网站</h3> <p>生成第一个网站,并在浏览器中预览。</p> </li> <li> <h3>第 4 章 文章</h3> <p>介绍文章的组成,然后编写一个 rake 任务,自动创建文章。</p> </li> <li> <h3>第 5 章 页面</h3> <p>说明页面的组成,以及页面的存放位置和组织方式。</p> </li> <li> <h3>第 6 章 编写内容</h3> <p>说明如何正确编写易错的内容,包括插入图像、链接和代码高亮。</p> </li> <li> <h3>第 7 章 开发一个简单的主题</h3> <p>自己动手,使用 Twitter Bootstrap 开发一个 Jekyll 主题。</p> </li> <li> <h3>第 8 章 添加评论系统</h3> <p>Jekyll 网站默认没有评论系统,本章说明如何添加 Disqus 和多说。</p> </li> <li> <h3>第 9 章 Jekyll 的插件系统</h3> <p>全面了解 Jekyll 的插件系统,使用插件增强网站和主题的功能。</p> </li> <li> <h3>第 10 章 数据文件</h3> <p>把元数据保存在数据文件中,通过编程的方式在网站中调用。</p> </li> <li> <h3>第 11 章 把网站部署到服务器</h3> <p>把 Jekyll 网站部署到 GitHub Pages 和虚拟主机的最佳实践。</p> </li> <li> <h3>附录 A 设置 Jekyll 网站</h3> </li> <li> <h3>附录 B Markdown 句法简介</h3> </li> <li> <h3>附录 C Liquid 模板引擎简介</h3> </li> <li> <h3>附录 D 修订日志</h3> </li> </ul> <% end %> <% content_for :faq do%> <ul> <li> <h3>阅读这本书需要具备哪些知识?</h3> <p>您需要知道如何使用命令行,如何使用文本编辑器,了解基本的 HTML 和 CSS 知识。</p> </li> <li> <h3>这本书针对 Jekyll 的哪个版本?</h3> <p>本书针对 Jekyll 3.2(目前最新的版本),而且会随着新版的发布持续更新。</p> </li> <li> <h3>付款后如何下载电子书?</h3> <p>您付款后,销售平台会给您发送一封电子邮件,邮件中有电子书的下载链接,点击链接即可下载 PDF 和 ePub 格式的电子书。</p> </li> <li> <h3>以后会更新吗?新版还要收费吗?</h3> <p>本书采用“精益出版”策略,也就是说会不断更新完善。如果您已经购买电子书,后续更新都可免费获取。</p> </li> <li> <h3>如何下载后续更新的电子书?</h3> <p>本书更新后会通过销售平台给您发送电子邮件,邮件中有新版电子书的下载链接。</p> </li> <li> <h3>这本书有附带的源码吗?在哪里下载?</h3> <p>本书附带的源码托管在 GitHub 中,放在 <a href="https://github.com/jekyll-book" target="_blank" rel="noopener">jekyll-book</a> 组织名下。各章的源码在相应的仓库中。</p> </li> <li> <h3>我可以把自己购买的电子书分享给别人吗?</h3> <p>本书没有 DRM 限制,为的是让您自由选择阅读设备。本书受版权法保护,因此不能分享给别人。</p> </li> <li> <h3>我是在校生,有什么优惠吗?</h3> <p>本书针对在校生提供 7 折优惠,请到<%= link_to '这个网页', url_for('education'), title: '申请教育优惠' %>中申请。请提前准备好学生身份证明文件。</p> </li> </ul> <% end %>
import "./TaskModal.styles.css"; import { useState, useEffect } from "react"; import { useValidateForm } from "hooks"; import { initialTaskInfo } from "utils"; import { Toast } from "utils"; function TaskModal({ options }) { const { showModal, taskInfo, setShowModal } = options; const [modalTaskInfo, setModalTaskInfo] = useState(initialTaskInfo); const [formErrorMessage, SetFormErrorMessage] = useState(""); const { validateModal } = useValidateForm({ formErrorMessage, SetFormErrorMessage, }); function onInputChangeHandler(event) { const name = event.target?.name; const value = event.target?.value; setModalTaskInfo((p) => Object.assign({}, p, { [name]: value })); } function hideModal() { setShowModal(false); } function postTaskAction(e) { validateModal(e, hideModal, taskInfo); Toast.success(` Task ${taskInfo.Title === "" ? "Added" : "Updated"}`); } useEffect(() => { setModalTaskInfo((p) => Object.assign({}, p, taskInfo)); return () => setModalTaskInfo(initialTaskInfo); }, [taskInfo]); return ( <> <section className="modalBackground" style={{ display: showModal ? "block" : "none" }} ></section> <form onSubmit={(e) => { postTaskAction(e); }} className="task-modal" style={{ display: showModal ? "grid" : "none" }} > <button className="modal-close" onClick={() => hideModal()} type="button" > <span className=" material-icons-outlined">close</span> </button> <input type="text" placeholder="Add Title" className="modal-title" required name="Title" width="20" minLength="5" maxLength="40" value={modalTaskInfo.Title} onChange={(e) => onInputChangeHandler(e)} /> <select className="modal-tag" placeholder="Add Tag" required name="Tag" value={modalTaskInfo.Tag} onChange={(e) => onInputChangeHandler(e)} > <option disabled value=""> {" "} -- select an tag --{" "} </option> <option value="Intelligence">Intelligence</option> <option value="Strength">Strength</option> <option value="Social Skills">Social Skills</option> </select> <textarea type="text" className="modal-description" placeholder="Add Description" required name="Description" minLength="5" value={modalTaskInfo.Description} onChange={(e) => onInputChangeHandler(e)} ></textarea> <input type="number" className="modal-time" placeholder="Add Minutes" min="15" max="60" step="5" required name="Time" value={modalTaskInfo.Time} onChange={(e) => onInputChangeHandler(e)} /> <span className="modal-empty">{formErrorMessage}</span> <div className="modal-actions"> <button className="modal-action-cancel" onClick={() => hideModal()} type="button" > Cancel </button> <span className="modal-action-empty"></span> <button className="modal-action-add" type="submit"> {taskInfo.Title === "" ? "Add" : "Update"} </button> </div> </form> </> ); } export { TaskModal };
# READING LIST - The following is part of the recommended books for Computer Science Stucy in 1st Year College ## Reading List for modules - Principles of Programming - Programming in C, 4th Edi, *Stephen Kochan* - Head first C, *David Grithins* - The C programming language, *Kernighan, Brian W.* - Linux in a nutshell, *Siever Ellen* - [Learn yourself a Haskell](https://learnyouahaskell.com/chapters) - Introductory Mathematics for Computer Science - Statistics for technology, *Christopher Chatfield* - Anton's Calculus: early transcendentals, *Howard Anton* - Discrete Math - Discrete Mathematics and Its Application, *Kenneth H. Rosen* - Object Oriented Programming - Beginning Java Programming, *Bart Baesens* - Theory of Computation - Logic, *Wilfrid Hodges* - Algorithms, *Robert Sedgewick* - Algorithms in C++, *Robert Sedgewick* - Discrete mathematics for computer scientist, *Truss, J.K.* - Algorithm - Data Structure and Algorithms, *Alfred V. Aho*
import { SINGLE_ARTIST_PAGE } from "@/pathes"; import { IArtist } from "@/redux/Artists/ArtistsSlice"; import React from "react"; import { useMediaPredicate } from "react-media-hook"; import { Link } from "react-router-dom"; const ArtistAvatar: React.FC<IArtist> = ({ followers, id, imageUrl, name }) => { const isMobile = useMediaPredicate("(max-width: 1024px)"); return ( <Link to={`/${SINGLE_ARTIST_PAGE}/${id}`} className="flex flex-col items-center justify-between gap-2 text-sm text-gray-800 dark:text-white lg:text-base" > <img className="h-full w-full rounded-full hover:opacity-70" src={imageUrl} alt="" /> {isMobile ? ( <p className="text-sm"> {name.length <= 10 ? name : name.slice(0, 9) + "... "} </p> ) : ( <p className="text-base"> {name.length <= 15 ? name : name.slice(0, 14) + "... "} </p> )} <p className="text-xs dark:opacity-60">{followers}k followers</p> </Link> ); }; export default ArtistAvatar;
import React from 'react'; import ReactDOM from 'react-dom/client'; // import 'bootstrap/dist/css/bootstrap.min.css' import { createBrowserRouter, createRoutesFromElements, Route, RouterProvider, } from 'react-router-dom' import './assets/styles/bootstrap.custom.css' import './assets/styles/index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import HomeScreen from './screens/HomeScreen'; import ProductScreen from './screens/ProductScreen'; const router = createBrowserRouter( createRoutesFromElements( <Route path="/" element={<App />}> <Route index={true} path="/" element={<HomeScreen/>} /> <Route path="/product/:id" element={<ProductScreen/>} /> </Route> ) ) const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <RouterProvider router={router}/> </React.StrictMode> ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
<?php /** * TastyIgniter * * An open source online ordering, reservation and management system for restaurants. * * @package TastyIgniter * @author SamPoyigi * @copyright TastyIgniter * @link http://tastyigniter.com * @license http://opensource.org/licenses/GPL-3.0 The GNU GENERAL PUBLIC LICENSE * @since File available since Release 1.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); /** * Extension Class * * @category Libraries * @package TastyIgniter\Libraries\Extension.php * @link http://docs.tastyigniter.com */ class Extension { private $extensions = array(); public function __construct() { $this->CI =& get_instance(); } public function getInstalledExtensions($type = NULL) { $this->CI->load->model('Extensions_model'); return $this->CI->Extensions_model->getInstalledExtensions($type); } public function getExtensions($type = NULL) { ! empty($this->extensions) OR $this->extensions = $this->getInstalledExtensions(); if ( ! empty($type)) { $results = array(); foreach ($this->extensions as $name => $extenion) { if ($extenion['type'] === $type) { $results[$name] = $extenion; } } return $results; } return $this->extensions; } public function getModules() { return $this->getInstalledExtensions('module'); } public function getModule($name) { $modules = $this->getModules(); if ( ! empty($modules[$name]) AND is_array($modules[$name])) { return $modules[$name]; } } public function getPayments() { return $this->getInstalledExtensions('payment'); } public function getPayment($name) { $payments = $this->getPayments(); if ( ! empty($payments[$name]) AND is_array($payments[$name])) { return $payments[$name]; } } public function getAvailablePayments($load_payment = TRUE) { $payments = array(); $this->CI->load->library('location'); foreach ($this->getPayments() as $payment) { if ( ! empty($payment['ext_data'])) { if ($payment['ext_data']['status'] === '1') { $payments[$payment['name']] = array( 'name' => $payment['title'], 'code' => $payment['name'], 'priority' => $payment['ext_data']['priority'], 'status' => $payment['ext_data']['status'], 'data' => ($load_payment) ? Modules::run($payment['name'] . '/' . $payment['name'] . '/index') : array(), ); } } } if ( ! empty($payments)) { $sort_order = array(); foreach ($payments as $key => $value) { $sort_order[$key] = $value['priority']; } array_multisort($sort_order, SORT_ASC, $payments); } return $payments; } public function loadConfig($module, $fail_gracefully = FALSE, $non_persistent = FALSE) { if ( ! is_string($module)) return FALSE; // and retrieve the configuration items if ($non_persistent === TRUE) { $path = ROOTPATH . EXTPATH . "{$module}/config/"; $config = is_file($path . "{$module}.php") ? Modules::load_file($module, $path, 'config') : NULL; } else { $this->CI->config->load($module . '/' . $module, TRUE); $config = $this->CI->config->item($module); } if ($error = $this->checkConfig($module, $config)) { return ($fail_gracefully === FALSE) ? $error : show_error($error); } return $config; } public function getConfig($module = '', $item = '') { if ( ! is_string($module)) return NULL; $config = $this->CI->config->item($module); if ($item == '') { return isset($config) ? $config : NULL; } return isset($config, $config[$item]) ? $config[$item] : NULL; } public function getMeta($module = '', $config = array()) { ! empty($config) OR $config = $this->getConfig($module); if (isset($config['extension_meta']) AND is_array($config['extension_meta'])) { return $config['extension_meta']; } else { $metadata['type'] = (isset($config['ext_type'])) ? $config['ext_type'] : ''; $metadata['settings'] = (isset($config['admin_options'])) ? $config['admin_options'] : ''; return $metadata; } } private function checkConfig($module, $config = array()) { if ( $config === NULL) { return sprintf($this->CI->lang->line('error_config_not_found'), $module); } // Check if the module configuration items are correctly set $mtypes = array('module', 'payment', 'widget'); $metadata = (isset($config['extension_meta'])) ? $config['extension_meta'] : array(); if ( ! is_array($config) OR ! is_array($metadata)) { return sprintf($this->CI->lang->line('error_config_invalid'), $module); } if ( ! isset($config['ext_name']) AND ! isset($metadata['name'])) { return sprintf($this->CI->lang->line('error_config_invalid_key'), 'name', $module); } if ( (isset($config['ext_name']) AND $module !== $config['ext_name']) OR (isset($metadata['name']) AND $module !== $metadata['name'])) { return sprintf($this->CI->lang->line('error_config_invalid_key'), 'name', $module); } if ( ! isset($config['ext_type']) OR ! in_array($config['ext_type'], $mtypes)) { if ( ! isset($metadata['type']) OR ! in_array($metadata['type'], $mtypes)) { return sprintf($this->CI->lang->line('error_config_invalid_key'), 'type', $module); } } if (class_exists('Admin_' . $module, FALSE)) { $this->CI->load->library('user'); if ( ! isset($metadata['settings']) OR ! is_bool($metadata['settings']) OR ! class_exists('Admin_Controller', FALSE)) { return sprintf($this->CI->lang->line('error_config_invalid_key'), 'admin_options', $module); } } return FALSE; } /** * Migrate to the latest version or drop all migrations * for a given module migration * * @param $module * @param bool $downgrade * * @return bool */ public function runMigration($module, $downgrade = FALSE) { $path = Modules::path($module, 'config/'); if ( ! is_file($path . 'migration.php')) { return FALSE; } $migration = Modules::load_file('migration', $path, 'config'); $migration['migration_enabled'] = TRUE; $this->CI->load->library('migration', $migration); if ($downgrade === TRUE) { $this->CI->migration->version('0', $module); } else { $this->CI->migration->current($module); } } } // END Extension Class /* End of file Extension.php */ /* Location: ./system/tastyigniter/libraries/Extension.php */
import React,{useEffect, useRef, useState} from 'react' import { AiFillEdit, AiFillDelete } from "react-icons/ai"; import { MdDone } from "react-icons/md"; import { Todo } from '../model'; type Props={ todo:Todo; todos:Todo[]; setTodos:React.Dispatch<React.SetStateAction<Todo[]>>; } const SingleTodo:React.FC<Props> = ({todo,todos,setTodos}) => { const inputRef=useRef<HTMLInputElement>(null); const [edit,setEdit]=useState<boolean>(false); const [editTodo,setEditTodo]=useState<string>(todo.todo); const handleDone=(id:number)=>{ setTodos(todos.map((todo)=>( todo.id===id?{...todo,isDone:!todo.isDone}:todo ))); }; const handleDelete=(id:number)=>{ setTodos(todos.filter(todo => todo.id !== id)); } const handleEdit=(e:React.FormEvent,id:number)=>{ e.preventDefault(); setTodos(todos.map((todo)=>( todo.id===id?{...todo,todo:editTodo}:todo ))) setEdit(false); // setEditTodo(todo.todo); } useEffect(()=>{ inputRef.current?.focus(); },[edit]) return ( <form className='todos__single' onSubmit={(e)=>handleEdit(e,todo.id)}> { edit ?( <input type="text" value={editTodo} ref={inputRef} onChange={ (e)=>setEditTodo(e.target.value) } className='todos__single--text' /> ):( todo.isDone ? ( <s className='todos__single--text'>{todo.todo}</s> ):( <span className='todos__single--text'>{todo.todo}</span> ) ) } <div> <span className='icon' onClick={()=>{ if(!edit && !todo.isDone){ setEdit(!edit); } }}> <AiFillEdit /> </span> <span className='icon' onClick={()=>handleDelete(todo.id)} > <AiFillDelete /> </span> <span className='icon' onClick={()=>handleDone(todo.id)}> <MdDone /> </span> </div> </form> ) } export default SingleTodo
// // TaskEditView.swift // TodoListAppTutorial // // Created by Callum Hill on 31/7/2022. // import SwiftUI struct TaskEditView: View { @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> @Environment(\.managedObjectContext) private var viewContext @EnvironmentObject var dateHolder: DateHolder @State var selectedTaskItem: TaskItem? @State var name: String @State var desc: String @State var dueDate: Date @State var scheduleTime: Bool init(passedTaskItem: TaskItem?, initialDate: Date) { if let taskItem = passedTaskItem { _selectedTaskItem = State(initialValue: taskItem) _name = State(initialValue: taskItem.name ?? "") _desc = State(initialValue: taskItem.desc ?? "") _dueDate = State(initialValue: taskItem.dueDate ?? initialDate) _scheduleTime = State(initialValue: taskItem.scheduleTime) } else { _name = State(initialValue: "") _desc = State(initialValue: "") _dueDate = State(initialValue: initialDate) _scheduleTime = State(initialValue: false) } } var body: some View { Form { Section(header: Text("Task")) { TextField("Task Name", text: $name) TextField("Desc", text: $desc) } Section(header: Text("Due Date")) { Toggle("Schedule Time", isOn: $scheduleTime) DatePicker("Due Date", selection: $dueDate, displayedComponents: displayComps()) } if selectedTaskItem?.isCompleted() ?? false { Section(header: Text("Completed")) { Text(selectedTaskItem?.completedDate?.formatted(date: .abbreviated, time: .shortened) ?? "") .foregroundColor(.green) } } Section() { Button("Save", action: saveAction) .font(.headline) .frame(maxWidth: .infinity, alignment: .center) } } } func displayComps() -> DatePickerComponents { return scheduleTime ? [.hourAndMinute, .date] : [.date] } func saveAction() { withAnimation { if selectedTaskItem == nil { selectedTaskItem = TaskItem(context: viewContext) } selectedTaskItem?.created = Date() selectedTaskItem?.name = name selectedTaskItem?.dueDate = dueDate selectedTaskItem?.scheduleTime = scheduleTime dateHolder.saveContext(viewContext) self.presentationMode.wrappedValue.dismiss() } } } struct TaskEditView_Previews: PreviewProvider { static var previews: some View { TaskEditView(passedTaskItem: TaskItem(), initialDate: Date()) } }
package it.contrader.authenticationservice.security; import io.jsonwebtoken.*; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseCookie; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.util.WebUtils; import java.security.Key; import java.util.Date; import java.util.List; import java.util.stream.Collectors; @Component public class JwtUtils { private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class); @Value("${contrader.app.jwtSecret}") private String jwtSecret; @Value("${contrader.app.jwtExpirationMs}") private int jwtExpirationMs; @Value("${contrader.app.jwtCookieName}") private String jwtCookie; public String getJwtFromHeader(HttpServletRequest request) { String bearerToken = request.getHeader("Authorization"); if (bearerToken != null && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7); } return null; } public String generateJwt(UserDetailsImpl userPrincipal) { List<String> authorities = userPrincipal.getAuthorities() .stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.toList()); return generateTokenFromUsername(userPrincipal.getUsername(), authorities); } public void setRequestJwt(String jwt) { ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if(requestAttributes != null) { requestAttributes.getRequest().getSession().setAttribute("Authorization", "Bearer " + jwt); } } public String getUserNameFromJwtToken(String token) { return Jwts.parserBuilder().setSigningKey(key()).build() .parseClaimsJws(token).getBody().getSubject(); } private Key key() { return Keys.hmacShaKeyFor(Decoders.BASE64.decode(jwtSecret)); } public boolean validateJwtToken(String authToken) { try { Jwts.parserBuilder().setSigningKey(key()).build().parse(authToken); return true; } catch (MalformedJwtException e) { logger.error("Invalid JWT token: {}", e.getMessage()); } catch (ExpiredJwtException e) { logger.error("JWT token is expired: {}", e.getMessage()); } catch (UnsupportedJwtException e) { logger.error("JWT token is unsupported: {}", e.getMessage()); } catch (IllegalArgumentException e) { logger.error("JWT claims string is empty: {}", e.getMessage()); } return false; } public String generateTokenFromUsername(String username, List<String> authorities) { String roles = String.join(",", authorities); return Jwts.builder() .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs)) .claim("roles", roles) .signWith(key(), SignatureAlgorithm.HS256) .compact(); } }
from logging import getLogger from uuid import UUID from sqlalchemy.ext.asyncio import AsyncSession from chatbot.db import get_db from chatbot.service.session import message as message_service from chatbot.service.tool.base_event_handler import BaseEventHandler from chatbot.task import enqueue from .task import run_question_answering logger = getLogger(__name__) class EventHandler(BaseEventHandler): """Event handler""" async def on_session_created(self, user_id: UUID, session_id: UUID, message: str): """Called when a new session is created""" logger.debug( "on_session_created, user_id=%s, session_id=%s, message=%s", user_id, session_id, message, ) db: AsyncSession = await anext(get_db()) await message_service.create(db, user_id, session_id, message) await enqueue( run_question_answering, user_id=str(user_id), session_id=str(session_id) ) async def on_session_finished(self, user_id: UUID, session_id: UUID): """Called when a session is finished""" logger.debug( "on_session_finished, user_id=%s, session_id=%s", user_id, session_id )
import logging import re import httpx from fastapi import Depends, HTTPException, status from fastapi.security import OpenIdConnect from jose import jwt from src.core.config import Configuration from src.v1.models import auth_model LOGGER = logging.getLogger(__name__) LOGGER.debug(f"Configuration.OIDC_CLIENT_ID: {Configuration.OIDC_CLIENT_ID}") LOGGER.debug(f"Configuration.OIDC_CLIENT_ID: {Configuration.OIDC_WELLKNOWN}") oidc = OpenIdConnect( openIdConnectUrl=Configuration.OIDC_WELLKNOWN, scheme_name=Configuration.OIDC_CLIENT_ID, ) async def get_current_user(bearerToken: str = Depends(oidc)) -> auth_model.User: """ Consumes the access token if it exists, validates it and extracts the user information from it, returning that. :param bearerToken: The bearer token from the header :type bearerToken: str, optional :raises InvalidAuthorization: _description_ :return: The user information that was extracted from the bearer token :rtype: auth_model.User """ authorize(bearerToken) # make sure the authorization information is correctg try: # extract the token, ie remove Bearer string token = bearerToken.replace("Bearer ", "") # # getting the jwks_uri well_knowns = httpx.get(url=Configuration.OIDC_WELLKNOWN) well_knowns_data = well_knowns.json() jwks_url = well_knowns_data["jwks_uri"] LOGGER.debug(f"jwks_url: {jwks_url}") # # get the public key jwks_resp = httpx.get(url=jwks_url) jwks_key = jwks_resp.json() algorithm = jwt.get_unverified_header(token).get("alg") LOGGER.debug(f"algorithm: {algorithm}") decode_options = {"verify_signature": True} LOGGER.debug(f"client id: {Configuration.OIDC_CLIENT_ID}") payload = jwt.decode( token, jwks_key, audience=Configuration.OIDC_CLIENT_ID, algorithms=[algorithm], options=decode_options, ) LOGGER.debug(f"payload: {payload}") except jwt.JWTError as e: raise InvalidAuthorization(detail=f"Could not validate credentials: {e}") except Exception as e: LOGGER.error(f"Error: {e}") raise print(f"token is: {token}") LOGGER.debug(f"oidc: {oidc} {oidc.__call__}") return payload async def authorize(user_payload: auth_model.User = Depends(get_current_user)) -> bool: """ having successfully authenticated and retrieved a valid access token, this method will ensure that required roles are defined in the access token. :param user_payload: the user information extracted from the bearer token :type user_payload: auth_model.User, optional :raises HTTPException: _description_ :raises InvalidAuthorization: _description_ """ is_authorized = False roles = re.split("\s+", Configuration.OIDC_REQUIRED_ROLES) roles_set = set(roles) LOGGER.debug(f"required roles: {roles_set}") LOGGER.debug(f"user_payload: {user_payload}") try: if user_payload is None: # Not authenticated with oauth2_scheme, maybe with other scheme? # Raise here, or check for other options, or allow a simpler version for the anonymous users raise HTTPException(status_code=403, detail="Not authenticated") LOGGER.debug(f"user_payload: {user_payload['client_roles']}") # user_roles = re.split("\s+", user_payload["client_roles"]) user_roles_set = set(user_payload["client_roles"]) LOGGER.debug(f"granted roles: {user_roles_set}") intersected = list(roles_set.intersection(user_roles_set)) if intersected: is_authorized = True if not is_authorized: raise InvalidAuthorization( detail=f"User does not have the required roles: {roles}" ) except jwt.JWTError as e: raise InvalidAuthorization(detail=f"Could not validate credentials: {e}") except Exception as e: LOGGER.error(f"Error: {e}") raise return is_authorized class InvalidAuthorization(HTTPException): """ Exception raised when the header doesn't have the correct authorization config ie... not authorized """ def __init__(self, detail: str) -> None: super().__init__( status_code=status.HTTP_401_UNAUTHORIZED, detail=detail, headers={"WWW-Authenticate": "Bearer"}, )
<!doctypehtml><meta charset=utf-8><script crossorigin=anonymous src=https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.js></script><script crossorigin=anonymous src=https://cdn.jsdelivr.net/npm/@mediapipe/control_utils/control_utils.js></script><script crossorigin=anonymous src=https://cdn.jsdelivr.net/npm/@mediapipe/drawing_utils/drawing_utils.js></script><script crossorigin=anonymous src=https://cdn.jsdelivr.net/npm/@mediapipe/hands/hands.js></script><link href=style.min.css rel=stylesheet><script type=module>const videoElement = document.getElementsByClassName('input_video')[0]; const canvasElement = document.getElementsByClassName('output_canvas')[0]; const canvasCtx = canvasElement.getContext('2d'); function onResults(results) { canvasCtx.save(); canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height); canvasCtx.drawImage( results.image, 0, 0, canvasElement.width, canvasElement.height); if (results.multiHandLandmarks) { for (const landmarks of results.multiHandLandmarks) { drawConnectors(canvasCtx, landmarks, HAND_CONNECTIONS, { color: '#f82ecf', lineWidth: 2 }); drawLandmarks(canvasCtx, landmarks, { color: '#09f6fe', lineWidth:1 }); } } canvasCtx.restore(); } const hands = new Hands({ locateFile: (file) => { return `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`; } }); hands.setOptions({ maxNumHands: 2, modelComplexity: 1, minDetectionConfidence: 0.5, minTrackingConfidence: 0.5 }); hands.onResults(onResults); const camera = new Camera(videoElement, { onFrame: async () => { await hands.send({ image: videoElement }); }, }); camera.start();</script><div class=container><h2 class=animado>Imagen Original</h2><video class=input_video></video><div class=canvas><h2 class=animado>Deteccion de Manos</h2><canvas class=output_canvas></canvas></div></div>
Contributing to Chart.js Contributions to Chart.js are welcome and encouraged, but please have a look through the guidelines in this document before raising an issue, or writing code for the project. Using issues ------------ The [issue tracker](https://github.com/chartjs/Chart.js/issues) is the preferred channel for reporting bugs, requesting new features and submitting pull requests. If you're suggesting a new chart type, please take a look at [writing new chart types](https://github.com/chartjs/Chart.js/blob/master/docs/07-Advanced.md#writing-new-chart-types) in the documentation or consider [creating a plugin](https://github.com/chartjs/Chart.js/blob/master/docs/07-Advanced.md#creating-plugins). To keep the library lightweight for everyone, it's unlikely we'll add many more chart types to the core of Chart.js, but issues are a good medium to design and spec out how new chart types could work and look. Please do not use issues for support requests. For help using Chart.js, please take a look at the [`chartjs`](http://stackoverflow.com/questions/tagged/chartjs) tag on Stack Overflow. Reporting bugs -------------- Well structured, detailed bug reports are hugely valuable for the project. Guidlines for reporting bugs: - Check the issue search to see if it has already been reported - Isolate the problem to a simple test case - Provide a demonstration of the problem on [JS Bin](http://jsbin.com) or similar Please provide any additional details associated with the bug, if it's browser or screen density specific, or only happens with a certain configuration or data. Local development ----------------- Run `npm install` to install all the libraries, then run `gulp dev --test` to build and run tests as you make changes. Pull requests ------------- Clear, concise pull requests are excellent at continuing the project's community driven growth. But please review [these guidelines](https://github.com/blog/1943-how-to-write-the-perfect-pull-request) and the guidelines below before starting work on the project. Be advised that **Chart.js 1.0.2 is in feature-complete status**. Pull requests adding new features to the 1.x branch will be disregarded. Guidelines: - Please create an issue first: - For bugs, we can discuss the fixing approach - For enhancements, we can discuss if it is within the project scope and avoid duplicate effort - Please make changes to the files in [`/src`](https://github.com/chartjs/Chart.js/tree/master/src), not `Chart.js` or `Chart.min.js` in the repo root directory, this avoids merge conflicts - Tabs for indentation, not spaces please - If adding new functionality, please also update the relevant `.md` file in [`/docs`](https://github.com/chartjs/Chart.js/tree/master/docs) - Please make your commits in logical sections with clear commit messages Joining the project ------------- - Active committers and contributors are invited to introduce yourself and request commit access to this project. Please send an email to hello@nickdownie.com or file an issue. - We have a very active Slack community that you can join at https://chartjs-slack-automation.herokuapp.com. If you think you can help, we'd love to have you! License ------- By contributing your code, you agree to license your contribution under the [MIT license](https://github.com/chartjs/Chart.js/blob/master/LICENSE.md).
# StructuredLight.jl This package provides tools to simulate the propagation of paraxial light beams. This includes the calculation of Laguerre-Gauss and Hermite-Gauss beam profiles, the action of lenses, the propagation in free space as well as in Kerr media. We also provide methods that help the visualization of such beams. You can install this package by hitting `]` to enter the Pkg REPL-mode and then typing ``` add StructuredLight ``` ## Documentation - [**STABLE**](https://marcsgil.github.io/StructuredLight.jl/dev/) ## Example The following code is a minimal working example for this package: ```julia using StructuredLight #Loads the package rs = LinRange(-5,5,256) #Define a linear grid of points E0 = lg(rs,rs) #Calculates the fundamental Laguerre-Gaussian mode visualize(E0) #visualizes the mode E = free_propagation(E0,rs,rs,1) #Propagates the mode through a distance of z=1 visualize(E) #visualizes the evolved mode ``` This illustrates the basic idea of the package: first, you construct a matrix representing the mode you want to propagate, and then one calls `free_propagation`. ## CUDA support The propagation can be done on Nvidia GPUs. One only needs to pass the initial profile as a `CuArray`. ```julia using CUDA E0 = lg(rs,rs) |> cu #Transfers array to gpu E = free_propagation(E0,rs,rs,zs) ``` ## Perspectives Currently, I'm studying the propagation of light in media with second order non-linearity and through turbulence. Depending on my advances, I may include functionalities covering these topics.
import datetime import time import pandas as pd import pyarrow as pa from ds_core.handlers.abstract_handlers import ConnectorContract from ds_core.components.abstract_component import AbstractComponent from nn_rag.components.commons import Commons from nn_rag.managers.controller_property_manager import ControllerPropertyManager from nn_rag.intent.controller_intent import ControllerIntentModel from nn_rag.components.discovery import DataDiscovery # noinspection PyArgumentList class Controller(AbstractComponent): """Controller Class is a special capability that controls a pipeline flow. It still inherits core AbstractComponent but not child AbstractCommonComponent that the other capabilities inherit from. """ ASSET_BANK = 'https://raw.githubusercontent.com/project-hadron/hadron-asset-bank/master/contracts/pyarrow/' TOY_SAMPLE = 'https://raw.githubusercontent.com/project-hadron/hadron-asset-bank/master/datasets/toy_sample/' REPORT_USE_CASE = 'use_case' URI_PM_REPO = None def __init__(self, property_manager: ControllerPropertyManager, intent_model: ControllerIntentModel, default_save=None, reset_templates: bool=None, template_path: str=None, template_module: str=None, template_source_handler: str=None, template_persist_handler: str=None, align_connectors: bool=None): """ Encapsulation class for the components set of classes :param property_manager: The contract property manager instance for this component :param intent_model: the model codebase containing the parameterizable intent :param default_save: The default behaviour of persisting the contracts: if False: The connector contracts are kept in memory (useful for restricted file systems) :param reset_templates: (optional) reset connector templates from environ variables (see `report_environ()`) :param template_path: (optional) a template path to use if the environment variable does not exist :param template_module: (optional) a template module to use if the environment variable does not exist :param template_source_handler: (optional) a template source handler to use if no environment variable :param template_persist_handler: (optional) a template persist handler to use if no environment variable :param align_connectors: (optional) resets aligned connectors to the template """ super().__init__(property_manager=property_manager, intent_model=intent_model, default_save=default_save, reset_templates=reset_templates, template_path=template_path, template_module=template_module, template_source_handler=template_source_handler, template_persist_handler=template_persist_handler, align_connectors=align_connectors) @classmethod def from_uri(cls, task_name: str, uri_pm_path: str, creator: str, uri_pm_repo: str=None, pm_file_type: str=None, pm_module: str=None, pm_handler: str=None, pm_kwargs: dict=None, default_save=None, reset_templates: bool=None, template_path: str=None, template_module: str=None, template_source_handler: str=None, template_persist_handler: str=None, align_connectors: bool=None, default_save_intent: bool=None, default_intent_level: bool=None, order_next_available: bool=None, default_replace_intent: bool=None, has_contract: bool=None): """ Class Factory Method to instantiates the component's application. The Factory Method handles the instantiation of the Properties Manager, the Intent Model and the persistence of the uploaded properties. See class inline _docs for an example method :param task_name: The reference name that uniquely identifies a task or subset of the property manager :param uri_pm_path: A URI that identifies the resource path for the property manager. :param creator: A user name for this task activity. :param uri_pm_repo: (optional) A repository URI to initially load the property manager but not save to. :param pm_file_type: (optional) defines a specific file type for the property manager :param pm_module: (optional) the module or package name where the handler can be found :param pm_handler: (optional) the handler for retrieving the resource :param pm_kwargs: (optional) a dictionary of kwargs to pass to the property manager :param default_save: (optional) if the configuration should be persisted. default to 'True' :param reset_templates: (optional) reset connector templates from environ variables. Default True (see `report_environ()`) :param template_path: (optional) a template path to use if the environment variable does not exist :param template_module: (optional) a template module to use if the environment variable does not exist :param template_source_handler: (optional) a template source handler to use if no environment variable :param template_persist_handler: (optional) a template persist handler to use if no environment variable :param align_connectors: (optional) resets aligned connectors to the template. default Default True :param default_save_intent: (optional) The default action for saving intent in the property manager :param default_intent_level: (optional) the default level intent should be saved at :param order_next_available: (optional) if the default behaviour for the order should be next available order :param default_replace_intent: (optional) the default replace existing intent behaviour :param has_contract: (optional) indicates the instance should have a property manager domain contract :return: the initialised class instance """ # save the controllers uri_pm_repo path if isinstance(uri_pm_repo, str): cls.URI_PM_REPO = uri_pm_repo pm_file_type = pm_file_type if isinstance(pm_file_type, str) else 'json' pm_module = pm_module if isinstance(pm_module, str) else cls.DEFAULT_MODULE pm_handler = pm_handler if isinstance(pm_handler, str) else cls.DEFAULT_PERSIST_HANDLER _pm = ControllerPropertyManager(task_name=task_name, creator=creator) _intent_model = ControllerIntentModel(property_manager=_pm, default_save_intent=default_save_intent, default_intent_level=default_intent_level, order_next_available=order_next_available, default_replace_intent=default_replace_intent) super()._init_properties(property_manager=_pm, uri_pm_path=uri_pm_path, default_save=default_save, uri_pm_repo=uri_pm_repo, pm_file_type=pm_file_type, pm_module=pm_module, pm_handler=pm_handler, pm_kwargs=pm_kwargs, has_contract=has_contract) return cls(property_manager=_pm, intent_model=_intent_model, default_save=default_save, reset_templates=reset_templates, template_path=template_path, template_module=template_module, template_source_handler=template_source_handler, template_persist_handler=template_persist_handler, align_connectors=align_connectors) @classmethod def from_env(cls, task_name: str=None, default_save=None, reset_templates: bool=None, align_connectors: bool=None, default_save_intent: bool=None, default_intent_level: bool=None, order_next_available: bool=None, default_replace_intent: bool=None, uri_pm_repo: str=None, has_contract: bool=None, **kwargs): """ Class Factory Method that builds the connector handlers taking the property contract path from the os.environ['HADRON_PM_PATH'] or, if not found, uses the system default, for Linux and IOS '/tmp/components/contracts for Windows 'os.environ['AppData']\\components\\contracts' The following environment variables can be set: 'HADRON_PM_PATH': the property contract path, if not found, uses the system default 'HADRON_PM_REPO': the property contract should be initially loaded from a read only repo site such as github 'HADRON_PM_TYPE': a file type for the property manager. If not found sets as 'json' 'HADRON_PM_MODULE': a default module package, if not set uses component default 'HADRON_PM_HANDLER': a default handler. if not set uses component default This method calls to the Factory Method 'from_uri(...)' returning the initialised class instance :param task_name: (optional) The reference name that uniquely identifies the ledger. Defaults to 'primary' :param default_save: (optional) if the configuration should be persisted :param reset_templates: (optional) reset connector templates from environ variables. Default True (see `report_environ()`) :param align_connectors: (optional) resets aligned connectors to the template. default Default True :param default_save_intent: (optional) The default action for saving intent in the property manager :param default_intent_level: (optional) the default level intent should be saved at :param order_next_available: (optional) if the default behaviour for the order should be next available order :param default_replace_intent: (optional) the default replace existing intent behaviour :param uri_pm_repo: The read only repo link that points to the raw data path to the contracts repo directory :param has_contract: (optional) indicates the instance should have a property manager domain contract :param kwargs: to pass to the property ConnectorContract as its kwargs :return: the initialised class instance """ task_name = task_name if isinstance(task_name, str) else 'master' return super().from_env(task_name=task_name, default_save=default_save, reset_templates=reset_templates, align_connectors=align_connectors, default_save_intent=default_save_intent, default_intent_level=default_intent_level, order_next_available=order_next_available, default_replace_intent=default_replace_intent, uri_pm_repo=uri_pm_repo, has_contract=has_contract, **kwargs) @classmethod def scratch_pad(cls) -> ControllerIntentModel: """ A class method to use the Components intent methods as a scratch pad""" return super().scratch_pad() @property def tools(self) -> ControllerIntentModel: """The intent model instance""" return self._intent_model @property def register(self) -> ControllerIntentModel: """The intent model instance""" return self._intent_model @property def pm(self) -> ControllerPropertyManager: """The properties manager instance""" return self._component_pm def remove_all_tasks(self, save: bool=None): """removes all tasks""" for level in self.pm.get_intent(): self.pm.remove_intent(level=level) self.pm_persist(save) def set_use_case(self, title: str=None, domain: str=None, overview: str=None, scope: str=None, situation: str=None, opportunity: str=None, actions: str=None, project_name: str=None, project_lead: str=None, project_contact: str=None, stakeholder_domain: str=None, stakeholder_group: str=None, stakeholder_lead: str=None, stakeholder_contact: str=None, save: bool=None): """ sets the use_case values. Only sets those passed :param title: (optional) the title of the use_case :param domain: (optional) the domain it sits within :param overview: (optional) a overview of the use case :param scope: (optional) the scope of responsibility :param situation: (optional) The inferred 'Why', 'What' or 'How' and predicted 'therefore can we' :param opportunity: (optional) The opportunity of the situation :param actions: (optional) the actions to fulfil the opportunity :param project_name: (optional) the name of the project this use case is for :param project_lead: (optional) the person who is project lead :param project_contact: (optional) the contact information for the project lead :param stakeholder_domain: (optional) the domain of the stakeholders :param stakeholder_group: (optional) the stakeholder group name :param stakeholder_lead: (optional) the stakeholder lead :param stakeholder_contact: (optional) contact information for the stakeholder lead :param save: (optional) if True, save to file. Default is True """ self.pm.set_use_case(title=title, domain=domain, overview=overview, scope=scope, situation=situation, opportunity=opportunity, actions=actions, project_name=project_name, project_lead=project_lead, project_contact=project_contact, stakeholder_domain=stakeholder_domain, stakeholder_group=stakeholder_group, stakeholder_lead=stakeholder_lead, stakeholder_contact=stakeholder_contact) self.pm_persist(save=save) def load_source_canonical(self, reset_changed: bool=None, has_changed: bool=None, return_empty: bool=None, **kwargs) -> pa.Table: """returns the contracted source data as a DataFrame :param reset_changed: (optional) resets the has_changed boolean to True :param has_changed: (optional) tests if the underline canonical has changed since last load else error returned :param return_empty: (optional) if has_changed is set, returns an empty canonical if set to True :param kwargs: arguments to be passed to the handler on load """ return self.load_canonical(self.CONNECTOR_SOURCE, reset_changed=reset_changed, has_changed=has_changed, return_empty=return_empty, **kwargs) def load_canonical(self, connector_name: str, reset_changed: bool=None, has_changed: bool=None, return_empty: bool=None, **kwargs) -> pa.Table: """returns the canonical of the referenced connector :param connector_name: the name or label to identify and reference the connector :param reset_changed: (optional) resets the has_changed boolean to True :param has_changed: (optional) tests if the underline canonical has changed since last load else error returned :param return_empty: (optional) if has_changed is set, returns an empty canonical if set to True :param kwargs: arguments to be passed to the handler on load """ canonical = super().load_canonical(connector_name=connector_name, reset_changed=reset_changed, has_changed=has_changed, return_empty=return_empty, **kwargs) return canonical def load_persist_canonical(self, reset_changed: bool=None, has_changed: bool=None, return_empty: bool=None, **kwargs) -> pa.Table: """loads the clean pandas.DataFrame from the clean folder for this contract :param reset_changed: (optional) resets the has_changed boolean to True :param has_changed: (optional) tests if the underline canonical has changed since last load else error returned :param return_empty: (optional) if has_changed is set, returns an empty canonical if set to True :param kwargs: arguments to be passed to the handler on load """ return self.load_canonical(self.CONNECTOR_PERSIST, reset_changed=reset_changed, has_changed=has_changed, return_empty=return_empty, **kwargs) @staticmethod def quality_report(canonical: pa.Table, nulls_threshold: float = None, dom_threshold: float = None, cat_threshold: int = None, stylise: bool = None): """ Analyses a dataset, passed as a DataFrame and returns a quality summary :param canonical: The table to view. :param cat_threshold: (optional) The threshold for the max number of unique categories. Default is 60 :param dom_threshold: (optional) The threshold limit of a dominant value. Default 0.98 :param nulls_threshold: (optional) The threshold limit of a nulls value. Default 0.9 :param stylise: (optional) if the output is stylised """ stylise = stylise if isinstance(stylise, bool) else True return DataDiscovery.data_quality(canonical=canonical, nulls_threshold=nulls_threshold, dom_threshold=dom_threshold, cat_threshold=cat_threshold, stylise=stylise) @staticmethod def canonical_report(canonical: pa.Table, headers: [str, list] = None, regex: [str, list] = None, d_types: list = None, drop: bool = None, stylise: bool = None, display_width: int = None): """The Canonical Report is a data dictionary of the canonical providing a reference view of the dataset's attribute properties :param canonical: the table to view :param headers: (optional) specific headers to display :param regex: (optional) specify header regex to display. regex matching is done using the Google RE2 library. :param d_types: (optional) a list of pyarrow DataType e.g [pa.string(), pa.bool_()] :param drop: (optional) if the headers are to be dropped and the remaining to display :param stylise: (optional) if True present the report stylised. :param display_width: (optional) the width of the observational display """ stylise = stylise if isinstance(stylise, bool) else True tbl = Commons.filter_columns(canonical, headers=headers, regex=regex, d_types=d_types, drop=drop) return DataDiscovery.data_dictionary(canonical=tbl, stylise=stylise, display_width=display_width) @staticmethod def schema_report(canonical: pa.Table, headers: [str, list] = None, regex: [str, list] = None, d_types: list = None, drop: bool = None, stylise: bool = True, table_cast: bool = None): """ presents the current canonical schema :param canonical: the table to view :param headers: (optional) specific headers to display :param regex: (optional) specify header regex to display. regex matching is done using the Google RE2 library. :param d_types: (optional) a list of pyarrow DataType e.g [pa.string(), pa.bool_()] :param drop: (optional) if the headers are to be dropped and the remaining to display :param stylise: (optional) if True present the report stylised. :param table_cast: (optional) if the column should try to be cast to its type """ stylise = stylise if isinstance(stylise, bool) else True table_cast = table_cast if isinstance(table_cast, bool) else True tbl = Commons.filter_columns(canonical, headers=headers, regex=regex, d_types=d_types, drop=drop) return DataDiscovery.data_schema(canonical=tbl, table_cast=table_cast, stylise=stylise) @staticmethod def table_report(canonical: pa.Table, head: int=None): """ Creates a report from a pyarrow table in a tabular form :param canonical: the table to view :param head: The number of rows to show. """ return Commons.table_report(canonical, head=head) def reset_use_case(self, save: bool=None): """resets the use_case back to its default values""" self.pm.reset_use_case() self.pm_persist(save) def report_use_case(self, stylise: bool=None): """ a report on the use_case set as part of the domain contract""" stylise = stylise if isinstance(stylise, bool) else True report = self.pm.report_use_case() report = pd.DataFrame(report, index=['values']) if stylise: report = report.transpose().reset_index() report.columns = ['use_case', 'values'] return Commons.report(report, index_header='use_case') return pa.Table.from_pandas(report) def report_tasks(self, stylise: bool=True): """ generates a report for all the current component task""" report = pd.DataFrame.from_dict(data=self.pm.report_intent()) intent_replace = {'feature_select': 'FeatureSelect', 'feature_engineer': 'FeatureEngineer', 'feature_transform': 'FeatureTransform', 'feature_build': 'FeatureBuild', 'feature_predict': 'FeaturePredict'} report['component'] = report.intent.replace(to_replace=intent_replace) report = report.loc[:, ['level', 'order', 'component', 'parameters', 'creator']] if stylise: return Commons.report(report, index_header='level') return pa.Table.from_pandas(report) def report_run_book(self, stylise: bool=True): """ generates a report on all the intent actions""" report = pd.DataFrame(self.pm.report_run_book()) report = report.explode(column='run_book', ignore_index=True) report = report.join(pd.json_normalize(report['run_book'])).drop(columns=['run_book']).fillna('') if stylise: return Commons.report(report, index_header='name') return pa.Table.from_pandas(report) def add_run_book(self, run_levels: [str, list], book_name: str=None, save: bool=None): """ sets a named run book, the run levels are a list of levels and the order they are run in :param run_levels: the name or list of levels to be run :param book_name: (optional) the name of the run_book. defaults to 'primary_run_book' :param save: (optional) override of the default save action set at initialisation. """ book_name = book_name if isinstance(book_name, str) else self.pm.PRIMARY_RUN_BOOK for run_level in Commons.list_formatter(run_levels): self.add_run_book_level(run_level=run_level, book_name=book_name) return def add_run_book_level(self, run_level: str, book_name: str=None, source: str=None, persist: [str, list]=None, save: bool=None): """ adds a single runlevel to the end of a run_book. If the name already exists it will be replaced. When designing the runbook this gives easier implementation of the data handling specific for this runbook :param run_level: the run_level to add. :param book_name: (optional) the name of the run_book. defaults to 'primary_run_book' :param source: (optional) the intent level source :param persist: (optional) the intent level persist :param save: (optional) override of the default save action set at initialisation. """ book_name = book_name if isinstance(book_name, str) else self.pm.PRIMARY_RUN_BOOK run_level = Commons.param2dict(run_level=run_level, source=source, persist=persist) if self.pm.has_run_book(book_name=book_name): run_levels = self.pm.get_run_book(book_name=book_name) for i in range(len(run_levels)): if isinstance(run_levels[i], str) and run_levels[i] == run_level: run_levels[i].remove(run_level) elif isinstance(run_levels[i], dict) and run_levels[i].get('run_level') == run_level.get('run_level'): del run_levels[i] run_levels.append(run_level) else: run_levels = [run_level] self.pm.set_run_book(book_name=book_name, run_levels=run_levels) self.pm_persist(save) def report_intent(self, levels: [str, int, list]=None, stylise: bool = True): """ generates a report on all the intent :param levels: (optional) a filter on the levels. passing a single value will report a single parameterised view :param stylise: (optional) returns a stylised dataframe with formatting :return: pd.Dataframe """ if isinstance(levels, (int, str)): report = pd.DataFrame.from_dict(data=self.pm.report_intent_params(level=levels)) if stylise: return Commons.report(report, index_header='order') else: report = pd.DataFrame.from_dict(data=self.pm.report_intent(levels=levels)) if stylise: return Commons.report(report, index_header='level') return pa.Table.from_pandas(report) def report_notes(self, catalog: [str, list]=None, labels: [str, list]=None, regex: [str, list]=None, re_ignore_case: bool=False, stylise: bool=True, drop_dates: bool=False): """ generates a report on the notes :param catalog: (optional) the catalog to filter on :param labels: (optional) s label or list of labels to filter on :param regex: (optional) a regular expression on the notes :param re_ignore_case: (optional) if the regular expression should be case sensitive :param stylise: (optional) returns a stylised dataframe with formatting :param drop_dates: (optional) excludes the 'date' column from the report :return: pd.Dataframe """ stylise = True if not isinstance(stylise, bool) else stylise drop_dates = False if not isinstance(drop_dates, bool) else drop_dates report = self.pm.report_notes(catalog=catalog, labels=labels, regex=regex, re_ignore_case=re_ignore_case, drop_dates=drop_dates) report = pd.DataFrame.from_dict(data=report) if stylise: return Commons.report(report, index_header='section', large_font='label') return pa.Table.from_pandas(report) def run_controller(self, run_book: [str, list, dict]=None, repeat: int=None, sleep: int=None, run_time: int=None, source_check_uri: str=None, run_cycle_report: str=None): """ Runs the components pipeline based on the runbook instructions. The run_book is a pre-registered Controller run_book names to execute. If no run book is given, default values are substituted, finally taking the intent list if all else fails. The run_cycle_report automatically generates the connector contract with the name 'run_cycle_report'. To reload the report for observation use the controller method 'load_canonical(...) passing the name 'run_cycle_report'. :param run_book: (optional) a run_book reference, a list of task names (intent levels) :param repeat: (optional) the number of times this intent should be repeated. None or -1 -> never, 0 -> forever :param sleep: (optional) number of seconds to sleep before repeating :param run_time: (optional) number of seconds to run the controller using repeat and sleep cycles time is up :param source_check_uri: (optional) The source uri to check for change since last controller instance cycle :param run_cycle_report: (optional) a full name for the run cycle report """ if isinstance(run_cycle_report, str): self.add_connector_persist(connector_name='run_cycle_report', uri_file=run_cycle_report) df_report = pd.DataFrame(columns=['time', 'text']) if not self.pm.has_intent(): return # tidy run_book run_book = Commons.list_formatter(run_book) if not run_book: if self.pm.has_run_book(self.pm.PRIMARY_RUN_BOOK): run_book = self.pm.get_run_book(self.pm.PRIMARY_RUN_BOOK) elif self.pm.has_intent(self.pm.DEFAULT_INTENT_LEVEL): self.add_run_book_level(run_level=self.pm.DEFAULT_INTENT_LEVEL, book_name=self.pm.PRIMARY_RUN_BOOK) run_book = self.pm.get_run_book(self.pm.PRIMARY_RUN_BOOK) else: for level in self.pm.get_intent().keys(): self.add_run_book_level(run_level=level, book_name=self.pm.PRIMARY_RUN_BOOK) run_book = self.pm.get_run_book(self.pm.PRIMARY_RUN_BOOK) run_dict = [] for book in run_book: if isinstance(book, str): if self.pm.has_run_book(book): for item in self.pm.get_run_book(book): run_dict.append(item) else: run_dict.append({'run_level': f'{book}'}) else: run_dict.append(book) handler = None if isinstance(source_check_uri, str): self.add_connector_uri(connector_name='source_check_uri', uri=source_check_uri) handler = self.pm.get_connector_handler(connector_name='source_check_uri') run_time = run_time if isinstance(run_time, int) else 0 if run_time > 0 and not isinstance(sleep, int): sleep = 1 end_time = datetime.datetime.now() + datetime.timedelta(seconds=run_time) repeat = repeat if isinstance(repeat, int) and repeat > 0 else 1 run_count = 0 while True: # run_time always runs once if isinstance(run_cycle_report, str): df_report.loc[len(df_report.index)] = [datetime.datetime.now(), f'starting pipeline -{run_count}-'] for count in range(repeat): if isinstance(run_cycle_report, str): df_report.loc[len(df_report.index)] = [datetime.datetime.now(), f'starting cycle -{count}-'] if handler and handler.exists(): if handler.has_changed(): handler.reset_changed(False) else: if isinstance(run_cycle_report, str): df_report.loc[len(df_report.index)] = [datetime.datetime.now(), 'Source has not changed'] if isinstance(sleep, int) and count < repeat - 1: time.sleep(sleep) continue for book in run_dict: run_level = book.get('run_level') source = book.get('source', self.CONNECTOR_SOURCE) persist = book.get('persist', self.CONNECTOR_PERSIST) if isinstance(run_cycle_report, str): df_report.loc[len(df_report.index)] = [datetime.datetime.now(), f"running: '{run_level}'"] # run level shape = self.intent_model.run_intent_pipeline(run_level=run_level, source=source, persist=persist, controller_repo=self.URI_PM_REPO) if isinstance(run_cycle_report, str): df_report.loc[len(df_report.index)] = [datetime.datetime.now(), f'outcome shape: {shape}'] if isinstance(run_cycle_report, str): df_report.loc[len(df_report.index)] = [datetime.datetime.now(), 'cycle complete'] if isinstance(sleep, int) and count < repeat-1: if isinstance(run_cycle_report, str): df_report.loc[len(df_report.index)] = [datetime.datetime.now(), f'sleep for {sleep} seconds'] time.sleep(sleep) if isinstance(run_cycle_report, str): run_count += 1 if end_time < datetime.datetime.now(): break else: if isinstance(run_cycle_report, str): df_report.loc[len(df_report.index)] = [datetime.datetime.now(), f'sleep for {sleep} seconds'] time.sleep(sleep) if isinstance(run_cycle_report, str): df_report.loc[len(df_report.index)] = [datetime.datetime.now(), 'pipeline complete'] _ = pa.Table.from_pandas(df_report, preserve_index=False) self.save_canonical(connector_name='run_cycle_report', canonical=_) return @staticmethod def runbook_script(task: str, source: str=None, persist: str=None, drop: bool=None) -> dict: """ a utility method to help build feature conditions by aligning method parameters with dictionary format. This also sets default, in-memory and connector contracts specific for a task. if not specified, source or persist will use the default values. '${<connector>}' will use the environment variable is a connector contract of that name that must exist in the task connectors. :param task: the task name (intent level) name this runbook is applied too or a number if synthetic generation. :param source: (optional) a task name indicating where the source of this task will come from. :param persist: (optional) a task name indicating where the persist of this task will go to. :param drop: (optional) if true indicates in-memory canonical should be dropped once read. :return: dictionary of the parameters """ source = source if isinstance(source, str) else Controller.CONNECTOR_SOURCE source = ConnectorContract.parse_environ(source) if source.startswith('${') and source.endswith('}') else source persist = persist if isinstance(persist, str) else Controller.CONNECTOR_PERSIST persist = ConnectorContract.parse_environ(persist) if persist.startswith('${') and persist.endswith('}') else persist drop = drop if isinstance(drop, bool) else True return Commons.param2dict(**locals())
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import * as mongoose from 'mongoose'; import { ReportTypes } from 'src/common/constants'; import { TimestampBase } from './timestamp-base'; @Schema({ timestamps: true }) export class Report extends TimestampBase { @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' }) accuser; @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' }) accused; //transaction id @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Transaction' }) transaction; //comment id @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }) comment; //comment description @Prop() description: string; @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }) post; @Prop({ type: String, enum: ReportTypes, required: true, }) type; @Prop({ default: false }) isReviewed: boolean; } export const ReportSchema = SchemaFactory.createForClass(Report);
import React, { useEffect } from 'react'; import { Platform, StatusBar } from 'react-native'; //Third Party import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import { Provider as PaperProvider } from 'react-native-paper'; import Toast from 'react-native-toast-message'; //Screens import LoggedInTabNavigator from 'app/navigation/HomeTabNavigator'; //App Modules import { HomeTabNavigatorParams } from 'app/navigation/types'; import useToastConfig from 'app/hooks/useToastConfig'; import { PaperThemeDark, PaperThemeDefault } from 'app/config/app-theme-config'; import useThemeConfigStore from 'app/store/themeConfig'; import { navigationRef } from 'app/navigation/NavigationService'; const homeOptions: Object = { title: 'Home', headerTitleStyle: { fontWeight: 'bold', }, headerShown: false, }; const RootNavigation: React.FC = () => { const isDark = useThemeConfigStore(state => state.isDark); const primary = useThemeConfigStore(state => state.primary); const onPrimary = useThemeConfigStore(state => state.onPrimary); const secondaryContainer = useThemeConfigStore(state => state.secondaryContainer); const onSecondary = useThemeConfigStore(state => state.onSecondary); const Stack = createNativeStackNavigator<HomeTabNavigatorParams>(); const toastConfig = useToastConfig(); const theme = isDark ? { ...PaperThemeDark, colors: { ...PaperThemeDark.colors, primary: primary, onPrimary: onPrimary, secondaryContainer: secondaryContainer, onSecondary: onSecondary, }, } : { ...PaperThemeDefault, colors: { ...PaperThemeDefault.colors, primary: primary, onPrimary: onPrimary, secondaryContainer: secondaryContainer, onSecondary: onSecondary, }, }; useEffect(() => { if (Platform.OS === 'ios') { return; } let to = setTimeout(() => { StatusBar.setBackgroundColor('#FFFFFF01'); }, 500); return () => clearTimeout(to); }, []); return ( <PaperProvider theme={theme}> <NavigationContainer ref={navigationRef} theme={theme}> <StatusBar backgroundColor={'#FFFFFF01'} barStyle={isDark ? 'light-content' : 'dark-content'} translucent={true} /> <Stack.Navigator> <Stack.Screen name="LoggedInTabNavigator" component={LoggedInTabNavigator} options={homeOptions} /> </Stack.Navigator> <Toast config={toastConfig} /> </NavigationContainer> </PaperProvider> ); }; export default RootNavigation;
<?php use function Withinboredom\Bytes\Kilobytes; it('can be serialized', function () { $kb = Kilobytes(12); $string = serialize($kb); expect($string)->toBe('O:29:"Withinboredom\Bytes\Kilobytes":1:{s:5:"bytes";i:12288;}'); }); it('can be deserialized', function () { $string = 'O:29:"Withinboredom\Bytes\Kilobytes":1:{s:5:"bytes";i:16384;}'; $kb = unserialize($string); expect($kb)->toBe(Kilobytes(16)); }); it('emits a warning when it should', function () { $expected = Kilobytes(16); $string = 'O:29:"Withinboredom\Bytes\Kilobytes":1:{s:5:"bytes";i:16384;}'; $kb = unserialize($string); $error = error_get_last(); expect($error['message'])->toBe( 'A value was unserialized that will not have the appropriate identity. If you are seeing this message, please use a custom serialization/deserialization logic if you rely on identity of DataUnit.' ) ->and($kb->getBinaryValue())->toBe($expected->getBinaryValue()) ->and($kb)->not()->toBe($expected) ->and($kb)->toEqual($expected); });
package main import "fmt" func max(num1,num2 int) int { if num1 > num2 { return num1 } else { return num2 } } func lcs(input1,input2 []int) []int { matrix := make([][]int,len(input1)+1) for i,_ := range matrix { matrix[i] = make([]int,len(input2)+1) } for i:=1 ; i<=len(input1) ; i+=1 { for j:=1 ; j<=len(input2) ; j+=1 { if input1[i-1] == input2[j-1] { matrix[i][j] = 1+matrix[i-1][j-1] } else { matrix[i][j] = max(matrix[i-1][j],matrix[i][j-1]) } } } length := matrix[len(input1)][len(input2)] output := make([]int,length,length) index := length for i,j := len(input1),len(input2) ; i > 0 && j >0 ; { if input1[i-1] == input2[j-1] { output[index-1] = input1[i-1] i-=1 j-=1 index-=1 } else if matrix[i-1][j] > matrix[i][j-1] { i-=1 } else { j-=1 } } return output } func main() { var len1,len2 int _,err:= fmt.Scanf("%d %d",&len1,&len2) if err == nil { var input1,input2 []int = make([]int,0,len1),make([]int,0,len2) for i:=0 ; i<len1 ; i+=1 { var num int _,err := fmt.Scanf("%d",&num) if err == nil { input1 = append(input1,num) } } for i:=0 ; i<len2 ; i+=1 { var num int _,err := fmt.Scanf("%d",&num) if err == nil { input2 = append(input2,num) } } for _,num := range lcs(input1,input2) { fmt.Printf("%d ",num) } } }
<div *ngIf="productsList.length else cover" class="d-flex flex-column align-items-center shoppingCartProduts"> <!-- Productos --> <mat-expansion-panel *ngFor="let product of productsList; index as i" [expanded]="i === 0" hideToggle class="shadowBorder col-12 my-2 p-2"> <!-- Fuera (fila) --> <mat-expansion-panel-header> <!-- Contenedor del titulo --> <mat-panel-title> <div class="d-flex gap-3 align-items-center"> <img class="rounded" style="max-width: 150px;" [src]="product.image[0]" alt="Imagen del producto"> <!-- Contenedor del titulo del plan --> <div class="d-flex flex-column"> <!-- Nombre del plan --> <p class="d-flex align-items-center mb-2 cmm-txt-primary fs-34 fw-bold"> {{product.productName}} </p> <!-- Nombre del template --> <p class="m-0 fs-20"> {{product.name}} </p> </div> </div> </mat-panel-title> <mat-panel-description class="justify-content-end m-0 pe-4" style="flex-grow: initial;"> <!-- Contenedor del monto y textos descriptivos del monto --> <div class="d-flex flex-column align-items-center" style="min-width: 150px;"> <!-- Monto --> <p class="fs-28 fw-bold m-0"> ${{ product.extraAmount ? (product.amount * +product.quantity) + product.extraAmount : (product.amount * +product.quantity) }} </p> <!-- Solo si es con contratacion --> <p *ngIf="product.extraAmount" class="fs-14 m-0">Contratacio</p> <p *ngIf="product.extraAmount" class="fs-14 m-0 text-center">+</p> <!-- Plan de mensualidad --> <p *ngIf="product.extraAmount" class="fs-14 m-0"> Plan de prueba </p> </div> </mat-panel-description> </mat-expansion-panel-header> <!-- Dentro --> <div class="h-100 d-flex flex-column justify-content-end" style="min-height: 250px;"> <!-- Descripcion --> <p class="fs-18 text-center mb-auto py-4"> {{product.description}} </p> <!-- Precio de contratacion --> <div *ngIf="product.extraAmount" class="w-100 d-flex flex-wrap justify-content-between align-items-center py-3 border-top"> <!-- titulo --> <p class="fs-20 fw-bold m-0">Precio de contratación:</p> <!-- Monto --> <p class="fs-20 fw-bold m-0">{{product.extraAmount}} USD</p> </div> <!-- Precio de mensualidades --> <div class="w-100 d-flex flex-wrap justify-content-between align-items-center py-3 border-top"> <!-- titulo --> <div class="d-flex flex-column"> <p class="fs-20 fw-bold m-0">Mensualidades a pagar:</p> <p *ngIf="product.extraAmount" class="text-center fs-12 m-0"> Al contratar tu primer servicio <br> <span class="fw-bold">obtienes tu primer mes gratis.</span> </p> </div> <!-- Botonera --> <div class="d-flex justify-content-around align-items-center border rounded p-2" style="width: 200px;"> <button class="border-0 cmm-bg-white d-flex align-items-center" (click)="minus(i)"> <mat-icon>remove</mat-icon> </button> <p class="fs-26 m-0"> {{+product.quantity}} </p> <button class="border-0 cmm-bg-white d-flex align-items-center" (click)="plus(i)"> <mat-icon>add</mat-icon> </button> </div> <!-- Monto --> <p class="fs-20 fw-bold m-0">{{product.amount * +product.quantity}} USD</p> </div> <!-- Precio de contratacion --> <div *ngIf="product.discount" class="w-100 d-flex flex-wrap justify-content-between align-items-center py-3 border-top"> <!-- titulo --> <p class="fs-20 fw-bold m-0">Descuento de un mes gratis:</p> <!-- Monto --> <p class="fs-20 fw-bold m-0">-{{product.discount}} USD</p> </div> <!-- Monto total --> <div class="w-100 d-flex flex-wrap justify-content-between align-items-center py-3 border-top"> <!-- titulo --> <p class="fs-20 fw-bold m-0">Costo del plan:</p> <!-- Monto --> <p class="fs-20 fw-bold m-0">{{productAmount(i)}} USD</p> </div> </div> </mat-expansion-panel> <cmm-cmp-b-button [button_text]="'Continuar'" (submit)="nextStep.emit(true)" class="d-flex mx-auto w-100 mt-4" style="max-width: 500px;"></cmm-cmp-b-button> </div> <!-- Contenedor principal del cover --> <ng-template #cover> <div class="cmm-bg-white shadowBorder rounded"> <!-- cover de la tabla --> <cmm-cmp-c-cover title="No tiene productos en su carrito" message="Puede ver entre nuestros productos disponibles si desea agregarlos a su carrito o puede refrescar la vista para actualizar su carrito"></cmm-cmp-c-cover> <div class="w-100 d-flex flex-wrap justify-content-around px-3 pb-3"> <cmm-cmp-b-button class="p-1 w-100" style="max-width: 300px;" button_text="Ver productos" buttonType="gradient" [routerLink]="['products/ecommerce']"></cmm-cmp-b-button> <cmm-cmp-b-button class="p-1 w-100" style="max-width: 300px;" button_text="Refrescar carrito" (submit)="nextStep.emit(false)"></cmm-cmp-b-button> </div> </div> </ng-template>
---------------------------------------------------------------------- CONJUNCTS (Drule) ---------------------------------------------------------------------- CONJUNCTS : (thm -> thm list) SYNOPSIS Recursively splits conjunctions into a list of conjuncts. KEYWORDS rule, conjunction. DESCRIBE Flattens out all conjuncts, regardless of grouping. Returns a singleton list if the input theorem is not a conjunction. A |- t1 /\ t2 /\ ... /\ tn ----------------------------------- CONJUNCTS A |- t1 A |- t2 ... A |- tn FAILURE Never fails. EXAMPLE Suppose the identifier {th} is bound to the theorem: A |- (x /\ y) /\ z /\ w Application of {CONJUNCTS} to {th} returns the following list of theorems: [A |- x, A |- y, A |- z, A |- w] : thm list SEEALSO Drule.BODY_CONJUNCTS, Drule.CONJ_LIST, Drule.LIST_CONJ, Thm.CONJ, Thm.CONJUNCT1, Thm.CONJUNCT2, Drule.CONJ_PAIR. ----------------------------------------------------------------------
--- title: How you should allow elevated users enter and exit the service portal description: Out-of-the-box ServiceNow isn't great for allowing elevated users to jump in and out the service portal, but it's easily fixed with some small changes. date: 2020-12-26 tags: - ServiceNow - Solution - Opinion eleventyExcludeFromCollections: false --- The self-service Service Portal is a powerful feature of ServiceNow. It provides end users and non-fulfiller users with a clean, user friendly, and straight-forward experience which allows them to easily find what they need to, without overwhelming them with the myriad of navigation options available in the Platform UI (a.k.a. the backend, the ITIL view, the normal view). ![Platform UI vs Service Portal](./platform-ui-sp.jpg) Here's a screenshot of how the service portal looks as it comes out-of-the-box. ![Baseline service portal screenshot](./ootb-sp-screenshot.jpg) ## The problem An issue that I experience regularly is when fulfiller-users want to enter and exit the service portal and aren't sure how, or that power users find it frustrating to frequently enter and exit the service portal by playing with the URL. There's no buttons and no links (except for admins), and that's a problem. ![Try to platform](./try-to-platform.jpg) ![Try to sp](./try-to-sp.jpg) Out of the box, entering and exiting the service portal involves the user has manually updating the URL in the browser address bar, which also requires that the user knows the URL of the Service Portal they want to enter. ![Editing the URL](./editing-address-bar.png) How can this be made easier to improve the user experience? Here's what I often recommend. ## The solution The design of this solution is simple: * The user will be automatically redirected to the Service Portal if they don't have one of the roles we specify. * The user can enter the Service Portal from the Application Navigator: **Self-service > Service Portal**. * The user can exit the Service Portal using a button in the header that only appears if they have one of the roles we specify. ![Design](./design-diagram.svg) It's at this point that you'll want to decide the user roles that will decide if the user gets redirected to the service portal or not. As it comes out-of-the-box, the **SPEntryPage** script will not redirect any user that has any role of any kind. This works well for simple scenarios, but I find that this is too broad a brush when custom non-fulfiller roles start being used, such as roles to control access to homepages. Whatever works for you. ### Automatically redirecting to the Service Portal ServiceNow has already made this part easy. Use the script include "SPEntryPage", and modify it slightly so that users with the desired role(s) do not get redirected. This script is run when the user navigates to the base URL of the instance (if they're not trying to go anywhere). If they have a link to somewhere specific like a record, they won't be redirected, and will successfully land where they were trying to get to. I think this is a good thing. Redirecting to the service portal typically loses where the user was trying to get to, and users will quickly get frustrated when they don't end up where they wanted to go. This also looks bad if a user clicks on a link to something in an email sent out from ServiceNow and gets mistakenly redirected somewhere else instead. E.g. * instance.service-now.com/ = **redirected** * instance.service-now.com/incident.do? = **not redirected** * instance.service-now.com/navto.do?url=incident.do = **not redirected** > The company "Awesome Inc" only wants IT staff to be able to see the Platform UI. All other staff members should be redirected to the Service Portal. > HR and Facilities staff should also be redirected. > > If the user has the "itil" role, they will continue to use the Platform UI. Otherwise, they'll be redirected to the Service Portal. To accommodate this scenario, lets change this line in the **SPEntryPage** script from this: ```js if (user.hasRoles() && !redirectURL && !isServicePortalURL) ``` to this: ```js if (user.hasRole("itil") && !redirectURL && !isServicePortalURL) ``` That should be about it. Redirecting users using the **SPEntryPage** script has been extensively covered by a number of authors & documents, here are some links if you'd like to look into the topic further. * https://hi.service-now.com/kb_view.do?sysparm_article=KB0746730 * https://docs.servicenow.com/bundle/istanbul-servicenow-platform/page/build/service-portal/concept/c_SPSSOLoginAndRedirects.html * https://serviceportal.io/docs/documentation/sso_configuration.md ### Entering the Service Portal from the Platform UI With the out-of-the-box ServiceNow service portal configuration, the only ways to enter the service portal are: * To be redirected to it when you login. * To manually navigate to the service portal by changing the browser address by adding `/sp`. ![Editing the URL](./editing-address-bar.png) This is a user-experience problem for users that wouldn't normally be redirected. Examples include: * IT Support staff who want to access the portal to assist an end-user. * ServiceNow administrators who have to regularly switch in and out of the service portal. * Knowledge managers who want to check how their knowledge articles appear in the user-facing service portal. There is a very easy solution for this user-experience problem. Create a new module called **Service portal ➚** in the application navigator under **Self-service**. I like the little "➚" symbol that ServiceNow has been using because it denotes that the link will open in a new tab when you click on it. You shouldn't need to add any role against the module because it'll be visible to everyone, just set: * **Type** to **URL (from Arguments:)**. * **Arguments** to `/sp`. * **Window name** to `_blank` so it opens in a new tab. ![Link to service portal](./service-portal-self-service-link.png) ### Exiting the portal So you've followed a link into the service portal, but you're an ITIL user and want to get out. How do you do it? In the out-of-the-box service portal, there's no button or link that you can use to leave. This forces the you to manually change the address in your browser's address bar, chopping off the `/sp?` and everything after it. A change I recommend is to create an **Exit** menu item on the service portal's header menu. This will appear as a button at the top of the service portal to users with the same roles that don't get redirected, and clicking on it will redirect the user to the platform UI. To do so, open the Service Portal Menu that's set as the header menu for your service portal and create a new menu item with these details: * **Name** to `Exit portal`, `Advanced mode`, or `Fulfiller view`. Something to say "leave the service portal". * **Order** to `100` or so, to position it on the far-left. * **Glyph** to the up arrow. I like this because it denotes that you're going to leave the service portal. * **Type** to `URL`. * **URL** to just `/`. * and **Condition** to `gs.hasRole("itil")`. Note that this is the same condition used in the SPEntryPage redirection for consistency. ![Exit portal menu item](./exit-portal-screenshot.png) And that's it! Fulfiller and power users can now enter and exit the service portal as they like. I can't recommend this change enough. It can be frustrating for users that get into the portal and have to force their way out of it, more so for users that know that the service portal exists but can't find where it is. These links and buttons cuts down a handful of clicks and key presses down to a single click. This is an easy but worthwhile boost to user experience.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Number Theory</title> <link rel="stylesheet" href="styles.css"> <script type="text/javascript" id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"> </script> <script type="text/javascript" src="number_theory.js"></script> </head> <body> <div class="container"> <a href="index.html">Back to Study Guide</a> <h1>Number Theory</h1> <h2>Divisibility</h2> <p>Understanding how numbers divide is basic in number theory.</p> <p><strong>Examples:</strong></p> <ul> <li>GCD (Greatest Common Divisor)</li> <li>LCM (Least Common Multiple)</li> </ul> <h2>Prime Numbers</h2> <p>Primes are numbers greater than 1 that have only two divisors: 1 and the number itself.</p> <p><strong>Examples:</strong></p> <ul> <li>Sieve of Eratosthenes</li> <li>Fermat's Little Theorem</li> </ul> <h2>Modular Arithmetic</h2> <p>This involves doing arithmetic with remainders.</p> <p><strong>Examples:</strong></p> <ul> <li>Modulo Addition</li> <li>Modulo Multiplication</li> </ul> <a href="index.html">Back to Study Guide</a> </div> </body> </html>
import React, { useState } from "react"; import data from "../data/data"; // Import your JSON data const FilterEmployees = ({ onFilter }) => { const [searchTerm, setSearchTerm] = useState(""); const [isFiltering, setIsFiltering] = useState(false); const handleSearch = (e) => { const term = e.target.value; setSearchTerm(term); // Check if data is available in localStorage, oeelse use default data const jsonData = localStorage.getItem("organizationData"); const orgData = jsonData ? JSON.parse(jsonData) : data; if (term.trim() === "") { setIsFiltering(false); // Reset filter if search term is empty onFilter(null); // No filtering, pass null } else { setIsFiltering(true); // Perform filtering on all employees (CEO, Head of Department, Team Leaders, Team Members) const filtered = filterEmployees(orgData, term); onFilter(filtered); // Pass the filtered data to the parent component } }; const cancelFilter = () => { setIsFiltering(false); setSearchTerm(""); onFilter(null); // Cancel the filter, pass null }; return ( <div className="text-center mt-5"> <input type="text" value={searchTerm} onChange={handleSearch} placeholder="Search Employee" className="md:px-3 px-2 py-1 md:py-2 w-[70%] md:w-1/3 lg:w-1/5 bg-gray-100 border border-gray-300 rounded-l-full focus:outline-none focus:ring focus:border-blue-300" /> <button onClick={cancelFilter} className="md:px-3 px-2 py-1 md:py-2 bg-blue-500 border border-blue-500 rounded-r-full text-white transition-all duration-300 ease-in-out hover:bg-white hover:text-blue-500 focus:outline-none focus:ring focus:border-blue-500" > Cancel </button> </div> ); }; // Function to filter employees based on search term const filterEmployees = (orgData, term) => { const filteredEmployees = []; // Filter CEO's details if (matchesSearchTerm(orgData.CEO, term)) { filteredEmployees.push(orgData.CEO); } // Iterate through all departments for (const deptName in orgData.CEO.departments) { const department = orgData.CEO.departments[deptName]; // Check Head of Department if (matchesSearchTerm(department, term)) { filteredEmployees.push(department); } // Check Team Leaders and Team Members department.teams.forEach((team) => { // Check Team Leader if (matchesSearchTerm(team.teamLeader, term)) { filteredEmployees.push(team.teamLeader); } // Check Team Members team.teamLeader.teamMembers.forEach((member) => { if (matchesSearchTerm(member, term)) { filteredEmployees.push(member); } }); }); } // Remove duplicates by filtering unique IDs return filteredEmployees.filter( (emp, index, self) => index === self.findIndex((e) => e.id === emp.id) ); }; // Helper function to check if value matches the search term const matchesSearchTerm = (value, term) => Object.values(value).some((v) => v.toString().toLowerCase().includes(term.toLowerCase()) ); export default FilterEmployees;
import { NestFactory } from '@nestjs/core' import { AppModule } from './app.module' import { ConfigType } from '@nestjs/config' import { apiConfig } from '@/config' import { Logger, ValidationPipe } from '@nestjs/common' import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger' import { ProcessTimeInterceptor, ResponseWrapInterceptor } from '@/common/interceptor' import { OtherExceptionFilter, HttpExceptionFilter } from '@/common/filter' import { NestExpressApplication } from '@nestjs/platform-express' async function bootstrap() { const app = await NestFactory.create<NestExpressApplication>(AppModule) const apiConf = app.get<ConfigType<typeof apiConfig>>(apiConfig.KEY) app.setGlobalPrefix('/api') app.useGlobalInterceptors(new ProcessTimeInterceptor()) app.useGlobalInterceptors(new ResponseWrapInterceptor()) app.useGlobalFilters(new OtherExceptionFilter()) app.useGlobalFilters(new HttpExceptionFilter()) app.useGlobalPipes( new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, forbidUnknownValues: true }) ) app.useStaticAssets('public') const config = new DocumentBuilder() .setTitle('ying chat app') .setDescription('a real-time chat app') .setVersion('1.0') .build() const document = SwaggerModule.createDocument(app, config, { ignoreGlobalPrefix: true }) SwaggerModule.setup('doc', app, document) await app.listen(apiConf.port) Logger.log( `Application running on: http://localhost:${apiConf.port}/api`, 'Main' ) } bootstrap()
package model; import javax.persistence.*; import java.util.List; import static javax.persistence.GenerationType.IDENTITY; /** * Clase que representa los Monitores disponibles en el gimnasio */ @Entity @Table(name="monitor") public class Monitor { @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "ID_Monitor") private int id_monitor; @Column(name = "Nombre") private String nombre; @Column(name = "Email") private String email; @Column(name = "Contrasena") private String contrasena; @OneToMany(mappedBy = "monitor", cascade = CascadeType.ALL, fetch = FetchType.EAGER)//1 monitor puede tener varias actividades private List<ActividadHorario> actividades;//lista de actividades public Monitor() { } public Monitor(int id_monitor, String nombre, String email, String contrasena) { this.id_monitor = id_monitor; this.nombre = nombre; this.email = email; this.contrasena = contrasena; } public Monitor(String nombre, String email, String contrasena) { this.nombre = nombre; this.email = email; this.contrasena = contrasena; } public Monitor(int id_monitor, String nombre, String email, String contrasena, List<ActividadHorario> actividades) { this.id_monitor = id_monitor; this.nombre = nombre; this.email = email; this.contrasena = contrasena; this.actividades = actividades; } public int getId_monitor() { return id_monitor; } public void setID_Monitor(int id_monitor) { this.id_monitor = id_monitor; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getContrasena() { return contrasena; } public void setContrasena(String contrasena) { this.contrasena = contrasena; } public List<ActividadHorario> getActividades() { return actividades; } public void setActividades(List<ActividadHorario> actividades) { this.actividades = actividades; } @Override public String toString() { String id_monitor_int=String.valueOf(id_monitor); return id_monitor_int; } }
import { Resolver, Query, Mutation, Args } from '@nestjs/graphql'; import { UsersService } from './users.service'; import { CreateUserInput } from 'src/graphql'; @Resolver('User') export class UsersResolver { constructor(private readonly usersService: UsersService) {} @Mutation('createUser') create(@Args('createUserInput') createUserInput: CreateUserInput) { return this.usersService.create(createUserInput); } @Query('users') findAll() { return this.usersService.findAll(); } @Mutation('paginationUsers') PaginationUsers(@Args('page') page: number, @Args('limit') limit: number) { return this.usersService.PaginateUsers(page, limit); } @Query('user') findOne(@Args('id') id: string) { return this.usersService.findOne(id); } @Query('usersLogin') findOneLogin() { return this.usersService.findUserLogin(); } @Mutation('removeUser') remove(@Args('id') id: string) { return this.usersService.remove(id); } }
#pragma once #include "../config.h" #include <functional> #include <any> #include <tuple> CGULL_NAMESPACE_START CGULL_GUTS_NAMESPACE_START //! Function return value tagging struct return_tag {}; struct return_auto_tag : return_tag {}; struct return_void_tag : return_tag {}; struct return_any_tag : return_tag {}; struct return_promise_tag : return_tag {}; // template<> struct function_return_value_traits< ... > template< typename _T > struct function_return_value_traits { using tag = return_auto_tag; }; // template<> struct function_return_value_traits< void > template<> struct function_return_value_traits< void > { using tag = return_void_tag; }; // template<> struct function_return_value_traits< std::any > template<> struct function_return_value_traits< std::any > { using tag = return_any_tag; }; // template<> struct function_return_value_traits< promise > // see it in promise.h after promise definition... //! Function arguments tagging struct args_count_0 {}; struct args_count_1_auto {}; struct args_count_1_any {}; struct args_count_x {}; // template<> struct function_args_traits< (>1), auto > template< int _C, typename _T > struct function_args_traits { using tag = args_count_x; }; // template<> struct function_args_traits< 0, void > template<> struct function_args_traits< 0, void > { using tag = args_count_0; }; // template<> struct function_args_traits< 1, std::any > template<> struct function_args_traits< 1, std::any > { using tag = args_count_1_any; }; // template<> struct function_args_traits< 1, auto > template< typename _X > struct function_args_traits< 1, _X > { using tag = args_count_1_auto; }; template<typename T> struct function_traits : public function_traits<decltype(&T::operator())> {}; template< typename _Result, typename ... _Args > struct function_traits<_Result(_Args...)> { //! Full type of function. using function_type = _Result(_Args...); //! Full type of member function. #if 0 template<typename _Class> using member_type = typename memfn_type< typename std::remove_pointer< typename std::remove_reference<_Class>::type>::type, _Result, _Args... >::type; #endif //! Type of return value. using result_type = _Result; //! Return value tag. using result_tag = typename function_return_value_traits< result_type >::tag; //! Full function type fingerprint. using fingerprint_type = std::tuple< result_type, _Args... >; //! Signature for void-returning callback where result passed as first argument. template<typename _ThisResult, typename _PromiseType, typename _ResultFirst, typename _Enable = void> struct void_returning { using type = _ThisResult (_PromiseType, _ResultFirst, _Args...); }; template<typename _ThisResult, typename _PromiseType, typename _ResultFirst> struct void_returning<_ThisResult, _PromiseType, _ResultFirst, std::enable_if_t<std::is_void_v<_ResultFirst>> > { using type = _ThisResult (_PromiseType, _Args...); }; template<typename _ThisResult, typename _PromiseType> using void_returning_t = typename void_returning<_ThisResult, _PromiseType, _Result>::type; //! Arguments count. static constexpr int args_count = sizeof...(_Args); //! Arguments type info by element with OOR error generation. template< size_t I > struct arg { using type = typename std::tuple_element< I, std::tuple<_Args...> >::type; }; //! Arguments type info by element with OOR error hiding. template< size_t I, typename _Enable = void > struct arg_safe { using type = void; }; //! msvc enable_if type deduction bug workaround. ref: https://stackoverflow.com/questions/3209085 template< size_t I > struct _arg_safe_condition_helper { static constexpr bool value = I < args_count; }; template< size_t I > struct arg_safe< I, std::enable_if_t< _arg_safe_condition_helper< I >::value > > { using type = typename arg<I>::type; }; //! Arguments traits. using args_tag = typename function_args_traits< args_count, std::decay_t< typename arg_safe<0>::type > >::tag; }; template<typename _Result, typename ... _Args> struct function_traits<_Result(*)(_Args...)> : public function_traits<_Result(_Args...)> {}; template<typename _Class, typename _Result, typename ... _Args> struct function_traits<_Result(_Class::*)(_Args...)> : public function_traits<_Result(_Args...)> { //! Type of member function class. using owner_type = _Class&; }; template<typename _Class, typename _Result, typename ... _Args> struct function_traits<_Result(_Class::*)(_Args...) const> : public function_traits<_Result(_Args...)> { //! Type of member function class. using owner_type = const _Class&; }; template<typename _Class, typename _Result, typename ... _Args> struct function_traits<_Result(_Class::*)(_Args...) volatile> : public function_traits<_Result(_Args...)> { //! Type of member function class. using owner_type = volatile _Class&; }; template<typename _Class, typename _Result, typename ... _Args> struct function_traits<_Result(_Class::*)(_Args...) const volatile> : public function_traits<_Result(_Args...)> { //! Type of member function class. using owner_type = const volatile _Class&; }; template< typename _T > using memfn_internal = std::_Mem_fn<_T>; template<typename _Function> struct function_traits<std::function<_Function> > : public function_traits<_Function> {}; template<typename _Result, typename _Class> struct function_traits<memfn_internal<_Result _Class::*> > : public function_traits<_Result(_Class*)> {}; template<typename _Result, typename _Class, typename ... _Args> struct function_traits<memfn_internal<_Result(_Class::*)(_Args...)> > : public function_traits<_Result(_Class*, _Args...)> {}; template<typename _Result, typename _Class, typename ... _Args> struct function_traits<memfn_internal<_Result(_Class::*)(_Args...) const> > : public function_traits<_Result(const _Class*, _Args...)> {}; template<typename _Result, typename _Class, typename ... _Args> struct function_traits<memfn_internal<_Result(_Class::*)(_Args...) volatile> > : public function_traits<_Result(volatile _Class*, _Args...)> {}; template<typename _Result, typename _Class, typename ... _Args> struct function_traits<memfn_internal<_Result(_Class::*)(_Args...) const volatile> > : public function_traits<_Result(const volatile _Class*, _Args...)> {}; template<typename T> struct function_traits<T&> : public function_traits<T> {}; template<typename T> struct function_traits<const T&> : public function_traits<T> {}; template<typename T> struct function_traits<volatile T&> : public function_traits<T> {}; template<typename T> struct function_traits<const volatile T&> : public function_traits<T> {}; template<typename T> struct function_traits<T&&> : public function_traits<T> {}; template<typename T> struct function_traits<const T&&> : public function_traits<T> {}; template<typename T> struct function_traits<volatile T&&> : public function_traits<T> {}; template<typename T> struct function_traits<const volatile T&&> : public function_traits<T> {}; template< typename _Callback > using functor_t = typename std::function<typename function_traits<_Callback>::function_type>; // argument dispatcher template< int _I, typename _Head, typename... _Args > struct argGetter { using return_type = typename argGetter<_I-1, _Args...>::return_type; static return_type get(_Head&&, _Args&&... tail) { return argGetter<_I-1, _Args...>::get(tail...); } }; template< typename _Head, typename... _Args > struct argGetter<0, _Head, _Args...> { using return_type = _Head; static return_type get(_Head&& head, _Args&&... ) { return head; } }; template< int _I, typename _Head, typename... _Args > auto getArg(_Head&& head, _Args&&... tail) -> typename argGetter<_I, _Head, _Args...>::return_type { return argGetter<_I, _Head, _Args...>::get(head, tail...); } template<typename _Func1, typename _Func2> using is_same_fingerprint = std::is_same< typename function_traits<_Func1>::fingerprint_type, typename function_traits<_Func2>::fingerprint_type >; template<typename _Func1, typename _Func2> inline constexpr bool is_same_fingerprint_v = is_same_fingerprint<_Func1, _Func2>::value; CGULL_GUTS_NAMESPACE_END CGULL_NAMESPACE_END
import { browser } from '$app/environment'; import { parse } from 'node-html-parser'; import { format } from 'date-fns'; import readingTime from 'reading-time'; import type { Post } from '$lib/types'; if (browser) { throw new Error(`Posts should only be generated server-side`); } // Get all posts' metadata export const posts = Object.entries(import.meta.glob(`/content/posts/*/*.md`, { eager: true })) .map(([, obj]) => { const post = obj as Post; const html = parse(post.default.render().html); // When description isn't provided in frontmatter, use the first paragraph of the post as preview instead. const preview = post.metadata.description ? parse(post.metadata.description) : html.querySelector('p'); return { ...post.metadata, // Format date as yyyy-MM-dd datetime: format( // Offset by timezone so that the date is correct addTimeZoneOffset(new Date(post.metadata.datetime)), 'yyyy-MM-dd' ), preview: { html: preview?.toString(), // Text only preview (i.e no html elements), used for SEO text: preview?.structuredText ?? preview?.toString() }, // Estimate reading time for the post readingTime: readingTime(html.structuredText).text }; }) // Sort by most recent date .sort((a, b) => new Date(b.datetime).getTime() - new Date(a.datetime).getTime()) // Add references to the next and previous post .map((post, index, allPosts) => ({ ...post, next: allPosts[index - 1], previous: allPosts[index + 1] })); function addTimeZoneOffset(date: Date) { const offsetInMilliseconds = new Date().getTimezoneOffset() * 60 * 1000; return new Date(new Date(date).getTime() + offsetInMilliseconds); }
= Operator Board An operator board helps Network Operations Centers (NOCs) visualize network monitoring information. You can use and arrange customizable dashlets to display different types of information (alarms, availability maps, and so on) on the board. You can also create multiple operator boards and customize them for different user groups. There are two visualization modes in which you can display dashlets: * *Ops panel:* Displays multiple dashlets on one page. Useful for displaying information in a centralized location (for example, on a NOC operator's workstation). + .Four dashlets on an ops panel image::visualizations/opsboard/01_opspanel-concept.png["Diagram showing an ops panel with four dashlets."] * *Ops board:* Displays one dashlet at a time, in rotation. Useful for displaying a variety of information that users can view independently (for example, on a wall-mounted screen in a NOC). + .Four dashlets in rotation on an ops board image::visualizations/opsboard/02_opsboard-concept.png["Diagram showing an ops panel with four dashlets stacked on top of each other, indicating that they are shown one by one in rotation."] [[opsboard-config]] == Configuration You must have admin permissions to create and configure operator boards. After you create an operator board, you can specify how the information will be visualized (as a panel or a board). Follow these steps to create a new operator board: . Click the *gear* symbol at the top-right of the page. . Under Additional Tools, click *Ops Board Configuration*. . Click the *plus* symbol (*+*) beside the Overview tab, type a name for the new ops board, and click *Save*. . Click *Add Dashlet*, select a dashlet from the *Dashlet* list, and configure its settings: ** *Title:* Dashlet name to display in the operator board. ** *Priority:* How often the dashlet displays in the rotation. Priority 1 is the highest, meaning it appears the most often. ** *Duration:* How long the dashlet displays in the rotation, in seconds. ** *Boost-Priority:* Change the dashlet's priority if it is in an alert state. This setting is optional, and is not available for all dashlets. ** *Boost-Duration:* Change the display duration if the dashlet is in an alert state. This setting is optional, and is not available for all dashlets. ** (Optional) Click *Properties* to configure additional settings (alarm severity, chart type, and so on). . Click the *up arrow* and *down arrow* symbols to change the dashlet's order. This affects its rotation order in the ops board view, or its position in the ops panel view. . Click *Preview* in the dashlet settings area to preview the dashlet. . Click *Preview* beside the operator board name to preview the board and all of its dashlets. The board's configuration is automatically saved. To view the operator board, click menu:Dashboards[Ops Board] in the top menu bar. Depending on the visualization you want to see, select either *Ops Panel* or *Ops Board*. == Dashlets Each dashlet visualizes specific information: * xref:deep-dive/visualizations/opsboard/dashlets/alarm-detail.adoc[*Alarm Details:*] Displays a table with alarms and their details. * xref:deep-dive/visualizations/opsboard/dashlets/alarms.adoc[*Alarms:*] Displays a table with a short description of alarms. * xref:deep-dive/visualizations/opsboard/dashlets/charts.adoc[*Charts:*] Displays predefined and custom bar graphs. * xref:deep-dive/visualizations/opsboard/dashlets/grafana.adoc[*Grafana:*] Displays a Grafana dashboard with data spanning a specified time range. * xref:deep-dive/visualizations/opsboard/dashlets/image.adoc[*Image:*] Displays a custom image. * xref:deep-dive/visualizations/opsboard/dashlets/ksc.adoc[*KSC Reports:*] Displays a specified KSC report. * xref:deep-dive/visualizations/opsboard/dashlets/map.adoc[*Map:*] Displays the https://opennms.discourse.group/t/geographical-maps/2212[geographical map]. * xref:deep-dive/visualizations/opsboard/dashlets/rrd.adoc[*RRD:*] Displays one or more RRD graphs. * xref:deep-dive/visualizations/opsboard/dashlets/rtc.adoc[*RTC:*] Displays configured SLA categories. * xref:deep-dive/visualizations/opsboard/dashlets/summary.adoc[*Summary:*] Displays a trend of incoming alarms spanning a specified time range. * xref:deep-dive/visualizations/opsboard/dashlets/surveillance.adoc[*Surveillance:*] Displays a specified surveillance view. * xref:deep-dive/visualizations/opsboard/dashlets/url.adoc[*URL:*] Displays the content of a defined web page or web application. To filter the information displayed in a dashlet, configure it using a generic xref:deep-dive/visualizations/opsboard/criteria-builder.adoc[criteria builder].
using PizzaPlace.Models; using PizzaPlace.Pizzas; namespace PizzaPlace.Factories { /// <summary> /// Produces pizza on one giant revolving surface.Downside is, that all /// pizzas must have the same cooking time, when prepared at the same time. /// </summary> public class GiantRevolvingPizzaOven(TimeProvider timeProvider) : PizzaOven(timeProvider) { private const int GiantRevolvingPizzaOvenCapacity = 120; private int? _previousCookingTime = null; protected override int Capacity => GiantRevolvingPizzaOvenCapacity; protected override void PlanPizzaMaking( IEnumerable<(RecipeDto Recipe, Guid Guid)> recipeOrders) { foreach ((RecipeDto recipe, Guid orderGuid) in recipeOrders) { _pizzaQueue.Enqueue((MakePizza(recipe), orderGuid)); } } private Func<Task<Pizza?>> MakePizza(RecipeDto recipe) => async () => { if (_previousCookingTime == null || recipe.CookingTimeMinutes == _previousCookingTime) { _previousCookingTime = recipe.CookingTimeMinutes; await CookPizza(recipe.CookingTimeMinutes); } else { await CookPizza((int)_previousCookingTime); await CookPizza(recipe.CookingTimeMinutes); } return GetPizza(recipe.RecipeType); }; } }
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/src/foundation/key.dart'; import 'package:flutter/src/widgets/framework.dart'; class AdviceField extends StatelessWidget { final String advice; const AdviceField({Key? key, required this.advice}) : super(key: key); @override Widget build(BuildContext context) { final themeData = Theme.of(context); return Material( elevation: 20, borderRadius: BorderRadius.circular(15), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), color: themeData.colorScheme.onPrimary, ), child: Padding( padding: EdgeInsets.symmetric(horizontal: 15, vertical: 20), child: Text( '''" $advice "''', style: themeData.textTheme.bodyText1, textAlign: TextAlign.center, ), ), ), ); } }
use crate::lan_api::LanDiscoArguments; use crate::platform_api::GoveeApiArguments; use crate::service::hass::HassArguments; use crate::undoc_api::UndocApiArguments; use clap::Parser; use std::str::FromStr; mod ble; mod cache; mod commands; mod hass_mqtt; mod lan_api; #[macro_use] mod platform_api; mod rest_api; mod service; mod temperature; mod undoc_api; mod version_info; #[derive(clap::Parser, Debug)] #[command(version = version_info::govee_version(), propagate_version=true)] pub struct Args { #[command(flatten)] api_args: GoveeApiArguments, #[command(flatten)] lan_disco_args: LanDiscoArguments, #[command(flatten)] undoc_args: UndocApiArguments, #[command(flatten)] hass_args: HassArguments, #[command(subcommand)] cmd: SubCommand, } #[derive(clap::Parser, Debug)] pub enum SubCommand { LanControl(commands::lan_control::LanControlCommand), LanDisco(commands::lan_disco::LanDiscoCommand), ListHttp(commands::list_http::ListHttpCommand), List(commands::list::ListCommand), HttpControl(commands::http_control::HttpControlCommand), Serve(commands::serve::ServeCommand), Undoc(commands::undoc::UndocCommand), } impl Args { pub async fn run(&self) -> anyhow::Result<()> { match &self.cmd { SubCommand::LanControl(cmd) => cmd.run(self).await, SubCommand::LanDisco(cmd) => cmd.run(self).await, SubCommand::ListHttp(cmd) => cmd.run(self).await, SubCommand::HttpControl(cmd) => cmd.run(self).await, SubCommand::List(cmd) => cmd.run(self).await, SubCommand::Serve(cmd) => cmd.run(self).await, SubCommand::Undoc(cmd) => cmd.run(self).await, } } } pub fn opt_env_var<T: FromStr>(name: &str) -> anyhow::Result<Option<T>> where <T as FromStr>::Err: std::fmt::Display, { match std::env::var(name) { Ok(p) => { Ok(Some(p.parse().map_err(|err| { anyhow::anyhow!("parsing ${name}: {err:#}") })?)) } Err(std::env::VarError::NotPresent) => Ok(None), Err(err) => anyhow::bail!("${name} is invalid: {err:#}"), } } fn setup_logger() { fn resolve_timezone() -> chrono_tz::Tz { std::env::var("TZ") .or_else(|_| iana_time_zone::get_timezone()) .ok() .and_then(|name| name.parse().ok()) .unwrap_or(chrono_tz::UTC) } let tz = resolve_timezone(); let utc_suffix = if tz == chrono_tz::UTC { "Z" } else { "" }; env_logger::builder() // A bit of boilerplate here to get timestamps printed in local time. // <https://github.com/rust-cli/env_logger/issues/158> .format(move |buf, record| { use chrono::Utc; use env_logger::fmt::Color; use std::io::Write; let subtle = buf .style() .set_color(Color::Black) .set_intense(true) .clone(); write!(buf, "{}", subtle.value("["))?; write!( buf, "{}{utc_suffix} ", Utc::now().with_timezone(&tz).format("%Y-%m-%dT%H:%M:%S") )?; write!(buf, "{:<5}", buf.default_styled_level(record.level()))?; if let Some(path) = record.module_path() { write!(buf, " {}", path)?; } write!(buf, "{}", subtle.value("]"))?; writeln!(buf, " {}", record.args()) }) .filter_level(log::LevelFilter::Info) .parse_env("RUST_LOG") .init(); } #[tokio::main(worker_threads = 2)] async fn main() -> anyhow::Result<()> { color_backtrace::install(); if let Ok(path) = dotenvy::dotenv() { eprintln!("Loading environment overrides from {path:?}"); } setup_logger(); let args = Args::parse(); args.run().await }
import { ErrorLogMetrics, ErrorLogReport } from '../types'; export class ErrorReportComposer { /** * Creates a report based on the collected metrics. * @param {ErrorLogMetrics} metrics * @return {ErrorLogReport} */ public createReport(metrics: ErrorLogMetrics): ErrorLogReport { return { totalErrors: metrics.totalErrors, uniqueIPs: Object.keys(metrics.ipAddresses).length, errorCodes: metrics.errorCodes, topErrorEndpoints: this.getTopWithCount(metrics.paths), errorsByMethod: metrics.methods, topErrorUserAgents: this.getTopWithCount(metrics.userAgents), peakErrorHour: this.getPeakHour(metrics.errorCountByHour), errorCountByHour: metrics.errorCountByHour, errorCountByDay: metrics.errorCountByDay, classifications: metrics.classifications, severityCounts: metrics.severityCounts, }; } private getPeakHour(frequency: { [key: string]: number }): string { let max = 0; let peakHour = ''; for (const key in frequency) { if (frequency[key] > max) { max = frequency[key]; peakHour = key; } } return peakHour; } private getTopWithCount( items: { [key: string]: number }, limit: number = 5 ): { [key: string]: number } { // Assuming values range from 0 to some MAX_VALUE const MAX_VALUE = 1000; // Adjust based on your knowledge of the data const buckets: string[][] = Array.from({ length: MAX_VALUE + 1 }, () => []); for (const [key, value] of Object.entries(items)) { if (value <= MAX_VALUE) { // Ensure value is within the expected range buckets[value].push(key); } } const result: { [key: string]: number } = {}; for (let i = MAX_VALUE; i >= 0 && Object.keys(result).length < limit; i--) { for (const key of buckets[i]) { if (Object.keys(result).length < limit) { result[key] = i; } else { break; } } } return result; } }
class PlaylistsController < ApplicationController include Search before_action :certificated before_action :authorized, except: %i[index show] before_action :input_playlist, except: %i[index index_favorited create] def index playlists = fileter_playlists playlists = apply_term(playlists) apply_order(playlists) render status: :ok, json: @playlists, each_serializer: PlaylistSerializer, meta: { elementsCount: @playlists_all_page.size, limit: params[:limit] }, adapter: :json, current_user: @current_user end # お気に入りプレイリスト一覧 def index_favorited apply_order(@current_user.fav_playlists) render status: :ok, json: @playlists, each_serializer: PlaylistSerializer, meta: { elementsCount: @playlists_all_page.size, limit: params[:limit] }, adapter: :json, current_user: @current_user end def show render status: :ok, json: @playlist, current_user: @current_user end def create @playlist = @current_user.playlists.build(title: params[:title]) if @playlist.save render status: :created, json: { slug: @playlist.slug } else render status: :unprocessable_entity end end def update correct_user(@playlist) and return if @playlist.update(title: params[:title]) render status: :created else render status: :unprocessable_entity end end def destroy correct_user(@playlist) and return @playlist.destroy render status: :no_content end def add_clip correct_user(@playlist) and return @clip = Clip.find_by(slug: params[:clip_id]) @playlist.add(@clip) render status: :created end def remove_clip correct_user(@playlist) and return @clip = Clip.find_by(slug: params[:clip_id]) @playlist.remove(@clip) render status: :no_content end def order_clips correct_user(@playlist) and return params[:clip_slugs].each.with_index(2) do |clip_slug, index| @clip = Clip.find_by(slug: clip_slug) @playlist.playlist_clips.find_by(clip_id: @clip.id).update(order: index) end end def favorite @current_user.favorite(@playlist) render status: :created end def unfavorite @current_user.unfavorite(@playlist) render status: :no_content end private def input_playlist @playlist = Playlist.find_by(slug: params[:id]) end def fileter_playlists # fieldが空のとき if params[:field].empty? return Playlist.all end # すべてを対象にソート if params[:target] == "all" and_search(params[:field], "search_keywords", Playlist) # creatorでソート elsif params[:target] == "creator" Playlist.joins(:user).where(users: { display_name: params[:field] }) # creatorのloginNameでソート elsif params[:target] == "creatorId" Playlist.joins(:user).where(users: { id: params[:field] }) # User.find_by(id: params[:field]).playlists # TODO: 一致検索のとき、どっちの方が早いか確かめる # titleでソート elsif params[:target] == "title" and_search(params[:field], "title", Playlist) end end def apply_term(playlists) # 1日 if params[:term] == "day" playlists.where(created_at: Time.zone.yesterday..Time.zone.now) # 1週間 elsif params[:term] == "week" playlists.where(created_at: 1.week.ago..Time.zone.now) # 1カ月 elsif params[:term] == "month" playlists.where(created_at: 1.month.ago..Time.zone.now) # 1年 elsif params[:term] == "year" playlists.where(created_at: 1.year.ago..Time.zone.now) # 指定なし(全期間) else playlists end end def apply_order(playlists) # お気に入り登録が多い順 if params[:order] == "fav_desc" playlists = playlists.sort_by { |playlist| playlist.favorites.length }.reverse ids = playlists.map(&:id) playlists = Playlist.in_order_of(:id, ids) # お気に入り登録が少ない順 elsif params[:order] == "fav_asc" playlists = playlists.sort_by { |playlist| playlist.favorites.length } ids = playlists.map(&:id) playlists = Playlist.in_order_of(:id, ids) # 日付の新しい順 elsif params[:order] == "date_desc" playlists = playlists.order(created_at: "DESC") # 日付の古い順 elsif params[:order] == "date_asc" playlists = playlists.order(created_at: "ASC") # 指定なし(お気に入り登録が多い順) else playlists = playlists.sort_by { |playlist| playlist.favorites.length }.reverse ids = playlists.map(&:id) playlists = Playlist.in_order_of(:id, ids) end @playlists_all_page = playlists if playlists.empty? @playlists = playlists else @playlists = playlists.paginate(page: params[:page], per_page: params[:limit]) end end end
package com.csot.recruit.controller.campus; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jodd.servlet.URLDecoder; import org.amberframework.core.bind.annotation.CurrentUser; import org.amberframework.core.common.model.AjaxRtnJson; import org.amberframework.web.miniui.pojo.MiniGridPageSort; import org.amberframework.web.miniui.pojo.MiniRtn2Grid; import org.amberframework.web.system.auth.model.original.user.SysUser; import org.elasticsearch.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import com.csot.recruit.common.util.CampusUtils; import com.csot.recruit.dao.original.campus.CampusPostMapper; import com.csot.recruit.dao.original.campus.CampusSiteMapper; import com.csot.recruit.dao.original.campus.CampusStudentMapper; import com.csot.recruit.model.original.attachment.Attachment; import com.csot.recruit.model.original.campus.CampusStudent; import com.csot.recruit.model.template.Template; import com.csot.recruit.service.attachment.AttachmentService; import com.csot.recruit.service.campus.CampusAddressbookService; import com.csot.recruit.service.campus.CampusStudentService; import com.csot.recruit.service.campus.CampusTaskService; import com.csot.recruit.service.mail.MailSendService; import com.csot.recruit.service.template.TemplateService; @Controller @RequestMapping("campusStudentController") public class CampusStudentController { private static final Logger logger = LoggerFactory.getLogger(CampusStudentController.class); @Resource private CampusStudentService campusStudentService; @Resource private CampusAddressbookService campusAddressbookService; @Resource private MailSendService mailSendService; @Resource private TemplateService templateService; @Resource private AttachmentService AttachmentService; @Resource private CampusTaskService campusTaskService; @Resource private CampusSiteMapper campusSiteMapper; @Resource private CampusPostMapper campusPostMapper; @Resource private CampusStudentMapper campusStudentMapper; @RequestMapping("list") public ModelAndView list() { return new ModelAndView("com/csot/campus/campusStudentList"); } @RequestMapping("datagrid") @ResponseBody public MiniRtn2Grid<CampusStudent> datagrid(MiniGridPageSort pageSort, HttpServletRequest request) { String siteId = request.getParameter("siteId"); String postId = request.getParameter("postId"); String stuName = request.getParameter("stuName"); String school = request.getParameter("school"); String org = request.getParameter("org"); String center = request.getParameter("center"); String yearth = request.getParameter("yearth"); String showType = request.getParameter("showType"); String radioValue1 = request.getParameter("radioValue1"); if (StringUtils.hasText(radioValue1)) { radioValue1 = URLDecoder.decode(radioValue1, "UTF-8"); // 后台转码,防止乱码 } String radioValue2 = request.getParameter("radioValue2"); if (StringUtils.hasText(radioValue2)) { radioValue2 = URLDecoder.decode(radioValue2, "UTF-8"); // 后台转码,防止乱码 } String radioValue3 = request.getParameter("radioValue3"); if (StringUtils.hasText(radioValue3)) { radioValue3 = URLDecoder.decode(radioValue3, "UTF-8"); // 后台转码,防止乱码 } String radioValue4 = request.getParameter("radioValue4"); if (StringUtils.hasText(radioValue4)) { radioValue4 = URLDecoder.decode(radioValue4, "UTF-8"); // 后台转码,防止乱码 } String radioValue5 = request.getParameter("radioValue5"); if (StringUtils.hasText(radioValue5)) { radioValue5 = URLDecoder.decode(radioValue5, "UTF-8"); // 后台转码,防止乱码 } String radioValue6 = request.getParameter("radioValue6"); if (StringUtils.hasText(radioValue6)) { radioValue6 = URLDecoder.decode(radioValue6, "UTF-8"); // 后台转码,防止乱码 } String radioValue7 = request.getParameter("radioValue7"); if (StringUtils.hasText(radioValue7)) { radioValue7 = URLDecoder.decode(radioValue7, "UTF-8"); // 后台转码,防止乱码 } String radioValue8 = request.getParameter("radioValue8"); if (StringUtils.hasText(radioValue8)) { radioValue8 = URLDecoder.decode(radioValue8, "UTF-8"); // 后台转码,防止乱码 } return campusStudentService.getGrid(pageSort, siteId, postId, stuName, school, org, center, yearth, showType, radioValue1, radioValue2, radioValue3, radioValue4, radioValue5, radioValue6, radioValue7, radioValue8); } @RequestMapping("create") public ModelAndView create(HttpServletRequest request) { // 创建时设置以下字段的默认值为无 CampusStudent campusStudent = new CampusStudent(); campusStudent.setOffer("无"); campusStudent.setIdcardCopy("无"); campusStudent.setBreakOff("无"); campusStudent.setPhoto("无"); campusStudent.setCetTranscript("无"); campusStudent.setTranscript("无"); campusStudent.setTrilateral("无"); campusStudent.setReferenceForm("无"); request.setAttribute("campusStudent", campusStudent); return new ModelAndView("com/csot/campus/campusStudentEdit"); } @RequestMapping("modify/{id}") public ModelAndView modify(@PathVariable String id, HttpServletRequest request) { CampusStudent campusStudent = campusStudentService.getByPrimaryKey(id); request.setAttribute("campusStudent", campusStudent); return new ModelAndView("com/csot/campus/campusStudentEdit"); } @RequestMapping("view/{id}") public ModelAndView view(@PathVariable String id, HttpServletRequest request) { CampusStudent campusStudent = campusStudentService.getByPrimaryKey(id); request.setAttribute("campusStudent", campusStudent); return new ModelAndView("com/csot/recruit/campus/campusStudentView"); } @RequestMapping("remove/{id}") @ResponseBody public AjaxRtnJson remove(@PathVariable String id) { AjaxRtnJson ajaxRtn = new AjaxRtnJson(); int count = 0; try { String[] idStr = id.split(","); for (int i = 0; i < idStr.length; i++) { String stuId = idStr[i]; campusStudentService.remove(stuId); count++; } if (count == idStr.length) { ajaxRtn = new AjaxRtnJson(true, "成功删除" + count + "条数据。"); } else { ajaxRtn = new AjaxRtnJson(true, "删除" + count + "条数据,有" + (idStr.length - count) + "条数据删除失败"); } } catch (DataAccessException e) { logger.error(e.getMessage(), e); ajaxRtn = new AjaxRtnJson(false, "删除失败: " + e.getMessage()); } return ajaxRtn; } @RequestMapping("save") @ResponseBody public AjaxRtnJson save(CampusStudent campusStudent) { campusStudent.setYearth(CampusUtils.getCurrentYearth()); // 修改界面中的单选框的值如果没有选择有或者无,则设置相应的值为无 Date date = new Date(); campusStudent.setBreakOffTime(date); // 若存在相同的身份证号,则更新 if (null != campusStudentMapper.selectByPrimaryKey(campusStudent.getId())) { campusStudent.setChangeTime(date); try { campusStudentService.updateSelective(campusStudent); return new AjaxRtnJson(true, "修改成功"); } catch (DataAccessException e) { logger.error(e.getMessage(), e); return new AjaxRtnJson(false, "修改失败: " + e.getMessage()); } } else { try { campusStudentService.create(campusStudent); return new AjaxRtnJson(true, "新建成功"); } catch (DataAccessException e) { logger.error(e.getMessage(), e); return new AjaxRtnJson(false, "新建失败: " + e.getMessage()); } } } @RequestMapping("importStudentInfo") public ModelAndView importStudentInfo() { return new ModelAndView("com/csot/campus/campusStudentImport"); } @RequestMapping("importStudentInfoExcel") @ResponseBody public AjaxRtnJson importStudentInfoExcel(HttpServletRequest request) { // 转型为MultipartHttpRequest: MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartFile = multipartRequest.getFile("myFile"); String basePath = request.getServletContext().getRealPath("/resources/upload"); try { String message = campusStudentService.importStudentInfo(multipartFile, basePath); return new AjaxRtnJson(true, message); } catch (Exception e) { logger.error(e.getMessage()); return new AjaxRtnJson(false, e.getMessage()); } } /** * 下载学生资料导入模板 */ @RequestMapping("campusStuInfoTemplete") public void campusStuInfoTemplete(HttpServletRequest request, HttpServletResponse response) throws IOException { // 模板存放路径 String filePath = request.getSession().getServletContext().getRealPath("") + "/excelTemplate/campusStudent.xls"; File f = new File(filePath); if (!f.exists()) { response.sendError(404, "File not found!"); return; } BufferedInputStream br = new BufferedInputStream(new FileInputStream(f)); byte[] buf = new byte[1024]; int len = 0; response.reset(); response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("校招学生资料导入模板.xls", "utf-8").replace("+", "%20")); OutputStream out = response.getOutputStream(); while ((len = br.read(buf)) > 0) { out.write(buf, 0, len); } br.close(); out.close(); } /** * 根据查询结果导出学生信息资料 * * @param request * @param response */ @RequestMapping("exportCampusStudentInfo") @ResponseBody public void exportCampusStudentInfo(MiniGridPageSort pageSort, HttpServletRequest request, HttpServletResponse response) { List<CampusStudent> campusStuList = datagrid(pageSort, request).getData(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String fileName = "CampusStudentInfo_" + sdf.format(new Date()) + ".xls"; String xmlPath = "excelTemplate/CampusStudentExportTemplate.xml"; String templatePath = "excelTemplate/campusStudent.xls"; campusTaskService.exportByTemplate(response, fileName, campusStuList, xmlPath, templatePath); } /** * 发送email * * @return */ @RequestMapping("sendEmail/{ids}") public ModelAndView sendEmail(@PathVariable String ids) { ModelAndView mav = new ModelAndView("com/csot/campus/campusStuEmailSend"); mav.addObject("ids", ids); return mav; } /** * 按模板发送email * * @return */ @RequestMapping("sendByTemplate/{ids}") public ModelAndView sendByTemplate(@PathVariable String ids, HttpServletRequest request) { String[] idArr = ids.split(","); List<CampusStudent> campusStuList = Lists.newArrayList(); String realName = ""; for (int i = 0; i < idArr.length; i++) { CampusStudent campusStudent = campusStudentService.getByPrimaryKey(idArr[i]); campusStuList.add(campusStudent); } for (int j = 0; j < campusStuList.size(); j++) { realName += campusStuList.get(j).getRealname() + ";"; } request.setAttribute("realName", realName); request.setAttribute("ids", ids); return new ModelAndView("com/csot/campus/campusStuEmailSendByTemp"); } // 自定义发送邮件 @RequestMapping("sendByDefinition/{ids}") public ModelAndView sendByDefinition(@CurrentUser SysUser sysUser, @PathVariable String ids, HttpServletRequest request) { String[] idArr = ids.split(","); List<CampusStudent> campusStuList = Lists.newArrayList(); String realName = ""; String type = "create"; String id = "0"; List<Attachment> attachments = new ArrayList<Attachment>(); Template template = null; if (!"create".equals(type) && !("0".equals(id))) { template = templateService.getByPrimaryKey(id); // 查询出关联的附件 attachments = AttachmentService.findAttachsByRelateId(id); } else { // 通过登录用户,找到供应商名称或编号 template = new Template(); // id填充,用作页面保存附件关联 template.setId(UUID.randomUUID().toString().replace("-", "")); template.setCreator(sysUser.getAccount()); template.setCreateDate(new Date()); } for (int i = 0; i < idArr.length; i++) { CampusStudent campusStudent = campusStudentService.getByPrimaryKey(idArr[i]); campusStuList.add(campusStudent); } for (int j = 0; j < campusStuList.size(); j++) { realName += campusStuList.get(j).getRealname() + ";"; } request.setAttribute("realName", realName); request.setAttribute("ids", ids); request.setAttribute("template", template); request.setAttribute("attachments", attachments); request.setAttribute("type", type); return new ModelAndView("com/csot/campus/campusStuEmailSendByDefinite"); } @RequestMapping("sendEmailToStu") @ResponseBody public AjaxRtnJson sendEmailToStuByTemp(HttpServletRequest request) { // 获取前端传过来的参数 String templateId = request.getParameter("templateId"); String ids = request.getParameter("ids"); Template template = templateService.getByPrimaryKey(templateId); String[] idArr = ids.split(","); List<CampusStudent> campusStuList = Lists.newArrayList(); for (int i = 0; i < idArr.length; i++) { CampusStudent campusStudent = campusStudentService.getByPrimaryKey(idArr[i]); campusStuList.add(campusStudent); } try { for (int i = 0; i < campusStuList.size(); i++) { mailSendService.sendEmail(campusStuList.get(i).getEmail(), template, campusStuList.get(i)); } return new AjaxRtnJson(true, "发送成功"); } catch (Exception e) { logger.error(e.getMessage()); return new AjaxRtnJson(false, e.getMessage()); } } // ByDef @RequestMapping("sendEmailToStuByDef") @ResponseBody public AjaxRtnJson sendEmailToStuByDef(Template template, HttpServletRequest request) { // 获取前端传过来的参数 String ids = request.getParameter("ids"); String[] idArr = ids.split(","); List<CampusStudent> campusStuList = Lists.newArrayList(); for (int i = 0; i < idArr.length; i++) { CampusStudent campusStudent = campusStudentService.getByPrimaryKey(idArr[i]); campusStuList.add(campusStudent); } try { for (int i = 0; i < campusStuList.size(); i++) { mailSendService.sendEmail(campusStuList.get(i).getEmail(), template, campusStuList.get(i)); } return new AjaxRtnJson(true, "发送成功"); } catch (Exception e) { logger.error(e.getMessage()); return new AjaxRtnJson(false, e.getMessage()); } } /** * 填写违约原因 * * @return */ @RequestMapping("doSetBreakOffReason/{id}") public ModelAndView doSetBreakOffReason(@PathVariable String id, HttpServletRequest request) { CampusStudent campusStudent = campusStudentService.getByPrimaryKey(id); request.setAttribute("campusStudent", campusStudent); return new ModelAndView("com/csot/campus/stuBreakOffReason"); } /** * 设置显示字段 * * @return */ @RequestMapping("showColumn") public ModelAndView showColumn() { return new ModelAndView("com/csot/campus/campusStudentSelectForm"); } /** * 更多查询条件隐藏 * * @return */ @RequestMapping("queryMore") public ModelAndView queryMore() { return new ModelAndView("com/csot/campus/campusStuQueryMore"); } }
import 'package:flutter/material.dart'; import 'package:flutter_travel_guide_dashborad/core/constant/style.dart'; class DropDownTextField extends StatefulWidget { final String hintText; final List<String> options; final void Function(String?) onChanged; final String? selectedOption; final Function? addClicked; final bool withAdd; const DropDownTextField({ Key? key, required this.hintText, required this.options, required this.onChanged, required this.selectedOption, this.addClicked, this.withAdd = false, }) : super(key: key); @override DropDownTextFieldState createState() => DropDownTextFieldState(); } class DropDownTextFieldState extends State<DropDownTextField> { String? _selectedOption; @override void initState() { _selectedOption = widget.selectedOption; super.initState(); } @override void didUpdateWidget(covariant DropDownTextField oldWidget) { _selectedOption = widget.selectedOption; super.didUpdateWidget(oldWidget); } @override Widget build(BuildContext context) { if (widget.withAdd && !widget.options.contains("add")) { widget.options.add("add"); } return Container( padding: const EdgeInsets.symmetric(horizontal: 24.0), decoration: BoxDecoration( border: Border.all(color: Colors.black38), color: Colors.black12.withAlpha(11), borderRadius: BorderRadius.circular(10), ), child: DropdownButtonHideUnderline( child: DropdownButton<String>( borderRadius: BorderRadius.circular(20), iconDisabledColor: Colors.blue, iconEnabledColor: Colors.blue, value: _selectedOption, hint: Text(widget.hintText, style: StylesText.newDefaultTextStyle.copyWith(color: Colors.grey)), isExpanded: true, onChanged: (value) { if (widget.withAdd && value == "add") { widget.addClicked?.call(); } else { setState(() { _selectedOption = value; widget.onChanged(value); }); } }, items: widget.options.map((String option) { return DropdownMenuItem<String>( value: option, child: Text( option, style: StylesText.newDefaultTextStyle .copyWith(color: Colors.black), ), ); }).toList(), ), ), ); } }
const { MessageEmbed, MessageActionRow, MessageSelectMenu, CommandInteractionOptionResolver, Collection } = require('discord.js'); const {getClosest, getUserSettings, jsonParse, translate, untranslate} = require('../util'); const fs = require('fs'); const PagedEmbed = require('../util/PagedEmbed'); const PagedMessage = require("../util/PagedMessage"); const name = translate('datasheet'); const description = translate('Displays a useful data sheet.'); const filter = () => true; const options = [ { type: 3, //str name: translate('name'), description: translate('The data sheet to search for.'), required: true, choices: [ { name: 'Artifact Upgrade', value: 'Artifact' }, { name: 'Character Upgrade', value: 'Character' }, { name: 'Monthly Shop', value: 'Paimon Shop' }, { name: 'Reaction Guide', value: 'Reaction Guide' }, { name: 'Resin Guide', value: 'Resin' }, { name: 'Talent Upgrade', value: 'Talent' }, { name: 'Weapon Upgrade', value: 'Weapon' }, { name: 'Genshin Terms', value: 'Terms' } ] } ]; async function execute(interaction) { const basePath = './data/guides/data'; let dirPath = basePath + '/' + interaction.locale; if (!fs.existsSync(dirPath)) dirPath = basePath + '/en-GB'; const enPath = basePath + '/en-GB'; const aliases = jsonParse('./data/aliases/data.json', {}); const query = untranslate(interaction.options.getString('name') ?? '', interaction.locale); const closest = getClosest((aliases[query] ?? query), fs.readdirSync(enPath).map(f => f.split('.')[0])); if (!closest || !query) { const emojiMap = jsonParse('./data/emojis/datasheetEmojis.json', {}); let list = []; for (const name of Object.keys(emojiMap)) { const itemName = name; list.push(itemName); } list = list.sort(); const listEmbed = new MessageEmbed() .setColor(getUserSettings(interaction.user.id).color) .setDescription(translate('Make a selection to proceed.', interaction.locale)); const pages = []; const pageSize = 25; for (let i = 0; i <= list.length; i += pageSize) { const embed = listEmbed; const row = new MessageActionRow(); const selectMenu = new MessageSelectMenu() .setCustomId('itemselect'); const options = list.slice(i, i + pageSize) .map(item => ({value: item, label: item, emoji: emojiMap[untranslate(item, interaction.locale)]})); selectMenu.addOptions(options); row.addComponents(selectMenu); pages.push({embeds: [embed], components: [row]}); } const pagedMsg = new PagedMessage(interaction, pages); const {message} = await pagedMsg.update(); const filter = i => interaction.user.id === i.user.id; const time = 10 * 60 * 1000; const collector = message.createMessageComponentCollector({filter, time}); collector.on('collect', async i => { await i.deferUpdate().catch(() => { }); if (i.customId !== 'itemselect') return null; await pagedMsg.end(false); const cmdOptions = [{ name: options[0].name, type: 'STRING', value: i.values[0] }]; interaction.options = new CommandInteractionOptionResolver( interaction.client, cmdOptions, { users: new Collection(), members: new Collection(), roles: new Collection(), channels: new Collection(), messages: new Collection() } ); interaction.client.commands.get(name).execute(interaction); }); } const data = jsonParse(dirPath + '/' + untranslate(closest, interaction.locale) + '.json', jsonParse(basePath + '/en-GB/' + untranslate(closest, interaction.locale) + '.json', [])) .map((pg, i, arr) => Object({ ...pg, color: getUserSettings(interaction.user.id).color, footer: { text: pg.footer.text + ' • ' + translate('Page {0} of {0}', interaction.locale) .replace('{0}', i + 1) .replace('{0}', arr.length) } })); return new PagedEmbed(interaction, data); } module.exports = {name, description, options, filter, execute};
import classNames from 'classnames'; import React, { ComponentProps, FC } from 'react'; interface InputProps extends ComponentProps<'input'> { fullWidth?: boolean; } export const Input: FC<InputProps> = ({ fullWidth = true, ...rest }) => { return ( <input {...rest} className={classNames( 'rounded-[5px] bg-white px-5 py-2.5 text-sm text-dark shadow-card placeholder:text-description focus:outline-primary/50', { 'w-full': fullWidth, }, )} /> ); };
package ru.transservice.routemanager.ui.routesettings import android.os.Bundle import android.view.* import androidx.appcompat.widget.SearchView import androidx.fragment.app.Fragment import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.navigation.fragment.navArgs import androidx.navigation.navGraphViewModels import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import ru.transservice.routemanager.MainActivity import ru.transservice.routemanager.R import ru.transservice.routemanager.databinding.FragmentRegionListBinding import ru.transservice.routemanager.service.LoadResult class RegionListFragment : Fragment() { private var _binding: FragmentRegionListBinding? = null private val binding get() = _binding!! private lateinit var regionAdapter: RegionListAdapter private val viewModel: RouteSettingsViewModel by navGraphViewModels(R.id.navRouteSettings) lateinit var navController: NavController private val args: RegionListFragmentArgs by navArgs() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { } initViewModel() setHasOptionsMenu(true) regionAdapter = RegionListAdapter { viewModel.setRegion(it) navController.navigate(RegionListFragmentDirections.actionRegionListFragmentToRouteSettingsFragment()) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_search, menu) val searchItem = menu.findItem(R.id.action_search) val searchView = searchItem?.actionView as SearchView searchView.queryHint = "Введите наименование" searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener{ override fun onQueryTextSubmit(query: String?): Boolean { viewModel.handleSearchQuery(query!!) return true } override fun onQueryTextChange(newText: String?): Boolean { viewModel.handleSearchQuery(newText!!) return true } }) super.onCreateOptionsMenu(menu, inflater) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentRegionListBinding.inflate(inflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) navController = Navigation.findNavController(requireActivity(),R.id.nav_host_fragment) with(binding.rvRegionsList){ layoutManager = LinearLayoutManager(context) addItemDecoration(DividerItemDecoration(context,DividerItemDecoration.VERTICAL)) adapter = regionAdapter } viewModel.mediatorListRegionResult.observe(viewLifecycleOwner, { when (it) { is LoadResult.Loading -> { (requireActivity() as MainActivity).swipeLayout.isRefreshing = true } is LoadResult.Success -> { (requireActivity() as MainActivity).swipeLayout.isRefreshing = false regionAdapter.updateItems(it.data ?: listOf()) if (regionAdapter.selectedPos == RecyclerView.NO_POSITION) { args.region?.let { val pos = regionAdapter.getItemPosition(it) regionAdapter.selectedPos = pos with(binding.rvRegionsList) { scrollToPosition(pos) } } } } } }) } override fun onDestroyView() { super.onDestroyView() _binding = null } companion object { @JvmStatic fun newInstance() = RegionListFragment().apply { arguments = Bundle().apply { } } } private fun initViewModel(){ viewModel.loadRegions() viewModel.removeSources() viewModel.addSourcesRegion() viewModel.addSourcesVehicle() } }
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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. */ #include <chrono> #include <thread> #include <unistd.h> #include <gtest/gtest.h> #include <iservice_registry.h> #include <surface.h> #include <display_type.h> using namespace testing; using namespace testing::ext; namespace OHOS::Rosen { class SurfaceIPCTest : public testing::Test, public IBufferConsumerListenerClazz { public: static void SetUpTestCase(); virtual void OnBufferAvailable() override; pid_t ChildProcessMain(); static inline sptr<Surface> csurf = nullptr; static inline int32_t pipeFd[2] = {}; static inline int32_t ipcSystemAbilityID = 34156; static inline BufferRequestConfig requestConfig = {}; static inline BufferFlushConfig flushConfig = {}; }; void SurfaceIPCTest::SetUpTestCase() { GTEST_LOG_(INFO) << getpid(); requestConfig = { .width = 0x100, // small .height = 0x100, // small .strideAlignment = 0x8, .format = PIXEL_FMT_RGBA_8888, .usage = HBM_USE_CPU_READ | HBM_USE_CPU_WRITE | HBM_USE_MEM_DMA, .timeout = 0, }; flushConfig = { .damage = { .w = 0x100, .h = 0x100, } }; } void SurfaceIPCTest::OnBufferAvailable() { } pid_t SurfaceIPCTest::ChildProcessMain() { pipe(pipeFd); pid_t pid = fork(); if (pid != 0) { return pid; } int64_t data; read(pipeFd[0], &data, sizeof(data)); sptr<IRemoteObject> robj = nullptr; while (true) { auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); robj = sam->GetSystemAbility(ipcSystemAbilityID); if (robj != nullptr) { break; } sleep(0); } auto producer = iface_cast<IBufferProducer>(robj); auto psurf = Surface::CreateSurfaceAsProducer(producer); sptr<SurfaceBuffer> buffer = nullptr; int releaseFence = -1; auto sret = psurf->RequestBuffer(buffer, releaseFence, requestConfig); if (sret != OHOS::GSERROR_OK) { data = sret; write(pipeFd[1], &data, sizeof(data)); exit(0); } buffer->GetExtraData()->ExtraSet("123", 0x123); buffer->GetExtraData()->ExtraSet("345", (int64_t)0x345); buffer->GetExtraData()->ExtraSet("567", "567"); sret = psurf->FlushBuffer(buffer, -1, flushConfig); data = sret; write(pipeFd[1], &data, sizeof(data)); sleep(0); read(pipeFd[0], &data, sizeof(data)); close(pipeFd[0]); close(pipeFd[1]); exit(0); return 0; } /* * Function: produce and consumer surface by IPC * Type: Function * Rank: Important(2) * EnvConditions: N/A * CaseDescription: 1. produce surface, fill buffer * 2. consume surface and check buffer */ HWTEST_F(SurfaceIPCTest, BufferIPC001, Function | MediumTest | Level2) { auto pid = ChildProcessMain(); ASSERT_GE(pid, 0); csurf = Surface::CreateSurfaceAsConsumer("test"); csurf->RegisterConsumerListener(this); auto producer = csurf->GetProducer(); auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); sam->AddSystemAbility(ipcSystemAbilityID, producer->AsObject()); int64_t data = 0; write(pipeFd[1], &data, sizeof(data)); sleep(0); read(pipeFd[0], &data, sizeof(data)); EXPECT_EQ(data, OHOS::GSERROR_OK); sptr<SurfaceBuffer> buffer = nullptr; int32_t fence = -1; int64_t timestamp; Rect damage; auto sret = csurf->AcquireBuffer(buffer, fence, timestamp, damage); EXPECT_EQ(sret, OHOS::GSERROR_OK); EXPECT_NE(buffer, nullptr); if (buffer != nullptr) { int32_t int32; int64_t int64; std::string str; buffer->GetExtraData()->ExtraGet("123", int32); buffer->GetExtraData()->ExtraGet("345", int64); buffer->GetExtraData()->ExtraGet("567", str); EXPECT_EQ(int32, 0x123); EXPECT_EQ(int64, 0x345); EXPECT_EQ(str, "567"); } sret = csurf->ReleaseBuffer(buffer, -1); EXPECT_EQ(sret, OHOS::GSERROR_OK); write(pipeFd[1], &data, sizeof(data)); close(pipeFd[0]); close(pipeFd[1]); sam->RemoveSystemAbility(ipcSystemAbilityID); int32_t ret = 0; do { waitpid(pid, nullptr, 0); } while (ret == -1 && errno == EINTR); } /* * Function: RequestBuffer and flush buffer * Type: Function * Rank: Important(2) * EnvConditions: N/A * CaseDescription: 1. call RequestBuffer, check sret and buffer * 2. call flushbuffer and check sret */ HWTEST_F(SurfaceIPCTest, Cache001, Function | MediumTest | Level2) { csurf->RegisterConsumerListener(this); auto producer = csurf->GetProducer(); auto psurf = Surface::CreateSurfaceAsProducer(producer); sptr<SurfaceBuffer> buffer = nullptr; int releaseFence = -1; auto sret = psurf->RequestBuffer(buffer, releaseFence, requestConfig); ASSERT_EQ(sret, OHOS::GSERROR_OK); ASSERT_NE(buffer, nullptr); int32_t int32; int64_t int64; std::string str; buffer->GetExtraData()->ExtraGet("123", int32); buffer->GetExtraData()->ExtraGet("345", int64); buffer->GetExtraData()->ExtraGet("567", str); ASSERT_EQ(int32, 0x123); ASSERT_EQ(int64, 0x345); ASSERT_EQ(str, "567"); sret = psurf->FlushBuffer(buffer, -1, flushConfig); ASSERT_EQ(sret, OHOS::GSERROR_OK); } }
/* Copyright (C) 2002-2021 CERN for the benefit of the ATLAS collaboration */ #ifndef ATHENAPOOLTEST_LARCELLCONTFAKEREADER_H #define ATHENAPOOLTEST_LARCELLCONTFAKEREADER_H /** * @file LArCellContFakeReader.h * * @brief Test Algorithm for POOL I/O uses CaloCellContainer as test * data * * @author RD Schaffer <R.D.Schaffer@cern.ch> * * $Id: LArCellContFakeReader.h,v 1.4 2006-12-20 16:48:06 schaffer Exp $ * */ /** * @class LArCellContFakeReader * * @brief Test Algorithm for POOL I/O uses CaloCellContainer as test * data * */ #include "AthenaBaseComps/AthAlgorithm.h" #include "CaloDetDescr/CaloDetDescrManager.h" #include "StoreGate/ReadCondHandleKey.h" class CaloCell_ID; class CaloCellContainer; class LArCellContFakeReader : public AthAlgorithm { public: /// Algorithm constructor LArCellContFakeReader(const std::string &name,ISvcLocator *pSvcLocator); /// Algorithm initialize at begin of job virtual StatusCode initialize() override; /// Algorithm execute once per event virtual StatusCode execute() override; /// Algorithm finalize at end of job virtual StatusCode finalize() override; // Private methods: private: /// Avoid use of default constructor LArCellContFakeReader(); /// Avoid use of copy constructor LArCellContFakeReader(const LArCellContFakeReader&); /// Avoid use of copy operator LArCellContFakeReader &operator=(const LArCellContFakeReader&); // Private data: private: /// Print out cell info void printCells(const CaloCellContainer* larCont) const; /// Need DD mgr to create cells SG::ReadCondHandleKey<CaloDetDescrManager> m_caloMgrKey { this , "CaloDetDescrManager" , "CaloDetDescrManager" , "SG Key for CaloDetDescrManager in the Condition Store" }; /// Need id helper to create cells const CaloCell_ID* m_calocellId; }; #endif // SRC_LARCELLCONTFAKEREADER_H
package com.example.diplom.rdb; import com.example.diplom.entity.User; import com.example.diplom.form.UserRegistrationForm; import com.example.diplom.rdb.repository.UserRepository; import com.example.diplom.service.UserService; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class RdbUserService implements UserService { private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; public RdbUserService(UserRepository userRepository, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } @Override public boolean register(UserRegistrationForm userRegistrationForm) { if (!userRegistrationForm.getPassword().equals(userRegistrationForm.getPasswordConfirmation())) { return false; } if (userRepository.findByLogin(userRegistrationForm.getLogin()).isPresent()) { return false; } User user = new User(); user.setLogin(userRegistrationForm.getLogin()); String passwordHash = passwordEncoder.encode(userRegistrationForm.getPassword()); user.setPassword(passwordHash); user.setRole(userRegistrationForm.getRole()); userRepository.save(user); return true; } @Override public Iterable<User> findUsersByRole(String role) { return userRepository.findByRole(role); } @Override public Optional<User> findUserByLogin(String login) { return userRepository.findByLogin(login); } @Override public Optional<User> findById(Integer id) { return userRepository.findById(id); } }
import { BadRequestException, CanActivate, ExecutionContext, Injectable, UnauthorizedException, } from '@nestjs/common'; import { Observable } from 'rxjs'; import { InfToken } from 'src/share/interfaces/InfToken'; import { validationNullORUndefined } from 'src/share/utils/validation.util'; import { TokenService } from 'src/token/token.service'; import { User } from 'src/user/entities/user.entity'; import { UserService } from 'src/user/user.service'; @Injectable() export class AuthGuard implements CanActivate { constructor( private readonly userService: UserService, private readonly tokenService: TokenService, ) {} public async canActivate(context: ExecutionContext): Promise<boolean> { const req = context.switchToHttp().getRequest(); const token: string = req.headers['authorization']; if (validationNullORUndefined(token)) { throw new BadRequestException('토큰이 없습니다'); } const payload: InfToken = await this.tokenService.verifyToken(token); const user: User | undefined = await this.userService.getUserByUserID( payload.userEmail, ); if (validationNullORUndefined(user)) { throw new UnauthorizedException('유저가 존재하지 않습니다.'); } req.user = user; return true; } }
from kivy.app import App from kivy.uix.label import Label from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.button import Button from kivy.uix.checkbox import CheckBox from kivy.uix.image import Image from kivy.uix.textinput import TextInput from kivy.graphics import Color, Rectangle, Ellipse from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.scrollview import ScrollView from kivy.uix.anchorlayout import AnchorLayout class WelcomeScreen(Screen): def __init__(self, **kwargs): super().__init__(**kwargs) welcome_label = Label( text="Welcome to the App", font_size=24, pos_hint={'center_x': 0.5, 'center_y': 0.7} ) start_button = Button( text="Start", size_hint=(None, None), size=(100, 50), pos_hint={'center_x': 0.5, 'y': 0.1}, on_press=self.on_start_button_click ) self.add_widget(welcome_label) self.add_widget(start_button) def on_start_button_click(self, instance): self.manager.current = "image1" class Image1Screen(Screen): def __init__(self, **kwargs): super().__init__(**kwargs) image1 = Image(source="image_1.jpg") self.add_widget(image1) next_button = Button( text="Next", size_hint=(None, None), size=(100, 50), pos_hint={'center_x': 0.90, 'y': 0.05}, on_press=self.on_next_button_click ) self.add_widget(next_button) def on_next_button_click(self, instance): self.manager.current = "image2" class Image2Screen(Screen): def __init__(self, **kwargs): super().__init__(**kwargs) image2 = Image(source="image_2.jpg") self.add_widget(image2) next_button = Button( text="Next", size_hint=(None, None), size=(100, 50), pos_hint={'center_x': 0.90, 'y': 0.05}, on_press=self.on_next_button_click ) back_button = Button( text="Back", size_hint=(None, None), size=(100, 50), pos_hint={'center_x': 0.10, 'y': 0.05}, on_press=self.on_back_button_click ) self.add_widget(next_button) self.add_widget(back_button) def on_next_button_click(self, instance): self.manager.current = "input_screen" def on_back_button_click(self, instance): self.manager.current = "image1" class InputScreen(Screen): def __init__(self, **kwargs): super().__init__(**kwargs) layout = GridLayout(cols=2, row_force_default=True, row_default_height=60, spacing=10, padding=30) # Use a Label for the description self.weight_input = TextInput(text='Enter Weight here (lb)') self.height_input = TextInput(text='Enter Height here (cm)') submit = Button( text="Submit", size_hint=(None, None), size=(200, 50), pos_hint={'center_x': 0.5, 'y': 0.3}, on_press=self.submit ) layout.add_widget(self.weight_input) layout.add_widget(self.height_input) self.add_widget(submit) # Use a Label for the description more_text_label = Label( text='Explain how your day is going:', font_size=24, pos_hint={'center_x': 0.5, 'center_y': 0.7} ) # Use a TextInput for entering the description self.more_text_input = TextInput( hint_text='Type here', size_hint=(None, None), size=(600, 200), pos_hint={'center_x': 0.5, 'center_y': 0.5} ) next_button = Button( text="Next", size_hint=(None, None), size=(100, 50), pos_hint={'center_x': 0.90, 'y': 0.05}, on_press=self.on_next_button_click ) back_button = Button( text="Back", size_hint=(None, None), size=(100, 50), pos_hint={'center_x': 0.10, 'y': 0.05}, on_press=self.on_back_button_click ) self.add_widget(back_button) self.add_widget(next_button) self.add_widget(more_text_label) self.add_widget(self.more_text_input) self.add_widget(layout) def on_back_button_click(self, instance): self.manager.current = "image2" def on_next_button_click(self, instance): self.manager.current = "exit_window" def submit(self, instance): weight = self.weight_input.text height = self.height_input.text more_text = self.more_text_input.text # Here, you can process the submitted weight and height as needed # For example, you can print them to the console print(f"Weight: {weight}, Height: {height}, More Text: {more_text}") class ExitWindow(Screen): def __init__(self, **kwargs): super().__init__(**kwargs) exit_label = Label( text="Do you want to exit the app?", font_size=24, pos_hint={'center_x': 0.5, 'center_y': 0.7} ) exit_button = Button( text="Exit", size_hint=(None, None), size=(100, 50), pos_hint={'center_x': 0.90, 'y': 0.05}, on_press=self.on_exit_button_click ) back_button = Button( text="Back", size_hint=(None, None), size=(100, 50), pos_hint={'center_x': 0.10, 'y': 0.05}, on_press=self.on_back_button_click ) self.add_widget(exit_label) self.add_widget(exit_button) self.add_widget(back_button) def on_exit_button_click(self, instance): App.get_running_app().stop() def on_back_button_click(self, instance): self.manager.current = "input_screen" class MyApp(App): def build(self): screen_manager = ScreenManager() welcome_screen = WelcomeScreen(name="welcome") image1_screen = Image1Screen(name="image1") image2_screen = Image2Screen(name="image2") input_screen = InputScreen(name="input_screen") exit_window = ExitWindow(name="exit_window") screen_manager.add_widget(welcome_screen) screen_manager.add_widget(image1_screen) screen_manager.add_widget(image2_screen) screen_manager.add_widget(input_screen) screen_manager.add_widget(exit_window) return screen_manager if __name__ == '__main__': MyApp().run()
package com.lym.springboot.springbootaop.advice; import com.lym.springboot.springbootaop.annotation.LoggerManage; import org.apache.commons.lang.builder.ToStringBuilder; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * @Author: in liuyuanming * @Description: * @Date:Created in 2019/6/5 16:06 */ @Aspect @Component public class LoggerAdvice { private Logger logger = LoggerFactory.getLogger(this.getClass()); ThreadLocal<Long> startTime = new ThreadLocal<>(); @Before("within(com.lym.springboot.springbootaop.*) && @annotation(loggerManage)") public void addBeforeLogger(JoinPoint joinPoint, LoggerManage loggerManage) { logger.info("执行--" + loggerManage.description() + "--开始"); startTime.set(System.currentTimeMillis()); logger.info(joinPoint.getSignature().toString()); logger.info(parseParames(joinPoint.getArgs())); } @AfterReturning("within(com.lym.springboot.springbootaop.*) && @annotation(loggerManage)") public void addAfterReturningLogger(JoinPoint joinPoint, LoggerManage loggerManage) { logger.info("执行--" + loggerManage.description() + "--结束"); logger.info("执行时间--" + (System.currentTimeMillis() - startTime.get())); } @AfterThrowing(pointcut = "within(com.lym.springboot.springbootaop.*) && @annotation(loggerManage)", throwing = "ex") public void addAfterThrowingLogger(JoinPoint joinPoint, LoggerManage loggerManage, Exception ex) { logger.error("执行--" + loggerManage.description() + "--异常", ex); } private String parseParames(Object[] parames) { if (null == parames || parames.length <= 0) { return ""; } StringBuffer param = new StringBuffer("参数--"); for (Object obj : parames) { String va = ToStringBuilder.reflectionToString(obj); param.append(va).append(" "); } return param.toString(); } }
from django.urls import path, include from media_manager.views import media as media_view from media_manager.views import notifications as notification_view from media_manager.views import source as source_view media_urlpatterns = [ path('', media_view.list_media, name="list_media"), path('videos/', media_view.list_media_video, name="list_media_video"), path('audios/', media_view.list_media_audio, name="list_media_audio"), path('videos/<int:video_id>', media_view.show_media_video, name="show_media_video"), path('audios/<int:audio_id>', media_view.show_media_audio, name="show_media_audio"), # render media form and store new media path('create_media/', media_view.create_and_store_media, name="create_media"), path('<int:media_id>/', media_view.show_media, name="show_media"), # edit and update media path('<int:media_id>/edit', media_view.edit_and_update_media, name="edit_media"), path('<int:media_id>/delete', media_view.delete_media, name="delete_media"), ] notification_urlpatterns = [ path('', notification_view.notifications_main, name="main_notification"), path('<notification_type>', notification_view.list_notifications, name="list_notification"), path('<notification_type>/<int:notification_id>/', notification_view.show_notification, name="show_notification"), path('<notification_type>/<int:notification_id>/reject', notification_view.reject_notification, name="reject_notification"), path('<notification_type>/<int:notification_id>/accept', notification_view.accept_notification, name="accept_notification"), path('<notification_type>/<int:notification_id>/delete', notification_view.delete_notification, name="delete_notification"), ] source_media_urlpatterns = [ path('', source_view.list_source, name="list_source"), # render source media form and store new source media path('create_source/', source_view.create_and_store_source, name="create_source"), path('<int:source_id>/', source_view.show_source, name="show_source"), # edit and update source media path('<int:source_id>/edit', source_view.edit_and_update_source, name="edit_source"), path('<int:source_id>/delete', source_view.delete_source, name="delete_source"), ] urlpatterns = [ path('medias/', include(media_urlpatterns)), path('notifications/', include(notification_urlpatterns)), path('sources/', include(source_media_urlpatterns)) ]
package com.itheima.stock.controller; import com.itheima.stock.pojo.domain.*; import com.itheima.stock.service.StockService; import com.itheima.stock.vo.resp.PageResult; import com.itheima.stock.vo.resp.R; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.util.List; import java.util.Map; /** * ClassName: StockController * Package: com.itheima.stock.controller * Description: * * @Author R * @Create 2024/2/3 11:47 * @Version 1.0 */ @RestController @RequestMapping("/api/quot") public class StockController { @Autowired private StockService stockService; @GetMapping("/index/all") public R<List<InnerMarketDomain>> getInnerMarketInfo() { return stockService.getInnerMarketInfo(); } @GetMapping("/sector/all") public R<List<StockBlockDomain>> sectorAll() { return stockService.sectorAllLimit(); } /** * 分页查询股票最新数据,并按照涨幅排序查询 * @param page * @param pageSize * @return */ @GetMapping("/stock/all") public R<PageResult> getStockPageInfo(@RequestParam(name = "page",required = false,defaultValue = "1") Integer page, @RequestParam(name = "pageSize",required = false,defaultValue = "20") Integer pageSize){ return stockService.getStockPageInfo(page,pageSize); } @GetMapping("/stock/increase") public R<List<StockUpdownDomain>> getStockPageInfos() { return stockService.getStockPageInfos(); } /** * 统计最新交易日下股票每分钟涨跌停的数量 * @return */ @GetMapping("/stock/updown/count") public R<Map> getStockUpdownCount() { return stockService.getStockUpdownCount(); } /** * 将指定页的股票数据导出到excel表下 * @param response * @param page 当前页 * @param pageSize 每页大小 */ @GetMapping("/stock/export") public void stockExport(HttpServletResponse response, Integer page, Integer pageSize) { stockService.stockExport(response,page,pageSize); } @GetMapping("/stock/tradeAmt") public R<Map> stockTradeVol4InnerMarket() { return stockService.stockTradeVol4InnerMarket(); } /** * 查询当前时间下股票的涨跌幅度区间统计功能 * 如果当前日期不在有效时间内,则以最近的一个股票交易时间作为查询点 * @return */ @GetMapping("/stock/updown") public R<Map> getStockUpDown(){ return stockService.stockUpDownScopeCount(); } /** * 功能描述:查询单个个股的分时行情数据,也就是统计指定股票T日每分钟的交易数据; * 如果当前日期不在有效时间内,则以最近的一个股票交易时间作为查询时间点 * @param code 股票编码 * @return */ @GetMapping("/stock/screen/time-sharing") public R<List<Stock4MinuteDomain>> stockScreenTimeSharing(String code){ return stockService.stockScreenTimeSharing(code); } /** * 单个个股日K 数据查询 ,可以根据时间区间查询数日的K线数据 * @param stockCode 股票编码 */ @RequestMapping("/stock/screen/dkline") public R<List<Stock4EvrDayDomain>> getDayKLinData(@RequestParam("code") String stockCode){ return stockService.stockCreenDkLine(stockCode); } }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AuthModule } from '@auth0/auth0-angular'; import { environment as env } from '../environments/environment'; import { LoginPageComponent } from './login-page/login-page.component'; import { ProfilePageComponent } from './profile-page/profile-page.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import {MatCardModule} from '@angular/material/card'; import {MatToolbarModule} from '@angular/material/toolbar'; import {MatGridListModule} from '@angular/material/grid-list'; import {MatFormFieldModule} from '@angular/material/form-field'; import {MatIconModule} from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule } from '@angular/forms' import { ReactiveFormsModule} from '@angular/forms'; import { ProfileRegisterPageComponent } from './profile-register-page/profile-register-page.component'; import { UserPageComponent } from './user-page/user-page.component' import {MatBadgeModule} from '@angular/material/badge'; import {MatButtonModule} from '@angular/material/button'; import {MatListModule} from '@angular/material/list'; @NgModule({ declarations: [ AppComponent, LoginPageComponent, ProfilePageComponent, ProfileRegisterPageComponent, UserPageComponent ], imports: [ BrowserModule, AppRoutingModule, AuthModule.forRoot({ ...env.auth, }), BrowserAnimationsModule, MatCardModule, MatToolbarModule, MatGridListModule, MatIconModule, MatFormFieldModule, MatInputModule, MatBadgeModule, MatButtonModule, MatListModule, HttpClientModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>clustery.js 高兴能的滚动列表</title> <script src="./lib/vue.js" charset="utf-8"></script> <style> * { padding: 0; margin: 0; } html, body, #app { height: 100%; } li { list-style: none; } .wrapper { height: 600px; overflow: auto; } .list-item { border-bottom: 2px solid #ddd; } </style> </head> <body> <div class="app" id="app"> <div ref="wrapper" class="wrapper"> <cluster :query="query"> <template scope="props"> <div v-for="item in props.list" class="list-item" :key="item.id"> <h4>ID {{ item.id }}</h4> <div class="content" v-html="item.content"></div> </div> </template> </cluster> </div> </div> <script src="./lib/thenable.js"></script> <script> var arr = []; var texts = ['大吉大利', '合家安康', '生意兴隆', '一帆风顺'], heights = [30, 50, 60, 70], colors = ['#ebeeff', '#ebf7ff', '#9be8d7']; function queryData(start, end) { var arr = []; for (var i = start, max = end; i < max; i++) { arr.push({ id: i + 1, content: '<p style="height: '+ heights[Math.floor(Math.random() * heights.length)] +'px; background: '+ colors[Math.floor(Math.random() * colors.length)] +';">'+ texts[Math.floor(Math.random() * texts.length)] +'</p>' }); } return arr; } arr = queryData(0, 30); function getOffset(el) { var offset = { x: el.offsetLeft, y: el.offsetTop }; var pt = el.offsetParent; while (pt) { offset.x += (pt.offsetLeft || 0); offset.y += (pt.offsetTop || 0); pt = pt.offsetParent; } return offset; } // @require ./lib/thenable.js var Cluster = Vue.extend({ props: { query: { type: Function, required: true }, perPage: { type: Number, default: 15 }, params: { type: Object, default: function() { return {}; } } }, template: ` <div class="wrapper" ref="scroll"> <h1>滚动测试</h1> <div class="inner" ref="content"> <div :style="{height: topHeight + 'px'}" ref="top"></div> <slot :list="list" :params="params"></slot> <div :style="{height: bottomHeight + 'px'}" ref="bottom"></div> </div> </div> `, data: function() { return { index: 0, list: [], isLoading: false, // 预先加载距离 preload: 10, topHeight: 0, bottomHeight: 0 }; }, watch: { }, created: function() { var ctx = this; ctx.all = []; // 存储高度 ctx.heightMap = {}; // ctx.minShowPage = 2; ctx.maxShowPage = 3; ctx.topBorder = 0; ctx.bottomBorder = 0; }, mounted: function() { var ctx = this; ctx.loadData(0); ctx.scrollEvn = function(e) { if (ctx.isLoading) { return; } var scrollTop = ctx.$refs.scroll.scrollTop; if (scrollTop > ctx.bottomBorder) { ctx.isLoading = true; ctx.index++; ctx.loadData(this.index) .then(function() { ctx._setTopHeightByIndex(ctx._getItemGroup(ctx.list[0])); ctx.isLoading = false; console.log('生成新的数据'); }); } }.bind(ctx); ctx._setTopHeightByIndex = function(count) { var height = 0; for (var i = 0; i < count; i++) { height += (ctx.heightMap[i] || 0) } ctx.topHeight = height; }; ctx.$refs.scroll.addEventListener('scroll', ctx.scrollEvn); }, methods: { updateDistance: function() { var ctx = this; var distance = getOffset(ctx.$refs.scroll).y + ctx.$refs.scroll.clientHeight; ctx.bottomBorder = getOffset(ctx.$refs.bottom).y - distance - ctx.preload; if (ctx.list.length <= 0) { return; } var children = ctx.$refs.content.children; var preGroup = ctx._getItemGroup(ctx.list[0]); var preY = getOffset(children[1]).y; for (var i = 0, max = ctx.list.length; i < max; i++) { var item = ctx.list[i], group = ctx._getItemGroup(item); if (group != preGroup) { var y = getOffset(children[i]).y; ctx.heightMap[preGroup] = y - preY; preGroup = group; preY = y; } else if (i == max - 1 && group == preGroup) { var y = getOffset(ctx.$refs.bottom).y; ctx.heightMap[group] = y - preY; } } console.log(ctx.bottomBorder); }, loadData: function(index) { var ctx = this; // 加载 index - 1, index, index + 1 的数据 return new Thenable(function(resolve) { ctx.loadByIndex(index - 1) .then(function() { return ctx.loadByIndex(index + 1); }) .then(function() { return ctx.loadByIndex(index); }) .then(function() { ctx.$nextTick(function() { ctx.updateDistance(); resolve(); }); }); }); }, loadByIndex: function(index) { var ctx = this, prevs = ctx.prevs, nexts = ctx.nexts; var all = ctx.all; var current = ctx.index; var half = Math.floor(ctx.maxShowPage / 2); // TODO 这个判定不怎么准确.... if (index > half) { if (all.length >= (index + half) * ctx.perPage) { // 重新分配数据 ctx.list = all.slice((index - half) * ctx.perPage, (index + half) * ctx.perPage); } else { // 请求缺失的数据 var thenables = []; for (var i = index - half; i <= index + half; i++) { thenables.push(ctx.queryPage(i)); } return Thenable.all(thenables).then(function() { return ctx.loadByIndex(index); }); } } else { if (all.length >= (half + 1) * ctx.perPage) { ctx.list = all.slice(0, (half + 1) * ctx.perPage); } else { var thenables = []; for (var i = 0; i < (half + 1); i++) { thenables.push(ctx.queryPage(i)); } return Thenable.all(thenables).then(function() { return ctx.loadByIndex(index); }); } } return Thenable.resolve(); }, queryData: function(start, end) { var ctx = this; if (ctx.all.length >= end) { return Thenable.resolve(); } return new Thenable(function(resolve) { ctx.query({ start: start, end: end}, function(arr) { var list = arr.slice(0); ctx._setItemsInOrder(list, start, end); ctx._setItemsInGroup(list, Math.floor(start / ctx.perPage)); list.unshift(start, end); ctx.all.splice.apply(ctx.all, list); resolve(); }); }); }, queryPage: function(index) { return this.queryData(index * this.perPage, (index + 1) * this.perPage); }, _setItemsInOrder: function(list, start, end) { for (var i = 0, max = Math.min(list.length, end - start); i < max; i++) { if (list[i]) { list[i]['_s_index_'] = i + start; } } }, _getItemOrder: function(item) { return item['_s_index_']; }, _setItemsInGroup: function(list, groupIndex) { for (var i = 0, max = list.length; i < max; i++) { if (list[i]) { list[i]['_s_group_'] = groupIndex; } } }, _getItemGroup: function(item, height) { return item['_s_group_']; } } }); Vue.component('cluster', Cluster); var app = new Vue({ el: '#app', data: { start: 0, end: arr.length, topHeight: 0, bottomHeight: 0, list: arr }, mounted: function() { // var ctx = this; // ctx.clustery = new Clustery({ // scrollElem: this.$refs.wrapper, // contentElem: this.$refs.inner, // rows_in_block: 20, // blocks_in_cluster: 4, // callbacks: { // shouldUpdate: function(_data) { // ctx.setRenderData(_data); // } // } // }); // var ctx = this; // setTimeout(function() { // ctx.list.push.apply(ctx.list, queryData(ctx.list.length, ctx.list.length + 30)); // }, 1000); }, destroyed: function() { if(this.clustery) { this.clustery.destroy(); } }, methods: { setRenderData: function(_data) { if (typeof _data === 'object') { this.topHeight = _data.top_offset; this.bottomHeight = _data.bottom_offset; this.start = _data.start; this.end = _data.end; } else { this.bottomHeight = _data; } }, query: function(data, insert) { var start = data.start, end = data.end; setTimeout(function() { insert(queryData(start, end)); }, 2000); } }, computed: { sliceList: function() { return this.list.slice(this.start, this.end); } } }); </script> </body> </html>
import SwiftUI struct IngredientDropdown: View { @Binding var selectedIngredient: Ingredient? var dropDownList: [Ingredient] init(selectedIngredient: Binding<Ingredient?> = .constant(nil), dropDownList: [Ingredient]) { self._selectedIngredient = selectedIngredient self.dropDownList = dropDownList } var body: some View { Menu { Button("None") { self.selectedIngredient = nil } ForEach(dropDownList, id: \.self) { ingredient in Button { self.selectedIngredient = ingredient } label: { HStack { Text(ingredient.name) if selectedIngredient == ingredient { Image(systemName: "checkmark") } } } } } label: { HStack{ if let selectedIngredient = selectedIngredient { Text(selectedIngredient.name) .foregroundColor(.primary) } else { Text("Select an ingredient") .foregroundColor(.secondary) } Spacer() Image(systemName: "chevron.down") .foregroundColor(Color.gray) .font(Font.system(size: 20, weight: .medium)) } .padding(5) } } } struct IngredientDropdown_Previews: PreviewProvider { static var previews: some View { IngredientDropdown(dropDownList: MockData.ingredientList) } }
package Guvi_Task_9; import java.util.Scanner; public class StringReversal { // Method to reverse a given string public static String reverseString(String inputString) { // Create a StringBuilder to build the reversed string StringBuilder reversed = new StringBuilder(); // Iterate over the inputString from end to start for (int i = inputString.length() - 1; i >= 0; i--) { // Append each character to the StringBuilder in reverse order reversed.append(inputString.charAt(i)); } // Convert StringBuilder back to String and return the reversed string return reversed.toString(); } public static void main(String[] args) { // Create a Scanner object to read input from the console Scanner scanner = new Scanner(System.in); // Prompt the user to enter a string System.out.print("Enter a string: "); // Read the input string entered by the user String userInput = scanner.nextLine(); // Call the reverseString method to reverse the input string String reversedString = reverseString(userInput); // Output the reversed string to the console System.out.println("Reversed string: " + reversedString); // Close the scanner scanner.close(); } }
<template> <div :class="[ isRanking ? 'col-xl-4 col-md-6 col-11' : 'col-xl-3 col-lg-4 col-md-6 col-11' ]" class="mx-auto d-block"> <div class="spot_card"> <RouterLink :to="`/spots/${spot.id}`"> <div class="spot_card_img"> <img :src="`${spot.first_spot_image}`" alt="釣りスポットの画像"> </div> </RouterLink> <div class="spot_card_content"> <div class="card_spot_name"> {{ spot.spot_name }} </div> <div class="card_detail"> <div class="card_item"> <FavoriteButton :spot="spot" @favorite="$emit('favorite')" @unfavorite="$emit('unfavorite')" /> </div> <div class="card_item"> <i class="fa fa-comment mr-1"></i>{{ spot.count_spot_comments }} </div> <div class="card_item"> <i class="fas fa-clock mr-1"></i>{{ spot.created_at | moment }} </div> <RouterLink :to="`/users/${spot.user_id}`"> <img :src="`${spot.user.user_image}`" alt="釣りスポット投稿者の画像"> </RouterLink> </div> <div class="spot_address" v-if="spot.address && spot.address.length > 0"> {{ spot.address }} </div> <!-- <p>{{ spot.explanation }}</p> --> </div> </div> </div> </template> <script> import FavoriteButton from '../FavoriteButton.vue' import moment from 'moment'; export default { components: { FavoriteButton, }, props: { spot: { type: Object, required: true }, isRanking: { type: Boolean, required: true }, }, filters: { moment: function (date) { return moment(date).format('MM/DD'); } }, } </script>
import pandas as pd import altair as alt titanic = pd.read_csv("../../data/titanic.csv") titanic.dropna(subset = ["Embarked"], inplace=True) print(titanic.info()) # shneidermans mantra # overview first, zoom and filter, details on demand # titanic: age against fare price # bar of embarkation selection = alt.selection_point(fields=["Pclass"], bind="legend") age_fare = alt.Chart(titanic).mark_circle().encode( alt.X("Age:Q"), alt.Y("Fare:Q").scale(domain=[0,600]), color=alt.Color("Pclass:N"), opacity=alt.condition(selection, alt.value(0.8), alt.value(0.2)), tooltip=[ alt.Tooltip("Name", title="Passenger Name"), alt.Tooltip("Age", title="Passenger Age"), alt.Tooltip("Fare", title="Paid"), ] ).add_params( selection ).properties(width=1000).interactive() embark_highlight = alt.Chart(titanic).mark_bar().encode( alt.Y("Survived:N", title=None, axis=alt.Axis(labelAngle=0)), alt.X("count()").scale(domain=[0,800]), color="Pclass:N", opacity=alt.condition(selection, alt.value(0.8), alt.value(0.2)), row="Embarked" ).add_params(selection).properties(width=400) embark_filter = alt.Chart(titanic).mark_bar().encode( alt.Y("Survived:N", title=None, axis=alt.Axis(labelAngle=0)), alt.X("count()").scale(domain=[0,800]), color="Pclass:N", row="Embarked" ).transform_filter(selection).properties(width=400) alt.vconcat(age_fare, embark_filter).save("titanic_interactive.html")
import Card from "./Finance/Card"; import Atm from "./Atm/Atm"; import BalanceReceipt from "./Atm/Receipts/BalanceReceipt"; import WithdrawalReceipt from "./Atm/Receipts/WithdrawalReceipt"; import ItemEnum from "./Enums/ItemEnum"; import History from "./History"; export default class User { private cash = 0; private card: Card; private pin: number; private readonly history = new History(); public constructor( private readonly fullName: string, ) { } public setCard(card: Card) { this.card = card; } public getCard(): Card { return this.card; } public setPin(pin: number) { this.pin = pin; } public getCash(): number { return this.cash; } public addCash(amount: number) { this.cash += amount; } public getHistory(): History { return this.history; } public getBalance(atm: Atm): BalanceReceipt { this.history.clear(); this.history.addAtmText(atm); atm.insertCard(this.card); this.history.addAtmText(atm); atm.typeNumber(this.pin) this.history.addAtmText(atm); atm.selectItem(ItemEnum.FIRST) // Balance this.history.addAtmText(atm); atm.selectItem(ItemEnum.FIRST) // Print receipt this.history.addAtmText(atm); const receipt = atm.collectReceipt().pop() this.returnCard( atm.cancel() .collectCard() ); this.history.addAtmText(atm); return receipt; } public withdrawCash(atm: Atm, amount: number): WithdrawalReceipt { this.history.clear(); this.history.addAtmText(atm); atm.insertCard(this.card) this.history.addAtmText(atm); atm.typeNumber(this.pin) this.history.addAtmText(atm); atm.selectItem(ItemEnum.SECOND) // Withdraw this.history.addAtmText(atm); atm.typeNumber(amount) // Enter mount this.addCash(atm.collectCash()) this.history.addAtmText(atm); atm.selectItem(ItemEnum.FIRST) // Print receipt const receipt = atm.collectReceipt().pop(); this.returnCard( atm .cancel() .collectCard() ); this.history.addAtmText(atm); return receipt; } public transferMoney(atm: Atm, cardId: number, amount: number) { this.history.clear(); this.history.addAtmText(atm); atm.insertCard(this.card) this.history.addAtmText(atm); atm.typeNumber(this.pin) this.history.addAtmText(atm); atm.selectItem(ItemEnum.THIRD) // Transfer this.history.addAtmText(atm); atm.typeNumber(cardId) // Enter card ID atm.typeNumber(amount) // Enter amount this.history.addAtmText(atm); atm.selectItem(ItemEnum.FIRST) // Print receipt this.history.addAtmText(atm); const receipt = atm.collectReceipt().pop(); this.returnCard( atm .cancel() .collectCard() ); this.history.addAtmText(atm); return receipt; } private returnCard(card: Card) { this.card = card; } }
"""Module for handling stellar intensity data from stellar_intens files.""" from pathlib import Path import astropy.io.fits as pyfits import numpy as np from astropy.units import Quantity from lod_unit import lod from scipy.interpolate import CubicSpline from .util import convert_to_lod class StellarIntens: """Class to handle and interpolate stellar intensity data. This class loads stellar intensity data and corresponding stellar diameters, providing an interpolation interface to get the stellar intensity map for a given stellar diameter. Attributes: ln_interp (CubicSpline): A spline interpolator that operates on the natural logarithm of the stellar intensities to ensure that interpolated values are non-negative. Args: yip_dir (Path): Path to the directory containing the yield input package (YIP). stellar_intens_file (str): Filename of the FITS file containing the stellar intensity data. stellar_diam_file (str): Filename of the FITS file containing the stellar diameters. """ def __init__( self, yip_dir: Path, stellar_intens_file: str, stellar_diam_file: str, ) -> None: """Initializes StellarIntens class by loading data and creating the interpolant. Stellar intensity data and stellar diameters are loaded from FITS files, and a natural logarithm-based cubic spline interpolator is set up to facilitate interpolation. Args: yip_dir (Path): The directory where the stellar intensity and diameter FITS files are located. stellar_intens_file (str): The filename of the FITS file containing unitless arrays of stellar intensities. stellar_diam_file (str): The filename of the FITS file containing arrays of stellar diameters in lambda/D units. """ # Load on-axis stellar intensity PSF data psfs = pyfits.getdata(Path(yip_dir, stellar_intens_file), 0) # Load the stellar angular diameters in units of lambda/D diams = pyfits.getdata(Path(yip_dir, stellar_diam_file), 0) * lod # Interpolate stellar data in logarithmic space to ensure non-negative # interpolated values self.ln_interp = CubicSpline(diams, np.log(psfs)) def __call__(self, stellar_diam: Quantity, lam=None, D=None): """Returns the stellar intensity map at a specified stellar diameter. Stellar intensity is interpolated based on a specified diameter using the previously configured cubic spline interpolator. The interpolation considers the logarithm of the intensity to ensure that all computed values are positive. Args: stellar_diam (Quantity): The desired stellar diameter for which to retrieve the intensity map, in units of lambda/D. lam (Quantity, optional): Wavelength of observation, required if stellar_diam is in angular units. D (Quantity, optional): Diameter of the telescope, required if stellar_diam is in angular units. Returns: NDArray: An interpolated 2D map of the stellar intensity at the given stellar diameter. """ # Set up conversion from angular units to lambda/D if stellar_diam.unit != lod: stellar_diam = convert_to_lod(stellar_diam, lam=lam, D=D) # Return the exponentiated result of the interpolation to get the # actual intensity map return np.exp(self.ln_interp(stellar_diam))
package com.mycom.joytrip.user.service; import java.util.List; import javax.servlet.http.HttpSession; import org.mindrot.jbcrypt.BCrypt; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mycom.joytrip.board.dao.BoardDao; import com.mycom.joytrip.common.exception.CustomInsertException; import com.mycom.joytrip.mytrip.dao.MytripDao; import com.mycom.joytrip.review.dao.ReviewDao; import com.mycom.joytrip.star.dao.StarDao; import com.mycom.joytrip.user.dao.UserDao; import com.mycom.joytrip.user.dto.UserDto; import com.mycom.joytrip.user.dto.UserResultDto; @Service public class UserServiceImpl implements UserService{ @Autowired UserDao userDao; @Autowired ReviewDao reviewDao; @Autowired BoardDao boardDao; @Autowired StarDao starDao; @Override public UserDto userLogin(UserDto userDto) { UserDto user = userDao.userLogin(userDto.getUserEmail()); System.out.println(user); System.out.println(userDto.getUserPassword() + user.getUserPassword()); if (user != null && BCrypt.checkpw(userDto.getUserPassword(), user.getUserPassword())) { System.out.println("여기안옴>?"); user.setUserPassword(null); return user; } return null; } @Override public List<UserDto> list() { return userDao.list(); } @Override public UserDto detail(int studentId) { UserDto dto = userDao.detail(studentId); int visitedCount = reviewDao.myVisitedCount(studentId); int reviewCount = reviewDao.myReviewCount(studentId); int boardCount = boardDao.myBoardCount(studentId); int starCount = starDao.myStarCount(studentId); dto.setBoardCount(boardCount); dto.setReviewCount(reviewCount); dto.setVisitedCount(visitedCount); dto.setStarCount(starCount); return dto; } @Override public int insert(UserDto dto) { UserDto detailUser = userDao.detailByEmail(dto.getUserEmail()); // 기존에 존재하는 회원이라면 if (detailUser != null) { throw new CustomInsertException("이미 존재하는 이메일입니다!"); } String hashpw = BCrypt.hashpw(dto.getUserPassword(), BCrypt.gensalt()); dto.setUserPassword(hashpw); System.out.println("hashpw" + hashpw); return userDao.insert(dto); } @Override public int update(UserDto dto) { return userDao.update(dto); } @Override public int delete(int studentId) { return userDao.delete(studentId); } @Override public UserDto detailByEmail(String userEmail) { return userDao.detailByEmail(userEmail); } @Override public int updateUserPw(UserDto userDto, HttpSession session) { UserDto user = (UserDto) session.getAttribute("userDto"); String hashpw = BCrypt.hashpw(userDto.getUserPassword(), BCrypt.gensalt()); if (user != null) { if (BCrypt.checkpw(userDto.getUserPassword(), userDao.detail(user.getUserId()).getUserPassword())) { throw new CustomInsertException("기존과 동일한 비밀번호입니다!"); } userDto.setUserPassword(hashpw); userDto.setUserId(user.getUserId()); return userDao.updateUserPwAfterLogin(userDto); } userDto.setUserPassword(hashpw); return userDao.updateUserPwBeforeLogin(userDto); } @Override public UserResultDto searchByNicknameOrEmail(String searchWord) { UserResultDto userResultDto = new UserResultDto(); List<UserDto> list = userDao.searchByNicknameOrEmail(searchWord); userResultDto.setList(list); return userResultDto; } }
const express = require("express"); require("dotenv").config(); const cors = require("cors"); const axios = require("axios"); const app = express(); app.use(cors()); app.get("/", async (req, res) => { try { const response = await axios.get( `https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=fr-FRA&page=${req.query.page}&sort_by=popularity.desc&with_genres=${req.query.genre_ids}&api_key=${process.env.API_KEY}` ); console.log(response.data); console.log(response.data.id); console.log(req.query.data); console.log(req.query.id); const limitedResults = response.data.results.slice(0, 4); response.data.results = limitedResults; return res.status(200).json(response.data); } catch (error) { return res.status(500).json({ message: error.message }); } }); app.get("/movies/:id", async (req, res) => { try { const response = await axios.get( `https://api.themoviedb.org/3/movie/${req.params.id}?api_key=${process.env.API_KEY}&language=fr-FRA` ); console.log(response.data); console.log(req.query.id); return res.status(200).json(response.data); } catch (error) { return res.status(500).json({ message: error.message }); } }); app.get("/movie/:id/watchon", async (req, res) => { try { const response = await axios.get( `https://api.themoviedb.org/3/movie/${req.params.id}/watch/providers?api_key=${process.env.API_KEY}&language=fr-FRA` ); console.log("provider >>>>", req.query.id); return res.status(200).json(response.data); } catch (error) { return res.status(500).json({ message: error.message }); } }); app.get("/movie/:id/trailer", async (req, res) => { try { const response = await axios.get( `https://api.themoviedb.org/3/movie/${req.params.id}/videos?api_key=${process.env.API_KEY}&language=fr-FRA` ); console.log("provider >>>>", req.query.id); return res.status(200).json(response.data); } catch (error) { return res.status(500).json({ message: error.message }); } }); app.get("/movies/:id/watch", async (req, res) => { try { const response = await axios.get( `https://api.themoviedb.org/3/movie/${req.params.id}?api_key=${process.env.API_KEY}&language=en-USA` ); console.log(response.data); console.log(req.query.id); return res.status(200).json(response.data); } catch (error) { return res.status(500).json({ message: error.message }); } }); app.get("/movies/:id/similar", async (req, res) => { try { const response = await axios.get( `https://api.themoviedb.org/3/movie/${req.params.id}/similar?api_key=${process.env.API_KEY}&language=fr-FRA` ); console.log(response.data); console.log(req.query.id); return res.status(200).json(response.data); } catch (error) { return res.status(500).json({ message: error.message }); } }); app.listen(process.env.PORT, () => { console.log("Server Starded"); });
# Event Planner A (Very) Simple CLI Event Planner written in Python ## Installation Installation is very simple you just have to download `event-planner.py` and have Python 3.x installed. ## Usage ```bash python3 event-planner.py ``` **NOTE:** `event-planner.py` creates a file called `.dates` where it stores dates set by the user, make sure there is no other file named `.dates` in the directory where `event-planner.py` is located. When run the program will return a prompt that looks like this, ``` Event Planner v[VERSION NUMBER] What do you want to do? (Enter 'help' for a list of commands) ``` From here you can enter seven (7) different commands: - `help` - Returns List of Commands - `exit` - Exits Program - `view` - Shows all Existing Events - `add` - Adds an Event - `edit` - Edits an Existing Event - `remove` - Removes an Existing Event - `delete all` - Removes all Existing Events **NOTE:** After Performing any Action or Getting an Error, `event-planner.py` recursively calls the `main()` function so the program effectively restarts and asks for a command once more. For example, if using the `view` command, ``` Event Planner v[VERSION NUMBER] What do you want to do? (Enter 'help' for a list of commands) view Events: [LIST OF EVENTS HERE] Event Planner v[VERSION NUMBER] What do you want to do? (Enter 'help' for a list of commands) ``` As you can see the program starts over from the beginning, the guide for the commands implies knowlege of this behaivor. ### Using the `help` command Using `help` is very simple, all you have to do is type `help` and press <kbd>enter</kbd> and then you will be presented with the complete list of commands like so, ``` Event Planner v[VERSION NUMBER] What do you want to do? (Enter 'help' for a list of commands) help view - View all events planned add - Add a new event edit - Edit an event remove - Remove an event help - View this list of commands delete all - Delete all events exit - Exit the program ``` ### Using the `exit` command Using `exit` is equally as simple as the `help` command, just type `exit` and press <kbd>enter</kbd> and then the program will be exited in the following manner, ``` Event Planner v[VERSION NUMBER] What do you want to do? (Enter 'help' for a list of commands) exit Exiting program... ``` ### Using the `view` command Using `view` requires you to type `view` and pressing <kbd>enter</kbd> and then you will be presented with a list of your existing events in an ordered list in the following manner, ``` Event Planner v[VERSION NUMBER] What do you want to do? (Enter 'help' for a list of commands) view Events: 1. [EVENT #1] 2. [EVENT #2] 3. [EVENT #3] ....... N. [EVENT #N] ``` ### Using the `add` command Using `add` requires you to multiple steps, firstly type `add` and press <kbd>enter</kbd>, then you will be met with the following question from the program, ``` Event Planner v[VERSION NUMBER] What do you want to do? (Enter 'help' for a list of commands) add What is the name of the event? (Max 128 characters) [NAME] ``` Then you enter the name of the event you want to add, the name is limited to 128 characters (bytes), if this limit is exceeded it will be truncated and only the first 128 characters will be used. After that you will be propmpted to add a date to your event which will appear in the following manner, ``` Event Planner v[VERSION NUMBER] What do you want to do? (Enter 'help' for a list of commands) add What is the name of the event? (Max 128 characters) [NAME] What is the date of the event? (MM-DD-YYYY HH:MM:SS AM/PM) [DATE] ``` The date of the event you provide _MUST_ be in the `MM-DD-YYYY HH:MM:SS AM/PM` format, otherwise the program will throw an error. After entering this the program will indicated that the event has been added successfully, ``` Event Planner v[VERSION NUMBER] What do you want to do? (Enter 'help' for a list of commands) add What is the name of the event? (Max 128 characters) [NAME] What is the date of the event? (MM-DD-YYYY HH:MM:SS AM/PM) [DATE] Event added! ``` ### Using the `edit` command Using the `edit` command also requires multiple steps, firstly you must type `edit` and then press <kbd>enter</kbd>, then the program will reply with the following, ``` ```
package application; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Scanner; import entities.Employee; public class Program { public static void main(String[] args) { Locale.setDefault(Locale.US); Scanner sc = new Scanner(System.in); List<Employee> list = new ArrayList<Employee>(); System.out.println("How many Employees will be registered? "); int n = sc.nextInt(); for (int i = 0; i < n; i++) { System.out.println(); System.out.println("Employee #" + (i + 1) + ":"); System.out.print("Id: "); Integer id = sc.nextInt(); while (hasId(list, id)) { System.out.println("Id: "); id = sc.nextInt(); } System.out.print("Name: "); sc.nextLine(); String name = sc.nextLine(); System.out.print("Salary: "); Double salary = sc.nextDouble(); Employee emp = new Employee(id, name, salary); list.add(emp); } System.out.print("Enter the employee id that will have salary increase: "); int idSalary = sc.nextInt(); /* * Sem Lambda Integer pos = position(list, idSalary); * * if (pos == null) { System.out.println("This id does not exist!"); } else { * System.out.println("Enter the percentage"); double percent = sc.nextDouble(); * list.get(pos).increaseSalary(percent); } */ /* Com Lambda */ Employee emp = list.stream().filter(x -> x.getId() == idSalary).findFirst().orElse(null); if (emp == null) { System.out.println("This id does not exist!"); } else { System.out.println("Enter the percentage"); double percent = sc.nextDouble(); emp.increaseSalary(percent); } System.out.println(); System.out.println("List of employees: "); for (Employee empl : list) { System.out.println(empl.toString()); } sc.close(); } public static Integer position(List<Employee> list, int id) { for (int i = 0; i < list.size(); i++) { if (list.get(i).getId() == id) { return i; } } return null; } static boolean hasId(List<Employee> list, int id) { Employee emp = list.stream().filter(x -> x.getId() == id).findFirst().orElse(null); return emp != null; } }
import { HttpAdapterHost, NestFactory } from '@nestjs/core'; import { ConfigService } from '@nestjs/config'; import { ValidationPipe, Logger } from '@nestjs/common'; import { AppModule } from './app.module'; import { PrismaClientExceptionFilter } from 'nestjs-prisma'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalPipes(new ValidationPipe()); app.setGlobalPrefix('/api/v1'); app.enableShutdownHooks(); const { httpAdapter } = app.get(HttpAdapterHost); app.useGlobalFilters(new PrismaClientExceptionFilter(httpAdapter)); const configService = app.get(ConfigService); if (configService.get<boolean>('CORS_ENABLED')) { app.enableCors({ allowedHeaders: ['Content-Type', 'Authorization'], origin: [ ...(JSON.parse(configService.get('ALLOWED_ORIGINS') ?? '[]') || []), ], }); } const port = configService.get('PORT'); await app.listen(port || 3000, async () => { const logger = new Logger('NestApplication'); const appUrl = await app.getUrl(); logger.verbose(`API is running on ${appUrl}/api/v1/`); }); } bootstrap();
package com.example.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class DemoApplication { private static final Logger log = LoggerFactory.getLogger(DemoApplication.class); public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public RestTemplate restTemplate(RestTemplateBuilder builder){ return builder.build(); } @Bean public CommandLineRunner run(RestTemplate restTemplate) throws Exception{ return args -> { Base base = restTemplate.getForObject( "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo", Base.class); log.info(base.toString()); }; } }
package me.zhengjie.modules.merchant.service; import cn.hutool.core.collection.CollUtil; import lombok.AllArgsConstructor; import me.zhengjie.modules.merchant.domain.Project; import me.zhengjie.modules.merchant.domain.ProjectSchedule; import me.zhengjie.modules.merchant.domain.vo.ScheduleCommand; import me.zhengjie.modules.merchant.enums.ProjectEnums; import me.zhengjie.modules.merchant.enums.ScheduleEnum; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @AllArgsConstructor public class ProjectUpdateService { private final ProjectService projectService; private final ProjectScheduleService projectScheduleService; @Transactional(rollbackFor = Exception.class) public void assign(ScheduleCommand command) { ProjectSchedule schedule = new ProjectSchedule() .setAssignUser(command.getAssignUser()) .setAssignUserId(command.getAssignUserId()) .setProjectId(command.getProjectId()) .setScheduleStatus(ScheduleEnum.TEAMLEADER) .setAmountPercent(command.getAmountPercent()) .setScheduleDesc("未开始") .setNickName(command.getNickName()); //查询该项目是否有被指派过项目经理,如果有则修改原有记录的指派状态 List<ProjectSchedule> schedules = projectScheduleService.lambdaQuery().eq(ProjectSchedule::getProjectId,command.getProjectId()) .eq(ProjectSchedule::getScheduleStatus,ScheduleEnum.TEAMLEADER).list(); if (CollUtil.isNotEmpty(schedules)){ schedules.forEach(x ->{ x.setAssignStatus(1); }); projectScheduleService.updateBatchById(schedules); } projectScheduleService.save(schedule); Project project = projectService.getById(command.getProjectId()); project.setProjectStatus(ProjectEnums.INPROGRESS.getValue()); projectService.updateById(project); } @Transactional(rollbackFor = Exception.class) public void finance(ScheduleCommand resources) { ProjectSchedule schedule = new ProjectSchedule() .setProjectId(resources.getProjectId()) .setScheduleStatus(ScheduleEnum.FINANCE) .setScheduleDesc("完成") .setAmountPercent(resources.getAmountPercent()) .setNickName(resources.getNickName()); projectScheduleService.save(schedule); Project project = projectService.getById(resources.getProjectId()); project.setAmountPercent(resources.getAmountPercent()); projectService.updateById(project); } @Transactional(rollbackFor = Exception.class) public void complete(ScheduleCommand resources) { Project project = projectService.getById(resources.getProjectId()); project.setProjectStatus(ProjectEnums.COMPLETION.getValue()); projectService.updateById(project); ProjectSchedule schedule = new ProjectSchedule() .setProjectId(resources.getProjectId()) .setScheduleStatus(ScheduleEnum.COMPLETION) .setScheduleDesc("完成") .setAmountPercent(project.getAmountPercent()) .setNickName(resources.getNickName()); projectScheduleService.save(schedule); } }
import React, { useState, useEffect, useRef, useMemo } from 'react'; import {Text, TouchableOpacity, StyleSheet, View, FlatList} from 'react-native'; import { windowHeight, windowWidth } from '../utils/Dimensions'; import Ionicons from 'react-native-vector-icons/Ionicons'; import MapView, { Marker, PROVIDER_GOOGLE } from "react-native-maps"; import { doc, getDoc, getDocs, collection, orderBy, query, where, collectionGroup } from "firebase/firestore"; import { db } from '../firebase/firebaseConfig'; import { mapStyle } from "../styles/mapStyle"; import * as Location from 'expo-location'; const MapScreen = ({ navigation }) => { const [region, setRegion] = useState({ latitude: 39.8283, longitude: -98.5795 , latitudeDelta: 30.0, longitudeDelta: 50.0, }); const [sellerData, setSellerData] = useState([]); const [errorMsg, setErrorMsg] = useState(null); const [userInteraction, setUserInteraction] = useState(false); const [myLocation, setMyLocation] = useState(null); const [locationIcon, setLocationIcon] = useState("location-outline"); const mapRef = useRef(null); const zoomToLocation = async () => { try { let { status } = await Location.requestForegroundPermissionsAsync(); if (status !== 'granted') { setErrorMsg('Permission to access location was denied'); return; } let location = await Location.getCurrentPositionAsync({}); const newRegion = { latitude: location.coords.latitude, longitude: location.coords.longitude, latitudeDelta: 0.0922, longitudeDelta: 0.0421, }; setMyLocation(newRegion); setRegion(newRegion); mapRef.current.animateToRegion(newRegion, 1000); } catch (error) { console.log('Error zooming to location: ', error); } }; let text = 'Waiting..'; if (errorMsg) { text = errorMsg; } const handleRegionChangeComplete = updatedRegion => { if (userInteraction) { setRegion(updatedRegion); //locationIcon(); } }; useEffect(() => { const fetchSellerData = async () => { try { const sellerSnapshot = await getDocs(collection(db, 'sellers')); const sellerData = sellerSnapshot.docs.map((doc) => { const seller = doc.data(); seller.id = doc.id; // Assign the document ID to the id property return seller; }); setSellerData(sellerData); } catch (error) { console.log('Error fetching locations: ', error); } }; fetchSellerData(); }, []); useEffect(() => { const fetchIcon = async () => { if (myLocation?.latitude === region?.latitude && myLocation?.longitude === region?.longitude) setLocationIcon('navigate'); else setLocationIcon('navigate-outline'); }; fetchIcon(); }, [region]); const handleMarkerPress = (pin) => { navigation.navigate('SellerPage', { sellerData: pin }); }; const renderMap = useMemo( () => ( <MapView provider={PROVIDER_GOOGLE} style={styles.map} ref={mapRef} initialRegion={region} onRegionChangeComplete={handleRegionChangeComplete} onTouchStart={() => setUserInteraction(true)} onTouchEnd={() => setUserInteraction(false)} customMapStyle={mapStyle} onPress={(event) => { const coordinate = event.nativeEvent.coordinate; const tappedMarker = sellerData.find( (seller) => seller.location.latitude === coordinate.latitude && seller.location.longitude === coordinate.longitude ); if (tappedMarker) { handleMarkerPress(tappedMarker); } }} > {sellerData.map((seller, index) => ( <Marker key={index} coordinate={{ latitude: seller.location.latitude, longitude: seller.location.longitude, }} style={{ flex: 1, alignContent: 'flex-end' }} > <Text style={{ fontSize: 16, color: '#000', textAlign: 'center', width: 100}}>{seller.name}</Text> <Ionicons name="location" color="#B97309" size={40} style={{ alignSelf: 'center' }} /> </Marker> ))} </MapView> ), [sellerData] ); return ( <View style={styles.container}> {renderMap} <TouchableOpacity onPress={zoomToLocation} style={{ backgroundColor: '#fff', borderRadius: 10, margin: 20, marginTop: 50 }} > <Ionicons name={locationIcon} color="#B97309" size={30} style={{ padding: 5, alignSelf: 'center' }} /> </TouchableOpacity> </View> ); }; export default MapScreen; const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, flex: 1, //the container will fill the whole screen. flexDirection: "row", justifyContent: "flex-end", alignItems: "right", }, map: { ...StyleSheet.absoluteFillObject, }, });
import type { Address, Client } from "viem" import { type AccountsParameters, accounts } from "../../actions/stackup/accounts" import { type SponsorUserOperationParameters, type SponsorUserOperationReturnType, sponsorUserOperation } from "../../actions/stackup/sponsorUserOperation" import type { EntryPoint } from "../../types/entrypoint" import { type StackupPaymasterClient } from "../stackup" export type StackupPaymasterClientActions<entryPoint extends EntryPoint> = { /** * Returns paymasterAndData & updated gas parameters required to sponsor a userOperation. * * https://docs.stackup.sh/docs/paymaster-api-rpc-methods#pm_sponsoruseroperation * * @param args {@link SponsorUserOperationParameters} UserOperation you want to sponsor & entryPoint. * @returns paymasterAndData & updated gas parameters, see {@link SponsorUserOperationReturnType} * * @example * import { createClient } from "viem" * import { stackupPaymasterActions } from "permissionless/actions/stackup" * * const bundlerClient = createClient({ * chain: goerli, * transport: http("https://api.stackup.sh/v1/paymaster/YOUR_API_KEY_HERE") * }).extend(stackupPaymasterActions) * * await bundlerClient.sponsorUserOperation(bundlerClient, { * userOperation: userOperationWithDummySignature, * entryPoint: entryPoint * }}) * */ sponsorUserOperation: ( args: Omit<SponsorUserOperationParameters<entryPoint>, "entrypoint"> ) => Promise<SponsorUserOperationReturnType<entryPoint>> /** * Returns all the Paymaster addresses associated with an EntryPoint that’s owned by this service. * * https://docs.stackup.sh/docs/paymaster-api-rpc-methods#pm_accounts * * @param args {@link AccountsParameters} entryPoint for which you want to get list of supported paymasters. * @returns paymaster addresses * * @example * import { createClient } from "viem" * import { stackupPaymasterActions } from "permissionless/actions/stackup" * * const bundlerClient = createClient({ * chain: goerli, * transport: http("https://api.stackup.sh/v1/paymaster/YOUR_API_KEY_HERE") * }).extend(stackupPaymasterActions) * * await bundlerClient.accounts(bundlerClient, { * entryPoint: entryPoint * }}) * */ accounts: (args: AccountsParameters<entryPoint>) => Promise<Address[]> } export const stackupPaymasterActions = <entryPoint extends EntryPoint>(entryPointAddress: entryPoint) => (client: Client): StackupPaymasterClientActions<entryPoint> => ({ sponsorUserOperation: async (args) => sponsorUserOperation(client as StackupPaymasterClient<entryPoint>, { ...args, entryPoint: entryPointAddress }), accounts: async (args) => accounts(client as StackupPaymasterClient<entryPoint>, args) })
import React, { useState, useRef, useEffect } from 'react'; // JS // const input = document.getElementById('myText'); // const inputValue = input.value // React // value, onChange //*** dynamic object keys => IMPORTANT ([name]: value) const ControlledInputs = () => { // const [firstName, setFirstName] = useState(''); // const [email, setEmail] = useState(''); const [people, setPeople] = useState([]); const [person, setPerson] = useState({firstName:'', email: ''}); const refContainer = useRef(null); useEffect(() => { refContainer.current.focus(); }); const handleSubmit = (e) => { e.preventDefault(); let newPerSon = {}; if (person.firstName && person.email) { newPerSon = { id: new Date().getTime().toString(), ...person } setPeople([...people, newPerSon]); setPerson({firstName:'', email: ''}); } else { console.log('please input values'); } }; const handleChange = (e) => { const name = e.target.name; const value = e.target.value; setPerson ({...person, [name]: value}); }; return ( <> <article> <form className='form'> <div className='form-control'> <label htmlFor='firstName'>Name : </label> <input type='text' id='firstName' name='firstName' value={person.firstName} onChange={handleChange} ref={refContainer} /> </div> <div className='form-control'> <label htmlFor='email'>Email : </label> <input type='email' id='email' name='email' value={person.email} onChange={handleChange} /> </div> <button type='submit' onClick={handleSubmit}>add person</button> </form> {people.map((person, index) => { const { id, firstName, email } = person; return ( <div className='item' key={id}> <h4>{firstName}</h4> <p>{email}</p> </div> ); })} </article> </> ); }; export default ControlledInputs;
package geometrica; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<formaGeometrica> formas = new ArrayList<>(); formas.add(new Retangulo(5, 10)); formas.add(new Circulo(4)); formas.add(new Triangulo(6, 8)); formas.add(new Quadrado(7)); formas.add(new Losango(6, 7)); // Define um formato com duas casas decimais DecimalFormat df = new DecimalFormat("#.##"); for (formaGeometrica forma : formas) { double area = forma.calcularArea(); String nome = forma.getNome(); // Formata a área com o formato definido String areaFormatada = df.format(area); System.out.println("Área da forma " + nome + ": " + areaFormatada); } } }
package com.grofers.Entity; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Entity @Data @NoArgsConstructor @AllArgsConstructor public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long productId; @NotBlank(message = "Name is mandatory") private String name; @NotNull(message = "Supplier ID is mandatory") @ManyToOne @JoinColumn(name = "supplierId", insertable = false, updatable = false) private Supplier supplier; @NotNull(message = "Category ID is mandatory") @ManyToOne @JoinColumn(name = "categoryId", insertable = false, updatable = false) private Category category; @NotNull(message = "Price is mandatory") @Min(value = 0, message = "Price must be positive") private Double price; }
<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\AuthController; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider and all of them will | be assigned to the "api" middleware group. Make something great! | */ Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); }); //Route::get('auth/google', [AuthController::class, 'redirectToGoogle'])->middleware('web'); //Route::get('auth/google/callback', [AuthController::class, 'handleGoogleCallback']); Route::post('auth/google', [AuthController::class, 'handleGoogleCallback']); Route::post('/signup', [AuthController::class, 'register']); Route::post('/signin', [AuthController::class, 'login']); Route::post('send-forget-mail', [AuthController::class, 'sendForgetMail']); Route::post('verify-otp', [AuthController::class, 'verifyOTP']); Route::post('update-password', [AuthController::class, 'updatePassword']); Route::post('/check_mail', [App\Http\Controllers\AuthController::class, 'checkMail']); Route::post('/test-pdf', [App\Http\Controllers\ManagePDFController::class, 'testConvert']); Route::post('/fetch_request', [App\Http\Controllers\RequestController::class, 'fetchRequest']); Route::post('/approver_fetch_request', [App\Http\Controllers\RequestController::class, 'approverFetchRequest']); Route::post('/approve_request', [App\Http\Controllers\RequestController::class, 'approveRequest']); Route::post('/reject_request', [App\Http\Controllers\RequestController::class, 'rejectRequest']); Route::post('/answer_request', [App\Http\Controllers\RequestController::class, 'answerRequest']); Route::post('/send_otp', [App\Http\Controllers\RequestController::class, 'sendOTP']); Route::post('/verify_otp', [App\Http\Controllers\RequestController::class, 'verifyOTP']); Route::get('/test', [App\Http\Controllers\RequestController::class, 'testLaravel']); Route::get('/otp_sms', [App\Http\Controllers\RequestController::class, 'sendSMSOTP']); //Route::post('/add_request_log', [App\Http\Controllers\RequestController::class, 'addRequestLog']); Route::post('/verify_user_otp', [App\Http\Controllers\AuthController::class, 'otpVerification']); Route::post('/resend_user_otp', [App\Http\Controllers\AuthController::class, 'resendOtp']); //stripe testing Route::post('confirm_payment', [App\Http\Controllers\SubscriptionController::class, 'confirmPayment']); Route::get('get_payment', [App\Http\Controllers\SubscriptionController::class, 'retreivePayment']); Route::get('get_payment_2', [App\Http\Controllers\SubscriptionController::class, 'getPayment']); Route::get('complete_payment', [App\Http\Controllers\SubscriptionController::class, 'completePayment']); Route::post('create_payment_intent_2', [App\Http\Controllers\SubscriptionController::class, 'createPaymentIntent']); Route::post('testjson', [App\Http\Controllers\SubscriptionController::class, 'testJson']); Route::get('attach_payment', [App\Http\Controllers\SubscriptionController::class, 'attachPaymentMethod']); //ending stripe testing Route::middleware('auth:api')->group(function () { //profile management Route::get('/profile_data', [App\Http\Controllers\ProfileManagementController::class, 'profileData']); Route::post('/update_profile_data', [App\Http\Controllers\ProfileManagementController::class, 'updateProfileData']); Route::post('change-password', [AuthController::class, 'changePassword']); Route::post('change-profile-img', [App\Http\Controllers\ProfileManagementController::class, 'changeProfileImg']); Route::post('change-logo-img', [App\Http\Controllers\ProfileManagementController::class, 'changeLogoImg']); Route::get('logout', [AuthController::class, 'logout']); Route::get('/pdf_images/{imageName}', [App\Http\Controllers\ImageController::class, 'show']); Route::prefix('user')->middleware(['role:2'])->group(function () { //CONTACTS Module Route::resource('/contacts', App\Http\Controllers\ContactController::class); Route::post('/bulk_import_contacts', [App\Http\Controllers\ContactController::class, 'bulkImport']); Route::post('/bulk_delete_contacts', [App\Http\Controllers\ContactController::class, 'bulkDelete']); Route::post('/update_contact_phones', [App\Http\Controllers\ContactController::class, 'updatePhones']); Route::post('/convert-to-png', [App\Http\Controllers\ManagePDFController::class, 'convertToPng']); Route::post('/add_image_element', [App\Http\Controllers\ManagePDFController::class, 'addImageElement']); //User Request Module Route::resource('/user_request', App\Http\Controllers\RequestController::class); Route::get('/inbox', [App\Http\Controllers\RequestController::class, 'inbox']); Route::get('/get_file/{id}', [App\Http\Controllers\RequestController::class, 'getFileBase']); Route::post('/create_request_draft', [App\Http\Controllers\RequestController::class, 'createDraft']); Route::post('/store_request_fields', [App\Http\Controllers\RequestController::class, 'fieldsDraft']); Route::post('/change_request_status', [App\Http\Controllers\RequestController::class, 'changeRequestStatus']); //request trash module Route::post('/add_to_trash', [App\Http\Controllers\RequestController::class, 'addToTrash']); Route::post('/remove_from_trash', [App\Http\Controllers\RequestController::class, 'removeFromTrash']); Route::get('/all_trash_items', [App\Http\Controllers\RequestController::class, 'allTrashItems']); //ending req trash module //request bookmark module Route::post('/add_to_bookmarks', [App\Http\Controllers\RequestController::class, 'addToBookmarks']); Route::post('/remove_from_bookmarks', [App\Http\Controllers\RequestController::class, 'removeFromBookmarks']); Route::get('/all_bookmarked_items', [App\Http\Controllers\RequestController::class, 'allBookmarkedItems']); //ending req bookmark module //reminder Route::post('/send_reminder', [App\Http\Controllers\RequestController::class, 'sendReminder']); //ending reminder //subscription api's Route::resource('/subscription', App\Http\Controllers\SubscriptionController::class); Route::post('/cancel_subscription', [App\Http\Controllers\SubscriptionController::class, 'cancelSubscription']); Route::post('charge_payment', [App\Http\Controllers\SubscriptionController::class, 'charge']); Route::post('create_payment_intent', [App\Http\Controllers\SubscriptionController::class, 'createPaymentIntent']); //ending subscription api's Route::resource('/transaction', App\Http\Controllers\TransactionController::class); Route::get('get_billing_info', [App\Http\Controllers\BillingInfoController::class, 'index']); Route::post('update_billing_info', [App\Http\Controllers\BillingInfoController::class, 'update']); Route::resource('/payment_method', App\Http\Controllers\PaymentMethodController::class); //global settings Route::post('/use_company', [App\Http\Controllers\GlobalSettingController::class, 'useCompany']); //team members Route::resource('/team', App\Http\Controllers\TeamController::class); Route::post('/join_team', [App\Http\Controllers\TeamController::class, 'joinTeam']); Route::get('/join_requests', [App\Http\Controllers\TeamController::class, 'joinRequests']); Route::post('/leave_team', [App\Http\Controllers\TeamController::class, 'leaveTeam']); Route::post('/reject_team', [App\Http\Controllers\TeamController::class, 'rejectTeam']); //user global setting Route::resource('/user_global_setting', App\Http\Controllers\UserGlobalSettingController::class); //support email //Route::post('/send_support_mail', [App\Http\Controllers\UserGlobalSettingController::class, 'supportMail']); Route::resource('/send_support_mail', App\Http\Controllers\SupportMailController::class); } ); //********************************** */ //******************************* */ Route::prefix('admin')->middleware(['role:1'])->group(function () { Route::resource('/admin_user_request', App\Http\Controllers\RequestController::class); Route::resource('/plan', App\Http\Controllers\PlanController::class); Route::resource('/user_management', App\Http\Controllers\UserManagementController::class); Route::post('/change_plan', [App\Http\Controllers\UserManagementController::class, 'changePlan']); Route::resource('/tickets', App\Http\Controllers\SupportMailController::class); Route::post('/change_ticket_status', [App\Http\Controllers\SupportMailController::class, 'changeTicketStatus']); Route::get('/admin_dashboard', [App\Http\Controllers\DashboardController::class, 'stat']); } ); });
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; const routes: Routes = [ { path: 'welcome', loadChildren: () => import('./welcome').then((i) => i.WelcomeModule), }, { path: 'not-found', loadChildren: () => import('./not-found').then((i) => i.NotFoundModule), }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class StaticRoutingModule {}
const { request, response } = require('express'); const bcryptjs = require('bcryptjs'); const Empresa = require('../models/empresa'); const { generarJWT } = require('../helpers/generar-jwt'); const login = async( req = request, res = response ) => { const { correo, password } = req.body; try { //Verificar si el correo existe const empresa = await Empresa.findOne( { correo } ); if ( !empresa ) { return res.status(404).json({ msg: 'Correo de la persona no existe en la base de datos 404' }); } //Si el usuario esta activo (usuario.estado === false) if ( empresa.estado === false ) { return res.status(400).json({ msg: 'La cuenta de la persona esta inactiva' }); } //Verificar la password el usuario //comporeSync, encripta ambas passwords y las compara const validarPassword = bcryptjs.compareSync( password, empresa.password ); if ( !validarPassword ) { return res.status(400).json({ msg: 'La password es incorrecta' }); } //Generar JWT const token = await generarJWT( empresa.id ); res.json({ msg: 'Login Auth Funciona!', correo, password, token }); } catch (error) { console.log(error); res.status(500).json({ msg: 'Hable con el admin' }) } } module.exports = { login }
import React, { Component } from 'react'; class ForceUpdateExample extends Component { constructor(props) { super(props); // state 정의 this.loading = true; this.formData = 'no data'; this.handleData = this.handleData.bind(this); setTimeout(this.handleData, 4000); } handleData() { const data = 'new data'; // state 변경 this.loading = false; this.formData = data + this.formData; // 강제로 화면을 새로고침한다. this.forceUpdate(); } render() { return ( <div> <span>로딩중: {String(this.loading)}</span> <span>결과: {this.formData}</span> </div> ); } } export default ForceUpdateExample;
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Requests\PostStoreRequest; use App\Http\Requests\PostUpdateRequest; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Storage; use App\Post; use App\Category; use App\Tag; class PostController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { $posts = Post::orderBy('id', 'DESC') ->where('user_id', auth()->user()->id) ->paginate(); return view('admin.posts.index', compact('posts')); } public function create() { $categories = Category::orderBy('name', 'ASC')->pluck('name', 'id'); $tags = Tag::orderBy('name', 'ASC')->get(); return view('admin.posts.create', compact('categories', 'tags')); } public function store(PostStoreRequest $request) { $post = Post::create($request->all()); $this->authorize('pass', $post); if($request->file('image')){ $path = Storage::disk('public')->put('image', $request->file('image')); $post->fill(['file' => asset($path)])->save(); } $post->tags()->attach($request->get('tags')); return redirect()->route('posts.edit', $post->id)->with('info', 'Entrada creada con éxito'); } public function show($id) { $post = Post::find($id); $this->authorize('pass', $post); return view('admin.posts.show', compact('post')); } public function edit($id) { $categories = Category::orderBy('name', 'ASC')->pluck('name', 'id'); $tags = Tag::orderBy('name', 'ASC')->get(); $post = Post::find($id); $this->authorize('pass', $post); return view('admin.posts.edit', compact('post', 'categories', 'tags')); } public function update(PostUpdateRequest $request, $id) { $post = Post::find($id); $this->authorize('pass', $post); $post->fill($request->all())->save(); if($request->file('image')){ $path = Storage::disk('public')->put('image', $request->file('image')); $post->fill(['file' => asset($path)])->save(); } $post->tags()->sync($request->get('tags')); return redirect()->route('posts.edit', $post->id)->with('info', 'Entrada actualizada con éxito'); } public function destroy($id) { $post = Post::find($id)->delete(); $this->authorize('pass', $post); return back()->with('info', 'Eliminado correctamente'); } }
<!DOCTYPE html> <script type="importmap"> { "imports": { "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.prod.js" } } </script> <div id="app" class="mx-auto dark"> <div class="flex items-center mt-4 px-8 py-4 overflow-x-auto whitespace-nowrap bg-white rounded-lg shadow-md dark:bg-gray-800" style="visibility: hidden;" :style="{ visibility: postsFilteredByTitle ? 'visible' : 'hidden' }"> <a href="/" class="text-gray-600 dark:text-gray-200" tabindex="2"> <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" viewBox="0 0 20 20" fill="currentColor"> <path d="M10.707 2.293a1 1 0 00-1.414 0l-7 7a1 1 0 001.414 1.414L4 10.414V17a1 1 0 001 1h2a1 1 0 001-1v-2a1 1 0 011-1h2a1 1 0 011 1v2a1 1 0 001 1h2a1 1 0 001-1v-6.586l.293.293a1 1 0 001.414-1.414l-7-7z" /> </svg> </a> <span class="mx-5 text-gray-500 dark:text-gray-300"> / </span> <a href="/page2.html" class="px-6 py-2 font-medium tracking-wide text-white capitalize transition-colors duration-300 transform bg-blue-600 rounded-lg hover:bg-blue-500 focus:outline-none focus:ring focus:ring-blue-300 focus:ring-opacity-80" tabindex="1" role="button"> Switch to Page 2 </a> <span class="mx-5 text-gray-500 dark:text-gray-300"> / </span> <a @click="filterPostsByTitleAscending = !filterPostsByTitleAscending" class="px-6 py-2 font-medium tracking-wide text-white capitalize transition-colors duration-300 transform bg-blue-600 rounded-lg hover:bg-blue-500 focus:outline-none focus:ring focus:ring-blue-300 focus:ring-opacity-80" tabindex="1" role="button"> Sort{{ filterPostsByTitleAscending === null ? '' : 'ed' }} by Title{{ filterPostsByTitleAscending === null ? '' : filterPostsByTitleAscending ? ' (ASC)' : ' (DESC)'}} </a> <span v-if="userIdFilter" class="mx-5 text-gray-500 dark:text-gray-300"> / </span> <a v-if="userIdFilter" @click="userIdFilter = null" class="px-6 py-2 font-medium tracking-wide text-white capitalize transition-colors duration-300 transform bg-blue-600 rounded-lg hover:bg-blue-500 focus:outline-none focus:ring focus:ring-blue-300 focus:ring-opacity-80" tabindex="1" role="button"> {{ getUserById(userIdFilter).name }} &times; </a> </div> <div v-for="post in postsFilteredByTitle" class="max-w-2xl mt-4 px-8 py-4 bg-white rounded-lg shadow-md dark:bg-gray-800" style="visibility: hidden;" :style="{ visibility: postsFilteredByTitle ? 'visible' : 'hidden' }"> <div class="mt-2"> <div class="text-xl font-bold text-gray-700 dark:text-white hover:text-gray-600 dark:hover:text-gray-200">{{ post.title }}</div> <p class="mt-2 text-gray-600 dark:text-gray-300">{{ post.body }}</p> </div> <div class="flex items-center justify-between mt-4"> <div class="flex items-center"> <img class="hidden object-cover w-10 h-10 mx-4 rounded-full sm:block" :src="getUserById(post.userId).thumbnailUrl" alt="avatar"> <a @click="userIdFilter = post.userId" class="font-bold text-blue-600 dark:text-blue-400 hover:underline" tabindex="3" role="link">{{ getUserById(post.userId).name }} &gt;</a> </div> </div> </div> </div> <script type="module"> import { computed, createApp, ref } from 'vue' import { useFetch } from './fetch.js' createApp({ setup() { const BASE_API_URL = 'https://jsonplaceholder.typicode.com' const userIdFilter = ref(null) const postsApiUrl = computed(() => userIdFilter.value ? `${BASE_API_URL}/users/${userIdFilter.value}/posts` : `${BASE_API_URL}/posts` ) const { data: posts } = useFetch(postsApiUrl) const { data: users } = useFetch(`${BASE_API_URL}/users`) const { data: photos } = useFetch(`${BASE_API_URL}/photos`) const filterPostsByTitleAscending = ref(null) const postsFilteredByTitle = computed(() => filterPostsByTitleAscending.value === null ? posts.value : (posts.value || []).sort((a, b) => a.title < b.title ? filterPostsByTitleAscending.value ? -1 : 1 : a.title > b.title ? filterPostsByTitleAscending.value ? 1 : -1 : 0) ) const usersWithPosts = computed(() => (users.value || []).filter(({ id }) => (posts.value || []).some(({ userId }) => userId === id) ) || [] ) const userPhotos = computed(() => (photos.value || []).filter(({ id: userId }) => usersWithPosts.value.some(({ id }) => id === userId)) ) function getUserById (userId) { return { ...usersWithPosts.value.find(({ id }) => id === userId), thumbnailUrl: userPhotos.value.find(({ id }) => id === userId)?.thumbnailUrl, } || {} } return { filterPostsByTitleAscending, getUserById, postsFilteredByTitle, userIdFilter, } }, }).mount('#app') </script> <style> * { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } html { width: 100%; height: 100%; display: flex; line-height: 1.5; -webkit-text-size-adjust: 100%; -moz-tab-size: 4; tab-size: 4; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; font-feature-settings: normal; font-variation-settings: normal; } body { height: min-content; overflow-x: hidden; align-items: center; flex: 1 1 0%; width: 100%; min-height: 100%; display: flex; margin: 0; line-height: inherit; } #app.mx-auto { margin-left: auto; margin-right: auto; } #app a { color: inherit; text-decoration: inherit; cursor: pointer; } #app [role=button], button { cursor: pointer; } #app [type=button], [type=reset], [type=submit], button { -webkit-appearance: button; appearance: button; background-color: transparent; background-image: none; } #app button, select { text-transform: none; } #app button, input, optgroup, select, textarea { font-family: inherit; font-size: 100%; font-weight: inherit; line-height: inherit; color: inherit; margin: 0; padding: 0; } #app blockquote, dd, dl, figure, h1, h2, h3, h4, h5, h6, hr, p, pre { margin: 0; } #app img, video { max-width: 100%; height: auto; } #app audio, canvas, embed, iframe, img, object, svg, video { display: block; } #app .bg-blue-600 { --tw-bg-opacity: 1; background-color: rgb(37 99 235 / var(--tw-bg-opacity)); } #app .bg-white { --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity)); } #app .capitalize { text-transform: capitalize; } #app .cursor-pointer { cursor: pointer; } #app .duration-300 { transition-duration: 300ms; } #app .flex { display: flex; } #app .font-bold { font-weight: 700; } #app .font-light { font-weight: 300; } #app .font-medium { font-weight: 500; } #app .h-5 { height: 1.25rem; } #app .h-10 { height: 2.5rem; } #app .hidden { display: none; } #app .hover\:underline:hover { -webkit-text-decoration-line: underline; text-decoration-line: underline; } #app :is(.dark .dark\:bg-gray-800) { --tw-bg-opacity: 1; background-color: rgb(31 41 55 / var(--tw-bg-opacity)); } #app :is(.dark .dark\:text-blue-400) { --tw-text-opacity: 1; color: rgb(96 165 250 / var(--tw-text-opacity)); } #app :is(.dark .dark\:text-gray-200) { --tw-text-opacity: 1; color: rgb(229 231 235 / var(--tw-text-opacity)); } #app :is(.dark .dark\:text-gray-300) { --tw-text-opacity: 1; color: rgb(209 213 219 / var(--tw-text-opacity)); } #app :is(.dark .dark\:text-gray-400) { --tw-text-opacity: 1; color: rgb(156 163 175 / var(--tw-text-opacity)); } #app :is(.dark .dark\:text-white) { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } #app .items-center { align-items: center; } #app .justify-between { justify-content: space-between; } #app .max-w-2xl { max-width: 42rem; } #app .mt-2 { margin-top: 0.5rem; } #app .mt-4 { margin-top: 1rem; } #app .mx-4 { margin-left: 1rem; margin-right: 1rem; } #app .mx-5 { margin-left: 1.25rem; margin-right: 1.25rem; } #app .object-cover { object-fit: cover; } #app .overflow-x-auto { overflow-x: auto; } #app .px-6 { padding-left: 1.5rem; padding-right: 1.5rem; } #app .px-8 { padding-left: 2rem; padding-right: 2rem; } #app .py-2 { padding-top: 0.5rem; padding-bottom: 0.5rem; } #app .py-4 { padding-top: 1rem; padding-bottom: 1rem; } #app .rounded-full { border-radius: 9999px; } #app .rounded-lg { border-radius: 0.5rem; } #app .shadow-md { box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } #app .text-blue-600 { --tw-text-opacity: 1; color: rgb(37 99 235 / var(--tw-text-opacity)); } #app .text-gray-500 { --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity)); } #app .text-gray-600 { --tw-text-opacity: 1; color: rgb(75 85 99 / var(--tw-text-opacity)); } #app .text-gray-700 { --tw-text-opacity: 1; color: rgb(55 65 81 / var(--tw-text-opacity)); } #app .text-white { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } #app .text-xl { font-size: 1.25rem; line-height: 1.75rem; } #app .tracking-wide { letter-spacing: 0.025em; } #app .transform { transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } #app .transition-colors { transition-property: color, background-color, border-color, fill, stroke, -webkit-text-decoration-color; transition-property: color, background-color, border-color, text-decoration-color, fill, stroke; transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, -webkit-text-decoration-color; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } #app .w-5 { width: 1.25rem; } #app .w-10 { width: 2.5rem; } #app .whitespace-nowrap { white-space: nowrap; } @media (min-width: 640px) { #app .sm\:block { display: block; } } </style>
from django import forms from django.core.exceptions import ValidationError from django.contrib.auth import password_validation, get_user_model, authenticate from django.contrib.auth.forms import UsernameField, ReadOnlyPasswordHashField from django.utils.translation import gettext_lazy as _ from django.utils.text import capfirst from .utils import generate_and_mail_link from .tokens import default_token_generator UserModel = get_user_model() generate_and_mail_password_reset_link = generate_and_mail_link class BaseUserCreationForm(forms.ModelForm): """ A form that creates a user, with not privileges, from the given username email and password. """ error_messages = { "password_mismatch": _("The two password fields did not match."), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput( attrs={ "autocomplete": "new-password", } ), help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput( attrs={"autocomplete": "new-password"}, ), strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = UserModel fields = ("email", "username", "first_name", "last_name") field_classes = {"username": UsernameField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # auto focus USERNAME_FIELD if self._meta.model.USERNAME_FIELD in self.fields: self.fields[self._meta.model.USERNAME_FIELD].widget.attrs[ "autofocus" ] = True def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise ValidationError( message=self.error_messages["password_mismatch"], code="password_mismatch", ) return password2 def _post_clean(self): super()._post_clean() # Validate the password after self.instance is updated with form data # by super() password = self.cleaned_data.get("password2") if password: try: password_validation.validate_password(password, self.instance) except ValidationError as error: self.add_error("password2", error) def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() if hasattr(self, "save_m2m"): self.save_m2m() return user class UserCreationForm(BaseUserCreationForm): def clean_username(self): """Reject usernames that differ only in case.""" username = self.cleaned_data.get("username") if ( username and self._meta.model.objects.filter(username__iexact=username).exists() ): self._update_errors( ValidationError( message={ "username": self.instance.unique_error_message( self._meta.model, ["username"] ) } ) ) else: return username def clean_email(self): """Reject email that differ only in case.""" email = self.cleaned_data.get("email") if email and self._meta.model.objects.filter(email__iexact=email).exists(): self._update_errors( ValidationError( message={ "email": self.instance.unique_error_message( self._meta.model, ["email"] ) } ) ) else: return email class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField( label=_("Password"), help_text=_( "Raw passwords are not stored, so there is no way to see this " "user's password, but you can change the password using " '<a href="{}">this form</a>.' ), ) class Meta: model = UserModel fields = "__all__" field_classes = {"username": UsernameField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) password = self.fields.get("password") if password: password.help_text = password.help_text.format( f"../../{self.instance.pk}/password/" ) user_permissions = self.fields.get("user_permissions") if user_permissions: user_permissions.queryset = user_permissions.queryset.select_related( "content_type" ) class AuthenticationForm(forms.Form): """ Base class for authenticating users. """ username = UsernameField( widget=forms.TextInput( attrs={ "autofocus": True, } ) ) password = forms.CharField( label=("Password"), strip=False, widget=forms.PasswordInput( attrs={"autocomplete": "current-password"}, ), ) error_messages = { "invalid_login": _( "Please enter a correct %(username)s and password. Note that both " "fields may be case-sensitive." ), "inactive": _("This account is inactive."), } def __init__(self, request=None, *args, **kwargs): """ The 'request' parameter is set for custom auth user by subclasses. The form data comes via the standard 'data' kwarg. """ self.request = request self.user_cache = None super().__init__(*args, **kwargs) # set the max length and label for the username field. self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD) username_max_length = self.username_field.max_length or 254 self.fields["username"].max_length = username_max_length self.fields["username"].widget.attrs["max_length"] = username_max_length if self.fields["username"].label is None: self.fields["username"].label = capfirst(self.username_field.verbose_name) def clean(self): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") if username is not None and password: self.user_cache = authenticate( self.request, username=username, password=password ) if self.user_cache is None: raise self.get_invalid_login_error() else: self.confirm_login_allowed(self.user_cache) return self.cleaned_data def confirm_login_allowed(self, user): """ Controls whether the given User may log in. This is a policy setting, independent of end-user authentication. This default behavior is to allow login by active users, and reject login by inactive users. If the given user cannot log in, this method should raise a ``ValidationError``. If the given user may log in, this method should return None. """ if not user.is_active: raise ValidationError( self.error_messages["inactive"], code="inactive", ) def get_user(self): return self.user_cache def get_invalid_login_error(self): return ValidationError( self.error_messages["invalid_login"], code="invalid_login", params={"username": self.username_field.verbose_name}, ) class PasswordResetForm(forms.Form): email = forms.EmailField( label=_("Email"), max_length=254, widget=forms.EmailInput(attrs={"autocomplete": "email"}), ) def save( self, domain_override=None, subject_template_name="registration/password_reset_subject.txt", email_template_name="registration/password_reset_email.html", use_https=False, token_generator=default_token_generator, from_email=None, request=None, html_email_template_name=None, extra_email_context=None, ): """ Generate a one-use only link for resetting password and send it to the user. """ email = self.cleaned_data["email"] generate_and_mail_password_reset_link( email, domain_override, subject_template_name, email_template_name, use_https, token_generator, from_email, request, html_email_template_name, extra_email_context, ) class SetPasswordForm(forms.Form): """ A form that lets a user set their password without entering the old password """ error_messages = { "password_mismatch": _("The two password fields didn’t match."), } new_password1 = forms.CharField( label=_("New Password"), widget=forms.PasswordInput(attrs={"autocomplete": "new_password"}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, widget=forms.PasswordInput(attrs={"autocomplete": "new_password"}), ) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_new_password2(self): password1 = self.cleaned_data["new_password1"] password2 = self.cleaned_data["new_password2"] if password1 and password2 and password1 != password2: raise ValidationError( self.error_messages["password_mismatch"], code="password_mismatch" ) password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user class PasswordChangeForm(SetPasswordForm): """ A form that lets a user change their password by entering their old password. """ error_messages = { **SetPasswordForm.error_messages, "password_incorrect": _( "Your old password was entered incorrectly. Please enter it again." ), } old_password = forms.CharField( label=_("Old password"), strip=False, widget=forms.PasswordInput( attrs={"autocomplete": "current-password", "autofocus": True} ), ) field_order = ["old_password", "new_password1", "new_password2"] def clean_old_password(self): """ Validate that the old_password field is correct. """ old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise ValidationError( self.error_messages["password_incorrect"], code="password_incorrect", ) return old_password
// imports import IApiResponse from '../../Interfaces/WAQI/IApiResponse'; import IWeatherData from '../../Interfaces/WAQI/IWeatherData'; import ApiResponseException from '../../../Utils/Exceptions/Model/ApiResponseException'; /** * ApiResponse class */ export default class ApiResponse implements IApiResponse { // #region Props /** * Holds the status as string */ status!: string; /** * Holds the data as IWeatherData */ data!: IWeatherData; // #endregion // #region Ctor constructor(status: string, data: IWeatherData) { this.setStatus(status); this.setData(data); } // #endregion // #region Meths /** * Sets the status * @param status {string} the status */ setStatus(status: string): void { if (status === undefined || status === null) { throw new ApiResponseException( 'WAQI - API Response Error', 'status is required', new Error('status is required'), status ); } this.status = status; } /** * Returns the status as string * @returns {string} status * @memberof ApiResponse * @method getStatus */ getStatus(): string { return this.status; } setData(data: IWeatherData): void { if (data === undefined || data === null) { throw new ApiResponseException( 'WAQI - API Response Error', 'data is required', new Error('data is required'), data ); } this.data = data; } /** * Returns the data as IWeatherData * @returns {IWeatherData} data * @memberof ApiResponse * @method getData */ getData(): IWeatherData { return this.data; } // #endregion }
package com.day27; import java.util.Arrays; import java.util.List; @SuppressWarnings("serial") class InvalidMonthException extends Exception{ public InvalidMonthException(String msg) { super(msg); } } class MonthCheck { List<String> monthList = Arrays.asList("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); public MonthCheck(String mon) throws InvalidMonthException { if(!monthList.contains(mon)) throw new InvalidMonthException("Invalid Month : Please provide a valid month"); else System.out.println("Valid Month : "+mon); } } public class CustomizedExceptionExample5 { public static void main(String[] args) { try { @SuppressWarnings("unused") MonthCheck obj = new MonthCheck("Dec"); } catch (InvalidMonthException e) { System.out.println(e.getMessage()); } } }
###### Chapter 14 Principal components and factor analysis #### # two related but distinct ways for exploring and simplifing complex multivariate # data are principal components and exploratory factor analysis # principal components analysis is a data-reduction technique that transforms a # a larger number of correlated variables into a much smaller set of # uncorrelated variables called principal components # For example, you might use PCA to transform 30 correlated (and possibly # redundant) environmental variables into 5 uncorrelated composite variables # that retain as much information from the original set of variables as # possible. # exploratory factor analysis (EFA) is a collection of methods designed to # uncover the latent structure in a given set of variables. It looks for a # smaller set of underlying or latent constructs that can explain the # relationships among the observe or manifest variables. # For example, the dataset Harman74.cor contains the correlations among 24 # psychological tests given to 145 seventh- and eighth-grade children. If # you apply EFA to this data, the results suggest that the 276 test # intercorrelations can be explained by the children’s abilities on 4 # underlying factors (verbal ability, processing speed, deduction, and # memory). #### # Principal components (PC1 and PC2) are linear combinations of the observed # variables (X1 to X5). The weights used to form the linear composites are # chosen to maximize the variance each principal component accounts for, # while keeping the components uncorrelated. # In contrast, factors (F1 and F2) are assumed to underlie or “cause” the # observed variables, rather than being linear combinations of them. # The errors (e1 to e5) represent the variance in the observed variables # unexplained by the factors. The circles indicate that the factors and # errors aren’t directly observable but are inferred from # the correlations among the variables. In this example, the curved arrow # between the factors indicates that they’re correlated. Correlated factors # are common, but not required, in the EFA model. #### # analysts used rules of thumb like “factor analysis requires 5–10 times as many # subjects as variables.” # Recent studies suggest that the required sample size depends on the number of # factors, the number of variables associated with each factor, and # how well the set of factors explains the variance in the variables # (Bandalos and BoehmKaufman, 2009). #### # The most common steps are as follows: # 1 Prepare the data. Both PCA and EFA derive their solutions from the # correlations among the observed variables. You can input either the raw # data matrix or the correlation matrix to the principal() and fa() # functions. If raw data is input, the correlation matrix is automatically # calculated. Be sure to screen the data for missing values before # proceeding. # 2 Select a factor model. Decide whether PCA (data reduction) or EFA # (uncovering latent structure) is a better fit for your research goals. # If you select an EFA approach, you’ll also need to choose a specific # factoring method (for example, maximum likelihood). # 3 Decide how many components/factors to extract. # 4 Extract the components/factors. # 5 Rotate the components/factors. # 6 Interpret the results. # 7 Compute component or factor scores #### # The goal of PCA is to replace a large number of correlated variables with a # smaller number of uncorrelated variables while capturing as much # information in the original variables as possible. # These derived variables, called principal components, are linear combinations # of the observed variables. Specifically, the first principal component # PC1 = a1X1 + a2X2 + ... + akXk is the weighted combination of the k # observed variables that accounts for the most variance in the original # set of variables. # The second principal component is the linear combination that accounts for # the most variance in the original variables, under the constraint that # it’s orthogonal (uncorrelated) to the first principal component. # Each subsequent component maximizes the variance accounted for, while at the # same time remaining uncorrelated with all previous components. # Theoretically, you can extract as many principal components as there are # variables. But from a practical viewpoint, you hope that you can # approximate the full set of variables with a much smaller set of # components. #### t <- USJudgeRatings sapply(t, class) # Because the goal is to simplify the data, you’ll approach this problem using # PCA. # Several criteria are available for deciding how many components to retain in a PCA. # They include # ■ Basing the number of components on prior experience and theory # ■ Selecting the number of components needed to account for some threshold # cumulative amount of variance in the variables (for example, 80%) # ■ Selecting the number of components to retain by examining the eigenvalues # of the k × k correlation matrix among the variables -- the most common # way. # Each component is associated with an eigenvalue of the correlation matrix. # The first PC is associated with the largest eigenvalue, the second PC # with the second-largest eigenvalue, and so on. # The Kaiser–Harris criterion suggests retaining components with eigenvalues # greater than 1. # Components with eigenvalues less than 1 explain less variance than contained # in a single variable. In the Cattell Scree test, the eigenvalues are # plotted against their component numbers. Such plots typically demonstrate # a bend or elbow, and the components above this sharp break are retained. # Finally, you can run simulations, extracting eigenvalues from random data # matrices of the same size as the original matrix. If an eigenvalue based # on real data is larger than the average corresponding eigenvalues # from a set of random data matrices, that component is retained. # The approach is called parallel analysis (see Hayton, Allen, and Scarpello, # 2004, for more details) require("psych") fa.parallel(t[, -1], fa = "pc", n.iter = 100, show.legend = FALSE, main = "scree plot with parellel analysis") abline(h = 1) # Assessing the number of principal components to retain for the USJudgeRatings # example. A scree plot (the line with x’s), eigenvalues greater than # 1 criteria (horizontal line), and parallel analysis with 100 simulations # (dashed line) suggest retaining a single component #### pc <- principal(t[, -1], nfactors = 1) pc # Here, you’re inputting the raw data without the CONT variable and specifying # that one unrotated component should be extracted. (Rotation is explained # in section 14.3.3.) Because PCA is performed on a correlation matrix, # the raw data is automatically converted to a correlation matrix before # the components are extracted. # The column labeled PC1 contains the component loadings, which are the # correlations of the observed variables with the principal component(s). # If you extracted more than one principal component, there would be # columns for PC2, PC3, and so on. # Component loadings are used to interpret the meaning of components. You can # see that each variable correlates highly with the first component (PC1). # It therefore appears to be a general evaluative dimension. # The column labeled h2 contains the component communalities—the amount of # variance in each variable explained by the components. # The u2 column contains the component uniquenesses—the amount of variance # not accounted for by the components (or 1 – h2). For example, 80% of # the variance in physical ability (PHYS) ratings is accounted for by # the first PC, and 20% isn’t. PHYS is the variable least well # represented by a one-component solution. # The row labeled SS Loadings contains the eigenvalues associated with the # components. The eigenvalues are the standardized variance associated # with a particular component (in this case, the value for the first # component is 10). Finally, the row labeled Proportion Var represents the # amount of variance accounted for by each component. # Here you see that the first principal component accounts for 92% of the # variance in the 11 variables. #### t2 <- Harman23.cor fa.parallel(t2$cov, n.obs = t2$n.obs, fa = "pc", n.iter = 100, show.legend = FALSE, se.bars = TRUE, main = "scree plot with parallel analysis") abline(h = 1) # Sharp breaks in the plot suggest the appropriate number of components or # factors to extract. # “Parallel" analyis is an alternative technique that compares the scree of # factors of the observed data with that of a random data matrix of the # same size as the original. This may be done for continuous, dichotomous, # or polytomous data using Pearson, tetrachoric or polychoric correlations. # This won’t always be the case, and you may need to extract different numbers # of components and select the solution that appears most useful. pc <- principal(t2$cov, nfactors = 2, rotate = "none") pc # you see that the first component accounts for 58% of the variance in the # physical measurements, whereas the second component accounts for 22%. # Together, the two components account for 81% of the variance. The two # components together account for 88% of the variance in the height # variable. # Components and factors are interpreted by examining their loadings. The first # component correlates positively with each physical measure and appears to # a general size factor. The second component contrasts the first four # variables (height, arm. span, forearm, and lower leg), with the second # four variables (weight, bitro diameter, chest girth, and chest width). # It therefore appears to be a length-versus-volume factor. # Conceptually, this isn’t an easy construct to work with. Whenever two or more # components have been extracted, you can rotate the solution to make it # more interpretable. #### # Rotations are a set of mathematical techniques for transforming the component # loading matrix into one that’s more interpretable. # They do this by “purifying” the components as much as possible. Rotation # methods differ with regard to whether the resulting components remain # uncorrelated (orthogonal rotation) or are allowed to correlate (oblique # rotation). # They also differ in their definition of purifying. The most popular # orthogonal rotation is the varimax rotation, which attempts to purify the # columns of the loading matrix, so that each component is defined by a # limited set of variables (that is, each column has a few large loadings # and many very small loadings). # Applying a varimax rotation to the body measurement data, you get the results # provided in the next listing. rc <- principal(t2$cov, nfactors = 2, rotate = "Varimax") rc pc # The column names change from PC to RC to denote rotated components. Looking at # the loadings in column RC1, you see that the first component is primarily # defined by the first four variables (length variables). The loadings in # the column RC2 indicate that the second component is primarily defined # by variables 5 through 8 (volume variables). # Note that the two components are still uncorrelated and that together, they # still explain the variables equally well. You can see that the rotated # solution explains the variables equally well because the variable # communalities haven’t changed. Additionally, the cumulative variance # accounted for by the two-component rotated solution (81%) hasn’t changed. # But the proportion of variance accounted for by each individual component has # changed (from 58% to 44% for component 1 and from 22% to 37% for component # 2). # This spreading out of the variance across components is common, and # technically you should now call them components rather than # principal components (because the variance-maximizing properties of # individual components haven’t been retained). # The ultimate goal is to replace a larger set of correlated variables with a # smaller set of derived variables. To do this, you need to obtain scores # for each observation on the components. #### pc <- principal(t[, -1], nfactors = 1, scores = TRUE) head(pc$scores) # The principal component scores are saved in the scores element of the object # returned by the principal() function when the option scores=TRUE. cor(t$CONT, pc$scores) # you could now get the correlation between the number # of contacts occurring between a lawyer and a judge and their evaluation # of the judge using #### # When the principal components analysis is based on a correlation matrix and # the raw data aren’t available, getting principal component scores for # each observation is clearly not possible. But you can get the coefficients # used to calculate the principal components. rc <- principal(t2$cov, nfactors = 2, rotate = "varimax") round(unclass(rc$weights), 2) # The component scores are obtained using the formulas # PC1 = 0.28*height + 0.30*arm.span + 0.30*forearm + 0.29*lower.leg - # 0.06*weight - 0.08*bitro.diameter - 0.10*chest.girth - # 0.04*chest.width # and # PC2 = -0.05*height - 0.08*arm.span - 0.09*forearm - 0.06*lower.leg + # 0.33*weight + 0.32*bitro.diameter + 0.34*chest.girth + # 0.27*chest.width # These equations assume that the physical measurements have been standardized # (mean = 0, sd = 1). Note that the weights for PC1 tend to be around 0.3 # or 0. The same is true for PC2. # As a practical matter, you could simplify your approach further by taking # the first composite variable as the mean of the standardized scores for # the first four variables. # Similarly, you could define the second composite variable as the mean of the # standardized scores for the second four variables. This is typically # what I’d do in practice. #### # If your goal is to look for latent underlying variables that explain your # observed variables, you can turn to factor analysis. # The goal of EFA is to explain the correlations among a set of observed # variables by uncovering a smaller set of more fundamental unobserved # variables underlying the data. These hypothetical, unobserved variables # are called factors. (Each factor is assumed to explain the variance # shared among two or more observed variables, so technically, they’re # called common factors.) # The model can be represented as Xi = a1F1 + a2F2 + ... + apFp + Ui # where Xi is the ith observed variable (i = 1…k) # Fj are the common factors (j = 1…p), and p < k. # Ui is the portion of variable Xi unique to that variable (not explained by # the common factors). # The ai can be thought of as the degree to which each factor contributes to # the composition of an observed variable. #### # you’ll apply EFA to the correlations among six psychological tests. One # hundred twelve individuals were given six tests, including a nonverbal # measure of general intelligence (general), a picture-completion test # (picture), a block design test (blocks), a maze test (maze), a reading # comprehension test (reading), and a vocabulary test (vocab). # Can you explain the participants’ scores on these tests with a smaller # number of underlying or latent psychological constructs? covariance <- ability.cov$cov correlation <- cov2cor(covariance) # Because you’re looking for hypothetical constructs that explain the data, # you’ll use an EFA approach. As in PCA, the next task is to decide how # many factors to extract. fa.parallel(correlation, n.obs = 112, fa = "both", n.iter = 100, main = "scree plots with parallel analysis") # When in doubt, it’s usually a better idea to overfactor than to underfactor. # Overfactoring tends to lead to less distortion of the “true” solution. # For EFA, the Kaiser–Harris criterion is number of eigenvalues above 0, rather # than 1. (Most people don’t realize this, so it’s a good way to win bets # at parties.) In the present case the Kaiser–Harris criteria # also suggest two factors. #### # Unlike PCA, there are many methods of extracting common factors. They include # maximum likelihood (ml), iterated principal axis (pa), weighted least # square (wls), generalized weighted least squares (gls), and minimum # residual (minres). # Statisticians tend to prefer the maximum likelihood approach because of its # well-defined statistical model. # Sometimes, this approach fails to converge, in which case the iterated # principal axis option often works well. fa <- fa(correlation, nfactors = 2, rotate = "none", fm = "pa") fa ra <- fa(correlation, nfactors = 2, rotate = "varimax", fm = "pa") ra # Looking at the factor loadings, the factors are certainly easier to # interpret. Reading and vocabulary load on the first factor; and picture # completion, block design, and mazes load on the second factor. The general # nonverbal intelligence measure loads on both factors. This may indicate # a verbal intelligence factor and a nonverbal intelligence factor. ra.promax <- fa(correlation, nfactors = 2, rotate = "promax", fm = "pa") ra.promax # By using an orthogonal rotation, you artificially force the two # factors to be uncorrelated. What would you find if you allowed the two # factors to correlate? You can try an oblique rotation such as promax. #### # In an orthogonal solution, attention focuses on the factor structure matrix # (the correlations of the variables with the factors). # In an oblique solution, there are three matrices to consider: the factor # structure matrix, the factor pattern matrix, and the factor # intercorrelation matrix. # The factor pattern matrix is a matrix of standardized regression coefficients. # They give the weights for predicting the variables from the factors. # The factor intercorrelation matrix gives the correlations among the factors. # the values in the PA1 and PA2 columns constitute the factor pattern matrix. # They’re standardized regression coefficients rather than correlations. # Examination of the columns of this matrix is still used to name the factors # (although there’s some controversy here). Again, you’d find a verbal and # nonverbal factor. # The factor intercorrelation matrix indicates that the correlation between the # two factors is 0.57. This is a hefty correlation. If the factor # intercorrelations had been low, you might have gone back to an orthogonal # solution to keep things simple. # The factor structure matrix (or factor loading matrix) isn’t provided. # But you can easily calculate it using the formula F = P*Phi, where F is # the factor loading fsm <- function(oblique) { if (class(oblique)[2] == "fa" & is.null(oblique$Phi)) { warning("Object doesn't look like oblique EFA") } else { p <- unclass(oblique$loading) F <- p %*% oblique$Phi colnames(F) <- c("PA1", "PA2") return(F) } } fsm2 <- fsm(ra.promax) # Now you can review the correlations between the variables and # the factors. Comparing them to the factor loading matrix in the # orthogonal solution, you see that these columns aren’t as pure. This is # because you’ve allowed the underlying factors to be correlated. Although # the oblique approach is more complicated, it’s often a more realistic # model of the data. #### factor.plot(ra.promax, labels = rownames(ra.promax$loadings)) #### fa.diagram(ra.promax, simple = FALSE) # if you let simple = TRUE, only the # largest loading per item is displayed. It shows the largest loadings # for each factor, as well as the produces correlations between the factors. # This type of diagram is helpful when there are several factors. fa.diagram(ra.promax, simple = TRUE) #### t3 <- Harman74.cor fa.parallel(t3$cov, n.obs = t3$n.obs, fa = "both", n.iter = 100) # facotr is 4 ra <- fa(t3$cov, nfactors = 4, rotate = "promax", fm = "pa") # fsm3 <- function(oblique) { if (class(oblique)[2] == "fa" & is.null(oblique$Phi)) { warning("Object doesn't look like oblique EFA") } else { p <- unclass(oblique$loading) F <- p %*% oblique$Phi colnames(F) <- c("PA1", "PA2", "PA3", "PA4") return(F) } } fsm3(ra) # factor.plot(ra, labels = rownames(ra$loadings)) # fa.diagram(ra, simple = TRUE) #### fa$weights # Additionally, the scoring coefficients (standardized regression # weights) are available in the weights element of the object returned. # Unlike component scores, which are calculated exactly, factor scores can only # be estimated. Several methods exist. #### # In EFA, you allow the data to determine the number of factors to be extracted # and their meaning. But you could start with a theory about how many # factors underlie a set of variables, how the variables load on those # factors, and how the factors correlatewith one another. You could then # test this theory against a set of collected data. The approach is called # confirmatory factor analysis (CFA) # CFA is a subset of a methodology called structural equation modeling (SEM). # SEM allows you to posit not only the number and composition of underlying # factors but also how these factors impact one another. You can think of # SEM as a combination of confirmatory factor analyses (for the variables) # and regression analyses (for the factors). The resulting output includes # statistical tests and fit indices. There are several excellent packages # for CFA and SEM in R. They include sem, OpenMx, and lavaan. # Finally, R contains numerous methods for multidimensional scaling (MDS). # MDS is designed to detect underlying dimensions that explain the # similarities and distances between a set of measured objects # (for example, countries). #### # PCA is a useful data-reduction method that can replace a large number of # correlated variables with a smaller number of uncorrelated variables, # simplifying the analyses. # EFA contains a broad range of methods for identifying latent or unobserved # constructs (factors) that may underlie a set of observed or manifest # variables. # Whereas the goal of PCA is typically to summarize the data and reduce its # dimensionality, EFA can be used as a hypothesis-generating tool, # useful when you’re trying to understand the relationships between a large # number of variables. It’s often used in the social sciences for theory # development. ####