text stringlengths 184 4.48M |
|---|
<template>
<transition
v-on:before-enter="beforeEnter"
v-on:enter="enter"
v-on:after-enter="afterEnter"
v-bind:css="false">
<div class="top-progress" :style="barStyle" v-if="show">
<div class="peg" :style="pegStyle">
</div>
</div>
</transition>
</template>
<script>
function clamp (n, min, max) {
if (n < min) {
return min
}
if (n > max) {
return max
}
return n
}
let queue = (() => {
let pending = []
function next () {
let fn = pending.shift()
if (fn) {
fn(next)
}
}
return fn => {
pending.push(fn)
if (pending.length === 1) {
next()
}
}
})()
export default {
name: 'vueTopprogress',
data () {
return {
error: false,
show: false,
progress: 0,
opacity: 1,
status: null,
isPaused: false
}
},
props: {
speed: {
type: Number,
default: 350
},
color: {
type: String,
default: '#29d'
},
colorShadow: String,
errorColor: {
type: String,
default: '#f44336'
},
trickle: {
type: Boolean,
default: true
},
trickleSpeed: {
type: Number,
default: 250
},
easing: {
type: String,
default: 'linear'
},
height: {
type: Number,
default: 3
},
minimum: {
type: Number,
default: 0.8
},
maximum: {
type: Number,
default: 97.5
},
zIndex: {
type: Number,
default: 9999
}
},
computed: {
progressColor () {
return this.error ? this.errorColor : this.color
},
isStarted () {
return typeof this.status === 'number'
},
boxShadow () {
return this.colorShadow || this.progressColor
},
barStyle () {
return {
position: 'fixed',
top: '0',
left: '0',
right: '0',
width: `${this.progress}%`,
height: `${this.height}px`,
backgroundColor: this.progressColor,
transition: `all ${this.speed}ms ${this.easing}`,
opacity: `${this.opacity}`,
zIndex: `${this.zIndex}`
}
},
pegStyle () {
return {
display: 'block',
position: 'absolute',
right: '0',
width: '100px',
height: '100%',
opacity: this.progress ? '1' : '0',
boxShadow: `0 0 10px ${this.boxShadow}, 0 0 5px ${this.boxShadow}`,
transform: 'rotate(3deg) translate(0px, -4px)'
}
}
},
methods: {
beforeEnter (el) {
this.opacity = 0
this.progress = 0
this.width = 0
},
enter (el, done) {
this.opacity = 1
done()
},
afterEnter (el) {
this._runStart()
},
_work () {
setTimeout(() => {
if (!this.isStarted || this.isPaused) {
return
}
this.increase()
this._work()
}, this.trickleSpeed)
},
_runStart () {
this.status = (this.progress === 100 ? null : this.progress)
if (this.trickle) {
this._work()
}
},
start () {
this.isPaused = false
if (this.show) {
this._runStart()
} else {
this.show = true
}
},
set (amount) {
this.isPaused = false
let o
if (this.isStarted) {
o = amount < this.progress
? clamp(amount, 0, 100)
: clamp(amount, this.minimum, 100)
} else {
o = 0
}
this.status = (o === 100 ? null : o)
queue(next => {
this.progress = o
if (o === 100) {
setTimeout(() => {
this.opacity = 0
setTimeout(() => {
this.show = false
this.error = false
next()
}, this.speed)
}, this.speed)
} else {
setTimeout(next, this.speed)
}
})
},
increase (amount) {
let o = this.progress
if (o < 100 && typeof amount !== 'number') {
if (o >= 0 && o < 25) {
amount = Math.random() * 3 + 3
} else if (o >= 25 && o < 50) {
amount = Math.random() * 3
} else if (o >= 50 && o < 85) {
amount = Math.random() * 2
} else if (o >= 85 && o < 99) {
amount = 0.5
} else {
amount = 0
}
}
this.set(clamp(o + amount, 0, this.maximum))
},
decrease (amount) {
if (this.progress === 0) {
return
}
this.increase(-amount)
},
done () {
this.set(100)
},
getProgress () {
return this.status ? this.progress : 0
},
pause () {
this.isPaused = true
},
fail () {
this.error = true
this.done()
}
}
}
</script> |
import React from "react"
import ImmutablePureComponent from "react-immutable-pure-component"
import ImPropTypes from "react-immutable-proptypes"
import PropTypes from "prop-types"
import { getModelName } from './utils'
export default class ModelFlatWrapper extends ImmutablePureComponent {
static propTypes = {
namespace: PropTypes.string.isRequired,
schema: ImPropTypes.map.isRequired,
getComponent: PropTypes.func.isRequired,
getConfigs: PropTypes.func.isRequired,
specSelectors: PropTypes.object.isRequired,
includeReadOnly: PropTypes.bool,
includeWriteOnly: PropTypes.bool,
}
getAllModels(namespace, schema, options, models = {}) {
if (schema) {
const type = schema.get('type') || 'object'
if (type === 'object') {
const modelName = getModelName(schema, namespace)
models[modelName] = schema
const properties = schema.get("properties")
const additionalProperties = schema.get("additionalProperties")
if (properties) {
properties
.filter((value) => {
return (!value.get("readOnly") || options.includeReadOnly) &&
(!value.get("writeOnly") || options.includeWriteOnly)
})
.mapKeys((propertyName, propertyValue) => {
this.getAllModels(namespace, propertyValue, options, models)
})
}
if (additionalProperties) {
this.getAllModels(namespace, additionalProperties, options, models)
}
} else if (type === 'array' && schema.get('items')) {
this.getAllModels(namespace, schema.get('items'), options, models)
}
}
return models
}
render() {
let { namespace, schema, getComponent, getConfigs, specSelectors, includeReadOnly, includeWriteOnly } = this.props
const ModelFlat = getComponent('ModelFlat')
const ModelFlatProperty = getComponent('ModelFlatProperty')
const type = schema.get('type') || 'object'
const models = this.getAllModels(namespace, schema, { includeReadOnly, includeWriteOnly })
return <div className="model-box schema-flat">
{Object.entries(models).map(([key, value]) => {
return <ModelFlat
namespace={namespace}
key={key}
name={key}
schema={value}
getComponent={getComponent}
getConfigs={getConfigs}
specSelectors={specSelectors}
includeReadOnly={includeReadOnly}
includeWriteOnly={includeWriteOnly} />
})}
{
type === 'object' ? null :
<ModelFlatProperty
namespace={namespace}
getComponent={getComponent}
getConfigs={getConfigs}
schema={schema}
name={""} />
}
</div>
}
} |
---
layout: default
title: Managing Roles in OpenIAP Flow
parent: What Is OpenIAP Flow
nav_order: 2
---
# Managing Roles in OpenIAP Flow
## What are Roles?
Roles in **OpenIAP Flow** are sets of privileges and permissions that can be assigned to users or other roles. These roles are crucial for controlling access to various types of data within OpenIAP Flow, including projects/workflows and queues.
## Nested Roles
In OpenIAP Flow, roles can be nested up to three levels by default, although this limit can be adjusted by the system administrator. Nested roles allow for a more granular and hierarchical organization of permissions and access rights.
## RPA Roles
Roles can also be designated as OpenRPA roles. These special roles are used to group multiple OpenRPA robots, enabling the distribution of Invoke OpenRPA calls among all members. This maximizes robot utilization and allows for multiple workflows to be run in parallel.
## List of Built-in Roles in OpenIAP Flow
OpenIAP Flow includes several built-in roles, each with specific permissions:
- **users**: Represents all users created in OpenIAP Flow.
- **admins**: Members can manage all aspects of OpenIAP Flow.
- **customer admins**: Members can manage all customers, if multi tenancy is enabled
- **resellers**: Members (who is also customer admin) can create new customers.
- **workitem queue admins**: Members can access all workitem queues and all workitems in those queues
- **workitem queue users**: Members can create new workitem queues
- **filestore users**: Can upload and download files in OpenIAP Flow.
- **filestore admins**: Have full control over all files uploaded in OpenIAP Flow.
- **nodered admins**: Allows members to log into Node-RED instances.
- **nodered api users**: Allows members to access any http endpoint exposed from all Node-RED workflows.
- **robot admins**: legacy role, not in use anymore
- **robot users**: legacy role, not in use anymore
- **robot agent users**: legacy role, not in use anymore
- **nodered users**: legacy role, not in use anymore
- **personal nodered users**: legacy role, not in use anymore |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>视频列表</title>
<link type="text/css" rel="stylesheet" href="/static/bootstrap/3.3.7/bootstrap.min.css">
<script src="/static/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="/static/bootstrap/3.3.7/bootstrap.min.js"></script>
</head>
<body>
<div class="panel">
<div class="panel-body">
<h2 class="h2">视频列表</h2>
<div class="row">
<div class="col-sm-4">
<h3>上传视频</h3>
<div class="form-group">
<form id="image-form" class="form-group">
<label for="upload-image"></label>
<input type="file" name="video" accept="video/mp4"/>
</form>
<div class="form-group">
<button class="btn btn-primary btn" id="upload">上传</button>
</div>
</div>
</div>
</div>
<div id="image-div">
</div>
</div>
</div>
<script>
$(function () {
$.get('/videos/list', function (res) {
res.forEach(e => {
$('#image-div').append('<div class="col-sm-6 col-md-4">' +
' <div class="thumbnail">' +
' <div class="caption">' +
' <h5>文件名: <a href="/get/video?name=' + e.name + '">' + e.name + '</a></h5>' +
' <h5>文件大小: ' + e.size + 'MB</h5>' +
' <h5>修改时间: ' + e.time + '</h5>' +
' <button class="btn btn-primary btn-xs" onclick="show(\'' + e.name + '\')">展示</button>' +
' <button class="btn btn-danger btn-xs" onclick="del(\'' + e.name + '\')">删除</button>' +
' </div>' +
' </div>' +
'</div>');
})
})
$('#upload').click(function () {
const formData = new FormData($('#image-form')[0]);
$.ajax('/api/video/upload', {
method: 'POST',
data: formData,
processData: false,
contentType: false,
success() {
alert('上传成功')
window.location.reload();
},
error() {
},
});
})
})
function show(name) {
if (confirm('确认展示?')) {
$.post('/api/video/show', {
name: name
}, function (res) {
alert(res.msg)
})
}
}
function del(name) {
if (confirm('确认删除?')) {
$.post('/del/video', {
name: name
}, function (res) {
window.location.reload();
})
}
}
</script>
</body>
</html> |
<div class="modal-content-wrapper">
<header class="modal-header">
<h1 class="modal-title">Create a new ERG</h1>
</header>
<section class="modal-body">
<mat-stepper [linear]="isLinear" #stepper>
<mat-step [stepControl]="firstFormGroup">
<form [formGroup]="firstFormGroup">
<ng-template matStepLabel>What is the name of this ERG</ng-template>
<mat-form-field appearance="fill">
<mat-label>ERG NAME</mat-label>
<input
matInput
placeholder="Black@Chezie"
formControlName="ergName"
required
/>
</mat-form-field>
<div>
<button mat-button matStepperNext>Next</button>
</div>
</form>
</mat-step>
<mat-step [stepControl]="secondFormGroup" label="Members in ERG">
<form [formGroup]="secondFormGroup">
<mat-form-field appearance="fill">
<mat-label># Of Members In ERG</mat-label>
<input
matInput
formControlName="numberOfMembers"
placeholder="25"
required
/>
</mat-form-field>
<div>
<button mat-button matStepperPrevious>Back</button>
<button mat-button matStepperNext>Next</button>
</div>
</form>
</mat-step>
<mat-step>
<ng-template matStepLabel>Finish</ng-template>
<p>Create and Finish</p>
<div>
<button mat-button matStepperPrevious>Back</button>
<button mat-button (click)="createErg()">Create</button>
</div>
</mat-step>
</mat-stepper>
</section>
<footer class="modal-footer">
<button
mat-raised-button
class="modal-cancel-button"
(click)="closeModal()"
>
Close
</button>
</footer>
</div> |
import { AbstractControl, ValidatorFn } from '@angular/forms';
export interface StringLengthError {
maxlength?: {
requiredLength: number;
};
minlength?: {
requiredLength: number;
};
}
export interface StringLengthOptions {
maximumLength?: number;
minimumLength?: number;
}
export function validateStringLength({
maximumLength = Infinity,
minimumLength = 0,
}: StringLengthOptions = {}): ValidatorFn {
return (control: AbstractControl): StringLengthError | null => {
if (['', null, undefined].indexOf(control.value) > -1) return null;
const value = String(control.value);
return getMinLengthError(value, minimumLength) || getMaxLengthError(value, maximumLength);
};
}
function getMaxLengthError(value: string, requiredLength: number): StringLengthError {
return value.length > requiredLength ? { maxlength: { requiredLength } } : null;
}
function getMinLengthError(value: string, requiredLength: number): StringLengthError {
return value.length < requiredLength ? { minlength: { requiredLength } } : null;
} |
// src/components/Cart.js
import React, { useContext } from "react";
import { CartContext } from "./CartContext";
const Cart = () => {
const { cart, removeItemFromCart, clearCart } = useContext(CartContext);
const removeFromCartHandler = (productid) => {
removeItemFromCart(productid);
};
const clearCartHandler = () => {
clearCart();
};
console.log("cart", cart);
return (
<div>
<h2>Your Cart</h2>
{cart.items.length > 0 ? (
<button onClick={() => clearCartHandler()}>Clear Cart</button>
) : null}
<ul>
{cart.items.map((item) => (
<>
<li key={item.id}>
{item.name} - Item price is : {item.price}, Quantity : {item.quantity} , Total price : Rs{item.totalPrice}
</li>
<button onClick={() => removeFromCartHandler(item.id)}>
Remove from cart
</button>
</>
))}
</ul>
</div>
);
};
export default Cart; |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int[][] adjMat;
static int result = 0;
static boolean[] visited;
public static void bfs(int idx) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(idx);
visited[idx] = true;
while (!queue.isEmpty()) {
int cur = queue.poll();
for (int i = 1; i < adjMat.length; i++) {
if (adjMat[cur][i] == 1 && !visited[i]) {
queue.offer(i);
visited[i] = true;
result++;
}
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = null;
int computerCnt = Integer.parseInt(br.readLine());
int edge = Integer.parseInt(br.readLine());
adjMat = new int[computerCnt + 1][computerCnt + 1]; // 1번부터 시작
visited = new boolean[computerCnt + 1];
for (int i = 0; i < edge; i++) {
st = new StringTokenizer(br.readLine());
int v1 = Integer.parseInt(st.nextToken());
int v2 = Integer.parseInt(st.nextToken());
adjMat[v1][v2] = adjMat[v2][v1] = 1;
}
bfs(1);
System.out.println(result);
}
} |
OP_KEYS = %w{addr addi mulr muli banr bani borr bori setr seti gtir gtri gtrr eqir eqri eqrr}
class Op
attr_reader :opkey
def initialize(op)
@opkey, @ina, @inb, @out = op
end
def run!(register)
send("#{@opkey}!",register)
end
def addr(register); register[@ina] + register[@inb]; end
def addi(register); register[@ina] + @inb; end
def mulr(register); register[@ina] * register[@inb]; end
def muli(register); register[@ina] * @inb; end
def banr(register); register[@ina] & register[@inb]; end
def bani(register); register[@ina] & @inb; end
def borr(register); register[@ina] | register[@inb]; end
def bori(register); register[@ina] | @inb; end
def setr(register); register[@ina]; end
def seti(register); @ina; end
def gtir(register); @ina > register[@inb] ? 1 : 0; end
def gtri(register); register[@ina] > @inb ? 1 : 0; end
def gtrr(register); register[@ina] > register[@inb] ? 1 : 0; end
def eqir(register); @ina == register[@inb] ? 1 : 0; end
def eqri(register); register[@ina] == @inb ? 1 : 0; end
def eqrr(register); register[@ina] == register[@inb] ? 1 : 0; end
OP_KEYS.each do |opkey|
define_method("is_#{opkey}?") do |register|
register[@out] == send("#{opkey}", register)
end
define_method("#{opkey}!") do |register|
register[@out] = send("#{opkey}", register)
end
end
end
lines = File.readlines("input")
ip_reg = lines.shift.match(/#ip (\d+)/).captures.first.to_i
data = lines.map{ |l| l.match(/([a-z]+) (\d+) (\d+) (\d+)/){ |m|
Op.new(m.captures.each_with_index.map{ |v,i| i == 0 ? v : v.to_i }) }
}
def run(data, register, ip_reg, ip)
0.step do |i|
p ip
p register
register[ip_reg] = ip
op = data[ip]
op.run!(register)
ip = register[ip_reg] + 1
break if data[ip].nil?
end
register[0]
end
p run(data, [0] + [0] * 5, ip_reg, 0) |
import numpy as np
import math
import random
import os
import json
#from tqdm import tqdm
import time
import sys
import threading
from multiprocessing import Pool, cpu_count
ROW_COUNT = 6
COLUMN_COUNT = 7
WINDOW_LENGTH = 4
PLAYER_PIECE = 1
BOT_PIECE = 2
EMPTY = 0
def create_board():
board = np.zeros((ROW_COUNT, COLUMN_COUNT))
return board
def print_board(board):
flipped_board = np.flipud(board)
# print white
print("\033[0;37;47m 0 \033[0;37;47m 1 \033[0;37;47m 2 \033[0;37;47m 3 \033[0;37;47m 4 \033[0;37;47m 5 \033[0;37;47m 6 \033[0m")
for i in flipped_board:
row_str = ""
for j in i:
if j == 1:
# Print yellow
row_str += "\033[0;37;43m 1 "
elif j == 2:
# Print red
row_str += "\033[0;37;41m 2 "
else:
# Print navy
row_str += "\033[0;37;48;5;18m "
print(row_str + "\033[0m")
def get_valid_locations(board):
valid_locations = []
for col in range(COLUMN_COUNT):
if is_valid(board, col):
valid_locations.append(col)
return valid_locations
def drop_piece(board, row, col, piece):
board[row][col] = piece
def is_valid(board, col):
return board[ROW_COUNT - 1][col] == 0
def get_next_open_row(board, col):
for row in range(ROW_COUNT):
if board[row][col] == 0:
return row
#def print_board(board):
# print(np.flip(board, 0))
def score_position(board, piece):
score = 0
# centre column
centre_array = [int(i) for i in list(board[:, COLUMN_COUNT // 2])]
centre_count = centre_array.count(piece)
score += centre_count * 3
#horizontal positions
for row in range(ROW_COUNT):
row_array = [int(i) for i in list(board[row, :])]
for col in range(COLUMN_COUNT - 3):
window = row_array[col : col + WINDOW_LENGTH]
score += evaluate_window(window, piece)
# vertical positions
for col in range(COLUMN_COUNT):
col_array = [int(i) for i in list(board[:, col])]
for row in range(ROW_COUNT - 3):
window = col_array[row : row + WINDOW_LENGTH]
score += evaluate_window(window, piece)
# positive diagonals
for row in range(ROW_COUNT - 3):
for col in range(COLUMN_COUNT - 3):
window = [board[row + i][col + i] for i in range(WINDOW_LENGTH)]
score += evaluate_window(window, piece)
# negative diagonals
for row in range(ROW_COUNT - 3):
for col in range(COLUMN_COUNT - 3):
window = [board[row + 3 - i][col + i] for i in range(WINDOW_LENGTH)]
score += evaluate_window(window, piece)
return score
def evaluate_window(window, piece):
score = 0
opp_piece = PLAYER_PIECE
if piece == PLAYER_PIECE:
opp_piece = BOT_PIECE
# winning move
if window.count(piece) == 4:
score += 100
# opponent's winning move
#elif window.count(opp_piece) == 3 and window.count(EMPTY) == 1:
#score += 50
# connecting 3
elif window.count(piece) == 3 and window.count(EMPTY) == 1:
score += 5
# connecting 2
elif window.count(piece) == 2 and window.count(EMPTY) == 2:
score += 2
# blocking an opponent's winning move
if window.count(opp_piece) == 3 and window.count(EMPTY) == 1:
score -= 4
return score
def winning_move(board, piece):
#horizontal locations
for c in range(COLUMN_COUNT - 3):
for r in range(ROW_COUNT):
if board[r][c] == piece and board[r][c + 1] == piece and board[r][c + 2] == piece and board[r][c + 3] == piece:
return True
#vertical locations
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT - 3):
if board[r][c] == piece and board[r + 1][c] == piece and board[r + 2][c] == piece and board[r + 3][c] == piece:
return True
#positive diagonal
for c in range(COLUMN_COUNT - 3):
for r in range(ROW_COUNT - 3):
if board[r][c] == piece and board[r + 1][c + 1] == piece and board[r + 2][c + 2] == piece and board[r + 3][c + 3] == piece:
return True
#negative diagonal
for c in range(COLUMN_COUNT - 3):
for r in range(3, ROW_COUNT):
if board[r][c] == piece and board[r - 1][c + 1] == piece and board[r - 2][c + 2] == piece and board[r - 3][c + 3] == piece:
return True
def is_terminal_node(board):
return winning_move(board, PLAYER_PIECE) or winning_move(board, BOT_PIECE) or len(get_valid_locations(board)) == 0
def minimax(board, depth, alpha, beta, maximisingPlayer):
valid_locations = get_valid_locations(board)
is_terminal = is_terminal_node(board)
if depth == 0 or is_terminal:
if is_terminal:
if winning_move(board, BOT_PIECE):
return (None, 9999999)
elif winning_move(board, PLAYER_PIECE):
return (None, -9999999)
else:
return (None, 0)
else:
return (None, score_position(board, BOT_PIECE))
if maximisingPlayer:
value = -math.inf
column = random.choice(valid_locations)
for col in valid_locations:
row = get_next_open_row(board, col)
b_copy = board.copy()
drop_piece(b_copy, row, col, BOT_PIECE)
new_score = minimax(b_copy, depth - 1, alpha, beta, False)[1]
if new_score > value:
value = new_score
column = col
alpha = max(alpha, value)
if alpha >= beta:
break
return column, value
else:
value = math.inf
column = random.choice(valid_locations)
for col in valid_locations:
row = get_next_open_row(board, col)
b_copy = board.copy()
drop_piece(b_copy, row, col, PLAYER_PIECE)
new_score = minimax(b_copy, depth - 1, alpha, beta, True)[1]
if new_score < value:
value = new_score
column = col
beta = min(beta, value)
if alpha >= beta:
break
return column, value
def play_manjaro_vs_bot():
board = create_board()
print_board(board)
game_over = False
turn = random.randint(0, 1)
while not game_over:
if turn == 0:
depth = random.randint(3, 5)
col, minimax_score = minimax(board, depth, -math.inf, math.inf, True)
if is_valid(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, BOT_PIECE)
else:
depth = random.randint(3, 5)
col, minimax_score = minimax(board, depth, -math.inf, math.inf, False)
if is_valid(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, PLAYER_PIECE)
print_board(board)
if winning_move(board, PLAYER_PIECE):
print("Player 1 wins!")
game_over = True
elif winning_move(board, BOT_PIECE):
print("Player 2 wins!")
game_over = True
elif len(get_valid_locations(board)) == 0:
print("It's a tie!")
game_over = True
turn += 1
turn = turn % 2
def play_user_vs_bot():
board = create_board()
print_board(board)
game_over = False
turn = random.randint(0, 1)
while not game_over:
if turn == 0:
while True:
try:
col = int(input("Player make your selection (0-6): "))
if col < 0 or col > 6:
raise ValueError
if is_valid(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, PLAYER_PIECE)
break
else:
print("Column is full. Choose another column.")
except ValueError:
print("Please enter a valid number between 0 and 6.")
else:
col, minimax_score = minimax(board, 4, -math.inf, math.inf, True)
if is_valid(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, BOT_PIECE)
print_board(board)
if winning_move(board, PLAYER_PIECE):
print("Player wins!")
game_over = True
elif winning_move(board, BOT_PIECE):
print("Bot wins!")
game_over = True
elif len(get_valid_locations(board)) == 0:
print("It's a tie!")
game_over = True
turn += 1
turn = turn % 2
###
'''
def minimax_worker(args):
board, depth, alpha, beta, maximisingPlayer, col = args
valid_locations = get_valid_locations(board)
is_terminal = is_terminal_node(board)
if depth == 0 or is_terminal:
if is_terminal:
if winning_move(board, BOT_PIECE):
return col, 9999999 if maximisingPlayer else -9999999
elif winning_move(board, PLAYER_PIECE):
return col, -9999999 if maximisingPlayer else 9999999
else:
return col, 0
return col, score_position(board, BOT_PIECE) if maximisingPlayer else score_position(board, PLAYER_PIECE)
if maximisingPlayer:
value = -9999999
for col in valid_locations:
row = get_next_open_row(board, col)
b_copy = board.copy()
drop_piece(b_copy, row, col, BOT_PIECE)
new_col, new_score = minimax_worker((b_copy, depth - 1, alpha, beta, False, col))
if new_score > value:
value = new_score
alpha = max(alpha, value)
best_col = col
if alpha >= beta:
break
return best_col, value
else:
value = 9999999
for col in valid_locations:
row = get_next_open_row(board, col)
b_copy = board.copy()
drop_piece(b_copy, row, col, PLAYER_PIECE)
new_col, new_score = minimax_worker((b_copy, depth - 1, alpha, beta, True, col))
if new_score < value:
value = new_score
beta = min(beta, value)
best_col = col
if alpha >= beta:
break
return best_col, value
def minimax(board, depth, alpha, beta, maximisingPlayer):
valid_locations = get_valid_locations(board)
args_list = []
for col in valid_locations:
row = get_next_open_row(board, col)
b_copy = board.copy()
drop_piece(b_copy, row, col, BOT_PIECE if maximisingPlayer else PLAYER_PIECE)
args_list.append((b_copy, depth - 1, alpha, beta, not maximisingPlayer, col))
pool = Pool(cpu_count())
results = pool.map(minimax_worker, args_list)
pool.close()
pool.join()
if maximisingPlayer:
best_value = -math.inf
for col, value in results:
if value > best_value:
best_value = value
best_col = col
return best_col, best_value
else:
best_value = math.inf
for col, value in results:
if value < best_value:
best_value = value
best_col = col
return best_col, best_value
'''
def collect_statistics(num_games):
bot_wins = 0
player_wins = 0
ties = 0
for _ in range(num_games):
board = create_board()
game_over = False
turn = random.randint(0, 1)
while not game_over:
if turn == 0:
col, minimax_score = minimax(board, 4, -math.inf, math.inf, True)
if is_valid(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, BOT_PIECE)
else:
col, minimax_score = minimax(board, 4, -math.inf, math.inf, False)
if is_valid(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, PLAYER_PIECE)
if winning_move(board, PLAYER_PIECE):
player_wins += 1
game_over = True
elif winning_move(board, BOT_PIECE):
bot_wins += 1
game_over = True
elif len(get_valid_locations(board)) == 0:
ties += 1
game_over = True
turn += 1
turn = turn % 2
total_games = bot_wins + player_wins + ties
bot_win_rate = (bot_wins / total_games) * 100
player_win_rate = (player_wins / total_games) * 100
tie_rate = (ties / total_games) * 100
statistics = {
"total_games": total_games,
"bot_win_rate": bot_win_rate,
"player_win_rate": player_win_rate,
"tie_rate": tie_rate
}
return statistics
def save_statistics(new_statistics):
filepath = 'statistics.json'
all_statistics = []
try:
with open(filepath, 'r') as file:
all_statistics = json.load(file)
except FileNotFoundError:
pass
all_statistics.extend(new_statistics)
with open(filepath, 'w') as file:
json.dump(all_statistics, file, indent=4)
def indeterminate_progress(done):
while not done.is_set():
for symbol in '|/-\\':
sys.stdout.write('\rGathering statistics ' + symbol)
sys.stdout.flush()
time.sleep(0.1)
def main():
all_statistics = []
while True:
print("Welcome to Connect Four!")
print("Select an option:")
print("1. Play Connect Four")
print("2. Display Game Statistics")
print("3. Exit")
while True:
try:
choice = int(input("Enter your choice (1, 2, or 3): "))
if choice not in [1, 2, 3]:
raise ValueError
break
except ValueError:
print("Please enter a valid choice (1, 2, or 3).")
if choice == 1:
print("Choose an option:")
print("1. Play against the bot")
print("2. Watch bot vs bot")
while True:
try:
sub_choice = int(input("Enter your choice (1 or 2): "))
if sub_choice not in [1, 2]:
raise ValueError
break
except ValueError:
print("Please enter a valid choice (1 or 2).")
if sub_choice == 1:
play_user_vs_bot()
else:
play_manjaro_vs_bot()
elif choice == 2:
done = threading.Event()
spinner_thread = threading.Thread(target=indeterminate_progress, args=(done,))
spinner_thread.start()
num_games = 5
statistics = collect_statistics(num_games)
done.set()
spinner_thread.join()
print("\nStatistics:")
print(statistics)
all_statistics.append(statistics)
save_statistics(all_statistics)
else:
print("Exiting the game. Goodbye!")
save_statistics(all_statistics)
break
replay = input("Do you want to play again? (yes/no): ")
if replay.lower() != 'yes' and replay.lower() != 'y':
save_statistics(all_statistics)
break
if __name__ == "__main__":
main() |
package nl.solar.app.rest;
import nl.solar.app.WebConfig;
import nl.solar.app.models.Warehouse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
/**
* Test class for the WarehouseController
* @author Wilco van de Pol
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WarehouseControllerTest {
@Autowired
private WebConfig webConfig;
@Autowired
TestRestTemplate restTemplate;
@Value("${server.servlet.context-path}")
private String servletContextPath;
@BeforeEach
public void setup() {
webConfig.SECURED_PATHS = Set.of("/empty");
if (servletContextPath == null) {
servletContextPath = "/";
}
restTemplate.getRestTemplate().setRequestFactory(new HttpComponentsClientHttpRequestFactory());
}
@Test
public void allWarehousesCanBeRetrieved(){
ResponseEntity<Warehouse[]> response =
this.restTemplate.getForEntity("/warehouses", Warehouse[].class);
// check status code and the response body
assertEquals(HttpStatus.OK, response.getStatusCode(), "Status code should be 'OK'");
Warehouse[] warehouses = response.getBody();
assertThat(warehouses.length, is(greaterThan(0)));
}
@Test
public void specificWarehouseCanBeRetrieved() {
ResponseEntity<Warehouse> response =
this.restTemplate.getForEntity("/warehouses/1000", Warehouse.class);
// check status code and the response body
assertEquals(HttpStatus.OK, response.getStatusCode(), "Status code should be 'OK'");
Warehouse warehouse = response.getBody();
if (warehouse != null) {
assertEquals(warehouse.getName(), "Solar Sedum");
assertEquals(warehouse.getLocation(), "H.J.E. Wenckebachweg 47D, 1096AK Amsterdam");
}
}
@Test
public void aNewWarehouseCanBePosted() {
Warehouse warehouse = new Warehouse(
1234,
"Test Name",
"Test Location");
ResponseEntity<Warehouse> response1 =
this.restTemplate.postForEntity("/warehouses", warehouse,Warehouse.class);
// check status code and response body
assertEquals(HttpStatus.CREATED, response1.getStatusCode());
Warehouse newWarehouse = response1.getBody();
if (newWarehouse != null){
assertThat(newWarehouse.getId(), is(greaterThan(0L)));
assertEquals(warehouse.getName(), newWarehouse.getName());
}
// check location
String location = response1.getHeaders().getLocation().getPath();
assertThat(location, is(equalTo(servletContextPath + "warehouses/" + newWarehouse.getId())));
// retrieve the book that was just posted and verify
ResponseEntity<Warehouse> response2 =
this.restTemplate.getForEntity("/warehouses/" + newWarehouse.getId(), Warehouse.class);
assertEquals(HttpStatus.OK, response2.getStatusCode());
Warehouse savedWarehouse = response2.getBody();
assertEquals(savedWarehouse.getName(), warehouse.getName());
}
} |
import os
import argparse
from pathlib import Path
import cv2
import numpy as np
from deep_image_matching.utils.database import (
COLMAPDatabase,
blob_to_array,
pair_id_to_image_ids,
)
def generate_pairs(imgs_dir):
pairs = []
n_images = len(os.listdir(imgs_dir))
for i in range(n_images-1):
if i%2 == 0:
pairs.append((i+1, i+2))
return pairs
class ShowPairMatches:
def __init__(
self,
database_path: Path,
imgs_dict: dict,
imgs_dir: Path,
out_file: Path,
max_size: int,
):
self.db_path = database_path
self.imgs_dict = imgs_dict
self.imgs_dir = imgs_dir
self.out_file = out_file
self.max_out_img_size = max_size
self.imgs = {}
self.keypoints = {}
self.matches = {}
self.two_views_matches = {}
if self.db_path.suffix == ".db":
self.db_type = "colmap"
else:
print("Error. Not supported database extension. Quit")
quit()
def LoadDatabase(self):
print("Loading database..")
if self.db_type == "colmap":
db = COLMAPDatabase.connect(self.db_path)
self.imgs = dict(
(image_id, name)
for image_id, name in db.execute("SELECT image_id, name FROM images")
)
self.keypoints = dict(
(image_id, blob_to_array(data, np.float32, (-1, 2)))
for image_id, data in db.execute("SELECT image_id, data FROM keypoints")
)
for pair_id, r, c, data in db.execute(
"SELECT pair_id, rows, cols, data FROM matches"
):
if data is not None:
pair_id = pair_id_to_image_ids(pair_id)
self.matches[(int(pair_id[0]), int(pair_id[1]))] = blob_to_array(
data, np.uint32, (-1, 2)
)
for pair_id, r, c, data in db.execute(
"SELECT pair_id, rows, cols, data FROM two_view_geometries"
):
if data is not None:
pair_id = pair_id_to_image_ids(pair_id)
self.two_views_matches[
(int(pair_id[0]), int(pair_id[1]))
] = blob_to_array(data, np.uint32, (-1, 2))
def ShowMatches(self):
if self.db_type == "colmap":
self.ShowColmapMatches()
def ShowColmapMatches(self):
print("Showing matches..")
if self.imgs_dict["type"] == "ids":
id0 = int(self.imgs_dict["data"][0])
id1 = int(self.imgs_dict["data"][1])
elif self.imgs_dict["type"] == "names":
inverted_dict = {v: k for k, v in self.imgs.items()}
im0 = self.imgs_dict["data"][0]
id0 = inverted_dict[im0]
im1 = self.imgs_dict["data"][1]
id1 = inverted_dict[im1]
keypoints0 = self.keypoints[id0]
keypoints1 = self.keypoints[id1]
print(f"Img {id0}: kpts shape = {keypoints0.shape}")
print(f"Img {id1}: kpts shape = {keypoints1.shape}")
print("raw matches shape", np.shape(self.matches[(id0, id1)]))
print("verified matches shape", np.shape(self.two_views_matches[(id0, id1)]))
img0_path = self.imgs_dir / self.imgs[id0]
img1_path = self.imgs_dir / self.imgs[id1]
print("img0_path", img0_path)
print("img1_path", img1_path)
self.GeneratePlot(
img0_path,
img1_path,
keypoints0,
keypoints1,
self.two_views_matches[(id0, id1)],
)
def GeneratePlot(
self,
img0_path: Path,
img1_path: Path,
kpts0: np.ndarray,
kpts1: np.ndarray,
matches: np.ndarray,
):
# Load images
img0 = cv2.imread(str(img0_path))
img1 = cv2.imread(str(img1_path))
# Convert keypoints to integers
kpts0_int = np.round(kpts0).astype(int)
kpts1_int = np.round(kpts1).astype(int)
# Create a new image to draw matches
img_matches = np.zeros(
(max(img0.shape[0], img1.shape[0]), img0.shape[1] + img1.shape[1], 3),
dtype=np.uint8,
)
img_matches[: img0.shape[0], : img0.shape[1]] = img0
img_matches[: img1.shape[0], img0.shape[1] :] = img1
# Show keypoints
for kpt in kpts0_int:
kpt = tuple(kpt)
cv2.circle(img_matches, kpt, 3, (0, 0, 255), -1)
for kpt in kpts1_int:
kpt = tuple(kpt + np.array([img0.shape[1], 0]))
cv2.circle(img_matches, kpt, 3, (0, 0, 255), -1)
# Draw lines and circles for matches
for match in matches:
pt1 = tuple(kpts0_int[match[0]])
pt2 = tuple(np.array(kpts1_int[match[1]]) + np.array([img0.shape[1], 0]))
# Draw a line connecting the keypoints
cv2.line(img_matches, pt1, pt2, (0, 255, 0), 1)
# Draw circles around keypoints
cv2.circle(img_matches, pt1, 3, (255, 0, 0), -1)
cv2.circle(img_matches, pt2, 3, (255, 0, 0), -1)
img_matches_resized = self.resize_image(img_matches, self.max_out_img_size)
## Show the image with matches
# cv2.imshow(f"Verified matches {img0_path.name} - {img1_path.name}", img_matches_resized)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
cv2.imwrite(str(self.out_file), img_matches_resized)
def resize_image(self, img, max_side_length):
height, width = img.shape[:2]
if max(height, width) > max_side_length:
scale_factor = max_side_length / max(height, width)
img_resized = cv2.resize(
img, (int(width * scale_factor), int(height * scale_factor))
)
return img_resized
else:
return img
def parse_args():
parser = argparse.ArgumentParser(
description="Show matches from COLMAP database. 'python ./show_matches.py -d assets/output/database.db -i 'DSC_6466.JPG DSC_6468.JPG' -t names -o . -f assets/example_cyprus/' or 'python ./show_matches.py -d assets/output/database.db -i '1 2' -t ids -o . -f assets/example_cyprus/'"
)
parser.add_argument(
"-d", "--database", type=str, help="Path to COLMAP database", required=True
)
parser.add_argument(
"-f", "--imgsdir", type=str, help="Path to images directory", required=True
)
parser.add_argument(
"-o", "--output", type=str, help="Path to output folder", required=True
)
parser.add_argument(
"--all", action='store_true', help="Export matches for all pairs", required=False
)
parser.add_argument(
"-i",
"--images",
type=str,
help="Images IDs or names. E.g.: 'img1.jpg img2.jpg' or '37 98'. Max two images.",
required=False,
)
parser.add_argument(
"-t", "--type", type=str, choices=["names", "ids"], required=False
)
parser.add_argument(
"-m",
"--max_size",
type=int,
help="Max size of the output image showing matches",
required=False,
default=1500,
)
args = parser.parse_args()
return args
def main():
args = parse_args()
database_path = Path(args.database)
out_dir = Path(args.output)
imgs_dir = Path(args.imgsdir)
max_size = args.max_size
print(f"database path: {database_path}")
print(f"output dir: {out_dir}")
if args.all == False:
i1, i2 = args.images.split()
out_file = out_dir / f"{i1}_{i2}.png"
imgs = {
"type": args.type,
"data": (i1, i2),
}
print("images: ", imgs)
show_pair_matches = ShowPairMatches(
database_path=database_path,
imgs_dict=imgs,
imgs_dir=imgs_dir,
out_file=out_file,
max_size=max_size,
)
show_pair_matches.LoadDatabase()
show_pair_matches.ShowMatches()
else:
pairs = generate_pairs(imgs_dir)
print(pairs)
for pair in pairs:
i1, i2 = pair[0], pair[1]
out_file = out_dir / f"{i1}_{i2}.png"
imgs = {
"type": "ids",
"data": (i1, i2),
}
print("images: ", imgs)
show_pair_matches = ShowPairMatches(
database_path=database_path,
imgs_dict=imgs,
imgs_dir=imgs_dir,
out_file=out_file,
max_size=max_size,
)
show_pair_matches.LoadDatabase()
try:
show_pair_matches.ShowMatches()
except:
print("No verified matches found")
if __name__ == "__main__":
main() |
"""
Managing Attack Logs.
"""
import numpy as np
from textattack.attack_results import FailedAttackResult, SkippedAttackResult
from . import CSVLogger, FileLogger, VisdomLogger, WeightsAndBiasesLogger
class AttackLogManager:
"""Logs the results of an attacks to all attached loggers."""
# 总体管理各种 logger
def __init__(self):
self.loggers = [] # 各种 logger 的列表
self.results = [] # 对抗攻击的结果
def enable_stdout(self):
self.loggers.append(FileLogger(stdout=True)) # 使用 FileLogger 输出到屏幕
def enable_visdom(self):
self.loggers.append(VisdomLogger())
def enable_wandb(self):
self.loggers.append(WeightsAndBiasesLogger())
def add_output_file(self, filename):
self.loggers.append(FileLogger(filename=filename)) # 输出到 txt
def add_output_csv(self, filename, color_method):
self.loggers.append(CSVLogger(filename=filename, color_method=color_method)) # 输出到 csv
summary_name = filename.replace('csv', 'summary')
self.summary_name = summary_name
def log_result(self, result):
"""
Logs an ``AttackResult`` on each of `self.loggers`.
对每个攻击的结果写入到 logger
"""
self.results.append(result) # 保存结果
for logger in self.loggers: # 对于所有的 logger
logger.log_attack_result(result) # 调用对应的记录结果的方法
def log_results(self, results):
"""
Logs an iterable of ``AttackResult`` objects on each of `self.loggers`.
对于 iterable 的攻击结果集合, 调用上面的单条方法,记录结果
"""
for result in results:
self.log_result(result)
self.log_summary() # 完了在记录一下本次攻击的摘要
def log_summary_rows(self, rows, title, window_id): # 不懂,神奇的函数
for logger in self.loggers:
logger.log_summary_rows(rows, title, window_id)
def log_sep(self): #
for logger in self.loggers:
logger.log_sep()
def flush(self): # 估计是输出
for logger in self.loggers:
logger.flush()
def log_attack_details(self, attack_name, model_name):
# @TODO log a more complete set of attacks details
attack_detail_rows = [
["Attack algorithm:", attack_name],
["Model:", model_name],
]
self.log_summary_rows(attack_detail_rows, "Attack Details", "attack_details")
def log_summary(self):
total_attacks = len(self.results)
if total_attacks == 0:
return
# Count things about attacks.
all_num_words = np.zeros(len(self.results))
perturbed_word_percentages = np.zeros(len(self.results))
num_words_changed_until_success = np.zeros(
2 ** 16
) # @ TODO: be smarter about this
failed_attacks = 0
skipped_attacks = 0
successful_attacks = 0
max_words_changed = 0
for i, result in enumerate(self.results):
all_num_words[i] = len(result.original_result.attacked_text.words)
if isinstance(result, FailedAttackResult):
failed_attacks += 1
continue
elif isinstance(result, SkippedAttackResult):
skipped_attacks += 1
continue
else:
successful_attacks += 1
num_words_changed = len(
result.original_result.attacked_text.all_words_diff(
result.perturbed_result.attacked_text
)
)
num_words_changed_until_success[num_words_changed - 1] += 1
max_words_changed = max(
max_words_changed or num_words_changed, num_words_changed
)
if len(result.original_result.attacked_text.words) > 0:
perturbed_word_percentage = (
num_words_changed
* 100.0
/ len(result.original_result.attacked_text.words)
)
else:
perturbed_word_percentage = 0
perturbed_word_percentages[i] = perturbed_word_percentage
# Original classifier success rate on these samples.
original_accuracy = (total_attacks - skipped_attacks) * 100.0 / (total_attacks)
original_accuracy = str(round(original_accuracy, 2)) + "%"
# New classifier success rate on these samples.
accuracy_under_attack = (failed_attacks) * 100.0 / (total_attacks)
accuracy_under_attack = str(round(accuracy_under_attack, 2)) + "%"
# Attack success rate.
if successful_attacks + failed_attacks == 0:
attack_success_rate = 0
else:
attack_success_rate = (
successful_attacks * 100.0 / (successful_attacks + failed_attacks)
)
attack_success_rate = str(round(attack_success_rate, 2)) + "%"
perturbed_word_percentages = perturbed_word_percentages[
perturbed_word_percentages > 0
]
average_perc_words_perturbed = perturbed_word_percentages.mean()
average_perc_words_perturbed = str(round(average_perc_words_perturbed, 2)) + "%"
average_num_words = all_num_words.mean()
average_num_words = str(round(average_num_words, 2))
summary_table_rows = [
["Number of successful attacks:", str(successful_attacks)],
["Number of failed attacks:", str(failed_attacks)],
["Number of skipped attacks:", str(skipped_attacks)],
["Original accuracy:", original_accuracy],
["Accuracy under attacks:", accuracy_under_attack],
["Attack success rate:", attack_success_rate],
["Average perturbed word %:", average_perc_words_perturbed],
["Average num. words per input:", average_num_words],
]
num_queries = np.array(
[
r.num_queries
for r in self.results
if not isinstance(r, SkippedAttackResult)
]
)
avg_num_queries = num_queries.mean()
avg_num_queries = str(round(avg_num_queries, 2))
summary_table_rows.append(["Avg num queries:", avg_num_queries])
self.log_summary_rows(
summary_table_rows, "Attack Results", "attack_results_summary"
)
# Show histogram of words changed.
numbins = max(max_words_changed, 10)
for logger in self.loggers:
logger.log_hist(
num_words_changed_until_success[:numbins],
numbins=numbins,
title="Num Words Perturbed",
window_id="num_words_perturbed",
)
self.summary_table_rows = summary_table_rows
self.title = "Attack Results"
def write_summary(self):
import terminaltables
import os
_path = os.path.realpath(os.path.join(self.summary_name, os.pardir))
if not os.path.exists(_path):
os.makedirs(_path)
with open(self.summary_name, 'w', encoding='utf8') as fout:
table_rows = [[self.title, ""]] + self.summary_table_rows
table = terminaltables.AsciiTable(table_rows)
fout.write(table.table) |
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.wm;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.IntArray;
import android.view.IDisplayWindowListener;
import java.util.ArrayList;
import java.util.Set;
/**
* Manages dispatch of relevant hierarchy changes to interested listeners. Listeners are assumed
* to be remote.
*/
class DisplayWindowListenerController {
RemoteCallbackList<IDisplayWindowListener> mDisplayListeners = new RemoteCallbackList<>();
private final WindowManagerService mService;
DisplayWindowListenerController(WindowManagerService service) {
mService = service;
}
int[] registerListener(IDisplayWindowListener listener) {
synchronized (mService.mGlobalLock) {
mDisplayListeners.register(listener);
final IntArray displayIds = new IntArray();
mService.mAtmService.mRootWindowContainer.forAllDisplays((displayContent) -> {
displayIds.add(displayContent.mDisplayId);
});
return displayIds.toArray();
}
}
void unregisterListener(IDisplayWindowListener listener) {
mDisplayListeners.unregister(listener);
}
void dispatchDisplayAdded(DisplayContent display) {
int count = mDisplayListeners.beginBroadcast();
for (int i = 0; i < count; ++i) {
try {
mDisplayListeners.getBroadcastItem(i).onDisplayAdded(display.mDisplayId);
} catch (RemoteException e) {
}
}
mDisplayListeners.finishBroadcast();
}
void dispatchDisplayChanged(DisplayContent display, Configuration newConfig) {
// Only report changed if this has actually been added to the hierarchy already.
boolean isInHierarchy = false;
for (int i = 0; i < display.getParent().getChildCount(); ++i) {
if (display.getParent().getChildAt(i) == display) {
isInHierarchy = true;
}
}
if (!isInHierarchy) {
return;
}
int count = mDisplayListeners.beginBroadcast();
for (int i = 0; i < count; ++i) {
try {
mDisplayListeners.getBroadcastItem(i).onDisplayConfigurationChanged(
display.getDisplayId(), newConfig);
} catch (RemoteException e) {
}
}
mDisplayListeners.finishBroadcast();
}
void dispatchDisplayRemoved(DisplayContent display) {
int count = mDisplayListeners.beginBroadcast();
for (int i = 0; i < count; ++i) {
try {
mDisplayListeners.getBroadcastItem(i).onDisplayRemoved(display.mDisplayId);
} catch (RemoteException e) {
}
}
mDisplayListeners.finishBroadcast();
}
void dispatchFixedRotationStarted(DisplayContent display, int newRotation) {
int count = mDisplayListeners.beginBroadcast();
for (int i = 0; i < count; ++i) {
try {
mDisplayListeners.getBroadcastItem(i).onFixedRotationStarted(
display.mDisplayId, newRotation);
} catch (RemoteException e) {
}
}
mDisplayListeners.finishBroadcast();
}
void dispatchFixedRotationFinished(DisplayContent display) {
int count = mDisplayListeners.beginBroadcast();
for (int i = 0; i < count; ++i) {
try {
mDisplayListeners.getBroadcastItem(i).onFixedRotationFinished(display.mDisplayId);
} catch (RemoteException e) {
}
}
mDisplayListeners.finishBroadcast();
}
void dispatchKeepClearAreasChanged(DisplayContent display, Set<Rect> restricted,
Set<Rect> unrestricted) {
int count = mDisplayListeners.beginBroadcast();
for (int i = 0; i < count; ++i) {
try {
mDisplayListeners.getBroadcastItem(i).onKeepClearAreasChanged(display.mDisplayId,
new ArrayList<>(restricted), new ArrayList<>(unrestricted));
} catch (RemoteException e) {
}
}
mDisplayListeners.finishBroadcast();
}
} |
import { useQuery } from "@tanstack/react-query";
import { supabase } from "../supabase";
const listRecords = async (inventoryId: number) => {
const { data, error } = await supabase
.from("record_view")
.select()
.eq("inventory_id", inventoryId)
.order("display_order", { ascending: true, nullsFirst: true });
if (error) throw new Error(error.message);
return data;
};
export const useListProductRecords = (inventoryId: number) => {
const query = useQuery(["recordsList", inventoryId], () =>
listRecords(inventoryId)
);
return query;
}; |
Intro
-----
- this section is about learning how to build component-driven UI, the component concept is embraced by React
- we learn what componenets are and why exactly React embraces them
This mean we learn:
- React Core Syntax & JSX
- What Components are and how to work with them
- Working with Data
- All the key concepts needed for every React App you will build
What are Components? And why is React all About Them?
-----------------------------------------------------
- React is a JS library for building UI, in general, so are HTML, CSS and JS
- we use libraries like React because they simplify building complex, interactive and reactive user interfaces
- in order to achieve this, React uses 'Components'
- components are reusable building blocks in your user interface
- components are just a combination of HTML code, CSS for styling and possibly JS for logic
- reusability is just a trait of a component, not a requirement
- all user interfaces are made up of components(building blocks)
- pretty much everything you see on a UI is a component, except for text itself(althought that could probably be a component as well if we wanted)
- for example, on twitter, each post is a component - each icon is a component, these components are stored in other components - which are stored in other components
- containers, buttons, input elements, etc.. all are components
- all user interfaces can be split up into components
- React is all about these components
- you build these individual components, and then you tell React how to compose them together into a final user interface
- React embraces this concept of components because:
-> of the reusability aspect (avoid repetition and DRY)
-> it allows us to seperate our concerns (Don't do too many things in one and the same place, keeps codebase small and managable)
-> instead of having one file for all the html code, and one for all the JS code for the entire UI...
-> we have small, seperate units (components) where every component has one clear concern/focus
-> if we split this code throughout multiple files, we have small pieces of code which are easy to manage and maintain
-> this is simillar to splitting big chunks of code into multiple smaller functions
React is Written in a 'Declarative Way'!
----------------------------------------
- react allows you to create re-usable and reactive components consisting of HTML and JS (and then some CSS after), which we then use to build user interfaces
- react uses something called a 'declarative' approach
-> define the desired target state(s) and let React figure out the actual JavaScript Dom instructions
- pretty much build our own, custom HTML elements which we combine together to build a user interface
Creating a New React Project
-----------------------------
- the easiest way to get started with a react project is to use a tool called create-react-app
- full documentation on google or create-react-app.dev
- preconfigured folders with some basic React code files and important configuration files
- these configuration files help you build the react app for production use
- projects created this way will give you a nice dev environment with a development web server
- this allows you to preview the application locally on your machine, in a way that the browser automatically updates the page when you make changes to your code
- so it simplifies our development process, adds a couple of key transformation steps that we need - and later also helps us optimize our React code before we push it to a production server
Node.js:
- in order to execute the above steps, you first need node.js installed
- node.js is a runtime for JS, which allows you to run JS outside of the browser
- not needed for React, however, we need it to run the create-react-app tool command
- behind the scenes, the project generated by this tool will use node.js for the development preview server as well as the transformation and optimization steps
- download the latest version (i think the recommended is better but ok)
How to use create-react-app tool:
npx create-react-app my-app
cd my-app
npm start
- use the above commands in the vs code command line
- the first line creates a new react project folder(takes a minute), the second line navigates into that folder
- the last line runs a special script which exists inside of the project folder to bring up a development server (opens on localhost: 3000)
The Project Folder:
- the files in this folder might change over time - don't worry, as long as the main things are there you're good
- you should see a src folder and a package.json file
-> the package.json file holds all the dependencies of the file, the exact names and versions of these packages will change over time but it does not impact how React works
-> the src folder holds the actual source code you will be working on
Note that in Max's course, he tells us to download a 'cleaned up' version of this starter project folder, which excludes some files and folders
Also note that you can stop the dev environment from running by pressing ctrl+c in the command line it was ran in
Installing Packages:
- vscode has your default system terminal/command prompt integrated into it - so we can run commands from there (ctrl+` shortcut to open terminal)
- we can run: npm install
-> this downloads all the packages and dependencies listed in your package.json file into this project folder
-> the vscode terminal will automatically navigate into this project folder
-> these dependencies are not included in the zip file because it would bloat it uneccessarily - making downloading them a nightmare
-> in most projects this is the proccess, downloading the starter files, then downloading the dependencies (in the projects you don't start from scratch)
- once ran, it will create a folder called 'node_modules' which holds all of these dependencies
-> should never edit or work in these folders, they are third party code that we will import and should not be changed
After this we can run npm start again:
- this starts the development preview server again
- should keep this open while you are working on the project to see any changes
- can always close it by press ctrl+c in the terminal, and restart it by using npm start in the terminal
- as long as this process is running, it will automatically watch your code files - any time a change happens, it will automatically update the loaded page in the browser
Analyzing the Standard React Project
-------------------------------------
- the src folder is where we will spend the majority of our time, and where we will write our react code
- important to understand that React is just javascript - it's just syntactic sugar that makes our lives easier as developers
- the 'npm start' command we used to run our dev environment also takes this syntactic sugar and transforms it into actual javascript code before executing it
- essentially, we can write code in a more modern and efficient way - but it will still be transformed to code that will work on all browsers
- note that the 'index.js' file is the first file to be executed - very important to know this
- in the index.js file:
-> we import ReactDom from the react 3rd party library, making that feature available inside of index.js
-> ReactDom is like an object that has methods and properties, imported from the React library
- we use the createRoot method on ReactDom to create a main entry point(main hook) of the overall UI you are about to build with react
-> this tells React where the react application should be placed in the webpage(the html)
In the public folder, we have our index.html file. We will rarely be in this file but it is the single html file of the project
- this is a regular html file
- in this html file, there is an empty div within the body with the class of root - it's just a regular div
- it is labeled as such because it is where we want to inject the react driven UI(the UI we build with react)
So in the index.js file, we select this root element in the DOM by using a normal document.getElementByID method - setting the main entry point
- this is passed to the ReactDom.createRoot() method as an argument, the result is an object and is stored in a variable called 'root'.
- this root object has a method called .render(), which takes an argument (a component) and renders it to the webpage
- what this essentially does is takes the argument and injects it into the main entry point (the root div we selected earlier)
What we pass into .render() is the App component, which is actually an import from one of our own files in the src folder called App.js
- note that when importing JS files, we can omit the .js extension, but for files like css files, we keep the extension
eg. root.render(<App />); // renders the App component inside of the root element
- App is a component, which we pass into render using JSX syntax (will explain later)
- it will be inserted inside of the root element of our html
- like we said before, App is imported into our index.js from the App.js file - this is where it is stored
- if we take a closer look at the App.js file, we will see that it contains a function name App, and has a default export of App (the function)
- this function returns what looks to be html, a div with an h2 inside of it that has a title as content
- however, this is not HTML, this is JSX, as it is being used within JavaScript
- since it is exported from this file and being imported into index.js, we can use its features in index.js (this is how importing and exporting in modern JS works)
Introducing JSX
---------------
- a special syntax invented and introduced by the react team
- it works in our JS files because of our overall project set up (transformation steps running behind the scenes)
- its basically HTML inside of JS
- stands for 'JavaScript XML' (apparently HTML is XML at the end of the day)
- this code will be automatcally transformed into usable code, this is syntactic sugar again (code that is easy to write, also works in the browser)
How React Works
---------------
- Remember that a component is a custom html element
- remember that React also takes a declarative approach - meaning, we define the desired target state and let React figure out the atual JS DOM instructions
- in our App.js file, in the App function - The jsx that is returned is the desired state, we want to render the 'HTML' within that return statement
- in our index.js, we tell React to render the imported App component inside of our root element
- the App component aka the custom App HTML element, and is being rendered inside the root element at this point
- this custom element is just the exported function from App.js, whose return value is the JSX (the HTML code)
- this JSX is ultimately what we see on the webpage
- what ever is inside of this JSX (as long as its formatted correctly) will be injected into the root element as it appears in the JSX
- note that in regular JS, you would have to take a lot more steps - create a new element, set its content, append it to another element (imparetive, step by step)
- this works, but becomes cumbersome in complex UIs
- with React, we just define the desired end state, and React will generate all of the DOM instructions behind the scenes to render it on to the screen
Building a First Custom Component
---------------------------------
- we could build this component in the same App.js file, but it is best practice to build new componenets in their own new files, one file per component
- this means that a React project with dozens or hundreds of components will also have just as many files, which is totally normal
- to organize the code a little bit better, we can add a component folder in our src folder, which will hold all our component source files
- App.js will not be placed in this folder because it is a special kind of component, regarding its role in the application
-> it's the 'root' component, its the main component being rendered in our starting file index.js
-> all other componenets will be either nested inside of App.js or nested inside of other componenets, which then in turn again are nested somewhere else
- In React, we build a Component Tree
-> we have the main App componenet at the top
-> below that we have any other kinds of custom HTML elements
-> these other components can hold more components, etc
-> big applications can result in quite big component trees, where only the top most component is rendered directly into the HTML page (with help from the ReactDom render instruction)
-> all the other components will not be rendered with this instruction
-> instead, they will be used as regular HTML elements inside of our HTML code inside of our components
- its a common convention in React applications to name your component files like this:
-> Starting with a capital character
-> CamelCase
-> one word
-> should have a component that renders something related to what the name of the file is (if not exactly what the name is)
-:> ^this way the file name tells us what type of logic and HTML code will live inside of that file
- How do we write a component in react?
-> it's important to understand that a component in react is just a JS function
-> it is only special in regards to what it returns, which is JSX
-> so essentially, we write a function declaration with an identifier matching the file name
-> this function will return the JSX code that we want to be rendered by this component
-> to use this component, we need to export it to make it available outside of this file (can export as default)
-> we then import it into the file that has the HTML we wish to render(nest) it in - in this case it will be the App.js file
-> note that we do not import it into index.js because we already have our root component rendered in that file
-> instead we want to use our custom component like a regular HTML element and insert it into our App component's JSX
-> the key difference between a custom component and a regular HTML element is that it starts with a capital letter
-> custom components MUST start with a Capital letter so that React can detect that it is a custom component
-> note that we have to use the name that we specified as an import, since that is how the connection was established
Writing More Complex JSX Code
-----------------------------
- when writing JSX code in a component, you can only have ONE root component
- this means that you cant have two elements that are siblings, only one parent element - though, within this parent you can have more elements that have siblings and children
- also, by default - you can't make code readable by putting the JSX on new lines like in normal HTML
- however, you can achieve readability by wrapping the JSX in parenthesis (), and then adding new lines and indents where necessary
- note that on windows you can auto format your JSX by pressing alt+shift+F
- you can obviously give your elements static content, just like regular HTML - meaning you specifically typed it in
Adding Basic CSS Styling
------------------------
- we still use CSS in React, but there is nothing too React specific when it comes to that CSS code
- we can just add a new CSS file
- typically the CSS file of a component is added next to the components JS file
- in the JS file of this component, import the CSS file so that the build process is aware of that CSS file and knows that it should be considered
- a CSS file is essentially a bunch of rules applied to a bunch of Classes/IDS/default selectors
- these classes/ids need to be added to the corresponeding JSX elements in order for them to be applied - CSS for default selectors are applied to the corresponding HTML tags in the JSX
- one thing to note that is different, is that when we want to add a class attribute to JSX, it is done using 'className' instead of 'class' like normal HMTL
- this is because JSX is still JavaScipt, and 'class' is a reserved word in JS (would still work but is bad practice)
Outputting Dynamic Data & Working with Expressions in JSX
----------------------------------------------------------
- you might want more than one of a certain component, eg. in a to do list, you might want multiple tasks
- you probably want these tasks to be simillar in style but have different values
- we want to be able to receive data from e.g. a user or an API and be able to display it dynamically
- this is not possible if you hardcode the values into your components, you need to make these values dynamic
- this is where Reacts reusability is so powerful
- remember that React components are just a combination of JS, HTML and some CSS
- so we can(and typically do) write some vanilla JavaScript code in our react components
- also remember that JSX is essentially JavaScript
- in our JSX there is a special syntax that allows us to write simple JS expressions within the HTML
- we use curly braces {}, what ever is written in these braces can be evaluated as basic JS expressions, as long as it's within the JSX
- this means we could insert things like 1 + 1, Math.random(), calculations and variables - and it would work
- this also means that we can get dynamic data from e.g. a user or an api in the function definition, store it in a variable then insert that variable into the returned JSX
- if we had a dynamic variable called 'expense' that got its value dynamically from a user, we could insert it into our JSX like this:
e.g. <h2>{expense}<h2/> // inserting a variable into jsx, done with curly braces
- note that trying to do this with a variable that hold something like a date object, will break the app
- this is because it can't be output as text
- we would have to take a property/method of the object - for example for a date object, the method .toISOString(), which ouputs it as a string
This achieves the use of dynamic placeholders instead of just hardcoded values.
This can ultimately allow us to have multiple identical components with different data that is dynamically generated (more on this in a bit)
Passing Data via "props"
------------------------
- a component is reusable by default, meaning that you can copy and paste it as many times as you want inside of the root div of a component
- however, the data of these components are the same - because the data is baked into the component
- thinking about normal JS
-> we also use functions to split functionality accross multiple smaller code bases
-> we use functions to also have reusable functions which we can call multiple times
-> when we write functions is JavaScript, we make these functions reusable by accepting parameters*
-> this allows us to call the same function over and over but using different data (passed as different argument/parameter values)
-> therefor the function may(and typically will) produce different results for different input values - even though it's still always the same function being called
- React basically has the same concept built in
-> we can make our components reusable by using parameters and a concept called props*
-> in order to do this, we store the data that we want to be dynamic in the 'parent' component of the component this data should be used in (like the child component)
-> we do this instead of storing this data in the component itself (the child), we store it in the component that it is living in (the parent)
-> However, components can't just use data stored in other components - we have to pass the data to the custom component
-> so if a variable lives in the parent component, we need a way to pass it to the child component so it can be used there to define what is being output in that component
-> we can do this by utilizing a concept called 'props'
-> remember that we are basically building our own HTML custom elements, and just as HTML elements can have attributes, so can our custom HTML elements
-> we can pass data from a parent component to a child component by using attributes
-> these attributes are set inside of the parent component, and set onto the child component within the JSX
-> inside of that child custom component, we can get access to all these attributes that might have been set on our custom component
-> in React, we call this concept 'props' instead of attributes - which simply stands for properties - in other words, we can set the properties of our own custom components
- How the props concept works
-> we want to make these child components configurable from outside
-> the data should not be stored inside of them, but instead be passed from outside, which we can do with the props concept
-> in the parent component, we can simply add attributes to the child custom html elements
-> we do this the same way we would add attributes to a regular element
> name of the attribute (can be named as we like)
> followed by an equal sign
> followed by the value we want the attribute to contain
> this value can be hard coded, or it can be dynamic by using {} like mentioned before ( {} aka embeded expressions, can be used anywhere in JSX )
-> once these attributes have been added to the child component in the parent file's JSX, it means we have essentially passed them
-> now in the child components file, we have to access them in order to use them - we do this through parameters
-> React insures that we get one parameter in every component that we use - which would be an object that holds all of the passed properties(attributes)
-> This object is automatically passed as a parameter, however, we have to name it within the parenthesis in order to access it (kind of like events (e))
-> we name this object 'props' (can be named anything but props is conventional), which is passed to the child component's function declaration as a parameter (in the child components file)
-> naming it props makes it clear that it is the object that hold all the values we get from the attributes that were passed to our custom element in the parents JSX
-> the prop contains key-value pairs
> the keys will be the attribute names that were passed
> the values will be the values set on those keys
-> you can access the values of these keys in the child component's JSX by using simple dot notation
eg <h2>{props.keyName}</h2>
-> this means we can now get all the data we need from outside of the component we want the data for
- this allows us to get all the data we need from outside the component
- So we're not defining the data inside of the child component (the component that ultimately uses the data in it's JSX directly)
- instead, the data is defined in the parent component, and passed into the child component through attributes
- we are then accessing these attributes in the child components file by accessing the props object using simple dot notation
- this makes components truly reusable and configurable (allows them to work like normal functions, in the sense that they provide different results based on the arguments(props) that are passed)
Adding 'Normal' JavaScript to Components
-----------------------------------------
- we could add JavaScript Logic directly to the JSX if we wanted to, and it would work fine
- however, this is not the best practice as it clutters the JSX, making it harder to see exactly what we are trying to output
- a better practice is to write our JavaScript logic before the return statement containing our JSX
- we figure out the more complex logic, get the desired value from it and store the result in a variable
- we can then insert that variable into the JSX, which is a much more organized way of accomplishing this - easier to read
Splitting Components:
---------------------
- as a React project grows, your components eventually get bigger and bigger as you have more and more logic and JSX code in them - this happens naturally
- Reacts component concept allows you to split your code into smaller building blocks, where every component is focused on one core task
- we then build the overall user interface by combining these building blocks
- by doing this, we keep every component on its own relatively small and managable, as well as its code base - and still build a complex UI
- this also makes the newly made component reusable in different parts of the project
- there is no hard rule on when to build a new component vs adding more to an existing component
- however, when you do feel that a component is getting too big/complex, you can split it up into smaller components where needed
- when doing this, we take the same steps as before to add a new component (naming conventions and all)
- once created, we can replace our old JSX with the new custom component after importing it into the file
- note that if there is no content between opening and closing tags of the custom component, you can just write it with a self closing tag
- the biggest takeaway from this is understanding that you can pass props from app.js to a child component, then from that child component to its own child component etc
- sometimes you need to make a component just to pass data to a another component inside of it, which is totally fine
The Concept of "Composition" ("children props")
-----------------------------------------------
- generally, the approach of building a user interface from smaller building blocks is called composition
- so far we have learned about highly specific components, which have exact intended outputs
- these components are just configured through props (fairly standard, very common in react apps)
- sometimes, we want to have a component where you don't configure everything through props
- instead, we are able to pass content between the opening and closing tags of that component
- for now, we can refer to this as a shell component (or a wrapper component), because it will be used as a wrapper around other components (like a containter)
- Shell/Wrapper Components can help reduce code duplication
-> the idea of having components is to have reusable building blocks, also to avoid code duplication
-> sometimes our components share html structure or style, which is a form of duplication
-> we can extract the styles that components have in common
-> e.g. rounded corners and a drop shadow for a container of a list item, and the container of the list itself
-> if two or more components have the same styles, we can extract those styles from their CSS files
-> we can then create a seperate shell component with these extracted styles/structures e.g. Card (a container look with rounded corners, drop shadow - conventional name)
- Creating a 'shell' component essentially the same as creating a regular component
-> the main thing that it does is return a div (or any other html container element)
-> keep in mind that we are planning to use this component as a wrapper in order to apply shared styles(styles that are repeated)
-> we give the div a specific className of our choice, e.g. card, to specify that we are styling it in a specific way
-> obviously, the styles we want this shell component to have would be the shared styles we extracted from the original components
-> we create a CSS file for the shell component and add these extracted styles to it
-> in this CSS file, we use the className we chose for the div in the shell component earlier as a selector
-> we then import this CSS file into the shell component
- The shell component acts as a container/wrapper
-> now that its CSS file has been imported, the shell component will have the shared styles applied
-> this shell component will not be configured through some attributes (props)***
-> instead, we would replace the root div of our original components with this shell component (I use the term root div wrong here, but I mean the main div of the component when I say this)
-> NOTE: might not even be needed as the main div, could maybe even be used as a child div, im not sure - but it is just a container so it makes sense that it would
-> this allows us to get these predefined styles automatically
-> in order to be able to use this shell component in another component, we need to import the shell components file
-> but we need another step to make this work, because by default, you can't use custom components as wrappers around content
-> wrapping content only works for built in HTML elements by default
- However, we can build custom wrapper components
-> we do this by passing the props object in the shell component's function declaration
-> instead of using passed attributes like we normally would, we instead use a special prop
-> this prop is built in to react, which every component receives, even if you're never setting it explicitly
-> the prop is is props.children, a property of the prop object
-> 'children' is a reserved name
-> the value of 'children' is the content between the opening and closing tags of your custom component
-> we insert props.children as an embedded expression within the shell components root element
-> this is a variable that represents the content that the shell component will be wrapped around when used in other component files
- This will allow content to show up, but the rest of the styles will not be applied
-> remember that in the original components file (the ones we extracted styles from), the original container usually has it's own className
-> this className corresponds to its own CSS file, where it gets all the styles that are unique to it (the ones we didn't extract)
-> at this point of the process, these styles are not applied to the shell component that replaced the original container element
-> the className might be passed as a prop to our shell component, however, we aren't telling our shell component what to do with it at this point
- there is another step to take before our original components unique styles are applied to the shell component
-> remember that the shell component is a custom component defined by us
-> all the default HTML elements support className for adding CSS classes to the rendered HTML elements
-> however, your custom components only support what you tell them to support
-> if you want to make sure that a className can be set on your shell component and then also has an effect, we have to tweak the code in that component
-> this is simply achieved by setting what ever we have set as a className on the shell component(passed as a prop), to the className string we're setting on the container element in the shell component file
-> since we are passing the className as a prop to our shell component, we can access it in our shell component file
-> we can add the value of the passed className prop to our shell component's container element's className list, which is a string
-> we can simply create a classes variable, add our shell compenent class with our passed className prop value
-> we then add this classes variable as an embedded expression to be the value of our shell component container's className value
- this allows you to get the same look as before but also have a reusable wrapper component that can be used in multiple places in the codebase
- this also allows us to extract some code duplication from inside our css files into this seperate wrapper component
- we also are able to extract some HTML/JSX code (more useful when wrapper components are more complex like with modals and alerts)
- in a lot of cases, being able to extract that saves a lot of code duplication and often allows you to keep your other components clean
A First Summary
---------------
- Components are the most important concept in React
- in React, we build user interfaces by building and combining components
- React introduces its own core syntax and JSX
- it involves building, using, and working with components and props
- it allows us to share data accross components through this props concept
- with all these components we are building, in the end we are just splitting up all of our code accross multiple files and building blocks
- so if we want to have more than one of a component, we can just use that component multiple times - instead of repeating the JSX multiple times
- in the end, what ends up on the screen are just default html elements
- if you inspect the webpage, you don't see your custom components, its just <divs> - though the classes are still there
- these custom components are not really html elements, they're just used in our code
A Closer Look at JSX
--------------------
- our current project set up allows us to create these components without importing the third party React library for every single file
- this is because of modern project set up 'magic'
- back in the day we, we had to import React in every single component file if we wanted to use it
- we also had a different syntax, there was no JSX, there were simply methods of React being called to create elements
- JSX is syntactic sugar, which behind the seens, is just calling these methods
- React.creatElement can only create one element at a time, but can take an object of properties to be added to that element
- it can also take an infinite number of arguments that represent the nested elements
- this is why we can only have one root element per component, because in the end - we are just using this method - which can only create one element at a time (though more can be nested)
Organizing Component Files
---------------------------
- organizing your component files becomes more necessary the more components you have
- instead of just having one components folder, it might be a good idea to have sub-folders
- e.g a folder for general UI components, a folder for a specific feature like a group of components that deal with rendering expenses and expense data
- after doing this, make sure to update all your imports
- this is really just done to keep components and files organized, instead of keeping them in one big folder
- the way you organize these files is up to you (and your team)
An Alternative Function Syntax
------------------------------
- we know we can use function declarations to create components
- we can also use function expressions
- this means we can also use arrow functions, which looks cleaner to some people
- doesn't offer any benefits to what we've covered so far, its really just personal preference |
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { StudentAddComponent } from './student-add/student-add.component';
import { StudentDetailsComponent } from './student-details/student-details.component';
import { StudentListComponent } from './student-list/student-list.component';
const routes: Routes = [
{ path: 'student-list', component: StudentListComponent },
{ path: 'student-add', component: StudentAddComponent },
{ path: 'student-details', component: StudentDetailsComponent },
{ path: '', redirectTo: 'student-list', pathMatch: 'full' },
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class StudentRoutingModule {} |
package keeper
import (
"fmt"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
params "github.com/cosmos/cosmos-sdk/x/params/types"
channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types"
gogoprototypes "github.com/gogo/protobuf/types"
"github.com/tendermint/tendermint/libs/log"
"github.com/axelarnetwork/axelar-core/utils"
"github.com/axelarnetwork/axelar-core/utils/key"
"github.com/axelarnetwork/axelar-core/x/axelarnet/types"
nexus "github.com/axelarnetwork/axelar-core/x/nexus/exported"
"github.com/axelarnetwork/utils/funcs"
"github.com/axelarnetwork/utils/slices"
)
var (
cosmosChainPrefix = key.FromStr("cosmos_chain")
feeCollector = key.FromStr("fee_collector")
transferPrefix = key.FromStr("ibc_transfer")
ibcTransferQueueName = "route_transfer_queue"
_ = key.RegisterStaticKey(types.ModuleName, 2) // failedTransferPrefix is deprecated in v0.23
seqIDMappingPrefix = key.RegisterStaticKey(types.ModuleName, 3)
ibcPathPrefix = key.RegisterStaticKey(types.ModuleName, 4)
seqGeneralMsgIDMappingPrefix = key.RegisterStaticKey(types.ModuleName, 5)
// reserved values
// nonceKey is deprecated in v0.23
_ = key.RegisterStaticKey(types.ModuleName, 1)
)
// Keeper provides access to all state changes regarding the Axelarnet module
type Keeper struct {
storeKey sdk.StoreKey
cdc codec.BinaryCodec
params params.Subspace
channelK types.ChannelKeeper
feegrantK types.FeegrantKeeper
}
// NewKeeper returns a new axelarnet keeper
func NewKeeper(cdc codec.BinaryCodec, storeKey sdk.StoreKey, paramSpace params.Subspace, channelK types.ChannelKeeper, feegrantK types.FeegrantKeeper) Keeper {
return Keeper{cdc: cdc, storeKey: storeKey, params: paramSpace.WithKeyTable(types.KeyTable()), channelK: channelK, feegrantK: feegrantK}
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName))
}
// GetParams returns the module parameters.
func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) {
k.params.GetParamSet(ctx, ¶ms)
return
}
// SetParams sets the module parameters.
func (k Keeper) SetParams(ctx sdk.Context, p types.Params) {
k.params.SetParamSet(ctx, &p)
}
// GetRouteTimeoutWindow returns the timeout window for IBC transfers routed by axelarnet
func (k Keeper) GetRouteTimeoutWindow(ctx sdk.Context) uint64 {
var result uint64
k.params.Get(ctx, types.KeyRouteTimeoutWindow, &result)
return result
}
// GetTransferLimit returns the transfer limit for transfers processed by axelarnet
func (k Keeper) GetTransferLimit(ctx sdk.Context) uint64 {
var result uint64
k.params.Get(ctx, types.KeyTransferLimit, &result)
return result
}
// GetEndBlockerLimit returns the transfer limit for IBC transfers routed in the end blocker by axelarnet
func (k Keeper) GetEndBlockerLimit(ctx sdk.Context) uint64 {
var result uint64
k.params.Get(ctx, types.KeyEndBlockerLimit, &result)
return result
}
// GetIBCPath retrieves the IBC path associated to the specified chain
func (k Keeper) GetIBCPath(ctx sdk.Context, chain nexus.ChainName) (string, bool) {
cosmosChain, ok := k.GetCosmosChainByName(ctx, chain)
if !ok || cosmosChain.IBCPath == "" {
return "", false
}
return cosmosChain.IBCPath, true
}
// IsCosmosChain returns true if the given chain name is for a cosmos chain
func (k Keeper) IsCosmosChain(ctx sdk.Context, chain nexus.ChainName) bool {
_, ok := k.GetCosmosChainByName(ctx, chain)
return ok
}
// GetCosmosChainByName gets the address prefix of the given cosmos chain
func (k Keeper) GetCosmosChainByName(ctx sdk.Context, chain nexus.ChainName) (cosmosChain types.CosmosChain, found bool) {
return cosmosChain, k.getStore(ctx).GetNew(cosmosChainPrefix.Append(key.From(chain)), &cosmosChain)
}
// SetChainByIBCPath sets the chain name for the given ibc path
func (k Keeper) SetChainByIBCPath(ctx sdk.Context, ibcPath string, chain nexus.ChainName) error {
if err := types.ValidateIBCPath(ibcPath); err != nil {
return err
}
return k.getStore(ctx).SetNewValidated(ibcPathPrefix.Append(key.FromStr(ibcPath)),
utils.WithValidation(&gogoprototypes.StringValue{Value: chain.String()},
func() error { return chain.Validate() }))
}
// GetChainNameByIBCPath returns the chain name for the given ibc path
func (k Keeper) GetChainNameByIBCPath(ctx sdk.Context, ibcPath string) (nexus.ChainName, bool) {
var chain gogoprototypes.StringValue
found := k.getStore(ctx).GetNew(ibcPathPrefix.Append(key.FromStr(ibcPath)), &chain)
return nexus.ChainName(chain.GetValue()), found
}
// GetCosmosChains retrieves all registered cosmos chain names
func (k Keeper) GetCosmosChains(ctx sdk.Context) []nexus.ChainName {
return slices.Map(k.getCosmosChains(ctx), func(c types.CosmosChain) nexus.ChainName { return c.Name })
}
func (k Keeper) getCosmosChains(ctx sdk.Context) (cosmosChains []types.CosmosChain) {
iter := k.getStore(ctx).IteratorNew(cosmosChainPrefix)
defer utils.CloseLogError(iter, k.Logger(ctx))
for ; iter.Valid(); iter.Next() {
var cosmosChain types.CosmosChain
iter.UnmarshalValue(&cosmosChain)
cosmosChains = append(cosmosChains, cosmosChain)
}
return cosmosChains
}
// SetCosmosChain sets the address prefix for the given cosmos chain
func (k Keeper) SetCosmosChain(ctx sdk.Context, chain types.CosmosChain) error {
// register a cosmos chain to axelarnet
return k.getStore(ctx).SetNewValidated(cosmosChainPrefix.Append(key.From(chain.Name)), &chain)
}
// SetFeeCollector sets axelarnet fee collector
func (k Keeper) SetFeeCollector(ctx sdk.Context, address sdk.AccAddress) error {
if err := sdk.VerifyAddressFormat(address); err != nil {
return err
}
k.getStore(ctx).SetRawNew(feeCollector, address)
return nil
}
// GetFeeCollector gets axelarnet fee collector
func (k Keeper) GetFeeCollector(ctx sdk.Context) (sdk.AccAddress, bool) {
bz := k.getStore(ctx).GetRawNew(feeCollector)
if bz == nil {
return sdk.AccAddress{}, false
}
return bz, true
}
func (k Keeper) getStore(ctx sdk.Context) utils.KVStore {
return utils.NewNormalizedStore(ctx.KVStore(k.storeKey), k.cdc)
}
// GetIBCTransferQueue returns the queue of IBC transfers
func (k Keeper) GetIBCTransferQueue(ctx sdk.Context) utils.KVQueue {
return utils.NewGeneralKVQueue(
ibcTransferQueueName,
k.getStore(ctx),
k.Logger(ctx),
func(value codec.ProtoMarshaler) utils.Key {
transfer := value.(*types.IBCTransfer)
return utils.KeyFromBz(transfer.ID.Bytes())
},
)
}
func getTransferKey(id nexus.TransferID) key.Key {
return transferPrefix.Append(key.From(id))
}
// EnqueueIBCTransfer stores the pending ibc transfer in the queue
func (k Keeper) EnqueueIBCTransfer(ctx sdk.Context, transfer types.IBCTransfer) error {
transferKey := getTransferKey(transfer.ID)
if k.getStore(ctx).HasNew(transferKey) {
return fmt.Errorf("transfer %s already exists", transfer.ID.String())
}
k.GetIBCTransferQueue(ctx).Enqueue(utils.KeyFromBz(transferKey.Bytes()), &transfer)
return nil
}
// validateIBCTransferQueueState checks if the keys of the given map have the correct format to be imported as ibc transfer queue state.
func (k Keeper) validateIBCTransferQueueState(state utils.QueueState, queueName ...string) error {
if err := state.ValidateBasic(queueName...); err != nil {
return err
}
for _, item := range state.Items {
var transfer types.IBCTransfer
if err := k.cdc.UnmarshalLengthPrefixed(item.Value, &transfer); err != nil {
return err
}
if err := transfer.ValidateBasic(); err != nil {
return err
}
}
return nil
}
// GetTransfer returns the ibc transfer for the given transfer ID
func (k Keeper) GetTransfer(ctx sdk.Context, id nexus.TransferID) (transfer types.IBCTransfer, ok bool) {
k.getStore(ctx).GetNew(getTransferKey(id), &transfer)
return transfer, transfer.Status != types.TransferNonExistent
}
func (k Keeper) setTransfer(ctx sdk.Context, transfer types.IBCTransfer) error {
return k.getStore(ctx).SetNewValidated(getTransferKey(transfer.ID), &transfer)
}
func (k Keeper) setTransferStatus(ctx sdk.Context, transferID nexus.TransferID, status types.IBCTransfer_Status) error {
t, ok := k.GetTransfer(ctx, transferID)
if !ok {
return fmt.Errorf("transfer %s not found", transferID)
}
err := t.SetStatus(status)
if err != nil {
return err
}
return k.setTransfer(ctx, t)
}
// SetTransferCompleted sets the transfer as completed
func (k Keeper) SetTransferCompleted(ctx sdk.Context, transferID nexus.TransferID) error {
return k.setTransferStatus(ctx, transferID, types.TransferCompleted)
}
// SetTransferFailed sets the transfer as failed
func (k Keeper) SetTransferFailed(ctx sdk.Context, transferID nexus.TransferID) error {
return k.setTransferStatus(ctx, transferID, types.TransferFailed)
}
// SetTransferPending sets the transfer as pending
func (k Keeper) SetTransferPending(ctx sdk.Context, transferID nexus.TransferID) error {
return k.setTransferStatus(ctx, transferID, types.TransferPending)
}
func getSeqIDMappingKey(portID, channelID string, seq uint64) key.Key {
return seqIDMappingPrefix.
Append(key.FromStr(portID)).
Append(key.FromStr(channelID)).
Append(key.FromUInt(seq))
}
// SetSeqIDMapping sets transfer ID by port, channel and packet seq
func (k Keeper) SetSeqIDMapping(ctx sdk.Context, t types.IBCTransfer) error {
nextSeq, ok := k.channelK.GetNextSequenceSend(ctx, t.PortID, t.ChannelID)
if !ok {
return sdkerrors.Wrapf(
channeltypes.ErrSequenceSendNotFound,
"source port: %s, source channel: %s", t.PortID, t.ChannelID,
)
}
funcs.MustNoErr(
k.getStore(ctx).SetNewValidated(
getSeqIDMappingKey(t.PortID, t.ChannelID, nextSeq),
utils.NoValidation(&gogoprototypes.UInt64Value{Value: uint64(t.ID)}),
),
)
return nil
}
// GetSeqIDMapping gets transfer ID by port, channel and packet seq
func (k Keeper) GetSeqIDMapping(ctx sdk.Context, portID, channelID string, seq uint64) (nexus.TransferID, bool) {
var val gogoprototypes.UInt64Value
return nexus.TransferID(val.Value), k.getStore(ctx).GetNew(getSeqIDMappingKey(portID, channelID, seq), &val)
}
// DeleteSeqIDMapping deletes (port, channel, packet seq) -> transfer ID mapping
func (k Keeper) DeleteSeqIDMapping(ctx sdk.Context, portID, channelID string, seq uint64) {
k.getStore(ctx).DeleteRaw(getSeqIDMappingKey(portID, channelID, seq).Bytes())
}
func (k Keeper) getIBCTransfers(ctx sdk.Context) (transfers []types.IBCTransfer) {
iter := k.getStore(ctx).IteratorNew(transferPrefix)
defer utils.CloseLogError(iter, k.Logger(ctx))
for ; iter.Valid(); iter.Next() {
var t types.IBCTransfer
iter.UnmarshalValue(&t)
transfers = append(transfers, t)
}
return transfers
}
func (k Keeper) getSeqIDMappings(ctx sdk.Context) map[string]uint64 {
mapping := make(map[string]uint64)
iter := k.getStore(ctx).IteratorNew(seqIDMappingPrefix)
defer utils.CloseLogError(iter, k.Logger(ctx))
for ; iter.Valid(); iter.Next() {
var val gogoprototypes.UInt64Value
iter.UnmarshalValue(&val)
mapping[string(iter.Key())] = val.Value
}
return mapping
}
func getSeqMessageIDMappingKey(portID, channelID string, seq uint64) key.Key {
return seqGeneralMsgIDMappingPrefix.
Append(key.FromStr(portID)).
Append(key.FromStr(channelID)).
Append(key.FromUInt(seq))
}
// SetSeqMessageIDMapping sets general message ID by port, channel and packet seq
func (k Keeper) SetSeqMessageIDMapping(ctx sdk.Context, portID, channelID string, seq uint64, id string) error {
if _, found := k.GetSeqMessageIDMapping(ctx, portID, channelID, seq); found {
return fmt.Errorf("message ID already set for %s/%s %d", channelID, portID, seq)
}
funcs.MustNoErr(
k.getStore(ctx).SetNewValidated(
getSeqMessageIDMappingKey(portID, channelID, seq),
utils.NoValidation(&gogoprototypes.StringValue{Value: id}),
),
)
return nil
}
// GetSeqMessageIDMapping gets general message ID by port, channel and packet seq
func (k Keeper) GetSeqMessageIDMapping(ctx sdk.Context, portID, channelID string, seq uint64) (string, bool) {
var val gogoprototypes.StringValue
return val.Value, k.getStore(ctx).GetNew(getSeqMessageIDMappingKey(portID, channelID, seq), &val)
}
// DeleteSeqMessageIDMapping deletes (port, channel, packet seq) -> general message ID mapping
func (k Keeper) DeleteSeqMessageIDMapping(ctx sdk.Context, portID, channelID string, seq uint64) {
k.getStore(ctx).DeleteRaw(getSeqMessageIDMappingKey(portID, channelID, seq).Bytes())
} |
package arraylist_product;
import java.sql.*;
import java.util.ArrayList;
public class ProductDAO {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
public ProductDAO(){
try {
//JDBC Driver 클래스의 객체 생성 런타임시 로드
//Class.forName("com.mysql.cj.jdbc.Driver");
// 연결 주소, 사용자 계정, 패스워드 문자열 설정
String url = "jdbc:mysql://localhost:3306/sqldb2?serverTimezone=UTC";
String user = "root";
String pwd = "1234";
// DB 연결하기 위한 객체 생성
// DriverManager를 통해 Connection 객체 생성
// MySQL 서버 연결 : 주소, 사용자 계정, 패스워드 전송
con = DriverManager.getConnection(url, user, pwd);
// Connection 객체가 생성되면 DB 연결 성공
if(con != null) {
System.out.println("DB 연결 성공!");
}
} catch (Exception e) {
System.out.println("오류 발생!");
e.printStackTrace();
}
}
public ArrayList<ProductDTO> selectProduct() {
ArrayList<ProductDTO> dataSet = null;
try {
String sql = "select * from product order by prdNo";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery(sql);
dataSet = new ArrayList<ProductDTO>();
while(rs.next()) {
dataSet.add(new ProductDTO(rs.getString(1),
rs.getString(2),
rs.getInt(3),
rs.getString(4),
rs.getString(5),
rs.getInt(6)
));
}
} catch (Exception e) {
System.out.println("오류 발생");
e.printStackTrace();
}
return dataSet;
}
public void insertProduct(ProductDTO dto) {
try {
// sql문 작성
String sql = "insert into product values(?,?,?,?,?,?)";
pstmt = con.prepareStatement(sql);
pstmt.setString(1,dto.getPrdNo());
pstmt.setString(2,dto.getPrdName());
pstmt.setInt(3,dto.getPrdPrice());
pstmt.setString(4,dto.getPrdMaker());
pstmt.setString(5,dto.getPrdColor());
pstmt.setInt(6,dto.getCtgNo());
int result = pstmt.executeUpdate();
if(result > 0) System.out.println("데이터 입력 성공");
} catch (Exception e) {
System.out.println("오류 발생");
e.printStackTrace();
}
}
} |
import { useEffect } from 'react'
import Cookies from 'cookies'
import { useStoreActions } from 'easy-peasy'
import { House as HouseModel } from '../model.js'
import House from '../components/House'
import Layout from '../components/Layout'
export default function Home({ bnb_session, houses }) {
const setLoggedIn = useStoreActions((actions) => actions.login.setLoggedIn)
useEffect(() => {
if (bnb_session) {
setLoggedIn(true)
}
}, [bnb_session, setLoggedIn])
return <Layout content={
<div>
<h2>Places to stay</h2>
<div className="houses">
{houses.map((house, index) => {
return <House key={index} {...house} />
})}
</div>
<style jsx>{`
.houses {
display: grid;
grid-template-columns: 49% 49%;
grid-template-rows: 300px 300px;
grid-gap: 2%;
}
`}</style>
</div>
}
/>
}
export async function getServerSideProps({ req, res, query }) {
const cookies = new Cookies(req, res)
const bnb_session = cookies.get('bnb_session')
const houses = await HouseModel.findAndCountAll()
return {
props: {
bnb_session: bnb_session || null,
houses: houses.rows.map((house) => house.dataValues)
}
}
} |
using System.ComponentModel;
using Exiled.API.Interfaces;
namespace TTAddons
{
public class Config : IConfig
{
public bool IsEnabled { get; set; } = true;
public bool Debug { get; set; } = false;
[Description ("Allow SCP players to use the .unstuck command. Default is true.")]
public bool AllowUnstuckForScps { get; set; } = true;
[Description ("The time in seconds that SCPs can use the .unstuck command. Default is 30 seconds.")]
public int UnstuckTime { get; set; } = 30;
[Description("Chance of a player spawning as SCP-3114 (0-1)f. Default is 0.05.")]
public float Scp3114Chance { get; set; } = 0.05f;
[Description("Minimum players required to spawn SCP-3114. Default is 10.")]
public int Scp3114MinPlayers { get; set; } = 10;
[Description("True: Choose an SCP to replace with 3114, False: Choose a ClassD to replace with 3114. Default is false.")]
public bool Scp3114ReplaceScp { get; set; } = false;
[Description("Enable spectator lobby game. Default is true.")]
public bool EnableSpectatorGame { get; set; } = false;
[Description("Enable weapon stats. Default is true.")]
public bool EnableWeaponStats { get; set; } = false;
[Description("How long do Zombies get spawn protection for? Allows resurrecting players in Tesla gates. Default is 3f seconds.")]
public float Scp0492SpawnProtection { get; set; } = 3f;
[Description("Enable SCP-049 resurrection logic replacement? Allows changing maximum zombie resurrections, how long they have to revive, etc. Default is false.")]
public bool ReplaceScp049ResurrectLogic { get; set; } = false;
[Description("How many times can Scp049 resurrect a player? Default is 2.")]
public int Scp049MaxResurrections { get; set; } = 2;
[Description("How long does Scp049 have to resurrect a player that was a target of 'Doctor's good sense'? Default is 18f seconds.")]
public float Scp049TargetCorpseDuration { get; set; } = 18f;
[Description("How long does Scp049 have to resurrect a normal player? Default is 12f seconds.")]
public float Scp049HumanCorpseDuration { get; set; } = 12f;
[Description("How much Hume Shield does Scp049 get for resurrecting a player? Default is 200f.")]
public float Scp049ResurrectTargetReward { get; set; } = 200f;
[Description("Should Scp079's experience scale with player count? Default is false")]
public bool EnableScp079XpScaling { get; set; } = false;
[Description("Base player count for Scp079 experience scaling. Smaller numbers make the SCP weaker at higher player counts, bigger numbers make the SCP stronger at lower player counts. Default is 15.")]
public int Scp079BasePlayerCount { get; set; } = 15;
}
} |
package com.test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* 执行静态块 initEnums==={0=北京市, 1=北京市, 2=云南省} initEnums==={0=北京市, 1=北京市, 2=云南省}
* 执行getInstance 执行getCache {0=北京市, 1=北京市, 2=云南省}
*
* @author lzl
*
*/
public class CachingEnumResolver1 {
private static final CachingEnumResolver1 SINGLE_ENUM_RESOLVER;
public static Map CODE_MAP_CACHE;
public static String test="testonwe";
static {
System.out.println("执行静态块");
CODE_MAP_CACHE = new HashMap();
// 为了说明问题,我在这里初始化一条数据
CODE_MAP_CACHE.put("0", "北京市");
SINGLE_ENUM_RESOLVER = new CachingEnumResolver1();
initEnums();
}
// private, for single instance
public CachingEnumResolver1() {
// 初始化加载数据 引起问题,该方法也要负点责任
initEnums();
}
/**
* 初始化所有的枚举类型
*/
public static void initEnums() {
// ~~~~~~~~~问题从这里开始暴露 ~~~~~~~~~~~//
if (null == CODE_MAP_CACHE) {
System.out.println("CODE_MAP_CACHE为空,问题在这里开始暴露.");
CODE_MAP_CACHE = new HashMap();
}
CODE_MAP_CACHE.put("1", "北京市");
CODE_MAP_CACHE.put("2", "云南省");
System.out.println("initEnums===" + CODE_MAP_CACHE.toString());
// ..... other code...
}
public Map getCache() {
System.out.println("执行getCache");
return Collections.unmodifiableMap(CODE_MAP_CACHE);
}
public String test(){
System.out.println("执行test");
return "test";
}
/**
* 获取单态实例
*
* @return
*/
public static CachingEnumResolver1 getInstance() {
System.out.println("执行getInstance");
return SINGLE_ENUM_RESOLVER;
}
public static void main(String[] args) {
System.out.println(CachingEnumResolver1.test);
System.out.println(CachingEnumResolver1.getInstance().getCache());
System.out.println(CachingEnumResolver1.getInstance().getCache());
System.out.println(new CachingEnumResolver1().test());
}
} |
package com.trad.trad.application.controller.implementation;
import com.trad.trad.application.controller.api.IUserApi;
import com.trad.trad.application.security.AuthCredentials;
import com.trad.trad.application.security.AuthenticationResponse;
import com.trad.trad.domain.dto.UserDto;
import com.trad.trad.domain.dto.ValidAccountDto;
import com.trad.trad.domain.exception.TradAppException;
import com.trad.trad.domain.services.Interfaz.IAuthenticationUser;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserImp implements IUserApi {
@Autowired
private IAuthenticationUser iAuthenticationUser;
@Override
public ResponseEntity<AuthenticationResponse> login(AuthCredentials credentials) {
try {
return ResponseEntity.ok(iAuthenticationUser.generateToken(credentials));
}catch (BadCredentialsException err ){
return new ResponseEntity<>(new AuthenticationResponse(err.getMessage()), HttpStatus.UNAUTHORIZED );
}
}
@Override
public ResponseEntity<UserDto> registerUser(@Valid UserDto userDto ) {
return new ResponseEntity<>(iAuthenticationUser.registerUser(userDto) , HttpStatus.CREATED );
}
@Override
public ResponseEntity<String> validAccount(@Valid ValidAccountDto validatedAccount) {
try {
return ResponseEntity.ok().body("Estado: " + iAuthenticationUser.validAccount(validatedAccount) );
}catch (TradAppException ex){
return new ResponseEntity<>(ex.getMessage(),ex.getHttpStatusCode());
}
}
} |
const fs = require('fs'); // to read input file contents
const readline = require('readline'); // to read user input (i.e. file_name)
const isCompounded = (word, unique_words) => {
// base condition
if (unique_words.has(word)) {
return true;
}
for (let i = 1; i < word.length; i++) {
const prefix = word.slice(0, i);
const suffix = word.slice(i);
/* only if the current prefix is found to exist as a word
in words then only go for the rest of the suffix */
if (unique_words.has(prefix) && isCompounded(suffix, unique_words)) {
return true;
}
}
return false;
}
const find_longestCompoundedWord = (words) => {
/* sorting words in decreasing order of their lengths so that the very
first compounded word which we get is automatically the longest possible */
words.sort((a, b) => b.length - a.length);
// making a collections of unique words
const unique_words = new Set(words);
for (const word of words) {
/* delete the current word from unique_words so that any
prefix or suffix doesn't match to the word itself */
unique_words.delete(word);
if (isCompounded(word, unique_words)) {
return word;
}
}
// if not found return null
return null;
}
const publishOutput = ({
longestCompoundWord,
secondLongestCompoundWord,
timeTaken,
file_name
}) => {
console.log(`Longest Compound Word: ${
longestCompoundWord == null
? "couldn't locate 🔍 for 1st longest compound word"
: longestCompoundWord}`);
console.log(`Second Longest Compound Word: ${
secondLongestCompoundWord == null
? "couldn't locate 🔍 for 2nd longest compound word"
: secondLongestCompoundWord}`);
console.log(`Time taken to process file ${file_name}: ${timeTaken} milliseconds`);
}
const getUserInput = (file_name) => {
/* creating a relative path for file
example: current_directory + '/' + file_name */
const relativePath = process.cwd() + '/' + file_name;
const start_time = Date.now();
// extract all the words from Input_0?.txt file and make an array out of those words
const words = fs.readFileSync(relativePath, 'utf8')
.split('\n')
.map(word => word.trim()) // to remove '/r' from end of extracted words
.filter(word => word !== ''); // just a pre-cautionary search to filter out any unnecessary empty string
// longest compound word
const longestCompoundWord = find_longestCompoundedWord(words);
// slice-off longest compound word from words array
words.splice(words.indexOf(longestCompoundWord), 1);
// find second longest compound word
const secondLongestCompoundWord = find_longestCompoundedWord(words);
const end_time = Date.now();
const timeTaken = end_time - start_time;
// publish the output
publishOutput({
longestCompoundWord,
secondLongestCompoundWord,
timeTaken,
file_name
});
}
/* creating an interface named 'read_line' to interact with user via creating
prompts and taking in the response (which is the file_name) as input for the
call_back function to initiate the process of finding longest compound word */
const read_line = readline.createInterface({
input: process.stdin,
output: process.stdout
});
read_line.question('Enter the file name: ', (file_name) => {
getUserInput(file_name);
read_line.close();
}); |
import React from "react";
import course from "../constants/Course";
const CourseMain = () => {
return (
<div className="bg-gray-50 dark:bg-gray-900 min-h-screen py-12">
<div className="text-center mx-auto text-black dark:text-white container py-10 font-poppins border-b-4 border-blue-500 dark:border-indigo-500">
<h1 className="text-3xl sm:text-4xl font-bold">Our Courses</h1>
</div>
<div className="container mx-auto grid gap-8 grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 py-14">
{course.map((c) => (
<div
key={c.key}
className="bg-white dark:bg-gray-800 rounded-lg shadow-lg overflow-hidden hover:shadow-2xl transition-all ease-in-out duration-300 hover:scale-105 transform"
>
<img
src={c.img}
alt={c.name}
className="w-full h-56 object-cover"
/>
<div className="p-6 flex flex-col">
<h2 className="text-xl font-bold mb-4 text-center text-gray-800 dark:text-gray-100 border-b-2 border-gray-300 dark:border-gray-700 pb-2">
{c.name}
</h2>
<p className="text-gray-600 dark:text-gray-300">{c.text}</p>
</div>
</div>
))}
</div>
</div>
);
};
export default CourseMain; |
import {useState} from "react";
import Image from "../assets/ayushmann.png";
const About = () => {
const[data, setData] = useState({
image:Image,
title:"Software and Java Developer",
desc1: `A Java and Software Developer with extensive experience in object-oriented programming(OOPs) and software development life
cycle (SDLC) processes. I have hands-on experience with Java
development. Alongside Java. Throughout my academic career and
personal projects, I've created web applications and front-end
projects that demonstrate my ability to design, develop, and
deploy software solutions.`,
desc2: `I've built dynamic web pages with Reactjs, HTML, CSS, and JavaScript, integrated databases like
MySQL, and implemented Java-based APIs with JDBC for database
connectivity. I am available for any kind of job opportunity that suits my skills and interests.`,
})
return (
<>
<div id="about" className="Main-Container py-12 ">
<h1 className="text-center p-6 mb-14 text-4xl bg-slate-300 font-bold">
About Me
</h1>
{/* Image */}
<div className="flex items-center">
<div className="w-full flex justify-center">
<img
className="rounded-3xl shadow w-fit"
src={data.image}
alt="Ayushman"
/>
</div>
{/* Description */}
<div className="w-full flex justify-center">
<div className="space-y-5 w-2/3">
<h1 className="text-4xl font-semibold">{data.title}</h1>
<p>{data.desc1}</p>
<p>{data.desc2}</p>
<br />
</div>
</div>
</div>
</div>
</>
);
};
export default About; |
import PropTypes from 'prop-types';
import css from "./FriendList.module.css";
import FriendListItem from './FriendListItem';
const FriendList = ({ friends }) => {
return (
<ul className={css.friendList}>
{friends.map(friend => (
<FriendListItem key={friend.id} {...friend} />
))}
</ul>
);
};
FriendList.propTypes = {
friends: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.number.isRequired,
})
),
};
export default FriendList; |
# 关于 JavaScript 运行时应该知道的一切
> 原文:<https://levelup.gitconnected.com/dev-explainer-javascript-runtimes-8e4d1e3af405>

作者图片
JavaScript 可能是有史以来最有影响力的编程语言之一(不管是好是坏)——它可以在几乎所有现代网络浏览器中运行,不管是什么操作系统。无论你是在 MacOS、Windows 还是 Linux 上使用 Safari、Chrome 还是 Firefox,JavaScript 都会在后台运行(除非你禁用它)。
然而,JavaScript(参见 [ECMAScript](https://www.ecma-international.org/publications-and-standards/standards/ecma-262/) )只是一种编程语言:一种计算机应该如何解释 ASCII 字符序列的抽象规范。为了实际执行 JavaScript 代码,你需要一个名为*运行时*(又名*引擎*)的程序。每个现代的网络浏览器都捆绑了一个 JavaScript 运行时。Chrome 用的是 V8 引擎,Firefox 用的是 SpiderMonkey,Safari 用的是 WebKit/JavaScriptCore。
最近,出现了在 web 浏览器之外执行 Javascript 代码的趋势。现在有多个 JavaScript 运行时被设计为在“服务器端”执行 JavaScript(也称为独立程序,类似于 Python 或 Java 等其他编程语言)。在本文中,我将简要介绍 JavaScript 运行时的当前状态及其各种优缺点。
# 浏览器运行时(V8、SpiderMonkey、Webkit 等)
我将所有这些都打包到本节中,因为它们并不是本文的重点。虽然这些引擎*可以独立使用*,但它们的主要目的是嵌入到另一个应用程序中。它们支持您最喜欢的 web 浏览器,以及我将在下面讨论的其他运行时。但是,您通常不会使用它们,比如说,通过命令行在本地运行 web 服务器。
# NodeJS

2015 年 NodeJS 标志,取自维基共享
目前最流行的服务器端 JS 运行时是 [NodeJS](https://nodejs.org/) ,基于 V8。NodeJS 广泛用于开发 web 服务器、web apps、API 等。NodeJS 使用 [npm](https://www.npmjs.com/) 包管理器,它拥有数百万个现成的库,几乎可以满足你所能想象到的所有用例。
NodeJS 本身有很多特性——它的事件循环支持异步编程;它是跨平台的;其标准库支持网络请求、与操作系统/文件系统接口、使用 REPL/TTY 等。
然而,你通常会看到 NodeJS 与非常流行的库一起使用,例如 [React](https://reactjs.org/) 、 [Express](https://expressjs.com/) 、 [Lodash](https://lodash.com/) 、 [Axios](https://github.com/axios/axios) 等。这些库为互联网提供了很大一部分动力,你会发现一个接一个的教程解释如何使用它们。
然而,NodeJS 也不是没有问题。如此庞大的生态系统,碎片化和安全问题肯定会出现。
为了使用基于 NodeJS 的框架部署网站或应用程序,您需要使用*捆绑器*将所有代码打包在一起。你必须在[汇总](https://rollupjs.org/guide/en/)、[包裹](https://parceljs.org/)、[网络包](https://webpack.js.org/)、 [esbuild](https://esbuild.github.io/) 、 [vite](https://vitejs.dev/) 、 [snowpack](https://www.snowpack.dev/) 等之间做出选择。如果你陷入配置地狱,太糟糕了!您应该使用`npx xxx-create-app`来为您生成所有的配置文件。对于一个新的开发人员来说,弄清楚所有这些工具之间的区别并选择正确的选项是非常令人困惑的。
对于 NodeJS 来说,处理依赖关系也是一件痛苦的事情。众所周知,运行一个`npm install`会带来数百个包,社区中一个常见的抱怨是`node_modules`文件夹太大,它存储了一个项目所有下载的依赖项。
此外,还有一些潜在的安全问题,您必须妥善处理。恶意行为者可以将一个恶意软件设计为 npm 包,然后将其偷偷放入某个包的依赖列表中,该包依赖于某个包,而该包又依赖于某个包,该包又依赖于 React 等流行库。如果一个包被移除,如此深的依赖链也会导致问题——还记得移除[左填充](https://qz.com/646467/how-one-programmer-broke-the-internet-by-deleting-a-tiny-piece-of-code/)导致互联网暂时中断吗?
这些问题中的一些可以通过诸如[纱线](https://yarnpkg.com/)、[精梳机](https://bower.io/)或 [pnpm](https://pnpm.io/) 的替代品来缓解。但是,npm 仍然是标准,现在每个 JS 库都有 5 个不同的安装命令(当然我是夸大了,但是看这个[例子](https://github.com/axios/axios#installing)和这个[相关的 XKCD](https://xkcd.com/927/) )。
但同样,NodeJS 的受欢迎程度是不可低估的。它最好的资产是它庞大的生态系统,你会发现 NodeJS 提供了你创建下一个伟大的 web 应用所需的一切。
# 德诺

Deno 标志,取自维基共享资源
NodeJS 是多年来的标准,但是现在, [Deno](https://deno.land/) 是这个街区的新成员。Deno 于 2018 年发布,是 NodeJS 的更现代版本。事实上,Deno 和 NodeJS 拥有同一个创造者:瑞安·达尔(Ryan Dahl)。另外,两个运行时都是基于 V8 引擎的(虽然 Deno 是用 [Rust](https://www.rust-lang.org/) 写的,而 NodeJS 用的是 C++)。
Deno 的编写是为了解决 NodeJS 的各种缺点,从安全性到可用性。Deno 是“默认安全的”——如果 Deno 代码需要访问文件系统或发出网络请求,您需要显式地提供许可。此外,Deno 是作为一个一体化的可执行文件发布的,它提供了一流的类型脚本支持,用`deno {lint,fmt}`进行林挺/格式化,用`deno bundle`进行捆绑,用`deno test`进行测试运行,等等。
Deno 处理依赖关系的方式也与 NodeJS 完全不同。远程依赖项直接从 URL 导入。比如可以用`import * as oak from "https://deno.land/x/oak@v10.6.0/mod.ts";`导入 [oak](https://deno.land/x/oak@v10.6.0/mod.ts) ,一个 HTTP 框架。Deno 然后将处理依赖关系管理——它将下载包并在本地缓存它们。一种常见的模式是使用单个`deps.ts`文件来导入远程库,并在本地重新导出它们以供其他 JavaScript 或 TypeScript 文件使用。
总的来说,Deno 生态系统要比 NodeJS 小很多。Node 有一个实验性的兼容模式(见这里的),但是它并不是 100%的时候都能工作。另一方面,Deno 有自己的一系列新的有趣的 web 库,如 [fresh](https://fresh.deno.dev/) (一个全栈 web 框架) [oak](https://deno.land/x/oak@v10.6.0/mod.ts) (一个 HTTP 路由器),以及 [ultra](https://github.com/exhibitionist-digital/ultra) (一个流 SSR 框架)。此外,像 [Lodash](https://deno.land/x/lodash@4.17.19) 、 [day.js](https://deno.land/x/dayjs@v1.11.5) 和 [xstate](https://deno.land/x/xstate@xstate%404.33.1) 这样的流行节点库都是由 Deno 支持的,托管在`deno.land/x`上。更不用说,Deno 有一套经过审核的标准模块,涵盖了许多使用案例,包括操作系统/文件系统交互、I/O、网络请求、加密等。
关于生态系统的话题,Deno 官方提供的一个不可忽视的独特 web 服务是 [Deno Deploy](https://deno.com/deploy) 。Deno Deploy 允许您在全球范围内部署 Deno 代码——考虑通用的无服务器功能(例如 AWS Lambda 或 Google Cloud 功能)。Deno Deploy 可以用来托管网站、代理 API 服务、处理表单/POST 请求等等。目前,Deno Deploy 有一个免费的产品,支持每天 100,000 个请求和每月 100 GiB 的数据传输(本文没有赞助,我只是觉得这真的很酷)。
虽然 Deno 还没有杀死 NodeJS(可能永远也不会),但它是一个很好的替代品,已经被 Slack、Netlify 和 Github 等公司使用。如果你没有义务使用 NodeJS,我肯定会在你的下一个项目中尝试 Deno。
# 小圆面包

Bun 标志,取自 Bun 的 Github 项目页面
如果 Deno 是这个街区的新成员,Bun 就是这个街区更新的成员。它由贾里德·萨姆纳(Jarred Sumner)于 2021 年底发布,并立即在网上掀起波澜。Bun 的主要产品是它的速度——它声称启动速度比 NodeJS 快 4 倍,在各种情况下运行 JavaScript 比 NodeJS/Deno 快 2 到 3 倍。
这怎么可能呢?嗯,Bun 是用 [Zig](https://ziglang.org/) 编写的,这是一种低级的 C 语言替代,它从一开始就针对速度进行了优化——它的大部分代码都是从头开始编写的。它使用 JavaScriptCore 作为后端 JS 引擎。
除了性能,Bun 标榜的是很棒的可用性,就像 Deno 一样。Bun 由一个可执行文件组成,它包括一个 TypeScript transpiler、内置 bundler、task runner 和 package manager,所有这些都比它们的 NodeJS 等价物更快。
Bun 使用与 NodeJS 相同的模块解析算法,这使得它与 npm 兼容。它还实现了 Node 的大部分 API,这允许它与本机节点模块一起工作。总的来说,Bun 的目标是用一个快速、易用的包来代替与 NodeJS 相关的打包程序、传输程序和包管理程序。
Bun 出现的时间不长,我们只能等着看它是否会在现代 JS 生态系统中站稳脚跟。不过,基于它的速度和 NodeJS 兼容性,似乎 Bun 会有一个光明的未来。
# 各种嵌入式 JS 运行时
令人惊讶的是,JS 也被用在微控制器等嵌入式设备上。出现了一些可嵌入的运行时,它们都在极端的 CPU 和内存使用要求下执行 JavaScript 代码。
* [Duk tape](https://github.com/svaarala/duktape)——专注于可移植性和紧凑尺寸的嵌入式 Javascript 引擎
* [Elk](https://github.com/cesanta/elk)——一个用于嵌入式系统的低占用空间的 JavaScript 引擎
* Espruino —一个用于微控制器的 JavaScript 解释器,只有 128kB 闪存和 8kB RAM。
# 接下来呢?
JavaScript/TypeScript 运行时生态系统似乎仍在发展。成千上万的工时被用来提高 JavaScript 的速度,然而 Bun 表明仍有很大的改进潜力。同时,Deno 正在展示可用性和简单性在现代开发工具中的重要性。我期待看到 JavaScript 的前景在未来会如何继续变化。
Edit (8/15/22): Deno just [宣布](https://deno.com/blog/changes)他们正在努力提高 npm 兼容性,他们的目标是“让 Deno 成为最快的 JavaScript 运行时”。这可能是他们对 Bun 的反应吗?我很期待看到事情的发展。
# 分级编码
感谢您成为我们社区的一员!在你离开之前:
* 👏为故事鼓掌,跟着作者走👉
* 📰查看[级编码出版物](https://levelup.gitconnected.com/?utm_source=pub&utm_medium=post)中的更多内容
* 🔔关注我们:[推特](https://twitter.com/gitconnected) | [LinkedIn](https://www.linkedin.com/company/gitconnected) | [时事通讯](https://newsletter.levelup.dev)
🚀👉 [**加入升级人才集体,找到一份惊艳的工作**](https://jobs.levelup.dev/talent/welcome?referral=true) |
import dotenv from "dotenv";
dotenv.config();
import express from "express";
import cors from "cors";
import connectDB from "./config/db.js";
import connectCloudinary from "./config/cloudinary.js";
import adminRouter from "./routes/adminRoute.js";
import doctorRouter from "./routes/doctorRoute.js";
import userRouter from "./routes/userRoute.js";
//app config
const app = express();
const PORT = process.env.PORT || 4000;
connectCloudinary();
//middlewares
app.use(express.json());
app.use(cors());
//api end points
app.use("/api/admin", adminRouter); //api for admin
app.use("/api/doctor", doctorRouter); //api for doctors
app.use("/api/user", userRouter); //api for users
//start server
const startServer = async () => {
try {
await connectDB();
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
} catch (err) {
console.error(`Failed to start server: ${err.message}`);
process.exit(1);
}
};
startServer(); |
import General.Hitbox;
import processing.core.PApplet;
/**
* Represents an abstract obstacle in the game.
* This class extends {@link GameObject} with added behaviors specific to game obstacles,
* such as automatic movement and position checking.
* <p>
* Specific types of obstacles should extend this class and implement the {@code checkPosition} method
* to define custom behaviors on movement boundaries or interactions with other game objects.
*/
public abstract class Obstacle extends GameObject {
/**
* Constructs an Obstacle with specified dimensions, movement speed, starting position, and hitbox.
*
* @param width The width of the obstacle in 'chunks'.
* @param movementSpeed The speed at which the obstacle moves.
* @param startPositionX The starting X coordinate of the obstacle.
* @param hitboxRelative The relative hitbox of the obstacle for collision detection.
*/
public Obstacle(int width, double movementSpeed, int startPositionX, Hitbox hitboxRelative) {
super(width, movementSpeed, startPositionX, hitboxRelative);
}
/**
* Constructs an Obstacle with specified dimensions and movement speed, starting position, but without a custom hitbox.
* <p>
* This constructor creates an obstacle with a default hitbox same size as the game object.
*
* @param width The width of the obstacle in 'chunks'.
* @param movementSpeed The speed at which the obstacle moves.
* @param startPositionX The starting X coordinate of the obstacle.
*/
public Obstacle(int width, int movementSpeed, int startPositionX) {
this(width, movementSpeed, startPositionX, new Hitbox(0, 0, 0, 0));
}
/**
* This method is used to check and update the obstacle's position.
* Implementations should ensure the obstacle adheres to game boundaries and
* interacts with the game environment as expected.
* <p>
* It must be implemented by subclasses to define specific obstacle behavior.
*/
protected abstract void checkPosition();
/**
* Draws the obstacle on the given PApplet canvas and updates its position according to its fixed movement.
* <p>
* This method overrides the {@code draw} method in {@link GameObject} to include automatic movement and position checking before drawing.
*
* @param pApplet The PApplet instance (canvas) on which to draw the obstacle.
*/
public void draw(PApplet pApplet) {
setFixedMovementX(getFixedMovementX() + getMovementSpeed());
checkPosition();
super.draw(pApplet);
}
} |
import { FC } from 'react'
import { Toaster } from 'react-hot-toast'
import { Provider } from 'react-redux'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import { PersistGate } from 'redux-persist/integration/react'
import { ThemeProvider } from 'styled-components'
import { AppLayout } from './components'
import { persistor, store } from './redux'
import { Global, ROUTES, theme } from './utils'
import { CourseView, HomeView, InviteView, Login, Profile, Register, Settings } from './views'
const App: FC = () => {
return (
<Provider store={store}>
<PersistGate persistor={persistor}>
<ThemeProvider theme={theme}>
<Global />
<Router>
<Switch>
<Route path={ROUTES.App.login} component={Login} />
<Route path={ROUTES.App.register} component={Register} />
<AppLayout>
<Switch>
<Route path={ROUTES.App.home} component={HomeView} exact />
<Route path={ROUTES.App.course} component={CourseView} />
<Route path={ROUTES.App.invite} component={InviteView} />
<Route path={ROUTES.App.settings} component={Settings} />
<Route path={ROUTES.App.profile} component={Profile} />
</Switch>
</AppLayout>
</Switch>
</Router>
<Toaster position="bottom-center" />
</ThemeProvider>
</PersistGate>
</Provider>
)
}
export default App |
"use client";
import React from "react";
import Image from "next/image";
import Promote from "../../../public/insurance/promote.png";
import { motion } from "framer-motion";
import { useInView } from "react-intersection-observer";
const Unique = () => {
// Separate useInView hooks for each section
const { ref: titleRef, inView: titleInView } = useInView({
triggerOnce: true,
threshold: 0.2,
});
const { ref: card1Ref, inView: card1InView } = useInView({
triggerOnce: true,
threshold: 0.2,
});
const { ref: card2Ref, inView: card2InView } = useInView({
triggerOnce: true,
threshold: 0.2,
});
const { ref: card3Ref, inView: card3InView } = useInView({
triggerOnce: true,
threshold: 0.5,
});
const { ref: card4Ref, inView: card4InView } = useInView({
triggerOnce: true,
threshold: 0.5,
});
const { ref: card5Ref, inView: card5InView } = useInView({
triggerOnce: true,
threshold: 0.5,
});
const { ref: imageRef, inView: imageInView } = useInView({
triggerOnce: true,
threshold: 0.5,
});
return (
<div className="w-full h-auto flex flex-col items-center gap-14">
<div className="w-full bg-white flex flex-col lg:flex-row items-center justify-between p-5 gap-10">
<div className="flex flex-col items-start gap-14 w-full lg:w-2/4">
{/* Title and Divider */}
<motion.div
ref={titleRef}
initial={{ opacity: 0, x: -100 }}
animate={{ opacity: titleInView ? 1 : 0, x: titleInView ? 0 : -100 }}
transition={{ duration: 0.6 }}
className="flex flex-col items-start gap-3"
>
<h1 className="text-3xl lg:text-4xl font-extrabold">What makes us Different?</h1>
<hr className="w-96 h-0.5 bg-slate-200" />
</motion.div>
{/* Cards Section */}
<div className="flex flex-col items-start gap-4 w-full p-5">
{/* Card 1 */}
<motion.div
ref={card1Ref}
initial={{ opacity: 0, x: -100 }}
animate={{ opacity: card1InView ? 1 : 0, x: card1InView ? 0 : -100 }}
transition={{ duration: 0.5, delay: 0.1 }}
className="w-full lg:w-96 desktop3xl:w-1/2 h-32 desktop3xl:h-44 bg-white shadow-lg border border-x border-slate-200 rounded-lg flex items-center justify-center phone:justify-start hover:bg-[#000f23] transition-all ease-in-out duration-700 hover:text-white p-3 phone:h-36"
>
<div className="flex items-start gap-6 p-3 w-full">
<div className="bg-[#0040FF] w-10 h-10 p-4 rounded-full flex items-center justify-center text-white font-bold phone:p-4">1</div>
<div className="flex flex-col items-start gap-3 w-full">
<h1 className="text-lg font-bold">Real-Solutions</h1>
<p className="text-sm font-medium">Seamless support and claim assistance.</p>
</div>
</div>
</motion.div>
{/* Card 2 */}
<div className="w-full flex items-end justify-end ">
<motion.div
ref={card2Ref}
initial={{ opacity: 0, x: 100 }}
animate={{ opacity: card2InView ? 1 : 0, x: card2InView ? 0 : 100 }}
transition={{ duration: 0.5, delay: 0.1 }}
className="w-full lg:w-96 h-32 desktop3xl:w-1/2 desktop3xl:h-44 bg-white shadow-lg border border-x border-slate-200 rounded-lg flex items-center justify-center phone:justify-start hover:bg-[#000f23] transition-all ease-in-out duration-700 hover:text-white p-3 phone:h-36"
>
<div className="flex items-start gap-6 p-3">
<div className="bg-[#0040FF] w-10 h-10 rounded-full p-4 flex items-center justify-center text-white font-bold phone:p-4">2</div>
<div className="flex flex-col items-start gap-3">
<h1 className="text-lg font-bold">Diverse Insurance Products</h1>
<p className="text-sm font-medium">Comprehensive coverage options.</p>
</div>
</div>
</motion.div>
</div>
{/* Card 3 */}
<motion.div
ref={card3Ref}
initial={{ opacity: 0, x: -100 }}
animate={{ opacity: card3InView ? 1 : 0, x: card3InView ? 0 : -100 }}
transition={{ duration: 0.5, delay: 0.1 }}
className="w-full lg:w-96 h-32 desktop3xl:w-1/2 desktop3xl:h-44 bg-white shadow-lg border border-x border-slate-200 rounded-lg flex items-center justify-center phone:justify-start hover:bg-[#000f23] transition-all ease-in-out duration-700 hover:text-white p-3 phone:h-36"
>
<div className="flex items-start gap-6 p-3">
<div className="bg-[#0040FF] w-10 h-10 rounded-full p-4 flex items-center justify-center text-white font-bold phone:p-4">3</div>
<div className="flex flex-col items-start gap-3">
<h1 className="text-lg font-bold">Local Experts</h1>
<p className="text-sm font-medium">Knowledgeable team providing personalized care.</p>
</div>
</div>
</motion.div>
{/* Card 4 */}
<div className="flex w-full items-end justify-end">
<motion.div
ref={card4Ref}
initial={{ opacity: 0, x: 100 }}
animate={{ opacity: card4InView ? 1 : 0, x: card4InView ? 0 : 100 }}
transition={{ duration: 0.5, delay: 0.1 }}
className="w-full lg:w-96 h-32 desktop3xl:w-1/2 desktop3xl:h-44 bg-white shadow-lg border border-x border-slate-200 rounded-lg flex items-center justify-center phone:justify-start hover:bg-[#000f23] transition-all ease-in-out duration-700 hover:text-white p-3 phone:h-36"
>
<div className="flex items-start gap-6 p-3">
<div className="bg-[#0040FF] w-10 h-10 rounded-full p-4 flex items-center justify-center text-white font-bold phone:p-4">4</div>
<div className="flex flex-col items-start gap-3">
<h1 className="text-lg font-bold">Flexible Plans</h1>
<p className="text-sm font-medium">Customized insurance plans for diverse needs.</p>
</div>
</div>
</motion.div>
</div>
{/* Card 5 */}
<motion.div
ref={card5Ref}
initial={{ opacity: 0, x: -100 }}
animate={{ opacity: card5InView ? 1 : 0, x: card5InView ? 0 : -100 }}
transition={{ duration: 0.5, delay: 0.1 }}
className="w-full lg:w-96 h-32 desktop3xl:w-1/2 desktop3xl:h-44 bg-white shadow-lg border border-x border-slate-200 rounded-lg flex items-center justify-center phone:justify-start hover:bg-[#000f23] transition-all ease-in-out duration-700 hover:text-white p-3 phone:h-36"
>
<div className="flex items-start gap-6 p-3">
<div className="bg-[#0040FF] w-10 h-10 rounded-full p-4 flex items-center justify-center text-white font-bold phone:p-4">5</div>
<div className="flex flex-col items-start gap-3">
<h1 className="text-lg font-bold">24/7 Customer Support</h1>
<p className="text-sm font-medium">Round-the-clock assistance for queries and issues.</p>
</div>
</div>
</motion.div>
</div>
</div>
{/* Image Section with Slide In Animation */}
<motion.div
ref={imageRef}
initial={{ opacity: 0, x: 100 }}
animate={{ opacity: imageInView ? 1 : 0, x: imageInView ? 0 : 100 }}
transition={{ duration: 0.6 }}
className="w-full lg:w-3/5 h-96 lg:h-3/4"
>
<Image
src={Promote}
width={7680}
height={4320}
alt="promote Image"
className="w-full h-full object-cover rounded-2xl"
/>
</motion.div>
</div>
</div>
);
};
export default Unique; |
#include "dryfruit.hpp"
#include "alcohol.hpp"
#include "cargo.hpp"
#include "fruit.hpp"
#include "item.hpp"
#include "ship.hpp"
#include "weapon.hpp"
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
int main() {
//setting up the ship no.1
Ship ship1(196, "Flying Dutch", 30, 50, 100000); //id, name, speed, max_crew, capacity
Ship ship2(598, "Black Pearl", 120, 34, 500);
//adding crew members
// ship2 += 14;
//ships data
ship1.printData();
ship2.printData();
//declaring cargo stuff
std::shared_ptr<Cargo> apples = std::make_shared<Fruit>("Apples", 10000, 1, 30); //name, amount, basePrice, expiryDays
std::shared_ptr<Cargo> rum = std::make_shared<Alcohol>("Rum", 250, 10, 40.0); //name, amount, basePrice, alcoholPercentage
std::shared_ptr<Cargo> ferrari = std::make_shared<Item>("Golden Armour", 1, 1000000, Rarity::Almost_Unavailable); //name, amount, basePrice, rarity
std::shared_ptr<Cargo> guns = std::make_shared<Weapon>("Sword", 200, 2, 25, Rarity::Common); //name, amount, basePrice, damage, rarity
std::shared_ptr<Cargo> dryFruits = std::make_shared<DryFruit>("Carrots", 500, 2, 60); // name, amount, basePrice, expiryDays)
//loading cargo on the ship1
std::cout << "Ship ID-" << ship1.getId() << " \"" << ship1.getName() << "\":" << std::endl;
ship1.load(apples);
ship1.load(rum);
ship1.load(ferrari);
//loading cargo on the ship2
std::cout << "Ship ID-" << ship2.getId() << " \"" << ship2.getName() << "\":" << std::endl;
ship2.load(guns);
ship2.load(dryFruits);
//list of cargo on the ship1
ship1.listCargo();
std::cout << std::endl;
//simulation of time for apples to expire
std::cout << "Counting down the days for apples to expire: " << std::endl;
for (int i = 0; i < 30; ++i) {
--(*std::static_pointer_cast<Fruit>(apples));
if (i % 5 == 0 || i == 29) {
std::cout << "Day " << i + 1 << ":" << std::endl;
ship1.listCargo();
}
}
std::cout << std::endl;
//unloading apples from ship1
std::cout << "Unloading apples from the ship ID-" << ship1.getId() << ":" << std::endl;
ship1.unload(apples.get());
std::cout << std::endl;
ship1.listCargo();
std::cout << std::endl;
//attempt of unloading non-existing stuff from the ship1
std::cout << "Unloading cargo from the ship ID-" << ship1.getId() << ":" << std::endl;
ship1.unload(apples.get());
std::cout << std::endl;
ship1.listCargo();
std::cout << std::endl;
//transfer of cargo between ship1 and ship2
std::cout << "Transfering rum from ship ID-" << ship1.getId() << " \"" << ship1.getName() << " \""
<< " to ship ID-"<< ship2.getId() << " \"" << ship2.getName() << " \":" << std::endl;
ship1.transferCargo(ship1, ship2, rum.get());
std::cout << std::endl;
ship1.listCargo();
std::cout << std::endl;
ship2.listCargo();
std::cout << std::endl;
//adding subtracting some crew members
ship2 += 6;
ship2 -= 3;
//testing class DryFruit
std::cout << dryFruits->getName();
std::cout << " original price: " << dryFruits->getPrice() << std::endl;
std::cout << " simulating dry fruit usage on ship " << ship1.getName() << ": " << std::endl;
for (int i = 0; i < 20; ++i) {
--(*std::static_pointer_cast<DryFruit>(dryFruits));
if (i % 5 == 0 || i == 19) {
std::cout << " after " << i + 1 << " uses, expiry date is: " << std::static_pointer_cast<Fruit>(dryFruits)->getExpiryDays() << std::endl;
}
}
return 0;
} |
from django.shortcuts import render, redirect
from .models import Livro
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib.auth import login as login_django
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required(login_url='/login/')
def home(request):
livros = Livro.objects.all() #pega tudo o que foi cadastrado no nosso model Livro
return render(request, 'home.html', {'livro': livros})
def login(request):
if request.method == "GET":
return render(request, 'login.html')
else:
username = request.POST.get('username')
senha = request.POST.get('senha')
user = authenticate(username=username,password=senha)
if(user):
login_django(request, user)
return HttpResponse('Logado no Sistema')
else:
return HttpResponse('Usuário ou Senha inválidos')
def cadastro_livro(request):
if request.method == "GET":
return render(request, 'cadastro_livro.html')
else:
titulo = request.POST.get('titulo')
autor = request.POST.get('autor')
editora = request.POST.get('editora')
data_cadastro = request.POST.get('data_cadastro')
livro = Livro.objects.filter(titulo=titulo).first()
if livro:
return HttpResponse('Esse livro já está cadastrado.')
livro = Livro.objects.create(titulo=titulo, autor=autor, editora=editora, data_cadastro=data_cadastro)
livro.save()
return redirect('/livros')
def cadastro(request):
if request.method == "GET":
return render(request, 'cadastro.html')
else:
username = request.POST.get('username')
email = request.POST.get('email')
senha = request.POST.get('senha')
user = User.objects.filter(username=username).first()
if user:
return HttpResponse('Já existe esse usuário cadastrado.')
user = User.objects.create_user(username=username, email=email, password=senha)
user.save()
return HttpResponse('Usuário cadastrado com Sucesso.')
def plataforma(request):
if request.user.is_authenticated:
return HttpResponse('Autenticado') #Só vai puder acessar quem estiver logado
return HttpResponse('Você precisa estar logado') |
import torch
from mmdet.core.bbox.match_costs.builder import MATCH_COST
@MATCH_COST.register_module()
class BBox3DL1Cost(object):
"""BBox3DL1Cost.
Args:
weight (int | float, optional): loss_weight
"""
def __init__(self, weight=1.0):
self.weight = weight
def __call__(self, bbox_pred, gt_bboxes):
"""
Args:
bbox_pred (Tensor): Predicted boxes with normalized coordinates
(cx, cy, w, h), which are all in range [0, 1]. Shape
[num_query, 4].
gt_bboxes (Tensor): Ground truth boxes with normalized
coordinates (x1, y1, x2, y2). Shape [num_gt, 4].
Returns:
torch.Tensor: bbox_cost value with weight
"""
bbox_cost = torch.cdist(bbox_pred, gt_bboxes, p=1)
return bbox_cost * self.weight
@MATCH_COST.register_module()
class PtsL1Cost(object):
"""OrderedPtsL1Cost.
Args:
weight (int | float, optional): loss_weight
"""
def __init__(self, weight=1.0):
self.weight = weight
def __call__(self, bbox_pred, gt_bboxes):
"""
Args:
bbox_pred (Tensor): Predicted boxes with normalized coordinates
(x, y), which are all in range [0, 1]. Shape
[num_query, num_pts, 2].
gt_bboxes (Tensor): Ground truth boxes with normalized
coordinates (x,y).
Shape [num_gt, num_ordered, num_pts, 2].
Returns:
torch.Tensor: bbox_cost value with weight
"""
num_gts, num_pts, num_coords = gt_bboxes.shape
# import pdb;pdb.set_trace()
bbox_pred = bbox_pred.view(bbox_pred.size(0), -1)
gt_bboxes = gt_bboxes.view(num_gts, -1)
bbox_cost = torch.cdist(bbox_pred, gt_bboxes, p=1)
return bbox_cost * self.weight |
"use client";
import * as React from "react";
import { motion } from "framer-motion";
import { Swiper as SwiperObject } from "swiper";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import { BsArrowUpRight, BsGithub } from "react-icons/bs";
import {
Tooltip,
TooltipProvider,
TooltipContent,
TooltipTrigger,
WorkSliderBtns,
} from "@/components";
import Link from "next/link";
import Image from "next/image";
const projects = [
{
num: "01",
category: "Frontend",
title: "Movil Renta",
description:
"Participe como desarrollador Frontend en la aplicación Movil Renta, un sitio enfacado en la renta de automoviles mediante reservas, con la integracion de Payway para el pago del servicio.",
stack: [{ name: "Next.js" }, { name: "Tailwind.css" }, { name: "Typescript" },{ name: "Zustand"}],
image: "/mockup-rentacar.png",
live: "https://car-movilrenta.vercel.app/home",
github: "https://github.com/fer3443",
},
{
num: "02",
category: "Full Stack",
title: "Comic Store",
description:
"En este proyecto participe tanto en el desarrollo Frontend, como Backend. Para la UI utilizamos componentes provistos por shadcn junto a tailwind y la incorporacion de MercadoPago para efectuar la compra de productos. Mi tareas como backender fueron realizar el crud de autenticación del usuario, con JWT, hasheo de informacion mediante bcrypt y el uso de cookies.",
stack: [{ name: "Next.js" }, { name: "Tailwind.css" }, { name: "Shadcn" }, {name: "MongoDb"}, {name: "Zustand"}],
image: "/mockup_benemex.png",
live: "https://www.benemexcomicstoree.ar/",
github: "https://github.com/fer3443",
},
{
num: "03",
category: "Full Stack",
title: "Arroyo Shop",
description:
"Tienda online, creada a partir del diseño de Tesla - Shop, como practica para el aprendizaje y perfeccionamiento de Next.js, con gran cantidad de componentes generados como server side, incorporacion de PayPal y zustand como gestor de estado global. Con Next Auth para la creacion y autenticacion de usuarios. Uso de ORM Prisma y como base de datos PostgresSQL.",
stack: [{ name: "Next.js" }, {name: "Zustand"},{name:"Prisma"},{name:"PostgresSql"}],
image: "/mockup-arroyoshop.png",
live: "/",
github: "https://github.com/fer3443/arroyo-shop",
},
];
export const WorkComponent = () => {
const [project, setProject] = React.useState(projects[0]);
const handleSlideChange = (swiper: SwiperObject) => {
const currentIndex = swiper.activeIndex;
setProject(projects[currentIndex]);
};
return (
<motion.div
initial={{ opacity: 0 }}
animate={{
opacity: 1,
transition: { delay: 2.4, duration: 0.4, ease: "easeIn" },
}}
className="min-h-[80vh] flex flex-col justify-center py-12 xl:py-0"
>
<div className="container mx-auto">
<div className="flex flex-col xl:flex-row xl:gap-[30px]">
<div className="w-full xl:w-[50%] xl:h-[460px] flex flex-col xl:justify-between order-2 xl:order-none">
<div className="flex flex-col gap-[30px] h-[50%]">
{/* outline num */}
<div className="text-8xl leading-none font-extrabold text-transparent text-outline">
{project.num}
</div>
<h2 className="text-[42px] font-bold leading-none text-white group-hover:text-accent transition-all duration-500 capitalize">
{project.title} - {project.category}
</h2>
{/* project description */}
<p className="text-white/60">{project.description}</p>
{/* Stack */}
<ul className="flex gap-4 flex-wrap md:flex-nowrap">
{project.stack.map((item, index) => (
<li key={index} className="text-xl text-accent">
{item.name}
{index !== project.stack.length - 1 && ","}
</li>
))}
</ul>
{/*border */}
<div className="border border-white/20" />
{/*buttons */}
<div className="flex items-center gap-4">
<Link href={project.live}>
<TooltipProvider delayDuration={100}>
<Tooltip>
<TooltipTrigger className="w-[60px] h-[60px] rounded-full bg-white/5 flex justify-center items-center group">
<BsArrowUpRight className="text-white text-3xl group-hover:text-accent" />
</TooltipTrigger>
<TooltipContent>
<p>Live project</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</Link>
{/* github project*/}
<Link href={project.live}>
<TooltipProvider delayDuration={100}>
<Tooltip>
<TooltipTrigger className="w-[60px] h-[60px] rounded-full bg-white/5 flex justify-center items-center group">
<BsGithub className="text-white text-3xl group-hover:text-accent" />
</TooltipTrigger>
<TooltipContent>
<p>Github repository</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</Link>
</div>
</div>
</div>
<div className="w-full xl:w-[50%]">
<Swiper
spaceBetween={30}
slidesPerView={1}
className="xl:h-[520] mb-12"
onSlideChange={handleSlideChange}
>
{projects.map((project, index) => (
<SwiperSlide key={index}>
<div className="h-[460px] relative group flex justify-center items-center bg-pink-50/20">
{/* overlay*/}
<div className="absolute top-0 bottom-0 w-full h-full bg-black/10 z-10" />
{/* Image */}
<div className="relative w-full h-full">
<Image
src={project.image}
alt="image"
fill
className="object-cover"
/>
</div>
</div>
</SwiperSlide>
))}
{/* slider buttons */}
<WorkSliderBtns containerStyles="flex gap-2 absolute right-0 bottom-[calc(50%_-_22px)] xl:bottom-0 z-20 w-full justify-between xl:w-max xl:justify-none" btnStyles="bg-accent hover:bg-accent-hover text-primary text-[22px] w-[44px] h-[44px] flex justify-center items-center transition-all"/>
</Swiper>
</div>
</div>
</div>
</motion.div>
);
}; |
import {
View,
StyleSheet,
Text,
Image,
ScrollView,
ImageBackground,
} from "react-native";
import Button from "../components/Button";
import SignOutButton from "../components/SignOutButton";
import { auth } from "../firebase";
import { signOut } from "firebase/auth";
import { useContext, useEffect } from "react";
import { DetailsContext } from "../store/context/details";
function HomeScreen({ navigation }) {
const detailsctx = useContext(DetailsContext);
useEffect(() => {
console.log(detailsctx);
}, []);
function onPress() {
signOut(auth)
.then(() => navigation.replace("Welcome"))
.catch((error) => alert(error.message));
}
function navigateToMBTIPage() {
navigation.navigate("MBTI");
}
function navigateToMatchingPage() {}
return (
<View style={styles.main}>
<ScrollView>
<View style={styles.profile}>
<ImageBackground source={require("../assets/island.png")} />
<Image
style={styles.image}
source={require("../assets/avatar.png")}
/>
<Text style={styles.text}>
Welcome back, {auth.currentUser.email} !!!
</Text>
</View>
<View style={styles.traits}>
<View style={styles.detailstextcontainer}>
<Text style={styles.detailstext}> Name: </Text>
</View>
<View style={styles.detailstextcontainer}>
<Text style={styles.detailstext}> Gender: </Text>
</View>
<View style={styles.detailstextcontainer}>
<Text style={styles.detailstext}> My Best Trait: </Text>
</View>
<View style={styles.detailstextcontainer}>
<Text style={styles.detailstext}> My Worst Trait: </Text>
</View>
</View>
<View style={styles.buttonsContainer}>
<View style={styles.buttonContainer}>
<Button onPress={navigateToMBTIPage}>MBTI TEST</Button>
</View>
<View style={styles.buttonContainer}>
<Button onPress={navigateToMatchingPage}>GET A MATCH</Button>
</View>
</View>
<View style={styles.signoutbutton}>
<SignOutButton onPress={onPress}>SIGN OUT</SignOutButton>
</View>
</ScrollView>
</View>
);
}
export default HomeScreen;
styles = StyleSheet.create({
image: {
width: 200,
height: 200,
alignSelf: "center",
justifyContent: "flex-center",
shadowColor: "#823b31",
shadowOffset: { width: 0, height: 3 },
shadowOpacity: 16,
shadowRadius: 0.35,
},
main: {
flex: 1,
backgroundColor: "#fa6559",
justifyContent: "center",
alignItems: "stretch",
},
text: {
textAlign: "center",
color: "black",
padding: 8,
marginBottom: 200,
},
signOut: {
flex: 1,
},
buttonsContainer: { flex: 1, paddingHorizontal: 45, marginBottom: 100 },
profile: {
marginTop: 40,
flex: 1,
},
traits: {
flex: 1,
padding: 8,
marginHorizontal: 16,
backgroundColor: "#a3293f",
marginVertical: 8,
borderRadius: 8,
},
detailstext: {
color: "white",
},
detailstextcontainer: {
padding: 5,
},
buttonContainer: {
padding: 4,
paddingVertical: 4,
},
signoutbutton: {
flex: 1,
paddingHorizontal: 45,
marginBottom: 100,
paddingVertical: 4,
},
}); |
package lyson
import (
"bytes"
)
// JsonObject Is the Implementation of JSONObject
type JsonObject struct {
// entries Are the Entries Wrapped in the JSON Object
entries map[string]any
}
func NewObject() *JsonObject {
result := new(JsonObject)
result.entries = make(map[string]any)
return result
}
// PutEntry Puts a Value at a Key
func (obj *JsonObject) PutEntry(key string, value any) error {
err := verifyDataType(value)
if nil == err {
obj.entries[key] = value
}
return err
}
func (obj *JsonObject) GetObject(key string) (any, bool) {
value, ok := obj.entries[key]
return value, ok
}
func (obj *JsonObject) GetInt(key string) (int, bool, error) {
value, ok := obj.entries[key]
if !ok {
return 0, ok, nil
}
result, err := getInt(value)
return result, ok, err
}
func (obj *JsonObject) GetLong(key string) (int64, bool, error) {
value, ok := obj.entries[key]
if !ok {
return 0, ok, nil
}
result, err := getLong(value)
return result, ok, err
}
func (obj *JsonObject) GetDouble(key string) (float64, bool, error) {
value, ok := obj.entries[key]
if !ok {
return 0, ok, nil
}
result, err := getDouble(value)
return result, ok, err
}
func (obj *JsonObject) GetBoolean(key string) (bool, bool, error) {
value, ok := obj.entries[key]
if !ok {
return false, ok, nil
}
result, err := getBoolean(value)
return result, ok, err
}
func (obj *JsonObject) GetString(key string) (string, bool, error) {
value, ok := obj.entries[key]
if !ok {
return "", ok, nil
}
result, err := getString(value)
return result, ok, err
}
func (obj *JsonObject) GetJsonObject(key string) (*JsonObject, bool, error) {
value, ok := obj.entries[key]
if !ok {
return nil, ok, nil
}
result, err := getJsonObject(value)
return result, ok, err
}
func (obj *JsonObject) GetJsonArray(key string) (*JsonArray, bool, error) {
value, ok := obj.entries[key]
if !ok {
return nil, ok, nil
}
result, err := getJsonArray(value)
return result, ok, err
}
func (obj *JsonObject) ToString() string {
if 0 == len(obj.entries) {
return "{}"
}
var buf bytes.Buffer
var valueText string
for key := range obj.entries {
buf.WriteString(",\"")
buf.WriteString(key)
buf.WriteString("\":")
valueText = TransformToString(obj.entries[key])
buf.WriteString(valueText)
}
result := buf.String()
return "{" + result[1:] + "}"
} |
#
# This script is a mix between the work done by
# Sarju Bhagat <sarju@westpoint.ltd.uk> and
# Martin O'Neal of Corsaire (http://www.corsaire.com)
#
# DISCLAIMER
# The information contained within this script is supplied "as-is" with
# no warranties or guarantees of fitness of use or otherwise. Corsaire
# accepts no responsibility for any damage caused by the use or misuse of
# this information.
#
#
#
# See the Nessus Scripts License for details
#
if(description)
{
script_id(12300);
script_bugtraq_id(10275, 8050);
script_cve_id("CVE-2004-0050");
name["english"] = "Inktomi Search Physical Path Disclosure";
script_name(english:name["english"]);
script_version ("$Revision: 1.4 $");
desc["english"] = "
This web server is running a vulnerable version of Inktomi Search
Certain requests using MS-DOS special file names such as nul can cause
a python error. The error message contains sensitive information such
as the physical path of the webroot. This information may be useful to
an attacker.
Solution : Upgrade to the latest version. This product is now developed i
by Verity and is called Ultraseek
See also : http://www.corsaire.com/advisories/c040113-001.txt
Risk factor : Low";
script_description(english:desc["english"]);
summary["english"] = "Checks for a Inktomi Search vulnerability";
script_summary(english:summary["english"]);
script_category(ACT_GATHER_INFO);
script_copyright(english:"This script is Copyright (C) 2004 Westpoint Limited and Corsaire Limited");
family["english"] = "CGI abuses";
script_family(english:family["english"]);
script_dependencie("http_version.nasl");
script_require_ports("Services/www", 8765);
exit(0);
}
include("http_func.inc");
include("http_keepalive.inc");
#
# The script code starts here
#
port = get_http_port(default:8765);
if(!get_port_state(port))exit(0);
# Check that the remote web server is UltraSeek, as
# some other servers may crash the host when requested
# for a DOS device.
banner = get_http_banner(port:port);
if ( banner == NULL || "Server: Ultraseek" >!< banner ) exit(0);
req = http_get(item:"/nul", port:port);
res = http_keepalive_send_recv(port:port, data:req);
if ( res == NULL ) exit(0);
if ( "httpsrvr.py:1033" >!< res ||
"500 Internal Server Error" >!< res ) exit(0);
w = egrep(pattern:"directory", string:res);
if(w)
{
webroot = ereg_replace(string:w, pattern:"^.*'(.*)'.*$", replace:"\1");
if (webroot == w) exit(0);
report = "
This web server is running a vulnerable version of Inktomi Search
Certain requests using MS-DOS special file names such as nul can cause
a python error. The error message contains sensitive information such
as the physical path of the webroot. This information may be useful to
an attacker.
The remote web root is : " + w + "
Solution :
Upgrade to the latest version. This product is now devloped by Verity
and is called Ultraseek
See also : http://www.corsaire.com/advisories/c040113-001.txt
Risk factor : Low";
security_warning(port:port, data:report);
} |
<?php
declare(strict_types=1);
namespace Doctrine\ORM\Tools\Console\Command\ClearCache;
use Doctrine\ORM\Cache;
use Doctrine\ORM\Tools\Console\Command\AbstractEntityManagerCommand;
use InvalidArgumentException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use function sprintf;
/**
* Command to clear a collection cache region.
*/
class CollectionRegionCommand extends AbstractEntityManagerCommand
{
/** @return void */
protected function configure()
{
$this->setName('orm:clear-cache:region:collection')
->setDescription('Clear a second-level cache collection region')
->addArgument('owner-class', InputArgument::OPTIONAL, 'The owner entity name.')
->addArgument('association', InputArgument::OPTIONAL, 'The association collection name.')
->addArgument('owner-id', InputArgument::OPTIONAL, 'The owner identifier.')
->addOption('em', null, InputOption::VALUE_REQUIRED, 'Name of the entity manager to operate on')
->addOption('all', null, InputOption::VALUE_NONE, 'If defined, all entity regions will be deleted/invalidated.')
->addOption('flush', null, InputOption::VALUE_NONE, 'If defined, all cache entries will be flushed.')
->setHelp(<<<'EOT'
The <info>%command.name%</info> command is meant to clear a second-level cache collection regions for an associated Entity Manager.
It is possible to delete/invalidate all collection region, a specific collection region or flushes the cache provider.
The execution type differ on how you execute the command.
If you want to invalidate all entries for an collection region this command would do the work:
<info>%command.name% 'Entities\MyEntity' 'collectionName'</info>
To invalidate a specific entry you should use :
<info>%command.name% 'Entities\MyEntity' 'collectionName' 1</info>
If you want to invalidate all entries for the all collection regions:
<info>%command.name% --all</info>
Alternatively, if you want to flush the configured cache provider for an collection region use this command:
<info>%command.name% 'Entities\MyEntity' 'collectionName' --flush</info>
Finally, be aware that if <info>--flush</info> option is passed,
not all cache providers are able to flush entries, because of a limitation of its execution nature.
EOT
);
}
/**
* {@inheritDoc}
*
* @return int
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$ui = (new SymfonyStyle($input, $output))->getErrorStyle();
$em = $this->getEntityManager($input);
$ownerClass = $input->getArgument('owner-class');
$assoc = $input->getArgument('association');
$ownerId = $input->getArgument('owner-id');
$cache = $em->getCache();
if (! $cache instanceof Cache) {
throw new InvalidArgumentException('No second-level cache is configured on the given EntityManager.');
}
if (( ! $ownerClass || ! $assoc) && ! $input->getOption('all')) {
throw new InvalidArgumentException('Missing arguments "--owner-class" "--association"');
}
if ($input->getOption('flush')) {
$cache->getCollectionCacheRegion($ownerClass, $assoc)
->evictAll();
$ui->comment(
sprintf(
'Flushing cache provider configured for <info>"%s#%s"</info>',
$ownerClass,
$assoc
)
);
return 0;
}
if ($input->getOption('all')) {
$ui->comment('Clearing <info>all</info> second-level cache collection regions');
$cache->evictEntityRegions();
return 0;
}
if ($ownerId) {
$ui->comment(
sprintf(
'Clearing second-level cache entry for collection <info>"%s#%s"</info> owner entity identified by <info>"%s"</info>',
$ownerClass,
$assoc,
$ownerId
)
);
$cache->evictCollection($ownerClass, $assoc, $ownerId);
return 0;
}
$ui->comment(sprintf('Clearing second-level cache for collection <info>"%s#%s"</info>', $ownerClass, $assoc));
$cache->evictCollectionRegion($ownerClass, $assoc);
return 0;
}
} |
//
// CurrentWeather.swift
// rainyshinycloudy
//
// Created by Aaryn Biro on 2017-05-17.
// Copyright © 2017 Aaryn Biro. All rights reserved.
//
import UIKit
import Alamofire
//data cconstant current weather class
class CurrentWeather {
//data encpsulation- best practice
var _cityName: String!
var _date: String!
var _weatherType: String!
var _currentTemp: String!
var cityName: String {
if _cityName == nil {
_cityName = ""
}
return _cityName
}
var date: String {
if _date == nil{
_date = ""
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
let currentDate = dateFormatter.string(from: Date())
self._date = "Today, \(currentDate)"
return _date
}
var weatherType: String {
if _weatherType == nil {
_weatherType = ""
}
return _weatherType
}
var currentTemp: String {
if _currentTemp == nil {
_currentTemp = "0.0"
}
return _currentTemp
}
func downloadWeatherDetails(completed: @escaping DownloadComplete){
//must bypass security https in info.plist
//initialize url to tell alamofire where to download from
// let currentWeatherURL = URL(string: CURRENT_WEATHER_URL)
Alamofire.request(CURRENT_WEATHER_URL).responseJSON { response in
let result = response.result
//print(result)
print(response)
//see data coming in^^
//create dictionary
if let dict = result.value as? Dictionary<String, AnyObject> {
if let name = dict["name"] as? String{
self._cityName = name.capitalized //first letter capitalized
print(self._cityName)
}
if let weather = dict["weather"] as? [Dictionary<String, AnyObject>]{
if let main = weather[0]["main"] as? String{
self._weatherType = main.capitalized
print(self._weatherType)
}
}
//inside of original dictionary
if let main = dict["main"] as? Dictionary<String, AnyObject>{
if let currentTemp = main["temp"] as? Double {
let kelvinToCelcius = Double(round(currentTemp - 273.15))
let strCurrent = "\(kelvinToCelcius)\"°"
self._currentTemp = strCurrent.replacingOccurrences(of: "\"", with: "")
print(self._currentTemp)
}
}
}
//need to tell it when to finish
completed()
}
}
} |
package com.kingyon.elevator.uis.fragments.homepage;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.kingyon.elevator.R;
import com.kingyon.elevator.constants.Constants;
import com.kingyon.elevator.entities.PlanItemEntity;
import com.kingyon.elevator.nets.CustomApiCallback;
import com.kingyon.elevator.nets.NetService;
import com.kingyon.elevator.uis.adapters.BaseAdapterWithHF;
import com.kingyon.elevator.uis.adapters.adapterone.PointPlanAddAdapter;
import com.kingyon.elevator.uis.dialogs.CellAdSuccessDialog;
import com.kingyon.elevator.uis.dialogs.PlanEditDialog;
import com.kingyon.elevator.utils.CommonUtil;
import com.kingyon.elevator.utils.LeakCanaryUtils;
import com.leo.afbaselibrary.nets.exceptions.ApiException;
import com.leo.afbaselibrary.uis.activities.BaseActivity;
import com.leo.afbaselibrary.uis.fragments.BaseStateLoadingDialogFragment;
import com.leo.afbaselibrary.utils.ScreenUtil;
import com.leo.afbaselibrary.widgets.emptyprovider.FadeViewAnimProvider;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
/**
* Created by GongLi on 2018/12/29.
* Email:lc824767150@163.com
*/
public class PointPlanDialogFragment extends BaseStateLoadingDialogFragment implements BaseAdapterWithHF.OnItemClickListener<PlanItemEntity>, PlanEditDialog.OnResultListener {
@BindView(R.id.tv_business)
TextView tvBusiness;
@BindView(R.id.tv_diy)
TextView tvDiy;
@BindView(R.id.tv_info)
TextView tvInfo;
@BindView(R.id.rv_plans)
RecyclerView rvPlans;
@BindView(R.id.fl_content)
FrameLayout flContent;
private String type;
private long cellId;
private TextView[] adTypes;
private PointPlanAddAdapter planAddAdapter;
private List<PlanItemEntity> caches = new ArrayList<>();
private PlanEditDialog editDialog;
public static PointPlanDialogFragment newInstance(String type, long cellId) {
Bundle args = new Bundle();
args.putString(CommonUtil.KEY_VALUE_1, type);
args.putLong(CommonUtil.KEY_VALUE_2, cellId);
PointPlanDialogFragment fragment = new PointPlanDialogFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public int getContentViewId() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
Window window = dialog.getWindow();
if (window != null) {
window.setWindowAnimations(R.style.BL_PopupAnimation);
}
}
return R.layout.fragment_dialog_point_plan;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.normal_dialog_question);
}
@Override
public void init(Bundle savedInstanceState) {
if (getArguments() != null) {
type = getArguments().getString(CommonUtil.KEY_VALUE_1, "");
cellId = getArguments().getLong(CommonUtil.KEY_VALUE_2);
}
super.init(savedInstanceState);
planAddAdapter = new PointPlanAddAdapter(getContext());
rvPlans.setLayoutManager(new LinearLayoutManager(getContext()));
rvPlans.setAdapter(planAddAdapter);
planAddAdapter.setOnItemClickListener(this);
adTypes = new TextView[]{tvBusiness, tvDiy, tvInfo};
initTypeSelected();
loadData();
}
@Override
public void loadData() {
caches.clear();
caches.addAll(planAddAdapter.getAllChoosed());
// NetService.getInstance().plansList(type, null, null)
// .compose(this.<List<CellItemEntity>>bindLifeCycle())
// .subscribe(new CustomApiCallback<List<CellItemEntity>>() {
// @Override
// protected void onResultError(ApiException ex) {
// showToast(ex.getDisplayMessage());
// loadingComplete(STATE_ERROR);
// if (ex.getCode() == ApiException.NO_LOGIN || ex.getCode() == ApiException.RE_LOGIN) {
// dismiss();
// }
// }
//
// @Override
// public void onNext(List<CellItemEntity> cellItemEntities) {
// if (planItemEntities != null) {
// for (PlanItemEntity newItem : planItemEntities) {
// boolean hasChoosed = false;
// for (PlanItemEntity oldItem : caches) {
// if (newItem.getObjectId() == oldItem.getObjectId()) {
// hasChoosed = true;
// break;
// }
// }
// newItem.setChoosed(hasChoosed);
// }
// caches.clear();
// }
// planAddAdapter.refreshDatas(planItemEntities);
// loadingComplete(STATE_CONTENT);
// }
// });
}
@Override
public void onStart() {
Window window = getDialog().getWindow();
if (window != null) {
WindowManager.LayoutParams attributes = window.getAttributes();
if (attributes != null) {
attributes.width = ScreenUtil.getScreenWidth(getContext()) - ScreenUtil.dp2px(32);
attributes.height = ViewGroup.LayoutParams.WRAP_CONTENT;
window.setAttributes(attributes);
}
window.setGravity(Gravity.CENTER);
}
super.onStart();
}
@OnClick({R.id.tv_ensure, R.id.tv_business, R.id.tv_diy, R.id.tv_info})
public void onViewClicked(View view) {
if (view.getId() == R.id.tv_ensure) {
String planIds = planAddAdapter.getAllChoosedParam();
if (TextUtils.isEmpty(planIds)) {
showToast("请选择至少一个点位计划");
} else {
requestAddToPlan(planIds);
}
} else {
if (adTypes == null) {
return;
}
for (TextView tvType : adTypes) {
if (view.getId() == tvType.getId()) {
tvType.setSelected(!tvType.isSelected());
} else {
tvType.setSelected(false);
}
}
updatePlanType();
}
}
private void requestAddToPlan(String planIds) {
NetService.getInstance().plansAddCells(planIds, String.valueOf(cellId))
.compose(this.<String>bindLifeCycle())
.subscribe(new CustomApiCallback<String>() {
@Override
protected void onResultError(ApiException ex) {
showToast(ex.getDisplayMessage());
}
@Override
public void onNext(String s) {
showSuccessDialog();
dismiss();
}
});
}
private void showSuccessDialog() {
if (getActivity() != null) {
CellAdSuccessDialog successDialog = new CellAdSuccessDialog(getActivity());
successDialog.show("", "已添加", "去下单", "继续添加");
} else {
showToast("操作成功");
}
}
private void updatePlanType() {
int selectId = 0;
for (TextView tvType : adTypes) {
if (tvType.isSelected()) {
selectId = tvType.getId();
break;
}
}
switch (selectId) {
case R.id.tv_business:
type = Constants.PLAN_TYPE.BUSINESS;
break;
case R.id.tv_diy:
type = Constants.PLAN_TYPE.DIY;
break;
case R.id.tv_info:
type = Constants.PLAN_TYPE.INFORMATION;
break;
default:
type = "";
break;
}
loadData();
}
private void initTypeSelected() {
int targetId;
switch (type) {
case Constants.PLAN_TYPE.BUSINESS:
targetId = R.id.tv_business;
break;
case Constants.PLAN_TYPE.DIY:
targetId = R.id.tv_diy;
break;
case Constants.PLAN_TYPE.INFORMATION:
targetId = R.id.tv_info;
break;
default:
targetId = 0;
break;
}
for (TextView tvType : adTypes) {
tvType.setSelected(targetId == tvType.getId());
}
}
@Override
public void onItemClick(View view, int position, PlanItemEntity entity, BaseAdapterWithHF<PlanItemEntity> baseAdaper) {
if (entity == null) {
if (!TextUtils.isEmpty(type)) {
showAddPlanDialog(type);
} else {
showToast("请先选择计划类型");
}
} else {
entity.setChoosed(!entity.isChoosed());
planAddAdapter.notifyDataSetChanged();
}
}
private void showAddPlanDialog(String type) {
if (editDialog == null) {
editDialog = new PlanEditDialog(getContext(), this);
}
editDialog.showType((BaseActivity) getActivity(), type);
editDialog.setCanceledOnTouchOutside(false);
}
protected void initStateLayout() {
stateLayout.setViewSwitchAnimProvider(new FadeViewAnimProvider());
stateLayout.setErrorAndEmptyAction(new View.OnClickListener() {
@Override
public void onClick(View v) {
autoLoading();
}
});
stateLayout.showProgressView(getString(R.string.loading));
}
@Override
protected void dealLeackCanary() {
LeakCanaryUtils.watchLeakCanary(this);
}
@Override
public boolean onResultListner(final PlanItemEntity entity, final String name, final String type) {
NetService.getInstance().plansAdd(entity != null ? entity.getObjectId() : null, name, type)
.compose(this.<String>bindLifeCycle())
.subscribe(new CustomApiCallback<String>() {
@Override
protected void onResultError(ApiException ex) {
showToast(ex.getDisplayMessage());
}
@Override
public void onNext(String s) {
showToast("添加成功");
loadData();
if (editDialog != null && editDialog.isShowing()) {
editDialog.dismiss();
}
}
});
return false;
}
} |
/*
This file contains the basic framework code for a JUCE plugin processor.
*/
#include "PluginProcessor.h"
#include "PluginEditor.h"
#include "Utils.h"
MDAJX10SynthAudioProcessor::MDAJX10SynthAudioProcessor()
#ifndef JucePlugin_PreferredChannelConfigurations
: AudioProcessor(BusesProperties()
#if ! JucePlugin_IsMidiEffect
#if ! JucePlugin_IsSynth
.withInput("Input", juce::AudioChannelSet::stereo(), true)
#endif
.withOutput("Output", juce::AudioChannelSet::stereo(), true)
#endif
)
#endif
{
/* noiseParam = dynamic_cast<juce::AudioParameterFloat*>(
apvts.getParameter(ParameterId::noise.getParamID()));*/
castParameter(apvts, ParameterId::oscMix, oscMixParam);
castParameter(apvts, ParameterId::oscTune, oscTuneParam);
castParameter(apvts, ParameterId::oscFine, oscFineParam);
castParameter(apvts, ParameterId::glideMode, glideModeParam);
castParameter(apvts, ParameterId::glideRate, glideRateParam);
castParameter(apvts, ParameterId::glideBend, glideBendParam);
castParameter(apvts, ParameterId::filterFreq, filterFreqParam);
castParameter(apvts, ParameterId::filterReso, filterResoParam);
castParameter(apvts, ParameterId::filterEnv, filterEnvParam);
castParameter(apvts, ParameterId::filterLFO, filterLFOParam);
castParameter(apvts, ParameterId::filterVelocity, filterVelocityParam);
castParameter(apvts, ParameterId::filterAttack, filterAttackParam);
castParameter(apvts, ParameterId::filterDecay, filterDecayParam);
castParameter(apvts, ParameterId::filterSustain, filterSustainParam);
castParameter(apvts, ParameterId::filterRelease, filterReleaseParam);
castParameter(apvts, ParameterId::envAttack, envAttackParam);
castParameter(apvts, ParameterId::envDecay, envDecayParam);
castParameter(apvts, ParameterId::envSustain, envSustainParam);
castParameter(apvts, ParameterId::envRelease, envReleaseParam);
castParameter(apvts, ParameterId::lfoRate, lfoRateParam);
castParameter(apvts, ParameterId::vibrato, vibratoParam);
castParameter(apvts, ParameterId::noise, noiseParam);
castParameter(apvts, ParameterId::octave, octaveParam);
castParameter(apvts, ParameterId::tuning, tuningParam);
castParameter(apvts, ParameterId::outputLevel, outputLevelParam);
castParameter(apvts, ParameterId::polyMode, polyModeParam);
}
MDAJX10SynthAudioProcessor::~MDAJX10SynthAudioProcessor()
{
}
const juce::String MDAJX10SynthAudioProcessor::getName() const
{
return JucePlugin_Name;
}
bool MDAJX10SynthAudioProcessor::acceptsMidi() const
{
#if JucePlugin_WantsMidiInput
return true;
#else
return false;
#endif
}
bool MDAJX10SynthAudioProcessor::producesMidi() const
{
#if JucePlugin_ProducesMidiOutput
return true;
#else
return false;
#endif
}
bool MDAJX10SynthAudioProcessor::isMidiEffect() const
{
#if JucePlugin_IsMidiEffect
return true;
#else
return false;
#endif
}
double MDAJX10SynthAudioProcessor::getTailLengthSeconds() const
{
return 0.0;
}
int MDAJX10SynthAudioProcessor::getNumPrograms()
{
return 1; // NB: some hosts don't cope very well if you tell them there are 0 programs,
// so this should be at least 1, even if you're not really implementing programs.
}
int MDAJX10SynthAudioProcessor::getCurrentProgram()
{
return 0;
}
void MDAJX10SynthAudioProcessor::setCurrentProgram(int index)
{
}
const juce::String MDAJX10SynthAudioProcessor::getProgramName(int index)
{
return {};
}
void MDAJX10SynthAudioProcessor::changeProgramName(int index, const juce::String& newName)
{
}
void MDAJX10SynthAudioProcessor::prepareToPlay(double sampleRate, int samplesPerBlock)
{
synth.allocateResources(sampleRate, samplesPerBlock);
reset();
}
void MDAJX10SynthAudioProcessor::releaseResources()
{
synth.deallocateResources();
}
void MDAJX10SynthAudioProcessor::reset()
{
synth.reset();
}
#ifndef JucePlugin_PreferredChannelConfigurations
bool MDAJX10SynthAudioProcessor::isBusesLayoutSupported(const BusesLayout& layouts) const
{
#if JucePlugin_IsMidiEffect
juce::ignoreUnused(layouts);
return true;
#else
// This is the place where you check if the layout is supported.
// In this template code we only support mono or stereo.
// Some plugin hosts, such as certain GarageBand versions, will only
// load plugins that support stereo bus layouts.
if (layouts.getMainOutputChannelSet() != juce::AudioChannelSet::mono()
&& layouts.getMainOutputChannelSet() != juce::AudioChannelSet::stereo())
return false;
// This checks if the input layout matches the output layout
#if ! JucePlugin_IsSynth
if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet())
return false;
#endif
return true;
#endif
}
#endif
void MDAJX10SynthAudioProcessor::processBlock(juce::AudioBuffer<float>& buffer, juce::MidiBuffer& midiMessages)
{
juce::ScopedNoDenormals noDenormals;
const juce::String& paramID = ParameterId::noise.getParamID();
float noiseMix = noiseParam->get()/ 100.0f;
noiseMix *= noiseMix;
synth.noiseMix = noiseMix * 0.06f;
auto totalNumInputChannels = getTotalNumInputChannels();
auto totalNumOutputChannels = getTotalNumOutputChannels();
// Clear any output channels that don't contain input data.
for (auto i = totalNumInputChannels; i < totalNumOutputChannels; ++i) {
buffer.clear(i, 0, buffer.getNumSamples());
}
splitBufferByEvents(buffer, midiMessages);
}
void MDAJX10SynthAudioProcessor::splitBufferByEvents(juce::AudioBuffer<float>& buffer, juce::MidiBuffer& midiMessages)
{
int bufferOffset = 0;
// Loop through the MIDI messages, which are sorted by samplePosition.
for (const auto metadata : midiMessages) {
// Render the audio that happens before this event (if any).
int samplesThisSegment = metadata.samplePosition - bufferOffset;
if (samplesThisSegment > 0) {
render(buffer, samplesThisSegment, bufferOffset);
bufferOffset += samplesThisSegment;
}
// Handle the event. Ignore MIDI messages such as sysex.
if (metadata.numBytes <= 3) {
uint8_t data1 = (metadata.numBytes >= 2) ? metadata.data[1] : 0;
uint8_t data2 = (metadata.numBytes == 3) ? metadata.data[2] : 0;
handleMIDI(metadata.data[0], data1, data2);
}
}
// Render the audio after the last MIDI event. If there were no
// MIDI events at all, this renders the entire buffer.
int samplesLastSegment = buffer.getNumSamples() - bufferOffset;
if (samplesLastSegment > 0) {
render(buffer, samplesLastSegment, bufferOffset);
}
midiMessages.clear();
}
void MDAJX10SynthAudioProcessor::handleMIDI(uint8_t data0, uint8_t data1, uint8_t data2)
{
// char s[16];
// snprintf(s, 16, "%02hhX %02hhX %02hhX", data0, data1, data2);
// DBG(s);
synth.midiMessage(data0, data1, data2);
}
void MDAJX10SynthAudioProcessor::render(juce::AudioBuffer<float>& buffer, int sampleCount, int bufferOffset)
{
float* outputBuffers[2] = { nullptr, nullptr };
outputBuffers[0] = buffer.getWritePointer(0) + bufferOffset;
if (getTotalNumOutputChannels() > 1) {
outputBuffers[1] = buffer.getWritePointer(1) + bufferOffset;
}
synth.render(outputBuffers, sampleCount);
}
bool MDAJX10SynthAudioProcessor::hasEditor() const
{
return true; // (change this to false if you choose to not supply an editor)
}
juce::AudioProcessorEditor* MDAJX10SynthAudioProcessor::createEditor()
{
auto editor = new juce::GenericAudioProcessorEditor(*this);
editor->setSize(500, 1050);
return editor;
}
void MDAJX10SynthAudioProcessor::getStateInformation(juce::MemoryBlock& destData)
{
// You should use this method to store your parameters in the memory block.
// You could do that either as raw data, or use the XML or ValueTree classes
// as intermediaries to make it easy to save and load complex data.
}
void MDAJX10SynthAudioProcessor::setStateInformation(const void* data, int sizeInBytes)
{
// You should use this method to restore your parameters from this memory block,
// whose contents will have been created by the getStateInformation() call.
}
// This creates new instances of the plugin..
juce::AudioProcessor* JUCE_CALLTYPE createPluginFilter()
{
return new MDAJX10SynthAudioProcessor();
}
juce::AudioProcessorValueTreeState::ParameterLayout MDAJX10SynthAudioProcessor::createParameterLayout()
{
juce::AudioProcessorValueTreeState::ParameterLayout layout;
layout.add(std::make_unique<juce::AudioParameterChoice>(
ParameterId::polyMode,
"Polyphony",
juce::StringArray{ "Mono", "Poly" },
1));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::oscTune,
"Osc Tune", //oscillator tuning
juce::NormalisableRange<float>(-24.0f, 24.0f, 1.0f),
-12.0f, //default value
juce::AudioParameterFloatAttributes().withLabel("cent") //expressed in semitones
));
auto oscMixStringFromValue = [](float value, int)
{
char s[16] = { 0 };
snprintf(s, 16, "%4.0f:%2.0f", 100.0 - 0.5f * value * value);
return juce::String(s);
};
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::oscMix,
"OscMix",
juce::NormalisableRange<float>(0.0f, 100.0f),
0.0f,
juce::AudioParameterFloatAttributes()
.withLabel("%")
.withStringFromValueFunction(oscMixStringFromValue)
));
layout.add(std::make_unique<juce::AudioParameterChoice>(
ParameterId::glideMode,
"Glide Mode",
juce::StringArray{ "Off", "Legato", "Always" }, //choice box that offers three choices
0));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::glideRate,
"Glide Rate",
juce::NormalisableRange<float>(0.0f, 100.f, 1.0f),
35.0f,
juce::AudioParameterFloatAttributes().withLabel("%"))); //determines how it takes to glide from one note to the next
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::glideBend,
"Glide Bend",
juce::NormalisableRange<float>(-36.0f, 36.0f, 0.01f, 0.4f, true),
0.0f,
juce::AudioParameterFloatAttributes().withLabel("semi"))); //lets you add an additional glide to any note that gets played between -36 and +36 semitones.
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::filterFreq,
"Filter Freq",
juce::NormalisableRange<float>(0.0f, 100.0f, 0.1f),
100.0f,
juce::AudioParameterFloatAttributes().withLabel("%")));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::filterReso,
"Filter Reso",
juce::NormalisableRange<float>(0.0f, 100.0f, 1.0f),
15.0f,
juce::AudioParameterFloatAttributes().withLabel("%")));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::filterEnv,
"Filter Env",
juce::NormalisableRange<float>(-100.0f, 100.0f, 0.1f),
50.0f,
juce::AudioParameterFloatAttributes().withLabel("%")));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::filterLFO,
"Filter LFO",
juce::NormalisableRange<float>(0.0f, 100.0f, 1.0f),
0.0f,
juce::AudioParameterFloatAttributes().withLabel("%")));
auto filterVelocityStringFromValue = [](float value, int)
{
if (value < -90.0f)
return juce::String("OFF");
else
return juce::String(value);
};
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::filterVelocity,
"Velocity",
juce::NormalisableRange<float>(-100.0f, 100.0f, 1.0f),
0.0f,
juce::AudioParameterFloatAttributes()
.withLabel("%")
.withStringFromValueFunction(filterVelocityStringFromValue)));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::filterAttack,
"Filter Attack",
juce::NormalisableRange<float>(0.0f, 100.0f, 1.0f),
0.0f,
juce::AudioParameterFloatAttributes().withLabel("%")));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::filterDecay,
"Filter Decay",
juce::NormalisableRange<float>(0.0f, 100.0f, 1.0f),
30.0f,
juce::AudioParameterFloatAttributes().withLabel("%")));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::filterSustain,
"Filter Sustain",
juce::NormalisableRange<float>(0.0f, 100.0f, 1.0f),
0.0f,
juce::AudioParameterFloatAttributes().withLabel("%")));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::filterRelease,
"Filter Release",
juce::NormalisableRange<float>(0.0f, 100.0f, 1.0f),
25.0f,
juce::AudioParameterFloatAttributes().withLabel("%")));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::envAttack,
"Env Attack",
juce::NormalisableRange<float>(0.0f, 100.0f, 1.0f),
0.0f,
juce::AudioParameterFloatAttributes().withLabel("%")));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::envDecay,
"Env Decay",
juce::NormalisableRange<float>(0.0f, 100.0f, 1.0f),
50.0f,
juce::AudioParameterFloatAttributes().withLabel("%")));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::envSustain,
"Env Sustain",
juce::NormalisableRange<float>(0.0f, 100.0f, 1.0f),
100.0f,
juce::AudioParameterFloatAttributes().withLabel("%")));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::envRelease,
"Env Release",
juce::NormalisableRange<float>(0.0f, 100.0f, 1.0f),
30.0f,
juce::AudioParameterFloatAttributes().withLabel("%")));
auto lfoRateStringFromValue = [](float value, int)
{
float lfoHz = std::exp(7.0f * value - 4.0f);
return juce::String(lfoHz, 3);
};
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::lfoRate,
"LFO Rate",
juce::NormalisableRange<float>(),
0.81f,
juce::AudioParameterFloatAttributes()
.withLabel("Hz")
.withStringFromValueFunction(lfoRateStringFromValue)));
auto vibratoStringFromValue = [](float value, int)
{
if (value < 0.0f)
return "PWM" + juce::String(-value, 1);
else
return juce::String(value, 1);
};
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::vibrato,
"Vibrato",
juce::NormalisableRange<float>(-100.0f, 100.0f, 0.1f),
0.0f,
juce::AudioParameterFloatAttributes()
.withLabel("%")
.withStringFromValueFunction(vibratoStringFromValue)));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::noise,
"Noise",
juce::NormalisableRange <float>(0.0f, 100.0f, 1.0f),
0.0f,
juce::AudioParameterFloatAttributes().withLabel("%")));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::octave,
"Octave",
juce::NormalisableRange <float>(-2.0f, 2.0f, 1.0f),
0.0f));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::tuning,
"Tuning",
juce::NormalisableRange<float>(-100.0f, 100.0f, 0.1f),
0.0f,
juce::AudioParameterFloatAttributes().withLabel("cent")));
layout.add(std::make_unique<juce::AudioParameterFloat>(
ParameterId::outputLevel,
"Output Level",
juce::NormalisableRange<float>(-24.0f, 6.0f, 0.1f),
0.0f,
juce::AudioParameterFloatAttributes().withLabel("dB"))); ///Volume parameter
return layout;
} |
# Laravel Khalti
This package can help you integrate Khalti new ePayment Gateway (NEW) to your php application.
[Khalti ePay Docs](https://docs.khalti.com/khalti-epayment/)
Here is an example of how you can initiate Khalti transaction:
```php
...
use Neputer\Facades\Khalti;
use Illuminate\Support\Facades\Redirect;
class PaymentController extends Controller {
...
public function pay() {
$return_url = "http://example.com/verify";
$purchase_order_id = "your_transaction_id"; // example 123567;
$purchase_order_name = "your_order_name"; // example Transaction: 1234,
$amount = 1000; // Your total amount in paisa Rs 1 = 100 paisa
$response = Khalti::initiate($return_url, $purchase_order_id, $purchase_order_name, $amount);
// Custom handle of khalti response
return Redirect::to($response->payment_url);
}
public function verify(Request $request) {
$pidx = $request->get('pidx');
return Khalti::lookup($pidx);
}
}
```
## Installation
You can install the package via composer:
```bash
composer require neputertech/khalti
```
The package will automatically register itself.
You can publish the config with:
```bash
php artisan vendor:publish --tag=khalti-config
```
This is the contents of the published config file:
```php
<?php
return [
'debug' => env('KHALTI_DEBUG', true), // set false to run on live khalti url
'website_url' => 'https://example.com', // your website url
'public_key' => env('KHALTI_PUBLIC_KEY', ''), // public key from khalti
'secret_key' => env('KHALTI_SECRET_KEY', ''), // secret key from khalti
];
```
## Update .env with your khalti credentials
This credentals are provided with merchant dashboard.
set debug flag to false in config to use live khalti
```bash
KHALTI_DEBUG=true # Set this flag to false to use khatli in production
KHALTI_PUBLIC_KEY=
KHALTI_SECRET_KEY=
```
## Usage
The basic concept of this package is that you can integrate Khalti ePayment Gateway (NEW) to your laravel applications and initiate/verify transactions |
import React, { useEffect, useState, useContext } from 'react';
import PageLayout, { PageHeading, PageSubHeading, PageContent, PageDivider } from '../AddOns/PageLayout';
import NameJoiner from 'utils/NameJoiner';
import { Button } from 'utils/Buttons'
import { Link } from 'react-router-dom';
import ErrorBoundary from 'utils/ErrorBoundary'
import { UserContext } from '../../index';
import styles from './Home.scss';
export default function Home () {
const context = useContext(UserContext);
const currentLanguage = document.cookie.split('; ').find(row => row.startsWith('ksweddingviewer_language=')).split('=')[1] || "english"
return (
<ErrorBoundary>
<PageLayout>
<PageHeading value={NameJoiner(context.guestInfo.guests.map(guest => guest.name))} />
<PageDivider />
{ currentLanguage === 'it' &&
<>
<PageSubHeading>{t('pages.home.passport')}</PageSubHeading>
<PageContent>
{t('pages.home.passportmessage')}
</PageContent>
</> }
<PageSubHeading>
{t('pages.home.subheading')}
</PageSubHeading>
<PageContent>
{t('pages.home.maincontent1')}
<br />
{t('pages.home.maincontent2')}
<br />
{t('pages.home.maincontent3')}
<br />
{t('pages.home.maincontent4')}
</PageContent>
{ currentLanguage !== 'it' &&
<>
<PageHeading value={t('pages.home.gifts')} />
<PageDivider />
<PageContent>
{t('pages.home.giftsmessage1')}
<br />
{t('pages.home.giftsmessage2')}
<br />
{t('pages.home.giftsmessage3')}
</PageContent>
</> }
</PageLayout>
</ErrorBoundary>
)
} |
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use App\Models\Common\Product;
class completeProductPosNotesExport implements ShouldAutoSize, WithEvents, FromQuery, WithHeadings, WithMapping
{
/**
* @return \Illuminate\Support\Collection
*/
public function __construct($query)
{
$this->query = $query;
}
public function query()
{
$query = $this->query;
return $query;
}
public function headings() : array
{
$heading_array = [];
array_push($heading_array, 'product_code');
array_push($heading_array, 'product_name');
array_push($heading_array, 'expiration_date');
array_push($heading_array, 'quantity');
array_push($heading_array, 'notes');
return $heading_array;
}
public function map($item) : array
{
$data_array = [];
if($item->stock_out_available->count() > 0) {
$sum = $item->stock_out_available->sum('available_stock');
array_push($data_array, $item->product['refrence_code']);
array_push($data_array, $item->product['short_desc']);
array_push($data_array, $item->expiration_date);
array_push($data_array, round($sum, 2));
array_push($data_array, $item->title);
}
return $data_array;
}
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
},
];
}
} |
/// <reference types="urijs" />
import { Asset } from "@stellar/stellar-base";
import { CallBuilder } from "./call_builder";
import { ServerApi } from "./server_api";
/**
* The Stellar Network allows payments to be made across assets through path
* payments. A strict send path payment specifies a series of assets to route a
* payment through, from source asset (the asset debited from the payer) to
* destination asset (the asset credited to the payee).
*
* A strict send path search is specified using:
*
* The source asset
* The source amount
* The destination assets or destination account.
*
* As part of the search, horizon will load a list of assets available to the
* source address and will find any payment paths from those source assets to
* the desired destination asset. The search's source_amount parameter will be
* used to determine if there a given path can satisfy a payment of the desired
* amount.
*
* Do not create this object directly, use {@link Server#strictSendPaths}.
* @see [Find Payment Paths](https://developers.stellar.org/api/aggregations/paths/)
* @extends CallBuilder
* @param {string} serverUrl Horizon server URL.
* @param {Asset} sourceAsset The asset to be sent.
* @param {string} sourceAmount The amount, denominated in the source asset, that any returned path should be able to satisfy.
* @param {string|Asset[]} destination The destination account or the destination assets.
*
*/
export declare class StrictSendPathCallBuilder extends CallBuilder<ServerApi.CollectionPage<ServerApi.PaymentPathRecord>> {
constructor(serverUrl: URI, sourceAsset: Asset, sourceAmount: string, destination: string | Asset[]);
} |
//
// ViewController.swift
// UIPickerView
//
// Created by Владимир Дмитриев on 28.07.23.
//
import UIKit
//class ViewController: UIViewController {
//
// let picker = UIPickerView()
//
// override func viewDidLoad() {
// super.viewDidLoad()
//
// picker.center = view.center
//
// picker.dataSource = self
// picker.delegate = self
//
// self.view.addSubview(picker)
//
// }
//
//}
//
//extension ViewController: UIPickerViewDataSource {
//
// func numberOfComponents(in pickerView: UIPickerView) -> Int {
// return 1
// }
//
// func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
// return 10
// }
//
//}
//
//extension ViewController: UIPickerViewDelegate {
//
// func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
// let result = "row = \(row)"
// return result
// }
//
//}
//class ViewController: UIViewController {
//
// let picker = UIDatePicker()
//
// override func viewDidLoad() {
// super.viewDidLoad()
//
// picker.center = view.center
// picker.datePickerMode = .date
//
// self.view.addSubview(picker)
//
// var oneYearTime = TimeInterval()
// oneYearTime = 365 * 24 * 60 * 60
//
// let todayDate = Date()
// let oneYearFromToday = todayDate.addingTimeInterval(oneYearTime)
// let twoTearFromToday = todayDate.addingTimeInterval(2 * oneYearTime)
//
// picker.minimumDate = oneYearFromToday
// picker.maximumDate = twoTearFromToday
//
// picker.addTarget(self, action: #selector(datePickerChange(paranDatePicker:)), for: .valueChanged)
//
// }
//
// @objc func datePickerChange (paranDatePicker: UIDatePicker) {
// if paranDatePicker.isEqual(self.picker) {
// print("dateChange = ", paranDatePicker.date)
//
// }
// }
//
//}
class ViewController: UIViewController {
let picker = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
picker.center = view.center
picker.datePickerMode = .countDownTimer
self.view.addSubview(picker)
var oneYearTime = TimeInterval()
oneYearTime = 365 * 24 * 60 * 60
let todayDate = Date()
let oneYearFromToday = todayDate.addingTimeInterval(oneYearTime)
let twoTearFromToday = todayDate.addingTimeInterval(2 * oneYearTime)
picker.minimumDate = oneYearFromToday
picker.maximumDate = twoTearFromToday
picker.countDownDuration = 2 * 60
picker.addTarget(self, action: #selector(datePickerChange(paranDatePicker:)), for: .valueChanged)
}
@objc func datePickerChange (paranDatePicker: UIDatePicker) {
if paranDatePicker.isEqual(self.picker) {
print("dateChange = ", paranDatePicker.date)
}
}
} |
package br.com.jcomputacao.sped.efd.pisCofins;
import br.com.jcomputacao.aristoteles.field.FieldDecimalMaximumLengthArchetype;
import br.com.jcomputacao.aristoteles.field.FieldDefaultArchetype;
import br.com.jcomputacao.aristoteles.field.FieldStringMaximumLengthArchetype;
import br.com.jcomputacao.aristoteles.format.FormatFactory;
import br.com.jcomputacao.aristoteles.format.FormatType;
import br.com.jcomputacao.aristoteles.format.FormatWrapper;
import br.com.jcomputacao.aristoteles.line.LineArchetype;
/**
* 17/11/2011 19:39:59
* @author rafael.galvao
*/
public class RegistroM610 extends LineArchetype{
public static String REG = "REG";
/**
* Tabela 4.3.5
* <table>
* <tr><th colspan="2">4.3.5 – Tabela Código de Contribuição Social Apurada</th></tr>
* <tr><th>Codigo</th><th>Descricao</th></tr>
* <tr><td>01</td><td>Contribuição não-cumulativa apurada a alíquota básica</td></tr>
* <tr><td>02</td><td>Contribuição não-cumulativa apurada a alíquotas diferenciadas</td></tr>
* <tr><td>03</td><td>Contribuição não-cumulativa apurada a alíquota por unidade de medida de produto</td></tr>
* <tr><td>04</td><td>Contribuição não-cumulativa apurada a alíquota básica – Atividade Imobiliária</td></tr>
* <tr><td>31</td><td>Contribuição apurada por substituição tributária</td></tr>
* <tr><td>32</td><td>Contribuição apurada por substituição tributária – Vendas à Zona Franca de Manaus</td></tr>
* <tr><td>51</td><td>Contribuição cumulativa apurada a alíquota básica</td></tr>
* <tr><td>53</td><td>Contribuição cumulativa apurada a alíquota por unidade de medida de produto</td></tr>
* <tr><td>54</td><td>Contribuição cumulativa apurada a alíquota básica – Atividade Imobiliária</td></tr>
* <tr><td>70</td><td>Contribuição apurada da Atividade Imobiliária - RET</td></tr>
* <tr><td>71</td><td>Contribuição apurada de SCP – Incidência Não Cumulativa</td></tr>
* <tr><td>72</td><td>Contribuição apurada de SCP – Incidência Cumulativa</td></tr>
* <tr><td>99</td><td>Contribuição para o PIS/Pasep – Folha de Salários</td></tr>
* </table>
*/
public static String COD_CONT = "COD_CONT";
public static String VL_REC_BRT = "VL_REC_BRT";
public static String VL_BC_CONT = "VL_BC_CONT";
public static String ALIQ_COFINS = "ALIQ_COFINS";
public static String QUANT_BC_COFINS = "QUANT_BC_COFINS";
public static String ALIQ_COFINS_QUANT = "ALIQ_COFINS_QUANT";
public static String VL_CONT_APUR = "VL_CONT_APUR";
public static String VL_AJUS_ACRES = "VL_AJUS_ACRES";
public static String VL_AJUS_REDUC = "VL_AJUS_REDUC";
public static String VL_CONT_DIFER = "VL_CONT_DIFER";
public static String VL_CONT_DIFER_ANT = "VL_CONT_DIFER_ANT";
public static String VL_CONT_PER = "VL_CONT_PER";
public RegistroM610(){
setName("Detalhamento da contribuição para a seguridade social - Cofins do período");
setDelimiter("|");
FormatWrapper fw = FormatFactory.getFormat(FormatType.DECIMAL);
fw.setReplaceComa(false);
FormatWrapper fw3 = FormatFactory.getDecimalFormatWithPrecision(3);
fw3.setReplaceComa(false);
FormatWrapper fw4 = FormatFactory.getDecimalFormatWithPrecision(4);
fw4.setReplaceComa(false);
FieldDecimalMaximumLengthArchetype fdm = new FieldDecimalMaximumLengthArchetype(15,2);
fdm.setFormat(fw);
//01
addFieldArchetype(REG, new FieldDefaultArchetype("M610"));
//02
addFieldArchetype(COD_CONT, new FieldStringMaximumLengthArchetype(2));
//03
addFieldArchetype(VL_REC_BRT, fdm);
//04
addFieldArchetype(VL_BC_CONT, fdm);
//05
FieldDecimalMaximumLengthArchetype f05 = new FieldDecimalMaximumLengthArchetype(13,4);
f05.setFormat(fw4);
f05.setNullableRepresentation("");
f05.setFullFillingNullable(false);
addFieldArchetype(ALIQ_COFINS, f05);
//06
FieldDecimalMaximumLengthArchetype f06 = new FieldDecimalMaximumLengthArchetype(16,3);
f06.setFormat(fw3);
f06.setNullableRepresentation("");
f06.setFullFillingNullable(false);
addFieldArchetype(QUANT_BC_COFINS, f06);
//07
FieldDecimalMaximumLengthArchetype f07 = new FieldDecimalMaximumLengthArchetype(17,4);
f07.setFormat(fw4);
f07.setNullableRepresentation("");
f07.setFullFillingNullable(false);
addFieldArchetype(ALIQ_COFINS_QUANT, f07);
//08
addFieldArchetype(VL_CONT_APUR, fdm);
//09
addFieldArchetype(VL_AJUS_ACRES, fdm);
//10
addFieldArchetype(VL_AJUS_REDUC, fdm);
//11
FieldDecimalMaximumLengthArchetype f11 = new FieldDecimalMaximumLengthArchetype(15,2);
f11.setFormat(fw);
f11.setNullableRepresentation("");
f11.setFullFillingNullable(false);
addFieldArchetype(VL_CONT_DIFER, f11);
//12
FieldDecimalMaximumLengthArchetype f12 = new FieldDecimalMaximumLengthArchetype(15,2);
f12.setFormat(fw);
f12.setNullableRepresentation("");
f12.setFullFillingNullable(false);
addFieldArchetype(VL_CONT_DIFER_ANT, f12);
//13
addFieldArchetype(VL_CONT_PER, fdm);
}
} |
import { IUserRepo, UserFindOptions } from 'database/repository.interfaces/user.repo.intrerface';
import { UserDomainModel } from 'domain.types/user/user.domain.model';
import { UserDetailsDto } from 'domain.types/user/user.dto';
import { Op } from 'sequelize';
import { UserMapper } from '../mapper/user.mapper';
import User from '../models/user.model';
export class UserRepo implements IUserRepo {
getById = async (userId: string): Promise<UserDetailsDto> => {
const user: User = await User.findOne({
where: {
id: userId,
},
});
const details: UserDetailsDto = await UserMapper.toDetailsDto(user);
return details;
};
async getUserHashedPassword(userId: string): Promise<string> {
const user: User = await User.findOne({
where: {
id: userId,
},
});
return user.Password;
}
async findOneUser(options: UserFindOptions): Promise<UserDetailsDto> {
const DeletedAt = options.isActive === true ? { DeletedAt: null } : { DeletedAt: { [Op.not]: null } };
let findByEmail = {};
if (options.email) {
findByEmail = {
Email: options.email,
};
}
let findByUserId = {};
if (options.userId) {
findByUserId = {
id: options.userId,
};
}
const user: User = await User.findOne({
where: {
...findByEmail,
...findByUserId,
...DeletedAt,
},
});
const details: UserDetailsDto = await UserMapper.toDetailsDto(user);
return details;
}
async findUsersByRoleId(roleid: string): Promise<UserDetailsDto[]> {
const users: User[] = await User.findAll({
where: {
RoleId: roleid,
},
});
const temp: Promise<UserDetailsDto>[] = users.map(async (user) => await UserMapper.toDetailsDto(user));
const userDetailsDto: UserDetailsDto[] = await Promise.all(temp);
return userDetailsDto;
}
async createUser(userDetails: UserDomainModel): Promise<UserDetailsDto> {
const entity = {
Prefix: userDetails.Prefix,
FirstName: userDetails.FirstName,
MiddleName: userDetails.MiddleName,
LastName: userDetails.LastName,
Email: userDetails.Email,
Password: userDetails.Password,
RoleId: userDetails.RoleId,
};
const user: User = await User.create(entity);
const dto: UserDetailsDto = await UserMapper.toDetailsDto(user);
return dto;
}
} |
# This is a helper file to help and support the ELECTRE III file(electre3.py)
# by inputing data and defining variables
import numpy as np
import copy
from . import load_data as ld
class El3_init:
def __init__(self, class_: ld.Store_data, tolerance=None, dist=None) -> None:
self.crit = class_.crit # num of criteria
self.alt = class_.alt # num of alternatives
self.altNames = class_.altNames # alternatives names
self.critNames = class_.critNames # criteria names
self.decMatrix = class_.decMatrix # Decision Matrix
self.optType = np.full((1, self.crit), -1) # Min or Max
self.w = np.full_like(self.optType, -1, dtype=np.float64) # Weights
self.q = np.full_like(self.optType, -1, dtype=np.float64) # Indifference Threshold
self.p = np.full_like(self.optType, -1, dtype=np.float64) # Preference Threshold
self.v = np.full_like(self.optType, -1, dtype=np.float64) # Veto Threshold
self.tolerance = tolerance
self.dist = dist
def input_data(): # Used with get_input() method
try:
x = input()
return float(x)
except ValueError:
print('Has to have some kind of value.')
x = -1
return float(x)
def get_input(class_: El3_init): # User ipnput data from console [not used with GUI]
x = class_
for criterion in range(x.crit):
while True:
print('Enter the optimization type(min or max), |min=1, max=0| for criterion',
x.critNames[criterion]+':')
x.optType[0, criterion] = int(input_data())
if x.optType[0, criterion] == 1 or x.optType[0, criterion] == 0:
break
else:
print('Wrong input.')
while True:
print('Enter the weight (w) for criterion', x.critNames[criterion]+':')
x.w[0, criterion] = input_data()
if x.w[0, criterion] >= 0 and x.w[0, criterion] <= 1:
break
else:
print('The value has to be between 0 and 1.')
while True:
print('Enter the Indifference threshold (q) for criterion', x.critNames[criterion]+':')
x.q[0, criterion] = input_data()
if x.q[0, criterion] >= 0:
break
else:
print('The value has to be >= 0.')
while True:
print('Enter the Preference threshold (p) for criterion', x.critNames[criterion]+':')
x.p[0, criterion] = input_data()
if x.p[0, criterion] >= x.q[0, criterion]:
break
else:
print('The value has to be >= of q=' +
str(x.q[0, criterion]), 'for criterion', x.critNames[criterion] + '.')
while True:
print('Enter the Veto threshold (v) for criterion', x.critNames[criterion]+':')
x.v[0, criterion] = input_data()
if x.v[0, criterion] >= 0: # x.p[0, criterion]:
break
else:
print('The value has to be >= 0. If there is no value just enter 0.')
return x
def generate_r_thresh_values(class_1: El3_init, class_2: El3_init): # random generated data
x = class_1
y = class_2
rng = np.random.default_rng()
y.w = x.w.copy()
y.p = x.p.copy()
y.q = x.q.copy()
y.v = x.v.copy()
tolerance = y.tolerance
dist = y.dist
while True:
w = rng.random(size=np.shape(x.w), dtype=np.float64) # uniform
w /= w.sum(axis=1)
if np.sum(w[0, :-1]) < 1:
w[0, -1] = 1 - np.sum(w[0, :-1])
y.w = w
break
for crit in range(x.crit):
if dist == '1':
y.q[0, crit] = float(rng.uniform(low=(x.q[0, crit] - (tolerance * x.q[0, crit])),
high=(x.q[0, crit] + (tolerance * x.q[0, crit])), size=1))
while True:
if x.p[0, crit] != 0:
p = float(rng.uniform(low=(x.p[0, crit] - (tolerance * x.p[0, crit])),
high=(x.p[0, crit] + (tolerance * x.p[0, crit])), size=1))
if p >= y.q[0, crit]:
y.p[0, crit] = p
break
else:
p = float(rng.uniform(low=0, high=tolerance, size=1))
if p >= y.q[0, crit]:
y.p[0, crit] = p
break
while True:
if x.v[0, crit] != 0:
v = float(rng.uniform(low=(x.v[0, crit] - (tolerance * x.v[0, crit])),
high=(x.v[0, crit] + (tolerance * x.v[0, crit])), size=1))
if v >= y.p[0, crit]:
y.v[0, crit] = v
break
else:
v = float(rng.uniform(low=0, high=tolerance, size=1))
y.v[0, crit] = v
break
elif dist == '2':
val = np.array([(x.q[0, crit] - (tolerance * x.q[0, crit])), (x.q[0, crit] + (tolerance * x.q[0, crit]))])
m = np.mean(a=val)
s = np.std(a=val)
y.q[0, crit] = rng.normal(loc=float(m), scale=s/3.05)
while True:
if x.p[0, crit] != 0:
val[0] = (x.p[0, crit] - (tolerance * x.p[0, crit]))
val[1] = (x.p[0, crit] + (tolerance * x.p[0, crit]))
m = np.mean(a=val)
s = np.std(a=val)
p = rng.normal(loc=float(m), scale=s/3.05)
if p >= y.q[0, crit]:
y.p[0, crit] = p
break
else:
val[0] = 0
val[1] = tolerance
m = np.mean(a=val)
s = np.std(a=val)
p = rng.normal(loc=float(m), scale=s/3.05)
if p >= y.q[0, crit]:
y.p[0, crit] = p
break
while True:
if x.v[0, crit] != 0:
val[0] = (x.v[0, crit] - (tolerance * x.v[0, crit]))
val[1] = (x.v[0, crit] + (tolerance * x.v[0, crit]))
m = np.mean(a=val)
s = np.std(a=val)
v = rng.normal(loc=float(m), scale=s/3.05)
if v >= y.p[0, crit]:
y.v[0, crit] = v
break
else:
val[0] = 0
val[1] = tolerance
m = np.mean(a=val)
s = np.std(a=val)
v = rng.normal(loc=float(m), scale=s/3.05)
y.v[0, crit] = v
break
elif dist == '3':
left = (x.q[0, crit] - (tolerance * x.q[0, crit]))
right = (x.q[0, crit] + (tolerance * x.q[0, crit]))
y.q[0, crit] = rng.triangular(left=left, right=right,
mode=float(rng.uniform(low=left, high=right, size=1)), size=1)
while True:
if x.p[0, crit] != 0:
left = (x.p[0, crit] - (tolerance * x.p[0, crit]))
right = (x.p[0, crit] + (tolerance * x.p[0, crit]))
p = rng.triangular(left=left, right=right,
mode=float(rng.uniform(low=left, high=right, size=1)), size=1)
if p >= y.q[0, crit]:
y.p[0, crit] = p
break
else:
left = 0
right = tolerance
p = rng.triangular(left=left, right=right,
mode=float(rng.uniform(low=left, high=right, size=1)), size=1)
if p >= y.q[0, crit]:
y.p[0, crit] = p
break
while True:
if x.v[0, crit] != 0:
left = (x.v[0, crit] - (tolerance * x.v[0, crit]))
right = (x.v[0, crit] + (tolerance * x.v[0, crit]))
v = rng.triangular(left=left, right=right,
mode=float(rng.uniform(low=left, high=right, size=1)), size=1)
if v >= y.p[0, crit]:
y.v[0, crit] = v
break
else:
left = 0
right = tolerance
v = rng.triangular(left=left, right=right,
mode=float(rng.uniform(low=left, high=right, size=1)), size=1)
y.v[0, crit] = v
break
elif dist == '4':
thresh = np.array([(x.q[0, crit] - (tolerance * x.q[0, crit])),
(x.q[0, crit] + (tolerance * x.q[0, crit]))])
exp = rng.uniform(low=float(thresh[0]), high=float(thresh[1]), size=1)
coef = 1 + (4 * (((exp - thresh[0]) * (thresh[1] - exp)) /
((thresh[1] - thresh[0]) * (thresh[1] - thresh[0]))))
Alpha = (2 * thresh[1] + (4 * exp) - (5 * thresh[0])) / (3 * (thresh[1] - thresh[0])) * coef
Beta = (2 * (5 * thresh[1]) - (4 * exp) - thresh[0]) / (3 * (thresh[1] - thresh[0])) * coef
c = rng.beta(a=float(Alpha), b=float(Beta), size=1)
interval = thresh[1] - thresh[0]
relocation = thresh[0] + (interval * c)
q = relocation
if q >= thresh[0] and q <= thresh[1]:
y.q[0, crit] = q
while True:
if x.p[0, crit] != 0:
thresh[0] = (x.p[0, crit] - (tolerance * x.p[0, crit]))
thresh[1] = (x.p[0, crit] + (tolerance * x.p[0, crit]))
exp = rng.uniform(low=float(thresh[0]), high=float(thresh[1]), size=1)
coef = 1 + (4 * (((exp - thresh[0]) * (thresh[1] - exp)) /
((thresh[1] - thresh[0]) * (thresh[1] - thresh[0]))))
Alpha = (2 * thresh[1] + (4 * exp) - (5 * thresh[0])) / (3 * (thresh[1] - thresh[0])) * coef
Beta = (2 * (5 * thresh[1]) - (4 * exp) - thresh[0]) / (3 * (thresh[1] - thresh[0])) * coef
c = rng.beta(a=float(Alpha), b=float(Beta), size=1)
interval = thresh[1] - thresh[0]
relocation = thresh[0] + (interval * c)
p = relocation
if p >= y.q[0, crit] and p <= thresh[1]:
y.p[0, crit] = p
break
else:
thresh[0] = 0
thresh[1] = tolerance
exp = rng.uniform(low=float(thresh[0]), high=float(thresh[1]), size=1)
coef = 1 + (4 * (((exp - thresh[0]) * (thresh[1] - exp)) /
((thresh[1] - thresh[0]) * (thresh[1] - thresh[0]))))
Alpha = (2 * thresh[1] + (4 * exp) - (5 * thresh[0])) / (3 * (thresh[1] - thresh[0])) * coef
Beta = (2 * (5 * thresh[1]) - (4 * exp) - thresh[0]) / (3 * (thresh[1] - thresh[0])) * coef
c = rng.beta(a=float(Alpha), b=float(Beta), size=1)
interval = thresh[1] - thresh[0]
relocation = thresh[0] + (interval * c)
p = relocation
if p >= y.q[0, crit] and p <= thresh[1]:
y.p[0, crit] = p
break
while True:
if x.v[0, crit] != 0:
thresh[0] = (x.v[0, crit] - (tolerance * x.v[0, crit]))
thresh[1] = (x.v[0, crit] + (tolerance * x.v[0, crit]))
exp = rng.uniform(low=float(thresh[0]), high=float(thresh[1]), size=1)
coef = 1 + (4 * (((exp - thresh[0]) * (thresh[1] - exp)) /
((thresh[1] - thresh[0]) * (thresh[1] - thresh[0]))))
Alpha = (2 * thresh[1] + (4 * exp) - (5 * thresh[0])) / (3 * (thresh[1] - thresh[0])) * coef
Beta = (2 * (5 * thresh[1]) - (4 * exp) - thresh[0]) / (3 * (thresh[1] - thresh[0])) * coef
c = rng.beta(a=float(Alpha), b=float(Beta), size=1)
interval = thresh[1] - thresh[0]
relocation = thresh[0] + (interval * c)
v = relocation
if v >= y.p[0, crit] and v <= thresh[1]:
y.v[0, crit] = v
break
else:
thresh[0] = 0
thresh[1] = tolerance
exp = rng.uniform(low=float(thresh[0]), high=float(thresh[1]), size=1)
coef = 1 + (4 * (((exp - thresh[0]) * (thresh[1] - exp)) /
((thresh[1] - thresh[0]) * (thresh[1] - thresh[0]))))
Alpha = (2 * thresh[1] + (4 * exp) - (5 * thresh[0])) / (3 * (thresh[1] - thresh[0])) * coef
Beta = (2 * (5 * thresh[1]) - (4 * exp) - thresh[0]) / (3 * (thresh[1] - thresh[0])) * coef
c = rng.beta(a=float(Alpha), b=float(Beta), size=1)
interval = thresh[1] - thresh[0]
relocation = thresh[0] + (interval * c)
v = relocation
if v >= thresh[0] and v <= thresh[1]:
y.v[0, crit] = v
break
return y
def run(class_: ld.Store_data): # run with user input from console [not used with GUI]
x = class_
x = El3_init(class_=x)
x = get_input(class_=x)
return x
def run_r(class_: El3_init, tolerance, dist): # run with generator attributes
x = class_
x.tolerance = tolerance
x.dist = dist
y = copy.deepcopy(x)
y = generate_r_thresh_values(class_1=x, class_2=y)
return y |
class Solution:
# T.C: O(N) for loop + O(N + E) for one DFS => O(N + E)
# S.C: O(N) for visited + O(N) for pathVisited + O(N) for safeNodes + max O(N) for recursion => O(N)
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
n = len(graph)
visited = [ False ] * n
pathVisited = [ False ] * n
safeNodes = [ False ] * n
for i in range(n):
if not visited[i]:
self.dfs(i, visited, pathVisited, safeNodes, graph)
ans = []
for i in range(n):
if safeNodes[i]:
ans.append(i)
return ans
def dfs(self, node, visited, pathVisited, safeNodes, graph):
visited[node] = True
pathVisited[node] = True
for adjNode in graph[node]:
# if a cycle is detected return False from here
# and keep the pathVisited[node] as True as it would denote cycle
if visited[adjNode] is False:
if not self.dfs(adjNode, visited, pathVisited, safeNodes, graph):
return False
elif pathVisited[adjNode]:
return False
safeNodes[node] = True
pathVisited[node] = False
return True |
import React, { useEffect, useState } from 'react'
import AxiosClient from '../../config/AxiosClient'
import Swal from 'sweetalert2'
import Navbar from '../shared/Navbar'
import Footer from '../shared/Footer'
import { Link, useNavigate } from "react-router-dom";
import { Button, Row, Col, Modal } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faPenToSquare, faTrashCan } from '@fortawesome/free-solid-svg-icons'
import '../css/config.css'
import { SideBarMenu } from '../shared/SideBarMenu';
interface Config {
id: string
NumeroRegistro: string
Llave: string
}
const Config = () => {
let navigate = useNavigate()
//Modal Registrar
const [showModal, setShowModal] = useState(false);
const handleClose = () => setShowModal(false);
const handleShow = () => setShowModal(true);
//Modal editar
const [show, setShow] = useState(false);
const handleCloseE = () => setShow(false);
const handleShowE = () => setShow(true);
//Lista de configuraciones para la tabla
const [configuraciones, setConfiguraciones] = useState<Array<Config>>([])
const [inputValues, setInputValues] = useState<Config>({
id: '',
NumeroRegistro: '',
Llave: ''
})
useEffect(() => {
AxiosClient.get('/api/configuraciones/getAllConfig/').then((result) => {
console.log(result.data)
setConfiguraciones(result.data)
//console.log(configuraciones)
})
}, [])
const handleSubmit = async (evt: React.FormEvent<HTMLFormElement>) => {
evt.preventDefault();
AxiosClient.post('/api/configuraciones/addConfig/', inputValues).then(res => {
Swal.fire({
position: 'center',
icon: 'success',
title: 'Registrado éxitosamente',
showConfirmButton: false,
timer: 1500
}).then(() => {
setShowModal(showModal => !showModal)
//navigate('/Config');
window.location.href = '/Config';
})
}).catch(error => {
console.log(error);
Swal.fire({
icon: "error",
title: error.status,
text: "No se pudo registrar",
});
})
}
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValues({
...inputValues,
[e.target.name]: e.target.value
})
}
const handleDelete = (e: React.MouseEvent<HTMLButtonElement>) => {
AxiosClient.delete('/api/configuraciones/deleteConfig/' + e.currentTarget.value).then(res => {
Swal.fire({
position: 'center',
icon: 'success',
title: 'Eliminado éxitosamente',
showConfirmButton: false,
timer: 1500
}).then(() => {
//navigate('/Config');
window.location.href = '/Config';
})
}).catch(error => {
console.log(error);
Swal.fire({
icon: "error",
title: error.status,
text: "No se pudo eliminar",
});
})
}
const handleEdit = (e: React.MouseEvent<HTMLButtonElement>) => {
AxiosClient.get('/api/configuraciones/getConfig/' + e.currentTarget.value).then((result) => {
setInputValues(result.data);
handleShowE();
})
}
const updateEdit = async (evt: React.FormEvent<HTMLFormElement>) => {
evt.preventDefault();
console.log(inputValues);
AxiosClient.put('/api/configuraciones/updateConfig/' + inputValues.id, inputValues).then(res => {
Swal.fire({
position: 'center',
icon: 'success',
title: 'Editado éxitosamente',
showConfirmButton: false,
timer: 1500
}).then(() => {
handleCloseE();
//navigate('/Config');
window.location.href = '/Config';
})
}).catch(error => {
console.log(error);
Swal.fire({
icon: "error",
title: error.status,
text: "No se pudo editar",
});
})
}
return (
<div>
<Row>
<Col>Nombre Persona</Col>
</Row>
<Row>
<Col className='col-sm-2'>
<SideBarMenu />
</Col>
<Col className="col-sm-10">
<div className="row">
<div className="row">
<h1 className="titulo">Configuraciones</h1>
</div>
<div className="row">
<div className="col">
<Button type="button" className="insert" onClick={handleShow}>Insertar</Button>
</div>
<div className="col"></div>
<div className="col"></div>
</div>
<div className="row">
<div className="col-sm-9">
<table className="tableC">
<thead>
<tr >
<th>LLave</th>
<th># registros</th>
<th>Editar</th>
<th>Eliminar</th>
</tr>
</thead>
<tbody>
{
configuraciones.map(config => {
return (
<tr key={config.Llave} className="table-success">
<th> {config.Llave} </th>
<th> {config.NumeroRegistro} </th>
<th>
<Button value={config.id} onClick={handleEdit} >
<FontAwesomeIcon icon={faPenToSquare}></FontAwesomeIcon>
</Button>
</th>
<th>
<Button value={config.id} onClick={handleDelete} >
<FontAwesomeIcon icon={faTrashCan}></FontAwesomeIcon>
</Button>
</th>
</tr>
)
})
}
</tbody>
</table>
</div>
<div className="row"></div>
</div>
</div>
<div>
<Modal show={showModal} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Formulario</Modal.Title>
</Modal.Header>
<Modal.Body>
<form onSubmit={handleSubmit}>
<input className="form-control" type="text" onChange={handleChange} value={inputValues.NumeroRegistro}
name='NumeroRegistro' placeholder='# de registros' />
<input className="form-control" type="text" onChange={handleChange} value={inputValues.Llave}
name='Llave' placeholder='Llave' />
<button> Registrar </button>
</form>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose} >Close</Button>
</Modal.Footer>
</Modal>
</div>
<div>
<Modal show={show} onHide={handleCloseE}>
<Modal.Header closeButton>
<Modal.Title>Editar</Modal.Title>
</Modal.Header>
<Modal.Body>
<form onSubmit={updateEdit}>
<input className="form-control" type="text" onChange={handleChange} value={inputValues.id}
name='id' disabled />
<input className="form-control" type="text" onChange={handleChange} value={inputValues.NumeroRegistro}
name='NumeroRegistro' placeholder='# de registros' />
<input className="form-control" type="text" onChange={handleChange} value={inputValues.Llave}
name='Llave' placeholder='Llave' />
<button> Editar </button>
</form>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleCloseE} >Close</Button>
</Modal.Footer>
</Modal>
</div>
</Col>
</Row>
<Row>
< Footer></Footer>
</Row>
</div>
);
}
export default Config |
<div class="c-mod wh-box1 clearfix">
<form id="saveForm" action="$appServer.get('/person/fill.htm')" method="post">
#if(${item.id})
<input type="hidden" name="id" value="$!{item.id}"/>
#end
<input id="cardImg" type="hidden" name="cardImg" value="$!{item.cardImg}"/>
<input id="headImg" type="hidden" name="headImg" value="$!{item.headImg}"/>
<h1>个人资料</h1>
<ul class="c-bczl">
<li class="c-bcz clearfix"><span class="c-b-txt">头像:</span><span class="c-comptx c-gr-tx">
<a id="headImgBtn" href="javascript:;">
#if($!{item.headImg} && $!{item.headImg} != "")
<img src="$!{uploadServer}/img/$!{item.headImg}.img">
#else
<em class="up-avatar">上 传</em>
#end
</a>
</span></li>
#springBind("item.name")
<li class="c-bcz clearfix"><span class="c-b-txt">姓名:</span>
<input type="text" required="true" class="form-inp form-short" name="$!{status.expression}" value="$!{status.value}" maxlength="20">
</li>
#if($status.isError())<li class="c-b-ts"><span class="rd">$!{status.errorMessage}</span></li>#end
#springBind("item.cardType")
## <li class="c-bcz clearfix"><span class="c-b-txt">手机号:</span><input type="text" class="form-inp form-short" name="" placeholder="请输入手机号"><span class="c-gr-ts rd">请输入正确的手机号,便于我们及时与您联系!</span></li>
## <li class="c-bcz clearfix"><span class="c-b-txt">邮箱:</span><input type="text" class="form-inp form-short" name="" placeholder="请输入邮箱"></li>
<li class="c-bcz clearfix"><span class="c-b-txt">证件类型:</span>
<select id="cardType" class="form-sel form-short" name="$!{status.expression}" >
<option value="1" #if("1" == "$!{status.value}") selected #end>身份证</option>
<option value="2" #if("2" == "$!{status.value}") selected #end>护照</option>
<option value="3" #if("3" == "$!{status.value}") selected #end>军官证</option>
</select>
</li>
#if($status.isError())<li class="c-b-ts"><span class="rd">$!{status.errorMessage}</span></li>#end
#springBind("item.cardNo")
<li class="c-bcz clearfix"><span class="c-b-txt">证件号码:</span>
<input type="text" required="true" class="form-inp form-short" name="$!{status.expression}" value="$!{status.value}" maxlength="20">
</li>
<li class="c-bcz clearfix"><span class="c-b-txt" >上传证件:</span>
<span class="c-up-box" ><a id="cardImgBtn" href="javascript:;">
#if($!{item.cardImg} && $!{item.cardImg} != "")
<img src="$!{uploadServer}/img/$!{item.cardImg}.img"/>
#else
<img src="$imageServer.get('images/up_zm.jpg')">
#end</a>
## <a href="" class="c-up-close">×</a>
</span>
</li>
</li>
#if($status.isError())<li class="c-b-ts"><span class="rd">$!{status.errorMessage}</span></li>#end
</ul>
<div class="c-subdiv"><button class="c-btnsub">提交</button></div>
</form>
</div>
#set($vjs = $imageServer.get('js/lib/jquery.validate.min.js'))
#js($vjs)
#set($ljs = $imageServer.get('layui/layui.js'))
#js($ljs)
#set($ujs = $imageServer.get('js/upload.js'))
#js($ujs)
<script>
$(function () {
#if($errorMessage && $errorMessage != "")
layui.use("layer",function() {
layui.layer.alert("$!{errorMessage}");
});
#end
layui.use('layer', function () {
var $ = layui.jquery, layer = layui.layer;
//预览图片实现
$(".previewBtn").click(function () {
var imgBox = $(this).parent().find(".img_box");
layer.open({
type: 1,
shade: false,
title: false,
content: imgBox
});
});
var loadIndex;
//头像图片上传
$("#headImgBtn").fileUpload({
uploadUrl: "$!{uploadServer}/upload/file.htm",//上传路径
type: 0,//0:图片 1:文档 2:视频 3:音频
docType: "GRTX",//档案类型
objectId: "$!{user.memberId}",//档案目标id(所属人)
beforeUpload: function(path) {
loadIndex = layer.load(0, {shade: false});
},
uploadEnd: function(result){
if(result.success == true) {
$("#headImg").val(result.id);
$("#headImgBtn").html("");
$("#headImgBtn").showImg('$!{uploadServer}/img/'+ result.id +'.img');
} else {
layer.alert(result.error);
}
layer.close(loadIndex);
}
});
//证件图片上传
$("#cardImgBtn").fileUpload({
uploadUrl: "$!{uploadServer}/upload/file.htm",//上传路径
type: 0,//0:图片 1:文档 2:视频 3:音频
docType: "SFZ",//档案类型
objectId: "$!{user.memberId}",//档案目标id(所属人)
beforeUpload: function(path) {
//切换档案类型
var dType = ("2" == $("#cardType").val()) ? "HZ" : "SFZ";
$("input[name='docType']").val(dType);
loadIndex = layer.load(0, {shade: false});
},
uploadEnd: function(result){
if(result.success == true) {
$("#cardImg").val(result.id);
$("#cardImgBtn").find('img').remove();
$("#cardImgBtn").showImg('$!{uploadServer}/img/'+ result.id +'.img');
} else {
layer.alert(result.error);
}
layer.close(loadIndex);
}
});
});
jQuery.validator.addMethod("charactor", function(value, element, params) {
return this.optional(element) || /^[a-zA-Z0-9]*$/.test(value);
}, jQuery.validator.format("编码仅可以输入字母或数字"));
$ ("#saveForm").validate({
ignore: ".ignore",
rules: {
name: "required",
cardType: "required",
cardNo: {
required: true,
charactor: true
}
},
messages: {
name: "请输入姓名",
cardType: "请选择证件类型",
cardNo: {
required: "请输入证件号码",
charactor: "证件号码尽可以输入字母和数字"
}
},
errorPlacement: function(error, element) {
$ (".error").find("label").remove();
element.parent().after(error);
},
submitHandler: function(form) {
form.submit();
}
});
});
</script> |
from typing import Any, Dict, List, Type, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="SearchFacetCountResponseDto")
@_attrs_define
class SearchFacetCountResponseDto:
"""
Attributes:
count (int):
value (str):
"""
count: int
value: str
additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> Dict[str, Any]:
count = self.count
value = self.value
field_dict: Dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"count": count,
"value": value,
}
)
return field_dict
@classmethod
def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:
d = src_dict.copy()
count = d.pop("count")
value = d.pop("value")
search_facet_count_response_dto = cls(
count=count,
value=value,
)
search_facet_count_response_dto.additional_properties = d
return search_facet_count_response_dto
@property
def additional_keys(self) -> List[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties |
import { BaseChart, PartialChart } from './base'
import {
Dimension,
Metric,
Report,
ChartType,
} from './util'
import { getColorschemeColors } from '../../../shared'
export default class FunnelChart extends BaseChart {
constructor (def: PartialChart = {}) {
super(def)
// Assure required fields; this helps with backwards compatibility
for (const v of (this.config.reports || []) as Array<Report>) {
for (const d of (v.dimensions || []) as Array<Dimension>) {
if (!d.meta) {
d.meta = {}
}
if (!d.meta.fields) {
d.meta.fields = []
}
}
for (const m of (v.metrics || []) as Array<Metric>) {
if (m.cumulative === undefined) {
m.cumulative = true
}
}
}
}
/**
* Since funnel charts always define one type, this check can be simplified
*/
mtrCheck ({ field, aggregate }: Metric) {
if (!field) {
throw new Error('notification.chart.invalidConfig.missingMetricsField')
}
if (field !== 'count' && !aggregate) {
throw new Error('notification.chart.invalidConfig.missingMetricsAggregate')
}
}
/**
* Extend this method to include filtering for just specific values.
* For example:
* We wish to show only new and converted leads.
*/
formatReporterParams (r: Report) {
const base = super.formatReporterParams(r)
const ff = base.filter
let df = ''
if (r.dimensions && r.dimensions[0]) {
const rd = r.dimensions[0]
if (r.dimensions[0].meta) {
const fields = r.dimensions[0].meta.fields || []
df = fields.map(({ value }: any) => `${rd.field || ''}='${value}'`)
.join(' OR ')
}
}
if (ff && df) {
base.filter = `(${base.filter}) AND (${df})`
} else if (!ff && df) {
base.filter = df
}
return base
}
// Funnel chart creates a metric including all reports, so this step is deferred to there
makeDataset (m: Metric, d: Dimension, data: Array<number|any>, alias: string) {
return {
type: m.type,
label: m.label || m.field,
data,
tooltip: {
fixed: !!m.fixTooltips,
relative: !!m.relativeValue,
},
}
}
makeOptions (data: any) {
const { reports = [], colorScheme, noAnimation = false, toolbox } = this.config
const { saveAsImage } = toolbox || {}
const { labels, datasets = [], tooltip } = data
const { legend: l } = reports[0] || {}
const colors = getColorschemeColors(colorScheme)
const tooltipFormatter = `{b}<br />{c} ${tooltip.relative ? ' ({d}%)' : ''}`
const labelFormatter = `{c}${tooltip.relative ? ' ({d}%)' : ''}`
return {
animation: !noAnimation,
textStyle: {
fontFamily: 'Poppins-Regular',
},
toolbox: {
feature: {
saveAsImage: saveAsImage ? {
name: this.name
} : undefined,
},
top: 15,
right: 5,
},
tooltip: {
show: true,
trigger: 'item',
formatter: tooltipFormatter,
appendToBody: true,
},
legend: {
show: !l?.isHidden,
type: l?.isScrollable ? 'scroll' : 'plain',
top: (l?.position?.isDefault ? undefined : l?.position?.top) || undefined,
right: (l?.position?.isDefault ? undefined : l?.position?.right) || undefined,
bottom: (l?.position?.isDefault ? undefined : l?.position?.bottom) || undefined,
left: (l?.position?.isDefault ? l?.align || 'center' : l?.position?.left) || 'auto',
orient: l?.orientation || 'horizontal'
},
series: datasets.map(({ data }: any) => {
return {
type: 'funnel',
sort: 'descending',
top: 45,
bottom: 10,
left: '5%',
width: '90%',
label: {
show: tooltip.fixed,
position: 'inside',
align: 'center',
verticalAlign: 'middle',
formatter: labelFormatter,
},
emphasis: {
label: {
show: tooltip.fixed,
fontSize: 14,
},
},
data: labels.map((name: string, i: number) => {
return { name, value: data[i], itemStyle: { color: colors[i] } }
}),
}
}),
}
}
baseChartType (): string {
return 'funnel'
}
/**
* Includes a few additional post processing steps:
* * generate a set of labels based on all reports, all data sets,
* * generates a set of data based on all reports, all data sets,
*/
async fetchReports (a: any) {
const rr = await super.fetchReports(a) as any
const values = []
let tooltip = {}
// Above provided data sets might not have their labels/values ordered
// correctly
const valMap: any = {}
// Map values to their labels
for (let ri = 0; ri < rr.length; ri++) {
const r = rr[ri]
r.labels.forEach((l: string, i: number) => {
valMap[l] = r.datasets[0].data[i]
})
tooltip = { ...tooltip, ...r.datasets[0].tooltip }
// Construct labels & data based on provided reports
const report = this.config.reports?.[ri]
const d = report?.dimensions?.[0] as Dimension
let { fields = [] } = d.meta || {}
fields = fields.length ? fields : r.labels
for (let label of fields) {
const value = typeof label === 'object' ? label.value : label
values.push({
// Use value for label and resolve it on FE (i18n)
label: value,
data: valMap[value] || 0,
})
}
}
// We are rendering the chart upside down
// (by default it renders in ASC, but we want DESC)
const labels: any[] = []
const data: any[] = []
values.sort((a, b) => a.data - b.data).forEach(v => {
labels.push(v.label)
data.push(v.data)
})
// Determine color to render for specific value
const colorMap: { [_: string]: string } = {}
this.config.reports?.forEach(r => {
for (const { value, color } of r.dimensions?.[0].meta?.fields) {
colorMap[value] = color
}
})
// Get cumulative data but also keep original for tooltips
if (this.isCumulative()) {
for (let i = 1; i < data.length; i++) {
data[i] += data[i - 1]
}
}
return {
labels,
datasets: [{
data,
}],
tooltip,
}
}
isCumulative (): boolean {
// Cumulative true by default
// Find false value
let cumulative = true
const { reports = [] } = this.config
reports.forEach(({ metrics = [] }) => {
if (cumulative && !metrics[0].cumulative) {
cumulative = false
}
})
return cumulative
}
defMetrics (): Metric {
return Object.assign({}, {
type: ChartType.funnel,
fixTooltips: false,
relativeValue: true,
})
}
defDimension (): Dimension {
return Object.assign({}, {
conditions: {},
meta: { fields: [] }
})
}
} |
package dbconn
import (
"context"
"database/sql"
"fmt"
"github.com/siddontang/loggers"
"github.com/cashapp/spirit/pkg/table"
)
type TableLock struct {
table *table.TableInfo
lockTxn *sql.Tx
logger loggers.Advanced
}
// NewTableLock creates a new server wide lock on a table.
// i.e. LOCK TABLES .. READ.
// It uses a short-timeout with backoff and retry, since if there is a long-running
// process that currently prevents the lock by being acquired, it is considered "nice"
// to let a few short-running processes slip in and proceed, then optimistically try
// and acquire the lock again.
func NewTableLock(ctx context.Context, db *sql.DB, table *table.TableInfo, writeLock bool, config *DBConfig, logger loggers.Advanced) (*TableLock, error) {
lockStmt := "LOCK TABLES " + table.QuotedName + " READ"
if writeLock {
lockStmt = fmt.Sprintf("LOCK TABLES %s WRITE, `%s`.`_%s_new` WRITE",
table.QuotedName,
table.SchemaName, table.TableName,
)
}
var err error
var isFatal bool
var lockTxn *sql.Tx
for i := 0; i < config.MaxRetries; i++ {
func() {
lockTxn, _ = db.BeginTx(ctx, nil)
defer func() {
if err != nil {
_ = lockTxn.Rollback()
if i < config.MaxRetries-1 && !isFatal {
backoff(i)
}
}
}()
// In gh-ost they lock the _old table name as well.
// this might prevent a weird case that we don't handle yet.
// instead, we DROP IF EXISTS just before the rename, which
// has a brief race.
logger.Warnf("trying to acquire table lock, timeout: %d", config.LockWaitTimeout)
_, err = lockTxn.ExecContext(ctx, lockStmt)
if err != nil {
// See if the error is retryable, many are
if !canRetryError(err) {
isFatal = true
return
}
logger.Warnf("failed trying to acquire table lock, backing off and retrying: %v", err)
return
}
}()
// check if successful
if err == nil {
logger.Warn("table lock acquired")
return &TableLock{
table: table,
lockTxn: lockTxn,
logger: logger,
}, nil
}
}
// retries exhausted, return the last error
return nil, err
}
// ExecUnderLock executes a set of statements under a table lock.
func (s *TableLock) ExecUnderLock(ctx context.Context, stmts []string) error {
for _, stmt := range stmts {
if stmt == "" {
continue
}
_, err := s.lockTxn.ExecContext(ctx, stmt)
if err != nil {
return err
}
}
return nil
}
// Close closes the table lock
func (s *TableLock) Close() error {
_, err := s.lockTxn.Exec("UNLOCK TABLES")
if err != nil {
return err
}
err = s.lockTxn.Rollback()
if err != nil {
return err
}
s.logger.Warn("table lock released")
return nil
} |
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
import argparse
import os
import sys
from pathlib import Path
import cv2
import torch
import torch.backends.cudnn as cudnn
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0] # YOLOv5 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
from utils.common import DetectMultiBackend
from utils.datasets import LoadStreams
from utils.general import (check_img_size, check_imshow, check_requirements,non_max_suppression, print_args, scale_coords)
from utils.plots import Annotator, colors
from utils.torch_utils import select_device, time_sync
@torch.no_grad()
def run(weights=ROOT / 'runs/train/exp11/weights/best.pt', # model.pt path(s)
source=0, # file/dir/URL/glob, 0 for webcam
data=ROOT / '../V5_data/data.yaml', # dataset.yaml path
imgsz=(640, 640), # inference size (height, width)
conf_thres=0.25, # confidence threshold
iou_thres=0.45, # NMS IOU threshold
max_det=1000, # maximum detections per image
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
classes=None, # filter by class: --class 0, or --class 0 2 3
agnostic_nms=False, # class-agnostic NMS
augment=False, # augmented inference
line_thickness=3, # bounding box thickness (pixels)
hide_labels=False, # hide labels
hide_conf=False, # hide confidences
half=False, # use FP16 half-precision inference
dnn=False, # use OpenCV DNN for ONNX inference
):
source = str(source)
# Load model
device = select_device(device)
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data)
stride, names, pt, jit, onnx, engine = model.stride, model.names, model.pt, model.jit, model.onnx, model.engine
imgsz = check_img_size(imgsz, s=stride) # check image size
# Half pytorch混合精度
half &= (pt or jit or onnx or engine) and device.type != 'cpu' # FP16 supported on limited backends with CUDA
if pt or jit:
model.model.half() if half else model.model.float()
# Dataloader
view_img = check_imshow()#检查能否显示
cudnn.benchmark = True # set True to speed up constant image size inference
dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)#开启摄像头 0 (640, 640) 32 True
bs = len(dataset) # batch_size
# Run inference
model.warmup(imgsz=(1 if pt else bs, 3, *imgsz), half=half) # warmup
dt, seen = [0.0, 0.0, 0.0], 0
for path, im, im0s, vid_cap, s in dataset:
t1 = time_sync()
im = torch.from_numpy(im).to(device)
im = im.half() if half else im.float() # uint8 to fp16/32
im /= 255 # 0 - 255 to 0.0 - 1.0
if len(im.shape) == 3:
im = im[None] # expand for batch dim
t2 = time_sync()
dt[0] += t2 - t1
# Inference
pred = model(im, augment=augment, visualize=False)
t3 = time_sync()
dt[1] += t3 - t2
# NMS
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
dt[2] += time_sync() - t3
# Process predictions
for i, det in enumerate(pred): # per image
p, im0, frame = path[i], im0s[i].copy(), dataset.count
annotator = Annotator(im0, line_width=line_thickness, example=str(names))
if len(det): #每张图上有几个检测到的目标
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
# Write results
for *xyxy, conf, cls in reversed(det):
c = int(cls) # integer class
label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
x=annotator.box_label(xyxy, label, color=colors(c, True))
print("左上角:",x[0],"右下角:",x[1],"cls:",x[2][:-4],"confidence:",x[2][-4:])
im0 = annotator.result()
if view_img:
cv2.imshow(str(p), im0)
cv2.waitKey(1) # 1 millisecond
if __name__ == "__main__":
run() |
---
title: Gerando cobranças
keywords: cobranças, pagamentos, split de pagamentos, crédito, pix, boleto
last_updated: July 3, 2016
tags: [cobranças, pagamentos, split, crédito, pix, boleto]
summary: "Veja como gerar cobranças e escolher os métodos de pagamento que irá aceitar"
sidebar: mydoc_sidebar
permalink: gerando-cobrancas.html
folder: pagamentos
---
## Introdução
Neste guia vamos ver como cadastrar uma fatura através de nossa API. Antes de realizar pagamentos é necessário cadastrar uma fatura. No cadastro da fatura você pode:
* Informar os itens que estão sendo comercializados;
* Escolher e restringir os métodos de pagamento a serem aceitos (opcional);
* Escolher o número máximo de parcelas (opcional);
* Cadastrar o cliente que irá efetuar o pagamento (opcional).
* Cadastrar taxas para serem dividas entre outros estabelecimentos cadastrados na Gen (Split de Pagamentos)
## Criando a fatura
Você deve cadastrar uma fatura na plataforma da Gen informando os dados dos itens omercializados. Os dados do cliente são opcionais, você pode informar ou deixar que ele insira durante o pagamento.
Envie uma requisição POST na API de pedidos com os dados no formato a seguir:
[Referência da API: Pedidos](https://docs.gen.com.br/#4617b1ac-d942-4645-bc0c-760e790c0c13)
``` bash
curl -X POST 'https://api-dev.genpag.com.br/api/sellers/:sellerId/orders' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer (access token)' \
--data '{
"order": {
"items": [
{
"description": "Produto 1",
"quantity": 2,
"unit_price_cents": 2290
}
],
"customer_id": "28f7cfc6-465c-99d3-d0ff-80367b49ce12",
"customer": {
"name": "Jhon Trevor",
"email": "customer@email.com",
"cpf": "01234567891",
"phone": "+5562992929292",
"birth_date": "1965-08-10",
"cnpj": "12345678000166",
address": {
"line1": "Rua tal",
"line2": "0",
"line3": "QD 2, LT 1, Ed. Sala 100"
"neighborhood": "Centro",
"city": "São Paulo",
"state": "SP",
"country_code": "BR",
"postal_code": "01153-000"
}
},
}
}'
```
* **items**: Um array contendo os itens vendidos
* **description**: Descrição do item
* **unit_price_cents**: Valor do item em centavos
* **quantity**: Quantidade de itens
* **customer_id**: O ID de um cliente já cadastrado na plataforma. Você pode enviar somente este campo, ou então os dados do cliente no objeto customer
* **customer**
* **address**: Endereço do cliente
* **line1**: Rua
* **line2**: Número ou 0 se não houver número no endereço
* **line3**: Complemento
* **city**: Cidade
* **state**: Estado, sigla
* **neighborhood**: Bairro
* **postal_code**: CEP
* **country_code**: Código do país
* **cpf**: CPF do cliente
* **cnpj**: CNPJ do cliente se for pessoa jurídica
* **phone**: Telefone do cliente
* **email**: E-mail do cliente
## Restringindo formas de pagamento
As formas de pagamento disponíveis na plataforma são:
* Cartão de crédito;
* Boleto;
* PIX.
Por padrão, todos os métodos são aceitos para uma fatura recém criada, mas você pode restringir quais formas de pagamento podem ser utilizadas em um pedido específico utilizando o campo **methods**.
Os valores disponíveis são:
* **CREDIT**: Cartão de crédito
* **BANK_SLIP**: Boleto
* **PIX**: Pix de cobrança
```bash
curl -X POST 'https://api-dev.genpag.com.br/api/sellers/:sellerId/orders' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer (access token)' \
--data '{
"order": {
"items": [
{
"description": "Produto 1",
"quantity": 2,
"unit_price_cents": 2290
}
],
"methods": ["BANK_SLIP", "PIX"]
}
}'
```
## Restringindo número máximo de parcelas
É possível parcelar os pagamentos no cartão de crédito em até 12x. Voce pode restringir o número máximo de parcelas para determinado pedido utilizando o campo **max_installments**. Essa restrição será aplicada em todas as nossas interfaces de checkout, seja por API, link de pagamento ou aplicativo. Confira o exemplo a seguir:
```bash
curl -X POST 'https://api-dev.genpag.com.br/api/sellers/:sellerId/orders' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer (access token)' \
--data '{
"order": {
"items": [
{
"description": "Produto 1",
"quantity": 2,
"unit_price_cents": 2290
}
],
"max_installments": 3 // Restringe o parcelamento em até 3x
}
}'
```
## Split de pagamentos para estabelecimentos parceiros
Ao criar uma nova fatura, você pode especificar uma lista de estabelecimentos parceiros para receber um valor fixo ou percentual da transação atual como pagamento de taxas ou comissões, por exemplo. Para isso basta enviar no campo **order_fees** uma lista de objetos contendo:
* **seller_id**: ID do estabelecimento parceiro
* **percent**: percentual da transação atual que ele ira raceber
* **amount_cents**: Valor fixo, em centavos que ele ira receber pela transação. Se for informado, esse valor se sobrepoe ao campo percent
* **method**: Metodo de pagamento à qual essa taxa se aplica. É ecessário inserir uma entrada para cada método de pagamento e estabelecimento parceiro;
Confira o exempo a seguir:
## Pŕoximos passos
Após gerar uma fatura, o próximo passo é registrar um ou mais pagamentos para completar o valor total da fatura. Vocẽ pode fazer isso usando nossa API ou nossas interfaces de checkout, você só vai precisar do ID da fatura gerada, veja os pŕoximos passos;
* Utilize nos link de checkout para receber rapidamente sem se preocupar em implementar sua propria interface de pagamento. Ver tutorial
* Aprenda a gerar boletos para faturas criadas;
* Aprenda a gerar PIX de cobrança
* Veja como realizar o pagamento de uma fatura utilizando cartão de crédito
* Cadasre webhooks para receber notificações de eventos da nossa API no seu sistema.
{% include links.html %} |
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Package\Archiver;
use Symfony\Component\Finder;
/**
* An exclude filter that processes hgignore files
*
* @author Nils Adermann <naderman@naderman.de>
*/
class HgExcludeFilter extends BaseExcludeFilter
{
const HG_IGNORE_REGEX = 1;
const HG_IGNORE_GLOB = 2;
/**
* Either HG_IGNORE_REGEX or HG_IGNORE_GLOB
* @var int
*/
protected $patternMode;
/**
* Parses .hgignore file if it exist
*
* @param string $sourcePath
*/
public function __construct($sourcePath)
{
parent::__construct($sourcePath);
$this->patternMode = self::HG_IGNORE_REGEX;
if (file_exists($sourcePath.'/.hgignore')) {
$this->excludePatterns = $this->parseLines(
file($sourcePath.'/.hgignore'),
array($this, 'parseHgIgnoreLine')
);
}
}
/**
* Callback line parser which process hgignore lines
*
* @param string $line A line from .hgignore
*
* @return array|null An exclude pattern for filter()
*/
public function parseHgIgnoreLine($line)
{
if (preg_match('#^syntax\s*:\s*(glob|regexp)$#', $line, $matches)) {
if ($matches[1] === 'glob') {
$this->patternMode = self::HG_IGNORE_GLOB;
} else {
$this->patternMode = self::HG_IGNORE_REGEX;
}
return null;
}
if ($this->patternMode == self::HG_IGNORE_GLOB) {
return $this->patternFromGlob($line);
}
return $this->patternFromRegex($line);
}
/**
* Generates an exclude pattern for filter() from a hg glob expression
*
* @param string $line A line from .hgignore in glob mode
*
* @return array An exclude pattern for filter()
*/
protected function patternFromGlob($line)
{
$pattern = '#'.substr(Finder\Glob::toRegex($line), 2, -1).'#';
$pattern = str_replace('[^/]*', '.*', $pattern);
return array($pattern, false, true);
}
/**
* Generates an exclude pattern for filter() from a hg regexp expression
*
* @param string $line A line from .hgignore in regexp mode
*
* @return array An exclude pattern for filter()
*/
public function patternFromRegex($line)
{
// WTF need to escape the delimiter safely
$pattern = '#'.preg_replace('/((?:\\\\\\\\)*)(\\\\?)#/', '\1\2\2\\#', $line).'#';
return array($pattern, false, true);
}
} |
<template>
<div class="container p-4 mx-auto min-h-screen">
<div v-if="manga != null" class="">
<div>
<img :src="imageProxy(manga.image)" alt="" class="rounded-2xl w-full">
</div>
<div class="text-white mt-3">
<h1 class="font-bold text-xl">
{{ checkNull(manga.title.english) ? manga.title.english : manga.title.romaji }}
</h1>
<div class="md:w-full mx-auto py-3 my-3 px-5 text-white bg-slate-800 rounded-xl" v-if="manga.genres">
<div class="font-bold">Genres:</div>
<div v-for="g in manga.genres" :key="g" class="inline-block mr-2 text-sm" :id="g"
:style="'color:' + randomColor(g)">
{{ g }}
</div>
</div>
<div v-if="manga.status">
<span>Status:</span><span class="ml-2">{{ manga.status }}</span>
</div>
<p class="max-h-56 overflow-y-auto mt-3 text-zinc-400 text-justify text-sm">
{{ manga.description.en ? manga.description.en : manga.description }}
</p>
</div>
<div class="text-white my-3">
<h1 class=" font-bold">Chapters:</h1>
<div class="grid grid-cols-3 gap-2 mt-2">
<!-- <NuxtLink v-for="chp in manga.chapters" :key="chp" :to="'/manga/' + manga.id + '/' + chp.id" -->
<NuxtLink v-for="chp in manga.chapters" :key="chp" :to="'/manga/' + $route.params.info + '/' + chp.id"
class=" bg-zinc-500 py-3 px-4 rounded-md text-sm">
{{ chp.title ? chp.title : "No Title" }}
</NuxtLink>
</div>
</div>
</div>
<div v-else class="w-full flex justify-center mt-5">
<SpiningLoading></SpiningLoading>
</div>
</div>
</template>
<script>
export default {
data() {
return {
manga: null,
id: null,
loading: true,
}
},
mounted() {
this.id = this.$route.params.info
this.getMangaInfo(this.id)
},
methods: {
async getMangaInfo(id) {
const config = useRuntimeConfig();
const mangaApi = config['public'].mangaApi
await fetch(`${mangaApi}info/${id}?provider=mangadex`)
.then(res => res.json())
.then(data => {
// console.log(data)
this.manga = data
this.loading = false
}).catch(err => {
console.log(err)
})
},
randomColor() {
var letters = 'BCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * letters.length)];
}
return color;
// return '#' + Math.floor(Math.random() * 16777215).toString(16);
},
},
}
</script>
<style></style> |
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Booki</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w=="
crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" />
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<div class="main-container">
<header>
<a href="#"><img class="logo" src="./images/logo/Booki.png" alt="Logo Booki"></a>
<nav>
<a class=liens href="#hebergements">Hébergement</a>
<a class=liens href="#activities">Activités</a>
</nav>
</header>
<main class="main-container">
<section>
<h2 >Trouvez votre hébergement pour des vacances de rêve</h2>
<p>En plein centre ville ou en pleine nature.</p>
<div class="info">
<article class="search-bar">
<div class="location"> <i class="fa-sharp fa-solid fa-location-dot fa-black"></i></div>
<form action="/form/submit" method="GET">
<input type="text" name="text" class="search" value="Marseille, France">
<button type="submit" class="submit"><i class="a-sharp fa-white fa-solid fa-magnifying-glass"></i><span>Rechercher</span></button>
</form>
</article>
<article class="filtre">
<h2>Filtres</h2>
<div class="filtre-buttons">
<button type="button"> <i class="fa-solid fa-money-bill-wave"></i> Économique</button>
<button type="button"> <i class="fa-solid fa-person"></i> Familial</button>
<button type="button"> <i class="fa-solid fa-heart"></i> Romantique</button>
<button type="button"> <i class="fa-solid fa-fire"></i> Nos pépites</button>
</div>
</article>
<article class="info-bubble">
<i class="fa-solid fa-xs fa-info fa-border"></i>
<p> Plus de 500 logements sont disponibles dans cette ville.</p>
</article>
</div>
</section>
<div class="hebergements-and-populaires">
<section class="hebergements">
<h2 class="section-title" id=hebergements>Hébergement à Marseille</h2>
<div class="hebergements-cards">
<article class="card">
<a class="card-link" href="#">
<img src="./images/hebergements/fred-kleber.jpg" alt="Image de la chambre d'hôtel montrant un lit">
<div class="card-content">
<div class="card-txt">
<h3 class="card-title">Hôtel du port</h3>
<p class="card-subtitle">Nuit à partir de 52<span class="euro">€</span></p>
</div>
<div class="card-rating">
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star neutral-star" aria-hidden="true"></i>
<span class="sr-only">Note de 4 sur 5</span>
</div>
</div>
</a>
</article>
<article class="card">
<a class="card-link" href="#">
<img src="./images/hebergements/febrian-zakaria.jpg" alt="Image de la chambre d'hôtel montrant un lit">
<div class="card-content">
<div class="card-txt">
<h3 class="card-title">Hôtel Chez Amina</h3>
<p class="card-subtitle">Nuit à partir de 96<span class="euro">€</span></p>
</div>
<div class="card-rating">
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star neutral-star" aria-hidden="true"></i>
<span class="sr-only">Note de 4 sur 5</span>
</div>
</div>
</a>
</article>
<article class="card">
<a class="card-link" href="#">
<img src="./images/hebergements/reisetopia.jpg" alt="Image de la chambre d'hôtel montrant un lit">
<div class="card-content">
<div class="card-txt">
<h3 class="card-title">Hôtel Les mouettes</h3>
<p class="card-subtitle">Nuit à partir de 76<span class="euro">€</span></p>
</div>
<div class="card-rating">
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star neutral-star" aria-hidden="true"></i>
<span class="sr-only">Note de 4 sur 5</span>
</div>
</div>
</a>
</article>
<article class="card">
<a class="card-link" href="#">
<img src="./images/hebergements/annie-spratt.jpg" alt="Image de la chambre d'hôtel montrant un lit">
<div class="card-content">
<div class="card-txt">
<h3 class="card-title">Hôtel de la mer</h3>
<p class="card-subtitle">Nuit à partir de 46<span class="euro">€</span></p>
</div>
<div class="card-rating">
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star neutral-star" aria-hidden="true"></i>
<span class="sr-only">Note de 4 sur 5</span>
</div>
</div>
</a>
</article>
<article class="card">
<a class="card-link" href="#">
<img src="./images/hebergements/marcus-loke.jpg" alt="Image de la chambre d'hôtel montrant un lit">
<div class="card-content">
<div class="card-txt">
<h3 class="card-title">Auberge La Canebère</h3>
<p class="card-subtitle">Nuit à partir de 25<span class="euro">€</span></p>
</div>
<div class="card-rating">
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star neutral-star" aria-hidden="true"></i>
<span class="sr-only">Note de 4 sur 5</span>
</div>
</div>
</a>
</article>
<article class="card">
<a class="card-link" href="#">
<img src="./images/hebergements/nicate-lee.jpg" alt="Image de la chambre d'hôtel montrant un lit">
<div class="card-content">
<div class="card-txt">
<h3 class="card-title">Auberge Le Panier</h3>
<p class="card-subtitle">Nuit à partir de 23<span class="euro">€</span></p>
</div>
<div class="card-rating">
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star neutral-star" aria-hidden="true"></i>
<span class="sr-only">Note de 4 sur 5</span>
</div>
</div>
</a>
</article>
</div>
<a class="hebergements-footer" href=#> Afficher plus</a>
</section>
<section class="populaires">
<div class="populaires-title">
<h2 class="section-title">Les plus populaires</h2>
<i class="fa-solid fa-chart-line" aria-hidden="true"></i>
</div>
<div class="populaires-cards">
<<<<<<< HEAD
<article class="card">
<a class="card-link-populaires" href="#">
<img src="./images/hebergements/emile-guillemot.jpg" alt="Image de la chambre d'hôtel montrant un lit">
<div class="card-content">
<div class="card-txt">
<h3 class="card-title">Hôtel Le soleil du matin</h3>
<p class="card-subtitle">Nuit à partir de 128<span class="euro">€</span></p>
=======
<a href="#">
<article class="card">
<img src="./images/hebergements/emile-guillemot.jpg" alt="Image de la chambre d'hôtel montrant un lit">
<div class="card-content">
<div class="card-txt">
<h3 class="card-title">Hôtel Le soleil du matin</h3>
<p class="card-subtitle">Nuit à partir de 128<span class="euro">€</span></p>
</div>
<div class="card-rating">
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star neutral-star" aria-hidden="true"></i>
<span class="sr-only">Note de 4 sur 5</span>
</div>
>>>>>>> dc05a6d7070cf8fa521bbc7cbd919d977a82a350
</div>
</article>
</a>
<a href="#">
<article class="card">
<img src="./images/hebergements/aw-creative.jpg" alt="Image de la chambre d'hôtel montrant un lit">
<div class="card-content">
<div class="card-txt">
<h3 class="card-title">Chambres d’hôtes Au cœur de l’eau</h3>
<p class="card-subtitle">Nuit à partir de 71<span class="euro">€</span></p>
</div>
<div class="card-rating">
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star neutral-star" aria-hidden="true"></i>
<span class="sr-only">Note de 4 sur 5</span>
</div>
</div>
<<<<<<< HEAD
</div>
</a>
</article>
<article class="card">
<a class="card-link-populaires" href="#">
<img src="./images/hebergements/aw-creative.jpg" alt="Image de la chambre d'hôtel montrant un lit">
<div class="card-content">
<div class="card-txt">
<h3 class="card-title">Chambres d’hôtes Au cœur de l’eau</h3>
<p class="card-subtitle">Nuit à partir de 71<span class="euro">€</span></p>
</div>
<div class="card-rating">
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star neutral-star" aria-hidden="true"></i>
<span class="sr-only">Note de 4 sur 5</span>
</div>
</div>
</a>
</article>
<article class="card">
<a class="card-link-populaires" href="#">
<img src="./images/hebergements/febrian-zakaria2.jpg" alt="Image de la chambre d'hôtel montrant un lit">
<div class="card-content">
<div class="card-txt">
<h3 class="card-title">Hôtel Bleu et Blanc</h3>
<p class="card-subtitle">Nuit à partir de 68<span class="euro">€</span></p>
</div>
<div class="card-rating">
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star neutral-star" aria-hidden="true"></i>
<span class="sr-only">Note de 4 sur 5</span>
</div>
</div>
</a>
</article>
=======
</article>
</a>
<a href="#">
<article class="card">
<img src="./images/hebergements/febrian-zakaria2.jpg" alt="Image de la chambre d'hôtel montrant un lit">
<div class="card-content">
<div class="card-txt">
<h3 class="card-title">Hôtel Bleu et Blanc</h3>
<p class="card-subtitle">Nuit à partir de 68<span class="euro">€</span></p>
</div>
<div class="card-rating">
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star" aria-hidden="true"></i>
<i class="fa-xs fa-solid fa-star neutral-star" aria-hidden="true"></i>
<span class="sr-only">Note de 4 sur 5</span>
</div>
</div>
</article>
</a>
>>>>>>> dc05a6d7070cf8fa521bbc7cbd919d977a82a350
</div>
</section>
</div>
<div class="activities">
<h1 class="section-title" id="activities"> Activités à Marseille</h1>
<section class="activities-cards">
<a class="card-link-activities" href="#">
<article class="card">
<img src=./images/activites/reno-laithienne.jpg alt="photo du vieux port de Marseille">
<span class="card-content">Vieux-Port</span>
</article>
</a>
<a class="card-link-activities" href="#">
<article class="card">
<img src=./images/activites/paul-hermann.jpg alt="photo du fort de Pomègues">
<span class="card-content">Fort de Pomègues</span>
</article>
</a>
<a class="card-link-activities" href="#">
<article class="card">
<img src=./images/activites/kilyan-sockalingum.jpg alt="photo du parc national des calanques">
<span class="card-content">Parc national des Calanques</span>
</article>
</a>
<a class="card-link-activities" href="#">
<article class="card">
<img src=./images/activites/florian-wehde.jpg alt="photo de l'église Notre dame de la garde">
<span class="card-content">Notre-Dame-de-la-Garde</span>
</article>
</a>
</section>
</div>
</main>
<footer class="main-container">
<section>
<h2>À propos</h2>
<ul class="no-style">
<li><a href="#">Fonctionement du site</a></li>
<li><a href="#">Conditions générales</a></li>
<li><a href="#">Données et confidentialité</a></li>
</ul>
</section>
<section>
<h2>Nos hébergements</h2>
<ul class="no-style">
<li><a href="#">Charte de qualité</a></li>
<li><a href="#">Proposer votre hotêl</a></li>
</ul>
</section>
<section>
<h2>Assistance</h2>
<ul class="no-style">
<li><a href="#">Centre d'aide</a></li>
<li><a href="#">Nous contacter</a></li>
</ul>
</section>
</footer>
</div>
</body>
</html> |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "mysqlc_table.hxx"
#include "mysqlc_tables.hxx"
#include "mysqlc_catalog.hxx"
#include <TConnection.hxx>
#include <connectivity/dbtools.hxx>
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/sdbc/ColumnValue.hpp>
#include <comphelper/types.hxx>
//----- OCollection -----------------------------------------------------------
void connectivity::mysqlc::Tables::impl_refresh()
{
static_cast<Catalog&>(m_rParent).refreshTables();
}
static void lcl_unescape(OUString& rName)
{
// Remove ending ` if there's one
sal_Int32 nLastIndexBacktick = rName.lastIndexOf("`");
if ((nLastIndexBacktick > 0) && (nLastIndexBacktick == (rName.getLength() - 1)))
{
rName = rName.copy(0, nLastIndexBacktick);
}
// Remove beginning `
nLastIndexBacktick = rName.indexOf("`");
if (nLastIndexBacktick == 0)
{
rName = rName.copy(1, rName.getLength() - 1);
}
// Replace double ` by simple `
rName = rName.replaceAll("``", "`");
}
connectivity::sdbcx::ObjectType connectivity::mysqlc::Tables::createObject(const OUString& rName)
{
OUString sCatalog, sSchema, sTable;
::dbtools::qualifiedNameComponents(m_xMetaData, rName, sCatalog, sSchema, sTable,
::dbtools::EComposeRule::InDataManipulation);
css::uno::Any aCatalog;
if (!sCatalog.isEmpty())
{
lcl_unescape(sCatalog);
aCatalog <<= sCatalog;
}
lcl_unescape(sSchema);
lcl_unescape(sTable);
// Only retrieving a single table, so table type is irrelevant (param 4)
css::uno::Reference<css::sdbc::XResultSet> xTables
= m_xMetaData->getTables(aCatalog, sSchema, sTable, css::uno::Sequence<OUString>());
if (!xTables.is())
throw css::uno::RuntimeException("Could not acquire table.");
css::uno::Reference<css::sdbc::XRow> xRow(xTables, css::uno::UNO_QUERY_THROW);
if (!xTables->next())
throw css::uno::RuntimeException();
connectivity::sdbcx::ObjectType xRet(
new Table(this, m_rMutex, m_xMetaData->getConnection(),
xRow->getString(1), // Catalog
xRow->getString(2), // Schema
xRow->getString(3), // Name
xRow->getString(4), // Type
xRow->getString(5))); // Description / Remarks / Comments
if (xTables->next())
throw css::uno::RuntimeException("Found more tables than expected.");
return xRet;
}
css::uno::Reference<css::beans::XPropertySet> connectivity::mysqlc::Tables::createDescriptor()
{
// There is some internal magic so that the same class can be used as either
// a descriptor or as a normal table. See VTable.cxx for the details. In our
// case we just need to ensure we use the correct constructor.
return new Table(this, m_rMutex, m_xMetaData->getConnection());
}
//----- XAppend ---------------------------------------------------------------
void connectivity::mysqlc::Tables::createTable(
const css::uno::Reference<css::beans::XPropertySet>& descriptor)
{
const css::uno::Reference<css::sdbc::XConnection> xConnection = m_xMetaData->getConnection();
OUString aSql = ::dbtools::createSqlCreateTableStatement(descriptor, xConnection);
css::uno::Reference<css::sdbc::XStatement> xStmt = xConnection->createStatement();
if (xStmt.is())
{
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
// XAppend
connectivity::sdbcx::ObjectType connectivity::mysqlc::Tables::appendObject(
const OUString& _rForName, const css::uno::Reference<css::beans::XPropertySet>& descriptor)
{
createTable(descriptor);
return createObject(_rForName);
}
void connectivity::mysqlc::Tables::appendNew(const OUString& _rsNewTable)
{
insertElement(_rsNewTable, nullptr);
// notify our container listeners
css::container::ContainerEvent aEvent(static_cast<XContainer*>(this),
css::uno::Any(_rsNewTable), css::uno::Any(),
css::uno::Any());
comphelper::OInterfaceIteratorHelper3 aListenerLoop(m_aContainerListeners);
while (aListenerLoop.hasMoreElements())
aListenerLoop.next()->elementInserted(aEvent);
}
OUString
connectivity::mysqlc::Tables::getNameForObject(const connectivity::sdbcx::ObjectType& _xObject)
{
OSL_ENSURE(_xObject.is(), "OTables::getNameForObject: Object is NULL!");
return ::dbtools::composeTableName(m_xMetaData, _xObject,
::dbtools::EComposeRule::InDataManipulation, false)
.replaceAll(u"`", u"̀ `");
}
//----- XDrop -----------------------------------------------------------------
void connectivity::mysqlc::Tables::dropObject(sal_Int32 nPosition, const OUString& sName)
{
css::uno::Reference<css::beans::XPropertySet> xTable(getObject(nPosition));
if (connectivity::sdbcx::ODescriptor::isNew(xTable))
return;
OUString sType;
xTable->getPropertyValue("Type") >>= sType;
m_xMetaData->getConnection()->createStatement()->execute("DROP " + sType + " " + sName);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ |
use crate::prelude::*;
#[system]
#[read_component(Point)]
#[read_component(Player)]
#[read_component(Enemy)]
#[write_component(Health)]
#[read_component(Item)]
#[read_component(Carried)]
pub fn player_input(
ecs: &mut SubWorld,
commands: &mut CommandBuffer,
#[resource] key: &Option<VirtualKeyCode>,
#[resource] turn_state: &mut TurnState,
) {
let mut players = <(Entity, &Point)>::query()
.filter(component::<Player>());
if let Some(key) = *key {
let delta = match key {
VirtualKeyCode::Left => Point::new(-1, 0),
VirtualKeyCode::Right => Point::new(1, 0),
VirtualKeyCode::Up => Point::new(0, -1),
VirtualKeyCode::Down => Point::new(0, 1),
VirtualKeyCode::G => {
let (player, player_pos) = players.iter(ecs)
.find_map(|(entity, pos)| Some((*entity, *pos)))
.unwrap();
let mut items = <(Entity, &Item, &Point)>::query();
items.iter(ecs)
.filter(|(_entity, _item, &item_pos)| item_pos == player_pos)
.for_each(|(entity, _item, _item_pos)| {
commands.remove_component::<Point>(*entity);
commands.add_component(*entity, Carried(player));
});
Point::new(0, 0)
}
VirtualKeyCode::Key1 => use_item(0, ecs, commands),
VirtualKeyCode::Key2 => use_item(1, ecs, commands),
VirtualKeyCode::Key3 => use_item(2, ecs, commands),
VirtualKeyCode::Key4 => use_item(3, ecs, commands),
VirtualKeyCode::Key5 => use_item(4, ecs, commands),
VirtualKeyCode::Key6 => use_item(5, ecs, commands),
VirtualKeyCode::Key7 => use_item(6, ecs, commands),
VirtualKeyCode::Key8 => use_item(7, ecs, commands),
VirtualKeyCode::Key9 => use_item(8, ecs, commands),
_ => Point::new(0, 0), // ::zero()
};
let (player_entity, destination) = players.iter(ecs)
.find_map(|(entity, pos)| Some((*entity, *pos + delta)))
.unwrap();
let mut enemies = <(Entity, &Point)>::query().filter(component::<Enemy>());
if delta.x != 0 || delta.y != 0 {
let mut hit_something = false;
enemies.iter(ecs)
.filter(|(_, pos)| { **pos == destination })
.for_each(|(entity, _)| {
hit_something = true;
commands
.push(((), WantsToAttack {
attacker: player_entity,
victim: *entity,
}));
});
if !hit_something {
commands
.push(((), WantsToMove {
entity: player_entity,
destination,
}));
}
};
*turn_state = TurnState::PlayerTurn;
}
}
fn use_item(n: usize, ecs: &mut SubWorld, commands: &mut CommandBuffer) -> Point {
let player_entity = <(Entity, &Player)>::query()
.iter(ecs)
.find_map(|(entity, _player)| Some(*entity))
.unwrap();
let item_entity = <(Entity, &Item, &Carried)>::query()
.iter(ecs)
.filter(|(_, _, carried)| carried.0 == player_entity)
.enumerate()
.filter(|(item_count, (_, _, _))| *item_count == n)
.find_map(|(_, (item_entity, _, _))| Some(*item_entity));
if let Some(item_entity) = item_entity {
commands
.push(((), ActivateItem {
used_by: player_entity,
item: item_entity,
}));
}
Point::zero()
} |
package ru.job4j.collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
public class SimpleLinkedList<E> implements LinkedList<E> {
private int size = 0;
private Node<E> first;
private Node<E> last;
private int modCount;
@Override
public void add(E value) {
Node<E> l = last;
Node<E> newNode = new Node<>(value, null);
last = newNode;
if (l == null) {
first = newNode;
} else {
l.next = newNode;
}
size++;
modCount++;
}
@Override
public E get(int index) {
Objects.checkIndex(index, size);
Node<E> node = first;
for (int i = 0; i < index; i++) {
node = node.next;
}
return node.value;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
int expectedModCount = modCount;
Node<E> currentNode = first;
@Override
public boolean hasNext() {
if (expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
return currentNode != null;
}
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Node<E> result = currentNode;
currentNode = currentNode.next;
return result.value;
}
};
}
private static class Node<E> {
private final E value;
private Node<E> next;
public Node(E value, Node<E> next) {
this.value = value;
this.next = next;
}
}
} |
<?php
/**
* @author Sujith Haridasan <sharidasan@owncloud.com>
* @author Ilja Neumann <ineumann@owncloud.com>
*
* @copyright Copyright (c) 2019, ownCloud GmbH
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Encryption\Command;
use OC\Files\Storage\Wrapper\Encryption;
use OC\Files\View;
use OC\ServerNotAvailableException;
use OCA\Encryption\Util;
use OCP\Files\IRootFolder;
use OCP\HintException;
use OCP\IConfig;
use OCP\IUser;
use OCP\IUserManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class FixEncryptedVersion extends Command {
private bool $supportLegacy;
public function __construct(
private IConfig $config,
private LoggerInterface $logger,
private IRootFolder $rootFolder,
private IUserManager $userManager,
private Util $util,
private View $view,
) {
$this->supportLegacy = false;
parent::__construct();
}
protected function configure(): void {
parent::configure();
$this
->setName('encryption:fix-encrypted-version')
->setDescription('Fix the encrypted version if the encrypted file(s) are not downloadable.')
->addArgument(
'user',
InputArgument::OPTIONAL,
'The id of the user whose files need fixing'
)->addOption(
'path',
'p',
InputOption::VALUE_REQUIRED,
'Limit files to fix with path, e.g., --path="/Music/Artist". If path indicates a directory, all the files inside directory will be fixed.'
)->addOption(
'all',
null,
InputOption::VALUE_NONE,
'Run the fix for all users on the system, mutually exclusive with specifying a user id.'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$skipSignatureCheck = $this->config->getSystemValueBool('encryption_skip_signature_check', false);
$this->supportLegacy = $this->config->getSystemValueBool('encryption.legacy_format_support', false);
if ($skipSignatureCheck) {
$output->writeln("<error>Repairing is not possible when \"encryption_skip_signature_check\" is set. Please disable this flag in the configuration.</error>\n");
return 1;
}
if (!$this->util->isMasterKeyEnabled()) {
$output->writeln("<error>Repairing only works with master key encryption.</error>\n");
return 1;
}
$user = $input->getArgument('user');
$all = $input->getOption('all');
$pathOption = \trim(($input->getOption('path') ?? ''), '/');
if ($user) {
if ($all) {
$output->writeln("Specifying a user id and --all are mutually exclusive");
return 1;
}
if ($this->userManager->get($user) === null) {
$output->writeln("<error>User id $user does not exist. Please provide a valid user id</error>");
return 1;
}
return $this->runForUser($user, $pathOption, $output);
} elseif ($all) {
$result = 0;
$this->userManager->callForSeenUsers(function (IUser $user) use ($pathOption, $output, &$result) {
$output->writeln("Processing files for " . $user->getUID());
$result = $this->runForUser($user->getUID(), $pathOption, $output);
return $result === 0;
});
return $result;
} else {
$output->writeln("Either a user id or --all needs to be provided");
return 1;
}
}
private function runForUser(string $user, string $pathOption, OutputInterface $output): int {
$pathToWalk = "/$user/files";
if ($pathOption !== "") {
$pathToWalk = "$pathToWalk/$pathOption";
}
return $this->walkPathOfUser($user, $pathToWalk, $output);
}
/**
* @return int 0 for success, 1 for error
*/
private function walkPathOfUser(string $user, string $path, OutputInterface $output): int {
$this->setupUserFs($user);
if (!$this->view->file_exists($path)) {
$output->writeln("<error>Path \"$path\" does not exist. Please provide a valid path.</error>");
return 1;
}
if ($this->view->is_file($path)) {
$output->writeln("Verifying the content of file \"$path\"");
$this->verifyFileContent($path, $output);
return 0;
}
$directories = [];
$directories[] = $path;
while ($root = \array_pop($directories)) {
$directoryContent = $this->view->getDirectoryContent($root);
foreach ($directoryContent as $file) {
$path = $root . '/' . $file['name'];
if ($this->view->is_dir($path)) {
$directories[] = $path;
} else {
$output->writeln("Verifying the content of file \"$path\"");
$this->verifyFileContent($path, $output);
}
}
}
return 0;
}
/**
* @param bool $ignoreCorrectEncVersionCall, setting this variable to false avoids recursion
*/
private function verifyFileContent(string $path, OutputInterface $output, bool $ignoreCorrectEncVersionCall = true): bool {
try {
// since we're manually poking around the encrypted state we need to ensure that this isn't cached in the encryption wrapper
$mount = $this->view->getMount($path);
$storage = $mount->getStorage();
if ($storage && $storage->instanceOfStorage(Encryption::class)) {
$storage->clearIsEncryptedCache();
}
/**
* In encryption, the files are read in a block size of 8192 bytes
* Read block size of 8192 and a bit more (808 bytes)
* If there is any problem, the first block should throw the signature
* mismatch error. Which as of now, is enough to proceed ahead to
* correct the encrypted version.
*/
$handle = $this->view->fopen($path, 'rb');
if ($handle === false) {
$output->writeln("<warning>Failed to open file: \"$path\" skipping</warning>");
return true;
}
if (\fread($handle, 9001) !== false) {
$fileInfo = $this->view->getFileInfo($path);
if (!$fileInfo) {
$output->writeln("<warning>File info not found for file: \"$path\"</warning>");
return true;
}
$encryptedVersion = $fileInfo->getEncryptedVersion();
$stat = $this->view->stat($path);
if (($encryptedVersion == 0) && isset($stat['hasHeader']) && ($stat['hasHeader'] == true)) {
// The file has encrypted to false but has an encryption header
if ($ignoreCorrectEncVersionCall === true) {
// Lets rectify the file by correcting encrypted version
$output->writeln("<info>Attempting to fix the path: \"$path\"</info>");
return $this->correctEncryptedVersion($path, $output);
}
return false;
}
$output->writeln("<info>The file \"$path\" is: OK</info>");
}
\fclose($handle);
return true;
} catch (ServerNotAvailableException $e) {
// not a "bad signature" error and likely "legacy cipher" exception
// this could mean that the file is maybe not encrypted but the encrypted version is set
if (!$this->supportLegacy && $ignoreCorrectEncVersionCall === true) {
$output->writeln("<info>Attempting to fix the path: \"$path\"</info>");
return $this->correctEncryptedVersion($path, $output, true);
}
return false;
} catch (HintException $e) {
$this->logger->warning("Issue: " . $e->getMessage());
// If allowOnce is set to false, this becomes recursive.
if ($ignoreCorrectEncVersionCall === true) {
// Lets rectify the file by correcting encrypted version
$output->writeln("<info>Attempting to fix the path: \"$path\"</info>");
return $this->correctEncryptedVersion($path, $output);
}
return false;
}
}
/**
* @param bool $includeZero whether to try zero version for unencrypted file
*/
private function correctEncryptedVersion(string $path, OutputInterface $output, bool $includeZero = false): bool {
$fileInfo = $this->view->getFileInfo($path);
if (!$fileInfo) {
$output->writeln("<warning>File info not found for file: \"$path\"</warning>");
return true;
}
$fileId = $fileInfo->getId();
if ($fileId === null) {
$output->writeln("<warning>File info contains no id for file: \"$path\"</warning>");
return true;
}
$encryptedVersion = $fileInfo->getEncryptedVersion();
$wrongEncryptedVersion = $encryptedVersion;
$storage = $fileInfo->getStorage();
$cache = $storage->getCache();
$fileCache = $cache->get($fileId);
if (!$fileCache) {
$output->writeln("<warning>File cache entry not found for file: \"$path\"</warning>");
return true;
}
if ($storage->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) {
$output->writeln("<info>The file: \"$path\" is a share. Please also run the script for the owner of the share</info>");
return true;
}
// Save original encrypted version so we can restore it if decryption fails with all version
$originalEncryptedVersion = $encryptedVersion;
if ($encryptedVersion >= 0) {
if ($includeZero) {
// try with zero first
$cacheInfo = ['encryptedVersion' => 0, 'encrypted' => 0];
$cache->put($fileCache->getPath(), $cacheInfo);
$output->writeln("<info>Set the encrypted version to 0 (unencrypted)</info>");
if ($this->verifyFileContent($path, $output, false) === true) {
$output->writeln("<info>Fixed the file: \"$path\" with version 0 (unencrypted)</info>");
return true;
}
}
// Test by decrementing the value till 1 and if nothing works try incrementing
$encryptedVersion--;
while ($encryptedVersion > 0) {
$cacheInfo = ['encryptedVersion' => $encryptedVersion, 'encrypted' => $encryptedVersion];
$cache->put($fileCache->getPath(), $cacheInfo);
$output->writeln("<info>Decrement the encrypted version to $encryptedVersion</info>");
if ($this->verifyFileContent($path, $output, false) === true) {
$output->writeln("<info>Fixed the file: \"$path\" with version " . $encryptedVersion . "</info>");
return true;
}
$encryptedVersion--;
}
// So decrementing did not work. Now lets increment. Max increment is till 5
$increment = 1;
while ($increment <= 5) {
/**
* The wrongEncryptedVersion would not be incremented so nothing to worry about here.
* Only the newEncryptedVersion is incremented.
* For example if the wrong encrypted version is 4 then
* cycle1 -> newEncryptedVersion = 5 ( 4 + 1)
* cycle2 -> newEncryptedVersion = 6 ( 4 + 2)
* cycle3 -> newEncryptedVersion = 7 ( 4 + 3)
*/
$newEncryptedVersion = $wrongEncryptedVersion + $increment;
$cacheInfo = ['encryptedVersion' => $newEncryptedVersion, 'encrypted' => $newEncryptedVersion];
$cache->put($fileCache->getPath(), $cacheInfo);
$output->writeln("<info>Increment the encrypted version to $newEncryptedVersion</info>");
if ($this->verifyFileContent($path, $output, false) === true) {
$output->writeln("<info>Fixed the file: \"$path\" with version " . $newEncryptedVersion . "</info>");
return true;
}
$increment++;
}
}
$cacheInfo = ['encryptedVersion' => $originalEncryptedVersion, 'encrypted' => $originalEncryptedVersion];
$cache->put($fileCache->getPath(), $cacheInfo);
$output->writeln("<info>No fix found for \"$path\", restored version to original: $originalEncryptedVersion</info>");
return false;
}
/**
* Setup user file system
*/
private function setupUserFs(string $uid): void {
\OC_Util::tearDownFS();
\OC_Util::setupFS($uid);
}
} |
import 'package:json_annotation/json_annotation.dart';
import 'package:shikimoriapp/feature/profile/data/dto/creditional_image_dto.dart';
part 'creditional_dto.g.dart';
///Credential data transfer object
@JsonSerializable(fieldRename: FieldRename.snake)
class CreditionalDTO {
///Constructor
const CreditionalDTO({
required this.id,
required this.nickname,
required this.avatar,
required this.image,
required this.lastOnlineAt,
required this.url,
required this.sex,
required this.website,
required this.fullYears,
required this.locale,
this.name,
this.birthOn,
});
factory CreditionalDTO.fromJson(Map<String, dynamic> json) =>
_$CreditionalDTOFromJson(json);
///User id
final int id;
///User nickname
final String nickname;
///User avatar
final String avatar;
///User image
final CreditionalImageDTO image;
///User last online at
final DateTime lastOnlineAt;
///User url
final String url;
///User name
final dynamic name;
///User sex
final String sex;
///User website
final String website;
///User birth on
final dynamic birthOn;
///User full years
final int fullYears;
///User locale
final String locale;
} |
'use client';
import NProgress from 'nprogress';
import { useEffect } from 'react';
import { usePathname } from '@/i18n';
import { useGlobalStore } from '@/stores/global';
import { useSearchParams } from 'next/navigation';
import 'nprogress/nprogress.css';
const RouteHandlerProvider = ({ children }: { children: React.ReactNode }) => {
const pathname = usePathname();
const search = useSearchParams();
const { setLastRoute } = useGlobalStore();
useEffect(() => {
return () => {
setLastRoute(pathname);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pathname]);
useEffect(() => {
const handleRouteChangeStart = () => NProgress.start();
const handleRouteChangeComplete = () => NProgress.done();
const handleRouteChangeError = () => NProgress.done();
document.addEventListener('routeChangeStart', handleRouteChangeStart);
document.addEventListener('routeChangeComplete', handleRouteChangeComplete);
document.addEventListener('routeChangeError', handleRouteChangeError);
return () => {
document.removeEventListener('routeChangeStart', handleRouteChangeStart);
document.removeEventListener('routeChangeComplete', handleRouteChangeComplete);
document.removeEventListener('routeChangeError', handleRouteChangeError);
};
}, []);
return <div>{children}</div>;
};
export default RouteHandlerProvider; |
import { createStyles, makeStyles, Theme } from "@material-ui/core/styles";
import { useEffect, useState } from "react";
import TextField from "@material-ui/core/TextField";
import {
FormControlLabel,
FormGroup,
FormControl,
FormLabel,
Switch,
Button,
Box,
CircularProgress,
} from "@material-ui/core";
import { apiCall } from "../../../utils/apiCall";
import { mutate } from "swr";
import { RootReducer } from "../../../store/reducers";
import { useSelector } from "react-redux";
import { ICategory } from "../../../types/category";
// components
import Modal from "../modal";
import Error from "../error";
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
"& > *": {},
},
grid: {
flexGrow: 1,
},
formControl: {
margin: theme.spacing(3),
},
})
);
interface IProps {
close: Function;
category?: ICategory;
categoryLength: number;
}
interface IState {
category_name: string;
is_hidden: boolean;
category_order: string;
}
interface IError {
category_name: string[];
is_hidden: string[];
category_order: string[];
}
const CategoryForm = ({ close, category, categoryLength }: IProps) => {
const classes = useStyles();
const [loading, setLoading] = useState<boolean>(false);
const user = useSelector((state: RootReducer) => state.auth.user);
const [errors, setErrors] = useState<IError>({
category_name: [],
is_hidden: [],
category_order: [],
});
const [state, setState] = useState<IState>({
category_name: "",
category_order: `${categoryLength}`,
is_hidden: false,
});
useEffect(() => {
if (category) {
setState({
...state,
category_name: category.category_name || "",
category_order: category.category_order || "",
is_hidden: category.is_hidden || false,
});
}
}, []);
const handleSwitch = (e: React.ChangeEvent<HTMLInputElement>) => {
setState({ ...state, [e.target.name]: e.target.checked });
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setState({ ...state, [e.target.name]: e.target.value });
};
const handleChangeNumber = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
if (!Number.isNaN(Number(value))) {
setState({
...state,
[e.target.name]: value.trim().split(".", 1)[0],
});
}
};
const handleSubmit = async (e) => {
e.preventDefault();
if (!loading) {
const errors = handleValidate();
for (let e of Object.values(errors)) {
if (e.length) return;
}
try {
setLoading(true);
if (!category) {
const category = await apiCall(
"post",
`/category?authId=${user.user_id}`,
state
);
mutate(
"/categories",
(categories) => {
return [
...categories.map((c) =>
c.category_order ===
Number(state.category_order)
? {
...c,
category_order:
categories.length + 1,
}
: c
),
category,
];
},
false
);
} else {
const editedCategory = await apiCall(
"put",
`/category/${category.category_id}?authId=${user.user_id}`,
state
);
mutate(
"/categories",
(categories) => {
const toEditCatg = categories.find(
(c) =>
Number(c.category_order) ===
Number(state.category_order)
);
if (toEditCatg)
toEditCatg.category_order =
category.category_order;
const foundCatg = categories.find(
(c) => c.category_id === category.category_id
);
if (foundCatg)
foundCatg.category_order = state.category_order;
return categories.map((c) =>
c.category_id === toEditCatg?.category_id
? toEditCatg
: c.category_id === category.category_id
? foundCatg
: c
);
},
false
);
}
close();
} catch (err) {
setLoading(false);
setErrors({ ...errors, ...err });
}
}
};
const handleValidate = () => {
const TmpErrors: IError = {
category_name: [],
is_hidden: [],
category_order: [],
};
if (!state.category_name.trim()) {
TmpErrors.category_name.push("Please fill in category name.");
}
if (!state.category_order) {
TmpErrors.category_order.push("Please fill in category order.");
}
setErrors({ ...errors, ...TmpErrors });
return TmpErrors;
};
return (
<>
<Modal
type="parent"
width={50}
closeInfo={{
close,
check: true,
}}
>
<form
onSubmit={handleSubmit}
className={classes.root}
noValidate
autoComplete="off"
>
<div>
<FormControl
component="fieldset"
className={classes.formControl}
>
<FormLabel component="legend">
Category Settings
</FormLabel>
<FormGroup>
<FormControlLabel
control={
<Switch
checked={state.is_hidden}
onChange={handleSwitch}
name="is_hidden"
/>
}
label="Hidden"
/>
</FormGroup>
</FormControl>
<Box mb={3}>
<TextField
id="category_name"
name="category_name"
label="Name"
size="small"
required={true}
value={state.category_name}
error={!!errors.category_name?.length}
variant="outlined"
onChange={handleChange}
style={{ width: "100%" }}
/>
<Error errors={errors.category_name} />
</Box>
<Box mb={3}>
<TextField
id="category_order"
name="category_order"
label="Order"
size="small"
required={true}
value={state.category_order}
error={!!errors.category_order?.length}
variant="outlined"
onChange={handleChangeNumber}
style={{ width: "100%" }}
/>
<Error errors={errors.category_order} />
</Box>
<Box
display="flex"
flexDirection="column"
style={{ marginTop: "20px" }}
>
<Button
color="secondary"
type="submit"
variant="contained"
>
{loading ? (
<CircularProgress
style={{ color: "white" }}
/>
) : (
"Submit"
)}
</Button>
</Box>
</div>
</form>
</Modal>
</>
);
};
export default CategoryForm; |
import torch
import torch.nn as nn
from torch.nn import TransformerEncoderLayer, TransformerEncoder
from torch.nn.functional import *
from torch.nn.modules.activation import MultiheadAttention, xavier_uniform_, xavier_normal_, \
constant_, Parameter, _LinearWithBias
from torch.nn.modules.transformer import _get_clones
def relational_multi_head_attention_forward(
query: Tensor,
key: Tensor,
value: Tensor,
relation: Tensor,
embed_dim_to_check: int,
num_heads: int,
in_proj_weight: Tensor,
in_proj_bias: Tensor,
bias_k: Optional[Tensor],
bias_v: Optional[Tensor],
add_zero_attn: bool,
dropout_p: float,
out_proj_weight: Tensor,
out_proj_bias: Tensor,
training: bool = True,
key_padding_mask: Optional[Tensor] = None,
need_weights: bool = True,
attn_mask: Optional[Tensor] = None,
use_separate_proj_weight: bool = False,
q_proj_weight: Optional[Tensor] = None,
k_proj_weight: Optional[Tensor] = None,
v_proj_weight: Optional[Tensor] = None,
static_k: Optional[Tensor] = None,
static_v: Optional[Tensor] = None,
relation_type: str = None,
) -> Tuple[Tensor, Optional[Tensor]]:
r"""
Args:
query, key, value: map a query and a set of key-value pairs to an output.
See "Attention Is All You Need" for more details.
relation: relation between queries and keys.
embed_dim_to_check: total dimension of the model.
num_heads: parallel attention heads.
in_proj_weight, in_proj_bias: input projection weight and bias.
bias_k, bias_v: bias of the key and value sequences to be added at dim=0.
add_zero_attn: add a new batch of zeros to the key and
value sequences at dim=1.
dropout_p: probability of an element to be zeroed.
out_proj_weight, out_proj_bias: the output projection weight and bias.
training: apply dropout if is ``True``.
key_padding_mask: if provided, specified padding elements in the key will
be ignored by the attention. This is an binary mask. When the value is True,
the corresponding value on the attention layer will be filled with -inf.
need_weights: output attn_output_weights.
attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
the batches while a 3D mask allows to specify a different mask for the entries of each batch.
use_separate_proj_weight: the function accept the proj. weights for query, key,
and value in different forms. If false, in_proj_weight will be used, which is
a combination of q_proj_weight, k_proj_weight, v_proj_weight.
q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias.
static_k, static_v: static key and value used for attention operators.
Shape:
Inputs:
- query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
the embedding dimension.
- key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
the embedding dimension.
- value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
the embedding dimension.
- relation: :math:`(L, S, N, E)` where L is the target sequence length, where S is the source sequence length,
N is the batch size, E is the embedding dimension.
- key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.
If a ByteTensor is provided, the non-zero positions will be ignored while the zero positions
will be unchanged. If a BoolTensor is provided, the positions with the
value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
- attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked
positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend
while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True``
are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
is provided, it will be added to the attention weight.
- static_k: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
- static_v: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
Outputs:
- attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
E is the embedding dimension.
- attn_output_weights: :math:`(N, L, S)` where N is the batch size,
L is the target sequence length, S is the source sequence length.
"""
tens_ops = (query, key, value, in_proj_weight, in_proj_bias, bias_k, bias_v, out_proj_weight, out_proj_bias)
if has_torch_function(tens_ops):
return handle_torch_function(
multi_head_attention_forward,
tens_ops,
query,
key,
value,
embed_dim_to_check,
num_heads,
in_proj_weight,
in_proj_bias,
bias_k,
bias_v,
add_zero_attn,
dropout_p,
out_proj_weight,
out_proj_bias,
training=training,
key_padding_mask=key_padding_mask,
need_weights=need_weights,
attn_mask=attn_mask,
use_separate_proj_weight=use_separate_proj_weight,
q_proj_weight=q_proj_weight,
k_proj_weight=k_proj_weight,
v_proj_weight=v_proj_weight,
static_k=static_k,
static_v=static_v,
)
tgt_len, bsz, embed_dim = query.size()
assert embed_dim == embed_dim_to_check
# allow MHA to have different sizes for the feature dimension
assert key.size(0) == value.size(0) and key.size(1) == value.size(1)
head_dim = embed_dim // num_heads
assert head_dim * num_heads == embed_dim, "embed_dim must be divisible by num_heads"
scaling = float(head_dim) ** -0.5
if not use_separate_proj_weight:
if (query is key or torch.equal(query, key)) and (key is value or torch.equal(key, value)):
# self-attention
q, k, v = linear(query, in_proj_weight, in_proj_bias).chunk(3, dim=-1)
elif key is value or torch.equal(key, value):
# encoder-decoder attention
# This is inline in_proj function with in_proj_weight and in_proj_bias
_b = in_proj_bias
_start = 0
_end = embed_dim
_w = in_proj_weight[_start:_end, :]
if _b is not None:
_b = _b[_start:_end]
q = linear(query, _w, _b)
if key is None:
assert value is None
k = None
v = None
else:
# This is inline in_proj function with in_proj_weight and in_proj_bias
_b = in_proj_bias
_start = embed_dim
_end = None
_w = in_proj_weight[_start:, :]
if _b is not None:
_b = _b[_start:]
k, v = linear(key, _w, _b).chunk(2, dim=-1)
else:
# This is inline in_proj function with in_proj_weight and in_proj_bias
_b = in_proj_bias
_start = 0
_end = embed_dim
_w = in_proj_weight[_start:_end, :]
if _b is not None:
_b = _b[_start:_end]
q = linear(query, _w, _b)
# This is inline in_proj function with in_proj_weight and in_proj_bias
_b = in_proj_bias
_start = embed_dim
_end = embed_dim * 2
_w = in_proj_weight[_start:_end, :]
if _b is not None:
_b = _b[_start:_end]
k = linear(key, _w, _b)
# This is inline in_proj function with in_proj_weight and in_proj_bias
_b = in_proj_bias
_start = embed_dim * 2
_end = None
_w = in_proj_weight[_start:, :]
if _b is not None:
_b = _b[_start:]
v = linear(value, _w, _b)
else:
q_proj_weight_non_opt = torch.jit._unwrap_optional(q_proj_weight)
len1, len2 = q_proj_weight_non_opt.size()
assert len1 == embed_dim and len2 == query.size(-1)
k_proj_weight_non_opt = torch.jit._unwrap_optional(k_proj_weight)
len1, len2 = k_proj_weight_non_opt.size()
assert len1 == embed_dim and len2 == key.size(-1)
v_proj_weight_non_opt = torch.jit._unwrap_optional(v_proj_weight)
len1, len2 = v_proj_weight_non_opt.size()
assert len1 == embed_dim and len2 == value.size(-1)
if in_proj_bias is not None:
q = linear(query, q_proj_weight_non_opt, in_proj_bias[0:embed_dim])
k = linear(key, k_proj_weight_non_opt, in_proj_bias[embed_dim : (embed_dim * 2)])
v = linear(value, v_proj_weight_non_opt, in_proj_bias[(embed_dim * 2) :])
else:
q = linear(query, q_proj_weight_non_opt, in_proj_bias)
k = linear(key, k_proj_weight_non_opt, in_proj_bias)
v = linear(value, v_proj_weight_non_opt, in_proj_bias)
q = q * scaling
if attn_mask is not None:
assert (
attn_mask.dtype == torch.float32
or attn_mask.dtype == torch.float64
or attn_mask.dtype == torch.float16
or attn_mask.dtype == torch.uint8
or attn_mask.dtype == torch.bool
), "Only float, byte, and bool types are supported for attn_mask, not {}".format(attn_mask.dtype)
if attn_mask.dtype == torch.uint8:
warnings.warn("Byte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.")
attn_mask = attn_mask.to(torch.bool)
if attn_mask.dim() == 2:
attn_mask = attn_mask.unsqueeze(0)
if list(attn_mask.size()) != [1, query.size(0), key.size(0)]:
raise RuntimeError("The size of the 2D attn_mask is not correct.")
elif attn_mask.dim() == 3:
if list(attn_mask.size()) != [bsz * num_heads, query.size(0), key.size(0)]:
raise RuntimeError("The size of the 3D attn_mask is not correct.")
else:
raise RuntimeError("attn_mask's dimension {} is not supported".format(attn_mask.dim()))
# attn_mask's dim is 3 now.
# convert ByteTensor key_padding_mask to bool
if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8:
warnings.warn(
"Byte tensor for key_padding_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead."
)
key_padding_mask = key_padding_mask.to(torch.bool)
if bias_k is not None and bias_v is not None:
if static_k is None and static_v is None:
k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
if attn_mask is not None:
attn_mask = pad(attn_mask, (0, 1))
if key_padding_mask is not None:
key_padding_mask = pad(key_padding_mask, (0, 1))
else:
assert static_k is None, "bias cannot be added to static key."
assert static_v is None, "bias cannot be added to static value."
else:
assert bias_k is None
assert bias_v is None
r = None
# if relation is not None:
# assert r_proj_weight is not None
# assert r_proj_bias is not None
# assert relation.size(0) == tgt_len
# assert relation.size(1) == key.size(0)
# assert relation.size(2) == bsz
# r = linear(relation, r_proj_weight, r_proj_bias)
q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
if k is not None:
k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1)
if v is not None:
v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1)
if static_k is not None:
assert static_k.size(0) == bsz * num_heads
assert static_k.size(2) == head_dim
k = static_k
if static_v is not None:
assert static_v.size(0) == bsz * num_heads
assert static_v.size(2) == head_dim
v = static_v
src_len = k.size(1)
if relation is not None:
if relation_type is "qk+r":
r = relation.contiguous().view(tgt_len, -1, bsz * num_heads, 1).squeeze(3).permute(2, 0, 1)
elif relation_type is "q(k+r)":
r = relation.contiguous().view(tgt_len, src_len, bsz * num_heads, head_dim).permute(2, 0, 1)
r = r.view(bsz * num_heads, tgt_len * src_len, head_dim)
r = torch.bmm(r, q.unsqueeze(2).repeat(1, 1, src_len, 1)
.view(bsz * num_heads, tgt_len * src_len, head_dim).transpose(1, 2))\
.view(bsz * num_heads, tgt_len, src_len)
if key_padding_mask is not None:
assert key_padding_mask.size(0) == bsz
assert key_padding_mask.size(1) == src_len
if add_zero_attn:
src_len += 1
k = torch.cat([k, torch.zeros((k.size(0), 1) + k.size()[2:], dtype=k.dtype, device=k.device)], dim=1)
v = torch.cat([v, torch.zeros((v.size(0), 1) + v.size()[2:], dtype=v.dtype, device=v.device)], dim=1)
if attn_mask is not None:
attn_mask = pad(attn_mask, (0, 1))
if key_padding_mask is not None:
key_padding_mask = pad(key_padding_mask, (0, 1))
attn_output_weights = torch.bmm(q, k.transpose(1, 2))
if r is not None:
attn_output_weights = attn_output_weights + r
assert list(attn_output_weights.size()) == [bsz * num_heads, tgt_len, src_len]
if attn_mask is not None:
if attn_mask.dtype == torch.bool:
attn_output_weights.masked_fill_(attn_mask, float("-inf"))
else:
attn_output_weights += attn_mask
if key_padding_mask is not None:
attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
attn_output_weights = attn_output_weights.masked_fill(
key_padding_mask.unsqueeze(1).unsqueeze(2),
float("-inf"),
)
attn_output_weights = attn_output_weights.view(bsz * num_heads, tgt_len, src_len)
attn_output_weights = softmax(attn_output_weights, dim=-1)
attn_output_weights = dropout(attn_output_weights, p=dropout_p, training=training)
attn_output = torch.bmm(attn_output_weights, v)
assert list(attn_output.size()) == [bsz * num_heads, tgt_len, head_dim]
attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
if need_weights:
# average attention weights over heads
attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
return attn_output, attn_output_weights.sum(dim=1) / num_heads
else:
return attn_output, None
class RelationalMultiheadAttention(MultiheadAttention):
r"""Allows the model to jointly attend to information
from different representation subspaces.
See `Attention Is All You Need <https://arxiv.org/abs/1706.03762>`_
.. math::
\text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O
where :math:`head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)`.
Args:
embed_dim: total dimension of the model.
num_heads: parallel attention heads.
dropout: a Dropout layer on attn_output_weights. Default: 0.0.
bias: add bias as module parameter. Default: True.
add_bias_kv: add bias to the key and value sequences at dim=0.
add_zero_attn: add a new batch of zeros to the key and
value sequences at dim=1.
kdim: total number of features in key. Default: None.
vdim: total number of features in value. Default: None.
Note that if :attr:`kdim` and :attr:`vdim` are None, they will be set
to :attr:`embed_dim` such that query, key, and value have the same
number of features.
Examples::
>>> realational_multihead_attn = RelationalMultiheadAttention(embed_dim, num_heads)
>>> attn_output, attn_output_weights = realational_multihead_attn(query, key, value)
"""
bias_k: Optional[torch.Tensor]
bias_v: Optional[torch.Tensor]
def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None,
vdim=None, add_relation=False, rdim=None, relation_type=None):
super(RelationalMultiheadAttention, self).__init__(embed_dim=embed_dim, num_heads=num_heads,
dropout=dropout, bias=bias, add_bias_kv=add_bias_kv,
add_zero_attn=add_zero_attn, kdim=kdim, vdim=vdim)
self.add_relation = add_relation
self.rdim = rdim if rdim is not None else embed_dim
self.relation_type = relation_type if relation_type else "qk+r"
if self.add_relation:
if relation_type == "qk+r":
self.r_proj_weight = Parameter(torch.Tensor(num_heads, self.rdim))
self.r_proj_bias = Parameter(torch.empty(num_heads))
elif relation_type == "q(k+r)":
self.r_proj_weight = Parameter(torch.Tensor(embed_dim, self.rdim))
self.r_proj_bias = Parameter(torch.empty(embed_dim))
self._reset_parameters()
def _reset_parameters(self):
if self._qkv_same_embed_dim:
xavier_uniform_(self.in_proj_weight)
else:
xavier_uniform_(self.q_proj_weight)
xavier_uniform_(self.k_proj_weight)
xavier_uniform_(self.v_proj_weight)
if hasattr(self, "add_relation") and self.add_relation:
xavier_uniform_(self.r_proj_weight)
constant_(self.r_proj_bias, 0.)
if self.in_proj_bias is not None:
constant_(self.in_proj_bias, 0.)
constant_(self.out_proj.bias, 0.)
if self.bias_k is not None:
xavier_normal_(self.bias_k)
if self.bias_v is not None:
xavier_normal_(self.bias_v)
def __setstate__(self, state):
# Support loading old MultiheadAttention checkpoints generated by v1.1.0
if '_qkv_same_embed_dim' not in state:
state['_qkv_same_embed_dim'] = True
super(MultiheadAttention, self).__setstate__(state)
def forward(self, query: Tensor, key: Tensor, value: Tensor, relation_dict = None, key_padding_mask: Optional[Tensor] = None,
need_weights: bool = True, attn_mask: Optional[Tensor] = None) -> Tuple[Tensor, Optional[Tensor]]:
r"""
Args:
query, key, value: map a query and a set of key-value pairs to an output.
See "Attention Is All You Need" for more details.
key_padding_mask: if provided, specified padding elements in the key will
be ignored by the attention. When given a binary mask and a value is True,
the corresponding value on the attention layer will be ignored. When given
a byte mask and a value is non-zero, the corresponding value on the attention
layer will be ignored
need_weights: output attn_output_weights.
attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
the batches while a 3D mask allows to specify a different mask for the entries of each batch.
Shapes for inputs:
- query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
the embedding dimension.
- key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
the embedding dimension.
- value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
the embedding dimension.
- key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.
If a ByteTensor is provided, the non-zero positions will be ignored while the position
with the zero positions will be unchanged. If a BoolTensor is provided, the positions with the
value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
- attn_mask: if a 2D mask: :math:`(L, S)` where L is the target sequence length, S is the
source sequence length.
If a 3D mask: :math:`(N\cdot\text{num\_heads}, L, S)` where N is the batch size, L is the target sequence
length, S is the source sequence length. ``attn_mask`` ensure that position i is allowed to attend
the unmasked positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend
while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True``
is not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
is provided, it will be added to the attention weight.
Shapes for outputs:
- attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
E is the embedding dimension.
- attn_output_weights: :math:`(N, L, S)` where N is the batch size,
L is the target sequence length, S is the source sequence length.
"""
if relation_dict is not None:
relation_labels = relation_dict["relation_labels"]
relation_ids = relation_dict["relation_ids"]
batch_index = relation_dict["batch_index"]
pad_embedding = relation_dict["pad_embedding"]
relation_labels = linear(relation_labels, self.r_proj_weight, self.r_proj_bias)
pad_embedding = linear(pad_embedding.unsqueeze(0), self.r_proj_weight, self.r_proj_bias).squeeze()
tgt_length, bsz, _ = query.size()
src_length, _, _ = key.size()
# TODO: q(k+r)时, 先张成relation矩阵会爆显存
relation = pad_embedding.view(1, 1, 1, -1).repeat(bsz, tgt_length, src_length, 1)
relation[batch_index, relation_ids[:, :, 0], relation_ids[:, :, 1]] = relation_labels
relation = relation.permute(1, 2, 0, 3)
if not self._qkv_same_embed_dim:
return relational_multi_head_attention_forward(
query, key, value, relation, self.embed_dim, self.num_heads,
self.in_proj_weight, self.in_proj_bias,
self.bias_k, self.bias_v, self.add_zero_attn,
self.dropout, self.out_proj.weight, self.out_proj.bias,
training=self.training,
key_padding_mask=key_padding_mask, need_weights=need_weights,
attn_mask=attn_mask, use_separate_proj_weight=True,
q_proj_weight=self.q_proj_weight, k_proj_weight=self.k_proj_weight,
v_proj_weight=self.v_proj_weight)
else:
return relational_multi_head_attention_forward(
query, key, value, relation, self.embed_dim, self.num_heads,
self.in_proj_weight, self.in_proj_bias,
self.bias_k, self.bias_v, self.add_zero_attn,
self.dropout, self.out_proj.weight, self.out_proj.bias,
training=self.training,
key_padding_mask=key_padding_mask, need_weights=need_weights,
attn_mask=attn_mask)
else:
if not self._qkv_same_embed_dim:
return relational_multi_head_attention_forward(
query, key, value, None, self.embed_dim, self.num_heads,
self.in_proj_weight, self.in_proj_bias,
self.bias_k, self.bias_v, self.add_zero_attn,
self.dropout, self.out_proj.weight, self.out_proj.bias,
training=self.training,
key_padding_mask=key_padding_mask, need_weights=need_weights,
attn_mask=attn_mask, use_separate_proj_weight=True,
q_proj_weight=self.q_proj_weight, k_proj_weight=self.k_proj_weight,
v_proj_weight=self.v_proj_weight)
else:
return relational_multi_head_attention_forward(
query, key, value, None, self.embed_dim, self.num_heads,
self.in_proj_weight, self.in_proj_bias,
self.bias_k, self.bias_v, self.add_zero_attn,
self.dropout, self.out_proj.weight, self.out_proj.bias,
training=self.training,
key_padding_mask=key_padding_mask, need_weights=need_weights,
attn_mask=attn_mask)
class RelationalTransformerEncoderLayer(TransformerEncoderLayer):
r"""TransformerEncoderLayer is made up of self-attn and feedforward network.
This standard encoder layer is based on the paper "Attention Is All You Need".
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez,
Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in
Neural Information Processing Systems, pages 6000-6010. Users may modify or implement
in a different way during application.
Args:
d_model: the number of expected features in the input (required).
nhead: the number of heads in the multiheadattention models (required).
dim_feedforward: the dimension of the feedforward network model (default=2048).
dropout: the dropout value (default=0.1).
activation: the activation function of intermediate layer, relu or gelu (default=relu).
Examples::
>>> encoder_layer = RelationalTransformerEncoderLayer(d_model=512, nhead=8)
>>> src = torch.rand(10, 32, 512)
>>> rel = torch.rand(10, 10, 32, 512)
>>> out = encoder_layer(src, rel)
"""
def __init__(self, d_model, nhead, add_relation=False, dim_feedforward=2048,
dropout=0.1, activation="relu", relation_type=None):
super(RelationalTransformerEncoderLayer, self).__init__(d_model, nhead, dim_feedforward=dim_feedforward,
dropout=dropout, activation=activation)
self.self_attn = RelationalMultiheadAttention(d_model, nhead, add_relation=add_relation,
dropout=dropout, relation_type=relation_type)
def forward(self, src: Tensor, relation = None, src_mask: Optional[Tensor] = None,
src_key_padding_mask: Optional[Tensor] = None) -> Tensor:
r"""Pass the input through the encoder layer.
Args:
src: the sequence to the encoder layer (required).
src_mask: the mask for the src sequence (optional).
src_key_padding_mask: the mask for the src keys per batch (optional).
Shape:
see the docs in Transformer class.
"""
src2 = self.self_attn(src, src, src, relation_dict=relation, attn_mask=src_mask,
key_padding_mask=src_key_padding_mask)[0]
src = src + self.dropout1(src2)
src = self.norm1(src)
src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
src = src + self.dropout2(src2)
src = self.norm2(src)
return src
class RelationalTransformerEncoder(TransformerEncoder):
r"""TransformerEncoder is a stack of N encoder layers
Args:
encoder_layer: an instance of the TransformerEncoderLayer() class (required).
num_layers: the number of sub-encoder-layers in the encoder (required).
norm: the layer normalization component (optional).
Examples::
>>> encoder_layer = RelationalTransformerEncoderLayer(d_model=512, nhead=8)
>>> transformer_encoder = RelationalTransformerEncoder(encoder_layer, num_layers=6)
>>> src = torch.rand(10, 32, 512)
>>> rel = torch.rand(10, 10, 32, 512)
>>> out = transformer_encoder(src, rel)
"""
__constants__ = ['norm']
def __init__(self, encoder_layer, num_layers, norm=None):
super(TransformerEncoder, self).__init__()
self.layers = _get_clones(encoder_layer, num_layers)
self.num_layers = num_layers
self.norm = norm
def forward(self, src: Tensor, relation = None, mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None) -> Tensor:
r"""Pass the input through the encoder layers in turn.
Args:
src: the sequence to the encoder (required).
mask: the mask for the src sequence (optional).
src_key_padding_mask: the mask for the src keys per batch (optional).
Shape:
see the docs in Transformer class.
"""
output = src
for mod in self.layers:
output = mod(output, relation=relation, src_mask=mask, src_key_padding_mask=src_key_padding_mask)
if self.norm is not None:
output = self.norm(output)
return output
if __name__ == "__main__":
encoder_layer = RelationalTransformerEncoderLayer(add_relation=True, d_model=512, nhead=8)
transformer_encoder = RelationalTransformerEncoder(encoder_layer, num_layers=6)
src = torch.rand(10, 32, 512)
rel = torch.rand(10, 10, 32, 512)
out = transformer_encoder(src, rel) |
const EQUAL = Symbol('EQUAL');
function deepAreSortedArraysEqual<T extends Array<any>>(array1: T, array2: T) {
if (array1.length !== array2.length) {
return false;
}
return array1.every((item, i) => deepDiff(item, array2[i]) === EQUAL);
}
export function deepDiff<T extends any>(value1: T, value2: T): Partial<T> | typeof EQUAL {
const type1 = typeof value1;
const type2 = typeof value2;
if (value1 === value2) {
return EQUAL;
}
if (type1 !== type2) {
return value2;
}
if (type2 !== 'object') {
return value2;
}
if (Array.isArray(value1) && Array.isArray(value2)) {
if (deepAreSortedArraysEqual(value1, value2)) return EQUAL;
return value2;
}
const object1 = value1 as AnyLiteral;
const object2 = value2 as AnyLiteral;
const keys1 = Array.from(new Set([...Object.keys(object1), ...Object.keys(object2)]));
const reduced = keys1.reduce((acc: any, el) => {
if (object1[el] === object2[el]) {
return acc;
}
const o1has = object1.hasOwnProperty(el);
const o2has = object2.hasOwnProperty(el);
if (!o2has) {
acc[el] = { __delete: true };
return acc;
}
if (!o1has && o2has) {
acc[el] = object2[el];
return acc;
}
const diff = deepDiff(object1[el], object2[el]);
if (diff !== EQUAL) acc[el] = diff;
return acc;
}, {});
if (Object.keys(reduced).length === 0) {
return EQUAL;
}
return reduced;
} |
@extends('panel.master')
@section('content')
<main id="main" class="main">
@include('panel.alert')
@error('currentpassword')
<p class="invalid-feedback">{{ $message }}</p>
@enderror
@error('newpassword')
<p class="invalid-feedback">{{ $message }}</p>
@enderror
<div class="pagetitle">
<h1>Profile</h1>
<nav>
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="#">Home</a></li>
<li class="breadcrumb-item">Users</li>
<li class="breadcrumb-item active">Profile</li>
</ol>
</nav>
</div><!-- End Page Title -->
<section class="section profile">
<div class="row">
<div class="col-xl-4">
<div class="card">
<div class="card-body profile-card pt-4 d-flex flex-column align-items-center">
@if (Auth::check() && Auth::user()->image != '')
<img src="{{ asset('profile_pic/thumb/'.Auth::user()->image) }}" alt="Profile" class="rounded-circle">
@else
<img src="{{asset('assets/images/avatar7.png')}}" alt="Profile" class="rounded-circle">
@endif
<h2>{{ Auth::check() ? Auth::user()->name :" "}}</h2>
<h3>{{ Auth::check() ? Auth::user()->designation :" " }}</h3>
<div class="social-links mt-2">
<a href="#" class="twitter"><i class="bi bi-twitter"></i></a>
<a href="#https://www.facebook.com/profile.php?id=100060307328465" class="facebook"><i class="bi bi-facebook"></i></a>
<a href="#" class="instagram"><i class="bi bi-instagram"></i></a>
<a href="#" class="linkedin"><i class="bi bi-linkedin"></i></a>
</div>
</div>
</div>
</div>
<div class="col-xl-8">
<div class="card">
<div class="card-body pt-3">
<!-- Bordered Tabs -->
<ul class="nav nav-tabs nav-tabs-bordered">
<li class="nav-item">
<a class="nav-link active" data-bs-toggle="tab" href="#profile-overview">Overview</a>
</li>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="tab" href="#profile-edit">Edit Profile</a>
</li>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="tab" href="#profile-change-password">Change Password</a>
</li>
</ul>
<div class="tab-content pt-2">
<div class="tab-pane fade show active profile-overview" id="profile-overview">
<h5 class="card-title">About</h5>
<p class="small fst-italic">{{ Auth::check() ? Auth::user()->bio : 'hello!'}}</p>
<h5 class="card-title">Profile Details</h5>
<div class="row">
<div class="col-lg-3 col-md-4 label ">Full Name</div>
<div class="col-lg-9 col-md-8">{{Auth::check() ? Auth::user()->name : " "}}</div>
</div>
<div class="row">
<div class="col-lg-3 col-md-4 label">Job</div>
<div class="col-lg-9 col-md-8">{{ ( Auth::check() && Auth::user()->designation )? Auth::user()->designation: "-- " }}</div>
</div>
<div class="row">
<div class="col-lg-3 col-md-4 label">Phone</div>
<div class="col-lg-9 col-md-8">{{ ( Auth::check() && Auth::user()->mobile )? Auth::user()->mobile : '-- '}}</div>
</div>
<div class="row">
<div class="col-lg-3 col-md-4 label">Email</div>
<div class="col-lg-9 col-md-8">{{Auth::check() ? Auth::user()->email :" "}}</div>
</div>
</div>
<!-- Profile Edit Form -->
<div class="tab-pane fade pt-3" id="profile-edit">
<form action="{{route('panel.updateProfile') }}" method="POST" id="userForm" name="userForm">
@csrf
<div class="row mb-3">
<label for="fullName" class="col-md-4 col-lg-3 col-form-label">Full Name</label>
<div class="col-md-8 col-lg-9">
<input name="name" type="text" class="form-control @error('name') is-invalid @enderror" id="name" value="{{Auth::check() ? Auth::user()->name : " "}}">
@error('name')
<p class="invalid-feedback">{{ $message }}</p>
@enderror
</div>
</div>
<div class="row mb-3">
<label for="about" class="col-md-4 col-lg-3 col-form-label">About</label>
<div class="col-md-8 col-lg-9">
<textarea name="bio" class="form-control @error('bio') is-invalid @enderror" id="bio" style="height: 100px">{{Auth::check() ? Auth::user()->bio : " "}}</textarea>
</div>
@error('bio')
<p class="invalid-feedback">{{ $message }}</p>
@enderror
</div>
<div class="row mb-3">
<label for="Job" class="col-md-4 col-lg-3 col-form-label">Designation</label>
<div class="col-md-8 col-lg-9">
<input name="designation" type="text" class="form-control @error('designation') is-invalid @enderror" id="designation" value="{{Auth::check() ? Auth::user()->desination : " "}}">
</div>
@error('designation')
<p class="invalid-feedback">{{ $message }}</p>
@enderror
</div>
<div class="row mb-3">
<label for="Phone" class="col-md-4 col-lg-3 col-form-label">Phone</label>
<div class="col-md-8 col-lg-9">
<input name="phone" type="text" class="form-control @error('mobile') is-invalid @enderror" id="mobile" value="{{Auth::check() ? Auth::user()->mobile : " "}}">
</div>
@error('mobile')
<p class="invalid-feedback">{{ $message }}</p>
@enderror
</div>
<div class="row mb-3">
<label for="Email" class="col-md-4 col-lg-3 col-form-label">Email</label>
<div class="col-md-8 col-lg-9">
<input name="email" type="email" class="form-control @error('email') is-invalid @enderror" id="email" value="{{Auth::check() ? Auth::user()->email : " "}}">
@error('email')
<p class="invalid-feedback">{{ $message }}</p>
@enderror
</div>
</div>
<div class="text-center">
<button class="btn btn-primary" type="submit" >Save Changes</button>
</div>
</form><!-- End Profile Edit Form -->
</div>
<div class="tab-pane fade pt-3" id="profile-change-password">
<!-- Change Password Form -->
<form action="{{route('panel.changePassword')}}" id="changePasswordForm" name="changePasswordForm" method="POST">
@csrf
<div class="row mb-3">
<label for="currentpassword" class="col-md-4 col-lg-3 col-form-label">Current Password</label>
<div class="col-md-8 col-lg-9">
<input name="currentpassword" type="password" class="form-control @error('currentpassword') is-invalid @enderror" id="currentpassword">
</div>
@error('currentpassword')
<p class="invalid-feedback">{{ $message }}</p>
@enderror
</div>
<div class="row mb-3">
<label for="newpassword" class="col-md-4 col-lg-3 col-form-label">New Password</label>
<div class="col-md-8 col-lg-9">
<input name="newpassword" type="password" class="form-control @error('newpassword') is-invalid @enderror" id="newpassword">
</div>
@error('newpassword')
<p class="invalid-feedback">{{ $message }}</p>
@enderror
</div>
<div class="row mb-3">
<label for="renewpassword" class="col-md-4 col-lg-3 col-form-label">Re-enter New Password</label>
<div class="col-md-8 col-lg-9">
<input name="renewpassword" type="password" class="form-control @error('renewpassword') is-invalid @enderror" id="renewpassword">
</div>
@error('renewpassword')
<p class="invalid-feedback">{{ $message }}</p>
@enderror
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Change Password</button>
</div>
</form><!-- End Change Password Form -->
</div>
</div><!-- End Bordered Tabs -->
</div>
</div>
</div>
</div>
</section>
</main><!-- End #main -->
@endsection
@section('customJs')
@endsection |
// import 'package:flutter/material.dart';
// import 'package:flutter_svg/flutter_svg.dart';
// import 'package:provider/provider.dart';
// import 'package:pos_portal/view_model/cart_view_model.dart';
// import '../utils/colors.dart';
// import '../model/cart.dart';
//
// class CartShop extends StatefulWidget {
// const CartShop({super.key});
//
// @override
// State<CartShop> createState() => _CartShopState();
// }
//
// class _CartShopState extends State<CartShop> {
// @override
// Widget build(BuildContext context) {
// final cartViewModel = Provider.of<CartViewModel>(context);
// return Container(
// padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
// color: Colors.white,
// child: Consumer<CartViewModel>(
// builder: (context, cartViewModel, _) {
// int cartLength = cartViewModel.cartLength;
// double total = cartViewModel.getTotalPrice();
// print("Change detected in CartShop widget. Total price: $total"); // Not printed
// return Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// Row(
// children: [
// Padding(
// padding: const EdgeInsets.only(right: 20),
// child: Stack(
// children: [
// const SizedBox(
// height: 33,
// width: 38,
// ),
// SvgPicture.asset(
// 'assets/svg/icon_cart.svg',
// width: 33.25,
// height: 32.81,
// ),
// Positioned(
// right: 0,
// top: 0,
// child: Container(
// width: 16,
// height: 16,
// decoration: BoxDecoration(
// color: MyColors.error,
// borderRadius: BorderRadius.circular(8),
// ),
// child: Center(
// child: Text(
// cartLength.toString(),
// style: const TextStyle(
// color: Colors.white,
// fontSize: 11,
// fontWeight: FontWeight.w600,
// fontFamily: 'Montserrat',
// ),
// ),
// ),
// ),
// ),
// ],
// ),
// ),
// const Padding(
// padding: EdgeInsets.only(right: 6),
// child: Text(
// 'Total:',
// style: TextStyle(
// color: Colors.black,
// fontSize: 16,
// fontWeight: FontWeight.w500,
// fontFamily: 'Montserrat'),
// ),
// ),
// Text(
// 'Rp ${total.toStringAsFixed(2)}',
// style: const TextStyle(
// color: Colors.black,
// fontSize: 16,
// fontWeight: FontWeight.w600,
// fontFamily: 'Montserrat'),
// ),
// ],
// ),
// SizedBox(
// width: MediaQuery.of(context).size.width * 0.30,
// child: ElevatedButton(
// style: ButtonStyle(
// backgroundColor: MaterialStateProperty.all(MyColors.primary),
// shape: MaterialStateProperty.all<RoundedRectangleBorder>(
// RoundedRectangleBorder(
// borderRadius: BorderRadius.circular(8),
// ),
// ),
// ),
// onPressed: () {
// // Navigate to the payment method page
// },
// child: const Text(
// 'Bayar',
// style: TextStyle(
// fontFamily: 'Montserrat',
// fontSize: 16,
// fontWeight: FontWeight.w700,
// color: Colors.white),
// ),
// ),
// ),
// ],
// );
// },
// ),
// );
// }
// }
import 'package:flutter/material.dart';
import 'package:pos_portal/view_model/cart_provider.dart';
import 'package:provider/provider.dart';
class CartShop extends StatefulWidget {
const CartShop({super.key});
@override
State<CartShop> createState() => _CartShopState();
}
class _CartShopState extends State<CartShop> {
late CartProvider _cartProvider;
@override
Widget build(BuildContext context) {
_cartProvider = Provider.of<CartProvider>(context);
return Text('Cart length: ${_cartProvider.carts.length}');
}
} |
import { HttpExceptionEnum } from "../../../../exceptions";
import ValidationException from "../../../../exceptions/ValidationException";
import { IUserRepository } from "../../../../modules/User/repositories/interfaces/IUserRepository";
import { DiskStorage } from "../../../../providers/DiskStorage";
export default class UpdateUserAvatarUseCase {
private userRepository: IUserRepository;
constructor(userRepository: IUserRepository) {
this.userRepository = userRepository;
}
async execute(userId: string, userAvatar: string) {
const existingUser: any = await this.userRepository.getById(userId);
const diskStorage = new DiskStorage();
if (!existingUser) {
throw new ValidationException(
HttpExceptionEnum.NOT_FOUND,
{
message: `Usuário não encontrado.`,
},
404,
);
}
if (existingUser.avatar) {
await diskStorage.deleteFile(existingUser.avatar);
}
const filename = await diskStorage.saveFile(userAvatar);
existingUser.avatar = filename;
const updatedUser = await this.userRepository.update(userId, {
avatar: existingUser.avatar,
});
return updatedUser;
}
} |
package com.loginregistration.controller;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import com.loginregistration.model.Constant;
import com.loginregistration.service.UserService;
import com.loginregistration.service.UserServiceImpl;
@SuppressWarnings("serial")
@WebServlet(urlPatterns = "/taotaikhoan")
public class RegisterController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession(false);
if (session != null && session.getAttribute("username") != null) {
resp.sendRedirect(req.getContextPath() + "/admin");
return;
}
// Check cookie
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
session = req.getSession(true);
session.setAttribute("username", cookie.getValue());
resp.sendRedirect(req.getContextPath() + "/admin");
return;
}
}
}
req.getRequestDispatcher(Constant.Path.REGISTER).forward(req, resp);
}
@SuppressWarnings("static-access")
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
req.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String email = req.getParameter("email");
String fullname = req.getParameter("fullname");
String phone = req.getParameter("phone");
UserService service = new UserServiceImpl();
String alertMsg = "";
if (service.checkExistEmail(email)) {
alertMsg = "Email đã tồn tại!";
req.setAttribute("alert", alertMsg);
req.getRequestDispatcher(Constant.Path.REGISTER).forward(req, resp);
return;
}
if (service.checkExistUsername(username)) {
alertMsg = "Tài khoản đã tồn tại!";
req.setAttribute("alert", alertMsg);
req.getRequestDispatcher(Constant.Path.REGISTER).forward(req, resp);
return;
}
boolean isSuccess = service.register(username, password, email, fullname, phone);
if (isSuccess) {
// SendMail sm= new SendMail();
// sm.sendMail(email, "Shopping.iotstar.vn", "Welcome to Shopping. Please Login
// to use service. Thanks !");
req.setAttribute("alert", alertMsg);
resp.sendRedirect(req.getContextPath() + "/login");
} else {
alertMsg = "System error!";
req.setAttribute("alert", alertMsg);
req.getRequestDispatcher(Constant.Path.REGISTER).forward(req, resp);
}
}
} |
"""Server stores knowledge about which client has which file."""
from __future__ import annotations
import logging
from typing import Sequence
import curio, curio.io
from directories import File, Directory, decode
import json
from collections import defaultdict
RECV_SIZE = 1024
declared_dirs: Sequence[Directory] = [] # TODO: add names to user
files: defaultdict[str, set[str]] = defaultdict(set)
def search_user_dir(dir: Directory, term: str) -> Directory | None:
"""Search a term in a user directory, returns False if no matches."""
search_result = dir.copy()
def search(x: Directory | File) -> bool:
if term in x.name:
return True
match x:
case File():
return False
case Directory():
x.contents = [y for y in x.contents if search(y)]
return x.contents != []
if not search(search_result):
return None
else:
return search_result
def add_user_dir(clientaddr, dir: Directory):
"""Register a user directory, recursively adding files into `files`."""
declared_dirs.append(dir)
def get_all_file_hashes(dir: Directory):
for x in dir.contents:
match x:
case File():
yield x.hash
case Directory():
yield from get_all_file_hashes(x)
for filehash in get_all_file_hashes(dir):
files[filehash].add(clientaddr)
async def receive_message(client: curio.io.Socket, addr: tuple[str, int]):
"""Receive a message from a client connection, and return response."""
print(client, type(client))
print(addr, type(addr))
msg: bytearray = bytearray()
while data := await client.recv(RECV_SIZE): # BUG: Can potentially cause exception
msg += data
response = await process_message(addr, msg.decode())
logging.info(f"Received message from {addr}: {msg}")
logging.info(f"Sending response: {response}")
await client.sendall(response)
async def process_message(clientaddr: tuple[str, int], msg: str) -> bytes:
"""Parse a single user message, returning a response."""
if msg == 'ping':
return b"I'm awake!"
elif msg.startswith('DECLAREDIR'):
dir = decode(msg.split(maxsplit=1)[1])
if isinstance(dir, File):
return b"File declaration unsupported"
add_user_dir(clientaddr, dir)
return f'Sure mate, {dir.name} was added'.encode()
elif msg == 'ALL':
return Directory('ALL FILES', declared_dirs).to_json().encode()
elif msg.startswith('QUERY'):
filehash = msg.split(maxsplit=1)[1]
if users_with_file := files.get(filehash):
return json.dumps(list(users_with_file)).encode()
return b'NOUSERS'
elif msg.startswith('SEARCH'):
search_term = msg.split(maxsplit=1)[1]
search_results: list[Directory] = []
for x in declared_dirs:
y = search_user_dir(x, search_term)
if y is not None:
search_results.append(y)
return Directory('SEARCH RESULTS', search_results).to_json().encode()
else:
return b"UNSUPPORTED"
def main():
logging.info('Started. Currently supports "ping", "all" and "declare" command(s).')
try:
curio.run(curio.tcp_server, '', 25000, receive_message)
except KeyboardInterrupt:
logging.info("Server shutting down...")
if __name__ == '__main__':
main() |
<template>
<div class="container">
<el-select v-model="filterType" style="width: 120px;">
<el-option v-for="item in filterTypeOptions" :key="item.value" :label="item.label" :value="<string>item.value" />
</el-select>
<el-select v-model="matchProp" style="width: 120px;">
<el-option v-for="item in matchOptions" :key="item.value" :label="item.label" :value="<string>item.value" />
</el-select>
<el-select v-model="predicate" style="width: 120px;">
<el-option v-for="item in predicateOptions" :key="item.value" :label="item.label" :value="<string>item.value" />
</el-select>
<!-- 文件名/扩展名输入 -->
<el-input v-if='matchProp === "filename" || matchProp === "extension"' v-model="predicateStringParam" />
<el-checkbox v-if='matchProp === "filename" || matchProp === "extension"' v-model="ignoreCase"
border>忽略大小写</el-checkbox>
<!-- 文件大小输入 -->
<el-input-number v-if='matchProp === "size"' v-model="predicateNumberParam" :min="0" controls-position="right" />
<el-select v-if='matchProp === "size"' v-model="sizeUnit" style="width: 80px;">
<el-option v-for='item in ["KB", "MB", "GB", "TB"]' :key="item" :label="item" :value="item" />
</el-select>
<!-- 日期输入 -->
<el-date-picker v-if='matchProp === "modifyTime"' v-model="predicateNumberParam" type="datetime"
placeholder="Select date and time" style="margin-right: 12px;" />
<!-- 提交 -->
<el-button type="primary" @click="onSubmit" style="width: 80px;">提交</el-button>
<!-- 备注提示 -->
<el-alert v-if="Boolean(remark)" type="info" :closable="false" show-icon>
<template v-slot:title>
<span class="alert">{{ remark }}</span>
</template>
</el-alert>
</div>
</template>
<script lang="ts" setup>
import { filterTypeOptions, matchOptions, stringPredicateOptions, numberPredicateOptions } from '@/lib/filter/filter.const';
import { FileFilterItem } from '@/lib/filter/FileFilterItem';
// 包含还是排除
const filterType = ref<FileFilterType>("include")
// 过滤的属性
const matchProp = ref<FileFilterProp>("filename")
// 过滤的操作(谓词)
const predicate = ref<FileFilterPredicate>(undefined)
const predicateOptions = ref<PredicateItem[]>([])
// 过滤操作的参数
const predicateStringParam = ref("")
const predicateNumberParam = ref(0)
// 过滤操作的额外参数
const ignoreCase = ref(true) // 忽略大小写
const sizeUnit = ref<SizeUnit>("KB") // 大小的单位
// 备注提示
const remark = ref("")
watch(matchProp, () => {
const m = matchProp.value;
if (m === "filename" || m === "extension") {
predicateOptions.value = stringPredicateOptions
predicate.value = stringPredicateOptions[0].value
}
else if (m === "size" || m === "modifyTime") {
predicateOptions.value = numberPredicateOptions
predicate.value = numberPredicateOptions[0].value
predicateNumberParam.value = 0
}
else {
console.error("存在没有处理的选项", m)
}
switch (m) {
case "filename":
remark.value = "这里的文件名不包括扩展名称"
break
case "extension":
remark.value = "后缀名称包括字符 \".\""
break
default:
remark.value = ""
}
}, {
immediate: true
})
const buildFilterOptions: () => FileFilterItem | null = () => {
const options = {
prop: matchProp.value,
predicate: predicate.value,
stringValue: predicateStringParam.value?.trim(),
numberValue: predicateNumberParam.value,
caseSensitive: !ignoreCase.value,
sizeUnit: sizeUnit.value,
}
if (options.prop === "filename" || options.prop === "extension") {
if (!options.stringValue) {
ElMessage.error('Oops, 还没有填写具体内容')
return null
}
}
if (options.prop === "modifyTime" && options.numberValue < 1) {
ElMessage.error('Oops, 请重新选择日期')
return null
}
return FileFilterItem.build(
filterType.value,
options.prop,
options.predicate,
options.stringValue,
options.numberValue,
options.caseSensitive,
options.sizeUnit)
}
const emit = defineEmits(["submit"])
const onSubmit = () => {
const options = buildFilterOptions()
if (options) {
emit("submit", options)
}
}
</script>
<style lang="less" scoped>
.container {
display: flex;
align-items: center;
padding: 4px 0 0 0;
&>div,
label,
button {
margin-right: 12px;
}
}
.el-input {
max-width: 240px;
}
.el-alert {
max-width: 280px;
padding: 6px 8px;
}
.alert {
line-height: 21px;
}
</style> |
package org.klojang.jdbc;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* <p>Converts the rows in a JDBC {@link ResultSet} into {@code Map<String, Object}
* pseudo-objects. Instances are obtained via
* {@link MappifierFactory#getMappifier(ResultSet) MappifierFactory.getMappifier()}.
*
* @author Ayco Holleman
* @see MappifierFactory
* @see ResultSetBeanifier
*/
public sealed interface ResultSetMappifier extends Iterable<Map<String, Object>>
permits DefaultMappifier, EmptyMappifier {
/**
* Converts the current row in a {@code ResultSet} into a map. If the
* {@code ResultSet} is empty, or if there are no more rows in the {@code ResultSet},
* an empty {@code Optional} is returned. You can keep calling {@code mappify()} to
* successively extract all rows in the result set.
*
* @return a map containing the values in the current row in a {@code ResultSet}
* @see MappifierFactory#getMappifier(ResultSet)
*/
Optional<Map<String, Object>> mappify();
/**
* Converts at most {@code limit} rows in a {@code ResultSet} into maps. If the
* {@code ResultSet} is empty, an empty {@code List} is returned.
*
* @param limit the maximum number of records to mappify
* @return a {@code List} of {@code Map} objects or an empty {@code List} if the
* {@code ResultSet} contained no (more) rows
*/
List<Map<String, Object>> mappify(int limit);
/**
* Converts all remaining rows in a {@code ResultSet} into maps.
*
* @return a {@code List} of {@code Map} objects or an empty {@code List} if the
* {@code ResultSet} contained no (more) rows
*/
List<Map<String, Object>> mappifyAll();
/**
* Converts all remaining rows in a {@code ResultSet} into maps.
*
* @param sizeEstimate an estimate of the total size of the result set
* @return a {@code List} of {@code Map} objects or an empty {@code List} if the
* {@code ResultSet} contained no (more) rows
*/
List<Map<String, Object>> mappifyAll(int sizeEstimate);
/**
* Returns {@code true} if the end of the {@code ResultSet} has been reached;
* {@code false} otherwise.
*
* @return Whether the end of the {@code ResultSet} has been reached
*/
boolean isEmpty();
} |
/*
* Copyright (C) 2024 Mark R. Turner. All Rights Reserved.
*
* The Ember ("EMBedded c webservER") server code is based on the FreeRTOS Labs
* TCP protocols example at
* https://github.com/FreeRTOS/FreeRTOS/blob/main/FreeRTOS-Plus/Demo/Common/Demo_IP_Protocols/Common/FreeRTOS_TCP_server.c
* (and associated directories).
*
* For that reason, the FreeRTOS licence is reproduced below. However, the
* reader should be aware that the author has undertaken considerable additional
* work to extend both the core TCP server and the protocol implementations.
*
* In any case, the additional work is released under the same MIT licence as the
* FreeRTOS Labs demonstration code.
*
* FreeRTOS V202212.00
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*
* MIT Licence
* 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.
*
*/
includes
#include <FreeRTOS.h>
#include <FreeRTOS_IP.h>
#include "inc/ember_private.h"
#include "inc/ember.h"
private constants
private data prototypes
typedef struct
{
BaseType_t xReady;
const configSTACK_DEPTH_TYPE uxStackSz;
const TickType_t uxStartupDelay;
const TickType_t uxPeriod;
TaskHandle_t xPid;
const TCPServerConfig_t *const pxWebConfig;
TCPServer_t *pxServer;
} EmberConfig_t;
private function prototypes
/* Task for the Ember server */
static void prvEmber_Service(void *args);
static TCPServer_t *prvCreateTCPServer(
const TCPServerConfig_t *const pxServerCfg);
static BaseType_t prvCreateProtocolServer(
WebProtoServer_t *pxProto,
const WebProtoConfig_t *pxProtoCfg);
static void prvTCPServerWork(void);
static void prvAcceptNewClient(WebProtoServer_t *pxProto, Socket_t xNewSock);
static TCPClient_t *prvRemoveClient(TCPClient_t *pxClient);
static TCPClient_t *prvDropClient(TCPClient_t *pxClient);
external objects
extern const TCPServerConfig_t xWebProtoConfig __attribute__((weak, alias("_xWebProtoConfig")));
/* the `xWebProtoConfig` object should be located elsewhere in source, e.g. in ember_config.c
* */
static const TCPServerConfig_t _xWebProtoConfig = {0, 0};
private global variables
static EmberConfig_t xEmber =
{ pdFALSE, emberSTACK_SIZE, emberSTARTUP_DELAY_MS, emberPERIOD_MS, 0, &xWebProtoConfig, 0 };;
public functions
void Ember_Init()
{
if (xEmber.xReady)
return;
xTaskCreate(prvEmber_Service, (const char *)"Ember", xEmber.uxStackSz, 0,
tskIDLE_PRIORITY, &xEmber.xPid);
xEmber.xReady = pdTRUE;
}
void Ember_DeInit()
{
if (!xEmber.xReady)
return;
vTaskDelete(xEmber.xPid);
xEmber.xPid = 0;
xEmber.xReady = pdFALSE;
}
void Ember_SelectClients(BaseType_t (*xActionFunc)(void *, void *), void *pxArg)
{
TCPClient_t *pxCurrClient, *pxNextClient;
BaseType_t xRc;
if (!xEmber.xReady || !xEmber.pxServer || !xEmber.pxServer->pxClients)
return;
xSemaphoreTake(xEmber.pxServer->xClientMutex, xEmber.uxPeriod * 2);
pxCurrClient = xEmber.pxServer->pxClients;
while (pxCurrClient)
{
pxNextClient = pxCurrClient->pxNextClient;
xRc = xActionFunc(pxCurrClient, pxArg);
if (xRc < 0)
prvDropClient(pxCurrClient);
pxCurrClient = pxNextClient;
}
xSemaphoreGive(xEmber.pxServer->xClientMutex);
}
private functions
static void prvEmber_Service(void *args)
{
vTaskDelay(xEmber.uxStartupDelay);
xEmber.pxServer = prvCreateTCPServer(xEmber.pxWebConfig);
if (!xEmber.pxServer)
{
xEmber.xPid = 0;
xEmber.xReady = pdFALSE;
return;
}
while (1)
{
prvTCPServerWork();
}
}
/* TODO: servers should be created on a specific network interface, not just assigned to
* the first one (or maybe all of them)
* */
static TCPServer_t *prvCreateTCPServer(
const TCPServerConfig_t *const pxServerCfg)
{
TCPServer_t *pxNewServer;
SocketSet_t xSockSet;
Socket_t xSock;
struct freertos_sockaddr xSockAddr;
BaseType_t xNoTimeout = 0;
if (!pxServerCfg || pxServerCfg->uxNumProtocols <= 0)
return 0;
xSockSet = FreeRTOS_CreateSocketSet();
if (!xSockSet)
return 0;
size_t uxServerSz = sizeof(TCPServer_t) + ((pxServerCfg->uxNumProtocols - 1) * sizeof(WebProtoServer_t));
pxNewServer = pvPortMalloc(uxServerSz);
if (!pxNewServer)
{
FreeRTOS_DeleteSocketSet(xSockSet);
return 0;
}
memset(pxNewServer, 0, uxServerSz);
pxNewServer->xSockSet = xSockSet;
for (BaseType_t i = 0; i < pxServerCfg->uxNumProtocols; i++)
{
if (prvCreateProtocolServer(&pxNewServer->pxProtocols[i],
&pxServerCfg->pxProtocols[i]) == pdTRUE)
{
xSock = pxNewServer->pxProtocols[i].xSock;
pxNewServer->pxProtocols[i].pxParent = pxNewServer;
// TODO: need to specify the network interface, not just get the first one!
xSockAddr.sin_address.ulIP_IPv4 = FreeRTOS_GetIPAddress();
xSockAddr.sin_port = FreeRTOS_htons(pxServerCfg->pxProtocols[i].xPortNum);
xSockAddr.sin_family = FREERTOS_AF_INET;
FreeRTOS_bind(xSock, &xSockAddr, sizeof(xSockAddr));
FreeRTOS_listen(xSock, pxServerCfg->pxProtocols[i].xBacklog);
FreeRTOS_setsockopt(xSock, 0, FREERTOS_SO_RCVTIMEO, (void *)&xNoTimeout,
sizeof(xNoTimeout));
FreeRTOS_setsockopt(xSock, 0, FREERTOS_SO_SNDTIMEO, (void *)&xNoTimeout,
sizeof(xNoTimeout));
FreeRTOS_FD_SET(xSock, xSockSet, eSELECT_READ | eSELECT_EXCEPT);
}
}
pxNewServer->uxNumProtocols = pxServerCfg->uxNumProtocols;
pxNewServer->pcRcvBuff[0] = 0;
pxNewServer->xClientMutex = xSemaphoreCreateMutex();
return pxNewServer;
}
static BaseType_t prvCreateProtocolServer(
WebProtoServer_t *pxProto,
const WebProtoConfig_t *pxProtoCfg)
{
memset(pxProto, 0, sizeof(pxProto));
Socket_t xSock = FreeRTOS_socket(FREERTOS_AF_INET, FREERTOS_SOCK_STREAM,
FREERTOS_IPPROTO_TCP);
if (!xSock)
return pdFALSE;
pxProto->pcRootDir = pxProtoCfg->pcRootDir;
pxProto->xSock = xSock;
pxProto->uxClientSz = pxProtoCfg->uxClientSz;
pxProto->xCreator = pxProtoCfg->xCreator;
pxProto->xWorker = pxProtoCfg->xWorker;
pxProto->xDelete = pxProtoCfg->xDelete;
return pdTRUE;
}
static void prvTCPServerWork(void)
{
TCPClient_t *currClient;
BaseType_t xRc;
if (!xEmber.xReady || !xEmber.pxServer)
return;
// check for new connections/clients
xRc = FreeRTOS_select(xEmber.pxServer->xSockSet, xEmber.uxPeriod);
if (xRc != 0)
{
for (BaseType_t i = 0; i < xEmber.pxServer->uxNumProtocols; i++)
{
struct freertos_sockaddr sockAddr;
Socket_t newSock;
socklen_t newSockLen = sizeof(sockAddr);
WebProtoServer_t *currProto = &xEmber.pxServer->pxProtocols[i];
if (currProto->xSock == FREERTOS_NO_SOCKET)
continue;
newSock = FreeRTOS_accept(currProto->xSock, &sockAddr, &newSockLen);
if (newSock != FREERTOS_INVALID_SOCKET && newSock != FREERTOS_NO_SOCKET)
prvAcceptNewClient(currProto, newSock);
}
}
// service existing connections/clients
currClient = xEmber.pxServer->pxClients;
while (currClient)
{
BaseType_t sockLive = FreeRTOS_issocketconnected(currClient->xSock);
if (sockLive == pdTRUE)
{
xRc = currClient->xWork(currClient);
if (xRc < 0)
currClient = prvRemoveClient(currClient);
else
currClient = currClient->pxNextClient;
}
else
{
currClient = prvRemoveClient(currClient);
}
}
}
static void prvAcceptNewClient(WebProtoServer_t *pxProto, Socket_t xNewSock)
{
xSemaphoreTake(xEmber.pxServer->xClientMutex, portMAX_DELAY);
TCPClient_t *newClient = 0;
// (try to) malloc enough space for a suitable new TCP client struct
newClient = (TCPClient_t *)pvPortMalloc(pxProto->uxClientSz);
if (!newClient)
{
FreeRTOS_closesocket(xNewSock);
xSemaphoreGive(xEmber.pxServer->xClientMutex);
return;
}
memset(newClient, 0, pxProto->uxClientSz);
newClient->pxParent = pxProto->pxParent;
newClient->xSock = xNewSock;
newClient->xCreator = pxProto->xCreator;
newClient->xWork = pxProto->xWorker;
newClient->xDelete = pxProto->xDelete;
// try to create the new client; if this fails, delete it and ditch
if (newClient->xCreator && newClient->xCreator(newClient) != 0)
{
FreeRTOS_closesocket(xNewSock);
vPortFree(newClient);
xSemaphoreGive(xEmber.pxServer->xClientMutex);
return;
}
// the new client will be the head of the linked list
newClient->pxPrevClient = 0;
newClient->pxNextClient = xEmber.pxServer->pxClients;
if (newClient->pxNextClient)
newClient->pxNextClient->pxPrevClient = newClient;
xEmber.pxServer->pxClients = newClient;
// add the client socket to the server's socketset
FreeRTOS_FD_SET(xNewSock, xEmber.pxServer->xSockSet,
eSELECT_READ | eSELECT_EXCEPT);
xSemaphoreGive(xEmber.pxServer->xClientMutex);
}
static TCPClient_t *prvRemoveClient(TCPClient_t *pxClient)
{
if (!pxClient)
return 0;
xSemaphoreTake(xEmber.pxServer->xClientMutex, portMAX_DELAY);
TCPClient_t *pxNextClient = pxClient->pxNextClient;
prvDropClient(pxClient);
vPortFree(pxClient);
xSemaphoreGive(xEmber.pxServer->xClientMutex);
return pxNextClient;
}
static TCPClient_t *prvDropClient(TCPClient_t *pxClient)
{
TCPClient_t *pxPrevClient = pxClient->pxPrevClient;
TCPClient_t *pxNextClient = pxClient->pxNextClient;
// close any system resources used by the client (file handles, typically)
if (pxClient->xDelete)
pxClient->xDelete(pxClient);
// close the client's socket
if (pxClient->xSock != FREERTOS_NO_SOCKET)
{
FreeRTOS_FD_CLR(pxClient->xSock, xEmber.pxServer->xSockSet, eSELECT_ALL);
FreeRTOS_closesocket(pxClient->xSock);
pxClient->xSock = FREERTOS_NO_SOCKET;
}
// unlink the target client from the list
if (pxPrevClient)
pxPrevClient->pxNextClient = pxNextClient;
if (pxNextClient)
pxNextClient->pxPrevClient = pxPrevClient;
// if the target client was the head of the list, point the head at the next entry
// (which might be NULL)
if (pxClient == pxClient->pxParent->pxClients)
pxClient->pxParent->pxClients = pxNextClient;
} |
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
class ExpenceBookRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
public function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json([
'success' => false,
'message' => 'Validation errors',
'data' => $validator->errors()
]));
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|string|max:50',
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
];
}
public function messages()
{
return [
'name.required' => 'Name is required!',
'image.required' => 'Image is required!'
];
}
} |
interface Person3 {
name: string;
age: number;
}
const person3: Person3[] = [
{ name: 'min', age: 31 },
{ name: 'woo', age: 31 },
];
//타입 체크를 하지 않는 함수.
function filterBy<T>(property: any, value: any, array: T[]) {
//프로퍼티와 값을 기반으로 데이터를 필터링 한다.
return array.filter(item => item[property] === value);
}
console.log(filterBy('name', 'min', person3)); //올바른 함수 호출
console.log(filterBy('lastName', 'woo', person3)); //잘못된 함수 호출(lastName은 없음)
console.log(filterBy('age', 'kkk', person3)); //잘못된 함수 호출(age는 number인데 string을 넘김) |
package Services;
import dataAccess.DAO.AuthtokenDAO;
import dataAccess.DAO.GameDAO;
import Requests.JoinGameRequest;
import Results.JoinGameResult;
import dataAccess.DataAccessException;
//import dataAccess.Database;
import dataAccess.DatabaseManager;
import java.sql.Connection;
import java.sql.SQLException;
/**
* A service to handle the logic for the join game operation.
*/
public class JoinGameService {
/**
* Makes a user join a game.
* @param joinGameRequest The information required to join a game.
* @param authtoken The authoke of the signed-in user.
* @return A JoinGameResult object containing the results of the joinGame operation.
*/
public JoinGameResult Execute(JoinGameRequest joinGameRequest, String authtoken){
JoinGameResult joinGameResult = new JoinGameResult();
//DatabaseManager db = new DatabaseManager();
try (Connection conn = DatabaseManager.getConnection()) {
AuthtokenDAO authtokenDAO = new AuthtokenDAO(conn);
GameDAO gameDAO = new GameDAO(conn);
if (authtokenDAO.Find(authtoken) == null) {
joinGameResult.setSuccess(false);
joinGameResult.setMessage("Error: Unauthorized.");
//db.closeConnection(db.getConnection());
return joinGameResult;
}
if (gameDAO.Find(joinGameRequest.getGameID()) == null) {
joinGameResult.setSuccess(false);
joinGameResult.setMessage("Error: Bad request.");
//db.closeConnection(db.getConnection());
return joinGameResult;
}
if (joinGameRequest.getPlayerColor() != null) {
boolean claimedSpot = gameDAO.claimSpot(joinGameRequest.getGameID(), joinGameRequest.getPlayerColor(), authtokenDAO.Find(authtoken).getUsername());
if (!claimedSpot) {
joinGameResult.setSuccess(false);
joinGameResult.setMessage("Error: Already taken.");
//db.closeConnection(db.getConnection());
return joinGameResult;
}
}
//db.closeConnection(db.getConnection());
joinGameResult.setSuccess(true);
joinGameResult.setMessage("Joined game successfully.");
} catch (DataAccessException | SQLException e) {
e.printStackTrace();
joinGameResult.setMessage("Error in joining game.");
}
return joinGameResult;
}
} |
import random
from dataclasses import dataclass
from pathlib import Path
from abc import ABC, abstractmethod
from typing import Tuple, Any, List, Union
from joblib import Memory
from termcolor import colored
from openai.openai_object import OpenAIObject
cur_file = Path(__file__).parent.absolute()
import openai
@dataclass(frozen=True)
class LmPrompt:
text: str
max_toks: int
stop: List[str] = None
logprobs: int = None
temperature: float = 1.0
top_p: float = 0.9,
presence_penalty: float = 0.0
@dataclass
class LmPrediction:
text: str
metad: Any
class LmPredictor:
@abstractmethod
def predict(
self,
prompt: Union[str, LmPrompt],
) -> LmPrediction:
pass
def _cast_prompt(self, prompt: Union[str, LmPrompt]) -> LmPrompt:
if isinstance(prompt, str):
return LmPrompt(prompt, 100)
return prompt
def model_name(self):
return self.__class__.__name__
cachedir = 'autoregressive_prompt_model_cache'
diskcache = Memory(cachedir, verbose=0)
class OpenAIPredictor(LmPredictor):
def __init__(
self,
api,
engine_name: str,
cache_outputs: bool = True,
):
if not cache_outputs:
raise NotImplementedError
self._api = api
self._engine_name = engine_name
self._cache_outputs = cache_outputs
def model_name(self):
return self._engine_name
def predict(
self,
prompt: Union[str, LmPrompt],
) -> LmPrediction:
prompt = self._cast_prompt(prompt)
return _openai_cache_prediction(self._api, self._engine_name, prompt)
@diskcache.cache(ignore=['api'], verbose=0)
def _openai_cache_prediction(
api,
engine_name,
prompt,
):
print("PREDICT", prompt)
completion = api.Completion.create(
engine=engine_name,
prompt=prompt.text,
max_tokens=prompt.max_toks,
stop=prompt.stop,
stream=False,
logprobs=prompt.logprobs,
temperature=prompt.temperature,
top_p=prompt.top_p,
presence_penalty=prompt.presence_penalty,
)
if random.random() < 0.05:
print("PREDICT", "\n" + colored(prompt.text, 'blue'))
print("GOT", colored(completion.choices[0].text, 'green'))
return LmPrediction(completion.choices[0].text, completion)
class FoobarPredictor(LmPredictor):
def __init__(
self,
):
pass
def predict(
self,
prompt: Union[str, LmPrompt],
) -> LmPrediction:
prompt = self._cast_prompt(prompt)
print("PREDICT", colored(prompt.text, 'blue'))
return LmPrediction("Foobar", None)
def get_goose_lm(
model_name: str = "gpt-neo-125m",
):
import openai
openai.api_key = Path("~/goose_key.txt").expanduser().read_text().strip()
openai.api_base = "https://api.goose.ai/v1"
return OpenAIPredictor(
api=openai,
engine_name=model_name,
)
def get_open_ai_lm(
model_name: str = "gpt-neo-125m",
):
import openai
openai.api_key = Path("~/oai_key.txt").expanduser().read_text().strip()
return OpenAIPredictor(
api=openai,
engine_name=model_name,
)
# List Engines (Models)
#engines = openai.Engine.list()
## Print all engines IDs
#for engine in engines.data:
# print(engine.id)
#print(engines)
#return OpenAIPredictor("gpt-j-6b")
# Create a completion, return results streaming as they are generated. Run with `python3 -u` to ensure unbuffered output.
#completion = openai.Completion.create(
# engine="gpt-j-6b",
# prompt="Once upon a time there was a Goose. ",
# max_tokens=160,
# stream=False
#)
## Print each token as it is returned
#for c in completion:
# print(c.choices[0].text, end='')
#print("")
def main():
lm = get_goose_lm()
text = lm.predict(
LmPrompt(
"Once upon a time there was a Goose. And",
max_toks=1, logprobs=10,
))
#print(type(text))
print(text.text)
text = lm.predict(
LmPrompt(
"Once upon a time there was a Goose. And",
max_toks=1, logprobs=10,
))
#print(type(text))
print(text.text)
if __name__ == "__main__":
main() |
package com.recipe.service;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.recipe.entity.Recipe;
import com.recipe.entity.RecipeIngre;
import com.recipe.entity.RecipeOrder;
import com.recipe.repository.RecipeIngreRepository;
import com.recipe.repository.RecipeOrderRepository;
import com.recipe.repository.RecipeRepository;
import lombok.RequiredArgsConstructor;
import java.io.IOException;
@Service
@RequiredArgsConstructor
@Transactional
public class RecipeCrawlerService {
@Autowired
private final RecipeRepository recipeRepository;
private final RecipeIngreRepository recipeIngreRepository;
private final RecipeOrderRepository recipeOrderRepository;
int count = 0;
public void crawlAndSaveRecipes() throws IOException {
String url = "https://wtable.co.kr/recipes";
Document doc = Jsoup.connect(url).get();
Elements recipes = doc.select("a:has(.erZvWP)");
for (Element recipe : recipes) {
String subTitle = recipe.select(".LxJcT").text();
String title = recipe.select(".hpYiJK").text();
String imageUrl = recipe.select(".duQJWI").attr("src");
String words = recipe.select(".MiXMV").text();
String level = words.split(" ")[0];
String time = words.split(" ")[1];
Recipe recipeObject = new Recipe();
recipeObject.setSubTitle(subTitle);
recipeObject.setTitle(title);
recipeObject.setImageUrl(imageUrl);
recipeObject.setLevel(level);
recipeObject.setDurTime(time);
recipeRepository.save(recipeObject);
crawlAndSaveDetailPage(recipeObject, recipe.select("a").attr("href"));
}
}
private void crawlAndSaveDetailPage(Recipe recipeObject, String detailUrl) throws IOException {
if (!detailUrl.startsWith("http://")) {
detailUrl = "https://wtable.co.kr" + detailUrl;
}
Document detailDoc = Jsoup.connect(detailUrl).get();
String description = detailDoc.select(".IdQIJ").text();
String intro = detailDoc.select(".ksodYd").text();
String IngreImg = detailDoc.selectFirst(".ingredient").select("img").attr("src");
Element parentElement = detailDoc.selectFirst(".igroups");
Elements basicIngres = parentElement.select("ul > li:first-child > ul li");
Elements seasonIngres = parentElement.select("ul > li:last-child > ul li");
count++;
//조리순서 저장
Elements recipeOrderDivs = detailDoc.select(".ihCzrN");
for(Element recipeOrderDiv : recipeOrderDivs) {
String imgSrc = recipeOrderDiv.select("img").attr("src");
String ex = recipeOrderDiv.select(".enJPxd").text();
RecipeOrder recipeOrder = new RecipeOrder();
recipeOrder.setOrderNumber(count);
recipeOrder.setImgUrl(imgSrc);
recipeOrder.setContent(ex);
recipeOrderRepository.save(recipeOrder);
}
RecipeIngre recipeIngre;
// 기본 재료 저장
for (Element basic_ingre : basicIngres) {
recipeIngre = new RecipeIngre();
String ingre = basic_ingre.text();
recipeIngre.setIngreImg(IngreImg);
recipeIngre.setRecipeCount(count);
recipeIngre.setBasicIngreName(ingre);
recipeIngre.setRecipe(recipeObject);
recipeIngreRepository.save(recipeIngre);
}
//중복된 데이터 판별
if(!seasonIngres.equals(basicIngres)) {
// 양념 재료 저장
for (Element season_ingre : seasonIngres) {
recipeIngre = new RecipeIngre();
String ingre = season_ingre.text();
recipeIngre.setRecipeCount(count);
recipeIngre.setSeasonIngreName(ingre);
recipeIngre.setRecipe(recipeObject);
recipeIngreRepository.save(recipeIngre);
}
}
recipeObject.setDescription(description);
recipeObject.setIntro(intro);
// 완성된 Recipe 객체 저장
recipeRepository.save(recipeObject);
}
} |
package program;
import java.util.ArrayList;
import java.util.List;
public class _1208 {
public static void main(String[] args) {
Solution solution = new Solution();
int res = solution.equalSubstring("krrgw", "zjxss", 19);
System.out.println(res);
}
public static class Solution {
//方法1.滑动窗口模板
public int equalSubstring(String s, String t, int maxCost) {
int l = 0, r = 0; //区间内左指针,区间内右指针
int N = s.length();
int max = 0; //记录最大长度
int sum = 0; //记录当前区间内差值和
while(r < N){ //r的右指针右移,r指针占移动主导,拖动着l右移
sum += Math.abs(s.charAt(r) - t.charAt(r)); //计算当前区间内差值和sum
while(sum > maxCost){ //当差值和大于maxCost时,左指针右移
sum -= Math.abs(s.charAt(l) - t.charAt(l)); //sum减去之前加上的差值和
l++;
}
max = Math.max(max, r - l + 1); //如果区间差值和合理,更新最大长度
r++; //r右移
}
return max;
}
}
} |
textops Module
Andrei Pelinescu-Onciul
FhG FOKUS
<pelinescu-onciul@fokus.fraunhofer.de>
Edited by
Andrei Pelinescu-Onciul
<pelinescu-onciul@fokus.fraunhofer.de>
Edited by
Daniel-Constantin Mierla
<miconda@gmail.com>
Edited by
Juha Heinanen
<jh@tutpro.com>
Copyright © 2003 FhG FOKUS
__________________________________________________________________
Table of Contents
1. Admin Guide
1. Overview
1.1. Known Limitations
2. Dependencies
2.1. Kamailio Modules
2.2. External Libraries or Applications
3. Functions
3.1. search(re)
3.2. search_body(re)
3.3. search_hf(hf, re, flags)
3.4. search_append(re, txt)
3.5. search_append_body(re, txt)
3.6. replace(re, txt)
3.7. replace_body(re, txt)
3.8. replace_all(re, txt)
3.9. replace_body_all(re, txt)
3.10. replace_body_atonce(re, txt)
3.11. subst('/re/repl/flags')
3.12. subst_uri('/re/repl/flags')
3.13. subst_user('/re/repl/flags')
3.14. subst_body('/re/repl/flags')
3.15. subst_hf(hf, subexp, flags)
3.16. set_body(txt,content_type)
3.17. set_reply_body(txt,content_type)
3.18. filter_body(content_type)
3.19. append_to_reply(txt)
3.20. append_hf(txt[, hdr])
3.21. insert_hf(txt[, hdr])
3.22. append_urihf(prefix, suffix)
3.23. is_present_hf(hf_name)
3.24. is_present_hf_re(hf_name_re)
3.25. append_time()
3.26. append_time_to_request()
3.27. is_method(name)
3.28. remove_hf(hname)
3.29. remove_hf_re(re)
3.30. has_body(), has_body(mime)
3.31. is_audio_on_hold()
3.32. is_privacy(privacy_type)
3.33. in_list(subject, list, separator)
3.34. cmp_str(str1, str2)
3.35. cmp_istr(str1, str2)
3.36. starts_with(str1, str2)
3.37. set_body_multipart([txt,content_type][,boundary])
3.38. append_body_part(txt,content_type[,
content_disposition])
3.39. remove_body_part(content_type)
4. Known Limitations
2. Developer Guide
1. Functions
1.1. load_textops(*import_structure)
List of Examples
1.1. search usage
1.2. search_body usage
1.3. search_hf usage
1.4. search_append usage
1.5. search_append_body usage
1.6. replace usage
1.7. replace_body usage
1.8. replace_all usage
1.9. replace_body_all usage
1.10. replace_body_atonce usage
1.11. subst usage
1.12. subst_uri usage
1.13. subst usage
1.14. subst_body usage
1.15. subst_hf usage
1.16. set_body usage
1.17. set_reply_body usage
1.18. filter_body usage
1.19. append_to_reply usage
1.20. append_hf usage
1.21. insert_hf usage
1.22. append_urihf usage
1.23. is_present_hf usage
1.24. is_present_hf_re usage
1.25. append_time usage
1.26. append_time_to_request usage
1.27. is_method usage
1.28. remove_hf usage
1.29. remove_hf_re usage
1.30. has_body usage
1.31. is_audio_on_hold usage
1.32. is_privacy usage
1.33. in_list() usage
1.34. cmp_str usage
1.35. cmp_str usage
1.36. starts_with usage
1.37. set_body_multipart usage
1.38. append_body_part usage
1.39. remove_body_part usage
Chapter 1. Admin Guide
Table of Contents
1. Overview
1.1. Known Limitations
2. Dependencies
2.1. Kamailio Modules
2.2. External Libraries or Applications
3. Functions
3.1. search(re)
3.2. search_body(re)
3.3. search_hf(hf, re, flags)
3.4. search_append(re, txt)
3.5. search_append_body(re, txt)
3.6. replace(re, txt)
3.7. replace_body(re, txt)
3.8. replace_all(re, txt)
3.9. replace_body_all(re, txt)
3.10. replace_body_atonce(re, txt)
3.11. subst('/re/repl/flags')
3.12. subst_uri('/re/repl/flags')
3.13. subst_user('/re/repl/flags')
3.14. subst_body('/re/repl/flags')
3.15. subst_hf(hf, subexp, flags)
3.16. set_body(txt,content_type)
3.17. set_reply_body(txt,content_type)
3.18. filter_body(content_type)
3.19. append_to_reply(txt)
3.20. append_hf(txt[, hdr])
3.21. insert_hf(txt[, hdr])
3.22. append_urihf(prefix, suffix)
3.23. is_present_hf(hf_name)
3.24. is_present_hf_re(hf_name_re)
3.25. append_time()
3.26. append_time_to_request()
3.27. is_method(name)
3.28. remove_hf(hname)
3.29. remove_hf_re(re)
3.30. has_body(), has_body(mime)
3.31. is_audio_on_hold()
3.32. is_privacy(privacy_type)
3.33. in_list(subject, list, separator)
3.34. cmp_str(str1, str2)
3.35. cmp_istr(str1, str2)
3.36. starts_with(str1, str2)
3.37. set_body_multipart([txt,content_type][,boundary])
3.38. append_body_part(txt,content_type[, content_disposition])
3.39. remove_body_part(content_type)
4. Known Limitations
1. Overview
1.1. Known Limitations
The module implements text based operations over the SIP message
processed by Kamailio. SIP is a text based protocol and the module
provides a large set of very useful functions to manipulate the message
at text level, e.g., regular expression search and replace, Perl-like
substitutions, checks for method type, header presence, insert of new
header and date, etc.
1.1. Known Limitations
search ignores folded lines. For example, search(“(From|f):.*@foo.bar”)
doesn't match the following From header field:
From: medabeda
<sip:medameda@foo.bar>;tag=1234
2. Dependencies
2.1. Kamailio Modules
2.2. External Libraries or Applications
2.1. Kamailio Modules
The following modules must be loaded before this module:
* No dependencies on other Kamailio modules.
2.2. External Libraries or Applications
The following libraries or applications must be installed before
running Kamailio with this module loaded:
* None.
3. Functions
3.1. search(re)
3.2. search_body(re)
3.3. search_hf(hf, re, flags)
3.4. search_append(re, txt)
3.5. search_append_body(re, txt)
3.6. replace(re, txt)
3.7. replace_body(re, txt)
3.8. replace_all(re, txt)
3.9. replace_body_all(re, txt)
3.10. replace_body_atonce(re, txt)
3.11. subst('/re/repl/flags')
3.12. subst_uri('/re/repl/flags')
3.13. subst_user('/re/repl/flags')
3.14. subst_body('/re/repl/flags')
3.15. subst_hf(hf, subexp, flags)
3.16. set_body(txt,content_type)
3.17. set_reply_body(txt,content_type)
3.18. filter_body(content_type)
3.19. append_to_reply(txt)
3.20. append_hf(txt[, hdr])
3.21. insert_hf(txt[, hdr])
3.22. append_urihf(prefix, suffix)
3.23. is_present_hf(hf_name)
3.24. is_present_hf_re(hf_name_re)
3.25. append_time()
3.26. append_time_to_request()
3.27. is_method(name)
3.28. remove_hf(hname)
3.29. remove_hf_re(re)
3.30. has_body(), has_body(mime)
3.31. is_audio_on_hold()
3.32. is_privacy(privacy_type)
3.33. in_list(subject, list, separator)
3.34. cmp_str(str1, str2)
3.35. cmp_istr(str1, str2)
3.36. starts_with(str1, str2)
3.37. set_body_multipart([txt,content_type][,boundary])
3.38. append_body_part(txt,content_type[, content_disposition])
3.39. remove_body_part(content_type)
3.1. search(re)
Searches for the re in the message.
Meaning of the parameters is as follows:
* re - Regular expression.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.1. search usage
...
if ( search("[Ss][Ii][Pp]") ) { /*....*/ };
...
3.2. search_body(re)
Searches for the re in the body of the message.
Meaning of the parameters is as follows:
* re - Regular expression.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.2. search_body usage
...
if ( search_body("[Ss][Ii][Pp]") ) { /*....*/ };
...
3.3. search_hf(hf, re, flags)
Searches for the re in the body of a header field.
Meaning of the parameters is as follows:
* hf - header field name.
* re - regular expression.
* flags - control flags - it has to be one of: a - all headers
matching the name; f - only first header matching the name; l -
only the last header matching the name.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.3. search_hf usage
...
if ( search_hf("From", ":test@", "a") ) { /*....*/ };
...
3.4. search_append(re, txt)
Searches for the first match of re and appends txt after it.
Meaning of the parameters is as follows:
* re - Regular expression.
* txt - String to be appended.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.4. search_append usage
...
search_append("[Oo]pen[Ss]er", " SIP Proxy");
...
3.5. search_append_body(re, txt)
Searches for the first match of re in the body of the message and
appends txt after it.
Meaning of the parameters is as follows:
* re - Regular expression.
* txt - String to be appended.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.5. search_append_body usage
...
search_append_body("[Oo]pen[Ss]er", " SIP Proxy");
...
3.6. replace(re, txt)
Replaces the first occurrence of re with txt.
Meaning of the parameters is as follows:
* re - Regular expression.
* txt - String.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.6. replace usage
...
replace("openser", "Kamailio SIP Proxy");
...
3.7. replace_body(re, txt)
Replaces the first occurrence of re in the body of the message with
txt.
Meaning of the parameters is as follows:
* re - Regular expression.
* txt - String.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.7. replace_body usage
...
replace_body("openser", "Kamailio SIP Proxy");
...
3.8. replace_all(re, txt)
Replaces all occurrence of re with txt.
Meaning of the parameters is as follows:
* re - Regular expression.
* txt - String.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.8. replace_all usage
...
replace_all("openser", "Kamailio SIP Proxy");
...
3.9. replace_body_all(re, txt)
Replaces all occurrence of re in the body of the message with txt.
Matching is done on a per-line basis.
Meaning of the parameters is as follows:
* re - Regular expression.
* txt - String.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.9. replace_body_all usage
...
replace_body_all("openser", "Kamailio SIP Proxy");
...
3.10. replace_body_atonce(re, txt)
Replaces all occurrence of re in the body of the message with txt.
Matching is done over the whole body.
Meaning of the parameters is as follows:
* re - Regular expression.
* txt - String.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.10. replace_body_atonce usage
...
# strip the whole body from the message:
if(has_body() && replace_body_atonce("^.+$", ""))
remove_hf("Content-Type");
...
3.11. subst('/re/repl/flags')
Replaces re with repl (sed or perl like).
Meaning of the parameters is as follows:
* '/re/repl/flags' - sed like regular expression. flags can be a
combination of i (case insensitive), g (global) or s (match newline
don't treat it as end of line).
're' - is regular expresion
'repl' - is replacement string - may contain pseudo-varibales
'flags' - substitution flags (i - ignore case, g - global)
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.11. subst usage
...
# replace the uri in to: with the message uri (just an example)
if ( subst('/^To:(.*)sip:[^@]*@[a-zA-Z0-9.]+(.*)$/t:\1\u\2/ig') ) {};
# replace the uri in to: with the value of avp sip_address (just an example)
if ( subst('/^To:(.*)sip:[^@]*@[a-zA-Z0-9.]+(.*)$/t:\1$avp(sip_address)\2/ig')
) {};
...
3.12. subst_uri('/re/repl/flags')
Runs the re substitution on the message uri (like subst but works only
on the uri)
Meaning of the parameters is as follows:
* '/re/repl/flags' - sed like regular expression. flags can be a
combination of i (case insensitive), g (global) or s (match newline
don't treat it as end of line).
're' - is regular expresion
'repl' - is replacement string - may contain pseudo-varibales
'flags' - substitution flags (i - ignore case, g - global)
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.12. subst_uri usage
...
# adds 3463 prefix to numeric uris, and save the original uri (\0 match)
# as a parameter: orig_uri (just an example)
if (subst_uri('/^sip:([0-9]+)@(.*)$/sip:3463\1@\2;orig_uri=\0/i')){$
# adds the avp 'uri_prefix' as prefix to numeric uris, and save the original
# uri (\0 match) as a parameter: orig_uri (just an example)
if (subst_uri('/^sip:([0-9]+)@(.*)$/sip:$avp(uri_prefix)\1@\2;orig_uri=\0/i')){
$
...
3.13. subst_user('/re/repl/flags')
Runs the re substitution on the message uri (like subst_uri but works
only on the user portion of the uri)
Meaning of the parameters is as follows:
* '/re/repl/flags' - sed like regular expression. flags can be a
combination of i (case insensitive), g (global) or s (match newline
don't treat it as end of line).
're' - is regular expresion
'repl' - is replacement string - may contain pseudo-varibales
'flags' - substitution flags (i - ignore case, g - global)
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.13. subst usage
...
# adds 3463 prefix to uris ending with 3642 (just an example)
if (subst_user('/3642$/36423463/')){$
...
# adds avp 'user_prefix' as prefix to username in r-uri ending with 3642
if (subst_user('/(.*)3642$/$avp(user_prefix)\13642/')){$
...
3.14. subst_body('/re/repl/flags')
Replaces re with repl (sed or perl like) in the body of the message.
Meaning of the parameters is as follows:
* '/re/repl/flags' - sed like regular expression. flags can be a
combination of i (case insensitive), g (global) or s (match newline
don't treat it as end of line).
're' - is regular expresion
'repl' - is replacement string - may contain pseudo-varibales
'flags' - substitution flags (i - ignore case, g - global)
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.14. subst_body usage
...
if ( subst_body('/^o=(.*) /o=$fU /') ) {};
...
3.15. subst_hf(hf, subexp, flags)
Perl-like substitutions in the body of a header field.
Meaning of the parameters is as follows:
* hf - header field name.
* subexp - substitution expression in the same format as of the
'subst' function parameter.
* flags - control flags - it has to be one of: a - all headers
matching the name; f - only first header matching the name; l -
only the last header matching the name.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.15. subst_hf usage
...
if ( subst_hf("From", "/:test@/:best@/", "a") ) { /*....*/ };
...
3.16. set_body(txt,content_type)
Set body to a SIP message.
Meaning of the parameters is as follows:
* txt - text for the body, can include pseudo-variables.
* content_type - value of Content-Type header, can include
pseudo-variables.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.16. set_body usage
...
set_body("test", "text/plain");
...
3.17. set_reply_body(txt,content_type)
Set body to a SIP reply to be generated by Kamailio.
Meaning of the parameters is as follows:
* txt - text for the body, can include pseudo-variables.
* content_type - value of Content-Type header, can include
pseudo-variables.
This function can be used from REQUEST_ROUTE, FAILURE_ROUTE,
BRANCH_ROUTE.
Example 1.17. set_reply_body usage
...
set_reply_body("test", "text/plain");
...
3.18. filter_body(content_type)
Filters multipart/mixed body by leaving out all other body parts except
the first body part of given type.
Meaning of the parameters is as follows:
* content_type - Content type to be left in the body.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.18. filter_body usage
...
if (has_body("multipart/mixed")) {
if (filter_body("application/sdp") {
remove_hf("Content-Type");
append_hf("Content-Type: application/sdp\r\n");
} else {
xlog("Body part application/sdp not found\n");
}
}
...
3.19. append_to_reply(txt)
Append txt as header to the reply.
Meaning of the parameters is as follows:
* txt - String which may contains pseudo-variables.
This function can be used from REQUEST_ROUTE, BRANCH_ROUTE,
FAILURE_ROUTE, ERROR_ROUTE.
Example 1.19. append_to_reply usage
...
append_to_reply("Foo: bar\r\n");
append_to_reply("Foo: $rm at $Ts\r\n");
...
3.20. append_hf(txt[, hdr])
Appends 'txt' as header after first header field or after last 'hdr'
header field.
Meaning of the parameters is as follows:
* txt - Header field to be appended. The value can contain
pseudo-variables which will be replaced at run time.
* hdr - Header name after which the 'txt' is appended.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.20. append_hf usage
...
append_hf("P-hint: VOICEMAIL\r\n");
append_hf("From-username: $fU\r\n", "Call-ID");
...
3.21. insert_hf(txt[, hdr])
Inserts 'txt' as header before the first header field or before first
'hdr' header field if 'hdr' is given.
Meaning of the parameters is as follows:
* txt - Header field to be inserted. The value can contain
pseudo-variables which will be replaced at run time.
* hdr - Header name before which the 'txt' is inserted.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.21. insert_hf usage
...
insert_hf("P-hint: VOICEMAIL\r\n");
insert_hf("To-username: $tU\r\n");
insert_hf("P-hint: VOICEMAIL\r\n", "Call-ID");
insert_hf("To-username: $tU\r\n", "Call-ID");
...
3.22. append_urihf(prefix, suffix)
Append header field name with original Request-URI in middle.
Meaning of the parameters is as follows:
* prefix - string (usually at least header field name).
* suffix - string (usually at least line terminator).
This function can be used from REQUEST_ROUTE, FAILURE_ROUTE,
BRANCH_ROUTE.
Example 1.22. append_urihf usage
...
append_urihf("CC-Diversion: ", "\r\n");
...
3.23. is_present_hf(hf_name)
Return true if a header field is present in message.
Note
The function is also able to distinguish the compact names. For exmaple
“From” will match with “f”
Meaning of the parameters is as follows:
* hf_name - Header field name.(long or compact form)
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.23. is_present_hf usage
...
if (is_present_hf("From")) log(1, "From HF Present");
...
3.24. is_present_hf_re(hf_name_re)
Return true if a header field whose name matches regular expression
'hf_name_re' is present in message.
Meaning of the parameters is as follows:
* hf_name_re - Regular expression to match header field name.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.24. is_present_hf_re usage
...
if (is_present_hf_re("^P-")) log(1, "There are headers starting with P-\n");
...
3.25. append_time()
Adds a time header to the reply of the request. You must use it before
functions that are likely to send a reply, e.g., save() from
'registrar' module. Header format is: “Date: %a, %d %b %Y %H:%M:%S
GMT”, with the legend:
* %a abbreviated week of day name (locale)
* %d day of month as decimal number
* %b abbreviated month name (locale)
* %Y year with century
* %H hour
* %M minutes
* %S seconds
Return true if a header was succesfully appended.
This function can be used from REQUEST_ROUTE, FAILURE_ROUTE,
BRANCH_ROUTE.
Example 1.25. append_time usage
...
append_time();
...
3.26. append_time_to_request()
Adds a time header to the request. Header format is: “Date: %a, %d %b
%Y %H:%M:%S GMT”, with the legend:
* %a abbreviated week of day name (locale)
* %d day of month as decimal number
* %b abbreviated month name (locale)
* %Y year with century
* %H hour
* %M minutes
* %S seconds
Return true if a header was succesfully appended.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, BRANCH_ROUTE.
Example 1.26. append_time_to_request usage
...
if(!is_present_hf("Date"))
append_time_to_request();
...
3.27. is_method(name)
Check if the method of the message matches the name. If name is a known
method (invite, cancel, ack, bye, options, info, update, register,
message, subscribe, notify, refer, prack), the function performs method
ID testing (integer comparison) instead of ignore case string
comparison.
The 'name' can be a list of methods in the form of
'method1|method2|...'. In this case, the function returns true if the
SIP message's method is one from the list. IMPORTANT NOTE: in the list
must be only methods defined in Kamailio with ID (invite, cancel, ack,
bye, options, info, update, register, message, subscribe, notify,
refer, prack, publish; for more see:
http://www.iana.org/assignments/sip-parameters).
If used for replies, the function tests the value of method field from
CSeq header.
Meaning of the parameters is as follows:
* name - SIP method name
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE, and BRANCH_ROUTE.
Example 1.27. is_method usage
...
if(is_method("INVITE"))
{
# process INVITEs here
}
if(is_method("OPTION|UPDATE"))
{
# process OPTIONs and UPDATEs here
}
...
3.28. remove_hf(hname)
Remove from message all headers with name “hname”. Header matching is
case-insensitive. Matches and removes also the compact header forms.
Returns true if at least one header is found and removed.
Meaning of the parameters is as follows:
* hname - header name to be removed.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE and BRANCH_ROUTE.
Example 1.28. remove_hf usage
...
if(remove_hf("User-Agent"))
{
# User Agent header removed
}
# compact form: remove "Contact" or "m" header
remove_hf("Contact")
# compact form: remove "Contact" or "m" header
remove_hf("m")
...
3.29. remove_hf_re(re)
Remove from message all headers with name matching regular expression
“re”
Returns true if at least one header is found and removed.
Meaning of the parameters is as follows:
* re - regular expression to match the header name to be removed.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE and BRANCH_ROUTE.
Example 1.29. remove_hf_re usage
...
if(remove_hf_re("^P-"))
{
# All headers starting with "P-" removed
}
...
3.30. has_body(), has_body(mime)
The function returns true if the SIP message has a body attached. The
checked includes also the “Content-Length” header presence and value.
If a parameter is given, the mime described will be also checked
against the “Content-Type” header.
Meaning of the parameters is as follows:
* mime - mime to be checked against the “Content-Type” header. If not
present or 0, this check will be disabled.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE and BRANCH_ROUTE.
Example 1.30. has_body usage
...
if(has_body("application/sdp"))
{
# do interesting stuff here
}
...
3.31. is_audio_on_hold()
The function returns true if the SIP message has a body attached and at
least one audio stream in on hold.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE and BRANCH_ROUTE.
Example 1.31. is_audio_on_hold usage
...
if(is_audio_on_hold())
{
# do interesting stuff here
}
...
3.32. is_privacy(privacy_type)
The function returns true if the SIP message has a Privacy header field
that includes the given privacy_type among its privacy values. See
http://www.iana.org/assignments/sip-priv-values for possible privacy
type values.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE and BRANCH_ROUTE.
Example 1.32. is_privacy usage
...
if(is_privacy("id"))
{
# do interesting stuff here
}
...
3.33. in_list(subject, list, separator)
Function checks if subject string is found in list string where list
items are separated by separator string. Subject and list strings may
contain pseudo variables. Separator string needs to be one character
long. Returns 1 if subject is found and -1 otherwise.
Function can be used from all kinds of routes.
Example 1.33. in_list() usage
...
$var(subject) = "fi";
$var(list) = "dk,fi,no,se";
if (in_list("$var(subject)", "$var(list)", ",") {
xlog("L_INFO", "subject is found in list\n");
}
...
3.34. cmp_str(str1, str2)
The function returns true if the two parameters matches as string case
sensitive comparison.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE and BRANCH_ROUTE.
Example 1.34. cmp_str usage
...
if(cmp_str("$rU", "kamailio"))
{
# do interesting stuff here
}
...
3.35. cmp_istr(str1, str2)
The function returns true if the two parameters matches as string case
insensitive comparison.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE and BRANCH_ROUTE.
Example 1.35. cmp_str usage
...
if(cmp_istr("$rU@you", "kamailio@YOU"))
{
# do interesting stuff here
}
...
3.36. starts_with(str1, str2)
The function returns true if the first string starts with the second
string.
This function can be used from REQUEST_ROUTE, ONREPLY_ROUTE,
FAILURE_ROUTE and BRANCH_ROUTE.
Example 1.36. starts_with usage
...
if (starts_with("$rU", "+358"))
{
# do interesting stuff here
}
...
3.37. set_body_multipart([txt,content_type][,boundary])
Set multipart body to a SIP message. If called with no parameters, will
convert present body to multipart.
Meaning of the parameters is as follows:
* txt - text for the body, can include pseudo-variables.
* content_type - value of Content-Type header, can include
pseudo-variables.
* boundary - string to use as boundary, can include pseudo-variables.
Default: unique-boundary-1
This function can be used from REQUEST_ROUTE, FAILURE_ROUTE,
BRANCH_ROUTE.
The core will take care of the last boundary ending "--". Detecting
wich one is the last and fixing the others if needed.
Example 1.37. set_body_multipart usage
...
set_body_multipart("test", "text/plain", "delimiter");
...
Will produce:
...
Content-Type: multipart/mixed;boundary="delimiter"
Mime-Version: 1.0
--delimiter
Content-Type: text/plain
text
--delimiter
...
3.38. append_body_part(txt,content_type[, content_disposition])
Append a part on multipart body SIP message. Will use
"unique-boundary-1" as boundary.
Meaning of the parameters is as follows:
* txt - text for the multipart body, can include pseudo-variables.
* content_type - value of Content-Type header, can include
pseudo-variables.
* content_disposition - value of Content-Disposition header, can
include pseudo-variables.
This function can be used from REQUEST_ROUTE, FAILURE_ROUTE,
BRANCH_ROUTE.
The core will take care of the last boundary ending "--". Detecting
wich one is the last and fixing the others if needed.
Example 1.38. append_body_part usage
...
$var(b) = "7e Od 04 55 75 69 20 4d 61 6b 65 43 61 6c 6c"
append_body_part("$var(b)", "application/vnd.cirpack.isdn-ext", "signal;handlin
g=required");
...
Will append this the body:
...
Content-Type: application/vnd.cirpack.isdn-ext
Content-Disposition: signal;handling=required
7e Od 04 55 75 69 20 4d 61 6b 65 43 61 6c 6c
--unique-boundary-1
...
3.39. remove_body_part(content_type)
Remove a part on a multipart body SIP message.
Meaning of the parameters is as follows:
* content_type - value of Content-Type header of the part to be
removed. If more than one exists the first occurrence will be
removed.
This function can be used from REQUEST_ROUTE, FAILURE_ROUTE,
BRANCH_ROUTE.
The core will take care of the last boundary ending "--". Detecting
wich one is the last and fixing the others if needed.
Example 1.39. remove_body_part usage
...
remove_body_part("application/vnd.cirpack.isdn-ext");
...
4. Known Limitations
Search functions are applied to the original request, i.e., they ignore
all changes resulting from message processing in Kamailio script.
Chapter 2. Developer Guide
Table of Contents
1. Functions
1.1. load_textops(*import_structure)
1. Functions
1.1. load_textops(*import_structure)
1.1. load_textops(*import_structure)
For programmatic use only--import the Textops API.
Meaning of the parameters is as follows:
* import_structure - Pointer to the import structure - see “struct
textops_binds” in modules/textops/api.h |
package com.giousa.中介者模式;
import java.util.ArrayList;
import java.util.List;
/**
* 中介者模式解决问题的思路很简单,就是通过引入一个中介对象,让其他对象只与中介对象交互,
* 而中介对象知道如何和其他所有对象的交互,这样对象之间的交互关系就没有了,从而实现了对象之间的解耦。
*
* 中介者模式的主要优点
* 1、中介者模式简化了对象之间的交互,它用中介者和同事的一对多交互代替了原来同事之间的多对多交互,一对多关系更容易理解、维护和扩展,将原本难以理解的网状结构转换成相对简单的星型结构。
*
* 2、中介者模式可将各同事对象解耦。中介者有利于各同事之间的松耦合,我们可以独立的改变和复用每一个同事和中介者,增加新的中介者和新的同事类都比较方便,更好地符合 “开闭原则”。
*
* 3、可以减少子类生成,中介者将原本分布于多个对象间的行为集中在一起,改变这些行为只需生成新的中介者子类即可,这使各个同事类可被重用,无须对同事类进行扩展。
*
* 中介者模式的主要缺点
* 1、在具体中介者类中包含了大量同事之间的交互细节,可能会导致具体中介者类非常复杂,使得系统难以维护。(也就是把具体同事类之间的交互复杂性集中到了中介者类中,结果中介者成了最复杂的类)
*
* 适用场景
* 1、系统中对象之间存在复杂的引用关系,系统结构混乱且难以理解。
*
* 2、一个对象由于引用了其他很多对象并且直接和这些对象通信,导致难以复用该对象。
*
* 3、想通过一个中间类来封装多个类中的行为,而又不想生成太多的子类。可以通过引入中介者类来实现,在中介者中定义对象交互的公共行为,如果需要改变行为则可以增加新的具体中介者类。
*
* 以房屋中介功能为例,实现的功能是:
* 租客发布租房信息到房屋中介,房屋中介将收到的信息发布给所有的房东
* 房东发布信息到房屋中介,房屋中介将收到的信息发布给租客
*
* 以公司同事为例,实现的功能是:
* 同事可以发出所有消息或任务,除本人外,其他人都可以接收到。
*/
public class Demo {
/**
* 中介者抽象类
*/
public static abstract class Mediator {
/**
* 注册同事类
*/
public abstract void register(Colleague colleague);
/**
* 处理接收逻辑
*/
public abstract void operation(Colleague colleague);
}
/**
* 具体中介者类
*/
public static class ConcreteMediator extends Mediator {
private List<Colleague> colleagues = new ArrayList<>();
@Override
public void register(Colleague colleague) {
if (!colleagues.contains(colleague)) {
colleagues.add(colleague);
colleague.setMediator(this);
}
}
@Override
public void operation(Colleague colleague) {
for (Colleague coll : colleagues) {
if (!coll.equals(colleague)) {
coll.receive();
}
}
}
}
/**
* 抽象同事类
*/
public static abstract class Colleague {
protected Mediator mediator;
public void setMediator(Mediator mediator) {
this.mediator = mediator;
}
public abstract void receive();
public abstract void send();
}
/**
* 具体同事类1
*/
public static class ConcreteColleague1 extends Colleague {
@Override
public void receive() {
System.out.println("具体同事类 ConcreteColleague1 接收请求");
}
@Override
public void send() {
System.out.println("具体同事类 ConcreteColleague1 发送请求");
/*中介者进行转发*/
mediator.operation(this);
}
}
/**
* 具体同事类2
*/
public static class ConcreteColleague2 extends Colleague {
@Override
public void receive() {
System.out.println("具体同事类 ConcreteColleague2 接收到请求");
}
@Override
public void send() {
System.out.println("具体同事类 ConcreteColleague2 发送请求");
mediator.operation(this);
}
}
public static void main(String[] args) {
Mediator concreteMediator = new ConcreteMediator();
Colleague concreteColleague1 = new ConcreteColleague1();
Colleague concreteColleague2 = new ConcreteColleague2();
concreteMediator.register(concreteColleague1);
concreteMediator.register(concreteColleague2);
concreteColleague1.send();
concreteColleague2.send();
}
} |
export interface IBuilder<T> {
with<K extends keyof T>(key: K, value: T[K]): IBuilder<T>;
build(): T;
}
export class Builder<T> implements IBuilder<T> {
private constructor(private target: Partial<T>) {}
/**
* Returns a new {@link Builder} with the property {@link key} set to {@link value}.
*
* @param key - the name of the property from T to be set
* @param value - the value of the property from T to be set
*/
with<K extends keyof T>(key: K, value: T[K]): IBuilder<T> {
const target: Partial<T> = { ...this.target, [key]: value };
return new Builder<T>(target);
}
/**
* Returns an instance of T with the values that were set so far
*/
build(): T {
return this.target as T;
}
public static new<T>(): IBuilder<T> {
return new Builder<T>({});
}
} |
package com.example.controller
import com.example.db.dao.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.freemarker.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.util.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.encodeToString
import com.example.model.Product
object ProductController {
private val json = Json
suspend fun getAllProducts(call: ApplicationCall) {
val products = daoProduct.allProducts()
val jsonProducts = json.encodeToString(products)
call.respondText(jsonProducts, ContentType.Application.Json, HttpStatusCode.OK)
}
suspend fun addProduct(call: ApplicationCall) {
val post = call.receiveParameters()
val name = post["name"] ?: return call.respond(HttpStatusCode.BadRequest, "Missing field: name")
val description = post["description"] ?: return call.respond(HttpStatusCode.BadRequest, "Missing field: description")
val price = post["price"]?.toDoubleOrNull() ?: return call.respond(HttpStatusCode.BadRequest, "Missing field: price")
val quantity = post["quantity"]?.toIntOrNull() ?: return call.respond(HttpStatusCode.BadRequest, "Missing field: quantity")
val categoryId = post["categoryId"]?.toIntOrNull()
val product = daoProduct.addNewProduct(name, description, price, quantity, categoryId)
if (product == null) {
call.respond(HttpStatusCode.InternalServerError, "Error adding product")
} else {
call.respondRedirect("/products/${product.id}")
}
}
suspend fun getProduct(call: ApplicationCall) {
val id = call.parameters["id"]?.toIntOrNull() ?: return call.respond(HttpStatusCode.BadRequest, "Missing field: id")
val product = daoProduct.product(id)
if (product == null) {
call.respond(HttpStatusCode.NotFound, "Product not found")
} else {
val jsonProduct = json.encodeToString(product)
call.respondText(jsonProduct, ContentType.Application.Json, HttpStatusCode.OK)
}
}
suspend fun editProduct(call: ApplicationCall) {
val id = call.parameters["id"]?.toIntOrNull() ?: return call.respond(HttpStatusCode.BadRequest, "Missing field: id")
val post = call.receiveParameters()
val name = post["name"] ?: return call.respond(HttpStatusCode.BadRequest, "Missing field: name")
val description = post["description"] ?: return call.respond(HttpStatusCode.BadRequest, "Missing field: description")
val price = post["price"]?.toDoubleOrNull() ?: return call.respond(HttpStatusCode.BadRequest, "Missing field: price")
val quantity = post["quantity"]?.toIntOrNull() ?: return call.respond(HttpStatusCode.BadRequest, "Missing field: quantity")
val categoryId = post["categoryId"]?.toIntOrNull()
val success = daoProduct.editProduct(id, name, description, price, quantity, categoryId)
if (!success) {
call.respond(HttpStatusCode.NotFound, "Product not found")
} else {
call.respondRedirect("/products/$id")
}
}
suspend fun deleteProduct(call: ApplicationCall) {
val id = call.parameters["id"]?.toIntOrNull() ?: return call.respond(HttpStatusCode.BadRequest, "Missing field: id")
val success = daoProduct.deleteProduct(id)
if (!success) {
call.respond(HttpStatusCode.NotFound, "Product not found")
} else {
call.respondRedirect("/products")
}
}
} |
/**
* Copyright 2018 EPFL LCA1
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import {Component, OnInit, ViewChild} from '@angular/core';
import {GbConstraintComponent} from '../gb-constraint/gb-constraint.component';
import {AutoComplete} from 'primeng';
import {MessageHelper} from '../../../../utilities/message-helper';
import {TreeNode} from '../../../../models/tree-models/tree-node';
import {GenomicAnnotationConstraint} from '../../../../models/constraint-models/genomic-annotation-constraint';
import {Subject} from 'rxjs';
import {debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';
import {GenomicAnnotation} from '../../../../models/constraint-models/genomic-annotation';
import {ErrorHelper} from '../../../../utilities/error-helper';
@Component({
selector: 'gb-genomic-annotation-constraint',
templateUrl: './gb-genomic-annotation-constraint.component.html',
styleUrls: ['./gb-genomic-annotation-constraint.component.css', '../gb-constraint/gb-constraint.component.css']
})
export class GbGenomicAnnotationConstraintComponent extends GbConstraintComponent implements OnInit {
@ViewChild('annotationNameAutoComplete', { static: true }) annotationNameAutoComplete: AutoComplete;
@ViewChild('annotationValueAutoComplete', { static: true }) annotationValueAutoComplete: AutoComplete;
private _searchedAnnotations: GenomicAnnotation[];
private _searchedAnnotationValues: string[];
private annotationValuesSearchTerm: Subject<string>;
/*
* flag indicating if to show more options
*/
private _showMoreOptions = false;
ngOnInit() {
this.initializeConstraints();
}
initializeConstraints(): Promise<any> {
return new Promise<any>((resolve, reject) => {
// default zygosity
this.genomicConstraint.zygosityHomozygous = true;
this.genomicConstraint.zygosityHeterozygous = true;
this.genomicConstraint.zygosityUnknown = true;
this.searchedAnnotations = [];
this.searchedAnnotationValues = [];
this.annotationValuesSearchTerm = new Subject();
this.annotationValuesSearchTerm.pipe(
debounceTime(200),
distinctUntilChanged(),
switchMap( (searchTerm: string) => this.genomicAnnotationsService.getAnnotationValues(this.selectedAnnotation, searchTerm))
).subscribe(
(vals: string[]) => this.searchedAnnotationValues = vals,
(err) => ErrorHelper.handleError(`Error querying annotation ${this.selectedAnnotation.name}`, err)
);
this.showMoreOptions = false;
});
}
/*
* -------------------- event handlers: autocompletes --------------------
*/
/**
* when the user searches through annotation names list
* @param event
*/
annotationNameOnSearch(event) {
let query = event.query.toLowerCase();
let annotations = this.constraintService.genomicAnnotations;
if (query) {
this.searchedAnnotations = annotations.filter((genAnnotation: GenomicAnnotation) =>
genAnnotation.displayName.toLowerCase().includes(query) ||
genAnnotation.name.toLowerCase().includes(query)
);
} else {
this.searchedAnnotations = annotations;
}
}
/**
* when the user searches through annotation values
* @param event
*/
annotationValueOnSearch(event) {
let query = event.query.toLowerCase();
if (query && this.selectedAnnotation) {
this.annotationValuesSearchTerm.next(query);
}
}
/**
* Toggle the 'more options' panel
*/
toggleMoreOptions() {
this.showMoreOptions = !this.showMoreOptions;
}
onDrop(event: DragEvent) {
event.stopPropagation();
let selectedNode: TreeNode = this.treeNodeService.selectedTreeNode;
this.droppedConstraint =
this.constraintService.generateConstraintFromTreeNode(selectedNode, selectedNode ? selectedNode.dropMode : null);
if (this.droppedConstraint && this.droppedConstraint.className === 'GenomicAnnotationConstraint') {
this.genomicConstraint = this.droppedConstraint as GenomicAnnotationConstraint;
this.initializeConstraints()
.then(() => {
this.update();
});
} else {
const summary = `Dropped a ${this.droppedConstraint.className}, incompatible with GenomicAnnotationConstraint.`;
MessageHelper.alert('error', summary);
}
this.treeNodeService.selectedTreeNode = null;
this.droppedConstraint = null;
}
/*
* -------------------- getters and setters --------------------
*/
get genomicConstraint(): GenomicAnnotationConstraint {
return this.constraint as GenomicAnnotationConstraint;
}
set genomicConstraint(value: GenomicAnnotationConstraint) {
this.constraint = value;
}
get selectedAnnotation(): GenomicAnnotation {
return this.genomicConstraint.annotation;
}
set selectedAnnotation(value: GenomicAnnotation) {
this.genomicConstraint.annotation = value;
this.initializeConstraints();
this.update();
}
get selectedAnnotationValue(): string {
return this.genomicConstraint.annotationValue;
}
set selectedAnnotationValue(value: string) {
this.genomicConstraint.annotationValue = value;
this.initializeConstraints();
this.update();
}
get searchedAnnotations(): GenomicAnnotation[] {
return this._searchedAnnotations;
}
set searchedAnnotations(value: GenomicAnnotation[]) {
this._searchedAnnotations = value;
}
get searchedAnnotationValues(): string[] {
return this._searchedAnnotationValues;
}
set searchedAnnotationValues(value: string[]) {
this._searchedAnnotationValues = value;
}
get showMoreOptions(): boolean {
return this._showMoreOptions;
}
set showMoreOptions(value: boolean) {
this._showMoreOptions = value;
}
} |
import 'package:movie_booking_app/data/vos/cast_crew_vo/cast_crew_vo.dart';
import 'package:movie_booking_app/data/vos/check_out_vo/checkout_vo.dart';
import 'package:movie_booking_app/data/vos/day_timeslot_vo/day_timeslot_vo.dart';
import 'package:movie_booking_app/data/vos/genre_vo/genre_vo.dart';
import 'package:movie_booking_app/data/vos/movie_vo/movie_vo.dart';
import 'package:movie_booking_app/data/vos/seating_plan_vo/seating_type_vo.dart';
import 'package:movie_booking_app/data/vos/snack_and_payment_vo/snack_and_payment_vo.dart';
import 'package:movie_booking_app/data/vos/user_vo/user_vo.dart';
import 'package:movie_booking_app/network/data_agent/movie_booking_data_agent.dart';
import 'package:movie_booking_app/network/response/check_out_response/check_out_raw_response.dart';
import 'package:movie_booking_app/network/response/create_card_response/create_card_response.dart';
import 'package:movie_booking_app/network/response/logout_response/logout_response.dart';
import 'package:movie_booking_app/network/response/user_response/user_response.dart';
import '../mock_data/mock_data.dart';
class MovieDataAgentImplMock extends MovieBookingDataAgent{
@override
Future<CheckoutVO?> checkout(String authorization, CheckOutRawResponse checkOutRawResponse) {
return Future.value(getMockCheckoutForTest());
}
@override
Future<CreateCardResponse?> createCard(String cardNumber, String cardHolder, String expirationDate, String cvc, String authorization) {
return Future.value(CreateCardResponse(0,'',createCardMockForTest()));
}
@override
Future<List<MovieVO>?> getComingSoonMovie(String apiKey, String language, int page) {
return Future.value(moviesMockForTest().where((element) => element.isComingSoon??false).toList());
}
@override
Future<List<DayTimeSlotVO>?> getDayTimeSlotsList(int movieID, String date, String authorization) {
return Future.value(cinemaDayTimeslotMockForTest());
}
@override
Future<List<GenreVO>?> getGenre(String apiKey, String language) {
// TODO: implement getGenre
throw UnimplementedError();
}
@override
Future<List<CastCrewVO>?> getMovieCastList(int movieID, String apiKey, String language) {
return Future.value(actorsMockForTest());
}
@override
Future<List<CastCrewVO>?> getMovieCrewList(int movieID, String apiKey, String language) {
// TODO: implement getMovieCrewList
throw UnimplementedError();
}
@override
Future<MovieVO?> getMovieDetails(int movieID, String apiKey, String language) {
return Future.value(moviesMockForTest().first);
}
@override
Future<List<MovieVO>?> getNowPlayingMovie(String apiKey, String language, int page) {
return Future.value(moviesMockForTest().where((element) => element.isNowShowing??false).toList());
}
@override
Future<List<SnackAndPaymentVO>?> getPaymentMethodsList(String authorization) {
return Future.value(paymentMockForTest());
}
@override
Future<UserVO?> getProfile(String authorization) {
return Future.value(profileMockForTest());
}
@override
Future<List<SeatinTypeVO>?> getSeatingPlaneList(int cinemaDayTimeSlotsID, String bookingDate, String authorization) {
return Future.value(seatingPlanMockForTest());
}
@override
Future<List<SnackAndPaymentVO>?> getSnackList(String authorization) {
return Future.value(snacksMockForTest());
}
@override
Future<UserResponse?> getUserLoginStatus(String email, String password) {
// TODO: implement getUserLoginStatus
throw UnimplementedError();
}
@override
Future<UserResponse?> getUserRegisterStatus(String name, String email, String phone, String password, String googleAccessToken, String faceBookAccessToken) {
return Future.value(UserResponse(0,'',registerAndLoginMockForTest().first,''));
}
@override
Future<UserResponse?> loginWithFacebook(String accessToken) {
return Future.value(UserResponse(0,'',registerAndLoginMockForTest().first,''));
}
@override
Future<UserResponse?> loginWithGoogle(String accessToken) {
return Future.value(UserResponse(0,'',registerAndLoginMockForTest().first,''));
}
@override
Future<LogoutResponse?> logout(String authorization) {
// TODO: implement logout
throw UnimplementedError();
}
} |
#! /usr/bin/env ruby -S rspec
require 'spec_helper_acceptance'
describe 'has_key function' do
describe 'success' do
pp1 = <<-DOC
$a = { 'aaa' => 'bbb','bbb' => 'ccc','ddd' => 'eee' }
$b = 'bbb'
$c = true
$o = has_key($a,$b)
if $o == $c {
notify { 'output correct': }
}
DOC
it 'has_keys in hashes' do
apply_manifest(pp1, :catch_failures => true) do |r|
expect(r.stdout).to match(%r{Notice: output correct})
end
end
pp2 = <<-DOC
$a = { 'aaa' => 'bbb','bbb' => 'ccc','ddd' => 'eee' }
$b = 'ccc'
$c = false
$o = has_key($a,$b)
if $o == $c {
notify { 'output correct': }
}
DOC
it 'has_keys not in hashes' do
apply_manifest(pp2, :catch_failures => true) do |r|
expect(r.stdout).to match(%r{Notice: output correct})
end
end
end
describe 'failure' do
it 'handles improper argument counts'
it 'handles non-hashes'
end
end |
# Built-in python libraries
import unittest
# Side-packages
import requests
import pandas as pd
class TestWebAPI(unittest.TestCase):
API_ENDPOINT = "http://localhost:8080/predict"
sample_input_location = 'Requirements/sample_data_list_dictionary.pickle'
@classmethod
def setUpClass(cls):
cls.test_data = pd.read_pickle(cls.sample_input_location)
def test_ok_api_call_responses(self):
# iterate over the entire dataset
print("\n")
for i in range(len(self.test_data)):
input_data = self.test_data[i]
with self.subTest(data=input_data):
response = requests.post(self.API_ENDPOINT, json=input_data)
self.assertEqual(response.status_code, 200)
print(f"API call {i+1} successfully executed.")
def test_valid_response_format(self):
input_data = {
"RequestId" : "8564669c",
"RequestDateTime" : "2023-05-31T18:49:33.670326Z",
"BirthDate" : "2005-04-10T00:00:00Z",
"Email" : "rock-n-rolla@ritchie.com",
"GrossAmount" : 98.23,
"EMCResult" : "E",
"NumberOfPayments" : 2.0,
"Merchant" : "Merchant_A",
"labels" : 1
}
expected_response = {
"merchant_name": "Merchant_A",
"model_version": "1.0",
"predicted_probability": 0.9254831276114961,
"request_datetime": "2023-05-31T18:49:33.670326Z",
"request_id": "8564669c"
}
response = requests.post(self.API_ENDPOINT, json=input_data)
data = response.json()
self.assertEqual(response.status_code, 200)
for item in expected_response:
self.assertIn(item, data.keys())
print("\nThe response format is as expected for an Ok API call")
def test_valid_api_call_without_email(self):
input_data = {
"RequestId" : "8564669c",
"RequestDateTime" : "2023-05-31T18:49:33.670326Z",
"BirthDate" : "2005-04-10T00:00:00Z",
"GrossAmount" : 98.23,
"EMCResult" : "E",
"NumberOfPayments" : 2.0,
"Merchant" : "Merchant_A",
"labels" : 1
}
expected_response = {
"merchant_name": "Merchant_A",
"model_version": "1.0",
"predicted_probability": 0.9254831276114961,
"request_datetime": "2023-05-31T18:49:33.670326Z",
"request_id": "8564669c"
}
response = requests.post(self.API_ENDPOINT, json=input_data)
data = response.json()
self.assertEqual(response.status_code, 200)
for item in expected_response:
self.assertIn(item, data.keys())
print("\nAPI call executed successfully with valid input (missing Email)")
def test_bad_request_missing_birthday(self):
input_data = {
"RequestId" : "8564669c",
"RequestDateTime" : "2023-05-31T18:49:33.670326Z",
"GrossAmount" : 98.23,
"EMCResult" : "E",
"NumberOfPayments" : 2.0,
"Merchant" : "Merchant_A",
"labels" : 1
}
response = requests.post(self.API_ENDPOINT, json=input_data)
self.assertEqual(response.status_code, 400)
print("\nException raised for missing BirthDate")
def test_bad_request_time_format(self):
input_data = {
"RequestId" : "8564669c",
"RequestDateTime" : "2023-05-31T18:49:33.670326Z",
"BirthDate" : "20050:00Z",
"GrossAmount" : 98.23,
"EMCResult" : "E",
"NumberOfPayments" : 2.0,
"Merchant" : "Merchant_A",
"labels" : 1
}
response = requests.post(self.API_ENDPOINT, json=input_data)
self.assertEqual(response.status_code, 400)
print("\nException raised for bad BirthDate format")
if __name__ == '__main__':
unittest.main() |
#pragma once
#include <string>
#include <string.h>
#include <algorithm>
#include <ostream>
#include <vector>
#include <math.h>
#include <cmath>
#include <stdio.h>
inline bool ends_with(const std::string &s, const char *t) {
if (s.length() < strlen(t))
return false;
return s.compare(s.length() - strlen(t), std::string::npos, t) == 0;
}
inline std::string rstrip(const std::string &s, const char *t) {
const size_t l = strlen(t);
if (s.length() < l)
return s;
if (s.compare(s.length() - l, std::string::npos, t) == 0)
return std::string(s.begin(), s.end() - l);
else
return s;
}
inline size_t max_len(const char** s, size_t n) {
size_t l = 0;
for (size_t i = 0; i < n; ++i)
l = std::max(l, strlen(s[i]));
return l;
}
template<typename _it>
inline std::vector<const char*> charp_array(_it begin, _it end) {
std::vector<const char*> v;
v.reserve(end - begin);
for (auto i = begin; i != end; ++i)
v.push_back(i->c_str());
return v;
}
#define MAX_LEN(A) max_len(A, sizeof(A)/sizeof(A[0]))
std::string convert_size(size_t size);
namespace Util { namespace String {
// Workaround since sprintf is inconsistent in double rounding for different implementations.
inline int format_double(double x, char *p, int64_t buf_size) {
if (x >= 100.0)
return snprintf(p, buf_size, "%lli", (long long)std::floor(x)); // for keeping output compatible with BLAST
long long i = std::llround(x*10.0);
return snprintf(p, buf_size, "%lli.%lli", i / 10, i % 10);
}
std::string replace(const std::string& s, char a, char b);
std::string ratio_percentage(const double x, const double y);
std::string ratio_percentage(const size_t x, const size_t y);
int64_t interpret_number(const std::string& s);
}} |
/*
* Copyright (c) 2024 OceanBase.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package server
import (
"fmt"
"os"
"syscall"
"time"
log "github.com/sirupsen/logrus"
"github.com/oceanbase/obshell/agent/api/web"
"github.com/oceanbase/obshell/agent/config"
"github.com/oceanbase/obshell/agent/constant"
"github.com/oceanbase/obshell/agent/errors"
"github.com/oceanbase/obshell/agent/executor/agent"
"github.com/oceanbase/obshell/agent/executor/ob"
"github.com/oceanbase/obshell/agent/global"
"github.com/oceanbase/obshell/agent/lib/path"
"github.com/oceanbase/obshell/agent/lib/process"
agentlog "github.com/oceanbase/obshell/agent/log"
"github.com/oceanbase/obshell/agent/meta"
"github.com/oceanbase/obshell/agent/repository/db/sqlite"
"github.com/oceanbase/obshell/agent/secure"
agentservice "github.com/oceanbase/obshell/agent/service/agent"
)
var agentService = agentservice.AgentService{}
// init will initialize all modules,
// including log, global, sqlite, agent, httpServer, and task registration.
func (a *Agent) init() (err error) {
a.initLogger()
global.InitGlobalVariable()
a.isOBhasStarted()
a.isUpgradeMode()
if err = a.initSqlite(); err != nil {
return errors.Wrap(err, "init sqlite failed")
}
if err = secure.Init(); err != nil {
return errors.Wrap(err, "secure init failed")
}
if err = a.initAgent(); err != nil {
return errors.Wrap(err, "init agent failed")
}
if err = a.preCheckForUpgrade(); err != nil {
return errors.Wrap(err, "pre check for upgrade failed")
}
a.initServer()
a.initTask()
return nil
}
// initLogger initializes logger module with default config
func (a *Agent) initLogger() {
log.Info("initialize logger")
agentlog.InitLogger(config.DefaultAgentLoggerConifg())
}
// initSqlite loads the sqlite instance and migrate the tables when necessary,
// and set the agent to the running state
func (a *Agent) initSqlite() (err error) {
log.Info("initialize sqlite")
if err = sqlite.LoadSqliteInstance(); err != nil {
return err
}
if err = sqlite.MigrateSqliteTables(a.upgradeMode); err != nil {
return errors.Wrap(err, "migrate sqlite tables failed")
}
return nil
}
// initServerForUpgrade will only start the unix socket service When upgrading.
func (a *Agent) initServerForUpgrade() error {
log.Info("init local server [upgrade mode]")
serverConfig := config.ServerConfig{
Ip: meta.OCS_AGENT.GetIp(),
Port: meta.OCS_AGENT.GetPort(),
Address: meta.OCS_AGENT.String(),
RunDir: path.RunDir(),
UpgradeMode: true,
}
a.server = web.NewServerOnlyLocal(config.DebugMode, serverConfig)
socketListener, err := a.server.NewUnixListener()
if err != nil {
return err
}
a.tmpSocketPath = a.server.SocketPath()
a.tmpServer = *a.server
a.server.UnixListener = socketListener
a.server.RunLocalServer()
return nil
}
// WaitServerProcKilled will wait for the old agent to exit When upgrading.
// If the old agent does not exit within 10 minutes, an error will be returned.
func WaitServerProcKilled(pid int32) error {
log.Infof("wait %d killed", pid)
for i := 0; i < constant.AGENT_START_TIMEOUT; i++ {
exist, err := process.CheckProcessExist(pid)
if err != nil {
return errors.Wrap(err, "check server proc failed")
}
if !exist {
log.Infof("%d killed", pid)
time.Sleep(5 * time.Second)
return nil
}
log.Infof("%d still exist, wait 1s", pid)
time.Sleep(time.Second)
}
return errors.New("wait obshell server killed timeout")
}
// initAgent will get the final agent info based on meta ,incoming configuration, and default value.
func (a *Agent) initAgent() (err error) {
log.Info("initialize agent")
if err = agentService.InitAgent(); err != nil {
return errors.Wrap(err, "init agent failed")
}
log.Infof("meta from sqlite is %s", meta.OCS_AGENT)
if a.obHasStarted {
if !a.upgradeMode {
if err = ob.LoadOBConfigFromConfigFile(); err != nil {
log.WithError(err).Error("load ob config from config file failed")
process.ExitWithFailure(constant.EXIT_CODE_ERROR_IP_NOT_MATCH, fmt.Sprintf("load ob config from config file failed: %v\n", err))
}
}
} else if meta.OCS_AGENT.IsUnidentified() {
// Error must be nil.
agentService.BeSingleAgent()
}
a.checkAgentInfo()
// Update agent info if necessary.
if err = a.updateAgent(); err != nil {
return err
}
log.Info("initialize agent status")
return agentService.InitializeAgentStatus()
}
func (a *Agent) updateAgent() (err error) {
if meta.OCS_AGENT.Equal(&a.AgentInfo) {
return nil
}
switch meta.OCS_AGENT.GetIdentity() {
case meta.UNIDENTIFIED:
if meta.OCS_AGENT.GetIp() != a.AgentInfo.Ip {
process.ExitWithFailure(constant.EXIT_CODE_ERROR_IP_NOT_MATCH, fmt.Sprintf("agent ip not match, input is %s, meta is %s", a.AgentInfo.Ip, meta.OCS_AGENT.GetIp()))
}
fallthrough
case meta.SINGLE:
err = agentService.UpdateAgentInfo(&a.AgentInfo)
default:
err = fmt.Errorf("agent info not equal, input is %v, meta is %v", a.AgentInfo, meta.OCS_AGENT)
}
return
}
func (a *Agent) checkAgentInfo() {
log.Info("check agent info")
// Fill agent ip.
if a.AgentInfo.Ip == "" && meta.OCS_AGENT.GetIp() != "" {
a.AgentInfo.Ip = meta.OCS_AGENT.GetIp()
}
// Fill agent port.
if a.AgentInfo.GetPort() == 0 {
// While port is empty and agent is single, set port to default value.
// If agent is not single, it must have port. Otherwise, there will be an error
if meta.OCS_AGENT.GetPort() == 0 && (meta.OCS_AGENT.IsSingleAgent() || meta.OCS_AGENT.IsUnidentified()) {
a.AgentInfo.Port = constant.DEFAULT_AGENT_PORT
}
if meta.OCS_AGENT.GetPort() != 0 {
a.AgentInfo.Port = meta.OCS_AGENT.GetPort()
}
}
// If agent ip or port is empty, exit.
if a.AgentInfo.Ip == "" || a.AgentInfo.Port == 0 {
log.Error("agent info is invalid")
process.ExitWithFailure(constant.EXIT_CODE_ERROR_INVAILD_AGENT, fmt.Sprintf("agent info is invalid: %v", a.AgentInfo))
}
if a.NeedBeCluster && !meta.OCS_AGENT.IsClusterAgent() {
process.ExitWithFailure(constant.EXIT_CODE_ERROR_NOT_CLUSTER_AGENT, "obshell need to be cluster. Please do takeover first.")
}
}
// initServer will only initialize the Server and will not start the service.
func (a *Agent) initServer() {
log.Info("init server")
serverConfig := config.ServerConfig{
Ip: meta.OCS_AGENT.GetIp(),
Port: meta.OCS_AGENT.GetPort(),
Address: meta.OCS_AGENT.String(),
RunDir: path.RunDir(),
}
log.Infof("server config is %v", serverConfig)
a.server = web.NewServer(config.DebugMode, serverConfig)
a.startChan = make(chan bool, 1)
}
// initTask will register tasks
func (a *Agent) initTask() {
ob.RegisterObStartTask()
ob.RegisterObStopTask()
ob.RegisterObInitTask()
ob.RegisterObScaleOutTask()
ob.RegisterUpgradeTask()
agent.RegisterAgentTask()
}
// Check if the ob config file exists.
func (a *Agent) isOBhasStarted() bool {
// If an error occurs, it's assumed that OB is not started.
a.obHasStarted, _ = ob.HasStarted()
return a.obHasStarted
}
func (a *Agent) isUpgradeMode() bool {
log.Info("Check if obshell is in upgrade mode.")
if a.OldServerPid != 0 {
// If the old agent is running in the same directory as the new agent,
// it is considered an upgrade.
cwdDir, err := os.Readlink(fmt.Sprintf("/proc/%d/cwd", a.OldServerPid))
if err != nil {
return false
}
log.Infof("the cwd of %d is %s", a.OldServerPid, cwdDir)
if global.HomePath == cwdDir {
log.Info("The obshell is in upgrade mode.")
a.upgradeMode = true
// Unset root password env to avoid cover sqlite when upgrade (agent restart)
syscall.Unsetenv(constant.OB_ROOT_PASSWORD)
}
}
return a.upgradeMode
}
// preCheckForUpgrade will initialize the unix socket service,
// and check if the old server has been killed.
func (a *Agent) preCheckForUpgrade() (err error) {
if a.upgradeMode {
if err = a.initServerForUpgrade(); err != nil {
return err
}
if err = WaitServerProcKilled(a.OldServerPid); err != nil {
return err
}
}
return nil
} |
/*
* This is the entry point of the application.
* It creates a WebGL context and starts the engine,
* which clears the canvas with a rainbow color every frame.
* Since it is easier to run through the hue wheel than the RGB wheel,
* we convert HSL to RGB.
*/
import WebGLManager from "./Core/WebGLManager.js";
import Engine from "./Core/Engine.js";
import hslToRgb from "./Utils/hslToRgb.js";
import Logger from "../Utils/Logger.js";
// Initialize WebGLManager to create a WebGL context
const glManager = new WebGLManager("canvas");
// Resize the canvas to fill the window
glManager.resize();
const gl = glManager.gl;
// Initialize the Engine with the WebGL context
const engine = new Engine(gl);
// Show me rainbows!
let hue = 0;
// Set the engine update method to change the clear color every frame
engine.update = function (deltaTime) {
// Update the clear color to a new hue every frame
hue = (hue + deltaTime / 50) % 360; // Rotate through the color wheel every 50ms
const [r, g, b] = hslToRgb(hue / 360, 1, 0.5); // 100% Saturation, 50% Lightness for vivid colors
this.gl.clearColor(r, g, b, 1);
};
// Start the engine
engine.start(); |
<!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>W3.CSS Template</title>
<link rel="stylesheet" href="./assets/css/style.css">
<link rel="stylesheet" href="./assets/font-icons/themify-icons-font/themify-icons/themify-icons.css">
<link href="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/W3Schools_logo.svg/1024px-W3Schools_logo.svg.png" type="image/x-icon" rel="shortcut icon">
</head>
<body>
<!-- BEGIN: NAV -->
<div id="main">
<div id="header">
<ul id="nav">
<li><a href="#">Home</a></li>
<li><a href="#band">Band</a></li>
<li><a href="#tour">Tour</a></li>
<li><a href="#contact">Contact</a></li>
<li>
<a href="# ">More
<i class="nav-arow-down ti-angle-down"></i>
</a>
<ul class="subnav">
<li><a href="">Merchandise</a></li>
<li><a href="">Extras</a></li>
<li><a href="">Media</a></li>
</ul>
</li>
</ul>
<!-- END: NAV -->
<!-- BEGIN: SEARCH BUTTON -->
<div class="search-button">
<i class="search-icon ti-search"></i>
</div>
<div id="mobile-menu-btn" class="mobile-menu">
<i class="menu-btn ti-menu"></i>
</div>
<!-- END: SEARCH BUTTON -->
</div>
<div id="slider">
<div class="text-content">
<h2 class="text-heading">Chicago</h2>
<div class="text-description">
Thank you, Chicago - A night we won't forget.
</div>
</div>
</div>
<div id="content">
<div id="band" class="content-section">
<h2 class="section-heading">THE BAND</h2>
<p class="section-sub-heading">We love music</p>
<p class="about-content">
We have created a fictional band website. Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
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 id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</p>
<div class="row member-list">
<div class="col col-third text-content">
<p class="member-name">Name</p>
<img src="/assets/img/slider1/bandmember.jpg" alt="ảnh thành viên" class="member-jmg">
</div>
<div class="col col-third text-content">
<p class="member-name">Name</p>
<img src="/assets/img/slider1/bandmember.jpg" alt="ảnh thành viên" class="member-jmg">
</div>
<div class="col col-third text-content">
<p class="member-name">Name</p>
<img src="/assets/img/slider1/bandmember.jpg" alt="ảnh thành viên" class="member-jmg">
</div>
<div class="clear"></div>
</div>
</div>
<!-- tour section -->
<div id="tour" class="tour-section">
<div class="content-section">
<h2 class="section-heading text-white">TOUR DATES</h2>
<p class="section-sub-heading text-white">Remember to book your tickets!</p>
<!-- tikets -->
<ul class="tikets-list">
<li>September <span class="sold-out">Sold out</span></li>
<li>October <span class="sold-out">Sold out</span></li>
<li>November <span class="quantity">3</span></li>
</ul>
<!-- place -->
<div class=" row ">
<div class="col col-third">
<img src="/assets/img/slider1/place.jpg" alt="Paris" class="place-img">
<div class="place-content">
<h3 class="place-heading">New York</h3>
<p class="place-time">Fri 27 Nov 2016</p>
<p class="place-desc">Praesent tincidunt sed tellus ut rutrum sed vitae justo.</p>
<button class="btn js-buy-titket ">Buy Tickets</button>
</div>
</div>
<div class="col col-third">
<img src="/assets/img/slider1/place1.jpg" alt="Paris" class="place-img">
<div class="place-content">
<h3 class="place-heading">Paris</h3>
<p class="place-time">Sat 28 Nov 2016</p>
<p class="place-desc">Praesent tincidunt sed tellus ut rutrum sed vitae justo.</p>
<button class="btn js-buy-titket">Buy Tickets</button>
</div>
</div>
<div class="col col-third">
<img src="/assets/img/slider1/place2.jpg" alt="San Francisco" class="place-img">
<div class="place-content">
<h3 class="place-heading">San Francisco</h3>
<p class="place-time">Sun 29 Nov 2016</p>
<p class="place-desc">Praesent tincidunt sed tellus ut rutrum sed vitae justo.</p>
<button class="btn js-buy-titket">Buy Tickets</button>
</div>
</div>
</div>
<!-- end-place -->
</div>
</div>
<!-- BEGIN: content-section -->
<div id="contact" class="content-section">
<h2 class="section-heading">CONTACT</h2>
<p class="section-sub-heading">Fan? Drop a note!</p>
<div class="row contact-content">
<div class="col col-half contact-info ">
<p><i class="ti-location-pin"></i>Chicago, US</p>
<p><i class="ti-mobile"></i>Phone: +00 151515</p>
<p><i class="ti-email"></i>Email: mail@mail.com</p>
</div>
<div class="col col-half contact-inform">
<form action="">
<div class="row ">
<div class="col col-half ">
<input type="text" name="" placeholder="Name" required id="" class="form-control">
</div>
<div class="col col-half">
<input type="email" name="" placeholder="Email" required id="" class="form-control">
</div>
</div>
<div class="row mt-8">
<div class="col col-full">
<input type="text" name="" placeholder="Message" required id="" class="form-control">
</div>
</div>
<input class="btn pull-right mt-16 " type="submit" value="Send">
</form>
</div>
</div>
</div>
<!-- END: content-section -->
<div class="map-section">
<img src="/assets/img/slider1/map.jpg" alt="ảnh map">
</div>
</div>
<div id="footer">
<div class="socials">
<a href="#"><i class="ti-facebook"></i></a>
<a href="#"><i class="ti-instagram"></i></a>
<a href="#"><i class="ti-youtube"></i></a>
<a href="#"><i class="ti-pinterest"></i></a>
<a href="#"><i class="ti-twitter"></i></a>
<a href="#"><i class="ti-linkedin"></i></a>
</div>
<p class="copy-right">Powered by w3.css</p>
</div>
</div>
<div class="modal js-modal">
<div class="modal-container">
<div class="madal-icon-close js-modal-close">
<i class=" ti-close"></i>
</div>
<header class="madal-header">
<i class="madal-icon-bag ti-bag"></i>
Tickets
</header>
<div class="madal-body">
<label for="titket-quantity" class="modal-label">
<i class="ti-shopping-cart"></i>
Titkets, $15 per person
</label>
<input id="titket-quantity" type="text" class="modal-input" placeholder="How many ?">
<label for="titket-email" class="modal-label">
<i class="ti-user"></i>
Send to
</label>
<input id="titket-email" type="email" class="modal-input" placeholder="Enter email...">
<button id="buy-titkets">
Pay <i class="ti-check"></i>
</button>
</div>
<footer class="madal-footer">
<p class="madal-help">Need <a href="">help?</a></p>
</footer>
</div>
</div>
<script>
const buyBtns = document.querySelectorAll('.js-buy-titket');
const modal = document.querySelector('.js-modal');
const modalClose = document.querySelector('.js-modal-close')
function showBuyTickets() {
modal.classList.add('open')
}
function hideBuyTickets() {
modal.classList.remove('open')
}
for( const buyBtn of buyBtns) {
buyBtn.addEventListener('click',showBuyTickets)
}
modalClose.addEventListener('click',hideBuyTickets)
</script>
<script>
var header = document.getElementById('header');
var mobileMenu = document.getElementById('mobile-menu-btn');
var headerHeight = header.clientHeight;
mobileMenu.onclick= function(){
var isClosed = header.clientHeight === headerHeight;
if(isClosed) {
header.style.height='auto';
}
else{
header.style.height=null;
}
}
var menuItems = document.querySelectorAll('#nav li a[href="#"]')
for(var i=0;i<menuItems.length;i++){
var menuItem = menuItems[i];
menuItem.onclick = function(){
header.style.height=null;
}
}
</script>
</body>
</html> |
import 'package:flutter/material.dart';
import 'package:todolist/data/api/rick_morty_api.dart' as rick_morty_api;
export 'rick_and_morty.dart';
class RickAndMorty extends StatefulWidget {
const RickAndMorty({Key? key}) : super(key: key);
@override
State<RickAndMorty> createState() => _RickAndMortyState();
}
class _RickAndMortyState extends State<RickAndMorty> {
late Future<rick_morty_api.Characters> rickAndMortyResponse;
@override
void initState() {
super.initState();
rickAndMortyResponse = rick_morty_api.fetchCharacter();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Rick and Morty'),
),
body: Center(
child: Column(
children: [
const Text('Rick and Morty'),
FutureBuilder<rick_morty_api.Characters>(
future: rickAndMortyResponse,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Expanded(
child: ListView(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: snapshot.data!.previous == ""
? null
: () {
setState(() {
rickAndMortyResponse =
rick_morty_api.fetchCharacter(
url: snapshot.data!.previous);
});
},
child: const Text("Previous"),
),
Text('Page: ${snapshot.data!.currentPage - 1}'),
ElevatedButton(
onPressed: snapshot.data!.next == ""
? null
: () {
setState(() {
rickAndMortyResponse =
rick_morty_api.fetchCharacter(
url: snapshot.data!.next);
});
},
child: const Text("Next"),
),
],
),
for (var character in snapshot.data!.characters)
CharacterCard(character: character)
],
),
);
}
},
),
],
),
),
);
}
}
class CharacterCard extends StatelessWidget {
const CharacterCard({Key? key, required this.character}) : super(key: key);
final rick_morty_api.Character character;
@override
Widget build(BuildContext context) {
return Column(
children: [
const SizedBox(height: 10),
Card(
child: Column(
children: [
ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(10.0),
topRight: Radius.circular(20.0),
),
child: Image.network(character.imgUrl),
),
Text(character.name),
Text(character.status),
Text(character.species),
],
),
),
],
);
}
} |
import {inject, injectable} from "tsyringe"
import { ICategoriesRepository } from "../../repositories/ICategoriesRepository";
import { AppError } from '../../../../shared/errors/appError';
interface IRequest{
name:string;
description:string;
}
@injectable()
class CreateCategoryUseCase{
constructor(
// injetando a dependendica
@inject("CategoriesRepository")
private categoriesRepository:ICategoriesRepository){}
async execute({name, description}:IRequest):Promise<void>{
const categoryExist = await this.categoriesRepository.findByName(name);
if(categoryExist){
throw new AppError("category exists");
}
await this.categoriesRepository.create({name, description})
}
}
export {CreateCategoryUseCase} |
package alphasql
import (
"bytes"
"database/sql/driver"
"errors"
"fmt"
"reflect"
"strconv"
"time"
)
// Scanner is an interface used by [Rows.Scan].
type Scanner interface {
// Scan assigns a value from a database driver.
//
// The src value will be of one of the following types:
//
// int64
// float64
// bool
// []byte
// string
// time.Time
// nil - for NULL values
//
// An error should be returned if the value cannot be stored
// without loss of information.
//
// Reference types such as []byte are only valid until the next call to Scan
// and should not be retained. Their underlying memory is owned by the driver.
// If retention is necessary, copy their values before the next call to Scan.
Scan(src any) error
}
// RawBytes is a byte slice that holds a reference to memory owned by
// the database itself. After a [Rows.Scan] into a RawBytes, the slice is only
// valid until the next call to [Rows.Next], [Rows.Scan], or [Rows.Close].
type RawBytes []byte
type decimalDecompose interface {
// Decompose returns the internal decimal state in parts.
// If the provided buf has sufficient capacity, buf may be returned as the coefficient with
// the value set and length set as appropriate.
Decompose(buf []byte) (form byte, negative bool, coefficient []byte, exponent int32)
}
type decimalCompose interface {
// Compose sets the internal decimal value from parts. If the value cannot be
// represented then an error should be returned.
Compose(form byte, negative bool, coefficient []byte, exponent int32) error
}
func asString(src any) string {
switch v := src.(type) {
case string:
return v
case []byte:
return string(v)
}
rv := reflect.ValueOf(src)
switch rv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(rv.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return strconv.FormatUint(rv.Uint(), 10)
case reflect.Float64:
return strconv.FormatFloat(rv.Float(), 'g', -1, 64)
case reflect.Float32:
return strconv.FormatFloat(rv.Float(), 'g', -1, 32)
case reflect.Bool:
return strconv.FormatBool(rv.Bool())
default:
return fmt.Sprintf("%v", src)
}
}
func asBytes(buf []byte, rv reflect.Value) (b []byte, ok bool) {
switch rv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.AppendInt(buf, rv.Int(), 10), true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return strconv.AppendUint(buf, rv.Uint(), 10), true
case reflect.Float32:
return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 32), true
case reflect.Float64:
return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 64), true
case reflect.Bool:
return strconv.AppendBool(buf, rv.Bool()), true
case reflect.String:
s := rv.String()
return append(buf, s...), true
default:
return
}
}
func stringConversionError(err error) error {
var ne *strconv.NumError
if errors.As(err, &ne) {
return ne.Err
}
return err
}
// convertAssignRows copies to dest the value in src, converting it if possible.
// An error is returned if the copy would result in loss of information.
// dest should be a pointer type. If rows is passed in, the rows will
// be used as the parent for any cursor values converted from a
// driver.Rows to a Rows.
func convertAssignRows(src, dest any) error {
// Common cases, without reflect.
switch s := src.(type) {
case string:
switch d := dest.(type) {
case *string:
if d == nil {
return ErrNilPointer
}
*d = s
return nil
case *[]byte:
if d == nil {
return ErrNilPointer
}
*d = []byte(s)
return nil
case *RawBytes:
if d == nil {
return ErrNilPointer
}
*d = append((*d)[:0], s...)
return nil
}
case []byte:
switch d := dest.(type) {
case *string:
if d == nil {
return ErrNilPointer
}
*d = string(s)
return nil
case *any:
if d == nil {
return ErrNilPointer
}
*d = bytes.Clone(s)
return nil
case *[]byte:
if d == nil {
return ErrNilPointer
}
*d = bytes.Clone(s)
return nil
case *RawBytes:
if d == nil {
return ErrNilPointer
}
*d = s
return nil
}
case time.Time:
switch d := dest.(type) {
case *time.Time:
*d = s
return nil
case *string:
*d = s.Format(time.RFC3339Nano)
return nil
case *[]byte:
if d == nil {
return ErrNilPointer
}
*d = []byte(s.Format(time.RFC3339Nano))
return nil
case *RawBytes:
if d == nil {
return ErrNilPointer
}
*d = s.AppendFormat((*d)[:0], time.RFC3339Nano)
return nil
}
case decimalDecompose:
switch d := dest.(type) {
case decimalCompose:
return d.Compose(s.Decompose(nil))
}
case nil:
switch d := dest.(type) {
case *any:
if d == nil {
return ErrNilPointer
}
*d = nil
return nil
case *[]byte:
if d == nil {
return ErrNilPointer
}
*d = nil
return nil
case *RawBytes:
if d == nil {
return ErrNilPointer
}
*d = nil
return nil
}
}
var sv reflect.Value
switch d := dest.(type) {
case *string:
sv = reflect.ValueOf(src)
switch sv.Kind() {
case reflect.Bool,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64:
*d = asString(src)
return nil
default:
}
case *[]byte:
sv = reflect.ValueOf(src)
if b, ok := asBytes(nil, sv); ok {
*d = b
return nil
}
case *RawBytes:
sv = reflect.ValueOf(src)
if b, ok := asBytes([]byte(*d)[:0], sv); ok {
*d = b
return nil
}
case *bool:
bv, err := driver.Bool.ConvertValue(src)
if err == nil {
*d = bv.(bool)
}
return err
case *any:
*d = src
return nil
}
if scanner, ok := dest.(Scanner); ok {
return scanner.Scan(src)
}
dpv := reflect.ValueOf(dest)
if dpv.Kind() != reflect.Pointer {
return ErrNotAPointer
}
if dpv.IsNil() {
return ErrNilPointer
}
if !sv.IsValid() {
sv = reflect.ValueOf(src)
}
dv := reflect.Indirect(dpv)
if sv.IsValid() && sv.Type().AssignableTo(dv.Type()) {
switch b := src.(type) {
case []byte:
dv.Set(reflect.ValueOf(bytes.Clone(b)))
default:
dv.Set(sv)
}
return nil
}
if dv.Kind() == sv.Kind() && sv.Type().ConvertibleTo(dv.Type()) {
dv.Set(sv.Convert(dv.Type()))
return nil
}
// The following conversions use a string value as an intermediate representation
// to convert between various numeric types.
//
// This also allows scanning into user defined types such as "type Int int64".
// For symmetry, also check for string destination types.
switch dv.Kind() {
case reflect.Pointer:
if src == nil {
dv.SetZero()
return nil
}
dv.Set(reflect.New(dv.Type().Elem()))
return convertAssignRows(dv.Interface(), src)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if src == nil {
return fmt.Errorf("converting NULL to %s is unsupported", dv.Kind())
}
s := asString(src)
i64, err := strconv.ParseInt(s, 10, dv.Type().Bits())
if err != nil {
err = stringConversionError(err)
return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err)
}
dv.SetInt(i64)
return nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if src == nil {
return fmt.Errorf("converting NULL to %s is unsupported", dv.Kind())
}
s := asString(src)
u64, err := strconv.ParseUint(s, 10, dv.Type().Bits())
if err != nil {
err = stringConversionError(err)
return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err)
}
dv.SetUint(u64)
return nil
case reflect.Float32, reflect.Float64:
if src == nil {
return fmt.Errorf("converting NULL to %s is unsupported", dv.Kind())
}
s := asString(src)
f64, err := strconv.ParseFloat(s, dv.Type().Bits())
if err != nil {
err = stringConversionError(err)
return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err)
}
dv.SetFloat(f64)
return nil
case reflect.String:
if src == nil {
return fmt.Errorf("converting NULL to %s is unsupported", dv.Kind())
}
switch v := src.(type) {
case string:
dv.SetString(v)
return nil
case []byte:
dv.SetString(string(v))
return nil
}
default:
}
return ErrRowsUnsupportedScan
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.