text
stringlengths 184
4.48M
|
|---|
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import {
Controller,
Get,
Post,
UseGuards,
Param,
Delete,
Put,
ParseIntPipe,
Body,
} from '@nestjs/common';
import { JwtAuthGuard } from '@mezcal/auth/guards/jwt/jwt-auth.guard';
import { ShopDTO } from '@mezcal/modules/owner/shops/model/shop.dto';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import {
PaginationPrimeNG,
PaginationPrimeNgResult,
} from '@mezcal/common/dto/pagination/paginationprimeng.dto';
import { ShopsService } from '@mezcal/modules/owner/shops/shops.service';
import { DeleteResult, UpdateResult } from 'typeorm';
import { ShopEntity } from './model/shop.entity';
import { Profiles } from '@mezcal/common/decorators/profiles.decorator';
import { ProfileTypes } from '@mezcal/modules/admin/profiles/model/profiles.enum';
import { Rules } from '@mezcal/common/decorators/rules.decorator';
/**
* Controlador de usuarios
*/
@ApiBearerAuth()
@ApiTags('owner')
@Controller('owner')
@Profiles(ProfileTypes.OWNER)
@UseGuards(JwtAuthGuard)
export class ShopsController {
/**
* Servicios utilizados
* @param shopsService
* @param logger
*/
constructor(private readonly shopsService: ShopsService) {}
/**
* Api: GET /api/v1/shops/:id
*
* @param {number} id el id del shopo a actualizar
* @returns {ShopDTO} - el shopo de la base de datos
*/
@Rules('view:shops')
@Get('shops/:id')
getById(@Param('id', ParseIntPipe) id: number): Promise<ShopEntity> {
return this.shopsService.getById(id);
}
/**
* Api: PUT /api/v1/shopos/:id
*
* @param {number} id el id del shopo a actualizar
* @param {ShopDTO} shop los cambios al shopo
* @returns {ShopDTO} - el shopo de la base de datos
*/
@Rules('update:shops')
@Put('shops/:id')
updateShop(
@Param('id') id: number,
@Body() shop: ShopDTO,
): Promise<UpdateResult> {
return this.shopsService.update(id, shop);
}
/**
* Elimina un shopo de la base de datos, se verifica que sea de la casa que
* esta intentando hacer el borrado.
*
* Otra linea.
*
* @param {number} id el shopo a borrar
* @returns {DeleteResult} result del borrado.
*/
@Rules('delete:shops')
@Delete('shops/:id')
delete(@Param('id') id: number): Promise<DeleteResult> {
return this.shopsService.delete(id);
}
/**
* Api: GET /api/v1/shopos
*
* @returns {ShopDTO[]} shopos
*/
@Rules('view:shops')
@Get('shops/get-house-id/:id')
getHouseId(@Param('id') id: number): Promise<ShopEntity[]> {
return this.shopsService.getHouseId(id);
}
/**
* Api: POST /api/v1/shopos
*
* @param {ShopDTO} shop shopo a crear.
* @returns {ShopDTO} shop
*/
@Rules('create:shops')
@Post('shops')
post(@Body() shop: ShopDTO): Promise<ShopEntity> {
return this.shopsService.create(shop);
}
/**
* Api: POST /api/v1/shopos/paginate
*
* @param {PaginationPrimeNG} options
* @returns {PaginationPrimeNgResult} la salida
*/
@Rules('view:shops')
@Post('shops/paginate')
paginate(
@Body() options: PaginationPrimeNG,
): Promise<PaginationPrimeNgResult> {
return this.shopsService.paginate(options);
}
}
|
from collections import deque
from typing import Set, Tuple
from custom_dataclasses.expression import Abstraction, Expression, Application, Variable
class Evaluator:
def __init__(self, max_reductions: int):
self.max_reductions = max_reductions
self.queue = deque()
def eval(self, term: Expression) -> Tuple[Expression, str]:
return self.singleEval(term)
def occurs_in(self, expr: Expression, var: Variable) -> bool:
if isinstance(expr, Variable):
return expr == var
elif isinstance(expr, Application):
return self.occurs_in(expr.func, var) or self.occurs_in(expr.arg, var)
elif isinstance(expr, Abstraction):
return expr.var != var and self.occurs_in(expr.body, var)
def get_variables(self, expression: Expression) -> set:
if isinstance(expression, Variable):
return {expression.name}
elif isinstance(expression, Application):
return Evaluator.get_variables(expression.func) | Evaluator.get_variables(expression.arg)
elif isinstance(expression, Abstraction):
return {expression.var.name} | Evaluator.get_variables(expression.body)
else:
return set()
def get_used_names(self, expr: Expression) -> Set[str]:
if isinstance(expr, Variable):
return {expr.name}
elif isinstance(expr, Application):
return self.get_used_names(expr.func) | self.get_used_names(expr.arg)
elif isinstance(expr, Abstraction):
return {expr.var.name} | self.get_used_names(expr.body)
else:
return set()
def new_name(self, abstraction: Abstraction) -> str:
used_names = self.get_used_names(abstraction)
for char in 'abcdefghijklmnopqrstuvwxyz':
if char not in used_names:
return char
raise Exception("All variable names from a-z are already used!")
def singleEval(self, term: Expression, r=0) -> Tuple[Expression, str]:
if r > self.max_reductions:
return term, "None"
if isinstance(term, Variable):
return term, "None"
elif isinstance(term, Application):
if isinstance(term.func, Abstraction):
# Check if α-conversion is needed
if isinstance(term.func.body, Abstraction) and self.alpha_conversion_needed(term.func.body, term.func.var, term.arg):
# α-conversion
converted_abstraction = self.alpha_convert(term.func)
return Application(converted_abstraction, term.arg), "α"
else:
# β-reduction
replaced_term = self.substitute(term.func.body, term.func.var, term.arg)
return replaced_term, "β"
reduced_func, func_op = self.singleEval(term.func, r + 1)
if (func_op != "None"):
return Application(reduced_func, term.arg), func_op
reduced_arg, arg_op = self.singleEval(term.arg, r + 1)
if (arg_op != "None"):
return Application(term.func, reduced_arg), arg_op
else:
return Application(reduced_func, reduced_arg), "None"
elif isinstance(term, Abstraction):
expr, operation = self.singleEval(term.body, r + 1)
return Abstraction(term.var, expr), operation
def alpha_conversion_needed(self, body: Abstraction, var: Variable, val: Expression) -> bool:
# Condition 1: `var` appears free in the body of the abstraction
var_in_body = self.occurs_in(body.body, var) and body.var != var
# Condition 2: The variable of the abstraction (`body.var`) appears free in `val`
body_var_in_val = self.occurs_in(val, body.var)
return var_in_body and body_var_in_val
def substitute(self, body: Expression, var: Variable, val: Expression) -> Expression:
if isinstance(body, Variable):
if body == var:
return val
else:
return body
elif isinstance(body, Application):
return Application(self.substitute(body.func, var, val), self.substitute(body.arg, var, val))
elif isinstance(body, Abstraction):
if body.var == var:
# The variable is shadowed by this abstraction, do not replace
return body
else:
return Abstraction(body.var, self.substitute(body.body, var, val))
def alpha_convert(self, abstraction: Abstraction) -> Abstraction:
new_var = Variable(self.new_name(abstraction))
# Perform alpha conversion
if isinstance(abstraction.body, Abstraction):
abstraction = self.replace_variable(abstraction, abstraction.body.var.name, new_var.name)
return abstraction
def replace_variable(self, expression: Expression, old_var_name: str, new_var_name: str) -> Expression:
if isinstance(expression, Variable):
if expression.name == old_var_name:
return Variable(new_var_name)
else:
return expression
elif isinstance(expression, Application):
return Application(
self.replace_variable(expression.func, old_var_name, new_var_name),
self.replace_variable(expression.arg, old_var_name, new_var_name))
elif isinstance(expression, Abstraction):
return Abstraction(
Variable(new_var_name) if expression.var.name == old_var_name else expression.var,
self.replace_variable(expression.body, old_var_name, new_var_name))
else:
return expression
|
/*
* Description : Customer operations header file
* Copyright (C) 2023 Said Guouihaj
* Licence : GPLv3
*/
#pragma once
#include <iostream>
#include <string>
#include <memory>
#include "person.hpp"
#include "account.hpp"
#include "db.hpp"
class Customer : public Person {
public:
/**
* @brief Construct a new Customer object
*
*/
Customer();
/**
* @brief Destroy the Customer object
*
*/
~Customer(){};
/**
* @brief Sign in to customer account
*
* @param password entered user password
*/
void signIn(const std::string& password);
/**
* @brief get the actual user account balance
*
* @return double The value of the balance
*/
Balance viewBalance();
/**
* @brief Submit cash to user account
*
* @param amount The amount to submit
* @return true When the cash submitted successfuly
* @return false Otherwise
*/
bool submitCash(double amount);
/**
* @brief Withdraw cash from user account
*
* @param amount The amount to withdraw
* @return true If the amount withdrawed successfully
* @return false Otherwise
*/
bool withdrawCash(double amount);
/**
* @brief Set the customer user name
*
* @param userName The userName
*/
void setUserName(const std::string& userName){
this->userName = userName;
}
/**
* @brief Get the customer user name
*
* @return std::string
*/
const std::string& getUserName(){
return this->userName;
}
/**
* @brief Set the customer online state
*
* @param onlineState whether the customer is online or not
*/
void setOnlineState(bool onlineState){
this->onlineState = onlineState;
}
/**
* @brief Get the customer online state
*
* @return true if the customer is online
* @return false otherwise
*/
bool getOnlineState(){
return this->onlineState;
}
Account getAccount() const {
return this->account;
}
private:
std::string userName; // customer userName
int id; // id and accountId are successively customer and account ids
Account account;
std::unique_ptr<DBManager> db; // A pointer to the database
bool onlineState = false; // the customer online state initialized to false
};
|
import * as queryString from "query-string"
import React, {memo} from "react"
import {useHistory} from "react-router"
import ErrorBoundary from "../components/common/ErrorBoundary"
import {ExternalModule, splitUrl, useExternalLib} from "./ExternalLib"
import {ModuleString, ModuleUrl} from "./ExternalLib/types"
import {MuiThemeProvider} from "./muiThemeProvider"
import NotFound from "./errors/NotFound"
export type DynamicTabData = {
title: string,
id: string,
// expected:
// * url of working app - to include in iframe
// * url ({module}/{path}@{host}/{remoteEntry}.js) of hosted remoteEntry js file (module federation) with default exported react component - included as component
// * url of internal route in NK
url: string,
requiredPermission?: string,
type: "Local" | "IFrame" | "Remote",
}
const RemoteTabComponent = ({scope, basepath}: { scope: ModuleString, basepath?: string }) => {
const {module: {default: Component}} = useExternalLib(scope)
const history = useHistory()
return <Component basepath={basepath} onNavigate={history.push}/>
}
const RemoteModuleTab = (props: { url: ModuleUrl, basepath?: string }) => {
const [url, scope] = splitUrl(props.url)
return (
<ErrorBoundary FallbackComponent={() => <NotFound/>}>
<MuiThemeProvider>
<ExternalModule url={url}>
<RemoteTabComponent scope={scope} basepath={props.basepath}/>
</ExternalModule>
</MuiThemeProvider>
</ErrorBoundary>
)
}
const IframeTab = ({url}: { url: string }) => (
<iframe
src={queryString.stringifyUrl({url: url, query: {iframe: true}})}
width="100%"
height="100%"
frameBorder="0"
/>
)
export const DynamicTab = memo(function DynamicComponent({tab, basepath}: { tab: DynamicTabData, basepath?: string }): JSX.Element {
switch (tab.type) {
case "Remote": return <RemoteModuleTab url={tab.url} basepath={basepath}/>
case "IFrame": return <IframeTab url={tab.url}/>
}
})
|
using CoreSharp.Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace CoreSharp.Models;
/// <summary>
/// An extension to <see cref="DbConnection"/> to run quick actions on it.
/// </summary>
public sealed class DbQuery
{
// Fields
private readonly DbConnection _connection;
private readonly DbTransaction _transaction;
private int _timeoutSeconds;
// Constructors
public DbQuery(DbConnection connection)
{
ArgumentNullException.ThrowIfNull(connection);
_connection = connection;
_timeoutSeconds = _connection.ConnectionTimeout;
}
public DbQuery(DbTransaction transaction)
: this(transaction?.Connection)
{
ArgumentNullException.ThrowIfNull(transaction);
_transaction = transaction;
}
// Properties
/// <summary>
/// Gets or sets the wait time (in seconds) before terminating
/// the attempt to execute a <see cref="DbCommand.CommandTimeout"/> and generating an error.
/// </summary>
public int TimeoutSeconds
{
get => _timeoutSeconds;
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(TimeoutSeconds), $"{nameof(TimeoutSeconds)} ({value}) cannot have negative value.");
}
_timeoutSeconds = value;
}
}
/// <summary>
/// Gets or sets a value indicating how the <see cref="DbCommand.CommandText"/> property is to be interpreted.
/// </summary>
public CommandType QueryType { get; set; } = CommandType.Text;
/// <summary>
/// Represents a collection of parameters associated with a <see cref="DbCommand"/>
/// and their respective mappings to columns in a DataSet.
/// </summary>
public ICollection<DbParameter> Parameters { get; } = new HashSet<DbParameter>();
// Methods
/// <summary>
/// Adds the specified <see cref="DbParameter"/> object to the <see cref="DbParameterCollection"/>.
/// </summary>
public void AddParameter(string parameterName, object parameterValue)
{
var parameter = _connection.CreateParameter(parameterName, parameterValue);
Parameters.Add(parameter);
}
/// <summary>
/// Executes the command against its connection object,
/// returning the number of rows affected.
/// </summary>
public async Task<int> ExecuteAsync(string query, CancellationToken cancellationToken = default)
{
await using var command = await BuildDbCommandAsync(query, cancellationToken);
return await command.ExecuteNonQueryAsync(cancellationToken);
}
/// <summary>
/// Executes the command and returns the first column of the first row in the first returned result set.
/// All other columns, rows and result sets are ignored.
/// </summary>
public async Task<TResult> ExecuteAsync<TResult>(string query, CancellationToken cancellationToken = default)
{
await using var command = await BuildDbCommandAsync(query, cancellationToken);
return (TResult)await command.ExecuteScalarAsync(cancellationToken);
}
/// <summary>
/// Fills a <see cref="DataTable"/> with values from a data source using the <see cref="DbDataReader"/>.
/// If the <see cref="DataTable"/> already contains rows, the incoming data from the data source is merged with the existing rows.
/// </summary>
public async Task<int> FillAsync(string query, DataTable dataTable, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(dataTable);
await using var command = await BuildDbCommandAsync(query, cancellationToken);
await using var reader = await command.ExecuteReaderAsync(cancellationToken);
dataTable.Load(reader);
return dataTable.Rows.Count;
}
/// <inheritdoc cref="FillAsync(string, DataSet, IEnumerable{DataTableMapping}, CancellationToken)"/>
public async Task<int> FillAsync(string query, DataSet dataSet, CancellationToken cancellationToken = default)
{
var mappings = Enumerable.Empty<DataTableMapping>();
return await FillAsync(query, dataSet, mappings, cancellationToken);
}
/// <summary>
/// Adds or refreshes rows in the DataSet.
/// </summary>
public async Task<int> FillAsync(string query, DataSet dataSet, IEnumerable<DataTableMapping> tableMappings, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(dataSet);
ArgumentNullException.ThrowIfNull(tableMappings);
await using var command = await BuildDbCommandAsync(query, cancellationToken);
var adapter = _connection.CreateDataAdapter();
try
{
adapter.SelectCommand = command;
if (tableMappings.Any())
{
adapter.TableMappings.AddRange(tableMappings.ToArray());
}
return adapter.Fill(dataSet);
}
finally
{
if (adapter is IAsyncDisposable adapterAsAsyncDisposable)
{
await adapterAsAsyncDisposable.DisposeAsync();
}
if (adapter is IDisposable adapterAsDisposable)
{
adapterAsDisposable.Dispose();
}
}
}
private async Task<DbCommand> BuildDbCommandAsync(string query, CancellationToken cancellationToken = default)
{
// Open connection
if (!_connection.IsOpen())
{
await _connection.OpenAsync(cancellationToken);
}
// Prepare DbCommand
var command = _connection.CreateCommand();
command.Connection = _connection;
command.Transaction = _transaction;
command.CommandTimeout = TimeoutSeconds;
command.CommandType = QueryType;
command.CommandText = query;
if (Parameters.Count > 0)
{
command.Parameters.AddRange(Parameters.ToArray());
}
return command;
}
}
|
import { DataSource, Repository } from "typeorm";
import { IdOrganization } from "../../../organization/application/domain/idOrganization";
import { Organization } from "../../../organization/application/domain/Organization";
import { OrganizationRepository } from "../../../organization/application/ports/output/OrganizationRepository";
import { Logger } from "../../models/Logger";
import { OrganizationDBO } from "../../typeOrmData/entity/OrganizationDBO";
export class SqlOrganizationRepository implements OrganizationRepository {
#logger: Logger;
#dataSource: Repository<OrganizationDBO>;
constructor(dependencies: {logger: Logger, dataSource: DataSource}) {
this.#logger = dependencies.logger;
this.#dataSource = dependencies.dataSource.getRepository(OrganizationDBO);;
}
async store(organization: Organization): Promise<Organization> {
this.#logger.log('Executing SqlOrganizationRepository');
const organizationDBO = OrganizationDBO.fromDomain(organization)
await this.#dataSource.save(organizationDBO);
this.#logger.log(`Created organization with id ${organizationDBO.idOrganization}`);
return organization;
};
async get(key?: IdOrganization): Promise<Organization[]> {
this.#logger.log('Executing SqlOrganizationRepository');
const organizationsDBO = !!key
? await this.#dataSource.findBy({idOrganization: key?.getValue})
: await this.#dataSource.find();
console.log(organizationsDBO);
return organizationsDBO.map( (organization) => organization.toDomain());
};
async delete(key: IdOrganization): Promise<boolean> {
this.#logger.log('Executing SqlOrganizationRepository');
const result = await this.#dataSource.delete(key.getValue);
return result.affected === 1;
};
async update(key: IdOrganization, organization: Organization): Promise<boolean> {
this.#logger.log('Executing SqlOrganizationRepository');
const organizationDBO = OrganizationDBO.fromDomain(organization);
const result = await this.#dataSource.update(key.getValue, organizationDBO);
return result.affected === 1;
};
}
|
<script lang="ts">
import FaSearch from 'svelte-icons/fa/FaSearch.svelte'
export let searchResults;
let query: String;
const getMusic = async () => {
if (query) {
query = query.split(" ").join("+");
let response = await fetch(`https://itunes.apple.com/search?country=US&term=${query}&media=music&entity=album`);
let { results } = await response.json();
searchResults = results;
query = '';
console.log(searchResults);
}
}
</script>
<div>
<form on:submit|preventDefault={() => getMusic()}>
<input id="music-search" placeholder="Search for albums" bind:value={query}/>
<button type="submit"><FaSearch/></button>
</form>
</div>
<style>
form {
position: relative;
display: inline-block;
}
input {
background-color: white;
border: none;
padding: 15px;
margin: 25px 25px 0px 25px;
border-radius: 70px;
}
button {
width: 20px;
margin: 20px 20px 0px 20px;
display: block;
top: 0;
bottom: 0;
position: absolute;
right: 15px;
border-radius: 70px;
}
</style>
|
import { BasicColumn } from '/@/components/Table';
import { FormProps, FormSchema } from '/@/components/Table';
import { getDictCache } from '/@/utils/gitegg/dictUtils';
import { updateTenantStatus } from '/@/api/system/base/tenant';
import { renderStatusSwitch } from '/@/utils/gitegg/formUtils';
import dayjs from 'dayjs';
export const tenantColumn: BasicColumn[] = [
{
title: '租户名称',
align: 'center',
dataIndex: 'tenantName',
},
{
title: '域名',
align: 'center',
dataIndex: 'domainName',
},
{
title: '联系人',
align: 'center',
dataIndex: 'contacts',
},
{
title: '联系电话',
align: 'center',
dataIndex: 'contactNumber',
},
{
title: '账号限额',
align: 'center',
dataIndex: 'accountLimit',
},
{
title: '过期时间',
align: 'center',
dataIndex: 'expireTime',
},
{
title: '授权码',
align: 'center',
dataIndex: 'licenseKey',
},
{
title: '租户状态',
align: 'center',
dataIndex: 'tenantStatus',
customRender: ({ record }) => {
return renderStatusSwitch(record, updateTenantStatus, 'tenantStatus', '租户');
},
},
];
// 搜索表单定义
export function getSearchFormConfig(): Partial<FormProps> {
return {
labelWidth: 100,
autoSubmitOnEnter: true,
autoAdvancedLine: 1,
actionColOptions: {
span: 24,
},
schemas: [
{
label: '租户名称',
field: 'tenantName',
component: 'Input',
colProps: { span: 6 },
componentProps: {
placeholder: '请输入租户名称',
},
},
{
label: '域名',
field: 'domainName',
component: 'Input',
colProps: { span: 6 },
componentProps: {
placeholder: '请输入域名',
},
},
{
label: '联系电话',
field: 'contactNumber',
component: 'Input',
colProps: { span: 6 },
componentProps: {
placeholder: '请输入联系电话',
},
},
{
label: '状态',
field: 'tenantStatus',
component: 'ApiSelect',
colProps: { span: 6 },
componentProps: {
api: getDictCache,
params: { dictCode: 'ENABLE_OR_NOT' },
resultField: 'dictList',
// use name as label
labelField: 'dictName',
// use id as value
valueField: 'dictCode',
placeholder: '请选择状态',
},
},
{
label: '开始时间',
field: 'beginDateTime',
colProps: { span: 6 },
component: 'DatePicker',
componentProps: {
format: 'YYYY-MM-DD HH:mm:ss',
style: 'width:100%;',
placeholder: '请选择有效日期',
showNow: false,
showTime: {
defaultValue: dayjs().startOf('day'),
},
},
},
{
label: '结束时间',
field: 'endDateTime',
colProps: { span: 6 },
component: 'DatePicker',
componentProps: {
format: 'YYYY-MM-DD HH:mm:ss',
style: 'width:100%;',
placeholder: '请选择有效日期',
showNow: false,
showTime: {
defaultValue: dayjs().endOf('day'),
},
},
},
],
};
}
export const tenantForm: FormSchema[] = [
{
field: 'id',
label: '主键',
show: false,
component: 'Input',
},
{
label: '租户名称',
field: 'tenantName',
component: 'Input',
componentProps: {
placeholder: '请输入租户名称',
},
required: true,
},
{
label: '域名',
field: 'domainName',
component: 'Input',
componentProps: {
placeholder: '请输入域名',
},
required: true,
},
{
label: '上传背景图片',
field: 'backgroundImage',
component: 'CommonUpload',
componentProps: {
uploadBtnText: '上传背景图片',
maxNumber: 1,
accessPrivate: false,
uploadType: 'image',
},
rules: [{ required: true, message: '请上传背景图片', trigger: 'change' }],
},
{
label: '联系人',
field: 'contacts',
component: 'Input',
componentProps: {
placeholder: '联系人',
},
required: true,
},
{
label: '联系电话',
field: 'contactNumber',
component: 'Input',
componentProps: {
placeholder: '请输入联系电话',
},
required: true,
},
{
label: '联系地址',
field: 'address',
component: 'Input',
componentProps: {
placeholder: '请输入联系联系地址',
},
required: true,
},
{
label: '账号限额',
field: 'accountLimit',
component: 'Input',
componentProps: {
placeholder: '输入账号限额',
},
required: true,
},
{
label: '过期时间',
field: 'expireTime',
component: 'DatePicker',
componentProps: {
format: 'YYYY-MM-DD HH:mm:ss',
style: 'width:100%;',
placeholder: '请选择过期时间',
showTime: {
defaultValue: dayjs().endOf('day'),
},
},
required: true,
},
{
label: '授权码',
field: 'licenseKey',
component: 'Input',
componentProps: {
placeholder: '输入授权码',
},
required: true,
},
{
label: '租户状态',
field: 'tenantStatus',
component: 'ApiRadioGroup',
defaultValue: '1',
componentProps: {
api: getDictCache,
params: { dictCode: 'ENABLE_OR_NOT' },
resultField: 'dictList',
// use name as label
labelField: 'dictName',
// use id as value
valueField: 'dictCode',
placeholder: '请选择状态',
},
required: true,
},
{
label: '备注',
field: 'comments',
component: 'InputTextArea',
},
];
|
import { prismaClient } from '../../infra/database/prisma-client';
import { kafka } from '../../infra/provider/kafka';
import { KafkaSendMessage } from '../../infra/provider/kafka/producer';
type CreateCustomerRequest = {
name: string;
password: string;
email: string;
phone: string;
};
export class CreateCustomerUseCase {
constructor() {}
async execute(data: CreateCustomerRequest) {
const customer = await prismaClient.customer.findFirst({
where: { email: data.email },
});
if (customer) throw new Error('Customer already exists!');
const customerCreated = await prismaClient.customer.create({
data: {
...data,
},
});
const kafkaProducer = new KafkaSendMessage();
await kafkaProducer.execute('CUSTOMER_CREATED', {
id: customerCreated.id,
email: customerCreated.email,
});
return customerCreated;
}
}
|
# frozen_string_literal: true
# == Schema Information
#
# Table name: topics
#
# id :integer not null, primary key
# level :integer not null
# name :string not null
# visible :boolean default(TRUE), not null
# created_at :datetime
# updated_at :datetime
# parent_id :integer
#
# Foreign Keys
#
# fk_rails_... (parent_id => topics.id)
#
FactoryBot.define do
factory :topic do
sequence(:name) { |i| "Topic #{i}" }
level { rand(1..3) }
visible { true }
parent_id { nil }
after(:build) do |topic|
topic.parent_id = Topic.find_or_create_by!(level: 3, name: 'level three').id if topic.level_two?
if topic.level_one?
level_three_topic = Topic.find_or_create_by!(level: 3, name: 'level three')
topic.parent_id = Topic.find_or_create_by!(level: 2, name: 'level two', parent_id: level_three_topic.id).id
end
end
trait :with_change_log do
after(:create) do |t|
create(:change_log, changed_record: t)
end
end
end
end
|
"use client";
import React, { useEffect } from "react";
import { useMap } from "react-leaflet";
import L from "leaflet";
import "leaflet-polylinedecorator";
import "./mapComponent.css";
const generatePolylinePositions = (data) =>
data.map((city) => [city.mlatitute, city.mlongitute]);
const MyMapComponent = ({ data }) => {
const map = useMap();
useEffect(() => {
if (data && data.length >= 1 && data[0]?.mlatitute !== undefined && data[0]?.mlongitute !== undefined) {
const startMarker = L.marker(
[data[0].mlatitute, data[0].mlongitute],
{
icon: createMarkerIcon(0),
}
).addTo(map);
map.setView([data[0]?.mlatitute, data[0]?.mlongitute], 18);
}
// console.log("first ",data);
if (data && data.length > 1) {
// console.log("second ",data);
for (let i = 0; i < data?.length - 1; i++) {
const start = L.latLng(data[i]?.mlatitute, data[i]?.mlongitute);
const end = L.latLng(
data[i + 1].mlatitute,
data[i + 1].mlongitute
);
const color =
data[i]?.mlatitute === data[i + 1]?.mlatitute &&
data[i]?.mlongitute === data[i + 1]?.mlongitute
? "red"
: "green";
const polyline = L.polyline([start, end], {
color: color,
}).addTo(map);
const arrowDecorator = L.polylineDecorator(polyline, {
patterns: [
{
offset: "50%",
repeat: 0,
symbol: L.Symbol.arrowHead({
pixelSize: 10,
polygon: false,
pathOptions: { color: color },
}),
},
],
}).addTo(map);
const label = `${i + 1}`;
// console.log(label);
const markerColor =
data[i]?.mlatitute === data[i + 1]?.mlatitute &&
data[i]?.mlongitute === data[i + 1]?.mlongitute
? "red"
: "green";
const icon = createMarkerIcon(label, markerColor);
const marker = L.marker(end, {
icon,
});
marker.addTo(map);
}
const bounds = L.latLngBounds(
generatePolylinePositions(data),
data.map((location) =>
L.latLng(location.mlatitute, location.mlongitute)
)
);
// console.log("second ",data);
map.fitBounds(bounds, { maxZoom: 18 });
}
}, [data, map]);
const createMarkerIcon = (label, color = "green") => {
const labelContainerStyle =
color === "red"
? "background-color: red; color: white;"
: "background-color: sky-blue; color: white;";
return L.divIcon({
className: "custom-marker-label",
html: `<div class="label-container" style="${labelContainerStyle}">${label}</div>`,
});
};
return null;
};
export default MyMapComponent;
// import React, { useEffect } from "react";
// import { useMap } from "react-leaflet";
// import L, { marker } from "leaflet";
// import "leaflet-routing-machine";
// import "leaflet-polylinedecorator";
// import "./mapComponent.css";
// const generateWaypoints = (data) =>
// data.map((city) => L.latLng(city.mlatitute, city.mlongitute));
// const MyMapComponent = ({ data }) => {
// const map = useMap();
// useEffect(() => {
// // console.log("data:", data);
// if (data && data.length > 1) {
// const waypoints = generateWaypoints(data);
// const routingControl = L.Routing.control({
// waypoints,
// lineOptions: {
// styles: [{ color: "green", opacity: 1, weight: 5 }],
// },
// addWaypoints: false,
// draggableWaypoints: false,
// fitSelectedRoutes: "smart",
// createMarker: function (i, waypoint, n) {
// if (i === 0 || i === n - 1) {
// return null;
// }
// const label = `${i}`;
// const icon = L.divIcon({
// className: "custom-marker-label",
// html: `<div class="label-container">${label}</div>`,
// });
// const marker = L.marker(waypoint.latLng, {
// icon,
// });
// return marker;
// },
// });
// routingControl.addTo(map);
// routingControl.on("routesfound", function (e) {
// const routes = e.routes[0].coordinates;
// console.log(routes);
// // Create a marker instance for animation
// const animationMarker = L.marker(routes[0], { opacity: 0 }).addTo(map);
// routes.forEach((coord, index) => {
// setTimeout(() => {
// animationMarker.setLatLng([coord.lat, coord.lng]);
// }, 100 * index);
// });
// });
// waypoints.forEach((waypoint, index) => {
// const label = `${index + 1}`;
// const icon = L.divIcon({
// className: "custom-marker-label",
// html: `<div class="label-container">${label}</div>`,
// });
// const marker = L.marker(waypoint, {
// icon,
// });
// marker.addTo(map);
// });
// }
// }, [data, map]);
// return null;
// };
// export default MyMapComponent;
|
declare integer as UI_MAXIMUM_DIALOG_WIDTH = 40;
lock UI_MAXIMUM_DIALOG_WIDTH;
declare function PrintArray(&A)
begin
Println("Array of length " + A.length);
Println("Array[" + A.start + " to " + A.finish + "] = {");
declare integer as i;
for i = A.start to A.finish
Println(" " + A[i]);
Println("}");
end;
declare function DialogBox(msg, &prompt, &allowable)
begin
declare integer as i;
declare reference strarray = {};
while msg.length > 0 do
begin
declare integer as index = UI_MAXIMUM_DIALOG_WIDTH;
PrintArray(strarray);
Newln();
if index < msg.length then
begin
if Ord(" ") != msg[index] then
index = StrFindLastOf(msg, " ", index, true);
Append(strarray, strarray.finish + 1, StrLeft(msg, index));
msg = StrRight(msg, index + 1);
end;
else
begin
Append(strarray, strarray.finish + 1, msg);
msg = "";
end;
end;
Append(strarray, strarray.finish + 1, "");
Append(strarray, strarray.finish + 1, CenterJustify(UI_MAXIMUM_DIALOG_WIDTH, prompt));
declare integer as width = 0;
for i = strarray.start to strarray.finish
if strarray[i].length > width then
width = strarray[i].length;
width = width + 6;
lock width;
Println("Printing the array...");
Newln();
Println(strarray);
Newln();
Newln();
for i = strarray.start to strarray.finish
begin
Print(i + ". " + LeftJustify(width - 6, strarray[i]));
end;
declare integer as ch;
repeat
ch = ReadCh();
until STRINVALID != StrFind(STRPRINTABLE, ch, 0, false);
end;
#DialogBox(
# "This is an example of a really long string value that must be displayed in the terminal window.",
# "Press [space] to continue...",
# " "
#);
declare reference A = {};
Newln();
PrintArray(A);
Newln();
Insert(A, A.finish + 1, 1);
PrintArray(A);
Newln();
Insert(A, A.finish + 1, 2);
PrintArray(A);
Newln();
Insert(A, A.finish + 1, 3);
Newln();
PrintArray(A);
Newln();
|
// src/components/CustomModal.tsx
import { FC } from 'react';
import { Modal} from '@mui/material';
import * as S from './styles'
import { IoMdCloseCircleOutline } from 'react-icons/io';
type CustomModalProps = {
onClose: () => void;
open: boolean;
image: string;
title: string;
content: string;
available?: string;
rating: string;
};
const MyModal: FC<CustomModalProps> = ({ ...props }) => {
return (
<Modal
open={props.open}
onClose={props.onClose}
aria-labelledby="modal-title"
aria-describedby="modal-description"
>
<S.StyledBox>
<S.Img src={props.image} alt="" />
<S.ContentContainer>
<h1>{props.title}</h1>
<p>{props.content}</p>
<div>
{ props.available ? <p>{props.available}</p> : ''}
<h3>Avaliação</h3>
<p>{props.rating}</p>
</div>
</S.ContentContainer>
<IoMdCloseCircleOutline
size={45}
onClick={props.onClose}
className='icon'
/>
</S.StyledBox>
</Modal>
);
};
export default MyModal;
|
Complete project summary:
`memory_store.py`:
1. `logger(message: str, level: int = 1) -> None`:
- Logs messages according to the specified log level.
- Input: message (str) and an optional log level (int, default is 1).
- Output: None (prints log messages to the console).
2. `store_filtered_chunks(chroma_handler: ChromaDBHandler, prompt: str, result: str, name: str) -> None`:
- Stores the filtered chunks of the given prompt and result.
- Input: chroma_handler (ChromaDBHandler object), prompt (str), result (str), and name (str).
- Output: None (stores data in the ChromaDB collection).
3. `store_chunk(chroma_handler: ChromaDBHandler, chunk: str, name: str, chunk_type: str, prompt_id: str) -> None`:
- Stores a single chunk of text data with the associated metadata.
- Input: chroma_handler (ChromaDBHandler object), chunk (str), name (str), chunk_type (str), and prompt_id (str).
- Output: None (stores data in the ChromaDB collection).
`memory_retrieve.py`:
1. `filter_memories_by_distance(retrieved_memories: dict, distance_value: float, higher_than: bool = True) -> List[str]`:
- Filters the retrieved memories based on their distance value.
- Input: retrieved_memories (dict), distance_value (float), and an optional higher_than flag (bool, default is True).
- Output: filtered_memories (list of strings).
2. `get_filtered_memories(prompt: str, name: str, chunktype: str, distance_value: float = 0.1) -> List[str]`:
- Retrieves and filters memories based on the given prompt, name, chunk type, and an optional distance value.
- Input: prompt (str), name (str), chunktype (str), and an optional distance_value (float, default is 0.1).
- Output: filtered_memories (list of strings).
`text_generator.py`:
1. `get_config() -> dict`:
- Loads the configuration data from the `config.json` file.
- Input: None
- Output: A dictionary containing the configuration data.
2. `run(prompt: str, **kwargs) -> str`:
- Sends a prompt to a remote large language model for processing and returns the generated result.
- Input: prompt (str) and optional keyword arguments (**kwargs) to override default parameters.
- Output: The generated text result (str).
`config.json`:
- Contains the HOST address and default parameters for the text generation API.
Project Overview:
The Autonomous Agent Creation System project aims to leverage a large language model (LLM) to develop a system
that allows users to create and configure a chain of tasks in order to achieve a specific goal.
The system will utilize a modular task system, a graphical user interface (GUI), and a vector database memory storage
to enhance the performance and context of the LLM. This will enable the task agents to cooperate and optimize the outcome of the tasks effectively.
Recommendations:
1. Create a GUI for users to define tasks, inputs, and outputs easily and intuitively.
2. Implement a system that can parse the user-defined goal and generate the required tasks automatically.
3. Develop an algorithm to optimize the task chain, either by the user's intervention or automatically.
4. Incorporate feedback loops to improve the system's overall performance and adaptability.
5. Allow for seamless integration of external tools, libraries, or APIs as part of the task chain.
6. Ensure data security and privacy by encrypting sensitive data and implementing access controls.
7. Monitor and log system performance for debugging and maintenance purposes.
Optimal Task List:
1. Design the system architecture and outline its core components.
2. Develop the modular task system, allowing for task definition, input, and output functions.
3. Create the GUI for users to interact with the task system and configure task chains.
4. Implement the LLM integration to automatically generate task chains based on user goals.
5. Develop the memory storage functionality for providing task-based memory to task agents.
6. Create algorithms for optimizing task chains and improving the LLM context.
7. Implement a feedback loop mechanism for improving system performance and adaptability.
8. Integrate external tools, libraries, or APIs as necessary.
9. Ensure data security, privacy, and access controls.
10. Monitor, log, and maintain system performance.
Brief Project Description:
The Autonomous Agent Creation System is a project that aims to create a user-friendly
interface for configuring task chains to achieve specific goals. It leverages a large language model to generate
tasks automatically, optimize task chains, and provide contextual information. The system utilizes a modular task system,
a graphical user interface, and a vector database memory storage to enhance the overall performance and adaptability of the LLM,
ensuring the efficient completion of tasks.
Here's a high-level overview of the proposed system architecture:
1. User Interface (UI): A graphical user interface (GUI) that allows users to define tasks, inputs, and outputs easily and intuitively. The UI should be user-friendly and provide clear instructions on how to create and configure task chains.
2. Task System: The core of the project, responsible for handling tasks, inputs, and outputs. The task system should be modular and allow users to define custom tasks along with their required input and output functions. It should also enable users to create and manage task chains.
3. LLM Integration: The system will integrate with a large language model to automatically generate task chains based on user goals. The LLM should be used to provide context and optimization for the task chains, ensuring that the generated results are relevant and accurate.
4. Memory Storage: A vector database memory storage will provide task-based memory to task agents, allowing them to improve their context and enhance the LLM's performance. This component should be designed to handle the storage and retrieval of data efficiently and securely.
5. Task Chain Optimization: An algorithm that optimizes task chains by reordering tasks, modifying task parameters, or suggesting alternative tasks to achieve the user's goal more efficiently.
6. Feedback Loop: A mechanism that collects user feedback and system performance data to improve the system's adaptability and performance over time.
7. External Integrations: The system should allow for seamless integration with external tools, libraries, or APIs to support additional functionality or enhance the capabilities of the task agents.
8. Monitoring and Logging: The system should log and monitor its performance to facilitate debugging and maintenance.
Here's a visual representation of the system architecture:
```
+---------------------+
| User Interface (UI) |
+---------------------+
|
v
+----------------+
| Task System |
+----------------+
|
v
+----------------+
| LLM Integration|
+----------------+
|
v
+----------------+
| Memory Storage |
+----------------+
|
v
+---------------------+
| Task Chain Optimization |
+---------------------+
|
v
+-------------+
| Feedback Loop |
+-------------+
|
v
+---------------------+
| External Integrations |
+---------------------+
|
v
--------+
| Monitoring and Logging |
+----------------------+
```
|
export module cmoon.type_traits:function_traits;
import std.core;
namespace cmoon
{
export
template<typename F>
struct function_traits;
export
template<typename Return, typename... Args> // Free Function
struct function_traits<Return(Args...)>
{
using result_type = Return;
using decay_type = Return(*)(Args...);
using arguments = std::tuple<Args...>;
template<std::size_t I>
using argument = std::tuple_element_t<I, arguments>;
static constexpr auto arity {sizeof...(Args)};
};
export
template<typename Return, typename... Args> // Function Pointers
struct function_traits<Return(*)(Args...)> : function_traits<Return(Args...)> {};
export
template<typename Class, class Return, typename... Args> // Member Functions
struct function_traits<Return(Class::*)(Args...)> : function_traits<Return(Args...)>
{
using class_type = Class;
};
export
template<typename Class, class Return, typename... Args> // const member functions and lambdas
struct function_traits<Return(Class::*)(Args...) const> : function_traits<Return(Class::*)(Args...)> {};
}
|
// Header.js
import React, { useState, useRef } from "react";
import "./Header.css";
import MyTime from "../assets/MyTime.png";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faUserCircle,
faUser,
faSearch,
faCog,
faSignOut,
} from "@fortawesome/free-solid-svg-icons";
import Search from "./Search";
import SettingsModal from "./SettingsModal";
const Header = ({
eventsData,
onCalendarIconClick,
onToggleDarkMode,
isDarkMode,
}) => {
const [isDropdownOpen, setDropdownOpen] = useState(false);
const [isSearchModalOpen, setSearchModalOpen] = useState(false);
const [isSettingsModalOpen, setSettingsModalOpen] = useState(false);
const dropdownRef = useRef(null);
const toggleDropdown = () => {
setDropdownOpen(!isDropdownOpen);
};
const toggleSearchModal = () => {
setSearchModalOpen(!isSearchModalOpen);
setDropdownOpen(false);
};
const toggleSettingsModal = () => {
setSettingsModalOpen(!isSettingsModalOpen);
setDropdownOpen(false);
};
return (
<div className="header">
<div className="header-logo">
<p className="header-image">
<img className="header-image-picture" src={MyTime} alt="MyTimeLogo" />
</p>
<h1>MyTime</h1>
</div>
<div className="header-buttons">
<div>
<button className="search-button" onClick={toggleSearchModal}>
<FontAwesomeIcon icon={faSearch} />
</button>
{isSearchModalOpen && eventsData && (
<Search
eventsData={eventsData}
onClose={toggleSearchModal}
onCalendarIconClick={onCalendarIconClick}
/>
)}
</div>
<div className="user-dropdown" ref={dropdownRef}>
<button className="user-button" onClick={toggleDropdown}>
<FontAwesomeIcon icon={faUserCircle} />
</button>
{isDropdownOpen && (
<div className="dropdown-menu">
<p className="menu-item" onClick={toggleSettingsModal}>
<FontAwesomeIcon icon={faUser} />
Demo
</p>
<p className="menu-item" onClick={toggleSettingsModal}>
<FontAwesomeIcon icon={faCog} />
Settings
</p>
<p className="menu-item logout">
<FontAwesomeIcon icon={faSignOut} />
Logout
</p>
</div>
)}
</div>
</div>
{isSettingsModalOpen && (
<SettingsModal
onClose={toggleSettingsModal}
onToggleDarkMode={onToggleDarkMode}
isDarkMode={isDarkMode}
/>
)}
</div>
);
};
export default Header;
|
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragments.SignUpUserFrag">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:src="@drawable/reg" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:fontFamily="@font/poppins_bold"
android:text="@string/create_new_account"
android:textAlignment="center"
android:textSize="28sp" />
<!-- <TextView-->
<!-- android:layout_width="wrap_content"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:text="Already Registered? "-->
<!-- android:textColor="@color/Black"-->
<!-- android:fontFamily="@font/poppins"-->
<!-- android:layout_marginLeft="30dp"-->
<!-- android:textAlignment="center"-->
<!-- android:textSize="14sp"/>-->
</LinearLayout>
<ProgressBar
android:id="@+id/register_progress_bar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="30dp"
android:indeterminate="true"
android:indeterminateDrawable="@drawable/progress_bar_layout"
android:outlineAmbientShadowColor="@color/black"
android:padding="25dp"
android:visibility="gone" />
<LinearLayout
android:id="@+id/register_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="@+id/fullName"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="@drawable/edittextbg"
android:fontFamily="@font/poppins"
android:hint="@string/full_name"
android:inputType="text"
android:paddingStart="8dp"
android:singleLine="true" />
<EditText
android:id="@+id/registerMail"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="@dimen/dimen_10"
android:layout_marginRight="20dp"
android:background="@drawable/edittextbg"
android:fontFamily="@font/poppins"
android:hint="@string/email"
android:inputType="textEmailAddress"
android:paddingStart="8dp"
android:singleLine="true" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="@dimen/dimen_10"
android:layout_marginRight="20dp"
android:background="@drawable/edittextbg"
android:fontFamily="@font/poppins"
android:hint="@string/password"
android:inputType="textPassword"
android:paddingStart="8dp"
android:singleLine="true" />
<EditText
android:id="@+id/confirmPwd"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="@dimen/dimen_10"
android:layout_marginRight="20dp"
android:background="@drawable/edittextbg"
android:fontFamily="@font/poppins"
android:hint="@string/confirm_password"
android:inputType="textPassword"
android:paddingStart="8dp"
android:singleLine="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="@dimen/dimen_10"
android:layout_marginRight="20dp"
android:orientation="horizontal">
<CheckBox
android:id="@+id/checkbox"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_gravity="center"
android:layout_marginEnd="4dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:fontFamily="@font/poppins"
android:text="@string/by_continuing_you_agree_with_our_term_and_conditions_and_privacy_policy"
android:textSize="12sp" />
</LinearLayout>
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/register"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="@dimen/dimen_10"
android:layout_marginRight="20dp"
android:layout_marginBottom="@dimen/dimen_10"
android:background="@drawable/edittextbg"
android:backgroundTint="@color/purple_500"
android:enabled="false"
android:fontFamily="@font/poppins_bold"
android:text="@string/sign_up"
android:textAllCaps="false"
android:textColor="@color/white"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:fontFamily="@font/poppins"
android:text="@string/already_registered"
android:textSize="12sp" />
<TextView
android:id="@+id/register_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="25dp"
android:fontFamily="@font/poppins"
android:text="@string/login"
android:textColor="@color/purple_500"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
|
第二章 PL的"Hello World"LED实验
**实验Vivado工程为“led”。**
对于Versal来说PL(FPGA)开发是至关重要的,这也是Versal比其他ARM的有优势的地方,可以定制化很多ARM端的外设,在定制ARM端的外设之前先让我们通过一个LED例程来熟悉PL(FPGA)的开发流程,熟悉Vivado软件的基本操作,这个开发流程和不带ARM的FPGA芯片完全一致。
在本例程中,我们要做的是LED灯控制实验,每秒钟控制开发板上的LED灯翻转一次,实现亮、灭、亮、灭的控制。
2.1 LED硬件介绍
----------------
开发板的PL部分连接了1个红色的用户LED灯。这1个灯完全由PL控制。如果PL_LED1为高电平,三级管导通,灯则会亮,否则会灭。
.. image:: images/media/image29.png
:width: 3.22222in
:height: 2.47569in
2.2 创建Vivado工程
--------------------
1) 启动Vivado,在Windows中可以通过双击Vivado快捷方式启动
2) 在Vivado开发环境里点击“Create New Project”,创建一个新的工程。
.. image:: images/media/image30.png
:width: 4.90245in
:height: 3.54576in
3) 弹出一个建立新工程的向导,点击“Next”
.. image:: images/media/image31.png
:width: 4.82126in
:height: 4.08408in
4) 在弹出的对话框中输入工程名和工程存放的目录,我们这里取一个led的工程名。需要注意工程路径“Project
location”不能有中文空格,路径名称也不能太长。
.. image:: images/media/image32.png
:width: 4.85347in
:height: 3.06944in
5) 在工程类型中选择“RTL Project”
.. image:: images/media/image33.png
:width: 5.26181in
:height: 3.32917in
6) 目标语言“Target
language”选择“Verilog”,虽然选择Verilog,但VHDL也可以使用,支持多语言混合编程。
.. image:: images/media/image34.png
:width: 5.20556in
:height: 3.27708in
7) 点击“Next”,不添加任何文件
.. image:: images/media/image35.png
:width: 5.39514in
:height: 3.34097in
8) 选择“xc2302-sfva784-1LP-e-S”
.. image:: images/media/image36.png
:width: 5.13403in
:height: 4.59444in
9) 点击“Finish”就可以完成以后名为“led”工程的创建。
.. image:: images/media/image37.png
:width: 5.40347in
:height: 3.40417in
10) Vivado软件界面
.. image:: images/media/image38.png
:width: 4.61346in
:height: 3.97672in
2.3 创建Verilog HDL文件点亮LED
-------------------------------
1) 点击Project Manager下的Add Sources图标(或者使用快捷键Alt+A)
.. image:: images/media/image39.png
:width: 3.88736in
:height: 2.26719in
2) 选择添加或创建设计源文件“Add or create design sources”,点击“Next”
.. image:: images/media/image40.png
:width: 5.11453in
:height: 3.45338in
3) 选择创建文件“Create File”
.. image:: images/media/image41.png
:width: 5.19748in
:height: 3.5094in
4) 文件名“File name”设置为“led”,点击“OK”
.. image:: images/media/image42.png
:width: 4.86244in
:height: 3.28317in
5) 点击“Finish”,完成“led.v”文件添加
.. image:: images/media/image43.png
:width: 4.89769in
:height: 3.30698in
6) 在弹出的模块定义“Define
Module”,中可以指定“led.v”文件的模块名称“Module
name”,这里默认不变为“led”,还可以指定一些端口,这里暂时不指定,点击“OK”。
.. image:: images/media/image44.png
:width: 4.48908in
:height: 3.21372in
7) 在弹出的对话框中选择“Yes”
.. image:: images/media/image45.png
:width: 4.33533in
:height: 3.10366in
8) 双击“led.v”可以打开文件,然后编辑
.. image:: images/media/image46.png
:width: 4.52898in
:height: 3.45462in
9) 编写“led.v”,这里定义了一个32位的寄存器timer,
用于循环计数0~199999999(1秒钟), 计数到199999999(1秒)的时候,
寄存器timer变为0,并翻转四个LED。这样原来LED是灭的话,就会点亮,如果原来LED为亮的话,就会熄灭。由于输入时钟为200MHz的差分时钟,因此需要添加IBUFDS原语连接差分信号,编写好后的代码如下:
+-----------------------------------------------------------------------+
| \`timescale 1ns **/** 1ps |
| |
| **module** led\ **(** |
| |
| //Differential system clock |
| |
| **input** sys_clk_p\ **,** |
| |
| **input** sys_clk_n\ **,** |
| |
| **input** rst_n\ **,** |
| |
| **output** **reg** led |
| |
| **);** |
| |
| **reg[**\ 31\ **:**\ 0\ **]** timer_cnt\ **;** |
| |
| **wire** sys_clk **;** |
| |
| IBUFDS IBUFDS_inst **(** |
| |
| **.**\ O\ **(**\ sys_clk\ **),** // Buffer output |
| |
| **.**\ I\ **(**\ sys_clk_p\ **),** // Diff_p buffer input (connect |
| directly to top-level port) |
| |
| **.**\ IB\ **(**\ sys_clk_n\ **)** // Diff_n buffer input (connect |
| directly to top-level port) |
| |
| **);** |
| |
| **always@(posedge** sys_clk\ **)** |
| |
| **begin** |
| |
| **if** **(!**\ rst_n\ **)** |
| |
| **begin** |
| |
| led **<=** 1'b0 **;** |
| |
| timer_cnt **<=** 32'd0 **;** |
| |
| **end** |
| |
| **else** **if(**\ timer_cnt **>=** 32'd199_999_999\ **)** //1 second |
| counter, 200M-1=199999999 |
| |
| **begin** |
| |
| led **<=** **~**\ led\ **;** |
| |
| timer_cnt **<=** 32'd0\ **;** |
| |
| **end** |
| |
| **else** |
| |
| **begin** |
| |
| led **<=** led\ **;** |
| |
| timer_cnt **<=** timer_cnt **+** 32'd1\ **;** |
| |
| **end** |
| |
| **end** |
| |
| **endmodule** |
+-----------------------------------------------------------------------+
10) 编写好代码后保存
2.4 添加管脚约束
-----------------
Vivado使用的约束文件格式为xdc文件。xdc文件里主要是完成管脚的约束,时钟的约束,
以及组的约束。这里我们需要对led.v程序中的输入输出端口分配到FPGA的真实管脚上。
1) 新建约束文件
.. image:: images/media/image47.png
:width: 5.99722in
:height: 2.96736in
2) Create File
.. image:: images/media/image48.png
:width: 4.95556in
:height: 3.31319in
.. image:: images/media/image49.png
:width: 2.33472in
:height: 1.8in
3) 将复位信号rst_n绑定到PL端的按键,给LED和时钟分配管脚、电平标准,约束如下
.. image:: images/media/image50.png
:width: 4.82986in
:height: 1.96389in
+-----------------------------------------------------------------------+
| set_property PACKAGE_PIN AB23 [get_ports sys_clk_p] |
| |
| set_property PACKAGE_PIN F21 [get_ports rst_n] |
| |
| set_property PACKAGE_PIN E20 [get_ports led] |
| |
| set_property IOSTANDARD LVCMOS15 [get_ports led] |
| |
| set_property IOSTANDARD LVCMOS15 [get_ports rst_n] |
| |
| set_property IOSTANDARD LVDS15 [get_ports sys_clk_p] |
| |
| create_clock -period 5.000 -name sys_clk_p -waveform {0.000 2.500} |
| [get_ports sys_clk_p] |
+-----------------------------------------------------------------------+
2.5 生成pdi文件
-----------------
1) 编译的过程可以细分为综合、布局布线、生成bit文件等,这里我们直接点击“Generate
Device Image”,直接生成pdi文件。
.. image:: images/media/image51.png
:width: 1.8375in
:height: 0.75069in
2) 在弹出的对话框中可以选择任务数量,这里和CPU核心数有关,一般数字越大,编译越快,点击“OK”
.. image:: images/media/image52.png
:width: 2.2739in
:height: 1.78158in
3) 编译的时候发现有报错
.. image:: images/media/image53.png
:width: 5.98611in
:height: 0.78264in
[DRC CIPS-2] Versal CIPS exists check - wdi: Versal designs must
contain a CIPS IP in the netlist hierarchy to function properly.
Please create an instance of the CIPS IP and configure it. Without a
CIPS IP in the design, Vivado will not generate a CDO for the PMC,
an elf for the PLM.
从报错来看,versal设计是必须包含CIPS的,也就是PS端,因此需要添加CIPS核。
4) 选择Create Block Design
.. image:: images/media/image54.png
:width: 2.26458in
:height: 2.29792in
.. image:: images/media/image55.png
:width: 3.19792in
:height: 1.73125in
5) 添加CIPS
.. image:: images/media/image56.png
:width: 5.19167in
:height: 2.67778in
.. image:: images/media/image57.png
:width: 2.63333in
:height: 2.09792in
6) 双击CIPS,选择PL_Subsystem,只有PL端的逻辑
.. image:: images/media/image58.png
:width: 4.18542in
:height: 3.7875in
7) 右键Generate Output products
.. image:: images/media/image59.png
:width: 2.89653in
:height: 1.85833in
.. image:: images/media/image60.png
:width: 2.08403in
:height: 2.85278in
8) 之后右键创建HDL
.. image:: images/media/image61.png
:width: 3.44167in
:height: 1.77569in
.. image:: images/media/image62.png
:width: 3.06875in
:height: 1.50694in
9) 在led.v中例化PS端文件
.. image:: images/media/image63.png
:width: 1.49444in
:height: 0.55972in
.. image:: images/media/image64.png
:width: 3.28958in
:height: 1.52986in
10) 之后再Generate
Bitstream,编译中没有任何错误,编译完成,弹出一个对话框让我们选择后续操作,可以选择“Open
Hardware Manger”,当然,也可以选择“Cancel”,我们这里选择
“Cancel”,先不下载。
.. image:: images/media/image65.png
:width: 2.51597in
:height: 1.51181in
2.6 Vivado仿真
---------------
接下来我们不妨小试牛刀,利用Vivado自带的仿真工具来输出波形验证流水灯程序设计结果和我们的预想是否一致(注意:在生成bit文件之前也可以仿真)。具体步骤如下:
1. 设置Vivado的仿真配置,右击SIMULATION中Simulation Settings。
.. image:: images/media/image66.png
:width: 2.71162in
:height: 2.82275in
2. 在Simulation
Settings窗口中进行如下图来配置,这里设置成50ms(根据需要自行设定),其它按默认设置,单击OK完成。
.. image:: images/media/image67.png
:width: 4.16967in
:height: 3.68114in
3. 添加激励测试文件,点击Project Manager下的Add
Sources图标,按下图设置后单击Next。
.. image:: images/media/image68.png
:width: 4.24388in
:height: 2.19655in
4. 点击Create File生成仿真激励文件。
.. image:: images/media/image69.png
:width: 3.47146in
:height: 2.72528in
在弹出的对话框中输入激励文件的名字,这里我们输入名为vtf_led_test。
.. image:: images/media/image70.png
:width: 2.21088in
:height: 1.80096in
5. 点击Finish按钮返回。
.. image:: images/media/image71.png
:width: 3.95375in
:height: 3.03139in
这里我们先不添加IO Ports,点击OK。
.. image:: images/media/image72.png
:width: 3.1395in
:height: 2.2426in
在Simulation
Sources目录下多了一个刚才添加的vtf_led_test文件。双击打开这个文件,可以看到里面只有module名的定义,其它都没有。
.. image:: images/media/image73.png
:width: 4.14019in
:height: 2.71368in
6. 接下去我们需要编写这个vtf_led_test.v文件的内容。首先定义输入和输出信号,然后需要实例化led_test模块,让led_test程序作为本测试程序的一部分。再添加复位和时钟的激励。完成后的vtf_led_test.v文件如下:
+-----------------------------------------------------------------------+
| \`timescale 1ns **/** 1ps |
| |
| // Module Name: vtf_led_test |
| |
| |
| **module** vtf_led_test\ **;** |
| |
| // Inputs |
| |
| **reg** sys_clk_p\ **;** |
| |
| **reg** rst_n **;** |
| |
| **wire** sys_clk_n\ **;** |
| |
| // Outputs |
| |
| **wire** led\ **;** |
| |
| // Instantiate the Unit Under Test (UUT) |
| |
| led uut **(** |
| |
| **.**\ sys_clk_p\ **(**\ sys_clk_p\ **),** |
| |
| **.**\ sys_clk_n\ **(**\ sys_clk_n\ **),** |
| |
| **.**\ rst_n\ **(**\ rst_n\ **),** |
| |
| **.**\ led\ **(**\ led\ **)** |
| |
| **);** |
| |
| **initial** |
| |
| **begin** |
| |
| // Initialize Inputs |
| |
| sys_clk_p **=** 0\ **;** |
| |
| rst_n **=** 0\ **;** |
| |
| // Wait for global reset to finish |
| |
| **#**\ 1000\ **;** |
| |
| rst_n **=** 1\ **;** |
| |
| **end** |
| |
| //Create clock |
| |
| **always** **#**\ 2.5 sys_clk_p **=** **~** sys_clk_p\ **;** |
| |
| **assign** sys_clk_n **=** **~**\ sys_clk_p **;** |
| |
| **endmodule** |
+-----------------------------------------------------------------------+
7) 编写好后保存,vtf_led_test.v自动成了这个仿真Hierarchy的顶层了,它下面是设计文件led_test.v。
.. image:: images/media/image74.png
:width: 2.63408in
:height: 2.45107in
8) 点击Run Simulation按钮,再选择Run Behavioral
Simulation。这里我们做一下行为级的仿真就可以了。
.. image:: images/media/image75.png
:width: 2.88031in
:height: 3.23482in
如果没有错误,Vivado中的仿真软件开始工作了。
9)
在弹出仿真界面后如下图,界面是仿真软件自动运行到仿真设置的50ms的波形。
.. image:: images/media/image76.png
:width: 6.00417in
:height: 1.23611in
由于LED[3:0]在程序中设计的状态变化时间长,而仿真又比较耗时,在这里观测timer[31:0]计数器变化。把它放到Wave中观察(点击Scope界面下的uut,
再右键选择Objects界面下的timer, 在弹出的下拉菜单里选择Add Wave
Window)。
.. image:: images/media/image77.png
:width: 3.82425in
:height: 2.22484in
添加后timer显示在Wave的波形界面上,如下图所示。
.. image:: images/media/image78.png
:width: 4.75283in
:height: 1.31547in
10) 点击如下标注的Restart按钮复位一下,再点击Run
All按钮。(需要耐心!!!),可以看到仿真波形与设计相符。(注意:仿真的时间越长,仿真的波形文件占用的磁盘空间越大,波形文件在工程目录的xx.sim文件夹)
.. image:: images/media/image79.png
:width: 4.16502in
:height: 1.82527in
.. image:: images/media/image80.png
:width: 6.00417in
:height: 1.37986in
我们可以看到led的信号会变成1,说明LED灯会变亮。
2.7 下载
----------
1) 连接好开发板的JTAG接口,给开发板上电,注意拔码开关要选择JTAG模式,也就是全部拔到”ON”,“ON”代表的值是0,不用JTAG模式,下载会报错。
.. image:: images/media/image81.png
:width: 5.50347in
:height: 3.82569in
.. image:: images/media/image82.png
:width: 4.09375in
:height: 2.23403in
2) 在“HARDWARE MANAGER”界面点击“Auto Connect”,自动连接设备
.. image:: images/media/image83.png
:width: 3.01461in
:height: 2.12162in
3) 选择芯片,右键“Program Device...”
.. image:: images/media/image84.png
:width: 3.34583in
:height: 2.10347in
4) 在弹出窗口中点击“Program”
.. image:: images/media/image85.png
:width: 3.53194in
:height: 1.88056in
5) 等待下载
.. image:: images/media/image86.png
:width: 3.18855in
:height: 0.87404in
6) 下载完成以后,我们可以看到PL
LED开始每秒变化一次。到此为止Vivado简单流程体验完成。后面的章节会介绍如果把程序烧录到Flash,需要PS系统的配合才能完成,只有PL的工程不能直接烧写Flash。在”体验ARM,裸机输出”Hello
World”一章的常见问题中有介绍。
2.8 实验总结
--------------
本章节介绍了如何在PL端开发程序,包括工程建立,约束,仿真等方法,在后续的代码开发方式中皆可参考此方法。
|
import {
LoginHeader,
Input,
FormStatus,
Footer
} from '@/presentation/components/'
import Context from '@/presentation/contexts/form/form-context'
import Styles from './login-styles.scss'
import React, { useState } from 'react'
type StateProps = {
isLoading: boolean
errorMessage: string
}
const Login: React.FC = () => {
const [state] = useState<StateProps>({
isLoading: false,
errorMessage: ''
})
return (
<div className={Styles.login}>
<LoginHeader />
<Context.Provider value={state}>
<form action="" className={Styles.form}>
<h2>Login</h2>
<Input id="email" type="email" placeholder="Digite seu e-mail" />
<Input id="password" type="password" placeholder="Digite sua senha" />
<button data-testid="submit" disabled type="submit" className={Styles.subimit}>Entrar</button>
<span className={Styles.link}> Criar conta</span>
<FormStatus />
</form>
</Context.Provider>
<Footer />
</div>
)
}
export default Login
|
package ru.citeck.ecos.webapp.task;
import org.jetbrains.annotations.NotNull;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import ru.citeck.ecos.context.lib.auth.AuthContext;
import ru.citeck.ecos.webapp.lib.task.EcosTaskComponentsFactory;
import ru.citeck.ecos.webapp.lib.task.executor.TaskExecutorComponent;
import ru.citeck.ecos.webapp.lib.task.executor.TaskExecutorProperties;
@Component
public class EcosTaskComponentsFactoryImpl implements EcosTaskComponentsFactory {
@NotNull
@Override
public TaskExecutorComponent createTaskExecutorComponent(
@NotNull String key,
@NotNull TaskExecutorProperties props
) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor() {
@Override
public Thread createThread(Runnable runnable) {
return super.createThread(() -> {
AuthContext.runAsSystemJ(runnable::run);
});
}
};
executor.setCorePoolSize(props.getCorePoolSize());
executor.setMaxPoolSize(props.getMaxPoolSize());
executor.setQueueCapacity(props.getQueueCapacity());
executor.setThreadNamePrefix("ecos-task-executor-" + key + "-");
executor.setAwaitTerminationSeconds(10);
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.initialize();
return new TaskExecutorComponentImpl(executor);
}
}
|
import { describe, it } from '@tcom/test';
import { mock, instance, verify, reset, when, deepEqual } from '@tcom/test/mock';
import { expect } from '@tcom/test/assert';
import { RequesterType, TransactionPurpose, UserWallet, WalletEntry, WalletEntryFilter, WalletEntryManager, WalletFlow, WalletManager, WalletType } from '@tcom/platform/lib/banking';
import { WalletEntryController } from '../../src/controllers/wallet-entry.controller';
import { NotFoundError, PagedResult } from '@tcom/platform/lib/core';
const walletEntries: WalletEntry[] = [{
id: 1,
purpose: TransactionPurpose.Subscription,
requesterId: 'Chargify',
requesterType: RequesterType.System,
createTime: new Date(),
}];
describe('WalletEntryController', () => {
const mockWalletManager = mock(WalletManager);
const mockEntryManager = mock(WalletEntryManager);
function getController(): WalletEntryController {
return new WalletEntryController(instance(mockWalletManager), instance(mockEntryManager));
}
const walletId = 7;
const accountId = 1;
const purpose = TransactionPurpose.Subscription;
const from = new Date();
const to = new Date();
const page = 1;
const pageSize = 20;
const userId = 1;
beforeEach(() => {
reset(mockWalletManager);
reset(mockEntryManager);
});
describe('getAll()', () => {
it('should return all wallet entries', async () => {
// Given
const walletFilter: WalletEntryFilter = {
walletId,
accountId,
purpose,
from,
to,
page,
pageSize
};
when(mockEntryManager.getAll(deepEqual(walletFilter))).thenResolve(new PagedResult(walletEntries, 1, page, pageSize));
const controller = getController();
// When
const result = await controller.getAll(accountId, walletId, purpose, from, to);
// Then
expect(result.items).to.equal(walletEntries);
verify(mockEntryManager.getAll(deepEqual(walletFilter))).once();
});
});
describe('getForUser()', async () => {
const userWallet: UserWallet = {
id: walletId,
type: WalletType.User,
flow: WalletFlow.All,
createTime: new Date(),
userId,
};
const walletFilter: WalletEntryFilter = {
walletId,
accountId,
purpose,
from,
to,
page,
pageSize
};
it('should return all wallet entries for a user', async () => {
// Given
when(mockWalletManager.getForUser(userId)).thenResolve(userWallet);
when(mockEntryManager.getAll(deepEqual(walletFilter))).thenResolve(new PagedResult(walletEntries, 10, page, pageSize));
const controller = getController();
// When
const result = await controller.getForUser(userId, accountId, purpose, from, to, page, pageSize);
// Then
expect(result.items[0].id).to.equal(1);
verify(mockWalletManager.getForUser(userId)).once();
verify(mockEntryManager.getAll(deepEqual(walletFilter))).once();
});
it('should throw a not found error if no wallet entry is returned', async () => {
// Given
when(mockWalletManager.getForUser(userId)).thenResolve();
const controller = getController();
// When
const delegate = async () => controller.getForUser(1);
// Then
await expect(delegate()).to.be.rejectedWith(NotFoundError, 'Wallet not found.');
});
});
describe('getById()', () => {
const walletEntriesById: WalletEntry = {
id: 1,
purpose: TransactionPurpose.Subscription,
requesterId: 'Chargify',
requesterType: RequesterType.System,
createTime: new Date(),
transactions: [{
id: 1,
entryId: 1,
accountId: 13,
walletId: 5,
amount: -29.99,
amountRaw: -29.99,
baseAmount: -29.99,
currencyCode: 'USD',
exchangeRate: 1,
purpose,
requesterId: 'Chargify',
requesterType: RequesterType.System,
createTime: new Date()
}]
};
it('should return a wallet entry by ID', async () => {
// Given
when(mockEntryManager.get(1)).thenResolve(walletEntriesById);
const controller = getController();
// When
const result = await controller.getById(1);
// Then
expect(result.purpose).to.equal('Subscription');
expect(result.id).to.equal(1);
verify(mockEntryManager.get(1)).once();
});
it('should throw a not found error if no wallet entry by ID is returned', async () => {
// Given
when(mockEntryManager.get(1)).thenResolve();
const controller = getController();
// When
const delegate = async () => controller.getById(1);
// Then
await expect(delegate()).to.be.rejectedWith(NotFoundError, 'Entry not found.');
});
});
});
|
//new Object -> Object.prototype
// const objA = {
// chaveA: 'A',
// //__proto__: Object.prototype
// };
// const objB = {
// chaveB: 'B',
// //__proto__: objA
// };
// //setando o prototype do objeto b mudando pra a
// Object.setPrototypeOf(objB, objA)
// console.log(objB.chaveA);
// console.log(Object.getPrototypeOf(objA)); //usar isso ao imvés de obj.__proto__
function Produto(nome, preco) {
this.nome = nome;
this.preco = preco;
}
Produto.prototype.desconto = function (percentual) {
this.preco = this.preco - (this.preco * (percentual / 100));
};
Produto.prototype.aumento = function (percentual) {
this.preco = this.preco + (this.preco * (percentual / 100));
};
const p1 = new Produto('Camiseta', 50);
// Literal -> não posui os metodos do produto, então usamos o setPrototypeOf para passar o prototype também para ele
const p2 = {
nome: 'Caneca',
preco: 15
};
Object.setPrototypeOf(p2, Produto.prototype);
p2.aumento(10);
const p3 = Object.create(Produto.prototype, {
preco: {
writable: true,
configurable: true,
enumerable: true,
value: 99
},
tamanho: {
writable: true,
configurable: true,
enumerable: true,
value: 42
},
});
p3.aumento(10);
console.log(p3);
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.24;
contract MemoryCalldata {
/*
* Memory vs calldata:
* In solidity, whenever you are working with dynamic data types, you MUST specify
* how to treat those variables with either memory or calldata.
*
* Example of dynamic data types: array, struct, string, bytes, etc.
*
* Memory
* - allows you to modify the variable passed as input
* - It is more expensive due to the OPCODES involved for that
*
* Calldata
* - cannot modify the variable passed as input (like CONST)
* - It is cheaper due to less OPCODES being used
*
*/
mapping(address => string) mappingAddressString;
function saveData(address _wallet, string memory _name) public {
_name = string.concat(_name, "-4000");
mappingAddressString[_wallet] = _name;
}
function saveData2(address _wallet, string calldata _name) public {
// _name = string.concat(_name, "-4000");
mappingAddressString[_wallet] = _name;
}
}
|
import java.util.*;
public class Sorts {
//One ArrayList for each type, and one for each to hold the original, unsorted list
private ArrayList<Integer> intList;
private final ArrayList<Integer> unsortedIntList;
private ArrayList<Double> doubleList;
private final ArrayList<Double> unsortedDoubleList;
private final int ARRSIZE;
/**
* Sorts is the constructor for the Sorts class. It takes in three <tt>ArrayList</tt>s.
* One list each for Integers, Doubles, and Strings. Currently, the String sorting is
* not enabled so null can be passed in with no negative repercussions.
* @param ints An <tt>ArrayList</tt> of Integers
* @param doubs An <tt>ArrayList</tt> of Doubles
* @param strs An <tt>ArrayList</tt> of Strings
*/
public Sorts(ArrayList<Integer> ints, ArrayList<Double> doubs, ArrayList<String> strs, int arrsize) {
this.unsortedIntList = ints;
this.unsortedDoubleList = doubs;
this.intList = new ArrayList<Integer>();
this.doubleList = new ArrayList<Double>();
this.setArrays(ints, doubs, strs);
this.ARRSIZE = arrsize;
}
/**
* Sets the values of the ArrayLists we'll be doing the sorting on. We set the values individually
* so that we don't have to worry about passing too many things by reference, or anything similar.
* Assumed to be used only by the constructor of the Sorts class.
* @param ints An <tt>ArrayList</tt> of Integers
* @param doubs An <tt>ArrayList</tt> of Doubles
* @param strs An <tt>ArrayList</tt> of Strings
*/
private void setArrays(ArrayList<Integer> ints, ArrayList<Double> doubs, ArrayList<String> strs) {
for (int i: ints)
this.intList.add(i);
for (double d: doubs)
this.doubleList.add(d);
}
public void doSorts(Integer[] intArray, Double[] doubleArray, String[] strArray) {
long startTime, endTime, duration;
if (ARRSIZE <= 200) {
startTime = System.currentTimeMillis();
this.bubble(intArray);
this.bubble(doubleArray);
this.bubble(strArray);
//sort.newBubble(stringArray); //TODO:
endTime = System.currentTimeMillis();
duration = endTime - startTime;
printStats("bubble", duration);
startTime = System.currentTimeMillis();
this.optimizedBubble(intArray);
this.optimizedBubble(doubleArray);
this.optimizedBubble(strArray);
endTime = System.currentTimeMillis();
duration = endTime - startTime;
printStats("obubble", duration);
}
if (ARRSIZE <= 250) {
startTime = System.currentTimeMillis();
this.selection(intArray);
this.selection(doubleArray);
this.selection(strArray);
endTime = System.currentTimeMillis();
duration = endTime - startTime;
printStats("selection", duration);
}
if (ARRSIZE <= 300) {
startTime = System.currentTimeMillis();
this.insertion(intArray);
this.insertion(doubleArray);
this.insertion(strArray);
endTime = System.currentTimeMillis();
duration = endTime - startTime;
printStats("insertion", duration);
}
startTime = System.currentTimeMillis();
this.comb(intArray);
this.comb(doubleArray);
this.comb(strArray);
endTime = System.currentTimeMillis();
duration= endTime - startTime;
printStats("comb", duration);
startTime = System.currentTimeMillis();
Arrays.sort(intArray.clone());
Arrays.sort(doubleArray.clone());
Arrays.sort(strArray.clone());
endTime = System.currentTimeMillis();
duration = endTime - startTime;
printStats("java's", duration);
this.mergeSort();
this.quickSort();
}
public void printStats(String sort, long duration) {
System.out.printf("ARRSIZE --> %d, %s sort\t --> %f seconds.\n", ARRSIZE, sort, duration/1000.0);
}
/**
* An updated version of the bubbleSort method that simply takes an Array of
* Objects and sorts those rather than dealing with separate sorting implementations
* for the different types supported.
* Integers Doubles and Strings are supported currently.
* <p><u><b>BUBBLE SORT DESCRIPTION:</b></u></p>
* The algorithm goes through the list checking, one
* index at a time to see if any two elements should be swapped. It completes
* only when a full iteration through the list yielded no swaps. <p/>
* Note: if the ARRSIZE in Driver is too large, this function doesn't have a chance of completing. Too slow.
* There is nothing passed in and nothing is returned. The run time is O(n^2). <br/>
* @param arrayToSort
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public void bubble(Comparable[] toSort) {
boolean swapped = true;
Comparable[] array = toSort.clone();
while (swapped) {
swapped = false;
for (int i = 1; i < toSort.length; i++) {
if (array[i-1].compareTo(array[i]) > 0) {
Comparable newObj = array[i-1];
array[i-1] = array[i];
array[i] = newObj;
swapped = true;
}
}
}
this.assertSortedAsc(array);
}
/**
* Updated optimized bubble sort. This method simply takes in an Array of Objects
* assumed to be either Strings, Doubles, or Integers, and it sorts them.
* <p><u><b>OPTIMIZED BUBBLE SORT DESCRIPTION:</b></u></p>
*
* Optimizes by using the fact that after N passes, the last element in the list will be
* sorted, and so on, moving down through the list. This results in anywhere
* from 10 to 50% improvement over the basic bubbleSort algorithm. <br/>
* @param toSort
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public void optimizedBubble(Comparable[] toSort) {
Comparable[] array = toSort.clone();
int size = array.length;
do {
int newN = 0;
for (int i = 1; i < array.length; i++) {
//follows the same principle as bubbleSort; if two elements are
//out of order it will swap them; difference is with the newN
if (array[i-1].compareTo(array[i]) > 0) {
Comparable bigElement = array[i-1];
array[i-1] = array[i];
array[i] = bigElement;
newN = i;
}
}
size = newN;
} while (size > 0);
this.assertSortedAsc(array);
}
/**
* An updated selection sort that simply takes an array of comparable things,
* and sorts them using the selection sorting algorithm.
* Selection sort is one of the simplest sorts, getting the smallest element
* the first time through, then the second smallest, and so on through the
* entire list.
* <br />
* Prevents a lot of extra swapping, but in general is not a competitive sorting algorithm, at all.
* @param toSort
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public void selection(Comparable[] toSort) {
Comparable[] array = toSort.clone();
Comparable minimum;
int mindex = 0;
/*
* Two loops: one to place the minimum for this time through, and the other
* to find the minimum for this time through the sort
*/
for (int startPos = 0; startPos < array.length; startPos++) {
minimum = array[startPos];
mindex = startPos;
//go through every other element in the array and find the minimum
for (int i = startPos + 1; i < array.length; i++) {
if (array[i].compareTo(minimum) < 0) {
minimum = array[i];
mindex = i;
}
}
//If they are the same, you don't need to do anything; otherwise swap
if (minimum.compareTo(array[startPos]) != 0) {
array[mindex] = array[startPos];
array[startPos] = minimum;
}
}
this.assertSortedAsc(array);
}
/**
* Updated insertion sort. This method simply takes in an Array of Objects
* assumed to be either Strings, Doubles, or Integers, and it sorts them.
* <p><u><b>INSERTION SORT DESCRIPTION:</b></u></p>
*
*
* Generally faster sorting than the other simple sorting methods, and is often the one
* chosen out of Bubble, Selection, or Insertion because of that. It is
* highly dependent on the dataset you are sorting. Already mostly-sorted data is done quickly.
* <br />
* Can easily swap from ascending to descending here.
*
* @param toSort
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public void insertion(Comparable[] toSort) {
Comparable[] sorted = toSort.clone();
for (int i = 1; i < sorted.length -1; i++) {
Comparable placing = sorted[i]; //placing is what's being placed into the deck
int j = i-1;
/*
* Move through the sorted deck, continue when the thing we're placing
* less than what we're looking at. When done, we finally place it
* in it's final location (for this loop)
*/
while (j >= 0 && sorted[j].compareTo(placing) > 0) {
sorted[j+1] = sorted[j];
j--;
}
sorted[j+1] = placing;
}
this.assertSortedAsc(sorted);
}
/**
* This is an updated version of comb sort, but it doesn't completely work.
* It gets every element in the array except for one, at least in the normal
* case. Too bad, as it's relatively fast.
* <br />
* <u><b>DOES NOT ALWAYS COMPLETELY WORK!!!</b></u>
* <br />
* That's unfortunate, as well, as this is a very fast sorting algorithm.
* @param toSort
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public void comb(Comparable[] toSort) {
Comparable[] sorted = toSort.clone();
double shrinkFactor = 1.247330950103979;
int gap = sorted.length;
boolean swapped = false;
while (gap != 1 || swapped == false) {
gap /= shrinkFactor;
if (gap < 1)
gap = 1;
int i = 0;
swapped = false;
while (i + gap < sorted.length) {
if (sorted[i].compareTo(sorted[i + gap]) > 0) {
Comparable temp = sorted[i];
sorted[i] = sorted[i + gap];
sorted[i + gap] = temp;
swapped = true;
}
i++;
}
}
//cannot call the checker below, as it doesn't work.
//this.assertSortedAsc(sorted);
}
/**
* MergeSort algorithm based on the famous sorting algorithm of which details
* can be found on <a href="http://en.wikipedia.org/wiki/Merge_sort">Wikipedia</a>. <br/>
* This is supposedly one of the fastest sorting algorithms, with a run speed of O(nlogn),
* even in the worse case. However, probably due to the fact that it's not being optimized,
* and I'm using ArrayLists exclusively, it's not nearly as fast as CombSort or HeapSort. <p/>
* <b>The runtime of this method with an ARRSIZE of 250 was <i>3.112</i> seconds.</b> <br/>
* While this is faster than Insertion and Selection Sort, it cannot compare to the two fast
* algorithms up to this point. On to quicksort we go!
* <p/>
* One thing to keep in mind, the way I've set up my lists may benefit the other sorting algorithms
* more than mergesort for whatever reason. When finished with quicksort, I should find a function
* to reverse the order of the lists and see if that changes the speed of the sorts.
* TODO: Develop a way to reverse the order of the lists to compare in another way
*/
public void mergeSort() {
this.resetArrays();
long startTime = System.currentTimeMillis();
//Will deal with Integers first, then move on to Doubles and Strings
this.intList = runIntMergeSort(this.intList);
this.doubleList = runDoubMergeSort(this.doubleList);
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
print("Merge Sort took " + duration/1000.0 + " seconds");
}
/**
* The method that does the work for the Integer version of MergeSort().
* It's the worker method and it's a helper method. It runs MergeSort() on
* an ArrayList of Integers. To do this, it breaks the ArrayList into two
* even halves and recursively calls itself until the size gets down to 1.
* At that point, it starts merging the left and right sides with another helper
* method, mergeInt().
* @param list The ArrayList of Integers that MergeSort is being run on.
* @return In the end, a sorted ArrayList of Integers will be returned.
* But it will change, because it's recursive.
*/
private ArrayList<Integer> runIntMergeSort(ArrayList<Integer> list) {
if (list.size() <= 1) //If the size of the list is 1, it's sorted, so return it
return list;
//else, list size is > 1, so split into sublists
ArrayList<Integer> left = new ArrayList<Integer>(list.size()/2 + 1), right = new ArrayList<Integer>(list.size()/2 + 1);
int middle = list.size()/2;
for (int i = 0; i < middle; i++)
left.add(list.get(i));
for (int i = middle; i < list.size(); i++)
right.add(list.get(i));
//Recursively call runIntMergeSort to further split each sublist is of size 1
left = runIntMergeSort(left);
right = runIntMergeSort(right);
//Merge the sublists returned and return the merged sublist
return mergeInt(left, right);
}
/**
* A helper method that does the work for the Double version of MergeSort().
* It runs MergeSort(0 on an ArryList of Doubles. To do this, it breaks the
* original ArrayList into halves and recursively calls itself until the size
* of the the lists are 1. At that point, it starts merging the left and right
* sides with another helper method, mergeDouble().
* @param list The ArrayList of Doubles that MergeSort is being run on.
* @return A sorted ArrayList of Doubles will be returned at the end.
*/
private ArrayList<Double> runDoubMergeSort(ArrayList<Double> list) {
if (list.size() <= 1) //If the size of the list is 1, it's sorted, so return it
return list;
//else, list size is > 1, so split into sublists
ArrayList<Double> left = new ArrayList<Double>(list.size()/2 + 1), right = new ArrayList<Double>(list.size()/2 + 1);
int middle = list.size()/2;
for (int i = 0; i < middle; i++)
left.add(list.get(i));
for (int i = middle; i < list.size(); i++)
right.add(list.get(i));
//Recursively call runIntMergeSort to further split each sublist is of size 1
left = runDoubMergeSort(left);
right = runDoubMergeSort(right);
//Merge the sublists returned and return the merged sublist
return mergeDouble(left, right);
}
/**
* The method that does the merging of the ArrayLists for MergeSort() when
* dealing with Integers. The method for Doubles is mergeDouble(). It follows
* the convention for a top-down MergeSort, merging two ArrayLists of Integers. <br/>
* The ArrayList will be ordered from lowest to highest.
* @param left The left half of a list, as specified by MergeSort()
* @param right The right half of a list, as speciified by MergeSort()
* @return A sorted ArrayList of Integers that is the size of left + right
*/
private ArrayList<Integer> mergeInt(ArrayList<Integer> left, ArrayList<Integer> right) {
ArrayList<Integer> result = new ArrayList<Integer>();
while (left.size() > 0 || right.size() > 0) {
if (left.size() > 0 && right.size() > 0) {
//Whichever is lower, we want to add to result
if (left.get(0) <= right.get(0))
result.add(left.remove(0));
else
result.add(right.remove(0));
}
//Add the remaining to result, one way or another
else if (left.size() > 0)
result.add(left.remove(0));
else if (right.size() > 0)
result.add(right.remove(0));
}
return result;
}
/**
* The method that does the merging of the ArrayLists for MergeSort() when
* dealing with Doubles. The method for Integers is mergeInt(). It follows the
* convention for a top-down MergeSort, merging two ArrayLists of Doubles. </br>
* The ArrayList will be sorted from lowest to highest.
* @param left The left half of a list, as specified by MergeSort()
* @param right The right half of a list, as specified by MergeSort()
* @return A sorted ArrayList of Doubles that is the size of left + right
*/
private ArrayList<Double> mergeDouble(ArrayList<Double> left, ArrayList<Double> right) {
ArrayList<Double> result = new ArrayList<Double>();
while (left.size() > 0 || right.size() > 0) {
if (left.size() > 0 && right.size() > 0) {
//Whichever is lower, we want to add to result
if (left.get(0) <= right.get(0))
result.add(left.remove(0));
else
result.add(right.remove(0));
}
//Add the remaining to result, one way or another
else if (left.size() > 0)
result.add(left.remove(0));
else if (right.size() > 0)
result.add(right.remove(0));
}
return result;
}
/**
* QuickSort is one of the fastest sorting algorithms known to man. It has
* a best-case runtime of O(NlogN) and a worst-case of O(N^2), but it runs faster
* than most of the other sorting algorithms. It's space efficent, as well. <br/>
* QuickSort is a divide and conquer algorithm. Splits everything into low and high
* elements and works from there, using a pivot point and sorting the sublists.
* <p/>
* <ol>
* <li>Pick a pivot point from the list</li>
* <li>Reorder the list so elements less than the pivot are before the pivot, those
* greater than it come after it. Pivot is now in its final position. </li>
* <li>Recursively sort the sub-list of lesser elements adn the sublist of greater elements</li>
* </ol>
* <p/>
* <b>The runtime of this method with an ARRSIZE of 250 was <i>0.094</i> seconds.</b> <br/>
* <b>The runtime of this method with an ARRSIZE of 2000 was <i>7.372</i> seconds. </b> <br/>
* Note that QuickSort is a little slower than the other fast datasets in a small set.
* However, larger sets are not a comparison. At 2000, QuickSort dominates.
*
*/
public void quickSort() {
this.resetArrays();
long startTime = System.currentTimeMillis();
//this.intList = quickSortInt(this.intList);
//this.doubleList = quickSortDouble(this.doubleList);
//this.intList =
quickSortInt(this.intList, 0, this.intList.size() - 1);
quickSortDouble(this.doubleList, 0, this.doubleList.size() - 1);
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
print("Quick Sort took " + duration/1000.0 + " seconds.");
}
/**
* This is simply Java's Collections.sort() method, timed here for
* comparison's sake. Interestingly, my implementation of quicksort has
* shown to be very competitive with this.
*/
public void collectionSort() {
this.resetArrays();
long startTime = System.currentTimeMillis();
Collections.sort(this.doubleList);
Collections.sort(this.intList);
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
print("Java's Collections' sort took " + duration/1000.0 + " seconds.");
}
/**
* The partition operation for the Integer version of QuickSort. This partitions
* the elements between indexes left and right, by moving all elements less
* than what's in the pivot position before the pivot and those greater than it to after
* the pivot position. Only uses exchanges, so nothing has changed in terms of the
* content of the list itself. <br/>
* Duplicates can be on either side of the pivot.
* May not be the best or fastest version of the partition function, but it's
* probably the easiest to understand.
* <br/>Same as the Double version.
*/
private int partitionInt(ArrayList<Integer> list, int leftIndex, int rightIndex, int pivotIndex) {
int pivot = list.get(pivotIndex);
int rightElement = list.get(rightIndex);
//Swap the pivot and right element, moving pivot to the end of list
list.set(rightIndex, pivot);
list.set(pivotIndex, rightElement);
int storeIndex = leftIndex;
for (int i = leftIndex; i < rightIndex; i++) {
if (list.get(i) < pivot) {
int storeElement = list.get(storeIndex);
list.set(storeIndex, list.get(i));
list.set(i, storeElement);
storeIndex++;
}
}
int storeElement = list.get(storeIndex);
list.set(storeIndex, list.get(rightIndex));
list.set(rightIndex, storeElement);
return storeIndex;
}
/**
* The partition operation for the Double version of QuickSort. This partitions
* the elements between indexes left and right, by moving all elements less
* than what's in the pivot position before the pivot and those greater than it to after
* the pivot position. Only uses exchanges, so nothing has changed in terms of the
* content of the list itself. <br/>
* Duplicates can be on either side of the pivot.
* May not be the best or fastest version of the partition function, but it's
* probably the easiest to understand.
* <br/>Same as the Integer version.
*/
private int partitionDouble(ArrayList<Double> list, int leftIndex, int rightIndex, int pivotIndex) {
double pivot = list.get(pivotIndex);
double rightElement = list.get(rightIndex);
//Swap the pivot and right element; move pivot to the end of the list
list.set(rightIndex, pivot);
list.set(pivotIndex, rightElement);
int storeIndex = leftIndex;
for (int i = leftIndex; i < rightIndex; i++) {
if (list.get(i) < pivot) {
double storeElement = list.get(storeIndex);
list.set(storeIndex, list.get(i));
list.set(i, storeElement);
storeIndex++;
}
}
double storeElement = list.get(storeIndex);
list.set(storeIndex, list.get(rightIndex));
list.set(rightIndex, storeElement);
return storeIndex;
}
/**
* The helper method that runs QuickSort for Integers. Actually quite simple
* once the partition method is out of the way, QuickSort recursively calls
* itself until it's down to a size of 1, breaking the lists one smaller at a
* time, which guarantees a max of N recursive calls.
* <br/>
* Same as the Double version, except for it being Integer instead of Double.
* @param list The list that's being sorted.
* @param left The left most item in the list
* @param right The right most item in the list
*/
private void quickSortInt(ArrayList<Integer> list, int left, int right) {
if (left < right) {
//A better way to choose the pivot is to use a median method, but will do that later
int pivotIndex = (left + right) / 2;
int pivotNewIndex = partitionInt(list, left, right, pivotIndex);
quickSortInt(list, left, pivotNewIndex - 1);
quickSortInt(list, pivotNewIndex + 1, right);
}
}
/**
* The helper method that runs QuickSort for Doubles. Actually quite simple
* once the partition method is out of the way, QuickSort recursively calls
* itself until it's down to a size of 1, breaking the lists one smaller at a
* time, which guarantees a max of N recursive calls.
* <br/>
* Same as the Double version, except for it being Double instead of Integer.
* @param list The list that's being sorted.
* @param left The left most item in the list
* @param right The right most item in the list
*/
private void quickSortDouble(ArrayList<Double> list, int left, int right) {
if (left < right) {
//A better way to choose the pivot is to use a median method, but will do that later
int pivotIndex = (left + right) / 2;
int pivotNewIndex = partitionDouble(list, left, right, pivotIndex);
quickSortDouble(list, left, pivotNewIndex - 1);
quickSortDouble(list, pivotNewIndex + 1, right);
}
}
/**
* A very simple helper method that prints out an Object of any kind.
* This method can be called with ints, doubles, strings, sorts, etc.
* <br/>Simply calls System.out.println() for the object passed in. If it's
* your own object, there must be a toString() method provided.
* @param input The object you want to print out.
*/
private void print(Object input) {
System.out.println(input);
}
/**
* Checks if any elements in the array are not in ascending order.
* If it finds any, it exits immediately.
* @param toCheck
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public void assertSortedAsc(Comparable[] toCheck) {
for (int i = 0; i < toCheck.length - 1; i++) {
if (!(toCheck[i].compareTo(toCheck[i+1]) <= 0)) {
System.err.println("Array found not in ascending order. Exiting.");
System.err.println("The index that failed was " + i);
System.out.flush();
print(toCheck.length);
printArray(toCheck, i);
System.exit(-1);
}
}
}
@SuppressWarnings("rawtypes")
public void printArray(Comparable[] toPrint, int failIndex) {
for (int index = failIndex-10; index < failIndex+10 && index < toPrint.length; index++) {
System.out.println("index: " + index + ": " + toPrint[index]);
}
}
/**
* Private helper method that resets the ArrayLists back to how they were before
* being sorted. This is required because everything is passed by reference in Java
* and we want to change the values themselves.
* Nothing is passed in and nothing is returned. this.intList and this.doubleList are modified.
*/
private void resetArrays() {
int index = 0;
for (int i: this.unsortedIntList) {
this.intList.set(index, i);
index++;
}
index = 0;
for (double d: this.unsortedDoubleList) {
this.doubleList.set(index, d);
index++;
}
}
}
|
import React, { useState } from 'react';
import { css } from '@emotion/react';
import PropTypes from 'prop-types';
import { useLocation } from '@reach/router';
import { isValidEmail } from '../utils/isValidEmail';
import { titleCaseify } from '../utils/titleCase';
import RecaptchaFooter from './SignupModal/RecaptchaFooter';
import Button from './Button';
import PageTools from './PageTools';
import useThemeTranslation from '../hooks/useThemeTranslation';
import useTessen from '../hooks/useTessen';
import { FEEDBACK_FORM_TYPE } from '../utils/constants';
const ComplexFeedback = ({ pageTitle }) => {
const [feedbackType, setfeedbackType] = useState(null);
const [userComments, setUserComments] = useState(null);
const [userEmail, setUserEmail] = useState(null);
const [shouldSubmit, setShouldSubmit] = useState(false);
const [formSubmitted, setFormSubmitted] = useState(false);
const { t } = useThemeTranslation();
const tessen = useTessen();
const location = useLocation();
const CAPTCHA_ACTION = 'userFeedback';
const recaptchaReady = () => {
return new Promise((resolve, reject) => {
try {
window.grecaptcha.ready(resolve);
} catch (err) {
reject(err);
}
});
};
const generateRecaptchaToken = () => {
// turn the recaptcha thenable into an actual promise
return new Promise((resolve, reject) => {
window.grecaptcha
.execute(window._nr_feedback.reCaptchaToken, {
action: CAPTCHA_ACTION,
})
.then(resolve, reject);
});
};
const handleFeedbackClick = (feedbackType) => {
setfeedbackType(feedbackType);
setShouldSubmit(true);
tessen.track({
eventName: 'feedbackRating',
category: `${titleCaseify(feedbackType)}FeedbackClick`,
path: location.pathname,
});
};
const handleSubmit = async () => {
setFormSubmitted(true);
await recaptchaReady();
const recaptchaToken = await generateRecaptchaToken();
tessen.track({
eventName: 'feedbackSubmitted',
category: `${titleCaseify(feedbackType)}FeedbackSubmit`,
path: location.pathname,
userEmail,
userComments,
});
const jiraSubmission = {
title: pageTitle,
formType: FEEDBACK_FORM_TYPE.general,
description: userComments,
rating: feedbackType,
pageUrl: location.href,
email: userEmail,
recaptchaToken,
};
if (userComments) {
fetch(
'https://docs-user-feedback-service.newrelic-external.com/user-feedback-service',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(jiraSubmission),
}
);
}
};
const handleReset = () => {
setfeedbackType(null);
setFormSubmitted(false);
setUserComments(null);
};
return (
<PageTools.Section
css={css`
display: flex;
border: none;
flex-direction: column;
max-width: 320px;
background: #afe2e3;
gap: 1rem;
p {
color: var(--system-text-primary-light);
margin: 0;
font-size: 14px;
}
input::placeholder {
color: var(--system-text-primary-light);
}
h5,
h4 {
color: var(--system-text-primary-light);
}
`}
>
{formSubmitted ? (
<h5
css={css`
margin: 0;
`}
>
{t('feedback.submitMessage')} 🤠{' '}
<Button
onClick={handleReset}
css={css`
border: none;
border-bottom: 1px solid;
border-radius: 0;
padding: 0;
background: none;
`}
>
{t('feedback.reset')}
</Button>
</h5>
) : (
<>
<h4
css={css`
margin-bottom: 0;
text-align: center;
`}
>
{t('feedback.question')}
</h4>
<div
css={css`
display: flex;
flex-wrap: wrap;
justify-content: space-around;
align-items: flex-start;
button {
width: 45%;
font-size: 14px;
border: none;
}
@supports not (gap: 0.5rem) {
a:first-of-type {
margin-right: 0.25rem;
}
}
`}
>
<Button
variant={Button.VARIANT.OUTLINE}
size={Button.SIZE.LARGE}
onClick={() => handleFeedbackClick('yes')}
css={css`
height: 3rem;
margin-bottom: 0.5rem;
color: var(--system-text-primary-light);
background: var(--system-background-app-light);
${feedbackType === 'yes' &&
css`
background: var(--system-text-primary-light);
color: var(--system-text-primary-dark);
`}
`}
>
<div
css={css`
margin-right: 0.5rem;
font-size: 14px;
`}
>
😁
</div>
{t('feedback.yes')}
</Button>
<Button
variant={Button.VARIANT.OUTLINE}
size={Button.SIZE.SMALL}
onClick={() => handleFeedbackClick('no')}
css={css`
height: 3rem;
margin-bottom: 0.5rem;
color: var(--system-text-primary-light);
background: var(--system-background-app-light);
${feedbackType === 'no' &&
css`
background: var(--system-text-primary-light);
color: var(--system-text-primary-dark);
`}
`}
>
<div
css={css`
margin-right: 0.5rem;
font-size: 14px;
`}
>
🙁
</div>
{t('feedback.no')}
</Button>
</div>
{feedbackType && (
<>
<p>{t('feedback.comments')}</p>
<textarea
value={userComments}
maxLength="30000"
onChange={(e) => {
setUserComments(e.target.value);
}}
css={css`
font-size: 0.75rem;
padding: 0.5rem;
min-height: 100px;
border-radius: 4px;
border: none;
`}
/>
<p>{t('feedback.email')}</p>
<div
css={css`
p {
font-size: 0.625rem;
}
`}
>
<p>{t('feedback.emailDisclaimer')}</p>
</div>
<input
value={userEmail}
placeholder="datanerd@example.com"
onChange={(e) => {
setUserEmail(e.target.value);
setShouldSubmit(
isValidEmail(e.target.value) || e.target.value.length === 0
);
}}
css={css`
font-size: 0.75rem;
padding: 0.5rem;
border-radius: 4px;
border: none;
`}
/>
{userEmail && !isValidEmail(userEmail) && (
<p
css={css`
// using && here to increase specificity over the p styling in the section above
&& {
color: var(--attention-notification-critical);
margin-top: -1rem;
}
`}
>
{t('feedback.validEmail')}
</p>
)}
<Button
variant={Button.VARIANT.NORMAL}
size={Button.SIZE.LARGE}
onClick={handleSubmit}
disabled={!shouldSubmit}
css={css`
height: 3rem;
background: var(--system-text-primary-light);
color: var(--system-text-primary-dark);
.dark-mode &:hover {
background: var(--color-black);
color: var(--system-text-primary-dark);
}
&:disabled {
cursor: not-allowed;
}
`}
>
{t('feedback.submitButton')}
</Button>
<RecaptchaFooter />
</>
)}
</>
)}
</PageTools.Section>
);
};
ComplexFeedback.propTypes = {
pageTitle: PropTypes.string.isRequired,
};
export default ComplexFeedback;
|
// format a list horizontally with spacing
@mixin horizontal-list($spacing: var(--s1)) {
list-style-type: none;
padding: 0;
display: flex;
flex-direction: row;
justify-content: center;
& > * + * {
margin-left: $spacing;
margin-top: 0;
}
}
// format a list vertically with spacing
@mixin vertical-list($spacing: var(--s-3)) {
list-style-type: none;
padding: 0;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
& > * + * {
margin-top: $spacing;
margin-left: 0;
}
}
@mixin breakpoint($break) {
@if $break == large {
@media (min-width: $break-large) {
@content;
}
} @else if $break == medium {
@media (min-width: $break-medium) {
@content;
}
} @else if $break == small {
@media (min-width: $break-small) {
@content;
}
} @else {
@media ($break) {
@content;
}
}
}
|
--------- Peer-graded Assignment: AB Testing
------ We are running an experiment at an item-level, which means all users who visit
------ will see the same page, but the layout of different item pages may differ.
------ CODE
---- Compare the final_assignments_qa table to the assignment events we captured for user_level_testing.
---- Write an answer to the following question: Does this table have everything you need to compute metrics
---- like 30-day view-binary?
----- The answer is No. The creation_date is needed in order to calculate the binary metrics.
SELECT *
FROM dsv1069.final_assignments_qa;
---- Write a query and table creation statement to make final_assignments_qa look like the
---- final_assignments table. If you discovered something missing in part 1, you may fill in the value with a
---- place holder of the appropriate data type.
----- We are going to perform a query and declare the creation of tables.
SELECT item_id
,test_a AS test_assignment
,(
CASE
WHEN test_a IS NOT NULL
THEN 'test_a'
ELSE NULL
END
) AS test_number
,(
CASE
WHEN test_a IS NOT NULL
THEN '2013-01-05 00:00:00'
ELSE NULL
END
) AS test_start_date
FROM dsv1069.final_assignments_qa
UNION
SELECT item_id
,test_b AS test_assignment
,(
CASE
WHEN test_b IS NOT NULL
THEN 'test_b'
ELSE NULL
END
) AS test_number
,(
CASE
WHEN test_b IS NOT NULL
THEN '2013-01-05 00:00:00'
ELSE NULL
END
) AS test_start_date
FROM dsv1069.final_assignments_qa
UNION
SELECT item_id
,test_c AS test_assignment
,(
CASE
WHEN test_c IS NOT NULL
THEN 'test_c'
ELSE NULL
END
) AS test_number
,(
CASE
WHEN test_c IS NOT NULL
THEN '2013-01-05 00:00:00'
ELSE NULL
END
) AS test_start_date
FROM dsv1069.final_assignments_qa
UNION
SELECT item_id
,test_d AS test_assignment
,(
CASE
WHEN test_d IS NOT NULL
THEN 'test_d'
ELSE NULL
END
) AS test_number
,(
CASE
WHEN test_d IS NOT NULL
THEN '2013-01-05 00:00:00'
ELSE NULL
END
) AS test_start_date
FROM dsv1069.final_assignments_qa
UNION
SELECT item_id
,test_e AS test_assignment
,(
CASE
WHEN test_e IS NOT NULL
THEN 'test_e'
ELSE NULL
END
) AS test_number
,(
CASE
WHEN test_e IS NOT NULL
THEN '2013-01-05 00:00:00'
ELSE NULL
END
) AS test_start_date
FROM dsv1069.final_assignments_qa
UNION
SELECT item_id
,test_f AS test_assignment
,(
CASE
WHEN test_f IS NOT NULL
THEN 'test_f'
ELSE NULL
END
) AS test_number
,(
CASE
WHEN test_f IS NOT NULL
THEN '2013-01-05 00:00:00'
ELSE NULL
END
) AS test_start_date
FROM dsv1069.final_assignments_qa;
---- Use the final_assignments table to calculate the order binary for the 30 day window after the test assignment
---- for item_test_2 (You may include the day the test started)
----- We are going to use the final_assignment table to perform the binary calculation.
SELECT test_assignment
,COUNT(DISTINCT item_id) AS number_of_items
,SUM(order_binary) AS items_ordered_30d
FROM (
SELECT item_test_2.item_id, item_test_2.test_assignment, item_test_2.test_number
,item_test_2.test_start_date, item_test_2.created_at
,MAX(CASE
WHEN (
created_at > test_start_date
AND DATE_PART('day', created_at - test_start_date) <= 30
)
THEN 1
ELSE 0
END) AS order_binary
FROM (
SELECT final_assignments.*
,DATE (orders.created_at) AS created_at
FROM dsv1069.final_assignments AS final_assignments
LEFT JOIN dsv1069.orders AS orders ON final_assignments.item_id = orders.item_id
WHERE test_number = 'item_test_2'
) AS item_test_2
GROUP BY item_test_2.item_id
,item_test_2.test_assignment
,item_test_2.test_number
,item_test_2.test_start_date
,item_test_2.created_at
) AS order_binary
GROUP BY test_assignment;
---- Use the final_assignments table to calculate the view binary, and average views for the 30 day window
---- after the test assignment for item_test_2. (You may include the day the test started)
----- We will use the final_assignment table to calculate the binary view and the average.
SELECT item_test_2.item_id
,item_test_2.test_assignment
,item_test_2.test_number
,MAX(CASE
WHEN (
view_date > test_start_date
AND DATE_PART('day', view_date - test_start_date) <= 30
)
THEN 1
ELSE 0
END) AS view_binary
FROM (
SELECT final_assignments.*
,DATE (events.event_time) AS view_date
FROM dsv1069.final_assignments AS final_assignments
LEFT JOIN (
SELECT event_time
,CASE
WHEN parameter_name = 'item_id'
THEN CAST(parameter_value AS NUMERIC)
ELSE NULL
END AS item_id
FROM dsv1069.events
WHERE event_name = 'view_item'
) AS events ON final_assignments.item_id = events.item_id
WHERE test_number = 'item_test_2'
) AS item_test_2
GROUP BY item_test_2.item_id, item_test_2.test_assignment
,item_test_2.test_number LIMIT 100;
---- Use the https://thumbtack.github.io/abba/demo/abba.html to compute the lifts in metrics and the p-values for the binary
---- metrics (30 day order binary and 30 day view binary) using a interval 95% confidence.
----- We will use https://thumbtack.github.io/abba/demo/abba.html to calculate the increases in metrics and P-values.
SELECT test_assignment
,test_number
,COUNT(DISTINCT item) AS number_of_items
,SUM(view_binary_30d) AS view_binary_30d
FROM (
SELECT final_assignments.item_id AS item
,test_assignment, test_number, test_start_date
,MAX((
CASE
WHEN DATE (event_time) - DATE (test_start_date) BETWEEN 0
AND 30
THEN 1
ELSE 0
END
)) AS view_binary_30d
FROM dsv1069.final_assignments
LEFT JOIN dsv1069.view_item_events ON final_assignments.item_id = view_item_events.item_id
WHERE test_number = 'item_test_2'
GROUP BY final_assignments.item_id, test_assignment, test_number, test_start_date
) AS view_binary
GROUP BY test_assignment, test_number, test_start_date;
------- Completed :) :)
|
import React from 'react';
import PropTypes from 'prop-types';
import { ListGroup } from 'react-bootstrap';
import Card from 'react-bootstrap/Card';
export default function User({ user }) {
console.warn('UserImage: ', user.fbUser.photoURL);
let photo = '';
if (user.profileImageUrl === null) {
photo = 'https://media.istockphoto.com/id/1337144146/vector/default-avatar-profile-icon-vector.jpg?s=612x612&w=0&k=20&c=BIbFwuv7FxTWvh5S3vB6bkT0Qv8Vn8N5Ffseq84ClGI=';
} else {
photo = user.profileImageUrl;
}
return (
<Card style={{ width: '18rem', margin: '10px' }}>
<Card.Img variant="top" src={photo} alt="profile picture" style={{ height: 'auto' }} />
<Card.Body>
<Card.Title>{`${user.firstName} ${user.lastName}`}</Card.Title>
<Card.Text>
{user.email}
</Card.Text>
</Card.Body>
<ListGroup className="list-group-flush">
<ListGroup.Item>Bio: {user.bio}</ListGroup.Item>
</ListGroup>
</Card>
);
}
User.propTypes = {
user: PropTypes.shape({
profileImageUrl: PropTypes.string,
firstName: PropTypes.string,
lastName: PropTypes.string,
bio: PropTypes.string,
email: PropTypes.string,
createdOn: PropTypes.string,
fbUser: PropTypes.shape({
photoURL: PropTypes.string,
}),
}).isRequired,
};
|
# 6. 扩展功能:用户自定义运算符
## 6.1 介绍
欢迎阅读“使用 LLVM 实现语言”教程的第 6 章。在我们教程的这一点上,我们现在拥有了一种功能齐全的语言,它非常简单,但也很有用。然而,它仍然存在一个大问题。我们的语言没有很多有用的运算符(比如除法、逻辑否定,甚至除了小于之外的任何比较)。
本教程的这一章题外话,将用户定义的运算符添加到简单而美观的 Kaleidoscope 语言中。这个题外话现在在某些方面为我们提供了一种简单而丑陋的语言,但同时也是一种强大的语言。创建自己的语言的一大好处是您可以决定什么是好是坏。在本教程中,我们假设可以使用它来展示一些有趣的解析技术。
在本教程结束时,我们将运行一个呈现 Mandelbrot 集的示例 Kaleidoscope 应用程序。这给出了一个示例,说明您可以使用 Kaleidoscope 及其功能集构建什么。
## 6.2 用户自定义运算符
我们将添加到 Kaleidoscope 中的“运算符重载”比 C++ 等语言更通用。在 C++ 中,你只能重新定义现有的运算符:你不能通过编程方式改变语法、引入新的运算符、改变优先级等。在本章中,我们将把这个能力添加到 Kaleidoscope 中,这将让用户四舍五入支持的运算符集。
在像这样的教程中介绍用户定义的运算符的目的是展示使用手写解析器的强大功能和灵活性。到目前为止,我们一直在实现的解析器对语法的大部分部分使用递归下降,对表达式使用运算符优先级解析。详见第 2 章。通过使用运算符优先级解析,程序员可以很容易地在语法中引入新的运算符:语法在 JIT 运行时是动态可扩展的。
我们将添加的两个特定功能是可编程的一元运算符(目前,Kaleidoscope 根本没有一元运算符)和二元运算符。这方面的一个例子是:
``` cpp
# Logical unary not.
def unary!(v)
if v then
0
else
1;
# Define > with the same precedence as <.
def binary> 10 (LHS RHS)
RHS < LHS;
# Binary "logical or", (note that it does not "short circuit")
def binary| 5 (LHS RHS)
if LHS then
1
else if RHS then
1
else
0;
# Define = with slightly lower precedence than relationals.
def binary= 9 (LHS RHS)
!(LHS < RHS | LHS > RHS);
```
许多语言都渴望能够在语言本身中实现其标准运行时库。在 Kaleidoscope 中,我们可以在库中实现该语言的重要部分!
我们将这些功能的实现分为两部分:实现对用户定义的二元运算符的支持和添加一元运算符。
## 6.3 用户自定义二元运算符
使用我们当前的框架添加对用户定义的二元运算符的支持非常简单。我们将首先添加对一元/二元关键字的支持:
``` cpp
enum Token {
...
// operators
tok_binary = -11,
tok_unary = -12
};
...
static int gettok() {
...
if (IdentifierStr == "for")
return tok_for;
if (IdentifierStr == "in")
return tok_in;
if (IdentifierStr == "binary")
return tok_binary;
if (IdentifierStr == "unary")
return tok_unary;
return tok_identifier;
```
这只是添加了对一元和二元关键字的词法分析器支持,就像我们在前面的章节中所做的那样。关于我们当前的 AST 的一件好事是,我们通过使用它们的 ASCII 码作为操作码来表示具有完全泛化的二元运算符。对于我们的扩展运算符,我们将使用相同的表示,因此我们不需要任何新的 AST 或解析器支持。
另一方面,我们必须能够在 ```def binary| 5``` 中表示这些新运算符的定义。到目前为止,在我们的语法中,函数定义的“名称”被解析为“原型”产生式并进入 ```PrototypeAST``` AST 节点。为了将我们新的用户定义的运算符表示为原型,我们必须像这样扩展 ```PrototypeAST``` AST 节点:
``` cpp
/// PrototypeAST - This class represents the "prototype" for a function,
/// which captures its argument names as well as if it is an operator.
class PrototypeAST {
std::string Name;
std::vector<std::string> Args;
bool IsOperator;
unsigned Precedence; // Precedence if a binary op.
public:
PrototypeAST(const std::string &name, std::vector<std::string> Args,
bool IsOperator = false, unsigned Prec = 0)
: Name(name), Args(std::move(Args)), IsOperator(IsOperator),
Precedence(Prec) {}
Function *codegen();
const std::string &getName() const { return Name; }
bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
char getOperatorName() const {
assert(isUnaryOp() || isBinaryOp());
return Name[Name.size() - 1];
}
unsigned getBinaryPrecedence() const { return Precedence; }
};
```
基本上,除了知道原型的名称外,我们现在还跟踪它是否是一个运算符,如果是,运算符的优先级是多少。优先级仅用于二元运算符(如下所示,它不适用于一元运算符)。现在我们有一种方法来表示用户定义的运算符的原型,我们需要解析它:
``` cpp
/// prototype
/// ::= id '(' id* ')'
/// ::= binary LETTER number? (id, id)
static std::unique_ptr<PrototypeAST> ParsePrototype() {
std::string FnName;
unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
unsigned BinaryPrecedence = 30;
switch (CurTok) {
default:
return LogErrorP("Expected function name in prototype");
case tok_identifier:
FnName = IdentifierStr;
Kind = 0;
getNextToken();
break;
case tok_binary:
getNextToken();
if (!isascii(CurTok))
return LogErrorP("Expected binary operator");
FnName = "binary";
FnName += (char)CurTok;
Kind = 2;
getNextToken();
// Read the precedence if present.
if (CurTok == tok_number) {
if (NumVal < 1 || NumVal > 100)
return LogErrorP("Invalid precedence: must be 1..100");
BinaryPrecedence = (unsigned)NumVal;
getNextToken();
}
break;
}
if (CurTok != '(')
return LogErrorP("Expected '(' in prototype");
std::vector<std::string> ArgNames;
while (getNextToken() == tok_identifier)
ArgNames.push_back(IdentifierStr);
if (CurTok != ')')
return LogErrorP("Expected ')' in prototype");
// success.
getNextToken(); // eat ')'.
// Verify right number of names for operator.
if (Kind && ArgNames.size() != Kind)
return LogErrorP("Invalid number of operands for operator");
return std::make_unique<PrototypeAST>(FnName, std::move(ArgNames), Kind != 0,
BinaryPrecedence);
}
```
这些都是相当简单的解析代码,我们过去已经看到过很多类似的代码。上面代码的一个有趣部分是为二元运算符设置 ```FnName``` 的几行代码。这会为新定义的“@”运算符构建类似“binary@”的名称。然后它利用了 LLVM 符号表中的符号名称允许包含任何字符的事实,包括嵌入的 nul 字符。
下一个有趣的事情是对这些二元运算符的代码生成支持。鉴于我们当前的结构,这是为我们现有的二元运算符节点简单添加默认情况:
``` cpp
Value *BinaryExprAST::codegen() {
Value *L = LHS->codegen();
Value *R = RHS->codegen();
if (!L || !R)
return nullptr;
switch (Op) {
case '+':
return Builder.CreateFAdd(L, R, "addtmp");
case '-':
return Builder.CreateFSub(L, R, "subtmp");
case '*':
return Builder.CreateFMul(L, R, "multmp");
case '<':
L = Builder.CreateFCmpULT(L, R, "cmptmp");
// Convert bool 0/1 to double 0.0 or 1.0
return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
"booltmp");
default:
break;
}
// If it wasn't a builtin binary operator, it must be a user defined one. Emit
// a call to it.
Function *F = getFunction(std::string("binary") + Op);
assert(F && "binary operator not found!");
Value *Ops[2] = { L, R };
return Builder.CreateCall(F, Ops, "binop");
}
```
正如您在上面看到的,新代码实际上非常简单。它只是在符号表中查找适当的运算符并生成对其的函数调用。由于用户定义的运算符只是作为普通函数构建的(因为“原型”归结为具有正确名称的函数),所以一切就绪。
我们缺少的最后一段代码是一些顶级魔法:
``` cpp
Function *FunctionAST::codegen() {
// Transfer ownership of the prototype to the FunctionProtos map, but keep a
// reference to it for use below.
auto &P = *Proto;
FunctionProtos[Proto->getName()] = std::move(Proto);
Function *TheFunction = getFunction(P.getName());
if (!TheFunction)
return nullptr;
// If this is an operator, install it.
if (P.isBinaryOp())
BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
// Create a new basic block to start insertion into.
BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
...
```
基本上,在对函数进行代码生成之前,如果它是用户定义的运算符,我们会将其注册到优先级表中。这允许我们已有的二元运算符解析逻辑来处理它。由于我们正在开发一个完全通用的运算符优先级解析器,因此我们需要做的就是“扩展语法”。
现在我们有了有用的用户定义的二元运算符。这在很大程度上建立在我们之前为其他运营商构建的框架之上。添加一元运算符更具挑战性,因为我们还没有任何框架 - 让我们看看它需要什么。
## 6.4 用户自定义一元运算符
由于我们目前不支持 Kaleidoscope 语言中的一元运算符,因此我们需要添加所有内容来支持它们。上面,我们向词法分析器添加了对“一元”关键字的简单支持。除此之外,我们还需要一个 AST 节点:
``` cpp
/// UnaryExprAST - Expression class for a unary operator.
class UnaryExprAST : public ExprAST {
char Opcode;
std::unique_ptr<ExprAST> Operand;
public:
UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
: Opcode(Opcode), Operand(std::move(Operand)) {}
Value *codegen() override;
};
```
这个 AST 节点现在非常简单明了。它直接镜像二元运算符 AST 节点,只是它只有一个孩子。有了这个,我们需要添加解析逻辑。解析一元运算符非常简单:我们将添加一个新函数来完成它:
``` cpp
/// unary
/// ::= primary
/// ::= '!' unary
static std::unique_ptr<ExprAST> ParseUnary() {
// If the current token is not an operator, it must be a primary expr.
if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
return ParsePrimary();
// If this is a unary operator, read it.
int Opc = CurTok;
getNextToken();
if (auto Operand = ParseUnary())
return std::make_unique<UnaryExprAST>(Opc, std::move(Operand));
return nullptr;
}
```
我们在这里添加的语法非常简单。如果我们在解析主运算符时看到一元运算符,我们会将运算符作为前缀吃掉,并将剩余部分解析为另一个一元运算符。这使我们能够处理多个一元运算符(例如“!!x”)。请注意,一元运算符不能像二元运算符那样有歧义的解析,因此不需要优先级信息。
这个函数的问题是我们需要从某个地方调用 ParseUnary。为此,我们将 ParsePrimary 的先前调用者更改为调用 ParseUnary:
``` cpp
/// binoprhs
/// ::= ('+' unary)*
static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
std::unique_ptr<ExprAST> LHS) {
...
// Parse the unary expression after the binary operator.
auto RHS = ParseUnary();
if (!RHS)
return nullptr;
...
}
/// expression
/// ::= unary binoprhs
///
static std::unique_ptr<ExprAST> ParseExpression() {
auto LHS = ParseUnary();
if (!LHS)
return nullptr;
return ParseBinOpRHS(0, std::move(LHS));
}
```
通过这两个简单的更改,我们现在能够解析一元运算符并为它们构建 AST。接下来,我们需要添加对原型的解析器支持,以解析一元运算符原型。我们扩展上面的二元运算符代码:
``` cpp
/// prototype
/// ::= id '(' id* ')'
/// ::= binary LETTER number? (id, id)
/// ::= unary LETTER (id)
static std::unique_ptr<PrototypeAST> ParsePrototype() {
std::string FnName;
unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
unsigned BinaryPrecedence = 30;
switch (CurTok) {
default:
return LogErrorP("Expected function name in prototype");
case tok_identifier:
FnName = IdentifierStr;
Kind = 0;
getNextToken();
break;
case tok_unary:
getNextToken();
if (!isascii(CurTok))
return LogErrorP("Expected unary operator");
FnName = "unary";
FnName += (char)CurTok;
Kind = 1;
getNextToken();
break;
case tok_binary:
...
```
与二元运算符一样,我们使用包含运算符字符的名称来命名一元运算符。这在代码生成时帮助我们。说到,我们需要添加的最后一部分是对一元运算符的代码生成支持。它看起来像这样:
``` cpp
Value *UnaryExprAST::codegen() {
Value *OperandV = Operand->codegen();
if (!OperandV)
return nullptr;
Function *F = getFunction(std::string("unary") + Opcode);
if (!F)
return LogErrorV("Unknown unary operator");
return Builder.CreateCall(F, OperandV, "unop");
}
```
此代码类似于二元运算符的代码,但比它更简单。它更简单主要是因为它不需要处理任何预定义的运算符。
## 6.5 简单实践
这有点难以置信,但通过我们在最后几章中介绍的一些简单扩展,我们已经发展出一种真实的语言。有了它,我们可以做很多有趣的事情,包括 I/O、数学和许多其他事情。例如,我们现在可以添加一个漂亮的排序运算符(printd 被定义为打印出指定值和换行符):
``` cpp
ready> extern printd(x);
Read extern:
declare double @printd(double)
ready> def binary : 1 (x y) 0; # Low-precedence operator that ignores operands.
...
ready> printd(123) : printd(456) : printd(789);
123.000000
456.000000
789.000000
Evaluated to 0.000000
```
我们还可以定义一堆其他“原始”操作,例如:
``` cpp
# Logical unary not.
def unary!(v)
if v then
0
else
1;
# Unary negate.
def unary-(v)
0-v;
# Define > with the same precedence as <.
def binary> 10 (LHS RHS)
RHS < LHS;
# Binary logical or, which does not short circuit.
def binary| 5 (LHS RHS)
if LHS then
1
else if RHS then
1
else
0;
# Binary logical and, which does not short circuit.
def binary& 6 (LHS RHS)
if !LHS then
0
else
!!RHS;
# Define = with slightly lower precedence than relationals.
def binary = 9 (LHS RHS)
!(LHS < RHS | LHS > RHS);
# Define ':' for sequencing: as a low-precedence operator that ignores operands
# and just returns the RHS.
def binary : 1 (x y) y;
```
鉴于前面的 if/then/else 支持,我们还可以为 I/O 定义有趣的函数。例如,下面打印出一个字符,其“密度”反映了传入的值:值越低,字符越密集:
``` cpp
ready> extern putchard(char);
...
ready> def printdensity(d)
if d > 8 then
putchard(32) # ' '
else if d > 4 then
putchard(46) # '.'
else if d > 2 then
putchard(43) # '+'
else
putchard(42); # '*'
...
ready> printdensity(1): printdensity(2): printdensity(3):
printdensity(4): printdensity(5): printdensity(9):
putchard(10);
**++.
Evaluated to 0.000000
```
基于这些简单的原始操作,我们可以开始定义更多有趣的东西。例如,这里有一个小函数,它确定复平面中某个函数发散所需的迭代次数:
``` cpp
# Determine whether the specific location diverges.
# Solve for z = z^2 + c in the complex plane.
def mandelconverger(real imag iters creal cimag)
if iters > 255 | (real*real + imag*imag > 4) then
iters
else
mandelconverger(real*real - imag*imag + creal,
2*real*imag + cimag,
iters+1, creal, cimag);
# Return the number of iterations required for the iteration to escape
def mandelconverge(real imag)
mandelconverger(real, imag, 0, real, imag);
```
这个 ```z = z2 + c``` 函数是一个美丽的小生物,它是计算 [Mandelbrot 集](http://en.wikipedia.org/wiki/Mandelbrot_set)的基础。我们的 ```mandelconverge``` 函数返回复杂轨道逃逸所需的迭代次数,饱和到 255。这本身并不是一个非常有用的函数,但是如果你在二维平面上绘制它的值,你可以看到 Mandelbrot放。鉴于我们仅限于在这里使用 putchard,我们惊人的图形输出是有限的,但我们可以使用上面的密度绘图仪将一些东西组合在一起:
``` cpp
# Compute and plot the mandelbrot set with the specified 2 dimensional range
# info.
def mandelhelp(xmin xmax xstep ymin ymax ystep)
for y = ymin, y < ymax, ystep in (
(for x = xmin, x < xmax, xstep in
printdensity(mandelconverge(x,y)))
: putchard(10)
)
# mandel - This is a convenient helper function for plotting the mandelbrot set
# from the specified position with the specified Magnification.
def mandel(realstart imagstart realmag imagmag)
mandelhelp(realstart, realstart+realmag*78, realmag,
imagstart, imagstart+imagmag*40, imagmag);
```
鉴于此,我们可以尝试绘制 mandelbrot 集!让我们试试看:
``` cpp
ready> mandel(-2.3, -1.3, 0.05, 0.07);
*******************************+++++++++++*************************************
*************************+++++++++++++++++++++++*******************************
**********************+++++++++++++++++++++++++++++****************************
*******************+++++++++++++++++++++.. ...++++++++*************************
*****************++++++++++++++++++++++.... ...+++++++++***********************
***************+++++++++++++++++++++++..... ...+++++++++*********************
**************+++++++++++++++++++++++.... ....+++++++++********************
*************++++++++++++++++++++++...... .....++++++++*******************
************+++++++++++++++++++++....... .......+++++++******************
***********+++++++++++++++++++.... ... .+++++++*****************
**********+++++++++++++++++....... .+++++++****************
*********++++++++++++++........... ...+++++++***************
********++++++++++++............ ...++++++++**************
********++++++++++... .......... .++++++++**************
*******+++++++++..... .+++++++++*************
*******++++++++...... ..+++++++++*************
*******++++++....... ..+++++++++*************
*******+++++...... ..+++++++++*************
*******.... .... ...+++++++++*************
*******.... . ...+++++++++*************
*******+++++...... ...+++++++++*************
*******++++++....... ..+++++++++*************
*******++++++++...... .+++++++++*************
*******+++++++++..... ..+++++++++*************
********++++++++++... .......... .++++++++**************
********++++++++++++............ ...++++++++**************
*********++++++++++++++.......... ...+++++++***************
**********++++++++++++++++........ .+++++++****************
**********++++++++++++++++++++.... ... ..+++++++****************
***********++++++++++++++++++++++....... .......++++++++*****************
************+++++++++++++++++++++++...... ......++++++++******************
**************+++++++++++++++++++++++.... ....++++++++********************
***************+++++++++++++++++++++++..... ...+++++++++*********************
*****************++++++++++++++++++++++.... ...++++++++***********************
*******************+++++++++++++++++++++......++++++++*************************
*********************++++++++++++++++++++++.++++++++***************************
*************************+++++++++++++++++++++++*******************************
******************************+++++++++++++************************************
*******************************************************************************
*******************************************************************************
*******************************************************************************
Evaluated to 0.000000
ready> mandel(-2, -1, 0.02, 0.04);
**************************+++++++++++++++++++++++++++++++++++++++++++++++++++++
***********************++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*********************+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
*******************+++++++++++++++++++++++++++++++++++++++++++++++++++++++++...
*****************+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.....
***************++++++++++++++++++++++++++++++++++++++++++++++++++++++++........
**************++++++++++++++++++++++++++++++++++++++++++++++++++++++...........
************+++++++++++++++++++++++++++++++++++++++++++++++++++++..............
***********++++++++++++++++++++++++++++++++++++++++++++++++++........ .
**********++++++++++++++++++++++++++++++++++++++++++++++.............
********+++++++++++++++++++++++++++++++++++++++++++..................
*******+++++++++++++++++++++++++++++++++++++++.......................
******+++++++++++++++++++++++++++++++++++...........................
*****++++++++++++++++++++++++++++++++............................
*****++++++++++++++++++++++++++++...............................
****++++++++++++++++++++++++++...... .........................
***++++++++++++++++++++++++......... ...... ...........
***++++++++++++++++++++++............
**+++++++++++++++++++++..............
**+++++++++++++++++++................
*++++++++++++++++++.................
*++++++++++++++++............ ...
*++++++++++++++..............
*+++....++++................
*.......... ...........
*
*.......... ...........
*+++....++++................
*++++++++++++++..............
*++++++++++++++++............ ...
*++++++++++++++++++.................
**+++++++++++++++++++................
**+++++++++++++++++++++..............
***++++++++++++++++++++++............
***++++++++++++++++++++++++......... ...... ...........
****++++++++++++++++++++++++++...... .........................
*****++++++++++++++++++++++++++++...............................
*****++++++++++++++++++++++++++++++++............................
******+++++++++++++++++++++++++++++++++++...........................
*******+++++++++++++++++++++++++++++++++++++++.......................
********+++++++++++++++++++++++++++++++++++++++++++..................
Evaluated to 0.000000
ready> mandel(-0.9, -1.4, 0.02, 0.03);
*******************************************************************************
*******************************************************************************
*******************************************************************************
**********+++++++++++++++++++++************************************************
*+++++++++++++++++++++++++++++++++++++++***************************************
+++++++++++++++++++++++++++++++++++++++++++++**********************************
++++++++++++++++++++++++++++++++++++++++++++++++++*****************************
++++++++++++++++++++++++++++++++++++++++++++++++++++++*************************
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++**********************
+++++++++++++++++++++++++++++++++.........++++++++++++++++++*******************
+++++++++++++++++++++++++++++++.... ......+++++++++++++++++++****************
+++++++++++++++++++++++++++++....... ........+++++++++++++++++++**************
++++++++++++++++++++++++++++........ ........++++++++++++++++++++************
+++++++++++++++++++++++++++......... .. ...+++++++++++++++++++++**********
++++++++++++++++++++++++++........... ....++++++++++++++++++++++********
++++++++++++++++++++++++............. .......++++++++++++++++++++++******
+++++++++++++++++++++++............. ........+++++++++++++++++++++++****
++++++++++++++++++++++........... ..........++++++++++++++++++++++***
++++++++++++++++++++........... .........++++++++++++++++++++++*
++++++++++++++++++............ ...........++++++++++++++++++++
++++++++++++++++............... .............++++++++++++++++++
++++++++++++++................. ...............++++++++++++++++
++++++++++++.................. .................++++++++++++++
+++++++++.................. .................+++++++++++++
++++++........ . ......... ..++++++++++++
++............ ...... ....++++++++++
.............. ...++++++++++
.............. ....+++++++++
.............. .....++++++++
............. ......++++++++
........... .......++++++++
......... ........+++++++
......... ........+++++++
......... ....+++++++
........ ...+++++++
....... ...+++++++
....+++++++
.....+++++++
....+++++++
....+++++++
....+++++++
Evaluated to 0.000000
ready> ^D
```
此时,您可能开始意识到 Kaleidoscope 是一种真实而强大的语言。它可能不是自相似的 :),但它可以用来绘制自相似的东西!
至此,我们结束了本教程的“添加用户定义的运算符”一章。我们已经成功地扩充了我们的语言,添加了在库中扩展语言的能力,并且我们已经展示了如何使用它在 Kaleidoscope 中构建一个简单但有趣的最终用户应用程序。在这一点上,Kaleidoscope 可以构建各种功能性的应用程序,并且可以调用具有副作用的函数,但它实际上不能定义和改变变量本身。
引人注目的是,变量变异是某些语言的一个重要特征,如何在不向前端添加“SSA 构造”阶段的情况下添加对可变变量的支持一点也不明显。在下一章中,我们将介绍如何在不在前端构建 SSA 的情况下添加变量变异。
## 6.6 完整代码清单
这是我们运行示例的完整代码清单,增强了对用户定义运算符的支持。要构建此示例,请使用:
``` bash
# Compile
clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core orcjit native` -O3 -o toy
# Run
./toy
```
在某些平台上,您需要在链接时指定 -rdynamic 或 -Wl,--export-dynamic。这确保了在主可执行文件中定义的符号被导出到动态链接器,因此在运行时可用于符号解析。如果将支持代码编译到共享库中,则不需要这样做,尽管这样做会在 Windows 上导致问题。
|
<%= form_for(@ticket) do |f| %>
<% if @ticket.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@ticket.errors.count, "error") %> prohibited this ticket from being saved:</h2>
<ul>
<% @ticket.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :seat_id_seq %><br />
<%= f.text_field :seat_id_seq %>
</div>
<div class="field">
<%= f.label :addres %><br />
<%= f.text_area :addres %>
</div>
<div class="field">
<%= f.label :price_paid %><br />
<%= f.text_field :price_paid %>
</div>
<div class="field">
<%= f.label :email_addres %><br />
<%= f.text_field :email_addres %>
</div>
<div class="field">
<%= f.label :phone %><br />
<%= f.text_field :phone %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
|
import { z } from 'zod';
export const signUpFormSchema = z
.object({
email: z.string(),
password: z
.string()
.regex(
/^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[!@#$%^&*]).{8,20}$/,
'패스워드는 암호 대소문자, 숫자, 기호 포함 8~20자 이내'
),
passwordCheck: z.string(),
nickname: z
.string()
.min(2, '닉네임은 최소 2자 이상이어야 합니다.')
.max(12, '닉네임은 최대 12자 이내여야 합니다.'),
// .regex(
// /^[가-힣a-zA-Z0-9._]{2,12}$/,
// '닉네임은 한글, 영문 대소문자, 숫자, _ , . 만 허용됩니다.'
// ),
job: z.object({
name: z.string(),
isPublic: z.boolean().default(true),
}),
gender: z.object({
name: z.string(),
isPublic: z.boolean().default(true),
}),
birthDate: z.object({
date: z.string(),
isPublic: z.boolean().default(true),
}),
terms: z.object({
age: z.boolean(),
termsOfUse: z.boolean(),
privacyPolicy: z.boolean(),
marketing: z.boolean().optional(),
ads: z.boolean().optional(),
}),
})
.refine((data) => data.password === data.passwordCheck, {
path: ['passwordCheck'],
message: '비밀번호가 맞지 않습니다.',
});
export type SignUpFormValues = z.infer<typeof signUpFormSchema>;
export type TermsKeys = keyof SignUpFormValues['terms'];
const getToday = () => {
const dateNow = new Date();
const today = dateNow.toISOString().slice(0, 10);
return today;
};
export const defaultValues: SignUpFormValues = {
email: '',
password: '',
passwordCheck: '',
job: {
name: '',
isPublic: true,
},
nickname: '',
gender: {
name: '남자',
isPublic: true,
},
birthDate: {
date: getToday(),
isPublic: true,
},
terms: {
age: false,
termsOfUse: false,
privacyPolicy: false,
marketing: false,
ads: false,
},
};
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title class="page-sit">goit-markup-hw-02</title>
<link rel="stylesheet" href="./css/styles.css" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
</head>
<body>
<!--HEADER-->
<header class="header">
<nav class="header-nav">
<a href="./index.html" class="header-logo">Web<span class="header-logo-color">Studio</span></a>
<ul class="header-menu-list">
<li class="header-menu-item">
<a class="header-menu-link" href="./index.html" >Studio</a>
</li>
<li class="header-menu-item">
<a class="header-menu-link" href="" >Portfolio</a>
</li>
<li class="header-menu-item">
<a class="header-menu-link" href="" >Contacts</a>
</li>
</ul>
</nav>
<address class="header-address">
<ul class="header-address-list">
<li class="header-address-item">
<a class="header-address-link" href="mailto:info@devstudio.com">info@devstudio.com</a>
</li>
<li class="header-address-item">
<a class="header-address-link" href="tel:+110001111111">+11 (000) 111-11-11</a>
</li>
</ul>
</address>
</header>
<!--MAIN-->
<main>
<!--Baner "Effective Solutions"-->
<section class="headline">
<h1 class="headline-title">Effective Solutions for Your Business</h1>
<button class="headline-btn" type="button">Order Service</button>
</section>
<!--Content (Strategy, Punctuality, Diligence, Technologies)-->
<section class="content-spdt">
<h2 class="visually-hidden">Advantages</h2>
<ul class="content-spdt-menu-list">
<li class="content-menu-item">
<h3 class="content-subtitle">Strategy</h3>
<p class="content-menu-text">Our goal is to identify the business problem to walk away with the perfect and creative solution.</p>
</li>
<li class="content-menu-item">
<h3 class="content-subtitle">Punctuality</h3>
<p class="content-menu-text">Bring the key message to the brand's audience for the best price within the shortest possible time.</p>
</li>
<li class="content-menu-item">
<h3 class="content-subtitle">Diligence</h3>
<p class="content-menu-text">Research and confirm brands that present the strongest digital growth opportunities and minimize risk.</p>
</li>
<li class="content-menu-item">
<h3 class="content-subtitle">Technologies</h3>
<p class="content-menu-text">Design practice focused on digital experiences. We bring forth a deep passion for problem-solving.</p>
</li>
</ul>
</section>
<!--Our Team-->
<section class="team">
<h2 class="team-title">Our Team</h2>
<ul class="team-menu-list">
<li class="team-menu-item">
<img class="team-image"
src="./images/mark.jpg"
alt="Mark Guerrero"
width="264"
height="260"
/>
<h3 class="team-subtitle">Mark Guerrero</h3>
<p class="team-menu-text">Product Designer</p>
</li>
<li class="team-menu-item">
<img class="team-image"
src="./images/tom.jpg"
alt="Tom Ford"
width="264"
height="260"
/>
<h3 class="team-subtitle">Tom Ford</h3>
<p class="team-menu-text">Frontend Developer</p>
</li>
<li class="team-menu-item">
<img class="team-image"
src="./images/camila.jpg"
alt="Camila Garcia"
width="264"
height="260"
/>
<h3 class="team-subtitle">Camila Garcia</h3>
<p class="team-menu-text">Marketing</p>
</li>
<li class="team-menu-item">
<img class="team-image"
src="./images/daniel.jpg"
alt="Daniel Wilson"
width="264"
height="260"
/>
<h3 class="team-subtitle">Daniel Wilson</h3>
<p class="team-menu-text">UI Designer</p>
</li>
</ul>
</section>
<!--Our Portfolio-->
<section class="portfolio">
<h2 class="portfolio-title">Our Portfolio</h2>
<ul class="portfolio-list">
<li class="portfolio-item">
<img class="portfolio-image"
src="./images/banking.jpg"
alt="Banking App"
width="360"
height="300"
/>
<h3 class="portfolio-subtitle">Banking App</h3>
<p class="portfolio-text">App</p>
</li>
<li class="portfolio-item">
<img class="portfolio-image"
src="./images/cashless.jpg"
alt="Cashless Payment"
width="360"
height="300"
/>
<h3 class="portfolio-subtitle">Cashless Payment</h3>
<p class="portfolio-text">Marketing</p>
</li>
<li class="portfolio-item">
<img class="portfolio-image"
src="./images/meditation.jpg"
alt="Meditation App"
width="360"
height="300"
/>
<h3 class="portfolio-subtitle">Meditation App</h3>
<p class="portfolio-text">App</p>
</li>
<li class="portfolio-item">
<img class="portfolio-image"
src="./images/taxi.jpg"
alt="Taxi Service"
width="360"
height="300"
/>
<h3 class="portfolio-subtitle">Taxi Service</h3>
<p class="portfolio-text">Marketing</p>
</li>
<li class="portfolio-item">
<img class="portfolio-image"
src="./images/screen.jpg"
alt="Screen Illustrations"
width="360"
height="300"
/>
<h3 class="portfolio-subtitle">Screen Illustrations</h3>
<p class="portfolio-text">Design</p>
</li>
<li class="portfolio-item">
<img class="portfolio-image"
src="./images/online.jpg"
alt="Online Courses"
width="360"
height="300"
/>
<h3 class="portfolio-subtitle">Online Courses</h3>
<p class="portfolio-text">Marketing</p>
</li>
</ul>
</section>
</main>
<!--FOOTER-->
<footer class="futter">
<a class="futter-logo" href="./index.html">Web<span class="futter-logo-color">Studio</span></a>
<p class="futter-text">Increase the flow of customers and sales for your business with digital marketing & growth solutions.</p>
</footer>
</body>
</html>
|
import Joi from "joi";
export const AuthSchema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().min(6).max(20).required(),
name: Joi.string().optional(),
});
export const ZoneSchema = Joi.object({
name: Joi.string(),
fees: Joi.number(),
});
export const BottomImageSchema = Joi.object({
text: Joi.string().required(),
title: Joi.string().required(),
image: Joi.string().required(),
});
export const ProductSchema = Joi.object({
name: Joi.string().required(),
price: Joi.number().required(),
description: Joi.string().required(),
stock: Joi.number().default(10).optional(),
discountValue: Joi.number().optional(),
categoryId: Joi.string().required(),
image: Joi.array().items(
Joi.object({
url: Joi.string(),
})
),
});
export const SliderSchema = Joi.object({
name: Joi.string().required(),
place: Joi.string().required(),
});
export const BannerSchema = Joi.object({
text: Joi.string().required(),
image: Joi.string().required(),
title: Joi.string().required(),
action: Joi.string().optional(),
location: Joi.string().optional(),
});
export const AnouncementSchema = Joi.object({
text: Joi.string().required(),
});
export const CategorySchema = Joi.object({
name: Joi.string().required(),
imageUrl: Joi.string().required(),
});
export const CouponSchema = Joi.object({
name: Joi.string().required(),
amount: Joi.number().required(),
decription: Joi.string().required(),
Minimum: Joi.number().required(),
expiration: Joi.date().required(),
maxUsage: Joi.number().required(),
});
|
---
permalink: /etc/CodingTest/124/
title: "124 나라의 숫자 파이썬"
toc: true
categories:
- etc🐵CodingTest
comments: true
sidebar:
- title: "etc🐵"
- nav: "etc-menu"
tags:
- CodingTest
- Level1
- 정규표현식
list_name: 정규표현식
sexy: 1
main: "CodingTest"
header:
teaser: /assets/images/python/124-1.jpg
overlay_image: /assets/images/python/124-1.jpg
overlay_filter: 0.5
excerpt: 124나라의 숫자 ↗️
---
[프로그래머스 - 124나라의 숫자 ↗️](https://programmers.co.kr/learn/courses/30/lessons/12899)
# 124 나의 숫자
진법/진수의 문제 유형은 두가지 경우가 있다
1. 10진수 0, 1, 2 .. ,N 과 같이 N진법에 대응하는 10진수 숫자가 0부터 시작하는 경우
2. 10진수 1, 2, 3 .. ,N 과 같이 N진법에 대응하는 10진수 숫자가 1부터 시작하는 경우
- ## 0부터 시작하는 경우
<p align="center"><img src="{{site.baseurl}}/assets/images/python/124-1.jpg"></p>
- ## 1부터 시작하는 경우
<p align="center"><img src="{{site.baseurl}}/assets/images/python/124-2.jpg"></p>
- ### 정답
```python
def solution(n):
if n != 0:
q, r = divmod(n - 1, 3)
return solution(q) + '124'[r]
return ""
```
|
const sellerModel = require("../models/sellerModel");
const userModel = require("../models/userModel");
//CREATE SELLER
const createSellerController = async (req, res) => {
try {
//find user
const user = await userModel.findById({ _id: req.body._id });
if (!user) {
return res.status(404).send({
success: false,
message: "User not found",
});
}
user.role = "seller";
await user.save();
const { city } = req.body;
const seller = new sellerModel({ user: user._id, city });
seller.verified = true;
await seller.save();
res.status(200).send({
success: true,
message: "Seller Created",
});
} catch (error) {
console.log(error);
res.status(500).send({
success: false,
message: "Internal Server Error in CREATE SELLER API",
error,
});
}
};
const getSellerById = async (req, res) => {
try {
const seller = await sellerModel
.findById(req.params.id)
.populate("user")
.exec();
if (!seller) {
return res.status(404).send({
success: false,
message: "Seller not found",
});
}
res.status(200).send({
success: true,
message: "Seller",
seller,
});
} catch (error) {
console.log(error);
res.status(500).send({
success: false,
message: "Internal Server Error in GET SELLER BY ID API",
error,
});
}
};
const getSellerByUserId = async (req, res) => {
try {
const seller = await sellerModel
.findOne({ user: req.params.id })
.populate("user")
.exec();
if (!seller) {
return res.status(404).send({
success: false,
message: "Seller not found",
});
}
res.status(200).send({
success: true,
message: "Seller",
seller,
});
} catch (error) {
console.log(error);
res.status(500).send({
success: false,
message: "Internal Server Error in GET SELLER BY USER ID API",
error,
});
}
};
module.exports = { createSellerController, getSellerById, getSellerByUserId };
|
# Latin American Training on the Microbiological Diagnosis and Genomic Data Analysis Using Bioinformatic
# CursoUnuBiolacVen 2023
Repositorio de informacion del **material practico** para el Curso UnuBiolac Venezuela (INHRR)
- [Rafael Puche](https://twitter.com/rpucheq)
- [Fernando Hernandez](https://twitter.com/Nandox_85)
- [Ascanio Rojas](https://twitter.com/bioinfoula)
- [Bruno Gomez Gil](https://twitter.com/brunogomezgil)
# Material de Apoyo
- [Presentaciones](Presentaciones)
- [Instalacion de maquina virtual](https://sites.google.com/ciad.mx/cursobioinfomicrob/instalacion?authuser=0)
- [Programas Usados](https://drive.google.com/drive/folders/1C-PAQRT5S3GXCt5GeJf1JOnfKdj_Q6MU?usp=sharing)
- [Imagen](https://drive.google.com/file/d/1kCwlowON4-E2M8ZSt_OHDmlJV7UZn-Xy/view?usp=sharing)
# Dia 1 (Martes)
## Practico 1 - Linea de Comandos
## Temario
### 1. Navegación en el sistema de archivos:
Practica el uso de comandos como `cd`, `ls`, `pwd` y `mkdir` para navegar en el sistema de archivos y crear nuevas carpetas.
### 2. Manipulación de archivos:
Usa comandos como `cp`, `mv`, `rm` para copiar, mover, eliminar y crear nuevos archivos.
### 3. Redirección y tuberías:
Practica el uso de la redirección `(>, >>)` y las tuberías `|` para manipular la entrada y salida de los comandos.
### 4. Procesamiento de texto:
Usa comandos como `cat`, `less`, `head`, `tail`, `sort`, `uniq` y `grep` para ver y procesar archivos de texto.
[0800-Comandos](Intro_CLI.md)
## Práctico 2 - Introducción a R y RStudio
[Tutorial](Intro_R.md)
# Dia 3 (Miercoles)
## Practico 3 - Archivos FASTQ, Control de Calidad y Ensamblaje de Genomas
## Archivos
### Mega
Para descargar estos archivos desde `Mega` en tu terminal haz click en los enlaces:
- [Forward](https://mega.nz/file/0opC1CKA#-4VaMGavon43Ky6nrmgs2vUugI3GP_f912mqtJN_xNA)
- [Reverse](https://mega.nz/file/sgpm0R5a#xv1BPKiKvgBRS_gq5Z1Cn04UHtAYA3fr6ZaLujlpiNs)
### 1. Análisis de archivos FASTQ
Conocer la estructura y contenido de un archivo FASTQ. Que informacion podemos obtener?.
### 2. Control de Calidad de archivo FASTQ
Evaluar la calidad de diversos archivos FASTQ usando la herramienta FASTQC
### 3. Ensamble de un genoma bacteriano *de novo*
Emplear SPAdes como ensamblador *de novo* para un genoma problema
### [Tutorial](https://github.com/rpucheq/NGS_data_analysis/blob/main/Practicos/Practico_2.md)
# Dia 4 y 5 (Jueves y Viernes) - Prof. Bruno Gomez Gil
Está diseñado para ser realizado en una imagen virtual disponible ya que ésta tiene precargados los programas, scripts y bases de datos que se utilizarán, por lo que hay primero que instalarla.
Este minicurso consta de tres tipos de análisis:
- [amplicons 16S](https://sites.google.com/ciad.mx/cursobioinfomicrob/16s-v4?authuser=0)
- [metagenomas](https://sites.google.com/ciad.mx/cursobioinfomicrob/visualizaci%C3%B3n?authuser=0)
- [ensamble del genoma del virus SARS-Cov2 de COVID](https://sites.google.com/ciad.mx/cursobioinfomicrob/sars-cov-2?authuser=0)
[Tutoriales e instalacion de maquina virtual](https://sites.google.com/ciad.mx/cursobioinfomicrob/curso-biolac)
|
# PhxJsonRpc
![ci.yml][link-ci]
[![hex.pm badge][link-shield]][link-hex]
Simple implementation of JSON-RPC server, written in [elixir][link-elixir] and working with [phoenix][link-phoenix].
Allows you to define any number of rpc endpoints, which can be accessed via http protocol.
## How it works
The package uses router `macro` for matching RPC calls to your end-user service.
It uses `JSON SCHEMA` as a specification for your services and provides parsing, validation and error handling briefly.
Requests can be served in batches with asyncronous order.
For usage with phoenix see this [guide][link-guide].
## Installation
The package can be installed
by adding `phx_json_rpc` to your list of dependencies in `mix.exs`:
```elixir
def deps do
[
{:phx_json_rpc, "~> 0.5.0"}
]
end
```
This package depends on [ex_json_schema](https://github.com/jonasschmidt/ex_json_schema) for validation purposes.
## Supported phoenix versions
The package tested with `phoenix >= 1.6`, but probably will work with any version started from `1.4`.
## Documentation
The docs can be found at [https://hexdocs.pm/phx_json_rpc][link-docs].
## Links
The package creation was inspired by some other repos:
- [json-rpc-laravel](https://github.com/avto-dev/json-rpc-laravel)
- [open-rpc](https://github.com/open-rpc/)
- [phoenix1.4-json-rpc](https://github.com/vruizext/phoenix1.4-json-rpc)
## License
MIT. Please see the [license file](LICENSE.md) for more information.
[link-ci]: https://github.com/shirokovnv/phx_json_rpc/actions/workflows/ci.yml/badge.svg
[link-elixir]: https://elixir-lang.org/
[link-phoenix]: https://www.phoenixframework.org/
[link-guide]: https://hexdocs.pm/phx_json_rpc/PhxJsonRpc.html
[link-docs]: https://hexdocs.pm/phx_json_rpc
[link-shield]: https://img.shields.io/hexpm/v/phx_json_rpc
[link-hex]: https://hex.pm/packages/phx_json_rpc
|
если надо скопировать значения старого массива в новую переменную массива и изменить ее, не затрагивая значения старого массива, можно использовать фиксированное назначение массива или использовать комбинацию make и copy
---
basket1 := make([]string, 1, 3)
basket1[0] = "apple"
basket2 := basket1[:2]
basket2[1] = "mango"
basket3 := make([]string, cap(basket1))
copy(basket3, basket2)
basket3[1] = "pineapple"
basket3[2] = "kiwi"
fmt.Println(basket3) // [apple pineapple kiwi]
fmt.Println(basket2) // [apple mango]
fmt.Println(basket1) // [apple]
---
|
import PropTypes from "prop-types";
import { TransactionHistoryStyled } from "components/taskFour/TransactionHistory/TransactionHistory.styled";
import { TransactionItem } from "components/taskFour/TransactionItem/TransactionItem";
export const TransactionHistory = ({ items }) => {
return (
<TransactionHistoryStyled>
<thead>
<tr>
<th>Type</th>
<th>Amount</th>
<th>Currency</th>
</tr>
</thead>
<tbody>
{
items.map(({ id, type, amount, currency, }) => <TransactionItem key={id} type={ type } amount={ amount } currency={ currency } />)
}
</tbody>
</TransactionHistoryStyled>
);
};
TransactionHistory.propTypes = {
items: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
amount: PropTypes.string.isRequired,
currency: PropTypes.string.isRequired,
})
)
}
|
package ru.practicum.explore.event.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.Builder;
import lombok.Getter;
import lombok.AccessLevel;
import lombok.ToString;
import lombok.experimental.FieldDefaults;
import ru.practicum.explore.location.LocationDto;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
@Getter
@Setter
@ToString
@Builder
@AllArgsConstructor
@NoArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class EventNewDto {
Long id;
@NotBlank
@Size(min = 3, max = 120)
String title;
@NotBlank
@Size(min = 20, max = 7000)
String description;
@NotBlank
@Size(min = 20, max = 2000)
String annotation;
@NotNull
Long category;
@NotNull
LocationDto location;
@NotNull
@Future
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
LocalDateTime eventDate;
Long participantLimit;
Boolean requestModeration;
Boolean paid;
public Long getParticipantLimit() {
if (participantLimit == null) {
participantLimit = 0L;
}
return participantLimit;
}
public Boolean getRequestModeration() {
if (requestModeration == null) {
requestModeration = true;
}
return requestModeration;
}
public Boolean getPaid() {
if (paid == null) {
paid = false;
}
return paid;
}
}
|
// styles
import { FormControl, FormLabel, Input as InputControl, Text, useColorModeValue } from '@chakra-ui/react'
// interfaces
import type { InputProps } from '@/interfaces/common/Input'
// libs
import isEmpty from 'just-is-empty'
const Input = ({ type = 'text', label = '', value = '', placeholder, error, invalid, disabled = false, hasAutoComplete = true, onChange }: InputProps): JSX.Element => {
const inputColor = useColorModeValue('secondaryGray.800', 'white')
const inputBg = useColorModeValue('white', 'gray.700')
return (
<FormControl fontSize='sm' isInvalid={invalid}>
<FormLabel>{label}</FormLabel>
<InputControl
type={type}
placeholder={placeholder}
color={inputColor}
backgroundColor={inputBg}
{...(hasAutoComplete && { autoComplete: 'new-password' })}
errorBorderColor='red.300'
onChange={onChange}
value={value}
disabled={disabled}
/>
{!isEmpty(error?.message) && (<Text color='red.300' mt='2'>{error?.message}</Text>)}
</FormControl>
)
}
export default Input
|
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<!-- Bootstrap CSS-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- Bootstrap Bundle JS-->
<script defer src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</head>
<div th:replace="header :: content"></div>
<body>
<div class="container">
<div class="mb-3">
<!-- <p th:text="${director.toString()}">VALUE</p>-->
<h5 th:text="*{director.surname + ' ' + director.name}"></h5>
<!-- <p class="text-left" th:text="*{director.surname + ' ' + director.name}">TEXT</p>-->
<p class="text-left" th:text="*{'Sex: ' + director.sex}">TEXT</p>
<p class="text-left" th:text="*{'Birthday: ' + director.birthday + ' (' + director.zodiac + ')'}">TEXT</p>
<p class="text-left" th:text="*{'Birthplace: ' + director.birthplace}">TEXT</p>
<div th:if="${not director.film.isEmpty()}">
<h5>Films:</h5>
<div th:each="film : ${director.film}">
<a th:href="@{/film/{id}(id=${film.id})}">
<div th:text="${film.title + ' '}"></div>
</a>
</div>
</div>
<div th:if="${not director.getSeries().isEmpty()}">
<h5>Series:</h5>
<div th:each="series : ${director.getSeries()}">
<a th:href="@{/series/{id}(id=${series.id})}">
<div th:text="${series.title + ' '}"></div>
</a>
</div>
</div>
</div>
</div>
</body>
</html>
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IBatch.sol";
/**
*@title Batch
*@author Wanggyu, Suh
*@notice Batch transfer contract
1. Send ethereum multiple times with same amount.
2. Send erc20 multiple times with different amount.
- (1) Before call batch, send token to this contract.
- (2) call batch function.
3. Send ethereum multiple times with different amount.
*/
contract Batch is IBatch {
mapping (string => IERC20) private tokens;
mapping (address => bool) private administrators;
bool private addable;
modifier onlyAdmin {
require(administrators[msg.sender] == true, "Transfer: not allowed account");
_;
}
modifier modeAddable {
require(addable, "Transfer: not allowed to add administrator");
_;
}
constructor(address admin) {
administrators[admin] = true;
addable = true;
}
function batch(address[] memory recipient, string[] memory token, uint256[] memory amount) external override onlyAdmin {
require(recipient.length == token.length && recipient.length == amount.length, "Transfer: Invalid input");
for(uint i = 0; i < recipient.length; i++) {
tokens[token[i]].transfer(recipient[i], amount[i]);
}
}
function addToken(string memory name, IERC20 token) external override onlyAdmin {
tokens[name] = token;
}
function withdraw(uint256 amount, string memory token) public onlyAdmin {
tokens[token].transfer(msg.sender, amount);
}
/**
@dev add a administrator
*/
function addAdmin(address newAdmin) public onlyAdmin modeAddable {
administrators[newAdmin] = true;
}
/**
@dev Once call this function, can not add administrator forever
*/
function blockAddable() public onlyAdmin {
addable = false;
}
}
|
/*
* The MIT License
*
* Copyright 2016 oncore.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.oncore.chhs.client.ejb;
import com.oncore.chhs.client.dto.profile.CreateOrUpdateProfile;
import com.oncore.chhs.client.dto.profile.Profile;
/**
* The ProfileService provides methods for retrieving, creating and updating
* a user's name and contact information.
*
* @author OnCore LLC
*/
public interface ProfileService {
/**
* Find the user's profile.
*
* @param userUid The user's unique ID.
*
* @return The user's profile.
*/
public Profile findProfileByUserUid(Integer userUid);
/**
* Create a new user profile, including address and
* contact information.
*
* @param profile The profile data to create.
*/
public void createProfile( CreateOrUpdateProfile profile );
/**
* Update a user's profile, including address and contact
* information.
*
* @param profile The profile data to update.
*/
public void updateProfile( CreateOrUpdateProfile profile );
}
|
import { useQuery, gql } from "@apollo/client";
import { ChangeEvent, MouseEvent, useState } from "react";
import {
IQuery,
IQueryFetchBoardsArgs,
} from "../../../src/commons/types/generated/types";
import _ from "lodash";
import { uuidv4 } from "@firebase/util";
const FETCH_BOARDS = gql`
query fetchBoards($page: Int, $search: String) {
fetchBoards(page: $page, search: $search) {
_id
writer
title
}
}
`;
export default function StaticRoutingMovedPage(): JSX.Element {
const [keyword, setKeyword] = useState("");
const { data, refetch } = useQuery<
Pick<IQuery, "fetchBoards">,
IQueryFetchBoardsArgs
>(FETCH_BOARDS);
const onClickPage = (e: MouseEvent<HTMLSpanElement>): void => {
void refetch({ page: Number(e.currentTarget.id) });
};
const getDebounce = _.debounce((value) => {
setKeyword(value);
void refetch({ search: value, page: 1 });
}, 500);
const onChangeSearch = (e: ChangeEvent<HTMLInputElement>): void => {
getDebounce(e.currentTarget.value);
};
return (
<div>
검색어 입력: <input type="text" onChange={onChangeSearch} />
{data?.fetchBoards.map((el) => (
<div key={el._id}>
<span>
{el.title
.replaceAll(keyword, `@#$${keyword}@#$`)
.split("@#$")
.map((el) => (
<span
key={uuidv4()}
style={{ color: el === keyword ? "red" : "black" }}
>
{el}
</span>
))}
</span>
<span>{el.writer}</span>
</div>
))}
{new Array(10).fill("철수").map((_, index) => (
<span key={index + 1} id={String(index + 1)} onClick={onClickPage}>
{index + 1}
</span>
))}
</div>
);
}
|
function error(prop, expected, actual) {
throw new TypeError(`Invalid value assignment on "${prop}", expected: ${expected}, actual: ${actual}`);
}
function getType(value) {
const type = value === null ? 'null' : typeof value;
if (type == 'string' || type == 'number' || type == 'boolean' || type == 'undefined' || type == 'null') {
return type[0].toUpperCase() + type.slice(1);
}
return value.constructor.name;
}
function getValidator(prop, constructor) {
const constructorName = constructor.name;
if (constructor === String || constructor === Number || constructor === Boolean) {
return (value) => {
if (typeof value !== constructorName.toLowerCase()) {
error(prop, constructorName, getType(value));
}
return true;
};
}
return (value) => {
if (!(value instanceof constructor)) {
error(prop, constructorName, getType(value));
}
return true;
};
}
function defineProperty(object, name, constructor) {
let value;
const validate = getValidator(name, constructor);
Object.defineProperty(object, name, {
enumerable: true,
configurable: true,
get() {
return value;
},
set(val) {
if (validate(val)) {
value = val;
}
}
});
}
export default function typed(props) {
const object = {};
Object.keys(props).forEach((prop) => defineProperty(object, prop, props[prop]));
return object;
}
|
import React, { useMemo, useRef } from "react";
import vertexShader from "./vertexShader";
import fragmentShader from "./fragmentShader";
import { useFrame } from "@react-three/fiber";
import { MathUtils, OctahedronGeometry, WireframeGeometry } from "three";
const Blob = () => {
const mesh = useRef();
const hover = useRef(false);
const uniforms = useMemo(() => {
return {
u_time: { value: 0 },
u_intensity: { value: 0.3 },
};
});
useFrame((state) => {
const { clock } = state;
if (mesh.current) {
mesh.current.material.uniforms.u_time.value =
0.1 * clock.getElapsedTime();
mesh.current.material.uniforms.u_intensity.value = MathUtils.lerp(
mesh.current.material.uniforms.u_intensity.value,
hover.current ? 1 : 0.8,
0.01
);
}
});
return (
<mesh
ref={mesh}
scale={1.3}
position={[0, 0, 0]}
onPointerOver={() => (hover.current = true)}
onPointerOut={() => (hover.current = false)}
>
<icosahedronGeometry args={[2, 60]} />
<shaderMaterial
vertexShader={vertexShader}
fragmentShader={fragmentShader}
uniforms={uniforms}
/>
</mesh>
);
};
export default Blob;
|
# install baasilca-react-native-progrss-loader
React Native progrss loader component for both Android and iOS, using baasilca-react-native-progrss-loader
## Install
```bash
npm install baasilca-react-native-progrss-loader --save
```
## Example
contact 9846366876 (whatsapp) @baasilca(instagram)
{:height="36px" width="36px"}
## Usage
```javascript
import React, { Component } from 'react'
import DialogWithLoadingIndicator from 'baasilca-react-native-progrss-loader'
export default Progress=()=>{
return (
<DialogWithLoadingIndicator visible title={"Please Wait..."} />
)
}
}
```
<!-- You can check [index.js](https://github.com/xgfe/react-native-datepicker/blob/master/index.android.js) in the Example for detail. -->
<!-- ## Properties
| Prop | Default | Type | Description |
| :------------ |:---------------:| :---------------:| :-----|
| style | - | `object` | Specify the style of the DatePicker, eg. width, height... |
| date | - | <code>string | date | Moment instance</code> | Specify the display date of DatePicker. `string` type value must match the specified format |
| mode | 'date' | `enum` | The `enum` of `date`, `datetime` and `time` |
| androidMode | 'default' | `enum` | The `enum` of `default`, `calendar` and `spinner` (only Android) |
| format | 'YYYY-MM-DD' | `string` | Specify the display format of the date, which using [moment.js](http://momentjs.com/). The default value change according to the mode. |
| confirmBtnText | '确定' | `string` | Specify the text of confirm btn in ios. |
| cancelBtnText | '取消' | `string` | Specify the text of cancel btn in ios. |
| iconSource | - | <code>{uri: string} | number</code> | Specify the icon. Same as the `source` of Image, always using `require()` |
| minDate | - | <code>string | date</code> | Restricts the range of possible date values. |
| maxDate | - | <code>string | date</code> | Restricts the range of possible date values. |
| duration | 300 | `number` | Specify the animation duration of datepicker.|
| customStyles | - | `object` | The hook of customize datepicker style, same as the native style. `dateTouchBody`, `dateInput`...|
| showIcon | true | `boolean` | Controller whether or not show the icon |
| hideText | false | `boolean` | Controller whether or not show the `dateText` |
| iconComponent | - | `element` | Set the custom icon |
| disabled | false | `boolean` | Controller whether or not disable the picker |
| is24Hour | - | `boolean` | Set the TimePicker is24Hour flag. The default value depend on `format`. Only work in Android |
| allowFontScaling | true | `boolean` | Set to false to disable font scaling for every text component |
| placeholder | '' | `string` | The placeholder show when this.props.date is falsy |
| onDateChange | - | `function` | This is called when the user confirm the picked date or time in the UI. The first and only argument is a date or time string representing the new date and time formatted by [moment.js](http://momentjs.com/) with the given format property. |
| onOpenModal | - | `function` | This is called when the DatePicker Modal open. |
| onCloseModal | - | `function` | This is called when the DatePicker Modal close |
| onPressMask | - | `function` | This is called when clicking the ios modal mask |
| modalOnResponderTerminationRequest | - | `function` | Set the callback for React Native's [Gesture Responder System](https://facebook.github.io/react-native/docs/gesture-responder-system.html#responder-lifecycle)'s call to `onResponderTerminationRequest`. By default this will reject a termination request, but can be overidden in case the View under the Modal is implementing custom gesture responders, and you wish for those to be overidden in certain cases. |
| TouchableComponent | `TouchableHighlight` | `Component` | Replace the `TouchableHighlight` with a custom `Component`. For example : `TouchableOpacity` |
| getDateStr | - | Function | A function to override how to format the date into a `String` for display, receives a `Date` instance -->
<!-- ### Property `customStyles` available keys
<!-- * appearance: `close`, `visible`, `title`, `dateIcon`, `placeholderText`, `dateText` -->
<!-- * ios select panel: `datePickerCon`, `datePicker`, `btnConfirm`, `btnTextConfirm`, `btnCancel`, `btnTextCancel` -->
<!-- ## Instance Methods -->
<!-- | Method | Params | Description |
| :------------ |:---------------:| :---------------:|
| onPressDate | - | Manually open the date picker panel |
| onPressCancel | - | Manually close the date picker panel like, similarly pressing cancel btn | -->
|
import React from 'react';
import NextError from 'next/error';
interface ErrorProps {
statusCode: number;
}
interface ErrorInitialProps {
res: {
statusCode: number;
};
err: ErrorProps;
}
/**
* @link https://nextjs.org/docs/advanced-features/custom-error-page
* @param {statusCode: number}
* @description next js 자체에도 에러페이지를 만들어주는 컴포넌트가 있음.
* 아래에 모듈과 소스 주석 처리 해놓았음
* @returns
*/
function Error({ statusCode }: ErrorProps) {
return (
<NextError statusCode={statusCode} />
// <p>
// {statusCode
// ? `An error ${statusCode} occurred on server`
// : 'An error occurred on client'}
// </p>
);
}
Error.getInitialProps = ({ res, err }: ErrorInitialProps) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
return { statusCode };
};
// import Error from 'next/error';
// export async function getServerSideProps() {
// const res = await fetch('https://api.github.com/repos/vercel/next.js')
// const errorCode = res.ok ? false : res.statusCode
// const json = await res.json()
// return {
// props: { errorCode, stars: json.stargazers_count },
// }
// }
// export default function Page({ errorCode, stars }) {
// if (errorCode) {
// return <Error statusCode={errorCode} />;
// }
// return <div>Next stars: {stars}</div>;
// }
export default Error;
|
<!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">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,400i,600,700,700i&display=swap" rel="stylesheet">
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/fontawesome-all.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="css/swiper.css" rel="stylesheet">
<link href="css/magnific-popup.css" rel="stylesheet">
<link href="css/styles.css" rel="stylesheet">
<link rel="stylesheet" href="/css/team.css">
<link rel="stylesheet" href="style.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- Favicon -->
<link rel="icon" href="images/favicon.png">
<title>Registration - IPS</title>
</head>
<body>
<!-- Preloader -->
<div class="spinner-wrapper">
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
<!-- end of preloader -->
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark navbar-custom fixed-top">
<!-- Text Logo - Use this if you don't have a graphic logo -->
<!-- <a class="navbar-brand logo-text page-scroll" href="index.html">Corso</a> -->
<!-- Image Logo -->
<div class="logo">
<a class="navbar-brand logo-image" href="index.html"><img src="images/favicon.png" alt="alternative"></a>
</div>
<ul class="navbar-nav">
<li class="nav-item">
<a href="/index.html" class="nav-link h6" style="font-weight: bold; color: #fff;">Institiute of Professional Development</a>
</li>
</ul>
<!-- Mobile Menu Toggle Button -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-awesome fas fa-bars"></span>
<span class="navbar-toggler-awesome fas fa-times"></span>
</button>
<!-- end of mobile menu toggle button -->
<div class="collapse navbar-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link page-scroll" style="color: #fff;" href="/index.html">HOME</a>
</li>
<li class="nav-item dropdown">
<a style="color: #fff;" class="nav-link dropdown-toggle page-scroll" href="#date" id="navbarDropdown" role="button" aria-haspopup="true" aria-expanded="false">ABOUT</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="aboutus.html"><span class="item-text">Want To Know About Us ?</span></a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="team.html"><span class="item-text">Our Staff</span></a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="instructors.html"><span class="item-text">Our Instructors</span></a>
</div>
</li>
<li class="nav-item course-link">
<a style="color: #fff;" class="nav-link page-scroll" href="/courses.html" target="_blank">COURSES</a>
</li>
<!-- Dropdown Menu -->
<!-- end of dropdown menu -->
<li class="nav-item">
<a style="color: #fff;" class="nav-link page-scroll" href="/blog.html" target="_blank" id="navbarDropdown" role="button" aria-haspopup="true" aria-expanded="false">BLOG</a>
</li>
<li class="nav-item">
<a style="color: #fff;" class="nav-link page-scroll" href="/contact.html" target="_blank" id="navbarDropdown" role="button" aria-haspopup="true" aria-expanded="false">CONTACT</a>
</li>
</ul>
<!-- <span class="nav-item social-icons">
<span class="fa-stack">
<a href="#your-link" class="top-links">
<i class="fas fa-circle fa-stack-2x"></i>
<i class="fab fa-facebook-f fa-stack-1x"></i>
</a>
</span>
<span class="fa-stack">
<a href="#your-link" class="top-links">
<i class="fas fa-circle fa-stack-2x"></i>
<i class="fab fa-twitter fa-stack-1x"></i>
</a>
</span>
</span> -->
</div>
</nav> <!-- end of navbar -->
<!-- end of navigation -->
<div class="team-section">
<img src="/images/slider-images/slider-image-1.jpg" alt="">
<div class="overlay"></div>
<div class="text">
<h2>Increasing <span class="auto-typed"></span></h2>
</div>
</div>
<!-- Header -->
<div class="container-fluid">
<div class="container">
<div class="form">
<div class="row col-md-8 offset-2 ">
<div class="logo-side col-md-2 mt-4 mb-4">
<img src="logo PNG.png" alt="">
</div>
<div class="name-ins col-md-10 mt-5 mb-4 ">
<!-- <h4>KARAKORAM INTERNATIONAL UNIVERSITY</h4> -->
<h4>INSTITUTE OF PROFESSIONAL DEVELOPEMENT KIU</h4>
<h6>Gilgit-Baltistan</h6>
</div>
</div>
<div class="row offset-2 mb-3 mt-4">
<h5>Course Information</h5>
</div>
<div class="row offset-2 col-md-8">
<div class="col">
<!-- <label for="form12" class="form-label">Select Couses</label> -->
<select class="form-select col-md-3" aria-label="Default select example">
<option selected>Select Course</option>
<option value="1">Chinese Language</option>
<option value="2">Graphic Design</option>
<option value="3">Android Developement</option>
</select>
</div>
<div class="col">
<select class="form-select col-md-3" aria-label="Default select example">
<option selected>Select Duration</option>
<option value="1">One Month</option>
<option value="2">Three Month</option>
<option value="3">Six Month</option>
</select>
</div>
</div>
<div class="row offset-2 mb-3 mt-4">
<h5>Personal Information</h5>
</div>
<div class="row col-md-8 offset-2">
<div class="col">
<input type="text" class="form-control" placeholder="Candidate Name"
aria-label="Candidate Name">
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Father's Name" aria-label="Father's Name">
</div>
</div>
<div class="row col-md-8 offset-2 mt-3">
<div class="col">
<input type="email" class="form-control" placeholder="Email" aria-label="Email">
</div>
</div>
<div class="row col-md-8 offset-2 mt-3">
<div class="col">
<input type="text" class="form-control" placeholder="CNIC No" aria-label="CNIC No">
</div>
<div class="col">
<input type="date" class="form-control" onfocus="(this.type='date')"
onblur="if(this.value==''){this.type='text'}" placeholder="Date of Birth"
aria-label="Date Of Birth">
</div>
</div>
<div class="row col-md-8 offset-2 mt-3">
<div class="col">
<label>Gender</label>
<input type="radio" class="form-check-input" name="gender" id="male" value="male">
<label for="male" class="form-input-label">Male</label>
<input type="radio" class="form-check-input" name="gender" id="Female" value="Female">
<label for="Female" class="form-input-label">Female</label>
</div>
<div class="col">
<input class="form-control" type="file" id="formFile">
</div>
</div>
<div class="row col-md-8 offset-2 mt-3">
<div class="col">
<input type="text" class="form-control" placeholder="Phone Number" aria-label="Phone Number">
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Whatsapp Number"
aria-label="Whatsapp Number">
</div>
</div>
<div class="row col-md-8 offset-2 mt-3">
<div class="col">
<input type="text" class="form-control" placeholder="District" aria-label="District">
</div>
<div class="col">
<select class="form-select col-md-3" aria-label="Default select example">
<option selected>Select Profession</option>
<option value="1">Student</option>
<option value="2">Employee</option>
<option value="3">Others</option>
</select>
</div>
</div>
<div class="row col-md-8 offset-2 mt-3">
<div class="col">
<input type="text" class="form-control" placeholder="Address" aria-label="Address">
</div>
</div>
<div class="row offset-2 mb-3 mt-4">
<h5>Qualification</h5>
</div>
<div class="row col-md-8 offset-2">
<div class="col">
<select class="form-select col-md-3" aria-label="Default select example">
<option selected>Education Level</option>
<option value="1">Student</option>
<option value="2">Employee</option>
<option value="3">Others</option>
</select>
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Name of Institute"
aria-label="Name of Institute">
</div>
<div class="col">
<input type="date text" class="form-control" onfocus="(this.type='date')"
onblur="if(this.value==''){this.type='text'}" value="Passout Date"
placeholder="Passout Date" aria-label="Passout Date">
</div>
</div>
<div class="row col-md-8 offset-2 mt-4">
<div class="col">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck">
<label class="form-check-label" for="gridCheck">
Check me out
</label>
</div>
</div>
</div>
<div class="row col-md-8 offset-2 mt-4">
<div class="col">
<button type="submit" class="btn btn-primary col-md-6">Submit</button>
</div>
</div>
</div>
</div>
</div>
<!-- Footer -->
<div class="footer">
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="footer-col first">
<h5>IPD</h5>
<p class="p-small">Institute of professional development KIU</p>
</div>
</div> <!-- end of col -->
<div class="col-md-3">
<div class="footer-col second">
<h5>Links</h5>
<ul class="list-unstyled li-space-lg p-small">
<li class="media">
<i class="fas fa-square"></i>
<div class="media-body"><a target="_blank" href="https://www.kiu.edu.pk/">KIU</a></div>
</li>
<li class="media">
<i class="fas fa-square"></i>
<div class="media-body"><a target="_blank" href="https://navttc.gov.pk/">NAVTAC</a></div>
</li>
<li class="media">
<i class="fas fa-square"></i>
<div class="media-body"><a target="_blank" href="blog.html">Blogs</a></div>
</li>
</ul>
</div>
</div> <!-- end of col -->
<div class="col-md-3">
<div class="footer-col third">
<h5>Links</h5>
<ul class="list-unstyled li-space-lg p-small">
<li class="media">
<i class="fas fa-square"></i>
<div class="media-body"><a target="_blank" href="contact.html">Contact Us</a></div>
</li>
<li class="media">
<i class="fas fa-square"></i>
<div class="media-body"><a target="_blank" href="courses.html">Courses</a></div>
</li>
<li class="media">
<i class="fas fa-square"></i>
<div class="media-body"><a target="_blank" href="index.html">Home</a></div>
</li>
</ul>
</div>
</div> <!-- end of col -->
<div class="col-md-3">
<div class="footer-col fourth">
<h5>Social Media</h5>
<p class="p-small">For news & updates follow us</p>
<a href="#your-link">
<i class="fab fa-facebook-f"></i>
</a>
<a href="#your-link">
<i class="fab fa-twitter"></i>
</a>
<a href="#your-link">
<i class="fab fa-pinterest-p"></i>
</a>
<a href="#your-link">
<i class="fab fa-instagram"></i>
</a>
<a href="#your-link">
<i class="fab fa-linkedin-in"></i>
</a>
<a href="#your-link">
<i class="fab fa-youtube"></i>
</a>
</div>
</div> <!-- end of col -->
</div> <!-- end of row -->
</div> <!-- end of container -->
</div> <!-- end of footer -->
<!-- end of footer -->
<!-- Copyright -->
<div class="copyright">
<div class="container">
<div class="row">
<div class="col-lg-12">
<p class="p-small">Copyright © 2022 <a href="#">D4 Developers</a> - All rights reserved</p>
</div> <!-- end of col -->
</div> <!-- enf of row -->
</div> <!-- end of container -->
</div> <!-- end of copyright -->
<!-- end of copyright -->
<script src="js/jquery.min.js"></script> <!-- jQuery for Bootstrap's JavaScript plugins -->
<script src="js/popper.min.js"></script> <!-- Popper tooltip library for Bootstrap -->
<script src="js/bootstrap.min.js"></script> <!-- Bootstrap framework -->
<script src="js/jquery.easing.min.js"></script> <!-- jQuery Easing for smooth scrolling between anchors -->
<script src="js/jquery.countdown.min.js"></script> <!-- The Final Countdown plugin for jQuery -->
<script src="js/swiper.min.js"></script> <!-- Swiper for image and text sliders -->
<script src="js/jquery.magnific-popup.js"></script> <!-- Magnific Popup for lightboxes -->
<script src="js/validator.min.js"></script> <!-- Validator.js - Bootstrap plugin that validates forms -->
<script src="js/scripts.js"></script> <!-- Custom scripts -->
<script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.12"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
<script>
var typed = new Typed('.auto-typed',{
strings:['Skills','Productivity','Employment'],
typeSpeed:100,
backSpeed:100,
loop:true
})
</script>
</body>
</html>
|
import type { Emitter } from "@niloc/utils"
import { Emitter as EmitterImpl } from "@niloc/utils"
import { StringWriter } from "../../tools/StringWriter"
import { ModelHandle } from "../ModelHandle"
import { Reader } from "../Reader"
import { ChangeRequester } from "../Synchronize"
import { Writer } from "../Writer"
interface FieldEvents {
changed: void
}
export abstract class Field {
public static setIndex(field: Field, index: number) {
field._index = index
}
public static setChangeRequester(field: Field, requester: ChangeRequester) {
field._changeRequester = requester
field.onChangeRequester(requester)
}
public static setModelHandle(field: Field, handle: ModelHandle) {
field.onModelHandle(handle)
}
public static toString(field: Field) {
const writer = new StringWriter()
this.write(field, writer)
return writer.toString()
}
public static write(field: Field, writer: StringWriter) {
field.toString(writer)
}
public static register(fields: Iterable<Field>, callback: () => void): () => void {
const _fields = [...fields]
for (const field of _fields)
field.emitter().on('changed', callback)
return () => {
for (const field of _fields)
field.emitter().off('changed', callback)
}
}
private _index: number = -1
private _changeRequester: ChangeRequester | null = null
private _emitter = new EmitterImpl<FieldEvents>()
index() { return this._index }
emitter(): Emitter<FieldEvents> { return this._emitter }
abstract read(reader: Reader): void
abstract write(writer: Writer): void
readChange(reader: Reader): void { this.read(reader) }
writeChange(writer: Writer): void { this.write(writer) }
clearChange(): void { }
protected changed(): void {
this._changeRequester?.change(this._index)
this._emitter.emit('changed')
}
protected onChangeRequester(_requester: ChangeRequester) { }
protected onModelHandle(_handle: ModelHandle) { }
protected toString(writer: StringWriter) { writer.writeLine("???") }
}
|
/*
https://practice.geeksforgeeks.org/problems/bottom-view-of-binary-tree/1#
Bottom View of Binary Tree
*/
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
#define MAX_HEIGHT 100000
// Tree Node
struct Node
{
int data;
Node* left;
Node* right;
};
// Utility function to create a new Tree Node
Node* newNode(int val)
{
Node* temp = new Node;
temp->data = val;
temp->left = NULL;
temp->right = NULL;
return temp;
}
vector <int> bottomView(Node *root);
// Function to Build Tree
Node* buildTree(string str)
{
// Corner Case
if(str.length() == 0 || str[0] == 'N')
return NULL;
// Creating vector of strings from input
// string after spliting by space
vector<string> ip;
istringstream iss(str);
for(string str; iss >> str; )
ip.push_back(str);
// Create the root of the tree
Node* root = newNode(stoi(ip[0]));
// Push the root to the queue
queue<Node*> queue;
queue.push(root);
// Starting from the second element
int i = 1;
while(!queue.empty() && i < ip.size()) {
// Get and remove the front of the queue
Node* currNode = queue.front();
queue.pop();
// Get the current node's value from the string
string currVal = ip[i];
// If the left child is not null
if(currVal != "N") {
// Create the left child for the current node
currNode->left = newNode(stoi(currVal));
// Push it to the queue
queue.push(currNode->left);
}
// For the right child
i++;
if(i >= ip.size())
break;
currVal = ip[i];
// If the right child is not null
if(currVal != "N") {
// Create the right child for the current node
currNode->right = newNode(stoi(currVal));
// Push it to the queue
queue.push(currNode->right);
}
i++;
}
return root;
}
// } Driver Code Ends
//Function to return a list containing the bottom view of the given tree.
class Solution {
public:
vector <int> bottomView(Node *root) {
// return bottomViewBFS(root);
map<int, pair<int, int>> mp;
bottomViewDFS(root, 0, 0, mp);
vector<int> ans;
for(auto x: mp)
ans.push_back(x.second.second);
return ans;
}
void bottomViewDFS(Node* root, int dist, int height, map<int, pair<int, int>>& mp)
{
if(!root)
return;
if(mp.find(dist) == mp.end())
mp[dist] = {height, root->data};
else //if(mp.find(dist) != mp.end())
{
if(height >= mp[dist].first)
mp[dist] = {height, root->data}; //replace the data with less height
}
// if(root->left)
bottomViewDFS(root->left, dist-1, height+1, mp);
// if(root->right)
bottomViewDFS(root->right, dist+1, height+1, mp);
}
vector<int> bottomViewBFS(Node *root)
{
map<int,int> um; // to map the nodes
//BFS Level Order Traversal
queue<pair<Node*, int>> q;
q.push({root, 0}); // vertical distance
int sz, dist;
Node * node;
while(!q.empty())
{
sz = q.size();
while(sz--)
{
node = q.front().first;
dist = q.front().second; q.pop();
// cout<<node->data<<" ";
if(node->left)
q.push({node->left, dist-1});
if(node->right)
q.push({node->right, dist+1});
um[dist] = node->data;
}
// cout<<endl;
}
vector<int> ans;
for(auto x: um)
ans.push_back(x.second);
return ans;
}
};
// { Driver Code Starts.
int main() {
int t;
string tc;
getline(cin, tc);
t=stoi(tc);
while(t--)
{
string s ,ch;
getline(cin, s);
Node* root = buildTree(s);
Solution ob;
vector <int> res = ob.bottomView(root);
for (int i : res) cout << i << " ";
cout << endl;
}
return 0;
}
// } Driver Code Ends
|
package org.example.server;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import static org.example.service.IOFile.fileRead;
import static org.example.service.IOFile.fileWrite;
public class ServerWindow extends JFrame {
private static final int WIDTH = 350;
private static final int HEIGHT = 400;
private static final String FILE_PATH_DB = "messages.txt";
private static final Map<String, char[]> usersConnect = new HashMap<>();
static JTextArea textArea = new JTextArea(1, 9);
JScrollPane textAreaPanel = new JScrollPane(textArea);
boolean serverStart = false;
JButton btnStart = new JButton("Пуск");
JButton btnStop = new JButton("Стоп");
JPanel panelButtons = new JPanel(new GridLayout(1, 2));
public ServerWindow() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
int widthSizeSystem = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
int heightSizeSystem = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
setLocation(widthSizeSystem - WIDTH - 50, heightSizeSystem - HEIGHT - 50);
setSize(WIDTH, HEIGHT);
setResizable(false);
panelButtons.add(btnStart);
panelButtons.add(btnStop);
add(panelButtons, BorderLayout.SOUTH);
// textAreaPanel.add(textArea);
// textAreaPanel.add(scrollBar);
add(textAreaPanel);
setVisible(true);
btnStart.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
serverStart = true;
textArea.append("Сервер запущен\n");
repaint();
}
});
btnStop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
serverStart = false;
textArea.append("Сервер становлен\n");
repaint();
}
});
}
public static void sendMessage(String user, String message) {
textArea.append(user + " : " + message + "\n");
// ClientWindow.newMessage(user, message);
fileWrite(FILE_PATH_DB, user + " : " + message + "\n");
}
public static String getAllMessages(String user) {
if (usersConnect.containsKey(user)) {
return fileRead(FILE_PATH_DB);
}
return "Вы не авторизованы";
}
public boolean isServerStart() {
return serverStart;
}
public boolean conectServer(String login, char[] password) {
if (serverStart && !usersConnect.containsKey(login)) {
usersConnect.put(login, password);
textArea.append("Подключился пользователь: " + login + "\n");
repaint();
return true;
}
return false;
}
public boolean isConnectUser(String user, char[] password) {
return usersConnect.containsKey(user);
}
}
|
<template>
<article>
<header>
<div class="main-icon">{{ props.job.company.charAt(0) }}</div>
<div class="info">
<h5>{{ props.job.position }}</h5>
<p>{{ props.job.company }}</p>
</div>
</header>
<div class="content">
<div class="content-center">
<job-info icon="location-arrow" :text="props.job.jobLocation" />
<job-info icon="calendar-alt" :text="date" />
<job-info icon="briefcase-alt" :text="props.job.jobType" />
<div class="status" :class="props.job.status">
{{ props.job.status }}
</div>
</div>
<footer>
<div class="actions">
<router-link to="/add-job" class="btn edit-btn" @click="
storeJob.setEditJob({
editJobId: props.job._id,
position: props.job.position,
company: props.job.company,
jobLocation: props.job.jobLocation,
jobType: props.job.jobType,
status: props.job.status,
})
">Edit</router-link>
<button type="button" class="btn delete-btn" @click="storeJob.deleteJob(props.job._id)">
Delete
</button>
</div>
</footer>
</div>
</article>
</template>
<script setup>
import { defineProps } from "vue";
import moment from "moment";
import JobInfo from "./JobInfo.vue";
import { jobStore } from "@/stores/jobStore";
const props = defineProps(["job"]);
const storeJob = jobStore();
const date = moment(props.job.createdAt).format("MMM Do, YYYY");
</script>
<style lang="scss" scoped>
article {
background: var(--white);
border-radius: var(--borderRadius);
display: grid;
grid-template-rows: 1fr auto;
box-shadow: var(--shadow-2);
&:hover>.actions {
visibility: visible;
}
}
header {
padding: 1rem 1.5rem;
border-bottom: 1px solid var(--grey-100);
display: grid;
grid-template-columns: auto 1fr;
align-items: center;
text-align: left;
h5 {
letter-spacing: 0;
}
}
.main-icon {
width: 60px;
height: 60px;
display: grid;
place-items: center;
background: var(--primary-500);
border-radius: var(--borderRadius);
font-size: 1.5rem;
font-weight: 700;
text-transform: uppercase;
color: var(--white);
margin-right: 2rem;
}
.info h5 {
margin-bottom: 0.25rem;
}
.info p {
margin: 0;
text-transform: capitalize;
color: var(--grey-400);
letter-spacing: var(--letterSpacing);
}
.pending {
background: #fcefc7;
color: #e9b949;
}
.interview {
background: #e0e8f9;
color: #647acb;
}
.declined {
color: #d66a6a;
background: #ffeeee;
}
.content {
padding: 1rem 1.5rem;
}
.content-center {
display: grid;
grid-template-columns: 1fr;
row-gap: 0.5rem;
@media (min-width: 576px) {
grid-template-columns: 1fr 1fr;
}
@media (min-width: 992px) {
grid-template-columns: 1fr;
}
@media (min-width: 1120px) {
grid-template-columns: 1fr 1fr;
}
}
.status {
border-radius: var(--borderRadius);
text-transform: capitalize;
letter-spacing: var(--letterSpacing);
text-align: center;
width: 100px;
height: 30px;
margin-top: 0.5rem;
}
footer {
margin-top: 1rem;
}
.edit-btn,
.delete-btn {
letter-spacing: var(--letterSpacing);
cursor: pointer;
height: 30px;
}
.edit-btn {
color: var(--green-dark);
background: var(--green-light);
margin-right: 0.5rem;
}
.delete-btn {
color: var(--red-dark);
background: var(--red-light);
}
.actions {
float: left;
}
</style>
|
package com.catalisa.cidadeseguraapi.erro;
import com.catalisa.cidadeseguraapi.bairro.BairroInexistenteException;
import com.catalisa.cidadeseguraapi.cidade.CidadeInexistenteException;
import com.catalisa.cidadeseguraapi.endereco.EnderecoInexistenteException;
import com.catalisa.cidadeseguraapi.estado.EstadoInexistenteException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import java.time.LocalDateTime;
import java.util.Map;
@RestControllerAdvice
public class ExceptionHandler {
@org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
public ResponseEntity<?> handleDatabaseErrors(RuntimeException e, WebRequest request) {
Map<String, Object> body = Map.of(
"status", 500,
"path", request.getDescription(false).replace("uri=", ""),
"timestamp", LocalDateTime.now(),
"message", e.getLocalizedMessage()
);
return ResponseEntity
.internalServerError().body(body);
}
@org.springframework.web.bind.annotation.ExceptionHandler({
BairroInexistenteException.class, CidadeInexistenteException.class,
EnderecoInexistenteException.class, EstadoInexistenteException.class})
public ResponseEntity<?> handleDatabaseErrorsRequest(RuntimeException e, WebRequest request) {
Map<String, Object> body = Map.of(
"status", 402,
"path", request.getDescription(false).replace("uri=", ""),
"timestamp", LocalDateTime.now(),
"message", e.getMessage()
);
return ResponseEntity.unprocessableEntity().body(body);
}
}
|
import { Injectable, PipeTransform, ArgumentMetadata, HttpException, HttpStatus } from '@nestjs/common';
import { Helper } from '@webilix/helper-library';
import { Errors } from '../errors';
import { FormatsEnum } from '../formats';
import { Condition } from './validator.type';
import { IDateCondition, INumberCondition, IStringCondition } from './validator.interface';
@Injectable()
export class ValidatorPipe implements PipeTransform {
private errors: string[] = [];
private setError(error: string): void {
this.errors.push(error);
}
transform(values: { [key: string]: any }, meta: ArgumentMetadata) {
this.errors = [];
const conditions = Reflect.getMetadata('validator', meta.metatype || {});
if (conditions) {
values = this.updateValues(conditions, values);
this.validate(conditions, values);
}
if (this.errors.length !== 0) throw new HttpException(this.errors, HttpStatus.BAD_REQUEST);
return values;
}
private updateValues(conditions: any, values: { [key: string]: any }): { [key: string]: any } {
const update = (condition: Condition, value: any): any => {
if (Helper.IS.empty(value)) return value;
switch (condition.type) {
case 'BOOLEAN':
case 'NUMBER':
return value;
case 'DATE':
if (!Helper.IS.STRING.jsonDate(value)) return value;
value = Helper.STRING.changeNumbers(value, 'EN');
if (!condition.omitConvert) value = new Date(value);
return value;
case 'STRING':
if (!Helper.IS.string(value)) return value;
if (!condition.omitTrim) value = value.trim();
if (condition.format) value = Helper.STRING.changeNumbers(value, 'EN');
else if (condition.changeNumbers) value = Helper.STRING.changeNumbers(value, condition.changeNumbers);
return value;
case 'OBJECT':
const properties: string[] = Object.keys(condition.properties);
properties.forEach((property: string) => {
if (Helper.IS.empty(value[property])) return;
value[property] = update(condition.properties[property], value[property]);
});
return value;
}
};
Object.keys(conditions).forEach((key: string) => {
const condition: Condition = conditions[key];
if (condition.array) {
if (Helper.IS.array(values[key]))
values[key].map((_: any, index: number) => update(condition, values[key][index]));
} else values[key] = update(condition, values[key]);
});
return values;
}
private validate(conditions: any, values: { [key: string]: any }) {
Object.keys(conditions).forEach((key: string) => {
const condition: Condition = conditions[key];
if (condition.array) this.validateArray(condition, values[key]);
else this.validateValue(condition, values[key]);
});
}
private validateType(condition: Condition, value: any): boolean {
if (Helper.IS.empty(value)) return true;
switch (condition.type) {
case 'BOOLEAN':
return Helper.IS.boolean(value);
case 'DATE':
return Helper.IS.date(value) || Helper.IS.STRING.jsonDate(value);
case 'NUMBER':
return Helper.IS.number(value);
case 'OBJECT':
return Helper.IS.object(value);
case 'STRING':
return Helper.IS.string(value);
}
}
private validateArray(condition: Condition, value: any[]): void {
if (!condition.array) return;
const title: string = condition.title;
// UNDEFINED
if (value === undefined) return this.setError(Errors.undefined(title));
// NULLABLE
const isEmpty: boolean = Helper.IS.empty(value);
if (!condition.nullable && isEmpty) return this.setError(Errors.empty(title));
if (isEmpty) return;
// TYPE
if (!Helper.IS.array(value)) return this.setError(Errors.invalid(title));
// COUNT && UNIQUE
if (condition.array !== true) {
if (condition.array.minCount && value.length < condition.array.minCount)
return this.setError(Errors.minCount(title, condition.array.minCount));
if (condition.array.maxCount && value.length > condition.array.maxCount)
return this.setError(Errors.maxCount(title, condition.array.maxCount));
if (
condition.array.unique &&
!Helper.IS.ARRAY.unique(value, condition.array.unique === true ? undefined : condition.array.unique)
)
return this.setError(Errors.unique(title));
}
// Change nullable option for array values
condition = { ...condition, nullable: false };
value.forEach((_: any, index: number) => this.validateValue(condition, value[index], index + 1));
}
private validateValue(condition: Condition, value: any, index?: number, parent?: string): void {
const title: string =
(parent ? `${parent}: ` : '') + condition.title + (index ? ` ${Helper.NUMBER.getTitle(index)}` : '');
// UNDEFINED
if (value === undefined) return this.setError(Errors.undefined(title));
// NULLABLE
const isEmpty: boolean = Helper.IS.empty(value);
if (!condition.nullable && isEmpty) return this.setError(Errors.empty(title));
if (isEmpty) return;
// TYPE
if (!this.validateType(condition, value)) return this.setError(Errors.invalid(title));
// CONDITIONS
switch (condition.type) {
case 'BOOLEAN':
return;
case 'DATE':
return this.validateDate(condition, title, new Date(value));
case 'NUMBER':
return this.validateNumber(condition, title, +value);
case 'STRING':
return this.validateString(condition, title, value.toString());
case 'OBJECT':
const properties: string[] = Object.keys(condition.properties);
properties.forEach((property: string) =>
this.validateValue(condition.properties[property], value[property], undefined, title),
);
return;
}
}
private validateDate(condition: IDateCondition, title: string, value: Date): void {
if (condition.minDate && value.getTime() < condition.minDate.getTime())
return this.setError(Errors.minDate(title, condition.minDate));
if (condition.maxDate && value.getTime() > condition.maxDate.getTime())
return this.setError(Errors.maxDate(title, condition.maxDate));
}
private validateNumber(condition: INumberCondition, title: string, value: number): void {
if (condition.minimum && value < condition.minimum) return this.setError(Errors.minimum(title, condition.minimum));
if (condition.maximum && value > condition.maximum) return this.setError(Errors.maximum(title, condition.maximum));
if (condition.enum && !condition.enum.includes(value)) return this.setError(Errors.invalid(title));
}
private validateString(condition: IStringCondition, title: string, value: string): void {
if (condition.format && !FormatsEnum[condition.format].validate(value)) return this.setError(Errors.invalid(title));
if (condition.enum && !condition.enum.includes(value)) return this.setError(Errors.invalid(title));
if (condition.length && value.length !== condition.length)
return this.setError(Errors.eqLength(title, condition.length));
if (condition.minLength && value.length < condition.minLength)
return this.setError(Errors.minLength(title, condition.minLength));
if (condition.maxLength && value.length > condition.maxLength)
return this.setError(Errors.maxLength(title, condition.maxLength));
if (condition.pattern && !condition.pattern.test(value)) return this.setError(Errors.invalid(title));
}
}
|
import React from 'react';
import { Link } from 'react-router-dom';
import './AboutUs.css';
import AboutImage from '../../images/aboutimg.jpg';
import { motion } from 'framer-motion';
const AboutUs = () => {
const transition = {type: "spring", duration: 2}
return (
<section className='about-us container'>
<div className="about-us-left">
<motion.h2
initial={{transform: 'scale(0.8)'}}
whileInView={{ transform: 'scale(1)' }}
transition={transition}
><span className='stroke-text'>About Us </span> and Our Work</motion.h2>
<motion.p
initial={{transform: 'scale(0.8)'}}
whileInView={{ transform: 'scale(1)' }}
transition={transition}
>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim.</motion.p>
<motion.p
initial={{transform: 'scale(0.8)'}}
whileInView={{ transform: 'scale(1)' }}
transition={transition}
><strong>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore.</strong></motion.p>
<motion.div
initial={{ marginTop: '6rem'}}
whileInView={{ marginTop: '1.5rem' }}
transition={transition}
>
<Link to="/contact" className='btn'>Book a Call</Link>
</motion.div>
</div>
<div className="about-us-right">
<motion.img src={AboutImage} alt=""
initial={{transform: 'scale(0.8)'}}
whileInView={{ transform: 'scale(1)' }}
transition={transition}
/>
</div>
</section>
)
}
export default AboutUs
|
import React, { useEffect } from "react";
import { Form, Table, Input, Space, Button, InputNumber, Select } from "antd";
// import styler from './index.less';
export default function EditTable(props) {
const [form] = Form.useForm();
const onFinish = (values) => {
console.log(values);
};
const columns = (add, remove) => {
const rules = [{ required: true, message: "请填充内容!" }];
return [
{
title: "#",
dataIndex: "key",
key: "key",
sorter: (a, b) => a.key - b.key,
render: (a) => a + 1,
},
{
title: "name",
dataIndex: "name",
key: "name",
sorter: (a, b) => a.name - b.name,
render: (_, record) => {
return (
<Form.Item
rules={rules}
name={[record.name, "name"]}
// fieldKey={[record.fieldKey, "name"]}
>
<Input placeholder="place input name" />
</Form.Item>
);
},
},
{
title: "age",
dataIndex: "age",
key: "age",
render: (_, record) => {
return (
<Form.Item
rules={rules}
name={[record.name, "age"]}
// fieldKey={[record.fieldKey, "age"]}
>
<Select
options={[
{
value: 0,
label: "A",
},
{
value: 1,
label: "B",
},
]}
/>
</Form.Item>
);
},
},
{
title: "address",
dataIndex: "address",
key: "address",
render: (_, record, index) => {
return (
<Form.Item shouldUpdate noStyle>
{({ getFieldValue }) =>
getFieldValue(["table", index, "name"]) === "yh" ? (
<Form.Item
rules={rules}
name={[record.name, "address"]}
// fieldKey={[record.fieldKey, "address"]}
>
<Input placeholder="pleace input address" />
</Form.Item>
) : (
<Form.Item
rules={rules}
name={[record.name, "address"]}
// fieldKey={[record.fieldKey, "address"]}
>
<InputNumber />
</Form.Item>
)
}
</Form.Item>
);
},
},
{
title: "text",
dataIndex: "key",
key: "key",
render: (a, b, c) => {
console.log(a, b, c);
return a;
// return (
// <Form.Item
// rules={rules}
// name={[record.name, "text"]}
// // fieldKey={[record.fieldKey, "name"]}
// >
// <Input placeholder="place input name" bordered={false} />
// </Form.Item>
// );
},
},
{
title: "操作",
dataIndex: "action",
key: "action",
render: (text, record) => {
return (
<Button
type="text"
onClick={() => remove(record.name)}
className="iconfont icondelete"
>
删除
</Button>
);
},
},
];
};
useEffect(() => {
let arr = Array.from({ length: 20 }).map((item, index) => {
return {
key: index,
name: index,
age: 0,
address: index,
text: "123",
};
});
form.setFieldValue("table", arr);
}, []);
return (
<div>
<Form form={form} onFinish={onFinish}>
<Form.Item label colon={false}>
<Form.List name="table">
{(fields, { add, remove }) => {
console.log(fields);
return (
<div>
<Table dataSource={fields} columns={columns(add, remove)} />
<Button type="primary" onClick={add}>
增加
</Button>
</div>
);
}}
</Form.List>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
提交
</Button>
</Form.Item>
</Form>
</div>
);
}
|
@mixin box-shadow() {
-webkit-box-shadow: 1px 1px 0px rgba(0, 0, 0, 0.3); /* Safari 3-4, iOS 4.0.2 - 4.2, Android 2.3+ */
-moz-box-shadow: 1px 1px 0px rgba(0, 0, 0, 0.3); /* Firefox 3.5 - 3.6 */
box-shadow: 1px 1px 0px rgba(0, 0, 0, 0.3);
}
@mixin input-styles($color) {
border: none;
text-align: center;
padding: 5px;
margin: 10px;
outline: none;
color: $color;
background: transparent;
border-bottom: 1px solid $color;
}
@mixin placeholder($color) {
&::-webkit-input-placeholder {
color: $color;
}
&:-moz-placeholder {
color: $color;
}
&::-moz-placeholder {
color: $color;
}
&:-ms-input-placeholder {
color: $color;
}
}
$lightBlue: #19b2e0;
$darkGrey: #7f7f7f;
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
a {
text-decoration: none;
}
.title {
font-size: 20px;
font-weight: lighter;
letter-spacing: 5px;
text-align: center;
}
.container {
width: 95%;
margin: 30px auto;
}
.image {
&.desc {
color: $darkGrey;
height: 50px;
overflow: scroll;
}
}
.header {
font-family: cursive;
letter-spacing: 10px;
color: black;
text-align: center;
font-size: 50px;
}
.btn {
padding: 10px;
color: black;
background: transparent;
font-size: 15px;
letter-spacing: 2px;
outline: none;
border: 1px solid black;
margin: 10px;
cursor: pointer;
@include box-shadow();
}
.center {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: calc(100vh - 80px);
}
.error {
color: red;
font-size: 13px;
}
.form-wrapper {
margin: auto;
width: 80%;
max-width: 400px;
text-align: center;
.form {
display: flex;
flex-direction: column;
input {
@include input-styles(black);
@include placeholder($darkGrey);
}
.upload-button {
color: $darkGrey;
}
}
a {
font-size: 13px;
font-style: italic;
color: $darkGrey;
font-weight: lighter;
span {
border-bottom: 1px dotted black;
}
}
}
/*
* ALBUMS & PHOTOS
*/
.grid {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
justify-content: center;
margin-top: 40px;
> div {
margin: 20px;
position: relative;
width: 300px;
}
}
|
from ..database import DatabaseConnection
class Server:
def __init__(self, id_server = None, nombre = None, descripcion = None, id_user = None):
self.id_server = id_server
self.nombre = nombre
self.descripcion = descripcion
self.id_user = id_user
def serialize(self):
return {
"id_server": self.id_server,
"nombre": self.nombre,
"descripcion": self.descripcion,
}
@classmethod
def get(cls, server):
"""Get a server by id
Args:
- server (server): server object with the id attribute
Returns:
- server: server object
"""
query = """SELECT id_server, nombre, descripcion FROM db_tif.servidor WHERE id_server = %s"""
params = server.id_server,
result = DatabaseConnection.fetch_one(query, params=params)
return cls(*result)
@classmethod
def get_all(cls):
"""Get all servers
Returns:
- list: List of server objects
"""
query = """SELECT id_server, nombre, descripcion FROM db_tif.servidor"""
results = DatabaseConnection.fetch_all(query)
servers = []
if results is not None:
for result in results:
servers.append(cls(*result))
return servers
@classmethod
def get_servers(cls, server):
"""Get a server by id
Args:
- server (server): server object with the id attribute
Returns:
- server: server object
"""
query = f"SELECT db_tif.servidor.id_server, db_tif.servidor.nombre FROM db_tif.servidor INNER JOIN db_tif.membresia_servidor ON db_tif.servidor.id_server = db_tif.membresia_servidor.id_server WHERE db_tif.membresia_servidor.id_user = {server.id_user};"
results = DatabaseConnection.fetch_all(query)
servers = []
if results is not None:
for result in results:
servers.append(cls(*result))
return servers
@classmethod
def create(cls, server):
"""Create a new server and return its ID along with the user ID
Args:
- server (server): server object
- user_id (int): ID of the user who created the server
Returns:
- int: ID of the newly created server
"""
#Si existe el id del usuario que crea el servidor
if server.id_user is not None:
#Creo un nuevo servidor con el id del usuario logueado
query = """INSERT INTO db_tif.servidor (nombre, descripcion) VALUES (%s, %s);"""
params = server.nombre, server.descripcion,
DatabaseConnection.execute_query(query, params=params)
#Capturo el id del ultimo servidor creado
query2 = """SELECT MAX(id_server) AS id FROM db_tif.servidor;"""
param2 = None
id_serv = DatabaseConnection.fetch_one(query2, params=param2)
id_server = id_serv[0]
#Creo un registro de membresia con el id del usuario logueado y el ultimo id de server creado
query3 = """INSERT INTO db_tif.membresia_servidor (id_user, id_server) VALUES (%s, %s)"""
params3 = server.id_user, id_server,
DatabaseConnection.execute_query(query3, params=params3)
#Se crea un canal por DEFAULT llamado "General" al momento de crear un servidor
query4 = f"INSERT INTO db_tif.canal (nombre, id_server) VALUES ('General', {id_server});"
DatabaseConnection.execute_query(query4)
else:
#En el caso que el usuario no este logueado, se crea el servidor sin id
query = """INSERT INTO db_tif.servidor (nombre, descripcion) VALUES (%s, %s);"""
params = server.nombre, server.descripcion,
DatabaseConnection.execute_query(query, params=params)
@classmethod
def update(cls, server):
"""Update a server
Args:
- server (server): server object
"""
params = server.nombre, server.descripcion, server.id_user, server.id_channel, server.id_server,
query = "UPDATE db_tif.servidor SET nombre = %s, descripcion = %s, id_user = %s, id_channel = %s WHERE id_server = %s;"
DatabaseConnection.execute_query(query, params=params)
@classmethod
def delete(cls, server):
"""Delete a server
Args:
- server (server): server object with the id attribute
"""
query = "DELETE FROM db_tif.servidor WHERE id_server = %s;"
params = server.id_server,
DatabaseConnection.execute_query(query, params=params)
@classmethod
def server_user(cls, server):
"""Get a server by id
Args:
- server (server): server object with the id attribute
Returns:
- server: server object
"""
query = """SELECT id_server, nombre, descripcion FROM db_tif.servidor WHERE id_server = %s"""
params = server.id_server, server.id_user
result = DatabaseConnection.fetch_one(query, params=params)
return cls(*result)
@classmethod
def add_server(cls, server):
"""Create a new server and return its ID along with the user ID
Args:
- server (server): server object
- user_id (int): ID of the user who created the server
Returns:
- int: ID of the newly created server
"""
#Creo un registro de membresia con el id del usuario logueado y el ultimo id de server creado
query = """INSERT INTO db_tif.membresia_servidor (id_user, id_server) VALUES (%s, %s)"""
params = server.id_user, server.id_server,
DatabaseConnection.execute_query(query, params=params)
|
package com.lloufa.gestionstockback.controller.api;
import com.lloufa.gestionstockback.dto.CommandeClientDto;
import com.lloufa.gestionstockback.dto.LigneCommandeClientDto;
import com.lloufa.gestionstockback.model.EtatCommande;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
@Api("commandes-clients-api")
@RequestMapping("/commandesClients")
public interface CommandeClientApi {
@PostMapping
@ApiOperation(value = "Enregistrer une commande client", notes = "Cette méthode permet d'enregistrer une commande client", response = CommandeClientDto.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "L'objet commande client est crée"),
@ApiResponse(code = 400, message = "L'objet commande client n'est pas valide")
})
ResponseEntity<CommandeClientDto> save(@RequestBody CommandeClientDto commandeClientDto);
@ApiOperation(value = "Modifier une commande client", notes = "Cette méthode permet de modifier une commande client", response = CommandeClientDto.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "L'objet commande client est modifié"),
@ApiResponse(code = 400, message = "L'objet commande client n'est pas valide")
})
@PutMapping
ResponseEntity<CommandeClientDto> update(@RequestBody CommandeClientDto commandeClientDto);
@ApiOperation(value = "Modifier l'état de la commande client", notes = "Cette méthode permet de modifier l'état d'une commande client", response = CommandeClientDto.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "L'objet commande client est modifié"),
@ApiResponse(code = 400, message = "L'objet commande client n'est pas valide")
})
@PutMapping(value = "{id}/{etatCommande}")
ResponseEntity<CommandeClientDto> updateEtat(@PathVariable Integer id, @PathVariable EtatCommande etatCommande);
@ApiOperation(value = "Modifier la quantité de la commande client", notes = "Cette méthode permet de modifier la quantité d'une commande client", response = CommandeClientDto.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "L'objet commande client est modifié"),
@ApiResponse(code = 400, message = "L'objet commande client n'est pas valide")
})
@PutMapping(value = "{idCommande}/{idLigneCommande}/{quantite}")
ResponseEntity<CommandeClientDto> updateQuantite(@PathVariable Integer idCommande, @PathVariable Integer idLigneCommande, @PathVariable BigDecimal quantite);
@ApiOperation(value = "Modifier le client de la commande client", notes = "Cette méthode permet de modifier le client d'une commande client", response = CommandeClientDto.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "L'objet commande client est modifié"),
@ApiResponse(code = 400, message = "L'objet commande client n'est pas valide")
})
@PutMapping(value = "{id}/{idClient}")
ResponseEntity<CommandeClientDto> updateClient(@PathVariable Integer id, @PathVariable Integer idClient);
@ApiOperation(value = "Modifier l'article de la commande client", notes = "Cette méthode permet de modifier l'article d'une commande client", response = CommandeClientDto.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "L'objet commande client est modifié"),
@ApiResponse(code = 400, message = "L'objet commande client n'est pas valide")
})
@PutMapping(value = "{idCommande}/{idLigneCommande}/{idArticle}")
ResponseEntity<CommandeClientDto> updateArticle(@PathVariable Integer idCommande, @PathVariable Integer idLigneCommande, @PathVariable Integer idArticle);
@GetMapping(value = "{id}")
@ApiOperation(value = "Rechercher une commande client", notes = "Cette méthode permet de rechercher une commande client par son ID", response = CommandeClientDto.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "La commande client a été trouvée dans la BDD"),
@ApiResponse(code = 404, message = "Aucune commande client n'existe dans la BDD avec l'ID fourni")
})
ResponseEntity<CommandeClientDto> findById(@PathVariable Integer id);
@GetMapping(value = "{code}")
@ApiOperation(value = "Rechercher une commande client", notes = "Cette méthode permet de rechercher une commande client par son CODE", response = CommandeClientDto.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "La commande client a été trouvée dans la BDD"),
@ApiResponse(code = 404, message = "Aucune commande client n'existe dans la BDD avec le CODE fourni")
})
ResponseEntity<CommandeClientDto> findByCode(@PathVariable String code);
@GetMapping
@ApiOperation(value = "Renvoi la liste des commandes clients", notes = "Cette méthode permet de rechercher et renvoyer la liste des commandes clients", responseContainer = "List<CommandeClientDto.class>")
@ApiResponse(code = 200, message = "La liste des commandes clients a été trouvée / Une liste dans la BDD")
ResponseEntity<List<CommandeClientDto>> findAll();
@GetMapping(value = "/ligneCommandeClient/{idClient}")
@ApiOperation(value = "Renvoi la liste des lignes de commandes d'un client", notes = "Cette méthode permet de rechercher et renvoyer la liste des lignes de commandes d'un client", responseContainer = "List<LigneCommandeClientDto.class>")
@ApiResponse(code = 200, message = "La liste des lignes de commandes d'un client a été trouvée / Une liste dans la BDD")
ResponseEntity<List<LigneCommandeClientDto>> findAllLigneCommandeClientByCommandeClientId(@PathVariable Integer idClient);
@DeleteMapping(value = "{id}")
@ApiOperation(value = "Rechercher une commande client", notes = "Cette méthode permet de supprimer une commande client par ID")
@ApiResponse(code = 200, message = "La commande client a été trouvée dans la BDD")
ResponseEntity<?> delete(@PathVariable Integer id);
@DeleteMapping(value = "{idCommande}/{idLigneCommande}")
@ApiOperation(value = "Rechercher une commande client", notes = "Cette méthode permet de supprimer une commande client par ID")
@ApiResponse(code = 200, message = "La commande client a été trouvée dans la BDD")
ResponseEntity<CommandeClientDto> deleteArticle(@PathVariable Integer idCommande, @PathVariable Integer idLigneCommande);
}
|
import json
from random import shuffle
from collections import Counter
import torch
import time
import logging
import argparse
import os
logger = logging.getLogger()
logger.setLevel(logging.CRITICAL)
# os.environ['CUDA_VISIBLE_DEVICES'] = '0'
os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
# from reptile import Learner
from methods import maml, anil, stocbio, ma_soba, saba, f2sa, ttsa, bo_rep, slip
from task import MetaTask
import random
import numpy as np
torch.backends.cudnn.enabled = False
def random_seed(value):
torch.backends.cudnn.deterministic=True
torch.manual_seed(value)
torch.cuda.manual_seed(value)
np.random.seed(value)
random.seed(value)
def create_batch_of_tasks(taskset, is_shuffle = True, batch_size = 4):
idxs = list(range(0,len(taskset)))
if is_shuffle:
random.shuffle(idxs)
for i in range(0,len(idxs), batch_size):
yield [taskset[idxs[i]] for i in range(i, min(i + batch_size,len(taskset)))]
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--data", default='snli', type=str,
help="dataset: [news_data, snli]", )
parser.add_argument("--data_path", default='../data/snli_1.0', type=str,
help="Path to dataset file")
parser.add_argument("--save_direct", default='snli', type=str,
help="Path to save file")
parser.add_argument("--word2vec", default="data/snli_1.0/wordvec.pkl", type=str,
help="Path to word2vec file")
parser.add_argument("--methods" , default='slip', type=str,
help="choise method [stocbio, anil, maml, ttsa, f2sa, saba, ma_soba, bo_rep, slip]")
parser.add_argument("--num_labels", default=2, type=int,
help="Number of class for classification")
parser.add_argument("--epochs", default=20, type=int,
help="Number of outer interation")
parser.add_argument("--k_spt", default=20, type=int,
help="Number of support samples per task")
parser.add_argument("--k_qry", default=20, type=int,
help="Number of query samples per task")
parser.add_argument("--task_batch_size", default=20, type=int,
help="Batch of task size")
parser.add_argument("--inner_batch_size", default=50, type=int,
help="Training batch size in inner iteration")
parser.add_argument("--outer_update_lr", default= 1e-1, type=float,
help="Meta learning rate")
parser.add_argument("--hessian_lr", default=1e-2, type=float,
help="update for hessian")
parser.add_argument("--hessian_q", default=5, type=int,
help="Q steps for hessian-inverse-vector product")
parser.add_argument("--inner_update_lr", default=1e-1, type=float,
help="Inner update learning rate")
parser.add_argument("--inner_update_step", default=1, type=int,
help="Number of interation in the inner loop during train time")
parser.add_argument("--inner_update_step_eval", default=40, type=int,
help="Number of interation in the inner loop during test time")
parser.add_argument("--num_task_train", default=400, type=int,
help="Total number of meta tasks for training")
parser.add_argument("--num_task_test", default=100, type=int,
help="Total number of tasks for testing")
parser.add_argument("--grad_clip", default=False, type=bool,
help="whether grad clipping or not")
parser.add_argument("--grad_normalized", default=False, type=bool,
help="whether grad normalized or not")
parser.add_argument("--gamma", default=1e-3, type=float,
help="clipping threshold")
parser.add_argument("--no_meta", default=False, type=bool,
help="whether use meta learning")
parser.add_argument("--seed", default=2, type=int,
help="random seed")
# single loops parameters
parser.add_argument("--beta", default=0.90, type=float,
help="momentum parameters")
parser.add_argument("--nu", default=1e-2, type=float,
help="learning rate of z")
parser.add_argument("--xi", default=0.08, type=float,
help="step-size ratio")
parser.add_argument("--incre_step", default=0.01, type=float,
help="incremental step for lambda in f2sa")
parser.add_argument("--y_warm_start", default=3, type=int,
help="update steps for y")
parser.add_argument("--interval", default=2, type=int,
help="update interval for y")
parser.add_argument("--lamb", default=1e-1, type=float,
help="lagerange coefficient")
# RNN hyperparameter settings
parser.add_argument("--word_embed_dim", default=300, type=int,
help="word embedding dimensions")
parser.add_argument("--encoder_dim", default=4096, type=int,
help="encodding dimensions")
parser.add_argument("--n_enc_layers", default=2, type=int,
help="encoding layers")
parser.add_argument("--fc_dim", default=1024, type=int,
help="dimension of fully-connected layer")
parser.add_argument("--n_classes", default=3, type=int,
help="classes of targets")
parser.add_argument("--linear_fc", default=False, type=bool,
help="classes of targets")
parser.add_argument("--pool_type", default="max", type=str,
help="type of pooling")
args = parser.parse_args()
random_seed(args.seed)
if args.data == 'snli':
args.data_path = '../data/snli_1.0'
train = torch.load('../data/snli_1.0/SNLI/train_Data.pkl')
test = torch.load('../data/snli_1.0/SNLI/test_Data.pkl')
args.n_classes = 3
args.n_labels = 3
if args.data == 'reviews_data':
args.data_path = '../data/reviews_data/dataset.json'
reviews = json.load(open(args.data_path))
low_resource_domains = ["office_products", "automotive", "computer_&_video_games"]
# divide data into training and test data by domain
train_examples = [r for r in reviews if r['domain'] not in low_resource_domains]
test_examples = [r for r in reviews if r['domain'] in low_resource_domains]
print(len(train_examples), len(test_examples))
train = MetaTask(train_examples, num_task=args.num_task_train, k_support=args.k_spt,
k_query=args.k_qry, word2vec=args.word2vec)
test = MetaTask(test_examples, num_task=args.num_task_test, k_support=args.k_spt,
k_query=args.k_qry, word2vec=args.word2vec)
args.n_classes = 2
args.n_labels = 2
st = time.time()
if args.methods == 'maml':
learner = maml.Learner(args)
elif args.methods == 'anil':
learner = anil.Learner(args)
elif args.methods == 'stocbio':
learner = stocbio.Learner(args)
if args.methods == 'ttsa':
learner = ttsa.Learner(args)
if args.methods == 'f2sa':
learner = f2sa.Learner(args)
elif args.methods == 'saba':
learner = saba.Learner(args)
elif args.methods == 'ma_soba':
learner = ma_soba.Learner(args)
elif args.methods == 'bo_rep':
learner = bo_rep.Learner(args)
elif args.methods == 'slip':
learner = slip.Learner(args)
acc_test = []
loss_test = []
acc_train = []
loss_train = []
for epoch in range(args.epochs):
print(f'Hyper-representation method: {args.methods}')
print(f"[epoch/epochs]:{epoch}/{args.epochs}")
db = create_batch_of_tasks(train, is_shuffle = True, batch_size = args.task_batch_size)
acc = None
loss = None
print(f'\n---------Epoch: {epoch} -----------')
for task_batch_id, task_batch in enumerate(db):
acc, loss = learner(task_batch, training = True, task_batch_id = task_batch_id, epoch=epoch)
acc_train.append(acc)
loss_train.append(loss)
print(f'{args.methods}, Epoch: {epoch}, training Loss: {loss_train}')
print(f'{args.methods}, Epoch: {epoch}, training Acc: {acc_train}')
print("---------- Testing Mode -------------")
db_test = create_batch_of_tasks(test, is_shuffle=False, batch_size=args.inner_batch_size)
for test_batch in db_test:
acc, loss = learner(test_batch, training = False, task_id = step)
acc_test.append(acc)
loss_test.append(loss)
print(f'{args.methods}, Epoch: {epoch}, Test Loss: {loss_test}')
print(f'{args.methods}, Epoch: {epoch}, Test Acc: {acc_test}')
file_name = f'meta_learning_{args.methods}_lr_seed{args.seed}'
if not os.path.exists('logs/'+args.save_direct):
os.mkdir('logs/'+args.save_direct)
save_path = 'logs/'+args.save_direct
total_time = (time.time() - st) / 3600
files = open(os.path.join(save_path, file_name)+'.txt', 'w')
files.write(str({'Exp configuration': str(args), 'AVG Train ACC': str(acc_train),
'AVG Test ACC': str(acc_test), 'AVG Train LOSS': str(loss_train), 'AVG Test LOSS': str(loss_test),'time': total_time}))
files.close()
torch.save((acc_train, acc_test, loss_train, loss_test), os.path.join(save_path, file_name))
print(f'time:{total_time} h')
if __name__ == "__main__":
main()
|
/// Represents a specific year and month.
///
/// This class extends the [DateTime] class and provides additional functionality for working with year and month values.
///
/// The [YearMonth] class is immutable, meaning its values cannot be changed after it is created.
///
/// Example usage:
/// ```dart
/// final yearMonth = YearMonth.now();
/// print(yearMonth.year); // Output: current year
/// print(yearMonth.month); // Output: current month
/// print(yearMonth.toString()); // Output: "YYYY-MM"
/// ```
class YearMonth extends DateTime {
YearMonth._internal(int year, int month) : super.utc(year, month, 1);
/// Creates a `YearMonth` object representing the current year and month.
factory YearMonth.now() {
final now = DateTime.now().toUtc();
return YearMonth._internal(now.year, now.month);
}
/// Creates a `YearMonth` object from a JSON map.
factory YearMonth.fromJson(Map<String, dynamic> json) {
final year = json['year'] as int;
final month = json['month'] as int;
return YearMonth._internal(year, month);
}
/// Converts the `YearMonth` object to a JSON map.
Map<String, dynamic> toJson() {
return {
'year': year,
'month': month,
};
}
@override
String toString() {
return '$year-$month';
}
}
|
import { useState } from "react";
import { StatusBar } from "expo-status-bar";
import { StyleSheet, View, Image, Text } from "react-native";
import * as ImagePicker from "expo-image-picker";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import ImageViewer from "./components/ImageViewer/ImageViewer";
import Button from "./components/Button/Button";
import IconButton from "./components/Button/IconButton";
import CircleButton from "./components/Button/CircleButton";
import EmojiPicker from "./components/Emoji/EmojiPicker";
import EmojiList from "./components/Emoji/EmojiList";
import EmojiSticker from "./components/Emoji/EmojiSticker";
const PlaceholderImage = require("./assets/images/background-image.png");
export default function App() {
// Select Image
const [selectedImage, setSelectedImage] = useState(null);
const [isModalVisible, setIsModalVisible] = useState(false);
const [showAppOptions, setShowAppOptions] = useState(false);
const [pickedEmoji, setPickedEmoji] = useState(null);
const pickImageAsync = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
quality: 1,
});
!result.canceled
? (() => {
setSelectedImage(result.assets[0].uri);
setShowAppOptions(true);
})()
: alert("You did not select any image");
};
const onReset = () => {
setShowAppOptions(false);
};
const onAddSticker = () => {
setIsModalVisible(true);
};
const onModalClose = async () => {
setIsModalVisible(false);
};
const onSaveImageAsync = async () => {};
return (
<GestureHandlerRootView style={styles.container}>
<View style={styles.container}>
<View style={styles.imageContainer}>
<ImageViewer
placeholderImageSource={PlaceholderImage}
selectedImage={selectedImage}
/>
{pickedEmoji && (
<EmojiSticker imageSize={40} stickerSource={pickedEmoji} />
)}
</View>
{showAppOptions ? (
<View style={styles.optionsContainer}>
<View style={styles.optionsRow}>
<IconButton iconName="refresh" label="Reset" onPress={onReset} />
<CircleButton onPress={onAddSticker} />
<IconButton
iconName="save-alt"
label="Save"
onPress={onSaveImageAsync}
/>
</View>
</View>
) : (
<View style={styles.footerContainer}>
<Button
label="Choose a photo"
theme="primary"
onPress={pickImageAsync}
/>
<Button
label="Use this photo"
onPress={() => {
setShowAppOptions(true);
}}
/>
</View>
)}
<EmojiPicker isVisible={isModalVisible} onClose={onModalClose}>
<EmojiList onSelect={setPickedEmoji} onCloseModal={onModalClose} />
</EmojiPicker>
<StatusBar style="auto" />
</View>
</GestureHandlerRootView>
);
}
const styles = StyleSheet.create({
text: {
color: "#ffff",
},
container: {
flex: 1,
backgroundColor: "#25292e",
alignItems: "center",
},
imageContainer: {
flex: 1,
paddingTop: 58,
},
optionsContainer: {
position: "absolute",
bottom: 80,
},
optionsRow: {
alignItems: "center",
flexDirection: "row",
},
footerContainer: {
flex: 1 / 3,
alignItems: "center",
},
});
|
import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
goToPrevious,
goToNext,
setAnswer,
setQuestionIndex,
} from "../redux/quizSlice.js";
import { mcqData } from "../mcqData.js";
import { useNavigate } from "react-router-dom"; // Import useNavigate for navigation
function Question({ question, options, selectedOption, onChange }) {
return (
<div>
<h2 className="text-xl font-semibold mb-2">{question}</h2>
<div>
{options.map((option, index) => (
<div key={index} className="mb-2">
<input
type="radio"
id={`option-${index}`}
name="options"
value={option}
checked={selectedOption === option}
onChange={onChange}
/>
<label htmlFor={`option-${index}`} className="ml-2">
{option}
</label>
</div>
))}
</div>
</div>
);
}
export default function Quiz() {
const dispatch = useDispatch();
const { questionIndex, answers } = useSelector((state) => state.quiz);
const currentQuestion = mcqData[questionIndex];
const navigate = useNavigate(); // Get navigate function for navigation
const { currentUser } = useSelector((state) => state.user);
const [loading, setLoading] = useState(false);
console.log(currentUser._id);
console.log(answers);
const handlePrevious = () => {
dispatch(goToPrevious());
};
const handleNext = () => {
dispatch(goToNext(mcqData.length));
};
const handleAnswerChange = (event) => {
dispatch(setAnswer({ index: questionIndex, answer: event.target.value }));
};
const handleSubmit = async () => {
try {
setLoading(true);
// Calculate score based on correct answers
const score = answers.reduce(
(acc, answer, index) =>
answer === mcqData[index].correctAnswer ? acc + 1 : acc,
0
);
const userId = currentUser._id;
const response = await fetch(`/api/auth/users/${userId}/marks`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
marks: score, // Send the calculated score to the server
}),
});
if (!response.ok) {
throw new Error("Failed to submit answers");
}
// Reset question index to default value
dispatch(setQuestionIndex(0));
// Navigate to the result page
navigate("/result");
} catch (error) {
console.error("Error submitting answers:", error);
} finally {
setLoading(false);
}
};
const isLastQuestion = questionIndex === mcqData.length - 1;
return (
<div className="flex items-center justify-center h-screen bg-gradient-to-r from-purple-400 to-indigo-500">
<div className="bg-white p-8 shadow-xl sm:p-10 border border-gray-200 rounded-md max-w-md w-full transform scale-105 hover:scale-100 transition-transform duration-300 ease-in-out mx-auto">
<img
src={currentUser.profilePic}
alt="profile"
className="w-24 h-24 rounded-full mx-auto"
/>
<h1 className="text-4xl font-extrabold text-gray-900 mb-4 text-center">
Quiz Page
</h1>
<p className="text-gray-600 text-lg mb-8 text-center">
Question {questionIndex + 1} of {mcqData.length}
</p>
<Question
question={currentQuestion.question}
options={currentQuestion.options}
selectedOption={answers[questionIndex]}
onChange={handleAnswerChange}
/>
<div className="flex justify-between mb-4">
<button
className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-3 px-6 rounded-full focus:outline-none focus:shadow-outline transform transition-transform hover:scale-110"
onClick={handlePrevious}
disabled={questionIndex === 0}
>
Previous
</button>
{!isLastQuestion && (
<button
className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-3 px-6 rounded-full focus:outline-none focus:shadow-outline transform transition-transform hover:scale-110"
onClick={handleNext}
>
Next
</button>
)}
{isLastQuestion && (
<button
className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-3 px-6 rounded-full focus:outline-none focus:shadow-outline transform transition-transform hover:scale-110"
onClick={handleSubmit}
disabled={loading}
>
{loading ? "Submitting..." : "Submit"}
</button>
)}
</div>
</div>
</div>
);
}
|
require_relative 'Car'
require_relative 'Van'
require_relative 'Bike'
car1 = Car.new("Honda","HD123","1",4,false)
car2 = Car.new("Prado","PD1234","2",6,false)
car3 = Car.new("Honda","HD1235","3",8,true)
car4 = Car.new("Rolex","KD623","4",4,true)
bike1 = Bike.new("Honda","HG726","5",12,false)
bike2 = Bike.new("Suzuki","KD623","6",13,true)
bike3 = Bike.new("Honda","KD663","7",14,false)
bike4 = Bike.new("United","KD653","8",15,false)
van1 = Van.new("Suzuki","GF324","9",4,10,false)
van2 = Van.new("Suzuki","GF324","10",6,11,false)
van3 = Van.new("Civic","GF324","11",8,12,true)
van4 = Van.new("Suzuki","GF324","12",4,13,false)
$vehicles = [car1, car2, car3, car4, bike1, bike2, bike3, bike4, van1, van2, van3, van4]
def add_vehicle(new_vehicle)
$vehicles << new_vehicle
end
def remove_vehicle(reg_no)
$vehicles.delete_if { |vehicle| vehicle.reg_no == reg_no }
end
van5 = Van.new("Suzuki","GF324","13",4,13,false)
add_vehicle(van5)
remove_vehicle("13")
def inventory
$vehicles.each { |vehicle|
if !vehicle.rented_out
puts "Registeration Number of Available #{vehicle.class.name} is #{vehicle.reg_no}"
end
}
end
def rent_out(type)
vehicle = $vehicles.find { |v| v.type == type && !v.rented_out }
if vehicle
vehicle.rented_out = true
vehicle.rent[type.to_sym]
else
"No available #{type}s to rent."
end
end
result = rent_out('van')
puts result
inventory
puts $vehicles.size
|
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- my css -->
<link rel="stylesheet" type="text/css" href="custombootstrap.css">
<title>Contact-Bootstrap</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-blue bg-dark">
<a class="navbar-brand" href="#">Juan Alberto Pimentel JR</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText"
aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarText">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="C:\Users\Juanito\Bootstrap-Portfolio\index.html">Home <span
class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="C:\Users\Juanito\Bootstrap-Portfolio\portfolio.html">Portfolio</a>
</li>
<li class="nav-item">
<a class="nav-link" href="C:\Users\Juanito\Bootstrap-Portfolio\contact.html">Contact</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col big-box">
<div class="card bg-dark text-white">
<img src="C:\Users\Juanito\Basic-Portfolio\assets\images\cat.jpg" class="card-img" alt="cat">
<div class="card-img-overlay">
<a href="file:///C:/Users/Juanito/Psychic_Game/index.html">
<h5 class="card-title">Psychic Game</h5>
</a>
</div>
</div>
</div>
<div class="col">
<div class="row">
<div class="col mini-box">
<div class="card bg-dark text-white">
<img src="C:\Users\Juanito\Basic-Portfolio\assets\images\nightlife.jpg" class="card-img"
alt="night life">
<div class="card-img-overlay">
<a href="">
<h5 class="card-title">Trivia Game</h5>
</a>
</div>
</div>
</div>
<div class="col mini-box">
<div class="card bg-dark text-white">
<img src="C:\Users\Juanito\Basic-Portfolio\assets\images\city.jpg" class="card-img"
alt="city train">
<div class="card-img-overlay">
<a href="">
<h5 class="card-title">Rutgers Info Widget</h5>
</a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col mini-box">
<div class="card bg-dark text-white">
<img src="C:\Users\Juanito\Basic-Portfolio\assets\images\food.jpg" class="card-img"
alt="restaraunt food">
<div class="card-img-overlay">
<a href="">
<h5 class="card-title">Rock Paper Scissors</h5>
</a>
<!-- <p class="card-text">If needed enter text description of link to display on top of img</p> -->
</div>
</div>
</div>
<div class="col mini-box">
<div class="card bg-dark text-white">
<img src="C:\Users\Juanito\Basic-Portfolio\assets\images\ripple.jpg" class="card-img"
alt="ripple effect">
<div class="card-img-overlay">
<a href="">
<h5 class="card-title">RPG Game</h5>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<br>
<footer class="footer mt-auto py-3">
<div class="container">
<span>Copyright</span>
</div>
</footer>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
</body>
</html>
|
package com.example.retrofitexample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.retrofitexample.api.ApiService;
import com.example.retrofitexample.api.SeviceBuilder;
import com.example.retrofitexample.model.User;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private TextView title;
private TextView price;
private TextView category;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = findViewById(R.id.title);
price = findViewById(R.id.price);
category = findViewById(R.id.category);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
callApi();
}
});
}
public void callApi() {
SeviceBuilder.getApiService().getUsers().enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
Toast.makeText(MainActivity.this, "Call api success", Toast.LENGTH_SHORT).show();
List<User> user = response.body();
title.setText(user.get(0).getName());
price.setText(user.get(0).getEmail());
category.setText(user.get(0).getRole());
}
@Override
public void onFailure(Call<List<User>> call, Throwable t) {
Toast.makeText(MainActivity.this, t.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
|
//
// InstallerExportView.swift
// Mist
//
// Created by Nindi Gill on 17/6/2022.
//
import SwiftUI
struct InstallerExportView: View {
@AppStorage("exportApplication")
private var exportApplication: Bool = true
@AppStorage("exportDiskImage")
private var exportDiskImage: Bool = false
@AppStorage("exportISO")
private var exportISO: Bool = false
@AppStorage("exportPackage")
private var exportPackage: Bool = false
var installer: Installer
@Binding var exports: [InstallerExportType]
private var isoCompatible: Bool {
guard let architecture: Architecture = Hardware.architecture else {
return false
}
return (architecture == .intel && installer.mavericksOrNewer) || (architecture == .appleSilicon && installer.bigSurOrNewer)
}
private var compatibilityMessage: String {
guard let architecture: Architecture = Hardware.architecture else {
return ""
}
switch architecture {
case .appleSilicon:
return "**Note:** ISOs are unavailable for building **macOS Catalina 10.15 and older** on [Apple Silicon Macs](https://support.apple.com/en-us/HT211814)."
case .intel:
return "**Note:** ISOs are unavailable for building **OS X Mountain Lion 10.8 and older** on Intel-based Macs."
}
}
var body: some View {
VStack {
Text("Select Export Types:")
.padding(.bottom)
HStack {
Spacer()
InstallerExportViewItem(exportType: .application, selected: $exportApplication)
.disabled(exports.count == 1 && exportApplication)
InstallerExportViewItem(exportType: .diskImage, selected: $exportDiskImage)
.disabled(exports.count == 1 && exportDiskImage)
InstallerExportViewItem(exportType: .iso, selected: $exportISO)
.disabled(isoCompatible ? exports.count == 1 && exportISO : true)
.opacity(isoCompatible ? 1 : 0.5)
InstallerExportViewItem(exportType: .package, selected: $exportPackage)
.disabled(exports.count == 1 && exportPackage)
Spacer()
}
if !isoCompatible {
Text(.init(compatibilityMessage))
.padding(.top)
}
}
.padding()
.onChange(of: exportApplication) { _ in
updateExports()
}
.onChange(of: exportDiskImage) { _ in
updateExports()
}
.onChange(of: exportISO) { _ in
updateExports()
}
.onChange(of: exportPackage) { _ in
updateExports()
}
.onAppear {
updateExports()
}
}
private func updateExports() {
var exports: [InstallerExportType] = []
if !isoCompatible && exportISO {
exportISO = false
}
if !exportApplication && !exportDiskImage && !exportISO && !exportPackage {
exportApplication = true
}
if exportApplication {
exports.append(.application)
}
if exportDiskImage {
exports.append(.diskImage)
}
if exportISO {
exports.append(.iso)
}
if exportPackage {
exports.append(.package)
}
self.exports = exports
}
}
struct InstallerExportView_Previews: PreviewProvider {
static var previews: some View {
InstallerExportView(installer: .example, exports: .constant(InstallerExportType.allCases))
}
}
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class CurrencyConverterApp extends JFrame {
private JComboBox<String> baseCurrencyCombo, targetCurrencyCombo;
private JTextField amountField;
private JTextArea resultArea;
private static final String API_KEY = "YOUR_API_KEY"; // Replace with your API key
private static final String API_URL = "https://open.er-api.com/v6/latest/";
public CurrencyConverterApp() {
setTitle("Currency Converter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
String[] currencies = {"USD", "EUR", "GBP", "JPY", "CAD"}; // List of common currencies
baseCurrencyCombo = new JComboBox<>(currencies);
targetCurrencyCombo = new JComboBox<>(currencies);
amountField = new JTextField(10);
resultArea = new JTextArea(5, 20);
resultArea.setEditable(false);
JButton convertButton = new JButton("Convert");
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
convertCurrency();
}
});
JPanel inputPanel = new JPanel();
inputPanel.add(new JLabel("Base Currency:"));
inputPanel.add(baseCurrencyCombo);
inputPanel.add(new JLabel("Target Currency:"));
inputPanel.add(targetCurrencyCombo);
inputPanel.add(new JLabel("Amount:"));
inputPanel.add(amountField);
inputPanel.add(convertButton);
setLayout(new BorderLayout());
add(inputPanel, BorderLayout.NORTH);
add(new JScrollPane(resultArea), BorderLayout.CENTER);
}
private void convertCurrency() {
String baseCurrency = (String) baseCurrencyCombo.getSelectedItem();
String targetCurrency = (String) targetCurrencyCombo.getSelectedItem();
double amount;
try {
amount = Double.parseDouble(amountField.getText());
} catch (NumberFormatException ex) {
resultArea.setText("Please enter a valid amount.");
return;
}
String apiUrl = API_URL + baseCurrency;
try {
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
connection.disconnect();
JSONObject json = new JSONObject(response.toString());
JSONObject rates = json.getJSONObject("rates");
double exchangeRate = rates.getDouble(targetCurrency);
double convertedAmount = amount * exchangeRate;
resultArea.setText(String.format("%.2f %s is %.2f %s",
amount, baseCurrency, convertedAmount, targetCurrency));
} catch (Exception e) {
resultArea.setText("Error fetching exchange rates.");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
CurrencyConverterApp app = new CurrencyConverterApp();
app.setVisible(true);
});
}
}
|
import { KeoIconProps, KeoIcon } from 'presentation/components';
import { lighten, ListItemIcon, ListItemText, Menu as MuiMenu, MenuItem, MenuList, useTheme } from '@mui/material';
import { ReactNode } from 'react';
type DefinedIcon = KeoIconProps
type UndefinedIcon = {
name?: undefined;
variant?: never;
iconProps?: never
}
type DropdownIcon = DefinedIcon | UndefinedIcon
export type MenuPopupList = {
action?: () => void
label: string;
icon: DropdownIcon
}
type MenuPopupProps = {
onClose: () => void;
anchorEl: HTMLElement | null;
variant?: 'ltr' | 'rtl';
list: MenuPopupList[];
}
function Popup({ list, onClose, anchorEl, variant = 'ltr' }: MenuPopupProps) {
const theme = useTheme();
return (
<MuiMenu
open={!!anchorEl}
anchorEl={anchorEl}
onClose={onClose}
anchorOrigin={
(variant === 'ltr' && { vertical: 'bottom', horizontal: 'left' })
|| (variant === 'rtl' && { vertical: 'bottom', horizontal: 'right' })
|| undefined
}
transformOrigin={
(variant === 'ltr' && ({ vertical: 'top', horizontal: 'left' }))
|| (variant === 'rtl' && ({ vertical: 'top', horizontal: 'right' }))
|| undefined
}
sx={{
'.MuiPaper-root': {
border: `1px solid ${theme.palette.divider}`,
boxShadow: `0 3px 4px 0 ${theme.color.gray[900]}33`,
minWidth: '200px'
},
}}
>
{list && (
<MenuList disablePadding>
{list.length > 0 && list.map((list, index) => {
const handleClick = () => {
if (list.action) list.action();
onClose();
};
return (
<MenuItem key={index} onClick={handleClick}>
{list.icon.variant && (
<ListItemIcon>
<KeoIcon {...list.icon} />
</ListItemIcon>
)}
<ListItemText>{list.label}</ListItemText>
</MenuItem>
);
})}
</MenuList>
)}
</MuiMenu>
);
}
Popup.displayName = 'KeoDropdownPopup';
export default Popup
|
# Count words
Kate likes to count words in text blocks. By words she means continuous sequences of English alphabetic characters (from a to z ). Here are examples:
```
Hello there, little user5453 374 ())$. I’d been using my sphere as a stool. Slow-moving target 839342 was hit by OMGd-63 or K4mp. contains "words" ['Hello', 'there', 'little', 'user', 'I', 'd', 'been', 'using', 'my','sphere', 'as', 'a', 'stool', 'Slow', 'moving', 'target', 'was', 'hit', 'by', 'OMGd', 'or', 'K', 'mp']
```
Kate doesn't like some of words and doesn't count them. Words to be excluded are "a", "the", "on", "at", "of", "upon", "in" and "as", case-insensitive.
Today Kate's too lazy and have decided to teach her computer to count "words" for her.
# Example Input 1
```
Hello there, little user5453 374 ())$.
```
# Example Output 1
```
4
```
# Example Input 2
```
I’d been using my sphere as a stool. I traced counterclockwise circles on it with my fingertips and it shrank until I could palm it. My bolt had shifted while I’d been sitting. I pulled it up and yanked the pleats straight as I careered around tables, chairs, globes, and slow-moving fraas. I passed under a stone arch into the Scriptorium. The place smelled richly of ink. Maybe it was because an ancient fraa and his two fids were copying out books there. But I wondered how long it would take to stop smelling that way if no one ever used it at all; a lot of ink had been spent there, and the wet smell of it must be deep into everything.
```
# Example Output 2
```
112
```
# Solution
```
import re
def word_count(s):
exec,count = ["a", "the", "on", "at", "of", "upon", "in", "as"],0
s = re.sub(r'[^A-Za-z]', ' ', s)
s = s.split()
for i in s:
if i.lower() not in exec:
count+=1
return count
```
|
---
title: "Kompiuteris pabunda pats"
description: ""
tags: [ ]
date: "2011-01-08"
lastmod: "2017-06-29"
---
Jei norite kompiuterį laikinai sustabdyti į RAM arba į diską taip, kad kompiuteris pabustų pats tam tikru metu, pasinaudokite
**rtcwake \[-m mem|disk|no|...\] { \[-s _po\_sekundžių_\] | \[-t _laikas\_sekundėmis\_po\_1970-01-01_\] }** komanda.
Pavyzdžiui, jei kompiuterį norite trims minutėms (180 s) sustabdyti į diską _(**\-m disk**)_, įvykdykite:
**rtcwake -m disk -s 180**
Jei norite nedelsiant sustabdyti į RAM _(**\-m mem**)_,o pažadinti 2011-01-08 11:40:00, tuomet įvykdykite
**rtcwake -m mem -a -t 1294479600**
kur _\-a_ nurodo automatinį laiko juostos atpažinimą (_\-u_ būtų pasauliniam laikui, _\-l_ – vietiniam laikui), o _\-t_ nurodo laiką sekundėmis, praėjusį nuo 1970-01-01 00:00:00 pasauliniu laiku. Laiką sekundėmis nuo tos datos galima sužinoti įvykdžius **date --date="2011-01-08 11:40:00" +%s**. Arba galite rašyti tiesiog taip:
**rtcwake -m mem -a -t "\`date --date="2011-01-08 11:40:00" +%s\`"**
Galima nurodyti pabudimo laiką nepristabdant jo darbo _(**\-m no**)_. Tokiu būdu nurodytumėte, kad kompiuteris tiesiog reikiamu metu būtų įjungtas:
**rtcwake -m no -a -t 1294479600**
**Pastabos:**
Šiam veiksmui reikia administratoriaus teisių. Naudokite tik tas kompiuterio pristabdymo veiksenas, kurios be priekaištų veikia jūsų kompiuteryje. Atsargiai pasirinkite pabudimo laiką, kad, pvz., nešiojamasis kompiuteris netyčia nepabustų krepšyje. Šią funkciją įdomu būtų naudoti kartu su _crontab_, leidžiančia užduotis vykdyti nustatytu laiku.
Daugiau informacijos gausite įvykdę **man rtcwake**
Informacijos šaltinis:
[http://www.osnews.com/story/24111/Wake\_Your\_Linux\_Up\_From\_Sleep\_for\_a\_Cron\_Job](http://www.osnews.com/story/24111/Wake_Your_Linux_Up_From_Sleep_for_a_Cron_Job)
|
{% extends 'site/base.html.twig' %}
{% block title %}
{{ boite.nom }}
-
{{ boite.editeur }}
-
{{ boite.annee }}
{% endblock %}
{% block body %}
<h1 class="col-12 text-center mt-5 pt-3 mb-3">{{ boite.nom }} - {{ boite.editeur }} - <span class="small">{{ boite.annee }}</span></h1>
<div class="row mb-3">
{% include "site/components/catalogues/_retour-button.html.twig" %}
</div>
<!-- BLOC PRESENTATION DU JEU -->
<div class="row mb-5" id="">
<div class="card col-11 mx-auto col-md-10 col-lg-8 p-0 border shadow">
<div class="col-12 d-flex justify-content-center my-4">
{% set url = path('catalogue_pieces_detachees_demande', { id: boite.id, slug: boite.slug, editeur: boite.editeur }) %}
{% include "site/components/catalogues/share_buttons.html.twig" %}
</div>
<div class="card-body d-flex flex-wrap">
<!-- image de la boite -->
<div class="col-12 col-md-6 text-center p-0">
<div class="divImgPresentation mt-4">
<div class="zoom">
<div class="zoom__top zoom__left"></div>
<div class="zoom__top zoom__centre"></div>
<div class="zoom__top zoom__right"></div>
<div class="zoom__middle zoom__left"></div>
<div class="zoom__middle zoom__centre"></div>
<div class="zoom__middle zoom__right"></div>
<div class="zoom__bottom zoom__left"></div>
<div class="zoom__bottom zoom__centre"></div>
<div class="zoom__bottom zoom__right"></div>
{# <img class="zoom__image" src="data:image/png;base64,{{ images[key] }}"/> #}
<img class="zoom__image" src="data:image/png;base64,{{ boite.imageblob }}"/>
</div>
</div>
</div>
<!-- contenu d'une boite -->
<div class="card col-12 col-md-6 p-0 text-primary">
<div class="card-header bg-vos">Contenu d'un jeu complet :</div>
<div class="card-body mt-2">
<ul>
{% set contenus = boite.contenu|split('\r\n') %}
{% if boite.contenu | length > 0 %}
{% for contenu in contenus %}
<li>{{ contenu }}</li>
{% endfor %}
{% else %}
Aucune information pour le moment...
{% endif %}
</ul>
</div>
</div>
<!-- information d'envois -->
<div class="col-11 mx-auto mt-5 p-0">
{% include "/site/components/tableau_des_envois.html.twig" %}
</div>
<!-- message d'information sur un jeu -->
{% if boite.message is defined and boite.message is not null %}
<div class="col-12 text-danger text-center my-5">
<i class="fas fa-bell fa-2x"> Information:</i>
<p class="pl-5">{{ boite.message }}</p>
</div>
{% endif %}
<!-- question pre-formulaire -->
<div class="col-11 mx-auto mt-4">
Vous souhaitez faire une demande de pièces pour ce jeu ?
<a href="{{ path('informations-comment-ca-marche') }}" target="_blank" data-html="true" data-toggle="tooltip" data-placement="top" title="Aide">
<i class="fas fa-question-circle text-info p-2"></i>
</a><br/>
Remplissez ce formulaire et ajoutez cette demande à votre panier !
</div>
<!-- formulaire de demande -->
<form class="col-12 p-0 d-flex flex-wrap" method="post" class="border-primary pt-3" action="{{ path('panier-ajout-pieces-detachees') }}" name="formulaireDemandePiece" enctype="multipart/form-data">
<div class="form-group col-12 col-md-6 p-0">
<textarea class="form-control mt-3" rows="3" id="message" name="message" onkeyup="limiteur();" placeholder="Bonjour, avez vous cette pièce ?..." minlength="15" maxlenght="300" required></textarea>
<span id="precision" class="jumbotron bg-primary text-light p-2">
<i class="fas fa-lightbulb text-info"></i>
N’oubliez pas d’être précis dans votre demande :
<ul class="m-0">
<li>nombre de pièces souhaité</li>
<li>couleur</li>
<li>forme</li>
<li>etc...</li>
</ul>
<div class="col-12 p-0 text-right">Merci</div>
</span>
<small class="form-text text-danger text-center">Entre 15 et 300 caractères.</small>
<div class="small text-center" id="caracteresRestantFormulaireContenuJeu">300 caractères restant...</div>
</div>
<div class="form-group p-0 col-12 col-md-6 mt-4 mt-md-0">
<label class="col-12 text-center">Vous pouvez illustrer votre demande avec 2 photos maximum :</label>
<div class="image-upload text-center">
<label for="file-input">
<i class="fas fa-camera fa-3x cursor-grab"></i>
</label>
<input type="file" name="photo[]" id="file-input" onchange="getFileInfo()" multiple/>
</div>
<div class="col-12 text-center" id="resultatInput"></div>
<p class="col-12 text-center mt-2">
{% include "/components/informations_upload_images.html.twig" %}
</p>
</div>
<div class="col-12 text-center">
<input type="hidden" name="boite" value="{{ boite.id }}">
<input type="hidden" id="recaptchaResponse" name="recaptcha-response">
{% if is_granted('ROLE_USER') %}
<button type="submit" class="btn btn-success mt-3 mb-2">Ajouter au panier</button>
{% else %}
<a href="{{ path('app_login') }}" class="btn btn-warning mt-3 mb-2">Merci de vous identifier !</a>
{% endif %}
</div>
</form>
</div>
</div>
</div>
<div class="row mb-3">
{% include "site/components/catalogues/_retour-button.html.twig" %}
</div>
<script>
function limiteur() {
maximum = 300;
champ = document.getElementById("message");
indic = document.getElementById("message").indicateur;
if (champ.value.length > maximum) {
champ.value = champ.value.substring(0, maximum);
} else {
document.getElementById("caracteresRestantFormulaireContenuJeu").innerHTML = maximum - champ.value.length + " caractères restant...";
document.getElementById("precision").style.display = "block";
}
if (champ.value.length == 0) {
document.getElementById("precision").style.display = "none";
} else { // Init a timeout variable to be used below
let timeout = null;
// Listen for keystroke events
champ.addEventListener('keyup', function (e) {
// Clear the timeout if it has already been set.
// This will prevent the previous task from executing
// if it has been less than <MILLISECONDS>
clearTimeout(timeout);
// Make a new timeout set to go off in 1000ms (1 second)
timeout = setTimeout(function () {
document.getElementById("precision").style.display = "none";
}, 4000);
});
}
}
var resultatInput = document.getElementById('resultatInput');
resultatInput.innerHTML = "Aucune image !";
function getFileInfo() {
var countFiles = document.getElementById('file-input').files.length;
if (countFiles > 1) {
resultatInput.innerHTML = "2 images séléctionnées";
} else {
var name = document.getElementById('file-input').files[0].name;
resultatInput.innerHTML = "Image séléctionnée:<br/>" + name;
}
}
</script>
{% endblock %}
|
import {
ConflictException,
HttpException,
Injectable,
UnprocessableEntityException,
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import axios from "axios";
import { Token } from "graphql";
import { Payment } from "src/apis/payment/entities/payment.entity";
import { Repository } from "typeorm";
@Injectable()
export class IamportService {
async getToken() {
const result = await axios.post("https://api.iamport.kr/users/getToken", {
imp_key: process.env.IAMPORT_API_KEY, // REST API키
imp_secret: process.env.IAMPORT_API_SECRET, // REST API Secret
});
return result.data.response.access_token;
// try {
// } catch (error) {
// throw new HttpException(
// error.response.data.message,
// error.response.status
// );
// }
}
async checkPaid({ impUid, amount, token }) {
console.log(impUid, amount, token);
try {
const result = await axios.get(
`https://api.iamport.kr/payments/${impUid}`,
{ headers: { Authorization: token } }
);
if (result.data.response.status !== "paid")
throw new ConflictException("결제 내역이 존재하지 않습니다.");
if (result.data.response.amount !== amount)
throw new UnprocessableEntityException("결제 금액이 잘못되었습니다.");
} catch (error) {
if (error?.response?.data?.message) {
console.log("에러입니다.");
throw new HttpException(
error.response.data.message,
error.response.status
);
} else {
throw error;
}
}
}
async cancel({ impUid, token }) {
try {
const result = await axios.post(
"http://api.iamport.kr/payments/cancel",
{
imp_uid: impUid,
},
{
headers: { Authorization: token },
}
);
console.log(result);
return result.data.response.cancel_amount;
} finally {
// catch (error) {
// throw new HttpException(
// error.response.data.message,
// error.response.status
// );
// }
}
}
//함수 뭐?? 값 조회? / 비교
async validateData({ amount, impUid }) {
//아임포트에서 토큰 받아오기
try {
const getToken = await axios({
url: "https://api.iamport.kr/users/getToken",
method: "post", // POST method
headers: { "Content-Type": "application/json" }, // "Content-Type": "application/json"
data: {
imp_key: process.env.IAMPORT_API_KEY, // REST API키
imp_secret: process.env.IAMPORT_API_SECRET, // REST API Secret
},
});
const access = getToken.data.response.access_token;
const result = await axios({
url: `https://api.iamport.kr/payments/${impUid}`, // imp_uid 전달
method: "get", // GET method
headers: {
Authorization: `Bearer ${access}`,
}, // 인증 토큰 Authorization header에 추가
});
} catch (error) {
if (error.response.status === 404)
throw new UnprocessableEntityException("없습니다.");
}
//const { _amount: _amount, status } = result.data.response;
// if (status !== "paid") {
// throw new UnprocessableEntityException("결제가 완료되지 않았습니다.");
// }
// if (amount !== _amount) {
// throw new UnprocessableEntityException(
// "결제금액 불일치. 위/변조 된 결제"
// );
}
// async delete({ impUid, amount }) {
// const imp_uid = impUid;
// // 검증로직들
// // 1.아임포트에 요청해서 결제 완료 기록이 존재하는지 확인
// const getToken = await axios({
// url: "https://api.iamport.kr/users/getToken",
// method: "post", // POST method
// headers: { "Content-Type": "application/json" }, // "Content-Type": "application/json"
// data: {
// imp_key: process.env.IAMPORT_API_KEY, // REST API키
// imp_secret: process.env.IAMPORT_API_SECRET, // REST API Secret
// },
// });
// const access = getToken.data.response.access_token;
// /* 아임포트 REST API로 결제환불 요청 */
// const getCancelData = await axios({
// url: "https://api.iamport.kr/payments/cancel",
// method: "post",
// headers: {
// "Content-Type": "application/json",
// Authorization: `Bearer ${access}`,
// },
// data: {
// reason: "테스트용", // 가맹점 클라이언트로부터 받은 환불사유
// imp_uid, // imp_uid를 환불 `unique key`로 입력
// amount, // 가맹점 클라이언트로부터 받은 환불금액
// checksum: amount, // [권장] 환불 가능 금액 입력
// },
// });
// const all = getCancelData.data.response.amount;
// }
}
|
import React, {ChangeEvent, FC, FormEvent, useEffect, useState} from 'react';
import './Input.scss'
import {TErrors} from "../../../../Types/Profile/IAddItem";
import lodash from "lodash"
import DropdownTop from "../../Dropdown/DropdownTop/DropdownTop";
import Icons from "../../Icons/Icons";
import DropdownDrop from "../../Dropdown/DropdownDrop/DropdownDrop";
import Dropdown from "../../Dropdown/Dropdown";
interface IInputSuggest {
items: string[];
}
interface IInput {
type?: string;
typeInput?: 'standart' | null;
defaultValue?: string;
placeholder?: string;
getValueChanged?: (value: string) => void;
errors?: TErrors | null;
tag?: 'input' | 'textarea';
suggest?: IInputSuggest | null;
delay?: number;
sizeInput?: 'small';
}
const Input: FC<IInput> = (props) => {
const {
type = 'text',
typeInput,
defaultValue = '',
placeholder,
getValueChanged,
errors,
tag,
suggest,
delay = 300,
sizeInput
} = props
const [value, setValue] = useState<string>('')
const [activeInput, setActiveInput] = useState<boolean>(false)
useEffect(() => {
if (defaultValue !== value) {
setValue(defaultValue)
}
}, [defaultValue])
useEffect(() => {
if (defaultValue !== value) {
const delayValue = setTimeout(() => {
if (getValueChanged) {
getValueChanged(value)
}
}, delay)
return () => clearTimeout(delayValue)
}
}, [value])
const changeActiveInput = (type: string) => {
if (type === 'focus') {
setActiveInput(true)
}
if (type === 'blur') {
if (value.length > 0) {
setActiveInput(true)
} else {
setActiveInput(false)
}
}
}
return (
<>
{
typeInput === 'standart'
?
<>
{
tag === 'textarea'
?
<textarea
className={`textarea`}
value={value}
onChange={(e) => setValue(e.target.value)}
onFocus={() => changeActiveInput('focus')}
onBlur={() => changeActiveInput('blur')}
placeholder={placeholder}
>
</textarea>
:
<input
className={`input`}
type={type}
value={value}
onChange={(e) => setValue(e.target.value)}
onFocus={() => changeActiveInput('focus')}
onBlur={() => changeActiveInput('blur')}
placeholder={placeholder}
/>
}
{
errors &&
errors?.status &&
<div className="form-input-error" dangerouslySetInnerHTML={{__html: errors?.errorText}}>
</div>
}
</>
:
<div
className={`form-input ${activeInput ? 'form-input--active' : ''} ${sizeInput ? 'form-input--small' : ''} ${errors && errors?.status ? 'input--error' : ''}`}
>
{
placeholder &&
<div className={`form-input-title ${tag === 'textarea' ? 'form-input-title--textarea' : ''}`}>
{
placeholder
}
</div>
}
{
!suggest
?
<>
{
tag === 'textarea'
?
<textarea
className={`textarea`}
value={value}
onChange={(e) => setValue(e.target.value)}
onFocus={() => changeActiveInput('focus')}
onBlur={() => changeActiveInput('blur')}
>
</textarea>
:
<input
className={`input`}
type={type}
value={value}
onChange={(e) => setValue(e.target.value)}
onFocus={() => changeActiveInput('focus')}
onBlur={() => changeActiveInput('blur')}
/>
}
{
errors &&
errors?.status &&
<div className="form-input-error" dangerouslySetInnerHTML={{__html: errors?.errorText}}>
</div>
}
</>
:
<Dropdown>
<DropdownTop
style={{
width: '100%',
}}
>
<input
className={`input`}
type={type}
value={value}
onChange={(e) => setValue(e.target.value)}
onFocus={() => changeActiveInput('focus')}
onBlur={() => changeActiveInput('blur')}
/>
</DropdownTop>
<DropdownDrop>
{
suggest.items &&
suggest.items.length > 0 &&
<div className="select-drop">
{
suggest.items.map((item, indexItem) => (
item &&
<div
key={item + indexItem.toString()}
className={`item`}
data-close-dropdown-to-click="true"
onClick={(e) => setValue(item)}
>
{
item
}
</div>
))
}
</div>
}
</DropdownDrop>
</Dropdown>
}
</div>
}
</>
);
};
export default React.memo(Input);
|
import {
useDeleteQuestionCardCategory,
useUpdateQuestionCardCategory,
} from '@lib/graphql/user/hook/useQuestionCard';
import useInput from '@lib/hooks/useInput';
import useToggle from '@lib/hooks/useToggle';
import { handleError } from '@lib/utils/utils';
import palette from '@styles/palette';
import { Button, Input, message } from 'antd';
import { DefaultOptionType } from 'antd/lib/select';
import React from 'react';
import styled from 'styled-components';
interface CardCategoryItemProps {
category: DefaultOptionType;
setCardCategories: React.Dispatch<React.SetStateAction<DefaultOptionType[]>>;
}
const CardCategoryItem: React.FC<CardCategoryItemProps> = ({
category,
setCardCategories,
}) => {
const [deleteCategory] = useDeleteQuestionCardCategory();
const [editCategory] = useUpdateQuestionCardCategory();
const {
value: editMode,
setValue: setEditMode,
onToggle: onToggleEditMode,
} = useToggle(false);
const {
value: editCategoryName,
setValue: setEditCategoryName,
onChange: onChangeEditCategoryName,
} = useInput(category.label as string);
const requestDeleteCategory = async () => {
try {
const id = category.value as number;
const confirmed = confirm('카테고리를 삭제하시겠습니까?');
if (!confirmed) return;
const res = await deleteCategory({
variables: {
input: {
id,
},
},
});
if (res.data) {
const { deleteQuestionCardCategory } = res.data;
if (deleteQuestionCardCategory.ok) {
message.success('카테고리가 삭제되었습니다.');
setCardCategories((prev) =>
prev.filter((category) => category.value !== id)
);
return;
}
return message.error(deleteQuestionCardCategory.error);
}
} catch (e) {
handleError(e);
}
};
const requestUpdateCategory = async () => {
try {
const id = category.value as number;
const confirmed = confirm('카테고리를 수정하시겠습니까?');
if (!confirmed) return;
const res = await editCategory({
variables: {
input: {
id,
name: editCategoryName,
},
},
});
if (res.data) {
const { updateQuestionCardCategory } = res.data;
if (updateQuestionCardCategory.ok) {
message.success('카테고리가 수정되었습니다.');
setEditMode(false);
setCardCategories((prev) =>
prev.map((category) => {
if (category.value === id) {
return { ...category, label: editCategoryName };
}
return category;
})
);
return;
}
return message.error(updateQuestionCardCategory.error);
}
} catch (e) {
handleError(e);
}
};
return (
<CardCategoryItemContainer>
<p className="card-category-modal-list-item-label">
{editMode ? (
<Input value={editCategoryName} onChange={onChangeEditCategoryName} />
) : (
category.label
)}
</p>
<div className="card-category-modal-list-item-button-wrapper">
{editMode ? (
<>
<button
onClick={requestUpdateCategory}
className="card-category-modal-list-item-button"
>
수정
</button>
<button
onClick={onToggleEditMode}
className="card-category-modal-list-item-button"
>
취소
</button>
</>
) : (
<>
<button
onClick={onToggleEditMode}
className="card-category-modal-list-item-button"
>
수정
</button>
<button
onClick={requestDeleteCategory}
className="card-category-modal-list-item-button"
>
삭제
</button>
</>
)}
</div>
</CardCategoryItemContainer>
);
};
export default CardCategoryItem;
const CardCategoryItemContainer = styled.li`
padding: 10px;
border-bottom: 1px solid ${palette.gray_200};
display: flex;
gap: 15px;
.card-category-modal-list-item-label {
flex: 7;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.card-category-modal-list-item-button-wrapper {
display: flex;
gap: 10px;
flex: 3;
justify-content: flex-end;
}
.card-category-modal-list-item-button {
font-size: 0.9rem;
color: ${palette.gray_700};
transition: 0.2s;
:hover {
color: ${palette.antd_blue_01};
}
}
`;
|
<?php
declare(strict_types=1);
namespace App\Tests\Unit\Crud\List;
use App\Crud\Domain\Enum\FieldType;
use App\Crud\Domain\Value\Field;
use App\Crud\List\ListResult;
use App\Tests\Unit\UnitTestCase;
/**
* @covers \App\Crud\List\ListResult
*/
final class ListResultTest extends UnitTestCase
{
/**
* @test
*/
public function instantiate(): void
{
$result = new ListResult($fields = [new Field(FieldType::ID, 'ID', 'id')], []);
self::assertSame($fields, $result->fields);
self::assertEmpty($result->rows);
self::assertFalse($result->hasRows());
}
/**
* @test
*/
public function instantiateInvalid(): void
{
self::expectException(\InvalidArgumentException::class);
new ListResult([], []);
}
/**
* @test
*/
public function hasRows(): void
{
$result = new ListResult([new Field(FieldType::ID, 'ID', 'id')], [
[],
[],
]);
self::assertTrue($result->hasRows());
}
}
|
/* Assignment 1 Submission
Date: 1/10/22
Group Member Student Number
Sam Brown 200550698
Andres Galeota
Ushno Roylee
Jared Thompson
Justin Chu
*/
-- Tips - You can remove this section when submitting ****
-- Use comments to indicate the question number that each statement addresses.
-- See the format provided for Q1 - Q2 to format the remainder of your SQL script
-- Use proper SQL Standards when formatting your script
-- sql documentation -> https://dev.mysql.com/doc/refman/8.0/en/tutorial.html
-- sql commands + syntax -> https://www.w3schools.com/sql/default.asp
-- github documentation -> https://docs.github.com/en/get-started/quickstart/hello-world
-- github collab guide -> https://medium.com/@jonathanmines/the-ultimate-github-collaboration-guide-df816e98fb67
-- report -> https://docs.google.com/document/d/1-8Iqy60_41eKcWAEKXjuxYjTD5qO3fpzpJDxu6Aoo3E/edit
-- delete question after you've inserted code. explain rationale behind code
-- ----- Replace this with a brief descriptive comment for each query. Explain the function & details of the command, don't just repeat the question.
-- Q1) Create a database for this assignment.
CREATE DATABASE assign1db;
-- Q2) Instruct MySQL Server to use the database you just created.
USE assign1db
-- Q3) In a separate SQL tab, open the barrie_weather.sql file provided. Under question 3, copy its
--contents into your assignment1 script, then run the commands to create the table (also
--called barrie_weather, and will be used to answer following questions) and then populate it
--with data using the provided insert statements.
-- here are the commands to do this, debating how to load it in without making it a pain in the ass
CREATE TABLE `barrie_weather` (
`longitude` double DEFAULT NULL,
`latitude` double DEFAULT NULL,
`station_name` text,
`climate_ID` int DEFAULT NULL,
`date_time` text,
`year` int DEFAULT NULL,
`month` int DEFAULT NULL,
`day` int DEFAULT NULL,
`time` text,
`temp` double DEFAULT NULL,
`temp_flag` text,
`dew_pt` double DEFAULT NULL,
`dew_pt_flag` text,
`rel_hum` int DEFAULT NULL,
`rel_hum_flag` text,
`wind_dir_10d` text,
`wind_dir_flag` text,
`wind_spd_kmh` int DEFAULT NULL,
`wind_spd_flag` text,
`visibility` text,
`vis_flag` text,
`pressure_kPa` double DEFAULT NULL,
`pressure_flag` text,
`hmdx` text,
`hmdx_flag` text,
`wind_chill` text,
`wind_chill_flag` text,
`weather` text
) ENGINE=InnoDB;
-- Q4) In the report only, explain how the provided CREATE TABLE statement could be improved.
--Please focus on the data types and parameters for this discussion.
-- https://docs.google.com/document/d/1-8Iqy60_41eKcWAEKXjuxYjTD5qO3fpzpJDxu6Aoo3E/edit
-- Q5) The provided INSERT statements in barrie_weather were generated automatically and load
-- data very slowly because of the way that the script’s commands have been structured. What
-- is it about the structure of this script that causes the script to run slowly? In the report only,
-- explain how you could restructure the commands if you were tasked with inserting the
-- same data into barrie_weather.
-- https://docs.google.com/document/d/1-8Iqy60_41eKcWAEKXjuxYjTD5qO3fpzpJDxu6Aoo3E/edit
-- Q6) Select all data for every hour of data where the temperature (temp) was greater than 26.5.
-- Provide an additional comment in your SQL script that states the number of rows returned.
-- Q7) Select the date_time, temp, pressure_kPA and wind_spd_kmh for every hour of data where
-- the temperature was 24 or less and the air pressure (pressure_kPa) was greater than 96.83.
-- Provide an additional comment in your SQL script that states the number of rows returned
-- Q8) Select the date and time (date_time), temperature (temp) and temperature flag (temp_flag)
-- columns for every hour where temperature data has been marked as missing using an ‘M’
-- value in the temp_flag column.
-- In the report, record the date and time.
-- Hint: remember that single quotes are required for text values.
-- Q9) Return the same results as in Question 8, except construct the query to return both ‘M’ and
-- ‘Missing’ values.
-- Note: There are a number of ways of doing this, please use LIKE
-- Q10) Count (SELECT COUNT) the number of hours contained in this dataset, where the dew point
-- temperature (dew_pt) is greater than one.
-- Q11) Count the number of hours that the wind was blowing (wind_spd_kmh is greater than 0)
-- and from a direction ranging between north and east (wind_dir_10d is between 0 and 9)
-- Q12) In the report only, in Barrie what percent of the time are the conditions listed in Q11 true?
-- Q13) Select all data for every hour of data where either the temperature (temp) is below freezing,
-- or wind chill (wind_chill) was below zero. Additionally, the wind speed flag (wind_spd_flag)
-- must indicate that there were no problems with the wind speed instrument (i.e. no M or
-- Missing values present)
-- BTW: an anemometer is an instrument that measures wind speed
-- Q14) Fix the M vs Missing problem in the temperature flag field by using UPDATE to change any
-- instances of Missing values to just plain M.
-- Q15) Use an update statement to change all ' ' values in the temp_flag column to NULL (no quotes,
-- just the letters N-U-L-L) this will change.
-- Hint: The values should end up looking like those in the humidex (hmdx) column.
-- FYI: The best way to store null data is using the NULL value. Look to the humidex (hmdx)
-- column for an example of this being implemented properly.
|
# Derek Young and Alex Mandel
# University of California, Davis
# 2021
# Last edited and adapted by Clemente Gotelli
# LHE-EPFL
# 2022
#### Import libraries
# import the fuctionality we need to make time stamps to measure performance
import time
import datetime
import platform
import os
import glob
import re
import yaml
### import the Metashape functionality
import Metashape
#### Helper functions and globals
# Set the log file name-value separator
# Chose ; as : is in timestamps
# TODO: Consider moving log to json/yaml formatting using a dict
sep = "; "
def stamp_time():
'''
Format the timestamps as needed
'''
stamp = datetime.datetime.now().strftime('%Y%m%dT%H%M')
return stamp
def diff_time(t2, t1):
'''
Give a end and start time, subtract, and round
'''
total = str(round(t2-t1, 1))
return total
# Used by add_gcps function
def get_marker(chunk, label):
for marker in chunk.markers:
if marker.label == label:
return marker
return None
# Used by add_gcps function
def get_camera(chunk, label):
for camera in chunk.cameras:
if camera.label.lower() == label.lower():
return camera
return None
#### Functions for each major step in Metashape
def project_setup(cfg):
'''
Create output and project paths, if they don't exist
Define a project ID based on photoset name and timestamp
Define a project filename and a log filename
Create the project
Start a log file
'''
# Make project directories (necessary even if loading an existing project because this workflow saves a new project based on the old one, leaving the old one intact
if not os.path.exists(cfg["output_path"]):
os.makedirs(cfg["output_path"])
if not os.path.exists(cfg["project_path"]):
os.makedirs(cfg["project_path"])
### Set a filename template for project files and output files
## Get the first parts of the filename (the photoset ID and location string)
run_name = cfg["run_name"]
## Project file example to make: "projectID_YYYYMMDDtHHMM-jobID.psx"
timestamp = stamp_time()
run_id = "_".join([run_name,cfg["subFolder"],timestamp])
# TODO: If there is a slurm JobID, append to time (separated with "-", not "_"). This will keep jobs initiated in the same minute distinct
project_file = os.path.join(cfg["project_path"], '.'.join([run_id, 'psx']) )
log_file = os.path.join(cfg["output_path"], '.'.join([run_id+"_log",'txt']) )
'''
Create a doc and a chunk
'''
# create a handle to the Metashape object
doc = Metashape.Document() #When running via Metashape, can use: doc = Metashape.app.document
# If specified, open existing project
if cfg["load_project"] != "":
doc.open(cfg["load_project"])
else:
# Initialize a chunk, set its CRS as specified
chunk = doc.addChunk()
chunk.crs = Metashape.CoordinateSystem(cfg["project_crs"])
chunk.marker_crs = Metashape.CoordinateSystem(cfg["project_crs"])
# Save doc doc as new project (even if we opened an existing project, save as a separate one so the existing project remains accessible in its original state)
doc.save(project_file)
'''
Log specs except for GPU
'''
# log Metashape version, CPU specs, time, and project location to results file
# open the results file
# TODO: records the Slurm values for actual cpus and ram allocated
# https://slurm.schedmd.com/sbatch.html#lbAI
with open(log_file, 'a') as file:
# write a line with the Metashape version
file.write(sep.join(['Project', run_id])+'\n')
file.write(sep.join(['Agisoft Metashape Professional Version', Metashape.app.version])+'\n')
# write a line with the date and time
file.write(sep.join(['Processing started', stamp_time()]) +'\n')
# write a line with CPU info - if possible, improve the way the CPU info is found / recorded
file.write(sep.join(['Node', platform.node()])+'\n')
file.write(sep.join(['CPU', platform.processor()]) +'\n')
# write two lines with GPU info: count and model names - this takes multiple steps to make it look clean in the end
return doc, log_file, run_id
def enable_and_log_gpu(log_file):
'''
Enables GPU and logs GPU specs
'''
gpustringraw = str(Metashape.app.enumGPUDevices())
gpucount = gpustringraw.count("name': '")
gpustring = ''
currentgpu = 1
while gpucount >= currentgpu:
if gpustring != '': gpustring = gpustring+', '
gpustring = gpustring+gpustringraw.split("name': '")[currentgpu].split("',")[0]
currentgpu = currentgpu+1
#gpustring = gpustringraw.split("name': '")[1].split("',")[0]
gpu_mask = Metashape.app.gpu_mask
with open(log_file, 'a') as file:
file.write(sep.join(['Number of GPUs Found', str(gpucount)]) +'\n')
file.write(sep.join(['GPU Model', gpustring])+'\n')
file.write(sep.join(['GPU Mask', str(gpu_mask)])+'\n')
# If a GPU exists but is not enabled, enable the 1st one
if (gpucount > 0) and (gpu_mask == 0):
Metashape.app.gpu_mask = 1
gpu_mask = Metashape.app.gpu_mask
file.write(sep.join(['GPU Mask Enabled', str(gpu_mask)])+'\n')
# This writes down all the GPU devices available
#file.write('GPU(s): '+str(Metashape.app.enumGPUDevices())+'\n')
# set Metashape to *not* use the CPU during GPU steps (appears to be standard wisdom)
Metashape.app.cpu_enable = False
return True
def add_photos(doc, cfg):
'''
Add photos to project and change their labels to include their containing folder
'''
## Get paths to all the project photos
print(os.path.join(cfg["main_path"],cfg["subFolder"],"**","*.*"))
a = glob.iglob(os.path.join(cfg["main_path"],cfg["subFolder"],"**","*.*"), recursive=True) #(([jJ][pP][gG])|([tT][iI][fF]))
print(a)
b = [path for path in a]
photo_files = [x for x in b if (re.search("(.tif$)|(.jpg$)|(.TIF$)|(.JPG$)",x) and (not re.search("dem_usgs.tif",x)))]
## Add them
if cfg["multispectral"]:
doc.chunk.addPhotos(photo_files, layout = Metashape.MultiplaneLayout)
else:
doc.chunk.addPhotos(photo_files)
## Need to change the label on each camera so that it includes the containing folder(S)
for camera in doc.chunk.cameras:
path = camera.photo.path
# remove the base imagery dir from this string
rel_path = path.replace(os.path.join(cfg["main_path"],cfg["subFolder"]),"")
# if it starts with a '/', remove it
newlabel = re.sub("^/","",rel_path)
camera.label = newlabel
## If specified, change the accuracy of the cameras to match the RTK flag (RTK fix if flag = 50, otherwise no fix
if cfg["use_rtk"]:
for cam in doc.chunk.cameras:
rtkflag = cam.photo.meta['DJI/RtkFlag']
if rtkflag == '50':
cam.reference.location_accuracy = Metashape.Vector([cfg["fix_accuracy"],cfg["fix_accuracy"],cfg["fix_accuracy"]])
cam.reference.accuracy = Metashape.Vector([cfg["fix_accuracy"],cfg["fix_accuracy"],cfg["fix_accuracy"]])
else:
cam.reference.location_accuracy = Metashape.Vector([cfg["nofix_accuracy"],cfg["nofix_accuracy"],cfg["nofix_accuracy"]])
cam.reference.accuracy = Metashape.Vector([cfg["nofix_accuracy"],cfg["nofix_accuracy"],cfg["nofix_accuracy"]])
doc.save()
return True
def align_photos(doc, log_file, cfg):
'''
Match photos, align cameras, optimize cameras
'''
#### Align photos
# get a beginning time stamp
timer1a = time.time()
# Align cameras
doc.chunk.matchPhotos(downscale=cfg["alignPhotos"]["downscale"],
subdivide_task = cfg["subdivide_task"],
reference_preselection_mode = cfg["alignPhotos"]["preselectionMode"])
doc.chunk.alignCameras(adaptive_fitting=cfg["alignPhotos"]["adaptive_fitting"],
subdivide_task = cfg["subdivide_task"])
doc.save()
# get an ending time stamp
timer1b = time.time()
# calculate difference between end and start time to 1 decimal place
time1 = diff_time(timer1b, timer1a)
# record results to file
with open(log_file, 'a') as file:
file.write(sep.join(['Align Photos', time1])+'\n')
return True
def importReference(doc, cfg):
'''
Imports a reference system already set for a project with the same markers and local coordinate system
'''
#crs = Metashape.CoordinateSystem('LOCAL_CS["Local Coordinates (m)",LOCAL_DATUM["Local Datum",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]]]')
print('changing reference to local coordinates')
doc.chunk.crs = Metashape.CoordinateSystem(cfg["project_crs"])
doc.chunk.marker_crs = Metashape.CoordinateSystem(cfg["project_crs"])
print('Detecting markers')
doc.chunk.detectMarkers(tolerance=50, filter_mask=False)
doc.save()
print('Importing reference system')
doc.chunk.importReference(path=os.path.join(cfg["main_path"],cfg["subFolder"],"referenceMarkers.txt"), format=cfg["importMarkers"]["format"], delimiter=cfg["importMarkers"]["delimiter"], create_markers=False, columns='nxyz')
doc.chunk.updateTransform()
print('todo listo')
doc.save()
return True
def reset_region(doc):
'''
Reset the region and make it much larger than the points; necessary because if points go outside the region, they get clipped when saving
'''
doc.chunk.resetRegion()
region_dims = doc.chunk.region.size
region_dims[2] *= 3
doc.chunk.region.size = region_dims
return True
def optimize_cameras(doc, cfg):
'''
Optimize cameras
'''
# Currently only optimizes the default parameters, which is not all possible parameters
doc.chunk.optimizeCameras(adaptive_fitting=cfg["optimizeCameras"]["adaptive_fitting"])
doc.save()
return True
def build_dense_cloud(doc, log_file, run_id, cfg):
'''
Build depth maps and dense cloud
'''
### Build depth maps
# get a beginning time stamp for the next step
timer2a = time.time()
# build depth maps only instead of also building the dense cloud ##?? what does
doc.chunk.buildDepthMaps(downscale=cfg["buildDenseCloud"]["downscale"],
filter_mode=cfg["buildDenseCloud"]["filter_mode"],
reuse_depth=cfg["buildDenseCloud"]["reuse_depth"],
max_neighbors=cfg["buildDenseCloud"]["max_neighbors"],
subdivide_task=cfg["subdivide_task"])
doc.save()
# get an ending time stamp for the previous step
timer2b = time.time()
# calculate difference between end and start time to 1 decimal place
time2 = diff_time(timer2b, timer2a)
# record results to file
with open(log_file, 'a') as file:
file.write(sep.join(['Build Depth Maps', time2]) + '\n')
### Build dense cloud
# get a beginning time stamp for the next step
timer3a = time.time()
# build dense cloud
doc.chunk.buildDenseCloud(max_neighbors=cfg["buildDenseCloud"]["max_neighbors"],
keep_depth = cfg["buildDenseCloud"]["keep_depth"],
subdivide_task = cfg["subdivide_task"],
point_colors = False)
doc.save()
# get an ending time stamp for the previous step
timer3b = time.time()
# calculate difference between end and start time to 1 decimal place
time3 = diff_time(timer3b, timer3a)
# record results to file
with open(log_file, 'a') as file:
file.write(sep.join(['Build Dense Cloud', time3])+'\n')
### Classify ground points
if cfg["buildDenseCloud"]["classify"]:
# get a beginning time stamp for the next step
timer_a = time.time()
doc.chunk.dense_cloud.classifyGroundPoints(max_angle=cfg["buildDenseCloud"]["max_angle"],
max_distance=cfg["buildDenseCloud"]["max_distance"],
cell_size=cfg["buildDenseCloud"]["cell_size"])
doc.save()
# get an ending time stamp for the previous step
timer_b = time.time()
# calculate difference between end and start time to 1 decimal place
time_tot = diff_time(timer_b, timer_a)
# record results to file
with open(log_file, 'a') as file:
file.write(sep.join(['Classify Ground Points', time_tot]) + '\n')
### Export points
if cfg["buildDenseCloud"]["export"]:
output_file = os.path.join(cfg["output_path"], run_id + '_points.las')
if cfg["buildDenseCloud"]["classes"] == "ALL":
# call without classes argument (Metashape then defaults to all classes)
doc.chunk.exportPoints(path=output_file,
source_data=Metashape.DenseCloudData,
format=Metashape.PointsFormatLAS,
crs=Metashape.CoordinateSystem(cfg["project_crs"]),
subdivide_task=cfg["subdivide_task"])
else:
# call with classes argument
doc.chunk.exportPoints(path=output_file,
source_data=Metashape.DenseCloudData,
format=Metashape.PointsFormatLAS,
crs=Metashape.CoordinateSystem(cfg["project_crs"]),
clases=cfg["buildDenseCloud"]["classes"],
subdivide_task=cfg["subdivide_task"])
return True
def build_dem(doc, log_file, run_id, cfg):
'''
Build end export DEM
'''
# get a beginning time stamp for the next step
timer5a = time.time()
#prepping params for buildDem
projection = Metashape.OrthoProjection()
projection.crs = Metashape.CoordinateSystem(cfg["project_crs"])
print(projection.crs)
#prepping params for export
compression = Metashape.ImageCompression()
compression.tiff_big = cfg["buildDem"]["tiff_big"]
compression.tiff_tiled = cfg["buildDem"]["tiff_tiled"]
compression.tiff_overviews = cfg["buildDem"]["tiff_overviews"]
if (cfg["buildDem"]["type"] == "DSM") | (cfg["buildDem"]["type"] == "both"):
# call without classes argument (Metashape then defaults to all classes)
doc.chunk.buildDem(source_data = Metashape.DenseCloudData,
subdivide_task = cfg["subdivide_task"],
projection = projection)
output_file = os.path.join(cfg["output_path"], run_id + '_dsm.tif')
if cfg["buildDem"]["export"]:
doc.chunk.exportRaster(path=output_file,
projection=projection,
nodata_value=cfg["buildDem"]["nodata"],
source_data=Metashape.ElevationData,
image_compression=compression,
clip_to_boundary=cfg["buildDem"]["clip_to_boundary"])
if (cfg["buildDem"]["type"] == "DTM") | (cfg["buildDem"]["type"] == "both"):
# call with classes argument
doc.chunk.buildDem(source_data = Metashape.DenseCloudData,
subdivide_task = cfg["subdivide_task"],
projection = projection)
output_file = os.path.join(cfg["output_path"], run_id + '_dtm.tif')
if cfg["buildDem"]["export"]:
doc.chunk.exportRaster(path=output_file,
projection=projection,
nodata_value=cfg["buildDem"]["nodata"],
source_data=Metashape.ElevationData,
image_compression=compression,
clip_to_boundary=cfg["buildDem"]["clip_to_boundary"])
if (cfg["buildDem"]["type"] != "DTM") & (cfg["buildDem"]["type"] == "both") & (cfg["buildDem"]["type"] == "DSM"):
raise ValueError("DEM type must be either 'DSM' or 'DTM' or 'both'")
doc.save()
# get an ending time stamp for the previous step
timer5b = time.time()
# calculate difference between end and start time to 1 decimal place
time5 = diff_time(timer5b, timer5a)
# record results to file
with open(log_file, 'a') as file:
file.write(sep.join(['Build DEM', time5])+'\n')
return True
# This is just a helper function called by build_orthomosaic
def export_orthomosaic(doc, log_file, run_id, cfg):
'''
Export orthomosaic
'''
return True
def build_export_orthomosaic(doc, log_file, run_id, cfg, file_ending):
'''
Helper function called by build_orthomosaics. build_export_orthomosaic builds and exports an ortho based on the current elevation data.
build_orthomosaics sets the current elevation data and calls build_export_orthomosaic (one or more times depending on how many orthomosaics requested)
'''
# get a beginning time stamp for the next step
timer6a = time.time()
#prepping params for buildDem
projection = Metashape.OrthoProjection()
projection.crs = Metashape.CoordinateSystem(cfg["project_crs"])
doc.chunk.buildOrthomosaic(surface_data=Metashape.ElevationData,
blending_mode=cfg["buildOrthomosaic"]["blending"],
fill_holes=cfg["buildOrthomosaic"]["fill_holes"],
refine_seamlines=cfg["buildOrthomosaic"]["refine_seamlines"],
subdivide_task=cfg["subdivide_task"],
projection=projection,
resolution=cfg["buildOrthomosaic"]["resolution"])
doc.save()
## Export orthomosaic
if cfg["buildOrthomosaic"]["export"]:
output_file = os.path.join(cfg["output_path"], run_id + '_ortho_' + file_ending + '.tif')
compression = Metashape.ImageCompression()
compression.tiff_big = cfg["buildOrthomosaic"]["tiff_big"]
compression.tiff_tiled = cfg["buildOrthomosaic"]["tiff_tiled"]
compression.tiff_overviews = cfg["buildOrthomosaic"]["tiff_overviews"]
projection = Metashape.OrthoProjection()
projection.crs = Metashape.CoordinateSystem(cfg["project_crs"])
doc.chunk.exportRaster(path=output_file,
projection=projection,
nodata_value=cfg["buildOrthomosaic"]["nodata"],
source_data=Metashape.OrthomosaicData,
image_compression=compression,
resolution=cfg["buildOrthomosaic"]["resolution"])
# get an ending time stamp for the previous step
timer6b = time.time()
# calculate difference between end and start time to 1 decimal place
time6 = diff_time(timer6b, timer6a)
# record results to file
with open(log_file, 'a') as file:
file.write(sep.join(['Build Orthomosaic', time6]) + '\n')
return True
def build_orthomosaics(doc, log_file, run_id, cfg):
'''
Build orthomosaic. This function just calculates the needed elevation data(s) and then calls build_export_orthomosaic to do the actual building and exporting. It does this multiple times if orthos based on multiple surfaces were requsted
'''
# prep projection for export step below (in case export is enabled)
projection = Metashape.OrthoProjection()
projection.crs = Metashape.CoordinateSystem(cfg["project_crs"])
# get a beginning time stamp for the next step
timer6a = time.time()
# what should the orthomosaic filename end in? e.g., DSM, DTM, USGS to indicate the surface it was built on
file_ending = cfg["buildOrthomosaic"]["surface"]
# Otherwise use Metashape point cloud to build elevation model
# DTM: use ground points only
if (cfg["buildOrthomosaic"]["surface"] == "DTM") | (cfg["buildOrthomosaic"]["surface"] == "DTMandDSM"):
doc.chunk.buildDem(source_data = Metashape.DenseCloudData,
classes=Metashape.PointClass.Ground,
subdivide_task=cfg["subdivide_task"],
projection=projection)
build_export_orthomosaic(doc, log_file, run_id, cfg, file_ending = "dtm")
# DSM: use all point classes
if (cfg["buildOrthomosaic"]["surface"] == "DSM") | (cfg["buildOrthomosaic"]["surface"] == "DTMandDSM"):
doc.chunk.buildDem(source_data = Metashape.DenseCloudData,
subdivide_task=cfg["subdivide_task"],
projection=projection)
build_export_orthomosaic(doc, log_file, run_id, cfg, file_ending = "dsm")
return True
def export_report(doc, run_id, cfg):
'''
Export report
'''
output_file = os.path.join(cfg["output_path"], run_id+'_report.pdf')
doc.chunk.exportReport(path = output_file)
return True
def finish_run(log_file,config_file):
'''
Finish run (i.e., write completed time to log)
'''
# finish local results log and close it for the last time
with open(log_file, 'a') as file:
file.write(sep.join(['Run Completed', stamp_time()])+'\n')
# open run configuration again. We can't just use the existing cfg file because its objects had already been converted to Metashape objects (they don't write well)
with open(config_file) as file:
config_full = yaml.safe_load(file)
# write the run configuration to the log file
with open(log_file, 'a') as file:
file.write("\n\n### CONFIGURATION ###\n")
documents = yaml.dump(config_full,file, default_flow_style=False)
file.write("### END CONFIGURATION ###\n")
return True
def SetBoundary(doc, cfg): # ADD OPTION FOR SETTING DEM WITH A POLYGON WHICH VERTICES ARE MARKERS.
if cfg["buildDem"]["boundaryMode"] == "Markers":
print("Boundary mode with Markers.")
T = doc.chunk.transform.matrix
P = doc.chunk.shapes.projection.matrix
if not doc.chunk.shapes:
doc.chunk.shapes = Metashape.Shapes()
doc.chunk.shapes.crs = Metashape.CoordinateSystem(cfg["project_crs"])
#doc.chunk.shapes.crs = doc.chunk.crs
crs = Metashape.CoordinateSystem(cfg["project_crs"])
shape = doc.chunk.shapes.addShape()
shape.label = "boundary"
shape.geometry.type = Metashape.Geometry.Type.PolygonType
shape.boundary_type = Metashape.Shape.BoundaryType.OuterBoundary
coords = [P.mulp(crs.project(T.mulp(marker.position))) for marker in doc.chunk.markers]
selected_coords = []
cfg["importMarkers"]["rightlim"]
for i in range(0, (cfg["importMarkers"]["rightlim"]-1)):
selected_coords.append(coords[i])
for i in range(cfg["importMarkers"]["lefttlim"]-1, 21, -1):
selected_coords.append(coords[i])
shape.geometry = Metashape.Geometry.Polygon(selected_coords)
doc.save()
elif cfg["buildDem"]["boundaryMode"] == "Shape":
print("Boundary mode with imported Shape.")
doc.chunk.importShapes(os.path.join(cfg["main_path"],cfg["subFolder"],'outBoundary.shp'), boundary_type=Metashape.Shape.OuterBoundary)
else:
print("The boundary was not properly set.")
return True
|
import os
import sys
import time
import snap7
from configparser import ConfigParser
sys.path.append(os.path.join(os.path.dirname(__file__), '../../..'))
from xarm.wrapper import XArmAPI
PLC_IP = '192.168.0.1'
XARM_IP = '192.168.1.201'
RACK = 0
SLOT = 1
plc = snap7.client.Client()
STATES = {
"IDLE": 0,
"WAIT_SENSOR": 1,
"WAIT_ACTION": 2,
"OK_ROUTINE": 3,
"SCRAP_ROUTINE": 4,
"SHUTDOWN": 100
}
class SnapArm:
"""Class to connect to the PLC and the xArm"""
def __init__(self):
# PLC configs
self.plc = snap7.client.Client()
self.plc.connect(PLC_IP, RACK, SLOT)
# Arm configs
self.arm = XArmAPI(XARM_IP, do_not_open=True)
self.arm.register_error_warn_changed_callback(self.handle_err_warn_changed)
self.arm.connect()
# enable motion
self.arm.motion_enable(enable=True)
# set mode: position control mode
self.arm.set_mode(0)
# set state: sport state
self.arm.set_state(state=0)
self.current_state = STATES["IDLE"]
self.sensor_state = None
self.plc_action_data = None
self.ok_counter = 0
self.scrap_counter = 0
self.run()
def handle_err_warn_changed(self, item):
print('ErrorCode: {}, WarnCode: {}'.format(item['error_code'], item['warn_code']))
# TODO: Do different processing according to the error code
def decimal_to_binary(self, decimal):
binary = bin(decimal)[2:].zfill(16) # Convert to binary and zero-fill to 16 bits
text = binary
position = 8
# Check if the position is valid
if position < len(text):
part1 = text[:position] # Characters before position 3
part2 = text[position:] # Characters at position 3 and onwards
return [part1, part2]
else:
print("Position is out of range")
def execute_ok_routine(self):
self.arm.set_position(x=-52.2, y=330.8, z=-46.3, roll=-178.2, pitch=0.9, yaw=94.1, speed=100, wait=False)
self.arm.set_cgpio_digital(0, 1)
self.arm.set_position(x=-55.7, y=308.5, z=85, roll=-177.7, pitch=-0.6, yaw=92.8, speed=100, wait=False)
self.arm.set_position(x=259.4, y=12.4, z=115.9, roll=179.6, pitch=-2.3, yaw=0.9, speed=100, wait=False)
self.arm.set_position(x=286.7, y=24.4, z=-67.1, roll=179.8, pitch=-0.1, yaw=2.9, speed=100, wait=False)
self.arm.set_cgpio_digital(0, 0)
self.arm.set_position(x=259.4, y=12.4, z=115.9, roll=179.6, pitch=-2.3, yaw=0.9, speed=100, wait=False)
self.arm.set_position(x=300, y=0, z=180, roll=-180, pitch=0, yaw=0, speed=100, wait=False)
self.ok_counter += 1
a, b = self.decimal_to_binary(self.ok_counter)
self.plc_action_data[0] = int(a)
self.plc_action_data[1] = int(b)
self.plc.db_write(1, 0, self.plc_action_data)
def execute_scrap_routine(self):
self.arm.set_position(x=-52.2, y=330.8, z=-46.3, roll=-178.2, pitch=0.9, yaw=94.1, speed=100, wait=False)
self.arm.set_cgpio_digital(0, 1)
self.arm.set_position(x=-55.7, y=308.5, z=85, roll=-177.7, pitch=-0.6, yaw=92.8, speed=100, wait=False)
self.arm.set_position(x=256.6, y=-145, z=77.8, roll=179.7, pitch=-2, yaw=-0.4, speed=100, wait=False)
self.arm.set_position(x=272.9, y=-135.4, z=-89, roll=-179.1, pitch=-6.2, yaw=2.6, speed=100, wait=False)
self.arm.set_cgpio_digital(0, 0)
self.arm.set_position(x=256.6, y=-145, z=77.8, roll=179.7, pitch=-2, yaw=-0.4, speed=100, wait=False)
self.arm.set_position(x=300, y=0, z=180, roll=-180, pitch=0, yaw=0, speed=100, wait=False)
self.scrap_counter += 1
a, b = self.decimal_to_binary(self.scrap_counter)
self.plc_action_data[2] = int(a)
self.plc_action_data[3] = int(b)
plc.db_write(1, 0, self.plc_action_data)
def run(self):
while True:
try:
if self.current_state == STATES["IDLE"]:
self.arm.set_position(x=300, y=0, z=180, roll=-180, pitch=0, yaw=0, speed=100, wait=False)
print("Waiting for sensor...")
self.current_state = STATES["WAIT_SENSOR"]
elif self.current_state == STATES["WAIT_SENSOR"]:
self.sensor_state = self.arm.get_cgpio_digital()
if self.sensor_state == (0, [1, 1, 1, 1, 1, 1, 1, 0]):
self.arm.set_position(x=-69.6, y=243.5, z=96.8, roll=179.8, pitch=0.8, yaw=92, speed=100, wait=False)
print("Waiting for action...")
self.current_state = STATES["WAIT_ACTION"]
elif self.current_state == STATES["WAIT_ACTION"]:
self.plc_action_data = self.plc.db_read(1, 0, 5)
if self.plc_action_data[4] == 0b00000001:
self.current_state = STATES["OK_ROUTINE"]
elif self.plc_action_data[4] == 0b00000010:
self.current_state = STATES["SCRAP_ROUTINE"]
elif self.current_state == STATES["OK_ROUTINE"]:
print("OK routine")
self.execute_ok_routine()
self.current_state = STATES["IDLE"]
elif self.current_state == STATES["SCRAP_ROUTINE"]:
print("Scrap routine")
self.execute_scrap_routine()
self.current_state = STATES["IDLE"]
elif self.current_state == STATES["SHUTDOWN"]:
#self.handle_shutdown()
break
time.sleep(0.1)
except KeyboardInterrupt:
#self.handle_shutdown()
self.arm.disconnect()
break
if __name__ == "__main__":
try:
SnapArm()
except Exception as e:
print(e)
sys.exit(1)
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
.B{ border:1px solid black; }
button{ width: 45%; }
.showDiv{ width: 45%; border: 1px groove black;
position: fixed; right: 1px; }
</style>
<script type="text/javascript">
//window.alert("Basics");
//(function () { alert("Basics") }());
//var c = (function () { alert("Basics"); }); c();
// ver obj = { fun : function(){..} , .. }; obj.fun();
//var d = () => { alert("Basics"); }; d();
// x/=y ~ x=(x/y) || x%=y ~ x=(x%y)
// === equal value and type
// !== not equal value and not type
// >>, <<, >>>,~(NOT),^(XOR), 5|6(OR), ~5(NOT), 5^6(AND)
//_______________Strings_______________________________
// String.length; \' \" \\ \b \r \f \t \v
// String.indexOf("Th"); String.search("Th");
// slice(start,end); | substring(start,end); | substr(start,end); (start); ~ (start -> end of string)
// str.search(/w3schools/i); => search ignores capsLock || str.replace("a","aa");
// String.replace("AA","aa"); .toUpperCase(); .toLowerCase(); .concar(" ",stringObj);
// string.charAt(5); returns 'C' || string[0] || String.split(","); return array
// str.charAt(0); , str.charCodeAt(0); in Ascii, str.includes("world"); boolean , str.slice(0); slice(start,end)
// str.split(" "); returns array of words
// typeOf NaN || parseInt() || parseFloat()
// Math.PI; Math.round(4.77); returns 5 || Math.pow(8,2); 8^2
// Math.sqrt(64); || Math.abs(-4.7); +4.7 || Math.sin(90*Math.PI);
// Math.ceil(4.4); return 5 || Math.floor(4.7); return 4 || Math.cos(..)
// Math.min(0,5,1,3); return 0; , Math.max(5,7); return 7;
// Math.random(); || .atan2(x) || .atan(x) || .acos(x) || .abs(x) || .tan(x)
//_________________Date_________________
// Date.parse("March 21, 2012"); new Date("2005-03-22 00:00:00");
// var d = new Date(2011,10,30);
// var date_ = new Date(y,m,d,11,30,4); 11:30:04
// || arr instanceof Array
// getDate() {1-31}, getDay() {0-6} , getFullYear() {year} , getHours() {0-23} , getMonth() {0-11}
// new Date(year, month, day, hours, minutes, seconds, milliseconds)
// ArrayAll.concat(arrayA,arrayB); <= add the 2 arrays , array.slice(1); remove fist elm || .slice(1,3); remove 1 to 3 first elements
// switch(x){ case n:....break; default:.... }
// install things on FOR announcment for (i = 0, text = ""; i < len; i++)
// short cut (; i < len; ) , i=0 || i++|| for (x in person){ person[x] }
// [abc] , [0-9] , (x|y) , \d (digit), /e/.exec(string); returns e's if exist
// /e/.test(string); returns true if e is there
// try { throw "5" } catch(err){ innerHTML = err; } ...
// EvalError , RangeError , ReferenceError , SyntaxError , TypeError , URIError
// err.name ^ || typeOf undefined || typeOf null
// function(){ return; } => returns undefined
// null IS FOR objects, undefined IS FOR virables
// var elm = document.createElement("script").src="..."; document.body.appendChild(elm);
// hasOwnProperty isPrototypeOf name isFinite isNaN prototype <= for Objects
// DOM : ____________________________________________________________
// document.removeChild(element) || document.replaceChild(element)
// document.anchors , returns all <a> .applets returns <applet>
// .baseURI , .body <body> , .cookie , .documentElement return <html>
// .forms <form> , var x = document.forms["frm1"]; .head
// .images <img> document.images.length; , .scripts return <scrips>
// .URL returns url || buttonOBJ.className;
// var x = document.querySelectorAll("p.intro"); returns all innerHTML in <P>
// .addEventListener("click", functionAA); , .tagName();
// window.addEventListener("resize", function(){....});
// NODES : ___________________________________________________________
// parentNode , childNodes[2] , firstChild , lastChild , nextSibling ,previousSibling
// .nodeName , .getElementById("id01").nodeName
// element.appendChild(para); .removeChild(child); .parentNode.removeChild(child);
// .className , .parentNode.tagName // < virables not functions
// ____________________________________________________________
// setInterval(function, miliseconds); setTimeout(function,miliseconds);
// clearInterval(theIntervalObj); clearTimeout(timeOutOBJ)
// AJAX
// variable = new XMLHttpRequest(); OR new ActiveXObject("Microsoft.XMLHTTP");
// readyState {0 not, 1 connected, 2 sent, 3 processing, 4 finished & back }
// xhttp.open("GET", "ajax_info.txt", true);
// xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// GET more simple, POST saves more info can be controlled better
// XMLrequest.responseText , responseXML, statusText
// XMLrequest.onreadystatechange = function;
// xhttp.send();
// document.querySelector(".example").style.backgroundColor = "red"; // all queries that has "example" in it
var showBox = function () {
return document.getElementsByClassName("showDiv")[0];
} // callBack because HTML hasn't loaded the div below yet
function date() {
showBox().innerHTML = Date();
} // in Date.getDay,getHours,getMinutes
function debug() {
console.log("Calling debugger");
debugger;
}
function typeOF() {
var s = typeof document.createElement("div");
var f = typeof function () { };
showBox().innerHTML = f + " , " + s + " , " + typeof "STRING!";
}
function nativeCode() {
showBox().innerHTML = "StringY".constructor;
}
function Converterr() {
showBox().innerHTML = "Number(false);=" + Number(false) +
"<br>Boolean(1);=" + Boolean(5) + " anything except 0 is true";
}
function infinityy() {
var inf = Infinity;
showBox().innerHTML = "(infinity > 112233)=?" + (inf > 112233);
}
//function ExponentiationN() {
// showBox().innerHTML = (10**2);
// }
function pureJSON(){
var json = {a:"bb",b:50};
showBox().innerHTML = json.a + " json.b+5=" + (json.b + 5) +
"<br> json[\"b\"] = 555; + 5 = " + (json["b"]+5);
}
function differnceInDays() {
var date1 = new Date("7/13/2011");
var date2 = new Date("12/15/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
showBox().innerHTML = "days between 7/13/2011 and 12/15/2010 = " + diffDays;
}
function changeTEXT(sender,text){ sender.innerHTML = text; }
function NotANumber(){
var x = "dsfsd";
if( parseInt(x) == NaN ){ alert("GGG"); }
alert('x = "dsfsd" ' + isNaN(x));
}
function addTwoZeros(){
var x = 2.332; alert(x.toExponential(2));
}
function LargestNumInJS(){ alert(Number.MAX_VALUE); }
function DateInUTC(sender){
var date = new Date();
showBox().innerHTML = date.getUTCDate() + " , " + new Date(date.getUTCDate()) +
" , " + new Date("2005-03-22") + " , " + new Date().getFullYear();
myDaysEnum();
}
function myDaysEnum(){
var days = ["Sun","Mon","Tu","Wed","Thu","Fri","Sat"];
alert(days[new Date().getDay()]);
}
function sortARRAY(){
var arr = ["KK","Ba","cc"];
arr.sort();
alert(arr);
arr.push("aBB");
alert("After push aBB, "+arr+" sort: "+arr.sort() + "isArray(..)?="
+ isAnArray(arr)) + " or " + arr instanceof Array;
alert("pop the last element : arr.pop() = "+arr.pop());
arr.shift();
alert("shift ~ remove the first elm : "+arr);
arr.unshift("back!"); alert("restore it ~ unshift : "+arr);
arr.reverse(); alert("sort in reverse : "+arr);
}
function isAnArray(x){
return (x.constructor.toString().indexOf("Array") > -1);
}
function ifMethodShortCut(){
// var newIF = (55 > 22) ? "55 is bigger than 22";
// alert(newIF);
}
function FORshortCut(){
var text = "d"; var arr = ["Ac","Bv"];
list: { text += arr[0]; break list; text += arr[1]; }
alert(text);
}
function appendDIV(){
var div = document.createElement("div");
div.innerHTML = "<p>Append after load page, helps DOM load faster</p>";
document.body.appendChild(div);
}
function infoOnButton(sender){
// alert(sender.has)
}
function funcASaObject(first){
function Person(first) {
this.firstName = first;
}
Person.prototype.nationality = "English";
var CC = new Person("BB");
alert(CC.nationality);
}
function ArgsLength(a,b){
// alert(arguments.length);
}
function getElements(){
var elemes = document.getElementsByTagName("button");
// getElementsByClassName("B");
alert("There are " + elemes.length + " buttons ALL WILL BE GREEN");
for(var i=0; i<elemes.length;i++){
if(elemes[i].className == "B"){
if( elemes[i].parentNode.tagName == "DIV" )
elemes[i].style.backgroundColor = "green";
}
}
}
function enableCookies(sender){
navigator.cookieEnabled = (!navigator.cookieEnabled);
sender.innerHTML = "Cookies status : " + navigator.cookieEnabled;
}
function upperCase(){
document.getElementById("ttt").value = document.getElementById("ttt").value.toUpperCase();
}
function ScreenHW(){
alert("width : "+screen.width+" available width "+screen.availWidth+
"height : "+screen.height+"available height"+screen.availHeight+
"screen.colorDepth"+screen.colorDepth);
}
function windowsLocation(sender){
sender.innerHTML = "hostname : " + window.location.hostname +"<br>" +
"pathname : " + window.location.pathname + "<br>" +
"protocol : " + window.location.protocol + "<br>" +
"history.back " + window.history.back() + "<br>" +
"history.forward " + window.history.forward();
}
function makeCookie(expirationDays){
var date = new Date();
date.setTime(date.getTime() + (expirationDays*24*60*60*1000));
document.cookie = "username=SSSS; "+
" expires="+ date.toUTCString()+";"+
"path=/";
}
function loadCookie(sender){
var user = getCookie("username");
if(user != ""){
sender.innerHTML = "Welcome again "+user;
}
}
function StringThings(sender){
var str = "FOOOOO";
var r = "555";
for(var i=0; i <str.length; i++){
sender.innerHTML += str[i] + " , "+(44+parseInt(r));
}
}
function DateMy(sender) { //month, day, hours , values start from 0, put -1
var d = new Date(2004,03,18,15,00,00,00);
sender.innerHTML = d.toDateString();
}
function define_library() {
var Library = {};
var name = "Timmy";
Library.greet = function () {
alert("Hello from the " + name + " library.");
}
return Library;
}
if (typeof (Library) === 'undefined') {
window.Library = define_library();
}
// window.Library.greet();
function compareStringsCase(string1, string2, sender) {
var s = "not sensitive " + (string1.toUpperCase() == string2.toUpperCase()).toString();
var m = " sensitive " + (string1 == string2).toString();
sender.innerHTML += s + " " + m;
}
function stacks(sender) {
var stack = new Array();
stack.push("A");
sender.innerHTML += "is it empty? " + stack.length;
sender.innerHTML += " after : pop: " + stack.pop() + " length: " + stack.length;
}
function test(sender) {
sender.innerHTML = Math.max(5, 10);
}
function returnFunction(i) {
switch (i) {
case 1:
return function () { alert('ONE!'); }; break;
case 2:
return function () { alert('TWO'); }; break;
default:
return function () { alert('what?'); }; break;
}
}
function getFunctions() {
//var method = returnFunction(2);
//method();
returnFunction(2)();
}
// method 1
window.localStorage.setItem('someStoredItem', 'data from window.localStorage.setItem');
function storageF() {
if (typeof (Storage) != "undefined") {
alert(window.localStorage.getItem('someStoredItem'));
window.localStorage.removeItem('someStoredItem');
} else {
alert("browser doesn't support LocalStorage");
}
}
// Types
function showMeTypes(sender) {
sender.innerHTML = 'typeof("string") = ' + typeof ("string") + "<br>" +
'typeof(10) = ' + typeof (10) + "<br>" +
'typeof(10.003) = ' + typeof (10.003) + "<br>" +
'typeof([1,5,88]) = ' + typeof ([1, 5, 88]) + "<br>" +
'typeof(NaN) = ' + typeof (NaN) + "<br>" +
'typeof({name:"bon",age:55}) = ' + typeof ({ name: "bon", age: 55 }) + "<br>" +
'typeof(null) = ' + typeof (null) + "<br>" +
'typeof(function(){}) = ' + typeof (function () { }) + "<br>" +
'typeof(lalalala) = ' + typeof (lalalala) + "<br>" +
'typeof(undefined) = ' + typeof (undefined) + "<br>" +
'typeof(new Date()) = ' + typeof (new Date());
}
function getKEYS(sender) {
var objj = { key1: "value1", key2: "value2" };
var keys = Object.keys(objj);
sender.innerHTML = '{ key1: "value1", key2: "value2" } keys: <br>';
for (var i = 0; i < keys.length; i++) {
sender.innerHTML += keys[i] + ' , ';
}
}
function SameClass() {
var d = new Date();
var e = new Date();
showBox().innerHTML = 'new Date().constructor === new Date().constructor?' +
'<br>' + (d.constructor === e.constructor) + '<br>' +
'new Array().constructor === new Date().constructor?' +
'<br>' + (new String().constructor === e.constructor);
}
function BooleanStringToNumber() {
showBox().innerHTML = 'Number("3.14")+Number("dd")=' +
(Number("3.14") + Number("dd")) + '<br>' +
'Number("3")+Number("555")=' + '<br>' +
(Number(3) + Number(555)) + '<br>' +
'3+true=' + (3 + true) + '<br>' +
'3+Number(true)=' + (3 + Number(true));
}
function tryCatch() {
try{
showBox().innerHTML = "throw('something!!');";
throw "something";
} catch (err) {
showBox().innerHTML += "catch(err){ err = " + err;
}
}
//_________RegExp | Regular Expression__________//
// used for search patterns, text search, text replacement
// search() returns -1 if not found , replace()
// /pattern/modifiers =>
// var patt = /aa/i; aa = pattern, i = case insensitive
// g = returns ARRAY with all the matches
// m = multiple matching
// [abc] = a,b,c , [a-c] = a,b,c ,[0-9] ,(x|y) = x or y, {x} #x characters
// \d = find digit , \s = white space , \b|\e = not the beginning or end
// \uxxxx = unicode hexadecimal number of xxxx digits
// n+ (atleast one) , n* (0 to infinity), n? (0 or 1)
// text(..) true false , match(..),exec(..) string or null
// /../ ~ new RegExp(...)
// . any char , \. actual dot , .? any char 1 or 0 times
// .* any char any times, .+ any char once or more
function RegExpExample() {
var obj = "lalala3lado";
showBox().innerHTML = 'var obj = "lalala3lado"; <br> ' +
'var n = obj.search(/a3/i); = ' + obj.search(/a3/i) + '<br>' +
'obj[n] = ' + obj[obj.search(/a3/i)] + '<br>' +
'case sensitive: obj.search("a3") = ' + obj.search("a3") + '<br>' +
'obj.search("A3") = ' + obj.search("A3") + '<br>' +
'REPLACE___________: <br>' +
'obj = ' + obj + ' obj.replace(/la3/i, "roror") <br> ' +
'obj = ' + obj.replace(/la3/i, "roror") + '<br>' +
'obj.replace(/UUU/i, "r") = ' + obj.replace(/UUU/i, "r") + '<br>' +
'TEST__________:(true false)<br>' +
'/a/.test("bbbab") = ' + /a/.test("bbbab") + '<br>' +
'exec(...)__________:<br>' +
'/er/.exec("Dser") = ' + /er/.exec("Dser") + '<br>' +
'/AA/.exec("Dser") = ' + /AA/.exec("Dser") + '<br>' +
'/[a-z]/.exec("gag") = ' + /[a-z]/.exec("gag");
}
function RegExpExpressions() {
showBox().innerHTML = 'get numbers "0ga1s7".match(/\\d+/g) = [' +
"0g55a1s7".match(/\d+/g).toString() + ']<br>' +
'get space " d f ".match(/\s/g) = ' +
" d f ".match(/\s/g).toString() + '<br>middle of word : "deed".match(/\\b/g) = ' + "deed".match(/\e/g).toString() +
'<br> "food".match(/[a-z]{3}/) = ' +
"food".match(/[a-z]{3}/).toString() + '<br>' +
'"food".match(/[a-z]?/) = ' + "food".match(/[a-z]?/).toString() +
'<br>"food".match(/[a-z]*/) = ' + "food".match(/[a-z]*/).toString();
}
function getRequest(requestName) {
var encodedRequest = encodeURIComponent(requestName);
var encodedExp = '[?&]' + encodedRequest +'=([^&]*)';
showBox().innerHTML = 'encoded : ' + encodedRequest + '<br>' +
'encoded expression : <br>' + encodedExp +
'<br> found : <br>';
var AddressArray = new RegExp(encodedExp).exec(location.search);
if (AddressArray != null) {
showBox().innerHTML += AddressArray[i] + ',';
}
}
function myCompare(dateA, dateB) {
var a = daysDiff(dateA.date);
var b = daysDiff(dateB.date);
return a - b;
}
function sort(sortByFunction, array) {
for (var i = 0; i < array.length; i++) {
for (var j = (i + 1) ; j < array.length; j++) {
if (sortByFunction(array[i], array[j]) > 0) {
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
// POINTERS
// pointers don't exists, must make a global data object
var myData = {};
function ArrayPointers()
{
var mySring = 'Gellloooo!';
showBox().innerHTML = 'Before change : ' + mySring + '<br>' +
'Strings cannot be changed, redefine String.replaceAt(..)<br>';
myData['pointer'] = mySring;
changeWithPointer('pointer');
mySring = myData['pointer'];
showBox().innerHTML += 'After change : ' + mySring;
}
function changeWithPointer(pointer) {
myData[pointer] = myData[pointer].repaceAt(2, 'T');
}
String.prototype.repaceAt = function (i, char) {
return this.substr(0, i) + char + this.substr(i + char);
}
</script>
</head>
<body>
<div id="shw" class="showDiv"> info box </div>
<button onclick="date(this)">Date();</button><br />
<script> document.write("document.write..."); </script><br />
<button onclick="debug()">Debug</button><br />
<button onclick="typeOF()">type of this</button><br />
<button onclick="nativeCode(this)">Native code of String</button><br />
<button onclick="Converterr(this)">Conver bool to number</button><br />
<button onclick="ExponentiationN(this)">10 ** 2=? similar to 10^2</button><br />
<button onclick="pureJSON(this)">json = {a:"bb",b:50}</button><br />
<button id="effectt" onmouseover="changeTEXT(this,'Changed')"
onmouseout="changeTEXT(this,'Effect Button')">Effect Button</button><br />
<button onclick="NotANumber()">Not a Number</button><br />
<button onclick="addTwoZeros()">Add 2 zeros to 2.332</button><br />
<button onclick="LargestNumInJS()">Largest Number in JS</button><br />
<button onclick="changeTEXT(this,Math.floor(Math.random()*10))">Random num 0~10 (not 10)</button><br />
<button onclick="DateInUTC(this)">Date in UTC</button><br />
<button onclick="sortARRAY()">SORT array.sort and Push(elm)</button><br />
<button onclick="ifMethodShortCut()">IF short cut</button><br />
<button onclick="FORshortCut()">list : { ... break .... }</button><br />
<!-- Using strict JS : <script> "use strict"; x=3.14; delete x; </script><br /> -->
<button onclick="appendDIV()" class="B">appeand div to DOM <br> (Document Object Model) {html-head-title-body...}</button><br />
<div>
<button onclick="funcASaObject('FFF')" class="B">function as an Object</button><br />
<button onclick="ArgsLength('A','bb')" class="B">Arguments length</button><br />
<button onclick="getElements()" class="B">getElementsByTag</button><br />
</div>
<button onclick="enableCookies(this)">navigator.cookieEnabled</button><br />
<input type="text" onchange="upperCase()" id="ttt" /><br />
<button onclick="changeTEXT(this,document.documentElement.innerHTML)">document.documentElement.innerHTML = this html page</button><br />
<button onclick="ScreenHW()">screen.availHeight || screen.Height || colorDepth</button><br />
<button onclick="windowsLocation(this)">window.location || windows.history.back</button><br />
<button onclick="changeTEXT(this,navigator.appName)">navigator.appName</button><br />
<button onclick="window.confirm('Confirmation!!')">windows.confirm return true/false</button><br />
<button onclick="window.prompt('sometext','defaultText')">window.prompt(string,string) returns object</button><br />
<button onclick="makeCookie(2)">set cookie!</button><br />
<button onclick="loadCookie(this)">load cookie!</button><br />
<button onclick="StringThings(this)">StringArray</button><br />
<button onclick="DateMy(this)">GET DATE</button><br />
<button onclick="compareStringsCase('TTGG','TTgg',this)">compare TTgg to TTGG</button><br />
<button onclick="stacks(this)">stacks</button><br />
<button onclick="test(this)">TEST</button><br />
<button onclick="getFunctions()">function that returns functions</button><br />
<button onclick="storageF(this)">local storage</button><br />
<button onclick="showMeTypes(this)"> TYPES!! typeof</button><br />
<button onclick="getKEYS(this)">two of the same class</button><br />
<button onclick="SameClass(this)">same class? use === </button><br />
<button onclick="BooleanStringToNumber(this)">Convert Boolean/String to Number</button><br />
<button onclick="tryCatch()">costume throw</button><br />
<button onclick="RegExpExample()">Regular Expression</button><br />
<button onclick="RegExpExpressions()">^ Expressions, match()</button><br />
<button onclick="getRequest('my request')">
search in RegEXP in loacation.search<br />
for ?ttt=... getRequest('my request')
</button><br />
<button onclick="differnceInDays()">Difference in Days between 2 dates</button><br />
<button onclick="ArrayPointers()">Pointers!!! <br />
+ Redefine Replace Character at Strings <br />
+ Substr, adding to prototype functions</button><br />
<button onclick=""></button><br />
<button onclick=""></button><br />
<button onclick=""></button><br />
<button onclick=""></button><br />
<button onclick=""></button><br />
<button onclick=""></button><br />
</body>
</html>
|
import * as React from 'react';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import InputLabel from '@mui/material/InputLabel';
import DialogTitle from '@mui/material/DialogTitle';
import axios from 'axios';
const AddComment = ({ postId }) => {
const [open, setOpen] = React.useState(false);
const [titleValue, setTitleValue] = React.useState('');
const [textValue, setTextValue] = React.useState('');
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const handleSubmit = () => {
setOpen(false);
const data = {
cookie: document.cookie,
postId: postId,
commentTitle: titleValue,
commentText: textValue,
};
const url = "http://localhost:5000/Comment";
axios.post(url, data)
.then((res) => {
console.log("Comment added successfuly.");
window.location.replace(`/post/${postId}`);
})
.catch((error) => {
// Handle error
console.error("Error fetching comments:", error);
});
};
const handleTitleChange = (event) => {
setTitleValue(event.target.value);
};
const handleTextChange = (event) => {
setTextValue(event.target.value);
};
return (
<div>
<Button variant="outlined" onClick={handleClickOpen}>
Add Comment
</Button>
<Dialog open={open} onClose={handleClose}>
<DialogTitle>Comment</DialogTitle>
<DialogContent>
<InputLabel htmlFor="title">Title</InputLabel>
<TextField
autoFocus
margin="dense"
id="title"
type="text"
fullWidth
variant="standard"
value={titleValue}
onChange={handleTitleChange}
/>
<InputLabel htmlFor="content">Content</InputLabel>
<TextField
autoFocus
multiline
margin="dense"
id="content"
type="text"
fullWidth
variant="standard"
minRows={6}
value={textValue}
onChange={handleTextChange}
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button onClick={handleSubmit}>Comment</Button>
</DialogActions>
</Dialog>
</div>
);
}
export default AddComment;
|
// Inorder Traversal of a Binary Tree
// 1,2,4,-1,-1,5,-1,-1,3,-1,6,-1,-1
// 4, 2, 5, 1, 3, 6
public class J18_InorderTraversal {
static class Node{
int data;
Node left;
Node right;
Node(int data){
this.data=data;
this.left=null;
this.right=null;
}
}
static class BinaryTree{
static int idx=-1;
public static Node buildTree(int nodes[]){
idx++;
if(nodes[idx]==-1)
return null;
Node newNode = new Node(nodes[idx]);
newNode.left = buildTree(nodes);
newNode.right = buildTree(nodes);
return newNode;
}
public static void inOrder(Node root){ // function to print inorder traversal of a binary tree
if(root==null)
return;
inOrder(root.left);
System.out.print(root.data+" ");
inOrder(root.right);
}
}
public static void main(String[] arg){
int nodes[] = {1,2,4,-1,-1,5,-1,-1,3,-1,6,-1,-1};
BinaryTree tree = new BinaryTree();
Node root = tree.buildTree(nodes);
tree.inOrder(root);
}
}
|
import { DataType } from 'sequelize-typescript';
import { setupSequelize } from '#seedwork/infra/testing/helpers/db';
import { UserSequelize } from '../user-sequelize';
const { UserModel } = UserSequelize;
describe('UserModel Integration Tests', () => {
setupSequelize({models: [UserModel]});
test('mapping props to columns', async () => {
const attributesMap = UserModel.getAttributes();
const attributes = Object.keys(attributesMap);
expect(attributes.length).toBe(6);
expect(attributes).toStrictEqual([
'id',
'name',
'email',
'password',
'is_active',
'created_at',
]);
const idAttr = attributesMap.id;
expect(idAttr).toMatchObject({
field: 'id',
fieldName: 'id',
primaryKey: true,
type: DataType.UUID(),
});
const nameAttr = attributesMap.name;
expect(nameAttr).toMatchObject({
field: 'name',
fieldName: 'name',
allowNull: false,
type: DataType.STRING(255),
});
const emailAttr = attributesMap.email;
expect(emailAttr).toMatchObject({
field: 'email',
fieldName: 'email',
allowNull: false,
type: DataType.STRING(255),
});
const passwordAttr = attributesMap.password;
expect(passwordAttr).toMatchObject({
field: 'password',
fieldName: 'password',
allowNull: false,
type: DataType.STRING(),
});
const isActiveAttr = attributesMap.is_active;
expect(isActiveAttr).toMatchObject({
field: 'is_active',
fieldName: 'is_active',
allowNull: false,
type: DataType.BOOLEAN(),
});
const createdAtAttr = attributesMap.created_at;
expect(createdAtAttr).toMatchObject({
field: 'created_at',
fieldName: 'created_at',
allowNull: false,
type: DataType.DATE(),
});
});
it('should create a user', async () => {
const arrange = {
id: '667b9345-0bcc-41bd-970d-0df043578a1c',
name: 'Toto',
email: 'email@mail.com',
password: 'Some password1',
is_active: true,
created_at: new Date()
}
const user = await UserModel.create(arrange);
expect(user).toBeDefined();
expect(user.toJSON()).toStrictEqual(arrange);
});
it('search user', async () => {
await UserModel.factory().create();
});
});
|
= STAT 39000: Project 10 -- Fall 2020
**Motivation:** Although SQL syntax may still feel unnatural and foreign, with more practice it _will_ start to make more sense. The ability to read and write SQL queries is a bread-and-butter skill for anyone working with data.
**Context:** We are in the second of a series of projects that focus on learning the basics of SQL. In this project, we will continue to harden our understanding of SQL syntax, and introduce common SQL functions like `AVG`, `MIN`, and `MAX`.
**Scope:** SQL, sqlite
.Learning objectives
****
- Explain the advantages and disadvantages of using a database over a tool like a spreadsheet.
- Describe basic database concepts like: rdbms, tables, indexes, fields, query, clause.
- Basic clauses: select, order by, limit, desc, asc, count, where, from, etc.
- Utilize SQL functions like min, max, avg, sum, and count to solve data-driven problems.
****
== Dataset
The following questions will use the dataset similar to the one from Project 9, but this time we will use a MariaDB version of the database, which is also hosted on Scholar, at `scholar-db.rcac.purdue.edu`.
As in Project 9, this is the Lahman Baseball Database. You can find its documentation http://www.seanlahman.com/files/database/readme2017.txt[here], including the definitions of the tables and columns.
== Questions
[IMPORTANT]
====
Please make sure to **double check** that the your submission does indeed contain the files you think it does. You can do this by downloading your submission from Gradescope after uploading. If you can see all of your files and they open up properly on your computer, you should be good to go.
====
[IMPORTANT]
====
Please make sure to look at your knit PDF *before* submitting. PDFs should be relatively short and not contain huge amounts of printed data. Remember you can use functions like `head` to print a sample of the data or output. Extremely large PDFs will be subject to lose points.
====
[IMPORTANT]
====
For this project all solutions should be done using R code chunks, and the `RMariaDB` package. Run the following code to load the library:
[source,r]
----
library(RMariaDB)
----
====
=== Question 1
Connect to RStudio Server https://rstudio.scholar.rcac.purdue.edu, and, rather than navigating to the terminal like we did in the previous project, instead, create a connection to our MariaDB lahman database using the `RMariaDB` package in R, and the credentials below. Confirm the connection by running the following code chunk:
[source,r]
----
con <- dbConnect(RMariaDB::MariaDB(),
host="scholar-db.rcac.purdue.edu",
db="lahmandb",
user="lahman_user",
password="HitAH0merun")
head(dbGetQuery(con, "SHOW tables;"))
----
[TIP]
====
In the example provided, the variable `con` from the `dbConnect` function is the connection. Each query that you make, using the `dbGetQuery`, needs to use this connection `con`. You can change the name `con` if you want to (it is user defined), but if you change the name `con`, you need to change it on all of your connections. If your connection to the database dies while you are working on the project, you can always re-run the `dbConnect` line again, to reset your connection to the database.
====
.Items to submit
====
- R code used to solve the problem.
- Output from running your (potentially modified) `head(dbGetQuery(con, "SHOW tables;"))`.
====
=== Question 2
How many players are members of the 40/40 club? These are players that have stolen at least 40 bases (`SB`) and hit at least 40 home runs (`HR`) in one year.
[TIP]
====
Use the `batting` table.
====
[IMPORTANT]
====
You only need to run `library(RMariaDB)` and the `dbConnect` portion of the code a single time towards the top of your project. After that, you can simply reuse your connection `con` to run queries.
====
[IMPORTANT]
====
In our xref:templates.adoc[project template], for this project, make all of the SQL queries using the `dbGetQuery` function, which returns the results directly in `R`. Therefore, your `RMarkdown` blocks for this project should all be `{r}` blocks (as opposed to the `{sql}` blocks used in Project 9).
====
[TIP]
====
You can use `dbGetQuery` to run your queries from within R. Example:
[source,r]
----
dbGetQuery(con, "SELECT * FROM battings LIMIT 5;")
----
====
[NOTE]
====
We already demonstrated the correct SQL query to use for the 40/40 club in the video below, but now we want you to use `RMariaDB` to solve this query.
====
++++
<iframe class="video" src="https://cdnapisec.kaltura.com/p/983291/sp/98329100/embedIframeJs/uiconf_id/29134031/partner_id/983291?iframeembed=true&playerId=kaltura_player&entry_id=1_os59oucz&flashvars[streamerType]=auto&flashvars[localizationCode]=en&flashvars[leadWithHTML5]=true&flashvars[sideBarContainer.plugin]=true&flashvars[sideBarContainer.position]=left&flashvars[sideBarContainer.clickToClose]=true&flashvars[chapters.plugin]=true&flashvars[chapters.layout]=vertical&flashvars[chapters.thumbnailRotator]=false&flashvars[streamSelector.plugin]=true&flashvars[EmbedPlayer.SpinnerTarget]=videoHolder&flashvars[dualScreen.plugin]=true&flashvars[Kaltura.addCrossoriginToIframe]=true&&wid=1_gy4f8y6j"></iframe>
++++
.Items to submit
====
- R code used to solve the problem.
- The result of running the R code.
====
=== Question 3
How many times in total has Giancarlo Stanton struck out in years in which he played for "MIA" or "FLO"?
++++
<iframe class="video" src="https://cdnapisec.kaltura.com/p/983291/sp/98329100/embedIframeJs/uiconf_id/29134031/partner_id/983291?iframeembed=true&playerId=kaltura_player&entry_id=1_whzcdsrc&flashvars[streamerType]=auto&flashvars[localizationCode]=en&flashvars[leadWithHTML5]=true&flashvars[sideBarContainer.plugin]=true&flashvars[sideBarContainer.position]=left&flashvars[sideBarContainer.clickToClose]=true&flashvars[chapters.plugin]=true&flashvars[chapters.layout]=vertical&flashvars[chapters.thumbnailRotator]=false&flashvars[streamSelector.plugin]=true&flashvars[EmbedPlayer.SpinnerTarget]=videoHolder&flashvars[dualScreen.plugin]=true&flashvars[Kaltura.addCrossoriginToIframe]=true&&wid=1_ruufmsf4"></iframe>
++++
[IMPORTANT]
====
Questions in this project need to be solved using SQL when possible. You will not receive credit for a question if you use `sum` in R rather than `SUM` in SQL.
====
[TIP]
====
Use the `people` table to find the `playerID` and use the `batting` table to find the statistics.
====
.Items to submit
====
- R code used to solve the problem.
- The result of running the R code.
====
=== Question 4
The https://en.wikipedia.org/wiki/Batting_average_(baseball)[Batting Average] is a metric for a batter's performance. The Batting Average in a year is calculated by stem:[\frac{H}{AB}] (the number of hits divided by at-bats). Considering (only) the years between 2000 and 2010, calculate the (seasonal) Batting Average for each batter who had more than 300 at-bats in a season. List the top 5 batting averages next to `playerID`, `teamID`, and `yearID.`
[TIP]
====
Use the `batting` table.
====
.Items to submit
====
- R code used to solve the problem.
- The result of running the R code.
====
=== Question 5
How many unique players have hit > 50 home runs (`HR`) in a season?
[TIP]
====
If you view `DISTINCT` as being paired with `SELECT`, instead, think of it as being paired with one of the fields you are selecting.
====
.Items to submit
====
- R code used to solve the problem.
- The result of running the R code.
====
=== Question 6
Find the number of unique players that attended Purdue University. Start by finding the `schoolID` for Purdue and then find the number of players who played there. Do the same for IU. Who had more? Purdue or IU? Use the information you have in the database, and the power of R to create a misleading graphic that makes Purdue look better than IU, even if just at first glance. Make sure you label the graphic.
[TIP]
====
Use the `schools` table to get all `schoolID` and the `collegeplaying` table to get the statistics.
====
[TIP]
====
You can mess with the scale of the y-axis. You could (potentially) filter the data to start from a certain year or be between two dates.
====
[TIP]
====
To find IU's id, try the following query: `SELECT schoolID FROM schools WHERE name_full LIKE '%indiana%';`. You can find more about the LIKE clause and `%` https://www.tutorialspoint.com/sql/sql-like-clause.htm[here].
====
.Items to submit
====
- R code used to solve the problem.
- The result of running the R code.
====
=== Question 7
Use R, SQL and the lahman database to create an interesting infographic. For those of you who are not baseball fans, try doing a Google image search for "baseball plots" for inspiration. Make sure the plot is polished, has appropriate labels, color, etc.
.Items to submit
====
- R code used to solve the problem.
- The result of running the R code.
====
|
<template>
<div class="app-container">
<div class="home-top">
<basics-title
title="白名单"
:actions="[{
type: 'button', // 按钮
label: '手动导入',
click: addBlack,
attr: {
type: 'primary',
plain: true,
size: 'mini',
icon: 'el-icon-plus'
}
}]"
/>
<el-tabs v-model="type">
<el-tab-pane v-for="item in typeList" :key="item.key" :label="item.label" :name="item.value">
<span slot="label">
{{ item.label }}
</span>
</el-tab-pane>
</el-tabs>
</div>
<div class="home-content">
<basics-search
ref="searchs"
:loading="loadings._ums_api_ig_v1_whitelists"
:searchs="searchs"
@submitSearch="submitSearch"
/>
<basics-table
ref="table"
:table="table"
:loading="loadings._ums_api_ig_v1_whitelists"
:list="list"
:get-list="getList"
:columns="columns"
:total="total"
:list-query="listQuery"
:action-function="actionFunction"
>
<template slot="disturbMobile" slot-scope="scope">
<div>
{{ (disturbMobileObj && scope.row.id === disturbMobileObj.id) ? scope.row.mobile : scope.row.mobile.replace(/([0-9]{3})([0-9]{5})([0-9]{3})/, '$1*****$3') }}
<svg-icon
style="cursor: pointer;"
:icon-class="disturbMobileIcone(scope.row.id)"
@click="isDisturbMobile(scope.row)"
/>
</div>
</template>
<template slot="cname" slot-scope="scope">
<div>{{ scope.row.cname }}</div>
<div>{{ scope.row.cmobile }}</div>
</template>
</basics-table>
</div>
<el-dialog
width="650px"
:title="'手动导入'"
:visible.sync="dialog"
>
<basics-form
ref="dialogRef"
:key="dialog"
:forms="forms"
:loading="loadings._ums_api_out_in_platForm_addOrUpdateObBusinessChannel"
class="form-item"
:actions="formActions(cancelForm)"
@submitForm="onFormSubmit"
@changeForm="changeNewForm"
/>
</el-dialog>
<el-dialog
title=""
:visible.sync="enableVisible"
width="650px"
>
<span slot="title" style="font-size: 20px"> <i style="color: rgb(255,163,45)" class="el-icon-warning" /> 是否确定解除 </span>
<span style="font-size: 16px; padding-left: 25px"> 解除后将不再进行勿扰过滤 </span>
<span slot="footer" class="dialog-footer">
<el-button size="small" @click="enableVisible = false">取 消</el-button>
<el-button size="small" type="primary" @click="enable">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
import { searchs } from './search'
import BasicsTitle from '@/components/BasicsTitle'
import BasicsSearch from '@/components/BasicsSearch'
import BasicsForm from '@/components/BasicsForm'
import BasicsTable from '@/components/BasicsTable'
import { mapGetters } from 'vuex'
import { getWhitelists, setWhitelists, deleteWhite } from '@/api/do-not-disturb/list'
import columns, { actions } from './columns'
import forms, { formActions, typeList } from './form'
import moment from 'moment'
const init_pagaination = {
page: 1,
limit: 20
}
export default {
name: 'WhiteList',
components: { BasicsTitle, BasicsSearch, BasicsForm, BasicsTable },
filters: {
timeFormat(e) {
return (e !== '0' && e) ? moment(+e).format('YYYY-MM-DD HH:mm:ss') : '永久'
}
},
data() {
return {
typeList,
type: '0',
forms,
formActions,
dialog: false,
enableVisible: false,
table: {
stripe: false,
border: false
},
columns,
searchs,
total: 0,
list: [],
searchQuery: {},
listQuery: { ...init_pagaination },
actionFunction: actions({
tableAction: this.tableAction
}),
actionObj: null,
disturbMobileObj: null
}
},
watch: {
type(val, oldVal) {
if (val !== oldVal) {
this.$refs.searchs.reset()
this.searchQuery = {};
}
},
},
computed: {
...mapGetters(['loadings']),
disturbMobileIcone() {
return function(e) {
if (e !== this.disturbMobileObj?.id) {
return "eye-open"
} else {
return "eye"
}
}
},
},
mounted() {
this.$nextTick(() => {
this.getList()
})
},
methods: {
isDisturbMobile(e) {
if (e?.id === this.disturbMobileObj?.id) {
this.disturbMobileObj = null
} else {
this.disturbMobileObj = e
}
},
cancelForm() {
this.dialog = !this.dialog
},
// 新增白名单
addBlack() {
this.dialog = true
},
onFormSubmit(values) {
const newData = { ...values }
newData.startTime = (values.daterange?.[0] && values.takeEffectType === '1') ? moment(values.daterange[0]).format("YYYY-MM-DD") : ''
newData.endTime = (values.daterange?.[1] && values.takeEffectType === '1') ? moment(values.daterange[1]).format("YYYY-MM-DD") : ''
newData.mobile = values.mobile?.replace(/\n/g, ',')
setWhitelists(newData).then(res => {
if (res?.code === 0) {
this.initParamsAndGetList()
this.$message({
type: 'success',
message: '新增成功'
})
}
})
this.dialog = false
},
changeNewForm(value, oldval) {
// 是否显示时间选择器
if (value.takeEffectType === '1') {
this.$refs.dialogRef.set({
type: 'noShow',
data: { daterange: false }
})
} else if (value.takeEffectType === '0') {
this.$refs.dialogRef.set({
type: 'noShow',
data: { daterange: true }
})
}
},
// 列表的action按钮时间
tableAction(dat, row, index, type) {
this.actionObj = row
this.$nextTick(() => {
this.enableVisible = true
});
},
// 解除白名单
enable() {
const { actionObj } = this
deleteWhite({ id: actionObj.id }).then(res => {
if (res?.code === 0) {
this.enableVisible = false
this.$message({
type: 'success',
message: '解除成功'
})
this.$nextTick(() => {
this.getList()
})
}
})
},
// 列表初始化
initParamsAndGetList() {
this.listQuery = {
...init_pagaination
}
this.$nextTick(() => {
this.getList()
})
},
// 列表搜索
submitSearch(value) {
const newSearchQuery = { ...this.searchQuery, ...value }
newSearchQuery.startTime = value.daterange?.[0] ? moment(value.daterange[0]).format("YYYY-MM-DD") : ''
newSearchQuery.endTime = value.daterange?.[1] ? moment(value.daterange[1]).format("YYYY-MM-DD") : ''
newSearchQuery.cname = "";
newSearchQuery.cmobile = "";
newSearchQuery[value.userInfoInputSelectProp] = value.userInfoInputSelect;
this.searchQuery = newSearchQuery;
this.initParamsAndGetList()
},
getList() {
const { searchQuery, listQuery, type } = this
const newSearchQuery = {
...searchQuery,
type,
page: listQuery.page,
pageSize: listQuery.limit
}
// 每次获取列表数据重置查看手机号
this.disturbMobileObj = null
getWhitelists(newSearchQuery).then(res => {
if (res?.code === 0) {
const { payload: { list, totalSize, totalPage }} = res
this.list = list
this.total = totalSize
if (totalPage > 1 && list.length === 0) {
this.listQuery = {
...init_pagaination,
page: totalPage - 1
}
this.$nextTick(() => {
this.getList()
})
}
}
})
}
}
}
</script>
<style lang="scss" scoped>
.home-top {
border-radius: 10px;
}
</style>
|
<!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>z-index</title>
<style>
.contenitore{
width: 1024px;
margin: 0 auto;
border:2px solid rgb(0, 0, 0);
position:relative;
height: 800px;
}
.contenitore div{
position: absolute;
width: 150px;
height: 150px;
}
#rosso{
background-color: red;
top:20px;
left: 20px;
z-index: 3;
border-radius: 10px;
text-align: center;
}
#blu{
background-color: blue;
top:40px;
left: 40px;
z-index: 2;
border-radius: 10px;
text-align: center;
}
#verde{
background-color: greenyellow;
top: 60px;
left: 60px;
z-index: 1;
border-radius: 10px;
text-align: center;
}
#viola{
background-color: violet;
top: 80px;
left: 80px;
z-index: 0;
border-radius: 10px;
text-align: center;
}
#viola:hover{
z-index: 4;
transform: scale(1.2);
}
#verde:hover{
z-index: 4;
transform: scale(1.15);
}
#blu:hover{
z-index: 4;
transform: scale(1.1);
}
#rosso:hover{
z-index: 4;
transform: scale(1.05);
}
img{
position: absolute;
left: 0;
top: 0;
z-index: -1;
}
/* auto-> uguale a tutti i parents
numero-> qualsiasi numero intero (positivo o negativo)
initial-> default(0)
inherit->eredita dal genitore
*/
</style>
</head>
<body>
<h2>La proprietà z-index</h2>
<div class="contenitore">
<div id="rosso">ROSSO</div>
<div id="blu">BLUE</div>
<div id="verde">VERDE</div>
<div id="viola">VIOLA</div>
<img src="httpcloud3steamusercontentcomugc166572776348276016248435CCD07BC6AD4039E73E4393D760CC57B6EF7.png" alt="">
</div>
</body>
</html>
|
package entity
import (
"time"
)
type User struct {
ID uint `json:"id" gorm:"primaryKey;type:int4;autoIncrement"`
Username string `json:"username" gorm:"type:varchar"`
Email string `json:"email" gorm:"type:varchar"`
Fullname string `json:"fullname" gorm:"type:varchar"`
Address string `json:"address" gorm:"type:varchar"`
PhoneNumber string `json:"phone_number" gorm:"type:varchar"`
KeycloakID string `json:"keycloak_id" gorm:"type:varchar"`
UserRoleID int `json:"user_role_id" gorm:"type:int4"`
StatusID int `json:"status_id" gorm:"type:int4"`
ProfilePicturePath string `json:"profile_picture_path" gorm:"type:varchar"`
IsActive bool `json:"is_active" gorm:"default:false"`
CreatedAt time.Time `json:"created_at" gorm:"default:now()"`
UpdatedAt time.Time `json:"updated_at" gorm:"default:now()"`
// foreign key
UserRole UserRole `json:"user_role" gorm:"foreignKey:UserRoleID; constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
Status MasterStatus `json:"status" gorm:"foreignKey:StatusID; constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}
|
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
import glob
from sklearn.ensemble import RandomForestClassifier
from pathlib import Path
import scipy.constants as const
import h5py
import glob
import pandas as pd
import joblib
np.seterr(invalid='ignore')
def rebin_spectrum(in_wave, in_flux, out_wave=None, density=True):
"""
Rebin a spectrum with flux conservation (density=True) to the out_wave wavelength array.
Code written by J. Trevor Mendle.
Input
-----
in_wave (NumPy array)
The original wavelength array to be rebinned
in_flux (NumPy array)
The original flux array to be rebined
out_wave (None or Numpy array)
The rebinned wavelength array
density (bool)
Whether to rebin treating flux as density (True) or not (False).
density=True (default) conserves flux density.
Returns
-------
out_wave (NumPy array)
The rebinned flux array.
"""
if out_wave is None:
print("Define a wavelength array to be returned")
edges_in = (in_wave[:-1] + in_wave[1:]) / 2
edges_in = np.r_[in_wave[0] - np.diff(in_wave)[0], np.r_[edges_in, in_wave[-1] + np.diff(in_wave)[-1]]]
edges_out = (out_wave[:-1] + out_wave[1:]) / 2.
edges_out = np.r_[out_wave[0] - np.diff(out_wave)[0], np.r_[edges_out, out_wave[-1] + np.diff(out_wave)[-1]]]
if density:
cumul = np.nancumsum(np.r_[0, np.diff(edges_in) * in_flux])
else:
cumul = np.nancumsum(np.r_[0, in_flux])
cumul_rebinned = np.interp(edges_out, edges_in, cumul)
if density:
return np.diff(cumul_rebinned) / np.diff(edges_out)
else:
return np.diff(cumul_rebinned)
def read_hdf5_spec(filelist):
# Get all files to be used for training
specfiles = []
with open(filelist, 'r') as f:
for line in f:
specfiles.append(line.strip())
specfiles.sort()
fluxdata = []
sightline = []
z_qso_data = []
# Loop over hdf5 files
for hdf5file in specfiles:
print("Working with file: %s"%hdf5file)
# Load file for nsight sightlines
data = h5py.File(hdf5file, 'r')
#QSO info
zems = np.array(data['z_qso'])
#Spectra
wave = np.array(data['wave_weavify'][0])
fluxes = np.array(data['flux_weavify']) #Of shape nsight x npix
#Column densities
Ncat = data['absorbers'] #Group of nsight numpy recarrays
# Loop over each sightline
for ind in range(len(Ncat)):
sight = '%s'%ind
# Get qso properties
zqso = zems[ind]
# Get flux
flux = fluxes[ind, :]
# Drop systems where flux is all -999
flux_check = [flux[i] == -999. for i in range(len(flux))]
if not all(flux_check):
fluxdata.append(list(flux))
sightline.append(ind)
z_qso_data.append(zqso)
specDict = dict(Flux = fluxdata,
wave = list(wave),
orig_wave = data['wave'],
zqso = z_qso_data,
sightline = sightline)
return specDict
def slice_analysis_data(data, wave, slide_idx):
fluxdata = data['Flux']
zqso_data = data['zqso']
wave_constwave = data['wave']
sightline_data = data['sightline']
# Slice spectrum into small regions and add tag for whether there is/isnt an absorber
fluxslices = []
velslices = []
waveslices = []
sightlines = []
for source in range(len(fluxdata)):
if source%100 == 0:
print("Slicing spectrum %s"%source + " out of %s"%len(fluxdata))
# Rebin spectra onto constant velocity
spec_constwave = fluxdata[source]
spec = rebin_spectrum(np.array(wave_constwave), np.array(spec_constwave),
out_wave=wave, density=True)
zqso = zqso_data[source]
wl_qso = 1215.67*(zqso + 1)
# Create slices of the spectra with associated flags
startidx = 0 #initialise first chunk
num_idxs = 100 #size of window
while startidx + num_idxs < len(spec):
wave_slice = wave[startidx:startidx+num_idxs]
flux_slice = spec[startidx:startidx+num_idxs]
startidx += slide_idx # number of indices to shift window by
# Exclude slice if it falls in the Lya forest
if wave_slice[0] < wl_qso:
continue
# Add slice to array of inputs
fluxslices.append(flux_slice)
#velslices.append(vel_slice)
waveslices.append(wave_slice)
sightlines.append(sightline_data[source])
return fluxslices, waveslices, sightlines
########################################################
analysis_list = "analysis_mocks.lst"
analysis_listSpec = read_hdf5_spec(analysis_list)
orig_wave_arr = np.array(analysis_listSpec['orig_wave'])
print("Slicing spectra...")
fluxslices, waveslices, sightlines = slice_analysis_data(analysis_listSpec,orig_wave_arr,25)
print("Loading the model...")
model = joblib.load("model_spec9557_EW0.2_withWeakFlag.joblib")
print("Making predictions...")
# Classify whether test sample are absorber or not
preds = model.predict(fluxslices)
# If you want confidence, return probability of classes
preds_probability = model.predict_proba(fluxslices)
# Create high confidence predictions
prob_cut = 0.3
preds_highConf = np.zeros(len(preds))
strongCIV = [((probs[1]>prob_cut) & (probs[1] == max(probs))) for probs in preds_probability]
strongMgII = [((probs[2]>prob_cut) & (probs[2] == max(probs))) for probs in preds_probability]
strongOther = [((max(probs[3:])>prob_cut) & (max(probs[3:]) == max(probs))) for probs in preds_probability]
preds_highConf[strongCIV] = 1
preds_highConf[strongMgII] = 2
preds_highConf[strongOther] = 3
print("Saving data...")
wave_cen = np.array(waveslices)[:,50]
d = {'wave_cen': wave_cen,
'preds':preds,
'preds_probability': list(preds_probability),
'preds_highConf': list(preds_highConf),
'sightline': list(sightlines)}
df = pd.DataFrame(data=d)
df.to_pickle("mock_samp650_predictions.pkl")
# Save only the predicted CIV and MgII
predsMask = (preds == 1) | (preds == 2)
d = {'wave_cen': np.array(wave_cen)[predsMask],
'preds':preds[predsMask],
'preds_probability': list(preds_probability[predsMask]),
'sightline': list(sightlines[predsMask])}
df = pd.DataFrame(data=d)
df.to_pickle("mock_samp650_predicted_Abs_only.pkl")
# Save only the high confidence predicted CIV and MgII
predsMask = (preds_highConf == 1) | (preds_highConf == 2)
d = {'wave_cen': np.array(wave_cen)[predsMask],
'preds':preds[predsMask],
'preds_highConf': list(preds_highConf[predsMask]),
'preds_probability': list(preds_probability[predsMask]),
'sightline': list(sightlines[predsMask])}
df = pd.DataFrame(data=d)
df.to_pickle("mock_samp650_predicted_Abs_only_highConf" + str(prob_cut) + ".pkl")
|
/*
Flowerbox
Copyright (C) 2016 Kayateia
For license info, please see notes/gpl-3.0.txt under the project root.
*/
/*
Flowerbox permissions are broken into 3 different segments:
- Owner permissions
- Group permissions
- Other permissions
Owner permissions are easy: owners always have full permissions to everything, except
potentially with properties with a sticky bit.
Group permissions are the permissions that apply when the acting user is a member
of the group hierarchy specified in the group field of the wob. This is not implemented yet.
Other permissions are for everyone else: If you are neither the owner nor in the group,
this is what you will get.
For each object that is securable, these three groups are separated by 8 bits within a
single 24-bit number, from most to least significant. So for example, a property that is
read/write for the owner, readable for group, and not readable by others, might have a
textual representation like "rw:r::". This would be represented in numeric
form as 0x060400.
*/
import { Wob, WobProperties } from "./Wob";
// Note that the static members of this class are lower case to match Petal conventions,
// because these will be exported directly to Petal.
export class Perms {
// Admin
// Verbs: This verb, when executed, will run with elevated (admin) privileges.
// This permission is not transitive, so any code called from the admin verb
// will not have elevated privileges (unless that verb is also +a).
public static a = 0x10;
// Sticky
// Properties: This property will retain ownership and permissions from the
// object on which it originated. This bit is set on the "misc" part.
// Verbs: This verb, when executed, will run with the privileges of the verb's
// caller. This means that it has access to all of the caller's data and may
// create new objects as the caller. This permission is not transitive, so any
// code called from the sticky verb will revert to the standard model
// (unless that verb is also +s).
public static s = 0x08;
// Read
// Properties: Can read the property value
// Verbs: Can read the verb program
// Wobs: Can read the property list and the base property
public static r = 0x04;
// Write
// Properties: Can write the property value
// Verbs: Can write the verb program
// Wobs: Can create and delete properties and verbs, change base property
public static w = 0x02;
// Execute
// Verbs: Can execute the verb
public static x = 0x01;
private static GetSetBits(mask: number, bits: number, newValue?: number): number {
if (newValue !== undefined && newValue !== null)
return (mask & ~(0xff << bits)) | ((newValue & 0xff) << bits);
else
return (mask >> bits) & 0xff;
}
// Gets or sets the misc portion of a permissions mask.
public static misc(mask: number, newValue?: number): number {
return Perms.GetSetBits(mask, 24, newValue);
}
// Gets or sets the owner portion of a permissions mask.
// Note that this is not used in practice, but it's here for completion's sake.
public static owner(mask: number, newValue?: number): number {
return Perms.GetSetBits(mask, 16, newValue);
}
// Gets or sets the group portion of a permissions mask.
public static group(mask: number, newValue?: number): number {
return Perms.GetSetBits(mask, 8, newValue);
}
// Gets or sets the others portion of a permissions mask.
public static others(mask: number, newValue?: number): number {
return Perms.GetSetBits(mask, 0, newValue);
}
// This expects a string of the form "rwx:r:r:s" and returns permissions bit values.
//
// "owner:group:other:meta"
//
// There are a total of four possible groups in the permission string. The first segment
// is for owner/user, the second for group, the third for "other", and the fourth is the
// meta/misc bits. The fourth segment is actually higher up in the number than the
// other three, but it's last so that it can be more optional. If any group is missing
// or empty, it will be assumed that it's zero. Also, the bits within a group need
// not be in any prescribed order.
public static parse(maskString: string): number {
if (maskString === undefined)
return undefined;
let groups: string[] = maskString.split(":");
function parseOneChunk(chunk: string): number {
let chunkOut = 0;
for (let c of chunk) {
if (c === "r")
chunkOut |= Perms.r;
if (c === "w")
chunkOut |= Perms.w;
if (c === "x")
chunkOut |= Perms.x;
if (c === "s")
chunkOut |= Perms.s;
if (c === "a")
chunkOut |= Perms.a;
}
return chunkOut;
}
let out = 0;
if (groups.length > 0)
out = Perms.owner(out, parseOneChunk(groups[0]));
if (groups.length > 1)
out = Perms.group(out, parseOneChunk(groups[1]));
if (groups.length > 2)
out = Perms.others(out, parseOneChunk(groups[2]));
if (groups.length > 3)
out = Perms.misc(out, parseOneChunk(groups[3]));
return out;
}
// This expects a permissions bit mask, and returns a string of the form "rwx:r:r:s".
// Note that all groups will be present even if they are empty.
public static unparse(mask: number): string {
if (mask === undefined)
return undefined;
function unparseOneChunk(maskPart: number): string {
let chunkOut = "";
if (maskPart & Perms.r)
chunkOut += "r";
if (maskPart & Perms.w)
chunkOut += "w";
if (maskPart & Perms.x)
chunkOut += "x";
if (maskPart & Perms.a)
chunkOut += "a";
if (maskPart & Perms.s)
chunkOut += "s";
return chunkOut;
}
let out = unparseOneChunk(Perms.owner(mask));
out += ":" + unparseOneChunk(Perms.group(mask));
out += ":" + unparseOneChunk(Perms.others(mask));
out += ":" + unparseOneChunk(Perms.misc(mask));
return out;
}
// These two constants are for permissions on properties and verbs for only the owner (private).
public static ownerOnly = Perms.owner(0, Perms.r | Perms.w);
public static ownerOnlyExec = Perms.owner(0, Perms.r | Perms.w | Perms.x);
}
// Static methods for verifying various security actions against the permissions on a wob.
export class Security {
// Default permissions
// Returns the default permissions for a property.
public static GetDefaultPropertyString(): string {
return "rw:r:r:";
}
// Returns the default permissions for a property.
public static GetDefaultPropertyPerms(): number {
return Perms.parse(Security.GetDefaultPropertyString());
}
// Returns the default permissions for a verb.
public static GetDefaultVerbString(): string {
return "rwx:rx:rx:";
}
// Returns the default permissions for a verb.
public static GetDefaultVerbPerms(): number {
return Perms.parse(Security.GetDefaultVerbString());
}
// Returns the default permissions for a wob.
public static GetDefaultWobString(): string {
return "rw:r:r:";
}
// Returns the default permissions for a wob.
public static GetDefaultWobPerms(): number {
return Perms.parse(Security.GetDefaultWobString());
}
// Wob permissions
// Checks if the specified user has all the specified permissions on a wob.
public static CheckWob(wob: Wob, userId: number, mask: number): boolean {
// We ignore group for now.
let ownerId = wob.owner;
if (!ownerId)
return false;
if (ownerId === userId)
return true;
let perms = wob.perms;
let others = Perms.others(perms);
if ((others & mask) === mask)
return true;
return false;
}
// Checks if the specified user has read permissions on a wob.
public static CheckWobRead(wob: Wob, userId: number): boolean {
return Security.CheckWob(wob, userId, Perms.r);
}
// Checks if the specified user has write permissions on a wob.
public static CheckWobWrite(wob: Wob, userId: number): boolean {
return Security.CheckWob(wob, userId, Perms.w);
}
// Property permissions
// Checks if the specified user has all the specified permissions on a property on a wob.
public static CheckProperty(wob: Wob, property: string, userId: number, mask: number): boolean {
// We ignore group for now.
let owner = wob.owner;
if (!owner)
return false;
if (owner === userId)
return true;
let prop = wob.getProperty(property);
if (!prop) {
// FIXME: Some logic here about creating properties.
return false;
}
let perms = prop.perms;
if (!perms)
perms = Security.GetDefaultPropertyPerms();
let others = Perms.others(perms);
if ((others & mask) === mask)
return true;
return false;
}
// Checks if the specified user has read permissions on a property on a wob.
public static CheckPropertyRead(wob: Wob, property: string, userId: number): boolean {
return Security.CheckProperty(wob, property, userId, Perms.r);
}
// Checks if the specified user has write permissions on a property on a wob.
public static CheckPropertyWrite(wob: Wob, property: string, userId: number): boolean {
return Security.CheckProperty(wob, property, userId, Perms.w);
}
// Returns true if the specified property has its stick bit set.
public static CheckPropertySticky(wob: Wob, property: string): boolean {
let prop = wob.getProperty(property);
if (!prop)
return false;
let perms = prop.perms;
if (!perms)
return false;
let misc = Perms.misc(perms);
return !!(misc & Perms.s);
}
// Verb permissions
// Checks if the specified user has all the specified permissions on a verb on a wob.
public static CheckVerb(wob: Wob, verbWord: string, userId: number, mask: number): boolean {
// We ignore group for now.
let owner = wob.owner;
if (!owner)
return false;
if (owner === userId)
return true;
let verb = wob.getVerb(verbWord);
if (!verb) {
// FIXME: Some logic here about creating verbs.
return false;
}
let perms = verb.perms;
if (!perms)
perms = Security.GetDefaultVerbPerms();
let others = Perms.others(perms);
if (others & mask)
return true;
return false;
}
// Checks if the specified user has read permissions on a verb on a wob.
public static CheckVerbRead(wob: Wob, verb: string, userId: number): boolean {
return Security.CheckVerb(wob, verb, userId, Perms.r);
}
// Checks if the specified user has write permissions on a verb on a wob.
public static CheckVerbWrite(wob: Wob, verb: string, userId: number): boolean {
return Security.CheckVerb(wob, verb, userId, Perms.w);
}
// Checks if the specified user has execute permissions on a verb on a wob.
public static CheckVerbExecute(wob: Wob, verb: string, userId: number): boolean {
return Security.CheckVerb(wob, verb, userId, Perms.x);
}
// Returns true if the specified verb has the specified bit set on it.
public static CheckVerbBit(wob: Wob, verbWord: string, bit: number): boolean {
let verb = wob.getVerb(verbWord);
if (!verb)
return false;
let perms = verb.perms;
if (!perms)
return false;
let misc = Perms.misc(perms);
return !!(misc & bit);
}
// Returns true if the specified verb is intended to be run with elevated privileges.
public static CheckVerbElevated(wob: Wob, verbWord: string): boolean {
return Security.CheckVerbBit(wob, verbWord, Perms.a);
}
// Returns true if the specified verb is intended to be run with caller privileges.
public static CheckVerbSticky(wob: Wob, verbWord: string): boolean {
return Security.CheckVerbBit(wob, verbWord, Perms.s);
}
// The rest of these are basically convenience methods that call back to the ones above,
// to centralize all the checks so we can easily change them later.
// Checks if the specified user has the rights to get the list of properties on a wob.
public static CheckGetWobProperties(wob: Wob, userId: number): boolean {
return Security.CheckWobRead(wob, userId);
}
// Checks if the specified user has the rights to get the list of verbs on a wob.
public static CheckGetWobVerbs(wob: Wob, userId: number): boolean {
return Security.CheckWobRead(wob, userId);
}
// Checks if the specified user has the rights to add a property to a wob.
public static CheckSetWobProperties(wob: Wob, userId: number): boolean {
return Security.CheckWobWrite(wob, userId);
}
// Checks if the specified user has the rights to add a verb to a wob.
public static CheckSetWobVerbs(wob: Wob, userId: number): boolean {
return Security.CheckWobWrite(wob, userId);
}
}
|
Si vous cherchez à interagir avec des conteneurs Docker, plusieurs commandes de base vous seront utiles pour gérer et contrôler vos conteneurs. Voici un aperçu des commandes les plus couramment utilisées :
1. **Lancer un conteneur** :
```bash
docker run [options] IMAGE [COMMAND] [ARG...]
```
- Exemple : `docker run -d -p 80:80 nginx` (lance un conteneur nginx en arrière-plan et mappe le port 80).
2. **Lister les conteneurs** :
```bash
docker ps [options]
```
- Exemple : `docker ps -a` (affiche tous les conteneurs, y compris ceux qui sont arrêtés).
3. **Arrêter un conteneur** :
```bash
docker stop [CONTAINER]
```
- Exemple : `docker stop mon_conteneur` (arrête le conteneur nommé "mon_conteneur").
4. **Démarrer un conteneur arrêté** :
```bash
docker start [CONTAINER]
```
- Exemple : `docker start mon_conteneur`.
5. **Redémarrer un conteneur** :
```bash
docker restart [CONTAINER]
```
- Exemple : `docker restart mon_conteneur`.
6. **Supprimer un conteneur** :
```bash
docker rm [CONTAINER]
```
- Exemple : `docker rm mon_conteneur` (supprime le conteneur après qu'il soit arrêté).
7. **Voir les logs d'un conteneur** :
```bash
docker logs [CONTAINER]
```
- Exemple : `docker logs mon_conteneur`.
8. **Exécuter une commande dans un conteneur actif** :
```bash
docker exec [options] CONTAINER COMMAND [ARG...]
```
- Exemple : `docker exec -it mon_conteneur bash` (ouvre une session bash dans le conteneur).
9. **Inspecter un conteneur** :
```bash
docker inspect [CONTAINER]
```
- Exemple : `docker inspect mon_conteneur` (fournit des détails détaillés sur le conteneur).
10. **Afficher les statistiques de l'utilisation des ressources par les conteneurs** :
```bash
docker stats
```
- Exemple : `docker stats` (affiche les statistiques en temps réel pour tous les conteneurs en cours).
Ces commandes vous permettent de gérer vos conteneurs Docker efficacement, que ce soit pour le développement ou pour la production. Si vous avez besoin de détails spécifiques sur une commande, n'hésitez pas à demander!
|
"use client"
import { useEffect, useState } from "react"
import { Zap } from "lucide-react"
import { MAX_FREE_GENERATIONS } from "@/consts"
import { Button } from "@/components/ui/button"
import { Progress } from "@/components/ui/progress"
import { Card, CardContent } from "@/components/ui/card"
import useProModal from "@/hooks/use-pro-modal"
interface FreeGenerationsCounterProps {
apiLimitCount: number
isPro: boolean
}
const FreeGenerationsCounter = ({ apiLimitCount, isPro = false }: FreeGenerationsCounterProps) => {
const proModal = useProModal()
const [isMounted, setIsMounted] = useState(false)
useEffect(() => {
setIsMounted(true)
}, [])
if (!isMounted) return null
if (isPro) return null
return (
<div className="px-3">
<Card className="bg-white/10 border-0">
<CardContent className="py-6">
<div className="text-center text-sm text-white mb-4 space-y-2">
<p>
{apiLimitCount} / {MAX_FREE_GENERATIONS} free generations
</p>
<Progress
className="h-3"
value={(apiLimitCount / MAX_FREE_GENERATIONS) * 100}
/>
</div>
<Button onClick={proModal.onOpen} variant="premium" className="w-full">
Upgrade
<Zap className="h-4 w-4 ml-2 fill-white" />
</Button>
</CardContent>
</Card>
</div>
);
}
export default FreeGenerationsCounter;
|
//
// DailyScrum.swift
// Scrumdinger
//
// Created by Ahmet Tınastepe on 11.03.2023.
//
import Foundation
struct DailyScrum: Identifiable, Codable {
let id: UUID
var title: String
var attendees: [Attendee]
var lengthInMinutes: Int
var theme: Theme
var history: [History] = []
init(data: Data) {
self.id = UUID()
self.title = data.title
self.attendees = data.attendees
self.lengthInMinutes = Int(data.lengthInMinutes)
self.theme = data.theme
}
}
extension DailyScrum {
struct Attendee: Identifiable, Codable {
let id: UUID
let name: String
init(id: UUID = UUID(), name: String) {
self.id = id
self.name = name
}
}
struct Data {
var title: String = ""
var attendees: [Attendee] = []
var lengthInMinutes: Double = 5
var theme: Theme = .seafoam
}
var data: Data {
Data(title: title, attendees: attendees, lengthInMinutes: Double(lengthInMinutes), theme: theme)
}
mutating func update(from data: Data) {
title = data.title
attendees = data.attendees
lengthInMinutes = Int(data.lengthInMinutes)
theme = data.theme
}
}
extension DailyScrum {
private static let data: [Data] = [
Data(title: "Design", attendees: [Attendee(name: "Cathy"), Attendee(name: "Daisy")], lengthInMinutes: 10, theme: .yellow),
Data(title: "App Dev", attendees: [Attendee(name: "Katie"), Attendee(name: "Gray")], lengthInMinutes: 5, theme: .orange),
Data(title: "Web Dev", attendees: [Attendee(name: "Christina"), Attendee(name: "Karla")], lengthInMinutes: 15, theme: .poppy)
]
static let sampleData: [DailyScrum] = [
DailyScrum(data: data[0]),
DailyScrum(data: data[1]),
DailyScrum(data: data[2]),
]
}
|
<mat-card>
<mat-list>
<div mat-subheader>
<h2>TODAS LAS RESERVAS</h2>
</div>
<div class="mat-elevation-z8" style="margin-top: 10px">
<table mat-table [dataSource]="reservations" class="mat-elevation-z8">
<!--- Definir las columnas de la tabla -->
<ng-container matColumnDef="reservaId">
<th mat-header-cell *matHeaderCellDef> Id </th>
<td mat-cell *matCellDef="let element"> {{element.reservaId}} </td>
</ng-container>
<ng-container matColumnDef="pasajero">
<th mat-header-cell *matHeaderCellDef> Pasajero </th>
<td mat-cell *matCellDef="let element"> {{element.pasajero}} </td>
</ng-container>
<ng-container matColumnDef="piloto">
<th mat-header-cell *matHeaderCellDef> Piloto </th>
<td mat-cell *matCellDef="let element"> {{element.piloto}} </td>
</ng-container>
<ng-container matColumnDef="fechaReserva">
<th mat-header-cell *matHeaderCellDef> fechaReserva </th>
<td mat-cell *matCellDef="let element"> {{element.fechaReserva}} </td>
</ng-container>
<!-- Columna para los iconos de actualizar y eliminar -->
<ng-container matColumnDef="acciones">
<th mat-header-cell *matHeaderCellDef> Acciones </th>
<td mat-cell *matCellDef="let element">
<button mat-icon-button (click)="verReservacion(element.reservaId)">
<mat-icon>remove_red_eye</mat-icon>
</button>
<button mat-icon-button (click)="eliminarReservacion(element.reservaId)">
<mat-icon>delete</mat-icon>
</button>
<button mat-icon-button (click)="descargarReservacion(element.reservaId)">
<mat-icon>cloud_download</mat-icon>
</button>
</td>
</ng-container>
<!--- Renderizar las filas de la tabla -->
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
</mat-list>
<div class="container text-center mt20">
<button routerLink="/admin/add-reservation" mat-raised-button color="primary">Agregar Reserva</button>
</div>
</mat-card>
|
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import Toastify from "toastify-js";
export default function ProductForm({ url, formName, product, handleSubmit }) {
const navigate = useNavigate();
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [price, setPrice] = useState(0);
const [stock, setStock] = useState(0);
const [imgUrl, setImgUrl] = useState("");
const [categoryId, setCategoryId] = useState("");
const [categories, setCategories] = useState([]);
useEffect(() => {
if (product) {
setName(product.name);
setDescription(product.description);
setPrice(product.price);
setStock(product.stock);
setImgUrl(product.imgUrl);
setCategoryId(product.categoryId);
}
}, [product]);
async function fetchCategories() {
try {
const { data } = await axios.get(
`${url}/apis/branded-things/categories`,
{
headers: {
Authorization: `Bearer ${localStorage.access_token}`,
},
}
);
setCategories(data.data);
} catch (error) {
Toastify({
text: error.response.data.error,
duration: 3000,
newWindow: true,
close: true,
gravity: "bottom",
position: "right",
stopOnFocus: true,
style: {
background: "#A91D3A",
},
}).showToast();
}
}
useEffect(() => {
fetchCategories();
}, []);
return (
<>
<section
className="col-md-9 ms-sm-auto col-lg-10 px-md-4"
id="new-product-section"
>
<div className="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 className="display-2">{formName}</h1>
</div>
<div className="row">
<div className="col-12 col-md-6">
<form
id="product-form"
onSubmit={(event) =>
handleSubmit(
event,
name,
description,
price,
stock,
imgUrl,
categoryId
)
}
>
<div className="mb-3">
<label htmlFor="product-name">
Name <span className="text-danger fw-bold">*</span>
</label>
<input
type="text"
className="form-control"
id="product-name"
placeholder="Enter product name"
autoComplete="off"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="mb-3">
<label htmlFor="product-category">
Category <span className="text-danger fw-bold">*</span>
</label>
<select
onChange={(e) => setCategoryId(e.target.value)}
name="category"
id="product-category"
className="form-select"
required
>
{categories.map((category) => {
return (
<option key={category.id} value={category.id}>
{category.name}
</option>
);
})}
</select>
</div>
<div className="mb-3">
<label htmlFor="product-desc">
Description <span className="text-danger fw-bold">*</span>
</label>
<input
type="text"
className="form-control"
id="product-desc"
placeholder="Enter product description"
autoComplete="off"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
<div className="row">
<div className="col-12 col-md-6">
<div className="mb-3">
<label htmlFor="product-stock">
Stock <span className="text-danger fw-bold">*</span>
</label>
<input
type="number"
min="0"
className="form-control"
id="product-stock"
placeholder="Enter product stock"
autoComplete="off"
value={stock}
onChange={(e) => setStock(e.target.value)}
/>
</div>
</div>
<div className="col-12 col-md-6">
<div className="mb-3">
<label htmlFor="product-price">
Price <span className="text-danger fw-bold">*</span>
</label>
<input
type="number"
min="0"
className="form-control"
id="product-price"
placeholder="Enter product price"
autoComplete="off"
value={price}
onChange={(e) => setPrice(e.target.value)}
/>
</div>
</div>
</div>
<div className="mb-3">
<label htmlFor="product-image">Image</label>
<input
type="text"
className="form-control"
id="product-image"
placeholder="Enter product image url"
autoComplete="off"
value={imgUrl}
onChange={(e) => setImgUrl(e.target.value)}
/>
</div>
<div className="row mt-5 mb-3">
<div className="col-6">
<button
className="btn btn-lg btn-light rounded-pill w-100 p-2"
href=""
onClick={() => navigate("/")}
>
Cancel
</button>
</div>
<div className="col-6">
<button
className="btn btn-lg btn-primary rounded-pill w-100 p-2"
type="submit"
href=""
>
Submit
</button>
</div>
</div>
</form>
</div>
</div>
</section>
</>
);
}
|
import mongoose, { Schema, Document, Mongoose, Types } from 'mongoose';
import { IRole } from './role.model';
export interface IAddress {
street: string;
city: string;
state: string;
postalCode: string;
country: string;
}
export interface IUser extends Document {
_id?: Types.ObjectId;
firstName: string;
lastName: string;
email?: string;
password: string;
username: string;
role: IRole | Types.ObjectId;
bio?: string;
birthDate?: Date;
profilePicture?: string;
location?: string;
website?: string;
address?: IAddress;
// Add more fields as needed
}
const AddressSchema: Schema = new Schema({
street: { type: String, required: true },
city: { type: String, required: true },
state: { type: String, required: true },
postalCode: { type: String, required: true },
country: { type: String, required: true },
});
const UserSchema: Schema = new Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, unique: true },
password: { type: String, required: true },
username: { type: String, required: true, unique: true },
role: { type: Schema.Types.ObjectId, ref: 'Role', required: true },
bio: { type: String },
birthDate: { type: Date },
profilePicture: { type: String },
location: { type: String },
website: { type: String },
address: { type: AddressSchema },
},
{
timestamps: true,
_id: true,
autoCreate: true,
versionKey: false,
collection: 'users',
});
export const User = mongoose.model<IUser>('User', UserSchema);
|
{% extends 'base.html' %}
{% load bootstrap5 %}
{% load custom_filters %}
{% block content %}
{% include 'partials/_banner.html' with heading="Post Doctoral Alumni" %}
<div class="container my-5">
<div class="row">
<div class="col-lg-3 d-sm-none d-md-block ">
{% include 'partials/_members.html' %}
</div>
<div class="col-lg-9">
{% if bios %}
{% for bio in bios %}
<div class="d-flex mb-5">
{% if bio.image %}
<div class="flex-shrink-0">
<img class="img-fluid" src="{{ bio.image.url }}" style="width: 157px;" alt="...">
</div>
{% endif %}
<div class="flex-grow-1 ms-3">
<div class="card shadow-lg">
<div class="card-header bg-info d-flex justify-content-between">
<h5 class="">{{ bio.name }}</h5>
<p class="card-text"> {% if user.is_authenticated %} <a class="btn btn-outline-dark btn-sm" href="{% url 'members:bio_update' pk=bio.pk %}">Edit</a> {% endif %} </p>
</div>
<div class="card-body">
{% if bio.bio %}
<p class="card-text"><span class="fw-bold">Bio:</span> {{ bio.bio }}</p>
{% endif %}
<hr class="border border-info">
{% if bio.research_area %}
<p class="card-text">
<span class="fw-bold">Research Areas:</span> {% with bio.research_area|split_string:',' as research_area_list %}
<ul class="list-group">
{% for research_area in research_area_list %}
<li class="list-group-item">{{ research_area }}</li>
{% endfor %}
</ul>
{% endwith %}
</p>
{% endif %}
<hr class="border border-info">
{% if bio.career %}
<p class="card-text">
<span class="fw-bold">Career:</span> {% with bio.career|split_string:',' as career_list %}
<ul class="list-group">
{% for career in career_list %}
<li class="list-group-item">{{ career }}</li>
{% endfor %}
</ul>
{% endwith %}
</p>
<hr class="border border-info">
{% endif %}
<p class="card-text">
<span class="fw-bold">Education:</span> <br>
{{ bio.education|linebreaksbr }}
</p>
<p class="card-text"> {% if user.is_authenticated %} <a class="btn btn-outline-info" href="{% url 'members:bio_update' pk=bio.pk %}">Edit</a> {% endif %} </p>
</div>
<div class="card-footer d-flex justify-content-between bio-links">
{% with bio.email_list|split_string:',' as email_list %}
<span class="fw-bold">
<i class="fa-solid fa-envelope"></i>
{% for email in email_list %}
<a href="mailto:{{ email }}">{{ email }} |</a>
{% endfor %}
</span>
{% endwith %}
{% if bio.link %}
<span class="fw-bold">
<!-- <a href="{{ bio.link }}" target="_blank"><i class="fa-brands fa-google-scholar"></i></a> -->
<a href="{{ bio.link }}" target="_blank"><i class="fas fa-globe"></i> View more</a>
</span>
</span>
{% endif %}
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<p>No bio</p>
{% endif %}
</div>
</div>
</div>
{% endblock %}
|
import random
class Dog:
def __init__(self, name, age, skill):
self.name = name
self.age = age
self.skill = skill
def showSkill(self):
return f'{self.name} skill is {self.skill}'
class Band:
def __init__(self, band_name, music_genre, number_of_gold_records=0, number_of_platinum_records=0):
self.band_name = band_name
self.music_genre = music_genre
self.number_of_gold_records = number_of_gold_records
self.number_of_platinum_records = number_of_platinum_records
def set_number_of_gold_records(self, number):
self.number_of_gold_records = number
def set_number_of_platinum_records(self, number):
self.number_of_platinum_records = number
def is_active(self):
return 'is active' if self.number_of_platinum_records > 0 else 'is not active'
def __str__(self):
return f'{self.band_name} ({self.music_genre}) - Gold Records: {self.number_of_gold_records}, Platinum Records: {self.number_of_platinum_records}'
class CoverBand(Band):
def __init__(self, band_name, music_genre, covered_bands_and_performers=[]):
super().__init__(band_name, music_genre)
self.covered_bands_and_performers = covered_bands_and_performers
def add_covered_band(self, band):
self.covered_bands_and_performers.append(band)
def get_covered_bands_and_performers(self):
return self.covered_bands_and_performers
def __str__(self):
return f'{super().__str__()} - Covers: {", ".join(self.covered_bands_and_performers)}'
# Create instances of CoverBand and call its methods
cover_band = CoverBand("Cover Masters", "Variety", ["The Beatles", "Queen"])
cover_band.add_covered_band("Elvis Presley")
cover_band.set_number_of_gold_records(2)
cover_band.set_number_of_platinum_records(1)
print(cover_band)
print(f'{cover_band.band_name} {cover_band.is_active()}')
print(f'Covered Bands and Performers: {", ".join(cover_band.get_covered_bands_and_performers())}')
# Coin flipping function
def toss_coin():
return random.choice(["Heads", "Tails"])
# Toss the coin 10, 20, and 50 times
for num_tosses in [10, 20, 50]:
results = [toss_coin() for _ in range(num_tosses)]
heads_count = results.count("Heads")
tails_count = results.count("Tails")
print(f'Tossing the coin {num_tosses} times - Heads: {heads_count}, Tails: {tails_count}')
|
import React from 'react';
import { View, TouchableOpacity, Image } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { styles } from './styles';
import { theme } from '../../theme';
interface Props {
screenshot: string | null;
onTakeShot: () => void;
onRemoveShot: () => void;
}
export function ScreenshotButton({ screenshot, onTakeShot, onRemoveShot }: Props) {
return (
<TouchableOpacity
style={styles.container}
onPress= {screenshot ? onRemoveShot: onTakeShot}
>
{
screenshot
?
<View>
<Image
style={styles.image}
source={{uri: screenshot}}
/>
<Ionicons
name="md-trash-outline"
size={22}
color={theme.colors.text_secondary}
weight= 'fill'
style={styles.removeIcon}
/>
</View>
:
<Ionicons
name="md-camera-outline"
size={22}
color={theme.colors.text_secondary}
weight= 'bold'
/>
}
</TouchableOpacity>
);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.