text
stringlengths 184
4.48M
|
---|
% Domantas Keturakis
% PS III kursas, I gr.
%
% Užduotis:
% 14. [S] Žaidimas "Kryžiukai-nuliukai".
% Duota stačiakampių langelių lenta iš N eilučių ir M stulpelių (N ir M duoti). Kai kurie iš langelių užpildyti kryžiukais arba nuliukais. Kad laimėtų, komandai reikia iš eilės sudėlioti K (duotas) simbolių. Nustatykite, kaip nuliukai dviem ėjimais laimi prieš kryžiukus.
% [I, J] | [R, C] | [N, M]
% Y axis: I, R, N
% X axis: J, C, M
:- module(main, [standard_board/3, allTrans/3, chain/4, win/3]).
:- use_module(library(clpfd)).
:- use_module(library(lists)).
:- use_module(matrix).
:- use_module(list).
:- use_module(line).
todo() :- fail.
cell(o). % occupied by O
cell(x). % occupied by X
cell(e). % empty
standard_board([
[e, e, e],
[e, e, e],
[e, e, e]
], N, M) :- N #= 3, M #= 3.
write_line([]) :- write('\n').
write_line([o|Ls]) :- write('O '), write_line(Ls).
write_line([x|Ls]) :- write('X '), write_line(Ls).
write_line([e|Ls]) :- write('. '), write_line(Ls).
write_board([]) :- write('\n').
write_board([B|Bs]) :- write_line(B), write_board(Bs).
write_states([]).
write_states([B|Ls]) :- write_board(B), write_states(Ls).
% state transitions
prevL_nextL_index_prevEl_nextEl([PrevEl|Ls], [NextEl|Ls], 0, PrevEl, NextEl).
prevL_nextL_index_prevEl_nextEl([E|PrevL], [E|NextL], I, PrevEl, NextEl) :-
prevL_nextL_index_prevEl_nextEl(PrevL, NextL, I1, PrevEl, NextEl), I1 #= I - 1.
transL(Ps, Ns, I, P, N) :- prevL_nextL_index_prevEl_nextEl(Ps, Ns, I, P, N).
transM(Ps, Ns, [I, J], P, N) :-
transL(Ps, Ns, I, Pl, Nl),
transL(Pl, Nl, J, P, N).
?- transM([[a,a], [a,a]], [[a,a], [a,b]], [1,1], a, b).
?- matrix_dim_fill(B1, [4, 3], e),
transM(B1,B2, [1,1], e, o),
matrix_index_elem(B2, [1,1], o).
% Px - Previous matriX
% Nx - Next matriX
trans(Px, Nx, o) :- transM(Px, Nx, [_, _], e, o).
trans(Px, Nx, x) :- transM(Px, Nx, [_, _], e, x).
allTrans(Px, Nxs, o):- findall(Nx, trans(Px, Nx, o), Nxs).
allTrans(Px, Nxs, x):- findall(Nx, trans(Px, Nx, x), Nxs).
opposite(x, o).
opposite(o, x).
% Mx - Start board
% Ex - end state
% Lx - list of states
% S - a side for which a trun is taken (either x or o)
chain(Ex, Ex, [Ex], _).
chain(Mx, Ex, [Mx|Ls], S) :-
trans(Mx, Sx, S),
opposite(S, O),
chain(Sx, Ex, Ls, O),
Mx \= Ex.
win(Board, K, S) :-
matrix_length_line(Board, K, Lines),
list_length_fill(Lines, K, S).
% example query:
%?- Board = [
% [e, e, e, e],
% [e, e, o, x],
% [e, e, e, e]
% ],
% chain(Board, WinForO, States, o),
% length(States, 4),
% win(WinForO,3, o),
%
% write_states(States). |
package com.stelmah.example.leetcode;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class Task10 {
@Test
void example1() {
var s = "aa";
var p = "a";
Assertions.assertEquals(false, isMatch(s, p));
}
@Test
void example2() {
var s = "aa";
var p = "a*";
Assertions.assertEquals(true, isMatch(s, p));
}
@Test
void example3() {
var s = "aa";
var p = ".*";
Assertions.assertEquals(true, isMatch(s, p));
}
@Test
void example4() {
var s = "a";
var p = "ab*";
Assertions.assertEquals(true, isMatch(s, p));
}
@Test
void example5() {
var s = "aaba";
var p = "ab*a*c*a";
Assertions.assertEquals(false, isMatch(s, p));
}
@Test
void example6() {
var s = "mississippi";
var p = "mis*is*ip*.";
Assertions.assertEquals(true, isMatch(s, p));
}
@Test
void example7() {
var s = "aaa";
var p = ".*";
Assertions.assertEquals(true, isMatch(s, p));
}
public boolean isMatch(String s, String p) {
if (s.isEmpty() && p.isEmpty()) {
return true;
}
var firstCharMatch = false;
if (s.length() >= 1 && p.length() >= 1) {
firstCharMatch = (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.');
}
if (s.length() == 1 && p.length() == 1) {
return firstCharMatch;
}
if (p.isEmpty() && !s.isEmpty()) {
return false;
}
if (p.length() >= 2 && p.charAt(1) == '*') {
return (isMatch(s, p.substring(2))) || (firstCharMatch && s.length() > 0 && isMatch(s.substring(1),
p));
} else {
return firstCharMatch && isMatch(s.substring(1), p.substring(1));
}
}
} |
/**
* Teleport
* Copyright (C) 2024 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';
import styled from 'styled-components';
import { Box, Flex, Text } from 'design';
import { pluralize } from 'shared/utils/text';
import { AssumedRequest } from 'teleterm/services/tshd/types';
import { useAssumedRolesBar } from './useAssumedRolesBar';
export function AssumedRolesBar({ assumedRolesRequest }: Props) {
const {
duration,
assumedRoles,
dropRequest,
dropRequestAttempt,
hasExpired,
} = useAssumedRolesBar(assumedRolesRequest);
const roleText = pluralize(assumedRoles.length, 'role');
const durationText = `${roleText} assumed, expires in ${duration}`;
const hasExpiredText =
assumedRoles.length > 1 ? 'have expired' : 'has expired';
const expirationText = `${roleText} ${hasExpiredText}`;
const assumedRolesText = assumedRoles.join(', ');
return (
<Box
px={3}
py={2}
bg="brand"
borderTop={1}
css={`
border-color: ${props => props.theme.colors.spotBackground[1]};
`}
>
<Flex justifyContent="space-between" alignItems="center">
<Flex alignItems="center">
<Box
borderRadius="20px"
py={1}
px={3}
mr={2}
color="text.primary"
bg="text.primaryInverse"
style={{
fontWeight: '500',
overflow: 'hidden',
textOverflow: 'ellipsis',
maxWidth: '200px',
whiteSpace: 'nowrap',
}}
title={assumedRolesText}
>
{assumedRolesText}
</Box>
<Text typography="body" color="text.primaryInverse">
{hasExpired ? expirationText : durationText}
</Text>
</Flex>
<StyledButtonLink
onClick={dropRequest}
disabled={dropRequestAttempt.status === 'processing'}
>
Drop Request
</StyledButtonLink>
</Flex>
</Box>
);
}
type Props = {
assumedRolesRequest: AssumedRequest;
};
const StyledButtonLink = styled.button`
color: ${props => props.theme.colors.text.primaryInverse};
background: none;
text-decoration: underline;
text-transform: none;
padding: 8px;
outline: none;
border: none;
border-radius: 4px;
font-family: inherit;
&:hover,
&:focus {
background: ${props => props.theme.colors.spotBackground[1]};
cursor: pointer;
}
&:disabled {
background: ${props => props.theme.colors.spotBackground[0]};
color: ${props => props.theme.colors.text.disabled};
}
`; |
package com.example.backend.model.genre;
import lombok.*;
import java.util.Set;
import java.util.HashSet;
import java.util.Objects;
import jakarta.persistence.*;
import com.example.backend.model.game.Game;
import com.fasterxml.jackson.annotation.JsonBackReference;
@Data
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Entity(name="Genre")
@Table(name = "genres")
public class Genre {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "genre_id", updatable = false)
private Long genreId;
@Column (name = "genre_description")
private String description;
@Enumerated(EnumType.STRING)
@Column (name = "genre_name", nullable = false)
private EGenreName genreName;
public Genre(final String description, final EGenreName genreName) {
this.description = description;
this.genreName = genreName;
}
@ManyToMany(mappedBy = "genres")
@JsonBackReference
@Builder.Default
private Set<Game> games = new HashSet<>();
public void addGame(final Game game) {
this.games.add(game);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Genre otherGenre = (Genre) o;
return this.genreName.equals(otherGenre.genreName);
}
@Override
public int hashCode() {
return Objects.hash(this.genreName);
}
} |
import React, { useEffect } from "react";
import { MidiMap, invertMidiMap } from "./MidiMapping";
import { Drum } from "./Drum";
export type Message = {
command: number;
channel: number;
note: number;
drum?: Drum;
velocity: number;
timeStamp: number;
};
/**
* Utilities for accessing the MIDIInput and MIDI mapping
*/
export class MidiInput {
private static context = React.createContext<{
input: MIDIInput | undefined;
mapping: MidiMap;
}>({} as never);
/**
* Shortcut for React Context Provider
*/
public static Provider({
value,
children,
}: {
value: { input: MIDIInput; mapping: MidiMap };
children: React.ReactNode;
}) {
useEffect(() => {
const invertedMidiMap = invertMidiMap(value.mapping);
if (!value.input) return;
const onMessage = (event: MIDIMessageEvent) => {
const [num, note, velocity] = event.data!;
const command = num >> 4;
const channel = num & 0xf;
MidiInput.messageListeners.forEach((fn) => {
fn({
command,
channel,
note,
drum: invertedMidiMap[note] ?? undefined,
velocity,
timeStamp: event.timeStamp,
});
});
};
value.input.onmidimessage = onMessage;
return () => {
if (value.input.onmidimessage === onMessage) {
value.input.onmidimessage = null;
}
};
}, [value]);
return (
<MidiInput.context.Provider value={value}>
{children}
</MidiInput.context.Provider>
);
}
public static messageListeners = new Set<(message: Message) => void>();
public static useOnMessage(fn: (message: Message) => void, deps: any[] = []) {
useEffect(() => {
this.messageListeners.add(fn);
return () => {
this.messageListeners.delete(fn);
};
}, deps);
}
} |
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
*/
package com.mycompany.ujicobapisahclasslat1;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
/**
*
* @author ASUS
*/
public class UjiCobaPisahClassLat1 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection connection = KonekClass.dptKonek();
if (connection != null){
try{
Statement st = connection.createStatement();
System.out.println("Koneksi berhasil");
try {
Scanner scanner = new Scanner(System.in);
System.out.println("Masukan data mobil baru: ");
System.out.print("Id: ");
String id = scanner.nextLine();
System.out.print("Vendor: ");
String vendor = scanner.nextLine();
System.out.print("Tipe: ");
String tipe = scanner.nextLine();
System.out.print("CC Mesin: ");
String ccMesin = scanner.nextLine();
System.out.print("Kecepatan maximal: ");
String kecMax = scanner.nextLine();
String insertQuery = "insert into mobil (id, vendor, tipe, mesin, maxSpeed) values (?, ?, ?, ?, ?)";
PreparedStatement ps = connection.prepareStatement(insertQuery);
ps.setString(1, id);
ps.setString(2, vendor);
ps.setString(3, tipe);
ps.setString(4, ccMesin);
ps.setString(5, kecMax);
int rowAffected = ps.executeUpdate();
if (rowAffected > 0) {
System.out.println("Data mobil berhasil dimasukan ke database");
} else {
System.out.println("Gagal memasukan data mobil ke database");
}
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
String query = "select * from mobil";
ResultSet rs = st.executeQuery(query);
while(rs.next()){
System.out.println("\nMobil " + rs.getString("vendor"));
System.out.println("Tipe " + rs.getString("tipe"));
System.out.println("CC Mesin " + rs.getString("Mesin"));
System.out.println("Kecepatan maksimal " + rs.getString("maxSpeed"));
}
st.close();
}
catch (SQLException e){
e.printStackTrace();
}
finally{
KonekClass.tutupKoneksi();
System.out.println("\nKoneksi ditutup....");
}
}
else{
System.out.println("Gagal terhubung ke database");
}
}
} |
const sinon = require('sinon');
const { expect } = require('chai');
const productModel = require('../../../src/models/product.model');
const connection = require('../../../src/models/connection');
const {productsMock, idMocks, id} = require('../mock/products.mock');
describe('Testa a camada model para a rota "/product"', function () {
afterEach(function () { sinon.restore() });
describe('1.Testa a camada model para a função "getAll"', function () {
it('Quando encontra todos os produtos cadastrados', async function () {
sinon.stub(connection, 'execute').resolves([productsMock]);
const response = await productModel.getAll();
expect(response).to.be.deep.equal(productsMock);
});
});
// TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) RESOLVIDO NO SLACK
describe('2.Testa a camada model para a função "getProductsById"', function () {
it('Faz a busca de um produto pelo id', async function () {
sinon.stub(connection, 'execute').resolves([[productsMock]]);
const response = await productModel.getById(id);
expect(response).to.be.equal(idMocks);
});
});
describe('3.Testa a camada model para a função "insertProduct"', function () {
it('Quando insere corretamente', async function () {
sinon.stub(connection, 'execute').resolves([{ insertId: 4 }]);
const response = await productModel.insertProduct('Lanterna');
expect(response).to.be.deep.equal({ id: 4, name: 'Lanterna' });
});
});
describe('4.Testa a camada model para a função "updateProduct"', function () {
it('Quando atualiza corretamente', async function () {
sinon.stub(connection, 'execute').resolves({ insertId: 3 });
const response = await productModel.updateProduct('Lanterna');
expect(response).to.be.deep.equal({ insertId: 3 });
});
});
}); |
import React, { createRef } from 'react';
//import "@arcgis/core/assets/esri/css/main.css";
//import "./css/ArcgisMap.css";
import { loadModules } from 'esri-loader';
var Print;
class PrintWidget extends React.Component {
/**
* Creator of the Measurement widget class
* @param {*} props
*/
constructor(props) {
super(props);
//We create a reference to a DOM element to be mounted
this.container = createRef();
//Initially, we set the state of the component to
//not be showing the basemap panel
this.state = { showMapMenu: false };
this.menuClass =
'esri-icon-printer esri-widget--button esri-widget esri-interactive';
this.titleMaxLength = 50;
this.authorMaxLength = 60;
this.textMaxLength = 180;
this.sizeMax = 15000;
this.dpiMax = 1200;
this.scaleMax = 600000000;
}
loader() {
return loadModules(['esri/widgets/Print']).then(([_Print]) => {
Print = _Print;
});
}
/**
* Method that will be invoked when the
* button is clicked. It controls the open
* and close actions of the component
*/
openMenu() {
if (this.state.showMapMenu) {
this.props.mapViewer.setActiveWidget();
this.container.current.querySelector('.right-panel').style.display =
'none';
this.container.current
.querySelector('.esri-widget--button')
.classList.remove('active-widget');
document
.querySelector('.esri-ui-top-right.esri-ui-corner')
.classList.remove('show-panel');
// By invoking the setState, we notify the state we want to reach
// and ensure that the component is rendered again
this.setState({ showMapMenu: false });
} else {
this.props.mapViewer.setActiveWidget(this);
this.container.current.querySelector('.right-panel').style.display =
'flex';
this.container.current
.querySelector('.esri-widget--button')
.classList.add('active-widget');
document
.querySelector('.esri-ui-top-right.esri-ui-corner')
.classList.add('show-panel');
// By invoking the setState, we notify the state we want to reach
// and ensure that the component is rendered again
this.setState({ showMapMenu: true });
}
}
/**
* This method is executed after the rener method is executed
*/
async componentDidMount() {
await this.loader();
this.props.view.ui.add(this.container.current, 'top-right');
this.print = new Print({
view: this.props.view,
container: this.container.current.querySelector('.print-panel'),
});
}
componentDidUpdate() {
this.setLayoutConstraints();
this.setMapOnlyConstraints();
}
/**
* Sets constrictions on text inputs
*/
setMapOnlyConstraints() {
let mapOnly = document.querySelector("[data-tab-id='mapOnlyTab']");
//If map only options are deployed, same restriction for all the text inputs
var observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.attributeName === 'aria-selected') {
let currentExpand = mutation.target.getAttribute('aria-selected');
if (currentExpand === 'true') {
this.setTextFilters();
let optSVGZ = document.querySelector("[value='svgz']");
optSVGZ && optSVGZ.parentElement.removeChild(optSVGZ);
/*let advanceOptions = document.querySelector(
'.esri-print__advanced-options-button',
);*/
let fileName = document.querySelector(
"[data-input-name='fileName']",
);
fileName.parentElement.setAttribute('style', 'display:none');
} else {
this.setLayoutConstraints();
}
}
});
});
mapOnly && observer.observe(mapOnly, { attributes: true });
}
setLayoutConstraints() {
this.setTextFilters();
let advanceOptions = document.querySelector(
'.esri-print__advanced-options-button',
);
let optSVGZ = document.querySelector("[value='svgz']");
optSVGZ && optSVGZ.parentElement.removeChild(optSVGZ);
//If advanced options are deployed, same restriction for all the text inputs
var advancedFunction = (mutations) => {
mutations.forEach((mutation) => {
if (mutation.attributeName === 'aria-expanded') {
let currentExpand = mutation.target.getAttribute('aria-expanded');
if (currentExpand) {
this.setTextFilters();
}
}
});
};
var observer = new MutationObserver((m) => {
advancedFunction(m);
});
advanceOptions && observer.observe(advanceOptions, { attributes: true });
}
noSpecialChars(elem) {
let c = elem.selectionStart;
let r = /[^a-z0-9 .]/gi;
let v = elem.value;
if (r.test(v)) {
elem.value = v.replace(r, '');
c--;
}
elem.setSelectionRange(c, c);
}
imposeMax(elem) {
if (elem.value !== '') {
if (parseInt(elem.value) < parseInt(elem.min)) {
elem.value = elem.min;
}
if (parseInt(elem.value) > parseInt(elem.max)) {
elem.value = elem.max;
}
} else {
elem.value = elem.value.replace(/[^e+-,.]/gi, '');
}
}
noSpecialNumbs(e) {
var invalidChars = ['-', '+', 'e', ',', '.'];
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
}
setTextFilters() {
let inputs = document.querySelectorAll('input.esri-print__input-text');
inputs.forEach((input) => {
if (input.type === 'text' && !input.oninput) {
if (
input.getAttribute('data-input-name') === 'title' ||
input.getAttribute('data-input-name') === 'fileName'
) {
input.setAttribute('maxlength', '' + this.titleMaxLength);
} else if (input.getAttribute('data-input-name') === 'author') {
input.setAttribute('maxlength', '' + this.authorMaxLength);
} else {
input.setAttribute('maxlength', '' + this.textMaxLength);
}
input.oninput = () => {
this.noSpecialChars(input);
};
} else if (input.type === 'number' && !input.oninput) {
if (
input.getAttribute('data-input-name') === 'width' ||
input.getAttribute('data-input-name') === 'height'
) {
input.setAttribute('max', '' + this.sizeMax);
} else if (input.getAttribute('data-input-name') === 'dpi') {
input.setAttribute('max', '' + this.dpiMax);
} else if (input.getAttribute('data-input-name') === 'scale') {
input.setAttribute('max', '' + this.scaleMax);
}
input.oninput = () => {
this.imposeMax(input);
};
input.onkeydown = (e) => {
this.noSpecialNumbs(e);
};
}
});
}
/**
* This method renders the component
* @returns jsx
*/
render() {
return (
<>
<div ref={this.container} className="print-container">
<div tooltip="Print" direction="left" type="widget">
<div
className={this.menuClass}
id="map_print_button"
aria-label="Print"
onClick={this.openMenu.bind(this)}
onKeyDown={this.openMenu.bind(this)}
tabIndex="0"
role="button"
></div>
</div>
<div className="right-panel">
<div className="right-panel-header">
<span>Print</span>
<span
className="map-menu-icon esri-icon-close"
onClick={this.openMenu.bind(this)}
onKeyDown={this.openMenu.bind(this)}
tabIndex="0"
role="button"
></span>
</div>
<div className="right-panel-content">
<div className="print-panel"></div>
</div>
</div>
</div>
</>
);
}
}
export default PrintWidget; |
import 'dart:convert';
import 'dart:developer';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:track/forget_password/forget_password.dart';
import 'package:track/l10n/l10n.dart';
import 'package:track/login/login.dart';
import 'package:track/sign_up/sign_up.dart';
import 'package:track_theme/track_theme.dart';
import 'package:track/widgets/widgets.dart';
class LoginForm extends StatefulWidget {
const LoginForm({super.key});
@override
State<LoginForm> createState() => _LoginFormState();
}
class _LoginFormState extends State<LoginForm> {
final loginForm = GlobalKey<FormState>();
//text field controllers
//fixme remove setted value
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Form(
key: loginForm,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
EmailField(
controller: _emailController,
textInputAction: 'next',
),
AppStyle.sizedBoxSpace,
PasswordField(controller: _passwordController),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () => Navigator.of(context).push(
MaterialPageRoute(builder: (context) => ForgetPasswordScreen()),
),
child: Text(l10n.forgetPassword),
),
],
),
FilledButton(
style: AppStyle.fullWidthButton,
onPressed: () => login(),
child: Text(l10n.login),
),
OutlinedButton(
style: AppStyle.fullWidthButton,
onPressed: () => Navigator.of(context).push(
MaterialPageRoute(builder: (context) => SignUpScreen()),
),
child: Text(l10n.signUp),
),
],
),
);
}
void login() {
if (loginForm.currentState!.validate()) {
context.read<LoginCubit>().loginWithCredentials(
email: _emailController.text, password: _passwordController.text);
}
}
} |
import type {HeadersFunction, LoaderFunction, MetaFunction} from "@remix-run/node";
import {Link, useLoaderData, useLocation, useParams} from "@remix-run/react";
import {json, Response} from "@remix-run/node";
import {getCategories, getProducts, getProductsByParams} from "~/model/products";
import ProductItem from "~/components/product-item/ProductItem";
import {
FilterBar,
SelectedCategory,
DropPanel,
Span,
FilterOptions,
SortOptions,
ProductWrapper
} from './Shopping.styles';
import type {TProduct} from "~/types/model.type";
type Option = {
value: string;
text: string;
};
type LoaderData = {
products: TProduct[];
categories: string[];
genders: string[];
sort: Option[];
};
export const loader: LoaderFunction = async ({params, request}) => {
const url = new URL(request.url);
const sort: string | null = url.searchParams.get('sort');
const products = !params['*']
? getProducts(sort)
: getProductsByParams({category: params['*']}, sort);
if (!products || !products.length) {
throw new Response("Not Found", {status: 404});
}
return json<LoaderData>({
products,
categories: getCategories(),
genders: ['men', 'woman', 'unisex'],
sort: [{
value: 'asc',
text: 'Price (Low to High)'
}, {
value: 'desc',
text: 'Price (High to Low)'
}]
});
}
export const headers: HeadersFunction = () => {
return {
"X-Where-Are-You": "Switch Shopping",
};
};
export const meta: MetaFunction = ({ data, params }) => {
const category = params['*'];
if (!data) {
return {
title: 'Missing Shopping',
description: `The is no products with the category "${category}"`,
};
}
return {
title: category ? `Shopping - ${category}` : 'Shopping',
description: 'This is a real shopping page!!'
};
}
const Shopping = () => {
const params = useParams();
const {pathname} = useLocation();
const {products = [], categories = [], sort} = useLoaderData<LoaderData>();
const selectedCategory = params['*'];
return (
<main>
<FilterBar>
<DropPanel>
<Span>Filter by</Span><SelectedCategory>{selectedCategory}</SelectedCategory>
<FilterOptions>
<li key="all">
<Link to={'/shopping'}>All</Link>
</li>
{categories.map((category) => (
<li key={category}>
<Link to={category}>{category}</Link>
</li>
))}
</FilterOptions>
</DropPanel>
<DropPanel>
<Span>Sort by</Span>
<SortOptions>
<li key="recommended">
<Link to={pathname}>Recommended</Link>
</li>
{sort.map((option) => (
<li key={option.value}>
<Link to={`?sort=${option.value}`}>{option.text}</Link>
</li>
))}
</SortOptions>
</DropPanel>
</FilterBar>
<ProductWrapper>
{products?.map((product) => <ProductItem key={product.id} item={product}/>)}
</ProductWrapper>
</main>
)
};
export default Shopping; |
import { ControlValidator } from '../validator';
import { Control } from '../../control/control';
import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { Nullable } from '../../util';
@Directive()
export abstract class AbstractContainsValidators
extends ControlValidator<Nullable<string>, boolean>
implements OnChanges
{
@Input() contains!: string;
readonly name: string = 'contains';
validate({ value }: Control<Nullable<string>>): boolean | null {
if (!value) {
return null;
}
return !value.includes(this.contains) || null;
}
ngOnChanges(changes: SimpleChanges): void {
const { contains } = changes;
if (contains && !contains.isFirstChange()) {
this.validationChange$.next();
}
}
}
export class ContainsValidator extends AbstractContainsValidators {
constructor(contains: string) {
super();
this.contains = contains;
}
} |
export function renderTemplate({element, template, callback,
position = "after", clear = false }={}) {
if (clear) {element.innerHTML = ""}; // empty element first if so directed
element.insertAdjacentHTML(`${position}begin`, template);
}
export async function loadTemplate(path) {
const response = await fetch(path);
return response.text();
}
export async function loadHeaderFooter() {
const header = await loadTemplate(`../templates/header.html`);
const footer = await loadTemplate(`../templates/footer.html`);
renderTemplate({element: select("header"), template: header, clear: true});
renderTemplate({element: select("footer"), template: footer, clear: true});
}
export function renderList({templateFunction, element, list,
position = "after", clear = false }={}) {
let templates = "";
for (const item of list) {
templates += templateFunction(item); // add all templates
}
if (clear) {element.innerHTML = ""}; // empty element first if so directed
element.insertAdjacentHTML(`${position}begin`, templates);
}
export function getParam(param) {
const query = window.location.search;
const urlParams = new URLSearchParams(query);
return urlParams.get(param);
}
// wrapper for querySelector...returns matching element
export function select(selector, parent = document) {
return parent.querySelector(selector);
}
// or a more concise version if you are into that sort of thing:
// export const qs = (selector, parent = document) => parent.querySelector(selector);
// retrieve data from localstorage
export function getLocalStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
// save data to local storage
export function setLocalStorage(key, data) {
localStorage.setItem(key, JSON.stringify(data));
}
// set a listener for both touchend and click
export function setClick(callback, selector) {
select(selector).addEventListener("touchend", (event) => {
event.preventDefault()
callback()
})
select(selector).addEventListener("click", callback)
}
export function setClicks(callback, ...selectors) {
for (const selector of selectors)
setClick(callback, selector)
}
export function toggleClass(selector, className) {
select(selector).classList.toggle(removeDot(className))
}
export function toggleClasses(selector, ...classNames) {
for (const className of classNames) {
select(selector).classList.toggle(removeDot(className))
}
}
export function hasClass(selector, className) {
return select(selector).classList.contains(removeDot(className))
}
function removeDot(className) {
return className.slice(1)
} |
import React, { useEffect, useState } from "react";
import {TableCell,TableBody,TableRow} from "@mui/material";
import { FaEdit } from "react-icons/fa";
import { useRouter } from "next/router";
import { toast } from "react-toastify";
import { taxPayerType } from "../../../services/apiServices/revenue/taxPayerType/taxPayertypeService";
import MuiTable from "../../reusableDesign/muiTableDesign/MuiTable";
import { englishToNepali } from "../../../utils/utility";
import ListViewPageDesign from "../../reusableDesign/ListViewPageDesign";
import ListHeader from "../../reusableDesign/ListHeader";
import ListButton from "../../reusableDesign/ListButton";
import LoadingSpinner from "../../reusableDesign/Loading";
export default function TaxPayerType() {
const router = useRouter();
const [apiData, setApiData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
let taxPayerTypeApiData = () => {
taxPayerType().then((response) => {
try {
response.status === true;
{
setApiData(response.data);
setLoading(false);
}
} catch (error) {
toast.error(response.message, {
autoClose: 1000,
});
}
});
};
taxPayerTypeApiData();
}, [setApiData]);
const handleEdit = (id) => {
router.push(`/revenue/taxPayer/createTaxPayerType/${id}`);
};
const locale = (
<MuiTable tableHead={tableHeadData}>
<TableBody>
{apiData.map((row, index) => (
<TableRow key={index} className="hover:bg-[#a0cae7fd]">
<TableCell>{englishToNepali(index + 1)}</TableCell>
<TableCell>{row.name}</TableCell>
<TableCell>{row.code}</TableCell>
<TableCell
className="pl-7 cursor-pointer hover:text-blue-900"
onClick={() => {
handleEdit(row.id);
}}
>
<FaEdit size={20} />
</TableCell>
</TableRow>
))}
</TableBody>
</MuiTable>
);
return (
<ListViewPageDesign>
<ListHeader title="करदाता प्रकार सूची" />
<ListButton url={`/revenue/taxPayer/createTaxPayerType`} />
{loading ? <LoadingSpinner /> : locale}
</ListViewPageDesign>
);
}
const tableHeadData = [
{ id: "id", name: "सि.नं." },
{ id: "name", name: "नाम" },
{ id: "code", name: "कोड" },
{ id: "Action", name: "कार्य" },
]; |
/// ייבואים
import React, { useState, useEffect } from "react";
import { DataGrid } from "@mui/x-data-grid";
function ShowUsers() {
/// סטייטים
const [users, setUsers] = useState([]);
/// פונקציות
const showAllUsers = async () => {
try {
const response = await fetch(`${process.env.REACT_APP_HOST_API}/users`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
if (response.ok) {
const data = await response.json();
if (data && data.usersFdb && data.usersFdb.length > 0) {
setUsers(data.usersFdb);
} else {
console.error("No valid user data in the response");
}
} else {
console.error("Server response is not okay");
}
} catch (error) {
console.error("Error while fetching data from the server", error);
}
};
useEffect(() => {
showAllUsers();
}, []);
const columns = [
{ field: "id", headerName: "ID", width: 70, key: "id" },
{ field: "userName", headerName: "User Name", width: 130, key: "userName" },
{ field: "email", headerName: "Email", width: 200, key: "email" },
];
/// רינדור הקומפוננטה
return (
<div style={{ maxWidth: '90%', margin: '0 auto'}}>
<h1 className="headOfUsers" > Users: </h1>
<div style={{ height: 400, width: "100%" }}>
<DataGrid
rows={users}
columns={columns}
pageSize={5}
checkboxSelection
key="users_key"
/>
</div>
</div>
);
}
export default ShowUsers; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css"
integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"
integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous" />
<link rel="stylesheet" href="style.css" />
<title>Sunland</title>
</head>
<body data-spy="scroll" data-target="#main-nav" id="home">
<nav class="navbar navbar-expand-sm bg-dark navbar-dark fixed-top" id="main-nav">
<div class="container">
<a href="index.html" class="navbar-brand">Sunland</a>
<button class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a href="#home-section" class="nav-link">Home</a>
</li>
<li class="nav-item">
<a href="#explore-head-section" class="nav-link">Students<Input:checkbox></Input:checkbox></a>
</li>
<li class="nav-item">
<a href="#create-head-section" class="nav-link">Parents</a>
</li>
<li class="nav-item">
<a href="#share-head-section" class="nav-link">Instructors</a>
</li>
</ul>
</div>
</div>
</nav>
<header id="home-section">
<div class="dark-overlay">
<div class="home-inner container">
<div class="row">
<div class="col-lg-8 d-none d-lg-block">
<h1 class="display-4">
Best School in the World!
</h1>
<img src="sunland1.jpg" alt="students1" width="200px">
<img src="sunland2.jpg" alt="students2" width="200px">
<img src="sunland3.jpg" alt="students3" width="200px">
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
</div>
<div class="p-4 align-self-end">
Enroll your children and watch them grow!
</div>
</div>
<div class="d-flex">
<div class="p-4 align-self-end">
<button type="button" class="btn btn-primary btn-lg">Sign Up!</button>
</div>
</div>
</div>
</div>
</div>
</div>
</header>
<section id="explore-head-section" class="bg-success">
<div class="container">
<div class="row">
<div class="col text-center py-5">
<h1 class="display-4">Student's Page</h1>
<p><a href="#">Student SignIn</a></p>
</div>
</div>
</div>
</section>
<section id="explore-section">
<div class="container">
<div class="row">
<div class="col-md-6">
<img src="img/explore-section1.jpg" alt="" class="img-fluid mb-3 rounded-circle" />
</div>
<div class="col-md-6">
<h3>Assignments</h3>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
Assignment 1
</div>
</div>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
Assignment 2
</div>
</div>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
Assignment 3
</div>
</div>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
Assignment 4
</div>
</div>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
Assignment 5
</div>
</div>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
Assignment 6
</div>
</div>
</div>
</section>
<section id="create-head-section" class="bg-warning">
<div class="container">
<div class="row">
<div class="col text-center py-5">
<h1 class="display-4">Parent's Page</h1>
<p><a href="#">Parent SignIn</a></p>
</div>
</div>
</div>
</section>
<section id="create-section" class="py-5">
<div class="container">
<div class="row">
<div class="col-md-6 order-2">
<img src="sunland1.png" alt="" class="img-fluid mb-3 rounded-circle" />
</div>
<div class="col-md-6 order-1">
<h3>Blogs</h3>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
</div>
<div class="p-4 align-self-end">
Blog 1
</div>
</div>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
</div>
<div class="p-4 align-self-end">
Blog 2
</div>
</div>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
</div>
<div class="p-4 align-self-end">
Blog 3
</div>
</div>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
</div>
<div class="p-4 align-self-end">
Blog 4
</div>
</div>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
</div>
<div class="p-4 align-self-end">
Blog 5
</div>
</div>
</div>
</div>
</div>
</section>
<section id="share-head-section" class="bg-danger">
<div class="container">
<div class="row">
<div class="col text-center py-5">
<h1 class="display-4">Instructor's Page</h1>
<p><a href="#">Instructor LogIn</a></p>
</div>
</div>
</div>
</section>
<section id="share-section" class="bg-light text-muted py-5">
<div class="container">
<div class="row">
<div class="col-md-6">
<img src="sunland2.png" alt="" class="img-fluid mb-3 rounded-circle" />
</div>
<div class="col-md-6">
<h3>Instructor's Posts</h3>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
</div>
<div class="p-4 align-self-end">
Post 1
</div>
</div>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
</div>
<div class="p-4 align-self-end">
Post 2
</div>
</div>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
</div>
<div class="p-4 align-self-end">
Post 3
</div>
</div>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
</div>
<div class="p-4 align-self-end">
Post 4
</div>
</div>
<div class="d-flex">
<div class="p-4 align-self-start">
<i class="fas fa-check fa-2x"></i>
</div>
<div class="p-4 align-self-end">
Post 5
</div>
</div>
</div>
</div>
</div>
</section>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"
integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T"
crossorigin="anonymous"></script>
<script>
$("#year").text(new Date().getFullYear());
$("body").scrollspy({ target: "#main-nav" });
$("#main-nav a").on("click", function (event) {
if (this.hash !== "") {
event.preventDefault();
const hash = this.hash;
$("html, body").animate(
{
scrollTop: $(hash).offset().top
},
800,
function () {
window.location.hash = hash;
}
);
}
});
</script>
</body>
</html> |
function plotPeriod(data, dStart, dEnd)
%plotPeriod(data, dStart, dEnd)
%Plot a period between two dates
%
% Parameters:
% -----------
% data = historical data to plot
% dStart = initial date
% dEnd = final date
%
% Returns:
% --------
%
% Example:
% --------
% plotPeriod(gspc,"2010-1-31","2015-12-10")
if ~exist('data', 'var')
fprintf('\tERROR: %s does not exist. Did you load it first?\n', data)
fprintf('\ttype ''help plotPeriod'' for more information\n')
return
end
startDate = datetime(dStart, 'Inputformat', 'yyyy-MM-dd');
endDate = datetime(dEnd, 'InputFormat', 'yyyy-MM-dd');
if startDate > endDate
fprintf('\tERROR: Start date must be before End date\n')
fprintf('\ttype ''help plotPeriod'' for more information\n')
return
end
dateRange = (data.Date >= startDate) & (data.Date <= endDate);
plot(data.Date(dateRange), data.Open(dateRange), 'LineWidth', 2)
end |
<template>
<Body>
<section class="w-full h-screen flex items-center overflow-hidden">
<div class="test w-[62%] h-screen p-10">
<div
class="w-full flex items-center justify-between"
v-motion
:initial="{ opacity: 0 }"
:enter="{ opacity: 1, scale: 1 }"
:delay="100"
>
<ULink to="login" class="flex items-center gap-1">
<UIcon name="i-heroicons-chevron-left" class="text-[1.4rem]"/>
<p class="font-[Roboto] text-[1rem] font-light capitalize">quay về đăng nhập</p>
</ULink>
</div>
<div class="w-full h-full flex items-center justify-center"
v-motion
:initial="{ opacity: 0 }"
:enter="{ opacity: 1, scale: 1 }"
:delay="300"
>
<div class="w-[80%] h-[80%] flex items-center justify-center flex-col mt-[-2.5rem]">
<h2 class="text-[1.5rem] font-bold font-[Roboto] uppercase mb-[1.1rem] mt-[-.6rem]">
{{ emailSent ? 'Kiểm tra email đăng ký' : 'bạn đã quên mật khẩu?' }}
</h2>
<p class="text-[1rem] font-[Roboto] font-light uppercase mb-[-10.6rem]">
{{ emailSent ? 'Chúng tôi vừa gửi mã code đến email của bạn' : 'vui lòng nhập email và nhấn tiếp tục để nhận code reset mật khẩu' }}
</p>
<UForm class="w-full h-full flex items-center justify-center flex-col gap-[2.5rem] mb-[-10.15rem]" action="" @submit="handleEmailSubmit">
<UFormGroup :label="emailSent ? 'Mã code' : 'Email của bạn'" name="email" class="w-[26rem] font-[Roboto] text-[1rem] relative">
<UIcon name="i-heroicons-envelope-open-solid" class="absolute top-[.85rem] left-3 text-[1.1rem]"/>
<input
:type="emailSent ? 'text' : 'email'"
class="w-full h-[3rem] outline-none pl-10 pr-4 bg-transparent border-0 border-b-[1px] border-b-[#ffffffc0] transition-all focus:border-b-[rgb(0,220,130)] text-[1.05rem] font-light"
v-model="emailInput"
required
autocomplete="off"
:placeholder="emailSent ? 'Nhập mã vào đây...' : 'Nhập email đăng ký...'"
>
</UFormGroup>
<UButton
type="submit"
class="transition-all ease-out duration-300 w-[26rem] h-[3rem] flex items-center justify-center"
size="xl"
variant="solid"
:ui="{ rounded: 'rounded-full' }">
<span class="font-['Roboto'] uppercase text-[.9rem] font-bold">{{ emailSent ? 'xác nhận' : 'tiếp tục'}}</span>
<Icon :icon="emailSent ? 'line-md:confirm-circle' :'bi:send-fill'" class="text-[1.05rem]"/>
</UButton>
</UForm>
<p class="font-[Roboto] text-[.85rem] font-light">Bạn đang gặp vấn đề? <ULink class="font-bold uppercase transition-all hover:text-[rgb(0,220,130)]" @click="toast.add({ icon: 'i-heroicons-exclamation-circle-20-solid', title: 'Chức năng đang được phát triển', timeout: 2500, color: 'yellow' })">cần hỗ trợ</ULink></p>
</div>
</div>
</div>
<div class="w-[38%] h-screen"
v-motion
:initial="{ opacity: 0 }"
:enter="{ opacity: 1, scale: 1 }"
:delay="10"
>
<NuxtImg src="/photo4.jpg" class="w-full h-full" />
</div>
</section>
</Body>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { Icon } from '@iconify/vue';
useHead({
title: 'Quên Mật Khẩu',
});
const toast = useToast();
const emailSent = ref(false);
const emailInput = ref('');
const emailCorrect = '[email protected]';
const handleEmailSubmit = (): void => {
if (emailInput.value === emailCorrect) {
emailSent.value = true;
emailInput.value = '';
} else {
toast.add({
icon: 'i-heroicons-no-symbol-solid',
color: 'red',
title: 'Email không tồn tại',
description: 'Vui lòng kiểm tra lại email của bạn.',
timeout: 2500
});
}
};
</script>
<style scoped>
</style> |
import { useState, useEffect, useRef } from "react";
import DashboardLayout from "../layout/DashboardLayout"
import { useAuth } from "../../../auth/AuthProvider";
import { database } from "../../firebase";
import { getDatabase, ref, get, set, onValue } from "firebase/database";
import AddUserModal from "./AddUserModal";
import Swal from 'sweetalert2';
const Users = () => {
// const { fetchfetchAllUsers } = useAuth();
const [users, setUsers] = useState([]);
const [name, setName] = useState('');
const [openModal, setOpanModal] = useState(false);
const [newUser, setNewUser] = useState([]);
const { deleteVoter } = useAuth();
useEffect(() => {
const fetchAllUsers = async () => {
try {
const usersRef = ref(database, `users`);
const usersSnapshot = await get(usersRef);
if (usersSnapshot.exists()) {
const usersData = usersSnapshot.val();
console.log(usersData)
// Convert nested object into an array of users
const usersArray = Object.entries(usersData).map(([uid, userData]) => ({
uid,
...userData,
}));
setUsers(usersArray);
} else {
console.log('No users found');
}
} catch (error) {
console.error('Error fetching users:', error.message);
}
};
fetchAllUsers();
}, [])
const handleOpenModal = (e) => {
e.preventDefault();
setOpanModal(true)
};
const handleCloseModal = (e) => {
e.preventDefault();
setOpanModal(false)
};
const handleDeleteUser = async (userId) => {
try {
const result = await Swal.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!"
});
if (result.isConfirmed) {
await deleteVoter(userId);
await Swal.fire({
title: "Deleted!",
text: "User has been deleted.",
icon: "success"
});
window.location.reload();
}
} catch (error) {
console.log("error while deleting from client", error);
}
};
return (
<DashboardLayout>
<div className="bg-black text-white pt-2 rounded-lg">
<h2 className="text-2xl text-gold font-semibold mb-4">User Table</h2>
<div className="mb-4 flex max-w-[500px] gap-4">
<input
type="text"
placeholder="Enter new user"
value={name}
onChange={(e) => setName(e.target.value)}
className="shadow appearance-none border rounded w-full border-[#777]/30 py-3 px-3 bg-[#777]/30 text-white leading-tight focus:outline-none focus:shadow-outline"
/>
<button onClick={handleOpenModal} className="font-medium text-black bg-gold py-3 mx-auto w-[50%] text-center flex justify-center items-center gap-2 hover:border-gold hover:bg-transparent hover:text-gold rounded border border-transparent duration-300">Add User</button>
{
openModal ? (
<div>
<AddUserModal openModal={openModal} closeModal={handleCloseModal} username={name} />
</div>
) : (
null
)
}
</div>
<table className="w-full overflow-hidden">
<thead className="border-[#777]/50 border-b border-t">
<tr className="border-[#777]/50 border">
<th className="py-2 border-[#777]/50 border">ID</th>
<th className="py-2 border-[#777]/50 border">Name</th>
<th className="py-2 border-[#777]/50 border">Action</th>
</tr>
</thead>
<tbody>
{
users.map((user) => (
<tr key={user.uid} className="text-center border-[#777]/50 border">
<td className="py-2 border-[#777]/50 border">{user.uid}</td>
<td className="py-2 border-[#777]/50 border">{user.name}</td>
<td className="py-2 border-[#777]/50 border">
<button
onClick={() => handleDeleteUser(user.uid)}
className="bg-red-500 text-white px-3 py-1 rounded-lg"
>
Delete
</button>
</td>
</tr>
))
}
</tbody>
</table>
</div>
</DashboardLayout>
)
}
export default Users |
//
// DetailMovieModel.swift
// TMDBMovie
//
// Created by Evan Eka Laksana on 26/10/23.
//
import Foundation
struct DetailMovieModel {
struct Request {
var id: Int
}
struct Response: Codable {
let adult: Bool?
let backdropPath: String?
let budget: Int?
let genres: [Genres]?
let id: Int?
let imdbID: String?
let originalTitle: String?
let overview: String?
let popularity: Double?
let posterPath: String?
let productionCompanies: [ProductionCompanies]?
let productionCountries: [ProductionCountries]?
let releaseDate: String?
let revenue: Int?
let runtime: Int?
let status: String?
let tagline: String?
let title: String?
let video: Bool?
let voteAverage: Double?
let voteCount: Double?
let languages: [SpokenLanguages]?
enum CodingKeys: String, CodingKey {
case adult
case backdropPath = "backdrop_path"
case budget
case genres
case id
case imdbID = "imdb_id"
case originalTitle = "original_title"
case overview
case popularity
case posterPath = "poster_path"
case productionCompanies = "production_companies"
case productionCountries = "production_countries"
case releaseDate = "release_date"
case voteAverage = "vote_average"
case voteCount = "vote_count"
case languages = "spoken_languages"
case revenue,runtime,status,tagline,title,video
}
}
struct DetailMovieViewModel {
let id: Int
let movieTitle: String
let rating: Double
let ratingValue: Double
let movieYear: String
let movieCover: String
let backdropCover: String
let isWatched: Bool
let synopsis: String
let genres: String
let tagline: String
let runtime: String
let releaseDate: String
let isAdult: Bool
let popularity: Double
}
struct Genres: Codable {
let id: Int?
let name: String?
}
struct ProductionCompanies: Codable {
let id: Int?
let name: String?
let originCountry: String?
enum CodingKeys: String, CodingKey {
case name,id
case originCountry = "origin_country"
}
}
struct ProductionCountries: Codable {
let iso31661: String?
let name: String?
enum CodingKeys: String, CodingKey {
case name
case iso31661 = "iso_3166_1"
}
}
struct SpokenLanguages: Codable {
let iso6391: String?
let name: String?
let englishName: String?
enum CodingKeys: String, CodingKey {
case name
case iso6391 = "iso_639_1"
case englishName = "english_name"
}
}
} |
const express = require("express");
const mongoose = require("mongoose");
const path = require('path');
const bodyParser = require("body-parser");
const app = express();
const multer = require("multer");
const cors = require("cors");
app.use(cors());
mongoose.connect("mongodb+srv://naiduabhay1:[email protected]/news");
// Define mongoose schema for news feed
const newsSchema = new mongoose.Schema({
title: String,
content: String,
category: String,
status: String,
date: String,
fileUrl: String,
});
// Create mongoose model
const NFeed = mongoose.model("NFeed", newsSchema);
// Multer configuration for file upload
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./uploads");
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});
const upload = multer({ storage: storage });
// Serve static files from uploads directory
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// Middleware for parsing request body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// POST route for creating a new news feed
app.post("/", upload.single("file"), async (req, res) => {
try {
// Construct file path
const filePath = "uploads/" + req.file.filename;
// Create new news feed instance
const newsFeed = new NFeed({
title: req.body.title,
content: req.body.content,
category: req.body.category,
status: req.body.status,
date: req.body.date,
fileUrl: req.file ? filePath : null, // Store the file path if available
});
// Save the news feed to database
await newsFeed.save();
res.status(201).send("News feed created successfully");
} catch (error) {
console.error("Error creating news feed:", error);
res.status(500).send("Internal server error");
}
});
// GET route for fetching all news feeds
app.get("/", async (req, res) => {
try {
const data = await NFeed.find({});
res.send(data);
} catch (error) {
console.error("Error finding news feed:", error);
res.status(500).send("Internal server error");
}
});
// DELETE route for deleting a news feed
app.delete("/", async (req, res) => {
try {
// Get data from request body
const data = req.body;
// Delete the news feed
const deletedFeed = await NFeed.deleteOne(data);
res.send(deletedFeed);
} catch (error) {
console.error("Error finding news feed:", error);
res.status(500).send("Internal server error");
}
});
// Define port
const PORT = process.env.PORT || 8000;
// Start server
app.listen(PORT, () =>
console.log("Server is running on port " + PORT)
); |
import React from 'react';
import Header from './Header';
import Main from './Main';
import Footer from './Footer';
import PopupWithForm from './PopupWithForm';
import ImagePopup from './ImagePopup';
import { cardApi } from '../utils/cardApi';
import { authApi } from '../utils/authApi';
import currentUserContext from '../contexts/CurrentUserContext';
import EditProfilePopup from './EditProfilePopup';
import EditAvatarPopup from './EditAvatarPopup';
import AddPlacePopup from './AddPlacePopup';
import Login from './Login';
import Register from './Register';
import { Routes, Route, Navigate, useNavigate, useLocation } from 'react-router';
import ProtectedRouteElement from './ProtectedRoute';
import InfoTooltip from './InfoTooltip';
function App() {
const [isEditProfilePopupOpen, setIsEditProfilePopupOpen] = React.useState(false);
const [isEditAvatarPopupOpen, setIsEditAvatarPopupOpen] = React.useState(false);
const [isAddPlacePopupOpen, setIsAddPlacePopupOpen] = React.useState(false);
const [isLoading, setIsLoading] = React.useState(false);
const [selectedCard, setSelectedCard] = React.useState(null);
const [currentUser, setCurrentUser] = React.useState(null);
const [cards, setCards] = React.useState([]);
const [isMenuOpen, setMenuOpen] = React.useState(false);
const [isLoggedIn, setLoggedIn] = React.useState(false);
const [tooltip, setTooltip] = React.useState({
isOpened: false,
isSuccess: false,
text: ''
});
const navigate = useNavigate();
const location = useLocation();
function handleEditAvatarClick() {
setIsEditAvatarPopupOpen(true);
};
function handleEditProfileClick() {
setIsEditProfilePopupOpen(true);
};
function handleAddPlaceClick() {
setIsAddPlacePopupOpen(true);
};
function handleCardClick(card) {
setSelectedCard(card);
};
function handleCardLike(card) {
const isLiked = card.likes.some(i => i === currentUser._id);
cardApi.changeLikeCardStatus(card._id, isLiked)
.then((newCard) => {
setCards((state) => state.map((c) => c._id === card._id ? newCard.data : c));
})
.catch(err => console.log(err));
};
function handleCardDelete(card) {
cardApi.deleteCard(card._id)
.then(() => {
setCards((state) => state.filter((c) => c._id !== card._id));
})
.catch(err => console.log(err));
};
function closeAllPopups() {
setIsEditAvatarPopupOpen(false);
setIsEditProfilePopupOpen(false);
setIsAddPlacePopupOpen(false);
setTooltip({
...tooltip,
isOpened: false
});
setSelectedCard(null);
};
function handleUpdateUser({ name, about }) {
setIsLoading(true);
cardApi.setUserInfo(name, about)
.then(res => {
setCurrentUser({
...currentUser,
name: res.data.name,
about: res.data.about
});
closeAllPopups();
})
.catch(err => console.log(err))
.finally(() => setIsLoading(false));
};
function handleUpdateAvatar(link) {
setIsLoading(true);
cardApi.updateAvatar(link)
.then(res => {
setCurrentUser({
...currentUser,
avatar: res.data.avatar
});
closeAllPopups();
})
.catch(err => console.log(err))
.finally(() => setIsLoading(false));
};
function handleAddPlaceSubmit({ title, link }) {
setIsLoading(true);
cardApi.addCard(title, link)
.then(newCard => {
setCards([newCard.data, ...cards]);
closeAllPopups();
})
.catch(err => console.log(err))
.finally(() => setIsLoading(false));
};
function handleRegistration(email, password) {
setIsLoading(true);
authApi.register(email, password)
.then(() => {
setTooltip({
isOpened: true,
isSuccess: true,
text: 'Вы успешно зарегистрировались!'
})
})
.catch(err => {
setTooltip({
isOpened: true,
isSuccess: false,
text: err
})
})
.finally(() => setIsLoading(false));
}
function handleAuthorization(email, password) {
if (!email || !password) {
return;
}
setIsLoading(true);
authApi.authorize(email, password)
.then(() => {
setLoggedIn(true);
navigate('/');
})
.catch(err => {
setTooltip({
isOpened: true,
isSuccess: false,
text: err
})
})
.finally(() => setIsLoading(false));
}
function handleSignOut() {
return authApi.logout()
.then(() => setLoggedIn(false))
.catch(err => console.log(err));
}
React.useEffect(() => {
authApi.getContent()
.then(() => {
setLoggedIn(true);
navigate('/');
})
.catch(err => {
console.log(err);
});
}, []);
function handleMainMount() {
Promise.all([cardApi.getUserInfo(), cardApi.getInitialCards()])
.then(([userData, cardsData]) => {
setCurrentUser(userData.data);
setCards(cardsData.data);
})
.catch(err => {
console.log(err);
});
}
const handleMenuOpen = () => isMenuOpen ? setMenuOpen(false) : setMenuOpen(true);
return (
<currentUserContext.Provider value={currentUser}>
<div className={`page${isMenuOpen && (location?.pathname === '/') ? ' page_translated' : ''}`}>
<Header onMenuClick={handleMenuOpen} onSignOut={handleSignOut} isOpen={isMenuOpen} email={currentUser ? currentUser.email : ''} />
<Routes>
<Route path='/*' element={isLoggedIn ? <Navigate to='/' replace /> : <Navigate to='/sign-in' replace />} />
<Route path='/' exact element={<>
<ProtectedRouteElement
element={Main}
isLoggedIn={isLoggedIn}
onEditProfile={handleEditProfileClick}
onAddPlace={handleAddPlaceClick}
onEditAvatar={handleEditAvatarClick}
onCardClick={handleCardClick}
onCardLike={handleCardLike}
onCardDelete={handleCardDelete}
cards={cards}
onComponentMount={handleMainMount} />
<Footer />
<EditProfilePopup isOpen={isEditProfilePopupOpen} isLoading={isLoading} onClose={closeAllPopups} onUpdateUser={handleUpdateUser} />
<AddPlacePopup isOpen={isAddPlacePopupOpen} isLoading={isLoading} onClose={closeAllPopups} onAddPlace={handleAddPlaceSubmit} />
<EditAvatarPopup isOpen={isEditAvatarPopupOpen} isLoading={isLoading} onClose={closeAllPopups} onUpdateAvatar={handleUpdateAvatar} />
<PopupWithForm name='confirm' title='Вы уверены?' />
<ImagePopup card={selectedCard} onClose={closeAllPopups} />
</>} />
<Route path='/sign-in' element={<Login onSubmit={handleAuthorization} isLoading={isLoading} />} />
<Route path='/sign-up' element={<Register onSubmit={handleRegistration} isLoading={isLoading} />} />
</Routes>
<InfoTooltip {...tooltip} onClose={closeAllPopups} />
</div>
</currentUserContext.Provider >
);
}
export default App; |
<?php
namespace Vendors;
class Autoloader {
private static $_includePath;
private static $_namespace;
private static $_namespaceSeparator = '\\';
private static $_fileExtension = '.php';
/**
* Sets the base include path for all class files in the namespace of this class loader.
*
* @param string $includePath
*/
public static function setIncludePath($includePath) {
self::$_includePath = rtrim($includePath, DIRECTORY_SEPARATOR);
}
/**
* Register's the autoloader to the SPL autoload stack.
*
* @return void
*/
public static function register() {
spl_autoload_register('self::load', true, true);
}
/**
* Loads a class.
*
* @param string $class Class to load
* @return bool If it loaded the class
*/
public static function load($className) {
if (null === self::$_namespace || self::$_namespace . self::$_namespaceSeparator === substr($className, 0, strlen(self::$_namespace . self::$_namespaceSeparator))) {
$fileName = '';
$namespace = '';
if (false !== ($lastNsPos = strripos($className, self::$_namespaceSeparator))) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace(self::$_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . self::$_fileExtension;
require (self::$_includePath !== null ? self::$_includePath . DIRECTORY_SEPARATOR : '') . $fileName;
}
}
} |
import React from "react";
import { NaturePeople, Search } from "@material-ui/icons";
import { AppBar, Toolbar } from "@material-ui/core";
import "./topbar.css";
import { Link } from "react-router-dom";
import { AuthContext } from "../../context/AuthContext";
import { useContext } from "react";
const Topbar = () => {
const { user } = useContext(AuthContext);
const PF = process.env.REACT_APP_PUBLIC_FOLDER;
return (
<>
<AppBar position="static" color="primary">
<Toolbar>
<div className="topbarcontainer">
<div className="topbarleft">
<Link to="/" style={{ textDecoration: "none" }}>
<span className="logo"><NaturePeople /> Vruskhvalli</span>
</Link>
</div>
<div className="topbarcenter">
<div className="searchbar">
<Search className="searchIcon" />
<input
placeholder="search for friend or place"
className="searchInput"
/>
</div>
</div>
<div className="topbarright">
<Link to={`profile/${user.username}`}>
<img
src={user.profilePicture || PF + "person/noimg.png"}
className="postProfileImg"
/>
</Link>
<Link to={`profile/${user.username}`} style={{ textDecoration: "none" }}>
<h1 className="postUserName">
{user.username}
</h1>
</Link>
</div>
</div>
</Toolbar>
</AppBar>
</>
);
};
export default Topbar; |
<div class="container flex-page">
<div class="page-header">
<h1 ng-hide="nd.edit">Add your pooch!</h1>
<h1 ng-show="nd.edit">Edit your pooch!</h1>
</div>
<div class="flex-profile">
<section class="flex-container">
<form class="form" name="newdog" ng-submit="nd.submitDog(newdog)" novalidate>
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="nd.dog.name"
mongoose-error/>
<p class="help-block" ng-show="form.name.$error.mongoose">
{{ nd.errors.other }}
</p>
</div>
<div class="form-group">
<label>Breed</label>
<input type="text" name="breed" class="form-control" ng-model="nd.dog.breed"
mongoose-error/>
<p class="help-block" ng-show="form.breed.$error.mongoose">
{{ nd.errors.other }}
</p>
</div>
<!-- // Coming Soon //
<label>Photo Upload</label>
<div flow-init
flow-name="nd.flow"
flow-files-submitted="nd.uploadImg(nd.flow)"
flow-file-success="$file.msg = $message">
<span class="btn" flow-btn>Upload File</span>
<span ng-repeat="file in $flow.files">{{file.name}}</span>
</div> -->
<div class="form-group">
<label>Photo</label>
<input type="text" name="photo" class="form-control" ng-model="nd.dog.photo" placeholder="http://www.site.com/my-dog-picture.jpg"
mongoose-error/>
<p class="help-block" ng-show="form.photo.$error.mongoose">
{{ nd.errors.other }}
</p>
</div>
<div class="form-group">
<label>Bio</label>
<input type="text" name="bio" class="form-control" ng-model="nd.dog.bio"
mongoose-error/>
<p class="help-block" ng-show="form.bio.$error.mongoose">
{{ nd.errors.other }}
</p>
</div>
<div class="form-group">
<label>Shots</label>
<input type="text" name="shot" class="form-control" ng-model="nd.dog.shot"
mongoose-error/>
<p class="help-block" ng-show="form.shot.$error.mongoose">
{{ nd.errors.other }}
</p>
</div>
<div class="form-group">
<label>Vet Contact Info</label>
<input type="text" name="vet_contact" class="form-control" ng-model="nd.dog.vet_contact"
mongoose-error/>
<p class="help-block" ng-show="form.vet_contact.$error.mongoose">
{{ nd.errors.other }}
</p>
</div>
<button ng-hide="nd.edit" class="btn btn-lg btn-primary" type="submit">Add dog</button>
<button ng-show="nd.edit" class="btn btn-lg btn-primary" type="submit">Update Dog</button>
</form>
</section>
<section class="flex-container">
<div class="">
<label>Preview</label>
<div class="thumbnail preview">
<img flow-init flow-object="nd.flow" flow-img="nd.flow.files[0]" />
<img src="{{nd.dog.photo}}" alt="{{nd.dog.name}}">
<div class="caption">
<h3>{{nd.dog.name}}<br><small>{{nd.dog.breed}}</small></h3>
<p>{{nd.dog.bio}}</p>
</div>
</div>
</div>
</section>
</div>
</div> |
import type { AppProps } from "next/app";
import Head from "next/head";
import React from "react";
import { QueryClient, QueryClientProvider } from "react-query";
import { LoginProvider } from "../context/loginContext";
import "../styles/buttons.css";
import "../styles/colors.css";
import "../styles/fonts.css";
import "../styles/globals.css";
import "../styles/inputs.css";
import "../styles/texts.css";
function MyApp({ Component, pageProps }: AppProps) {
const queryClient = new QueryClient()
return (
<QueryClientProvider client={queryClient}>
<LoginProvider>
<Head>
<title>Next Challenge</title>
<meta
name="description"
content="Challenge to Next Js generated by create next app"
/>
<link rel="icon" href="/favicon.ico" />
</Head>
<Component {...pageProps} />
</LoginProvider>
</QueryClientProvider>
);
}
export default MyApp; |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Transitions</title>
<style>
html, body {
background:linen;
font-family: Verdana, Geneva, Tahoma, sans-serif;
margin: 2em 5em;
scroll-behavior: smooth;
}
nav{
background:linen;
position: sticky;
top: -1px;
width: 100%;
}
nav ul{
display: flex;
flex-wrap: wrap;
}
nav li{
list-style-type: none;
padding: 1em;
}
dt{
font-weight: bolder;
}
dd {
font-style: italic;
}
.opdracht2 p {
color: royalblue;
}
.opdracht2 p:hover {
color: red;
transition: color 2s;
}
/* opdracht3 .box2, .opdracht3 .box3, .opdracht3 .box4, .opdracht3 .box5 */
.opdracht3 .box {
width: 100px;
height: 100px;
border: 2px solid grey;
text-align: center;
transition-property:margin-left, background-color, border-radius;
transition-duration:3s,3s,2s;
}
.opdracht3:hover .box1{
margin-left: 600px;
background-color: red;
border-radius: 50%;
transition-timing-function: ease-in-out;
/* transition-duration:3s,3s,2s; */
}
.opdracht3:hover .box2{
margin-left: 600px;
background-color: red;
border-radius: 30px;
transition-timing-function: ease;
transition-duration:3s,3s,2s;
}
.opdracht3:hover .box3{
margin-left: 600px;
background-color: red;
transition-timing-function: ease-in;
transition-duration:3s,3s;
}
.opdracht3:hover .box4{
margin-left: 600px;
background-color: red;
transition-timing-function: ease-out;
transition-duration:3s,2s;
}
/* :nth-child(1) */
.opdracht3:hover .box5{
margin-left: 600px;
background-color: red;
transition-timing-function:linear;
transition-duration:3s,1.5s;
transition-timing-function: cubic-bezier(.5, 2.9, .9, -1.9)
}
.opdracht4 {
position: relative;
height: 500px;
width: 500px;
background: lightgray;
border: 2px solid grey;
}
.opdracht4 .box{
position: absolute;
text-align: center;
height: 100px;
width: 100px;
background-color: lightcoral;
transition-property:top, bottom, left, right;
transition-duration:3s,3s,2s,2s;
transition-delay:0s,2s,0s,2s;
}
.opdracht4 .box1{right:40%; top: 40%;}
.opdracht4 .box2{left:40%; top: 40%;}
.opdracht4 .box3{left:40%; bottom:40%;}
.opdracht4:hover .box1{
top:0;
right: 0;
}
.opdracht4:hover .box2{
top:0;
left: 0px;
}
.opdracht4:hover .box3{
bottom:0px;
left: 0px;
}
.opdracht5 {
position: relative;
height: 500px;
width: 250px;
margin: auto;
}
.opdracht5 .img{
position: absolute;
z-index: 1;
}
.opdracht5 .cover{
position: absolute;
height: 250px;
width: 250px;
background-color: tomato;
z-index: 2;
/* transform: translate(0px, 0px); */
transform-origin: left bottom;
transition: transform 1s;
}
.opdracht5:hover .cover{
transform: rotate(45deg) translate(100px, 50px);
/* transform: translate(120px, 120px); */
}
.opdracht6{
display: flex;
height:350px;
align-items: center;
justify-content: center;
}
.opdracht6 .card{
margin: 0 -4em ;
padding: 3em 1em;
background: gray;
border: 3px solid black;
border-radius: 10%;
transition: margin 1s;
}
.opdracht6 .card:hover{
margin:0 4em;
}
/* https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations */
/* https://developer.mozilla.org/en-US/docs/Web/CSS/animation */
.opdracht7{
display: flex;
justify-content: center;
align-items: center;
height: 350px;
width: 350px;
background: black;
margin: auto;
}
.opdracht7 .shape{
width: 150px;
height: 150px;
background: chocolate;
animation-name: deform;
animation-duration: 8s;
animation-iteration-count: infinite;
}
@keyframes deform {
0% { background-color:aqua;
transform: rotate(45deg);
}
20% {background-color: blue;
transform: rotate(90deg);
border-radius: 50%;
}
40%{background: ghostwhite;
border-radius: 0 50% 0 50%;
transform: rotate(180deg);
}
60%{border-radius: 50% 50% 0 0;
transform: rotate(90deg);
background: gold;
}
80%{border-radius: 0% 50% 50% 50%;
transform: rotate(45deg);
background: greenyellow; }
100%{border-radius: 0 0 50% 50%;
transform: rotate(0deg);
background: deeppink }
}
</style>
</head>
<body>
<h1>Transitions</h1>
<nav>
<ul style="display:flex;">
<li><a href="#opdr1">OPDR1</a></li>
<li><a href="#opdr2">OPDR2</a></li>
<li><a href="#opdr3">OPDR3</a></li>
<li><a href="#opdr4">OPDR4</a></li>
<li><a href="#opdr5">OPDR5</a></li>
<li><a href="#opdr6">OPDR6</a></li>
<li><a href="#opdr7">OPDR7</a></li>
</ul>
</nav>
<br><hr><br><br>
<h3 id="opdr1" style="padding-top: 120px; margin-top: -120px;">Opdracht 2</h3>
<dt>Zoek uit wat transitions zijn en beschrijf met eigen woorden wat het betekent.</dt>
<dd>Transitions / annimations binnen CSS zijn opties om waardes van bepaalde CSS properties te veranderen over
een bepaalde tijd.
</dd>
<br>
<div class="opdracht1">
</div>
<br><br><hr><br><br>
<h3 id="opdr2" style="padding-top: 120px; margin-top: -120px;">Opdracht 2</h3>
<dt>Maak een simpele transition wat de kleur van een tekst aanpast.</dt>
<dd></dd>
<br>
<div class="opdracht2">
<p>Ga met je muis over deze text.</p>
</div>
<br><br><hr><br><br>
<h3 id="opdr3" style="padding-top: 120px; margin-top: -120px;">Opdracht 3</h3>
<dt>Transitions kent verschillende transition-timing. Zie hieronder een voorbeeld. Maak het na.</dt>
<dd></dd>
<br>
<div class="opdracht3">
<div class="box box1">1</div>
<div class="box box2">2</div>
<div class="box box3">3</div>
<div class="box box4">4</div>
<div class="box box5">5</div>
</div>
<br><br><hr><br><br>
<h3 id="opdr4" style="padding-top: 120px; margin-top: -120px;">Opdracht 4</h3>
<dt>Je kunt op verschillende properties transitions aangeven. Zie hieronder een voorbeeld. Zoek uit op welke properties de transitions zitten en maak het ongeveer hetzelfde na</dt>
<dd></dd>
<br>
<div class="opdracht4">
<div class="box box1">1</div>
<div class="box box2">2</div>
<div class="box box3">3</div>
</div>
<br><br><hr><br><br>
<h3 id="opdr5" style="padding-top: 120px; margin-top: -120px;">Opdracht 5</h3>
<div class="opdracht5">
<div class="img"><img src="./img/emoticon.jpg" alt="" width="250px" height="250px"></div>
<div class="cover"></div>
</div>
<br><br><hr><br><br>
<h3 id="opdr6">Opdracht 6</h3>
<br>
<div class="opdracht6">
<div class="card card1">
<p>Article Sep 16, 2019</p>
<h2>Placeholder title</h2>
<p>Author: Elmer Volgers</p>
</div>
<div class="card card2">
<p>Article Sep 16, 2019</p>
<h2>Placeholder title</h2>
<p>Author: Elmer Volgers</p>
</div>
<div class="card card3">
<p>Article Sep 16, 2019</p>
<h2>Placeholder title</h2>
<p>Author: Elmer Volgers</p>
</div>
<div class="card card4">
<p>Article Sep 16, 2019</p>
<h2>Placeholder title</h2>
<p>Author: Elmer Volgers</p>
</div>
</div>
<br><br><hr><br><br>
<h3 id="opdr7">Opdracht 7</h3>
<br>
<div class="opdracht7">
<div class="shape"></div>
</div>
<br><br><hr><br><br>
</body>
</html> |
import { Card, CardBody, Text, Button, HStack, VStack } from "@chakra-ui/react";
import { ArrowUpIcon, ArrowDownIcon } from "@chakra-ui/icons";
const TodoCards = ({ data, setCardData }: any) => {
const handleClick = (index: number) => {
setCardData((prevData: any) =>
prevData.map((item: any, i: number) =>
i === index ? { ...item, completed: !item.completed } : item
)
);
};
const handleDeleteClick = (index: number) => {
setCardData(
(prevData: any) => prevData.filter((_: any, i: number) => i !== index) // so this logic will provide us the new array that is not equal to the index which we were passing as an argument
);
};
const handleMoveUp = (index: number) => {
if (index > 0) {
setCardData((prevData: any) => {
const newData = [...prevData];
[newData[index], newData[index - 1]] = [
newData[index - 1],
newData[index],
];
return newData;
});
}
};
const handleMoveDown = (index: number) => {
if (index < data.length - 1) {
setCardData((prevData: any) => {
const newData = [...prevData];
[newData[index], newData[index + 1]] = [
newData[index + 1],
newData[index],
];
return newData;
});
}
};
return (
<>
{data.map((item: any, index: any) => (
<Card
key={index}
margin={3}
bgColor="#333333"
border="2px solid"
borderColor={item.completed ? "#B5E550" : "transparent"}
borderRadius={16}
>
<CardBody>
<HStack justifyContent="space-between">
<VStack alignItems="flex-start">
<Text
textDecoration={item.completed ? "line-through" : "none"}
color="#cccccc"
fontWeight="bold"
fontSize={33}
>
{item.inputBar}
</Text>
<HStack gap={3}>
<Text fontSize={15} color="#fbff12">
#{item.todoType}
</Text>
<Text fontSize={14} color="#ff206e">
#{item.Category}
</Text>
<Text fontSize={12} color="#41ead4">
#{item.dateAndTime}
</Text>
</HStack>
</VStack>
<HStack>
<VStack>
<Button
onClick={() => handleMoveUp(index)}
isDisabled={index === 0}
>
<ArrowUpIcon />
</Button>
<Button
onClick={() => handleMoveDown(index)}
isDisabled={index === data.length - 1}
>
<ArrowDownIcon />
</Button>
</VStack>
<VStack>
<Button onClick={() => handleClick(index)} width="100px">
{item.completed ? "Undo" : "Complete"}
</Button>
<Button
onClick={() => handleDeleteClick(index)}
width="100px"
>
Delete
</Button>
</VStack>
</HStack>
</HStack>
</CardBody>
</Card>
))}
</>
);
};
export default TodoCards; |
/**
* @file PrimitiveWrappers.c
* @author: Zhang Hai
*/
/*
* Copyright (C) 2014 Zhang Hai
*
* This file is part of zhclib.
*
* zhclib is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* zhclib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with zhclib. If not, see <http://www.gnu.org/licenses/>.
*/
#include "PrimitiveWrappers.h"
/* For string_format() */
#include "string.h"
#define DEFINE_PRIMITIVE_WRAPPER(NAME, TYPE, FORMAT) \
\
void NAME##_initializeMethods(NAME *this) { \
_$(this, new) = NAME##_new; \
_$(this, delete) = NAME##_delete; \
_$(this, toString) = NAME##_toString; \
_$(this, newFromValue) = NAME##_newFromValue; \
} \
\
void NAME##_initialize(NAME *this, string name) { \
\
Object_initialize((Object *)this, name); \
\
_(this, value) = 0; \
\
NAME##_initializeMethods(this); \
} \
\
void NAME##_initializeFromValue(NAME *this, string name, \
TYPE value) { \
\
Object_initialize((Object *)this, name); \
\
_(this, value) = value; \
\
NAME##_initializeMethods(this); \
} \
\
void NAME##_finalize(NAME *this) { \
Object_finalize((Object *)this); \
} \
\
NAME *NAME##_new() { \
OBJECT_NEW(NAME, , #NAME) \
} \
\
OBJECT_DEFINE_DELETE(NAME) \
\
string NAME##_toString(NAME *this) { \
return string_format(FORMAT, _(this, value)); \
} \
\
NAME *NAME##_newFromValue(TYPE value) { \
OBJECT_NEW(NAME, FromValue, #NAME, value) \
} \
DEFINE_PRIMITIVE_WRAPPER(Boolean, bool, "%d")
DEFINE_PRIMITIVE_WRAPPER(Character, char, "%c")
DEFINE_PRIMITIVE_WRAPPER(Integer, int, "%d")
DEFINE_PRIMITIVE_WRAPPER(Long, long, "%ld")
DEFINE_PRIMITIVE_WRAPPER(Float, float, "%f")
DEFINE_PRIMITIVE_WRAPPER(Double, double, "%f")
#undef DEFINE_PRIMITIVE_WRAPPER |
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org/">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Student Review Quiz Page</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<link rel="stylesheet" th:href="@{/css/styles.css}">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
</head>
<body>
<header class="header" id="header">
<nav class="navbar navbar-expand-lg navbar-light">
<h2><a exact="true" class="logo" th:href="@{#}">LMS</a></h2>
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
</li>
</ul>
<div sec:authorize="isAuthenticated()">
<ul class="navbar-nav">
<li class="nav-item dropdown">
<a class="nav-link" href="#" id="navbarDropdown" style=" color: #7d99ff; " data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Welcome <b><span sec:authentication="name">Username</span></b>
<span sec:authentication="principal.authorities">Roles</span>
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
<a class="dropdown-item" th:href="@{/logout}">Logout</a>
</div>
</li>
</ul>
</div>
</nav>
</header>
<div class="wrapper">
<!-- Sidebar -->
<nav id="sidebar">
<ul class="list-unstyled components">
<li>
<a th:href="@{/student/home}"><i class="fas fa-tachometer-alt"></i>Dashboard</a>
</li>
<li class="active">
<a th:href="@{/student/class}"><i class="fas fa-list-ul"></i>Class</a>
</li>
<li>
<a th:href="@{'/student/assignment/' + ${session.studentCurrentIdClass}}"><i class="fas fa-hand-point-right"></i>List Assignments</a>
</li>
<li>
<a th:href="@{'/student/quiz/showQuizesStudent/'+${session.class.idClass}+'/1'}"><i class="fas fa-hand-point-right"></i>List Quizzes</a>
</li>
<li class="act">
<a th:href="@{/student/markReport}"><i class="fas fa-hand-point-right"></i>Mark Report</a>
</li>
<li>
<a th:href="@{/student/account}"><i class="fas fa-id-card"></i>Account</a>
</li>
</ul>
</nav>
<div id="content">
<div class="container-fluid">
<div class="d-flex justify-content-between mt-4">
<div>
<h3><i class="fas fa-puzzle-piece"></i> [[${nameQuiz}]] </h3>
</div>
</div>
<div class="main-container">
<div class="row pb-5 mb-4">
<div class="col-12 mt-4" th:each="feedback:${feedbacks}">
<!-- Card-->
<div class="card rounded shadow-sm border-0" >
<div class="card-body" >
<div class="d-flex justify-content-between">
<div>
<h5 th:text="${feedback.key.contentQuestion}" ></h5>
<ol type="A">
<li th:each="answer:${feedback.value}">
<div th:each="listQuizDetail:${listQuizDetails}">
<div th:if="${answer.question.idQuestion} == ${listQuizDetail.idQuestion}"
th:class="${answer.isCorrect} ? 'alert alert-success'" role="alert">
<input type="radio" th:name="'answer' + ${answer.idAnswer}"
th:checked="${answer.idAnswer} == ${listQuizDetail.userAnswer}" disabled />
<label th:text="${answer.content}"></label>
</div>
</div>
</li>
</ol>
</div>
<div>
<div class="text-right font-weight-bold p-2">
<div th:each="answer:${feedback.value}">
<div th:each="listQuizDetail:${listQuizDetails}">
<div th:if="${answer.question.idQuestion} == ${listQuizDetail.idQuestion}">
<b class="text-success" th:if="${answer.idAnswer} == ${listQuizDetail.userAnswer} and ${answer.isCorrect}==True">Corrected</b>
<b class="text-danger" th:if="${answer.idAnswer} == ${listQuizDetail.userAnswer} and ${answer.isCorrect}==False">Not Correct</b>
<b class="text-danger" th:if="${listQuizDetail.userAnswer} == -1 and ${answer.isCorrect}==True">Not Correct</b>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-12 mt-4 text-center">
<div class="form-group">
<a th:href="@{/student/markReport}" class="btn btn-success">Back</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html> |
{% load static %}
<nav class="navbar navbar-expand-lg navbar-light" style="background-color: lightskyblue">
<div class="container">
<a class="navbar-brand" href="{% url 'posts:index' %}">
<img src="{% static 'img/logo.png' %}" width="30" height="30" class="d-inline-block align-top">
<span style="color:red">Ya</span>tube
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarContent"
aria-controls="navbarContent" aria-expanded="false">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav nav-pills mr-auto mb-2"
{% with request.resolver_match.view_name as view_name %}>
<li class="nav-item mt-3">
<a class="nav-link {% if view_name == 'about:author' %}active{% endif %}" style="color: black"
href="{% url 'about:author' %}">Об авторе</a>
</li>
<li class="nav-item mt-3">
<a class="nav-link {% if view_name == 'about:tech' %}active{% endif %}" style="color: black"
href="{% url 'about:tech' %}">Технологии</a>
</li>
{% if user.is_authenticated %}
<li class="nav-item mt-3">
<a class="nav-link {% if view_name == 'posts:post_create' %}active{% endif %}" style="color: black"
href="{% url 'posts:post_create' %}">Новая запись</a>
</li>
<li class="nav-item mt-3">
<a class="nav-link link-light {% if view_name == 'users:password_change' %}active{% endif %}" style="color: white"
href="{% url 'users:password_change' %}">Изменить пароль</a>
</li>
<li class="nav-item mt-3">
<a class="nav-link link-light {% if view_name == 'users:logout' %}active{% endif %}" style="color: white"
href="{% url 'users:logout' %}">Выйти</a>
</li>
<li class="navbar-text mt-3" style="color: darkblue">
Пользователь: {{ user.username }}
</li>
{% else %}
<li class="nav-item mt-3">
<a class="nav-link link-light {% if view_name == 'users:login' %}active{% endif %}" style="color: white"
href="{% url 'users:login' %}">Войти</a>
</li>
<li class="nav-item mt-3">
<a class="nav-link link-light {% if view_name == 'users:signup' %}active{% endif %}" style="color: white"
href="{% url 'users:signup' %}">Регистрация</a>
</li>
{% endif %}
{% endwith %}
</ul>
<form action="" class="d-flex"></form>
</div>
</div>
</nav>
<script src="{% static 'js/bootstrap.bundle.min.js' %}"></script>
</header> |
// App.js
import React from 'react';
import { View, StyleSheet } from 'react-native';
import Header from './components/Header';
import Container from './components/Container';
import Advice from './components/Advice';
import Footer from './components/Footer';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import SobreMim from './components/SobreMim';
import SobreAPI from './components/SobreAPI';
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ headerShown: false }}
/>
<Stack.Screen
name="SobreMim"
component={SobreMim}
options={{ title: 'Sobre Mim' }}
/>
<Stack.Screen
name="SobreAPI"
component={SobreAPI}
options={{ title: 'Sobre a API' }}
/>
</Stack.Navigator>
</NavigationContainer>
);
};
const HomeScreen = ({ navigation }) => {
const navigateToSobreMim = () => {
navigation.navigate('SobreMim');
};
const navigateToSobreAPI = () => {
navigation.navigate('SobreAPI');
};
return (
<View style={styles.appContainer}>
<Header
onSobreMimPress={navigateToSobreMim}
onSobreAPIPress={navigateToSobreAPI}
/>
<Container>
<Advice />
</Container>
<Footer />
</View>
);
};
const styles = StyleSheet.create({
appContainer: {
flex: 1,
},
});
export default App; |
import React from "react";
import deleteIcon from "../../assets/delete.svg";
import { getImgUrl } from "../../utils/movie-utility";
const CartItem = ({ movie, onRemoveItem }) => {
return (
<div className="grid grid-cols-[1fr_auto] gap-4">
<div className="flex items-center gap-4">
<img
className="rounded max-w-[60px] max-h-[75px] overflow-hidden"
src={getImgUrl(movie.cover)}
alt=""
/>
<div>
<h3 className="text-base md:text-xl font-bold">{movie.title}</h3>
<p className="max-md:text-xs text-[#575A6E]">{movie.genre}</p>
<span className="max-md:text-xs">${movie.price}</span>
</div>
</div>
<div className="flex justify-between gap-4 items-center">
<button
className="bg-[#D42967] rounded-md p-2 md:px-4 inline-flex items-center space-x-2 text-white"
onClick={() => onRemoveItem(movie)}
>
<img className="w-5 h-5" src={deleteIcon} alt="" />
<span className="max-md:hidden">Remove</span>
</button>
</div>
</div>
);
};
export default CartItem; |
public class SoftwareEngineer extends TechnicalEmployee {
public boolean accessToCode;
public SoftwareEngineer(String name) {
//Should start without access to code and with 0 code check ins
super(name);
setCodeAccess(true);
}
public boolean getCodeAccess() {
//Should return whether or not this SoftwareEngineer has access to make changes to the code base
return accessToCode;
}
public void setCodeAccess(boolean access) {
//Should allow an external piece of code to update the SoftwareEngieer's code privileges to either true or false
accessToCode = access;
}
public int getSuccessfulCheckIns() {
//Should return the current count of how many times this SoftwareEngineer has successfully checked in code
return checkIns;
}
public boolean checkInCode() {
//Should check if this SoftwareEngineer's manager approves of their check in.
// If the check in is approved their successful checkin count should be increased and the method should return "true".
// If the manager does not approve the check in the SoftwareEngineer's code access
// should be changed to false and the method should return "false"
TechnicalLead manager = (TechnicalLead) this.getManager();
if (manager.approveCheckIn(this)) {
this.checkIns++;
return true;
} else {
accessToCode = false;
return false;
}
}
} |
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from rest_framework.test import APITestCase
class AccountsTestCase(APITestCase):
def setUp(self):
self.username = "test_user"
self.password = "TestingPass123"
User.objects.create_user(
email=self.username,
username=self.username,
password=self.password,
is_staff=True,
is_superuser=True,
is_active=True,
)
def test_login(self):
payload = {"username": self.username, "password": self.password}
url = "/internal/login/"
response = self.client.post(url, payload)
sessions = Session.objects.all()
self.assertEqual(response.status_code, 200)
self.assertEqual(len(sessions), 1)
def test_register(self):
payload = {"username": "new_user", "password": self.password, "repeat_password": self.password}
url = "/internal/register/"
response = self.client.post(url, payload)
self.assertEqual(response.status_code, 201)
users = User.objects.all()
self.assertEqual(len(users), 2) |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from itertools import groupby
def is_numeric_value(value):
if value:
return value.replace('.', '', 1).isdigit() or value.replace(',', '', 1).isdigit()
return False
class AgreementsInsurer(models.Model):
_name = "agreements.insurer"
_description = """Acuerdos con aseguradoras"""
_order = "default"
@api.depends("insurer_id", "coverage_id", "short_name")
def _compute_name(self):
for this in self:
insurer_name = this.insurer_id.name if this.insurer_id else ""
coverage_name = this.coverage_id.name if this.coverage_id else ""
short_name = this.short_name if this.short_name else ""
this.name = "{insurer_name} - {coverage_name} - {short_name}".format(insurer_name=insurer_name,
coverage_name=coverage_name,
short_name=short_name)
name = fields.Char(
string="Nombre",
readonly=True,
compute="_compute_name"
)
short_name = fields.Char(
string="Nombre Corto"
)
insurer_id = fields.Many2one(
'res.partner',
string='Aseguradora',
)
coverage_id = fields.Many2one(
'coverage.template',
string='Plantilla de coberturas',
required=True
)
agreements_line_ids = fields.One2many(
'agreements.insurer.line',
'agreements_id',
string='Acuerdos Aseguradora'
)
contract_id = fields.Many2one(
"broker.contract",
string="Contrato Asociado"
)
default = fields.Boolean(
string="¿Es producto cerrado?",
default=False
)
amount_fee = fields.Float(
string="Prima Neta",
compute="get_amount_fee"
)
base_product_id = fields.Many2one(
"agreements.insurer",
string="Acuerdo Base"
)
is_quotation = fields.Boolean(
string="Es Cotización?",
default=False
)
@api.model_create_multi
def create(self, vals_list):
agreement_object_obj = self.env['movement.object.agreement'].sudo()
agreements = super().create(vals_list)
list_object = []
if self.env.context.get("object_id") and self.env.context.get("lead_id"):
for agree in agreements:
res = {
"agreement_id": agree.id,
"object_id": self.env.context.get("object_id"),
"state": "draft",
}
list_object.append(res)
agreement_object_obj.create(list_object)
params = {
"default_identification": self.env.context.get("object_id")
}
return agreements
@api.depends("agreements_line_ids")
def get_amount_fee(self):
value = False
if self.agreements_line_ids:
values = self.agreements_line_ids.filtered(
lambda line: line.is_amount_fee and is_numeric_value(line.value)).mapped("value")
value = sum([float(val) for val in values])
self.amount_fee = value
@api.onchange("coverage_id")
def _onchange_coverage(self):
for this in self:
for line in this.agreements_line_ids:
line.unlink()
list_lines = []
coverage_lines = this.coverage_id.coverage_line_ids
if coverage_lines:
line_order = sorted(coverage_lines, key=lambda x: x.sequence, reverse=False)
for line in line_order:
list_lines.append(fields.Command.create({
"field": line.field,
"sequence": line.sequence,
"name": line.name,
"display_type": line.display_type,
"name_title": line.title_line.id if line.title_line else None,
"coverage_line_id": line.id
}))
this.write({'agreements_line_ids': list_lines})
def create_data_agreement(self, object_id):
for this in self:
data = {
"nombre": this.name,
"company": this.insurer_id.id,
"id": this.id,
}
groups = {}
lines_visible = object_id.coverage_template_id.coverage_line_ids.filtered(lambda tmp: tmp.visible).mapped(
"id")
agreements_sorted = sorted(
this.agreements_line_ids.filtered(
lambda l: not l.display_type == 'line_section' and l.coverage_line_id.id in lines_visible),
key=lambda x: x.sequence)
for key, group in groupby(agreements_sorted, key=lambda x: x.name_title.name):
groups[key] = list(group)
section = []
for key, groups in groups.items():
res_section = {
"name": key,
}
lines = []
for line in groups:
edit = line.coverage_line_id.internal
coverage = line.coverage_line_id.is_coverage
res = {
"value": line.value if line.value else "N/A",
"id": line.id,
"edit": edit,
"rate": line.rate,
"amount_insured": line.amount_insured,
"coverage": coverage
}
lines.append(res)
res_section.update({
"line": lines
})
section.append(
res_section
)
data.update({
"section": section
})
return data
@api.returns('self', lambda value: value.id)
def copy(self, default=None):
default = dict(default or {})
amount_insured = False
if default.get("amount_insured"):
amount_insured = default.get("amount_insured")
default.pop("amount_insured",None)
coverage_id = self.coverage_id.id if not default.get("coverage_id") else default.get("coverage_id")
default.update({
"default": False,
"short_name": self.short_name,
"name": self.name,
"amount_fee": self.amount_fee,
"insurer_id": self.insurer_id.id,
"base_product_id": self.id,
"coverage_id": coverage_id,
})
agreement = super(AgreementsInsurer, self).copy(default=default)
agreement._onchange_coverage()
lines_origin = self.agreements_line_ids.filtered(lambda line_origin: line_origin.display_type == 'attribute')
for line in agreement.agreements_line_ids.filtered(lambda line_new: line_new.display_type == 'attribute'):
line_origin = lines_origin.filtered(lambda l_origin: l_origin.field == line.field)
if line_origin:
line.amount_insured = (amount_insured or line_origin[0].amount_insured) if not line.is_limit else 0.0
line.rate = line_origin[0].rate
line.value = line_origin[0].value
return agreement
class AgreementsInsurerLine(models.Model):
_name = "agreements.insurer.line"
agreements_id = fields.Many2one(
'agreements.insurer',
string='Acuerdo con aseguradoras'
)
coverage_line_id = fields.Many2one(
"coverage.template.line",
string="Linea de plantilla"
)
sequence = fields.Integer(
related='coverage_line_id.sequence',
store=True
)
display_type = fields.Selection(
related='coverage_line_id.display_type',
store=True
)
name = fields.Char(
related='coverage_line_id.name',
store=True
)
field = fields.Char(
related='coverage_line_id.field',
store=True
)
is_amount_fee = fields.Boolean(
related='coverage_line_id.is_amount_fee',
store=True
)
amount_insured = fields.Float(
string="Valor Asegurado"
)
rate = fields.Char(
string="Tasa"
)
is_coverage = fields.Boolean(
related='coverage_line_id.is_coverage',
store=True
)
is_deductible = fields.Boolean(
related='coverage_line_id.is_deductible',
store=True
)
is_limit = fields.Boolean(
related='coverage_line_id.is_limit',
store=True
)
value = fields.Text(
'Valor'
)
name_title = fields.Many2one(
related='coverage_line_id.title_line',
store=True
)
def name_get(self):
result = []
for record in self:
name = record.field if record.field else record.name
result.append((record.id, name))
return result
def set_value_line(self, value, field):
for this in self:
values = {
field: value
}
this.write(values)
if field != 'value':
this.onchange_value()
@api.onchange("rate", "amount_insured")
def onchange_value(self):
if self.rate and is_numeric_value(self.rate):
value_data = self.amount_insured * (float(
self.rate.replace(",", ".")) / 100) if self.amount_insured and self.amount_insured > 0 else None
self.value = round(value_data, 2)
elif self.rate and not is_numeric_value(self.rate):
self.value = "SIN COSTO" |
import { useState } from "react";
const useList = <T,>(initialState: Array<T>) => {
const [items, setItems] = useState<Array<T>>(initialState);
const remove = (index: number) => {
setItems((prevItems) => {
const updatedtems = [...prevItems];
updatedtems.splice(index, 1);
return updatedtems;
});
};
const add = (value: T) => {
setItems((prevItems) => [...prevItems, value]);
};
const setItem = (value: T, index: number) => {
setItems((prevItems) => {
const updatedtems = [...prevItems];
updatedtems[index] = value;
return updatedtems;
});
};
return {
items,
setItems,
setItem,
remove,
add,
};
};
export default useList; |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.columnar
import scala.collection.immutable.HashSet
import scala.util.Random
import java.sql.{Date, Timestamp}
import org.apache.spark.sql.Row
import org.apache.spark.sql.catalyst.expressions.GenericMutableRow
import org.apache.spark.sql.catalyst.types.{DataType, NativeType}
object ColumnarTestUtils {
def makeNullRow(length: Int) = {
val row = new GenericMutableRow(length)
(0 until length).foreach(row.setNullAt)
row
}
def makeRandomValue[T <: DataType, JvmType](columnType: ColumnType[T, JvmType]): JvmType = {
def randomBytes(length: Int) = {
val bytes = new Array[Byte](length)
Random.nextBytes(bytes)
bytes
}
(columnType match {
case BYTE => (Random.nextInt(Byte.MaxValue * 2) - Byte.MaxValue).toByte
case SHORT => (Random.nextInt(Short.MaxValue * 2) - Short.MaxValue).toShort
case INT => Random.nextInt()
case LONG => Random.nextLong()
case FLOAT => Random.nextFloat()
case DOUBLE => Random.nextDouble()
case STRING => Random.nextString(Random.nextInt(32))
case BOOLEAN => Random.nextBoolean()
case BINARY => randomBytes(Random.nextInt(32))
case DATE => new Date(Random.nextLong())
case TIMESTAMP =>
val timestamp = new Timestamp(Random.nextLong())
timestamp.setNanos(Random.nextInt(999999999))
timestamp
case _ =>
// Using a random one-element map instead of an arbitrary object
Map(Random.nextInt() -> Random.nextString(Random.nextInt(32)))
}).asInstanceOf[JvmType]
}
def makeRandomValues(
head: ColumnType[_ <: DataType, _],
tail: ColumnType[_ <: DataType, _]*): Seq[Any] = makeRandomValues(Seq(head) ++ tail)
def makeRandomValues(columnTypes: Seq[ColumnType[_ <: DataType, _]]): Seq[Any] = {
columnTypes.map(makeRandomValue(_))
}
def makeUniqueRandomValues[T <: DataType, JvmType](
columnType: ColumnType[T, JvmType],
count: Int): Seq[JvmType] = {
Iterator.iterate(HashSet.empty[JvmType]) { set =>
set + Iterator.continually(makeRandomValue(columnType)).filterNot(set.contains).next()
}.drop(count).next().toSeq
}
def makeRandomRow(
head: ColumnType[_ <: DataType, _],
tail: ColumnType[_ <: DataType, _]*): Row = makeRandomRow(Seq(head) ++ tail)
def makeRandomRow(columnTypes: Seq[ColumnType[_ <: DataType, _]]): Row = {
val row = new GenericMutableRow(columnTypes.length)
makeRandomValues(columnTypes).zipWithIndex.foreach { case (value, index) =>
row(index) = value
}
row
}
def makeUniqueValuesAndSingleValueRows[T <: NativeType](
columnType: NativeColumnType[T],
count: Int) = {
val values = makeUniqueRandomValues(columnType, count)
val rows = values.map { value =>
val row = new GenericMutableRow(1)
row(0) = value
row
}
(values, rows)
}
} |
package Gladiator
import public ObjectIdGenerator
import public HeroDefaults
import public Icons
import public Charge
import public initlater Artifact
import public SoundUtils
import LinkedList
import ErrorHandling
import AbilityObjEditing
import CompileTimeData
import ObjectIds
import UtilCommands
import MapBounds
import ClosureForGroups
import Stats
let MASTERY_SHOP_POSITIONS = boundMax + vec2(-1000, 1000)
public function getAllGladiators() returns LinkedList<Gladiator>
return Gladiator.instances
public class Gladiator
protected static let instances = new LinkedList<thistype>
private unit gladiatorUnit
private GladiatorType gladiatorType
private player owner
private unit masteryShop = null
private var abilitiesReleased = 0
construct(GladiatorType gladiatorType, player owner, vec2 spawnPos, angle facing )
this.owner = owner
this.gladiatorType = gladiatorType
gladiatorUnit = gladiatorType.createGladiatorUnit(owner, spawnPos, facing)
if( gladiatorType.masteryShopType == 0 )
error("Mastery shop type for {0} has not been set!".format(gladiatorType.getName()))
masteryShop = createUnit(owner, gladiatorType.masteryShopType, MASTERY_SHOP_POSITIONS, angle(0))
instances.add(this)
/** Releases an ability, adding it to the gladiator unit. The abilityNumber is the number in the list */
function unlockNextAbility() returns string
let abilities = gladiatorType.getAllAbilities()
if( abilities.size() <= abilitiesReleased)
Log.warn("{0}'s {1} should release ability {2}, but the gladiator only has {3} abilities".format(
owner.getNameColored(), gladiatorUnit.getName(), abilitiesReleased.toString(), abilities.size().toString() ))
return ""
let abilityId = abilities.get(abilitiesReleased)
if( gladiatorUnit.getAbilityLevel(abilityId) > 0 )
Log.error("{0}'s {1} already has that ability".format(owner.getNameColored(), gladiatorUnit.getName()))
else
gladiatorUnit.addAbility(abilityId)
abilitiesReleased++
return GetAbilityName(abilityId)
function getUnit() returns unit
return gladiatorUnit
function getSpawnSound() returns SoundDefinition
return gladiatorType.getSoundOnSpawn()
function getRespawnSound() returns SoundDefinition
return gladiatorType.getSoundOnRespawn()
function getSoundOnNewAbility() returns SoundDefinition
return gladiatorType.getSoundOnNewAbility()
/** Refreshes the gladiator, healing it and running all RefreshFunctions defined for the
GladiatorType (refresh cooldowns i.e.) */
function refresh()
if( gladiatorUnit.isAlive() )
gladiatorUnit.setHP(gladiatorUnit.getMaxHP())
gladiatorUnit.setMana(gladiatorUnit.getMaxMana())
gladiatorUnit.resetCooldown()
for action in gladiatorType.refreshActions
action.run(gladiatorUnit )
function getOwner() returns player
return owner
function getColor() returns color
return gladiatorType.getColor()
function getGladiatorType() returns GladiatorType
return gladiatorType
function getMasteryShop() returns unit
return masteryShop
static function isUnitGladiator(unit whichUnit) returns boolean
return getInstance(whichUnit) != null
static function getInstance(unit whichUnit) returns Gladiator
for instance in instances
if instance.gladiatorUnit == whichUnit
return instance
return null
static function getInstance(player whichPlayer) returns Gladiator
for instance in instances
if instance.owner == whichPlayer
return instance
return null
interface GladiatorAction
function run(unit gladiator)
public class GladiatorType
private static let allTypes = new LinkedList<thistype>
private static boolean hasBeenInitialized
private string name
private int unitType
private color col
private string chargeIcon
private string chargeName
private string chargeDescription
private let abilities = new LinkedList<int>
private let artifacts = new LinkedList<Artifact>
private SoundDefinition snd_Spawn = null
private SoundDefinition snd_Respawn = null
private SoundDefinition snd_NewAbility = null
private LinkedList<GladiatorAction> actions_OnSpawn = null
protected let refreshActions = new LinkedList<GladiatorAction>
protected int masteryShopType = 0
construct(string name)
allTypes.add(this)
this.name = name
function setUnitType(int unitType)
this.unitType = unitType
let tempUnit = createUnit(Player(PLAYER_NEUTRAL_PASSIVE), unitType, vec2(0,0),angle(0))
name = tempUnit.getName()
tempUnit.remove()
function setBaseStats(real damage, real armor, real health, real attackSpeed, real moveSpeed, real energy, real energyRegen)
unitType
..setUnitTypeStat(STAT_DAMAGE, damage)
..setUnitTypeStat(STAT_ARMOR, armor)
..setUnitTypeStat(STAT_HEALTH, health)
..setUnitTypeStat(STAT_ATTACKSPEED, attackSpeed)
..setUnitTypeStat(STAT_MOVESPEED, moveSpeed)
..setUnitTypeStat(STAT_ENERGY, energy )
..setUnitTypeStat(STAT_ENERGY_REGEN, energyRegen )
..setUnitTypeStat(STAT_RESISTANCE, 0)
function setSoundOnSpawn(string soundPath)
snd_Spawn = new SoundDefinition(soundPath, false)
function setSoundOnRespawn(string soundPath)
snd_Respawn = new SoundDefinition(soundPath, false)
function setSoundOnNewAbility(string soundPath)
snd_NewAbility = new SoundDefinition(soundPath, false)
function setColor(color col)
this.col = col
function setMasteryShopType(int masteryShopType)
this.masteryShopType = masteryShopType
function addAbilities(vararg int abilities)
for abil in abilities
this.abilities.add(abil)
function getSoundOnSpawn() returns SoundDefinition
checkInit()
return snd_Spawn
function getSoundOnRespawn() returns SoundDefinition
checkInit()
return snd_Respawn
function getSoundOnNewAbility() returns SoundDefinition
checkInit()
return snd_NewAbility
function getAbility(int number) returns int
checkInit()
return abilities.size() >= number ? 0 : abilities.get(number)
function getAllAbilities() returns LinkedList<int>
checkInit()
return abilities
function getUnitType() returns int
checkInit()
return unitType
function getColor() returns color
return col
function addActionOnSpawn( GladiatorAction action )
if actions_OnSpawn == null
actions_OnSpawn = new LinkedList<GladiatorAction>
actions_OnSpawn.add(action)
private static function checkInit()
if not hasBeenInitialized
initialize()
function createGladiatorUnit(player owner, vec2 spawnPos, angle facing) returns unit
let gladiatorUnit = createUnit(owner, unitType, spawnPos, facing)
..suspendXp(true)
..enableCharge()
if actions_OnSpawn != null
for action in actions_OnSpawn
action.run(gladiatorUnit)
return gladiatorUnit
function getName() returns string
return name
function getNameColored() returns string
return col.toColorString() + name + "|r"
function addArtifacts(vararg Artifact artifacts)
for artifact in artifacts
this.artifacts.add(artifact)
function releaseNextArtifact() returns Artifact
for artifact in artifacts
if not artifact.isReleased()
artifact.release()
return artifact
return null
function onRefresh(GladiatorAction action)
refreshActions.add(action)
static function getAllTypes() returns LinkedList<thistype>
return allTypes
private static function initialize()
hasBeenInitialized = true
public let allGladiatorIds = new LinkedList<int>
let data_GladiatorUnitIds = compiletime(defineDataObj())
let HERO_GLOW_ABILITY_ID = 'A020'
/** Defines the generics of a gladiator unit (hide minimap, set attack type etc. ) */
public function defineGladiatorUnit(int newId, int originId, string name, string icon, bool addHeroGlow, string chargeName, string chargeDescription, string chargeIcon) returns HeroDefinition
let chargeAbilityId = defineGladiatorChargeAbility(chargeName, chargeDescription, chargeIcon)
let definition = new HeroDefinition(newId, originId)
..setName(name)
..setProperNames(name)
..setIconGameInterface(icon)
..setSightRadiusNight(1800)
..setSightRadiusNight(1800)
..setManaMaximum(100)
..hideHeroMinimapDisplay(true)
..setCanFlee(false)
..setSpeedBase(250)
..setAgilityPerLevel(0)
..setStrengthPerLevel(0)
..setIntelligencePerLevel(0)
..setHitPointsRegenerationRate(0)
..setCollisionSize(25)
..setArmorType(ArmorType.Medium)
..setAttack1AttackType(AttackType.Normal)
..setSelectionScale(1.4)
..setHeroAbilities("")
..setNormalAbilities(
AbilityIds.inventory.toRawCode() + "," + chargeAbilityId.toRawCode() + (addHeroGlow ? ", " + HERO_GLOW_ABILITY_ID.toRawCode() : ""))
..hideHeroDeathMsg(true)
..hideHeroInterfaceIcon(true)
..setTooltipBasic(name)
..setDescription("")
..setTooltipExtended("")
..setGoldCost(0)
..setLumberCost(0)
..setFoodCost(0)
..setStockMaximum(1)
..setStockStartDelay(0)
..setStockReplenishInterval(1)
..setButtonPositionX(0)
..setButtonPositionY(0)
..setUnitSoundSet("")
..setRequirements("")
..setAttacksEnabled(1)
..setAttack1AttackType(AttackType.Normal)
..setAttack1DamageBase(1)
..setAttack1DamageSidesperDie(1)
..setAttack1DamageNumberofDice(1)
..setAttack1AttackType(AttackType.Normal)
..setTurnRate(3)
..setOrientationInterpolation(0) // Allows for almost instant visual turning
data_GladiatorUnitIds.addData(newId.toRawCode())
return definition
public function defineGladiatorChargeAbility(string name, string description, string icon) returns int
let abilityId = ABIL_ID_GEN.next()
new AbilityDefinitionAuraEnduranceCreep(abilityId)
..setTooltipNormal(1, "Charge: " + name)
..setTooltipNormalExtended(1, description)
..setIconNormal(icon)
..setButtonPositionNormalX(3)
..setButtonPositionNormalY(1)
..setHotkeyNormal("none")
..setTargetsAllowed(1, "none")
..setAreaEffect("none")
..setArtCaster("none")
..setArtSpecial("none")
..setArtTarget("none")
..setAreaofEffect(1, 0)
..setAttackSpeedIncrease(1, 0)
..setMovementSpeedIncrease(1, 0)
return abilityId
init
for stringId in data_GladiatorUnitIds.getData()
allGladiatorIds.add(stringId.fromRawCode())
// Chat Commands
init
let cmd = defineUtilCommand("gladiator")
var sub = cmd.addSubCommand("getall")
..setAction() (p, args, opts) ->
var gladiatorNames = ""
for gladiator in getAllGladiators()
gladiatorNames += "\n " + gladiator.getOwner().getNameColored() + ": " + gladiator.getUnit().getProperName()
p.print("\nGladiators:" + gladiatorNames)
// Spawn Gladiator
sub = cmd.addSubCommand("new")
..addArgument(ArgumentType.STRING)
..setAction() (p, args, opts) ->
GladiatorType gladType = null
let gladName = args.getString()
var allNames = ""
for gladiator in GladiatorType.getAllTypes()
let adjustedName = gladiator.getName().replace(" ", "").replace("-", "").toLowerCase()
if( adjustedName == gladName )
gladType = gladiator
if(allNames != "")
allNames += ", "
allNames += adjustedName
if( gladType == null )
p.print("Couldn't find gladiator type '{0}'. Available types are: {1}".format(gladName.highlight(), allNames))
else
new Gladiator(gladType, p, p.getMousePos(), angle(0))
sub.addHelpCommand("Spawns a Gladiator for of a given gladiator type. The type is name in lower-case without spaces and '-'. (i.e. Half-Breed -> halfbreed)")
// Unlock abilites for selected gladiators
sub = cmd.addSubCommand("unlockability")
..addArgument(ArgumentType.INT)
..setAction() (p,args,opts) ->
forUnitsSelected(p) u ->
let abilitiesToUnlock = args.getInt()
if( not Gladiator.isUnitGladiator(u) )
p.print("{0} is not a gladiator".format(u.getName().highlight()))
else
let gladiator = Gladiator.getInstance(u)
let name = gladiator.getGladiatorType().getNameColored()
for i=0 to abilitiesToUnlock
let abilityName = gladiator.unlockNextAbility()
if( abilityName != "" )
p.print("Unlocked {0} for {1}.".format(abilityName.highlight(), name), 8) |
import random
import csv
from common.magic_item_properties import *
from config.config import *
def get_item_price(rarity):
min_price, max_price = price_ranges.get(rarity, (0, 0))
return random.randint(min_price, max_price)
def roll_dice(max_value):
return random.randint(1, max_value)
def get_magic_items_from_file(file_name):
magic_items = []
with open(file_name, "r") as file:
reader = csv.reader(file, delimiter="\t")
for row in reader:
magic_items.append(row)
return magic_items
def get_magic_item(rarity):
filename = f"data/{rarity}.csv"
try:
with open(filename, "r") as file:
items = [line.strip() for line in file.readlines() if line.strip()]
if not items:
return None
item = random.choice(items)
return item
except FileNotFoundError:
return None
def get_magic_item_url(magic_item_name, magic_items_info):
for item_info in magic_items_info:
if item_info[0] == magic_item_name:
return item_info[1]
return ""
def get_magic_item_from_table(table_number, row_number):
if table_number not in table_mapping:
print("Invalid table number.")
return
table_name = table_mapping[table_number]
filename = f"data/{table_name}.csv"
try:
with open(filename, "r") as file:
items = [line.strip() for line in file.readlines() if line.strip()]
if not items:
return None
item = items[row_number - 1] # Adjust row number to 0-based index
return item
except FileNotFoundError:
return None
def determine_enchantment():
enchantment_roll = random.random()
enchantment_index = random.randint(0, 99)
if enchantment_roll < curse_probability:
return "Cursed", item_curses[enchantment_index]
elif enchantment_roll < curse_probability + blessing_probability:
return "Blessed", item_boons[enchantment_index]
else:
return None, None
def pick_random_rarity():
rand_val = random.random()
cumulative_prob = 0
for rarity, probability in rarities_probabilities.items():
cumulative_prob += probability
if rand_val <= cumulative_prob:
return rarity
return "common"
def generate_item_notes(magic_item_name):
notes = ""
if "spell scroll" in magic_item_name.lower():
spell_level = magic_item_name.split("(")[-1].replace(")", "").strip()
if spell_level in spells_by_level:
random_spell = random.choice(spells_by_level[spell_level])
notes = "Spell: " + random_spell
elif "of resistance" in magic_item_name.lower():
notes = "Resistance: " + random.choice(resistance_types)
return notes
def get_xlation(key):
if key in xlations:
return xlations[key]
return key |
import React, { useState } from "react";
import "./Home.css";
import { MagnifyingGlass, MapPin, CaretRight } from "phosphor-react";
import Card from "../components/Card";
import Modal from "../components/Modal";
import CardOn from "../components/CardOn";
import ModalAction from "../components/ModalAction";
import CardInst from "../components/CardInst";
export default function Home() {
const [isModalOpen, setIsModalOpen] = useState(false);
const [isModalActionOpen, setIsModalActionOpen] = useState(false);
const [modalTitle, setModalTitle] = useState("");
const [modalImg, setModalImg] = useState("");
const [modalDate, setModalDate] = useState("");
const [modalLoc, setModalLoc] = useState("");
const [modalMonth, setModalMonth] = useState("");
const [modalDesc, setModalDesc] = useState("");
const [modalInstLogo, setModalInstLogo] = useState("");
const [modalInst, setModalInst] = useState("");
const openModal = () => {
setIsModalOpen(true);
};
const closeModal = () => {
setIsModalOpen(false);
};
const closeModalAction = () => {
setIsModalActionOpen(false);
};
return (
<>
<Modal isOpen={isModalOpen} onClose={closeModal} />
<ModalAction
isOpen={isModalActionOpen}
onClose={closeModalAction}
modalTitle={modalTitle}
modalImg={modalImg}
modalDate={modalDate}
modalLoc={modalLoc}
modalMonth={modalMonth}
modalDesc={modalDesc}
modalInstLogo={modalInstLogo}
modalInst={modalInst}
/>
<header>
<div className="head">
<div className="logo">
<img src="https://i.ibb.co/SKpGhQf/Vector.png" alt="" />
<h1>abrace</h1>
</div>
<div className="search-box">
<input type="text" placeholder="Procure projetos perto de você" />
<MagnifyingGlass size={32} color="#000" />
</div>
</div>
<div className="more">
<h3>
Seja um agente de transformação em sua vizinhança.
<br /> Encontre projetos próximos e abrace uma causa!
</h3>
<button onClick={openModal}>Saiba Mais</button>
</div>
</header>
<main>
<div className="actions">
<h2>Projetos em destaque</h2>
<div className="actions-box">
<a
onClick={() => {
setIsModalActionOpen(true);
setModalTitle("Atletas do Futuro");
setModalImg(
"https://i.ibb.co/xC6jFF5/serge-kutuzov-FPy-FUndok-unsplash.jpg"
);
setModalDate("13 a 15");
setModalLoc("Bugio");
setModalMonth("Outubro");
setModalInst("Associação Educação em Movimento");
setModalInstLogo(
"https://t4.ftcdn.net/jpg/04/39/50/43/360_F_439504373_11n5huxPHDCsECv6PbjIxFB9gqHil1dc.jpg"
);
setModalDesc(
"O projeto social Atletas do Futuro é uma iniciativa que visa proporcionar oportunidades de desenvolvimento físico, emocional e social para crianças da nossa comunidade. Através de oficinas esportivas, buscamos não apenas promover um estilo de vida ativo, mas também cultivar valores como trabalho em equipe, disciplina, respeito e autoconfiança, preparando essas crianças para um futuro brilhante."
);
}}
>
<Card
cardDate={"13 a 15"}
cardMonth={"Out"}
cardTitle={"Atletas do Futuro"}
cardLoc={"Bugio"}
image={"https://i.ibb.co/xC6jFF5/serge-kutuzov-FPy-FUndok-unsplash.jpg"}
/>
</a>
<a
onClick={() => {
setIsModalActionOpen(true);
setModalTitle("Oficina Arte e Cultura");
setModalImg("https://i.ibb.co/tLQXdz6/oficinaartes.jpg");
setModalDate("18 a 22");
setModalLoc("Santa Maria");
setModalMonth("Outubro");
setModalInst("Fundação Renovar");
setModalInstLogo(
"https://img.freepik.com/vetores-premium/logotipo-infantil-com-design-de-mao-de-pessoas_579179-2339.jpg"
);
setModalDesc(
"O projeto Oficina Arte e Cultura é uma oportunidade única para crianças e jovens explorarem o mundo da arte e da cultura, enquanto desenvolvem habilidades vitais para o seu crescimento pessoal. Através desse projeto, esperamos inspirar futuros artistas, líderes e cidadãos conscientes, que contribuirão para uma sociedade mais inclusiva e criativa. Com o apoio da comunidade, educadores dedicados e artistas voluntários, estamos moldando um futuro mais colorido e culturalmente enriquecido para nossas crianças e jovens."
);
}}
>
<Card
cardDate={"18 a 22"}
cardMonth={"Out"}
cardTitle={"Oficina Arte e Cultura"}
cardLoc={"Santa Maria"}
image={"https://i.ibb.co/tLQXdz6/oficinaartes.jpg"}
/>
</a>
<a
onClick={() => {
setIsModalActionOpen(true);
setModalTitle("Salvando Patinhas");
setModalImg("https://i.ibb.co/dcZH3d6/catanddog.jpg");
setModalDate("30");
setModalLoc("Grageru");
setModalMonth("Outubro");
setModalInst("Centro de Acolhimento e Proteção Animal");
setModalInstLogo(
"https://cdn.dribbble.com/users/113499/screenshots/7671703/media/1c281ce5c275a0f177fe4f3564638af8.png"
);
setModalDesc(
"O projeto social Salvando Patinhas é uma iniciativa amorosa e compassiva dedicada a melhorar a qualidade de vida de animais de rua e residentes em abrigos. Nosso objetivo é arrecadar alimentos, medicamentos e cuidados essenciais para animais abandonados e carentes, proporcionando-lhes uma segunda chance para uma vida mais digna e saudável."
);
}}
>
<Card
cardDate={"30"}
cardMonth={"Out"}
cardTitle={"Salvando Patinhas"}
cardLoc={"Grageru"}
image={"https://i.ibb.co/dcZH3d6/catanddog.jpg"}
/>
</a>
<a
onClick={() => {
setIsModalActionOpen(true);
setModalTitle("Cozinha da Oportunidade");
setModalImg("https://i.ibb.co/yqBS2kv/cooking.jpg");
setModalDate("13 a 17");
setModalLoc("Getúlio Vargas");
setModalMonth("Novembro");
setModalInst(
"Centro de Desenvolvimento Profissional Brilliance"
);
setModalInstLogo(
"https://st2.depositphotos.com/1010751/6195/v/950/depositphotos_61952259-stock-illustration-teamwork-three-people-logo.jpg"
);
setModalDesc(
"Cozinha da Oportunidade é uma iniciativa inspiradora que combina a paixão pela culinária com o espírito empreendedor, proporcionando às pessoas a oportunidade de aprender habilidades culinárias e de negócios. Nosso objetivo é capacitar indivíduos, especialmente aqueles em situação de vulnerabilidade social, para se tornarem chefs empreendedores e construir um futuro sustentável por meio da gastronomia."
);
}}
>
<Card
cardDate={"13 a 17"}
cardMonth={"Nov"}
cardTitle={"Cozinha da Oportunidade"}
cardLoc={"Getúlio Vargas"}
image={"https://i.ibb.co/yqBS2kv/cooking.jpg"}
/>
</a>
<a
onClick={() => {
setIsModalActionOpen(true);
setModalTitle("Arco-Íris da Esperança");
setModalImg("https://i.ibb.co/ykBs25R/lovewins.jpg");
setModalDate("06");
setModalLoc("Centro");
setModalMonth("Novembro");
setModalInst("Instituto Aliança pela Igualdade");
setModalInstLogo(
"https://media.istockphoto.com/id/1363566694/vector/humanitarian-assistance-love-teamwork-voluntary-family-vector-icon-template.jpg?s=612x612&w=0&k=20&c=o1U50c-bdABqNU0axWjEN8Xuz3ErziZ77oVcgbgvs48="
);
setModalDesc(
"O projeto Arco-Íris da Esperança é um farol de amor e esperança para pessoas LGBTQ+ em situação de rua e aquelas que enfrentam desafios de saúde. Ao fornecer cuidados abrangentes e apoio emocional, estamos criando um ambiente onde todos possam florescer e encontrar a esperança e a aceitação que merecem. Com o apoio de voluntários comprometidos, profissionais de saúde e parceiros da comunidade, estamos trabalhando para tornar o mundo mais acolhedor e inclusivo para todos, independentemente de sua orientação sexual ou identidade de gênero."
);
}}
>
<Card
cardDate={"06"}
cardMonth={"Nov"}
cardTitle={"Arco-Íris da Esperança"}
cardLoc={"Centro"}
image={"https://i.ibb.co/ykBs25R/lovewins.jpg"}
/>
</a>
<a
onClick={() => {
setIsModalActionOpen(true);
setModalTitle("Projeto Rua Limpa");
setModalImg("https://i.ibb.co/mNMkrZ1/street.jpg");
setModalDate("11");
setModalLoc("Porto Dantas");
setModalMonth("Novembro");
setModalInst("Organização Missão Esperança");
setModalInstLogo(
"https://img.freepik.com/premium-vector/nature-tree-shoot-logo-vector-design-by-hand-tree-logo-vector-symbol-illustration-design_629573-229.jpg"
);
setModalDesc(
"O projeto social Rua Limpa é uma iniciativa com o propósito de promover a conscientização ambiental e melhorar a qualidade de vida em nossa comunidade, por meio da limpeza e preservação das ruas e espaços públicos. Nosso objetivo é mobilizar voluntários e residentes locais para assumir a responsabilidade de manter nossas ruas livres de lixo e resíduos, promovendo um ambiente mais limpo e saudável para todos."
);
}}
>
<Card
cardDate={"11"}
cardMonth={"Nov"}
cardTitle={"Projeto Rua Limpa"}
cardLoc={"Porto Dantas"}
image={"https://i.ibb.co/mNMkrZ1/street.jpg"}
/>
</a>
</div>
</div>
</main>
<section className="righton">
<h2>Ações em andamento</h2>
<div className="righton-box">
<a
onClick={() => {
setIsModalActionOpen(true);
setModalTitle("Guarda-Roupa Solidário");
setModalImg("https://i.ibb.co/6tK1NYC/donationclothes.jpg");
setModalDate("🟢");
setModalLoc("Japãozinho");
setModalMonth("Em Andamento");
setModalInst("Associação de Apoio à Vida");
setModalInstLogo(
"https://img.myloview.com/stickers/love-and-care-logo-icon-heart-with-hand-shape-logo-design-400-171363956.jpg"
);
setModalDesc(
"Guarda-Roupa Solidário é uma iniciativa calorosa e prática que tem como objetivo fornecer roupas e acessórios essenciais para pessoas em situação de vulnerabilidade social. Através da doação e redistribuição de roupas, estamos tornando a vida mais confortável e digna para indivíduos e famílias em necessidade. Com o apoio da comunidade, voluntários e parcerias locais, estamos aquecendo os corações e vestindo a esperança daqueles que precisam, construindo uma sociedade mais solidária e consciente."
);
}}
>
<CardOn
cardTitle={"Guarda-Roupa Solidário"}
cardLoc={"Japãozinho"}
image={"https://i.ibb.co/6tK1NYC/donationclothes.jpg"}
/>
</a>
<a
onClick={() => {
setIsModalActionOpen(true);
setModalTitle("Revitalização do Rio Poxim");
setModalImg("https://i.ibb.co/g39Fszx/cleaningriver.jpg");
setModalDate("🟢");
setModalLoc("Farolândia");
setModalMonth("Em Andamento");
setModalInst("Organização Missão Esperança");
setModalInstLogo(
"https://img.freepik.com/premium-vector/nature-tree-shoot-logo-vector-design-by-hand-tree-logo-vector-symbol-illustration-design_629573-229.jpg"
);
setModalDesc(
"O projeto de Revitalização do Rio Poxim é um esforço coletivo para recuperar e preservar um importante recurso natural em nossa região. Ao envolver a comunidade, promover a conscientização e implementar práticas sustentáveis, estamos trabalhando para restaurar a saúde do rio e criar um ambiente mais saudável e próspero para todos. Com o apoio de voluntários dedicados, especialistas em conservação ambiental e parcerias locais, estamos construindo um futuro mais sustentável e equilibrado para nossa comunidade e o meio ambiente."
);
}}
>
<CardOn
cardTitle={"Revitalização do Rio Poxim"}
cardLoc={"Farolândia"}
image={"https://i.ibb.co/g39Fszx/cleaningriver.jpg"}
/>
</a>
<a
onClick={() => {
setIsModalActionOpen(true);
setModalTitle("Projeto Mãos Que Alimentam");
setModalImg("https://i.ibb.co/yNJ3t1S/fooding.jpg");
setModalDate("🟢");
setModalLoc("Centro");
setModalMonth("Em Andamento");
setModalInst("Associação de Apoio à Vida");
setModalInstLogo(
"https://img.myloview.com/stickers/love-and-care-logo-icon-heart-with-hand-shape-logo-design-400-171363956.jpg"
);
setModalDesc(
"O projeto Mãos que Alimentam é um gesto de compaixão que visa garantir que ninguém na comunidade passe fome. Ao fornecer refeições e cestas básicas, estamos não apenas satisfazendo necessidades imediatas, mas também promovendo um ambiente de apoio e solidariedade. Com a ajuda de voluntários dedicados, doadores e a participação ativa da comunidade, estamos trabalhando para fazer uma diferença significativa na vida daqueles que mais precisam, oferecendo uma refeição e uma mão estendida de esperança."
);
}}
>
<CardOn
cardTitle={"Projeto Mãos Que Alimentam"}
cardLoc={"Centro"}
image={"https://i.ibb.co/yNJ3t1S/fooding.jpg"}
/>
</a>
<a
onClick={() => {
setIsModalActionOpen(true);
setModalTitle("Cine Comunidade");
setModalImg("https://i.ibb.co/6WXD4QD/cinema.jpg");
setModalDate("🟢");
setModalLoc("Santos Dumont");
setModalMonth("Em Andamento");
setModalInst("Fundação Renovar");
setModalInstLogo(
"https://img.freepik.com/vetores-premium/logotipo-infantil-com-design-de-mao-de-pessoas_579179-2339.jpg"
);
setModalDesc(
"O Cine Comunidade é uma iniciativa que visa trazer cultura, entretenimento e conexão para nossa comunidade do cinema. Ao proporcionar acesso ao cinema e eventos relacionados, estamos enriquecendo as vidas dos moradores locais, oferecendo oportunidades para aprender, se divertir e apreciar a diversidade cultural por meio da tela grande. Com o apoio de toda população estaremos construindo uma comunidade mais unida, culta e conectada."
);
}}
>
<CardOn
cardTitle={"Cine Comunidade"}
cardLoc={"Santos Dumont"}
image={"https://i.ibb.co/6WXD4QD/cinema.jpg"}
/>
</a>
</div>
</section>
<section className="whotohelp">
<h2>Saiba Quem Ajudar</h2>
<p className="desc">
Reunimos uma lista de fundações incríveis que precisam da sua ajuda:
</p>
<div className="whotohelp-box">
<CardInst
image={"https://www.tamar.org.br/imagens/logo_tamar.jpg"}
cardInstTitle={"Projeto Tamar"}
cardInstDesc={
"A Fundação Projeto Tamar atua no litoral brasileiro desde a década de 80 com a missão de promover a recuperação das tartarugas marinhas, através de ações de pesquisa, conservação e inclusão social."
}
link={"https://www.tamar.org.br/noticia1.php?cod=1019"}
/>
<CardInst
image={
"https://site.hyb.com.br/dados/base/gacc/meu_site/gacc-noticia1.jpg"
}
cardInstTitle={"GACC"}
cardInstDesc={
"Humanizar o tratamento de crianças e adolescentes com câncer e doenças hematológicas, oferecendo assistência biopsicossocial e material, garantindo a eles o direito a saúde e a vida."
}
link={"https://www.gacc-se.org.br/"}
/>
<CardInst
image={
"https://avosos.org.br/wp-content/uploads/2018/04/marca-avosos-numeros.png"
}
cardInstTitle={"AVOSOS"}
cardInstDesc={
"Atuar na assistência às crianças e adolescentes com câncer e doenças hematológicas crônicas de Sergipe, criando e articulando soluções em uma rede de ações, visando contribuir de forma integral para a melhoria do tratamento e da qualidade de vida desses pacientes."
}
link={"https://avosos.org.br/"}
/>
<CardInst
image={
"https://static.wixstatic.com/media/3f1abc_26c9b5517e9f40c0b8332ee55368a182.jpg/v1/fill/w_237,h_235,al_c,q_80,usm_0.66_1.00_0.01,enc_auto/3f1abc_26c9b5517e9f40c0b8332ee55368a182.jpg"
}
cardInstTitle={"SAME"}
cardInstDesc={
"Promover a melhoria da qualidade de vida e presevar a dignidade da pessoa idosa."
}
link={"https://samelardeidosos.wixsite.com/same"}
/>
<CardInst
image={
"https://www.ciras.org.br/system/mlkWxJhNMRE9Rd8D0x7eQhkxsAuXFLFtUy04JRrEzBGD07N-Fa5uCfogPiuZ57I15nITzNWWnao2nEsCGRlKFQ/themes/base/config/files/202011191343_66_logo-ciras-site-png.png"
}
cardInstTitle={"CIRAS"}
cardInstDesc={
"Atender com excelência e de forma gratuita pessoas de baixa renda com deficiência física, mental ou motora, para que tenha uma vida digna e independente."
}
link={"https://www.ciras.org.br/"}
/>
</div>
</section>
<footer>
<div className="logo">
<img src="https://i.ibb.co/SKpGhQf/Vector.png" alt="" />
<h1>abrace</h1>
</div>
<p>© 2023</p>
</footer>
</>
);
} |
<!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>IDS 517 HW7</title>
<!-- Link To CSS -->
<link rel="stylesheet" href="style.css">
<!-- Box Icons -->
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css">
</head>
<body>
<!-- Navbar -->
<header>
<a href="#" class="logo">Shubham Dwivedi</a>
<div class="bx bx-menu" id="menu-icon"></div>
<ul class="navbar">
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#skills">Skills</a></li>
<li><a href="#services">Interests</a></li>
<li><a href="#multimedia">Multimedia</a></li>
<li><a href="#contact">Contact Me</a></li>
<div class="bx bx-moon" id="darkmode"></div>
</ul>
</header>
<!-- Home -->
<section class="home" id="home">
<div class="social">
<!-- Added link to the Github profile -->
<a href="https://github.com/sdwive4" target="_blank"><i class='bx bxl-github'></i></a>
<!-- Added link to the Linkdein profile -->
<a href="https://www.linkedin.com/in/shubham-dwivedi-48239670/" target="_blank"><i class="bx bxl-linkedin"></i></a>
</div>
<div class="home-img">
<img src="uiclogo.png" alt="">
</div>
<div class="home-text">
<span>Hello, I'm</span>
<h1>Shubham Dwivedi</h1>
<h2>MS-MIS Student, University of Illinois at Chicago</h2>
<a href="#contact" class="btn">Contact Me</a>
</div>
</section>
<!-- About -->
<section class="about" id="about">
<div class="heading">
<h2>About Me</h2>
<span>Introduction</span>
</div>
<!-- About Content -->
<div class="about-container">
<div class="about-img">
<img src="coder.gif" alt="">
</div>
<div class="about-text">
<p>As a graduate student for a Master's degree in Management Information Systems, I am passionate about utilizing my technical skills in programming languages such as Java, Python, C++, SQL, JavaScript, R, and Ruby, as well as tools such as Eclipse, IntelliJ, SOAP UI, and Tableau, to drive data-driven decisions and solve complex problems.</p>
<div class="information">
<!-- Box 1 -->
<div class="info-box">
<i class='bx bxs-user' ></i>
<span>Shubham Dwivedi</span>
</div>
<!-- Box 2 -->
<div class="info-box">
<i class='bx bxs-phone' ></i>
<span>+1 347 517 2808</span>
</div>
<!-- Box 3 -->
<div class="info-box">
<i class='bx bxs-envelope' ></i>
<span>[email protected]</span>
</div>
</div>
<a href="CV.pdf" class="btn" target="_blank">Open Cv in New Tab</a>
</div>
</div>
</section>
<!-- Skills -->
<section class="skills" id="skills">
<div class="heading">
<h2>Skills</h2>
<span>My Skills</span>
</div>
<!-- Skills Content -->
<div class="skills-container">
<div class="bars">
<!-- Box 1 -->
<div class="bars-box">
<h3>HTML</h3>
<span>82%</span>
<div class="light-bar"></div>
<div class="percent-bar html-bar"></div>
</div>
<!-- Box 2 -->
<div class="bars-box">
<h3>CSS</h3>
<span>71%</span>
<div class="light-bar"></div>
<div class="percent-bar css-bar"></div>
</div>
<!-- Box 3 -->
<div class="bars-box">
<h3>JavaScript</h3>
<span>66%</span>
<div class="light-bar"></div>
<div class="percent-bar js-bar"></div>
</div>
<!-- Box 4 -->
<div class="bars-box">
<h3>Java</h3>
<span>79%</span>
<div class="light-bar"></div>
<div class="percent-bar react-bar"></div>
</div>
</div>
<div class="skills-img">
<img src="skills.png" alt="">
</div>
</div>
</section>
<!-- Interests -->
<section class="services" id="services">
<div class="heading">
<h2>Interests</h2>
<span>Technical Interests</span>
</div>
<div class="services-content">
<!-- Box 1 -->
<div class="services-box">
<i class='bx bx-code-alt' ></i>
<h3>HTML</h3>
<a href="https://www.w3schools.com/html/" target="_blank">Learn More</a>
</div>
<!-- Box 2 -->
<div class="services-box">
<i class='bx bx-server' ></i>
<h3>Java</h3>
<a href="https://www.w3schools.com/java/" target="_blank">Learn More</a>
</div>
<!-- Box 3 -->
<div class="services-box">
<i class='bx bx-brush' ></i>
<h3>CSS</h3>
<a href="https://www.w3schools.com/css/" target="_blank">Learn More</a>
</div>
<div class="services-box">
<i class='bx bxl-wordpress' ></i>
<h3>wordpress</h3>
<a href="https://www.w3schools.com/aws/aws_guided_project_deploy_wordpress_site_using_ec2.php" target="_blank">Learn More</a>
</div>
</div>
</section>
<!-- multimedia -->
<!-- Adding youtube videos for multimedia section of the webpage. Done this by adding the embedded codes of the youtube videos -->
<section class="multimedia" id="multimedia">
<div class="heading">
<h2>Multimedia</h2>
<span>Section to showcase multimedia videos for Web Development and Things to do in Chicago</span>
</div>
<div class="multimedia-content">
<div class="multimedia-img">
<iframe width="560" height="315" src="https://www.youtube.com/embed/qz0aGYrrlhU" title="Web Development tutorial" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
<div class="multimedia-img">
<iframe width="560" height="315" src="https://www.youtube.com/embed/AE0mfx2sVjU" title="City of Chicago" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
</div>
</section>
<!-- Contact -->
<section class="contact" id="contact">
<div class="heading">
<h2>Contact Me</h2>
<span>Connect With Me</span>
</div>
<div class="contact-form">
<form action="">
<input type="text" placeholder="Your Name">
<input type="email" name="" id="" placeholder="Your Email">
<textarea name="" id="" cols="30" rows="10" placeholder="Write Message Here..."></textarea>
<input type="button" value="Send" class="contact-button">
</form>
</div>
</section>
<!-- Link To JS -->
<script src="script.js"></script>
</body>
</html> |
import { useDispatch, useSelector } from "react-redux"
import { decrement, increment, incrementByAmount,reset } from "./store/slices/contadorSlice";
export const CounterApp=()=> {
//"theCounter viene del store, se accede por medio del selector"
//=>state+objetoStore+objetoslice
const count=useSelector((state)=>state.theCounter.counter)
const dispatch=useDispatch();
return (
<>
<div className="container">
<h2>Counter Redux</h2>
<hr/>
<h3>Contador: {count}</h3>
<button
onClick={()=>dispatch(increment())}
className="btn btn-success mx-1">Incrementar
</button>
<button
onClick={()=>dispatch(decrement())}
className="btn btn-primary mx-1">Decrementar</button>
<button
onClick={()=>dispatch(incrementByAmount(2))}
className="btn btn-success mx-1">Sumar + 2</button>
<button
onClick={()=>dispatch(reset())}
className="btn btn-success mx-1">Reset</button>
</div>
</>
)
}
export default CounterApp |
#' Calculates the relative (%) increase in precision between two methods
#'
#' Calculates the relative (%) increase in precision between two competing methods (B vs A). As this metric compares two methods directly, it cannot be used in `join_metrics()`.
#'
#' @param estimates_A A numeric vector containing the estimates from model A.
#' @param estimates_B A numeric vector containing the estimates from model B.
#' @param get A character vector containing the values returned by the function.
#' @param na.rm A logical value indicating whether NA values for `estimates` should be removed before empSE calculation.
#'
#' @return A named vector containing the estimate and the Monte Carlo standard error for the relative (%) increase in precision of method B versus method A.
#' @export
#'
#' @examples relativePrecision(estimates_A = rnorm(n = 1000), estimates_B = rnorm(n = 1000))
relativePrecision <- function(estimates_A, estimates_B, get = c("relativePrecision", "relativePrecision_mcse"), na.rm = FALSE) {
assertthat::assert_that(length(!is.na(estimates_A)) == length(!is.na(estimates_B)))
n <- length(!is.na(estimates_A))
x <- c()
if (any(is.na(c(estimates_A, estimates_B))) & na.rm == FALSE) {
x["relativePrecision"] <- NA
x["relativePrecision_mcse"] <- NA
return(x[get])
}
if (na.rm) {
estimates_A <- estimates_A[!is.na(estimates_A)]
estimates_B <- estimates_B[!is.na(estimates_B)]
}
empSE_A <- empSE(estimates = estimates_A, get = "empSE")
empSE_B <- empSE(estimates = estimates_B, get = "empSE")
x["relativePrecision"] <- 100 * ((empSE_A / empSE_B)^2 - 1)
x["relativePrecision_mcse"] <- 200 * ((empSE_A / empSE_B)^2) * sqrt((1 - stats::cor(x = estimates_A, y = estimates_B)^2) / (n - 1))
return(x[get])
} |
package org.example.entity;
import org.example.validation.ValidEmail;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Date;
@Entity
@Table(name = "User", schema = "dop")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
@Column(name = "firstName")
private String firstName;
@Column(name = "lastName")
private String lastName;
@Column(name = "dateOfBirth")
private Date dateOfBirth;
@Column(name = "password")
private String password;
@Column(name = "email")
@ValidEmail
private String email;
@Column(name = "contactNo")
private Long contactNo;
@Column(name = "securityQuestion")
private String securityQuestion;
@Column(name = "securityAnswer")
private String securityAnswer;
@Column(name = "emailEnabled")
private boolean emailEnabled;
@Column(name = "phoneEnabled")
private boolean phoneEnabled;
@Column(name = "userName")
private String userName;
@Enumerated(EnumType.STRING)
@Column(name = "authProvider")
private AuthenticationProvider authProvider;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public AuthenticationProvider getAuthProvider() {
return authProvider;
}
public void setAuthProvider(AuthenticationProvider authProvider) {
this.authProvider = authProvider;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getContactNo() {
return contactNo;
}
public void setContactNo(Long contactNo) {
this.contactNo = contactNo;
}
public String getSecurityQuestion() {
return securityQuestion;
}
public void setSecurityQuestion(String securityQuestion) {
this.securityQuestion = securityQuestion;
}
public String getSecurityAnswer() {
return securityAnswer;
}
public void setSecurityAnswer(String securityAnswer) {
this.securityAnswer = securityAnswer;
}
public boolean getEmailEnabled() {
return emailEnabled;
}
public void setEmailEnabled(boolean emailEnabled) {
this.emailEnabled = emailEnabled;
}
public boolean isEmailEnabled() {
return emailEnabled;
}
public boolean isPhoneEnabled() {
return phoneEnabled;
}
public void setPhoneEnabled(boolean phoneEnabled) {
this.phoneEnabled = phoneEnabled;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", dateOfBirth=" + dateOfBirth +
", password='" + password + '\'' +
", email='" + email + '\'' +
", contactNo=" + contactNo +
", securityQuestion='" + securityQuestion + '\'' +
", securityAnswer='" + securityAnswer + '\'' +
", emailEnabled=" + emailEnabled +
", phoneEnabled=" + phoneEnabled +
", userName='" + userName + '\'' +
", authProvider=" + authProvider +
'}';
}
} |
<?php
session_start();
require_once 'config/connection.php';
// uses previous user's session
if (isset($_SESSION['user'])) {
if ($_SESSION['type'] == "Admin") {
header("Location: dashboard_admin.php");
} elseif ($_SESSION['type'] == "Supplier") {
header("Location: dashboard_supplier.php");
} elseif ($_SESSION["type"] == "Customer") {
header("homepage.php");
}
exit;
}
// Removes unneccessary characters in data input
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// Initialize error variables
$error = false;
if (isset($_POST['login'])) {
$email = test_input($_POST['email']);
$pass = test_input($_POST['pass']);
// Prevent SQL injection
if (empty($email)) {
$error = true;
$emailError = "Please enter your email address.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = true;
$emailError = "Please enter a valid email address.";
}
if (empty($pass)) {
$error = true;
$passwordError = "Please enter your password.";
}
// If there's no error, continue to login
if (!$error) {
$password = $pass;
$res = mysqli_query($connection, "SELECT user_id, user_email, user_password, user_type FROM users WHERE user_email='$email' AND user_password = '$pass'");
$row = mysqli_fetch_array($res, MYSQLI_ASSOC);
$count = mysqli_num_rows($res);
// Password hashing verify
// if ($count == 1 && password_verify($password, $row['user_password'])) {
// $_SESSION['user'] = $row['user_id'];
// $_SESSION['type'] = $row['user_type'];
// if ($row['user_type'] == 'Admin') {
// header("Location: dashboard_admin.php");
// } elseif ($row['user_type'] == 'Supplier') {
// header("Location: dashboard_supplier.php");
// } elseif ($row["user_type"] == 'Customer') {
// header('Location: homepage.php');
// }
// exit;
// } else {
// $errorMSG = "Incorrect Credentials, Try again...";
// }
// Logs in to the corresponding user_type
if ($count == 1 && $row['user_password'] == $password) {
$_SESSION['user'] = $row['user_id'];
$_SESSION['type'] = $row['user_type'];
if ($row['user_type'] == 'Admin') {
header("Location: dashboard_admin.php");
} elseif ($row['user_type'] == 'Supplier') {
header("Location: dashboard_supplier.php");
} elseif ($row["user_type"] == 'Customer') {
header('Location: homepage.php');
}
exit;
} else {
$errorMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vendo Central ng Pilipinas</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<?php include('includes/header2.html'); ?>
</head>
<body>
<!-- Log in form -->
<div id="login-form" class="container">
<div class="d-flex justify-content-center align-items-center">
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off" method="POST"
class="w-25">
<?php
if (isset($errorMSG)) {
?>
<div class="alert alert-danger d-flex align-items-center mt-3" role="alert">
<i class="bi flex-shrink-0 me-2 bi-exclamation-triangle" role="img" aria-label="Warning:"></i>
<div>
<?php echo isset($errorMSG) ? $errorMSG : ''; ?>
</div>
</div>
<?php
} ?>
<div class="mt-3">
<h3>Sign in.</h3>
</div>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label"> Email </label>
<input type="email" name="email" class="form-control" id="exampleFormControlInput1"
value="<?php echo isset($email) ? $email : ''; ?>">
</div>
<span class="text-danger">
<?php echo isset($emailError) ? $emailError : ''; ?>
</span>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label">Password</label>
<input type="password" name="pass" class="form-control">
</div>
<span class="text-danger">
<?php echo isset($passwordError) ? $passwordError : ''; ?>
</span>
<div class="d-flex mt-3">
<button type="submit" class="btn btn-primary" name="login">Submit</button>
</div>
</form>
</div>
<div class="text-center mt-3">
<p>Do not have an account yet? <a href="registration.php">Register here</a>.</p>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js">
</script>
<script src="https://unpkg.com/@popperjs/core@2"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
<?php include('includes/footer.html'); ?>
</body>
</html>
<?php mysqli_close($connection); ?> |
# Required Libraries
from collections import Counter
import matplotlib.pyplot as plt
import nltk
import numpy as np
import seaborn as sns
import spacy
from gensim.models import Word2Vec
from nltk.corpus import stopwords
from nltk.probability import FreqDist
from nltk.tokenize import RegexpTokenizer
from nltk.tokenize import word_tokenize
from sklearn.decomposition import PCA
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
#TODO: Library requires work!
# Document Statistics
def document_statistics(documents):
num_documents = len(documents)
avg_doc_length = np.mean([len(doc.split()) for doc in documents])
max_doc_length = np.max([len(doc.split()) for doc in documents])
min_doc_length = np.min([len(doc.split()) for doc in documents])
print("Number of documents:", num_documents)
print("Average document length:", avg_doc_length)
print("Maximum document length:", max_doc_length)
print("Minimum document length:", min_doc_length)
return max_doc_length
# Class Distribution
def class_distribution(labels):
label_counts = Counter(labels)
plt.bar(label_counts.keys(), label_counts.values())
plt.xlabel('Class')
plt.ylabel('Frequency')
plt.title('Class Distribution')
plt.show()
# Word Frequency Analysis
def word_frequency_analysis(documents):
tokenizer = RegexpTokenizer(r'\w+')
all_words = [word.lower() for doc in documents for word in tokenizer.tokenize(doc)]
fdist = FreqDist(all_words)
plt.figure(figsize=(10, 5))
fdist.plot(30, cumulative=False)
plt.show()
# Stopwords and Punctuation
def remove_stopwords_and_punctuation(documents):
stop_words = set(stopwords.words('english'))
tokenizer = RegexpTokenizer(r'\w+')
clean_documents = []
for doc in documents:
words = tokenizer.tokenize(doc)
clean_words = [word for word in words if word.lower() not in stop_words]
clean_doc = ' '.join(clean_words)
clean_documents.append(clean_doc)
return clean_documents
# TFIDF
def tfidf_representation(documents):
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(documents)
return tfidf_matrix, vectorizer.get_feature_names_out()
# Word Embedding Visualization (using PCA)
def word_embedding_visualization(documents):
word_list = [word_tokenize(doc.lower()) for doc in documents]
model = Word2Vec(word_list, min_count=1)
X = model[model.wv.vocab]
pca = PCA(n_components=2)
result = pca.fit_transform(X)
plt.scatter(result[:, 0], result[:, 1])
words = list(model.wv.vocab)
for i, word in enumerate(words):
plt.annotate(word, xy=(result[i, 0], result[i, 1]))
plt.show()
# Document Similarity
def document_similarity(documents):
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(documents)
cosine_sim = cosine_similarity(tfidf_matrix, tfidf_matrix)
sns.heatmap(cosine_sim, annot=True, fmt=".2f", cmap='coolwarm')
plt.show()
# Named Entity Recognition
def named_entity_recognition(documents):
nlp = spacy.load("en_core_web_sm")
for doc in documents:
doc_entities = nlp(doc)
for entity in doc_entities.ents:
print(entity.text, entity.label_)
# Topic Modeling
def topic_modeling(documents):
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(documents)
svd = TruncatedSVD(n_components=2)
svd_matrix = svd.fit_transform(tfidf_matrix)
print(svd_matrix)
if __name__ == '__main__':
# Download NLTK resources
nltk.download('punkt')
nltk.download('stopwords')
# Sample text data
documents = ["This is the first document.",
"This document is the second document.",
"And this is the third one.",
"Is this the first document?"]
# document_statistics(documents)
# labels = ['n', 'y', 'n', 'y'] # Sample labels for two classes
# class_distribution(labels)
#
# word_frequency_analysis(documents)
#
# clean_documents = remove_stopwords_and_punctuation(documents)
# print("Documents after removing stopwords and punctuation:", clean_documents)
#
# tfidf_matrix, feature_names = tfidf_representation(clean_documents)
# print("TFIDF Matrix:")
# print(tfidf_matrix.toarray())
# print("Feature Names:", feature_names)
#
# word_embedding_visualization(documents)
#
# document_similarity(documents)
#
# named_entity_recognition(documents)
#
# topic_modeling(documents) |
<?
require_once $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/include/prolog_admin_before.php';
// получим права доступа текущего пользователя на модуль
$POST_RIGHT = $APPLICATION->GetGroupRight("chieff.books");
// если нет прав - отправим к форме авторизации с сообщением об ошибке
if ($POST_RIGHT == "D")
$APPLICATION->AuthForm(GetMessage("ACCESS_DENIED"));
// Подключаем языковой файл для примера
IncludeModuleLangFile(__FILE__);
$aTabs = array(
array("DIV" => "edit1", "TAB" => GetMessage("TAB1"), "ICON" => "main_user_edit", "TITLE" => GetMessage("TAB1")),
array("DIV" => "edit2", "TAB" => GetMessage("TAB2"), "ICON" => "main_user_edit", "TITLE" => GetMessage("TAB2")),
);
$tabControl = new CAdminTabControl("tabControl", $aTabs);
// Подключим свой ORM-класс
\Bitrix\Main\Loader::includeModule("chieff.books");
// Сначала, определим несколько переменных, которые нам понадобятся впоследствии:
$ID = intval($ID); // идентификатор редактируемой записи
$message = null; // сообщение об ошибке
$bVarsFromForm = false; // флаг "Данные получены с формы", обозначающий, что выводимые данные получены с формы, а не из БД.
use Bitrix\Main\Type;
// Необходимость сохранения изменений мы определим по следующим параметрам:
// Страница вызвана методом POST
// Среди входных данных есть идентификаторы кнопок "Сохранить" и "Применить"
// Если эти условия сооблюдены и пройдены проверки безопасности, можно сохранять переданные скрипту данные:
if (
$REQUEST_METHOD == "POST" // проверка метода вызова страницы
&&
($save != "" || $apply != "") // проверка нажатия кнопок "Сохранить" и "Применить"
&&
$POST_RIGHT == "W" // проверка наличия прав на запись для модуля
&&
check_bitrix_sessid() // проверка идентификатора сессии
) {
$bookTable = new \chieff\books\BookTable;
// обработка данных формы
$arFields = Array(
"ACTIVE" => ($ACTIVE <> "Y" ? "N" : "Y"),
"TYPE" => $TYPE,
"NAME" => $NAME,
"RELEASED" => $RELEASED,
"ISBN" => intval($ISBN),
"AUTHOR_ID" => $AUTHOR_ID,
"DESCRIPTION" => $DESCRIPTION,
"TIME_ARRIVAL" => new Type\DateTime($TIME_ARRIVAL),
);
// сохранение данных
if ($ID > 0) {
$res = $bookTable->Update($ID, $arFields);
} else {
$res = $bookTable->Add($arFields);
if ($res->isSuccess())
$ID = $res->getId();
}
if ($res->isSuccess()) {
// если сохранение прошло удачно - перенаправим на новую страницу
// (в целях защиты от повторной отправки формы нажатием кнопки "Обновить" в браузере)
if ($apply != "")
// если была нажата кнопка "Применить" - отправляем обратно на форму.
LocalRedirect(
"/bitrix/admin/chieff_books_edit.php?ID=" .
$ID .
"&mess=ok" .
"&lang=" . LANG .
"&" . $tabControl->ActiveTabParam()
);
else
// если была нажата кнопка "Сохранить" - отправляем к списку элементов.
LocalRedirect("/bitrix/admin/chieff_books_list.php?lang=" . LANG);
} else {
// если в процессе сохранения возникли ошибки - получаем текст ошибки и меняем вышеопределённые переменные
if ($e = $APPLICATION->GetException())
$message = new CAdminMessage("Ошибка сохранения", $e);
else {
$mess = print_r($res->getErrorMessages(), true);
$message = new CAdminMessage("Ошибка сохранения: " . $mess);
}
$bVarsFromForm = true;
}
}
// Выборка и подготовка данных для формы
// Для начала, определим значения по умолчанию. Все данные, полученные из БД будем сохранять в переменные с префиксом str_
$str_ACTIVE = "Y";
$str_TYPE = "";
$str_NAME = "";
$str_RELEASED = "";
$str_ISBN = "";
$str_AUTHOR_ID = "";
$str_DESCRIPTION = "";
$str_TIME_ARRIVAL = ConvertTimeStamp(false, "FULL");
// Выберем данные:
if ($ID > 0) {
$result = \chieff\books\BookTable::GetByID($ID);
if ($result->getSelectedRowsCount()) {
$bookTable = $result->fetch();
$str_ACTIVE = $bookTable["ACTIVE"];
$str_TYPE = $bookTable["TYPE"];
$str_NAME = $bookTable["NAME"];
$str_RELEASED = $bookTable["RELEASED"];
$str_ISBN = $bookTable["ISBN"];
$str_AUTHOR_ID = $bookTable["AUTHOR_ID"];
$str_DESCRIPTION = $bookTable["DESCRIPTION"];
$str_TIME_ARRIVAL = $bookTable["TIME_ARRIVAL"];
} else
$ID = 0;
}
// Подготовим полученные данные и установим заголовок страницы:
// если данные переданы из формы, инициализируем их
if ($bVarsFromForm) {
$DB->InitTableVarsForEdit("chieff_books_books_table", "", "str_");
}
// Если редактируем, то выведем один заголовок, если нет, другой
$APPLICATION->SetTitle(($ID > 0 ? "Редактирование " . $ID : "Добавление"));
// Задание параметров административного меню
// Также можно задать административное меню, которое будет отображаться над таблицей со списком (только если у текущего пользователя есть права на редактирование). Административное формируется в виде массива, элементами которого являются ассоциативные массивы с ключами:
// TEXT - Текст пункта меню.
// TITLE - Текст всплывающей подсказки пункта меню.
// LINK - Ссылка на кнопке.
// LINK_PARAM - Дополнительные параметры ссылки (напрямую подставляются в тэг <A>).
// ICON - CSS-класс иконки действия.
// HTML - Задание пункта меню напрямую HTML-кодом.
// SEPARATOR - Разделитель между пунктами меню (true|false).
// NEWBAR - Новый блок элементов меню (true|false).
// MENU - Создание выпадающего подменю. Значение задается аналогично контекстному меню строки таблицы.
$aMenu = array(
array(
"TEXT" => "К списку",
"TITLE" => "К списку",
"LINK" => "chieff_books_list.php?lang=" . LANG,
"ICON" => "btn_list",
)
);
if ($ID > 0) {
$aMenu[] = array("SEPARATOR"=>"Y");
$aMenu[] = array(
"TEXT" => "Добавить",
"TITLE" => "Добавить",
"LINK" => "chieff_books_edit.php?lang=" . LANG,
"ICON" => "btn_new",
);
$aMenu[] = array(
"TEXT" => "Удалить",
"TITLE" => "Удалить",
"LINK" => "javascript:if(confirm('" . "Подтвердить удаление?" . "')) " . "window.location='chieff_books_list.php?ID=" . $ID . "&action=delete&lang=" . LANG . "&" . bitrix_sessid_get() . "';",
"ICON" => "btn_delete",
);
$aMenu[] = array("SEPARATOR"=>"Y");
}
require_once $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/include/prolog_admin_after.php';
// Прежде всего, выведем подготовленное административное меню.
// Создадим экземпляр класса административного меню
$context = new CAdminContextMenu($aMenu);
// Выведем меню
$context->Show();
// Если есть сообщения об ошибках или об успешном сохранении - выведем их.
if ($_REQUEST["mess"] == "ok" && $ID > 0)
CAdminMessage::ShowMessage(array("MESSAGE" => "Сохранено успешно", "TYPE" => "OK"));
if ($message)
echo $message->Show();
elseif ($bookTable->LAST_ERROR != "")
CAdminMessage::ShowMessage($bookTable->LAST_ERROR);
?>
<form method="POST" Action="<?=$APPLICATION->GetCurPage()?>" ENCTYPE="multipart/form-data" name="post_form">
<?// проверка идентификатора сессии ?>
<?echo bitrix_sessid_post();?>
<input type="hidden" name="lang" value="<?=LANG?>">
<?if ($ID > 0 && !$bCopy):?>
<input type="hidden" name="ID" value="<?=$ID?>">
<?
endif;
// отобразим заголовки закладок
$tabControl->Begin();
$tabControl->BeginNextTab();
?>
<tr>
<td width="40%"><?="Активность"?></td>
<td width="60%"><input type="checkbox" name="ACTIVE" value="Y"<?if($str_ACTIVE == "Y") echo " checked"?>></td>
</tr>
<tr>
<td align="right" style="font-weight: bold;"><?="Тип"?></td>
</tr>
<?
$i=0;
$arTypes = Array(
'Техническая литература',
'Художественная литература',
'Научная литература'
);
foreach($arTypes as $type):
?>
<tr>
<td>
<input type="radio" id="type<?=$i?>" name="TYPE" value="<?=$type?>" <?if($str_TYPE == $type) echo "checked"?>>
</td>
<td>
<label for="type<?=$i?>" title="<?=$type?>"><?=$type?></label><br>
</td>
<?$i++?>
</tr>
<?endforeach;?>
<tr>
<td width="40%"><?="Название"?></td>
<td width="60%"><input type="text" name="NAME" value="<?=$str_NAME?>" /></td>
</tr>
<tr>
<td width="40%"><?="Выпущено"?></td>
<td width="60%"><input type="text" name="RELEASED" value="<?=$str_RELEASED?>" /></td>
</tr>
<tr>
<td width="40%"><?="ISBN"?></td>
<td width="60%"><input type="text" name="ISBN" value="<?=$str_ISBN?>" /></td>
</tr>
<tr>
<td width="40%"><?="Айди автора"?></td>
<td width="60%"><input type="text" name="AUTHOR_ID" value="<?=$str_AUTHOR_ID?>" /></td>
</tr>
<tr>
<td width="40%"><?="Описание"?></td>
<td width="60%"><textarea class="typearea" cols="45" rows="5" wrap="VIRTUAL" name="DESCRIPTION"><?=$str_DESCRIPTION?></textarea></td>
</tr>
<?
$tabControl->BeginNextTab();
?>
<tr class="heading">
<td colspan="2"><?="Время прибытия"?></td>
</tr>
<tr>
<td width="40%"><span class="required">*</span>Время прибытия<?=" (".FORMAT_DATETIME."):"?></td>
<td width="60%"><?=CalendarDate("TIME_ARRIVAL", $str_TIME_ARRIVAL, "post_form", "20")?></td>
</tr>
<?
// завершение формы - вывод кнопок сохранения изменений
$tabControl->Buttons(
array(
"disabled" => ($POST_RIGHT < "W"),
"back_url" => "chieff_books_list.php?lang=".LANG,
)
);
// завершаем интерфейс закладки
$tabControl->End();
// дополнительное уведомление об ошибках - вывод иконки около поля, в котором возникла ошибка
$tabControl->ShowWarnings("post_form", $message);
// Завершим нашу страницу информационным сообщением:
echo BeginNote();
?>
<span class="required">*</span>Какое-то важное сообщение
<?
EndNote();
require_once $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/include/epilog_admin.php';
?> |
package com.example.gaminglog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.Switch;
public class SettingsActivity extends AppCompatActivity {
private Switch switchDarkMode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
switchDarkMode = findViewById(R.id.switch_dark_mode);
switchDarkMode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// Enable dark mode
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
// Disable dark mode
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
SharedPreferences preferences = getSharedPreferences("settings", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("dark_mode_enabled", isChecked);
editor.apply();
}
});
SharedPreferences preferences = getSharedPreferences("settings", MODE_PRIVATE);
boolean isDarkModeEnabled = preferences.getBoolean("dark_mode_enabled", false);
switchDarkMode.setChecked(isDarkModeEnabled);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
} |
export const useBooks = () => {
const client = useSupabaseClient();
const user = useSupabaseUser();
const userISBNs = ref<UserBook[]>([]);
// userISBNsテーブルのデータを取得する
const getUserISBNsData = async (): Promise<UserBook[]> => {
const { data, error } = await client.from("user_isbn").select("*");
if (error) throw error;
return data as UserBook[];
};
// openDBにfetchしてbooksに追加する
const getBooksData = async (ISBNs: string): Promise<BookData[]> => {
// 1000件以上登録されている場合は1000件までに制限する (openDBのAPI制限)
if (ISBNs.split(",").length > 1000)
ISBNs = ISBNs.split(",").slice(0, 1000).join(",");
const { data, error } = await useFetch("/api/openDB", {
method: "GET",
params: {
isbn: ISBNs,
},
});
if (error.value) throw new Error(error.value.message);
if (data.value === null) throw new Error("No data");
// 本のデータをBookData型に変換する
const booksData = data.value.map((book: BookResponse): BookData => {
console.log(book);
// 著者名の整形
let author: string =
book.onix.DescriptiveDetail.Contributor[0].PersonName.content;
const authorArray = author.split(",");
if (authorArray.length > 1)
author = authorArray[0] + " " + authorArray[1];
// 日付の整形
let date: string =
book.onix?.PublishingDetail?.PublishingDate[0]?.Date ?? "";
date = date.slice(0, 4) + "/" + date.slice(4, 6) + "/" + date.slice(6, 8);
if (date === "//") date = "";
return {
isbn: book.onix.RecordReference,
title:
book.onix.DescriptiveDetail.TitleDetail.TitleElement.TitleText
.content,
author,
publisher: book.onix.PublishingDetail.Imprint.ImprintName,
label: book.summary.series ?? "",
date,
price:
book.onix?.ProductSupply?.SupplyDetail?.Price[0]?.PriceAmount ?? 0,
page: book.onix.DescriptiveDetail?.extent?.[0]?.extentValue ?? 0,
cover: "https://placehold.jp/105x148.png",
};
});
return booksData;
};
// subscribeしている情報が変更された時、openDBにfetchしてbooksに追加する
const handleInserts = (payload: Payload): void => {
if (payload.eventType === "DELETE") {
userISBNs.value = userISBNs.value.filter((book) => {
return book.id !== payload.old.id;
});
}
if (payload.eventType === "INSERT") {
userISBNs.value.push(payload.new);
}
if (payload.eventType === "UPDATE") {
userISBNs.value = userISBNs.value.map((book) => {
if (book.id === payload.old.id) return payload.new;
return book;
});
}
};
// supabaseのusers_isbnテーブルの変更をsubscribeする
const startSubscribe = (): void => {
client
.channel("user_isbn")
.on(
"postgres_changes",
{
event: "*",
schema: "public",
table: "user_isbn",
},
handleInserts,
)
.subscribe((status) => {
if (status === "SUBSCRIBED") console.log("started subscribe!!!");
});
};
// user.value?.idをキーにしてデータを登録する
const addBook = async (newUserBook: UserBook): Promise<void> => {
const { error } = await client
.from("user_isbn")
.insert({
user_id: user.value?.id,
isbn: newUserBook.isbn,
book_data: newUserBook.book_data,
state: newUserBook.state,
})
.select("*")
.single();
if (error) throw error;
};
// データの削除
const deleteBook = async (id: string) => {
const { error } = await client.from("user_isbn").delete().eq("id", id);
if (error) throw error;
};
// データの再取得
const reloadBook = async (userBooks: UserBook) => {
const bookData = await getBooksData(userBooks.isbn);
const { error } = await client
.from("user_isbn")
.update({ book_data: bookData[0] })
.eq("id", userBooks.id);
if (error) throw error;
};
// データの更新
const updateBook = async (userBooks: UserBook) => {
if (userBooks.id === "") return;
const { error } = await client
.from("user_isbn")
.update({
book_data: userBooks.book_data,
state: userBooks.state,
})
.eq("id", userBooks.id);
if (error) throw error;
};
return {
userISBNs,
getUserISBNsData,
getBooksData,
startSubscribe,
addBook,
deleteBook,
reloadBook,
updateBook,
};
}; |
//
// SettingList.swift
// RemoteWellnessSupportApp
//
// Created by 岩本雄貴 on 2024/04/29.
//
import SwiftUI
struct SettingList: View {
@StateObject var viewModel = SettingListViewModel()
@EnvironmentObject var router: SettingScreenNavigationRouter
@AppStorage(Const.AppStatus.hasCompletedOnboarding) var hasCompletedOnboarding: Bool
= Const.AppDefaults.hasCompletedOnboarding
@AppStorage(Const.AppStatus.hasCompletedNotificationSetting) var hasCompletedNotificationSetting
= Const.AppDefaults.hasCompletedNotificationSetting
@AppStorage(Const.AppStatus.hasCompletedProfileRegister) var hasCompletedProfileRegister
= Const.AppDefaults.hasCompletedProfileRegister
var body: some View {
GeometryReader { geometry in
ScrollView {
VStack(alignment: .leading, spacing: 0) {
SettingItemView(imageName: SettingsItem.ImageName.profileEditList.rawValue,
title: SettingsItem.Label.profileEditList.rawValue,
geometry: geometry) {
router.items.append(SettingScreenNavigationItem.profileSetting)
}
SettingItemView(imageName: SettingsItem.ImageName.reminderEditList.rawValue,
title: SettingsItem.Label.reminderEditList.rawValue,
geometry: geometry) {
router.items.append(SettingScreenNavigationItem.reminderEditList)
}
SettingItemView(imageName: SettingsItem.ImageName.accountDeletion.rawValue,
title: SettingsItem.Label.accountDeletion.rawValue,
geometry: geometry) {
viewModel.showModal = true
}
.alert("退会しますか?", isPresented: $viewModel.showModal) {
Button("キャンセル", role: .cancel) {}
Button("退会する", role: .destructive) {
viewModel.unsubscribe()
hasCompletedNotificationSetting = false
hasCompletedProfileRegister = false
hasCompletedOnboarding = false
}
} message: {
Text("退会すると今までのデータは削除されます")
}
}
}
}
}
} |
% F-16's Trim Values Function.
% -------------------------------------------------------------------------
% Cagatay SAHIN
% 21.04.2021
% [email protected]
% -------------------------------------------------------------------------
% Trim values function to calculate equlibrium point of F-16 with respect
% to specific flight envolope which is altitude and speed.
% The trim function equation and conditions can be found in Steven's
% "Aircraft Control and Simulation" textbook. The textbook also, be found
% in "references" folder.
% -------------------------------------------------------------------------
% Parameters:
% Inputs:
% inputs => Initial condition of A/C's trim function.
% tas => True airspeed (ft/s)
% alpha => Angle of attack (deg)
% beta => Angle of sideslip (deg)
% z_e => Altitude (ft)
% ele => Elevator deflection (deg)
% ail => Aileron deflection (deg)
% rud => Rudder deflection (deg)
% thrtl => Throttle position ()
% Outputs:
% outputs => Output of A/C's trim function.
% trim => Trim information of F-16 such as states and controls
% cost => Final cost value of trim optimization.
% -------------------------------------------------------------------------
% Notes:
% For this version of trim condition just steady level wing flight
% is investigated.
function outputs = getTrimValues_Euler(inputs)
%% -------------------------|Global Variables|-------------------------
global initials
% ---------------------------------------------------------------------
%% ------------------------|Initial Conditions|------------------------
% State Variable Information
initials.tas = inputs.tas;
initials.alpha = inputs.alpha;
initials.beta = inputs.beta;
initials.phi = inputs.phi;
initials.theta = inputs.theta;
initials.psi = inputs.psi;
initials.p = inputs.p;
initials.q = inputs.q;
initials.r = inputs.r;
initials.x_e = inputs.x_e;
initials.y_e = inputs.y_e;
initials.z_e = inputs.z_e;
% Control Input Information
initials.thrtl = inputs.thrtl;
initials.ele = inputs.ele;
initials.ail = inputs.ail;
initials.rud = inputs.rud;
initials.sb = inputs.sb;
initials.lef = inputs.lef;
% Other Variables Information
initials.theta_dot = inputs.phi_dot;
initials.phi_dot = inputs.theta_dot;
initials.psi_dot = inputs.psi_dot;
% Latitude and Longitude Calculation
lla = ned2lla([initials.x_e, initials.y_e, initials.z_e], ...
[inputs.lat, inputs.long, 0], 'flat');
initials.lat = lla(1);
initials.long = lla(2);
% Rate of Climb
initials.rateOfClimb = inputs.rateOfClimb;
% Flight Path Angle
initials.gamma = inputs.gamma;
% ---------------------------------------------------------------------
%% ------------------------|Optimization Part|-------------------------
iter = 1;
cost = 1;
counter = 0;
prevCost = 0;
initialsVar = [inputs.thrtl; inputs.ele; inputs.alpha; ...
inputs.ail; inputs.rud; inputs.beta];
while iter == 1 && counter <= 5
OPTIONS = optimset('TolFun', 1e-10, 'TolX', 1e-10, ...
'MaxFunEvals', 5e+04, 'MaxIter', 1e+04);
[inputs, ~, ~, ~] = fminsearch('getCostValues_Euler', ...
initialsVar, OPTIONS);
[cost, states, controls] = getCostValues_Euler(inputs);
counter = counter+1;
if counter == 5 || prevCost == cost
iter = 0;
end % End of "Trim Iteration" If Condition.
prevCost = cost;
initialsVar = inputs;
end % End of "Trim While Loop" While Condition.
% ---------------------------------------------------------------------
%% -------------------|Final (Optimized) Parameters|-------------------
outputs.trim.states = states;
outputs.trim.controls = controls;
outputs.cost = cost;
% ---------------------------------------------------------------------
%% -----------------------|Final Representation|-----------------------
disp(['<strong>Cost = </strong>' ...
num2str(outputs.cost)])
disp(['<strong>Iteration Number = </strong>' ...
num2str(counter)])
disp(['<strong>Throttle = </strong>' ...
num2str(outputs.trim.controls.throttle) ' '])
disp(['<strong>Elevator Deflection = </strong>' ...
num2str(outputs.trim.controls.elevator) ' deg'])
disp(['<strong>Aileron Deflection = </strong>' ...
num2str(outputs.trim.controls.aileron) ' deg'])
disp(['<strong>Rudder Deflection = </strong>' ...
num2str(outputs.trim.controls.rudder) ' deg'])
disp(['<strong>Leadig Edge Flap Deflection = </strong>' ...
num2str(outputs.trim.controls.lef) ' deg'])
disp(['<strong>Speed Breaker Deflection = </strong>' ...
num2str(outputs.trim.controls.sb) ' deg']);
disp(['<strong>Angle of Attack = </strong>' ...
num2str(rad2deg(outputs.trim.states.alpha)) ' deg'])
disp(['<strong>Angle of Sideslip = </strong>' ...
num2str(rad2deg(outputs.trim.states.beta)) ' deg'])
disp(['<strong>True Airspeed = </strong>' ...
num2str(outputs.trim.states.tas) 'ft/s'])
end % End of "F-16's Trim Values" Function. |
import 'package:animated_snack_bar/animated_snack_bar.dart';
import 'package:chat4u/helpers/api.dart';
import 'package:chat4u/main.dart';
import 'package:chat4u/models/user.dart';
import 'package:chat4u/widgets/ui_design.dart';
import 'package:flutter/material.dart';
import 'package:timer_snackbar/timer_snackbar.dart';
class ShowDialog {
static snakbar(context, {required String message}) {
return ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message, textAlign: TextAlign.center),
backgroundColor: Colors.red.withOpacity(.8),
behavior: SnackBarBehavior.floating),
);
}
static animatedSnakbar(context,
{required String message, required AnimatedSnackBarType snackbarType}) {
return AnimatedSnackBar.material(
message,
borderRadius: BorderRadius.circular(20),
type: snackbarType,
duration: Duration(seconds: 5),
).show(context);
}
static timeSnackbar(context, {required String message}) {
return timerSnackbar(
context: context,
contentText: message,
afterTimeExecute: () => print("Operation Execute."),
second: 5,
);
}
static pogressbar(context) {
return showDialog(
context: context,
builder: (_) => Center(child: CircularProgressIndicator()));
}
static bottomSheet(context) {
return showModalBottomSheet(
context: context,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(24),
topRight: Radius.circular(24),
),
),
builder: (_) => ListView(
shrinkWrap: true,
padding: EdgeInsets.only(top: mq.height * .03, bottom: mq.height * .05),
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
child: Text(
"Pick a profile picture",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ImageButton(
width: .3,
height: .12,
click: () async {
await Api.fromCamera(context);
},
imagePath: "images/camera.png",
),
ImageButton(
width: .3,
height: .12,
click: () async {
await Api.fromGallery(context);
},
imagePath: "images/picture.png",
),
],
),
],
),
);
}
static profile(context, {required UserModel model, void Function()? click}) {
return showDialog(
context: context,
builder: (_) => AlertDialog(
backgroundColor: Colors.white.withOpacity(.9),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
content: SizedBox(
width: mq.width * 6,
height: mq.height * .35,
child: Stack(
children: [
Positioned(
top: mq.height * .075,
left: mq.width * .1,
child: ImageURL(
image: model.image, wh: mq.width * .5, hb: mq.height * .25),
),
Positioned(
top: mq.width * .04,
left: mq.height * .02,
width: mq.width * .55,
child: Text(
model.name,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
),
Positioned(
right: 8,
top: 6,
child: MaterialButton(
minWidth: 0,
padding: EdgeInsets.all(0),
shape: CircleBorder(),
onPressed: click,
child: Icon(
Icons.info_outline,
color: Colors.blue,
size: 30,
),
),
),
],
),
),
),
);
}
} |
import { NextFunction, Request, Response } from 'express';
import { verify } from 'jsonwebtoken';
import authConfig from '../../../../config/auth';
import { UsersRepository } from '../../../../modules/accounts/infra/typeorm/repositories/UsersRepository';
import { AppError } from '../../../errors/AppError';
async function ensureAuthenticated(
request: Request,
response: Response,
next: NextFunction,
): Promise<void> {
const authHeader = request.headers.authorization;
if (!authHeader) throw new AppError('Unauthorized', 401);
const [, token] = authHeader.split(' ');
let userId: string;
try {
const decoded = verify(token, authConfig.token.secret);
userId = decoded.sub as string;
} catch (err) {
throw new AppError('The token is invalid or expired!', 401);
}
const usersRepository = new UsersRepository();
const user = await usersRepository.findById(userId as string);
if (!user) throw new AppError('Unauthorized', 401);
request.user = { id: user.id };
next();
}
export { ensureAuthenticated }; |
#!/usr/bin/env python3
import enum
import logging
import sys
from typing import Final
import qbittorrentapi
@enum.unique
class ToolExitCodes(enum.IntEnum):
ALL_GOOD = 0
BASE_ERROR = 1
QBIT_AUTH_FAILURE = 2
HTTP_ERROR = 3
INVALID_PORT = 4
QBIT_PREF_MISSING = 5
if __name__ == "__main__":
# Torrent host and WebUI port
_TORRENT_HOST: Final[str] = "localhost"
_TORRENT_PORT: Final[int] = 8080 # default qBittorrent WebUI port
__EXIT_CODE = ToolExitCodes.ALL_GOOD
logging.basicConfig(level=logging.INFO,
datefmt="%Y-%m-%d %H:%M:%S",
format='%(asctime)s %(name)-10s %(levelname)-8s %(message)s')
logger = logging.getLogger("port-tool")
qbit_port: int = -1
vpn_port: int = -1
# forwarded_port file path chosen
file_path = "/host/binded/folder/path/forwarded_port" # "forwarded_port" is the default name of Gluetun file where forwarded port information is saved
# Try to read the file
try:
with open(file_path, 'r') as file:
vpn_port = int(file.read().strip())
except FileNotFoundError:
print(f"File {file_path} non trovato.")
exit(1)
# Gather the qBittorent _port
try:
qbt_client = qbittorrentapi.Client(host=f'http://{_TORRENT_HOST}:{_TORRENT_PORT}',
username='username',
password='password')
qbt_client.auth_log_in()
logger.info(f'qBittorrent: {qbt_client.app.version}')
logger.info(f'qBittorrent Web API: {qbt_client.app.web_api_version}')
if "listen_port" in qbt_client.app.preferences:
qbit_port: int = int(qbt_client.app.preferences["listen_port"])
logger.info(f"Torrent Port is {qbit_port}")
else:
logger.error("Preference listen_port not found")
__EXIT_CODE = ToolExitCodes.QBIT_PREF_MISSING
# Change prefs if needed
if __EXIT_CODE == ToolExitCodes.ALL_GOOD:
if vpn_port != qbit_port:
qbt_client.app.preferences = dict(listen_port=vpn_port)
logger.info(f"Updated qBittorrent listening port to {vpn_port}")
qbt_client.app.preferences = dict(embedded_tracker_port=vpn_port)
logger.info(f"Updated qBittorrent tracker port to {vpn_port}")
else:
logger.info(f"Ports matched, no change ({vpn_port} == {qbit_port})")
except qbittorrentapi.LoginFailed as e:
logger.error(str(e))
__EXIT_CODE = ToolExitCodes.QBIT_AUTH_FAILURE
sys.exit(__EXIT_CODE) |
import React from "react";
import { Layout } from 'antd';
import '../App.css';
import { Card, Progress, Statistic } from 'antd';
import { getStatsData } from "../utils/requests";
import LoadingIcon from "../components/LoadingIcon";
const { Content } = Layout;
const AdminDashboard = (props) => {
const [stats, setStats] = React.useState({});
const getStats = async () => {
await getStatsData().then(res => {
if (res.ok) {
res.json().then(
data => {
setStats(data);
}
)
}
})
}
React.useEffect(() => {
getStats();
} , []);
return (
<>
<Content >
{JSON.stringify(stats) === '{}' ? <div style={{height:'100%', display:'flex', justifyContent:'center', alignItems:'center' }}><LoadingIcon/></div> :
(<div className="admin-dashboard-total-card">
<div>
<Card
title="Total Users Registered"
bordered={false}
style={{ marginBottom: '10px' }}
>
<Statistic value={stats.user_total} />
</Card>
<Card
title="Total Assessments Taken"
bordered={false}
style={{ marginBottom: '10px' }}
>
<Statistic value={stats.result_total} />
</Card>
<Card
title="Average Score"
bordered={false}
style={{ marginBottom: '10px' }}
>
<Statistic value={stats.avg_score} />
</Card>
</div>
<Card
title="Detailed Average Performance"
bordered={false}
>
<div className="admin-dashboard-circle-group">
<div className="admin-dashboard-circle">
<div className="admin-dashboard-circle-text">Energy</div>
<Progress
type="circle"
strokeColor={{
'0%': '#108ee9',
'100%': '#87d068',
}}
percent={stats.avg_energy} />
</div>
<div className="admin-dashboard-circle">
<div className="admin-dashboard-circle-text">Location</div>
<Progress
type="circle"
strokeColor={{
'0%': '#108ee9',
'100%': '#87d068',
}}
percent={stats.avg_location} />
</div>
<div className="admin-dashboard-circle">
<div className="admin-dashboard-circle-text">Public Transport</div>
<Progress
type="circle"
strokeColor={{
'0%': '#108ee9',
'100%': '#87d068',
}}
percent={stats.avg_pt} />
</div>
<div className="admin-dashboard-circle">
<div className="admin-dashboard-circle-text">Certification</div>
<Progress
type="circle"
strokeColor={{
'0%': '#108ee9',
'100%': '#87d068',
}}
percent={stats.avg_ct} />
</div>
</div>
</Card>
</div>)}
</Content>
</>
)
}
export default AdminDashboard; |
import React from 'react'
import Container from './Container'
import WeatherIcon from './WeatherIcon'
import WeatherDetails, { WeatherDetailsProps } from './WeatherDetails'
import { convertKelvinToCelsius } from '@/utils/convertKalvinToCelsius';
export interface ForecastWeatherDetailProps extends WeatherDetailsProps {
weatherIcon: string;
date: string;
day: string;
temp: number;
feels_like: number;
temp_min: number;
temp_max: number;
description: string;
}
export default function ForecastWeatherDetail(props: ForecastWeatherDetailProps) {
const {
weatherIcon = "02d",
date = "19.09",
day = "Tuesday",
temp,
feels_like,
temp_min,
temp_max,
description
} = props;
return (
<Container className='gap-4'>
{/* Left Section */}
<section className='flex gap-4 items-center px-4'>
<div className='flex flex-col gap-1 items-center'>
<WeatherIcon iconName={weatherIcon} />
<p className='text-xs'>{date}</p>
<p className='text-xs'>{day}</p>
</div>
{/* */}
<div className='flex flex-col px-4'>
<span className='text-5xl'>{convertKelvinToCelsius(temp ?? 0)}°</span>
<p className='text-xs space-x-1 whitespace-nowrap'>
<span> Feels like</span>
<span>{convertKelvinToCelsius(feels_like ?? 0)}°</span>
</p>
<p className='capitalize'>{description}</p>
</div>
</section>
{/* Right Section */}
<section className='overflow-x-auto flex justify-between gap-4 px-4 w-full pr-10'>
<WeatherDetails {...props} />
</section>
</Container>
)
} |
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { SequelizeModule } from "@nestjs/sequelize";
import { ProductsModule } from "./products/products.module";
import { UsersModule } from "./users/users.module";
import { Product } from "./products/products.model";
@Module({
imports: [
ConfigModule.forRoot({
envFilePath: `.${process.env.NODE_ENV}.env`,
}),
SequelizeModule.forRoot({
dialect: "postgres",
host: process.env.POSTGRES_HOST,
port: +process.env.POSTGRES_PORT,
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
models: [Product],
synchronize: true,
autoLoadModels: true,
}),
ProductsModule,
UsersModule,
],
controllers: [],
providers: [],
})
export class AppModule {} |
import { useState, useEffect } from 'react'
export default function Home() {
const [name, setName] = useState('')
const [age, setAge] = useState('')
const [users, setUsers] = useState([])
const handleDelete = async (id) => {
const response = await fetch(`/api/users/delete?id=${id}`, { method: 'DELETE' })
const data = await response.json()
setUsers(data)
}
const handleSubmit = async (event) => {
event.preventDefault()
const response = await fetch('/api/users/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name, age }),
})
const data = await response.json()
setUsers(data)
}
useEffect(() => {
const fetchData = async () => {
const response = await fetch('/api/users/read')
const data = await response.json()
setUsers(data)
}
fetchData()
}, [])
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={(event) => setName(event.target.value)} />
</label>
<label>
Age:
<input type="number" value={age} onChange={(event) => setAge(event.target.value)} />
</label>
<button type="submit">Create</button>
<ul>
{users.map((user) => (
<li key={user._id}>
{user.name} ({user.age})
<button onClick={() => handleDelete(user._id)}>Delete</button>
</li>
))}
</ul>
</form>
)
} |
package com.example.case_study.model;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "educationDegrees")
public class EducationDegree {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@OneToMany(mappedBy = "educationDegree", cascade = CascadeType.ALL)
private List<Employee> employees;
public EducationDegree() {
}
public EducationDegree(String name, List<Employee> employees) {
this.name = name;
this.employees = employees;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} |
import { pullAll } from "lodash-es";
import { ignoredHtmlElements } from "../htmlConstants";
import getElementContent from "./getElementContent";
/**
* Gathers all elements that can be closed given the position of the current element in the source code.
*
* Elements that can be closed are all elements that are opened before this element, but in which this element is
* not nested.
* E.g.
* ```html
* <strong>Hello</strong><em>World<b>!!!</b></em>`
* ```
* with `<b>!!!</b>` as the current element,
* means that the `<strong>` needs to be closed, but `<em>` **not**.
*
* @param {module:tree/structure.FormattingElement} currentElement The current element.
* @param {module:tree/structure.FormattingElement[]} openElements The elements that are currently open.
*
* @returns {module:tree/structure.FormattingElement[]} The elements that can be closed.
*/
const elementsThatCanBeClosed = function (currentElement, openElements) {
return openElements.filter(el => {
const endTag = el.location.endTag;
return endTag.endOffset <= currentElement.location.startOffset;
});
};
/**
* Closes the elements that can be closed given the position of the current element within the source code.
*
* This does two things:
* 1. The closed element's text end index is calculated based on the current offset.
* 2. The closed element's end tag lengths are counted towards the current offset, to make sure that the computed position
* of the formatting elements are still correct.
*
* @param {module:tree/structure.FormattingElement[]} elementsToClose The list of open elements that need to be closed
* @param {number} currentOffset The current offset when parsing the formatting elements
*
* @returns {number} The updated current offset
*
* @private
*/
const closeElements = function (elementsToClose, currentOffset) {
// Sort, so we close all elements in the right order.
elementsToClose.sort((a, b) => a.location.endTag.endOffset - b.location.endTag.endOffset);
elementsToClose.forEach(elementToClose => {
const endTag = elementToClose.location.endTag;
// Set the end position as seen in the text.
elementToClose.textEndIndex = endTag.startOffset - currentOffset;
/*
Add the end tag length of the to be closed element to the total offset.
*/
const endTagLength = endTag.endOffset - endTag.startOffset;
currentOffset += endTagLength;
});
return currentOffset;
};
/**
* Adds the content length of the given element (the part between the tags) to the current offset
* and adds the content to the element as a parameter.
*
* @param {module:tree/structure.FormattingElement} element The element of which to add the content length.
* @param {string} html The original html source code.
* @param {number} currentOffset The current offset to which to add the length to.
*
* @returns {number} The updated current offset
*/
const handleIgnoredContent = function (element, html, currentOffset) {
// Has 0 length in text, so end = start.
element.textEndIndex = element.textStartIndex;
// Set content.
const content = getElementContent(element, html);
element.content = content;
// Update current offset.
currentOffset += content.length;
return currentOffset;
};
/**
* Sets the start and end position of the formatting elements in the given node's text.
*
* @param {module:tree/structure.LeafNode} node The node containing a TextContainer
* @param {string} html The source code
*
* @returns {void}
*
* @private
*/
const calculateTextIndices = function (node, html) {
if (!node.textContainer.formatting || node.textContainer.formatting.length === 0) {
return;
}
const openElements = [];
/*
Keeps track of the current total size of the start and end tags (and the ignored content)
These should not be counted towards the start and end position of the elements in the text.
*/
let currentOffset = node.location.startTag ? node.location.startTag.endOffset : node.location.startOffset;
node.textContainer.formatting.forEach(element => {
// Close elements that can be closed.
const elementsToClose = elementsThatCanBeClosed(element, openElements);
currentOffset = closeElements(elementsToClose, currentOffset);
// Remove closed elements from the list.
pullAll(openElements, elementsToClose);
const startTag = element.location.startTag;
const endTag = element.location.endTag;
// For example: "<strong>".length
const startTagLength = startTag.endOffset - startTag.startOffset;
currentOffset += startTagLength;
// Set start position of element in heading's / paragraph's text.
element.textStartIndex = startTag.endOffset - currentOffset;
if (endTag) {
// Keep track of the elements that need to be closed.
openElements.push(element);
} else {
/*
Some elements have no end tags,
e.g. void elements like <img/> or self-closing elements.
We can close them immediately (with length of 0, since it has no content).
*/
element.textEndIndex = element.textStartIndex;
}
/*
If this element is an ignored element its contents are not in the text,
so its content should be added to the respective formatting element instead,
and the current offset should be updated.
*/
if (ignoredHtmlElements.includes(element.type)) {
currentOffset = handleIgnoredContent(element, html, currentOffset);
}
});
// Close all remaining elements.
closeElements(openElements, currentOffset);
};
export default calculateTextIndices;
//# sourceMappingURL=calculateTextIndices.js.map |
<#import "../../common/home.ftlh" as h>
<#import "../../common/fileinput.ftlh" as f>
<@h.home "Product adding">
<@f.fileinput "photo", "" />
<link href="static/css/bootstrap-select.css" rel="stylesheet">
<script src="static/js/bootstrap-select.js"></script>
<form method="post" action="products/create" enctype="multipart/form-data">
<div class="form-group row">
<label class="col-sm-2">Photo:</label>
<div class="col-sm-10">
<input class="form-control" id="photo" type="file" name="photo" required>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">Name:</label>
<div class="col-sm-10">
<input class="form-control" name="name" value="<#if product??>${product.name!}</#if>">
<#if nameError??><div class="text-warning">${nameError}</div></#if>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">Description:</label>
<div class="col-sm-10">
<textarea class="form-control" name="description" rows="4"><#if product??>${product.description!}</#if></textarea>
<#if descriptionError??><div class="text-warning">${descriptionError}</div></#if>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">Category:</label>
<div class="col-sm-10">
<select class="form-control selectpicker" name="category" data-live-search="true" data-size="4">
<#list categories as category>
<option value="${category.id?c}"
<#if product?? && category == product.category>selected</#if>>${category.name}</option>
</#list>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">Price:</label>
<div class="col-sm-10">
<input class="form-control" type="number" name="price" value="<#if product?? && product.price??>${product.price?c}</#if>">
<#if priceError??><div class="text-warning">${priceError}</div></#if>
</div>
</div>
<input type="hidden" name="_csrf" value="${_csrf.token}">
<button class="btn btn-success" type="submit">Create</button>
</form>
<form method="get" action="products">
<button class="btn btn-info" type="submit">Back</button>
</form>
</@h.home> |
import { IStorageProvider, StorageConfig } from '../../interfaces';
import {
CreateBucketCommand,
DeleteBucketCommand,
DeleteObjectCommand,
GetObjectCommand,
HeadBucketCommand,
HeadObjectCommand,
ListObjectsCommand,
PutObjectCommand,
S3Client,
S3ClientConfig,
} from '@aws-sdk/client-s3';
import { Readable } from 'stream';
import { streamToBuffer } from '../../utils';
import fs from 'fs';
import { getSignedUrl as awsGetSignedUrl } from '@aws-sdk/s3-request-presigner';
import ConduitGrpcSdk from '@conduitplatform/grpc-sdk';
import { ConfigController } from '@conduitplatform/module-tools';
import { SIGNED_URL_EXPIRY_SECONDS } from '../../constants/expiry';
type AwsError = { $metadata: { httpStatusCode: number } };
type GetResult = Buffer | Error;
type StoreResult = boolean | Error;
export class AWSS3Storage implements IStorageProvider {
private readonly _storage: S3Client;
private _activeContainer: string = '';
constructor(options: StorageConfig) {
const config: S3ClientConfig = {
region: options.aws.region,
credentials: {
accessKeyId: options.aws.accessKeyId,
secretAccessKey: options.aws.secretAccessKey,
},
};
if (options.aws.endpoint !== '') {
config.endpoint = options.aws.endpoint;
}
this._storage = new S3Client(config);
}
container(name: string): IStorageProvider {
this._activeContainer = this.getFormattedContainerName(name);
return this;
}
async store(fileName: string, data: any, isPublic?: boolean): Promise<StoreResult> {
await this._storage.send(
new PutObjectCommand({
Bucket: this._activeContainer,
Key: fileName,
Body: data,
GrantRead: isPublic
? 'uri="http://acs.amazonaws.com/groups/global/AllUsers"'
: undefined,
}),
);
return true;
}
async get(fileName: string, downloadPath?: string): Promise<GetResult> {
const stream = await this._storage.send(
new GetObjectCommand({
Bucket: this._activeContainer,
Key: fileName,
}),
);
const data = await streamToBuffer(stream.Body as Readable);
if (downloadPath) {
fs.writeFileSync(downloadPath, data);
}
return data;
}
async createFolder(name: string): Promise<boolean | Error> {
//check if keep.txt file exists
const exists = await this.folderExists(name);
if (exists) return true;
await this._storage.send(
new PutObjectCommand({
Bucket: this._activeContainer,
Key: name + '.keep.txt',
Body: 'DO NOT DELETE',
}),
);
ConduitGrpcSdk.Metrics?.increment('folders_total');
return true;
}
async folderExists(name: string): Promise<boolean | Error> {
try {
await this._storage.send(
new HeadObjectCommand({
Bucket: this._activeContainer,
Key: name + '.keep.txt',
}),
);
return true;
} catch (error) {
if (
(error as AwsError).$metadata.httpStatusCode === 403 ||
(error as AwsError).$metadata.httpStatusCode === 404
) {
return false;
}
throw error;
}
}
async createContainer(name: string): Promise<boolean | Error> {
name = this.getFormattedContainerName(name);
await this._storage.send(
new CreateBucketCommand({
Bucket: name,
}),
);
this._activeContainer = name;
ConduitGrpcSdk.Metrics?.increment('containers_total');
return true;
}
async containerExists(name: string): Promise<boolean> {
name = this.getFormattedContainerName(name);
try {
await this._storage.send(new HeadBucketCommand({ Bucket: name }));
return true;
} catch (error) {
if (
(error as AwsError).$metadata.httpStatusCode === 403 ||
(error as AwsError).$metadata.httpStatusCode === 404
) {
return false;
}
throw error;
}
}
async deleteContainer(name: string): Promise<boolean | Error> {
name = this.getFormattedContainerName(name);
await this._storage.send(
new DeleteBucketCommand({
Bucket: name,
}),
);
ConduitGrpcSdk.Metrics?.decrement('containers_total');
return true;
}
async deleteFolder(name: string): Promise<boolean | Error> {
const exists = await this.folderExists(name);
if (!exists) return false;
ConduitGrpcSdk.Logger.log('Getting files list...');
const files = await this.listFiles(name);
let i = 0;
ConduitGrpcSdk.Logger.log('Deleting files...');
for (const file of files) {
i++;
await this.delete(file.Key!);
ConduitGrpcSdk.Logger.log(file.Key!);
}
ConduitGrpcSdk.Logger.log(`${i} files deleted.`);
ConduitGrpcSdk.Metrics?.decrement('folders_total');
return true;
}
async delete(fileName: string): Promise<boolean | Error> {
await this._storage.send(
new DeleteObjectCommand({
Bucket: this._activeContainer,
Key: fileName,
}),
);
return true;
}
async exists(fileName: string): Promise<boolean | Error> {
try {
await this._storage.send(
new HeadObjectCommand({
Bucket: this._activeContainer,
Key: fileName,
}),
);
return true;
} catch (error) {
if (
(error as AwsError).$metadata.httpStatusCode === 403 ||
(error as AwsError).$metadata.httpStatusCode === 404
) {
return false;
}
throw error;
}
}
async getSignedUrl(fileName: string) {
const command = new GetObjectCommand({
Bucket: this._activeContainer,
Key: fileName,
});
return awsGetSignedUrl(this._storage, command, {
expiresIn: SIGNED_URL_EXPIRY_SECONDS,
});
}
async getPublicUrl(fileName: string) {
return `https://${this._activeContainer}.s3.amazonaws.com/${fileName}`;
}
getUploadUrl(fileName: string): Promise<string | Error> {
const command = new PutObjectCommand({
Bucket: this._activeContainer,
Key: fileName,
});
return awsGetSignedUrl(this._storage, command, {
expiresIn: SIGNED_URL_EXPIRY_SECONDS,
});
}
private getFormattedContainerName(bucketName: string): string {
const accountId = ConfigController.getInstance().config.aws.accountId;
return `conduit-${accountId}-${bucketName}`;
}
private async listFiles(name: string) {
const files = await this._storage.send(
new ListObjectsCommand({
Bucket: this._activeContainer,
Prefix: name,
}),
);
if (!files.Contents) return [];
return files.Contents;
}
} |
import React, { useEffect, useRef } from "react";
export default function useOutsideClick(
callback: () => void):
React.RefObject<HTMLDivElement> {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleClick = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as HTMLElement)) {
callback();
}
}
document.addEventListener('click', handleClick);
return () => {
document.removeEventListener('click', handleClick);
};
}, [ref, callback]);
return ref;
}; |
<template>
<div class="wrapper">
<Title :title-content="'我的订单'"/>
<div class="orders">
<div class="order"
v-for="(item, index) in list"
:key="index"
>
<div class="order__title">
{{item.shopName}}
<span class="order__status">
{{item.isCanceled ? '已取消' : '已完成'}}
</span>
</div>
<div class="order__content">
<div class="order__content__imgs">
<template
v-for="(innerItem, innerIndex) in item.products"
:key="innerIndex"
>
<img class="order__content__img"
:src="innerItem.product.img"
v-if="innerIndex <= 3"
/>
</template>
</div>
<div class="order__content__info">
<div class="order__content__price">¥ {{item.totalPrice}}</div>
<div class="order__content__count">共 {{item.totalNumber}} 件</div>
</div>
</div>
</div>
</div>
</div>
<Docker :currentIndex="2"/>
</template>
<script>
import Docker from '../../components/Docker'
import Title from '../../components/Title'
import { get } from '@/utils/request'
import { reactive, toRefs } from 'vue'
const useOrderListEffect = () => {
const data = reactive({ list: [] })
const getOrderList = async () => {
const result = await get('/api/order')
if (result?.errno === 0 && result?.data?.length) {
result.data.forEach((order) => {
const products = order.products || []
let totalNumber = 0
let totalPrice = 0
products.forEach((productItem) => {
totalNumber += (productItem?.orderSales || 0)
totalPrice += ((productItem?.product?.price * productItem?.orderSales) || 0)
})
order.totalNumber = totalNumber
order.totalPrice = totalPrice
})
data.list = result.data
}
}
getOrderList()
const { list } = toRefs(data)
return { list }
}
export default {
name: 'OrderList',
components: { Docker, Title },
setup () {
const { list } = useOrderListEffect()
return { list }
}
}
</script>
<style lang="scss" scoped>
@import "../../style/viriables";
@import "../../style/mixins";
.wrapper {
@include wrapper
}
.orders {
padding: .16rem .18rem 0 .18rem;
}
.order {
background: $bgColor;
height: 1.11rem;
padding: .16rem;
box-sizing: border-box;
&__title {
font-size: .16rem;
color: $content-fontcolor;
line-height: .22rem;
margin-bottom: .16rem;
}
&__status {
font-size: .14rem;
color: $light-fontColor;
float: right;
}
&__content {
display: flex;
&__imgs {
flex: 1;
}
&__img {
width: .4rem;
height: .4rem;
margin-right: .12rem;
}
&__info {
width: .7rem;
}
&__price {
font-size: .14rem;
color: $highlight-fontColor;
text-align: right;
line-height: .2rem;
margin-bottom: .04rem;
}
&__count {
font-size: .12rem;
color: $content-fontcolor;
text-align: right;
line-height: .14rem;
}
}
}
</style> |
import { useRef, useState } from "react";
import { collection, addDoc, getFirestore } from "firebase/firestore";
import { toast } from "react-toastify";
import { Textarea, Input, Button } from "@/components";
import { useAuth, useNotes } from "@/store";
export const NoteForm = () => {
const { user } = useAuth();
const { addNote } = useNotes();
const titleRef = useRef();
const descriptionRef = useRef();
const [creating, setCreating] = useState(false);
const handleSaveNote = async () => {
try {
setCreating(true);
const noteRef = collection(getFirestore(), `${user.uid}/user/todos`);
const note = {
title: titleRef.current.value,
description: descriptionRef.current.value,
timecreation: new Date().getTime(),
};
const doc = await addDoc(noteRef, note);
addNote({ id: doc.id, ...note });
titleRef.current.value = "";
descriptionRef.current.value = "";
} catch (error) {
toast.error("Oops.\nSomething went wrong when creating the note");
} finally {
setCreating(false);
}
};
return (
<>
<div className="flex flex-col m-auto w-3/5 sm:w-1/2 lg:w-1/3 rounded border-2 drop-shadow-lg border-neutral-800 bg-neutral-800">
<Input ref={titleRef} name="title" placeholder="Title" />
<Textarea
ref={descriptionRef}
className="resize-none h-24"
name="description"
placeholder="Take a note..."
/>
<Button
disabled={creating}
onClick={handleSaveNote}
className="absolute right-2 -bottom-4 bg-yellow-500 rounded-full w-9 h-9 flex items-center justify-center hover:bg-yellow-400 disabled:bg-gray-400"
>
<i className="fa-solid fa-plus"></i>
</Button>
</div>
</>
);
}; |
import React, {useMemo, useState} from 'react';
import "bootstrap-icons/font/bootstrap-icons.css";
import '@/styles/_product.scss';
import {winner} from "@/constant/user";
import {handleDataDetail} from "../../utils/help";
import ProductDetail from "./ProductDetail";
import _ from 'lodash';
import MyButton from "@/components/Elements/Buttons/MyButton";
const ProductItem = ({product}) => {
const [showDetail, setShowDetail] = useState(false);
const {isWinner, description, details, img, sale, title} = product;
const handleShowDetail = () => {
setShowDetail(!showDetail)
}
return (
<div className="product">
<div className="product__header">
{isWinner && (
<div className="product__header__banner">
<span className="product__header__product__title">
{winner}
</span>
</div>
)}
<div className="product__header__image">
<img
src={img}
alt={""}
className="product__header__image__product"
/>
</div>
<div className="product__header__title">
<div className="product__header__title__info">
<h3 className="product__header__title__info__brand">{title}</h3>
<span className="product__header__title__info__discount">{sale} OFF</span>
</div>
<p className="product__header__title__description">
{description}
</p>
<div className="product__header__title__mobile"></div>
<div className="product__header__title__actions">
<span className="product__header__title__actions__feature">
Product features
</span>
<i className="fa fa-angle-up" aria-hidden="true"></i>
</div>
</div>
<div className="product__header__price">
<div className="product__header__price__score">
<span className="product__header__price__score__value">9.8</span>
<span>score</span>
</div>
<div className="product__header__price__group">
<MyButton onClick={handleShowDetail} styleModify={"product__header__price--button"}>
<span>More Info</span>
</MyButton>
<div className="product__header__price__compare">
<p className="product__header__price__compare__text">Compare prices</p>
<i className="fa fa-angle-down" aria-hidden="true"></i>
</div>
</div>
</div>
</div>
<hr/>
{
showDetail && <ProductDetail dataDetail={details}/>
}
</div>
);
};
export default ProductItem; |
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flame_audio/flame_audio.dart';
import 'package:flappy_bird/app/components/style/image_local.dart';
import 'package:flappy_bird/app/components/style/sound_local.dart';
import 'package:flappy_bird/app/modules/game_start/movement.dart';
import 'package:flappy_bird/app/modules/game_start/configuration.dart';
import 'package:flappy_bird/app/modules/game_start/GamePlay.dart';
import 'package:flappy_bird/app/routes/app_pages.dart';
import 'package:flutter/material.dart';
class Bird extends SpriteGroupComponent<BirdMovement>
with HasGameRef<GamePlay>, CollisionCallbacks {
Bird();
dynamic score = 0;
@override
Future<void> onLoad() async {
final birdMidFlap = await gameRef.loadSprite(ImageLocal.birdMidFlap);
final birdUpFlap = await gameRef.loadSprite(ImageLocal.birdUpFlap);
final birdDownFlap = await gameRef.loadSprite(ImageLocal.birdDownFlap);
gameRef.bird;
size = Vector2(50, 40);
current = BirdMovement.middle;
position = Vector2(50, gameRef.size.y / 2 - size.y / 2);
sprites = {
BirdMovement.middle: birdMidFlap,
BirdMovement.up: birdUpFlap,
BirdMovement.down: birdDownFlap,
};
add(CircleHitbox());
}
void fly() {
add(MoveByEffect(Vector2(0, Config.gravity),
EffectController(duration: 0.2, curve: Curves.decelerate),
onComplete: () => current = BirdMovement.down));
current = BirdMovement.up;
FlameAudio.play(SoundLocal.flying);
}
@override
void update(double dt) {
super.update(dt);
position.y += Config.birdVelocity * dt;
if (position.y < 1) {
gameOver();
}
}
@override
void onCollisionStart(
Set<Vector2> intersectionPoints,
PositionComponent other,
) {
debugPrint("Interact avagtar with obstacle");
super.onCollisionStart(intersectionPoints, other);
gameOver();
}
void reset() {
position = Vector2(50, gameRef.size.y / 2 - size.y / 2);
score = 0;
}
void gameOver() {
gameRef.overlays.add(Routes.GAMEOVER);
gameRef.pauseEngine();
FlameAudio.play(SoundLocal.collision);
game.isHit = true;
gameRef.pauseEngine();
}
} |
//! Data structures used in disclosure, created by the holder and sent to the RP.
//!
//! The main citizens of this module are [`DeviceResponse`], which is what the holder sends to the verifier during
//! verification, and [`IssuerSigned`], which contains the entire issuer-signed mdoc and the disclosed attributes.
use coset::{CoseMac0, CoseSign1};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_bytes::ByteBuf;
use serde_repr::{Deserialize_repr, Serialize_repr};
use serde_with::skip_serializing_none;
use std::fmt::Debug;
use crate::{
iso::mdocs::*,
utils::{
cose::MdocCose,
serialization::{NullCborValue, RequiredValue, TaggedBytes},
},
};
/// A disclosure of a holder, containing multiple [`Document`]s, containing some or all of their attributes.
#[skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DeviceResponse {
pub version: DeviceResponseVersion,
pub documents: Option<Vec<Document>>,
pub document_errors: Option<Vec<DocumentError>>,
pub status: u64,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum DeviceResponseVersion {
#[serde(rename = "1.0")]
V1_0,
}
pub type DocumentError = IndexMap<DocType, ErrorCode>;
/// A disclosed mdoc, containing:
/// - the MSO signed by the issuer including the mdoc's public key and the digests of the attributes,
/// - the values and `random` bytes of the disclosed (i.e. included) attributes,
/// - the holder signature (over the session transcript so far, which is not included here; see
/// [`DeviceAuthentication`](super::DeviceAuthentication)), using the private key corresponding to the public key
/// contained in the mdoc; this acts as challenge-response mechanism.
#[skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Document {
pub doc_type: DocType,
pub issuer_signed: IssuerSigned,
pub device_signed: DeviceSigned,
pub errors: Option<Errors>,
}
/// The issuer-signed MSO in Cose format, as well as some or all of the attributes including their randoms
/// (i.e. [`IssuerSignedItem`]s) contained in the mdoc. This includes the public key of the MSO,
/// but not the private key (for that, see [`Mdoc`](crate::holder::Mdoc)).
///
/// This data structure is used as part of mdocs (in which case `name_spaces` necessarily contains all attributes
/// of the mdoc), and also as part of a disclosure of the mdoc in the [`Document`] struct (in which some
/// attributes may be absent, i.e., not disclosed).
#[skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct IssuerSigned {
pub name_spaces: Option<IssuerNameSpaces>,
pub issuer_auth: MdocCose<CoseSign1, TaggedBytes<MobileSecurityObject>>,
}
/// The holder signature as during disclosure of an mdoc (see [`Document`]) computed with the mdoc private key, as well
/// as any self-asserted attributes.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DeviceSigned {
pub name_spaces: DeviceNameSpacesBytes,
pub device_auth: DeviceAuth,
}
/// Attributes included in a holder disclosure that have not been signed by the issuer, but only
/// by the holder: self-asserted attributes. See also [`DeviceSigned`] and
/// [`DeviceAuthentication`](super::DeviceAuthentication).
pub type DeviceNameSpaces = IndexMap<NameSpace, DeviceSignedItems>;
/// See [`DeviceNameSpaces`].
pub type DeviceNameSpacesBytes = TaggedBytes<DeviceNameSpaces>;
/// Self-asserted attributes as part of an mdoc disclosure.
pub type DeviceSignedItems = IndexMap<DataElementIdentifier, DataElementValue>;
/// The signature or MAC created by the holder during disclosure of an mdoc, with the private key of the mdoc
/// (whose public key is included in its MSO).
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub enum DeviceAuth {
DeviceSignature(MdocCose<CoseSign1, RequiredValue<NullCborValue>>),
DeviceMac(MdocCose<CoseMac0, RequiredValue<NullCborValue>>),
}
pub type Errors = IndexMap<NameSpace, ErrorItems>;
pub type ErrorItems = IndexMap<DataElementIdentifier, ErrorCode>;
pub type ErrorCode = i32;
/// Contains an encrypted mdoc disclosure protocol message, and a status code containing an error code or a code
/// that aborts the session.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SessionData {
pub data: Option<ByteBuf>,
pub status: Option<SessionStatus>,
}
/// Status codes sent along with encrypted mdoc disclosure protocol messages in [`StatusCode`].
#[derive(Serialize_repr, Deserialize_repr, Debug, Clone)]
#[repr(u8)]
pub enum SessionStatus {
EncryptionError = 10,
DecodingError = 11,
Termination = 20,
} |
package repository
import (
"database/sql"
"log"
"github.com/dafiqarba/be-payroll/entity"
_ "github.com/lib/pq"
)
// TODO: search how to return a populated struct from function, if struct is defined
type UserRepo interface {
//Create
CreateUser(user entity.User) (string, error)
//Read
FindByEmail(email string) (entity.UserLogin, error)
GetUserList() ([]entity.User, error)
GetUserDetail(id int) (entity.UserDetailModel, error)
}
type userConnection struct {
connection *sql.DB
}
func NewUserRepo(dbConn *sql.DB) UserRepo {
return &userConnection{
connection: dbConn,
}
}
func (db *userConnection) GetUserList() ([]entity.User, error) {
//Variable to store collection of users
var users []entity.User
//Execute SQL Query
rows, err := db.connection.Query(`SELECT * FROM users`)
//Error Handling
if err != nil {
log.Fatalf("tidak bisa mengeksekusi query. %v", err)
}
log.Println("| Requst received")
//Close the Execution of SQL Query
defer rows.Close()
//Iterate over all available rows and strore the data
for rows.Next() {
var user entity.User
// scan and assign into destination variable
err = rows.Scan(&user.User_id, &user.Email, &user.Password, &user.Name, &user.Position_id, &user.Nik, &user.Role_id)
if err != nil {
log.Fatalf("tidak bisa mengambil data. %v", err)
}
// append to users slice
users = append(users, user)
}
// returns populated data
return users, err
}
func (db *userConnection) GetUserDetail(id int) (entity.UserDetailModel, error) {
var userDetail entity.UserDetailModel
//SQL Query
query := `
SELECT
u.user_id, u.username, u.name, u.position_id, u.nik, u.role_id, r.role_name, p.position_name
FROM users AS u
INNER JOIN roles AS r
ON r.role_id = u.role_id
INNER JOIN positions AS p
ON p.position_id = u.position_id
WHERE user_id=$1`
//Execute SQL Query
row := db.connection.QueryRow(query,id)
err := row.Scan(&userDetail.User_id, &userDetail.Username, &userDetail.Name, &userDetail.Position_id, &userDetail.Nik, &userDetail.Role_id, &userDetail.Role_name, &userDetail.Position_name)
//Err Handling
if err != nil {
if err == sql.ErrNoRows {
log.Println("| "+err.Error())
return userDetail, err
} else {
log.Println("| "+err.Error())
return userDetail, err
}
}
// returns login data
return userDetail, err
}
func (db *userConnection) CreateUser (u entity.User) (string, error) {
//Variable that holds registered user email
var createdUser string
//Query
query := `
INSERT INTO
users (username, name, password, email, nik, role_id, position_id)
VALUES
($1, $2, $3, $4, $5, $6, $7)
RETURNING email
;
`
//Execute query and Populating createdUser variable
err := db.connection.QueryRow(query, u.Username, u.Name, u.Password, u.Email, u.Nik, u.Role_id, u.Position_id).Scan(&createdUser)
if err != nil {
log.Println("| " + err.Error())
return "", err
}
//Returns registered user email and nil error
return createdUser, err
}
func (db *userConnection) FindByEmail (emailToCheck string) (entity.UserLogin, error) {
// Var to be populated with user data
var userData entity.UserLogin
//Query
query := `
SELECT
u.user_id, u.username, u.email, u.password, u.role_id
FROM
users AS u
WHERE
email = $1;
`
//Execute
row := db.connection.QueryRow(query, emailToCheck)
err := row.Scan(&userData.User_id, &userData.Username, &userData.Email, &userData.Password, &userData.Role_id)
//Err Handling
if err != nil {
if err == sql.ErrNoRows {
log.Println("| "+err.Error())
return userData, err
} else {
log.Println("| "+err.Error())
return userData, err
}
}
// returns login data
return userData, err
} |
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-formulario-edificio',
templateUrl: './formulario-edificio.component.html',
styleUrls: ['./formulario-edificio.component.css']
})
export class FormularioEdificioComponent implements OnInit {
rutaImagen: string = '';
edificioId: string = '';
edificio: { ID: string, descripcion: string, valor: string, depreciacion: string, mantenimiento: string } | undefined;
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.params.subscribe(params => {
this.rutaImagen = params['rutaImagen'];
this.edificioId = params['edificioId'];
this.edificio = this.edificios.find(e => e.ID === this.edificioId);
});
}
edificios: { ID: string, descripcion: string, valor: string, depreciacion: string, mantenimiento: string }[] = [
{ ID: '1', descripcion: 'NuevaContra2', valor: 'Angel Mero Celorio', depreciacion: 'Angel Mero Celorio', mantenimiento: 'Angel Mero Celorio'},
{ ID: '2', descripcion: 'Edificio Grande', valor: '423442.00', depreciacion: '3%', mantenimiento: 'no'},
{ ID: '3', descripcion: 'Edificio Mediano', valor: '3123123.32', depreciacion: '14%', mantenimiento: 'si'},
{ ID: '4', descripcion: 'Edificio medianamente Grande', valor: '343212.34', depreciacion: '11%', mantenimiento: 'no'},
{ ID: '5', descripcion: 'Edificio amplio con 2 pisos', valor: '86567.39', depreciacion: '12%', mantenimiento: 'si'},
{ ID: '6', descripcion: 'Edificio con 3 plantas', valor: '34447.67', depreciacion: '6%', mantenimiento: 'no'},
{ ID: '7', descripcion: 'Edificio pequeño', valor: '324242.88', depreciacion: '13%', mantenimiento: 'no'},
{ ID: '8', descripcion: 'Edificio Grande', valor: '332452.66', depreciacion: '12%', mantenimiento: 'no'},
{ ID: '9', descripcion: 'Edificio Amplio', valor: '34234.22', depreciacion: '3%', mantenimiento: 'no'},
{ ID: '10', descripcion: 'Mediananamente Grande', valor: '22344.12', depreciacion: '9%', mantenimiento: 'si'},
{ ID: '11', descripcion: 'Grande 3 Edificio', valor: '33443.33', depreciacion: '4%', mantenimiento: 'si'},
{ ID: '12', descripcion: 'Grande Edificio', valor: '3243243.77', depreciacion: '9%', mantenimiento: 'si'},
{ ID: '13', descripcion: 'Edificio Mediano', valor: '4234324.99', depreciacion: '7%', mantenimiento: 'no'},
{ ID: '14', descripcion: 'Edificio Grande', valor: '577657657.12', depreciacion: '5%', mantenimiento: 'no'},
{ ID: '15', descripcion: 'Edificio Pequeño', valor: '32424332.44', depreciacion: '12%', mantenimiento: 'no'},
{ ID: '16', descripcion: 'Edificio Grande', valor: '4535435.66', depreciacion: '8%', mantenimiento: 'si'},
];
enviarFormulario() {
// Validación del campo descripción
const descripcionRegex = /^[A-Za-z\s]+$/; // Solo letras y espacios
if (!this.edificio || !descripcionRegex.test(this.edificio.descripcion)) {
alert("La descripción es incorrecta. Solo se permiten letras y espacios.");
return;
}
// Validación del campo valor
const valorRegex = /^\d+\.\d{2}$/; // Número decimal con hasta 2 decimales
if (!this.edificio || !valorRegex.test(this.edificio.valor)) {
alert("El valor es incorrecto. Debe ser un números enteros válido con dos decimales.");
return;
}
// Validación del campo depreciación
const depreciacionRegex = /^(\d{1,2}(\.\d{1,2})?|25(\.0{1,2})?)%$/; // Número decimal con hasta 2 decimales o 25%
if (!this.edificio || !depreciacionRegex.test(this.edificio.depreciacion)) {
alert("La depreciación es incorrecta. Debe ser un número decimal válido de hasta el 25%.");
return;
}
// Validación del campo mantenimiento
if (!this.edificio || this.edificio.mantenimiento.length > 200) {
alert("El mantenimiento es incorrecto. Solo se permiten un máximo de 200 caracteres.");
return;
}
// Resto del código para enviar el formulario
}
} |
<html>
<head>
<title>Crossfire Playerbook - Chapter 5</title>
</head>
<body>
<h1>Skills System</h1>
<h2><a name="5.1.0">Description</h2>
Under the skills system the flow of play changes dramatically. Instead of
gaining experience for basically just killing monsters (and disarming traps)
players will now gain a variety of experience through the use of skills.
Some skills replicate old functions in the game (e.g. melee weapons skill,
missile weapon skill) while others add new functionality (e.g. stealing,
hiding, writing, etc). A complete list of the available skills can be found
in table <a href="#table_skill_stats">skill statistics</a>. Appendix <a
href="appB.html">B (skills)</a> contains descriptions for many of the
skills. <p>
<em>Note:</em> The skills system is enabled as the default option
as of version 0.92.0<p>
<em>Note2:</em> The new skills/experience system is compatible
with character files from at least version 0.91.1 onward.
<a name="table_skill_stats">
<center>
<table border=1 cellpadding=5">
<tr><th>Skill</th><th>Experience Category</th><th colspan=3>Associated Stats</th></tr>
<tr><th></th><th></th><th>Stat 1</th><th>Stat 2</th><th>Stat 3</th></tr>
<!--#include file="skill_stat.html"-->
</table>
Skills</center>
<p>
<h2><a name="5.2.0">About experience and skills</h2>
<h3><a name="5.2.1">Associated and miscellaneous skills</h3>
In <em>Crossfire</em> two types of skills exist; The first kind, ``associated''
skills, are those skills which are <em>associated with a category of
experience</em>. The other kind of skill, ``miscellaneous'' skills,
are <em>not</em> related to any experience category.
<p>
The main difference between these two kinds of skills is in the
result of their use.
When associated skills are used <em>successfully</em> experience is
accrued in the experience category <em>associated with that skill</em>.
In contrast, the use of miscellaneous skills <em>never</em> gains
the player any experience regardless of the success in using it.
<p>
<em>Both</em> miscellaneous and associated skills can <em>fail</em>. This means
that the attempt to use the skill was unsuccessful. <em>Both</em>
miscellaneous and associated skills <em>can</em> have certain
primary stats <em>associated</em> with them. These associated stats can help
to determine if the use of a skill is successful and to what
<em>degree</em> it is successful.
<p>
All gained experience is modified by the associated
stats for that skill (table <a href="#table_skill_stats">skill statistics</a>) and then the
appropriate experience category automatically updated as needed.
<p>
<h3><a name="5.2.2">Restrictions on skills use and gaining experience</h3>
Neither a character's stats nor the character class restricts the
player from gaining experience in any of the experience
categories. Also, there are no inherent
restrictions on character skill use-any player may
use any <em>acquired</em> skill.
<p>
<center>
<table border=1 cellpadding=5><col align=center>
<a name="table_exp_stat_mod">
<tr><th>Average of associated stats</th>
<th>Experience gained multiplier</th>
<th>Average of associated stats</th>
<th>Experience gained multiplier</th></tr>
<!--#include file="statskmod.html"-->
</table>
How stats associated with a skill modify gained experience<p>
</center>
<p>
<h3><a name="5.2.3">Algorithm for Experience Gain under the skills system</h3>
<p>
Here we take the view that a player must 'overcome an opponent'
in order to gain experience. Examples include foes killed in combat,
finding/disarming a trap, stealing from some being, identifying
an object, etc.
<p>
Gained experience is based primarily on the difference in levels
between 'opponents', experience point value of a ``vanquished foe'',
the values of the associated stats of the skill being used and
two factors that are set internally <em>Note:</em> If you want to
know more about this, check out the skills_developers.doc.)
<p>
Below the algorithm for experience gain is given where player ``pl''
that has ``vanquished'' opponent ``op'' using skill ``sk'':<p>
<quote>
EXP GAIN = (EXP(op) + EXP(sk)) * lvl_mult * stat_mult<p>
</quote>
where EXP(sk) is a constant award based on the skill used,
EXP(op) is the base experience award for `op' which depends
on what op is (see below),
stat_mult is taken from table <a href="#table_exp_stat_mod">experience modification</a>,
and lvl_mult is:
<p>
For level(pl) < level(op):: <p>
<samp>
lvl_mult = FACTOR(sk) * (level(op) - level(pl))<p>
</samp>
For level(pl) = level(op):: <p>
<samp>
lvl_mult = FACTOR(sk)<p>
</samp>
For level(pl) > level(op):: <p>
<samp>
lvl_mult = (level(op)/level(pl)); <p>
</samp>
where level(op) is the level of `op', level(pl) is the level
of the player, and FACTOR(sk) is an internal factor based on
the skill used by pl.
<p>
There are three different cases for how EXP(op) can be computed:
<ol>
<li> <strong>op is a living creature</strong>: EXP(op) is just the base
experience award given in the <A href="../spoiler-html/spoiler.html">spoiler</a> .
<li><strong>op is a trap</strong>: EXP(op) = 1/(fraction of the time which the
trap is visible). Thus, traps which are highly <em>visible</em> get <em>lower</em>
values.
<li><strong>op is not a trap but is non-living</strong>: EXP(op) = internal
experience award of the item. Also, the lvl_mult is multiplied by
any <samp>magic</samp> enchantment on the item.
</ol>
<p>
<h2><a name="5.3.0">How skills are used</h2>
<centeR>
<a name="table_skill_cmd">
<table cellpadding=5 border=1>
<tr><td><samp>skills</samp></td><td> This command lists all the player's
current known skills, their level
of use and the associated experience
category of each skill. </td></tr>
<tr><td> <samp>ready_skill <skill></samp></td><td> This command changes
the player's current readied skill to
<samp><skill></samp>. </td></tr>
<tr><Td> <samp>use_skill <skill> <string></samp></td><td> This
command changes the player's current
readied skill <em>and</em> then executes it
in the facing direction of the player.
Similar in action to the <samp>invoke</samp>
command. </td></tr>
</table>
Skills commands<p>
</center>
Three player commands are related to skills use: <samp>ready_skill</samp>,
<samp>use_skill</samp>, and <Samp>skills</samp> (see table <a
href="#table_skill_cmd">skill commands</a>). Generally, a player will use a
skill by first readying the right one, with the <samp>ready_skill</samp>
command and then making a ranged ``attack'' to activate the skill; using
most skills is just like firing a wand or a bow. In a few cases however, a
skill is be used just by having it <em>readied</em>. For example, the
<samp>mountaineer</samp> skill allows favorable movement though hilly
terrain while it is readied.<p>
To change to a new skill, a player can use either the <samp>use_skill</samp>
or <samp>ready_skill</samp> commands, but note that the use of several
common items can automatically change the player's current skill too.
Examples of this include readying a bow (which will cause the code to make
the player's current skill <samp>missile_weapons</samp>) or readying a melee
weapon (current skill auto-matically becomes <samp>melee weapons</samp>).
Also, some player actions can cause a change in the current skill. Running
into a monster while you have a readied weapon in your inventory causes the
code to automatically make our current skill <samp>melee weapons</samp>. As
another example of this-casting a spell will cause the code to switch the
current skill to <samp>wizardry</samp> or <samp>praying</samp> (as
appropriate to the spell type).<p>
It is not possible to use more than one skill at a time.<p>
<h2><a name="5.4.0">Acquiring skills</h2>
Skills may be gained in two ways. In the first, new skills may
<em>learned</em>. This is done by reading a ``skill scroll'' and the
process is very similar to learning a spell. Just as in attempts to learn
incantations, success in learning skills is dependent on a random test based
on the learner's INT. Using your INT stat, look in the learn% column in
table <a href="chap2.html#table_pri_eff">primary stat effects</a> to find
your % chance of learning a skill. Once you hit 100%, you will always be
successfull in learning new skills. <p>
The acquisition of a <em>skill tool</em> will also allow the player to use
a new skill. An example of a skill tool is ``lockpicks''
<!--#include file="lockpicks.html"-->
(which allow the
player to pick door locks). The player merely applies the skill
tool in order to gain use of the new skill. If the tool is unapplied,
the player loses the use of the skill associated with the tool.
<p>
After a new skill is gained (either learned or if player has an applied
skill tool) it will appear on the player's skill roster (use the 'skills'
command to view its status). If the new skill is an associated skill, then
it will automatically be gained at the player's current level in the
appropriate experience category. For example, Stilco the Wraith, who is 5th
level in <samp>agility</samp>, buys a set of lockpicks and applies them. He
may now use the skill lockpicking at 5th level of ability since that is an
<samp>agility</samp> associated skill.
<p>
<a href="handbook.html"><img src="fig/book.gif">Back to table of contents</a><br>
<a href="chap4.html"><img src="fig/stairup.gif">Go to chapter 4</a><br>
<a href="chap6.html"><img src="fig/stairdown.gif">Go to chapter 6</a><br> |
import { ThumbsUp, Trash } from 'phosphor-react'
import { useState } from 'react';
import { Avatar } from '../Avatar'
import styles from './styles.module.scss'
interface Props {
content: string;
onDeleteComment: (comment: string) => void;
}
export function Comment({ content, onDeleteComment }: Props) {
const [likeCount, setLikeCount] = useState(0)
function handleDeleteComment() {
onDeleteComment(content);
}
function handleAddLike() {
setLikeCount((oldValue) => {
return oldValue + 1;
})
}
return (
<div className={styles.comment}>
<Avatar hasBorder={false} src="https://github.com/filipesaretta.png" />
<div className={styles.commentBox}>
<div className={styles.commentContent}>
<header>
<div className={styles.commentProfile}>
<strong>
Filipe Saretta
</strong>
<time title='09 jun de 2022 às 20:00' dateTime='2022-06-09 20:00'>Cerca de 1h atrás</time>
</div>
<button onClick={handleDeleteComment} title='Delete Comment'>
<Trash size={25} />
</button>
</header>
<p>{content}</p>
</div>
<footer>
<button onClick={handleAddLike}>
<ThumbsUp size={20} /> Apludir <span>{likeCount}</span>
</button>
</footer>
</div>
</div>
)
} |
import React, { useState, useEffect } from "react";
import GlobalStyles from "./components/GlobalStyles";
import ProfileContainer from "./components/ProfileContainer";
import SearchBar from "./components/SearchBar";
import { ToggleButton } from "./components/ToggleButton";
import fetchUserProfile from "./scripts/fetch";
function App() {
const [isDarkMode, setIsDarkMode] = useState(false);
const [userData, setUserData] = useState(null);
const [error, setError] = useState(null);
const [lastSearchedUser, setLastSearchedUser] = useState(null);
const toggleIsDarkMode = () => {
setIsDarkMode(!isDarkMode);
};
const handleSearch = async (searchString) => {
try {
const data = await fetchUserProfile(searchString);
setUserData(data);
setError(null);
localStorage.setItem("lastSearchedUser", searchString);
} catch (error) {
setError("No results");
}
};
const handleError = (errorMessage) => {
setError(errorMessage);
};
useEffect(() => {
const storedUser = localStorage.getItem("lastSearchedUser");
if (storedUser) {
setLastSearchedUser(storedUser);
} else {
setLastSearchedUser("octocat");
}
}, []);
useEffect(() => {
if (lastSearchedUser) {
handleSearch(lastSearchedUser);
}
}, [lastSearchedUser]);
return (
<div className="App">
<GlobalStyles isDarkMode={isDarkMode} />
<div className="AppHeader">
<h1 className="Title">gitlookup</h1>
<ToggleButton onClick={toggleIsDarkMode} isDarkMode={isDarkMode} />
</div>
<div className="SearchBar">
<SearchBar onSubmit={handleSearch} onError={handleError} isDarkMode={isDarkMode} />
</div>
<div className="ProfileContainer">
<ProfileContainer userData={userData} error={error} isDarkMode={isDarkMode} />
</div>
</div>
);
}
export default App; |
import paseo.*
import prendas.*
describe "test de una familia que NO pasea" {
//NOTA: Este fixture está incompleto y sirve para comenzar a testear el examen.
//Es a modo de ayuda, pero no es obligatorio respetar este escenario.
// Puede modificarse tanto como sea necesario.
var mediaIzquierda = new ElementoDePrenda(nivelDeDesgaste = 1) //elemento de par
var mediaDerecha = new ElementoDePrenda(nivelDeDesgaste = 3)
//prenda par, la media izquierda tiene que tener 1 de desgaste, la derecha 3, el abrigo es default 0
var mediasZoe = new PrendaPar(talle=s, elementoIzquierdo=mediaIzquierda, elementoDerecho=mediaDerecha, abrigo=0)
//prenda par, el izquierdo y derecho tiene los valores default (desgaste 0, abrigo 1)
var zapatillaIzquierda= new ElementoDePrenda()
var zapatillaDerecha= new ElementoDePrenda()
var zapatillasZoe = new PrendaPar(talle=s, elementoIzquierdo=zapatillaIzquierda, elementoDerecho=zapatillaDerecha)
//prenda pesada con 5 de abrigo
var jeanZoe = new RopaPesada(talle=s, abrigo=5)
//prenda liviana con desgaste default: 0
var remeraZoe = new RopaLiviana(talle=s)
// prenda pesada con desgaste default: 0
var camperaZoe = new RopaPesada(talle=s)
//un juguete para niños de 5 a 100 anios
var ukelele = new Juguete(edadMinima=5, edadMaxima=100)
//prenda liviana con un desgaste de 5
var remeraMilena = new RopaLiviana(talle=xs, desgaste=5) //prenda liviana
//prenda liviana con desgaste default: 0
var calzaMilena = new RopaLiviana(talle=xs) //prenda liviana
//prenda par, la ojota izquierda tiene que tener 1 de desgaste y 2 de abrigo, la ojota derecha tiene 3 de desgaste y 3 de abrigo
var ojotaDerecha= new ElementoDePrenda(nivelDeDesgaste=3, abrigo=3)
var ojotaIzquierda= new ElementoDePrenda(nivelDeDesgaste=1, abrigo=2)
var ojotasMilena = new PrendaPar(talle=l , elementoIzquierdo=ojotaIzquierda, elementoDerecho=ojotaDerecha)
//ninio
var zoe = new Ninio(talle=s, edad=11, prendas=#{mediasZoe, zapatillasZoe, jeanZoe, remeraZoe, camperaZoe })
//ninio problematico
var milena = new NinioProblematico(talle=xs, edad=2, prendas = #{remeraMilena, calzaMilena, ojotasMilena }, juguete=ukelele)
//familia
var familiaAptaSalir = new Familia(hijos = #{ zoe})
//familia
var familiaNoAptaParaSalir= new Familia(hijos = #{milena, zoe})
test "comodidad" {
assert.equals(6 , mediasZoe.nivelDeComodidad(zoe) )
assert.equals(8 , zapatillasZoe.nivelDeComodidad(zoe))
assert.equals(8 , jeanZoe.nivelDeComodidad(zoe))
assert.equals(10 , remeraZoe.nivelDeComodidad(zoe))
assert.equals(8 , camperaZoe.nivelDeComodidad(zoe))
assert.equals(7 , remeraMilena.nivelDeComodidad(milena))
assert.equals(10 , calzaMilena.nivelDeComodidad(milena))
assert.equals(-3 , ojotasMilena.nivelDeComodidad(milena))
}
//PUNTO 2
test "intercambiar pares ok" {
var mediaIzq = mediasZoe.elementoIzquierdo()
var mediaDer = mediasZoe.elementoDerecho()
var zapaIzq = zapatillasZoe.elementoIzquierdo()
var zapaDer = zapatillasZoe.elementoDerecho()
mediasZoe.intercambiar(zapatillasZoe)
assert.equals(mediaIzq, mediasZoe.elementoIzquierdo())
assert.equals(mediaDer, zapatillasZoe.elementoDerecho())
assert.equals(zapaIzq, zapatillasZoe.elementoIzquierdo())
assert.equals(zapaDer, mediasZoe.elementoDerecho())
}
test "intercambiar pares no ok" {
// //Que sucede si intercambio un par de talles distinto?
// //probar el cambio entre las ojotas de milena y las medias de zoe
// //El test está incompleto!
assert.throwsException({ojotasMilena.intercambiar(mediasZoe)})
}
//PUNTO 3
test "nivel de abrigo" {
assert.equals(2 , mediasZoe.nivelDeAbrigo())
assert.equals(2 , zapatillasZoe.nivelDeAbrigo())
assert.equals(5 , jeanZoe.nivelDeAbrigo() )
assert.equals(1 , remeraZoe.nivelDeAbrigo())
assert.equals(3 , camperaZoe.nivelDeAbrigo())
assert.equals(1 , remeraMilena.nivelDeAbrigo())
assert.equals(1 , calzaMilena.nivelDeAbrigo())
assert.equals(5 , ojotasMilena.nivelDeAbrigo())
}
//PUNTO 4
test "puede salir de paseo" {
assert.that(familiaAptaSalir.puedePasear())
assert.notThat(familiaNoAptaParaSalir.puedePasear())
}
//PUNTO 5
test "infaltables" {
assert.equals(#{jeanZoe,calzaMilena}, familiaNoAptaParaSalir.prendasInfantables())
}
test "chiquitos" {
assert.equals(#{milena}, familiaNoAptaParaSalir.chiquitos()
)
}
//PUNTO 6
test "salir de paseo ok" {
//como el test del punto 4 me da con una falla rompe test del punto 6 porque
//esta implementado que salte un error cuando una familia sale sin cumplir la
//condicion de que pueda salir
familiaAptaSalir.pasear()
assert.equals(1.8 , mediaIzquierda.nivelDeDesgaste())
assert.equals(4.2 , mediaDerecha.nivelDeDesgaste())
assert.equals(3 , mediasZoe.nivelDeDesgaste())
assert.equals(1 , zapatillasZoe.nivelDeDesgaste())
assert.equals(1 , jeanZoe.nivelDeDesgaste())
assert.equals(1 , remeraZoe.nivelDeDesgaste())
assert.equals(1 , camperaZoe.nivelDeDesgaste())
}
//PUNTO 7
test "salir de paseo no ok" {
// Que sucede si le pido pasear a una familia que no está lista?
// El test está incompleto!
assert.throwsException({familiaNoAptaParaSalir.pasear()})
}
} |
# Introduction to DL
Deep Learning is a subset of machine learning that focuses on training Artificial Neural Networks (ANNs) to solve a task at hand.
A very important quality of the ANN is that it can process raw data like pixels of an image and extract patterns from it. These patterns are treated as features to predict the outcomes.
ANN accepts image pixels as inputs, extract patterns like edges and curves and so on, and correlates these patterns to predict an outcome.
## Why do we need Deep Learning
1. ML needs us to specify features
2. DL extracts features from raw and complex data
3. Internal representation of data is built using extracted features (this may not be feasible manually!)
4. DL algorithms can make use of parallel computations (data is split into small batches and process parallelly)
5. This leads to scalability and performance
In short, Deep Learning complements machine learning algorithms for complex data for which features cannot be described easily.

## History of DL

## Types of DL


## Artificial Neural Networks (ANNs)
Artificial Neural Networks (ANNs) are inspired by the human brain. They are made up of interconnected nodes called as neurons.
In ANN, we assign weights to the connection between neurons. Weighted inputs are added up. If the sum crosses a specified threshold, the neuron is fired and the outputs of a layer of neuron become an input to an another layer.
ANN Building Blocks:
- **Layers**: input, hidden, output layers receive inputs, transform it, and produce outputx
- **Neurons**: computational units which accepts an input and produce an output
- **Weights**: determines the strength of connection between neurons (the connection could be between input and a neuron, or it could be between a neuron and another neuron)
- **Activation Function**: works on weighted sum of inputs to a neuron and produces an output
- **Bias**: additional input to a neuron that allows certain degree of flexibility
*Hidden layers in neural networks are crucial for character recognition because they enable the network to learn and extract complex features and patterns, such as edges, shapes, and curves, which are essential for recognizing characters.*
*A neuron in an Artificial Neural Network is the fundamental building block responsible for performing weighted summation and applying an activation function to input data to produce an output.*


## How are ANNs trained ?
During training, we show an image to the ANN. Let us say it is an image of digit 2. So we expect output neuron for digit 2 to fire. But in real, let us say output neuron of a digit 6 fired. So what do we do? We know that there is an error. So to correct an error, we adjust the weights of the connection between neurons based on a calculation, which we call as **Backpropagation Algorithm**. By showing thousands of images and adjusting the weights iteratively, ANN is able to predict correct outcome for most of the input images.
This process of adjusting weights through backpropagation is called as **model training**.
Backpropagation Algorithm:
1. Guess and compare
2. Measure the error
3. Adjust the guess
4. Update the weight |
import 'dart:async';
import 'dart:math';
import 'dart:ui';
import 'package:flame_audio/flame_audio.dart';
import 'package:get/get.dart';
import 'package:ysh/controllers/game_controller.dart';
import 'package:ysh/game/components/explosion.dart';
import 'package:ysh/game/components/playerBox.dart';
import 'package:ysh/game/maps/map.dart';
import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'package:flame_forge2d/flame_forge2d.dart' as forge;
import 'package:flutter/material.dart';
class BoxGame extends forge.Forge2DGame with HasTappables{
BoxGame({required this.level}):super(gravity: Vector2(0, 30));
int level;
late MapLevel map;
final random=Random();
PlayerBox? player;
GameController get controller=>Get.find<GameController>();
addPlayer(PlayerBox player)async{
this.player?.removeFromParent();
this.player=player;
await add(player);
}
@override
Color backgroundColor() {
return Colors.transparent;
}
@override
FutureOr<void> onLoad() async{
map=MapLevel(level: level);
await add(map);
camera.zoom=canvasSize.x/(32+5);
return super.onLoad();
}
@override
void update(double dt) {
super.update(dt);
}
applyExplosion(Vector2 position){
add(Explosion(position: position));
controller.playExplosionSFX();
player?.applyImpact(position);
}
@override
void onTapDown(int pointerId, TapDownInfo info) {
applyExplosion(info.eventPosition.game);
super.onTapDown(pointerId, info);
}
} |
# **Flask 2: Templates & Jinja**
[Download demo code](https://curric.springboard.com/software-engineering-career-track/default/lectures/flask-jinja-demo.zip)
## Goals
- Explain what HTML templates are, and why they are useful
- Use Jinja to create HTML templates for our Flask applications
- Debug our Flask applications more quickly by installing the Flask Debug Toolbar
- Serve static files (CSS, JS, etc) with Flask
## **Review**
### **Views**
Views are functions that return a **string** (a string of HTML)
### **Routes**
Routes define the URL that will run a view function.
They are declared by using *decorators*.
A route and view function:
```html
@app.route('/form')
def show_form():
"""Show greeting form."""
return """
<!DOCTYPE html>
<html>
<head>
<title>Hi There!</title>
</head>
<body>
<h1>Hi There!</h1>
<form action="/greet">
What's your name? <input name="person">
<button>Go!</button>
</form>
</body>
</html>
"""
```
This is kind of messy to read through (and we don’t get nice things like color-highlighting in editors). Much better to keep HTML in a separate file.
## **Templates**
### **How Can Templates Help?**
- Produce HTML
- Allows your responses to be dynamically created
- Can use variables passed from your views
- For loops, if/else statements
- Can inherit from other templates to minimize repetition
### **Jinja**
**Jinja** is a popular template system for Python, used by Flask.
There are many template systems for Python. Jinja is a particularly popular one. Django has its own template system, which served as an inspiration for Jinja.
### **Templates Directory**
Your templates directory lives under your project directory. Flask knows to look for them there.
```jsx
my-project-directory/
venv/
app.py
templates/
hello.html
```
### **Our Template**
*demo/templates/hello.html*
```html
<!DOCTYPE html>
<html>
<head>
<title>This is the hello page</title>
</head>
<body>
<h1>HELLO!</h1>
</body>
</html>
```
### **Rendering a Template**
```jsx
@app.route('/')
def index():
"""Return homepage."""
return render_template("hello.html")
```
Will find ***hello.html*** in ***templates/*** automatically.
## **Flask Debug Toolbar**
Ultra-useful add-on for Flask that shows, in browser, details about app.
Install add-on product:
```bash
(venv) $ pip3 install flask-debugtoolbar
```
Add the following to your Flask ***app.py:***
```jsx
from flask import Flask, request, render_template
from flask_debugtoolbar import DebugToolbarExtension
app = Flask(__name__)
app.config['SECRET_KEY'] = "oh-so-secret"
debug = DebugToolbarExtension(app)
... # rest of file continues
SECRET_KEY
```
<aside>
💡 **Note**: For now, that secret key doesn’t really have to be something secret (it’s fine to check this file into your GitHub, and you can use any string for the **SECRET_KEY.**
Later, when we talk about security & deployment, we’ll talk about when and how to actually keep this secret.
</aside>
### **Using The Toolbar**
***Request Vars:*** Explore what Flask got in request from browser
***HTTP Headers:*** Can be useful to explore all headers your browser sent
***Templates:*** What templates were used, and what was passed to them?
***Route List:*** What are all routes your app defines?
## **Dynamic Templates**
Jinja will replace things like ***{{ msg }}*** with value of ***msg*** passed when rendering:
*templates/lucky.html*
```html
<h1>Hi!</h1>
<p>Lucky number: {{ lucky_num }}</p>
```
*app.py*
```html
@app.route("/lucky")
def show_lucky_num():
"Example of simple dynamic template"
num = randint(1, 100)
return render_template("lucky.html",
lucky_num=num)
```
## **Example: Greeting**
Let’s make a form that gathers a user’s name.
On form submission, it should use that name & compliment the user.
### **Our Form**
*demo/templates/form.html*
```html
<!DOCTYPE html>
<html>
<body>
<h1>Hi There!</h1>
<form action="/greet">
<p>What's your name? <input name="person"></p>
<button>Go!</button>
</form>
</body>
</html>
```
### **Our Template**
*demo/templates/compliment.html*
```html
<!DOCTYPE html>
<html>
<body>
<p>Hi {{ name }}! You're so {{ compliment }}!</p>
</body>
</html>
```
### **Our Route**
```jsx
@app.route('/greet')
def offer_greeting():
"""Give player compliment."""
player = request.args["person"]
nice_thing = choice(COMPLIMENTS)
return render_template("compliment.html",
name=player,
compliment=nice_thing)
```
## **Example 2: Better Greeting!**
Let’s improve this:
- We’ll ask the user if they want compliments & only show if so
- We’ll show a list of *3* random compliments, like this:
```html
You're so:
<ul>
<li>clever</li>
<li>tenacious</li>
<li>smart</li>
</ul>
```
### **Our Form**
*demo/templates/form-2.html*
```html
<!DOCTYPE html>
<html>
<body>
<h1>Better Hi There!</h1>
<form action="/greet-2">
<p>What's your name? <input name="person"></p>
<p>Want compliments?
<input type="checkbox" name="wants_compliments">
</p>
<button>Go!</button>
</form>
</body>
</html>
```
### **Our Route**
```jsx
@app.route('/greet-2')
def offer_better_greeting():
"""Give player optional compliments."""
player = request.args["person"]
# if they didn't tick box, `wants_compliments` won't be
# in query args -- so let's use safe `.get()` method of
# dict-like things
wants = request.args.get("wants_compliments")
nice_things = sample(COMPLIMENTS, 3) if wants else []
return render_template("compliments.html",
compliments=nice_things,
name=player)
```
### **Conditionals in Jinja**
{% if CONDITION_EXPR %} ... {% endif %}
```html
{% if compliments %}
You're so:
...
{% endif %}
```
### **Loops in Jinja**
{% for VAR in ITERABLE %} ... {% endfor %}
```html
<ul>
{% for compliment in compliments %}
<li>{{ compliment }}</li>
{% endfor %}
</ul>
```
### **Our Template**
*demo/templates/compliments.html*
```html
<!DOCTYPE html>
<html>
<body>
<h1>Hi {{ name }}!</h1>
{% if compliments %}
<p>You're so:</p>
<ul>
{% for compliment in compliments %}
<li>{{ compliment }}</li>
{% endfor %}
</ul>
{% endif %}
</body>
</html>
```
## **Template Inheritance**
### **Motivation**
Different pages on the same site are often 95% the same.
### **Repetition is Boring**
Your templates have many things in common
```html
<!DOCTYPE html>
<html>
<head>
<title> TITLE GOES HERE </title>
<link rel="stylesheet" href="/static/css/styles.css">
<script src="http://unpkg.com/jquery"></script>
</head>
<body>
<h1>Our Site</h1>
BODY CONTENT GOES HERE
<footer>Copyright by Whiskey.</footer>
</body>
</html>
```
If you want the same stylesheet everywhere, you have to remember to include it in every template. If you forget in one template, that page won’t have your custom css that you spent so much time getting right. The same goes for scripts. If you want jquery everywhere, do you really want to have to remember to include it in the head in every template.
### **How to Use Template Inheritance**
- Make a that will hold all the repetitive stuff ***base.html***
- “Extend” that base template in your other pages
- Substitute blocks in your extended pages
### **Sample Base Template**
{% block BLOCKNAME %} ... {% endblock %}
*templates/base.html*
```html
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}TITLE GOES HERE{% endblock %}</title>
<link rel="stylesheet" href="/static/css/styles.css">
<script src="http://unpkg.com/jquery"></script>
</head>
<body>
<h1>Our Site</h1>
{% block content %}BODY CONTENT GOES HERE{% endblock %}
<footer>Copyright by Whiskey.</footer>
</body>
</html>
```
### **Page Using Template**
{% block BLOCKNAME %} ... {% endblock %}
*templates/my-page.html*
```html
{% extends 'base.html' %}
{% block title %}My awesome page title{% endblock %}
{% block content %}
<h2>I'm a header!</h2>
<p>I'm a paragraph!</p>
{% endblock %}
```
## **Where Other Project Files Go**
### **Do I Need Routes for CSS (or JS, etc)?**
```jsx
@app.route("my-css.css")
def my_css():
return """
b { color: red }
...
"""
```
No! That would be tedious — plus, everyone gets the *same C*SS.
### **Static Files: CSS and JS**
In ***static/*** directory:
```jsx
my-project-directory/
venv/
app.py
templates/
hello.html
static/
my-css.css
my-script.js
```
Find files like:
```jsx
<link rel="stylesheet" href="/static/my-css.css">
```
The static directory is where you put files that don’t change, unlike templates, which are parsed. The static directory can be divided in to the types of files that it contains: js for javascript, css for css files, img for images, etc., but that isn’t necessary. |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BarPlot = BarPlot;
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _web = require("@react-spring/web");
var _SeriesContextProvider = require("../context/SeriesContextProvider");
var _CartesianContextProvider = require("../context/CartesianContextProvider");
var _BarElement = require("./BarElement");
var _axis = require("../models/axis");
var _constants = require("../constants");
var _jsxRuntime = require("react/jsx-runtime");
const _excluded = ["skipAnimation"];
/**
* Solution of the equations
* W = barWidth * N + offset * (N-1)
* offset / (offset + barWidth) = r
* @param bandWidth The width available to place bars.
* @param numberOfGroups The number of bars to place in that space.
* @param gapRatio The ratio of the gap between bars over the bar width.
* @returns The bar width and the offset between bars.
*/
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function getBandSize({
bandWidth: W,
numberOfGroups: N,
gapRatio: r
}) {
if (r === 0) {
return {
barWidth: W / N,
offset: 0
};
}
const barWidth = W / (N + (N - 1) * r);
const offset = r * barWidth;
return {
barWidth,
offset
};
}
const useCompletedData = () => {
const seriesData = React.useContext(_SeriesContextProvider.SeriesContext).bar ?? {
series: {},
stackingGroups: [],
seriesOrder: []
};
const axisData = React.useContext(_CartesianContextProvider.CartesianContext);
const {
series,
stackingGroups
} = seriesData;
const {
xAxis,
yAxis,
xAxisIds,
yAxisIds
} = axisData;
const defaultXAxisId = xAxisIds[0];
const defaultYAxisId = yAxisIds[0];
const data = stackingGroups.flatMap(({
ids: groupIds
}, groupIndex) => {
return groupIds.flatMap(seriesId => {
const xAxisKey = series[seriesId].xAxisKey ?? defaultXAxisId;
const yAxisKey = series[seriesId].yAxisKey ?? defaultYAxisId;
const xAxisConfig = xAxis[xAxisKey];
const yAxisConfig = yAxis[yAxisKey];
const verticalLayout = series[seriesId].layout === 'vertical';
let baseScaleConfig;
if (verticalLayout) {
if (!(0, _axis.isBandScaleConfig)(xAxisConfig)) {
throw new Error(`MUI-X-Charts: ${xAxisKey === _constants.DEFAULT_X_AXIS_KEY ? 'The first `xAxis`' : `The x-axis with id "${xAxisKey}"`} shoud be of type "band" to display the bar series of id "${seriesId}"`);
}
if (xAxis[xAxisKey].data === undefined) {
throw new Error(`MUI-X-Charts: ${xAxisKey === _constants.DEFAULT_X_AXIS_KEY ? 'The first `xAxis`' : `The x-axis with id "${xAxisKey}"`} shoud have data property`);
}
baseScaleConfig = xAxisConfig;
} else {
if (!(0, _axis.isBandScaleConfig)(yAxisConfig)) {
throw new Error(`MUI-X-Charts: ${yAxisKey === _constants.DEFAULT_Y_AXIS_KEY ? 'The first `yAxis`' : `The y-axis with id "${yAxisKey}"`} shoud be of type "band" to display the bar series of id "${seriesId}"`);
}
if (yAxis[yAxisKey].data === undefined) {
throw new Error(`MUI-X-Charts: ${yAxisKey === _constants.DEFAULT_Y_AXIS_KEY ? 'The first `yAxis`' : `The y-axis with id "${yAxisKey}"`} shoud have data property`);
}
baseScaleConfig = yAxisConfig;
}
const xScale = xAxisConfig.scale;
const yScale = yAxisConfig.scale;
const bandWidth = baseScaleConfig.scale.bandwidth();
const {
barWidth,
offset
} = getBandSize({
bandWidth,
numberOfGroups: stackingGroups.length,
gapRatio: baseScaleConfig.barGapRatio
});
const barOffset = groupIndex * (barWidth + offset);
const {
stackedData,
color
} = series[seriesId];
return stackedData.map((values, dataIndex) => {
const bottom = Math.min(...values);
const top = Math.max(...values);
return {
bottom,
top,
seriesId,
dataIndex,
layout: series[seriesId].layout,
x: verticalLayout ? xScale(xAxis[xAxisKey].data?.[dataIndex]) + barOffset : xScale(bottom),
y: verticalLayout ? yScale(top) : yScale(yAxis[yAxisKey].data?.[dataIndex]) + barOffset,
xOrigin: xScale(0),
yOrigin: yScale(0),
height: verticalLayout ? Math.abs(yScale(bottom) - yScale(top)) : barWidth,
width: verticalLayout ? barWidth : Math.abs(xScale(bottom) - xScale(top)),
color,
highlightScope: series[seriesId].highlightScope
};
});
});
});
return data;
};
const getOutStyle = ({
layout,
yOrigin,
x,
width,
y,
xOrigin,
height
}) => (0, _extends2.default)({}, layout === 'vertical' ? {
y: yOrigin,
x,
height: 0,
width
} : {
y,
x: xOrigin,
height,
width: 0
});
const getInStyle = ({
x,
width,
y,
height
}) => ({
y,
x,
height,
width
});
/**
* Demos:
*
* - [Bars](https://mui.com/x/react-charts/bars/)
* - [Bar demonstration](https://mui.com/x/react-charts/bar-demo/)
* - [Stacking](https://mui.com/x/react-charts/stacking/)
*
* API:
*
* - [BarPlot API](https://mui.com/x/api/charts/bar-plot/)
*/
function BarPlot(props) {
const completedData = useCompletedData();
const {
skipAnimation
} = props,
other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
const transition = (0, _web.useTransition)(completedData, {
keys: bar => `${bar.seriesId}-${bar.dataIndex}`,
from: getOutStyle,
leave: getOutStyle,
enter: getInStyle,
update: getInStyle,
immediate: skipAnimation
});
return /*#__PURE__*/(0, _jsxRuntime.jsx)(React.Fragment, {
children: transition((style, {
seriesId,
dataIndex,
color,
highlightScope
}) => /*#__PURE__*/(0, _jsxRuntime.jsx)(_BarElement.BarElement, (0, _extends2.default)({
id: seriesId,
dataIndex: dataIndex,
highlightScope: highlightScope,
color: color
}, other, {
style: style
})))
});
}
process.env.NODE_ENV !== "production" ? BarPlot.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, animations are skiped.
* @default false
*/
skipAnimation: _propTypes.default.bool,
/**
* The props used for each component slot.
* @default {}
*/
slotProps: _propTypes.default.object,
/**
* Overridable component slots.
* @default {}
*/
slots: _propTypes.default.object
} : void 0; |
#include <bits/stdc++.h>
using namespace std;
int value(char c)
{
if (c == 'I')
return 1;
else if (c == 'V')
return 5;
else if (c == 'X')
return 10;
else if (c == 'L')
return 50;
else if (c == 'C')
return 100;
else if (c == 'D')
return 500;
else if (c == 'M')
return 1000;
else
return 0;
}
// T.C. : O(N)
int roman_to_number(string s)
{
int ans = 0;
int currVal = 0, prevVal = 0;
for (int i = s.length() - 1; i >= 0; i--)
{
currVal = value(s[i]);
if (prevVal > currVal)
{
ans -= currVal;
}
else
{
ans += currVal;
}
prevVal = currVal;
}
return ans;
}
// another approach using map
// T.C. :O(N);
int roman_to_number_using_map(string s)
{
map<char, int> mp;
mp.insert({'I', 1});
mp.insert({'V', 5});
mp.insert({'X', 10});
mp.insert({'L', 50});
mp.insert({'C', 100});
mp.insert({'D', 500});
mp.insert({'M', 1000});
int ans = 0;
for (int i = 0; i < s.length(); i++)
{
if (mp[s[i]] < mp[s[i + 1]])
{
ans += mp[s[i + 1]] - mp[s[i]];
i++;
}
else
{
ans += mp[s[i]];
}
}
return ans;
}
int main()
{
string s = "MCMXCIV";
cout << roman_to_number(s)<<endl;
cout << roman_to_number_using_map(s);
return 0;
} |
import React from "react";
import styled, { keyframes, DefaultTheme } from "styled-components";
import { MENU_HEIGHT } from "../config";
export interface Props {
secondary?: boolean;
isActive?: boolean;
theme: DefaultTheme;
}
export interface LabelProps {
isActive?: boolean;
}
const rainbowAnimation = keyframes`
0%,
100% {
background-position: 0 0;
}
50% {
background-position: 100% 0;
}
`;
const LinkLabel = styled.div<LabelProps>`
color: ${({ theme, isActive }) => (isActive ? theme.colors.primary : theme.colors.primaryBright)};
transition: color 0.4s;
flex-grow: 1;
`;
const MenuEntry = styled.a<Props>`
cursor: pointer;
display: flex;
align-items: center;
height: ${MENU_HEIGHT}px;
padding: ${({ secondary }) => (secondary ? "0 32px" : "0 16px")};
font-size: ${({ secondary }) => (secondary ? "14px" : "16px")};
background-color: ${({ isActive, theme }) => (isActive ? theme.colors.secondary : "transparent")};
color: ${({ theme }) => theme.colors.textSubtle};
// box-shadow: ${({ isActive, theme }) => (isActive ? `inset 4px 0px 0px ${theme.colors.primary}` : "none")};
border-radius: 8px;
a {
display: flex;
align-items: center;
width: 100%;
height: 100%;
}
// svg {
// fill: ${({ theme }) => theme.colors.textSubtle};
// }
&:hover {
background-color: ${({ isActive, theme }) => (isActive ? theme.colors.secondary : theme.colors.tertiary)};
}
// Safari fix
flex-shrink: 0;
&.rainbow {
background-clip: text;
animation: ${rainbowAnimation} 3s ease-in-out infinite;
background: ${({ theme }) => theme.colors.gradientBubblegum};
background-size: 400% 100%;
}
`;
MenuEntry.defaultProps = {
secondary: false,
isActive: false,
role: "button",
};
// const LinkLabelMemo = React.memo(LinkLabel, (prev, next) => prev.isPushed === next.isPushed);
export { MenuEntry, LinkLabel }; |
###############################################################################
# OpenVAS Vulnerability Test
#
# Apple QuickTime Multiple Arbitrary Code Execution Vulnerabilities (Windows)
#
# Authors:
# Veerendra GG <[email protected]>
#
# Copyright:
# Copyright (c) 2008 Greenbone Networks GmbH, http://www.greenbone.net
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2
# (or any later version), as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
###############################################################################
CPE = "cpe:/a:apple:quicktime";
if(description)
{
script_oid("1.3.6.1.4.1.25623.1.0.800102");
script_version("2020-03-04T09:29:37+0000");
script_tag(name:"last_modification", value:"2020-03-04 09:29:37 +0000 (Wed, 04 Mar 2020)");
script_tag(name:"creation_date", value:"2008-09-26 14:12:58 +0200 (Fri, 26 Sep 2008)");
script_tag(name:"cvss_base", value:"6.8");
script_tag(name:"cvss_base_vector", value:"AV:N/AC:M/Au:N/C:P/I:P/A:P");
script_cve_id("CVE-2008-1581", "CVE-2008-1582", "CVE-2008-1583",
"CVE-2008-1584", "CVE-2008-1585");
script_bugtraq_id(29619);
script_xref(name:"CB-A", value:"08-0094");
script_name("Apple QuickTime Multiple Arbitrary Code Execution Vulnerabilities (Windows)");
script_category(ACT_GATHER_INFO);
script_copyright("Copyright (C) 2008 Greenbone Networks GmbH");
script_family("General");
script_dependencies("secpod_apple_quicktime_detection_win_900124.nasl");
script_mandatory_keys("QuickTime/Win/Ver");
script_tag(name:"affected", value:"Apple QuickTime before 7.5 on Windows (Any).");
script_tag(name:"insight", value:"The flaws are due to,
- boundary error when parsing packed scanlines from a PixData
structure in a PICT file which can be exploited via specially crafted
PICT file.
- memory corruption issue in AAC-encoded media content can be
exploited via a specially crafted media file.
- error in the handling of PICT files or Indeo video codec content that
can be exploited via a specially crafted PICT file or movie file with
Indeo video codec content respectively.
- error in the handling of file URLs that can be exploited by making user
to play maliciously crafted QuickTime content.");
script_tag(name:"summary", value:"The host is installed with Apple QuickTime which is prone to
Multiple Arbitrary Code Execution Vulnerabilities.");
script_tag(name:"solution", value:"Upgrade to Apple QuickTime version 7.5 or later.");
script_tag(name:"impact", value:"Successful exploitation allows attackers to execute arbitrary
code or unexpected application termination.");
script_tag(name:"qod_type", value:"registry");
script_tag(name:"solution_type", value:"VendorFix");
script_xref(name:"URL", value:"http://support.apple.com/kb/HT1991");
script_xref(name:"URL", value:"http://secunia.com/advisories/29293");
script_xref(name:"URL", value:"http://www.nruns.com/security_advisory_quicktime_arbitrary_code_execution.php");
exit(0);
}
include("host_details.inc");
include("version_func.inc");
if(!infos = get_app_version_and_location(cpe:CPE, exit_no_version:TRUE))
exit(0);
vers = infos["version"];
path = infos["location"];
if(version_is_less(version:vers, test_version:"7.5")) {
report = report_fixed_ver(installed_version:vers, fixed_version:"7.5", install_path:path);
security_message(port:0, data:report);
exit(0);
}
exit(99); |
import { useMsal } from '@azure/msal-react'
import DashboardIcon from '@mui/icons-material/Dashboard'
import ExpandLess from '@mui/icons-material/ExpandLess'
import ExpandMore from '@mui/icons-material/ExpandMore'
import HomeIcon from '@mui/icons-material/Home'
import Collapse from '@mui/material/Collapse'
import List from '@mui/material/List'
import ListItemButton from '@mui/material/ListItemButton'
import ListItemIcon from '@mui/material/ListItemIcon'
import ListItemText from '@mui/material/ListItemText'
import React, { useLayoutEffect, useRef, useState } from 'react'
import { Link, NavLink, useLocation, useNavigate } from 'react-router-dom'
import logo from '../../../assets/img/supermicro.png'
import { useKBAuthentication } from '../../../context/KBAuthenticationContext'
import { authApi } from '../../../services/index'
import './sidebar.css'
const getProdSidebarItems = (roleScore) => {
let basicItems = [
{
name: 'Home',
href: '/',
icon: <HomeIcon className="text-white" />
}
]
if (roleScore >= 2) {
basicItems.push({
name: 'Dashboard',
href: '/dashboard',
icon: <DashboardIcon className="text-white" />,
children: [
{
name: 'Support Issue',
href: '/support-issues/edit',
icon: 'bx bxs-edit-alt'
},
{
name: 'SBOM',
href: '/dashboard/sbom',
icon: 'bx bx-search-alt'
},
{
name: 'Scan Issues',
href: '/dashboard/scan-issues',
icon: 'bx bx-search-alt'
}
// {
// name: 'Qemu',
// href: '/dashboard/qemu',
// icon: 'bx bx-terminal'
// }
]
})
}
if (roleScore >= 3) {
basicItems = basicItems.map((item) => {
if (item.name === 'Dashboard') {
item.children.push({
name: 'Admin',
href: '/dashboard',
icon: 'bx bxs-wrench'
})
}
return item
})
}
return basicItems
}
const getDevbSidebarItems = (roleScore) => {
let basicItems = [
{
name: 'Home',
href: '/',
icon: <HomeIcon className="text-white" />
}
]
if (roleScore >= 2) {
basicItems.push({
name: 'Dashboard',
href: '/dashboard',
icon: <DashboardIcon className="text-white" />,
children: [
{
name: 'Support Issue',
href: '/support-issues/edit',
icon: 'bx bxs-edit-alt'
},
{
name: 'SBOM Search',
href: '/dashboard/sbom',
icon: 'bx bx-search-alt'
},
{
name: 'Scan Issues',
href: '/dashboard/scan-issues',
icon: 'bx bx-scan'
},
{
name: 'Qemu',
href: '/dashboard/qemu',
icon: 'bx bx-terminal'
}
]
})
}
if (roleScore >= 3) {
basicItems = basicItems.map((item) => {
if (item.name === 'Dashboard') {
item.children.push({
name: 'Admin',
href: '/dashboard',
icon: 'bx bxs-wrench'
})
}
return item
})
}
return basicItems
}
/**
* The side bar items to show base on user role defined in array form.
* The basic should have:
* name: the name text will show at sidebar
* herf: the herf will apply to the link
* icon: the icon will show before the name text
* childern: if the link has childern, its sub links will defined here
* *notes: for multiple layers sideber (> 2), there may have logical error in the render function. Haven't test yet.
* @param {string} role the user role from KBAuthentication Context
* @returns
*/
const sidebaritems = (role) => {
let roleScore = 0
if (role === 'operator') roleScore = 2
else if (role === 'admin') roleScore = 3
if (!import.meta.env.PROD) {
return getDevbSidebarItems(roleScore)
} else return getProdSidebarItems(roleScore)
}
/**
* The SibeBar component
* @returns
*/
const SideBar = () => {
const { dispatch, role } = useKBAuthentication()
const location = useLocation()
const navigate = useNavigate()
const collapseRef = useRef(true)
const { instance } = useMsal()
const storedStatus = JSON.parse(sessionStorage.getItem('menuCollapseStatus')) || {}
const [itemCollapseStatus, setCollapse] = useState(storedStatus)
const sidebarCollapse = () => {
if (collapseRef.current) {
document.getElementById('main').style.marginLeft = '50px'
document.getElementById('kb-sidebar').classList.toggle('collapse')
document.getElementById('collapse-btn').classList.toggle('close')
window.localStorage.setItem('sidebar-collapse', 'true')
} else {
document.getElementById('main').style.marginLeft = '210px'
document.getElementById('kb-sidebar').classList.toggle('collapse')
document.getElementById('collapse-btn').classList.toggle('close')
window.localStorage.setItem('sidebar-collapse', 'false')
}
collapseRef.current = !collapseRef.current
}
const Logout = async () => {
window.sessionStorage.removeItem('userInfo')
try {
await authApi.logout()
if (import.meta.env.PROD) instance.logoutRedirect()
dispatch({ type: 'LOGOUT' })
window.sessionStorage.removeItem('userInfo')
} catch (e) {
console.log('has log out error', e)
}
// navigate('/logout');
}
const handleMenuClick = (href, collapseIndex) => {
if (collapseIndex) {
const newStatus = { ...itemCollapseStatus, [collapseIndex]: !itemCollapseStatus[collapseIndex] }
sessionStorage.setItem('menuCollapseStatus', JSON.stringify(newStatus))
setCollapse(newStatus)
}
if (href) {
if (href === location.pathname) navigate(0)
else navigate(href)
}
}
const renderSideBarItem = () =>
sidebaritems(role).map((item, index) => {
if (item.children?.length > 0) {
return (
<div key={index + item.name + 'list'}>
<ListItemButton
onClick={() => {
if (!collapseRef.current) sidebarCollapse()
handleMenuClick(null, item.name)
}}
sx={{
':hover': {
bgcolor: 'white',
color: 'black'
}
}}
>
<i className="bx bx-desktop pl-1 pr-6" />
<ListItemText primary={item.name} />
{itemCollapseStatus[item.name] ? <ExpandLess /> : <ExpandMore />}
</ListItemButton>
<Collapse in={itemCollapseStatus[item.name]} timeout="auto" unmountOnExit>
<List
className=" text-white"
component="nav"
sx={{
paddingLeft: 3
}}
>
{item.children.map((child) => {
return (
<ListItemButton
key={child.name}
onClick={() => handleMenuClick(child.href)}
className="sidebar-item w-full text-left"
sx={{
'&:hover': {
bgcolor: 'white'
}
}}
>
<i className={child.icon} />
<ListItemText primary={child.name} />
</ListItemButton>
)
})}
</List>
</Collapse>
</div>
)
}
if (item.name === 'Home') {
return (
<NavLink
key={item.name + 'list'}
to={item.href}
className=""
onClick={() => handleMenuClick(item.href)}
>
<div className="sidebar-item w-full text-left">
<i className="bx bxs-home" />
Home
</div>
</NavLink>
)
}
return (
<ListItemButton key={item.name + 'list'} onClick={() => handleMenuClick(item.href)}>
<ListItemIcon>{item.icon}</ListItemIcon>
<ListItemText primary={item.name} />
</ListItemButton>
)
})
useLayoutEffect(() => {
if (window.localStorage.getItem('sidebar-collapse') === 'true') {
document.getElementById('main').style.marginLeft = '50px'
document.getElementById('kb-sidebar').classList.add('collapse')
document.getElementById('collapse-btn').classList.add('close')
collapseRef.current = false
}
}, [])
const [dark, setDark] = useState(false)
function toggleTheme() {
setDark((prev) => !prev)
document.getElementById('root').classList.toggle('dark')
}
return (
<div id="kb-sidebar" className="sidebar">
<button id="collapse-btn" className="collapse-btn" onClick={sidebarCollapse}>
<i className="bx bx-arrow-to-left bx-sm" />
</button>
<div className="relative mb-8 flex items-center text-xs">
<img src={logo} alt="supermicro" className="ml-[50px] max-w-[80px]" />
<span name="logo-name" className="ml-2 whitespace-nowrap text-lg text-white">
SSKB
</span>
</div>
<div className="sidebar-items h-[85%]">
<Link to="/" className="sidebar-item cursor-pointer">
<div className="w-full text-left">
<i className="bx bxs-home" />
Home
</div>
</Link>
<Link to="/support-issue" className="sidebar-item cursor-pointer">
<div className="w-full text-left">
<i className="bx bxs-edit-alt" />
Support Issue
</div>
</Link>
<Link to="/system-sbom" className="sidebar-item cursor-pointer">
<div className="w-full text-left">
<i className="bx bxs-search" />
System SBOM
</div>
</Link>
<Link to="/third-party-package " className="sidebar-item cursor-pointer">
<div className="w-full text-left">
<i className="bx bxs-search" />
Third Party Package
</div>
</Link>
{/* <List component="nav" className="uppercase text-white">
{renderSideBarItem()}
</List> */}
<div className="w-full flex-auto text-white"></div>
{['admin', 'operator'].includes(role) && (
<Link to="/dashboard" className="sidebar-item cursor-pointer">
<div className="w-full text-left">
<i className="bx bxs-wrench" />
Dashboard
</div>
</Link>
)}
<Link to="/profile" className="sidebar-item cursor-pointer">
<div className=" w-full text-left">
<i className="bx bxs-user" />
Profile
</div>
</Link>
<Link to="/report" className="sidebar-item cursor-pointer">
<div className="w-full text-left">
<i className="bx bxs-message-rounded-error" />
Report
</div>
</Link>
{/* {!import.meta.env.PROD && (
<div className="sidebar-item cursor-pointer">
<button className=" w-full text-left" onClick={toggleTheme}>
{dark ? (
<>
<i className="bx bx-sun" />
<span>Dark Theme</span>
</>
) : (
<>
<i className="bx bxs-sun" />
<span>Light Theme</span>
</>
)}
</button>
</div>
)} */}
<div className="sidebar-item">
<button type="button" onClick={Logout} className="w-full text-left">
<i className="bx bx-log-out" />
Logout
</button>
</div>
</div>
</div>
)
}
export default SideBar |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.server;
import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
import static com.android.internal.os.BinderCallsStats.SettingsObserver.SETTINGS_COLLECT_LATENCY_DATA_KEY;
import static com.android.internal.os.BinderCallsStats.SettingsObserver.SETTINGS_DETAILED_TRACKING_KEY;
import static com.android.internal.os.BinderCallsStats.SettingsObserver.SETTINGS_ENABLED_KEY;
import static com.android.internal.os.BinderCallsStats.SettingsObserver.SETTINGS_IGNORE_BATTERY_STATUS_KEY;
import static com.android.internal.os.BinderCallsStats.SettingsObserver.SETTINGS_MAX_CALL_STATS_KEY;
import static com.android.internal.os.BinderCallsStats.SettingsObserver.SETTINGS_SAMPLING_INTERVAL_KEY;
import static com.android.internal.os.BinderCallsStats.SettingsObserver.SETTINGS_SHARDING_MODULO_KEY;
import static com.android.internal.os.BinderCallsStats.SettingsObserver.SETTINGS_TRACK_DIRECT_CALLING_UID_KEY;
import static com.android.internal.os.BinderCallsStats.SettingsObserver.SETTINGS_TRACK_SCREEN_INTERACTIVE_KEY;
import android.app.ActivityThread;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.BatteryStatsInternal;
import android.os.Binder;
import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.os.ShellCommand;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.provider.Settings;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.KeyValueListParser;
import android.util.Slog;
import com.android.internal.os.AppIdToPackageMap;
import com.android.internal.os.BackgroundThread;
import com.android.internal.os.BinderCallsStats;
import com.android.internal.os.BinderInternal;
import com.android.internal.os.CachedDeviceState;
import com.android.internal.util.DumpUtils;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class BinderCallsStatsService extends Binder {
private static final String TAG = "BinderCallsStatsService";
private static final String SERVICE_NAME = "binder_calls_stats";
private static final String PERSIST_SYS_BINDER_CALLS_DETAILED_TRACKING
= "persist.sys.binder_calls_detailed_tracking";
/** Resolves the work source of an incoming binder transaction. */
static class AuthorizedWorkSourceProvider implements BinderInternal.WorkSourceProvider {
private ArraySet<Integer> mAppIdTrustlist;
AuthorizedWorkSourceProvider() {
mAppIdTrustlist = new ArraySet<>();
}
public int resolveWorkSourceUid(int untrustedWorkSourceUid) {
final int callingUid = getCallingUid();
final int appId = UserHandle.getAppId(callingUid);
if (mAppIdTrustlist.contains(appId)) {
final int workSource = untrustedWorkSourceUid;
final boolean isWorkSourceSet = workSource != Binder.UNSET_WORKSOURCE;
return isWorkSourceSet ? workSource : callingUid;
}
return callingUid;
}
public void systemReady(Context context) {
mAppIdTrustlist = createAppidTrustlist(context);
}
public void dump(PrintWriter pw, AppIdToPackageMap packageMap) {
pw.println("AppIds of apps that can set the work source:");
final ArraySet<Integer> trustlist = mAppIdTrustlist;
for (Integer appId : trustlist) {
pw.println("\t- " + packageMap.mapAppId(appId));
}
}
protected int getCallingUid() {
return Binder.getCallingUid();
}
private ArraySet<Integer> createAppidTrustlist(Context context) {
// Use a local copy instead of mAppIdTrustlist to prevent concurrent read access.
final ArraySet<Integer> trustlist = new ArraySet<>();
// We trust our own process.
trustlist.add(UserHandle.getAppId(Process.myUid()));
// We only need to initialize it once. UPDATE_DEVICE_STATS is a system permission.
final PackageManager pm = context.getPackageManager();
final String[] permissions = { android.Manifest.permission.UPDATE_DEVICE_STATS };
final int queryFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
final List<PackageInfo> packages =
pm.getPackagesHoldingPermissions(permissions, queryFlags);
final int packagesSize = packages.size();
for (int i = 0; i < packagesSize; i++) {
final PackageInfo pkgInfo = packages.get(i);
try {
final int uid = pm.getPackageUid(pkgInfo.packageName, queryFlags);
final int appId = UserHandle.getAppId(uid);
trustlist.add(appId);
} catch (NameNotFoundException e) {
Slog.e(TAG, "Cannot find uid for package name " + pkgInfo.packageName, e);
}
}
return trustlist;
}
}
/** Listens for flag changes. */
private static class SettingsObserver extends ContentObserver {
private boolean mEnabled;
private final Uri mUri = Settings.Global.getUriFor(Settings.Global.BINDER_CALLS_STATS);
private final Context mContext;
private final KeyValueListParser mParser = new KeyValueListParser(',');
private final BinderCallsStats mBinderCallsStats;
private final AuthorizedWorkSourceProvider mWorkSourceProvider;
SettingsObserver(Context context, BinderCallsStats binderCallsStats,
AuthorizedWorkSourceProvider workSourceProvider) {
super(BackgroundThread.getHandler());
mContext = context;
context.getContentResolver().registerContentObserver(mUri, false, this,
UserHandle.USER_SYSTEM);
mBinderCallsStats = binderCallsStats;
mWorkSourceProvider = workSourceProvider;
// Always kick once to ensure that we match current state
onChange();
}
@Override
public void onChange(boolean selfChange, Uri uri, int userId) {
if (mUri.equals(uri)) {
onChange();
}
}
public void onChange() {
// Do not overwrite the default set manually.
if (!SystemProperties.get(PERSIST_SYS_BINDER_CALLS_DETAILED_TRACKING).isEmpty()) {
return;
}
try {
mParser.setString(Settings.Global.getString(mContext.getContentResolver(),
Settings.Global.BINDER_CALLS_STATS));
} catch (IllegalArgumentException e) {
Slog.e(TAG, "Bad binder call stats settings", e);
}
mBinderCallsStats.setDetailedTracking(mParser.getBoolean(
SETTINGS_DETAILED_TRACKING_KEY, BinderCallsStats.DETAILED_TRACKING_DEFAULT));
mBinderCallsStats.setSamplingInterval(mParser.getInt(
SETTINGS_SAMPLING_INTERVAL_KEY,
BinderCallsStats.PERIODIC_SAMPLING_INTERVAL_DEFAULT));
mBinderCallsStats.setMaxBinderCallStats(mParser.getInt(
SETTINGS_MAX_CALL_STATS_KEY,
BinderCallsStats.MAX_BINDER_CALL_STATS_COUNT_DEFAULT));
mBinderCallsStats.setTrackScreenInteractive(
mParser.getBoolean(SETTINGS_TRACK_SCREEN_INTERACTIVE_KEY,
BinderCallsStats.DEFAULT_TRACK_SCREEN_INTERACTIVE));
mBinderCallsStats.setTrackDirectCallerUid(
mParser.getBoolean(SETTINGS_TRACK_DIRECT_CALLING_UID_KEY,
BinderCallsStats.DEFAULT_TRACK_DIRECT_CALLING_UID));
mBinderCallsStats.setIgnoreBatteryStatus(
mParser.getBoolean(SETTINGS_IGNORE_BATTERY_STATUS_KEY,
BinderCallsStats.DEFAULT_IGNORE_BATTERY_STATUS));
mBinderCallsStats.setShardingModulo(mParser.getInt(
SETTINGS_SHARDING_MODULO_KEY,
BinderCallsStats.SHARDING_MODULO_DEFAULT));
mBinderCallsStats.setCollectLatencyData(
mParser.getBoolean(SETTINGS_COLLECT_LATENCY_DATA_KEY,
BinderCallsStats.DEFAULT_COLLECT_LATENCY_DATA));
// Binder latency observer settings.
BinderCallsStats.SettingsObserver.configureLatencyObserver(
mParser,
mBinderCallsStats.getLatencyObserver());
final boolean enabled =
mParser.getBoolean(SETTINGS_ENABLED_KEY, BinderCallsStats.ENABLED_DEFAULT);
if (mEnabled != enabled) {
if (enabled) {
Binder.setObserver(mBinderCallsStats);
Binder.setProxyTransactListener(
new Binder.PropagateWorkSourceTransactListener());
Binder.setWorkSourceProvider(mWorkSourceProvider);
} else {
Binder.setObserver(null);
Binder.setProxyTransactListener(null);
Binder.setWorkSourceProvider((x) -> Binder.getCallingUid());
}
mEnabled = enabled;
mBinderCallsStats.reset();
mBinderCallsStats.setAddDebugEntries(enabled);
mBinderCallsStats.getLatencyObserver().reset();
}
}
}
/**
* @hide Only for use within the system server.
*/
public static class Internal {
private final BinderCallsStats mBinderCallsStats;
Internal(BinderCallsStats binderCallsStats) {
this.mBinderCallsStats = binderCallsStats;
}
/** @see BinderCallsStats#reset */
public void reset() {
mBinderCallsStats.reset();
}
/**
* @see BinderCallsStats#getExportedCallStats.
*
* Note that binder calls stats will be reset by statsd every time
* the data is exported.
*/
public ArrayList<BinderCallsStats.ExportedCallStat> getExportedCallStats() {
return mBinderCallsStats.getExportedCallStats();
}
/** @see BinderCallsStats#getExportedExceptionStats */
public ArrayMap<String, Integer> getExportedExceptionStats() {
return mBinderCallsStats.getExportedExceptionStats();
}
}
public static class LifeCycle extends SystemService {
private BinderCallsStatsService mService;
private BinderCallsStats mBinderCallsStats;
private AuthorizedWorkSourceProvider mWorkSourceProvider;
public LifeCycle(Context context) {
super(context);
}
@Override
public void onStart() {
mBinderCallsStats = new BinderCallsStats(new BinderCallsStats.Injector());
mWorkSourceProvider = new AuthorizedWorkSourceProvider();
mService = new BinderCallsStatsService(
mBinderCallsStats, mWorkSourceProvider);
publishLocalService(Internal.class, new Internal(mBinderCallsStats));
publishBinderService(SERVICE_NAME, mService);
boolean detailedTrackingEnabled = SystemProperties.getBoolean(
PERSIST_SYS_BINDER_CALLS_DETAILED_TRACKING, false);
if (detailedTrackingEnabled) {
Slog.i(TAG, "Enabled CPU usage tracking for binder calls. Controlled by "
+ PERSIST_SYS_BINDER_CALLS_DETAILED_TRACKING
+ " or via dumpsys binder_calls_stats --enable-detailed-tracking");
mBinderCallsStats.setDetailedTracking(true);
}
}
@Override
public void onBootPhase(int phase) {
if (SystemService.PHASE_SYSTEM_SERVICES_READY == phase) {
CachedDeviceState.Readonly deviceState = getLocalService(
CachedDeviceState.Readonly.class);
mBinderCallsStats.setDeviceState(deviceState);
BatteryStatsInternal batteryStatsInternal = getLocalService(
BatteryStatsInternal.class);
mBinderCallsStats.setCallStatsObserver(new BinderInternal.CallStatsObserver() {
@Override
public void noteCallStats(int workSourceUid, long incrementalCallCount,
Collection<BinderCallsStats.CallStat> callStats) {
batteryStatsInternal.noteBinderCallStats(workSourceUid,
incrementalCallCount, callStats);
}
@Override
public void noteBinderThreadNativeIds(int[] binderThreadNativeTids) {
batteryStatsInternal.noteBinderThreadNativeIds(binderThreadNativeTids);
}
});
// It needs to be called before mService.systemReady to make sure the observer is
// initialized before installing it.
mWorkSourceProvider.systemReady(getContext());
mService.systemReady(getContext());
}
}
}
private SettingsObserver mSettingsObserver;
private final BinderCallsStats mBinderCallsStats;
private final AuthorizedWorkSourceProvider mWorkSourceProvider;
BinderCallsStatsService(BinderCallsStats binderCallsStats,
AuthorizedWorkSourceProvider workSourceProvider) {
mBinderCallsStats = binderCallsStats;
mWorkSourceProvider = workSourceProvider;
}
public void systemReady(Context context) {
mSettingsObserver = new SettingsObserver(context, mBinderCallsStats, mWorkSourceProvider);
}
public void reset() {
Slog.i(TAG, "Resetting stats");
mBinderCallsStats.reset();
}
@Override
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
if (!DumpUtils.checkDumpAndUsageStatsPermission(ActivityThread.currentApplication(),
SERVICE_NAME, pw)) {
return;
}
boolean verbose = false;
int worksourceUid = Process.INVALID_UID;
if (args != null) {
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if ("-a".equals(arg)) {
verbose = true;
} else if ("-h".equals(arg)) {
pw.println("dumpsys binder_calls_stats options:");
pw.println(" -a: Verbose");
pw.println(" --work-source-uid <UID>: Dump binder calls from the UID");
return;
} else if ("--work-source-uid".equals(arg)) {
i++;
if (i >= args.length) {
throw new IllegalArgumentException(
"Argument expected after \"" + arg + "\"");
}
String uidArg = args[i];
try {
worksourceUid = Integer.parseInt(uidArg);
} catch (NumberFormatException e) {
pw.println("Invalid UID: " + uidArg);
return;
}
}
}
if (args.length > 0 && worksourceUid == Process.INVALID_UID) {
// For compatibility, support "cmd"-style commands when passed to "dumpsys".
BinderCallsStatsShellCommand command = new BinderCallsStatsShellCommand(pw);
int status = command.exec(this, null, FileDescriptor.out, FileDescriptor.err, args);
if (status == 0) {
return;
}
}
}
mBinderCallsStats.dump(pw, AppIdToPackageMap.getSnapshot(), worksourceUid, verbose);
}
@Override
public int handleShellCommand(ParcelFileDescriptor in, ParcelFileDescriptor out,
ParcelFileDescriptor err, String[] args) {
ShellCommand command = new BinderCallsStatsShellCommand(null);
int status = command.exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
err.getFileDescriptor(), args);
if (status != 0) {
command.onHelp();
}
return status;
}
private class BinderCallsStatsShellCommand extends ShellCommand {
private final PrintWriter mPrintWriter;
BinderCallsStatsShellCommand(PrintWriter printWriter) {
mPrintWriter = printWriter;
}
@Override
public PrintWriter getOutPrintWriter() {
if (mPrintWriter != null) {
return mPrintWriter;
}
return super.getOutPrintWriter();
}
@Override
public int onCommand(String cmd) {
PrintWriter pw = getOutPrintWriter();
if (cmd == null) {
return -1;
}
switch (cmd) {
case "--reset":
reset();
pw.println("binder_calls_stats reset.");
break;
case "--enable":
Binder.setObserver(mBinderCallsStats);
break;
case "--disable":
Binder.setObserver(null);
break;
case "--no-sampling":
mBinderCallsStats.setSamplingInterval(1);
break;
case "--enable-detailed-tracking":
SystemProperties.set(PERSIST_SYS_BINDER_CALLS_DETAILED_TRACKING, "1");
mBinderCallsStats.setDetailedTracking(true);
pw.println("Detailed tracking enabled");
break;
case "--disable-detailed-tracking":
SystemProperties.set(PERSIST_SYS_BINDER_CALLS_DETAILED_TRACKING, "");
mBinderCallsStats.setDetailedTracking(false);
pw.println("Detailed tracking disabled");
break;
case "--dump-worksource-provider":
mBinderCallsStats.setDetailedTracking(true);
mWorkSourceProvider.dump(pw, AppIdToPackageMap.getSnapshot());
break;
case "--work-source-uid":
String uidArg = getNextArgRequired();
try {
int uid = Integer.parseInt(uidArg);
mBinderCallsStats.recordAllCallsForWorkSourceUid(uid);
} catch (NumberFormatException e) {
pw.println("Invalid UID: " + uidArg);
return -1;
}
break;
default:
return handleDefaultCommands(cmd);
}
return 0;
}
@Override
public void onHelp() {
PrintWriter pw = getOutPrintWriter();
pw.println("binder_calls_stats commands:");
pw.println(" --reset: Reset stats");
pw.println(" --enable: Enable tracking binder calls");
pw.println(" --disable: Disables tracking binder calls");
pw.println(" --no-sampling: Tracks all calls");
pw.println(" --enable-detailed-tracking: Enables detailed tracking");
pw.println(" --disable-detailed-tracking: Disables detailed tracking");
pw.println(" --work-source-uid <UID>: Track all binder calls from the UID");
}
}
} |
import React, { useState } from 'react';
import Image from 'next/image';
import Icon, { EIconColor, EIconName } from 'components/Icon';
import Button from 'components/Button';
import Amount from 'components/Amount';
import Checkbox from 'components/Checkbox';
import ModalConfirm from 'components/ModalConfirm';
import { TCartProductsProps } from './CartProducts.types';
const CartProducts: React.FC<TCartProductsProps> = ({ onNext }) => {
const [deleteCartModalState, setDeleteCartModalState] = useState<{
visible: boolean;
}>({ visible: false });
const handleOpenDeleteCartModal = (): void => {
setDeleteCartModalState({ visible: true });
};
const handleCloseDeleteCartModal = (): void => {
setDeleteCartModalState({ visible: false });
};
const handleSubmit = (): void => {
onNext?.();
};
return (
<div className="CartProducts">
<div className="CartProducts-wrapper">
<h3 className="CartPage-title">GIỎ HÀNG CỦA BẠN</h3>
<div className="CartProducts-main-wrapper">
<div className="CartProducts-group">
<div className="CartProducts-group-body d-flex align-items-center">
<div className="CartProducts-group-body-item tick">
<Checkbox />
</div>
<div className="CartProducts-group-body-item information">
<div className="CartProducts-group-text">
Tất cả (Có 6 sản phẩm)
</div>
</div>
<div className="CartProducts-group-body-item price">
<div className="CartProducts-group-text text-center">
Đơn giá
</div>
</div>
<div className="CartProducts-group-body-item amount d-flex justify-content-center">
<div className="CartProducts-group-text text-center">
Số lượng
</div>
</div>
<div className="CartProducts-group-body-item total">
<div className="CartProducts-group-text text-center">
Thành tiền
</div>
</div>
<div className="CartProducts-group-body-item action d-flex justify-content-center">
<Icon
name={EIconName.TrashShopdi}
onClick={handleOpenDeleteCartModal}
/>
</div>
</div>
</div>
<div className="CartProducts-group">
<div className="CartProducts-group-header d-flex align-items-center">
<div className="CartProducts-group-body-item tick">
<Checkbox />
</div>
<div className="CartProducts-group-body-item shop">
<div className="CartProducts-group-title">
Cửa hàng sản phẩm công nghệ ABC
</div>
<div className="CartProducts-group-text">Có 3 sản phẩm</div>
</div>
<div className="CartProducts-group-body-item arrow">
<Icon
name={EIconName.AngleRight}
color={EIconColor.SILVER_CHALICE}
/>
</div>
</div>
{[1, 2, 3, 4].map((item) => (
<div
key={item}
className="CartProducts-group-body d-flex align-items-center"
>
<div className="CartProducts-group-body-item tick">
<Checkbox />
</div>
<div className="CartProducts-group-body-item information">
<div className="CartProducts-group-information d-flex align-items-center">
<div className="CartProducts-group-information-image">
<Image
src="/img/image-product.png"
layout="fill"
objectFit="cover"
/>
</div>
<div className="CartProducts-information-info">
<div className="CartProducts-group-text">
Louis Vuitton
</div>
<div className="CartProducts-group-subtitle">
Đồng hồ Tambour Slim Bloom ULess dsadsad
</div>
</div>
</div>
</div>
<div className="CartProducts-group-body-item price">
<div className="CartProducts-group-text">
<del>186.040.000 đ</del>
</div>
<div className="CartProducts-group-title">
<strong>146.040.000 đ</strong>
</div>
</div>
<div className="CartProducts-group-body-item amount d-flex justify-content-center">
<div className="CartProducts-group-text text-center">
<Amount min={1} />
</div>
</div>
<div className="CartProducts-group-body-item total">
<div className="CartProducts-group-title">
<strong>146.040.000 đ</strong>
</div>
</div>
<div className="CartProducts-group-body-item action d-flex justify-content-center">
<Icon
name={EIconName.TrashShopdi}
onClick={handleOpenDeleteCartModal}
/>
</div>
</div>
))}
</div>
</div>
<div className="CartProducts-submit d-flex justify-content-end">
<Button
primary
title="Mua hàng"
size="large"
onClick={handleSubmit}
/>
</div>
</div>
<ModalConfirm
{...deleteCartModalState}
title="XÁC NHẬN XÓA"
description="Bạn có chắc chắn muốn xóa 01 sản phẩm trong giỏ hàng?"
iconName={EIconName.TrashShopdi}
onClose={handleCloseDeleteCartModal}
/>
</div>
);
};
export default CartProducts; |
//
// Copyright (C) 2017 - Statoil ASA
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
#pragma once
#include "RimCheckableObject.h"
#include "cafAppEnum.h"
#include "cafPdmChildArrayField.h"
#include "cafPdmChildField.h"
#include "cafPdmField.h"
// Include to make Pdm work for cvf::Color
#include "cafPdmFieldCvfColor.h"
namespace caf
{
class PdmOptionItemInfo;
}
class RimRegularLegendConfig;
class RimFractureTemplateCollection;
///
///
class RimStimPlanColors : public RimCheckableObject
{
CAF_PDM_HEADER_INIT;
public:
enum StimPlanResultColorType
{
COLOR_INTERPOLATION,
SINGLE_ELEMENT_COLOR
};
public:
RimStimPlanColors();
~RimStimPlanColors() override;
RimRegularLegendConfig* activeLegend() const;
QString uiResultName() const;
void setDefaultResultName();
QString unit() const;
cvf::Color3f defaultColor() const;
bool showStimPlanMesh() const { return m_showStimPlanMesh; }
void setShowStimPlanMesh( bool showStimPlanMesh );
void loadDataAndUpdate();
void updateLegendData();
void updateStimPlanTemplates() const;
StimPlanResultColorType stimPlanResultColorType() const { return m_stimPlanCellVizMode(); };
void updateConductivityResultName();
protected:
QList<caf::PdmOptionItemInfo> calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions ) override;
void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override;
void defineUiTreeOrdering( caf::PdmUiTreeOrdering& uiTreeOrdering, QString uiConfigName = "" ) override;
void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override;
private:
RimFractureTemplateCollection* fractureTemplateCollection() const;
static QString toResultName( const QString& resultNameAndUnit );
static QString toUnit( const QString& resultNameAndUnit );
private:
caf::PdmField<cvf::Color3f> m_defaultColor;
caf::PdmField<QString> m_resultNameAndUnit;
caf::PdmChildArrayField<RimRegularLegendConfig*> m_legendConfigurations;
caf::PdmField<bool> m_showStimPlanMesh;
caf::PdmField<caf::AppEnum<StimPlanResultColorType>> m_stimPlanCellVizMode;
}; |
<h1 mat-dialog-title>Únete a nosotros</h1>
<mat-tab-group>
<mat-tab label="Iniciar Sesión">
<form class="login-form" [formGroup]="loginForm">
<!------------------------------EMAIL---------------------------------------------------->
<mat-form-field class="login-full-width" appearance="fill">
<mat-label>Correo Electrónico</mat-label>
<input type="email" matInput formControlName="email" [errorStateMatcher]="matcher" formControlName="email" placeholder="Ex. [email protected]">
</mat-form-field>
<!-- [errorStateMatcher]="matcher" -->
<div *ngIf="loginForm.controls['email'].errors" >
<mat-error *ngIf="loginForm.controls['email'].errors['required']">
Se requiere un <strong>correo electronico</strong>
</mat-error>
</div>
<!------------------------------PASSWORD---------------------------------------------------->
<mat-form-field class="login-full-width" appearance="fill">
<mat-label>Contraseña</mat-label>
<input matInput [type]="pass1Visibility ? 'password' : 'text'" formControlName="password">
<mat-icon matSuffix (click)="pass1Visibility = !pass1Visibility">{{pass1Visibility ? 'visibility_off' : 'visibility'}}</mat-icon>
</mat-form-field>
<hr>
<h2 mat-dialog-title>Ingresa con:</h2>
<div class="icons">
<ul>
<li><button (click)="googleLogin()" style="margin-left: 50px;"><img alt="Google" width="22px" src="https://cdn.icon-icons.com/icons2/836/PNG/512/Google_Chrome_icon-icons.com_66794.png"></button></li>
<!-- <li><button><img alt="Facebook" width="22px" src="https://cdn.icon-icons.com/icons2/2429/PNG/512/facebook_logo_icon_147291.png"></button></li>
<li><button><img alt="GitHub" width="22px" src="https://cdn.icon-icons.com/icons2/901/PNG/512/github_icon-icons.com_69253.png"></button></li>
<li><button><img alt="Steam" width="22px" src="https://cdn.icon-icons.com/icons2/2428/PNG/512/steam_black_logo_icon_147078.png"></button></li>
<li><button><img alt="Epic Games" width="22px" src="https://cdn.icon-icons.com/icons2/2407/PNG/512/epic_games_icon_146187.png"></button></li> -->
</ul>
</div>
<!-----------------------------LOGIN BUTTON---------------------------------------------------------------->
<button style="margin-top: 10px;" type="submit" mat-raised-button color="primary" (click)="onLogin()">Iniciar Sesión</button>
<!--------------------------------------------------------------------------------------------------------->
</form>
</mat-tab>
<mat-tab label="Registrarse">
<form class="signin-form" [formGroup]="signinForm">
<!------------------------------EMAIL---------------------------------------------------->
<mat-form-field class="login-full-width" appearance="fill">
<mat-label>Correo Electrónico</mat-label>
<input type="email" matInput formControlName="email" [errorStateMatcher]="matcher" formControlName="email" placeholder="Ex. [email protected]">
</mat-form-field>
<div *ngIf="signinForm.controls['email'].errors" >
<mat-error *ngIf="signinForm.controls['email'].errors['required']">
Se requiere un <strong>correo electronico</strong>
</mat-error>
</div>
<!------------------------------PASSWORD---------------------------------------------------->
<mat-form-field class="login-full-width" appearance="fill">
<mat-label>Contraseña</mat-label>
<input matInput [type]="pass2Visibility ? 'password' : 'text'" formControlName="password">
<mat-icon matSuffix (click)="pass2Visibility = !pass2Visibility">{{pass2Visibility ? 'visibility_off' : 'visibility'}}</mat-icon>
</mat-form-field>
<div *ngIf="signinForm.controls['password'].errors">
<mat-error *ngIf="signinForm.controls['password'].errors['required']">
Se requiere una <strong>constraseña</strong>
</mat-error>
<mat-error *ngIf="signinForm.controls['password'].errors['minlength'] && !signinForm.controls['password'].errors['required']">
Al menos <strong>8 caracteres</strong>
</mat-error>
<mat-error *ngIf="signinForm.controls['password'].errors['hasNumber'] && !signinForm.controls['password'].errors['required']">
Al menos un <strong>número</strong>
</mat-error>
<mat-error *ngIf="signinForm.controls['password'].errors['hasCapitalCase'] && !signinForm.controls['password'].errors['required']">
Al menos una <strong>letra capital</strong>
</mat-error>
<mat-error *ngIf="signinForm.controls['password'].errors['hasSmallCase'] && !signinForm.controls['password'].errors['required']">
Al menos una <strong>letra minuscula</strong>
</mat-error>
<mat-error *ngIf="signinForm.controls['password'].errors['hasSpecialCharacter'] && !signinForm.controls['password'].errors['required']">
Al menos un <strong>caracter especial</strong>
</mat-error>
</div>
<!------------------------------CONFIRM PASSWORD---------------------------------------------------->
<mat-form-field class="login-full-width" appearance="fill">
<mat-label>Confirmar contraseña</mat-label>
<input matInput [type]="passConfVisibility ? 'password' : 'text'" formControlName="confirm">
<mat-icon matSuffix (click)="passConfVisibility = !passConfVisibility">{{passConfVisibility ? 'visibility_off' : 'visibility'}}</mat-icon>
</mat-form-field>
<div *ngIf="signinForm.controls['confirm'].errors">
<mat-error *ngIf="signinForm.controls['confirm'].errors['NoPasswordMatch'] && !signinForm.controls['confirm'].errors['required']">
La constraseña <strong>no coincide</strong>
</mat-error>
</div>
<!-----------------------------SIGNIN BUTTON---------------------------------------------------------------->
<button style="margin-top: 10px;" type="submit" mat-raised-button color="primary" (click)="onRegister()">Registrarse</button>
<!------------------------------------------------------------------------------------------------->
</form>
</mat-tab>
</mat-tab-group> |
// RWD 設定
=breakpoint($point: 1)
@if $point null == true
@if $point == sm
// bootstarp 內建 Small devices (landscape phones, 576px and up) 手機橫的
@media (min-width: 576px) and (max-width: 767.98px)
@content
@else if $point == md
// bootstarp 內建 Medium devices (tablets, 768px and up) 平板直的
@media (min-width: 768px) and (max-width: 991.98px)
@content
@else if $point == lg
// bootstarp 內建 Large devices (desktops, 992px and up) 平板橫的 & 小螢幕電腦 ex.1024
@media (min-width: 992px) and (max-width: 1199.98px)
@content
@else if $point == fsm
// bootstarp 內建 Large devices (desktops, 992px and up) 平板橫的 & 小螢幕電腦 ex.1024
@media (min-width: 576px)
@content
@else if $point == fmd
// bootstarp 內建 Large devices (desktops, 992px and up) 平板橫的 & 小螢幕電腦 ex.1024
@media (min-width: 768px)
@content
@else if $point == xl
// bootstarp 內建Extra large devices (large desktops, 1200px and up) 寬 1200 以上螢幕
@media (min-width: 1200px)
@content
@else if $point == mo1280
// 橘子預設 寬 1280 x 800 8:5 以上螢幕
@media (min-width: 1281px)
@content
@else if $point == mo1366
// 橘子預設 寬 1366 x 768 16:9 以上螢幕
@media (min-width: 1367px)
@content
@else if $point == mo1440
// 橘子預設 寬 1440 x 900 8:5 以上螢幕
@media (min-width: 1441px)
@content
@else if $point == mo1600
// 橘子預設 寬 1600 x 900 16:9 以上螢幕
@media (min-width: 1601px)
@content
@else if $point == mo1680
// 橘子預設 寬 1680 x 1050 8:5 以上螢幕
@media (min-width:1681px)
@content
@else if $point == mo1920
// 橘子預設 寬 1920 x 1080 16:9 以上螢幕
@media (min-width: 1921px)
@content
@else if $point == iphone5p
// iPhone 5 & 5S
@media only screen and (min-device-width : 320px) and (max-device-width : 568px) and (orientation : portrait)
@content
@else if $point == iphone5l
@media only screen and (min-device-width : 320px) and (max-device-width : 568px) and (orientation : landscape)
@content
@else if $point == iphone6p
// iPhone 6, 7, & 8
@media only screen and (min-device-width : 375px) and (max-device-width : 667px) and (orientation : portrait)
@content
@else if $point == iphone6l
@media only screen and (min-device-width : 375px) and (max-device-width : 667px) and (orientation : landscape)
@content
@else if $point == iphoneplusl
// iPhone 6, 7, & 8 Plus
@media only screen and (min-device-width : 414px) and (max-device-width : 736px) and (orientation : portrait)
@content
@else if $point == iphoneplusp
@media only screen and (min-device-width : 414px) and (max-device-width : 736px) and (orientation : landscape)
@content
@else if $point == iphonexl
// iPhone X
@media only screen and (min-device-width : 375px) and (max-device-width : 812px) and (-webkit-device-pixel-ratio : 3) and (orientation : portrait)
@content
@else if $point == iphonexp
@media only screen and (min-device-width : 375px) and (max-device-width : 812px) and (-webkit-device-pixel-ratio : 3) and (orientation : landscape)
@content
@else if $point == ipdp
// Retina iPad
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio: 2)
@content
@else if $point == ipdl
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio: 2)
@content
@else if $point == ipadprop
// Retina iPad pro
@media only screen and (min-device-width: 1024px) and (max-device-width: 1366px) and (-webkit-min-device-pixel-ratio: 2) and (orientation: portrait)
@content
@else if $point == ipadprol
@media only screen and (min-device-width: 1024px) and (max-device-width: 1366px) and (-webkit-min-device-pixel-ratio: 2) and (orientation: landscape)
@content
@else
// Extra small devices (portrait phones, less than 576px) 手機直的
@media (max-width: 575px)
@content |
package com.tinyhuman.tinyhumanapi.diary.controller;
import com.tinyhuman.tinyhumanapi.baby.controller.dto.BabyCreate;
import com.tinyhuman.tinyhumanapi.baby.enums.Gender;
import com.tinyhuman.tinyhumanapi.common.exception.ResourceNotFoundException;
import com.tinyhuman.tinyhumanapi.common.mock.TestContainer;
import com.tinyhuman.tinyhumanapi.diary.controller.port.dto.*;
import com.tinyhuman.tinyhumanapi.diary.domain.Picture;
import com.tinyhuman.tinyhumanapi.user.domain.User;
import com.tinyhuman.tinyhumanapi.user.enums.FamilyRelation;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import java.time.LocalDate;
import java.util.List;
import static org.assertj.core.api.Assertions.*;
class DiaryDetailControllerTest {
TestContainer testContainer;
@BeforeEach
void setUp() {
testContainer = TestContainer.builder()
.uuidHolder(() -> "test-uuid-code")
.build();
// user id: 1
testContainer.userRepository.save(User.builder()
.name("유닛")
.email("[email protected]")
.password("unit")
.build()
);
// baby id: 1
testContainer.babyController.register(BabyCreate.builder()
.name("아기")
.gender(Gender.MALE)
.nickName("아기별명")
.relation(FamilyRelation.FATHER)
.timeOfBirth(23)
.dayOfBirth(LocalDate.of(2022, 9, 27))
.fileName("profile.jpg")
.build());
// diary id: 1
testContainer.diaryCreateController.createDiary(DiaryCreate.builder()
.babyId(1L)
.daysAfterBirth(20)
.userId(1L)
.likeCount(0)
.sentences(List.of(SentenceCreate.builder().sentence("안녕하세요.").build(),
SentenceCreate.builder().sentence("반갑습니다.").build(),
SentenceCreate.builder().sentence("감사합니다.").build()))
.files(List.of(PictureCreate.builder().fileName("hello.jpg").build(),
PictureCreate.builder().fileName("nicetomeetyou.jpg").build(),
PictureCreate.builder().fileName("thankyou.jpg").build()))
.build());
}
@Nested
@DisplayName("사용자는 일기의 글을 수정할 수 있다.")
class UpdateSentence {
@Test
@DisplayName("글을 수정하고 200을 응답한다.")
void updateSentence() {
SentenceCreate updateSentence = SentenceCreate.builder()
.sentence("수정한 글입니다.")
.build();
ResponseEntity<DiaryResponse> result =
testContainer.diaryDetailController.updateDiarySentence(1L, 1L, updateSentence);
assertThat(result.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(200));
assertThat(result.getBody().id()).isEqualTo(1L);
assertThat(result.getBody().sentences())
.extracting("sentence")
.contains("수정한 글입니다.", "반갑습니다.", "감사합니다.");
assertThat(result.getBody().sentences().stream()
.filter(s -> s.id().equals(1L))
.findFirst()
.get().sentence()).isEqualTo("수정한 글입니다.");
assertThat(result.getBody().sentences().size()).isEqualTo(3);
}
@Test
@DisplayName("존재하지 않는 diary id를 요청하면 예외를 던진다.")
void updateSentenceWithInvalidDiaryId() {
SentenceCreate updateSentence = SentenceCreate.builder()
.sentence("수정한 글입니다.")
.build();
assertThatThrownBy(() -> testContainer.diaryDetailController.updateDiarySentence(9999L, 1L, updateSentence))
.isInstanceOf(ResourceNotFoundException.class)
.hasMessageContaining("Diary");
}
@Test
@DisplayName("존재하지 않는 sentence id를 요청하면 예외를 던진다.")
void updateSentenceWithInvalidId() {
SentenceCreate updateSentence = SentenceCreate.builder()
.sentence("수정한 글입니다.")
.build();
assertThatThrownBy(() -> testContainer.diaryDetailController.updateDiarySentence(1L, 9999L, updateSentence))
.isInstanceOf(ResourceNotFoundException.class)
.hasMessageContaining("Sentence");
}
}
@Nested
@DisplayName("사용자는 일기의 글을 삭제할 수 있다.")
class DeleteSentence {
@Test
@DisplayName("일기 id를 입력 받아 일기를 삭제한다.")
void deleteDiary() {
ResponseEntity<Void> result = testContainer.diaryDetailController.deleteDiarySentence(1L, 1L);
assertThat(result.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(204));
}
@Test
@DisplayName("존재하지 않는 diary id를 요청하면 예외를 던진다.")
void deleteWithInvalidDiaryId() {
assertThatThrownBy(() -> testContainer.diaryDetailController.deleteDiarySentence(9999L, 1L))
.isInstanceOf(ResourceNotFoundException.class)
.hasMessageContaining("Diary");
}
@Test
@DisplayName("존재하지 않는 sentence id를 요청하면 예외를 던진다.")
void deleteWithInvalidId() {
assertThatThrownBy(() -> testContainer.diaryDetailController.deleteDiarySentence(1L, 9999L))
.isInstanceOf(ResourceNotFoundException.class)
.hasMessageContaining("Sentence");
}
}
@Nested
@DisplayName("사용자는 일기의 메인 사진을 변경할 수 있다.")
class ChangeMainPictures {
@Test
@DisplayName("현재 메인 사진과 바꿀 메인 사진을 입력 받아 메인 사진을 변경한다.")
void changeMainPicture() {
Long currentMainPictureId = 1L;
Long targetMainPictureId = 3L;
Picture currentMain = testContainer.pictureRepository.findById(currentMainPictureId).get();
Picture targetMain = testContainer.pictureRepository.findById(targetMainPictureId).get();
ChangeMainPicture changeMainPicture = ChangeMainPicture.builder()
.currentPictureId(currentMainPictureId)
.newPictureId(targetMainPictureId)
.build();
assertThat(currentMain.isMainPicture()).isTrue();
assertThat(targetMain.isMainPicture()).isFalse();
ResponseEntity<List<Picture>> result = testContainer.diaryDetailController.changeMainPicture(1L, changeMainPicture);
assertThat(result.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(200));
assertThat(result.getBody().size()).isEqualTo(2);
assertThat(result.getBody())
.extracting("id", "isMainPicture")
.contains(tuple(1L, false), tuple(3L, true));
}
}
} |
package Com.Day5;
abstract class Player{
String P_name;
int P_Age;
void read_Playerdetails(String P_name,int P_Age)
{
this.P_name=P_name;
this.P_Age=P_Age;
}
void display() {
System.out.println(" Player Name:"+P_name+"\n "+"Player Age:"+P_Age);
}
public Player() {
System.out.println("let's see no of players in each Games..!!");
}
abstract void noOfplayers();
}
class cricketPlayer extends Player{
@Override
void noOfplayers() {
System.out.println("Cricket have totally 11 players per team");
}
}
class footBallPlayer extends Player{
@Override
void noOfplayers() {
System.out.println("FootBall have totally 11 players per team");
}
}
class volleyBallPlayer extends Player{
@Override
void noOfplayers() {
System.out.println("volleyBall have totally 11 players per team");
}
}
public class PlayerDetails {
public static void main(String[] args) {
Player obj1 =new cricketPlayer();
System.out.println("-------------------------------");
obj1.read_Playerdetails("Kohli", 32);
obj1.display();
obj1.noOfplayers();
Player obj2 =new footBallPlayer();
obj2.noOfplayers();
}
} |
// This file handles all API interactions
import IRMExerciseInList from "../Interfaces/ResponseModels/IRMExerciseInList";
import ModelExercise from "../Models/ModelExercise";
import ModelSet from "../Models/ModelSet";
import ModelWorkout from "../Models/ModelWorkout";
import axios, { AxiosResponse } from 'axios';
import IRMWorkoutHistory from "../Interfaces/ResponseModels/IRMWorkoutHistory";
import IRMPastExercise from "../Interfaces/ResponseModels/IRMPastExercise";
import IRMPastSet from "../Interfaces/ResponseModels/IRMPastSet";
import ModelWorkoutHistory from "../Models/ModelWorkoutHistory";
const url = process.env.REACT_APP_API_URL;
// This function handles fetching exercises for exercise list
export const fetchExercises = async (searchInput = ''): Promise<IRMExerciseInList[]> => {
try {
const response: AxiosResponse<IRMExerciseInList[]> = await axios.get(`${url}/api/get_exercises?searchInput=${searchInput}`);
if (response.status !== 200) {
throw new Error(`HTTP Error! Status: ${response.status}`);
}
return response.data;
} catch (error) {
console.error('There was an error fetching exercises: ', error);
throw error;
}
}
// This function handles fetching information to auto fill exercise tracking
export const fetchAutoFillInfo = async (addedExerciseIds: number[]): Promise<ModelExercise[]> => {
try {
const idsAsString: string = addedExerciseIds.join(', ');
const response: AxiosResponse<IRMPastExercise[]> = await axios.get(`${url}/api/get_latest_exercise_info?exercise_ids=${idsAsString}`);
if (response.status !== 200) {
throw new Error(`HTTP Error! Status: ${response.status}`);
}
const info: IRMPastExercise[] = response.data;
const modifiedInfo: ModelExercise[] = info.map((exercise: IRMPastExercise) => {
const setsWithCompletion: ModelSet[] = exercise.sets.map((set: IRMPastSet) => ({
...set,
isCompleted: false, // Set the initial value of isCompleted for each set
}));
return {
...exercise,
sets: setsWithCompletion,
};
});
return modifiedInfo;
} catch (error) {
console.error('There was an error auto-filling exercise information: ', error);
throw error;
}
}
export const postWorkout = async (workout: ModelWorkout): Promise<void> => {
try {
const response: AxiosResponse<void> = await axios.post(`${url}/api/post_workout`, workout);
if (response.status !== 200) {
throw new Error(`HTTP Error! Status: ${response.status}`);
}
// Can optionally return the response data if back end sends any
// return response.data;
} catch (error) {
console.error('There was an error posting the workout: ', error);
throw error;
}
};
export const fetchWorkoutHistoryNoDetails = async (): Promise<ModelWorkoutHistory<string>[]> => {
try {
const response: AxiosResponse<IRMWorkoutHistory<string>[]> = await axios.get(`${url}/api/get_workout_history_without_details`);
if (response.status !== 200) {
throw new Error(`HTTP Error! Status: ${response.status}`);
}
const info: IRMWorkoutHistory<string>[] = response.data;
const modifiedInfo: ModelWorkoutHistory<string>[] = info.map((workoutHistory: IRMWorkoutHistory<string>) => ({ ...workoutHistory }));
return modifiedInfo;
} catch (error) {
console.error('There was an error fetching exercise history without details: ', error);
throw error;
}
}
export const fetchWorkoutHistoryWithDetails = async (workoutId: number | null): Promise<ModelWorkoutHistory<ModelExercise>> => {
try {
const response: AxiosResponse<IRMWorkoutHistory<IRMPastExercise>> = await axios.get(`${url}/api/get_workout_history_by_workoutId?workout_id=${workoutId}`);
if (response.status !== 200) {
throw new Error(`HTTP Error! Status: ${response.status}`);
}
const workout: IRMWorkoutHistory<IRMPastExercise> = response.data;
const exercises: ModelExercise[] = workout.exercises_done_in_workout.map((exercise: IRMPastExercise) => {
const setsWithCompletion: ModelSet[] = exercise.sets.map((set: IRMPastSet) => ({
...set,
isCompleted: true
}));
return ({
...exercise,
sets: setsWithCompletion,
});
});
const formattedWorkout: ModelWorkoutHistory<ModelExercise> = { ...workout, exercises_done_in_workout: exercises }
return formattedWorkout;
} catch (error) {
console.error('There was an error fetching exercise history without details: ', error);
throw error;
}
} |
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Review extends Model
{
protected $fillable =
[
'user_id', 'product_id', 'starts', 'review'
];
use HasFactory;
public function customer()
{
return $this->belongsTo(User::class , 'user_id' , 'id');
}
public function product()
{
return $this->belongsTo(Product::class ) ;
}
public function humanFormattedDate()
{
return \Carbon\Carbon::createFromTimestamp( strtotime( $this->created_at ) )->diffForHumans() ;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using UnityEngine;
/*
Cette classe représente un réseau de neurones artificiels (RNA) avec plusieurs couches.
RDN : Reseau de Neurones
*/
public class NeuralNetwork
{
private static int NextId = 0;
public int id;
// Forme du RDN (ici, 6 entrees, 3 couches cachees a 32, 16 puis 8 neurones, 4 sorties)
public int[] LayersLengths = { 6, 32, 16, 8, 4 };
public List<Layer> Layers = new List<Layer>();
public double mutationRate = 0.2;
public double mutationRange = 0.5;
// Constructeur de RDN vide
public NeuralNetwork()
{
id = NextId++;
for (int i = 0; i < LayersLengths.Length - 1; i++)
{
Layers.Add(new Layer(LayersLengths[i], LayersLengths[i + 1]));
}
}
// Constructeur d'un RDN à partir d'un autre RDN (pour eviter les problemes de reference)
public NeuralNetwork(NeuralNetwork original_NN)
{
id = NextId++;
LayersLengths = original_NN.LayersLengths;
mutationRate = original_NN.mutationRate;
mutationRange = original_NN.mutationRange;
foreach (Layer original_NNLayer in original_NN.Layers)
{
Layer newLayer = new Layer(original_NNLayer.NbInputs, original_NNLayer.NbNodes);
// Copier les poids
for (int i = 0; i < newLayer.WeightArray.GetLength(0); i++)
{
for (int j = 0; j < newLayer.WeightArray.GetLength(1); j++)
{
newLayer.WeightArray[i, j] = original_NNLayer.WeightArray[i, j];
}
}
// Copier les biais
for (int i = 0; i < newLayer.BiasArray.Length; i++)
{
newLayer.BiasArray[i] = original_NNLayer.BiasArray[i];
}
Layers.Add(newLayer);
}
}
// Reinitialisation du RDN
public void RAZ()
{
foreach (Layer layer in Layers)
{
layer.Init();
}
}
// Fonction principale qui donne des sorties (outputs) a des entrees (inputs)
public double[] Brain(double[] inputs)
{
if (inputs.Length != Layers[0].NbInputs)
{
throw new ArgumentException(
"The number of inputs doesn't match the number of inputs of the Layer."
);
}
int outputLayerIndex = Layers.Count() - 1;
// Forward propagation
if (outputLayerIndex != 0)
{
Layers[0].Predict(inputs);
Layers[0].Activation();
for (int i = 1; i < outputLayerIndex; i++)
{
Layers[i].Predict(Layers[i - 1].NodeArray);
Layers[i].Activation();
}
Layers[outputLayerIndex].Predict(Layers[outputLayerIndex - 1].NodeArray);
}
else
{
Layers[0].Predict(inputs);
}
Layers[outputLayerIndex].Convert();
return Layers[outputLayerIndex].NodeArray;
}
// Applique la mutation à chaque couche du RDN
public void Mutate()
{
// mutationRate = 100/(nbGen+200);
foreach (Layer layer in Layers)
{
layer.Mutate(mutationRate, mutationRange);
}
}
public void Randomize()
{
foreach (Layer layer in Layers)
{
layer.Randomize();
}
}
public override string ToString()
{
string outString = "";
foreach (int i in LayersLengths)
{
outString += $"{i} ";
}
outString += "\n";
foreach (Layer l in Layers)
{
outString += l.ToString();
}
return outString;
}
} |
### Test Automation
<img src="https://github.com/suwinphyu/readLists/blob/gh-pages/images/testautomation.png" width="680" height="300">
#### 𝐓𝐞𝐬𝐭 𝐀𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐨𝐧 လုပ်ဆောင်ရန်အတွက် စဉ်းစားသင့်သည့် အချက်များ
* ဘာကြောင့် test automation ကိုစတင် အသုံးပြုချင်တာလဲ
* ဘယ်လို အပိုင်းတွေမှာ အသုံးပြုချင်တာလဲ
* Test automation ကို ဘယ်သူတွေက လုပ်ဆောင်ကြမှာလဲ
* ဘယ်လောက်ထိ သူတို့ရဲ့ လုပ်ဆောင်နိုင်ချေကို မျှော်လင့်ထားလဲ
* ဘယ်လို နည်းလမ်းတွေနဲ့ စတင်ဖို့ ရည်ရွယ်ထားသလဲ
#### "ဘာကြောင့် test automation ကိုစတင် အသုံးပြုချင်တာလဲ"
Features ကို မြန်မြန် release လုပ်ချင်လို့၊ Manual testing ကိုလျော့ချချင်လို့ ၊ Software tester တွေကို new features ကိုပဲ အလေးထားပြီး testing လုပ်စေချင်လို့ Regression Testing လုပ်ဆောင်ရတဲ့ အချိန်ကို လျော့ချနိုင်ဖို့ ၊Application build လုပ်ပြီးတိုင်း Integration testing ကို မြန်မြန် လုပ်ဆောင်နိုင်ဖို့ အစရှိသည့်ရည်ရွယ်ချက်တွေဖြင့် စတင်နိုင်ပါတယ်။
#### "Test automation ကို ဘယ်သူတွေက လုပ်ဆောင်ကြမှာလဲ"
Test automation ကို developလုပ်နိုင်အောင် Test automation scripts ရေးမည့်သူ ၊ Test execution လုပ်တဲ့အခါ test results တွေကို စောင့်ကြည့်ပေးမယ့်သူ ၊ Business logic procedure ပြောင်းတဲ့အခါ မူလရေးသားထားတဲ့ scripts တွေကို update လုပ်ပေးမယ့်သူတွေ လိုအပ်ပါတယ်။ တစ်ယောက်တည်းက ပဲ အကုန်လုပ်ဆောင်တာလည်းဖြစ်နိုင်ပါတယ်.. team အလိုက် လုပ်ဆောင်ခွဲဝေလုပ်ဆောင်တာမျိုးလည်း ရှိနိုင်တယ် ။
#### "Test automation scripts ဘယ်သူတွေ ရေးသားကြမလဲ"
Developer – development ပိုင်းမှာ ကျွမ်းကျင်ပေမယ့် new features and bug fixing task တွေရှိတဲ့အတွက် test scripts ရေးသားဖို့ အချိန်မရနိုင်ပါဘူး
Manual Tester – Testing logic and thinking ကို နားလည်ပေမယ့် test script ရေးသားဖို့အချိန်တစ်ခု လိုအပ်ပါတယ်။ New features တွေကို sprint အတွင်း အချိန်မီ testing လုပ်ရန်သာမက old features တွေအတွက် test automation ရေးသားဖို့ အချိန်လုံလောက်နိုင်ပါ့မလား
Developer ကော Manual Tester တွေပါ current tasks တွေကို လျော့ချပြီး automation အတွက် အချိန်တွေ လိုအပ်တဲ့ resources တွေပေးမယ်ဆိုလည်း ဒါဟာ အကောင်းဆုံးနည်းလမ်းလို့တော့ မဆိုလိုနိုင်ပါဘူး
```
𝐓𝐞𝐬𝐭 𝐀𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐨𝐧 သည်လည်းပဲ 𝐬𝐨𝐟𝐭𝐰𝐚𝐫𝐞 𝐝𝐞𝐯𝐞𝐥𝐨𝐩𝐦𝐞𝐧𝐭 လုပ်ငန်းစဉ် တစ်ခုလိုပါပဲ. .
𝐓𝐢𝐦𝐞 𝐚𝐧𝐝 𝐒𝐤𝐢𝐥𝐥 လိုအပ်ပါတယ် အချိန်ရှိတဲ့ အခါမှသာ လုပ်ဆောင်မယ့်
side task တခုအနေနဲ့ အသုံးပြုမယ်ဆိုရင်တော့ ခဏပဲ စတင်ပြီး ရပ်ဆိုင်းသွားပါလိမ့်မယ်
```
ဒါကြောင့်မို့ Test Automation အပိုင်းကို စိတ်ဝင်စားတဲ့သူ ဒါမှမဟုတ် automation engineer နဲ့ပူးပေါင်းပြီး စတင်လုပ်ဆောင်သင့်ပါတယ်
ဘယ်လို Tool တွေကို အသုံးပြုကြမလဲ ၊ Test script ရေးသားရာတွင် အသုံးပြုမည့် Programming language ၊ ဘယ်လို scenarios တွေကို အရင်ဆုံး စတင်ပြီး automation လုပ်သင့်သလဲ စသည်တို့ကိုလည်း automation စတင်လုပ်ဆောင်ရာတွင် ထည့်သွင်းစဉ်းစားသင့်ပါတယ်။
#### Selenium
ဒီတခါမှာတော့ Automation testing tool တစ်ခုဖြစ်တဲ့ 𝐒𝐞𝐥𝐞𝐧𝐢𝐮𝐦 (https://www.selenium.dev/downloads/) အကြောင်းလေ့လာကြရအောင်..
Selenium က web application အတွက်သာ အသုံးပြုလို့ရတဲ့ opensource testing tool တစ်ခုဖြစ်ပြီးတော့ မည်သည့် browser မှာမဆို အသုံးပြုလို့ရပါတယ်။ Test Script ရေးသားဖို့အတွက် အဓိက Language တွေအနေနဲ့ Ruby,Java,Python,C# and JavaScript တွေကို အသုံးပြုပြီးရေးသားနိုင်ပါတယ်။ တခြား PHP, Kotlin အစရှိသည်တို့ဖြင့်လည်း language binding လုပ်ပြီး အသုံးပြုနိုင်ပါတယ်။
အားနည်းချက်အနေနဲ့ကတော့ Configuration လုပ်ရာမှာ နည်းနည်းရှုပ်တယ်။ Images testing လုပ်ဆောင်လို့မရနိုင်တဲ့အတွက် တခြား third-party tool(eg. Sikuli with selenium ) တွေနဲ့ integrate လုပ်ပေးရပါမယ်။ Built-in Reporting feature မပါတဲ့အတွက် Test report ထုတ်နိုင်ဖို့၊ Test Data တွေကို export ထုတ်နိုင်ဖို့အတွက် မိမိအသုံးပြုမယ့် language အလိုက် framework တွေ ထပ်ပေါင်းထည့်ပေးရပါမယ်( eg. Java အတွက်ဆို TestNG / JUnit) Test development လုပ်ဆောင်ရန်အတွက် သက်ဆိုင်ရာ Language အလိုက် coding အခြေခံ သဘောတရားကို နားလည်ထားရမှာဖြစ်တဲ့အတွက် ROI Time ကြာမြင့်နိုင်ပါတယ်။ Popup box handling အတွက် script ရေးသားရာမှာလည်း အမျိုးအစား (Alert / Pop up/confirmation / Prompt/ Authentication) နဲ့ testing environment တည်ဆောက်ထားသော OS (eg. Window/Linux) ပေါ်မူတည်ပြီး ပြောင်းလဲနိုင်ပါတယ်။
Selenium ရဲ့ components (၃) ခုကတော့
1. IDE (browser extension tool, records the users’ actions in the browser)
2. Grid (run test cases in different machines across different platforms)
3. Web Driver (browser automation APIs)
###### IDE
IDE ကတော့ သုံးရတာလွယ်ကူတယ် Firefox and Chrome extension (eg.https://chrome.google.com/webstore/detail/selenium-ide/mooikfkahbdckldjjndioackbalphokd ) ပဲရှိတဲ့အတွက် တခြား browser တွေမှာ သုံးလို့မရပါဘူး ။ Setup လုပ်ထားသော URL ရဲ့ user action ကို record လုပ်ထားပေးပြီး test-case အနေနဲ့ generate လုပ်ယူနိုင်ပါတယ်။
###### Grid
Grid ကိုတော့ Multiple Operation Systems (Nodes) ပေါ်မှာ browser အမျိုးမျိုးနဲ့ တပြိုက်နက်တည်း run တဲ့အခါမှာ အသုံးပြုနိုင်ပါတယ်။ Parallel Testing လုပ်နိုင်တဲ့အတွက် test execution time ကိုလျော့ချပေးနိုင်ပါတယ်။
###### Web Driver
Browser automation APIs တစ်ခုဖြစ်ပြီး ရေးသားထားသော test script များကို language အလိုက် interpret လုပ်ပေးပြီး browser ပေါ်တွင် automatically အလုပ်လုပ်နိုင်အောင် web-driver ကို အသုံးပြုခြင်းဖြစ်ပါတယ်။ |
import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {MoviesComponent} from './movies/movies.component';
import {MovieComponent} from './movie/movie.component';
const routes: Routes = [
{path: '', redirectTo: '/movies', pathMatch: 'full'},
{path: 'movies', component: MoviesComponent},
{path: 'movie/:id', component: MovieComponent},
{path: '**', redirectTo: '/movies'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
} |
import { Button, Col, DatePicker, Empty, Form, Row, Space, Table, Tooltip, notification } from "antd";
import { Content } from "antd/es/layout/layout";
import { AccesoUsuario, AccionesUsuario } from "./data";
import { NextPage } from "next";
import { ColumnsType } from "antd/es/table";
import Paragraph from "antd/es/typography/Paragraph";
import dayjs from "dayjs";
import {
FilePdfFilled,
} from "@ant-design/icons";
import locale from "antd/es/date-picker/locale/es_ES";
import { pdf } from "@react-pdf/renderer";
import { createContext, useState } from "react";
import { Persona, dias, meses } from "../personal/agregar/data";
import PdfAcciones from "./pdf-acciones";
interface Props {
accionesUsuario: AccionesUsuario[];
accesosUsuario: AccesoUsuario[];
persona: Persona;
displayAccionesUsuario: AccionesUsuario[];
displayAccesosUsuario: AccesoUsuario[];
setDisplayAccionesUsuario: any;
setDisplayAccesosUsuario: any;
}
export const accesoContext = createContext({});
export const accionesContext = createContext({});
import isBeetwen from "dayjs/plugin/isBetween";
import PdfAccesos from "./pdf-accesos";
const SeguimientoCuenta: NextPage<Props> = (props) => {
dayjs.extend(isBeetwen);
const [rangeAcceso, setRangeAcceso] = useState<{ de: any, hasta: any }>({ de: null, hasta: null })
const [rangeAcciones, setRangeAcciones] = useState<{ de: any, hasta: any }>({ de: null, hasta: null })
//COLUMNAS
const columnaAcciones: ColumnsType<AccionesUsuario> = [
{
title: "ID Acción",
dataIndex: "id_denunciado",
key: "id_denunciado",
className: "text-center",
fixed: "left",
width: 110,
render(_, accion) {
return (
<Paragraph className="center" copyable>
{accion.id_accion}
</Paragraph>
);
},
},
{
title: "Fecha / Hora de Acción",
key: "fecha_hora_accion",
render(_, accion) {
return (
dayjs(accion.fecha_hora_accion).format("DD/MM/YYYY-HH:mm:ss")
);
},
width: 200,
},
{
title: "Tabla",
key: "tabla",
dataIndex: "tabla",
className: "text-center",
width: 120,
},
{
title: "Tipo",
key: "tipo",
dataIndex: "tipo",
},
];
const { RangePicker } = DatePicker;
const columnaAcceso: ColumnsType<AccesoUsuario> = [
{
title: "ID Acceso",
key: "id_acceso",
className: "text-center",
fixed: "left",
width: 120,
render(_, acceso) {
return (
<Paragraph className="center" copyable>
{acceso.id_acceso}
</Paragraph>
);
},
},
{
title: "Fecha / Hora de entrada",
key: "fecha_hora_acceso",
width: 150,
dataIndex: "fecha_hora_acceso",
className: "text-center",
render(_, acceso) {
return `${dayjs(acceso.fecha_hora_acceso).format("DD/MM/YYYY-HH:mm:ss")}`
}
},
{
title: "Fecha / Hora de salida",
key: "fecha_hora_salida",
width: 150,
dataIndex: "fecha_hora_acceso",
className: "text-center",
render(_, acceso) {
return `${dayjs(acceso.fecha_hora_salida).format("DD/MM/YYYY-HH:mm:ss")}`
}
},
];
return (
<>
<Content>
<Row gutter={[40, 24]}>
<Col span={24} lg={{ span: 12 }}>
<Tooltip
title="Generar PDF"
placement={"right"}
color={"#b51308"}
key={"pdf"}
>
<Button
className="center info-button"
style={{ height: 50, width: 50, minWidth: 50 }}
icon={
<FilePdfFilled
style={{
color: "#b51308",
fontSize: 30,
}}
/>
}
onClick={() => {
notification.info({
message: "Generando PDF, por favor espere...",
});
pdf(
<accesoContext.Provider
value={{
accesos: props.displayAccesosUsuario,
persona: props.persona,
rangeAcceso: rangeAcceso
}}
>
<PdfAccesos />
</accesoContext.Provider>
)
.toBlob()
.then((blob) => {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
let nombrePdf = `Accesos-${dayjs().year()}-${dayjs().month()}-${dayjs().date()}.pdf`;
link.setAttribute("download", nombrePdf);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
notification.success({
message: "PDF " + nombrePdf + " generado con éxito...",
});
});
}}
/>
</Tooltip>
<Form.Item label="Filtrar por rango de fechas:">
<RangePicker
locale={{
...locale,
lang: {
...locale.lang,
shortWeekDays: dias,
shortMonths: meses,
},
}}
onChange={(value: any) => {
if (value) {
let [inicio, final] = value;
setRangeAcceso({ de: inicio.$d, hasta: final.$d })
let fechaInicio = dayjs(inicio.$d);
let fechaFinal = dayjs(final.$d);
props.setDisplayAccesosUsuario(props.accesosUsuario.filter(acceso => {
return dayjs(acceso.fecha_hora_acceso).isBetween(fechaInicio, fechaFinal) && dayjs(acceso.fecha_hora_salida).isBetween(fechaInicio, fechaFinal);
}))
}
else {
setRangeAcceso({ de: null, hasta: null })
props.setDisplayAccesosUsuario(props.accesosUsuario);
}
}}
/>
</Form.Item>
<Table
className="mt-2"
scroll={{ y: 600 }}
rowKey={(acceso) => acceso.id_acceso + "T"}
key="table"
pagination={{ pageSize: 20, position: ["bottomCenter"], showSizeChanger: false }}
columns={columnaAcceso}
locale={{
emptyText: (
<Space direction="vertical" align="center">
<Empty description="No existen datos a mostrar..." />
</Space>
),
}}
dataSource={props.displayAccesosUsuario}
/>
</Col>
<Col span={24} lg={{ span: 12 }}>
<Tooltip
title="Generar PDF"
placement={"right"}
color={"#b51308"}
key={"pdf"}
>
<Button
className="center info-button"
style={{ height: 50, width: 50, minWidth: 50 }}
icon={
<FilePdfFilled
style={{
color: "#b51308",
fontSize: 30,
}}
/>
}
onClick={() => {
notification.info({
message: "Generando PDF, por favor espere...",
});
pdf(
<accionesContext.Provider
value={{
acciones: props.accionesUsuario,
persona: props.persona,
rangeAcciones: rangeAcciones,
}}
>
<PdfAcciones />
</accionesContext.Provider>
)
.toBlob()
.then((blob) => {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
let nombrePdf = `Acciones-${dayjs().year()}-${dayjs().month()}-${dayjs().date()}.pdf`;
link.setAttribute("download", nombrePdf);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
notification.success({
message: "PDF " + nombrePdf + " generado con éxito...",
});
});
}}
/>
</Tooltip>
<Form.Item label="Filtrar por rango de fechas:">
<RangePicker
locale={{
...locale,
lang: {
...locale.lang,
shortWeekDays: dias,
shortMonths: meses,
},
}}
onChange={(value: any) => {
if (value) {
let [inicio, final] = value;
setRangeAcciones({ de: inicio.$d, hasta: final.$d })
let fechaInicio = dayjs(inicio.$d);
let fechaFinal = dayjs(final.$d);
props.setDisplayAccionesUsuario(props.accionesUsuario.filter(acceso => {
return dayjs(acceso.fecha_hora_accion).isBetween(fechaInicio, fechaFinal);
}))
}
else {
setRangeAcciones({ de: null, hasta: null })
props.setDisplayAccionesUsuario(props.accionesUsuario);
}
}}
/>
</Form.Item>
<Table
className="mt-2"
scroll={{ y: 500 }}
rowKey={(accion) => accion.id_accion + "T"}
key="table"
pagination={{ pageSize: 20, position: ["bottomCenter"], showSizeChanger: false }}
columns={columnaAcciones}
locale={{
emptyText: (
<Space direction="vertical" align="center">
<Empty description="No existen datos a mostrar..." />
</Space>
),
}}
dataSource={props.displayAccionesUsuario}
/>
</Col>
</Row>
</Content>
</>
);
};
export default SeguimientoCuenta; |
Date.CultureInfo = {
/* Culture Name */
name: "en-AU",
englishName: "English (Australia)",
nativeName: "English (Australia)",
/* Day Name Strings */
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
abbreviatedDayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
shortestDayNames: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
firstLetterDayNames: ["S", "M", "T", "W", "T", "F", "S"],
/* Month Name Strings */
monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
abbreviatedMonthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
/* AM/PM Designators */
amDesignator: "AM",
pmDesignator: "PM",
firstDayOfWeek: 1,
twoDigitYearMax: 2029,
/**
* The dateElementOrder is based on the order of the
* format specifiers in the formatPatterns.DatePattern.
*
* Example:
<pre>
shortDatePattern dateElementOrder
------------------ ----------------
"M/d/yyyy" "mdy"
"dd/MM/yyyy" "dmy"
"yyyy-MM-dd" "ymd"
</pre>
*
* The correct dateElementOrder is required by the parser to
* determine the expected order of the date elements in the
* string being parsed.
*/
dateElementOrder: "dmy",
/* Standard date and time format patterns */
formatPatterns: {
shortDate: "d/MM/yyyy",
longDate: "dddd, d MMMM yyyy",
shortTime: "h:mm tt",
longTime: "h:mm:ss tt",
fullDateTime: "dddd, d MMMM yyyy h:mm:ss tt",
sortableDateTime: "yyyy-MM-ddTHH:mm:ss",
universalSortableDateTime: "yyyy-MM-dd HH:mm:ssZ",
rfc1123: "ddd, dd MMM yyyy HH:mm:ss GMT",
monthDay: "dd MMMM",
yearMonth: "MMMM yyyy"
},
/**
* NOTE: If a string format is not parsing correctly, but
* you would expect it parse, the problem likely lies below.
*
* The following regex patterns control most of the string matching
* within the parser.
*
* The Month name and Day name patterns were automatically generated
* and in general should be (mostly) correct.
*
* Beyond the month and day name patterns are natural language strings.
* Example: "next", "today", "months"
*
* These natural language string may NOT be correct for this culture.
* If they are not correct, please translate and edit this file
* providing the correct regular expression pattern.
*
* If you modify this file, please post your revised CultureInfo file
* to the Datejs Forum located at http://www.datejs.com/forums/.
*
* Please mark the subject of the post with [CultureInfo]. Example:
* Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)
*
* We will add the modified patterns to the master source files.
*
* As well, please review the list of "Future Strings" section below.
*/
regexPatterns: {
jan: /^jan(uary)?/i,
feb: /^feb(ruary)?/i,
mar: /^mar(ch)?/i,
apr: /^apr(il)?/i,
may: /^may/i,
jun: /^jun(e)?/i,
jul: /^jul(y)?/i,
aug: /^aug(ust)?/i,
sep: /^sep(t(ember)?)?/i,
oct: /^oct(ober)?/i,
nov: /^nov(ember)?/i,
dec: /^dec(ember)?/i,
sun: /^su(n(day)?)?/i,
mon: /^mo(n(day)?)?/i,
tue: /^tu(e(s(day)?)?)?/i,
wed: /^we(d(nesday)?)?/i,
thu: /^th(u(r(s(day)?)?)?)?/i,
fri: /^fr(i(day)?)?/i,
sat: /^sa(t(urday)?)?/i,
future: /^next/i,
past: /^last|past|prev(ious)?/i,
add: /^(\+|aft(er)?|from|hence)/i,
subtract: /^(\-|bef(ore)?|ago)/i,
yesterday: /^yes(terday)?/i,
today: /^t(od(ay)?)?/i,
tomorrow: /^tom(orrow)?/i,
now: /^n(ow)?/i,
millisecond: /^ms|milli(second)?s?/i,
second: /^sec(ond)?s?/i,
minute: /^mn|min(ute)?s?/i,
hour: /^h(our)?s?/i,
week: /^w(eek)?s?/i,
month: /^m(onth)?s?/i,
day: /^d(ay)?s?/i,
year: /^y(ear)?s?/i,
shortMeridian: /^(a|p)/i,
longMeridian: /^(a\.?m?\.?|p\.?m?\.?)/i,
timezone: /^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt|utc)/i,
ordinalSuffix: /^\s*(st|nd|rd|th)/i,
timeContext: /^\s*(\:|a(?!u|p)|p)/i
},
timezones: [{name:"UTC", offset:"-000"}, {name:"GMT", offset:"-000"}, {name:"EST", offset:"-0500"}, {name:"EDT", offset:"-0400"}, {name:"CST", offset:"-0600"}, {name:"CDT", offset:"-0500"}, {name:"MST", offset:"-0700"}, {name:"MDT", offset:"-0600"}, {name:"PST", offset:"-0800"}, {name:"PDT", offset:"-0700"}]
};
/********************
** Future Strings **
********************
*
* The following list of strings may not be currently being used, but
* may be incorporated into the Datejs library later.
*
* We would appreciate any help translating the strings below.
*
* If you modify this file, please post your revised CultureInfo file
* to the Datejs Forum located at http://www.datejs.com/forums/.
*
* Please mark the subject of the post with [CultureInfo]. Example:
* Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)b
*
* English Name Translated
* ------------------ -----------------
* about about
* ago ago
* date date
* time time
* calendar calendar
* show show
* hourly hourly
* daily daily
* weekly weekly
* bi-weekly bi-weekly
* fortnight fortnight
* monthly monthly
* bi-monthly bi-monthly
* quarter quarter
* quarterly quarterly
* yearly yearly
* annual annual
* annually annually
* annum annum
* again again
* between between
* after after
* from now from now
* repeat repeat
* times times
* per per
* min (abbrev minute) min
* morning morning
* noon noon
* night night
* midnight midnight
* mid-night mid-night
* evening evening
* final final
* future future
* spring spring
* summer summer
* fall fall
* winter winter
* end of end of
* end end
* long long
* short short
*/ |
package com.generic.retailer.controller;
import static org.hamcrest.MatcherAssert.assertThat;
import com.generic.retailer.RetailerAPIApplication;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import static io.restassured.RestAssured.given;
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = RetailerAPIApplication.class)
class ProductIntegrationTest {
@LocalServerPort
int port;
@BeforeEach
public void setUp() {
RestAssured.port = port;
}
@Test
void listAllProduct() throws Exception {
Response response = given()
.when()
.accept(ContentType.JSON)
.get("/retailer/v0/products");
response.then()
.statusCode(200)
.contentType(ContentType.JSON);
assertThat(response.getBody().jsonPath().getJsonObject("trolley"), Matchers.iterableWithSize (3));
}
} |
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { CookieService } from 'ngx-cookie-service';
@Injectable()
export class InjectSessionInterceptor implements HttpInterceptor {
constructor(private cookie: CookieService) { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
try {
const token = this.cookie.get('tokenSesion')
let newRequest = request;
newRequest = request.clone({
setHeaders: {
authorization: `Bearer ${token}`
}
})
return next.handle(newRequest);
} catch (error) {
return next.handle(request);
}
}
} |
import { createContext, ReactNode, useCallback, useState } from "react";
import { getPage } from "../api";
type ParsedPageInformation = {
url: string;
title: string;
content: string;
};
export const PageContentCacheContext = createContext({
urls: {} as Record<string, ParsedPageInformation | null>,
async request(url: string): Promise<ParsedPageInformation | null> {
throw new Error("Not implemented");
},
});
export default function PageContentCacheProvider({
children,
}: {
children: ReactNode;
}) {
const [urls, setUrls] = useState(
{} as Record<string, ParsedPageInformation | null>
);
const request = useCallback(
async (url: string) => {
let content: ParsedPageInformation | null = urls[url];
if (urls[url] === undefined) {
const result = await getPage(url);
if (!result) {
content = null;
} else {
content = { url, ...result };
}
setUrls((urls) => ({ ...urls, [url]: content }));
}
return content;
},
[urls]
);
return (
<PageContentCacheContext.Provider value={{ urls, request }}>
{children}
</PageContentCacheContext.Provider>
);
} |
---
title: "Class 5: Data Visualization"
author: "Angela Bartolo (PID: A15932451)"
format: gfm
---
#Base R graphics vs ggplot2
There are many graphics systems available in R, including so-called "base" R graphics and the very popular **ggplot2** package.
To compare these let's play with the inbuilt `cars` dataset.
```{r}
head(cars)
```
To use "base" R I can simply call the `plot()` function:
```{r}
plot(cars)
```
To use `ggplot2` package I first need to install it with the function `install.packages("ggplot2")`.
I will run this in my R console (i.e. the R brain) as I do not want to re-install it every time I render my report...
The main function in this package is called `ggplot()`. Can I just call it
```{r}
library(ggplot2)
ggplot()
```
To make a figure with ggplot I need always at least 3 things:
- **data** (i.e. what I want to plot)
- **aes** the aesthetic mapping of the data to the plot I want
- the **geoms** (i.e. how I want to plot the data)
```{r}
ggplot(data=cars) +
aes(x=speed, y=dist) +
geom_point()
```
If I want to add more things, I can just keep adding layers, e.g.
```{r}
ggplot(data=cars) +
aes(x=speed, y=dist) +
geom_point() +
geom_smooth()
```
GGplot is much more verbose than base R plots for standard plots but it has a consistent layer system that I can use to make just about any plot.
Let's make a plot with a straight line fit - i.e. a linear model and no standard error shown.
```{r}
ggplot(data=cars) +
aes(x=speed, y=dist) +
geom_point() +
geom_smooth(se=FALSE, method="lm") +
labs(title = "Stopping distance for old cars",
subtitle = "From the inbuilt cars dataset",
caption = "BIMM143",
x = "Speed (MPG)",
y = "Stopping distance (ft)") +
theme_bw()
```
## A more complicated plot
Let's plot some gene expression data.
The code below reads the results of a differential expression analysis where a new anti-viral drug is being tested.
```{r}
url <- "https://bioboot.github.io/bimm143_S20/class-material/up_down_expression.txt"
genes <- read.delim(url)
head(genes)
```
> Q. How many genes are in this dataset
```{r}
nrow(genes)
```
> Q. How can I summarize the last column - the "State" column?
```{r}
table(genes$State)
```
```{r}
p <- ggplot(data=genes) +
aes(x=Condition1, y=Condition2, color=State) +
geom_point()
```
I can now just call `p` when I want to plot or add to it
```{r}
p + labs(x="Control",
y="Drug Treated",
title= "Gene Expression Changes Upon Drug Treatment") +
scale_colour_manual(values=c("pink","grey","green"))
```
## Going Further
Here I read a slightly larger dataset
```{r}
url <- "https://raw.githubusercontent.com/jennybc/gapminder/master/inst/extdata/gapminder.tsv"
gapminder <- read.delim(url)
head(gapminder)
```
Plotting lifeExp vs gdpPercap
```{r}
ggplot(data=gapminder) +
aes(x=gdpPercap, y=lifeExp, color=continent, size = pop) +
geom_point(alpha=0.3)
```
A very useful layer to add sometimes is for "faceting".
```{r}
ggplot(data=gapminder) +
aes(x=gdpPercap, y=lifeExp, color=continent, size = pop) +
geom_point(alpha=0.3) +
facet_wrap(~continent)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.