text stringlengths 184 4.48M |
|---|
import React, { useState, useEffect } from 'react';
import {
View,
Text,
Image,
Dimensions,
TextInput,
ActivityIndicator,
} from 'react-native';
import { Ionicons, EvilIcons } from '@expo/vector-icons';
import { AntDesign } from '@expo/vector-icons';
import {
ChartDot,
ChartPath,
ChartPathProvider,
ChartYLabel,
} from '@rainbow-me/animated-charts';
import Coin from '../../../assets/data/crypto.json';
import CoinDetailHeader from './components/CoinDetailHeader';
import styles from './style';
import { useRoute } from '@react-navigation/native';
import {
getDetailedCoinData,
getCoinMarketChart,
} from '../../services/request.js';
const CoinDetailedScreen = () => {
// states
const [coin, setCoin] = useState(null);
const [loading, setLoading] = useState(false);
const [coinMarketData, setCoinMarketData] = useState(null);
const [coinValue, setCoinValue] = useState('1');
const [twdValue, setTwdValue] = useState('');
// to get the coin id as parameter to call accoding API
const route = useRoute();
const {
params: { coinId },
} = route;
// to get the screen full size
const screenWidth = Dimensions.get('window').width;
// to get coin details and market chart
const fetchCoinData = async () => {
setLoading(true);
const fetchedCoinData = await getDetailedCoinData(coinId);
const fetchedMarketCoinData = await getCoinMarketChart(coinId);
setCoin(fetchedCoinData);
setCoinMarketData(fetchedMarketCoinData);
setTwdValue(fetchedCoinData.market_data.current_price.twd.toString());
setLoading(false);
};
useEffect(() => {
fetchCoinData();
}, []);
if (loading || !coin || !coinMarketData) {
return <ActivityIndicator size='large' />;
}
const {
id,
image: { small },
symbol,
name,
market_data: {
market_cap_rank,
current_price,
price_change_percentage_24h,
},
} = coin;
const { prices } = coinMarketData;
const percentageColor =
price_change_percentage_24h < 0 ? '#ea3943' : '#16c784';
// to compare the current price to the price at the first price
const chartColor = current_price.twd > prices[0][1] ? '#16c784' : '#ea3943';
// run and change UI thread instead JS thread, only updating UI
const formatCurrency = (value) => {
'worklet';
if (value === '') {
return `NT$${current_price.twd.toLocaleString()} `;
}
return `NT$${parseFloat(value).toLocaleString()}`;
};
const changeCoinValue = (value) => {
setCoinValue(value);
const floatValue = parseFloat(value.replace(',', '.')) || 0;
setTwdValue((floatValue * current_price.twd).toLocaleString().toString());
};
const changeTwdValue = (value) => {
setTwdValue(value);
const floatValue = parseFloat(value.replace(',', '.')) || 0;
setCoinValue((floatValue / current_price.twd).toLocaleString().toString());
};
return (
<View style={{ paddingHorizontal: 10 }}>
{/* ChartPathProvider: using anything from this lib, need to be wrapped */}
<ChartPathProvider
data={{
points: prices.map(([x, y]) => ({ x, y })),
smoothingStrategy: 'bezier',
}}
>
<CoinDetailHeader
coinId={id}
image={small}
name={name}
symbol={symbol}
marketCapRank={market_cap_rank}
/>
<View style={styles.priceContainer}>
<View>
<Text style={styles.name}>{name}</Text>
<ChartYLabel format={formatCurrency} style={styles.currentPrice} />
</View>
<View
style={{
backgroundColor: percentageColor,
paddingHorizontal: 3,
paddingVertical: 8,
borderRadius: 5,
flexDirection: 'row',
}}
>
<AntDesign
name={price_change_percentage_24h < 0 ? 'caretdown' : 'caretup'}
size={12}
color={'white'}
style={{ alignSelf: 'center', marginRight: 5 }}
/>
<Text style={styles.priceChange}>
{price_change_percentage_24h.toFixed(2)}%
</Text>
</View>
</View>
<View>
<ChartPath
storkeWidth={2}
height={screenWidth / 2}
stroke={chartColor}
width={screenWidth}
/>
<ChartDot
style={{
backgroundColor: chartColor,
}}
/>
</View>
<View style={{ flexDirection: 'row' }}>
<View style={{ flexDirection: 'row', flex: 1 }}>
<Text style={{ color: 'white', alignSelf: 'center' }}>
{symbol.toUpperCase()}
</Text>
<TextInput
style={styles.input}
value={coinValue}
keyboardType='numeric'
onChangeText={changeCoinValue}
/>
</View>
<View style={{ flexDirection: 'row', flex: 1 }}>
<Text style={{ color: 'white', alignSelf: 'center' }}>TWD</Text>
{/* value only takes string */}
<TextInput
style={styles.input}
value={twdValue}
keyboardType='numeric'
onChangeText={changeTwdValue}
/>
</View>
</View>
</ChartPathProvider>
</View>
);
};
export default CoinDetailedScreen; |
/*
* Copyright 2023 Google LLC
*
* 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.sampleapp;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
import com.facebook.react.defaults.DefaultReactActivityDelegate;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "SampleApp";
}
/**
* Returns the instance of the {@link ReactActivityDelegate}. Here we use a util class {@link
* DefaultReactActivityDelegate} which allows you to easily enable Fabric and Concurrent React
* (aka React 18) with two boolean flags.
*/
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new DefaultReactActivityDelegate(
this,
getMainComponentName(),
// If you opted-in for the New Architecture, we enable the Fabric Renderer.
DefaultNewArchitectureEntryPoint.getFabricEnabled());
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.uenf.pubmeddataset;
import java.util.Collection;
import com.uenf.pubmeddataset.util.EmptyObjectException;
import com.uenf.pubmeddataset.util.NullValueException;
import com.uenf.pubmeddataset.internet.ArticleDownloader;
import com.uenf.pubmeddataset.internet.DownloadConfiguration;
import com.uenf.pubmeddataset.util.DataSet;
import com.uenf.pubmeddataset.util.DynaArticle;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Test;
import static com.uenf.pubmeddataset.internet.ParameterName.*;
import static org.junit.Assert.*;
import static org.junit.matchers.JUnitMatchers.*;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.*;
/**
*
* @author Kirill
*/
public class DataSetTest {
DownloadConfiguration config = new DownloadConfiguration(ABSTRACT, TITLE, PMID, MESH_TERMS);
@Test
public void shouldGenerateKeyWords() throws Exception {
ArticleDownloader downloader = new ArticleDownloader(config);
List<DynaArticle> articles = downloader.getDynaArticles("whey protein", 10);
ConceptDataSet cds = new ConceptDataSet(articles, "whey protein");
cds.generateKeyWords();
for (DynaArticle article : articles) {
List<String> genKws = (List<String>) article.getGeneratedKws();
for (String kw : genKws) {
assertNotNull(kw);
if (kw.length() < 0) {
fail();
}
}
}
}
/*
* Dado que um artigo possui termos MeSH e um resumo,
* este metodo deve fazer a intercessao dos termos MeSH como o resumo,
* eliminando os termos MeSH que nao estiverem presentes no resumo.
* Se todos os termos MeSH forem excluidos, o artigo é eliminado do DataSet.
*/
@Test
public void shouldIntersectMeshTermsWithTheAbstractText() throws Exception {
DynaArticle article = new DynaArticle(config);
article.put(ABSTRACT, "Kirill Lassounski Fodastico Horrores");
Set<String> meshTerms = new HashSet<String>();
meshTerms.add("Kirill");
meshTerms.add("Kirillski");
meshTerms.add("Kirillkoff");
meshTerms.add("Lassounski");
article.put(MESH_TERMS, meshTerms);
Set<DynaArticle> articles = new HashSet<DynaArticle>();
articles.add(article);
ConceptDataSet cds = new ConceptDataSet(articles, "Kirill Lassounski");
cds.intersectMeshTermsWithAbstract();
DynaArticle alteredArticle = cds.getArticleIt().next();
Set<String> alteredMeshTerms = (Set<String>) alteredArticle.getAttribute(MESH_TERMS).getValue();
assertThat(alteredMeshTerms, hasItems("Kirill", "Lassounski"));
assertThat(alteredMeshTerms.size(), is(equalTo(2)));
}
/*
* Dado que um artigo possui termos MeSH e um resumo,
* este metodo deve fazer a intercessao dos termos MeSH como o resumo,
* eliminando os termos MeSH que nao estiverem presentes no resumo.
* Se todos os termos MeSH forem excluidos, o artigo é eliminado do DataSet.
*/
@Test
public void shouldRemoveArticleFromDataSetIfIntersectionResultInEmptyMeshTermsSet() throws Exception {
DynaArticle article = new DynaArticle(config);
article.put(ABSTRACT, "Kirill Lassounski Fodastico Horrores");
Set<String> meshTerms = new HashSet<String>();
meshTerms.add("Kirillski");
meshTerms.add("Kirillkoff");
article.put(MESH_TERMS, meshTerms);
Set<DynaArticle> articles = new HashSet<DynaArticle>();
articles.add(article);
ConceptDataSet cds = new ConceptDataSet(articles, "Fodastico Horrores");
cds.intersectMeshTermsWithAbstract();
assertTrue(cds.getArticles().isEmpty());
}
/*
* Given that an article has MeshTerms and/or GeneratedKeyWords,
* This method should remove the search term from this sets.
* So that the the set does not contain the search term wich is irrelevant
* in some testing cases. If some of the sets get empty the article is removed from the dataset.
*/
@Test
public void shouldRemoveSearchTermFromArticleAvailiableData() throws Exception {
DynaArticle article = new DynaArticle(config);
article.put(ABSTRACT, "Kirill Lassounski Fodastico Horrores");
Set<String> meshTerms = new HashSet<String>();
meshTerms.add("Kirillski");
meshTerms.add("Kirillkoff");
meshTerms.add("Kirill");
meshTerms.add("Fodastico Horrores");
article.put(MESH_TERMS, meshTerms);
List<DynaArticle> articles = new ArrayList<DynaArticle>();
articles.add(article);
ConceptDataSet cds = new ConceptDataSet(articles, "Fodastico Horrores");
cds.generateKeyWords();
cds.removeSearchTermFromData();
DynaArticle alteredArticle = cds.getArticleIt().next();
Set<String> alteredMeshTerms = (Set<String>) alteredArticle.getAttribute(MESH_TERMS).getValue();
assertThat(alteredMeshTerms, hasItems("Kirillski", "Kirillkoff", "Kirill"));
assertThat(alteredMeshTerms.size(), is(equalTo(3)));
List<String> generatedKws = (List) alteredArticle.getGeneratedKws();
assertThat(generatedKws, hasItems("Kirill", "Lassounski", "Fodastico", "Horrores"));
assertThat(generatedKws.size(), is(equalTo(4)));
}
@Test
public void shouldRemoveArticleIfRunsOutOfWordsAfterSearchTermRemoval() throws Exception {
DynaArticle article = new DynaArticle(config);
article.put(ABSTRACT, "Kirill Lassounski");
Set<String> meshTerms = new HashSet<String>();
meshTerms.add("Kirill");
article.put(MESH_TERMS, meshTerms);
List<DynaArticle> articles = new ArrayList<DynaArticle>();
articles.add(article);
ConceptDataSet cds = new ConceptDataSet(articles, "Kirill");
cds.generateKeyWords();
cds.removeSearchTermFromData();
assertTrue(cds.getArticles().isEmpty());
}
}
class ConceptDataSet extends DataSet {
ConceptDataSet(Collection<DynaArticle> articles, String searchTerm) {
super(articles, searchTerm);
}
@Override
public void generateKeyWords() {
for (Iterator<DynaArticle> articleIt = this.getArticleIt(); articleIt.hasNext();) {
DynaArticle article = articleIt.next();
String abstractText = null;
try {
abstractText = (String) article.getAttribute(ABSTRACT).getValue();
} catch (Exception ex) {
Logger.getLogger(ConceptDataSet.class.getName()).log(Level.SEVERE, null, ex);
}
String[] tokens = abstractText.split(" ");
article.setGeneratedKeyWords(new ArrayList(Arrays.asList(tokens)));
}
}
/**
* Makes the intersection between MeshTerms and AbstractText if availiable.
* If an article runs out of MeshTerms it is removed from the dataset.
*/
public void intersectMeshTermsWithAbstract() throws Exception {
List<DynaArticle> removeArticleList = new ArrayList<DynaArticle>();
nullAttribute:
for (DynaArticle article : articles) {
String abstractText = null;
Set<String> meshTerms = null;
try {
abstractText = (String) article.getAttribute(ABSTRACT).getValue();
meshTerms = (Set<String>) article.getAttribute(MESH_TERMS).getValue();
} catch (Exception ex) {
Logger.getLogger(DataSet.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Attribute for " + (String) article.getAttribute(PMID).getValue() + " is null");
continue nullAttribute;
}
List<String> removeTermList = new ArrayList<String>();
for (String term : meshTerms) {
if (!abstractText.contains(term)) {
removeTermList.add(term);
}
}
meshTerms.removeAll(removeTermList);
if (meshTerms.isEmpty()) {
removeArticleList.add(article);
}
}
articles.removeAll(removeArticleList);
}
/**
* Removes the searchTerm from the MeshTerms if avaliable
* Remove o termo que foi utilizado na busca do conjunto de palavras geradas e
* do conjunto de palavras definidas.
*/
public void removeSearchTermFromData() {
List articlesToRemove = new ArrayList();
nullAttribute:
for (DynaArticle article : articles) {
Set<String> meshTerms = null;
List generatedkws = null;
try {
try {
meshTerms = (Set<String>) article.getAttribute(MESH_TERMS).getValue();
} catch (NullValueException ex) {
Logger.getLogger(DataSet.class.getName()).log(Level.SEVERE, null, ex);
continue nullAttribute;
}
meshTerms.remove(searchTerm);
if (meshTerms.isEmpty()) {
articlesToRemove.add(article);
}
} catch (NoSuchFieldException e) {
System.out.println("There are no Mesh Terms");
continue nullAttribute;
}
try {
generatedkws = (List) article.getGeneratedKws();
generatedkws.remove(searchTerm);
} catch (EmptyObjectException e) {
System.out.println("There are no Generated Key Words");
continue nullAttribute;
}
}
articles.removeAll(articlesToRemove);
}
} |
import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, Dimensions, TouchableOpacity, Modal } from 'react-native';
import PickerSelect from 'react-native-picker-select';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { TextInput } from 'react-native-paper';
import theme from '../PaperTheme';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
// 저장
const storeData = async (key, value) => {
try {
await AsyncStorage.setItem(key, value);
} catch (e) {
// 저장 오류
console.error('Failed to save the data to the storage');
}
};
// 로드
const getData = async (key) => {
try {
const value = await AsyncStorage.getItem(key);
if (value !== null) {
// 값이 존재할 경우
return value;
}
} catch (e) {
// 로드 오류
console.error('Failed to load the data from the storage');
}
};
// 삭제
const removeData = async (key) => {
try {
await AsyncStorage.removeItem(key);
} catch (e) {
// 삭제 오류
console.error('Failed to delete the data from the storage');
}
};
const WINDOW_HEIGHT = Dimensions.get('window').height;
const deliveryRequestList = [
{ label: '문 앞에 놓아주세요.', value: '문 앞에 놓아주세요.' },
{ label: '경비실에 맡겨주세요.', value: '경비실에 맡겨주세요.' },
{ label: '배송 전 전화해주세요.', value: '배송 전 전화해주세요.' },
];
// 제목 단위 폰트 사이즈
const FONT_SIZE_HEADER = WINDOW_HEIGHT * 0.03;
// 작은 폰트 사이즈
const FONT_SIZE_SMALL = WINDOW_HEIGHT * 0.015;
// 중간 폰트 사이즈
const FONT_SIZE_MEDIUM = WINDOW_HEIGHT * 0.02;
// 큰 폰트 사이즈
const FONT_SIZE_LARGE = WINDOW_HEIGHT * 0.025;
// 버튼 둥근 모서리 값
const BUTTON_BORDER_RADIUS = WINDOW_HEIGHT * 0.006;
// 버튼 padding 값
const BUTTON_PADDING = WINDOW_HEIGHT * 0.01;
const DeliveryInfo = ({ deliveryName, setDeliveryName, deliveryPhoneNum, setDeliveryPhoneNum, deliveryAddress, setDeliveryAddress, thankCost, deliveryCost, setDeliveryRequest }) => {
const handlePhoneNumChange = (text) => {
// 숫자만 추출
const numbersOnly = text.replace(/[^0-9]/g, '');
// 숫자를 형식에 맞춰 나눔
let formattedNumber;
if (numbersOnly.length <= 3) {
formattedNumber = numbersOnly;
} else if (numbersOnly.length <= 7) {
formattedNumber = `${numbersOnly.slice(0, 3)}-${numbersOnly.slice(3)}`;
} else {
formattedNumber = `${numbersOnly.slice(0, 3)}-${numbersOnly.slice(3, 7)}-${numbersOnly.slice(7, 11)}`;
}
// 상태 업데이트
setDeliveryPhoneNum(formattedNumber);
};
const [modalVisible, setModalVisible] = useState(false);
const openModal = () => {
setModalVisible(true);
};
const closeModal = () => {
setModalVisible(false);
};
const handleSave = async () => {
await storeData('deliveryName', deliveryName);
await storeData('deliveryPhoneNum', deliveryPhoneNum);
await storeData('deliveryAddress', deliveryAddress);
setModalVisible(false);
};
const formattedThankCost = parseInt(thankCost).toLocaleString();
const formattedDeliveryCost = parseInt(deliveryCost).toLocaleString();
const totalCost = parseInt(thankCost) + parseInt(deliveryCost);
const formattedTotalCost = totalCost.toLocaleString();
return (
<View>
<View style={styles.deliverySection}>
<View style={styles.infoHeader}>
<Text style={styles.sectionTitle}>배송 정보 입력</Text>
<TouchableOpacity style={styles.editButton}
onPress={openModal}>
<Text style={styles.editButtonText}>정보 수정</Text>
</TouchableOpacity>
</View>
<View style={styles.infoContainer}>
<View style={styles.infoRow}>
<Text style={styles.label}>받는 분</Text>
<Text style={styles.value}>{deliveryName}</Text>
</View>
<View style={styles.infoRow}>
<Text style={styles.label}>연락처</Text>
<Text style={styles.value}>{deliveryPhoneNum}</Text>
</View>
<View style={styles.infoRow}>
<Text style={styles.label}>주소</Text>
<Text style={styles.value}>{deliveryAddress}</Text>
</View>
</View>
<PickerSelect
onValueChange={(value) => setDeliveryRequest(value)}
items={deliveryRequestList}
style={pickerSelectStyles}
useNativeAndroidPickerStyle={false}
placeholder={{
label: '배송시 요청사항 선택',
value: null,
}}
/>
</View>
<View style={styles.paymentSection}>
<Text style={styles.sectionTitle}>결제 금액 확인</Text>
<View style={styles.paymentContent}>
<Text style={styles.paymentInfo}>사례비 금액</Text>
<Text style={[styles.paymentInfo, { color: '#000000' }]}>{formattedThankCost}원</Text>
</View>
<View style={styles.paymentContent}>
<Text style={styles.paymentInfo}>배송비</Text>
<Text style={[styles.paymentInfo, { color: '#000000' }]}>{formattedDeliveryCost}원</Text>
</View>
<View style={[styles.paymentContent, { marginTop: 20 }]}>
<Text style={styles.TotalInfo}>총 금액</Text>
<Text style={styles.TotalInfo}>{formattedTotalCost}원</Text>
</View>
</View>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={closeModal}
>
<View style={styles.modalContainer}>
<View style={styles.modalView}>
<View style={{ flexDirection: 'row', alignItems: 'center', width: '100%' }}>
<Text style={styles.modalHeader}>배송 정보 입력</Text>
<TouchableOpacity
onPress={closeModal}
style={{ alignSelf: 'flex-start' }}>
<FontAwesome name="close" size={FONT_SIZE_LARGE} color="#000" />
</TouchableOpacity>
</View>
<View style={{ width: '100%' }}>
<TextInput
style={styles.input}
mode="outlined"
onChangeText={setDeliveryName}
value={deliveryName}
theme={theme}
placeholder="이름"
/>
<TextInput
mode="outlined"
style={styles.input}
onChangeText={handlePhoneNumChange}
value={deliveryPhoneNum}
theme={theme}
keyboardType="phone-pad"
placeholder="전화번호"
/>
<TextInput
mode="outlined"
style={styles.input}
onChangeText={setDeliveryAddress}
value={deliveryAddress}
theme={theme}
placeholder="주소"
/>
</View>
<TouchableOpacity style={styles.saveButton} onPress={handleSave}>
<Text style={styles.saveButtonText}>저장</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
</View>
);
};
const styles = StyleSheet.create({
deliverySection: {
marginTop: 10,
borderTopWidth: 10,
borderTopColor: '#F8F8F8',
padding: 15,
},
infoHeader: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
sectionTitle: {
fontSize: FONT_SIZE_HEADER,
fontWeight: 'bold',
marginBottom: 15,
},
editButton: {
backgroundColor: '#007bff',
alignItems: 'center',
justifyContent: 'center',
padding: BUTTON_PADDING,
borderRadius: BUTTON_BORDER_RADIUS,
},
editButtonText: {
color: '#fff',
fontWeight: 'bold',
fontSize: FONT_SIZE_SMALL,
},
infoContainer: {
paddingBottom: 10,
},
infoRow: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 10, // 각 줄 사이의 간격
},
label: {
fontSize: FONT_SIZE_MEDIUM,
color: '#000',
fontWeight: 'bold',
width: WINDOW_HEIGHT * 0.1, // 라벨의 너비를 고정하여 값들의 시작점을 일치시킵니다.
},
value: {
fontSize: FONT_SIZE_MEDIUM,
color: '#000',
flex: 1, // 값이 라벨 너비를 초과할 수 있도록 합니다.
},
requestInput: {
flexDirection: 'row',
borderWidth: 1,
borderColor: '#9B9B9B',
borderRadius: WINDOW_HEIGHT * 0.005,
padding: WINDOW_HEIGHT * 0.01,
height: WINDOW_HEIGHT * 0.06,
justifyContent: 'space-between',
alignItems: 'center',
},
requestPlaceholder: {
fontSize: FONT_SIZE_MEDIUM,
color: '#9B9B9B',
},
paymentSection: {
marginTop: 10,
borderTopWidth: 10,
borderTopColor: '#F8F8F8',
padding: 15,
},
paymentContent: {
flexDirection: 'row',
justifyContent: 'space-between',
marginBottom: 10,
},
paymentInfo: {
color: '#9B9B9B',
fontWeight: 'bold',
fontSize: FONT_SIZE_MEDIUM,
},
TotalInfo: {
color: '#000000',
fontWeight: 'bold',
fontSize: FONT_SIZE_LARGE,
},
modalView: {
margin: 20,
backgroundColor: "white",
borderRadius: 20,
padding: 35,
alignItems: "center",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5,
alignSelf: 'center', // 모달을 가운데로 정렬합니다.
width: '90%', // 모달의 너비를 확장합니다.
height: '50%', // 모달의 최대 높이를 설정합니다.
justifyContent: 'space-between', // 모달 내부의 요소들을 세로 방향으로 가운데 정렬합니다.
},
modalHeader: {
fontSize: FONT_SIZE_HEADER,
fontWeight: 'bold',
width: '100%',
textAlign: 'left',
marginBottom: 20,
},
modalContainer: {
flex: 1, // 모달 컨테이너가 전체 화면을 차지하도록 설정
justifyContent: 'center', // 수직 방향으로 중앙 정렬
alignItems: 'center', // 가로 방향으로 중앙 정렬
},
input: {
width: '100%',
backgroundColor: "#fff",
marginBottom: 10,
},
saveButton: {
backgroundColor: "#007bff",
padding: 10,
borderRadius: 20,
marginTop: 10,
width: '100%', // 저장 버튼의 너비를 늘립니다.
alignItems: 'center', // 버튼 내부의 텍스트를 가운데로 정렬합니다.
},
saveButtonText: {
color: "white",
fontSize: FONT_SIZE_MEDIUM,
fontWeight: "bold",
},
});
const pickerSelectStyles = StyleSheet.create({
inputIOS: {
height: WINDOW_HEIGHT * 0.055,
fontSize: 16,
paddingVertical: 12,
paddingHorizontal: 10,
borderWidth: 1,
borderColor: 'gray',
borderRadius: 4,
color: 'black',
paddingRight: 30, // iOS에서 화살표 아이콘 영역을 확보
},
placeholder: {
color: '#BDBDBD',
},
inputAndroid: {
height: WINDOW_HEIGHT * 0.055,
fontSize: 16,
paddingHorizontal: 10,
paddingVertical: 8,
borderWidth: 0.5,
borderColor: 'purple',
borderRadius: 8,
color: 'black',
paddingRight: 30, // 안드로이드에서 화살표 아이콘 영역을 확보
},
});
export default DeliveryInfo |
//
// ColorBars.swift
// NewTerm Common
//
// Created by Adam Demasi on 23/9/21.
//
import Foundation
struct ColorBars {
private struct RGB: CustomStringConvertible {
var r: Int, g: Int, b: Int
init(_ r: Int, _ g: Int, _ b: Int) {
self.r = r
self.g = g
self.b = b
}
var description: String { "\(r);\(g);\(b)" }
}
private static let bars: [[RGB]] = [
[RGB(192, 192, 192), RGB(192, 192, 0), RGB( 0, 192, 192), RGB( 0, 192, 0), RGB(192, 0, 192), RGB(192, 0, 0), RGB( 0, 0, 192)],
[RGB( 0, 0, 192), RGB( 19, 19, 19), RGB(192, 0, 192), RGB( 19, 19, 19), RGB( 0, 192, 192), RGB( 19, 19, 19), RGB(192, 192, 192)],
[RGB( 0, 33, 76), RGB(255, 255, 255), RGB( 50, 0, 106), RGB( 19, 19, 19), RGB( 9, 9, 9), RGB( 19, 19, 19), RGB( 29, 29, 29), RGB( 19, 19, 19)]
]
static func render(screenSize: ScreenSize, message: String) -> Data {
// Don’t bother drawing if the screen is too small
if screenSize.cols < 7 || screenSize.rows < 10 {
return Data()
}
// Draw color bars
let firstSectionSize = ScreenSize(cols: UInt16(Double(screenSize.cols) / 7),
rows: UInt16(Double(screenSize.rows) * 0.66))
let thirdSectionSize = ScreenSize(cols: UInt16(Double(screenSize.cols) / 6),
rows: UInt16(Double(screenSize.rows) * 0.25))
let secondSectionSize = ScreenSize(cols: UInt16(Double(screenSize.cols) / 7),
rows: screenSize.rows - firstSectionSize.rows - thirdSectionSize.rows - 1)
let firstSectionWidth = firstSectionSize.cols * 7
let thirdSectionWidth = thirdSectionSize.cols * 5 + (UInt16(Double(thirdSectionSize.cols) / 3) * 3)
let widestWidth = max(firstSectionWidth, thirdSectionWidth)
var data = "\u{1b}[?25l\u{1b}c"
let space = String(repeating: " ", count: Int(firstSectionSize.cols))
let differenceSpace = String(repeating: " ", count: Int(widestWidth - firstSectionWidth))
for _ in 0..<firstSectionSize.rows {
for color in bars[0] {
data += "\u{1b}[48;2;\(color)m\(space)"
}
if firstSectionWidth < widestWidth {
data += "\u{1b}[48;2;\(bars[0].last!)m\(differenceSpace)"
}
data += "\u{1b}[0m\r\n"
}
for _ in 0..<secondSectionSize.rows {
for color in bars[1] {
data += "\u{1b}[48;2;\(color)m\(space)"
}
if firstSectionWidth < widestWidth {
data += "\u{1b}[48;2;\(bars[1].last!)m\(differenceSpace)"
}
data += "\u{1b}[0m\r\n"
}
let finalSpace = String(repeating: " ", count: Int(thirdSectionSize.cols))
let finalInnerWidth = Int(Double(thirdSectionSize.cols) / 3)
let finalInnerSpace = String(repeating: " ", count: finalInnerWidth)
let finalDifferenceSpace = String(repeating: " ", count: Int(widestWidth - thirdSectionWidth))
for _ in 0..<thirdSectionSize.rows {
for i in 0..<bars[2].count {
// Special case: There is a gradient of 3 colors in the second-last rectangle.
let space = i >= 4 && i <= 6 ? finalInnerSpace : finalSpace
data += "\u{1b}[48;2;\(bars[2][i])m\(space)"
}
if thirdSectionWidth < widestWidth {
data += "\u{1b}[48;2;\(bars[2].last!)m\(finalDifferenceSpace)"
}
data += "\u{1b}[0m\r\n"
}
// Draw error text
let textPosition = ScreenSize(cols: UInt16(max(0, Double((Int(widestWidth) - message.count + 2) / 2).rounded(.toNearestOrEven))),
rows: UInt16(Double(screenSize.rows / 2).rounded(.down)))
data += "\u{1b}[\(textPosition.rows);\(textPosition.cols)H\u{1b}[1;7m \(message) \u{1b}[m\u{1b}[\(screenSize.cols);0H"
return data.data(using: .utf8)!
}
} |
<template>
<button
data-testid="sendButton"
id="sendButton"
name="sendButton"
class="btn btn-primary"
:disabled="disabled"
@click.prevent="submit"
>
<spinner v-show="activatedSpinner" />
<slot></slot>
</button>
</template>
<script>
import spinner from "./Spinner.vue";
export default {
props: {
testId: {
type: String,
required: true
},
id: {
type: String,
required: true
},
name: {
type: String,
required: true
},
disabled: {
type: Boolean,
required: true
},
submit: {
type: Function,
required: true
},
activatedSpinner: {
type: Boolean,
required: true
}
},
components: {
spinner
}
}
</script> |
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
if (!User::where('first_name', 'Super')->exists()) {
$user = new User();
$user->first_name = "Super";
$user->last_name = "Admin";
$user->email = "superadmin@example.com";
$user->password = bcrypt(12345678);
$user->save();
} else {
$user = User::where('first_name', 'Super')->where('last_name', 'Admin')->first();
}
$role = Role::find(1);
$user->assignRole($role);
$user->update();
$permissions = Permission::all();
$roles = Role::all();
foreach ($roles as $role) {
if ($role->name == 'Super Admin' || $role->name == 'Admin') {
$role->givePermissionTo($permissions);
} elseif ($role->name == 'Publisher') {
$role->givePermissionTo($permissions->whereIn('name', [
'users.create',
'users.show',
'users.edit',
'users.destroy',
'manuscripts.show',
'manuscripts.edit',
'manuscripts.destroy',
'manuscripts.publish',
'manuscripts.review',
'manuscripts.show_all',
'manuscripts.cover_letter',
'manuscripts.conflict_of_interest',
'manuscripts.declaration_of_interest_statement',
'journals.create',
'journals.show',
'journals.edit',
'journals.destroy',
'journals.show_all',
'dashboard.show',
'dashboard.show_all',
'dashboard.show_reviewers_status',
]));
} elseif($role->name == 'Editor') {
$role->givePermissionTo($permissions->whereIn('name', [
'manuscripts.show',
'manuscripts.edit',
'manuscripts.destroy',
'manuscripts.review',
'manuscripts.show_all',
'manuscripts.cover_letter',
'manuscripts.conflict_of_interest',
'manuscripts.declaration_of_interest_statement',
'journals.show',
'journals.edit',
'dashboard.show',
'dashboard.show_reviewers_status',
]));
} elseif($role->name == 'Reviewer') {
$role->givePermissionTo($permissions->whereIn('name', [
'manuscripts.show',
'manuscripts.edit',
'manuscripts.review',
'journals.show',
'journals.edit',
'dashboard.show',
]));
} elseif($role->name == 'Author') {
$role->givePermissionTo($permissions->whereIn('name', [
'manuscripts.show',
'manuscripts.edit',
'manuscripts.destroy',
'manuscripts.cover_letter',
'manuscripts.conflict_of_interest',
'manuscripts.declaration_of_interest_statement',
'journals.show',
'dashboard.show',
]));
}
}
}
} |
import React, { useState, useEffect } from 'react';
import Card from 'react-bootstrap/Card';
import Footer from './footer';
import Navigation from './navbar';
import { getDataByCategory } from "../Services/api";
import img23 from '../Images/uni1.avif';
const Unisex = () => {
const [UnisexData, setUnisexData] = useState([]);
useEffect(() => {
getUnisexdata();
}, []);
const getUnisexdata = async () => {
try {
const response = await getDataByCategory({ category: 'unisex' });
setUnisexData(response.data);
} catch (error) {
console.log('Unisex data did not exist...', error);
}
};
return (
<div>
<Navigation />
<div>
<img src={img23} style={{ width: "100%" }} alt="Unisex Perfume" />
</div>
<div style={{ display: "flex", width: "100%" }}>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '2rem', justifyContent: 'center' }}>
{UnisexData.map((product, index) => (
<Card key={index} className="mb-3" style={{ width: '18rem', marginTop: '2rem', textAlign: 'center' }}>
<img src={product.pic} alt={product.name} style={{ height: '100%' }} />
<Card.Body>
<Card.Title>{product.name}</Card.Title>
<Card.Text>
<p>Price: ${product.price}</p>
<p>Brand: {product.brand}</p>
</Card.Text>
<button style={{ backgroundColor: '#6CB4EE', borderRadius: '20px' }}>Buy</button>
</Card.Body>
</Card>
))}
</div>
</div>
<Footer />
</div>
);
}
export default Unisex; |
import mongoose from "mongoose";
const todoSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
priority: {
type: String,
default: "medium",
},
completed: {
type: Boolean,
default: false,
},
selectedUser: {
type: String,
required: true,
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
},
{
timestamps: true,
}
);
const Todo = mongoose.model("Todo", todoSchema);
export default Todo; |
{% extends('layouts.admin') %}
{% import('form_macro') as form_macro %}
{% block title %}
{% if app.request.get('id') > 0 %}{{ trans('Edit User') }}{% else %}{{ trans('Create User') }}{% endif %}
{% endblock %}
{% block auth_content %}
<div class="container-fluid">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">
{% if app.request.get('id') > 0 %}{{ trans('Edit User') }}{% else %}{{ trans('Create User') }}{% endif %}
</h3>
</div>
<form action="" method="post">
{{ csrf_field() }}
<div class="card-body">
{{ form_macro.messages() }}
{{ form_macro.textField({label: trans('Name'), field: 'name', value: old('name', user.name)}) }}
{{ form_macro.emailField({label: trans('Email'), field: 'email', value: old('email', user.email)}) }}
{{ form_macro.select({label: trans('Role'), field: 'role', value: old('role', user.role), options: [
{value: 'admin', name: 'Admin'},
{value: 'user', name: 'User'}
]}) }}
{% if user.id >0 %}
<div class="mb-3">
<div>
<label class="form-check">
<input class="form-check-input" type="checkbox" onchange="$('#password-fields').toggle();">
<span class="form-check-label">{{ trans('Change password')}} </span>
</label>
</div>
</div>
{% endif %}
<div id="password-fields" {% if user.id > 0 %}style="display: none;"{% endif %}>
{{ form_macro.passwordField({label: trans('Password'), field: 'password'}) }}
{{ form_macro.passwordField({label: trans('Password Confirmation'), field: 'password_confirmation'}) }}
</div>
</div>
<div class="card-footer d-flex">
<button type="submit" class="btn btn-primary">
{% if app.request.get('id') > 0 %}{{ trans('Update') }}{% else %}{{ trans('Create') }}{% endif %}
</button>
{% if user.id > 0 %}
<a href="{{ route('users.delete', {id: user.id}) }}" class="btn btn-danger" style="margin-left: auto" onclick="return confirm('{{ trans('Are you sure?') }}');">
{{ trans('Delete') }}
</a>
{% endif %}
</div>
</form>
</div>
</div>
</div>
{% endblock %} |
// Delight of promise chaining
//This is a FAKE Http Request Function
//It takes 1 second to resolve or reject the promise, depending on the url that is passed in
const fakeRequest = (url) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const pages = {
'/users' : [
{ id: 1, username: 'Bilbo' },
{ id: 5, username: 'Esmerelda' }
],
'/users/1' : {
id : 1,
username : 'Bilbo',
upvotes : 360,
city : 'Lisbon',
topPostId : 454321
},
'/users/5' : {
id : 5,
username : 'Esmerelda',
upvotes : 571,
city : 'Honolulu'
},
'/posts/454321' : {
id : 454321,
title :
'Ladies & Gentlemen, may I introduce my pet pig, Hamlet'
},
'/about' : 'This is the about page!'
};
const data = pages[url];
if (data) {
resolve({ status: 200, data }); //resolve with a value!
}
else {
reject({ status: 404 }); //reject with a value!
}
}, 1000);
});
};
// .then() works on a promise
fakeRequest('/users')
.then(res => {
console.log(res);
// will give us the response from the '/users'
const id = res.data[0].id;
// Now we need to return a promise
return fakeRequest(`/users/${id}`);
})
.then(res => {
console.log(res);
const topPostId = res.data.topPostId;
// Now we need to return a promise again
return fakeRequest(`/posts/${topPostId}`);
})
.then(res => {
console.log(res);
})
.catch(res => {
console.log("REQUEST REJECTED");
console.log("ERROR CODE", res.status);
})
// One of the delights in promise chaining is that even if one of the request fails then the catch() would work
// It is like catchAll() -- though there is no such method like that |
import random
import AI_Learn
import pandas as pd
# 🟦
# 🟩
# 🟥
# 🟨
# ⬜
# creating a class where images will be generated
class creatingLayout():
# init method to initialize all the variable
def __init__(self):
self.grid = None
self.color = ['🟦', '🟩', '🟥', '🟨']
self.picked_rows = []
self.picked_cols = []
self.debug = False
self.color_combinations = []
# Method to place the wires on on the image
def wiredGrid(self, D):
# create grid
self.grid = [["⬜" for _ in range(D)] for _ in range(D)]
# dictionry to store the combination
self.color_combinations = []
# Ask 50% chance to Pick row or col
which = random.choice([True, False])
# If which is True then row else coln
if which:
# Loop until all four wires places on image
while len(self.color) > 0:
# first row then coln
self.getRow(D)
self.getCol(D)
else:
# Loop until all four wires places on image
while len(self.color) > 0:
# first coln then row
self.getCol(D)
self.getRow(D)
# Print Grid when debug mode is ON
if self.debug:
for x in self.grid:
print(''.join(x))
print()
return self.grid , self.color_combinations
# Get ROW
def getRow(self, D):
# Pick a random row from the grid
pick_row = random.randint(0, D - 1)
# Check if the row pick from the grid is not same as picked last time
while pick_row in self.picked_rows:
pick_row = random.randint(0, D - 1)
self.picked_rows.append(pick_row)
# Pick a random color for the row
pick_color = random.randint(0, len(self.color) - 1)
# Iterate through the row and place the wire of choosen color
for y in range(D):
self.grid[pick_row][y] = self.color[pick_color]
# order of the color is appended to the color combination
self.color_combinations.append((self.color[pick_color], 0)) # 0 represents row
# remove the picked color from the color variable
self.color.pop(pick_color)
# Get COLUMN
def getCol(self, D):
# Pick a random column from the grid
pick_col = random.randint(0, D - 1)
# Check if the column is picked from the grid is not same as picked last time
while pick_col in self.picked_cols:
pick_col = random.randint(0, D - 1)
self.picked_cols.append(pick_col)
# Pick a random color for the columns
pick_color = random.randint(0, len(self.color) - 1)
# Iterate through the column and place the wire of choosen color
for x in range(D):
self.grid[x][pick_col] = self.color[pick_color]
# order of the color is appended to the color combination
self.color_combinations.append((self.color[pick_color], 1)) # 1 represents column
# remove the picked color from the color variable
self.color.pop(pick_color)
# Wired Image status
def wiredGrid_status_is(self):
# Get the red wire index from the color combination dictionary
redPixel_index = self.find_indexes(self.color_combinations, "🟥")
# Get the yellow wire index from the color combination dictionary
yellowPixel_index = self.find_indexes(self.color_combinations, "🟨")
# If the yellow wire index is greater than red means the yellow is placed after red
if yellowPixel_index > redPixel_index:
return 1 # Danger
# If the yellow wire index is smaller than red means the yellow is placed before red
elif yellowPixel_index < redPixel_index:
return 0 # Safe
# Helper Method to find the index from list with the target component
def find_indexes(self, givenList, target_color):
indexes = [index for index, (color, _) in enumerate(givenList) if color == target_color]
return indexes[0]
# Generate data:-
# Parameters are dataset sixe, grid size, and test_split_ratio
def generate_data_for_task_1(dataSet , gridSize, test_split_ratio):
result_list = []
try :
for i in range(dataSet):
# Create a layout
layout = creatingLayout()
# get the grid and its order of wire places
grid , color_order = layout.wiredGrid(gridSize)
# Get Circuit status whether its dangerous or nor
circuit_status = layout.wiredGrid_status_is()
# result dictionary contains the columns names:
# 1) encoding - represents the hot encoding of the each pixel flatten into 1D array
# 2) binary classification - represents the binary 1 for danger and 0 for safe
# 3) multi classification - represents the color at the third position using hot encoding
result_dict = {'encoding': AI_Learn.encoding_for_1(grid),
'binary_classification': circuit_status }
# Enter the result for from the dictionary to the result list
result_list.append(result_dict)
# if i == 500:
# result_df = pd.DataFrame(result_list)
# result_df.to_excel('DataSets/validation_dataSet_1.xlsx', index=False)
# result_list = []
# Based on the set training ratio, data will be save to training_dataSet
if i == dataSet - int((dataSet * test_split_ratio)):
result_df = pd.DataFrame(result_list)
result_df.to_excel('DataSets/training_dataSet_1.xlsx', index=False)
# After entering storing to training result list is empty to store new data to test
result_list = []
# Based on the set test ratio, data will be save to training_dataSet
if i == dataSet - 1:
result_df = pd.DataFrame(result_list)
result_df.to_excel('DataSets/testing_dataSet_1.xlsx', index=False)
# Any exception occured for the file opening
except Exception as e:
print("Please make sure for the file path. \n Error", e)
print("***********************************************************")
print(" -> DATA GENERATED FOR MODEL - 1 <- ")
print("***********************************************************")
# Parameters are dataset sixe, grid size, and test_split_ratio
def generate_data_for_task_2(dataSet , gridSize, test_split_ratio):
result_list = []
va = 0
check = 0
try :
while check != 2:
# Create a layout
layout = creatingLayout()
# get the grid and its order of wire places
grid , color_order = layout.wiredGrid(gridSize)
# Get Circuit status whether its dangerous or nor
circuit_status = layout.wiredGrid_status_is()
if circuit_status == 1:
result_dict = {'encoding': AI_Learn.encoding_for_2(grid),
'multi_classification': AI_Learn.order_encoding(color_order) }
result_list.append(result_dict)
if va == (dataSet - int((dataSet * test_split_ratio))):
result_df = pd.DataFrame(result_list)
result_df.to_excel('DataSets/training_dataSet_2.xlsx', index=False)
check += 1
# if va == 500:
# result_df = pd.DataFrame(result_list)
# result_df.to_excel('DataSets/validation_dataSet_2.xlsx', index=False)
if va == int((dataSet * test_split_ratio)):
result_df = pd.DataFrame(result_list)
result_df.to_excel('DataSets/testing_dataSet_2.xlsx', index=False)
result_list = []
check += 1
va += 1
# Any exception occured for the file opening
except Exception as e:
print("Please make sure for the file path. \n Error", e)
print("***********************************************************")
print(" -> DATA GENERATED FOR MODEL - 2 <- ")
print("***********************************************************") |
const AddedComment = require('../../Domains/comments/entities/AddedComment');
const Comments = require('../../Domains/comments/entities/Comments');
const CommentRepository = require('../../Domains/comments/CommentRepository');
const NotFoundError = require('../../Commons/exceptions/NotFoundError');
const AuthorizationError = require('../../Commons/exceptions/AuthorizationError');
class CommentRepositoryPostgres extends CommentRepository {
constructor(pool, idGenerator) {
super();
this._pool = pool;
this._idGenerator = idGenerator;
}
async addComment({ content }, threadId, owner) {
const id = `comment-${this._idGenerator()}`;
const query = {
text: 'INSERT INTO comments VALUES($1, $2, $3, $4) RETURNING id, content, owner',
values: [id, threadId, content, owner],
};
const result = await this._pool.query(query);
return new AddedComment(result.rows[0]);
}
async verifyComment(id) {
const query = {
text: 'SELECT id FROM comments WHERE id = $1',
values: [id],
};
const result = await this._pool.query(query);
if (result.rowCount === 0) throw new NotFoundError('comment tidak ditemukan');
}
async verifyCommentOnThread(commentId, threadId) {
const query = {
text: 'SELECT id FROM comments WHERE id = $1 AND thread_id = $2',
values: [commentId, threadId],
};
const result = await this._pool.query(query);
if (result.rowCount === 0) throw new NotFoundError('comment tidak ditemukan');
}
async verifyDeleteComment(id, owner) {
const query = {
text: 'SELECT id FROM comments WHERE id = $1 AND owner = $2',
values: [id, owner],
};
const result = await this._pool.query(query);
if (result.rowCount === 0) throw new AuthorizationError('akses hapus comment tidak diijinkan');
}
async getComment({ threadId }) {
const query = {
text: `
SELECT comments.id, users.username, comments.date, comments.is_deleted, comments.content
FROM comments
LEFT JOIN users ON comments.owner = users.id
WHERE comments.thread_id = $1
ORDER BY comments.date
`,
values: [threadId],
};
const result = await this._pool.query(query);
return result.rows.map((val) => new Comments(val));
}
async deleteComment({ commentId: id }) {
const query = {
text: `UPDATE comments SET is_deleted = true WHERE id = $1 RETURNING id`,
values: [id],
};
await this._pool.query(query);
}
}
module.exports = CommentRepositoryPostgres; |
--16. SUBSTR 함수를 사용하여 사원들의 입사한 년도와 입사한 달만 출력하시오.
select ename, substr(hiredate,1,5) as destroy_day,
substr(hiredate,1,2) as destroy_year,
substr(hiredate,4,2) as destroy_month
from emp;
--17. SUBSTR 함수를 사용하여 4월에 입사한 사원을 출력하시오.
select *
from emp
where substr(hiredate,4,2) ='04';
--18. MOD 함수를 사용하여 사원번호가 짝수인 사람만 출력하시오.
SELECT empno, ename, deptno
FROM emp
WHERE mod(empno, 2) = 0;
--19. 입사일을 년도는 2자리(YY), 월은 숫자(MM)로 표시하고
--요일은 약어 (DY)로 지정하여 출력하시오.
select empno,ename,
to_char(hiredate, 'YYYY.MM.DY') as hire_date,
to_char(hiredate, 'MM') as " 입사 월" ,
to_char(hiredate, 'DY') as "입사 요일"
from emp;
--20. 올해 몇 칠이 지났는지 출력하시오.
--현재날짜에서 올해 1월 1일을 뺀 결과를 출력하고 TO_DATE 함수를
--사용하여 데이터 형을 일치 시키시오.
SELECT TO_NUMBER(TO_CHAR(SYSDATE, 'DDD')) FROM dual;
select sysdate, to_date('2023-01-01', 'YYYY.MM.DD'),
sysdate - to_date('2023-01-01', 'YYYY.MM.DD')
from dual;
--21. 사원들의 상관 사번을 출력하되 상관이 없는
-- 사원에 대해서는 NULL 값 대신 0으로 출력하시오.
select ename,empno,deptno,comm from emp where comm is not null;
select mgr, nvl(mgr,0) from emp;
--22. DECODE 함수로 직급에 따라 급여를 인상하도록 하시오.
--직급이 ‘ANALIST”인 사원은 200, ‘SALESMAN’인 사원은 180,
--‘MANAGER’인 사원은 150, ‘CLERK”인 사원은 100을 인상하시오.
select ename, job, sal, decode(
job,
'ANALIST', sal+200,
'SALEMAN', sal+180,
'MANAGER', sal+150,
'CLERCK', sal+100
) as up_salse
from emp;
--23. 모든 사원의 급여 최고액, 최저액,
--총액 및 평균 급여를 출력하시오. 평균에 대해서는 정수로 반올림하시오.
select deptno, count(*) as "사원의수" ,
sum(sal) as "총급여액" ,
trunc(avg(sal)) as "평균급여액" ,
max(sal) as "최고급여액" ,
min(sal) as "최소급여액",
count(comm) as "커미션을받는사원수"
from emp
group by deptno;
--. 각 담당 업무 유형별로 급여 최고액, 최저액,
--총액 및 평균 액을 출력하시오. 평균에 대해서는 정수로 반올림 하시오.
select job, count(*) as "사원수",
max(sal) as"최고액",
min(sal) as"최저액",
sum(sal) as "총액",
trunc(avg(sal)) as"평균액"
from emp
group by job;
--25. COUNT(*) 함수를 이용하여 담당업무가 동일한 사원 수를 출력하시오.
select job, count(*) as"담당업무 동일 사원 수 "
from emp
group by job;
--26. 관리자 수를 출력하시오.
SELECT job, COUNT(*) as "관리자 수"
FROM emp
GROUP BY job
HAVING job = 'MANAGER';
select count(distinct mgr)
from emp;
--27. 급여 최고액, 급여 최저액의 차액을 출력하시오.
select max(sal), min(sal), max(sal) - min(sal) as "급여 최고액 - 최저액"
from emp;
--28. 직급별 사원의 최저 급여를 출력하시오.
--관리자를 알 수 없는 사원과 최저 급여가 2000 미만인
--그룹은 제외시키고 결과를 급여에 대한 내림차순으로 정렬하여 출력하시오.
SELECT job, MIN(sal) AS min_sal
FROM emp
WHERE job != 'MANAGER' AND sal >= 2000
GROUP BY job
ORDER BY min_sal DESC;
select job, min(sal)
from emp
where mgr is not null
group by job
having min(sal) >= 2000
order by min(sal) desc
;
--29. 각 부서에 대해 부서번호, 사원 수,
--부서 내의 모든 사원의 평균 급여를 출력하시오.
--평균 급여는 소수점 둘째 자리로 반올림 하시오.
SELECT deptno, count(*) as "사원수",
round(avg(sal),2) as "모든 사원 평균 급여"
from emp
group by deptno;
--30. 각 부서에 대해 부서번호 이름, 지역 명,
--사원 수, 부서내의 모든 사원의 평균 급여를 출력하시오.
--평균 급여는 정수로 반올림 하시오. DECODE 사용.
SELECT dept.deptno, dept.dname, dept.loc, COUNT(emp.empno) AS "사원 수",
ROUND(AVG(emp.sal)) AS "평균 급여"
FROM emp JOIN dept ON emp.deptno = dept.deptno
GROUP BY dept.deptno, dept.dname, dept.loc
ORDER BY dept.deptno ASC;
select * from dept;
select deptno,
decode(deptno,10, 'ACCOUNTING',
20, 'RESEARCH',
30, 'SALES',
40, 'OPERATIONS'
)as dname, decode (deptno,10,'NEW YORK',
20, 'DALLAS',
30, 'CHICAGO',
40, 'BOSTON'
) as loc, count(*), round(avg(sal))
from emp
group by deptno
order by deptno
; |
import { Table, Typography } from "antd";
import { useContext, useState } from "react";
import { ContextUserProvider } from "../../context/ContextProvider";
import { Searchs } from "../../components/Searchs";
import { DeleteUsers } from "../../components/DeleteUsers";
import { ModalCreateUsers } from "../../components/ModalCreateUsers";
import ColumnGroup from "antd/es/table/ColumnGroup";
import Column from "antd/es/table/Column";
import { ModalUpdateUsers } from "../../components/ModalUpdateUsers";
export const Home = () => {
const { filteredDataUsers, onSelectChange, selectedRowKeys } =
useContext(ContextUserProvider);
const [bottom, setBottom] = useState("bottomLeft");
const dataUserMap = filteredDataUsers.map((user) => ({
...user,
key: user.id,
}));
const rowSelection = {
selectedRowKeys,
onChange: onSelectChange,
};
return (
<div className="whitespace-nowrap ">
<div>
<Searchs />
</div>
<div>
<ModalCreateUsers />
</div>
<div className="overflow-scroll">
{dataUserMap.length > 0 ? (
<div>
<Table
pagination={{
showSizeChanger: true,
showQuickJumper: true,
pageSizeOptions: ["5", "10"],
position: [bottom],
}}
rowSelection={rowSelection}
dataSource={dataUserMap}
>
<ColumnGroup title="name">
<Column
title="firstname"
dataIndex="name.firstname"
key="name.firstname"
sorter={(a, b) => {
const nameA = a?.name?.firstname || "";
const nameB = b?.name?.firstname || "";
return nameA.localeCompare(nameB);
}}
render={(text, record) =>
record.name && record.name.firstname
? record.name.firstname
: "N/A"
}
/>
<Column
title="lastname"
dataIndex="name.lastname"
id="name.lastname"
sorter={(a, b) => {
const nameA = a?.name?.lastname || "";
const nameB = b?.name?.lastname || "";
return nameA.localeCompare(nameB);
}}
render={(text, record) =>
record.name && record.name.lastname
? record.name.lastname
: "N/A"
}
/>
</ColumnGroup>
<Column
title="username"
dataIndex="username"
key="username"
sorter={(a, b) => a?.username.localeCompare(b?.username)}
/>
<Column
title="email"
dataIndex="email"
key="email"
sorter={(a, b) => a.email.localeCompare(b.email)}
render={(text, record) => (
<a
href={`mailto :${record.email}`}
target="_blank"
rel="noopener noreferrer"
>
{record.email}
</a>
)}
/>
<Column
title="address"
dataIndex="address"
key="address"
sorter={(a, b) => a.address.city.localeCompare(b.address.city)}
render={(text, record) =>
record.address && record.address.city
? record.address.city
: "N/A"
}
/>
<Column
title="phone"
dataIndex="phone"
key="phone"
sorter={(a, b) => a.phone.localeCompare(b.phone)}
/>
<Column
title="action"
key="action"
render={(text, record) => (
<div className="flex">
<button>
<ModalUpdateUsers record={record} />
</button>
</div>
)}
/>
</Table>
</div>
) : (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<Typography.Title level={2}>
Không tìm thấy người dùng
</Typography.Title>
</div>
)}
</div>
<div
style={{
padding: "10px 50px",
width: "100%",
background: "#ddd",
color: "rgba(255, 255, 255, 0.65)",
position: "sticky",
bottom: 0,
}}
>
<DeleteUsers />
</div>
</div>
);
}; |
package day3
import (
"bufio"
"fmt"
"log"
"math"
"os"
"strconv"
"strings"
)
type edge = struct {
startX int
startY int
endX int
endY int
steps int
}
func isHorizontal(e edge) bool {
return e.startY == e.endY
}
func isVertical(e edge) bool {
return e.startX == e.endX
}
func Crosses(e1 edge, e2 edge) (int, int, int, bool) {
// wires intersect if they're a common point between them.
// a wire is either horizontal or vertical.
// for now we'll assume that if they're both horizontal/vertical that they
// don't cross. probably wrong in the grand scheme of things
if isHorizontal(e1) && isHorizontal(e2) {
return 0, 0, 0, false
}
if isVertical(e1) && isVertical(e2) {
return 0, 0, 0, false
}
if isVertical(e1) && isHorizontal(e2) {
e1, e2 = e2, e1
}
// e1 is horizontal and e2 is vertical.
if e1.startY != e1.endY {
panic("invalid")
}
if e2.startX != e2.endX {
panic("invalid")
}
// if there is a cross, it will be at e2.startX, e1.startY. we need this
// to be on both wires. since we don't store startX and endX sorted this
// gets annoying.
var crosses bool = true
if e2.startY < e2.endY {
crosses = crosses && (e2.startY < e1.startY && e1.startY < e2.endY)
} else {
crosses = crosses && (e2.endY < e1.startY && e1.startY < e2.startY)
}
if e1.startX < e1.endX {
crosses = crosses && (e1.startX < e2.startX && e2.startX < e1.endX)
} else {
crosses = crosses && (e1.endX < e2.startX && e2.startX < e1.startX)
}
if !crosses {
return 0, 0, 0, false
}
// distance to cross = steps from start of e1 to cross +
// steps from start of e2 to cross
var xSteps int = 0
var ySteps int = 0
xSteps = e1.startX - e2.startX
ySteps = e2.startY - e1.startY
if xSteps < 0 {
xSteps = -xSteps
}
if ySteps < 0 {
ySteps = -ySteps
}
return e2.startX, e1.startY, xSteps + ySteps, true
}
func Run(f *os.File) {
scanner := bufio.NewScanner(f)
// two lines. we start from 0, 0 for both.
rows := 0
var edges1 []edge
var edges2 []edge
for scanner.Scan() {
if rows > 1 {
panic("Only should have had two lines of input")
}
e := make([]edge, 0)
steps := 0 // steps to get to
line := scanner.Text()
res := strings.Split(line, ",")
var startX int = 0
var endX int = 0
var startY int = 0
var endY int = 0
for _, r := range res {
n, err := strconv.ParseInt(r[1:], 10, 64)
if err != nil {
log.Fatal(err)
}
switch r[0] {
case 'D':
endX = startX
endY = startY + int(n)
case 'U':
endX = startX
endY = startY - int(n)
case 'R':
endX = startX + int(n)
endY = startY
case 'L':
endX = startX - int(n)
endY = startY
default:
panic("Invalid direction")
}
e = append(e, edge{startX, startY, endX, endY, steps})
steps += int(n)
startX = endX
startY = endY
}
if rows == 0 {
edges1 = e
} else if rows == 1 {
edges2 = e
}
rows++
}
minDistance := math.MaxInt
for _, e1 := range edges1 {
for _, e2 := range edges2 {
_, _, steps, c := Crosses(e1, e2)
// so the steps to get to the cross is steps to get to e1 + steps to get to e2 + steps to get to cross (from e1) + steps to get to cross (from e2)
if c {
if steps+e1.steps+e2.steps < minDistance {
minDistance = steps + e1.steps + e2.steps
}
}
}
}
fmt.Println(minDistance)
} |
import dill
class TextAnalyticsFunctions:
def __init__(self, sdg):
self.sdg = sdg
self.model_type = None
self.model = None
def train(self, training_text, training_labels):
"""
Train model using set of text and expected labels.
Parameters:
- training_text (list or array-like): Input features.
- training_labels (list or array-like): Target labels (binary).
"""
if self.model_type == "rules":
self.model = "ignore"
elif self.model_type == "ml":
self.model = self.train_ml_model(training_text, training_labels)
else:
raise ValueError(
"Invalid model type. Supported types are 'rules' and 'ml'."
)
def predict(self, text):
"""
Generate SDG predictions for a piece of text using an NLP model.
Parameters:
- text (str): A string representing the outline or course description
for which predictions are to be made.
Returns:
dict: A dictionary containing the model's prediction and additional metadata.
The dict contains the SDG that is predicted to belong to the text and metadata
that provides supporting details that led to the positive prediction. This
could include a confidence score that passed a certain threshold,
a span of text that matches a keyword associated with an SDG or other details.
Negative predictions should not be included in the list.
Example:
>>> outline = "This is a sample outline for testing purposes."
>>> prediction = main(outline)
>>> print(prediction)
{
"category": "SDG-8",
"prediction": 0,
"metadata": {
"confidence": 0.6,
"spans": [[16, 34, "test"]],
"other": {} # Other information to include
}
"""
if self.model is None:
raise ValueError("Model not trained. Call train() first.")
if self.model_type == "rules":
prediction, metadata = self.predict_rules_model(text)
elif self.model_type == "ml":
prediction, metadata = self.predict_ml_model(text)
else:
raise ValueError(
"Invalid model type. Supported types are 'rules' and 'ml'."
)
return dict(category=self.sdg, prediction=prediction, metadata=metadata)
def save(self, file_path):
"""
Save the entire class to a file.
Parameters:
- file_path (str): File path to save the model.
"""
with open(file_path, "wb") as file:
dill.dump(self, file)
def __repr__(self):
return f"{self.sdg}__{self.model_type}__{self.model}" |
import Component from '@ember/component';
import { computed, set } from '@ember/object';
import { addObserver } from '@ember/object/observers';
import { not, and } from '@ember/object/computed';
import { isPresent } from '@ember/utils';
import { camelize } from '@ember/string';
import { htmlSafe } from '@ember/template';
import { scheduleOnce, next } from '@ember/runloop';
import { Promise } from 'rsvp';
import { layout, attribute, className, classNames } from '@ember-decorators/component';
import { waitForTransitionEnd } from '../../utils';
import { Dimensions } from '../../constants';
import template from './template';
type VoidCallback = () => void;
/**
* The UiCollapse component provides the base mechanics to smoothly collapse/expand a block element.
*/
@classNames('ui-collapse')
@layout(template)
export default class UiCollapse extends Component {
/**
* Toggles whether the element is expanded or collapsed.
*/
public collapsed = true;
/**
* An optional callback that will run when the element first begins to collapse.
*/
public onHide?: VoidCallback;
/**
* An optional callback that will run when the element finishes being collapsed.
*/
public onHidden?: VoidCallback;
/**
* An optional callback that will run when the element first begins to expand.
*/
public onShow?: VoidCallback;
/**
* An optional callback that will run when the element finishes being expanded.
*/
public onShown?: VoidCallback;
/**
* The axis that the collapse/expand will occur on. Can be either "height" or "width".
*/
@className
public collapseDimension = Dimensions.Height;
/**
* This can be set to a value > 0 if a custom expanded height/width pixel value is needed.
*/
public expandedSize?: number;
/**
* This can be set to a value > 0 if a custom collapsed height/width pixel value is needed.
*/
public collapsedSize = 0;
/**
* The UiCollapse component sets a `height` or `width` style on the collapsing element
* in order to provide a destination value for the CSS transition to move to. The inline
* value is typically removed when no longer needed but if you want it to keep it around
* for whatever reason you can set this to false.
*/
public resetSizeBetweenTransitions = true;
/**
* Whether the component is actively undergoing a transition.
*
* @protected
*/
@className('collapsing')
transitioning = false;
/**
* The calculated size for either width or height that the element will have when
* the transition is finished. This gets written as an inline style value for the
* element.
*
* @protected
*/
transitioningSize?: number;
/**
* Most likely, the "transitionend" event will be used to indicate that the
* collapse/expand has finished. This is a backup timeout if for whatever
* reason that doesn't happen.
*
* @protected
*/
transitionDuration = 350;
/**
* An internal flag that will always be the opposite value of collapsed, so, it will
* be true if the element is expanded and false otherwise. The change occurs on the
* leading edge of the animation.
*
* @protected
*/
active = false;
@className('collapse')
@not('transitioning')
protected declare notTransitioning: boolean;
@className('show')
@and('notTransitioning', 'active')
protected declare showContent: boolean;
@attribute
@computed('collapseDimension', 'transitioningSize')
get style() {
return typeof this.transitioningSize === 'number'
? htmlSafe(`${this.collapseDimension}: ${this.transitioningSize}px;`)
: undefined;
}
getExpandedSize(action: 'show' | 'hide') {
if (isPresent(this.expandedSize)) {
return this.expandedSize;
}
const prefix = action === 'show' ? 'scroll' : 'offset';
const propName = camelize(`${prefix}-${this.collapseDimension}`) as
| 'scrollHeight'
| 'scrollWidth'
| 'offsetHeight'
| 'offsetWidth';
return (this.element as HTMLElement)[propName];
}
async show() {
if (typeof this.onShow === 'function') {
this.onShow();
// The purpose of this here is to ensure that anything which might have been queued
// up to render as a result of calling onShow will be rendered before we move on
// to calculate the size of the container.
await new Promise((resolve) => scheduleOnce('afterRender', null, resolve));
}
set(this, 'transitioning', true);
set(this, 'transitioningSize', this.collapsedSize);
set(this, 'active', true);
await new Promise((resolve) => next(null, resolve));
set(this, 'transitioningSize', this.getExpandedSize('show'));
await waitForTransitionEnd(this.element, this.transitionDuration);
if (this.isDestroyed) {
return;
}
set(this, 'transitioning', false);
if (this.resetSizeBetweenTransitions) {
set(this, 'transitioningSize', undefined);
}
this.onShown?.();
}
async hide() {
this.onHide?.();
set(this, 'transitioning', true);
set(this, 'transitioningSize', this.getExpandedSize('hide'));
set(this, 'active', false);
await new Promise((resolve) => next(null, resolve));
set(this, 'transitioningSize', this.collapsedSize);
await waitForTransitionEnd(this.element, this.transitionDuration);
if (this.isDestroyed) {
return;
}
set(this, 'transitioning', false);
if (this.resetSizeBetweenTransitions) {
set(this, 'transitioningSize', undefined);
}
this.onHidden?.();
}
_onCollapsedChange() {
if (this.collapsed !== this.active) {
return;
} else if (this.collapsed) {
this.hide();
} else {
this.show();
}
}
_updateCollapsedSize() {
if (!this.resetSizeBetweenTransitions && this.collapsed && !this.transitioning) {
set(this, 'transitioningSize', this.collapsedSize);
}
}
_updateExpandedSize() {
if (!this.resetSizeBetweenTransitions && !this.collapsed && !this.transitioning) {
set(this, 'transitioningSize', this.expandedSize);
}
}
// eslint-disable-next-line ember/classic-decorator-hooks
init() {
super.init();
set(this, 'active', !this.collapsed);
// eslint-disable-next-line ember/no-observers
addObserver(this, 'collapsed', this, this._onCollapsedChange);
// eslint-disable-next-line ember/no-observers
addObserver(this, 'collapsedSize', this, this._updateCollapsedSize);
// eslint-disable-next-line ember/no-observers
addObserver(this, 'expandedSize', this, this._updateExpandedSize);
}
} |
package com.weit.presentation.ui.journal.update.content
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.google.android.gms.maps.model.LatLng
import com.weit.domain.model.journal.TravelJournalContentUpdateInfo
import com.weit.domain.usecase.coordinate.GetStoredCoordinatesUseCase
import com.weit.domain.usecase.image.PickImageUseCase
import com.weit.domain.usecase.journal.UpdateTravelJournalContentUseCase
import com.weit.presentation.model.journal.TravelJournalContentUpdateDTO
import com.weit.presentation.model.post.place.PlacePredictionDTO
import com.weit.presentation.model.post.place.SelectPlaceDTO
import com.weit.presentation.ui.util.MutableEventFlow
import com.weit.presentation.ui.util.asEventFlow
import com.weit.presentation.ui.util.toMillis
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.time.LocalDate
class TravelJournalContentUpdateViewModel @AssistedInject constructor(
@Assisted val travelJournalContentUpdateDTO: TravelJournalContentUpdateDTO,
private val updateTravelJournalContentUseCase: UpdateTravelJournalContentUseCase,
private val getStoredCoordinatesUseCase: GetStoredCoordinatesUseCase
): ViewModel() {
@AssistedFactory
interface TravelJournalContentUpdateFactory{
fun create(travelJournalContentUpdateDTO: TravelJournalContentUpdateDTO) : TravelJournalContentUpdateViewModel
}
val content = MutableStateFlow(travelJournalContentUpdateDTO.content)
private val _date = MutableStateFlow(travelJournalContentUpdateDTO.travelJournalContentDate)
val date : StateFlow<LocalDate> get() = _date
private val _placeName = MutableStateFlow(travelJournalContentUpdateDTO.placeName)
val placeName : StateFlow<String?> get() = _placeName
private val _placeId = MutableStateFlow(travelJournalContentUpdateDTO.placeID)
val placeId : StateFlow<String?> get() = _placeId
private val _images = MutableStateFlow(travelJournalContentUpdateDTO.updateContentImages)
val images : StateFlow<List<String>> get() = _images
private val _deleteImages = MutableStateFlow<List<Long>>(emptyList())
val deleteImages : StateFlow<List<Long>> get() = _deleteImages
private val _event = MutableEventFlow<Event>()
val event = _event.asEventFlow()
fun onPickDailyDate() {
viewModelScope.launch {
val date = travelJournalContentUpdateDTO.travelJournalContentDate
val minDateMillis = travelJournalContentUpdateDTO.travelJournalStart.toMillis()
val maxDateMillis = travelJournalContentUpdateDTO.travelJournalEnd.toMillis()
Log.d("jomi", "$minDateMillis / $maxDateMillis")
_event.emit(Event.ShowDailyDatePicker(date, minDateMillis, maxDateMillis ))
}
}
fun onDailyDateSelected(year: Int, monthOfYear: Int, dayOfMonth: Int) {
viewModelScope.launch {
val selectedDate = LocalDate.of(year, monthOfYear + 1, dayOfMonth)
_date.emit(selectedDate)
}
}
fun onDatePickerDismissed() {
viewModelScope.launch {
_event.emit(Event.ClearDatePickerDialog)
}
}
fun onSelectPictures(pickImageUseCase: PickImageUseCase) {
viewModelScope.launch {
val selectedPicture = pickImageUseCase()
val currentImage = images.value
_images.emit(currentImage + selectedPicture)
}
}
fun deletePicture(deleteImage: String, newImages : List<String>){
viewModelScope.launch {
_images.emit(newImages)
val deleteImageIndex = travelJournalContentUpdateDTO.updateContentImages.indexOf(deleteImage)
val currentDeleteImages = deleteImages.value
val newDeleteImages = currentDeleteImages.toMutableList().plus(travelJournalContentUpdateDTO.updateContentImageIds[deleteImageIndex])
_deleteImages.emit(newDeleteImages)
}
}
private suspend fun getStoredCoordinates(date: LocalDate?): List<LatLng> {
if (date == null) {
return emptyList()
}
val start: Long = date.toMillis()
val end = date.plusDays(1).toMillis()
return getStoredCoordinatesUseCase(start, end).map { LatLng(it.lat.toDouble(), it.lng.toDouble()) }
}
fun updateTravelJournalContent() {
viewModelScope.launch{
val newDate = date.value
val newContent = content.value
val newPlaceId = placeId.value
val allImage = images.value
val newImages = allImage.filterNot { travelJournalContentUpdateDTO.updateContentImages.contains(it) }
val newDeleteImages = deleteImages.value
val latLngs = getStoredCoordinates(newDate)
if (newContent.isNullOrBlank()) {
_event.emit(Event.NoContentData)
return@launch
}
if (allImage.isEmpty()) {
_event.emit(Event.NoImagesData)
return@launch
}
val result = updateTravelJournalContentUseCase(
travelJournalContentUpdateDTO.travelJournalId,
travelJournalContentUpdateDTO.travelJournalContentId,
TravelJournalContentUpdateInfo(
newContent,
newPlaceId,
latLngs.map { it.latitude },
latLngs.map { it.longitude },
newDate.toString(),
newImages.map {
it.split("/").last() + IMAGE_EXTENSION_WEBP
},
newDeleteImages
),
newImages
)
if (result.isSuccess) {
_event.emit(Event.SuccessUpdate(travelJournalContentUpdateDTO.travelJournalId))
} else {
//todo 에러처리
Log.d("update travel",
"update Travel Journal Fail : ${result.exceptionOrNull()}")
}
}
}
fun showSelectedPlace() {
viewModelScope.launch {
val dto = TravelJournalContentUpdateDTO(
travelJournalContentUpdateDTO.travelJournalId,
travelJournalContentUpdateDTO.travelJournalContentId,
travelJournalContentUpdateDTO.travelJournalStart,
travelJournalContentUpdateDTO.travelJournalEnd,
date.value,
content.value,
placeName.value,
placeId.value,
travelJournalContentUpdateDTO.latitude,
travelJournalContentUpdateDTO.longitude,
images.value,
deleteImages.value
)
_event.emit(Event.ShowSelectPlace(dto, emptyList()))
}
}
fun updatePlace(dto: SelectPlaceDTO) {
viewModelScope.launch {
_placeId.emit(dto.placeId)
_placeName.emit(dto.name)
}
}
sealed class Event {
data class ShowDailyDatePicker(
val currentDate: LocalDate?,
val minDateMillis: Long,
val maxDateMillis: Long,
) : Event()
data class ShowSelectPlace(
val updateDTO: TravelJournalContentUpdateDTO,
val placePredictionDTO : List<PlacePredictionDTO>
): Event()
object ClearDatePickerDialog : Event()
object NoContentData : Event()
object NoImagesData : Event()
data class SuccessUpdate(
val travelJournalId: Long
) : Event()
}
companion object {
private const val IMAGE_EXTENSION_WEBP = ".webp"
fun provideFactory(
assistedFactory: TravelJournalContentUpdateFactory,
travelJournalContentUpdateDTO: TravelJournalContentUpdateDTO
) : ViewModelProvider.Factory = object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return assistedFactory.create(travelJournalContentUpdateDTO) as T
}
}
}
} |
<?php
namespace App\Notifications;
use App\Models\Project;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class ProjectReadyToNOT extends Notification
{
use Queueable;
private $project = null;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct(Project $project)
{
$this->project = $project;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject("Project Ready to NOT")
->line('A project has been marked ready to NOT.')
->action('Notification Action', url(route('project::view', $this->project->id)))
->line('Please review and take actions');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
} |
classdef Joint < awi.fe.FEBaseClass
%Joint Describes a joint connecting two coincident nodes for use in a
%finite element model.
%
% The definition of the 'Joint' object matches that of the RJOINT bulk
% data type from MSC.Nastran.
%Primary Properties
properties
%Element identification number
EID
%ID number of the GA node
GA
%ID number of the GB node
GB
%Constrained DOFs in the global coordinate system at GB
CB
end
%Store a reference to the 'awi.fe' objects
properties (Hidden = true)
%Handle to the 'awi.fe.Node' objects that the joint connect to
Nodes
end
methods % set / get
function set.EID(obj, val) %set.EID
%set.EID Set method for the property 'EID'.
%
% Passes the value straight to the inherited 'ID' property
% which will validate and store the ID number.
obj.ID = val;
end
function set.GA(obj, val) %set.GA
validateID(obj, val, 'GA')
obj.GA = val;
end
function set.GB(obj, val) %set.GB
validateID(obj, val, 'GB')
obj.GB = val;
end
function set.CB(obj, val) %set.CB
validateDOF(obj, val, 'CB')
if ischar(val)
val = str2double(val);
end
obj.CB = val;
end
function set.Nodes(obj, val) %set.Nodes
%set.Nodes Set method for the 'Nodes' property.
%
% 'Nodes' must be a [2,1] vector of 'awi.fe.Node' objects.
assert(numel(val) <= 2, sprintf('An object of class ''%s'' ', ...
'can only connect to 2 nodes.', class(obj)));
validateattributes(val, {'awi.fe.Node'}, {'column', 'nonempty'}, ...
class(obj), 'Nodes')
obj.Nodes = val;
end
function val = get.GA(obj) %get.GA
%get.GA Get method for the property 'GA'.
%
% If the object has been assigned a handle to its 'awi.fe.Node'
% object then always use their ID numbers, else use GA/GB.
if isempty(obj.Nodes)
val = obj.GA;
else
val = obj.Nodes(1).GID;
end
end
function val = get.GB(obj) %get.GB
%get.GB Get method for the property 'GB'.
%
% If the object has been assigned a handle to its 'awi.fe.Node'
% object then always use their ID numbers, else use GA/GB.
if numel(obj.Nodes) == 2
val = obj.Nodes(2).GID;
else
val = obj.GB;
end
end
end
methods % construction
function obj = Joint
%Make a note of the property names
addFEProp(obj, 'EID', 'GA', 'GB', 'CB');
end
end
methods % visualisation
function hg = drawElement(obj, ha)
%drawElement Draws the Joint objects as a set of discrete
%markers.
%
% Accepts an array of objects.
hg = [];
%Grab the node objects
jNodes = {obj.Nodes};
jNodes(cellfun(@isempty, jNodes)) = [];
jNodes = horzcat(jNodes{:});
if isempty(jNodes)
return
end
jCoords = [jNodes(1, :).X];
hg = line(ha, jCoords(1, :), jCoords(2, :), jCoords(3, :), ...
'LineStyle', 'none', ...
'Marker' , 's' , ...
'MarkerFaceColor', 'm', ...
'MarkerEdgeColor', 'k', ...
'Tag', 'Joints');
end
end
methods % writing data in MSC.Nastran format
function writeToFile(obj, fid, bComment)
%writeToFile Write the data for the 'awi.fe.Joint' object into
%a text file using the format of the MSC.Nastran RJOINT bulk
%data entry.
%By default, do not close the file
bClose = false;
if nargin < 2 %Ask the user for the file
fName = awi.fe.FEBaseClass.getBulkDataFile;
bClose = true;
fid = fopen(fName, 'w');
end
if nargin < 3 %Comments by standard
bComment = true;
end
if bComment %Helpful comments?
comment = ['RJOINT : Defines a rigid joint element ', ...
'connecting two coinciding grid points.'];
awi.fe.FEBaseClass.writeComment(comment, fid);
end
awi.fe.FEBaseClass.writeColumnDelimiter(fid, '8');
nObj = numel(obj);
%Card name
nam = repmat({'RJOINT'}, [1, nObj]);
%Set up the format for printing
data = [nam ; {obj.ID} ; {obj.GA} ; {obj.GB} ; {obj.CB}];
%Write in 16-character column width as standard
format = '%-8s%-8i%-8i%-8i%-8i\r\n';
%Write the data to the file
fprintf(fid, format, data{:});
if bClose %Close the file?
fclose(fid);
end
end
end
end |
import os
import unittest
from datetime import datetime
from managers.file_based_thread_manager import FileBasedThreadManager
from models.thread import Message, SenderType, Thread
class TestFileBasedThreadManager(unittest.TestCase):
"""
Unit tests for the FileBasedThreadManager class.
"""
def setUp(self):
"""
Set up test data for FileBasedThreadManager tests.
"""
self.test_file_path = "test_threads.json"
self.thread_manager = FileBasedThreadManager(self.test_file_path)
self.test_thread_id = "thread123"
self.test_user_id = "user123"
self.test_messages = [
Message(role="user", content="Hello", timestamp=datetime.now()),
Message(role="assistant", content="Hi there!", timestamp=datetime.now()),
]
self.thread = Thread(
thread_id=self.test_thread_id,
user_id=self.test_user_id,
messages=self.test_messages,
last_updated=datetime.now(),
)
def tearDown(self):
"""
Clean up after tests.
"""
if os.path.exists(self.test_file_path):
os.remove(self.test_file_path)
def test_save_thread(self):
"""
Test the save_thread method of FileBasedThreadManager.
"""
self.thread_manager.save_thread(self.thread)
loaded_thread = self.thread_manager.load_thread_by_thread_id(
self.test_thread_id
)
self.assertEqual(self.thread, loaded_thread)
def test_get_threads_by_user_and_companion(self):
"""
Test the get_threads_by_user_and_companion method of FileBasedThreadManager.
"""
# Save a test thread to ensure there is at least one thread for the user
self.thread_manager.save_thread(self.thread)
# Setup additional threads with different sender_ids
additional_thread = Thread(
thread_id="thread456",
user_id=self.test_user_id,
messages=[
Message(
sender_id=self.test_user_id,
content="User message",
timestamp=datetime.now(),
sender_type=SenderType.USER,
),
Message(
sender_id="companion_id",
content="Companion message",
timestamp=datetime.now(),
sender_type=SenderType.COMPANION,
),
],
last_updated=datetime.now(),
)
self.thread_manager.save_thread(additional_thread)
# Retrieve threads for the test user and companion
loaded_threads = self.thread_manager.get_threads_by_user_and_companion(
self.test_user_id, "companion_id"
)
# Assert that the returned list includes only the appropriate thread
self.assertEqual(len(loaded_threads), 1)
self.assertIn("thread456", [thread.thread_id for thread in loaded_threads])
def test_get_threads_by_user_id(self):
"""
Test the get_threads_by_user_id method of FileBasedThreadManager.
"""
# Save a test thread to ensure there is at least one thread for the user
self.thread_manager.save_thread(self.thread)
# Retrieve threads for the test user
loaded_threads = self.thread_manager.get_threads_by_user_id(self.test_user_id)
# Assert that the returned list is not empty
self.assertTrue(loaded_threads)
# Assert that all returned threads belong to the test user
for thread in loaded_threads:
self.assertEqual(thread.user_id, self.test_user_id)
def test_load_thread_by_thread_id(self):
"""
Test the load_thread_by_thread_id method of FileBasedThreadManager.
"""
self.thread_manager.save_thread(self.thread)
loaded_thread = self.thread_manager.load_thread_by_thread_id(
self.test_thread_id
)
self.assertEqual(self.thread, loaded_thread)
def test_delete_thread(self):
"""
Test the delete_thread method of FileBasedThreadManager.
"""
self.thread_manager.save_thread(self.thread)
self.thread_manager.delete_thread(self.test_thread_id)
loaded_thread = self.thread_manager.load_thread_by_thread_id(
self.test_thread_id
)
self.assertIsNone(loaded_thread)
if __name__ == "__main__":
unittest.main() |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('manage_stocks', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('warehouse_id');
$table->unsignedBigInteger('product_id');
$table->foreign('warehouse_id')->references('id')
->on('warehouses')
->onUpdate('cascade')
->onDelete('cascade');
$table->foreign('product_id')->references('id')
->on('products')
->onUpdate('cascade')
->onDelete('cascade');
$table->double('quantity');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('manage_stocks');
}
}; |
/**
* Importing npm packages
*/
import { ArgsType, Field, InputType, Int, PartialType } from '@nestjs/graphql';
/**
* Importing user defined packages
*/
import { addField, updateField } from './common.args';
/**
* Defining types
*/
/**
* Declaring the constants
*/
@InputType()
export class AddFoodInput {
@Field(() => Int, { description: 'Start time of eating in 24 hr format HHMM' })
time: number;
@Field(() => [String], { description: 'Items in the menu' })
items: string[];
}
@InputType()
export class UpdateFoodInput extends PartialType(AddFoodInput) {}
@ArgsType()
export class AddFoodArgs extends addField(AddFoodInput) {}
@ArgsType()
export class UpdateFoodArgs extends updateField(UpdateFoodInput) {} |
package com.dicosoluciones.changeplayer.playermanager.data.di
import android.content.Context
import androidx.room.Room
import com.dicosoluciones.changeplayer.playermanager.data.PlayerDao
import com.dicosoluciones.changeplayer.playermanager.data.PlayerDatabase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class DatabaseModule {
@Provides
fun providePlayerDao(playerDatabase: PlayerDatabase):PlayerDao {
return playerDatabase.playerDao()
}
@Provides
@Singleton
fun providePlayerDatabase(@ApplicationContext appContext: Context): PlayerDatabase {
return Room.databaseBuilder(appContext, PlayerDatabase::class.java, "PlayerDatabase").build()
}
} |
#include <iostream>
#include "/opt/homebrew/include/libtorrent/session.hpp"
#include "/opt/homebrew/include/libtorrent/torrent_info.hpp"
#include "/opt/homebrew/include/libtorrent/announce_entry.hpp"
#include "cxxopts.hpp"
int main(int argc, char* argv[]) {
cxxopts::Options options("MyProgram", " - example command line options");
std::string source_path;
std::string destination_path;
options.add_options()
("h,help", "Print help. " )
("s,source", "source file", cxxopts::value<std::string>(source_path))
("d,destination", "destination file", cxxopts::value<std::string>(destination_path));
auto result = options.parse(argc, argv);
if (result.count("help")) {
std::cout << options.help() << std::endl;
return 0;
}
if (result.count("source")) {
std::cout<<"source path: " <<source_path << std::endl;
}
if (result.count("destination")) {
std::cout<<"destination path: " <<destination_path << std::endl;
}
libtorrent::torrent_info ti(source_path );
std::cout << "Torrent name: " << ti.name() << std::endl;
std::cout << "Piece length: " << ti.piece_length() << " bytes" << std::endl;
const std::vector<libtorrent::announce_entry>& trackers = ti.trackers();
std::cout << "Trackers:" << std::endl;
for (const auto& tracker : trackers) {
std::cout << " " << tracker.url << std::endl;
}
//} catch (const std::exception& e) {
// std::cerr << "Error: " << e.what() << std::endl;
// return 1;
//}
//get peers from the tracker
libtorrent::session ses;
libtorrent::add_torrent_params params;
params.ti = std::make_shared <libtorrent::torrent_info>(ti);
libtorrent::torrent_handle th = ses.add_torrent(params);
//start the session
ses.start_upnp();
while(true){
ses.post_torrent_updates();
libtorrent::torrent_status status = th.status();
// Print information about the number of peers from the tracker
std::cout << "Number of peers from tracker: " << status.list_peers << std::endl;
std::vector<libtorrent::peer_info> peers;
th.get_peer_info(peers);
for(const auto&peer : peers){
std::cout << "Peer IP : "<<peer.ip.address().to_string() <<", Port: "<< peer.ip.port() << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return 0;
} |
//In the Swift file where you want to access location data, import Core Location:
import CoreLocation
// Create a CLLocationManager instance and set its delegate to receive location updates.
//We typically do this in a view controller:
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
}
//Request permission from the user to access their location:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
let speed = location.speed // Speed in meters per second
if speed >= 0 {
// Speed is a positive value indicating the device is moving
print("Current speed: \(speed) m/s")
} else {
// Speed is an invalid value (-1) indicating it could not be determined
print("Speed could not be determined")
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if CLLocationManager.locationServicesEnabled() {
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
locationManager.requestWhenInUseAuthorization() // or requestAlwaysAuthorization()
case .restricted, .denied:
// Handle restriction or denial
case .authorizedWhenInUse, .authorizedAlways:
// Permission granted
locationManager.startUpdatingLocation()
@unknown default:
fatalError()
}
} else {
// Location services are not enabled
}
}
func sendLocationToServer(latitude: Double, longitude: Double) {
// Create a URL with your FastAPI server endpoint
guard let url = URL(string: "http://0.0.0.0:5000/receive_location") else { # url must be changed here to uvicorn link
print("Invalid URL")
return
}
// Create a JSON payload with latitude and longitude
let locationData: [String: Any] = ["lat": latitude, "long": longitude]
// Convert JSON to Data
guard let jsonData = try? JSONSerialization.data(withJSONObject: locationData) else {
print("Failed to serialize JSON data")
return
}
// Create a POST request
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
// Send the request
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error: \(error)")
} else if let data = data {
if let responseString = String(data: data, encoding: .utf8) {
print("Response: \(responseString)")
}
}
}.resume()
}
// Implement the CLLocationManagerDelegate methods to handle location updates:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
// Use latitude and longitude
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
// Handle failure to get location
}
//To conserve battery, start and stop location updates as needed:
locationManager.startUpdatingLocation()
//When you no longer need to receive location updates, call:
locationManager.startUpdatingLocation() |
import 'package:delayed_display/delayed_display.dart';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import '../../compononts/brackgound.dart';
import '../../config.dart';
import 'second_page .dart';
class TabFristPage extends StatefulWidget {
const TabFristPage({Key key}) : super(key: key);
@override
State<TabFristPage> createState() => _TabFristPageState();
}
class _TabFristPageState extends State<TabFristPage> {
final AudioPlayer player1 = AudioPlayer();
final AudioPlayer player2 = AudioPlayer();
final AudioPlayer player3 = AudioPlayer();
final AudioPlayer player4 = AudioPlayer();
Future loadMp3() async {
await player1.setAsset('assets/mp3/level1.mp3');
await player2.setAsset('assets/mp3/level2.mp3');
await player3.setAsset('assets/mp3/level3.mp3');
await player4.setAsset('assets/mp3/level4.mp3');
}
@override
void dispose() {
if (player1.playing) {
player1.stop();
}
if (player3.playing) {
player3.stop();
}
if (player2.playing) {
player2.stop();
}
if (player4.playing) {
player4.stop();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
double screenHeight = MediaQuery.of(context).size.height;
double screenWidth = MediaQuery.of(context).size.width;
return Scaffold(
backgroundColor: kPrimeryColor2,
body: Background(
child: Stack(
children: [
Container(
margin: EdgeInsets.only(top: screenHeight < 1000 ? 230 : 290),
padding: const EdgeInsets.symmetric(horizontal: 16),
width: screenWidth,
child: DelayedDisplay(
delay: const Duration(milliseconds: 300),
child: Text(
"Wählt entsprechend eurem Spielniveau euer Level aus. Je niedriger das Level, desto langsamer ist der Rhythmus. Schafft ihr es, euch zum Rockmusiker hochzuspielen und das höchste Level zu meistern?",
textAlign: TextAlign.justify,
style: TextStyle(fontSize: screenHeight < 1000 ? 18 : 22),
),
),
),
Positioned(
bottom: screenHeight < 1000 ? 385 : 520,
left: 0,
child: InkWell(
onTap: () async {
await loadMp3();
if (player2.playing) {
player2.stop();
}
if (player3.playing) {
player3.stop();
}
if (player4.playing) {
player4.stop();
}
if (!player1.playing) {
player1.play();
}else{
player1.stop();
}
},
child: DelayedDisplay(
delay: const Duration(milliseconds: 500),
child: Image.asset(
"assets/images/level1.png",
height: screenHeight < 1000 ? 210 : 280,
),
),
),
),
Positioned(
bottom: screenHeight < 1000 ? 385 : 520,
right: 0,
child: InkWell(
onTap: () async {
await loadMp3();
if (player1.playing) {
player1.stop();
}
if (player3.playing) {
player3.stop();
}
if (player4.playing) {
player4.stop();
}
if (!player2.playing) {
player2.play();
}else{
player2.stop();
}
},
child: DelayedDisplay(
delay: const Duration(milliseconds: 700),
child: Image.asset(
"assets/images/level2.png",
height: screenHeight < 1000 ? 210 :280,
),
),
),
),
Positioned(
bottom: screenHeight < 1000 ? 170 : 230,
left: 0,
child: InkWell(
onTap: () async {
await loadMp3();
if (player1.playing) {
player1.stop();
}
if (player2.playing) {
player2.stop();
}
if (player4.playing) {
player4.stop();
}
if (!player3.playing) {
player3.play();
}else{
player3.stop();
}
},
child: DelayedDisplay(
delay: const Duration(milliseconds: 900),
child: Image.asset(
"assets/images/level3.png",
height: screenHeight < 1000 ? 210 : 280,
),
),
),
),
Positioned(
bottom: screenHeight < 1000 ? 174 : 230,
right: 0,
child: InkWell(
onTap: () async {
await loadMp3();
if (player1.playing) {
player1.stop();
}
if (player3.playing) {
player3.stop();
}
if (player2.playing) {
player2.stop();
}
if (!player4.playing) {
player4.play();
}else{
player4.stop();
}
},
child: DelayedDisplay(
delay: const Duration(milliseconds: 1100),
child: Image.asset(
"assets/images/level4.png",
height: screenHeight < 1000 ? 210 : 280,
),
),
),
),
Positioned(
bottom: screenHeight < 1000 ? 290 :380,
left: 0,
child: InkWell(
onTap: () {},
child: DelayedDisplay(
delay: const Duration(milliseconds: 1500),
child: Image.asset(
"assets/images/onion.png",
height: screenHeight < 1000 ? 130 : 170,
),
),
),
),
Positioned(
bottom: 20,
left: 30,
child: InkWell(
onTap: () {},
child: DelayedDisplay(
delay: const Duration(milliseconds: 1500),
child: Image.asset(
"assets/images/act1.png",
height: screenHeight < 1000 ? 140 : 170,
),
),
),
),
Positioned(
bottom: 20,
right: 30,
child: InkWell(
onTap: () {},
child: DelayedDisplay(
delay: const Duration(milliseconds: 1500),
child: Image.asset(
"assets/images/act2.png",
height: screenHeight < 1000 ? 140 : 170,
),
),
),
),
Padding(
padding: EdgeInsets.only(bottom: screenHeight < 1000 ? 90 : 120),
child: Align(
alignment: Alignment.bottomCenter,
child: InkWell(
onTap: () {
if (player1.playing) {
player1.stop();
}
if (player3.playing) {
player3.stop();
}
if (player2.playing) {
player2.stop();
}
if (player4.playing) {
player4.stop();
}
Navigator.push(
context,
MaterialPageRoute(
builder: ((context) => const TabSecondPage())));
},
child: DelayedDisplay(
delay: const Duration(milliseconds: 1500),
child: Image.asset(
"assets/images/nxt_btn.png",
height: screenHeight < 1000 ?60:80,
),
),
),
),
)
],
),
),
);
}
} |
# msc-thesis-scripts
Python scripts to reproduce results from my MSc thesis.
## STA/LTA trigger
An ensemble STA/LTA trigger is implemented in `stalta_trigger.py`. All
parameters can be set in `stalta_params.py`. This results in a "raw"
catalog that needs to be further processed. This can be achieved with the
script `merge_events.py` which takes a raw catalog as input and merges
all entries that belong to the same event, i.e. cleaning the raw catalog from
duplicates. All events in a catalog can be plotted by passing the cleaned
catalog to the script `plot_events_from_catalogue.py`. All catalogs are saved
in the `output/` folder.
## Extracting features for clustering
For my MSc thesis I extracted two different types of features related to
velocities and signal coherence. There are two corresponding scripts:
`extract_features_velo.py` and `extract_features_covmat.py`. The extracted
features are stored in the `output/` folder.
## Information on accessing AWS data
### Mount EBS
Following are the steps I used to mount an EBS volume. Before that, the volume
needs to be created and attached to the EC2 instance. This can be done via the
AWS web interface. Subsequently, it should show up when running `lsblk`.
Usually there is not yet a file system on the new EBS volume. This can be
checked by running `file -s /dev/NAME`, where NAME is the name of the EBS
volume as shown when running `lsblk`. I usually use the ext4 file system,
e.g. `mkfs -t ext4 /dev/NAME`. The volume can then be mounted to the
filesystem. I usually run:
```
mkdir /dataStorage
mount /dev/xvdf /dataStorage
df -hT
```
The last command checks if the EBS volume was successfully mounted.
### Download data from S3 to EBS
For this, the awscli must be installed on the instance.
```
aws s3 cp bucket_name/ target_folder/ --options
```
For example:
* bucket_name = s3://rhoneglacier-eth/new/20200707/
* options: --recursive; --exclude “*”; --include "idas2_UTC_20200707_074*"
Of course you can use other options like the boto3 you used in your python scripts.
### NOTES:
* You need root access to read and write to the EBS volume
* You need the AWS key to access S3
* For the start: It would probably be really useful to have a bash script that:
* Creates EBS volume (Let's say G2 with 500 GB)
* Attaches EBS volume to instance
* Starts the instance
* Makes filesystem on EBS volume and mount
* Downloads one day of data to the EBS volume |
<?php declare(strict_types=1);
/**
* This file is part of the Yasumi package.
*
* Copyright (c) 2015 - 2020 AzuyaLabs
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Sacha Telgenhof <me@sachatelgenhof.com>
*/
namespace Yasumi\tests\Ukraine;
use ReflectionException;
use Yasumi\Holiday;
/**
* Class UkraineTest
* @package Yasumi\tests\Ukraine
*/
class UkraineTest extends UkraineBaseTestCase
{
/**
* @var int year random year number used for all tests in this Test Case
*/
protected $year;
/**
* Tests if all official holidays in Ukraine are defined by the provider class
* @throws ReflectionException
*/
public function testOfficialHolidays(): void
{
$holidays = [
'newYearsDay',
'internationalWorkersDay',
'christmasDay',
'easter',
'pentecost',
'internationalWomensDay',
'victoryDay',
];
if ($this->year >= 1996) {
$holidays[] = 'constitutionDay';
}
if ($this->year >= 1991) {
$holidays[] = 'independenceDay';
}
if ($this->year >= 2015) {
$holidays[] = 'defenderOfUkraineDay';
}
if ($this->year < 2018) {
$holidays[] = 'secondInternationalWorkersDay';
}
if ($this->year >= 2017) {
$holidays[] = 'catholicChristmasDay';
}
$this->assertDefinedHolidays(
$holidays,
self::REGION,
$this->year,
Holiday::TYPE_OFFICIAL
);
}
/**
* Tests if all observed holidays in Ukraine are defined by the provider class
* @throws ReflectionException
*/
public function testObservedHolidays(): void
{
$this->assertDefinedHolidays([], self::REGION, $this->year, Holiday::TYPE_OBSERVANCE);
}
/**
* Tests if all seasonal holidays in Ukraine are defined by the provider class
* @throws ReflectionException
*/
public function testSeasonalHolidays(): void
{
$this->assertDefinedHolidays([], self::REGION, $this->year, Holiday::TYPE_SEASON);
}
/**
* Tests if all bank holidays in Ukraine are defined by the provider class
* @throws ReflectionException
*/
public function testBankHolidays(): void
{
$this->assertDefinedHolidays([], self::REGION, $this->year, Holiday::TYPE_BANK);
}
/**
* Tests if all other holidays in Ukraine are defined by the provider class
* @throws ReflectionException
*/
public function testOtherHolidays(): void
{
$this->assertDefinedHolidays([], self::REGION, $this->year, Holiday::TYPE_OTHER);
}
/**
* Initial setup of this Test Case
*/
protected function setUp(): void
{
$this->year = $this->generateRandomYear();
}
} |
<script setup>
import { ref, onMounted, computed } from 'vue';
import { useUserStore } from '../stores/user';
import { Plugins } from '@capacitor/core';
import { Camera, CameraResultType } from '@capacitor/camera';
import supabase from '../supabase';
const { DistancePlugin, ProfilePicture } = Plugins;
const store = useUserStore();
const user = ref(store.user);
const steps = ref('');
const imageData = ref('');
const totalWorkouts = ref('');
const profilePicURL = ref('');
const profilePicExists = ref('');
const enteredName = ref('What should we call you?');
const editEnteredName = ref(false);
const workouts = ref('');
const getDailySteps = async () => {
let data = await DistancePlugin.getTodaySteps();
steps.value = data;
};
const getTotalWorkoutCount = async () => {
const { count, error } = await supabase
.from('workouts')
.select('*', { count: 'exact', head: true })
.eq('user', user.value.id)
.eq('is_routine', false);
if (error) {
} else {
totalWorkouts.value = count;
}
};
// if (typeof window.capacitor !== 'undefined') {
const getDistance = async () => {
let result = await DistancePlugin.authorize();
// let data = await DistancePlugin.getDistance({ startDate: '2022/07/01' });
let workoutsFromIOS = await DistancePlugin.getWorkouts();
workouts.value = workoutsFromIOS;
};
const openCamera = async () => {
const image = await Camera.getPhoto({
quality: 100,
allowEditing: true,
resultType: CameraResultType.Base64,
});
const base64Data = image.base64String;
const fileName = `image-${user.value.id}.png`;
const binaryData = atob(base64Data);
const arrayBuffer = new ArrayBuffer(binaryData.length);
const uint8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < binaryData.length; i++) {
uint8Array[i] = binaryData.charCodeAt(i);
}
const blob = new Blob([arrayBuffer], { type: 'image/png' });
const { err } = await supabase.storage
.from('avatars')
.remove(`public/image-${user.value.id}.png`);
profilePicURL.value = null;
const { data, error } = await supabase.storage
.from('avatars')
.upload(`public/${fileName}`, blob);
if (error) {
} else {
getProfilePicture();
checkLinkExists();
}
};
const getProfilePicture = async () => {
const { data, error } = await supabase.storage
.from('avatars')
.getPublicUrl(`public/image-${user.value.id}.png`);
const avatarUrl = data.publicUrl;
const imgUrl = `${avatarUrl}?_t=${Date.now()}`;
profilePicURL.value = imgUrl;
};
const checkLinkExists = async () => {
try {
const response = await fetch(
`https://papqpygzqwwtbveqlnfm.supabase.co/storage/v1/object/public/avatars/public/image-${user.value.id}.png`,
{
method: 'HEAD',
}
);
profilePicExists.value = response.status;
} catch (error) {
return false;
}
};
const dynamicProfilePic = computed(() => {
return profilePicURL.value;
});
const addNameToUserDetails = async () => {
await supabase
.from('users')
.insert({
name: user.value.id,
})
.eq('id', user.value.id)
.select()
.then((response) => {
console.log(response);
});
};
onMounted(() => {
getDailySteps();
getTotalWorkoutCount();
getProfilePicture();
checkLinkExists();
});
// }
</script>
<template>
<div class="w-full h-full flex flex-col bg-gray-200">
<div class="w-full flex">
<div
class="h-[14.5rem] w-full bg-primary flex items-center p-8 pt-14 text-white relative"
>
<div class="w-2/3 h-full">
<h1
class="font-boldHeadline"
:class="totalWorkouts > 99 ? 'text-8xl' : 'text-9xl'"
>
{{ totalWorkouts }}
</h1>
</div>
<div class="w-1/3 flex flex-col h-full pt-2">
<p
v-if="totalWorkouts <= 1"
class="uppercase text-gray-400 text-xs font-boldHeadline"
>
workout
</p>
<p v-else class="uppercase text-gray-400 text-xs font-boldHeadline">
workouts
</p>
<p class="uppercase text-white text-xs font-boldHeadline">
completed
</p>
</div>
<p
class="absolute left-5 bottom-1 text-sm font-boldHeadline"
v-if="steps"
>
{{ Number(steps.totalSteps.toFixed()) }} steps today
</p>
<div
v-if="profilePicExists === 404"
@click="openCamera"
class="absolute h-24 w-24 rounded-full bg-primary right-8 -bottom-12 border-gray-200 border-4 flex items-center justify-center"
>
<i class="fa-solid fa-camera text-2xl"></i>
</div>
<div
v-else
class="absolute h-24 w-24 rounded-full bg-primary right-8 -bottom-12 border-gray-200 border-4 flex items-center justify-center"
>
<img
v-if="profilePicURL && profilePicExists !== 404"
:src="dynamicProfilePic"
@click="openCamera"
class="h-20 w-20 object-cover rounded-full"
alt=""
/>
</div>
</div>
</div>
<div class="w-full flex flex-col p-4 text-black">
<div class="">
<p class="font-boldHeadline text-lg">How you doing today?</p>
</div>
<!-- <div class="">
<p v-if="user.name">
Homer Simpson <i class="fa-solid fa-pencil ml-4"></i>
</p>
<div v-else>
<input type="text" v-model="enteredName" />
<i class="fa-solid fa-pencil ml-4"></i>
</div>
</div> -->
</div>
<form class="w-full text-black font-bold flex flex-col p-4">
<input type="text" placeholder="name" />
<input type="text" placeholder="name" />
<input type="text" placeholder="name" />
<input type="text" placeholder="name" />
</form>
</div>
</template> |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ComboBox - jQuery EasyUI Demo</title>
<link rel="stylesheet" type="text/css" href="../themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../themes/icon.css">
<link rel="stylesheet" type="text/css" href="demo.css">
<script type="text/javascript" src="../jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="../jquery.easyui.min.js"></script>
<script>
function loadData(){
/*
$('#cc').combobox({
url:'combobox_data.json',
valueField:'id',
textField:'text',
formatter:function(row){
var r="<font color=green>"+row.text+"</font>";
return r;
},
onSelect:function(re){
alert(re.id);
}
});
*/
$.ajax({
type: "GET",
url: "http://localhost/bypx/senddata.jsp",
dataType: "text",
success : function(data){
alert(data);
}
});
}
function setValue(){
$('#cc').combobox('setValue','CO');
}
function getValue(){
var val = $('#cc2').combobox('getValues');
alert(val);
}
function disable(){
$('#cc').combobox('disable');
}
function enable(){
$('#cc').combobox('enable');
}
</script>
</head>
<body>
<h2>ComboBox</h2>
<div class="demo-info">
<div class="demo-tip icon-tip"></div>
<div>Type in combobox to try auto complete.</div>
</div>
<div style="margin:10px 0;">
<a href="#" class="easyui-linkbutton" onclick="loadData()">LoadData</a>
<a href="#" class="easyui-linkbutton" onclick="setValue()">SetValue</a>
<a href="#" class="easyui-linkbutton" onclick="getValue()">GetValue</a>
<a href="#" class="easyui-linkbutton" onclick="disable()">Disable</a>
<a href="#" class="easyui-linkbutton" onclick="enable()">Enable</a>
</div>
<p>Simple ComboBox: </p>
<select id="cc" class="easyui-combobox" name="state" style="width:200px;" data-options="required:true">
</select>
<p>Multiple ComboBox: </p>
<input id="cc2" class="easyui-combobox"
name="language"
data-options="
url:'combobox_data.json',
valueField:'id',
textField:'text',
multiple:true,
panelHeight:'auto'
">
</body>
</html> |
import React from 'react'
import { Nav, Navbar, NavLink } from 'react-bootstrap';
import { useSelector } from 'react-redux';
import { Link } from 'react-router-dom';
import { MenuBar, ShoppingCart } from '../atoms';
const TopBar = () => {
const { titleDashboard } = useSelector(state => state.auth);
return (
<Navbar variant="light" className='d-flex justify-content-between px-4 border' fixed="top" style={{ marginLeft: '239px', backgroundColor: '#ffffff', borderBottom: '1px solid #e8e8e8' }}>
<Navbar.Brand> <span className="color-primary fw-bold fs-2">{titleDashboard}</span></Navbar.Brand>
<Nav>
<NavLink as={Link} to={'/'}>
<span className="fs-4 color-primary fw-bolder">Home</span>
</NavLink>
<ShoppingCart />
<MenuBar />
</Nav>
</Navbar >
)
}
export default TopBar; |
defmodule KouekiWeb.TagTest do
use KouekiWeb.ConnCase
import Koueki.Factory
test "GET /v2/tags/:id", %{conn: conn} do
user = insert(:user)
tag = insert(:tag)
conn =
conn
|> assign(:user, user)
|> get("/v2/tags/#{tag.id}")
assert %{"name" => _, "id" => _} = json_response(conn, 200)
end
test "POST /v2/tags/", %{conn: conn} do
user = insert(:user)
conn =
conn
|> assign(:user, user)
|> post("/v2/tags/", %{name: "taggerino"})
assert %{"name" => "taggerino", "id" => id} = json_response(conn, 201)
# Same name - fail
conn =
build_conn()
|> assign(:user, user)
|> post("/v2/tags/", %{name: "taggerino"})
assert %{"error" => _} = json_response(conn, 400)
end
end |
import type {NextFunction, Request, Response} from 'express';
import express from 'express';
import UserCollection from '../user/collection';
import LikeCollection from './collection';
import * as userValidator from '../user/middleware';
import * as likeValidator from '../like/middleware';
import * as util from './util';
const router = express.Router();
/**
* Get all the likes
*
* @name GET /api/likes
*
* @return {FreetResponse[]} - A array of all the likes
*/
/**
* Get likes by user.
*
* @name GET /api/likes?username=username
*
* @return {FreetResponse[]} - An array of likes created by user with username
* @throws {400} - If username is not given
* @throws {404} - If no user has given username
*
*/
router.get(
'/',
async (req: Request, res: Response, next: NextFunction) => {
// Check if username query parameter was supplied'
if (req.query.username !== undefined) {
next();
return;
}
const userLikes = await LikeCollection.findAll();
const response = userLikes.map(util.constructLikeResponse);
res.status(200).json(response);
},
[
userValidator.isUserExists
],
async (req: Request, res: Response) => {
const userObj = await UserCollection.findOneByUsername(req.query.username as string);
const userLikes = await LikeCollection.findByUser(userObj.id);
const response = userLikes.map(util.constructLikeResponse);
res.status(200).json(response);
}
);
/**
* Create a like
*
* @name POST /api/likes
*
* @param {string} postId - post to be liked
* @return {LikeResponse} - The created like
* @throws {403} - If the user is not logged in
* @throws {404} - If the post does not exist
* @throws {409} - If the user already liked the post
*
*/
router.post(
'/',
[
userValidator.isUserLoggedIn,
likeValidator.isPostExists,
likeValidator.canCreateLike
],
async (req: Request, res: Response) => {
const like = await LikeCollection.createLike(req.body.postId, req.session.userId);
res.status(200).json({
message: `Post ${like.postId.toString()} liked by user ${like.userId.toString()}`,
user: util.constructLikeResponse(like)
});
}
);
/**
* Delete a Like
*
* @name DELETE /api/likes/:postId
*
* @return {string} - A success message
* @throws {403} - If the user is not logged in
* @throws {404} - If the postId is invalid
* @throws {409} - If the user has not liked the post
*/
router.delete(
'/:postId?',
[
userValidator.isUserLoggedIn,
likeValidator.isPostExists,
likeValidator.likeExist
],
async (req: Request, res: Response) => {
await LikeCollection.findAndDeleteOne(req.params.postId, req.session.userId);
res.status(200).json({
message: 'Your like was deleted successfully.'
});
}
);
export {router as likeRouter}; |
package HQL1CrudOperation.HQL1CrudOperation.Repository;
import HQL1CrudOperation.HQL1CrudOperation.Model.Student;
import jakarta.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
@Repository
public interface StudRepository extends JpaRepository<Student,Integer> {
@Query("from Student s where s.sName=:name")
public List<Student> displayByName(@Param("name") String name);
//------------------------------------------------------------------
@Query("update Student s set s.sName=:prefix || s.sName where s.sGender=:gender")
@Modifying
@Transactional
public void updateNameByGender(@Param("prefix") String prefix,@Param("gender") String gender);
//----------------------------------------------------------------------------------------------
@Query("from Student s where s.sGender=:gender and s.sAge>:age")
public List<Student> displayDataWhosePerGenderAndAgeGreaterThanPerAge(@Param("gender") String gender,@Param("age") int age);
//--------------------------------------------------------------------------------------------------------------------------
@Query("select distinct s.sName from Student s")
public List<String> displayDistinctName();
//--------------------------------------------------------------
@Query("select distinct s.sAge from Student s")
public List<Integer> displayDistinctAges();
//----------------------------------------------------------
@Query("select sName from Student s where s.sName like %:ch%")
public List<String> displayNamePresentPerCharacter(@Param("ch") String ch);
//------------------------------------------------------------------------------
@Query("select sName from Student s where s.sName like :ch%")// endsWith=%:ch
public List<String> displayNameStartsWithPerCharacter(@Param("ch") String ch);
//----------------------------------------------------------------------------------
@Query("update Student s set s.sPer=s.sPer+:extraMarks where s.sPer<=:per")
@Modifying
@Transactional
public int updatePercentagesByAdding10MarksExtra(@Param("per") double per,@Param("extraMarks") double extraMarks);
//-----------------------------------------------------------------------------------------------------------------
@Query("delete from Student s where s.sName=:name")
@Modifying
@Transactional
public void deleteDataByName(@Param("name") String name);
//--------------------------------------------------------------
} |
<----- Steps to create JSF and Primefaces project ------ >
Steps:
1.) eclipse or netbeans first go to create new project option
2.) choose dynamic web project0( through java maven) to create new project
3.) then open pom.xml file and this dependency to enable project as a JSF/Primefaces project
Dependencies are :
<dependencies>
<!-- PrimeFaces -->
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>11.0.0</version>
</dependency>
<!-- JSF -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.11</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.11</version>
</dependency>
<!-- JSF IMPLEMENTATION (MOJARRA) -->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.2.20</version>
</dependency>
<!-- JSF -->
<dependency>
<groupId>javax.faces</groupId>
<artifactId>javax.faces-api</artifactId>
<version>2.3</version>
<scope>provided</scope>
</dependency>
<!-- SERVLET API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- JSP API -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<!-- EL (EXPRESSION LANGUAGE) API -->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<!-- MYSQL DB DEPENDENCY -->
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!-- JAVA DEPENDENCY FOR DEPENDENCY INJECTION LIKE @Inject @PostConstruct etc annotation -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-api</artifactId>
<version>${jakartaee}</version>
<scope>provided</scope>
</dependency>
</dependencies>
4.) now if you want to create xhtml page (index.xhtml) so go to web pages folder
5.) there select this folder and right click and make jsf page with .xhtml extension
6.) for creating java class go to source packages folder and there you can create java classes
7.)set web.xml file which is present in inside folder web pages/web-inf/web.xml and configure it like :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map these files with JSF -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
8.) add tomcat to the project choose add server option in project menu or server menu
9.) add this username and password in your tomcat-users file so that it can configure
<user password="Tomcat!323" roles="manager-gui, admin-gui, manager-script, admin-script,admin" username="tomcat"/>
or if it is asking encrypted password (username and password same for both)
<user username="tomcat" password="ece7470ebe563c93$1000$5ed817ac45bf7369f1a7311e43f08475dbc26f86" roles="manager-gui, admin-gui, manager-script, admin-script"/>
tomcat-users file present in tomcat/conf/tomcat-users.xml
10.) set maven also in environment setting
file : index.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<h1>Hello World Prime Faces</h1>
<h:form>
<h:inputTextarea id="editor" value="#{beanName.method/variable}" style="width: 100%; height: 100px;" />
<p:commandButton value="Submit" onclick="window.location.reload()" />
</h:form>
</h:body>
</html>
value="#{helloWorld.home}"
file : HelloWorld.java
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean
@ViewedScoped
class HelloWorld
{
private String home(){
return "hello";
}
}
11.) build with dependency
12.) clean and build
13.) then run in server |
/** @odoo-module **/
import { Component, xml } from "@odoo/owl";
import { makeTestEnv } from "@web/../tests/helpers/mock_env";
import {
click,
editInput,
getFixture,
mount,
mouseEnter,
triggerEvent,
triggerEvents,
} from "@web/../tests/helpers/utils";
import { commandService } from "@web/core/commands/command_service";
import { dialogService } from "@web/core/dialog/dialog_service";
import { fieldService } from "@web/core/field_service";
import { hotkeyService } from "@web/core/hotkeys/hotkey_service";
import { notificationService } from "@web/core/notifications/notification_service";
import { ormService } from "@web/core/orm_service";
import { popoverService } from "@web/core/popover/popover_service";
import { registry } from "@web/core/registry";
import { CustomFavoriteItem } from "@web/search/custom_favorite_item/custom_favorite_item";
import { WithSearch } from "@web/search/with_search/with_search";
import { getDefaultConfig } from "@web/views/view";
import { viewService } from "@web/views/view_service";
import { actionService } from "@web/webclient/actions/action_service";
import { MainComponentsContainer } from "@web/core/main_components_container";
import { nameService } from "@web/core/name_service";
import { datetimePickerService } from "@web/core/datetime/datetimepicker_service";
const serviceRegistry = registry.category("services");
const favoriteMenuRegistry = registry.category("favoriteMenu");
export function setupControlPanelServiceRegistry() {
serviceRegistry.add("action", actionService);
serviceRegistry.add("dialog", dialogService);
serviceRegistry.add("field", fieldService);
serviceRegistry.add("hotkey", hotkeyService);
serviceRegistry.add("name", nameService);
serviceRegistry.add("notification", notificationService);
serviceRegistry.add("orm", ormService);
serviceRegistry.add("popover", popoverService);
serviceRegistry.add("view", viewService);
serviceRegistry.add("command", commandService);
serviceRegistry.add("datetime_picker", datetimePickerService);
}
export function setupControlPanelFavoriteMenuRegistry() {
favoriteMenuRegistry.add(
"custom-favorite-item",
{ Component: CustomFavoriteItem, groupNumber: 3 },
{ sequence: 0 }
);
}
export async function makeWithSearch(params) {
const props = { ...params };
const serverData = props.serverData || undefined;
const mockRPC = props.mockRPC || undefined;
const config = {
...getDefaultConfig(),
...props.config,
};
delete props.serverData;
delete props.mockRPC;
delete props.config;
const componentProps = props.componentProps || {};
delete props.componentProps;
delete props.Component;
class Parent extends Component {
setup() {
this.withSearchProps = props;
}
getProps(search) {
const props = Object.assign({}, componentProps, {
context: search.context,
domain: search.domain,
groupBy: search.groupBy,
orderBy: search.orderBy,
comparison: search.comparison,
display: Object.assign({}, search.display, componentProps.display),
});
return filterPropsForComponent(params.Component, props);
}
}
Parent.template = xml`
<WithSearch t-props="withSearchProps" t-slot-scope="search">
<Component t-props="getProps(search)"/>
</WithSearch>
<MainComponentsContainer />
`;
Parent.components = { Component: params.Component, WithSearch, MainComponentsContainer };
const env = await makeTestEnv({ serverData, mockRPC });
const searchEnv = Object.assign(Object.create(env), { config });
const parent = await mount(Parent, getFixture(), { env: searchEnv, props });
const parentNode = parent.__owl__;
const withSearchNode = getUniqueChild(parentNode);
const componentNode = getUniqueChild(withSearchNode);
const component = componentNode.component;
return component;
}
/** This function is aim to be used only in the tests.
* It will filter the props that are needed by the Component.
* This is to avoid errors of props validation. This occurs for example, on ControlPanel tests.
* In production, View use WithSearch for the Controllers, and the Layout send only the props that
* need to the ControlPanel.
*
* @param {Component} Component
* @param {Object} props
* @returns {Object} filtered props
*/
function filterPropsForComponent(Component, props) {
// This if, can be removed once all the Components have the props defined
if (Component.props) {
let componentKeys = null;
if (Component.props instanceof Array) {
componentKeys = Component.props.map((x) => x.replace("?", ""));
} else {
componentKeys = Object.keys(Component.props);
}
if (componentKeys.includes("*")) {
return props;
} else {
return Object.keys(props)
.filter((k) => componentKeys.includes(k))
.reduce((o, k) => {
o[k] = props[k];
return o;
}, {});
}
} else {
return props;
}
}
function getUniqueChild(node) {
return Object.values(node.children)[0];
}
function getNode(target) {
return target instanceof Component ? target.el : target;
}
export function findItem(target, selector, finder = 0) {
const el = getNode(target);
const elems = [...el.querySelectorAll(selector)];
if (Number.isInteger(finder)) {
return elems[finder];
}
return elems.find((el) => el.innerText.trim().toLowerCase() === String(finder).toLowerCase());
}
/** Menu (generic) */
export async function toggleMenu(el, menuFinder) {
const menu = findItem(el, `.dropdown button.dropdown-toggle`, menuFinder);
await click(menu);
}
export async function toggleMenuItem(el, itemFinder) {
const item = findItem(el, `.o_menu_item`, itemFinder);
if (item.classList.contains("dropdown-toggle")) {
await mouseEnter(item);
} else {
await click(item);
}
}
export async function toggleMenuItemOption(el, itemFinder, optionFinder) {
const item = findItem(el, `.o_menu_item`, itemFinder);
const option = findItem(item.parentNode, ".o_item_option", optionFinder);
if (option.classList.contains("dropdown-toggle")) {
await mouseEnter(option);
} else {
await click(option);
}
}
export function isItemSelected(el, itemFinder) {
const item = findItem(el, `.o_menu_item`, itemFinder);
return item.classList.contains("selected");
}
export function isOptionSelected(el, itemFinder, optionFinder) {
const item = findItem(el, `.o_menu_item`, itemFinder);
const option = findItem(item.parentNode, ".o_item_option", optionFinder);
return option.classList.contains("selected");
}
export function getMenuItemTexts(target) {
const el = getNode(target);
return [...el.querySelectorAll(`.dropdown-menu .o_menu_item`)].map((e) => e.innerText.trim());
}
export function getVisibleButtons(el) {
return [
...$(el).find(
[
"div.o_control_panel_breadcrumbs button:visible", // button in the breadcrumbs
"div.o_control_panel_actions button:visible", // buttons for list selection
].join(",")
),
];
}
/** Filter menu */
export async function openAddCustomFilterDialog(el) {
await click(findItem(el, `.o_filter_menu .o_menu_item.o_add_custom_filter`));
}
/** Group by menu */
export async function selectGroup(el, fieldName) {
el.querySelector(".o_add_custom_group_menu").value = fieldName;
await triggerEvent(el, ".o_add_custom_group_menu", "change");
}
export async function groupByMenu(el, fieldName) {
await toggleSearchBarMenu(el);
await selectGroup(el, fieldName);
}
/** Favorite menu */
export async function deleteFavorite(el, favoriteFinder) {
const favorite = findItem(el, `.o_favorite_menu .o_menu_item`, favoriteFinder);
await click(findItem(favorite, "i.fa-trash-o"));
}
export async function toggleSaveFavorite(el) {
await click(findItem(el, `.o_favorite_menu .o_add_favorite`));
}
export async function editFavoriteName(el, name) {
const input = findItem(
el,
`.o_favorite_menu .o_add_favorite + .o_accordion_values input[type="text"]`
);
input.value = name;
await triggerEvents(input, null, ["input", "change"]);
}
export async function saveFavorite(el) {
await click(findItem(el, `.o_favorite_menu .o_add_favorite + .o_accordion_values button`));
}
/** Search bar */
export function getFacetTexts(target) {
const el = getNode(target);
return [...el.querySelectorAll(`div.o_searchview_facet`)].map((facet) =>
facet.innerText.trim()
);
}
export async function removeFacet(el, facetFinder = 0) {
const facet = findItem(el, `div.o_searchview_facet`, facetFinder);
await click(facet.querySelector(".o_facet_remove"));
}
export async function editSearch(el, value) {
const input = findItem(el, `.o_searchview input`);
input.value = value;
await triggerEvent(input, null, "input");
}
export async function validateSearch(el) {
const input = findItem(el, `.o_searchview input`);
await triggerEvent(input, null, "keydown", { key: "Enter" });
}
/** Switch View */
export async function switchView(el, viewType) {
await click(findItem(el, `button.o_switch_view.o_${viewType}`));
}
/** Pager */
export function getPagerValue(el) {
const valueEl = findItem(el, ".o_pager .o_pager_value");
return valueEl.innerText.trim().split("-").map(Number);
}
export function getPagerLimit(el) {
const limitEl = findItem(el, ".o_pager .o_pager_limit");
return Number(limitEl.innerText.trim());
}
export async function pagerNext(el) {
await click(findItem(el, ".o_pager button.o_pager_next"));
}
export async function pagerPrevious(el) {
await click(findItem(el, ".o_pager button.o_pager_previous"));
}
export async function editPager(el, value) {
await click(findItem(el, ".o_pager .o_pager_value"));
await editInput(getNode(el), ".o_pager .o_pager_value.o_input", value);
}
// Action Menu
/**
* @param {EventTarget} el
* @param {string} [menuFinder="Action"]
* @returns {Promise}
*/
export async function toggleActionMenu(el) {
await click(el.querySelector(".o_cp_action_menus .dropdown-toggle"));
}
/** SearchBarMenu */
export async function toggleSearchBarMenu(el) {
await click(findItem(el, `.o_searchview_dropdown_toggler`));
} |
;; line 1154 "markup.nw"
;; $Id: markup.nw,v 1.24 1997/03/26 16:18:58 kehr Exp $
(lisp:defpackage "MARKUP")
(lisp:in-package "MARKUP")
(lisp:provide "markup")
#+CLISP (lisp:require "base")
#+CLISP (lisp:require "locref")
#+CLISP (lisp:require "idxstyle")
#+CLISP (lisp:require "index")
#+CLISP (lisp:require "ordrules")
#+CLISP (lisp:require "version")
(eval-when (compile load eval)
(lisp:use-package "CLOS")
#+(and :XP CLISP) (lisp:use-package "XP")
#+CLISP (setq custom:*suppress-check-redefinition* t)
#-CLISP (lisp:require "base")
#-CLISP (lisp:require "locref")
#-CLISP (lisp:require "idxstyle")
#-CLISP (lisp:require "index")
(lisp:use-package "BASE")
(lisp:use-package "LOCREF")
(lisp:use-package "IDXSTYLE")
(lisp:use-package "INDEX"))
;; line 1222 "markup.nw"
;; $Id: markup.nw,v 1.24 1997/03/26 16:18:58 kehr Exp $
;; line 71 "markup.nw"
(defparameter *markup-output-stream* *standard-output*)
(defparameter *markup-verbose-mode* nil)
(defparameter *markup-verbose-open* "<")
(defparameter *markup-verbose-close* ">")
(defparameter *markup-indentation* 2)
(defparameter *markup-indent-level* 0)
(defparameter *empty-markup* "")
(defvar *markup-percentage-list*)
(defvar *current-number*)
(defun do-markup-indent ()
(incf *markup-indent-level* *markup-indentation*))
(defun do-markup-outdent ()
(decf *markup-indent-level* *markup-indentation*))
;; line 102 "markup.nw"
(defun do-markup-string (str)
(declare (inline))
(write-string str *markup-output-stream*))
;; line 111 "markup.nw"
(defun do-markup-default (str &optional arg1 arg2 arg3)
(when *markup-verbose-mode*
(loop for x from 1 to *markup-indent-level*
do (write-string " " *markup-output-stream*))
(do-markup-string *markup-verbose-open*)
(do-markup-string str)
(when arg1
(format *markup-output-stream* " [~S]" arg1)
(when arg2
(format *markup-output-stream* " [~S]" arg2)
(when arg3
(format *markup-output-stream* " [~S]" arg3)
)))
(do-markup-string *markup-verbose-close*)
(terpri *markup-output-stream*)
))
;; line 138 "markup.nw"
(defmacro do-markup-list (some-list
&key
identifier counter
elt-body sep-body
open-body close-body)
`(PROGN
,(when open-body `,open-body)
(LET ,(if counter
`((LIST-END (CAR (LAST ,some-list)))
(COUNTER ,counter))
`((LIST-END (CAR (LAST ,some-list)))))
(DO ((SLIST ,some-list (CDR SLIST)))
((ENDP SLIST))
(LET ((,identifier (CAR SLIST)))
,elt-body
,(if sep-body
`(UNLESS (EQL ,identifier LIST-END)
,sep-body)))))
,(when close-body close-body)))
;; line 162 "markup.nw"
#|
(macroexpand '(markup-list '(1 2 3) :identifier FOO
:open-body (print "open")
:close-body (print "close")
:elt-body (print FOO)
:sep-body (print ",")))
expands to
(PROGN (PRINT "open")
(LET ((LIST-END (CAR (LAST '(1 2 3)))))
(DO ((SLIST '(1 2 3) (CDR SLIST))) ((ENDP SLIST))
(LET ((FOO (CAR SLIST))) (PRINT FOO)
(UNLESS (EQL FOO LIST-END) (PRINT ","))
) ) )
(PRINT "close")
) ;
T
|#
;; line 193 "markup.nw"
(defmacro define-list-environment-methods (name
signature
&key open close sep declare body)
(let ((name (stringify name)))
`(EVAL-WHEN (COMPILE LOAD EVAL)
(HANDLER-BIND ((WARNING #'MUFFLE-WARNING))
(CL:DEFMETHOD
,(intern (string-upcase (concatenate 'string name "-open"))
'markup)
,signature ,@declare ,@open ,@body)
(CL:DEFMETHOD
,(intern (string-upcase (concatenate 'string name "-close"))
'markup)
,signature ,@declare ,@close ,@body)
(CL:DEFMETHOD
,(intern (string-upcase (concatenate 'string name "-sep"))
'markup)
,signature ,@declare ,@sep ,@body)))))
;; line 214 "markup.nw"
(defmacro define-environment-methods (name
signature
&key open close declare body)
(let ((name (stringify name)))
`(EVAL-WHEN (COMPILE LOAD EVAL)
(HANDLER-BIND ((WARNING #'MUFFLE-WARNING))
(CL:DEFMETHOD
,(intern (string-upcase (concatenate 'string name "-open"))
'markup)
,signature ,@declare ,@open ,@body)
(CL:DEFMETHOD
,(intern (string-upcase (concatenate 'string name "-close"))
'markup)
,signature ,@declare ,@close ,@body)))))
(defmacro define-method (name
signature
&key declare body)
(let ((name (stringify name)))
`(EVAL-WHEN (COMPILE LOAD EVAL)
(HANDLER-BIND ((WARNING #'MUFFLE-WARNING))
(CL:DEFMETHOD
,(intern (string-upcase name) 'markup)
,signature ,@declare ,@body)))))
;; line 326 "markup.nw"
(defmethod do-markup-index ((idx base-index))
(setq *current-number* 0)
(setq *markup-percentage-list* index:*percentage-list*)
(do-markup-index-open idx)
(do-markup-list (get-entries idx)
:identifier LETTER-GRP
:open-body (do-markup-letter-group-list-open)
:elt-body (do-markup-letter-group LETTER-GRP)
:sep-body (do-markup-letter-group-list-sep)
:close-body (do-markup-letter-group-list-close))
(index:print-rest-of-percentages *markup-percentage-list*)
(do-markup-index-close idx))
(define-environment-methods do-markup-index ((idx base-index))
:open ((do-markup-default "INDEX:OPEN")
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "INDEX:CLOSE")))
;; line 351 "markup.nw"
(defmacro markup-index (&whole whole &rest args)
(destructuring-switch-bind (&key
open close hierdepth
&switch
tree flat)
args
(let (hierdepth-cmd)
(when (or hierdepth tree flat)
(cond
((and tree flat)
(error "you can't specify :tree and :flat simultaneously in ~%~S~%"
whole))
((and hierdepth (or tree flat))
(error "you can't specify :hierdepth with :tree or :flat simultaneously in ~%~S~%"
whole))
(flat (setq hierdepth-cmd
`(SET-HIERDEPTH 0 *INDEX*)));; no tree-structure
;; MOST-POSITIVE-FIXNUM means make all trees
(tree (setq hierdepth-cmd
`(SET-HIERDEPTH MOST-POSITIVE-FIXNUM *INDEX*)))
(hierdepth
(when (not (numberp hierdepth))
(error "~S is not a number in ~S~%" whole))
(setq hierdepth-cmd
`(SET-HIERDEPTH ,hierdepth *INDEX*))))
`(LET ()
(markup::define-environment-methods
DO-MARKUP-INDEX ((idx index:base-index))
:declare ((declare (ignore idx)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close))))
,hierdepth-cmd)))))
;; line 390 "markup.nw"
(define-list-environment-methods do-markup-letter-group-list ()
:open ((do-markup-default "LETTER-GROUP-LIST:OPEN")
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "LETTER-GROUP-LIST:CLOSE"))
:sep ((do-markup-default "LETTER-GROUP-LIST:SEP")))
;; line 409 "markup.nw"
(defmethod do-markup-letter-group ((letter-grp letter-group))
(let ((group-definition (get-group-definition letter-grp)))
(do-markup-letter-group-open group-definition)
(do-markup-letter-group-head-open group-definition)
(do-markup-letter-group-head group-definition)
(do-markup-letter-group-head-close group-definition)
(do-markup-list (get-members letter-grp)
:identifier IDXENT #| the identifier to use in the expansion |#
:open-body (do-markup-indexentry-list-open 0
#|initial depth:=0|#)
:elt-body (do-markup-indexentry IDXENT 0)
:sep-body (do-markup-indexentry-list-sep 0)
:close-body (do-markup-indexentry-list-close 0))
(do-markup-letter-group-close group-definition)))
(define-environment-methods do-markup-letter-group
((group letter-group-definition))
:open ((do-markup-default "LETTER-GROUP:OPEN" (get-name group))
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "LETTER-GROUP:CLOSE" (get-name group))))
(define-environment-methods do-markup-letter-group-head
((group letter-group-definition))
:open ((do-markup-default "LETTER-GROUP-HEAD:OPEN" (get-name group))
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "LETTER-GROUP-HEAD:CLOSE" (get-name group))))
(define-method do-markup-letter-group-head ((group letter-group-definition))
:body ((do-markup-default "LETTER-GROUP-HEAD" (get-name group))))
;; line 503 "markup.nw"
(define-list-environment-methods do-markup-indexentry-list ((depth number))
:open ((do-markup-default "INDEXENTRY-LIST:OPEN" depth)
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "INDEXENTRY-LIST:CLOSE" depth))
:sep ((do-markup-default "INDEXENTRY-LIST:SEP" depth)))
;; line 525 "markup.nw"
(defmethod do-markup-indexentry ((idxent index-entry)
(depth number))
(when (>= (incf *current-number*) (caar *markup-percentage-list*))
(index:print-percent (pop *markup-percentage-list*)))
(do-markup-indexentry-open depth)
(let ((print-key (get-print-key idxent)))
(do-markup-list (merge-print-and-main-key print-key (get-main-key idxent))
:identifier KEYWORD
:open-body (do-markup-keyword-list-open depth)
:elt-body (do-markup-keyword KEYWORD depth)
:sep-body (do-markup-keyword-list-sep depth)
:close-body (do-markup-keyword-list-close depth)))
(let ((locrefs (get-locrefs idxent)))
(unless (endp locrefs)
(do-markup-list locrefs
:identifier LOCCLS-GRP
:open-body (do-markup-locclass-list-open)
:elt-body (do-markup-locclass LOCCLS-GRP)
:sep-body (do-markup-locclass-list-sep)
:close-body (do-markup-locclass-list-close))))
(let ((subentries (get-subentries idxent)))
(unless (endp subentries)
(let ((new-depth (1+ depth)))
(do-markup-list subentries
:identifier IDXENT
:open-body (do-markup-indexentry-list-open new-depth)
:elt-body (do-markup-indexentry IDXENT new-depth)
:sep-body (do-markup-indexentry-list-sep new-depth)
:close-body (do-markup-indexentry-list-close new-depth)))))
(do-markup-indexentry-close depth))
(defun merge-print-and-main-key (print-key main-key)
;;(info "~&(merge-print-and-main-key ~S ~S)" print-key main-key)
(if print-key
(mapcar #'(lambda (print main)
(or print main))
print-key main-key)
main-key))
;; line 571 "markup.nw"
(define-environment-methods do-markup-indexentry ((depth number))
:open ((do-markup-default "INDEXENTRY:OPEN" depth)
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "INDEXENTRY:CLOSE" depth)))
;; line 595 "markup.nw"
(define-list-environment-methods do-markup-keyword-list ((depth number))
:open ((do-markup-default "KEYWORD-LIST:OPEN" depth)
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "KEYWORD-LIST:CLOSE" depth))
:sep ((do-markup-default "KEYWORD-LIST:SEP" depth)))
;; line 617 "markup.nw"
(defmethod do-markup-keyword (keyword (depth number))
(do-markup-keyword-open depth)
(do-markup-string keyword)
(do-markup-keyword-close depth))
;; line 624 "markup.nw"
(define-environment-methods do-markup-keyword ((depth number))
:open ((do-markup-default "KEYWORD:OPEN" depth)
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "KEYWORD:CLOSE" depth)))
;; line 654 "markup.nw"
(define-list-environment-methods do-markup-locclass-list ()
:open ((do-markup-default "LOCCLASS-LIST:OPEN")
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "LOCCLASS-LIST:CLOSE"))
:sep ((do-markup-default "LOCCLASS-LIST:SEP")))
;; line 677 "markup.nw"
(defmethod do-markup-locclass ((locref-cls-grp locref-class-group))
(let ((locclass (get-locclass locref-cls-grp)))
(do-markup-locref-class-open locclass)
(do-markup-list (get-members locref-cls-grp)
:identifier ATTRIBUTE-GRP
:open-body (do-markup-attribute-group-list-open)
:elt-body (do-markup-attribute-group ATTRIBUTE-GRP locclass)
:sep-body (do-markup-attribute-group-list-sep)
:close-body (do-markup-attribute-group-list-close))
(do-markup-locref-class-close locclass)))
(define-environment-methods do-markup-locref-class
((locrefcls layered-location-class))
:open ((do-markup-default "LOCREF-CLASS:OPEN" (get-name locrefcls))
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "LOCREF-CLASS:CLOSE" (get-name locrefcls))))
;; line 1044 "markup.nw"
(defmethod do-markup-locclass ((xref-cls-grp crossref-class-group))
(let ((xrefclass (get-locclass xref-cls-grp)))
(do-markup-list (get-members xref-cls-grp)
:identifier XREF
:open-body (do-markup-crossref-list-open xrefclass)
:elt-body (do-markup-crossref XREF)
:sep-body (do-markup-crossref-list-sep xrefclass)
:close-body (do-markup-crossref-list-close xrefclass))))
(define-list-environment-methods do-markup-crossref-list
((xrefclass crossref-location-class))
:open ((do-markup-default "CROSSREF-LIST:OPEN" (get-name xrefclass))
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "CROSSREF-LIST:CLOSE" (get-name xrefclass)))
:sep ((do-markup-default "CROSSREF-LIST:SEP" (get-name xrefclass))))
;; line 1080 "markup.nw"
(defmethod do-markup-crossref ((xref crossref-location-reference))
(let ((xrefclass (get-locclass xref)))
(do-markup-list (get-target xref)
:identifier XREF-LAYER
:open-body (do-markup-crossref-layer-list-open xrefclass)
:elt-body (do-markup-crossref-layer XREF-LAYER xrefclass)
:sep-body (do-markup-crossref-layer-list-sep xrefclass)
:close-body (do-markup-crossref-layer-list-close xrefclass))))
(define-list-environment-methods do-markup-crossref-layer-list
((xref-class crossref-location-class))
:open ((do-markup-default "CROSSREF-LAYER-LIST:OPEN"
(get-name xref-class))
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "CROSSREF-LAYER-LIST:CLOSE"
(get-name xref-class)))
:sep ((do-markup-default "CROSSREF-LAYER-LIST:SEP"
(get-name xref-class))))
;; line 1119 "markup.nw"
(defmethod do-markup-crossref-layer (xref-layer
(xref-class crossref-location-class))
(do-markup-crossref-layer-open xref-class)
(do-markup-string xref-layer)
(do-markup-crossref-layer-close xref-class))
(define-environment-methods do-markup-crossref-layer
((xref-class crossref-location-class))
:open ((do-markup-default "CROSSREF-LAYER:OPEN" (get-name xref-class))
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "CROSSREF-LAYER:CLOSE" (get-name xref-class))))
;; line 718 "markup.nw"
(define-list-environment-methods do-markup-attribute-group-list ()
:open ((do-markup-default "ATTRIBUTE-GROUP-LIST:OPEN")
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "ATTRIBUTE-GROUP-LIST:CLOSE"))
:sep ((do-markup-default "ATTRIBUTE-GROUP-LIST:SEP")))
;; line 737 "markup.nw"
(defmethod do-markup-attribute-group ((attribute-group category-attribute-group)
(loccls layered-location-class))
(let ((ordnum (get-ordnum attribute-group)))
(do-markup-attribute-group-open ordnum)
(do-markup-list (get-members attribute-group)
:identifier LOCREF
:open-body (do-markup-locref-list-open loccls 0)
:elt-body (do-markup-locref LOCREF loccls 0)
:sep-body (do-markup-locref-list-sep loccls 0)
:close-body (do-markup-locref-list-close loccls 0))
(do-markup-attribute-group-close ordnum)))
(define-environment-methods do-markup-attribute-group ((ordnum number))
:open ((do-markup-default "ATTRIBUTE-GROUP:OPEN" ordnum)
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "ATTRIBUTE-GROUP:CLOSE" ordnum)))
;; line 776 "markup.nw"
(define-list-environment-methods do-markup-locref-list
((loccls layered-location-class) (depth number))
:open ((do-markup-default "LOCREF-LIST:OPEN" (get-name loccls) depth)
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "LOCREF-LIST:CLOSE" (get-name loccls) depth))
:sep ((do-markup-default "LOCREF-LIST:SEP" (get-name loccls) depth)))
;; line 808 "markup.nw"
(defmethod do-markup-locref ((locref location-reference)
(loccls layered-location-class)
(depth number))
#+ASSERT! (assert! (and (typep locref 'layered-location-reference)
(typep depth 'number)))
(let ((attr (get-catattr locref))
(subrefs (get-subrefs locref))
(new-depth (1+ depth)))
(do-markup-locref-open attr loccls depth)
(cond
(subrefs
(let ((layer 0))
(do-markup-list (get-layers locref)
:identifier LOCREF-LAYER
:open-body (do-markup-locref-layer-list-open loccls depth)
:elt-body (do-markup-locref-layer LOCREF-LAYER loccls depth
(prog1 layer
(incf layer)))
:sep-body (do-markup-locref-layer-list-sep loccls depth)
:close-body (do-markup-locref-layer-list-close loccls depth)))
(do-markup-list subrefs
:identifier LOCREF
:open-body (do-markup-locref-list-open loccls new-depth)
:elt-body (do-markup-locref LOCREF loccls new-depth)
:sep-body (do-markup-locref-list-sep loccls new-depth)
:close-body (do-markup-locref-list-close loccls new-depth)))
((= 0 depth)
(do-markup-string (get-locref-string locref)))
(t (let ((layer 0))
(do-markup-list (get-layers locref)
:identifier LOCREF-LAYER
:open-body (do-markup-locref-layer-list-open loccls depth)
:elt-body (do-markup-locref-layer LOCREF-LAYER loccls depth
(prog1 layer
(incf layer)))
:sep-body (do-markup-locref-layer-list-sep loccls depth)
:close-body (do-markup-locref-layer-list-close loccls depth)))))
(do-markup-locref-close attr loccls depth)))
;; line 855 "markup.nw"
(define-list-environment-methods do-markup-locref-layer-list
((loccls layered-location-class) (depth number))
:open ((do-markup-default "LOCREF-LAYER-LIST:OPEN" (get-name loccls) depth)
(do-markup-indent))
:sep ((do-markup-default "LOCREF-LAYER-LIST:SEP" (get-name loccls) depth))
:close ((do-markup-outdent)
(do-markup-default "LOCREF-LAYER-LIST:CLOSE" (get-name loccls) depth)))
;; line 883 "markup.nw"
(defun do-markup-locref-layer (locref-layer loccls depth layer)
(do-markup-locref-layer-open loccls depth layer)
(do-markup-string locref-layer)
(do-markup-locref-layer-close loccls depth layer))
(define-environment-methods do-markup-locref-layer
((locref-class layered-location-class) (depth number) (layer number))
:open ((do-markup-default "LOCREF-LAYER:OPEN"
(get-name locref-class) depth layer)
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "LOCREF-LAYER:CLOSE"
(get-name locref-class) depth layer)))
;; line 918 "markup.nw"
(define-environment-methods do-markup-locref ((attr category-attribute)
(loccls layered-location-class)
(depth number))
:open ((do-markup-default "LOCREF:OPEN"
(get-name attr) (get-name loccls) depth)
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "LOCREF:CLOSE"
(get-name attr) (get-name loccls) depth)))
;; line 955 "markup.nw"
(defmethod do-markup-locref ((range location-range)
(loccls layered-location-class)
(depth number))
(let ((length (get-length range)))
(do-markup-range-open loccls length)
(do-markup-locref (get-first range) loccls depth)
(do-markup-range-sep loccls length)
(when (markup-range-print-end-p loccls length)
(do-markup-locref (get-last range) loccls depth))
(do-markup-range-close loccls length)))
(define-list-environment-methods do-markup-range
((loccls layered-location-class) (length number))
:open ((do-markup-default "RANGE:OPEN" (get-name loccls) length)
(do-markup-indent))
:close ((do-markup-outdent)
(do-markup-default "RANGE:CLOSE" (get-name loccls) length))
:sep ((do-markup-default "RANGE:SEP" (get-name loccls) length)))
(defmethod markup-range-print-end-p ((loccls layered-location-class)
(length number))
t)
;; line 304 "markup.nw"
(defmacro markup-trace (&rest args)
(destructuring-switch-bind (&key
(open *markup-verbose-open*)
(close *markup-verbose-close*)
&switch
on)
args
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 312 "markup.nw"
(t `(LET ()
(SETQ *markup-verbose-open* ,open)
(SETQ *markup-verbose-close* ,close)
,(when on `(SETQ *markup-verbose-mode* t)))))))
;; line 399 "markup.nw"
(defmacro markup-letter-group-list (&key open close sep)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 260 "markup.nw"
((and sep (not (stringp sep)))
(nraw "parameter `~S' is not a string! (ignored)~%" sep))
;; line 401 "markup.nw"
(t `(markup::define-list-environment-methods
DO-MARKUP-LETTER-GROUP-LIST ()
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))
:sep ,(when sep `((do-markup-string ,sep)))))))
;; line 443 "markup.nw"
(defmacro markup-letter-group (&whole whole &rest args)
(destructuring-switch-bind (&key
open close group
open-head close-head
&switch
upcase downcase capitalize)
args
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 451 "markup.nw"
;; line 252 "markup.nw"
((and open-head (not (stringp open-head)))
(nraw "parameter `~S' is not a string! (ignored)~%" open-head))
((and close-head (not (stringp close-head)))
(nraw "parameter `~S' is not a string! (ignored)~%" close-head))
;; line 452 "markup.nw"
;; line 275 "markup.nw"
((and group (progn
(setq group (stringify group))
(not (lookup-letter-group-definition *indexstyle* group))))
(nraw "parameter `~S' is not a valid letter-group! (ignored)~%" group))
;; line 453 "markup.nw"
((or (and upcase downcase)
(and upcase capitalize)
(and downcase capitalize))
(error "more than one modifier in~%~S" whole))
(t `(LET ()
(markup::define-environment-methods
DO-MARKUP-LETTER-GROUP
(,(if group
`(lg-def (EQL ',(lookup-letter-group-definition
*indexstyle* group)))
'(lg-def letter-group-definition)))
:declare ((declare (ignore lg-def)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close))))
(markup::define-environment-methods
DO-MARKUP-LETTER-GROUP-HEAD
(,(if group
`(lg-def (EQL ',(lookup-letter-group-definition
*indexstyle* group)))
'(lg-def letter-group-definition)))
:declare ((declare (ignore lg-def)))
:open ,(when open-head `((do-markup-string ,open-head)))
:close ,(when close-head `((do-markup-string ,close-head))))
,(when (or open-head close-head)
`(markup::define-method
DO-MARKUP-LETTER-GROUP-HEAD
(,(if group
`(lg-def (EQL ',(lookup-letter-group-definition
*indexstyle* group)))
'(lg-def letter-group-definition)))
:body ((do-markup-string
,(cond (upcase `(string-upcase
(get-name lg-def)))
(downcase `(string-downcase
(get-name lg-def)))
(capitalize `(string-capitalize
(get-name lg-def)))
(t `(get-name lg-def))))))))))))
;; line 512 "markup.nw"
(defmacro markup-indexentry-list (&key open close sep depth)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 260 "markup.nw"
((and sep (not (stringp sep)))
(nraw "parameter `~S' is not a string! (ignored)~%" sep))
;; line 514 "markup.nw"
;; line 265 "markup.nw"
((and depth (not (integerp depth)))
(nraw "parameter `~S' is not a number! (ignored)~%" depth))
;; line 515 "markup.nw"
(t `(markup::define-list-environment-methods
DO-MARKUP-INDEXENTRY-LIST
(,(if depth `(depth (EQL ,depth)) '(depth number)))
:declare ((declare (ignore depth)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))
:sep ,(when sep `((do-markup-string ,sep)))))))
;; line 579 "markup.nw"
(defmacro markup-indexentry (&key open close depth)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 581 "markup.nw"
;; line 265 "markup.nw"
((and depth (not (integerp depth)))
(nraw "parameter `~S' is not a number! (ignored)~%" depth))
;; line 582 "markup.nw"
(t `(markup::define-environment-methods
DO-MARKUP-INDEXENTRY
(,(if depth `(depth (EQL ,depth)) '(depth number)))
:declare ((declare (ignore depth)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))))))
;; line 604 "markup.nw"
(defmacro markup-keyword-list (&key open close sep depth)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 260 "markup.nw"
((and sep (not (stringp sep)))
(nraw "parameter `~S' is not a string! (ignored)~%" sep))
;; line 606 "markup.nw"
;; line 265 "markup.nw"
((and depth (not (integerp depth)))
(nraw "parameter `~S' is not a number! (ignored)~%" depth))
;; line 607 "markup.nw"
(t `(markup::define-list-environment-methods
DO-MARKUP-KEYWORD-LIST
(,(if depth `(depth (EQL ,depth)) '(depth number)))
:declare ((declare (ignore depth)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))
:sep ,(when sep `((do-markup-string ,sep)))))))
;; line 632 "markup.nw"
(defmacro markup-keyword (&key open close depth)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 634 "markup.nw"
;; line 265 "markup.nw"
((and depth (not (integerp depth)))
(nraw "parameter `~S' is not a number! (ignored)~%" depth))
;; line 635 "markup.nw"
(t `(markup::define-environment-methods
DO-MARKUP-KEYWORD
(,(if depth `(depth (EQL ,depth)) '(depth number)))
:declare ((declare (ignore depth)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))))))
;; line 663 "markup.nw"
(defmacro markup-locclass-list (&key open close sep)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 260 "markup.nw"
((and sep (not (stringp sep)))
(nraw "parameter `~S' is not a string! (ignored)~%" sep))
;; line 665 "markup.nw"
(t `(markup::define-list-environment-methods
DO-MARKUP-LOCCLASS-LIST ()
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))
:sep ,(when sep `((do-markup-string ,sep)))))))
;; line 699 "markup.nw"
(defmacro markup-locref-class (&key open close class)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 701 "markup.nw"
;; line 282 "markup.nw"
((and class (progn (setq class (stringify class))
(not (lookup-locref-class *indexstyle* class))))
(nraw "parameter `~S' is not a location-reference class! (ignored)~%" class))
;; line 702 "markup.nw"
(t `(markup::define-list-environment-methods
DO-MARKUP-LOCREF-CLASS
(,(if class
`(locrefcls (EQL ',(cdr (lookup-locref-class
*indexstyle* class))))
'(locrefcls layered-location-class)))
:declare ((declare (ignore locrefcls)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))))))
;; line 727 "markup.nw"
(defmacro markup-attribute-group-list (&key open close sep)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 260 "markup.nw"
((and sep (not (stringp sep)))
(nraw "parameter `~S' is not a string! (ignored)~%" sep))
;; line 729 "markup.nw"
(t `(markup::define-list-environment-methods
DO-MARKUP-ATTRIBUTE-GROUP-LIST ()
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))
:sep ,(when sep `((do-markup-string ,sep)))))))
;; line 759 "markup.nw"
(defmacro markup-attribute-group (&key open close group)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 761 "markup.nw"
;; line 275 "markup.nw"
((and group (progn
(setq group (stringify group))
(not (lookup-letter-group-definition *indexstyle* group))))
(nraw "parameter `~S' is not a valid letter-group! (ignored)~%" group))
;; line 762 "markup.nw"
(t `(markup::define-environment-methods
DO-MARKUP-ATTRIBUTE-GROUP
(,(if group
`(ordnum (EQL ,group))
'(ordnum number)))
:declare ((declare (ignore ordnum)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))))))
;; line 786 "markup.nw"
(defmacro markup-locref-list (&key open close sep class depth)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 260 "markup.nw"
((and sep (not (stringp sep)))
(nraw "parameter `~S' is not a string! (ignored)~%" sep))
;; line 788 "markup.nw"
;; line 265 "markup.nw"
((and depth (not (integerp depth)))
(nraw "parameter `~S' is not a number! (ignored)~%" depth))
;; line 789 "markup.nw"
;; line 282 "markup.nw"
((and class (progn (setq class (stringify class))
(not (lookup-locref-class *indexstyle* class))))
(nraw "parameter `~S' is not a location-reference class! (ignored)~%" class))
;; line 790 "markup.nw"
(t `(markup::define-list-environment-methods
DO-MARKUP-LOCREF-LIST
(,(if class
`(locrefcls (EQL ',(cdr (lookup-locref-class
*indexstyle* class))))
'(locrefcls layered-location-class))
,(if depth `(depth (EQL ,depth)) '(depth number)))
:declare ((declare (ignore locrefcls depth)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))
:sep ,(when sep `((do-markup-string ,sep)))))))
;; line 865 "markup.nw"
(defmacro markup-locref-layer-list (&key open close sep class depth)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 260 "markup.nw"
((and sep (not (stringp sep)))
(nraw "parameter `~S' is not a string! (ignored)~%" sep))
;; line 867 "markup.nw"
;; line 265 "markup.nw"
((and depth (not (integerp depth)))
(nraw "parameter `~S' is not a number! (ignored)~%" depth))
;; line 868 "markup.nw"
;; line 282 "markup.nw"
((and class (progn (setq class (stringify class))
(not (lookup-locref-class *indexstyle* class))))
(nraw "parameter `~S' is not a location-reference class! (ignored)~%" class))
;; line 869 "markup.nw"
(t `(markup::define-list-environment-methods
DO-MARKUP-LOCREF-LAYER-LIST
(,(if class
`(locrefcls (EQL ',(cdr (lookup-locref-class
*indexstyle* class))))
'(locrefcls layered-location-class))
,(if depth `(depth (EQL ,depth)) '(depth number)))
:declare ((declare (ignore locrefcls depth)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))
:sep ,(when sep `((do-markup-string ,sep)))))))
;; line 899 "markup.nw"
(defmacro markup-locref-layer (&key class open close depth layer)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 901 "markup.nw"
;; line 265 "markup.nw"
((and depth (not (integerp depth)))
(nraw "parameter `~S' is not a number! (ignored)~%" depth))
;; line 902 "markup.nw"
;; line 270 "markup.nw"
((and layer (not (integerp layer)))
(nraw "parameter `~S' is not a number! (ignored)~%" layer))
;; line 903 "markup.nw"
;; line 282 "markup.nw"
((and class (progn (setq class (stringify class))
(not (lookup-locref-class *indexstyle* class))))
(nraw "parameter `~S' is not a location-reference class! (ignored)~%" class))
;; line 904 "markup.nw"
(t `(markup::define-environment-methods
DO-MARKUP-LOCREF-LAYER
(,(if class
`(locrefcls (EQL ',(cdr (lookup-locref-class
*indexstyle* class))))
'(locrefcls layered-location-class))
,(if depth `(depth (EQL ,depth)) '(depth number))
,(if layer `(layer (EQL ,layer)) '(layer number)))
:declare ((declare (ignore depth layer)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))))))
;; line 930 "markup.nw"
(defmacro markup-locref (&key open close class attr depth)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 932 "markup.nw"
;; line 294 "markup.nw"
((and attr (progn (setq attr (stringify attr))
(not (lookup-catattr *indexstyle* attr))))
(nraw "parameter `~S' is not an attribute! (ignored)~%" attr))
;; line 933 "markup.nw"
;; line 265 "markup.nw"
((and depth (not (integerp depth)))
(nraw "parameter `~S' is not a number! (ignored)~%" depth))
;; line 934 "markup.nw"
;; line 282 "markup.nw"
((and class (progn (setq class (stringify class))
(not (lookup-locref-class *indexstyle* class))))
(nraw "parameter `~S' is not a location-reference class! (ignored)~%" class))
;; line 935 "markup.nw"
(t `(markup::define-environment-methods
DO-MARKUP-LOCREF
(,(if attr
`(attr (EQL ',(lookup-catattr *indexstyle* attr)))
'(attr category-attribute))
,(if class
`(locrefcls (EQL ',(cdr (lookup-locref-class
*indexstyle* class))))
'(locrefcls layered-location-class))
,(if depth `(depth (EQL ,depth)) '(depth number)))
:declare ((declare (ignore attr locrefcls depth)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))))))
;; line 1002 "markup.nw"
(defmacro markup-range (&whole whole &rest args)
(destructuring-switch-bind (&key
open close sep class length
&switch ignore-end)
args
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 260 "markup.nw"
((and sep (not (stringp sep)))
(nraw "parameter `~S' is not a string! (ignored)~%" sep))
;; line 1008 "markup.nw"
;; line 282 "markup.nw"
((and class (progn (setq class (stringify class))
(not (lookup-locref-class *indexstyle* class))))
(nraw "parameter `~S' is not a location-reference class! (ignored)~%" class))
;; line 1009 "markup.nw"
((and length (not (numberp length)))
(nraw "parameter `~S' is not a number! (ignored)~%" length))
(t `(let ()
(markup::define-list-environment-methods
DO-MARKUP-RANGE
(,(if class
`(locrefcls (EQL ',(cdr (lookup-locref-class
*indexstyle* class))))
'(locrefcls layered-location-class))
,(if length
`(length (EQL ,length))
'(length number)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))
:sep ,(when sep `((do-markup-string ,sep))))
(define-method markup::MARKUP-RANGE-PRINT-END-P
(,(if class
`(locrefcls (EQL ',(cdr (lookup-locref-class
*indexstyle* class))))
'(locrefcls layered-location-class))
,(if length
`(length (EQL ,length))
'(length number)))
:declare ((declare (ignore locrefcls length)))
:body (,(not ignore-end))))))))
;; line 1064 "markup.nw"
(defmacro markup-crossref-list (&key open sep close class)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 260 "markup.nw"
((and sep (not (stringp sep)))
(nraw "parameter `~S' is not a string! (ignored)~%" sep))
;; line 1066 "markup.nw"
;; line 288 "markup.nw"
((and class (progn (setq class (stringify class))
(not (lookup-crossref-class *indexstyle* class))))
(nraw "parameter `~S' is not a cross-reference class! (ignored)~%" class))
;; line 1067 "markup.nw"
(t `(markup::define-list-environment-methods
DO-MARKUP-CROSSREF-LIST
(,(if class
`(xrefcls (EQL ',(cdr (lookup-crossref-class *indexstyle*
class))))
'(xrefcls crossref-location-class)))
:declare ((declare (ignore xrefcls)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))
:sep ,(when sep `((do-markup-string ,sep)))))))
;; line 1103 "markup.nw"
(defmacro markup-crossref-layer-list (&key open sep close class)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 260 "markup.nw"
((and sep (not (stringp sep)))
(nraw "parameter `~S' is not a string! (ignored)~%" sep))
;; line 1105 "markup.nw"
;; line 288 "markup.nw"
((and class (progn (setq class (stringify class))
(not (lookup-crossref-class *indexstyle* class))))
(nraw "parameter `~S' is not a cross-reference class! (ignored)~%" class))
;; line 1106 "markup.nw"
(t `(markup::define-list-environment-methods
DO-MARKUP-CROSSREF-LAYER-LIST
(,(if class
`(xrefcls (EQL ',(cdr (lookup-crossref-class *indexstyle*
class))))
'(xrefcls crossref-location-class)))
:declare ((declare (ignore xrefcls)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))
:sep ,(when sep `((do-markup-string ,sep)))))))
;; line 1134 "markup.nw"
(defmacro markup-crossref-layer (&key open close class)
(cond
;; line 245 "markup.nw"
((and open (not (stringp open)))
(nraw "parameter `~S' is not a string! (ignored)~%" open))
((and close (not (stringp close)))
(nraw "parameter `~S' is not a string! (ignored)~%" close))
;; line 1136 "markup.nw"
;; line 288 "markup.nw"
((and class (progn (setq class (stringify class))
(not (lookup-crossref-class *indexstyle* class))))
(nraw "parameter `~S' is not a cross-reference class! (ignored)~%" class))
;; line 1137 "markup.nw"
(t `(markup::define-list-environment-methods
DO-MARKUP-CROSSREF-LAYER
(,(if class
`(xrefcls (EQL ',(cdr (lookup-crossref-class *indexstyle*
class))))
'(xrefcls crossref-location-class)))
:declare ((declare (ignore xrefcls)))
:open ,(when open `((do-markup-string ,open)))
:close ,(when close `((do-markup-string ,close)))))))
;; line 1188 "markup.nw"
(eval-when (compile load eval)
(defparameter *markup-user-interface-definitions*
'(*markup-verbose-mode*
*markup-verbose-open*
*markup-verbose-close*
markup-crossref-layer
markup-crossref-layer-list
markup-crossref-list
markup-index
markup-letter-group
markup-letter-group-list
markup-indexentry
markup-indexentry-list
markup-keyword
markup-keyword-list
markup-locclass-list
markup-locref-class
markup-attribute-group-list
markup-attribute-group
markup-locref-list
markup-locref
markup-locref-layer-list
markup-locref-layer
markup-range
markup-trace
)))
;; line 1238 "markup.nw"
(eval-when (compile load eval)
;; line 89 "markup.nw"
(export '(*markup-output-stream*
*markup-verbose-mode*
*markup-verbose-open*
*markup-verbose-close*
*indexstyle-readtable*))
;; line 347 "markup.nw"
(export '(do-markup-index))
;; line 1217 "markup.nw"
(export '*markup-user-interface-definitions*)
(export *markup-user-interface-definitions*)
;; line 1240 "markup.nw"
)
;; line 1178 "markup.nw"
(defvar *RCS-Identifier* '(
;; line 1244 "markup.nw"
("markup" . "$Id: markup.nw,v 1.24 1997/03/26 16:18:58 kehr Exp $")
;; line 236 "startup.nw"
("startup" . "$Id: startup.nw,v 1.17 1997/03/26 16:19:03 kehr Exp $")
;; line 1178 "markup.nw"
))
;; this should be the last of the module since it defines the
;; additional package `xindy'.
;; line 210 "startup.nw"
;; $Id: startup.nw,v 1.17 1997/03/26 16:19:03 kehr Exp $
(lisp:defpackage "XINDY")
(lisp:in-package "XINDY")
(eval-when (compile load eval)
(lisp:use-package "BASE")
(lisp:use-package :xindy-version)
(lisp:use-package "MARKUP")
(lisp:use-package "CLOS")
(lisp:use-package "COMMON-LISP")
#+CLISP (lisp:use-package "EXT")
(lisp:import markup:*markup-user-interface-definitions*))
(eval-when (compile load eval)
(pushnew :HANDLER *features*))
;; FIXME: error messages about package locks
;(eval-when (compile load eval)
; (pushnew :BREAK-DRIVER *features*))
;; line 44 "startup.nw"
(defun issue-startup-message ()
(info "xindy kernel version: ~A~%" *xindy-kernel-version*)
(info "~A version ~A~% architecture: ~A~%"
(lisp-implementation-type) (lisp-implementation-version)
(machine-version))
)
(defun startup (&key idxstyle rawindex output logfile
show-version markup-trace (trace-level 0))
(when show-version
(issue-startup-message)
(exit-normally))
(when markup-trace (setq *markup-verbose-mode* t))
#+:HANDLER
(handler-case
(do-startup idxstyle rawindex output logfile trace-level)
(error
(condition)
(oops* (simple-condition-format-string condition)
(simple-condition-format-arguments condition))
(error-exit)))
#-:HANDLER
(do-startup idxstyle rawindex output logfile trace-level))
;; line 70 "startup.nw"
(defun do-startup (idxstyle raw-index output logfile trace-level)
(set-searchpath-by-environment)
(setq custom:*default-file-encoding* charset:iso-8859-1)
(when logfile
(info "~&Opening logfile ~S " logfile)
(handler-case
(setq *logging-stream* (open logfile
:direction :output
:if-does-not-exist :create
:if-exists :supersede))
(error ()
(oops "Opening logfile ~S failed!" logfile)
(error-exit)))
(info "(done)~%")
;; Set necessary flags...
(setq *logging-on* t)
(case trace-level
(0)
(1 (setq *mappings-trace* t))
(2 (setq *mappings-trace* t) (setq *locref-trace* t))
(3 (setq *mappings-trace* t) (setq *locref-trace* t))
(t (error "Invalid :trace-level ~S !" trace-level)))
#+:ORDRULES (when *mappings-trace*
(setq ordrules::*message-logging* 1))
(multiple-value-bind (sec min hour day mon year)
(get-decoded-time)
(gol t ";; This logfile was generated automatically by `xindy'~%")
(gol t ";; at ~2,'0D.~2,'0D.~4,'0D ~2,'0D:~2,'0D:~2,'0D~%"
day mon year hour min sec))
(gol t ";; Indexstyle: ~S, Rawindex: ~S, Output: ~S~%~%"
idxstyle raw-index output)
)
(info "~&Reading indexstyle...~%")
(let ((*readtable* idxstyle:*indexstyle-readtable*))
(idxstyle:do-require idxstyle))
(info "~&Finished reading indexstyle.")
(info "~&Finalizing indexstyle... ")
(idxstyle:make-ready idxstyle:*indexstyle*)
(info "(done)~%~%")
(info "~&Reading raw-index ~S..." raw-index)
(load raw-index :verbose nil)
(info "~&Finished reading raw-index.~%~%")
(handler-case
(setq *markup-output-stream*
(open output
:direction :output
:if-does-not-exist :create
:if-exists :supersede))
(error ()
(oops "Opening file ~S failed!" output)
(error-exit)))
(info "~&Processing index...")
(index:process-index index:*index*)
(info "~&Finished processing index.~%~%")
(info "~&Writing markup...")
(markup:do-markup-index index:*index*)
(info "~%Markup written into file ~S.~%" output))
;; line 139 "startup.nw"
(defun set-searchpath-by-environment ()
(let ((sp (#+CLISP
system::getenv
#+ALLEGRO
sys:getenv
"XINDY_SEARCHPATH")))
(when sp (idxstyle:set-searchpath-by-string sp))))
;; line 170 "startup.nw"
#+:BREAK-DRIVER
(fmakunbound '*break-driver*)
#+:BREAK-DRIVER
(defun *break-driver* (continuable
&optional (condition nil) (print-it nil)
&aux (may-continue
(or continuable
(and condition
(find-restart 'continue condition))
) )
(interactive-p (interactive-stream-p *debug-io*))
(commandsr '())
)
(declare (ignore may-continue interactive-p commandsr))
;; This when-clause is from Bruno Haible.
(when (and condition print-it)
(terpri *error-output*)
(write-string "*** - " *error-output*)
#+CLISP (system::print-condition condition *error-output*)
#-CLISP (print condition *error-output*)
)
(format *ERROR-OUTPUT* "~&Bye.")
(error-exit))
#+:BREAK-DRIVER-OLD
(defun *break-driver* (continuable &rest rest)
(declare (ignore continuable rest))
(format *ERROR-OUTPUT* "~&Bye.")
(error-exit))
#+:BREAK-DRIVER
(eval-when (compile load eval)
(export '*break-driver*))
;; line 230 "startup.nw"
(eval-when (compile load eval)
;; line 135 "startup.nw"
(export '(startup *xindy-kernel-version*))
;; line 232 "startup.nw"
) |
#include <ctype.h>
#include <stddef.h>
#include <stdio.h>
#include <sys/queue.h>
#include "esp_console.h"
#include "esp_log.h"
#include "esp_system.h"
#include "argtable3/argtable3.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "linenoise/linenoise.h"
#include "circ_buf.h"
#include "log_common.h"
#include "log_buffer.h"
#include "log_print.h"
static EXT_RAM_BSS_ATTR char log_data[CONFIG_LOGGER_LOG_BUFFER_SIZE];
static circ_buf_t log_buf;
static uint32_t last_index = 0;
static struct {
uint32_t offset;
uint32_t entry;
} peek_cache = {};
static SemaphoreHandle_t xSemaphore = NULL;
static StaticSemaphore_t xSemaphoreBuffer;
struct log_header_s {
uint32_t index;
uint8_t core;
uint8_t level;
uint16_t data_len;
uint64_t timestamp;
char task[configMAX_TASK_NAME_LEN];
char tag[CONFIG_LOGGER_LOG_MAX_TAG_SIZE];
} __attribute__((packed));
static void purge_entry()
{
struct log_header_s header = {};
if (!circ_peek(&log_buf, (char *)&header, sizeof(struct log_header_s)))
return;
circ_pull_ptr_pulled(&log_buf, sizeof(struct log_header_s) + header.data_len);
memset(&peek_cache, 0, sizeof(peek_cache));
}
static void log_buffer_push_entry(struct log_entry_s *e)
{
struct log_header_s header = {
.index = last_index++,
.core = e->core,
.level = e->level,
.timestamp = e->timestamp,
.data_len = e->data_len,
};
strncpy(header.task, e->task, sizeof(header.task));
strncpy(header.tag, e->tag, sizeof(header.tag));
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) != pdTRUE) {
return;
}
// Free space in log header
while (circ_get_free_bytes(&log_buf) < (sizeof(struct log_header_s) + e->data_len)) {
purge_entry();
}
if (circ_push(&log_buf, (char *)&header, sizeof(struct log_header_s)) != sizeof(struct log_header_s))
abort();
if (circ_push(&log_buf, (char *)e->data, e->data_len) != e->data_len)
abort();
xSemaphoreGive(xSemaphore);
}
bool log_pull_entry(struct log_entry_s *entry)
{
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) != pdTRUE) {
return false;
}
struct log_header_s header = {};
// Peek entry, without pulling it
if (!circ_pull(&log_buf, (char *)&header, sizeof(header))) {
xSemaphoreGive(xSemaphore);
return false;
}
if (header.data_len == 0)
abort();
entry->core = header.core;
entry->level = header.level;
strncpy(entry->task, header.task, sizeof(entry->task));
strncpy(entry->tag, header.tag, sizeof(entry->tag));
entry->timestamp = header.timestamp;
entry->data_len = header.data_len;
if (header.data_len > sizeof(entry->data))
abort();
if (circ_pull(&log_buf, (char *)entry->data, header.data_len) != header.data_len)
abort();
memset(&peek_cache, 0, sizeof(peek_cache));
xSemaphoreGive(xSemaphore);
return true;
}
bool log_peek_entry(struct log_entry_s *entry, uint32_t *index)
{
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) != pdTRUE)
return false;
size_t offset = 0;
if (peek_cache.offset > 0 && peek_cache.entry > 0 && peek_cache.entry == *index) {
offset = peek_cache.offset;
}
// Lets search of an entry, that is greater than timestamp.
while (1) {
struct log_header_s header = {};
// Peek entry, without pulling it
if (circ_peek_offset(&log_buf, (char *)&header, sizeof(header), offset) != sizeof(header)) {
xSemaphoreGive(xSemaphore);
return false;
}
// Store offset in a local cache to speed up peeking.
peek_cache.entry = header.index;
peek_cache.offset = offset;
offset += sizeof(header);
if (header.index > *index) {
*index = header.index;
entry->core = header.core;
entry->level = header.level;
strcpy(entry->task, header.task);
strcpy(entry->tag, header.tag);
entry->timestamp = header.timestamp;
entry->data_len = header.data_len;
if (header.data_len < 1)
abort();
if (header.data_len > sizeof(entry->data))
abort();
if (circ_peek_offset(&log_buf, (char *)entry->data, header.data_len, offset) != header.data_len)
abort();
break;
}
offset += header.data_len;
};
xSemaphoreGive(xSemaphore);
return true;
}
struct log_buffer_stat {
size_t buffer_max_size_bytes;
size_t buffer_size_bytes;
size_t buffer_size_entries;
};
void log_buffer_stats(struct log_buffer_stat *stat)
{
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) != pdTRUE)
return;
memset(stat, 0, sizeof(struct log_buffer_stat));
stat->buffer_max_size_bytes = circ_total_size(&log_buf);
// Lets search of an entry, that is greater than timestamp.
while (1) {
struct log_header_s header = {};
// Peek entry, without pulling it
if (circ_peek_offset(&log_buf, (char *)&header, sizeof(header), stat->buffer_size_bytes) != sizeof(header)) {
xSemaphoreGive(xSemaphore);
return;
}
stat->buffer_size_bytes += sizeof(header) + header.data_len;
stat->buffer_size_entries++;
};
xSemaphoreGive(xSemaphore);
}
static struct {
struct arg_lit *clear;
struct arg_lit *color;
struct arg_lit *purge;
struct arg_lit *stats;
struct arg_end *end;
} dmesg_args;
static int cmd_dmesg(int argc, char **argv)
{
int nerrors = arg_parse(argc, argv, (void **)&dmesg_args);
if (nerrors != 0) {
arg_print_errors(stderr, dmesg_args.end, argv[0]);
return 1;
}
struct log_entry_s entry = {};
bool clear = dmesg_args.clear->count > 0;
bool color = dmesg_args.color->count > 0;
if (dmesg_args.purge->count > 0) {
while (log_pull_entry(&entry)) {
}
return 0;
}
if (dmesg_args.stats->count > 0) {
struct log_buffer_stat stat;
log_buffer_stats(&stat);
printf("Log buffer max size: %d bytes.\n", stat.buffer_max_size_bytes);
printf("Log buffer current size: %d bytes.\n", stat.buffer_size_bytes);
printf("Log buffer current size: %d entries.\n", stat.buffer_size_entries);
return 0;
}
if (clear) {
while (log_pull_entry(&entry)) {
if (color)
print_log_entry_color(&entry, stdout);
else
print_log_entry(&entry, stdout);
}
} else {
uint32_t index = 0;
while (log_peek_entry(&entry, &index)) {
if (color)
print_log_entry_color(&entry, stdout);
else
print_log_entry(&entry, stdout);
}
}
return 0;
}
esp_err_t log_buffer_early_init()
{
xSemaphore = xSemaphoreCreateBinaryStatic(&xSemaphoreBuffer);
circ_init(&log_buf, log_data, sizeof(log_data));
log_capture_register_handler(&log_buffer_push_entry);
xSemaphoreGive(xSemaphore);
return ESP_OK;
}
esp_err_t log_buffer_init(void)
{
dmesg_args.clear = arg_lit0("c", "clear", "Clear buffer on receive");
dmesg_args.color = arg_lit0("o", "color", "Color the output");
dmesg_args.purge = arg_lit0("p", "purge", "Purge buffer without printing");
dmesg_args.stats = arg_lit0("s", "stats", "Print log buffer stats");
dmesg_args.end = arg_end(2);
const esp_console_cmd_t dmesg_cmd = {
.command = "dmesg",
.help = "Print log buffer",
.hint = NULL,
.func = &cmd_dmesg,
.argtable = &dmesg_args,
};
ESP_ERROR_CHECK(esp_console_cmd_register(&dmesg_cmd));
return ESP_OK;
} |
#' Get and check and full file path
#'
#' @description This generic function takes a directory and
#' file name then checks to make sure they exist.
#' The parameter \code{check_mode} will also test to make sure
#' the file is readable (default) or writeable (\code{check_mode = "write"}).
#' By default it will return an error if the file doesn't exist
#' but with \code{create = TRUE} it will create an empty file with
#' appropriate permissions.
#'
#' @param directory The file directory
#' @param file_name The file name (with extension if not supplied to \code{ext})
#' @param ext The extension (type of the file) - optional
#' @param check_mode The mode passed to
#' [fs::file_access()], defaults to "read"
#' to check that you have read access to the file
#' @param create Optionally create the file if it doesn't exists,
#' the default is to only create a file if we set `check_mode = "write"`
#' @param file_name_regexp A regular expression to search for the file name
#' if this is used `file_name` should not be, it will return the most recently
#' created file using [find_latest_file()]
#' @param selection_method Passed only to [find_latest_file()], will select the
#' file based on latest modification date (default) or file name
#'
#' @return The full file path, an error will be thrown
#' if the path doesn't exist or it's not readable
#'
#' @family file path functions
#' @export
get_file_path <-
function(directory,
file_name = NULL,
ext = NULL,
check_mode = "read",
create = NULL,
file_name_regexp = NULL,
selection_method = "modification_date") {
if (!fs::dir_exists(directory)) {
cli::cli_abort("The directory {.path {directory}} does not exist.")
}
check_mode <- match.arg(
arg = check_mode,
choices = c("exists", "read", "write", "execute")
)
if (!is.null(file_name)) {
file_path <- fs::path(directory, file_name)
} else if (!is.null(file_name_regexp)) {
if (check_mode == "read") {
file_path <- find_latest_file(directory,
regexp = file_name_regexp,
selection_method = selection_method
)
} else {
cli::cli_abort(
c("{.arg check_mode = \"{check_mode}\"} can't be used to
find the latest file with {.arg file_name_regexp}",
"v" = "Try {.arg check_mode = \"read\"}"
)
)
}
} else {
cli::cli_abort(
"You must specify a {.var file_name} or a regular expression
to search for with {.var file_name_regexp}"
)
}
if (!is.null(ext)) {
file_path <- fs::path_ext_set(file_path, ext)
}
if (!fs::file_exists(file_path) && check_mode != "exists") {
if (is.null(create) && check_mode == "write" ||
!is.null(create) && create == TRUE) {
# The file doesn't exist but we do want to create it
fs::file_create(file_path)
cli::cli_alert_info(
"The file {.file {fs::path_file(file_path)}} did not exist in
{.path {directory}}, it has now been created."
)
} else {
possible_file_name <- fs::path_file(
fs::dir_ls(
directory,
regexp = fs::path_ext_remove(file_path),
ignore.case = TRUE
)
)
error_text <- "The file {.file {fs::path_file(file_path)}} does not
exist in {.path {directory}}"
if (length(possible_file_name) == 1L) {
# There was a file matching the name, except for case differences.
error_text <- c(
error_text,
">" = "Did you mean {.file {possible_file_name}}?"
)
}
# The file doesn't exist and we don't want to create it
cli::cli_abort(error_text)
}
} else if (check_mode == "exists") {
if (!fs::file_exists(file_path)) {
return(FALSE)
}
}
if (!fs::file_access(file_path, mode = check_mode)) {
cli::cli_abort(
"{.file {fs::path_file(file_path)}} exists in {.path {directory}} but is
not {check_mode}able."
)
}
return(file_path)
}
#' SLF directory - hscdiip
#'
#' @description File path for the general SLF directory for accessing HSCDIIP
#' folders/files
#'
#' @return The path to the main SLF Extracts folder
#' @export
#'
#' @family directories
get_slf_dir <- function() {
slf_dir <- fs::path("/", "conf", "hscdiip", "SLF_Extracts")
return(slf_dir)
}
#' SLF directory - sourcedev / Source_Linkage_File_Updates
#'
#' @description File path for the SLF development directory on `sourcedev`
#'
#' @return The path to the main SLF dev folder
#' @export
#'
#' @family directories
get_dev_dir <- function() {
fs::path("/", "conf", "sourcedev", "Source_Linkage_File_Updates")
}
#' Year Directory
#'
#' @description Get the directory for Source Linkage File Updates for the given
#' year.
#'
#' @param year The Financial Year e.g. 1718
#' @param extracts_dir (optional) Whether to
#' return the Extracts folder (`TRUE`) or the top-level
#' folder (`FALSE`).
#'
#' @return The file path to the year directory (on sourcedev)
#' @export
#'
#' @family directories
get_year_dir <- function(year, extracts_dir = FALSE) {
year_dir <- fs::path(get_dev_dir(), year)
if (!fs::dir_exists(year_dir)) {
fs::dir_create(year_dir)
cli::cli_alert_info(
"{.path {year_dir}} did not exist, it has now been created."
)
}
if (extracts_dir) {
year_extracts_dir <- fs::path(year_dir, "Extracts")
if (!fs::dir_exists(year_extracts_dir)) {
fs::dir_create(year_extracts_dir)
cli::cli_alert_info(
"{.path {year_extracts_dir}} did not exist, it has now been created."
)
}
return(year_extracts_dir)
} else {
return(year_dir)
}
} |
#
# (C) Tenable Network Security, Inc.
#
include("compat.inc");
if (description)
{
script_id(69137);
script_version("$Revision: 1.4 $");
script_cvs_date("$Date: 2016/11/01 19:59:57 $");
script_cve_id("CVE-2013-2577", "CVE-2013-3492", "CVE-2013-3493");
script_bugtraq_id(61397, 61503, 61505);
script_osvdb_id(95580);
script_xref(name:"Secunia", value:"54174");
script_xref(name:"EDB-ID", value:"27049");
script_name(english:"XnView 2.x < 2.04 Multiple Buffer Overflow Vulnerabilities");
script_summary(english:"Checks XnView.exe's Product Version number");
script_set_attribute(
attribute:"synopsis",
value:
"The remote Windows host contains an application that is affected by
multiple buffer overflow vulnerabilities."
);
script_set_attribute(
attribute:"description",
value:
"The version of XnView installed on the remote Windows host is 2.x,
earlier than 2.04. It is, therefore, reportedly affected by the
following overflow vulnerabilities:
- An unspecified error exists that could allow a buffer
overflow during 'PCT' file handling. (CVE-2013-2577)
- Unspecified errors exist that could allow heap-based
buffer overflows during 'FPX' and 'PSP' file handling.
(CVE-2013-3492, CVE-2013-3493)"
);
# Release notes
script_set_attribute(attribute:"see_also", value:"http://newsgroup.xnview.com/viewtopic.php?f=35&t=28400");
script_set_attribute(attribute:"see_also", value:"http://seclists.org/bugtraq/2013/Jul/152");
script_set_attribute(attribute:"solution", value:"Upgrade to XnView version 2.04 or later.");
script_set_cvss_base_vector("CVSS2#AV:N/AC:M/Au:N/C:C/I:C/A:C");
script_set_cvss_temporal_vector("CVSS2#E:POC/RL:OF/RC:C");
script_set_attribute(attribute:"exploitability_ease", value:"Exploits are available");
script_set_attribute(attribute:"exploit_available", value:"true");
script_set_attribute(attribute:"exploit_framework_core", value:"true");
script_set_attribute(attribute:"vuln_publication_date", value:"2013/07/22");
script_set_attribute(attribute:"patch_publication_date", value:"2013/07/18");
script_set_attribute(attribute:"plugin_publication_date", value:"2013/07/30");
script_set_attribute(attribute:"plugin_type", value:"local");
script_set_attribute(attribute:"cpe", value:"cpe:/a:xnview:xnview");
script_end_attributes();
script_category(ACT_GATHER_INFO);
script_family(english:"Windows");
script_copyright(english:"This script is Copyright (C) 2013-2016 Tenable Network Security, Inc.");
script_dependencies("xnview_rgbe_overflow.nasl");
script_require_keys("SMB/XnView/Version");
exit(0);
}
include("audit.inc");
include("global_settings.inc");
include("misc_func.inc");
kb_base = "SMB/XnView";
get_kb_item_or_exit(kb_base+"/Installed");
path = get_kb_item_or_exit(kb_base+"/Path");
version = get_kb_item_or_exit(kb_base+"/Version", exit_code:1);
# Check the version number.
ver = split(version, sep:'.', keep:FALSE);
for (i=0; i<max_index(ver); i++)
ver[i] = int(ver[i]);
# 2.00 < 2.03
if (ver[0] == 2 && ver[1] < 4)
{
port = get_kb_item("SMB/transport");
if (!port) port = 445;
if (report_verbosity > 0)
{
report =
'\n Path : ' + path +
'\n Installed version : ' + version +
'\n Fixed version : 2.04\n';
security_hole(port:port, extra:report);
}
else security_hole(port);
}
else audit(AUDIT_INST_PATH_NOT_VULN, "XnView", version, path); |
import 'package:dartz/dartz.dart';
import 'package:equatable/equatable.dart';
import '../../../core/error/failure.dart';
import '../../../core/usecase/usecase.dart';
import '../entities/person_entity.dart';
import '../repositories/person_repository.dart';
class GetAllPersons extends UseCase<List<PersonEntity>, PagePersonParams> {
final PersonRepository personRepository;
GetAllPersons(this.personRepository);
@override
Future<Either<Failure, List<PersonEntity>>> call(
PagePersonParams params) async {
return await personRepository.getAllPersons(params.page);
}
}
class PagePersonParams extends Equatable {
final int page;
PagePersonParams({required this.page});
@override
List<Object> get props => [page];
} |
/*
* Copyright (c) 2013 Samsung Electronics Co., Ltd.
* Copyright (c) 2013 Linaro Ltd.
* Author: Thomas Abraham <thomas.ab@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Common Clock Framework support for all Samsung platforms
*/
#ifndef __SAMSUNG_CLK_H
#define __SAMSUNG_CLK_H
#include <linux/clkdev.h>
#include <linux/clk-provider.h>
#include "clk-pll.h"
/**
* struct samsung_clk_provider: information about clock provider
* @reg_base: virtual address for the register base.
* @clk_data: holds clock related data like clk* and number of clocks.
* @lock: maintains exclusion between callbacks for a given clock-provider.
*/
struct samsung_clk_provider {
void __iomem *reg_base;
struct clk_onecell_data clk_data;
spinlock_t lock;
};
/**
* struct samsung_clock_alias: information about mux clock
* @id: platform specific id of the clock.
* @dev_name: name of the device to which this clock belongs.
* @alias: optional clock alias name to be assigned to this clock.
*/
struct samsung_clock_alias {
unsigned int id;
const char *dev_name;
const char *alias;
};
#define ALIAS(_id, dname, a) \
{ \
.id = _id, \
.dev_name = dname, \
.alias = a, \
}
#define MHZ (1000 * 1000)
/**
* struct samsung_fixed_rate_clock: information about fixed-rate clock
* @id: platform specific id of the clock.
* @name: name of this fixed-rate clock.
* @parent_name: optional parent clock name.
* @flags: optional fixed-rate clock flags.
* @fixed-rate: fixed clock rate of this clock.
*/
struct samsung_fixed_rate_clock {
unsigned int id;
char *name;
const char *parent_name;
unsigned long flags;
unsigned long fixed_rate;
};
#define FRATE(_id, cname, pname, f, frate) \
{ \
.id = _id, \
.name = cname, \
.parent_name = pname, \
.flags = f, \
.fixed_rate = frate, \
}
/*
* struct samsung_fixed_factor_clock: information about fixed-factor clock
* @id: platform specific id of the clock.
* @name: name of this fixed-factor clock.
* @parent_name: parent clock name.
* @mult: fixed multiplication factor.
* @div: fixed division factor.
* @flags: optional fixed-factor clock flags.
*/
struct samsung_fixed_factor_clock {
unsigned int id;
char *name;
const char *parent_name;
unsigned long mult;
unsigned long div;
unsigned long flags;
};
#define FFACTOR(_id, cname, pname, m, d, f) \
{ \
.id = _id, \
.name = cname, \
.parent_name = pname, \
.mult = m, \
.div = d, \
.flags = f, \
}
/**
* struct samsung_mux_clock: information about mux clock
* @id: platform specific id of the clock.
* @dev_name: name of the device to which this clock belongs.
* @name: name of this mux clock.
* @parent_names: array of pointer to parent clock names.
* @num_parents: number of parents listed in @parent_names.
* @flags: optional flags for basic clock.
* @offset: offset of the register for configuring the mux.
* @shift: starting bit location of the mux control bit-field in @reg.
* @width: width of the mux control bit-field in @reg.
* @mux_flags: flags for mux-type clock.
* @alias: optional clock alias name to be assigned to this clock.
*/
struct samsung_mux_clock {
unsigned int id;
const char *dev_name;
const char *name;
const char *const *parent_names;
u8 num_parents;
unsigned long flags;
unsigned long offset;
u8 shift;
u8 width;
u8 mux_flags;
const char *alias;
};
#define __MUX(_id, dname, cname, pnames, o, s, w, f, mf, a) \
{ \
.id = _id, \
.dev_name = dname, \
.name = cname, \
.parent_names = pnames, \
.num_parents = ARRAY_SIZE(pnames), \
.flags = (f) | CLK_SET_RATE_NO_REPARENT, \
.offset = o, \
.shift = s, \
.width = w, \
.mux_flags = mf, \
.alias = a, \
}
#define MUX(_id, cname, pnames, o, s, w) \
__MUX(_id, NULL, cname, pnames, o, s, w, 0, 0, NULL)
#define MUX_A(_id, cname, pnames, o, s, w, a) \
__MUX(_id, NULL, cname, pnames, o, s, w, 0, 0, a)
#define MUX_F(_id, cname, pnames, o, s, w, f, mf) \
__MUX(_id, NULL, cname, pnames, o, s, w, f, mf, NULL)
#define MUX_FA(_id, cname, pnames, o, s, w, f, mf, a) \
__MUX(_id, NULL, cname, pnames, o, s, w, f, mf, a)
/**
* @id: platform specific id of the clock.
* struct samsung_div_clock: information about div clock
* @dev_name: name of the device to which this clock belongs.
* @name: name of this div clock.
* @parent_name: name of the parent clock.
* @flags: optional flags for basic clock.
* @offset: offset of the register for configuring the div.
* @shift: starting bit location of the div control bit-field in @reg.
* @div_flags: flags for div-type clock.
* @alias: optional clock alias name to be assigned to this clock.
*/
struct samsung_div_clock {
unsigned int id;
const char *dev_name;
const char *name;
const char *parent_name;
unsigned long flags;
unsigned long offset;
u8 shift;
u8 width;
u8 div_flags;
const char *alias;
struct clk_div_table *table;
};
#define __DIV(_id, dname, cname, pname, o, s, w, f, df, a, t) \
{ \
.id = _id, \
.dev_name = dname, \
.name = cname, \
.parent_name = pname, \
.flags = f, \
.offset = o, \
.shift = s, \
.width = w, \
.div_flags = df, \
.alias = a, \
.table = t, \
}
#define DIV(_id, cname, pname, o, s, w) \
__DIV(_id, NULL, cname, pname, o, s, w, 0, 0, NULL, NULL)
#define DIV_A(_id, cname, pname, o, s, w, a) \
__DIV(_id, NULL, cname, pname, o, s, w, 0, 0, a, NULL)
#define DIV_F(_id, cname, pname, o, s, w, f, df) \
__DIV(_id, NULL, cname, pname, o, s, w, f, df, NULL, NULL)
#define DIV_T(_id, cname, pname, o, s, w, t) \
__DIV(_id, NULL, cname, pname, o, s, w, 0, 0, NULL, t)
/**
* struct samsung_gate_clock: information about gate clock
* @id: platform specific id of the clock.
* @dev_name: name of the device to which this clock belongs.
* @name: name of this gate clock.
* @parent_name: name of the parent clock.
* @flags: optional flags for basic clock.
* @offset: offset of the register for configuring the gate.
* @bit_idx: bit index of the gate control bit-field in @reg.
* @gate_flags: flags for gate-type clock.
* @alias: optional clock alias name to be assigned to this clock.
*/
struct samsung_gate_clock {
unsigned int id;
const char *dev_name;
const char *name;
const char *parent_name;
unsigned long flags;
unsigned long offset;
u8 bit_idx;
u8 gate_flags;
const char *alias;
};
#define __GATE(_id, dname, cname, pname, o, b, f, gf, a) \
{ \
.id = _id, \
.dev_name = dname, \
.name = cname, \
.parent_name = pname, \
.flags = f, \
.offset = o, \
.bit_idx = b, \
.gate_flags = gf, \
.alias = a, \
}
#define GATE(_id, cname, pname, o, b, f, gf) \
__GATE(_id, NULL, cname, pname, o, b, f, gf, NULL)
#define GATE_A(_id, cname, pname, o, b, f, gf, a) \
__GATE(_id, NULL, cname, pname, o, b, f, gf, a)
#define GATE_D(_id, dname, cname, pname, o, b, f, gf) \
__GATE(_id, dname, cname, pname, o, b, f, gf, NULL)
#define GATE_DA(_id, dname, cname, pname, o, b, f, gf, a) \
__GATE(_id, dname, cname, pname, o, b, f, gf, a)
#define PNAME(x) static const char *x[] __initdata
/**
* struct samsung_clk_reg_dump: register dump of clock controller registers.
* @offset: clock register offset from the controller base address.
* @value: the value to be register at offset.
*/
struct samsung_clk_reg_dump {
u32 offset;
u32 value;
};
/**
* struct samsung_pll_clock: information about pll clock
* @id: platform specific id of the clock.
* @dev_name: name of the device to which this clock belongs.
* @name: name of this pll clock.
* @parent_name: name of the parent clock.
* @flags: optional flags for basic clock.
* @con_offset: offset of the register for configuring the PLL.
* @lock_offset: offset of the register for locking the PLL.
* @type: Type of PLL to be registered.
* @alias: optional clock alias name to be assigned to this clock.
*/
struct samsung_pll_clock {
unsigned int id;
const char *dev_name;
const char *name;
const char *parent_name;
unsigned long flags;
int con_offset;
int lock_offset;
enum samsung_pll_type type;
const struct samsung_pll_rate_table *rate_table;
const char *alias;
};
#define __PLL(_typ, _id, _dname, _name, _pname, _flags, _lock, _con, \
_rtable, _alias) \
{ \
.id = _id, \
.type = _typ, \
.dev_name = _dname, \
.name = _name, \
.parent_name = _pname, \
.flags = CLK_GET_RATE_NOCACHE, \
.con_offset = _con, \
.lock_offset = _lock, \
.rate_table = _rtable, \
.alias = _alias, \
}
#define PLL(_typ, _id, _name, _pname, _lock, _con, _rtable) \
__PLL(_typ, _id, NULL, _name, _pname, CLK_GET_RATE_NOCACHE, \
_lock, _con, _rtable, _name)
#define PLL_A(_typ, _id, _name, _pname, _lock, _con, _alias, _rtable) \
__PLL(_typ, _id, NULL, _name, _pname, CLK_GET_RATE_NOCACHE, \
_lock, _con, _rtable, _alias)
struct samsung_clock_reg_cache {
struct list_head node;
void __iomem *reg_base;
struct samsung_clk_reg_dump *rdump;
unsigned int rd_num;
};
struct samsung_cmu_info {
/* list of pll clocks and respective count */
struct samsung_pll_clock *pll_clks;
unsigned int nr_pll_clks;
/* list of mux clocks and respective count */
struct samsung_mux_clock *mux_clks;
unsigned int nr_mux_clks;
/* list of div clocks and respective count */
struct samsung_div_clock *div_clks;
unsigned int nr_div_clks;
/* list of gate clocks and respective count */
struct samsung_gate_clock *gate_clks;
unsigned int nr_gate_clks;
/* list of fixed clocks and respective count */
struct samsung_fixed_rate_clock *fixed_clks;
unsigned int nr_fixed_clks;
/* list of fixed factor clocks and respective count */
struct samsung_fixed_factor_clock *fixed_factor_clks;
unsigned int nr_fixed_factor_clks;
/* total number of clocks with IDs assigned*/
unsigned int nr_clk_ids;
/* list and number of clocks registers */
unsigned long *clk_regs;
unsigned int nr_clk_regs;
};
extern struct samsung_clk_provider *__init samsung_clk_init(
struct device_node *np, void __iomem *base,
unsigned long nr_clks);
extern void __init samsung_clk_of_add_provider(struct device_node *np,
struct samsung_clk_provider *ctx);
extern void __init samsung_clk_of_register_fixed_ext(
struct samsung_clk_provider *ctx,
struct samsung_fixed_rate_clock *fixed_rate_clk,
unsigned int nr_fixed_rate_clk,
const struct of_device_id *clk_matches);
extern void samsung_clk_add_lookup(struct samsung_clk_provider *ctx,
struct clk *clk, unsigned int id);
extern void __init samsung_clk_register_alias(struct samsung_clk_provider *ctx,
const struct samsung_clock_alias *list,
unsigned int nr_clk);
extern void __init samsung_clk_register_fixed_rate(
struct samsung_clk_provider *ctx,
const struct samsung_fixed_rate_clock *clk_list,
unsigned int nr_clk);
extern void __init samsung_clk_register_fixed_factor(
struct samsung_clk_provider *ctx,
const struct samsung_fixed_factor_clock *list,
unsigned int nr_clk);
extern void __init samsung_clk_register_mux(struct samsung_clk_provider *ctx,
const struct samsung_mux_clock *clk_list,
unsigned int nr_clk);
extern void __init samsung_clk_register_div(struct samsung_clk_provider *ctx,
const struct samsung_div_clock *clk_list,
unsigned int nr_clk);
extern void __init samsung_clk_register_gate(struct samsung_clk_provider *ctx,
const struct samsung_gate_clock *clk_list,
unsigned int nr_clk);
extern void __init samsung_clk_register_pll(struct samsung_clk_provider *ctx,
const struct samsung_pll_clock *pll_list,
unsigned int nr_clk, void __iomem *base);
extern struct samsung_clk_provider __init *samsung_cmu_register_one(
struct device_node *,
struct samsung_cmu_info *);
extern unsigned long _get_rate(const char *clk_name);
extern void samsung_clk_save(void __iomem *base,
struct samsung_clk_reg_dump *rd,
unsigned int num_regs);
extern void samsung_clk_restore(void __iomem *base,
const struct samsung_clk_reg_dump *rd,
unsigned int num_regs);
extern struct samsung_clk_reg_dump *samsung_clk_alloc_reg_dump(
const unsigned long *rdump,
unsigned long nr_rdump);
#endif /* __SAMSUNG_CLK_H */ |
/*
* Advance Programming Group Project
* Date of Submission: 11/11/2022
* Lab Supervisor: Christopher Panther
*
* Group Members:-
* ~ Gabrielle Johnson 2005322
* ~ Jazmin Hayles 2006754
* ~ Rushawn White 2002469
* ~ Barrignton Patternson 2008034
*
*/
package com.application.view.inventory.order;
import com.application.models.tables.Product;
import com.application.view.ServerApp;
import com.application.view.inventory.INVViewPNL;
import com.application.view.utilities.InvalidCharListener;
import com.database.server.Client;
import lombok.Getter;
import lombok.Setter;
import net.miginfocom.swing.MigLayout;
import org.apache.logging.log4j.Level;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@Getter
@Setter
public class INVViewFormPNL implements ActionListener {
private final String title;
private final INVViewPNL invViewPNL;
private final Client client;
private JPanel pnl;
private JLabel idLBL, nameLBL, shDescLBL, loDescLBL, stockLBL, totSoldLBL, priceLBL;
private JTextField idTXT, nameTXT, shDescTXT, stockTXT, totSoldTXT, priceTXT;
private JTextArea loDescTXTA;
public JButton save, delete, clear;
private String prodID;
public INVViewFormPNL(String title, INVViewPNL invViewPNL, Client client) {
this.title = title;
this.invViewPNL = invViewPNL;
this.client = client;
this.prodID = (String) client.genID("Product", Product.idLength);
initializeComponents();
addComponents();
setProperties();
}
/**
* Initializes swing Components used in this form
*/
private void initializeComponents() {
pnl = new JPanel(new MigLayout("fill, ins 10 10 0 10", "[grow 0]10[grow 50][grow 50]", "[]5[]5[]5[]5[]5[]5[]15[]"));
idLBL = new JLabel("ID Number:");
nameLBL = new JLabel("Product Name:");
shDescLBL = new JLabel("Short Description:");
loDescLBL = new JLabel("Long Description:");
stockLBL = new JLabel("Stock:");
totSoldLBL = new JLabel("Total Sold:");
priceLBL = new JLabel("Unit Price:");
idTXT = new JTextField(prodID);
nameTXT = new JTextField("");
shDescTXT = new JTextField("");
loDescTXTA = new JTextArea(5, 30);
stockTXT = new JTextField("");
totSoldTXT = new JTextField("0");
priceTXT = new JTextField("");
save = new JButton("Save", new ImageIcon(ServerApp.saveIMG));
delete = new JButton("Delete", new ImageIcon(ServerApp.deleteIMG));
clear = new JButton("Clear", new ImageIcon(ServerApp.clearIMG));
}
/**
* adding components to the panel with miglayout constraints
*/
private void addComponents() {
pnl.add(idLBL);
pnl.add(idTXT, "growx, wrap");
pnl.add(nameLBL);
pnl.add(nameTXT, "growx, span, wrap");
pnl.add(shDescLBL);
pnl.add(shDescTXT, "growx, span, wrap");
pnl.add(loDescLBL);
pnl.add(loDescTXTA, "grow, span, wrap");
pnl.add(stockLBL);
pnl.add(stockTXT, "growx, wrap");
pnl.add(totSoldLBL);
pnl.add(totSoldTXT, "growx, wrap");
pnl.add(priceLBL);
pnl.add(priceTXT, "growx, wrap");
pnl.add(save, "center, span, split 3, width 100");
pnl.add(delete, "center, width 100");
pnl.add(clear, "center, wrap, width 100, wrap");
}
/**
* Sets properties of components on the form
*/
private void setProperties() {
InvalidCharListener stockListener = new InvalidCharListener(new char[]{
'\\', '(', ')', '*', '.', '?', '|', '+', '$', '^',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '=', '-', '_', '~', '`', '/', '\t', '\n', '<', '>', ',', '&', '#', '@', '!'
});
InvalidCharListener priceListener = new InvalidCharListener(new char[]{
'\\', '(', ')', '*', '?', '|', '+', '$', '^',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '=', '-', '_', '~', '`', '/', '\t', '\n', '<', '>', ',', '&', '#', '@', '!'
});
pnl.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Product Form"));
idTXT.setEnabled(false);
totSoldTXT.setEnabled(false);
delete.setEnabled(false);
stockTXT.addKeyListener(stockListener);
priceTXT.addKeyListener(priceListener);
clear.addActionListener(this);
save.addActionListener(this);
delete.addActionListener(this);
}
/**
* method clears form fields
*/
public void clear() {
idTXT.setText(prodID);
nameTXT.setText("");
shDescTXT.setText("");
loDescTXTA.setText("");
stockTXT.setText("");
totSoldTXT.setText("0");
priceTXT.setText("");
delete.setEnabled(false);
invViewPNL.getProdTBL().clearSelection();
invViewPNL.setProdIndex(-1);
invViewPNL.getSearch().getPrint().setEnabled(false);
}
/**
* Method updates specific product info in table based on form input
*
* @param product
*/
public void update(Product product) {
delete.setEnabled(true);
idTXT.setText(product.getIdNum());
nameTXT.setText(product.getName());
shDescTXT.setText(product.getShDesc());
loDescTXTA.setText(product.getLoDesc());
stockTXT.setText(String.valueOf(product.getStock()));
totSoldTXT.setText(String.valueOf(product.getTotSold()));
priceTXT.setText(String.format("%.2f", product.getPrice()));
}
@Override
public void actionPerformed(ActionEvent e) {
int prodIndex = invViewPNL.getProdIndex();
if (e.getSource().equals(clear)) {
clear();
clear.setSelected(false);
} else if (e.getSource().equals(save) || (e.getSource().equals(delete) && prodIndex != -1)) {
boolean isSave = e.getSource().equals(save);
boolean isNew = prodID.equals(idTXT.getText());
Product product = null;
String btnType = (isSave ? "Save" : "Delete");
String cudType = (isSave ? (isNew ? "create" : "update") : "delete");
if (JOptionPane.showConfirmDialog(invViewPNL.getPnl(), btnType + " Product?", title, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) {
if (isSave) {
product = new Product(
idTXT.getText(),
nameTXT.getText(),
shDescTXT.getText(),
loDescTXTA.getText(),
stockTXT.getText().equals("") ? -1 : Integer.parseInt(stockTXT.getText()),
totSoldTXT.getText().equals("") ? -1 : Integer.parseInt(totSoldTXT.getText()),
priceTXT.getText().equals("") ? -1 : Double.parseDouble(priceTXT.getText())
);
if (!product.isValid()) {
client.log(Level.WARN, "Could not " + cudType + " product! {invalid details}");
JOptionPane.showMessageDialog(invViewPNL.getPnl(), "Invalid Product Details! Try again...", title, JOptionPane.ERROR_MESSAGE);
return;
}
}
boolean result = (Boolean) client.cud(cudType, "Product", (isSave ? product : ServerApp.products.get(prodIndex).getIdNum()));
String idNum = (isSave ? product.getIdNum() : ServerApp.products.get(prodIndex).getIdNum());
if (result) {
client.log(Level.INFO, cudType + "d product. {" + idNum + "}");
JOptionPane.showMessageDialog(invViewPNL.getPnl(), "Product successfully " + cudType + "!", title, JOptionPane.INFORMATION_MESSAGE);
if (isSave) {
if (isNew) {
prodID = (String) client.genID("Product", Product.idLength);
ServerApp.products.add(product);
invViewPNL.getProdTBL().getTModel().addRow(product.toArray());
} else {
ServerApp.products.set(prodIndex, product);
invViewPNL.getProdTBL().updateRow(prodIndex, product.toArray());
}
} else {
ServerApp.products.remove(prodIndex);
invViewPNL.getProdTBL().getTModel().removeRow(prodIndex);
}
ServerApp.sPNL.getOrder().getProdTBL().refresh(ServerApp.products.to2DArray());
invViewPNL.clear();
} else {
client.log(Level.WARN, "Could not " + cudType + " product! {" + idNum + "}");
JOptionPane.showMessageDialog(pnl, "Could not " + cudType + " product! Try again...", title, JOptionPane.ERROR_MESSAGE);
if (isNew) {
prodID = (String) client.genID("Product", Product.idLength);
idTXT.setText(prodID);
}
}
}
save.setSelected(false);
delete.setSelected(false);
}
}
} |
package leetcode.editor.cn;
//你有一套活字字模 tiles,其中每个字模上都刻有一个字母 tiles[i]。返回你可以印出的非空字母序列的数目。
//
// 注意:本题中,每个活字字模只能使用一次。
//
//
//
// 示例 1:
//
//
//输入:"AAB"
//输出:8
//解释:可能的序列为 "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA"。
//
//
// 示例 2:
//
//
//输入:"AAABBC"
//输出:188
//
//
// 示例 3:
//
//
//输入:"V"
//输出:1
//
//
//
// 提示:
//
//
// 1 <= tiles.length <= 7
// tiles 由大写英文字母组成
//
//
// 👍 169 👎 0
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
/**
* 活字印刷
*
* @author IronSid
* @version 1.0
* @since 2023-05-19 00:04:09
*/
public class LetterTilePossibilitiesSolution {
static
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public static final int M = (int) (1e9 + 7);
public static final BigInteger BIM = BigInteger.valueOf(M);
public static final int N = (int) (1e5);
private char[] ch;
private HashSet<String> set;
static HashMap<String, Long> C = new HashMap<>();
static long C(int n, int k) {
C.computeIfAbsent(n + " " + k, t ->
fac(n).multiply(fac(n - k).modInverse(BIM)).multiply(fac(k).modInverse(BIM)).mod(BIM).longValueExact()
);
return C.get(n + " " + k);
}
static List<Long> fac= new ArrayList<>((int) (N + 10));
static {
fac.add(1L);
}
static BigInteger fac(int n) {
for (int i = fac.size(); i <= n; i++) {
fac.add(fac.get(i - 1) * i % M);
}
return BigInteger.valueOf(fac.get(n));
}
public int numTilePossibilities(String tiles) {
List<Integer> list = new ArrayList<>();
int[] f = new int[128];
for (char c : tiles.toCharArray()) {
f[c]++;
}
for (char c = 'A'; c <= 'Z'; c++) {
if (f[c] != 0) list.add(f[c]);
}
int m = list.size();
int n = tiles.length();
// dp[i][j] 表示前 i 种字符构造长为 j 的序列的方案数
long[][] dp = new long[m + 1][n + 1];
dp[0][0] = 1;
for (int i = 1; i <= m; i++) {
int cnt = list.get(i - 1);
// 枚举序列列长度
for (int j = 0; j <= n; j++) {
// 枚举取多少个当前字符
for (int k = 0; k <= j && k <= cnt; k++) {
dp[i][j] += dp[i - 1][j - k] * C(j, k);
}
}
}
long ans = 0;
for (int j = 1; j <= n; j++) {
ans += dp[m][j];
}
return (int) ans;
}
}
//leetcode submit region end(Prohibit modification and deletion)
} |
import { Buffer } from 'buffer';
import BigNumber from 'bignumber.js';
import { useCalcTime } from '@/components/hooks';
import { ethers } from 'ethers';
import keccak256 from 'keccak256';
import MerkleTree from 'merkletreejs';
export const base64toBuff = (data) => {
var arr = data.split(',');
var buffer = Buffer.from(arr[1], 'base64');
// new Blob(buffer)
let array = new Uint8Array(buffer, 0, buffer.length);
return Array.from(array);
};
export const toArray = (str: string) => {
const buffer: Array<number> = [];
for (let i of str) {
const _code = i.charCodeAt(0);
if (_code < 0x80) {
buffer.push(_code);
} else if (_code < 0x800) {
buffer.push(0xc0 + (_code >> 6));
buffer.push(0x80 + (_code & 0x3f));
} else if (_code < 0x10000) {
buffer.push(0xe0 + (_code >> 12));
buffer.push(0x80 + ((_code >> 6) & 0x3f));
buffer.push(0x80 + (_code & 0x3f));
}
}
return buffer.map((number) => Number(number.toString(8)));
};
export const toUint8Arr = (str: string) => {
const buffer: Array<number> = [];
for (let i of str) {
const _code = i.charCodeAt(0);
if (_code < 0x80) {
buffer.push(_code);
} else if (_code < 0x800) {
buffer.push(0xc0 + (_code >> 6));
buffer.push(0x80 + (_code & 0x3f));
} else if (_code < 0x10000) {
buffer.push(0xe0 + (_code >> 12));
buffer.push(0x80 + ((_code >> 6) & 0x3f));
buffer.push(0x80 + (_code & 0x3f));
}
}
return Uint8Array.from(buffer);
};
export const payloadStr = (payload: Record<string, any>): string => {
let str = '';
if (payload && Object.keys(payload).length > 0) {
Object.keys(payload).forEach((key) => {
str = str + `&${key}=${payload[key]}`;
});
}
return str;
};
/* 防抖默认1秒 */
export function debounce<T>(fn: (data: T) => void, delay: number = 1000) {
let timeout: NodeJS.Timeout | null = null;
return function (data: T) {
if (timeout !== null) clearTimeout(timeout);
timeout = setTimeout(fn.bind({}, data), delay);
};
}
export function handleScroll(event, callback?: Function) {
let divEl = event.target as HTMLDivElement;
if (divEl.scrollTop + divEl.clientHeight === divEl.scrollHeight) {
console.log('===到底了---');
if (callback) {
callback();
}
}
}
export function hexToStr(hex, encoding = 'utf-8') {
var trimedStr = hex.trim();
var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;
var len = rawStr.length;
if (len % 2 !== 0) {
alert('Illegal Format ASCII Code!');
return '';
}
var curCharCode: number;
var resultStr: Array<number> = [];
for (var i = 0; i < len; i = i + 2) {
curCharCode = parseInt(rawStr.substr(i, 2), 16);
resultStr.push(curCharCode);
}
// encoding为空时默认为utf-8
var bytesView = new Uint8Array(resultStr);
var str = new TextDecoder(encoding).decode(bytesView);
return str;
}
const bignumberFormat = (num) => {
return num.toFormat(1, { groupSeparator: '', decimalSeparator: '.' }).split('.')[0];
};
const bignumberToInt = (num) => {
return Number(bignumberFormat(num));
};
export function getValueDivide8(num: number) {
let res = new BigNumber(num || 0).dividedBy(Math.pow(10, 8));
return res.toFixed();
}
export function getValueMultiplied8(num: number) {
return bignumberToInt(new BigNumber(num).multipliedBy(Math.pow(10, 8)));
}
export function dealWithIpfsShowUri(uri: string | undefined) {
if (uri?.startsWith('ipfs://')) {
console.log('avatar ', `https://dweb.link/ipfs/${uri.slice(7)}`);
return `https://dweb.link/ipfs/${uri.slice(7)}`;
}
if (uri === 'https://aptosnames.com') {
return 'https://bafybeihkaf5s53awrqlfpcpsojk26d2glvfyow5u35eqmy7buzqg2upzl4.ipfs.dweb.link/orign.jpeg';
}
return uri;
}
export function getCollectionAvatarUrl(uri: string | undefined) {
if (uri?.endsWith('/featured')) {
return uri.replace('featured', 'logo');
}
return dealWithIpfsShowUri(uri);
}
export function getShowTime(text) {
const res = useCalcTime(new Date(text).getTime());
if (res?.days && res.days > 30) return text;
if (res?.days) return `${res?.days} ${res.days === 1 ? 'day' : 'days'} ago`;
if (!res?.days && res?.hours) return `${res.hours} ${res.hours === 1 ? 'hour' : 'hours'} ago`;
if (!res?.hours && res?.minutes)
return `${res?.minutes} ${res?.minutes === 1 ? 'minute' : 'minutes'} ago`;
if (!res?.minutes && res?.seconds) return 'just now';
}
export function parseCollectionId(collectionId: string) {
const decodeCollectionId = decodeURIComponent(collectionId);
const temp = decodeCollectionId.split('::');
const creator = temp[0];
const collection_name = decodeCollectionId.substring(creator.length + 2);
return { creator, collection_name };
}
export function getMerkleTreeRoot(whitelistAddresses: Array<string>) {
//1.叶子节点数据制作
let leafNodes: Array<string> = [];
for (let address of whitelistAddresses) {
try {
let leafNode = ethers.utils.keccak256(address);
leafNodes.push(leafNode);
} catch (e) {
//console.log('address ', address, 'is invalid');
}
}
//2.生成树根
let tree = new MerkleTree(leafNodes, keccak256, { sortPairs: true });
return { root: Array.from(tree.getRoot()), result: leafNodes };
}
export function testMerkleTree() {
let whitelistAddresses = [
'0x626f6456e3a1e0d4bbd8cfdb96dd506fe21b1ef5f35eb607e01f8fdfe8a1c14d',
'0x7fee4bb13e2551fca3c8ead6ae5532fda5e4d777f458efbea2f12063dc0c3e2d',
'0x4a17667c94548a635152b0a41e087329e0f9c3ae492a132a06ad24d91df0a8f0',
'0xc2f9d818b7905fef5cab2032df40669dbfc22c6dbe5e07d7c0df237a4a498e58',
'0xa7b7c02a55811c9494f24cf0312335e102566a4ffee5bd6946e60377470ef760',
'0xce606a1301b66aeccb155f6c58bea9eef2234a93d493604e557a21eb81eef7bc',
'0xc38504a6d5275e49e0210ab4b33e8e6eb1fb8e138c841cba39f313f329b4ef57',
'0xb57d384eabbb86e3ddce9437b2c5b2fd6f5b996828239609691e7fb5ceff59b1',
'0xb874c5e7332aa464a539f36393cadb35eac52d7a145cc77e333d8dbe27035364',
'0xd10086e7ae5f568655b8bb51f37c0f9b68d3feb55f06488dd1542acf07e041e2',
];
//1.叶子节点数据制作
let leafNodes: any[] = [];
for (let test in whitelistAddresses) {
let leafNode = ethers.utils.keccak256(whitelistAddresses[test]);
leafNodes.push(leafNode);
}
//2.生成树根
let tree = new MerkleTree(leafNodes, keccak256, { sortPairs: true });
console.log('root: ', tree.getHexRoot());
//3.生成叶子的proof(需要检验的地址)
console.log(tree.getHexProof(leafNodes[0]));
}
export function getWhiteListSaleName(index: number) {
if (index === 0) return 'OG Sale';
if (index === 1) return 'Whitelist Sale';
return `Whitelist${index - 1} Sale`;
} |
// RoadConstruction.js
import React from 'react';
import NavBar from '../NavBar'
import Footer from '../Footer'
import useScrollToTop from '../useScrollToTop';
import { makeStyles } from '@material-ui/core/styles';
import ArrowDownwardIcon from '@material-ui/icons//ArrowDownward';
import Fade from '@material-ui/core/Fade';
import roadConstructionImg from '../../components/images/road_construction_img.jpeg'
import InfoCard from '../InfoCard';
import {Typography, Button, Link } from '@material-ui/core';
import { useNavigate } from 'react-router-dom';
const useStyles = makeStyles((theme) => ({
coverImageContainer: {
position: 'relative',
height: '870px',
overflow: 'hidden',
backgroundImage: `url('/road_construction.jpeg')`,
backgroundSize: 'cover',
backgroundPosition: 'center center',
},
overlay: {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
padding: "20",
color: "white",
textAlign: "center",
width: "50%",
fontSize: "2rem",
fontFamily: 'Roboto',
marginTop: "-5vw"
},
boldWord: {
fontWeight: "bold",
fontFamily: 'Georgia'
},
box:{
display: "flex",
alignItems: "center"
},
arrowAnimation: {
alignItems: 'center',
justifyContent: 'center',
paddingTop: "1rem",
animation: '$raindrop 2s infinite',
},
'@keyframes raindrop': {
'0%, 100%': {
transform: 'translateY(0)',
},
'50%': {
transform: 'translateY(-5px)', // Adjust the raindrop effect height as needed
},
},
buttonContainer: {
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
width: '32px', // Adjust the width as needed to fit the circle
height: '32px', // Adjust the height as needed to fit the circle
borderRadius: '50%',
border: '2px solid white',
},
arrowIcon: {
color: 'white', // Set the icon color to white
},
horizontalLine: {
position: 'relative',
display: 'flex',
margin: '0 auto', // Center the image horizontally
width: '80%',
height: '20px',
},
quoteSection: {
padding: theme.spacing(4),
textAlign: 'center',
},
quoteButton: {
marginTop: theme.spacing(2),
backgroundColor: 'maroon'
},
quoteSectionText: {
color: 'black',
fontWeight: 'bold',
fontFamily: 'Roboto'
}
}));
const RoadConstruction = () => {
useScrollToTop();
const classes = useStyles();
const navigate = useNavigate();
function scrollToFirstSection() {
const firstSectionOffsetTop = document.getElementById('first-section').offsetTop;
window.scrollTo({
top: firstSectionOffsetTop,
behavior: 'smooth',
});
}
function handleClick() {
navigate('/contact');
}
return (
<div>
<NavBar/>
<div className={classes.coverImageContainer}/>
<Fade in={true} timeout={2000}>
<div>
<div className={classes.overlay}>
<div className={classes.boldWord}>
ROAD CONSTRUCTION
</div>
<div className={classes.arrowAnimation}>
<div className={classes.buttonContainer}>
<ArrowDownwardIcon onClick={scrollToFirstSection} className={classes.arrowIcon} />
</div>
</div>
</div>
</div>
</Fade>
<InfoCard
title="Concrete Results"
subtitle="Road Construction"
description="Explore premier road construction services at Jason's Landscaping. Specializing in the design, development, and maintenance of
roads, our skilled team ensures the seamless connection of communities and the facilitation of smooth transportation. Our comprehensive services
include precision grading, asphalt paving, and ongoing maintenance, guaranteeing roads built to last."
image={roadConstructionImg}
link="/services/site-prep"
imageOnRight={true}
hideButton={true}
/>
<img src="/horizontal_line.png" alt="line" className={classes.horizontalLine}/>
<div className={classes.quoteSection} id="first-section">
<Typography variant="h5" className={classes.quoteSectionText}>
Request a Quote Today!
</Typography>
<Button
component={Link}
onClick={handleClick}
variant="contained"
color="primary"
className={classes.quoteButton}
>
Contact Us
</Button>
</div>
<Footer/>
</div>
);
};
export default RoadConstruction; |
#ifndef NODESTATEMANAGER_H
#define NODESTATEMANAGER_H
/**********************************************************************************************************************
*
* Copyright (C) 2012 Continental Automotive Systems, Inc.
*
* Author: Jean-Pierre.Bogler@continental-corporation.com
*
* Interface between NodeStateManager and other components in the same process
*
* The file defines the interfaces and data types, which components in the same process or on the D-Bus
* can use to communicate to the NodeStateManager (NSM). Please note that there are further interfaces
* defined in XML to access the NSM via D-Bus.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Date Author Reason
* 2012.06.01 uidu5846 1.0.0.0 CSP_WZ#388: Initial version of the NodeStateManager interface
* 2012.09.27 uidu5846 1.1.0.0 CSP_WZ#1194: Changed file header structure and license to be released
* as open source package. Introduced 'NodeStateTypes.h' to
* avoid circle includes and encapsulate type definitions.
* 2012.10.24 uidu5846 1.2.0.0 CSP_WZ#1322: Changed types of interface parameters to native types.
* Since the same native types are used, no interface change.
* 2013.04.18 uidu5846 1.2.1 OvipRbt#1153: Increased minor version number.
*
**********************************************************************************************************************/
/** \ingroup SSW_LCS */
/** \defgroup SSW_NSM_TEMPLATE Node State Manager
* \{
*/
/** \defgroup SSW_NSM_INTERFACE API document
* \{
*/
#ifdef __cplusplus
extern "C"
{
#endif
/**********************************************************************************************************************
*
* HEADER FILE INCLUDES
*
**********************************************************************************************************************/
#include "NodeStateTypes.h"
/**********************************************************************************************************************
*
* CONSTANTS
*
**********************************************************************************************************************/
/**
* Module version, use SswVersion to interpret the value.
* The lower significant byte is equal 0 for released version only
*/
#define NSM_INTERFACE_VERSION 0x01020100U
/**********************************************************************************************************************
*
* TYPE
*
**********************************************************************************************************************/
/* There are no types defined here */
/**********************************************************************************************************************
*
* GLOBAL VARIABLES
*
**********************************************************************************************************************/
/* There are no exported global variables */
/**********************************************************************************************************************
*
* FUNCTION PROTOTYPE
*
**********************************************************************************************************************/
/** \brief Set data (property) of the NodeStateManager.
\param[in] enData Type of the data to set (see ::NsmDataType_e).
\param[in] pData Pointer to the memory location containing the data.
\param[in] u32DataLen Length of the data that should be set (in byte).
\retval see ::NsmErrorStatus_e
This is a generic interface that can be used by the NSMc to write a specific data item that from the NSM. */
NsmErrorStatus_e NsmSetData(NsmDataType_e enData, unsigned char *pData, unsigned int u32DataLen);
/** \brief Get data (property) of the NodeStateManager.
\param[in] enData Type of the data to get (see ::NsmDataType_e).
\param[out] pData Pointer to the memory location where the data should be stored.
\param[in] u32DataLen Length of the data that should be stored (in byte).
\retval A positive value indicates the number of bytes that have been written to the out buffer pData.
A negative value indicates an error.
This is a generic interface that can be used by the NSMc to read a specific data item that from the NSM. */
int NsmGetData(NsmDataType_e enData, unsigned char *pData, unsigned int u32DataLen);
/** \brief Get version of the interface
\retval Version of the interface as defined in ::SswVersion_t
This function asks the lifecycle to perform a restart of the main controller. */
unsigned int NsmGetInterfaceVersion(void);
/**********************************************************************************************************************
*
* MACROS
*
**********************************************************************************************************************/
/* There are no macros defined */
#ifdef __cplusplus
}
#endif
/** \} */ /* End of SSW_NSM_INTERFACE */
/** \} */ /* End of SSW_NSM_TEMPLATE */
#endif /* NSM_NODESTATEMANAGER_H */ |
import React, { useEffect, useState } from 'react'
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import axios from 'axios';
//import * as React from 'react';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
export default function Home() {
const [from, setFrom] = React.useState('');
const [to, setTo] = React.useState('');
const [data, setData] = useState([])
const [disp, setDisp] = useState([])
useEffect(() => {
axios.get("http://localhost:8080/Flights").then((res) => setData(res.data))
}, [])
const handleSearch = () => {
const disp1 = data.filter((e) => {
// console.log("eee",e)
if ((from == e.from) && (to == e.to)) {
return e
}
})
setDisp(disp1)
console.log("disp", disp1)
console.log("apend", disp)
}
return (
<div>
<div>
<Box
component="form"
sx={{
'& > :not(style)': { m: 1, width: '85ch' },
}}
noValidate
autoComplete="off"
>
<TextField
id="outlined-name"
label="FROM"
// value={name}
onChange={(e) => { setFrom(e.target.value) }}
/><br />
<TextField
id="outlined-name"
label="TO"
// value={name}
onChange={(e) => { setTo(e.target.value) }}
/><br />
<Button variant="contained" onClick={handleSearch}>Search</Button>
</Box>
</div>
<div>
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell><b>Name</b></TableCell>
<TableCell align="right"><b>From</b></TableCell>
<TableCell align="right"><b>To </b> </TableCell>
<TableCell align="right"><b>Cost </b> </TableCell>
<TableCell align="right"><b>From Time </b> </TableCell>
<TableCell align="right"><b>To Time </b></TableCell>
<TableCell align="right"><b>PNR </b> </TableCell>
<TableCell align="right"><b>Capacity </b> </TableCell>
</TableRow>
</TableHead>
<TableBody>
{disp.map((e) => (
<TableRow
key={e.id}
sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
>
<TableCell component="th" scope="row">
{e.airlines}
</TableCell>
<TableCell align="right">{e.from}</TableCell>
<TableCell align="right">{e.to}</TableCell>
<TableCell align="right">{e.cost}</TableCell>
<TableCell align="right">{e.FromTime}</TableCell>
<TableCell align="right">{e.ToTime}</TableCell>
<TableCell align="right">{e.pnr}</TableCell>
<TableCell align="right">{e.capacity}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
{/* <table>
<tr>
<th>Name</th>
<th>From</th>
<th>To</th>
<th>Cost</th>
<th>From Time</th>
<th>To Time</th>
<th>PNR</th>
<th>Capacity</th>
</tr>
{
disp.map((e) => (
<tr key={e.id}>
<td>{e.airlines}</td>
<td>{e.from}</td>
<td>{e.to}</td>
<td>{e.cost}</td>
<td>{e.FromTime}</td>
<td>{e.ToTime}</td>
<td>{e.pnr}</td>
<td>{e.capacity}</td>
</tr>
))
}
</table> */}
</div>
</div>
)
} |
import { Injectable } from '@angular/core';
import {
Auth,
createUserWithEmailAndPassword,
getAuth,
onAuthStateChanged,
sendPasswordResetEmail,
signInWithEmailAndPassword,
} from '@angular/fire/auth';
import { BehaviorSubject } from 'rxjs';
import { ApiService } from '../api/api.service';
@Injectable({
providedIn: 'root',
})
export class AuthService {
public _uid = new BehaviorSubject<string>('');
currentUser: any;
constructor(private fireAuth: Auth, private apiService: ApiService) {
this.getId();
}
async login(email: string, password: string): Promise<any> {
try {
const response = await signInWithEmailAndPassword(
this.fireAuth,
email,
password
);
if (response?.user) this.setUserData(response.user.uid);
} catch (e) {
throw e;
}
}
getId() {
const auth = getAuth();
this.currentUser = auth.currentUser;
return this.currentUser?.uid;
}
setUserData(uid: string) {
this._uid.next(uid);
}
randomIntFromInterval(min: any, max: any) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
async register(formValue: any) {
try {
const registeredUser = await createUserWithEmailAndPassword(
this.fireAuth,
formValue.email,
formValue.password
);
const data = {
uid: registeredUser.user.uid,
email: formValue.email,
name: formValue.username,
description: '',
photo: 'https://i.pravatar.cc/' + this.randomIntFromInterval(200, 400),
images: ['https://ionicframework.com/docs/img/demos/card-media.png'],
};
await this.apiService.setDocument(
`users/${registeredUser.user.uid}`,
data
);
const userData = {
id: registeredUser.user.uid,
};
console.log(registeredUser.user.uid);
this.setUserData(registeredUser.user.uid);
return userData;
} catch (e) {
throw e;
}
}
async resetPassword(email: string) {
try {
await sendPasswordResetEmail(this.fireAuth, email);
} catch (e) {
throw e;
}
}
async logout() {
try {
await this.fireAuth.signOut();
this._uid.next('');
return true;
} catch (e) {
throw e;
}
}
checkAuth(): Promise<any> {
return new Promise((resolve, reject) => {
onAuthStateChanged(this.fireAuth, (user) => {
resolve(user);
});
});
}
async getUserData(id: any) {
const docSnap: any = await this.apiService.getDocById(`users/${id}`);
if (docSnap?.exists()) {
return docSnap.data();
} else {
throw 'No such document exists';
}
}
async updateUserData(userId: any, data: any) {
try {
await this.apiService.updateDocument(`users/${userId}`, data);
} catch (error) {
console.log(error);
}
}
async getUserSettings(id: any) {
const docSnap: any = await this.apiService.getDocById(`userSettings/${id}`);
if (docSnap?.exists()) {
return docSnap.data();
} else {
throw 'No settings data exists';
}
}
async updateUserSettings(userId: any, data: any) {
try {
await this.apiService.setDocument(`userSettings/${userId}`, data);
} catch (error) {
console.log(error);
}
}
async updateUserDiscoverSetting(userId: any, data: any) {
try {
await this.apiService.updateDocument(`users/${userId}`, data);
} catch (error) {
console.log(error);
}
}
} |
import { useState } from 'react'
import { useNavigate } from 'react-router-dom';
const Login = ({ setJWT }) => {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [loading, setLoading] = useState(false)
const [response, setResponse] = useState('');
const [error, setError] = useState('')
const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault()
const newUser = { username, password }
setLoading(true)
try {
const response = await fetch('https://blogapi-production-98cb.up.railway.app/users/login', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newUser)
})
if (!response.ok) {
setError("Username or password incorrect")
throw new Error("Username or password incorrect")
}
const data = await response.json()
setResponse(data)
setJWT(data.token)
setLoading(false)
navigate(`/posts`)
} catch (error) {
console.error('Error:', error);
setLoading(false);
}
}
return (
<>
<h1>Login</h1>
<div className='registerForm'>
<form onSubmit={handleSubmit}>
<label>Username:</label>
<input
type="text"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<label>Password:</label>
<input
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
{!loading && <button>Submit</button>}
{ loading && <button disabled>Logging In...</button>}
</form>
</div>
{error ? <p>{error}</p> : ''}
<img style={{ marginLeft: '1rem', marginTop: '2rem', width: '15rem' }} src='https://svgsilh.com/svg/32253.svg'></img>
</>
)
}
export default Login |
import React from 'react'
import { View, Text, ScrollView, Keyboard, SafeAreaView } from 'react-native';
import Input from '../components/registerInput';
import { ButtonElement } from '../components/ButtonElement';
import logotype from '../assets/images/loginlogo.png';
import '../assets/styles/_login.css';
import '../assets/styles/_buttons.css';
const RegisterScreen = ({navigation}) => {
const [inputs, setInputs] = React.useState({
fullname: '',
username: '',
email: '',
password: '',
validatepassword: '',
});
const [errors, setErrors] = React.useState({});
const validate = () => {
Keyboard.dismiss();
let isValid = true;
if (!inputs.email){
handleError('Please input email', 'email');
isValid = false;
} else if (!inputs.email.match(/\S+@\S+\.\S+/)){
handleError('Invalid input!', 'email');
isValid = false;
}
if(!inputs.fullname){
handleError('Please input fullname', 'fullname');
isValid = false;
}
if(!inputs.username){
handleError('Please input username', 'username');
isValid = false;
}
if(!inputs.password){
handleError('Please input password', 'password');
isValid = false;
} else if (inputs.password.length < 7) {
handleError('Min password length of 7', 'password');
}
if(inputs.validatepassword != inputs.password){
handleError('Passwords do not match!', 'validatepassword');
isValid = false;
}
if(isValid){
finish();
}
};
const finish = () => {
navigation.navigate('LoginScreen');
}
const handleOnChange = (text, input) => {
setInputs((prevState)=>({...prevState, [input]: text}));
};
const handleError = (errorMessage, input)=>{
setErrors((prevState)=>({...prevState,[input]:errorMessage}))
}
return (
<>
<SafeAreaView style={{backgroundColor: "white", flex: 1}}>
<ScrollView
contentContainerStyle={{
paddingTop: 50,
paddingHorizontal: 20,
}}>
<img src = {logotype} alt = "" className = 'loginlogo'/>
<Text style={{color: "black",fontSize: 40}}>Register</Text>
<View style={{marginVertical: 20}}>
<Input
onFocus={() => {
handleError(null, 'fullname');
}}
onChangeText={text => handleOnChange(text, 'fullname')}
label="Full name"
error={errors.fullname}
/>
<Input
onFocus={() => {
handleError(null, 'username');
}}
onChangeText={text => handleOnChange(text, 'username')}
label="Username"
error={errors.username}
/>
<Input
onFocus={() => {
handleError(null, 'email');
}}
onChangeText={text => handleOnChange(text, 'email')}
label="E-mail"
error={errors.email}
/>
<Input
onFocus={() => {
handleError(null, 'password');
}}
onChangeText={text => handleOnChange(text, 'password')}
label="Password"
error={errors.password}
password
/>
<Input
onFocus={() => {
handleError(null, 'validatepassword');
}}
onChangeText={text => handleOnChange(text, 'validatepassword')}
label="Validate password"
error={errors.validatepassword}
vpassword
/>
<ButtonElement text = "Finish" className="btn--main" onPress={validate}/>
<Text
onPress={() => navigation.naviate('LoginScreen')}
style={{
color: "black",
marginVertical: 20,
textAlign: 'center',
fontSize: 18,
}}>
Already have an account? Log in</Text>
</View>
</ScrollView>
</SafeAreaView>
</>
)
}
export default {RegisterScreen}; |
import * as ImageJS from "image-js";
// @ts-ignore-next-line
import { InferenceSession, Tensor } from "onnxruntime-web";
let model: InferenceSession = null
const MODEL_DIR: string = '/rembg-web/silueta.onnx'
onmessage = async function(event: MessageEvent) {
if (event.data === 'loadModel') {
try {
await loadModel()
postMessage('modelLoaded');
} catch (error) {
postMessage('modelLoadError');
}
} else if (event.data[0] === 'rembg') {
try {
const workerResult = await rembg(event.data[1])
postMessage(['result', workerResult]);
} catch (error) {
postMessage('rembgError');
}
}
}
export const loadModel = async () => {
if (model) return model
const URL: string = MODEL_DIR;
const session = await InferenceSession.create(URL, { executionProviders: ['wasm'] });
model = session
return model
}
export const rembg = async (src: string) => {
const model = await loadModel()
const inputImage = await ImageJS.Image.load(src)
const { width, height } = inputImage
const imageSize = 320;
let inputPixels = inputImage.resize({ width: imageSize, height: imageSize }).data as Uint8Array
if (inputImage.alpha === 1) {
inputPixels = removeAlpha(inputPixels);
}
const inputChannels = [
new Float32Array(imageSize * imageSize),
new Float32Array(imageSize * imageSize),
new Float32Array(imageSize * imageSize),
];
const max = getMax(inputPixels);
const mean = [0.485, 0.456, 0.406];
const std = [0.229, 0.224, 0.225];
for (let i = 0; i < inputPixels.length; i++) {
const channel = i % 3;
const channelIndex = Math.floor(i / 3);
inputChannels[channel][channelIndex] =
(inputPixels[i] / max - mean[channel]) / std[channel];
}
const input = concatFloat32Array([
inputChannels[2],
inputChannels[0],
inputChannels[1],
]);
const results = await (model as InferenceSession).run({ "input.1": new Tensor("float32", input, [1, 3, 320, 320]) });
const mostPreciseOutputName = String(
Math.min(...(model as InferenceSession).outputNames.map((name: any) => +name)),
);
const outputMaskData = results[mostPreciseOutputName]
.data as Float32Array;
for (let i = 0; i < outputMaskData.length; i++) {
outputMaskData[i] = outputMaskData[i] * 255;
}
// 从小 resize 到大时,清晰度会变差,导致最后的成图会有锯齿
const sharpMask = new ImageJS.Image({ width: imageSize, height: imageSize, data: outputMaskData, components: 1, alpha: 0 })
.resize({ width, height })
.data;
const finalPixels = inputImage.clone().data
for (let i = 0; i < finalPixels.length / 4; i++) {
const alpha = sharpMask[i];
finalPixels[i * 4 + 3] = alpha;
}
const base64 = (new ImageJS.Image({ width, height, data: finalPixels, kind: 'RGBA' as ImageJS.ImageKind.RGBA, alpha: 1, components: 3 }))
.toBase64();
return 'data:image/png;base64,' + base64
}
export function concatFloat32Array(arrays: Float32Array[]): Float32Array {
let length = 0;
for (const array of arrays) length += array.length;
const output = new Float32Array(length);
let outputIndex = 0;
for (const array of arrays) {
for (const n of array) {
output[outputIndex] = n;
outputIndex++;
}
}
return output;
}
export function removeAlpha(array: Uint8Array): Uint8Array {
const output = new Array();
for (let i = 0; i < array.length; i++) {
if (i % 4 !== 3) {
output.push(array[i]);
}
}
return Uint8Array.from(output);
}
export function getMax(array: Uint8Array): number {
let max = 0;
for (let i = 0; i < array.length; i++) {
if (array[i] > max) max = array[i];
}
return max;
} |
package sample.cafekiosk.spring.domain.product;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import java.util.stream.Stream;
/**
* TDD 테스트
* 단위 테스트
*/
class ProductTypeTest {
@DisplayName("상품 타입이 재고 관련 타입인지를 체크한다.")
@Test
void containsStockType1(){
//given
ProductType givenType = ProductType.HANDMADE;
//when
boolean result = ProductType.containsStockType(givenType);
//then
assertThat(result).isFalse();
}
@DisplayName("상품 타입이 재고 관련 타입인지를 체크한다.")
@Test
void containsStockType2(){
//given
ProductType givenType = ProductType.BOTTLE;
//when
boolean result = ProductType.containsStockType(givenType);
//then
assertThat(result).isTrue();
}
/**
* @ParameterizedTest
* 검증할 여러 상황이 존재하지만, 결국 재고 관련 타입 체크라는 하나의 테스트이다.
* 아래와 같이 하나의 테스트이지만, 검증할게 여려가지라면 사용하는 방식
*/
@DisplayName("기존")
@Test
void containsStockType3(){
//given
ProductType givenType1 = ProductType.HANDMADE;
ProductType givenType2 = ProductType.BOTTLE;
ProductType givenType3 = ProductType.BAKERY;
//when
boolean result1 = ProductType.containsStockType(givenType1);
boolean result2 = ProductType.containsStockType(givenType2);
boolean result3 = ProductType.containsStockType(givenType3);
//then
assertThat(result1).isFalse();
assertThat(result2).isTrue();
assertThat(result3).isTrue();
}
@DisplayName("변경1")
@CsvSource({"HANDMADE,false", "BOTTLE,true", "BAKERY,true"})
@ParameterizedTest
void containsStockType4(ProductType productType, boolean expected){
//when
boolean result = ProductType.containsStockType(productType);
//then
assertThat(result).isEqualTo(expected);
}
private static Stream<Arguments> provideProductTypesForCheckStockType(){
return Stream.of(
Arguments.of(ProductType.HANDMADE, false),
Arguments.of(ProductType.BOTTLE, true),
Arguments.of(ProductType.BAKERY, true)
);
}
@DisplayName("변경2")
@MethodSource("provideProductTypesForCheckStockType")
@ParameterizedTest
void containsStockType5(ProductType productType, boolean expected){
//when
boolean result = ProductType.containsStockType(productType);
//then
assertThat(result).isEqualTo(expected);
}
} |
import {
Children,
isValidElement,
cloneElement,
MouseEvent,
HTMLAttributes,
ReactNode,
} from "react";
/**
* Stops the propagation of click events on the provided React children elements.
*
* @param children - The React children elements.
* @returns The modified React children elements with click event propagation stopped.
*/
export function stopPropagation({ children }: { children: ReactNode }) {
return Children.map(children, (child) => {
if (isValidElement(child)) {
return cloneElement(child, {
onClick: (e: MouseEvent<HTMLElement>) => {
e.stopPropagation();
if (child.props.onClick) {
child.props.onClick(e);
}
},
} as HTMLAttributes<HTMLElement>);
}
return child;
});
} |
import { NextResponse } from "next/server";
import { auth } from "@clerk/nextjs";
import prismadb from "@/lib/prismadb";
export async function POST(
req: Request,
{params} : {params : {storeId:string}}
) {
try{
const {userId} = auth();
const body = await req.json();
const {label,imageUrl} = body;
if (!userId){
return new NextResponse("Unauthenticated",{status:401});
}
if (!label){
return new NextResponse("Label is required",{status:400});
}
if (!imageUrl){
return new NextResponse("Image URL is required",{status:400});
}
if (!params.storeId){
return new NextResponse("Store ID is required",{status:400});
}
const storeByUserId = await prismadb.store.findFirst({
where:{
id:params.storeId,
userId
}
})
if (!storeByUserId){
return new NextResponse("Unauthorized is required",{status:403});
}
const billboard = await prismadb.billboard.create({
data:{
label,
imageUrl,
storeId: params.storeId
}
});
return NextResponse.json(billboard);
}
catch(error){
console.log('[BILLBOARDS_POST]',error);
return new NextResponse("Internal Error", {status:500});
}
}
export async function GET(
req: Request,
{params} : {params : {storeId:string}}
) {
try{
if (!params.storeId){
return new NextResponse("Store ID is required",{status:400});
}
const billboards = await prismadb.billboard.findMany({
where:{
storeId: params.storeId
}
});
return NextResponse.json(billboards);
}
catch(error){
console.log('[BILLBOARDS_GET]',error);
return new NextResponse("Internal Error", {status:500});
}
} |
import { User } from 'src/modules/user/entity/user.entity';
import {
IsString,
IsOptional,
IsNotEmpty,
IsNumber,
IsBoolean,
} from 'class-validator';
export class StoreResponse {
success: boolean;
data: any;
}
export class AddProduct {
@IsNotEmpty()
@IsString()
title: string;
@IsNotEmpty()
@IsString()
description: string;
@IsNotEmpty()
@IsString()
image: string;
@IsNotEmpty()
@IsString()
shortDescription: string;
@IsNotEmpty()
@IsString()
details: string;
@IsNotEmpty()
@IsNumber()
price: number;
@IsNotEmpty()
@IsString()
category: string;
@IsNotEmpty()
@IsString()
region: string;
@IsNotEmpty()
@IsString()
topic: string;
@IsNotEmpty()
@IsString()
countryId: string;
@IsNotEmpty()
@IsString()
subscriptionId: string;
}
export class UpdateProduct {
@IsNotEmpty()
@IsString()
id: string;
@IsOptional()
@IsNotEmpty()
@IsString()
title: string;
@IsOptional()
@IsNotEmpty()
@IsString()
shortDescription: string;
@IsOptional()
@IsNotEmpty()
@IsString()
details: string;
@IsOptional()
@IsNotEmpty()
@IsString()
description: string;
@IsOptional()
@IsNotEmpty()
@IsString()
image: string;
@IsOptional()
@IsNumber()
price: number;
@IsOptional()
@IsNotEmpty()
@IsString()
category: string;
@IsOptional()
@IsNotEmpty()
@IsString()
region: string;
@IsOptional()
@IsNotEmpty()
@IsString()
topic: string;
@IsOptional()
@IsNotEmpty()
@IsString()
countryId: string;
@IsOptional()
@IsBoolean()
active: boolean;
@IsOptional()
@IsString()
subscriptionId: string;
}
export class AddToCart {
user: User;
@IsNotEmpty()
@IsNumber()
qyt: number;
@IsNotEmpty()
@IsNumber()
price: number;
@IsNotEmpty()
@IsString()
productId: string;
}
export class UpdateCart {
user: User;
@IsNotEmpty()
@IsString()
id: string;
@IsNotEmpty()
@IsNumber()
qyt: number;
}
export class DeleteCart {
@IsNotEmpty()
@IsString()
id: string;
}
export class CreateOrder {
user: User;
@IsNotEmpty()
@IsString()
orderType: string;
@IsNotEmpty()
@IsString()
deliveryAddress: string;
@IsOptional()
@IsString()
couponCode: string;
@IsOptional()
@IsString()
salesCode: string;
} |
import Link from 'next/link'
import Image from 'next/image'
import { Flex, Box, Text, Button } from '@chakra-ui/react'
import Property from '../components/Property'
import { baseUrl, fetchApi} from '../utils/fetchApi'
const Banner = ({purpose, title1, title2, desc1, desc2, buttonText, linkName, imageUrl}) => (
<Flex flexWrap="wrap" justifyContent="center" alignItems="center" m="10">
<Image src={imageUrl} width={500} height={300} alt="banner" />
<Box p="5">
<Text color="gray.500" fontSize="sm" fontWeight="medium">{purpose}</Text>
<Text fontSize="3xl" fontWeight="bold">{title1}<br/>{title2}</Text>
<Text paddingTop="3" paddingBottom="3" color="gray.700" fontSize="sm" fontWeight="medium">{desc1}<br/>{desc2}</Text>
<Button fontSize="xl" >
<Link href={linkName}>{buttonText}</Link>
</Button>
</Box>
</Flex>
)
export default function Home({ propertiesForSale, propertiesForRent}) {
console.log(propertiesForRent, propertiesForSale);
return (
<Box>
<Banner
purpose="Rent A Home"
title="Rental Homes for"
title2="Everyone"
desc1="Explore Apartments, Villas, Homes"
desc2="and more"
buttonText="Explore Renting"
linkName="/search?purpose=for-rent"
imageUrl="https://bayut-production.s3.eu-central-1.amazonaws.com/image/145426814/33973352624c48628e41f2ec460faba4"
/>
<Flex flexWrap="wrap">
{ /* Fetch Properties and map over them */}
{propertiesForRent.map((property)=><Property property={property} key={property.id}/>)}
</Flex>
<Banner
purpose="Buy A Home"
title="Find, Buy & Own Your"
title2="Dream Home"
desc1="Explore Apartments, Villas, Homes"
desc2="and more"
buttonText="Explore Buying"
linkName="/search?purpose=for-sale"
imageUrl='https://bayut-production.s3.eu-central-1.amazonaws.com/image/110993385/6a070e8e1bae4f7d8c1429bc303d2008'
/>
{ /* Fetch Properties and map over them */}
<Flex flexWrap="wrap">
{propertiesForSale.map((property)=><Property property={property} key={property.id}/>)}
</Flex>
</Box>
)
}
export async function getStaticProps() {
const propertyForSale = await fetchApi(`${baseUrl}/properties/list?locationExternalIDs=5002&purpose=for-sale&hitsPerPage=6`)
const propertyForRent = await fetchApi(`${baseUrl}/properties/list?locationExternalIDs=5002&purpose=for-rent&hitsPerPage=6`)
return{
props: {
propertiesForSale: propertyForSale?.hits,
propertiesForRent: propertyForRent?.hits,
}
}
} |
import * as React from 'react';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import './Multiple_Align.css';
function Multiple_Align() {
const [file1, setFile1] = useState(null);
const [data1, setData1] = useState("");
const [genTree, setGenTree] = useState(false);
const [mail, setMail] = useState("");
const handleSingleFile = async (e) => {
console.log("Single file upload");
setFile1(e.target.files[0]);
const reader = new FileReader();
reader.onload = async (e) => {
const text = (e.target.result);
console.log("Reading file 1:")
setData1(text);
console.log("File 1 read")
};
if (e.target.files[0]) {
reader.readAsText(e.target.files[0]);
}
}
const handleReset = () => {
setFile1(null);
setData1("");
setGenTree(false);
setMail("");
}
const handleUpload = async () => {
console.log("Upload button clicked");
console.log("data1:", data1);
if(data1) {
let data = {
seqs: data1,
genTree: genTree,
mail: mail
}
console.log("Data:", data1);
try {
const res = await axios.post("http://127.0.0.1:8000/multi_seq_align", data);
// console.log(res);
// setRes(res);
// const fileContents = `${res.data.per_line_out}`
// const blob = new Blob([fileContents], {type: 'text/plain'});
// const url = window.URL.createObjectURL(blob);
// setDownload(url);
if (res.status === 200) {
window.alert("Multiple alignment request successfully sent! Check your email for the result.");
window.location.href = '/home';
} else {
window.alert("Something went wrong. Please try again.");
window.location.href = '/home';
}
} catch (err) {
console.log(err.response);
window.alert("Something went wrong. Please try again.");
window.location.href = '/home';
}
}
}
return (
<div>
<div className="title-bar">
<h1>ALIGN MULTIPLE SEQUENCES</h1>
<button onClick={() => window.location.href = '/home'}>Home</button>
</div>
<div className="form-container">
<div>
<div>
<input type="file" accept=".fna, .fasta, .FASTA" onChange={handleSingleFile} />
<input type="email" placeholder="Enter your email" onChange={(e) => setMail(e.target.value)} />
<h6>File</h6>
{file1 && <p>{file1.name}</p>}
<h6>Data</h6>
{data1 && <p>{data1.split('\n').slice(0, 90).join('\n')}</p>}
<div className="gen-tree">
<label htmlFor="gen-tree">Generate phylogenetic tree?</label>
<input type="checkbox" id="gen-tree" name="gen-tree" onChange={() => setGenTree(!genTree)} />
</div>
<button onClick={handleUpload}>Upload</button>
<button onClick={handleReset}>Reset</button>
</div>
</div>
</div>
</div>
);
}
export default Multiple_Align; |
/* eslint-disable no-unused-vars */
import { useState } from "react";
import validate from "../../helpers/validate";
import styles from "./Login.module.css";
import axios from "axios";
import { useDispatch } from "react-redux";
import { setUserDataReduce } from "../../redux/userSlice";
import { useNavigate } from "react-router-dom";
const Login = () => {
const POSTLOGIN_URL = "https://5a85-186-127-224-4.ngrok-free.app/users/login";
const [UserData, setUserData] = useState({
username: "",
password: "",
});
const [Errors, setErrors] = useState({});
const handlerInputChange = (event) => {
const { name, value } = event.target;
setUserData({
...UserData,
[name]: value,
});
setErrors(validate({ ...UserData, [name]: value }));
};
const Dispatch = useDispatch();
const Navigate = useNavigate();
const handleOnSubmit = (event) => {
event.preventDefault();
axios
.post(POSTLOGIN_URL, UserData)
.then((response) => response.data)
.then((data) => {
Dispatch(setUserDataReduce(data));
alert("Inicio de sesion exitoso!");
Navigate("/");
})
.catch(() => {
alert(
" Lo siento, no pudimos iniciar sesión en este momento. Por favor, verifica tus credenciales e intenta nuevamente. Si el problema persiste, no dudes en contactarnos para obtener ayuda."
);
});
};
return (
<>
<section className={styles.sectionLogin}>
<div className={styles.containerGeneralLogin}>
<div>
<img
src="https://img.freepik.com/fotos-premium/disparo-vertical-dentista-haciendo-escaneo-dental-dientes-pacientes_118628-3726.jpg"
alt=""
/>
</div>
<form className={styles.formLogin} onSubmit={handleOnSubmit}>
<p className={styles.titleformLogin}>Login </p>
<label htmlFor="username" className={styles.labelLogin}>
Usuario:
</label>
<input
className={styles.inputLogin}
type="text"
name="username"
value={UserData.username}
placeholder="usuario"
onChange={handlerInputChange}
/>
<p className={styles.parrafoFormLogin}>
{Errors.username === "" ? null : Errors.username}
</p>
<label htmlFor="password" className={styles.labelLogin}>
Contraseña:
</label>
<input
className={styles.inputLogin}
type="password"
name="password"
value={UserData.password}
placeholder="*****"
onChange={handlerInputChange}
/>
<p className={styles.parrafoFormLogin}>
{Errors.password === "" ? null : Errors.password}
</p>
<p className={styles.parrafoFormLogin}>
Todos los campos son obligatorios
</p>
<button
type="submit"
className={styles.submitLogin}
disabled={Errors.username || Errors.password}
>
Ingresar
</button>
</form>
</div>
</section>
</>
);
};
export default Login; |
#!/usr/bin/python3
"""This is the Rectangle module.
"""
from models.base import Base
class Rectangle(Base):
"""This class inherits from Base and defines a Rectangle object.
Attributes:
__width (int): the width of the rectangle.
__height (int): the height of the rectangle.
__x (int): the horizontal (x) padding of the rectangle.
__y (int): the vertical (y) padding of the rectangle.
"""
def __init__(self, width, height, x=0, y=0, id=None):
"""Initializes the default attributes of the Base object.
Args:
width (int): the wanted width of the rectangle.
height (int): the wanted height of the rectangle.
x (int): the wanted horizontal (x) padding of the rectangle.
y (int): the wanted vertical (y) padding of the rectangle.
id (int): the wanted identifier of the Base object.
"""
super().__init__(id)
self.width = width
self.height = height
self.x = x
self.y = y
# width attribute getter and setter.
@property
def width(self):
"""Get and Set the width attribute of the Rectangle."""
return self.__width
@width.setter
def width(self, value):
if type(value) is not int:
raise TypeError("width must be an integer")
if value <= 0:
raise ValueError("width must be > 0")
self.__width = value
# height attribute getter and setter.
@property
def height(self):
"""Get and Set the height attribute of the Rectangle."""
return self.__height
@height.setter
def height(self, value):
if type(value) is not int:
raise TypeError("height must be an integer")
if value <= 0:
raise ValueError("height must be > 0")
self.__height = value
# x getter and setter.
@property
def x(self):
"""Get and Set the x attribute of the Rectangle."""
return self.__x
@x.setter
def x(self, value):
if type(value) is not int:
raise TypeError("x must be an integer")
if value < 0:
raise ValueError("x must be >= 0")
self.__x = value
# y getter and setter.
@property
def y(self):
"""Get and Set the y attribute of the Rectangle."""
return self.__y
@y.setter
def y(self, value):
if type(value) is not int:
raise TypeError("y must be an integer")
if value < 0:
raise ValueError("y must be >= 0")
self.__y = value
def area(self):
"""Area of the rectangle."""
return self.width * self.height
def display(self):
"""Prints in stdout the Rectangle instance with the character '#'."""
for i in range(self.height):
print("#" * self.width)
def __str__(self):
"""Returns the string representation of the Rectangle."""
return (
f"[Rectangle] ({self.id}) {self.x}/{self.y} - "
f"{self.width}/{self.height}"
)
def display(self):
"""Prints in stdout the Rectangle instance with the character '#'."""
for y_offset in range(self.y):
print()
for _ in range(self.height):
print(" " * self.x, end="")
print("#" * self.width)
def update(self, *args, **kwargs):
"""Updates the attributes of the Rectangle.
Args:
*args: Variable number of positional arguments.
- 1 argument: Updates the id attribute.
- 2 arguments: Updates the id and width attributes.
- 3 arguments: Updates the id, width, and height attributes.
- 4 arguments: Updates the id, width, height, and x attributes.
- 5 arguments: Updates all attributes.
**kwargs: Variable number of keyword arguments.
Each key represents an attribute of the instance.
"""
if args:
if len(args) >= 1:
self.id = args[0]
if len(args) >= 2:
self.width = args[1]
if len(args) >= 3:
self.height = args[2]
if len(args) >= 4:
self.x = args[3]
if len(args) >= 5:
self.y = args[4]
else:
for key, value in kwargs.items():
setattr(self, key, value)
def to_dictionary(self):
"""Returns the dictionary representation of a Rectangle."""
dictionary = {
'id': self.id,
'width': self.width,
'height': self.height,
'x': self.x,
'y': self.y
}
return dictionary |
package com.example.my_ecomerge_app.view.adapter
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.example.my_ecomerge_app.R
import com.example.my_ecomerge_app.application.MyApplication
import com.example.my_ecomerge_app.model.Cart
import com.example.my_ecomerge_app.view.activity.HomeAcitivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.NumberFormat
import java.util.Currency
import java.util.Locale
class AdapterBill(private var listProduct: MutableList<Cart>, private var context: Context) :
RecyclerView.Adapter<AdapterBill.MyViewHolder>() {
// private var listener: OnItemClick? = null
//
// fun setOnItemClick(listener : OnItemClick){
// this.listener = listener
// }
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.item_bill_order, parent, false)
return MyViewHolder(view)
}
override fun getItemCount(): Int {
return listProduct.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val product = listProduct[position]
val imageUri = Uri.parse(product.imgFood)
Log.d("---", imageUri.toString())
val formattedPrice = formatPrice(product.price)
val updatedTotalPrice = calculateTotalPrice()
holder.tvNameFood.text = product.nameFood
holder.tvPrice.text = formattedPrice
holder.tvQuantity.text = product.quantity.toString()
// holder.tvPrice.text = updatedTotalPrice
var quantity = product.quantity
var calculate: Double = 1.00
holder.btnPlus.setOnClickListener {
quantity++
holder.tvQuantity.text = quantity.toString()
calculate = quantity * product.price
product.quantity = quantity
// product.price = calculate
CoroutineScope(Dispatchers.IO).launch {
MyApplication.appDatabase.cartDao().updateItem(product)
}
}
holder.btnMinus.setOnClickListener {
quantity--
val currentQuantity = quantity
holder.tvQuantity.text = quantity.toString()
product.quantity = quantity
val updatedTotalPrice = calculateTotalPrice()
// listCart.price = calculate
CoroutineScope(Dispatchers.IO).launch {
MyApplication.appDatabase.cartDao().updateItem(product)
}
if (quantity == 0) {
AlertDialog.Builder(context)
.setTitle("Delete")
.setIcon(R.drawable.baseline_warning_24)
.setMessage("Bạn có muốn xoá sản phẩm này không?")
.setPositiveButton("Có") { dialog, _ ->
// Xoá phần tử khỏi danh sách và cập nhật UI
listProduct.removeAt(position)
notifyDataSetChanged()
// Xoá phần tử từ cơ sở dữ liệu
CoroutineScope(Dispatchers.IO).launch {
MyApplication.appDatabase.cartDao().deleteItemById(product.id)
}
if (listProduct.size <= 0) {
val intent = Intent(context, HomeAcitivity::class.java)
context.startActivity(intent)
(context as AppCompatActivity).finish()
}
dialog.dismiss()
}
.setNegativeButton("Không") { dialog, _ ->
val setQuantity = "1"
holder.tvQuantity.text = setQuantity
val updatedTotalPrice = calculateTotalPrice()
holder.tvPrice.text = updatedTotalPrice
CoroutineScope(Dispatchers.IO).launch {
product.quantity = setQuantity.toInt()
MyApplication.appDatabase.cartDao().updateItem(product)
}
dialog.dismiss()
}
.create()
.show()
}
}
}
fun calculateTotalPrice(): String {
return formatPrice(listProduct.sumByDouble { it.price * it.quantity })
}
inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvNameFood: TextView = itemView.findViewById(R.id.tvName)
val tvChange: TextView = itemView.findViewById(R.id.tvChangeBill)
val tvPrice: TextView = itemView.findViewById(R.id.tvPriceBill)
val tvQuantity: TextView = itemView.findViewById(R.id.tvQuanityBill)
val btnPlus: ImageView = itemView.findViewById(R.id.btnPlusBill)
val btnMinus: ImageView = itemView.findViewById(R.id.btnMinusBill)
}
private fun formatPrice(price: Double): String {
val vietnamLocale = Locale("vi", "VN")
val currencyFormat = NumberFormat.getCurrencyInstance(vietnamLocale)
currencyFormat.currency = Currency.getInstance("VND")
return currencyFormat.format(price)
}
} |
import { HttpException, HttpStatus } from '@nestjs/common';
import { existsSync, mkdirSync } from 'fs';
import { diskStorage } from 'multer';
import { extname } from 'path';
import { v4 as uuid } from 'uuid';
const uploadPath = './public/upload/images';
// Multer configuration
export const multerConfig = {
dest: uploadPath,
};
// Multer upload options
export const multerOptions = {
// Enable file size limits
limits: {
fileSize: 1024 * 1024 * 50,
},
// Check the mimetypes to allow for upload
fileFilter: (req: any, file: any, cb: any) => {
if (file.mimetype.match(/\/(jpg|jpeg|png|gif)$/)) {
// Allow storage of file
cb(null, true);
} else {
// Reject file
cb(
new HttpException(
`Unsupported file type ${extname(file.originalname)}`,
HttpStatus.BAD_REQUEST,
),
false,
);
}
},
// Storage properties
storage: diskStorage({
// Destination storage path details
destination: (req: any, file: any, cb: any) => {
const uploadPath = multerConfig.dest;
// Create folder if doesn't exist
if (!existsSync(uploadPath)) {
mkdirSync(uploadPath);
}
cb(null, uploadPath);
},
// File modification details
filename: (req: any, file: any, cb: any) => {
cb(null, `${uuid()}${extname(file.originalname)}`);
},
}),
}; |
<div id="eml-profile-newbie" ng-show="authService.hasPermission('Employee_Mgmt')">
<form novalidate name="newbieForm">
<div class="modal-header">
<h4 class="modal-title">
<strong>{{ ::"employees.NEW_EMPLOYEE" | translate }}</strong>
</h4>
</div>
<div class="modal-body">
<!-- First Name -->
<div class="row">
<div class="col-md-4 no-right-padding text-uppercase">
<p>{{ ::"app.FIRST_NAME" | translate }}</p>
</div>
<div class="col-md-8 eml-strong eml-inline-editing form-group">
<input required
focus-me="true"
name="firstName"
type="text"
placeholder="{{ ::'app.FIRST_NAME' | translate }}"
ng-model="newbie.dto.firstName"/>
<!-- Common Directive: Validate-messages starts -->
<div validate-messages messages-for="newbieForm.firstName" submitted="newbie.submitted"></div>
</div>
</div>
<!-- Last Name -->
<div class="row">
<div class="col-md-4 no-right-padding text-uppercase">
<p>{{ ::"app.LAST_NAME" | translate }}</p>
</div>
<div class="col-md-8 eml-strong eml-inline-editing form-group">
<input required
type="text"
name="lastName"
placeholder="{{ ::'app.LAST_NAME' | translate }}"
ng-model="newbie.dto.lastName"/>
<!-- Common Directive: Validate-messages starts -->
<div validate-messages messages-for="newbieForm.lastName" submitted="newbie.submitted"></div>
</div>
</div>
<!-- Employee ID -->
<div class="row">
<div class="col-md-4 no-right-padding text-uppercase">
<p>{{ ::"employees.EMPLOYEE_IDENTIFIER" | translate }}</p>
</div>
<div class="col-md-8 eml-strong eml-inline-editing form-group">
<input required
type="text"
name="employeeIdentifier"
placeholder="{{ ::'employees.EMPLOYEE_IDENTIFIER' | translate }}"
ng-model="newbie.dto.employeeIdentifier"/>
<!-- Common Directive: Validate-messages starts -->
<div validate-messages messages-for="newbieForm.employeeIdentifier" submitted="newbie.submitted"></div>
</div>
</div>
<!-- Home Team -->
<div class="row">
<div class="col-md-4 no-right-padding text-uppercase">
<p>{{ ::"employees.HOME_TEAM" | translate }}</p>
</div>
<div class="col-md-8 eml-strong eml-inline-editing form-group">
<select required
ng-model="newbie.dto.employeeTeamCreateDto.teamId"
name="homeTeamId"
ng-options="team.id as team.name group by team.site.name
for team in newbie.sitesTeamsTree">
<option>---</option>
</select>
<!-- Common Directive: Validate-messages starts -->
<div validate-messages messages-for="newbieForm.homeTeamId" submitted="newbie.submitted"></div>
</div>
</div>
<div class="row divider"></div>
<!-- Login checkbox -->
<div class="row">
<div class="checkbox col-md-12 no-right-padding">
<label>
<input type="checkbox"
ng-checked="newbie.loginEqualsId"
ng-model="newbie.loginEqualsId"> {{ ::"employees.LOGIN_TO_EQUAL_ID" | translate }}
</label>
</div>
</div>
<!-- If Login equals ID -->
<div class="row" ng-show="newbie.loginEqualsId">
<div class="col-md-4 no-right-padding text-uppercase">
<p>{{ ::"employees.LOGIN" | translate }}</p>
</div>
<div class="col-md-8 eml-strong">
<p>{{ newbie.dto.employeeIdentifier }}</p>
</div>
</div>
<!-- Login custom input -->
<div class="row" ng-hide="newbie.loginEqualsId">
<div class="col-md-4 no-right-padding text-uppercase">
<p>{{ ::"employees.LOGIN" | translate }}</p>
</div>
<div class="col-md-8 eml-strong eml-inline-editing form-group">
<input ng-required="!newbie.loginEqualsId"
type="text"
name="loginId"
placeholder="{{ ::'employees.LOGIN' | translate }}"
ng-model="newbie.dto.userAccountDto.login"/>
<!-- Common Directive: Validate-messages starts -->
<div validate-messages messages-for="newbieForm.loginId" submitted="newbie.submitted"></div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default"
ng-click="newbie.cancelModal()">{{ ::"app.CANCEL" | translate }}</button>
<button class="btn btn-success"
ng-click="newbie.createEmployee()">{{ ::"app.CREATE" | translate }}</button>
</div>
</form>
</div> |
# Prompts
## Concept
Prompting is the fundamental input that gives LLMs their expressive power. LlamaIndex uses prompts to build the index, do insertion,
perform traversal during querying, and to synthesize the final answer.
LlamaIndex uses a set of [default prompt templates](https://github.com/jerryjliu/llama_index/blob/main/llama_index/prompts/default_prompts.py) that work well out of the box.
In addition, there are some prompts written and used specifically for chat models like `gpt-3.5-turbo` [here](https://github.com/jerryjliu/llama_index/blob/main/llama_index/prompts/chat_prompts.py).
Users may also provide their own prompt templates to further customize the behavior of the framework. The best method for customizing is copying the default prompt from the link above, and using that as the base for any modifications.
## Usage Pattern
Using prompts is simple.
```python
from llama_index.prompts import PromptTemplate
template = (
"We have provided context information below. \n"
"---------------------\n"
"{context_str}"
"\n---------------------\n"
"Given this information, please answer the question: {query_str}\n"
)
qa_template = PromptTemplate(template)
# you can create text prompt (for completion API)
prompt = qa_template.format(context_str=..., query_str=...)
# or easily convert to message prompts (for chat API)
messages = qa_template.format_messages(context_str=..., query_str=...)
```
See our Usage Pattern Guide for more details.
```{toctree}
---
maxdepth: 2
---
prompts/usage_pattern.md
```
## Example Guides
Simple Customization Examples
```{toctree}
---
maxdepth: 1
---
Completion prompts </examples/customization/prompts/completion_prompts.ipynb>
Chat prompts </examples/customization/prompts/chat_prompts.ipynb>
```
Prompt Engineering Guides
```{toctree}
---
maxdepth: 1
---
/examples/prompts/prompt_mixin.ipynb
/examples/prompts/advanced_prompts.ipynb
/examples/prompts/prompts_rag.ipynb
```
Experimental
```{toctree}
---
maxdepth: 1
---
/examples/prompts/prompt_optimization.ipynb
/examples/prompts/emotion_prompt.ipynb
``` |
*Version August 2012
--------------------
basic syntax:
hhi var, by(varlist) [if exp] [in range] [outfile, replace]
Description:
hhi generates Herfindahl-Hirschman index variables also commonly known as concentration index in economics and finance. The module supports multiple variables and group ids and allows user to export output in table format (csv comma delimited).
Options
-------
by(varlist): allows multiple groups defined by `varlist' e.g. (year, country, region)
outfile: export data in table format (.csv comma delimited)
Examples:
----------
hhi x1 x2
hhi x1, by (year country region)
hhi x1, by (year country region) outfile
hhi x1 x2 x3, by(year country region)
hhi x1 x2 x3, by(year country region) outfile replace
Author
Muhammad Rashid Ansari
INSEAD Business School
1 Ayer Rajah Avenue, Singapore 138676
rashid.ansari@insead.edu |
import 'package:auto_size_text/auto_size_text.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:no_name_ecommerce/services/translate_string_service.dart';
import 'package:no_name_ecommerce/view/utils/common_helper.dart';
import 'package:no_name_ecommerce/view/utils/constant_colors.dart';
import 'package:provider/provider.dart';
double screenPadHorizontal = 25;
gapH(double value) {
return SizedBox(
height: value,
);
}
gapW(double value) {
return SizedBox(
width: value,
);
}
commonImage(String imageLink, double height, double width) {
return ClipRRect(
borderRadius: BorderRadius.circular(6),
child: CachedNetworkImage(
imageUrl: imageLink,
placeholder: (context, url) {
return Image.asset('assets/images/placeholder.png');
},
height: height,
width: width,
fit: BoxFit.cover,
),
);
}
detailsRow(String title, int quantity, String price) {
return Consumer<TranslateStringService>(
builder: (context, ln, child) => Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
flex: 3,
child: Text(
ln.getString(title),
style: const TextStyle(
color: greyParagraph,
fontSize: 14,
fontWeight: FontWeight.w400,
),
),
),
quantity != 0
? Expanded(
flex: 1,
child: Text(
'x$quantity',
textAlign: TextAlign.center,
style: const TextStyle(
color: greyFour,
fontSize: 16,
fontWeight: FontWeight.w400,
),
))
: Container(),
Expanded(
flex: 2,
child: AutoSizeText(
price,
maxLines: 1,
textAlign: TextAlign.right,
style: const TextStyle(
color: greyFour,
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
)
],
),
);
}
bRow(String title, String text, {bool lastItem = false, icon}) {
return Column(
children: [
Consumer<TranslateStringService>(
builder: (context, ln, child) => Row(
children: [
//icon
SizedBox(
width: 125,
child: Row(children: [
icon != null
? Row(
children: [
SvgPicture.asset(
icon,
height: 19,
),
const SizedBox(
width: 7,
),
],
)
: Container(),
Text(
ln.getString(title),
style: const TextStyle(
color: greyFour,
fontSize: 14,
fontWeight: FontWeight.w400,
),
)
]),
),
Flexible(
child: Text(
text,
style: const TextStyle(
color: greyFour,
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
)
],
),
),
lastItem == false
? Container(
margin: const EdgeInsets.symmetric(vertical: 14),
child: dividerCommon(),
)
: Container()
],
);
}
capsule(String capsuleText) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 7, horizontal: 11),
decoration: BoxDecoration(
color: getCapsuleColor(capsuleText).withOpacity(.1),
borderRadius: BorderRadius.circular(4)),
child: Text(
capsuleText,
style: TextStyle(
color: getCapsuleColor(capsuleText),
fontWeight: FontWeight.w600,
fontSize: 12),
),
);
}
getCapsuleColor(String status) {
if (status.toLowerCase() == 'pending' || status.toLowerCase() == 'open') {
return successColor;
} else if (status.toLowerCase() == 'cancel') {
return Colors.red;
} else if (status.toLowerCase() == 'complete' ||
status.toLowerCase() == 'close') {
return Colors.orange[600];
} else if (status.toLowerCase() == 'low' ||
status.toLowerCase() == 'medium') {
return successColor;
} else if (status.toLowerCase() == 'high' ||
status.toLowerCase() == 'urgent') {
return Colors.red;
} else {
return Colors.grey[600];
}
} |
import { Request, Response } from 'express';
import CreateRoomService from '@modules/rooms/services/CreateRoomService';
import UpdateRoomService from '@modules/rooms/services/UpdateRoomService';
import DeleteRoomService from '@modules/rooms/services/DeleteRoomService';
import { getCustomRepository, getRepository } from 'typeorm';
import RoomsRepository from '@modules/rooms/infra/typeorm/repositories/RoomsRepository';
import Room from '@modules/rooms/infra/typeorm/entities/Room';
import { instanceToInstance } from 'class-transformer';
export default class RoomsController {
public async create(
request: Request,
response: Response,
): Promise<Response> {
const {
room_type,
room_number,
capacity,
floor,
description,
availability,
} = request.body;
const { filename } = request.file;
const roomsRepository = new RoomsRepository();
const createRoom = new CreateRoomService(roomsRepository);
const room = await createRoom.execute({
room_type,
room_number,
capacity,
floor,
description,
availability,
image: filename,
});
return response.json(room);
}
public async delete(
request: Request,
response: Response,
): Promise<Response> {
const room_code = request.params.id;
const roomsRepository = new RoomsRepository();
const deleteRoom = new DeleteRoomService(roomsRepository);
const room = await deleteRoom.execute(room_code);
return response.json(room);
}
public async update(
request: Request,
response: Response,
): Promise<Response> {
const {
room_code,
room_type,
room_number,
capacity,
floor,
description,
availability,
} = request.body;
const roomsRepository = new RoomsRepository();
const updateRoom = new UpdateRoomService(roomsRepository);
console.log(!!request.file);
if (!!request.file) {
const room = await updateRoom.execute({
room_code,
room_type,
room_number,
capacity,
floor,
description,
availability,
image: request.file.filename,
});
return response.json(room);
} else {
const room = await updateRoom.execute({
room_code,
room_type,
room_number,
capacity,
floor,
description,
availability,
});
return response.json(room);
}
}
public async index(
request: Request,
response: Response,
): Promise<Response> {
try {
const roomsRepository = getCustomRepository(RoomsRepository);
const rooms = await roomsRepository.find();
return response.json(instanceToInstance(rooms));
} catch (error) {
console.error(error);
}
}
public async show(request: Request, response: Response): Promise<Response> {
const room_code = request.params.room_code;
const roomsRepository = getRepository(Room);
const room = await roomsRepository.find({
where: { room_code },
});
return response.json(instanceToInstance(room));
}
public async showOnDay(
request: Request,
response: Response,
): Promise<Response> {
const interval = request.query['interval'];
const day = request.query['day'];
const week = request.query['week'];
console.log(interval)
try {
const roomsRepository = getRepository(Room);
const rooms =
await roomsRepository.query(`SELECT room_code, interval, MAX(room_type) as room_type, MAX(room_number) as room_number, MAX(floor) as floor, MAX(${day}) as ${day} FROM (
SELECT non_fixed_schedules.room_code, non_fixed_schedules.interval, non_fixed_schedules.${day}, rooms.room_type, rooms.room_number, rooms.floor
FROM non_fixed_schedules
LEFT JOIN rooms
ON non_fixed_schedules.room_code = rooms.room_code
WHERE non_fixed_schedules.week = '${week}' AND non_fixed_schedules.interval = ${interval}
UNION
SELECT schedules.room_code, schedules.interval, schedules.${day}, rooms.room_type, rooms.room_number, rooms.floor
FROM schedules
LEFT JOIN rooms
ON schedules.room_code = rooms.room_code
WHERE schedules.interval = ${interval}
) t
GROUP BY t.room_code, t.interval
ORDER BY t.room_code, t.interval`);
return response.json(rooms);
} catch (error) {
console.error(error);
}
}
} |
% Options for packages loaded elsewhere
\PassOptionsToPackage{unicode}{hyperref}
\PassOptionsToPackage{hyphens}{url}
%
\documentclass[
]{article}
\usepackage{amsmath,amssymb}
\usepackage{iftex}
\ifPDFTeX
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{textcomp} % provide euro and other symbols
\else % if luatex or xetex
\usepackage{unicode-math} % this also loads fontspec
\defaultfontfeatures{Scale=MatchLowercase}
\defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
\fi
\usepackage{lmodern}
\ifPDFTeX\else
% xetex/luatex font selection
\fi
% Use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\IfFileExists{microtype.sty}{% use microtype if available
\usepackage[]{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\makeatletter
\@ifundefined{KOMAClassName}{% if non-KOMA class
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}}
}{% if KOMA class
\KOMAoptions{parskip=half}}
\makeatother
\usepackage{xcolor}
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
\makeatother
% Scale images if necessary, so that they will not overflow the page
% margins by default, and it is still possible to overwrite the defaults
% using explicit options in \includegraphics[width, height, ...]{}
\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
% Set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother
\setlength{\emergencystretch}{3em} % prevent overfull lines
\providecommand{\tightlist}{%
\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
\usepackage{float}
\usepackage{sectsty}
\ifLuaTeX
\usepackage{selnolig} % disable illegal ligatures
\fi
\IfFileExists{bookmark.sty}{\usepackage{bookmark}}{\usepackage{hyperref}}
\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
\urlstyle{same}
\hypersetup{
hidelinks,
pdfcreator={LaTeX via pandoc}}
\author{}
\date{\vspace{-2.5em}}
\begin{document}
\hypertarget{organism-physiology-in-response-to-multiple-drivers-of-environmental-change}{%
\section{Organism Physiology in Response to Multiple Drivers of
Environmental
Change}\label{organism-physiology-in-response-to-multiple-drivers-of-environmental-change}}
~~~~~ Organisms and environments are entwined, as the relationship
between organisms and the environments they are embedded within, is in
constant flux through inextricable links and flows of energy. The
relationship between organisms and environments varies through both
space and time and is influenced by a mosaic of dynamic biotic and
abiotic drivers \citep{connell1977mechanisms, menge1987community}.
Organisms are active participants in constructing their environment,
from altering seawater biogeochemistry through physiological processes
to organisms constructing biogenic structures; plenty of studies
demonstrate that the processes that organisms undergoe cascade to
influence the environment\citep{lewontin1983organism,estes1974sea}.
Organisms, throughout their development, must physiologically cope with
the conditions of the environment that they are situated within,
inlfuencing species beyond themselves and thus inevitably influencing
community structure and populations \citep{bozinovic2015physiological}.
Organisms and the ecosystems they construct, while playing an essential
role in structuring the physical and biological environment, are
simultaneously governed by the ability to perform and function under a
myriad of complex interactions, as each act to influence one another
non- contemporaneously and contemporaneously through direct and indirect
feedback loops \citep{levin1974disturbance,paine1980food}. Organisms are
simultaneously creators and products of the environment. In a geological
epoch of rapid ecological change, it is increasingly imperative to
understand the extent to which organisms can respond to environmental
variability across multiple drivers of change and how changing
organismal processes may scale up to influence other species.
Understanding physiological responses, interactions, and constraints of
marine organisms to anthropogenic climate change is perhaps the sine qua
non for understanding the changes between marine organisms and the
ecosystems they construct. This research intends to inform how the
changing oceanic environment may affect organismal physiology by teasing
apart the relationship between environmental drivers and physiological
performance to assess changes in energitic requirements. This research
also intends to elucidate how changes within physiological processes in
one organism may have indirect effects on other species. In this regard,
the fate of organisms is intertwined as the energetic requirements of
one species codetermines the other, illustrating that organisms are
directly or indirectly the subjects and objects of ecological change
\citep{lewontin1983organism}.
~~~~~ Environments undergo dynamic changes driven by natural
fluctuations in abiotic and biotic factors that, in turn, shape
community structure and processes, drive ecological shifts, and create
diverse mosaics of microhabitats
\citep{connell1961influence, stenseth2002ecological, kroeker2017embracing}.
Environmental drivers are an abiotic parameter that influences organisms
and environments across a spectrum ranging from enhancing, optimal, or
stressful conditions
\citep{cote2016interactions, boyd2012understanding}. For example, within
marine ecosystems, the combination of oceanographic processes and local
coastal geography may create an array of patterns and variability in
abiotic drivers such as temperature, flow, pH, dissolved oxygen, etc.,
that may impact the structure and processes of ecological communities on
distances ranging from microscale to macroscale
\citep{deser2010sea, hofmann2010living}. Such heterogeneous patterns are
naturally occurring and create complex gradients that shape ecological
communities and influence physiological processes within individual
organisms \citep{helmuth2006mosaic}.Many organisms have evolved to
withstand complex and variable environmental gradients, mediated through
physiological mechanisms such as phenotypic plasticity and
acclimatization \citep{hofmann2010living, tomanek2002heat}. According to
the metabolic theory of ecology, environmental gradients and changes in
abiotic factors may result in physiological trade-offs due to the
alterations within the energetic partitioning of an organism's
metabolism \citep{portner2008physiology, brown2004metabolic}.
Metabolism, comprises the total sum of biological and chemical processes
in converting energetic resources and materials into biomass and
activity \citep{brown2004metabolic}. Furthermore, organismal metabolic
rates are intrinsically linked to respiration rates, as cellular
respiration mediates the conversion of nutrients into energy in the form
of adenosine triphosphate (ATP) for cellular processes. By comparing the
respiration rates of organisms across gradients of environmental
drivers, we can effectively quantify and compare the metabolic
constraints and tolerance limits of organisms, thereby inferring changes
in energetic requirements as well as energetic transfer within
ecosystems \citep{somero2002thermal, silbiger2019comparative}. The
influence of multiple drivers of environmental change on metabolic
processes is of paramount interest in ecology, as alterations in
metabolism directly impact a species' survival, behavior, and energetic
requirements, consequently affecting fitness and ecosystem processes
\citep{carey2016sea}.
Cellular respiration involving the consumption of oxygen (O2) through a
process of organismal respiration to produce energy in the form of
adenosine triphosphate (ATP) \cite{babcock1992oxygen} according to the
equation:
\[
C_6H_{12}O_6 + 6O_2 \rightarrow 6CO_2 + 6H_2O + \text{energy (as ATP)}
\]
~~~~~ The physiological processes of marine organisms are directly
impacted by abiotic drivers such as temperature and pH, which play
pivotal roles in shaping the functioning and structure of marine
ecosystems. \citep{woodwell1970effects}. Temperature, in particular, is
the fundamental driver in determining physiological rates of organisms
as the kinetic energy of biochemical reactions is temperature dependent
\citep{levins1968evolution, somero2002thermal, portner2012integrating}.
Biological processes such as organismal and ecological interactions are
also strongly influenced by temperature
\citep{hochachka2002biochemical}. This is exemplified by the
relationship between temperature and body size, where organisms develop
faster yet decrease in size under elevated temperatures
\citep{elahi2020historical}. Metabolic rates are strongly influenced by
an organism's body size and temperature and are subject to change due to
changes in abiotic drivers and the natural variability of drivers
\citep{brown2004metabolic, oconnor2007temperature}. Further, organisms
adapt to local temperatures to match optimal conditions for
physiological processes and acclimatize to a range around these values
\citep{sinclair2016can}. Any range too far beyond the ability of an
organism to acclimatize influences survival, fitness, and population
densities \citep{hochachka2002biochemical}. Studies have shown the
influence of sea surface temperature on metabolic processes such as
growth, feeding, reproduction, and influencing the range of species
distributions
\citep{kordas2011community, sanford2002feeding, pinsky2013marine}.
However, it is essential to note that temperature is not the only driver
of biological processes and temperature has interactive effects with
other abiotic drivers \citep{darling2008quantifying}. pH is also an
important abiotic driver that impacts the physiological performance of
marine organisms and influences the biogenic structures that organisms
create \citep{hofmann2010living}. pH plays a vital role in metabolic
processes due to its effect on biochemical pathways and internal
acid-base balance \citep{gaylord2015ocean}. For example, low pH is often
associated with elevated metabolic rates due to the increase in
energetic costs in creating calcified structures such as the formation
of shells in mollusks or the skeletons of corals and echinoderms
\citep{doney2009ocean, spalding2017energetic}. Due to differences in the
energetic costs associated with calcification, there are significant
differences in the ability to control acid-base regulation between
species \citep{doney2009ocean}. Consequently, changes in physicochemical
parameters of the environment affect species differently, impact the
interaction between species and, in turn, affect the structures of
ecological communities; therefore, studying how differences between
abiotic drivers affect organismal physiology will have ecosystem-level
implications \citep{tomanek2002physiological, barclay2019variation}.
~~~~~ Organisms are adapted to cope with a natural range of abiotic
conditions, yet anthropogenic climate change may outpace organismal
physiological capacities and may also act interactively to result in
``ecological surprises'\,' (sense, Paine et al., 1969). For example, the
cumulative impact of two drivers acting together may interact to be
equivalent to their sum, known as an additive effect, less than their
additive effect, which is known as an antagonistic interaction, or
greater than their additive effect, known as a synergistic interaction
(Côté et al., 2016). For decades anti-racist and feminist scholars have
provided critical insight into the ways in we must think about isolated
phenomena as intersectional due to their complex interactions (Davis,
1983; Crenshaw, 1989). The field of marine biology requires this
paradigm shift that embraces the interactions between stressors to grasp
the complexity of the future. Combined, these drastic changes in abiotic
drivers will continue to act in conjecture with one another and could
potentially ameliorate or exacerbate impacts on organismal physiological
processes and reverberate the effects of ecological change through
ecosystems (Kroeker, Kordas, \& Harley, 2017).
\newpage
~~~~~ As the atmospheric carbon dioxide (CO2) concentration continues to
surpass the limits of the earth system, marine organisms will be forced
to endure profound transformations of the environment, from shifts in
temperature to altered geochemistry (richardson2023earth,
portner2008physiology\}. Ocean warming (OW) and ocean acidification (OA)
represent two of the most significant changes occurring in marine
ecosystems across the globe, both driven by the unremitted rise of
anthropogenic-induced carbon dioxide emissions. OW and OA are not
isolated phenomena; they share a common origin, and in a rapidly
changing world, their combined impacts on organismal physiology
necessitate special attention as multiple drivers of change may act
interactively \citep{cote2016interactions}. Since the beginning of the
20th century, the global mean sea surface temperature (SST) has
increased by 0.88 {[}0.68--1.01{]}\(^\circ\)C, and is further projected
to warm by 2.89\(^\circ\)C {[}2.01--4.07\(^\circ\)C{]} at the end of the
century, which surpasses the thermal tolerance limits of many marine
species (following the representative concentration pathway 8.5 emission
scenario)
\citep{kikstra2022ipcc, fox2021ocean, bay2017genomic, somero2010physiology}.
Concurrently, the ocean has absorbed \textasciitilde30\% of
anthropogenic CO2 \citep{feely2004impact}, altering the carbonate
chemistry of seawater through a decrease in the concentration of
carbonate ions \(\mathrm{CO_3^{2-}}\) and a decline in seawater pH
\citep{feely2004impact}. Mean surface ocean pH values have declined by
0.1 units since the pre-industrial era, with a further projected
diminution of 0.1 - 0.4 units by the end of the century
\citep{change2014impacts, orr2005anthropogenic}, posing a unique threat
to calcifying marine organisms. Consequently, the impacts of OW and OA
will not be consistent across geographic regions, leading to
differential effects that will modify already variable spatial and
temporal environments. Building a mechanistic understanding of how the
combined impacts of ocean warming and acidification affect marine
organisms is integral for reliable projections of how climate change may
continue to affect marine organisms.
~~~~~ Coastal marine organisms frequently encounter a wide range of
temperatures and experience fluctuations in biogeochemistry, resulting
from temporal variations, such as tidal and seasonal cycles. The rocky
intertidal system is one such system that is known for its variable
conditions on both temporal and spatial scales, making them a model
ecosystem for understanding how organisms interact and respond to change
\citep{connell1961influence, paine1969pisaster, kwiatkowski2016nighttime, jellison2022low}.
Organisms within the rocky intertidal zone must contend with alternating
periods of immersion and emersion of tidal fluctuations, which commonly
lead to large variations in temperature, oxygen availability, and pH,
\citep{denny2001physical, helmuth2002climate}. Of these naturally
occurring changes, thermal variability within the intertidal zone is
believed to be a dominant driver in structuring the vertical and
latitudinal distribution patterns by limiting upper zonation through
abiotic stress and lower zonation through biotic influence
\citep{helmuth2006mosaic, somero2002thermal, somero2010physiology, connell1961influence}.
Daily temperature fluctuations are drastic enough to elevate the body
temperatures of marine organisms by more than 20\(^\circ\)C during a
tidal emersion event \citep{Helmuth1999thermal}. Furthermore, changes in
pH within tidepools may exceed 1 unit when nighttime respiration rates
exceed photosynthetic rates
\citep{jellison2016ocean, kwiatkowski2016nighttime}. Such highly
variable abiotic changes are naturally occurring and create complex
gradients that shape ecological communities and influence physiological
processes within individual organisms \citep{helmuth2006mosaic}. Given
that organisms within the intertidal zone simultaneously face drastic
fluctuations from abiotic drivers, and experience conditions far beyond
what is expected in the future, understanding organismal performance in
these ecosystems may provide a window for looking toward the future.
Intertidal organisms are well known for the ability to utilize anaerobic
metabolic responses (e.g., metabolic depression) to minimize metabolic
costs of dealing with thermal stress, making them an ideal model system
to understand the impacts of thermal stress on physiology (Pörtner et
al., 2017).
~~~~~ The role of biotic and abiotic drivers in influencing metabolic
processes has been of primary interest to the field of ecology as
changes in metabolism directly affect the survival, behavior, and energy
requirements of organisms, thereby impacting organism and ecosystem
function \citep{carey2016sea}. Physiological processes are heavily
influenced by environmental factors, and many marine organisms undergo
biological responses to natural diel variability present within
environments \citep{hofmann2010living}. Temperature is the primary
environmental driver regulating physiological rates of ectothermic
organisms, as kinetic energy of biochemical reactions are temperature
dependent
\citep{levins1968evolution, huey1979integrating, hochachka2002biochemical}.
Further, temperature is the key determinant in the regulating rates of
biological processes, ranging from metabolic rates
\citep{gillooly2001effects} to species interactions
\citep{sanford1999regulation}, such as growth, feeding, reproduction,
and determining the range of species distributions
\citep{kordas2011community, sanford2002feeding, pinsky2013marine}. The
physiological processes of metabolism are the total sum of biological
and chemical processes in converting energetic resources and materials
into biomass and activity \citep{brown2004metabolic}. Changes in pH also
play a vital role in metabolic processes due to its effect on
biochemical pathways and internal acid-base balance
\citep{gaylord2015ocean}. Specifically, declines in seawater carbonate
ions and pH attributed to OA are strongly correlated to decreases in
calcification and growth rates of many marine organisms
\citep{kroeker2013impacts}. Due to species-specific differences in the
energetic costs associated with calcification, there are significant
differences in the ability to control internal acid-base regulation
between species \citep{doney2009ocean}. Ultimately, changes in the
environment that lead to alterations in organismal energetic
requirements will scale up to affect the processes of ecological
communities; therefore, studying how multiple abiotic factors affect
organismal physiology has ecosystem-level implications
\citep{tomanek2002heat, barclay2019variation, kroeker2022ecological}.
\newpage
\hypertarget{thermal-performance-curves-as-a-tool-to-understand-multiple-drivers-of-change-on-organismal-physiology}{%
\subsection{Thermal Performance Curves as a Tool to Understand Multiple
Drivers of Change on Organismal
Physiology}\label{thermal-performance-curves-as-a-tool-to-understand-multiple-drivers-of-change-on-organismal-physiology}}
\begin{figure}[htbp]
\centering
\includegraphics[width=1\textwidth]{Images/thermal_performance_curve_schematic.png}
\caption{Figure 1. Thermal performance curve schematic illustrating the relationship between biological rates and temperature, including critical thermal maximum (CTMax), critical thermal minimum (CTMin), thermal optimum (Topt), activation energy (E), deactivation energy (Eh), and the thermal breadth of the curve (TBr). Hypothesized characteristics of a thermal performance curve exposed to ocean acidification, including reduced thermal optimum, reduced performance of maximum physiological rate, and reduced breathe of the curve.}
\label{fig:thermal-performance-curve-schematic}
\end{figure}
~~~~~ The use of performance curves can help to quantify the
relationship between abiotic drivers and physiological rates to forecast
future effects \cite{kroeker2017embracing} and can allow for comparative
assessments across different biological rates and environmental
conditions (Figure 1.)
\cite{schulte2011thermal, silbiger2019comparative, silva2021local, padfield2021rtpc, becker2020nutrient}.
Further, thermal performance curves have been suggested to fill in the
gap of uncertainty between multiple stressors as they empirically
characterize the relationship between biological performance rates
across a wide range of temperatures
\cite{padfield2021rtpc, schulte2011thermal, silbiger2019comparative}.
Thermal performance curves are a univariate function that describes how
some measure of performance (e.g., metabolic rate) varies with
temperature. As temperature increases so do the biochemical and
physiological rates until they reach a species-specific optimal
temperature. Beyond the optimum rate, further increases in temperature
denature proteins, stunt growth, and cause reductions in performance and
survival \cite{somero2002thermal, portner2002climate}. Thermal
performance curves are typically left-skewed and hump-shaped and include
several metrics, including but not limited to a thermal optimum
(TOpt)---the temperature at the highest rate of performance---and a
critical thermal minimum (CTMin) and a thermal maximum (CTMax)--- the
upper and lower thermal limit that an organism can tolerate
\cite{schulte2011thermal, huey1979integrating, huey1989evolution}. These
tolerance thresholds and the range they encompass are governed by an
organism's ability to respond to sub-lethal and lethal conditions
through an organismal-level response and molecular-level responses such
as anaerobic metabolism and heat shock response
\cite{portner2017oxygen, somero2002thermal}. Further, exposure to
concurrent drivers of ecological change, like OA, are expected to
constrict an organism's performance curve and thermal limits, such as
decreasing the breadth of thermal performance
\cite{portner2008physiology, portner2010oxygen}. Comparing physiological
responses to gradients of abiotic drivers may allow us to quantify and
compare the tolerance limits of organisms
\cite{silbiger2019comparative}.
~~~~~ Despite the increasing emphasis on multi-driver and multi-species
studies, a mechanistic understanding of the nonlinear responses of
multiple confounding stressors of future scenarios remains a knowledge
gap. (Kroeker, Kordas, \& Harley, 2017). The elevated sense of urgency
involved with these global threats contributes to the need for a more
nuanced understanding of the impact of multiple stressor interactions on
organismal and ecosystem processes (Côté et al., 2016). The response of
organisms to climate change, survival, and fitness depends on
physiological trade-offs, which are essentially changed within the
allocation of an organism's energy for different biological functions
and demands for resources. Considering that metabolic processes respond
differently to multiple environmental drivers and that physiological
systems within and between organisms differ, it is imperative to tease
apart the metabolic rates. Organisms may respond to changing abiotic
drivers by altering their energetic allocation or energetic intake, such
as altering consumption rates or growth (O'Connor 2009). For example,
the metabolic theory of ecology predicts an increase in consumption
rates with increasing temperature (O'Connor 2009). These alterations
within an individual species' physiological performance are significant
because they can scale up to affect ecosystem function (Post et al.,
1999). Building a mechanistic understanding regarding how the combined
impacts of ocean warming and acidification affect marine organisms is
integral for reliable projections of how climate change may continue to
affect marine organisms.
~~~~~ Specifically, we ask the question: how does exposure to decreased
pH influence thermal performance curves of respiration of an intertidal
gastropod, Tegula funebralis? We anticipate that the thermal optimum
(TOpt) for respiration rates will shift towards lower temperatures,
indicating a reduced ability to sustain optimal metabolic activity in
the face of ocean acidification. Additionally, we expect a decrease in
the thermal breadth of the curve (TBr), indicating a narrower range of
temperatures at which the gastropod can effectively maintain its
respiratory rates.
\end{document} |
import React from "react";
import Wrapper from "../assets/wrappers/SmallSidebar";
import { FaTimes } from "react-icons/fa";
import Logo from "./Logo";
import { useDispatch, useSelector } from "react-redux";
import { toggleSidebar } from "../features/user/userSlice";
import NavLinks from "./NavLinks";
const SmallSidebar = () => {
const dispatch = useDispatch();
const { isSidebarOpen } = useSelector((store) => store.user);
const handleToggleSidebar = () => {
dispatch(toggleSidebar());
};
return (
<Wrapper>
{isSidebarOpen && (
<div
className={
isSidebarOpen
? "sidebar-container show-sidebar"
: "sidebar-container"
}
>
<div className="content">
<button className="close-btn" onClick={handleToggleSidebar}>
<FaTimes />
</button>
<header>
<Logo></Logo>
</header>
<NavLinks handleToggleSidebar={handleToggleSidebar}></NavLinks>
</div>
</div>
)}
</Wrapper>
);
};
export default SmallSidebar; |
/***************************************************************************
qgsprocessingcontext.h
----------------------
begin : April 2017
copyright : (C) 2017 by Nyall Dawson
email : nyall dot dawson at gmail dot com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifndef QGSPROCESSINGCONTEXT_H
#define QGSPROCESSINGCONTEXT_H
#include "qgis_core.h"
#include "qgis.h"
#include "qgsproject.h"
#include "qgsexpressioncontext.h"
#include "qgsfeaturerequest.h"
#include "qgsexception.h"
#include "qgsprocessingfeedback.h"
#include "qgsprocessingutils.h"
#include <QThread>
#include <QPointer>
class QgsProcessingLayerPostProcessorInterface;
/**
* \class QgsProcessingContext
* \ingroup core
* \brief Contains information about the context in which a processing algorithm is executed.
*
* Contextual information includes settings such as the associated project, and
* expression context.
* \since QGIS 3.0
*/
class CORE_EXPORT QgsProcessingContext
{
public:
//! Flags that affect how processing algorithms are run
enum Flag
{
// UseSelectionIfPresent = 1 << 0,
};
Q_DECLARE_FLAGS( Flags, Flag )
/**
* Logging level for algorithms to use when pushing feedback messages.
*
* \since QGIS 3.20
*/
enum LogLevel
{
DefaultLevel = 0, //!< Default logging level
Verbose, //!< Verbose logging
};
/**
* Constructor for QgsProcessingContext.
*/
QgsProcessingContext();
//! QgsProcessingContext cannot be copied
QgsProcessingContext( const QgsProcessingContext &other ) = delete;
//! QgsProcessingContext cannot be copied
QgsProcessingContext &operator=( const QgsProcessingContext &other ) = delete;
~QgsProcessingContext();
/**
* Copies all settings which are safe for use across different threads from
* \a other to this context.
*/
void copyThreadSafeSettings( const QgsProcessingContext &other )
{
mFlags = other.mFlags;
mProject = other.mProject;
mTransformContext = other.mTransformContext;
mExpressionContext = other.mExpressionContext;
mInvalidGeometryCallback = other.mInvalidGeometryCallback;
mUseDefaultInvalidGeometryCallback = other.mUseDefaultInvalidGeometryCallback;
mInvalidGeometryCheck = other.mInvalidGeometryCheck;
mTransformErrorCallback = other.mTransformErrorCallback;
mDefaultEncoding = other.mDefaultEncoding;
mFeedback = other.mFeedback;
mPreferredVectorFormat = other.mPreferredVectorFormat;
mPreferredRasterFormat = other.mPreferredRasterFormat;
mEllipsoid = other.mEllipsoid;
mDistanceUnit = other.mDistanceUnit;
mAreaUnit = other.mAreaUnit;
mLogLevel = other.mLogLevel;
}
/**
* Returns any flags set in the context.
* \see setFlags()
*/
QgsProcessingContext::Flags flags() const { return mFlags; }
/**
* Sets \a flags for the context.
* \see flags()
*/
void setFlags( QgsProcessingContext::Flags flags ) { mFlags = flags; }
/**
* Returns the project in which the algorithm is being executed.
* \see setProject()
*/
QgsProject *project() const { return mProject; }
/**
* Sets the \a project in which the algorithm will be executed.
*
* This also automatically sets the transformContext(), ellipsoid(), distanceUnit() and
* areaUnit() to match the project's settings.
*
* \see project()
*/
void setProject( QgsProject *project )
{
mProject = project;
if ( mProject )
{
mTransformContext = mProject->transformContext();
if ( mEllipsoid.isEmpty() )
mEllipsoid = mProject->ellipsoid();
if ( mDistanceUnit == QgsUnitTypes::DistanceUnknownUnit )
mDistanceUnit = mProject->distanceUnits();
if ( mAreaUnit == QgsUnitTypes::AreaUnknownUnit )
mAreaUnit = mProject->areaUnits();
}
}
/**
* Returns the expression context.
*/
QgsExpressionContext &expressionContext() { return mExpressionContext; }
/**
* Returns the expression context.
*/
SIP_SKIP const QgsExpressionContext &expressionContext() const { return mExpressionContext; }
/**
* Sets the expression \a context.
*/
void setExpressionContext( const QgsExpressionContext &context ) { mExpressionContext = context; }
/**
* Returns the coordinate transform context.
* \see setTransformContext()
*/
QgsCoordinateTransformContext transformContext() const { return mTransformContext; }
/**
* Sets the coordinate transform \a context.
*
* Note that setting a project for the context will automatically set the coordinate transform
* context.
*
* \see transformContext()
*/
void setTransformContext( const QgsCoordinateTransformContext &context ) { mTransformContext = context; }
/**
* Returns the ellipsoid to use for distance and area calculations.
*
* \see setEllipsoid()
* \since QGIS 3.16
*/
QString ellipsoid() const;
/**
* Sets a specified \a ellipsoid to use for distance and area calculations.
*
* If not explicitly set, the ellipsoid will default to the project()'s ellipsoid setting.
*
* \see ellipsoid()
* \since QGIS 3.16
*/
void setEllipsoid( const QString &ellipsoid );
/**
* Returns the distance unit to use for distance calculations.
*
* \see setDistanceUnit()
* \see areaUnit()
* \since QGIS 3.16
*/
QgsUnitTypes::DistanceUnit distanceUnit() const;
/**
* Sets the \a unit to use for distance calculations.
*
* If not explicitly set, the unit will default to the project()'s distance unit setting.
*
* \see distanceUnit()
* \see setAreaUnit()
* \since QGIS 3.16
*/
void setDistanceUnit( QgsUnitTypes::DistanceUnit unit );
/**
* Returns the area unit to use for area calculations.
*
* \see setAreaUnit()
* \see distanceUnit()
* \since QGIS 3.16
*/
QgsUnitTypes::AreaUnit areaUnit() const;
/**
* Sets the \a unit to use for area calculations.
*
* If not explicitly set, the unit will default to the project()'s area unit setting.
*
* \see areaUnit()
* \see setDistanceUnit()
* \since QGIS 3.16
*/
void setAreaUnit( QgsUnitTypes::AreaUnit areaUnit );
/**
* Returns the current time range to use for temporal operations.
*
* \see setCurrentTimeRange()
* \since QGIS 3.18
*/
QgsDateTimeRange currentTimeRange() const;
/**
* Sets the \a current time range to use for temporal operations.
*
* \see currentTimeRange()
* \since QGIS 3.18
*/
void setCurrentTimeRange( const QgsDateTimeRange ¤tTimeRange );
/**
* Returns a reference to the layer store used for storing temporary layers during
* algorithm execution.
*/
QgsMapLayerStore *temporaryLayerStore() { return &tempLayerStore; }
/**
* \brief Details for layers to load into projects.
* \ingroup core
* \since QGIS 3.0
*/
class CORE_EXPORT LayerDetails
{
public:
/**
* Constructor for LayerDetails.
*/
LayerDetails( const QString &name, QgsProject *project, const QString &outputName = QString(), QgsProcessingUtils::LayerHint layerTypeHint = QgsProcessingUtils::LayerHint::UnknownType )
: name( name )
, outputName( outputName )
, layerTypeHint( layerTypeHint )
, project( project )
{}
//! Default constructor
LayerDetails() = default;
/**
* Friendly name for layer, possibly for use when loading layer into project.
*
* \warning Instead of directly using this value, prefer to call setOutputLayerName() to
* generate a layer name which respects the user's local Processing settings.
*/
QString name;
/**
* Set to TRUE if LayerDetails::name should always be used as the loaded layer name, regardless
* of the user's local Processing settings.
* \since QGIS 3.16
*/
bool forceName = false;
/**
* Associated output name from algorithm which generated the layer.
*/
QString outputName;
/**
* Layer type hint.
*
* \since QGIS 3.4
*/
QgsProcessingUtils::LayerHint layerTypeHint = QgsProcessingUtils::LayerHint::UnknownType;
/**
* Layer post-processor. May be NULLPTR if no post-processing is required.
* \see setPostProcessor()
* \since QGIS 3.2
*/
QgsProcessingLayerPostProcessorInterface *postProcessor() const;
/**
* Sets the layer post-processor. May be NULLPTR if no post-processing is required.
*
* Ownership of \a processor is transferred.
*
* \see postProcessor()
* \since QGIS 3.2
*/
void setPostProcessor( QgsProcessingLayerPostProcessorInterface *processor SIP_TRANSFER );
/**
* Sets a \a layer name to match this output, respecting any local user settings which affect this name.
*
* \since QGIS 3.10.1
*/
void setOutputLayerName( QgsMapLayer *layer ) const;
//! Destination project
QgsProject *project = nullptr;
private:
// Ideally a unique_ptr, but cannot be due to use within QMap. Is cleaned up by QgsProcessingContext.
QgsProcessingLayerPostProcessorInterface *mPostProcessor = nullptr;
};
/**
* Returns a map of layers (by ID or datasource) to LayerDetails, to load into the canvas upon completion of the algorithm or model.
* \see setLayersToLoadOnCompletion()
* \see addLayerToLoadOnCompletion()
* \see willLoadLayerOnCompletion()
* \see layerToLoadOnCompletionDetails()
*/
QMap< QString, QgsProcessingContext::LayerDetails > layersToLoadOnCompletion() const
{
return mLayersToLoadOnCompletion;
}
/**
* Returns TRUE if the given \a layer (by ID or datasource) will be loaded into the current project
* upon completion of the algorithm or model.
* \see layersToLoadOnCompletion()
* \see setLayersToLoadOnCompletion()
* \see addLayerToLoadOnCompletion()
* \see layerToLoadOnCompletionDetails()
* \since QGIS 3.2
*/
bool willLoadLayerOnCompletion( const QString &layer ) const
{
return mLayersToLoadOnCompletion.contains( layer );
}
/**
* Sets the map of \a layers (by ID or datasource) to LayerDetails, to load into the canvas upon completion of the algorithm or model.
* \see addLayerToLoadOnCompletion()
* \see layersToLoadOnCompletion()
* \see willLoadLayerOnCompletion()
* \see layerToLoadOnCompletionDetails()
*/
void setLayersToLoadOnCompletion( const QMap< QString, QgsProcessingContext::LayerDetails > &layers );
/**
* Adds a \a layer to load (by ID or datasource) into the canvas upon completion of the algorithm or model.
* The \a details parameter dictates the LayerDetails.
* \see setLayersToLoadOnCompletion()
* \see layersToLoadOnCompletion()
* \see willLoadLayerOnCompletion()
* \see layerToLoadOnCompletionDetails()
*/
void addLayerToLoadOnCompletion( const QString &layer, const QgsProcessingContext::LayerDetails &details );
/**
* Returns a reference to the details for a given \a layer which is loaded on completion of the
* algorithm or model.
*
* \warning First check willLoadLayerOnCompletion(), or calling this method will incorrectly
* add \a layer as a layer to load on completion.
*
* \see willLoadLayerOnCompletion()
* \see addLayerToLoadOnCompletion()
* \see setLayersToLoadOnCompletion()
* \see layersToLoadOnCompletion()
* \since QGIS 3.2
*/
QgsProcessingContext::LayerDetails &layerToLoadOnCompletionDetails( const QString &layer )
{
return mLayersToLoadOnCompletion[ layer ];
}
/**
* Returns the behavior used for checking invalid geometries in input layers.
* \see setInvalidGeometryCheck()
*/
QgsFeatureRequest::InvalidGeometryCheck invalidGeometryCheck() const { return mInvalidGeometryCheck; }
/**
* Sets the behavior used for checking invalid geometries in input layers.
* Settings this to anything but QgsFeatureRequest::GeometryNoCheck will also
* reset the invalidGeometryCallback() to a default implementation.
* \see invalidGeometryCheck()
*/
void setInvalidGeometryCheck( QgsFeatureRequest::InvalidGeometryCheck check );
/**
* Sets a callback function to use when encountering an invalid geometry and
* invalidGeometryCheck() is set to GeometryAbortOnInvalid. This function will be
* called using the feature with invalid geometry as a parameter.
* \see invalidGeometryCallback()
* \since QGIS 3.0
*/
#ifndef SIP_RUN
void setInvalidGeometryCallback( const std::function< void( const QgsFeature & ) > &callback ) { mInvalidGeometryCallback = callback; mUseDefaultInvalidGeometryCallback = false; }
#else
void setInvalidGeometryCallback( SIP_PYCALLABLE / AllowNone / );
% MethodCode
Py_BEGIN_ALLOW_THREADS
sipCpp->setInvalidGeometryCallback( [a0]( const QgsFeature &arg )
{
SIP_BLOCK_THREADS
Py_XDECREF( sipCallMethod( NULL, a0, "D", &arg, sipType_QgsFeature, NULL ) );
SIP_UNBLOCK_THREADS
} );
Py_END_ALLOW_THREADS
% End
#endif
/**
* Returns the callback function to use when encountering an invalid geometry and
* invalidGeometryCheck() is set to GeometryAbortOnInvalid.
* \note not available in Python bindings
* \see setInvalidGeometryCallback()
* \since QGIS 3.0
*/
SIP_SKIP std::function< void( const QgsFeature & ) > invalidGeometryCallback( QgsFeatureSource *source = nullptr ) const;
/**
* Returns the default callback function to use for a particular invalid geometry \a check
* \note not available in Python bindings
* \since QGIS 3.14
*/
SIP_SKIP std::function< void( const QgsFeature & ) > defaultInvalidGeometryCallbackForCheck( QgsFeatureRequest::InvalidGeometryCheck check, QgsFeatureSource *source = nullptr ) const;
/**
* Sets a callback function to use when encountering a transform error when iterating
* features. This function will be
* called using the feature which encountered the transform error as a parameter.
* \see transformErrorCallback()
* \since QGIS 3.0
*/
#ifndef SIP_RUN
void setTransformErrorCallback( const std::function< void( const QgsFeature & ) > &callback ) { mTransformErrorCallback = callback; }
#else
void setTransformErrorCallback( SIP_PYCALLABLE / AllowNone / );
% MethodCode
Py_BEGIN_ALLOW_THREADS
sipCpp->setTransformErrorCallback( [a0]( const QgsFeature &arg )
{
SIP_BLOCK_THREADS
Py_XDECREF( sipCallMethod( NULL, a0, "D", &arg, sipType_QgsFeature, NULL ) );
SIP_UNBLOCK_THREADS
} );
Py_END_ALLOW_THREADS
% End
#endif
/**
* Returns the callback function to use when encountering a transform error when iterating
* features.
* \note not available in Python bindings
* \see setTransformErrorCallback()
* \since QGIS 3.0
*/
std::function< void( const QgsFeature & ) > transformErrorCallback() const { return mTransformErrorCallback; } SIP_SKIP
/**
* Returns the default encoding to use for newly created files.
* \see setDefaultEncoding()
*/
QString defaultEncoding() const { return mDefaultEncoding; }
/**
* Sets the default \a encoding to use for newly created files.
* \see defaultEncoding()
*/
void setDefaultEncoding( const QString &encoding ) { mDefaultEncoding = encoding; }
/**
* Returns the associated feedback object.
* \see setFeedback()
*/
QgsProcessingFeedback *feedback() { return mFeedback; }
/**
* Sets an associated \a feedback object. This allows context related functions
* to report feedback and errors to users and processing logs. While ideally this feedback
* object should outlive the context, only a weak pointer to \a feedback is stored
* and no errors will occur if feedback is deleted before the context.
* Ownership of \a feedback is not transferred.
* \see setFeedback()
*/
void setFeedback( QgsProcessingFeedback *feedback ) { mFeedback = feedback; }
/**
* Returns the thread in which the context lives.
* \see pushToThread()
*/
QThread *thread() { return tempLayerStore.thread(); }
/**
* Pushes the thread affinity for the context (including all layers contained in the temporaryLayerStore()) into
* another \a thread. This method is only safe to call when the current thread matches the existing thread
* affinity for the context (see thread()).
* \see thread()
*/
void pushToThread( QThread *thread )
{
// cppcheck-suppress assertWithSideEffect
Q_ASSERT_X( QThread::currentThread() == QgsProcessingContext::thread(), "QgsProcessingContext::pushToThread", "Cannot push context to another thread unless the current thread matches the existing context thread affinity" );
tempLayerStore.moveToThread( thread );
}
/**
* Takes the results from another \a context and merges them with the results currently
* stored in this context. This includes settings like any layers loaded in the temporaryLayerStore()
* and layersToLoadOnCompletion().
* This is only safe to call when both this context and the other \a context share the same
* thread() affinity, and that thread is the current thread.
*/
void takeResultsFrom( QgsProcessingContext &context );
/**
* Returns a map layer from the context with a matching \a identifier.
* This method considers layer IDs, names and sources when matching
* the \a identifier (see QgsProcessingUtils::mapLayerFromString()
* for details).
*
* Ownership is not transferred and remains with the context.
*
* \see takeResultLayer()
*/
QgsMapLayer *getMapLayer( const QString &identifier );
/**
* Takes the result map layer with matching \a id from the context and
* transfers ownership of it back to the caller. This method can be used
* to remove temporary layers which are not required for further processing
* from a context.
*
* \see getMapLayer()
*/
QgsMapLayer *takeResultLayer( const QString &id ) SIP_TRANSFERBACK;
/**
* Returns the preferred vector format to use for vector outputs.
*
* This method returns a file extension to use when creating vector outputs (e.g. "shp"). Generally,
* it is preferable to use the extension associated with a particular parameter, which can be retrieved through
* QgsProcessingDestinationParameter::defaultFileExtension(). However, in some cases, a specific parameter
* may not be available to call this method on (e.g. for an algorithm which has only an output folder parameter
* and which creates multiple output layers in that folder). In this case, the format returned by this
* function should be used when creating these outputs.
*
* It is the algorithm's responsibility to check whether the returned format is acceptable for the algorithm,
* and to provide an appropriate fallback when the returned format is not usable.
*
* \see setPreferredVectorFormat()
* \see preferredRasterFormat()
*
* \since QGIS 3.10
*/
QString preferredVectorFormat() const { return mPreferredVectorFormat; }
/**
* Sets the preferred vector \a format to use for vector outputs.
*
* This method sets a file extension to use when creating vector outputs (e.g. "shp"). Generally,
* it is preferable to use the extension associated with a particular parameter, which can be retrieved through
* QgsProcessingDestinationParameter::defaultFileExtension(). However, in some cases, a specific parameter
* may not be available to call this method on (e.g. for an algorithm which has only an output folder parameter
* and which creates multiple output layers in that folder). In this case, the format set by this
* function will be used when creating these outputs.
*
* \see preferredVectorFormat()
* \see setPreferredRasterFormat()
*
* \since QGIS 3.10
*/
void setPreferredVectorFormat( const QString &format ) { mPreferredVectorFormat = format; }
/**
* Returns the preferred raster format to use for vector outputs.
*
* This method returns a file extension to use when creating raster outputs (e.g. "tif"). Generally,
* it is preferable to use the extension associated with a particular parameter, which can be retrieved through
* QgsProcessingDestinationParameter::defaultFileExtension(). However, in some cases, a specific parameter
* may not be available to call this method on (e.g. for an algorithm which has only an output folder parameter
* and which creates multiple output layers in that folder). In this case, the format returned by this
* function should be used when creating these outputs.
*
* It is the algorithm's responsibility to check whether the returned format is acceptable for the algorithm,
* and to provide an appropriate fallback when the returned format is not usable.
*
* \see setPreferredRasterFormat()
* \see preferredVectorFormat()
*
* \since QGIS 3.10
*/
QString preferredRasterFormat() const { return mPreferredRasterFormat; }
/**
* Sets the preferred raster \a format to use for vector outputs.
*
* This method sets a file extension to use when creating raster outputs (e.g. "tif"). Generally,
* it is preferable to use the extension associated with a particular parameter, which can be retrieved through
* QgsProcessingDestinationParameter::defaultFileExtension(). However, in some cases, a specific parameter
* may not be available to call this method on (e.g. for an algorithm which has only an output folder parameter
* and which creates multiple output layers in that folder). In this case, the format set by this
* function will be used when creating these outputs.
*
* \see preferredRasterFormat()
* \see setPreferredVectorFormat()
*
* \since QGIS 3.10
*/
void setPreferredRasterFormat( const QString &format ) { mPreferredRasterFormat = format; }
/**
* Returns the logging level for algorithms to use when pushing feedback messages to users.
*
* \see setLogLevel()
* \since QGIS 3.20
*/
LogLevel logLevel() const;
/**
* Sets the logging \a level for algorithms to use when pushing feedback messages to users.
*
* \see logLevel()
* \since QGIS 3.20
*/
void setLogLevel( LogLevel level );
private:
QgsProcessingContext::Flags mFlags = QgsProcessingContext::Flags();
QPointer< QgsProject > mProject;
QgsCoordinateTransformContext mTransformContext;
QString mEllipsoid;
QgsUnitTypes::DistanceUnit mDistanceUnit = QgsUnitTypes::DistanceUnknownUnit;
QgsUnitTypes::AreaUnit mAreaUnit = QgsUnitTypes::AreaUnknownUnit;
QgsDateTimeRange mCurrentTimeRange;
//! Temporary project owned by the context, used for storing temporarily loaded map layers
QgsMapLayerStore tempLayerStore;
QgsExpressionContext mExpressionContext;
QgsFeatureRequest::InvalidGeometryCheck mInvalidGeometryCheck = QgsFeatureRequest::GeometryNoCheck;
bool mUseDefaultInvalidGeometryCallback = true;
std::function< void( const QgsFeature & ) > mInvalidGeometryCallback;
std::function< void( const QgsFeature & ) > mTransformErrorCallback;
QString mDefaultEncoding;
QMap< QString, LayerDetails > mLayersToLoadOnCompletion;
QPointer< QgsProcessingFeedback > mFeedback;
QString mPreferredVectorFormat;
QString mPreferredRasterFormat;
LogLevel mLogLevel = DefaultLevel;
#ifdef SIP_RUN
QgsProcessingContext( const QgsProcessingContext &other );
#endif
};
Q_DECLARE_OPERATORS_FOR_FLAGS( QgsProcessingContext::Flags )
/**
* \brief An interface for layer post-processing handlers for execution following a processing algorithm operation.
*
* Note that post-processing of a layer will ONLY occur if that layer is set to be loaded into a QGIS project
* on algorithm completion. See QgsProcessingContext::layersToLoadOnCompletion().
*
* Algorithms that wish to set post-processing steps for generated layers should implement this interface
* in a separate class (NOT the algorithm class itself!).
*
* \ingroup core
* \since QGIS 3.2
*/
class CORE_EXPORT QgsProcessingLayerPostProcessorInterface
{
public:
virtual ~QgsProcessingLayerPostProcessorInterface() = default;
/**
* Post-processes the specified \a layer, following successful execution of a processing algorithm. This method
* always runs in the main thread and can be used to setup renderers, editor widgets, metadata, etc for
* the given layer.
*
* Post-processing classes can utilize settings from the algorithm's \a context and report logging messages
* or errors via the given \a feedback object.
*
* In the case of an algorithm run as part of a larger model, the post-processing occurs following the completed
* execution of the entire model.
*
* Note that post-processing of a layer will ONLY occur if that layer is set to be loaded into a QGIS project
* on algorithm completion. See QgsProcessingContext::layersToLoadOnCompletion().
*/
virtual void postProcessLayer( QgsMapLayer *layer, QgsProcessingContext &context, QgsProcessingFeedback *feedback ) = 0;
};
#endif // QGSPROCESSINGPARAMETERS_H |
import { DefaultObject } from './DefaultObject'
import { DefaultTuple } from './DefaultTuple'
import { DefaultValue } from './DefaultValue'
/**
* Default a value or collection by another value or collection. Meaning that if
* the first value is undefined or null, the second value will be used instead.
*
* You can also apply defaults to nested objects by setting the `N` template to
* a positive number.
*
* @template T The value or collection to default
* @template U The value or collection to default with
* @template N The depth to apply the defaults
* @returns The defaulted value or collection
* @example Default<number | undefined, string> // number | string
*/
export type Default<T, U, N extends number = 0> =
T extends unknown[] ? U extends unknown[]
? DefaultTuple<T, U, N>
: DefaultValue<T, U>
// --- Default objects.
: T extends object ? U extends object
? DefaultObject<T, U, N>
: DefaultValue<T, U>
// --- Default primitives.
: DefaultValue<T, U>
/** c8 ignore next */
if (import.meta.vitest) {
it('should default objects', () => {
type Result = Default<{ a: number; b: string | undefined }, { a: number; b: string }>
expectTypeOf<Result>().toEqualTypeOf<{ a: number; b: string }>()
})
it('should default tuples', () => {
type Result = Default<[number, string | undefined], [number, string]>
expectTypeOf<Result>().toEqualTypeOf<[number, string]>()
})
it('should default arrays', () => {
type Result = Default<(number | undefined)[], string[]>
expectTypeOf<Result>().toEqualTypeOf<(number | string)[]>()
})
it('should default primitives', () => {
type Result = Default<number | undefined, string>
expectTypeOf<Result>().toEqualTypeOf<number | string>()
})
it('should default non matching types from left to right', () => {
type Result = Default<number | undefined, string[]>
expectTypeOf<Result>().toEqualTypeOf<number | string[]>()
})
} |
const cityName = document.getElementById("city-name");
const btnTag = document.getElementById("weather");
const locationBtnTag = document.getElementById("get-location");
async function getWeatherDataFromCity(cityNameTag) {
try {
const city = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${cityNameTag}&units=metric&appid=da2a364bd4ecf1f22effba1f91a381d9`
);
const cityData = await city.json();
//console.log(cityData);
return cityData;
} catch {
console.error();
}
}
btnTag.addEventListener("click", async (e) => {
e.preventDefault();
try {
const geoCityLocation = await getWeatherDataFromCity(cityName.value);
//console.log(geoCityLocation);
const result = await getWeatherInfo(
geoCityLocation.coord.lat,
geoCityLocation.coord.lon
);
console.log(result);
displayWeatherResult(result);
localStorage.setItem(`${result.name}`, result.name);
} catch (err) {
//error.innerText = "Please enter a valid city Name";
console.log("its this error " + err);
}
});
const getWeatherInfo = async (lat, lon) => {
try {
const weather = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=da2a364bd4ecf1f22effba1f91a381d9&units=metric`
);
const data = await weather.json();
return data;
} catch {
console.log("error1");
}
};
const getCurrentLocationWeather = async (position) => {
try {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const result = await getWeatherInfo(latitude, longitude);
console.log(result);
displayWeatherResult(result);
} catch {
console.log("error2");
}
};
locationBtnTag.addEventListener("click", () => {
navigator.geolocation.getCurrentPosition(getCurrentLocationWeather);
});
const displayWeatherResult = (data) => {
console.log(data);
const cityName = document.getElementById("city");
const icon = document.getElementById("icon");
const tempreture = document.getElementById("tempreture");
const description = document.getElementById("description");
const windSpeed = document.getElementById("wind-speed");
const cloudiness = document.getElementById("cloud");
const feelsLike = document.getElementById("feels-like");
const sunrise = document.getElementById("sunrise");
const sunset = document.getElementById("sunset");
cityName.innerText = data.name;
icon.src = `https://openweathermap.org/img/wn/${data.weather[0].icon}.png`;
icon.alt = `${data.weather[0].description}`;
tempreture.innerText = `${data.main.temp.toFixed(0)}°C`;
//description.innerText = data.weather[0].description;
windSpeed.innerText = `Wind speed: ${data.wind.speed} m/s`;
feelsLike.innerText = `Feels Like: ${data.main.feels_like.toFixed(0)} °C`;
cloudiness.innerText = `Cloudiness: ${data.clouds.all}%`;
sunrise.innerText = `Sunrise: ${new Date(
data.sys.sunrise * 1000
).toLocaleTimeString("en-US", {
hour: "2-digit",
minute: "2-digit",
})}`;
sunset.innerText = `Sunset: ${new Date(
data.sys.sunset * 1000
).toLocaleTimeString("en-US", {
hour: "2-digit",
minute: "2-digit",
})}`;
}; |
import { useState } from 'react';
import { dbService } from '../../../FirebaseModules';
import { doc, deleteDoc } from 'firebase/firestore';
import Modal from '../../../style/Modal';
import Buttons from '../../../style/Buttons';
import DeleteButton from '../../../style/DeleteButton';
import CancelButton from '../../../style/CancelButton';
import QuestionType from '../../../style/QuestionType';
import { Editor } from '@tinymce/tinymce-react';
import { toast } from 'react-toastify';
import styles from './QuestionContainer.module.css';
export default function QuestionContainer({
userCode,
testCode,
questionObject,
index,
setIsEditingQuestion,
setQuestionIndex,
}: {
userCode: string | undefined;
testCode: string | undefined;
questionObject: any;
index: number;
setIsEditingQuestion: any;
setQuestionIndex: any;
}) {
const [isDeletingQuestion, setIsDeletingQuestion] = useState<boolean>(false);
const [showQuestion, setShowQuestion] = useState<boolean>(false);
async function deleteQuestion(userCode: string, testCode: string, questionCode: string) {
if (userCode && testCode && questionCode) {
try {
await deleteDoc(doc(dbService, 'users', userCode, 'tests', testCode, 'questions', questionCode));
toast.success('문제를 삭제했습니다.', { toastId: '' });
} catch (error) {
console.log(error);
toast.error('문제 삭제에 실패했습니다.', { toastId: '' });
}
} else {
toast.error('문제 삭제에 실패했습니다.', { toastId: '' });
}
setIsDeletingQuestion(false);
setShowQuestion(false);
}
return (
<div className={styles.container}>
<div className={styles.info} onClick={() => setShowQuestion((prev) => !prev)}>
<div className={styles.infoNumber}>{index + 1}</div>
<div className={styles.infoValue} style={{ justifySelf: 'left', fontWeight: 500 }}>
{questionObject.name}
</div>
<QuestionType type={questionObject.type} />
<div className={styles.infoValue}>{questionObject.points}점</div>
<div className={styles.infoValue}>
{(() => {
switch (questionObject.grading) {
case 0:
return questionObject.type === 'essay' ? '직접 채점' : '정답 시 만점';
case 1:
return '오답 시 감점';
case 2:
return '응답 시 만점';
}
})()}
</div>
<img
src={process.env.PUBLIC_URL + '/icons/apply/arrow_up.svg'}
className={showQuestion ? styles.arrowShow : styles.arrowHide}
/>
</div>
<div className={showQuestion ? styles.showQuestion : styles.hideQuestion}>
<div className={styles.label}>지문</div>
<div className={styles.passage}>
<Editor
apiKey={process.env.REACT_APP_TINYMCE_EDITOR_ID}
disabled={true}
value={questionObject.question}
init={{
readonly: true,
menubar: false,
toolbar: false,
statusbar: false,
plugins: ['autoresize', 'codesample'],
content_style: `
@import url('https://cdn.jsdelivr.net/gh/orioncactus/pretendard/dist/web/static/pretendard.css');
body {
font-family:'Pretendard';
font-weight: 500;
margin: 0px;
padding: 0px;
word-break: keep-all;
}
`,
}}
/>
</div>
{questionObject.type !== 'essay' && <div className={styles.label}>정답</div>}
{questionObject.type === 'mc' && (
<div className={styles.choiceContainer}>
{questionObject.choices.map((elem: any, index: number) => (
<div className={styles.choiceElements}>
<div
className={questionObject.answer[index] ? styles.choiceNumberCorrect : styles.choiceNumberIncorrect}
>
{index + 1}
</div>
<div className={questionObject.answer[index] ? styles.choiceValueCorrect : styles.choiceValueIncorrect}>
{elem}
</div>
</div>
))}
</div>
)}
{questionObject.type === 'sa' && <div className={styles.choiceValueCorrect}>{questionObject.answer}</div>}
{questionObject.type === 'tf' && (
<div className={styles.answer}>
{questionObject.answer ? (
<div className={styles.choiceElements}>
<div className={styles.choiceNumberTrue}>
<img src={process.env.PUBLIC_URL + '/icons/dashboard/correct.svg'} />
</div>
<div className={styles.choiceValueTrue}>참</div>
</div>
) : (
<div className={styles.choiceElements}>
<div className={styles.choiceNumberFalse}>
<img src={process.env.PUBLIC_URL + '/icons/dashboard/wrong.svg'} />
</div>
<div className={styles.choiceValueFalse}>거짓</div>
</div>
)}
</div>
)}
<Buttons position={'left'} gap={30} style={{ marginTop: '30px', marginBottom: '30px' }}>
<div
className={styles.button}
onClick={() => {
if (userCode && testCode && questionObject) {
setIsEditingQuestion(true);
setQuestionIndex(index);
}
}}
>
<img className={styles.buttonIcon} src={process.env.PUBLIC_URL + '/icons/dashboard/edit.svg'} />
수정
</div>
<div className={styles.button} onClick={() => setIsDeletingQuestion(true)}>
<img className={styles.buttonIcon} src={process.env.PUBLIC_URL + '/icons/dashboard/delete.svg'} />
삭제
</div>
</Buttons>
</div>
{isDeletingQuestion && (
<Modal title="문제 삭제" onClose={() => setIsDeletingQuestion(false)}>
<div>해당 문제를 삭제하시겠습니까?</div>
<br />
<br />
<Buttons>
<DeleteButton
text="삭제"
onClick={() => {
if (userCode && testCode && questionObject) {
deleteQuestion(userCode, testCode, questionObject.questionCode);
}
}}
/>
<CancelButton text="취소" onClick={() => setIsDeletingQuestion(false)} />
</Buttons>
</Modal>
)}
</div>
);
} |
import { fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import { TaskContext } from "../TaskContext";
import TaskForm from "./TaskForm";
describe("TaskForm", () => {
it("submits form data", () => {
const addTaskMock = jest.fn();
const contextValue = { addTask: addTaskMock };
render(
<TaskContext.Provider value={contextValue}>
<TaskForm />
</TaskContext.Provider>
);
const titleInput = screen.getByLabelText("Title");
const descriptionInput = screen.getByLabelText("Description");
const addButton = screen.getByText("Add Task");
fireEvent.change(titleInput, { target: { value: "Test Title" } });
fireEvent.change(descriptionInput, {
target: { value: "Test Description" },
});
fireEvent.click(addButton);
expect(addTaskMock).toHaveBeenCalledWith({
title: "Test Title",
description: "Test Description",
completed: false,
});
});
}); |
/**
* Forward declaration of guess API.
* @param num your guess
* @return -1 if num is lower than the guess number
* 1 if num is higher than the guess number
* otherwise return 0
* int guess(int num);
*/
class Solution {
public:
int guessNumber(int n) {
int l=1,u=n;
while(l<=u)
{
int mid=l+(u-l)/2;
int x=guess(mid);
if(x==0)
return mid;
else if(x==1)
l=mid+1;
else
u=mid-1;
}
return -1;
}
}; |
/** @jsxImportSource @emotion/react */
import "twin.macro";
import { isEmpty, isNil } from "lodash";
import { ProductItem } from "models/utils.model";
import React from "react";
import { useEffect } from "react";
import { useState } from "react";
import { useSearchParam } from "react-use";
import { getHistoryPayment } from "services/payment.service";
import { PaymentItem } from "components/Payment/PaymentItem";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "app/reducer/reducer";
import Loader from "components/Loader/Loader";
import { toggleLoading } from "app/slices/toggle.slice";
import { sleepAsync } from "utils/utils";
import { ReactComponent as Nodata } from "asset/images/no-data.svg";
import { useHistory } from "react-router-dom";
export const History = () => {
const [name, setName] = useState("");
const [detail, setDetail] = useState<ProductItem[]>([]);
const phone = useSearchParam("phone");
const toggle = useSelector((state: RootState) => state.toggle);
const history = useHistory();
const dispatch = useDispatch();
useEffect(() => {
(async () => {
if (isNil(phone)) return;
const res = await getHistoryPayment({ sdt: phone });
const { data } = res;
setDetail(data?.chiTiet);
setName(data?.chiTiet[0]?.hoTen);
await fakeSleep(1000);
if (isEmpty(data?.chiTiet[0]?.hoTen)) {
await sleepAsync(3000);
history.push("/search");
await fakeSleep(1000);
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const fakeSleep = async (milisecond: number) => {
dispatch(toggleLoading(true));
await sleepAsync(milisecond);
dispatch(toggleLoading(false));
};
return (
<div tw="mt-16 mb-10 ml-auto mr-auto width[70%]">
{toggle.isLoading && (
<div className="loader__component">
<Loader />
</div>
)}
<h1 tw="text-xl text-style-purple-1 font-bold mb-5 w-1/2 mx-auto text-center">
Lịch sử mua hàng
</h1>
{name && (
<div tw="w-1/2 m-auto p-3">
<div tw="mb-3">
Chào anh{" "}
<span tw="font-semibold">
{name + " "}-{" " + phone}
</span>
</div>
</div>
)}
{isEmpty(name) && (
<div tw="flex flex-col items-center m-auto p-3 text-center">
<span tw="text-2xl font-medium">
Bạn chưa từng mua hàng ở cửa hàng chúng tôi
</span>
<Nodata width={480} height={480} />
</div>
)}
{detail.map((item, index) => {
return <PaymentItem isHistoryPage item={item} index={index} />;
})}
</div>
);
}; |
import { PipeTransform, Pipe } from '@angular/core';
import {IBill} from './bill';
@Pipe({
name: 'billTitleFilter'
})
export class BillTitleFilterPipe implements PipeTransform {
transform(value: IBill[], filter: string): IBill[] {
filter = filter ? filter.toLocaleLowerCase() : null;
return filter ? value.filter((bill: IBill) =>
bill.billTitle.toLocaleLowerCase().indexOf(filter) !== -1) : value;
}
} |
import React, { useState, useEffect } from "react";
import {
Card,
Form,
Input,
DatePicker,
Select,
Space,
List,
Button,
Typography,
} from "antd";
import {
DeleteOutlined,
EditOutlined,
CloseOutlined,
PlusOutlined,
} from "@ant-design/icons";
import moment from "moment";
import { FormControl, FormLabel, Box } from '@chakra-ui/react';
const { Title, Text } = Typography;
const { Option } = Select;
const AddTransactions = ({
bookingId,
authToken,
onTransactionsUpdated,
}) => {
const [windowWidth, setWindowWidth] = useState(window.innerWidth);
const [showForm, setShowForm] = useState(false);
const [editMode, setEditMode] = useState(false);
const [transactions, setTransactions] = useState(null);
const [selectedTransaction, setSelectedTransaction] = useState(null);
const [form] = Form.useForm();
const today = new Date().toISOString().split("T")[0];
const fetchTransactions = async () => {
try {
const response = await fetch(
`http://ec2-54-211-23-206.compute-1.amazonaws.com:8081/billing/getAllTransactions?bookingId=${bookingId}`,
{
headers: {
'Authorization': `Bearer ${authToken}`
}
}
);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
setTransactions(data);
onTransactionsUpdated(data);
} catch (error) {
console.error("Error fetching transactions:", error);
}
};
useEffect(() => {
if (bookingId) {
fetchTransactions();
}
}, [bookingId]);
useEffect(() => {
if (selectedTransaction) {
const transformedTransaction = {
...selectedTransaction,
date: moment(selectedTransaction.date),
};
form.setFieldsValue(transformedTransaction);
}
}, [selectedTransaction, form]);
useEffect(() => {
const handleResize = () => setWindowWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
// const handleAddTransactionClick = () => {
// form.setFieldsValue({ method: "online" });
// setShowForm(true);
// setEditMode(false);
// setSelectedTransaction(null);
// form.resetFields();
// };
const updateTransaction = async () => {
const values = form.getFieldsValue();
const payload = {
amountPaid: values.amountPaid,
paymentMode: values.paymentMode,
bookingId: bookingId,
date: values.date.format("YYYY-MM-DD"),
};
try {
const response = await fetch(
"http://ec2-54-211-23-206.compute-1.amazonaws.com:8081/billing/getAllTransactions/update",
{
method: "PUT",
headers: {
"Content-Type": "application/json",
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(payload),
}
);
fetchTransactions();
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
console.log("Transaction updated successfully");
} catch (error) {
fetchTransactions();
console.error("Error updating transaction:", error);
}
};
const handleAddTransactionClick = () => {
setShowForm(true);
setEditMode(false);
setSelectedTransaction(null);
form.resetFields();
form.setFieldsValue({
paymentMode: "online",
date: moment(), // Set the default date to the current date
});
};
const handleEditTransactionClick = (transaction) => {
setShowForm(true);
setEditMode(true);
// setSelectedTransaction(transaction);
// setSelectedTransaction({ ...transaction, transactionId: transaction.id });
setSelectedTransaction({ ...transaction });
};
const handleCancelClick = () => {
setShowForm(false);
setEditMode(false);
setSelectedTransaction(null);
form.resetFields();
};
const saveTransaction = () => {
form
.validateFields()
.then(async (values) => {
const formattedValues = {
...values,
date: moment(values.date).format("YYYY-MM-DD"),
};
console.log("Form Data:", formattedValues);
console.log(bookingId);
const payload = {
bookingId: bookingId,
...formattedValues,
};
console.log("payload", payload);
try {
const response = await fetch(
"http://ec2-54-211-23-206.compute-1.amazonaws.com:8081/transaction/create",
{
method: "PUT",
headers: {
"Content-Type": "application/json",
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(payload),
}
);
fetchTransactions();
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log("Response from API:", result);
} catch (error) {
console.error("Error making API call:", error);
}
if (editMode) {
const updatedTransactions = transactions.map((transaction) =>
transaction.id === selectedTransaction.id
? { ...transaction, ...formattedValues }
: transaction
);
setTransactions(updatedTransactions);
} else {
setTransactions([
...transactions,
{ ...formattedValues, id: transactions.length + 1 },
]);
}
form.resetFields();
setShowForm(false);
setEditMode(false);
setSelectedTransaction(null);
})
.catch((info) => {
console.log("Validate Failed:", info);
});
};
// const deleteTransaction = async (id) => {
// try {
// // const response = await fetch(
// // `http://ec2-54-211-23-206.compute-1.amazonaws.com:8081/transaction/delete?transactionId=${id}&bookingId=${bookingId}`,
// // {
// // method: "DELETE",
// // }
// // );
// // if (!response.ok) {
// // throw new Error(`HTTP error! Status: ${response.status}`);
// // }
// console.log("Transaction deleted successfully");
// console.log("Booking ID:", bookingId);
// console.log("Transaction ID:", id);
// const updatedTransactions = transactions.filter(
// (transaction) => transaction.id !== id
// );
// setTransactions(updatedTransactions);
// } catch (error) {
// console.error("Error deleting transaction:", error);
// }
// };
const deleteTransaction = async (transactionId) => {
console.log(
"Deleting transaction with Booking ID:",
bookingId,
"and Transaction ID:",
transactionId
);
try {
const response = await fetch(
`http://ec2-54-211-23-206.compute-1.amazonaws.com:8081/transaction/delete?transactionId=${transactionId}&bookingId=${bookingId}`,
{
method: "DELETE",
headers: {
'Authorization': `Bearer ${authToken}`
}
}
);
fetchTransactions();
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
console.log("Transaction deleted successfully");
const updatedTransactions = transactions.filter(
(transaction) => transaction.id !== transactionId
);
setTransactions(updatedTransactions);
} catch (error) {
console.error("Error deleting transaction:", error);
}
};
const logTransactionDetails = async (transactionId, formattedValues) => {
console.log(formattedValues);
console.log(transactionId);
if (transactionId) {
const transactionDetails = {
amountPaid: formattedValues.amountPaid,
paymentMode: formattedValues.paymentMode,
bookingId: bookingId,
date: formattedValues.date,
};
console.log("Transaction Details for Updating:");
console.log(transactionDetails);
try {
const response = await fetch(
`http://ec2-54-211-23-206.compute-1.amazonaws.com:8081/transaction/edit?bookingId=${bookingId}&transactionId=${transactionId.transactionId}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(transactionDetails),
}
);
form.resetFields();
setShowForm(false);
setEditMode(false);
setSelectedTransaction(null);
fetchTransactions();
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const result = await response.json();
console.log("Response from API:", result);
} catch (error) {
console.error("Error updating transaction:", error);
}
} else {
console.log("Transaction not found for ID:", transactionId);
}
};
const responsiveStyle = {
...styles.transactionCard,
width: windowWidth < 768 ? "100%" : "90%",
margin: windowWidth < 480 ? "10px 0" : "20px auto",
};
return (
<Card style={styles.transactionCard}>
<div style={styles.headerContainer}>
<Title level={4} style={styles.headerTitle}>
Transactions
</Title>
<Button style={styles.addButton} onClick={handleAddTransactionClick}>
<PlusOutlined /> Add Transaction
</Button>
</div>
{showForm && (
<Form form={form} layout="vertical" style={styles.transactionForm}>
<div style={{ display: "flex", flexWrap: "wrap" }}>
<FormControl id="date" style={{ flex: 1, marginRight: 16, marginBottom: 16 }} isRequired>
<FormLabel htmlFor="date">Date</FormLabel>
<Input
as="input"
type="date"
defaultValue={today} // Set today's date as default
min={today} // Disable past dates
onChange={(e) => form.setFieldsValue({ date: moment(e.target.value) })}
bg="white" // Add this to ensure the background is white
/>
</FormControl>
<Form.Item
name="amountPaid"
label="Amount"
min={0}
rules={[{ required: true, message: "Please input amount!" }]}
style={{ flex: 1, marginRight: 16, marginBottom: 16 }}
>
<Input prefix="₹" type="number" min={0}
/>
</Form.Item>
<Form.Item
name="paymentMode"
label="Payment Method"
style={{ flex: 1, marginRight: 16, marginBottom: 16 }}
>
<Select defaultValue="online">
<Option value="online">Online</Option>
<Option value="cash">Cash</Option>
<Option value="creditCard">Credit Card</Option>
<Option value="upi">UPI</Option>
</Select>
</Form.Item>
</div>
<Space>
<Button
type="primary"
onClick={() => {
if (editMode) {
form
.validateFields()
.then((values) => {
const formattedValues = {
...values,
date: moment(values.date).format("YYYY-MM-DD"),
};
logTransactionDetails(
selectedTransaction,
formattedValues
);
})
.catch((info) => {
console.log("Validate Failed:", info);
});
} else {
saveTransaction();
}
}}
>
{editMode ? "Update" : "Save"}
</Button>
<Button onClick={handleCancelClick}>
<CloseOutlined /> Cancel
</Button>
</Space>
</Form>
)}
{Array.isArray(transactions) && transactions.length >= 0 && (
<List
itemLayout="horizontal"
dataSource={transactions}
renderItem={(item) => (
<Card key={item.id} style={styles.transactionListItem}>
<div style={styles.transactionDetails}>
<Text style={styles.transactionId}>Transaction #{item.id}</Text>
<Text style={styles.transactionText}>
🗓️ {moment(item.date).format("YYYY-MM-DD")} | 💵: ₹
{item.amountPaid} | 💳: {item.paymentMode}
</Text>
<div style={styles.actionButtons}>
<Button
icon={<EditOutlined />}
onClick={() => handleEditTransactionClick(item)}
style={styles.editButton}
/>
<Button
icon={<DeleteOutlined />}
onClick={() => deleteTransaction(item.transactionId)}
style={styles.deleteButton}
/>
</div>
</div>
</Card>
)}
/>
)}
</Card>
);
};
const styles = {
transactionCard: {
maxWidth: "100%",
width: "825px",
backgroundColor: "#FFFFFF",
borderRadius: 10,
boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
},
headerContainer: {
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 20,
},
headerTitle: {
margin: 0,
},
addButton: {
backgroundColor: "#4CAF50",
color: "white",
border: "none",
borderRadius: 5,
},
transactionForm: {
marginBottom: 20,
},
transactionListItem: {
backgroundColor: "#f5f5f5",
margin: "10px 0",
borderRadius: 5,
boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
},
transactionDetails: {
display: "flex",
justifyContent: "space-between",
alignItems: "center",
padding: "12px 24px",
},
transactionId: {
margin: 0,
color: "#333333",
fontWeight: "bold",
},
transactionText: {
margin: 0,
color: "#333333",
},
actionButtons: {
display: "flex",
alignItems: "center",
},
editButton: {
backgroundColor: "#2196F3",
color: "white",
border: "none",
marginRight: 8,
},
deleteButton: {
backgroundColor: "#F44336",
color: "white",
border: "none",
},
};
export default AddTransactions; |
import React, { useState } from "react";
import { Modal, Box, TextField, Button, Typography } from "@mui/material";
import axios from "axios";
const AddDevice = ({ clientId, isOpen, handleClose, updateDevices }) => {
const [error, setError] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
setError("");
const { deviceType, manufacturer, modelName, modelNumber, serialNumber } =
e.target.elements;
try {
const req = {
clientId: clientId,
deviceType: deviceType.value,
manufacturer: manufacturer.value,
modelName: modelName.value,
modelNumber: modelNumber.value,
serialNumber: serialNumber.value,
};
const backendApiUrl = import.meta.env.VITE_BACKEND_API;
const response = await axios.post(
`${backendApiUrl}/clients/${clientId}/device`,
req
);
updateDevices(response.data);
handleClose();
} catch (e) {
setError(e.response?.data?.error || "An unexpected error occurred.");
}
};
const customStyles = {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: "50%",
bgcolor: "background.paper",
boxShadow: 24,
p: 4,
borderRadius: 2,
outline: "none",
};
return (
<Modal open={isOpen} onClose={handleClose}>
<Box sx={customStyles}>
<Typography variant="h6" gutterBottom component="div">
New Device Info
</Typography>
<Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
<TextField
margin="normal"
required
fullWidth
label="Device Type"
name="deviceType"
autoFocus
/>
<TextField
margin="normal"
required
fullWidth
label="Manufacturer"
name="manufacturer"
/>
<TextField
margin="normal"
required
fullWidth
label="Model Name"
name="modelName"
/>
<TextField
margin="normal"
required
fullWidth
label="Model Number"
name="modelNumber"
/>
<TextField
margin="normal"
required
fullWidth
label="Serial Number"
name="serialNumber"
/>
{error && (
<Typography variant="body2" color="error" gutterBottom>
{error}
</Typography>
)}
<Box sx={{ display: "flex", justifyContent: "flex-end", mt: 2 }}>
<Button onClick={handleClose} sx={{ mr: 2 }}>
Cancel
</Button>
<Button type="submit" variant="contained">
Add Device
</Button>
</Box>
</Box>
</Box>
</Modal>
);
};
export default AddDevice; |
//
// AnimationProjectView.swift
// ProjectLibraryApp
//
// Created by Ivan Aguiar on 12/10/2022.
//
import SwiftUI
struct AnimationProjectView: View {
var body: some View {
ZStack {
LinearGradient(colors: [.mint, .green], startPoint: .zero, endPoint: .bottom)
.opacity(0.5)
.ignoresSafeArea()
VStack (spacing: 10) {
CornerAnimationView()
SnakAnimationView()
TransitionAnimationView()
HStack (spacing: 10){
CircleAnimationView()
ScaleEffectAnimationView()
}
}
.navigationTitle("Elements Animation")
.navigationBarTitleDisplayMode(.large)
.toolbar {
ToolbarItemGroup (placement: .navigationBarTrailing) {
NavigationLink(destination: ExplanationView(title: "Elements Animation", description: "This project was inspired by HACKING WITH SWIFT. The principle goal is to understand how Animation works. The secondary goal is to customize the components and try to simplify the code as it is possible."), label: {
HStack {
Text("Explanation")
Image(systemName: "brain.head.profile")
}
})
}
}
}
}
}
struct AnimationProjectView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
AnimationProjectView()
}
}
} |
import { Server } from "http";
import { Server as SecureServer } from "https";
import { Config as SshConfig } from "node-ssh";
import { Express } from "express";
import OAS from "../json/openapi.json";
import {
CPIV5Response,
StartFlowV5Request,
FlowStatusV5Response,
} from "./generated/openapi/typescript-axios";
import {
IPluginLedgerConnector,
IWebServiceEndpoint,
IPluginWebService,
ICactusPluginOptions,
ConsensusAlgorithmFamily,
} from "@hyperledger/cactus-core-api";
import { consensusHasTransactionFinality } from "@hyperledger/cactus-core";
import {
Checks,
Logger,
LoggerProvider,
LogLevelDesc,
} from "@hyperledger/cactus-common";
import { DeployContractJarsEndpoint } from "./web-services/deploy-contract-jars-endpoint";
import {
IGetPrometheusExporterMetricsEndpointV1Options,
GetPrometheusExporterMetricsEndpointV1,
} from "./web-services/get-prometheus-exporter-metrics-endpoint-v1";
import { PrometheusExporter } from "./prometheus-exporter/prometheus-exporter";
import {
IInvokeContractEndpointV1Options,
InvokeContractEndpointV1,
} from "./web-services/invoke-contract-endpoint-v1";
import {
IListCPIEndpointV1Options,
ListCPIEndpointV1,
} from "./web-services/get-cpi-endpoint-v1";
import {
IFlowStatusEndpointV1Options,
FlowStatusEndpointV1,
} from "./web-services/list-flow-status-endpoint-v1";
import {
IFlowStatusResponseEndpointV1Options,
FlowStatusResponseEndpointV1,
} from "./web-services/get-flow-status-response-endpoint-v1";
import {
IListFlowsEndpointV1Options,
ListFlowsEndpointV1,
} from "./web-services/list-flows-endpoint-v1";
import {
INetworkMapEndpointV1Options,
NetworkMapEndpointV1,
} from "./web-services/network-map-endpoint-v1";
import {
IDiagnoseNodeEndpointV1Options,
DiagnoseNodeEndpointV1,
} from "./web-services/diagnose-node-endpoint-v1";
import {
IStartFlowEndpointV1Options,
StartFlowEndpointV1,
} from "./web-services/start-flow-endpoint-v1";
import fs from "fs";
import fetch from "node-fetch";
import https from "https";
export enum CordaVersion {
CORDA_V4X = "CORDA_V4X",
CORDA_V5 = "CORDA_V5",
}
export interface IPluginLedgerConnectorCordaOptions
extends ICactusPluginOptions {
logLevel?: LogLevelDesc;
sshConfigAdminShell: SshConfig;
corDappsDir: string;
prometheusExporter?: PrometheusExporter;
cordaStartCmd?: string;
cordaStopCmd?: string;
apiUrl?: string;
cordaVersion?: CordaVersion;
holdingIDShortHash?: any;
clientRequestID?: any;
/**
* Path to the file where the private key for the ssh configuration is located
* This property is optional. Its use is not recommended for most cases, it will override the privateKey property of the sshConfigAdminShell.
* @type {string}
* @memberof IPluginLedgerConnectorCordaOptions
*/
sshPrivateKeyPath?: string;
}
export class PluginLedgerConnectorCorda
implements
IPluginLedgerConnector<
FlowStatusV5Response,
StartFlowV5Request,
CPIV5Response,
any
>,
IPluginWebService
{
//add here implement similar to transact connector-fabric,
public static readonly CLASS_NAME = "DeployContractJarsEndpoint";
private readonly instanceId: string;
private readonly log: Logger;
public prometheusExporter: PrometheusExporter;
// need to add checking if v4 or v5 and what to deploy
private endpoints: IWebServiceEndpoint[] | undefined;
public get className(): string {
return DeployContractJarsEndpoint.CLASS_NAME;
}
private httpServer: Server | SecureServer | null = null;
constructor(public readonly options: IPluginLedgerConnectorCordaOptions) {
const fnTag = `${this.className}#constructor()`;
Checks.truthy(options, `${fnTag} options`);
Checks.truthy(options.sshConfigAdminShell, `${fnTag} sshConfigAdminShell`);
Checks.truthy(options.instanceId, `${fnTag} instanceId`);
const level = options.logLevel || "INFO";
const label = "plugin-ledger-connector-corda";
this.log = LoggerProvider.getOrCreate({ level, label });
this.instanceId = this.options.instanceId;
this.prometheusExporter =
options.prometheusExporter ||
new PrometheusExporter({ pollingIntervalInMin: 1 });
Checks.truthy(
this.prometheusExporter,
`${fnTag} options.prometheusExporter`,
);
this.prometheusExporter.startMetricsCollection();
// if privateKeyPath exists, overwrite privateKey in sshConfigAdminShell
this.readSshPrivateKeyFromFile();
}
public getOpenApiSpec(): unknown {
return OAS;
}
public getPrometheusExporter(): PrometheusExporter {
return this.prometheusExporter;
}
public async getPrometheusExporterMetrics(): Promise<string> {
const res: string = await this.prometheusExporter.getPrometheusMetrics();
this.log.debug(`getPrometheusExporterMetrics() response: %o`, res);
return res;
}
public async getConsensusAlgorithmFamily(): Promise<ConsensusAlgorithmFamily> {
return ConsensusAlgorithmFamily.Authority;
}
public async hasTransactionFinality(): Promise<boolean> {
const currentConsensusAlgorithmFamily =
await this.getConsensusAlgorithmFamily();
return consensusHasTransactionFinality(currentConsensusAlgorithmFamily);
}
public getInstanceId(): string {
return this.instanceId;
}
public getPackageName(): string {
return "@hyperledger/cactus-plugin-ledger-connector-corda";
}
public async onPluginInit(): Promise<unknown> {
return;
}
public deployContract(): Promise<any> {
throw new Error("Method not implemented.");
}
public async transact(): Promise<any> {
this.prometheusExporter.addCurrentTransaction();
return null as any;
}
async registerWebServices(app: Express): Promise<IWebServiceEndpoint[]> {
const webServices = await this.getOrCreateWebServices();
await Promise.all(webServices.map((ws) => ws.registerExpress(app)));
// await Promise.all(webServices.map((ws) => ws.registerExpress(app)));
return webServices;
}
private readSshPrivateKeyFromFile(): void {
const { sshPrivateKeyPath } = this.options;
if (sshPrivateKeyPath) {
const fileContent = fs
.readFileSync(sshPrivateKeyPath, "utf-8")
.toString();
this.options.sshConfigAdminShell.privateKey = fileContent;
}
}
public async getOrCreateWebServices(): Promise<IWebServiceEndpoint[]> {
if (Array.isArray(this.endpoints)) {
return this.endpoints;
}
const pkgName = this.getPackageName();
this.log.info(`Instantiating web services for ${pkgName}...`);
const endpoints: IWebServiceEndpoint[] = [];
{
const endpoint = new DeployContractJarsEndpoint({
sshConfigAdminShell: this.options.sshConfigAdminShell,
logLevel: this.options.logLevel,
corDappsDir: this.options.corDappsDir,
cordaStartCmd: this.options.cordaStartCmd,
cordaStopCmd: this.options.cordaStopCmd,
apiUrl: this.options.apiUrl,
});
endpoints.push(endpoint);
}
{
const opts: IInvokeContractEndpointV1Options = {
apiUrl: this.options.apiUrl,
logLevel: this.options.logLevel,
};
const endpoint = new InvokeContractEndpointV1(opts);
endpoints.push(endpoint);
}
{
const opts: IGetPrometheusExporterMetricsEndpointV1Options = {
connector: this,
logLevel: this.options.logLevel,
};
const endpoint = new GetPrometheusExporterMetricsEndpointV1(opts);
endpoints.push(endpoint);
}
{
const opts: IListFlowsEndpointV1Options = {
apiUrl: this.options.apiUrl,
logLevel: this.options.logLevel,
cordaVersion: this.options.cordaVersion,
connector: this,
};
const endpoint = new ListFlowsEndpointV1(opts);
endpoints.push(endpoint);
}
{
const opts: INetworkMapEndpointV1Options = {
apiUrl: this.options.apiUrl,
logLevel: this.options.logLevel,
};
const endpoint = new NetworkMapEndpointV1(opts);
endpoints.push(endpoint);
}
{
const opts: IDiagnoseNodeEndpointV1Options = {
apiUrl: this.options.apiUrl,
logLevel: this.options.logLevel,
};
const endpoint = new DiagnoseNodeEndpointV1(opts);
endpoints.push(endpoint);
}
{
const opts: IListCPIEndpointV1Options = {
apiUrl: this.options.apiUrl,
logLevel: this.options.logLevel,
connector: this,
};
const endpoint = new ListCPIEndpointV1(opts);
endpoints.push(endpoint);
}
{
const opts: IFlowStatusEndpointV1Options = {
apiUrl: this.options.apiUrl,
logLevel: this.options.logLevel,
holdingIDShortHash: this.options.holdingIDShortHash,
connector: this,
};
const endpoint = new FlowStatusEndpointV1(opts);
endpoints.push(endpoint);
}
{
const opts: IFlowStatusResponseEndpointV1Options = {
apiUrl: this.options.apiUrl,
logLevel: this.options.logLevel,
holdingIDShortHash: this.options.holdingIDShortHash,
clientRequestID: this.options.clientRequestID,
connector: this,
};
const endpoint = new FlowStatusResponseEndpointV1(opts);
endpoints.push(endpoint);
}
{
const opts: IStartFlowEndpointV1Options = {
apiUrl: this.options.apiUrl,
logLevel: this.options.logLevel,
connector: this,
};
const endpoint = new StartFlowEndpointV1(opts);
endpoints.push(endpoint);
}
this.log.info(`Instantiated endpoints of ${pkgName}`);
return endpoints;
}
public async shutdown(): Promise<void> {
return;
}
public async getFlowList(): Promise<string[]> {
return ["getFlowList()_NOT_IMPLEMENTED"];
}
public async startFlow(req: StartFlowV5Request): Promise<any> {
const fnTag = `${this.className}#startFlowV5Request()`;
this.log.debug("%s ENTER", fnTag);
const username = "admin";
const password = "admin";
const authString = Buffer.from(`${username}:${password}`).toString(
"base64",
);
const headers = {
Authorization: `Basic ${authString}`,
};
const httpsAgent = new https.Agent({ rejectUnauthorized: false });
try {
const holdingIDShortHash = req.holdingIDShortHash;
const cordaReq = {
clientRequestId: req.clientRequestId,
flowClassName: req.flowClassName,
requestBody: req.requestBody
};
const cordaReqBuff = Buffer.from(JSON.stringify(cordaReq));
const response = await fetch(
"https://127.0.0.1:8888/api/v1/flow/" + holdingIDShortHash,
{
method: `POST`,
headers: headers,
body: cordaReqBuff,
agent: httpsAgent,
},
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const responseData = await response.json();
console.log("Response:", responseData);
return responseData;
} catch (error) {
console.error("Error fetching data:", error);
}
}
public async listCPI(): Promise<any> {
const username = "admin";
const password = "admin";
const authString = Buffer.from(`${username}:${password}`).toString(
"base64",
);
const headers = {
Authorization: `Basic ${authString}`,
};
const httpsAgent = new https.Agent({ rejectUnauthorized: false });
try {
const response = await fetch("https://127.0.0.1:8888/api/v1/cpi", {
method: `GET`,
headers: headers,
agent: httpsAgent,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const responseData = await response.json();
return responseData;
} catch (error) {
console.error("Error fetching data:", error);
}
}
public async getFlow(holdingshortHashID: string): Promise<any> {
const fnTag = `${this.className}#startFlowV5Request()`;
this.log.debug("%s ENTER", fnTag);
const username = "admin";
const password = "admin";
const authString = Buffer.from(`${username}:${password}`).toString(
"base64",
);
const headers = {
Authorization: `Basic ${authString}`,
};
const httpsAgent = new https.Agent({ rejectUnauthorized: false });
try {
const response = await fetch(
"https://127.0.0.1:8888/api/v1/flow/" + holdingshortHashID,
{
method: `GET`,
headers: headers,
agent: httpsAgent,
},
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const responseData = await response.json();
console.log("Response:", responseData);
return responseData;
} catch (error) {
console.error("Error fetching data:", error);
}
}
} |
import fallbackImage from 'assets/img/fallBack.png';
import { graphql, useStaticQuery } from 'gatsby';
import React from 'react';
import { Helmet } from 'react-helmet';
import { useLocation } from '@reach/router';
import { SeoProps } from '@types';
// add detailed seo props
export const Seo = ({
seoTitle,
seoDescription,
imageSrc,
}: SeoProps): JSX.Element => {
const { site } = useStaticQuery(
graphql`
query {
site {
siteMetadata {
title
description
author
lang
keywords
siteUrl
}
}
}
`,
);
const image = imageSrc ? imageSrc : fallbackImage;
const { pathname } = useLocation();
return (
<Helmet
htmlAttributes={{
lang: site.siteMetadata.lang ?? 'ru',
}}
title={`${site.siteMetadata.title} | ${seoTitle}`}
meta={[
{
name: 'charSet',
content: 'utf-8',
},
{
name: 'description',
content: seoDescription ?? site.siteMetadata.description,
},
{
property: 'og:title',
content: seoTitle ?? site.siteMetadata.title,
},
{
property: 'og:description',
content: seoDescription ?? site.siteMetadata.description,
},
{
property: 'og:type',
content: 'website',
},
{
name: 'og:image',
content: image,
},
{
name: 'og:image:height',
content: 640,
},
{
name: 'og:image:width',
content: 480,
},
{
name: 'og:url',
content: (process.env.NODE_ENV === 'development' ? `https://localhost:8000${pathname}` : `${site.siteMetadata.siteUrl}${pathname}`),
},
{
name: 'twitter:card',
content: 'summary',
},
{
name: 'twitter:creator',
content: site.siteMetadata.author,
},
{
name: 'twitter:title',
content: seoTitle ?? site.siteMetadata.title,
},
{
name: 'twitter:description',
content: seoDescription ?? site.siteMetadata.description,
},
]}
/>
);
}; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch Names from Firebase</title>
</head>
<body>
<select id="nameDropdown" onchange="updatePlaceholder()">
<option value="" data-email="">Select a Name</option>
</select>
<br><br>
<label for="message">Message:</label><br>
<textarea id="message" name="message" rows="4" cols="50"></textarea>
<br><br>
<!-- <button onclick="fetchNames()">Fetch Names</button> -->
<button onclick="sendEmail()">Send Email</button>
<script src="https://www.gstatic.com/firebasejs/8.5.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.5.0/firebase-database.js"></script>
<script src="https://cdn.emailjs.com/dist/email.min.js"></script>
<script>
// Initialize Firebase
const firebaseConfig = {
apiKey: "AIzaSyAkigLuiZ5MjbM4e_syOe71xeH8gVoLLr4",
authDomain: "automaticattendancesyste-a6a0f.firebaseapp.com",
databaseURL: "https://automaticattendancesyste-a6a0f-default-rtdb.firebaseio.com",
projectId: "automaticattendancesyste-a6a0f",
storageBucket: "automaticattendancesyste-a6a0f.appspot.com",
messagingSenderId: "942313834507",
appId: "1:942313834507:web:9f15279555550f566f5f0e"
};
firebase.initializeApp(firebaseConfig);
const database = firebase.database();
// Initialize EmailJS
emailjs.init("8L0dhatUmIAoUfXnt");
function fetchNames() {
const usersRef = database.ref('users');
usersRef.once('value', function(snapshot) {
const nameDropdown = document.getElementById('nameDropdown');
nameDropdown.innerHTML = '<option value="" data-email="">Select a Name</option>';
snapshot.forEach(function(childSnapshot) {
const uid = childSnapshot.key;
const name = childSnapshot.child('name').val();
const email = childSnapshot.child('email').val();
addOptionToDropdown(nameDropdown, name, email);
});
});
}
function addOptionToDropdown(dropdown, name, email) {
const option = document.createElement('option');
option.text = name;
option.value = name;
option.setAttribute('data-email', email);
dropdown.appendChild(option);
}
function updatePlaceholder() {
const nameDropdown = document.getElementById('nameDropdown');
const selectedOption = nameDropdown.options[nameDropdown.selectedIndex];
nameDropdown.options[0].text = selectedOption.text;
}
function sendEmail() {
const nameDropdown = document.getElementById('nameDropdown');
const selectedOption = nameDropdown.options[nameDropdown.selectedIndex];
const selectedEmail = selectedOption.getAttribute('data-email');
const message = document.getElementById('message').value; // Get the message from the textarea
// Send email using EmailJS
const templateParams = {
to_email: selectedEmail,
from_email: 'amisharaje2018@gmail.com',
subject: 'Subject of your email',
body: message // Use the message obtained from the textarea
};
emailjs.send("service_0p1g27i", "template_ir4c4ue", templateParams)
.then(function(response) {
console.log("Email sent successfully:", response);
alert("Email sent successfully to: " + selectedEmail);
}, function(error) {
console.error("Email sending failed:", error);
alert("Email sending failed. Please try again later.");
});
}
fetchNames();
</script>
</body>
</html> |
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="fragments/head :: head(Minioasis)">
<title>Minioasis Library</title>
</head>
<body>
<div th:replace="fragments/topnav :: topnav"></div>
<div class="container pt-2">
<div th:replace="fragments/nav.favourite :: navfavourite"></div>
<h4>
<span th:text="#{search.patron}">Search Patron</span>
<a href="#" th:href="@{/admin/patron/save}">
<img th:src="@{/images/patron.png}" alt=""/>
</a>
<a class="btn btn-outline-light text-primary" href="#" th:href="@{/admin/patron/list(page=0,size=10,sort='cardKey,desc')}">
<i class="fas fa-search fa-2x"></i>
</a>
</h4>
<ul class="nav nav-tabs pt-3" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="general-tab" data-toggle="tab" href="#general" role="tab" aria-controls="general" aria-selected="true">
<i class="fab fa-envira"></i>
<span th:text="#{general}">General</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" id="date-tab" data-toggle="tab" href="#date" role="tab" aria-controls="date" aria-selected="false">
<i class="fab fa-envira"></i>
<span th:text="#{date}">Date</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" id="type-tab" data-toggle="tab" href="#type" role="tab" aria-controls="type" aria-selected="false">
<i class="fab fa-envira"></i>
<span th:text="#{type}">Type</span>
</a>
</li>
</ul>
<form action="#" th:action="@{/admin/patron/search}" th:object="${criteria}" method="get">
<input type="hidden" id="page" name="page" value="0" />
<input type="hidden" id="size" name="size" value="10" />
<input type="hidden" id="sort" name="sort" value="card_key,desc" />
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="general" role="tabpanel" aria-labelledby="general-tab">
<div class="form-row pt-3">
<div class="form-group col-md-3">
<label>
<span th:text="#{name}">Name</span>.
<span th:text="#{name2}">Name2</span>.
<span th:text="#{ic}">IC</span>.
<span th:text="#{mobile}">Mobile</span>.
</label>
<input type="text" class="form-control" th:field="*{keyword}" autofocus="autofocus"/>
</div>
<div class="form-group col-md-3">
<label th:text="#{card.key}">Card Key</label>
<input type="text" class="form-control" th:field="*{cardKey}"/>
</div>
<div class="form-group col-md-3">
<label th:text="#{note}">Note</label>
<input type="text" class="form-control" th:field="*{note}"/>
</div>
<div class="form-group col-md-2">
<label th:text="#{notes}">Notes</label>
<a th:href="@{/admin/patron/search(page=0,size=20,sort='cardKey,desc',note='isNotEmpty()')}" id="next">
<button type="button" class="form-control btn btn-outline-success"><i class="far fa-sticky-note"></i></button>
</a>
</div>
</div>
</div>
<div class="tab-pane fade" id="date" role="tabpanel" aria-labelledby="date-tab">
<div class="form-row pt-3">
<div class="form-group col-md-2">
<label>
<i class="far fa-calendar-plus"></i>
<span th:text="#{start.date}">Start Date</span>
</label>
<input type="text" class="form-control" th:field="*{startDateFrom}" placeholder="yyyy-MM-dd" />
</div>
<div class="form-group col-md-2">
<label><i class="far fa-calendar-minus"></i></label>
<input type="text" class="form-control" th:field="*{startDateTo}" placeholder="To" />
</div>
<div class="form-group col-md-2">
<label>
<i class="far fa-calendar-plus"></i>
<span th:text="#{end.date}">End Date</span>
</label>
<input type="text" class="form-control" th:field="*{endDateFrom}" placeholder="From" />
</div>
<div class="form-group col-md-2">
<label><i class="far fa-calendar-minus"></i></label>
<input type="text" class="form-control" th:field="*{endDateTo}" placeholder="To" />
</div>
<div class="form-group col-md-2">
<label>
<i class="far fa-calendar-plus"></i>
<span th:text="#{created}">Created</span>
</label>
<input type="text" class="form-control" th:field="*{createdFrom}" placeholder="From" />
</div>
<div class="form-group col-md-2">
<label><i class="far fa-calendar-minus"></i></label>
<input type="text" class="form-control" th:field="*{createdTo}" placeholder="To" />
</div>
</div>
</div>
<div class="tab-pane fade" id="type" role="tabpanel" aria-labelledby="type-tab">
<div class="form-row pt-3">
<div class="form-group col-md-3">
<label th:text="#{patron.type}">Patron Type</label>
<select class="form-control" th:field="*{patronTypes}" multiple="multiple">
<option th:each="pt : ${pts}" th:value="${pt.id}" th:text="${pt.name}" />
<option th:remove="all" value="24121">SM1</option>
<option th:remove="all" value="12123">SM2</option>
</select>
</div>
<div class="form-group col-md-3">
<label th:text="#{group}">Group</label>
<select class="form-control" th:field="*{groups}" multiple="multiple">
<option th:each="g : ${gps}" th:value="${g.id}" th:text="${g.code}" />
<option th:remove="all" value="24121">SM1</option>
<option th:remove="all" value="12123">SM2</option>
</select>
</div>
<div class="form-group col-md-3">
<label th:text="#{active}">Active</label>
<select class="form-control" th:field="*{actives}" multiple="multiple">
<option th:each="a : ${ats}" th:value="${a}" th:text="${a}" />
<option th:remove="all" value="Y" th:text="${yes}">SM1</option>
<option th:remove="all" value="N" th:text="${no}">SM2</option>
</select>
</div>
</div>
</div>
</div>
<input hidden="hidden" type="submit" name="search" value="Submit"/>
</form>
<hr/>
<div class="float-right">
<a th:if="${page.hasPrevious()}" th:href="${previous}" id="previous">
<button type="button" class="btn btn-outline-info rounded-pill">Previous</button>
</a>
<a th:if="${page.hasNext()}" th:href="${next}" id="next">
<button type="button" class="btn btn-outline-info rounded-pill">Next</button>
</a>
</div>
Total : <span th:text="${page.totalElements}">105</span>
<div class="table-responsive-sm">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th th:text="#{photo}">Photo</th>
<th th:text="#{name} + '(Gender) / IC'">Name (Gender) / IC</th>
<th th:text="#{active}">Active</th>
<th th:text="#{patron.type}">P.Type</th>
<th th:text="#{card.key}">C.Key</th>
<th th:text="#{group}">Group</th>
<th th:text="#{start.end}">Start / End</th>
<th th:text="#{note}">Note</th>
<th th:text="#{actions}">Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="e,iterator : ${page.content}">
<td th:text="${iterator.index + 1} + ${page.number * page.size}">1</td>
<td>
<img src="@{/images/smiley.png}"
th:src="@{/admin/thumbnail.photo/patron/{id}(id=${e.ic})}"
class="thumbnail"
style="min-height:75px;height:100px;width:75px;"/>
</td>
<td>
<a href="#" th:href="@{/admin/patron/{id}(id=${e.id})}" th:text="|${e.name} , ${e.name2}|">Moan Wai Meng</a>
<p>[[${'( ' + e.gender + ' )'}]]</p>
<p>[[${e.ic}]]</p>
</td>
<td th:text="${e.active}">Student</td>
<td th:text="${e.patronType.name}">Student</td>
<td>
<a href="#" th:href="@{/admin/circ/checkout?pid={cardKey}(cardKey=${e.cardKey})}" th:text="${e.cardKey}">cardKey</a>
</td>
<td th:text="${e.group.code}">SM1</td>
<td th:inline="text">
[[${#temporals.format(e.startDate,'yyyy-MM-dd')}]]
<br>
[[${#temporals.format(e.endDate,'yyyy-MM-dd')}]]
</td>
<td><textarea rows="4" cols="30" name="note" th:text="${e.note}"></textarea></td>
<td>
<a href="#" th:href="@{/admin/patron/edit?id={id}(id=${e.id})}"><i class="far fa-edit"></i></a>
|
<a href="#" th:href="@{/admin/patron/delete/{id}(id=${e.id})}"><i class="far fa-trash-alt"></i></a>
<p></p>
<a sec:authorize="hasRole('ROLE_ADMIN')" class="btn btn-sm btn-outline-info text-info" href="#" th:href="@{/admin/audit/patron/{id}/list(page=0,size=10,id=${e.id})}">
<i class="fas fa-history"></i>
</a>
</td>
</tr>
<tr th:remove="all">
<td>2</td>
<td>Photo</td>
<td>Name</td>
<td>CardKey</td>
<td>patron Type</td>
<td>Note</td>
<td><a href="#">Edit</a> | <a href="#">Delete</a></td>
</tr>
</tbody>
</table>
</div>
<div th:replace="fragments/script :: script"></div>
<div th:replace="fragments/footer :: footer"></div>
</div>
</body>
</html> |
//输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
//
// 要求时间复杂度为O(n)。
//
//
//
// 示例1:
//
// 输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
//输出: 6
//解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
//
//
//
// 提示:
//
//
// 1 <= arr.length <= 10^5
// -100 <= arr[i] <= 100
//
//
// 注意:本题与主站 53 题相同:https://leetcode-cn.com/problems/maximum-subarray/
//
//
// Related Topics 数组 分治 动态规划 👍 429 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class SolutionOffer42 {
/**
* 状态定义: 设动态规划列表 dpdp ,dp[i]dp[i] 代表以元素 nums[i]nums[i] 为结尾的连续子数组最大和。
* 为何定义最大和 dp[i] 中必须包含元素 nums[i]:
* 保证 dp[i] 递推到 dp[i+1] 的正确性;如果不包含 nums[i],递推时则不满足题目的 连续子数组 要求。
*
* 转移方程: 若 dp[i-1] ≤ 0 ,说明 dp[i - 1] 对 dp[i] 产生负贡献,即 dp[i-1] + nums[i] 还不如 nums[i] 本身大。
*
* 当 dp[i - 1] > 0 时:执行 dp[i] = dp[i-1] + nums[i];
* 当 dp[i - 1] <= 0 时:执行 dp[i] = nums[i];
* 初始状态: dp[0] = nums[0],即以 nums[0] 结尾的连续子数组最大和为 nums[0] 。
*
* 返回值: 返回 dp 列表中的最大值,代表全局最大值。
*
* 实用参考 124
* 经典 DP: 152, 343
*/
public int maxSubArray(int[] nums) {
int[] dp = new int[nums.length];
dp[0] = nums[0];
int res = dp[0];
for (int i = 1; i < nums.length; i++) {
dp[i] = Math.max(dp[i-1] + nums[i], nums[i]);
res = Math.max(res, dp[i]);
}
return res;
}
}
//leetcode submit region end(Prohibit modification and deletion) |
import { TestBed } from "@angular/core/testing";
import { provideMockActions } from '@ngrx/effects/testing';
import { Observable, of, throwError } from 'rxjs';
import { Action } from '@ngrx/store';
import { ProductsEffects } from './products.effects';
import { EffectsModule } from "@ngrx/effects";
import { provideMockStore } from "@ngrx/store/testing";
import { ProductServiceMock } from "src/mock/product-service.mock";
import { loadProducts, loadProductsFail, loadMoreProducts, loadProductsSuccess, removeProduct, removeProductFail, removeProductSuccess, updateProductOnList, updateProductOnListFail, updateProductOnListSuccess, filterProducts } from "./products.actions";
import { ProductService } from "src/app/services/product/product.service";
import { changeVisibilitySuccess } from "../../product-detail/store/products/product-detail.actions";
describe('ProductsEffects', () => {
let actions$ = new Observable<Action>();
let effects: ProductsEffects;
let productService: ProductServiceMock;
const products = [{id: '1'}] as any;
const error = {error: "error"};
beforeEach(() => {
productService = new ProductServiceMock();
TestBed.configureTestingModule({
imports: [
EffectsModule.forRoot([]),
EffectsModule.forFeature([ProductsEffects])
],
providers: [
ProductsEffects,
provideMockStore({initialState: {products: {page: 0}}}),
provideMockActions(() => actions$)
],
})
.overrideProvider(ProductService, {useValue: productService});
effects = TestBed.get(ProductsEffects);
})
describe("Given load products", () => {
beforeEach(() => {
actions$ = of(loadProducts());
})
it('when success, then return load success', (done) => {
productService._response = of(products);
effects.loadEffect$.subscribe(response => {
expect(response).toEqual(loadProductsSuccess({products}));
done();
})
})
it('when fail, then return load fail', (done) => {
productService._response = throwError(error);
effects.loadEffect$.subscribe(response => {
expect(response).toEqual(loadProductsFail({error}));
done();
})
})
})
describe("Given filter products", () => {
beforeEach(() => {
const filter = {category: "anyCategoryId"} as any;
actions$ = of(filterProducts({filter}));
})
it('when success, then return load success', (done) => {
productService._response = of(products);
effects.loadEffect$.subscribe(response => {
expect(response).toEqual(loadProductsSuccess({products}));
done();
})
})
it('when fail, then return load fail', (done) => {
productService._response = throwError(error);
effects.loadEffect$.subscribe(response => {
expect(response).toEqual(loadProductsFail({error}));
done();
})
})
})
describe("Given load more products", () => {
beforeEach(() => {
actions$ = of(loadMoreProducts());
})
it('when success, then return load success', (done) => {
productService._response = of(products);
effects.loadEffect$.subscribe(response => {
expect(response).toEqual(loadProductsSuccess({products}));
done();
})
})
it('when fail, then return load fail', (done) => {
productService._response = throwError(error);
effects.loadEffect$.subscribe(response => {
expect(response).toEqual(loadProductsFail({error}));
done();
})
})
})
describe("Given remove", () => {
beforeEach(() => {
const product = {id: 1} as any;
actions$ = of(removeProduct({product}));
})
it('when success, then return load success', (done) => {
productService._response = of(products);
effects.removeEffect$.subscribe(response => {
expect(response).toEqual(removeProductSuccess());
done();
})
})
it('when fail, then return load fail', (done) => {
productService._response = throwError(error);
effects.removeEffect$.subscribe(response => {
expect(response).toEqual(removeProductFail({error}));
done();
})
})
})
describe("Given remove success", () => {
beforeEach(() => {
actions$ = of(removeProductSuccess());
})
it('then return load', (done) => {
effects.removeSuccessEffect$.subscribe(response => {
expect(response).toEqual(loadProducts());
done();
})
})
})
describe("given change visibility success", () => {
beforeEach(() => {
actions$ = of(changeVisibilitySuccess({id: "anyProductId"}));
})
it('then return update product on list', (done) => {
effects.changeVisibilitySuccessEffect$.subscribe(response => {
expect(response).toEqual(updateProductOnList({id: "anyProductId"}));
done();
})
})
})
describe("given update product on list", () => {
beforeEach(() => {
actions$ = of(updateProductOnList({id: "anyProductId"}));
})
it('when success, then return update product on list success', (done) => {
const product = {id: "anyProductId"} as any;
productService._response = of(product);
effects.updateProductOnList$.subscribe(response => {
expect(response).toEqual(updateProductOnListSuccess({product}));
done();
})
})
it('when fail, then return update product on list error', (done) => {
productService._response = throwError(error);
effects.updateProductOnList$.subscribe(response => {
expect(response).toEqual(updateProductOnListFail({error}));
done();
})
})
})
}); |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Nkgjjm.Models;
namespace Nkgjjm.Areas.Panel.Pages.Supplier
{
public class EditModel : PageModel
{
private readonly Nkgjjm.Models.ApplicationDbContext _context;
public EditModel(Nkgjjm.Models.ApplicationDbContext context)
{
_context = context;
}
[BindProperty]
public Suppliers Suppliers { get; set; } = default!;
public async Task<IActionResult> OnGetAsync(int? id)
{
if (!string.IsNullOrEmpty(HttpContext.Session.GetString("Login")))
{
if (id == null || _context.TblSupplier == null)
{
return NotFound();
}
var suppliers = await _context.TblSupplier.FirstOrDefaultAsync(m => m.Id == id);
if (suppliers == null)
{
return NotFound();
}
Suppliers = suppliers;
return Page();
}
else
{
return Redirect("~/Index");
}
}
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Attach(Suppliers).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!SuppliersExists(Suppliers.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToPage("./Index");
}
private bool SuppliersExists(int id)
{
return (_context.TblSupplier?.Any(e => e.Id == id)).GetValueOrDefault();
}
}
} |
// Malom, a Nine Men's Morris (and variants) player and solver program.
// Copyright(C) 2007-2016 Gabor E. Gevay, Gabor Danner
// Copyright (C) 2023 The Sanmill developers (see AUTHORS file)
//
// See our webpage (and the paper linked from there):
// http://compalg.inf.elte.hu/~ggevay/mills/index.php
//
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef PERFECT_PERFECT_PLAYER_H_INCLUDED
#define PERFECT_PERFECT_PLAYER_H_INCLUDED
#include "perfect_common.h"
#include "perfect_game.h"
#include "perfect_move.h"
#include "perfect_rules.h"
#include "perfect_sector.h"
#include "perfect_wrappers.h"
#include <bitset>
#include <cassert> // for assert
#include <cstdint> // for int64_t
#include <cstdlib> // for std::exit
#include <exception> // for std::exception
#include <fstream>
#include <functional>
#include <iostream>
#include <iostream> // for std::cerr
#include <map>
#include <mutex> // for std::mutex and std::lock_guard
#include <stdexcept>
#include <stdexcept> // for std::out_of_range
#include <string>
#include <vector>
enum class CMoveType {
SetMove,
SlideMove // should be renamed to SlideOrJumpMove
};
struct AdvancedMove
{
int from, to;
CMoveType moveType;
bool withTaking, onlyTaking; // withTaking includes the steps in mill
// closure, onlyTaking only includes removal
int takeHon;
int toBitBoard()
{
if (onlyTaking) {
return 1 << takeHon;
}
int ret = 1 << to;
if (moveType == CMoveType::SlideMove) {
ret += 1 << from;
}
if (withTaking) {
ret += 1 << takeHon;
}
return ret;
}
};
class Sectors
{
public:
static std::map<Wrappers::WID, Wrappers::WSector> sectors;
static bool created;
static std::map<Wrappers::WID, Wrappers::WSector> getSectors();
static bool hasDatabase();
};
class Player
{
protected:
Game *g {nullptr}; // Assuming Game is a pre-defined class
public:
Player()
: g(nullptr)
{ }
// The object is informed to enter the specified game
virtual void enter(Game *_g);
// The object is informed to exit from the game
virtual void quit();
// The object is informed that it is its turn to move
virtual void toMove(const GameState &s) = 0; // Assuming GameState is a
// pre-defined class
// Notifies about the opponent's move
virtual void followMove(CMove *) { } // Assuming Object is a pre-defined
// class or built-in type
// The object is informed that it is the opponent's turn to move
virtual void oppToMove(const GameState &) { }
// Game is over
virtual void over(const GameState &) { }
// Cancel thinking
virtual void cancelThinking() { }
// Determine the opponent player
protected:
Player *opponent()
{
return (g->ply(0) == this) ? g->ply(1) : g->ply(0); // Assuming Game has
// a ply function
}
};
class PerfectPlayer : public Player
{
public:
std::map<Wrappers::WID, Wrappers::WSector> secs;
PerfectPlayer();
virtual ~PerfectPlayer() { }
void enter(Game *_g) override;
void quit() override { Player::quit(); }
Wrappers::WSector *getSec(const GameState s);
std::string toHumanReadableEval(Wrappers::gui_eval_elem2 e);
int futurePieceCount(const GameState &s);
bool makesMill(const GameState &s, int from, int to);
bool isMill(const GameState &s, int m);
std::vector<AdvancedMove> setMoves(const GameState &s);
std::vector<AdvancedMove> slideMoves(const GameState &s);
// m has a withTaking step, where takeHon is not filled out. This function
// creates a list, the elements of which are copies of m supplemented with
// one possible removal each.
std::vector<AdvancedMove> withTakingMoves(const GameState &s,
AdvancedMove &m);
std::vector<AdvancedMove> onlyTakingMoves(const GameState &s);
std::vector<AdvancedMove> getMoveList(const GameState &s);
GameState makeMoveInState(const GameState &s, AdvancedMove &m);
// Assuming gui_eval_elem2 and getSec functions are defined somewhere
Wrappers::gui_eval_elem2 moveValue(const GameState &s, AdvancedMove &m);
template <typename T, typename K>
std::vector<T> allMaxBy(std::function<K(T)> f, const std::vector<T> &l,
K minValue);
// Assuming the definition of gui_eval_elem2::min_value function
std::vector<AdvancedMove> goodMoves(const GameState &s);
int NGMAfterMove(const GameState &s, AdvancedMove &m);
template <typename T>
T chooseRandom(const std::vector<T> &l);
void sendMoveToGUI(AdvancedMove m);
void toMove(const GameState &s) override;
int numGoodMoves(const GameState &s);
int cp;
struct MoveValuePair
{
AdvancedMove m;
double val;
};
Wrappers::gui_eval_elem2 eval(GameState s);
int64_t boardNegate(int64_t a);
};
#endif // PERFECT_PLAYER_H_INCLUDED |
import { UseCaseInterface } from "../../@shared/domain/usecase/usecase.interface";
import {
FindInvoiceFacadeInputDTO,
FindInvoiceFacadeOutputDTO,
GenerateInvoiceFacadeInputDto,
GenerateInvoiceFacadeOutputDto,
InvoiceFacadeInterface,
} from "./invoice.facade.interface";
export interface UseCaseProps {
findInvoiceUseCase: UseCaseInterface;
generateInvoiceUseCase: UseCaseInterface;
}
export class InvoiceFacade implements InvoiceFacadeInterface {
private _findInvoiceUseCase: UseCaseInterface;
private _generateInvoiceUseCase: UseCaseInterface;
constructor({ findInvoiceUseCase, generateInvoiceUseCase }: UseCaseProps) {
this._findInvoiceUseCase = findInvoiceUseCase;
this._generateInvoiceUseCase = generateInvoiceUseCase;
}
async find(
input: FindInvoiceFacadeInputDTO
): Promise<FindInvoiceFacadeOutputDTO> {
return await this._findInvoiceUseCase.execute(input);
}
async generate(
input: GenerateInvoiceFacadeInputDto
): Promise<GenerateInvoiceFacadeOutputDto> {
return await this._generateInvoiceUseCase.execute(input);
}
} |
%% Cooperative Robotics
% Group: Gava Luna, Lagomarsino Marta
% ------------------------------------------------------------
%function MainDexrov
addpath('./simulation_scripts');
clc;
clear;
close all
% Simulation variables (integration and final time)
deltat = 0.005;
end_time = 35;
loop = 1;
maxloops = ceil(end_time/deltat);
% this struct can be used to evolve what the UVMS has to do
mission.phase = 1;
mission.phase_time = 0;
% Rotation matrix to convert coordinates between Unity and the <w> frame
% do not change
wuRw = rotation(0,-pi/2,pi/2);
vRvu = rotation(-pi/2,0,-pi/2);
% pipe parameters
u_pipe_center = [-10.66 31.47 -1.94]'; % in unity coordinates
pipe_center = wuRw'*u_pipe_center; % in world frame coordinates
pipe_radius = 0.3;
% UDP Connection with Unity viewer v2
uArm = udp('127.0.0.1',15000,'OutputDatagramPacketSize',28);
uVehicle = udp('127.0.0.1',15001,'OutputDatagramPacketSize',24);
fopen(uVehicle);
fopen(uArm);
% initialize uvms structure
uvms = InitUVMS('DexROV');
% uvms.q
% Initial joint positions. You can change these values to initialize the simulation with a
% different starting position for the arm
uvms.q = [-0.0031 1.2586 0.0128 -1.2460 0.0137 0.0853-pi/2 0.0137]';
% uvms.p
% initial position of the vehicle
% the vector contains the values in the following order
% [x y z r(rot_x) p(rot_y) y(rot_z)]
% RPY angles are applied in the following sequence
% R(rot_x, rot_y, rot_z) = Rz (rot_z) * Ry(rot_y) * Rx(rot_x)
uvms.p = [-1.9379 10.4813-6.1 -29.7242-0.1 0 0 0]';
% initial goal position definition
% slightly over the top of the pipe
distanceGoalWrtPipe = 0.3;
uvms.goalPosition = pipe_center + (pipe_radius + distanceGoalWrtPipe)*[0 0 1]';
goalOrientation = [pi 0 0];
uvms.wRg = rotation(pi,0,0);
uvms.wTg = [uvms.wRg uvms.goalPosition; 0 0 0 1];
% defines the tool control point
uvms.eTt = eye(4);
% defines the target position for the vehicle position task
uvms.targetPosition = pipe_center + (pipe_radius + 1.5)*[0 0 1]';
targetRotation = [0, -0.06, 0.5];
uvms.wRtarget = rotation(0, -0.06, 0.5);
uvms.wTtarget = [uvms.wRtarget uvms.targetPosition; 0 0 0 1]; % transf. matrix w->target
% exercise = input('Enter the exercise: ','s');
% % Definition and initialization of missions
% mission = InitMissionPhase2(exercise);
% mission = InitMissionPhase(exercise);
option = input(['1 -> to perform an exercise,' newline '0 -> to enter specific objectives: ']);
if option
exercise = input(' Enter the exercise: ','s');
if strcmp(exercise,'5.1') || strcmp(exercise,'5.2')
coordSchema = 0;
else
coordSchema = 1;
end
% Definition and initialization of missions
mission = InitMissionPhase2(exercise);
else
nPhases = input(' Enter number of phases: ');
activeTasks = input(' Enter active tasks (vector 1x10): ');
exitCondition = input([' Enter exit condition:' newline '1 -> vehicle reaching target position' ...
newline '2 -> vehicle landing on the seafloor' ...
newline '3 -> vehicle landing on the seafloor aligning to the nodule' ...
newline '4 -> end effector reaching goal position: ']);
mission = InitMissionPhase(nPhases,activeTasks, exitCondition);
coordSchema = input(' Arm-Vehicle Coordination Scheme (0 -> no; 1 -> yes): ');
end
% Preallocation
plt = InitDataPlot(maxloops, mission);
plt.targetPosition = uvms.targetPosition; % vehicle target position
plt.targetRotation = targetRotation;
plt.goalPosition = uvms.goalPosition; % tool goal position
plt.goalOrientation = goalOrientation;
%plt.goalRotation = goalRotation;
uvms = ComputeActivationFunctions(uvms, mission);
tic
for t = 0:deltat:end_time
% update all the involved variables
uvms = UpdateTransforms(uvms);
uvms = ComputeJacobians(uvms);
uvms = ComputeTaskReferences(uvms);
uvms = ComputeActivationFunctions(uvms, mission);
uvms.t = t;
mission.current_time = t;
if ~coordSchema
% Exercise 5
% the sequence of iCAT_task calls defines the priority
[uvms] = taskSequence(uvms, mission);
else
% Exercise 6 - Arm-Vehicle Coordination Scheme
if mission.phase == 1
% the sequence of iCAT_task calls defines the priority
[uvms] = taskSequence(uvms, mission);
else
% save the current vehicle velocity in a constant variable
current_v = uvms.p_dot;
% TPIK 1
[uvms] = taskSequence(uvms, mission);
v1 = uvms.p_dot;
% TPIK 2
[uvms] = taskSequence(uvms, mission, current_v);
q_dot2 = uvms.q_dot;
% get the two variables for integration
uvms.q_dot = q_dot2;
% sinusoidal velocity disturbance wrt world frame
a_x = 0.5; % amplitude of the sine along x
a_y = 0.5; % amplitude of the sine along y
w = pi; % frequency of the sine
disturbance = sin(w*t)*[a_x a_y 0 0 0 0]';
% sinusoidal velocity disturbance wrt vehicle frame
disturbance_v = [uvms.vTw(1:3,1:3) zeros(3); ...
zeros(3) uvms.vTw(1:3,1:3)]*disturbance;
uvms.p_dot = v1 + disturbance_v;
end
end
% Integration
uvms.q = uvms.q + uvms.q_dot*deltat;
% beware: p_dot should be projected on <v>
uvms.p = integrate_vehicle(uvms.p, uvms.p_dot, deltat);
% check if the mission phase should be changed
[uvms, mission,plt] = UpdateMissionPhase(uvms, mission, plt);
% send packets to Unity viewer
SendUdpPackets(uvms,wuRw,vRvu,uArm,uVehicle);
% collect data for plots
plt = UpdateDataPlot(plt,uvms,t,loop, mission);
loop = loop + 1;
% add debug prints here
if (mod(t,0.1) == 0 && ~(plt.goalreached))
disp(['Time: ',num2str(t)]);
disp(['Phase: ',num2str(mission.phase)]);
disp(['Vehicle position: ',num2str(uvms.p')]);
disp('- - - - - - - - -');
end
% enable this to have the simulation approximately evolving like real
% time. Remove to go as fast as possible
SlowdownToRealtime(deltat);
end
fclose(uVehicle);
fclose(uArm);
PrintPlot(plt);
%end |
import React from "react";
import { nanoid } from 'nanoid'
import PropTypes from 'prop-types';
import styled from "styled-components";
const StyledFilter = styled.div`
display: flex;
flex-direction: column;
margin-left: 50px;
margin-bottom: 20px;
label {
font-weight: 500;
margin-bottom: 8px;
}
input {
width: 200px;
border: 1px solid silver;
border-radius: 4px;
&:hover,
&:focus {
outline: none;
border: 1px solid skyblue;
}
}
`
export function Filter({ inputChangeHandler, filterValue }) {
const filterInpudId = nanoid();
return (
<StyledFilter>
<label htmlFor={filterInpudId}>Find contacts by name </label>
<input
type="text"
name="filter"
id={filterInpudId}
pattern="^[a-zA-Zа-яА-Я]+(([' -][a-zA-Zа-яА-Я ])?[a-zA-Zа-яА-Я]*)*$"
title="Name may contain only letters, apostrophe, dash and spaces. For example Adrian, Jacob Mercer, Charles de Batz de Castelmore d'Artagnan"
value={filterValue}
onChange={inputChangeHandler}
/>
</StyledFilter>
)
}
Filter.propTypes = {
inputChangeHandler: PropTypes.func.isRequired,
filterValue: PropTypes.string.isRequired,
} |
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Services\PayUService\Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;
class User_Controller extends Controller
{
public function register(Request $request)
{
try {
$fields = $request->validate([
"name" => "required|string",
"email" => "required|string|unique:users,email",
"password" => "required|string|confirmed"
]);
$new_user = User::create([
'name'=>$fields['name'],
'email'=>$fields['email'],
'password'=>bcrypt($fields['password']),
]);
$token = $new_user->createToken("myapptoken")->plainTextToken;
return response()->json(["message"=>"User Created","payload"=>$token],201);
} catch (\Exception $error) {
throw $error;
}
}
public function login(Request $request) {
try {
$fields = $request->validate([
'email' => 'required|string',
'password' => 'required|string'
]);
// Check email
$user = User::where('email', $fields['email'])->first();
// Check password
if(!$user || !Hash::check($fields['password'], $user->password)) {
return response(["message" => "Bad creds"], 401);
}else{
$token = $user->createToken('myapptoken')->plainTextToken;
return response()->json(["message"=>"User Logged in","payload"=>$token], 200);
}
} catch (\Exception $error) {
throw $error;
}
}
public function logout(Request $request) {
try {
auth()->user()->tokens()->delete();
return [
'message' => 'Logged out'
];
} catch (\Exception $error) {
throw $error;
}
}
} |
import {Component, EventEmitter, Input, Output} from "@angular/core";
import {V1x1Module} from "../../model/v1x1_module";
import {V1x1ConfigurationDefinition} from "../../model/v1x1_configuration_definition";
import {ConfigurableComponent} from "./configurable";
import {V1x1Api} from "../../services/api";
import {V1x1ApiCache} from "../../services/api_cache";
import {V1x1Configuration} from "../../model/v1x1_configuration";
import {V1x1ConfigurationDefinitionField} from "../../model/v1x1_configuration_definition_field";
import {JsonConvert} from "json2typescript";
@Component({
selector: 'configuration-scope',
template: `
<div class="card-container">
<form>
<mat-card>
<mat-card-header>
<mat-card-title><h1>{{v1x1Module.displayName}}</h1></mat-card-title>
<mat-card-subtitle>{{v1x1Module.description}}</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
<configuration-field *ngIf="scope !== 'tenant'"
[field]="overrideField" [complexFields]="{}"
[originalConfiguration]="originalEnabled"
[activeTenant]="activeTenant" [activeChannelGroup]="activeChannelGroup" [activeChannel]="activeChannel"
[configuration]="enabled" (configurationChange)="setEnabled($event)"></configuration-field>
<configuration-field *ngFor="let field of configurationDefinition.fields"
[field]="field" [complexFields]="configurationDefinition.complexFields"
[originalConfiguration]="originalConfiguration[field.jsonField]"
[activeTenant]="activeTenant" [activeChannelGroup]="activeChannelGroup" [activeChannel]="activeChannel"
[configuration]="configuration[field.jsonField]" (configurationChange)="setConfigField(field.jsonField, $event)"></configuration-field>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="primary" *ngIf="configDirty()" (click)="saveChanges()">Save Changes</button>
<button mat-raised-button color="accent" *ngIf="configDirty()" (click)="abandonChanges()">Abandon Changes</button>
</mat-card-actions>
</mat-card>
</form>
</div>
`
})
export class ConfigurationScopeComponent extends ConfigurableComponent {
@Input() public v1x1Module: V1x1Module;
@Input() public configurationDefinition: V1x1ConfigurationDefinition;
@Input() public scope: string;
@Input() public enabled: boolean;
@Output() public enabledChange = new EventEmitter();
@Input() public originalEnabled: boolean;
@Output() public originalEnabledChange = new EventEmitter();
public json = JSON;
public overrideField = JsonConvert.deserializeObject({
display_name: "Override?",
description: "This controls whether this overrides the settings in Everything.",
default_value: "null",
config_type: "MASTER_ENABLE",
requires: [],
tenant_permission: "READ_WRITE",
json_field: "enabled",
complex_type: null
}, V1x1ConfigurationDefinitionField);
constructor(private cachedApi: V1x1ApiCache, private api: V1x1Api) {
super();
}
saveChanges() {
if(this.scope === 'tenant')
this.api.putTenantConfiguration(this.activeTenant.id, this.v1x1Module.name, new V1x1Configuration(true, this.configuration))
.subscribe(v1x1Config => {
this.originalConfigurationValue = JSON.parse(JSON.stringify(v1x1Config.configuration));
this.originalConfigurationChange.emit(this.originalConfigurationValue);
this.configDirtyChange.emit(this.configDirty());
});
else if(this.scope === 'channelGroup')
this.api.putChannelGroupConfiguration(this.activeTenant.id, this.v1x1Module.name, this.activeChannelGroup.platform, this.activeChannelGroup.id, new V1x1Configuration(this.enabled, this.configuration))
.subscribe(v1x1Config => {
this.originalEnabled = v1x1Config.enabled;
this.originalEnabledChange.emit(this.originalEnabled);
this.originalConfigurationValue = JSON.parse(JSON.stringify(v1x1Config.configuration));
this.originalConfigurationChange.emit(this.originalConfigurationValue);
this.configDirtyChange.emit(this.configDirty());
});
else if(this.scope === 'channel')
this.api.putChannelConfiguration(this.activeTenant.id, this.v1x1Module.name, this.activeChannelGroup.platform, this.activeChannelGroup.id, this.activeChannel.id, new V1x1Configuration(this.enabled, this.configuration))
.subscribe(v1x1Config => {
this.originalEnabled = v1x1Config.enabled;
this.originalEnabledChange.emit(this.originalEnabled);
this.originalConfigurationValue = JSON.parse(JSON.stringify(v1x1Config.configuration));
this.originalConfigurationChange.emit(this.originalConfigurationValue);
this.configDirtyChange.emit(this.configDirty());
});
else
this.acceptChanges();
}
setEnabled(enabled: boolean) {
this.enabled = enabled;
this.enabledChange.emit(enabled);
this.configChanged();
}
configDirty(): boolean {
return super.configDirty() || this.enabled !== this.originalEnabled;
}
abandonChanges(): void {
this.enabled = this.originalEnabled;
this.enabledChange.emit(this.enabled);
super.abandonChanges();
}
} |
{% extends "base.html" %}
{% block title %}Новый пост{% endblock %}
{% block content %}
<div class="container py-5">
<div class="row justify-content-center">
<div class="col-md-8 p-5">
<div class="card">
<div class="card-header">
{% if post %}
Редактировать запись
{% else %}
Добавить запись
{% endif %}
</div>
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
{{ error|escape }}
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
{{ error|escape }}
</div>
{% endfor %}
{% endif %}
<div class="card-body">
<form method="post"
action="{% if post %}
{% url 'posts:post_edit' post_id=post.id %}
{% else %}
{% url 'posts:post_create' %}
{% endif %}"
enctype="multipart/form-data">
{% csrf_token %}
{% load user_filters %}
{% for field in form %}
<div class="form-group row my-3 p-3">
<label for="id_text">
{{ field.label }}
<span class="required text-danger">*</span>
</label>
{{ field|addclass:"form-control" }}
<small id="id_text-help" class="form-text text-muted">
{{ field.help_text }}
</small>
</div>
{% endfor %}
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-primary">
{% if post %}
Сохранить
{% else %}
Добавить
{% endif %}
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %} |
<template>
<div class="col-12 col-md-7">
<div class="get-in-get-touch" data-aos="fade" data-aos-once="true">
<h4 class="them-title" v-if="data.title">{{data.title}}</h4>
<!--p v-if="data.description">{{data.description}}</p-->
<form>
<div class="form-floating mb-4">
<input
type="text"
v-model="name"
@blur="nameValid()"
:class="validName ? 'form-control custom-input' : 'form-control custom-input warning-border'"
id="name"
placeholder="Insira o nome"
/>
<label class="custom-label" for="name">Introduza o nome</label>
<span class="warning" v-if="!validName">O nome é obrigatório*</span>
</div>
<div class="form-floating mb-4">
<input
type="email"
:class="validEmail ? 'form-control custom-input' : 'form-control custom-input warning-border'"
@blur="emailValid()"
v-model="email"
id="email"
placeholder="Digite o e-mail"
/>
<label class="custom-label" for="email">Introduza o e-mail</label>
<span class="warning" v-if="!validEmail">Digite um endereço de e-mail válido*</span>
</div>
<div class="form-floating mb-4">
<input
type="text"
v-model="subject"
@blur="subjectValid()"
:class="validSubject ? 'form-control custom-input' : 'form-control custom-input warning-border'"
id="subject"
placeholder="Sujeito"
/>
<label class="custom-label" for="subject">Assunto</label>
<span class="warning" v-if="!validSubject">O assunto é obrigatório*</span>
</div>
<div class="form-floating mb-4">
<textarea
:class="validMessage ? 'form-control custom-input textarea-height' : 'form-control custom-input textarea-height warning-border'"
@blur="messageValid()"
v-model="message"
placeholder="Digite sua mensagem"
rows="3"
id="Message"
></textarea>
<label class="custom-label" for="Message">Introduza a sua mensagem</label>
<span class="warning" v-if="!validMessage">A mensagem é obrigatória*</span>
</div>
<div class="theme-btn universal-btn" id="button-3">
<div id="circle"></div>
<nuxt-link to>
<button type="submit" @click="dataSubmit">
<span>
Enviar
<i class="fal fa-arrow-right"></i>
</span>
</button>
</nuxt-link>
</div>
</form>
</div>
</div>
</template>
<script>
import api from '../../services'
export default {
props: ['data'],
data() {
return {
name: '',
email: '',
subject: '',
message: '',
formData: {},
validData: true,
validName: true,
validEmail: true,
validSubject: true,
validMessage: true,
}
},
methods: {
async dataSubmit() {
this.messageValid()
this.subjectValid()
this.emailValid()
this.nameValid()
if (
this.validMessage &&
this.validSubject &&
this.validEmail &&
this.validName
) {
this.formData = {
email: this.email,
name: this.name,
subject: this.subject,
message: this.message,
}
const data = await api.product.contact(this.formData)
this.formReset()
this.$toasted.show('Sucesso!', {
position: 'top-center',
duration: 3000
})
} else {
this.$toasted.show('Erro ao enviar dados', {
position: 'top-center',
duration: 3000
})
}
},
nameValid() {
if (this.name === '') {
this.validName = false
} else {
this.validName = true
}
},
emailValid() {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(this.email)) {
this.validEmail = true
} else {
this.validEmail = false
}
},
subjectValid() {
if (this.subject === '') {
this.validSubject = false
} else {
this.validSubject = true
}
},
messageValid() {
if (this.message === '') {
this.validMessage = false
} else {
this.validMessage = true
}
},
formReset() {
this.name = ''
this.email = ''
this.subject = ''
this.message = ''
},
},
}
</script>
<style lang="scss" scoped>
$them-color: #fd5044;
.contact-us.contact-label {
width: 100%;
background-color: #f9fbfc;
form .form-floating > .custom-input:focus ~ .custom-label,
form .form-floating > .custom-input:not(:placeholder-shown) ~ .custom-label,
form .form-floating > .form-select ~ .custom-label {
opacity: 1;
transform: scale(0.85) translateY(-11px) translateX(0.8rem) !important;
color: #6a6a6a !important;
background-color: #ffffff;
height: 26px;
color: #686868;
font-size: 16px;
padding: 0;
}
.textarea-height {
height: 110px !important;
resize: none;
padding-top: 16px !important;
}
label.custom-label {
padding: 13px 10px;
font-size: 15px;
color: #686868;
}
.contact-us-bg-img {
background: linear-gradient(0deg, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8)),
url(~assets/images/contact-us-bg-img.jpg);
background-repeat: no-repeat;
background-size: cover;
position: relative;
height: 100%;
z-index: 1;
padding: 45px 40px;
border-radius: 5px;
.contact-us-content {
width: 100%;
h4 {
text-transform: uppercase;
margin-bottom: 40px;
}
.office-information {
padding-left: 0px;
margin-bottom: 0;
li {
margin-bottom: 32px;
}
p {
margin-bottom: 0;
font-size: 18px;
line-height: 30px;
font-weight: 400;
color: #fff;
transition: all 0.3s ease-in-out;
}
a {
transition: all 0.3s ease-in-out;
color: #fff;
}
& li:hover a {
color: $them-color !important;
}
& li:hover a p {
color: $them-color !important;
}
i {
font-size: 30px;
}
}
}
}
.get-in-get-touch {
border: 1px solid #b3b3b3;
border-radius: 5px;
padding: 40px;
margin-left: 60px;
background: #ffffff;
p {
font-size: 15px;
font-weight: 400;
color: #000;
line-height: 26px;
margin-bottom: 0;
padding-bottom: 30px;
}
}
}
section.contact-images {
width: 100%;
padding: 60px 0px;
ul.d-flex.justify-content-between {
padding-left: 0;
margin-bottom: 0;
img {
opacity: 0.6;
transition: all 0.3s ease-in-out;
&:hover {
opacity: 1;
}
}
}
}
#button-3 a {
padding: 0 !important;
}
</style> |
---
title: "NBA 4920/6921 Lecture 14"
subtitle: "Lasso Regression Application"
author: "Murat Unal"
date: "10/19/2021"
output:
beamer_presentation:
colortheme: beaver
df_print: kable
fig_height: 3
fig_width: 5
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(comment = '',
warning = FALSE,
message = FALSE)
```
------------------------------------------------------------------------
```{r message=FALSE, warning=FALSE}
rm(list=ls())
options(digits = 3, scipen = 999)
library(ggplot2)
library(tidyverse)
library(ISLR)
library(jtools)
library(caret)
library(leaps)
library(glmnet)
Hitters <- ISLR::Hitters
Hitters <- na.omit(Hitters)
set.seed(2)
```
# Ridge Regression
```{r}
x=model.matrix(Salary~.,Hitters)[,-1]
y=Hitters$Salary
```
- The __model.matrix()__ function is particularly useful for creating x; not only does it produce a matrix corresponding to the 19 predictors but it also
automatically transforms any qualitative variables into dummy variables.
- The latter property is important because __glmnet()__ can only take numerical,
quantitative inputs.
***
- The __glmnet()__ engine has an `alpha` argument that determines what type of model is fit.
- If `alpha=0` then a ridge regression model is fit, and if `alpha=1` then a lasso model is fit. We first fit a ridge regression model.
- By default, the __glmnet()__ engine standardizes the variables so that they are on the same scale.
***
- __glmnet()__ will fit ridge models across a wide range of $\lambda$
values by default, 100 $\lambda$ values that are data derived
- We could also run the engine for a grid of 100 values ranging from high to low $\lambda$
```{r}
grid=10^seq(10,-2,length=100)
grid[1]
grid[100]
```
***
- For regression problems set `familty="gaussian"`, and `familty="binomial"` for classification
```{r}
ridge.mod=glmnet(x,y,alpha=0,lambda=grid,family="gaussian")
names(ridge.mod)
```
***
- Associated with each value of $\lambda$ is a vector of ridge regression coefficients, stored in a matrix that can be accessed by `coef()`.
- In this case, it is a __20×100__ matrix, with 20 rows (one for each predictor, plus an intercept) and 100 columns (one for each value of $\lambda$ ).
```{r}
dim(coef(ridge.mod))
```
***
- As $\lambda$grows larger, our ridge regression coefficient magnitudes are more constrained.
```{r}
plot(ridge.mod, xvar = "lambda")
```
***
```{r}
#Display 1st lambda value
ridge.mod$lambda[1]
# Display coefficients associated with
# 1st lambda value
coef(ridge.mod)[,1]
```
***
- We can use the `predict()` function for a number of purposes. For instance, we can obtain the ridge regression coefficients for a new value of $\lambda$ , say 50:
- If the desired $\lambda$ value is not included in the initial fit, then `glmnet()` performs linear interpolation to make predictions for the desired $\lambda$ value.
- Linear interpolation usually works fine, but we could change this by calling `exact=TRUE`. This way predictions are to be made at values of $\lambda$ not included in the original fit and the model is refit before predictions are made.
***
- Let's check if $\lambda=50$ is used in the original fit
```{r}
any(ridge.mod$lambda==50)
```
- Let's see if there's any difference
```{r}
coef.approax <- predict(ridge.mod, s = 50, type = "coefficients",
exact = FALSE)
coef.exact <- predict(ridge.mod, s = 50, type = "coefficients",
exact = TRUE, x=x,y=y)
cbind(coef.approax, coef.exact)
```
***
- Let's now split the samples into a training set and a test set in order
to estimate the test error of ridge regression
```{r}
train=sample(1:nrow(x), 0.7*nrow(x))
```
***
- Next we fit a ridge regression model on the training set, and evaluate
its RMSE on the test set, using $\lambda = 4$.
- Note the use of the `predict()`
function again.
- This time we get predictions for a test set, by replacing
`type="coefficients"` with the `newx` argument
```{r}
ridge.mod=glmnet(x[train,],y[train],alpha=0,lambda=grid)
ridge.pred.lambda4=predict(ridge.mod,s=4,newx=x[-train,])
rmse.ridge.lambda4 = sqrt(mean((ridge.pred.lambda4-
y[-train])^2))
rmse.ridge.lambda4
```
***
- Note that if we had instead simply fit a model
with just an intercept, we would have predicted each test observation using
the mean of the training observations.
- In that case, we could compute the
test set MSE like this:
```{r}
sqrt(mean((mean(y[train])-y[-train])^2))
```
***
- We could also get the same result by fitting a ridge regression model with
a very large value of $\lambda$. Note that 1e10 means $10^{10}$
```{r}
ridge.pred.lambdabig=predict(ridge.mod,s=1e10,
newx=x[-train,])
rmse.ridge.lambdabig <- sqrt(mean((ridge.pred.lambdabig-
y[-train])^2))
rmse.ridge.lambdabig
```
***
- So fitting a ridge regression model with $\lambda = 4$ leads to a much lower -train RMSE than fitting a model with just an intercept.
- Let's now check whether
there is any benefit to performing ridge regression with $\lambda = 4$ instead of
just performing least squares regression.
***
- Recall that least squares is simply
ridge regression with $\lambda = 0$
```{r}
ridge.pred.lambda0=predict(ridge.mod,s=0,exact = TRUE,
x=x[train,],y=y[train],newx=x[-train,])
rmse.ridge.lambda0 <- sqrt(mean((ridge.pred.lambda0-
y[-train])^2))
rmse.ridge.lambda0
```
- It looks like we are indeed improving over regular least-squares!
# Cross-validation
- Instead of arbitrarily choosing $\lambda = 4$ , it would be better to use cross-validation to choose the tuning parameter $\lambda$.
- We can do this by writing our own function as we did before or we could just use the built-in cross-validation function, `cv.glmnet()`.
- By default, the function performs `10-fold` cross-validation, though this can be changed using the argument `folds`.
- We can define the loss used for cross-validation using `type.measure`
```{r}
cv.out=cv.glmnet(x[train,],y[train],alpha=0,nfold=10,
type.measure="mse")
bestlam=cv.out$lambda.min
bestlam
```
***
- The first vertical dashed line gives the value of $\lambda$ that gives minimum mean cross-validated error. The second is the $\lambda$ that gives an MSE within one standard error of the smallest.
```{r}
plot(cv.out)
```
***
- Finally, we obtain the coefficients from our fitted model
using the value of $\lambda$ chosen by cross-validation.
- As expected, none of the coefficients are zero—ridge regression does not
perform variable selection!
```{r}
predict(ridge.mod,type ="coefficients",s=bestlam,
exact=TRUE, x=x[train,], y=y[train])
```
***
```{r}
final.pred = predict(ridge.mod, newx=x[-train,],s=bestlam,
exact=TRUE,x=x[train,],y=y[train])
rmse.ridge.lambdabest <- sqrt(mean((y[-train]-
final.pred)^2))
rmse.ridge.lambdabest
```
***
- Let's compare all test RMSEs:
```{r}
RMSE <- matrix(NA,ncol = 1, nrow = 8)
rownames(RMSE) <- c("rmse.ridge.lambdabig",
"rmse.ridge.lambda4","rmse.ridge.lambda0",
"rmse.ridge.lambdabest","rmse.lasso.lambda1se",
"rmse.lasso.lambdabest", "rmse.elnet.lambda1se",
"rmse.elnet.lambdabest")
RMSE[1:4,1] <- c(rmse.ridge.lambdabig,
rmse.ridge.lambda4,rmse.ridge.lambda0,
rmse.ridge.lambdabest)
RMSE
```
- Ridge regression indeed obtains the minimum test RMSE!
***
- Rdige regression for median $\lambda$ value
```{r}
median(grid)
# Set s=median(grid) and make predictions
ridge.pred.lambdamedian=predict(ridge.mod,s=10098,
newx=x[-train,])
rmse.ridge.lambdamedian<-sqrt(mean((ridge.pred.lambdamedian-
y[-train])^2))
rmse.ridge.lambdamedian
```
# Lasso
- We saw that ridge regression with a choice of $\lambda$ can outperform least
squares as well as the null model on the Hitters data set.
- We now ask
whether the lasso can yield either a more accurate or a more interpretable
model than ridge regression.
- We once again
use the __glmnet()__; however, this time we use the argument $\alpha=1$.
- Other than that change, we proceed just as we did in fitting a ridge model.
***
- Let's run a lasso regression using the previous grid values for $\lambda$
and call it __lasso.mod__
```{r }
lasso.mod=glmnet(x[train,],y[train],alpha=1,lambda=grid)
```
***
- Let's plot the coefficients against the lambdas
```{r }
plot(lasso.mod, xvar = "lambda")
```
- We can see from the coefficient plot that depending on the choice of tuning
parameter, some of the coefficients will be exactly equal to zero.
# Cross-validation
- Let's do 10-fold cross-validation and save the output to __lasso.cv__.
```{r }
lasso.cv=cv.glmnet(x[train,],y[train],alpha=1,
nfold=10,type.measure="mse")
```
***
- Now plot __lasso.cv__.
- What is the size of the model that has min $\lambda$ and the one that has $\lambda$ that is within one standard error of the minimum?
```{r }
plot(lasso.cv)
```
***
- Let's do prediction on the test cases using both values of $\lambda$, __lambda.min__ and __lambda.1se__, the value of $\lambda$ that gives the most regularized model such that the cross-validated error is within one standard error of the minimum.
- Save the outputs as __lasso.lambdabest__ and __lasso.lambda1se__
```{r }
lasso.lambdabest=predict(lasso.cv,s=lasso.cv$lambda.min,
newx=x[-train,])
lasso.lambda1se=predict(lasso.cv,s=lasso.cv$lambda.1se,
newx=x[-train,])
```
***
- Compute RMSE of the predictions
```{r }
rmse.lasso.lambdabest <- sqrt(mean((lasso.lambdabest-
y[-train])^2))
rmse.lasso.lambda1se <- sqrt(mean((lasso.lambda1se-
y[-train])^2))
RMSE[5:6,1] <- c(rmse.lasso.lambda1se,rmse.lasso.lambdabest)
```
***
- Model performance across models
```{r }
RMSE
```
***
- This is substantially lower than the test set RMSE of the null model and of least squares, however it's larger than the test RMSE of ridge regression with $\lambda$ chosen by cross-validation
***
- Let's see which variables are selected by lasso.
- Call the __predict__ function on __lasso.cv__ and use `s=lasso.cv$lambda.min` and `type="coefficients"`
```{r}
lasso.coef=predict(lasso.cv,s=lasso.cv$lambda.min,
type="coefficients")[1:20,]
lasso.coef[lasso.coef!=0]
```
***
- However, the lasso has a substantial advantage over ridge regression in
that the resulting coefficient estimates are sparse. Here we see that `r length(lasso.coef[lasso.coef==0])` of
the 19 coefficient estimates are exactly zero.
- So the lasso model with $\lambda$
chosen by cross-validation contains only `r length(lasso.coef[lasso.coef!=0])-1` variables. |
# -*- coding: utf-8 -*-
import json
import scrapy
from unsplash.items import ImageItem
class UnsplashImageSpider(scrapy.Spider):
name = 'unsplash_image'
allowed_domains = ['unsplash.com']
# 定义起始页面
start_urls = ['https://unsplash.com/napi/photos?page=1&per_page=12']
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.page_index = 1
def parse(self, response):
# 解析服务器响应的JSON字符串
photo_list = json.loads(response.text) # ①
# 遍历每张图片
for photo in photo_list:
item = ImageItem()
item['image_id'] = photo['id']
item['download'] = photo['links']['download']
yield item
self.page_index += 1
# 获取下一页的链接
next_link = 'https://unsplash.com/napi/photos?page=' + str(self.page_index) + '&per_page=12'
# 继续获取下一页的图片
yield scrapy.Request(next_link, callback=self.parse) |
<?php
/**
* More specialized comparisons are used for specific argument types
* for $expected and $actual, see below.
* assertEquals(float $expected, float $actual[, string $message = '', float $delta = 0])
* Reports an error identified by $message if the two floats $expected and
* $actual are not within $delta of each other.
* Please read "What Every Computer Scientist Should Know About Floating-Point Arithmetic"
* to understand why $delta is neccessary.
*
*/
class FloatEqualsTest extends PHPUnit_Framework_TestCase
{
public function testSuccess()
{
$this->assertEquals(1.0, 1.1, '', 0.2);
}
public function testFailure()
{
$this->assertEquals(1.0, 1.1);
}
}
?> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.